Markdown Editor

Branching Strategy Template (Trunk-Based, SLSA Source)

Branching standard: model selection, naming, MUST/SHOULD rules, ruleset settings, SLSA Source mapping, merging, release branches, hotfixes, exceptions, metrics

软件与工程完整SLSA 1.2 Source track; DORA trunk-based development; Conventional Commits 1.0.0branchingstrategy

使用方法: Use it when you standardise how teams branch, review, merge and release across repositories. Fill the model decision and the protection rules first, then the release and hotfix flow. The main pitfall is writing rules that live only in the document instead of being enforced as platform rulesets.

预览

Branching Strategy: [Repository, product or organisation name]

Standard for how code changes flow through version control: the chosen branching model and why, branch types and naming, numbered policy statements, protection rules for each protected branch, commits, pull requests and merge methods, release branches, tags and hotfixes, handling long-running work, exceptions, compliance measurement and review. Aligned with the SLSA specification v1.2 Source track (protected references, continuous history, technical controls and two-party review), the DORA capability "trunk-based development" (dora.dev), Conventional Commits 1.0.0 and Semantic Versioning 2.0.0. Replace every [bracketed] value and every row marked Example. Worked examples use Corvid Commerce, a fictional SaaS company that runs an online checkout platform.

Document control

FieldValue
Document ID[BRS-001]
Version[0.1]
Status[Draft / In review / Approved / Superseded]
Owner[@engineering-director]
Approvers/reviewers[@platform-lead], [@appsec-lead], [@release-manager], [@staff-engineer]
Last updatedYYYY-MM-DD
Classification[Internal]
Repositories in scope[Example: All repositories in the corvid organisation tagged tier 1 or tier 2]
Chosen model[Example: Trunk-based development with short-lived branches; release branches only for the on-premises connector]
Source platform[Example: Hosted Git service with organisation rulesets]
Target SLSA levels[Example: Build L3, Source L3 for tier 1 (Source L4 for payment services); Build L2, Source L3 for tier 2]
Next reviewYYYY-MM-DD (at least annually)

Approvals

RoleNameDecisionDate
Engineering director[@name][Approve / Approve with conditions / Reject]YYYY-MM-DD
Platform engineering lead[@name][Decision]YYYY-MM-DD
Application security lead[@name][Decision]YYYY-MM-DD
Release manager[@name][Decision]YYYY-MM-DD

Revision history

VersionDateAuthorChange summary
0.1YYYY-MM-DD[@name]First draft
1.0YYYY-MM-DD[@name]Example: Approved; organisation rulesets enforced on all tier 1 repositories
1.1YYYY-MM-DD[@name]Example: Merge queue made mandatory on the checkout monorepo

Contents

1. Purpose and scope

1.1 Purpose

This standard sets one way of integrating, reviewing and releasing code across [Organisation]. It aims to keep the default branch always releasable, to make every change reviewed and traceable, to give release engineering a predictable flow for patches, and to provide the source integrity controls that auditors and customers expect.

1.2 Scope

In scopeOut of scope
Example: Service, library and web application repositories in tier 1 and tier 2Personal sandboxes and archived repositories
Example: Deploy configuration repositories read by the deploy controllerGenerated mirrors of third-party code
Example: Infrastructure-as-code repositoriesData science notebooks without production use
[Item][Item]

1.3 Applicability

All people with write access to in-scope repositories, including contractors and automation accounts, follow this standard. Automation accounts follow the same protection rules as people unless listed in the bypass register (section 10.3).

2. Roles and responsibilities

ActivityEngineering directorPlatform teamAppSecRelease managerRepository maintainersContributors
Own and approve this standardARCCCI
Configure organisation rulesetsIA/RCIII
Monitor rule drift and bypassesIRAIII
Create and retire release branchesICIA/RCI
Approve exceptionsACRCII
Follow branch, commit and pull request rulesIIIIAR

R = responsible, A = accountable, C = consulted, I = informed.

3. Branching model selection

3.1 Candidate models

ModelHow it worksFits whenCosts and risks
Trunk-based developmentEveryone integrates into one trunk at least daily through short-lived branches; releases are cut from trunkContinuous deployment of one live version; strong automated tests; feature flags availableNeeds fast CI and discipline on small changes; unfinished work must be hidden by flags or abstraction
GitHub flowBranch from the default branch, open a pull request, address review, merge, delete the branch; teams usually deploy after mergeSmall teams, web services, open-source projects with one supported versionSame as trunk-based but without explicit limits on branch lifetime; branches can grow long
Trunk with release branchesTrunk-based development plus a release branch per supported minor version for stabilisation and patchesInstalled software, SDKs or APIs with several supported versionsFixes must flow trunk first, then be cherry-picked; branches multiply with support windows
Git flowLong-lived develop and main, plus feature, release and hotfix branchesInfrequent, scheduled releases of versioned software with formal stabilisationLong-lived branches, late integration, frequent merge conflicts; poorly suited to continuous delivery

