簡體   English   中英

使用Python檢查GIT文件的修訂

[英]Check Revision of GIT file with Python

可以說我有一個文件位於:

    '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設置存儲庫對象,因為不能保證我的路徑甚至是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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM