Home > Software design >  Temporarily Checkout Revision and then Restore Repository State
Temporarily Checkout Revision and then Restore Repository State

Time:08-16

Summary

I am working on a script. As a part of this script, I need to programmatically

  1. Checkout some git revision
  2. Do some read-only operations from this revision
  3. Restore the repo state to how it was before the program started (i.e., check out whatever revision I was on originally).

I'm imagine each of these steps would involve some set of git commands. I ideally want there to be no side affects from these three operations -- i.e., step 3 should restore all local changes and the repository is in the same state.

What I've Tried So Far

This almost works:

git stash --include-untracked
git name-rev --name-only HEAD # Save to <HEAD_REV>
git checkout <NEW_REV>

# Do stuff 

git checkout <HEAD_REV>
git stash pop

This mostly works, but I'm not sure if there are some edge states where it will fail to restore the repository state. Can anyone more experienced in git tell me if there's a gold-standard way to do this?

CodePudding user response:

One way to get a throwaway checkout is to use git worktree :

git worktree add --detach ../tmpworktree <new_rev>
cd ../tmpworktree

# work work ...

cd ../repo
git worktree remove ../tmpworktree

CodePudding user response:

1 you should consider running git clean -f after doing stuff.

2 I learned recently that you can run git checkout - to go back to where you were before (very much like git checkout HEAD@{1} but more powerful because it will checkout a branch if that is where you were before). Analog mechanism to cd -. Gotta love it!!! <3

  •  Tags:  
  • git
  • Related