Make .gitignore ignore everything except a few files

前端 未结 23 2896
无人共我
无人共我 2020-11-22 00:14

I understand that a .gitignore file cloaks specified files from Git\'s version control. I have a project (LaTeX) that generates lots of extra files (.auth, .dvi, .pdf, logs,

23条回答
  •  [愿得一人]
    2020-11-22 00:54

    I know I am late for the party,but here's my answer.

    As @Joakim said, to ignore a file, you can use something like below.

    # Ignore everything
    *
    
    # But not these files...
    !.gitignore
    !someFile.txt
    

    but if the file is with in nested directories, it's little bit hard to manually write the rules.

    For example, if we want to skip all files in a git project, but not a.txt which is located in aDir/anotherDir/someOtherDir/aDir/bDir/cDir. Then, our .gitignore will be something like this

    # Skip all files
    *
    
    # But not `aDir/anotherDir/someOtherDir/aDir/bDir/cDir/a.txt`
    !aDir/
    aDir/*
    !aDir/anotherDir/
    aDir/anotherDir/*
    !aDir/anotherDir/someOtherDir/
    aDir/anotherDir/someOtherDir/*
    !aDir/anotherDir/someOtherDir/aDir/
    aDir/anotherDir/someOtherDir/aDir/*
    !aDir/anotherDir/someOtherDir/aDir/bDir/
    aDir/anotherDir/someOtherDir/aDir/bDir/*
    !aDir/anotherDir/someOtherDir/aDir/bDir/cDir/
    aDir/anotherDir/someOtherDir/aDir/bDir/cDir/*
    !aDir/anotherDir/someOtherDir/aDir/bDir/cDir/a.txt
    

    The above given .gitignore file will skip all dirs and files except !aDir/anotherDir/someOtherDir/aDir/bDir/cDir/a.txt

    As you may have noted, it's hard to define those rules.

    To solve this hurdle, I've created a simple console application named git-do-not-ignore which will generate the rules for you. I've hosted the project in github with detailed instruction.

    Usage Example

    java -jar git-do-not-ignore.jar "aDir/anotherDir/someOtherDir/aDir/bDir/cDir/a.txt"
    

    Output

    !aDir/
    aDir/*
    !aDir/anotherDir/
    aDir/anotherDir/*
    !aDir/anotherDir/someOtherDir/
    aDir/anotherDir/someOtherDir/*
    !aDir/anotherDir/someOtherDir/aDir/
    aDir/anotherDir/someOtherDir/aDir/*
    !aDir/anotherDir/someOtherDir/aDir/bDir/
    aDir/anotherDir/someOtherDir/aDir/bDir/*
    !aDir/anotherDir/someOtherDir/aDir/bDir/cDir/
    aDir/anotherDir/someOtherDir/aDir/bDir/cDir/*
    !aDir/anotherDir/someOtherDir/aDir/bDir/cDir/a.txt
    

    There's also a simple web version available here

    Thank you.

提交回复
热议问题