Looking to learn Git on your own, but not sure about where to get started? This article will be a great starting point for you. It’s the first in a series of articles called “Git” good, and it’s designed to help anyone learn Git online in a simple, linear and accessible manner.
In this article, we will be going through the install process for Git and exploring its most basic functionalities.
- What is Git?
- Installing Git
- Running Git for the first time
- Starting the project
What is Git?
Git is a source control system. It is a software that is designed to track changes on a set of files, most often used by programmers to backup and version their projects, as well as collaborate with each other. The unique thing about Git as a source control system is that it can be used both as a local source control system, as well as a distributed source control system.
In this article, we will do a simple exercise that will demonstrate the capabilities of Git as a local source control system, as well as how to upload it online, so that our project becomes managed by a distributed source control system.
Want to learn more about the types of source control systems available? You can check out this article.
a. Downloading your OS installer
To get started, the first thing we need to do is install Git SCM using one of the links below, depending on the operating system you are on:
While there are other, more user-friendly softwares (such as GitHub Desktop) that can also manage Git projects, they usually don’t offer the full suite of features and capabilities that Git provides.
b. Setting the default text editor
Use the default or recommended settings for all the prompts in your installation, except for the one that asks for you to set your default Git text editor. Select Notepad (or any other text editor you are familiar with), or TextEdit if you are on Mac.
We will be using Notepad as our text editor in this guide.
Article continues after the advertisement:
Running Git for the first time
Once Git is installed, you’ll want to right-click anywhere in a folder or on a Desktop and select Git Bash Here. This will open the Git command line, which is where we will be doing most of our work on.
a. Set a username and email address
The first thing you’ll want to do in Git Bash is to execute the following commands:
$ git config --global user.name "John Doe" $ git config --global user.email firstname.lastname@example.org
This sets the username and email that will be tagged to commits made by this computer. While not particularly important in smaller, one-man projects, proper authorship tagging is important in team projects that are eventually uploaded onto a repository like GitHub, or shared amongst multiple computers, as it allows us to track all changes to our projects and who made them.
b. Re-setting the default text editor
If you did not set the correct text editor for yourself during installation, you can still set it in Git Bash with the following command:
$ git config --global core.editor [EDITOR_NAME]
To set your text editor to Notepad, you will use the following command:
$ git config --global core.editor notepad
Starting on our project
a. Initialising the project onto Git
To allow Git to start doing its file tracking work, we will need to put all the files we want Git to manage in a project folder. For this article, we will be using this simple Python project as our example project.
Download the ZIP from the link, and extract the zipped files into a folder. We will be naming our folder
swissknife, which is the name of the Python project.
Open Git Bash by right-clicking inside your project folder, and select Git Bash Here. Then, type in the following command into Git Bash.
$ git init
This converts your folder into a Git project folder, which creates a hidden
.git folder in your project folder. This hidden folder stores all of your Git project data.
We are now ready to do some source control with Git.
Committing our first version
swissknife folder contains scripts for a working version of project. Eventually, new features will be added onto the project to expand its capabilities. Before we add new features, however, we want to commit the current version of our project onto Git.
A commit is a snapshot of the project. Having a commit allows us to roll our project back to this version if anything goes wrong (e.g. if the new version introduces errors that breaks the program, and we can’t fix it).
First, we need to open Git Bash and type in:
$ git add *
This tells Git that we want all the files in our folder to be included in our commit. Once this is done, we run the following command to commit.
$ git commit
You will get some messages on Git Bash, followed by a pop-up on Notepad that contains text similar to what you see in the box below. Type in a commit message on the first line of the pop-up, then press Ctrl + S to save the message. Once you are done, close Notepad.
This is our first commit for the project! # Please enter the commit message for your changes. Lines starting # with '#' will be ignored, and an empty message aborts the commit. # # On branch master # # Initial commit # # Changes to be committed: # new file: instructions/instructions.py # new file: swissknife.py #
To confirm that your commit has been made, you can use the
git log command, which should give the following output:
$ git log commit f66d99d6f6d905c29cad2ce37ad3862c82aeb968 (HEAD -> master) Author: Terence <email@example.com> Date: Sun May 23 17:24:00 2021 +0800 This is our first commit for the project!
Article continues after the advertisement:
Making further commits
As the project is developed further, we are going to make more commits at key points in the project development. Hence, we are going to explore how to commit further changes made to our projects.
Make the following changes (highlighted in green) to
instructions/instructions.py. Alternatively, you can also copy and paste the contents below into their respective files to reflect the changes.
We are also gonna add a new file
readme.md into our project folder, whose contents are displayed below.
import os class SwissKnife: modules = list() @classmethod def start(cls): cls.welcome() while True: cls.menu() @classmethod def read_modules(cls): from glob import glob dirlist = glob("*/") # Searches for directories. for directory in dirlist: file = directory + directory[0:-1] # If the directory has a file that we can run, run it. if(os.path.isfile(file + ".py")): cName = directory[0:-1].capitalize() mod = __import__(file.replace("\\","."),fromlist=[cName]) obj = getattr(mod, cName)() cls.modules.append(obj); print("There are",len(cls.modules),"modules installed."); @classmethod def welcome(cls): print("===========================================") print("Welcome to Swiss Knife!") cls.datetime() cls.display_cwd() cls.read_modules() print("===========================================") print() @classmethod def menu(cls): # Notify the user they are in the menu. print("Below are the modules available.") print("--------------------------------") l = len(cls.modules) for i in range(0, l): print(i+1,". ",cls.modules[i].display_name,sep="") print("E. Exit") print() # Retrieve the option and process it. opt = input("Select the module you want to run: ") if opt.lower() == "e": print() print("Exiting program... Good bye!") exit() else: opt = int(opt) if opt > 0 and opt <= l: cls.modules[opt - 1].run() else: print("Invalid option selected. Please try again.") @staticmethod def display_cwd(): os.chdir(os.path.dirname(os.path.realpath(__file__))) print("The current working directory is: ",os.getcwd(),".",sep="") @staticmethod def datetime(): from datetime import date print("The date today is ", date.today().strftime("%B %d, %Y"),".",sep="") SwissKnife.start()
class Instructions: name = "Instructions" display_name = "Display instructions." @classmethod def run(cls): print() print() print("----------------") print("Instructions") print("----------------") print() print("Swiss Knife is a modular Python application designed to do common actions that are easier to perform using scripts, like finding and replacing strings in text file or programming tools.") print() print("It is designed to be a programmer's best friend. No matter what language you are working on, you are sure to find Swiss Knife modules that are of use to you.") print() print("To add an additional module into Swiss Knife, create a folder beside swissknife.py and write a class in the folder with the same name.") print() print("----------------") print("END Instructions") print("----------------") print() print()
# Usage Guide To use this program, you'll need to have Python installed. Once Python is installed, run swissknife.py.
Once the changes are made to existing files, and the new
readme.md file is added, we can run the
git status command to see all modified files, as well as newly-added files, in the project since the last commit.
$ git status On branch master Changes not staged for commit: (use "git add …" to update what will be committed) (use "git restore …" to discard changes in working directory) modified: instructions/instructions.py modified: swissknife.py Untracked files: (use "git add …" to include in what will be committed) instructions/pycache/ readme.md no changes added to commit (use "git add" and/or "git commit -a")
We can also run
git diff [FILENAME], which will compare the file with the last committed version and show the differences between them. For example, here is the output for
git diff swissknife.py:
Note: If your output for
git diff is very long, use the ↑ and ↓ arrow keys to navigate through it. When you are done, press the Q key to exit.
$ git diff swissknife.py diff --git a/swissknife.py b/swissknife.py index c55e619..4900c15 100644 --- a/swissknife.py +++ b/swissknife.py class SwissKnife: @@ -34,6 +33,7 @@ class SwissKnife: def welcome(cls): print("===========================================") print("Welcome to Swiss Knife!") + cls.datetime() cls.display_cwd() cls.read_modules() print("===========================================") @@ -57,6 +57,8 @@ class SwissKnife: opt = input("Select the module you want to run: ") if opt.lower() == "e": + print() + print("Exiting program… Good bye!") exit() else: opt = int(opt)
Note: You can also use the
git diff command without specifying a filename, but it’s not recommended as that will output a lot of data if there are many changed files.
The next thing we want to do is add all new and changed files:
$ git add *
Then, we make another commit:
$ git commit
As usual, when we run the commit command, we’ll need to key in an appropriate commit message. Afterwards, the
git log should show us our previous commit.
$ git log commit b5c65ae31b2f03d4872be6ae1bdf9032c265590c (HEAD -> master) Author: Terence <firstname.lastname@example.org> Date: Mon May 24 01:31:06 2021 +0800 Added readme.md and made some aesthetic updates. commit f66d99d6f6d905c29cad2ce37ad3862c82aeb968 (HEAD -> master) Author: Terence <email@example.com> Date: Sun May 23 17:24:00 2021 +0800 This is our first commit for the project!
Fun fact: You can also use
git show to display the details of your last commit.
git show is different from
git log because it also shows you the changes made to each file (similar to what you get in
This wraps up Part 1 of our article. In the next article, we will be exploring how to revert changes to our projects, as well as how to use branches to safely develop new features to our project without affecting the stability of our existing codebase.
Be sure to drop us a comment if you like the article, or if you have any suggestions on how you can make it better.
Article continues after the advertisement: