たとえば、以下のようなプロジェクトがあったとします。
$ ls -1Fa
.git/
.gitignore
README.md
assets/
dist/
hogehoge.log
index.html
node_modules/
package-lock.json
package.json
public/
src/
tarコマンドで、
$ tar -czf /tmp/backup.tar.gz .
としてしまうと、不要なnode_modulesディレクトリやログ、生成物(dist)も含めてアーカイブされてしまいます。
$ tar -tf /tmp/backup.tar.gz
./
./node_modules/
./node_modules/xxxxxx/
./node_modules/xxxxxx/yyyyy
:
:
:
:
./package-lock.json
./src/
:
:
./.gitignore
./package.json
./README.md
./.git/
:
:
./dist/
:
:
./assets/
:
:
./hogehoge.log
./public/
:
:
./index.html
tarコマンドには除外オプションがあり、不要なファイルは.gitignoreに定義されているので、組み合わせることができないかと調べてみたところ、tarオプションにすでに組み込まれていました。(2014年リリースのバージョン1.28で追加)
GNU tar 1.34 より
‘–exclude-vcs-ignores’
Before archiving a directory, see if it contains any of the following files: ‘cvsignore’, ‘.gitignore’, ‘.bzrignore’, or ‘.hgignore’. If so, read ignore patterns from these files. The patterns are treated much as the corresponding VCS would treat them, i.e.:
オプションをつけて実行してみると、.gitignoreに登録しているファイルフォルダを除外してアーカイブされます。
.gitignoreの中身
$ cat .gitignore
node_modules
*.log
dist
$ tar -czf /tmp/backup.tar.gz --exclude-vcs-ignores .
$ tar -tf /tmp/backup.tar.gz
./
./package-lock.json
./src/
:
:
./.gitignore
./package.json
./README.md
./.git/
:
:
./assets/
:
:
./public/
:
:
./index.html
.gitignoreのフォーマットに従って除外されるので、.gitkeepなどの一部Git管理下に置いているものも除外されるようです。
ディレクトリ構造
test/
test/.gitkeep
test/sampledir/
test/sample.txt
testディレクトリのうち.gitkeepはgit addで登録済み
.gitignoreの中身
test/*
tarコマンドでアーカイブ
# オプションなし
$ tar -czf /tmp/backup.tar.gz .
$ tar -tf /tmp/backup.tar.gz |grep test
./test/
./test/.gitkeep
./test/test1/
./test/sample2.txt
# オプションあり
$ tar -czf /tmp/backup.tar.gz --exclude-vcs-ignores .
$ tar -tf /tmp/backup.tar.gz |grep test
./test/