Python获取当前git的repo地址的示例代码!
Python获取当前git的repo地址的示例代码!
大家好,当谈及版本控制系统时,Git是最为广泛使用的一种,而Python作为一门多用途的编程语言,在处理Git仓库时也展现了其强大的能力,本文给大家介绍了python获取当前git的repo地址的方法,需要的朋友可以参考下。
要获取当前 Git 仓库的远程地址,可以使用 subprocess 模块执行 Git 命令。下面是如何做到这一点的示例代码:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
import subprocessdef get_git_remote_url():try:# 获取远程 URLresult = 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_urlexcept 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模块
安装模块
|
1
|
pip3 install gitpython |
基本使用
|
1
2
3
4
5
6
7
|
import osfrom 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') |
其他常见操作
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
|
# ############## 2. pull最新代码 ##############import osfrom git.repo import Repolocal_path = os.path.join('NB')repo = Repo(local_path)repo.git.pull()# ############## 3. 获取所有分支 ##############import osfrom git.repo import Repolocal_path = os.path.join('NB')repo = Repo(local_path)branches = repo.remote().refsfor item in branches:print(item.remote_head)# ############## 4. 获取所有版本 ##############import osfrom git.repo import Repolocal_path = os.path.join('NB')repo = Repo(local_path)for tag in repo.tags:print(tag.name)# ############## 5. 获取所有commit ##############import osfrom git.repo import Repolocal_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 osfrom git.repo import Repolocal_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 osfrom git.repo import Repolocal_path = os.path.join(NB')repo = Repo(local_path)with open(os.path.join('NB.tar'), 'wb') as fp:repo.archive(fp) |
所有的方法封装到类中
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
|
import osfrom git.repo import Repofrom git.repo.fun import is_git_dirclass GitRepository(object):"""git仓库管理"""def __init__(self, local_path, repo_url, branch='master'):self.local_path = local_pathself.repo_url = repo_urlself.repo = Noneself.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().refsreturn [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地址的示例代码的文章就介绍到这了。
学习资料见知识星球。
以上就是今天要分享的技巧,你学会了吗?若有什么问题,欢迎在下方留言。
快来试试吧,小琥 my21ke007。获取 1000个免费 Excel模板福利!
更多技巧, www.excelbook.cn
欢迎 加入 零售创新 知识星球,知识星球主要以数据分析、报告分享、数据工具讨论为主;
1、价值上万元的专业的PPT报告模板。
2、专业案例分析和解读笔记。
3、实用的Excel、Word、PPT技巧。
4、VIP讨论群,共享资源。
5、优惠的会员商品。
6、一次付费只需129元,即可下载本站文章涉及的文件和软件。

