]> git.phdru.name Git - git-wiki.git/blob - git-wiki.txt
Explain that git interprets aliases literally
[git-wiki.git] / git-wiki.txt
1 #format rst
2
3 Abstract
4 ========
5
6 This page (it was PEP 103) collects information about git. There is, of
7 course, a lot of documentation for git, so the PEP concentrates on
8 more complex (and more related to Python development) issues,
9 scenarios and examples.
10
11
12 Documentation
13 =============
14
15 Git is accompanied with a lot of documentation, both online and
16 offline.
17
18
19 Documentation for starters
20 --------------------------
21
22 Git Tutorial: `part 1
23 <https://www.kernel.org/pub/software/scm/git/docs/gittutorial.html>`_,
24 `part 2
25 <https://www.kernel.org/pub/software/scm/git/docs/gittutorial-2.html>`_.
26
27 `Git User's manual
28 <https://www.kernel.org/pub/software/scm/git/docs/user-manual.html>`_.
29 `Everyday GIT With 20 Commands Or So
30 <https://www.kernel.org/pub/software/scm/git/docs/giteveryday.html>`_.
31 `Git workflows
32 <https://www.kernel.org/pub/software/scm/git/docs/gitworkflows.html>`_.
33
34
35 Advanced documentation
36 ----------------------
37
38 `Git Magic
39 <http://www-cs-students.stanford.edu/~blynn/gitmagic/index.html>`_,
40 with a number of translations.
41
42 `Pro Git <https://git-scm.com/book>`_. The Book about git. Buy it at
43 Amazon or download in PDF, mobi, or ePub form. It has translations to
44 many different languages. Download Russian translation from `GArik
45 <https://github.com/GArik/progit/wiki>`_.
46
47 `Git Wiki <https://git.wiki.kernel.org/index.php/Main_Page>`_.
48
49 `Git Buch <http://gitbu.ch/index.html>`_ (German).
50
51
52 Offline documentation
53 ---------------------
54
55 Git has builtin help: run ``git help $TOPIC``. For example, run
56 ``git help git`` or ``git help help``.
57
58
59 Quick start
60 ===========
61
62 Download and installation
63 -------------------------
64
65 Unix users: `download and install using your package manager
66 <https://git-scm.com/download/linux>`_.
67
68 Microsoft Windows: download `git-for-windows
69 <https://github.com/git-for-windows/git/releases>`_.
70
71 MacOS X: use git installed with `XCode
72 <https://developer.apple.com/xcode/>`_ or download from `MacPorts
73 <https://www.macports.org/ports.php?by=name&substr=git>`_ or
74 `git-osx-installer
75 <http://sourceforge.net/projects/git-osx-installer/files/>`_ or
76 install git with `Homebrew <http://brew.sh/>`_: ``brew install git``.
77
78 `git-cola <https://git-cola.github.io/index.html>`_ (`repository
79 <https://github.com/git-cola/git-cola>`__) is a Git GUI written in
80 Python and GPL licensed. Linux, Windows, MacOS X.
81
82 `TortoiseGit <https://tortoisegit.org/>`_ is a Windows Shell Interface
83 to Git based on TortoiseSVN; open source.
84
85
86 Initial configuration
87 ---------------------
88
89 This simple code is often appears in documentation, but it is
90 important so let repeat it here. Git stores author and committer
91 names/emails in every commit, so configure your real name and
92 preferred email::
93
94     $ git config --global user.name "User Name"
95     $ git config --global user.email user.name@example.org
96
97
98 Examples in this PEP
99 ====================
100
101 Examples of git commands in this PEP use the following approach. It is
102 supposed that you, the user, works with a local repository named
103 ``python`` that has an upstream remote repo named ``origin``. Your
104 local repo has two branches ``v1`` and ``master``. For most examples
105 the currently checked out branch is ``master``. That is, it's assumed
106 you have done something like that::
107
108     $ git clone https://git.python.org/python.git
109     $ cd python
110     $ git branch v1 origin/v1
111
112 The first command clones remote repository into local directory
113 `python``, creates a new local branch master, sets
114 remotes/origin/master as its upstream remote-tracking branch and
115 checks it out into the working directory.
116
117 The last command creates a new local branch v1 and sets
118 remotes/origin/v1 as its upstream remote-tracking branch.
119
120 The same result can be achieved with commands::
121
122     $ git clone -b v1 https://git.python.org/python.git
123     $ cd python
124     $ git checkout --track origin/master
125
126 The last command creates a new local branch master, sets
127 remotes/origin/master as its upstream remote-tracking branch and
128 checks it out into the working directory.
129
130
131 Branches and branches
132 =====================
133
134 Git terminology can be a bit misleading. Take, for example, the term
135 "branch". In git it has two meanings. A branch is a directed line of
136 commits (possibly with merges). And a branch is a label or a pointer
137 assigned to a line of commits. It is important to distinguish when you
138 talk about commits and when about their labels. Lines of commits are
139 by itself unnamed and are usually only lengthening and merging.
140 Labels, on the other hand, can be created, moved, renamed and deleted
141 freely.
142
143
144 Remote repositories and remote branches
145 =======================================
146
147 Remote-tracking branches are branches (pointers to commits) in your
148 local repository. They are there for git (and for you) to remember
149 what branches and commits have been pulled from and pushed to what
150 remote repos (you can pull from and push to many remotes).
151 Remote-tracking branches live under ``remotes/$REMOTE`` namespaces,
152 e.g. ``remotes/origin/master``.
153
154 To see the status of remote-tracking branches run::
155
156     $ git branch -rv
157
158 To see local and remote-tracking branches (and tags) pointing to
159 commits::
160
161     $ git log --decorate
162
163 You never do your own development on remote-tracking branches. You
164 create a local branch that has a remote branch as upstream and do
165 development on that local branch. On push git pushes commits to the
166 remote repo and updates remote-tracking branches, on pull git fetches
167 commits from the remote repo, updates remote-tracking branches and
168 fast-forwards, merges or rebases local branches.
169
170 When you do an initial clone like this::
171
172     $ git clone -b v1 https://git.python.org/python.git
173
174 git clones remote repository ``https://git.python.org/python.git`` to
175 directory ``python``, creates a remote named ``origin``, creates
176 remote-tracking branches, creates a local branch ``v1``, configure it
177 to track upstream remotes/origin/v1 branch and checks out ``v1`` into
178 the working directory.
179
180 Some commands, like ``git status --branch`` and ``git branch --verbose``,
181 report the difference between local and remote branches.
182 Please remember they only do comparison with remote-tracking branches
183 in your local repository, and the state of those remote-tracking
184 branches can be outdated. To update remote-tracking branches you
185 either fetch and merge (or rebase) commits from the remote repository
186 or update remote-tracking branches without updating local branches.
187
188
189 Updating local and remote-tracking branches
190 -------------------------------------------
191
192 To update remote-tracking branches without updating local branches run
193 ``git remote update [$REMOTE...]``. For example::
194
195     $ git remote update
196     $ git remote update origin
197
198
199 Fetch and pull
200 ''''''''''''''
201
202 There is a major difference between
203
204 ::
205
206     $ git fetch $REMOTE $BRANCH
207
208 and
209
210 ::
211
212     $ git fetch $REMOTE $BRANCH:$BRANCH
213
214 The first command fetches commits from the named $BRANCH in the
215 $REMOTE repository that are not in your repository, updates
216 remote-tracking branch and leaves the id (the hash) of the head commit
217 in file .git/FETCH_HEAD.
218
219 The second command fetches commits from the named $BRANCH in the
220 $REMOTE repository that are not in your repository and updates both
221 the local branch $BRANCH and its upstream remote-tracking branch. But
222 it refuses to update branches in case of non-fast-forward. And it
223 refuses to update the current branch (currently checked out branch,
224 where HEAD is pointing to).
225
226 The first command is used internally by ``git pull``.
227
228 ::
229
230     $ git pull $REMOTE $BRANCH
231
232 is equivalent to
233
234 ::
235
236     $ git fetch $REMOTE $BRANCH
237     $ git merge FETCH_HEAD
238
239 Certainly, $BRANCH in that case should be your current branch. If you
240 want to merge a different branch into your current branch first update
241 that non-current branch and then merge::
242
243     $ git fetch origin v1:v1  # Update v1
244     $ git pull --rebase origin master  # Update the current branch master
245                                        # using rebase instead of merge
246     $ git merge v1
247
248 If you have not yet pushed commits on ``v1``, though, the scenario has
249 to become a bit more complex. Git refuses to update
250 non-fast-forwardable branch, and you don't want to do force-pull
251 because that would remove your non-pushed commits and you would need
252 to recover. So you want to rebase ``v1`` but you cannot rebase
253 non-current branch. Hence, checkout ``v1`` and rebase it before
254 merging::
255
256     $ git checkout v1
257     $ git pull --rebase origin v1
258     $ git checkout master
259     $ git pull --rebase origin master
260     $ git merge v1
261
262 It is possible to configure git to make it fetch/pull a few branches
263 or all branches at once, so you can simply run
264
265 ::
266
267     $ git pull origin
268
269 or even
270
271 ::
272
273     $ git pull
274
275 Default remote repository for fetching/pulling is ``origin``. Default
276 set of references to fetch is calculated using matching algorithm: git
277 fetches all branches having the same name on both ends.
278
279
280 Push
281 ''''
282
283 Pushing is a bit simpler. There is only one command ``push``. When you
284 run
285
286 ::
287
288     $ git push origin v1 master
289
290 git pushes local v1 to remote v1 and local master to remote master.
291 The same as::
292
293     $ git push origin v1:v1 master:master
294
295 Git pushes commits to the remote repo and updates remote-tracking
296 branches. Git refuses to push commits that aren't fast-forwardable.
297 You can force-push anyway, but please remember - you can force-push to
298 your own repositories but don't force-push to public or shared repos.
299 If you find git refuses to push commits that aren't fast-forwardable,
300 better fetch and merge commits from the remote repo (or rebase your
301 commits on top of the fetched commits), then push. Only force-push if
302 you know what you do and why you do it. See the section `Commit
303 editing and caveats`_ below.
304
305 It is possible to configure git to make it push a few branches or all
306 branches at once, so you can simply run
307
308 ::
309
310     $ git push origin
311
312 or even
313
314 ::
315
316     $ git push
317
318 Default remote repository for pushing is ``origin``. Default set of
319 references to push in git before 2.0 is calculated using matching
320 algorithm: git pushes all branches having the same name on both ends.
321 Default set of references to push in git 2.0+ is calculated using
322 simple algorithm: git pushes the current branch back to its
323 @{upstream}.
324
325 To configure git before 2.0 to the new behaviour run::
326
327 $ git config push.default simple
328
329 To configure git 2.0+ to the old behaviour run::
330
331 $ git config push.default matching
332
333 Git doesn't allow to push a branch if it's the current branch in the
334 remote non-bare repository: git refuses to update remote working
335 directory. You really should push only to bare repositories. For
336 non-bare repositories git prefers pull-based workflow.
337
338 When you want to deploy code on a remote host and can only use push
339 (because your workstation is behind a firewall and you cannot pull
340 from it) you do that in two steps using two repositories: you push
341 from the workstation to a bare repo on the remote host, ssh to the
342 remote host and pull from the bare repo to a non-bare deployment repo.
343
344 That changed in git 2.3, but see `the blog post
345 <https://github.com/blog/1957-git-2-3-has-been-released#push-to-deploy>`_
346 for caveats; in 2.4 the push-to-deploy feature was `further improved
347 <https://github.com/blog/1994-git-2-4-atomic-pushes-push-to-deploy-and-more#push-to-deploy-improvements>`_.
348
349
350 Tags
351 ''''
352
353 Git automatically fetches tags that point to commits being fetched
354 during fetch/pull. To fetch all tags (and commits they point to) run
355 ``git fetch --tags origin``. To fetch some specific tags fetch them
356 explicitly::
357
358     $ git fetch origin tag $TAG1 tag $TAG2...
359
360 For example::
361
362     $ git fetch origin tag 1.4.2
363     $ git fetch origin v1:v1 tag 2.1.7
364
365 Git doesn't automatically pushes tags. That allows you to have private
366 tags. To push tags list them explicitly::
367
368     $ git push origin tag 1.4.2
369     $ git push origin v1 master tag 2.1.7
370
371 Or push all tags at once::
372
373     $ git push --tags origin
374
375 Don't move tags with ``git tag -f`` or remove tags with ``git tag -d``
376 after they have been published.
377
378
379 Private information
380 '''''''''''''''''''
381
382 When cloning/fetching/pulling/pushing git copies only database objects
383 (commits, trees, files and tags) and symbolic references (branches and
384 lightweight tags). Everything else is private to the repository and
385 never cloned, updated or pushed. It's your config, your hooks, your
386 private exclude file.
387
388 If you want to distribute hooks, copy them to the working tree, add,
389 commit, push and instruct the team to update and install the hooks
390 manually.
391
392
393 Commit editing and caveats
394 ==========================
395
396 A warning not to edit published (pushed) commits also appears in
397 documentation but it's repeated here anyway as it's very important.
398
399 It is possible to recover from a forced push but it's PITA for the
400 entire team. Please avoid it.
401
402 To see what commits have not been published yet compare the head of the
403 branch with its upstream remote-tracking branch::
404
405     $ git log origin/master..  # from origin/master to HEAD (of master)
406     $ git log origin/v1..v1  # from origin/v1 to the head of v1
407
408 For every branch that has an upstream remote-tracking branch git
409 maintains an alias @{upstream} (short version @{u}), so the commands
410 above can be given as::
411
412     $ git log @{u}..
413     $ git log v1@{u}..v1
414
415 To see the status of all branches::
416
417     $ git branch -avv
418
419 To compare the status of local branches with a remote repo::
420
421     $ git remote show origin
422
423 Read `how to recover from upstream rebase
424 <https://git-scm.com/docs/git-rebase#_recovering_from_upstream_rebase>`_.
425 It is in ``git help rebase``.
426
427 On the other hand, don't be too afraid about commit editing. You can
428 safely edit, reorder, remove, combine and split commits that haven't
429 been pushed yet. You can even push commits to your own (backup) repo,
430 edit them later and force-push edited commits to replace what have
431 already been pushed. Not a problem until commits are in a public
432 or shared repository.
433
434
435 Undo
436 ====
437
438 Whatever you do, don't panic. Almost anything in git can be undone.
439
440
441 git checkout: restore file's content
442 ------------------------------------
443
444 ``git checkout``, for example, can be used to restore the content of
445 file(s) to that one of a commit. Like this::
446
447     git checkout HEAD~ README
448
449 The commands restores the contents of README file to the last but one
450 commit in the current branch. By default the commit ID is simply HEAD;
451 i.e. ``git checkout README`` restores README to the latest commit.
452
453 (Do not use ``git checkout`` to view a content of a file in a commit,
454 use ``git cat-file -p``; e.g. ``git cat-file -p HEAD~:path/to/README``).
455
456
457 git reset: remove (non-pushed) commits
458 --------------------------------------
459
460 ``git reset`` moves the head of the current branch. The head can be
461 moved to point to any commit but it's often used to remove a commit or
462 a few (preferably, non-pushed ones) from the top of the branch - that
463 is, to move the branch backward in order to undo a few (non-pushed)
464 commits.
465
466 ``git reset`` has three modes of operation - soft, hard and mixed.
467 Default is mixed. ProGit `explains
468 <https://git-scm.com/book/en/Git-Tools-Reset-Demystified>`_ the
469 difference very clearly. Bare repositories don't have indices or
470 working trees so in a bare repo only soft reset is possible.
471
472
473 Unstaging
474 '''''''''
475
476 Mixed mode reset with a path or paths can be used to unstage changes -
477 that is, to remove from index changes added with ``git add`` for
478 committing. See `The Book
479 <https://git-scm.com/book/en/Git-Basics-Undoing-Things>`_ for details
480 about unstaging and other undo tricks.
481
482
483 git reflog: reference log
484 -------------------------
485
486 Removing commits with ``git reset`` or moving the head of a branch
487 sounds dangerous and it is. But there is a way to undo: another
488 reset back to the original commit. Git doesn't remove commits
489 immediately; unreferenced commits (in git terminology they are called
490 "dangling commits") stay in the database for some time (default is two
491 weeks) so you can reset back to it or create a new branch pointing to
492 the original commit.
493
494 For every move of a branch's head - with ``git commit``, ``git
495 checkout``, ``git fetch``, ``git pull``, ``git rebase``, ``git reset``
496 and so on - git stores a reference log (reflog for short). For every
497 move git stores where the head was. Command ``git reflog`` can be used
498 to view (and manipulate) the log.
499
500 In addition to the moves of the head of every branch git stores the
501 moves of the HEAD - a symbolic reference that (usually) names the
502 current branch. HEAD is changed with ``git checkout $BRANCH``.
503
504 By default ``git reflog`` shows the moves of the HEAD, i.e. the
505 command is equivalent to ``git reflog HEAD``. To show the moves of the
506 head of a branch use the command ``git reflog $BRANCH``.
507
508 So to undo a ``git reset`` lookup the original commit in ``git
509 reflog``, verify it with ``git show`` or ``git log`` and run ``git
510 reset $COMMIT_ID``. Git stores the move of the branch's head in
511 reflog, so you can undo that undo later again.
512
513 In a more complex situation you'd want to move some commits along with
514 resetting the head of the branch. Cherry-pick them to the new branch.
515 For example, if you want to reset the branch ``master`` back to the
516 original commit but preserve two commits created in the current branch
517 do something like::
518
519     $ git branch save-master  # create a new branch saving master
520     $ git reflog  # find the original place of master
521     $ git reset $COMMIT_ID
522     $ git cherry-pick save-master~ save-master
523     $ git branch -D save-master  # remove temporary branch
524
525
526 git revert: revert a commit
527 ---------------------------
528
529 ``git revert`` reverts a commit or commits, that is, it creates a new
530 commit or commits that revert(s) the effects of the given commits.
531 It's the only way to undo published commits (``git commit --amend``,
532 ``git rebase`` and ``git reset`` change the branch in
533 non-fast-forwardable ways so they should only be used for non-pushed
534 commits.)
535
536 There is a problem with reverting a merge commit. ``git revert`` can
537 undo the code created by the merge commit but it cannot undo the fact
538 of merge. See the discussion `How to revert a faulty merge
539 <https://www.kernel.org/pub/software/scm/git/docs/howto/revert-a-faulty-merge.html>`_.
540
541
542 One thing that cannot be undone
543 -------------------------------
544
545 Whatever you undo, there is one thing that cannot be undone -
546 overwritten uncommitted changes. Uncommitted changes don't belong to
547 git so git cannot help preserving them.
548
549 Most of the time git warns you when you're going to execute a command
550 that overwrites uncommitted changes. Git doesn't allow you to switch
551 branches with ``git checkout``. It stops you when you're going to
552 rebase with non-clean working tree. It refuses to pull new commits
553 over non-committed files.
554
555 But there are commands that do exactly that - overwrite files in the
556 working tree. Commands like ``git checkout $PATHs`` or ``git reset
557 --hard`` silently overwrite files including your uncommitted changes.
558
559 With that in mind you can understand the stance "commit early, commit
560 often". Commit as often as possible. Commit on every save in your
561 editor or IDE. You can edit your commits before pushing - edit commit
562 messages, change commits, reorder, combine, split, remove. But save
563 your changes in git database, either commit changes or at least stash
564 them with ``git stash``.
565
566
567 Merge or rebase?
568 ================
569
570 Internet is full of heated discussions on the topic: "merge or
571 rebase?" Most of them are meaningless. When a DVCS is being used in a
572 big team with a big and complex project with many branches there is
573 simply no way to avoid merges. So the question's diminished to
574 "whether to use rebase, and if yes - when to use rebase?" Considering
575 that it is very much recommended not to rebase published commits the
576 question's diminished even further: "whether to use rebase on
577 non-pushed commits?"
578
579 That small question is for the team to decide. To preserve the beauty
580 of linear history it's recommended to use rebase when pulling, i.e. do
581 ``git pull --rebase`` or even configure automatic setup of rebase for
582 every new branch::
583
584     $ git config branch.autosetuprebase always
585
586 and configure rebase for existing branches::
587
588     $ git config branch.$NAME.rebase true
589
590 For example::
591
592     $ git config branch.v1.rebase true
593     $ git config branch.master.rebase true
594
595 After that ``git pull origin master`` becomes equivalent to ``git pull
596 --rebase origin master``.
597
598 It is recommended to create new commits in a separate feature or topic
599 branch while using rebase to update the mainline branch. When the
600 topic branch is ready merge it into mainline. To avoid a tedious task
601 of resolving large number of conflicts at once you can merge the topic
602 branch to the mainline from time to time and switch back to the topic
603 branch to continue working on it. The entire workflow would be
604 something like::
605
606     $ git checkout -b issue-42  # create a new issue branch and switch to it
607         ...edit/test/commit...
608     $ git checkout master
609     $ git pull --rebase origin master  # update master from the upstream
610     $ git merge issue-42
611     $ git branch -d issue-42  # delete the topic branch
612     $ git push origin master
613
614 When the topic branch is deleted only the label is removed, commits
615 are stayed in the database, they are now merged into master::
616
617     o--o--o--o--o--M--< master - the mainline branch
618         \         /
619          --*--*--*             - the topic branch, now unnamed
620
621 The topic branch is deleted to avoid cluttering branch namespace with
622 small topic branches. Information on what issue was fixed or what
623 feature was implemented should be in the commit messages.
624
625 But even that small amount of rebasing could be too big in case of
626 long-lived merged branches. Imagine you're doing work in both ``v1``
627 and ``master`` branches, regularly merging ``v1`` into ``master``.
628 After some time you will have a lot of merge and non-merge commits in
629 ``master``. Then you want to push your finished work to a shared
630 repository and find someone has pushed a few commits to ``v1``. Now
631 you have a choice of two equally bad alternatives: either you fetch
632 and rebase ``v1`` and then have to recreate all you work in ``master``
633 (reset ``master`` to the origin, merge ``v1`` and cherry-pick all
634 non-merge commits from the old master); or merge the new ``v1`` and
635 loose the beauty of linear history.
636
637
638 Null-merges
639 ===========
640
641 Git has a builtin merge strategy for what Python core developers call
642 "null-merge"::
643
644     $ git merge -s ours v1  # null-merge v1 into master
645
646
647 Branching models
648 ================
649
650 Git doesn't assume any particular development model regarding
651 branching and merging. Some projects prefer to graduate patches from
652 the oldest branch to the newest, some prefer to cherry-pick commits
653 backwards, some use squashing (combining a number of commits into
654 one). Anything is possible.
655
656 There are a few examples to start with. `git help workflows
657 <https://www.kernel.org/pub/software/scm/git/docs/gitworkflows.html>`_
658 describes how the very git authors develop git.
659
660 ProGit book has a few chapters devoted to branch management in
661 different projects: `Git Branching - Branching Workflows
662 <https://git-scm.com/book/en/Git-Branching-Branching-Workflows>`_ and
663 `Distributed Git - Contributing to a Project
664 <https://git-scm.com/book/en/Distributed-Git-Contributing-to-a-Project>`_.
665
666 There is also a well-known article `A successful Git branching model
667 <http://nvie.com/posts/a-successful-git-branching-model/>`_ by Vincent
668 Driessen. It recommends a set of very detailed rules on creating and
669 managing mainline, topic and bugfix branches. To support the model the
670 author implemented `git flow <https://github.com/nvie/gitflow>`_
671 extension.
672
673
674 Advanced configuration
675 ======================
676
677 Line endings
678 ------------
679
680 Git has builtin mechanisms to handle line endings between platforms
681 with different end-of-line styles. To allow git to do CRLF conversion
682 assign ``text`` attribute to files using `.gitattributes
683 <https://www.kernel.org/pub/software/scm/git/docs/gitattributes.html>`_.
684 For files that have to have specific line endings assign ``eol``
685 attribute. For binary files the attribute is, naturally, ``binary``.
686
687 For example::
688
689     $ cat .gitattributes
690     *.py text
691     *.txt text
692     *.png binary
693     /readme.txt eol=CRLF
694
695 To check what attributes git uses for files use ``git check-attr``
696 command. For example::
697
698 $ git check-attr -a -- \*.py
699
700
701 Useful assets
702 -------------
703
704 `GitAlias <http://gitalias.com/>`_ (`repository
705 <https://github.com/GitAlias/gitalias>`_) is a big collection of
706 aliases. A careful selection of aliases for frequently used commands
707 could save you a lot of keystrokes!
708
709 `GitIgnore <https://www.gitignore.io/>`_ and
710 https://github.com/github/gitignore are collections of ``.gitignore``
711 files for all kinds of IDEs and programming languages. Python
712 included!
713
714 `pre-commit <http://pre-commit.com/>`_ (`repositories
715 <https://github.com/pre-commit>`_) is a framework for managing and
716 maintaining multi-language pre-commit hooks. The framework is written
717 in Python and has a lot of plugins for many programming languages.
718
719
720 Advanced topics
721 ===============
722
723 Staging area
724 ------------
725
726 Staging area aka index aka cache is a distinguishing feature of git.
727 Staging area is where git collects patches before committing them.
728 Separation between collecting patches and commit phases provides a
729 very useful feature of git: you can review collected patches before
730 commit and even edit them - remove some hunks, add new hunks and
731 review again.
732
733 To add files to the index use ``git add``. Collecting patches before
734 committing means you need to do that for every change, not only to add
735 new (untracked) files. To simplify committing in case you just want to
736 commit everything without reviewing run ``git commit --all`` (or just
737 ``-a``) - the command adds every changed tracked file to the index and
738 then commit. To commit a file or files regardless of patches collected
739 in the index run ``git commit [--only|-o] -- $FILE...``.
740
741 To add hunks of patches to the index use ``git add --patch`` (or just
742 ``-p``). To remove collected files from the index use ``git reset HEAD
743 -- $FILE...`` To add/inspect/remove collected hunks use ``git add
744 --interactive`` (``-i``).
745
746 To see the diff between the index and the last commit (i.e., collected
747 patches) use ``git diff --cached``. To see the diff between the
748 working tree and the index (i.e., uncollected patches) use just ``git
749 diff``. To see the diff between the working tree and the last commit
750 (i.e., both collected and uncollected patches) run ``git diff HEAD``.
751
752 See `WhatIsTheIndex
753 <https://git.wiki.kernel.org/index.php/WhatIsTheIndex>`_ and
754 `IndexCommandQuickref
755 <https://git.wiki.kernel.org/index.php/IndexCommandQuickref>`_ in Git
756 Wiki.
757
758
759 Aliases
760 -------
761
762 Recursive aliases
763 '''''''''''''''''
764
765 Git doesn't allow recursive aliases. The expansion of an alias is
766 interpreted by git as a builtin command. I.e., in the following example
767 alias ``com`` doesn't work because there is no builtin command ``git
768 ci``::
769
770     [alias]
771     ci = commit
772     com = ci
773
774 You can trick git by using shell. The following example works albeit a
775 bit slow::
776
777     [alias]
778     ci = commit
779     com = !git ci
780
781
782 Literal expansion
783 '''''''''''''''''
784
785 Git interprets aliases literally. I.e., when expanding an alias git just
786 does simple textual substitution. That could be a surprise if an alias
787 is passed parameters on the command line. For example, the following
788 alias works without parameters -- it pushes configured branch(es) to all
789 configured remotes::
790
791     [alias]
792     push-to-all-remotes = !git remote | xargs -n1 git push
793
794 But it doesn't work if a user wants to provide a list of branches to
795 push: the command ``git push-to-all-remotes master`` is expanded by git
796 as ``!git remote | xargs -n1 git push master`` which is certainly not
797 what the user wants -- remote's name must comes first, before branches.
798 This is a fix::
799
800     [alias]
801     push-to-all-remotes = !git remote | xargs -I% -n1 git push %
802
803 Then the command ``git push-to-all-remotes master`` is expanded by git
804 as ``!git remote | xargs -I% -n1 git push % master``; xargs substitutes
805 ``%`` with remote's name.
806
807
808 Root
809 ----
810
811 Git switches to the root (top-level directory of the project where
812 ``.git`` subdirectory exists) before running any command. Git
813 remembers though the directory that was current before the switch.
814 Some programs take into account the current directory. E.g., ``git
815 status`` shows file paths of changed and unknown files relative to the
816 current directory; ``git grep`` searches below the current directory;
817 ``git apply`` applies only those hunks from the patch that touch files
818 below the current directory.
819
820 But most commands run from the root and ignore the current directory.
821 Imagine, for example, that you have two work trees, one for the branch
822 ``v1`` and the other for ``master``. If you want to merge ``v1`` from
823 a subdirectory inside the second work tree you must write commands as
824 if you're in the top-level dir. Let take two work trees,
825 ``project-v1`` and ``project``, for example::
826
827     $ cd project/subdirectory
828     $ git fetch ../project-v1 v1:v1
829     $ git merge v1
830
831 Please note the path in ``git fetch ../project-v1 v1:v1`` is
832 ``../project-v1`` and not ``../../project-v1`` despite the fact that
833 we run the commands from a subdirectory, not from the root.
834
835
836 ReReRe
837 ------
838
839 Rerere is a mechanism that helps to resolve repeated merge conflicts.
840 The most frequent source of recurring merge conflicts are topic
841 branches that are merged into mainline and then the merge commits are
842 removed; that's often performed to test the topic branches and train
843 rerere; merge commits are removed to have clean linear history and
844 finish the topic branch with only one last merge commit.
845
846 Rerere works by remembering the states of tree before and after a
847 successful commit. That way rerere can automatically resolve conflicts
848 if they appear in the same files.
849
850 Rerere can be used manually with ``git rerere`` command but most often
851 it's used automatically. Enable rerere with these commands in a
852 working tree::
853
854     $ git config rerere.enabled true
855     $ git config rerere.autoupdate true
856
857 You don't need to turn rerere on globally - you don't want rerere in
858 bare repositories or single-branch repositories; you only need rerere
859 in repos where you often perform merges and resolve merge conflicts.
860
861 See `Rerere <https://git-scm.com/book/en/Git-Tools-Rerere>`_ in The
862 Book.
863
864
865 Database maintenance
866 --------------------
867
868 Git object database and other files/directories under ``.git`` require
869 periodic maintenance and cleanup. For example, commit editing left
870 unreferenced objects (dangling objects, in git terminology) and these
871 objects should be pruned to avoid collecting cruft in the DB. The
872 command ``git gc`` is used for maintenance. Git automatically runs
873 ``git gc --auto`` as a part of some commands to do quick maintenance.
874 Users are recommended to run ``git gc --aggressive`` from time to
875 time; ``git help gc`` recommends to run it  every few hundred
876 changesets; for more intensive projects it should be something like
877 once a week and less frequently (biweekly or monthly) for lesser
878 active projects.
879
880 ``git gc --aggressive`` not only removes dangling objects, it also
881 repacks object database into indexed and better optimized pack(s); it
882 also packs symbolic references (branches and tags). Another way to do
883 it is to run ``git repack``.
884
885 There is a well-known `message
886 <https://gcc.gnu.org/ml/gcc/2007-12/msg00165.html>`_ from Linus
887 Torvalds regarding "stupidity" of ``git gc --aggressive``. The message
888 can safely be ignored now. It is old and outdated, ``git gc
889 --aggressive`` became much better since that time.
890
891 For those who still prefer ``git repack`` over ``git gc --aggressive``
892 the recommended parameters are ``git repack -a -d -f --depth=20
893 --window=250``. See `this detailed experiment
894 <http://vcscompare.blogspot.ru/2008/06/git-repack-parameters.html>`_
895 for explanation of the effects of these parameters.
896
897 From time to time run ``git fsck [--strict]`` to verify integrity of
898 the database. ``git fsck`` may produce a list of dangling objects;
899 that's not an error, just a reminder to perform regular maintenance.
900
901
902 Tips and tricks
903 ===============
904
905 Command-line options and arguments
906 ----------------------------------
907
908 `git help cli
909 <https://www.kernel.org/pub/software/scm/git/docs/gitcli.html>`_
910 recommends not to combine short options/flags. Most of the times
911 combining works: ``git commit -av`` works perfectly, but there are
912 situations when it doesn't. E.g., ``git log -p -5`` cannot be combined
913 as ``git log -p5``.
914
915 Some options have arguments, some even have default arguments. In that
916 case the argument for such option must be spelled in a sticky way:
917 ``-Oarg``, never ``-O arg`` because for an option that has a default
918 argument the latter means "use default value for option ``-O`` and
919 pass ``arg`` further to the option parser". For example, ``git grep``
920 has an option ``-O`` that passes a list of names of the found files to
921 a program; default program for ``-O`` is a pager (usually ``less``),
922 but you can use your editor::
923
924     $ git grep -Ovim  # but not -O vim
925
926 BTW, if git is instructed to use ``less`` as the pager (i.e., if pager
927 is not configured in git at all it uses ``less`` by default, or if it
928 gets ``less`` from GIT_PAGER or PAGER environment variables, or if it
929 was configured with ``git config [--global] core.pager less``, or
930 ``less`` is used in the command ``git grep -Oless``) ``git grep``
931 passes ``+/$pattern`` option to ``less`` which is quite convenient.
932 Unfortunately, ``git grep`` doesn't pass the pattern if the pager is
933 not exactly ``less``, even if it's ``less`` with parameters (something
934 like ``git config [--global] core.pager less -FRSXgimq``); fortunately,
935 ``git grep -Oless`` always passes the pattern.
936
937
938 bash/zsh completion
939 -------------------
940
941 It's a bit hard to type ``git rebase --interactive --preserve-merges
942 HEAD~5`` manually even for those who are happy to use command-line,
943 and this is where shell completion is of great help. Bash/zsh come
944 with programmable completion, often automatically installed and
945 enabled, so if you have bash/zsh and git installed, chances are you
946 are already done - just go and use it at the command-line.
947
948 If you don't have necessary bits installed, install and enable
949 bash_completion package. If you want to upgrade your git completion to
950 the latest and greatest download necessary file from `git contrib
951 <https://git.kernel.org/cgit/git/git.git/tree/contrib/completion>`_.
952
953 Git-for-windows comes with git-bash for which bash completion is
954 installed and enabled.
955
956
957 bash/zsh prompt
958 ---------------
959
960 For command-line lovers shell prompt can carry a lot of useful
961 information. To include git information in the prompt use
962 `git-prompt.sh
963 <https://git.kernel.org/cgit/git/git.git/tree/contrib/completion/git-prompt.sh>`_.
964 Read the detailed instructions in the file.
965
966 Search the Net for "git prompt" to find other prompt variants.
967
968
969 SSH connection sharing
970 ----------------------
971
972 SSH connection sharing is a feature of OpenSSH and perhaps derivatives
973 like PuTTY. SSH connection sharing is a way to decrease ssh client
974 startup time by establishing one connection and reusing it for all
975 subsequent clients connecting to the same server. SSH connection
976 sharing can be used to speedup a lot of short ssh sessions like scp,
977 sftp, rsync and of course git over ssh. If you regularly
978 fetch/pull/push from/to remote repositories accessible over ssh then
979 using ssh connection sharing is recommended.
980
981 To turn on ssh connection sharing add something like this to your
982 ~/.ssh/config::
983
984     Host *
985     ControlMaster auto
986     ControlPath ~/.ssh/mux-%r@%h:%p
987     ControlPersist 600
988
989 See `OpenSSH wikibook
990 <https://en.wikibooks.org/wiki/OpenSSH/Cookbook/Multiplexing>`_ and
991 `search <https://www.google.com/search?q=ssh+connection+sharing>`_ for
992 more information.
993
994 SSH connection sharing can be used at GitHub, GitLab and SourceForge
995 repositories, but please be advised that BitBucket doesn't allow it
996 and forcibly closes master connection after a short inactivity period
997 so you will see errors like this from ssh: "Connection to bitbucket.org
998 closed by remote host."
999
1000
1001 git on server
1002 =============
1003
1004 The simplest way to publish a repository or a group of repositories is
1005 ``git daemon``. The daemon provides anonymous access, by default it is
1006 read-only. The repositories are accessible by git protocol (git://
1007 URLs). Write access can be enabled but the protocol lacks any
1008 authentication means, so it should be enabled only within a trusted
1009 LAN. See ``git help daemon`` for details.
1010
1011 Git over ssh provides authentication and repo-level authorisation as
1012 repositories can be made user- or group-writeable (see parameter
1013 ``core.sharedRepository`` in ``git help config``). If that's too
1014 permissive or too restrictive for some project's needs there is a
1015 wrapper `gitolite <http://gitolite.com/gitolite/index.html>`_ that can
1016 be configured to allow access with great granularity; gitolite is
1017 written in Perl and has a lot of documentation.
1018
1019 Web interface to browse repositories can be created using `gitweb
1020 <https://git.kernel.org/cgit/git/git.git/tree/gitweb>`_ or `cgit
1021 <http://git.zx2c4.com/cgit/about/>`_. Both are CGI scripts (written in
1022 Perl and C). In addition to web interface both provide read-only dumb
1023 http access for git (http(s):// URLs). `Klaus
1024 <https://pypi.python.org/pypi/klaus>`_ is a small and simple WSGI web
1025 server that implements both web interface and git smart HTTP
1026 transport; supports Python 2 and Python 3, performs syntax
1027 highlighting.
1028
1029 There are also more advanced web-based development environments that
1030 include ability to manage users, groups and projects; private,
1031 group-accessible and public repositories; they often include issue
1032 trackers, wiki pages, pull requests and other tools for development
1033 and communication. Among these environments are `Kallithea
1034 <https://kallithea-scm.org/>`_ and `pagure <https://pagure.io/>`_,
1035 both are written in Python; pagure was written by Fedora developers
1036 and is being used to develop some Fedora projects. `GitPrep
1037 <http://gitprep.yukikimoto.com/>`_ is yet another GitHub clone,
1038 written in Perl. `Gogs <https://gogs.io/>`_ is written in Go. `GitBucket
1039 <https://gitbucket.github.io/gitbucket-news/about/>`_ is written in
1040 Scala. `RocketGit <https://rocketgit.com/>`_ is AGPL-licensed
1041 development environment written in PHP (there are plans to rewrite
1042 critical parts in C).
1043
1044 And last but not least, `GitLab <https://about.gitlab.com/>`_. It's
1045 perhaps the most advanced web-based development environment for git.
1046 Written in Ruby, community edition is free and open source (MIT
1047 license).
1048
1049
1050 From Mercurial to git
1051 =====================
1052
1053 There are many tools to convert Mercurial repositories to git. The
1054 most famous are, probably, `hg-git <https://hg-git.github.io/>`_ and
1055 `fast-export <http://repo.or.cz/w/fast-export.git>`_ (many years ago
1056 it was known under the name ``hg2git``).
1057
1058 But a better tool, perhaps the best, is `git-remote-hg
1059 <https://github.com/felipec/git-remote-hg>`_. It provides transparent
1060 bidirectional (pull and push) access to Mercurial repositories from
1061 git. Its author wrote a `comparison of alternatives
1062 <https://github.com/felipec/git/wiki/Comparison-of-git-remote-hg-alternatives>`_
1063 that seems to be mostly objective.
1064
1065 To use git-remote-hg, install or clone it, add to your PATH (or copy
1066 script ``git-remote-hg`` to a directory that's already in PATH) and
1067 prepend ``hg::`` to Mercurial URLs. For example::
1068
1069     $ git clone https://github.com/felipec/git-remote-hg.git
1070     $ PATH=$PATH:"`pwd`"/git-remote-hg
1071     $ git clone hg::https://hg.python.org/peps/ PEPs
1072
1073 To work with the repository just use regular git commands including
1074 ``git fetch/pull/push``.
1075
1076 To start converting your Mercurial habits to git see the page
1077 `Mercurial for Git users
1078 <https://www.mercurial-scm.org/wiki/GitConcepts>`_ at Mercurial wiki.
1079 At the second half of the page there is a table that lists
1080 corresponding Mercurial and git commands. Should work perfectly in
1081 both directions.
1082
1083 Python Developer's Guide also has a chapter `Mercurial for git
1084 developers <https://docs.python.org/devguide/gitdevs.html>`_ that
1085 documents a few differences between git and hg.
1086
1087
1088 Git and GitHub
1089 ==============
1090
1091 `gitsome <https://github.com/donnemartin/gitsome>`_ - Git/GitHub
1092 command line interface (CLI). Written in Python, work on MacOS, Unix,
1093 Windows. Git/GitHub CLI with autocomplete, includes many GitHub
1094 integrated commands that work with all shells, builtin xonsh with
1095 Python REPL to run Python commands alongside shell commands, command
1096 history, customizable highlighting, thoroughly documented.