背景
現在越來越多的公司採用gitlab來管理代碼。gitlab有個問題,免費版不支持全局代碼搜索,這很麻煩。如果把代碼全部clone到本地就可以方便的進行各種搜索了。可是gitlab也不提供git clone所有項目的功能。
公司越來越大,項目越來越多,怎麼辦呢?自己寫個腳本來批量的git clone吧。
思路
gitlab有提供api來獲取projecct列表,那麼就可以遍歷這個列表來做git clone
參見:https://docs.gitlab.com/ee/api/projects.html#list-all-projects
腳本
注意:gitlab的api每次最多隻能獲取100個projecct的信息。我提供的這個腳本帶翻頁功能,可以支持100個以上的項目。
# -*- coding: UTF-8 -*-
# 在Python3.0測試通過
# 需要在gitlab裏面新建一個AccessToken填入gitlabToken
import sys
if sys.version_info < (3, 0):
import urllib
else:
from urllib.request import urlopen
import json
import subprocess, shlex
import time
import os
gitlabAddr = '201.1.2.115:8099'
gitlabToken = 'Nzyg92-123456aa4ay__y'
for index in range(10):
url = "http://%s/api/v4/projects?private_token=%s&per_page=100&page=%d&order_by=name" % (gitlabAddr, gitlabToken, index)
print(url)
if sys.version_info < (3, 0):
allProjects = urllib.urlopen(url)
else:
allProjects = urlopen(url)
allProjectsDict = json.loads(allProjects.read().decode(encoding='UTF-8'))
if len(allProjectsDict) == 0:
break
for thisProject in allProjectsDict:
try:
thisProjectURL = thisProject['http_url_to_repo']
thisProjectPath = thisProject['path_with_namespace']
print(thisProjectURL + ' ' + thisProjectPath)
if os.path.exists(thisProjectPath):
command = shlex.split('git -C "%s" pull' % (thisProjectPath))
else:
command = shlex.split('git clone %s %s' % (thisProjectURL, thisProjectPath))
resultCode = subprocess.Popen(command)
time.sleep(0.5)
except Exception as e:
print("Error on %s: %s" % (thisProjectURL, e.strerror))
腳本使用方法
這是一個python腳本,可以另存爲gitall.py比如。然後電腦上安裝一下python。再寫個批處理文件updategit.bat包含一條命令:python gitall.py。這樣以後雙擊updategit.bat就可以使用了。
第一次使用的時候有可能會彈框要求輸入gitlab的賬號密碼。