06. Inspecting a Repository

The history in Git is the complete list of all commits made since the repository was created. The history also contains references to any branches, merges, and tags made within the repository.

Status

The git status command displays the state of the working directory and the staging area. It lets you see which changes have been staged, which haven’t, and which files aren’t being tracked by Git.

Status output does not show you any information regarding the committed project history.

  • On branch...

  • Changes to be committed:

  • Changes not staged for commit:

  • Untracked files:

git status
git status -s # short output

Logging

The git log command displays committed snapshots. It lets you list the project history, filter it, and search for specific changes.

git log показывает историю коммитов:

  • -<limit> - показать <limit> число последних коммитов

  • --oneline - сокращенная запись вывода

  • -p показывает изменения в коммитах

  • --stat - показывает статистику для каждого коммита

  • --pretty=online|short|full|fuller|format:%h

  • --graph - рисует ASCII график коммитов

  • --relative-date - показывает относительную дату коммита, а не абсолютную

  • --name-status - показывает список измененных файлов с информацией о добавлении/изменении и удалении.

  • --since/--until/--after - задает время отсчета истории (2.weeks, 2008-01-15, 2.years.)

  • --author="<pattern>"/--commiter - поиск коммитов определенного автора

  • --grep="<pattern>" --all-match - grep позволяет искать по ключевым словам, а --all-match задает поиск по всем им.

  • --decorate - показывает имена веток над последними коммитами в этих ветках

  • --abbrev-commit - показывать сокращенные хэши коммитов

  • путь - путь указывается последним и выводит только те коммиты, которые связаны с измененными файлами в этой директории

git log <file> # show commits only affecting specified <file>
git log --since=2.weeks
git log --graph --decorate --oneline

git log master..branch # показать все коммиты, которые есть в branch но нет в master
git log branch --not master # то же самое

git diff master...branch # показать только те наработки, которые появились в ветке branch после расхождения с master
git log origin/master..HEAD # все коммиты в текущей ветке, отсутствующие в ветке origin/master

Advanced Logging

Запись master..branch - вычислит разницу между branch и master: покажет какие коммиты есть в branch, но нет в master. Запись branch..master делает обратную операцию.

Запись git log branch1 ^branch2 или git log branch1 --not branch2 покажет все коммиты, которые есть в ветке branch1, но не в ветке branch2.

Запись master...branch показывает коммиты которые есть или в одной ветке, или в другой, но не в обоих одновременно. С этой командой часто используют параметр --left-right, позволяющий посмотреть, с какой стороны диапазона находится каждый коммит.

git grep "<text>"
git clean -n

Show

The git show command is really useful for presenting any of the objects in a very human readable format.

  • Running this command on a file will simply output the contents of the file.

  • Running it on a tree will just give you the filenames of the contents of that tree, but none of its subtrees.

  • If you call it on a tree that is a commit object, you will get simple information about the commit.

git show master@{yesterday}
git show HEAD^ # показать предыдущий коммит относительно HEAD

Команда git describe branch возвращает имя последнего тега, плюс число сделанных поверх него коммитов и хеш код, например v1.6.2-rc1-20-g8c5b85c.

Diffing

If you simply run git diff with no arguments, it will show you the differences between your current working directory and your index, that is, the last time you ran ‘git add’ on your files.

By default diff show difference for:

  • Working directory

  • Last commit

git diff # show diff only for changed files
git diff --stat # short diff
git diff --cached # compare staging area with last commit
git diff HEAD # compare working area and staged area with the last commit
git diff --staged # show diff only for staged files

git diff <branch> # show diff between current branch and specified branch

git diff <branch>...<master> # show all difference between branch and master.
git config --global diff.indentHeuristic true

The default output of the git diff command is a valid patch file. If you pipe the output into a file and email it to someone, they can apply it with the patch command: git diff master..experiment > experiment.patch.

git blame

Показывает кто и когда модифицировал файл последний раз.

git shortlog

The git shortlog command is a special version of git log intended for creating release announcements. It groups each commit by author and displays the first line of each commit message. This is an easy way to see who is been working on what.

git shortlog -since="last week"
git shortlog -s -n --all # number of commits per author on all branches

Other commands

  • git rev-parse показывает по имени коммита в какой ветке он находится

  • git reflog возвращает список изменений HEAD для текущей ветки (историю изменения HEAD во времени в вашем репозитории).

  • git bisect позволяет в интерактивном режиме выполнять двоичный поиск по истории коммитов.

Last updated