Table of Contents

Git

GitHub: GitOps, GitHub Copilot (Learn AI-Assisted Python Programming), GitHub for Major Software and Languages, GitHub Fundamentals, GitHub Inventor: GitHub and Git, GitHub Stars: GitHub Organization Ranking, GitHub Stars Ranking, GitHub Star Ranking for Repositories, GitHub Big Tech, Cloud Monk's favorite GitHub repos, gh plugin, git help, Version control, GitHub topics, Git topics, Git, GitHub repos, GitHub bibliography, Manning Git-GitHub Series, GitHub Actions, GitHub CodeSpaces, GitHub CLI, GitHub Free, GitHub Pro, GitHub Team, GitHub Enterprise, GitHub security (GitHub MFA - GitHub Passkeys) - GitHub Secrets - Authenticating with GitHub from Git (gh auth login), GLFS, GitHub Packages, GitHub alternative source code repos (GitHub - GitLab - AWS CodeCommit - Google Cloud Source Repositories - Bitbucket), Install Git, Git for Windows (choco search github, brew search github), Git for Linux, Git for macOS, GitHub glossary, Git glossary. (navbar_github - see also navbar_git, navbar_gitops, navbar_iac)

(DevOps deployment navbar)

Return to GitOps, DevOps deployment, Kubernetes-Docker, Linux configuration (Unix shell initialization - bash profile) Ansible-Terraform, Package manager, Package management, Packages, Configuration, Configuration automation, Deployment automation, Continuous deployment, Delivery, Continuous delivery, Integration, Continuous integration, CI-CD, CI/CD, Version control, GitHub, GitHub Actions, GitHub CLI, AWS Cloud Shell, AWS Tools for PowerShell, Azure Cloud Shell, Azure PowerShell, Google Cloud Shell, Oracle Cloud Shell (Oracle Cloud Infrastructure Cloud Shell), IBM Cloud Shell, Linode Cloud Shell, DigitalOcean Cloud Shell, GitHub Codespaces IDE, AWS Cloud9 IDE, Databricks Cloud Shell, JetBrains, Azure DevOps, JetBrains TeamCity, Management, Configuration management

installation - Installation of - Install

“Git is a free, open source, distributed version control system created by Linus Torvalds. Git requires low operational overhead, yet is flexible and powerful enough to support the demands of complex, and large scale, distributed software development projects.” (9781492091189)

“Git is robust enough to track content in areas as varied as data science, graphic design and book authoring.”

Git Server

A Git Server enables you to collaborate more easily because it ensures the availability of a central and reliable source of truth for the repositories you will be working on. A Git Server is also where your remote Git repositories are stored; as common practise goes, the repository has the most up to date and stable source of your projects. You have the option to install and configure your own Git Server, or forgo the overhead and opt to host your git repositories on a reliable third party hosting site.

Git Clients

Git clients are of two types: the git command-line and the git GUI tools. When you install and configure a git client, you will be able to access the remote repositories, work on a local copy of it, and push changes back to the git server. If you are new to Git, we recommend starting out using the git command-line; familiarize yourself with the common sub-set of git commands required for your day to day operations and then progress to a Git GUI tool of your choice.

Git Characteristics

Now that we have covered an overview of the Git Components, let’s learn about the characteristics of Git. When you understand these distinct traits of Git, it enables you to effortlessly switch from a centralized version control mindset to a distributed version control mentality. We like to refer to this as “Thinking in Git”.

Stores revision changes as Snapshots The very first concept to unlearn is the way git stores multiple revisions on a file that you are working on. Unlike other version control systems, Git does not track revision changes as a series of modifications, commonly known as Delta’s; Instead it takes a snapshot of changes to the state of your repository at a specific point in time. In Git terminology this is known as “commits”. Think of this as capturing a moment in time as a photograph.

Enhanced for Local Development In Git you work on a copy of the repository on your local development machine. This is known as a local repository, a clone of the remote repository on a git server. Your local repository will have the resources and the snapshots of the revision changes made on those resources all in one location. Git terms these collections of linked snapshots “repository commit history” or “repo history” for short. This allows you to work in a disconnected environment since git does not need a constant connection to the git server to version control your changes. As a natural consequence, you are able to work on large complex projects across distributed teams without compromising efficiency and performance for version control operations.

