Git is a powerful distributed versioning system loved by developers worldwide. Regardless of whether you are a Noob or a Jedi, Git contains advanced features that can help increase your productivity and make versioning easier. This writeup focuses on advanced tips and tricks to enhance your Git skills, streamline the version control process and make your workflows more efficient.
One of the best practices when working with Git is to create a new branch every time you want to add a new feature or fix a bug. This helps keep your main branch clean and allows you to work on multiple features simultaneously.
Here's how to create a new feature branch:
git checkout -b feature_branch
Once the feature is ready and tested, you can merge it to the main branch. If you are working in a team, you would typically want to create a pull request so that your teammates can review your changes before they are integrated into the main codebase.
Git has a fantastic feature to clean up untracked or ignored files from your working tree. Git clean command can be used with -dfx options to recursively clean the working directory.
Sample command to clean unwanted files:
git clean -dfx
Be careful while using 'git clean' command, as it will remove the files permanently.
Git rebase is a command that allows you to rearrange, modify, or delete your commit history. It's particularly useful when you want to combine your work with that of another team member or adapt your work to changes in the main repository.
git rebase -i HEAD~5 # Interactive rebase of the last 5 commits
In the interactive rebasing list you can select commits to squash, reword, delete or change their order.
Squashing enables you to take multiple commits and combine them into a single commit. This feature is clearly helpful when you want to incorporate several small changes into one large changeset.
Here's how to squash the last 'n' commits:
git rebase -i HEAD~n
In the text editor that opens, replace 'pick' with 'squash' at the start of each line for the commits you want to squash.
Sometimes, you may want to apply some changes (commit) from one branch into another. This is when you'll want to use git cherry-pick.
git cherry-pick <commit-hash>
Git has several commands to inspect and compare branches.
You can show the differences between two branches with:
git diff <branch_one>..<branch_two>
And you can inspect the commit history of a branch with:
git log <branch_name>
Git has a nice feature that allows you to generate a patch file for changes between two branches, releases, or commits.
To create a patch:
git diff > mypatch.patch
To apply that patch:
git apply mypatch.patch
Git's log command is a powerful tool for understanding the history of your project. Using flags like --stat, --decorate, --oneline, and --graph can give you a wealth of information, including list of files changed, an ASCII graph of your branch and merge history, and more.
git log --oneline --decorate --color --graph --all