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
Général
Initial Setup
git config --global user.name "FirstName LastName"
git config --global user.email "your-email@exemple.com"

git config --global user.name "FirstName LastName" associates your name with all your future commits.
git config --global user.email "your-email@exemple.com" associates your email address. This is what allows GitHub/GitLab to link the commit to your user account.
Set aside unfinished work
git stash -u

The -u option includes newly created files that are not yet tracked by Git
Very useful for clearing out your working directory without having to make a “draft” commit. The project instantly becomes “clean” again, and you can switch branches once more
To pick up where you left off, return to the relevant branch and restore the files exactly as they were: git switch feature/branchName git stash pop The pop command reapplies the changes and automatically removes the temporary stash from Git's memory.
Essential variants to know
git stash list: Displays a list of all your temporary stashes (if you have created multiple ones).
git stash apply : Like pop, but keeps the stash in Git’s memory instead of deleting it (useful if you want to apply the changes to multiple branches).
git stash drop: Deletes the last temporary stash without applying it (if you ultimately decide to discard the draft).
Check settings
git config --list

Displays all active settings combined (local and global)
Useful for debugging strange behavior or checking where a setting comes from.
To see the exact path of the file where the setting originates, use: git config --show-origin --list Very handy for determining whether a setting is locked at the Local or Global level
Set up Git for a clean history
git config --global pull.rebase true

Force Git to perform a rebase instead of a merge every time you run a git pull
This prevents the creation of unnecessary merge commits and keeps the history clean.
This command configures Git's behavior during automatic synchronizations with servers.
Branch
Count local branches
git branch --format='%(refname:short)' | wc -l

Counts local branches in the 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 tracking
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 newFeature

Creates a new branch and switches to it immediately.
git checkout 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
List and delete remote branches
git branch -r
git push origin --delete branchName

The command lists all remote branches that Git cached during the last sync
Delete remote branches in 3 steps
1. The command returns the list of branches: origin/fix/install-crane-watch-image origin/feature/autoPR-watch-distroless origin/feature/improve-staging-add-scan-image 2. Delete a single branch with: git push origin --delete fix/install-crane-watch-image Or, delete multiple branches: git push origin --delete feature/autoPR-watch-distroless \ feature/improve-staging-add-scan-image 3. Local-to-remote synchronization with: git fetch -p
Delete a local branch
git branch -d branchName

Deletes a local branch safely.
Show modified files between branches
git diff branch1..branch2 --name-only

Shows differences between two branches.
CI/CD
git clone --depth 1

Performs a shallow clone by downloading only the most recent state of the project, without retrieving the full history of past changes. Ideal for speeding up CI/CD pipelines
Real-World Example
Let’s imagine a corporate project that has been in existence for 5 years: Its history contains 20,000 commits. The entire repository is 2 GB. The current code (the latest commit), however, is only 50 MB.
You must either configure the pipeline step with this command (Jenkins, standalone Shell scripts, or Cron jobs, in the Dockerfile, etc.) or configure the deployment bot.
GitHub Actions : Uses the action actions/checkout which performs this optimization in the background.
GitLab CI : Uses an internal variable. By default, it performs an optimized git fetch, which can be adjusted in the pipeline with the variable GIT_DEPTH: “1”
Limitations

Shallow cloning is perfect for machines, but has limitations for humans:

Incomplete git log: If you type git log, you will see only a single commit (the latest one)
Rebase/Merge Issues: It is very difficult (if not impossible) to perform complex merges or rebases on a --depth 1 clone because Git lacks the ancestor commits needed to calculate the differences
Set permissions for a file from the Git history
git update-index --chmod=+x ci-script/install-trivy.sh

Make the script executable directly in the Git history. It grant permission for the “ci-script/install-trivy.sh” script to run before using it in workflow steps. It simplify steps by calling the script directly during the run.
Don't forget to commit the changes. Git immediately detects that the file's metadata has changed. Finish by running git push to send it to the server.
Check a file's status in Git
If you want to check whether Git considers a file to be executable or not, use the command: git ls-files --stage ci-scripts/install-trivy.sh If the result starts with 100644: The file is not executable
If the result starts with 100755: The file is executable, or has been made executable.
By default, Windows does not support Linux execution permissions (chmod +x). Git saves the file with the default permissions (non-executable). When Linux downloads the file, it refuses to run it for security reasons. Instead of switching to a Linux machine to fix the file, we force Git to store the executable permission directly in its index
Push an empty commit (triggers workflows)
git commit --allow-empty -m "Trigger CI/CD pipeline" && git push

