gitignore目录中的所有文件/子目录,但允许readme.txt

时间:2016-05-08 08:01:02

标签: git

假设这是我的目录树:

-root

--dir1

--dir2

整个树是一个Git项目,但是dir2是特殊的:目录本身必须在Git下,以及一个readme.txt来解释这个目录的用途。所有其他文件,子目录和子目录中的文件必须被gitignored。

我没有成功地累了各种各样的组合:

/dir2/!readme.txt
!/dir2/readme.txt

我该怎么做?

2 个答案:

答案 0 :(得分:1)

.gitignore文件中的条目告诉git报告更改时是否应忽略这些文件和/或目录。

您可以手动添加任何文件,与.gitignore中的条目无关。

所以,在你的情况下,你应该在.gitignore中添加dir2,然后正常添加git add dir2/readme.txt,这会将该文件导入git,让git忽略该目录中的任何其他更改。

哦,根据您进行这些更改的顺序,您可能需要在git add上添加-f标志,以强制将文件添加到git中,因为它会因为文件被覆盖而抱怨通过.gitignore设置。

答案 1 :(得分:0)

基本上,如果文件已添加到存储库中,则.gitignore不会涵盖该文件。因此,如果您(强行)将dir2/readme.txt添加到回购广告中,则会定期跟踪它,您可以将整个dir2放入.gitignore

在新创建的存储库中考虑以下操作日志:

tmp/git/repo3 $ git init   
Initialized empty Git repository in tmp/git/repo3/.git/
tmp/git/repo3 $ mkdir dir2                
tmp/git/repo3 $ touch file dir2/file
tmp/git/repo3 $ git status
On branch master                                    

Initial commit

Untracked files:
  (use "git add <file>..." to include in what will be committed)

    dir2/
    file

nothing added to commit but untracked files present (use "git add" to track)
tmp/git/repo3 $ echo "dir2/" >.gitignore
tmp/git/repo3 $ git status
On branch master

Initial commit

Untracked files:
  (use "git add <file>..." to include in what will be committed)

    .gitignore
    file

nothing added to commit but untracked files present (use "git add" to track)
tmp/git/repo3 $ git add file .gitignore
tmp/git/repo3 $ git commit -m "initial commit"
[master (root-commit) d3b1044] initial commit
 2 files changed, 1 insertion(+)       
 create mode 100644 .gitignore
 create mode 100644 file
tmp/git/repo3 $ echo "this is readme" >dir2/readme.txt
tmp/git/repo3 $ git status # now check that readme.txt isn't tracked by git status
On branch master
nothing to commit, working directory clean
tmp/git/repo3 $ git add -f dir2/readme.txt # forcibly add the ignored file
tmp/git/repo3 $ git commit -m "Readme.txt"
[master d7a034b] Readme.txt             
 1 file changed, 1 insertion(+)                          
 create mode 100644 dir2/readme.txt

tmp/git/repo3 $ echo "A change to readme" >> dir2/readme.txt # now let's change readme.txt and make sure git status notices the change
tmp/git/repo3 $ git status                 
On branch master
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)                
  (use "git checkout -- <file>..." to discard changes in working directory) 

    modified:   dir2/readme.txt                                             

no changes added to commit (use "git add" and/or "git commit -a")