Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the shortest way to swap staged and unstaged changes in git?

Tags:

git

If some changes are added to the index and there are some changes that are not added to the index, how do I swap this two sets of changes?

like image 295
whitered Avatar asked Aug 26 '10 08:08

whitered


People also ask

What is staged and unstaged changes in git?

Unstaged changes are in Git but not marked for commit. Staged changes are in Git and marked for commit.

How do you commit unstaged changes?

To unstage commits on Git, use the “git reset” command with the “–soft” option and specify the commit hash. Alternatively, if you want to unstage your last commit, you can the “HEAD” notation in order to revert it easily. Using the “–soft” argument, changes are kept in your working directory and index.

Can file appear as both staged and unstaged in git?

@zerkms yes, but if you change which parts of the file are staged/unstaged, it does that in "hunks" which seem to be one or more lines for text files.


2 Answers

For a lower-level solution, you can use a bit of plumbing to talk directly to the index:

INDEXTREE=`git write-tree` git add -A WORKTREE=`git write-tree` git checkout $INDEXTREE -- . git clean -f git read-tree $WORKTREE 

What that does is build a couple of temporary tree objects in the git store, one for the index and one for the working copy. Then, it restores the old index and checks it out into the working tree. Finally. it resets the index to the version representing the old working tree.

I haven't tested this, so I'm not sure how well it handles added files in either the index or the working tree.

like image 25
Walter Mundt Avatar answered Sep 19 '22 16:09

Walter Mundt


It think that this is easiest to do with temporary commits. When you have staged and unstaged commits, you have the possibility of conflicts when trying to reorder the changes.

Make a commit with the staged changes, create a branch for later use:

git commit -m "Saved staged" git branch save-staged 

Make a commit with the unstaged changes (if the unstaged changes include new files you may need to explicitly git add them first):

git commit -a -m "Unstaged changes" 

Rebase the unstaged changes onto the original HEAD (may involve conflict resolution):

git rebase --onto HEAD^^ HEAD^ 

Rebase the staged changes onto the unstaged changes (may involve conflict resolution):

git reset --hard save-staged git rebase --onto HEAD@{1} HEAD^ 

Finally, reset the index to the (originally) unstaged changes:

git reset HEAD^ 

And move the branch pointer back to the original HEAD:

git reset --soft HEAD^ 

Removed temporary branch:

git branch -D save-staged 
like image 140
CB Bailey Avatar answered Sep 17 '22 16:09

CB Bailey