How to add folder to gitignore

How to add folder to gitignore

.gitignore exclude folder but include specific subfolder

How to add folder to gitignore. Смотреть фото How to add folder to gitignore. Смотреть картинку How to add folder to gitignore. Картинка про How to add folder to gitignore. Фото How to add folder to gitignore

20 Answers 20

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

To do what you want, you have to “unignore” every parent directory of anything that you want to “unignore”. Usually you end up writing rules for this situation in pairs: ignore everything in a directory, but not some certain subdirectory.

Note
The trailing /* is significant:

Commit 59856de from Karsten Blees (kblees) for Git 1.9/2.0 (Q1 2014) clarifies that case:

gitignore.txt : clarify recursive nature of excluded directories

It is not possible to re-include a file if a parent directory of that file is excluded. ( * )
( * : unless certain conditions are met in git 2.8+, see below)
Git doesn’t list excluded directories for performance reasons, so any patterns on contained files have no effect, no matter where they are defined.

You must white-list folders first, before being able to white-list files within a given folder.

Update Feb/March 2016:

Note that with git 2.9.x/2.10 (mid 2016?), it might be possible to re-include a file if a parent directory of that file is excluded if there is no wildcard in the path re-included.

Nguyễn Thái Ngọc Duy ( pclouds ) is trying to add this feature:

So with git 2.9+, this could have actually worked, but was ultimately reverted:

How to add folder to gitignore

Setup and Config

Getting and Creating Projects

Basic Snapshotting

Branching and Merging

Sharing and Updating Projects

Inspection and Comparison

Patching

Debugging

Email

External Systems

Server Admin

Guides

Administration

Plumbing Commands

Check your version of git by running

SYNOPSIS

DESCRIPTION

A gitignore file specifies intentionally untracked files that Git should ignore. Files already tracked by Git are not affected; see the NOTES below for details.

Each line in a gitignore file specifies a pattern. When deciding whether to ignore a path, Git normally checks gitignore patterns from multiple sources, with the following order of precedence, from highest to lowest (within one level of precedence, the last matching pattern decides the outcome):

Patterns read from the command line for those commands that support them.

Which file to place a pattern in depends on how the pattern is meant to be used.

Patterns which a user wants Git to ignore in all situations (e.g., backup or temporary files generated by the user’s editor of choice) generally go into a file specified by core.excludesFile in the user’s

The underlying Git plumbing tools, such as git ls-files and git read-tree, read gitignore patterns specified by command-line options, or from files specified by command-line options. Higher-level Git tools, such as git status and git add, use patterns from the sources specified above.

PATTERN FORMAT

A blank line matches no files, so it can serve as a separator for readability.

A line starting with # serves as a comment. Put a backslash (» \ «) in front of the first hash for patterns that begin with a hash.

Trailing spaces are ignored unless they are quoted with backslash (» \ «).

If there is a separator at the end of the pattern then the pattern will only match directories, otherwise the pattern can match both files and directories.

Two consecutive asterisks (» ** «) in patterns matched against full pathname may have special meaning:

A leading » ** » followed by a slash means match in all directories. For example, » **/foo » matches file or directory » foo » anywhere, the same as pattern » foo «. » **/foo/bar » matches file or directory » bar » anywhere that is directly under directory » foo «.

A slash followed by two consecutive asterisks then a slash matches zero or more directories. For example, » a/**/b » matches » a/b «, » a/x/b «, » a/x/y/b » and so on.

Other consecutive asterisks are considered regular asterisks and will match according to the previous rules.

CONFIGURATION

NOTES

The purpose of gitignore files is to ensure that certain files not tracked by Git remain untracked.

EXAMPLES

The pattern foo/ will match a directory foo and paths underneath it, but will not match a regular file or a symbolic link foo (this is consistent with the way how pathspec works in general in Git)

Ignoring files

In this article

You can configure Git to ignore files you don’t want to check in to GitHub.

Configuring ignored files for a single repository

