0

I think many reps have certain files with some sensitive information like a hash key, specific env variables or some machine specific configuration that are user related and not to be committed. Is there a way to switch between branches without having to stage, stash and unstash those changes every time and without having to add those files to .gitignore?

Andre GolFe
  • 300
  • 5
  • 12
  • 3
    Do not store sensitive data in a Git repository, if at all possible. If you must, do not make this Git repository available to anyone else. (Note that your *working tree* is not actually *in* the repository, so it's safe, given appropriate *other* precautions, to store such files in the working tree: just don't *add* them to the repository!) – torek Aug 25 '21 at 21:28
  • 1
    https://stackoverflow.com/a/22171275/7976758, https://stackoverflow.com/a/1976900/7976758 – phd Aug 25 '21 at 22:01

1 Answers1

1

In general, this is an instance of the generic question, “How do I ignore changes to a tracked file?” and it's answered in the Git FAQ:

Git doesn’t provide a way to do this. The reason is that if Git needs to overwrite this file, such as during a checkout, it doesn’t know whether the changes to the file are precious and should be kept, or whether they are irrelevant and can safely be destroyed. Therefore, it has to take the safe route and always preserve them.

It’s tempting to try to use certain features of git update-index, namely the assume-unchanged and skip-worktree bits, but these don’t work properly for this purpose and shouldn’t be used this way.

If your goal is to modify a configuration file, it can often be helpful to have a file checked into the repository which is a template or set of defaults which can then be copied alongside and modified as appropriate. This second, modified file is usually ignored to prevent accidentally committing it.

The approach to using a template and ignoring the actual configuration file here is especially helpful since you definitely don't someone thoughtlessly doing a git add -u and then accidentally committing their secrets. In this particular case, you might do well with an ignored file that lets the user specify all their secrets and then generating the configuration file based on that file and the template.

Also note that you should avoid storing sensitive data in a Git repository. It's very common that a repository or some of the files in it accidentally leak (laptop theft, server misconfiguration, etc.), and if your secrets aren't in the repository, then they won't be exposed. You should inject this data from the environment using an appropriate secret store, which most CI systems have. If you need to use a configuration file, you can use the template and generation script mentioned above to take that data from the environment and use it for your configuration file.

bk2204
  • 64,793
  • 6
  • 84
  • 100