python获取当前git的repo地址的示例代码

 更新时间:2024年09月29日 08:41:09   作者:胡少侠7  
大家好,当谈及版本控制系统时,Git是最为广泛使用的一种,而Python作为一门多用途的编程语言,在处理Git仓库时也展现了其强大的能力,本文给大家介绍了python获取当前git的repo地址的方法,需要的朋友可以参考下

要获取当前 Git 仓库的远程地址,可以使用 subprocess 模块执行 Git 命令。下面是如何做到这一点的示例代码:

import subprocess

def get_git_remote_url():
    try:
        # 获取远程 URL
        result = subprocess.run(
            ['git', 'config', '--get', 'remote.origin.url'],
            check=True,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True
        )
        
        # 获取并返回输出
        remote_url = result.stdout.strip()
        return remote_url

    except subprocess.CalledProcessError as e:
        print(f"An error occurred: {e}")
        return None

# 使用示例
remote_url = get_git_remote_url()
if remote_url:
    print(f"Remote URL: {remote_url}")
else:
    print("Failed to retrieve the remote URL.")

注意事项:

  • Git 必须安装:确保本地环境已安装 Git 并且正在 Git 仓库的目录中运行。
  • 错误处理:代码简单处理了可能发生的错误,可根据需要增加异常处理和日志记录。
  • 远程名称:示例使用了默认的 origin,若远程名称不同,请更改命令中的相应部分。

拓展:python操作git gitpython模块

安装模块

pip3 install gitpython

基本使用

import os
from git.repo import Repo

# 创建本地路径用来存放远程仓库下载的代码
download_path = os.path.join('NB')
# 拉取代码
Repo.clone_from('https://github.com/DominicJi/TeachTest.git',to_path=download_path,branch='master')

其他常见操作

# ############## 2. pull最新代码 ##############
import os
from git.repo import Repo
 
local_path = os.path.join('NB')
repo = Repo(local_path)
repo.git.pull()


# ############## 3. 获取所有分支 ##############
import os
from git.repo import Repo
 
local_path = os.path.join('NB')
repo = Repo(local_path)
 
branches = repo.remote().refs
for item in branches:
    print(item.remote_head)
    

# ############## 4. 获取所有版本 ##############
import os
from git.repo import Repo
 
local_path = os.path.join('NB')
repo = Repo(local_path)
 
for tag in repo.tags:
    print(tag.name)


# ############## 5. 获取所有commit ##############
import os
from git.repo import Repo
 
local_path = os.path.join('NB')
repo = Repo(local_path)
 
# 将所有提交记录结果格式成json格式字符串 方便后续反序列化操作
commit_log = repo.git.log('--pretty={"commit":"%h","author":"%an","summary":"%s","date":"%cd"}', max_count=50,
                          date='format:%Y-%m-%d %H:%M')
log_list = commit_log.split("\n")
real_log_list = [eval(item) for item in log_list]
print(real_log_list)
 

 # ############## 6. 切换分支 ##############
import os
from git.repo import Repo
 
local_path = os.path.join('NB')
repo = Repo(local_path)
 
before = repo.git.branch()
print(before)
repo.git.checkout('master')
after = repo.git.branch()
print(after)
repo.git.reset('--hard', '854ead2e82dc73b634cbd5afcf1414f5b30e94a8')


 
# ############## 7. 打包代码 ##############
import os
from git.repo import Repo

