danilo.pianini@unibo.itCompiled on: 2026-11-30 — printable version
Git supports two types of tags:
-a (unsigned), -s, or -u optionsgit describe) ignore lightweight tags by defaultNice people sign commits, certifying their authorship.
If you do not have a signature yet, time to create one
gpg --gen-keygpg --list-keysgpg --keyserver hkps://keys.openpgp.org --send-keys <YOUR_KEY_ID>Once you have a private key to sign with, you can configure Git to use it for signing things by setting the user.signingkey config setting.
git config --global user.signingkey <YOUR_KEY_ID>
Since Git 2.34, commits and tags can be signed with an SSH key instead of a GPG key
git config --global gpg.format ssh
git config --global user.signingkey ~/.ssh/id_ed25519.pub
git config --global commit.gpgsign true # sign every commit
git config --global tag.gpgsign true # sign every annotated tag
git log --show-signature) requires a list of trusted keys:
git config --global gpg.ssh.allowedSignersFile ~/.ssh/allowed_signers<email> <public key>Trailers are Key: value lines at the end of a commit message, used to add structured metadata
feat(parser): support multi-line string literals
Literals delimited by triple quotes can now span multiple lines.
Closes: #142
Co-authored-by: Jane Doe <jane.doe@example.com>
Signed-off-by: John Smith <john.smith@example.com>
Co-authored-by: multiple authors for one commit (GitHub shows all of them)Signed-off-by: the author certifies they have the right to submit the change
git commit -sCloses:, Fixes:, Reviewed-by:, Assisted-by:…: project conventionsAdding trailers without editing the message by hand:
git commit -s -m "fix: handle empty input" # adds Signed-off-by
git commit --trailer "Co-authored-by: Jane Doe <jane.doe@example.com>"
Querying trailers:
# list co-authors across the history
git log --format='%(trailers:key=Co-authored-by,valueonly)' | sort -u
# parse trailers of a message
git log -1 --format=%B | git interpret-trailers --parse
Trailers and AI assistance:
Co-authored-by: an agent identity, or Assisted-by:Signed-off-by: is a statement by a human: an agent cannot certify the origin of the code for youClassic situation:
$\Rightarrow$ You don’t want to commit half-finished work, but you can’t lose what you have done…
git stash to the rescueStashing takes the dirty state of the working directory and saves it on a stack of unfinished changes that you can reapply at any time
git stash
git stash list
git stash apply [stash@{N}] [--index]
stash@{N}, applies the N-th stashed change--index is specified, the changes that were staged at the time of push get re-stagedgit stash drop stash@{N}
git stash pop
git stash apply && git stash drop stash@{0}Stashing works for quick interruptions, but:
A second git clone works, but duplicates the whole history, and the clones do not share branches
Worktrees: multiple working directories attached to the same repository
git worktreeHEAD, index (staging area), working files
git worktree add ../project-hotfix hotfix/crash # check out an existing branch
git worktree add -b feat/cli ../project-cli master # create a new branch from master
git fetch origin pull/42/head # GitHub exposes PRs as refs
git worktree add --detach ../project-review FETCH_HEAD
git worktree list # show all worktrees
git worktree remove ../project-hotfix # delete a worktree (not the branch!)
git worktree prune # clean up worktrees deleted by hand
Practical notes:
git stash |
git worktree |
second git clone |
|
|---|---|---|---|
| Use for | Short interruptions | Parallel work on the same repo | Independent copies |
| Working directories | One | Many | Many |
| History | Shared | Shared (one .git) |
Duplicated |
| Branches | Shared | Shared, one checkout per branch | Independent, sync via remote |
| Cost | None | Working files + build | Full repository + build |
git merge experiment
4 was developed after 3
Rebasing provides a way to alter the project history by changing the parent (re-base) of existing commits
git checkout experiment && git rebase master
git checkout experiment && git rebase master
git checkout master && git merge
git checkout master && git merge
fast-forward!
We want to leave server as is, but rebase client onto master
Option --onto can be used to transplant entire branches
git rebase --onto destination start end
start to enddestinationgit rebase --onto master server client
Reads: pick all commits from server (excluded) to client (included), remove them and replay them starting from master
Or: pick all commits from client, remove all those in server, then replay them starting from master
pull is a non-atomic operation (roughly) equivalent to git fetch && git merge FETCH_HEAD
There is no reason for the operation of reconciliation to be merge: it could well be rebase!
git fetch && git rebase FETCH_HEAD (roughly)
Both operations are actually supported! The full commands would be:
git pull --rebase=false $\Rightarrow$ reunite using merge (the historical default)
git pull --rebase=true $\Rightarrow$ reunite using rebase!
Note: new versions of git require explicit configuration!
git config --global pull.rebase [true/false]Note: rebase is more sensitive to modified files in the worktree!
git stash && git pull --rebase=true && git stash popgit pull --rebase=true --autostashDo not rebase commits that exist outside your repository
Rebasing rewrites the project history and as such generates incompatible histories
--force rewrites history remotely and may delete other people’s commits!git pull --rebase is safe, if the local commits were never pushed to any remote
git config --global pull.rebase trueA (very common) situation: the same repository is pushed to two remotes, both receiving changes
pull.rebase true, and we push to bothA on GitHub, a co-author added B on Overleaf, we committed L locallygit pull --rebase github master && git push github master
L is replayed on top of A, becoming L', and published on GitHubgit pull --rebase overleaf master && git push overleaf master
A and L' are local commits not on Overleaf: they get replayed on top of BA' and L'' are copies of A and L' (same changes, different hashes), and now they are publishedgit push github master ❌ rejected (non-fast-forward), so: git pull --rebase github master && git push github master
A' and L'' are skipped: git detects that GitHub already has the same changesB is replayed as B', and published on GitHub1git push overleaf master ❌ rejected, so: git pull --rebase overleaf master
Merge creates a commit that both histories contain
git pull --no-rebase github master && git push github master && git push overleaf master
M: from now on, pulls and pushes are fast-forwardsgit config pull.rebase false in that repository)Select depending on what you conceptually want:
They tell two stories:
rerereRebasing repeatedly (e.g., a long-lived branch kept up to date with master) means
solving the same conflicts over and over
rerere (reuse recorded resolution) remembers how you solved a conflict, and re-applies the resolution automatically
git config --global rerere.enabled true
rerere.autoUpdate true)git rerere diff: shows what would be re-appliedgit rerere forget <path>: drops a wrong recorded resolutionSquashing is the practice of reassembling multiple commits into a single one
merge or manuallygit reset --soft HEAD~4
The worktree still has all changes from 6! What if we commit?
git commit
Commits 3 to 6 have been squashed into a single commit 3'!
merge --squashUse a branch to “keep alive” the commits discarded by the reset
(or we remember the hash, or we use a tag)
git branch target
now move master back to the last commit to preserve
merge --squashnow move master back to the last commit to preserve
git reset --hard HEAD~4
Ready: merge all changes in target, creating a single commit!
merge --squashgit merge --squash target && git commit
Remove the old branch: git branch -D target
Squashing alters history more than rebase does
Merge when you want to retain history, keeping track of what happened
Rebase only when you are the only one with the commits, to favor linearity
Squash when some of the commits are somewhat “tests”, points in time you do not want to get back to anyway
-i) to rewrite historyrebase -i <tree-ish>
The most important commands are:
pick or p $\Rightarrow$ use commit, no changes
reword or r $\Rightarrow$ use commit, but edit the commit messageedit or e $\Rightarrow$ use commit, but stop for amendingsquash or s $\Rightarrow$ use commit, but meld into previous commitfixup or f $\Rightarrow$ like “squash”, but discard this commit’s log messagedrop or d $\Rightarrow$ remove commit$ git rebase -i HEAD~7
pick 41669e3 chore(deps): update shared-slides digest to 550f3a8
pick 053bfca chore(deps): update shared-slides digest to 249f7ae
pick 7af4843 chore(deps): update themes/reveal-hugo digest to 6c4bcb7
pick 3e4259e chore(deps): update shared-slides digest to 5384aaf
pick 117fa35 chore(deps): update themes/reveal-hugo digest to f9ead1f
pick 6eb514b chore(deps): update shared-slides digest to 0b573b0
pick 17743ec migrate from `GetJSON` to `resources.GetRemote` with `transform.Unmarshal`
Commits are listed in the reverse order compared to git log.
reword 053bfca chore(deps): update shared-slides digest to 249f7ae
drop 41669e3 chore(deps): update shared-slides digest to 550f3a8
squash 7af4843 chore(deps): update themes/reveal-hugo digest to 6c4bcb7
squash 3e4259e chore(deps): update shared-slides digest to 5384aaf
squash 117fa35 chore(deps): update themes/reveal-hugo digest to f9ead1f
pick 6eb514b chore(deps): update shared-slides digest to 0b573b0
edit 17743ec migrate from `GetJSON` to `resources.GetRemote` with `transform.Unmarshal`
git rebase --continueTypical situation: during a review, you find a mistake in a commit three commits ago
Instead of editing the history by hand, record the fix declaring which commit it fixes:
git commit --fixup=a1b2c3d # creates "fixup! <message of a1b2c3d>"
git commit --fixup=amend:a1b2c3d # also replaces the message of a1b2c3d
git commit --fixup=reword:a1b2c3d # only replaces the message
When the branch is ready, let git reorder and meld the fixups:
git rebase -i --autosquash master
git config --global rebase.autoSquash true # make it the default
pick a1b2c3d feat(parser): support multi-line strings
fixup 9f8e7d6 fixup! feat(parser): support multi-line strings
pick 4c5d6e7 test(parser): multi-line strings
Large features are better delivered as small, dependent pull requests: a stack
feat/api $\rightarrow$ feat/model $\rightarrow$ mastermaster moved to 7. Rebasing feat/ui rewrites 4, 5, and 6…
feat/model and feat/api would still point to the old commits!--update-refsgit rebase --update-refs master (from feat/ui)
git config --global rebase.updateRefs true to make it the defaultgit push --force-with-lease origin feat/model feat/api feat/ui)
--force-with-lease: overwrite the remote branch only if it is still where we last saw it
(otherwise someone else pushed, and we would delete their commits)feat/model is merged, feat/api is retargeted to masterDon’t push your work until you’re happy with it
One of the cardinal rules of Git is that, since so much work is local within your clone, you have a great deal of freedom to rewrite your history locally. However, once you push your work, it is a different story entirely, and you should consider pushed work as final unless you have good reason to change it. In short, you should avoid pushing your work until you’re happy with it and ready to share it with the rest of the world.
Selecting and importing a single commit (or commit range) from another branch
git cherry-pick <tree-ish>
<tree-ish> and adds it to HEAD<tree-ish> is a branch name, cherry picks the last commit of the branchgit cherry-pick from..to
from to ref toCherry picking is often useful for applying fixes or patches which are in development from other branches.
Bisection is a technique to find the commit that introduced a bug
git bisect startgit bisect badgit bisect goodgit bisect good or git bisect badgit bisect run0 if the bug is absent, and 1 to 127 except 125 otherwise
125 means “cannot be tested”git bisect run <command> <args>Using a repository within another repository
Typical use:
Adding an external submodule:
git submodule add <REPO_URL> <DESTINATION>
.gitmodules file in the repository root<DESTINATION>.gitmodules and <DESTINATION> must be tracked<DESTINATION>A plain clone does not initialize submodules. Special care applies.
git clone --recurse-submodules <URL> <DESTINATION>
If the repository has been cloned plainly, then submodules can be initialized manually
git submodule update --init --recursive
git submodule update --remote --recursive
git submodule update --init --recursive in each new worktreeChanges in submodules are dealt with as if they were in a separate repository
foreach can be used to run some command on all modules
git submodule foreach git pull--recurse-submodulesgit mv path/to/submodulegit rm path/to/submoduleThey allow an existing submodule to be moved and removed, respectively
No single built-in command in old versions of git 😑 :
git submodule deinit -f -- sub/module/path
rm -rf .git/modules/sub/module/path
git rm -f sub/module/path
Note: Do not use a trailing slash on the submodule path when using these commands!
git blameShows what revision and author last modified each line of a file
git blame foo
foo, line by linegit blame -L 16,42 foo
fooIt is possible to use a regular expression as an argument to -L,
finding who did something specific
Blame often points to the wrong commit: whoever reformatted or moved the code
git blame -w: ignore whitespace changesgit blame -C -C -C: detect lines moved or copied from other files# .git-blame-ignore-revs, committed in the repository
# Reformat the whole project with ktlint
4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2c3d
git config blame.ignoreRevsFile .git-blame-ignore-revs
.git-blame-ignore-revs automatically, if present in the repository root⬇️ git checkout HEAD~4 && git checkout -b very-important ⬇️
⬇️ Multiple extremely important commits ⬇️
⬇️ git checkout master ⬇️
git branch -D very-important ➡️
⬇️ git branch -D very-important ⬇️

