Skip to content
ImagineWorld

Publishing Your Changes

node_idnode-book_mastering-git_chapter-07-publishing-your-changes
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num7
chapter_titlePublishing Your Changes
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 6, Collaborative Development with Git (the previous chapter), taught you how to use Git to work together as a team, focusing on repository-to-repository interaction. It described different ways of setting up repositories for collaboration, presenting different collaborative workflows, such as centralized and integration manager workflows. It also showed how Git manages information about remote repositories.

In this chapter, you will find out how you can exchange information between your local repository and remote repositories, and how Git can manage credentials that might be needed to access remote repositories.

This chapter will also teach you how to provide your changes upstream, so that they appear in the official history of the project, in its canonical repository. This can be done by pushing your changes to a central repository, pushing them to your own publishing repository and sending some kind of a pull request to the integration manager, or even exchanging patches.

This chapter will cover the following topics:

  • Transport protocols used by Git and their advantages and disadvantages
  • Managing credentials (passwords, keys) for remote repositories
  • Publishing changes: push and pull requests, and exchanging patches
  • Using bundles for offline transfer and speeding up the initial clone
  • Remote transport helpers and their use

In general, URLs in the configuration of remote repository contain information about the transport protocol, the address of the remote server (where appropriate), and the path to the repository. Sometimes, the server that provides access to the remote repository supports various transport protocols; you need to select which one to use. This section is intended to help with this choice.

If the remote repository is on the same local filesystem, you can use either the path to the repository or the file:// schema to specify the repository URL:

/path/to/repo.git/
file:///path/to/repo.git/

The former implies the --local option to the Git clone, which bypasses the smart Git-aware mechanism and simply makes a copy (or a hard link for immutable files under .git/objects, though you can avoid this with the --no-hardlinks option); the latter is slower but can be used to get a clean copy of a repository (for example, after history rewriting done to remove an accidentally committed password or another secret; which is described in Chapter 10, Keeping History Clean, in the Rewriting history section).

This transport is a nice option for quickly grabbing work from someone else’s working repository, or for sharing work using a shared filesystem with the appropriate permissions.

As a special case, a single dot (.) denotes the current repository. This means that

$ git pull . next

is, assuming that pull.rebase is set to false, roughly equivalent to

$ git merge next

When the repository you want to fetch from is on another machine, you need to access the Git server. Nowadays, Git-aware smart servers are most commonly encountered. The smart downloader negotiates which revisions are necessary, and creates a customized packfile to send to a client. Similarly, during the push, the Git server talks to Git on the user’s machine (to the client) to find which revisions to upload.

Git-aware smart servers use the git upload-pack downloader for fetching and git receive-pack for pushing. You can tell Git where to find them if they are not in PATH (but, for example, are installed in one’s home directory) with the --upload-pack and --receive-pack options for fetching and pushing, or the uploadpack and receivepack configuration variables in the remote.<name> section.

With very few exceptions (such as the repository using submodules accessed by an ancient Git instance that does not understand them), Git transport is backward- and forward-compatible—the client and server negotiate what capabilities they can both use.

The native transport, using git:// URLs, provides read-only anonymous access (though you could, in theory, configure Git to allow pushing by enabling the receive-pack service, either from the command line via the --enable=receive-pack option, or via the daemon.receivePack boolean-valued configuration variable—using this mechanism is not recommended at all, even in a closed local network).

The Git protocol does no authentication, including no server authentication, and should be used with caution on unsecured networks. The git daemon TCP server for this protocol normally listens on port 9418; you need to be able to access this port (through the firewall) to be able to use the native Git protocol.

Trivia

There is no secure version of the git:// protocol. There is no git:// over TLS like there is for the FTP and HTTP protocols—namely, FTPS and HTTPS. On the other hand, one can consider SSH transport, as used by Git, to be the git:// protocol over SSH.

The Secure Shell (SSH) transport protocol provides authenticated read-write access. Git simply runs git upload-pack or git receive-pack on the server, using SSH to execute the remote command. There is no possibility for anonymous, unauthenticated access, though you could, as a workaround, set up a guest account for it (passwordless or with an empty password).

Using public-private key authentication allows access without requiring you to provide a password on every connection. You might, however, need to provide it once to unlock a password-protected private key. You can read more about authentication in the Credentials/password management section in this chapter. Many Git hosting sites and software forges require key authentication for accessing repositories via SSH.

For the SSH protocol, you can use the URL syntax with ssh:// as the protocol part:

ssh://[user@]host.example.com[:port]/path/to/repo.git/

Alternatively, you can use the scp -like syntax:

[user@]host.example.com:path/to/repo.git/

The SSH protocol additionally supports the ~username expansion, just like the native Git transport (~ is the home directory of the user you log in as, and ~user is the home directory of user), in both syntax forms:

ssh://[user@]host.example.com/~[user]/path/to/repo.git/
[user@]host.example.com:~[user]/path/to/repo.git/

SSH uses the first contact authentication for servers (TOFU —short for Trust On First Use)—it remembers the key that the server side previously used, and warns the user if it has changed, asking for confirmation (the server key could have been changed legitimately, for example, due to an SSH server reinstall). You can check the server key fingerprint on the first connection.

Git also supports the smart HTTP(S) protocol, which requires a Git-aware CGI or server module—for example, git-http-backend (itself a CGI module). This protocol uses the following URL syntax:

http[s]://[user@]host.example.com[:port]/path/to/repo.git/

By default, without any other configuration, Git allows anonymous downloads (git fetch, git pull, git clone, and git ls-remote), but requires that the client is authenticated for upload (git push).

Standard HTTP authentication is used if authentication is required to access a repository, which is done by the HTTP server software. Using SSL/TLS with HTTPS ensures that if the password is required (for example, if the server uses basic HTTP authentication), then it is sent encrypted and the server identity is verified (using server CA certificate).

Some transports do not require any Git-aware smart server—they don’t need Git installed on the server (for smart transports, at least git-upload-pack and/or git-receive-pack is needed). Those are the FTP(S) and dumb HTTP(S) protocol transports (nowadays, implemented using the remote-curl helper).

These transports need only the appropriate stock server (an FTP server, or a web server), and up-to-date data from git update-server-info. When fetching from such a server, Git uses the so-called commit walker downloader: going down from fetched branches and tags, Git walks down the commit chain, and downloads objects or packs containing missing revisions and other data (for example, file content at revision).

This transport is inefficient (in terms of bandwidth, but especially in terms of latency), but on the other hand, it can be resumed if interrupted. Nevertheless, there are better solutions than using dumb protocols—namely, involving bundles (see the Offline transport with bundles section in this chapter), when the network connection to the server is unreliable enough that you can’t get the clone operation to finish.

Pushing to a dumb server is possible only via the HTTP and HTTPS protocols. It requires the web server to support WebDAV, and Git has to be built with the expat library linked. The FTP and FTPS protocols are read-only (supporting only clone, fetch, and pull).

As a design feature, Git can automatically upgrade dumb protocol URLs to smart URLs. Conversely, a Git-aware HTTP server can downgrade to the backward-compatible dumb protocol (at least for fetching: smart HTTP servers don’t support WebDAV-based dumb HTTP push operation). This feature allows the use of the same HTTP(S) URL for both dumb and smart access:

http[s]://[user@]host.example.com[:port]/path/to/repo.git/

Sometimes, there is no direct connection between your machine and the server holding the Git repository that you want to fetch from. Or, perhaps there is no server running, and you want to copy changes to another machine anyway. Maybe your network is down. Perhaps you’re working somewhere on-site and don’t have access to the local network for security reasons. Maybe your wireless/Ethernet card just broke.

Enter the git bundle command. This command will package up everything that would normally be transferred over the wire, putting objects and references into a special binary archive file called bundle (like packfile, only with branches and so on). You need to specify which commits are to be packed—something that network protocols do automatically for you for online transport.

Trivia

When you are using one of the smart transports, a want/have negotiation phase takes place, where the client tells the server what it does have in its repository and which advertised references on the server it wants, to find common revisions. This is then used by the server to create a packfile, and to send the client only what’s necessary, minimizing the bandwidth use.

Next, you need to move this bundle (this archive) by some means to your machine. It can be done, for example, by so-called sneakernet, which means saving the bundle to removable storage and physically moving the media. You can then incorporate the bundle contents by using git clone or git fetch with the filename of the bundle in place of the repository URL.

When direct access to the server is not possible, for example, from within a firewalled LAN, sometimes you can connect via a proxy.

