菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
2910
0

python 操作 Git

原创
05/13 14:22
阅读数 3326
  • 在搭建 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

发表评论

0/200
2910 点赞
0 评论
收藏
为你推荐 换一批