Advanced Branching Techniques
local graph
Chapter 8 — Advanced Branching Techniques
Section titled “Chapter 8 — Advanced Branching Techniques”Chapter 6, Collaborative Development with Git, described how to arrange teamwork while focusing on repository-level interactions. In that chapter, you learned about various centralized and distributed workflows, as well as their advantages and disadvantages.
This chapter will dive deeper into the details of collaboration in distributed development. We’ll explore the relationships between local branches and branches in remote repositories. Then, we’ll introduce the concept of remote-tracking branches, branch tracking, and upstream. This chapter will also teach us how to specify the synchronization of branches between repositories by using refspecs and push modes.
You will also learn branching techniques: how branches can be used to create new features, prepare new releases, and fix bugs. You will learn about the advantages and disadvantages of different branching patterns. Among other things, this chapter will show you how to use branches so that it would be easy for you to select which features will go into the next version of the project.
In this chapter, we will cover the following topics:
- Different kinds of branches, both long-lived and short-lived, and their purpose
- Various branching patterns, and how they can be composed into workflows
- Release engineering for different branching models
- Using branches to fix a security issue in more than one released version
- Remote-tracking branches and refspecs
- Rules for fetching and pushing branches and tags
- Selecting a push mode to fit the chosen collaboration workflow
The purpose of branching
Section titled “The purpose of branching”A branch in a version control system is an active parallel line of development (also called a codeline). They are used to isolate, separate, and gather different types of work. For example, branches can be used to prevent your current unfinished work on a feature in progress from interfering with the management of bug fixes (isolation), or to gather fixes for an older version of the developed software (gathering and integration).
A single Git repository can have an arbitrarily large number of branches. Moreover, with a distributed version control system, such as Git, there could be many repositories for a single project (known as forks or clones), some public and some private; each such repository will have their own local branches. This can be considered source branching. Each developer would have at least one private clone of the project’s public repository to work in.
A bit of history – a note on the evolution of branch management
Early distributed version control systems used one branch per repository model. Both Bazaar (then Bazaar-NG) and Mercurial documentation, at the time when they began their existence, recommended cloning the repository to create a new branch.
Git, on the other hand, had good support for multiple branches in a single repository almost from the start. However, in the beginning, it was assumed that there would be one central multibranch repository interacting with many single-branch repositories (see, for example, the legacy .git/branches directory, which was used to specify URLs and fetch branches, as described in the gitrepository-layout(7) man page), though with Git it was more about defaults than capabilities.
Because branching is cheap in Git (and merging is easy), and collaboration is quite flexible, people started using branches more and more, even for solitary work. This led to the wide use of the extremely useful topic branch workflow (also known as feature branching).
Isolation versus integration
Section titled “Isolation versus integration”Version control systems such as Git allow different people to work on the same code base without interfering with each other. They also makes it easy to switch between different types of work. But this separated work would then need to be merged back together into some integration target to be useful and to be later included in a release.
We need isolation, but we also need to integrate changes, combining work into a coherent whole. To avoid conflicts as best as possible, our changes need to be visible to others, or even better be integrated. For example, if we change a calling convention of some API, but our work remains isolated, others cannot easily adjust to those changes. They would use the old version of the API in their work – leading to merge conflicts and a more difficult integration in the future. So, from this point of view, earlier and more frequent integration is something to be desired.
However, some features are more involved, and their development consists of many steps. The goal of frequent integration conflicts with the need to isolate unfinished work, and to prevent such work from being visible. If we want frequent integration, we need to be able to handle such issues.
The path to production release
Section titled “The path to production release”The main goal of software development is to deploy code into production, to create a usable release of the project, and to have something to be used. A proper branching technique helps us achieve a stable base for creating such a release.
What branching pattern to use depends on the particularities of the project. For example, the team may need to isolate a work in progress from a stable base. There can also be more or less friction in the release process. Additionally, you might need to manage multiple versions of releases, or multiple versions of the project in production.
There are specific branching patterns to help you handle such issues.
Long-running and short-lived branches
Section titled “Long-running and short-lived branches”Branches whose main purpose is to gather and integrate changes need to be long-lived, or even permanent. They are intended to last indefinitely, or at least for a very long time; they are rarely deleted.
From a collaboration point of view, a long-lived branch can be expected to be there when you are next updating data or publishing changes. This means that you can safely start work by forking off any of the long-lived branches in the remote repository, and be assured that there should be no problems with integrating that work. This means that at least one such branch must exist. Branches that people usually base their work on, that define the current version of the project, are sometimes called mainlines.
While long-lived branches stay forever, short-lived or temporary branches are created to deal with single issues, and are usually removed (deleted) after dealing with said issue (after the branch is merged or the feature is dropped). They are intended to last only as long as the issue is present. Their purpose is time-limited.
Having a separate branch for a separate issue helps us isolate and gather subsequent steps in the process of resolving a problem, whether it’s adding a new feature or creating an urgent bug fix. Those branches are usually named after their topic.
Visibility of branches
Section titled “Visibility of branches”What you can find in public repositories are usually only long-lived branches. In most cases, these branches should never rewind (the new version is always a descendant of the old versions). This makes it possible for you to safely build your work on top of the public branch.
There are some special cases here, though; there can be branches that are rebuilt after each new release (requiring forced fetch at that time), and there can be branches that do not fast forward. Each such case should be explicitly mentioned in the developer documentation to help you avoid unpleasant surprises.
Because of their provisional nature, short-lived branches are usually only present in the local private repository of a developer or integration manager (maintainer), and are not pushed to public distribution repositories. If they appear in public repositories, they are often only present in a public repository of an individual contributor as a target for a pull request (see the blessed repository workflow in Chapter 6, Collaborative Development with Git).
Alternatives to branching
Section titled “Alternatives to branching”With frequent integration, potential conflicts are discovered early. However, some features take longer to develop, and they are simply not ready when the time comes to push them to the mainline. But teams don’t want to expose half-developed features. With a branching workflow geared toward integration rather than isolation, there is often a need for some kind of mechanism to hide unfinished work.
One technique is to build backend code first, and only create the user interface for it when it is ready, like a keystone. On the other hand, changing the existing code can be done by creating a temporary abstraction layer, which would then allow you to switch the underlying implementation to the new one when it is ready.
Another useful method is to hide different unfinished implementations behind feature switches or feature toggles. This technique is useful outside providing separation for integrated but unfinished features. For example, with runtime feature toggles, you can compare two different algorithms on live production data, or you can perform A/B tests.
Visibility without integration
Section titled “Visibility without integration”An alternative to frequent integration into the mainline could be to use outside channels. It can be done by creating a proposed-updates type of branch, which would be used to merge all feature branches. This improves the visibility of changes and provides a place to test branch integrations.
Tools and services such as GitLive (available as a VS Code extension and as a JetBrains IDE plugin) exist that can show who is working on which branch, on which issue, and even show working copy local changes of teammates.
Branching patterns
Section titled “Branching patterns”In many cases, the choice of branching pattern (of the branching technique) depends on how stable the branch is, or in other words how healthy it is. A stable branch, or a healthy branch is a branch in such a state that the current tip commit on that branch always builds and deploys successfully, and the software runs with zero or at most a few bugs.
Ensuring that a branch is healthy pretty much requires doing daily builds and having a comprehensive suite of automated tests that are run frequently – if not at each commit, then at least at each integration (merge). However, explaining how to do this is outside the scope of this book.
Integration patterns
Section titled “Integration patterns”Deciding what branching strategy to use to integrate individual changes into a coherent and healthy mainline depends on various factors. Techniques that tend toward frequent integration, such as continuous integration, require the branch being merged into to be healthy. This requires a disciplined team, where each developer can make sure that each change is well-tested and does not break the developed application.
On the other hand, if it isn’t certain that the feature being developed is of a good enough quality, and we want it assessed as a unit only after it is finished, then integrating less frequently might make more sense. Requiring pre-integration code reviews also drives you toward specific branching patterns.
Mainline integration
Section titled “Mainline integration”The simplest possible branching strategy is to work directly out of the mainline (the trunk) and merge your changes (commits) directly into it. In this workflow, the developer starts from the mainline and creates their work on top of it.
This strategy is called mainline integration or trunk-based development (the name depends on how the main branch is called).
After the developer reaches a point where they want to integrate, they start by fetching the current state of the mainline. If other developers published their changes when they were working on the project, they would need to combine those changes, using either a merge or a rebase operation – see Chapter 9, Merging Changes Together for more detail. Then, they verify that the code is healthy and push integrated changes into the mainline.
Topic branches-based development
Section titled “Topic branches-based development”In the topic branching pattern (also called feature branching), the idea is to make a new separate branch for each topic. This might be creating a new feature or a bug fix. This type of branch intends to gather subsequent development steps of a feature (where each step – a commit – should be a self-contained piece, easy to review), and to isolate the work on one feature from work on other topics. Using a feature branch allows topical changes to be kept together, and not mixed with other commits. It also makes it possible for a whole topic to be dropped (or reverted) as a unit, be reviewed as a unit, and be accepted (integrated) as a unit.
The end goal for the commits on a topic branch is to have them included in a released version of a product. This means that, ultimately, the short-lived topic branch is to be merged into the long-lived branch, which is gathering stable work, and must be deleted.
To make it easier to integrate topic branches, the recommended practice is to create such branches by forking off the oldest, most stable integration branch that you will eventually merge into. Usually, this means creating a branch, starting from the stable-work graduation branch. However, if a given feature does depend on a topic not yet in the stable line, you need to fork off the appropriate topic branch containing the dependency you need.
Note that if it turns out that you forked off the wrong branch, you can always fix it by rebasing (see Chapter 9, Merging Changes Together, and Chapter 10, Keeping History Clean), because topic branches are not public.
Continuous integration
Section titled “Continuous integration”When using the mainline integration pattern, integrations are as frequent as possible: after each commit. Feature branching implies a lower bound to the period of integrations – you integrate fully developed cohesive features.
With the continuous integration pattern (which is also called scaled trunk-based development), you try to integrate as frequently as possible – that is, whenever you have made a worthwhile number of changes and the branch is still healthy. The work is best done with short-lived feature branches, just integrated more frequently. The recommended practice is to integrate at least daily, with the feature branch living a few days at most.
When using this pattern, you need to be able to deal with a partially built feature. If mainline code runs in production (continuous delivery), you need to consider how to avoid exposing such unfinished features in the running code. This was described in the Alternatives to branching section.
Release engineering
Section titled “Release engineering”If the mainline is kept healthy enough and is in an always-releasable state (following the tenets of continuous delivery), you can mark revision for release simply by creating a Git tag from the current tip. This simple branching pattern is called the release-ready mainline.
But if this is not the case, or if you need to manage more than one version of the product, more complex branching patterns are needed. In that case, specialized branches are required on the path from the integration branch to the production release.
Progressive-stability branches
Section titled “Progressive-stability branches”One possible solution to the problem of ongoing development not being stable enough to be always ready for the release (temporarily including some unstable code), is to put less mature and more mature code in separate maturity branches. Thus, the latest possibly unstable version is kept isolated from the one that is always ready for release. The intent of each of these branches is to integrate the development work of the respective degree of stability, from maintenance work (which accepts only relevant bugfixes), through stable work (production-ready), to unstable or development work (planning for the future) – for example, from maint, to master, to next:

