【问题标题】:How to find the first occurrence of a line (or part of a line) using Git?如何使用 Git 查找第一次出现的行(或行的一部分)?
【发布时间】:2016-07-02 16:12:15
【问题描述】:

假设我们在代码中看到一行:

a = foo.bar + xyz.abc + fn() * 3;

现在我们知道foo.bar 是“错误”代码或导致某些问题的代码。而git blame 将显示该行是由迈克尔编写的。但是,Michael 可能没有签入那部分代码。他可能只修改了* 3 部分。那么在这种情况下,我们如何才能在 repo 中找到foo.bar 的第一次出现,并找出是谁编写或添加了它?

我想用

git show HEAD:path/to/file.js | grep 'foo.bar'

然后

git show HEAD~1:path/to/file.js | grep 'foo.bar'
git show HEAD~2:path/to/file.js | grep 'foo.bar'

只需将2 增加到34 等,直到我看不到显示foo.bar 的那一行。

但是如果这个数字可以很大,比如120343。有没有更好或更快的方法?

【问题讨论】:

标签: git


【解决方案1】:

你可以使用 blame with commit sha 来继续更深层次地责备,例如:

git blame -L65,+2 -- application.py
# the commit sha in the output is 4dd5a167
# 4dd5a167 (Boris Serebrov 2015-09-08 21:33:20 +0300 65)     except database.ItemNotFound:
# 74311d17 (Boris Serebrov 2015-11-12 11:16:50 +0200 66)         # no node - log error and create it

# continue blaming from the 4dd5a167's parent (4dd5a167^)
git blame -L65,+2 4dd5a167^ -- application.py

此功能在vim-fugitive vim 插件中使用,通常非常有用。您可以执行:Gblame,然后按~ 来“重新责备”更改。 即使您不是 vim 用户,也值得尝试看看它是如何工作的。 Here 很好地解释了逃犯的行为。

【讨论】:

    【解决方案2】:

    我猜你想要做的事情可以通过带有选项 --grep-reflog 的命令 git-log 来完成。

    既然你已经知道你感兴趣的文件,我想这个列表会很短。有了一些使用得当的选项,我想你想要的一切都可以用 git-log 完成。

    git-log Documentation page

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-10-04
      • 2016-05-10
      • 2015-06-08
      • 1970-01-01
      • 2018-03-22
      • 2019-08-17
      • 2018-11-28
      相关资源
      最近更新 更多