Git Hour 6: Branch Strategy and Repository Architecture in Practice
- Can compareTrunk development + feature switch、GitHub Flow、GitFlow、GitLab Flowwithrelease train, and select one for the team based on release frequency, team size, number of supported versions, and compliance requirements, and explain the reasons and costs.
- Master the complete process of release branches and hot fixes: pull the release branch from tag, repair the advanced trunk, and then
cherry-pick -xMove back (upstream first), handle move-back conflicts, maintain multiple long-term support (LTS) branches, and usegit cherry/git log --cherry-pickFind commits that missed the move back. - From the four dimensions of permissions, CI cost, dependency management, and code ownershipMonorepo / PolyrepoTrade-offs; the right choice when reuse across repositories is requiredsubmoduleorsubtree, and avoid their common pitfalls.
- Make large repositorys "faster":Git LFS(track、
lfs migrate, locking, platform quota),partial clone(--filter=blob:none/tree:0)、Sparse checkout cone mode、scalar, and understand the real mechanics of downloading objects on demand. - use
git maintenance start, commit-graph, multi-pack-index and reftable to maintain long-lived repositories; complete the migration plan from SVN/TFVC to Git, usegit filter-repoSplit repositories and merge repositories with history preserved using irrelevant history merges. - Complete the review checklist onceComprehensive Architecture Review, can identify typical failure modes of branching strategies and repository structures.
1-hour time allocation table
| # | time | module | core content | animation/interaction | Experiment (~/git-lab/p6) |
|---|---|---|---|---|---|
| 0 | before class | Preparation: Multi-Team Sample Project | Generate three repositories and a monorepo version of myapp (backend) + web (frontend) + infra (infrastructure code) | Architecture readiness self-assessment | setup-p6.shOne-click generation |
| 1 | 00–08 | Branch strategy comparison | Backbone development + feature switch, GitHub Flow, GitFlow, GitLab Flow, release train; selection basis | Core Animation:Mainline development vs GitFlow commit and release flow timeline | Use the same set of requirements for trunk development and GitFlow respectively |
| 2 | 08–15 | Release branches, hotfixes and rollbacks | release branch, hotfix,cherry-pick -x, moveback conflicts, LTS branches, missing moveback detection | Backshift matrix: which branches a fix goes into | Repair into main and then back to release/1.0 and release/0.9 |
| 3 | 15–22 | Monorepo and Polyrepo | Permissions, CI costs, dependency management, code ownership, atomic changes | decision scorer | Comparison of commits and CIs for the same change in two structures |
| 4 | 22–29 | Submodules and subtrees | gitlink、update --init --recursive, fixed commit,--remote, common pitfalls; subtree add/pull/split | gitlink pointer movement demonstration | Connect infra in two ways: submodule and subtree |
| 5 | 29–38 | Large repository: LFS, partial clone, sparse checkout | LFS pointer and filter,lfs migrate, lock, quota;blob:none/tree:0;cone mode;scalar | Core Animation:Partial cloning + sparse checkout to download objects on demand | Partial clone + cone mode only takes services/api |
| 6 | 38–45 | Repository maintenance | gc、maintenance start、commit-graph、multi-pack-index、reftable | Maintenance task schedule | Enable background maintenance and compare time consumption |
| 7 | 45–53 | repository migration | SVN (git svn)/TFVC (Azure Repos import/git-tfs),filter-repo --subdirectory-filter, merge repository retention history | Split/merge historical changes demonstration | Detach infra and merge the two repositorys |
| 8 | 53–60 | Comprehensive Architecture Review | Review checklist, failure modes, troubleshooting | Interactive troubleshooting tree | Conduct a review of the sample organization |
| — | After class | cheat sheet · Comprehensive experiment | Design branch strategy and repository structure for multi-team projects, and complete split + LFS migration drill | Final exam (12 questions) | Comprehensive experiment |
Knowledge Coverage Matrix Knowledge Coverage Matrix
| target skill | M1 | M2 | M3 | M4 | M5 | M6 | M7 | M8 | key commands | experiment |
|---|---|---|---|---|---|---|---|---|---|---|
| Choose and justify a branching strategy | ✓ | ✓ | · | · | · | · | ✓ | ✓ | switch -c、merge --no-ff、tag -a | M1, comprehensive experiment |
| Releases, hotfixes and rollbacks | ✓ | ✓ | · | · | · | · | · | ✓ | cherry-pick -x、cherry、log --cherry-pick | M2 |
| Repository structure choices | · | · | ✓ | ✓ | ✓ | · | ✓ | ✓ | CODEOWNERS, path filtering | M3, comprehensive experiment |
| Cross-repository reuse (submodule/subtree) | · | · | ✓ | ✓ | · | · | ✓ | ✓ | submodule update --init --recursive、subtree add/pull/split | M4 |
| Large files and large repositorys | · | · | ✓ | · | ✓ | ✓ | ✓ | ✓ | lfs track/migrate/lock、clone --filter、sparse-checkout、scalar | M5, comprehensive experiment |
| Repository maintenance and performance | · | · | · | · | ✓ | ✓ | · | ✓ | maintenance start、commit-graph、multi-pack-index、refs migrate | M6 |
| Migrate, split and merge repositorys | · | · | ✓ | ✓ | ✓ | · | ✓ | ✓ | svn clone、filter-repo、merge --allow-unrelated-histories | M7, comprehensive experiment |
| Architecture review and troubleshooting | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | count-objects -vH、rev-list --missing | M8 |
What’s excluded from this lesson (and where to learn it)
| Topic | Why not in this lesson | where to study |
|---|---|---|
| Basic mechanism and conflict resolution of merge / rebase / cherry-pick | This lesson has been mastered by default and only explains their usage in the release process. | Lesson 2 |
| Branch protection on the platform, rulesets, CODEOWNERS configuration details, import tools | Belongs to hosting platform capabilities | Lesson 3、Lesson 4 |
| The impact of feature switch pipelines, path-triggered CI, and shallow cloning on version calculations | Part of CI/CD & Automation | Lesson 5 |
| Use filter-repo to clear secrets, reflog recovery, and object damage repair | It belongs to in-depth debugging and historical recovery (this lesson only uses filter-repo for splitting) | Lesson 7 |
| Specific usage of monorepo build tools such as Bazel / Nx / Turborepo | It’s a build system, not Git | Official documentation for each tool |
How to use this courseware
Principles · Diagrams · Animations · Commands · Experiments · Production Examples · Troubleshooting · Tests · Voice · Videos. This course focuses on "Design Decisions". It is recommended to read the comparison table of "Principles" first and then look at "Production Cases".
A test score ≥ 70% or clicking "Mark this module complete" will be counted as progress and saved in this browser (it will be cleared after refreshing when local storage is disabled).
The "Voice" tab uses the built-in Web Speech API (zh-CN) of the browser to read the explanation script; if there is no Chinese voice package, the explanation script can still be read or handed over to the TTS tool.
git maintenance(Introduced in 2.29, starting from 2.30startschedulable); sparse checkoutDeprecated non-cone mode(2.37);scalar merged into Git core installation(2.38, and enable the built-in fsmonitor when available);git init --ref-format=reftable(2.45);git backfillReplenish partially cloned missing blobs in batches (2.49);git maintenanceAdded reflog expired task (2.50);git repack --drop-filteredReclaim oversized blobs in partial clones (2.56).Git 3.0It is planned to change the default of the new repository to SHA-256 and reftable, and the default branch name tomain——These areplan, not yet released (subject to git-scm.com/docs/BreakingChanges). The output in this lab is from an actual run of Git 2.51, and the hashes will be different than yours.Module 0 · Preparation: Multi-Team Sample Project (to be completed before class)
- CompletedLesson 2(merge, rebase, cherry-pick) withLesson 5(Git in CI); familiar with Lesson 1
~/git-lab/myapp(Flask + gunicorn + Redis, including Dockerfile and compose.yaml). - Environment: Ubuntu 24.04 (Azure VM or WSL)/macOS/Windows Git Bash, command is POSIX shell. No cloud account is required: all "remote" are local bare repositorys.
file://The protocol also supports partial cloning. - Extra tools:Git LFS(Git for Windows installation package comes with it; Ubuntu
sudo apt install git-lfs;macOSbrew install git-lfs),git-filter-repo(Single Python script,pipx install git-filter-repo、brew install git-filter-repoor Ubuntu 24.04apt install git-filter-repo)。
Connection with previous lesson
Lesson 5 We have CI build myapp on every push. This lesson raises the perspective from "an assembly line in a repository" to "organization": back-end team maintenancemyapp(Python API), maintained by the front-end teamweb, platform team maintenanceinfra(Terraform vs. Kubernetes Checklist). The three teams have to answer: What branch model should be used? One repository or three? Where to put the front-end design draft (large binary file)? How to fix bugs after releasing 1.0?
Step 1: Check the tools
git --version git lfs version git filter-repo --version command -v scalar || echo "scalar not found (the git package of some distributions does not install it, M5 will explain)"
git version 2.56.0 git-lfs/3.8.1 (GitHub; linux amd64; go 1.25.x) a40bce548d2c /usr/bin/scalar
The version number of filter-repo is a string of commit hashes; the LFS version packaged by each distribution may lag behind the latest version 3.8.1 on GitHub, and 3.x can complete this lesson experiment.
Step 2: Generate a sample org (can be run repeatedly)
The script will be in~/git-lab/p6Generate below: ①remotes/Three bare repositories (myapp, web, infra) in - simulate polyrepo; ②remotes/platform.git——monorepo with the same content (services/api、frontend/web、infra/), with the v1.0.0 tag, arelease/1.0Branch and several "miscommitted" binaries for LFS migration of M5 and split of M7.
#!/usr/bin/env bash
# Lesson 6: Multi-team example project. Repeatable operation (will delete and rebuild ~/git-lab/p6)
set -euo pipefail
P6=~/git-lab/p6
rm -rf "$P6" && mkdir -p "$P6/remotes" "$P6/work"
export GIT_AUTHOR_NAME="Lab Bot" GIT_AUTHOR_EMAIL="lab@example.com"
export GIT_COMMITTER_NAME="Lab Bot" GIT_COMMITTER_EMAIL="lab@example.com"
# ---------- monorepo: platform ----------
W="$P6/work/platform"; git init -q -b main "$W"; cd "$W"
mkdir -p services/api frontend/web/assets infra/terraform infra/k8s .github
cat > services/api/app.py <<'EOF'
from flask import Flask
import redis,os
app = Flask(__name__)
cache = redis.Redis(host=os.getenv("REDIS_HOST", "redis"), port=6379)
@app.get("/")
def index():
return f"Hello from myapp! hits={cache.incr('hits')}\n"
@app.get("/healthz")
def healthz():
return "ok\n"
EOF
printf 'flask==3.1.0\ngunicorn==23.0.0\nredis==5.2.1\n' > services/api/requirements.txt
printf 'FROM python:3.13-slim\nWORKDIR /app\nCOPY . .\nRUN pip install -r requirements.txt\nCMD ["gunicorn","-b","0.0.0.0:8000","app:app"]\n' > services/api/Dockerfile
printf '{ "name": "web", "version": "1.0.0" }\n' > frontend/web/package.json
printf '<h1>myapp web</h1>\n' > frontend/web/index.html
printf 'resource "azurerm_resource_group" "rg" {\n name = "rg-myapp"\n location = "eastus"\n}\n' > infra/terraform/main.tf
printf 'apiVersion: apps/v1\nkind: Deployment\nmetadata:\n name: myapp\n' > infra/k8s/deploy.yaml
printf '/services/api/ @org/backend\n/frontend/ @org/frontend\n/infra/ @org/platform\n' > .github/CODEOWNERS
printf '# platform monorepo\n' > README.md
git add . && git commit -qm "chore: initial monorepo layout"
# Large binary file committed by mistake (M5 is processed with lfs migrate)
head -c 3000000 /dev/urandom > frontend/web/assets/hero.psd
head -c 2000000 /dev/urandom > frontend/web/assets/demo.mp4
git add . && git commit -qm "feat(web): add design assets"
echo '@app.get("/version")' >> services/api/app.py
echo 'def version(): return "1.0.0\n"' >> services/api/app.py
git commit -qam "feat(api): add /version"
git tag -a v1.0.0 -m "release 1.0.0"
git branch release/1.0 v1.0.0
head -c 3000000 /dev/urandom > frontend/web/assets/hero.psd
git commit -qam "feat(web): new hero design"
printf 'variable "env" { default = "dev" }\n' >> infra/terraform/main.tf
git commit -qam "feat(infra): env variable"
git clone -q --bare "$W" "$P6/remotes/platform.git"
# ---------- polyrepo:myapp/web/infra ----------
mk(){ # $1=name $2=source directory
local d="$P6/work/$1"; git init -q -b main "$d"
cp -r "$W/$2/." "$d/"; git -C "$d" add . ; git -C "$d" commit -qm "chore: initial $1"
git -C "$d" tag -a v1.0.0 -m "release 1.0.0"
git clone -q --bare "$d" "$P6/remotes/$1.git"
}
mk myapp services/api; mk web frontend/web; mk infra infra
for r in "$P6"/remotes/*.git; do git -C "$r" config uploadpack.allowFilter true; git -C "$r" config uploadpack.allowAnySHA1InWant true; done
echo "OK: $(ls "$P6/remotes")"
du -sh "$P6/remotes/platform.git"
bash setup-p6.sh git -C ~/git-lab/p6/work/platform log --oneline --graph --all --decorate
OK: infra.git myapp.git platform.git web.git 7.8M /home/azureuser/git-lab/p6/remotes/platform.git * 6e38394 (HEAD -> main) feat(infra): env variable * a3dbce7 feat(web): new hero design * 0d81c15 (tag: v1.0.0, release/1.0) feat(api): add /version * 01437f4 feat(web): add design assets * d35e323 chore: initial monorepo layout
uploadpack.allowFilter?Partial cloning requires that the server is willing to generate packs according to the filter. GitHub, GitLab, and Azure Repos are supported by default; the local bare repository needs to manually open these two configurations, otherwise--filterwill be ignored and printedwarning: filtering not recognized by server, ignoring。Warm-up: Answer from memory (30 seconds)
What is the relationship between the new commit generated by cherry-pick and the original commit?
The content changes (diff) are the same, but the parent is different, so the hashes are different; Git does not record the relationship between the two.-xwill be appended at the end of the commit information(cherry picked from commit …), which is the basis of M2 migration audit in this lesson.
What objects are downloaded by default when cloning?
By default, all reachable commits, trees, blobs (and tags) are downloaded, that is, all files in all versions of the complete history. Part of the clone of M5 is to "download less" here: no blobs (or even trees) first, and then fetch them as needed when checking out.
Architecture Readiness Self-Assessment (10 items)
tick youIt can be done nowproject (results saved in this browser). Come back and check it again after finishing this lesson and completing the comprehensive experiment.
Module 1 · Comparison of branch strategies: trunk development, GitHub Flow, GitFlow
- Name each of the five mainstream strategieslong term branch、integration pointandRelease point。
- Explain why "the longer the branch lives, the more painful the merge" and how to use trunk developmentFeature switchSeparate "deployment" and "release".
- Select the appropriate strategy for a team and explain the costs based on release frequency, team size, number of versions that need to be supported simultaneously, and compliance requirements.
What: Three questions to answer for branching strategies
- Where does the integration happen?——How long does it take for the developer's changes to be merged into which branch before they are put together with other people's code?
- Where does the release come from?——Are the online components built from main, release branch, or environment branch?
- How to fix it?——Where are the production problems fixed, and how to ensure that the fixes will not be "resurrected" in the next version?
Five strategies at a glance
| Strategy | long term branch | How developers work | Release method | suitable for |
|---|---|---|---|---|
| trunk development(Trunk-Based Development) | only main(trunk) | Directly commit small steps to trunk, or use short branches + PR that survive ≤ 1–2 days; unfinished functions are hidden inFeature switchbehind | Continuous deployment from trunk; pull the release branch from a commit of trunk when needed (only receive cherry-pick fixes) | A team with high-frequency releases (multiple times a day), perfect CI, and the ability to switch features; this is also the practice of large-scale organizations such as Google and Meta. |
| GitHub Flow | main | Open feature branch from main → PR → Review + CI → Merge | main is always deployable, after merging (or on a branch before merging) | Web services, SaaS, small to medium-sized teams; essentially "backbone development with PR" |
| GitFlow(Vincent Driessen,2010) | main(Only release version) +develop(Integrated) | Open from developfeature/*, return to develop after completion | pull from developrelease/*Stable → merge into main and tag → merge back into develop;hotfix/*Pull it from main and merge it into main and develop after repairing it. | Software with clear version numbers and the need to maintain multiple released versions simultaneously (desktop software, SDK, embedded, products delivered quarterly) |
| GitLab Flow | main+ environment branch (pre-production、production) or version branch (2-3-stable) | Feature branch merged into main | Main's commits are in orderdownstreamMerge into environment branch to deploy; fix to followupstream first(First main, then cherry-pick to downstream) | Deployment time is not under your control (such as App Store review, customer maintenance window), or requires multiple environments to be promoted step by step |
| release train(Release Train) | main + release branch cut out periodically | Developed with the same trunk: As long as the function is combined and the switch is turned on when "departure", you can get on the bus, otherwise wait for the next bus | Branch, stabilize, and release from main at a fixed rhythm (such as every 2 weeks or every 4 weeks); no delays due to individual functions | Large-scale products, mobile apps, browsers for multi-team collaboration (Chrome uses a fixed 4-week release cycle) |
Why: Why long branches are dangerous
Every extra day the branch lives, the greater the difference between it and main, the more conflicts it has when merging, and the harder it is to review, andIntegration issues are delayed until the end("Merge Hell"). The DORA study lists "trunk development" as one of the capabilities related to high delivery performance: fewer than 3 active branches, branches that live no more than one day before merging, and no "code freeze" period. Trunk development does not mean “no branching”;Make branches very short-lived。
How: Feature switch decouples "deployment" and "release"
import os
def flag(name, default=False): # Usually used in production with LaunchDarkly / Unleash / Azure App Configuration, etc.
return os.getenv(f"FF_{name.upper()}", str(default)).lower() == "true"
@app.get("/")
def index():
if flag("new_greeting"): # The code has been deployed in main, but the function is not visible to the user
return "Hi from the new myapp!\n"
return f"Hello from myapp! hits={cache.incr('hits')}\n"
- deploy(deploy) = put the code into the production environment;publish(release) = Make functionality visible to users. Switches allow unfinished functions to be safely folded into main.
- Switches have a cost: each switch is an additional code path that requires testing for both states, andThere must be a cleanup plan(Delete the switch code after the function is fully released), otherwise it will accumulate into technical debt.
- Great for refactoringBranch by Abstraction: First introduce the abstraction layer, and the old and new implementations coexist in main, and gradually switch, instead of opening a reconstruction branch that survives for three months.
When: selection basis
| Dimensions | Prefer trunk development/GitHub Flow | Prefer GitFlow / GitLab Flow / Release Train |
|---|---|---|
| Release frequency | Daily to multiple times a week, continuous deployment | Monthly, quarterly, or as determined by external review/customer window |
| Also supported versions | There is only one "current online version" | Multiple released versions must be patched (1.x, 2.x LTS) |
| Team size and maturity | CI is fast and reliable, has good test coverage, and can switch features; it is also suitable for large scale (requires strong CI and merge queue) | When CI is weak and testing relies on manual regression, the release branch provides a stabilization window (but CI should be invested at the same time) |
| Compliance/Audit | Satisfied on main with PR review, required checks, signature commit, deployment approval (Lessons 3–5) | When "release content freezing + change approval records" is required, the release branch and tag make the audit boundary clearer |
Figure 1-1 Branch shapes of five strategies
Figure 1-2 Strategy selection decision tree
Core Animation: Same 3 features + 1 hotfix, trunk development vs GitFlow commit and release flow
Processing of upper and lower timelinesexactly the sameWorking on: Features A, B, C and a production hotfix. Play through it step by step and observe three things:How long does it take for the code to be integrated with others?、When can it be released?、Hot repair needs to be integrated into several places. The counter on the right counts the "Number of Mergers" and "Number of Unintegrated Days".
Daily commands corresponding to the two strategies
| action | Trunk Development/GitHub Flow | GitFlow |
|---|---|---|
| start a function | git switch -c feat/login origin/main | git switch -c feature/login origin/develop |
| stay in sync | git pull --rebase origin main(multiple times a day) | git pull --rebase origin develop |
| Complete function | PR → main (squash or rebase merge), delete branch | PR → develop (commonly used--no-ffPreserve functional boundaries) |
| Ready for release | Deploy directly from main; orgit switch -c release/1.4 <commit> | git switch -c release/1.4 develop→ stable → merge into main andtag -a v1.4.0→ develop |
| hot fix | Xiujin main →cherry-pick -xGo to release branch (M2) | git switch -c hotfix/1.4.1 main→ Merge into main + tag → Merge into develop (or current release) |
Use pure Git commands to go through GitFlow release (does not rely on git-flow extension)
git switch -c develop main # One-time: build develop git switch -c feature/login develop # ... Commit ... git switch develop && git merge --no-ff feature/login && git branch -d feature/login git switch -c release/1.1 develop # Freeze functions and only fix bugs git commit -am "chore(release): bump version to 1.1.0" git switch main && git merge --no-ff release/1.1 && git tag -a v1.1.0 -m "release 1.1.0" git switch develop && git merge --no-ff release/1.1 && git branch -d release/1.1 git push origin main develop --follow-tags
Description:Originalgit-flowThe command line extension (nvie/gitflow) has not been maintained for many years, and there are many forked versions; it is enough to understand the above native commands, and use branch protection and PR implementation on the platform.
Trunk development: short branch + feature switch + cut release from trunk
git switch -c feat/new-greeting origin/main
#The code is packaged behind flag("new_greeting") and is closed by default
git commit -am "feat(api): new greeting behind FF_NEW_GREETING"
git push -u origin feat/new-greeting # Open PR and merge on the same day after CI passes
# Release: Cut the release branch from the verified commit on trunk (optional) and tag it
git switch -c release/1.1 origin/main && git tag -a v1.1.0 -m "release 1.1.0" && git push origin release/1.1 v1.1.0
Measuring branch health (applies to any strategy)
# How many commits are behind/ahead of main for each remote branch, and the last commit time git fetch --prune for b in $(git for-each-ref --format='%(refname:short)' refs/remotes/origin | grep -v -E 'origin/(main|HEAD)$|^origin$'); do printf '%-32s %s %s\n' "$b" "$(git rev-list --left-right --count origin/main...$b | tr '\t' '/')" "$(git log -1 --format=%cr $b)" done
origin/feat/new-greeting 0/1 3 hours ago origin/feature/billing-rewrite 214/57 7 weeks ago origin/release/1.0 3/1 2 days ago
How to interpret:The branch "214/57, 7 weeks ago" is a candidate for merge hell - main has advanced 214 commits. The main development team usually puts "branches that are alive for more than 2 days" into the Kanban board reminder.
Experiment 1: The same set of requirements are divided into main development and GitFlow (about 6 minutes)
cd ~/git-lab/p6/work git clone -q ~/git-lab/p6/remotes/myapp.git tbd # Trunk development git clone -q ~/git-lab/p6/remotes/myapp.git gf # GitFlow git -C gf switch -c develop && git -C gf push -q -u origin develop
cd ~/git-lab/p6/work/tbd
git switch -c feat/a
cat >> app.py <<'EOF'
FLAGS = {"feature_a": os.getenv("FF_FEATURE_A", "false") == "true"}
@app.get("/a")
def feature_a():
return ("A is on\n", 200) if FLAGS["feature_a"] else ("not found\n", 404)
EOF
git commit -qam "feat(api): feature A behind FF_FEATURE_A"
git switch main && git merge -q --ff-only feat/a && git branch -d feat/a
git log --oneline -3cd ~/git-lab/p6/work/gf git switch -c feature/a develop echo '# feature A' >> app.py && git commit -qam "feat(api): feature A" git switch develop && git merge -q --no-ff --no-edit feature/a git switch -c release/1.1 develop echo "1.1.0" > VERSION && git add VERSION && git commit -qm "chore(release): 1.1.0" git switch main && git merge -q --no-ff --no-edit release/1.1 && git tag -a v1.1.0 -m v1.1.0 git switch develop && git merge -q --no-ff --no-edit release/1.1 git log --oneline --graph --all --decorate -12
* 654bb26 (HEAD -> develop) Merge branch 'release/1.1' into develop |\ | | * 9cfc52c (tag: v1.1.0, main) Merge branch 'release/1.1' | | |\ | | |/ | |/| | * | ac9dbdf (release/1.1) chore(release): 1.1.0 |/ / * | 289d694 Merge branch 'feature/a' into develop |\ \ | |/ |/| | * 4b0e32b (feature/a) feat(api): feature A |/ * bb8b40c (tag: v1.0.0, origin/main, origin/develop, origin/HEAD) chore: initial myapp
for d in tbd gf; do echo "== $d"; git -C ~/git-lab/p6/work/$d rev-list --count --merges --all; git -C ~/git-lab/p6/work/$d branch --format='%(refname:short)'; done
With the same function, GitFlow generates 3 merge commits and maintains 2 long-term branches; the trunk develops 0 merge commits and 1 long-term branch. Function A is in trunk developmentAlready on main(The switch is off) and can be turned on at any time; in GitFlow, you have to wait for the next release.
cd ~/git-lab/p6/work/tbd
FF_FEATURE_A=true python -c "import app; c=app.app.test_client(); print(c.get('/a').data)"rm -rf ~/git-lab/p6/work/tbd ~/git-lab/p6/work/gf git -C ~/git-lab/p6/remotes/myapp.git branch -D develop
Case 1: SaaS team moves from GitFlow to trunk development
Question:The 20-person team uses GitFlow to pull releases from develop every two weeks, and the stabilization period is often one week; after hot fixes are merged into main, they forget to close develop many times, causing the same bug to be "resurrected" in the next version.Method:① Delete develop after merging develop into main, and set main as the default branch and add protection; ② Introduce the feature switch service, stipulating that unfinished functions must be switched after the switch; ③ If the PR survives for more than 2 days, raise it at the station meeting; ④ Turn on the merge queue (lesson 3) to ensure that main is always green; ⑤ Still retain the release branch cut from main for the rollback window.Effect:Releases went from biweekly to multiple times a day, and "bug resurgence" disappeared.Limitations:Automated tests need to be completed first; the number of switches must be capped and cleaned regularly.
Case 2: Embedded products retain release branch + LTS
Question:Device firmware needs to support 3 major versions at the customer site for 18 months.Method:Daily development is still trunk development (short branches), but each major versionrelease/N.xAnd maintained as LTS; repairs will always be done first in main, and thencherry-pick -xMove back (M2).Effect:There is no second long-term branch called develop, and the migration path is one-way and auditable.
Case 3: Regulated finance team worried about “non-compliant backbone development”
Question:Audits require that every change be approved and traceable.Method:Compliance is throughcontrol pointInstead of the number of branches, main is protected, PR must be approved by 2 people and the code owner approves, CI and security scanning are required, signature commits, production deployment requires environment approval, and releases are protected with annotation tags.Effect:The audit can be completely traced from tag → merge commit → PR → approval record → deployment record.
Frequently asked questions and solutions
The hotfix is online, but the same bug appears in the next version
Reason:In GitFlow, hotfix only merges into main and not into develop (or the fix is only done on the release branch and not into main).
git log --oneline main ^develop --no-merges # Commits that exist in main but not in develop git cherry -v develop main # Judge by patch-id, + means develop is missing
Fix:Merge or cherry-pick missing fixes into develop/main.Prevention:Use upstream first (fix the advanced trunk) and add a "reasonable reason for every non-cherry-pick commit on the release branch" check in CI.
CONFLICT (content): Merge conflict in … —— Conflicts break into pieces when merging long-term feature branches
Reason:Branches live for weeks, which is a huge difference from main.
git rev-list --left-right --count main...feature/big git diff --stat main...feature/big | tail -1
Fix:First merge (or rebase) main into the functional branch and solve it in batches; split the large branch into multiple small PRs that can be merged independently and hidden with switches.Prevention:Trunk development, Branch by Abstraction, limiting PR size.
The contents of develop and main are inconsistent. I don’t know which version is online.
git describe --tags --abbrev=0 main git log --oneline v1.4.0..develop --no-merges | wc -l
Fix:Use tag as the single source of truth for "what's online", and the deployment pipeline only builds from tag; consider removing develop.
There are more and more feature switches and no one dares to delete them
git grep -n -E 'flag\("[a-z_]+"\)' | sed -E 's/.*flag\("([a-z_]+)"\).*/\1/' | sort | uniq -c | sort -rn
git log -S 'flag("new_greeting")' --format='%h %ad %s' --date=short | tail -1 # Time when the switch was introduced
Fix:Create a "cleanup" task for each switch and set an expiration date; switches that are more than N weeks old are included in the cleanup; the switch service records the time when the switch service was last modified.
1. List the non-merge commits that are on main but not on develop (check whether the hot fix is missing).
git log --oneline --no-merges develop..main # Or judge based on the patch content (cherry-picked ones can also be identified): git cherry -v develop main
2. Use native commands to complete the hotfix of GitFlow: pull hotfix/1.1.1 from main, merge it into main after repair, tag it, and merge it into develop.
git switch -c hotfix/1.1.1 main git commit -am "fix: crash on empty cart" git switch main && git merge --no-ff hotfix/1.1.1 && git tag -a v1.1.1 -m v1.1.1 git switch develop && git merge --no-ff hotfix/1.1.1 && git branch -d hotfix/1.1.1
A SaaS product with a team of 40 people deployed multiple times a day, currently using GitFlow, with frequent "merge days". How would you recommend migrating?
The goal is trunk development + feature switching: ① First make CI fast and reliable enough (≤ 10 minutes), and open the merge queue; ② Introduce the switch service and the agreement that "unfinished functions must be after the switch"; ③ Freeze develop: merge develop into main, change the default branch to main, protect main, and delete develop; ④ Provide that PR is less than 400 lines and survive ≤ 2 days; ⑤ release Branches are only used for rollback/stability windows when needed, and repairs are made upstream first; ⑥ Use branch health scripts and DORA indicators (deployment frequency, change lead time) to measure effects. Risk: When there is insufficient testing, the problem will go directly to main - so step 1 is the prerequisite.
Verified instructional videos
The above titles and channels have been verified by the YouTube oEmbed interface (2026-11-15).
Official documents and original materials
- trunkbaseddevelopment.com(Paul Hammant)
- DORA: Trunk-based development
- A successful Git branching model (GitFlow original text, including 2020 Note of reflection)
- GitHub flow
- Martin Fowler: Patterns for Managing Source Code Branches · Feature Toggles
- Microsoft Learn: Adopt a Git branching strategy
Video storyboard (approximately 90 seconds)
This courseware cannot directly generate videos/MP3s. Storyboards and explanation scripts have been provided, which can be generated by video tools.
Screen: Two parallel timelines, with only a blue main line at the top and main and orange develop at the bottom.
Narrator: With the same three functions and one hot fix, let’s see how the two branching strategies work.
Screen: Functions A, B, and C at the top return to main in a small arc on the same day. A small green "deployment" box appears below each commit, with a closed switch icon next to it.
Narrator: In trunk development, functions are hidden behind switches. They are integrated and deployed every day. What users see is determined by the switch.
Screen: The function branch below is getting longer and longer on develop, and finally converges on the release branch, with the words "Release Date" flashing.
Narrator: In GitFlow, functions are advanced in develop, and main is entered after the release branch is stable. Integration was postponed until release.
Screen: The red hotfix requires two arrows (main and develop) at the bottom, and only one arrow to go to main and one cherry-pick to release.
Narrator: Fewer and shorter-lived branches, fewer merges, and fewer accidents. When choosing a strategy, first consider how many versions you want to maintain and how often you want to release them.
Module 2 · Release branches, hotfixes, and cherry-pick rollbacks
cherry-pick -xGo back to a release branch that is still supported- Pull the release branch from the tag and explain "what is allowed and what is not allowed" on the release branch.
- Press upstream first to complete a hot fix: repair main →
cherry-pick -xArriverelease/1.0→ hitv1.0.1;Can resolve move-back conflicts. - use
git cherry、git log --cherry-pick、--grep "cherry picked from"Audit "which fixes haven't been moved back yet" and develop a support strategy for multiple LTS branches.
What: Release branches and hot fixes
| concept | definition | rules |
|---|---|---|
| release branch | A branch pulled from some verified commit (usually a tag or release candidate), such asrelease/1.0 | Only bug fixes, security fixes, version numbers, and documentation changes will be accepted;Do not receive new features;Protected, only via PR |
| hotfix | Emergency fixes for released versions | Main development/GitLab Flow: repair main first, then move back; GitFlow: pull the hotfix branch from main and merge it into main and develop |
| backport | "Copy" commits on trunk to the old release branch | use git cherry-pick -x;Keep commits small and independent for easy rollback |
| forward-port | Repair in the old branch first, then bring it to the new branch and main | It is easy to miss main, which will cause the bug to reappear in the next version - try to avoid it; in case of emergency, main should be added immediately |
| LTS branch | Commit to a long-term release branch with fixes, e.g.release/2.xSupported for 18 months | State the support period and accepted repair categories (usually only security and serious defects are accepted); archive after expiration (tag, lock branch) |
Why: why upstream first
- will not be missed: Repair the advanced main, and the next version will naturally include it; the rollback only affects the old version.
- Review once: The repair is reviewed and tested according to the normal process on main. When moving back the PR, you only need to confirm that "it can be applied cleanly and the test passes".
- auditable:
-xBy writing the original commit hash in the rollback commit, anyone can trace the release branch back to the original fix on main.
How: what cherry-pick is doing
git cherry-pick CActually it was onceThree-way merger: base = parent commit of C, ours = current branch HEAD, theirs = C. Git applies the difference "C's parent → C" to the current branch, generating anew commit(The author and commit information follow C, the committer is you, and parent is the current HEAD). So when the context of the old branch is very different from main (for example, that code has been refactored on main), it willMove back conflict。
| Options | function |
|---|---|
-x | Append at the end of the commit message(cherry picked from commit < full hash >). Only applies to cases where the "source commit is on the public branch" (the hash of the private branch cannot be seen by others) |
-m 1 | When picking a merge commit, specify the first parent as the main line (used when moving back the merge commit of the entire PR) |
A..B / A^..B | Pick a range in order (A..BExcluding A) |
-n(--no-commit) | Applies only to the workspace and staging area to facilitate combining multiple commits into one rollback commit |
--continue / --skip / --abort | Continue after conflict / skip current commit / abandon entire sequence |
--empty=drop|keep|stop | How to handle when the target branch already contains the change (default stop) |
When: Which fixes need to be moved back to where
| Repair type | main | Current release release/1.1 | LTS release/1.0 | Support for release/0.9 has been discontinued |
|---|---|---|---|---|
| Security vulnerability (high risk) | ✓ | ✓ | ✓ | Determined by contract/announcement |
| Serious flaws (data loss, crashes) | ✓ | ✓ | ✓ | ✗ |
| General defects | ✓ | ✓ | Depends on the situation | ✗ |
| New features, refactoring | ✓ | ✗ | ✗ | ✗ |
git cherry(To compare two branches, presspatch-idIndicate which commits have "patch equivalents" already exist) andgit cherry-pick(copy commit) are two commands. patch-id is a hash of the contents of the diff: when moving backResolved conflictsThe commit patch-id will change,git cherryIt will be mistakenly reported as "not moved back (+)" - so you should also look at it when auditing-xEndnote.Figure 2-1 upstream first: fix flow from main to release branch
Figure 2-2 The source of the rollback conflict: the base of the three-way merge is the parent commit of F
Backtracking Matrix: Which branches does a fix go into?
Select the repair type and play through it step by step. The animation moves fixes back from main to branches still in support in upstream first order, and simulates conflicts on branches with large context differences.
Core commands
| command | function |
|---|---|
git switch -c release/1.0 v1.0.0 | Pull release branch from tag |
git cherry-pick -x <commit> | Move back and record the source |
git cherry-pick -x -m 1 <merge> | Move back the merge commit of the entire PR |
git cherry -v <upstream> <head> | List commits (+) and existing ones (-) in head with "equivalent patches not in upstream" by patch-id |
git log --cherry-pick --right-only --no-merges A...B | Commits that B has and A does not (excluding equivalent patches) |
git log --grep "cherry picked from" release/1.0 | List all rollback commits on the release branch |
git branch -r --contains <commit> | Which branches a certain commit (original hash) is on |
git tag --contains <commit> | Which versions contain the commit (only the original hash is recognized, not the moved copy) |
A complete hotfix (actual running results)
cd ~/git-lab/p6/work && git clone -q ~/git-lab/p6/remotes/platform.git rel && cd rel
sed -i 's|return "ok\\n"|return {"status": "ok"}|' services/api/app.py
git commit -qam "fix(api): healthz returns JSON for probes" # ① Fix advanced main
git switch release/1.0
git cherry-pick -x main # ② Move back
git log -1 --format=%B
[release/1.0 8f453b6] fix(api): healthz returns JSON for probes Date: Sun Nov 15 17:12:53 2026 -0500 1 file changed, 1 insertion(+), 1 deletion(-) fix(api): healthz returns JSON for probes (cherry picked from commit c30b01ab852ec2f313e22ecf3d5818b373d10a83)
git tag -a v1.0.1 -m "release 1.0.1: healthz JSON" # ③ Patch version git push origin main release/1.0 v1.0.1
Move back conflict (actual running result)
There is a refactoring on main firstd3ff315 refactor(api): extract hits variable, and then repair2486da8 fix(api): tolerate missing redis. Move back only fix:
git cherry-pick -x 2486da8 git diff
Auto-merging services/api/app.py
CONFLICT (content): Merge conflict in services/api/app.py
error: could not apply 2486da8... fix(api): tolerate missing redis
hint: After resolving the conflicts, mark them with
hint: "git add/rm <pathspec>", then run
hint: "git cherry-pick --continue".
...
diff --cc services/api/app.py
index 23e186d,4d2902f..0000000
--- a/services/api/app.py
+++ b/services/api/app.py
@@@ -5,7 -5,8 +5,12 @@@ cache = redis.Redis(host=os.getenv("RED
@app.get("/")
def index():
++<<<<<<< HEAD
+ return f"Hello from myapp! hits={cache.incr('hits')}\n"
++=======
+ hits = cache.incr("hits") if cache else 0
+ return f"Hello from myapp! hits={hits}\n"
++>>>>>>> 2486da8 (fix(api): tolerate missing redis)
Three processing methods:① Manual handleintention to repairport to legacy code (most common),git addaftergit cherry-pick --continue, and state "Conflicts resolved: ..." in the commit message; ② Move the previous reconstruction back together (git cherry-pick -x d3ff315 2486da8)——Only when the refactoring is small and risk-free; ③ Write an equivalent fix separately for the old branch, and the commit information refers to the original commit.
Audit: Which fixes haven’t been moved back yet? (actual operation results)
git cherry -v release/1.0 main git log --oneline --cherry-pick --right-only --no-merges release/1.0...main git log release/1.0 --grep="cherry picked from" --format='%h %s'
+ cb5754fb80f6cb90dd972ee3ccfba833aa475bad feat(web): new hero design + 535a7b70259f3ec832329379278ecbd0632be9f2 feat(infra): env variable - c30b01ab852ec2f313e22ecf3d5818b373d10a83 fix(api): healthz returns JSON for probes + d3ff315133ef83ee466b56ca3f013ef8b3fc6496 refactor(api): extract hits variable + 2486da842ba2b373565fa4734a3cc0e3bc31c4ed fix(api): tolerate missing redis 2486da8 fix(api): tolerate missing redis d3ff315 refactor(api): extract hits variable 535a7b7 feat(infra): env variable cb5754f feat(web): new hero design 073ce0c fix(api): tolerate missing redis 8f453b6 fix(api): healthz returns JSON for probes
How to read:Cleanly moved backc30b01adisplayed as-(an equivalent patch already exists); whereasResolved conflictsof 2486da8Still showing+, because the patch-id has changed. The third command press-xThe endnote lists two rollbacks - so the audit script should start with "fix:Does the full hash of the class commit appear in the release branch?cherry picked from"endnote" shall prevail.
#!/usr/bin/env bash
# List fix commits on main since v1.0.0 and check if they have been rolled back to release/1.0
set -euo pipefail
picked=$(git log release/1.0 --format=%B | sed -n 's/^(cherry picked from commit \([0-9a-f]\{40\}\))$/\1/p')
git log --no-merges --format='%H %s' v1.0.0..main | grep -E '^[0-9a-f]+ fix(\(|:)' | while read -r sha subject; do
if grep -q "$sha" <<<"$picked"; then echo "Moved back ${sha:0:7} $subject"; else echo "Not moved back ${sha:0:7} $subject"; fi
done
Experiment 2: Fix into main, move back to release/1.0 and resolve conflicts (about 6 minutes)
rm -rf ~/git-lab/p6/work/rel):
cd ~/git-lab/p6/work && git clone -q ~/git-lab/p6/remotes/platform.git rel && cd rel git config user.name Alice; git config user.email alice@example.com git branch -a
sed -i 's|return "ok\\n"|return {"status": "ok"}|' services/api/app.py
git commit -qam "fix(api): healthz returns JSON for probes"
python3 - <<'EOF'
p = "services/api/app.py"; s = open(p).read()
s = s.replace(' return f"Hello from myapp! hits={cache.incr(\'hits\')}\\n"',
' hits = cache.incr("hits")\n return f"Hello from myapp! hits={hits}\\n"')
open(p, "w").write(s)
EOF
git commit -qam "refactor(api): extract hits variable"
sed -i 's|hits = cache.incr("hits")|hits = cache.incr("hits") if cache else 0|' services/api/app.py
git commit -qam "fix(api): tolerate missing redis"
git log --oneline -4git switch release/1.0 git cherry-pick -x main~2 # clean git cherry-pick -x main # Conflict git status -s
services/api/app.py, replace the conflict block with a line of "old code + fix intent": return f"Hello from myapp! hits={cache.incr('hits') if cache else 0}\n"
git add services/api/app.py git cherry-pick --continue # Append a line in the editor: Conflicts resolved: adapted to pre-refactor code git log -2 --format='%h %s%n%b'
git tag -a v1.0.1 -m "release 1.0.1" git cherry -v release/1.0 main | grep fix git log release/1.0 --grep="cherry picked from" --oneline git describe --tags release/1.0
- c30b01a... fix(api): healthz returns JSON for probes + 2486da8... fix(api): tolerate missing redis 073ce0c fix(api): tolerate missing redis 8f453b6 fix(api): healthz returns JSON for probes v1.0.1
release/0.9, determine whether to move back (according to "Move Back Matrix", general defects will not be moved back to branches that have stopped supporting).cd ~/git-lab/p6/work && rm -rf rel # Not pushed, remote is not affected
Case 1: Open source projects are automatically moved back using robots
Question:Large-scale open source projects (such as Kubernetes, Python, Node.js) maintain multiple release branches at the same time, and manual rollbacks are easy to miss.Method:hit on PRbackport release-1.30Tags like this are automatically executed on the target branch after merging by robots (such as the backport GitHub Action/bot commonly used in the community)cherry-pick -xOpen a PR together; in case of conflict, the robot will comment under the original PR and it will be handled manually.Effect:Movebacks become part of the process and can be audited by tag in the PR list.Limitations:Robots can only handle clean moves, conflicts still require humans.
Case 2: "The fix is only on the release branch", the bug will be resurrected in the next version
Question:Friday night shift is directly atrelease/2.3Fixed a payment bug, no one brought it back to main on Monday,v2.4.0The same flaw appears again.Method:The process stipulates that the PR of the release branch must be linked to the original PR on main or containcherry picked from; CI checks every non-merge commit on the release branch and requires annotations if endnotes are missing.forward-port-requiredAnd automatically open a forward task.Effect:Exceptions are still allowed, but they are not forgotten.
Case 3: LTS support period out of control
Question:The team "smoothly" patched all 6 old versions, and there were more and more rollback conflicts.Method:The release support strategy is written into the README: the latest two minor versions + one LTS. LTS only accepts security fixes, and the branch will be patched after expiration.eol/1.0Tagged and locked (the platform's branch protection/rule set is set to read-only).Effect:The rollback workload is predictable and customers know the upgrade schedule.
Common errors and solutions
error: could not apply 2486da8... fix(api): tolerate missing redis
Reason:Move-back conflict: The target branch lacks the context (previous refactoring or feature) that the fix depends on.
git status -s git log --oneline release/1.0..main -- services/api/app.py # Main What else has been changed before this code? git show 2486da8 --stat
Fix:After manually transplanting the intentiongit add + git cherry-pick --continue;or--abortThen pick up the pre-commit together; or write an equivalent fix.
error: commit abc1234 is a merge but no -m option was given.
Reason:When a merge commit (such as a PR's merge commit) is selected, Git doesn't know which parent to take as the main line.
git cherry-pick -x -m 1 abc1234
The previous cherry-pick is now empty, possibly due to conflict resolution.
Reason:The target branch already contains the change (it was moved back before, or it was independently fixed).
git cherry-pick --skip # or --empty=drop automatically skip
After the release branch is merged into main, a large number of repeated changes or conflicts occur
Reason:Under the move-back model, the commits on release are all copies of the commits on main, and the same change appears twice during the merge.
git reset --hard ORIG_HEAD # Undo merge when not pushed git revert -m 1 <merge> # When pushed
Prevention:Under the upstream first model, the release branch will never be closed back to main; only GitFlow's release/hotfix branch will be closed back.
git tag --contains shows that the fix is not in v1.0.1, but the code is clearly fixed.
Reason:--containsOnly the original commit hash is recognized, and the moved copy is the new commit.
git log v1.0.1 --grep="$(git rev-parse c30b01a)" --oneline
1. Merge and commit the PR on main9f1e2d3Return the whole to release/1.1 and record the source.
git switch release/1.1 git cherry-pick -x -m 1 9f1e2d3
2. List the original hashes referenced by all rollback commits on release/1.0.
git log release/1.0 --format=%B | sed -n 's/^(cherry picked from commit \([0-9a-f]*\))$/\1/p'
You support 2.x (currently) and 1.x (LTS, security fixes only). The fix for a high-severity vulnerability in main relies on the new HTTP client only available in 2.x. How to go back to 1.x?
① To fix, merge it into main first and move it back to release/2.x (clean or with minor conflicts); ② 1.x lacks dependent context, so don’t move the entire new HTTP client back (high risk); ③ Write one for 1.xEquivalent minimal repair(For example, add verification on the old client), review and test separately, commit the information as "Backport of -xEndnotes, need to be documented in a ticket or PR tag).
Verified instructional videos
The above titles and channels have been verified by the YouTube oEmbed interface (2026-11-15).
Official documentation
- git-cherry-pick
- git-cherry
- git-patch-id
- Trunk Based Development: Branch for release
- Microsoft Learn: release branches and cherry-pick
Video storyboard (about 80 seconds)
This courseware cannot directly generate videos/MP3s. Storyboards and explanation scripts have been provided, which can be generated by video tools.
Screen: A red dot F appears on main, with two purple release branches release/1.1 and release/1.0 below.
Narrator: A bug is produced and the advanced trunk is fixed. This is called upstream first.
Screen: The dotted line copies F to release/1.1 to become F', and "cherry picked from commit..." pops up under the commit information.
Narrator: Use cherry-pick plus -x to move back, and the new commit remembers its origin.
Screen: When copying to release/1.0, a conflict mark appears. The left and right columns are the old code and the fix.
Narrator: The older the branch, the greater the context difference. Back migration conflicts are the norm, and what needs to be migrated is the intention of repair.
Screen: The terminal runs git cherry, with one line containing minus signs and one line containing plus signs.
Narrator: Don’t just trust git cherry when auditing. Reverts that have resolved conflicts will be falsely reported. The -x endnote is the evidence.
Module 3 · Monorepo vs. Polyrepo trade-off
- Defines monorepo, polyrepo and common hybrids ("few repositories" grouped by domain).
- fromPermissions, CI costs, dependency management, code ownershipCompare the two in four dimensions to know what Git itself can do in each dimension and what needs to be supplemented by the platform or construction tools.
- Can provide repository structure suggestions for a specific organization and write Git commands that trigger CI by path.
What: Definition
- Monorepo: Multiple projects (services, frontends, libraries, infrastructure code) are placed insame oneGit repository, divided by directory. It is not equivalent to a "monolithic application" - there can be 100 independently deployed microservices in a monorepo.
- Polyrepo(multi-repo): One repository per project, sharing code through package repositories (PyPI, npm, Maven, container image repositories) or submodules.
- mix: divided into a small number of repositories by team or area (e.g.
platform、mobile、infra-live), is the practical choice for many mid-sized organizations.
Comparison in four dimensions
| Dimensions | Monorepo | Polyrepo | The facts about Git itself |
|---|---|---|---|
| Permissions | Read permissions are all or nothing: if you can clone, you can see all directories; write permissions can be controlled by directory "who can approve" by CODEOWNERS / required reviewers / path rules | Each repository is independently authorized, which is naturally suitable for "outsourcing teams can only see their own code" and "confidential algorithm isolation" | Git protocol does not have directory-level read permissions: Once the object is in the repository, anyone who can fetch it can get it. Partial cloning and sparse checkouts are just "less downloads", not access control |
| CI cost | It is necessary to "build only the affected parts": trigger by path, build graph (Bazel, Nx, Turborepo, Pants), remote cache; otherwise, every commit must be fully built, and the cost will explode. | Each repository's pipeline naturally only builds itself; but cross-repository integration tests require additional orchestration. | git diff --name-only base...HEADis the starting point for all "impact detection"; shallow cloning can make it fail (Lesson 5) |
| Dependency management | Internal dependencies directly reference the source code,One commit atomically modifies the library and all callers;Usually enforces "one-version rule", no diamond dependency hell | The internal library is released to the package repository, and the caller upgrades according to SemVer; you can upgrade at your own pace, but there will be multiple versions coexisting and "upgrade debt" | Cross-repository changes cannot be committed atomically, and can only be "sent to the library first and then changed to the caller", or fixed commit using submodules (M4) |
| Code ownership | CODEOWNERS specifies teams by directory; high visibility, convenient for large-scale refactoring and code search | The repository is the unit of ownership with clear boundaries; but there are more duplicate codes and "unattended repositorys" | CODEOWNERS is a platform function (GitHub, GitLab; Azure Repos uses "automatically include reviewers + path filtering"), and Git is only responsible for storing files |
| Scale and performance | The number of files and history will become very large, requiring partial cloning of M5, sparse checkout, and maintenance of scalar and M6. | A single repository is small and fast | Many Git operations are directly proportional to the number of files and references in the workspace |
| branching strategy | Almost only mainline development: all teams share one main, and queues need to be merged | Each repository can choose different strategies (but avoid fragmentation of strategies) | — |
Why: Why do large companies use monorepo, and why do many companies not use it?
Google (self-developed Piper, not Git), Meta (derived from Sapling / Mercurial), and Microsoft (the Windows code base was moved to Git and developed VFS for Git, which later evolved into Scalar) chose giant single repositorys in exchange for atomic refactoring, unified dependencies and code visibility, but at the same time invested in dedicated version control and build teams. When small and medium-sized organizations do not have these investments, the CI and performance costs of monorepo may exceed the benefits; conversely, dozens of microservice repositorys operating independently will also cause dependency drift and duplicate configurations.
How: Minimum configuration for landing monorepo
- Directory convention:
services/、frontend/、libs/、infra/;The root directory stores unified tool configuration. - CODEOWNERS covers every top-level directory and the rule set requires code owner approval.
- CI trigger by path (GitHub Actions
on.push.paths、Azure Pipelinestrigger.paths、GitLabrules:changes), and when it becomes complex, a graph-building tool is introduced. - Merge queues to prevent main from turning red due to simultaneous merging of multiple teams.
- Developers use partial cloning + sparse checkout (M5) to only fetch their own directories.
When: Select recommendations
| situation | Suggestions |
|---|---|
| The front-end and infrastructure often need to be modified together (API contract, deployment list), and the 100-person team < can see all the code. | Monorepo or mixed repository by product |
| There are external contractors, compliance isolation (PCI, confidential algorithms), a mix of open and closed source | Polyrepo (at least isolate the parts that need to be isolated) |
| Multiple independent products, completely different release rhythms, almost no code sharing | Polyrepo |
| Internal shared libraries are used by many services, and upgrades often get stuck. | Monorepo or "repository into monorepo, service on demand" |
| Infrastructure code such as Terraform | Common practice: put the module in a shared repository and version it, configure the environment (live) in a separate repository and tighten the permissions |
Figure 3-1 The path of the same cross-team change in the two structures
Figure 3-2 Example of hybrid structure (one of the target forms of the comprehensive experiment in this lesson)
Interactive: Repository Structure Decision Scorer
Adjust each item to your organization's situation, and the scorer provides preferences and reasons for each of the four dimensions of this module. This is a heuristic tool to aid discussion, not a standard answer.
Core command: Locate "affected parts" in a monorepo
| command | function |
|---|---|
git diff --name-only origin/main...HEAD | Which files have been changed by PR (three points: relative to merge base) |
git diff --dirstat=files,0 origin/main...HEAD | Statistical change ratio by directory |
git log --format= --name-only --since=90.days | cut -d/ -f1-2 | sort | uniq -c | The popularity of changes in each directory in the past 90 days (useful when planning CODEOWNERS/split) |
git shortlog -sn -- services/api | Major contributors to a directory (who should be the owner) |
git ls-files | cut -d/ -f1-2 | sort | uniq -c | sort -rn | Number of files in each directory |
git count-objects -vH | Repository objects and pack volumes |
#!/usr/bin/env bash
# monorepo: Determine which targets to build based on the path of PR changes (the CI in Lesson 5 can be called directly)
set -euo pipefail
BASE=${1:-origin/main}
git fetch -q origin "${BASE#origin/}" # Make sure there is a merge base (shallow cloning requires --deepen or fetch-depth: 0)
changed=$(git diff --name-only "$BASE"...HEAD)
declare -A targets=()
while read -r f; do
case "$f" in
services/api/*) targets[api]=1 ;;
frontend/web/*) targets[web]=1;;
infra/*) targets[infra]=1 ;;
libs/*|.github/*) targets[api]=1; targets[web]=1;; # Shared code → all downstream builds
esac
done <<<"$changed"
echo "changed files: $(wc -l <<<"$changed")"
keys="${!targets[*]}"
echo "targets: ${keys:-none}"
cd ~/git-lab/p6/work && git clone -q ~/git-lab/p6/remotes/platform.git mono && cd mono git switch -c feat/rename-hits sed -i 's/hits=/count=/' services/api/app.py && echo '<!-- reads count -->' >> frontend/web/index.html git commit -qam "feat!: rename hits to count across api and web" bash ../affected.sh origin/main git diff --dirstat=files,0 origin/main...HEAD
changed files: 2 targets: api web 50.0% frontend/web/ 50.0% services/api/
put affected.shsave to~/git-lab/p6/work/Run again.targetsThe order depends on the bash associative array, which may beweb api。
Experiment 3: Make the same change once in monorepo and polyrepo (about 6 minutes)
cd ~/git-lab/p6/work && rm -rf mono && git clone -q ~/git-lab/p6/remotes/platform.git mono && cd mono git switch -c feat/rename-hits sed -i 's/hits=/count=/' services/api/app.py echo '<!-- reads count -->' >> frontend/web/index.html git commit -qam "feat!: rename hits to count across api and web" git show --stat --format='%h %s' HEAD
cd ~/git-lab/p6/work
for r in myapp web; do rm -rf poly-$r; git clone -q ~/git-lab/p6/remotes/$r.git poly-$r; done
cd poly-myapp && git switch -qc feat/count
sed -i 's/hits={cache.incr(.hits.)}/hits={h} count={h}/; s/def index():/def index():\n h = cache.incr("hits")/' app.py
git commit -qam "feat(api): add count alongside hits (compat period)" && git tag -a v1.2.0 -m v1.2.0
cd ../poly-web && git switch -qc feat/count
echo '<!-- reads count (requires myapp >= 1.2.0) -->' >> index.html
git commit -qam "feat(web): read count (requires myapp>=1.2.0)"
for r in myapp web; do git -C ../poly-$r log --oneline -1; done
Note that the web commit information can only use text to describe "depends on myapp ≥ 1.2.0" - Git cannot express cross-repository dependencies and requires package versions, submodules (M4) or release coordination.
infra/:
cd ~/git-lab/p6/work && rm -rf only-infra git clone -q --filter=blob:none --sparse ~/git-lab/p6/remotes/platform.git only-infra 2>&1 | tail -1 cd only-infra && git sparse-checkout set infra && ls git show HEAD:services/api/app.py | head -3 # You can still read the code of other teams (download on demand)
Conclusion: Sparse checkout ≠ permission control. Code that needs to be isolated must be placed in a separate repository. (Clone the local path withoutfile://When prefixing, Git takes local hard link optimization and printswarning: --filter is ignored in local clones; use file:// instead.--This is just to demonstrate visibility; M5 will use itfile://Make a true partial clone. )
cd ~/git-lab/p6/work/mono cat .github/CODEOWNERS git log --format= --name-only | grep -v '^$' | cut -d/ -f1-2 | sort | uniq -c | sort -rn
cd ~/git-lab/p6/work && rm -rf mono poly-myapp poly-web only-infra
Case 1: 40 microservice repositorys merged into 3 product repositorys
Question:Each microservice has a repository, and the shared library upgrade requires 40 PRs. Six months later, 15 services are still stuck at the old version; the CI template is copied in each repository.Method:Merged into 3 monorepo by product (M7's "merged repository retains history"), CODEOWNERS retains ownership of original team, CI triggers with path + build cache.Effect:The shared library upgrade becomes a PR; only one copy of the CI template is maintained.Limitations:The language tool chain versions need to be unified first; the two services responsible for external contractors maintain independent repositorys.
Case 2: CI bill tripled in monorepo
Question:All services are built with every PR after moving into the monorepo.Method:Use firstaffected.shWe stopped the bleeding with path mapping, introduced building graph tools and remote caching; restricted changes to shared directories to "need platform team approval".Effect:The average number of targets per PR build dropped from 30 to 2–3.
Case 3: Compliance audit requires segregation of payment code
Question:PCI audit requires that only a few people have access to the cardholder data processing code, but it is in the monorepo.Method:use git filter-repo --subdirectory-filter(M7) handleservices/paymentsTogether with the history, it was dismantled into independent repositories andClear from monorepo historyThis directory (otherwise objects in the history remain readable by everyone); monorepo calls it via a published package or API.Effect:Access control is returned to the repository level, and the audit is passed.
Frequently asked questions and solutions
fatal: ambiguous argument 'origin/main...HEAD': unknown revision or path not in the working tree.
Reason:CI medium shallow clone or single branch clone, noorigin/mainor no merge base (lesson 5).
git fetch --no-tags origin main:refs/remotes/origin/main --depth=200 git merge-base origin/main HEAD || git fetch --unshallow
Affected detection missed a certain service, and bad code entered main
Reason:Path mapping does not cover shared directories or root directory configurations (e.g.package-lock.json、.github/)。
git diff --name-only origin/main...HEAD | grep -v -E '^(services|frontend|infra)/'
Fix:Unmatched paths trigger a full build by default (safety); when the scale increases, use the build graph tool to deduce dependencies.
git status / git log are slow in monorepo
git ls-files | wc -l GIT_TRACE_PERFORMANCE=1 git status 2>&1 | tail -5
Fix:M5's sparse detection and sparse index,core.fsmonitor true、core.untrackedCache true, M6's commit-graph and background maintenance; or directlyscalar register。
CODEOWNERS is not valid: PR does not automatically request team review
Reason:The file is in the wrong location, the team doesn't have write permissions, the order of the rules (last match takes effect), or the syntax is wrong. See detailsLesson 3。
1. List the top-level two-level directories involved in changes to the current PR (relative to origin/main) and remove duplicates.
git diff --name-only origin/main...HEAD | cut -d/ -f1-2 | sort -u
2. Find the three authors who committed the most services/api in the past year as CODEOWNERS candidates.
git shortlog -sn --since=1.year -- services/api | head -3
A 60 person company: 3 services on backend, 1 React frontend, Terraform infrastructure; 5 external contractors doing frontend only; production infrastructure changes require approval. Provide repository structure suggestions.
Recommended hybrid structure: ①productMonorepo puts back-end services and shared libraries (atomic changes to APIs and callers, unified dependencies); ② Whether the front-end enters monorepo depends on the contractor - because Git does not have directory-level read permissions, the contractor should not see the back-end code when the front-end is in a separate repositoryweb, connected through the client package (version) generated by OpenAPI; ③infra-modules(readable, tagged) +infra-live(Only the platform team can write, GitLab Flow or environmental approval); ④ Each repository has CODEOWNERS, trunk development, and CI triggered by path. If there are no contractor constraints, the front end can also be put into a monorepo to obtain atomic contract changes.
Verified instructional videos
The above titles and channels have been verified by the YouTube oEmbed interface (2026-11-15).
Official documents and information
- Atlassian: Monorepos in Git
- GitHub: About code owners
- GitHub Blog: Make your monorepo feel small with Git’s sparse index
- monorepo.tools
Video storyboard (approx. 75 seconds)
This courseware cannot directly generate videos/MP3s. Storyboards and explanation scripts have been provided, which can be generated by video tools.
Picture: There are three folders in a large box on the left and three small boxes on the right.
Narrator: Same three projects, one repository or three repositorys?
Screen: One PR on the left changes three folders at the same time and merges them at once; three PRs on the right are queued, and a "compatibility period" clock appears in the middle.
Narrator: A single repository can change the API and caller atomically; multiple repositorys must be released in sequence.
Screen: A lock appears on the big box on the left that can only lock the entire box; each small box on the right has its own lock.
Narrator: Git does not have directory-level read permissions, and code that needs to be isolated must be separated into independent repositorys.
Screen: CI bill histogram, the column becomes shorter after the path is triggered.
Narrator: When choosing a single repository, invest in the ability to "build only the affected parts."
Module 4 · Submodules and subtrees
- Explain the data structure of submodules:
.gitmodules+ The mode in the tree is160000of gitlinkentry (only one commit hash is recorded). - Skilled use
clone --recurse-submodules、submodule update --init --recursive、update --remote, understand "fixed commit" and "detached HEAD". - use
subtree add/pull/splitImport and export subdirectories, and choose between submodules, subtrees, and package managers.
What: submodule
The submodule puts a repository (superproject, parent repository) on a certain pathReference a specific commit in another repository. Two things are stored in the parent repository:
.gitmodules:path → URL (and optionallybranch、updatemode), are ordinary tracked files.- one of the tree objectsgitlink:
160000 commit <sha> infra. Parent repositoryNoSave any files or history of submodules, just this hash.
The actual repository for the submodule is at.git/modules/infra/, in the workspaceinfra/.gitis a file pointing to it. After checking out, the submodule is inDetach HEAD(detached HEAD) status - because the parent repository requires "that commit" rather than "the latest of a certain branch".
What:subtree
git subtree(the contrib script distributed with Git) puts the contents of another repositoryas a normal fileMerge into a subdirectory:addImport (can--squashinto a commit),pullupdate,push/splitExtract modifications to subdirectories into an independent history and push them back upstream. It appears to the user as a normal directory and does not require any additional steps when cloning.
Contrast
| submodule | subtree | Package manager (PyPI/npm/Terraform Registry) | |
|---|---|---|---|
| What is stored in the parent repository? | Only save commit hashes (gitlink) | Full file (optional with upstream history) | Version constraints (such asflask==3.1.0、version = "~> 1.4") |
| Clone experience | need --recurse-submodulesorupdate --init, otherwise it is an empty directory | Transparent, normal cloning is enough | Install dependency steps |
| fixed version | Accurate to commit (naturally fixed) | The content is in the repository | Version number + lock file |
| Modify dependencies | Enter the submodule directory to commit, push the subrepository, and then commit the new pointer to the parent repository (two commits) | Change it directly and use it latersubtree push/splitGive back to upstream | Change upstream, release, upgrade |
| Permissions | Sub-repositories can be authorized individually (sub-modules will fail when someone without permission clones the parent repository) | Content is fully visible to readers of the parent repository | Package repository authorization |
| suitable for | Need to accurately fix third-party source code, independent authorization of sub-repositories, embedded/game engines, etc. | A small amount of code is shared, hoping that users will not notice it. | Most language-level dependencies -Prioritize this |
How: Key configuration of submodules
| Configuration/Options | function |
|---|---|
git clone --recurse-submodules | Automatic init + update after cloning (including nesting) |
git submodule update --init --recursive | Register and checkout commits recorded in the parent repository, recursively processing nested submodules |
git submodule update --remote [--merge|--rebase] | Move the submodule to its tracking branch (.gitmodules of branch, the latest commit of the default remote HEAD); after that, a new pointer must be committed in the parent repository |
submodule.recurse=true | letpull、switch、checkoutWait for commands to automatically update submodules (except clone) |
status.submoduleSummary=true、diff.submodule=log | git status/git diffDisplay the commit list corresponding to the submodule pointer change |
push.recurseSubmodules=check|on-demand | Check/automatically push unpushed commits in submodules before pushing to the parent repository to avoid "pointers pointing to non-existent commits" |
git submodule set-url / set-branch / deinit / absorbgitdirs | Change URL, change tracking branch, cancel registration, move embedded .git to parent repository |
protocol.file.allowDefault isuser, submodule command internal clonelocal path/file://The time will be reportedfatal: transport 'file' not allowed. For experiments in this lessongit -c protocol.file.allow=always submodule …Temporary release; real projects use HTTPS/SSH URLs and are not affected. Do not set it to always globally.update --init, the directory is empty and the build failed. ② If the sub-module is committed but the sub-repository is not pushed, the parent repository pushes the new pointer → Othersupdatetimesdid not contain … / not our ref. ③ Commit on the detached HEAD, and the commit is "lost" after switching (use reflog to retrieve it). ④git pullOnly the pointer of the parent repository is updated, and the submodule workspace is not updated.git status show modified: infra (new commits), if at this timegit commit -awill pointerChange back to old value. ⑤ Private submodules require additional credentials in CI (Lesson 5). ⑥ Use relative URL (../infra.git) allows both forks and mirrors to work.Figure 4-1 Data structure of submodule: the parent repository only saves a commit hash
Figure 4-2 subtree: content enters parent repository history
gitlink pointer movement demonstration: the life cycle of a submodule
Play step by step and observe the parent repositoryinfraThe relationship between gitlink, the HEAD of the submodule workspace, and the subrepository main. The hash is taken from the actual running results of this lesson.
Submodules: add, clone, update (actual running results)
R=~/git-lab/p6/remotes cd ~/git-lab/p6/work && git clone -q $R/myapp.git sm && cd sm git submodule add $R/infra.git infra # local path → rejected git -c protocol.file.allow=always submodule add $R/infra.git infra cat .gitmodules git commit -qm "chore: add infra as submodule" git ls-tree HEAD infra git submodule status
fatal: transport 'file' not allowed fatal: clone of '/home/azureuser/git-lab/p6/remotes/infra.git' into submodule path '/home/azureuser/git-lab/p6/work/sm/infra' failed Cloning into '/home/azureuser/git-lab/p6/work/sm/infra'... done. [submodule "infra"] path = infra url = /home/azureuser/git-lab/p6/remotes/infra.git 160000 commit e5d225550f78ae77414df07319f14843246f96e3 infra e5d225550f78ae77414df07319f14843246f96e3 infra (v1.0.0)
git push -q origin main cd .. && git clone -q $R/myapp.git sm2 && cd sm2 ls infra | wc -l; git submodule status # Empty directory, prefix - means not initialized git -c protocol.file.allow=always submodule update --init --recursive git -C infra status | head -1
0 -e5d225550f78ae77414df07319f14843246f96e3 infra Submodule 'infra' (/home/azureuser/git-lab/p6/remotes/infra.git) registered for path 'infra' Cloning into '/home/azureuser/git-lab/p6/work/sm2/infra'... done. Submodule path 'infra': checked out 'e5d225550f78ae77414df07319f14843246f96e3' HEAD detached at e5d2255
git submodule statusprefix:-not initialized;+The commit checked out by the submodule is inconsistent with the one recorded in the parent repository;UMerge conflicts; spaces indicate consistency.
Upgrade fixed commits
git -c protocol.file.allow=always submodule update --remote infra # Move main to infra latest git status -s git diff --submodule=log git commit -qam "chore: bump infra submodule"
Submodule path 'infra': checked out '2efb83fe59e1a15066b8381f5ae910c3f05a8165' M infra Submodule infra e5d2255..2efb83f: > feat: output rg name
You can also enter the submodule to manually select the version:git -C infra fetch && git -C infra switch --detach v1.1.0 && git add infra——Pinning to tag is more controllable than pinning to "branch latest".
Recommended team configuration
git config --global submodule.recurse true # pull/switch automatically updates submodules git config --global status.submoduleSummary true git config --global diff.submodule log git config --global push.recurseSubmodules check # Refuse to push the parent repository when the submodule has unpushed commits. git config -f .gitmodules submodule.infra.url ../infra.git # Relative URL, adapted to forks and mirrors git submodule sync --recursive
Remove submodule
git submodule deinit -f infra git rm -f infra # Delete entries in .gitmodules and gitlink at the same time rm -rf .git/modules/infra git commit -m "chore: remove infra submodule"
subtree: add/pull/split (actual running results)
cd ~/git-lab/p6/work && git clone -q $R/web.git st && cd st git subtree add --prefix=infra $R/infra.git main --squash git log --oneline --graph -4
* branch main -> FETCH_HEAD Added dir 'infra' * 51b5c17 Merge commit 'ba366f504b8864561df2cc2f485d6469661f6e06' as 'infra' |\ | * ba366f5 Squashed 'infra/' content from commit 156c978 * 3d4634a chore: initial web
git subtree pull --prefix=infra $R/infra.git main --squash -m "chore: update infra subtree"
echo 'locals { team = "backend" }' >> infra/terraform/main.tf && git commit -qam "fix(infra): add team local"
git subtree split --prefix=infra -b infra-export # Extract the history of infra/ as an independent branch
git log --oneline infra-export -3
# git subtree push --prefix=infra $R/infra.git feature/from-web # Push back a branch upstream and open a PR
Subtree is already at commit 156c97801adfeba5c916be459be5f12718c148e2. fc1bef7019fbcbf4d36cb6d67942608ee3fa46df fc1bef7 fix(infra): add team local 156c978 feat: output rg name 091be25 chore: initial infra
Note:splitThe generated commit hash is deterministic. Run the same input multiple times to get the same hash; push the split result to the new upstream branch, and then open a PR according to the upstream process. Do not push the upstream main directly.
Experiment 4: Connect infra as submodule and subtree (about 6 minutes)
~/git-lab/p6/work/smAdd submodules and push. usegit cat-file -p HEAD^{tree}found160000 commitThat line.sm2Experience "normal cloning (empty directory)" andgit clone --recurse-submodules:
cd ~/git-lab/p6/work && rm -rf sm3 git -c protocol.file.allow=always clone -q --recurse-submodules ~/git-lab/p6/remotes/myapp.git sm3 git -C sm3 submodule status
cd ~/git-lab/p6/work/sm/infra git switch -c wip && echo '# local only' >> terraform/main.tf && git commit -qam "wip: not pushed" cd .. && git add infra && git commit -qm "chore: point infra to wip" git push --recurse-submodules=check origin main
The following submodule paths contain changes that can not be found on any remote: infra Please try git push --recurse-submodules=on-demand or cd to the path and use git push to push them to a remote. fatal: Aborting. fatal: the remote end hung up unexpectedly
Cancel:git reset --hard HEAD~1 && git submodule update。
stIn add → modify → split, compare the two methodsgit clonethe contents of the directory after.cd ~/git-lab/p6/work git -C sm count-objects -vH | grep size-pack; git -C st count-objects -vH | grep size-pack git -C sm ls-files | head; echo ---; git -C st ls-files | head
There are no infra files in the submodule's parent repository (only gitlink); the subtree's parent repository contains all files.
cd ~/git-lab/p6/work && rm -rf sm sm2 sm3 st infra-dev bash ~/setup-p6.sh # If you save the script in your home directory: Rebuild the remote repository and undo the push of this experiment to myapp.git
Case 1: CI build fails sporadically - submodule pointer points to non-existent commit
Question:The developer forgot to push after committing in the sub-module, so he pushed to the parent repository; CI reportfatal: remote error: upload-pack: not our ref …。Method:Team unitypush.recurseSubmodules=check;Add check step to CI of parent repositorygit submodule update --init --recursiveIf it fails, it will prompt "Please push the submodule"; the main of the sub-repository is protected, and the parent repository is only allowed to point to the commits reachable on the main of the sub-repository (CI usesgit -C infra merge-base --is-ancestor HEAD origin/mainverification).Effect:Such failures disappear.
Case 2: Use subtree to share CI templates, later changed to platform functions
Question:30 repositories use subtree to introduce the sameci-templates/Directory, each template update must be executed in 30 repositoriessubtree pull。Method:Switch to platform-native template reuse (GitHub reusable workflow, Azure Pipelines template + resource repository, GitLabinclude:project), quoted by tag.Effect:Template upgrade only changes the version number.Lessons:Subtree is suitable for "occasional synchronization" code and is not suitable for frequently changing shared configurations.
Case 3: Game Studio fixes engine version with submodule
Question:Multiple games share the self-developed engine, and each game needs to upgrade the engine at different times.Method:The engine is an independent repository (only writing permissions are given to the engine team). Each game uses sub-modules to fix the tags of the engine; art resources go to LFS (M5).Effect:Each game commit accurately records the version of the engine it was built with, allowing historical versions to be reproduced.
Common errors and solutions
fatal: transport 'file' not allowed
Reason:From 2.38.1protocol.file.allow Default user, cloning the local repository inside the submodule was rejected.
git -c protocol.file.allow=always submodule update --init
Only used if you trust this local repository; use HTTPS/SSH URLs in production.
fatal: remote error: upload-pack: not our ref e5d2255… / Fetched in submodule path 'infra', but it did not contain e5d2255…
Reason:The commits recorded in the parent repository were not pushed to the child repository remotely (or were deleted by force push).
git ls-tree HEAD infra
git -C infra branch -r --contains $(git ls-tree HEAD infra | awk '{print $3}')
Fix:Let the committer push the submodule's commit; or change the pointer back to the remote existing commit in the parent repository.
git status shows modified: infra (new commits), but I haven't changed anything
Reason:git pullThe gitlink of the parent repository was updated, but the submodule workspace is still at the old commit (or you switched commits in the submodule).
git diff --submodule=log infra git submodule update --recursive # Let the submodule keep up with the commits recorded in the parent repository
Note:Don't do it at this timegit commit -a, otherwise the pointer will be changed back to the old value; setsubmodule.recurse=truePrevention.
fatal: 'infra' already exists in the index
Reason:The path is already occupied by a normal file or an old submodule.
git rm -r --cached infra && rm -rf .git/modules/infra git submodule add <url> infra
fatal: can't squash-merge: 'infra' was never added. / fatal: prefix 'infra' already exists.
Reason:subtree pull --squashCan't find the originaladd --squashwritten in the commit messagegit-subtree-dirrecord; or the target directory already exists (e.g. was once a submodule).
git log --grep="git-subtree-dir: infra" --oneline
Fix:Keep using both add and pull (or neither)--squash;When the directory already exists, firstgit rm -rand commit.
1. Clone a repository with nested submodules and let subsequent pull/switch automatically update the submodules.
git clone --recurse-submodules <url> git config submodule.recurse true
2. Pin submodule infra to its v1.1.0 tag and commit.
git -C infra fetch --tags git -C infra switch --detach v1.1.0 git add infra && git commit -m "chore: pin infra to v1.1.0"
The front-end repository wants to reuse the OpenAPI definition file in the back-end repository (a directory that changes several times a month). Use submodules, subtrees or something else?
"Release component" is preferred: the back-end CI generates the client package (npm) from the OpenAPI definition and versions it, and the front-end relies on version dependencies - the version semantics are clear and there are no Git special operations. If source files must be shared: changes are infrequent and front-end developers are not expected to notice → subtree (regularsubtree pull --squash); requires precise knowledge of "which backend commit was used to build the frontend" and the frontend developer can accept the extra step of → pinning the submodule to the backend tag. If both sides often modify simultaneously, it means that they should be in the same repository (M3's monorepo).
Verified instructional videos
The above titles and channels have been verified by the YouTube oEmbed interface (2026-11-15).
Official documentation
- git-submodule
- gitsubmodules (concept)
- Pro Git 7.11 Submodules
- git-subtree(contrib)
- git-config: protocol.allow / protocol.file.allow
Video storyboard (about 80 seconds)
This courseware cannot directly generate videos/MP3s. Storyboards and explanation scripts have been provided, which can be generated by video tools.
Screen: The tree of the parent repository is expanded, and a line of 160000 commit e5d2255 infra is marked by a red box.
Narrator: A submodule is just one line in the parent repository: a pointer to a commit in another repository.
Screen: Colleagues clone normally, the infra folder is empty; the file appears after executing update --init, and the status bar shows HEAD detached.
Narrator: After cloning, you need to initialize the submodule. It will check out the commit recorded in the parent repository, so HEAD is separated.
Screen: The sub-repository main takes a step forward, and the parent repository pointer does not move; M infra appears after update --remote, and commits again.
Narrator: Upgrading a submodule requires two steps: moving the submodule, and then committing the new pointer to the parent repository.
Screen: subtree: External content is merged into the infra directory as ordinary files and is directly visible when cloning.
Narrator: subtree actually puts the content in without the user noticing; for most language dependencies, it is best to leave it to the package manager.
Module 5 · Large repository: Git LFS, partial cloning, sparse checkout, scalar
- Explain LFS pointer file + clean/smudge filter mechanism; will
git lfs track、git lfs migrate import/info, locking, and understanding the platform’s file size and quota limits. - Explain partially clonedpromisor remotemechanism, distinction
--filter=blob:none(no blob clone) vs.--filter=tree:0Applicable scenarios for (treeless cloning) and shallow cloning. - Use cone mode sparse checkout to only check out the required directories, and use
scalarRecommended settings for configuring a large repository at once.
Question: Why is a large repository slow?
| Where is "big"? | Symptoms | Countermeasures |
|---|---|---|
| Large binary files (design drafts, videos, models, data sets) | The clones are huge; each version is saved intact and almost impossible to compress/increment; the platform refuses to push (GitHub single file > 100 MiB) | Git LFS(or not put into Git at all: Object Storage + Manifest) |
| A long history, many versions | git cloneDownload all blobs in all history | partial clone --filter=blob:none;Use shallow clone ortree:0 |
| The workspace has a very large number of files (hundreds of thousands) | git status、checkoutSlow, huge index | Sparse checkout cone mode + sparse index、fsmonitor、untracked cache |
| There are many citations and many packs | fetch negotiation is slow,git log --graphslow | M6: commit-graph, multi-pack-index, background maintenance, reftable |
Git LFS: pointers + filters
git lfs track "*.psd" in .gitattributeswrite*.psd filter=lfs diff=lfs merge=lfs -text. After:
- clean filter(
git addtime): Save the file content locally.git/lfs/objects/, the Git object library only stores a 130-bytepointer file(version、oid sha256:…、size)。 - pre-push hook: When pushing, upload the LFS object to the LFS storage of the platform through the LFS API (HTTPS).
- smudge filter(When checking out): After reading the pointer, download the real content from the LFS server and put it into the workspace. Available
GIT_LFS_SKIP_SMUDGE=1Just pointer, thengit lfs pull --include=…Download on demand.
| command | Whether to rewrite history | Purpose |
|---|---|---|
git lfs track "*.psd" | No | Only affectsafterFiles added; large files already in history are still there |
git lfs migrate info --everything | No | Statistics of file sizes in history by extension to decide which types to migrate |
git lfs migrate import --include="*.psd" --everything | Yes(The hashes of all branches and tags will change) | Convert all matching files in history into pointers; laterpush --force --all/--tags, everyone re-clone |
git lfs migrate import --no-rewrite file... | No (append a new commit) | Only the current version is converted to LFS, and the old versions in history are still in Git. |
git lfs migrate export --include="*.psd" --everything | Yes | Reverse: Convert LFS back to normal Git objects |
Lockdown: Fix "Binary files cannot be merged"
Binary files such as design drafts and Unity scenes cannot be merged when they conflict.git lfs track "*.psd" --lockableHave such files checked out asread only, before editinggit lfs lock file.psd, the server records the holder of the lock; modifications to the file pushed by others will be rejected; after completiongit lfs unlock. Administrators can--forceUnlocked. The lock requires the platform to support the LFS File Locking API (GitHub, GitLab, and Azure Repos all support it; refer to the documentation of each platform).
Platform restrictions (verified in 2026-11)
| Platform | LFS quotas/limits |
|---|---|
| GitHub | LFS storage and bandwidth included per account: Free/Pro/Organization Free Edition each10 GiB storage + 10 GiB/month bandwidth;Team and Enterprise Cloud each250 GiB + 250 GiB;Exceeds billing per GiB. Normal Git objects: > 50 MiB warning, > 100 MiB rejected. LFS single file limit per plan (Free 2 GB, up to Enterprise Cloud 5 GB) |
| Azure Repos | Support LFS (HTTPS;SSH does not support LFS, see Lesson 3); Repository recommendation < 10 GB, upper limit 250 GB, single push ≤ 5 GB |
| GitLab | Supports LFS and file locking; LFS objects count against project/namespace storage quota (subject to GitLab.com's current storage quota documentation) |
| AWS CodeCommit | The roadmap had planned to support LFS, and Lesson 4 explains its current status; before it was supported, S3 was used to store large files. |
partial clone
Partial cloning lets the server generate packsOmit objects by filter, the client marks the remote aspromisor remote(remote.origin.promisor=true、remote.origin.partialclonefilter=blob:none). When any subsequent command requires a locally missing object, Git will not report "object lost", but will automatically initiate a fetch to the promisor to retrieve it (the missing blob will be retrieved when checking outbatchrequest).
| way | Download when cloning | Then download on demand | suitable for | Note |
|---|---|---|---|---|
| full clone | All commits, trees, blobs | — | small repository | — |
--filter=blob:none(blobless) | All commits and trees; only download the blobs required for checkout | switch branches,diff、blameGet blob in old version | Developer's daily life(GitHub recommended) | The first blame long history file will trigger multiple downloads; you can firstgit backfill(2.49+) Batch retrieval |
--filter=tree:0(treeless) | All commits; only download the tree and blob of HEAD | Taken when accessing the old committed tree, the cost is higher | One-off CI builds, just need the latest code but want to keep the full commit history (e.g.git describe) | Daily use by developers will frequently trigger downloads and is not recommended. |
--filter=blob:limit=1m | blob less than 1 MiB | big blob | There are large files mixed in the history but LFS has not been migrated yet | — |
Shallow clone --depth=1 | Only recent commits (truncated history) | Will not be automatically replenished; required--deepen/--unshallow | CI that is built once and then discarded | merge-base、describe, the affected detection will fail (Lesson 5) |
sparse-checkout cone mode
sparse checkout controlworkspaceWhich files appear in, and partial clones (controlDownloadWhich objects) are orthogonal, and the two work best together.cone modeOnly directories are accepted: files containing the root directory + directories you specify (recursively) + direct files in the ancestor directories of these directories. Its matching can be hashed by directory prefix, which is much faster than the gitignore-style mode of non-cone mode; the non-cone mode has been deprecated since 2.37. cooperate--sparse-index, only one "sparse directory entry" of the directory outside cone is stored in the index.git statusThe overhead of other commands is proportional to the number of files in cone.
Scalar: Configure a large repository with one command
scalarFrom Microsoft (successor of VFS for Git),Installed with Git core starting from 2.38。scalar clone <url>Will: only clone commit and tree (that is, no blob partial clone), initialize sparse checkout (default only top-level files, then usegit sparse-checkout setadd a directory), register for background maintenance (M6), enable the built-in fsmonitor when available, and set a set of recommended configurations (e.g.gc.auto=0、index.version=4、fetch.unpackLimit=1). The repository is placed<enlistment>/src(--no-srccan be placed directly in the directory). A repository is availablescalar registerAccess, use after upgrading Gitscalar reconfigure --allRefresh configuration. The git package for some Linux distributions may not be installedscalarExecutable file, you can manually configure it with the corresponding git command at this time.
.git/lfsor onlylfs pull --includerequired part.Figure 5-1 LFS clean / smudge process
Figure 5-2 Three types of cloned downloaded objects (actual running data of the platform repository in this lesson)
git rev-list --objects --all --missing=print | grep -c '^?')Core Animation: Partial Cloning + Sparse Checkout How to Download Objects on Demand
On the left is the object of the server (platform.git), on the right is your clone. Play step by stepclone --filter=blob:none --no-checkout → sparse-checkout set --cone services/api → checkout→ Access files outside cone → Expand cone. The gray dotted boxes are blobs that are "promised" but have not yet been downloaded. Numbers are taken from actual runs of this lesson.
Git LFS
git lfs install # Once per machine: register filter.lfs.* with hooks in ~/.gitconfig git lfs track "*.psd" "*.mp4" # Write .gitattributes (remember to commit it) git lfs track "*.psd" --lockable # Lockable (checkout is read-only) git add .gitattributes frontend/web/assets/hero.psd git lfs ls-files # Files managed by LFS in the current commit git lfs status git lfs lock frontend/web/assets/hero.psd && git lfs locks && git lfs unlock frontend/web/assets/hero.psd GIT_LFS_SKIP_SMUDGE=1 git clone <url> # Just pointer git lfs pull --include="frontend/web/assets/*.psd" git lfs prune # Clean up old local LFS objects that are no longer needed git lfs fsck # Verify local LFS objects and pointers
Migrate large files in history (history will be rewritten)
cd ~/git-lab/p6/work && git clone -q ~/git-lab/p6/remotes/platform.git lfs && cd lfs git lfs migrate info --everything --top=5 git lfs migrate import --everything --include="*.psd,*.mp4" cat .gitattributes git cat-file -p HEAD:frontend/web/assets/hero.psd
migrate: Sorting commits: ..., done. *.psd 6.0 MB 2/2 files 100% *.mp4 2.0 MB 1/1 files 100% *.py 1.3 KB 3/3 files 100% ... migrate: Rewriting commits: 100% (5/5), done. main 6e38394… -> 9b2f0d1… release/1.0 0d81c15… -> 4c7e2a8… migrate: Updating refs: ..., done. *.psd filter=lfs diff=lfs merge=lfs -text *.mp4 filter=lfs diff=lfs merge=lfs -text version https://git-lfs.github.com/spec/v1 oid sha256:4d7a214614ab2935c943f9e0ff69d22eadbb8f32b1258daaa5e2ca24d17e2393 size 3000000
The hashes of all branches and tags have changed (--everythingAll local and remote-tracking references will be rewritten and the labels will be updated), which will be needed latergit push --force --all origin && git push --force --tags origin, notify everyone to re-clone (pushing back the history in the old clone will resurrect large files). Platform side: Old objects on GitHub may still be referenced by PRs and occupy storage. Contact support to clean up if necessary (Lesson 7).
Partial cloning and sparse checkout (actual running results)
R=~/git-lab/p6/remotes cd ~/git-lab/p6/work git clone --filter=blob:none --no-checkout "file://$R/platform.git" pc && cd pc git rev-list --objects --all --missing=print | grep -c '^?' # Number of missing (promised) objects git sparse-checkout set --cone services/api git checkout main ls; cat .git/info/sparse-checkout git rev-list --objects --all --missing=print | grep -c '^?' git config remote.origin.promisor; git config remote.origin.partialclonefilter git count-objects -vH | grep size-pack
Cloning into 'pc'... 14 Your branch is up to date with 'origin/main'. Already on 'main' README.md services /* !/*/ /services/ !/services/*/ /services/api/ 10 true blob:none size-pack: 5.92 KiB
git show HEAD:infra/terraform/main.tf | head -2 # Files outside cone: automatically download 1 blob on demand git rev-list --objects --all --missing=print | grep -c '^?' git sparse-checkout add infra # Expand cone ls; git rev-list --objects --all --missing=print | grep -c '^?' git sparse-checkout list git sparse-checkout disable #Restore the complete workspace (all required blobs will be downloaded)
resource "azurerm_resource_group" "rg" {
name = "rg-myapp"
9
README.md
infra
services
8
infra
services/api
Treeless cloning with git backfill
git clone --filter=tree:0 "file://$R/platform.git" tl && cd tl git rev-list --objects --all --missing=print | grep -c '^?' # Actual operation: 4 git log --oneline -- services/api #requires old tree → automatic download git -C ../pc backfill # 2.49+: Fill in missing blobs in batches (--sparse only fills in cone)
Convert existing full clone to sparse + sparse index
git sparse-checkout init --cone --sparse-index git sparse-checkout set services/api frontend/web git config core.fsmonitor true && git config core.untrackedCache true
scalar
scalar clone --branch main https://github.com/<org>/<big-repo>.git big # The repository is in big/src cd big/src && git sparse-checkout set services/api scalar list # Registered repositorys scalar register ~/git-lab/p6/work/pc # Already have repository access (and enable background maintenance) scalar reconfigure --all # Refresh recommended configuration after upgrading Git scalar diagnose # Generate diagnostic zip (for bug reporting) scalar unregister ~/git-lab/p6/work/pc
Experiment 5: Partial clone + cone mode only takes services/api, and then migrates the design draft to LFS (about 8 minutes)
R=~/git-lab/p6/remotes; cd ~/git-lab/p6/work && rm -rf full pc git clone -q "file://$R/platform.git" full git clone -q --filter=blob:none --no-checkout "file://$R/platform.git" pc du -sh full/.git pc/.git
cd pc && git sparse-checkout set --cone services/api && git checkout -q main find . -path ./.git -prune -o -type f -print | sort git rev-list --objects --all --missing=print | grep -c '^?'
GIT_TRACE=1 git show HEAD~3:frontend/web/index.html 2>&1 | grep -E "fetch|run_command" | head -3
You will see Git running in the backgroundgit fetch … --filter=blob:none --stdinSubcommands like this retrieve a single object.
~/git-lab/p6/work/lfsexecuted inmigrate info with migrate import, and then compare:cd ~/git-lab/p6/work/lfs git reflog expire --expire=now --all && git gc -q --prune=now git count-objects -vH | grep size-pack # Git object library becomes smaller, large files are in .git/lfs/objects du -sh .git/lfs
git lfs track "*.psd" --lockable && cat .gitattributes git lfs lock frontend/web/assets/hero.psd # Local remote: error, indicating that the lock depends on the LFS API of the platform
cd ~/git-lab/p6/work && rm -rf full pc tl lfs
Case 1: The game repository is 120 GB, and it takes half a day for a new user to clone it.
Question:Art resources are committed directly to Git, with a cumulative total of 120 GB.Method:① git lfs migrate info --everythingFind the extension with the largest proportion; ② Freeze the push during the maintenance window.migrate import --everythingAfter conversion, force push to new repository (keep old repository read-only as archive); ③.gitattributesmiddle pair*.uasset、*.psd settings --lockable;④ CI cache.git/lfs。Effect:The Git history is reduced to 2 GB, and new users can start working within 30 minutes using partial cloning + LFS pull on demand.Limitations:LFS bandwidth quota becomes a new cost item that needs to be monitored.
Case 2: monorepo developers only care about their own directories
Question:A monorepo of 200,000 files,git statusIt takes 8 seconds.Method:For developers to use uniformlyscalar clone, provided by teamsparse-checkout setDirectory listing; for CI--filter=tree:0+ Sparse checkout only takes affected directories.Effect:git statusDown to sub-second level.
Case 3: LFS bandwidth is used up at the beginning of the month
Question:CI is fully cloned for every build, bandwidth quota is exhausted in 10 days, and pushes are rejected.Method:CI settingsGIT_LFS_SKIP_SMUDGE=1, only execute jobs that require resourcesgit lfs pull --include;cache.git/lfs/objects; Confirm with the business which large files should actually be placed in the product library/object storage.
Common errors and solutions
remote: error: File frontend/web/assets/demo.mp4 is 120.00 MB; this exceeds GitHub's file size limit of 100.00 MB (GH001)
Reason:Large files inhistoryMedium (onlygit rmor onlylfs tracknot enough).
git lfs migrate info --everything git lfs migrate import --include="*.mp4" --include-ref=refs/heads/main # Only rewrite branch history that has not been pushed yet
Encountered 1 file(s) that should have been pointers, but weren't
Reason:.gitattributesLFS was required, but someone committed the original file on a machine without LFS installed.
git lfs install git add --renormalize . && git commit -m "fix: convert files to LFS pointers"
The .psd in the workspace opens with a few lines of text (version https://git-lfs.github.com/spec/v1…)
Reason:LFS is not installed,GIT_LFS_SKIP_SMUDGE=1, or download failed (authentication/quota).
git lfs env | head -5 git lfs pull
batch response: This repository is over its data quota.
Reason:LFS storage or bandwidth quota exhausted.Fix:Purchase additional quota or wait for cycle reset; reduce CI downloads; move out large files that do not require version management.
warning: filtering not recognized by server, ignoring
Reason:Server is not starteduploadpack.allowFilter(Self-hosted Git server or local bare repository).
git -C /srv/git/platform.git config uploadpack.allowFilter true git -C /srv/git/platform.git config uploadpack.allowAnySHA1InWant true
fatal: could not fetch … from promisor remote
Reason:Some clones require an internet connection, but the network/credentials are not available, or the remote URL has changed.
git config remote.origin.url git fetch origin # Make sure you can connect first git backfill # Complement in batches when connected to the Internet, and can be offline later
1. Clone the repository without blob and check out only the services/api and libs directories.
git clone --filter=blob:none --sparse <url> repo cd repo && git sparse-checkout set services/api libs
2. Convert *.zip in all branch histories to LFS, and then push.
git lfs migrate import --everything --include="*.zip" git push --force --all origin && git push --force --tags origin
CI requires building services/api in a 15 GB monorepo and usinggit describeCalculate version number. How to clone the fastest without errors?
use git clone --filter=tree:0 --no-checkout(Keep the complete commit diagram,describeTags can be found; old trees/blobs are not downloaded) +git sparse-checkout set --cone services/api + git checkout $SHA. If you still need to do an affected test (git diff --name-only base...HEAD), diff requires trees at both ends, which will trigger a small amount of on-demand downloads, which is acceptable; it can also be used insteadblob:none. Don't use--depth=1:describetag not found, merge base missing (lesson 5). For LFS resourcesGIT_LFS_SKIP_SMUDGE=1Avoid downloading.
Verified instructional videos
The above titles and channels have been verified by the YouTube oEmbed interface (2026-11-15).
Official documentation
- git-lfs.com · Git LFS releases(v3.8.1) · git-lfs-migrate
- GitHub: Git LFS billing
- git-scm: partial clone · git-sparse-checkout · git-backfill · scalar
- GitHub Blog: Get up to speed with partial clone and shallow clone
Video storyboard (approximately 90 seconds)
This courseware cannot directly generate videos/MP3s. Storyboards and explanation scripts have been provided, which can be generated by video tools.
Screen: Neatly arranged blue commits, orange trees, and green file blocks on the server on the left; an empty laptop on the right.
Narrator: Normal cloning will move over every version of every file in history.
Screen: No blob clones only fly over blue and orange squares, and the green position is a gray dotted box marked promised.
Narrator: Blob-less cloning takes the commit and directory structure first, the file content is owed first, and the remote becomes the committer.
Screen: sparse-checkout circles services/api, only four green squares fly over during checkout, and the counter changes from 14 to 10.
Narrator: Sparse checkout determines which directories are needed in the workspace. When checking out, Git only downloads these files in batches.
Screen: When accessing the infra file, a block flies in alone; finally the LFS pointer text and scalar icon appear.
Narrator: Get it when needed, hand the big binary to LFS, and a scalar clone will configure it all for you.
Module 6 · Repository maintenance: gc, maintenance, commit-graph
- Explain loose objects, pack,
git gcwithgc --autorelationship. - use
git maintenance startEnable background maintenance and know the tasks and frequency of the incremental strategy. - Explain what commit-graph (including changed-path Bloom filter), multi-pack-index (including bitmap) and reftable speed up respectively, and can check/migrate.
What: Four things that will "mess" in the Git repository
| something | Why is there chaos | Organizing tools | income |
|---|---|---|---|
| loose objects | every timeadd/commitWrite a zlib-compressed separate file | gc、maintenance of loose-objects Task | Reduce the number of files, incremental compression |
| pack file | Each fetch may add a new pack | gc(Full repackaging),incremental-repack, geometry repacking | Open fewer files when looking for objects |
| Commit graph traversal | git log --graph、merge-base、--containsNeed to parse a large number of commit objects | commit-graph | Put the committed parent pointer, root tree, and generation number in a file that can be directly searched, and the traversal will be several times faster;--changed-pathsThe Bloom filter letsgit log -- <path>Skip irrelevant commits |
| References (refs) | Thousands of branch/tag/PR refs, each in one file or packed into packed-refs | pack-refs;reftableReference backend | Reference reading and writing are faster with atomic batch updates |
gc and gc --auto
git gcPack loose objects, merge pack, pack references, expired reflog, delete unreachable and exceed grace period (gc.pruneExpire, default 2 weeks) object, write commit-graph. Many commands will run at the end ofgit gc --auto: Loose objects exceedgc.auto(default 6700) or pack exceedsgc.autoPackLimit(default 50) is actually executed. Question: It'sfront deskRun, the last full repacking of a large repository may make yourgit commitStuck for a few minutes.
git maintenance: background, incremental
git maintenance(introduced in 2.29) is a "bigger gc".git maintenance startDo three things: Add the current repository to the global configurationmaintenance.repo; Settingsmaintenance.strategy=incrementalAnd turn off automatic maintenance at the front desk (maintenance.auto=false); register hourly/daily/weekly tasks with the system scheduler (Linux takes precedence over systemd user timers, otherwise cron; macOS launchctl; Windows schtasks).
| Task | Frequency under incremental strategy | function |
|---|---|---|
prefetch | hourly | Get the remote object in the backgroundrefs/prefetch/(not updatedorigin/*), after which the realgit fetchCompleted almost instantly |
commit-graph | hourly | Incrementally write commit-graph and verify it |
loose-objects | every day | Pack loose objects and delete packed ones |
incremental-repack | every day | Use multi-pack-index to merge small packs into packs of appropriate size without full repacking |
gc | Disable | The full gc is too heavy and does not run in the background. |
| Other tasks that can be run independently | — | pack-refs、reflog-expire(New in 2.50) etc. |
multi-pack-index(MIDX)
Each pack has its own.idx;When there are many packs, to find an object, you need to check the idx one by one. MIDX covers multiple packssingle index, can come with reachabilitybitmap, making the server calculate "which objects to send" faster during fetch/clone.incremental-repackand Geometry Repackaging rely on it; it is heavily used by the server side of hosting platforms.
reftable: new reference storage backend
defaultfilesThe backend stores each reference as.git/refs/…a file under (pluspacked-refs)。reftable(First implemented by JGit, merged into Git in 2.45) Exist references and reflog.git/reftable/In the binary table file below:
- The update for multiple citations isatomof (write a new table + update
tables.list)。 - Searching and prefix enumeration are faster and smaller when the number of references is huge; no more "case-insensitive file systems on Windows/macOS"
Feature/Awithfeature/aconflict" issue. - Create:
git init --ref-format=reftable;Migrate existing repository:git refs migrate --ref-format=reftable(2.46+). The repository will be setcore.repositoryformatversion=1withextensions.refStorage=reftable,Older versions of Git and tools that don’t support reftable(Some IDEs, libraries) will not be able to open it - confirm team toolchain before migrating. - Git 3.0 planChange the default reference format of new repositories to reftable (also planned to default SHA-256 and default branch name main); as of 2026-11 this is still the plan, existing repositories will not be automatically migrated.
git gc --aggressive"better" - it is very slow and usually has small gains, and only makes sense after a one-time import. ② "gc will immediately delete the commit I deleted by mistake" - unreachable objects are protected by reflog (default 90/30 days) and prune grace period (2 weeks), which will be retrieved in Lesson 7. ③ "maintenance will touch my origin/main" - prefetch writesrefs/prefetch/, does not change the remote-tracking branch. ④ "reftable is already the default" - still the plan for Git 3.0.Figure 6-1 The location of each maintenance product in the .git directory
Figure 6-2 Comparison between foreground gc and background maintenance
Interaction: maintenance scheduling simulator
Choose a point in time to see which tasks will run under the incremental policy and what files they write. (Rules fromgit help maintenance: Run hourly tasks every hour; run daily tasks at midnight; run weekly tasks at midnight on the first day of each week. )
Core commands
| command | function |
|---|---|
git count-objects -vH | Number of loose objects, number of packs and size |
git gc / git gc --prune=now | Fully organize/delete unreachable objects immediately (danger: giving up the opportunity to retrieve them) |
git maintenance start / stop | Register and schedule background maintenance/cancel scheduling |
git maintenance register / unregister | Join/move out onlymaintenance.repolist |
git maintenance run --task=<t> | Manually run a task (commit-graph, prefetch, loose-objects, incremental-repack, pack-refs, gc...) |
git commit-graph write --reachable --changed-paths | Write commit graph (including path Bloom filter);verify Verify |
git multi-pack-index write --bitmap | Write MIDX and bitmap;verify Verify |
git rev-parse --show-ref-format | Current reference backend (files/reftable) |
git refs migrate --ref-format=reftable [--dry-run] | Migrate reference backend (2.46+) |
git init --ref-format=reftable | Create a new reftable repository;init.defaultRefFormat=reftableSet as personal default |
gc and commit graph, MIDX (actual running results)
cd ~/git-lab/p6/work && git clone -q ~/git-lab/p6/remotes/platform.git maint && cd maint for i in $(seq 1 30); do echo $i >> services/api/n.txt; git add -A; git commit -qm "chore: n $i"; done for i in $(seq 1 50); do git tag t$i HEAD~$((i % 30)); done git count-objects -v | head -4 git gc git count-objects -v | head -5 git commit-graph write --reachable --changed-paths && git commit-graph verify && echo verify-ok git multi-pack-index write --bitmap && ls .git/objects/pack
count: 193 size: 7836 in-pack: 0 packs: 0 count: 0 size: 0 in-pack: 193 packs: 1 size-pack: 7833 verify-ok multi-pack-index multi-pack-index-857366cc74ba1642b086b295cf88aeb593c32391.bitmap pack-b97147cdd0f9299cff85b40e785cad27fb5fad40.idx pack-b97147cdd0f9299cff85b40e785cad27fb5fad40.pack pack-b97147cdd0f9299cff85b40e785cad27fb5fad40.rev
Local path cloning copies objects through hard links, so there are 193 loose objects at the beginning; after gc all go into 1 pack.
Enable background maintenance
git maintenance start # Current repository git config --global --get-all maintenance.repo git config --get maintenance.strategy # incremental systemctl --user list-timers 'git-maintenance@*' # Linux (systemd) # macOS: launchctl list | grep git; Windows: schtasks /query /tn "Git Maintenance (hourly)" git maintenance run --task=prefetch && git for-each-ref refs/prefetch | head -3
/home/azureuser/git-lab/p6/work/maint incremental NEXT LEFT LAST PASSED UNIT ACTIVATES Sun 2026-11-15 19:00:00 EST 41min - - git-maintenance@hourly.timer git-maintenance@hourly.service Mon 2026-11-16 00:00:00 EST 5h 41min - - git-maintenance@daily.timer git-maintenance@daily.service Mon 2026-11-16 00:00:00 EST 5h 41min - - git-maintenance@weekly.timer git-maintenance@weekly.service 3c1f0a2… commit refs/prefetch/remotes/origin/main
Migrate to reftable (actual running results)
git rev-parse --show-ref-format git refs migrate --ref-format=reftable --dry-run git refs migrate --ref-format=reftable git rev-parse --show-ref-format && ls .git/reftable git config core.repositoryformatversion; git config extensions.refstorage git tag | wc -l
files Finished dry-run migration of refs, the result can be found at '.git/ref_migration.a39652' reftable 0x000000000001-0x00000000001f-358d2e94.ref tables.list 1 reftable 51
Before migrating, make sure that no other process is writing this repository (such as background maintenance or IDE). Fallback:git refs migrate --ref-format=files。
Experiment 6: Turn on background maintenance and compare log speed (about 5 minutes)
cd ~/git-lab/p6/work && rm -rf long && git init -q long && cd long git fast-import --quiet <<EOF $(for i in $(seq 1 2000); do echo "commit refs/heads/main"; echo "committer Lab <lab@example.com> $((1700000000+i)) +0000" echo "data <<M"; echo "c$i"; echo "M" echo "M 100644 inline dir$((i%20))/f.txt"; echo "data <<D"; echo "$i"; echo "D"; echo done) EOF git checkout -q main && git count-objects -vH | grep -E "count|packs"
rm -f .git/objects/info/commit-graph; git config core.commitGraph false time git log --oneline -- dir7/f.txt | wc -l time git rev-list --count HEAD
git config core.commitGraph true git commit-graph write --reachable --changed-paths time git log --oneline -- dir7/f.txt | wc -l time git rev-list --count HEAD
When there are 2,000 commits, the difference is milliseconds; on a repository with hundreds of thousands of commits, the difference can reach seconds to minutes. The focus is on the mechanics of observation, not the absolute numbers in this case.
git maintenance start git config --show-origin --get-regexp '^maintenance\.'
git refs migrate --ref-format=reftable && git rev-parse --show-ref-format && git log --oneline -1
cd ~/git-lab/p6/work/long && git maintenance unregister cd ~/git-lab/p6/work/maint 2>/dev/null && git maintenance unregister git maintenance stop # If there are no more repositorys that need maintenance: remove the system timer cd ~/git-lab/p6/work && rm -rf long maint rt
Case 1: fetch is getting slower and slower on a self-hosted Git server
Question:CI fetches hundreds of times per minute, the repository accumulates thousands of small packs, and the server CPU soars.Method:Server-side scheduled operationgit maintenance run --task=incremental-repack --task=commit-graph(orgit repack --geometric=2 -d --write-midx --write-bitmap-index), keep the number of packs growing logarithmically and write the MIDX bitmap.Effect:The object counting phase of fetch is reduced from seconds to milliseconds. Hosting platforms (GitHub, GitLab) do exactly this kind of maintenance on the server side.
Case 2: Windows Developer "Stuck on Commit"
Question:In the big repositorygit commitOccasionally it hangs for 3 minutes, and the task manager displays git gc.Method:Uniform executiongit maintenance start(Turn off foreground auto gc and change to schtasks background task), or usescalar register(Also setting up fsmonitor etc.).Effect:The front desk pause disappears.
Case 3: Tens of thousands of PR citations slow down citation operations
Question:The mirror repository containsrefs/pull/*、refs/merge-requests/*tens of thousands of citations,git for-each-refNegotiation with fetch is slow and occasionally causes case conflicts on macOS.Method:Mirror only synchronizesheads with tags;For the newly created mirror repository--ref-format=reftable, migrate the existing repository after confirming CI tool chain support.Effect:Reference operations are significantly faster and case conflicts disappear.
Frequently asked questions and solutions
Auto packing the repository in background for optimum performance. / warning: There are too many unreachable loose objects; run 'git prune' to remove them.
Reason:A large number of unreachable loose objects (such as frequent rebase, repeated modification of large files).
git count-objects -vH git prune --dry-run | wc -l git gc --prune=now # After confirming that there is no need to retrieve anything
fatal: Unable to create '…/.git/objects/info/commit-graph.lock': File exists.
Reason:Another Git process (backend maintenance, IDE) is writing, or the previous process crashed leaving the lock file.
ps aux | grep -E "git (maintenance|gc|commit-graph)" | grep -v grep rm -f .git/objects/info/commit-graph.lock # After confirming that no process is running
error: could not write config file /etc/systemd/... / failed to start systemd timer
Reason:There is no user-level systemd in WSL or containers.
git maintenance start --scheduler=crontab
fatal: unknown repository extension found: refstorage
Reason:The repository has been migrated to reftable, but the version of Git (or the Git/library built into the tool) is too old.
git --version # Requires 2.45+ git refs migrate --ref-format=files # Migrate back when compatibility with old tools is required
git log -- path is still very slow
git config core.commitGraph git commit-graph verify GIT_TRACE2_PERF=1 git log --oneline -1 -- dir7/f.txt 2>&1 | grep -i bloom
Confirm the writing with--changed-paths;RenameTrack(--follow) cannot fully exploit Bloom filters.
1. Enable background maintenance for the current repository on WSL (without systemd).
git maintenance start --scheduler=crontab
2. Check the reference backend of the current repository and create a new test repository in reftable format.
git rev-parse --show-ref-format git init --ref-format=reftable /tmp/rt-test
The team wants to move all repositories to reftable "in preparation for Git 3.0." How do you evaluate that?
① Git 3.0 is planned tonew repositoryThe default is reftable, existing repositorys will not be forcibly migrated, there is no need to rush; ② List all tools that can directly read and write repositorys: each developer's Git version (≥ 2.45), IDE's built-in Git/library (JGit support; other libraries need to be confirmed), CI agent, backup script; ③ Pilot the repositorys (mirrors, monorepo) that have the most references and benefit the most.--dry-runAfter migration, the rollback command is retained; ④ The server-side repository is managed by the platform and is not needed and cannot be migrated by us; ⑤ Recorded in the architectural decision (ADR).
Verified instructional videos
The above titles and channels have been verified by the YouTube oEmbed interface (2026-11-15). Didn't find anything specifically about reftable orgit maintenanceFor verified videos, please refer to the official documents and the storyboard below.
Official documentation
- git-maintenance
- git-gc
- git-commit-graph · git-multi-pack-index
- git-refs · reftable format
- BreakingChanges (Git 3.0 plan)
Video storyboard (approx. 75 seconds)
This courseware cannot directly generate videos/MP3s. Storyboards and explanation scripts have been provided, which can be generated by video tools.
Screen: There are hundreds of small files scattered in the .git/objects directory. The git commit progress bar suddenly gets stuck and "Auto packing the repository" appears.
Narrator: Automatic gc in the foreground will stop commands when you least want to wait.
Screen: The clock rotates every hour, green small blocks prefetch and commit-graph flash in sequence; loose-objects and incremental-repack appear at midnight.
Narrator: git maintenance start turns maintenance into a small background task.
Picture: a long commit chain, the commit-graph file is like an index card, and the git log arrow jumps directly to the target commit.
Narrator: The commit graph makes history traversal much faster, and the Bloom filter allows log checking by path to skip irrelevant commits.
Screen: Thousands of files in the refs directory are pushed into a reftable table; Subtitles: Git 3.0 plan default.
Narrator: reftable makes reading and writing large numbers of references faster and more atomic. It was the planned default, not the current default.
Module 7 · Repository migration: SVN/TFVC to Git, splitting and merging repositorys
- Choose the right path for SVN vs. TFVC migration:
git svn(with author mapping and standard layout), TFVC import of Azure Repos (up to 180 days old, ≤ 1 GB) or git-tfs, and "tip migration". - use
git filter-repo --subdirectory-filterSplit the subdirectory along with its history into a separate repository and understand its relationship withgit subtree splitdifference. - use
--to-subdirectory-filter+merge --allow-unrelated-historiesMerge multiple repositories and keep traceable history.
The first decision before migration: Do you want history?
| Plan | practice | Advantages | Disadvantages |
|---|---|---|---|
| Tip migration(Only migrate to the latest version) | Export the latest code as the first Git commit; the old system remainsread onlyTo check the history | The fastest and cleanest, it won’t bring in the binaries and bad habits of the old system | The history needs to be checked in the old system;blameOnly until migration day |
| limited history | Only migrate the latest N days/trunk | Keep recent context | Still need to archive the old system |
| full history | git svn/git-tfs/svn-all-fast-export etc. | All history traceable in Git | Slow, requires author mapping, branch/tag/merge semantic conversion is not perfect; large files need to be migrated to LFS at the same time |
Microsoft's official recommendation is worth noting: Because TFVC and Git store history differently,It is recommended not to migrate history(tip migration) and keep TFVC online read-only - this is also the approach adopted by Microsoft when migrating products such as Windows to Git.
SVN → Git
- git svn(Distributed with Git, requires SVN bindings for Perl; Ubuntu package name
git-svn):git svn clone <url> --stdlayout --authors-file=authors.txt --prefix=svn/Convert trunk/branches/tags to a Git branch, and each SVN revision becomes a commit. SVN tags will becomerefs/remotes/svn/tags/*Branch requires the script to be converted into a real Git tag.git-svn-id:The endnote records the original revision number (--no-metadatacan be removed). - Large / non-standard layout: KDE commonly used in the community
svn-all-fast-export(svn2git) With rule files, the speed and handling of complex layouts are better than git svn. - Platform import tool:GitHub Importer no longer supports importing from Subversion, Mercurial, and TFVC starting from 2024-04 (github.com has also stopped SVN client access support on 2024-01-08). The official documentation instead recommends using it first.
git svnWait for the tool to convert locally before pushing; Azure Repos's "Import Repository" supports Git and TFVC sources; GitLab also recommends local conversion first.
TFVC → Azure Repos Git
| path | Applicable | Limitations (Microsoft Learn, version 2026-01) |
|---|---|---|
| Azure Repos “Import repository”(Source type = TFVC) | Small and clean TFVC repository, within the same organization | Import only root ora branch(path$/Project/Branch); historyUp to 180 days(from the latest changeset); import results (with history)≤ 1 GB;Do not configure LFS. A link to TFVC will be included with the first migration commit |
| git-tfs(Third-party open source, not supported by Microsoft) | Requires full history, multiple branches and merge relationships | TFVC's rename/rollback/file-level merge/label cannot be accurately expressed as Git concepts |
| Tip migration (recommended) | any size | Before migration: Remove binaries and build tools (use NuGet/Azure Artifacts instead),.tfignore→.gitignore、.tpattributes→.gitattributes, migrate only one branch, and select a new Git branch strategy (M1) |
Split the repository: git filter-repo
git filter-repo(Elijah Newren, Git official documentation recommends using it insteadfilter-branch) is a single-file Python tool based on fast-export/fast-import streaming rewriting history, which is several orders of magnitude faster than filter-branch and requires by defaultBrand new cloneRun during operation (to prevent misoperation), delete after rewritingoriginRemote (to prevent accidental push).
| Options | Effect |
|---|---|
--subdirectory-filter infra/ | only keepinfra/files and put themPromote to root directory;Commits that do not involve this directory are deleted |
--to-subdirectory-filter services/api/ | Reverse: Move all files in the entire repository toservices/api/Next (used before merging repositories) |
--path infra/ --path docs/infra.md | Only keep these paths (do not change the location); add--invert-pathsIndicates deleting these paths |
--path-rename old/:new/ | Rename path in all history |
--tag-rename '':'myapp-' | Prefix all tags to avoid tag conflicts when merging repositorys |
--analyze | generate.git/filter-repo/analysis/Report: Largest Files, Directories, Extensions (Planning Splits and LFS Migration) |
git subtree split --prefix=infraSubdirectory history can also be exported without additional tools, but it does not rewrite the original repository, is slower for large histories, and cannot handle tags, path renaming and other requirements at the same time; filter-repo is preferred for one-time migration.
Merge repositories and preserve history
- Each source repository is executed in a fresh clone
git filter-repo --to-subdirectory-filter < target directory > --tag-rename '':'< name >-'——So that every commit path in the history is already in the target directory,git log -- services/apiCan be traced back to the original commit. - in the target repository
git remote addandfetch --tags。 git merge --allow-unrelated-histories(History of different root commits refuses to merge by default:fatal: refusing to merge unrelated histories)。- Unify CI, CODEOWNERS (M3) after merging, archive old repository (make read-only and point to new location in README).
git log -- services/apiOnly merge commits can be seen (see the actual running results in the "Command" tab). ③ “After it is demolished, there will be nothing left in the original repository”——--subdirectory-filterJust rewritenew clone;The original monorepo needs to be created separately--path infra/ --invert-pathsAnd force push to really clear it (must do when it comes to compliance). ④ "filter-repo can run silently on a shared repository" - it rewrites all hashes, all collaborators must be re-cloned, and must be announced and frozen.Figure 7-1 Split: History after rewriting --subdirectory-filter
Figure 7-2 Merge: first "move" each repository into a subdirectory, and then merge the irrelevant history
Split/merge historical changes demonstration
Select the operation and gradually observe whether each commit is retained, deleted, or the path is rewritten (the commits and paths are taken from the platform, myapp, and web repositorys in this lesson).
SVN → Git(git svn)
sudo apt install git-svn subversion # Ubuntu; Git for Windows comes with git svn
svn log -q https://svn.example.com/repo | awk -F'|' '/^r/ {gsub(/ /,"",$2); print $2" = "$2" <"$2"@example.com>"}' | sort -u > authors.txt
# Edit authors.txt: jdoe = John Doe <john.doe@example.com>
git svn clone https://svn.example.com/repo --stdlayout --authors-file=authors.txt --prefix=svn/ repo-git
cd repo-git
# Convert svn tags (remote branches) to annotation tags
git for-each-ref --format='%(refname:short)' refs/remotes/svn/tags | while read t; do
git tag -a "${t#svn/tags/}" -m "migrated from SVN" "$t"; done
# Convert svn branches to local branches
git for-each-ref --format='%(refname:short)' refs/remotes/svn | grep -v -E 'svn/(tags/|trunk$)' | while read b; do
git branch "${b#svn/}" "$b"; done
git remote add origin https://github.com/<org>/repo.git
git push origin --all && git push origin --tags
Initialized empty Git repository in /home/azureuser/repo-git/.git/ r1 = 3a5c7e1… (refs/remotes/svn/trunk) A trunk/README r2 = 9b0d2f4… (refs/remotes/svn/trunk) … Checked out HEAD: https://svn.example.com/repo/trunk r1842
Native Git for Windows 2.51 outputgit-svn version 2.51.2.windows.1 (svn 1.14.2), indicating that git svn is still distributed with Git (Git 3.0's BreakingChanges manifest has not removed it either). If you need two-way synchronization during migration, usegit svn rebase/git svn dcommit;After the switch is completed, SVN should be set to read-only.
TFVC → Azure Repos Git
# Method 1 (web page): Repos → Files → Repository drop-down menu → Import repository → Source type = TFVC # Path $/Fabrikam/Main, check Migrate history and select the number of days (≤ 180), fill in the new repository name → Import # Method 2 (tip migration, command line, requires TFVC client tf.exe) tf get /version:T /recursive # Get the latest version in the mapped workspace # Remove binaries and build tools, convert .tfignore → .gitignore, check in TFVC after these cleanups: git init -b main && git add . && git commit -m "Migrate from TFVC \$/Fabrikam/Main at C12345 (history remains in TFVC, read-only)" git remote add origin https://dev.azure.com/<org>/<project>/_git/fabrikam git push -u origin main # Method 3 (full history, third-party git-tfs, not supported by Microsoft) git tfs clone https://dev.azure.com/<org> $/Fabrikam/Main --branches=all
Split: filter-repo (sample output) and subtree split (actual running results)
cd ~/git-lab/p6/work && git clone -q ~/git-lab/p6/remotes/platform.git infra-split && cd infra-split git filter-repo --analyze && head -8 .git/filter-repo/analysis/directories-all-sizes.txt git filter-repo --subdirectory-filter infra/ git log --oneline && ls
Parsed 5 commits New history written in 0.05 seconds; now repacking/cleaning... Repacking your repo and cleaning out old unneeded objects HEAD is now at 1d0e2b7 feat(infra): env variable Completely finished after 0.12 seconds. 1d0e2b7 feat(infra): env variable 7c55a10 chore: initial monorepo layout k8s terraform
# Equivalent approach when filter-repo is not installed (without rewriting the original repository): git subtree split --prefix=infra -b infra-only git log --oneline infra-only; git ls-tree --name-only infra-only
82f60b3b6b58194e69c8182eaca52e98115da92c 82f60b3 feat(infra): env variable bdf4f59 chore: initial monorepo layout k8s terraform
# Push to the new repository and delete the directory in the original monorepo (the original history will also be rewritten when complying with compliance requirements) git push ~/git-lab/p6/remotes/infra-new.git infra-only:main # First git init --bare infra-new.git git rm -r infra && git commit -m "chore: infra moved to infra repo" # Only delete the current version # git filter-repo --path infra/ --invert-paths # Clear the history together (requires forced push and re-cloning of all employees)
Merge repositories and preserve history
cd ~/git-lab/p6/work
for r in myapp:services/api web:frontend/web; do
name=${r%%:*}; dir=${r#*:}
git clone -q ~/git-lab/p6/remotes/$name.git tmp-$name
git -C tmp-$name filter-repo --to-subdirectory-filter "$dir/" --tag-rename "":"$name-"
done
git init -q -b main product && cd product && git commit -q --allow-empty -m "chore: create product monorepo"
for name in myapp web; do
git remote add $name ../tmp-$name && git fetch -q --tags $name
git merge --allow-unrelated-histories --no-edit $name/main
git remote remove $name
done
git log --oneline --graph && git tag && git log --oneline -- services/api
* e41b0c9 (HEAD -> main) Merge remote-tracking branch 'web/main' |\ | * 5f3a2d8 (tag: web-v1.0.0) chore: initial web * b7d19e2 Merge remote-tracking branch 'myapp/main' |\ | * 0c6e5f1 (tag: myapp-v1.0.0) chore: initial myapp * 8a12f03 chore: create product monorepo myapp-v1.0.0 web-v1.0.0 b7d19e2 Merge remote-tracking branch 'myapp/main' 0c6e5f1 chore: initial myapp
Comparison (actual running results):use git subtree add --prefix=services/api ../myapp.git main(without --squash) when merging,git log --oneline -- services/apiOutput onlyfc6e4b3 Add 'services/api/' from commit '1c8efa3…'--original commit1c8efa3The files in are in the root directory and cannot be found according to the path; and the tags of the source repository will not be brought over. No--allow-unrelated-historiesDirect merge will reportfatal: refusing to merge unrelated histories。
Experiment 7: Remove infra and merge myapp with web (about 8 minutes)
cd ~/git-lab/p6/work && rm -rf infra-split && git clone -q ~/git-lab/p6/remotes/platform.git infra-split && cd infra-split git filter-repo --analyze sed -n 1,10p .git/filter-repo/analysis/extensions-all-sizes.txt # You can also see that .psd/.mp4 is an LFS candidate
git filter-repo --subdirectory-filter infra/ git log --oneline; ls; git remote -v # origin has been removed (to prevent accidental push) git init -q --bare ~/git-lab/p6/remotes/infra-new.git git remote add origin ~/git-lab/p6/remotes/infra-new.git && git push -q -u origin main
cd ~/git-lab/p6/work && rm -rf split && git clone -q ~/git-lab/p6/remotes/platform.git split && cd split git subtree split --prefix=infra -b infra-only && git log --oneline infra-only
cd ~/git-lab/p6/work/product git ls-files | cut -d/ -f1-2 | sort -u git log --oneline -- services/api/app.py git tag
cd ~/git-lab/p6/work && rm -rf merged && git init -q -b main merged && cd merged git commit -q --allow-empty -m start git subtree add --prefix=services/api ~/git-lab/p6/remotes/myapp.git main git log --oneline -- services/api # Only merge commits
cd ~/git-lab/p6/work && rm -rf infra-split split product merged tmp-myapp tmp-web rm -rf ~/git-lab/p6/remotes/infra-new.git
Case 1: Migrating SVN repository to GitHub in 2015
Question:40,000 revised, non-standard layouts (/projects/*/trunk), there are installation packages mixed in the repository.Method:① Use the svn-all-fast-export rule file to convert each project into an independent Git repository (and determine the structure of M3 at the same time); ② The author mapping table is generated from LDAP; ③ After conversiongit lfs migrate importProcess the installation package, or delete it directly and use the product library; ④ Two walkthroughs + one official switch: Friday 18:00 SVN read-only → incremental conversion → push → switch CI on Monday.Effect:History is retained, and the repository size is reduced from 60 GB to 3 GB.Limitations:SVN's svn:externals needs to be manually changed to a submodule or package dependency (M4).
Case 2: Migrate TFVC to Azure Repos Git, select tip migration
Question:There are more than a dozen branches, file-level merging and a large number of labels in TFVC.Method:Migrate only the latest version of the Main branch as recommended by Microsoft; check in the clean changeset of "Remove binary, use NuGet instead, .tfignore → .gitignore" in TFVC before migration; keep the TFVC project read-only for two years for inspection history; adopt the GitHub Flow + branching strategy for the new repository (Lesson 3).Effect:The switchover was completed within a week; team training took more time than tool migration.
Case 3: Split open source components from private monorepo and release them
Question:to makelibs/sdkOpen source, but this directory briefly contained internal keys in the monorepo's history.Method:filter-repo --subdirectory-filter libs/sdk/later, use--replace-textor--path ... --invert-pathsClear sensitive files and use a confidential scanning tool to fully scan the new history (Lesson 7); push to the public repository after confirmation.Effect:Public repositories preserve useful history without revealing internal information.
Common errors and solutions
Aborting: Refusing to destructively overwrite repo history since this does not look like a fresh clone.
Reason:Protection of filter-repo: The repository has unpushed changes, more than one reflog, etc. It is not like a new clone.
git clone --no-local <url> fresh && cd fresh # Recommended: Re-clone git filter-repo --force … # Use after confirmation
fatal: refusing to merge unrelated histories
Reason:The two repositories have no common ancestor. This is expected when merging repositories.
git merge --allow-unrelated-histories --no-edit other/main
Author: (no author) <(no author)@…> / git svn: Author: jdoe not defined in authors.txt file
Reason:The author mapping file is missing an entry.
svn log -q <url> | awk -F'|' '/^r/ {gsub(/ /,"",$2); print $2}' | sort -u | while read u; do grep -q "^$u " authors.txt || echo "Missing: $u"; done
Use after filling upgit svn fetchContinue (will resume where you left off).
TFVC import failed: Repository or history exceeds 1 GB / requires more than 180 days of history
Reason:Limitations of the Azure Repos import tool.Fix:Reduce the number of days of history, clean the binary first, and import only one branch; or use tip migration / git-tfs instead.
Tag conflict after merging the repository: ! [rejected] v1.0.0 -> v1.0.0 (would clobber existing tag)
Reason:Both source repositories have tags with the same name.
git filter-repo --tag-rename '':'myapp-' # Change the name in the source clone and then fetch
1. Put theservices/payments/Split together with the history into the root directory of a separate repository.
git clone --no-local <monorepo-url> payments && cd payments git filter-repo --subdirectory-filter services/payments/ git remote add origin <new-url> && git push -u origin --all && git push origin --tags
2. Before merging, move the entire history of a repository totools/cli/down and add all tagscli-prefix.
git filter-repo --to-subdirectory-filter tools/cli/ --tag-rename '':'cli-'
A 300 person department was migrating from TFVC (8 years old, 30 GB, lots of binaries) to Azure Repos Git, and management asked for "full history to be preserved". What do you suggest?
Let’s explain the facts first: Azure Repos import only supports 180 days and ≤ 1 GB; complete history requires third-party tools such as git-tfs, and TFVC’s file-level merge, rename, and label cannot be accurately mapped. Microsoft officially recommends tip migration and keeping TFVC read-only. Recommendations: ① TFVC read-only retention (to meet the real requirement of "history can be checked"); ② When doing tip migration in Git (or the last 180 days), clean the binary first (NuGet/Azure Artifacts, LFS if necessary); ③ Redesign the repository boundary (M3) and branch strategy (M1) according to the product; ④ If a product really needs the history in Git, use git-tfs alone Pilot and verify; ⑤ Develop a switching plan: drills, freezing windows, CI switching, and training.
Verified instructional videos
The above titles and channels have been verified by the YouTube oEmbed interface (2026-11-15). No verified TFVC → Git migration video found, please refer to Microsoft Learn documentation.
Official documentation
- Microsoft Learn: Import and migrate repositories from TFVC to Git
- Microsoft Learn: Migrate from centralized version control to Git
- git-svn · Pro Git 9.2 Migrating to Git
- newren/git-filter-repo · filter-repo manual
- GitHub Changelog 2024-04-17: GitHub Importer update · 2024-01-08 Subversion has been sunset
Video storyboard (about 80 seconds)
This courseware cannot directly generate videos/MP3s. Storyboards and explanation scripts have been provided, which can be generated by video tools.
Image: An old server that says SVN / TFVC, next to a question mark: "Do you want history?".
Narrator: The first question in migration is not what tool to use, but whether to use history.
Screen: TFVC import dialog box, highlighting 180 days and 1 GB; the old server next to it has a "read-only" sign.
Narrator: Azure Repos's TFVC imports a maximum of 180 days of history. Microsoft recommends migrating only the latest version and keeping the old system read-only.
Screen: The commit chain of monorepo passes through filter-repo, leaving only two commits related to infra, and the files jump to the root directory.
Narrator: Split using subdirectory filter, irrelevant commits are removed, and all hashes are changed.
Screen: The two repositorys are first "moved" into subdirectories and then merged into one repository; git log can be traced back to the original commit according to the path.
Narrator: When merging repositorys, first rewrite the path, and then merge the irrelevant history. It only makes sense to check the history according to the path.
Module 8 · Comprehensive Architecture Review
- Use an 8-dimensional checklist to review an organization's Git architecture and provide prioritized recommendations for rectification.
- Identify typical failure patterns (long-lived branches, leaky rollbacks, submodule drift, LFS quotas, monorepo CI explosions, post-migration double-writes) and their signals.
- Use troubleshooting trees to locate branch strategy and repository architecture issues.
Architecture Review Checklist (8 Dimensions)
| # | Dimensions | Questions to ask | Evidence you can collect with Git | Common rectifications |
|---|---|---|---|---|
| 1 | Branch strategy (M1) | How many long-term branches are there? How long do branches live on average? Is main ready for deployment? | git for-each-ref --sort=-committerdate refs/remotes, branch health script | Delete develop, short branch + feature switch + merge queue |
| 2 | Release and rollback (M2) | Is the fix upstream first? How many versions are supported? Is there any leakage backshift? | git cherry、-xEndnote audit script,git describe | Move back bots, support policy documents, EOL tags |
| 3 | Repository boundary (M3) | Are boundaries equal to permission boundaries? Frequency of changes across repositorys? | Number of PRs associated across repositorys,git log --name-onlyChange popularity | Merge strongly coupled repositorys and separate directories that need to be isolated |
| 4 | Code Reuse (M4) | Where is submodule/subtree used? Is there a better way to manage packages? | git submodule status --recursive、.gitmodules | Those that can be packaged are changed to package dependencies; submodules are fixed to tags; relative URLs |
| 5 | Large files and large repositorys (M5) | Are there large files in history? LFS quota? How long does it take for developer cloning? | git count-objects -vH、filter-repo --analyze、lfs migrate info | LFS migration, partial clone + sparse checkout, scalar |
| 6 | Maintenance and Performance (M6) | Do you want to enable background maintenance? Number of citations? | git for-each-ref | wc -l、git config --get-all maintenance.repo | maintenance start, commit-graph, clean PR reference image |
| 7 | Migration and Archiving (M7) | Is the old system read-only? Are you still "double writing"? | The last commit time of the old repository | Freeze old system, point README to new location, archive |
| 8 | Governance and Compliance (Lessons 3–5) | Is main/release protected? CODEOWNERS coverage? Signatures and required checks? | Rule Set/Branch Policy Export, CODEOWNERS Not Covered Path | Rule sets, protected labels, deployment approvals |
Typical failure modes
| failure mode | early signal | root cause | Countermeasures |
|---|---|---|---|
| merge hell | Branch hundreds of commits behind main; "merge day" | long term feature branch | Main development, Branch by Abstraction |
| bug resurrection | The same defect appears again in the new version | Fix only in release / only in main (GitFlow leaks in develop) | upstream first + move back audit |
| Distributed monolith | One requirement requires changing 5 repositorys and releasing them in order. | Repositories split by teams instead of couplings | Merge strongly coupled repositories or stable API contracts |
| Submodule drift | modified: lib (new commits)Committed by mistake; CI reported not our ref | missing submodule.recurseCheck with push | Team configuration baseline, CI verification |
| quota exhausted | LFS push failed mid-month | CI fully downloads LFS objects | SKIP_SMUDGE, cache, selective pull |
| monorepo CI explosion | PR build time increases linearly with repository size | No affected detection | Path Mapping → Build Graph Tool + Remote Cache |
| Double write after migration | There are still people committing under the old system | No freezing or archiving | Read-only, CI only connects to new repositorys, announcements |
| Compliance quarantine failed | Audit found that sensitive code is readable by everyone | Mistakenly believe that sparse checkout/directory permissions can be isolated | Destroy repository + clear original repository history |
docs/adr/), including "Why not choose another option?"Figure 8-1 Example organization’s current situation and target architecture
Interactive: Architecture Review Scorecard
Check the boxes that apply to your team (or example organization). Each dimension is given a score and "the most worthwhile thing to do next." The results are only saved on this page and will be cleared after refreshing.
Orders to collect evidence during review
#!/usr/bin/env bash
# Run in a fresh clone of the repository to output the ground truth required for the architecture review
set -uo pipefail
echo "## Basic information"; git --version; git rev-parse --show-ref-format 2>/dev/null
echo "Default branch: $(git symbolic-ref --short refs/remotes/origin/HEAD 2>/dev/null)"
git count-objects -vH | grep -E 'size-pack|packs'
echo "## number of references"; git for-each-ref | awk '{print $3}' | cut -d/ -f1-2 | sort | uniq -c
echo "## Long-term/stale branch (by last commit time)"
git for-each-ref --sort=committerdate --format='%(committerdate:short) %(refname:short)' refs/remotes/origin | grep -v ' origin$' | head -10
echo "## Behind/leading relative to the default branch"
base=$(git symbolic-ref --short refs/remotes/origin/HEAD 2>/dev/null || echo origin/main)
for b in $(git for-each-ref --format='%(refname:short)' refs/remotes/origin | grep -v -E "^origin$|HEAD|^$base$"); do
echo "$(git rev-list --left-right --count $base...$b | tr '\t' '/') $b"; done | sort -t/ -k1 -rn | head -10
echo "## submodule"; git config -f .gitmodules --get-regexp '^submodule\..*\.url' 2>/dev/null || echo "None"
echo "## LFS"; grep -h 'filter=lfs' .gitattributes 2>/dev/null || echo "LFS not used"
echo "## The 5 largest blobs in history"
git rev-list --objects --all | git cat-file --batch-check='%(objecttype) %(objectsize) %(rest)' | awk '$1=="blob"' | sort -k2 -rn | head -5
echo "## Popularity of directory changes (last 180 days)"
git log --since=180.days --format= --name-only | grep -v '^$' | cut -d/ -f1-2 | sort | uniq -c | sort -rn | head -8
echo "## CODEOWNERS"; for f in .github/CODEOWNERS CODEOWNERS docs/CODEOWNERS; do [ -f "$f" ] && { echo "$f"; cat "$f"; }; done
echo "## Maintenance"; git config --get maintenance.strategy || echo "Background maintenance is not enabled"
cd ~/git-lab/p6/work && git clone -q --no-local ~/git-lab/p6/remotes/platform.git review && cd review bash ../repo-review.sh
## Basic information
git version 2.51.2
files
Default branch: origin/main
packs: 1
size-pack: 7.64 MiB
## Number of references
1 refs/heads
3 refs/remotes
1 refs/tags
## Long term/stale branches (by last commit time)
2026-11-15 origin/release/1.0
2026-11-15 origin/main
## Lagging/leading relative to the default branch
2/0 origin/release/1.0
## Submodule
None
## LFS
LFS not used
## The 5 largest blobs in history
blob 3000000 frontend/web/assets/hero.psd
blob 3000000 frontend/web/assets/hero.psd
blob 2000000 frontend/web/assets/demo.mp4
blob 329 services/api/app.py
blob 276 services/api/app.py
## Popularity of directory changes (last 180 days)
5 frontend/web
4 services/api
2 infra/terraform
1 infra/k8s
1README.md
1.github/CODEOWNERS
## CODEOWNERS
.github/CODEOWNERS
/services/api/ @org/backend
/frontend/ @org/frontend
/infra/ @org/platform
## Maintenance
Background maintenance is not enabled
--no-localHaving the local clone also take the normal transport protocol (getting a pack instead of a hard-linked loose object) results in a result much closer to cloning from the platform.
The "largest blob in history" in the output tells two things at the same time:hero.psdThere are two 3 MB versions both in history (onlylfs trackcannot be resolved), and candidate types for LFS migration.
Lab 8: Conduct a 15-minute review of a sample organization
repo-review.shsave to~/git-lab/p6/work/, run in new clones of platform, myapp, web, and infra respectively, and the results are saved asreview-*.txt。
cd ~/git-lab/p6/work for r in platform myapp web infra; do rm -rf rv-$r; git clone -q ~/git-lab/p6/remotes/$r.git rv-$r; (cd rv-$r && bash ../repo-review.sh > ../review-$r.txt 2>&1); done grep -A3 "biggest" review-platform.txt
Discovery 1 (P0): The production configuration in infra/ is readable and writable by all engineers Current status: platform monorepo's infra/ contains infra/k8s/deploy.yaml and other production lists; CODEOWNERS only requires review Risks: Unauthorized changes, failure to pass compliance audits; sparse checkout cannot be isolated Suggestion: filter-repo --subdirectory-filter infra/ Detach infra-live, the platform team has exclusive write permission, and production needs approval Cost: 0.5 days migration + CI adjustment; re-cloning of all employees (if the original history is cleared)
mkdir -p ~/git-lab/p6/work/rv-platform/docs/adr && cat > ~/git-lab/p6/work/rv-platform/docs/adr/0001-branching-strategy.md <<'EOF'
# ADR-0001 branch strategy: trunk development + release branch
Status: Accepted (2026-11-15)
Background: develop and main under GitFlow have been bifurcated for a long time and were hot-fixed three times.
Decision: delete develop; main protected, merge queue; unfinished features must be behind feature switches;
Release release/x.y from main, repair upstream first + cherry-pick -x; support the latest 2 minor versions + 1 LTS.
Alternatives: Keep GitFlow (rejected: merge costs and risk of missing merges); pure GitHub Flow without release branch (rejected: need to support LTS).
Consequences: Feature switch service and rollback audit scripts are required; CI must be stable within 10 minutes.
EOFcd ~/git-lab/p6/work && rm -rf rv-* review-*.txt review
Case 1: Post-merger repository integration review
Question:After the company is merged, GitHub (the main company) and Azure Repos + TFVC (the acquired party) exist at the same time.Review conclusion:P0 unifies identity and permissions; P1 TFVC does tip migration to Git and keeps it read-only; P1 unifies the branch strategies on both sides into trunk development + release; P2 merges the acquired party's 12 strongly coupled repositorys into 2 monorepo; P3 evaluates reftable (no urgency).Effect:The integration was completed within half a year without a single "big bang" switch.
Case 2: Review discovers that a “healthy-looking” repository actually has 4 GB of history
Question:The workspace is only 200 MB, but the clone takes 40 minutes.repo-review.shThe "Maximum blob" shows that there are multiple 500 MB database backups in history.Method:Use filter-repo to clear and force push according to the process of Lesson 7, and the platform side requests to clear the cache; at the same time,*.bakJoin.gitignorewith pre-receive/push rules (GitLab push rules, GitHub push rulesets).Effect:Repository dropped to 150 MB.
Case 3: Review prevented an unnecessary monorepo migration
Question:The team wanted to merge all 80 repositories "like Google".Review data:There are less than 2 cross-repository PRs per month, the team hardly shares code, and the release rhythm of each product is completely different.Conclusion:Maintain polyrepo and change to unify CI templates, shared library packages, and unify branch strategies and rule sets.Lessons:Architectural decisions should be based on evidence (hotness of changes, frequency of changes across repositories), not trends.
Interactive troubleshooting tree: branching strategy and repository architecture issues
Start with symptoms and make step-by-step selections, and finally provide diagnostic commands and repair directions.
1. List the 10 largest files (including paths) in history for evaluation of LFS migration.
git rev-list --objects --all | git cat-file --batch-check='%(objecttype) %(objectsize) %(rest)' | awk '$1=="blob"' | sort -k2 -rn | head -10
2. Find the remote branch that has not had any commits in the last 90 days.
git for-each-ref --format='%(committerdate:unix) %(refname:short)' refs/remotes/origin | awk -v t=$(date -d '90 days ago' +%s) '$1 < t {print $2}'You've been asked to review the Git architecture of a 200-person engineering organization over the course of a week. Give your review plan.
Day 1: Interview (release frequency, supported versions, compliance requirements, pain points) and export platform settings (rule sets/branch strategies/CODEOWNERS). Day 2–3: Run against Top 20 repositoriesrepo-review.sh, statistics on branch survival, missing rollbacks, repository volume and large files, sub-modules, cross-repository change frequency, and CI duration. Day 4: Summarize the findings according to the 8-dimensional list, mark P0–P3, and give the costs and benefits; P0 is usually permissions/compliance and “bug resurrection” type issues. Day 5: Review meeting + ADR draft (branch strategy, repository boundaries, large files, migration plan), agree on a 30/60/90-day rectification rhythm and measurement indicators (deployment frequency, change lead time, cloning time, CI duration).
Verified instructional videos
The above titles and channels have been verified by the YouTube oEmbed interface (2026-11-15).
References
- Patterns for Managing Source Code Branches
- DORA: Trunk-based development
- Architecture Decision Records(adr.github.io)
- Microsoft Learn: Adopt a Git branching strategy
Video storyboard (about 70 seconds)
This courseware cannot directly generate videos/MP3s. Storyboards and explanation scripts have been provided, which can be generated by video tools.
Screen: An octagonal radar chart, with eight dimensions lighting up one by one: branch, release, boundary, reuse, large file, maintenance, migration, and governance.
Narrator: A Git architecture review, looking at eight dimensions.
Screen: The terminal runs repo-review.sh, and the largest blob, number of backward commits, and stale branches are highlighted.
Narrator: Collect evidence first, then draw conclusions.
Screen: The red status card on the left is flipped one by one into the green target card on the right, and finally lands on the ADR document.
Narrator: For each finding, write down the status, risks, recommendations, costs and priorities, and record the decision in ADR.
Command cheat sheet
git switch -c feat/x origin/main # Trunk development: short branch git pull --rebase origin main git merge --no-ff feature/x # GitFlow: Preserve feature boundaries git switch -c release/1.4 v1.4.0-rc1 # Switch to the release branch from the verified commit git rev-list --left-right --count origin/main...origin/feat/x # Branch behind/leading git for-each-ref --sort=committerdate --format='%(committerdate:short) %(refname:short)' refs/remotes
git cherry-pick -x <sha> # Move back and record the source git cherry-pick -x -m 1 <merge-sha> # Move back the entire PR git cherry-pick --continue | --skip | --abort git cherry -v release/1.0 main # + not moved back (by patch-id) git log --cherry-pick --right-only --no-merges release/1.0...main git log release/1.0 --grep "cherry picked from" --oneline git tag -a v1.0.1 -m "release 1.0.1"
git diff --name-only origin/main...HEAD # Affected files git diff --dirstat=files,0 origin/main...HEAD git shortlog -sn --since=1.year -- services/api git log --since=90.days --format= --name-only | cut -d/ -f1-2 | sort | uniq -c | sort -rn
git submodule add ../infra.git infra git clone --recurse-submodules <url> git submodule update --init --recursive git submodule update --remote infra && git commit -am "bump infra" git submodule status --recursive git config submodule.recurse true; git config push.recurseSubmodules check git submodule deinit -f infra && git rm -f infra git subtree add --prefix=infra ../infra.git main --squash git subtree pull --prefix=infra ../infra.git main --squash git subtree split --prefix=infra -b infra-only
git lfs install git lfs track "*.psd" --lockable # Write .gitattributes git lfs ls-files; git lfs status git lfs migrate info --everything --top=10 git lfs migrate import --everything --include="*.psd,*.mp4" git lfs migrate import --no-rewrite big.bin git lfs lock f.psd; git lfs locks; git lfs unlock f.psd GIT_LFS_SKIP_SMUDGE=1 git clone <url>; git lfs pull --include="assets/**"
git clone --filter=blob:none <url> # Developer git clone --filter=tree:0 <url> # One-time CI git clone --filter=blob:none --sparse <url> git sparse-checkout set --cone services/api libs git sparse-checkout add infra; git sparse-checkout list; git sparse-checkout disable git sparse-checkout init --cone --sparse-index git rev-list --objects --all --missing=print | grep -c '^?' git backfill [--sparse] # 2.49+ scalar clone <url> big; scalar register; scalar reconfigure --all
git count-objects -vH git maintenance start [--scheduler=crontab] ; git maintenance stop git maintenance run --task=commit-graph --task=prefetch git commit-graph write --reachable --changed-paths; git commit-graph verify git multi-pack-index write --bitmap git rev-parse --show-ref-format git refs migrate --ref-format=reftable [--dry-run] git init --ref-format=reftable
git svn clone <url> --stdlayout --authors-file=authors.txt --prefix=svn/ git filter-repo --analyze git filter-repo --subdirectory-filter infra/ git filter-repo --to-subdirectory-filter services/api/ --tag-rename '':'myapp-' git filter-repo --path secrets/ --invert-paths git merge --allow-unrelated-histories --no-edit other/main git push origin --all && git push origin --tags
decision shorthand
| question | First choice | When to choose another |
|---|---|---|
| branching strategy | Trunk development + feature switch (+ release branch) | Multi-version coexistence, external release window → release branch / GitLab Flow / release train; GitFlow only when CI is weak and there is a clear version |
| Repair flow | upstream first:main → cherry-pick -x | Urgently revised on release → must be moved to main immediately |
| Repository boundaries | Divided by authority and coupling | Need isolation → independent repository; strong coupling → merge |
| code reuse | Package manager | Precisely fixed source code/independent licensing → submodule; synchronized occasionally, user-insensitive → subtree |
| large files | LFS (or not into Git) | Just current version →--no-rewrite |
| Big History / Big Workspace | blob:none+ cone sparse checkout (or scalar) | One-time CI →tree:0;Build only without history → shallow clone |
| Migration history | Tip migration + old system read-only | History required → git svn/svn-all-fast-export/git-tfs |
Comprehensive experiment + final exam
platformIn monorepo, using GitFlow, the design draft is committed directly, and everyone can change the production configuration. Objectives: ① Write the ADR of branch strategy and repository structure; ②infra/together with history, broken down into restrictedinfra-liverepository and remove it from the product repository history; ③ Migrate the design draft to LFS; ④ Establish a release branch and complete an upstream-first move back; ⑤ Provide developers with a "quick start" method of partial cloning + sparse checkout; ⑥ Start maintenance and verification.bash setup-p6.sh git lfs version && git filter-repo --version mkdir -p ~/git-lab/p6/final && cd ~/git-lab/p6/final
product monorepo:services + frontend;infra-live: Writable only by the platform team). You can refer to the ADR template in the M8 experiment and save it as~/git-lab/p6/final/adr-0001.md、adr-0002.md, which will be committed to the new repository later.git clone -q --no-local ~/git-lab/p6/remotes/platform.git analyze && cd analyze git filter-repo --analyze head -12 .git/filter-repo/analysis/extensions-all-sizes.txt head -12 .git/filter-repo/analysis/directories-all-sizes.txt cd .. && rm -rf analyze
git clone -q --no-local ~/git-lab/p6/remotes/platform.git infra-live && cd infra-live git filter-repo --subdirectory-filter infra/ git log --oneline && ls # Expected: 2 commits, k8s/terraform/ git init -q --bare ~/git-lab/p6/remotes/infra-live.git git remote add origin ~/git-lab/p6/remotes/infra-live.git && git push -q -u origin --all && git push -q origin --tags cd..
git clone -q --no-local ~/git-lab/p6/remotes/platform.git product && cd product git filter-repo --path infra/ --invert-paths # There is no more infra in the product history git lfs migrate import --everything --include="*.psd,*.mp4" cat .gitattributes git cat-file -p HEAD:frontend/web/assets/hero.psd # Pointer file git log --all --oneline -- infra | wc -l # expected 0 sed -i '/@org\/platform/d' .github/CODEOWNERS cp ../adr-000*.md . 2>/dev/null; mkdir -p docs/adr && mv adr-000*.md docs/adr/ 2>/dev/null git add -A && git commit -qm "docs: ADRs for branching and repo structure; drop infra owners" git reflog expire --expire=now --all && git gc -q --prune=now git count-objects -vH | grep size-pack # Git object library is very small, large files are in .git/lfs git init -q --bare ~/git-lab/p6/remotes/product.git git remote add origin "file://$HOME/git-lab/p6/remotes/product.git" # Use file:// URL, see instructions below git push -q -u origin --all && git push -q origin --tags
The local bare repository does not have an LFS server. written remotelyfile://URL, git-lfs will use the built-in standalone file transmission method to directly store the LFS object into the bare repository.lfs/objects/, suitable for drills. If your git-lfs version does not support it and reports an error, you can use it firstgit push --no-verifySkip the LFS upload and only verify the Git part. Real projects can be pushed directly to GitHub/GitLab/Azure Repos.
git switch -c release/1.0 v1.0.0 # The label has been rewritten with history
git switch main
sed -i 's|return "ok\\n"|return {"status": "ok"}|' services/api/app.py
git commit -qam "fix(api): healthz returns JSON for probes"
git switch release/1.0 && git cherry-pick -x main && git tag -a v1.0.1 -m "release 1.0.1"
git push -q origin main release/1.0 v1.0.1
git log release/1.0 --grep "cherry picked from" --onelinecd ~/git-lab/p6/final git -C ~/git-lab/p6/remotes/product.git config uploadpack.allowFilter true git clone -q --filter=blob:none --sparse "file://$HOME/git-lab/p6/remotes/product.git" dev-backend cd dev-backend && git sparse-checkout set services/api && ls git rev-list --objects --all --missing=print | grep -c '^?' du -sh .git
git maintenance register && git config --get maintenance.strategy bash ~/git-lab/p6/work/repo-review.sh | sed -n '/biggest/,/directory changes/p' git maintenance unregister
cd ~ && rm -rf ~/git-lab/p6/final ~/git-lab/p6/remotes/product.git ~/git-lab/p6/remotes/infra-live.git ~/git-lab/p6/lfs-store git maintenance stop 2>/dev/null || true # If maintenance start has been executed in this lesson
Open-ended self-assessment (answer yourself first, then expand for reference answers)
1.Why is it said that "the core of branch strategy is to control integration delay"? Give an example each using trunk development and GitFlow.
The longer the code is on the branch without being integrated with others, the later conflicts and integration flaws will be exposed. Functions under development in the trunk enter main on the same day (the switch is hidden), and the integration delay is measured in hours; functions in GitFlow are advanced in develop and enter main only when released. Hot fixes need to be combined in two places, and the integration delay is measured in weeks, and it is easy to miss the connection.
2.Why can’t rollback auditing rely solely ongit cherry?
git cherryCompare by patch-id; if the diff changes of commits that have resolved conflicts during the move back have different patch-ids, they will be falsely reported as not being moved back. should be-xThe original hash in the endnote is valid, combined with the PR tag or ticket.
3.In a monorepo, is it possible to only have the frontend directory visible to contractors?
It cannot be implemented using Git itself: the Git protocol does not have directory-level read permissions, sparse checkouts and partial clones only require less downloads, and objects can still be fetched. The parts visible to the contractor need to be placed in a separate repository or connected through components/packages.
4.What are the biggest pitfalls of submodules and subtrees?
Submodule: Forgetting to init after cloning, the parent repository pointer points to an unpushed commit, and the submodule is not updated after pull, causing the old pointer to be mistakenly committed. Subtree: Upstream synchronization requires manual pull and split, which is slow.--squashInconsistency will cause pulls to fail; content is fully visible to readers of the parent repository.
5. --filter=blob:none、--filter=tree:0、--depth=1What scenarios are they suitable for?
blob:none: In daily life of developers, keep complete commits and trees, and retrieve files on demand. tree:0: One-time CI, requires commit history (describe) but only builds the latest code. depth=1: A scenario that is only built once and does not require any history; will destroy merge-base/describe.
6.What are Microsoft's recommendations for TFVC migration? What are the limitations of the Azure Repos import tool?
It is recommended that tip migration, no history migration, and TFVC keep read-only history. The import tool only migrates the root or one branch, up to 180 days of history, the result is ≤ 1 GB, and does not configure LFS; more complex requirements can use third-party git-tfs (not supported by Microsoft).
Final exam (12 questions, covering all modules)
Sources and imprints
| Topic | Verify conclusion | Source (Accessed on 2026-11-15) |
|---|---|---|
| Git version and feature introduction version | 2.56(2026-09):repack --drop-filtered, gc/maintenance object library organization and pluggability, geometric repacking threshold adjustment, reftable performance optimization; 2.50: maintenance adds reflog expired tasks, scalar can not enable scheduling maintenance; 2.49:git backfill、refs migrateReflog can not be migrated; 2.45: reftable backend (--ref-format=reftable); 2.38: scalar is merged into the core and fsmonitor is enabled; 2.37: non-cone sparse checkout is deprecated; 2.29: introducedgit maintenance | git/git Documentation/RelNotes(2.29、2.30、2.37、2.38、2.45、2.49、2.50、2.56) |
| Git 3.0 plan | Planned: New repository default SHA-256, default reftable, default branch main, Rust becomes required,safe.bareRepositoryDefault explicit; removes grafts,whatchangedWait. No release date yet; the listing makes no mention of removing git-svn | git-scm.com/docs/BreakingChanges |
| git maintenance | Incremental strategy: commit-graph and prefetch every hour, loose-objects and incremental-repack every day, gc disabled; register settingsmaintenance.auto=false;Scheduler crontab/systemd-timer/launchctl/schtasks | git-maintenance(and Git for Windows 2.51 local documentation) |
| scalar | By default, clone only takes commit and tree, initial sparse checkout (only top-level files), background maintenance, and recommended configuration (gc.auto=0、index.version=4、fetch.unpackLimit=1etc.);--full-clone、--no-src;Subcommand list/register/unregister/run/reconfigure/diagnose/delete | git-scm.com/docs/scalar |
| Git LFS | The latest v3.8.1 (2026-10-22), v3.8.0 (08-28) | git-lfs releases |
| GitHub LFS quotas | Free/Pro/Organization: 10 GiB storage + 10 GiB bandwidth; Team and Enterprise Cloud: 250 GiB + 250 GiB; more are billed per GiB | GitHub Docs: Git LFS billing |
| TFVC → Git | Only migrate the root or one branch; up to 180 days of history; ≤ 1 GB; do not configure LFS; it is recommended not to migrate history (Microsoft's approach to migrating Windows); use git-tfs (third party, not supported) for complex situations | Import and migrate repositories from TFVC to Git(ms.date 2026-01-22) |
| GitHub and SVN | 2024-01-08 github.com stops supporting Subversion; starting from 2024-04-17, GitHub Importer no longer supports Mercurial, SVN, and TFVC import; the documentation recommends using git svn for local conversion | Subversion has been sunset · Updates to GitHub Importer |
| git filter-repo | --subdirectory-filter, --to-subdirectory-filter, --path/--invert-paths, --tag-rename, --analyze; require a fresh clone; remove origin after rewriting | newren/git-filter-repo |
| Partial clone/sparse callout | promisor remote, blob:none / tree:0 / blob:limit; cone mode and sparse index; server needsuploadpack.allowFilter | partial-clone · git-sparse-checkout · GitHub Blog |
| Submodule safe defaults | Starting from 2.38.1 (CVE-2022-39253)protocol.file.allowDefault user, submodule clones local repository reporttransport 'file' not allowed(Actual reproduction of this lesson) | git-config: protocol.allow |
| branching strategy | GitFlow original text and 2020 Note of reflection; DORA trunk development capabilities (active branches ≤ 3, branch survival < 1 day, no code freeze) | nvie.com · dora.dev · trunkbaseddevelopment.com |
Actual operating instructions
The output labeled "Actual running results" is from 2026-11-15 in Git for Windows 2.51.2 (GIT_CONFIG_NOSYSTEM=1, to avoid autocrlf interference), the path has been replaced by/home/azureuser, the hash and timestamp will be different in your environment. Includes: setup-p6.sh, cherry-pick -x conflicts with rollback,git cherryAudit, affected.sh, submodules (includingtransport 'file' not allowed), subtree add/split, partial clone and cone sparse detection missing object count, gc/commit-graph/MIDX,git refs migrate --ref-format=reftable、repo-review.sh。Failed to run in build environment: git-lfs (not allowed to execute downloaded binaries), git-filter-repo (not installed),git maintenance start(will modify the system scheduler), scalar (Git for this environment does not come with a scalar executable), git svn / git-tfs (without SVN/TFVC server) - these outputs are marked as "examples" and are formatted according to the official documentation.
Video verification instructions
All videos listed in this lesson were released on 2026-11-15 through the YouTube oEmbed interface (https://www.youtube.com/oembed?url=…&format=json) Verify titles and channels: _w6TwnLCFwA, GQQqf-C2ha4, hG_P6IRAjNQ, CR3LP2n2dWw, i657Bg_HAWI, rX80eKPdA28, 5q75e eEYApk, qsTthZi23VE, 9iU_IE6vnJ8, VvcJGjjEyKo, wfKXJNbAcQ8, GQW4tDLu_BM, gSlXo2iLBro, JESI498 HSMA, 8Z4Cmhji_FQ, sC1sfoCo5qY, 9gaTargV5BY, jXsvFfksvd0, LMG_-uJVdsw, 8iZqagosc5w, 6b6iOPvsp Ps, Qdi2HxPE9lg, 5xGc3UlsQHQ, kBMTLIWkYVQ, _EcmY7_zlv0, zoJWZwoM-Mw, SzEBzQrwxFk, U_IFGpJDbeU. Didn't find anything specifically about reftable,git maintenance, verified videos of TFVC migration, and the corresponding module provides storyboard scripts.
Audio explanation
The "Voice" tab uses the browser Web Speech API (zh-CN) to read the explanation text in real time. English terms are pronounced in en-US. The effect depends on the voice installed on the system. The production environment cannot call the TTS service, so there is no embedded MP3; when audio is needed, the transcript can be handed over to services such as Azure AI Speech.
Known limitations
- The GitHub LFS single file limit (Free 2 GB ... Enterprise Cloud 5 GB) comes from the long-term annotation of GitHub's "About Git Large File Storage" document. This time, only the quota page was verified; the storage quota of GitLab LFS changes with the package, and no specific number is written.
- The status of AWS CodeCommit’s support for Git LFS can be found in Lesson 4, which is not repeated in this lesson.
- The sample output of LFS migration, filter-repo, and git svn is written in the official document format, and the details (time consumption, hashing) will be different.
- "Move back matrix", "decision scorer" and "review scorecard" are heuristic tools for teaching and do not represent the only correct answer; the choice of branch strategy also depends on the organizational culture and tool chain.
- The number of objects in the animation is taken from the small sample repository in this lesson; the batch download and negotiation process when checking out in a real large repository is more complicated (available
GIT_TRACE2_EVENTobservation).