python批量下載gitlab項(xiàng)目 支持群組

#!/usr/bin/python3
from urllib.request import urlopen
import json
import subprocess, shlex
import time
import os

# 默認(rèn)使用 http 拉取坝辫,非 ssh
gitlabToken = 'kwxmuskShkUs-xxxxxxx'    # person token (ps: 只有第一次創(chuàng)建時(shí)可見篷就,不是feed token)
gitlabAddr  = 'xxxxxx.com'              # gitlab地址
targets     = ['xxx','xxx']             # 所屬群組 (ps: 為空克隆所有群組,慎用)
withShared  = 'false'                   # 是否包含共享的項(xiàng)目近忙,默認(rèn)false (ps:為true會(huì)拉取到歸屬其他群組的項(xiàng)目)

#-------------------------

counter = 0
procs = []

def get_next(group_id):
    global counter
    global procs

    print('get_next group_id:', group_id)
    url = gen_next_url(group_id)
    allProjects     = urlopen(url)
    allProjectsDict = json.loads(allProjects.read().decode())
    if len(allProjectsDict) == 0:
        return
    for thisProject in allProjectsDict: 
        try:
            thisProjectURL  = thisProject['http_url_to_repo']
            thisProjectPath = thisProject['path_with_namespace']
            if os.path.exists(thisProjectPath):
                command     = shlex.split('git -C "%s" pull' % (thisProjectPath))               
            else:
                print("=========== 開始克隆 %s %s ===========" % (group_id, thisProject['name']))
                print('執(zhí)行:git clone %s %s' % (thisProjectURL, thisProjectPath))                        
                command     = shlex.split('git clone %s %s' % (thisProjectURL, thisProjectPath))
                
            proc  = subprocess.Popen(command)
            procs.append(proc)
            time.sleep(1)
            counter += 1

        except Exception as e:
            print("Error on %s: %s" % (thisProjectURL, e.strerror))

    print("=========== 等待子線程執(zhí)行結(jié)束 ===========")
    for p in procs:
        p.wait()
        p.kill()
    print("=========== 子線程執(zhí)行結(jié)束 ===========")
    return

def have_next_projects(group_id):
    url = gen_next_url(group_id)
    allProjects     = urlopen(url)
    allProjectsDict = json.loads(allProjects.read().decode())
    if len(allProjectsDict) == 0:
        return False
    return True


def get_sub_groups(parent_id):
    url = gen_subgroups_url(parent_id)
    allProjects     = urlopen(url)
    allProjectsDict = json.loads(allProjects.read().decode())
    sub_ids = []
    if len(allProjectsDict) == 0:
        return sub_ids
    for thisProject in allProjectsDict: 
        try:
            id = thisProject['id']
            sub_ids.append(id)
        except Exception as e:
            print("Error on %s: %s" % (id, e.strerror))
    return sub_ids

def cal_next_sub_groupids(parent_id):
    parent = ''
    parent = parent_id
    
    is_start = 1
    parent_list = []
    sub_ids = get_sub_groups(parent_id)
    print('cal_next_sub_groupids sub_ids and parent_id:',sub_ids, parent_id)
    ok = have_next_projects(parent_id) 
    print('have_next_projects result:', ok)
    if len(sub_ids)!=0 and ok == False:
        for i in range(len(sub_ids)):
            print('cal_next_sub_groupids sub_ids[i]:', sub_ids[i])
            parent = sub_ids[i]
            a = cal_next_sub_groupids(sub_ids[i])
            return a
    if len(sub_ids) !=0 and ok == True:
        for i in range(len(sub_ids)):
            print('cal_next_sub_groupids parent:', parent)
            parent = sub_ids[i]
            parent_list.append(sub_ids[i])
            a = cal_next_sub_groupids(sub_ids[i])
            parent_list.extend(a)
    if len(sub_ids) == 0 and ok == True:
        print('cal_next_sub_groupids is_start:',is_start)
        parent_list.append(parent)
        return parent_list
    if len(sub_ids) ==0 and ok == False:
        return parent_list
    return parent_list

def download_code(parent_id):
    data =cal_next_sub_groupids(parent_id)
    print('download_code result: ',data)
    for group_id in data:
        get_next(group_id)
    return
 
def gen_next_url(target_id):
    return "https://%s/api/v4/groups/%s/projects?private_token=%s&with_shared=%s&order_by=updated_at" % (gitlabAddr, target_id, gitlabToken, withShared)

def gen_subgroups_url(target_id):
    return "https://%s/api/v4/groups/%s/subgroups?private_token=%s" % (gitlabAddr, target_id, gitlabToken)

def gen_global_url():
    return "http://%s/api/v4/projects?private_token=%s" % (gitlabAddr, gitlabToken)

def download_global_code():
    global counter
    global procs

    url = gen_global_url()
    allProjects     = urlopen(url)
    allProjectsDict = json.loads(allProjects.read().decode())
    if len(allProjectsDict) == 0:
        return
    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:
                print("=========== 開始克隆 %s %s ===========" % (group_id, thisProject['name']))
                print('執(zhí)行:git clone %s %s' % (thisProjectURL, thisProjectPath))    
                command     = shlex.split('git clone %s %s' % (thisProjectURL, thisProjectPath))

            proc  = subprocess.Popen(command)
            procs.append(proc)
            time.sleep(1)
            counter += 1
            
        except Exception as e:
            print("Error on %s: %s" % (thisProjectURL, e.strerror))

    print("=========== 等待子線程執(zhí)行結(jié)束 ===========")
    for p in procs:
        p.wait()
        p.kill()
    print("=========== 子線程執(zhí)行結(jié)束 ===========")
    return

def download_targets_code():
    for target in targets:
        url     = "https://%s/api/v4/groups?private_token=%s&search=%s" % (gitlabAddr, gitlabToken, target)
        allProjects     = urlopen(url)
        allProjectsDict = json.loads(allProjects.read().decode())
        if len(allProjectsDict) == 0:
            return
        target_id = '' 
        for thisProject in allProjectsDict: 
            try:
                this_name = thisProject['name']
                if target == this_name:
                    target_id = thisProject['id']
                    break
            except Exception as e:
                print("Error on %s: %s" % (this_name, e.strerror))    
        download_code(target_id)
    return

def main():
    if len(targets) == 0:
        download_global_code()
    else:
        download_targets_code()
    
    print("=========== 執(zhí)行結(jié)束竭业,克隆項(xiàng)目數(shù): %s ===========" % (counter))
    return


main()
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市及舍,隨后出現(xiàn)的幾起案子未辆,更是在濱河造成了極大的恐慌,老刑警劉巖击纬,帶你破解...
    沈念sama閱讀 206,126評(píng)論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件鼎姐,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡更振,警方通過查閱死者的電腦和手機(jī)炕桨,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,254評(píng)論 2 382
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來肯腕,“玉大人献宫,你說我怎么就攤上這事∈等觯” “怎么了姊途?”我有些...
    開封第一講書人閱讀 152,445評(píng)論 0 341
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)知态。 經(jīng)常有香客問我捷兰,道長(zhǎng),這世上最難降的妖魔是什么负敏? 我笑而不...
    開封第一講書人閱讀 55,185評(píng)論 1 278
  • 正文 為了忘掉前任贡茅,我火速辦了婚禮,結(jié)果婚禮上其做,老公的妹妹穿的比我還像新娘顶考。我一直安慰自己,他們只是感情好妖泄,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,178評(píng)論 5 371
  • 文/花漫 我一把揭開白布驹沿。 她就那樣靜靜地躺著,像睡著了一般蹈胡。 火紅的嫁衣襯著肌膚如雪渊季。 梳的紋絲不亂的頭發(fā)上朋蔫,一...
    開封第一講書人閱讀 48,970評(píng)論 1 284
  • 那天,我揣著相機(jī)與錄音梭域,去河邊找鬼斑举。 笑死,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播妒蛇,決...
    沈念sama閱讀 38,276評(píng)論 3 399
  • 文/蒼蘭香墨 我猛地睜開眼肋殴,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 36,927評(píng)論 0 259
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎励两,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體囊颅,經(jīng)...
    沈念sama閱讀 43,400評(píng)論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡当悔,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 35,883評(píng)論 2 323
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了踢代。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片盲憎。...
    茶點(diǎn)故事閱讀 37,997評(píng)論 1 333
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖胳挎,靈堂內(nèi)的尸體忽然破棺而出饼疙,到底是詐尸還是另有隱情,我是刑警寧澤慕爬,帶...
    沈念sama閱讀 33,646評(píng)論 4 322
  • 正文 年R本政府宣布窑眯,位于F島的核電站,受9級(jí)特大地震影響医窿,放射性物質(zhì)發(fā)生泄漏磅甩。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,213評(píng)論 3 307
  • 文/蒙蒙 一姥卢、第九天 我趴在偏房一處隱蔽的房頂上張望卷要。 院中可真熱鬧,春花似錦隔显、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,204評(píng)論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至倍权,卻和暖如春掷豺,著一層夾襖步出監(jiān)牢的瞬間捞烟,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 31,423評(píng)論 1 260
  • 我被黑心中介騙來泰國(guó)打工当船, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留题画,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 45,423評(píng)論 2 352
  • 正文 我出身青樓德频,卻偏偏與公主長(zhǎng)得像苍息,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子壹置,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,722評(píng)論 2 345

推薦閱讀更多精彩內(nèi)容