python操作git

安装模块

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)

将上述所有的方法封装到类中以便后续的调用(后续如果你想要操作git直接拷贝使用即可)

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的更多相关文章

  1. 利用Python代码编写计算器小程序

    import tkinter import tkinter.messagebox import math class JSQ: def __init__(self): #创建主界面 self.root ...

  2. 合并代码操作 | git fetch 与 git pull

    前言 首先我们要说简单说git的运行机制.git分为本地仓库和远程仓库,我们一般情况都是写完代码,commit到本地仓库(生成本地仓的commit ID,代表当前提交代码的版本号),然后push到远程 ...

  3. day06 python代码操作MySQL

    day06 python代码操作MySQL 今日内容 python代码操作MySQL 基于python与MySQL实现用户注册登录 python操作MySQL python 胶水语言.调包侠(贬义词& ...

  4. 字符编码和Python代码操作文件

    字符编码和Python代码操作文件 读写模式之a模式 # a模式 只追加模式 # 路径不存在:自动创建 with open(r'a.txt','a',encoding='utf8') as f: pa ...

  5. 利用Python openpyxl操作Excel

    from IPython.core.interactiveshell import InteractiveShell InteractiveShell.ast_node_interactivity = ...

  6. 利用python代码获取文件特定的内容,并保存为文档

    说明:有段时间需要读取上百个文件的单点能(sp),就写了下面的代码(计算化学狗努力转行中^-^) import os.path import re # 1 遍历指定目录,显示目录下的所有文件名 def ...

  7. 通过Python代码操作MySQL:

    pymsql / MySQLdb pymysql支持 py2/py3 MySQLdb支持py2 ORM框架 django orm ( 自己对数据连接有优化机制 ) SQLAlchemy ( 自带数据库 ...

  8. 利用Python操作MySQL数据库

    前言 在工作中,我们需要经常对数据库进行操作,比如 Oracle.MySQL.SQL Sever 等,今天我们就学习如何利用Python来操作 MySQL 数据库. 本人环境:Python 3.7.0 ...

  9. 八.python文件操作

    一,初识文件操作. 引子: 现在这个世界上,如果可以操作文件的所有软件都消失了,比如word,wps等等,此时你的朋友通过qq给你发过来一个文件,文件名是:美女模特空姐护士联系方式.txt,在座的所有 ...

随机推荐

  1. Java和Mysql中的数据类型

    1.mysql中的基本类型 1.整数: tinyint:1个字节   -128~127 smallint: 2个字节  -32768~32767 int :  4个字节 bigint:  8个字节 2 ...

  2. oracle 查询表空间

    测试用户连接C:\Users\ZP>sqlplus /nologconn hbcxuser/hbcxpass --查看所有表空间 select * from user_tablespaces-- ...

  3. windows下pip的安装

    安装地址:https://pypi.python.org/pypi/pip#downloads 下载完成后,找到文件并进行解压,找到下面路径. 打开cmd,cd到当前目录下,然后执行下面命令: pyt ...

  4. learning Perl:91行有啥用? 88 print "\n----------------------------------_matching_multiple-line_text--------------------------\n"; 91 my $lines = join '', <FILE>;

    89 open FILE, "< file_4_ex_ch7.txt"     90     or die "cannot open file: $!"; ...

  5. mediawiki问题

    部分内容参考 http://blog.csdn.net/gaogao0603/article/details/7689670 1.启用文件上传:在LocalSettings.php修改或者增加如下:$ ...

  6. day43-线程概念

    #1.进程:程序不能单独运行,要将程序加载到内存当中,系统为它分配资源才能运行,而这种执行的程序就是进程. #程序和进程的区别在于:程序是指令的集合,它是进程运行的静态描述文本:进程是程序的一次执行活 ...

  7. 必应翻译:让Windows上的翻译不再是难事

    文章译自:Translations Made Easy on Windows 比方说今年夏天你想出国旅行,计划去一趟德国.你的行程很丰富:参观慕尼黑和柏林,乘坐游船沿莱茵河而下,再品尝几串摩泽尔的葡萄 ...

  8. hibernate中lazy的使用

    lazy,延迟加载 Lazy的有效期:只有在session打开的时候才有效:session关闭后lazy就没效了. lazy策略可以用在: * <class>标签上:可以取值true/fa ...

  9. [LC] 345. Reverse Vowels of a String

    Write a function that takes a string as input and reverse only the vowels of a string. Example 1: In ...

  10. python代码覆盖率统计-coverage

    coverage.py是一个用来统计python程序代码覆盖率的工具.它使用起来非常简单,并且支持最终生成界面友好的html报告.在最新版本中,还提供了分支覆盖的功能. 官方网站: http://ne ...