Everything you need to know about using Git

Everything you need to know about using Git
Photo by Yancy Min / Unsplash

Git is a distributed version control system that allows developers to track changes in their code, collaborate with others, and manage different versions of their projects. Git is widely used in software development, and knowing how to use it effectively can make your work easier and more productive.

In this article, we will cover some of the basic concepts and commands that every developer should know about git. We will also compare two common ways of integrating changes from different branches: rebase and merge.

Basic Concepts

Before we dive into the commands, let’s review some of the key concepts that git uses.

  • Repository: A repository is a collection of files and folders that are tracked by git. A repository can be local (on your computer) or remote (on a server or a platform like GitHub).
  • Commit: A commit is a snapshot of the state of your repository at a certain point in time. Each commit has a unique identifier (a hash) and a message that describes what changes were made. Commits are linked together in a history that shows the evolution of your project.
  • Branch: A branch is a pointer to a specific commit in the history. You can create multiple branches to work on different features or tasks without affecting the main branch (usually called master or main). When you are done with a branch, you can merge it back to the main branch or delete it.
  • Remote: A remote is a reference to another repository that you can interact with. For example, you can push your local changes to a remote repository to share them with others, or pull changes from a remote repository to update your local copy.
  • Merge: A merge is an operation that combines two or more branches into one. There are different types of merges, such as fast-forward, recursive, or squash. Merging can create conflicts if the same files or lines of code are modified differently in different branches. Conflicts need to be resolved manually before completing the merge.
  • Rebase: A rebase is an operation that moves a branch to a new base commit. This can be useful to keep your branch up to date with the main branch or to rewrite the history of your branch. Rebasing can also create conflicts that need to be resolved manually.

Common Commands

There are many commands that git offers, but here are some of the most common ones that you will use frequently.

  • git init: This command creates a new git repository in the current directory. It initializes the .git folder that contains all the information and configuration for the repository.
  • git clone: This command copies an existing repository from a remote source to your local machine. It also sets up the remote as the origin for your local repository, so you can easily push and pull changes.
  • git status: This command shows the current state of your repository, such as which files are modified, staged, or untracked. It also tells you which branch you are on and if you are ahead or behind the remote branch.
  • git add: This command adds files or changes to the staging area, which is a temporary area where you can prepare your commits. You can use git add . to add all the changes in the current directory, or git add <file> to add a specific file or pattern.
  • git commit: This command creates a new commit with the files or changes that are in the staging area. You need to provide a message that describes the commit, using the -m flag. For example, git commit -m "Add README file". You can also use git commit -a to automatically add and commit all the modified files, skipping the staging area.
  • git push: This command sends your local commits to a remote repository. You need to specify the remote name and the branch name, such as git push origin main. If the remote branch does not exist, it will be created. You can also use git push -u origin main to set up the remote branch as the upstream for your local branch, so you can use git push without arguments in the future.
  • git pull: This command fetches the changes from a remote repository and merges them into your local branch. You need to specify the remote name and the branch name, such as git pull origin main. You can also use git pull --rebase origin main to rebase your local branch on top of the remote branch instead of merging.
  • git branch: This command lists all the branches in your repository, both local and remote. You can also use git branch <name> to create a new branch with the given name, or git branch -d <name> to delete a branch. To switch to a different branch, you need to use git checkout <name>.
  • git checkout: This command switches your working directory to a different branch or commit. You can use git checkout <name> to switch to an existing branch, or git checkout -b <name> to create and switch to a new branch. You can also use git checkout -- <file> to discard the changes in a specific file or pattern.
  • git log: This command shows the history of commits in your repository. You can use various flags and options to customize the output, such as git log --oneline to show a concise summary of each commit, or git log --graph to show a graphical representation of the branches and merges.

Example workflows

  1. Creating a repository
# If you want to create a new repository on your local machine, you can use init
git init <name> # where name is the name of the repository

# This will create a new directory with the name of the repository and initialize a .git folder inside it
# Change to the directory of the new repository
cd <name>

# If you want to create a new repository on a remote platform like GitHub, you can use clone
# First, you need to create an empty repository on the platform and copy its URL
# Then, you can use clone to copy the remote repository to your local machine
git clone <url> # where url is the URL of the remote repository

# This will create a new directory with the name of the repository and copy the .git folder from the remote repository
# Change to the directory of the new repository
cd <name>
  1. Fetching changes from a remote repository and updating your local branch.
# Fetch the changes from the remote repository
git fetch origin

# Check the status of your local branch
git status

# If your local branch is behind the remote branch, update it
git pull origin main

  1. Cloning a repository, adding changes and then pushing.
# Clone a remote repository to your local machine
git clone https://github.com/user/repo.git

# Change to the directory of the cloned repository
cd repo

# Make some changes to the files in the repository
# ...

# Check the status of the repository
git status

# Add the changes to the staging area
git add .

# Commit the changes with a message
git commit -m "Some changes"

# Push the changes to the remote repository
git push origin main
  1. Creating a new branch, making changes in the new branch, checkouting back to main branch and then merging to main from created branch, as well as deleting the merged branch.
# Create a new branch called feature and switch to it
git checkout -b feature

# Make some changes to the files in the feature branch
# ...

# Check the status of the feature branch
git status

# Add the changes to the staging area
git add .

# Commit the changes with a message
git commit -m "Some feature"

# Switch back to the main branch
git checkout main

# Merge the feature branch into the main branch
git merge feature

# Delete the feature branch
git branch -d feature
  1. Stashing your changes temporarily and applying them later.
