up-arrow

Introduction to Git

What is Git?

Git is a distributed version control system designed to track changes made to files in a project. It was created by Linus Torvalds in 2005 to manage the development of the Linux kernel.

With Git, developers can:

  • Collaborate in teams without overwriting others' work.
  • Maintain a complete history of changes in the project.
  • Restore previous versions in case of errors.

Why use Git?

Git has become the de facto standard in software development for the following reasons:

  1. Efficient collaboration: Allows multiple developers to work simultaneously on different parts of a project.
  2. Complete history: Keeps all changes made, along with who made them and why.
  3. Security: Git data is hard to corrupt due to its design.
  4. Distribution: Each copy of the repository contains the full project history, so it doesn't rely on a central server.
  5. Flexibility: Works for projects of any size and complexity.

Installing Git

To start using Git, you first need to install it on your computer. Let's see how to do it depending on your operating system.

  1. Windows

    • Download the installer from https://git-scm.com.
    • Run the downloaded file and follow the instructions in the setup wizard.
    • During installation, you'll be prompted to choose settings like the default editor. You can keep the recommended options.
  2. MacOS

    • If you have Homebrew installed, you can install Git with:
    • brew install git
    • You can also download it directly from https://git-scm.com.
  3. Linux

    Use your distribution's package manager to install Git. Some examples:

    • Ubuntu/Debian:
    • sudo apt-get install git
    • CentOS/Fedora:
    • sudo yum install git

    To verify that Git is installed correctly, run:

    git --version

Initial Git Setup

Once installed, it's important to perform an initial setup to personalize Git according to your identity and preferences.

  1. Set up username and email

    These values will be used to identify you in the commits you make.

    • Set your name:

      git config --global user.name "YourName"
    • Set your email:

      git config --global user.email "YourEmail@example.com"
    • To verify your configuration, use:

      git config --global --list
  2. Set up default editor

    Git uses a text editor for tasks such as writing long commit messages. By default, it uses vim, but you can change it to any editor you prefer. For example:

    • To set Visual Studio Code as the default editor:
    • git config --global core.editor "code --wait"
    • To set Nano as the default editor:
    • git config --global core.editor "nano"

Basic Git Concepts

Repositories

A repository in Git is the space where the files of a project are stored along with its change history. It can be local (on your machine) or remote (on a platform like GitHub or GitLab).

Create a repository

To create a local repository, use the command:

git init

This command initializes a new empty repository in the current directory.

Clone a repository

To get a copy of a remote repository on your local machine, use:

git clone REPOSITORY_URL

For example:

git clone https://github.com/user/repository.git

This will download all the files and history from the remote repository.

Branches

Branches are independent versions of your project that you can develop in parallel. Using branches makes it easier to work on new features without affecting the main branch.

Create a branch

To create a new branch, use:

git branch branch_name

For example, to create a branch named new-feature:

git branch new-feature

Switch branches

To switch to an existing branch, use:

git checkout branch_name

For example:

git checkout new-feature

You can also create a new branch and switch to it immediately with:

git checkout -b branch_name

Basic branch workflow

A typical workflow with branches is:

  1. Create a new branch for the feature you want to work on.
  2. Make changes and commits in that branch.
  3. Merge the feature branch into the main branch once the work is complete.

Commits

Commits are "snapshots" of the state of the files at a given point in time. Each commit includes a message describing the changes made.

Create a commit

After making changes to the files, use the following commands:

  1. Stage the files for commit:
  2. git add file_or_folder

    To stage all files, use:

    git add .
  3. Create the commit with a descriptive message:
  4. git commit -m "Message describing the changes"

Effective commit messages

A good commit message should be clear and descriptive. Follow these guidelines:

  • Use the imperative mood (e.g., "Add search function").
  • Keep the messages short and to the point.
  • Explain the reasoning behind the change if necessary.

View commit history

To view the commit history of a repository, use:

git log

