Back to the catalogue Courses

Git: version control and collaboration

Master commits, branches, merges and recovery to work with others without losing history.

MDJAD Intermediate 12 min read

Objectives and prerequisites

By the end of this course, you will be able to version a project with Git, read its history, create and merge branches, collaborate with a remote repository and undo a change without losing others' work. The common thread is the Mdjad catalogue repository, modified by two people.

Prerequisites: use a terminal and edit a file. No prior Git knowledge is required. The examples use Git 2.40 or later, on the command line, with a local repository and a fictional remote.

Path: chapters 1 to 3 establish the model and basic commands; chapters 4 and 5 cover branches and remote work; chapter 6 covers undoing; chapters 7 and 8 cover collaboration, tags and synthesis.

Convention: commands run in a lab repository. Outputs are shortened. Never force-push a shared branch without agreement. Destructive commands are flagged and assume a backup or a history that allows recovery.

1. Why version, and what Git records

Git records snapshots of file state. A commit contains a reference to a file tree, an author, a date and a message. Commits form a graph: each commit points to its parent or parents. This structure allows history to be recovered and branches to be created without copying the whole project.

Three areas coexist: the working tree, the index (staging area) and the repository. You modify files in the working tree, select changes with git add, then create a commit with git commit. A change not added does not enter the commit.

$ git init catalogue
$ cd catalogue
$ printf '# Mdjad catalogue\n' > README.md
$ git status
On branch master
No commits yet
Untracked files:
  README.md

$ git add README.md
$ git commit -m "docs: initialise the catalogue"
[master (root-commit) 1a2b3c4] docs: initialise the catalogue
 1 file changed, 1 insertion(+)

The index lets you compose a clean commit. If you changed two files for two different reasons, add and commit them separately. A commit should tell one intention, not a mixture of unrelated work. This makes review and rollback easier.

A Git repository contains a .git directory with objects, references and configuration. Do not edit these files by hand. Objects are addressed by a hash; the same content produces the same hash. Git can therefore store nearby versions efficiently.

Finally, versioning is not backup. A local repository can be lost with the disk. A remote adds a copy and a collaboration point, but does not replace a tested backup. Backup strategy and Git strategy are complementary.

2. Configure and read the state

Git uses an identity for commits. Configure a name and email globally or locally. The email should be the one you want in history. Local repository configuration can differ from global configuration.

$ git config --global user.name "Kelia M."
$ git config --global user.email "kelia@example.test"
$ git config --global init.defaultBranch main
$ git config --list --show-origin | head

git status shows the current branch, tracked or untracked files, and staged or unstaged changes. git diff shows unstaged changes; git diff --staged shows what will go into the next commit. Read the diff before committing.

$ git status --short
 M README.md
?? notes.txt

$ git diff
diff --git a/README.md b/README.md
--- a/README.md
+++ b/README.md
@@ -1 +1,2 @@
 # Mdjad catalogue
+Catalogue description.

git log shows history. --oneline condenses, --graph draws branches, --all includes all references. git show <commit> shows a commit's content. git log -p -- README.md follows one file.

Ignored files are declared in .gitignore. Ignore build artefacts, installed dependencies, local environment files and secrets. A file already tracked does not disappear because it is added to .gitignore: remove it from the index with git rm --cached.

Finally, an empty .gitkeep file lets you version an empty directory. Large binary files should use Git LFS or be stored elsewhere. A repository containing gigabytes of images becomes slow and hard to clone.

3. Commits, messages and useful history

A good commit message has a short summary line, then a body explaining why. The conventional commits style — feat:, fix:, docs:, refactor:, test: — makes reading and automation easier. The message must remain understandable without the diff.

$ git add src/Cart.php tests/CartTest.php
$ git commit -m "feat(cart): merge lines for the same product" -m "Adds a quantity instead of creating a duplicate line. Covered by a test."
$ git log --oneline --graph --decorate -5
* 7f9e2a1 (HEAD -> main) feat(cart): merge lines for the same product
* 3c4d5e6 test(cart): cover the empty cart
* 1a2b3c4 docs: initialise the catalogue

