devHọc Dev

Week 1 - Day 2: Remote, Merge vs Rebase and Undo/Recovery

Week 1 – Day 2

This lesson combines 3 topics: Remote Repositories — Working with a Team, Merge vs Rebase — The Most Important Decision, Undo and Recovery — Rescuing "Lost" Data.

Learning Objectives

  • Configure and manage remotes with git remote
  • Distinguish fetch, pull, push and when to use each
  • Understand tracking branches and upstream
  • Understand pull --rebase vs the default pull
  • Know when to use --force-with-lease instead of --force
  • Deeply understand the difference between a merge commit and a rebase
  • Master the "golden rule of rebasing": don't rebase published branches
  • Practice conflict resolution: from the basics to abort/continue
  • Know when to choose merge and when to choose rebase
  • Distinguish git reset --soft/--mixed/--hard and when to use each
  • Use git revert to undo safely on a shared branch
  • Use git restore to discard changes in the working dir/staging
  • Rescue "lost" commits with git reflog
  • Use git stash to temporarily save work in progress

Part 1: Remote Repositories — Working with a Team

1. What is a remote?

A remote is a name given to the URL of another repository — usually GitHub, GitLab or Bitbucket. When you clone, Git automatically creates a remote named origin.

LocalrepositoryRemote(GitHub)┌─────────────────────┐┌─────────────────────┐│main│push/fetch│origin/main││feature/auth│◄──────────►│origin/feature/...││refs/remotes/││││origin/main│└─────────────────────┘│origin/feature/│└─────────────────────┘Remote-trackingbranches(origin/main,origin/feature/...)arelocalcopiesoftheremotebranches—updatedonfetch.

2. Managing remotes

# Show the configured remotes
git remote -v
# origin  https://github.com/user/repo.git (fetch)
# origin  https://github.com/user/repo.git (push)

# Add a remote
git remote add origin https://github.com/user/repo.git
git remote add upstream https://github.com/original/repo.git

# Change a remote's URL (e.g. switch from HTTPS to SSH)
git remote set-url origin git@github.com:user/repo.git

# Remove a remote
git remote remove upstream

# Rename a remote
git remote rename origin github

# Show details of a remote
git remote show origin

3. git fetch — Download without merging

# Fetch all branches from origin
git fetch origin

# Fetch a specific branch
git fetch origin main

# Fetch all remotes
git fetch --all

# Fetch and remove remote-tracking branches deleted on the remote
git fetch --prune origin
# or configure auto-prune
git config --global fetch.prune true

After git fetch:

  • Remote-tracking branches (origin/main) are updated
  • Your local branches do not change
  • You can review the diff before merging: git diff main origin/main
# After fetching, see how the remote main differs from the local main
git fetch origin
git log main..origin/main --oneline    # commits on the remote not yet local
git log origin/main..main --oneline    # local commits not yet pushed to the remote
git diff main origin/main              # show the full diff

4. git push — Send to the remote

# Push the current branch to the remote and set upstream
git push -u origin main
git push -u origin feature/auth
# -u = --set-upstream: next time just type git push

# Push after upstream is set
git push

# Push to delete a remote branch
git push origin --delete feature/old-branch

# Push tags
git push origin v1.0.0
git push origin --tags   # push all tags

# Push all branches (rarely used)
git push --all origin

--force-with-lease — A safer push than --force

# Scenario: you rebased and need to push to the remote branch
# (the remote branch and local no longer share the same history)

# DANGEROUS: --force overwrites without checking
git push --force origin feature/auth
# If a colleague pushed while you were rebasing → their commits are lost!

# SAFER: --force-with-lease
git push --force-with-lease origin feature/auth
# Git checks: does the remote-tracking ref (origin/feature/auth) match
# the actual remote? If someone pushed first → Git refuses, you must fetch first

# Rules:
# - NEVER force push to main/master/develop (shared branches)
# - Use force-with-lease only on PERSONAL branches (feature/ branches)
# - After a personal rebase → force-with-lease

