当前位置: 代码网 > it编程>前端脚本>Python > python获取当前git的repo地址的示例代码

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

2024年09月29日 Python 我要评论
要获取当前 git 仓库的远程地址,可以使用subprocess模块执行git 命令。下面是如何做到这一点的示例代码:import subprocessdef get_git_remote_url()

要获取当前 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地址内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com