You can create a .gitignore file in your repository’s root directory to tell Git which files and directories to ignore when you make a commit. To share the ignore rules with other users who clone the repository, commit the .gitignore file in to your repository.

GitHub maintains an official list of recommended .gitignore files for many popular operating systems, environments, and languages in the github/gitignore public repository. You can also use gitignore.io to create a .gitignore file for your operating system, programming language, or IDE. For more information, see «github/gitignore» and the «gitignore.io» site.

Navigate to the location of your Git repository.

Create a .gitignore file for your repository.

If the command succeeds, there will be no output.

If you want to ignore a file that is already checked in, you must untrack the file before you add a rule to ignore it. From your terminal, untrack the file.

Configuring ignored files for all repositories on your computer

You can also create a global .gitignore file to define a list of rules for ignoring files in every Git repository on your computer. For example, you might create the file at

/.gitignore_global and add some rules to it.

/.gitignore_global for all Git repositories.

Excluding local files without creating a .gitignore file

If you don’t want to create a .gitignore file to share with others, you can create rules that are not committed with the repository. You can use this technique for locally-generated files that you don’t expect other users to generate, such as files created by your editor.

Use your favorite text editor to open the file called .git/info/exclude within the root of your Git repository. Any rule you add here will not be checked in, and will only ignore files for your local repository.

.gitignore

Git рассматривает каждый файл в вашей рабочей копии как файл одного из трех нижеуказанных типов.

Игнорируемые файлы — это, как правило, артефакты сборки и файлы, генерируемые машиной из исходных файлов в вашем репозитории, либо файлы, которые по какой-либо иной причине не должны попадать в коммиты. Вот некоторые распространенные примеры таких файлов:

Шаблоны игнорирования в Git

