Ignore specific changes to a file in git, but not the entire file

前端 未结 9 1786
春和景丽
春和景丽 2020-12-28 12:14

I have a file in a git repository that has a local change on it. I want to have git ignore the local change forever, but not the file. In particular,

  • If the fi
相关标签:
9条回答
  • 2020-12-28 12:45

    These answers are good, but may not best solve @Kevin's problem. I had a similar concern, often editing a config file so the app I was working on would access my own private development database instead of the production one. It's only a matter of time before I accidentally check in and push those config changes! I just needed a light weight way to ignore a file. Here's what I learned:

    • First, make your needed change to your file. I'll call it my_config.

    • Make a patch file of that change with git diff >../somewhere-else/my_config.patch

    • Now tell git to ignore that file (without having to change the checked-in .gitignore): git update-index --assume-unchanged my_config

    Now, as long as you don't make changes to my_config that you do want to check in, you can work freely. To stop ignoring my_config, do git update-index --no-assume-unchanged my_config. After pulling in somebody else's changes to my_config, you can easily restore your private change with git apply ../somewhere-else/my_config.patch, then ...assume-unchanged again, as above, and get back to work!

    Here are some helpful aliases you can put in your ~/.gitconfig:

    [alias]
        unchanged = update-index --assume-unchanged
        changed = update-index --no-assume-unchanged
        show-unchanged = !"git ls-files -v | sed -e 's/^[a-z] //p; d'"
    
    0 讨论(0)
  • 2020-12-28 12:45

    If you happen to be using intellij as your IDE, then it has a neat feature (changelists) that I believe does exactly what OP is requesting.

    You can mark and name a specific part of your local diff. If memory serves, this will keep those changes separate from all other local modifications and will only be staged for commit if you actively choose to do so - so long as you do your committing from intellij.

    0 讨论(0)
  • 2020-12-28 12:46

    As of Git 2.5 (July 2015), you can use git worktree:

    git worktree add -b patch-1 ../patch-1
    

    This is essentially just creating a branch, but it puts the new branch into a new folder alongside the parent repo. This is nice because you can do work on this branch, even without committing, then switch back to master with a clean working directory.

    0 讨论(0)
提交回复
热议问题