Git is Definitive Definitive means the git commands are explicit. It waits for you to carry out instructions on what to implement and when to execute it. For example, Git does not automatically sync changes from your local repository to the remote repository nor does it automatically save a snapshot of revision to your local repo history. Every action requires your explicit command or instruction to tell git what is required, ranging from adding new commits, fixing existing commits, pushing changes from your local repository to the remote repository and even retrieving new changes from the remote repository. In short, you need to be intentional with your actions, this also includes letting git know which files you intend to track since git does not auto-add new files to be version controlled.

Designed to bolster non linear Development Git allows you to ideate and experiment with variant implementation of features for viable solutions to your project by enabling you to diverge and work in parallel along the main stable code base of your project. This methodology, called “Branching”, is a very common practice and ensures the integrity of the main development line from any accidental changes that may break it.

In Git, the concept of branching is considered lightweight and inexpensive because a branch in git is just a pointer to the latest commit in a series of linked commits. For every branch you create, git keeps track of the series of commits for that branch. You can switch between branches with ease locally. Git then restores the state of the project to the most recent moment when the snapshot of the specified branch was created. When you decide to merge the changes from any branch into the main development line, git is able to combine those series of commits by applying techniques which we will discuss later in Chapter: Merges.

TIP

Since Git offers many novelties, keep in mind that the concept and practices of other version control systems may work differently or may not be applicable at all in Git.

The Git Command Line

Git command line is simple to use. Just type git version or git –version, to know if your machine has already been preloaded with git. You should see an output similar to the following:

$ git –version git version 2.31.1 If you do not have git installed on your machine, please refer to Appendix: Installing Git to learn how you can install git according to your Operating System Platform before continuing with the next section.

Upon installation, type git without any arguments. Git will then list its options and the most common subcommands.

  $ git
  git [--version] [--exec-path[=GIT_EXEC_PATH]]
      [-p|--paginate|--no-pager] [--bare] [--git-dir=GIT_DIR]
      [--work-tree=GIT_WORK_TREE] [--help] COMMAND [ARGS]
  The most commonly used git commands are:
     add        Add file contents to the index
     bisect     Find the change that introduced a bug by binary search
     branch     List, create, or delete branches
     checkout   Checkout and switch to a branch
     clone      Clone a repository into a new directory
     commit     Record changes to the repository
     diff       Show changes between commits, the commit and working trees, etc
     fetch      Download objects and refs from another repository
     grep       Print lines matching a pattern
     init       Create an empty git repository or reinitialize an existing one
     log        Show commit logs
     merge      Join two or more development histories
     mv         Move or rename a file, a directory, or a symlink
     pull       Fetch from and merge with another repository or a local branch
     push       Update remote refs along with associated objects
     rebase     Forward-port local commits to the updated upstream head
     reset      Reset current HEAD to the specified state
     rm         Remove files from the working tree and from the index
     show       Show various types of objects
     status     Show the working tree status
     tag        Create, list, delete, or verify a tag object signed with GPG
TIP

For a complete list of git subcommands, type git help –all.

As you can see from the usage hint, a small handful of options apply to git. Most options, shown as [ARGS] in the hint, apply to specific subcommands.

For example, the option –version affects the git command and produces a version number.

  $ git --version
  git version 2.31.1
In contrast, –amend is an example of an option specific to the git subcommand commit.
  $ git commit --amend
Some invocations require both forms of options. (Here, the extra spaces in the command line merely serve to visually separate the subcommand from the base command and are not required.)
  $ git --git-dir=project.git    repack -d
For convenience, documentation for each git subcommand is available using git help subcommand, git –help subcommand, git subcommand –help or man git-<subcommand>.

NOTE

You can visit http://www.kernel.org/pub/software/scm/git/docs/ to read the complete Git documentation online.

Example 1-1.

Historically, Git was provided as a suite of many simple, distinct, standalone commands developed according to the “Unix toolkit” philosophy: build small, interoperable tools. Each command sported a hyphenated name, such as git-commit and git-log. However, modern Git installations no longer support the hyphenated command forms and instead use a single git executable with a subcommand.

