← Git

Coding challenge

Challenge 004 - Branches and merge

Scenario

You are going to simulate the most common team workflow: create a feature branch, work on it, and then integrate it into main with a merge. In the end, main must contain the feature's work and the feature branch can be deleted.

Starting point: a repo with at least one commit on main.

How to solve it

# 1. Start from an up-to-date main and create the feature branch
git switch main
git switch -c feature/saludo
# We create and switch to feature/saludo in a single step

# 2. Make changes on the feature branch
echo "console.log('Hola equipo')" > saludo.js
git add saludo.js
git commit -m "feat: agrega script de saludo"

# 3. Go back to main to integrate the feature
git switch main

# 4. Merge the feature into main
git merge feature/saludo
# If main did not move forward, it will be a fast-forward (just moves the pointer)
# If main moved forward, a merge commit is created

# 5. Delete the already-integrated branch
git branch -d feature/saludo

Why it works

Working on a separate branch keeps main stable while you develop. The merge, run from the target branch (main), brings in the feature's work. If main received no new commits, it is a fast-forward; if it did, a merge commit is created. Once integrated, the feature branch has served its purpose and -d deletes it safely (it only allows deletion if it is already merged).

Full solution

View commented solution
# Create and work on the feature branch
git switch main
git switch -c feature/saludo
echo "console.log('Hola equipo')" > saludo.js
git add saludo.js
git commit -m "feat: agrega script de saludo"

# Integrate into main
git switch main
git merge feature/saludo

# Verify that the file reached main
ls
# saludo.js appears here

git log --oneline
# shows the feature commit on main

# Clean up the already-integrated branch
git branch -d feature/saludo
# -d only deletes if it is already merged (safe)
# -D forces the deletion even if it is not merged (careful)

Key point: the merge is done from the branch you want to integrate into (main), not from the feature. Delete already-integrated branches with -d to keep the repo clean.