# If you have some changes that you are not ready to commit, but you need to switch to a different branch or do something else, you can stash them
git stash

# Do whatever you need to do
# ...

# When you want to resume your work, you can apply the stashed changes
git stash apply

# Alternatively, you can pop the stashed changes, which applies them and removes them from the stash
git stash pop
  1. Undoing your changes or commits.
# If you want to undo the changes in a specific file or pattern, you can use checkout
git checkout -- <file>

# If you want to undo all the changes in your working directory, you can use reset
git reset --hard

# If you want to undo the last commit, you can use reset with the --soft or --hard flag, depending on whether you want to keep the changes in the staging area or not
git reset --soft HEAD~1 # keep the changes in the staging area
git reset --hard HEAD~1 # discard the changes completely
  1. Squashing multiple commits into one.
# If you have a series of small or related commits that you want to combine into one, you can use rebase with the --interactive or -i flag
git rebase -i HEAD~n # where n is the number of commits you want to squash

# This will open a text editor where you can choose which commits to squash, pick, edit, or drop
# You can use s or squash to squash a commit into the previous one, or f or fixup to squash a commit into the previous one and discard its message
# Save and exit the editor when you are done

# This will create a new commit that contains the changes from the squashed commits
# You can edit the message of the new commit in another text editor that will open
# Save and exit the editor when you are done
  1. Cherry-picking a commit from another branch.
# If you want to apply a specific commit from another branch to your current branch, you can use cherry-pick
git cherry-pick <hash> # where hash is the identifier of the commit you want to cherry-pick

# This will create a new commit on your current branch that contains the changes from the cherry-picked commit
# You can edit the message of the new commit if you want
# Save and exit the editor when you are done

The .gitignore file

A .gitignore file is a file that tells Git which files or folders to ignore in a project. A .gitignore file should be placed in the root directory of your project. You can use patterns, wildcards, and exceptions to specify which files to ignore or include. Here is an example of a .gitignore file for a Python project:

# Ignore Python compiled files
__pycache__/
*.pyc

# Ignore environment file
.env

# Ignore IDE settings
.idea/
.vscode/

# Ignore some files in a folder, but not all
data/*.csv
!data/important.csv

Rebase vs Merge

One of the common questions that developers face when working with git is whether to use rebase or merge to integrate changes from different branches. Both methods have their pros and cons, and the choice depends on the situation and the preference of the team.

What is git rebase?

Rebase is a way of rewriting the history of a branch by moving it to a new base commit. For example, if you have a feature branch that is based on an old commit of the main branch, you can use git rebase main to move your feature branch to the latest commit of the main branch. This will make your branch appear as if it was created from the latest commit, and avoid creating a merge commit.

The advantages of rebase are:

  • It keeps the history linear and clean, without unnecessary merge commits.
  • It makes it easier to review and understand the changes, as each commit represents a logical unit of work.
  • It avoids potential conflicts that may arise from merging divergent branches.

The disadvantages of rebase are:

  • It modifies the history of the branch, which can cause problems if the branch is shared with others. You should never rebase a branch that is already pushed to a remote repository, unless you are sure that no one else is working on it or you communicate with your team beforehand.
  • It can lose some context and information that may be useful for debugging or tracing the origin of a change. For example, if you rebase a branch that was merged with another branch, you will lose the information about the merge and the other branch.

What is git merge?

Merge is a way of combining two or more branches into one by creating a new commit that incorporates the changes from both branches. For example, if you have a feature branch that is based on an old commit of the main branch, you can use git merge main to merge the latest changes from the main branch into your feature branch. This will create a merge commit that shows the two parent branches and the conflicts that were resolved.

The advantages of merge are:

  • It preserves the history of the branch, without altering the existing commits. You can always see the original state and the source of each change.
  • It maintains the context and information that may be useful for debugging or tracing the origin of a change. For example, if you merge a branch that was merged with another branch, you can see the history of both branches and the merge.

The disadvantages of merge are:

  • It creates a non-linear and complex history, with many merge commits. This can make it harder to review and understand the changes, as each commit may not represent a logical unit of work.
  • It can introduce potential conflicts that need to be resolved manually. For example, if you merge a branch that has diverged significantly from the main branch, you may have to deal with many conflicts and inconsistencies.

There is no specific answer to which method is better, as both have their trade-offs and benefits. Some teams prefer to use rebase to keep the history clean and simple, while others prefer to use merge to preserve the history and context. Some teams use a combination of both, depending on the situation and the type of branch. The important thing is to follow a consistent and agreed-upon workflow with your team, and to communicate clearly and frequently with your collaborators.

Conclusion

n this article, we learned some of the essential concepts and commands that every developer should know about git, a distributed version control system that allows developers to track changes in their code, collaborate with others, and manage different versions of their projects. We also compared two common ways of integrating changes from different branches: rebase and merge, and discussed their pros and cons. Finally, we saw some examples of common and advanced workflows.

Git is a powerful and versatile tool that can help you work more efficiently and effectively as a developer. However, it also requires some practice and discipline to use it properly and avoid common pitfalls. You should always follow the best practices and conventions that suit your project and team, and communicate clearly and frequently with your collaborators. You should also consult official documentation or other reliable sources for more information and guidance on how to use git.

Learn more

If you plan to use Github, there'a another useful trick to enhance your workflow:

Seamlessly use Github using SSH keys
GitHub, along with many other code versioning platforms (such as Bitbucket), provides a secure and efficient way to manage and collaborate on projects. By utilizing SSH keys, you can seamlessly interact with your repositories, enabling secure authentication without the need for passwords. By leveraging SSH’s config file, you can simplify

Read more