Git commands understand both “short” and “long” options. For example, the git commit command treats the following examples as equivalents.

  $ git commit -m "Fixed a typo."
  $ git commit --message="Fixed a typo."
The short form, -m, uses a single hyphen, whereas the long form, –message, uses two. (This is consistent with the GNU long options extension.) Some options exist only in one form.

TIP

You can create a commit summary and detailed message for the summary by using the -m option consecutively:

$ git commit -m “Summary” -m “Detail of Summary” Finally, you can separate options from a list of arguments via the “bare double dash” convention. For instance, use the double dash to contrast the control portion of the command line from a list of operands, such as filenames.

  $ git diff -w main origin -- tools/Makefile
You may need to use the double dash to separate and explicitly identify file names if they might otherwise be mistaken for another part of the command. For example, if you happened to have both a file and a tag named main.c, then you will get different behavior:
  # Checkout the tag named "main.c"
  $ git checkout main.c
  # Checkout the file named "main.c"
  $ git checkout -- main.c
Quick Introduction to Using Git

To see git in action, you can create a new repository, add some content and track a few revisions. You can create a repository in two ways: either create a repository from scratch and populate it with some content, or work with an existing repository by cloning it from a remote git server.

Preparing to work with Git

Whether you are creating a new repository or working with an existing repository, there are basic prerequisite configurations that you need to complete after installing Git on your local development machine. It is much like you setting up the correct date, timezone and language on a new camera before taking your first snapshot.

Configuring the Commit Author

At a bare minimum , Git requires your name and email address before you make a first commit in your repository. The identity you supply then shows as the commit author, baked in together with other snapshot metadata. You can save your identity in a configuration file using the git config command.

  $ git config user.name "Jon Loeliger"
  $ git config user.email "jdl@example.com"
If you decide not to include your identity in a configuration file, you will have to specify your identity for every git commit subcommand by appending the following argument –author at the end of the command:
  $ git commit -m "log message" --author="Jon Loeliger "
Keep in mind this is the hard way, and it can quickly become tedious.

You can also specify your identity by supplying your name and email address to the GIT_AUTHOR_NAME and GIT_AUTHOR_EMAIL environment variables respectively. If set, these variables will override all configuration settings. However for specifications set on the command-line, Git will override the values supplied in the configuration file and environment variable.

Working with a local Repository

Now that you have configured your identity, you are ready to start working with a repository. Start by creating a new empty repository on your local development machines. We will start simple and work our way towards techniques for working with a shared repository on a git server.

Creating an Initial Repository

We will model a typical situation by creating a repository for your personal website. Let’s assume you’re starting from scratch and you are going to add content for your project in the local directory ~/my_website which you place in a git repository.

Type in the following commands to create the directory and place some basic content in a file called index.html:

  $ mkdir ~/my_website
  $ cd ~/my_website
  $ echo 'My awesome website!' > index.html
To convert ~/my_website into a git repository, run git init:
  $ git init -b main
  Initialized empty Git repository in .git/
If you prefer to initialize an empty git repository first and then add files to it, you can do so by running the following commands:
  $ git init -b main ~/my_website
  Initialized empty Git repository in .git/
  $ cd ~/my_website
  $ echo 'My awesome website!' > index.html
TIP

You can initialize a completely empty directory or an existing directory full of files. In either case, the process of converting the directory into a Git repository is the same.

The git init command creates a hidden directory called .git at the root level of your project. All revision information is stored in this hidden single top level .git folder.

Git considers the ~/my_website as the working directory. This directory contains the current version of files for your website. When you make changes to existing files or add new files to your project, Git records those changes in the hidden .git folder.

For the purpose of learning, we will reference two virtual directories named as Index and Local History to illustrate the concept of initializing a new Git repository. We will discuss the index and Local History in Chapters File Management and the Index and Commits respectively.

Figure 1-2 will help you visualize what we have just explained:

. └── my_website

  ├── .git/
  │   └── Hidden git objects
  └── index.html
Fig1 2r Figure 1-2. Initial Repository Visual

The dotted lines for the Index and Local History represent the hidden directories within the .git folder.

