用Python检查GIT文件的修订

用Python检查GIT文件的修订,python,git,Python,Git,假设我有一个文件位于: 'C:/Users/jdoe/development/git/something/A.txt' 我想定义一个Python函数,用于检查该文件是否在git repo中。如果它不在git repo中,我希望函数返回None。如果它在git repo中,我希望函数返回文件的状态以及文件修订 def git_check(path): if path is not in a git repo: return None

假设我有一个文件位于:

    'C:/Users/jdoe/development/git/something/A.txt'
我想定义一个Python函数,用于检查该文件是否在git repo中。如果它不在git repo中,我希望函数返回None。如果它在git repo中,我希望函数返回文件的状态以及文件修订

    def git_check(path):
         if path is not in a git repo:
             return None
         else:
             return (status, last_clean_revision)

我不确定是应该使用GitPython选项还是子流程。任何指导都将不胜感激。

从源代码看,GitPython似乎无论如何都在使用子流程

我会坚持使用GitPython来避免从git解析输出文本的麻烦


就指导而言,似乎没有太多文档,所以我建议您阅读源代码本身,它似乎有很好的注释。

我最终选择了子流程路线。我不喜欢先用GitPython设置repo对象,因为我的路径甚至不能保证是git存储库的一部分

对于那些感兴趣的人,以下是我的结论:

import subprocess

def git_check(path):  # haha, get it?
    # check if the file is in a git repository
    proc = subprocess.Popen(['git',
                             'rev-parse',
                             '--is-inside-work-tree',],
                             cwd = path,
                             stderr=subprocess.STDOUT, stdout=subprocess.PIPE)
    if 'true' not in proc.communicate()[0]:
        return None

    # check the status of the repository
    proc = subprocess.Popen(['git',
                             'status',],
                             cwd = path,
                             stderr=subprocess.STDOUT, stdout=subprocess.PIPE)
    log_lines = proc.communicate()[0].split('\n')
    modified_files = [x.split(':')[1].lstrip() for x in log_lines if 'modified' in x]
    new_files = [x.split(':')[1].lstrip() for x in log_lines if 'new file' in x]

    # get log information
    proc = subprocess.Popen(['git',
                             'log','-1'],
                             cwd = path,
                             stderr=subprocess.STDOUT, stdout=subprocess.PIPE)         
    log_lines = proc.communicate()[0].split('\n')
    commit = ' '.join(log_lines[0].split()[1:])
    author = ' '.join(log_lines[1].split()[1:])
    date = ' '.join(log_lines[2].split()[1:])


    git_info = {'commit':commit,
                'author':author,
                'data': date,
                'new files':new_files,
                'modified files':modified_files}

    return git_info

一定要使用GitPython:它应该允许更直接地使用Git,而不是解析命令行工具的输出。