Git Hour 8 (optional): 50 production problems + 50 interview questions

Develop the knowledge from the first seven lessons into two kinds of muscle memory: knowing which command to type first when seeing an error; explaining the principles in two minutes during the interview
A: 50 production issuesB: 50 interview questionsGit 2.56 · GitHub · Azure Repos · GitLab · CodeCommitVerification date 2026-11-15
overall learning objectives
  • When you see the original text of an error report, you can determine whether it belongs toCommit and undo, branch and merge, remote and certification, large repository/CI/securitywhich level in the system and say the first diagnostic command.
  • Understand the context behind each questionmechanism: Object immutable + ref movable, reflog is a safety net, fast-forward rules, merge base and three-way merges, credential helper search order, rejection of protected branches in the server-side pre-receive stage, "history truncation" for shallow clones, clean/smudge filters.
  • Able to practice in a local repositoryReproduce, diagnose, repair, clean up14 typical faults, most of which do not require a platform account.
  • Able to answer 50 high-frequency Git interview questions according to the structure of "30-second short answer → principle → command example → production experience", and respond to common follow-up questions.
  • Use mock interviews (timed + self-assessment) to quantify mastery and identify weak modules.

1-hour time allocation table

#timemodulecore contentAnimation·Interactionexperiment
0before classInstructions for use and fault experimental environmentGit 2.5x, bootstrap practice repository, local "bare repository remote", security rulesEnvironmental self-checkBuild ~/git-lab8
100–08A·Commit, retract and historyIssues 1–12: Accidentally committed to main, reset --hard lost work, amend has been pushed, secrets committed, identity error, detached HEAD, stash lost, local modifications are overwritten, index.lock, branch accidentally deleted, .gitignore does not take effect, rebase stuck“Where does my commit go?” decision treereflog retrieval · detached HEAD · mistakenly committed for relocation · stash recovery
208–16A · Branching, merging and rebasingQuestions 13–25: non-fast-forward, divergent branches, repeated conflicts, repeated commits after rebase, mistaken merge rollbacks, cherry-pick conflicts, branch judgment after squash, unrelated histories, modify/delete, merge "lost code", pull rejection, PR with other people's commits, lock file conflicts"Push/merge is wrong" decision treerevert -m 1 · rerere · rebase --onto · remerge-diff
316–24A·Remote, authentication and platformIssues 26–38: Authentication failed, publickey, 403, protected branch, GCM bad credentials, host key change, large file, RPC failed/413, TLS, connection timeout/proxy, Repository not found/TF401019, push rule, CodeCommit 403"push/clone failed" decision treeLocal pre-receive mock protected branch · GIT_TRACE · Credential sanitization
424–30A · Large repository, performance, CI and securityIssues 39–50: slow clone, LFS pointers, submodules, shallow clone missing history, newlines, case, size expansion, signature failure, dubious ownership, permission bits, hooks not executed, old clone reflow after history rewritingCI checkout fault simulatorShallow clone describe · newline renormalize · case renaming
530–37B·Basic concepts and internal principlesInterviews 1–13mock interview2 scene questions
637–44B · Branching, merging and historyInterview 14–25mock interview2 scene questions
744–52B·Collaboration process and platformInterview 26–38mock interview3 scene questions
852–60B · Scale, security and scene designInterview 39–50mock interview3 scene questions
—After classcheat sheet · Comprehensive drill50 "error reporting → first command → repair"; 50 shorthand cards; 8 mixed faults; full mock interviewFull mock interviewFinal exam 12 questions

knowledge coverage matrix

Topicm1m2m3m4m5m6m7m8
object model/ref/reflog●——●●●——
Undo: reset/restore/revert/amend●●——●●——
merge/rebase/conflict/cherry-pick—●———●●●
Remote/Authentication (SSH, HTTPS, GCM, PAT)—●●—●—●—
Platform: protected branches, rule sets, PR/MR, CODEOWNERS—●●——●●●
CI / Shallow Cloning / Hooks———●——●●
Large repository: LFS, partial clone, sparse checkout, submodule——●●●——●
Security: confidentiality, signatures, history rewriting●—●●——●●

Content not covered in this course (where to learn)

  • Explain the object model, three areas, and basic commands from scratch →Lesson 1 Core Fundamentals。
  • Complete configuration steps for the platform (Azure Repos / GitHub / CodeCommit / GitLab) →Lesson 3 / Lesson 4。
  • Pipeline syntax of GitHub Actions / Azure Pipelines / GitLab CI → Follow-up independent platform lesson; this lesson only covers the Git-related parts of the pipeline (Lesson 5)。
  • Git source code contribution, implementation details of protocol v2, and self-built operation and maintenance of the hosting platform (GitLab self-managed instance, Gitaly) → are subject to official documents and are not covered by this course.
  • Next door on the learning path:Docker 8 hours(Containerization), followed by Kubernetes and Infrastructure as Code;GitHub 8 hoursWait for the CI/CD platform course to come after them.

How to use this lesson

When Troubleshooting (Part A)
  • Open the corresponding modulequick overview, put the most identifiable words in the error report (such asnon-fast-forward、publickey、GH006、index.lock) into the filter box.
  • Click on a table row to jump directly toDetailed explanation of the problem, press "Diagnosis → Control Output → Repair" to execute.
  • Not sure which floor you’re on? useanimationPaginated decision tree/simulator.
Pre-Interview (Part B)
  • Look firstquick overview, select the questions you are not sure about according to difficulty.
  • mock interview: Randomly select questions, 2-minute countdown, answer first and read later, self-assessment of "yes/partially/no", and results are saved in this browser.
  • Answer structure:Conclusion → Principles → Commands/Examples → Pitfalls。
After class
  • cheat sheetSuitable for printing and sticking at work station.
  • Comprehensive drill: 8 mixed breakdowns + full mock interview (10 out of 50) + final exam.
  • Each question is linked back to the corresponding courseware for Lessons 1–7, and can be returned.

A/B two-part entry structure

Part A · Production Problems 50 Examples

Symptom → Root cause (mechanism level) → Diagnostic command → Example of expected output → Repair → Prevention and best practices → See Lesson N for details. The title should try to use the original error text actually output by Git/the platform; Git's hint copy and the remote message returned by the platform (GitHub, Azure DevOps, GitLab, AWS) will be adjusted with the version, and the entry has noted that "the wording may differ depending on the version."

Part B · 50 interview questions

Question → 30-second short answer → In-depth answer (principles, command examples) → Common follow-up questions → Bonus points → Common wrong answers. Difficulty:ElementaryIntermediateAdvanced。

Relationship to the first seven lessons

coursesMost cited content in this lesson
Lesson 1 Core FundamentalsObject model, three areas, reset/restore/revert, HEAD, remote base, .gitignore
Lesson 2 Branching, Merging, and TeamworkFast forward and three-way merges, conflicts and rerere, rebase, cherry-pick, stash, tracking branches, PR workflow, tags
Lesson 3 Azure Repos and GitHubSSH / HTTPS / GCM authentication, branch strategy, rule set, CODEOWNERS, platform side troubleshooting
Lesson 4 CodeCommit and GitLabgit-remote-codecommit, approval rules, protected branches, push rules, cross-platform mirroring
Lesson 5 Git in CI/CD and Automationhooks/pre-commit, shallow cloning and fetch-depth, signatures, secret scanning, agreed-upon commit, path filtering
Lesson 6 Branching Strategy and Repository ArchitectureTrunk development/GitFlow, hot fix rollback, monorepo, submodules, LFS, partial cloning, maintenance, migration
Lesson 7 In-depth Troubleshooting and History RecoveryGIT_TRACE, reflog, bisect, filter-repo, fsck, newline/case/permissions, network diagnostics
Release NotesThis lesson is based onGit 2.56(2026-09 release) is the baseline. Related changes for 2.56:git refsAdded create / delete / update / rename subcommands; experimentalgit historyNewdropsubcommand;git replayNew--linearize;git push origin/mainCorrective tips will be given for such common clerical errors.Git 3.0Planned breaking changes (default SHA-256 for new repositories, default reftable reference storage, default branch namemain) withBreakingChangesshall prevail,It's still a plan. Platform messages (GH006, GH013, TF402455, etc.) are the common form when this lesson is written, and all "expected outputs" areExample, the hash, time, username are different from your environment.

Module 0 · Instructions for use and fault experimental environment (before class)

Most faults can be reproduced locally: a working repository + a local bare repository serve as the "remote" and do not require a platform account.
Before class ≈ 10 minutesDon't experiment on a real repository
Prerequisites
  • Lessons 1 and 2 completed; Lessons 3–7 optional (read-only diagnostic commands and links are given in platform-specific entries).
  • Ubuntu 24.04 (Azure VM or WSL), macOS or Windows (Git for Windows + Git Bash).
  • Complete reproduction of platform-related issues (Module 3) requires a disposable test repository: a free GitHub account will do; an Azure DevOps free organization (5 Basic users); and GitLab free tier. Delete the test repository and revoke PAT/SSH keys after experimentation.

Installation and version checking

# Ubuntu: The built-in version is too old, use git-core PPA to get the latest stable version
sudo add-apt-repository -y ppa:git-core/ppa
sudo apt-get update && sudo apt-get install -y git git-lfs
# macOS: brew install git git-lfs
# Windows: Install the latest Git for Windows (comes with Git Credential Manager)
git --version
git lfs version
git version 2.56.x
git-lfs/3.x.x (GitHub; linux amd64; go 1.2x)

The PPA name and available versions end withLaunchpad git-core PPAshall prevail; versions lower than 2.40 can also complete most experiments, and individual commands (such asgit show --remerge-diffRequires 2.36+) will be noted.

Fault experiment repository ~/git-lab8

Lesson 1 Module 0 ofbootstrap-git-lab.shWhat is generated is~/git-lab/myapp;In this lesson, in order to "can break it at will", we will build a separate version with a local remote end:

#!/usr/bin/env bash
# lab8-bootstrap.sh - can be run repeatedly; will be deleted and rebuilt ~/git-lab8
set -euo pipefail
rm -rf ~/git-lab8 && mkdir -p ~/git-lab8 && cd ~/git-lab8
git init -q --bare -b main remote.git # Act as the "remote" of GitHub/Azure Repos
git clone -q remote.git alice && cd alice
git config user.name "Alice Lab"; git config user.email "alice@example.com"
cat > app.py <<'EOF'
from flask import Flask
app = Flask(__name__)

@app.get("/healthz")
def healthz():
    return "ok"
EOF
printf 'flask==3.*\ngunicorn==23.*\nredis==5.*\n' > requirements.txt
git add . && git commit -qm "feat: initial myapp"
for i in 1 2 3; do echo "# change $i" >> app.py; git commit -qam "chore: change $i"; done
git tag -a v1.0.0 -m "v1.0.0"
git push -q -u origin main --tags
git switch -qc feature/login
echo "def login(): return 'login'" >> app.py; git commit -qam "feat: login"
git push -q -u origin feature/login
git switch -q main
cd .. && git clone -q remote.git bob
git -C bob config user.name "Bob Lab"; git -C bob config user.email "bob@example.com"
echo "lab8 ready: $(git -C alice log --oneline | wc -l) commits on main"
lab8 ready: 4 commits on main

alice and bob are two independent clones, used to simulate "two people pushing at the same time";remote.gitYou can add server-side hooks (for module 3)pre-receivesimulate protected branches).

Environmental self-check list

Connection with previous lesson

Lesson 7GIT_TRACE、reflog、fsck、filter-repoThey appear in large numbers in this lesson; this lesson organizes them into entries of "Error reporting → First command → Repair" and fills in issues related to the platform and CI.

Safety Rules (required reading)

Back up first, do it laterDo it to the real repositoryreset --hard、push --force、filter-repo, Before deleting a branch, take an insurance first:git branch backup/$(date +%s), or the entire directorycp -a repo repo.bak(Including.git). reflog only exists inlocal, the remote repository does not have your reflog.
  • Experiment using only fake secrets (e.g.FAKE_SECRET=lab8-not-a-real-key). Once the real secret is pushed,The first step is always revocation/rotation, rather than changing history.
  • A separate test repository is used for platform experiments; after completion, delete the repository, revoke PAT, and delete the SSH public key.

Five Steps to General Troubleshooting (Throughout Part A)

stepscommandAnswered questions
1 Read all and report an errordistinguish fatal:(local Git),remote:(Server/Platform return),hint:(suggestion)Did the failure occur locally, on the network, or on the server?
2 Look at the statusgit status · git log --oneline --graph --all -20Which branch am I on? Is it merging/rebasing? Is HEAD free?
3 Look at the configurationgit config --show-origin --show-scope -l · git remote -vWhich configuration file takes effect? Is the remote URL SSH or HTTPS?
4 Look at the safety netgit reflog · git stash list · git fsck --lost-foundAre the "lost" things still in the object library?
5 Turn on trackingGIT_TRACE=1 GIT_CURL_VERBOSE=1 GIT_TRACE_PACKET=1 git fetch;SSH:GIT_SSH_COMMAND="ssh -vvv"Which credential was used, which key, what was the HTTP status code? (The output may contain tokens, delete them after use)

Module 1 · Part A: Commitment, Undoing, and History (Questions 1–12)

00:00 – 08:00 · Incorrect commit, lost work, changed pushed history, confidentiality, identity, free HEAD, stash, locked files
8 minutesreflog is a safety net12 questions
learning objectives
  • Explain in one sentence "almost all commits can be retrieved": the commit object is immutable, and only the ref pointing to it is lost; the reflog records every move of the ref (default retention is 90 days, and unreachable entries are retained for 30 days).
  • Distinguish three types of undo: only move ref (reset --soft), moving ref + staging area (--mixed), moving ref + staging area + working tree (--hard); and "Add a reverse commit"revert。
  • Remember a red line:Do not rewrite history that has been pushed and pulled by others.; Used when it must be rewritten--force-with-leaseand notify everyone.

Enter keywords in the error or phenomenon (such asreflog、detached、index.lock、stash) filter; click on a row to jump to the corresponding entry in "Problem Details".

#1 was committed to main (should be on the feature branch)
$ git log --oneline -3
9c1e2f4 (HEAD -> main) feat: add payment API ← should be on feature/payment
a3b4c5d (origin/main, origin/HEAD) chore: change 3
...
$ git status
On branch main
Your branch is ahead of 'origin/main' by 1 commit.
  (use "git push" to publish your local commits)

Phenomenon:Write the code directly on main and commit it; sometimes push (if main is not protected).

Root cause:git commitAlways pick up new commits afterThe branch pointed to by HEADbehind, and move this branch ref. Forgot firstgit switch -c, the commit falls on main. There's nothing wrong with the commit itself, it's just that it's "on the wrong branch".

