mjs
mjs

Reputation: 65313

How to make working tree exactly match HEAD? (including removing untracked files)

git reset --hard HEAD reverts any changes made to files in the working tree so that they match head. However, it doesn't touch untracked files. git clean -df removes all untracked local files and directories.

Is there an easy way to make tracked files match HEAD, and also remove untracked files, that works in all circumstances?

(You can't run the two commands one after the other, because git reset --hard HEAD fails if the repository has no commits. There's probably some way to check whether the reset is necessary, but I imagine it's fiddly.)

I think this is an equivalent question: how can I make my working tree identical[*] to the result of a fresh git clone of the repository?

[*] I'm happy for ignored files to be untouched.

Upvotes: 2

Views: 267

Answers (1)

Yuval Adam
Yuval Adam

Reputation: 165232

There is no single command for this, but can be achieved like you mentioned using:

git reset --hard HEAD && git clean -fdx

in succession. This might not work for empty repositories, but empty repositories aren't exactly first-class citizens in git (i.e. cloning an empty repo will yield a warning).

If you must have this work for empty repos, simple flip the commands:

git clean -fdx && git reset --hard HEAD

clean should run in any case, and the reset can fail without consequence.

Upvotes: 1

Related Questions