Skip to content
ImagineWorld

Git Administration

node_idnode-book_mastering-git_chapter-14-git-administration
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num14
chapter_titleGit Administration
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

The previous chapter, Customizing and Extending Git, among other things, explained how to use Git hooks for automation. The client-side hooks were described in detail, while the server-side hooks were only covered briefly. In this chapter, we will cover server-side hooks comprehensively and discuss client-side hooks’ usage as helpers.

The earlier chapters helped master your work with Git as a developer, as a team member collaborating with others, and as a maintainer. When the book discussed setting up repositories and branch structure, it was from the point of view of a Git user.

This chapter is intended to help those of you who are in a situation of dealing with the administrative side of Git. This includes setting up remote Git repositories and configuring their access. This chapter covers the work required to make Git go smoothly (that is, Git maintenance) and finding and recovering from repository errors. It also describes how to use server-side hooks to implement and enforce a development policy. Additionally, you will find here a short description of the various types of tools that can be used to manage remote repositories, helping you to choose from them.

In this chapter, we will cover the following topics:

  • Server-side hooks – implementing a policy and notifications
  • How to set up Git on a server
  • Third-party tools to manage remote repositories
  • Signed pushes to assert updating refs and enable audits
  • Reducing the size of hosted repositories with alternates and namespaces
  • Improving server performance and helping the initial clone
  • Checking for repository corruption and fixing a repository
  • Recovering from errors with the help of reflogs and git fsck
  • Git repository maintenance and repacking
  • Augmenting development workflows with Git

Occasionally, you may need to do some cleanup of a repository, usually to make it more compact. Such cleanups are also a very important step after migrating a repository from another version control system.

Modern Git (or, rather, all but ancient Git) from time to time runs the git gc --auto command in each repository. This command checks whether there are too many loose objects (objects stored as separate files, with one file per object, rather than those stored together in a packfile; objects are almost always created loosely), and if so, then it launches the garbage collection operation. Garbage collection means gathering up all the loose objects and placing them in packfiles, as well as consolidating many small packfiles into one large packfile. Additionally, it packs references into the packed-refs file. Objects that are unreachable even via reflog and are safely old are, by default, packed separately into a cruft pack. Git then deletes loose objects, cruft packs, and packfiles that got repacked (with some safety margin relating to the age of the loose objects files), thus pruning old unreachable objects. There are various configuration knobs in the gc.* namespace to control garbage collection operations.

You can run auto gc manually with git gc --auto or force garbage collection with git gc. The git count-objects command (sometimes with the help of the -v parameter) can be used to check whether there are signs that a repack is needed. You can even run individual steps of the garbage collection individually with git repack, git pack-refs, git prune, and git prune-packed.

By default, Git will try to reuse the results of an earlier packing to reduce CPU time spent on repacking, while still providing good disk space utilization. In some cases, you will want to more aggressively optimize the size of the repository at the cost of it taking more time; this is possible with git gc --aggressive (or by repacking the repository by hand with git repack, run with appropriate parameters). It is recommended to do this after importing from other version control systems, as the mechanism that Git uses for importing (namely, the fast-import stream) is optimized for the speed of the operation, not for the final repository size.

There are issues of maintenance not covered by git gc because of their nature. One of them is pruning (deleting) remote-tracking branches that were deleted in the remote repository. This can be done with git fetch --prune or git remote prune, or on a per-branch basis with git branch --delete --remotes <remote-tracking branch>. This action is left to the user and not run by git gc, as Git simply cannot know whether you have based your own work on the remote-tracking branch that will be pruned.

Git commands that add data to the repository, such as git add or git fetch, can trigger automatic garbage collection and perform some repository optimization. However, because they need to provide a responsive user interface, this does not trigger more costly repository optimizations. Those tasks include updating the commit graph data, prefetching from remote repositories (so that git fetch will have fewer objects to download), cleaning up loose objects, and doing an incremental repack. Such optimization tasks often scale with the full size of the repository.

A better solution is to run the maintenance tasks that are expensive in the background, periodically – hourly, daily, or weekly. With modern Git, you can schedule those tasks with the help of the git maintenance command. It will schedule those jobs differently depending on the operating system.

You can configure how often a given task is run. Note that git maintenance run, a process that performs scheduled tasks, puts a lock on the repository’s object database, preventing competing processes from leaving the repository in an unpredicted state. This is not the case for git gc; therefore, if you do periodic maintenance, use git maintenance run --task=gc instead of the git gc command.

It is almost impossible to never make any mistakes. This applies also to using Git. The knowledge presented in this book, and your experience with using Git, should help to reduce the number of mistakes. Note that Git tries quite hard not to help you avoid losing your work; many mistakes are recoverable. The next subsection will explain how you can try to recover from an error.

It may happen that you accidentally lost a commit. Perhaps you force-deleted an incorrect branch that you were going to work on, you rewound the branch to an incorrect place, or you were on an incorrect branch while starting an operation. Assuming something like this happened, is there any way to get your commits back and undo the mistake?

Because Git does not delete objects immediately and keeps them for a while, only deleting them if they are unreachable during the garbage collection phase, the commit you lost will be there; you just need to find it. The garbage collection operation has, as mentioned, its own safety margins; however, if you find that you need to troubleshoot, it is better to turn off automatic garbage collection temporarily with git config gc.auto never (and turning off the gc task if it is scheduled to run periodically with git maintenance, by setting maintenance.gc.enabled to false or by turning maintenance off with git maintenance unregister).

Often, the simplest way to find and recover lost commits is to use the git reflog tool. For each branch, and separately for the HEAD, Git silently records (logs) where the tip of the branch was in your local repository, what time it was there, and how it got there. This record is called the reflog. Each time you commit or rewind a branch, the reflog for the branch and the HEAD is updated. Each time you change the branches, the HEAD reflog is updated, and so on.