For the native Git protocol (git://), you can use the core.gitProxy configuration variable, or the GIT_PROXY_COMMAND environment variable to specify a proxy command—for example, ssh. This can be set on a per-remote basis with special syntax for the core.gitProxy value—namely, <command> for <remote>; for example, "ssh" for kernel.org.

You can use the http.proxy configuration variable or appropriate curl environment variables such as http_proxy to specify the HTTP proxy server to use for the HTTP(S) protocol (http(s)://). This can be set on a per-remote basis with the remote.<remote name>.proxy configuration variable.

You can configure SSH (using its configuration files—for example, ~/.ssh/config) to use tunneling (port forwarding) or a proxy command (for example, the netcat/nc; or netcat mode of SSH—that is, ssh -W – —if your SSH implementation supports this feature). It is a recommended solution for the SSH proxy; if neither tunneling nor using a proxy is possible, you can use the ext:: transport-helper, as shown later in this chapter, in the Transport relay with remote helpers section.

Let’s assume that you want to transfer the history of a project (say, limited to the master branch for simplicity) from machineA (for example, your work computer) to machineB (for example, an onsite computer). There is, however, no direct connection between those two machines.

First, we create a bundle that contains the whole history of the master branch (see Chapter 4, Exploring Project History), and tag this point of history to know what we bundled, which will be needed later:

user@machineA ~$ cd repo
user@machineA repo$ git bundle create ../repo.bundle master
user@machineA repo$ git tag -f lastbundle master

Here, the bundle file was created outside the working directory. This is a matter of choice; storing it outside of the repository means that you don’t have to worry about accidentally adding it to your project history, or having to add a new ignore rule. The *.bundle file extension is OR simply a matter of the naming convention.

Important note

For security reasons, to avoid information disclosure about the parts of history that were deleted but not purged (for example, an accidentally committed file with a password), Git only allows fetching from git show-ref -compatible references: branches, remote-tracking branches, and tags.

The same restrictions apply when creating a bundle. This means, for example, that (for implementation reasons) you cannot run git bundle creates master^1. Though, of course, because you control the server end, as a workaround you can create a new branch for master^, (temporarily) rewind master, or check out the detached HEAD at master^.

Then you transfer the just-created repo.bundle file to machineB (via email, on a USB pen drive, and so on). Because this bundle consists of a self-contained, whole subset of the history, down to the first (parent-less) root commit, you can create a new repository by cloning from it, by simply putting the bundle filename in place of the repository URL:

user@machineB ~$ git clone repo.bundle repo
Cloning into 'repo'...
warning: remote HEAD refers to non-existent ref, unable to checkout.
user@machineB ~$ cd repo
user@machineB repo$ git branch -a
remotes/origin/master

Oops. We didn’t bundle HEAD, so the Git clone didn’t know which branch is current and therefore should be checked out:

user@machineB repo$ git bundle list-heads ../repo.bundle
5d2584867fe4e94ab7d211a206bc0bc3804d37a9 refs/heads/master

Tip

Because a bundle can be treated as a remote repository, we could have simply used the git ls-remote ../repo.bundle command here instead of git bundle list-heads ../repo.bundle.

Therefore, with this bundle being as it is, we need to specify which branch to check out to avoid the problem (this would not be necessary if we had bundled HEAD too):

user@machineB ~$ git clone repo.bundle --branch master repo

Instead of cloning again, we can fix the problem with the failed checkout by selecting the current branch:

user@machineB repo$ git switch master
Already on 'master'
Branch 'master' set up to track remote branch 'master' from 'origin'.

As you can see, here, Git guessed that when trying to switch to a non-existent local branch, master, what we actually wanted was to create a local branch to create new commits to submit to the remote master branch. In other words, create a local branch following (tracking) the remote branch with the same name existing in the origin remote. What Git did is the same as if we ran the following command:

$ git switch --create master --track origin/master

To update the repository on machineB cloned from the bundle, you can fetch or pull after replacing the original bundle stored at /home/user/repo.bundle with the one with incremental updates.

To create a bundle containing changes since the last transfer in our example, go to machineA and run the following command:

user@machineA repo$ git bundle create ../repo.bundle \
lastbundle..master
user@machineA repo$ git tag -f lastbundle master

This will bundle all changes since the lastbundle tag; this tag denotes what was copied with the previous bundle (see Chapter 4, Exploring Project History, the Double-dot notation section, for an explanation of double-dot syntax). After creating a bundle, this will update the tag (using -f or --force to replace it), like was done the first time when creating a bundle, so that the next bundle can also be created incrementally from the now current point.

Then, you need to copy the bundle to machineB, replacing the old one. At this point, one can simply perform the pull operation to update the repository, as shown in the following example:

user@machineB repo$ git pullFrom /home/user/repo.bundle
ba5807e..5d25848 master -> origin/master
Updating ba5807e..5d25848
Fast-forward

Using a bundle to update an existing repository

Section titled “Using a bundle to update an existing repository”

Sometimes, you might have a repository cloned already, only for the network to fail. Or, perhaps you moved outside the local area network (LAN), and now you have no access to the server. The end result is that you have an existing repository, but no direct connection to the upstream (to the repository we cloned from).

Now, if you don’t want to bundle up the whole repository, which is wasteful, like in the Cloning and updating with bundles section, you need to find some way to specify the cut-off point (the base) in such a way that it is surely present in the target repository (which you want to update). You can specify the range of revisions to pack into the bundle using almost any technique from Chapter 4, Exploring Project History. The only limitation is that the history, as was said earlier, must start at a branch or tag (anything that git show-ref accepts). You can, of course, check the range with the git log command.

Commonly used solutions for specifying the range of revisions to pack into a bundle are as follows:

  • Use the tag that is present in both repositories: git bundle create ../ repo.bundle v0.1..master
  • Create a cut-off based on the time of commit creation: git bundle create ../repo.bundle -- since=1.week master
  • Bundle just the last few revisions, limiting the revision range by the number of commits: git bundle create ../repo.bundle - 5 master

Tip

It’s better to pack in too much than too little. You can check whether the repository has the requisite commits to fetch from the bundle with git bundle verify. If you pack in too little, you’ll get the following error:

user@machineB repo$ git pull ../ repo.bundle master

error: Repository lacks these prerequisite commits:

error: ca3cdd6bb3fcd0c162a690d5383bdb8e8144b0d2

Then, after transporting it to machineB, you can use the bundle file just like a regular repository to do a one-off pull (putting the bundle filename in place of the URL or the remote name):

user@machineB repo$ git pull ../repo.bundle master
From ../repo.bundle
* branch master -> FETCH_HEAD
Updating ba5807e..5d25848

If you don’t want to deal with the merge, you can fetch into the remote-tracking branch (the <remote branch>:<remote-tracking branch> notation used here, which is known as refspec, will be explained in Chapter 8, Advanced Branching Techniques):

user@machineB repo$ git fetch ../repo.bundle \
refs/heads/master:refs/remotes/origin/master
From ../repo.bundle
ba5807e..5d25848 master -> origin/master
Updating ba5807e..5d25848

Alternatively, you can use git remote add to create a new shortcut, using the path to the bundle file in place of the repository URL. Then, you can simply deal with bundles as described in the previous section.

Utilizing a bundle to help with the initial clone

Section titled “Utilizing a bundle to help with the initial clone”

Smart transports provide much more effective transport than dumb ones. On the other hand, the concept of a resumable clone using smart transport remains elusive to this day (it is not available in Git version 2.34, though perhaps somebody will implement it in the future). For large projects with a long history and with a large number of files, the initial clone might be quite large (for example, linux-next is more than 2.7 GB) and take a pretty long time. This might be a problem if the network is unreliable.

Tip – workaround

You can work around the issue of an unreliable network by using a shallow clone or a sparse clone (see Chapter 12, Managing Large Repositories) and widening it step by step until you arrive at the full repository. There are some third-party tools that do this automatically.

You can create a bundle from the source repository, for example, with the following command (which needs to run on the server):

$ git –git-dir=/dir/repo.git bundle create -- all HEAD

Some servers may offer such bundles to help with the initial clone. There is a practice where a bundle intended for cloning is available at the same URL as the repository, but with a .bundle suffix instead of .git. For example, https://git.example.com/user/repo.git has its bundle available at https://git.example.com/user/repo.bundle.

You can then download such a bundle, which is an ordinary static file, using any resumable transport: HTTP(S), FTP(S), rsync, or even BitTorrent (with the appropriate client that supports resuming the download).

With modern Git, the user can specify the bundle URI with the --bundle-uri command-line option, or a bundle list can be advertised by a Git server. A list of bundle URIs can also be saved in a config file. Fetching from bundle servers (such as https://github.com/git-ecosystem/git-bundle-server) is then automatic.

When Git doesn’t know how to handle a certain transport protocol (when one tries to use a protocol that doesn’t have built-in support), it attempts to use the appropriate remote helper for a protocol, if one exists. That’s why if there is an error within the protocol part of the repository URL—Git responds with an error message that looks like the following:

$ git clone shh://[email protected]:repo
Cloning into 'repo'…
fatal: Unable to find remote helper for 'shh'
git: 'remote-shh' is not a git command. See 'git --help'.

This error message means that Git tried to find git-remote-shh to handle the shh protocol (actually a typo for ssh), but didn’t find an executable with such a name.

You can explicitly request a specific remote helper with the <transport>::<address> syntax, where <transport> defines the helper (git remote-<transport>), and <address> is a string that the helper uses to find the repository.

Modern Git implements support for the dumb HTTP, HTTPS, FTP, and FTPS protocols with the curl family of remote helpers: git-remote-http, git-remote-https, git-remote-ftp, and git-remote-ftps, respectively.

Git includes two generic remote helpers that can be used to proxy smart transports: the git-remote-fd helper to connect to the remote server via either a bidirectional socket or a pair of pipes, and the git-remote-ext helper to use an external command to connect to the remote server.

In the case of the latter, which uses the "ext::<command> <arguments">" syntax for the repository URL, Git runs the specified command to connect to the server, passing data for the server to the standard input of the command, and receiving a response on its standard output. This data is assumed to be passed to a git:// server, git-upload-pack, git-receive-pack, or git-upload-archive (depending on the situation).

For example, let’s assume that you have your repository on a LAN host where you can log in using SSH. However, for security reasons, this host is not visible on the internet, and you need to go through the gateway host: login.example.com:

user@home ~$ ssh [email protected]
user@login ~$ ssh work
user@work ~$ find . -name .git -type d -print
./repo/.git

The trouble is that—also for security reasons—this gateway host either doesn’t have Git installed (reducing the attack surface) or doesn’t have your repository present (it uses a different filesystem). This means that you cannot use the ordinary SSH protocol—not unless you can set up an SSH tunnel from your home via a gateway to your work computer (with ssh -L). The SSH transport is just git-receive-pack / git-upload-pack accessed remotely via SSH, with the path to the repository as a parameter. This means that you can use the ext:: remote helper:

user@home ~$ git clone \
"ext::ssh -t ssh work %S 'repo'" repo
Cloning into 'repo'...
Checking connectivity... done.

Here, %S will be expanded by Git into the full name of the appropriate service— git-upload-pack for fetching and git-receive-pack for pushing. The -t option is needed if logging to the internal host uses interactive authentication (for example, a password). Note that you need to give the name (repo, here) to the result of cloning; otherwise, Git will use the command (ssh) as the repository name.

Tip

You can also use "ext::ssh [<parameters>...] %S '<repository>'" to use specific options for SSH transport—for example, selecting the keypair to use without needing to edit .ssh/config.

This is not the only possible solution—though there is no built-in support for sending the SSH transport through a proxy like there is for the native git:// protocol (among others, core.gitProxy) and for HTTP (among others, http.proxy), you can do it by configuring the SSH using the ProxyCommand config option, or by creating an SSH tunnel.

On the other hand, you can also use the ext:: remote helper to proxy the git:// protocol—for example, with the help of socat —including using a single proxy for multiple servers. See the git-remote-ext(1) manpage for details and examples.

The remote helper mechanism is very powerful. It can also be used to interact with other version control systems, transparently using their repositories as if they were native Git repositories. Though there is no such built-in helper (unless you count the contrib/ area in the Git sources), you can find the git-remote-hg, gitifyhg, or git-cinnabar helper to access Mercurial repositories, and git-remote-bzr to access Bazaar repositories.

Once installed, those remote helper bridges will allow you to clone, fetch, and push to and from the Mercurial or Bazaar repositories as if they were Git ones, using the <helper>::<URL> syntax. For example, to clone the Mercurial repository, you can simply run the following command:

$ git clone "hg::https://hg.example.com/repo"

There is also the remote.<remote name>.vcs configuration variable, if you don’t like using the <helper>:: prefix in the repository URL. With this method, you can use the same URL for Git as for the original version control system (VCS).

Foreign version control system clients

The alternative approach to using remote helper bridges is to use a specialized client, such as git-svn for Subversion, or git-p4 for Perforce. Those clients interact with the foreign VCS (usually a centralized VCS), manage and update the Git repository based on this interaction, and update the foreign repository based on changes present in the Git repository.

Of course, one needs to remember impedance mismatches between different version control systems, and the limitations of the remote helper mechanism. Some features do not translate at all or do not translate well—for example, octopus merges (with more than two parent commits) in Git, or multiple anonymous branches (heads) in Mercurial.

With remote helpers, there is also no place to fix mistakes, replace references to other revisions with target native syntax, and otherwise clean up artifacts created by repository conversions—as can and should be done with one-time conversion when changing version control systems. (Such a cleanup can be done with, for example, the help of the reposurgeon third-party tool.)

With remote helpers, you can even use things that are not version control repositories in the strict sense; for example, with the Git-Mediawiki project, you can use Git to view and edit a MediaWiki-based wiki (for example, Wikipedia), treating the history of pages as a Git repository:

$ git clone "mediawiki::https://wiki.example.com"

Besides that, there are remote helpers that allow additional transport protocols, or storage options—such as git-remote-s3bundle to store the repository as a bundle file on Amazon S3, or git-remote-codecommit for AWS CodeCommit (if you don’t want to or cannot use HTTPS authentication with static credentials). There is also git-ssb to encode repositories in a peer-to-peer log store via the Secure ScuttleButt protocol.

In most cases, with the exception of the local transport (where filesystem permissions control access), publishing changes to the remote repository requires authentication (the user identifies itself) and authorization (the given user has permission to perform the push operation). Sometimes, fetching the repository also requires authentication and authorization, like with private repositories.

Commonly used credentials for authentication are username and password. You can put the username in the HTTP and SSH repository URLs if you are not concerned about information leakage (in respect of leaking the information about valid usernames), or you can use the credential helper mechanism. You should never put passwords in URLs, even though it is technically possible for HTTP ones—the password can be visible to other people, for example when they are listing processes.

Besides the mechanism inherent in the underlying transport engine, be it SSH_ASKPASS for SSH or the ~/.netrc file for curl-based transport, Git provides its own integrated solutions.

Some of the Git commands that interactively ask for a password (and a username if it is not known)—such as git svn, the HTTP interface, or IMAP authentication—can be told to use an external program. The program is invoked with a suitable prompt (a so-called authentication domain, describing what the password is for), and Git reads the password from the standard output of this program.

Git will try the following places to ask the user for usernames and passwords; see the gitcredentials(7) manpage:

  • The program specified by the GIT_ASKPASS environment variable, if set (Git-specific environment variables always have higher precedence than configuration variables)
  • Otherwise, the core.askpass configuration variable is used, if set
  • Otherwise, the SSH_ASKPASS environment variable is used, if set (it is not Git-specific, that is why it is consulted later in the sequence)
  • Otherwise, the user is prompted on the terminal

This askpass external program is usually selected according to the desktop environment of the user (after installing it, if necessary):

  • (x11-) ssh-askpass provides a plain X-window dialog asking for the username and password
  • There is ssh-askpass-gnome for GNOME and ksshaskpass for KDE
  • mac-ssh-askpass can be used for macOS
  • win-ssh-askpass can be used for MS Windows

Git comes with a cross-platform password dialog in Tcl/Tk— git-gui--askpass —to accompany the git gui graphical interface and the gitk history viewer.

The Git configuration precedence (that we have seen an example of here) will be described in more detail in Chapter 13, Customizing and Extending Git.

For the SSH transport protocol, there are additional authentication mechanisms besides passwords. One of them is public key authentication. This method is very useful to avoid being asked for a password over and over. Also, the repository hosting service may require using it when providing SSH access—possibly because identifying a user based on their public key doesn’t require an individual account (that’s what, for example, gitolite uses— https://gitolite.com).

The idea of public key authentication is that the user creates a public/private key pair by running, for example, ssh-keygen. The public key is then sent to the server, for example, by using ssh-copy-id (which also adds the public key, *.pub, at the end of the ~/.ssh/authorized_keys file on the remote server), or by pasting it into a web form on a hosting service. You can then log in with your private key that is on your local machine, for example, as ~/.ssh/id_rsa. You might need to configure SSH (in ~/.ssh/config on Linux, and a similar configuration file on MS Windows) to use a specific identity file for a given connection (hostname) if it is not the default identity key.

Another convenient way to use public key authentication is with an authentication agent such as ssh-agent (or Pageant from PuTTY on MS Windows). Utilizing an agent also makes it more convenient to work with passphrase-protected private keys—you need to provide the password only once, to the agent, at the time of adding the key (which might require user action, for example, running ssh-add for ssh-agent).

It can be cumbersome to input the same credentials over and over. For SSH, you can use public key authentication, but there is no true equivalent for other transports. Git credential configuration provides two methods to at least reduce the number of questions.

The first is the static configuration of default usernames (if one is not provided in the URL) for a given authentication context —for example, hostname:

[credential "https://git.example.com"]
username = user

It helps if you don’t have secure storage for credentials.

The second is to use external programs from which Git can request both usernames and passwords— credential helpers. These programs usually interface with secure storage (a keychain, keyring, wallet, credentials manager, and so on) provided by the desktop environment or the operating system.

Git, by default, includes at least the cache and store helpers. The cache helper (git-credential-cache) stores credentials in memory for a short period of time; by default, it caches usernames and passwords for 15 minutes. The store helper (git-credential-store) stores unencrypted credentials for an indefinitely long time on disk, in files readable only by the user (similar to ~/.netrc); there is also a third-party netrc helper (git-credential-netrc) for GPG-encrypted netrc/authinfo files.

Selecting a credential helper to use (and its options) can be configured either globally or per authentication context, as in the previous example. Global credentials configuration looks like the following:

[credential]
helper = cache --timeout=300

This will make Git use the cache credential helper, which will then cache credentials for 300 seconds (5 minutes). If the credential helper name is not an absolute path (for example, /usr/local/bin/git-kde-credentials-helper), Git will prepend the git credential- prefix to the helper’s name. You can check what types of credential helpers are available with git help -a | grep credential-. Git for Windows also includes, optionally, git credential-helper-selection.

There exist credential helpers that use secure storage of the desktop environment. When you are using them, you need to provide the password only once, to unlock the storage (some helpers can be found in the contrib/ area in Git sources). There is git-credential-libsecret for GNOME and KDE, git-credential-osxkeychain for the macOS Keychain, and git-credential-manager for Microsoft’s cross-platform Git Credential Manager (GCM).

You can also use git-credential-oauth to avoid having to set up personal access tokens or SSH keys. With this solution, the first time you authenticate, the helper opens a browser window to the host. Subsequent access uses cached credentials. Here, one can use the fact that Git supports multiple credential helpers. GitHub, GitLab, and Bitbucket are among the Git hosting services that support OAuth authentication.

Git will use credential configuration for the most specific authentication context, though if you want to distinguish the HTTP URL by pathname (for example, providing different usernames to different repositories on the same host), you need to set the useHttpPath configuration variable to true. If there are multiple helpers configured for context, each will be tried in turn, until Git acquires both a username and a password.

Historical note

Before the introduction of credential helpers, one could use askpass programs that interface with the desktop environment keychain—for example, kwalletaskpass (for KDE Wallet) or git-password (for the macOS Keychain).

The Collaborative workflows section in Chapter 6, Collaborative Development with Git explained various repository setups. Here, we’ll learn about a few common patterns for contributing to a project. We’ll see what our main options for publishing changes are.

Before starting work on new changes, you should usually sync with the main development, incorporating the official version into your repository. This, and the work of the maintainer, is left to be described in Chapter 9, Merging Changes Together.

In a centralized workflow, publishing your changes consists simply of pushing them to the central server, as shown in Figure 6*.2*. Because you share this central repository with other developers, it can happen that somebody has already pushed to the branch you are trying to update (the non-fast-forward case). In this scenario, you need to pull (fetch and merge, or fetch and rebase) others’ changes, before being able to push yours. This case is shown at the start of the Updating your repository (with merge) section in Chapter 1, Git Basics in Practice.

Another possible system with a similar workflow is when your team submits each set of changes to the code review system—for example, Gerrit. One available option is to push to a special ref, refs/for/<branchname> (which is named after a target branch), in a special repository. Then, the change review server makes each set of changes land automatically on a separate per-set ref (for example, refs/changes/<change-id> for commits belonging to a series with the given change ID).

Important note

In both peer-to-peer (see Figure 6*.3*) and maintainer workflows, or the hierarchical workflow variant (Figure 6*.4* and Figure 6*.5*, respectively), the first step in getting your changes included in the project is to perform the push operation, but pushing to your own “public” repository (visible to the appropriate group) of your fork of the project. Then, you need to ask your co-developers, or the project maintainer, to merge your changes. You can do this, for example, by generating a pull request, as described below.

In all workflows other than the centralized workflow, one needs to send a notification that changes are available in the public repository to co-developers, to the maintainer, or to integration managers. The git request-pull command can help with this step. Given the starting point (the bottom of the revision range of interest), the URL or the name of the remote public repository, and optionally, the commit to end at (if it is not the HEAD), this command will generate a summary of changes:

$ git request-pull origin/master publish
The following changes since commit ba5807e44d75285244e1d2eacb1c10cbc5cf3935:
Merge: strtol() + checks (2014-05-31 20:43:42 +0200)
are available in the Git repository at:
https://git.example.com/random master
for you to fetch changes up to 82006acd359717624fb33a7ae554cba6be717911:
Merge branch 'master' of https://git.company.com/random (2021-05-30 00:58:23 +0200)
-----------------------------------------------------------
Alice Developer (1):
Support optional <count> parameter
src/rand.c | 26 +++++++++++++++++++++-----
1 files changed, 21 insertions(+), 5 deletions(-)

The pull request contains the SHA-1 of the base of the changes (which is the revision just before the first commit, in the series proposed for pull), the title of the base commit, the URL, the branch of the public repository (suitable as git pull parameters), the title of the final commit, the shortlog (the name of the git shortlog output), and diffstat (the name of the git diff --stat output) of the changes. This output can be sent to the maintainer—for example, by email.

Figure 7.1 – “New pull request” action shown in a list of branches on GitHub

A lot of Git hosting software and services include a built-in equivalent of git request-pull (for example, the Create pull request action in GitHub).

Many larger projects (and many open source projects) have established procedures for accepting changes in the form of patches, for example, to lower the barrier to entry for contributing. If you want to send a one-off code proposal to a project but do not plan to be a regular contributor, sending patches might be easier than a full collaboration setup (acquiring permission to commit in the centralized workflow, setting up a personal public repository for forking and similar workflows—on GitHub, that would consist of forking the project). Besides, one can generate patches with any compatible tool, and the project can accept patches no matter what is the version control setup.

Tip

Nowadays, with the proliferation of various free Git hosting services, it might be more difficult to set up an email client for sending properly formatted patch emails—though services such as GitGitGadget (for submitting patches to the Git project mailing list), or the older submitGit service, could help. Git itself also includes commands for sending mail, namely git send-email and git imap-send, both of which need configuration.

Additionally, patches, being a text representation of changes, can be easily understood by computers and humans alike. This makes them universally appealing, and very useful for code review purposes. Many open source projects historically used the public mailing list for that purpose: you can email a patch to this list and the public can review and comment on your changes (with services such as public-inbox and lore+lei, it is possible even without subscribing to the mailing list).

To generate email versions of each commit series, turning them into mbox-formatted patches, you can use the git format-patch command, as follows:

$ git format-patch -M -1
0001-Support-optional-count-parameter.patch

You can use any revision range specifier with this command. The most commonly used is limiting by the number of commits, as in the preceding example, or by using the double-dot revision range syntax—for example, @{u}.. (see Chapter 4, Exploring Project History, the Double-dot notation section). When generating a larger number of patches, it is often useful to select a directory to save generated patches. This can be done with the -o <directory> option. The -M option for git format-patch (passed to git diff) turns on rename detection; this can make patches smaller and easier to review.

The patch files end up looking like this:

From db23d0eb16f553dd17ed476bec731d65cf37cbdc Mon Sep 17 00:00:00 2001
From: Alice Developer <[email protected]>
Date: Sat, 31 May 2014 20:25:40 +0200
Subject: [PATCH] Initialize random number generator
Signed-off-by: Alice Developer
---
random.c | 2 ++
1 files changed, 2 insertions(+), 0 deletions(-)
diff --git a/random.c b/random.c
index cc09a47..5e095ce 100644
--- a/random.c
+++ b/random.c
@@ -1,5 +1,6 @@
#include <stdio.h>
#include <stdlib.h>
+#include <time.h>
int random_int(int max)
@@ -15,6 +16,7 @@ int main(int argc, char *argv[])
int max = atoi(argv[1]);
+ srand(time(NULL));
int result = random_int(max);
printf("%d\n", result);
--
2.42.0

It is actually a complete email in the mbox format. The subject (after stripping the [PATCH] prefix) and everything up to the three-dash line (---) forms the commit message—the description of the change. To email this to a mailing list or a developer, you can use either git send-email or git imap-send, or any email client capable of sending plain text email. The maintainer can then use git am to apply the patch series, creating commits automatically; there’s more about this in Chapter 9, Merging Changes Together, in the Applying a series of commits from patches section.

Email subject convention for patches

The [PATCH] prefix is there to make it easier to distinguish patches from other emails. This prefix can—and often does—include additional information, such as the number in the series (set) of patches, the revision of the series, the information about it being a work in progress (WIP), or the Request For Comments (RFC) status—for example, [``RFC/PATCHv4 3/8].

You can also edit these patch files to add more information for prospective reviewers—for example, information about alternative approaches, the differences between previous revisions of the patch (previous attempts), or a summary and/or references to the discussion on implementing the patch (for example, on a mailing list). You add such text between the --- line and the beginning of the patch, before the summary of changes (diffstat); it will be ignored by git am.

Tip – range diff

If the series of patches is undergoing revision and needs to be redone in a different way, it is recommended practice to provide in the cover letter the git range-diff output, showing the differences between one iteration of the series and the other.

In this chapter, we have learned how to choose a transport protocol (if the remote server offers such a choice), and a few tricks such as using foreign repositories as if they were native Git repositories and offline transport with bundles.

Contact with remote repositories can require providing credentials—usually, the username and password, to be able to, for example, push to the repository. This chapter described how Git can help make this part easier thanks to credential helpers.

Publishing your changes and sending them upstream may involve different mechanisms, depending on the workflow. This chapter described push, pull request, and patch-based techniques.

The two following chapters expand on the topic of collaboration: Chapter 8, Advanced Branching Techniques, explores relations between local branches and branches in a remote repository, and how to set up branches for collaboration, while Chapter 9, Merging Changes Together, talks about the opposite issue—how to join the results of parallel work.

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

  1. How can one clone a large repository when the connection to the host is quite unreliable, but you can log in to the host with the remote repository?
  2. What do you need to get your changes into the canonical repository in the centralized workflow, and what do you need to do in the integration manager workflow?
  3. How can you set up Git so you would need to provide a password only once, and not for each contact with the remote?
  4. Can you use Git to interact with foreign version-control system repositories, to submit commits and download updates?

Here are the answers to the questions given above:

  1. One possible solution is to use git bundle on the remote host, and send the generated file via resumable transport such as HTTPS, rsync, or BitTorrent, or simply transport it via removable media such as a USB stick.
  2. In the centralized workflow, you need to push to said central canonical repository, which might require merging changes from others first; in the integration manager workflow, you need to either push to your public repository and send some kind of pull request (for example, with git request-pull and email) against the canonical repository, or send patches by email to the maintainer.
  3. You can set up a credential helper appropriate for the operating system and desktop environment used; for SSH transport, you can also use ssh-agent or the equivalent.
  4. With appropriate tools, you can either use Git to work as a client for a foreign version control system (for example, git svn) or use a remote transport helper to treat a foreign repository as a Git remote (for example, git-cinnabar).

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