标题Python操作git仓库
离线安装GitPython模块,我这里使用python3版本,查找下载三个依赖模块,下载链接请移步上篇博文
切换到.whl文件所在的路径下,执行离线安装
pip install gitdv-4.0.5-py3-none-any.whl
pip install GitPython-3.1.7-py3-none-any.whl
pip install smmap-3..0.4-py3-none-any.whl
在线安装可以直接使用
pip install GitPython #在线安装会自动安装其依赖模块
安装完成后,可实现git基本操作
这里用python实现git连接远程库,新建/切换分支,拉取代码,新建tag并推送,远程与本地的操作类似,都要建立各自的仓库对象
基本的git命令使用:
from git import Repo #使用gitpython要导入git的Repo对象
克隆远程仓库
Repo.clone_from("git远程给仓库地址",to_path="将要克隆到的本地仓库地址")
初始化本地仓库
Repo.init(r"C:\Users\Icey\Desktop\aa") #aa为要初始化的本地仓库
提交两步走
repo = Repo(r"C:\Users\Icey\Desktop\aa") #获取本地仓库对象
index = repo.index #获取本地仓库的暂存区对象
#index.add(r'*') #将本地所有改动提交到暂存区
index.add(['aaaa.txt']) #将aaaa.txt文件提交到暂存区
index.commit("此次提交备注信息")
远程仓库拉取/推送
repo = Repo.clone_from("git远程给仓库地址",to_path=r"C:\Users\Icey\Desktop\bbb") #获取远程仓库对象
repo.git.pull() #拉取
repo.git.push("master") #推送到远程master分支
新建并切换分支
repo.git.branch("dev") #新建dev分支
repo.git.checkout("dev") #切换到dev分支
新建并推送tag到远程
repo.git.creat_tag("tag_name", m = "tag_msg") #新建一个名为tag_name的标签,tag_msg--tag备注信息
repo.git.push('origin',new_tag) #将标签推送远程仓库
下面附赠工作中的小脚本,本篇纯属工作之余的记录反思,有不对的还请各位大佬指正,小弟在此抱拳感谢
import os
from git import Repo
from git.repo.fun import is_git_dir
class GitRepository(object):
#初始化
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):
#判断本地仓库存在否,不存在则新建一个
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):
self.repo.git.pull()
#将本地提交推送到远程
def push(self):
self.repo.git.push('master')
#切换分支
def change_to branch(self,ch_branch):
self.repo.git.checkout(ch_branch)
#新建tag并推送远程
def tags(self,new_tag,new_msg):
self.repo.create_tag(new_tag,m = new_msg)
self.repo.git.push('origin',new_tag)
if __name__ == '__main__':
local_path = input('请输入本地仓库地址:')
repo_url = input('请输入远程仓库地址:')
repo = GitRepository(local_path,repo_url)
ch_branch = input("请输入要切换的分支名称:")
repo.change_to_branch(ch_branch)
repo.pull()
new_tag = input("请输入新建的tag:")
new_msg = input("请输入本次推送的备注信息:")
repo.tags()