Home > Software engineering >  Why is `git clean -xfdn` threatening to remove ~/?
Why is `git clean -xfdn` threatening to remove ~/?

Time:11-30

When switching between branches with significant differences between them, Xcode can get quite upset/confused (probably due to unversioned contents of xcuserdata).

I find that can be solved by ensuring my working copy is in a clean state:

git clean -xfd

To be confident of not unintentionally losing anything, a dry-run is a good idea:

git clean -xfdn

Right now, the alarming final line of output from the dry-run is:

Would remove ~/

The root of my working copy is a long way from my home directory. I can find no symlinks "reaching" out from my working copy to ~.

In this context, does git mean something else by ~/?

Why, from a working copy 5 directories deep, might it think ~/ needs deleting?

CodePudding user response:

When Git lists files (from git clean, or git ls-files, or other such commands), it never uses the ~/ user's-home-directory compression syntax. So if git clean -n -d other-flags-if/as-desired-here says "Would remove ~/", it means Git thinks there is a directory named ~ living in the current directory, and Git would remove it:

$ git clean -nd
Would remove Syntax.md
$ mkdir \~
$ git clean -nd
Would remove Syntax.md
Would remove ~/

Note that I had to use \~ when making this directory. I could also have used '~' or similar: it's the shell that expands ~ here. Git does have its own code to expand ~ so that you can refer to ~/.config/git-foo files in includeIf directives, for instance, but this code is applied somewhat inconsistently (basically, "wherever it should be" and not "wherever it shouldn't be", with should / should-not being a judgment call).1

You probably did not make a directory named ~, but something else apparently did.


1Because ~ expansion is performed by individual programs, and each one has its own rules about when and how ~ expansion occurs, we can get in a lot of trouble. The same applies to variables like $HOME and $USER. One of the niceties in original Unix, that has long since been lost, is that with the shell being the only place that does these special tricks, one had only to learn one set of rules about when such expansions took place, and how to prevent them. Now that so many programs take it upon themselves to do their own globbing, with each program having its own rules, it's quite a mess.

  •  Tags:  
  • git
  • Related