git reflogReference logs: a diary of when branches and other references were updated
git reflog example:
c5c29c1 (HEAD -> master, origin/master, origin/HEAD) HEAD@{0}: checkout: moving from 2aa2cbd6f5cdb91a02f2061e029106878706bf49 to master
2aa2cbd HEAD@{1}: checkout: moving from master to HEAD~1
c5c29c1 (HEAD -> master, origin/master, origin/HEAD) HEAD@{2}: commit: add git blame
2aa2cbd HEAD@{3}: commit: improve git slides, prepare for blame and reflog
ae7eb17 HEAD@{4}: pull (finish): returning to refs/heads/master
ae7eb17 HEAD@{5}: pull (pick): improve the style
d2b71b0 HEAD@{6}: pull (start): checkout d2b71b04466d11498fdd10cc57da98dc0ab8eae2
e77f8a0 HEAD@{7}: commit: improve the style
5339051 (tag: 0.1.0-2022-09-08T174231) HEAD@{8}: commit: fix: forcibly set the targetPath of hugo
e5eeecd (tag: 0.1.0-2022-09-08T173405) HEAD@{9}: commit: ci: fix JamesIves/github-pages-deploy-action parameter names
50c5efe (tag: 0.1.0-2022-09-08T172922) HEAD@{10}: commit: fix: set up the custom css path
ba8fae0 (tag: 0.1.0-2022-09-08T162354) HEAD@{11}: commit: fix: make the new template work
8546a6c HEAD@{12}: commit: chore: switch to @cric96 fork of hugo-reveal
format: hash (labels) reference: operation (status): details
Any of the tree-ishes can be used to check out!
git checkout HEAD@{6} would check out commit d2b71b0!
git reflog
Git clones the whole history, of all files. This becomes a problem with:
Git offers different tools, cutting the repository along different dimensions:
| Tool | Cuts | Typical use |
|---|---|---|
| Shallow clone | Old commits | CI builds (seen in CI) |
| Partial clone | File contents, downloaded on demand | Developers on big repos |
| Sparse checkout | Directories in the working tree | Monorepos |
| Git LFS | Large files, stored outside the repository | Binary assets |
Partial clone: download commits and trees, fetch file contents (blobs) only when needed
git clone --filter=blob:none https://github.com/org/huge-repo.git # blobless
git clone --filter=tree:0 https://github.com/org/huge-repo.git # treeless (CI-like)
log, blame work), contents downloaded lazilyblame) may be slower: they need the networkSparse checkout: populate only some directories of the working tree
git clone --filter=blob:none --sparse https://github.com/org/monorepo.git
cd monorepo
git sparse-checkout set services/billing libs/common # only these directories
git sparse-checkout add services/payments # one more
git sparse-checkout disable # back to the full tree
An extension to git: large files are replaced in the repository by small pointer files, the actual contents are stored on a separate server
git lfs install # once per machine
git lfs track "*.psd" "*.onnx" # writes rules into .gitattributes
git add .gitattributes model.onnx
git commit -m "chore: add model"
version https://git-lfs.github.com/spec/v1
oid sha256:4d7a214614ab2935c943f9e0ff69d22eadbb8f32b1258daaa5e2ca24d17e2393
size 132735481
git lfs installed, otherwise they get the pointer filesScripts that execute when some events happen, stored by default in .git/hooks
.git/hooks is not part of the repository code: hooks placed there cannot get committed and pushed
Events also dictate the file names:
applypatch-msgcommit-msg $\Leftarrow$ particularly useful to enforce a commit message format!fsmonitor-watchmanpre-applypatchpre-commitpre-merge-commitpre-pushpre-rebasepre-receiveprepare-commit-msgpost-updatepush-to-checkoutupdateGit can be told to look for hooks in a versioned directory:
git config core.hooksPath .githooks
org.danilopianini.gradle-pre-commit-git-hooks generates and installs hooks from the build scriptpre-commit, Husky, Lefthook): hooks declared in a versioned configuration file, installed with one commandgit commit --no-verify)
danilo.pianini@unibo.itCompiled on: 2026-11-30 — printable version