はんなりと、ゆるやかに

アジャイル、スクラムが好きが日々から学んだことをアウトプット

意外と知らない? git clean のオプションについて調べた

gitで追跡されていないファイルを再帰的に消したいけど、消せない場合があってgit cleanを調べました。
git cleanとはgitで追跡されていないファイルを削除するコマンド です。

公式ドキュメントはこちら

Git - git-clean Documentation

git clean に関する設定

git clean は-i-n-f いずれかのオプションを指定しないと使うことができません。
clean.requireForce の設定をデフォルトのtrueからfalseに変更することでオプションなしで使うこともできますが、変更する必要もないかなと思います。
変更したい場合は以下のコマンドを実行しましょう。

git config --local clean.requireForce false

今回調べたオプション

-n

消す予定のファイルを確認することができる

-f

上記にも書きましたが、clean.requireForceがデフォルト(true)の場合は、このオプションを指定しないと削除できません。

-d

追跡されていないディレクトリも削除対象に含まれます。

-x

gitignore に設定した無視ファイルも含めて削除します。

-X

gitignore に設定した無視ファイルだけを削除します。

オプションの違いでどう変わるか見てみます

確認するフォルダ構成は以下の感じです。
cleanから始まるファイル名は追跡されていないファイルです。
また、*.mdは.gitignoreで無視ファイルに設定しています。

root/
 ├ test1/
 │ ├ test2/
 │ │  ├ test2.txt
 │ │  ├ clean2.txt
 │ │  └ clean2.md
 │ ├ test3/
 │ │  ├ clean3.txt
 │ │  └ clean3.md
 │ │  
 │ ├ test1.txt
 │ ├ clean1.txt
 │ └ clean1.md
 ├ top.txt
 ├ clean.txt
 └ clean.md

git clean -f

Removing clean.txt
Removing test1/clean1.txt
Removing test1/test2/clean2.txt

無視ファイルと追跡されているファイルがないディレクトリ内(test3)は削除されませんでした。

git clean -xf

Removing clean.md
Removing clean.txt
Removing test1/clean1.md
Removing test1/clean1.txt
Removing test1/test2/clean2.md
Removing test1/test2/clean2.txt

無視ファイルは削除されましたが、追跡されているファイルがないディレクトリ内(test3)は削除されませんでした。

git clean -Xf

Removing clean.md
Removing test1/clean1.md
Removing test1/test2/clean2.md

無視ファイルのみが削除されましたが、追跡されているファイルがないディレクトリ内(test3)は削除されませんでした。

git clean -df

Removing clean.txt
Removing test1/clean1.txt
Removing test1/test2/clean2.txt
Removing test1/test3/clean3.txt

無視ファイルは削除されませんが、追跡されているファイルがないディレクトリ内(test3)のファイルも削除されました。

git clean -dxf

Removing clean.md
Removing clean.txt
Removing test1/clean1.md
Removing test1/clean1.txt
Removing test1/test2/clean2.md
Removing test1/test2/clean2.txt
Removing test1/test3/

追跡されているファイル以外すべてが削除されました。

git clean -dXf

Removing clean.md
Removing test1/clean1.md
Removing test1/test2/clean2.md
Removing test1/test3/clean3.md

無視ファイルだけが削除されました。

git clean -ndxf

Would remove clean.md
Would remove clean.txt
Would remove test1/clean1.md
Would remove test1/clean1.txt
Would remove test1/test2/clean2.md
Would remove test1/test2/clean2.txt
Would remove test1/test3/

オプションのnを付けると削除するファイル一覧が確認できるので、状況に応じて実行前に安全確認したほうが良いでしょう。

まとめ

追跡外のファイルを再帰的に消したいけど、消せないファイルがあってgit cleanを調べました。
僕の場合は追跡外ファイルしか含まれていないディレクトリが消せなかったのでgit clean -dfで消せることが分かりました。