本文最后更新于:2023年12月5日 下午

现在越来越多的公司采用 gitlab 来管理代码。gitlab有个问题,免费版不支持全局代码搜索,这很麻烦。如果把代码全部clone到本地就可以方便的进行各种搜索了。

思路

gitlab 有提供 api 来获取 projecct 列表,那么就可以遍历这个列表来做git clone

参见:https://docs.gitlab.com/ee/api/projects.html#list-all-projects

生成 token

使用 Gitlab API 需要生成私有 token

  • token的生成方法:

  • Token 仅在生成时可见一次,注意保存

脚本

注意:gitlab 的 api 每次最多只能获取100个projecct的信息。这个脚本带翻页功能,可以支持100个以上的项目。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# -*- 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' #git的地址
gitlabToken = 'Nzyg92-123456aa4ay__y' #gitlab的token,在gitlab的设置里有生产临时token

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['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(0.5)
except Exception as e:
print("Error on %s: %s" % (thisProjectURL, e.strerror))

参考资料



文章链接:
https://www.zywvvd.com/notes/tools/git/gitlab-download/gitlab-download/


“觉得不错的话,给点打赏吧 ୧(๑•̀⌄•́๑)૭”

微信二维码

微信支付

支付宝二维码

支付宝支付

Python 批量获取 gitlab 项目代码
https://www.zywvvd.com/notes/tools/git/gitlab-download/gitlab-download/
作者
Yiwei Zhang
发布于
2022年2月7日
许可协议