This will show detailed information about each commit, such as its author, date, and message.

For a more compact history, use:

git log --oneline

Teamwork with Git

Remotes

Remotes are repositories hosted on platforms like GitHub, GitLab, or Bitbucket. They allow collaboration with other developers by synchronizing changes between the local and remote repositories.

Add a remote

To link your local repository with a remote repository, use:

git remote add origin REPOSITORY_URL

For example:

git remote add origin https://github.com/user/repository.git

To check the configured remotes, use:

git remote -v

Fetch changes from remote (pull and fetch)

To get the latest changes from the remote to your local repository, you can use:

  • git fetch: Gets the remote changes but doesn't merge them with your local branch.
  • git pull: Gets the remote changes and automatically merges them with your current branch.

Command to make a pull:

git pull origin branch

For example:

git pull origin main

Push changes to remote

To send changes from your local repository to the remote, use:

git push origin branch

For example, to push changes to the main branch:

git push origin main

Conflict resolution

What are conflicts?

A conflict occurs when Git cannot automatically merge changes made to the same lines of a file by different collaborators. This usually happens when performing a merge or pull.

Strategies for resolving conflicts

  1. When a conflict occurs, Git will mark the conflicting areas in the affected files.
  2. Edit the file to choose which changes to keep.
  3. Save the file and mark the conflict as resolved with:
  4. git add affected_file
  5. Complete the merge with:
  6. git commit

To avoid conflicts:

  • Pull frequently to keep your branch up to date.
  • Communicate important changes with your team.

Pull requests and merge requests

What are they and when to use them?

A pull request (on GitHub) or merge request (on GitLab) is a request to merge changes from one branch to another. These tools make code review easier before merging the changes.

Typical process:

  1. Push your changes to a branch in the remote repository.
  2. Create a pull request from the platform interface.
  3. Wait for review and approval from other team members.
  4. Once approved, perform the merge.

Benefits:

  • Allows collaborative code review.
  • Facilitates discussion about specific changes.
  • Helps maintain a clear and organized project history.

Advanced Workflow

Rebases

What is a rebase?

Rebase is an alternative to merge that rewrites the commit history to apply changes from one branch onto another as if they had been made sequentially. This results in a more linear and readable history.

Basic command:

git rebase base_branch

For example, to apply the changes from your current branch onto the main branch:

git rebase main

Interactive rebase

Interactive rebase allows you to modify, combine, or delete commits during the rebase process. It's useful for cleaning up history before pushing changes.

Command to start an interactive rebase:

git rebase -i HEAD~n

Where n is the number of recent commits you want to modify.

During the process, you can perform actions like:

  • pick: Keep the commit as is.
  • reword: Change the commit message.
  • edit: Pause to modify the commit content.
  • squash: Combine multiple commits into one.
  • drop: Remove a commit.

Stashing

Temporarily save changes

The git stash command temporarily saves your current changes so that you can switch branches or perform other actions without losing your uncommitted work.

Command to save changes:

git stash

To add a description to the stash:

git stash save "Description"

Retrieve saved changes

To retrieve the most recently saved changes:

git stash apply

To retrieve and remove the stash from the list:

git stash pop

To list all saved stashes:

git stash list

Cherry-picking

Apply specific commits to another branch

Cherry-picking allows you to apply a specific commit from one branch to another without performing a full merge.

Basic command:

git cherry-pick COMMIT_ID

To get the commit ID, you can use:

git log

Example:

git cherry-pick a1b2c3d4

Git hooks

Git hooks are scripts that run automatically before or after key events such as commits, merges, or pushes. They are useful for automating tasks like checking code or deploying applications.

Customization and automation with hooks

Hooks are located in the .git/hooks directory of your repository. Some common hooks are:

  • pre-commit: Runs before a commit is made. Useful for checking code formatting.
  • pre-push: Runs before pushing changes to the remote. You can use it to run automated tests.
  • post-merge: Runs after a merge. It can be useful for updating dependencies.

