阿里云主机折上折
  • 微信号
Current Site:Index > Ignore file configuration (.gitignore)

Ignore file configuration (.gitignore)

Author:Chuan Chen 阅读数:59949人阅读 分类: 开发工具

What is a .gitignore File

A .gitignore is a plain text file used to tell Git which files or directories should be ignored and not included in version control. This file is typically placed in the root directory of a project but can also be placed in subdirectories, where it will only affect that directory and its subdirectories.

When executing the git add command, Git checks the rules in the .gitignore file, and any matching files will not be added to the staging area. This is useful for excluding compiled files, log files, local configuration files, and more.

Basic Syntax of .gitignore Files

The .gitignore file uses simple pattern-matching rules:

  1. Blank lines or lines starting with # are ignored (# is used for comments).
  2. Standard glob pattern matching is applied.
  3. A leading slash / prevents recursion.
  4. A trailing slash / specifies a directory.
  5. An exclamation mark ! at the start negates the rule.
# Ignore all .log files
*.log

# But do not ignore important.log
!important.log

# Only ignore the TODO file in the current directory, not in subdirectories
/TODO

# Ignore all files in the build/ directory
build/

# Ignore .txt files in the doc directory but not in its subdirectories
doc/*.txt

# Ignore all .pdf files in the doc directory and its subdirectories
doc/**/*.pdf

Common File Types to Ignore

Different types of projects require ignoring different files. Here are some common examples:

Frontend Projects

# Dependency directories
node_modules/

# Build output directories
dist/
build/
out/

# Cache files
.cache/

# Environment variable files
.env
.env.local
.env.development
.env.production

# Log files
*.log
logs/

# Editor directories and files
.idea/
.vscode/
*.swp
*.swo
.DS_Store

Python Projects

# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
.hypothesis/
.pytest_cache/

Global .gitignore File

In addition to project-specific .gitignore files, you can set up a global .gitignore file that applies to all Git repositories. This is useful for ignoring files specific to your development environment, such as editor configuration files.

To set up a global .gitignore file:

git config --global core.excludesfile ~/.gitignore_global

Then add global ignore rules to ~/.gitignore_global:

# macOS
.DS_Store

# Windows
Thumbs.db
ehthumbs.db
Desktop.ini

# Linux
*~

# Editors
.idea/
.vscode/
*.swp
*.swo

Advanced Pattern Matching

.gitignore supports more complex pattern matching:

  1. ** matches directories at any level.
  2. ? matches a single character.
  3. [] matches a range of characters.
# Ignore temp files in all directories
**/temp

# Ignore all files with .tmp or .temp extensions
*.[t]?mp

# Ignore a.txt, b.txt, ..., z.txt
[a-z].txt

# Ignore all files ending with ~
*~

Handling Special Cases

Sometimes you may need to ignore all files except specific ones:

# Ignore all files in a directory
folder/*

# But do not ignore folder/important.txt
!folder/important.txt

# Also do not ignore folder/subfolder/
!folder/subfolder/

Note: If a parent directory is ignored, negation rules for its subdirectories will not take effect. For example:

# This will not work
folder/
!folder/subfolder/

# Instead, write it like this
folder/*
!folder/subfolder/

Debugging .gitignore Rules

If .gitignore rules are not working as expected, you can check them using:

git check-ignore -v <file>

For example:

git check-ignore -v node_modules/package.json

This will show which .gitignore file and which rule matched the file.

Handling Tracked Files

.gitignore only affects untracked files. If a file is already tracked by Git, it will continue to be tracked even if later added to .gitignore. To remove a file from Git tracking (while keeping it in the local file system), use:

git rm --cached <file>

For example, to stop tracking a committed config.local.js file:

git rm --cached config.local.js
git commit -m "Stop tracking config.local.js"

Example for a Multi-Language Project

Here’s an example .gitignore for a multi-language project (including frontend and backend):

# Frontend
node_modules/
dist/
build/
*.min.js
*.min.css
.sourcemaps/
.parcel-cache/

# Backend
__pycache__/
*.pyc
*.pyo
*.pyd
.env
venv/
*.sqlite3

# General
.DS_Store
.idea/
.vscode/
*.log
logs/
tmp/
*.tmp
*.bak
*.swp
*.swo

Ignoring Deleted Files

Sometimes you may need to ignore files that have been deleted to prevent them from being re-added. Add them to .gitignore:

# Ignore deleted files
deleted-file.txt
removed-folder/

Template and Generated Files

For files that are frequently generated (e.g., from templates), handle them like this:

# Ignore generated config files
config/*.generated.*
!config/*.example.*

# Ignore auto-generated documentation
docs/generated/

Platform-Specific Files

Files generated by different operating systems may require special handling:

# macOS
.DS_Store
._*

# Windows
Thumbs.db
Desktop.ini

# Linux
*~

Performance Considerations

.gitignore rules can impact Git performance, especially in large projects. Some optimization tips:

  1. Prefer specific paths over wildcards.
  2. Place frequently used rules at the top of the file.
  3. Avoid overly complex pattern matching.
  4. For large directories (e.g., node_modules), explicitly ignore the entire directory.

Version Controlling .gitignore Files

Generally, the .gitignore file itself should be version-controlled so all developers share the same ignore rules. However, sometimes personal ignore rules are needed. In such cases, use:

  1. The project's .gitignore for shared rules.
  2. The local .git/info/exclude for personal rules.

The syntax of .git/info/exclude is the same as .gitignore, but it only applies to the current repository.

Best Practices in Real Projects

  1. Create the .gitignore file when initializing the project.
  2. Choose an appropriate template based on the project type.
  3. Regularly review the .gitignore file and remove unnecessary rules.
  4. Configure appropriate ignore rules for different environments (development, testing, production).
  5. Share the .gitignore file within the team to maintain consistency.

Troubleshooting Common Issues

Issue 1: .gitignore doesn’t seem to work.

Solutions:

  1. Check if the file is already tracked by Git (git ls-files <file>).
  2. Verify the .gitignore file is in the correct location.
  3. Ensure there are no syntax errors.
  4. Check if more specific rules are overriding yours.

Issue 2: Temporarily ignoring tracked files.

Solutions:

  1. Use git update-index --assume-unchanged <file> to temporarily ignore changes.
  2. Restore with git update-index --no-assume-unchanged <file>.

Issue 3: Path separator issues across operating systems.

Solutions:

  1. Use / as the path separator in .gitignore (Git handles platform differences automatically).
  2. Avoid using \ as the path separator.

Automation Tools

Some tools can help generate and maintain .gitignore files:

  1. gitignore.io - Online tool to generate .gitignore files for various projects.
  2. git ignore command (requires git-extras).

Example using git-extras:

# Install git-extras
brew install git-extras

# Generate .gitignore for a Node.js project
git ignore node > .gitignore

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.