Deep dive into version control using Git

Deep dive into version control using GitMastering Git for efficient code development and collaborationMumtahin MonzoorBlockedUnblockFollowFollowingJun 21Git is a free tool that allows for efficient code revisions by providing a distributed version control system.

It is one of the most helpful tools I learned when I started learning programming.

Whether I was working on my side projects, collaborating with friends, or working in a professional setting, Git proved itself to be extremely helpful.

The best analogy I can give you is a writing a report for a group project on a platform like Google Doc.

Your colleagues can work on their own segment of the report simultaneously without having to directly modify your part.

Git achieves this objectives by allowing you to create branches from a master branch and have multiple people collaborate on a project.

I will explain what Git branches are after walking through the installation process.

If you are just starting out or simply coding on projects solo, Git can still help you track your coding history, revert changes, and maintain an efficient workflow.

You have choices when working with Git.

I started my journey on Github as a student during my undergraduate studies.

Signing up as a student has the perk of getting a free private Github account with Github Education.

If you are a student, checkout the deals here.

Other than Github, I have also used Gitlab to collaborate on projects.

You can pick Github or Gitlab since they both provide similar functionalities.

This tutorial will focus on setting you up with Github.

If you want to migrate repositories from one platform to the other, please refer to the migration documents here or comment below and I will be happy to write a tutorial on it.

InstallationLinux$ sudo apt install git-allIf you have trouble or need installation for other Unix based distributions, visit here.

macOSFirst check whether you already have Git installed by running the following:$ git –versionIf you do not have the latest version, an installation prompt should appear.

Otherwise, the installation link can be accessed here for the most recent version.

WindowsFor windows, please click here and download should begin automatically.

This is Git for windows and according to the official Git documentation, Git for windows is different from Git itself.

Git windows comes with Git BASH which has BASH emulator so Git can be easily run on windows using command line features.

This way, experience you gain from running git commands on windows can easily be transferred to other systems if needed.

Another installation option is to install Github desktop.

Create a Github AccountAccess the sign up flow and create an account: https://github.

com/join?source=header-homeOnce you have created a Github account and you are logged in, you can now create repositories.

A repository is a place where you put your project(s) in.

You can decide to have a single project per repository or you can have a repository with many branches.

For the latter your branches can be related but I have seen users create unrelated branches in the same repository also known as orphan branches.

BranchesIf you are brand new to version control and Git, all of this can sound a bit confusing at this point.

I like to think of repositories as a meal.

Let’s treat it like a thanksgiving dinner.

You have the turkey, stuffing, cranberry sauce, and mashed potatoes in your plate.

The plate you will serve yourself all the different items of food is the repository.

You can choose to pick up four little plates (four repositories) and serve each item of food on a corresponding plate.

Your other option maybe to serve yourself each of the four items (branches) on a bigger plate (repository).

A branch is a snapshot of your main branch (the master branch resembling the closest vision of my project).

You take this particular snapshot and add additional changes/ features without affecting the main (master) branch.

No matter which method you prefer, there are choices for you to organize your projects using Git in a clean and concise manner.

I personally prefer having a single repository representing a project and then inside the project’s repository I will create branches that add features to my project.

Git branches are better understood once you get the concept of Git data stores.

When you make changes and commit them, Git stores the information as an object holding the snapshot of that change.

This is a special attribute for Git as a version control system because other version control systems preserve changes as a list of file-based changes.

Other Version Control SystemsOther Version Control Systems — Image taken from git-scmGit Storing DataGit storing data as a stream of snapshots — image taken from git-scmThis means that Git will be aware of any and all changes in your local repository once you initialize it (more about initialization below).

StatesWithin a given branch you have files and at any given time your files can be in one of three states:ModifiedStagedCommittedModified state is when changes have been made but none of the changes have been saved as their corresponding snapshots.

Picking modified files and identifying them to be items you want in your next saved snapshot is called staging.

Committed state is when the intended changes are safely stored in your local database.

It is really important to understand the different states any given file in your local repository in order to safely push changes to the remote repository.

Create your first repositoryNow that we have a background on repositories and branches, let’s create our first repository.

