Skip to content

Часто используемые трюки и советы при работе с Git

License

Notifications You must be signed in to change notification settings

Andrey-Kovinjonok/git-tips

This branch is 17 commits behind Imangazaliev/git-tips:master.

Folders and files

NameName
Last commit message
Last commit date
Feb 15, 2017
Feb 15, 2017
Feb 13, 2017
Feb 13, 2017
Feb 15, 2017
Feb 15, 2017
Feb 13, 2017
Feb 15, 2017

Repository files navigation

Git Tips

Часто используемые трюки и советы при работе с Git.

Хотите дополнить список? Ознакомьтесь с contributing.md

English | 中文 | Русский

Tools:

  • git-tip - консольная утилита, облегчающая использование всех этих команд. Docker-контейнер можно найти здесь

P.S: Все эти команды были проверены в git version 2.7.4 (Apple Git-66)

Branch

Commit

Config

Diff

Log

Stash

Tags

Разное

Создать новую ветку и переключиться на нее

git checkout -b <branch-name>

Alternatives:

git branch <branch-name> && git checkout <branch-name>

Быстрое переключение на предыдущую ветку

git checkout -

Список локальных и удаленных веток

git branch -a

Список веток в удаленном репозитории

git branch -r

Показать все ветки (в том числе и удаленные ветки), а так же последний коммит в них

git branch -vv

Переименовать ветку

git branch -m <new-branch-name>

Alternatives:

git branch -m [<old-branch-name>] <new-branch-name>

Удалить локальную ветку

git branch -d <local_branchname>

Удалить ветку в удаленном репозитории

git push origin --delete <remote_branchname>

Alternatives:

git push origin :<remote_branchname>

Показать список веток, которые уже слиты с веткой master

git branch --merged master

Удалить ветки, которые уже слиты с master

git branch --merged master | grep -v '^\*' | xargs -n 1 git branch -d

Alternatives:

git branch --merged master | grep -v '^\*\|  master' | xargs -n 1 git branch -d # will not delete master if master is not checked out

Найти ветки, которые содержат коммит с указанным хешем

git branch -a --contains <commit-ish>

Alternatives:

git branch --contains <commit-ish>

Track upstream branch

git branch -u origin/mybranch

Изменить сообщение последнего коммита

git commit --amend

Изменить предыдущий коммит без изменения сообщения к коммиту

git commit --amend --no-edit

Исправить имя автора последнего коммита

git commit --amend --no-edit --author='Author Name <[email protected]>'

Reset author, after author has been changed in the global config

git commit --amend --reset-author --no-edit

Создать коммит только с указанными файлами

git commit --only <file_path>

Сделать коммит, обойдя хуки pre-commit и commit-msg

git commit --no-verify

Отметить коммит как исправление к указанному коммиту

git commit --fixup <SHA-1>

Показать конфиг и все псевдонимы (alias)

git config --list

Изменить локальный/глобальный конфиг git

git config [--global] --edit

Изменить текстовый редактор

git config --global core.editor '$EDITOR'

Игнорировать изменения прав доступа на файлы при коммите

git config core.fileMode false

Сделать git чувствительным к регистру

git config --global core.ignorecase false

Включить автоматическое исправление опечаток

git config --global help.autocorrect 1

Отключить цветной вывод Git

git config --global color.ui false

Specific color settings

git config --global <specific command e.g branch, diff> <true, false or always>

Удалить запись из глобального конфига

git config --global --unset <entry-name>

Reuse recorded resolution, record and reuse previous conflicts resolutions

git config --global rerere.enabled 1

Всегда выполнять перемещение вместо слияния при получении изменений из удаленного репозитория

git config --global pull.rebase true

Alternatives:

#git < 1.7.9
git config --global branch.autosetuprebase always

Псевдонимы (alias) для команд Git

git config --global alias.<handle> <command> 
git config --global alias.st status

Показать изменения с момента последнего коммита

