Удалённые ветки
Удалённые ссылки — это ссылки (указатели) в ваших удалённых репозиториях, включая ветки, теги и так далее. Полный список удалённых ссылок можно получить с помощью команды git ls-remote или команды git remote show для получения удалённых веток и дополнительной информации. Тем не менее, более распространенным способом является использование веток слежения.
Ветки слежения — это ссылки на определённое состояние удалённых веток. Это локальные ветки, которые нельзя перемещать; Git перемещает их автоматически при любой коммуникации с удаленным репозиторием, чтобы гарантировать точное соответствие с ним. Представляйте их как закладки для напоминания о том, где ветки в удалённых репозиториях находились во время последнего подключения к ним.
Для синхронизации ваших изменений с удаленным сервером выполните команду git fetch (в нашем случае git fetch origin ). Эта команда определяет какому серверу соответствует «origin» (в нашем случае это git.ourcompany.com ), извлекает оттуда данные, которых у вас ещё нет, и обновляет локальную базу данных, сдвигая указатель origin/master на новую позицию.
Отправка изменений
Когда вы хотите поделиться веткой, вам необходимо отправить её на удалённый сервер, где у вас есть права на запись. Ваши локальные ветки автоматически не синхронизируются с удалёнными при отправке — вам нужно явно указать те ветки, которые вы хотите отправить. Таким образом, вы можете использовать свои личные ветки для работы, которую не хотите показывать, а отправлять только те тематические ветки, над которыми вы хотите работать с кем-то совместно.
Если вы используете HTTPS URL для отправки изменений, Git-сервер будет спрашивать имя пользователя и пароль для аутентификации. По умолчанию вам будет предложено ввести эти данные в терминале, чтобы сервер мог определить разрешена ли вам отправка изменений.
Для получения более подробной информации о различных вариантах кэша учётных данных обратитесь к разделу Хранилище учётных данных.
В следующий раз, когда один из ваших соавторов будет получать обновления с сервера, он получит ссылку на то, на что указывает serverfix на сервере, как удалённую ветку origin/serverfix :
Отслеживание веток
В действительности, это настолько распространённая команда, что существует сокращение для этого сокращения. Если вы пытаетесь извлечь ветку, которая не существует, но существует только одна удалённая ветка с точно таким же именем, то Git автоматически создаст ветку слежения:
Чтобы создать локальную ветку с именем, отличным от имени удалённой ветки, просто укажите другое имя:
Важно отметить, что эти цифры описывают состояние на момент последнего получения данных с каждого из серверов. Эта команда не обращается к серверам, а лишь говорит вам о том, какая информация с этих серверов сохранена в локальном кэше. Если вы хотите иметь актуальную информацию об этих числах, вам необходимо получить данные со всех ваших удалённых серверов перед запуском команды. Сделать это можно вот так:
Получение изменений
Удаление веток на удалённом сервере
Всё, что делает эта строка — удаляет указатель на сервере. Как правило, Git сервер хранит данные пока не запустится сборщик мусора, поэтому если ветка была удалена случайно, чаще всего её легко восстановить.
Git checkout
Переключение веток аналогично переключению старых коммитов и файлов, в которых рабочий каталог обновляется в соответствии с выбранной веткой/ревизией; вместе с тем новые изменения сохраняются в истории проекта, то есть это не просто операция чтения.
Переключение веток
Наличие выделенной ветки для каждой новой функции сильно отличается от традиционного рабочего процесса в SVN. Это значительно облегчает проведение новых экспериментов без страха разрушить существующую функциональность и позволяет одновременно работать со множеством несвязанных функций. Кроме того, ветки облегчают ведение нескольких совместных рабочих процессов.
Использование: существующие ветки
В вышеприведенном примере показано, как просмотреть список доступных веток с помощью команды git branch и переключиться на конкретную ветку (в данном случае — на ветку feature_inprogress_branch ).
Новые ветки
Переключение веток
Переключение на удаленную ветку
При совместной работе команды нередко используют удаленные репозитории. Такие репозитории могут размещаться на сервере с предоставлением общего доступа либо это может быть локальная копия другого коллеги. Каждый удаленный репозиторий содержит собственный набор веток. Для переключения на удаленную ветку нужно сначала извлечь содержимое этой ветки.
В современных версиях Git переключение на удаленную ветку не отличается от переключения на локальную ветку.
В старых версиях Git необходимо создавать новую ветку на основе удаленного репозитория ( remote ).
Кроме того, можно переключиться на новую локальную ветку и сбросить ее до последнего коммита удаленной ветки.
Открепленные указатели HEAD
Резюме
Готовы попробовать ветвление?
Ознакомьтесь с этим интерактивным обучающим руководством.
Git checkout track что это
Check your version of git by running
SYNOPSIS
DESCRIPTION
Updates files in the working tree to match the version in the index or the specified tree. If no pathspec was given, git checkout will also update HEAD to set the specified branch as the current branch.
To prepare for working on
, switch to it by updating the index and the files in the working tree, and by pointing HEAD at the branch. Local modifications to the files in the working tree are kept, so that they can be committed to the
.
You could omit
, in which case the command degenerates to «check out the current branch», which is a glorified no-op with rather expensive side-effects to show only the tracking information, if exists, for the current branch.
that is to say, the branch is not reset/created unless «git checkout» is successful.
Omitting
detaches HEAD at the tip of the current branch.
Overwrite the contents of the files that match the pathspec. When the
OPTIONS
Quiet, suppress feedback messages.
When checking out paths from the index, do not fail upon unmerged entries; instead, unmerged entries are ignored.
When checking out paths from the index, check out stage #2 (ours) or #3 (theirs) for unmerged paths.
This is because rebase is used in a workflow that treats the history at the remote as the shared canonical one, and treats the work done on the branch you are rebasing as the third-party work to be integrated, and you are temporarily assuming the role of the keeper of the canonical history during the rebase. As the keeper of the canonical history, you need to view the history from the remote as ours (i.e. «our shared canonical history»), while what you did on your side branch as theirs (i.e. «one contributor’s work on top of it»).
Create a new branch named and start it at ; see git-branch[1] for details.
When creating a new branch, set up «upstream» configuration. See «—track» in git-branch[1] for details.
Do not set up «upstream» configuration, even if the branch.autoSetupMerge configuration variable is true.
If
is not found but there does exist a tracking branch in exactly one remote (call it ) with a matching name, treat as equivalent to
If the branch exists in multiple remotes and one of them is named by the checkout.defaultRemote configuration variable, we’ll use that one for the purposes of disambiguation, even if the
isn’t unique across all remotes. Set it to e.g. checkout.defaultRemote=origin to always checkout remote branches from there if
is ambiguous but exists on the origin remote. See also checkout.defaultRemote in git-config[1].
The default behavior can be set via the checkout.guess configuration variable.
Create the new branch’s reflog; see git-branch[1] for details.
Rather than checking out a branch to work on it, check out a commit for inspection and discardable experiments. This is the default behavior of git checkout when is not a branch name. See the «DETACHED HEAD» section below for details.
This can be useful when you want to publish the tree from a commit without exposing its full history. You might want to do this to publish an open source branch of a project whose current tree is «clean», but whose full history contains proprietary or otherwise encumbered bits of code.
would update only entries matched by
When switching branches, if you have local modifications to one or more files that are different between the current branch and the branch to which you are switching, the command refuses to switch branches in order to preserve your modifications in context. However, with this option, a three-way merge between the current branch, your working tree contents, and the new branch is done, and you will be on the new branch.
When a merge conflict happens, the index entries for conflicting paths are left unmerged, and you need to resolve the conflicts and mark the resolved paths with git add (or git rm if the merge should result in deletion of the path).
When checking out paths from the index, this option lets you recreate the conflicted merge in the specified paths.
Interactively select hunks in the difference between the
git checkout refuses when the wanted ref is already checked out by another worktree. This option makes it check the ref out anyway. In other words, the ref can be held by more than one worktree.
Branch to checkout; if it refers to a branch (i.e., a name that, when prepended with «refs/heads/», is a valid ref), then that branch is checked out. Otherwise, if it refers to a valid commit, your HEAD becomes «detached» and you are no longer on any branch (see below for details).
Name for the new branch.
Tree to checkout from (when paths are given). If not specified, the index will be used.
Do not interpret any more arguments as options.
Limits the paths affected by the operation.
For more details, see the pathspec entry in gitglossary[7].
DETACHED HEAD
HEAD normally refers to a named branch (e.g. master ). Meanwhile, each branch refers to a specific commit. Let’s look at a repo with three commits, one of them tagged, and with branch master checked out:
It is sometimes useful to be able to checkout a commit that is not at the tip of any named branch, or even to create a new commit that is not referenced by a named branch. Let’s look at what happens when we checkout commit b (here we show two ways this may be done):
In fact, we can perform all the normal Git operations. But, let’s look at what happens when we then checkout master :
ARGUMENT DISAMBIGUATION
if you want to checkout these paths out of the index.
EXAMPLES
The following sequence checks out the master branch, reverts the Makefile to two revisions back, deletes hello.c by mistake, and gets it back from the index.
take a file out of another commit
restore hello.c from the index
If you want to check out all C source files out of the index, you can say
After working in the wrong branch, switching to the correct branch would be done using:
However, your «wrong» branch and correct mytopic branch may differ in files that you have modified locally, in which case the above checkout would fail like this:
After this three-way merge, the local modifications are not registered in your index file, so git diff would show you what changes you made since the tip of the new branch.
At this point, git diff shows the changes cleanly merged as in the previous example, as well as the changes in the conflicted files. Edit and resolve the conflict and mark it resolved with git add as usual:
Шпаргалка по Git
Шпаргалка по Git
Как выписать репозиторий с github
Как выписать ветку с github
С помощью команды «checkout» можно выписать уже существующую ветку с github:
Или так, что намного надежнее:
Если команда не сработала, нужно попробовать выполнить обновление:
Если вышеприведенные команды не сработали, выдали ошибку, и времени разбираться с ней нет, можно попробовать получить нужную ветку следующим способом:
Т.е. сначала мы создаем новую ветку, а затем вливаем в нее изменения из ветки на github.
Как создать новую ветку в локальном репозитории
2. Публикуем ее на github:
Как переключиться на другую ветку в git
Если вы случайно удалили какой-то файл, можно извлечь его из хранилища:
Как посмотреть список веток
Команда «branch» позволяет посмотреть список веток в локальном репозитории. Текущая ветка будет помечена звездочкой:
Как сделать commit
Создаем новую ветку, выполняем в ней нужные изменения.
2. Подготавливаем коммит, добавляя в него файлы командой:
Или удаляем устаревшие файлы:
3. Выполняем коммит:
4. Как правило, в репозитории существует две основные ветки — dev и master. Dev — общая ветка разработчиков и тестировщиков. Именно в нее добавляются все новые разработки перед очередным релизом. Master — ветка для выкладки продукта на боевые сервера.
После коммита надо влить в нашу ветку изменения из ветки dev и master:
Теперь наша ветка содержит изменения для проекта, и все последние изменения по другим задачам, которые успела внести команда.
5. Переключаемся на ветку dev:
6. Вливаем в dev изменения из ветки проекта:
7. Заливаем последнюю версию ветки dev на удаленный сервер:
push может не пройти, потому что удалённый origin/dev обогнал локальную его копию.
Как решить конфликт бинарных файлов
Допустим, при слиянии с другой веткой git выдал ошибку. Команда git status возвращает информацию о конфликте:
Конфликтный файл является бинарным (это могут быть архивные файлы, изображения и т.п.), и решение конфликта стандартным способом, с помощью редактирования — не возможно.
Чтобы решить такой конфликт, надо просто выбрать — какая версия файла будет использоваться: ваша или из вливаемой ветки. Чтобы использовать свой вариант файла, вводим команду:
Если мы выбираем версию из вливаемой ветки:
« ours » — от английского «наш», « theirs » — от английского «их».
Как посмотреть историю изменений
git log — просмотр логов.
Вывод данных о каждом коммите в одну строку:
Для вывода информации git log использует просмотрщик, указанный в конфиге репозитория.
Поиск по ключевому слову в комментариях к коммиту:
Команда «git show» позволяет просмотреть, какие именно изменения произошли в указанном коммите:
Можно посмотреть построчную информацию о последнем коммите, имя автора и хэш коммита:
git annotate, выводит измененные строки и информацию о коммитах, где это произошло:
Как сделать откат
Можно откатить до последней версии ветки:
После того, как откат сделан, и выполнен очередной локальный коммит, при попытке сделать push в удаленный репозиторий, git может начать ругаться, что версия вашей ветки младше чем на github и вам надо сделать pull. Это лечится принудительным коммитом:
Как выполнить слияние с другой веткой
git merge выполняет слияние текущей и указанной ветки. Изменения добавляются в текущую ветку.
git pull забирает изменения из ветки на удаленном сервере и проводит слияние с активной веткой.
git pull отличается от git merge тем, что merge только выполняет слияние веток, а pull прежде чем выполнить слияние — закачивает изменения с удаленного сервера. merge удобно использовать для слияния веток в локальном репозитории, pull — слияния веток, когда одна из них лежит на github.
Создание нового локального репозитория
git cherry-pick
git cherry-pick помогает применить один-единственный коммит из одной ветки к дереву другой.
3. Выполнить команду, указать код коммита:
4. После этого обновить ветку на сервере:
Как раскрасить команды git
Чтобы раскрасить вывод git, можно добавить в файл блок [color] :
git clone
clone the repository specified by ; this is similar to «checkout» in
some other version control systems such as Subversion and CVS
Add colors to your
[color] ui = auto
[color «branch»] current = yellow reverse
local = yellow
remote = green
[color «diff»] meta = yellow bold
frag = magenta bold
old = red bold
new = green bold
[color «status»] added = yellow
changed = green
untracked = cyan
Highlight whitespace in diffs
[color] ui = true
[color «diff»] whitespace = red reverse
[core] whitespace=fix,-indent-with-non-tab,trailing-space,cr-at-eol
Add aliases to your
git config —global user.name ‘John Doe’
git config —global user.email [email protected]
sets your name and email for commit messages
git config branch.autosetupmerge true
tells git-branch and git-checkout to setup new branches so that git-pull(1)
will appropriately merge from that remote branch. Recommended. Without this,
you will have to add —track to your branch command or manually merge remote
tracking branches with «fetch» and then «merge».
git config core.autocrlf true
This setting tells git to convert the newlines to the system’s standard
when checking out files, and to LF newlines when committing in
git config —list
To view all options
git config apply.whitespace nowarn
To ignore whitespace
You can add «—global» after «git config» to any of these commands to make it
apply to all git repos (writes to
Info
—-
git reflog
Use this to recover from *major* mess ups! It’s basically a log of the
last few actions and you might have luck and find old commits that
have been lost by doing a complex merge.
git diff
show a diff of the changes made since your last commit
to diff one file: «git diff — »
to show a diff between staging area and HEAD: `git diff —cached`
git status
show files added to the staging area, files with changes, and untracked files
git log
show recent commits, most recent on top. Useful options:
—color with color
—graph with an ASCII-art commit graph on the left
—decorate with branch and tag names on appropriate commits
—stat with stats (files changed, insertions, and deletions)
-p with full diffs
—author=foo only by a certain author
—after=»MMM DD YYYY» ex. («Jun 20 2008″) only commits after a certain date
—before=»MMM DD YYYY» only commits that occur before a certain date
—merge only the commits involved in the current merge conflicts
also to show the contents of a file at a specific revision, use
git show :
this is similar to cat-file but much simpler syntax.
git show —name-only
show only the names of the files that changed, no diff information.
git blame
show who authored each line in
git blame
show who authored each line in as of (allows blame to go back in
time)
git gui blame
really nice GUI interface to git blame
git diff head path/to/fubar
show the diff between a file on the current branch and potentially another branch
git diff —cached [ ] shows diff for staged (git-add’ed) files (which includes uncommitted git cherry-pick’ed files)
git ls-files
list all files in the index and under version control.
git ls-remote [HEAD] show the current version on the remote repo. This can be used to check whether
a local is required by comparing the local head revision.
git add
add all files under directory to the project, including subdirectories
Either way you need to add patterns to exclude to these files.
git reset HEAD …
remove the specified files from the next commit
git commit —amend
edit the commit message of the most recent commit
git branch
list all local branches
create a new branch named
, referencing the same point in history as
the current branch
git push :refs/heads/
create a new remote branch named
, referencing on the
remote. Repo is the name of the remote.
Example: git push origin origin:refs/heads/branch-1
Example: git push origin origin/branch-1:refs/heads/branch-2
Example: git push origin branch-1 ## shortcut
git branch —track
create a tracking branch. Will push/pull changes to/from another repository.
Example: git branch —track experimental origin/experimental
git branch —set-upstream
(As of Git 1.7.0)
Make an existing branch track a remote branch
Example: git branch —set-upstream foo origin/foo
delete the branch
; if the branch you are deleting points to a
commit which is not reachable from the current branch, this command
will fail with a warning.
even if the branch points to a commit not reachable from the current branch,
you may know that that commit is still reachable from some other branch or
tag. In that case it is safe to use this command to force git to delete the
branch.
make the current branch
, updating the working directory to reflect
the version referenced by
removes a branch from a remote repository.
Example: git push origin :old_branch_to_be_deleted
Checkout a file from another branch and add it to this branch. File
will still need to be added to the git branch, but it’s present.
Eg. git co remote_at_origin__tick702_antifraud_blocking …./…nt_elements_for_iframe_blocked_page.rb
Eg. git show remote_tick702 — path/to/fubar.txt
show the contents of a file that was created on another branch and that
does not exist on the current branch.
git show :
Show the contents of a file at the specific revision. Note: path has to be
absolute within the repo.
merge branch
into the current branch; this command is idempotent
and can be run as many times as needed to keep the current branch
up-to-date with changes in
git merge
—no-commit
merge branch
into the current branch, but do not autocommit the
result; allows you to make further tweaks
git merge
-s ours
merge branch
into the current branch, but drops any changes in
, using the current tree as the new tree
git cherry-pick [—edit] [-n] [-m parent-number] [-s] [-x]
selectively merge a single commit from another local branch
Example: git cherry-pick 7300a6130d9447e18a931e898b64eefedea19544
git hash-object
get the blob of some file whether it is in a repository or not
Find the commit in the repository that contains the file blob:
Squashing
———
WARNING: «git rebase» changes history. Be careful. Google it.
git rebase —interactive HEAD
10
(then change all but the first «pick» to «squash»)
squash the last 10 commits into one big commit
git mergetool
work through conflicted files by opening them in your mergetool (opendiff,
kdiff3, etc.) and choosing left/right chunks. The merged result is staged for
commit.
For binary files or if mergetool won’t do, resolve the conflict(s) manually
and then do:
Once all conflicts are resolved and staged, commit the pending merge with:
git fetch
update the remote-tracking branches for (defaults to «origin»).
Does not initiate a merge into the current branch (see «git pull» below).
git push
update the server with your commits across all branches that are *COMMON*
between your local copy and the server. Local branches that were never
pushed to the server in the first place are not shared.
update the server with your commits made to
since your last push.
This is always *required* for new branches that you wish to share. After
the first explicit push, «git push» by itself is sufficient.
git push origin
:refs/heads/
E.g. git push origin twitter-experiment:refs/heads/twitter-experiment
Which, in fact, is the same as git push origin
but a little
more obvious what is happening.
git revert
reverse commit specified by and commit the result. This does *not* do
the same thing as similarly named commands in other VCS’s such as «svn
revert» or «bzr revert», see below
Fix mistakes / Undo
——————-
git reset —hard
abandon everything since your last commit; this command can be DANGEROUS.
If merging has resulted in conflicts and you’d like to just forget about
the merge, this command will do that.
git reset —hard ORIG_HEAD or git reset —hard origin/master
undo your most recent *successful* merge *and* any changes that occurred
after. Useful for forgetting about the merge you just did. If there are
conflicts (the merge was not successful), use «git reset —hard» (above)
instead.
git reset —soft HEAD^
forgot something in your last commit? That’s easy to fix. Undo your last
commit, but keep the changes in the staging area for editing.
git commit —amend
redo previous commit, including changes you’ve staged in the meantime.
Also used to edit commit message of previous commit.
git stash
git stash save
save your local modifications to a new stash (so you can for example
«git svn rebase» or «git pull»)
git stash apply
restore the changes recorded in the stash on top of the current working tree
state
git stash pop
restore the changes from the most recent stash, and remove it from the stack
of stashed changes
git stash list
list all current stashes
git stash drop [ ] delete the stash
git stash clear
delete all current stashes
git remote add
adds a remote repository to your git config. Can be then fetched locally.
Example:
git remote add coreteam git://github.com/wycats/merb-plugins.git
git fetch coreteam
git push :refs/heads/
delete a branch in a remote repository
git push :refs/heads/
create a branch on a remote repository
Example: git push origin origin:refs/heads/new_feature_name
git push + :
replace a branch with
think twice before do this
Example: git push origin +master:my_branch
git remote show
show information about the remote server.
git push
For branches that are remotely tracked (via git push) but
that complain about non-fast forward commits when doing a
git push. The pull synchronizes local and remote, and if
all goes well, the result is pushable.
git fetch
Retrieves all branches from the remote repository. After
this ‘git branch —track …’ can be used to track a branch
from the new remote.
add the given repository at the given path. The addition will be part of the
next commit.
git submodule update [—init] Update the registered submodules (clone missing submodules, and checkout
the commit specified by the super-repo). —init is needed the first time.
git submodule foreach
Executes the given command within each checked out submodule.
Updating submodules
To update a submodule to a new commit:
1. update submodule:
cd
git pull
2. commit the new version of submodule:
cd
git format-patch HEAD^
Generate the last commit as a patch that can be applied on another
clone (or branch) using ‘git am’. Format patch can also generate a
patch for all commits using ‘git format-patch HEAD^ HEAD’
All page files will be enumerated with a prefix, e.g. 0001 is the
first patch.
git format-patch ^..
Generate a patch for a single commit. E.g.
git format-patch d8efce43099^..d8efce43099
Revision does not need to be fully specified.
Applies the patch file generated by format-patch.
git archive master | bzip2 > source-tree.tar.bz2
Will export archive as bz2
git archive —format zip —output /full/path master
Will export as zip
git instaweb —httpd=webrick [—start | —stop | —restart]
GIT_DIR
Location of the repository to use (for out of working directory repositories)
GIT_WORKING_TREE
Location of the Working Directory — use with GIT_DIR to specifiy the working directory root
or to work without being in the working directory at all.
Change author for all commits with given name
git filter-branch —commit-filter ‘
if [ «$GIT_COMMITTER_NAME» = «
» ];
then
GIT_COMMITTER_NAME=» »;
GIT_AUTHOR_NAME=» »;
GIT_COMMITTER_EMAIL=» »;
GIT_AUTHOR_EMAIL=» »;
git commit-tree «[email protected]»;
else
git commit-tree «[email protected]»;
fi’ HEAD