Not only used in CI, git commit --allow-empty forces Git to create a commit, even if no files have been modified, added, or deleted.
As with every commit, -m “...” adds a required (explicit) commit message
&& git push pushes the commit to your remote server (GitHub, GitLab, etc.).
This technique is very common for manually restarting a pipeline that has stalled or failed due to an external factor (for example, an unavailable third-party API or a network issue on the runner), without having to modify the application code.
Retrieve the short SHA-1
git rev-parse --short HEAD

Retrieves raw information such as the SHA-1 hash of the current commit.
A very useful command for tagging Docker images in CI/CD.Example: docker build -t myapp:$(git rev-parse --short HEAD) .
Tag a specific point in the history
git tag -a v1.0.0 -m "Release production"

Mark a specific point in the history (here: v1.0.0) followed by the commit message
Simple to create and essential for version control, this command sets a fixed, named marker (a tag) on the commit to officially mark a version of your application.
3-step procedure
1: Create the tag (locally): git switch main git tag -a v1.0.0 -m “Release production” -a: Creates an “annotated” tag (recommended). It contains the date, the author's name, and a message.
--m: Adds the version description message.
2: Verify that the tag is configured correctly using: git tag
To view the tag's specific details (author, date, message), use: git show v1.0.0
3: Push the tag (to the remote server)
Note: A standard git push never sends tags to GitHub/GitLab. You must explicitly tell it to send them:
Option 1: Push only this specific tag (Recommended for CI/CD) with git push origin v1.0.0
Option 2: Push all your local tags at once with git push origin --tags
in CI/CD
As soon as you push the tag, the CI/CD tool being used (GitLab CI, GitHub Actions) will detect it and trigger a specific automated pipeline that will:
  • Compile the code from
Commit
Copies a specific commit and applies it to the current branch (cherry-pick)
git cherry-pick a1b2c3d4

Allows to select a specific commit—in this case: a1b2c3d4 from a branch and copy it (as if picking a cherry) to the current branch, without merging the rest.
Step-by-step guide to git cherry-pick
example: Extract only the fix commit to bring it to the production branch.
1. Switch to the branch that should receive the fix: git switch main
2. Pick the cherry with: git cherry-pick a1b2c3d4
3. You're done! Git has replicated the patch's changes to main and created a brand-new, clean commit. All that's left is to push to production with: git push origin main
What to watch out for
Conflicts: If the code surrounding the change differs significantly between the two branches, Git will stop and ask you to resolve the conflict (just like during a rebase or merge).
History duplicates : The copied commit will have a new SHA-1 identifier on the main branch. To Git, these are now two separate commits, even though they do the same thing.
Squash multiple commits
git rebase -i HEAD~5

Allows you to merge multiple commits into a single commit.
Useful for cleaning up the history before pushing
Opens a text editor (Vim/Nano) listing the last 5 commits, from oldest to newest. Before each commit, you can replace the word pick with an action to modify the history.
pick (or p): Keeps the commit as is (default behavior).
reword (or r) : Keeps the commit, but pauses to let you edit its message (useful for correcting a spelling mistake).
edit (or e): Pauses on this commit to let you edit its content (add/delete lines of code).
squash (or s): Merges the commit with the commit immediately above it (the previous one). Git will then ask you to combine the messages.
drop (or d) : Completely deletes the commit and all the changes it contained.
The chronological order is reversed : in the rebase editor, the oldest commit is at the top and the most recent at the bottom (unlike git log).
The safety net : If you make a mistake along the way, immediately type the emergency command git rebase --abort
Hard reset to a specific commit
git reset --hard abc123

Forces the entire repository (files and history) to revert to the exact state of the specified commit (e.g., abc123).
To permanently delete the most recent commit and discard all associated changes, use: git reset --hard HEAD~1
These commands permanently delete the current work. The working directory and index are overwritten to match the target commit exactly.
Safe commit resets (--mixed, --soft)
git reset HEAD~1

Cancel the commit, but the modified files revert to “changes not staged for commit”
Equivalent to git reset --mixed HEAD~1
Moves HEAD and the current branch to the previous commit
The staging area is cleared (unstaged), but the working directory remains unchanged
To undo the last commit but keep the changes staged, use: git reset --soft HEAD~1 The files remain in the “Ready to be committed” (staged) state.
These commands undo commits in the history but preserve your modified files so you can rework the code.
Amend last commit (no message edit)
git commit --amend --no-edit

Modifies the last commit without editing its message.
Revert a commit
git revert abc123

Creates a new commit that reverts a previous one.
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
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
Log
List/filter commits
git log --oneline

Displays each commit on a single line (short SHA + message)
To view the last “n” commits graphically, use: git log --oneline --graph -10
To view the latest commit on the current branch, use: git log -1
To find commits by a specific author, use: git log --author=“Alice”
These commands provide a quick, visual overview of the project's timeline.
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