From 2a9bfcb78b85bb9ead2028acb9db0fac88ed0dd3 Mon Sep 17 00:00:00 2001 From: Adam Djellouli <37275728+djeada@users.noreply.github.com> Date: Thu, 24 Apr 2025 21:36:05 +0200 Subject: [PATCH] clarified the HEAD~2 root commit issue and suggested using --root or creating an initial commit (#10569) --- topics/git/solutions/squashing_commits.md | 35 ++++++++++++++--------- 1 file changed, 22 insertions(+), 13 deletions(-) diff --git a/topics/git/solutions/squashing_commits.md b/topics/git/solutions/squashing_commits.md index 3876196..891f605 100644 --- a/topics/git/solutions/squashing_commits.md +++ b/topics/git/solutions/squashing_commits.md @@ -1,24 +1,27 @@ ## Git - Squashing Commits - Solution - -1. In a git repository, create a new file with the content "Mario" and commit the change +1. In a git repository, create a new file with the content "Mario" and commit the change: ``` +echo "Mario" > new_file git add new_file -echo "Mario" -> new_file -git commit -a -m "New file" +git commit -m "New file" ``` -2. Make change to the content of the file you just created so the content is "Mario & Luigi" and create another commit +2. Make a change to the content of the file you just created so it becomes "Mario & Luigi," then create another commit: ``` echo "Mario & Luigi" > new_file git commit -a -m "Added Luigi" ``` -3. Verify you have two separate commits - `git log` +3. Verify you have two separate commits by running: -4. Squash the two commits you've created into one commit +``` +git log +``` + +4. Squash the two commits you've created into one commit: ``` git rebase -i HEAD~2 @@ -31,19 +34,25 @@ pick 5412076 New file pick 4016808 Added Luigi ``` -Change `pick` to `squash` - +Change `pick` to `squash`: ``` pick 5412076 New file squash 4016808 Added Luigi ``` -Save it and provide a commit message for the squashed commit +Save it and provide a commit message for the squashed commit. + +> **Note**: If running `git rebase -i HEAD~2` returns a fatal error (e.g., "invalid upstream 'HEAD~2'"), that usually means your second commit is actually the root commit and there's no valid parent before it. In that case, you can either: +> * Use `git rebase -i --root` to allow rewriting the root commit, **or** +> * Create an initial commit before these two commits so that `HEAD~2` points to valid commits. ### After you complete the exercise -Answer the following: +**Answer the following:** -* What is the reason for squashing commits? - history becomes cleaner and it's easier to track changes without commit like "removed a character" for example. -* Is it possible to squash more than 2 commits? - yes +* **What is the reason for squashing commits?** + History becomes cleaner and it's easier to track changes without many small commits like "removed a character," for example. + +* **Is it possible to squash more than 2 commits?** + Yes.