git diff

Показать все изменения (для файлов которых нет в индексе и которые уже там)

git diff HEAD

Изменения в файлах, которые находятся в индексе

git diff --cached

Alternatives:

git diff --staged

Показывать изменения в одну строку

git diff --word-diff

Показать список конфликтующих файлов

git diff --name-only --diff-filter=U

Открыть все конфликтующие файлы в редакторе

git diff --name-only | uniq | xargs $EDITOR

Список всех файлов, которые были изменены в коммите

git diff-tree --no-commit-id --name-only -r <commit-ish>

Показать логи за определенный период (от-до)

git log --since='FEB 1 2017' --until='FEB 14 2017'

Показать историю коммитов, сгрупировав их по имени автора

git shortlog

Показать историю коммитов, исключив коммиты указанного автора

git log --perl-regexp --author='^((?!excluded-author-regex).*)

Показать коммиты и изменения в них для определенного файла (даже если он был переименован)

git log --follow -p -- <file_path>

List only the root and merge commits

git log --first-parent

Показать незапушенные коммиты

git log --branches --not --remotes

Alternatives:

git log @{u}..
git cherry -v

Показать все коммиты с момента отделения от ветки master

git log --no-merges --stat --reverse master..

Коммиты в ветке Branch1, которых нет в Branch2

git log Branch1 ^Branch2

Показать GPG-сигнатуру в истории коммитов

git log --show-signature

Показать количество строк, которое добавил/удалил пользователь

git log --author='_Your_Name_Here_' --pretty=tformat: --numstat | gawk '{ add += <!-- @doxie.inject start -->; subs += <!-- @doxie.inject end -->; loc += <!-- @doxie.inject start --> - <!-- @doxie.inject end --> } END { printf "added lines: %s removed lines: %s total lines: %s
", add, subs, loc }' -

Alternatives:

git log --author='_Your_Name_Here_' --pretty=tformat: --numstat | awk '{ add += <!-- @doxie.inject start -->; subs += <!-- @doxie.inject end -->; loc += <!-- @doxie.inject start --> - <!-- @doxie.inject end --> } END { printf "added lines: %s, removed lines: %s, total lines: %s
", add, subs, loc }' - # on Mac OSX

Search Commit log across all branches for given text

git log --all --grep='<given-text>'

Показать все заметки (git notes)

git log --show-notes='*'

Показать дерево тегов (версий)

git log --pretty=oneline --graph --decorate --all

Alternatives:

gitk --all

Get first commit in a branch (from master)

git log master..<branch-name> --oneline | tail -1

Спрятать текущие изменения для отслеживаемых файлов

git stash

Alternatives:

git stash save

Спрятать текущие изменения, включая неотслеживаемые файлы

git stash save -u

Alternatives:

git stash save --include-untracked

Показать список спрятанных изменений

git stash list

Применить последние спрятанные изменения и удалить их из стека

git stash pop

Alternatives:

git stash apply stash@{0} && git stash drop stash@{0}

Применить последние спрятанные изменения без удаления их из стека

git stash apply <stash@{n}>

Очистить stash

git stash clear

Alternatives:

git stash drop <stash@{n}>

Удалить тег в локальном репозитории

git tag -d <tag-name>

Удалить тег в удаленном репозитории

git push origin :refs/tags/<tag-name>

Everyday Git in twenty commands or so

git help everyday

Show helpful guides that come with Git

git help -g

Клонировать отдельную ветку

git clone -b <branch-name> --single-branch https://github.com/user/repo.git

Клонировать репозиторий с указаным количеством коммитов

git clone https://github.com/user/repo.git --depth 1

Импортировать пакет в репозиторий

git clone repo.bundle <repo-dir> -b <branch-name>

Alias: git undo

git config --global alias.undo '!f() { git reset --hard $(git rev-parse --abbrev-ref HEAD)@{${1-1}}; }; f'