3.2 Decision criteria

CriterionWeightTrunk-basedGitHub flowTrunk with release branchesGit flow
Supports continuous deployment33321
Supports several maintained versions21133
Integration frequency and conflict risk33231
Simplicity for contributors23321
Fit with source integrity controls23332
Weighted total (Example)32293118

Example: Scores run from 1 (poor) to 3 (good). Trunk-based scores (3 x 3) + (2 x 1) + (3 x 3) + (2 x 3) + (2 x 3) = 9 + 2 + 9 + 6 + 6 = 32. Trunk with release branches scores 6 + 6 + 9 + 4 + 6 = 31. GitHub flow scores 9 + 2 + 6 + 6 + 6 = 29. Git flow scores 3 + 6 + 3 + 2 + 4 = 18.

3.3 Decision

Example: Corvid Commerce adopts trunk-based development with short-lived branches for all SaaS services. The on-premises payment connector, which customers install and for which two minor versions are supported, adds release branches per minor version. Git flow is not used for new repositories. Record the decision in Architecture Decision Record (dev/adr) as [ADR-021].

DORA describes trunk-based development as few active branches, branches that live for hours rather than days, merges into trunk at least daily and no code freeze or integration phase. Use these as the behaviours to measure in section 11.

4. Branch types and naming

TypePatternCreated fromMerges intoMaximum lifetimeProtected
Trunkmainn/an/aPermanentYes
Short-lived work<type>/<ticket>-<slug>, for example feat/CHK-812-split-tendermainmain[2 working days] target, [5] maximumNo
Releaserelease/<major>.<minor>, for example release/4.2main at the release cutNever merged back; fixes are cherry-picked from mainUntil end of support of that minor versionYes
Hotfixhotfix/<ticket>-<slug>main; from release/<major>.<minor> only when the code no longer exists on mainmain, then cherry-picked to each affected release/* branch (BR-POL-010)[1 working day]No
Dependency updatedeps/<tool>-<package>mainmainUntil merged or closed by the botNo
Merge queue temporaryCreated by the platformmainmainMinutesPlatform-managed

Allowed <type> prefixes: feat, fix, docs, refactor, test, chore, perf, ci, build, aligned with the commit types in section 7.1. Use lower-case letters, digits and hyphens only; names are at most [60] characters.

5. Policy statements

The key words MUST, MUST NOT, SHOULD and MAY are used as requirement levels in this section.

IDStatementEnforced by
BR-POL-001The default branch of every in-scope repository MUST be named main and MUST be protected by the organisation ruleset in section 6.Ruleset
BR-POL-002Changes to main and release/* MUST arrive through a pull request; direct pushes MUST be blocked for everyone except the bypass register in 10.3.Ruleset
BR-POL-003Force pushes and deletion of protected branches MUST be blocked.Ruleset
BR-POL-004A pull request into a protected branch MUST have at least one approval from a person other than the author and the last pusher, and MUST have code owner approval where Code Ownership Policy (dev/code-ownership-policy) assigns owners.Ruleset
BR-POL-005Approvals MUST be dismissed when new commits change the reviewed content.Ruleset
BR-POL-006All required status checks MUST pass on the exact commit that will be merged; repositories with more than [20] merges per day MUST use a merge queue.Ruleset, merge queue
BR-POL-007Short-lived branches SHOULD be merged within [2 working days] and MUST NOT live longer than [5 working days] without a recorded exception.Weekly report
BR-POL-008Contributors SHOULD integrate into main at least once per working day when actively developing.DORA-style metric in section 11
BR-POL-009Unfinished user-visible work MUST be hidden behind a feature flag or an abstraction rather than kept on a long-lived branch (section 9).Review
BR-POL-010Fixes for a release branch MUST land on main first and then be cherry-picked, unless the code no longer exists on main, in which case the pull request records why.Review, release checklist
BR-POL-011Release tags MUST follow Versioning and Release Policy (dev/versioning-release-policy), MUST be created by the release pipeline and MUST be protected against update and deletion.Tag ruleset
BR-POL-012Commits on protected branches SHOULD be signed and verified; payment service repositories MUST require signed commits.Ruleset
BR-POL-013Commit messages on main MUST follow Conventional Commits 1.0.0 (section 7.1).Status check
BR-POL-014Branch history on protected branches MUST be retained for the life of the repository; rewriting it requires the safe expunging process in 10.4.Ruleset, procedure
BR-POL-015Merged short-lived branches MUST be deleted automatically.Repository setting
BR-POL-016Repository administrators MUST NOT disable or weaken organisation rulesets at repository level; changes go through this standard.Organisation ruleset precedence, audit log alert

6. Protection rules

6.1 Ruleset per reference

Settingmainrelease/*Tags v*
Require a pull request before mergingYesYesn/a
Required approvalsExample: 1 (2 for payment services)2n/a
Require review from code ownersYesYesn/a
Required reviewers (team and file pattern)Example: AppSec, database and platform teams on the paths set in Code Ownership Policy (dev/code-ownership-policy) section 5.2Samen/a
Dismiss stale approvals when new commits are pushedYesYesn/a
Require approval of the most recent reviewable pushYesYesn/a
Require all review conversations to be resolvedYesYesn/a
Require status checks to passBuild, unit, static analysis, dependency scan, commit lintSame plus release test suiten/a
Require branch up to date or merge queueMerge queueUp to daten/a
Require linear historyYes (squash or rebase only)Yesn/a
Require signed commitsExample: Payment services onlyPayment services onlyn/a
Block force pushesYesYesYes
Restrict deletionsYesYesYes
Restrict creation and updaten/aRelease managers onlyRelease pipeline identity only
Bypass listEmptyEmptyRelease pipeline identity

6.2 Mapping to SLSA Source track

SLSA Source levelMeaning (paraphrased)How this standard meets it
Level 1: Version controlledSource is kept in a modern version control systemAll code in the hosted Git service
Level 2: History and provenanceBranch history is continuous, immutable and retained, and the source platform issues provenance for each new revisionBR-POL-003, BR-POL-014; source provenance attestations issued for every new revision of a protected branch by the platform or a source attestation tool. Do not claim Level 2 or above until this provenance exists
Level 3: Continuous technical controlsThe platform continuously enforces the organisation's technical controls on named protected referencesOrganisation rulesets on main, release/* and tags; BR-POL-016
Level 4: Two-party reviewTwo trusted people review changes to protected branchesAuthor plus at least one independent approver (BR-POL-004, BR-POL-005); two approvers on payment services

Example: The checkout monorepo (tier 1) meets Level 3 today because source provenance is issued and the organisation rulesets have been continuously enforced since revision [abc1234]. Payment service repositories target Level 4: they already require two approvers, and they claim Level 4 once [90 days] of continuous enforcement with an empty bypass list is evidenced. Tier 2 repositories target Level 3. Read the SLSA source requirements page for the normative wording before claiming a level.

7. Commits, pull requests and merging

7.1 Commit messages

Commits that land on main follow Conventional Commits 1.0.0: a type, an optional scope, an optional ! for a breaking change, a colon and a short imperative description. A BREAKING CHANGE: footer explains incompatible changes. With squash merging, the pull request title becomes the commit message, so the title check enforces the format.

feat(checkout)!: require idempotency key on payment capture

BREAKING CHANGE: clients must send the Idempotency-Key header on POST /captures.
Refs: CHK-812

The release pipeline derives the next version from these types according to Versioning and Release Policy (dev/versioning-release-policy): fix gives a patch, feat a minor and a breaking change a major increment under Semantic Versioning 2.0.0. Before 1.0.0, record in Versioning and Release Policy how breaking changes are numbered, because major version zero carries no stability promise.

7.2 Pull request rules

  1. Keep pull requests small: Example: fewer than [400] changed lines excluding generated files and lockfiles. Reviewers may ask for a split above that size.
  2. Fill in the pull request description using the Pull Request template (dev/pull-request): what changed, why, how it was tested, and the linked ticket.
  3. Open draft pull requests early for design feedback; code owners are requested when the pull request is marked ready.
  4. Review within the service levels in Code Ownership Policy (dev/code-ownership-policy).
  5. The author merges after approval and green checks, unless the repository uses an automatic merge queue.

7.3 Merge methods

MethodAllowed on mainAllowed on release/*Reason
Squash and mergeYes (default)YesOne commit per change, readable history, clean revert
Rebase and mergeYes, for stacked commits that each pass checksYesKeeps meaningful commit series
Merge commitNoNoBreaks the linear history required in section 6.1

7.4 Merge flow

The flow shows a change from branch creation to deployment when a merge queue is used.

8. Releases, tags and hotfixes

8.1 SaaS services (trunk only)

Each merge to main produces a build that the pipeline deploys. A release is the deployment of a specific digest; the pipeline tags the commit with the version computed from commit types. Hotfixes are ordinary small pull requests to main that follow the emergency path in section 10.2 when urgent. Rolling back is a revert pull request or a promotion of the previous digest, as defined in CI/CD Pipeline Design (dev/ci-cd-pipeline-design).

8.2 Installed software (trunk with release branches)

The diagram shows a fix that reaches two supported minor versions.

  1. The release manager creates release/<major>.<minor> from main at the agreed cut point and announces it.
  2. Only fixes and release-stabilising changes enter a release branch, each through a pull request that references the original commit on main.
  3. The release pipeline tags v<major>.<minor>.<patch> on the release branch; tags are never moved.
  4. When a minor version reaches end of support, the release branch is locked (read-only) and kept for history.
  5. Every release follows Release Checklist (dev/release-checklist).

8.3 Hotfix worked example

Example: A defect in tax rounding (CHK-901) affects v4.2.4 and v4.3.0 of the on-premises connector. The fix merges to main as fix(tax): round half-even per invoice line. Cherry-pick pull requests to release/4.3 and release/4.2 pass the release test suite, receive two approvals each and are tagged v4.3.1 and v4.2.5 by the release pipeline. The fix reaches all supported versions within [2 working days].

9. Long-running and risky work

TechniqueUse forRule
Feature flagsUser-visible features released graduallyFlags have an owner and an expiry date per Feature Flag Policy (dev/feature-flag-policy)
Branch by abstractionReplacing a component or library inside the code baseIntroduce an interface, move callers in small pull requests, switch, then delete the old path
Dark launchNew backend path exercised without user impactResults compared, not served, until approved
Expand and contractDatabase or API schema changesAdd new structure, migrate, remove the old one in a later release
Spike branchThrow-away experimentsNever merged; prefix spike/; deleted within [10 working days]

When a branch must live longer than the BR-POL-007 maximum (for example a vendor-mandated framework upgrade), the owner records an exception (section 10.1) and rebases on main at least daily.

10. Exceptions and emergency changes

10.1 Exception process

  1. The repository maintainer requests an exception with the rule ID, scope, reason, compensating control and end date.
  2. AppSec reviews the risk; the engineering director approves exceptions longer than [30 days].
  3. The exception is recorded in the register below and reviewed at expiry. Expired exceptions are closed or renewed with a new approval.
IDRepositoryRuleReasonCompensating controlApproved byExpires
BR-EXC-001 (Example)corvid/legacy-billingBR-POL-013Generated commits from a code generator cannot follow the formatPull request title check still applies[@engineering-director]YYYY-MM-DD
BR-EXC-002 (Example)corvid/checkoutBR-POL-007Search module framework major upgrade needs a 3-week branchDaily rebase, nightly CI on the branch[@engineering-director]YYYY-MM-DD
[BR-EXC-NNN][Repository][Rule][Reason][Control][@approver]YYYY-MM-DD

10.2 Emergency changes

During a declared incident the incident commander may authorise a reduced path: one approver where two are normally required (release/* and payment services), and non-security checks marked as not required for that pull request. The platform team applies the change as a time-boxed ruleset adjustment, logged in the bypass register (10.3) and reverted when the incident closes. Code owner review, at least one independent approval, security checks, signing and history rules still apply. The change is reviewed by a code owner within [one working day] after the incident and listed in the postmortem (dev/postmortem).

10.3 Bypass register

IdentityReferenceReasonApproved byReviewed
Release pipeline identity (Example)Tags v*Creates release tags[@platform-lead]Quarterly
[Identity][Reference][Reason][@approver][Cadence]

10.4 Safe expunging

Rewriting history on a protected branch is allowed only to remove leaked secrets, personal data or content under a legal takedown. The platform lead and AppSec approve it, the secret is rotated first, the operation is logged with the before and after commit identifiers, and affected teams are told to re-clone.

11. Compliance measurement

IDMetricFormulaTarget (Example)Source
BR-MET-001Ruleset coverageIn-scope repositories with the organisation ruleset active / in-scope repositories100%Platform API
BR-MET-002Median branch lifetimeMedian of (merge time minus first commit time) for merged pull requestsUnder 1 working dayPlatform API
BR-MET-003Long-lived branch countOpen branches older than the BR-POL-007 maximum without an exception0Weekly report
BR-MET-004Active branches per repositoryBranches with commits in the last 7 days, excluding release branches3 or fewer per repository (DORA indicator); larger monorepos set a justified per-team valuePlatform API
BR-MET-005Bypass eventsMerges or pushes that used a bypass, per month0 outside the bypass registerAudit log
BR-MET-006Cherry-pick lagMedian time from fix merged on main to fix tagged on each supported release branchUnder 2 working daysRelease records

Example: In September the checkout monorepo merged 410 pull requests. The median branch lifetime was 0.6 working days, 7 branches exceeded 5 working days and 1 of them was covered by BR-EXC-002, so BR-MET-003 is 6 and the six owners were contacted. Ruleset coverage was 39 of 41 repositories (95.1%); the two gaps were new repositories created outside the template.

Report these metrics monthly to the platform team and quarterly in Delivery Performance Report (dev/delivery-performance-report). Use them to improve the system, never to rank individuals.

12. Adoption and migration

StepActionOwnerDone when
1Inventory repositories and their current model, protections and branch agesPlatform teamInventory published
2Apply the organisation ruleset in evaluate mode and report violations (evaluate mode needs an enterprise plan on some platforms; otherwise run a read-only compliance report against the API)Platform teamTwo weeks of reports
3For each develop-based repository, merge develop into main, retarget open pull requests to main, then lock developRepository maintainersdevelop read-only
4Introduce feature flags for work that previously lived on long branchesService teamsFlags registered
5Switch the ruleset to enforcePlatform teamBR-MET-001 at 100%
6Delete locked develop branches after [30 days]Repository maintainersBranch removed, tag kept for history

13. Review cycle and related documents

Review this standard at least annually, after any change to the source platform's protection features, after a source integrity incident, and when the SLSA Source track changes. The platform team exports the live ruleset configuration at each review and compares it with section 6.

Related documents:

  • Code Ownership Policy (dev/code-ownership-policy) for code owner assignment and review service levels.
  • Versioning and Release Policy (dev/versioning-release-policy) for version numbers and support windows.
  • CI/CD Pipeline Design (dev/ci-cd-pipeline-design) for required checks and deployment.
  • Feature Flag Policy (dev/feature-flag-policy) for hiding unfinished work.
  • Software Configuration Management Plan (quality/scm-plan) for baselines and configuration control.
  • Contributing guide (dev/contributing) and Governance (dev/governance) for open-source contributors and maintainers.
  • Software Supply Chain Security Assessment (security/supply-chain-security) for the SLSA assessment across tracks.

14. Glossary and references

14.1 Glossary

TermMeaning in this standard
TrunkThe single shared branch (main) into which all changes integrate
Short-lived branchBranch for one small change, merged within days
Release branchBranch kept to stabilise and patch one supported minor version
Cherry-pickApplying a commit from one branch onto another
Merge queuePlatform feature that tests each change on top of the latest queued state before merging
RulesetPlatform configuration that enforces rules on branch or tag patterns
BypassPermission to act on a protected reference without meeting its rules
Linear historyHistory without merge commits on the protected branch
Branch by abstractionReplacing a component through an interface in small steps on trunk
Safe expungingControlled, logged removal of content from protected history

14.2 References

ReferenceVersion or date checkedUse
SLSA specification, Source track requirements, slsa.dev/spec/v1.2v1.2, approved; checked 2026-10-24Source levels 1 to 4 and controls
DORA capabilities, Trunk-based development, dora.devChecked 2026-10-24Branch count, lifetime, daily merge and no code freeze
Conventional Commits, conventionalcommits.org1.0.0Commit message format
Semantic Versioning, semver.org2.0.0Version increments
GitHub Docs, Available rules for rulesets, docs.github.comChecked 2026-10-24Example rule names for a hosted Git service
GitHub Docs, GitHub flow, docs.github.comChecked 2026-10-24GitHub flow steps
V. Driessen, A successful Git branching model, nvie.com (2010, with a 2020 note)Cited for the Git flow model onlyBackground on Git flow
OpenSSF Scorecard, Branch-Protection and Code-Review checksv5.6.0Automated check of protections

Standard and licence note

Based on the SLSA specification v1.2 Source track; SLSA level names and requirement concepts are used with attribution to the SLSA project (slsa.dev), published under the Community Specification License 1.0, and level meanings here are paraphrased. Trunk-based development behaviours follow the DORA capability page on dora.dev (Google LLC, CC BY 4.0). Conventional Commits 1.0.0 (CC BY 3.0) and Semantic Versioning 2.0.0 (CC BY 3.0) are cited by name and rule. Ruleset setting names reflect GitHub documentation; GitHub and GitLab are trademarks of their owners; this template is not affiliated with or endorsed by them, and the rules apply to any Git hosting platform with equivalent controls. Git flow is described from general knowledge and cited, not copied. Corvid Commerce is fictional. This template is original text written for this collection. Check the current official versions of each source before use. Template licence: MIT.

相关模板