Tech & DevOps HubEspace Tech & DevOps

Explorez le monde du Dev, du Cloud et des outils DevOps à travers nos articles et discussions Explore the world of development, the cloud and DevOps tools
 FR      EN
Git
Branch
Set tracking for remote branch
git branch --set-upstream-to=origin/branchName branchName

Process
Make sure you have the latest information by running git fetch
Next, to create a local branch that tracks an existing remote branch, use: git branch --set-upstream-to=origin/my-remote-branch my-local-branch The local branch “my-local-branch” will then be configured to track “origin/my-remote-branch”
If you create a new local branch and want to enable tracking on the first push, use: git push --set-upstream origin
This command pushes the “my-local-branch” branch to the remote repository and, at the same time, configures the local branch to track the newly created branch.
Create and switch to a branch
git switch -C prefix/branch-name

Creates a new branch and switches to it immediately.
git checkout -b is not removed: it is still necessary for other uses (restoring files, positioning yourself on a specific commit, etc.).
git switch only covers the “branch management” part of git checkout.
See also: git-switch-vs-git-checkout
Liste and count branches
git branch | wc -l

Counts the total number of local branches in the current Git repository.
Remote branches: git branch -r | wc -l (run `git fetch` first)
Local & Remote: git branch -a | wc -l
git branch -vv displays the current commit for each branch and its remote reference
To use the command in a script, use:
git branch --format=“%(refname:short)” to list branches in a completely ‘clean’ format: without an asterisk before the current branch, without leading spaces at the start of lines, and without invisible colour coding that could interfere with copy-and-paste or a script.
Clean up obsolete branches
git fetch --prune

This command updates the list of branches and locally removes references to remote branches that have been deleted on the server.
First, use: git fetch to update the local list of remote branches.
Automate the clean-up using the command with: git config --global fetch.prune true
Renaming a branch
git branch -m prefix/new-name

Use this command if you are on the branch (locally)
If you are on a different branch (locally): git branch -m prefix/old-name prefix/new-name
If the branch already exists on the remote repository. After renaming it locally: git push origin -u prefix/new-name
If you wish to delete the old remote branch name: git push origin --delete prefix/old-name
Please note: if this branch already has an open Pull Request, check that it is pointing to the new branch name after the renaming.
Delete a remote branch
git push origin --delete prefix/branch-name

This command permanently deletes a branch on the remote server
Use the following commands in order:
git fetch to download the latest changes, branches and commits from the remote repository.
git branch -r to list all remote branches.
Once you have the list, use the delete command.
For a multi-line command, add a [space]\ backslash at the end: git push origin --delete prefix/branchName \
prefix/branchName2 \
Delete a local branch
git branch -d prefix/branch-name

This command deletes one or more local branches
Use the following commands in order:
git branch to list all local branches.
Once you have the list, use the delete command.
For multiple lines, add a [space]\ backslash at the end: git branch -d prefix/branchName \
prefix/branchName2 \

Use -D to force deletion (even if not merged).
Show modified files between branches
git diff branch1..branch2 --name-only

Shows differences between two branches.
Commit
Apply a specific commit to the current branch
git cherry-pick <commit-hash>

Allows you to copy a specific commit from another branch and apply it to the current branch. This is the equivalent of a targeted ‘copy and paste’ of a single change.
1. Retrieve the commit hash from the branch containing the commit you wish to copy, and view the history using git log --oneline to copy its identifier (the 7- or 40-character hash)
2. Switch to the destination branch and run the command git cherry-pick a1b2c3d
List commits (oneline)
git log --oneline

Shows commit history in a compact format.
Amend last commit (no message edit)
git commit --amend --no-edit

Modifies the last commit without editing its message.
Hard reset to a specific commit
git reset --hard abc123

Resets repository state to a specific commit.
Hard reset to previous commit
git reset --hard HEAD~1

Resets the repository to the previous commit.
Mixed reset last commit
git reset HEAD~1

Resets working tree without removing changes.
Soft reset last commit
git reset --soft HEAD~1

Restores staging area while keeping file changes.
Revert a commit
git revert abc123

Creates a new commit that reverts a previous one.
Squash multiple commits
git rebase -i HEAD~5

Squashes multiple commits into a single one.
Show last 10 commits (graph)
git log --oneline --graph -10