A commit must be coherent: the code compiles, tests pass, the message matches. Committing broken code "to save" pollutes history and complicates bisect. Use a branch or a stash for temporary work.

git commit --amend fixes the last local commit. Do not use it on a commit already pushed and shared: you rewrite history and force others to resolve an artificial conflict. For a shared commit, create a new corrective commit.

git log -S"pattern" searches for when a text appeared; git blame shows the last change to each line. git bisect finds the commit that introduced a bug by dichotomy. These tools turn history into a diagnostic tool.

Finally, do not version secrets. If a password was committed, removing it from the last commit is not enough if it was pushed: the object remains in history. Revoke the secret, clean history with a dedicated tool and notify the team. Rotating the secret comes first.

4. Branches and merging

A branch is a moving reference to a commit. Creating a branch does not copy files; it creates a name that advances with commits. git switch -c feature/cart creates and switches to a branch. git branch lists local branches.

$ git switch -c feature/cart
Switched to a new branch 'feature/cart'
$ printf 'class Cart {}\n' > src/Cart.php
$ git add src/Cart.php
$ git commit -m "feat(cart): add the Cart class"
[feature/cart 8a9b0c1] feat(cart): add the Cart class

Merging integrates one branch into another. git switch main then git merge feature/cart. If main has not advanced, Git performs a fast-forward: it simply moves the reference. Otherwise, it creates a merge commit with two parents.

$ git switch main
$ git merge feature/cart
Updating 1a2b3c4..8a9b0c1
Fast-forward
 src/Cart.php | 1 +
 1 file changed, 1 insertion(+)

A conflict occurs when both branches modify the same area. Git marks the file with <<<<<<<, ======= and >>>>>>>. Edit the file to keep the correct combination, remove the markers, then git add and git commit. Do not choose "take everything" without understanding.

<<<<<<< HEAD
$total = $price * $quantity;
=======
$total = $price * $quantity + $shipping;
>>>>>>> feature/shipping

A short branch limits conflicts. Regularly integrate the main branch into your branch, or rebase a local unshared branch. Rebase rewrites commits: do not use it on a branch others use.

Finally, delete merged branches with git branch -d. An unmerged branch requires -D, which forces deletion: check that the work is integrated or backed up. Remote branches are deleted with git push origin --delete, with team agreement.

5. Remote repository, fetch, pull and push

A remote repository is a copy hosted on a server. git remote add origin <url> registers it. git fetch downloads objects and updates remote references without changing your working branch. git pull combines fetch and integration.

$ git remote add origin https://example.test/mdjad/catalogue.git
$ git fetch origin
$ git switch -c main --track origin/main
$ git pull --ff-only
Already up to date.

git push -u origin main pushes the branch and configures tracking. Then git push is enough. A push is refused if the remote branch has advanced: fetch, integrate, test, then push. Do not force without understanding what you overwrite.

A tracking branch associates a local branch with a remote branch. git status shows ahead or behind. git branch -vv shows associations. Without tracking, a git pull may ask for an additional target.

The choice between merge and rebase for integrating a remote branch depends on team policy. Merge preserves the exact history; rebase produces a linear history but rewrites commits. For a shared branch, prefer merge. For a personal branch, rebase may be accepted.

Finally, protect the main branch: required review, automated tests, no direct push. These rules are configured on the forge, not in local Git. They reduce the risk of breaking the shared branch. Document the procedure in the README.

6. Undo without losing everything

Before undoing, identify the state: unstaged change, staged change, local commit, pushed commit. Each situation has a different command. A destructive command can erase uncommitted work; check with git status and git diff.

# Undo an unstaged change to one file
$ git restore README.md

# Remove a file from the index without losing the change
$ git restore --staged README.md