Figure 8.1 – A linear view and a “silo” view of the maturity branches (also called progressive-stability branches)
These branches form a hierarchy with a decreasing level of graduation or stability of work, as shown in Figure 8*.1*. In the linear view (top of the figure), the stable revisions are further down the line in your commit history, and the cutting-edge unstable work is further up the history. Alternatively, we can think of branches as work silos (bottom of the figure), where work goes depending on the stability (graduation) of changes. Note that, in real development, progressive-stability branches would not keep being this simple. There would be new revisions on the branches after the forking points. Nevertheless, the overall shape will be the same, even in the presence of merging.
Here and in the following figures, the chosen commit names (C1, C2, C3, and so on) are only to distinguish commits, and in some cases also to make it easy to see which commit corresponds to another.
With maturation branches, the rule is to always merge more stable branches into less stable ones – that is, merge upwards. This would preserve the overall shape of branch silos (see Figure 8*.3* in the Graduation or progressive-stability branches workflow section of this chapter). This is because merging means including all the changes from the merged branch.
Therefore, merging a less stable branch into a more stable one would bring unstable work to the stable branch, violating the purpose and the contract of a stable branch.
Often, we see the graduation branches of the following levels of stability:
- The
maint,maintenance, orfixesbranch only contains bug fixes to the last major release; minor releases are done with the help of this branch. - The
main,master,trunk, orstablebranch, with the development intended for the next major release; the tip of this branch should always be in the production-ready state. - The
nextdevel,development,unstablebranch, where the new development goes to test whether it is ready for the next release; the tip can be used for nightly builds. - The
puorproposedbranch for the proposed updates. This is the integration testing branch and is meant for checking compatibility between different new features.
Having multiple long-running branches is not necessary, but it’s often helpful, especially in very large or complex projects. Often, in operations, each level of stability corresponds to its own platform or deployment environment.
You don’t need to – and probably shouldn’t – use every type of branch listed here. Pick only what is needed for your project.
Per-release branches and per-release maintenance
Section titled “Per-release branches and per-release maintenance”Preparing for the new release of a project can be a lengthy and involved process. Per-release branches can help with this. The release branch is meant to separate the ongoing development from preparing for the new release. It allows other developers to continue working on writing new features and on integration testing, while the quality assurance team, with the help of the release manager, takes time to test and stabilize the release candidate.
After creating a new release, keeping such per-release branches allows us to support and maintain older released versions of the software. At these times, such branches work as a place to gather bug fixes (for their software versions) and create minor releases.
Not all projects need to utilize per-release branches. You can prepare a new release on the stable-work graduation branch, or use a separate repository in place of using a separate branch. Also, not all projects must provide support for more than the latest version.
This type of branch is often named after the release it is intended for – for example, release-v1.4. It is better not to give the branch the same name that the tag has for the release.
Release train with feature-freeze
Section titled “Release train with feature-freeze”If your project is doing releases on a regular cadence (such as every 2 weeks or every 6 months), and the release process is complex and involved (for example, there is external testing or a verification process), then it might be beneficial to use a release train branching pattern. It can be considered a variant of the per-release branch pattern. It is depicted in Figure 8*.2*:

