Git: Difference between revisions

From ArchWiki
m (move Bisecting bugs with Git from See also to Related articles)
(update Pkg/AUR templates)
 
(115 intermediate revisions by 43 users not shown)
Line 1: Line 1:
[[Category:Version Control System]]
[[Category:Version control system]]
[[Category:Commands]]
[[Category:OpenPGP]]
[[de:Git]]
[[es:Git]]
[[es:Git]]
[[ja:Git]]
[[ja:Git]]
Line 5: Line 8:
{{Related articles start}}
{{Related articles start}}
{{Related|Bisecting bugs with Git}}
{{Related|Bisecting bugs with Git}}
{{Related|Concurrent Versions System}}
{{Related|Git server}}
{{Related|Gitweb}}
{{Related|Gitweb}}
{{Related|Cgit}}
{{Related|HTTP tunneling#Tunneling Git}}
{{Related|HTTP tunneling#Tunneling Git}}
{{Related|Subversion}}
{{Related|Subversion}}
{{Related|Concurrent Versions System}}
{{Related|VCS package guidelines}}
{{Related articles end}}
{{Related articles end}}
{{Quote|I've met people who thought that git is a front-end to GitHub. They were wrong, git is a front-end to the AUR.|[https://public-inbox.org/git/#didyoureallythinklinuswouldsaythat Linus T.]}}


[[wikipedia:Git (software)|Git]] is the version control system (VCS) designed and developed by Linus Torvalds, the creator of the Linux kernel. Git is now used to maintain [[AUR]] packages, as well as many other projects, including sources for the Linux kernel.  
:"I've met people who thought git is a front-end to GitHub. They were wrong, git is a front-end to the AUR." — [https://public-inbox.org/git/#didyoureallythinklinuswouldsaythat Linus T.]
 
[[wikipedia:Git (software)|Git]] is the version control system (VCS) designed and developed by Linus Torvalds, the creator of the Linux kernel. Git is now used to maintain [[AUR]] packages, as well as many other projects, including sources for the Linux kernel.


== Installation ==
== Installation ==
Line 23: Line 28:
See also [https://git-scm.com/download/gui/linux git GUI Clients].
See also [https://git-scm.com/download/gui/linux git GUI Clients].


* {{App|Giggle|GTK+ frontend for git.|https://wiki.gnome.org/Apps/giggle/|{{Pkg|giggle}}}}
* {{App|Giggle|GTK frontend for git.|https://wiki.gnome.org/Apps/giggle/|{{Pkg|giggle}}}}
* {{App|GitAhead|Graphical git client including a built-in Merge Tool.|https://gitahead.github.io/gitahead.com/|{{AUR|gitahead}}}}
* {{App|Git Cola|Sleek and powerful graphical user interface for Git written in Python.|https://git-cola.github.io/|{{AUR|git-cola}}}}
* {{App|Git Cola|Sleek and powerful graphical user interface for Git written in Python.|https://git-cola.github.io/|{{AUR|git-cola}}}}
* {{App|Git Extensions|Graphical user interface for Git that allows you to control Git without using the commandline.|https://gitextensions.github.io/|{{AUR|gitextensions}}}}
* {{App|Git Extensions|Graphical user interface for Git that allows you to control Git without using the commandline.|https://gitextensions.github.io/|{{AUR|gitextensions}}}}
* {{App|gitg|GNOME GUI client to view git repositories.|https://wiki.gnome.org/Apps/Gitg|{{Pkg|gitg}}}}
* {{App|gitg|GNOME GUI client to view git repositories. Part of {{Grp|gnome-extra}}.|https://wiki.gnome.org/Apps/Gitg|{{Pkg|gitg}}}}
* {{App|git-gui|Tcl/Tk based portable graphical interface to Git.|https://git-scm.com/docs/git-gui|{{Pkg|git}} + {{Pkg|tk}}}}
* {{App|git-gui|Tcl/Tk based portable graphical interface to Git.|https://git-scm.com/docs/git-gui|{{Pkg|git}} + {{Pkg|tk}}}}
:{{Note|To enable spell checking in ''git-gui'', {{Pkg|aspell}} is required, along with the dictionary corresponding to the {{ic|LC_MESSAGES}} [[environment variable]]. See {{Bug|28181}} and the [[aspell]] article.}}
:{{Note|To enable spell checking in ''git-gui'', {{Pkg|aspell}} is required, along with the dictionary corresponding to the {{ic|LC_MESSAGES}} [[environment variable]]. See {{Bug|28181}} and the [[aspell]] article.}}
* {{App|GitHub Desktop|Electron-based graphical user interface built by the GitHub team.|https://github.com/desktop/desktop|{{AUR|github-desktop}} {{AUR|github-desktop-bin}}}}
* {{App|gitk|Tcl/Tk based Git repository browser.|https://git-scm.com/docs/gitk|{{Pkg|git}} + {{Pkg|tk}}}}
* {{App|gitk|Tcl/Tk based Git repository browser.|https://git-scm.com/docs/gitk|{{Pkg|git}} + {{Pkg|tk}}}}
* {{App|Gittyup| Qt based Git client.|https://github.com/Murmele/Gittyup|{{AUR|gittyup}}}}
* {{App|Guitar|Git GUI Client.|https://github.com/soramimi/Guitar|{{AUR|guitar}}}}
* {{App|gitui|fast terminal-ui for git written in rust.|https://github.com/extrawurst/gitui|{{Pkg|gitui}}}}
* {{App|lazygit|simple terminal UI for git commands.|https://github.com/jesseduffield/lazygit|{{Pkg|lazygit}}}}
* {{App|QGit|Git GUI viewer to browse revisions history, view patch content and changed files, graphically following different development branches.|https://github.com/tibirna/qgit|{{Pkg|qgit}}}}
* {{App|QGit|Git GUI viewer to browse revisions history, view patch content and changed files, graphically following different development branches.|https://github.com/tibirna/qgit|{{Pkg|qgit}}}}
* {{App|[[Wikipedia:RabbitVCS|RabbitVCS]]|Set of graphical tools written to provide simple and straightforward access to the version control systems you use.|http://rabbitvcs.org/|{{AUR|rabbitvcs}}}}
* {{App|[[Wikipedia:RabbitVCS|RabbitVCS]]|Set of graphical tools written to provide simple and straightforward access to the version control systems you use.|http://rabbitvcs.org/|{{AUR|rabbitvcs}}}}
* {{App|Sublime Merge|Git Client from the makers of Sublime Text. |https://www.sublimemerge.com/|{{AUR|sublime-merge}}}}
* {{App|Tig|ncurses-based text-mode interface for git.|https://jonas.github.io/tig/|{{Pkg|tig}}}}
* {{App|Tig|ncurses-based text-mode interface for git.|https://jonas.github.io/tig/|{{Pkg|tig}}}}
* {{App|ungit|Brings user friendliness to git without sacrificing the versatility of git.|https://github.com/FredrikNoren/ungit|{{AUR|nodejs-ungit}}}}
* {{App|ungit|Brings user friendliness to git without sacrificing the versatility of git.|https://github.com/FredrikNoren/ungit|{{AUR|nodejs-ungit}}}}
Line 51: Line 63:


See [https://git-scm.com/book/en/Getting-Started-Git-Basics Getting Started - Git Basics].
See [https://git-scm.com/book/en/Getting-Started-Git-Basics Getting Started - Git Basics].
{{Deletion|Entire section regurgitates the upstream documentation, either remove the sections entirely or link to the upstream docs in each subsection.|Talk:Git#Deletion/editing of regurgitated docs}}
{{Style|Use subsections instead of unordered lists, subsections allow people to link directly to the section within the wiki, and spaces out the page better, this can not be done with unordered lists.}}


=== Getting a Git repository ===
=== Getting a Git repository ===
Line 57: Line 73:
:{{ic|git init}}, see {{man|1|git-init}}
:{{ic|git init}}, see {{man|1|git-init}}
* Clone an existing repository
* Clone an existing repository
:{{ic|git clone ''repository''}}, see {{man|1|git-clone}}
:{{ic|git clone ''repository''}}, see {{man|1|git-clone}} (also explains the Git URLs)


=== Recording changes ===
=== Recording changes ===
Line 117: Line 133:
=== Undoing things ===
=== Undoing things ===


* {{ic|git checkout}} - to restore working tree files, see {{man|1|git-checkout}}
* {{ic|git reset}} - reset current HEAD to the specified state, see {{man|1|git-reset}}
* {{ic|git reset}} - reset current HEAD to the specified state, see {{man|1|git-reset}}
* {{ic|git revert}} - revert some existing commits, see {{man|1|git-revert}}


* {{ic|git checkout}} - to restore working tree files, see {{man|1|git-checkout}}
These, along with few others, are further explained at [https://www.atlassian.com/git/tutorials/undoing-changes undoing-changes].
 
For more complex modifications of history, such as {{ic|git commit --amend}} and {{ic|git rebase}} see, for example, [https://www.atlassian.com/git/tutorials/rewriting-history rewriting-history]. It is highly advised not to use such rewrites for commits that were collaborated with other users. Or, at the very least, highly coordinate it in advance.


=== Branching ===
=== Branching ===
{{Expansion|Add links for some common branching models.}}


Fixes and new features are usually tested in branches. When changes are satisfactory they can merged back into the default (master) branch.
Fixes and new features are usually tested in branches. When changes are satisfactory they can merged back into the default (master) branch.
Line 212: Line 234:
  $ git push origin master
  $ git push origin master


If the {{ic|-u}} ({{ic|--set-upstream-to}}) option is used, the location is recorded so the next time just a {{ic|git push}} is necessary.
If the {{ic|-u}} ({{ic|--set-upstream}}) option is used, the location is recorded so the next time just a {{ic|git push}} is necessary.


==== Dealing with merges ====
==== Dealing with merges ====


See [http://git-scm.com/book/en/Git-Branching-Basic-Branching-and-Merging#Basic-Merge-Conflicts Basic Merge Conflicts] in the Git Book for a detailed explanation on how to resolve merge conflicts. Merges are generally reversible. If wanting to back out of a merge one can usually use the {{ic|--abort}} command (e.g. {{ic|git merge --abort}} or {{ic|git pull --abort}}).
See [https://git-scm.com/book/en/Git-Branching-Basic-Branching-and-Merging#Basic-Merge-Conflicts Basic Merge Conflicts] in the Git Book for a detailed explanation on how to resolve merge conflicts. Merges are generally reversible. If wanting to back out of a merge one can usually use the {{ic|--abort}} command (e.g. {{ic|git merge --abort}} or {{ic|git pull --abort}}).


=== History and versioning ===
=== History and versioning ===
Line 312: Line 334:
  $ git config --global diff.tool vimdiff
  $ git config --global diff.tool vimdiff


See {{man|1|git-config}} and [http://git-scm.com/book/en/v2/Customizing-Git-Git-Configuration Git Configuration] for more information.
See {{man|1|git-config}} and [https://git-scm.com/book/en/v2/Customizing-Git-Git-Configuration Git Configuration] for more information.


=== Adopting a good etiquette ===
=== Adopting a good etiquette ===
Line 325: Line 347:
You may wish to avoid the hassle of authenticating interactively at every push to the Git server.
You may wish to avoid the hassle of authenticating interactively at every push to the Git server.


* If you are authenticating with SSH keys, use an [[SSH agent]]. See also [[SSH#Speeding up SSH]] and [[SSH#Keep alive]].
* If you are authenticating with SSH keys, use an [[SSH agent]]. See also [[OpenSSH#Speeding up SSH]] and [[OpenSSH#Keep alive]].
* If you are authenticating with username and password, switch to [[SSH keys]] if the server supports SSH, otherwise try [https://git-scm.com/docs/git-credential-cache git-credential-cache] or [https://git-scm.com/docs/git-credential-store git-credential-store].
* If you are authenticating with username and password, switch to [[SSH keys]] if the server supports SSH, otherwise use git-credential-libsecret credential helper, or try [https://git-scm.com/docs/git-credential-cache git-credential-cache] or [https://git-scm.com/docs/git-credential-store git-credential-store].
 
=== Using git-credential-libsecret as credential-helper ===
 
Git may fetch your credentials from a org.freedesktop.secrets compatible keyring like [[GNOME/Keyring]] or [[KeePassXC]]. Therefore set up one compatible keyring and check if a keyring is registered to dbus using:
 
$ dbus-send --session --print-reply --dest=org.freedesktop.DBus / \
    org.freedesktop.DBus.GetConnectionUnixProcessID \
    string:org.freedesktop.secrets
 
then run
 
$ git config --global credential.helper /usr/lib/git-core/git-credential-libsecret
 
to set up git.
 
=== Using git-credential-netrc as credential-helper ===


=== Protocol Defaults ===
Git can read the [https://www.gnu.org/software/inetutils/manual/html_node/The-_002enetrc-file.html netrc] file to access credentials. First, direct Git to the netrc helper script:


If you are running a multiplexed SSH connection as shown above, Git over SSH might be faster than HTTPS. Also, some servers (like the AUR) only allow pushing via SSH. For example, the following config will set Git over SSH for any repository hosted on the AUR.
$ git config --global credential.helper /usr/share/git/credential/netrc/git-credential-netrc.perl
 
Then, [[create]] a {{ic|.netrc}} file:
 
{{hc|~/.netrc|
machine git-host
login username
password password
}}
 
The credential helper also supports [[gpg]]-encrypted files ({{ic|~/.netrc.gpg}}) if you like to keep your secrets safe.
 
=== Protocol defaults ===
 
If you are running a multiplexed SSH connection as shown above, Git over SSH might be faster than HTTPS. Also, some servers (like the AUR) only allow pushing via SSH. For example, the following configuration will set Git over SSH for any repository hosted on the AUR.


{{hc|~/.gitconfig|<nowiki>
{{hc|~/.gitconfig|<nowiki>
[url "ssh://aur@aur.archlinux.org/"]
[url "ssh://aur@aur.archlinux.org/"]
insteadOf &#61; https://aur.archlinux.org/
insteadOf = https://aur.archlinux.org/
insteadOf &#61; http://aur.archlinux.org/
insteadOf = http://aur.archlinux.org/
insteadOf &#61; git://aur.archlinux.org/
insteadOf = git://aur.archlinux.org/
</nowiki>}}
</nowiki>}}


=== Bash completion ===
=== Bash completion ===


In order to enable Bash completion, source {{ic|/usr/share/git/completion/git-completion.bash}} in a [[Bash#Configuration_files|Bash startup file]]. Alternatively, install {{pkg|bash-completion}}.
In order to enable Bash completion, source {{ic|/usr/share/git/completion/git-completion.bash}} in a [[Bash#Configuration files|Bash startup file]]. Alternatively, install {{pkg|bash-completion}}.


=== Git prompt ===
=== Git prompt ===
Line 350: Line 402:
* For [[zsh]]: {{ic|1=setopt PROMPT_SUBST ; PS1='[%n@%m %c$(__git_ps1 " (%s)")]\$ '}}
* For [[zsh]]: {{ic|1=setopt PROMPT_SUBST ; PS1='[%n@%m %c$(__git_ps1 " (%s)")]\$ '}}


To automate this see [[Command-line shell#Configuration files]].
Note that the command substitution must be escaped, see [[Bash/Prompt customization#Embedding commands]] for details. See [[Command-line shell#Configuration files]] for persistent configuration.


When changing to a directory of a Git repository, the prompt will change to show the branch name. Extra details can be set to be shown by the prompt:
When changing to a directory of a Git repository, the prompt will change to show the branch name. Extra details can be set to be shown by the prompt by setting the corresponding environment variable:


{| class="wikitable"
{| class="wikitable"
Line 358: Line 410:
  ! Shell variable !! Information
  ! Shell variable !! Information
  |-
  |-
  | GIT_PS1_SHOWDIRTYSTATE    || '''+''' for staged, '''*''' if unstaged.  
  | GIT_PS1_SHOWDIRTYSTATE    || {{ic|+}} for staged, {{ic|*}} if unstaged.
|-
| GIT_PS1_SHOWSTASHSTATE    || {{ic|$}} if something is stashed.
|-
| GIT_PS1_SHOWUNTRACKEDFILES || {{ic|%}} if there are untracked files.
  |-
  |-
  | GIT_PS1_SHOWSTASHSTATE    || '''$''' if something is stashed.
  | GIT_PS1_SHOWUPSTREAM      || {{ic|<}}, {{ic|>}}, {{ic|<>}} behind, ahead, or diverged from upstream.
  |-
  |-
  | GIT_PS1_SHOWUNTRACKEDFILES || '''%''' if there are untracked files.
  | GIT_PS1_STATESEPARATOR    || separator between branch name and state symbols
  |-
  |-
  | GIT_PS1_SHOWUPSTREAM      || '''<,>,<>''' behind, ahead, or diverged from upstream.
  | GIT_PS1_DESCRIBE_STYLE    || show commit relative to tag or branch, when detached HEAD
|-
| GIT_PS1_SHOWCOLORHINTS    || display in color
  |}
  |}


{{ic|GIT_PS1_SHOWUPSTREAM}} will need to be set to {{ic|auto}} for changes to take effect.
The full documentation for the environment variables is available in the comments of the script.


{{Note|If you experience that {{ic|$(__git_ps1)}} returns {{ic|((unknown))}}, then there is a {{ic|.git}} folder in your current directory which does not contain any repository, and therefore Git does not recognize it. This can, for example, happen if you mistake Git's configuration file to be {{ic|~/.git/config}} instead of {{ic|~/.gitconfig}}.}}
{{Note|
* If you experience that {{ic|$(__git_ps1)}} returns {{ic|((unknown))}}, then there is a {{ic|.git}} folder in your current directory which does not contain any repository, and therefore Git does not recognize it. This can, for example, happen if you mistake Git's configuration file to be {{ic|~/.git/config}} instead of {{ic|~/.gitconfig}}.
* If your prompt is experiencing delays with very large repositories, it is likely due to the {{ic|GIT_PS1_SHOWUNTRACKEDFILES}} option, which triggers a full directory tree scan every time to detect new files, causing noticeable performance impact. To disable this option locally for those repositories, you can use the command {{ic|git config --local bash.showUntrackedFiles false}}.
}}


Alternatively, you can use one of git shell prompt customization packages from [[AUR]] such as {{AUR|bash-git-prompt}} or {{AUR|gittify}}.
Alternatively, you can use one of git shell prompt customization packages from [[AUR]] such as {{AUR|bash-git-prompt}} or {{AUR|gittify}}.
Line 396: Line 457:


  $ git remote set-url origin git@''address'':''user''/''repo''.git
  $ git remote set-url origin git@''address'':''user''/''repo''.git
Alternatively, edit {{ic|.git/config}} with the new location.


Signed-off-by line append (a name-email signature is added to the commit which is required by some projects):
Signed-off-by line append (a name-email signature is added to the commit which is required by some projects):
Line 413: Line 476:
Git allows commits and tags to be signed using [[GnuPG]], see [https://git-scm.com/book/en/Git-Tools-Signing-Your-Work Signing Your Work].
Git allows commits and tags to be signed using [[GnuPG]], see [https://git-scm.com/book/en/Git-Tools-Signing-Your-Work Signing Your Work].


{{Note|To use {{Pkg|pinentry}} curses for GPG signing make sure to {{ic|1=export GPG_TTY=$(tty)}} (alternatively use pinentry-tty) otherwise the signing step will fail if GPG is currently in a locked state (since it cannot prompt for pin).}}
{{Note|To use [[pinentry]] curses for GPG signing make sure to {{ic|1=export GPG_TTY=$(tty)}} (alternatively use pinentry-tty) otherwise the signing step will fail if GPG is currently in a locked state (since it cannot prompt for pin).}}


To configure Git to automatically sign commits:
To configure Git to automatically sign commits:
Line 434: Line 497:
=== Directly sending patches to a mailing list ===
=== Directly sending patches to a mailing list ===


If you want to send patches directly to a mailing list, you have to install the following packages: {{Pkg|perl-authen-sasl}}, {{Pkg|perl-net-smtp-ssl}} and {{Pkg|perl-mime-tools}}.
If you want to send patches directly to a mailing list, you have to install the following packages: {{Pkg|perl-authen-sasl}} and {{Pkg|perl-io-socket-ssl}}.


Make sure you have configured your username and e-mail address, see [[#Configuration]].
Make sure you have configured your username and e-mail address, see [[#Configuration]].
Line 441: Line 504:


  $ git config --global sendemail.smtpserver ''smtp.example.com''
  $ git config --global sendemail.smtpserver ''smtp.example.com''
  $ git config --global sendemail.smtpserverport ''587''
  $ git config --global sendemail.smtpserverport ''465''
  $ git config --global sendemail.smtpencryption ''tls''
  $ git config --global sendemail.smtpencryption ''ssl''
  $ git config --global sendemail.smtpuser ''foobar@example.com''
  $ git config --global sendemail.smtpuser ''foobar@example.com''


Now you should be able to send the patch to the mailing list (see also [http://www.openembedded.org/wiki/How_to_submit_a_patch_to_OpenEmbedded#Sending_patches OpenEmbedded:How to submit a patch to OpenEmbedded#Sending patches]):
Now you should be able to send the patch to the mailing list (see also [https://www.openembedded.org/wiki/How_to_submit_a_patch_to_OpenEmbedded#Sending_patches OpenEmbedded:How to submit a patch to OpenEmbedded#Sending patches] and [https://git-send-email.io/ git-send-email.io]):


  $ git add ''filename''
  $ git add ''filename''
  $ git commit -s
  $ git commit -s
  $ git send-email --to=''openembedded-core@lists.openembedded.org'' --confirm=always -M -1
  $ git send-email --to=''pacman-contrib@lists.archlinux.org'' --confirm=always -M -1


=== When the remote repo is huge ===
=== Working with a large git repository ===


{{Style|Uses informal language, contractions, HTML tags instead of code templates and does not use interwiki links.}}
When working with a large remote repository, a significant amount of data has to be fetched. The following examples use the Linux kernel to illustrate how to work with such codebases.


When the remote repo is huge, what can you do? See this section. The examples are taken from the linux kernel.
==== Fetching the entire repository ====


==== Simplest way: fetch the entire repo ====
The easiest solution is to get the entire repository:
You can get the entire repository by


  $ git clone git://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git
  $ git clone git://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git


This download takes long - "git clone" can not be resumed once it's stopped, as of Aug 2018 - and it'll cost some HDD space.  
{{Note|{{ic|git clone}} cannot be resumed if interrupted.}}
 
You can update your repository by {{ic|git pull}}.
 
==== Partially fetching the repository ====


You can update your repo by
To limit your local repository to a smaller subset of the origin, say after v4.14 to bisect a bug, use a shallow clone:
$ git pull
==== Partial fetch ====
Probably you want to limit your local repository smaller, say after v4.14 to bisect a bug. Then do:


  $ git clone --shallow-exclude v4.13   git://git.kernel.org/pub/scm/linux/kernel/git/stable/linux-stable.git # You'll get v4.14 and later, but not v4.13 and older.
  $ git clone --shallow-exclude v4.13 git://git.kernel.org/pub/scm/linux/kernel/git/stable/linux-stable.git


Or maybe you only want the latest snapshot, ignoring all history. (If a tarball is available and it suffices, choose that. Getting a git repo costs more.) You can do it by:
You will get v4.14 and later, but not v4.13 and older.
 
If you only want the latest snapshot, ignoring all history. (If a tarball is available and it suffices, choose that. Downloading from a git repository needs more bandwidth.) You can get it with:


  $ git clone --depth 1 git://git.kernel.org/pub/scm/linux/kernel/git/stable/linux-stable.git
  $ git clone --depth 1 git://git.kernel.org/pub/scm/linux/kernel/git/stable/linux-stable.git


You can later obtain older commits, by e.g.
You can later obtain older commits, as the two following examples show:


  $ git fetch --tags --shallow-exclude v4.1 # Get the commits after v4.1.
  $ git fetch --tags --shallow-exclude v4.1
  $ git fetch --tags --shallow-since 2016-01-01
  $ git fetch --tags --shallow-since 2016-01-01


Without <code>--tags</code>, tags won't be fetched.
{{Note|Without {{ic|--tags}}, tags will not be fetched.}}


==== Get other branches ====
==== Getting other branches ====
Your local repo tracks, in the above example, only the mainline kernel, i.e. in which the ''latest development is done''. Suppose you want the latest ''LTS'', for example the up-to-date 4.14 branch. You can get it by:
 
Your local repository tracks, in the above example, only the mainline kernel, i.e. in which the ''latest development is done''. Suppose you want the latest ''LTS'', for example the up-to-date 4.14 branch. You can get it by:


  $ git remote set-branches --add origin linux-4.17.y
  $ git remote set-branches --add origin linux-4.17.y
Line 489: Line 555:
  $ git branch --track linux-4.17.y origin/linux-4.17.y
  $ git branch --track linux-4.17.y origin/linux-4.17.y


The last line is not mandatory, but probably you want it.
The last line is not mandatory, but probably wanted.
(To know the name of the branch you want, sorry, there's no general rule. You can guess one by seeing the "ref" link in the gitweb interface.)
(To know the name of the branch you want, there is no general rule. You can guess one by seeing the "ref" link in the gitweb interface.)


If you want the snapshot of linux-4.17.y, do
For the snapshot of linux-4.17.y, do


  $ git checkout -b linux-4.17.y
  $ git checkout -b linux-4.17.y
Line 498: Line 564:
Or to extract it in another directory,
Or to extract it in another directory,


  $ mkdir /foo/bar/src-4.17; cd /foo/bar/src-4.17
  $ mkdir /path/to/src-4.17; cd /path/to /src-4.17
  $ git clone --no-local --depth 1 -b linux-4.17.y  ../linux-stable
  $ git clone --no-local --depth 1 -b linux-4.17.y  ../linux-stable


As usual, do <code>git pull</code> to update your snapshot.
As usual, do {{ic|git pull}} to update your snapshot.


==== Possilbe Future alternative ====
==== Possible alternative ====
Git Virtual Filesystem (GVFS), developed by Microsoft, allows you to access git repositories without a local one. (See [https://blogs.msdn.microsoft.com/bharry/2017/05/24/the-largest-git-repo-on-the-planet/ this Microsoft blog] or the [[wikipedia:Git_Virtual_File_System|Wikipedia artcile]].) It's not available in Linux yet.


Anyway it is not for the above examples of the Linux kernel, though.
Virtual File System for Git (VFS for Git), allows to access git repositories without a local one. (See [https://blogs.msdn.microsoft.com/bharry/2017/05/24/the-largest-git-repo-on-the-planet/ this Microsoft blog] or the [[wikipedia:Virtual File System for Git|Wikipedia article]].)


== Git server ==
It already has a successor : [https://github.com/microsoft/scalar Scalar], which is available in {{AUR|git-vfs}}{{Broken package link|package not found}}, Microsoft's fork of git including gvfs and scalar.


How to set up connecting to repositories using varying protocols.
=== Filtering confidential information ===


=== SSH ===
Occasionally, software may keep plain-text passwords in configuration files, as opposed to hooking into a keyring. In these cases, git clean-filters may be handy to avoid accidentally commiting confidential information. E. g., the following file assigns a filter to the file “some-dotfile”:


To use the SSH protocol, first set up a public SSH key; for that follow the guide at [[SSH keys]]. To set up a SSH server, follow the [[SSH]] guide.
{{hc|.gitattributes|<nowiki>
some-dotfile filter=remove-pass
</nowiki>}}


With SSH working and a key generated, paste the contents of {{ic|~/.ssh/id_rsa.pub}} to {{ic|~/.ssh/authorized_keys}} (be sure it is all on one line). Now the Git repository can be accessed with SSH by doing:
Whenever the file “some-dotfile” is checked into git, git will invoke the filter “remove-pass” on the file before checking it in. The filter must be defined in the git-configuration file, e. g.:


$ git clone ''user''@''foobar.com'':''my_repository''.git
{{hc|.git/config|<nowiki>
 
[filter "remove-pass"]
You should now get an SSH yes/no question, if you have the SSH client setting {{ic|StrictHostKeyChecking}} set to {{ic|ask}} (the default). Type {{ic|yes}} followed by {{ic|Enter}}. Then you should have your repository checked out. Because this is with SSH, you also have commit rights now.
clean = "sed -e 's/^password=.*/#password=TODO/'"
 
</nowiki>}}
To modify an existing repository to use SSH, the remote location will need to be redefined:
 
$ git remote set-url origin git@localhost:''my_repository''.git
 
Connecting on a port other than 22 can be configured on a per-host basis in {{ic|/etc/ssh/ssh_config}} or {{ic|~/.ssh/config}}. To set up ports for a repository (here 443 as example):
 
{{hc|.git/config|2=
[remote "origin"]
    url = ssh://''user''@''foobar''.com:443/~''my_repository''/repo.git
}}
 
You are able to secure the SSH user account even more allowing only push and pull commands on this user account. This is done by replacing the default login shell by git-shell. Described in [https://git-scm.com/book/en/v2/Git-on-the-Server-Setting-Up-the-Server Setting Up the Server].
 
=== Smart HTTP ===
 
Git is able to use the HTTP(S) protocol as efficiently as the SSH or Git protocols, by utilizing the git-http-backend. Furthermore it is not only possible to clone or pull from repositories, but also to push into repositories over HTTP(S).
 
The setup for this is rather simple as all you need to have installed is the Apache web server ({{pkg|apache}}, with {{ic|mod_cgi}}, {{ic|mod_alias}}, and {{ic|mod_env}} enabled) and of course, {{pkg|git}}.
 
Once you have your basic setup running, add the following to your Apache configuration file, which is usually located at:
 
{{hc|/etc/httpd/conf/httpd.conf|
<Directory "/usr/lib/git-core*">
    Require all granted
</Directory>
SetEnv GIT_PROJECT_ROOT /srv/git
SetEnv GIT_HTTP_EXPORT_ALL
ScriptAlias /git/ /usr/lib/git-core/git-http-backend/
}}
 
This assumes your Git repositories are located at {{ic|/srv/git}} and that you want to access them via something like: {{ic|<nowiki>http(s)://your_address.tld/git/your_repo.git</nowiki>}}.
 
{{Note|Make sure that Apache can read and write to your repositories.}}
 
For more detailed documentation, visit the following links:
* https://git-scm.com/book/en/v2/Git-on-the-Server-Smart-HTTP
* https://git-scm.com/docs/git-http-backend
 
=== Git ===
 
{{Note|The Git protocol is not encrypted or authenticated, and only allows read access.}}


[[start|Start and enable]] {{ic|git-daemon.socket}}.
{{Note|Escaping special characters for sed expressions can be a [https://stackoverflow.com/questions/49652495/git-filter-and-sed-fight-over tricky task] in this context. Remember that git is turning two backslashes into one, while the shell that git invokes to run commands will again turn two backslashes into one. For more details, see [https://stackoverflow.com/a/49654653 Git filter and sed fight over `\$`].}}


The daemon is started with the following options:
=== HTML help files ===


ExecStart=-/usr/lib/git-core/git-daemon --inetd --export-all --base-path=/srv/git
The {{ic|git help}} documentation is also available in HTML form by installing {{AUR|git-htmldocs}}. After installing, the HTML docs can be accessed by passing the {{ic|-w}} flag. For example:


Repositories placed in {{ic|/srv/git/}} will be recognized by the daemon.  Clients can connect with something similar to:
$ git help -w merge


$ git clone git://''location''/''repository''.git
The HTML documentation can be loaded by default by setting a {{ic|git config}} option:


=== Setting access rights ===
$ git config --global help.format html


To restrict read and/or write access, use standard Unix permissions. Refer to
== Extensions ==
[https://github.com/sitaramc/gitolite/blob/d74e58b5de8c78bddd29b009ba2d606f7fcb4f2d/doc/overkill.mkd when gitolite is overkill] for more information.


For fine-grained access management, refer to [[gitolite]] and [[gitosis]].
* {{App|gitflow-avh|Extend git with [https://nvie.com/posts/a-successful-git-branching-model/ Vincent Driessen's branching model]. The AVH Edition adds more functionality.|https://github.com/petervanderdoes/gitflow|{{AUR|gitflow-avh}}}}
* {{App|git-extras|some utilities for git (repo summary, repl,changelog population, author commit percentages, etc.)|https://github.com/tj/git-extras|{{AUR|git-extras}}}} -  If you're using [https://ohmyz.sh oh-my-zsh], you may also enable [https://github.com/ohmyzsh/ohmyzsh/tree/master/plugins/git-extras git-extras plugin]
* {{App|gitmoji-cli|A [https://gitmoji.dev/ gitmoji] interactive NodeJS client for using gitmojis on commit messages.|https://github.com/carloscuesta/gitmoji-cli|{{AUR|nodejs-gitmoji-cli}}}}


== See also ==
== See also ==
Line 587: Line 613:
* [https://git-scm.com/book/en/ Pro Git book]
* [https://git-scm.com/book/en/ Pro Git book]
* [https://git.github.io/git-reference/ Git Reference] by GitHub
* [https://git.github.io/git-reference/ Git Reference] by GitHub
* [http://nathanhoad.net/git-workflow-forks-remotes-and-pull-requests Git workflow: Forks, remotes, and pull requests]
* [https://web.archive.org/web/20150316035247/https://nathanhoad.net/git-workflow-forks-remotes-and-pull-requests Git workflow: Forks, remotes, and pull requests]
* [https://wiki.videolan.org/Git VideoLAN wiki article]
* [https://wiki.videolan.org/Git VideoLAN wiki article]
* [https://gist.github.com/grawity/4392747 A comparison of protocols GitHubGist]
* [https://gist.github.com/grawity/4392747 A comparison of protocols GitHubGist]{{Dead link|2023|04|23|status=404}}
* [https://gun.io/blog/how-to-github-fork-branch-and-pull-request How to GitHub]
* [https://gun.io/blog/how-to-github-fork-branch-and-pull-request How to GitHub]

Latest revision as of 20:30, 27 February 2024

"I've met people who thought git is a front-end to GitHub. They were wrong, git is a front-end to the AUR." — Linus T.

Git is the version control system (VCS) designed and developed by Linus Torvalds, the creator of the Linux kernel. Git is now used to maintain AUR packages, as well as many other projects, including sources for the Linux kernel.

Installation

Install the git package. For the development version, install the git-gitAUR package. Check the optional dependencies when using tools such as git svn, git gui and gitk.

Graphical front-ends

See also git GUI Clients.

  • Giggle — GTK frontend for git.
https://wiki.gnome.org/Apps/giggle/ || giggle
  • GitAhead — Graphical git client including a built-in Merge Tool.
https://gitahead.github.io/gitahead.com/ || gitaheadAUR
  • Git Cola — Sleek and powerful graphical user interface for Git written in Python.
https://git-cola.github.io/ || git-colaAUR
  • Git Extensions — Graphical user interface for Git that allows you to control Git without using the commandline.
https://gitextensions.github.io/ || gitextensionsAUR
  • gitg — GNOME GUI client to view git repositories. Part of gnome-extra.
https://wiki.gnome.org/Apps/Gitg || gitg
  • git-gui — Tcl/Tk based portable graphical interface to Git.
https://git-scm.com/docs/git-gui || git + tk
Note: To enable spell checking in git-gui, aspell is required, along with the dictionary corresponding to the LC_MESSAGES environment variable. See FS#28181 and the aspell article.
  • GitHub Desktop — Electron-based graphical user interface built by the GitHub team.
https://github.com/desktop/desktop || github-desktopAUR github-desktop-binAUR
  • gitk — Tcl/Tk based Git repository browser.
https://git-scm.com/docs/gitk || git + tk
  • Gittyup — Qt based Git client.
https://github.com/Murmele/Gittyup || gittyupAUR
  • Guitar — Git GUI Client.
https://github.com/soramimi/Guitar || guitarAUR
  • gitui — fast terminal-ui for git written in rust.
https://github.com/extrawurst/gitui || gitui
  • lazygit — simple terminal UI for git commands.
https://github.com/jesseduffield/lazygit || lazygit
  • QGit — Git GUI viewer to browse revisions history, view patch content and changed files, graphically following different development branches.
https://github.com/tibirna/qgit || qgit
  • RabbitVCS — Set of graphical tools written to provide simple and straightforward access to the version control systems you use.
http://rabbitvcs.org/ || rabbitvcsAUR
  • Sublime Merge — Git Client from the makers of Sublime Text.
https://www.sublimemerge.com/ || sublime-mergeAUR
  • Tig — ncurses-based text-mode interface for git.
https://jonas.github.io/tig/ || tig
  • ungit — Brings user friendliness to git without sacrificing the versatility of git.
https://github.com/FredrikNoren/ungit || nodejs-ungitAUR

Configuration

In order to use Git you need to set at least a name and email:

$ git config --global user.name  "John Doe"
$ git config --global user.email "johndoe@example.com"

See Getting Started - First-Time Git Setup.

See #Tips and tricks for more settings.

Usage

A Git repository is contained in a .git directory, which holds the revision history and other metadata. The directory tracked by the repository, by default the parent directory, is called the working directory. Changes in the working tree need to be staged before they can be recorded (committed) to the repository. Git also lets you restore, previously committed, working tree files.

See Getting Started - Git Basics.

This article or section is being considered for removal.

Reason: Entire section regurgitates the upstream documentation, either remove the sections entirely or link to the upstream docs in each subsection. (Discuss in Talk:Git#Deletion/editing of regurgitated docs)

This article or section needs language, wiki syntax or style improvements. See Help:Style for reference.

Reason: Use subsections instead of unordered lists, subsections allow people to link directly to the section within the wiki, and spaces out the page better, this can not be done with unordered lists. (Discuss in Talk:Git)

Getting a Git repository

  • Initialize a repository
git init, see git-init(1)
  • Clone an existing repository
git clone repository, see git-clone(1) (also explains the Git URLs)

Recording changes

Git projects have a staging area, which is an index file in your Git directory, that stores the changes that will go into your next commit. To record a modified file you therefore firstly need to add it to the index (stage it). The git commit command then stores the current index in a new commit.

Staging changes

  • Add working tree changes to the index
git add pathspec, see git-add(1)
  • Remove changes from the index
git reset pathspec, see git-reset(1)
  • Show changes to be committed, unstaged changes and untracked files
git status, see git-status(1)

You can tell Git to ignore certain untracked files using .gitignore files, see gitignore(5).

Git does not track file movement. Move detection during merges is based only on content similarity. The git mv command is just there for convenience and is equivalent to:

$ mv -i foo bar
$ git reset -- foo
$ git add bar

Committing changes

The git commit command records the staged changes to the repository, see git-commit(1).

  • -m – supply the commit message as an argument, instead of composing it in your default text editor
  • -a – automatically stage files that have been modified or deleted (does not add untracked files)
  • --amend – redo the last commit, amending the commit message or the committed files
Tip: Always commit small changes frequently and with meaningful messages.

Revision selection

Git offers multiple ways to specify revisions, see gitrevisions(7) and Revision Selection.

Many Git commands take revisions as arguments. A commit can be identified by any of the following:

  • SHA-1 hash of the commit (the first 7 digits are usually sufficient to identify it uniquely)
  • Any commit label such as a branch or tag name
  • The label HEAD always refers to the currently checked-out commit (usually the head of the branch, unless you used git checkout to jump back in history to an old commit)
  • Any of the above plus ~ to refer to previous commits. For example, HEAD~ refers to one commit before HEAD and HEAD~5 refers to five commits before HEAD.

Viewing changes

Show differences between commits:

$ git diff HEAD HEAD~3

or between staging area and working tree:

$ git diff

View history of changes (where "-N" is the number of latest commits):

$ git log -p (-N)

Undoing things

These, along with few others, are further explained at undoing-changes.

For more complex modifications of history, such as git commit --amend and git rebase see, for example, rewriting-history. It is highly advised not to use such rewrites for commits that were collaborated with other users. Or, at the very least, highly coordinate it in advance.

Branching

This article or section needs expansion.

Reason: Add links for some common branching models. (Discuss in Talk:Git)

Fixes and new features are usually tested in branches. When changes are satisfactory they can merged back into the default (master) branch.

Create a branch, whose name accurately reflects its purpose:

$ git branch help-section-addition

List branches:

$ git branch

Switch branches:

$ git checkout branch

Create and switch:

$ git checkout -b branch

Merge a branch back to the master branch:

$ git checkout master
$ git merge branch

The changes will be merged if they do not conflict. Otherwise, Git will print an error message, and annotate files in the working tree to record the conflicts. The annotations can be displayed with git diff. Conflicts are resolved by editing the files to remove the annotations, and committing the final version. See #Dealing with merges below.

When done with a branch, delete it with:

$ git branch -d branch

Collaboration

A typical Git work-flow is:

  1. Create a new repository or clone a remote one.
  2. Create a branch to make changes; then commit those changes.
  3. Consolidate commits for better organization/understanding.
  4. Merge commits back into the main branch.
  5. (Optional) Push changes to a remote server.

Pull requests

After making and committing some changes, the contributor can ask the original author to merge them. This is called a pull request.

To pull:

$ git pull location master

The pull command combines both fetching and merging. If there are conflicts (e.g. the original author made changes in the same time span), then it will be necessary to manually fix them.

Alternatively, the original author can pick the changes wanting to be incorporated. Using the fetch option (and log option with a special FETCH_HEAD symbol), the contents of the pull request can be viewed before deciding what to do:

$ git fetch location master
$ git log -p HEAD..FETCH_HEAD
$ git merge location master

Using remotes

Remotes are aliases for tracked remote repositories. A label is created defining a location. These labels are used to identify frequently accessed repositories.

Create a remote:

$ git remote add label location

Fetch a remote:

$ git fetch label

Show differences between master and a remote master:

$ git log -p master..label/master

View remotes for the current repository:

$ git remote -v

When defining a remote that is a parent of the fork (the project lead), it is defined as upstream.

Push to a repository

After being given rights from the original authors, push changes with:

$ git push location branch

When git clone is performed, it records the original location and gives it a remote name of origin.

So what typically is done is this:

$ git push origin master

If the -u (--set-upstream) option is used, the location is recorded so the next time just a git push is necessary.

Dealing with merges

See Basic Merge Conflicts in the Git Book for a detailed explanation on how to resolve merge conflicts. Merges are generally reversible. If wanting to back out of a merge one can usually use the --abort command (e.g. git merge --abort or git pull --abort).

History and versioning

Searching the history

git log will give the history with a commit checksum, author, date, and the short message. The checksum is the "object name" of a commit object, typically a 40-character SHA-1 hash.

For history with a long message (where the "checksum" can be truncated, as long as it is unique):

$ git show (checksum)

Search for pattern in tracked files:

$ git grep pattern

Search in .c and .h files:

$ git grep pattern -- '*.[ch]'

Tagging

Tag commits for versioning:

$ git tag 2.14 checksum

Tagging is generally done for releasing/versioning but it can be any string. Generally annotated tags are used, because they get added to the Git database.

Tag the current commit with:

$ git tag -a 2.14 -m "Version 2.14"

List tags:

$ git tag -l

Delete a tag:

$ git tag -d 2.08

Update remote tags:

$ git push --tags

Organizing commits

Before submitting a pull request it may be desirable to consolidate/organize the commits. This is done with the git rebase --interactive option:

$ git rebase -i checksum

This will open the editor with a summary of all the commits in the range specified; in this case including the newest (HEAD) back to, but excluding, commit checksum. Or to use a number notation, use for example HEAD~3, which will rebase the last three commits:

pick d146cc7 Mountpoint test.
pick 4f47712 Explain -o option in readme.
pick 8a4d479 Rename documentation.

Editing the action in the first column will dictate how the rebase will be done. The options are:

  • pick — Apply this commit as is (the default).
  • edit — Edit files and/or commit message.
  • reword — Edit commit message.
  • squash — Merge/fold into previous commit.
  • fixup — Merge/fold into previous commit discarding its message.

The commits can be re-ordered or erased from the history (but be very careful with these). After editing the file, Git will perform the specified actions; if prompted to resolve merge problems, fix them and continue with git rebase --continue or back out with the git rebase --abort command.

Note: Squashing commits is only used for local commits, it will cause troubles on a repository that is shared by other people.

Tips and tricks

Using git-config

Git reads its configuration from four INI-type configuration files:

  • /etc/gitconfig for system-wide defaults
  • ~/.gitconfig and ~/.config/git/config (since 1.7.12) for user-specific configuration
  • .git/config for repository-specific configuration

These files can be edited directly, but the usual method is to use git config, as shown in the examples below.

List the currently set variables:

$ git config {--local,--global,--system} --list

Set the default editor from vim to nano:

$ git config --global core.editor "nano -w"

Set the default push action:

$ git config --global push.default simple

Set a different tool for git difftool (meld by default):

$ git config --global diff.tool vimdiff

See git-config(1) and Git Configuration for more information.

Adopting a good etiquette

  • When considering contributing to an existing project, read and understand its license, as it may excessively limit your ability to change the code. Some licenses can generate disputes over the ownership of the code.
  • Think about the project's community and how well you can fit into it. To get a feeling of the direction of the project, read any documentation and even the log of the repository.
  • When requesting to pull a commit, or submit a patch, keep it small and well documented; this will help the maintainers understand your changes and decide whether to merge them or ask you to make some amendments.
  • If a contribution is rejected, do not get discouraged, it is their project after all. If it is important, discuss the reasoning for the contribution as clearly and as patiently as possible: with such an approach a resolution may eventually be possible.

Speeding up authentication

You may wish to avoid the hassle of authenticating interactively at every push to the Git server.

Using git-credential-libsecret as credential-helper

Git may fetch your credentials from a org.freedesktop.secrets compatible keyring like GNOME/Keyring or KeePassXC. Therefore set up one compatible keyring and check if a keyring is registered to dbus using:

$ dbus-send --session --print-reply --dest=org.freedesktop.DBus / \
    org.freedesktop.DBus.GetConnectionUnixProcessID \
    string:org.freedesktop.secrets

then run

$ git config --global credential.helper /usr/lib/git-core/git-credential-libsecret

to set up git.

Using git-credential-netrc as credential-helper

Git can read the netrc file to access credentials. First, direct Git to the netrc helper script:

$ git config --global credential.helper /usr/share/git/credential/netrc/git-credential-netrc.perl

Then, create a .netrc file:

~/.netrc
machine git-host
login username
password password

The credential helper also supports gpg-encrypted files (~/.netrc.gpg) if you like to keep your secrets safe.

Protocol defaults

If you are running a multiplexed SSH connection as shown above, Git over SSH might be faster than HTTPS. Also, some servers (like the AUR) only allow pushing via SSH. For example, the following configuration will set Git over SSH for any repository hosted on the AUR.

~/.gitconfig
[url "ssh://aur@aur.archlinux.org/"]
	insteadOf = https://aur.archlinux.org/
	insteadOf = http://aur.archlinux.org/
	insteadOf = git://aur.archlinux.org/

Bash completion

In order to enable Bash completion, source /usr/share/git/completion/git-completion.bash in a Bash startup file. Alternatively, install bash-completion.

Git prompt

The Git package comes with a prompt script. To enable it, source the /usr/share/git/completion/git-prompt.sh and set a custom prompt with the %s parameter:

  • For Bash: PS1='[\u@\h \W$(__git_ps1 " (%s)")]\$ '
  • For zsh: setopt PROMPT_SUBST ; PS1='[%n@%m %c$(__git_ps1 " (%s)")]\$ '

Note that the command substitution must be escaped, see Bash/Prompt customization#Embedding commands for details. See Command-line shell#Configuration files for persistent configuration.

When changing to a directory of a Git repository, the prompt will change to show the branch name. Extra details can be set to be shown by the prompt by setting the corresponding environment variable:

Shell variable Information
GIT_PS1_SHOWDIRTYSTATE + for staged, * if unstaged.
GIT_PS1_SHOWSTASHSTATE $ if something is stashed.
GIT_PS1_SHOWUNTRACKEDFILES % if there are untracked files.
GIT_PS1_SHOWUPSTREAM <, >, <> behind, ahead, or diverged from upstream.
GIT_PS1_STATESEPARATOR separator between branch name and state symbols
GIT_PS1_DESCRIBE_STYLE show commit relative to tag or branch, when detached HEAD
GIT_PS1_SHOWCOLORHINTS display in color

The full documentation for the environment variables is available in the comments of the script.

Note:
  • If you experience that $(__git_ps1) returns ((unknown)), then there is a .git folder in your current directory which does not contain any repository, and therefore Git does not recognize it. This can, for example, happen if you mistake Git's configuration file to be ~/.git/config instead of ~/.gitconfig.
  • If your prompt is experiencing delays with very large repositories, it is likely due to the GIT_PS1_SHOWUNTRACKEDFILES option, which triggers a full directory tree scan every time to detect new files, causing noticeable performance impact. To disable this option locally for those repositories, you can use the command git config --local bash.showUntrackedFiles false.

Alternatively, you can use one of git shell prompt customization packages from AUR such as bash-git-promptAUR or gittifyAUR.

Visual representation

To get an idea of the amount of work done:

$ git diff --stat

git log with forking representation:

$ git log --graph --oneline --decorate

git log graph alias (i.e. git graph will show a decorated version):

$ git config --global alias.graph 'log --graph --oneline --decorate'

Commit tips

Reset to previous commit (very dangerous, erases everything to specified commit):

$ git reset --hard HEAD^

If a repository address gets changed, its remote location will need to be updated:

$ git remote set-url origin git@address:user/repo.git

Alternatively, edit .git/config with the new location.

Signed-off-by line append (a name-email signature is added to the commit which is required by some projects):

$ git commit -s

Signed-off-by automatically append to patches (when using git format-patch commit):

$ git config --local format.signoff true

Commit specific parts of files that have changed. This is useful if there are a large number of changes made that would be best split into several commits:

$ git add -p

Signing commits

Git allows commits and tags to be signed using GnuPG, see Signing Your Work.

Note: To use pinentry curses for GPG signing make sure to export GPG_TTY=$(tty) (alternatively use pinentry-tty) otherwise the signing step will fail if GPG is currently in a locked state (since it cannot prompt for pin).

To configure Git to automatically sign commits:

$ git config --global commit.gpgSign true

Working with a non-master branch

Occasionally a maintainer will ask that work be done on a branch. These branches are often called devel or testing. Begin by cloning the repository.

To enter another branch beside master (git clone only shows master branch but others still exist, git branch -a to show):

$ git checkout -b branch origin/branch

Now edit normally; however to keep the repository tree in sync be sure to use both:

$ git pull --all
$ git push --all

Directly sending patches to a mailing list

If you want to send patches directly to a mailing list, you have to install the following packages: perl-authen-sasl and perl-io-socket-ssl.

Make sure you have configured your username and e-mail address, see #Configuration.

Configure your e-mail settings:

$ git config --global sendemail.smtpserver smtp.example.com
$ git config --global sendemail.smtpserverport 465
$ git config --global sendemail.smtpencryption ssl
$ git config --global sendemail.smtpuser foobar@example.com

Now you should be able to send the patch to the mailing list (see also OpenEmbedded:How to submit a patch to OpenEmbedded#Sending patches and git-send-email.io):

$ git add filename
$ git commit -s
$ git send-email --to=pacman-contrib@lists.archlinux.org --confirm=always -M -1

Working with a large git repository

When working with a large remote repository, a significant amount of data has to be fetched. The following examples use the Linux kernel to illustrate how to work with such codebases.

Fetching the entire repository

The easiest solution is to get the entire repository:

$ git clone git://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git
Note: git clone cannot be resumed if interrupted.

You can update your repository by git pull.

Partially fetching the repository

To limit your local repository to a smaller subset of the origin, say after v4.14 to bisect a bug, use a shallow clone:

$ git clone --shallow-exclude v4.13 git://git.kernel.org/pub/scm/linux/kernel/git/stable/linux-stable.git

You will get v4.14 and later, but not v4.13 and older.

If you only want the latest snapshot, ignoring all history. (If a tarball is available and it suffices, choose that. Downloading from a git repository needs more bandwidth.) You can get it with:

$ git clone --depth 1 git://git.kernel.org/pub/scm/linux/kernel/git/stable/linux-stable.git

You can later obtain older commits, as the two following examples show:

$ git fetch --tags --shallow-exclude v4.1
$ git fetch --tags --shallow-since 2016-01-01
Note: Without --tags, tags will not be fetched.

Getting other branches

Your local repository tracks, in the above example, only the mainline kernel, i.e. in which the latest development is done. Suppose you want the latest LTS, for example the up-to-date 4.14 branch. You can get it by:

$ git remote set-branches --add origin linux-4.17.y
$ git fetch
$ git branch --track linux-4.17.y origin/linux-4.17.y

The last line is not mandatory, but probably wanted. (To know the name of the branch you want, there is no general rule. You can guess one by seeing the "ref" link in the gitweb interface.)

For the snapshot of linux-4.17.y, do

$ git checkout -b linux-4.17.y

Or to extract it in another directory,

$ mkdir /path/to/src-4.17; cd /path/to /src-4.17
$ git clone --no-local --depth 1 -b linux-4.17.y  ../linux-stable

As usual, do git pull to update your snapshot.

Possible alternative

Virtual File System for Git (VFS for Git), allows to access git repositories without a local one. (See this Microsoft blog or the Wikipedia article.)

It already has a successor : Scalar, which is available in git-vfsAUR[broken link: package not found], Microsoft's fork of git including gvfs and scalar.

Filtering confidential information

Occasionally, software may keep plain-text passwords in configuration files, as opposed to hooking into a keyring. In these cases, git clean-filters may be handy to avoid accidentally commiting confidential information. E. g., the following file assigns a filter to the file “some-dotfile”:

.gitattributes
some-dotfile filter=remove-pass

Whenever the file “some-dotfile” is checked into git, git will invoke the filter “remove-pass” on the file before checking it in. The filter must be defined in the git-configuration file, e. g.:

.git/config
[filter "remove-pass"]
clean = "sed -e 's/^password=.*/#password=TODO/'"
Note: Escaping special characters for sed expressions can be a tricky task in this context. Remember that git is turning two backslashes into one, while the shell that git invokes to run commands will again turn two backslashes into one. For more details, see Git filter and sed fight over `\$`.

HTML help files

The git help documentation is also available in HTML form by installing git-htmldocsAUR. After installing, the HTML docs can be accessed by passing the -w flag. For example:

$ git help -w merge

The HTML documentation can be loaded by default by setting a git config option:

$ git config --global help.format html

Extensions

https://github.com/petervanderdoes/gitflow || gitflow-avhAUR
  • git-extras — some utilities for git (repo summary, repl,changelog population, author commit percentages, etc.)
https://github.com/tj/git-extras || git-extrasAUR - If you're using oh-my-zsh, you may also enable git-extras plugin
  • gitmoji-cli — A gitmoji interactive NodeJS client for using gitmojis on commit messages.
https://github.com/carloscuesta/gitmoji-cli || nodejs-gitmoji-cliAUR

See also