Git Hour 5: Git in CI/CD and Automation
- Make it clear"Git is the single source of truth"The meaning in CI/CD: how Git events such as push / PR / tag are mapped to pipeline triggers, and which commit the pipeline gets (merge ref, HEAD SHA, detached HEAD).
- distinguishclient hooks(can be bypassed for quick feedback) withServer side check(rule sets, push protection, required status checks, cannot be bypassed), use
core.hooksPathwith pre-commit frameworkShare hooks across the team. - Know the default depth of checkout on the three major platforms:GitHub Actions
fetch-depth: 1、Azure Pipelines new pipeline shallow get depth 1(from 2022-09 sprint 209, some organizations),GitLab new projectsGIT_DEPTH20; Can explain why shallow cloning makesgit describe、git diff base...headFailure, and use deepening,--filter=blob:none, sparse detection balances speed and accuracy. - Configuration GPG / SSH / gitsignThree signature methods, understand the judgment conditions of the platform's "Verified" mark, and use the rule set to require signature commit.
- use gitleaks / TruffleHogScan secrets locally and in CI, understand platform push protection; follow "Rotate first, then clear history”。
- useConventional commit + commitlintTo standardize commit information, userelease-pleaseorsemantic-releaseAutomatically calculate semantic versions, generate CHANGELOG and publish; use path filtering and
git diff --name-onlyDo monorepo change detection.
1-hour time allocation table
| # | time | module | core content | animation/interaction | experiment |
|---|---|---|---|---|---|
| 0 | before class | Preparation: Sample repository and pipeline environment | Reuse myapp; GitHub repository and Actions; pipx installation pre-commit; gitleaks / TruffleHog; SSH signing key | Environmental self-check list | pre-commit --version、gitleaks version |
| 1 | 00–06 | Git-driven automation panorama | Git event → pipeline; single source of truth; merge ref and head SHA; GitOps | event router | View the PR’s merge ref |
| 2 | 06–14 | Git hooks and pre-commit framework | Client hooks list,core.hooksPath, pre-commit configuration and common hooks, server-side hooks and platform rules | Hooks life cycle timeline | Install pre-commit for myapp |
| 3 | 14–22 | checkout in CI | The default depth of the three platforms, the impact of shallow cloning, deepening, partial cloning, and sparse detection | Core Animation: Shallow clone missing commit → describe/three-point diff failed → succeeded after deepening | Reproduce and fix shallow cloning failure |
| 4 | 22–31 | Commit and Tag Signing | GPG、SSH(gpg.format ssh, allowedSignersFile), gitsign, Verified, require signature | Signature and verification process animation | SSH signing + local verification |
| 5 | 31–39 | Confidential leakage prevention and scanning | gitleaks, TruffleHog, push protection, leak response | Leak response decider | Find out in the practice repositoryFAKE_SECRET |
| 6 | 39–47 | Conventional commit and automatic publishing | Conventional Commits、SemVer、commitlint、release-please、semantic-release | Version number calculator | release-please release myapp |
| 7 | 47–54 | Monorepo path filtering and change detection | git diff --name-only base...head, filtering, required checking and skipping of paths on each platform | Change detection simulator | Build only change services by directory |
| 8 | 54–60 | Summary, self-test and cleanup of the first five hours | Review of Lessons 1–5; Troubleshooting Tree for Common Git Failures in CI; Cleanup | interactive troubleshooting tree | Clean up tokens, keys and test repositories |
| — | After class | cheat sheet · Comprehensive experiment | pre-commit + signed commit + confidential scanning + automatic release of agreed commits (GitHub Actions, with Azure Pipelines / GitLab CI writing method) | Final exam 12 questions | Comprehensive experiment |
Knowledge Coverage Matrix Knowledge Coverage Matrix
| target skill | M1 | M2 | M3 | M4 | M5 | M6 | M7 | M8 | key commands | experiment |
|---|---|---|---|---|---|---|---|---|---|---|
| Git events and pipeline triggering | ✓ | · | ✓ | · | · | ✓ | ✓ | ✓ | git ls-remote origin 'refs/pull/*' | M1 |
| Client hooks and sharing | · | ✓ | · | · | ✓ | ✓ | · | · | git config core.hooksPath .githooks | M2 |
| pre-commit framework | · | ✓ | · | · | ✓ | ✓ | · | ✓ | pre-commit run --all-files | M2 / Comprehensive Experiment |
| Shallow clone, deepen, partial clone, sparse callout | · | · | ✓ | · | · | ✓ | ✓ | ✓ | git fetch --deepen、--unshallow、--filter=blob:none | M3 |
| Commit and Tag Signing | · | · | · | ✓ | · | · | · | ✓ | git commit -S、git verify-commit | M4 / Comprehensive Experiment |
| Confidential scanning and push protection | · | ✓ | ✓ | · | ✓ | · | · | ✓ | gitleaks git、trufflehog git | M5 / Comprehensive Experiment |
| Conventional commit and automatic publishing | · | ✓ | ✓ | · | · | ✓ | · | · | npx commitlint --from | M6 / Comprehensive Experiment |
| Monorepo change detection | ✓ | · | ✓ | · | · | · | ✓ | · | git diff --name-only base...head | M7 |
| Git troubleshooting in CI | · | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | GIT_TRACE=1、git rev-parse --is-shallow-repository | M8 Troubleshooting Tree |
What’s excluded from this lesson (and where to learn it)
| Topic | Why not in this lesson | where to study |
|---|---|---|
| Overall view of pipeline syntax (matrix, cache, environment, OIDC deployment) | This lesson only talks about the "Git-related" part of the pipeline | Follow-up independent GitHub Actions / Azure DevOps / GitLab CI platform course; Docker course Lesson 5 |
| Branch strategy (GitFlow, trunk development, release branch), monorepo and polyrepo trade-offs | Architecture theme | Lesson 6 |
use git filter-repoCompletely clear secrets from history and restore reflog | Deep history rewriting | Lesson 7 (This lesson M5 only talks about response sequence and range) |
| Platform ruleset, branch protection, setup details for CODEOWNERS | Already taught in platform class | Lesson 3、Lesson 4 |
| SAST/DAST, dependency scanning, SBOM, artifact signature (cosign) | Beyond Git itself | Security documents for each platform, Sigstore documents |
How to use this courseware
Principles · Diagrams · Animations · Commands · Experiments · Production Examples · Troubleshooting · Tests · Voice · Videos. The animation of M3 is the core of this lesson: you must click "Deepen" personally.
Score ≥ 70% on the quiz or click "Mark this module complete" to count the progress and save it in this browser (it will be cleared after refreshing when local storage is disabled).
The "Voice" tab uses the built-in Web Speech API (zh-CN) of the browser to read the explanation script; if there is no Chinese voice package, the explanation script can still be read or handed over to the TTS tool.
pull_request_target / workflow_runCheck out the fork PR code; starting from v6persist-credentialsCredentials for writing$RUNNER_TEMPseparate file under.git/config; Use node24 runtime starting from v5.pre-commit 4.7.0(2026-10-13, requires Python ≥ 3.11),pre-commit-hooks v6.0.0。gitleaks 8.30.1(README states that it is "functionally complete" and only security patches will be released in the future. The maintainer will turn to Betterleaks),gitleaks-action v3,TruffleHog 3.99.9,gitsign 0.18.0,release-please-action v5.0.0(upgraded to node24),semantic-release 25.0.9,commitlint 21.2.4,dorny/paths-filter v4.0.3. The version number will continue to change. In production, please use Dependabot/Renovate to update and fix the Action to commit SHA.Module 0 · Preparation: Sample repository and assembly line environment (completed before class)
- CompletedLesson 1(
~/git-lab/myapppractice repository) andLesson 3(GitHub certifications, rulesets, PRs). The GitLab account from Lesson 4 can be used for the GitLab CI comparison writing method in this lesson (optional). - Host: Ubuntu 24.04 (Azure VM or WSL), macOS or Windows (Git for Windows + Git Bash); Git ≥ 2.34 (required for SSH signing), 2.56 recommended.
- GitHub account: Private repositories in the Free package can run GitHub Actions (there is a monthly minute limit, which is subject to the GitHub billing page); this lesson is expected to only take a few minutes.
- Python ≥ 3.11 (required by pre-commit 4.x; Ubuntu 24.04 comes with 3.12) and Node.js 22.14+ or 24.10+ (commitlint 21 requires ≥ 22.12, semantic-release 25 requires ^22.14 or ≥ 24.10, see respective package.json engines).
Fees, permissions and security tips (read first)
| Project | Dosage for this lesson | cost | Description |
|---|---|---|---|
| GitHub private repository + Actions | 1 repository, more than a dozen short jobs | Usually within the free quota | Quota and billing are subject to GitHub Docs “About billing for GitHub Actions” |
| GitHub Secret Protection (push protection) | Demo | Private repositories require paid products; public repositories have free confidential scanning | User-level push protection is on by default, preventing you from sendingpublicRepository push secret |
| gitleaks / TruffleHog / pre-commit | Local vs. CI | Open source and free | gitleaks-action inorganizationA free license key is required in the repository (GITLEAKS_LICENSE), not required for personal accounts |
| Azure DevOps / GitLab.com | Optional: Comparative writing method | Free tier is enough | Just need to be able to create a pipeline |
FAKE_SECRET=..., which is the scan target of the M5 - the repository must be set toPrivate; ② This lesson will create an SSH signing key and a token for release-please (optional). Press M8 to clean up after the experiment is over; ③ Do not put real cloud credentials into the practice repository, even for just one second.Step 1: Install/Check Tools
# Git (Ubuntu uses git-core PPA to get new versions)
sudo add-apt-repository -y ppa:git-core/ppa && sudo apt-get update && sudo apt-get install -y git
git --version
# pre-commit (Ubuntu 24.04 system Python is protected by PEP 668 and installed with pipx)
sudo apt-get install -y pipx && pipx ensurepath
pipx install pre-commit
pre-commit --version
# gitleaks (macOS: brew install gitleaks; Linux: download the tar.gz of the corresponding architecture from GitHub Releases)
GL=8.30.1
curl -sSL "https://github.com/gitleaks/gitleaks/releases/download/v${GL}/gitleaks_${GL}_linux_x64.tar.gz" | tar -xz -C /tmp gitleaks
sudo install /tmp/gitleaks /usr/local/bin/ && gitleaks version
# TruffleHog (macOS: brew install trufflehog; Linux uses the official installation script, install to /usr/local/bin)
curl -sSfL https://raw.githubusercontent.com/trufflesecurity/trufflehog/main/scripts/install.sh | sudo sh -s -- -b /usr/local/bin
trufflehog --version
# GitHub CLI (used to create repositorys and view Actions running)
gh --version && gh auth status
git version 2.56.0 pre-commit 4.7.0 8.30.1 trufflehog 3.99.9 gh version 2.x.x (…) github.com ✓ Logged in to github.com account alice (keyring)
Version numbers are examples. Before downloading the binary, it is recommended to check the checksum provided on the Release page (checksums.txt). The "curl | sh" installation script is convenient but the source must be trusted; it is recommended to use fixed version binaries or container images for production build machines (zricethezav/gitleaks、trufflesecurity/trufflehog)。
Step 2: Push myapp to a new private GitHub repository
cd ~/git-lab/myapp git status -sb && git log --oneline --graph --all | head -12 && git tag # If origin already exists in Lesson 3, skip creation gh repo create myapp-ci --private --source . --remote ci --push git push ci --tags git remote -v
✓ Created repository alice/myapp-ci on GitHub ✓ Added remote https://github.com/alice/myapp-ci.git ✓ Pushed commits to https://github.com/alice/myapp-ci.git ci https://github.com/alice/myapp-ci.git (fetch) ci https://github.com/alice/myapp-ci.git (push) origin https://github.com/alice/myapp.git (fetch) origin https://github.com/alice/myapp.git (push)
In order not to affect the repository of Lesson 3, this lesson is built separatelymyapp-ci, the remote name isci. When the repository is deleted, please go back toLesson 1 Module 0Rerunbootstrap-git-lab.sh。
Step 3: Prepare a minimal CI workflow (subsequent modules will gradually expand)
mkdir -p .github/workflows
cat > .github/workflows/ci.yml <<'EOF'
name: ci
on:
push:
branches: [main]
pull_request:
permissions:
contents: read
jobs:
info:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- name: Show what CI checked out
run: |
echo "event=$GITHUB_EVENT_NAME ref=$GITHUB_REF sha=$GITHUB_SHA"
git rev-parse --is-shallow-repository
git log --oneline -3 || true
git describe --tags || echo "describe failed (expected on shallow clone)"
EOF
git switch -c ci/bootstrap
git add .github/workflows/ci.yml && git commit -m "ci: add minimal workflow"
git push -u ci ci/bootstrap
gh pr create --repo alice/myapp-ci --fill --base main
event=pull_request ref=refs/pull/1/merge sha=5c1e0f7… true 5c1e0f7 Merge 9a3b2c1 into 2f8d4e6 fatal: No names found, cannot describe anything. describe failed (expected on shallow clone)
refs/pull/1/mergeFailure with describe is the phenomenon that M1 and M3 want to explain.Step 4: Prepare SSH signing key (for M4 use)
ssh-keygen -t ed25519 -C "alice@example.com git signing" -f ~/.ssh/id_ed25519_signing -N "" gh ssh-key add ~/.ssh/id_ed25519_signing.pub --type signing --title "git-lab signing" gh ssh-key list
--type signingRegister the public key asSigning key(Registered separately from the authentication key; the same key can also be registered for both uses). NoghSelect "Signing Key" in GitHub → Settings → SSH and GPG keys → New SSH key → Key type.
Warm-up: Answer from memory (30 seconds)
How is the repository on the CI runner different from your local repository?
It is created per job (managed runner), usuallyShallow clone, often indetached HEAD(Checking out a specific SHA instead of a branch), only the ref needed this time, without your global Git configuration (user.name, signing key, credential assistant), the permissions of the token are determined by the pipeline configuration. These points will be used again and again with the M3 and M8.
Can the pre-commit hook ensure that there are no secrets in the repository?
No. Client hooks can be usedgit commit --no-verifySkip it, or it may not be installed at all. It's "fast feedback"; "guarantee" is server-side: CI scans as required checks, platform push protection, rulesets. M2 and M5 will explain this layering clearly.
Module 1 · Git-driven automation panorama
- List the Git events that trigger the pipeline (push branch, push tag, PR/MR creation and update, merge, delete branch) and how they are written on the three major platforms.
- Explain clearly what the PR pipeline detectsmerge ref(
refs/pull/N/merge)instead of your branch HEAD, and the impact this has on version calculations and change detection. - Explaining "Git as a single source of truth": Code, pipeline definitions, infrastructure, version numbers, release notes are all derived from Git (GitOps).
What: Git event-driven automation
Hosting platform in everygit pushBegit-receive-packAfter accepting, you will get a set ofcitation update:old SHA → new SHA refs/heads/main. The platform wraps it as an event (GitHub'spush, Azure DevOps' "Code pushed", GitLab's push hook), and then decide whether to run it and which commit to run based on the pipeline definition in the repository. PR/MR is the platform's own object, and the platform will maintain a special reference for it:
| Platform | PR reference to source branch HEAD | A reference to the results of "Trial Merge" | Which PR pipeline builds by default |
|---|---|---|---|
| GitHub | refs/pull/N/head | refs/pull/N/merge(Only available when PR can be merged) | pull_requestEvent:merge ref,GITHUB_SHAIt is a trial merge commit |
| Azure Repos | refs/heads/< source branch > | refs/pull/ID/merge | PR build verification:merge ref(Build.SourceBranch=refs/pull/ID/merge) |
| GitLab | refs/merge-requests/IID/head | refs/merge-requests/IID/merge | By default, the MR pipeline runs onSource branch HEAD; Only run the "Merge Result Pipeline" (Premium) to test the merged results. |
Why: Why is Git a single source of truth?
- traceable: Any build product can answer "which SHA it comes from", and the image label, version number, and SBOM are all written into this SHA.
- replayable: Pipeline definition (
.github/workflows/*.yml、azure-pipelines.yml、.gitlab-ci.yml) itself is also in the repository, reviewed and rolled back together with the code. - auditable: Who pushed what to which ref when, all in the platform audit log + Git history; signature (M4) makes "who" verifiable.
- GitOps: Desired state (Kubernetes manifest, Terraform code) in Git, controller (Argo CD, Flux) or pipeline converges actual state to state in Git; rollback =
git revert。
How: Comparison of trigger writing methods for the three major platforms
| event | GitHub Actions | Azure Pipelines | GitLab CI |
|---|---|---|---|
| push to main | on: push: branches: [main] | trigger: branches: include: [main] | rules: - if: $CI_COMMIT_BRANCH == "main" |
| PR / MR | on: pull_request | GitHub repository:pr:;Azure Repos: in branch policyBuild verification(YAMLpr:Not valid for Azure Repos) | if: $CI_PIPELINE_SOURCE == "merge_request_event" |
| push tag | on: push: tags: ['v*'] | trigger: tags: include: ['v*'] | if: $CI_COMMIT_TAG |
| Filter by path | paths: / paths-ignore: | trigger: paths: include/exclude | rules: changes:(M7) |
| Commit SHA variable | GITHUB_SHA、github.event.pull_request.head.sha | Build.SourceVersion、System.PullRequest.SourceCommitId | CI_COMMIT_SHA、CI_MERGE_REQUEST_DIFF_BASE_SHA |
When: Which automation should be hung on which event
| Automation | event | Reason |
|---|---|---|
| Formatting, lint, unit testing, secret scanning | pre-commit (local) + PR | The earlier the cheaper; results on PR as required check |
| Integration testing, image building | PR(merge ref)+ push main | Verify "what the merge will look like" |
| Release PR / version number calculation | push main | Only generate versions on trunk (M6) |
| Release products and deploy production | push tag / GitHub Release | Tags are immutable version anchors (move/deletion is prohibited in conjunction with the tag rule set) |
| Regular full scan | schedule | Discover old secrets that new rules recognize |
git log -1You will see a "Merge X into Y" commit, which does not exist in your branch. ② "UseGITHUB_TOKENPushed commits/created PRs will trigger the workflow again" - No; to prevent recursion,GITHUB_TOKENTriggered event (workflow_dispatch、repository_dispatchExcept) will not create a new workflow run, which is why the release PR of release-please does not run CI by default (M6). ③ "Tag is the version" - lightweight tags can be moved, production needs to use annotation/signature tags and protect them with rule setsrefs/tags/v*。Architecture diagram: from git push to pipeline
Three commits of the PR
B...E(Three points: starting from merge-base), the version number calculation needs to use the label before CInteraction: Git Event Router
Select a Git operation and see what ref updates the platform generates, which pipelines are triggered, and what the runner checks out.
Core command: see clearly the references for platform maintenance
| command | function | Description |
|---|---|---|
git ls-remote origin 'refs/pull/*' | List head/merge references of GitHub PR | Azure Repos are the samerefs/pull/*;GitLab isrefs/merge-requests/* |
git fetch origin pull/1/merge:pr-1-merge | Get the trial merge results to the local branch | Reproduce the code seen by CI locally |
git log -1 --format='%H %P %s' | Show commits with parent commits | The two parent commit instructions in CI are merge ref |
gh run list / gh run view --log | View workflow runs and logs | Corresponding to Azureaz pipelines runs list, GitLab’sglab ci list |
gh pr checks | Check the status of a PR | Which are required checks are configured in the ruleset |
cd ~/git-lab/myapp git ls-remote ci 'refs/pull/*' git fetch ci pull/1/merge:pr-1-merge git log -1 --format='%H%n parents: %P%n %s' pr-1-merge gh run list --repo alice/myapp-ci --limit 3
9a3b2c1d… refs/pull/1/head 5c1e0f7a… refs/pull/1/merge 5c1e0f7a… parents: 2f8d4e6… 9a3b2c1… Merge 9a3b2c1… into 2f8d4e6… STATUS TITLE WORKFLOW BRANCH EVENT ID ✓ ci: add minimal workflow ci ci/bootstrap pull_request 1234567890
How to verify:The first parent commit of the merge commit is main's current commit (base), and the second is the PR's head.Common mistakes:GitHub does not generate PR when there is a conflictrefs/pull/N/merge,pull_requestThe workflow will not run.Production use:The problem of "failed only on CI" is reproduced locally.
Experiment 1: Observing three events (~4 minutes)
ref=refs/pull/1/merge, andgit logThe first line is "Merge ... into ...".gh pr merge 1 --repo alice/myapp-ci --squash --delete-branch gh run list --repo alice/myapp-ci --limit 2
git switch main && git pull ci main sed -i 's/ branches: \[main\]/ branches: [main]\n tags: ["v*"]/' .github/workflows/ci.yml git commit -am "ci: also run on version tags" && git push ci main git tag -a v0.9.0 -m "v0.9.0" && git push ci v0.9.0 gh run list --repo alice/myapp-ci --limit 3
STATUS TITLE WORKFLOW BRANCH EVENT ID ✓ v0.9.0 ci v0.9.0 push 1234567893 ✓ ci: also run on version tags ci main push 1234567892
BSD sed on macOS is not supported\nReplacement can be modified directly using the editor. If the ruleset protects main (lesson 3), please PR instead of pushing directly.
Case 1: PR is all green, but main is down after the merger
Question:The two PRs each passed based on the old main test, but the conflicting semantics (a renamed function, a new call) after merging caused the main build to fail.Reason:The PR's merge ref was tested on "then main"; the second PR was not retested after the first merge.Method:Turn on "Require branches to be up to date before merging" in the ruleset, or use the GitHub Merge Queue / GitLab Merge Train to have each PR tested against the true merge order (Lesson 3).
Case 2: Posting a PR "waiting for status check" forever
Question:release-please is usedGITHUB_TOKENCreate a release PR, as required by the rulesetciThe check never shows up.Reason:GITHUB_TOKENThe resulting event does not trigger a new workflow run.Method:Use GitHub App tokens or fine-grained PAT (release-please-action'stokeninput), or let CI also listenworkflow_dispatchand trigger manually.
Case 3: GitOps rollback only requires one revert
Question:The error rate increases after the new version is launched.Method:in environment repositorygit revertCommits and merges that update the mirror tag, Argo CD converges the cluster to the old version during the synchronization cycle; the audit record is the Git history.Limitations:Irreversible changes such as database migration cannot be rolled back by revert and need to be designed separately.
Common errors and solutions
PR is opened, but pull_request workflow is not running at all
Reason:① There is a PR conflict and there is no merge ref; ② The workflow file is only on the PR branch, andpaths/branchesFilter mismatch; ③ PR comes from fork and requires maintainer approval to run; ④ PR isGITHUB_TOKENCreated.Diagnosis:git ls-remote origin 'refs/pull/N/*'Check if there is a merge ref; check the approval policy of fork PR in the repository Settings → Actions.
Azure Repos: PR is written in YAML: but PR does not trigger the build
Reason:YAMLprTriggers are only valid for GitHub / Bitbucket Cloud repositories; PR builds for Azure Repos must beBranching Strategy → Build VerificationMedium Configuration (Lesson 3).
GitLab: Two pipelines (branch pipeline + MR pipeline) appear in the same push
Reason:The job rule matches both push andmerge_request_event。Fix:use workflow: rulesOnly run the MR pipeline when there is an open MR:
workflow:
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
- if: $CI_COMMIT_BRANCH && $CI_OPEN_MERGE_REQUESTS
when: never
- if: $CI_COMMIT_BRANCH
- if: $CI_COMMIT_TAG1. Get the trial merge result of GitHub PR #7 to the local branch pr7 and display its two parent commits.
git fetch origin pull/7/merge:pr7 && git log -1 --format=%P pr7
2. Print the real HEAD SHA of the PR source branch (not the trial merge commit) in GitHub Actions.
- run: echo "head=${{ github.event.pull_request.head.sha }} base=${{ github.event.pull_request.base.sha }}"The team wants to "calculate a pre-release version number based on the commit for each PR and write it into the image tag." Used in PR pipelinegit rev-parse HEADWhat's wrong with being a mirror tag?
The HEAD of the PR pipeline is a trial merge commit generated by the platform. It is not on any branch. It will change every time it is re-run after main advances, and the developer's commit cannot be traced from the image. should be usedgithub.event.pull_request.head.sha(Azure:System.PullRequest.SourceCommitId;GitLab:CI_COMMIT_SHA, which is the source branch HEAD in the MR pipeline). At the same time, the calculation of the version number relies on tags and history, which requires the full depth of M3.
Verified instructional videos
Official documentation
- GitHub:Events that trigger workflows
- Azure Pipelines:Triggers
- GitLab:Merge request pipelines
- OpenGitOps principles
Video storyboard (approximately 60 seconds)
Screen: The terminal executes git push, the platform icon lights up, and a line "old→new refs/heads/main" pops up.
Narrator: To the platform, a push is a set of reference updates.
Screen: A, B, C and feature branches appear on the commit graph, and the platform generates a dotted M commit.
Narrator: When you open a PR, the platform creates a trial merge commit, which is what the PR pipeline tests.
Screen: Three-layer access control: local hooks, platform rules, and pipelines must be checked.
Narrator: Local hooks give you fast feedback, and the platform and pipeline give you real guarantees.
Module 2 · Git hooks and pre-commit framework
- Tell us the triggering timing, parameters and "non-zero exit or abort" rules of commonly used client hooks (pre-commit, prepare-commit-msg, commit-msg, post-commit, pre-push, post-checkout, post-merge, post-rewrite).
- use
core.hooksPath, configured hooks for Git 2.54+ or the pre-commit framework to share hooks within the team and understand why they don't "auto-install". - write for myapp
.pre-commit-config.yaml(pre-commit-hooks v6.0.0, ruff, gitleaks, conventional commit checks), and used in CIpre-commit run --all-filesGet the bottom of it. - Distinguish between server-side hooks (pre-receive/update/post-receive) and SaaS platform rule sets, push rules, and push protection.
.gitDirectory structure.Importance:★★★★★What: What is the hook?
A hook is an executable file that Git executes at a specific moment in an operation. The default location is$GIT_DIR/hooks/(git initwill be put into a group*.sampleFor example, remove the suffix and add execution permission to enable it). Yespre-*class hook,If the exit code is non-0, the current operation will be aborted.;post-*Class hooks only provide notifications and cannot undo completed operations.
Client hooks (the most commonly used ones)
| hook | Trigger time | parameters/inputs | Can it be suspended? | Typical uses | Can be skipped |
|---|---|---|---|---|---|
pre-commit | git commitWrite before commit (no commit information yet) | None; check staging area | Yes | Formatting, lint, confidential scanning, large files | --no-verify / -n |
pre-merge-commit | git mergeAutomatically generate merge pre-commits | None | Yes | Same checks as pre-commit | --no-verify |
prepare-commit-msg | Before the editor opens | Message file path, source (message/template/merge/squash/commit), SHA | Yes | Automatically insert the ticket number in the branch name | Not subject to--no-verify influence |
commit-msg | After entering the commit information | Message file path | Yes | Agreed commit verification, DCOSigned-off-by | --no-verify |
post-commit | After commit is completed | None | No | Notification | — |
pre-push | git pushAfter communicating with the remote server and before transferring the object | Remote name, URL; stdin:local ref local SHA remote ref remote SHA | Yes | Run tests, disable pushing main | --no-verify |
post-checkout / post-merge | After switching branches/merging (including pull) | Old HEAD, new HEAD, whether to switch branches | No | Prompt to reinstall when dependencies change | — |
post-rewrite | commit --amend、rebaseAfter rewriting | stdin: old SHA new SHA | No | Sync notes | — |
reference-transaction | Any reference to the updated prepared / committed / aborted stage | Stage; stdin reference changes | The prepared stage can | Audit, copy | — |
Server-side hooks (only available on your own hosted Git server)
| hook | timing | function |
|---|---|---|
pre-receive | After receiving all objects and before updating any references (once per push) | stdin for allold new ref;Exit non-0 → the entire push is rejected |
update | Before each reference update (once per ref) | parametersref old new;Reject only the ref |
post-receive | All citations updated | Notify CI, send email; cannot refuse |
proc-receive | Handle special references (such asrefs/for/*) | Gerrit style code review workflow |
GitHub.com, Azure DevOps Services, GitLab.com and other SaaSUploading custom server-side hooks is not allowed, they provide equivalent hosting capabilities: GitHub rule set (commit information regularity, file path/size, signature requirements) and push protection; GitLab push rules (Premium) and confidential push protection (Ultimate); Azure Repos branch policy and confidential scanning (GitHub Advanced Security for Azure DevOps). Self-hosted versions (pre-receive hooks for GitHub Enterprise Server, server hooks for GitLab Self-Managed) can run custom scripts.
Why: Why the hook cannot be "automatically effective after commit to the repository"
.git/hooksNot under version control,git clonealsoNoInstall any hooks - This is an intentional security design: if cloning a repository automatically executes scripts in the repository, then cloning an unfamiliar repository is equivalent to running unfamiliar code. Therefore, all "shared hook" solutions require each developer to explicitly execute the installation command once, andcan always be bypassed。
How: Three ways to share
| way | practice | Advantages | Disadvantages |
|---|---|---|---|
core.hooksPath(Git 2.9+) | Put in repository.githooks/, each person executesgit config core.hooksPath .githooks | Zero dependencies, scripts can be reviewed | You have to write your own cross-platform script; it will make.git/hooks Invalid |
| Configuration hooks (Git 2.54+) | git config set hook.lint.command ... + hook.lint.event pre-commit; The same event can be configured with multiple configurations and can be placed in the system/global configuration for centralized distribution; it can be run in parallel starting from 2.55 | Can be combined with multiple hooks and centrally configured by MDM/mirror | Requires newer Git; team Git versions may not be relied upon for a while |
| pre-commit framework | Inside the repository.pre-commit-config.yaml, each person executespre-commit install | Multi-language, automatic creation of isolation environment, fixed version, rich ecosystem, CI can reuse the same configuration | Requires Python ≥ 3.11; download the environment for first run |
Key points of pre-commit framework
- Each hook comes from a Git repository
rev(tag or SHA), framed in~/.cache/pre-commitSet up an isolated environment (Python venv, node, golang, docker, etc.) for it so it doesn't pollute project dependencies. - The default is only forTemporary filesRun, and stash the unstaged changes temporarily to ensure that what is being checked is the content to be committed; repair class hooks (such as
end-of-file-fixer) The hook fails after modifying the file, you need to re-git add。 stagesDecide which hook type to run on:pre-commit、pre-push、commit-msg、prepare-commit-msg、post-checkout、manualWait (old namecommit/pushDeprecated).default_install_hook_typesgive it oncepre-commit installInstall multiple types at the same time.pre-commit autoupdateput allrevUpdate to latest tag (add--freezefixed as SHA);SKIP=hook-id git commitTemporarily skip a hook.- Run in CI
pre-commit run --all-files --show-diff-on-failure, useThe same configurationThose at the bottom of the pocket are not equipped with hooks or--no-verifycommit.
trailing-whitespace、end-of-file-fixer、check-yaml、check-added-large-files、check-merge-conflict、detect-private-key、no-commit-to-branch;ruff-pre-commit v0.17.5ruff-check with ruff-format; gitleaks v8.30.1gitleaks(Actual executiongitleaks git --pre-commit --redact --staged --verbose);conventional-pre-commit v4.5.0(commit-msgstage).When: Which checks are placed in the hook
| Put in pre-commit | Put in pre-push | Only put in CI |
|---|---|---|
| Seconds, only view temporary files: formatting, lint, confidential scanning, YAML syntax, large files | Ten seconds to one minute: unit testing, type checking | Minute level: integration testing, image building, full history secret scanning, dependency vulnerability scanning |
--no-verifyOne-click bypass, web interface editor and GitHub recommended modifications do not go through local hooks; CI and platform rules must be in place to cover this. ② "It doesn't matter if the hook is too slow" - Hooks that take more than a few seconds will make developers develop--no-verifyhabits, but reduce safety. ③ "Commit the hook script to .git/hooks" - that directory will not be committed at all.The position of the hook in commit and push
How the pre-commit framework works
~/.cache/pre-commitCan be significantly acceleratedAnimation: one commit + push through the hook
Play step by step after selecting a scene. Check--no-verifySee which checks are skipped and which are still in effect.
Core commands
| command | function | Description |
|---|---|---|
ls .git/hooks | View example hook | *.samplewill not be executed |
git config core.hooksPath .githooks | Use the hook directory in the repository | after .git/hooksNo longer in effect |
git hook run pre-commit | Manually run a hook (2.36+) | debug hook |
git hook list pre-commit | List hooks that will be run for an event (configuration hooks) | Newer Git, seegit help hook |
pre-commit install --install-hooks | Install hooks and pre-build the environment | cooperatedefault_install_hook_types |
pre-commit run --all-files | Run on all files | When first introduced, in CI |
pre-commit run gitleaks --files app.py | Only run one hook | Debugging |
pre-commit autoupdate [--freeze] | update rev | --freezePin to SHA |
SKIP=ruff-check git commit ... | skip specified hook | Than--no-verifymore precise |
pre-commit uninstall / pre-commit clean | Uninstall hook/clear cache | Troubleshooting |
myapp's .pre-commit-config.yaml
# .pre-commit-config.yaml
default_install_hook_types: [pre-commit, commit-msg]
default_stages: [pre-commit]
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v6.0.0
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
- id: check-yaml
- id: check-added-large-files
args: ["--maxkb=500"]
- id: check-merge-conflict
- id: detect-private-key
- id: no-commit-to-branch
args: ["--branch", "main"]
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.17.5
hooks:
- id: ruff-check
args: ["--fix"]
- id: ruff-format
- repo: https://github.com/gitleaks/gitleaks
rev: v8.30.1
hooks:
- id: gitleaks
- repo: https://github.com/compilerla/conventional-pre-commit
rev: v4.5.0
hooks:
- id: conventional-pre-commit
stages: [commit-msg]
args: []
Not dependent on framework: core.hooksPath version
mkdir -p .githooks
cat > .githooks/commit-msg <<'EOF'
#!/bin/sh
# Minimum verification for conventional commit: type(scope)!: subject
pattern='^(feat|fix|docs|style|refactor|perf|test|build|ci|chore|revert)(\([a-z0-9._-]+\))?!?: .{1,72}$'
head -1 "$1" | grep -Eq "$pattern" && exit 0
echo "commit-msg: The commit information does not comply with the conventional commit, for example: feat(api): add /version endpoint" >&2
exit 1
EOF
chmod +x .githooks/commit-msg
git config core.hooksPath .githooks
Git 2.54+: Configurable hooks
git config set hook.secrets.command "gitleaks git --pre-commit --staged --redact" git config set --append hook.secrets.event pre-commit git hook list pre-commit
How to verify:pre-commit run --all-filesAll Passed.Common mistakes:setcore.hooksPathAfter executionpre-commit installWill report "Cowardly refusing to install hooks with `core.hooksPath` set.", you need to firstgit config --unset core.hooksPath。Production use:The same configuration is used for local and CI.
Lab 2: Install pre-commit for myapp (~6 minutes)
.pre-commit-config.yamlSave to the root directory of the repository.cd ~/git-lab/myapp && git switch main && git pull ci main git switch -c chore/pre-commit # After pasting the configuration into .pre-commit-config.yaml: pre-commit install --install-hooks ls -l .git/hooks/pre-commit .git/hooks/commit-msg
pre-commit installed at .git/hooks/pre-commit pre-commit installed at .git/hooks/commit-msg -rwxr-xr-x 1 alice alice 615 Nov 15 10:02 .git/hooks/commit-msg -rwxr-xr-x 1 alice alice 615 Nov 15 10:02 .git/hooks/pre-commit
pre-commit run --all-files
trim trailing whitespace.................................................Failed - hook id: trailing-whitespace - exit code: 1 - files were modified by this hook Fixing app.py fix end of files.........................................................Passed check yaml...............................................................Passed check for added large files..............................................Passed check for merge conflicts................................................Passed detect private key.......................................................Passed don't commit to branch...................................................Passed ruff check...............................................................Passed ruff format..............................................................Failed - hook id: ruff-format - files were modified by this hook 1 file reformatted, 2 files left unchanged Detect hardcoded secrets.................................................Passed
If the repair class hook changes the file, it will be Failed - if you run it again, everything will be Passed. gitleaks hook watch onlyStaging area, so no historical records will be found here.FAKE_SECRET(That's a full history scan of the M5).
git add -A git commit -m "update stuff" git commit -m "chore: add pre-commit configuration"
Conventional Commit......................................................Failed - hook id: conventional-pre-commit - exit code: 1 [Bad commit message] >> update stuff Your commit message does not follow Conventional Commits formatting … [chore/pre-commit 7d1c2b0] chore: add pre-commit configuration
# Use splicing to generate sample values: to prevent the courseware file itself from containing a complete "key" and being intercepted by push protection printf 'AWS_ACCESS_KEY_ID=%s%s\nAWS_SECRET_ACCESS_KEY=%s%s\n' AKIA QYLPMN5HHFPZAM2 Gm8a4bS3uQ7Xb1Kc9L0d VfTq2Wz5Rr6YyHn3EpJk > leak.env git add leak.env && git commit -m "feat: add config" git restore --staged leak.env && rm leak.env
Detect hardcoded secrets.................................................Failed - hook id: gitleaks - exit code: 1 Finding: AWS_ACCESS_KEY_ID=REDACTED RuleID: aws-access-token File: leak.env … WRN leaks found: 2
The example value is a random character, and whether the rule is hit or not depends on the gitleaks rule version; whether it is hit or not does not affect subsequent steps.
.github/workflows/ci.ymlAdded jobs (fixed Action major version, fixed SHA in production). pre-commit:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7
with:
python-version: "3.13"
- uses: actions/cache@v6
with:
path: ~/.cache/pre-commit
key: pre-commit-${{ runner.os }}-${{ hashFiles('.pre-commit-config.yaml') }}
- run: pipx install pre-commit
- run: pre-commit run --all-files --show-diff-on-failure
git add .github/workflows/ci.yml && git commit -m "ci: run pre-commit on all files" git push -u ci chore/pre-commit && gh pr create --repo alice/myapp-ci --fill
actions/cacheCurrently v6 (verified 2026-11). Hooks in the commit-msg phase will not be--all-filesRun; the commit information in the PR is checked by M6's commitlint job.
Case 1: The hook is too slow, all members --no-verify
Question:A team put the complete test suite (4 minutes) into pre-commit, and after two weeks almost all commits had--no-verify。Method:pre-commit only retains second-level checks; tests are moved to pre-push (optional) with CI; CI'spre-commitThe job is set as a required check for the rule set.Result:Local feedback < 3 seconds, the bypass rate dropped significantly.
Case 2: pre-commit takes 2 minutes each time to rebuild the environment in CI
Method:to.pre-commit-config.yamlhash for key cache~/.cache/pre-commit; Or use the hosting service pre-commit.ci (free for open source, paid for private, based on its website). Notepre-commit/actionIt has entered the maintenance-only state. It is more transparent to write two lines of run by yourself.
Case 3: Self-hosted GitLab uses server hook to force the work order number
Question:Compliance requires each commit to be associated with a work order.Method:GitLab Self-Managed configures global settings on Gitaly nodespre-receiveThe server-side hook verifies the commit information; after migrating to GitLab.com, Premium's push rule "Commit Information Regular" is used.Inspiration:Custom server-side hooks are not migrated with SaaS and must be inventoried before migration.
Common errors and solutions
[ERROR] Cowardly refusing to install hooks with `core.hooksPath` set.
Reason:The repository or global configuration is setcore.hooksPath(It may be issued uniformly by the company).Diagnosis:git config --show-origin --get-all core.hooksPath。Fix:Cancel the configuration; or call it in the company's unified hook directorypre-commit hook-impl; Or use Git 2.54+ configuration hooks to allow multiple sources to coexist.
hint: The '.git/hooks/pre-commit' hook was ignored because it's not set as executable.
Reason:The script does not have execution permissions (common in files copied or extracted from Windows).Fix:chmod +x .githooks/*;Record the executable bit in the repository:git update-index --chmod=+x .githooks/commit-msg. Also note that on Windows, CRLF makes the shebang become/bin/sh\r, use .gitattributesSet*.sh text eol=lf。
An unexpected error has occurred: CalledProcessError … git clone … (pre-commit cannot download the hook repository)
Reason:network/agent,revDoes not exist, the company prohibits access to GitHub.Fix:Check rev;Configurationhttps_proxy;The intranet can mirror the hook repository and change itrepo:address, or userepo: localCall locally installed tools.
The hook passes locally, but pre-commit fails in CI: files were modified by this hook
Reason:The developer did not install the hook, or the local tool version and configurationrevInconsistent.Fix:local executionpre-commit run --all-filesCommit the fix later; do not use the system-installed ruff locally and CI use the version in the configuration.
1. Only run the gitleaks hook on the currently staged file without committing it.
pre-commit run gitleaks
Not added--all-filesBy default, it works on temporary files.
2. Update the rev of all hooks to the latest and fix them to commit SHA.
pre-commit autoupdate --freeze
The security team requests that "no one can commit .env files to any repository." Is it enough to just use pre-commit? How should it be designed?
No, client hooks can be--no-verify, Web editing, uninstalled hooks, etc. to bypass. Layered design: ① for pre-commitgitleakswith customizationfiles: '\.env$'Interception and quick feedback; ② Run the same configuration and full scan in CI, and set it as required inspection; ③ Platform side: GitHub rule set's "restricted file path" (push rules, subject to the current package), GitLab push rule "forbidden file name", push protection; ④.gitignoreIgnore in template.env。
Verified instructional videos
Official documentation
Video storyboard (approximately 60 seconds)
Screen:
git commitA line of commands is expanded into four grids: pre-commit, prepare-commit-msg, commit-msg, and post-commit.Narrator: A commit will call these hooks in sequence. If any pre hook returns non-zero, the commit will be cancelled.
Screen: The repo and rev in .pre-commit-config.yaml fly into the cache directory and become an isolated environment.
Narrator: The pre-commit framework writes the hook version in the repository, and everyone and CI use the same version.
Screen: When the developer enters --no-verify, the local hook is grayed out; after being pushed to the platform, it is blocked by CI required checks.
Narrator: Native hooks can be bypassed, so always have CI and platform rules in place.
Module 3 · Checkout in CI: shallow cloning, fetch-depth and sparse checkout
- Remember the defaults for three platforms: GitHub
fetch-depth: 1、fetch-tags: false; Azure Pipelines new pipeline (after 2022-09 sprint 209, some organizations) shallow acquisition depth 1. Synchronization label defaults to false; GitLab new projectGIT_DEPTH20。 - Explain from the object diagram why shallow cloning makes
git describe("No names found") andgit diff base...head("no merge base") failed. - Select fixes as needed:
fetch-depth: 0、--deepencycle,fetch-tags、--filter=blob:noneFull history + on-demand downloads, sparse checkouts.
What: Shallow cloning vs. partial cloning
shallow clone shallow(--depth N) | partial clone partial(--filter=blob:none) | sparse checkout sparse-checkout | |
|---|---|---|---|
| What is saved | Commit history: As long as the most recent N level commits, the parent commit of the boundary commit is "truncated" | File content: Get all commits and trees, and then download the blob when needed (tree:0Even trees are on demand) | workspace file: Check out only part of the directory to disk |
| Where is the record | .git/shallowList boundary commits | remote.origin.promisor=true、remote.origin.partialclonefilter | .git/info/sparse-checkout、core.sparseCheckoutCone |
| For historical commands | describe, merge-base, log, blame, rev-list --count are all possibleError or wrong result | The result is correct, when content is needed, it can be retrieved online (git log -p、blameWill trigger massive downloads) | does not affect history |
| Server requirements | generally supported | Filtering needs to be enabled on the server side (all supported by GitHub, Azure Repos, and GitLab) | pure client |
Default checkout for the three major platforms (verified in 2026-11)
| Platform | Default depth | tag | Turn off shallow cloning | Partially cloned/sparse |
|---|---|---|---|---|
GitHub Actions actions/checkout@v7 | fetch-depth: 1(Only take trigger commit) | fetch-tags: false;fetch-depth: 0will fetch all branches and tags | fetch-depth: 0 | filter: blob:none;sparse-checkout:(default cone mode) |
Azure Pipelines - checkout: self | In some organizations,New after 2022-09 sprint 209The pipeline has "shallow fetch" enabled by default and the depth1;Older pipelines do not get shallow by default. Subject to the Shallow fetch of the pipeline settings UI | New pipelines created after sprint 209fetchTags Default false, the previous one is true | fetchDepth: 0(takes precedence over UI settings) | fetchFilter: blob:none / tree:0;sparseCheckoutDirectories(cone)/ sparseCheckoutPatterns(Agent 3.253.0/4.253.0+, Git 2.25+) |
| GitLab CI | new projectGIT_DEPTH = 20(Settings → CI/CD → General Pipeline → Git Shallow Clones, max 1000) | Only take the refs required by the pipeline | GIT_DEPTH: 0Or clear/set to 0 in UI | GIT_FETCH_EXTRA_FLAGSParameters can be added;GIT_STRATEGY: fetch | clone | none |
Note: GitLab documentation emphasizes that depth is "clone depth, not commit count." Azure documentation reminds: If the depth is set too small, if the branch is pushed between queuing and checkout, the target commit may not be within the shallow history, causing the checkout to fail.
Why: What steps do shallow cloning make wrong?
| steps | what is needed | Phenomenon under shallow cloning |
|---|---|---|
git describe --tags(version number) | You can go back to a label from HEAD, and the label object is already local | fatal: No names found, cannot describe anything., or described as a more recent error label |
Change detection git diff --name-only origin/main...HEAD | Available locallyorigin/main, and can calculate merge-base | No such ref:fatal: ambiguous argument 'origin/main...HEAD': unknown revision;has ref but history truncated:fatal: origin/main...HEAD: no merge base |
commitlint --from base, gitleaks scan PR scope | All commits in range | "bad object", or only 1 commit checked (silent miss) |
| semantic-release / release-please / setuptools-scm / GitVersion | Full History + Tags | Calculate 1.0.0 or 0.1.dev1 and re-publish the existing version |
git rev-list --count HEADWhen the build number | full history | Always 1 (or equal to depth) |
git logGenerate release notes,git blame | full history | History "suddenly begins" at the boundary and the boundary commit appears as(grafted) |
How: Choose the repair method as needed
| demand | Recommended | cost |
|---|---|---|
| Only compile/test current code | Keep the default depth 1 | fastest |
| version number / changelog / release | fetch-depth: 0(+ label), for large repositoriesfetch-depth: 0 + filter: blob:none | Download all commits and trees, blobs on demand |
| PR change detection | Take the base branch and--deepenuntilgit merge-baseSuccess; or directly use the base/head SHA provided by the platform | Just take a few dozen more commits |
| monorepo only builds one service | Sparse call + partial cloning | The workspace and download size are small |
| Self-hosted runner repeatedly clones large repository | GIT_STRATEGY: fetch/ does not clean the workspace / references the repository (--reference) | Pay attention to residual files and cooperate withgit clean -ffdx |
When: When not to deepen
Not all assignments require history. Concentrate "steps that require history" into one job (such as release, changes), and keep other jobs as shallow clones; use them first for giant repositoriesblob:noneinstead offetch-depth: 0A complete clone of.
fetch-depth: 0Just a little slower" - On a repository of several gigabytes it might take a few minutes more per job, and most jobs don't need history at all. ② "It can be described as it deepens" - Also there aretag:actions/checkout defaultfetch-tags: false, our experiments also show that only--deepenThe old labels will not be brought back. ③ "--filter=blob:none"Equal to shallow cloning" - the history of some clones is complete, the history command results are correct, and they are only downloaded on demand when reading the file content. ④ "Shallow cloning omits files" - what is omitted isCommit, all files currently committed are there.
Object graph: What is there locally when depth=1
Comparison of three "slimming" methods
Core Animation: Shallow clone of missing commit, and after darkening
Click the buttons in order. Above is the local object diagram of the runner: solid line = existing locally, dotted light line = not available locally (available on the server). The log is the output from actually running the same steps on Git 2.51 (SHA is an example).
Core commands
| command | function | Description |
|---|---|---|
git rev-parse --is-shallow-repository | Determine whether shallow clone | Output true/false |
cat .git/shallow | View boundary commit | File does not exist = not shallow clone |
git fetch --deepen=50 | Deepen an additional 50 layers on the existing boundary | Increment |
git fetch --depth=200 | Set the depth to 200 (from the top of each ref) | absolute value |
git fetch --shallow-since=2026-10-01 | Deepen by date | Suitable for "changelog of the last month" |
git fetch --shallow-exclude=v1.2.0 | Get until a certain ref (exclusive) | Sometimes used for "from the previous tab" |
git fetch --unshallow | Go to full history | Equivalent to taking all |
git fetch --tags / --no-tags | Get all tags/no tags | describe requires tags |
git clone --filter=blob:none URL | blobless partial clone | Complete history |
git clone --filter=tree:0 URL | treeless partial clone | Only suitable for one-time construction; trees will be fetched on demand during diff |
git sparse-checkout set services/api libs/common | cone mode sparse checkout | git sparse-checkout list View |
git merge-base origin/main HEAD | Find common ancestors | Exit code 1 = not found |
GitHub Actions: Three ways to write
# A. Release/version jobs: full history + tags
- uses: actions/checkout@v7
with:
fetch-depth: 0 # 0 = all history, all branches and tags
# B. Large repository: complete commit of pictures + download content on demand
- uses: actions/checkout@v7
with:
fetch-depth: 0
filter: blob:none
# C. monorepo single service: sparse checkout (default cone mode)
- uses: actions/checkout@v7
with:
sparse-checkout: |
services/api
libs/common
PR change detection: only deepen to find merge-base
# Run after actions/checkout (depth 1); BASE_REF e.g. main
BASE_REF="${GITHUB_BASE_REF:-main}"
git fetch --no-tags --depth=50 origin "+refs/heads/${BASE_REF}:refs/remotes/origin/${BASE_REF}"
git fetch --no-tags --deepen=50 origin "$GITHUB_HEAD_REF" 2>/dev/null || true
for i in 1 2 3 4 5 6; do
git merge-base "origin/${BASE_REF}" HEAD >/dev/null 2>&1 && break
git fetch --no-tags --deepen=100 origin "${BASE_REF}"
done
git merge-base "origin/${BASE_REF}" HEAD || git fetch --unshallow --no-tags origin
git diff --name-only "origin/${BASE_REF}...HEAD"
The PR job checks out the merge ref (M1), and its second parent commit is the PR head; a simpler approach is to directly use the SHA given by the event:git diff --name-only ${{ github.event.pull_request.base.sha }}...${{ github.event.pull_request.head.sha }}(Both commits and their common ancestor still need to be local).
Azure Pipelines vs. GitLab CI
#azure-pipelines.yml steps: - checkout: self fetchDepth: 0 # Turn off shallow fetch (takes precedence over the Shallow fetch setting in the UI) fetchTags: true # New pipeline defaults to false fetchFilter: blob:none # Optional: partial clone persistCredentials: true # Only enable git push in subsequent steps. - script: git describe --tags
# .gitlab-ci.yml
variables:
GIT_DEPTH: 0 # or "50"; default for new projects is 20
GIT_FETCH_EXTRA_FLAGS: --tags # When tags are required
version:
script:
- git describe --tags
How to verify:Print first in the jobgit rev-parse --is-shallow-repository with git tag | head。Common mistakes:Only setfetch-depth: 0But it was executed again in subsequent stepsgit fetch --depth=1;Azure only changes the UI but writes YAMLfetchDepth: 1(YAML preferred).
Experiment 3: Reproduce and fix shallow clone failure locally (about 6 minutes, no network required)
mkdir -p ~/git-lab/shallow && cd ~/git-lab/shallow git init -q -b main src && cd src for i in 1 2 3; do echo $i > f$i; git add .; git commit -qm "feat: c$i"; done git tag -a v1.2.0 -m "v1.2.0" for i in 4 5; do echo $i > f$i; git add .; git commit -qm "fix: c$i"; done git switch -qc feature && echo x > x && git add . && git commit -qm "feat: x" git switch -q main && echo y > y && git add . && git commit -qm "chore: y" cd ..
file://The protocol will be truly shallow cloned, and the direct write path will be treated as a local hard link clone)git clone -q --depth 1 --branch feature "file://$PWD/src" ci && cd ci git rev-parse --is-shallow-repository git describe --tags git diff --name-only origin/main...HEAD
true fatal: No names found, cannot describe anything. 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 fetch -q --depth 1 origin main:refs/remotes/origin/main git diff --name-only origin/main...HEAD git merge-base origin/main HEAD; echo "exit=$?"
fatal: origin/main...HEAD: no merge base exit=1
git fetch -q --deepen=3 origin feature main git merge-base origin/main HEAD git describe --tags git fetch -q --tags origin git describe --tags git diff --name-only origin/main...HEAD
d8d2299b5413e066f51fc26dc918e131a1b011ac fatal: No names found, cannot describe anything. v1.2.0-3-gd66aeaa x
After deepening merge-base found (c5), the three-point diff correctly listed onlyx; but describe still fails until the label is retrieved.v1.2.0-3-gd66aeaaMeans "The 3rd commit after v1.2.0, HEAD is d66aeaa".
file://Filtering needs to be enabled on the server)git -C src config uploadpack.allowFilter true git clone -q --filter=blob:none --no-checkout "file://$PWD/src" bl && cd bl git rev-parse --is-shallow-repository git config remote.origin.promisor; git config remote.origin.partialclonefilter git describe --tags origin/feature git diff --name-only origin/main...origin/feature
false true blob:none v1.2.0-3-gd66aeaa x
Not openuploadpack.allowFilteryou will seewarning: filtering not recognized by server, ignoring, the clone degenerates into a full clone - this should also be checked on a self-built Git server.
infoThe checkout of the job is changed tofetch-depth: 0, confirm the describe output in the log after pushingv0.9.0-…。Case 1: Every release is 1.0.0
Question:After migrating to GitHub Actions, semantic-release "first released" 1.0.0 every time and failed because the tag already existed.Root cause:actions/checkoutThe default depth is 1 and no tags are taken. The tool cannot see any historical versions.Fix:post jobfetch-depth: 0(The semantic-release documentation also requires the full history).Prevention:Publish job opening assertiontest "$(git rev-parse --is-shallow-repository)" = false。
Case 2: monorepo change detection "nothing changed" leading to missed testing
Question:script writtengit diff --name-only HEAD~1, shallow cloneHEAD~1If it does not exist, the script will swallow the error and get an empty list, and all services will be skipped.Fix:Use base/head SHA + merge-base; when any Git command failsBuild all(fail-open to "build everything", not "build nothing").
Case 3: 6 GB repository 4 minutes per job clone
Method:Only two jobs, release and changes, require history, so change tofetch-depth: 0 + filter: blob:none(~40 seconds); the other 30 jobs remain at depth 1 + sparse checkouts to their respective service directories.Note:Run in blobless repositorygit log -porgit blameWill download a large number of blobs on demand, avoid in CI.
Common errors and solutions
fatal: No names found, cannot describe anything.
Root cause:There is no locally reachable label: shallow cloning truncates the history, or does not fetch the label (actions/checkoutfetch-tags: false, Azure new pipelinefetchTagsDefault false).Diagnosis:git tag | head; git rev-parse --is-shallow-repository。Fix:fetch-depth: 0;orgit fetch --tags --unshallow. Used when the repository does not have a labelgit describe --tags --alwaysDegenerates into short SHA.
fatal: origin/main...HEAD: no merge base
Root cause:The history of both sides is truncated, and the common ancestor is not local.Fix:Using "command" pagination--deepenloop, orfetch-depth: 0 + filter: blob:none。
fatal: ambiguous argument 'origin/main...HEAD': unknown revision or path not in the working tree.
Root cause:By default, shallow cloning only takes the triggered ref (single branch), which is not available locally.origin/main。Fix:git fetch --no-tags --depth=50 origin +refs/heads/main:refs/remotes/origin/main。
fatal: reference is not a tree: 3f9c… / Target commit not found during checkout (Azure: shallow fetch depth too small)
Root cause:After queuing, the branch is quickly advanced, and the fetch at depth 1 gets the new commit, and the target commit is not among them.Fix:increasefetchDepth(eg 10–50).
warning: filtering not recognized by server, ignoring
Root cause:The server does not support or has not enabled partial cloning (self-built serveruploadpack.allowFilter)。Fix:The server is up; or a full clone is accepted.
1. Currently is a shallow clone, turn it into full history and get back all tags.
git fetch --unshallow --tags origin
2. Write out the configuration of actions/checkout: complete commit history, but the file content is downloaded on demand, and only the services/api directory is checked out.
- uses: actions/checkout@v7
with:
fetch-depth: 0
filter: blob:none
sparse-checkout: services/apiVersion number script for GitLab projectsgit describeSometimes it succeeds and sometimes it fails, and most of the failures happen after a lot of commits have accumulated on main. Why?
GitLab new project defaultGIT_DEPTH=20. When the nearest tag is no more than 20 levels away from HEAD, the tag commit is within the shallow history and describe succeeds; if too many tags are committed and the tag falls outside the cutoff line, it fails. Fix: In this job settingsGIT_DEPTH: 0(or large enough) and ensure that labels are picked up; other jobs stay at the default depth.
Verified instructional videos
No verified video specifically talking about CI shallow cloning and fetch-depth was found. Please refer to the official documentation and the storyboard below.
Official documentation
- actions/checkout README(fetch-depth、fetch-tags、filter、sparse-checkout)
- Azure Pipelines: steps.checkout (Shallow fetch / Sync tags remarks)
- GitLab:Pipeline settings(Git shallow clone)
- GitHub Blog:Get up to speed with partial clone and shallow clone
- git-scm:git sparse-checkout
Video storyboard (approx. 75 seconds)
Image: Full commit image, v1.2.0 tag hanging on c3; a pair of scissors cutting along the left side of the x.
Narrator: By default, CI only fetches the most recent commit, and the history and tags on the left are not downloaded.
Picture: describe goes back from
Narrator: All commands that require history fail at the cutoff line.
Screen: deepen moves the dotted line to the left, c5 becomes a solid line, and the diff is successful; then fetch tags, the tag on c3 lights up, and describe outputs v1.2.0-3.
Narrator: Deepen retrieval of commits, retrieve tags to retrieve versions. Use blob:none for large repositories, which takes the entire history but downloads content on demand.
Module 4 · Commit and Tag Signing: GPG, SSH, gitsign
- Explain where the signature is stored: of the commit object
gpgsigheader and the end of the annotation tag message; the signature covers the object content (including tree SHA and parent commit), so the signature protects the entire historical snapshot. - There are three ways to configure: GPG (
user.signingkey)、SSH(gpg.format ssh、gpg.ssh.allowedSignersFile)、gitsign(gpg.format x509+gpg.x509.program gitsign)。 - Explain clearly the platform's "Verified" determination (the key is registered on the account + the committer's email has been verified), as well as the GitHub rule set "Require signature commit" and the GitLab push rule "Reject unsigned commit" (Premium).
git cat-file -p, Lesson 3 SSH Authentication Keys.Importance:★★★★ (supply chain security and compliance audit)What: What exactly did the signature sign?
git commit -SWhen , Git first constructs the text of the commit object (tree, parent, author, committer, message), gives this text to the signature program (gpg/ssh-keygen/gitsign), and then uses the returned signature asgpgsigThe header is inserted into the object and finally the SHA is calculated. Remove during verificationgpgsigheader, restore the signed text and then verify it. Because the text containstree SHA and parent SHA, a valid signature indirectly covers the full file snapshot and entire ancestral history of that commit.
Comparison of three signature methods
| GPG(OpenPGP) | SSH(Git 2.34+) | gitsign(Sigstore, no key) | |
|---|---|---|---|
| key | Long-term GPG key, expirable and revocable | Existing or dedicated SSH key (recommended by ed25519; FIDO2 hardware key availableed25519-sk) | No long-term keys: OIDC login → Fulcio issues certificate valid for ~10 minutes → Sign → Log to Rekor transparent log |
| Git configuration | user.signingkey <KEYID> | gpg.format ssh、user.signingkey ~/.ssh/key.pub | gpg.format x509、gpg.x509.program gitsign |
| local verification | Public key import keyring | gpg.ssh.allowedSignersFile(email ↔ public key) | gitsign verify --certificate-identity --certificate-oidc-issuer |
| GitHub show | Verified | Verified (public key registered as Signing Key) | Unverified(The Sigstore root is not in the GitHub trust root, and the short-term certificate needs to be verified with Rekor) |
| GitLab display | Verified | Verified | X.509 requires the instance to trust the corresponding CA, and public Sigstore generally displays unverified |
| suitable for | Existing PGP system, need to revoke semantics | Most developers: easiest | CI bots (workload identities), teams that don’t want to manage keys, need transparent log auditing |
Why: Why should you sign?
- Anti-counterfeiting: Anyone can
git config user.email ceo@example.comPost-push; the avatar displayed on the platform is only matched by email address. - Tamper proof: The rewritten history in mirroring, migration, and third-party hosting cannot maintain valid signatures.
- Compliance: SLSA, some industry audits require source code changes that can be traced to specific identities; release label signatures to allow users to verify "this is official v1.3.0".
How: Determination of platform "Verified" (GitHub)
- The signature is cryptographically valid, andThe signing key is registered on a GitHub account(GPG key, SSH Signing Key, or S/MIME certificate), andCommitter's emailIt is the verified email address of this account.
- Vigilant mode(Personal settings, off by default): When turned on, unsigned commits with you as the author/committer will also be marked as Unverified, and have a "Partially verified" status.
- Persistent verification: Submissions that pass verification when pushing will be recorded (with timestamp, REST API field
verified_at) and then remains Verified even if the key is rotated, revoked, or the member leaves the organization. - Commits created on the GitHub webpage (including squash merges in the interface) are generated by GitHub's
web-flowGPG key signature, showing Verified.
Signature commit required
| Platform | mechanism | Note |
|---|---|---|
| GitHub | Rule Set/Branch Protection:Require signed commits | Every commit pushed to the target branch must have a verified signature; gitsign signatures are considered unverified; some merge methods may be restricted, see GitHub documentation |
| GitLab | Push rules:Reject unsigned commits(Premium / Ultimate) | Authentication supports GPG, SSH, X.509; GitLab web commits signed by instance key |
| Azure Repos | As of the date of verification, no built-in policies were found in Microsoft Learn to display signature verification status or force signatures | Can be checked with script in PR build verificationgit log --format=%G?and set to required (see "Commands") |
When: Which one to choose?
Individual developers:SSH signature(Reuse the existing tool chain and get it done in five minutes). Organizational unity: SSH signing keys are placed in hardware keys or password managers (1Password and others support SSH agent signing). CI robot commit: give priority to robotsDo not commit directly(via PR + web merge, signed by platform); use GitHub App to create commits via API if needed (GitHub will sign), or gitsign the workload identity.
git tag -sortag.gpgSign=true。③ “git verify-commitIf it passes, it means it was signed by Alice" - in SSH mode, it depends on which email is mapped to which public key in the allowed_signers file; in gitsign mode, it must be usedgitsign verifyCheck both the identity and the issuer. ④ "The signature is still there after the rebase" - rebase/modification will generate a new commit and need to be re-signed (git rebase --exec 'git commit --amend --no-edit -S'or turn oncommit.gpgSign)。Signing and verification data flow
Keyless signing with gitsign
Animation: Signature → Push → Platform Verification
Select the signature method and situation, and gradually observe the commit object and platform judgment.
Core commands
| command | function | Description |
|---|---|---|
git commit -S -m ... | Signature commit | commit.gpgSign=truedefault signature |
git tag -s v1.3.0 -m ... | Signature note label | tag.gpgSign=true |
git verify-commit HEAD / git verify-tag v1.3.0 | Verify | Failure exit code is non-0 |
git log --show-signature -1 | Show signature details | — |
git log --format='%h %G? %GS %s' | View signature status in batches | %G?: G valid, B invalid, U valid but unknown trust, X signature expired, Y key expired, R key revoked, E unable to check (missing public key/not configured), N no signature |
git cat-file -p HEAD | Look at the gpgsig header | Understand the principles |
gitsign verify --certificate-identity=... --certificate-oidc-issuer=... HEAD | Verify gitsign signature and identity | Thangit verify-commitstricter |
SSH signing (recommended)
git config --global gpg.format ssh git config --global user.signingkey ~/.ssh/id_ed25519_signing.pub git config --global commit.gpgSign true git config --global tag.gpgSign true # Local authentication requires allowed signers file: email + namespaces + public key mkdir -p ~/.config/git echo "alice@example.com namespaces=\"git\" $(cat ~/.ssh/id_ed25519_signing.pub)" >> ~/.config/git/allowed_signers git config --global gpg.ssh.allowedSignersFile ~/.config/git/allowed_signers
GPG signature
gpg --quick-generate-key "Alice <alice@example.com>" ed25519 sign 1y gpg --list-secret-keys --keyid-format=long # Get sec ed25519/XXXXXXXXXXXXXXXX git config --global user.signingkey XXXXXXXXXXXXXXXX git config --global commit.gpgSign true gpg --armor --export XXXXXXXXXXXXXXXX | gh gpg-key add - export GPG_TTY=$(tty) # Write ~/.bashrc, otherwise the password input cannot be popped up
gitsign (single repository enabled)
brew install sigstore/tap/gitsign # Or download v0.18.0 from GitHub Releases git config --local gpg.x509.program gitsign git config --local gpg.format x509 git config --local commit.gpgSign true git commit -m "chore: keyless signed commit" # Browser pops up OIDC login gitsign verify --certificate-identity=alice@example.com \ --certificate-oidc-issuer=https://github.com/login/oauth HEAD
Check in CI that all commits in the PR are signed (for platforms without built-in policies, such as Azure Repos)
# Requires full scope history (M3) and allowed_signers files (can be placed in protected repository paths)
git config gpg.ssh.allowedSignersFile .github/allowed_signers
bad=$(git log --format='%H %G?' "$BASE_SHA..$HEAD_SHA" | awk '$2!="G"{print $1}')
if [ -n "$bad" ]; then echo "Unsigned or unverifiable commits:"; echo "$bad"; exit 1; fi
How to verify:git log --format='%G?' -1 output G。Common mistakes:When the SSH signature is not configured with allowedSignersFile, the verification reporterror: gpg.ssh.allowedSignersFile needs to be configured and exist for ssh signature verification,%G?forN/E- This only affects local verification, platforms may still show Verified.
Lab 4: SSH signature committed and verified on both ends (~5 minutes)
cd ~/git-lab/myapp && git switch -c feat/version-endpoint
printf '\n@app.get("/version")\ndef version():\n return {"version": "dev"}\n' >> app.py
git commit -am "feat(api): add /version endpoint"
git cat-file -p HEAD | sed -n '1,8p'
git log --show-signature -1
tree 9c3e1f0… parent 2f8d4e6… author Alice <alice@example.com> 1763190000 -0500 committer Alice <alice@example.com> 1763190000 -0500 gpgsig -----BEGIN SSH SIGNATURE----- U1NIU0lHAAAAAQAAADMAAAALc3NoLWVkMjU1MTkAAAAg… … -----END SSH SIGNATURE----- commit 7b1e… Good "git" signature for alice@example.com with ED25519 key SHA256:Xy3…
git log --format='%h %G? %an %s' -5
7b1e2c4 G Alice feat(api): add /version endpoint 2f8d4e6 N Alice ci: also run on version tags …
git push -u ci feat/version-endpoint && gh pr create --repo alice/myapp-ci --fill
gh api repos/alice/myapp-ci/commits/$(git rev-parse HEAD) --jq '.commit.verification | {verified, reason}'
{
"reason": "valid",
"verified": true
}Case 1: Impersonation commit
Question:An open source project appeared with a commit whose author was shown as a core maintainer. In fact, the attacker set the sameuser.email。Method:All maintainers turn on vigilant mode, and the repository rule set requires signature commit; the Verified badge will be used as the criterion during review.
Case 2: All robots failed after turning on "Require signature"
Question:Used to depend on update robots and release scriptsgit pushPushing an unsigned commit was rejected.Method:Commits of built-in robots such as Dependabot are signed by the platform; self-built release scripts are changed to create commits through the GitHub API (GitHub App token) and signed by GitHub; or only the robot opens a PR and is merged on the web page by a human or merge queue.
Case 3: Do historical commits become Unverified after an employee leaves?
Analysis:GitHub's persistent verification will retain verification records when pushing. Verified commits will still be Verified after resignation or key deletion. But if the repository is migrated to another platform and the new platform needs to be re-verified, then the lack of public key will show as unverified - export the maintainer's public key before migration and register it on the target platform, or keep independent signature verification instructions on the release label.
Common errors and solutions
error: gpg failed to sign the data / fatal: failed to write commit object
Reason:GPG cannot pop up password input (missingGPG_TTY, pinentry is not installed), key expired,user.signingkeyWrong writing.Diagnosis:echo test | gpg --clearsign;GIT_TRACE=1 git commit -S -m tLook at the command being called.Fix:export GPG_TTY=$(tty);gpgconf --kill gpg-agent;Renewalgpg --quick-set-expire。
error: gpg.ssh.allowedSignersFile needs to be configured and exist for ssh signature verification
Reason:Local verification of SSH signatures requires the allowed signers file.Fix:See the "Commands" tab; teams can commit a list of member public keys to the repository and use it in CI.
GitHub shows Unverified: "The email in this signature doesn't match the committer email" / Key not found
Reason:The committer's email address is not an account-verified email address (for example, the company email address is not added), or the SSH public key is only registered as an authentication key.Fix:Add and verify the email address in your account, or modify ituser.emailThen re-sign; register the public key again and select Signing Key as the type. gitsign signatures showing Unverified on GitHub are expected.
remote: error: GH013: Repository rule violations found for refs/heads/main. … Commits must have verified signatures.
Reason:The rule set requires signature, and there are unsigned/unverified commits in the push range (commonly caused by merging other people's unsigned commits or forgetting to re-sign after rebasing).Fix:git rebase --exec 'git commit --amend --no-edit -n -S' origin/mainThen push it to your branch and start a PR. The error wording shall be subject to the actual output of the platform.
1. List all commits in the origin/main..HEAD scope that have a signature status other than G.
git log --format='%h %G? %s' origin/main..HEAD | awk '$2!="G"'
2. Give the current commit a signature tag v1.3.0 and verify it.
git tag -s v1.3.0 -m "v1.3.0" && git verify-tag v1.3.0
The organization wants the release bot commit CHANGELOG in CI to also show Verified and does not want to manage long-term private keys. What are the options?
① Use the GitHub App installation token to create a commit through the REST/GraphQL API (GitHub signs with the web-flow key, showing Verified), release-please creates the release PR through the API; ② The robot only opens the PR, and the merge queue/web page merge generates a platform-signed commit; ③ gitsign uses the OIDC identity signature of the workflow, which can be audited in the transparent log, but GitHub shows Unverified, which needs to be used in its own verification processgitsign verify;④ If you must use SSH/GPG keys, put them in confidential storage and limit the environment and branches, and rotate them regularly.
Verified instructional videos
No verified gitsign special video found, please refer to Sigstore documentation.
Official documentation
- GitHub:About commit signature verification
- GitLab:Signed commits
- git-config:gpg.ssh.allowedSignersFile
- sigstore/gitsign
Video storyboard (approximately 60 seconds)
Screen: Two commit avatars are the same, one with green Verified and one without.
Narrator: Anyone can forge usernames and emails, only signatures can prove the source.
Screen:
git cat-file -p HEADHighlight the gpgsig header with arrows pointing to tree and parent.Narrator: The signature covers the tree and the parent commit, protecting the entire snapshot and history.
Screen: Comparison of three columns: GPG, SSH, gitsign, and finally the rule set "Require signed commits" is displayed.
Narrator: SSH signing is easiest for individuals, and the platform ruleset takes care of enforcement.
Module 5 · Confidential leakage prevention and scanning
- use gitleaksScan the staging area, all history, directories, use custom rules, baselines,
.gitleaksignoreManage false positives. - use TruffleHog ofOnline verificationDistinguish between a "real, valid key" and a "string that looks like a key".
- Understand where platform push protection (GitHub Secret Protection, GitHub Advanced Security for Azure DevOps, GitLab Secret Push Protection) blocks and bypasses when pushing.
- Execute leak response:Immediate revocation/rotation → Assess abuse → Fix code → Decide whether to rewrite history → Prevent recurrence。
git log -S。Importance:★★★★★What: Four lines of defense
| line of defense | location | Tools | Can it be bypassed |
|---|---|---|---|
| 1. Keep secrets out of the workspace | Developer PC | Secret Manager (Key Vault, Secrets Manager, 1Password),.gitignore, OIDC Federated Identity (no long-term keys to leak) | — |
| 2. Interception before commit | pre-commit | gitleaks(--staged)、TruffleHog、detect-private-key | OK (--no-verify) |
| 3. Intercept when pushing | Platform receive-pack | GitHub push protection, Azure DevOps push protection (GHAzDO Secret Protection), GitLab secret push protection (Ultimate) | Audit bypass (need to select a reason to generate an alarm) |
| 4. Discovered after pushing | CI + platform scan | In CI, gitleaks/TruffleHog full history scan (required check), platform secret scan alarm, scheduled scan | Not bypassable, but leaked |
gitleaks and TruffleHog
| gitleaks 8.30.1 | TruffleHog 3.99.9 | |
|---|---|---|
| Detection method | Regular + entropy + keyword (.gitleaks.tomlExtensible default rules) | Recognizes 800+ confidentiality types with 700+ detectorsCall service provider API verificationWhether the key is valid (such as AWS using GetCallerIdentity) |
| Scan objects | gitleaks git(Based ongit log -p)、dir、stdin; since v8.19detect/protectDeprecated | git、github、gitlab、filesystem、s3、dockerWait |
| False positive management | baseline report,.gitleaksignore(fingerprint), within the industrygitleaks:allow, rule allowlist | --results=verified,unknownOnly report valid/unconfirmable results |
| CI integration | gitleaks/gitleaks-action@v3(Organization repository requires free licenseGITLEAKS_LICENSE) or run the binary directly | trufflesecurity/trufflehog Action,--failExit code 183 on discovery |
| Status | The README states that it is "feature-complete" and that only security patches will be released in the future. The maintainers have moved to the new project Betterleaks. | Active publishing (almost every week) |
Why: Why “rotation takes precedence over rewriting history”
- Keys in public repositories may be pushed afterwithin minutesCaught by automated crawlers; you can never rewrite history faster than you can.
- The rewrite history cannot be cleared: existing clones and forks, CI logs and caches, and platform PR references (
refs/pull/*cannot be rewritten by you), search engines and archives, unreferenced objects accessed directly by SHA (need to contact platform support for cleaning). - Only let the keyInvalidOnly when losses are truly stopped; rewriting history is a "hygiene" job, used to reduce subsequent false positives and compliance risks, not the security measures themselves.
How: Five Steps to Breaches Response
| # | action | Description |
|---|---|---|
| 1 | Revoke/Rotate | Disable the old key at the service provider, issue the new key and update to the secret manager; don't wait to fix the PR merge |
| 2 | Assess abuse | Check the service provider's audit logs (CloudTrail, Entra login logs, GitHub audit logs) for abnormal calls since the time of the leak |
| 3 | fix code | Removed from the current code and read from the environment/secret manager instead; add rules to prevent recurrence |
| 4 | Decide whether to rewrite history | Private repository and rotated: acceptable for retention (joined to baseline); public repository/compliance requirements:git filter-repoClear and coordinate staff-wide re-clone, contact platform support to clear cached views (Lesson 7) |
| 5 | Review | Why didn’t the first three lines of defense stop me? Consider using OIDC instead of long-term keys |
When: What range to scan
| timing | range | command |
|---|---|---|
| pre-commit | Staging area | gitleaks git --pre-commit --staged --redact |
| PR | Commits introduced by PR | gitleaks git --log-opts="BASE..HEAD"(requires sufficient depth, M3) |
| First access/timing | All branches all history | gitleaks git --log-opts="--all"、trufflehog git file://. --results=verified,unknown |
FAKE_SECRET=fake-…This custom format will most likely require custom rules (as you'll see in the lab). ④ "Forget it if push protection is bypassed" - every bypass will generate an alarm and need to be dealt with.Timeline of secrets from creation to expiry
Why can’t rewriting history be clean?
Interactive: Leak Response Simulator
Scenario: An engineer pushes an AWS access key topublicrepository. Choose the order of your responses and see what happens on the timeline.
Core commands
| command | function |
|---|---|
gitleaks git -v | Scan the current branch history of the current repository (based ongit log -p) |
gitleaks git -v --log-opts="--all" | Scan all citations |
gitleaks git --log-opts="origin/main..HEAD" | Scan PR ranges only |
gitleaks dir -v . | Scan directory (without looking at history) |
gitleaks git --report-path base.json / --baseline-path base.json | Generate baseline/report only new findings |
gitleaks git --report-format sarif --report-path gl.sarif | Output SARIF, can be uploaded to code scanning |
trufflehog git file://. --results=verified,unknown | Scan the entire history of the local repository and only report those that have been verified to be valid or cannot be confirmed |
trufflehog git file://. --since-commit HEAD~5 --fail | Scan recent commits and exit with 183 if found |
git log -S 'FAKE_SECRET' --all --oneline | Find the commit that introduced/removed a string (Lesson 1) |
.gitleaks.toml: extend default rules and add custom rules
# .gitleaks.toml
title = "myapp gitleaks config"
[extend]
useDefault = true # Keep all built-in rules
[[rules]]
id = "myapp-fake-secret"
description = "myapp training secret FAKE_SECRET"
regex = '''FAKE_SECRET\s*=\s*([A-Za-z0-9_-]{12,})'''
secretGroup = 1
keywords = ["fake_secret"]
[allowlist]
description = "Test Fixture"
paths = ['''tests/fixtures/.*''']
CI: gitleaks (GitHub Actions) and TruffleHog
secrets:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
with:
fetch-depth: 0 # Scan history must have history (M3)
- uses: gitleaks/gitleaks-action@v3
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GITLEAKS_LICENSE: ${{ secrets.GITLEAKS_LICENSE }} # Only required for organizational repositories
- name: TruffleHog (verified only)
run: |
docker run --rm -v "$PWD:/repo" trufflesecurity/trufflehog:latest \
git file:///repo --results=verified,unknown --fail
In production:latestChange to fixed version tags or snippets. TruffleHog's verification will make a request to the service provider API - only unknown can be obtained in an isolated network.Common mistakes:Under shallow cloning, gitleaks only scans 1 commit, and "no discovery" is an illusion.
Lab 5: Finding FAKE_SECRET in the practice repository history (~6 min)
cd ~/git-lab/myapp git log -S FAKE_SECRET --all --oneline git grep -n FAKE_SECRET $(git rev-list --all) -- settings.env | head -3
abb417c fix: remove FAKE_SECRET from settings.env bbc4ca6 chore: add settings.env bbc4ca6…:settings.env:3:FAKE_SECRET=fake-9f8e7d6c-not-a-real-key
gitleaks git -v --log-opts="--all" .
○
│╲
│ ○
○ ░
░ gitleaks
INF 1x commits scanned.
INF scanned ~… bytes in …ms
INF no leaks found
Most likely "no leaks found":fake-9f8e7d6c-not-a-real-keyIt is not a key format for any known service and does not have high entropy. This is an example of "scanner misses ≠ no secrets".
.gitleaks.tomlSave to the root directory of the repository.gitleaks git -v --log-opts="--all" --redact .
Finding: FAKE_SECRET=REDACTED Secret: REDACTED RuleID: myapp-fake-secret Entropy: 3.92 File: settings.env Line: 3 Commit: bbc4ca6… Author: Git Lab Date: 2026-01-01T09:05:00Z Fingerprint: bbc4ca6…:settings.env:myapp-fake-secret:3 INF 1x commits scanned. WRN leaks found: 1
abb417c); rewriting history is left to Lesson 7. now add it.gitleaksignore, let CI be only fornewDisclosure failed:echo "bbc4ca6…:settings.env:myapp-fake-secret:3" >> .gitleaksignore # Paste the complete Fingerprint output from the previous step gitleaks git --log-opts="--all" . && echo "clean (with ignore)" git switch -c ci/secret-scan && git add .gitleaks.toml .gitleaksignore git commit -m "ci: add gitleaks config with custom rule and ignore list"
trufflehog git file://. --results=verified,unknown trufflehog git file://. --results=unverified | head -20
The first one has a high probability of no output (fake secrets cannot be verified); the second one may list several "unverified" candidates to understand how the verification mechanism can reduce noise.
secretsSet as required check.Case 1: Cloud key in public repository abused after 6 minutes
After:The developer pushed the configuration containing the access key to the public repository, and within a few minutes a large number of API calls from unfamiliar IPs appeared (creating high-configuration instance mining). The team first spent an hour doing filter-repo to rewrite history, during which the losses continued to expand.Correct approach:Revoke the key in the first minute; check CloudTrail again; and finally decide whether to clear the history.Prevention:CI deployments use OIDC federated identities instead, eliminating long-term keys.
Case 2: Push protection "I'll fix it later" becomes the norm
Question:Developers frequently choose to bypass reasons in order to meet deadlines.Method:Enable delegated bypass so only security team members can approve bypass requests; set an SLA for open alerts generated by "Fix Later."
Case 3: CI logs leak secrets
Question:When debuggingset -xplusgit clone https://user:$TOKEN@...Print the token to the log. The platform's log mask only recognizes values registered as confidential, and spliced/encoded values will not be masked.Method:Use Credential Assistant orhttp.extraheaderPass tokens, don't embed credentials in URLs; logs are treated as leaks and tokens are rotated. Tampered Actions in supply chain events will also print the secret in the runner's memory to the log (see M7 case), so the Action must be pinned to the SHA.
Common errors and solutions
remote: error: GH013: Repository rule violations found for refs/heads/feature. … Push cannot contain secrets
Reason:GitHub Push Protection detected a supported secret in a push-scoped commit.Fix:If the secret was last committed: after deletiongit commit --amend;In an earlier commit:git rebase -iEdit the commit to remove the secret; then push again.Don'tAppends only one "removed" commit - old commits in the push scope still contain secrets. Only use the bypass link in the prompt and select a reason if it is indeed a false positive.Anyway, if the secret has ever left your computer (such as being pushed elsewhere), rotate it first.
Azure Repos: Push rejected by Advanced Security push protection (secret detected)
Reason:The organization has enabled GitHub Advanced Security for Azure DevOps or the standalone GitHub Secret Protection for Azure DevOps, and push protection detects high-confidence secrets (web interface commits are also blocked).Fix:Same as GitHub: the most recent commit isgit commit --amend, used earliergit rebase -iRepost after editing; sample values can be added in frontPlaceholderprefix. When it is confirmed that it is a false alarm, you can add it to the commit information.skip-secret-scanning:trueBypass - Alerts will still be generated after push.
gitleaks "no leaks found" in CI, but local problems can be found
Reason:CI is a shallow clone and only scanned 1 commit; or CI did not read.gitleaks.toml(The working directory is different).Fix:fetch-depth: 0;explicit--config .gitleaks.toml; Check whether "N commits scanned" is reasonable in the log.
gitleaks-action: missing gitleaks license / Failed to run in the organization's repository
Reason:Organization-owned repositories require a free license key.Fix:Apply at gitleaks.io and save asGITLEAKS_LICENSEConfidential; or download the binary and run it directly (MIT license) without using Action.
Lots of false positives blocking all PRs
Fix:Used when accessing for the first time--report-path baseline.jsonGenerate baselines for CI--baseline-pathOnly report new findings; use rule allowlist for test fixturespaths; Used for single line false positivesgitleaks:allowComments (code review required).
1. Only scan the new commits of the current branch relative to origin/main and desensitize the output.
gitleaks git --redact --log-opts="origin/main..HEAD" .
2. Use TruffleHog to scan the local repository and only fail the command if a verified and valid key is found.
trufflehog git file://. --results=verified --fail
On Friday night, you discover that a production database password was committed 3 weeks agoprivateThe history of the repository, the current code has been deleted. Please provide processing steps and priorities.
① Immediately rotate the database password (the application reads the new password from the secret manager instead, and arranges a rolling restart), because the repository may have been cloned by many people, CIs, and integrations within 3 weeks; ② Check the database and network audit logs to confirm whether there are any abnormal logins since the commit time; ③ The current code has been deleted, and gitleaks custom rules and CI must be checked; ④ If the private repository has been rotated, the finding can be added to the baseline; if compliance requirements are cleared, follow Section 7 For class usegit filter-repoRewrite and coordinate the re-cloning of all members; ⑤ Review why the front line of defense did not stop it.
Verified instructional videos
Official documentation
- gitleaks README
- TruffleHog README
- GitHub:About push protection
- GitHub:Removing sensitive data from a repository
- GitLab:Secret push protection
Video storyboard (approximately 60 seconds)
Screen: A timeline: Editor → commit → push → remote, with a gate in front of each node.
Narrator: The earlier it is stopped, the cheaper it is. Once it is pushed, it will be treated as "leaked".
Screen: gitleaks outputs “no leaks found”, which becomes “leaks found: 1” after adding custom rules.
Narrator: The scanner only recognizes the formats it has seen, and you have to write your own rules for custom formats.
Screen: Two branches: rewrite history first (crawler has crawled, red) vs. rotate first (key expired, green).
Narrator: Revoking will make all copies invalid at the same time, and rewriting history will just clean things up.
Module 6 · Conventional commit, semantic versioning and automatic publishing
- Write out theConventional Commits 1.0.0Submission information (type, scope,
!、BREAKING CHANGE:footnote), say it is related toSemVer 2.0.0of mapping. - Use commitlint to verify locally (commit-msg) and CI (PR commit scope), and understand that "the PR title is the commit information" when merging squash.
- Contrast release-please(Release PR mode) vs.semantic-release(fully automatic mode), configure release-please for myapp and complete a release.
What: Conventional commit format
<type>[(scope)][!]: <description>
[body]
[footer(s)] For example BREAKING CHANGE: /v1 endpoints removed
Refs: #123
| Writing method | meaning | SemVer impact (≥ 1.0.0) |
|---|---|---|
fix(api): handle redis timeout | fix defects | PATCH:1.2.0 → 1.2.1 |
feat(api): add /version endpoint | new features | MINOR:1.2.0 → 1.3.0 |
feat(api)!: drop /v1 routesor footnoteBREAKING CHANGE: ... | Incompatible changes | MAJOR:1.2.0 → 2.0.0 |
docs: chore: ci: test: refactor: style: build: | Does not affect published types (types allowed by config-conventional) | Not published by default (perf:Processed by revision number in most tools, subject to tool configuration) |
SemVer 2.0.0 states: Major version number 0 (0.y.z) is in initial development and anything may change. Tools handle 0.x differently: release-please can be setbump-minor-pre-majorLet breaking changes in the 0.x phase be only upgraded to minor versions.
Why: The value of automatic publishing
- Version numbers no longer depend on human memory: Derive the next version from "commits since the last tag" to avoid duplication or number skipping.
- CHANGELOG automatically generated: Grouped by Features / Bug Fixes / BREAKING CHANGES, linked to commits and PRs.
- Release auditable: The release action is completed by the pipeline on a protected branch, and the tag is protected by a rule set.
How: Comparison of two major tools
| release-please(googleapis) | semantic-release | |
|---|---|---|
| mode | push main → create/updatePost a PR(Including version number and CHANGELOG); merge and release PR → tag + create GitHub Release | push main → directly calculate version, tag and publish (no PR) |
| artificial control point | It’s up to people to decide when to merge a PR | Each merge may release |
| Git historical sources | Pass GitHub APIRead commits and tags (release-please-action itself does not require checkout code) | readlocal clone: requiredfetch-depth: 0 |
| Language/Ecology | release-type:simple、node、python、go、javaetc.; monorepo is configured using manifest | Plug-in system (npm, GitHub, GitLab, exec...), mainly Node.js ecology but can publish any project |
| Platform | GitHub (Action currentv5.0.0, node24; underlying library v17.x) | GitHub, GitLab, and other CIs are available (v25.0.9, Node^22.14.0 || >=24.10.0) |
| Azure Pipelines / GitLab CI | release-please CLI available, but primarily designed for GitHub | Native support (GitLab plugin@semantic-release/gitlab) |
When: squash merge and commit information
When merging using squash, only one commit is left on main, whose information defaults fromPR title(GitHub can set a default message source), so verifyPR title(e.g.amannn/action-semantic-pull-requestor in CI forgithub.event.pull_request.titleRun commitlint); when using merge/rebase to merge, each commit in the PR will enter main and needs to be verified.every commit。
GITHUB_TOKENCreated PR will not triggerpull_requestWorkflow (M1), requires GitHub App/PAT token. ③ "The version number is written in the code and can be changed by people" - it will conflict with the tool; leave it to the tool to update (release-pleaseextra-filesThe version number in the extra file can be updated).release-please release process
Version number calculation rules
Interactive: Version number calculator
Starting with v1.2.0, click the button to add a commit to main and watch the next version number and CHANGELOG preview. Check "Phase 0.x" to see the difference in the initial development period.
Core commands and configuration
| command | function |
|---|---|
npx commitlint --from origin/main --to HEAD --verbose | Verify a range of commit messages |
echo "feat: x" | npx commitlint | Verify a message |
git log --format=%s v1.2.0..HEAD | Look at the commit titles since the last version |
git describe --tags --abbrev=0 | nearest tag (requires full depth, M3) |
npx semantic-release --dry-run --no-ci | Preview the next version locally (not publish) |
npx release-please release-pr --repo-url=alice/myapp-ci --token=$GH_TOKEN --dry-run | release-please CLI preview release PR |
commitlint configuration (v21, Node ≥ 22.12)
npm init -y >/dev/null
npm install --save-dev @commitlint/cli@21 @commitlint/config-conventional@21
cat > commitlint.config.mjs <<'EOF'
export default {
extends: ['@commitlint/config-conventional'],
rules: {
'scope-enum': [2, 'always', ['api', 'worker', 'deps', 'ci', 'docs']],
'subject-case': [0],
},
};
EOF
echo "update stuff" | npx commitlint
⧗ input: update stuff ✖ subject may not be empty [subject-empty] ✖ type may not be empty [type-empty] ✖ found 2 problems, 0 warnings
GitHub Actions: Verify commits and titles in PRs
commitlint:
if: github.event_name == 'pull_request'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
with:
fetch-depth: 0 # Require all commits within base..head range
- uses: actions/setup-node@v7
with:
node-version: 24
- run: npm ci
- name: Lint commits in PR
run: npx commitlint --from ${{ github.event.pull_request.base.sha }} --to ${{ github.event.pull_request.head.sha }} --verbose
- name: Lint PR title (squash merge message)
env:
TITLE: ${{ github.event.pull_request.title }}
run: echo "$TITLE" | npx commitlint
The PR title is passed in through environment variables instead of written directly${{ ... }}In the run script - the title is an untrusted input, and direct interpolation has the risk of script injection.
release-please (python project)
# .github/workflows/release-please.yml
name: release-please
on:
push:
branches: [main]
permissions:
contents: write
pull-requests: write
issues: write
jobs:
release-please:
runs-on: ubuntu-latest
outputs:
release_created: ${{ steps.rp.outputs.release_created }}
tag_name: ${{ steps.rp.outputs.tag_name }}
steps:
- uses: googleapis/release-please-action@v5
id: rp
with:
release-type: python
token: ${{ secrets.RELEASE_PLEASE_TOKEN }} # GitHub App/PAT, so that publishing PR can trigger CI; if omitted, use GITHUB_TOKEN
publish:
needs: release-please
if: needs.release-please.outputs.release_created == 'true'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
with:
ref: ${{ needs.release-please.outputs.tag_name }}
- run: echo "build and push image myapp:${{ needs.release-please.outputs.tag_name }}"
semantic-release (alternative)
release:
runs-on: ubuntu-latest
permissions:
contents: write
issues: write
pull-requests: write
steps:
- uses: actions/checkout@v7
with:
fetch-depth: 0 # Required: full history + tags
persist-credentials: false # Use GITHUB_TOKEN to push tags by semantic-release
- uses: actions/setup-node@v7
with:
node-version: 24
- run: npx semantic-release@25
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
Semantic-release in Azure Pipelines / GitLab CI
# azure-pipelines.yml (Azure Repos repository requires additional plug-ins or exec method to push tags, please refer to the plug-in documentation)
trigger:
branches: { include: [main] }
steps:
- checkout: self
fetchDepth: 0
fetchTags: true
persistCredentials: true # Allow subsequent git push tags (building service account requires "participate" permission)
- task: UseNode@1
inputs: { version: '24.x' }
- script: npx semantic-release@25
env:
GH_TOKEN: $(GH_TOKEN) # GitHub repository
# .gitlab-ci.yml
release:
image: node:24
variables:
GIT_DEPTH: 0
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
script:
- npm install --no-save semantic-release@25 @semantic-release/gitlab
- npx semantic-release
# Requires CI/CD variable GITLAB_TOKEN (api scope, protected+mask)
Lab 6: Use release-please to release the next version of myapp (about 7 minutes)
v1.0.0、v1.1.0(Lesson 1) and this lessonv0.9.0. release-please starts with the latest semver tag/Release; remove v0.9.0 first to avoid confusion.cd ~/git-lab/myapp && git push ci :refs/tags/v0.9.0 && git tag -d v0.9.0
git push ci v1.0.0 v1.1.0
printf '{ ".": "1.1.0" }\n' > .release-please-manifest.json
cat > release-please-config.json <<'EOF'
{
"packages": { ".": { "release-type": "python", "package-name": "myapp" } }
}
EOF
When using manifest configuration, remove it from the workflowrelease-typeBoth files can be read by typing; you can also just userelease-type: pythonsimple mode.
git switch main && git pull ci main mkdir -p .github/workflows # Paste the release-please.yml of the "Command" page git add .github/workflows/release-please.yml release-please-config.json .release-please-manifest.json git commit -m "ci: add release-please" git push ci main # If main is protected, please PR # Then merge the PR of experiment 4 (feat(api): add /version endpoint) gh pr merge --repo alice/myapp-ci --squash feat/version-endpoint
gh pr list --repo alice/myapp-ci --label "autorelease: pending" gh pr view --repo alice/myapp-ci "release-please--branches--main" --json title,body --jq .title
#6 chore(main): release 1.2.0 release-please--branches--main chore(main): release 1.2.0
Version 1.2.0 instead of 1.3.0? Since the starting point is 1.1.0, there is only one feat → MINOR. This is the value of a tool: it plays by the rules, not by your expectations.
gh pr merge 6 --repo alice/myapp-ci --squash git fetch ci --tags && git tag --sort=-v:refname | head -3 gh release view v1.2.0 --repo alice/myapp-ci --json tagName,name --jq '.tagName + " " + .name' git show v1.2.0:CHANGELOG.md | head -12
v1.2.0 v1.1.0 v1.0.0 v1.2.0 v1.2.0 # Changelog ## [1.2.0](https://github.com/alice/myapp-ci/compare/v1.1.0...v1.2.0) (2026-11-15) ### Features * **api:** add /version endpoint (#3) (7b1e2c4)
npx commitlint --from v1.0.0 --to HEAD, identify irregular commits in Lesson 1 history (if any), and understand why they were blocked at the PR stage.Case 1: Squash merge makes commitlint useless
Question:The team only verifies commits within the PR, but using squash merging and default messages coming from the PR header, there are a lot of "Update app.py"s on main.Method:Add PR title verification job and set it as a required check; the default squash message in the repository settings is changed to “Pull request title”.
Case 2: semantic-release repeatedly releases an existing version
Root cause:Checkout defaults to shallow cloning and no tags, and the tool thinks it has never been released.Fix:fetch-depth: 0;Assert at the beginning of the jobgit describe --tags --abbrev=0Success.
Case 3: Independent versions of each service in monorepo
Method:The release-please manifest isservices/api、services/workerConfigure packages separately, with labels in the shape ofapi-v1.4.0;Whether the commit affects a certain packagepathJudgment (same idea as M7’s change detection). Action output is prefixed by path, such assteps.rp.outputs['services/api--release_created']。
Common errors and solutions
release-please: "GitHub Actions is not permitted to create or approve pull requests."
Reason:Organization/repository settings prohibitedGITHUB_TOKENCreate a PR.Fix:Settings → Actions → General → Workflow permissions Check to allow creation of PRs, or use GitHub App tokens instead.
Publish PR always shows "Waiting for status to be reported"
Reason:PR byGITHUB_TOKENCreated, not triggeredpull_requestWorkflow (M1).Fix:token:Use GitHub App/Fine-grained PAT.
semantic-release: ENOGHTOKEN / EGITNOPERMISSION Cannot push to the Git repository.
Reason:The token is missing, or the token does not have permission to push a tag (a tag/branch protected by a ruleset).Fix:provideGITHUB_TOKEN/GH_TOKEN, homeworkpermissions: contents: write;If the ruleset protectsrefs/tags/v*, add the GitHub App used for publishing to the bypass list.
✖ subject may not be empty [subject-empty] ✖ type may not be empty [type-empty]
Reason:The message does not matchtype: subjectformat.Fix:Rewrite commit message (most recent:git commit --amend;earlier:git rebase -iwith reword), or rely on squash merge + canonical PR title.
1. List all committed titles since the last tag for manual judgment of the next version.
git log --format=%s "$(git describe --tags --abbrev=0)"..HEAD
2. Write a commit that contains the breaking change footnote.
git commit -m "feat(api): switch auth to OIDC" -m "BREAKING CHANGE: API keys are no longer accepted"
The team hopes to "release once every Thursday and merge and not release the rest of the time" while retaining the automatic version number and CHANGELOG. Which one should I choose between release-please and semantic-release? How to do it?
release-please is more appropriate: releasing a PR will automatically update the version and CHANGELOG with each merge, but it will only be tagged and released when the PR is merged and released on Thursday. Manual control points naturally exist. Semantic-release can also be implemented by running only when scheduled (schedule), but it will release the accumulated changes every time it runs, and lacks the "pre-release review CHANGELOG" link.
Verified instructional videos
Official documentation
- Conventional Commits 1.0.0
- Semantic Versioning 2.0.0
- commitlint
- release-please-action
- semantic-release documentation
Video storyboard (approximately 60 seconds)
Screen: Three pieces of commit information, fix, feat, feat!, light up the third, second, and first version numbers respectively.
Narrator: Conventional commits allow version numbers to be calculated.
Screen: There are constant commits and merges on main, and the version number and CHANGELOG of a released PR next to it change automatically.
Narrator: release-please maintains a release PR on an ongoing basis and you decide when to merge it.
Screen: Merge Release PR → Tag v1.3.0 → Release → Image Build.
Narrator: At the moment of merging, it is tagged, released, and the subsequent pipeline is triggered.
Module 7 · Monorepo path filtering and change detection
- Distinguish between two points
A..Bwith three pointsA...Bdiff, explains why PR change detection uses three points (starting from merge-base). - Use path filtering from the three major platforms (GitHub
paths、Azuretrigger.paths/ Build verification path filtering, GitLabrules:changes+compare_to) and their boundary cases. - Solve the problem of "path filtering skips the workflow and the required check is always pending"; do change detection at the job level and maintain an always-running summary check.
What: Two o’clock and three o’clock
| Writing method | git diffmeaning | used for |
|---|---|---|
git diff A BorA..B | Directly compare two snapshots: A has and B does not have, B has and A does not count. | push event:before..after |
git diff A...B | compare merge-base(A,B)with B:Only look at the changes on side B | PR:base...head, ignore new commits made after main after you forked |
Note git log A..B(B has commits that A does not) vs.git diff A..B(The difference between two snapshots) has different meanings, which is a common point of confusion. GitHub ComputepathsWhen filtering, use two points for push and three points for PR.
Why: What happens if change detection is wrong?
- Missed detection (danger): changed
libs/common, depends on itservices/apiNot tested; or shallow cloning causes diff to fail and the script treats empty results as "no changes". - Multiple checks (waste): Use two-point diff to compare PR, other people's changes on main are also included, and all services are rebuilt.
How: Path filtering on the three major platforms
| Platform | Writing method | boundary case |
|---|---|---|
| GitHub Actions | on.push.paths / paths-ignore;on.pull_request.paths | When pushing more than 1,000 commits, or generating a diff times outalways run;When the diff exceeds 3,000 files and the matching files are not among the first 3,000Not running;The check corresponding to the skipped workflow remainsPending, will block the PR requesting the check |
| Azure Pipelines | trigger: paths: include/exclude(CI); PR for Azure Repos atBranch Strategy → Build Verification → Path FilteringMedium settings | Paths are case sensitive; YAMLpr: pathsOnly valid for GitHub/Bitbucket repositories |
| GitLab CI | rules: - changes: paths: [...], can be addedcompare_to: refs/heads/main | The branch pipeline compares the before and after of this push; when there is a new branch or there is no push event (timing, API trigger)changesAlways true; MR pipeline compared to target branch |
Job-level change detection (recommended)
workflow levelpathsSimple, but poorly matched to required checks. A more robust structure: workflowalways run; first jobchangesCalculate which directories have changed (write it yourselfgit diff --name-only, or usedorny/paths-filter); each service operationif:depends on its output; the lastci-okThe job summarizes all results (skips are counted as passes, failures are counted as failures), and the rule set only requiresci-ok。
When: When to use a dedicated build system
Directory-level filtering is suitable for monorepo with simple dependencies between services. When the dependency graph is complex (shared libraries, multi-language), use tools such as Nx / Turborepo / Bazel / Pants to calculate the "affected projects". They also rely on the base and head given by Git (such as Nx'snx affected --base=... --head=...), so the depth problem of the M3 still exists.
git diff --name-only HEAD~1This is the change" - when there are multiple PR commits, only the last one is visible; in shallow clonesHEAD~1Does not exist; merge ref'sHEAD~1is main. ② "Path filtering allows necessary checks to pass automatically" - The skipped workflow checks in GitHub remain Pending. ③ "Third-party change detection Action is used@v47Very safe” – March 2025tj-actions/changed-filesAfter being compromised, the attacker redirected the existing version tag to a malicious commit and printed the secret in the runner log (CVE-2025-30066); fixing it to the complete commit SHA can prevent the tag from being moved.Two points vs three points
Workflow structure for job-level change detection
Interactive: Change Detection Simulator
Check the changed files on the feature branch, and select the main changes after you forked, compare the results of the two-point and three-point diffs and the service to be built.libs/commonDepends on both api and worker.
Core commands
| command | function |
|---|---|
git diff --name-only origin/main...HEAD | PR change document (three points) |
git diff --name-only "$BEFORE" "$AFTER" | push change files (two points) |
git diff --name-only base...head -- services/api libs/common | Only view the specified path |
git diff --dirstat=files,0 base...head | Statistical change ratio by directory |
git diff --name-only base...head | cut -d/ -f1-2 | sort -u | Extract the changed top-level service directory |
git log --format= --name-only base..head | sort -u | Summarize changed files by commit (the results may be different from diff: files that have been changed and then changed back will also appear) |
GitHub Actions: Job-level detection + summary inspection
name: monorepo-ci
on:
pull_request:
push:
branches: [main]
permissions:
contents: read
jobs:
changes:
runs-on: ubuntu-latest
outputs:
api: ${{ steps.f.outputs.api }}
worker: ${{ steps.f.outputs.worker }}
steps:
- uses: actions/checkout@v7
with:
fetch-depth: 0
filter: blob:none # Commit the picture completely and download the content on demand (M3)
- id: f
env:
BASE: ${{ github.event.pull_request.base.sha || github.event.before }}
HEAD: ${{ github.event.pull_request.head.sha || github.sha }}
run: |
set -euo pipefail
if [ -z "$BASE" ] || [ "$BASE" = "00000000000000000000000000000000000000" ] || ! git cat-file -e "$BASE^{commit}" 2>/dev/null; then
echo "base unknown (new branch / force push) -> build everything"
echo "api=true" >> "$GITHUB_OUTPUT"; echo "worker=true" >> "$GITHUB_OUTPUT"; exit 0
fi
if [ "$GITHUB_EVENT_NAME" = "pull_request" ]; then RANGE="$BASE...$HEAD"; else RANGE="$BASE..$HEAD"; fi
files=$(git diff --name-only "$RANGE")
echo "$files"
has() { echo "$files" | grep -Eq "$1" && echo true || echo false; }
echo "api=$(has '^(services/api|libs/common)/')" >> "$GITHUB_OUTPUT"
echo "worker=$(has '^(services/worker|libs/common)/')" >> "$GITHUB_OUTPUT"
build-api:
needs: changes
if: needs.changes.outputs.api == 'true'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
with:
sparse-checkout: |
services/api
libs/common
- run: echo "build services/api"
build-worker:
needs: changes
if: needs.changes.outputs.worker == 'true'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
with:
sparse-checkout: |
services/worker
libs/common
- run: echo "build services/worker"
ci-ok:
needs: [changes, build-api, build-worker]
if: always()
runs-on: ubuntu-latest
steps:
- run: |
echo '${{ toJSON(needs) }}'
if ${{ contains(needs.*.result, 'failure') || contains(needs.*.result, 'cancelled') }}; then exit 1; fi
If usingdorny/paths-filter@v4, also pin it (and all third-party actions) to the full commit SHA, e.g.uses: dorny/paths-filter@<40-bit SHA> # v4.0.3, and then hand it over to Dependabot for update.
Azure Pipelines and GitLab CI
# services/api/azure-pipelines.yml (one pipeline per service)
trigger:
branches:
include: [main]
paths:
include: [services/api, libs/common]
exclude: [services/api/docs]
# PR for Azure Repos: Branch Strategy → Build Validation → Fill in path filtering for this pipeline
# /services/api/*; /libs/common/*
steps:
- checkout: self
sparseCheckoutDirectories: services/api libs/common
- script: echo build api
# .gitlab-ci.yml
build-api:
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
changes:
paths: [services/api/**/*, libs/common/**/*]
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
changes:
paths: [services/api/**/*, libs/common/**/*]
compare_to: refs/heads/main # Compare with main; if not written, compare before and after this push
script:
- echo build api
How to verify:Only change the docs in the PR and confirm that both build jobs are skipped andci-okPassed.Common mistakes:GitLab compare_toAn error will be reported when the pointed ref does not exist in the job; the Azure path starts with/The beginning is written in the build verification, but not in YAML.
Lab 7: Add a second service to myapp and build only the changes (~6 minutes)
cd ~/git-lab/myapp && git switch main && git pull ci main git switch -c chore/monorepo-layout mkdir -p services/api services/worker libs/common git mv app.py services/api/app.py printf 'import time\nwhile True:\n time.sleep(60)\n' > services/worker/worker.py printf 'REDIS_HOST = "redis"\n' > libs/common/settings.py git add -A && git commit -m "refactor: split into services/api, services/worker and libs/common"
git switch -c feat/worker-retry echo '# retry' >> services/worker/worker.py && git commit -am "feat(worker): add retry" git diff --name-only chore/monorepo-layout...HEAD git diff --name-only chore/monorepo-layout...HEAD | cut -d/ -f1-2 | sort -u
services/worker/worker.py services/worker
feat/worker-retryOpen PR (base optionchore/monorepo-layout)。
git push -u ci chore/monorepo-layout feat/worker-retry gh pr create --repo alice/myapp-ci --base chore/monorepo-layout --head feat/worker-retry --fill gh pr checks --repo alice/myapp-ci --watch
changes pass 8s build-api skipping build-worker pass 12s ci-ok pass 3s
changeshomeworkfetch-depth: 0Delete it and push it again, observegit diffReport an error or roll back to the "all build" branch; then change back.Case 1: tj-actions/changed-files supply chain attack (2025-03)
After:The attacker obtained the write permission of the Action repository and changed the version tags from v1 to v45.0.7 to point to a malicious commit on 2025-03-14/15 (at that time, more than 23,000 repositories used this Action, and the fixed version was 46.0.1). The malicious code read the secrets in the runner process memory and printed them to the workflow log; the logs of the public repository are readable by anyone (CVE-2025-30066).Impact:Used extensively@v35、@v44Wait for the repository referenced by the tag to reveal secrets.Lessons:Third-party Action pinned toComplete SHA;WorkflowpermissionsMinimize; press M5 when an incident occurs to rotate all potentially exposed secrets; how many lines can be usedgit diffSolve things without introducing dependencies.
Case 2: Required check stuck in Pending
Question:Document-only PR can never be merged because the workflow levelpathsskippedbuildworkflow, whilebuildIt is a required inspection.Fix:Change to job-level detection +ci-okRollup jobs; ruleset only requiresci-ok。
Case 3: Shared library changes did not trigger downstream testing
Question:The filtering rules only writeservices/api/**。Fix:Write the dependent library directory into the filtering rules of each service, or introduce the Nx/Bazel dependency graph; for.github/, all build configuration changes in the root directory will be fully built.
Common errors and solutions
fatal: bad object 0000000000000000000000000000000000000000
Reason:During the first push of the new branchgithub.event.beforeIt's all zeros.Fix:When all zeros are detected, compare with the merge-base of the default branch, or build directly.
fatal: bad object 3f9c… (the before SHA of the push event does not exist)
Reason:After the forced push, the old before commit is no longer in the new history, and shallow clone/ordinary fetch cannot get it.Fix:git cat-file -e "$BASE^{commit}"Fallback to full build on failure.
Expected — Waiting for status to be reported (workflow skipped by path filtering)
Reason:Skipped workflow checks remain Pending.Fix:See "Principles" for job-level testing solutions.
GitLab: First pipeline of each new branch runs all jobs
Reason:There is no "last push" for new branches,rules:changesAlways true.Fix:Setup for branch pipelinecompare_to: refs/heads/main, or just use changes rules in the MR pipeline.
1. List the top-level service directories (services/* level one) that have been modified by the current branch relative to origin/main.
git diff --name-only origin/main...HEAD | grep '^services/' | cut -d/ -f1-2 | sort -u
2. Determine whether libs/common has been changed in the PR and indicate it with an exit code.
git diff --quiet origin/main...HEAD -- libs/common; echo $? # 1 = Changes, 0 = No changes
A monorepo has 40 services, the PR pipeline is filtered with workflow-level paths, one workflow per service, and the ruleset requires all 40 checks. What problems could arise? How to refactor?
Any PR only changes a few services, the rest of the workflow is skipped, the corresponding check is always pending, and the PR cannot be merged; even if it is not set as required, there is no way to ensure that all affected services are run. Refactoring: a workflow,changesThe job calculates the affected services (including shared library dependencies) using a three-point diff (full depth or blob:none), using a matrixstrategy.matrixGenerate jobs only for affected services, the lastci-okSummary, the rule set only requiresci-ok; Third-party Action fixed SHA.
Verified instructional videos
No verified video specifically talking about CI path filtering and monorepo change detection was found. Please refer to the official documentation and the storyboard below.
Official documentation
- GitHub: Workflow syntax (paths filtering rules and restrictions)
- Azure Pipelines: Azure Repos Git (path filtering, build verification)
- GitLab:rules:changes
- dorny/paths-filter
- GitHub Advisory GHSA-mrrh-fwg8-r2c3 / CVE-2025-30066(tj-actions/changed-files)
Video storyboard (approximately 60 seconds)
Screen: monorepo directory tree, PR only lights services/api.
Narrator: The goal of change detection is to only build affected services.
Screen: Two-point diff marks the worker changes on main in red; three-point diff only keeps the feature side.
Narrator: PR requires three points of diff, starting from the common ancestor.
Image: Multiple build jobs merge into a ci-ok check, the rule set only requires it.
Narrator: Use a summary check that is always run to avoid stuck merges with skipped checks.
Module 8 · Summary, Self-Assessment and Cleanup of the First Five Hours
- Use a diagram to illustrate how the knowledge from Lessons 1–5 forms a link from commit to release.
- Quickly locate errors based on the errors in the CI log: shallow clone missing history, detached HEAD, credentials/permissions, submodule not pulled, LFS pointer file, safe.directory, signature and secret interception.
- Clean up the tokens, keys, rulesets, and test repositories created in this lesson.
Review of the first five hours
| class | core concepts | Reflection in CI/CD |
|---|---|---|
| Lesson 1 Core Fundamentals | blob/tree/commit/ref; staging area;git log -S | What shallow cloning lacks is the commit object; the signature covers the tree and parent; the secrets in the scanning history are |
| Lesson 2 Branching and Collaboration | merge vs rebase; merge-base; conflict | PR’s merge ref; three-point diff; needs to be re-signed after rebase |
| Lesson 3 Azure Repos and GitHub | GCM Authentication, Rule Sets, Branching Strategies, CODEOWNERS | Required status checks, required signatures, push protection, build verification |
| Lesson 4 CodeCommit and GitLab | IAM conditions, protected branches, push rules, mirrors | GitLab push rules (reject unsigned, prohibited files), MR pipeline |
| Lesson 5 (this lesson) | Hooks, checkout depth, signatures, confidentiality, automatic release, change detection | Turn the "rules" of the first four lessons into "checks" that are performed on every push |
Seven categories of Git failures in CI
| Category | Typical error reports | One sentence fix |
|---|---|---|
| Shallow clone lacks history/tags | No names found、no merge base、unknown revision | fetch-depth: 0(+ filter: blob:none) or deepen |
| detached HEAD | fatal: You are not currently on a branch.、git rev-parse --abbrev-ref HEAD output HEAD | Use platform variables to get the branch name (GITHUB_HEAD_REF/GITHUB_REF_NAME、Build.SourceBranchName、CI_COMMIT_REF_NAME); for pushgit push origin HEAD:refs/heads/x |
| Credentials and permissions | 403、Permission to … denied to github-actions[bot]、could not read Username | Homeworkpermissions: contents: write;persist-credentials/persistCredentials;Azure build service account "participate" permission;GitLab job token access list |
| submodule not pulled | The directory is empty,fatal: No url found for submodule path | submodules: recursive;Private submodules require a token with permission (same organization/project or separate credentials) |
| LFS pointer file | The file content isversion https://git-lfs.github.com/spec/v1, the test reads garbled characters | lfs: true(GitHub/Azure) or after installing git-lfsgit lfs pull;The GitLab runner pulls LFS by default (git-lfs is required in the image) |
| security directory | fatal: detected dubious ownership in repository at '/__w/…' | Container in progressgit config --global --add safe.directory "$GITHUB_WORKSPACE" |
| Platform interception | GH013Rule set violations, push protection, unsigned | Press M4/M5 to fix commit instead of bypass |
git rev-parse --is-shallow-repository; git status -sb; git log --oneline -3 --decorate——Whether it is shallow cloned, whether it is detached, and what commits and references are in hand. plusGIT_TRACE=1 GIT_CURL_VERBOSE=1Look at the authentication (note that tokens may appear in the log, delete the log when used).Complete link from commit to publication
Interactive: CI Log Diagnosticator
Read the log snippets and select the root cause. If you answer correctly, the repair method will be displayed.
Cleanup command
| object | command |
|---|---|
| test repository | gh repo delete alice/myapp-ci --yes(Requireddelete_repo Scope:gh auth refresh -s delete_repo) |
| SSH signing key | gh ssh-key list → gh ssh-key delete <ID>;localrm ~/.ssh/id_ed25519_signing* |
| GPG public key (if added) | gh gpg-key list → gh gpg-key delete <KEYID> |
| release-please token | GitHub → Settings → Developer settings → Undo fine-grained PAT / Uninstall GitHub App |
| Git global signature configuration (if you don’t want to keep it) | git config --global --unset commit.gpgSign; git config --global --unset tag.gpgSign; git config --global --unset gpg.format |
| pre-commit | pre-commit uninstall -t pre-commit -t commit-msg; pre-commit clean |
| Local experiment directory | rm -rf ~/git-lab/shallow(myapp is reserved for Lessons 6 and 7) |
Universal diagnostic step in CI (can be placed as the first step in any pipeline)
echo "::group::git diagnostics" git --version git rev-parse --is-shallow-repository git status -sb | head -1 git log --oneline --decorate -3 git remote -v | sed -E 's#://[^@]+@#://***@#' git config --list --show-origin | grep -E 'extraheader|credential|safe.directory|lfs' | sed -E 's/(AUTHORIZATION: )[^ ]+.*/\1***/I' git tag --sort=-creatordate | head -3 echo "::endgroup::"
::group::Is the log grouping syntax for GitHub Actions; used by Azure##[group], used by GitLabsection_start. Be careful not to print the token.
Lab 8: Self-test and cleanup (about 5 minutes)
git rev-parse --is-shallow-repository git diff --name-only main...HEAD | cut -d/ -f1-2 | sort -u git log --format='%h %G? %s' -5 gitleaks git --redact --log-opts="main..HEAD" .
myapp-ciRepository and signature configuration.gh ssh-key list gh auth status ls ~/git-lab
Case 1: All Git commands report dubious ownership after migrating to container jobs
Question:The job is instead run in a container, the workspace is created by the runner user, root is inside the container, and the security check since Git 2.35.2 denies the operation.Fix:Beginning of stepsgit config --global --add safe.directory "$GITHUB_WORKSPACE"(actions/checkout is handled in its own step, but may still be required by other steps/tools).
Case 2: Test read into LFS pointer causing "picture corruption"
Question:The model file is stored in LFS, and the CI test reports a file format error.Diagnosis:head -c 120 model.bin show version https://git-lfs.github.com/spec/v1。Fix:lfs: true, and cache.git/lfs;Be aware of LFS bandwidth quotas.
Case 3: Private submodule fails to pull in PR
Question:GITHUB_TOKENOnly has permissions for the current repository.Fix:Configure a read-only deployment key or GitHub App token for the submodule repository, pass it in checkouttoken/ssh-keyInput provided; Azure requires that the build service account has read access to the submodule repository and that the submodule URL is in the same organization.
Interactive troubleshooting tree: Git fails in CI
Start with the phenomenon in the log, answer questions step by step, and get diagnosis and repair commands.
1. CI is in detached HEAD and wants to push the generated commit to the branch bot/update.
git push origin HEAD:refs/heads/bot/update
2. Determine whether model.bin in the repository is just an LFS pointer.
git lfs ls-files | grep model.bin; head -c 60 model.bin
A job works fine on the GitHub hosted runner, but after switching to a self-hosted runnergit describeA very old version number was output, and the build product version was incorrect. Possible reasons?
Self-hosted runner reuses workspace: old tags stay local (remote deleted or moved tags are not automatically deleted), orclean: falseResulting in residue; there may also be local tags with the same name but pointing to different commits (git fetch --tagsExisting tags are not overwritten by default). Fix:git fetch --prune --prune-tags --force --tags, or clean the workspace each time; the version number calculation job uses the clean workspace.
Verified instructional videos (for review)
Official documentation
Video storyboard (approximately 45 seconds)
Screen: Links composed of six grids: encoding, commit, push, PR pipeline, merge, and release.
Narrator: The content of the first five hours covers every link of this link.
Screen: No names found, detached HEAD, 403, and LFS pointers pop up in the CI log in sequence, and a line of repair pops up next to each.
Narrator: When encountering Git problems in CI, first check whether it is shallow cloned, whether it is detached, and what references are in hand.
Command cheat sheet
git config core.hooksPath .githooks git hook run pre-commit # 2.36+ git config set hook.lint.command "ruff check" # 2.54+ configuration hook git config set --append hook.lint.event pre-commit pre-commit install --install-hooks # Read default_install_hook_types pre-commit run --all-files --show-diff-on-failure pre-commit run gitleaks --files app.py pre-commit autoupdate --freeze SKIP=ruff-check git commit -m "..." git commit --no-verify # Bypass client hooks (CI cover)
git rev-parse --is-shallow-repository cat .git/shallow git fetch --deepen=50 / --depth=200 / --shallow-since=2026-10-01 git fetch --unshallow --tags git fetch --no-tags --depth=50 origin +refs/heads/main:refs/remotes/origin/main git clone --filter=blob:none URL # Complete history, get content on demand git sparse-checkout set services/api libs/common git merge-base origin/main HEAD # exit code 1 = no common ancestor
| Platform | Default | full history |
|---|---|---|
GitHub actions/checkout@v7 | fetch-depth: 1,fetch-tags: false | fetch-depth: 0 |
Azure - checkout: self | New pipeline after sprint 209 (2022-09): Shallow acquisition depth 1 for some organizations,fetchTags false | fetchDepth: 0 |
| GitLab | new projectGIT_DEPTH 20 | GIT_DEPTH: 0 |
git config --global gpg.format ssh git config --global user.signingkey ~/.ssh/id_ed25519_signing.pub git config --global gpg.ssh.allowedSignersFile ~/.config/git/allowed_signers git config --global commit.gpgSign true; git config --global tag.gpgSign true git commit -S -m "feat: ..."; git tag -s v1.3.0 -m v1.3.0 git verify-commit HEAD; git verify-tag v1.3.0 git log --format='%h %G? %GS %s' -10 # G/B/U/X/Y/R/E/N git config gpg.format x509; git config gpg.x509.program gitsign gitsign verify --certificate-identity=ME --certificate-oidc-issuer=ISSUER HEAD
gitleaks git -v --redact # Current branch history gitleaks git --log-opts="--all" # Quote all gitleaks git --log-opts="origin/main..HEAD" # PR scope gitleaks git --pre-commit --staged --redact #Staging area gitleaks dir -v . gitleaks git --report-path base.json; gitleaks git --baseline-path base.json trufflehog git file://. --results=verified,unknown --fail # Exit code 183 when found git log -S 'SECRET' --all --oneline # Azure Repos push protection false positive bypass: add skip-secret-scanning:true to the commit information
feat(api): add /version #MINOR fix(api): handle timeout # PATCH feat(api)!: drop /v1 # MAJOR (or footnote BREAKING CHANGE: ...) npx commitlint --from BASE --to HEAD --verbose echo "$TITLE" | npx commitlint git describe --tags --abbrev=0 git log --format=%s "$(git describe --tags --abbrev=0)"..HEAD npx semantic-release --dry-run --no-ci # release-please: googleapis/release-please-action@v5 (release-type: python)
git diff --name-only origin/main...HEAD # PR: three points git diff --name-only "$BEFORE" "$AFTER" # push: two points git diff --quiet origin/main...HEAD -- libs/common; echo $? git diff --name-only base...head | cut -d/ -f1-2 | sort -u # GitHub: on.pull_request.paths; Azure: trigger.paths + build verification path filtering; GitLab: rules:changes + compare_to
git status -sb; git log --oneline --decorate -3 git push origin HEAD:refs/heads/bot/update # detached HEAD push git config --global --add safe.directory "$PWD" # dubious ownership git submodule update --init --recursive git lfs install && git lfs pull # LFS pointer git fetch --prune --prune-tags --force --tags # Self-hosted runner residual tags GIT_TRACE=1 GIT_CURL_VERBOSE=1 git fetch # Note the token in the log
Comprehensive experiment + final exam
You are a platform engineer on the myapp team. The security audit puts forward four requirements: ① Each commit is checked locally for format and confidentiality; ② Each commit on main must have a verified signature; ③ No new secrets can enter main and are scanned throughout the history in CI; ④ The version number and CHANGELOG are automatically generated from agreed-upon commits, and they are automatically tagged and built after the PR is merged and released. All checks rolled into one required checkci-ok。
cd ~/git-lab/myapp && git switch main && git pull ci main git switch -c chore/quality-gates # 1) M2’s .pre-commit-config.yaml (including gitleaks and conventional-pre-commit) # 2) M5’s .gitleaks.toml and .gitleaksignore pre-commit install --install-hooks pre-commit run --all-files # 3) M4 SSH signature configuration (global) git config --global gpg.format ssh git config --global user.signingkey ~/.ssh/id_ed25519_signing.pub git config --global commit.gpgSign true # 4) Team allowed_signers (used for local verification in CI) mkdir -p .github && echo "alice@example.com namespaces=\"git\" $(cat ~/.ssh/id_ed25519_signing.pub)" > .github/allowed_signers
name: ci
on:
pull_request:
push:
branches: [main]
permissions:
contents: read
concurrency:
group: ci-${{ github.ref }}
cancel-in-progress: true
jobs:
pre-commit:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7
with: { python-version: "3.13" }
- uses: actions/cache@v6
with:
path: ~/.cache/pre-commit
key: pre-commit-${{ runner.os }}-${{ hashFiles('.pre-commit-config.yaml') }}
- run: pipx install pre-commit && pre-commit run --all-files --show-diff-on-failure
secrets:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
with: { fetch-depth: 0 } # Full history scan
- name: gitleaks (binary, MIT)
run: |
GL=8.30.1
curl -sSL "https://github.com/gitleaks/gitleaks/releases/download/v${GL}/gitleaks_${GL}_linux_x64.tar.gz" | tar -xz gitleaks
./gitleaks git --redact --log-opts="--all" --config .gitleaks.toml .
commits:
if: github.event_name == 'pull_request'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
with: { fetch-depth: 0 }
- uses: actions/setup-node@v7
with: { node-version: 24 }
- run: npm ci
- name: Conventional commits + PR title
env:
BASE: ${{ github.event.pull_request.base.sha }}
HEAD: ${{ github.event.pull_request.head.sha }}
TITLE: ${{ github.event.pull_request.title }}
run: |
npx commitlint --from "$BASE" --to "$HEAD" --verbose
echo "$TITLE" | npx commitlint
- name: All commits signed by allowed signers
env:
BASE: ${{ github.event.pull_request.base.sha }}
HEAD: ${{ github.event.pull_request.head.sha }}
run: |
git config gpg.ssh.allowedSignersFile .github/allowed_signers
bad=$(git log --format='%H %G?' "$BASE..$HEAD" | awk '$2!="G"{print $1}')
[ -z "$bad" ] || { echo "Unsigned/unknown signer:"; echo "$bad"; exit 1; }
ci-ok:
needs: [pre-commit, secrets, commits]
if: always()
runs-on: ubuntu-latest
steps:
- run: |
if ${{ contains(needs.*.result, 'failure') || contains(needs.*.result, 'cancelled') }}; then exit 1; fi
echo "all gates passed"
put all in productionuses:Pinned to full commit SHA and updated with Dependabot. Signature checking uses.github/allowed_signers- PRs to modify this file should be approved by CODEOWNERS (Security Team) (Lesson 3).
googleapis/release-please-action@v5 + publishHomework is inrelease_createdWhen building the imagemyapp:${tag}). fortokenConfigure the GitHub App token so that publishing a PR will also runci。ci-ok), "Require signed commits"; tag rule set protectionrefs/tags/v*Deletion and updates are prohibited, the GitHub App used for publishing is added to the bypass list; Secret Protection push protection is enabled for the repository (private repositories require corresponding products).git add -A && git commit -m "ci: add quality gates (pre-commit, secrets, signed conventional commits)" git log --format='%h %G? %s' -1 git push -u ci chore/quality-gates && gh pr create --repo alice/myapp-ci --fill gh pr checks --repo alice/myapp-ci --watch
a1b2c3d G ci: add quality gates (pre-commit, secrets, signed conventional commits) pre-commit pass 41s secrets pass 9s commits pass 22s ci-ok pass 2s
--no-verifyCommit a malformed file →pre-commitThe job failed; ② CommitFAKE_SECRET=fake-0123456789abcdef→ Local hook interception,--no-verifyaftersecretsThe job failed; ③git -c commit.gpgSign=false commit → commitsJob and rule set rejected; ④ PR title written "update" →commitsJob failed. Use after each verificationgit reset --hard HEAD~1 with git push --force-with-leaseRestore branch.trigger:
branches: { include: [main] }
# PR for Azure Repos: Set this pipeline to "Build Verification" in the branch policy (required)
pool: { vmImage: ubuntu-latest }
jobs:
- job: gates
steps:
- checkout: self
fetchDepth: 0
fetchTags: true
- task: UsePythonVersion@0
inputs: { versionSpec: '3.13' }
- script: pipx install pre-commit && pre-commit run --all-files --show-diff-on-failure
displayName: pre-commit
- script: |
GL=8.30.1
curl -sSL "https://github.com/gitleaks/gitleaks/releases/download/v${GL}/gitleaks_${GL}_linux_x64.tar.gz" | tar -xz gitleaks
./gitleaks git --redact --log-opts="--all" --config .gitleaks.toml .
displayName: gitleaks
- script: |
git config gpg.ssh.allowedSignersFile .github/allowed_signers
TARGET="origin/${SYSTEM_PULLREQUEST_TARGETBRANCHNAME:-main}"
bad=$(git log --format='%H %G?' "$TARGET..HEAD^2" | awk '$2!="G"{print $1}')
[ -z "$bad" ] || { echo "##vso[task.logissue type=error]Unsigned commits: $bad"; exit 1; }
displayName: signed commits
condition: eq(variables['Build.Reason'], 'PullRequest')
# Release: Run semantic-release on main (see M6). The build service account needs to have "participate" and "create tag" permissions on the repository
PR build checkout for Azure Reposrefs/pull/ID/merge,HEAD^2Is the commit of the PR source branch;SYSTEM_PULLREQUEST_TARGETBRANCHNAMEby predefined variablesSystem.PullRequest.TargetBranchNameMapping from (Azure Repos may bringrefs/heads/prefix, which needs to be processed according to the actual value). Azure Repos does not have a built-in "require signature" policy as of the verification date, so this script check is the only enforcement method.
workflow:
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
- if: $CI_COMMIT_BRANCH && $CI_OPEN_MERGE_REQUESTS
when: never
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
variables:
GIT_DEPTH: 0
stages: [check, release]
pre-commit:
stage: check
image: python:3.13
variables: { PRE_COMMIT_HOME: "$CI_PROJECT_DIR/.cache/pre-commit" }
cache: { key: { files: [.pre-commit-config.yaml] }, paths: [.cache/pre-commit] }
script: [pip install pre-commit, pre-commit run --all-files --show-diff-on-failure]
secrets:
stage: check
image: { name: zricethezav/gitleaks:v8.30.1, entrypoint: [""] }
script: [gitleaks git --redact --log-opts="--all" --config .gitleaks.toml .]
commitlint:
stage: check
image: node:24
rules: [{ if: $CI_PIPELINE_SOURCE == "merge_request_event" }]
script:
-npmci
- npx commitlint --from "$CI_MERGE_REQUEST_DIFF_BASE_SHA" --to "$CI_COMMIT_SHA" --verbose
release:
stage: release
image: node:24
rules: [{ if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH }]
script:
- npm install --no-save semantic-release@25 @semantic-release/gitlab
- npx semantic-release
# Signature: GitLab push rule "Reject unsigned commits" (Premium/Ultimate); Confidential: Ultimate's confidential push protection
The official image name and label of gitleaks are subject to Docker Hub / GitHub Packages;CI_MERGE_REQUEST_DIFF_BASE_SHAIt is the merge-base of MR and has the same semantics as three-point diff.
Open-ended self-assessment (6 questions)
1. Why is it said that "pre-commit is experience, and CI must be checked to ensure"? Please name at least three ways to bypass local hooks.
git commit --no-verify; not executedpre-commit install(Hooks are not installed with clones); edit/suggest changes on the platform webpage; use other Git clients or commit in CI/scripts;SKIP=environment variables. Therefore it must be run with the same configuration in CI as a required check, and then push protection and rulesets are used on the platform side.
2. The same repository, why on GitLabgit describeMore "often successful" than on GitHub?
GitLab new project defaultGIT_DEPTH=20, the tag is still in shallow history when it is not far from HEAD; GitHubactions/checkoutThe default depth is 1 and no labels are taken, which almost always fails. Neither is reliable - jobs requiring a version number should explicitlyfetch-depth: 0 / GIT_DEPTH: 0。
3. In a 2 GB repository, the release job requires history. How would you choose between "correct" and "fast"?
fetch-depth: 0 + filter: blob:none: The commit and tree are complete, describe, merge-base, and diff --name-only are all correct, and the blob is only downloaded for checkout; avoid running this jobgit log -p/blame. The remaining jobs remain at depth 1 + sparse checkout.
4. The organization requires that "all commits on main must be signed" but uses release-please and Dependabot. How compatible?
The commits generated by merging Dependabot and the web page are signed by GitHub; release-please creates commits and PRs through the GitHub API, and the commits are verified by the GitHub signature; the merged release PR uses squash (GitHub web page/API merge, platform signature). Need robot directgit pushThe scenario is changed to API commit or PR process.
5. The confidential scan found no problems within the PR scope, but the scheduled full scan reported a commit two years ago. Why is this happening? How to deal with it?
This format was recognized only after the rule base was updated, or it was not scanned at that time. Follow the M5 process: identify and rotate first (it might still be valid even two years ago, TruffleHog can verify), assess for abuse, then decide to join the baseline or rewrite history.
6. Design a monorepo change detection that requires "it is better to build more than to miss a build".
Job-level detection; complete commit graph (blob:none) + three-point diff; shared library and root directory build configuration changes trigger full volume; base is unavailable (new branch, forced push, all-zero SHA), full volume when Git command fails; summaryci-okAs the only required check; Action fixes the SHA.
Sources and imprints
Source table
| Topic | Source | Verify content | Date |
|---|---|---|---|
| actions/checkout | README / Releases | v7.0.1 (2026-07-20), v7.0.0 (2026-06-18, preventing pull_request_target/workflow_run from checking out fork PR), v6 credentials written to $RUNNER_TEMP, v5 node24;fetch-depth: 1、fetch-tags: false、filter、sparse-checkout(cone defaults to true),persist-credentials: true、submodules/lfs: false | 2026-11-15 |
| Azure Pipelines checkout | steps.checkout、Options for Git repositories | New pipeline sections organized after sprint 209 (2022-09) have a default shallow acquisition depth of 1;fetchDepth: 0Prioritize UI; new pipelinefetchTagsDefault false;fetchFilter(blob:none / tree:0);sparseCheckoutDirectories/Patterns(Agent 3.253.0/4.253.0+, Git 2.25+) | 2026-11-15 (page updated on 2026-11-02) |
| GitLab shallow clone | Pipeline settings | new projectGIT_DEPTH20, max 1000, 0/null = off;GIT_DEPTH/GIT_STRATEGYVariables can be overridden | 2026-11-15 |
| GitHub paths filter | Workflow syntax | Two points for push, three points for PR; >1,000 commits always run; >3,000 file limit; skipped workflow checks remain Pending | 2026-11-15 |
| Git hook | githooks、git hook、Git RelNotes 2.54/2.55 | 2.54 Configurable hooks (multiple same events can be configured centrally), 2.55 can be parallelized;git hook run/list | 2026-11-15 |
| pre-commit | pre-commit.com、GitHub Releases | pre-commit 4.7.0 (2026-10-13, Python ≥ 3.11); pre-commit-hooks v6.0.0 (2025-08-09); ruff-pre-commit v0.17.5 (hooksruff-check/ruff-format);conventional-pre-commit v4.5.0 | 2026-11-15 |
| signature | GitHub signature verification、GitLab Signed commits、gitsign | GPG/SSH/S/MIME; SSH requires Git 2.34; vigilant mode; persistent verification; web-flow signing; GitLab supports SSH/GPG/X.509, rejects unsigned commits as Premium/Ultimate; gitsign v0.18.0 (2026-10-20), GitHub shows Unverified | 2026-11-15 |
| Confidential scanning | gitleaks、gitleaks-action、TruffleHog | gitleaks 8.30.1 (2026-03-21, fully functional/security patch only), hook entrygitleaks git --pre-commit --redact --staged --verbose;gitleaks-action v3 (node24, organization license required); TruffleHog 3.99.9 (2026-11-12),--results、--failExit code 183 | 2026-11-15 |
| Push protection | GitHub push protection、GHAzDO secret scanning、GitLab secret push protection | Secret Protection is required at the GitHub repository level, enabled by default at the user level (public repository), bypass reasons and warnings; Azure push protection andskip-secret-scanning:true;GitLab Ultimate | 2026-11-15 |
| Automatic publishing | release-please-action、semantic-release、commitlint | release-please-action v5.0.0(2026-04-22,node24)、release-please v17.11.2;semantic-release v25.0.9(Node ^22.14.0 || ≥24.10.0);commitlint 21.2.4(Node ≥ 22.12.0) | 2026-11-15 |
| supply chain events | GHSA-mrrh-fwg8-r2c3 | tj-actions/changed-files 2025-03-14/15 tag changed to point to malicious commit (CVE-2025-30066, fix 46.0.1) | 2026-11-15 |
| Other Action versions | GitHub Releases API | actions/setup-python v7.1.0、actions/setup-node v7.1.0、actions/cache v6.1.0、dorny/paths-filter v4.0.3、tj-actions/changed-files v47.0.6 | 2026-11-15 |
Video verification instructions
All videos listed in this lesson are available through the YouTube oEmbed interface (https://www.youtube.com/oembed?url=…&format=json) Verified title and channel:
- R8_veQiYBjI — GitHub Actions Tutorial - Basic Concepts and CI/CD Pipeline with Docker(TechWorld with Nana)
- qP8kir2GUgo — GitLab CI CD Tutorial for Beginners [Crash Course](TechWorld with Nana)
- EvpZkdkp-v0 — How to use Git Hooks(Kie Codes)
- xhg1dJHLqSM — Boost Your Python Code Quality: Pre-commit Tutorial (UV & Ruff)(Timnology)
- lG90LZotrpo — Git Internals by John Britton of GitHub - CS50 Tech Talk(CS50)
- uhy_ojFqLg0 — Simplify signing Git commits and tags with SSH keys [Workshop] - Git Merge 2022(GitHub)
- 6hu3cbBhHqQ — git: the several ways to "--sign" (intermediate) anthony explains #504(anthonywritescode)
- hux-W8PAxYE — Scan for secrets and passwords with GitLeaks(geralexgr)
- Rrs-CAolDKY — I removed it from history… but GitHub can still serve it (loose commits).(Ana's Dev Scribbles)
- SH89HqJl5Gk — Semantic Deployment in 2024(Zeke Sikelianos)
- u-GU7EkZksA — Semantic Versioning & Conventional Commits Explained Easily | DevOps Tutorial – Part 01(Tharindu Kalhara)
- Uszj_k0DGsg — Git for Professionals Tutorial(freeCodeCamp.org)
- qsTthZi23VE — Advanced Git Tutorial - Interactive Rebase, Cherry-Picking, Reflog, Submodules and more(freeCodeCamp.org)
- lZp_FJ07lT8 — Secret Scanning in CI: Stop AWS Keys Leaking to GitHub(DevOps Interview Cloud)
No verified special video found: CI shallow cloning and fetch-depth, gitsign, monorepo path filtering - the corresponding module provides storyboard scripts. The recording time of the video content may be earlier than the version of the tool used in this lesson, and the commands shall be subject to this lesson.
Voice instructions
The "Speech" page uses the browser's built-in Web Speech API: Chinese explanations use the zh-CN voice, and English terms use the en-US voice. Chrome/Edge usually comes with Chinese voice on Windows/macOS; on Linux, you may need to install a voice package. The transcript can be used directly as a recording or as a script for a third-party TTS.
Known limitations
- The SHA, time, user name (alice), repository name, job time, and PR number in the expected output are all sample values; the error text and describe results of the M3 experiment come from actually running the same steps on Git 2.51 (SHA varies depending on the environment). allowedSignersFile error in M4
%G?The results have also been tested. The remaining commands are not actually executed on this page. - Azure Pipelines' shallow fetch default value "in some organizations" applies to pipelines newly created after sprint 209. Please refer to your pipeline settings UI; whether Azure Repos provides built-in signature verification/enforcement policies, it was not found in Microsoft Learn as of the verification date and is treated as "not provided".
- Does the gitleaks default rule hit the practice repository?
FAKE_SECRETDepending on the rule version, this lesson is designed according to "May not hit, need to customize the rules". - The function packages (Secret Protection, Premium/Ultimate) and prices of GitHub, GitLab, and Azure DevOps are frequently adjusted, please refer to the official billing page.
- The Action version number will continue to be updated after the course is released; in production, please fix it to commit SHA and use Dependabot/Renovate for maintenance.