Displays the latest commits in a visual graph format.
Show files changed between commits
git diff abc123 def456 --name-only

Shows file changes between two commits.
Show last commit
git log -1

Displays metadata of the most recent commit.
Show commits by author
git log --author="Alice"

Shows all commits made by a specific author.
History
Change commit author
git filter-repo --mailmap new-author.txt

Before running the command, create a mapping file named ‘new-author.txt’ in the project root directory and enter the replacement rule in the following format: New Name nouvel.email@example.com Old Name ancien.email@example.com
If you want to target by email only (without checking the name), write: New Name nouvel.email@example.com ancien.email@example.com
Search text in commit history
git log -S "keyword"

Search for all commits that added or removed the word or string
Very useful for security audits or for tracking down lost sensitive data«
To search for a string or a regular expression in code changes and across the entire commit history, use: git log -G »regex"
Differences: -G vs -S
git log -G “regex”: Detects all commits where the regular expression appears in the “diff”, even if the total number of occurrences of that text in the file remains the same
git log -S “string” (the “Pickaxe”): More restrictive. It only finds a commit if the searched-for word has been added to or removed from the file
Recover lost commits
git reflog

Displays the local history of all HEAD movements, useful to recover deleted commits or branches.
The result displays a list like this, from most recent to oldest: a1b2c3d HEAD@{0}: checkout: moving from feature to main
9j8k7l6 HEAD@{2}: commit (amend): Fixed display bug

To recover a deleted commit:
Option A (Safe) – Create a new branch from this commit:
git branch rescue-branch a1b2c3d
Option B (Direct) – Force your current branch to revert to this state using: git reset --hard a1b2c3d
Note: The reflog is not sent to the server (GitHub/GitLab). It only shows what you have done locally, on your computer.
It is not permanent: Git automatically clears the reflog after 30 to 90 days. It is a tool for rectifying recent errors.
Removing a file from Git
git rm filename

This command is usually run after the file has been deleted locally. It removes the file from Git’s tracking.
If you want to remove the file from Git BUT keep it on your computer, use: git rm --cached filename
In both cases, to permanently save this change, you must commit the change using: git commit -m ‘Removing filename’
Remove file from history
git-filter-repo --path PATH-TO-YOUR-FILE --invert-paths --force

Permanently deletes the specified file from the entire Git repository history.
GitHub repository: git-filter-repo
Alternatively, follow the steps described at bfg-repo-cleaner/#usage
Release
Create a signed release tag
git tag -s v1.0.0 -m "Release version 1.0.0"

Crée un tag immuable et signé cryptographiquement avec GPG pour certifier l'authenticité d'une version en production.
Stash
Applying a specific stash
git stash apply "stash^{/stash-name}"

First, list the saved stashes using: git stash list, then run the command apply
If the stash you wish to retrieve is unnamed, use: git stash apply stash@{0}: using its unique identifier
Difference between `apply` and `pop`:
git stash apply ‘stash^{/stash-name}’: applies the changes and keeps the stash in the list.
git stash pop ‘stash^{/my-stash}’: applies the changes and removes the stash from the list.
List stashes
git stash list

Example result:
stash@{0}: On main: form display bug fix
stash@{1}: On development: WIP: profile page development
stash@{2}: On main: my-stash

stash@{0} is the unique identifier for the stash (the most recent is always {0}).
On main, On ..: is the branch we were on when we created the stash.
stash-name or WIP: ... is the name (descriptive message) given to the stash.
Stash current changes
git stash -u

Allows you to temporarily save your unfinished changes so that you can return to a clean working directory, before reapplying them later.
The -u option includes new files not tracked by Git, ensuring you don’t forget them.
You can switch to another main branch (e.g. main or master), fetch the latest changes, then return to your working branch to merge the updates, for example, before retrieving the work you’d set aside.
Tip: If you do this often, name the stash as follows: git stash push -m ‘stash-name’
Apply and remove last stash
git stash pop

Restores the most recently stashed changes and removes them from the stash list.
Permanently delete all stashes
git stash clear

Warning: this command cannot be undone. Make sure you haven’t stashed anything important before running it.
Deleting a specific stash
git stash drop stash@{1}

This command uses the identifier (e.g. stash@{1}) with the drop command,
If you want to delete it by name, use: git stash drop ‘stash^{/my-stash}’