Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get a local git checkout to reflect precisely a known remote commit and nothing more?

Tags:

git

What is a canonical sequence of git commands to get a local git checkout to precisely reflect the HEAD of a remote branch, with all files up-to-date, and nothing more in the checkout directory? Effectively I am trying to simulate having freshly cloned a repository, but without the network-intensiveness that might require.

My best approximation so far is:

cd <the git directory>
git reset --hard HEAD
git clean -f -d -x
git fetch --prune
git checkout <the git branch name I want>
git pull --rebase

Are any of my steps unnecessary, or are there any I am missing?

(as an aside, the reason I want to do this is as part of an automated build system - I want to guarantee the build is working off a precise pristine copy, but cloning is very slow, so I'd like to just request fresh changes.

like image 745
Andrew Ferrier Avatar asked Nov 01 '25 17:11

Andrew Ferrier


1 Answers

You should only need:

git fetch
git checkout <branch>
git reset --hard origin/<branch>
git clean -dxf

This represents:

  • Syncing remote tracking branches with the remote
  • Switch context to the branch you want.
  • Reset that branch to the state on the remote repository.
  • Remove any non source controlled files, including those that fall under the .gitignore

Pruning is mostly likely unnecessary, though it will protect you against setting yourself to a state that no longer exists on the remote. If that sounds useful, the fetch can be run with the --prune flag. A pull is unnecessary since you can reference the remote tracking branches directly using the origin/{branch} syntax.

EDIT:

If it's a possibility that <branch> has been modified inbetween runs of these commands, you may end up with changes in your working tree that prevent you from checking out the branch in step 2. If that happens, you can either git stash or git reset --hard to either save your changes or wipe them completely before checking out the branch.

like image 87
joshtkling Avatar answered Nov 03 '25 08:11

joshtkling



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!