Click on the top right corner to open the link “new repository”.

Give the repository a new name and choose the privacy setting.

The third option on this set up page gives you the ability to initialize the repository with a README file.

We can skip that for now but README.

md files are quite important to use.

This is a text file that gets used by users to provide project overview, features, installation instructions, license, and credits.

Github will use this file, if available, to create a summary for your project on your main directory page for any given repository.

Once you have created a repository, this is known as a remote repositories.

Git usually provides you with the choices and the commands involved in creating a new repository on your local or use a local folder and initialize it as a repository.

For this tutorial, let’s say there is already a folder you already have containing code and documentation.

You want to add the content to this newly created repository.

Populate Remote Repository with local files$ git initThe command above creates an empty repository in the local folder holding files you want to add to the remote repository.

After initialization of the current local directory as a git repository, if you have files living in this local folders, they are in the modified state (see earlier discussion of States).

To stage these modified files, we need to mark the intended files.

Since we are adding to this remote repository for the first time, you need to add the following:git remote add origin https://github.

com/<username>/<your_repository_name>.

gitFor commits after this initial process, you can add files with either of the commands below:$ git add <file_path># commit all files$ git add .

At this point the the files are sitting in the “staging area”.

$ git commit -m “write your commit message here.

”Files should now be safely committed and recorded to the local database.

The commits now finally can be pushed to the remote repository with:$ git pushFor your initial commit, git push should push your current changes without any problems.

However, there maybe instances where you have multiple branches.

You want to push all your local branches to a specific remote repository.

In that case, use:$ git push <remote> — allAs you gain experience with Git and work through your projects, you may need to use the — force flag on git push.

It is highly recommended that the — force flag be used only when you are absolutely sure about your suggestions.

$ git push <remote> — forceWhen you push your changes, Git wants to verify the user pushing changes to a remote repository and will ask you for the username and password that you have created earlier during sign up.

If you are the global user, configure the username and password in global git config settings as shown later.

Make a local copy from a remote repositoryThe example above focuses on the scenario that you have development work done on your local machine that you then push to the remote repository.

The circumstance can be reversed where you need to use the content of a remote repository to get started on local development.

In this case, you are required to clone the repository of interest and to do this, make sure you have the access.

For example, you want to develop using bootstrap.

You visit the bootstrap github repository: https://github.

com/twbs/bootstrap.

Click on the clone or download button on the repository to copy the remote repository link.

Clone the repository with$ git clone https://github.

com/twbs/bootstrap.

gitUpdate local copies with changes in remoteAssume that you have submitted your changes but right after your co-worker submitted changes to the same branch.

In order to make sure your local branch is up to date with these changes, you need to pull those changes down.

$ git pull <remote>Git pull brings you the information from the remote repository by using (1)git fetch and (2)git merge under the hood.

The fetching happens from the node where the local repository has diverged from the master branch.

You can use git fetch at any time if there is need for tracking.

Git fetch downloads the information not available in your local repository and then git merge integrates the information into your local repository.

Another command very similar to git merge is git rebase.

The main advantage of using git rebase over git merge is that the integration of new information happens at the end of the last commit on a branch.

This results in a more linear commit history which is not always the case when git merge is being used.

In the case of git pull, the second step of merging the changes can also be swapped with a rebase using the following:$ git pull –rebase <remote>A scenario where as you are making changes to your local repository and you need to git pull new changes from the remote repository, switch to a different branch, etc.

You don’t want your local changes to be directly impacted but you want a clean working tree.

In that case,# 1 – stash local changes$ git stash# 2 – pull remote changes $ git pull # 3 – view stashed list$ git stash list# 4 – access what you JUST stashed$ git stash apply # 5 – access an older stash from the stashed list on #3$ git stash apply <stashed-id-from-list>At this point, you may ask what is the difference between what we are trying to achieve in git clone vs.

git pull?.First, their purposes are different.

Git clone takes information living in a remote repository and makes a local copy.

This is a one time action.

Git pull is the command used to update your local repository of small changes as the remote branch gets updated.

This is used more than once and preferably any time a change has been committed where your local branch is behind.

Git ConfigurationsWe mentioned that during a commit Git wants to verify the details of the user committing the changes to a repository.

It can get repetitive always putting in the username and password for each commit.

Using the Git global config file you can perform some modifications to mitigate the repetitiveness.

username:$ git config — global user.

name <username>2.

Email:$ git config — global user.

email <email>3.

Aliasing$ git config –global alias.

<alias> <git-command>Example, aliasing git status to just git s:$ git config –global alias.

s statusIt maybe needed to view and manually edit the configuration files that git uses to save the instructions above.

4.

Access Global Configuration File$ git config –global –editViewing HistoryOne of the most useful features of Git is being able easily view your commit history and get constant recap on your work.

Interruptions happen constantly during a work day.

Being able to simply run a commit log command and see the entire commit history helps you get a summary of all the changes.

$ git logIf you just run the git log command, the result can be a bit difficult for the human eye to follow.

However, we have options of decorating the logs, passing one-line commit messages, and adding a graph element.

# –all shows you the log history in its entirety# –oneline compresses the commit messages to a single line.

# –decorate adds branch names and tags from commits# –graph is a textual graph representation$ git log –all –decorate –oneline –graphSearching the commit logs by patterns is another useful feature.

If you want to go to a specific change submitted by yourself in a project where there are many collaborators, execute the following:$ git log — authors=<username>If it is a commit message containing specific phrase or patterns, search using:$ git log –grep=”<pattern>”Changes for specific files for each commits can be analyzed with stat:$ git log –statChanging HistoryRebaseUsing rebase, you can change the commit timelines as well.

It is usually advised to not rebase commits that have already been pushed to a public repository.

Passing just git rebase will take the commits from the current branch and automatically apply them to the passed branch.

I personally appreciate the interactive rebasing feature where you can decide how the commits are to be transferred to a new base.

# rebase current branch onto base(tag, commit ID, branch name, etc.

)$ git rebase <base># interactive changes$ git rebase -i <base>Changing Last Commit(s)The most frequent modifications of history are in relation to changing the last commits.

In the staging environment, you can decide that you do not want to add a certain:# change last commit message$ git commit –amendAccording to the Git documentation it is advised that you use this command carefully and treat it like a small rebase.

If you have already pushed your changes, do not amend.

Removing a file from Commit HistorySay that you got into this habit of adding all changes with git add .

and accidentally added a sensitive file that you want to remove from all your commit history.

Using the branch filter process you can achieve this:$ git filter-branch –tree-filter 'rm -f sensitive_file.

txt' HEADAdding a .

gitignoreThe scenario described above should not have occurred if you had made a file called .

gitignore and listed your “sensitive_file.

txt” as an item in that file.

Creating this file in your local directory and then adding back up files, configurations, etc.

will save you from pushing clutter to your remote repository.

Along with specific file names, you can also specify patterns.

For example, if you have *.

txt in your .

gitignore file, it would ignore all text files.

Looking at DifferencesChanges in current working directory can be directly compared to the last commit on the remote branch with:$ git diff HEADHEAD refers to the last commit in the branch that you are on.

Undo ChangesSo far we have thoroughly discussed the three different states for git files.

One of those states is staging.

If you want to undo a staged file, use$ git reset# to reset specific files use a file path$ git reset <file>Once branch has been pushed, we can still undo by changing a specific commit with revert.

The <commit> parameter shown below is a specific commit ref.

Observe your commit logs with git log (mentioned above) and then use commit ref for command below.

$ git revert <commit>ConclusionWe have come a long way from learning to create Git repositories to understanding how to undo our ‘mistakes’.

Understanding Git and getting used to the list of commands in this article may take a while but it is only a matter of time and practice.

If there are specific commands that are impossible to remember, use the aliasing method we talked about (see section on Git Configurations).

Even if you do not have a project to currently use Git for, create a mock repository and work with just text files for practice.

Ensure that your projects are well documented with README.

md (see section on Create your first repository) and commit often.

With this tutorial, you have enough knowledge to now collaborate on projects, change your projects’ histories, and keep a polished portfolio.

.

. More details

Leave a Reply