Git Golden Rules
Source: Dev.to
Golden Rules to Help Prevent Your Git Repository from Breaking
Golden Rule 1: Never Force Push
- Avoid using
git push -forgit push --force; they can overwrite other developers’ changes and cause conflicts. - Instead, push normally, e.g.:
git push origin main # or your remote branch name
Golden Rule 2: Always Pull Before Pushing
Pull the latest changes before you push:
git pull origin main # or your remote branch name
Golden Rule 3: Merge Branches Regularly
- Create a separate branch for each feature or bug fix.
- When finished, merge it into the main branch:
git checkout main
git merge feature/new-feature
- Resolve any conflicts, then stage the resolved files:
git add
Golden Rule 4: Resolve Merge Conflicts Carefully
- Use tools such as
git status,git diff, or a visual diff tool (e.g., Meld) to identify conflicts. - Manually edit the conflicted files, stage them with
git add, and test thoroughly.
Golden Rule 5: Test Thoroughly Before Committing
- Run automated tests, perform manual testing, and request code reviews.
- Never commit broken or incomplete code.
Golden Rule 6: Use Meaningful Branch Names and Descriptions
- Choose clear, descriptive names, e.g.,
feature/add-logininstead of justlogin. - Write concise commit messages that explain what changed and why.
Golden Rule 7: Keep Commits Small and Focused
- Avoid massive commits; break large features into smaller, logical commits (ideally under 10 lines of code).
Golden Rule 8: Regularly Review and Clean Up Your Branches
- Periodically prune stale branches and delete ones that are no longer needed to keep the repository tidy.
Additional Tips for Handling Merge Conflicts
- Abort a problematic merge:
git merge --abort - Temporarily stash changes:
git stash - Communicate with teammates about conflicts so they can help resolve them.
Communication Is Key
When others push changes to a branch you’re working on, keep the team informed:
-
Get notified – set up repository notifications.
-
Pull the updated branch:
git pull origin -
Resolve conflicts (if any) and stage the fixes with
git add. -
Rebase your local changes onto the latest updates:
git rebase origin/ -
Test thoroughly to ensure everything still works.
Best Practices for Collaborative Development
- Use feature branches to isolate work.
- Communicate regularly about which branches you’re working on.
- Pull frequently from the remote repository.
- Leverage Git hooks to enforce coding standards and formatting.
Automating Notifications with GitHub
If you host your code on GitHub, you can configure push notifications:
- Go to Repository Settings.
- Click Notifications.
- Select the branch you want to monitor.
- Choose the notification type (e.g., push, pull request).
Following these rules and practices will help you maintain a stable Git repository and foster a healthier collaborative environment.