GitPython中当前日期与某些时间之前的git diff

问题描述 投票:3回答:2

我正在使用GitPython在一段时间内(例如现在和1周前)查找更改的文件:

 repo = Repo(self.repo_directory)
 for item in repo.head.commit.diff('develop@{1 weeks ago}'):
     print ("smth") 

但是即使将周数更改为其他数字也没有任何反应,这意味着在该时间段内未检测到差异。如果我将'develop@{1 weeks ago}'更改为'HEAD@{1 weeks ago}',则更改的数量巨大,一周之内不正确。任何帮助表示赞赏。

python git git-diff gitpython
2个回答
1
投票

develop@{1 weeks ago}将使用reflog

引用日志或“引用日志”,记录分支和其他引用的提示在本地存储库中的更新时间。

这意味着一周前,您的本地Git存储库可能未在reflog上本地记录任何操作,而它已记录了“ HEAD”上发生的任何事情。

如果开发是远程更改的,然后将其历史记录本地导入,则develop可能不会产生任何结果(因为您的本地引用日志不会引用它。)>

develop@{1 weeks ago}会在any

日期运行(不仅限于reflog中记录的日期,后者仅限于本地运行,并且默认为90天)]]

但是我不知道GitPython是否实现了。其git log --since/--until模块更多地基于引用日志条目,这对您而言无济于事。

基于评论中的讨论,我提出了以下使用GitPython的解决方案(仅将所需的代码放在此处,并忽略了其余代码以避免混淆)

git log --since/--until

但是,git.refs.log的长度对我来说并不合理,因为它捕获了太多的变化,我不确定为什么。因此,基本上,我所做的是:找到所有提交,根据git.refs.log对它们进行排序,然后找到一个提交(代码中的 import git from git import Repo from git import RemoteProgress class MyProgressPrinter(RemoteProgress): def update(op_code, cur_count, max_count=None, message=''): print(op_code, cur_count, max_count, cur_count / (max_count or 100.0), message or "NO MESSAGE") def _get_commits_info(self): for fetch_info in self.repo.remotes.origin.fetch(progress=MyProgressPrinter()): self.commits_info.append( (fetch_info.commit.committed_date, fetch_info.commit)) self.commits_info = sorted(self.commits_info, key=lambda x: x[0]) #sort based on committed date def _get_the_changed_components(self): self._get_commits_info() last_date = self.commits_info[-1][0] last_commit = self.commits_info[-1][1] since_date = last_date - self.time_period * 86400 # for example time_period is 7 (days) since_commit = self._get_since_commit(since_date) # finds the since_commit from the sorted list of commits_info for item in last_commit.diff(since_commit): if item.a_path.find('certain_path') != -1: self.paths.add(item.a_path) #self.path is a set() ),其中其self.path用于committed_date。之后,得到排序的since_commit列表中的committed_date7 days ago之间的差异,然后将last commit es保存到集合中。

我也尝试了另一种方法,并从排序的commits_info一直到最后一次提交,从since_commit开始,得到了每两个连续提交之间的差异。这样,更改数量会更高。

有任何意见或帮助吗?还是您认为一段时间内获取差异是正确的方法?而更改次数更多的原因只是偶然?

更新和最终解决方案>]

因此,在两个提交之间进行比较(diff)似乎并没有给出从现在到有时甚至以前之间发生的更改,因为在合并之前的提交可能包括感兴趣的时间段之前的更改。为此,我找到了两个解决方案,首先计算从当前日期到现在的a_path更改次数,这不是很准确。为此,我们可以使用:

since_commit

然后计算commits_info字符串的数量,该数量基本上是对回购进行合并的次数,通常这会更改HEAD。但是,它是不准确

,但我们假设此计数为31。然后:
 g = Git(self.repo_directory)
 loginfo = g.log('--since={}'.format(since), '--pretty=tformat:') 

有效且直接的解决方案

Merge pull request

1
投票

基于评论中的讨论,我提出了以下使用GitPython的解决方案(仅将所需的代码放在此处,并忽略了其余代码以避免混淆)

© www.soinside.com 2019 - 2024. All rights reserved.