You can see where the tip of a branch has been at any time by running git reflog or git reflog <branch>. You can also run git log -g, where -g is a short way of saying --walk-reflog; this gives you a normal configurable log output. There is also --grep-reflog=<pattern> to search the reflog:

$ git reflog
6c89dee HEAD@{0}: commit: Ping asynchronously
d996b71 HEAD@{1}: rebase -i (finish): returning to refs/heads/ajax
d996b71 HEAD@{2}: rebase -i (continue): Ping asynchronously WIP
89579c9 HEAD@{3}: rebase -i (pick): Use Ajax mode
7c6d322 HEAD@{4}: commit (amend): Simplify index()
e1e6f65 HEAD@{5}: cherry-pick: fast-forward
eea7a7c HEAD@{6}: checkout: moving from ssh-check to ajax
c3e77bf HEAD@{7}: reset: moving to ajax@{1}

You should remember the <ref>@{<n>} syntax from Chapter 4, Exploring Project History. With the information from reflogs, you can rewind the branch in question to the version from before the set of operations, or you can start a new branch, starting with any commit in the list.

Let’s assume that your loss was caused by deleting the wrong branch. Because of the way reflogs are implemented (e.g., logs for a branch named foo – that is, for the refs/heads/foo ref – are kept in the .git/logs/refs/heads/foo file), a reflog for a given branch is deleted, together with the branch. You might still have the necessary information in the HEAD reflog, unless you have manipulated the branch tip without involving the working area, but it might not be easy to find it.

In a case where the information is not present in reflogs, one way to find the necessary information to recover lost objects is to use the git fsck utility, which checks your repository for integrity. With the --full option, you can use this command to show all unreferenced objects:

$ git fsck --full
Checking object directories: 100% (256/256), done.
Checking objects: 100% (58/58), done.
dangling commit 50b836cb93af955ca99f2ccd4a1cc4014dc01a58
dangling blob 59fc7435baf79180a3835dddc52752f6044bab99
dangling blob fd64375c1f2b17b735f3145446d267822ae3ddd5
[...]

You can see the SHA1 identifiers of the unreferenced (lost) commits in the lines with the dangling commit string prefix. To examine all these dangling commits, you can filter the git fsck output for the commits with grep "commit", extract their SHA1 identifiers with cut -d' ' -f3, and then feed these revisions into git log --stdin --no-walk, as shown here:

$ git fsck --full | grep "commit" | cut -d' ' -f3 | git log --stdin --no- walk

Tip

The same technique, but with using blob command, can be used to recover accidentally deleted files – assuming that you have used git add with the version of the file you want to recover.

The main purpose of git fsck is to check for repository corruption. Besides having the option to find dangling objects, this command runs sanity checks for each object and tracks the reachability fully. It can find corrupted and missing objects; then, if the corruption was limited to your clone and the correct version can be found in other repositories (in backups and other archives), you can try to recover those objects from an uncorrupted source.

Sometimes, however, the error might be more difficult to recover from. You can try to find a Git expert outside your team, but often, the data in the repository is proprietary. Creating a minimal reproduction of the problem is not always possible. With modern Git, if the problem is structural, you can try to use git fast-export --anonymize to strip the repository from the data, while ensuring that the anonymized repository reproduces the issue. Reproducing some bugs may require referencing particular commits or paths; with modern Git, you can ask for a particular token to be left as-is, or mapped to a new value with a set of -- anonymize-map options.

If the repository is fine but the problem is with the Git operations, you can try to use various tracking and debugging mechanisms built into Git, or you can try to increase the verbosity of the commands. You can turn on tracing with the appropriate environment variables (which we will show later). The trace output can be written to a standard error stream by setting the value of the appropriate environment variable to 1, 2, or true. The 0 or false value disables it. Other integer values between 2 and 10 will be interpreted as open file descriptors to be used for trace output. You can also set such environment variables to the absolute path of the file to write trace messages to.

These tracking-related variables include the following (see the manpage of the git wrapper for the complete list):

  • GIT_TRACE: This enables general trace messages that do not fit into any specific category. This includes the expansion of Git aliases (see Chapter 13, Customizing and Extending Git), built-in command execution, and external command execution (such as pager, editor, or helper).
  • GIT_TRACE_PACKET: This enables packet-level tracking of the network operations for the “smart” transport protocols. This can help to debug protocol issues or any troubles with the remote server that you set up. To debug and fetch from shallow repositories, there is GIT_TRACE_SHALLOW.
  • GIT_TRACE_CURL (possibly with GIT_TRACE_CURL_NO_DATA): This enables a curl full trace dump of the HTTP(S) transport protocol, similar to running the curl -- trace-ascii option.
  • GIT_TRACE_SETUP: This enables trace messages, printing information about the location of the administrative area of the repository, the working area, the current working directory, and the prefix (the last one is the subdirectory inside the repository directory structure).
  • GIT_TRACE_PERFORMANCE: This shows the total execution time of each Git command.

With modern Git, you can enable more detailed trace messages from the trace2 library, either in a simple text-based format meant for human consumption with GIT_TRACE2, or in the JSON-based format meant for machine interpretation with GIT_TRACE2_EVENT. In addition to redirecting the output from a standard error, to a given file descriptor, or to a given file, you can also ask to write output files to a given directory (one file per process) and even ask to open the path as a Unix domain socket. The Trace2 API replacement for GIT_TRACE_PERFORMANCE is GIT_TRACE2_PERF. Instead of environment variables, you can use the trace2.normalTarget, trace2.eventTarget, and trace2.perfTarget configuration variables, respectively.

There is also GIT_CURL_VERBOSE to emit all the messages generated by the curl library for the network operations over HTTP, and GIT_MERGE_VERBOSITY to control the amount of output shown by the recursive merge strategy.