Figure 8.2 – Release train branching pattern for monthly releases, with the May “train” tagged and released into production and the June “train” in a state just after a feature freeze
In this approach, each per-release branch is coupled with a feature-freeze date (in advance of the planned release date). A new branch for the new release is created no later than the feature-freeze date for the previous release. After the feature freeze, an integration branch turns into a release branch, accepting only bug fixes and changes that prepare the project for release. This approach is often used with feature branching.
If there’s more than one per-release branch active and accepting features, the developer can estimate how long would it take to finish the new feature and push it to the “train” corresponding to the later date (loading future trains). Earlier departing “trains” can be regularly merged into later departing ones.
This pattern can be transitioned into the continuous delivery pattern (production-ready mainline) by increasing the frequency of “trains” and reducing friction in the release process.
Hotfix branches for security fixes
Section titled “Hotfix branches for security fixes”Hotfix branches are like release branches but for unplanned releases. Their purpose is to act upon the undesired state of a live production or a widely deployed version, usually to resolve some critical bug in production (usually a severe security bug). This type of branch can be considered a longer-lived equivalent of the bugfix topic branches (see the Bugfix branches section of this chapter).
Other branching patterns involving long-lived branches
Section titled “Other branching patterns involving long-lived branches”The main purpose of the different types branches is to isolate and/or integrate lines of development. However, branching patterns exist that do not fit around the themes of team integration or the path to production (to release).
Per-customer or per-deployment branches
Section titled “Per-customer or per-deployment branches”Let’s say that some of your project’s customers require a few customization tweaks since they do things differently, or perhaps some deployment sites have special requirements. Suppose that these customizations cannot be done by simply changing the configuration. In this case, you would need to create separate lines of development for these customers or customizations.
But you don’t want these lines of development to remain separate. You expect that there will be changes that apply to all of them. One solution is to use one branch for each customization set, per customer, or per deployment. Another would be to use separate repositories. Both solutions help maintain parallel lines of development and transfer changes from one line to another.
Such environment branches can be considered an anti-pattern. With this approach, it is very easy to introduce changes that lead to different behavior in production and on the developer’s workstation, or end with having to maintain wildly divergent products for each customer.
Automation branches
Section titled “Automation branches”Say that you are working on a web application, and you want to automate its deployment using a version control system. One solution would be to set up a daemon to watch a specific branch (for example, the one named deploy) for changes. Updating this branch would automatically update and reload the application.
This is, of course, not the only possible solution. Another possibility would be to use a separate deploy repository and set up hooks there, so pushing would cause the web application to refresh. Alternatively, you could configure a hook in a public repository so that pushing to a specific branch triggers redeployment (this mechanism will be described in Chapter 14, Git Administration).
These techniques can also be used for continuous integration; instead of deploying the application, pushing it into a specific branch would cause the test suite to run (the trigger could create a new commit on this branch or merge it).
Mob branches for anonymous push access
Section titled “Mob branches for anonymous push access”Having a branch in a remote repository (on a server) with special treatment on push is a technique that has many uses, including helping to collaborate. It can be used to enable controlled anonymous push access for a project.
Let’s assume that you want to allow random contributors to push into the central repository. However, you would want to do this in a managed way: one solution is to create a special mob branch or a mob/* namespace (set of branches) with relaxed access control.
You’ll learn how to set this up in Chapter 14, Git Administration.
The orphan branch trick
Section titled “The orphan branch trick”The different types of branches described up to this point differed in their purpose and management. However, from a technical point of view (that is, from the point of view of the graph of commits), they all look the same. This is not the case with the so-called orphan branches.
An orphan branch is a parallel disconnected (orphaned) line of development that shares no revisions with the main history of a project. It is a reference to a disjoint subgraph in the DAG of revisions, without any intersection with the main DAG graph. In most cases, their checkout is also composed of different files.
Such branches are sometimes used as a trick to store tangentially related contents in a single repository, instead of using separate repositories. (When using separate repositories to store related content, you might want to use some naming convention to denote this fact – for example, a common prefix.) They can be used to do the following:
- Store the project’s web page files. For example, GitHub uses a branch named
gh-pagesfor the project’s pages. - Store generated files when the process of creating them requires some nonstandard toolchain. For example, the project documentation can be stored in the
html,man, andpdforphan branches (thehtmlbranch can be also used to deploy the documentation). This way, the user can get specific format of the documentation without needing to install the toolchain required to generate it. - Store the project TODO notes (for example, in the
todobranch), perhaps together with storing there some specialized maintainer tools (scripts). - Have deployment configuration for GitOps in the same repository as the source code, instead of having two separate repositories – one for code and one for deployment configuration.
You can create such a branch with git checkout --orphan <new branch> or by pushing into (or fetching into) a specific branch from a separate repository, as follows:
$ git fetch repo-htmldocs master:htmlThis command fetches the master branch from the unrelated repo-htmldocs repository into the unconnected html “orphan” branch.
Trivia
Creating an orphan branch with git checkout --orphan does not technically create a branch – that is, it does not make a new branch reference. What it does is point the symbolic HEAD reference to an unborn branch. The reference is created after the first commit on a new orphan branch. That’s why there is no option to create an orphan branch with the git branch command.
Other types of short-lived branches
Section titled “Other types of short-lived branches”While long-lived branches stay forever, short-lived or temporary branches are created to deal with single issues, and are usually removed after dealing with said issue. They are intended to last only as long as the issue is present.
Because of their provisional nature, they are usually only present in the local private repository of a developer or integration manager (maintainer), and are not pushed to public distribution repositories. If they appear in public repositories, they are there only in a public repository of an individual contributor (see the blessed repository workflow in Chapter 6, Collaborative Development with Git), as a target for a pull request.
Bugfix branches
Section titled “Bugfix branches”We can distinguish a special case of a topic branch whose purpose is fixing a bug. Such a branch should be created starting from the oldest integration branch it applies to (the most stable branch that contains the bug). This usually means forking off the maintenance branch or the divergence point of all the integration branches rather than the tip of the stable branch. A bugfix branch’s goal is to be merged into relevant long-lived integration branches.
Bugfix branches can be thought of as a short-lived equivalent of a long-lived hotfix branch. Using them is a better alternative to simply committing fixes on the maintenance branch (or another appropriate integration branch).
Detached HEAD – the anonymous branch
Section titled “Detached HEAD – the anonymous branch”You can think of the detached HEAD state (described in Chapter 2, Developing with Git) as the ultimate in temporary branches – so temporary that it even doesn’t have a name. Git uses such anonymous branches automatically in a few situations, such as during bisection and rebasing.
Because, in Git, there is only one anonymous branch and it must always be the current branch, it is usually better to create a true temporary branch with a temporary name; you can always change the name of the branch later.
One possible use of the detached HEAD is for proof-of-concept work. However, you need to remember to set the name of the branch if the changes turn out to be worthwhile (or if you need to switch branches). It is easy to go from an anonymous branch to a named branch. You simply need to create a new branch from the current detached HEAD state.
Branching workflows and release engineering
Section titled “Branching workflows and release engineering”Now that we know about the different branching patterns and their purposes, let’s examine how they can be composed into different branching workflows. Different situations call for different uses of branches, as well as different policies. For example, smaller projects are better suited for simpler branching workflows, while larger projects might need more advanced ones.
In this section, we’ll describe how to use a few common workflows. Each workflow is distinguished by the various types of branches it uses. In addition to getting to know what the ongoing development looks like for a given workflow, we’ll also examine what it recommends doing at the time of the new release (major and minor, where relevant).
The release and trunk branches workflow
Section titled “The release and trunk branches workflow”One of the simplest workflows is to use just a single integration branch. Such branches are sometimes called trunk branches; in Git, it would usually be the main or master branch (it is the default branch when creating a repository). In a pure version of this workflow, you would commit everything to the said branch, at least during the normal development stage. This way of working comes from the times of centralized version control, when branching and especially merging were more expensive, and people avoided branch-heavy workflows.
This workflow is well-suited for continuous integration. If you can maintain a healthy trunk, new releases can be cut directly from it via tagging.
On the other hand, if the release process is more involved, this workflow can be used together with per-release branches. In this case, when we decide to cut the new release, we create the new release branch out of the trunk. This is done to avoid the interference between stabilizing for release and the ongoing development work. The rule is that all the stabilization work goes on the release branch, while all the ongoing development goes to the trunk. Release candidates are cut (tagged) from the release branch, as is the final version of a major release. The release branch for a given version can be later used to gather bug fixes and to cut minor releases from it.
The disadvantage of such a simple workflow is that it requires maintaining a healthy branch. Otherwise, if we get in an unstable state during development, it can be hard to come up with a good starting point for a new release. An alternative solution is to create revert commits on the release branch, undoing the work that isn’t ready. However, this can be a lot of work, and it would make the history of a project hard to follow.
Another difficulty with this workflow is that a feature that looks good at first glance might cause problems later. This is something this workflow has trouble dealing with. If it turns out during development that some feature created with multiple commits feature is not a good idea, reverting it can be difficult. This is true especially if its commits are spread across the timeline (across the history).
Despite these problems, this simple workflow can be a good fit for a small or well-disciplined team.
The graduation branches workflow
Section titled “The graduation branches workflow”To be able to provide a stable line of the product, and to be able to test it in practice as a kind of floating beta version, you need to separate work that is stable from the work that is ongoing and might destabilize code. That’s what graduation branches are for – to integrate revisions with different degrees of maturation and stability (this type of long-running branch is also called an integration branch or progressive-stability branch). See Figure 8*.1* in the Maturity or progressive-stability branches section, which shows a graph view and a silo view of a simple case with progressive-stability branches and linear history. Let’s call the technique that utilizes mainly (or only) this type of branch the graduation branches workflow.
Besides keeping stable and unstable development separate, there is also a need for ongoing maintenance. If there is only one version of the product to support, and the process of creating a new release is simple enough, you can also use the graduation-type branch for this.
Here, simple enough means that you can just create the next major release out of the stable branch.
In such a situation, you would have at least three integration branches. There would be one branch for the ongoing maintenance work (containing only bug fixes to the last version), to create minor releases, another branch for stable work to create major releases (this branch can also be used for nightly stable builds), and another branch for ongoing development, possibly unstable:

Figure 8.3 – The graduation or progressive-stability branches workflow. You should never merge a less stable branch into a more stable one as it would bring all the unstable history
You can use this workflow as-is, with only graduation branches, and no other types of branches:
- You commit bug fixes on the maintenance branch and merge it into the stable branch and development branch, if necessary
- You create revisions with the well-tested work on the stable branch, merging it into the development branch when needed (for example, if the new work depends on them)
- You put the work in progress, which might be unstable, on the development branch
During normal development, you should never merge less stable branches into more stable ones as this decreases their stability. This simple version of this workflow is shown in Figure 8*.3*.
This, of course, requires that you know upfront whether the feature that you are working on should be considered stable or unstable. There is also an underlying assumption that different features work well together from the start. In practice, however, you would expect that each piece of the development matures from the proof of concept, through being a work in progress during possibly several iterations, before it stabilizes. This problem can be solved by using topic branches, as described next.
In the pure graduation branches workflow, you would create minor releases (with bug fixes) out of the maintenance branch. Major releases (with new features) are created out of the stable-work branch. After a major release, the stable-work branch is merged into the maintenance branch to begin supporting the new release that was just created. At this point, an unstable (development) branch can be merged into a stable one. This is the only time when merging upstream – that is, merging fewer stable branches into more stable branches – should be done.
The topic branches workflow
Section titled “The topic branches workflow”The idea behind the topic branches workflow is to create a separate short-lived branch for each topic or feature so that all the commits belonging to a given topic (all the steps in its development) are kept together. The purpose of each topic branch is to develop a new feature or create a bug fix:

Figure 8.4 – The topic branches workflow with one integration branch (master) and three topic or feature branches. One of the topic branches is merged into the integration branch and deleted
In the topic branches workflow (also called the feature branches workflow), you have at least two different types of branches. First, there needs to be at least one permanent (or just long-lived) integration branch. This type of branch is used purely for merging. Integration branches are public.
Second, there are separate short-lived temporary feature branches, each intended for the development of a topic or the creation of a bug fix. They are used to carry all the steps, and only the steps required in the development of a feature or a fix – this is a unit of work for a developer. These branches can be deleted after the feature or the bug fix is merged. Topic branches are usually private and are often not present in public repositories.
When a feature is ready for review, its topic branch is often rebased to make integration easier, and optionally to make the history clearer. It is then sent for review as a whole. The topic branch can be used in a pull request or can be sent as a series of patches (for example, using git format-patch and git send-email). It is then often saved as a separate topic branch in a maintainer’s working repository (for example, using git am --3way if it was sent as patches) to help in examining and managing it.
Then, the integration manager (the maintainer in the blessed repository workflow, or simply another developer in the central repository workflow) reviews each topic branch and decides whether it is ready for inclusion in the selected integration branch. If it is, then it will be merged (perhaps with the -- no-ff option).
Graduation branches in a topic branch workflow
Section titled “Graduation branches in a topic branch workflow”The simplest variant of the topic branches workflow uses only one integration branch. Usually, however, you would combine the graduation branches workflow with topic branches.

Figure 8.5 – The topic branches workflow with two graduation branches. Among topic branches, there is one that is stable enough to be merged into both graduation branches
In this often-used variant, the feature branch is started from the tip of a given stable branch (usually) or the last major release, unless the branch requires some other feature. In the latter case, the branch needs to be forked from (created from) the topic branch it depends on, such as the feat branch in Figure 8*.5*. Bugfix topic branches are created on top of the maintenance branch.
When the topic is considered done, it is merged into the development-work integration branch (for example, next) to be tested. For example, in Figure 8*.5*, topic branches idea and iss92 are both merged into next, while feat is not considered ready yet. Adventurous users can use builds from a given unstable branch to exercise the feature, though must take into account the possibility of crashes and data loss.
After this examination, when the feature is considered to be ready to be included in the next release, it is merged into the stable-work integration branch (for example, master). Figure 8*.5* includes one such branch: iss92. At this point, after merging it into the stable integration branch, the topic branch can be deleted.
Using a feature branch allows topical revision to be kept together and not mixed with other commits. The topic branch workflow allows you to easily undo topics as a whole and remove all bad commits together (removing a series of commits as a whole unit), instead of using a series of reverts.
If the feature turns out not to be ready, it is simply not merged into the stable branch, and it remains present only in the development-work branch. However, if we realize that it wasn’t ready too late, after the topic was merged into the stable branch, we would need to revert the merge. This is a slightly more advanced operation than reverting a single commit, but it is less troublesome than reverting commits one by one, while ensuring that all the commits get correctly reverted. Problems with reverting merges will be covered in Chapter 10, Keeping History Clean.
The workflow for topic branches containing bug fixes is similar. The only difference is that you need to consider which of the integration branches the bugfix branch is to be merged into. This, of course, depends on the situation. Perhaps the bugfix applies only to the maintenance branch, because it was accidentally fixed by a new feature in the stable-work and development-work branches; then, it is merged only to this branch. Perhaps the bug only applies to the stable-work and development-work branches because it is about the feature that was not present in the previous version, thus the maintenance branch is excluded from being merged into.
Using a separate topic branch for bug fixing, instead of committing a bugfix directly, has an additional advantage: it allows us to easily correct the misstep if it turns out after the fact that the fix applies to more branches than we thought.
For example, if it turns out that the fix needs to also be applied to the maintained version and not only to the current work, with the topic branch you can simply merge the fix into additional branches. This is not the case if we were to commit the fix directly to the stable branch. In the latter situation, you cannot use merging as it would destabilize the maintenance branch. You would need to copy the revision with the fix by cherry-picking it from the branch it was committed to into the maintenance branch (see Chapter 9, Merging Changes Together, for a detailed description of this operation). But it means that duplicated commits are present in the history of the project, and cherry-picked commits can sometimes interact wrongly with the act of merging.
The topic branches workflow also allows us to check whether the features conflict with each other, and then fix them as necessary. You can simply create a throw-away integration branch and merge into it topic branches containing these features, to test the interaction between them. You can even publish such branches meant for integration testing (named proposed-updates or just pu, for example) to allow other developers to examine the works in progress. However, you should state explicitly in the developer documentation that said branch should not be used as a basis to work on, as it is recreated each time from scratch.
Branch management for a release in a topic branch workflow
Section titled “Branch management for a release in a topic branch workflow”Let’s assume that we’re using three graduation (integration) branches: maint for maintenance work on the last release, master for stable work, and next for development.
The first thing that the maintainer (the release manager) needs to do before creating a new release is to verify that master is a superset of maint – that is, all the bugs are also fixed in the version being considered for the next release. You can do this by checking whether the following command gives an empty output (see Chapter 4, Exploring Project History):
$ git log master..maintIf the preceding command shows some unmerged commits, the maintainer needs to decide what to do with them. If these bug fixes don’t break anything, they can simply merge maint into master (as it’s merging the more stable branch into the less stable one).
Now that the maintainer knows that master is a superset of maint, they can create the new release from the remote master branch by tagging it and push the just-created tag to the distribution point (to the public repository) with the following command:
$ git tag -s -m "Foo version 1.4" v1.4 master$ git push origin v1.4 masterThe preceding command assumed that the public repository of the Foo project is the one described by origin and that we use the double-digit version for major releases (following the semantic versioning specification).
Tip
If the maintainer wants to support more than one older version, they would need to copy an old maintenance branch, as the next step would be to prepare it for maintaining the just-released revision: git branch maint-1.3.x maint.
Then, the maintainer updates maint to the new release, advancing the branch (note that step one ensured that maint was a subset of master):
$ git checkout maint$ git merge --ff-only masterIf the second command fails, it means that some commits on the maint branch are not present in master, or to be more exact that master is not a strict descendant of maint.
Because we usually consider features for inclusion in master one by one, there might be some topic branches that are merged into next, but they were abandoned before they were merged into master (or they are not merged because they were not ready). This means that though the next branch contains a superset of topic branches that compose the master branch, master is not necessarily the ancestor of next.
That’s why advancing the next branch after a release can be more complicated than advancing the maint branch. One solution is to rewind and rebuild the next branch:
$ git checkout next$ git reset --hard master$ git merge ai/topic_in_next_only_1...You can find unmerged topics to be merged to rebuild next by running the following command:
$ git branch --no-merged nextAfter creating the release after rebuilding next, other developers would have to force fetch the next branch (see the next section) as it would not fast-forward if it were not already configured to force fetch:
$ git pullFrom git://git.example.com/pub/scm/project 62b553c..c2e8e4b maint -> origin/maint a9583af..c5b9256 master -> origin/master + 990ffec...cc831f2 next -> origin/next (forced update)Notice the forced update for the next branch here.
git-flow – a successful Git branching model
Section titled “git-flow – a successful Git branching model”The more advanced version of the topic branching workflow builds on top of the graduation branch’s one. In some cases, an even more involved branching model might be necessary, utilizing more types of branches: graduation branches, release branches, hotfix branches, and topic branches. One such model is git-flow.
This development model uses two main long-running graduation branches to separate the production-ready stable state from the work involved with integrating the latest delivered ongoing development. Let’s call these branches master (stable work) and develop (gathers changes for the next release). The latter can be used for nightly builds. These two integration branches have an infinite lifetime.
These branches are accompanied by supporting branches – that is, feature branches, release branches, and hotfix branches.
Each new feature is developed on a topic branch. Such branches are forked off the tip of either the devel or master branch, depending on the requirements of the feature in question. When work on a feature is finished, its topic branch is merged with the --no-ff option (so that there is always a merge commit where a feature can be described) into devel for integration testing. When they are ready for the next release, they are merged into the master branch. A topic branch exists only as long as a feature is in development and is deleted when merged (or when abandoned).
The purpose of a release branch is twofold. When created, the goal is to prepare a new production release. This means doing last-minute cleanup, applying minor bug fixes, and preparing metadata for a release (for example, version numbers, release names, and so on). All but the last should be done using topic branches; metadata can be prepared directly on the release branch. This use of the release branch allows us to separate the quality assurance for the upcoming release from the work developing features for the next big release.
Such release branches are forked off when the stable state reflects, or is close to, the desired state planned for the new release. Each such branch is named after a release, usually something such as release-1.4 or release-v1.4.x. You would usually create a few release candidates from this branch (tagging them v1.4-rc1 and so on) before tagging the final state of the new release (for example, v1.4).
The release branch might exist only until the time the project release it was created for is rolled out, or it might be left to gather maintenance work: bug fixes for the given. In the latter situation, it replaces the maint branch of other workflows.
Hotfix branches are like release branches, but for an unplanned release usually connected with fixing serious security bugs. They are usually named hotfix-1.4.1 or something similar. A hotfix branch is created out of an old release tag if the respective release (maintenance) branch does not exist. The purpose of this type of branch is to resolve critical bugs found in a production version. After putting a fix on such branches, the minor release is cut (for each such branch).
Ship/Show/Ask – a modern branching strategy
Section titled “Ship/Show/Ask – a modern branching strategy”This approach tries to provide a balance between the advantages of doing pre-integration code reviews with pull requests and feature branches, and high-frequency integration and release-ready mainline that scaled trunk-based development provides.
In this workflow, you choose one of the three options – Ship, Show, or Ask – every time you make a change. With Ship, you add a change directly into the mainline (like in trunk-based development). This is useful if you want fast integration while being sure that the change is healthy – for example, if you add a feature using an established pattern, fix a simple bug, or update documentation.
With Show, you open a pull request but merge it straight away (if the automated checks pass). This allows for easy post-integration review while not making the feature wait.
Finally, with Ask, you follow the topic branch workflow and wait for the code review before integration.
Fixing a security issue
Section titled “Fixing a security issue”Let’s examine another situation: how we can use branches to fix a bug, such as a security issue. This requires a slightly different technique than in ordinary development.
As explained in the The topic branches workflow section, while it is possible to create a bugfix commit directly on the most stable of the integration branches that is affected by the bug, it is usually better to create a separate bugfix branch.
You start by forking from the oldest (most stable) integration branch the fix needs to be applied to, perhaps even at the branching point of all the branches it would apply to. You put the fix (perhaps consisting of multiple commits) on the branch that you have just created. After testing it, you simply merge the bugfix branch into each of the integration branches that need the fix.
This model can be also used to resolve conflicts (dependencies) between branches at an early stage. Let’s assume that you are working on some new feature (on a topic branch) that is not ready yet. While writing it, you noticed some bugs in the development version and you know how to fix them. You want to work on top of the fixed state, but you realize that other developers would also want the bugfix. Committing the fix on top of the feature branch takes the bugfix hostage. Fixing the bug directly on an integration branch has a risk of forgetting to merge the bugfix into the feature in progress.
The solution is to create a fix on a separate topic branch and merge it into both the topic branch for the feature being developed and into the test integration branch (and possibly the graduation branches).
Tip
You can use similar techniques to create and manage some features that are requested by a subset of customers. You need to simply create a separate topic branch for each such feature and merge it into the individual, per-customer branches.
The matter is a bit more complicated if there is security involved. In the case of a severe security bug, you would want to fix it not only in the current version but also in all the widely used versions.
To do this, you need to create a hotfix branch for various maintenance tracks (forking it from the specified version):
$ git checkout -b hotfix-1.9.x v1.9.4Then, you need to merge the topic branch with the fix in question into the just created hotfix branch, to finally create the bugfix release:
$ git merge CVE-2014-1234$ git tag -s -m "Project 1.9.5" v1.9.5Interacting with branches in remote repositories
Section titled “Interacting with branches in remote repositories”As we’ve seen, having many branches in a single repository is very useful. Easy branching and merging allow for powerful development models that utilize advanced branching techniques, such as topic branches. This means that remote repositories will also contain many branches. Therefore, we have to go beyond just the repository to the repository interaction, as described in Chapter 6, Collaborative Development with Git. We have to consider how to interact with multiple branches in the remote repositories.
We also need to think about how many local branches in our repository relate to the branches in the remote repositories (or, in general, other refs). The other important knowledge is how the tags in the local repository relate to the tags in other repositories.
Understanding the interaction between repositories, the branches in these repositories, and how to merge changes (as described in Chapter 9, Merging Changes Together) is required to truly master collaboration with Git.
Upstream and downstream
Section titled “Upstream and downstream”In software development, upstream refers to a direction toward the original authors or the maintainers of the project. We can say that the repository is upstream from us if it is closer (in the repository-to-repository steps) to the blessed repository – the canonical source of the software. If a change (a patch or a commit) is accepted upstream, it will be included either immediately or in a future release of an application, and all the people downstream will receive it.
Similarly, we can say that a given branch in a remote repository (the maintainer repository) is an upstream branch for a given local branch if changes in that local branch are to be ultimately merged and included in the remote branch.
Configuring what is considered upstream
A quick reminder: the upstream repository and the upstream branch in the said remote repository for a given branch are defined by the branch.<branchname>.remote and branch.<branchname>.merge configuration variables, respectively. The upstream branch can be referred to with the @{upstream} or @{ u} shortcut.
The upstream branch is usually set while creating a branch out of the remote-tracking branch, and it can be modified using either git branch --set-upstream-to or git push --set-upstream.
The upstream branch does not need to be a branch in the remote repository. It can be a local branch, though we usually say that it is a tracked branch rather than saying that it is an upstream one. This feature can be useful when one local branch is based on another local branch, such as when a topic branch is forked from another topic branch (because it contains the feature that is a prerequisite for the latter work).
Remote-tracking branches and refspec
Section titled “Remote-tracking branches and refspec”While collaborating on a project, you will be interacting with many repositories (see Chapter 6, Collaborative Development with Git). Each of these remote repositories you are interacting with will have a notion of the position of the branches. For example, the master branch in the remote repository, origin, doesn’t need to be at the same place as your local master branch in your clone of the repository. In other words, they don’t need to point to the same commit in the graph of revisions.
Remote-tracking branches
Section titled “Remote-tracking branches”To be able to check the integration status to see what changes there are in the origin remote repository that are not yet in yours, or what changes you made in your working repository that you have not published yet, you need to know where the branches in the remote repositories are (well, where they were the last time you contacted these repositories). This is the task of remote-tracking branches – the references that track where the branch was in the remote repository:
![]()
Figure 8.6 – Remote repository and local repository with local branches and remote-tracking branches. The grayed-out text in the fetch command denotes the default implicit parameters.
To track what happens in the remote repository, remote-tracking branches are updated automatically; this means that you cannot create new local commits on top of them (as you would lose these commits during updates). You need to create a local branch for it. This can be done, for example, by running git checkout <branchname>, assuming that the local branch with the given name does not already exist. This command creates a new local branch out of the remote branch’s <branchname> and sets the upstream information for it.
Refspec – remote to local branch mapping specification
Section titled “Refspec – remote to local branch mapping specification”As described in Chapter 4, Exploring Project History, local branches are in the refs/heads/ namespace, while remote-tracking branches for a given remote are in the refs/remotes/<remote name>/ namespace. But that’s just the default. The fetch (and push) lines in the remote.<remote name> configuration describe the mapping between branches (or refs in general) in the remote repository and the remote-tracking branches (or other refs) in the local repository.
This mapping is called refspec; it can be either explicit, mapping branches one by one, or globbing, describing a mapping pattern.
For example, the default mapping for the origin repository is as follows:
[remote "origin"] fetch = +refs/heads/*:refs/remotes/origin/*This says that, for example, the content of the master branch (whose full name is refs/heads/master) in the remote repository, origin, is to be stored in the local clone of a repository in the remote-tracking branch, origin/master (whose full name is refs/remotes/origin/master). The plus (+) sign at the beginning of the pattern tells Git to accept the updates to the remote-tracking branch that are not fast-forwarded – that is, they are not descendants of the previous value.
The mapping can be given using the fetch lines in the configuration for the remote, as shown previously, or can be also passed as arguments to a command (it is often enough to specify just the short name of the reference instead of the full refspec). The configuration is only taken into account if there are no refspecs on the command line.
Fetching and pulling versus pushing
Section titled “Fetching and pulling versus pushing”Sending changes (publishing) to the remote repository can be done with git push, while getting changes from it can be done with git fetch. These commands send changes in the opposite direction. However, note that your local repository has a very important difference – it has you sitting next to you’re keyboard so that you’re available to run other Git commands.
That’s why there is no equivalent in the local-to-remote direction to git pull, which combines getting and integrating changes (see the next section). There is simply nobody there to resolve possible conflicts (problems occurring during doing automated integration).
In particular, there is a difference between how branches and tags are fetched and how they are pushed. This will be explained in detail later.
Pull – fetching and updating the current branch
Section titled “Pull – fetching and updating the current branch”Many times, you want to incorporate changes from a specific branch of a remote repository into the current branch. The pull command downloads changes (running git fetch with the parameters given); then, it automatically integrates the retrieved branch head into the current branch. Depending on the configuration, it either calls git merge or git rebase to do that. You can use the --rebase=false or --rebase option to override the default, something that can be configured globally with the pull.rebase configuration option or branch.<branch name>.rebase per-branch configuration option.
Note that if there is no configuration for the remote (you are doing the pull by URL), Git uses the FETCH_HEAD ref to store tips of the fetched branches.
There is also the git request-pull command to create information about published or pending changes for the pull-based workflows – for example, for a variant of the blessed repository workflow. It creates a plain text equivalent of the GitHub merge requests, one that is particularly suitable to send by email.
Pushing to the current branch in a non-bare remote repository
Section titled “Pushing to the current branch in a non-bare remote repository”Usually, the repositories you push to are created for synchronization and are bare – that is, without a working area. A bare repository doesn’t even have the concept of the current branch (HEAD) – there is no worktree, so there is no checked-out branch.
Sometimes, however, you might want to push to the non-bare repository. This may happen, for example, as a way of synchronizing two repositories, or as a mechanism for deployment (for example, of a web page or a web application). By default, Git on the server will deny the ref update to the currently checked-out branch. This is because it brings HEAD out of sync with the worktree and the staging area, which is very confusing if you don’t expect it. You can, however, enable such a push by setting receive.denyCurrentBranch to warn or ignore (changing it from the default value of refuse). You can even make Git update the working directory (which must be clean – that is, without any uncommitted changes) by setting the said configuration variable to updateInstead.
An alternative and a more flexible solution to using git push for deployment is to configure appropriate hooks on the receiving side – see Chapter 13, Customizing and Extending Git, for information on hooks in general, and Chapter 14, Git Administration, for details on their use on the server.
The default fetch refspec and push modes
Section titled “The default fetch refspec and push modes”We usually fetch from public repositories with all the branches made public. Often, we want to get a full update of all the branches. That’s why git clone sets up the default fetch refspec in the way shown earlier in this chapter. The common exception to the “fetch all” rule is following a pull request. But in this case, we have the repository and the branch (or the signed tag) stated explicitly in the request, and we will run the pull command with the provided parameters: git pull < URL> <branch>.
On the other side, in the private working repository, there are usually many branches that we don’t want to publish or, at least, we don’t want to publish them yet. In most cases, we would want to publish a single branch: the one we were working on and the one we know is ready. However, if you are the integration manager, you would want to publish a carefully selected subset of the branches instead of just one single branch.
This is yet another difference between fetching and pushing. That’s why Git doesn’t set up push refspec by default (you can configure it manually nonetheless), but instead relies on the so-called push modes to decide what should be pushed where. Note that the push.default configuration variable used to configure this applies only while running the git push command without branches to push stated explicitly.
Using git push to sync out of a host that one cannot pull from
When you work on two machines, machineA and machineB, each with its own worktree, a typical way to synchronize between them is to run git pull from each other. However, in certain situations, you may only be able to make the connection in one direction (for example, because of a firewall or intermittent connectivity). Let’s assume that you can fetch and push from machineB, but you cannot fetch from machineA.
You want to perform a push from machineB to machineA in such a way that the result of the operation is practically indistinguishable from doing a fetch while being on machineA. For this, you need to specify, via refspec, that you want to push the local branch into its remote-tracking branch:
machineB$ git push machineA:repo.git \
refs/heads/master:refs/remotes/machineB/master
The first parameter is the URL in the scp -like syntax, while the second parameter is refspec. You can set this in the config file, in case you need to do something like this more often.
Fetching and pushing branches and tags
Section titled “Fetching and pushing branches and tags”The next section will describe which push modes are available, and when to use them (for which collaboration workflows). But first, we need to know how Git behaves concerning tags and branches while interacting with remote repositories.
Because pushing is not the exact opposite of fetching, and because branches and tags have different objectives (branches point to the lines of development, and tags point to name-specific revisions), their behavior is subtly different.
Fetching branches
Section titled “Fetching branches”Fetching branches is quite simple. With the default configuration, the git fetch command downloads changes and updates remote-tracking branches (if possible). The latter is done according to the fetch refspec for the remote.
There are, of course, exceptions to this rule. One such exception is mirroring the repository. In this case, all the refs from the remote repository are stored under the same name in the local repository. Here, git clone --mirror would generate the following configuration for origin:
[remote "origin"] url = https://git.example.com/project fetch = +refs/*:refs/* mirror = trueThe names of refs that are fetched, together with the object names they point at, are written to the .git/FETCH_HEAD file. This information is used, for example, by git pull; this is necessary if we are fetching via URL and not via a remote name. This is done because, when we fetch by the URL, there are simply no remote-tracking branches to store the information about the fetched branch to be integrated.
You can delete remote-tracking branches on a case-by-case basis with git branch -r -d; you can also remove them on a case-by-case basis for which the corresponding branch in the remote repository no longer exists with git remote prune (or with git fetch -- prune in modern Git).
Fetching tags and automatic tag following
Section titled “Fetching tags and automatic tag following”The situation with tags is a bit different. While we would want to make it possible for different developers to work independently on the same branch (for example, an integration branch such as master), in different repositories, we would need for all developers to have one specific tag to always refer to the same specific revision. That’s why the position of branches in remote repositories is stored using a separate per-remote namespace, refs/remotes/<remote name>/*, in remote-tracking branches, but tags are mirrored – each tag is stored with the same name in the refs/tags/* namespace.
Tip
Note that the positions of tags in the remote repository can be configured with the appropriate fetch refspec; Git is that flexible. One example where it might be necessary is fetching a subproject, where we want to store its tags in a separate namespace (more information on this issue in Chapter 11, Managing Subprojects).
This is also why, by default, while downloading changes, Git will also fetch and store all the tags that point to the downloaded objects locally. You can disable this automatic tag following with the --no-tags option. This option can be set on the command line as a parameter, or it can be configured with the remote.<remote name>.tagopt setting.
You can also make Git download all the tags with the --tags option, or by adding the appropriate fetch refspec value for tags:
fetch = +refs/tags/*:refs/tags/*Pushing branches and tags
Section titled “Pushing branches and tags”Pushing is different. Pushing branches is (usually) governed by the selected push mode. You push a local branch (usually just a single current branch) to update a specific branch in the remote repository, from refs/heads/ locally to refs/heads/ in remote. It is usually a branch with the same name, but it might be a differently named branch configured as upstream – details will be provided later. You don’t need to specify the full refspec: using the ref name (for example, the name of a branch) means pushing to the ref with the same name in the remote repository, creating it if it doesn’t exist. Pushing HEAD means pushing the current branch into the branch with the same name (not to HEAD in remote – it usually doesn’t exist).
Usually, you push tags explicitly with git push <remote repository> <tag> (or tag <tag> if there is both a tag and branch with the same name – both mean the +refs/tags/<tag>:refs/tags/<tag> refspec). You can push all the tags with --tags (and with appropriate refspec) and turn on the automatic tag with --follow-tags (it is not turned on by default as it is for fetch).
As a special case of refspec, pushing an “empty” source into some ref in remote deletes it. The --delete option to git push is just a shortcut for using this type of refspec. For example, to delete a ref matching experimental in the remote repository, you can run the following command:
$ git push origin :experimentalNote that the remote server might forbid the deletion of refs with receive.denyDeletes configuration option or with hooks.
Push modes and their use
Section titled “Push modes and their use”The behavior of git push, in the absence of the parameters specifying what to push, and in the absence of the configured push refspec, is specified by the push mode.
Different modes are available, each suitable for different collaborative workflows, which was shown in Chapter 6, Collaborative Development with Git.
The “simple” push mode – the default
Section titled “The “simple” push mode – the default”The default push mode in Git 2.0 and later is the so-called simple mode. It was designed with the idea of minimum surprise: the idea that it is better to prevent publishing a branch than to make some private changes accidentally public.
With this mode, you always push the current local branch into the same named branch in the remote repository. If you push into the same repository you fetch from (the centralized workflow), it requires the upstream to be set for the current branch. The upstream is named the same as the branch.
This means that in the centralized workflow (push into the same repository you fetch from), it works like upstream with the additional safety that the upstream must have the same name as the current (pushed) branch. With a triangular workflow, while pushing to a remote that is different from the remote you normally pull from, it works like current.
This is the safest option; it is well-suited for beginners, which is why it is the default mode. You can turn it on explicitly with git config push.default simple.
The “matching” push mode for maintainers
Section titled “The “matching” push mode for maintainers”Before version 2.0 of Git, the default push mode was matching. This mode is most useful for the maintainer (also known as the integration manager) in a blessed repository workflow. But most Git users are not maintainers; that’s why the default push mode was changed to simple.
The maintainer would get contributions from other developers, be it via pull requests or patches sent in an email, and put them into topic branches. They could also create topic branches for their own contributions. Then, the topic branches considered to be suitable were merged into the appropriate integration branches (for example, maint, master, and next) – merging will be covered in Chapter 9, Merging Changes Together. All this is done in the maintainer’s private repository.
The public blessed repository (one that everyone fetches from, as described in Chapter 6, Collaborative Development with Git) should only contain long-running branches (otherwise, other developers could start basing their work on a branch that suddenly vanishes). Git cannot know by itself which branches are long-lived and which are short-lived.
With the matching mode, Git will push all the local branches that have their equivalent with the same name in the remote repository. This means that only the branches that are already published will be pushed to the remote repository. To make a new branch public, you need to push it explicitly the first time, like so:
$ git push origin maint-1.4Important note
Note that with this mode, unlike with other modes, using the git push command without providing a list of branches to push can publish multiple branches at once, and may not publish the current branch.
To turn on the matching mode globally, you can run the following command:
$ git config push.default matchingIf you want to turn it on for a specific repository, you need to use a special refspec composed of a sole colon. Assuming that the said repository is named origin and that we want a not forced push, it can be done with the following command:
$ git config remote.origin.push :You can, of course, push matching branches by using the following refspec on the command line:
$ git push origin :The “upstream” push mode for the centralized workflow
Section titled “The “upstream” push mode for the centralized workflow”In the centralized workflow, there is a single shared central repository that every developer with commit access pushes to. This shared repository will only have long-lived integration branches, usually only maint and master, and sometimes only master.
You should rather never work directly on master (perhaps except for simple single-commit topics), but rather fork a topic branch for each separate feature out of the remote-tracking branch:
$ git checkout -b feature-foo origin/masterIn the centralized workflow, the integration is distributed: each developer is responsible for merging changes (in their topic branches), and publishing the result to the master branch in the central repository. You would need to update the local master branch, merge the topic branch to it, and push it:
$ git checkout master$ git pull$ git merge feature-foo$ git push origin masterAn alternate solution is to rebase the topic branch on the top of the remote-tracking branch rather than merging it. After rebasing, the topic branch should be an ancestor of master in the remote repository, so we can simply push it into master:
$ git checkout feature-foo$ git pull --rebase$ git push origin feature-foo:masterIn both cases, you are pushing the local branch (master in the merge-based workflow and the feature branch in the rebase-based workflow) into the branch it tracks in the remote repository – in this case, origin’s master.
That is what the upstream push mode was created for:
$ git config push.default upstreamThis mode makes Git push the current branch to the specific branch in the remote repository – the branch whose changes are usually integrated into the current branch. This branch in the remote repository is the upstream branch (and can be referenced as @{upstream}). Turning this mode on makes it possible to simplify the last command in both examples to the following:
$ git pushThe information about the upstream is created either automatically (while forking off the remote-tracking branch), or explicitly with the --track option. It is stored in the configuration file and it can be edited with ordinary configuration tools.
Alternatively, it can be changed later with the following:
$ git branch --set-upstream-to=<branchname>The “current” push mode for the blessed repository workflow
Section titled “The “current” push mode for the blessed repository workflow”In the blessed repository workflow, each developer has a private and public repository. In this model, you fetch from the blessed repository and push it to your public repository.
In this workflow, you start working on a feature by creating a new topic branch for it:
$ git checkout -b fix-tty-bug origin/masterWhen the features are ready, you push it into your public repository, perhaps rebasing it first to make it easier for the maintainer to merge it:
$ git push origin fix-tty-bugHere, it is assumed that you used pushurl to configure the triangular workflow, and the push remote is origin. You would need to replace origin here with the appropriate name of the publishing remote if you are using a separate remote for your public repository (using a separate repository makes it possible to use it not only for publishing but also for synchronization between different machines).
You can configure Git in such a way that when you’re on the fix-tty-bug branch, it is enough to just run git push. To do this, you need to set up Git to use the current push mode, like so:
$ git config push.default currentThis mode will push the current branch to the branch with the same name at the receiving end.
Note that if you’re using a separate remote for the publishing repository, you would need to set up the remote.pushDefault configuration option to be able to use just git push for publishing.
Summary
Section titled “Summary”This chapter has shown how to effectively use branches for development and collaboration. You also got to know a few useful tricks.
First, we learned about the various uses of branches, from integration, through release management and the parallel development of features, to fixing bugs. You learned about different branching patterns and branching workflows. This knowledge should help you branch and customize workflows so that they fit the needs of the project and your team’s preferences.
You also learned how to deal with multiple branches per repository while downloading or publishing changes. Git provides flexibility in how the information on branches and other refs in the remote repository is managed using the so-called refspecs to define a mapping to local refs: remote-tracking branches, local branches, and tags. Usually, fetching is governed by fetch refspec, but pushing is managed by the configured push mode. Various collaborative workflows require branch publishing to be handled differently; this chapter described which push mode to use with which workflow and explains why.
The next chapter, Chapter 9, Merging Changes Together, will explain how to integrate changes from other branches and other developers. You will learn about merging and rebasing, and how to deal with situations where Git can’t do this automatically (how to handle various types of merge conflicts). You will also learn about cherry-picking and reverting commits.
Questions
Section titled “Questions”Answer the following questions to test your knowledge of this chapter:
- What are the advantages of frequent integration?
- What are the advantages of topic branches?
- How can you store a project web page or its GitOps configuration in the same repository as the code, while keeping their histories and files separate?
- How can you synchronize the working directory of the Git repository hosted on other computers?
Answers
Section titled “Answers”Here are the answers to this chapter’s questions:
- More frequent integration leads to easier integration because with smaller differences, there is less chance of conflict, and because conflicts are discovered earlier. It also makes it easier to maintain a production-ready mainline, decreasing the time it takes to put the feature into the production environment.
- Using topic branches makes it easier to review and examine the steps it took to create a feature and remove it if needed. The use of topic branches also plays nicely with the requirement of pre-integration code review.
- You can use the “orphan” branch trick – for example, with
git checkout -- orphan– to have two or more unrelated histories in a single repository. - Log in to the other computer and use
git pull; if this is not possible, you cangit pushinto a non-bare repository (configuring what should happen to checked-out branches).
Further reading
Section titled “Further reading”To learn more about the topics that were covered in this chapter, take a look at the following resources:
- Martin Fowler, Patterns for Managing Source Code Branches (2020): https://martinfowler.com/articles/branching-patterns.html
- Rouan Wilsenach, Ship / Show / Ask: A modern branching strategy (2021): https://martinfowler.com/articles/ship-show-ask.html
- Vincent Driessen, git-flow - A successful Git branching model (2010): https://nvie.com/posts/a-successful-git-branching-model/
- gitworkflows - An overview of recommended workflows with Git: https://git-scm.com/docs/gitworkflows
- Paul Hammant and others, Trunk Based Development: https://trunkbaseddevelopment.com/
- Junio C Hamano: Resolving conflicts/dependencies between topic branches early (2009): https://gitster.livejournal.com/27297.html
- Junio C Hamano, Fun with various workflows 1 and 2 (2013): https://git-blame.blogspot.com/2013/06/fun-with-various-workflows-1.html and https://git-blame.blogspot.com/2013/06/fun-with-various-workflows-2.html