To enable a hook, create or edit the corresponding file, for example:

nano .git/hooks/pre-commit

Make sure the file is executable:

chmod +x .git/hooks/pre-commit

Error Management

Undo Changes

In Git, it's common to make mistakes or need to undo certain changes. Depending on the situation, you can use different commands:

Undo changes in files not added to the staging area

If you modified a file but haven't used git add yet, you can revert it to its last committed version with:

git checkout -- FILE_NAME

For example:

git checkout -- index.html

Remove files added to the staging area

If you added a file with git add but don't want to include it in the next commit:

git reset FILE_NAME

Example:

git reset index.html

Revert a Commit

If you've already committed changes but want to revert them, you can create a new commit that undoes the changes made:

git revert COMMIT_ID

You can get the COMMIT_ID using the command:

git log

For example:

git revert a1b2c3d4

This will open an editor to confirm the new commit that undoes the changes of the previous one.

Reset to the Previous State

If you want to undo changes more drastically and don't need to keep the history, you can use git reset.

Reset to the Last Committed State

To undo all changes since the last commit:

git reset --hard

Note: This will delete any uncommitted changes.

Reset to a Specific Commit

To go back to a previous state in history:

git reset --hard COMMIT_ID

Example:

git reset --hard a1b2c3d4

Warning: This will rewrite the history, so use it carefully, especially if you've already shared commits with others.

Recover Deleted Files

If you accidentally deleted a file but haven't committed the change yet, you can recover it:

git checkout -- FILE_NAME

For example:

git checkout -- styles.css

If you've already committed the deletion but want to recover the file, use:

git checkout COMMIT_ID -- FILE_NAME

For example:

git checkout a1b2c3d4 -- styles.css

This will restore the file from the specified commit.

Advanced Git Concepts

Submodules

What are submodules?

A submodule in Git is a repository nested within another repository. They are used to include dependencies or related projects that need to remain separate but are part of the main project.

For example, if a project uses a library that is in its own repository, you can include it as a submodule instead of copying the code.

Adding and Managing Submodules

To add a submodule, use the command:

git submodule add REPOSITORY_URL DESTINATION_PATH

Example:

git submodule add https://github.com/user/library.git libs/library

To initialize and clone all submodules in a repository:

git submodule update --init --recursive

If you want to update a submodule to its latest version:

git submodule update --remote

Git and CI/CD Services

Continuous Integration

Continuous integration (CI) is a practice where every change in the code is automatically tested for issues. With Git, you can easily integrate it with CI services such as GitHub Actions, Travis CI, or GitLab CI.

An example configuration in GitHub Actions would be to create a .github/workflows/ci.yml file:

name: CI
                    on:
                    push:
                    branches:
                    - main
                    jobs:
                    build:
                    runs-on: ubuntu-latest
                    steps:
                    - uses: actions/checkout@v3
                    - name: Set up environment
                    run: npm install
                    - name: Run tests
                    run: npm test

Automatic Deployment with Git

Automatic deployment involves sending changes automatically to a production server or a testing environment after they are committed to a specific branch. This can be configured with tools such as:

  • GitHub Actions: Automates deployment to platforms like Heroku, AWS, or custom servers.
  • GitLab CI/CD: Set up a .gitlab-ci.yml file to define testing and deployment stages.

For example, for deploying to Heroku:

deploy:
                        provider: heroku
                        api_key: $HEROKU_API_KEY
                        app: your-app-name

Best Practices with Git

Naming Conventions

It's important to follow clear conventions for branch, commit, and tag names:

  • Branch names: Use descriptive names, such as feature/new-feature, bugfix/fix-error.
  • Tag names: Use semantic tags for releases, such as v1.0.0.

Main and Feature Branches

