简体   繁体   English

Git:如何忽略对跟踪文件的更改?

[英]Git: How to ignore changes to a tracked file?

I have a file with database settings in my project which I have set to some defaults. 我的项目中有一个带有数据库设置的文件,我已将其设置为一些默认值。 The file is tracked by Git and checked in. Since this file will be edited with different values various developer machines, is there a way I can tell Git to ignore new changes to this file? 该文件由Git跟踪并签入。由于将使用各种开发人员机器使用不同的值来编辑此文件,因此有没有办法让我告诉Git忽略对此文件的新更改?

I tried adding the file to the .gitignore file, but since the file is tracked it isn't ignored. 我尝试将文件添加到.gitignore文件,但是由于已跟踪文件,因此不会忽略该文件。 This is alright and good in other situations, but I am wondering if there is something I can do here? 在其他情况下这还不错,但是我想知道是否可以在这里做些什么?

I recommend naming the source-controlled file differently than its actual expected name. 我建议对源代码控制文件的命名与其实际的预期名称不同。 For example, if the file is normally named config.json , then name your example file config.json.dist and commit this file. 例如,如果文件通常名为config.json ,则将示例文件命名为config.json.dist并提交该文件。 Then add config.json to your .gitignore file. 然后将config.json添加到您的.gitignore文件中。 Your devs would simply cp config.json.dist config.json after cloning, and then edit it as required, making subsequent commits without having to worry about accidentally changing the default file or forgetting to toggle some setting on and off all the time. 您的开发人员只需在克隆后简单地cp config.json.dist config.json ,然后根据需要对其进行编辑,即可进行后续提交,而不必担心意外更改默认文件或忘记一直打开和关闭某些设置。

You might even edit your code to search for config.json first, and if that doesn't exist, fall back to config.json.dist . 您甚至可以编辑代码以首先搜索config.json ,如果不存在,则退回到config.json.dist This would allow the devs to work without even performing the copy step. 这将使开发人员甚至无需执行复制步骤即可工作。 (This is how PHPUnit works.) (这是PHPUnit的工作方式。)

One may use git update-index --skip-worktree FILE for this purpose. 为此,可以使用git update-index --skip-worktree FILE

It is similar to --assume-unchanged but, unlike --assume-unchanged , is not just an unpredictable performance trick . 它与--assume-unchanged相似,但是与--assume-unchanged不同, 它不仅仅是一个不可预测的性能技巧

To cancel --skip-worktree effects and unset the flag use --no-skip-worktree . 要取消--skip-worktree效果并取消设置标志,请使用--no-skip-worktree

Downsides 缺点

  • This flag is for local repository only and cannot be pushed to the remote. 该标志仅用于本地存储库,不能推送到远程。 Thus every clone that needs to ignore the file should do it manually. 因此,每个需要忽略文件的克隆都应手动执行。
  • You may face conflicts when switching to another branch or using git pull . 当切换到另一个分支或使用git pull时,您可能会遇到冲突。 ( more details ) 更多详细信息

You can use git update-index --assume-unchanged <file> 您可以使用git update-index --assume-unchanged <file>

And if you want to track it again use git update-index --no-assume-unchanged <file> 如果要再次跟踪它,请使用git update-index --no-assume-unchanged <file>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM