# Git ## What’s a version control system? A version control system, or VCS, tracks the history of changes as people and teams collaborate on projects together. As the project evolves, teams can run tests, fix bugs, and contribute new code with the confidence that any version can be recovered at any time. Developers can review project history to find out: - Which changes were made? - Who made the changes? - When were the changes made? - Why were changes needed? ## What’s a distributed version control system? Git is an example of a distributed version control system (DVCS) commonly used for open source and commercial software development. DVCSs allow full access to every file, branch, and iteration of a project, and allows every user access to a full and self-contained history of all changes. Unlike once popular centralized version control systems, DVCSs like Git don’t need a constant connection to a central repository. Developers can work anywhere and collaborate asynchronously from any time zone. Without version control, team members are subject to redundant tasks, slower timelines, and multiple copies of a single project. To eliminate unnecessary work, Git and other VCSs give each contributor a unified and consistent view of a project, surfacing work that’s already in progress. Seeing a transparent history of changes, who made them, and how they contribute to the development of a project helps team members stay aligned while working independently. ## Story of Git Linus needed a new source code revision manager for Linux, and none of the available options in 2005 where good enough, so he wrote his own in. Kernel 2.6.12 was the first release managed by Git and version 1.0 of Git was released in December 2005. ## Git Popularity ![alt https://www.openhub.net/repositories/compare](https://i.imgur.com/4A8T4sv.jpg "https://www.openhub.net/repositories/compare") ![alt Google Trend](https://i.imgur.com/ehaOrMc.png "Google Trend") From openhub.net and google trend, Git very popular compare to others VCS. ## Why Git? According to the latest Stack Overflow developer survey, more than 70 percent of developers use Git, making it the most-used VCS in the world. Git is commonly used for both open source and commercial software development, with significant benefits for individuals, teams and businesses. - Git lets developers see the entire timeline of their changes, decisions, and progression of any project in one place. From the moment they access the history of a project, the developer has all the context they need to understand it and start contributing. - Developers work in every time zone. With a DVCS like Git, collaboration can happen any time while maintaining source code integrity. Using branches, developers can safely propose changes to production code. - Businesses using Git can break down communication barriers between teams and keep them focused on doing their best work. Plus, Git makes it possible to align experts across a business to collaborate on major projects. ## What’s a repository? A repository, or Git project, encompasses the entire collection of files and folders associated with a project, along with each file’s revision history. The file history appears as snapshots in time called commits, and the commits exist as a linked-list relationship, and can be organized into multiple lines of development called branches. Because Git is a DVCS, repositories are self-contained units and anyone who owns a copy of the repository can access the entire codebase and its history. Using the command line or other ease-of-use interfaces, a git repository also allows for: interaction with the history, cloning, creating branches, committing, merging, comparing changes across versions of code, and more. Working in repositories keeps development projects organized and protected. Developers are encouraged to fix bugs, or create fresh features, without fear of derailing mainline development efforts. Git facilitates this through the use of topic branches: lightweight pointers to commits in history that can be easily created and deprecated when no longer needed. Through platforms like GitLab, Git also provides more opportunities for project transparency and collaboration. Public repositories help teams work together to build the best possible final product. ## Basic Git commands To use Git, developers use specific commands to copy, create, change, and combine code. These commands can be executed directly from the command line or by using an application like [Git Bash](https://git-scm.com/download/win). Here are some common commands for using Git: - `git init` initializes a brand new Git repository and begins tracking an existing directory. It adds a hidden subfolder within the existing directory that houses the internal data structure required for version control. - `git clone` creates a local copy of a project that already exists remotely. The clone includes all the project’s files, history, and branches. - `git add` stages a change. Git tracks changes to a developer’s codebase, but it’s necessary to stage and take a snapshot of the changes to include them in the project’s history. This command performs staging, the first part of that two-step process. Any changes that are staged will become a part of the next snapshot and a part of the project’s history. Staging and committing separately gives developers complete control over the history of their project without changing how they code and work. - `git commit` saves the snapshot to the project history and completes the change-tracking process. In short, a commit functions like taking a photo. Anything that’s been staged with git add will become a part of the snapshot with git commit. - `git status` shows the status of changes as untracked, modified, or staged. - `git branch` shows the branches being worked on locally. - `git merge` merges lines of development together. This command is typically used to combine changes made on two distinct branches. For example, a developer would merge when they want to combine changes from a feature branch into the main branch for deployment. - `git pull` updates the local line of development with updates from its remote counterpart. Developers use this command if a teammate has made commits to a branch on a remote, and they would like to reflect those changes in their local environment. - `git push` updates the remote repository with any commits made locally to a branch. Learn more from a full reference guide to [Git commands.](https://git-scm.com/docs) ## Let's Do it ### Example: Contribute to an existing repository ```shell= # download a repository on GitLab.com to our machine git clone https://gitlab.com/me/repo.git # change into the `repo` directory cd repo # create a new branch to store any new changes git branch my-branch # switch to that branch (line of development) git checkout my-branch # make changes, for example, edit `file1.md` and `file2.md` using the text editor touch file1.md touch file2.md # stage the changed files git add file1.md file2.md # take a snapshot of the staging area (anything that's been added) git commit -m "my snapshot" # push changes to gitlab git push --set-upstream origin my-branch ``` ### Example: Start a new repository and publish it to GitLab First, you will need to create a new repository on GitLab. Do not initialize the repository with a README, .gitignore or License. This empty repository will await your code. ```shell= # create a new directory, and initialize it with git-specific functions git init my-repo # change into the `my-repo` directory cd my-repo # create the first file in the project touch README.md # git isn't aware of the file, stage it git add README.md # take a snapshot of the staging area git commit -m "add README to initial commit" # provide the path for the repository you created on gitlab git remote add origin https://gitlab.com/YOUR-USERNAME/YOUR-REPOSITORY.git # push changes to gitlab git push --set-upstream origin main ``` ### Example: Update in same file ```shell= # download a repository on GitLab.com to our machine https://gitlab.com/sofianhw/git-training.git # change into the `repo` directory cd git-training # create a new branch to store any new changes git branch YOUR-NAME # switch to that branch (line of development) git checkout YOUR-NAME # make changes nano names.txt # take a snapshot of the staging area (anything that's been added) git commit -m "Add my name" # push changes to gitlab git push --set-upstream origin YOUR-NAME ``` If conflict ```shell= git checkout conflicts_branch git fetch git rebase master # Fix conflicts by editing the files. git add conflicts.rb # No need to commit this file git rebase --continue # Remember that we have rewritten our commit history so we # need to force push so that our remote branch is restructured git push origin conflicts_branch -f ``` Rewriting last commit ```shell= git commit --amend -m "Update" ``` Delete last commit ```shell= git reset -hard HEAD^ ``` Undo last commit ```shell= git revert HEAD ``` Compare Commit ```shell= git diff commit1 commit2 ``` ## Git Branching - Start working on the master branch only. Don't create other branches until you really need them. - Every new developer has their own branch (local clone) - Never break master. Push only stuff what works.Other developers must be able to branch from master at any time and start working on something new,instead of having to deal with fixing a broken state that somebody else left in master. - If you have a need to push your work that is half-way done,that is a good signal that you should create a new branch. - Typically tree kind of branches: - feature branches - bugfix branches - personal branches - Project layout: split code up in many separate files. – Lower likelihood of conflicting changes when branches merge. ## Git Workflow ### GitFlow Gitflow Workflow is a Git workflow that helps with continuous software development and implementing DevOps practices. It was first published and made popular by [Vincent Driessen at nvie](http://nvie.com/posts/a-successful-git-branching-model/). The Gitflow Workflow defines a strict branching model designed around the project release. This provides a robust framework for managing larger projects. Gitflow is ideally suited for projects that have a scheduled release cycle. ![alt GitFlow](https://i.imgur.com/m2DoZrq.png "GitFlow") ### Getting Started ```shell= git flow usage: git flow <subcommand> Available subcommands are: init Initialize a new git repo with support for the branching model. feature Manage your feature branches. bugfix Manage your bugfix branches. release Manage your release branches. hotfix Manage your hotfix branches. support Manage your support branches. version Shows version information. config Manage your git-flow configuration. log Show log deviating from base branch. Try 'git flow <subcommand> help' for details. ``` #### Initialize ```shell= git flow init ``` #### Feature Branches ![](https://i.imgur.com/OkYJgSu.png) Creating a feature branch ```shell= git flow feature start feature_branch ``` Finishing a feature branch ```shell= git flow feature finish feature_branch ``` #### Release Branches ![](https://i.imgur.com/fHLA3js.png) Creating a release branch ```shell= git flow release start 0.1.0 ``` Finishing a release branch ```shell= git flow release finish '0.1.0' ``` #### Hotfix Branches ![alt GitFlow](https://i.imgur.com/m2DoZrq.png "GitFlow") Creating a hotfix branch ```shell= git flow hotfix start hotfix_branch ``` Finishing a hotfix branch ```shell= git flow hotfix finish hotfix_branch ``` #### The overall flow of Gitflow - A develop branch is created from master - A release branch is created from develop - Feature branches are created from develop - When a feature is complete it is merged into the develop branch - When the release branch is done it is merged into develop and master - If an issue in master is detected a hotfix branch is created from master - Once the hotfix is complete it is merged to both develop and master ### Trunk-Based Development ![](https://i.imgur.com/fnVrstI.png) - Whole team develops to shared branch called trunk Short lived feature branches - Release branches #### When? - Just starting up/need quick iterations - Mostly senior developers - Automated Testing - Feature Toggle #### When not? - Open source projects - Mostly junior developers