Получить данные из удаленного репозитория и сбросить состояние текущей ветки к ним

git fetch --all && git reset --hard origin/master

Prunes references to remote branches that have been deleted in the remote

git fetch -p

Alternatives:

git remote prune origin

Загрузить пулл-реквест в текущую ветку по ID

git fetch origin pull/<id>/head:<branch-name>

Alternatives:

git pull origin pull/<id>/head:<branch-name>

Specific fetch reference

git fetch origin master:refs/remotes/origin/mymaster

List of all files till a commit

git ls-tree --name-only -r <commit-ish>

Git reset first commit

git update-ref -d HEAD

Показать самый последний тег на текущей ветке

git describe --tags --abbrev=0

Revert: отменить коммит с помощью нового коммита

git revert <commit-ish>

Revert: отменить слияние (merge) с помощью нового коммита

git revert -m 1 <commit-ish>

Reset: Discard commits, advised for private branch

git reset <commit-ish>

Удалить файл из индекса

git reset HEAD <file-name>

Показать историю коммитов только для текущей ветки

git cherry -v master

Показать список удаленных репозиториев

git remote

Alternatives:

git remote show

Изменить URL удаленного репозитория

git remote set-url origin <URL>

List references in a remote repository

git ls-remote git://git.kernel.org/pub/scm/git/git.git

Добавить удаленный репозиторий

git remote add <remote-nickname> <remote-url>

Добавить в индекс часть файла

git add -p

Автокомплит Git-команд в bash

curl http://git.io/vfhol > ~/.git-completion.bash && echo '[ -f ~/.git-completion.bash ] && . ~/.git-completion.bash' >> ~/.bashrc

Изменения за указанный промежуток времени

git log --no-merges --raw --since='2 weeks ago'

Alternatives:

git whatchanged --since='2 weeks ago'

Перенести коммиты из одной ветки в другую с помощью cherry-pick

git checkout <branch-name> && git cherry-pick <commit-ish>

Извлечь отдельный файл из stash

git checkout <stash@{n}> -- <file_path>

Alternatives:

git checkout stash@{0} -- <file_path>

Undo local changes with the last content in head

git checkout -- <file_name>

Создать новую ветку без родительской ветки

git checkout --orphan <branch_name>

Показать все ветки, не слитые в master

git checkout master && git branch --no-merged

Показать все отслеживаемы файлы

git ls-files -t

Показать все неотслеживаемые файлы

git ls-files --others

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

git ls-files --others -i --exclude-standard

Create new working tree from a repository (git 2.5)

git worktree add -b <branch-name> <path> <start-point>

Create new working tree from HEAD state

git worktree add --detach <path> HEAD

Не отслеживать файлы (без удаления)

git rm --cached <file_path>

Alternatives:

git rm --cached -r <directory_path>

Before deleting untracked files/directory, do a dry run to get the list of these files/directories

git clean -n

Принудительно удалить неотслеживаемые файлы

git clean -f

Принудительно удалить неотслеживаемую директорию

git clean -f -d

Alternatives:

git clean -df

Обновить все субмодули

git submodule foreach git pull

Alternatives:

git submodule update --init --recursive
git submodule update --remote

Показать коммиты текущей ветки, которые будут слиты в мастер

git cherry -v master

Alternatives:

git cherry -v master <branch-to-be-merged>

Переместить ветку 'feature' на 'master' и слить ее в мастер

git rebase master feature && git checkout master && git merge -

Архивировать ветку master

git archive master --format=zip --output=master.zip

Retrieve the commit hash of the initial revision

 git rev-list --reverse HEAD | head -1

Alternatives:

git rev-list --max-parents=0 HEAD
git log --pretty=oneline | tail -1 | cut -c 1-40
git log --pretty=oneline --reverse | head -1 | cut -c 1-40

Deploying git tracked subfolder to gh-pages

git subtree push --prefix subfolder_name origin gh-pages

