问题
I want to modify the index of one (text) file without having to change the working tree file state. Is this possible?
回答1:
Another take on "changing file in index without altering working dir" is to apply a patch to index only. This is often the way GUI git clients stage only selected lines from a given file.
You start out by (if you want) clearing out the changes from index for that file:
git reset path/to/file
Then extracting the full patch for it
git diff path/to/file > /path/to/tmpfile
Edit the patch file to include only the changes you want to apply, and apply just the edited patch:
git apply --cached /path/to/tmpfile
See:
git help apply
回答2:
yes, you can use the --work-tree option on the git level of any (this is not actually true. It should work on any but there are edge cases) command:
git show HEAD:path/to/your/file.txt > /some/other/place/file.txt
# modify the file in /some/other/place/file.txt
git --work-tree=/some/other/place add /some/other/place/file.txt
回答3:
Yes, you can explicitly stage a blob at a particular path with git update-index
.
git update-index --cacheinfo 100644 <sha1-of-blob> path/in/repo
You will also need to use --add
if the path is a branch new file.
If the file that you want to stage is a blob that doesn't yet exist in the git repository then you can store a new blob in the git repository with git hash-object
, e.g.:
blobid=$(command_that_creates_output | git hash-object -w --stdin)
or
blobid=$(git hash-object -w /path/not/necessarily/in/repository)
You can then stage the blob as above.
git update-index --cacheinfo 100644 blobid path/in/repo
来源:https://stackoverflow.com/questions/8580277/git-ability-to-stage-a-certain-file-content-without-touching-the-working-tree