Git Handbook
Git is a distributed version control system created by Linus Torvalds in 2005. Every developer has a full copy of the repository history — no central server required for local operations. Git tracks snapshots, not diffs, and uses a content-addressable store (SHA-1 / SHA-256) to ensure integrity. It is the universal standard for source control, used from solo projects to multi-thousand-engineer monorepos.
This handbook is organised around what you want to do, not around commands. Each section covers a real-world use case with the commands you actually need.
Resources
- git-scm.com — official Git website and downloads
- Pro Git — the definitive free Git book by Scott Chacon
- GitHub Docs — GitHub-specific workflows, Actions, and CLI
- Atlassian Git tutorials — visual, workflow-focused guides
- Oh Shit, Git!? — quick fixes for common Git mistakes
Setup & Config
Identity
Git embeds your name and email in every commit. Set these before your first commit.
# Set globally (stored in ~/.gitconfig)
git config --global user.name "Ada Lovelace"
git config --global user.email "ada@example.com"
# Set per-repo (overrides global)
git config user.email "work@company.com"
# Show effective config
git config --list --show-originUseful Aliases
Aliases shorten repetitive commands. They live in ~/.gitconfig under [alias].
# Compact log graph
git config --global alias.lg "log --oneline --graph --decorate --all"
# Shorter status
git config --global alias.st "status -sb"
# Undo last commit, keep changes staged
git config --global alias.undo "reset --soft HEAD~1"
# List all aliases
git config --global alias.aliases "config --get-regexp alias"Editor & Diff Tool
# Use VS Code as commit editor and diff tool
git config --global core.editor "code --wait"
git config --global diff.tool vscode
git config --global difftool.vscode.cmd 'code --wait --diff $LOCAL $REMOTE'
# Use VS Code as merge tool
git config --global merge.tool vscode
git config --global mergetool.vscode.cmd 'code --wait $MERGED'Daily Work
Editing changes the working tree. Staging selects the snapshot for the next commit; committing records that staged snapshot in local history.
flowchart LR
W["Working tree"] -->|git add| S["Staging area / index"]
S -->|git commit| H["Local commit history"]
H -.->|git restore --staged: reset index to HEAD| S
Unstaging resets the index entry and keeps your working-tree edits. Changes made after staging need another git add to enter the next commit.
What changed?
# What is staged, modified, untracked?
git status
git status -sb # compact output
# Diff working tree vs last commit
git diff # unstaged changes
git diff --staged # staged changes (will go into next commit)
git diff HEAD # all changes (staged + unstaged) vs last commitStage & Unstage
The staging area (index) lets you compose commits precisely. You can stage individual hunks with -p to keep each commit focused.
# Stage specific file / directory
git add src/app.js
git add src/
# Stage only parts of a file (interactive hunk picker)
git add -p src/app.js
# Stage everything (tracked + untracked)
git add .
# Unstage a file (keep changes in working tree)
git restore --staged src/app.js
# Discard changes in working tree (DESTRUCTIVE — changes are gone)
git restore src/app.jsCommit
# Commit staged changes
git commit -m "feat: add login endpoint"
# Stage all tracked files and commit in one step
git commit -am "fix: correct off-by-one in pagination"
# Open editor for a multi-line message
git commit
# Commit with a body
git commit -m "feat: rate limiting" -m "Adds a token-bucket per IP.
Configurable via RATE_LIMIT_RPS env var.
Closes #42"Commit Messages & Conventional Commits
A useful commit message explains the intent of one focused change. Write a short, specific subject in the imperative (for example, add rather than added), and use the body to explain why the change is needed or what tradeoff it makes. Split unrelated changes into separate commits.
Conventional Commits adds a structured prefix that helps people scan history and lets configured tools generate changelogs and determine releases. It is a team convention; Git itself does not require or enforce it.
type(scope)!: short description
Optional body explaining why the change is needed.
Optional-Footer: valueThe type and description are required, separated by a colon and a space. The scope is optional and names the affected area, such as auth, router, or deps. Omit the parentheses when there is no scope. The optional ! marks a breaking change. Separate the optional body and footer block with blank lines; do not type the placeholder words literally.
Choosing a commit type
The specification defines feat and fix, and allows other types. The following are common conventions, not an exhaustive mandatory list. Agree on their exact boundaries with your team and release tooling.
| Type | When to use it | Example subject |
|---|---|---|
feat | Introduce a new feature or capability. | feat(search): add language filters |
fix | Correct a bug or incorrect behavior. | fix(search): handle empty queries |
docs | Change documentation, tutorials, or explanatory examples. | docs(git): explain commit types |
style | Change formatting only, such as whitespace or semicolons, without changing behavior. A visible UI or CSS change is usually feat or fix instead. | style(router): normalize indentation |
refactor | Restructure code without adding a feature or fixing a bug; preserve observable behavior. | refactor(search): extract query parsing |
perf | Improve performance, such as response time or memory usage, without changing the intended result. | perf(search): cache parsed queries |
test | Add or correct tests and test fixtures. | test(search): cover accented queries |
build | Change the build system, packaging, or external dependencies. | build(deps): update vite |
ci | Change CI/CD workflow definitions or automation scripts used by the pipeline. | ci: run checks on pull requests |
chore | Perform routine maintenance that does not fit a more specific type, such as repository housekeeping. | chore: update issue templates |
revert | Undo an earlier commit. Reference its commit hash in the body or a footer so readers can find the original change. | revert: undo the search cache |
Choose the type by the purpose of the change, not the file extension. A bug fix remains fix even if it reorganizes code and adds tests. Use refactor only when behavior is preserved, and prefer build or ci over a vague chore when those types describe the work. Split independent purposes into separate commits where practical.
feat(search): add filtering by language
fix(auth): prevent login with an expired session
refactor(router): extract route lookup without changing behavior
# Use two -m options to separate the subject and body with a blank line.
git commit -m "fix(search): preserve the selected language" -m "Keep the language filter when clearing the search text.
Closes #42"Breaking changes, footers, and releases
Any type can introduce a breaking change. Put ! immediately before the colon, or add an uppercase BREAKING CHANGE: footer describing the incompatibility and migration steps; you may use both. This example uses both to make the new API response shape explicit.
feat(api)!: return paginated search results
Return an object with items and total instead of a plain array.
BREAKING CHANGE: read results.items instead of iterating over results.
Refs: #123Footers can also reference issues or related commits, for example Closes #42 or Refs: #123. Revert behavior and issue-closing behavior depend on the tools and hosting platform you use.
With Semantic Versioning, fix corresponds to a patch release, feat to a minor release, and a breaking change of any type to a major release. Other types have no implicit version bump in the specification. Messages alone do not publish anything: release automation must be configured, and its rules determine the actual outcome.
Read the Conventional Commits 1.0.0 specification
Amend Last Commit
Fix a mistake in the most recent commit — before it is pushed to a shared branch.
# Fix the last commit message (not yet pushed)
git commit --amend -m "correct message"
# Add a forgotten file to the last commit
git add forgotten.js
git commit --amend --no-edit
# Change the author of the last commit
git commit --amend --author="Ada Lovelace <ada@example.com>" --no-edit
# ⚠️ Never amend commits that have already been pushed to a shared branchStash Work-in-Progress
Need to switch context urgently? Stash saves your dirty working tree so you can come back to it later.
# Save WIP (tracked files only)
git stash
git stash push -m "half-done feature X"
# Include untracked files
git stash push -u -m "with new files"
# List stashes
git stash list
# Apply latest stash and keep it in the list
git stash apply
# Apply specific stash
git stash apply stash@{2}
# Apply and remove from list
git stash pop
# Drop a stash
git stash drop stash@{0}
# Show diff of a stash
git stash show -p stash@{0}Branches
Create & Switch
Branches in Git are cheap — just a pointer to a commit. Create them freely.
# Create and switch in one step
git switch -c feature/login
# Create from a specific point (commit / tag / branch)
git switch -c hotfix/typo origin/main
# Switch to existing branch
git switch main
# Legacy syntax (still works)
git checkout -b feature/loginMerge
For diverged branches, a merge preserves both lines of history. Here M has both C and F as parents; arrows run from earlier commits to later commits.
flowchart LR
A --> B --> C
B --> F["F: feature commit"]
C --> M["M: merge commit on main"]
F --> M
# Fast-forward merge (linear history, no merge commit)
git switch main
git merge feature/login
# Always create a merge commit (record that branches diverged)
git merge --no-ff feature/login
# Abort a conflicting merge
git merge --abort
# After resolving conflicts manually:
git add resolved-file.js
git merge --continue
# Merge only specific file from another branch
git checkout feature/ui -- src/styles/theme.cssRebase
Starting from the same divergence above, rebasing feature onto main replays F after C as a new commit F-prime. Main remains at C until you integrate the feature.
flowchart LR
A --> B --> C["C: main"] --> FP["F-prime: rebased feature"]
The replayed commit has a new identity. Rebase changes feature history; merge preserves the original feature commit.
Rebase moves your commits on top of another branch, creating a linear history. Use it on private branches; avoid it on shared ones.
# Replay feature branch on top of main
git switch feature/login
git rebase main
# Abort if conflicts are too messy
git rebase --abort
# After resolving each conflict:
git add resolved-file.js
git rebase --continue
# Rebase onto a specific commit
git rebase --onto main feature/old feature/new
# ⚠️ Never rebase commits shared with others (force-push required after)Delete & Rename
# Delete a fully-merged branch
git branch -d feature/login
# Force delete (even if not merged)
git branch -D spike/experiment
# Delete remote tracking branch
git push origin --delete feature/login
git remote prune origin # remove stale remote-tracking refs
# Rename current branch
git branch -m new-name
# Rename any branch
git branch -m old-name new-nameTrack Remote
# See tracking relationships
git branch -vv
# Set upstream for current branch
git branch --set-upstream-to=origin/main
# Push and set upstream at the same time
git push -u origin feature/login
# Fetch all remotes and prune deleted ones
git fetch --all --pruneRemote & Sync
Manage Remotes
# List remotes
git remote -v
# Add a remote
git remote add origin https://github.com/user/repo.git
git remote add upstream https://github.com/original/repo.git
# Change remote URL (e.g. switch to SSH)
git remote set-url origin git@github.com:user/repo.git
# Rename / remove
git remote rename origin old-origin
git remote remove old-originFetch & Pull
flowchart TD
R["Remote repository"] -->|git fetch: download objects and update refs| T["Remote-tracking refs, such as origin/main"]
T -->|merge fetched branch| M["Integrate into current branch"]
T -->|rebase onto fetched branch| B["Replay local commits"]
Fetch alone leaves your current branch and working tree unchanged. Pull fetches, then integrates using merge or rebase according to options and configuration; a fast-forward-only policy rejects diverged history.
fetch downloads without touching your working tree. pull fetches then merges.
# Download new commits, don't merge
git fetch origin
git fetch --all --prune
# Pull = fetch + merge (default)
git pull
# Pull and rebase instead of merge (cleaner history)
git pull --rebase
# Pull a specific branch into current
git pull origin main
# Update a local branch without switching to it
git fetch origin main:mainPush
# Push current branch to its upstream
git push
# Push and set upstream in one go
git push -u origin feature/login
# Push a tag
git push origin v1.2.0
git push --tags # push all tags
# Force push (after rebase / amend — ⚠️ not on shared branches)
git push --force-with-lease # safe: fails if someone else pushed
git push --force # ⚠️ overwrites without checking
# Delete a remote branch
git push origin --delete feature/oldInspect History
Browse Log
# All commits, one line each
git log --oneline
# Graph of all branches
git log --oneline --graph --decorate --all
# Commits by author
git log --author="Ada"
# Commits in date range
git log --since="2024-01-01" --until="2024-06-01"
# Commits that touched a file
git log --follow -- src/auth.js
# Last 5 commits
git log -5
# Show stat (files changed)
git log --stat
# Full diff for each commit
git log -pDiff Anything
# Working tree vs staging area
git diff
# Staged vs last commit
git diff --staged
# Compare two branches
git diff main..feature/login
git diff main...feature/login # changes since they diverged
# Compare two commits
git diff abc1234 def5678
# Only file names that changed
git diff --name-only main..feature
# Diff a specific file between branches
git diff main -- src/auth.js
# Word-level diff (good for prose)
git diff --word-diffWho Changed What?
# Who last touched each line?
git blame src/auth.js
# Show only lines 10-30
git blame -L 10,30 src/auth.js
# Ignore whitespace changes
git blame -w src/auth.js
# Show the commit that deleted a line (requires -S and pickaxe)
git log -S "deleted_function_name" --source --allSearch Commits
The pickaxe (-S / -G) finds commits that added, removed, or changed a string — essential for tracking when a bug was introduced or a function was renamed.
# Find all commits whose message matches
git log --grep="fix: login"
# Find commits that added/removed a string (pickaxe)
git log -S "password_hash" --source --all
# Find commits that changed a regex pattern
git log -G "function login"
# Search file contents across history
git grep "TODO" HEAD
git grep "TODO" $(git rev-list --all) # all commits (slow)Find a Regression (bisect)
Binary-search the commit history to find exactly which commit introduced a bug. Git checks out the midpoint; you test and mark good/bad; repeat until Git pinpoints the culprit.
# Start bisect session
git bisect start
# Mark current commit as bad (has the bug)
git bisect bad
# Mark a known-good commit
git bisect good v1.0.0
# Git checks out a midpoint — test it, then mark:
git bisect good # or: git bisect bad
# Repeat until Git identifies the first bad commit.
# Automate with a test script (exit 0 = good, exit 1 = bad)
git bisect run npm test
# End the session
git bisect resetUndo & Fix
Discard Local Changes
# Discard all unstaged changes (DESTRUCTIVE)
git restore .
# Discard changes in one file
git restore src/app.js
# Remove untracked files (dry run first!)
git clean -n # show what would be deleted
git clean -f # delete untracked files
git clean -fd # delete untracked files + dirs
git clean -fdx # also delete ignored files (⚠️ node_modules etc.)Reset to a State
reset moves the HEAD pointer (and optionally the index and working tree) to any commit. --soft is safe; --hard is destructive.
# Move HEAD back N commits, keep changes staged
git reset --soft HEAD~1
git reset --soft HEAD~3
# Move HEAD back, unstage changes (default)
git reset HEAD~1
git reset --mixed HEAD~1
# Move HEAD back and DISCARD all changes (DESTRUCTIVE)
git reset --hard HEAD~1
git reset --hard origin/main # match remote exactly
# Unstage a specific file (without moving HEAD)
git reset HEAD -- src/app.jsRevert a Commit
revert creates a new commit that undoes the effect of an old one. Unlike reset, it is safe to use on shared/public branches.
# Create a new commit that undoes a previous one (safe for shared branches)
git revert abc1234
# Revert without opening the editor
git revert abc1234 --no-edit
# Revert a merge commit (specify which parent to keep)
git revert -m 1 abc1234
# Revert a range of commits (oldest first)
git revert oldest^..newestRecover Anything (reflog)
The reflog records every position HEAD has been in, including after hard resets, rebases, and deleted branches. It is your last resort for recovering "lost" work.
# See every HEAD position (including resets, rebases)
git reflog
# Recover a branch you accidentally deleted
git checkout -b recovered-branch HEAD@{3}
# Undo a hard reset
git reset --hard HEAD@{1}
# Reflog for a specific branch
git reflog show feature/login
# Reflog entries expire after 90 days by defaultRewrite History
These tools rewrite commits and change SHAs. Only use them on commits not yet pushed to a shared branch, or when you have team agreement and plan a coordinated force-push.
Interactive Rebase
The most powerful tool for cleaning up a branch before merging — reorder, rename, squash, or drop commits.
# Rewrite the last 4 commits
git rebase -i HEAD~4
# Rewrite since diverging from main
git rebase -i main
# Actions in the editor:
# pick — keep as-is
# reword — keep but edit message
# edit — pause to amend the commit
# squash — merge into previous commit, combine messages
# fixup — merge into previous commit, discard message
# drop — delete the commit entirely
# exec — run a shell command after the commitFixup & Squash
# Create a fixup commit targeting an earlier commit by message
git commit --fixup abc1234
# Then auto-squash during rebase
git rebase -i --autosquash HEAD~5
# Squash all commits on feature branch into one
git switch main
git merge --squash feature/login
git commit -m "feat: login feature" # single tidy commitCherry-pick
Apply a commit from any branch onto the current one — useful for backporting fixes.
# Apply a single commit from another branch
git cherry-pick abc1234
# Apply a range of commits
git cherry-pick abc1234^..def5678
# Apply but don't commit yet (stage the changes)
git cherry-pick --no-commit abc1234
# If conflicts:
git cherry-pick --continue
git cherry-pick --abortTags & Releases
Create & Push Tags
Use annotated tags for releases — they store a message, tagger, and date.
# Lightweight tag (just a pointer)
git tag v1.0.0
# Annotated tag (recommended for releases — stores author + message)
git tag -a v1.0.0 -m "First stable release"
# Tag a specific commit
git tag -a v1.0.0 abc1234 -m "Release"
# Push a single tag
git push origin v1.0.0
# Push all tags
git push --tags
# List tags matching a pattern
git tag -l "v1.*"Delete Tags
# Delete local tag
git tag -d v1.0.0-beta
# Delete remote tag
git push origin --delete v1.0.0-beta
# Move a tag to current HEAD (re-tag)
git tag -f v1.0.0 # move local
git push --force origin v1.0.0 # ⚠️ update remoteCI/CD
Git records changes; a CI/CD platform reacts to repository events and runs automated jobs on runners. Keep pipeline definitions in version control so changes to tests and delivery are reviewed alongside application code.
Concepts & Pipeline Stages
- Continuous integration (CI): integrate small changes frequently and automatically check each proposed change with linting, tests, and a build.
- Continuous delivery: successful changes produce a deployable artifact; a person approves the production release.
- Continuous deployment: every change that passes the release policy reaches production automatically. Monitoring and recovery are part of that policy.
flowchart LR
P["Push / pull request"] --> V["Install, lint, test, build"]
V --> A["Versioned artifact"]
A --> S["Deploy to staging and smoke test"]
S --> G["Production approval"]
G --> D["Deploy same artifact"]
D --> M["Health checks and monitoring"]
M -->|unhealthy| R["Restore previous artifact"]
A failed verification stops delivery. Jobs may run in parallel, but deployment must explicitly depend on successful verification. The diagram shows a delivery process with staging; the minimal examples below deploy directly to production after their gate and can be extended with a staging job.
GitHub Actions Example
This example targets a generic Node.js application with a committed package-lock.json, lint, test, and build scripts, a non-interactive test command, and build output in dist/. Adapt paths and commands for your project; these are teaching examples, not this handbook application's CI configuration. YAML indentation uses spaces.
How to read the YAML: a colon introduces a key and its value; indentation groups settings under their owner. A dash starts a list item, such as one step. [main] is a short list with one entry. Lines beginning with # are comments, so you can copy these explanations along with the sample. Keep the nesting when adapting it: for example, branches belongs to push, not to the entire workflow.
Three levels: a workflow is the whole file, a job is a unit assigned to a runner, and a step is an action or shell command inside that job. uses calls an action; with configures that action's inputs; run executes your own shell command. The action version after @ selects the action code, whereas node-version selects Node.js for your application.
# .github/workflows/ci.yml
# Display name shown in the Actions tab.
name: CI
# Events that start a new workflow run.
on:
# Check PRs when opened, updated, or reopened (default activity types).
pull_request:
push:
# This filter belongs to push only; PRs are not filtered by branch here.
branches: [main]
# Limit the automatic GITHUB_TOKEN to reading repository contents.
permissions:
contents: read
# Jobs are independent unless connected by needs.
jobs:
# Job identifier: other jobs refer to this as needs: verify.
verify:
# Request a GitHub-hosted Linux runner for this job.
runs-on: ubuntu-latest
# Stop a stuck job rather than consuming runner time indefinitely.
timeout-minutes: 15
# Ordered list: later steps normally run only if earlier steps succeed.
steps:
# uses invokes a reusable action; @v7 selects its major release tag.
- uses: actions/checkout@v7
# with supplies inputs to the action directly above it.
with:
# Do not leave checkout credentials available to later Git commands.
persist-credentials: false
- uses: actions/setup-node@v7
with:
# Application runtime, independent of the action's own runtime.
node-version: '24'
# Reuse npm downloads; dependencies still need installing below.
cache: npm
# run executes a shell command in the repository workspace.
- run: npm ci
# These names must exist under scripts in package.json.
- run: npm run lint
- run: npm test
- run: npm run build
# Save build output so another job can download it.
- uses: actions/upload-artifact@v7
with:
# Logical artifact name, not a directory name.
name: site
# Files to upload, relative to the workspace.
path: dist/
# Fail if the build did not produce the expected files.
if-no-files-found: error
# Keep this CI output for seven days.
retention-days: 7Walk through one run:
- Select the event. Opening or updating a pull request starts verification. Pushing to
mainstarts a separate run. Pushing to another branch without a pull request does not start this workflow. The workflow nameCIis a display label;verifyidentifies the job. - Prepare the runner. GitHub allocates a Linux machine. Checkout places the repository files in its workspace; setup-node makes Node.js 24 available and restores eligible npm downloads. Neither action builds the application.
- Verify the source.
npm ciinstalls the locked dependencies. Lint checks code rules, tests check behavior, and build creates the distributable files. Those last three commands execute scripts defined by your project; GitHub does not supply them. If tests enter watch mode, configure a command that runs once and exits. - Preserve the result. Upload reads
dist/and stores its contents as an artifact namedsite. The artifact name is how another job finds it. Missing output fails this step instead of silently recording a successful build without files.
Each shell step has its own process: a shell variable or directory change from one run does not automatically carry into another. Files written in the workspace do persist between steps of the same job. Use step/job environment settings and working-directory settings when commands need shared configuration.
pull_request checks proposed changes; the push trigger verifies the merged state of main. Steps in a job share a runner workspace and run in order. Separate jobs have separate workspaces, so use an artifact to transfer the build. npm ci installs from the lockfile and fails when it disagrees with package.json.
The optional deployment job below consumes the artifact from this same run. Before enabling it, create a production environment, configure required reviewers and allowed deployment branches where your plan supports them, and store DEPLOY_TOKEN as an environment secret. Merely naming an environment does not create an approval policy.
# Add under jobs: in the same ci.yml (same indentation as verify).
deploy:
# Wait for verify to succeed; failures prevent deployment by default.
needs: verify
# Both conditions must match: never deploy a pull-request run.
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
# This is a separate runner workspace from verify.
runs-on: ubuntu-latest
timeout-minutes: 10
# Apply the production environment's configured gates and secret scope.
environment: production
concurrency:
# Jobs using this group in the repository share a deployment lock.
group: production
# Do not interrupt an already running deployment for a newer run.
cancel-in-progress: false
steps:
# Fetch the deployment script; this does not restore verify's workspace.
- uses: actions/checkout@v7
with:
persist-credentials: false
- uses: actions/download-artifact@v8
with:
# Must match the upload's name in verify.
name: site
# Extract the artifact contents into this local directory.
path: dist/
# A step name is a label in the run's logs.
- name: Deploy the verified artifact
# Expose these values only to this step's process environment.
env:
# GitHub resolves the expression from its secret store.
DEPLOY_TOKEN: ${{ secrets.DEPLOY_TOKEN }}
# Commit associated with this main-branch push.
RELEASE_SHA: ${{ github.sha }}
# The shell expands the quoted variable; the script reads DEPLOY_TOKEN.
run: bash scripts/deploy.sh dist/ "$RELEASE_SHA"Why deployment has its own job: needs: verify establishes a dependency; if adds an event and branch restriction. On a pull request, verification runs and deployment is skipped. On a push to main, deployment becomes eligible after verification succeeds, then waits for any configured production protection rules.
The deployment runner starts with a fresh workspace. Checkout retrieves scripts/deploy.sh; download-artifact retrieves the already built site output into dist/. There is no second build, so the deployed files are the ones produced by verification. The name inside the download action's with selects an artifact; the step-level name labels a log entry.
Expressions versus shell variables: GitHub evaluates the expression in DEPLOY_TOKEN using its secret store and the expression in RELEASE_SHA using the triggering commit. The env block passes the results into the deployment step. Bash then expands "$RELEASE_SHA" into one argument; the script receives the directory as its first argument, the SHA as its second, and reads DEPLOY_TOKEN from its environment. Do not hard-code a real token in this file.
What the lock guarantees: the production concurrency group prevents two jobs in that group from deploying simultaneously. cancel-in-progress: false lets a running deployment finish. This is not a first-in, first-out release queue: pending runs can be superseded, and a delayed older run still needs a freshness check before activation.
scripts/deploy.sh is an application-specific prerequisite, not a built-in command. Implement it to upload the supplied directory using DEPLOY_TOKEN, record the supplied commit SHA, activate the release atomically where supported, and exit nonzero on deployment or health-check failure. The example does not supply a hosting provider integration. The branch condition prevents pull requests from deploying; concurrency prevents overlapping production jobs but does not guarantee release ordering. Reject stale releases before activation.
GitLab CI Example
GitLab reads .gitlab-ci.yml from the repository root. This example uses the same Node.js prerequisites and deployment script. Configure an eligible runner, protect the default branch and production environment as supported by your GitLab tier, and add an environment-scoped, protected, masked DEPLOY_TOKEN variable in CI/CD settings.
# .gitlab-ci.yml
# Default container image for jobs on a compatible container executor.
image: node:24-bookworm-slim
# Default stage order; needs can express more specific dependencies.
stages: [verify, deploy]
# Pipeline-level rules decide whether a pipeline is created at all.
workflow:
rules:
# Rules are evaluated in order; the first match determines the result.
- if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
- if: '$CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH'
# No matching rule means no pipeline for that event.
# Default cache configuration inherited by these jobs.
cache:
key:
# Changing the lockfile changes the dependency cache key.
files: [package-lock.json]
# Cache npm downloads, not the installed node_modules tree.
paths: [.npm/]
# Top-level job name, unlike GitHub's jobs: wrapper.
verify:
stage: verify
timeout: 15m
# Ordered shell commands; a failing command normally fails the job.
script:
# Use the cached download directory; fetch missing packages as needed.
- npm ci --cache .npm --prefer-offline
- npm run lint
- npm test
- npm run build
# Upload successful build output for later jobs.
artifacts:
paths: [dist/]
expire_in: 7 days
deploy_production:
stage: deploy
timeout: 10m
# Require this job and transfer its artifacts into the deploy workspace.
needs:
- job: verify
artifacts: true
# Track this job as a deployment to the named environment.
environment:
name: production
# Only one job with this resource group runs at a time in this project.
resource_group: production
# Job-level rules decide whether this job is included and how it starts.
rules:
- if: '$CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH'
# An authorized user must start the job through GitLab.
when: manual
# Treat this manual gate as blocking, not optional.
allow_failure: false
script:
# GitLab supplies the SHA; DEPLOY_TOKEN is configured outside this file.
- bash scripts/deploy.sh dist/ "$CI_COMMIT_SHA"Read this file in four parts:
- Execution defaults.
imagesupplies Node.js and Linux tools when the runner uses a container executor that supports it. A shell executor runs on its host instead, so the host must provide those tools.stagesdeclares the stage names and their normal order. - Pipeline admission.
workflow.rulesdecides whether GitLab creates a pipeline. Here a merge-request event or a default-branch update is admitted. GitLab fills in theCI_*variables. The default branch is read from project settings, so it need not be namedmain. Conditions are evaluated by GitLab, not by the job's shell. - Verification and storage. The
verifyjob installs, lints, tests, and builds. The npm flags point downloads at.npm/and prefer cached packages while allowing network fetches. The lockfile-derived key selects a cache;artifacts.pathsseparately saves the resultingdist/build. These paths are relative to the project directory. - Production gate. Job-level
rulesaddsdeploy_productiononly on the default branch and makes it manual.needsconnects it toverify;artifacts: truerequests that job's output.resource_groupprovides mutual exclusion for deployment, andenvironment.nameassociates the result with production.
Expected result: a merge-request pipeline verifies the change without adding the production job. A successful default-branch pipeline waits at the manual deployment gate. Because allow_failure is false, that gate must succeed for the pipeline to complete successfully. Starting it runs the deployment script with the verified build and CI_COMMIT_SHA; no application rebuild is required.
Do not confuse workflow.rules with a job's rules: the former can prevent the entire pipeline from existing; the latter controls a particular job. Also, when: manual provides a start button, not an authorization policy. Configure protected environments and variable access separately. An artifact may expire while a manual job waits, so choose retention that covers your approval window.
The workflow creates merge-request and default-branch pipelines. Open a merge request to check a feature branch. needs requires successful verification and downloads its artifact. The manual production job is blocking because allow_failure: false; restrict who may run it through environment permissions. resource_group serializes production deployment jobs; configure its process mode or reject stale releases if ordering matters.
Pull Requests & Quality Gates
- Protect
mainwith required review and required CI status checks. A workflow alone does not prevent merging a failed change. On GitLab, enable the merge requirement for successful pipelines. - Require the result for the current proposed revision. Use up-to-date branch checks, a merge queue, or merged-result pipelines when integration with concurrent changes matters; configure CI for the corresponding events.
- Keep required job names stable. Avoid path filters that leave a required workflow pending forever, and do not hide failures with
continue-on-error,allow_failure, or shell commands that always succeed. - Run quick static checks first, then unit tests, integration tests, and a production build. For libraries, add a runtime/OS matrix based on supported versions. Give matrix artifacts distinct names.
- Use local hooks for fast feedback, but enforce policy on the server: hooks can be absent or bypassed.
Caching & Artifacts
A cache speeds up work and must be safe to lose. Cache the package manager's download directory, key it by the lockfile and relevant runtime/platform, and still install dependencies. GitHub's npm cache does not replace npm ci; the GitLab example caches .npm/ for the same reason.
An artifact is an output needed by later jobs or people: compiled files, test reports, or a container image. Build once, identify the output by commit SHA and digest, and promote that same output through environments. Keep secrets and unnecessary files out of artifacts. Retain release artifacts long enough to support recovery; the seven-day retention here is a CI example, not a production rollback policy.
For a monorepo, set working directories, dependency-cache paths, and artifact paths explicitly. For containers, deploy an immutable image digest rather than a moving latest tag. Keep environment-specific configuration outside the artifact when possible.
Secrets & Environments
- Use the platform's secret store, least-privilege credentials, and separate staging/production access. Prefer provider-supported OIDC for short-lived cloud credentials; grant
id-token: writeonly to the job that needs it and constrain the cloud trust policy. - Treat pull-request code as untrusted. Keep deployment credentials out of validation jobs; do not run untrusted checkout code with privileged
pull_request_targetcredentials. Use isolated runners for untrusted contributions. - Major action tags in these examples aid readability. For production, review and pin third-party actions to full commit SHAs and container images to digests, then automate reviewed updates. Check compatibility for self-hosted runners and GitHub Enterprise Server.
- Pass untrusted event data through environment variables and quote shell arguments instead of interpolating it directly into shell source. Disable shell tracing around secrets and avoid printing tokens; masking is not a complete defense against leakage.
- Require production approval when appropriate, restrict deployment branches/tags, and protect pipeline and deployment-script changes through review. Rotate exposed credentials immediately; deleting them from the latest commit does not revoke them.
Releases & Rollback
Use reviewed annotated tags to identify releases and record the source SHA, artifact digest, configuration version, and deployment outcome. The examples above trigger deployments from the default branch, not tags. If you choose tag-triggered delivery, add a tag trigger and deployment condition, protect release tags, verify the tagged commit against release policy, and preserve the test-before-deploy dependency.
# Tag an already reviewed and verified commit on main.
git switch main
git pull --ff-only
git log -1 --oneline
git tag -a v1.2.0 -m "Release v1.2.0"
git push origin v1.2.0
# Inspect a failing GitHub Actions run (requires authenticated GitHub CLI).
gh run list --workflow ci.yml --limit 5
gh run view RUN_ID --log-failed
# Repair source history after an incident; replace BAD_COMMIT with a SHA.
git switch -c fix/revert-release
git revert BAD_COMMIT
git push -u origin fix/revert-release
# Open a PR and run CI. This does not roll back a running deployment.During an incident, redeploy a known-good retained artifact through the deployment system and verify health. A Git revert changes source history and requires a new verified deployment before production changes. Do not move an existing release tag to disguise a bad release; publish a new version. Database migrations may make older application versions incompatible, so use backward-compatible schema changes and plan data recovery separately.
For higher-risk services, deploy to staging first, then use a canary or blue/green rollout with explicit error-rate and latency thresholds. Stop or roll back when those thresholds fail. A successful upload alone does not prove the service works.
Troubleshooting & References
- Works locally, fails in CI: reproduce the runner's runtime and clean lockfile install; check case-sensitive paths, missing environment variables, timezone assumptions, and tests left in watch mode.
- Missing build in a later job: check the upload path, artifact name, retention, and explicit download/dependency. Jobs do not share a filesystem.
- Release version cannot find tags: GitHub checkout is shallow by default. Use
fetch-depth: 0when a versioning tool needs full history and tags; configure GitLab'sGIT_DEPTHappropriately. - Deployment waiting or missing credentials: inspect environment approvals, branch restrictions, protected-variable scope, and the triggering event. Fork validation generally cannot access repository secrets.
- Flaky tests or stale deployment: inspect logs and timing, make tests deterministic, and enforce deployment ordering. Retry transient infrastructure errors selectively; repeated retries can hide a real regression.
Validate GitLab YAML with CI Lint and inspect the pipeline graph. For GitHub, review Actions annotations and failed-step logs; a YAML parser alone cannot verify platform expressions or deployment permissions.
- GitHub workflow syntax reference — meanings and placement of workflow, job, and step keys.
- GitHub Actions how-to guides — workflows, environments, and delivery.
- GitHub Actions secure use — credentials, untrusted inputs, and action pinning.
- GitHub workflow artifacts — storing and transferring outputs.
- GitLab CI YAML reference — rules, dependencies, and deployment jobs.
- GitLab job artifacts and caching examples — choosing the right storage mechanism.
Submodules
Add & Init
# Add a submodule
git submodule add https://github.com/org/lib.git libs/lib
# Clone a repo that has submodules
git clone --recurse-submodules https://github.com/org/project.git
# If you already cloned without --recurse-submodules
git submodule init
git submodule updateUpdate
# Pull latest for all submodules
git submodule update --remote --merge
# Run a command in every submodule
git submodule foreach 'git checkout main && git pull'
# Remove a submodule completely
git submodule deinit libs/lib
git rm libs/lib
rm -rf .git/modules/libs/libAdvanced
Worktrees
Check out multiple branches simultaneously in separate directories — no stashing required. Ideal when you need to test a hotfix while keeping your feature branch intact.
# Check out a second branch in a separate directory (no stash needed)
git worktree add ../project-hotfix hotfix/critical
# List all worktrees
git worktree list
# Remove a worktree (after you're done)
git worktree remove ../project-hotfix
# Useful pattern: keep main checked out while working on a feature
git worktree add ../project-main mainSparse Checkout
Download only part of a large monorepo, keeping disk usage and clone time low.
# Only download / check out a subdirectory of a large monorepo
git clone --filter=blob:none --sparse https://github.com/org/monorepo.git
cd monorepo
git sparse-checkout set packages/ui packages/api
# Add more paths later
git sparse-checkout add packages/sharedHooks
Git hooks are shell scripts that run automatically at key points in the workflow.
# Hooks live in .git/hooks/ (not committed) or in a shared hooks dir.
# To share hooks, configure:
git config core.hooksPath .githooks
# Common hook files (make them executable: chmod +x):
# pre-commit — run lints / tests before commit
# commit-msg — validate commit message format
# pre-push — run tests before push
# post-merge — e.g. run npm install after pull
# Example pre-commit hook (.githooks/pre-commit):
# #!/bin/sh
# npm run lint || exit 1Patches by Email
# Create a patch file for the last 3 commits
git format-patch HEAD~3
# Create a single patch from a diff
git diff > my-changes.patch
# Apply a patch (tries to apply cleanly)
git apply my-changes.patch
# Apply a format-patch (preserves commit metadata)
git am 0001-feat-login.patch
# Send patches by email (git send-email)
git send-email --to=maintainer@project.org HEAD~3Useful Config Flags
Performance and workflow improvements worth enabling globally.
# Speed up large repos
git config core.fsmonitor true # OS file-system watcher
git config core.untrackedCache true # cache untracked file lookup
# Always rebase on pull (cleaner history)
git config --global pull.rebase true
# Prune stale remote refs on every fetch
git config --global fetch.prune true
# Auto-setup tracking when pushing a new branch
git config --global push.autoSetupRemote true
# Use patience diff algorithm (better for large refactors)
git config --global diff.algorithm patience
# Show moved lines differently in diffs
git config --global diff.colorMoved zebra
# Store credentials (macOS keychain / Windows Credential Manager)
git config --global credential.helper osxkeychain # macOS
git config --global credential.helper manager # Windows