python 操作 Git

  • 在搭建 devops 平台时有一个小功能是获取仓库的分支或者标签列表,遂使用 python 写了相关脚本

  • python 安装包 GitPython 并且 import git

  • 相关脚本

# 仓库操作对象
    def get_repo_target(self, addr):
        #取仓库地址作为目录名
        repo_name = addr.replace('/', '-')
        try:
            #在特定目录获取仓库操作对象
            repo = git.Repo(self.temp_dir + repo_name)
            #设置git拉取代码身份验证使用的私钥地址,刚开始使用GIT_SSH参数,值为私钥地址不起作用
            repo.git.update_environment(
                GIT_SSH_COMMAND='ssh -i ' + self.get_key_path(addr))
            Debug.info('已经存在仓库:' + addr)
        except Exception as e:
            Debug.info('未初始化仓库')
            Debug.error(str(e))
            Debug.info('初始化仓库')
            #未初始化过仓库,在特定目录初始化仓库操作对象
            repo = git.Repo.init(self.temp_dir + repo_name)
            Debug.info('添加远程仓库')
            repo.create_remote('origin', addr)

        Debug.info('fetch远程仓库数据')
        try:
            #获取仓库最新信息
            repo.git.fetch('--all')
        except Exception as e:
            Debug.info('fetch仓库数据信息失败')
            Debug.error(str(e))

        return repo

这里可能还要执行一下命令 mkdir /root/.ssh && echo 'StrictHostKeyChecking no' > /root/.ssh/config , 要不然在初次获取仓库主机信息时有个known_hosts的交互确认,这里是免交互确认

  • 获取分支脚本
# 获取仓库分支
    def get_branches(self, address):
        repo = self.get_repo_target(address)
        Debug.info('获取远程分支信息')
        branches = repo.git.branch('-r')
        branches = branches.split("\n")
        Debug.info(branches)
        filter_branches = []
        #这里去除 origin
        for item in branches:
            pos = item.find('/')
            filter_branches.append(item[pos+1:])
        return filter_branches
  • 获取标签列表
    # 获取仓库tag
    def get_tags(self, address):
        repo = self.get_repo_target(address)
        Debug.info('获取tag信息')
        #获取标签及标签提交信息
        tags = repo.git.tag('-ln')
        filter_tags = []
        tags = tags.split("\n")
        Debug.info(tags)
        #分享标签和标签提交信息,这里发现标签提交时如果未加 -m,会使用上次使用的提交信息
        for item in tags:
            pos = item.find(" ")
            tag_temp = {"name": item[:pos], "msg": item[pos:].strip()}
            filter_tags.append(tag_temp)
        return filter_tags
本作品采用《CC 协议》,转载必须注明作者和本文链接
雪花飘
讨论数量: 2

感谢楼主分享,能否分享一下self.get_key_path(addr)的具体实现

4年前 评论

@xiaopo 就是返回私钥的绝对路径

4年前 评论
xiaopo 4年前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!