python批量获取gitlab里面所有项目的代码

背景
现在越来越多的公司采用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'         #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['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脚本,可以另存为pull.py。然后电脑上安装一下python。再写个批处理文件updategit.bat包含一条命令:python pull.py(即在bat文件中执行上面的python脚本)。

1、在执行前先填写好token,token的生成方法是

 

将上面的页面中生成的token写到gitlabToken = 'Nzyg92-123456aa4ay__y'里。

2、gitlabAddr,填写你自己的gitlab地址

3、执行python pull.py

执行过程中会

第一次使用的时候有可能会弹框要求输入gitlab的账号密码。

我操作的时候弹出的是:

弹出这个对话框

然后命令行中提醒输入git账号及密码的。

这样每个项目被遍历下载下来。完成。


转自:https://blog.csdn.net/wwwsq/article/details/97106096

posted on 2021-07-08 19:15  duanxz  阅读(3353)  评论(0编辑  收藏  举报