> Squash All Commits on Feature Branch

2022-04-19
Git, Tutorial
  When working on a feature branch, it's common to make multiple commits as you progress. However, before merging into the main branch, you might want to consolidate these commits into a single, clean commit. Here's how to do it effectively.

  ## Why Squash Commits?

  Squashing commits helps:
  - Keep the main branch history clean and meaningful
  - Make code reviews easier
  - Simplify rollbacks if needed
  - Group related changes together

  ## The Process

  Here's the step-by-step process to squash your commits:

  1. First, make sure you're on your feature branch:
  ```bash
  git checkout feature-branch
  ```

  2. Find out how many commits you want to squash:
  ```bash
  git log
  ```

  3. Start an interactive rebase:
  ```bash
  git rebase -i HEAD~n  # n is the number of commits to squash
  ```

  4. In the editor that opens, change 'pick' to 'squash' for all commits except the first one:
  ```
  pick abc1234 First commit
  squash def5678 Second commit
  squash ghi9012 Third commit
  ```

  5. Save and close the editor. Another editor will open for the commit message.

  6. Edit the commit message as needed and save.

  ## Best Practices

  - Always squash before merging into main
  - Write clear, descriptive commit messages
  - Test after squashing to ensure everything still works
  - Push with force-with-lease to update remote:
    ```bash
    git push --force-with-lease origin feature-branch
    ```

  ## Common Issues and Solutions

  1. Conflicts During Rebase
     - Resolve conflicts manually
     - Continue with `git rebase --continue`
     - Or abort with `git rebase --abort`

  2. Lost Commits
     - Use `git reflog` to find and recover commits
     - Always create a backup branch before squashing

  ## Conclusion

  Squashing commits is a powerful way to maintain a clean git history. Just remember to:
  - Only squash commits that haven't been shared
  - Write meaningful commit messages
  - Test your code after squashing
  - Use force-with-lease when pushing