Customizing and Extending Git
local graph
Chapter 13 — Customizing and Extending Git
Section titled “Chapter 13 — Customizing and Extending Git”Earlier chapters were designed to help you understand how Git works and master Git as a version control system. The following two chapters will help you set up and configure Git, so that you can use it more effectively for yourself (this chapter) and help other developers use it (the next chapter).
This chapter will cover configuring and extending Git to fit one’s needs. First, it will show how to set up a Git command line to make it easier to use. For some tasks, though it is easier to use visual tools; the short introduction to graphical interfaces in this chapter should help you in choosing one. Next, there will be an explanation of how to change and configure Git behavior, from configuration files (with the selected configuration options described) to a per-file configuration with the .``gitattributes file.
Then this chapter will cover how to automate Git with hooks, describing for example how to make Git check whether the commit being created passes coding guidelines for a project. This part will focus on the client-side hook, and will only touch upon the server-side hooks— those are left for Chapter 14, Git Administration. The last part of the chapter will describe how to extend Git, from the Git command aliases, through integrating new user-visible commands, to helpers and drivers (new backend abilities).
Many issues, such as gitattributes, remote and credential helpers, and the basics of the Git configuration should be known from the previous chapters. This chapter will gather this information in a single place, and expand it a bit.
In this chapter, we will cover the following topics:
- Setting up the shell prompt and Tab completion for a command line
- Types and examples of graphical user interfaces
- Configuration files and basic configuration options
- Installing and using various types of hooks
- Simple and complex aliases
- Extending Git with new commands and helpers
Git on the command line
Section titled “Git on the command line”There are a lot of different ways to use the Git version control system. There are many graphical user interfaces (GUIs) of varying use cases and capabilities, and there exist tools and plugins that allow integration with an integrated development environment (IDE) or a file manager.
However, the command line is the only place you can run all of the Git commands and which provides support for all their options. New features, which you might want to use, are developed for the command line first. Also, most of the GUIs implement only some subsets of the Git functionality. Mastering the command line always guarantees a deep understanding of tools, mechanisms, and their abilities. Just knowing how to use a GUI is probably not enough to get a founded knowledge.
Whether you use Git on a command line from choice, as a preferred environment, or you need it because it is the only way to access the required functionality, there are a few shell features that Git can tap into to make your experience a lot friendlier.
Git-aware command prompt
Section titled “Git-aware command prompt”It’s useful to customize your shell prompt to show information about the state of the Git repository we are in.
Definition
The shell prompt is a short text message that is written to the terminal or the console output to notify the user of the interactive shell that some typed input is expected (usually a shell command).
This information can be as simple or as complex as you want. Git’s prompt might be similar to the ordinary command-line prompt (to reduce dissonance), or visibly different (to be able to easily distinguish that we are inside the Git repository).
There is an example implementation for bash and zsh shells in the contrib/ area. If you install Git from the sources, just copy the contrib/completion/git-prompt.sh file to your home directory; if you have installed Git on Linux via a package manager, you will probably have it at /etc/bash_completion.d/git-prompt.sh. This file provides the __git_ps1 shell function to generate a Git-aware prompt in the Git repositories, but first, you need to source this file in your .bashrc or .zshrc shell configuration file:
if [ -f /etc/bash_completion.d/git-prompt.sh ]; then source /etc/bash_completion.d/git-prompt.shfiThe shell prompt is configured using environment variables. To set up a prompt, you must change, directly or indirectly, the PS1 (prompt string one, the default interaction prompt) environment variable. Thus, one solution to create a Git-aware command prompt is to include a call to the __git_ps1 shell function in the PS1 environment variable, by using command substitution:
export PS1='\u@\h:\w$( git_ps1 " (%s)")\$ 'Note that, for zsh, you would also need to turn on the command substitution in the shell prompt with the setopt PROMPT_SUBST command.
Alternatively, for a slightly faster prompt and the possibility of color, you can use __git_ps1 to set PS1. This is done with the PROMPT_COMMAND environment variable in bash and with the precmd() function in zsh. You can find more information about this option in the comments in the git-prompt.sh file; for bash, it could be the following:
PROMPT_COMMAND='__git_ps1 "\\u@\\h:\\w" "\\\$ "'With this configuration (either solution), the prompt will look as follows:
[email protected]:~/random/src (master)$The Git Bash command from Git for Windows comes out of the box with a similar prompt configured (though the Git Bash default prompt takes two lines, not one).
The bash and zsh shell prompts can be customized with the use of special characters that get expanded by a shell. In the example used here (you can find more for example in the Bash Reference Manual), we have the following:
\umeans the current user (bob)\his the current hostname (host.company.org)\wmeans the current working directory (~/random/src)\$prints the $ part of the prompt (# if you are logged in as the root user)
$(...) in the PS1 setup is used to call external commands and shell functions. __git_ps1 " (%s)" here calls the git_ps1 shell function provided by git-prompt.sh with a formatting argument: the %s token is the placeholder for the presented Git status. Note that you need to either use single quotes while setting the PS1 variable from the command line, as in the example shown here, or escape shell substitution, so it is expanded while showing the prompt and not while defining the variable.
If you are using the __git_ps1 function, Git will also display information about the current ongoing multistep operation: merging, rebasing, bisecting, and so on. For example, during an interactive rebase (-i) on the branch master, the relevant part of the prompt would be master|REBASE-i. It is very useful to have this information right here in the command prompt, especially if you get interrupted in the middle of the operation.
It is also possible to indicate in the command prompt the state of the working tree, the index, and so on. We can enable these features by exporting the selected subset of these environment variables (for some features you can additionally turn it off on a per-repository basis with provided boolean-valued configuration variables):
GIT_PS1_SHOWDIRTYSTATE(withbash.showDirtyStatefor per-repository settings) shows “ * ” for unstaged changes and “ + ” for staged changes, if set to a non-empty value.GIT_PS1_SHOWSTASHSTATEshows “ $ ” if something is stashed.GIT_PS1_SHOWUNTRACKEDFILESandbash.showUntrackedFilesshow “ % ” if there are untracked files in the working directory.GIT_PS1_SHOWUPSTREAMandbash.showUpstreamcan be used to configure the ahead-behind state of the upstream repository, with a value ofautoin a space-separated list of values makes the prompt show whether you are behind “ < ”, up to date “ = ”, or ahead “ > ” of the upstream,nameshows the upstream name, andverbosedetails the number of commits you are ahead/behind (with sign; for example “+1” for being 1 commit ahead).gitcompares HEAD to@{upstream}andsvnto the SVN upstream.GIT_PS1_DESCRIBE_STYLEcan be set to configure how to show information about a detached HEAD situation; it can be set to one of the following values:containsuses newer annotated tags (v1.6.3.235),4),branchuses newer tag or branch (maindescribeuses the older annotated tag (v1.6.3.1-13-gdd42c2f),taguses any tag,defaultshows tag only if it is exactly matching the current commit.GIT_PS1_SHOWCONFLICTSTATEset to “yes” will notify the user if there are unresolved conflicts with |CONFLICT.GIT_PS1_SHOWCOLORHINTScan be used to configure colored hints about the current dirty state, that is about whether there are uncommitted changes (likegit status -sbdoes).GIT_PS1_HIDE_IF_PWD_IGNOREDorbash.hideIfPwdIgnoredare used to not show a Git-aware prompt if the current directory is set to be ignored by Git, even if we are inside a repository.
If you are using the zsh shell, you can take a look at the zsh-git set of scripts, the zshkit configuration scripts, or the oh-my-zsh framework available for zsh, instead of using bash —first complete the prompt setup from the Git contrib/. Alternatively, you can use the vcs_info subsystem built in to zsh.
There are also alternative prompt solutions for bash (usually for multiple different shells), for example, git-radar or powerline-shell.
Tip
You can, of course, generate your own Git-aware prompt. For example, you might want to split the current directory into the repository path part and the project subdirectory path part with the help of the git rev-parse command.
Command-line completion for Git
Section titled “Command-line completion for Git”Another shell feature that makes it easier to work with the Git command line is the programmable command-line completion. This feature can dramatically speed up typing Git commands. Command-line completion allows you to type the first few characters of a command, or a filename, and press the completion key (usually Tab) to fill the rest of the item. With the Git-aware completion, you can also fill in subcommands, command-line parameters, remotes, branches, and tags (ref names), each only where appropriate (for example, remote names are completed only if the command expects the remote name at a given position).
Git comes with built-in (but not always installed) support for the auto-completion of Git commands for the bash and zsh shells.
For bash, if the completion functionality is not installed with Git (at /etc/bash_completion.d/git.sh in Linux by default), you need to get a copy of the contrib/completion/git-completion.bash file out of the Git source code. Copy it somewhere accessible, such as your home directory, and source it from your .bashrc or .bash_profile:
. ~/git-completion.bashOnce the completion for Git is enabled, to test it, you can start to type a Git command, then press the Tab key. For example, you can type git check and then press Tab:
$ git check<TAB>With Git completion enabled, the bash (or zsh) shell would autocomplete what you entered so far to git checkout.
Similarly, in an ambiguous case, a double Tab press shows all the possible completions (though this is not true for all shells; some instead cycle through different completions):
$ git che<TAB><TAB>checkout cherry cherry-pickThe completion feature also works with options; this is quite useful if you don’t remember the exact option but only the prefix:
$ git config --<TAB><TAB>--add --get-regexp --remove-section --unset[…]Important note
Instead of the list of possible completions, some shells use (or can be configured to use) rotating completion, where with multiple possible completions, each Tab shows a different completion for the same prefix (cycling through them).
Note that command-line completion (also called tab completion) generally works only in the interactive mode, and is based on the unambiguous prefix, not on the unambiguous abbreviation.
Autocorrection for Git commands
Section titled “Autocorrection for Git commands”An unrelated built-in Git tool, but similar to tab completion, is autocorrection. By default, if you type something that looks like a mistyped command, Git helpfully tries to figure out what you meant. It still refuses to perform the guessed operation, even if there is only one candidate:
$ git chekoutgit: 'chekout' is not a git command. See 'git --help'.The most similar command is checkoutHowever, with the help.autoCorrect configuration variable set to a positive number, Git will automatically correct and execute the mistyped commands after waiting for the given number of deciseconds (0.1 of second). You can use a negative value with this option for immediate execution, or zero to go back to the default:
$ git chekoutWARNING: You called a Git command named 'chekout', which does not exist.Continuing in 0.1 seconds, assuming that you meant 'checkout'.Your branch is up-to-date with 'origin/master'.If there is more than one command that can be deduced from the entered text, nothing will be executed. This mechanism works only for Git commands; you cannot autocorrect subcommands, parameters, and options (as opposed to tab completion).
Making the command line prettier
Section titled “Making the command line prettier”Git fully supports a colored terminal output, which greatly aids in visually parsing the command output. A number of options can help you set the coloring to your preference.
First, you can specify when to use colors, such as for the output of certain commands. There is a color.ui master switch to control output coloring to turn off all of Git’s colored terminal outputs and set them to false. The default setting for this configuration variable is auto, which makes Git color the output when it’s going straight to a terminal, but omit the color-control codes when the output is redirected to a file or a pipe.
You can also set color.ui to always, though you’d rarely want this: if you want color codes in your redirected output, simply pass a --color flag to the Git command; conversely, the --no-color option would turn off the colored output.
If you want to be more specific about which commands and which parts of the output are colored, Git provides appropriate coloring settings: color.branch, color.diff, color.interactive, color.status, and so on. Just as with the color.ui master switch, each of these can be set to true, false, auto, and always.
In addition, each of these settings has subsettings that you can use to set specific colors for specific parts of the output. The color value of such configuration variables – for example, color.diff.meta (to configure the coloring of meta information in your diff output) – consists of space-separated names of the foreground color, the background color (if set), and the text attribute.
You can set the color to any of the following values: normal, black, red, green, yellow, blue, magenta, cyan, or white. As for the attributes, you can choose from bold, dim, ul (underline), blink, and reverse (swap the foreground color with the background one).
The pretty formats for git log also include an option to set colors; see the git log documentation for more information.
External tools
There are diff syntax highlighters that can be used with Git. They can be set up to work as a pager with the core.pager config variable, or configured via an alias. Examples include delta (https://dandavison.github.io/delta) and diff-highlight from the contrib area of Git source code.
Alternative command line
Section titled “Alternative command line”To understand some of the rough edges of the Git user’s interface, you need to remember that Git was developed to a large extent in a bottom-up fashion. Historically, Git began as a tool to write version-control systems (you can see how early Git was used in the A Git core tutorial for developers documentation that you can view with the git help core-tutorial command).
The first alternative “porcelain” (i.e., alternative user interface) for Git was Cogito. Nowadays, Cogito is no more; all of its features have long been incorporated into Git (or replaced by better solutions). There were some attempts to write wrapper scripts (alternative UIs) designed to make it easy to learn and use, for example, Easy Git (eg) and the newer Gitless. Jujutsu (jj) is a version control system in the early stages of development that can use Git repositories to store project history, and thus can be thought as a layer on top of Git, too.
There are also external Git porcelains that do not intend to replace the whole user interface, but either provide access to some extra features, or wrap Git to provide some restricted feature set. Patch management interfaces, such as StGit, TopGit, or Guilt (formerly Git Queues (gq)), are created to make it easy to rewrite, manipulate, and clean up selected parts of the unpublished history; these were mentioned as an alternative to an interactive rebase in Chapter 10, Keeping History Clean. Then, there are single-file version control systems, such as Zit, which use Git as a backend.
Alternative implementations
Beside alternative user interfaces, there are also different implementations of Git (defined as reading and writing Git repositories). They are at different stages of completeness. Besides the core C implementation, there is JGit in Java, and also the libgit2 project—the modern basis of Git bindings for various programming languages.
Graphical interfaces
Section titled “Graphical interfaces”You have learned how to use Git on the command line. The previous section told you how to customize and configure it to make it even more effective. But the terminal is not the end. There are other kinds of environments you can use to manage Git repositories. Sometimes, a visual representation is what you need.
Now, we’ll take a short look at the various kinds of user-centered graphical tools for Git; the tour of Git administrative tools is left for the next chapter, Chapter 14,Git Administration.
Types of graphical tools
Section titled “Types of graphical tools”Different tools and interfaces are tailored for different workflows. Some tools expose only a selected subset of the Git functionality or encourage a specific way of working with version control.
To be able to make an informed choice when selecting a graphical tool for Git, you need to know what types of operations the different types of tools support. Note that one tool can support more than one type of use.
First, there is the graphical history viewer. You can think of it as a powerful GUI over git log. This is the tool to be used when you are trying to find something that happened in the past, or you are visualizing and browsing your project’s history and the layout of branches. Such tools usually accept revision selection command-line options, such as --all. Command-line Git has git log --graph and the less-used git show-branch that uses ASCII art to show the history.
A similar tool is graphical blame, showing the line-wise history of a file. For each line, it can show when that line was created and when it was moved or copied to the current place. You can examine the details of each of the commits shown and usually browse through the history of the lines in a file. Other tools with similar applications, namely examining the evolution of the line range (git log -L) and the so-called pickaxe search (git log -S), do not have many GUIs.
Next, there are commit tools meant primarily to craft (and amend) commits, though usually they also include some kind of worktree management (for example, ignoring files and switching branches) and functionality for management of remotes. Such tools usually show both unstaged and staged changes, allowing you to move files between these states. Some of those tools, such as the interactive versions of git add, git reset, and so on, even allow you to stage and unstage individual chunks of changes. A graphical version of an interactive add is described in Chapter 3, Managing Your Worktrees, and mentioned in Chapter 2, Developing with Git. There are also tools to craft commit messages following specified criteria.
Then, we have file manager integration (or graphical shell integration). These plugins usually show the status of the file in Git (tracked/untracked/ignored) using icon overlays. They can offer a context menu for a repository, directory, and file, often with accompanying keyboard shortcuts. They may also bring drag and drop support.
Programmer editors and IDE) often offer support for IDE integration with Git (or version control in general). These offer repository management (as a part of team project management), make it possible to perform Git operations directly from the IDE, show the status of the current file and the repository, and perhaps even annotate the view of the file with version control information. They often include the commit tool, remote management, the history viewer, and the diff viewer.
Git repositories’ hosting sites often offer workflow-oriented desktop clients. These mostly focus on a curated set of commonly used features that work well together in the flow. They automate common Git tasks. They are often designed to highlight their service, offering extra features and integration, but they will work with any repository hosted anywhere.
There are even specialized editors and pagers, such as a graphical editor for the interactive rebase instruction sheet (see Chapter 9*, Merging Changes* Together), that can be set up with the sequence.editor config variable, or a syntax highlighting tool for diffs that can be set up as the default Git pager with core.pager.
Graphical diff and merge tools
Section titled “Graphical diff and merge tools”Graphical diff tools and graphical merge tools are somewhat special cases. In these categories, Git includes the commands for integration with third-party graphical tools, namely, git difftool and git mergetool. These tools are then called from the Git repository. Note that this is different from the external diff or diff merge drivers, which replace ordinary git diff or augment it.
Although Git has an internal implementation of diff and a mechanism for merge conflict resolutions (see Chapter 9, Merging Changes Together), you can use an external graphical diff tool instead. These are often used to show the differences better (usually, as a side-by-side diff, possibly with refinements), and help resolve a merge (often with a three-pane interface).
Configuring the graphical diff or graphical merge tool requires configuring a number of custom settings. To tell which tool to use for diff and merge, respectively, you can set up diff.tool and merge.tool, respectively. Without setting, for example, the merge.tool configuration variable, the git mergetool command would print the information on how to configure it, and will attempt to run one of predefined tools:
$ git mergetoolThis message is displayed because 'merge.tool' is not configured.See 'git mergetool --tool-help' or 'git help config' for more details.'git mergetool' will now attempt to use one of the following tools:tortoisemerge emerge vimdiffNo files need mergingRunning git mergetool --tool-help will show all the available tools, including those that are not installed. If the tool you use is not in $PATH, or it has the wrong version of the tool, you can use mergetool.<tool>.path to set or override the path for the given tool:
$ git mergetool --tool-help'git mergetool --tool=<tool>' may be set to one of the following: vimdiff Use Vim with a custom layout[…]The following tools are valid, but not currently available: araxis Use Araxis Merge[…]Some of the tools listed above only work in a windowedenvironment. If run in a terminal-only session, they will fail.If there is no built-in support for your tool, you can still use it; you just need to configure it. The mergetool.<tool>.cmd configuration variable specifies how to run the command, while mergetool.<tool>.trustExitCode tells Git whether the exit code of that program indicates a successful merge resolution or not. The relevant fragment of the configuration file (for a graphical mergetool named extMerge) could look as follows:
[merge] tool = extMerge[mergetool "extMerge"] cmd = extMerge "$BASE" "$LOCAL" "$REMOTE" "$MERGED"There are a few config options that control git mergetool behavior, either globally or on a per-tool basis. One of those is mergetool.hideResolved (and its per-tool mergetool.<tool>.hideResolved variant), which makes Git resolve as many conflicts as possible by itself, and presents only unresolved conflicts to the merge tool. Note that some merge tools do this themselves.
Some merge tools, such as vimdiff, are text interface tools that can work without the need for a graphical session. If you want to run one tool in text mode (for example, when using plain SSH access to a remote host), and another one in graphical mode, you can do this by configuring mergetool.tool in one tool, and mergetool.guitool in another – and use git mergetool --gui to invoke the GUI one.
Graphical interface examples
Section titled “Graphical interface examples”In this section, you will be presented with a selection of tools around Git that you could use, or that might prompt you to research further. A nice way to help you start this research is to list some selected GUI clients.
There are two visual tools that are a part of Git and are usually installed with it, namely gitk and git-gui. They are written in Tcl/Tk. gitk is a graphical history viewer, while git gui is a graphical commit tool; there is also git gui blame, a visually interactive line-history browser. These tools are interconnected: for example, browsing history from git gui opens gitk.
Visual tools do not need to use the graphical environment. There is tig (short for Text Interface for Git) that uses a nurses-based text-mode interface (TUI) and functions as a repository browser and commit tool and can act as a Git pager.
Another TUI example is git interactive-rebase-tool, which can be set up as an interactive sequence editor for the interactive rebase instruction sheet.
There is git cola, developed in Python and available for all the operating systems, which includes commit tools and remotes management, and also a diff viewer. Then, there is the simple and colorful Gitg tool for GNOME; you will get a graphical history viewer, diff viewer, and file browser.
One of the more popular open source GUI tools for macOS is GitX. There are a lot of forks of this tool; one of the more interesting ones is Gitbox. It features both the history viewer and commit tools.
For MS Windows, there is TortoiseGit and git-cheetah, both of which offer integration into the Windows context menu, so you can perform Git commands inside Windows Explorer (the file manager integration and shell interface).
GitHub Inc. and Atlassian both released a desktop GUI tool that you can easily use with your GitHub or Bitbucket repository, respectively, but neither tool is not limited to only interacting with a single service (GitHub or Bitbucket, respectively). Both GitHub Client and SourceTree feature repository management and offer a range of other common facilities to enhance your development workflow.
Many programming editors and IDEs have support for managing Git repositories, and sometimes also for interacting with Git hosting sites. This can be either built in, or available as IDE plugins or extensions. Examples include GitLens for Visual Studio Code, Magit for GNU Emacs, and Fugitive for ViM. Those tools often show information such as which lines are added or changed, or who authored them, inside the editor pane.
Configuring Git
Section titled “Configuring Git”So far, while describing how Git works and how to use it, we have introduced a number of ways to change its behavior. In this section, it will be explained in a systematic fashion how to configure Git operations on a temporary and permanent basis. We will also see how you can make Git behave in a customized fashion by introducing and reintroducing several important configuration settings. With these tools, it’s easy to get Git to work the way you want it to.
Command-line options and environment variables
Section titled “Command-line options and environment variables”Git processes the switches that change its behavior in a hierarchical fashion, from the least specific to the most specific one, with the most specific one (and shortest term) taking precedence.
The most specific one, overriding all the others, is the command-line options. They affect, obviously, only the current Git command.
Important note
One issue to note is that some command-line options, for example, --no-pager or --no-replace-objects, go to the git wrapper, not to the Git command itself. Examine, for example, the following line to see the distinction:
$ git --no-replace-objects log -5 --oneline -- graph --decorate
You can find the conventions used through the Git command-line interface on the manpage.
The second way to change how the Git command works is to use environment variables. They are specific to the current shell, and you need to use the export built-in command (or its equivalent) to propagate the variables to the subprocesses if a replacement is used. There are some environment variables that apply to all core Git commands, and some that are specific to a given (sub)command.
Git also makes use of some nonspecific environment variables. These are meant as a last resort; they are overridden by their Git-specific equivalents. Examples include variables such as PAGER and EDITOR.
Git configuration files
Section titled “Git configuration files”The final way to customize how Git works is with the configuration files. In many cases, there is a command-line option to configure an action, an environment variable for it, and finally a configuration variable, in descending order of preference.
Git uses a series of configuration files to determine non-default behavior that you might want to have. There are four layers of these files that Git looks through for configuration values. Git reads all these files in order from the least specific to the most specific one. The settings in the later ones override those set in the earlier ones. You can access the Git configuration with the git config command: by default, it operates on the union of all the files, but you can specify which one you want to access with the command-line options. You can also access any given file following the configuration file syntax (such as the .gitmodules file mentioned in Chapter 11, Managing Subprojects) by using the --file=<pathname> option (or the GIT_CONFIG environment variable).
Tip
You can also read the values from any blob with configuration-like contents; for example, you may use git config --blob=master:.gitmodules to read from the .gitmodules file in the master branch.
The first place Git looks for configuration is the system-wide configuration file. If Git is installed with the default settings, it can be found in /etc/gitconfig. Well, at least, on Linux it is there, as the Filesystem Hierarchy Standard (FHS) states that /etc is the directory for storing the host-specific system-wide configuration files; Git for Windows puts this file in the subdirectory of its Program Files folder. This file contains the values for every user on the system and all their repositories. To make git config read from and write and to this file specifically (and to open it with --edit), pass the --system option to the git config command.
You can skip the reading settings from this file with the GIT_CONFIG_NOSYSTEM environment variable. This can be used to set up a predictable environment or to avoid using a buggy configuration you can’t fix.
The next place Git looks is the user-specific configuration file: ~/.gitconfig, falling back to ~/.config/git/config if it exists (with the default configuration). This file is specific to each user and it affects all of the user’s repositories. If you pass the --global option to git config, it will read and write from this file specifically. Reminder: here, as in the other places, ~ (the tilde character) denotes the home directory of the current user ($HOME).
Finally, Git looks for the configuration values in the per-repository configuration file in the Git repository you are currently using, which is (by default and for non-bare repositories) .git/config. Values set there are specific to that local single repository. You can make Git read and write to this file by passing the -- local option.
With modern Git, if the extensions.worktreeConfig is set to true (the default value is false), there can also be a per-worktree configuration file in the .git/config.worktree file (see the git worktree command).
Each of these levels (system, global, and local) overrides the values from the previous level, so for example, values in .git/config trump those in ~/.gitconfig; well, unless the configuration variable is multivalued.
Tip
You can use the fact that the local (per-repository) configuration overrides the global (per-user) configuration to have your default identity in the per-user file and to override it if necessary on a per-repository basis with a per-repository configuration file.
Finally, you can set the config variable for an individual command with the -c option to the git wrapper:
$ git -c foo.int=1k config --get --type=int foo.int1024See the following sections for a full explanation of this result.
The syntax of Git configuration files
Section titled “The syntax of Git configuration files”Git’s configuration files are plain text, so you can also customize Git’s behavior by manually editing the chosen file. The syntax is fairly flexible and permissive; whitespaces are mostly ignored (contrary to .gitattributes). The hash # and the semicolon ; characters begin comments, which last until the end of the line. Blank lines are ignored.
The file consists of sections and variables, and its syntax is similar to the syntax of INI files. Both the section names and variable names are case-insensitive. A section begins with the name of the section in square brackets [section] and continues until the next section. Each variable must begin at some section, which means that there must be a section header before the first setting of a variable. Sections can repeat and can be empty.
Sections can be further divided into subsections. Subsection names are case-sensitive and can contain any character except newline (double quotes " and backslash \ must be escaped as \" and \\, respectively). The beginning of the subsection will look as follows:
[section "subsection"]All the other lines (and the remainder of the line after the section header) are recognized as a setting variable in the name = value form. As a special case, just name is a shorthand for name = true (boolean variables). Such lines can be continued to the next line by ending it with \ (the backslash character), that is by escaping the end-of-line character. Leading and trailing whitespaces are discarded; internal whitespaces within the value are retained verbatim. You can use double quotes to preserve leading or trailing whitespaces in values.
Includes and conditional includes
Section titled “Includes and conditional includes”You can include one config file from another by setting the special variable include.path to the path of the file to be included. The included file will be expanded immediately, similar to the mechanism of #include in C and C++. The path is relative to the configuration file with the include directive. You can turn this feature off with the -- no-includes option.
You can also conditionally include a config file from another similarly by setting an includeIf.<condition>.path variable. The condition starts with a keyword, followed by a colon :, and data relevant to the type of conditional included.
The supported keywords are as follows:
- gitdir, where the data that follows the keyword is used as a glob pattern to match the location of the
.gitdirectory (of the repo itself). For convenience,~and~/at the beginning of the pattern are substituted with the location of the home directory, and./at the beginning of the pattern is replaced with the directory containing the current config file. There is also gitdir/i variant that does the matching in a case-insensitive way. - onbranch, which can be used to match the currently checked-out branch against the glob pattern.
- hasconfig:remote.*.url, which checks whether, in any of the configuration, there exists at least one remote URL that matches the glob pattern.
For example, to use a different configuration for repositories inside the work-repos/ subdirectory in your home directory, you could use the following:
[includeIf "gitdir:~/work-repos/"] path = ~/work.incAccessing the Git configuration
Section titled “Accessing the Git configuration”You can use the git config command to access the Git configuration, starting from listing the configuration entries in a canonical form, through examining individual variables, to editing and adding entries.
You can query the existing configuration with git config --list, adding an appropriate parameter if you want to limit to a single configuration layer. On a Linux box with the default installation, in the fresh empty Git repository just after git init, the local (per-repository) setting would look approximately like the following:
$ git config --list --localcore.repositoryformatversion=0core.filemode=falsecore.bare=falsecore.logallrefupdates=trueYou can also use git var -l to list all configuration and environment variables affecting Git.
You can also query a single key with git config, limiting (or not) the scope to the specified file, by giving the name of the configuration variable as a parameter (optionally preceded by --get), with the section, optional subsection, and variable name (key) separated by a dot:
$ git config user.emailThis would return the last value, that is, the one with the greatest precedence. You can get all the values with --get-all, or specific keys with --get-regexp=<match>. This is quite useful while accessing a multivalued option such as refspecs for a remote.
Types of configuration variables and type specifiers
While requesting (or writing) a config variable, you can give a type specifier with the --type=<type> option. The type can be bool, which ensures that the returned value is true or false; int, which expands the optional value suffix of k (1,024 elements), m (1024k), or g (1024m); path, which expands ~ for the value of $HOME; and ~user for the home directory of the given user, and expiry-date to convert a fixed or relative date string to a timestamp.
There is also bool-or-int, and a few options related to storing colors and retrieving color escape codes; see the git config documentation.
With --get, --get-all, and --get-regexp, you can also limit the listing (and the settings for multiple-valued variables) to only those variables matching the value regexp (which is passed as an optional last parameter). For example, to find all configurations that affect proxying for a given host, you can use the following command:
$ git config --get core.gitproxy 'for kernel\.org$'You can also use the git config command to set the configuration variable value. The local layer (per-repository file) is the default for writing if nothing else is specified. For example, to set the email address of the user, which is to be common to most of their repositories, you can run the following:
$ git config --global user.name "Alice Developer"For multivalue configuration options (multivar), you can add multiple lines to it by using the --add option. To change a single entry of a multivar config variable, you can use something like the following command, where the first value denotes which value to change, and the second denotes the new value:
$ git config core.gitproxy '"ssh" for kernel.org' '"ssh" for kernel\.org$'It is also very easy to delete configuration entries with git config --unset.
Instead of setting all the configuration values on the command line, as shown in the preceding example, it is possible to set or change them just by editing the relevant configuration file directly. Simply open the configuration file in your favorite editor, or run the git config -- edit command.
The local repository configuration file just after a fresh git init on Linux looks as follows:
[core] repositoryformatversion = 0 filemode = true bare = false logallrefupdates = trueIf you want to change a configuration by editing the configuration file, it might be prudent to first find out where the configuration variable you want to change came from.
Finding where configuration value came from
Section titled “Finding where configuration value came from”With three (or four) layers of configuration files, it might be difficult to find out where the given configuration variable was set, and whether it was overridden or added to in a more specific configuration file. Then there is the additional complication of taking into account the include and includeIf sections.
That is where the --show-origin and --show-source options passed to the git config command together with the --list or --get/--get-all options can help. The git config --list command will list all variables set in config files, along with their values. The --show-scope option augments the output of all queried config options with the scope of that value (worktree, local, global, system, command), while --show-source shows the origin type (file, standard input, command line, blob) and the actual origin (config file path, or blob ID, if applicable).
Debugging per-file configuration
You can use git check-ignore to examine why a file is ignored, and git check-attr to find out the attributes assigned to the file and where they came from.
For example, let’s assume that user identity is defined in a per-user configuration file: ~/.gitconfig
[user] name = Joe Random email = [email protected]Let’s also assume that the git config command was used to create the work.inc file in the top directory of the project, and to include it from the per-repository config file:
$ git config --file=conf.inc foo.bar val$ git config --local include.path ./conf.incIn that context, we would get the following query results, shown here in shortened form:
$ git config --show-scope --show-origin --listglobal file:/home/joe/.gitconfig user.name=Joe Randomglobal file:/home/joe/.gitconfig [email protected]local file:.git/config core.repositoryformatversion=0local file:.git/config core.filemode=false[…]local file:.git/config include.path=./../conf.inclocal file:.git/./../conf.inc foo.bar=valThe first column shows the scope, the second column the origin, and the third the fully qualified config variable and its value.
Basic client-side configuration
Section titled “Basic client-side configuration”You can divide the configuration options recognized by Git into two categories: client side and server side. The majority of the options are about configuring your personal working preferences; they are client side. The server-side configuration will be touched upon in more detail in Chapter 14, Git Administration; in this section, you will find only the basics.
There are many supported configuration options, but only a small fraction of them needs to be set; a large fraction of them has sensible defaults, and explicitly setting them is only useful in certain edge cases. There are a lot of options available; you can see a list of all the options with git config --help. Here we’ll be covering only the most common and most useful options.
Two variables that really need to be set up are user.email and user.name.Those configuration variables define the user’s identity (though in modern Git, you can set up separate identities for authoring changes and for committing them with author.name and committer.name). Also, if you are signing annotated tags or commits (as discussed in Chapter 6, Collaborative Development with Git), you might want to set up your GPG signing key ID. This is done with the user.signingKey configuration setting.
By default, Git uses whatever you’ve set on the system as your default text editor (defined with the VISUAL or EDITOR environment variables; the first only for the graphical desktop environment) to create and edit your commit and tag messages. It also uses whatever you have set as the pager (PAGER) for paginating and browsing the output of the Git commands. To change this default to something else, you can use the core.editor setting. The same goes for core.pager. Git would ultimately fall back on the vi editor and on the less pager.
With Git, the pager is invoked automatically. The default less pager supports not only pagination, but also incremental search and other features.
Important note
With the default configuration (the LESS environment variable is not set), less when invoked by Git works as if it was invoked with LESS=FRX. This means that it would skip pagination if there were less than one page of output, it would pass through ANSI color codes, and it would not clear the screen on exit.
Creating commit messages is also affected by commit.template. If you set this configuration variable, Git will use that file as the default message when you commit. The template is not distributed with the repository in general. Note that Git would add the status information to the commit message template unless it is forbidden to do it by setting commit.status to false.
Such a template is quite convenient if you have a commit-message policy, as it greatly increases the chances of this policy being followed. It can, for example, include the commented-out instructions for filling the commit message. You can augment this solution with an appropriate hook that checks whether the commit message matches the policy (see the Commit process hooks section later in this chapter).
The status of the files in the working area is affected by the ignore patterns and the file attributes (see Chapter 3, Managing Your Worktrees). You can put ignore patterns in your project’s in-tree .gitignore file (usually, .gitignore is about which files are not to be tracked, and it is tracked itself by Git), or in the .git/info/excludes file for local and private patterns, to define which files are not interesting. These are project-specific; sometimes, you would want to write a kind of global (per-user) .gitignore file. You can use core.excludesFile to customize the path to the said file; in modern Git, there is a default value for this path, namely, ~/.config/git/ignore. There is also a corresponding core.attributesFile for this kind of global .gitattributes files, which defaults to ~/.config/git/attributes.
Trivia
Actually, it is $XDG_CONFIG_HOME/git/ignore; if the $XDG_CONFIG_HOME environment variable is not set or is empty, $HOME/.config/git/ignore is used.
Although Git has an internal implementation of diff, you can set up an external tool to be used instead with the help of diff.external. You would usually want to create a wrapper script that massages the parameters that Git passes to it and passes the ones needed in the order external diff requires. By default, Git passes the following arguments to the diff program:
path old-file old-hex old-mode new-file new-hex new-modeSee also the Graphical diff and merge tools section for the configuration of git difftool and git mergetool.
The rebase and merge setup, configuring pull
Section titled “The rebase and merge setup, configuring pull”When performing git pull operation, Git needs to know whether you prefer to use the merge operation to join the local history and the history fetched from the remote, or the rebase operation to join histories. That is why it requires you to provide a value for the pull.rebase configuration variable. You can find more information on the topic of merge and rebase in Chapter 9, Merging Changes Together.
There are several configuration settings that can be used to configure the behavior of git pull. There is the pull.rebase configuration option and a branch-specific branch.<name>.rebase option that, when set to true, tells Git to perform a rebase during the pull operation (for the <name> branch only in the latter case). If set to false, then git pull performs a merge. Both can also be set to merges to run rebase with the --rebase-merges option, to have local merge commits not be flattened in the process of rebasing.
You can make Git automatically set up the per-branch “pull to rebase” configuration while creating specific kinds of new branches with branch.autoSetupRebase. You can set it to never, local (for locally tracked branches only), remote (for remote tracked branches only), or always (for local plus remote). There is also branch.autoSetupMerge to set up a branch to track another branch.
Preserving undo information – the expiry of objects
Section titled “Preserving undo information – the expiry of objects”By default, Git will automatically remove unreferenced objects, clean reflogs of stale entries, and pack loose objects, all to keep the size of the repository down. You can also run the garbage collection manually with the git gc command. You should know about a repository’s object-oriented structure from Chapter 10, Keeping History Clean.
Git will, for safety reasons, use a grace period of two weeks while removing unreferenced objects; this can be changed with the gc.pruneExpire configuration: the setting is usually a relative date (for example, 1.month.ago; you can use dots as word separators). To disable the grace period (which is usually done from the command line), the now value can be used.
The branch tip history is kept for 90 days by default (or gc.reflogExpire, if set) for reachable revisions, and for 30 days (or gc.reflogExpireUnreachable) for reflog entries that are not a part of the current history. Both settings can be configured on a per-reframe basis, by supplying a pattern of the ref name to be matched as a subsection name, that is, gc.<pattern>.reflogExpire, and similar for the other setting. This can be used to change the expire settings for HEAD or for refs/stash (see Chapter 3, Managing Your Worktrees), or for remote-tracking branches refs/remotes/* separately. The setting is a length of time (for example, 6 months); to completely turn off reflog expiry, use the value of never. You can use the latter, for example, to switch off the expiring of stash entries.
Formatting and whitespace
Section titled “Formatting and whitespace”Code formatting and whitespace issues are some of the more frustrating and subtle problems you may encounter while collaborating, especially with cross-platform development. It’s very easy for patches and merges to introduce subtle and unnecessary whitespace changes, because editing the code can silently introduce such changes (which are often not visible), and because there are different notions of line endings on different operating systems: MS Windows, Linux, and macOS. Git has a few configuration options to help with these issues.
One important issue for cross-platform work is the notion of line-ending. This is because MS Windows uses a combination of a carriage return (CR) character and a linefeed (LF) character for new lines in text files, whereas macOS and Linux use only a linefeed character. Many editors on MS Windows will silently replace existing LF-style line endings with CRLF or use CRLF for new lines, which leads to subtle but annoying issues.
Git can handle this issue by auto-converting line endings into LF when you add a file to the index. If your editor uses CRLF line endings, Git can also convert line endings to the native form when it checks out code in your filesystem. There are two configuration settings that affect this matter: core.eol and core.autocrlf. The first setting, core.eol, sets the line ending to be used while checking out files into the working directory for files that have the text property set (see the following Per-file configuration with gitattributes section, which summarizes and recalls information about the file attributes from Chapter 3, Managing Your Worktrees).
The second and older setting, core.autocrlf, can be used to turn on the automatic conversion of line endings to CRLF. Setting it to true converts the LF line endings in the repository into CRLF when you check out files, and vice versa when you stage them; this is the setting you would probably want on a Windows machine. (This is almost the same as setting the text attribute to auto on all the files and core.eol to crlf.) You can tell Git to convert CRLF to LF on a commit but not the other way around by setting core.autocrlf to input instead; this is the setting to use if you are on a Linux or Mac system. To turn off this functionality, recording the line-endings in the repository as they are set this configuration value to false.
This handles one part of the whitespace issues – line-ending variance, and one vector of introducing them – editing files. Git also comes with a way to detect and fix some of the other whitespace issues. It can be configured to look for a set of common whitespace problems. The core.whitespace configuration setting can be used to activate them (for those disabled by default) or turn them off (for those enabled by default). The three that are turned on by default are the following:
blank-at-eol: This looks for trailing spaces at the end of a lineblank-at-eof: This notices blank lines at the end of a filespace-before-tab: This looks for spaces immediately before the tabs at the initial (beginning) indent part of the line
The trailing-space value in core.whitespace is a shorthand to cover both blank-at-eol and blank-at-eof.
The three that are disabled by default but can be turned on are the following:
indent-with-non-tab: This treats the line that is indented with space characters instead of the equivalent tabs as an error (where equivalence is controlled by thetabwidthoption). This option enforces indenting with Tab characters.tab-in-indent: This watches for tabs in the initial indentation portion of the line (here,tabwidthis used to fix such whitespace errors). This option enforces indenting with space characters.cr-at-eol: This tells Git that carriage returns at the end of the lines are OK (allowing CRLF endings in the repository).
You can tell Git which of these you want enabled or disabled by setting core.whitespace to the comma-separated list of values. To disable an option, prepend it with the - prefix in front of the value. For example, if you want all but cr-at-eol and tab-in-indent to be set, and also while setting the Tab space value to 4, you can use:
$ git config --local core.whitespace \ trailing-space,space-before-tab,indent-with-non-tab,tabwidth=4You can also set these options on a per-file basis with the whitespace attribute. For example, you can use it to turn off checking for whitespace problems in test cases to handle whitespace issues or ensure that the Python 2 code indents with spaces:
*.py whitespace=tab-in-indentEditorConfig
There exists the EditorConfig project (https://editorconfig.org/) that consists of a file format for defining coding styles, including the type of line endings, and a collection of text editor plugins that make editors adhere to the chosen style. The .editorconfig file should be tracked by Git.
Git will detect these issues when you run a git diff command and inform you about them using the color.diff.whitespace color, so you can notice them and possibly fix them before you create a new commit. While applying patches with git apply, you can ask Git to either warn about the whitespace issues with git apply --whitespace=warn, error out with --whitespace=error, or you can have Git try to automatically fix the issue with --whitespace=fix. The same applies to the git rebase command as well.
Server-side configuration
Section titled “Server-side configuration”There are a few configuration options available for the server side of Git. They will be described in more detail in Chapter 14, Git Administration; here you will find a short summary of some of the more interesting parameters.
You can make the Git server check for object consistency, namely, that every object received during a push matches its SHA-1 identifier, and that it is a valid object, with a receive.fsckObjects Boolean-valued configuration variable. It is turned off by default because git fsck is a fairly expensive operation, and it might slow down operations, especially on large pushes (which are common in large repositories). This is a check against faulty or malicious clients.
If you rewrite commits that you have already pushed to a server (which is bad practice, as explained in Chapter 10, Keeping History Clean) and try to push again, you’ll be denied. The client might, however, force-update the remote branch with the --force flag to the git push command. However, the server can be told to refuse force-pushes by setting receive.denyNonFastForward to true.
The receive.denyDeletes setting blocks one of the workarounds to the denyNonFastForward policy, namely, deleting and recreating a branch. This forbids the deletion of branches and tags; you must remove refs from the server manually.
All of these features could also be implemented via the server-side receive-like hooks; this will be covered in the Installing a Git hook section, and also to some extent in Chapter 14,Git Administration.
Per-file configuration with gitattributes
Section titled “Per-file configuration with gitattributes”Some of the customizations can also be specified for a path (perhaps via glob) so that Git applies these settings only for a subset of files or for a subdirectory. These path-specific settings are called gitattributes.
The order of precedence of applying this type of settings starts with the per-repository local (per-user) per-path settings in the $GIT_DIR/info/attributes file. Then, the .gitattributes files are consulted, starting with the one in the same directory as the path in question, going up through the .gitattributes files in the parent directories, up to the top level of the worktree (the root directory of a project).
Finally, the global per-user attributes file (specified by core.attributesFile, or at ~/.config/git/attributes if this is not set) and the system-wide file (in /etc/gitattributes in the default installation) are considered.
Available Git attributes are described in detail in Chapter 3, Managing Your Worktrees. Using attributes, you can, among others, do things such as specify the separate merge strategies via merge drivers for the specific kind of files (for example, ChangeLog), tell Git how to diff non-text files, or have Git filter content during checkout (on writing to the working area, that is, to the filesystem) and commit (on staging contents and committing changes to the repository, that is, creating objects in the repository database).
Syntax of the Git attributes file
Section titled “Syntax of the Git attributes file”A gitattributes file is a simple text file that sets up the local configuration on a per-path basis. Blank lines and lines starting with the hash character (#) are ignored; thus, a line starting with # serves as a comment, while blank lines can serve as separators for readability. To specify a set of attributes for a path, put a pattern followed by an attributes list, separated by a horizontal whitespace:
pattern attribute1 attribute2When more than one pattern matches the path, a later line overrides an earlier line, just like for the .gitignore files (you can also think that the Git attributes files are read from the least specific system-wide file to the most specific local repository file).
Git uses a backslash (\) as an escape character for patterns. Thus, for patterns that begin with a hash, you need to put a backslash in front of the first hash (that is written as \#). Because the attributes information is separated by whitespaces, trailing spaces in the pattern are ignored and inner spaces are treated as the end of the pattern unless they are quoted with a backslash (that is, written as “ \ “).
If the pattern does not contain a slash (/), which is a directory separator, Git will treat the pattern as a shell glob pattern and will check for a match against the pathname relative to the location of the .gitattributes file (or the top level for other attribute files). Thus, for example, the *.c patterns match the C files anywhere down from the place the .gitattributes file resides. A leading slash matches the beginning of the pathname. For example, /*.c matches bisect.c but not builtin/bisect--helper.c, while the *.c pattern would match both.
If the pattern includes at least one slash, Git will treat it as a shell glob suitable for consumption by the fnmatch(3) function call with the FNM_PATHNAME flag. This means that the wildcards in the pattern will not match the directory separator, that is, the slash (/) in the pathname; the match is anchored to the beginning of the path. For example, the include/*.h pattern matches include/version.h but not include/linux/asm.h or libxdiff/includes/xdiff.h. The shell glob wildcards are the following:
- * matching any string (including empty)
- ? matching any single character
- […] expression matching the character class (inside brackets, asterisks and question marks lose their special meaning); note that unlike in regular expressions, the complementation/negation of the character class is done with
!and not^. For example, to match anything but a number, one can use the[!0-9]shell pattern, which is equivalent to[^0-9]in a regexp.
Two consecutive asterisks (**) in patterns may have a special meaning, but only between two slashes (/**/), or between a slash and at the beginning or the end of the pattern. Such a wildcard matches zero or more path components. Thus, a leading ** followed by a slash (**/) means a match in all directories, while a trailing /** matches every file or directory inside the specified directory.
Each attribute can be in one of four states for a given path:
- First, it can be set (the attribute has a special value of true). This is specified by simply listing the name of the attribute in the attribute list, for example,
text. - Second, it can be unset (the attribute has a special value of false). This is specified by listing the name of the attribute prefixed with minus, for example,
-text. - Third, it can be set to a specific value; this is specified by listing the name of the attribute followed by an equal sign and its value, for example,
text=auto(note that there cannot be any whitespace around the equal sign as opposed to the configuration file syntax). - If no pattern matches the path, and nothing dictates whether the path has or does not have attributes, the attribute is said to be unspecified (you can override the setting for an attribute, forcing it to be explicitly unspecified with
!text).
If you find yourself using the same set of attributes over and over for many different patterns, you should consider defining a macro attribute. This can be defined in the local, global, or system-wide attributes file, but (from all possible places for a repository-specific attributes file), macros can be defined only in the top level .gitignore file. The macro is defined using [attr]<macro> in place of the file pattern; the attributes list defines the expansion of the macro. For example, the built-in binary macro attribute is defined as follows:
[attr]binary -diff -merge -textBut command-line options, environment variables, configuration files, gitattributes, and gitignore files are not the only ways to change what Git is doing. There is also the hooks mechanism, which can be used to make Git trigger user-defined actions automatically at specific points in Git’s execution.
Automating Git with hooks
Section titled “Automating Git with hooks”There are usually certain prerequisites to the code that is produced, either self-induced or enforced externally. The code should always be able to compile and pass at least a fast subset of the tests. With some development workflows, each commit message may need to reference an issue ID (or match the message template), or include a digital certificate of origin in the form of the Signed-off-by line. In many cases, these parts of the development process can be automated by Git.
Like many programming tools, Git includes a way to fire custom functionality contained in the user-provided code (custom scripts), when certain important pre-defined actions occur, that is, when certain events trigger. Such a functionality invoked as an event handler is called a hook. It allows us to take additional action and, at least for some hooks, also to stop the triggered functionality.
Hooks in Git can be divided into client-side and server-side hooks. Client-side hooks are triggered by local operations (on the client) such as committing, applying a patch series, rebasing, and merging. Server-side hooks on the other hand run on the server when network operations occur, such as receiving pushed commits.
You can also divide hooks into prehooks and post hooks. Pre hooks are called before an operation is finished, usually before the next step while performing an operation. If they exit with a nonzero value, they will cancel the current Git operation. Post hooks are invoked after an operation finishes and can be used for notification and logs; they cannot cancel an operation.
Installing a Git hook
Section titled “Installing a Git hook”The hooks in Git are executable programs (usually scripts), which are stored in the hooks/ subdirectory of the Git repository administrative area, that is, .git/hooks/ for non-bare repositories. You can change the location of the directory that Git searches for hooks via core.hooksPath configuration variable.
Hook programs are each named after the event that triggers them. This means that if you want one event to trigger more than one script, you will need to implement multiplexing yourself.
When you initialize a new repository with git init (this is done also while using git clone to create a copy of the other repository; clone calls init internally), Git populates the .git/hooks/ directory with a bunch of inactive example scripts. Many of these are useful by themselves, but they also document the hook’s API. All the examples are written as shell or Perl scripts, but any properly named executable would work just fine. If you want to use bundled example hook scripts, you’ll need to rename them, stripping the .sample extension and ensuring that they have the executable permission bit.
A template for repositories
Section titled “A template for repositories”Sometimes you would want to have the same set of hooks for all your repositories. You can have a global (per-user and system-wide) configuration file, a global attributes file, and a global ignore list. It turns out that it is possible to select hooks to be populated during the creation of the repository. The default sample hooks that get copied to the .git/hooks repository are populated from /usr/share/git-core/templates.
Also, the alternative directory with the repository creation templates can be given as a parameter to the --template command-line option (to git clone and git init), as the GIT_TEMPLATE_DIR environment variable, or as the init.templateDir configuration option (which can be set in a per-user configuration file). This directory must follow the directory structure of .git (of $GIT_DIR), which means that the hooks need to be in the hooks/ subdirectory there.
Note, however, that this mechanism has some limitations. As the files from the template directory are only copied to the Git repositories on their initialization, updates to the template directory do not affect the existing repositories. Though you can re-run git init in the existing repository to reinitialize it, just remember to save any modifications made to the hooks.
Hook management tools
Maintaining hooks for a team of developers can be tricky. There are many tools and frameworks for Git hook management; examples include Husky and pre-commit. You can find more examples of such tools listed on the https://githooks.com site. Those tools often allow for easier skipping hooks, running common code for all the hooks, or running multiple scripts for a specific hook.
Client-side hooks
Section titled “Client-side hooks”There are quite a few client-side hooks. They can be divided into the commit-workflow hooks (a set of hooks invoked by the different stages of creating a new commit), apply-email workflow hooks, and everything else (not organized into a multihook workflow).
Important note
It is important to note that hooks are not copied when you clone a repository. This is done partially for security reasons, as hooks run unattended and mostly invisibly. You need to copy (and rename) files themselves, though you can control which hooks get installed when creating or reinitializing a repository (see the previous subsection). This means that you cannot rely on the client-side hooks to enforce a policy; if you need to introduce some hard requirements, you’ll need to do it on the server side.
Commit process hooks
Section titled “Commit process hooks”There are four client-side hooks invoked (by default) while committing changes. They are as follows.
The pre-commit hook
Section titled “The pre-commit hook”The pre-commit hook is run first, even before you invoke the editor to type in the commit message. It is used to inspect the snapshot to be committed to check whether you haven’t forgotten anything. A nonzero exit from this hook aborts the commit. You can bypass invoking this hook altogether with git commit -–no-verifies. This hook takes no parameters.
This hook can, among others, be used to check for the correct code style, run the static code analyzer (linter) to check for problematic constructs, make sure that the code compiles and that it passes all the tests (and that the new code is covered by the tests), or check for the appropriate documentation on some new functionality. The default hook checks for whitespace errors (trailing whitespace by default) with git diff --check (or rather its plumbing equivalent), and optionally for non-ASCII filenames in the changed files. You can, for example, make a hook that asks for a confirmation while committing with a dirty work-arena (for the changes in the worktree that would not be a part of the commit being created); though it is an advanced technique. Or, you can have it check whether there is documentation and unit tests on the new methods.
There is also the pre-merge-commit hook that is invoked by git merge. By default the hook, when enabled, runs the pre-commit hook.
The prepare-commit-msg hook
Section titled “The prepare-commit-msg hook”The prepare-commit-msg hook is run after the default commit message is created (including the static text of the file given by commit.template, if any), and before the commit message is opened in the editor. It lets you edit the default commit message or create a template programmatically, before the commit author sees it. If the hook fails with a nonzero status, the commit will be aborted. This hook takes as parameters the path to the file that holds the commit message (later passed to the editor) and the information about source of the commit message (the latter is not present for ordinary git commit): message if the -m or -F option was given, template if the -t option was given or commit.template was set, merge if the commit is merged or the .git/MERGE_MSG file exists, squash if the .git/SQUASH_MSG file exists, or commit if the message comes from the other commit: the -c, -C, or --amend option was given. In the last case, the hook gets additional parameters, namely, a SHA-1 hash of the commit that is the source of the message.
The purpose of this hook is to edit or create the commit message, and this hook is not suppressed by the --no-verify option. This hook is most useful when it is used to affect commits where the default message is autogenerated, such as the templated commit message, merged commits, squashed commits, and amended commits. The sample hook that Git provides comments out the Conflict: part of the merge commit message.
Another example of what this hook can do is to use the description of the current branch given by branch.<branch-name>.description, if it exists, as a base for a branch-dependent dynamic commit template. Or perhaps, it can check whether we are on the topic branch, and then list all the issues assigned to you on a project issue tracker, to make it easy to add the proper artifact ID to the commit message.
The commit-msg hook
Section titled “The commit-msg hook”The commit-msg hook is run after the developer writes the commit message, but before the commit is actually written to the repository. It takes one parameter, a path to the temporary file with the commit message provided by the user (by default, .git/COMMIT_EDITMSG).
If this script exits with a nonzero status, Git aborts the commit process, so you can use it to validate that, for example, the commit message matches the project state, or that the commit message conforms to the required pattern. The sample hook provided by Git can check, sort, and remove duplicated Signed-off-by:lines (which might be not what you want to use, if signoffs are to be a chain of provenance). You could conceivably check in this hook whether the references to the issue numbers are correct (and perhaps expand them, adding the current summary of each mentioned issue).
Gerrit Code Review provides a commit-msg hook (which needs to be installed in the local Git repository) to automatically create, insert, and maintain a unique Change-Id: line above the signoffs during git commit. This line is used to track the iterations of coming up with a commit; if the commit message in the revision pushed to Gerrit lacks such information, the server will provide instructions on how to get and install that hook script.
The post-commit hook
Section titled “The post-commit hook”The post-commit hook runs after the entire process is completed. It doesn’t take any parameters, but at this point of the commit operation, the revision that got created during commit is available as HEAD. The exit status of this hook is ignored. There is also the post-merge hook.
Generally, this script (like most of the post-* scripts) is most often used for notifications and logging, and it obviously cannot affect the outcome of git commit. You can use it, for example, to trigger a local build in a continuous integration tool such as Jenkins. In most cases, however, you would want to do this with the post-receive hook on the dedicated continuous integration server.
Another use case is to list information about all the TODO and FIXME comments in the code and documentation (for example, the author, version, file path, line number, and message), printing them to the standard output of the hook, so that that they are not forgotten and remain up to date and useful.
Hooks for applying patches from emails
Section titled “Hooks for applying patches from emails”You can set up three client-side hooks for the email-based workflow (where commits are sent by email). They are all invoked by the git am command (the name of which comes from apply mailbox), which can be used to take saved emails with patches (created, for example, with git format-patch and sent with git sent-email) and turn them into a series of commits. We will cover these hooks next.
The applypatch-msg hook
Section titled “The applypatch-msg hook”The first hook to run is the applypatch-msg hook. It is run after extracting the commit message from the patch and before applying the patch itself. As usual, for a hook which is not a post-* hook, Git aborts applying the patch if this hook exists with a nonzero status. It takes a single argument: the name of the temporary file with the extracted commit message.
You can use this hook to make sure that the commit message is properly formatted, or to normalize the commit message by having the script alter the file. The example applypatch-msg hook provided by Git simply runs the commit-msg hook if it exists as a hook (the file exists and is executable).
The pre-applypatch hook
Section titled “The pre-applypatch hook”The next hook to run is the pre-applypatch hook. It is run after the patch is applied to the working area, but before the commit is created. You can use it to inspect the state of the project before making a commit; for example, by running tests. Exiting with a nonzero status aborts the git am script without committing the patch.
The sample hook provided by Git simply runs the pre-commit hook, if present.
The post-applypatch hook
Section titled “The post-applypatch hook”The last hook to run is the post-applypatch hook, which runs after the commit is made. It can be used for notifying or logging, for example, notifying all the developers or just the author of the patch that you have applied it.
Other client-side hooks
Section titled “Other client-side hooks”There are a few other client-side hooks that do not fit into a series of steps in a single process.
The pre-rebase hook
Section titled “The pre-rebase hook”The pre-rebase hook runs before you rebase anything. Like all the pre-* hooks, it can abort the rebase process with a nonzero exit code. You can use this hook to disallow rebasing (and thus rewriting) any commits that were already published. The hook is called with the name of the base branch (the upstream the series was forked from), and the name of the branch being rebased. The name of the branch being rebased is passed to the hook only if it is not the current branch. The sample pre-rebase hook provided by Git tries to do this, though it makes some assumptions specific to Git’s project development that may not match your workflow (take note that amending commits also rewrites them, and that rebasing may create a copy of a branch instead of rewriting it).
The pre-push hook
Section titled “The pre-push hook”The pre-push hook runs during the git push operation, after checking the remote status and identifying which revisions are missing on the server, but before any changes are pushed. The hook is called with the reference to the remote (the URL or the remote name) and the actual push URL (the location of remote) as the script parameters. Information about the commits to be pushed is provided on the standard input, one line per ref to be updated. You can use this hook to validate a set of ref updates before a push occurs; a nonzero exit code aborts the push. The example installed simply checks whether there are commits beginning with WIP in a set of revisions to be pushed or marked with the nopush keyword in the commit message, and when either of those is true, it aborts the push. You can even make a hook prompt the user to confirm they are sure. This hook compliments the server-side checks, avoiding data transfer that would fail validation anyway.
The post-rewrite hook
Section titled “The post-rewrite hook”The post-rewrite hook is run by commands that rewrite history (i.e., that replace commits), such as git commit --amend and git rebase. Note, however, that this hook is not run by large-scale history rewriting, such as git filter-repo. The type of command that triggered the rewrite (amend or rebase) is passed as a single argument, while the list of rewrites is sent to the standard input. This hook has many of the same uses as the post-checkout and post-merge hooks, and it runs after the automatic copying of notes, which is controlled by the notes.rewriteRef configuration variable (you can find more about the notes mechanism in Chapter 10*, Keeping* History Clean).
The post-checkout and post-merge hooks
Section titled “The post-checkout and post-merge hooks”The post-checkout hook is run after a successful git checkout (or git checkout <file>) after having updated the worktree. The hook is given three parameters: the SHA-1 hashes of the previous and current HEAD (which may or may not be different) and a flag indicating whether it was a whole project checkout (you were changing branches; the flag parameter is 1) or a file checkout (retrieving files from the index or named commit; the flag parameter is 0). As a special case, during the initial checkout after git clone, this hook passes the all-zero SHA-1 as the first parameter (as a source revision). You can use this hook to set up your working directory properly for your use case. This may mean handling large binary files outside the repository (as an alternative to applying the filter Git attribute on a per-file basis) that you don’t want to have in the repository, or setting the working directory metadata properties such as full permissions, owner, group, times, extended attributes, or ACLs. It can also be used to perform repository validity checks or enhance the git checkout output by auto-displaying the differences (or just the diff statistics) from the previous checked-out revision (if they were different).
The post-merge hook runs after a successful merge operation. You can use it in a way similar to post-checkout to restore data and metadata in the working tree that Git doesn’t track, such as full permissions data (or just make it invoke post-checkout directly). This hook can likewise validate the presence of files external to Git control that you might want copied in when the working tree changes.
For Git, objects in the repository (for example, commit objects representing revisions) are immutable; rewriting history (even amending a commit) is in fact creating a modified copy and switching to it, leaving the pre-rewrite history abandoned.
The pre-auto-gc hook
Section titled “The pre-auto-gc hook”Deleting a branch also leaves abandoned history. To prevent the repository from growing too much, Git occasionally performs garbage collection by removing old unreferenced objects. In all but the most ancient instances of Git, this is done as a part of normal Git operations by invoking git gc --auto. The pre-auto-gc hook is invoked just before garbage collection takes place and can be used to abort the operation, for example, if you are on battery power. It can also be used to notify you that garbage collection is happening.
Server-side hooks
Section titled “Server-side hooks”In addition to the client-side hooks, which are run in your own repository, there are a couple of important server-side hooks that a system administrator can use to enforce nearly any kind of policy for your project.
These hooks are run before and after you do a push to the server. The pre hooks (as mentioned earlier) can exit nonzero to reject a push or part of it; messages printed by the pre hooks will be sent back to the client (sender). You can use these hooks to set up complex push policies. Git repository management tools, such as gitolite and Git hosting solutions, use these to implement more involved access control for repositories. The post hooks can be used for notification, starting a build process (or just to rebuild and redeploy the documentation), or running a full test suite, for example as a part of a CI solution.
When writing server-side hooks, you need to take into account where in the sequence of operations the hook takes place and what information is available there, in the form of parameters, on the standard input, and in the repository.
Let’s review what happens on the server when it receives a push:
- Simplifying it a bit, the first step is that all the objects that were present in the client and missing on the server are sent to the server and stored (but are not yet referenced). If the receiving end fails to do this correctly (for example, because of the lack of disk space), the whole push operation will fail.
- The pre-receive hook is run. It takes a list describing the references that are being pushed on its standard input. If it exits with a nonzero status, it aborts the whole operation and none of the references that were pushed are accepted.
- For each ref being updated, the built-in sanity checks may reject the push to the ref, including the check for an update of a checked-out branch, a non-fast-forward push (unless forced), and so on.
- The update hook is run for each ref, passing ref to be pushed in arguments; if this script exits with a nonzero status, only this ref will be rejected.
- For each pushed ref, the ref in question is updated (unless it was rejected in an earlier stage).
- The post-receive hook is run, taking the same data as the
pre-receiveone. This one can be used to update other services (for example, to notify CI servers) or notify users (via an email or a mailing list, IRC, or a ticket-tracking system).
If the push is atomic, either all the refs are updated (if none were rejected), or none are updated.
For each ref that was updated, the post-update hook is run. This can also be used for logging. The sample hook runs git update-server-info to prepare a repository, saving extra information to be used over dumb transports, though it would work better if run once as post-receive.
If push tries to update the currently checked-out branch and the receive.denyCurrentBranch configuration variable is set to updateInstead, then the push-to-checkout hook is run.
Important note
You need to remember that in pre hooks, you don’t have refs updated yet, and that post hooks cannot affect the result of an operation. You can use pre hooks for access control (permission checking), and post hooks for notification and updating side data and logs.
You will see example hooks (server-side and client-side) for the Git-enforced policy in Chapter 14, Git Administration. You will also learn how other tools use those hooks, for example, for use in access control and triggering actions on push.
Extending Git
Section titled “Extending Git”Git provides a few mechanisms to extend it. You can add shortcuts and create new commands, and add support for new transports; all without requiring you to modify Git sources.
Command aliases for Git
Section titled “Command aliases for Git”There is one little tip that can make your Git command-line experience simpler, easier, and more familiar, namely, Git aliases. It is very easy in theory to create an alias. You simply need to create an alias.<command-name> configuration variable; its value is the expansion of the alias.
One of the uses for aliases is defining short abbreviations for commonly used commands and their arguments. Another is creating new commands. Here are a couple of examples you might want to set up:
$ git config --global alias.co checkout$ git config --global alias.ps = '--paginate status'$ git config --global alias.lg "log --graph --oneline --decorate"$ git config --global alias.aliases 'config --get-regexp ^alias\.'The preceding setup means that typing, for example, git co would be the same as typing git checkout, and git aliases would print all defined aliases. Aliases take arguments just as the regular Git commands do. Git does not provide any default aliases to define shortcuts for common operations, unless you use `git-fc` project, a friendly fork of Git by Felipe Contreras.
Arguments here are split by spaces and the usual shell quoting and escaping is supported. Notably, you can use a quote pair ("a b") or a backslash (a\ b) to include a space in a single argument.
Important note
Note, however, that you cannot have an alias with the same name as a Git command. In other words, you cannot use aliases to change the behavior of commands. The reasoning behind this restriction is that it could make existing scripts and hooks fail unexpectedly. Aliases that hide existing Git commands (with the same name as Git commands) are simply ignored.
You might, however, want to run an external command rather than a Git command in an alias. Or, you might want to join together the result of a few separate commands. In this case, you can start the alias definition with the ! character:
$ git config --global alias.unmerged \ '!git ls-files --unmerged | cut -f2 | sort -u'Because here the first command of the expansion of an alias can be an external tool, you need to specify the git wrapper explicitly, as shown in the preceding example.
Note
Note that in many shells, for example, in bash, the exclamation character ! is the history expansion character and it needs to be escaped as \! or be within single quotes (').
Note that such shell commands will be executed from the top-level directory of a repository (after doing cd to a top-level), which may not necessarily be the current directory. Git sets the GIT_PREFIX environment variable to the current directory path relative to the top directory of a repository, that is, git rev-parse --show-prefix. As usual, git rev-parse (and some git wrapper options) may be of use here.
The fact mentioned earlier can be used while creating aliases. The git serve alias, running git daemon to serve (read-only) the current repository at git://127.0.0.1/, makes use of the fact that the shell commands in aliases are executed from the top-level directory of a repo:
[alias] serve = !git daemon --reuseaddr --verbose --base-path=. --export-all ./.gitSometimes, you need to reorder arguments, use an argument twice, or pass an argument to the command early in the pipeline. You would want to refer to subsequent arguments as $1, $2, and so on, or to all arguments as $@, just like in shell scripts. One trick that you can find in older examples is to run a shell with a -c argument, like in the first of the examples mentioned next; the final dash is so that the arguments start with $1, not with $0. A more modern idiom is to define and immediately execute a shell function, like in the second example (it is a preferred solution because it uses one level of quoting less, and lets you use standard shell argument processing):
[alias] record-1 = !sh -c 'git add -p -- $@ && git commit' - record-2 = !f() { git add -p -- $@ && git commit }; fAliases are integrated with command-line completion. While determining which completion to use for an alias, Git searches for a git command, skipping an opening brace or a single quote (thus, supporting both of the idioms mentioned earlier). With modern Git you can use the null command “:” to declare the desired completion style. For example, alias expanding to the following:
!f() { : git commit ; ... } fwould use a command completion for git commit, regardless of the rest of the alias.
Git aliases are also integrated with the help system. If you use the --help option on an alias, Git tells you its expansion (so you can check the relevant man page):
$ git co --help'git co' is aliased to 'checkout'Adding new Git commands
Section titled “Adding new Git commands”Aliases are best at taking small one-liners and converting them into small useful Git commands. You can write complex aliases, but when it comes to larger scripts, you would probably like to incorporate them into Git directly.
Git subcommands can be standalone executables that live in the Git execution path (which you can find by running git --exec-path); on Linux, this is normally /usr/libexec/git-core. The git executable itself is a thin wrapper that knows where the subcommands live. If git foo is not a built-in command, the wrapper searches for the git-foo command first in the Git exec path, then in the rest of your $PATH. The latter makes it possible to write local Git extensions (local Git commands) without requiring access to the system’s space.
This feature is what it makes possible to have a user interface more or less integrated with the rest of Git in projects such as git imerge (see Chapter 9, Merging Changes Together), or git lfs or git annex (see Chapter 12,Managing Large Repositories). It is also how projects such as Git Extras, providing extra Git commands, were made.
Note, however, that if you don’t install the documentation for your command in typical places, or configure the documentation system to find the help page for a command, then git foo --help won’t work correctly.
You can list all external commands installed this way with git --list-cmds=others, or you can use git help --all, and the following list will appear at the end of its command output:
$ git --list-cmds=others credential-helper-selector credential-manager lfsCredential helpers and remote helpers
Section titled “Credential helpers and remote helpers”There is another place where simply putting an appropriately named executable enhances and extends Git. Remote helper programs are invoked by Git when it needs to interact with remote repositories and remote transport protocols not supported by Git natively. You can find more about them in Chapter 6, Collaborative Development with Git.
When Git encounters a URL of the form <transport>://<address>, where <transport> is a (pseudo)protocol that is not natively supported, it automatically invokes the git remote-<transport> command with a remote and full remote URL as arguments. A URL of the form <transport>::<address> also invokes this remote helper, but with just <address> as a second argument in the place of a URL. Additionally, with remote.<remote-name>.vcs set to <transport>, Git would explicitly invoke git remote-<transport> to access that remote.
The helpers mechanism in Git is about interacting with external scripts using a well-defined format.
Each remote helper is expected to support a subset of commands. You can find more information about the issue of creating new helpers on the gitremote-helpers(1) man page.
There is another type of helpers in Git, namely, credentials helpers. They can be used by Git to get the credentials from the user required, for example, to access a remote repository over HTTP. They are specified by the configuration, though, just like the merge and diff drivers and the clean and smudge filters.
Summary
Section titled “Summary”This chapter provided all the tools you need to use Git effectively. You got to know how to make the command-line interface easier to use and more effective with the Git-aware dynamic command prompt, command-line completion, autocorrection for Git commands, and using colors. You learned of the existence of alternative interfaces, from alternative porcelains to the various types of graphical clients.
You were reminded of the various ways to change the behavior of Git commands. You discovered how Git accesses its configuration and learned about a selected subset of configuration variables. You have learned how to automate Git with hooks and how to make use of them. Finally, you have learned how to extend Git with new commands and support new URL schemes.
This chapter was mainly about making Git more effective for you; the next chapter, Chapter 14*,* Git Administration, explains how to make Git more effective for other developers. You will cover more about server-side hooks and see their usage. You will also learn about repository maintenance.
Questions
Section titled “Questions”Answer the following questions to test your knowledge of this chapter:
- How do you save and reuse your favorite combination of options for the Git command?
- How can you find all created aliases?
- How do you run a graphical tool to display a
git diff, or to help with resolving a merge? - How can you find where a given configuration came from?
- How can you help ensure that a commit matches the recommended best practices?
Answers
Section titled “Answers”Here are the answers to the questions given above:
- Use a Git alias, a shell alias, or a shell function.
- You can use the
git config --get-regexp ^alias\.command. - Use
git difftoolfor displaying differences, orgit mergetoolto help with resolving merge conflicts. There is built-in support for many of the existing graphical tools. - If it is about configuration values, you can use
git config --show-origin(or--show-scope). If it is about per-file attributes, usegit check-attr. If it is about ignoring files, usegit check-ignore. - Use the
pre-commithook (and other similar hooks) to warn if best practices are not being followed. There are many third-party tools that help with hook management and often support various helper tools such as linters and code formatting tools.
Further reading
Section titled “Further reading”To learn more about the topics that were covered in this chapter, take a look at the following resources:
- Scott Chacon, Ben Straub: Pro Git, 2nd Edition (2014), Apress https://git-scm.com/book/en/v2
- Chapter 2 - Git Basics, Section 2.1 - Git Aliases
- Chapter 8 - Customizing Git
- Appendix A: Git in Other Environments
- Chapter 2 - Git Basics, Section 2.1 - Git Aliases
- Matthew Hudson: Git Hooks - A Guide for Programmers https://githooks.com/
- bash/zsh git prompt support https://github.com/git/git/blob/master/contrib/completion/git-prompt.sh
- bash/zsh completion support for core Git https://github.com/git/git/blob/master/contrib/completion/git-completion.bash
- Seth House: Conflict resolution in various mergetools (2020) https://www.eseth.org/2020/mergetools.html
- Julia Evans: Popular git config options (2024) https://jvns.ca/blog/2024/02/16/popular-git-config-options/
- Ricardo Gerardi: 8 Git aliases that make me more efficient (2020) https://opensource.com/article/20/11/git-aliases
- Git SCM Wiki (archived): Aliases https://archive.kernel.org/oldwiki/git.wiki.kernel.org/index.php/Aliases.html
- Git Homepage - GUI Clients https://git-scm.com/downloads/guis
- Git Rev News https://git.github.io/rev_news/