Git Basics

Git Basics

Commits, code merges, GitHub repository

Table of contents

No heading

No headings in the article.

Introduction to Git

  1. Git and the history of Git: Git is an open-source software created by Linus Torvalds in 2005. The meaning of open source is that the code of a particular software is publicly available and accessible and people can see, modify, and distribute the code at their convenience and need. This is a version control system that was created to be used by multiple developers. It helps the developers to collaborate and work on a common project to enhance the functionality of an ongoing project. Git is a source code management tool used in DevOps. It is a free and open-source version control system used to efficiently manage small to very large projects. Git is a version control system that allows multiple developers to collaborate on non-linear development by tracking changes in the source code.

    1. What is a version control system? Version control is a management system that tracks changes to a file or set of files, such as a code project. Using this system, developers can collaborate and manage the same project. This has a branching system in which each branch represents either a task or a developer, allowing the developers to work independently on a task. Finally, all of the changes are combined and merged into the main branch.

      The history of the changes made is also saved so that all project participants are aware of the changes made by a specific contributor.

    2. Git services: A Git repository is a collection of Git-tracked files and directories. It is essentially a snapshot of a project at a specific point in time, and it includes all of the project's files, directories, and metadata, as well as a history of all changes made to the project.

      We need to host our Git repositories somewhere so that we can share them and people can have access to it. For that, we need hosting platforms where we can put our code free of charge. Hosting platforms can be free or charged in different cases.

      Some examples of hosting platforms are:

      a. GitHub: Owned by Microsoft and it was launched in 2008. One of the most popular Git platforms.

      b. GitLab: Owned by GitLab Inc. Launched in 2011. This also is in great use nowadays.

      c. BitBucket: Owned by Atlassian, launched in 2008.

    3. Need to use Git as a developer: When you have completed your project, you can easily upload it to the internet using the "push" command, where it will be saved. You have complete flexibility to edit, delete, or modify your code as needed, and there is no need to keep track of your previous actions as there are commands that can retrieve the status of your work from when you last saved it. This is a useful feature.

Create the first GitHub repository

  1. Create a GitHub account:

    Go to this link and register yourself. https://github.com/signup

    Fill out the registration form and give yourself a cool username and remember the password and login credentials.

    And voila, you have a GitHub account now, well that was easy to do, isn't it?

    Then sign into your account and have a stroll with this beautiful software. Do remember to get acquainted with the options and functionalities, because at times if you cannot easily locate the options, certain tasks become overwhelming, do take out your time to explore GitHub.

  2. Install Git locally for various Operating Systems:

    First, download the latest Git for windows installer.

    Follow the given instruction on your screen.

    Open a terminal, it can be Powershell ( Windows) or Git bash and check if Git was installed correctly or not using the command, $git --version, if the output is something like git version 2.37.0.windows.1, then Git is successfully installed. And for other outputs, do the installation correctly again.

    1. Create a repository:

      1. Sign in to your GitHub account.

      2. Go to the top right-hand side and you will see a "+" icon on the menu bar.

      3. Click on this button and you will see a "New repository" option.

      4. A page will open with the Owner and Repository name as the options and you should fill the repository name with a unique name.

      5. Type in the description in the description bar.

      6. Set the visibility as public or private.

      7. Click on initialize this repository with a README (In a GitHub repository, the README is a file that contains information about the repository and its contents. It is typically the first file that a user will see when they visit the repository on the GitHub website, and it is often used to provide an overview of the project, including its purpose, how to use it, and any relevant documentation or resources).

      8. Click on "Create Repository" and you will see your repository is created.

      9. You can see your repository, go to "+" icon on menu bar and click on "Your repositories".

      10. Well done!

    2. Check-out and check-in processes:

      Check-out: Checking out a repository includes creating a local copy of the repository on your computer. This enables you to work on the code locally, making changes and then committing them to your local repository.

      Checking-in: You add your changes back to the particular repository with a detailed explanation message about the change you have made.

      Steps in GitHub:

      1. Create a local copy of the repository on your computer by using the git clone command.

      2. Make any desired changes to the code.

      3. Use the git commit command to save these changes to your local repository, along with a message describing the changes.

      4. Use the git push command to upload these changes to the remote repository on GitHub.

    3. Documentation: Documentation at GitHub is admired a lot and it gives you a detailed description of steps. When people open a folder, it opens with a ".git" folder, which is like a history database, it stores all changes, that were made at this repository.

    4. Environment: The staging environment is related to the commit command.

      A commit command is a record of all the files that a person has changed since the last time he/she worked on the project at any point.

      But how is git informed about which file to put into commit? So, this is where the staging environment or index come in. In Git, the git add command is used to stage changes for commit. When you make changes to files in your repository, these changes are not automatically included in the next commit. Instead, you must use the git add command to specify which changes you want to include in the commit.

      The git add command takes one or more file names as arguments, and it adds the changes made to these files to the "staging index." This is a temporary area where changes are stored until they are committed to the repository.

      For example, if you have made changes to a file called main.c, you can stage these changes for commit by running the following command:

      git add fileName.c

    5. Create a good coverage for your repository: To create a local version of your project, you will need to follow these steps:

      1. Make sure you have a version control system installed on your local machine, such as Git.

      2. Use a command line interface (CLI) to navigate to the directory where you want to store your local project.

      3. Initialize a new Git repository in this directory by running the following command:

    ```plaintext
    Copy codegit init
    ```

    1. If you have an existing project on a remote repository (such as on GitHub), you can clone the repository to your local machine by running the following command:


    ```plaintext
    Copy codegit clone https://github.com/<username>/<repository>.git
    ```

    1. If you do not have an existing project on a remote repository, you can create a new project locally by creating a new directory for your project and adding files to it.

    2. Once you have created your local project, you can use Git to track changes to your files and commit them to your local repository. You can also push your commits to a remote repository if you want to share your project with others or access it from a different machine.

    3. It's a good idea to create a .gitignore file to specify which files and directories you want Git to ignore when tracking changes to your project. This can help to avoid committing unnecessary or sensitive files to your repository.

