【问题标题】:Iterate commits b/w 2 specified commits in GitPython在 GitPython 中迭代提交 b/w 2 指定提交
【发布时间】:2019-08-06 04:16:01
【问题描述】:
import git
repo = git.Repo(repo_dir)
ref_name = 'master'
for commit in repo.iter_commits(rev=ref_name):
     <some code here>

此代码遍历所有提交。我想迭代 b/w 2 提交。 就像git log commit1...commit2

如何使用 GitPython 的 iter_commits() 方法来做同样的事情。

【问题讨论】:

  • 但是您知道在终端上执行git 命令的代码吗?如果是,您可以使用subprocess 创建一个函数。然后就可以调用函数运行git命令了。
  • 是的,我能做到。但我不想走那条路。我想使用这个 GitPython Lib
  • gitpython.readthedocs.io/en/stable/… 。从Commit.iter_items() 接受修订说明符,我相信修订范围也是其中的一部分。只要通过'commit1...commit2' 就可以了。
  • 如果你的问题完全是关于“我如何在 gitpython 中做 X 事情”,那么 gitpython 标签是合适的,但其他标签都不合适,因为你会得到像来自 @ 的答案优素福。请注意,commit 是关于数据库事务,而不是关于 Git 提交。

标签: python git loops commit gitpython


【解决方案1】:

repo.iter_commits(rev='1234abc..5678def')GitPython==2.1.11 中为我工作

例子:

repo = git.Repo(repo_dir)
for commit in repo.iter_commits(rev='master..HEAD'):
     <some code here>

【讨论】:

    【解决方案2】:

    你可以使用纯 gitpython。

    如果你希望能够遍历某个提交(假设第一个 commit 是 HEAD),只需使用 max_count。见The Commit object

    two_commits = list(repo.iter_commits('master', max_count=2))
    assert len(two_commits) == 2
    

    如果您想要与您提到的git log commit1...commit2 类似的能力:

    logs = repo.git.log("--oneline", "f5035ce..f63d26b")
    

    会给你:

    >>> logs
    'f63d26b Fix urxvt name to match debian repo\n571f449 Add more key for helm-org-rifle\nbea2697 Drop bm package'
    

    您也可以使用logs = repo.git.log("f5035ce..f63d26b"),但它会为您提供所有信息(就像您使用git log 而不使用--oneline

    如果您想要漂亮的输出,请使用漂亮的打印:

    from pprint import pprint as pp
    >>> pp(logs)
    ('f63d26b Fix urxvt name to match debian repo\n'
     '571f449 Add more key for helm-org-rifle\n'
     'bea2697 Drop bm package')
    

    更多关于repo.git.log的解释,见https://stackoverflow.com/a/55545500/6000005

    【讨论】:

      【解决方案3】:

      我建议你使用PyDriller(GitPython 的一个包装器,让事情变得更容易)。你问的可以这样做:

      for commit in RepositoryMining("path_to_repo", from_commit="first", to_commit="second").traverse_commits():
          # your code
      

      【讨论】:

        【解决方案4】:

        首先,创建一个函数来运行git 命令。

        from git import *
        from subprocess import Popen, PIPE
        
        def execute_gitcmd(cmd, repo):
            pipe = subprocess.Popen(cmd, shell=True, cwd=repo, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            (out, error) = pipe.communicate()
            return out, error
            pipe.wait()
        

        然后在终端上编写任何git 命令,例如:

        gitcmd = "git log -n1 --oneline"
        

        最后,调用你的函数:

        log = (execute_gitcmd(gitcmd, your_repository))
        

        希望这能有所帮助。

        【讨论】:

        • 1.问题是关于 GitPython。 2.函数有一个大bug——returnpipe.wait()之前。
        猜你喜欢
        • 2012-12-29
        • 1970-01-01
        • 2016-07-25
        • 2015-05-23
        • 2017-11-23
        • 2019-11-01
        • 1970-01-01
        • 2015-11-04
        • 2019-09-17
        相关资源
        最近更新 更多