如何让git永久忽略文件中的更改?

24
我正在使用存储网站数据的Git仓库。其中包含一个.htaccess文件,其中一些值适用于生产服务器。为了让我能够在该网站上工作,我必须更改文件中的某些值,但我永远不想提交这些更改,否则会破坏服务器。
由于.gitignore无法忽略已跟踪的文件,因此我使用“git update-index --assume-unchanged .htaccess”来忽略文件中的更改,但这仅适用于您切换分支之前。一旦您切换回原始分支,您的更改就会丢失。
是否有一种方法可以告诉Git忽略文件中的更改,并在更改分支时将其保留不变?(就像该文件未被跟踪一样)。
3个回答

13

只需告诉git假设该文件未更改:

$ git update-index --assume-unchanged FILE [FILE ...]

来自手册:

   --assume-unchanged, --no-assume-unchanged
       When these flags are specified, the object names recorded for the paths are not updated. Instead, these options set and unset the "assume unchanged" bit for the paths. When the "assume unchanged" bit is on, git stops checking the
       working tree files for possible modifications, so you need to manually unset the bit to tell git when you change the working tree file. This is sometimes helpful when working with a big project on a filesystem that has very slow
       lstat(2) system call (e.g. cifs).

       This option can be also used as a coarse file-level mechanism to ignore uncommitted changes in tracked files (akin to what .gitignore does for untracked files). Git will fail (gracefully) in case it needs to modify this file in the
       index e.g. when merging in a commit; thus, in case the assumed-untracked file is changed upstream, you will need to handle the situation manually.

如何使用Git忽略已跟踪文件中的更改中发现


2
请注意,问题中提到此方法无法工作...自那时以来有什么变化使它现在能够工作吗? - Malvineous
@Malvineous,我误读了问题的那一部分,但显然现在它可以工作:https://gist.github.com/4564516 - François Beausoleil
对于任何想知道的人,要重新跟踪文件,请使用“--no-assume-unchanged”。 - SUPERCILEX

11

2
完美!这解决了我的问题。我在.git/info/attributes中添加了“.htaccess filter=htaccess”,然后在.git/config中添加了:[filter "htaccess"] clean = sed 's|/mypath|/dev' smudge = sed 's|/dev|/mypath'现在,.htaccess文件中对/dev/something的任何引用都会被静默地替换为/mypath/something,并在最后恢复,这意味着我甚至可以编辑文件并提交更改,而不会在存储库中得到/mypath版本! - Malvineous

2

基于Git的方法:使用一个生产分支,并将特定于生产环境的更改保留在其中。要发布到生产环境,请将您的主分支合并到生产分支。

基于部署的方法:使用工具(如Capistrano / CFEngine / ...)自动化部署过程。这有许多优点,其中之一是能够将配置与代码分开。


我目前使用基于Git的方法(带有生产分支),但每个开发人员都有自己的开发环境下的单独.htaccess文件。即使有单独的生产分支,我们仍然必须手动避免将自定义的.htaccess文件提交到主分支中。尽管这不会破坏服务器,但当它发生时会使存储库变得混乱。 - Malvineous

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接