6. **Create README files locally:** To create a README file locally, follow these steps:

    1. Navigate to the directory where you want to store your README file using a command line interface (CLI) or a file manager.

    2. Create a new file by running the following command in the CLI:


    ```plaintext
    Copy codetouch README.md
    ```

    1. Open the [README.md](http://README.md) file in a text editor or IDE of your choice.

    2. Add the content you want to include in your README file. The README file is usually used to provide information about your project, such as its purpose, how to set it up and run it, and any dependencies it has. You can use markdown syntax to format the text in your README file.

    3. Save the file and commit it to your local repository using Git.

7. **Commit your changes and publish them at GitHub**: To commit your changes and publish them on GitHub, follow these steps:

    1. Make sure you have a version control system, such as Git, installed on your local machine.

    2. Navigate to the directory of your project using a command line interface (CLI).

    3. Stage your changes by running the following command:


    ```plaintext
    Copy codegit add .
    ```

    1. Commit your changes by running the following command:


    ```plaintext
    Copy codegit commit -m "Commit message"
    ```

    Replace "Commit message" with a brief description of your changes.

    1. If you have an existing repository on GitHub, you can push your changes to the remote repository by running the following command:


    ```plaintext
    Copy codegit push origin <branch>
    ```

    Replace `<branch>` with the name of the branch you want to push your changes to. For example, if you are pushing to the `master` branch, you would run `git push origin master`.

    1. If you do not have an existing repository on GitHub, you can create a new repository and push your local repository to it. To do this, log in to your GitHub account, navigate to the repositories page, and click the "New" button. Follow the prompts to create a new repository and push your local repository to it.

8. **Git commands**: Here is a list of some useful commands for Git:

    * `git init`: Initializes a new Git repository in the current directory.

    * `git clone <repository>`: Clones an existing repository to your local machine.

    * `git add <file>`: Stages a file for commit.

    * `git add .`: Stages allmodified and new files for commit.

    * `git commit -m "Commit message"`: Commits the staged files with the specified commit message.

    * `git push <remote> <branch>`: Pushes the specified branch to the specified remote repository.

    * `git pull <remote> <branch>`: Pulls the specified branch from the specified remote repository.

    * `git status`: Displays the status of the current repository, including modified files and the current branch.

    * `git log`: Shows a history of all commits in the current repository.

    * `git diff`: Shows the differences between the staged and unstaged changes in the current repository.

Git Merge

  1. Branching workflow: Branching is a powerful feature in Git that allows you to create separate lines of development within a single repository. This can be useful for working on new features, fixing bugs, or experimenting with different ideas without disrupting the main branch of your project.

    Here is a basic workflow for using branches in Git:

    1. Create a new branch by running the following command:
```plaintext
Copy codegit branch <branch name>
```

1. Switch to the new branch by running the following command:


```plaintext
Copy codegit checkout <branch name>
```

1. Make changes to your code and commit them to the new branch as you normally would.

2. When you are ready to merge your changes back into the main branch (usually `master`), switch to the main branch and pull in the changes from the new branch by running the following command:


```plaintext
Copy codegit merge <branch name>
```

1. If there are any conflicts between the two branches, you will need to resolve them by editing the conflicting files and committing the resolved changes.

2. Once the merge is complete, you can delete the old branch if it is no longer needed by running the following command:


```plaintext
Copy codegit branch -d <branch name>
```
  1. Git Merge: git merge is a Git command used to combine the changes from multiple branches into a single branch. When you run git merge, Git will compare the changes in the two branches and create a new commit that combines them.

    Here is the basic syntax for merging two branches in Git:

     Copy codegit merge <branch>
    

    For example, if you want to merge the changes from the feature branch into the master branch, you would run the following command:

     Copy codegit checkout master
     git merge feature
    

    If there are no conflicts between the two branches, the merge will be completed automatically. If there are conflicts, Git will pause the merge and ask you to resolve the conflicts manually. To do this, you will need to edit the conflicting files and commit the resolved changes.

  2. Git Flow: Git flow is a popular branching model for Git that aims to provide a structured workflow for managing branches in a project. It involves creating separate branches for different stages of development, such as development, release, and hotfix branches.

    Here is a basic overview of the Git flow workflow:

    1. Create a development branch from the master branch. This is where all new development work should take place.

    2. When you are ready to release a new version of your project, create a release branch from the development branch. This branch is used to finalize and test the release before it is merged into the master branch.

    3. When the release branch is ready to be deployed, merge it into the master branch and create a new tag to mark the release.

    4. If you need to make a quick fix to a released version of your project, create a hotfix branch from the master branch. Make the necessary changes and merge the hotfix branch back into the master branch.

    5. When the hotfix is complete, merge it back into the development branch to ensure that the fix is included in future releases.

Git flow can be a useful tool for organizing and managing the development of your project, but it is not the only way to use Git. You can also use other branching models or create your own workflow that fits the needs of your project.
  1. Git Rebasing: Git rebasing is a way to integrate changes from one branch into another branch. It involves replaying the commits from the source branch on top of the destination branch, rather than merging the two branches together.

    Here is the basic syntax for rebasing a branch in Git:

     Copy codegit rebase <source branch> <destination branch>
    

    For example, if you want to rebase the feature branch onto the master branch, you would run the following command:

     Copy codegit checkout feature
     git rebase master
    

    Rebasing has a number of benefits over merging, including a cleaner commit history and the ability to preserve the linear structure of the commits in a branch. However, it can also be more difficult to undo changes made during a rebase, so it is important to be careful when using this command.

  2. Using Git merge: To use git merge, you will need to have a version control system, such as Git, installed on your local machine.

    Here is the basic syntax for merging two branches in Git:

     Copy codegit merge <branch>
    

    For example, if you want to merge the changes from the feature branch into the master branch, you would run the following command:

     Copy codegit checkout master
     git merge feature
    

    If there are no conflicts between the two branches, the merge will be completed automatically. If there are conflicts, Git will pause the merge and ask you to resolve the conflicts manually. To do this, you will need to edit the conflicting files and commit the resolved changes.

  3. Fast-forward and 3-way merge: When merging two branches in Git, there are two main types of merge: fast-forward and 3-way merge.

    A fast-forward merge is a simple merge that moves the branch pointer of the destination branch to the commit on the source branch, without creating a new commit. This happens when the destination branch is an ancestor of the source branch, meaning that it contains all of the commits in the source branch.

    A 3-way merge, on the other hand, creates a new commit that combines the changes from both branches. This happens when the two branches have diverged, meaning that they have commits that are not present in the other branch.

    Here is an example of a fast-forward merge:

     Copy codeA---B---C---D---E (master)
              \
               F---G---H (feature)
    

    In this example, the feature branch is a direct descendant of the master branch, so a fast-forward merge can be performed by simply moving the master branch pointer to the H commit:

     Copy codeA---B---C---D---E---F---G---H (master)
    

    Here is an example of a 3-way merge:

     Copy codeA---B---C---D (master)
              \
               E---F---G (feature)
                    \
                     H---I---J (feature2)
    

    In this example, the feature and feature2 branches have both diverged from the master branch, so a 3-way merge is needed to combine the changes. A new commit, K, is created to merge the changes from both branches:

     Copy codeA---B---C---D---K (master)
              \       /
               E---F---G (feature)
                    \   \
                     H---I---J (feature2)
    
  4. Resolving conflict: When merging two branches in Git, conflicts may occur when the same lines of code have been modified in both branches. When this happens, Git will pause the merge and ask you to resolve the conflicts manually.

    To resolve conflicts in Git, follow these steps:

    1. Open the conflicting files in a text editor or IDE. You will see markers in the code indicating the conflicting lines.

    2. Review the conflicting changes and decide which changes you want to keep. You can delete the markers and the changes you do not want to keep.

    3. Save the modified files and stage them for commit by running the following command:

```plaintext
Copy codegit add <file>
```

1. Commit the changes by running the following command:


```plaintext
Copy codegit commit -m "Resolved conflicts"
```

1. If there are multiple conflicting files, repeat steps 2-4 for each file.

2. Once all conflicts have been resolved, you can continue the merge by running the `git merge --continue` command.
  1. Git merge advanced example: Here is an example of how to use the git merge command to merge two branches in a more advanced scenario:

    1. Check out the branch you want to merge into (the destination branch). For example:
```plaintext
Copy codegit checkout master
```

1. Fetch the latest commits from the remote repository by running the following command:


```plaintext
Copy codegit fetch
```

1. Merge the changes from the remote branch into your local branch. For example, if you want to merge the `feature` branch from the `origin` remote, you would run the following command:


```plaintext
Copy codegit merge origin/feature
```

1. If there are conflicts, resolve them by editing the conflicting files and committing the resolved changes.

2. Push the merged changes to the remote repository by running the following command:


```plaintext
Copy codegit push origin <branch>
```

1. If you want to delete the merged branch, you can do so by running the following command:


```plaintext
Copy codegit branch -d <branch>
```
  1. Additional materials about branching and merging: Here are some additional resources that you may find helpful for learning more about branching and merging in Git:

  2. Git CheatSheets: Here is a Git cheatsheet with some common Git commands and their usage:

    • git init: Initializes a new Git repository in the current directory.

    • git clone <repository>: Clones an existing repository to your local machine.

    • git add <file>: Stages a file for commit.

    • git add .: Stages all modified and new files for commit.

    • git commit -m "Commit message": Commits the staged files with the specified commit message.

    • git push <remote> <branch>: Pushes the specified branch to the specified remote repository.

    • git pull <remote> <branch>: Pulls the specified branch from the specified remote repository.

    • git status: Displays the status of the current repository, including modified files and the current branch.

    • git log: Shows a history of all commits in the current repository.

    • git diff: Shows the differences between the staged and unstaged changes in the current repository.

    • git branch <branch name>: Creates a new branch with the specified name.

    • git checkout <branch name>: Switches to the specified branch.

    • git merge <branch>: Merges the specified branch into the current branch.

    • git rebase <source branch> <destination branch>: Integrates the changes from the source branch into the destination branch by replaying the commits from the source branch on top of the destination branch.

THANK YOU!

HAPPY LEARNING!!

Did you find this article valuable?

Support Aditya Singh Rathore by becoming a sponsor. Any amount is appreciated!