Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
739 views
in Technique[技术] by (71.8m points)

git - Stash changes to specific files

I have a large git project that I, stupidly, imported to eclipse and ran an autoformat on. Now, every file in the project is showing as modified. Rather than commit my formatted files, I would rather revert all the files that I have only been formatted and not had other changes. For instance:

$ git status
# On branch master
# Changes not staged for commit:
#   (use "git add <file>..." to update what will be committed)
#   (use "git checkout -- <file>..." to discard changes in working directory)
#   (commit or discard the untracked or modified content in submodules)

#     modified: dir/file1.cpp
#     modified: dir/file1.h
#     modified: dir/file2.cpp
#     modified: dir/file2.h
#     modified: dir/file3.cpp
#     modified: dir/file3.h
#     modified: dir/file4.cpp
#     modified: dir/file4.h

I know that file2.cpp, file2.h, and file3.cpp have been modified with content (i.e., not just formatted). I want to stash the changes to these three files and then checkout an old revision, so that I can reapply the changes to these files after. I would rather avoid something like:

$ cp file2.cpp ~/tmp
$ git checkout blahblahblah
$ cp ~/tmp/file2.cpp .

If there's an obvious way to do this that doesnt involve stashing, let me know. whatever gets the job done.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can add the files with changes you want to keep, then stash the rest of the files and clear the stash:

git add file2.cpp file2.h file3.cpp
git stash --keep-index

At this point, you've stashed your unwanted changes. If you'd like to permanently get rid of them, run:

git stash drop

Now you have file2.cpp, file2.h, and file3.cpp staged for commit. If you then want to stash these files (and not commit them):

git reset
git stash

Now you'll be at your previous commit, with only those three files stashed.

Update:

Git 2.13 and later includes a more direct way to stash specific files with git stash push, as VonC explains in his answer.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...