The previous chapters should have given you enough knowledge to master most of the day-to-day version control tasks in Git. Chapter 6, Collaborative Development with Git, explained how you can lay out repositories for collaboration. Here, we will explain how to set up Git repositories to enable remote access on a server, allowing you to fetch from and push to them.

The topic of administration of the Git repositories is a large one. There are books written about specific repository management solutions, such as Gitolite, Gerrit, GitHub, or GitLab. Here, you will hopefully find enough information to help you choose a solution or your own.

Let’s start with the tools and mechanisms to manage remote repositories themselves, and then move on to the ways of serving Git repositories (i.e., putting Git on the server).

Hooks that are invoked on the server can be used for server administration; among others, these hooks can control access to the remote repository by performing the authorization step, and they can ensure that the commits entering the repository meet certain minimal criteria. The latter is best done with the additional help of client-side hooks, which were discussed in Chapter 13, Customizing and Extending Git. That way, users are not notified that their commits do not pass muster only when they want to publish them. Conversely, client-side hooks implementing validation are easy to skip with the --no-verify option (so server-side validation is necessary), and you need to remember to install them.

Important note

Note, however, that server-side hooks are invoked only during the push operation; you need other solutions for access control to the fetch (and clone) operation.

Hooks are also obviously not run while using “dumb” protocols – there is no Git on the server invoked then.

While writing hooks to implement some Git-enforced policy, you need to remember at what stage the hook in question is run and what information is available then. It is also important to know how the relevant information is passed to the hook; however, you can find the last quite easily in the Git documentation on the githooks man page. The previous chapter included a simple summary of server-side hooks. Here, we will expand a bit on this topic.

All the server-side hooks are invoked by git receive-pack, which is responsible for receiving published commits (which are received in the form of a packfile, hence the name of the command). If a hook, except for a post-* one, exits with the non-zero status, then the operation is interrupted and no further stages are run. The post hooks are run after the operation finishes, so there is nothing to interrupt.

Both the standard output and the standard error output are forwarded to git send-pack at the client end, so the hooks can simply pass messages for the user by printing them (for example, with echo, if the hook was written as a shell script). Note that the client doesn’t disconnect until all the hooks complete their operation, so be careful if you try to do anything that may take a long time, such as automated tests. It is better to have a hook simply start such long operations asynchronously and exit, allowing the client to finish.

You need to remember that, with 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, updating the side data, and logging. Hooks are listed in the order of operation.

The first hook to run is the pre-receive hook. It is invoked just before you start updating refs (branches, tags, notes, and so on) in the remote repository, but after all the objects are received. It is invoked once for the receive operation. If the server fails to receive published objects (for example, because of a lack of disk space or incorrect permissions), the whole git push operation will fail before Git invokes this hook.

This hook receives no arguments; all the information is received on the standard input of the script. For each ref to be updated, it receives a line in the following format:

<old-SHA1-value> <new-SHA1-value> <full-ref-name>

Refs that need to be created will have the old SHA1 value of 40 zeros, while refs that need to be deleted will have a new SHA1 value equal to the same. The same convention is used in all the other places, where the hooks receive the old and new state of the updated ref.

Push options

You can pass additional data to the server with git push --push-option=<option> or the push.pushOption configuration variable. Both can be given multiple times. This data is then passed to pre-receive and post-receive hooks via environment variables – GIT_PUSH_OPTION_COUNT and GIT_PUSH_OPTION_0, GIT_PUSH_OPTION_1, and so on.

This hook can be used to quickly abort the operation if the update cannot to be accepted – for example, if the received commits do not follow the specified policy or if the signed push (more on this later) is invalid. Note that to use it for access control (i.e., authorization) you need to get the authentication token somehow, be it with the getpwuid command or with an environment variable such as USER. However, this depends on the server setup and the server configuration.

The push-to-checkout hook to push to non-bare repositories

Section titled “The push-to-checkout hook to push to non-bare repositories”

When pushing to the non-bare repositories, if a push operation tries to update the currently checked-out branch, then the push-to-checkout hook will be run. This is done if the receive.denyCurrentBranch configuration variable is set to the updateInstead value (instead of one of the true or refuse, warn or false, or ignore values). This hook receives the SHA1 identifier of the commit that will be the tip of the current branch that is going to be updated.

This mechanism is intended to synchronize working directories when one side is not easily accessible interactively (for example, accessible via interactive ssh), or as a simple deployment scheme. It can be used to deploy to a live website or to run code tests on different operating systems.

If this hook is not present, Git will refuse the update of the ref if either the working tree or the index (the staging area) differs from HEAD – that is, if the status is “not clean.” This hook should be used to override this default behavior.

You can craft this hook to have it make changes to the working tree and the index that are necessary to bring them to the desired state. For example, the hook can simply run git read-tree -u -m HEAD "$1" to switch to the new branch tip (the -u option updates the files in the working tree), while keeping the local changes (the -m option makes it perform a fast-forward merge with two commits/trees). If this hook exits with a nonzero status, then Git will refuse to push to the currently checked-out branch.

The next to run is the update hook, which is invoked separately for each ref that is updated. This hook is invoked after the non-fast-forward check (unless the push is forced) and the per-ref built-in sanity checks that can be configured with receive. denyDeletes, receive.denyDeleteCurrent, receive.denyCurrentBranch, and receive.denyNonFastForwards.

Note that exiting with nonzero refuses the ref to be updated; if the push is atomic (git push --atomic), then refusing any ref to be updated will abandon the whole push operation. With an ordinary push, only the update of a single ref will be refused; the push of other refs will proceed normally.

This hook receives the information about the ref to be updated as its parameters, in order:

  • The full name of the ref that is updated,
  • The old SHA1 object name stored in the ref before the push operation
  • The new SHA1 object name to be stored in the ref after the push operation

