最近服务到期,不得不把代码库(gitlab11.1.0)迁移走。

顺手部署了个新版的gitlab13.7.3, 由于版本不一致,直接备份导入会报错。

经过查找,python有个库python-gitlab可以干这个事。

思路是:先从旧库导出,然后导入到新库。

代码如下:

#!/usr/bin/env python

"""
FileName: migrate_gitlab
Author: wst
Email: movingheart000@gmail.com
Date: 2022/6/29 20:40:28
Desc: 
"""
import os

import gitlab
import time
import subprocess
import json


def runcmd(command):
    ret = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding="utf-8",
                         timeout=2000)
    if ret.returncode == 0:
        print("success:", ret)
    else:
        print("error:", ret)


class MigrateGitlab:
    def __init__(self, url, token, aim_url, aim_token):
        self.gl = gitlab.Gitlab(url, token)
        self.aim_gl = gitlab.Gitlab(aim_url, aim_token)
        self.dir_path = "/home/wst/Documents/tmp/"       # 导出文件放置目录

    def download_repository(self):
        """下载仓库"""
        projects = self.gl.projects.list(all=True)
        for p in projects:
            print(f"id:{p.id}, \nname:{p.name}, \ndescription:{p.description}")
            print(f"ssh_url_to_repo:{p.ssh_url_to_repo}")
            export = p.exports.create()

            # Wait for the 'finished' status
            export.refresh()
            while export.export_status != 'finished':
                time.sleep(1)
                export.refresh()

            # Download the repo
            fn = f'{self.dir_path}{p.name}.tar.gz'
            with open(fn, 'wb') as f:
                export.download(streamed=True, action=f.write)

    def upload_repository(self):
        """上传仓库"""
        done_names = list()
        for file in os.listdir(self.dir_path):
            base_name = file.split(".", 1)[0]
            fn = os.path.join(self.dir_path, file)
            print("正在导入:", fn)
            # Import result
            with open(fn, 'rb') as f:
                try:
                    output = self.aim_gl.projects.import_project(
                        f, path=base_name, name=base_name, namespace='wst', overwrite=True
                    )
                    done_names.append(base_name)
                except gitlab.exceptions.GitlabHttpError as e:
                    if "Name has already been taken" in e.error_message:
                        # 若库已存在, 则忽略
                        print(f"{base_name} 已经存在!")
                    else:
                        print("导库出现未知错误!")
                except Exception as e:
                    print("e:", e, type(e), dir(e))
                    print(f"{base_name} 导入异常,请检查原因,或稍后手动导入。")
                finally:
                    json.dump(done_names, open("names.json", "w"))
            print(f"本项目[{base_name}]迁移结束!")

if __name__ == "__main__":
    url_ = "http://7.4.1.2"
    token_ = "eFFutSVYkUS2NF8rLUCx"
    aim_url_ = "https://gitlab.wo.com"
    aim_token_ = "w24PNqszNvepb9oSYzq8"
    imp_obj = MigrateGitlab(url_, token_, aim_url_, aim_token_)
    imp_obj.download_repository()
    imp_obj.upload_repository()

 

版权声明:

本文刊载的所有内容,包括文字、图片以及网页版式设计等均为本人自主创作,访问者可将本文提供的内容或服务用于个人学习、研究或欣赏,以及其他非商业性或非盈利性用途,但同时应遵守著作权法及其他相关法律的规定,不得侵犯本文及作者的合法权利。除此以外,将本文任何内容或服务用于其他用途时,须征得本人的书面许可,并支付报酬。email: movingheart000@gmail.com, wx:wst_ccut