# Undo the last local commit, keeping changes staged
$ git reset --soft HEAD~1

# Undo the last local commit and return changes to the working tree
$ git reset --mixed HEAD~1

git reset --hard erases staged and unstaged changes. It does not touch untracked files. Use it only when you are sure you want to lose the work. git clean -n shows untracked files that would be deleted; git clean -f deletes them.

git revert <commit> creates a new commit that undoes the effects of an already shared commit. It is the safe command for public history: it erases nothing. git reset rewrites history and is not suitable for a shared branch.

git reflog records HEAD movements. After an unfortunate reset, it often allows the old commit to be found. git switch -c rescue <hash> creates a rescue branch. The reflog is local and time-limited; do not rely on it as a backup.

Finally, stash sets aside uncommitted changes: git stash push -m "wip", then git stash list and git stash pop. A stash is not a branch and is not pushed. For long work, create a work branch rather than a forgotten stash.

7. Collaborate: branches, review and conventions

A simple flow: update the main branch, create a short branch, commit in small steps, push, open a merge request, get a review, integrate, delete the branch. This flow reduces conflicts and makes review possible.

$ git switch main
$ git pull --ff-only
$ git switch -c fix/price-rounding
$ git add src/Money.php tests/MoneyTest.php
$ git commit -m "fix(price): round to the nearest cent"
$ git push -u origin fix/price-rounding

A pull request describes the problem, the solution, the tests run and the risks. A useful review checks behaviour, edge cases, security and readability. "LGTM" without reading is not a review. The reviewer must be able to reproduce the tests.

Team conventions must be written: branch names, commit format, change size, definition of done. A small change is easier to review and revert. A thousand-line change often mixes several topics.

Merge conflicts are resolved locally before the request. Do not ask the reviewer to untangle an unresolved conflict. If the main branch has advanced, integrate it and re-run tests. A conflict resolved without tests is a source of regression.

Finally, protect secrets and personal data in commits and requests. A local configuration file, a log or a screenshot may contain sensitive information. Use fictional examples and an ignored environment file.

8. Tags, releases and synthesis

A tag marks an important commit, often a version. An annotated tag contains a message, author and date: git tag -a v1.0.0 -m "Version 1.0.0". git push origin v1.0.0 publishes the tag. A lightweight tag is a simple reference without metadata.

$ git tag -a v1.0.0 -m "Catalogue: first public version"
$ git show v1.0.0 --stat
$ git push origin v1.0.0

$ git log --oneline --decorate -3
* 9f8e7d6 (HEAD -> main, tag: v1.0.0) docs: prepare the release
* 8a9b0c1 feat(cart): add the Cart class
* 1a2b3c4 docs: initialise the catalogue

A release describes changes, migrations, precautions and the rollback procedure. A version number helps users know what they install. Do not move a published tag: create a new version.

The synthesis of the common thread: the repository contains readable history, short branches, coherent commits, reviews and tags. Each change can be explained, tested and undone. Git is not only a backup; it is a collaboration and diagnostic tool.

Frequent mistakes are committing secrets, force-pushing a shared branch, resetting public history, giant commits, vague messages and forgotten branches. Each has a simple prevention: ignores, branch protection, conventions and review.

Finally, practise recovery: simulate a reset, find the commit with reflog, undo a shared commit with revert. Knowing how to repair is more important than knowing every option. Clear history and tested backups make mistakes reversible.

9. Rebase, cherry-pick and integration choices

A merge preserves branches and may create a merge commit. A rebase replays your commits onto a new base to produce a linear history. Use rebase to update a local branch that only you manipulate; do not rewrite an already shared branch without coordination, because commit identifiers change.

git cherry-pick <commit> applies one specific change to the current branch. It is useful for carrying a targeted fix, but it duplicates the commit and does not replace a branching strategy. Before any integration, fetch remote references, inspect the diff, run the tests and be able to explain why merge, rebase or cherry-pick is the right choice.

10. Diagnose history and automate quality

