自动化git提交脚本

992 阅读2分钟

一、目的

更快捷的的提交代码,在一些不是复杂的git流程中,不用每次去输入命令,提高效率

提交的git命令

  • 'git pull origin master', # 从远程获取代码并合并本地的版本
  • 'git add .', # 添加目录到缓存区
  • 'git commit -m 备注', # 将暂存区内容添加到仓库中
  • 'git push -u origin "master"' # push到远程仓库

二、思路

执行git命令

  • 首先定义个command_arr,它的数据是由git命令按顺序组成
  • 之后使用pythonos模块中的systemapi,依次循环执行命令 代码如下
commitText = input('请填写备注:')
# git push
def create_git_push():
  command_arr = [
    'git pull origin master', # 从远程获取代码并合并本地的版本
    'git add .', # 添加目录到缓存区
    f'git commit -m {commitText}', # 将暂存区内容添加到仓库中
    'git push -u origin "master"' # push到远程仓库
  ]
  for command in command_arr:
    system(command)

如上,每次的备注信息是不同的,因此这个需要我们自定内容

其他的配置

其他配置主要是git的日志,每次提交后,都需要一个本地文件,能了解到每次提交了什么内容,因此备注需要写清楚

这里的备注的信息有,第一是时间信息,第二是备注信息,当然,可以把 提交的git log写入文件

这里使用python的内置函数open以及write

先获取时间,使用time模块,time模块有本地的localtime和格式化规则strftime

代码如下

from time import localtime, strftime
# 时间
nowTime = ''
def get_time():
  nowTime = strftime('%Y-%m-%d %H:%M:%S', localtime())

在这里格式化的规则没有具体较少,请查看自动化创建git本地库并提交 这里有具体的使用规则

保存的本地日志

# 创建文件
def create_txt():
  file = open(r'F:\2022\python-auto\gitlog.txt','w')
  file.write(f'创建时间:{nowTime} 备注信息:{commitText}')

之后执行以上命令

if __name__ == "__main__":
  get_time()
  create_txt()
  create_git_push()

执行结果如下

image.png

三、完整代码

from os import system
from time import localtime, strftime


commitText = input('请填写备注:')
# git push
def create_git_push():
  command_arr = [
    'git pull origin master', # 从远程获取代码并合并本地的版本
    'git add .', # 添加目录到缓存区
    f'git commit -m {commitText}', # 将暂存区内容添加到仓库中
    'git push -u origin "master"' # push到远程仓库
  ]
  for command in command_arr:
    system(command)

# 时间
nowTime = ''
def get_time():
  nowTime = strftime('%Y-%m-%d %H:%M:%S', localtime())

# 创建文件
def create_txt():
  file = open(r'F:\2022\python-auto\gitlog.txt','w')
  file.write(f'创建时间:{nowTime} 备注信息:{commitText}')

if __name__ == "__main__":
  get_time()
  create_txt()
  create_git_push()