2

我正在尝试确定git commitgit 存储库中是否需要 or 。我想出了对我来说很好的代码:

def is_dirty(repo):
  import pygit2
  status = repo.status()
  for filepath, flags in status.items():
    if flags != pygit2.GIT_STATUS_CURRENT:
        if flags != 16384:
            return True
  return False;

但这是非常低效的:repo.status()需要永远 - 至少与git status命令行相比。

所以我的问题是:有没有更有效的方法来知道存储库是否干净?

PS:我正在使用python3。在 python2 中,我使用了git具有is_dirty功能的模块。

4

3 回答 3

2

5年后。这是我现在所做的

pip3 install GitPython

接着

import git
repo = git.Repo("path/to/my/repo")
if repo.is_dirty(untracked_files=True):
   do_work()
于 2020-12-09T21:47:42.127 回答
1

Repository.status()性能在快速测试中表现良好。

典型用法:

import pygit2
from pathlib import Path
from typing import Dict, Union
repo_path: Union[Path, str] = Path("/path/to/your/repo")
repo = pygit2.Repository(pygit2.discover_repository(repo_path))
status: Dict[str, int] = repo.status()
print(status)
# {} (nothing to commit, working tree clean)
# {"myfile" : 256} (myfile is modified but not added)

我的功能版本,用于删除文件模式已更改的文件(代码 16384,GIT_FILEMODE_TREE)。

def get_repo_status(repo: pygit2.Repository) -> Dict[str, int]:
    # get the integer representing filemode changes
    changed_filemode_status_code: int = pygit2.GIT_FILEMODE_TREE
    original_status_dict: Dict[str, int] = repo.status()
    # transfer any non-filemode changes to a new dictionary
    status_dict: Dict[str, int] = {}
    for filename, code in original_status_dict.items():
        if code != changed_filemode_status_code:
            status_dict[filename] = code
    return status_dict

表现:

%timeit repo.status()
# 2.23 ms per loop
%timeit get_repo_status(repo)
# 2.28 ms per loop
%timeit subprocess.run(["git", "status"]) # yes, I know, this is not really comparable..
# 11.3 ms per loop
于 2020-06-08T13:42:31.423 回答
0

真的很脏的解决方案?python: 用 git status 执行一个 shell 脚本

sh:
VAR= $(git status)
dump var to file 

python:
meanwhile your python script is waiting for the file to be created
while(1)
if(os.path.exists(file_path))
status = read_file_function(file_path)
break 

愚蠢而简单,而且可能很明显

于 2015-11-15T03:51:15.593 回答