git bisect uses binary search to find the commit that introduced a regression between a known good version and a bad one. The method becomes powerful when every commit is runnable and the regression test can be automated. git blame is a starting point for finding the context of a line, not a tool for assigning blame.

In a team, the remote platform complements Git with branch protection, required reviews and continuous integration. The pipeline should at least verify tests, static analysis and the build before merging. These safeguards do not replace attentive review; they make acceptance criteria explicit and keep known failures away from the main branch.

Exercise 1 — First repository

Create a repository, a README.md file, stage it and commit. Show the state before and after the commit. What does "untracked" mean?

Solution

git init creates the repository; git status shows README.md as untracked, meaning not tracked. git add places it in the index; git commit records the snapshot. After the commit, the state is clean. An untracked file is not included in commits until added.

Exercise 2 — Read a diff

Modify two lines of a file, show git diff, stage only one change and show git diff --staged. Explain the difference between the two outputs.

Solution

git diff shows unstaged working-tree changes. git diff --staged shows what is in the index and will go into the next commit. After staging only part, the two outputs complement each other: one shows the remainder, the other shows what is ready.

Exercise 3 — Branch and merge

Create a branch, add a file, commit, return to the main branch and merge. Check history with --graph. Why is the merge a fast-forward?

Solution

The main branch has not advanced since the branch was created. Git can therefore move the reference without creating a merge commit: that is a fast-forward. git log --oneline --graph --all shows the line. If the branches had diverged, a merge commit would have been necessary.

Exercise 4 — Resolve a conflict

Two branches modify the same line. Trigger the conflict, identify the markers, choose a correct combination, then finish the merge. What must you do before committing?

Solution

After git merge, Git marks the area with <<<<<<<, ======= and >>>>>>>. Edit to keep the desired combination, remove the markers, then git add. Before committing, run tests and reread the diff; a resolved conflict can be syntactically valid but functionally wrong.

Exercise 5 — Undo cleanly

You committed an extra file locally. Undo the commit while keeping the changes, remove the file from the index, then commit again. Which command would you use if the commit had already been pushed?

Solution

git reset --soft HEAD~1 undoes the commit while keeping the index; git restore --staged file removes the file from the index; a clean new commit follows. If the commit is already pushed, use git revert <commit>: it creates an inverse commit without rewriting shared history.

Exercise 6 — Collaboration and tag

Create a branch, push it, open a fictional merge request, then tag the merged version. What information must the merge request contain?

Solution

The request describes the problem, solution, tests run, risks and review points. The branch is short and up to date. After merging, git tag -a v1.1.0 -m "..." marks the commit, then git push origin v1.1.0. A published tag must not be moved.

Capstone — catalogue history

Deliver a lab repository with: a history of six coherent commits, a merged feature/cart branch, a resolved and documented conflict, a v1.0.0 tag, a .gitignore file and a README describing the collaboration flow. Add a note explaining an undo with revert and a recovery with reflog.

Grading: clear messages; coherent commits; no secret; resolved and tested conflict; described branch protection; annotated tag; rollback procedure; readable history with --graph.

Common mistakes and recovery method

Classic mistakes: committing a secret, force-pushing a shared branch, using reset --hard without a backup, rebasing a public branch, creating giant commits, leaving branches behind, and ignoring an already tracked file without removing it from the index.

Method: before any undo, git status, git diff and git log --oneline --graph. To find a lost commit, git reflog. To undo a shared commit, git revert. For an untracked file deleted by mistake, look for a backup or a stash; Git does not know what it never tracked.

Self-assessment

You must be able to explain the three areas, read a diff, write a commit message, create and merge a branch, resolve a conflict, fetch a remote branch, undo a local or shared commit, and publish a tag.

Self-assessment: I can find a commit with reflog; I can explain the difference between merge and rebase; I can refuse a force-push; I can check that a secret is not versioned. To go further, study branch protection, team workflows and commit signing.

References