如何告诉 git 忽略单个行,即特定代码行的 gitignore [英] How to tell git to ignore individual lines, i.e. gitignore for specific lines of code

查看:45
本文介绍了如何告诉 git 忽略单个行,即特定代码行的 gitignore的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

.gitignore can ignore whole files, but is there a way to ignore specific lines of code while coding?

我经常重复地在项目中添加相同的调试行,但在提交之前必须记住将它们删除.我只想保留代码中的行,让 git 忽略它们.

I frequently and repeatedly add the same debug lines in a project, only to have to remember to remove them before committing. I'd like to just keep the lines in the code and have git disregard them.

推荐答案

这就是您可以使用 git 过滤器:

  1. 创建/打开 gitattributes 文件:
    • /.gitattributes(将提交到 repo)
    • /.git/info/attributes(不会提交到 repo)
  1. Create/Open gitattributes file:
    • <project root>/.gitattributes (will be committed into repo)
      OR
    • <project root>/.git/info/attributes (won't be committed into repo)
  • *.rb filter=gitignore,即在所有 *.rb 文件上运行名为 gitignore 的过滤器
  • *.rb filter=gitignore, i.e. run filter named gitignore on all *.rb files
  • $ git config --global filter.gitignore.clean "sed '/#gitignore$/d'",即删除这些行
  • $ git config --global filter.gitignore.smudge cat,即从repo拉取文件时什么都不做
  • $ git config --global filter.gitignore.clean "sed '/#gitignore$/d'", i.e. delete these lines
  • $ git config --global filter.gitignore.smudge cat, i.e. do nothing when pulling file from repo

注意事项:
当然,这是针对 ruby​​ 文件的,当一行以 #gitignore 结尾时应用,在 ~/.gitconfig 中全局应用.根据您的目的修改它.

Notes:
Of course, this is for ruby files, applied when a line ends with #gitignore, applied globally in ~/.gitconfig. Modify this however you need for your purposes.

警告!!
这使您的工作文件与存储库不同(当然).任何检出或变基都将意味着这些行将丢失!这个技巧似乎没用,因为这些行在 checkout、rebase 或 pull 时反复丢失,但我有一个特定的用例来利用它.

Warning!!
This leaves your working file different from the repo (of course). Any checking out or rebasing will mean these lines will be lost! This trick may seem useless since these lines are repeatedly lost on check out, rebase, or pull, but I've a specific use case in order to make use of it.

只需 git stash save "proj1-debug" 当过滤器处于非活动状态(只是在 gitconfig 或其他东西中暂时禁用它).这样,我的调试代码可以随时git stash apply'd 到我的代码中,而不必担心这些行会被意外提交.

Just git stash save "proj1-debug" while the filter is inactive (just temporarily disable it in gitconfig or something). This way, my debug code can always be git stash apply'd to my code at any time without fear of these lines ever being accidentally committed.

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

I have a possible idea for dealing with these problems, but I'll try implementing it some other time.

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

Thanks to Rudi and jw013 for mentioning git filters and gitattributes.

这篇关于如何告诉 git 忽略单个行,即特定代码行的 gitignore的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