Adding a File to Your Repository

Up to this point, you have only created a new git repository. In other words, this git repository is empty. Although the file index.html exists in the directory ~/my_website, to git this is the working directory, a representation of a scratch pad or directory where you frequently alter your files.

When you have finalized changes to the files and want to deposit those changes to the git repository, you need to explicitly do so by using the git add _file_ command:

  $ git add index.html
WARNING

Although you can let Git add all the files in the directory and all subdirectories using the git add . command, this can be a dangerous habit since it could lead to sensitive information or unwanted files being included when commits are made. To avoid including such information, you can use the .gitignore file which is covered in section The .gitignore File in Chapter: File Management and the Index.

The argument ., the single period or ‘dot' in Unix parlance, is shorthand for the current directory.

With the git add command, git understands that you intend to include the final iteration of the modification on the index.html as a revision in the repository. However, so far, git has merely staged the file, an interim step before taking a snapshot via a commit.

Git separates the add and commit steps to avoid volatility. Imagine how disruptive, confusing, and time-consuming it would be to update the repository each time you add, remove, or change a file. Instead, multiple provisional and related steps, such as an add, can be ‘batched', keeping the repository in a stable, consistent state. This method also allows for us to craft a narrative of why we are changing the code. In Chapter: Commits we will dive deeper on this concept.

We recommend that you strive to group logical changes as a ‘batch' before making a commit. This is called an atomic commit and this will help you along the way in situations where you need to do some advanced git operations discussed in later chapters.

Running the git status command reveals this in-between state of index.html:

  $ git status
  # On branch main
  #
  # Initial commit
  #
  # Changes to be committed:
  #   (use "git rm --cached ..." to unstage)
  #
  #       new file: index.html
The command reports that the new file index.html will be added to the repository during the next commit.

After staging the file, the next logical step is to commit the file to the repository. Once you commit the file, it becomes part of the repository commit history; For brevity we will refer to this as the repo history. Everytime you make a commit, git records several other metadata along with it, most notably the commit log message and the author of the change.

A fully qualified git commit command should supply a terse and meaningful log message using active language to denote the change that is being introduced by the commit. This is very helpful when you need to traverse through the repo history to track down a specific change or quickly identify changes of a commit without having to dig deeper into the change details. We dive in deeper on this topic in Chapter: Commits and Chapter: Altering Commits Rewriting History.

Let’s commit the staged index.html file for your website:

  $ git commit -m "Initial contents of my_website"
  Created initial commit 9da581d: Initial contents of my_website
   1 files changed, 1 insertions(+), 0 deletions(-)
   create mode 100644 index.html
NOTE

The details of the author who is making the commit are retrieved from the git configuration we set up earlier

In the code example, we supplied the '-m' argument to be able to provide the log message directly on the command line. If you prefer to provide a detailed log message via an interactive editor session, you can do so as well. You will need to configure git to launch your favourite editor during a git commit(leave out the '-m' argument); Set the GIT_EDITOR environment variable as follows:

  # In tcsh
  $ setenv GIT_EDITOR emacs
  # In bash or zsh
  $ export GIT_EDITOR=vim
NOTE

As a default, Git will honour the default text editor configured in the shell environment variables VISUAL or EDITOR. If neither are configured, it falls back to use the vi editor

After you commit the index.html into the repository, run git status to get an update on the current state of your repository. In our example, running git status should indicate that there are no outstanding changes to be committed.

  $ git status
  # On branch main
  nothing to commit (working directory clean)
Git also tells you that your working directory is clean, which means the working directory has no new or modified files that differ from what is in the repository.

Figure 1-3 will help you visualize all the steps you just learned:

fig1 3 Figure 1-3. Staging and adding a file to a repository

The Difference between the git add and git commit is much like you organizing a group of school children in a prefered order to get the perfect classroom photograph. git add does the organizing, whereas `git commit`takes the snapshot.

Fair Use Sources

Fair Use Sources:


© 1994 - 2024 Cloud Monk Losang Jinpa or Fair Use. Disclaimers

SYI LU SENG E MU CHYWE YE. NAN. WEI LA YE. WEI LA YE. SA WA HE.