gitpython实现window双击exe程序,自动提交git远程仓库

1.具体代码

使用gitpython实现,附带.gitignore的功能,gitpython本身没有这个功能,完整代码如下

import datetime
import os
import traceback
from os import path
from git import Repo
# current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")

# git 提交工具类
def commit_git(dir_path,origin,branch):
    start_time = datetime.datetime.now()
    repo = Repo(dir_path)
    print('=====================开始add,dir_path='+dir_path)
    index = repo.index
    add_list = exe_find_need_add_files(dir_path)
    # for item in add_list:
    #     print(item)
    index.add(items=add_list)
    print('=======add结束,开始commit')
    index.commit(message='python自动提交'+datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
    print('=======commit结束,开始push,origin='+origin+',branch='+branch)
    remote = repo.remote(origin)
    
    remote.push(branch)
    end_time = datetime.datetime.now()
    print('=====================push结束,dir_path='+dir_path+",这一步耗费时间:"+str(end_time-start_time))
    repo.close()

# 读取.gitignore信息
def read_ignore(dir_path):
    # 1. 读取排除文件
    ignore_path = dir_path+'/.gitignore'
    exclude_list = []
    if path.exists(ignore_path):
        with open(file = ignore_path, mode='r', encoding='utf-8') as file:
            temp = file.readline()
            while temp:
                temp = temp.replace('\r', '').replace('\n','')
                # print(temp+"=========>"+str(bool(temp)))
                if ((temp.startswith('#'))==False and bool(temp)==True):
                    exclude_list.append(temp)
                temp = file.readline()
    # 2. .git同样需要排除
    exclude_list.append('.git')
    return exclude_list

# 获取配置的git库信息,就是该脚本需要提交的信息
def select_config():
    # 1. 获取配置文件地址
    curr_config_path = os.getcwd()+'/config.txt'
    # 2. 创建一个返回数组
    git_list = []
    # 3. 读取配置文件内容
    with open(curr_config_path, 'r') as file:
        tempValue = file.readline()
        while tempValue:
            # print('==>'+tempValue)
            git_list.append(tempValue.replace('\r','').replace('\n',''))
            tempValue = file.readline()
    return git_list

# 将配置信息转换成path,origin,branch
def process_config(config_info):
    if config_info:
        infos = config_info.split('&&&')
        return infos
    return []

# 开始同步
def start_commit():
    # 1. 获取开始时间
    start_time = datetime.datetime.now()
    # 2. 获取配置列表
    git_list = select_config()
    for item in git_list:
        infos = process_config(item)
        if infos:
            # 3. 提交git操作
            print('当前操作库:'+infos[0]+","+infos[1]+","+infos[2])
            dir_path = infos[0]
            origin = infos[1]
            branch = infos[2]
            commit_git(dir_path,origin,branch)
    # 4. 结束时间
    end_time = datetime.datetime.now()
    print("==============共耗费时间:"+str(end_time-start_time))

# 1. 读取文件夹内所有文件,返回all_file_list
def find_all_files(parent_path, all_file_list):
    if path.exists(parent_path):
        curr_list = os.listdir(parent_path)
        # print(curr_list)
        for item in curr_list:
            curr_path = parent_path+'\\' + item
            if path.isdir(curr_path):
                find_all_files(curr_path, all_file_list)
            else:
                all_file_list.append(curr_path)
            # print(path.isdir(parent_path+'\\'+item))

# 2. 通过exclude_list返回need_add_list
def find_need_add_list(all_file_list, exclude_list):
    need_add_list = []
    for all_file_item in all_file_list:
        file_flag = True
        dir_flag = True
        for exclude_item in exclude_list:
            # 1. 如果包含‘*’,说明是文件排除,使用结尾匹配
            if exclude_item.startswith('*'):
                exclude_item = str_substring(exclude_item,1)
                if all_file_item.endswith(exclude_item):
                    file_flag = False
                    # print('1==>'+all_file_item+','+exclude_item+','+str(file_flag))
                    break
                    
            # 2. 说明是文件夹或者文件,则直接包含
            elif all_file_item.find(exclude_item.replace('\\','').replace('/','')+'\\') != -1:
                dir_flag = False
                # print('2==>'+all_file_item+','+exclude_item+','+str(dir_flag))
                break
        if dir_flag and file_flag:
            need_add_list.append(all_file_item)
            # print('3==>'+all_file_item+','+exclude_item+','+str(dir_flag and file_flag))
    return need_add_list

# 自定义方法,实现字符串截取功能
def str_substring(param, start, end=-1):
    if param:
        end = len(param) if end==-1 else end
        res = param[start:end]
        return res
    return param

# 获取所有需要操作的清单
def exe_find_need_add_files(parent_path):
    final_need_add_list = []
    # 1. 获取所有文件清单和排除清单
    all_file_list = []
    find_all_files(parent_path, all_file_list)
    exclude_list = read_ignore(parent_path)
    # 2. 获取需要操作的清单
    need_add_list = find_need_add_list(all_file_list, exclude_list)
    for item in need_add_list:
        item = item.replace(parent_path+'\\','')
        # print(item)
        final_need_add_list.append(item)
    
    return final_need_add_list

# 入口方法
if __name__ == "__main__":
    try:
        start_commit()
        # parent_path = r'E:\Use\caogao\demo2'
        # exe_find_need_add_files(parent_path)
    except:
        print("start======================>对不起,出现异常了!!!")
        traceback.print_exc()
        print("end======================>对不起,出现异常了!!!")
    str = input("程序已结束...")
    print(str)

2.运行效果图

gitpython实现window双击exe程序,自动提交git远程仓库_第1张图片

gitpython实现window双击exe程序,自动提交git远程仓库_第2张图片

使用的时候,配置好config.txt,直接双击“CommitGit.exe”就好了,关键文件就“config.txt”、"CommitGit.exe",其他文件为使用说明或者python源码。

整个文件下载:

https://download.csdn.net/download/liurui50/87744213

 

你可能感兴趣的:(git,gitpython)