Git is a powerful version control system that allows developers to track changes, collaborate with others, and manage project history efficiently. Whether you’re working on a small personal project or a large team-based application, understanding how to commit changes and undo mistakes is essential.
In this guide, we’ll cover:
Committing changes to your project
Viewing your commit history
Reverting code to a previous commit
After editing your code, Git allows you to stage and commit your changes so they become part of the project history.
git status
Shows which files are modified, staged, or untracked.
Example output:
On branch main Changes not staged for commit: modified: app/models.py modified: app/views.py Untracked files: new_file.py
Use git add to stage files you want to include in your next commit:
git add app/models.py app/views.py
To stage all changes, you can use:
git add .
Once staged, commit your changes with a descriptive message:
git commit -m "Add user authentication and profile page"
The commit message should clearly describe the changes you made.
After committing, your changes are saved in Git’s history.
To see all commits in your project:
git log --oneline
Example output:
6sfsfb0a Add user authentication and profile page fsfsfgh Fix bug in post creation i5sf9l Initial commit
Each commit has a hash (e.g., 6c03b0a) that identifies it.
This hash is useful when you want to revert or reset changes.
Sometimes you may make changes that you no longer want to keep. Git provides several ways to undo changes:
git reset --soft
Moves your branch pointer to the specified commit.
Keeps changes in your working directory staged for a new commit.
Example:
git reset --soft f4vdv6h
git revert
Creates a new commit that undoes the specified commit.
Safe to use if you’ve already shared your branch with others.
Example:
git revert 6ddg0a
Git will generate a commit like “Revert ‘Add user authentication and profile page’”.
git reset --hard
Resets your branch to the given commit and discards all changes after it.
Warning: This is destructive — changes cannot be recovered unless backed up.
Example:
git reset --hard ffsesh
Use git status after this to confirm your branch matches the previous state.
After committing or reverting locally, you can update your remote repository:
git push origin main
If you used --hard reset or changed history, you may need to force push:
git push origin main --force
⚠️ Use force push with caution, as it overwrites remote history.
© 2024 Webapptiv. All rights reserved.