ШаблонПримеры соответствияПояснение*
**/logslogs/debug.log
logs/monday/foo.bar
build/logs/debug.log
Добавьте в начало шаблона две звездочки, чтобы сопоставлять каталоги в любом месте репозитория.
**/logs/debug.loglogs/debug.log
build/logs/debug.log
но не
logs/build/debug.log
Две звездочки можно также использовать для сопоставления файлов на основе их имени и имени родительского каталога.
*.logdebug.log
foo.log
.log
logs/debug.log
Одна звездочка — это подстановочный знак, который может соответствовать как нескольким символам, так и ни одному.
*.log
!important.log
debug.log
trace.log
но не
important.log
logs/important.log
Добавление восклицательного знака в начало шаблона отменяет действие шаблона. Если файл соответствует некоему шаблону, но при этом также соответствует отменяющему шаблону, указанному после, такой файл не будет игнорироваться.
*.log
!important/*.log
trace.*
debug.log
important/trace.log
но не
important/debug.log
Шаблоны, указанные после отменяющего шаблона, снова будут помечать файлы как игнорируемые, даже если ранее игнорирование этих файлов было отменено.
/debug.logdebug.log
но не
logs/debug.log
Косая черта перед именем файла соответствует файлу в корневом каталоге репозитория.
debug.logdebug.log
logs/debug.log
По умолчанию шаблоны соответствуют файлам, находящимся в любом каталоге
debug?.logdebug0.log
debugg.log
но не
debug10.log
Знак вопроса соответствует строго одному символу.
debug7.logdebug0.log
debug1.log
но не
debug10.log
Квадратные скобки можно также использовать для указания соответствия одному символу из заданного диапазона.
debug[01].logdebug0.log
debug1.log
но не
debug2.log
debug01.log
Квадратные скобки соответствуют одному символу из указанного набора.
debug[!01].logdebug2.log
но не
debug0.log
debug1.log
debug01.log
Восклицательный знак можно использовать для указания соответствия любому символу, кроме символов из указанного набора.
debug[a-z].logdebuga.log
debugb.log
но не
debug1.log
Диапазоны могут быть цифровыми или буквенными.
logslogs
logs/debug.log
logs/latest/foo.bar
build/logs
build/logs/debug.log
Без косой черты в конце этот шаблон будет соответствовать и файлам, и содержимому каталогов с таким именем. В примере соответствия слева игнорируются и каталоги, и файлы с именем logs
logs/logs/debug.log
logs/latest/foo.bar
build/logs/foo.bar
build/logs/latest/debug.log
Косая черта в конце шаблона означает каталог. Все содержимое любого каталога репозитория, соответствующего этому имени (включая все его файлы и подкаталоги), будет игнорироваться
logs/
!logs/important.log
logs/debug.log
logs/important.log
Минуточку! Разве файл logs/important.log из примера слева не должен быть исключен нз списка игнорируемых?

Нет! Из-за странностей Git, связанных с производительностью, вы не можете отменить игнорирование файла, которое задано шаблоном соответствия каталогу

logs/**/debug.loglogs/debug.log
logs/monday/debug.log
logs/monday/pm/debug.log
Две звездочки соответствуют множеству каталогов или ни одному.
logs/*day/debug.loglogs/monday/debug.log
logs/tuesday/debug.log
but not
logs/latest/debug.log
Подстановочные символы можно использовать и в именах каталогов.
logs/debug.loglogs/debug.log
но не
debug.log
build/logs/debug.log
Шаблоны, указывающие на файл в определенном каталоге, задаются относительно корневого каталога репозитория. (При желании можно добавить в начало косую черту, но она ни на что особо не повлияет.)

Персональные правила игнорирования в Git

Глобальные правила игнорирования в Git

Игнорирование ранее закоммиченного файла

Коммит игнорируемого файла

Этот способ хорош, если у вас задан общий шаблон (например, *.log ), но вы хотите сделать коммит определенного файла. Однако еще лучше в этом случае задать исключение из общего правила:

Этот подход более прозрачен и понятен, если вы работаете в команде.

Скрытие изменений в игнорируем файле

При желании команде git check-ignore можно передать несколько имен файлов, причем сами имена могут даже не соответствовать файлам, существующим в вашем репозитории.

Готовы изучить Git?

Ознакомьтесь с этим интерактивным обучающим руководством.

Motivation

The Truth

There is only one source of truth. The official Git documentation on gitignore : https://git-scm.com/docs/gitignore

If only people would read this before posting to Stackoverflow…

As it turns out Git does not use regex, nor wildcards, nor Ant-style syntax, but unix glob patterns (specifically those valid for fnmatch(3) ). Don’t worry, you don’t need to read the fnmatch(3) documentation, simply refer to the tables in the next sections.

The Most Important Use Cases

First things first, how can we exclude every target folder created by Maven in every sub-module?

Here is an overview of the most relevant patterns:

.gitignore entryIgnores every…
target/…folder (due to the trailing /) recursively
target…file or folder named target recursively
/target…file or folder named target in the top-most directory (due to the leading /)
/target/…folder named target in the top-most directory (leading and trailing /)
*.class…every file or folder ending with .class recursively

Advanced Use Cases

For more complicated use cases refer to the following table:

.gitignore entryIgnores every…
#comment…nothing, this is a comment (first character is a #)
\#comment…every file or folder with name #comment (\ for escaping)
target/logs/…every folder named logs which is a subdirectory of a folder named target
target/*/logs/…every folder named logs two levels under a folder named target (* doesn’t include /)
target/**/logs/…every folder named logs somewhere under a folder named target (** includes /)
*.py[co]…file or folder ending in .pyc or .pyo. However, it doesn’t match .py!
!README.mdDoesn’t ignore any README.md file even if it matches an exclude pattern, e.g. *.md.
NOTE This does not work if the file is located within a ignored folder.

Examples

Maven based Java project

Important Dot Files in Your Home Folder

Wait, There’s More

One useful file you can define yourself is a global ignore file. It doesn’t have a default location or file name. You can define it yourself with the following command:

Conclusion

As we have seen it is fairly easy to ignore files and folders for the typical use cases. Even though ignore rules don’t support regex, gitignore is highly flexible and can be adapted to more complicated project structures using unix globs and different files on different levels.

More Resources

For each and every detail on gitignore refer to these resources.

Источники информации:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *