代码之家  ›  专栏  ›  技术社区  ›  Peeja

如何搜索Git分支以查找文件或目录?

  •  277
  • Peeja  · 技术社区  · 17 年前

    在Git中,如何通过多个分支按路径搜索文件或目录?

    我在一个分支中写了一些东西,但我不记得是哪一个。现在我需要找到它。

    澄清 :我正在查找在某个分支上创建的文件。我想通过路径而不是内容找到它,因为我不记得内容是什么。

    6 回复  |  直到 7 年前
        1
  •  359
  •   boatcoder    9 年前

    Git日志将为您找到它:

    % git log --all -- somefile
    
    commit 55d2069a092e07c56a6b4d321509ba7620664c63
    Author: Dustin Sallings <dustin@spy.net>
    Date:   Tue Dec 16 14:16:22 2008 -0800
    
        added somefile
    % git branch -a --contains 55d2069
      otherbranch
    

    也支持全局链接:

    % git log --all -- '**/my_file.png'
    

    单引号是必需的(至少在使用bash shell时如此),因此shell将glob模式传递给git,而不是将其扩展(就像在Unix中一样) find )

        2
  •  59
  •   ï¾ ï¾ ï¾    14 年前

    Git LS树可能会有帮助。要搜索所有现有分支:

    for branch in `git for-each-ref --format="%(refname)" refs/heads`; do
      echo $branch :; git ls-tree -r --name-only $branch | grep '<foo>'
    done
    

    这样做的好处是,您还可以使用正则表达式搜索文件名。

        3
  •  17
  •   Peter Mortensen Pieter Jan Bonestroo    7 年前

    虽然 ididak's response 很酷,而且 HANDYMAN5 提供了一个脚本来使用它,我发现使用这种方法有点局限。

    有时您需要搜索一些随时间而出现/消失的内容,那么为什么不针对所有提交进行搜索呢?除此之外,有时您需要详细的响应,而其他时候只提交匹配项。以下是这些选项的两个版本。将这些脚本放到您的路径上:

    查找文件

    for branch in $(git rev-list --all)
    do
      if (git ls-tree -r --name-only $branch | grep --quiet "$1")
      then
         echo $branch
      fi
    done
    

    Git查找文件详细信息

    for branch in $(git rev-list --all)
    do
      git ls-tree -r --name-only $branch | grep "$1" | sed 's/^/'$branch': /'
    done
    

    现在你可以做

    $ git find-file <regex>
    sha1
    sha2
    
    $ git find-file-verbose <regex>
    sha1: path/to/<regex>/searched
    sha1: path/to/another/<regex>/in/same/sha
    sha2: path/to/other/<regex>/in/other/sha
    

    请参阅使用 getopt 您可以修改该脚本以交替搜索所有提交、引用、引用/头、详细信息等。

    $ git find-file <regex>
    $ git find-file --verbose <regex>
    $ git find-file --verbose --decorated --color <regex>
    

    结帐 https://github.com/albfan/git-find-file 为了可能的实施。

        4
  •  9
  •   Greg Hewgill    17 年前

    你可以使用 gitk --all 搜索提交的“接触路径”和您感兴趣的路径名。

        5
  •  5
  •   lumbric    10 年前

    复制粘贴以使用 git find-file SEARCHPATTERN

    打印所有搜索的分支:

    git config --global alias.find-file '!for branch in `git for-each-ref --format="%(refname)" refs/heads`; do echo "${branch}:"; git ls-tree -r --name-only $branch | nl -bn -w3 | grep "$1"; done; :'
    

    仅打印结果为的分支:

    git config --global alias.find-file '!for branch in $(git for-each-ref --format="%(refname)" refs/heads); do if git ls-tree -r --name-only $branch | grep "$1" > /dev/null; then  echo "${branch}:"; git ls-tree -r --name-only $branch | nl -bn -w3 | grep "$1"; fi; done; :'
    

    这些命令将直接向您的 ~/.gitconfig 作为 global git alias .

        6
  •  -1
  •   Peter Mortensen Pieter Jan Bonestroo    7 年前

    相当体面的 find git存储库的命令可以在这里找到:

    https://github.com/mirabilos/git-find