5. git pull — Fetch + merge

git pull is a shortcut for git fetch + git merge (or git rebase).

# Default pull = fetch + merge
git pull origin main
git pull   # if upstream is set

# Pull with rebase instead of merge
git pull --rebase origin main
git pull --rebase

# See what will be pulled before pulling
git fetch && git log ..origin/main --oneline

Default pull vs pull --rebase

Scenario:youhavecommitC,theremotehascommitD(youdon'tknowaboutit)Statebeforepull:A──B──C←localmain└──D←origin/mainAftergitpull(default—merge):A──B──C──M←localmain(M=mergecommit)└──D──┘Aftergitpull--rebase:A──B──D──C'←localmain(CrebasedontopofD)^Differenthashbecausetheparentisdifferent

When should you use --rebase?

# Use --rebase when:
# - Working alone on a feature branch
# - You want linear history (no meaningless merge commits)
# - CI/CD requires linear history

# Make pull --rebase the default
git config --global pull.rebase true
# Or only for the current repo
git config pull.rebase true

# Use merge when:
# - You want to keep the "merged from upstream into the feature branch" context
# - The branch is shared (several people push to it)

6. Tracking Branches

A tracking branch is a link between a local branch and a remote branch. Once tracking is set, git push/git pull know which remote and which branch to sync with.

# When you clone, main automatically tracks origin/main

# Set upstream on the first push
git push -u origin feature/auth
# After that: git push and git pull work without arguments

# Show tracking info
git branch -vv
# main         abc1234 [origin/main] feat: add user login
# feature/auth def5678 [origin/feature/auth: ahead 2] feat: auth WIP

# Set tracking for an existing branch
git branch --set-upstream-to=origin/feature/auth feature/auth
# or shorter
git branch -u origin/feature/auth

# Create a local branch that tracks a remote branch
git switch --track origin/feature/auth
# creates local feature/auth tracking origin/feature/auth

7. Real-world remote workflow

Starting a new feature

# 1. Sync main first
git switch main
git pull --rebase origin main

# 2. Create a branch
git switch -c feature/payment-gateway

# 3. Work, commit
git add . && git commit -m "feat: add Stripe integration"

# 4. First push with -u
git push -u origin feature/payment-gateway

# 5. Subsequent pushes
git push

# 6. After the PR is merged, clean up
git switch main
git pull
git branch -d feature/payment-gateway
git push origin --delete feature/payment-gateway

Receiving your teammates' changes

# A colleague merged a PR into main
git switch main
git fetch origin
git log ..origin/main --oneline   # see what's new
git merge origin/main             # or git pull

# Update your feature branch after main has changed
git switch feature/my-feature
git rebase main   # rebase onto the latest main

Part 2: Merge vs Rebase — The Most Important Decision

1. Merge — Preserving history

Merge creates a new commit (a merge commit) with 2 parents, preserving the full context of both branches.

Beforemerge:main│A──B──C│└──D──E│feature/authAftergitmergefeature/auth:main│A──B──C──M(M=mergecommit,parents:CandE)│▲└──D──E
git switch main
git merge feature/auth
# Creates commit M with the message "Merge branch 'feature/auth'"

When to use merge:

  • Integrating a finished feature branch into main (creates a clear record)
  • Bringing changes from main into a long-running feature branch when you want to keep the context
  • Shared branches (used by several people)

2. Rebase — Rewriting history

Rebase "moves" your commits onto the tip of the target branch, producing linear history. Under the hood Git creates new commits (different hashes) with the same content.

Beforerebase:main│A──B──C│└──D──E│feature/authAftergitrebasemain(fromfeature/auth):main│A──B──C──D'──E'│feature/authD'andE'arenewcommits(differenthashes)withthesamechangesbuttheirparentisCinsteadofB
git switch feature/auth
git rebase main

# Then merge into main (will fast-forward)
git switch main
git merge feature/auth   # fast-forward, no merge commit

When to use rebase:

  • Updating a feature branch with the latest changes from main (instead of merging main into the feature)
  • Before opening a PR, so the history is clean and easy to review
  • Interactive rebase to clean up commits on a personal branch

3. Golden Rule of Rebasing

Never rebase a branch that has been pushed and that other people are using.

Why?

Scenario: feature/auth has been pushed, colleague B has checked it out

You (Dev A):
git rebase main         ← creates D', E' with new hashes
git push --force-with-lease origin feature/auth

Colleague B:
git pull origin feature/auth
# Git sees: the remote and local histories no longer share a parent!
# D and D' are different commits (even with the same content)
# → Nonsensical merge conflicts, duplicated history

Safety rules

OK to rebase:
- Commits that are only local, not yet pushed
- Personal branches (you are the only user)
- After telling the team NOT to use that branch during the rebase

Do NOT rebase:
- main, master, develop (shared branches)
- Branches that are pushed and colleagues are working on
- Any branch where you're not sure who is using it

4. Conflict Resolution

Conflicts during merge

git switch main
git merge feature/auth
# Auto-merging src/config.js
# CONFLICT (content): Merge conflict in src/config.js
# Automatic merge failed; fix conflicts and then commit the result.

# See which files have conflicts
git status
# both modified: src/config.js

# Content of the conflicted file:
<<<<<<< HEAD                        ← content from main (HEAD)
const timeout = 30 * 60 * 1000;
=======                             ← separator
const timeout = 60 * 60 * 1000;
>>>>>>> feature/auth               ← content from feature/auth

# Resolve: edit the file manually, remove the markers
const timeout = 60 * 60 * 1000;   // pick the feature/auth version

# Stage and complete the merge
git add src/config.js
git commit                          # Git fills in the merge commit message

# OR: abandon the merge entirely
git merge --abort

Conflicts during rebase

git switch feature/auth
git rebase main
# CONFLICT (content): Merge conflict in src/config.js
# error: could not apply abc1234... feat: update timeout

# See the conflicted file and resolve it
git status
# Unmerged paths:
#   both modified: src/config.js

# ... edit the file, remove the conflict markers ...

# Stage and continue the rebase
git add src/config.js
git rebase --continue
# Git applies the next commit; if there's another conflict → resolve again

# Abandon the rebase entirely
git rebase --abort   # returns to the state before the rebase

Conflict markers in detail

<<<<<<< HEAD
content of the branch you are on (HEAD)
||||||| original                    ← only appears when the diff3 conflict style is on
original content before either branch changed it
=======
content of the branch being merged/rebased
>>>>>>> branch-name

# Enable the diff3 conflict style to see the original base:
git config --global merge.conflictstyle diff3
# (Git 2.35+ has zdiff3 — a more compact variant of diff3)

5. Merge vs Rebase — Full comparison

CriterionMergeRebase
HistoryFully preservedLinear, easy to read
Merge commitYes (2 parents)No (fast-forward)
SafetySafe on shared branchesDangerous on published branches
TraceabilityClear feature contextHard to tell which feature a commit belongs to
git bisectWorks but more complexEasier with linear history
git revertCan revert a merge commitSimpler

Decision tree

Needtoupdateafeaturebranchwiththelatestmain?├──Branchusedonlybyyou→gitrebasemain└──Branchshared/pushedfortheteam→gitmergemainNeedtomergeafeatureintomain?├──Wanttoclearlysee"whenthisfeaturewasmerged"→--no-ffmerge├──Wantlinearhistory→rebasethefeaturefirst,thenmerge(fast-forward)└──GitHubPRsquashmerge→squash+merge(1commitforthewholefeature)

6. Some advanced rebase commands (preview of Day 3)

# Rebase the current branch onto main
git rebase main

# Rebase only the N most recent commits (interactive — covered on Day 3)
git rebase -i HEAD~3

# Rebase only some commits onto another branch
git rebase --onto new-base old-base branch

# Example: move feature/auth (currently based on develop) to be based on main
git rebase --onto main develop feature/auth

Part 3: Undo and Recovery — Rescuing "Lost" Data

1. Understand the state before undoing

Before undoing, always know WHAT you are undoing:

git status      # working dir and staging state
git log --oneline -5    # 5 most recent commits
git diff        # unstaged changes
git diff --staged   # staged changes

2. git reset — Move HEAD (and the branch pointer)

git reset moves HEAD and the branch pointer back to an older commit. The three modes differ in what happens to the staging area and the working directory.

State:HEAD│A──B──C←main└──stagingarea(somechanges)└──workingdir(morechanges)gitresetHEAD~1(i.e.resettoB)

--soft — Keep staging + working dir intact

git reset --soft HEAD~1
# HEAD moves to B
# Staging area: KEPT (plus the changes from commit C)
# Working directory: KEPT

# Result: C is "undone" but its content is still staged → easy to recommit

Use it when: you want to undo the last commit but keep the code to recommit it differently (e.g. split a large commit into smaller ones).

--mixed (default) — Keep working dir, drop staged

git reset HEAD~1
# or
git reset --mixed HEAD~1
# HEAD moves to B
# Staging area: staged changes CLEARED (C's content becomes unstaged)
# Working directory: KEPT

# Result: C is undone, the code is still in the files but not staged

Use it when: you want to reorganize what is staged and start staging from scratch.

--hard — Discard both staged and working dir

git reset --hard HEAD~1
# HEAD moves to B
# Staging area: CLEARED
# Working directory: CLEARED (files return to B's state)

# ⚠️ CANNOT be undone with Ctrl+Z — the changes are lost
# (unless you use git reflog to recover the commit hash)

Use it when: you want to drop the changes completely and return to an old commit.

Reset summary

Command                  HEAD  Staging  Working Dir
git reset --soft HEAD~1   ←     KEEP     KEEP
git reset --mixed HEAD~1  ←     CLEAR    KEEP
git reset --hard HEAD~1   ←     CLEAR    CLEAR

3. git revert — Safe undo for shared branches

git revert does NOT delete the old commit. Instead, it creates a new commit with the opposite change. It's safe because it doesn't rewrite history.

Beforerevert:A──B──C──D←maingitrevertC:A──B──C──D──C'←main^C'=committhatrevertsC(theoppositeofC)
# Revert a specific commit
git revert abc1234
# Git creates a new commit "Revert 'feat: add feature X'"

# Revert the most recent commit
git revert HEAD

# Revert a range
git revert HEAD~3..HEAD   # revert the 3 most recent commits

# Revert without auto-committing (to edit the message)
git revert --no-commit abc1234
git revert --no-commit def5678
git commit -m "revert: remove feature X and Y (security issue)"

# Revert a merge commit (you must specify the -m parent number)
git revert -m 1 <merge-commit-hash>
# -m 1 = keep parent 1's side (usually the main branch)

Reset vs Revert

git resetgit revert
HistoryRemoves commitsAdds a new commit
Safe on shared branchesNOYes
When to usePersonal branch, not yet pushedAlready pushed to a shared branch

4. git restore — Discard file changes

# Discard changes in the working dir (file returns to the staging or HEAD state)
git restore src/app.js
# ⚠️ CANNOT BE UNDONE — the changes are lost permanently (no trash)

# Unstage a file (back to unstaged, keep the changes in the working dir)
git restore --staged src/app.js

# Restore a file to the state of a specific commit
git restore --source=HEAD~2 src/app.js
git restore --source=abc1234 src/app.js

# Discard all changes in the working dir
git restore .
# ⚠️ EXTREMELY DANGEROUS — you lose all uncommitted changes

5. git reflog — The HEAD history "detective"

reflog records every position HEAD has ever been at, even after git reset --hard, including "lost" commits.

git reflog
# output:
# abc1234 HEAD@{0}: commit: feat: add payment
# def5678 HEAD@{1}: reset: moving to HEAD~1    ← this commit is "lost"
# 9a8b7c6 HEAD@{2}: commit: fix: resolve null ptr
# 1f2e3d4 HEAD@{3}: checkout: moving from feature/auth to main

# Recover the "lost" commit with reset --hard
git reset --hard def5678   # go back to that commit

# Or create a branch from the old commit
git switch -c recovery def5678

Rescuing a commit after git reset --hard

# Scenario: you accidentally ran reset --hard and wiped an important commit
git reset --hard HEAD~3   # oops!

# Rescue it with reflog
git reflog
# abc1234 HEAD@{1}: commit: ...  ← the commit you want back

git reset --hard abc1234   # restored!
# or cherry-pick
git cherry-pick abc1234

Reflog keeps data for 90 days by default (expired entries are garbage collected).

6. git stash — Temporarily save work in progress

git stash is a "temporary drawer" — it puts away unfinished code so you can switch to something else.

# Stash all changes (staged + unstaged)
git stash
git stash push -m "WIP: payment integration"   # with a message

# Also stash untracked files
git stash --include-untracked
git stash -u   # shorthand

# List stashes
git stash list
# stash@{0}: WIP on feature/auth: abc1234 feat: add login
# stash@{1}: WIP: payment integration

# Apply the most recent stash (keep it in the stash list)
git stash apply

# Apply a specific stash
git stash apply stash@{1}

# Apply and remove from the stash list
git stash pop
git stash pop stash@{1}

# Drop a specific stash
git stash drop stash@{0}

# Drop all stashes
git stash clear

# Show the content of a stash
git stash show -p stash@{0}

# Create a branch from a stash
git stash branch feature/resume-work stash@{0}

Real-world scenario

# Midway through feature/auth, your lead asks for an urgent bug fix on main

# 1. Put away the unfinished work
git stash push -m "WIP: JWT token implementation"

# 2. Switch to main and fix
git switch main
git switch -c hotfix/login-500
# ... fix the bug ...
git commit -m "fix: handle null session in login"
git switch main && git merge hotfix/login-500

# 3. Go back to the feature and get your work back
git switch feature/auth
git stash pop   # get the WIP code back

7. Checklist: What should I use?

Want to discard uncommitted changes in the working dir?
→ git restore <file>

Want to unstage a file?
→ git restore --staged <file>

Want to undo the LAST commit (not pushed, personal branch)?
→ git reset --soft HEAD~1   (keep the code, staged)
→ git reset --mixed HEAD~1  (keep the code, unstaged)
→ git reset --hard HEAD~1   (discard the code too)

Want to undo a commit on a shared branch (already pushed)?
→ git revert <commit-hash>

Accidentally ran reset --hard and lost code?
→ git reflog → find the hash → git reset --hard <hash>

Want to put unfinished work aside for a while?
→ git stash (and git stash pop later)

Review Questions

  1. At which step do git fetch and git pull differ?

    Show answer

    git fetch only downloads remote objects and updates remote-tracking branches (origin/main...) — it does not change local branches. git pull = git fetch + git merge (or git rebase). Fetch lets you review the differences (git diff main origin/main) before deciding to merge — safer when working on shared branches.

  2. What is a tracking branch? What are its benefits?

    Show answer

    A tracking branch is a link between a local branch and its corresponding remote branch (upstream). It's set when you use git push -u origin feature/x or git switch --track origin/feature/x. Benefit: once set, you can just type git push and git pull without specifying the remote/branch. git branch -vv shows tracking info and the number of commits ahead/behind.

  3. Why is --force-with-lease safer than --force?

    Show answer

    --force overwrites the remote branch regardless of whether anyone pushed something new. --force-with-lease checks whether the local remote-tracking ref (origin/feature/x) matches the actual remote before pushing. If a colleague pushed to that branch while you were rebasing → Git refuses, protecting their commits. Always use --force-with-lease on personal feature branches.

  4. How does the history produced by git pull --rebase differ from the default git pull?

    Show answer

    The default git pull (merge) creates a merge commit when both branches have their own commits — the history forks. git pull --rebase places your local commits on top of the remote commits, producing linear history without extra merge commits. Better suited to personal feature branches; configure it globally with git config --global pull.rebase true.

  5. When you run git push and Git says The current branch has no upstream branch, what should you do?

    Show answer

    The branch has no upstream tracking set. Run git push -u origin <branch-name> to push to the remote and set upstream at the same time. After that, git push and git pull work without extra arguments. You can configure auto-setup with git config --global push.autoSetupRemote true so you don't need to type -u every time.

  6. Does rebase create new commits (different hashes) or move the old commits?

    Show answer

    Rebase creates new commits with different hashes. Git reapplies each commit onto the target branch with a new parent — because the parent changes, the SHA-1 changes completely. Commits D and E become D' and E' after the rebase — the same changes but different hashes. This is why you must not rebase published branches: other people who have D/E will see diverged history.

  7. What is the "golden rule of rebasing"? What happens if you break it?

    Show answer

    Never rebase a branch that has been pushed and that other people are using. Breaking it leads to: colleagues have the old commits (D, E) and the remote has new commits (D', E') with different hashes — Git treats these as two diverged histories, causing "duplicate commits" after pulling, messy history, and nonsensical conflicts that are hard to resolve.

  8. When git rebase hits a conflict, which command do you use to continue after resolving it?

    Show answer

    git rebase --continue. Workflow: (1) edit the file to remove the conflict markers, (2) git add <file>, (3) git rebase --continue. If several commits conflict, Git keeps applying each commit and stops again at the next conflict. To cancel the entire rebase and return to the original state: git rebase --abort.

  9. What do git merge --abort and git rebase --abort do?

    Show answer

    Both cancel the operation in progress and return the repository to its previous state — as if you had never started the merge/rebase. --abort is safe to use at any point while resolving conflicts if you want to take a different approach. It only works while the operation is in progress (there is a MERGE_HEAD or a rebase directory in .git/).

  10. In what situation should you use git merge --no-ff instead of a regular merge?

Show answer

Use --no-ff when you want to keep a clear trace that a group of commits belongs to a specific feature/branch. In Git Flow, merging features into develop always uses --no-ff so the history clearly shows "feature X was merged here, consisting of N commits". With --no-ff, git log --graph shows the fork; with fast-forward, the history is linear and it's hard to tell which commits belong to which feature.

  1. How do the three modes of git reset differ with respect to the staging area and the working directory?
Show answer

All 3 modes move HEAD (and the branch pointer) to the specified commit. They differ in what happens to staged/working changes:

  • --soft: Keeps the staging area + working directory (changes from the undone commit become staged)
  • --mixed (default): Clears the staging area, keeps the working directory (changes become unstaged)
  • --hard: Clears both the staging area and the working directory (changes are lost permanently)
  1. Why is git revert safer than git reset when undoing on a pushed branch?
Show answer

git revert creates a new commit with the opposite change — it doesn't rewrite history, it only adds to it. Everyone who pulls receives the revert commit normally. git reset removes commits from history — a subsequent force push makes the remote history and colleagues' local histories diverge, causing confusion and data loss. Principle: once pushed to a shared branch → use only revert.

  1. After git reset --hard HEAD~2, how do you get the 2 deleted commits back?
Show answer

Use git reflog to find the hashes of the deleted commits. Reflog records every position HEAD has been at — even after a --hard reset. Find the hash of the commit you want to restore (e.g. abc1234), then: git reset --hard abc1234 to go back, or git switch -c recovery abc1234 to create a branch from it. Reflog keeps data for 90 days by default.

  1. How do git stash and git stash --include-untracked differ?
Show answer

git stash (default) only stashes tracked files — files that have been git added before. Untracked files (new files never added) are left behind in the working directory. git stash --include-untracked (or -u) also stashes untracked files. Add -a to stash ignored files too.

  1. When can git reflog no longer help?
Show answer

Two cases: (1) Reflog entries have expired — by default 90 days for reachable commits and 30 days for unreachable commits. After that, garbage collection removes the objects. (2) A freshly cloned repository — reflog is local and is not pushed to the remote. A clone starts with an empty reflog. Prevention: push important branches to the remote so you don't depend entirely on reflog.

Hands-on Exercises

Part 1: Remote Repositories — Working with a Team

# You need a GitHub account for this exercise

# 1. Create a repo on GitHub, then clone it
git clone https://github.com/YOUR_USER/test-repo.git
cd test-repo

# 2. See the automatically configured remote
git remote -v

# 3. Create a file and push
echo "# Test" > README.md
git add README.md
git commit -m "docs: add README"
git push -u origin main   # set upstream the first time

# 4. On GitHub: create a file through the UI (simulates a teammate's push)

# 5. Fetch and take a look
git fetch origin
git log ..origin/main --oneline  # see the commit from GitHub

# 6. Merge
git merge origin/main
git log --oneline

# 7. Create a feature branch and push
git switch -c feature/test
echo "feature content" > feature.txt
git add feature.txt && git commit -m "feat: test feature"
git push -u origin feature/test

# 8. View tracking
git branch -vv

Part 2: Merge vs Rebase — The Most Important Decision

# Part 1: Practice merge
mkdir rebase-lab && cd rebase-lab
git init -b main
git config user.name "Test" && git config user.email "test@example.com"

# Create the initial history
echo "initial" > app.js && git add . && git commit -m "init"
echo "main v2" >> app.js && git add . && git commit -m "feat: main v2"

# Create a feature branch
git switch -c feature/a
echo "feature a" >> app.js && git add . && git commit -m "feat: add feature a"

# Merge into main
git switch main
echo "main v3" >> app.js && git add . && git commit -m "feat: main v3"
git merge feature/a
git log --oneline --graph --all   # you see a merge commit

# Part 2: Practice rebase
git switch -c feature/b
echo "feature b" >> app.js && git add . && git commit -m "feat: add feature b"

git switch main
echo "main v4" >> app.js && git add . && git commit -m "feat: main v4"

git switch feature/b
git rebase main
git log --oneline --graph --all   # you see linear history

# Part 3: Create a conflict and resolve it
git switch -c conflict-test
echo "conflict version A" > conflict.txt
git add . && git commit -m "add conflict.txt A"

git switch main
echo "conflict version B" > conflict.txt
git add . && git commit -m "add conflict.txt B"

git merge conflict-test   # CONFLICT!
# Resolve: choose "conflict version A\nconflict version B"
cat > conflict.txt << 'EOF'
conflict version A
conflict version B
EOF
git add conflict.txt && git commit
git log --oneline --graph

Part 3: Undo and Recovery — Rescuing "Lost" Data

mkdir undo-lab && cd undo-lab
git init -b main
git config user.name "Test" && git config user.email "test@test.com"

# 1. Create history
echo "v1" > app.js && git add . && git commit -m "v1"
echo "v2" >> app.js && git add . && git commit -m "v2"
echo "v3" >> app.js && git add . && git commit -m "v3"
git log --oneline

# 2. Reset --soft
git reset --soft HEAD~1
git status   # v3 content is still staged
git log --oneline  # only 2 commits left

# 3. Commit again
git commit -m "v3 re-committed"

# 4. Reset --hard (delete 1 commit)
git reset --hard HEAD~1
git log --oneline   # commit v3 is gone

# 5. Use reflog to get it back
git reflog   # find the hash of commit v3
git reset --hard HEAD@{1}   # go back
git log --oneline

# 6. Practice stash
git switch -c feature/test
echo "WIP code" >> app.js
git stash push -m "WIP: test feature"
git status   # clean

git switch main
# ... pretend to fix a bug here ...
git switch feature/test
git stash pop   # get the WIP back
git status   # the changes are back

# 7. Revert (does not delete history)
git add . && git commit -m "feat: add something"
git revert HEAD   # create a revert commit
git log --oneline   # both commits are still there

References


Next lesson →