Adopt a well-defined workflow with branches, such as:

  • main: Stable branch, ready for production.
  • develop: Development branch, where new features are integrated before being merged into main.
  • feature/*: Branches for developing new features.
  • hotfix/*: Branches for fixing critical bugs in production.

This approach helps maintain control and organization in complex projects.

Tools and Additional Resources

Git in the Terminal

Working with Git from the terminal is the most direct and powerful way to use it. With well-structured commands, you can perform all the necessary operations. Some advantages of using Git in the terminal are:

  • Total control over Git operations.
  • Speed and efficiency by not relying on graphical interfaces.
  • A deep understanding of how Git works internally.

To get started, make sure you have a terminal configured with access to Git. If you're using Windows, Git Bash is an excellent option. On macOS and Linux, the native terminal already includes support for Git after installation.

Git Graphical Interface

If you prefer a more visual experience, there are many graphical tools for working with Git. Some popular options include:

  • GitHub Desktop: Ideal for GitHub users, with a simple interface that is useful for beginners.
  • Sourcetree: Offers advanced features like branch visualization and conflict resolution, perfect for complex projects.
  • GitKraken: A modern, user-friendly tool for users of any experience level.
  • Visual Studio Code: With integrated extensions like GitLens, you can work with Git directly from your code editor.

These tools are helpful for tasks such as visualizing history, resolving conflicts, and managing branches, especially if you are new to Git.

Resources to Learn More About Git

Continuous learning is key to mastering Git. Here are some recommended resources:

Official Documentation

The official Git documentation is a comprehensive and detailed reference for all its features. You can find it at:

Recommended Tutorials

Some tutorials and online courses can help you learn Git in a practical way:

Forums and Communities

Join active communities to solve problems, share knowledge, and stay up-to-date with best practices:

  • Stack Overflow: A global developer community where you can ask specific Git-related questions.
  • GitHub Community: The official GitHub forum for developers of all levels.
  • Reddit: r/git: A space to discuss Git-related topics.

With these resources, you'll have a solid foundation to become a Git expert.

Reference

Most Common Commands

Below is a list of the most commonly used Git commands, with a brief description of their function:

  • git init: Initializes a new Git repository in the current folder.
  • git clone [URL]: Clones a remote repository to your local system.
  • git status: Displays the current status of the repository, including unadded and uncommitted changes.
  • git add [file]: Adds a specific file to the staging area.
  • git add .: Adds all modified files to the staging area.
  • git commit -m "message": Saves changes to the repository with an explanatory message.
  • git push origin [branch]: Pushes changes to the remote repository on the specified branch.
  • git pull: Fetches and merges changes from the remote repository.
  • git branch: Displays a list of existing branches and highlights the current branch.
  • git checkout [branch]: Switches to the specified branch.
  • git merge [branch]: Merges changes from a specific branch into the current branch.
  • git log: Displays the commit history of the repository.
  • git reset [file]: Removes a file from the staging area.
  • git revert [commit]: Creates a new commit that reverts the changes of a previous commit.

Quick Command Reference Table

A compact table for quickly referencing essential commands:

Command Description
git init Initializes a repository.
git clone [URL] Clones a remote repository.
git status Displays the current status of the repository.
git add [file] Adds a file to the staging area.
git commit -m "message" Creates a new commit.
git push Pushes changes to the remote repository.
git pull Fetches and merges changes from the remote repository.
git branch Displays available branches.
git checkout Switches branches.
git merge Merges changes from another branch.

Git Terminology Glossary

Some key terms that will help you understand Git:

Repository
The location where Git stores the project’s change history and files.
Commit
A save point in the project’s history that includes changes made to files.
Branch
An independent line of development within the repository.
Remote
A repository hosted on an external server, such as GitHub or GitLab.
Staging Area
An intermediate stage where you select the changes to include in the next commit.
Merge
The action of combining changes from one branch into another.
Rebase
A method for moving or combining commits onto a new base in history.
Conflict
Occurs when two branches have incompatible changes in the same file.
Tag
A marker to identify specific points in history, such as released versions.