背景
现在越来越多的公司采用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个以上的项目。
# 在Python3.0测试通过
# 需要在gitlab里面新建一个AccessToken
# 需要在本地机器设置一个环境变量,比如:GIT_SSH_COMMAND = ssh -i C:/Users/wsq/key/wsq.key
from urllib.request import urlopen
import json
import subprocess, shlex
import time
import os
gitlabAddr = '[gitlabAddr like: 192.168.1.200:5678]'
gitlabToken = '[your access token created from gitlab]'
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)
allProjects = urlopen(url)
allProjectsDict = json.loads(allProjects.read().decode())
if len(allProjectsDict) == 0:
break
for thisProject in allProjectsDict:
try:
thisProjectURL = thisProject['ssh_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(1)
except Exception as e:
print("Error on %s: %s" % (thisProjectURL, e.strerror))
脚本使用方法
这是一个python脚本,可以另存为gitall.py比如。然后电脑上安装一下python。再写个批处理文件updategit.bat包含一条命令:python gitall.py。这样以后双击updategit.bat就可以使用了。
献给那些对团队代码保持强烈关注的小伙伴。
来源:oschina
链接:https://my.oschina.net/u/3730932/blog/3155976