0

I would like to write a script that guarantees a successful Git checkout without intervention from the user. I don't mind dumping anything that cannot be solved without user intervention: for example, uncommitted changes. I do want to keep explicitly ignored files (I consider these to be "under version control").

I made a script based on the cornucopia of answers to How do you discard unstaged changes in Git? and fixing errors I encountered over time (similar to but not exactly the same as Unstaged changes left after git --reset hard and Ignoring “Your local changes to the following files would be overwritten by merge” on pull).

I am now concerned that my piecemeal script contains redundancies, or could be shortened. Are any of the following calls redundant?

cd /SOME/FOLDER
git clean -df & git checkout .
git stash
git stash clear
git checkout SOME-BRANCH # or git checkout -B SOME-REMOTE SOME-BRANCH [1]
# possibly followed by a manual call to: git pull --rebase SOME-REMOTE

[1] Could these calls be git checkout -f and git checkout -fB?

lofidevops
  • 15,528
  • 14
  • 79
  • 119

1 Answers1

1

Here's what I use in one of my build scripts to create a clean checkout of HEAD (replace HEAD with any branch or commit that you want, or use a shell variable):

if [ $(git status --porcelain -uall | wc -l) -gt 0 ]; then
  echo "Creating pristine checkout of HEAD."
  git reset --quiet --hard HEAD
  git clean --quiet -fd
fi

The if clause checks if there is anything to be done at all. You can leave it out if you do not care about the slight increase in efficiency it might (or might not even) bring.

If you want to also remove files that are in ignore rules (.gitignore files), then you need to give the -x option to git-clean, and the --ignored option to git-status; you mentioned that you do not want that to happen.

I don't think any of the other calls that you make are necessary. Clearing the stash is not necessary (but it does not hurt, either).

Sigi
  • 1,784
  • 13
  • 19
  • I use the stash I encountered changes that could only be removed by stashing (since I don't use the stash otherwise, I cleared it afterwards) - I take it a `reset --hard ` should avoid this? – lofidevops May 06 '14 at 13:20
  • 1
    The above method definitely removes anything and everything that is not part of the HEAD commit tree (but keeps ignored files, on purpose). With the `-x` and `--ignored` options it even removes ignored files. – Sigi May 06 '14 at 14:39
  • 1
    Oh, and yes, `git reset --hard HEAD` is something else than `git checkout .` The latter checks out the index as the working copy (and keeps the index), while `reset --hard` makes sure that your working copy (and index) exactly corresponds to the given commit (the index will match the working copy then, or be empty if you will). – Sigi May 06 '14 at 14:44