local_path = os.path.join(NB')
repo = Repo(local_path)

with open(os.path.join('NB.tar'), 'wb') as fp:
    repo.archive(fp)

所有的方法封装到类中

import os
from git.repo import Repo
from git.repo.fun import is_git_dir


class GitRepository(object):
    """
    git仓库管理
    """
    def __init__(self, local_path, repo_url, branch='master'):
        self.local_path = local_path
        self.repo_url = repo_url
        self.repo = None
        self.initial(repo_url, branch)

    def initial(self, repo_url, branch):
        """
        初始化git仓库
        :param repo_url:
        :param branch:
        :return:
        """
        if not os.path.exists(self.local_path):
            os.makedirs(self.local_path)

        git_local_path = os.path.join(self.local_path, '.git')
        if not is_git_dir(git_local_path):
            self.repo = Repo.clone_from(repo_url, to_path=self.local_path, branch=branch)
        else:
            self.repo = Repo(self.local_path)

    def pull(self):
        """
        从线上拉最新代码
        :return:
        """
        self.repo.git.pull()

    def branches(self):
        """
        获取所有分支
        :return:
        """
        branches = self.repo.remote().refs
        return [item.remote_head for item in branches if item.remote_head not in ['HEAD', ]]

    def commits(self):
        """
        获取所有提交记录
        :return:
        """
        commit_log = self.repo.git.log('--pretty={"commit":"%h","author":"%an","summary":"%s","date":"%cd"}',
                                       max_count=50,
                                       date='format:%Y-%m-%d %H:%M')
        log_list = commit_log.split("\n")
        return [eval(item) for item in log_list]

    def tags(self):
        """
        获取所有tag
        :return:
        """
        return [tag.name for tag in self.repo.tags]

    def change_to_branch(self, branch):
        """
        切换分值
        :param branch:
        :return:
        """
        self.repo.git.checkout(branch)

    def change_to_commit(self, branch, commit):
        """
        切换commit
        :param branch:
        :param commit:
        :return:
        """
        self.change_to_branch(branch=branch)
        self.repo.git.reset('--hard', commit)

    def change_to_tag(self, tag):
        """
        切换tag
        :param tag:
        :return:
        """
        self.repo.git.checkout(tag)


if __name__ == '__main__':
    local_path = os.path.join('codes', 'luffycity')
    repo = GitRepository(local_path,remote_path)
    branch_list = repo.branches()
    print(branch_list)
    repo.change_to_branch('dev')
    repo.pull()

到此这篇关于python获取当前git的repo地址的示例代码的文章就介绍到这了,更多相关python获取git repo地址内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • 详谈Python 窗体(tkinter)表格数据(Treeview)

    详谈Python 窗体(tkinter)表格数据(Treeview)

    今天小编就为大家分享一篇详谈Python 窗体(tkinter)表格数据(Treeview),具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-10-10
  • pandas库中 DataFrame的用法小结

    pandas库中 DataFrame的用法小结

    这篇文章主要介绍了pandas库中 DataFrame的用法,利用pandas.DataFrame可以构建表格,通过列标属性调用列对象,本文结合实例代码给大家介绍的非常详细,需要的朋友可以参考下
    2023-05-05
  • Python抓取聚划算商品分析页面获取商品信息并以XML格式保存到本地

    Python抓取聚划算商品分析页面获取商品信息并以XML格式保存到本地

    这篇文章主要为大家详细介绍了Python抓取聚划算商品分析页面获取商品信息,并以XML格式保存到本地的方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-02-02
  • Python 通过监听端口实现唯一脚本运行方式

    Python 通过监听端口实现唯一脚本运行方式

    这篇文章主要介绍了Python 通过监听端口实现唯一脚本运行方式,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-05-05
  • Python中if语句的使用方法及实例代码

    Python中if语句的使用方法及实例代码

    if语句能够进行条件测试,并依据一定的条件进行具体的操作,下面这篇文章主要给大家介绍了关于Python中if语句的使用方法及实例代码,文中通过实例代码介绍的非常详细,需要的朋友可以参考下
    2022-11-11
  • python pandas多数据操作的完整指南

    python pandas多数据操作的完整指南

    在数据分析工作中,我们经常需要处理多个数据集并将它们以各种方式组合起来,Pandas 提供了多种强大的多数据操作方法,下面就跟随小编一起了解一下吧
    2025-04-04
  • python 中random模块的常用方法总结

    python 中random模块的常用方法总结

    这篇文章主要介绍了python 中random的常用方法总结的相关资料,需要的朋友可以参考下
    2017-07-07
  • Python中yield函数的用法详解

    Python中yield函数的用法详解

    这篇文章详细介绍了Python中的yield关键字及其用法,yield关键字用于生成器函数中,使得函数可以像迭代器一样工作,但不会一次性将所有结果加载到内存中,文中将用法介绍的非常详细,需要的朋友可以参考下
    2025-03-03
  • Python调用百度AI实现人像分割详解

    Python调用百度AI实现人像分割详解

    本文主要介绍了如何通过Python调用百度AI从而实现人像的分割与合成,文中的示例代码对我们的工作或学习有一定的帮助,需要的朋友可以参考一下
    2021-12-12
  • Python 模拟生成动态产生验证码图片的方法

    Python 模拟生成动态产生验证码图片的方法

    这篇文章主要介绍了Python 模拟生成动态产生验证码图片的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-02-02

最新评论