diagnostic commands
git status -sb # ## main...origin/main [ahead 1]
git log --oneline origin/main..main # Only look at the commits that have not been pushed yet
## main...origin/main [ahead 1]
9c1e2f4 feat: add payment API
Fix (not pushed yet)
git branch feature/payment # 1) Create a new branch at the current location, and the commit will "have a new home"
git reset --hard origin/main # 2) Move main back to the remote location (the workspace must be clean)
git switch feature/payment # 3) Continue working on the feature branch
Fix (already pushed to main)
  • main shared by the teamDon'treset + force push. usegit revert 9c1e2f4Push a reverse commit on the feature branchgit cherry-pick 9c1e2f4Go PR.
  • Note: revert will still work when the feature branch is later merged back into main (see "revert of revert" in #17).
Prevention and best practices
  • Protect main on the platform (requires PR), see #29.
  • Add one locallypre-commitHook: Refuse to commit when the current branch is main/master ([ "$(git branch --show-current)" != "main" ] || { echo "Don't commit directly to main"; exit 1; })。
  • Display the branch name in the shell prompt (git-prompt.sh/starship).

See detailsLesson 1 Getting Started with Branching and HEAD and Undoing、Lesson 5 Git hooks。

#2 After git reset --hard, the committed/uncommitted changes are "gone"
$ git reset --hard HEAD~3
HEAD is now at a3b4c5d chore: change 3
# Found that the last 3 commits contain all of today's work...

Phenomenon:git logI can’t see those commits; or there are still some before resetNot committedThe modifications will also disappear together.

Root cause:reset --hardMove the branch ref and overwrite the staging area and workspace with the target commit.CommittedThe contents of.git/objects, reflog records the position of HEAD before reset;Alreadygit addbut not committedThe content exists as a blob object, but there is no ref or reflog pointer, so it can only be retrieved with fsck;Never addedGit has never seen the modifications and cannot retrieve them (you can only rely on the IDE local history).

diagnostic commands
git reflog -10 # HEAD’s movement record
git fsck --lost-found # Blobs that have been staged but not committed → .git/lost-found/other/
a3b4c5d (HEAD -> main) HEAD@{0}: reset: moving to HEAD~3
7f8e9d0 HEAD@{1}: commit: feat: today's work part 3
...
dangling blob 4b825dc642cb6eb9a060e54bf8d69288fbee4904
Repair
git reset --hard HEAD@{1} # or git reset --hard 7f8e9d0: Move the branch back to before reset
# Just want to retrieve part of the content: git branch rescue 7f8e9d0 and then cherry-pick / checkout the file
# Uncommitted content has been temporarily stored:
ls .git/lost-found/other/ && git show 4b825dc6 > recovered_file.py
Prevention and best practices
  • Used when you want to "discard recent commits but keep changes"git reset --soft / --mixed, only used when you are sure to discard the workspace--hard。
  • Before dangerous operationsgit stash -uorgit branch backup/now, the cost is almost zero.
  • If you just want to undo the changes to a certain file, usegit restore file, do not reset the entire repository.
  • reflog defaultgc.reflogExpire=90 days、gc.reflogExpireUnreachable=30 days, do not run immediately after an accidentgit gc --prune=now。

See detailsLesson 1 Undo: restore, reset, revert、Lesson 7 reflog and retrieving lost commits。

#3 amend / rebase the pushed commit, push was rejected: Updates were rejected because the tip of your current branch is behind
$ git commit --amend -m "feat: login (fixed typo)"
$ git push
To github.com:org/myapp.git
 ! [rejected]        feature/login -> feature/login (non-fast-forward)
error: failed to push some refs to 'github.com:org/myapp.git'
hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. If you want to integrate the remote changes,
hint: use 'git pull' before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

Phenomenon:I just changed the commit information, but push said "lag behind the remote end". If you follow the promptsgit pull, you will get a merge commit, and the old commit and the new commit will appear in the history at the same time.

Root cause:--amendInstead of "modifying" the commit,Create a new commit(new hash) and have the branch point to it; the old commit is still on the remote side. The remote branch is no longer the ancestor of the local branch. Ordinary push only allows fast forwarding, so it is rejected. The wording of hint is generic "backward", I don't know if you reworded it on purpose.

diagnostic commands
git fetch
git log --oneline --left-right --graph HEAD...@{u} # < is unique to the local, > is unique to the remote
* 5d6e7f8 (HEAD -> feature/login) feat: login (fixed typo)    ← <
| * 1a2b3c4 (origin/feature/login) feat: login                 ← >
|/
Repair
# Exclusive feature branch: safe push (the remote end will reject it if it has been updated by others)
git push --force-with-lease --force-if-includes
# Shared branch / main: Do not rewrite, cancel amend, and add a repair commit instead
git reset --hard @{u} && git commit --allow-empty -m "docs: fix typo in previous message"
Prevention and best practices
  • Team agreement: PR can amend/rebase on its own branch before merging +--force-with-lease;The merged history is appended only.
  • Set aliasgit config --global alias.pushf "push --force-with-lease --force-if-includes", put an end to nudity--force。
  • Protect main from force push (GitHub ruleset "Block force pushes", Azure Repos's Force push permission, GitLab's Allowed to force push).

See detailsLesson 2 Rebasing and Remote Branching, interview questionsQ25。

#4 Committed secrets: push blocked by push protection (GH013 / Push cannot contain secrets)
remote: error: GH013: Repository rule violations found for refs/heads/feature/login.
remote:
remote: - GITHUB PUSH PROTECTION
remote:   —————————————————————————————————————————
remote:     Resolve the following violations before pushing again
remote:
remote:     - Push cannot contain secrets
remote:
remote:      —— AWS Access Key ID ——————————————————
remote:        locations:
remote:          - commit: 9c1e2f4...
remote:            path: config/settings.py:3
To github.com:org/myapp.git
 ! [remote rejected] feature/login -> feature/login (push declined due to repository rule violations)

Phenomenon:The push was rejected by the platform stating that a file in a commit contained a secret. even if you areLater commitsI deleted this line and the push was still rejected. GitLab (Secret push protection) and Azure DevOps (GitHub Advanced Security for Azure DevOps push protection) have similar mechanisms, but the message formats are different.

Root cause:Push protection scans forAll commits included in this push, rather than the final file status. As long as the secret appears in any commit to be pushed, it will enter the remote object library and must be removed from the history.

diagnostic commands
git log --oneline @{u}..HEAD # Commits to be pushed (new branches use origin/main..HEAD)
git log -p @{u}..HEAD -S 'AKIA' -- config/ # Which commit introduced this string of characters (pickaxe)
9c1e2f4 feat: add settings ← introduce secrets
b7c8d9e chore: remove key from settings
Repair
# 0) If the secret is true: revoke/rotate it on the cloud platform first (it is already in your local history and may still be in the IDE log)
# 1) There are only local commits that have not been pushed successfully: interactive rebase, edit the commit that introduced the secret
git rebase -i @{u} # Change pick before 9c1e2f4 to edit
# Modify the file and read from the environment variable instead: os.environ["AWS_ACCESS_KEY_ID"]
git add config/settings.py && git commit --amend --no-edit && git rebase --continue
git log -p @{u}..HEAD -S 'AKIA' # Push only when the output is empty
git push

Only confirmation isFalse positives/test dataOnly use the "Allow this secret" link provided by the platform to bypass (leaving audit records). See #50 for the situation where the secret has been pushed to the remote end.

Prevention and best practices
  • Locally use the pre-commit framework + gitleaks/detect-secrets to intercept before commit, which is less expensive than intercepting during push.
  • Secrets are placed in environment variables, Key Vault/Secrets Manager,.envwrite in.gitignore, and commit.env.example。
  • Enable push protection at the organizational level (GitHub public repositories are enabled by default for users, private repositories require a Secret Protection license; refer to official documentation).

See detailsLesson 5 Confidential Leak Prevention and Scanning、Lesson 7 filter-repo clear secrets。

#5 Author identity unknown *** Please tell me who you are. / Committed using the wrong email address
Author identity unknown

*** Please tell me who you are.

Run

  git config --global user.email "you@example.com"
  git config --global user.name "Your Name"

to set your account's default identity.
Omit --global to set the identity only in this repository.

fatal: unable to auto-detect email address (got 'ubuntu@vm-lab.(none)')

Phenomenon:The first commit of a new machine/new container fails; or a more subtle situation - the commit is successful, but using a personal email orroot@hostname, it is displayed as an unassociated user on the platform, and the push is rejected due to CLA check or the push rule that "the committed email address must belong to the organization's domain name".

Root cause:Author/committer identity comes from configuration (system → global → local → environment variablesGIT_AUTHOR_*/GIT_COMMITTER_*), Git will not verify it. Platform buttonEmailAssociate commits to accounts.

diagnostic commands
git config --show-origin --get-all user.email
git log --format='%h %an <%ae> | %cn <%ce>' -5
file:/home/alice/.gitconfig    alice.personal@gmail.com
3f4e5d6 Alice <alice.personal@gmail.com> | Alice <alice.personal@gmail.com>
Repair
git config --global user.name "Alice Zhang"
git config --global user.email "alice@corp.example.com"
# Fix commits that haven't been pushed yet (reset author from every commit after @{u})
git rebase @{u} --exec 'git commit --amend --no-edit --reset-author'
# Pushed history will not be rewritten: use .mailmap to make log/shortlog display the correct identity
echo 'Alice Zhang <alice@corp.example.com> <alice.personal@gmail.com>' >> .mailmap
Prevention and best practices
  • Separate work and personal repositories: use conditional inclusion[includeIf "gitdir:~/work/"] path = ~/.gitconfig-work(Starting from 2.56, it can also be judged based on the working tree position).
  • settings git config --global user.useConfigOnly true: Reject email guessing when not explicitly configured.
  • Explicitly set when CI robot commitsuser.name/email(e.g.github-actions[bot]noreply address).

See detailsLesson 1 Environment Preparation and Configuration、Lesson 4 GitLab Push Rules。

#6 Warning: you are leaving 1 commit behind, not connected to any of your branches (detached HEAD lost commit)
$ git switch main
Warning: you are leaving 1 commit behind, not connected to
any of your branches:

  e4f5a6b fix: hotfix tested on tag

If you want to keep it by creating a new branch, this may be a good time
to do so with:

 git branch <new-branch-name> e4f5a6b

Switched to branch 'main'

Phenomenon:before git checkout v1.0.0(or CI checked out a certain commit), then change the code and commit it, and the commit "disappears" after switching away.

Root cause:When checking out a tag, remote branch, or a hash, HEAD points directly to the commit instead of the branch (detached HEAD). The new commit at this time is only referenced by HEAD; once HEAD is removed, there will be no branch pointing to it and it will become an "unreachable" object, which may be cleaned up by gc after 30 days.

diagnostic commands
git reflog | grep -m5 -E 'commit|checkout'
git log --oneline -1 e4f5a6b
a3b4c5d HEAD@{0}: checkout: moving from e4f5a6b... to main
e4f5a6b HEAD@{1}: commit: fix: hotfix tested on tag
6b7c8d9 HEAD@{2}: checkout: moving from main to v1.0.0
Repair
git branch hotfix/1.0.1 e4f5a6b # Give it a branch name and the problem is solved
git switch hotfix/1.0.1
Prevention and best practices
  • use git switchinstead ofgit checkout: Must be written explicitly when checking out a non-branch--detach, will not "accidentally" dissociate.
  • To modify based on tags:git switch -c hotfix/1.0.1 v1.0.0。
  • It is normal for CI to build on the free HEAD (actions/checkout checks out a commit); but do not expect it to automatically push back the branch after committing in CI.

See detailsLesson 1 Getting Started with Branching and HEAD、Lesson 7 reflog。

#7 stash is lost: git stash drop / git stash clear accidentally deleted, or stash pop cannot be found after conflict
$ git stash pop
Auto-merging app.py
CONFLICT (content): Merge conflict in app.py
On branch main
...
The stash entry is kept in case you need it again.
$ git stash drop # I thought the conflict was resolved, so I just dropped it.
Dropped refs/stash@{0} (2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d)

Phenomenon:The stash list is empty, the conflict is not resolved correctly, and the original modifications cannot be retrieved.

Root cause:Each stash is actually one (with 2–3 parent commits)Commit object,refs/stashand its reflog pointing to it. drop/clear only deletes the reference, the object remains until the gc cleans up the unreachable object.dropThe complete hash is printed in the output.

diagnostic commands
# The terminal is still there: print the hash directly with drop
git show --stat 2c3d4e5f
# The terminal is closed: find all unreachable commits. The information committed by stash starts with "WIP on" / "On <branch>:"
git fsck --unreachable --no-reflogs | awk '/commit/ {print $3}' \
  | xargs git log --no-walk --format='%h %ci %s' | grep -E 'WIP on|On '
2c3d4e5 2026-11-15 10:42:13 +0800 WIP on main: a3b4c5d chore: change 3
Repair
git stash apply 2c3d4e5f # Re-apply (stash commit can be applied directly)
# Or save it as a branch first and then compare it slowly
git branch rescue/stash 2c3d4e5f
Prevention and best practices
  • stash is temporary: work older than a day is committed to a WIP branch (git switch -c wip/x && git commit -am wip)。
  • use git stash push -m "description"Naming; used in case of conflictgit stash apply(preserve entries) instead of pop.
  • When you need to work on two branches at the same time,git worktree add ../myapp-hotfix mainSafer than stashing repeatedly.

See detailsLesson 2 cherry-pick, stash and worktree、Lesson 7 fsck and object recovery。

#8 error: Your local changes to the following files would be overwritten by checkout / merge
$ git switch feature/login
error: Your local changes to the following files would be overwritten by checkout:
	app.py
Please commit your changes or stash them before you switch branches.
Aborting

$ git pull
error: Your local changes to the following files would be overwritten by merge:
	app.py
Please commit your changes or stash them before you merge.
Aborting

Phenomenon:Switch branch or pull rejected. Another variation:error: The following untracked working tree files would be overwritten by checkout(The untracked file has the same name as the tracked file in the target branch).

Root cause:This is Gitprotection mechanism: In the target commitapp.pyDifferent from the current HEAD, and there are uncommitted changes in your workspace, force update will overwrite them. If the modified files are the same in the two branches, Git will "carry over" the changes without reporting an error.

diagnostic commands
git status --short
git diff --stat HEAD feature/login -- app.py # The file is indeed different between the two branches
Repair (select by intent)
git stash push -m "wip before switch" && git switch feature/login && git stash pop # Take the changes with you
git switch -c feature/new-idea # The modification actually belongs to a new branch (the new branch starts from the current HEAD and will not conflict)
git restore app.py # Make sure you don’t want these changes
git pull --rebase --autostash # Automatically stash / restore when pulling
git switch --merge feature/login # Try to merge the three local modifications into the target branch (conflicts may occur)
Prevention and best practices
  • git config --global rebase.autoStash true、merge.autoStash true。
  • Commit in small steps; used when two branches need to be processed in parallelgit worktree。
  • Untracked file conflicts: Usually the build product was mistakenly committed to another branch..gitignore(See #11).

See detailsLesson 1 Three Regions、Lesson 2 stash and worktree。

#9 fatal: Unable to create '.../.git/index.lock': File exists.
fatal: Unable to create '/home/alice/myapp/.git/index.lock': File exists.

Another git process seems to be running in this repository, e.g.
an editor opened by 'git commit'. Please make sure all processes
are terminated then try again. If it still fails, a git process
may have crashed in this repository earlier:
remove the file manually to continue.

Phenomenon:Any command that writes to the staging area (add, commit, checkout, pull) fails.

Root cause:Git write.git/indexCreated firstindex.lock, rename atomically after writing. This lock will be left or occupied if the process is killed, the machine is powered off, the IDE's background Git process (VS Code, JetBrains' automatic fetch/status) is running, or the same directory is shared by two CI tasks. Similar ones arerefs/heads/main.lock(when updating ref).

diagnostic commands
ps aux | grep -v grep | grep -E '\bgit\b' # Windows: tasklist | findstr git
ls -l .git/index.lock; date #Whether the file was locked a long time ago
Repair
# After confirming that there are no git processes (including IDE, git gui, and open commit editor):
rm -f .git/index.lock
git status # If it prompts that the index is damaged: rm .git/index && git reset (rebuild the staging area from HEAD, the working tree remains unchanged)
Prevention and best practices
  • CI: Each job uses an independent working directory; after the self-hosted runner is forcibly canceled, residual locks are cleared at the beginning of the job.
  • Do not run two Git commands at the same time in the same repository directory (for example, script concurrencygit pull)。
  • Repositorys on network disks (SMB/NFS) are more likely to have lock residues, so try to place them on local disks.

See detailsLesson 7 Troubleshooting Methodology。

#10 error: The branch 'feature/x' is not fully merged. → After using -D, I found that I deleted it wrongly.
$ git branch -d feature/report
error: the branch 'feature/report' is not fully merged
hint: If you are sure you want to delete it, run 'git branch -D feature/report'
$ git branch -D feature/report
Deleted branch feature/report (was 8d9e0f1).

The wording varies slightly from version to version (earlier versions areerror: The branch 'feature/report' is not fully merged.addIf you are sure you want to delete it, run 'git branch -D feature/report'.)。

Phenomenon:After force deletion, you realize that there is unmerged work on it; or you click "Delete branch" on the platform.

Root cause:Deleting the branch only deletes the ref, but the commit is still there.Note: The branch's own reflog will be deleted along with the branch, but HEAD's reflog still records your commits and switches on the branch; when deleting, Git also prints the hash of the branch last pointed to.

diagnostic commands
git reflog | grep -m3 'feature/report' # Switch to/leave the record of this branch
git log --oneline -3 8d9e0f1 # Hash printed when deleting
# The remote branch was deleted: other colleagues may still have origin/feature/report in their local repositories (they haven’t fetch --prune yet)
Repair
git branch feature/report 8d9e0f1
git push -u origin feature/report # If the remote end is also deleted
# GitHub: There is a "Restore branch" button on the closed PR page; Azure Repos: Search the branch page for deleted branches → Restore branch
Prevention and best practices
  • Only use-d; first when seeing “not fully merged”git log main..feature/reportConfirm.
  • Note that after squash is merged-dThis error will also be reported (see #19). At this time, you need to confirm the PR status instead of using conditional reflection.-D。
  • Enable the platform's "no deletion" rule for important branches.

See detailsLesson 7 reflog and retrieving lost commits、Lesson 3 Platform Branch Management。

#11 .gitignore does not take effect: files with ignored rules still appear in git status
$cat.gitignore
.env
__pycache__/
$ git status --short
 M .env ← still shows that it has been modified
 M app/__pycache__/app.cpython-312.pyc

Phenomenon:Ignore rules have no effect on some files.

Root cause:.gitignore Only affectsNot trackedfile. These files have been committed (tracked) before adding the rule, and Git will continue to track their changes. Other common reasons: wrongly written rules (/buildOnly matches the root directory,build/Only matches directories), followed by!patternThe reverse rule is re-included and written in the wrong directory..gitignore, the file has UTF-16 BOM (used under Windowsecho >generated).

diagnostic commands
git ls-files --error-unmatch .env && echo "Already tracked"
git check-ignore -v --no-index .env app/__pycache__/x.pyc # Which rule (file: line number) is hit
.env
has been tracked
.gitignore:1:.env .env
.gitignore:2:__pycache__/ app/__pycache__/x.pyc
Repair
git rm --cached .env # Remove from index, keep local files
git rm -r --cached app/__pycache__
git commit -m "chore: stop tracking .env and bytecode"
# If there is a real secret in .env: it is still in the history → rotate secrets, clean history as needed (#50)

To temporarily ignore modifications to a tracked file only locally:git update-index --skip-worktree config/local.yaml(Do not compare with--assume-unchangedMixed, the latter is a performance tip and is not guaranteed to take effect).

Prevention and best practices
  • Put it away after initializing the project.gitignore(github/gitignore template).
  • Personal editor files are placed globally and ignoredcore.excludesFile, don't pollute the project's .gitignore.
  • CI China-Canada inspection:git ls-files -ci --exclude-standardFail with output (files that are tracked but should be ignored).

See detailsLesson 1 Getting Started with Configuration, .gitignore, and Troubleshooting。

#12 fatal: It seems that there is already a rebase-merge directory (rebase stuck halfway)
$ git rebase -i HEAD~5

fatal: It seems that there is already a rebase-merge directory, and
I wonder if you are in the middle of another rebase.  If that is the
case, please try
	git rebase (--continue | --abort | --skip)
If that is not the case, please
	rm -fr ".git/rebase-merge"
and run me again.  I am stopping in case you still have something
valuable there.

Phenomenon:The previous rebase was put down after encountering a conflict (closed the terminal and went to do other things), and now any new rebase cannot be started; the prompt is displayed(main|REBASE 3/5); Or the interactive rebase got the commit order/squash wrong.

Root cause:Rebasing is a process of "replaying commits one by one", and the progress is saved in.git/rebase-merge/(orrebase-apply/) until--continuecomplete or--abortGive up. HEAD is free during rebasing.

diagnostic commands
git status # interactive rebase in progress; onto a3b4c5d ...
cat .git/rebase-merge/head-name # The branch being rebased
git reflog -15 # The position of the branch before the rebase starts (the previous entry of "rebase (start)")
interactive rebase in progress; onto a3b4c5d
Last commands done (3 commands done):
   pick 1a2b3c4 feat: a
   squash 5d6e7f8 fix: a
You are currently rebasing branch 'feature/login' on 'a3b4c5d'.
Repair
git rebase --abort # Return to the state before rebase (most commonly used and safest)
# Completed but the result is wrong: Find the commit before rebasing in the branch reflog
git reset --hard feature/login@{1} # or ORIG_HEAD (rebase will set it)
# Only when confirming that there is no rebase in progress and the directory is residual, run rm -rf .git/rebase-merge
Prevention and best practices
  • Display repository status (REBASE / MERGING / CHERRY-PICKING) in the shell prompt.
  • Tag before rebasing:git tag before-rebase, delete after completion.
  • Enable rerere (#15) when the same conflict occurs repeatedly; consider changing the base to a merge for a long time.

See detailsLesson 2 Rebasing vs. Interactive Rebasing、Lesson 7 reflog。

Where is the "lost" stuff? Whether it can be retrieved depends on the area it last arrived at. workspace (never added)Git has never seen this contentCan only rely on IDE local historyWorst case scenario for #2 Temporary storage area (added)blob has been written to the object libraryNo ref, no refloggit fsck --lost-found local commitcommit object + refloggit reflog → create new branch#1 #2 #6 #10 #12 Pushedremote + clones of all colleaguesUse revert to undo, not rewriteConfidential: Rotate First (#4 #50) add commit push The only difference between the three modes of reset is "which layer to cover" --soft: only move branch ref → leave changes in the staging area (suitable for "reorganizing recent commits") --mixed (default): move ref + reset staging area → keep changes in workspace --hard: move ref + reset staging area + overwrite workspace → uncommitted modifications are lost; committed modifications can still be retrieved through reflog
Figure 1-1 Recoverability: The further to the right, the easier it is to retrieve (local), the further to the right, the harder it is to "retract" (shared)
amend is not a modification, but a replacement (#3) A B B' origin/feature (the remote end still points to B) feature (local pointer to B') B is not an ancestor of B' → ordinary push rejectedgit pull will merge B and B' → duplicate commitOwn branch: --force-with-leaseShared branch: cancel amend and add commit instead
Figure 1-2 Any rewrite (amend, rebase, filter-repo) will produce a new hash

“Where did my commit go?” Troubleshooting Decision Tree

Select the phenomenon you see and get diagnostic commands and conclusions step by step. Each conclusion can jump to the corresponding question for detailed explanation.

environmentGenerated in module 0~/git-lab8/aliceoperation; each experiment can be rerun before startinglab8-bootstrap.shGet a clean environment. All local operations, no platform fees.

Experiment 1-A: Use reflog to retrieve after reset --hard (#2)

Creating "today's work" and deleting it by mistake:
cd ~/git-lab8/alice
for i in 1 2 3; do echo "work $i" >> work.txt; git add work.txt; git commit -qm "feat: work $i"; done
echo "staged only" > staged.txt && git add staged.txt
git reset --hard HEAD~3
git log --oneline -1; ls staged.txt work.txt 2>&1 | head -2
a3b4c5d (HEAD -> main, origin/main) chore: change 3
ls: cannot access 'staged.txt': No such file or directory
ls: cannot access 'work.txt': No such file or directory
Diagnostics: reflog and fsck:
git reflog -4
git fsck --lost-found 2>/dev/null | grep blob
a3b4c5d HEAD@{0}: reset: moving to HEAD~3
7f8e9d0 HEAD@{1}: commit: feat: work 3
...
dangling blob 1c2d3e...
Fix:
git reset --hard HEAD@{1}
git show $(git fsck --lost-found 2>/dev/null | awk '/blob/{print $3; exit}') # Output staged only
git log --oneline -3
Cleanup:git reset --hard origin/main && rm -rf .git/lost-found

Lab 1-B: Commits on detached HEAD (#6)

Commit on tag, then cut away:
git checkout -q v1.0.0
echo "# hotfix" >> app.py && git commit -qam "fix: hotfix on tag"
git switch main 2>&1 | head -6
Warning: you are leaving 1 commit behind, not connected to
any of your branches:
  e4f5a6b fix: hotfix on tag
Retrieve and name:
git branch hotfix/1.0.1 HEAD@{1}
git log --oneline -2 hotfix/1.0.1
Cleanup:git branch -D hotfix/1.0.1

Experiment 1-C: Mistaken commit to main's "move" (#1)

echo "pay()" > pay.py && git add pay.py && git commit -qm "feat: payment"
git status -sb | head -1
## main...origin/main [ahead 1]
git branch feature/payment && git reset -q --hard origin/main
git log --oneline -1 main; git log --oneline -1 feature/payment
a3b4c5d chore: change 3
9c1e2f4 feat: payment
Cleanup:git branch -D feature/payment

Experiment 1-D: Recovery after stash drop (#7)

echo "# experimental" >> app.py
git stash push -m "experiment" && git stash drop
Saved working directory and index state On main: experiment
Dropped refs/stash@{0} (2c3d4e5f...)
Pretend the terminal is closed and use fsck to retrieve it:
h=$(git fsck --unreachable --no-reflogs 2>/dev/null | awk '/commit/{print $3}' \
   | xargs git log --no-walk --format='%H %s' | awk '/On main: experiment/{print $1; exit}')
echo "$h"; git stash apply "$h" && git diff --stat
Cleanup:git restore app.py

Instructional video (title and channel verified with YouTube oEmbed)

▶
Advanced Git Tutorial - Interactive Rebase, Cherry-Picking, Reflog, Submodules and more — freeCodeCamp.org
English · reflog retrieval, interactive rebase (corresponding to #2, #6, #12)
▶
Git Tutorial: Using the Stash Command — Corey Schafer
English · stash push/apply/pop/drop (corresponding to #7, #8)
▶
13 Advanced (but useful) Git Techniques and Shortcuts — Fireship
English · A quick overview of amend, reflog, stash and other techniques

No verified Chinese video specifically talking about "Misoperation Recovery" was found. Below is a 3-minute storyboard that can be recorded by yourself:

Shot 1 (0:00)Terminal: After 3 consecutive commitsreset --hard HEAD~3,git logOnly old commits remain, the audience exclaims.
Shot 2 (0:40) git reflogHighlightHEAD@{1},reset --hard HEAD@{1}One-click recovery; narration: "The commit will not be lost, only the pointer will be lost."
Shot 3 (1:30)Checkout tag → commit → cut away → "leaving 1 commit behind" warning appears, demogit branchNaming.
Shot 4 (2:20)Summarize the three layers: workspace (cannot be retrieved), staging area (fsck), commit (reflog); red line: pushed with revert.

Official documentation

or score ≥ 70% on the Quiz

Module 2 · Part A: Branching, Merging, and Rebasing (Questions 13–25)

08:00 – 16:00 · Push rejection, fork, conflict, duplicate commit, rollback merge, squash, cherry-pick
8 minutesmerge base · ort · rerere13 questions
learning objectives
  • All non-fast-forward rejections are explained by the "fast-forward rule": the remote ref must be an ancestor of the commit you want to push.
  • Understanding the three-way merge is based on the merge base, so "rollback merge", "squash merge" and "recommit after rebase" can all be inferred from the commit graph.
  • Master conflict-related tool chains:rerere、git checkout --conflict=diff3、git show --remerge-diff、git rebase --onto、git revert -m 1。

Enter the error keyword (such asnon-fast-forward、divergent、unrelated、CONFLICT、-m) filter; click on a row to jump to detailed explanation.

#13 ! [rejected] main -> main (fetch first) / (non-fast-forward)
To github.com:org/myapp.git
 ! [rejected]        main -> main (fetch first)
error: failed to push some refs to 'github.com:org/myapp.git'
hint: Updates were rejected because the remote contains work that you do not
hint: have locally. This is usually caused by another repository pushing to
hint: the same ref. If you want to integrate the remote changes, use
hint: 'git pull' before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

Phenomenon:A colleague pushed it first, but your push was rejected.(fetch first)It means that the remote end has objects that you do not have locally;(non-fast-forward)It means that you have fetched locally, but the branch has indeed forked (see #3, #14).

Root cause:By default, the remote end only acceptsfast forwardUpdate: New commits must be ancestors of the remote current commit, otherwise other people's commits will be lost. This is a protection mechanism, not a malfunction.

diagnostic commands
git fetch origin
git status -sb                                    # ## main...origin/main [ahead 1, behind 2]
git log --oneline --graph --left-right main...origin/main
Repair
git pull --rebase # Rebase your own commits onto the latest remote commit (linear history)
# Or git pull --no-rebase # Generate a merge commit
git push

Don't usegit push --force"Fix" the problem - that would delete the colleague's commit.

Prevention and best practices
  • Do not develop directly on the shared branch; feature branch + PR, conflicts are resolved in the PR.
  • settings git config --global pull.rebase true(or the team selects merge) and turns it on at the same timerebase.autoStash。
  • The high-concurrency backbone uses a merge queue and is merged sequentially by the platform (Interview question Q30).

See detailsLesson 1 Remote Repository、Lesson 2 Remote Branching and Tracking Relationships。

#14 fatal: Need to specify how to reconcile divergent branches.
$ git pull
hint: You have divergent branches and need to specify how to reconcile them.
hint: You can do so by running one of the following commands sometime before
hint: your next pull:
hint:
hint:   git config pull.rebase false  # merge
hint:   git config pull.rebase true   # rebase
hint:   git config pull.ff only       # fast-forward only
hint:
hint: You can replace "git config" with "git config --global" to set a default
hint: preference for all repositories. You can also pass --rebase, --no-rebase,
hint: or --ff-only on the command line to override the configured default per
hint: invocation.
fatal: Need to specify how to reconcile divergent branches.

Phenomenon:After upgrading Git (before and after 2.33), it can be used beforegit pullFails directly on fork. in CI scriptgit pullIt will also fail suddenly.

Root cause:git pull = fetch+ Integration. When there are new commits both locally and remotely, the integration method is ambiguous (merge or rebase). The new version of Git no longer silently generates merge commits, but requires you to explicitly choose them. Pull does not require configuration only if fast forwarding is possible.

diagnostic commands
git config --show-origin --get-regexp '^pull\.'
git rev-list --left-right --count HEAD...@{u} # Output "1 2": local leading 1, lagging 2
Repair
git config --global pull.rebase true # Personal recommendation: Keep feature branches linear
git pull # or one-time: git pull --rebase / --no-rebase / --ff-only
# CI/deployment script: only fast forward allowed, failure on fork is safer than silent merge
git pull --ff-only
Prevention and best practices
  • The team is unified in the onboarding documentpull.rebase / pull.ff。
  • Do not use it on the deployment machinegit pull, use git fetch && git reset --hard origin/mainOr deploy the build product directly.

See detailsLesson 2 Remote Branching and Tracking Relationships。

#15 The same conflict occurs repeatedly (every commit conflicts when long-term branches are repeatedly merged/rebased)
$ git rebase main
Auto-merging settings.py
CONFLICT (content): Merge conflict in settings.py
error: could not apply 1a2b3c4... feat: step 1
...
# After solving --continue, the next commit will have the same location conflict; rebase the next day and do it again

Phenomenon:Long-lived feature branches/release branches that have the same conflicts resolved every time they sync trunk.

Root cause:Rebase replays commits one by one. If there are 5 commits on the feature branch that all change the same area, there may be conflicts 5 times; and every time you rebase, Git does not remember how you solved it last time. Bidirectional merging (main → feature, feature → main multiple times) will also cause repeated conflicts with the same piece of code.

diagnostic commands
git log --oneline main..feature -- settings.py # How many commits on the feature branch have changed this file
git config --get rerere.enabled
ls .git/rr-cache 2>/dev/null | wc -l
Repair
git config --global rerere.enabled true # reuse recorded resolution: record and automatically reuse conflict resolution
git config --global rerere.autoUpdate true # Automatic add reuse solution (still needs to be checked)
# Reduce the number of conflicts at one time: first flatten the commit of the function branch itself, and then rebase it
git rebase -i --autosquash $(git merge-base main feature)
git rebase main
# Conflict is difficult to read: display common ancestor version
git config --global merge.conflictStyle zdiff3
CONFLICT (content): Merge conflict in settings.py
Resolved 'settings.py' using previous resolution.
Prevention and best practices
  • Shorten branch life (ideally < 2 days), replace long-lived branches with functional switches.
  • Synchronize the trunk in small steps frequently rather than once a month.
  • Split "hotspot files" (huge configurations, routing tables) to reduce the number of people modifying the same area at the same time.

See detailsLesson 2 Conflict Resolution and Rerere、Lesson 6 Branching Strategies。

#16 Duplicate commits appear in the history after rebase (same information, different hashes)
$ git log --oneline --graph -8
* f1e2d3c Merge branch 'feature/login' of github.com:org/myapp
|\
| * 1a2b3c4 feat: login ← original commit
* | 5d6e7f8 feat: login ← Copy after rebase
...

Phenomenon:The same change appears twice in the history; the PR shows dozens of "new" commits.

Root cause:A put the pushedfeature/loginRebase and force push; B's local is still the old commit, executegit pull(merge mode), Git merges the old commit and the new commit as two different lines. Rebase generatesnew commit(new hash), Git will not automatically recognize "this is the same change".

diagnostic commands
git log --oneline --cherry-mark --left-right HEAD...origin/feature/login # = indicates a commit with equivalent patch content
git range-diff ORIG_HEAD...HEAD # Compare two sets of commits
= 1a2b3c4 feat: login
= 5d6e7f8 feat: login
Repair
# B has not pushed the merge yet: discard the local merge, align it directly to the remote end after rebase, and then replay its own unique commit.
git reset --hard ORIG_HEAD # Go back to before pull
git rebase origin/feature/login # Old commits with the same content will be automatically skipped (same patch-id)
# Pushed: After rebasing (git rebase -i main, remove duplicates) on the PR branch --force-with-lease, and notify collaborators
Prevention and best practices
  • Branches shared by multiple people will not change the base; if you need to change the base, notify them in advance and the other party will usegit pull --rebase(The fork-point of reflog will be used to identify upstream rewrites).
  • settings pull.rebase trueMost "merge old copies" situations can be avoided.

See detailsLesson 2 Rebase。

#17 Merged into main by mistake and needs to be rolled back: error: commit X is a merge but no -m option was given.
$ git revert 7c8d9e0
error: commit 7c8d9e0 is a merge but no -m option was given.
fatal: revert failed

Phenomenon:An unfinished feature branch has been merged into main and pushed and needs to be revoked. If you directly revert the merge commit, an error will be reported; after the revert is successful, when you merge the same branch again a few weeks later, you will find that most of the changes "have not come back".

Root cause:The merge commit has two parent commits, and revert needs to know "relative to which parent commit" to calculate the reverse patch:-m 1It means taking the first parent (main at the time of merging) as the main line and undoing the changes brought in by the second parent. revert only undoescontent, not revokedhistory: Those commits are still considered "merged". When merging again, Git thinks they are already in main and will only bring in subsequent new commits.

diagnostic commands
git log --merges --oneline -5 main
git show --no-patch --format='%h %p %s' 7c8d9e0 # Two parents: the first parent is main and the second parent is feature
7c8d9e0 a3b4c5d 1a2b3c4 Merge pull request #42 from org/feature/report
Repair
git revert -m 1 7c8d9e0 # Generate "Revert "Merge pull request #42..."" Commit and push (take PR)
# When the function is completed in the future and you want to merge it again: "Undo that undo" first, and then merge the new fix.
git revert <revert commit hash > # revert the revert
git merge feature/report

GitHub's PR page has a "Revert" button, which will create a new branch and PR containing the revert; completed PRs in Azure Repos also have a Revert operation.

Prevention and best practices
  • Unfinished functions are hidden behind the function switch and merged. Rollback = turn off the switch, and there is no need to change the Git history.
  • protected main onDon'tRoll back with reset + force push: someone else may have already worked on it.
  • In the revert commit message, state the reason and "this revert needs to be reverted before merging again."

See detailsLesson 1 revert、Lesson 6 Release Branches and Hotfixes, interview questionsQ20。

#18 error: could not apply 1a2b3c4... (cherry-pick conflict / rollback hotfix failure)
$ git cherry-pick 1a2b3c4
Auto-merging app/payment.py
CONFLICT (content): Merge conflict in app/payment.py
error: could not apply 1a2b3c4... fix: rounding error in payment
hint: After resolving the conflicts, mark them with
hint: "git add/rm <pathspec>", then run
hint: "git cherry-pick --continue".
hint: You can instead skip this commit with "git cherry-pick --skip".
hint: To abort and get back to the state before "git cherry-pick",
hint: run "git cherry-pick --abort".

Phenomenon:Backport fixes on main torelease/1.4conflict; or cherry-pick a merge commitis a merge but no -m option was given; Or it succeeds but fails to compile the release branch.

Root cause:Cherry-pick uses the "parent commit of the selected commit" as the base to perform a three-way merge. If the context for repairing dependencies (pre-refactoring, function renaming) is not on the release branch, the patch will not be applied; even if the text merge is successful, the lack of semantic dependencies will cause the build to fail.

diagnostic commands
git log --oneline release/1.4..1a2b3c4^ -- app/payment.py # Repair dependent pre-commits that are not in the release branch
git diff --name-only --diff-filter=U # Conflict files
Repair
# Option 1: Continue after resolving conflicts and retain source information
git cherry-pick --continue
#Add -x next time: the commit information will be automatically appended with "(cherry picked from commit 1a2b3c4...)" for easy traceability
git cherry-pick -x 1a2b3c4
# Option 2: Pick together with previous commits (in chronological order)
git cherry-pick -x 9f8e7d6 1a2b3c4
# Option 3: Manually write an equivalent fix on the release branch (more stable when there are too many dependencies)
# Give up: git cherry-pick --abort
Prevention and best practices
  • Whether hot fixing should "repair the release branch first and then merge it back to the trunk" or "repair the trunk first and then move it back" requires team unification (Interview question Q37).
  • Keep fix commits small and independent, don't mix them with refactorings in one commit, and it will be easier to move back.
  • Move back the PR and run the full CI as well.

See detailsLesson 2 cherry-pick、Lesson 6 Release branches, hotfixes, and cherry-pick rollbacks。

#19 PR has been squashed and merged, but git branch --merged does not display it, and git branch -d reports not fully merged.
$ git fetch --prune
$ git branch --merged main
* main ← feature/login is not in the list
$ git branch -d feature/login
error: the branch 'feature/login' is not fully merged

Phenomenon:The platform shows that the PR has been merged, but the local tool thinks that the branch has not been merged; the script for cleaning up the branch does not dare to be deleted; if you continue to develop on the branch and commit the PR again, there will be a large number of conflicts with the merged content.

Root cause:What a squash merge (and a rebase merge) creates on main isnew commit, the original commit on the feature branch is not an ancestor of main .--merged with -dThe judgment is "reachability", so it is considered not merged.

diagnostic commands
git branch -vv | grep ': gone]' # The remote branch has been deleted (automatically deleted after the platform merges)
# Whether the content is already in main: construct a "squash" commit from merge-base and compare patch-id with git cherry
mb=$(git merge-base main feature/login)
git cherry main $(git commit-tree feature/login^{tree} -p $mb -m tmp) # Output "-" indicates that the equivalent content is already in main
gh pr list --state merged --head feature/login # Ask the platform directly (GitHub CLI)
  feature/login 1a2b3c4 [origin/feature/login: gone] feat: login
- 9e8d7c6b...
Repair
git branch -D feature/login # Confirm that PR has been merged before force deletion
# If you want to continue development after the merge: open a new branch based on the latest main instead of reusing the old branch
git switch -c feature/login-v2 origin/main
# Downstream branch of stacked PR: only move "own" commits to new main
git rebase --onto origin/main feature/login feature/login-ui
Prevention and best practices
  • The platform enables "automatic deletion of source branches after merging", and the localgit fetch --pruneand clean up[gone]branch.
  • Don't continue using the same branch after squashing the merge.

See detailsLesson 2 Pull Request Workflow, interview questionsQ21。

#20 fatal: refusing to merge unrelated histories
$ git pull origin main
From github.com:org/myapp
 * branch            main       -> FETCH_HEAD
fatal: refusing to merge unrelated histories

Phenomenon:local git initI started a project, checked "Add README / .gitignore / LICENSE" when creating a new repository on the platform, and then tried to connect the two; or migrate/merge two independent repositories.

Root cause:The two histories have no common ancestor (each has a root commit), and the three-way merge has no merge base. Since Git 2.9, this merge is rejected by default to prevent two unrelated projects from being accidentally merged.

diagnostic commands
git merge-base HEAD origin/main || echo "No common ancestor"
git rev-list --max-parents=0 HEAD origin/main # Two different root commits
Repair
# Confirm that you really need to connect the two pieces of history (for example, the README of platform initialization):
git pull origin main --allow-unrelated-histories # README conflicts may need to be resolved
git push -u origin main
# A cleaner way to create a new repository: Create an empty repository on the platform (do not check any initialization files) and push directly

If you intend to merge another repository into a subdirectory, considergit subtree add --prefix=libs/x <url> mainor filter-repo's--to-subdirectory-filterand then merge (Lesson 6)。

Prevention and best practices
  • When migrating existing projects, the platform repository remains empty.
  • When you see this error, stop and confirm that the remote URL is correct (git remote -v) - Many times it is pushed to the wrong repository.

See detailsLesson 1 Remote Repository、Lesson 6 Split and merge repositorys。

#21 CONFLICT (modify/delete): config.py deleted in HEAD and modified in feature.
$ git merge feature/config
CONFLICT (modify/delete): config.py deleted in HEAD and modified in feature/config.  Version feature/config of config.py left in tree.
CONFLICT (rename/delete): ...
Automatic merge failed; fix conflicts and then commit the result.

Phenomenon:One side deleted (or moved/renamed) the file, and the other side modified it. There is no conflict file<<<<<<<Mark, newbies don't know how to "solve" it.

Root cause:This istree level conflictInstead of content conflicts: Git can't decide for you whether to "keep the modified file" or "accept the deletion". Rename detection is based on content similarity (default 50%). If you rename and modify significantly at the same time, Git may not recognize that this is a rename, and the conflict will become add/add or modify/delete.

diagnostic commands
git status --short # UD / DU / AA and other status codes
git log --oneline --diff-filter=D -1 -- config.py # Who deleted it and why
git diff --find-renames=40% main...feature/config --stat # Relax the rename detection threshold and see
DU config.py
8e9f0a1 refactor: move config.py to myapp/settings/base.py
Repair
# Accept deletion (modifications need to be migrated to new location):
git rm config.py
# Manually apply the other party's modifications to the new file:
git diff $(git merge-base HEAD feature/config) feature/config -- config.py | git apply --3way --directory=. -p1 || true
# Or keep the modified file:
git add config.py
git commit
Prevention and best practices
  • Large-scale moves/renames are separated into one commit, and the content is not changed significantly in the same commit (to facilitate rename detection).
  • Make a notice on the team channel before refactoring so that branches in progress can be merged first.
  • Set if neededmerge.renameLimit, or pass when merging-X find-renames=40%。

See detailsLesson 2 Conflict Resolution。

#22 "Code is lost" after merge: a fix disappears after merge (conflict resolution gone wrong / evil merge)
The fix merged last week "fix: null check in login" is not found on main:
$ git log --oneline -S 'if user is None' -- app.py
3c4d5e6 fix: null check in login ← Commit in history
$ grep -n 'if user is None' app.py ← but not in the current code

Phenomenon:The commit is clearly in the history, but the code is missing;git blameCan't tell who deleted it.

Root cause:The most common one is that a merge chose the wrong side when resolving conflicts (git checkout --ours ., click "Accept Current" in the IDE), or use it when merging-s ours / -X ours. Changes that "do not belong to any party" introduced by merge commits (evil merges) will not appear in ordinarygit log -pin because it does not show the diff of merge commits by default.

diagnostic commands
git log --oneline -S 'if user is None' -m --first-parent -- app.py # Find the last commit that added or deleted this line on the main line (including merge)
git show --remerge-diff 7d8e9f0 # Git 2.36+: Compare "automatic merge results" and "actual commit results" to show manual conflict resolution
git log -p -m --first-parent -1 7d8e9f0 -- app.py
7d8e9f0 Merge branch 'feature/refactor'
diff --git a/app.py b/app.py
remerge CONFLICT (content): Merge conflict in app.py
-    if user is None:
-        return abort(401)
Repair
git cherry-pick -x 3c4d5e6 # Reapply missing fixes (may need to resolve conflicts)
# Or git revert a wrong merge (see #17), and then merge it correctly again
Prevention and best practices
  • After the conflict is resolved, you must run the test locally before committing it; the CI on the PR must pass (the "required status check" of branch protection).
  • Repairs require regression testing - if the code is lost, the test will fail immediately.
  • Used when reviewing merge commits--remerge-diffView manual changes.

See detailsLesson 2 Conflict Resolution、Lesson 7 bisect positioning regression。

#23 error: cannot pull with rebase: You have unstaged changes.
$ git pull --rebase
error: cannot pull with rebase: You have unstaged changes.
error: Please commit or stash them.

Phenomenon:Configuredpull.rebase=trueAfterwards, pull fails as long as the workspace is not clean (merge mode can continue as long as the modifications do not conflict).

Root cause:Rebasing requires checking out commits one by one and replaying them. You must start from a clean workspace, otherwise it will be impossible to distinguish between "your uncommitted changes" and "changes resulting from replaying".

diagnostic commands
git status --short
git config --get rebase.autoStash
Repair
git pull --rebase --autostash # This time automatic stash → rebase → stash pop
git config --global rebase.autoStash true # Automatically in the future
# Conflict during autostash recovery: modifications are still saved in the stash list, visible in git stash list, and resolved with git stash drop
Prevention and best practices
  • Turn on autostash; get used to committing WIP before pulling.
  • Note that autostash only processes modifications of tracked files. If an untracked file has the same name as a new upstream file, it will still report the untracked error #8.

See detailsLesson 2 Rebasing and stash。

#24 There are dozens of commits in the PR that don’t belong to me (the branch is based on the wrong starting point)
PR #57: feature/search → main
Commits (34) Files changed (61)
   ← Only 3 commits were written, and the remaining 31 were from develop/colleagues’ unmerged feature/old

Phenomenon:The commit list and diff of the PR are much larger than expected; reviewers cannot review; merging will bring other people's unfinished work into main.

Root cause:HEAD is not on main when creating a branch (e.g. on develop or another feature branch),git switch -c feature/searchFork from the current location, thus inheriting all commits on that branch. PR displays all commits that are "not in the target branch but in the source branch".

diagnostic commands
git log --oneline --graph origin/main..feature/search
git log --oneline --author="$(git config user.email)" origin/main..feature/search # My own commit
git merge-base --fork-point feature/old feature/search # Where to fork from
Repair
# Move only my commits "after feature/old" to main:
git rebase --onto origin/main feature/old feature/search
# When the starting point is not a branch name, use the fork point hash: git rebase --onto origin/main < The last upstream commit > feature/search
# Or interactive: git rebase -i origin/main, delete (drop) commits that do not belong to you
git push --force-with-lease
Prevention and best practices
  • Explicitly specify the starting point:git switch -c feature/search origin/main(fetch first).
  • When stacking PR (stacked PR), set the target branch of the downstream PR to the branch of the upstream PR, and merge it with the upstream PR.rebase --onto(#19)。

See detailsLesson 2 Rebase and PR workflow。

#25 Lock file/generated file conflict: CONFLICT (content): Merge conflict in package-lock.json
Auto-merging package-lock.json
CONFLICT (content): Merge conflict in package-lock.json
Auto-merging poetry.lock
CONFLICT (content): Merge conflict in poetry.lock

Phenomenon:Almost every PR conflicts on the lock file, generated code, and binary files; after manually editing the conflict mark, the lock file is damaged and CI installation dependencies fail.

Root cause:The lock file is generated by a tool. When multiple people upgrade different dependencies at the same time, the same area (or even the hash of the same line) will change; text three-party merging does not understand its semantics. Binary files (images, xlsx) cannot be text merged at all.

diagnostic commands
git diff --name-only --diff-filter=U
git check-attr merge -- package-lock.json docs/arch.png
Repair
# Lock file: Get the version of the target branch and let the tool regenerate it
git checkout --theirs package-lock.json # When merging, theirs = the merged branch; when rebase, the meaning is opposite!
npm install # or poetry lock --no-update / pip-compile
git add package-lock.json && git merge --continue
# Binary files: choose one side explicitly
git checkout --ours docs/arch.png && git add docs/arch.png
# .gitattributes: Binary does not attempt text merging; generated files are collapsed in diff
*.png binary
*.xlsx binary
package-lock.json -diff linguist-generated=true
Prevention and best practices
  • Dependency upgrades are centralized by robots (Dependabot/Renovate) to commit PRs, reducing the need for multiple people to change locked files at the same time.
  • The generated code is not committed and is generated during build; when it must be committed, "no diff after regeneration" must be verified in CI.
  • remember--ours/--theirsInverse in rebase (ours = upstream being rebased).

See detailsLesson 2 Conflict Resolution、Lesson 7 .gitattributes。

Fast-forward rule: the remote ref must be an ancestor of the new commit (#3 #13 #14 #16) A B C D origin/main (C pushed by colleagues)main (your D) push D: C is not an ancestor of D → rejectedpull --rebase: D replays as D' (parent = C) → can fast forwardpull --no-rebase: generate merge commit M (parent = D, C) Three-party mergers only look at three points: merge base, ours, and theirs • revert merge only undoes the content, the history is still "merged" → when merging again, the merge base has passed those commits (#17) • squash / rebase merge to generate new commit → original branch commit is not an ancestor of main → --merged / -d judgment invalid (#19) • No merge base → refusing to merge unrelated histories (#20)
Figure 2-1 All "push rejections/merge exceptions" can be inferred on the commit graph
rebase --onto: only move "my" commits (#19 #24) main feature/old (other people’s) feature/search(mine) --onto main feature/old main Only my 2 commits (new hashes)
Figure 2-2 git rebase --onto < new base > < old base (excluded) > < branch >

“Push/merge not right” troubleshooting decision tree

Start from the phenomenon you see, and gradually locate the specific problem and repair commands.

environmentuse ~/git-lab8Two clones of alice and bob in the directory; rerun the bootstrap script if necessary.

Experiment 2-A: Two people push at the same time (#13, #14)

bob pushes first, and alice later:
cd ~/git-lab8
(cd bob && echo "# bob" >> app.py && git commit -qam "bob: tweak" && git push -q)
cd alice && echo "alice" > NOTES.md && git add NOTES.md && git commit -qm "alice: notes"
git push 2>&1 | grep -E 'rejected|hint: Updates'
 ! [rejected]        main -> main (fetch first)
hint: Updates were rejected because the remote contains work that you do not
Observe the prompts when the pull strategy is not configured, and then use rebase to solve the problem:
git -c pull.rebase= -c pull.ff= pull 2>&1 | tail -1
git pull --rebase && git push && git log --oneline --graph -3
fatal: Need to specify how to reconcile divergent branches.
* 4e5f6a7 (HEAD -> main, origin/main) alice: notes
* 2b3c4d5 bob: tweak

If your global configuration has set pull.rebase, the first command will succeed directly; use here-cClear temporarily to observe the default behavior (handling of null values may vary from version to version).

Cleaning: No need to clean, you can continue to use it in subsequent experiments.

Experiment 2-B: Rollback merge with “revert of revert” (#17)

cd ~/git-lab8/alice && git pull -q
git merge --no-ff -q -m "Merge feature/login" origin/feature/login
git revert HEAD 2>&1 | head -1
error: commit 7c8d9e0 is a merge but no -m option was given.
git revert --no-edit -m 1 HEAD
grep -c login app.py # 0: Content has been revoked
git merge origin/feature/login # Already up to date. ← History is still considered "merged"
Undo that undo:
git revert --no-edit HEAD && grep -c login app.py # 1: Back
Cleanup:git reset -q --hard origin/main

Experiment 2-C: Rerere Reuse Conflict Resolution (#15)

git config rerere.enabled true
git switch -qc t1 && sed -i '1s/.*/from flask import Flask  # t1/' app.py && git commit -qam t1
git switch -q main && sed -i '1s/.*/from flask import Flask  # main/' app.py && git commit -qam m1
git merge t1 | tail -2
CONFLICT (content): Merge conflict in app.py
Recorded preimage for 'app.py'

macOS’s sed needs to be written assed -i ''。

sed -i -e '/^<<<<<<</d' -e '/^========/d' -e '/^>>>>>>>/d' -e '/# t1$/d' app.py # Keep the version of main
git commit -qam merged # Output Recorded resolution for 'app.py'.
git reset -q --hard HEAD~1 && git merge t1 | grep -i resolution
Resolved 'app.py' using previous resolution.
Cleanup:git merge --abort; git reset -q --hard origin/main; git branch -D t1; git config --unset rerere.enabled

Experiment 2-D: rebase --onto moves other people’s commits (#24)

git switch -qc feature/old origin/main && for i in 1 2; do echo "old $i" >> old.txt; git add old.txt; git commit -qm "old $i"; done
git switch -qc feature/search && echo "search" > search.py && git add search.py && git commit -qm "search: mine"
git log --oneline origin/main..feature/search | wc -l     # 3
git rebase -q --onto origin/main feature/old feature/search
git log --oneline origin/main..feature/search
9a8b7c6 search: mine

old.txtNo longer appears in feature/search: Two "other people's" commits were excluded.

Cleanup:git switch -q main; git branch -D feature/old feature/search

Instructional video (title and channel verified with YouTube oEmbed)

▶
Git MERGE vs REBASE: Everything You Need to Know — ByteByteGo
English · Commit graph changes for merge and rebase (corresponding to #13, #16)
▶
Git for Professionals Tutorial - Tools & Concepts for Mastering Version Control with Git — freeCodeCamp.org
English · Merge conflicts, rebase, cherry-pick, reflog
▶
So You Think You Know Git - FOSDEM 2024 — GitButler
English · Scott Chacon talks about rerere, --force-with-lease, zdiff3 and other little-known configurations
Shot 1 (0:00)Split screen left and right alice / bob, bob is pushed first, alice is rejected, highlighted(fetch first)。
Shot 2 (0:50)Commit diagram animation: D forks next to C →pull --rebaseThen D' is connected to C.
Shot 3 (1:40)Merge → revert -m 1 → merge again displays "Already up to date", and the narration explains "Content withdrawn, history retained".
Shot 4 (2:30)rerere automatically resolves conflicts for the second time. Conclusion: Long-term branches are the source of conflicts.

Official documentation

or score ≥ 70% on the Quiz

Module 3 · Part A: Remoteness, Authentication and Platforms (Questions 26–38)

16:00 – 24:00 · HTTPS and SSH authentication, permissions, protected branches, credential caching, host keys, size limits, networking and TLS
8 minutesGCM · SSH · PAT · pre-receive13 questions
learning objectives
  • Split a push into four parts:Network/TLS → Authentication (who you are) → Authorization (what you can do) → Server-side rules (pre-receive: protection branches, rule sets, push rules, size limits), and determine which section is stuck from the error report.
  • Know where HTTPS credentials come from (credential helper chain: GCM/osxkeychain/libsecret/store) and how to clear them; which key is used for SSH (ssh -vT)。
  • Familiar with typical rejection messages from GitHub, Azure Repos, GitLab, CodeCommit.

Enter the error keyword (such aspublickey、403、GH006、TF402455、413、SSL) filter; click on a row to jump to detailed explanation.

#26 remote: Support for password authentication was removed … fatal: Authentication failed for 'https://github.com/...'
Username for 'https://github.com': alice
Password for 'https://alice@github.com':
remote: Support for password authentication was removed on August 13, 2021.
remote: Please see https://docs.github.com/get-started/getting-started-with-git/about-remote-repositories#cloning-with-https-urls for information on currently recommended modes of authentication.
fatal: Authentication failed for 'https://github.com/org/myapp.git/'

Phenomenon:Failed to enter account password during HTTPS cloning/push. A similar situation on Azure DevOps isfatal: Authentication failed for 'https://dev.azure.com/org/proj/_git/myapp/'(PAT has expired, been revoked, or organizational policy prohibits PAT).

Root cause:The platform no longer accepts account passwords for Git operations and requires the use ofOAuth (browser login via Git Credential Manager)、Personal Access Token (PAT)or SSH. Authentication failure also occurs when the token expires/is revoked/is insufficient in scope.

diagnostic commands
git config --show-origin --get-all credential.helper # Which credential helper is used?
git credential-manager --version 2>/dev/null # Whether GCM is installed
GIT_TRACE=1 GIT_CURL_VERBOSE=1 git ls-remote https://github.com/org/myapp.git 2>&1 | grep -E 'HTTP/|credential' | head
file:/etc/gitconfig    manager
3.0.x
< HTTP/2 401
trace: run_command: 'git credential-manager get'
Repair
# Recommendation: Install and use Git Credential Manager (Git for Windows comes with it)
git config --global credential.helper manager # Linux also needs to configure credential.credentialStore (secretservice/gpg/cache)
git ls-remote https://github.com/org/myapp.git # Pop up the browser to complete OAuth login
# Or use PAT (fine-grained token, only granted to this repository Contents: Read and write), paste the token at the password
# Or use SSH instead: git remote set-url origin git@github.com:org/myapp.git
Prevention and best practices
  • GCM for humans (OAuth + Browser + MFA), short-lived tokens for machines (GitHub App installation tokens, workload identity federation with Azure, native CIGITHUB_TOKEN/System.AccessToken)。
  • Don't usecredential.helper store:Token written in clear text~/.git-credentials。
  • Set a minimum validity period for PAT, add calendar reminders, or switch to a method that doesn't require PAT.

See detailsLesson 3 Authentication: SSH, HTTPS, Git Credential Manager。

#27 git@github.com: Permission denied (publickey). fatal: Could not read from remote repository.
git@github.com: Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

Phenomenon:SSH clone/push failed. on Azure DevOps forgit@ssh.dev.azure.com: Permission denied (publickey).;Similar to GitLab.

Root cause:The server did not accept any public key provided by the client during the SSH handshake: the machine did not have a key, ssh-agent was not loaded, another key (such as a personal account) was provided, the public key was not added to the platform account, the key file permissions were too wide and was refused use by ssh, or~/.ssh/configThe Host alias did not match.

diagnostic commands
ssh -T git@github.com # On success: Hi alice! You've successfully authenticated...
ssh -vT git@github.com 2>&1 | grep -E 'Offering|Server accepts|identity file|Authenticated'
ssh-add -l # What keys are there in the agent?
ls -l ~/.ssh/id_* # Private key permissions should be 600
debug1: identity file /home/alice/.ssh/id_ed25519 type -1 ← -1 means the file does not exist
debug1: Offering public key: /home/alice/.ssh/id_rsa_personal RSA SHA256:...
debug1: Authentications that can continue: publickey
git@github.com: Permission denied (publickey).
Repair
ssh-keygen -t ed25519 -C "alice@corp.example.com" # Generate a new key (Azure DevOps has restrictions on key types, please refer to the official documentation)
eval "$(ssh-agent -s)" && ssh-add ~/.ssh/id_ed25519
cat ~/.ssh/id_ed25519.pub # Add to GitHub → Settings → SSH and GPG keys
# Multiple accounts: use Host alias to fix the key
cat >> ~/.ssh/config <<'EOF'
Host github-work
  HostName github.com
  User git
  IdentityFile ~/.ssh/id_ed25519_work
  IdentitiesOnly yes
EOF
git remote set-url origin git@github-work:org/myapp.git
Prevention and best practices
  • One key for each device, with a passphrase, using the agent/system keychain; only that one is revoked when you leave the company or lose the device.
  • Organizations that enable SSO need to "authorize SSO" (GitHub) individually for SSH keys.
  • Also consider hardware keys (ed25519-sk)。

See detailsLesson 3 Certification、Lesson 7 Network/Protocol Issues。

#28 remote: Permission to org/myapp.git denied to alice. … The requested URL returned error: 403
remote: Permission to org/myapp.git denied to alice.
fatal: unable to access 'https://github.com/org/myapp.git/': The requested URL returned error: 403

Phenomenon:The authentication is successful (the platform knows you are Alice), but the push is rejected. The clone may be normal (read-only permission), but the push may fail.

Root cause:Insufficient authorization. Common reasons: Only Read role; fine-grained PAT does not include this repository or does not provideContents: write;classic PAT missingreposcope (or missing when pushing workflow filesworkflowscope); the organization has SAML SSO enabled and the token is not authorized; the organization disables classic PAT; GCM cachesanother accountcredentials (look at the username in the error, see #30).

diagnostic commands
gh auth status #Who does the current token belong to and what scopes does it have?
gh api repos/org/myapp --jq .permissions # {"admin":false,"push":false,"pull":true,...}
GIT_CURL_VERBOSE=1 git push 2>&1 | grep -iE 'x-oauth-scopes|x-accepted|HTTP/' # Classic PAT will return the scope header
github.com
  ✓ Logged in to github.com account alice (keyring)
  - Token scopes: 'gist', 'read:org' ← Missing repo
{"admin":false,"maintain":false,"push":false,"triage":false,"pull":true}
Repair
  • Request the Write role from the repository administrator (or grant it through the team).
  • Regenerate the token: Fine-grained PAT selects the repository and grants Contents read and write; the SSO organization clicks "Configure SSO → Authorize" on the token page.
  • Clear cached credentials for the wrong account and try again (#30).
Prevention and best practices
  • Authorize through teams/groups, no direct authorization to individuals; regular access review.
  • Automate using GitHub App or deployment keys (single repository, read-only) without personal PAT.

See detailsLesson 3 GitHub Repository and Permissions。

#29 Protected branch rejection: GH006 Protected branch update failed / TF402455 / You are not allowed to push code to protected branches
# GitHub branch protection
remote: error: GH006: Protected branch update failed for refs/heads/main.
remote: error: Changes must be made through a pull request.
 ! [remote rejected] main -> main (protected branch hook declined)

#GitHub ruleset
remote: error: GH013: Repository rule violations found for refs/heads/main.
remote: - Changes must be made through a pull request.
 ! [remote rejected] main -> main (push declined due to repository rule violations)

#Azure Repos branch strategy
 ! [remote rejected] main -> main (TF402455: Pushes to this branch are not permitted; you must use a pull request to update this branch.)

#GitLab
remote: GitLab: You are not allowed to push code to protected branches on this project.
 ! [remote rejected] main -> main (pre-receive hook declined)

Phenomenon:There are no problems with authentication and permissions, but pushing directly to main (or forcing a push or deleting a branch) is rejected.

Root cause:The server runs after receiving the object and before updating refpre-receiveCheck (the platform implements branch protection/rule sets/branch strategies at this stage). Rules require merging via PR/MR, disallow push, require signed commits or linear history, etc.

diagnostic commands
gh api repos/org/myapp/rules/branches/main --jq '.[].type' # GitHub: Rules (including rule sets) that apply to this branch
az repos policy list --branch main --repository-id <id> -o table # Azure DevOps CLI
git log --oneline origin/main..HEAD # The commit you want to push directly
pull_request
required_status_checks
non_fast_forward
deletion
Repair
git switch -c fix/readme # Put the commit into the new branch
git push -u origin fix/readme # Create PR / MR after push
git switch main && git reset --hard origin/main # Let the local main be consistent with the remote one

The "bypass" in emergency situations should be an explicitly configured bypass role on the platform (GitHub ruleset bypass list, Azure Repos' "Bypass policies when pushing" permission) with an audit trail, rather than temporarily turning off protection.

Prevention and best practices
  • Local pre-commit/pre-push hooks for early warning (#1).
  • Prioritize the use of GitHub rulesets (hierarchical, organizationally unified, supports "evaluate" mode to observe first).

See detailsLesson 3 Azure Repos branch policy, GitHub ruleset、Lesson 4 GitLab Protected Branches。

#30 GCM / Keychain caches the credentials of the wrong account (still gets 403 after changing the account, or never prompts for input)
$ git push
remote: Permission to org/myapp.git denied to alice-personal. ← Not a work account
fatal: unable to access 'https://github.com/org/myapp.git/': The requested URL returned error: 403

Phenomenon:There are two personal and work accounts on the same computer; or the PAT has been changed and Git is still using the old one; the login window never pops up.

Root cause:Credential Assistant Pressprotocol + host(Default does not include path) Cache credentials, all github.com repositories share the same one. Credential Manager exists for Windows, Keychain (osxkeychain or GCM) for macOS, and libsecret/gpg/cache for Linux. As long as it's in the cache, Git won't ask you again.

diagnostic commands
git config --show-origin --get-all credential.helper
printf 'protocol=https\nhost=github.com\n\n' | git credential fill # will print out the cached username and token, be careful not to leak them
git credential-manager github list 2>/dev/null # GCM 2.1+: List logged-in GitHub accounts
Repair
# Make all credential helpers "forget" the credentials for this host
printf 'protocol=https\nhost=github.com\n\n' | git credential reject
# GCM: git credential-manager github logout alice-personal
# Windows: Control Panel → Credential Manager → Windows Credentials → Remove git:https://github.com
# macOS: Search github.com in keychain access and delete
# Long-term solution for multiple accounts: distinguish credentials by path, or include username in URL
git config --global credential.https://github.com.useHttpPath true
git remote set-url origin https://alice-work@github.com/org/myapp.git
Prevention and best practices
  • Use SSH Host aliases (#27) for work and personal accounts respectively or write the username in the URL.
  • Execute immediately after rotating PATgit credential reject。

See detailsLesson 3 Git Credential Manager。

#31 @@@ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@    WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!     @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!
Someone could be eavesdropping on you right now (man-in-the-middle attack)!
It is also possible that a host key has just been changed.
The fingerprint for the RSA key sent by the remote host is
SHA256:uNiVztksCsDhcc0u9e8BujQXVUpKZIDTMczCvj3tD2s.
Please contact your system administrator.
Add correct host key in /home/alice/.ssh/known_hosts to get rid of this message.
Offending RSA key in /home/alice/.ssh/known_hosts:3
Host key for github.com has changed and you have requested strict checking.
Host key verification failed.

Phenomenon:SSH push suddenly fails. Real case: GitHub changed the RSA host key on 2023-03-24, and all clients that cached the old key saw this warning; it is also common after self-built GitLab servers are reinstalled and load balancing is switched.

Root cause:When SSH connects for the first time, record the server public key inknown_hosts(TOFU); Afterwards, the key presented by the server is different, and SSH cannot distinguish between "legitimate replacement" and "man-in-the-middle attack", so the connection is refused.

diagnostic commands
ssh-keygen -F github.com # The key recorded in known_hosts
ssh-keyscan -t ed25519,rsa github.com 2>/dev/null | ssh-keygen -lf - # The fingerprint currently presented by the server
# Compare with the fingerprints officially announced by the platform (GitHub: docs.github.com → GitHub's SSH key fingerprints; you can also curl https://api.github.com/meta)
Repair
# Only after confirming that the new fingerprint is consistent with the official announcement:
ssh-keygen -R github.com
ssh -T git@github.com # Check the fingerprint of the prompt again and enter yes
# Or directly write the officially announced key (the enterprise environment can uniformly issue known_hosts through configuration management)
Prevention and best practices
  • neveruse StrictHostKeyChecking noBypass (same in CI); official known_hosts are preset in CI.
  • Inconsistent fingerprints and no announcements from the platform: There may really be a man-in-the-middle (corporate proxy, rogue Wi-Fi), stop pushing and report to security team.

See detailsLesson 3 SSH Authentication、Lesson 7 Network/Protocol Issues。

#32 remote: error: GH001: Large files detected. … exceeds GitHub's file size limit of 100.00 MB
remote: error: Trace: 8a9b...
remote: error: See https://gh.io/lfs for more information.
remote: error: File data/model.bin is 245.12 MB; this exceeds GitHub's file size limit of 100.00 MB
remote: error: GH001: Large files detected. You may want to try Git Large File Storage - https://git-lfs.github.com.
 ! [remote rejected] main -> main (pre-receive hook declined)

Phenomenon:Push rejected; even if latergit rmI committed this document again, but it was still rejected. GitHub gives a warning for files above 50 MB and rejects files above 100 MB; the limits of GitLab and Azure Repos can be configured in the administrator settings (subject to the official documentation).

Root cause:Server side checkAll objects pushed this time. The large file exists in a commit in the history, and deleting its new commit will not make the blob in the old commit disappear.

diagnostic commands
# What large objects are in the commit to be pushed?
git rev-list --objects @{u}..HEAD \
 | git cat-file --batch-check='%(objecttype) %(objectname) %(objectsize) %(rest)' \
 | awk '$1=="blob" && $3 > 50*1024*1024 {printf "%.1f MB %s\n", $3/1048576, $4}'
245.1 MB data/model.bin
Repair
# Not yet pushed successfully: remove large files from these local commits and track them to LFS instead
git lfs install
git lfs migrate import --include="*.bin" --include-ref=refs/heads/main # Rewrite local unpushed history and convert *.bin to LFS pointer
git push
# The file should not be entered into the repository: git rebase -i edit the commit that introduced it, git rm --cached data/model.bin, add .gitignore
Prevention and best practices
  • The project started at.gitattributesLFS rules declared in (git lfs track "*.bin")。
  • pre-commitcheck-added-large-filesHooks are intercepted locally.
  • Large files such as models and data sets are more suitable for object storage/product libraries, and only references and checksums are placed in the repository.

See detailsLesson 6 LFS、Lesson 7 filter-repo Cleaning Large Files。

#33 error: RPC failed; HTTP 413 curl 22 The requested URL returned error: 413 / send-pack: unexpected disconnect
Enumerating objects: 15234, done.
Writing objects: 100% (15234/15234), 1.21 GiB | 22.4 MiB/s, done.
error: RPC failed; HTTP 413 curl 22 The requested URL returned error: 413
send-pack: unexpected disconnect while reading sideband packet
fatal: the remote end hung up unexpectedly
Everything up-to-date

Phenomenon:Fails when pushing a large repository (migration) for the first time or when pushing a large number of commits at once; when cloningerror: RPC failed; curl 92 HTTP/2 stream 5 was not closed cleanly / early EOF。

Root cause:413 is "Payload Too Large" at the HTTP layer:Intermediate reverse proxy/load balancing(nginx client_max_body_size, enterprise agent, LB before building your own GitLab) or the platform has limits on the size of a single push (for example, GitHub’s single push limit is 2 GB).curl 92/early EOFMostly due to network instability, HTTP/2 intermediate device issues or timeouts.

diagnostic commands
git count-objects -vH # Repository volume
GIT_TRACE_CURL=1 GIT_TRACE_CURL_NO_DATA=1 git push 2>&1 | grep -E '^.*(< HTTP|server:|via:)' | head
git config --get http.version
Repair
# Push in batches: push a piece of history each time (commonly used when migrating large repositorys)
for c in $(git rev-list --reverse main | awk 'NR % 2000 == 0'); do git push origin $c:refs/heads/main; done
git push origin main
# HTTP/2 intermediary issue: temporary downgrade
git -c http.version=HTTP/1.1 push
# Switching to SSH can often bypass the size limit of the HTTP proxy
#Self-built service: increase nginx client_max_body_size / LB timeout

Common on the Internethttp.postBuffer=524288000 Usually can'tFix 413: It only controls the client buffer size (avoiding chunked transfer encoding), has no effect on server or proxy restrictions, and will increase memory usage (the git-config documentation clearly states this).

Prevention and best practices
  • Clean large files in history before migration (#45, filter-repo).
  • Use LFS for large files; very large binaries cannot be entered into Git.

See detailsLesson 7 Performance Diagnostics and Network/Protocol Issues、Lesson 6 Repository Migration。

#34 fatal: unable to access '…': SSL certificate problem: unable to get local issuer certificate
fatal: unable to access 'https://github.com/org/myapp.git/': SSL certificate problem: unable to get local issuer certificate

Phenomenon:HTTPS cloning fails under the company network but works fine at home; or you can build your own GitLab/Azure DevOps Server and use a certificate issued by an internal CA. Variations:SSL certificate problem: self-signed certificate in certificate chain。

Root cause:The enterprise TLS inspection agent reissues the certificate with its own root CA (man-in-the-middle decryption), or the server uses an internal CA; the CA certificate bundle used by Git (OpenSSL's ca-bundle) does not have this root certificate. Git on Windows can use OpenSSL or Schannel (system certificate store) by default.

diagnostic commands
GIT_CURL_VERBOSE=1 git ls-remote https://github.com/org/myapp.git 2>&1 | grep -iE 'issuer|subject|CAfile'
openssl s_client -connect github.com:443 -servername github.com </dev/null 2>/dev/null | openssl x509 -noout -issuer
* issuer: CN=Corp TLS Inspection CA; O=Example Corp ← It is not a public network CA, indicating that there is an intermediary agent
* CAfile: /etc/ssl/certs/ca-certificates.crt
Repair
# Linux: Add the enterprise root certificate to the system trust store
sudo cp corp-root-ca.crt /usr/local/share/ca-certificates/ && sudo update-ca-certificates
# Or specify the CA package for Git only (can be scoped by URL)
git config --global http.https://gitlab.corp.example.com/.sslCAInfo /etc/ssl/certs/corp-root-ca.pem
# Windows: Use the system certificate store (the enterprise root certificate is usually issued by group policy)
git config --global http.sslBackend schannel

Don'tuse http.sslVerify=falseorGIT_SSL_NO_VERIFY=1: This exposes credentials and code to any intermediary.

Prevention and best practices
  • The development machine and CI image are pre-installed with the enterprise root certificate.
  • Negotiate with the network team to add Git platform domains to the exemption list for TLS inspection.

See detailsLesson 7 Network/Protocol Issues、Lesson 3 Certification。

#35 Failed to connect to github.com port 443 after 21045 ms: Couldn't connect to server / ssh: connect to host github.com port 22: Connection timed out
fatal: unable to access 'https://github.com/org/myapp.git/': Failed to connect to github.com port 443 after 21045 ms: Couldn't connect to server
---
ssh: connect to host github.com port 22: Connection timed out
fatal: Could not read from remote repository.

Phenomenon:The network can access the web page but the Git connection times out; or SSH (port 22) is blocked by the firewall; or the local machine has an expired proxy.

Root cause:Browsers use PAC/system proxy while Git only readshttp.proxyconfiguration andhttps_proxy/HTTPS_PROXYEnvironment variables; corporate firewalls often block outbound port 22; DNS resolution errors or IPv6 routing issues can also cause timeouts.

diagnostic commands
git config --show-origin --get-regexp 'proxy'; env | grep -i _proxy
curl -sv https://github.com -o /dev/null 2>&1 | grep -E 'Connected|Trying|proxy'
ssh -T -p 443 git@ssh.github.com # GitHub also provides SSH on port 443
Repair
# Access HTTPS through enterprise proxy (only set for required domain names)
git config --global http.https://github.com.proxy http://proxy.corp.example.com:8080
# 22 Blocked: SSH over 443
cat >> ~/.ssh/config <<'EOF'
Hostgithub.com
  HostName ssh.github.com
  Port 443
  User git
EOF
# Invalid proxy: git config --global --unset http.proxy; unset https_proxy HTTPS_PROXY
Prevention and best practices
  • The proxy configuration is limited by URL to avoid using the internal network Git service through the external network proxy (or settingno_proxy)。
  • The agent of CI self-hosted runner is uniformly configured through environment variables and written into the runbook.

See detailsLesson 7 Network/Protocol Issues。

#36 remote: Repository not found. / TF401019: The Git repository with name or identifier X does not exist or you do not have permissions
remote: Repository not found.
fatal: repository 'https://github.com/org/myap.git/' not found
---
remote: TF401019: The Git repository with name or identifier myapp does not exist or you do not have permissions for the operation you are attempting.
fatal: repository 'https://dev.azure.com/org/proj/_git/myapp/' not found

Phenomenon:The repository obviously exists, but it says it cannot be found.

Root cause:platform pairPrivate repository without accessReturns "doesn't exist" (to avoid revealing the existence of the private repository), so the message could either be that the URL is misspelled/the repository has been renamed or moved, or that the current credentials do not have access (including GCM caching another account, #30). The URL for Azure DevOps also contains the organization and project names, and if you write them incorrectly, it will fail.

diagnostic commands
git remote -v
gh repo view org/myapp --json name,visibility 2>&1 | head -3 # View with the current gh identity
az repos show -r myapp --project proj --org https://dev.azure.com/org --query remoteUrl
Repair
  • Fix URL:git remote set-url origin https://github.com/org/myapp.git. GitHub will automatically redirect renamed/transferred repositorys, but it is best to update to the new address.
  • Confirm that the account has been added to the repository/project; clear the credentials of the wrong account (#30); SSO organizes the token authorization (#28).
Prevention and best practices
  • When the repository is renamed or migrated, leave a README guide in the old location and notify the CI maintainer to update the URL.
  • Use platform-provided checkout steps and tokens in CI instead of hard-coded URLs and personal credentials.

See detailsLesson 3: Practical troubleshooting on the platform side。

#37 Push rule/rule set rejection: Commits must have verified signatures, commit information or author email does not comply with the rules
# GitHub ruleset: require signed commits
remote: error: GH013: Repository rule violations found for refs/heads/feature/login.
remote: - Commits must have verified signatures.
remote: Found 1 violation:
remote: 1a2b3c4d...
# GitLab push rules (Premium/Ultimate): commit information regularity
remote: GitLab: Commit message does not follow the pattern '^(feat|fix|docs|chore)(\(.+\))?: .+'
# GitLab: The author's email must belong to the domain name
remote: GitLab: Committer's email 'alice@gmail.com' does not follow the pattern '@corp\.example\.com$'

Phenomenon:The push of the ordinary feature branch was also rejected because the committed metadata (signature, information, email, file name) did not comply with the organizational rules.

Root cause:The platform checks the metadata of each new commit during the pre-receive phase. The rule checks forAll pushed commits, not just the latest one.

diagnostic commands
git log --format='%h %G? %ae %s' @{u}..HEAD # %G?: G=valid signature, N=no signature, U/E=cannot be verified
git config --get commit.gpgsign; git config --get gpg.format
1a2b3c4 N alice@gmail.com update stuff
Repair
# After correcting the identity and signature, rewrite the commits that have not yet been merged
git config user.email alice@corp.example.com
git config gpg.format ssh; git config user.signingkey ~/.ssh/id_ed25519.pub; git config commit.gpgsign true
git rebase @{u} --exec 'git commit --amend --no-edit --reset-author -S'
# Modify commit information: git rebase -i @{u}, change pick to reword
git push --force-with-lease

To display Verified on GitHub, the same SSH public key needs to beSigning keyThe type is added again (the authentication key and signing key are registered separately).

Prevention and best practices
  • Move the rules forward to the local: commit-msg hook (commitlint), pre-commit; enable globallycommit.gpgsign。
  • New rules run in "evaluate/audit only" mode for a period of time (Evaluate is supported in GitHub rulesets) before being enforced.

See detailsLesson 4 GitLab Push Rules、Lesson 5 Signatures and Conventional Commits。

#38 AWS CodeCommit: The requested URL returned error: 403 (macOS Keychain cached expired temporary credentials)
fatal: unable to access 'https://git-codecommit.ca-central-1.amazonaws.com/v1/repos/myapp/': The requested URL returned error: 403

Phenomenon:Yesterday I was able to push, but today I got 403; or it failed only on macOS; or I still used the old identity after changing the AWS profile.

Root cause:Use the AWS CLI Credential Assistant (aws codecommit credential-helper), Git temporarily generates a signing password each time it requests (based on temporary credentials, which will expire); if macOS's osxkeychain credential assistant is ranked first, it willTemporary password cacheCome down and continue to return 403 after expiration. Also the IAM policy is missingcodecommit:GitPush, or SSO session expired, also 403.

diagnostic commands
git config --show-origin --get-all credential.helper # Whether there is osxkeychain ranked before codecommit
aws sts get-caller-identity --profile lab # Whether the current AWS identity/SSO session is valid
aws codecommit get-repository --repository-name myapp --region ca-central-1 --profile lab --query repositoryMetadata.Arn
Repair
# Recommendation: Use git-remote-codecommit (directly uses AWS credential chain, supports SSO and roles, without going through the credential assistant)
pip install git-remote-codecommit
git remote set-url origin codecommit::ca-central-1://lab@myapp # lab is AWS profile
aws sso login --profile lab && git push
# When continuing to use HTTPS + credential helper: remove the git-codecommit entry from the keychain and disable osxkeychain for this host
git config --global credential.https://git-codecommit.ca-central-1.amazonaws.com.helper ''
git config --global --add credential.https://git-codecommit.ca-central-1.amazonaws.com.helper '!aws codecommit credential-helper $@'
git config --global credential.https://git-codecommit.ca-central-1.amazonaws.com.UseHttpPath true

CodeCommit stopped accepting new customers in 2024-07, and announced that it would be fully available again in 2025-11; subsequent features (such as Git LFS support) are subject to AWS "What's New" and user guides.

Prevention and best practices
  • People use IAM Identity Center (SSO) + git-remote-codecommit, without using the Git credentials of the long-term IAM user.
  • CI uses the OIDC assumed role to obtain temporary credentials.

See detailsLesson 4 CodeCommit: Authentication and git-remote-codecommit。

Four levels of a git push, and typical error reports for each level ① Network/TLSDNS · Proxy · Certificate · known_hosts ② Authentication: Who are you?GCM/OAuth · PAT · SSH keys ③ Authorization: What can you do?Role · Token Scope · SSO ④ Server-side rulespre-receive: protection/ruleset/size #34 SSL certificate problem#35 Failed to connect / timed out#31 HOST IDENTIFICATION CHANGED#33 413 / unexpected disconnect #26 Authentication failed#27 Permission denied (publickey)#30 Wrong account cached#38 CodeCommit temporary credentials expire #28 Permission … denied (403)#36 Repository not foundTF401019 #29 GH006 / GH013 / TF402455#32 GH001 Large files#37 Signature/commit message rules#4 Push Protection (Confidential) Judgment skills: only fatal: no remote: → first two levels; remote: text appears → at least passed the authentication, see level ③④
Figure 3-1 Locate the level first, then check the reason
Where do HTTPS credentials come from (#26 #30 #38) git push credential.helper chainAsk get one by one in the order of configurationThe first one to return credentials wins GCM: OAuth browser login Keychain/Credential Manager Cache store: plain text ~/.git-credentials Platform401 → reject(clear)
Figure 3-2 Git calls approve (save) when authentication is successful, and reject (delete) when 401 is issued; however, 403 does not trigger deletion, so the credentials of the wrong account will always be retained.

"push/clone failed" troubleshooting decision tree

Step by step investigation according to the four levels; each conclusion can jump to the corresponding question.

environmentExperiments 3-A, 3-B fully local (usingremote.gitServer-side hook simulation platform rules); Experiment 3-C requires a GitHub test repository, which will be deleted after completion.

Experiment 3-A: Simulating protected branches with pre-receive hooks (#29)

Install the hook in the bare repository:
cd ~/git-lab8
cat > remote.git/hooks/pre-receive <<'EOF'
#!/usr/bin/env bash
zero=0000000000000000000000000000000000000000
while read old new ref; do
  if [ "$ref" = "refs/heads/main" ]; then
    echo "LAB8: Protected branch update failed for $ref."
    echo "LAB8: Changes must be made through a pull request."
    exit 1
  fi
  if [ "$new" = "$zero" ] && [[ "$ref" == refs/heads/release/* ]]; then
    echo "LAB8: Cannot delete release branches."; exit 1
  fi
done
EOF
chmod +x remote.git/hooks/pre-receive
Push main directly:
cd alice && git pull -q && git commit -q --allow-empty -m "direct to main" && git push
remote: LAB8: Protected branch update failed for refs/heads/main.
remote: LAB8: Changes must be made through a pull request.
To /home/alice/git-lab8/remote.git
 ! [remote rejected] main -> main (pre-receive hook declined)

Consistent with GitHub/GitLab's rejection format: server output withremote:prefix, ref status isremote rejected。

Repair according to platform process:
git switch -c fix/direct && git push -u origin fix/direct
git switch main && git reset -q --hard origin/main
Cleanup:rm ~/git-lab8/remote.git/hooks/pre-receive; git push origin --delete fix/direct; git branch -D fix/direct

Experiment 3-B: Simulating "Large File Rejection" (#32)

Limit single blob size (5 MB) with hook:
cat > ~/git-lab8/remote.git/hooks/pre-receive <<'EOF'
#!/usr/bin/env bash
while read old new ref; do
  range="$new"; [ "$old" != 0000000000000000000000000000000000000000 ] && range="$old..$new"
  git rev-list --objects $range --not --all 2>/dev/null \
   | git cat-file --batch-check='%(objecttype) %(objectsize) %(rest)' \
   | awk '$1=="blob" && $2>5242880 {print "LAB8: File " $3 " exceeds 5 MB"; bad=1} END{exit bad}' || exit 1
done
EOF
chmod +x ~/git-lab8/remote.git/hooks/pre-receive

The new object is already in the quarantine when pre-receive is run,--not --allObjects that already have reachable references are excluded.

cd ~/git-lab8/alice && git switch -qc feature/model
head -c 8000000 /dev/urandom > model.bin && git add model.bin && git commit -qm "add model"
git rm -q model.bin && git commit -qm "remove model" # It is useless to delete it
git push -u origin feature/model 2>&1 | grep -E 'LAB8|rejected'
remote: LAB8: File model.bin exceeds 5 MB
 ! [remote rejected] feature/model -> feature/model (pre-receive hook declined)
Fix: Remove these two commits from history:
git reset -q --hard main && git push -u origin feature/model
Cleanup:rm ~/git-lab8/remote.git/hooks/pre-receive; git switch main; git branch -D feature/model; git push origin --delete feature/model

Lab 3-C: Diagnosing which key is used for SSH (#27, GitHub account required)

ssh -vT git@github.com 2>&1 | grep -E 'Offering|Server accepts|Authenticated to|Hi '
debug1: Offering public key: /home/alice/.ssh/id_ed25519 ED25519 SHA256:...
debug1: Server accepts key: /home/alice/.ssh/id_ed25519 ED25519 SHA256:...
Authenticated to github.com ([140.82.x.x]:22) using "publickey".
Hi alice! You've successfully authenticated, but GitHub does not provide shell access.
Deliberately using an unregistered key:
ssh-keygen -q -t ed25519 -N '' -f /tmp/lab8_key
ssh -T -i /tmp/lab8_key -o IdentitiesOnly=yes git@github.com
git@github.com: Permission denied (publickey).
Cleanup:rm -f /tmp/lab8_key /tmp/lab8_key.pub

Instructional video (title and channel verified with YouTube oEmbed)

▶
Git and GitHub for Beginners - Crash Course — freeCodeCamp.org
English · Complete demo with SSH key generation and adding to GitHub (corresponds to #27)
▶
Git and GitHub Tutorial for Beginners — Kevin Stratvert
English · Git and GitHub certification process on Windows

No verified videos found specifically covering protected branch denial, GCM credential cleansing, and enterprise TLS proxy troubleshooting. The breakdown is as follows:

Shot 1 (0:00)Figure 3-1 Four levels of animation, each level lights up corresponding to an error report.
Shot 2 (0:50) ssh -vTThe output highlights Offering / Server accepts and demonstrates multi-account Host aliases.
Shot 3 (1:40)Local pre-receive hook rejects main push, compare GitHub's GH006 to Azure's TF402455.
Shot 4 (2:30) git credential rejectClear the wrong account and re-push successfully.

Official documentation

or score ≥ 70% on the Quiz

Module 4 · Part A: Large Repositorys, Performance, CI, and Security (Questions 39–50)

24:00 – 30:00 · Clone performance, LFS, submodules, shallow cloning, newlines, case, size, signatures, ownership, hooks, history rewriting
6 minutespartial clone · LFS · safe.directory12 questions
learning objectives
  • Know the difference between CI checkout and developer local cloning: shallow cloning (--depth), partial clone (--filter), whether to pull the tag / LFS / submodule, the user and file ownership in the container.
  • understand .gitattributesdriven filter mechanism (text/eolNewline conversion, LFS clean/smudge), can explain the problem of "wrong file content".
  • Able to handle team collaboration issues such as repository volume expansion and history rewriting.

Enter keywords (such asdescribe、lfs、submodule、CRLF、dubious、gpg) filter; click on a row to jump to detailed explanation.

#39 git clone is too slow/times out (tens of GB repository, cross-continental network)
$ time git clone https://github.com/org/monorepo.git
Cloning into 'monorepo'...
remote: Enumerating objects: 4831022, done.
Receiving objects:  37% (1787478/4831022), 6.12 GiB | 3.40 MiB/s
...
real    41m12s

Phenomenon:Cloning takes one hour for new employees on the first day; CI checkout takes several minutes each time;git statusAlso very slow.

Root cause:By default the clone will downloadAll files in all histories, all versions. The large binaries, generated files, and vendor directories in history make the packfile huge; when the number of working tree files is large (hundreds of thousands), status/checkout needs to scan the entire working tree.

diagnostic commands
git count-objects -vH # size-pack: object library size
git ls-files | wc -l # Number of working tree files
# git-sizer (GitHub open source tool) gives indicators such as the largest blob, the deepest tree, and the most files.
git-sizer --verbose | head -30
Repair
# 1) Partial cloning: do not download the file content (blob) first, obtain it on demand during checkout, and retain the complete commit history
git clone --filter=blob:none https://github.com/org/monorepo.git
# 2) Sparse checkout (cone mode): only check out the required directories
git clone --filter=blob:none --sparse https://github.com/org/monorepo.git && cd monorepo
git sparse-checkout set services/payment libs/common
# 3) One-time build (CI): shallow cloning
git clone --depth=1 --single-branch -b main https://github.com/org/monorepo.git
# 4) Recommended configuration collection for large repositorys: scalar (released with Git)
scalar clone https://github.com/org/monorepo.git # Partial clone + sparse checkout + background maintenance + fsmonitor, etc.
# 5) Already cloned: enable background maintenance and file system monitoring
git maintenance start; git config core.fsmonitor true; git config core.untrackedCache true
Prevention and best practices
  • Large files are entered into LFS or product library; generated files are not committed.
  • Developers use partial clones (preserves history, suitable for blame/log); CI uses shallow clones (build only) - be aware of the side effects of shallow clones (#42).
  • core.fsmonitorThe built-in daemon currently supports Windows and macOS (subject to the git-config document).

See detailsLesson 6 Large repository: LFS, partial clone, sparse checkout, scalar、Lesson 7 Performance Diagnostics。

#40 The file content becomes “version https://git-lfs.github.com/spec/v1 / oid sha256:… / size …” (LFS pointer file)
$ cat assets/logo.png
version https://git-lfs.github.com/spec/v1
oid sha256:4d7a214614ab2935c943f9e0ff69d22eadbb8f32b1258daaa5e2ca24d17e2393
size 128734
$ pythontrain.py
_pickle.UnpicklingError: invalid load key, 'v'. ← Pointer text is read

Phenomenon:The image cannot be opened, the model fails to load, and the file in the Docker image is only 130 bytes. Problem in the opposite direction:Encountered 3 file(s) that should have been pointers, but weren't:(Files that should go to LFS are committed as ordinary files).

Root cause:LFS passed.gitattributesinfilter=lfsImplementation: When committing, the clean filter uploads the content to LFS storage and stores it in Gitpointer;The smudge filter downloads the real content replacement pointer when checking out. git-lfs is not installed/initialized on the machine (git lfs install), LFS is not enabled when CI checkout (actions/checkout defaultlfs: false), or setGIT_LFS_SKIP_SMUDGE=1, you will only get the pointer.

diagnostic commands
git lfs env | head -5 # Whether to install and what is the endpoint?
git check-attr filter -- assets/logo.png # filter: lfs
git lfs ls-files | head # * means downloaded, - means only pointer
git lfs fsck # Check pointers and objects
assets/logo.png: filter: lfs
4d7a214614 - assets/logo.png ← "-": pointer only
Repair
git lfs install # Register filters in ~/.gitconfig (once per machine)
git lfs pull # Download the LFS object required for the current checkout and replace the pointer
# GitHub Actions: - uses: actions/checkout@v7 with: { lfs: true } (version is subject to Marketplace)
# Azure Pipelines: steps: - checkout: self lfs: true
# Fix "should be a pointer but isn't":
git add --renormalize . && git commit -m "chore: move files to LFS per .gitattributes"
Prevention and best practices
  • The README states that git-lfs is required; the development container/CI image is pre-installed.
  • Note that LFS bandwidth and storage quotas (GitHub, Azure Repos, and GitLab are different, please refer to the official documentation); CI cache.git/lfs。
  • Not required in DockerfileCOPYLFS's repository is not pulled; before buildinggit lfs pull。

See detailsLesson 6 LFS、Lesson 5 Checkout in CI。

#41 The submodule directory is empty / fatal: No url found for submodule path 'libs/auth' in .gitmodules
$ ls libs/auth
$ ← empty directory
$ git submodule update --init
fatal: No url found for submodule path 'libs/auth' in .gitmodules
---
CI: fatal: could not read Username for 'https://github.com': terminal prompts disabled
    fatal: clone of 'https://github.com/org/auth.git' into submodule path 'libs/auth' failed

Phenomenon:After cloning, the submodule directory is empty, and the build reports that the file cannot be found; after switching branches, the submodule stops at the old version (git status show modified: libs/auth (new commits)); Private submodule cloning failed in CI.

Root cause:The parent repository only records submodulesgitlink(some commit hash) and.gitmodulesURL in, default clone/checkoutNoGet submodule content recursively.No url foundIt shows that there is gitlink in the index but.gitmodulesMissing entries (someone directly put a nested repositorygit addwent in). CI tokens are usually only valid for the current repository and cannot access another private repository.

diagnostic commands
git submodule status # Prefix - uninitialized, + The checked-out commit is inconsistent with the one recorded in the parent repository
git ls-files -s libs/auth # mode 160000 = gitlink
cat .gitmodules
-7a8b9c0d1e2f... libs/auth
160000 7a8b9c0d1e2f... 0	libs/auth
Repair
git submodule update --init --recursive
git config --global submodule.recurse true # Automatically update submodules after checkout/pull
# Missing .gitmodules entry: re-add it correctly
git rm --cached libs/auth && git submodule add https://github.com/org/auth.git libs/auth
# CI (GitHub Actions): actions/checkout set submodules: recursive, and provide a token (ssh-key or GitHub App token) that can read the submodule repository.
# You can also use relative URLs (../auth.git) in .gitmodules to allow submodules to inherit the protocol and host of the parent repository.
Prevention and best practices
  • Team documentation statesgit clone --recurse-submodules。
  • Assessing whether submodules are really needed: a package manager (npm/pip private sources) or subtree is often easier (Interview question Q42).

See detailsLesson 6 Submodules and subtrees。

#42 CI shallow clone lacks history: fatal: No names found, cannot describe anything. / unknown revision origin/main
$ git describe --tags
fatal: No names found, cannot describe anything.
---
$ git diff --name-only origin/main...HEAD
fatal: ambiguous argument 'origin/main...HEAD': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions, like this:
'git <command> [<revision>...] -- [<file>...]'
---
$ git merge-base origin/main HEAD
fatal: Not a valid object name origin/main (or: no output, exit code 1)

Phenomenon:The local environment is normal, but the version number calculation (setuptools-scm, GitVersion, semantic-release) in CI fails or gets0.0.0; monorepo's "change detection" thinks all files have changed or nothing has changed; SonarQube's blame information is missing.

Root cause:CI defaults to shallow cloning for speed: GitHub Actionsactions/checkout Default fetch-depth: 1(Only take one commit, no tag, only the current ref); GitLab CI defaultGIT_DEPTHis 20 (default value for new projects, subject to documentation); Azure Pipelines new pipelines also enable shallow fetching by default (subject to documentation). History is truncated, tags and target branches are not local,describe with merge-baseThe required commit cannot be found.

diagnostic commands
git rev-parse --is-shallow-repository      # true
git rev-list --count HEAD                  # 1
git tag | wc -l; git branch -r
Repair
# Option 1: Get the complete history (the simplest, suitable for small and medium-sized repositorys)
# GitHub Actions: uses: actions/checkout@v7 with: { fetch-depth: 0 }
# GitLab CI: variables: { GIT_DEPTH: "0" }
# Azure Pipelines: - checkout: self fetchDepth: 0
# Option 2: Only fill in the necessary parts
git fetch --unshallow # Complete history
git fetch --tags --force # Only add tags
git fetch --no-tags --depth=50 origin main:refs/remotes/origin/main # Only fetch the target branch for merge-base
git fetch --deepen=100 # Gradually deepen until merge-base is found
Prevention and best practices
  • Jobs that require history (version calculations, change detection, releases) have an explicitly set depth; build-only jobs remain shallow clones.
  • For large repository--filter=blob:none+ Full commit history, than--depth=0Much cheaper.
  • In the PR event, GitHub checks out the merge commit (refs/pull/N/merge), pay attention to the benchmark when calculating diff.

See detailsLesson 5 Checkout in CI: Shallow clones, fetch-depth, and sparse checkouts、Lesson 5 Monorepo path filtering and change detection。

#43 warning: in the working copy of 'app.py', LF will be replaced by CRLF the next time Git touches it (line breaks cause the entire file to change)
warning: in the working copy of 'app.py', LF will be replaced by CRLF the next time Git touches it
---
$ git diff --stat
 app.py | 240 ++++++++++++++++++++++++++--------------------------------
                          ← Only one line is changed, diff displays the entire file
$ ./entrypoint.sh
/usr/bin/env: 'bash\r': No such file or directory ← CRLF entered the Linux container

The warning wording in older Git versions waswarning: LF will be replaced by CRLF in app.py.

Phenomenon:A mixed team of Windows and Linux/macOS developers, the whole file diff appears in the PR; the shell script reports in the container\rError.

Root cause:everyone'score.autocrlfDifferent (the Git for Windows installer defaults totrue), the editors each save different line breaks; there are no.gitattributesUnify the rules, so CRLF and LF are mixed into the repository object.

diagnostic commands
git config --show-origin --get core.autocrlf
git ls-files --eol | grep -v 'i/lf' | head # i/=newline in index w/=newline in workspace attr/=attribute
git diff --ignore-cr-at-eol --stat # After ignoring CR, only the real changes remain in diff
file:C:/Program Files/Git/etc/gitconfig    true
i/crlf  w/crlf  attr/                   entrypoint.sh
i/mixed w/crlf  attr/                   app.py
Repair
# .gitattributes (committed to the repository, effective for everyone, taking precedence over personal core.autocrlf)
* text=auto eol=lf
*.sh text eol=lf
*.bat text eol=crlf
*.ps1 text eol=crlf
*.png binary
git add .gitattributes
git add --renormalize . #Renormalize files in the index according to new rules
git commit -m "chore: normalize line endings"
# Separate normalized commits, recorded in .git-blame-ignore-revs to avoid contaminating blame
git rev-parse HEAD >> .git-blame-ignore-revs && git config blame.ignoreRevsFile .git-blame-ignore-revs
Prevention and best practices
  • Put it in every repository on the first day.gitattributes with .editorconfig。
  • Canonicalize commits individually, merge them as soon as possible, and notify in-progress branches to rebase after them.

See detailsLesson 7 Line Breaks, Case, Permissions, and Encoding Issues。

#44 Case problem: renaming Readme.md → README.md does not take effect / warning: the following paths have collided
$ mv Readme.md README.md && git status
nothing to commit, working tree clean ← Git on Windows/macOS No changes seen
---
$ git clone https://github.com/org/myapp.git
warning: the following paths have collided (e.g. case-sensitive paths
on a case-insensitive filesystem) and only one from the same
colliding group is in the working tree:

  'src/Utils.py'
  'src/utils.py'

Phenomenon:Renames that only change case are not recognized on Windows/macOS; modules that can be imported on Linux will cause an ImportError on macOS (or vice versa); there are two files in the repository that only differ in case, and one of them is "always modified" after cloning on a case-insensitive file system.

Root cause:Windows (NTFS default) and macOS (APFS default) file systems are case-insensitive, and Git setscore.ignorecase=true; Git internal paths are case-sensitive. Two files committed with different cases on Linux cannot coexist on a case-insensitive file system. Reference names (branch names) also have the same problem under the files reference backend (Feature/x with feature/x) - This is one of the problems that the default reftable backend is planned to solve.

diagnostic commands
git config --get core.ignorecase
git ls-files | sort -f | uniq -di # Duplicate paths with only uppercase and lowercase differences
Repair
git mv -f Readme.md README.md # Explicitly let Git record case renames
git commit -m "docs: rename README"
# Two conflicting files: merge/delete one on Linux (or case-sensitive volumes)
git rm --cached src/Utils.py && git commit -m "fix: remove case-duplicate Utils.py"

Don't do it by handcore.ignorecaseChange to false to "fix": on case-insensitive file systems this would cause Git to think the file was deleted and then added.

Prevention and best practices
  • Add checks in CI (Linux):git ls-files | sort -f | uniq -diIf there is output, it fails.
  • Use lowercase (kebab-case) for file and branch naming.

See detailsLesson 7 Line Breaks, Case, Permissions, and Encoding Issues。

#45 Repository bloat: .git is 8 GB, but the workspace is only 200 MB
$ du -sh .git; git count-objects -vH
8.1G .git
count: 21877
size: 1.9 GiB ← Lots of loose objects
in-pack: 512033
packs: 41
size-pack: 6.0 GiB
garbage: 0

Phenomenon:Cloning, fetch, and CI are getting slower and slower; the hosting platform warns that the repository exceeds the recommended size.

Root cause:Large files have been committed in history (old commits still reference them even if they are later deleted); frequently modified binary files are saved with a copy of each version; a large number of local loose objects and small packs are not merged (maintenance has not been run for a long time); it may also berefs/pull/*, old tags, and old branches retain unwanted history.

diagnostic commands
# The 20 largest blobs in history and their paths
git rev-list --objects --all \
 | git cat-file --batch-check='%(objecttype) %(objectname) %(objectsize) %(rest)' \
 | awk '$1=="blob"' | sort -k3 -n -r | head -20 | awk '{printf "%8.1f MB %s\n", $3/1048576, $4}'
git for-each-ref --format='%(refname)' | cut -d/ -f1-3 | sort | uniq -c # Reference distribution
  612.4 MB  data/dump-2024.sql
  245.1 MB  data/model.bin
   88.0 MB  vendor/sdk.zip
Repair
# Local: only when there is no maintenance
git maintenance run --task=gc # or git gc; regularly: git maintenance start
# History does have large files: use git filter-repo to rewrite history (see #50 for team collaboration)
git filter-repo --strip-blobs-bigger-than 50M # or --path data/dump-2024.sql --invert-paths
# Convert large files that need to be retained to LFS: git lfs migrate import --everything --include="*.bin"
# After rewriting: forcefully push all branches and tags. The platform side may need to contact support to clear cache/PR references before the volume will decrease.
Prevention and best practices
  • pre-commitcheck-added-large-files+ Platform file size limits (#32).
  • Check regularly with git-sizer; report repository volume trends in CI.
  • Do not commit database dumps, build products, and dependency packages to the repository.

See detailsLesson 6 Repository maintenance: gc, maintenance, commit-graph、Lesson 7 filter-repo。

#46 error: gpg failed to sign the data / fatal: failed to write commit object (signing failed or showing Unverified)
error: gpg failed to sign the data
fatal: failed to write commit object
---
# SSH signature verification:
$ git log --show-signature -1
error: gpg.ssh.allowedSignersFile needs to be configured and exist for ssh signature verification

Phenomenon:turn oncommit.gpgsignThe commit fails; or the commit is successful but the platform displaysUnverified;or localgit log --show-signatureUnable to verify SSH signature.

Root cause:GPG: gpg-agent cannot pop up password input (no TTY, requiredGPG_TTY), key expiration,user.signingkeyPoints to a key that does not exist. Unverified: The email address corresponding to the signature key is inconsistent with the commit email address, the public key is not uploaded to the platform (or the SSH public key is not registered asSigning key), the key has expired/revoked. Local verification of SSH signatures requires an "allowed signers" file mapping mailboxes to public keys.

diagnostic commands
git config --get-regexp '^(gpg|user\.signingkey|commit\.gpgsign)'
echo test | gpg --clearsign >/dev/null && echo "gpg ok" # Test gpg directly
GIT_TRACE=1 git commit --allow-empty -m test 2>&1 | grep -i gpg
git log --format='%h %G? %GK %ae' -3 # G valid / B bad signature / U unknown validity / X expired / E cannot be checked / N no signature
Repair
# GPG: Allow the agent to pop up input
export GPG_TTY=$(tty) # Write ~/.bashrc
gpg --list-secret-keys --keyid-format=long && git config --global user.signingkey <KEYID>
# Use SSH signing instead (simpler, reuse existing SSH keys)
git config --global gpg.format ssh
git config --global user.signingkey ~/.ssh/id_ed25519.pub
git config --global commit.gpgsign true
# Local verification: allowed signer files
echo "alice@corp.example.com $(cat ~/.ssh/id_ed25519.pub)" >> ~/.config/git/allowed_signers
git config --global gpg.ssh.allowedSignersFile ~/.config/git/allowed_signers
Prevention and best practices
  • Signing key email =user.email= The platform has verified the email address.
  • CI bot commits are signed using platform signing (e.g. commits created via the API are signed by the platform) or gitsign (Sigstore keyless signing, whichever is the project documentation).
  • For mandatory signature branches (#37), all employees must first complete the configuration.

See detailsLesson 5 Commit and Tag Signing: GPG, SSH, gitsign。

#47 fatal: detected dubious ownership in repository at '/workspace/myapp'
fatal: detected dubious ownership in repository at '/workspace/myapp'
To add an exception for this directory, call:

	git config --global --add safe.directory /workspace/myapp

Phenomenon:Executing any Git command on the mounted repository in the CI container (running as root) fails; on Windows, the same error is reported when accessing a repository created by another user or a repository on a network share. Version number calculation,git describeThe tool fails as a result.

Root cause:Security checks added since Git 2.35.2 to fix CVE-2022-24765: When the owner of the repository directory is not the current user, Git refuses to read its configuration (a malicious repository can pass.git/configincore.fsmonitorand other options to execute any command). The most common trigger scenario is that the UID in the container is different from the host.

diagnostic commands
id -u; stat -c '%u %U' /workspace/myapp /workspace/myapp/.git
git config --global --get-all safe.directory
0
1001 runner
1001 runner
Repair
# Only add exceptions for specific directories that are trusted (do not use '*' unless it is a one-time isolation container)
git config --global --add safe.directory /workspace/myapp
# Better way: the container runs with the same UID as the host
docker run --user "$(id -u):$(id -g)" -v "$PWD":/workspace/myapp ...
# Or correct ownership: sudo chown -R "$(id -u)":"$(id -g)" /workspace/myapp
Prevention and best practices
  • actions/checkout automatically adds safe.directory to the workspace, but may still trigger in subsequent container steps (different users).
  • Don't set it up on a shared multi-user machinesafe.directory=*。

See detailsLesson 5 Git in CI/CD、Lesson 7 Permission Issues。

#48 Each file shows old mode 100755 / new mode 100644 (file permission bit changes)
$ git diff
diff --git a/scripts/deploy.sh b/scripts/deploy.sh
old mode 100755
new mode 100644
diff --git a/app.py b/app.py
old mode 100644
new mode 100755
... (hundreds of files, content unchanged)

Phenomenon:Working with repositories on Windows disks in WSL (/mnt/c/...), unzipped from zip, or copied to FAT/NTFS USB drive, all files show permission changes; conversely, shell scripts committed on Windows show permission changes in Linux CIPermission denied。

Root cause:Git only tracks executable bits (100755 / 100644). File systems that do not support POSIX permissions will make all files appear executable or none; Git for Windows defaults tocore.fileMode=false, so scripts created on Windows are never recorded as executable.

diagnostic commands
git config --show-origin --get core.fileMode
git ls-files -s scripts/deploy.sh # 100755 or 100644
git diff --summary | grep 'mode change' | wc -l
Repair
# This file system cannot express permissions: let Git ignore local permission changes
git config core.fileMode false
# The script needs to be marked as executable in the repository (this can also be done on Windows)
git update-index --chmod=+x scripts/deploy.sh && git commit -m "chore: make deploy.sh executable"
# WSL: Place the repository in the Linux file system (~/src) instead of /mnt/c
Prevention and best practices
  • WSL users put their code in WSL's ext4 file system (which also performs much better).
  • Don't rely on the executable bit in CI: usebash scripts/deploy.shcall.

See detailsLesson 7 Line Breaks, Case, Permissions, and Encoding Issues。

#49 hint: The '.git/hooks/pre-commit' hook was ignored because it's not set as executable. (The hook was not executed / bypassed)
hint: The '.git/hooks/pre-commit' hook was ignored because it's not set as executable.
hint: You can disable this warning with `git config set advice.ignoredHook false`.

In earlier versions, the prompt wasgit config advice.ignoredHook false。

Phenomenon:The team-agreed formatting/confidential scanning hook was not run; new colleagues’ commits were not checked; someone used--no-verifySkip.

Root cause:Client hooks are stored in.git/hooks/(orcore.hooksPathspecified directory),Will not be distributed with clones, must be installed by everyone; the hook file must be executable (copying from zip or #48 permission issues on Windows will make it unexecutable); anyone cangit commit --no-verifySkip client hooks.

diagnostic commands
git config --get core.hooksPath
ls -l .git/hooks/pre-commit
pre-commit --version 2>/dev/null && cat .pre-commit-config.yaml | head
Repair
chmod +x .git/hooks/pre-commit
# Use the pre-commit framework for unified management (configuration files are committed to the repository and each person runs install once)
pipx install pre-commit && pre-commit install && pre-commit run --all-files
# Or place the hook in the directory in the repository and set hooksPath
git config core.hooksPath .githooks
Prevention and best practices
  • Client hooks are a convenience, not a security boundary: The same check must be performed again on the CI (Required Status Check) or on the server side (Push Protection, Rule Sets, Push Rules).
  • Automate execution in development container/onboarding scriptpre-commit install。

See detailsLesson 5 Git hooks and pre-commit framework。

#50 Secrets pushed to remote: old clone pushed secrets/large files back after rewriting history
Monday: Found that config/prod.env (containing database password) had been pushed to main three months ago
Tuesday: Admin cleaned and pushed all branches using git filter-repo
Wednesday: Confidential scan warns again - the same file appears in main's history
$ git log --oneline --all -- config/prod.env
4c5d6e7 Merge branch 'main' of github.com:org/myapp ← Colleague bob's merge
1a2b3c4 chore: add prod env ← Commit with old hash is back

Phenomenon:History cleaning "failed"; there were a large number of duplicate commits (old and new hashes) in the repository.

Root cause:History rewriting generates completely new hashes for affected commits. Everyone's old clones, forks, unmerged branches, and CI caches still have old commits; colleagues only need to execute a normalgit pull(merge)+git push, the old history is re-entered into the repository through merge commit. Additionally, the platform may still provide access to old commits via old PR references, fork networks, and cached views.

diagnostic commands
git log --all --oneline -- config/prod.env
git log --all --format='%h %an %s' --ancestry-path 1a2b3c4..main | tail -3 # Whose merge brings it back
gitleaks git --log-opts="--all" . # Full history secret scan (gitleaks 8.x syntax, subject to project documentation)
Repair (incident response sequence)
  1. Immediately revoke/rotate secrets—This is the only truly effective remedy. Historical cleansing only reduces exposure, and secrets should be treated as if they have been compromised.
  2. Freeze repository writes (temporary ruleset/lock branch), notify all collaborators.
  3. use git filter-repo --path config/prod.env --invert-paths(or--replace-text) is rewritten on a brand new image clone, forcing all branches and tags.
  4. ask everyoneRe-clone(or for each local branchgit rebase --ontoto new history), delete old clones; close/rebuild PRs and forks that reference old commits.
  5. The contact platform supports clearing cached views and PR references (described in the GitHub documentation "Removing sensitive data from a repository").
  6. Add reflow prevention measures: server-side push protection or detection of old commit hashes/confidential patterns in CI.
# Administrator: Rewrite on new image clone
git clone --mirror https://github.com/org/myapp.git && cd myapp.git
git filter-repo --path config/prod.env --invert-paths
git remote add origin https://github.com/org/myapp.git # filter-repo will remove origin to prevent accidental push
git push --force --mirror origin # Note that --mirror will delete redundant remote references.
Prevention and best practices
  • Prevention is better than cleanup: pre-commit secret scanning + platform push protection (#4) + secrets stored in a vault.
  • Write a "confidential leakage runbook" and practice it before talking about it.

See detailsLesson 7 Rewriting history: filter-repo clears secrets and large files、Lesson 5 Confidential Leak Prevention and Scanning, interview questionsQ44。

Comparison of cloning methods: what is downloaded (#39 #42) full cloneAll commits + all trees+ All historical versions of filesThe slowest, you can do anything offline --filter=blob:noneAll commits + all treesDownload file content on demandDeveloper preferred; log/merge-base is normal --sparse(cone)Check out only part of the directoryOften combined with partial clonesmonorepo team view --depth=1only one commitNo tags, no other branchesCI build is fast; describe fails .gitattributes driven filters (#40 #43) Commit (clean): workspace file → [eol converted to LF] → [LFS: upload content, write pointer] → object library Checkout (smudge): object library → [LFS: download real content with pointer] → [eol converted to platform/specify newline] → workspace
Figure 4-1 git-lfs is not installed = smudge is not executed = there are pointers in the workspace

CI checkout fault simulator

Select a fault scenario and run it: the pipeline is executed stage by stage, stopping at the stage where it will actually fail, and the logs and corresponding problems are displayed. Used to practice the "log positioning phase".

Start by choosing a scene.
$ Waiting to run…
environmentAll local; Lab 4-B is performed in Linux/WSL; Lab 4-C requires macOS or Windows (case-insensitive file systems) to see the difference.

Experiment 4-A: Shallow cloning causes describe and merge-base to fail (#42)

cd ~/git-lab8 && rm -rf ci-shallow
git clone -q --depth=1 --no-tags file://$PWD/remote.git ci-shallow && cd ci-shallow
git rev-parse --is-shallow-repository; git rev-list --count HEAD
git describe --tags
true
1
fatal: No names found, cannot describe anything.

When cloning local path--depthwill be ignored, so usefile:// URL。

Only add tags and history:
git fetch -q --unshallow --tags
git describe --tags
v1.0.0-1-g2b3c4d5
Cleanup:cd .. && rm -rf ci-shallow

Experiment 4-B: Newline confusion and normalization (#43)

cd ~/git-lab8/alice && git switch -qc eol-lab
printf '#!/bin/sh\r\necho hi\r\n' > run.sh && git add run.sh && git commit -qm "add run.sh (crlf)"
git ls-files --eol run.sh
i/crlf  w/crlf  attr/                 	run.sh
printf '* text=auto eol=lf\n*.sh text eol=lf\n' > .gitattributes
git add .gitattributes && git add --renormalize . && git commit -qm "chore: normalize eol"
git ls-files --eol run.sh
i/lf    w/crlf  attr/text eol=lf      	run.sh

The workspace file will become LF the next time it is checked out:rm run.sh && git checkout run.shSee it later asw/lf。

Cleanup:git switch -q main && git branch -D eol-lab

Experiment 4-C: Case-only renaming (#44)

git switch -qc case-lab && echo doc > Readme.md && git add Readme.md && git commit -qm doc
mv Readme.md README.md && git status --short # macOS/Windows: No output
mv README.md Readme.md && git mv -f Readme.md README.md && git status --short
R  Readme.md -> README.md
Cleanup:git commit -qm rename; git switch -q main; git branch -D case-lab

Experiment 4-D: Dubious ownership (#47, requires Docker)

docker run --rm -v ~/git-lab8/alice:/repo -w /repo alpine/git status 2>&1 | head -3
fatal: detected dubious ownership in repository at '/repo'
To add an exception for this directory, call:

Inside the container is root (UID 0), and the repository belongs to your user. mirroralpine/gitIt is a community image, and the entry point is git.

docker run --rm --user "$(id -u):$(id -g)" -e HOME=/tmp -v ~/git-lab8/alice:/repo -w /repo alpine/git status -sb | head -1
## main...origin/main
Cleanup: None.

Instructional video (title and channel verified with YouTube oEmbed)

▶
So You Think You Know Git Part 2 - DevWorld 2024 — GitButler
English · Large repository features: partial cloning, sparse checkout, scalar, fsmonitor, commit-graph (corresponding to #39)
▶
Advanced Git Tutorial - Interactive Rebase, Cherry-Picking, Reflog, Submodules and more — freeCodeCamp.org
English · Submodule chapter (corresponds to #41)

No verified videos specifically talking about LFS pointers, CI shallow cloning, and safe.directory troubleshooting were found. The breakdown is as follows:

Shot 1 (0:00)CI log:No names found, cannot describe anything;Switch tofetch-depth: 0The later version number is correct.
Shot 2 (0:50) cat logo.pngDisplay LFS pointer text,git lfs pullThe next picture appears.
Shot 3 (1:40) git ls-files --eoltable animation,--renormalizeBefore and after comparison.
Shot 4 (2:30)dubious ownership within the container →--userSolved; summary CI checkout four things: depth, label, LFS, submodule.

Official documentation

or score ≥ 70% on the Quiz

Module 5 · Part B: Fundamental Concepts and Internal Principles (Interviews 1–13)

30:00 – 37:00 · Distributed model, three zones, object model, ref and HEAD, hashing, pack, reflog, SHA-256 and reftable
7 minutesWhiteboard: Object Diagram13 questions
learning objectives
  • Able to draw the object diagram of commit → tree → blob on the whiteboard, and use it to explain branches, HEAD, reset, and reflog.
  • Answer "why" questions: why is Git fast, why does all the hashes change when one byte is changed, and why commits are almost never lost.
  • Knowledge of planned changes in Git 3.0 (SHA-256, reftable, default branch main) as a bonus.
Q1. What are the essential differences between Git and centralized version control such as SVN?Elementary
30 seconds short answer

Git is distributed: each clone containsfull historyIn the independent repository of SVN, commit, branching, viewing history, and merging are all done locally, and only fetch/push requires a network; the history of SVN is only on the central server, and commit is uploaded. Git storesSnapshot(each commit is a complete tree), branches are lightweight pointers, so branching and merging are very cheap.

in-depth answer
  • Local operation → Fast and offline; every clone is a backup.
  • Branches: SVN's branches are directory copies (server-side cheap copies), Git's branches are 41-byte files (or a record in reftable).
  • Integrity: Git is addressed with content hashes, and any corruption or tampering will be detected.
  • Permissions: SVN can be authorized by path; Git is generally authorized on a repository basis, and path-level control depends on platform rules (such as CODEOWNERS, push rules) or split repositorys.
  • Large files/binaries: SVN supports locks and on-demand checkouts; Git requires LFS (also has file locks) or partial cloning.
Frequently Asked Questions
  • Does "distributed" mean no central repository? ——Technically equivalent, the organization still agrees on an authoritative remote end (GitHub/Azure Repos).
  • In what scenarios does SVN/Perforce still have an advantage? ——Very large binary assets (games), strict path-level permissions, and the need for exclusive locks.
extra points

Mentioned that Git's partial cloning and sparse checkouts are closing the gap with centralized systems on large repositories; mentioned that migrations of TFVC/SVN history can be migrated using git-svn or platform import tools (Lesson 6).

Common wrong answers

"Git stores the difference of each file" - wrong, the logical model is a snapshot; differential compression is just a storage optimization of packfile (Q8).

See detailsLesson 1 Version Control and Git Architecture。

Q2. Explain the workspace, staging area (index) and repository. Why do we need a staging area?Elementary
30 seconds short answer

The workspace is the file you edit; the staging area (.git/index) is "what the next commit will look like"; repository (.git/objects+ refs) saves all commits.git addWrite the workspace content into a blob and update the index,git commitUse index to generate tree and commit. The staging area allows you toPrecise selectionChanges to commit (even partial chunks of a file).

in-depth answer
git add -p app.py # Interactively only temporarily saves some changes
git diff # workspace vs staging area
git diff --staged #Staging area vs HEAD
git restore --staged app.py # Cancel staging (do not move the workspace)
git ls-files -s | head -3 # Look at the entries in index: mode, blob hash, stage number, path

The index also caches the stat information (mtime, size) of the file, allowinggit statusEach file does not have to be rehashed; there will be three entries for stages 1/2/3 (base/ours/theirs) in the index for the same path in the event of a merge conflict.

Frequently Asked Questions
  • What is in the index when there is a conflict? ——Stage 1, 2, and 3 of the same path; after resolutiongit addCombine them into stage 0.
  • git commit -aWhat did you do? -- Automatically stage changes to tracked files (excluding new files).
extra points

It is mentioned that index is a binary file, and split index, untracked cache, and fsmonitor can be used to speed up large repositorys.

Common wrong answers

"The staging area is just a file list" - it saves thecontent hash, and then modify the file after it is temporarily saved, the content committed will still be the content when it was temporarily saved.

See detailsLesson 1 Three Regions。

Q3. What kinds of objects are there in Git’s object model? What does a commit produce in the object library?Intermediate
30 seconds short answer

Four types of objects:blob(File content, excluding file name),tree(directory: name + pattern + hash pointing to blob/subtree),commit(Pointing to a root tree, zero to more parent commits, author/committer, information),tag(Annotation tag: points to an object with signature/information). A commit will generate a new blob for the changed file, a new tree for the directory on the changed path, generate a commit, and finally move the branch ref.

in-depth answer
git cat-file -p HEAD # tree / parent / author / committer / message
git cat-file -p HEAD^{tree} # 100644 blob 3b18e5... app.py
git cat-file -t 3b18e5 # blob
echo 'hello' | git hash-object --stdin # Same content → Same hash → Automatic deduplication

Unchanged files and directoriesReuseOld objects, so "save a full snapshot each time" does not waste space.

Frequently Asked Questions
  • Where does the file name exist? ——tree; so renaming does not generate new blobs.
  • Are lightweight tags objects? ——No, it’s just a ref; the annotation tag is the tag object.
  • What are submodules in the tree? -- gitlink in mode 160000, pointing to a commit in another repository.
extra points

Can tell the storage format of the object:"type length\0 content"Calculate the hash and store it as a loose object after zlib compression.git/objects/ab/cdef..., and then packaged into packfile.

Common wrong answers

"The diff of this modification is saved in commit" - commit only points to a complete tree, and diff is temporarily calculated when comparing two trees.

See detailsLesson 1 Object Model: blob, tree, commit, ref。

Q4. What is a branch in Git? What is HEAD? What is detached HEAD?Elementary
30 seconds short answer

A branch is just aA movable pointer to a commit(refs/heads/maincontains a hash). HEAD is the "current location", usually aSymbol reference(ref: refs/heads/main), Git moves the branch pointed to by HEAD when committing. When HEAD directly stores a commit hash, it is detached HEAD. At this time, the commit does not belong to any branch.

in-depth answer
cat .git/HEAD # ref: refs/heads/main
git rev-parse main # The commit pointed to by the branch
git symbolic-ref HEAD # refs/heads/main
git switch --detach v1.0.0 && cat .git/HEAD # Directly hash

remote-tracking branch (refs/remotes/origin/main) is a local copy of the remote branch's location at the time of the last fetch, and only fetch will move it.

Frequently Asked Questions
  • Why is it almost zero cost to create a branch? -- Just write a ref.
  • What is the use of detached HEAD? -- Check historical versions, bisects, CI builds for specific commits; see Risk #6.
extra points

Mentioned storage of refs: loose ref file,packed-refs, and the optional reftable backend starting with Git 2.45 (Q10).

Common wrong answers

"A branch is a copy of the code" - that's SVN's thinking.

See detailsLesson 1 Getting Started with Branching and HEAD。

Q5. How is the committed hash calculated? Why does modifying an old commit change the hashes of all subsequent commits?Intermediate
30 seconds short answer

The commit hash is a pair of commit objectsAll content(Hash of root tree, parent commit hash, author and committer and timestamp, commit information, optional signature) Computed SHA-1 (or SHA-256 in repositories). Child commits contain the hash of the parent commit, so if any old commit is modified, its hash changes will be propagated to all descendants along the chain - this is the tamper-proof feature of Git history (similar to the Merkle structure).

in-depth answer
git cat-file commit HEAD | head -5
# Manually recalculate the hash:
(printf "commit %s\0" $(git cat-file commit HEAD | wc -c); git cat-file commit HEAD) | sha1sum
git rev-parse HEAD # Both are the same (SHA-1 repository)

So amend, rebase, cherry-pick, filter-repo are all generatednewCommit; even if the content is exactly the same, as long as the commit time is different, the hash is different.

Frequently Asked Questions
  • If two people make the exact same commit on different machines, will the hash be the same? ——They are the same only if the author, timestamp, parent commit, and information are all the same, which is almost impossible in practice.
  • Does the signature affect the hash? ——Yes, the signature is stored in the commit objectgpgsigHead.
extra points

Point out that Git currently uses SHA-1 with collision detection (SHA-1DC) by default, and plans to make new repositories use SHA-256 by default in Git 3.0 (Q9).

Common wrong answers

"The hash is calculated only based on the file contents" - that's the blob; the commit hash also contains metadata and parent links.

See detailsLesson 1 Object Model。

Q6. What are the differences between git reset --soft / --mixed / --hard, git restore, and git revert? When is each used?Intermediate
30 seconds short answer

resetMove the current branch:--softMove only ref;--mixed(Default) Reset the staging area;--hardThen cover the working tree.restoreOnly the file contents (workspace or staging area) are restored, branches are not moved.revertCreate a new reverse commit without rewriting history and apply to pushed commits.

in-depth answer
commandbranch refStaging areaworkspaceTypical uses
reset --soft HEAD~3moveReserveReserveMerge the last 3 local commits into one
reset HEAD~1moveresetReserveUndo the latest local commit and reorganize
reset --hard origin/mainmoveresetCoverDiscard everything local and align with remote
restore file / --stagedNot moving(--staged)restoreUndo modifications to a file/cancel staging
revert CForward (new commit)——Undo a pushed commit
Frequently Asked Questions
  • How to retrieve it after reset --hard? --reflog (issue #2).
  • What is required for revert merge commit? ——-m 1(Question #17, Q20).
extra points

Mentioned the introduction of Git 2.23switch/restore Split checkoutresponsibilities; mentionedreset --keep(More secure when there are local modifications).

Common wrong answers

"Use reset on main to undo a commit that a colleague has pulled and then push it" - destroys everyone's history.

See detailsLesson 1 Undo: restore, reset, revert。

Q7. What is the difference between git fetch and git pull? Which way of working do you prefer?Elementary
30 seconds short answer

fetchOnly download new objects from the remote and update the remote-tracking branch (origin/main), don’t touch your work;pull = fetch+ Integrate upstream into the current branch (merge or rebase, depending on configuration). I recommend fetching it first to see clearly (git log HEAD..origin/main), and then decide how to integrate; or explicitly configurepull.rebase/pull.ff。

in-depth answer
git fetch --prune # Also delete the remote-tracking branch that no longer exists
git log --oneline HEAD..@{u} # Commits that the upstream has but I don’t have
git pull --rebase # or --ff-only / --no-rebase

The new version of Git will reject pulls when forked and unconfigured (Issue #14) to avoid accidental merge commits.

Frequently Asked Questions
  • What is @{u}? ——The upstream of the current branch, represented bybranch.<name>.remote/mergedefinition.
  • Will fetch change my local branch? - No (unless explicitly writing the refspec to the local branch).
extra points

mentionedfetch.prune, ref filtering of protocol v2 reduces transmission,remote.origin.fetchThe meaning of refspec.

Common wrong answers

"Fetch is the old way of writing pull."

See detailsLesson 1 Remote Repository、Lesson 2 Remote Branching and Tracking Relationships。

Q8. What is packfile? How does Git compress storage? What does git gc / git maintenance do?Advanced
30 seconds short answer

New objects are first compressed with zlibloose objectsstorage;gc/repackPack them into a packfile and do between similar objectsdelta compression(Not limited to adjacent versions of the same file, find base objects heuristically by type, file name, size), and generate.idxindex.git maintenanceSplit these tasks into schedulable tasks (prefetch, commit-graph, loose-objects, incremental-repack, gc) and run them in the background.

in-depth answer
git count-objects -vH
git verify-pack -v .git/objects/pack/pack-*.idx | sort -k3 -n | tail -3 # Maximum object and delta chain
git maintenance start # Register scheduled tasks (cron/launchd/Windows scheduled tasks)
git commit-graph write --reachable --changed-paths # Speed up log, merge-base, log by path

Network transmission also uses pack: the server calculates the objects you are missing, generates (or reuses) packs and sends them; pack bitmaps can speed up reachability calculations.

Frequently Asked Questions
  • What will gc delete? ——Unreachable objects that have expired (default 2 weeks, and need to be reflogged and no longer referenced).
  • Why do large binaries bloat repositories? - Hard to delta compress, each version is saved almost completely (Issue #45).
extra points

Mentioned multi-pack-index, geometric repack (git repack --geometric=2), changed-path Bloom filter.

Common wrong answers

"Git uses diff to store each version, so it's logically incremental" - the logical model is a snapshot, and delta is just physical compression.

See detailsLesson 6 Repository maintenance: gc, maintenance, commit-graph。

Q9. What threats does SHA-1 collision pose to Git? How does Git respond? How is the SHA-256 migration going?Advanced
30 seconds short answer

SHAttered in 2017 demonstrated that SHA-1 can construct collisions. Git then defaults to usingCollision detectionSHA-1 implementation (SHA-1DC), which can identify known collision attack modes; at the same time, Git has already supported--object-format=sha256repository and plans toGit 3.0Let new repositories use SHA-256 by default (still planned as of 2026-11, subject to BreakingChanges documentation).

in-depth answer
  • Attack difficulty: The malicious object needs to collide with the legal object and be accepted by the other party; Git will not overwrite existing objects (the first to arrive wins).
  • Interoperability (double hash mapping) between SHA-256 repositories and SHA-1 repositories is still in progress; hosting platforms have varying degrees of support for SHA-256 repositories and need to be confirmed before migration.
  • Signatures (GPG/SSH) sign the committed content, and security also relies on hash strength.
git init --object-format=sha256 demo && git -C demo rev-parse --show-object-format
Frequently Asked Questions
  • How to migrate existing repository? ——Currently requires conversion history (all hashes will change) and requires platform support.
extra points

Put this together with other planned changes for Git 3.0: default reftable, default branch namesmain, and the preparations surrounding these in 2.56.

Common wrong answers

"Git has fully switched to SHA-256" - No, it is still optional and planned to be the default.

See detailsLesson 1 Release Notes、BreakingChanges。

Q10. How is ref stored? What is the difference between loose refs, packed-refs and reftable?Advanced
30 seconds short answer

Traditional "files" backend: each ref is.git/refs/A file (loose ref) underpacked-refstext file. reftable is a reference store in binary format (available since Git 2.45), with prefix compression and tombstone marking, atomic batch updates and deletions without rewriting large files, and reference names no longer depend on file system paths (resolving conflicts on case-insensitive file systems). Planned to become the default for new repositories in Git 3.0.

in-depth answer
git init --ref-format=reftable demo
git -C demo rev-parse --show-ref-format # reftable
git refs migrate --ref-format=reftable # Existing repository migration (experimental, backup first; subject to the document)
git for-each-ref --format='%(refname)' | head

From 2.56git refsAdded create / delete / update / rename subcommands, which can operate references independently of the reference backend - no more direct reading and writing in scripts.git/refsfile.

Frequently Asked Questions
  • Why does the files backend have issues on Windows/macOS? ——Feature/x with feature/xMap to the same file path (Issue #44).
  • What is the impact of having a repository with millions of refs (like PR refs)? ——The rewriting cost of packed-refs is high, and reftable has obvious advantages.
extra points

It is mentioned that alternative implementations such as JGit and libgit2 need to support reftable in order to allow default values to be switched (a prerequisite in BreakingChanges).

Common wrong answers

"Directcat .git/refs/heads/mainto get the branch hash" - this does not hold true in packed or reftable repositories, you should usegit rev-parse。

See detailsLesson 1 Object Model and ref。

Q11. What are the important contents in the .git directory?Intermediate
30 seconds short answer

HEAD(current location),config(repository level configuration),objects/(Object library: loose object + pack),refs/ with packed-refs(branch, tag, remote-tracking branch),index(staging area),logs/(reflog)、hooks/(Client hook sample),info/exclude(local ignore rules), and the status file in action:MERGE_HEAD、ORIG_HEAD、rebase-merge/、*.lock。

in-depth answer
ls.git
git rev-parse --git-dir --git-common-dir # The two are different in the case of worktree
cat .git/ORIG_HEAD # The position before reset/merge/rebase
git config --local --list

These status files are clues for troubleshooting: seeMERGE_HEADIndicates that the merge is not completed.rebase-merge/Indicates that the rebase was not completed (Issue #12),index.lockIndicates that a process is writing or crashing (Issue #9).

Frequently Asked Questions
  • Copy the entire.gitJust a backup? - Yes, includes reflog, hooks and local configuration (cloning will not copy these).
  • worktree's.gitWhat is it? ——A pointer to the main repositoryworktrees/files in the directory below.
extra points

mentionedobjects/info/alternates(Shared Object Library) with a partially cloned promisor pack.

Common wrong answers

"Hooks in .git/hooks are shared with everyone in the repository" - No (Issue #49).

See detailsLesson 1 Object Model、Lesson 7 Repository corruption: fsck。

Q12. What is reflog? How long can it be stored? In what situations can it save you, and in what situations can it not save you?Intermediate
30 seconds short answer

reflog islocalRecord every movement of each ref (and HEAD) in the log: commit, reset, checkout, rebase, merge, pull will all write one entry. By default, reachable entries are retained for 90 days and unreachable entries are retained for 30 days. It can retrieve commits "lost" by reset, rebase, amend, or delete branches; it cannot save changes that have never been committed, nor do they exist on the remote end or in someone else's clone.

in-depth answer
git reflog # = git reflog show HEAD
git reflog show feature/login #Move history of a certain branch
git log -g --format='%h %gd %gs' # View in log form
git reset --hard HEAD@{2} # or main@{yesterday}
Frequently Asked Questions
  • What about its reflog after deleting the branch? ——Deleted with the branch, but the reflog of HEAD is still there (Issue #10).
  • How to find content that is temporarily saved but not committed? ——git fsck --lost-found(Question #2).
extra points

Description gc.reflogExpire/gc.reflogExpireUnreachable, and do not immediately after the accidentgc --prune=now;The server (bare repository) does not enable reflog by default (core.logAllRefUpdates)。

Common wrong answers

"If you can't see the git log, it's gone."

See detailsLesson 7 reflog and retrieving lost commits。

Q13. Git saves snapshots instead of differences, so how does it detect renames? How to calculate diff and status efficiently?Advanced
30 seconds short answer

Git does not log "rename" operations. When comparing two trees, if a file is deleted on one side and a file is added on the other side, Git calculates the contentSimilarity(Default ≥ 50% is considered a rename, available-M/--find-renamesTweak) Infer rename. diff first compares tree hashes: identical subtrees are skipped directly, so diff in large repositories is still fast. status relies on cached stat information in the index and only rehashes files that may have changed.

in-depth answer
git log --follow --oneline -- src/settings.py # Track a single file across renames
git diff -M30% --stat HEAD~5 # Relax the threshold
git diff --diff-algorithm=histogram # More readable diff algorithm (myers/patience/histogram)
git config core.fsmonitor true # Use file system events to reduce status scans

Consequences: Git may not be able to recognize the substantial modifications while renaming (Issue #21); so it is best to commit the rename separately. 2.56 improvedlog --followTreatments in nonlinear history.

Frequently Asked Questions
  • Is there an upper limit to rename detection on merge? ——Yesmerge.renameLimit/diff.renameLimit。
  • How does blame track code movement across files? ——git blame -C -C。
extra points

Mentioned that the ort merge strategy (default since Git 2.34) greatly optimizes rename detection performance.

Common wrong answers

“git mvA rename operation will be logged in the repository"——git mvJustmv + git rm + git addConvenient way of writing.

See detailsLesson 1 View History and Differences、Lesson 2 Merge。

Interview whiteboard diagram: objects and references (Q3 Q4 Q5 Q12) HEAD refs/heads/main commit C2tree · parent · author commit C1parent = None (root) tree (root directory)app.py · src/ blob app.py v2 tree src/ blob (reuse) Symbol reference parent reflog (local): main@{0} = C2, main@{1} = C1…reset only moves ref; the object remains unchanged → you can return to any old position through reflogModify any object → new hash → propagated up to commit (tamper-proof)
Figure 5-1 Talk while drawing: ref → commit → tree → blob; reuse the same object with the same content

Scenario 5-1: Explain to a non-technical manager "Why you should migrate from TFVC/SVN to Git"

The team has 30 people and has been using TFVC for ten years. The manager is worried about migration risks. Please give the benefits, risks and phased plan.

Reference answer key
  • income: Local branches and offline work, PR code review and CI access control, ecology (GitHub/Azure Repos/GitLab tool chain), recruitment (Git is the industry standard).
  • risk: Large binaries (requires LFS), integrity of historical migrations, alternatives to path-level permissions, team learning curve.
  • stage: ① Select a pilot repository and migrate only the latest history (or all history, depending on audit requirements); ② Establish branch strategy and protection rules; ③ Training + cheat sheet; ④ Read-only freeze the old repository after double-writing for a period of time; ⑤ Migrate the remaining repositorys one by one.
  • measure: PR cycle time, build failure rate, number of merge conflicts.

Scenario question 5-2: A colleague said, "I reset --hard, and three days of work are gone."

When you are called to his work station, what questions do you ask and what commands do you type?

Reference answer key
  • Stop further damage first: don't rungc, do not re-clone, do not delete the directory;cp -aBack up the entire repository.
  • Q: Have you committed the work of these three days? Added it before? Have you pushed it? On which branch?
  • Committed:git reflogFind the position before reset,git branch rescue HEAD@{1}。
  • Only staging:git fsck --lost-foundLook at the dangling blobs one by one.
  • Unstaged: IDE local history, editor backups, operating system snapshots (Time Machine/File History).
  • Review: Encourage small steps to commit and push to personal branches; introductionreset --keep with stash。
or score ≥ 70% on the Quiz

Module 6 · Part B: Branching, Merging, and History (Interviews 14–25)

37:00 – 44:00 · merge and rebase, fast forward, ort, interactive rebase, cherry-pick, undo pushed, rollback merge, three PR merge methods, rerere, bisect, retrieval, force push
7 minutesWhiteboard: Commit Figure12 questions
learning objectives
  • Draw the commit diagrams of the three results of merge, rebase, and squash on the whiteboard, and explain the respective costs.
  • Explain the processing principles and principles of "pushed history"--force-with-leaseway of working.
  • Can tell a story about using bisect/reflog to solve a real problem (STAR structure).
Q14. What is the difference between merge and rebase? How do you choose your team?Intermediate
30 seconds short answer

merge retains the true fork history, generates a merge commit with two parent commits, and does not overwrite existing commits; rebase puts a series of commits on a new basereplay, getting a linear history, but generating new commits (new hashes). Principles:Private branches can be organized by rebase, public branches can only be merged。

in-depth answer
git switch feature && git rebase main # Move feature to the latest location of main (only on its own branch)
git switch main && git merge --no-ff feature # Keep a merge commit on main
mergerebase
historyRealistic, non-linearLinear and easy to read
conflictOne time solutionPossibly solved on a commit-by-commit basis (#15)
rewriteNoYes (has been pushed and needs to be pushed)
bisect / revertMerge commit requires -mEach commit is independent, simpler
Frequently Asked Questions
  • Want to give up midway through a rebase conflict? ——git rebase --abort。
  • Why are there duplicate commits from colleagues after rebase? ——Question #16.
extra points

mentionedgit pull --rebaseThe fork-point mechanism,rebase --update-refs(Overlay branches move together),git replay(New in 2.56--linearize, suitable for server-side/scripted rebasing).

Common wrong answers

"Rebase is always better than merge" or "Never use rebase" - clarify the applicable boundaries.

See detailsLesson 2 Merging and Rebasing。

Q15. What is fast-forward merge? What scenarios are --no-ff and --ff-only used for?Elementary
30 seconds short answer

When the target branch is the ancestor of the merged branch, the merge only needs to move the pointer forward and no merge commit is generated. This is fast-forward.--no-ffForce the generation of merge commits, preserving the "this is a feature" boundary on trunk;--ff-onlyOnly allows fast forwarding, otherwise fails, suitable for deploying scripts and maintaining linear history.

in-depth answer
git merge --ff-only origin/main # The local main is aligned with the remote end, and an error will be reported if it bifurcates, so there will be no accidental merge.
git merge --no-ff feature/login # Keep merge commits on the trunk, git log --first-parent is the "feature list"
git log --first-parent --oneline main
Frequently Asked Questions
  • Why does push only allow fast forwarding by default? --Otherwise remote commits will be lost (Issue #13).
  • What does the platform’s “Rebase and merge” have to do with fast forwarding? ——Rebase first and then fast forward (Q21).
extra points

Mentioned "Require linear history" in GitHub ruleset, Azure Repos merge type restrictions.

Common wrong answers

"Fast-forward merging will lose commits" - No, just no merge commits.

See detailsLesson 2 Merge: Fast Forward and Three-Way Merge。

Q16. How does a three-way merger work? What is a merge base? Any improvements to the ort strategy?Advanced
30 seconds short answer

Three-way merge compares three versions: the ends of two branches (ours, theirs) and their most recent common ancestor (merge base). For each file/block: if only one side is changed relative to base, that side will be taken; if the same block is changed on both sides, it is a conflict. ort (default since Git 2.34) is a rewrite of recursive that is faster, handles renames more accurately, and does merges in memory without cluttering the workspace.

in-depth answer
git merge-base main feature # common ancestor
git merge-tree --write-tree main feature # Calculate the merge result without touching the workspace (2.38+); the exit code is non-0 when there is a conflict
git checkout --conflict=zdiff3 app.py # Regenerate the conflict mark with base section

When multiple merge bases (cross-merge) are used, recursive/ort will first merge multiple bases into a virtual base.

Frequently Asked Questions
  • Why does the merge not take effect after rolling back the merge? --merge base has moved past those commits (Issue #17).
  • -X ours with -s oursThe difference? ——The former only favors our side on conflict blocks, while the latter completely ignores the opponent's changes.
extra points

mentionedgit merge-tree --write-treeUsed by the platform to calculate PR mergeability on the server side;--remerge-diffUsed for review of manual conflict resolution (Issue #22).

Common wrong answers

"Git decides which side to use chronologically".

See detailsLesson 2 Merging and Conflict Resolution。

Q17. What can interactive rebase do? How to use fixup / autosquash?Intermediate
30 seconds short answer

git rebase -iOpen a to-do list, you can pick / reword (change information) / edit (stop modification) / squash (merge and edit information) / fixup (merge and discard information) / drop / reorder each commit, and you can also insertexecRun the command. Used to organize "wip, fix typo" into meaningful commits before committing a PR.

in-depth answer
git commit --fixup=1a2b3c4 # Generate "fixup! ..." commit
git rebase -i --autosquash origin/main # Automatically queue fixup commits behind the target and mark them as fixup
git rebase -i origin/main --exec "pytest -q" # Each commit can pass the test (convenient for bisect)
git rebase -i --update-refs main # Overlay branches: update the intermediate branch pointers at the same time
Frequently Asked Questions
  • Made a mistake in the middle of sorting? ——--abort, or when finished useORIG_HEAD/reflog recovery (Issue #12).
  • How to push the pushed PR branch after sorting it out? ——--force-with-lease(Q25)。
extra points

mentionedrebase.autoSquash=true、git history(Experimental command, new drop subcommand in 2.56) is a higher-level history editing tool.

Common wrong answers

"Interactive rebase can be used casually on main".

See detailsLesson 2 Rebase and interactive rebase。

Q18. What are the uses and risks of cherry-pick?Intermediate
30 seconds short answer

cherry-pick applies the changes introduced by a commit to the current branch and generates a new commit. Typical uses: moving the fixes on the trunk back to the release branch, and moving the changes that were mistakenly committed to other branches. Risks: Producing commits with duplicate content but different hashes, which may cause conflicts in subsequent merges; missing pre-changes to fix dependencies; abuse will make it difficult to track the relationship between branches.

in-depth answer
git cherry-pick -x 1a2b3c4 # Record the source commit in the message
git cherry-pick A^..B # A continuous commit (including A)
git cherry-pick -m 1 <merge> # To pick merge commits, you need to specify the main line
git cherry -v release/1.4 main # + means there are commits with equivalent patches on main but not on release
Frequently Asked Questions
  • What to do about conflicts? ——After solving--continue, or--abort(Issue #18).
  • How do I know if a fix has been moved back? ——git cherry、-xsource line, orgit log --grep。
extra points

Explain the two flows of hot fixes (repair the trunk first and then move back vs. repair the release branch first and then merge it back to the trunk) and how the team chooses (Q37).

Common wrong answers

"cherry-pick will move the original commit" - the original commit is unchanged and a copy is generated.

See detailsLesson 2 cherry-pick、Lesson 6 Hotfix and rollback。

Q19. How to undo a commit that has been pushed to a shared branch?Intermediate
30 seconds short answer

use git revert < commit >Generate a reverse commit and push it normally (take a PR). Without rewriting history, everyone’s clones will be unaffected. Rewriting history will only be considered if the commit contains classified/illegal content and must be erased from history, in conjunction with rotating confidentiality and full staff coordination (Issue #50).

in-depth answer
git revert 1a2b3c4 # Single commit
git revert --no-commit A^..C && git commit -m "revert: feature
git revert -m 1 <merge> # Merge commit (Q20)
Frequently Asked Questions
  • Why not reset + force push? ——Others have already worked on the old history, and forcing their commits will be "reflowed" or lost; protected branches usually also prohibit forcing.
  • How to introduce it again after revert? ——revert that revert.
extra points

Mention the function switch that allows "undo" not to involve Git; mention the Revert button on the platform PR page.

Common wrong answers

"Use git reset HEAD~1 then push -f".

See detailsLesson 1 revert。

Q20. How to roll back an incorrect merge? Why do changes "not come back" when merging the same branch again later?Advanced
30 seconds short answer

use git revert -m 1 < merge commit >:-m 1Specify that the first parent (main line) is used as the basis to undo the changes brought by the second parent. Revert only undoes the content, and the merge history still exists, so when merging again, Git thinks that those commits have been merged, and will only bring in new commits. The correct approach is to revert that revert first, and then merge the new fix.

in-depth answer
git show --no-patch --format='%P' M # Two parents: P1 (main) P2 (feature)
git revert -m 1 M # Generate R
#...After fixing the problem on feature:
git revert R # Generate R' and restore the original changes
git merge feature # Only bring in new fixes

Git official documentationHow to revert a faulty mergeThis is discussed in detail (Linus vs. Junio emails).

Frequently Asked Questions
  • What if we use rebase to reorganize the feature (new hash) and then merge it? ——The new commit is not a merged commit and can be merged directly, but there will be two sets of equivalent changes in the history.
extra points

When it comes to squash merges, rollbacks are simpler (just one normal commit) - this is one of the reasons why some teams choose squash.

Common wrong answers

"Use-m 2"——That is based on feature and will undo the changes on main.

See question for details#17、Lesson 2。

Q21. What are the advantages and disadvantages of the three merge methods of PR (Merge commit / Squash / Rebase)?Intermediate
30 seconds short answer

Merge commit: Keep all commits and real forks on the trunk--first-parenti.e. feature list, but with a noisier history.Squash: PR becomes a commit on the trunk, with clean history and simple rollback, but fine-grained commits are lost, and the source branch cannot be reused later (Issue #19).Rebase: Replay to trunk one by one, linearly and retain each commit, but commit hash changes, each commit should pass the build.

in-depth answer
MergeSquashRebase
trunk historynonlinearLinear, one PR and one commitLinear, keep all commits
granularityfineCoarse (PR grade)fine
rollbackrevert -m 1revert a commitrevert multiple commits
signatureReserveRe-signed by the platformThe original signature becomes invalid after replay (the platform will sign according to the situation)

Azure Repos also provides "Semi-linear merge" (rebase first and then --no-ff merge); GitLab has three project-level settings: Merge commit / Merge commit with semi-linear history / Fast-forward merge.

Frequently Asked Questions
  • Which one do you choose? ——State the reason: for example, “small PR + squash + conventional commit title” to facilitate automatic generation of changelog (Q33).
extra points

It is mentioned that the platform can restrict the allowed merge methods, and cooperate with the rule set "Require linear history".

Common wrong answers

Just say "squash is the best" without talking about the cost.

See detailsLesson 2 Pull Request Workflow、Lesson 3 Platform Merger Options。

Q22. What is rerere? When should it be turned on?Intermediate
30 seconds short answer

rerere = reuse recorded resolution. When turned on, Git records the appearance before the conflict (preimage) when it encounters a conflict, and records the result (postimage) after you resolve it; it automatically applies the same resolution the next time it encounters the same conflict. It is suitable for scenarios where long-term branches are repeatedly synchronized, repeatedly rebased, or try merging first and then giving up and redoing it.

in-depth answer
git config --global rerere.enabled true
git rerere status / git rerere diff # Currently recorded conflicts
git rerere forget path/to/file # Delete when recording error resolution

Records are saved locally.git/rr-cache, will not be shared with the push.

Frequently Asked Questions
  • Will error resolution be applied automatically? ——Yes (if the solution was wrong at first), so it will not be automatically added by default and needs to be checked before committing.
extra points

Mentioned that Linux kernel maintainers use rerere heavily for test merges; Mentionedmerge.conflictStyle=zdiff3。

Common wrong answers

"rerere resolves all conflicts automatically."

See detailsLesson 2 Conflict Resolution and Rerere, problem#15。

Q23. How to use git bisect to locate the commit that introduced the bug? How to automate?Intermediate
30 seconds short answer

bisect performs a binary search between "known good" and "known bad" commits. At each step, the intermediate commits are checked out so that you can judge whether they are good or bad, and the first bad commit is found in log₂(N) steps. usegit bisect run < script >Can be fully automated: script exit code 0 = good, 1–124 = bad, 125 = skip (cannot test).

in-depth answer
git bisect start
git bisect bad HEAD
git bisect good v1.0.0
git bisect run sh -c 'pip install -q -r requirements.txt && pytest -q tests/test_login.py'
git bisect log > bisect.log && git bisect reset

About 10 steps for 1000 commits. Available in more merged histories--first-parentWhich PR to target first.

Frequently Asked Questions
  • There was a commit in the middle but it failed to compile? ——git bisect skipOr the script returns 125.
  • Why require every commit to build? ——Otherwise bisect will skip frequently; during squash or rebase--execTesting helps.
extra points

Tell a true story: "Performance regression, bisect run + benchmark script took 20 minutes to locate a certain dependency upgrade." mentionedgit bisect terms --term-old fast --term-new slow。

Common wrong answers

"Checkout one by one and try back."

See detailsLesson 7 git bisect positioning regression。

Q24. If the commit is "lost", what methods do you have to retrieve it?Intermediate
30 seconds short answer

By level: ①git reflog(HEAD and branch movement records); ②ORIG_HEAD(position before reset/merge/rebase); ③git fsck --lost-found / --unreachable(Commits, stash, and temporary blobs without any references); ④ Remote and colleague clones (origin/xxx), closed PR (Restore branch) on the platform; ⑤ Unstaged modifications can only rely on IDE history.

in-depth answer
git reflog --date=iso | head
git log -g --grep='feat: login' --oneline
git fsck --unreachable --no-reflogs | grep commit | awk '{print $3}' | xargs git log --no-walk --oneline
git branch rescue <hash>
Frequently Asked Questions
  • How long will it take to find it? --reflog expires + gc after cleaning up unreachable objects (default 30 days / 2 weeks grace).
extra points

Mention the accident firstcp -aBack up the entire repository and set it up temporarilygc.auto=0。

Common wrong answers

"Clone again" - This will throw away the local reflog and unpushed objects.

See detailsLesson 7 reflog and fsck, issues #2, #6, #7, #10.

Q25. What are the differences between --force, --force-with-lease, and --force-if-includes?Advanced
30 seconds short answer

--forceUnconditionally overwriting remote branches may erase the commits just pushed by others.--force-with-leaseOnly if the remote branch is still equal to your locally recordedorigin/branchOverwrite (compare and swap) the position. But if you fetch in the background (IDE automatically fetches), the local record has been updated, and the lease will "mistakenly think it is safe";--force-if-includes(Git 2.30+) Additional check that your local branch actually contains the remote commit (based on reflog).

in-depth answer
git push --force-with-lease --force-if-includes
git push --force-with-lease=feature/login:1a2b3c4 # Explicitly specify the expected remote value, the most strict
git config --global alias.pushf 'push --force-with-lease --force-if-includes'
Frequently Asked Questions
  • Can protected branches be pushed? - Usually prohibited by rules (GitHub "Block force pushes", Azure Repos Force push permissions, GitLab Allowed to force push).
extra points

Note that the "value" of lease comes fromrefs/remotes/origin/*, so the background fetch will weaken it, which is exactly--force-if-includesThe reason for being introduced.

Common wrong answers

"--force-with-lease is absolutely safe".

See question for details#3、Lesson 2 Remote Branching。

Interview whiteboard diagram: three combined results of the same PR (Q14 Q21) Merge commit M (two parents)Original commit retained Squash S (a new commit)The original branch commit is not on main (#19) Rebase A' B' (new hash)Linear; original A B is replaced Choose based on: Do you need fine-grained bisect? Is changelog automatically generated? Convenience of rollback? Is signature retention required?No matter which one, the source branch should be deleted after the PR merge, and the next change should be opened from the latest main branch.
Figure 6-1 Commit diagram of three merge methods

Scenario question 6-1: On Friday afternoon, an unfinished feature was merged into main, and the CD will be released in 30 minutes.

You are the engineer on duty. Tell us about your operational steps, communication and subsequent improvements.

Reference answer key
  • First, the release pipeline is suspended (or environmental approval is not released).
  • git revert -m 1 <merge>Use emergency PR (use an audited bypass if necessary) and merge after CI passes; do not reset + force push.
  • Notify the person in charge of the function: This revert needs to be reverted before re-merging (Q20).
  • Improvements: feature switches, required approvals and checks before merging, smoke testing before release, merge queue.

Scenario question 6-2: Online performance dropped by 40%, 300 commits in the past two weeks, no one knows which one it is

Describe your targeting approach.

Reference answer key
  • Determine the good/bad boundary: a release from two weeks ago was labeled good, currently it is bad.
  • Write repeatable benchmark scripts (threshold judgment, exit code 0/1, cannot build return 125).
  • git bisect start --first-parent bad goodFirst locate the PR, then bisect within the PR; about 9 steps.
  • Revert or fix it after finding it; add the benchmark test to CI to prevent recurrence.
or score ≥ 70% on the Quiz

Module 7 · Part B: Collaboration Processes and Platforms (Interviews 26–38)

44:00 – 52:00 · Branch model, PR practice, branch protection and rule sets, CODEOWNERS, merge queue, fork, certification, committed commit, tags and releases, long-term branches, migration, hot fixes, comparison of four platforms
8 minutesGitHub · Azure Repos · GitLab · CodeCommit13 questions
learning objectives
  • Able to recommend branching models based on team size and release cadence, and explain trade-offs.
  • Be familiar with the "guardrails" provided by the platform: branch protection/rule sets, required reviews and status checks, CODEOWNERS, merge queues, push rules.
  • Able to design the versioning and labeling process from commit to release.
Q26. Compare trunk development, GitHub Flow and GitFlow. How would you choose?Intermediate
30 seconds short answer

trunk development: Everyone merges into main frequently (daily), short-lived branch + function switch, suitable for continuous deployment.GitHub Flow: main is always deployable, each change has a feature branch + PR, and is deployed after merging - essentially trunk development with PR.GitFlow: develop, feature, release, hotfix, main multiple long-term branches, suitable for versioned releases and products that need to maintain multiple versions at the same time (such as locally installed software), but the process is heavy and there are many mergers.

in-depth answer
Trunk/GitHub FlowGitFlow
release cadencemultiple times a dayBy version (week/month)
long term branchOnly main (may have release/* maintenance branches)main + develop + release/* + hotfix/*
unfinished featuresFunction switchStay in feature branch
conflictFew and smallMany and big

The DORA study lists "backbone development" as one of the capabilities associated with high delivery performance.

Frequently Asked Questions
  • How to ensure the stability of main during trunk development? ——Required CI, review, merge queue, function switch, automatic rollback.
  • What should I do if I need to maintain two versions, 1.x and 2.x? ——Trunk + release branch + cherry-pick move back (Q37).
extra points

Note: The author of GitFlow himself added in the original article: Continuously delivered web applications are more suitable for simple models such as GitHub Flow.

Common wrong answers

"GitFlow is the industry standard and should be used by all projects."

See detailsLesson 6 Branching Strategies Comparison。

Q27. What does a good Pull Request look like? How do you do a code review?Elementary
30 seconds short answer

It should be small (generally within a few hundred lines), have a single purpose, have a clear title (can be committed in a conventional commit format), describe the "why" and how to verify it, associate work orders, have a green CI, and review it yourself first. During the review, focus on correctness, design, testing, security and readability, give specific, executable and friendly-toned opinions, and distinguish between "must modifications" and "suggestions".

in-depth answer
  • Split major changes into stacked PRs (stacked PRs) or merge refactoring first and then merge features.
  • Draft PR (Draft) is for early feedback.
  • Template:.github/pull_request_template.md, PR template for Azure Repos, MR description template for GitLab.
  • Metrics: PR cycle time, review waiting time; review is a team priority, not "look at it when you have time".
Frequently Asked Questions
  • What should I do if there are differences in review opinions? ——Communicate offline first. If necessary, the CODEOWNER/technical leader will decide, and the conclusion will be written back to PR.
extra points

When it comes to automation handing over mechanical checking (formatting, lint, security scanning) to machines, reviewers focus on design and logic.

Common wrong answers

“The bigger the PR, the better it reflects the workload.”

See detailsLesson 2 Pull Request Workflow and Code Review。

Q28. What rules are typically included in a branch protection/rule set? What is the difference between GitHub rulesets and classic branch protection?Intermediate
30 seconds short answer

Common rules: PR must be merged, required number of reviewers, old approvals revoked after new commits are pushed, required status checks (CI must pass and branches need to be in sync with target), CODEOWNERS reviews, require conversations resolved, signed commits, linear history, no push and delete, merge queue. GitHub rule sets can be configured uniformly at the organizational level, multiple rule sets can be superimposed, have an "Evaluate" mode, can set bypass lists, and can act on tags and pushes (file paths, sizes, etc., some functions depend on the package).

in-depth answer
  • Azure Repos branch policy: Minimum number of reviewers, associated work items, comments resolved, merge type restrictions, build validation, status checks, automatically included reviewers by path.
  • GitLab: Protected branches (who can push/merge/force push), MR approval rules, code owner approval, push rules (Premium/Ultimate).
  • CodeCommit: Restricted by IAM policyGitPush/MergeBranches*To a specific branch + approval rule template.
gh api repos/org/myapp/rulesets --jq '.[] | {name, enforcement}'
Frequently Asked Questions
  • Can administrators bypass this? - Classic protection with optional "Include Administrators"; rule sets are explicitly controlled via bypass lists.
extra points

Mentioned the promotion method of "Evaluate mode and observe for a week before enforcing it".

Common wrong answers

"It's enough to turn on branch protection" - without configuring required status checks, CI failures can still be merged.

See detailsLesson 3 Azure Repos branch policy, GitHub ruleset、Lesson 4 CodeCommit and GitLab。

Q29. How does CODEOWNERS work? What are the pitfalls?Intermediate
30 seconds short answer

CODEOWNERS file (GitHub on.github/, root directory ordocs/) Map the path to the user/team according to the gitignore style mode; when PR modifies the matching path, these people will be automatically requested for review, and in conjunction with the "require code owner review" rule, it will become a mandatory access control.The last matching rule takes effect。

in-depth answer
* @org/platform-leads
/services/payment/ @org/payments
*.tf @org/infra
/.github/ @org/devops # Protect CI configuration and CODEOWNERS itself
  • Pitfalls: Sequence (wildcard rules written later will overwrite specific rules); the team needs to have write permissions on the repository; grammatical errors in the file will invalidate the rules (GitHub prompts an error on the interface); CODEOWNERS itself must be protected, otherwise anyone can change it.
  • GitLab supports CODEOWNERS sections and optional approval; Azure Repos does not have a CODEOWNERS file and is implemented using the "automatically include reviewers" path strategy.
Frequently Asked Questions
  • Review bottleneck due to too many owners in a large monorepo? - Hierarchical ownership, team rotation, enforcement only on sensitive paths.
extra points

Mentioned using CI to verify CODEOWNERS coverage (directories without owners).

Common wrong answers

"The first matching rule takes effect".

See detailsLesson 3 CODEOWNERS, Required Reviews and Status Checks。

Q30. What is a merge queue? What problem was solved?Advanced
30 seconds short answer

When many PRs are concurrently merged into a busy trunk, "the PRs each pass based on the old main test" does not guarantee that the merged combination will also pass (semantic conflict), and "requiring branches to be synchronized with main" will make everyone constantly rebase and rerun CI. The merge queue queues the PRs to be merged, and creates a temporary branch based on "main + all previously queued PRs" to run CI. After passing, the PRs are fast-forwarded and merged in sequence, and the failed PRs are removed from the queue.

in-depth answer
  • GitHub merge queue: CI needs responsemerge_groupEvents; configurable batch size and number of concurrent builds.
  • GitLab: Merge trains; Azure Repos has no built-in equivalent functionality (you can use external tools or pipeline constraints, please refer to the official documentation).
on:
  pull_request:
  merge_group: # Let temporary branches in the queue also trigger CI
Frequently Asked Questions
  • What happens if a PR in the queue fails? - It was removed and subsequent PRs were rebased on the new combination of tests.
extra points

Combine "trunk development + merge queue + function switch" to tell a story to improve throughput.

Common wrong answers

"The merge queue is auto-merge" - auto-merge only merges a single PR when the conditions are met, and does not test the combination.

See detailsLesson 3 GitHub ruleset、Lesson 4 GitLab。

Q31. What is the difference between fork mode and shared repository mode? When to use fork?Elementary
30 seconds short answer

Shared repository: All contributors create branches in the same repository, relying on permissions and branch protection control, suitable for internal teams within the company. fork: Contributors develop in their own copies and commit cross-repository PRs. Maintainers do not need to give write permissions to external contributors. It is suitable for open source and Inner Source cross-department contributions.

in-depth answer
git remote add upstream https://github.com/org/myapp.git
git fetch upstream && git rebase upstream/main # Synchronize upstream
gh repo sync alice/myapp # GitHub CLI synchronization fork
  • Security: CI triggered by PR from fork cannot get secrets by default (pull_requestevent); use with cautionpull_request_target。
  • Enterprises can prohibit private repositories from being forked to personal accounts.
Frequently Asked Questions
  • Why does the fork's PR not have permission to deploy the preview? ——Safety design, see above.
extra points

Mentioned the difference between the Inner Source pattern (Lesson 3) and the template repository (templates do not retain history and upstream relationships).

Common wrong answers

"Fork is clone".

See detailsLesson 3 Fork, Template Repository and Inner Source。

Q32. How to choose between SSH and HTTPS authentication? What problem does Git Credential Manager solve?Intermediate
30 seconds short answer

SSH: Based on key pairs, configured once for long-term use, suitable for developers; port 22 needs to be opened (GitHub also provides port 443). HTTPS: It is easier to penetrate enterprise proxies. Use OAuth browser to log in with GCM (supports MFA, SSO, conditional access). The token is safely stored in the system keychain, avoiding manual management of PAT. Machine identities should use short-lived tokens (GitHub App, OIDC, platform built-in tokens).

in-depth answer
  • GCM supports GitHub, Azure DevOps (Entra ID), GitLab, Bitbucket, across Windows/macOS/Linux.
  • Azure DevOps recommends using Entra tokens instead of PATs, and organizations can limit the creation and scope of PATs.
  • SSH keys can also be used to commit signatures (Q43).
git config --global credential.helper manager
git config --global credential.azreposCredentialType oauth # Azure Repos uses Entra OAuth token (subject to GCM documentation)
Frequently Asked Questions
  • Why not recommendedcredential.helper store? ——Save in clear text.
  • What to do with multiple accounts? ——Question #30.
extra points

Mentioned SSH certificates (organizations issue short-lived SSH certificates, GitHub Enterprise supports SSH CAs).

Common wrong answers

“HTTPS is not secure so use SSH” – both are encrypted, the difference is how the credentials are managed.

See detailsLesson 3 Authentication: SSH, HTTPS, Git Credential Manager。

Q33. What are Conventional Commits? How to combine it with semantic versioning and automatic publishing?Intermediate
30 seconds short answer

Conventional commit specifies the commit information format:type(scope)!: description, type such as feat, fix, docs, chore;!orBREAKING CHANGE:Footnotes indicate breaking changes. Based on this, the tool automatically determines the version number (fix → patch, feat → minor version, destructive → major version), generates a changelog, tags and releases (semantic-release, release-please, etc.).

in-depth answer
feat(auth): support SSO login
fix(payment)!: change rounding to banker's rounding

BREAKING CHANGE: amounts are now rounded half-to-even.
  • Use commitlint (commit-msg hook) to verify locally, and then verify again in CI (the hook can be bypassed).
  • When squash is merged, the PR title is the final commit information. Just verify the PR title.
  • GitLab push rules can enforce commit message formats with regex (Issue #37).
Frequently Asked Questions
  • What Git prerequisites are required for automatic publishing? --Full history and tags (Shallow Clone Issue #42).
extra points

Semantic versioning conventions referring to breaking changes during 0.x releases.

Common wrong answers

"Commit message format is just a matter of style" - it's input for automation.

See detailsLesson 5 Conventional Commitment, Semantic Versioning, and Automated Publishing。

Q34. What is the difference between lightweight tags and annotation tags? Best practices for publishing tags?Elementary
30 seconds short answer

The lightweight tag just points to the committed ref; the annotation tag is a tag object, including the tagger, date, information, and can be signed. Publishing should usePS (preferably signed) tag, do not move or reuse the tag once it is pushed (downstream caching and verification rely on it).

in-depth answer
git tag -a v1.4.0 -m "release 1.4.0" # Notes
git tag -s v1.4.0 -m "release 1.4.0" # Signature (GPG/SSH)
git push origin v1.4.0 # Tags will not be pushed with ordinary push
git push --follow-tags # Push note tags related to commits
git describe --tags # v1.4.0-3-g1a2b3c4
  • Use rulesets/protected tags to limit who can createv*Tags, deletion and updates are prohibited.
  • Platform Release tag-based additional artifacts and descriptions.
Frequently Asked Questions
  • What should I do if I type the wrong label? ——You can delete it and retype it before it is used; if it is used, release a new version (v1.4.1) and do not move the label.
extra points

Mention the SLSA provenance of the product to associate the product with the commit/label.

Common wrong answers

"git push will automatically push tags".

See detailsLesson 2 Commit Specifications, Tags, and Publishing。

Q35. A feature takes two months to develop. How to avoid the pain caused by long-term branches?Intermediate
30 seconds short answer

Break it into small increments that can be merged independently, usingFunction switchHide the unfinished parts and continue to merge them into the trunk; use "branch by abstraction" when you need to replace existing implementations. If you really need a long-term branch, sync from main at least once a day, enable rerere, and keep running CI.

in-depth answer
  • Function switch: Configure/switch service control, gradually increase the volume according to environment and user group; delete the switch code (technical debt) after completion.
  • Abstract branching: first introduce the interface, the old implementation coexists with the new implementation, gradually switch the caller, and finally delete the old implementation - each step can be merged.
  • Database changes: expand/contract mode, backward compatible.
Frequently Asked Questions
  • What to do if there are too many function switches? --Switches have owners and expiration dates, and CI reports expired switches.
extra points

Let the data speak: The merge conflict cost and integration risk of long-term branches increase nonlinearly with the branch life.

Common wrong answers

"Open a feature branch and merge it all at once after two months."

See detailsLesson 6 Branching Strategies, problem#15。

Q36. How to migrate a repository from one platform to another (such as Azure Repos → GitHub)? What will be lost?Intermediate
30 seconds short answer

The Git data itself (all branches, tags, history) can be migrated in its entirety:git clone --mirror + git push --mirror, LFS objects need to be separatedgit lfs fetch --all / push --all。Platform data(PR and comments, work items/issues, Wiki, branch strategy, pipeline, permissions, Webhook) are not in Git and require platform migration tools (for example, GitHub Enterprise Importer supports migrating some metadata from Azure DevOps, Bitbucket, GitLab, please refer to the official documentation) or rebuild.

in-depth answer
git clone --mirror https://dev.azure.com/org/proj/_git/myapp
cd myapp.git
git lfs fetch --all
git push --mirror https://github.com/org/myapp.git
git lfs push --all https://github.com/org/myapp.git
# Note: --mirror will push platform references such as refs/pull/*, which may be rejected by the target platform (hide ref). You can instead push only heads and tags:
git push https://github.com/org/myapp.git 'refs/heads/*:refs/heads/*' 'refs/tags/*:refs/tags/*'
  • Migration checklist: freeze write windows, update CI and deployment remote URLs, reconfigure branch protection and CODEOWNERS, notify developersgit remote set-url, the old repository is set to read-only and retained for a period of time.
  • One-way mirroring can be set up during the transition period (Lesson 4).
Frequently Asked Questions
  • Commit author mapping? ——If the email address is the same, you can associate the account on the new platform; otherwise, use mailmap.
extra points

Clean large files before migration (Issue #45), otherwise the target platform may reject them (Issue #32).

Common wrong answers

"Use git clone and then push to migrate everything" - ordinary clone only has the local branch of the default branch.

See detailsLesson 3 Migration、Lesson 4 Cross-Platform Mirroring。

Q37. When multiple released versions need to be maintained at the same time, how to release branches and hot fixes?Intermediate
30 seconds short answer

cut out from mainrelease/1.4, only accept fixes; fix default "Repair the trunk first, then cherry-pick -x and move it back” to a release branch that is still under maintenance (fixes will not be missed from trunk). In an emergency, the release branch can be repaired first, but it must be merged/backed to the trunk immediately, and the omissions checked with automation. Each release is tagged on the release branch.

in-depth answer
git switch -c release/1.4 v1.4.0
git cherry-pick -x < Main fix on >
git tag -s v1.4.1 -m "1.4.1"
git cherry -v release/1.4 main | grep '^+' | head # Changes in main but not in the release branch (auxiliary check)
  • Tool: backport bot/Action on GitHub, automatically creates backport PRs by tag.
  • Maintenance window: Several versions are explicitly supported, after which the branch is stopped being maintained (and protected or archived is removed).
Frequently Asked Questions
  • Why not merge the release branch back to main? ——Yes (GitFlow approach), but release-specific changes (version numbers) will be brought back to the trunk and need to be processed.
extra points

Mentioned that "fix commits are small and independent" to make rollbacks easier (Issue #18).

Common wrong answers

"It's over after the release branch is repaired" - Missing fixes in the trunk will be returned in the next version.

See detailsLesson 6 Release branches, hotfixes, and cherry-pick rollbacks。

Q38. Compare the differences in branch protection and review between GitHub, Azure Repos, GitLab, and AWS CodeCommit.Intermediate
30 seconds short answer

All four provide PR/MR, required review and protected branches, but the implementation methods are different: GitHub uses rule sets (organization-level, stackable, evaluation mode) + CODEOWNERS + merge queue; Azure Repos uses branch strategies (build verification, automatic reviewers by path, work item association) + fine-grained Git permissions (such as Force push, Bypass policies); GitLab uses protected branches + MR approval rules + CODEOWNERS sections + Push rules (paid tier) + merge trains; CodeCommit uses IAM policies to control who can push/merge to which branch + approval rule templates, which are closely integrated with the AWS identity system.

in-depth answer
AbilityGitHubAzure ReposGitLabCodeCommit
protection mechanismRule Set/Branch ProtectionBranch strategy + permissionsprotected branchIAM conditions + approval rules
Review by pathCODEOWNERSAutomatically include reviewersCODEOWNERS (sections)Approval rules (not by path)
CI access controlRequired status checkBuild validation/status strategiesThe pipeline must succeedNeed to integrate CodeBuild, etc.
Combinatorial testingmerge queue—Merge trains—

Function and package restrictions are subject to the official documents of each platform; CodeCommit will be fully available in 2025-11.

Frequently Asked Questions
  • How to unify governance in a multi-platform organization? ——Defining rules in code (Terraform provider/API) for unified auditing.
extra points

Mention "as-code" management of rules (e.g. managing branch protection with Terraform's github/azuredevops/gitlab provider).

Common wrong answers

Only familiar with one platform but claiming "all are the same".

See detailsLesson 3、Lesson 4。

Interview Whiteboard Diagram: Guardrails from Commit to Release (Q27–Q34) local commitpre-commit · commitlint push branchPush protection · Push rules PR / MRCI · CODEOWNERS · Review merge queueCombinatorial testing mainNo push/deletion allowed Tag / ReleaseSignature · Protected Label Client-side check (can be bypassed, provides fast feedback) → Server-side/platform check (cannot be bypassed, true access control)The same rule is placed in both places: local commitlint + CI verification PR title; local gitleaks + platform push protectionBypass must be explicit and auditable (rule set bypass list / Bypass policies permission)
Figure 7-1 Defense in depth: Each layer blocks a different problem

Scenario Question 7-1: Design a collaboration process for 40 people, 5 teams, and a web product

Deployed multiple times a day; there are compliance requirements (changes need to be reviewed and traced). Please design the branch model, protection rules and release method.

Reference answer key
  • GitHub Flow / trunk development: short-lived branches, PR, squash merge, feature switches.
  • main ruleset: PR required, 1–2 reviews, CODEOWNERS (per service catalog), required CI, conversation resolved, no push/remove, merge queue.
  • Traceability: PR associated work order (Azure Boards/Jira), agreed commit title, signature commit (optional).
  • Release: After merging, it is deployed to pre-release and then to production after environment approval; tag + Release are automatically generated.
  • Metrics: Deployment frequency, change failure rate, PR cycle time.

Scenario 7-2: An open source project receives a PR from a fork and needs to run integration tests using cloud credentials

How to test external contributions without leaking confidentiality?

Reference answer key
  • Default pull_requestEvents only run tests that do not require confidentiality.
  • Integration tests require maintainer approval (first-time contributor approval, environment approval, "ok-to-test" tag trigger).
  • avoid inpull_request_targetCheck out and execute PR code; isolate permissions, minimize tokens if necessary.
  • Cloud credentials use OIDC short-lived tokens and restricted subjects.

Scenario 7-3: The company wants to move 200 repositorys from Azure Repos to GitHub

Give a migration plan.

Reference answer key
  • Inventory: repository size, LFS, activity, pipeline dependencies, permission model, whether PR needs to be retained.
  • Tools: GitHub Enterprise Importer (supported metadata is subject to documentation) or mirror script; large repositorys are cleaned up in advance.
  • In batches: pilot 5 projects first to verify CI, permissions, and rule set templates; then divide them into waves according to teams, and set a freezing window for each wave.
  • Finishing touches: old repository read-only, redirection instructions, updated wiki/documentation links, revocation of old PAT.
or score ≥ 70% on the Quiz

Module 8 · Part B: Scaling, Security, and Scenario Design (Interviews 39–50)

52:00 – 60:00 · monorepo, large repository performance, LFS, submodules, signatures, secret leaks, hooks, CI checkout, team and migration design, supply chain, incident handling
8 minutesFrequent exams for senior positions12 questions
learning objectives
  • When answering "design" questions, first clarify the requirements (scale, rhythm, compliance), and then provide solutions and trade-offs.
  • Master Git-level security controls: signatures, confidentiality protection, rule sets, least privileges, and auditing.
  • A complete toolbox that can be used to optimize the performance of large repositorys.
Q39. How to choose between Monorepo and Polyrepo?Advanced
30 seconds short answer

Monorepo: Atomized cross-project changes, unified dependencies and tools, easy code sharing and refactoring; the price is that the build system needs to support incremental build/testing (Bazel, Nx, Turborepo, etc.), CI path filtering, fine-grained ownership (CODEOWNERS), and large repository performance measures. Polyrepo: Clear boundaries, independent permissions, and a small repository. The price is that cross-repository changes require coordination of multiple PRs, dependency version drift, and tool duplication.

in-depth answer
  • Decision factors: degree of coupling between teams, whether releases need to be consistent, whether the organization is willing to invest in building a platform, access control requirements (Git cannot authorize reads by directory).
  • Monorepo's Git methods: partial clone + sparse checkout, commit-graph, fsmonitor, scalar, merge queue, path filtered CI.
  • Compromise: A small number of medium-sized repositories divided by domain; shared libraries are released through a package manager.
Frequently Asked Questions
  • How to build only the affected parts in a monorepo? ——Based ongit diff --name-only $(git merge-base origin/main HEAD)Add dependency graph; note shallow cloning issue #42.
extra points

For example: the monorepo of a large technology company relies on a customized version control/virtual file system; an ordinary team can support a considerable scale by using partial cloning and sparse checkout of Git.

Common wrong answers

"Monorepo puts all the code in one repository, with no additional cost."

See detailsLesson 6 Monorepo vs. Polyrepo trade-off。

Q40. It takes 40 minutes to clone a large repository and 10 seconds to perform git status. How would you optimize it?Advanced
30 seconds short answer

Measure first (git-sizer,count-objects、GIT_TRACE2_PERF), and then process them separately:Many/large objects→ partial clone--filter=blob:none, LFS, clean history;Many working tree files→ Sparse checkout (cone mode),core.fsmonitor、core.untrackedCache、split index;deep history→ commit-graph (including changed-path Bloom filter), multi-pack-index;maintenance → git maintenance start;or directlyscalar cloneGet the recommended configuration.

in-depth answer
GIT_TRACE2_PERF=1 git status 2>&1 | grep -E 'region_leave.*(refresh|untracked)' | head
git config feature.manyFiles true # A set of default values suitable for large working trees (index v4, untracked cache, etc.)
git sparse-checkout set --cone services/payment
git commit-graph write --reachable --changed-paths
git maintenance start
  • Server side: pack bitmap, bundle URI (download the bundle from CDN before cloning, subject to platform support).
  • CI: Shallow cloning + caching + checking out only the paths you need.
Frequently Asked Questions
  • Disadvantages of partial cloning? ——Requires network to obtain on demand; downloading will be triggered when blame/log -p is used.
extra points

Emphasize "measure first and then optimize" and provide indicators before and after optimization.

Common wrong answers

"Use --depth=1 for developers" - developers need history (log, blame, merge-base).

See question for details#39、Lesson 6 Large Repository。

Q41. What is the principle of Git LFS? What are the trade-offs?Intermediate
30 seconds short answer

LFS passed.gitattributes of filter=lfsRegister the clean/smudge filter: When committing, the large file content is stored in LFS storage (uploaded via LFS API). Only a pointer file of about 130 bytes is saved in Git; when checking out, the real content is downloaded based on the pointer. The repository history remains small, but introduces additional services, quotas, bandwidth costs, and the "pointer without LFS installation" problem.

in-depth answer
git lfs track "*.psd" "*.bin" # Write .gitattributes
git lfs ls-files
git lfs lock design/home.psd # Binary files that cannot be merged can be locked (requires server support)
GIT_LFS_SKIP_SMUDGE=1 git clone ... # Don't download yet, git lfs pull --include as needed
  • Large files already in history:git lfs migrate import(Rewriting history).
  • Alternatives: partial cloning (large files still in Git but downloaded on demand), artifact repository/object storage.
Frequently Asked Questions
  • Why does CI get a pointer? ——Question #40.
  • What happens to LFS objects when migrating platforms? ——Need to be pushed separately (Q36).
extra points

Compare LFS with partial cloning: the latter requires no additional services, but requires server-side support for filtering and large binaries are still difficult to delta compress.

Common wrong answers

"LFS compresses large files".

See detailsLesson 6 LFS。

Q42. What is the difference between submodule and subtree? Which one would you recommend?Intermediate
30 seconds short answer

Submodule: The parent repository only records the URL of the subrepository and a certain commit (gitlink), and the subrepository maintains an independent history; the version is precisely fixed, but additional commands are required (--recurse-submodules), prone to uninitialization or version inconsistency (Issue #41). subtree: Merge the contents of another repository (optional flattening history) into a subdirectory. The cloner will not be aware of it, but it is troublesome to synchronize the upstream and push back the changes. In many scenarios, using a package manager to publish versioned libraries is more appropriate than either.

in-depth answer
git submodule add https://github.com/org/auth.git libs/auth
git submodule update --remote libs/auth # Update to the latest commit of the sub-repository, and then commit gitlink in the parent repository
git subtree add --prefix=libs/auth https://github.com/org/auth.git main --squash
git subtree pull --prefix=libs/auth https://github.com/org/auth.git main --squash
Frequently Asked Questions
  • CI failed to pull private submodule? - The token is only valid for the current repository (Issue #41).
extra points

Can tell gitlink mode 160000, andsubmodule.recurse=true。

Common wrong answers

"The submodule will automatically follow the latest commit of the subrepository" - No, it is fixed on the recorded commit.

See detailsLesson 6 Submodules and subtrees。

Q43. Why do I need to sign for commit? What are the differences between GPG, SSH and gitsign?Intermediate
30 seconds short answer

Git's author information can be arbitrarily forged (problem #5), and the signature proves that "this commit was indeed created by the person holding a certain key and has not been tampered with." GPG: traditional method, key management is complex; SSH signature (Git 2.34+): reuses SSH keys, simple configuration, platform supports display Verified; gitsign (Sigstore): no long-term key, exchanges OIDC identity for short-term certificate, signature is recorded in transparent log.

in-depth answer
git config --global gpg.format ssh
git config --global user.signingkey ~/.ssh/id_ed25519.pub
git config --global commit.gpgsign true
git config --global tag.gpgsign true
git log --show-signature -1 # Local authentication requires gpg.ssh.allowedSignersFile (Issue #46)
  • Platform rules can require signed commits (Issue #37); GitHub's vigilant mode will mark unsigned commits as Unverified.
  • The squash/rebase merge is signed by the platform (the original signature is not retained).
Frequently Asked Questions
  • Can signatures protect against malicious code? ——No, it proves the source but not the safety of the content; it still needs to be reviewed.
extra points

Combined supply chain security: signature label + product provenance (Q49).

Common wrong answers

"You can prove your identity by setting user.email."

See detailsLesson 5 Commit and Tag Signing: GPG, SSH, gitsign。

Q44. If you find that someone has pushed the cloud access key to GitHub, what is your disposal process?Advanced
30 seconds short answer

The first step is to immediately revoke/rotate the key, and check the cloud audit log to confirm whether it has been abused; then evaluate the exposure scope (public or private, how long, and whether there is a fork); then decide whether to clean up the history (filter-repo rewrite + force push + all employees re-clone + contact the platform to clean the cache); finally review and add preventive measures (push protection, pre-commit scanning, use OIDC to eliminate long-term keys).

in-depth answer
  1. Revocation: The cloud console disables the key and issues a new key (or changes to OIDC, which eliminates the long-term key entirely).
  2. Investigate: Invocation of this key in CloudTrail/Azure Activity Log; keys for public repositories may be exploited by automated scans within minutes.
  3. Cleanup: Steps to issue #50; note that old clones and forks will reflow secrets.
  4. Notification: Report according to company security incident procedures.
  5. Prevention: GitHub push protection/confidential scanning (partners will automatically revoke leaked tokens on some platforms), gitleaks pre-commit hook, secrets stored in a vault.
Frequently Asked Questions
  • Is it okay to just delete the file and commit it again? — No, it still exists in history (issues #4, #50).
  • Do private repositorys also need to be rotated? ——Yes, everyone with access to the repository, CI logs, and backups may be exposed.
extra points

Mentioned runbooks, average response time metrics.

Common wrong answers

"It will be safe to delete the history with filter-repo first" - the order is wrong, and the cloned copy cannot be recovered.

See question for details#50、Lesson 7 filter-repo。

Q45. What are the Git hooks? What is the difference between client-side hooks and server-side hooks? What does the pre-commit framework solve?Intermediate
30 seconds short answer

Client-side hooks run on the developer machine: pre-commit, prepare-commit-msg, commit-msg, pre-push, post-checkout, etc., for quick feedback, but are not distributed with clones and can be--no-verifyBypass. Server-side hooks (pre-receive, update, post-receive) run on the server and can be enforced; the hosting platform packages them as branch protection, push rules, and Webhooks. The pre-commit framework uses the configuration file in the repository to uniformly declare hooks and their versions, and automatically installs the isolation environment.

in-depth answer
# .pre-commit-config.yaml
repos:
  - repo: https://github.com/pre-commit/pre-commit-hooks
    rev: v6.0.0 # 2026-11 latest, subject to project release
    hooks: [ {id: check-added-large-files}, {id: end-of-file-fixer} ]
  - repo: https://github.com/gitleaks/gitleaks
    rev: v8.30.1 # 2026-11 latest, subject to project release
    hooks: [ {id: gitleaks} ]

Run in CIpre-commit run --all-filesActs as a required check to cover client-side issues that can be bypassed.

Frequently Asked Questions
  • Hook not executing? --Issue #49.
extra points

mentionedcore.hooksPath, and the "hook definition in configuration" that Git is introducing (hook.<name>.command, the available versions are subject to the githooks documentation).

Common wrong answers

"With pre-commit hooks there is no need for CI checks".

See detailsLesson 5 Git hooks and pre-commit framework。

Q46. What are the best practices for Git checkout in CI?Intermediate
30 seconds short answer

Choose depth as needed (shallow clone for builds, full history or--filter=blob:none); enable tags, LFS, submodules on demand; use short-term tokens provided by the platform, and do not retain credentials after the job ends (such as actions/checkout'spersist-credentials: false); note that the container user and safe.directory; cache dependencies rather than cache the entire.git(unless evaluated).

in-depth answer
- uses: actions/checkout@v7 # The version is subject to Marketplace
  with:
    fetch-depth: 0 # When history/tags are needed
    filter: blob:none # Large repository: complete commit history but download file content on demand
    lfs: false # true when needed
    submodules: false # Recursive when needed and provide a token to access submodules
    persist-credentials: false # When subsequent steps do not require push
  • The PR build checks out the merge preview commit; the basis for calculating the diff must be clear.
  • Use the least privilege token when pushing (labeling, automatic commit) in CI, and prevent recursive triggering.
Frequently Asked Questions
  • describe failed? -- Issue #42. Dubious ownership? -- Issue #47.
extra points

Mentioned third-party Action fixed to commit SHA (to prevent tag tampering).

Common wrong answers

"Always fetch-depth: 0 in CI" - large repositorys are a waste of time.

See detailsLesson 5 Checkout in CI。

Q47. Design question: Design a Git branch and release strategy for a company with 200 engineers, mobile + backend + shared libraries.Advanced
30 seconds short answer

Let’s first clarify: the release rhythm (every day for the backend, once every two weeks for the mobile version according to the app store), the number of versions that need to be maintained, compliance requirements, and repository layout. Solution example: Backend trunk development + function switch + merge queue continuous deployment; mobile terminal trunk development + release branch (release/2026.11) After freezing, only receive move-back repairs and releases with signed tags; independent versioning of shared libraries (semantic version + automatic release); unified rule set templates and CODEOWNERS.

in-depth answer
  • Repository: back-end monorepo (many services, tight coupling) + respective repositorys on the mobile terminal + shared libraries published as packages.
  • Rules: Organization-level rule set (PR, review, required inspection, no push, signature optional); by catalog CODEOWNERS.
  • Release: The backend is merged and deployed to pre-release, and the volume is gradually increased; the mobile release branch + hot fix rollback process + the version number comes from the label.
  • Metrics: DORA four indicators; PR cycle time.
Frequently Asked Questions
  • How to deal with breaking API changes across backend and mobile? ——Versioned API, expansion-contraction, function switch.
extra points

Structural expression: requirements → constraints → solutions → trade-offs → evolution path.

Common wrong answers

Just say "use GitFlow" without asking about the requirements.

See detailsLesson 6 Branch Strategy and Repository Architecture in Practice。

Q48. Design question: Migrate a 15-year-old, 40 GB SVN/TFVC repository to Git.Advanced
30 seconds short answer

Assess → Decide on history retention policy → Clean and split → Convert → Validate → Cutover → Freeze the old system. Key decisions: whether to keep the entire history (audit requirement) or migrate only the last N years and archive the old repository; convert large binaries to LFS or move out; split the repository by module; author mapping.

in-depth answer
  • Tools: SVN →git svn clone --stdlayout --authors-file=authors.txt(slow) or svn2git-like tools; TFVC → Azure Repos import (only limited history is imported, subject to documentation) or git-tfs.
  • After conversion:git filter-repoRemove large files/split subdirectories;git lfs migrate import;git-sizer verification.
  • Verification: Randomly extract version comparison file tree; construct the most recent tags.
  • Switching: Freezing windows, read-only legacy libraries, updating CI, training and cheat sheets (questions #1–#12 are the most common pitfalls for newbies).
Frequently Asked Questions
  • What to do with SVN’s externals? - Submodules, subtrees or package managers (Q42).
  • What about path-level permissions? ——Split the repository or use CODEOWNERS + rule set to control writing (read permission can only be per repository).
extra points

Emphasize that “migration is a people issue”: training, pilots, support channels.

Common wrong answers

"Just import 40 GB of history" - the push is likely to be rejected by platform restrictions (Issue #32, #33).

See detailsLesson 6 Repository Migration: SVN/TFVC to Git。

Q49. From the perspective of source code repository, what software supply chain security measures will you take?Advanced
30 seconds short answer

Identity: SSO + enforced MFA, least privileges, periodic access review, short-lived token (OIDC/GitHub App) in place of PAT. Change Control: Rule Sets (PRs, Reviews, CODEOWNERS Protected CI Configuration, Required Checks, No Pushes), Signed Commits and Tags. Confidential: Push Protection + Scan + Vault. Dependencies: Dependabot/Renovate, dependency review. CI: Third-party Action fixed SHA, minimumpermissions, fork PR isolation. Traceability: Audit log streaming export, product source attestation (SLSA).

in-depth answer
  • OpenSSF Scorecard can automatically evaluate a repository for these practices.
  • protect.github/workflows、CODEOWNERS、.gitattributes, build scripts - these are the "game-changing files".
  • Release: Signing Tag → CI Build → Generate Provenance → Signed Artifacts → Pre-deployment Verification.
Frequently Asked Questions
  • What implications does the xz-utils backdoor incident give to Git? ——The importance of maintainer permissions and review, verification of the consistency of released tarballs and repository contents.
extra points

Measures can be mapped to threats: account stolen → MFA; internal malicious commit → double review; CI exploited → least privilege token.

Common wrong answers

Just say "Turn on 2FA."

See detailsLesson 5 Signatures and Confidentiality、Lesson 3 Rule Sets。

Q50. Scenario: Production accident, the regression needs to be located, repaired and hotfix released within 1 hour. Describe your entire Git operation process.Advanced
30 seconds short answer

Stop bleeding first: roll back the deployment first (redeploy the previous label) or turn off the function switch. Then position: compare commits between two release tags (git log v1.4.0..v1.4.1), when necessarygit bisect run. Repair: If the trunk has advanced a lot, hotfix the branch from the release tag → fix + test → PR (emergency review) → tag release → cherry-pick back to the trunk (or fix the trunk first and then move back, depending on the team agreement). Final review.

in-depth answer
git fetch --tags
git log --oneline --no-merges v1.4.0..v1.4.1 # Changes included in this release
git diff --stat v1.4.0 v1.4.1
git switch -c hotfix/1.4.2 v1.4.1
# Fix + Test
git commit -am "fix(payment): handle null currency"
git push -u origin hotfix/1.4.2 # Emergency PR → merge into release branch
git tag -s v1.4.2 -m "hotfix 1.4.2" && git push origin v1.4.2
git switch main && git cherry-pick -x <fix> # Return to the trunk (take PR)
Frequently Asked Questions
  • Rollback or rollforward? ——Depends on whether the data migration is reversible and whether the repair is simple.
  • Hotfix skipping CI? - Not skipped, but can use accelerated set of required checks; bypasses required audits.
extra points

Talk about timeline and communication (incident channel, status page), as well as improvement items for review output (testing, alarms, function switches).

Common wrong answers

"Change directly on main and push it."

See detailsLesson 6 Hot Repair、Lesson 7 Bisect。

Interview whiteboard diagram: Correct order of handling confidential leaks (Q44 / Question #50) ①Revocation/rotationCompleted in minutes ② Investigate abuseCloud audit log ③ Freeze + NotificationLock the branch and notify collaborators ④ Rewrite historyfilter-repo + strong recommendation ⑤ Backflow prevention + preventionRe-clone · Push protection Why rewriting history cannot be the first step: there are still old commits in old clones, forks, CI caches, and platform cache viewsSecrets should be considered leaked once they are pushed; rewriting history only reduces future exposureThe best solution is to have no long-term secrets: OIDC for CI and managed identities for applications
Figure 8-1 If you talk in this order during the interview, you will get a much higher score than just talking about filter-repo.

Scenario question 8-1: monorepo's CI runs all 2 hours of testing every time

The repository contains 30 services. How to reduce the CI time of PR to less than 15 minutes?

Reference answer key
  • Change detection:git diff --name-only $(git merge-base origin/main HEAD), make sure you have the target branch with enough history when checking out (Issue #42).
  • Dependency graph: Declaration of dependencies between services (build tools or custom manifests), affected services and their downstreams for testing.
  • Checkout speedup:--filter=blob:none+ Sparse checkout only takes affected directories.
  • Run a complete test in the merge queue or run a full test at night to save the day.
  • Caching dependencies and build artifacts (remote caching).

Scenario question 8-2: Audit requirement "Every change in production code can be traced back to an approved work order, and the author's identity is credible"

What controls would you implement at the Git and platform level?

Reference answer key
  • Rule set: PR required, at least 1 non-author reviewer, new push after approval to revoke approval, forced push and deletion prohibited.
  • Ticket correlation: Azure Repos "Relate work items" strategy; GitHub checks the ticket number in the title with PR template + CI.
  • Identity: SSO + MFA; requires signature commit; push rules limit commit of email domain names.
  • Evidence: Audit log export to SIEM; release tag signature; deployment record correlation commit SHA.

Scenario question 8-3: A new colleague said "Git is too difficult and I always break the repository"

As the team’s Git lead, what support and guardrails will you provide?

Reference answer key
  • Guardrails: protected main (it is impossible to directly destroy the shared history), push protection, pre-commit hooks, and unified merge methods.
  • Tools: Shell prompt displays branches and status, unified.gitconfigFragments (pull.rebase, autoStash, rerere, pushf aliases).
  • Education: Questions 1–12 for this lesson cheat sheet, “reflog safety net” demo, pair programming.
  • Culture: Mistakes can be recovered, questions are encouraged, and on-duty channels provide quick support.
or score ≥ 70% on the Quiz

Question Cheat Sheet + Interview Flashcards

50 "Error reporting → First diagnostic command → Common fixes" · 50 one-sentence bullet points cards · Printable
After class

A · 50 quick production questions

Enter keywords to filter (e.g.reflog、non-fast-forward、403、LFS). Click on the number to jump to the detailed explanation of the corresponding module.

B · 50 Interview Questions Shorthand Cards

First read the question and recall it yourself, then expand and compare the key points of one sentence; for details, return to the "Detailed Explanation of Interview Questions" in the corresponding module.

Universal command card

status and history

git status -sb
git log --oneline --graph --all -20
git log --oneline --left-right HEAD...@{u}
git show --stat HEAD
git log -S 'text' -p -- path # pickaxe: Who added or deleted this text
git blame -w -C -L 10,30 file

Retrieval and cancellation

git reflog -20
git branch rescue HEAD@{1}
git fsck --lost-found
git reset --soft|--mixed|--hard REF
git restore [--staged] file
git revert [-m 1] COMMIT
git rebase --abort | git merge --abort

Remote and Authentication

git remote -v; git fetch --prune
git push --force-with-lease --force-if-includes
ssh -vT git@github.com
printf 'protocol=https\nhost=github.com\n\n' | git credential reject
GIT_TRACE=1 GIT_CURL_VERBOSE=1 git ls-remote URL
git config --show-origin --show-scope -l

Big Repository/CI/Security

git clone --filter=blob:none --sparse URL
git sparse-checkout set dir1 dir2
git rev-parse --is-shallow-repository; git fetch --unshallow --tags
git lfs install && git lfs pull
git ls-files --eol; git add --renormalize .
git config --global --add safe.directory /path
git count-objects -vH; git maintenance start

Comprehensive drill + mock interview

8 mixed failure scenarios (see the phenomenon first, judge by yourself, and then develop the answer) · Full mock interview with 10 randomly selected questions from 50 questions · Final exam
After class ≈ 40 minutes

1. Comprehensive fault drill

Each scenario combines multiple questions from Part A. Write down your first diagnostic command and judgment first, then develop the answer.

Scenario 1:First day for new colleagues: Commit after cloning, push rejected twice with different errors
Time 1: Author identity unknown *** Please tell me who you are.
The 2nd time (commit and push main after configuration):
remote: error: GH006: Protected branch update failed for refs/heads/main.
Time 3 (push to new branch):
remote: error: GH013: Repository rule violations found for refs/heads/feature/x.
remote: - Commits must have verified signatures.

Answer:No identity configured (#5) → Push main directly and rejected by protection rules (#29, #1) → Signature rules (#37). Steps:git branch feature/x && git reset --hard origin/main;Configure SSH signature and register the Signing key on the platform;git rebase origin/main --exec 'git commit --amend --no-edit -S';Push the branch and create a PR. Improvement: unified configuration of onboarding scripts.

Scenario 2:"I rebase, then pull, and now there are 60 commits in the PR, many duplicates"
$ git log --oneline --cherry-mark --left-right origin/main...HEAD | head
> = 5d6e7f8 feat: search
> = 1a2b3c4 feat: search
>   9e0f1a2 Merge branch 'feature/search' of github.com:org/myapp
...

Answer:After rewriting the pushed branch, use the merge method to pull, and the old and new copies are merged (#16, #3). Fix:git reset --hard ORIG_HEADOr find the commit after rebase from reflog and confirmgit push --force-with-lease --force-if-includes; If the PR also contains commits from others, userebase --onto(#24). Improvements:pull.rebase=true。

Scenario 3:After publishing on Monday, I discovered that the fixes merged last Friday were missing.
$ git log --oneline -S 'validate_amount' -- app/payment.py
7d8e9f0 Merge branch 'feature/refactor'
3c4d5e6 fix: validate amount
$ git show --remerge-diff 7d8e9f0 -- app/payment.py
-    validate_amount(amount)

Answer:Wrong side of conflict resolution was chosen when merging feature/refactor, fix was discarded (#22). Fix:git cherry-pick -x 3c4d5e6Go through the hot repair process (Q50); add regression testing; used when reviewing and merging--remerge-diff。

Scenario 4:The version number on CI becomes 0.0.0, monorepo change detection considers "no change", and the image test fails.
fatal: No names found, cannot describe anything.
fatal: ambiguous argument 'origin/main...HEAD': unknown revision or path not in the working tree.
AssertionError: image size 131 bytes
$ head -1 tests/fixtures/logo.png
version https://git-lfs.github.com/spec/v1

Answer:Shallow clones lack history and tags (#42) + LFS is not enabled (#40). actions/checkout settingsfetch-depth: 0(orfilter: blob:none+ full history) withlfs: true;Before change detectiongit fetch origin main。

Scene 5:A PR from a Windows colleague shows that all 120 files have been modified, and an error occurs when the container is started.
warning: in the working copy of 'entrypoint.sh', LF will be replaced by CRLF the next time Git touches it
$ docker run myapp
/usr/bin/env: 'bash\r': No such file or directory
diff --git a/scripts/deploy.sh b/scripts/deploy.sh
old mode 100755
new mode 100644

Answer:Newline character (#43) + permission bit (#48). add.gitattributes(* text=auto eol=lf、*.sh text eol=lf) andadd --renormalize;git update-index --chmod=+xFix executable bit; normalize commit added.git-blame-ignore-revs。

Scene 6:After changing to a new computer and a new work account, push keeps getting 403, but clone is normal.
remote: Permission to org/myapp.git denied to alice-personal.
fatal: unable to access 'https://github.com/org/myapp.git/': The requested URL returned error: 403
$ git config --show-origin --get-all credential.helper
file:C:/Program Files/Git/etc/gitconfig    manager

Answer:GCM caches personal accounts (#30), and personal accounts only have read permissions for the organization repository (#28).git credential-manager github logout alice-personalorgit credential reject;Use multiple accountscredential.useHttpPathOr write the username in the URL, or the SSH Host alias (#27).

Scene 7:Migrating 12 GB repository to GitHub, push failed
remote: error: File db/dump-2019.sql is 612.40 MB; this exceeds GitHub's file size limit of 100.00 MB
remote: error: GH001: Large files detected.
---
(Delete and then push) error: RPC failed; HTTP 413 curl 22 The requested URL returned error: 413
send-pack: unexpected disconnect while reading sideband packet

Answer:Large files in history (#32, #45) + push volume/proxy limits (#33). First, do the image cloninggit filter-repo --strip-blobs-bigger-than 50M(Convert to LFS if needed), then push in batches; don’t rely onhttp.postBuffer。

Scene 8:Confidential scan alert: AWS key was pushed to main three months ago; someone cleared the history last week, but the alert reappeared
$ git log --all --oneline -- config/prod.env
4c5d6e7 Merge branch 'main' of github.com:org/myapp ← bob, yesterday
1a2b3c4 chore: add prod env
$ aws iam list-access-keys --user-name deploy-bot
"Status": "Active" ← The key has never been rotated

Answer:The processing order is wrong: there is no rotation first (Q44), and after cleaning, the old clone brings the secrets back through merging (#50). Immediately deactivate the key and check CloudTrail; freeze the repository, re-execute filter-repo, require all employees to re-clone, and close old PR/fork; CI switches to OIDC; enable push protection and pre-commit scanning (#4).

2. Full mock interview (10 randomly selected questions out of 50)

2-minute countdown for each question: answer orally first (you can write key points in the text box), then expand the reference answers, and self-assess "Yes/Partially/No". After the end, the score of this round is displayed, and the cumulative mastery rate is displayed by module. The self-assessment results are saved in this browser.

3. Open-ended self-assessment (6 questions)

  1. Draw the object diagram of commit → tree → blob, and use it to explain why the commit can be retrieved after reset --hard, but the modifications without add cannot be retrieved.
  2. Use the commit diagram to explain: Why is the push after amend rejected? Why doesn't merging again take effect after revert is merged?
  3. What four levels does a push have to pass through? List two errors and state the first diagnostic command.
  4. What parameters do you consider when doing a CI checkout? Which problem number does each parameter prevent?
  5. Compare the impact of squash, merge commit, and rebase on bisect, rollback, and branch cleanup.
  6. What is the order of handling a confidentiality breach? Why is rewriting history not the first step?

4. Final exam (12 questions)

Sources and imprints

Verification date: 2026-11-15 · Version baseline: Git 2.56 · Git LFS 3.8 · Git Credential Manager 3.0 · actions/checkout v7

Official documentation source

TopicConclusions used in this lessonSource (Accessed on 2026-11-15)
Git 2.56 release notesgit refsAdded create/delete/update/rename; experimentalgit history drop;git replay --linearize;git push origin/mainTips for typographical errors;includeIfSupport working tree location;fetch.followRemoteHEADRelNotes/2.56.0
Git 3.0 planDefault reftable, default branch main, SHA-256, etc. are allin planBreakingChanges
Cancellation and retrievalreset mode, reflog expiration time, fsck --lost-foundgit-reset · git-reflog · git-gc · git-fsck
Merge and rebaseFast forward rules, pull fork configuration, rerere, revert -m, rebase --onto, remerge-diff, ortgit-push · git-pull · git-rerere · revert-a-faulty-merge · git-rebase
Configurationsafe.directory (CVE-2022-24765, 2.35.2), http.postBuffer limitations, core.autocrlf/fileMode/ignorecase, feature.manyFilesgit-config
large repositoryPartial cloning, sparse checkout cone mode, scalar, maintenance, commit-graphpartial-clone · sparse-checkout · scalar · maintenance
gitattributestext/eol、binary、filter=lfsgitattributes
Git LFSThe latest v3.8.1 (2026-10-22); pointer format, migrate, lockgit-lfs releases · git-lfs.com
Git Credential ManagerLatest v3.0.2 (2026-10-26)GCM releases
git filter-repoLatest v2.47.0; standalone tool (pip/package manager installation)newren/git-filter-repo
actions/checkoutThe latest v7.0.1 (2026-07-20); default fetch-depth 1, lfs false, persist-credentials default trueactions/checkout
pre-commit / gitleakspre-commit-hooks v6.0.0、gitleaks v8.30.1、pre-commit v4.7.0pre-commit-hooks · gitleaks
GitHubPassword authentication removal (2021-08-13), GH001/GH006/GH013, push protection, rule set, SSH fingerprint (RSA key replaced on 2023-03-24), merge queue, sensitive data deletionAbout rulesets · Push protection · RSA host key update announcement
Azure ReposBranch Strategy, TF402455, TF401019, GCM + Entra CertificationBranch policies · Authentication
GitLabProtected branches, push rules (paid tier), Merge trains, shallow clone default depthProtected branches · Push rules
AWS CodeCommit2024-07 Stop accepting new customers; 2025-11 Return to full availability; git-remote-codecommit; macOS keychain cache causes 403Troubleshooting · git-remote-codecommit

Video verification instructions

All videos were uploaded on 2026-11-15 through the YouTube oEmbed interface (https://www.youtube.com/oembed?url=…&format=json) Verify title and channel; oEmbed does not return duration and release date, so they are not marked. Verified: Programming with Mosh "Git Tutorial for Beginners: Learn Git in 1 Hour" (8JJ101D3knE), freeCodeCamp.org "Git and GitHub for Beginners - Crash Course" (RGOj5yH7evk), "Advanced Git Tutorial - Interactive Rebase, Cherry-Picking, Reflog, Submodules and more" (qsTthZi23VE), "Git for Professionals Tutorial ..." (Uszj_k0DGsg), Fireship "Git Explained in 100 Seconds" (hwP7WQkmECE), "13 Advanced (but useful) Git Techniques and Shortcuts" (ecK3EnyGD8o), "Git It? How to use Git and Github" (HkdAHXoRtos), GitButler "So You Think You Know Git - FOSDEM 2024" (aolI_Rz0ZqY), "So You Think You Know Git Part 2 - DevWorld 2024" (Md44rcw13k4), ByteByteGo "Git MERGE vs REBASE: Everything You Need to Know" (0chZFIZLR_0), "How Git Works: Explained in 4 Minutes" (e9lnsKot_SQ), GitLab "Git Internals - How Git Works - Fear Not The SHA!" (P6jD966jzlk), HackersOnBoard "[Linux.conf.au 2013] - Git For Ages 4 And Up" (1ffBJ4sVUb4), Corey Schafer "Git Tutorial: Using the Stash Command" (KLEDKgMmbBI), "Git Tutorial for Beginners: Command-Line Fundamentals" (HVsySz-h9r4), Kevin Stratvert "Git and GitHub Tutorial for Beginners" (tRZGeaHPoaw).

Voice instructions

The "Speech" tab uses the browser's built-in Web Speech API and does not upload any data. The Chinese (zh-CN) voice package needs to be installed on the system; if not, you can read the lecture notes directly.

Known limitations

  • The original text of the error report shall be based on the common wording of Git 2.4x–2.56; the hint copy will be adjusted according to the version (for example, “not fully merged”, CRLF warning, and advice prompts will indicate the old version of the wording in the entry). returned by the platformremote:Messages (GH001/GH006/GH013, TF401019/TF402455, GitLab push rules) are determined by the platform and may change at any time.
  • All "example outputs" are for illustration, and the hash, time, username, and IP are different from your environment; the reproduction experiment is written according to the official documentation.Not actually implemented in this environment。
  • Details of conservative processing (subject to official documents): file size and push size limits for each platform, licensing requirements for GitHub push protection in private repositorys, default shallow clone depth of GitLab and Azure Pipelines, metadata range that can be migrated by GitHub Enterprise Importer, whether CodeCommit already supports Git LFS, SSH key types supported by Azure DevOps,git refs migratestability, configuration hooks (hook.<name>.command) available versions,core.fsmonitorPlatforms with built-in daemon support.
  • The self-assessment record of the mock interview is only saved in the localStorage of the current browser and will be lost after clearing the site data.