reset --hard HEAD~3,git logOnly old commits remain, the audience exclaims.| # | time | module | core content | Animation·Interaction | experiment |
|---|---|---|---|---|---|
| 0 | before class | Instructions for use and fault experimental environment | Git 2.5x, bootstrap practice repository, local "bare repository remote", security rules | Environmental self-check | Build ~/git-lab8 |
| 1 | 00–08 | A·Commit, retract and history | Issues 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 tree | reflog retrieval · detached HEAD · mistakenly committed for relocation · stash recovery |
| 2 | 08–16 | A · Branching, merging and rebasing | Questions 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 tree | revert -m 1 · rerere · rebase --onto · remerge-diff |
| 3 | 16–24 | A·Remote, authentication and platform | Issues 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 tree | Local pre-receive mock protected branch · GIT_TRACE · Credential sanitization |
| 4 | 24–30 | A · Large repository, performance, CI and security | Issues 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 rewriting | CI checkout fault simulator | Shallow clone describe · newline renormalize · case renaming |
| 5 | 30–37 | B·Basic concepts and internal principles | Interviews 1–13 | mock interview | 2 scene questions |
| 6 | 37–44 | B · Branching, merging and history | Interview 14–25 | mock interview | 2 scene questions |
| 7 | 44–52 | B·Collaboration process and platform | Interview 26–38 | mock interview | 3 scene questions |
| 8 | 52–60 | B · Scale, security and scene design | Interview 39–50 | mock interview | 3 scene questions |
| — | After class | cheat sheet · Comprehensive drill | 50 "error reporting → first command → repair"; 50 shorthand cards; 8 mixed faults; full mock interview | Full mock interview | Final exam 12 questions |
| Topic | m1 | m2 | m3 | m4 | m5 | m6 | m7 | m8 |
|---|---|---|---|---|---|---|---|---|
| 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 | ● | — | ● | ● | — | — | ● | ● |
non-fast-forward、publickey、GH006、index.lock) into the filter box.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."
Question → 30-second short answer → In-depth answer (principles, command examples) → Common follow-up questions → Bonus points → Common wrong answers. Difficulty:ElementaryIntermediateAdvanced。
| courses | Most cited content in this lesson |
|---|---|
| Lesson 1 Core Fundamentals | Object model, three areas, reset/restore/revert, HEAD, remote base, .gitignore |
| Lesson 2 Branching, Merging, and Teamwork | Fast forward and three-way merges, conflicts and rerere, rebase, cherry-pick, stash, tracking branches, PR workflow, tags |
| Lesson 3 Azure Repos and GitHub | SSH / HTTPS / GCM authentication, branch strategy, rule set, CODEOWNERS, platform side troubleshooting |
| Lesson 4 CodeCommit and GitLab | git-remote-codecommit, approval rules, protected branches, push rules, cross-platform mirroring |
| Lesson 5 Git in CI/CD and Automation | hooks/pre-commit, shallow cloning and fetch-depth, signatures, secret scanning, agreed-upon commit, path filtering |
| Lesson 6 Branching Strategy and Repository Architecture | Trunk development/GitFlow, hot fix rollback, monorepo, submodules, LFS, partial cloning, maintenance, migration |
| Lesson 7 In-depth Troubleshooting and History Recovery | GIT_TRACE, reflog, bisect, filter-repo, fsck, newline/case/permissions, network diagnostics |
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.# 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.
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).
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.
reset --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.FAKE_SECRET=lab8-not-a-real-key). Once the real secret is pushed,The first step is always revocation/rotation, rather than changing history.| steps | command | Answered questions |
|---|---|---|
| 1 Read all and report an error | distinguish 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 status | git status · git log --oneline --graph --all -20 | Which branch am I on? Is it merging/rebasing? Is HEAD free? |
| 3 Look at the configuration | git config --show-origin --show-scope -l · git remote -v | Which configuration file takes effect? Is the remote URL SSH or HTTPS? |
| 4 Look at the safety net | git reflog · git stash list · git fsck --lost-found | Are the "lost" things still in the object library? |
| 5 Turn on tracking | GIT_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) |
reset --soft), moving ref + staging area (--mixed), moving ref + staging area + working tree (--hard); and "Add a reverse commit"revert。--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".
$ 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".
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
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
git revert 9c1e2f4Push a reverse commit on the feature branchgit cherry-pick 9c1e2f4Go PR.pre-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; })。See detailsLesson 1 Getting Started with Branching and HEAD and Undoing、Lesson 5 Git hooks。
$ 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).
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
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
git reset --soft / --mixed, only used when you are sure to discard the workspace--hard。git stash -uorgit branch backup/now, the cost is almost zero.git restore file, do not reset the entire repository.gc.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。
$ 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.
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 ← > |/
# 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"
--force-with-lease;The merged history is appended only.git config --global alias.pushf "push --force-with-lease --force-if-includes", put an end to nudity--force。See detailsLesson 2 Rebasing and Remote Branching, interview questionsQ25。
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.
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
# 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.
.envwrite in.gitignore, and commit.env.example。See detailsLesson 5 Confidential Leak Prevention and Scanning、Lesson 7 filter-repo clear secrets。
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.
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>
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
[includeIf "gitdir:~/work/"] path = ~/.gitconfig-work(Starting from 2.56, it can also be judged based on the working tree position).git config --global user.useConfigOnly true: Reject email guessing when not explicitly configured.user.name/email(e.g.github-actions[bot]noreply address).See detailsLesson 1 Environment Preparation and Configuration、Lesson 4 GitLab Push Rules。
$ 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.
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
git branch hotfix/1.0.1 e4f5a6b # Give it a branch name and the problem is solved git switch hotfix/1.0.1
git switchinstead ofgit checkout: Must be written explicitly when checking out a non-branch--detach, will not "accidentally" dissociate.git switch -c hotfix/1.0.1 v1.0.0。See detailsLesson 1 Getting Started with Branching and HEAD、Lesson 7 reflog。
$ 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.
# 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
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
git switch -c wip/x && git commit -am wip)。git stash push -m "description"Naming; used in case of conflictgit stash apply(preserve entries) instead of pop.git worktree add ../myapp-hotfix mainSafer than stashing repeatedly.See detailsLesson 2 cherry-pick, stash and worktree、Lesson 7 fsck and object recovery。
$ 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.
git status --short git diff --stat HEAD feature/login -- app.py # The file is indeed different between the two branches
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)
git config --global rebase.autoStash true、merge.autoStash true。git worktree。.gitignore(See #11).See detailsLesson 1 Three Regions、Lesson 2 stash and worktree。
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).
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
# 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)
git pull)。See detailsLesson 7 Troubleshooting Methodology。
$ 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.
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)
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
-d; first when seeing “not fully merged”git log main..feature/reportConfirm.-dThis error will also be reported (see #19). At this time, you need to confirm the PR status instead of using conditional reflection.-D。See detailsLesson 7 reflog and retrieving lost commits、Lesson 3 Platform Branch Management。
$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).
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
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).
.gitignore(github/gitignore template).core.excludesFile, don't pollute the project's .gitignore.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。
$ 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.
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'.
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
git tag before-rebase, delete after completion.See detailsLesson 2 Rebasing vs. Interactive Rebasing、Lesson 7 reflog。
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.
~/git-lab8/aliceoperation; each experiment can be rerun before startinglab8-bootstrap.shGet a clean environment. All local operations, no platform fees.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
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...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 -3git reset --hard origin/main && rm -rf .git/lost-foundgit 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
git branch hotfix/1.0.1 HEAD@{1}
git log --oneline -2 hotfix/1.0.1git branch -D hotfix/1.0.1echo "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
git branch -D feature/paymentecho "# 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...)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 --statgit restore app.pyNo verified Chinese video specifically talking about "Misoperation Recovery" was found. Below is a 3-minute storyboard that can be recorded by yourself:
reset --hard HEAD~3,git logOnly old commits remain, the audience exclaims.git reflogHighlightHEAD@{1},reset --hard HEAD@{1}One-click recovery; narration: "The commit will not be lost, only the pointer will be lost."git branchNaming.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.
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.
git fetch origin git status -sb # ## main...origin/main [ahead 1, behind 2] git log --oneline --graph --left-right main...origin/main
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.
git config --global pull.rebase true(or the team selects merge) and turns it on at the same timerebase.autoStash。See detailsLesson 1 Remote Repository、Lesson 2 Remote Branching and Tracking Relationships。
$ 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.
git config --show-origin --get-regexp '^pull\.'
git rev-list --left-right --count HEAD...@{u} # Output "1 2": local leading 1, lagging 2
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
pull.rebase / pull.ff。git pull, use git fetch && git reset --hard origin/mainOr deploy the build product directly.See detailsLesson 2 Remote Branching and Tracking Relationships。
$ 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.
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
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.
See detailsLesson 2 Conflict Resolution and Rerere、Lesson 6 Branching Strategies。
$ 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".
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
# 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
git pull --rebase(The fork-point of reflog will be used to identify upstream rewrites).pull.rebase trueMost "merge old copies" situations can be avoided.See detailsLesson 2 Rebase。
$ 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.
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
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.
See detailsLesson 1 revert、Lesson 6 Release Branches and Hotfixes, interview questionsQ20。
$ 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.
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
# 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
See detailsLesson 2 cherry-pick、Lesson 6 Release branches, hotfixes, and cherry-pick rollbacks。
$ 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.
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...
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
git fetch --pruneand clean up[gone]branch.See detailsLesson 2 Pull Request Workflow, interview questionsQ21。
$ 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.
git merge-base HEAD origin/main || echo "No common ancestor" git rev-list --max-parents=0 HEAD origin/main # Two different root commits
# 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)。
git remote -v) - Many times it is pushed to the wrong repository.See detailsLesson 1 Remote Repository、Lesson 6 Split and merge repositorys。
$ 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.
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
# 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
merge.renameLimit, or pass when merging-X find-renames=40%。See detailsLesson 2 Conflict Resolution。
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.
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)
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
--remerge-diffView manual changes.See detailsLesson 2 Conflict Resolution、Lesson 7 bisect positioning regression。
$ 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".
git status --short git config --get rebase.autoStash
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
See detailsLesson 2 Rebasing and stash。
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".
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
# 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
git switch -c feature/search origin/main(fetch first).rebase --onto(#19)。See detailsLesson 2 Rebase and PR workflow。
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.
git diff --name-only --diff-filter=U git check-attr merge -- package-lock.json docs/arch.png
# 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
--ours/--theirsInverse in rebase (ours = upstream being rebased).See detailsLesson 2 Conflict Resolution、Lesson 7 .gitattributes。
Start from the phenomenon you see, and gradually locate the specific problem and repair commands.
~/git-lab8Two clones of alice and bob in the directory; rerun the bootstrap script if necessary.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
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).
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"
git revert --no-edit HEAD && grep -c login app.py # 1: Back
git reset -q --hard origin/maingit 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.
git merge --abort; git reset -q --hard origin/main; git branch -D t1; git config --unset rerere.enabledgit 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.
git switch -q main; git branch -D feature/old feature/search(fetch first)。pull --rebaseThen D' is connected to C.ssh -vT)。Enter the error keyword (such aspublickey、403、GH006、TF402455、413、SSL) filter; click on a row to jump to detailed explanation.
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.
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'
# 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
GITHUB_TOKEN/System.AccessToken)。credential.helper store:Token written in clear text~/.git-credentials。See detailsLesson 3 Authentication: SSH, HTTPS, Git Credential Manager。
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.
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).
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
ed25519-sk)。See detailsLesson 3 Certification、Lesson 7 Network/Protocol Issues。
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).
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}
See detailsLesson 3 GitHub Repository and Permissions。
# 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.
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
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.
See detailsLesson 3 Azure Repos branch policy, GitHub ruleset、Lesson 4 GitLab Protected Branches。
$ 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.
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
# 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
git credential reject。See detailsLesson 3 Git Credential Manager。
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @ 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.
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)
# 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)
StrictHostKeyChecking noBypass (same in CI); official known_hosts are preset in CI.See detailsLesson 3 SSH Authentication、Lesson 7 Network/Protocol Issues。
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.
# 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
# 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
.gitattributesLFS rules declared in (git lfs track "*.bin")。check-added-large-filesHooks are intercepted locally.See detailsLesson 6 LFS、Lesson 7 filter-repo Cleaning Large Files。
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.
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
# 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).
See detailsLesson 7 Performance Diagnostics and Network/Protocol Issues、Lesson 6 Repository Migration。
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.
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
# 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.
See detailsLesson 7 Network/Protocol Issues、Lesson 3 Certification。
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.
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
# 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
no_proxy)。See detailsLesson 7 Network/Protocol Issues。
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.
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
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.See detailsLesson 3: Practical troubleshooting on the platform side。
# 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.
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
# 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).
commit.gpgsign。See detailsLesson 4 GitLab Push Rules、Lesson 5 Signatures and Conventional Commits。
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.
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
# 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.
See detailsLesson 4 CodeCommit: Authentication and git-remote-codecommit。
Step by step investigation according to the four levels; each conclusion can jump to the corresponding question.
remote.gitServer-side hook simulation platform rules); Experiment 3-C requires a GitHub test repository, which will be deleted after completion.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-receivecd 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。
git switch -c fix/direct && git push -u origin fix/direct git switch main && git reset -q --hard origin/main
rm ~/git-lab8/remote.git/hooks/pre-receive; git push origin --delete fix/direct; git branch -D fix/directcat > ~/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-receiveThe 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)
git reset -q --hard main && git push -u origin feature/model
rm ~/git-lab8/remote.git/hooks/pre-receive; git switch main; git branch -D feature/model; git push origin --delete feature/modelssh -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.
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).
rm -f /tmp/lab8_key /tmp/lab8_key.pubNo verified videos found specifically covering protected branch denial, GCM credential cleansing, and enterprise TLS proxy troubleshooting. The breakdown is as follows:
ssh -vTThe output highlights Offering / Server accepts and demonstrates multi-account Host aliases.git credential rejectClear the wrong account and re-push successfully.--depth), partial clone (--filter), whether to pull the tag / LFS / submodule, the user and file ownership in the container..gitattributesdriven filter mechanism (text/eolNewline conversion, LFS clean/smudge), can explain the problem of "wrong file content".Enter keywords (such asdescribe、lfs、submodule、CRLF、dubious、gpg) filter; click on a row to jump to detailed explanation.
$ 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.
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
# 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
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。
$ 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.
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
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"
.git/lfs。COPYLFS's repository is not pulled; before buildinggit lfs pull。See detailsLesson 6 LFS、Lesson 5 Checkout in CI。
$ 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.
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
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.
git clone --recurse-submodules。See detailsLesson 6 Submodules and subtrees。
$ 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.
git rev-parse --is-shallow-repository # true git rev-list --count HEAD # 1 git tag | wc -l; git branch -r
# 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
--filter=blob:none+ Full commit history, than--depth=0Much cheaper.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。
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.
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
# .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
.gitattributes with .editorconfig。See detailsLesson 7 Line Breaks, Case, Permissions, and Encoding Issues。
$ 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.
git config --get core.ignorecase git ls-files | sort -f | uniq -di # Duplicate paths with only uppercase and lowercase differences
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.
git ls-files | sort -f | uniq -diIf there is output, it fails.See detailsLesson 7 Line Breaks, Case, Permissions, and Encoding Issues。
$ 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.
# 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
# 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.
check-added-large-files+ Platform file size limits (#32).See detailsLesson 6 Repository maintenance: gc, maintenance, commit-graph、Lesson 7 filter-repo。
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.
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
# 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
user.email= The platform has verified the email address.See detailsLesson 5 Commit and Tag Signing: GPG, SSH, gitsign。
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.
id -u; stat -c '%u %U' /workspace/myapp /workspace/myapp/.git git config --global --get-all safe.directory
0 1001 runner 1001 runner
# 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
safe.directory=*。See detailsLesson 5 Git in CI/CD、Lesson 7 Permission Issues。
$ 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.
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
# 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
bash scripts/deploy.shcall.See detailsLesson 7 Line Breaks, Case, Permissions, and Encoding Issues。
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.
git config --get core.hooksPath ls -l .git/hooks/pre-commit pre-commit --version 2>/dev/null && cat .pre-commit-config.yaml | head
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
pre-commit install。See detailsLesson 5 Git hooks and pre-commit framework。
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.
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)
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.git rebase --ontoto new history), delete old clones; close/rebuild PRs and forks that reference old commits.# 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.
See detailsLesson 7 Rewriting history: filter-repo clears secrets and large files、Lesson 5 Confidential Leak Prevention and Scanning, interview questionsQ44。
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".
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。
git fetch -q --unshallow --tags git describe --tags
v1.0.0-1-g2b3c4d5
cd .. && rm -rf ci-shallowcd ~/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。
git switch -q main && git branch -D eol-labgit 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
git commit -qm rename; git switch -q main; git branch -D case-labdocker 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
No verified videos specifically talking about LFS pointers, CI shallow cloning, and safe.directory troubleshooting were found. The breakdown is as follows:
No names found, cannot describe anything;Switch tofetch-depth: 0The later version number is correct.cat logo.pngDisplay LFS pointer text,git lfs pullThe next picture appears.git ls-files --eoltable animation,--renormalizeBefore and after comparison.--userSolved; summary CI checkout four things: depth, label, LFS, submodule.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.
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).
"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。
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).
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.
git addCombine them into stage 0.git commit -aWhat did you do? -- Automatically stage changes to tracked files (excluding new files).It is mentioned that index is a binary file, and split index, untracked cache, and fsmonitor can be used to speed up large repositorys.
"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。
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.
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 deduplicationUnchanged files and directoriesReuseOld objects, so "save a full snapshot each time" does not waste space.
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.
"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。
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.
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.
Mentioned storage of refs: loose ref file,packed-refs, and the optional reftable backend starting with Git 2.45 (Q10).
"A branch is a copy of the code" - that's SVN's thinking.
See detailsLesson 1 Getting Started with Branching and HEAD。
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).
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.
gpgsigHead.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).
"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。
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.
| command | branch ref | Staging area | workspace | Typical uses |
|---|---|---|---|---|
reset --soft HEAD~3 | move | Reserve | Reserve | Merge the last 3 local commits into one |
reset HEAD~1 | move | reset | Reserve | Undo the latest local commit and reorganize |
reset --hard origin/main | move | reset | Cover | Discard everything local and align with remote |
restore file / --staged | Not moving | (--staged) | restore | Undo modifications to a file/cancel staging |
revert C | Forward (new commit) | — | — | Undo a pushed commit |
-m 1(Question #17, Q20).Mentioned the introduction of Git 2.23switch/restore Split checkoutresponsibilities; mentionedreset --keep(More secure when there are local modifications).
"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。
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。
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-rebaseThe new version of Git will reject pulls when forked and unconfigured (Issue #14) to avoid accidental merge commits.
branch.<name>.remote/mergedefinition.mentionedfetch.prune, ref filtering of protocol v2 reduces transmission,remote.origin.fetchThe meaning of refspec.
"Fetch is the old way of writing pull."
See detailsLesson 1 Remote Repository、Lesson 2 Remote Branching and Tracking Relationships。
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.
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.
Mentioned multi-pack-index, geometric repack (git repack --geometric=2), changed-path Bloom filter.
"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。
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).
git init --object-format=sha256 demo && git -C demo rev-parse --show-object-format
Put this together with other planned changes for Git 3.0: default reftable, default branch namesmain, and the preparations surrounding these in 2.56.
"Git has fully switched to SHA-256" - No, it is still optional and planned to be the default.
See detailsLesson 1 Release Notes、BreakingChanges。
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.
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.
Feature/x with feature/xMap to the same file path (Issue #44).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).
"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。
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。
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).
.gitJust a backup? - Yes, includes reflog, hooks and local configuration (cloning will not copy these)..gitWhat is it? ——A pointer to the main repositoryworktrees/files in the directory below.mentionedobjects/info/alternates(Shared Object Library) with a partially cloned promisor pack.
"Hooks in .git/hooks are shared with everyone in the repository" - No (Issue #49).
See detailsLesson 1 Object Model、Lesson 7 Repository corruption: fsck。
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.
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}
git fsck --lost-found(Question #2).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)。
"If you can't see the git log, it's gone."
See detailsLesson 7 reflog and retrieving lost commits。
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.
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.
merge.renameLimit/diff.renameLimit。git blame -C -C。Mentioned that the ort merge strategy (default since Git 2.34) greatly optimizes rename detection performance.
“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。
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.
When you are called to his work station, what questions do you ask and what commands do you type?
gc, do not re-clone, do not delete the directory;cp -aBack up the entire repository.git reflogFind the position before reset,git branch rescue HEAD@{1}。git fsck --lost-foundLook at the dangling blobs one by one.reset --keep with stash。No verified videos specifically covering Git interview questions were found. It is recommended to use the "mock interview" of this module to record and play back yourself.
--force-with-leaseway of working.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。
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
| merge | rebase | |
|---|---|---|
| history | Realistic, non-linear | Linear and easy to read |
| conflict | One time solution | Possibly solved on a commit-by-commit basis (#15) |
| rewrite | No | Yes (has been pushed and needs to be pushed) |
| bisect / revert | Merge commit requires -m | Each commit is independent, simpler |
git rebase --abort。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).
"Rebase is always better than merge" or "Never use rebase" - clarify the applicable boundaries.
See detailsLesson 2 Merging and Rebasing。
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.
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
Mentioned "Require linear history" in GitHub ruleset, Azure Repos merge type restrictions.
"Fast-forward merging will lose commits" - No, just no merge commits.
See detailsLesson 2 Merge: Fast Forward and Three-Way Merge。
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.
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.
-X ours with -s oursThe difference? ——The former only favors our side on conflict blocks, while the latter completely ignores the opponent's changes.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).
"Git decides which side to use chronologically".
See detailsLesson 2 Merging and Conflict Resolution。
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.
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
--abort, or when finished useORIG_HEAD/reflog recovery (Issue #12).--force-with-lease(Q25)。mentionedrebase.autoSquash=true、git history(Experimental command, new drop subcommand in 2.56) is a higher-level history editing tool.
"Interactive rebase can be used casually on main".
See detailsLesson 2 Rebase and interactive rebase。
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.
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
--continue, or--abort(Issue #18).git cherry、-xsource line, orgit log --grep。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).
"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。
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).
git revert 1a2b3c4 # Single commit git revert --no-commit A^..C && git commit -m "revert: feature git revert -m 1 <merge> # Merge commit (Q20)
Mention the function switch that allows "undo" not to involve Git; mention the Revert button on the platform PR page.
"Use git reset HEAD~1 then push -f".
See detailsLesson 1 revert。
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.
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).
When it comes to squash merges, rollbacks are simpler (just one normal commit) - this is one of the reasons why some teams choose squash.
"Use-m 2"——That is based on feature and will undo the changes on main.
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.
| Merge | Squash | Rebase | |
|---|---|---|---|
| trunk history | nonlinear | Linear, one PR and one commit | Linear, keep all commits |
| granularity | fine | Coarse (PR grade) | fine |
| rollback | revert -m 1 | revert a commit | revert multiple commits |
| signature | Reserve | Re-signed by the platform | The 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.
It is mentioned that the platform can restrict the allowed merge methods, and cooperate with the rule set "Require linear history".
Just say "squash is the best" without talking about the cost.
See detailsLesson 2 Pull Request Workflow、Lesson 3 Platform Merger Options。
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.
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.
Mentioned that Linux kernel maintainers use rerere heavily for test merges; Mentionedmerge.conflictStyle=zdiff3。
"rerere resolves all conflicts automatically."
See detailsLesson 2 Conflict Resolution and Rerere, problem#15。
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).
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.
git bisect skipOr the script returns 125.--execTesting helps.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。
"Checkout one by one and try back."
See detailsLesson 7 git bisect positioning regression。
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.
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>
Mention the accident firstcp -aBack up the entire repository and set it up temporarilygc.auto=0。
"Clone again" - This will throw away the local reflog and unpushed objects.
See detailsLesson 7 reflog and fsck, issues #2, #6, #7, #10.
--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).
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'
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.
"--force-with-lease is absolutely safe".
See question for details#3、Lesson 2 Remote Branching。
You are the engineer on duty. Tell us about your operational steps, communication and subsequent improvements.
git revert -m 1 <merge>Use emergency PR (use an audited bypass if necessary) and merge after CI passes; do not reset + force push.Describe your targeting approach.
git bisect start --first-parent bad goodFirst locate the PR, then bisect within the PR; about 9 steps.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.
| Trunk/GitHub Flow | GitFlow | |
|---|---|---|
| release cadence | multiple times a day | By version (week/month) |
| long term branch | Only main (may have release/* maintenance branches) | main + develop + release/* + hotfix/* |
| unfinished features | Function switch | Stay in feature branch |
| conflict | Few and small | Many and big |
The DORA study lists "backbone development" as one of the capabilities associated with high delivery performance.
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.
"GitFlow is the industry standard and should be used by all projects."
See detailsLesson 6 Branching Strategies Comparison。
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".
.github/pull_request_template.md, PR template for Azure Repos, MR description template for GitLab.When it comes to automation handing over mechanical checking (formatting, lint, security scanning) to machines, reviewers focus on design and logic.
“The bigger the PR, the better it reflects the workload.”
See detailsLesson 2 Pull Request Workflow and Code Review。
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).
GitPush/MergeBranches*To a specific branch + approval rule template.gh api repos/org/myapp/rulesets --jq '.[] | {name, enforcement}'
Mentioned the promotion method of "Evaluate mode and observe for a week before enforcing it".
"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。
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。
* @org/platform-leads /services/payment/ @org/payments *.tf @org/infra /.github/ @org/devops # Protect CI configuration and CODEOWNERS itself
Mentioned using CI to verify CODEOWNERS coverage (directories without owners).
"The first matching rule takes effect".
See detailsLesson 3 CODEOWNERS, Required Reviews and Status Checks。
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.
merge_groupEvents; configurable batch size and number of concurrent builds.on: pull_request: merge_group: # Let temporary branches in the queue also trigger CI
Combine "trunk development + merge queue + function switch" to tell a story to improve throughput.
"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。
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.
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
pull_requestevent); use with cautionpull_request_target。Mentioned the difference between the Inner Source pattern (Lesson 3) and the template repository (templates do not retain history and upstream relationships).
"Fork is clone".
See detailsLesson 3 Fork, Template Repository and Inner Source。
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).
git config --global credential.helper manager git config --global credential.azreposCredentialType oauth # Azure Repos uses Entra OAuth token (subject to GCM documentation)
credential.helper store? ——Save in clear text.Mentioned SSH certificates (organizations issue short-lived SSH certificates, GitHub Enterprise supports SSH CAs).
“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。
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.).
feat(auth): support SSO login fix(payment)!: change rounding to banker's rounding BREAKING CHANGE: amounts are now rounded half-to-even.
Semantic versioning conventions referring to breaking changes during 0.x releases.
"Commit message format is just a matter of style" - it's input for automation.
See detailsLesson 5 Conventional Commitment, Semantic Versioning, and Automated Publishing。
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).
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
v*Tags, deletion and updates are prohibited.Mention the SLSA provenance of the product to associate the product with the commit/label.
"git push will automatically push tags".
See detailsLesson 2 Commit Specifications, Tags, and Publishing。
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.
Let the data speak: The merge conflict cost and integration risk of long-term branches increase nonlinearly with the branch life.
"Open a feature branch and merge it all at once after two months."
See detailsLesson 6 Branching Strategies, problem#15。
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.
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/*'
git remote set-url, the old repository is set to read-only and retained for a period of time.Clean large files before migration (Issue #45), otherwise the target platform may reject them (Issue #32).
"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。
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.
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)
Mentioned that "fix commits are small and independent" to make rollbacks easier (Issue #18).
"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。
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.
| Ability | GitHub | Azure Repos | GitLab | CodeCommit |
|---|---|---|---|---|
| protection mechanism | Rule Set/Branch Protection | Branch strategy + permissions | protected branch | IAM conditions + approval rules |
| Review by path | CODEOWNERS | Automatically include reviewers | CODEOWNERS (sections) | Approval rules (not by path) |
| CI access control | Required status check | Build validation/status strategies | The pipeline must succeed | Need to integrate CodeBuild, etc. |
| Combinatorial testing | merge queue | — | Merge trains | — |
Function and package restrictions are subject to the official documents of each platform; CodeCommit will be fully available in 2025-11.
Mention "as-code" management of rules (e.g. managing branch protection with Terraform's github/azuredevops/gitlab provider).
Only familiar with one platform but claiming "all are the same".
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.
How to test external contributions without leaking confidentiality?
pull_requestEvents only run tests that do not require confidentiality.pull_request_targetCheck out and execute PR code; isolate permissions, minimize tokens if necessary.Give a migration plan.
No verified video specifically comparing the branch protections of the four platforms was found; please refer to the official documents of each platform.
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.
git diff --name-only $(git merge-base origin/main HEAD)Add dependency graph; note shallow cloning issue #42.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.
"Monorepo puts all the code in one repository, with no additional cost."
See detailsLesson 6 Monorepo vs. Polyrepo trade-off。
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.
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
Emphasize "measure first and then optimize" and provide indicators before and after optimization.
"Use --depth=1 for developers" - developers need history (log, blame, merge-base).
See question for details#39、Lesson 6 Large Repository。
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.
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
git lfs migrate import(Rewriting history).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.
"LFS compresses large files".
See detailsLesson 6 LFS。
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.
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
Can tell gitlink mode 160000, andsubmodule.recurse=true。
"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。
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.
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)
Combined supply chain security: signature label + product provenance (Q49).
"You can prove your identity by setting user.email."
See detailsLesson 5 Commit and Tag Signing: GPG, SSH, gitsign。
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).
Mentioned runbooks, average response time metrics.
"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。
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.
# .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.
mentionedcore.hooksPath, and the "hook definition in configuration" that Git is introducing (hook.<name>.command, the available versions are subject to the githooks documentation).
"With pre-commit hooks there is no need for CI checks".
See detailsLesson 5 Git hooks and pre-commit framework。
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).
- 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 pushMentioned third-party Action fixed to commit SHA (to prevent tag tampering).
"Always fetch-depth: 0 in CI" - large repositorys are a waste of time.
See detailsLesson 5 Checkout in CI。
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.
Structural expression: requirements → constraints → solutions → trade-offs → evolution path.
Just say "use GitFlow" without asking about the requirements.
See detailsLesson 6 Branch Strategy and Repository Architecture in Practice。
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.
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.git filter-repoRemove large files/split subdirectories;git lfs migrate import;git-sizer verification.Emphasize that “migration is a people issue”: training, pilots, support channels.
"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。
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).
.github/workflows、CODEOWNERS、.gitattributes, build scripts - these are the "game-changing files".Measures can be mapped to threats: account stolen → MFA; internal malicious commit → double review; CI exploited → least privilege token.
Just say "Turn on 2FA."
See detailsLesson 5 Signatures and Confidentiality、Lesson 3 Rule Sets。
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.
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)
Talk about timeline and communication (incident channel, status page), as well as improvement items for review output (testing, alarms, function switches).
"Change directly on main and push it."
See detailsLesson 6 Hot Repair、Lesson 7 Bisect。
The repository contains 30 services. How to reduce the CI time of PR to less than 15 minutes?
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).--filter=blob:none+ Sparse checkout only takes affected directories.What controls would you implement at the Git and platform level?
As the team’s Git lead, what support and guardrails will you provide?
.gitconfigFragments (pull.rebase, autoStash, rerere, pushf aliases).No verified videos specifically talking about Git supply chain security or handling confidential leaks were found; please refer to GitHub Docs' "Removing sensitive data from a repository" and OpenSSF information.
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.
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.
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 filegit 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 --abortgit 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
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
Each scenario combines multiple questions from Part A. Write down your first diagnostic command and judgment first, then develop the answer.
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.
$ 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。
$ 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。
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。
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。
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).
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。
$ 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-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.
| Topic | Conclusions used in this lesson | Source (Accessed on 2026-11-15) |
|---|---|---|
| Git 2.56 release notes | git refsAdded create/delete/update/rename; experimentalgit history drop;git replay --linearize;git push origin/mainTips for typographical errors;includeIfSupport working tree location;fetch.followRemoteHEAD | RelNotes/2.56.0 |
| Git 3.0 plan | Default reftable, default branch main, SHA-256, etc. are allin plan | BreakingChanges |
| Cancellation and retrieval | reset mode, reflog expiration time, fsck --lost-found | git-reset · git-reflog · git-gc · git-fsck |
| Merge and rebase | Fast forward rules, pull fork configuration, rerere, revert -m, rebase --onto, remerge-diff, ort | git-push · git-pull · git-rerere · revert-a-faulty-merge · git-rebase |
| Configuration | safe.directory (CVE-2022-24765, 2.35.2), http.postBuffer limitations, core.autocrlf/fileMode/ignorecase, feature.manyFiles | git-config |
| large repository | Partial cloning, sparse checkout cone mode, scalar, maintenance, commit-graph | partial-clone · sparse-checkout · scalar · maintenance |
| gitattributes | text/eol、binary、filter=lfs | gitattributes |
| Git LFS | The latest v3.8.1 (2026-10-22); pointer format, migrate, lock | git-lfs releases · git-lfs.com |
| Git Credential Manager | Latest v3.0.2 (2026-10-26) | GCM releases |
| git filter-repo | Latest v2.47.0; standalone tool (pip/package manager installation) | newren/git-filter-repo |
| actions/checkout | The latest v7.0.1 (2026-07-20); default fetch-depth 1, lfs false, persist-credentials default true | actions/checkout |
| pre-commit / gitleaks | pre-commit-hooks v6.0.0、gitleaks v8.30.1、pre-commit v4.7.0 | pre-commit-hooks · gitleaks |
| GitHub | Password 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 deletion | About rulesets · Push protection · RSA host key update announcement |
| Azure Repos | Branch Strategy, TF402455, TF401019, GCM + Entra Certification | Branch policies · Authentication |
| GitLab | Protected branches, push rules (paid tier), Merge trains, shallow clone default depth | Protected branches · Push rules |
| AWS CodeCommit | 2024-07 Stop accepting new customers; 2025-11 Return to full availability; git-remote-codecommit; macOS keychain cache causes 403 | Troubleshooting · git-remote-codecommit |
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).
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.
remote:Messages (GH001/GH006/GH013, TF401019/TF402455, GitLab push rules) are determined by the platform and may change at any time.git refs migratestability, configuration hooks (hook.<name>.command) available versions,core.fsmonitorPlatforms with built-in daemon support.