The update.sample hook example can be used to block unannotated tags from entering the repository, and also to allow or deny deleting and modifying tags and deleting and creating branches. All the configurable of this sample hook is done with the appropriate hooks.* configuration variables, rather than being hardcoded. There is also the update-paranoid Perl script in contrib/hooks/, which can be used as an example of how to use this hook for access control. This hook is configured with an external configuration file, where, among other options, you can set up access so that only commits and tags from specified authors are allowed, and authors are required to have correct access permissions.

Many repository management tools, such as Gitolite, set up and use this hook for their work. You need to read the tool documentation if you want, for some reason, to run your own update hook together with the one provided by such a tool, perhaps with the help of some hook management tool (see, for example, a list of such tools on https://githooks.com/).

Then, after all the refs are updated, the post-receive hook is run. It takes the same data as the pre-receive one. Only now do all the refs point to the new SHA1s. It can happen that another user has modified the ref after it was updated but before the hook was able to evaluate it. This hook can be used to update other services (for example, notify the continuous integration server), notify users (via an email or a mailing list, a chat channel, or a ticket-tracking system), or log the information about the push for audit (for example, about signed pushes). It supersedes the post-update hook, and should be used instead.

There is no default post-receive hook, but you can find the simple post-receive-email script, and its replacement, git-multimail, in the contrib/hooks/ area.

These two example hooks are actually developed separately from Git itself, but for convenience, they are provided with the Git source. git-multimail sends one email summarizing each changed ref, one email for each new commit with the changes – threaded (as a reply) to the corresponding ref change email, and one announcement email for each new annotated tag. Each of these is separately configurable with respect to the email address used and, to some extent, also with respect to the information included in the emails.

To provide an example of third-party tools, irker includes the script to be used as Git’s post-receive hook to send notifications about the new changes to the appropriate IRC channel, using the irker daemon (set up separately).

Then, the post-update hook is run. Each ref that was actually successfully updated passes its name as one of parameters; this hook takes a variable number of parameters. This is only partial information; you don’t know what the original (old) and updated (new) values of the updated refs were, and the current position of the ref is prone to race conditions (as explained before). Therefore, if you actually need the position of the refs, the post-receive hook is a better solution.

The sample hook runs git update-server-info to prepare a repository for use over the dumb transports(described in the Legacy (dumb) transports section of Chapter 7*, Publishing Your Changes*, and in the Dumb protocols section later in this chapter), by creating and saving some extra information. If the directory with the repository is to be accessible via plain HTTP or other walker-based transport like FTP, you may consider enabling it. However, in modern Git, it is enough to simply set receive.updateServerInfo to true so that a hook is no longer necessary.

Using hooks to implement Git-enforced policy

Section titled “Using hooks to implement Git-enforced policy”

The only way to truly enforce a policy is to implement it using server-side hooks, either pre-receive or update; if you want a per-ref decision, you need to use the latter. Client-side hooks can be used to help developers pay attention to the policy, but these can be disabled, skipped, or not enabled.

Enforcing the policy with server-side hooks

Section titled “Enforcing the policy with server-side hooks”

One part of the development policy could be requiring that each commit message adheres to a specified template. For example, you could require each non-merge commit message to include the digital certificate of origin in the form of the Signed-off-by: line, or that each commit refers to the issue tracker ticket by including a string that looks like ref: 2387. The possibilities are endless.

To implement such a hook, you first need to turn the old and new values for a ref (that you got by either reading them line by line from the standard input in pre-receive, or as the update hook parameters) into a list of all the commits that are being pushed. You need to take care of the corner cases – deleting a ref (no commits pushed), creating a new ref, and a possibility of non-fast-forward pushes (where you need to use the merge base as the lower limit of the revision range – for example, with the git merge-base command), pushes to tags, pushes to notes, and other non-branch pushes. The operation of turning a revision range into a list of commits can be done with the git rev-list command, which is a low-level equivalent (plumbing) of the user-facing git log command (porcelain); by default, this command prints out only the SHA1 values of the commits in the specified revision range, one per line, and no other information.

Then, for each revision, you need to grab the commit message and check whether it matches the template specified in the policy. You can use another plumbing command, called git cat-file, and then extract the commit message from this command output by skipping everything before the first blank line. This blank line separates commit metadata in the raw form from the commit body:

$ git cat-file commit a7b1a955
tree 171626fc3b628182703c3b3c5da6a8c65b187b52
parent 5d2584867fe4e94ab7d211a206bc0bc3804d37a9
author Alice Developer 1440011825 +0200
committer Alice Developer 1440011825 +0200
Added COPYRIGHT file

Alternatively, you can use git show -s or git log -1, which are both porcelain commands, instead of git cat-file. However, you would then need to specify the exact output format – for example, git show -s -- format=%B <SHA1>.

When you have these commit messages, you can then use the regular expression match or another tool on each of the commit messages caught to check whether they matche the policy.

Another part of the policy may be the restrictions on how branches are managed. For example, you may want to prevent the deletion of long-lived development stage branches (see Chapter 8, Advanced Branching Techniques), while allowing the deletion of topic branches. To distinguish between them – that is, to find out whether the branch being deleted is a topic branch or not – you can either include a configurable list of branches to manage strictly, or you can assume that topic branches always use the <user>/<topic> naming convention. The latter solution can be enforced by requiring the newly created branches, which should be topic branches only, to match this naming convention.

Conceivably, you could make a policy that topic branches can be fast-forwarded only if they are not merged in, although implementing checks for this policy would be nontrivial.

Usually, only specific people have permission to push to the official repository of a project (holding a so-called commit bit). With server-side hooks, you can configure the repository so that it allows anyone to push, but only to the special mob branch; all the other push access is restricted.

You can also use server-side hooks to require that only annotated tags are allowed in the repository, that tags are signed with a public key that is present in the specified key server (and, thus, can be verified by other developers), and that tags cannot be deleted or updated. If needed, you can restrict signed tags to those coming from the selected (and configured) set of users – for example, enforcing a policy that only one of the maintainers can mark a project for a release (by creating an appropriately named tag – e.g., v0.9).

Early notices about policy violations with client-side hooks

Section titled “Early notices about policy violations with client-side hooks”

It would be not a good solution to have strict enforcement of development policies and not provide users with a way to help watch and fulfill those policies. Having your work rejected during a push can be frustrating; to fix the issue preventing one from publishing the commit, you would have to edit your local history of the project (that is, rewrite your changes). See Chapter 10, Keeping History Clean, for details on how to do it.

The answer to that problem is to provide some client-side hooks that users can install and have Git notify them immediately when they violate the policy, which would make their changes get rejected by the server. The intent is to help correct any problem as fast as possible, usually before committing the changes. These client-side hooks must be distributed somehow, as hooks are not copied when cloning a repository. Various ways to distribute these hooks are described in Chapter 13, Customizing and Extending Git.

If there are any limitations on the contents of the changes (for example, some files might be changed only by specified developers), a warning message can be created with pre-commit hook. The prepare-commit-msg hook (and the commit.template configuration variable) can provide the developer with a customized template to be filled in while working on a commit message. You can also make Git check the commit message, just before the commit is recorded, with the commit-msg hook. This hook would find out and inform you whether you have correctly formatted the commit message and whether it includes all the information required by the policy. This hook can also be used instead of or in addition to pre-commit, checking whether you are modifying the files you are not allowed to.

The pre-rebase hook can be used to verify that you don’t try to rewrite history in a manner that would lead to a non-fast-forward push (with receive.``denyNonFastForwards on the server, forcing a push won’t work anyway).

As a last resort, there is a pre-push hook, which can check for correctness before trying to connect to the remote repository.

Chapter 6, Collaborative Development with Git, includes a description of various mechanisms that a developer can use to ensure the integrity and authenticity of their work – signed tags, signed commits, and signed merges (merging signed tags). All these mechanisms assert that the objects (and the changes they contain) came from the signer.

However, signed tags and commits do not assert that the developer wanted to have a particular revision at the tip of a particular branch. Authentication done by the hosting site cannot be easily audited later, and it requires you to trust the hosting site and its authentication mechanism. Modern Git (version 2.2 or newer) allows you to sign pushes for this purpose.

Signed pushes require the server to set up receive.certNonceSeed and the client to use git push --signed. Handling of signed pushes is done with the server-side hooks. Currently, none of the Git forges such as GitHub, GitLab, Bitbucket, or Gitea support signed pushes; there are tools such as gittuf or Kernel.org Transparency Log Monitor that provide transparency logs for push operations.

The signed push certificate sent by the client is stored in the repository as a blob object and is verified using the GPG (GNU Privacy Guard). The pre-receive hook can then examine various GIT_PUSH_CERT_* environment variables (see the git-receive-pack man page for the details) to decide whether to accept or deny a given signed push.

Logging signed pushes for audit can be done with the post-receive hook. You can have this hook send an email notification about the signed push or have it append information about the push to a log file. The push certificate that is signed includes an identifier for the client’s GPG key, the URL of the repository, and the information about the operations performed on the branches or tags, in the same format as the pre-receive and post-receive input.

In Chapter 6, Collaborative Development with Git, we examined four major protocols used by Git to connect with remote repositories – local, HTTP, SSH (Secure Shell), and Git (the native protocol). This was done from the point of view of a client connecting to the repository, discussing what these protocols are and which one to use if the remote repository offers more than one.

This chapter will offer the administrator’s side of view, explaining how to set up and later move rephrased Git repositories to be served with different transport protocols. Here, we will also examine, for each protocol, what authentication and authorization look like.

This is the most basic protocol, where a client uses a path to the repository or the file:// URL to access remotes. You just need to have a shared filesystem, such as an NFS or SMB/CIFS mount, which contains Git repositories to serve. This is a nice option if you already have access to a networked filesystem, as you don’t need to set up any server.

Access to repositories using a file-based transport protocol is controlled by the existing file permissions and network access permissions. You need read permissions to fetch and clone and write permissions to push.

In the latter case, if you want to enable a push, you’d better set up a repository in such a way that pushing does not screw up the permissions. This can be helped by creating a repository with the --shared option to use git init (or git clone). This option allows users belonging to the same group to push into the repository by using the sticky group ID, ensuring that the repositories stay available to all the group members.

The disadvantage of this method is that shared access to a networked filesystem is, generally, more difficult to set up and reach safely from multiple remote locations than basic network access and setting up an appropriate server. Mounting the remote disk over the internet can be difficult and slow.

This protocol does not protect the repository against accidental damage. Every user has full access to the repository’s internal files, and there is nothing preventing them from accidentally corrupting the repository.

SSH is a common transport protocol (commonly used by Linux users) to self-host Git repositories. SSH access to servers is often already set up in many cases as a way to safely log in to the remote machine; if not, it is generally quite easy to set up and use. SSH is an authenticated and encrypted network protocol.

Conversely, you can’t serve anonymous access to Git repositories over SSH. People must have at least limited access to your machine over SSH; this protocol does not allow anonymous read-only access to published repositories.

Generally, there are two ways to give access to Git repositories over SSH. The first is to have a separate account on the server for each client trying to access the repository (although such an account can be limited and does not need full shell access, you can, in this case, use git-shell as a login shell for Git-specific accounts). This can be used both with ordinary SSH access, where you provide the password, and with a public-key login. In a one-account-per-user case, the access control situation is similar to the local protocol – namely, access is controlled with filesystem permissions.

A second method is to create a single shell account, which is often the git user, specifically to access Git repositories and use public-key login to authenticate users. Each user who will have access to the repositories would then need to send their SSH public key to the administrator, who would then add this key to the list of authorized keys. The actual user is identified by the key they use to connect to the server.

Another alternative is to have the SSH server authenticated from an LDAP server or some other centralized authentication scheme (often to implement single sign-on). As long as the client can get (limited) shell access, any SSH authentication mechanism can be used.

Next is the Git protocol. This is served by a special and really simple TCP daemon, which listens on a dedicated port (by default, port 9418). This is (or was) a common choice for fast, anonymous, and unauthenticated read-only access to Git repositories.

The Git protocol server, git daemon, is relatively easy to set up. Basically, you need to run this command, usually in a daemonized manner. How to run the daemon (the server) depends on the operating system you use. It can be a systemd unit file, an Upstart script, or a sysvinit script. A common solution is to use inetd or xinetd.

You can remap all the repository requests relative to the given path (a project root for the Git repositories) with --base-path=<directory>. There is also support for virtual hosting; see the git-daemon documentation for more details. By default, git daemon will export only the repositories that have the git-daemon-export-ok file inside gitdir, unless the --export-all option is used. Usually, you would also want to turn on --reuseaddr, allowing the server to restart without waiting for the connection to time out.

The downside of the Git protocol is the lack of authentication and the obscure port that it runs on (which may require you to punch a hole in the firewall). The lack of authentication is because, by default, it is used only for read access – that is, for fetching and cloning repositories. Generally, it is paired with either SSH (always authenticated and never anonymous) or HTTPS for pushing.

You can configure it to allow for a push (by starting the receive-pack service with the --enable=<service> command-line option or, on a per-repository basis, by setting the daemon.receivePack configuration to true), but it is generally not recommended. The only information available to hooks to implement access control is the client address, unless you require all the pushes to be signed. You can run external commands in an access hook, but this would not provide much more information about the client.

Tip

One service you might consider enabling is upload-archive, which serves git archive --remote.

This lack of authentication means that not only does the Git server not know who accesses the repositories, but also that the client must trust the network to not spoof the address while accessing the server. This transportation is not encrypted.

Setting up the so-called “smart” HTTP(S) protocol consists basically of enabling a server script that would invoke git receive-pack and git upload-pack on the server. Git provides a CGI script named git-http-backend for this task. This CGI script can detect whether the client understands the smart HTTP protocol; if not, it will fall back on the “dumb” behavior (a backward compatibility feature).

To use this protocol, you need a CGI server – for example, Apache (with this server, you would also need the mod_cgi module or its equivalent, and the mod_env and mod_alias modules). The parameters are passed using environment variables (hence the need for mod_env when using Apache) – GIT_PROJECT_ROOT to specify where repositories are and an optional GIT_HTTP_EXPORT_ALL if you want to have all the repositories exported, not only those with the git-daemon-export-ok file in them.

The authentication is done by the web server. In particular, you can set it up to allow unauthenticated anonymous read-only access, while requiring authentication for a push. Utilizing HTTPS gives encryption and server authentication, like with the SSH protocol. The URL for fetching and pushing is the same when using HTTP(S); you can also configure it so that the web interface to browse Git repositories uses the same URL for fetching.

Note

The documentation of git-http-backend includes a setup for Apache for different situations, including unauthenticated read and authenticated write. The setup presented there is a bit involved because initial ref advertisements use the query string, while the receive-pack service invocation uses path info.

Conversely, requiring authentication with any valid account for reads and writes, and leaving the restriction of writes to the server-side hook, is a simpler and often acceptable solution.

If you try to push to the repository that requires authentication, the server can prompt for credentials. Because the HTTP protocol is stateless and involves more than one connection sometimes, it is useful to utilize credential helpers (see Chapter 13, Customizing and Extending Git) to avoid either having to give the password more than once for a single operation, or having to save the password somewhere on the disk (for example, in the remote URL).

Gitolite for smart HTTPS access control

While Gitolite (https://gitolite.com/) provides an access control layer on top of Git for access over SSH, it can be configured to perform authorization for smart HTTP mode.

If you cannot run Git on the server, you can still use the dumb protocol, which does not require it. The dumb HTTP(S) protocol expects the Git repository to be served like normal static files from the web server. However, to be able to use this kind of protocol, Git requires the extra objects/info/packs and info/refs files to be present on the server and kept up to date with git update-server-info. This command is usually run on a push via one of the earlier mentioned smart protocols (the default post-update hook does that, and so does git-receive-pack if receive.updateServerInfo is set to true).

It is possible to push with the dumb protocol, but this requires a setup that allows you to update files using a specified transport; for the dumb HTTP(S) transport protocol, this means configuring WebDAV.

Authentication, in this case, is done by the web server for static files. Obviously, for this kind of transport, Git’s server-side hooks are not invoked, and thus they cannot be used to further restrict access.

Historical note

Note that, for modern Git, the dumb transport is implemented using the curl family of remote helpers, which may be not installed by default.

This transport works (for fetching) by downloading requested refs (as plain files), examining where to find files containing the referenced commit objects (hence the need for server information files, at least for objects in packfiles), getting them, and then walking through the chain of revisions, examining each object needed, and downloading new files if the object is not present yet in the local repository. This walker method can be horrendously inefficient if the repository is not packed well with respect to the requested revision range. It requires a large number of connections and always downloads the whole pack, even if only one object from it is needed.

With smart protocols, Git on the client side and Git on the server side negotiate between themselves which objects need to be sent (a want/have negotiation). Git then creates a customized packfile, utilizing the knowledge of what objects are already present on the other side, and usually includes only deltas – that is, the difference from what the other side has (a thin packfile). The other side rewrites the received packfile to be self-contained.

Git allows us to create support for new transport protocols by writing remote helper programs. This mechanism can be also used to support foreign repositories. Git interacts with a repository requiring a remote helper by spawning the helper as an independent child process, communicating with this process through its standard input and output with a set of commands. The use of remote transport helpers is described in Chapter 6, Collaborative Development with Git.

You can find third-party remote helpers to add support to the new ways of accessing repositories – for example, there is git-remote-dropbox to use Dropbox to store the remote Git repository. Note, however, that remote helpers are (possibly yet) limited in features compared to built-in transport support.

Nowadays, there is no need to write a Git repository management solution yourself. There is a wide range of various third-party solutions that you can use. It is impossible to list them all, and even giving recommendations is risky. The Git ecosystem is actively developed; which tool is the best could have changed since the time of writing.

I’d like to focus here just on the types of tools for administrators, just as I did for GUIs in Chapter 13, Customizing and Extending Git.

First, there are Git repository management solutions (we have seen one example of such in the form of the update-paranoid script in the contrib/ area). These tools focus on access control, usually the authorization part, making it easy to add repositories and manage their permissions. An example of such a tool is Gitolite.

They often support some mechanism to add your own additional access constraints.

Then, there are web interfaces that allow us to view Git repositories using a web browser. Some make it even possible to create new revisions using a web interface. They differ in capabilities, but they usually offer at least a list of available Git repositories, a summary view for each one, an equivalent of the git log and git show commands, and a view with a list of files in the repository. An example of such tools is the gitweb script in Perl that is distributed with Git; another is cgit, used by git.kernel.org.

Also useful are the code review (code collaboration) tools. These make it possible for developers in a team to review each other’s proposed changes using a web interface. These tools often allow the creation of new projects and the handling of access management. An example of such a tool is Gerrit Code Review.

Finally, there are Git hosting solutions, also called software forges, usually with a web interface for the administrative side of managing repositories, allowing us to add users, create repositories, manage their access, and often work from the web browser on Git repositories. Examples of such tools are GitLab and Gitea. There are also similar source code management systems, which provide (among other web-based interfaces) repository hosting services, together with the features to collaborate and manage development. One example of such a system is Kallithea; however, nowadays, many software forges include some source code management features, such as issue tracking, and CI/CD (Continuous Integration/Continuous Delivery) pipelines.

Of course, you don’t need to self-host your code. There is a plethora of third-party hosted options – GitHub, Bitbucket, and so on. There are even hosted solutions using open source hosting management tools, such as GitLab and Codeberg.

If you want to self-host Git repositories, there are a few things that may help you with server performance and user satisfaction.

If you are hosting many forks (clones) of the same repository, you might want to reduce disk usage by somehow sharing common objects. One solution is to use alternates (for example, with git clone --reference) while creating a fork. In this case, the derived repository would look to its parent object storage if the object is not found on its own.

There are, however, two problems with this approach. First, you need to ensure that the object the borrowing repository relies on does not vanish from the repository set as the alternate object storage (the repository you borrow from). This can be done, for example, by linking the borrowing repository refs in the repository lending the objects, (e.g., in the refs/borrowed/ namespace). Second is that the objects entering the borrowing repository are not automatically de-duplicated; you need to run git repack -a -d -l, which internally passes the --local option to git pack-objects.

An alternate solution would be to keep every fork together in a single repository and use git namespaces to manage separate views into the DAG of revisions, one for each fork. With plain Git, this solution means that the repository is addressed by the URL of the common object storage and the namespace to select a particular fork. Usually, this is managed by a server configuration or a repository management tool; such a mechanism translates the address of the repository into a common repository and the namespace. The git-http-backend manpage includes an example configuration to serve multiple repositories from different namespaces in a single repository. Gitolite also has some support for namespaces in the form of logical and backing repositories and option namespace.pattern, although not every feature works for logical repositories.

Storing multiple repositories as the namespace of a single repository avoids storing duplicated copies of the same objects. It automatically prevents duplication between new objects without the need for ongoing maintenance, as opposed to the alternate solution. Conversely, security is weaker; you need to treat anyone with access to the single namespace, which is within the repository, as if they had access to all the other namespaces (although this might not be a problem for your case).

Speeding up smart protocols with pack bitmaps

Section titled “Speeding up smart protocols with pack bitmaps”

Another issue that you can stumble upon while self-hosting repositories is the performance of smart protocols. For the clients of your server, it is important that operations finish quickly; as an administrator, you would not want to generate a high CPU load on the server due to serving Git repositories.

One feature, ported from JGit, should significantly improve the performance of the counting objects phase, while serving objects from a repository that uses it. This feature is a bitmap-index file, available since Git 2.0.

The bitmap-index file

The major function of the bitmap-index file is providing for a selected subset of commits, including the most recent ones, bit vectors (bitmaps) that store reachability information for a set of objects in a packfile, or in a multi-pack index. In each bit vector, the value of 1 at index i means that the i-th object (in the order defined by a packfile or a multi-pack index file) is reachable from the commit that the given bit vector belongs to.

This file is stored alongside packfiles and their indexes. It can be generated manually by running git repack -A -d --write-bitmap-index, or it can be generated automatically together with the packfile by setting the repack.writeBitmaps configuration variable to true. The disadvantage of this solution is that bitmaps take additional disk space, and the initial repack requires extra time to create bitmap-index. With modern Git, thanks to the multi-pack index, you no longer need to repack everything into a single packfile to be able to use the bitmap file. This feature also makes it faster to update the bitmap.

Nowadays, this feature is turned on by default for bare repositories.

Solving the large non-resumable initial clone problem

Section titled “Solving the large non-resumable initial clone problem”

Repositories with a large code base and a long history can get quite large. The problem is that the initial clone, where you need to get everything in a possibly large repository, is an all-or-nothing operation, at least for modern (safe and effective) smart transfer protocols – SSH, git://, and smart HTTP(S). This might be a problem if a network connection is not very reliable. There is no support for a resumable clone, and it unfortunately looks like it is a fundamentally hard problem to solve for Git developers. This does not mean, however, that you, as a hosting administrator, can do nothing to help users get this initial clone.

One solution is to create, with the git bundle command, a static file that can be used for the initial clone, or as a reference repository for the initial clone (the latter can be done with the git clone --reference=<bundle> --dissociate command after downloading the bundle). This bundle file can be distributed using any transport – in particular, one that can be resumed if interrupted, be it HTTP(S), FTP, rsync, or BitTorrent. The convention that people use, besides explaining how to get such a bundle in the developer documentation, is to use the same URL as that used for the repository but with the .bundle extension (instead of an empty extension or a .git suffix). If the bundle is available via the HTTP(S) or SSH protocols, it can be used without explicitly downloading it first with git clone -- bundle-uri=<bundle uri>.

There is also the bundle-uri capability of Git, where the server suggests where you can download such a bundle from the client, which in turn can use the bundle to speed up the initial clone. At the time of writing, no software forge supports this feature, but there is the git bundle-server (https://github.com/git-ecosystem/git-bundle-server) web server and management interface for use with this feature.

There are also more esoteric approaches to solving the problem of the initial clone cost, such as a step-by-step deepening of a shallow clone (or perhaps just using a shallow clone with git clone --depth is all that’s needed), starting with a partial clone, or using approaches such as GitTorrent.

Handling version control is only a part of the development workflow. There is also work management, code review and audit, running automated tests, and generating builds.

Many of these steps can be aided by specialized tools. Many of them offer Git integration. For example, code review can be managed using Gerrit, requiring that each change passes a review before being made public. Another example is setting up development environments so that pushing changes to the public repository can automatically close tickets in the issue tracker, based on the patterns in the commit messages. This can be done with server-side hooks or with the hosting service’s Webhooks.

A repository can serve as a gateway, running automated tests (for example, with the help of Jenkins’ or Hudson’s continuous integration service) and deploying changes to ensure quality environments only after passing all of these tests. Another repository can be configured to trigger builds for various supported systems. Many tools and services support push-to-deploy mechanisms (for example, Heroku or Google’s App Engine).

Git can automatically notify users and developers about published changes. This can be done via email, a mailing list, an IRC/Discord/Slack channel, or a web-based dashboard application. The possibilities are plentiful; you only need to find them.

Defining development workflows in the repository

Section titled “Defining development workflows in the repository”

Many software forges allow you to automate, customize, and execute software development workflows right from the repository. Those solutions, such as GitHub Actions and GitLab CI/CD, let you run various workflows (for example, to run tests or to deploy an application) when other events happen in your repository at the software forge. Those workflows are run using runners, either virtual machines or containers. They are usually defined by a YAML file checked into your repository.

While the specific dialect of the YAML markup language, the pathname of the file, and the available pre-defined actions differ from service to service, they are similar enough that you should be able to migrate from one solution to the other.

GitOps – using Git for operational procedures

Section titled “GitOps – using Git for operational procedures”

The natural extension of defining software development workflows in the Git repository is to use Git to automatically manage deployment infrastructure, especially for cloud-native applications. This is called GitOps – an operational framework that uses the Git repository to store infrastructure as code (IoC) files and application configuration files. This data can be stored in the same repository as the application code, or in a separate repository.

GitOps ensures that the infrastructure (including the development, testing, and deployment environments) is immediately reproducible, based on the state of the Git repository. This provides version control for operations should a rollback be needed.

Often, the infrastructure configuration is defined declaratively, and a specialized software agent (such as Argo CD, Flux, or Gitkube) running in the cloud pulls from the Git repository at regular intervals and checks the configuration against the live state, adjusting the state as necessary.

This chapter covered various issues related to the administrative side of working with Git. You learned the basics of maintenance, data recovery, and repository troubleshooting. You also learned how to set up Git on a server, how to use server-side hooks, and how to manage remote repositories. The chapter covered tips and tricks for a better remote performance. It described how you can use Git (with the help of third-party tools) to augment development workflows. The information in this chapter should help you to choose a Git repository management solution, or even write your own.

The next chapter will include a set of recommendations and best practices, both specific to Git and those that are version control-agnostic. A policy based on these suggestions can be enforced and encouraged with the help of the tools explored in this chapter.

Answer the following questions to test your knowledge of this chapter:

  1. How do you set up automatic repository maintenance to ensure that Git operations will not slow down?
  2. How you can try to recover a lost commit?
  3. How do you find out why some Git commands started to perform badly and took too much time to execute?
  4. How you can ensure that development follows a given defined policy?
  5. What is the simplest solution to sharing the repository privately, where all developers work on a single computer (on a single machine)?

Here are the answers to the questions given above:

  1. Use the git maintenance command.
  2. First, check the branch and HEAD reflogs if the lost committing question is not readily available from there. If this fails, you can try to browse through unreachable commits with git fsck.
  3. You can use the “ Git trace ” mechanism – for example, with the GIT_TRACE2_PERF or GIT_TRACE_PERFORMANCE environment variables.
  4. Use your software forge features, if possible (for example, to protect a branch against changes or deletion), or use server-side hooks. Enforcing the policy can be helped, but not ensured, with client-side hooks.
  5. Simply create the bare repository with git init --bare --shared, while ensuring that all developers that need access to it have appropriate filesystem permissions. If necessary, push to that repository.

To learn more about the topics that were covered in this chapter, take a look at the following resources: