.gitignoreで特定のディレクトリだけを許可する方法

Gitを使用していると、プロジェクトの中で特定のファイルやディレクトリを無視したり、管理したりする必要があります。public_htmlディレクトリの中にある特定のサブディレクトリだけをGitで管理したい場合、.gitignoreを使って細かく制御することができます。

例えば、public_htmlディレクトリ内で、public_html/wp-content/themes/my-theme/だけをGitで管理したい場合、次のように.gitignoreを設定します。

1. ディレクトリ構成例

/my-project

├── .gitignore
└── public_html/ ←このディレクトリ以下は除外したい
    ├── wp-content/
    │   ├── themes/
    │   │   ├── my-theme/ ←ただしこのディレクトリは許可したい
    │   │   └── other-theme/
    │   ├── plugins/
    │   └── uploads/
    ├── index.php
    ├── contact.php
    └── about.php

2. .gitignore設定例

# public_html以下のすべてを無視
/public_html/*

# wp-contentディレクトリだけはGitで管理する
!/public_html/wp-content/

# wp-content以下は除外するが、themesディレクトリは管理
/public_html/wp-content/*
!/public_html/wp-content/themes/

# themes以下は除外するが、my-themeだけを管理
/public_html/wp-content/themes/*
!/public_html/wp-content/themes/my-theme/

3. 設定の詳細

  • /public_html/*
    public_htmlディレクトリ内のすべてのファイルとサブディレクトリを除外します。
  • !/public_html/wp-content/
    wp-contentディレクトリはGitに含めるように設定します。
  • /public_html/wp-content/*
    wp-contentディレクトリ内のすべてのファイルやサブディレクトリを除外します。
  • !/public_html/wp-content/themes/
    wp-content/themes/ディレクトリもGitで管理するようにします。
  • /public_html/wp-content/themes/*
    themesディレクトリ内のすべてのテーマを除外します。
  • !/public_html/wp-content/themes/my-theme/
    最後に、my-themeディレクトリだけをGitで管理するように設定します。

4. 期待される挙動

この設定により、以下のような挙動が実現されます:

  • public_html/ディレクトリ内のすべてのファイルとサブディレクトリはGitで管理されません。
  • ただし、public_html/wp-content/ディレクトリはGitで管理されます。
  • さらに、wp-content/themes/ディレクトリはGitに含められます。
  • その中でも、wp-content/themes/my-theme/ディレクトリだけがGitで管理され、他のテーマやファイルは除外されます。

これで、public_html内で特定のディレクトリだけをGitに含め、他は除外することができます。

このように.gitignoreを使うことで、必要なディレクトリだけをGitで管理することができます。特に大きなディレクトリ構成の中で、特定の部分だけを管理したい場合に非常に便利な方