In this blog post, we will dive deep into the world of Git, the most widely used version control system. We will learn and implement best practices that are crucial for managing code efficiently in team environments and personal projects.
Git is a distributed version control system. This means that every developer's working copy of the code is also a repository that can contain the entire history and full version tracking capabilities, independent of network access or a central server.
A commit, or "revision", is an individual change to a file (or set of files). It's like when you save a file, except with Git, every time you save it creates a unique ID that allows you to keep record of what changes were made when and by who. Commits usually contain a commit message which is a brief description of what changes were made.
Branching is the way to work on different versions of a repository at one time. By default your repository has one branch named "main" that is considered to be the definitive branch. We use branches to experiment and make edits before committing them to "main".
Branching strategies can be very helpful in managing and organizing your work. Let's look at a couple of strategies and their uses.
Feature branches provide an isolated environment for every change to your codebase. When a developer wants to start working on something, no matter how big or small, they create a new branch. This ensures that the master branch always contains production-quality code.
# Starting a new feature
git checkout -b new-feature
git add .
git commit -m "Start developing a feature"
Gitflow workflow employs two parallel long-running branches to record the history of the project, master and develop. Master is always ready to be released on LIVE, with any changes waiting to be released managed in develop.
# Creating a feature branch
git checkout develop
git checkout -b new-feature
# Finished feature
git checkout develop
git merge new-feature
Commit messages are important means of communication between team members. Let's outline some of the best practices for writing effective commit messages.
Sometimes when you merge changes, you'll get merge conflicts. This usually happens when people make different changes to the same line of the same file, or when one person edits a file and another person deletes the same file.
# Merge conflict example
git merge feature-branch
# Resolve conflicts
git add .
git commit -m "Resolve merge conflicts"
Git hooks are scripts that Git executes before or after events such as: commit, push, and receive. Git hooks are a built-in feature - no need to download anything.
# Pre-commit hook example
#!/bin/sh
files=$(git diff --cached --name-only --diff-filter=ACM | grep '.jsx\?$')
if [ "$files" = "" ]; then
exit 0
fi
failed=0
for file in $files; do
eslint "$file"
if [ $? -ne 0 ]; then
failed=1
fi
done
if [ $failed -eq 1 ]; then
exit 1
fi
Ready to start learning? Start the quest now