質問

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?

役に立ちましたか?

解決

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).

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top