如何告诉git忽略单独的行,即特定代码行的gitignore

Kac*_*che 149 git ignore gitignore

.gitignore 可以忽略整个文件,但有没有办法在编码时忽略特定的代码行?

我经常反复在项目中添加相同的调试行,只需记住在提交之前删除它们.我想在代码中保留这些行并让git忽略它们.

Kac*_*che 134

这是你可以用git过滤器做的事情:

  1. 创建/打开gitattributes文件:
    • <project root>/.gitattributes(将被提交到repo)
    • <project root>/.git/info/attributes(不会被提交到repo)
  2. 添加一行定义要过滤的文件:
    • <project root>/.gitattributes,即运行<project root>/.git/info/attributes在所有*.rb filter=gitignore文件上命名的过滤器
  3. gitignore在您的*.rb:中定义过滤器:
    • gitignore,即删除这些行
    • gitconfig,即从repo中提取文件时什么也不做

注意:
当然,这适用于ruby文件,在行结束时$ git config --global filter.gitignore.clean "sed '/#gitignore$/'d"应用,全局应用$ git config --global filter.gitignore.smudge cat.根据您的需要修改此项.

警告!!
这使您的工作文件与repo不同(当然).任何退房或重新定位都意味着这些线路将会丢失!这个技巧似乎没用,因为这些行在签出,rebase或pull时反复丢失,但我有一个特定的用例才能使用它.

#gitignore 在过滤器处于非活动状态时(暂时禁用它~/.gitconfig或其他东西).这样,我的调试代码可以随时git stash save "proj1-debug"对我的代码进行处理,而不必担心这些行会被意外提交.

我有一个可能的想法来处理这些问题,但我会尝试在其他时间实现它.

感谢Rudi和jw013提到git过滤器和gitattributes.

  • 不应该是:`git config --global filter.gitignore.clean sed'/#gitignore $/d'`因为你已经命名了过滤器`gitignore` (2认同)
  • 这是有趣的.但它基本上就像有问题的行不存在.它不适用于简单地使*对行的更改*被忽略.因此,您无法在函数调用中更改变量的值.例如,而不是改变`flags = foo | bar` to`flags = foo | 吧| debug_thingy`,你必须确保在之后添加一个像`flags | = debug_thingy`这样的全新行. (2认同)
  • 我找到了一个适合我的解决方案。我正在使用 `git config --global filter.gitignore.clean "sed 's/.*gitignore//'"` 并替换这样的代码 `, var x = returned #gitignore var x = 42`。因此`#gitignore`后面的内容会替换该行,因此`#gitignore`后面必须保留缩进。 (2认同)

Mik*_*ike 21

编写java代码时遇到了类似的问题.我的解决方案是标记我不想提交的代码,然后添加一个预提交钩子来寻找我的标记:

#!/bin/bash
#
# This hook will look for code comments marked '//no-commit'
#    - case-insensitive
#    - dash is optional
#    - there may be a space after the //
#
noCommitCount=$(git diff --no-ext-diff --cached | egrep -i --count "(@No|\/\/\s?no[ -]?)commit")
if [ "$noCommitCount" -ne "0" ]; then
   echo "WARNING: You are attempting to commit changes which include a 'no-commit'."
   echo "Please check the following files:"
   git diff --no-ext-diff --cached --name-only -i -G"(@no|\/\/s?no-?)commit" | sed 's/^/   - /'
   echo
   echo "You can ignore this warning by running the commit command with '--no-verify'"
   exit 1
fi
Run Code Online (Sandbox Code Playgroud)

  • https://git-scm.com/docs/githooks#_pre_commit (3认同)
  • 与基于“sed”的过滤等相比,标记绝对感觉不那么可怕的解决方案和声明性。好一个。 (2认同)