Adding a project to repo using subtree

git subtree add --prefix=<directory_name>/<project_name> --squash [email protected]:<username>/<project_name>.git master

Get latest changes in your repo for a linked project using subtree

git subtree pull --prefix=<directory_name>/<project_name> --squash [email protected]:<username>/<project_name>.git master

Эспортировать ветку в файл (создать пакет)

git bundle create <file> <branch-name>

Показать название текущей ветки

git rev-parse --abbrev-ref HEAD

Ignore one file on commit (e.g. Changelog)

git update-index --assume-unchanged Changelog; git commit -a; git update-index --no-assume-unchanged Changelog

Спрятать изменения перед выполнением перемещения

git rebase --autostash

Show changes using common diff tools

git difftool -t <commit1> <commit2> <path>

Don’t consider changes for tracked file

git update-index --assume-unchanged <file_name>

Undo assume-unchanged

git update-index --no-assume-unchanged <file_name>

Удалить все файлы, которые находятся в .gitignore

git clean -X -f

Восстановить удаленный файл

git checkout <deleting_commit>^ -- <file_path>

Restore file to a specific commit-hash

git checkout <commit-ish> -- <file_path>

Check if the change was a part of a release

git name-rev --name-only <SHA-1>

Dry run (any command that supports dry-run flag should do)

git clean -fd --dry-run

Squash fixup commits normal commits

git rebase -i --autosquash

Интерактивное добавление файлов в индекс

git add -i

Показать список игнорируемых файлов

git check-ignore *

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

git status --ignored

Count unpacked number of objects and their disk consumption

git count-objects --human-readable

Prune all unreachable objects from the object database

git gc --prune=now --aggressive

Instantly browse your working repository in gitweb

git instaweb [--local] [--httpd=<httpd>] [--port=<port>] [--browser=<browser>]

Получить файл из другой ветки

git show <branch_name>:<file_name>

Изменить коммиты в интерактивном режиме

git rebase --interactive HEAD~2

Поиск коммита с багом при помощи бинарного поиска

git bisect start                    # Search start 
git bisect bad                      # Set point to bad commit 
git bisect good v2.6.13-rc2         # Set point to good commit|tag 
git bisect bad                      # Say current state is bad 
git bisect good                     # Say current state is good 
git bisect reset                    # Finish search 

Показать все локальные ветки, отсортировав их по дате изменения

git for-each-ref --sort=-committerdate --format='%(refname:short)' refs/heads/

Find lines matching the pattern (regex or string) in tracked files

git grep --heading --line-number 'foo bar'

Отправить коммиты в удаленный репозиторий, перезаписав историю (force push)

git push -f <remote-name> <branch-name>

Forced push but still ensure you don't overwrite other's work

git push --force-with-lease <remote-name> <branch-name>

Количество коммитов в ветке

git rev-list --count <branch-name>

Добавить заметку

git notes add -m 'Note on the previous commit....'

Apply commit from another repository

git --git-dir=<source-dir>/.git format-patch -k -1 --stdout <SHA1> | git am -3 -k

Найти общего предка двух веток

diff -u <(git rev-list --first-parent BranchA) <(git rev-list --first-parent BranchB) | sed -ne 's/^ //p' | head -1

Показывает автора, время и хеш-коммита последнего изменения для каждой строки файла

git blame <file-name>

Показывает автора, время и хеш-коммита последнего изменения для указанного диапазона строк

git blame -L <start>,<end>

Show a Git logical variable

git var -l | <variable>

Preformatted patch file

git format-patch -M upstream..topic

Показать название репозитория

git rev-parse --show-toplevel

Generates a summary of pending changes

git request-pull v1.0 https://git.ko.xz/project master:for-linus

Сделать резервную копию неотслеживаемых файлов

git ls-files --others -i --exclude-standard | xargs zip untracked.zip

About

Часто используемые трюки и советы при работе с Git

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • JavaScript 100.0%