>_ IzzyLab

Hands-on task

This task is step 8 of the course “Git: first commits”

Keep the junk out with .gitignore

easy~6 min

After the bot was run, the /root/bot repository got files that don't belong in git: .env with a token, and logs — files with the .log extension, in the root and in the logs/ directory.

  1. Make git ignore .env and any .log files — both the existing ones and future ones, in whatever directory they show up.
  2. Commit .gitignore. Neither .env nor the logs may end up in the commit.

The new file config.py is needed by the project — git must still see it.

What you'll practise:
  • .gitignore
  • ignore patterns
  • git check-ignore

Topic breakdown

Not everything in a project directory should go into git: passwords and tokens, logs, temporary and build files. The list of what git should ignore is kept in the .gitignore file at the root of the repository. It gets committed so the rules apply to the whole team.

One rule per line. For example, a .gitignore like this:

# secrets and temporary files
secret.txt
*.tmp
build/
  • secret.txt — a file with that name in any directory;
  • *.tmp — every file that ends in .tmp;
  • build/ — the whole build directory;
  • a line that starts with # is a comment. A comment at the end of a line with a rule doesn't work: git treats it as part of the name.

Ignored files disappear from git status, and git add . skips them. To check whether a file is ignored and by which rule: git check-ignore -v path.

Important: .gitignore only affects files that aren't in any commit yet. If a secret has already been committed, the rule won't remove it from the history — that's why .gitignore is set up before the first git add ..

If a file has already made it into a commit, a rule alone isn't enough: git keeps tracking it. First you remove the file from the index — git rm --cached path (it stays on disk) — and commit that together with .gitignore. And a secret from old commits is considered leaked and gets changed.

What's checked

  1. .gitignore is committed
  2. Git ignores .env
  3. Git ignores .log files in any directory
  4. Git still sees the files the project needs
  5. .env and the logs didn't get into commits

What it looks like