git clean exclude with regex

1.3k views Asked by At

I'd like to find a regex-way of using git clean.

Without regex:

git clean -dfx --exclude=".idea/"

With regex (tried; not working):

git clean -dfx --exclude='(.*\/)*(\.idea\/.*)(.*)'
git clean -dfx --exclude="(.*\/)*(\.idea\/.*)(.*)"
git clean -dfx --exclude=r'(.*\/)*(\.idea\/.*)(.*)'
git clean -dfx --exclude=r"(.*\/)*(\.idea\/.*)(.*)"

How do you use git clean with regex?

1

There are 1 answers

1
AnimiVulpis On

git clean has no support for regular expressions.


A workaround would be something like this:

$ git clean -n | cut -f3 -d' ' | grep -v -E --color=never '<PATTERN>' | ifne git clean

Breakdown of things happening here:

  • git clean -n produces a list of files that would be removed if git clean would be executed (you can use flags like -d, -x or -X here too)
    • -n dry-run (do not actually do anything)
  • cut -f3 -d' ' cuts the third field from those matches (delimited by an whitespace)
    • -f3 third field
    • -d' ' use whitespace as the delimiter
  • grep -v -E --color=never '<PATTERN>'
    • -v invert the matches from grep
    • -E interpret PATTERN as an extended regular expression
    • color=never to prevent colored grep output to mess with the following commands (may be omitted)
    • '<PATTERN>' a regular expression
  • ifne git clean will pipe the file list (if there are files) to git clean
    • ifne a utility function from moreutils (installable via homebrew or other package managers)
    • git clean will take this list and clean the files (use -n first to make sure no files get removed that you did not expect)

That is the magic of small command line programs each doing a simple specific task