# Version control, and setting Git up once

Why every team keeps code in version control, how to install Git, set your identity at the right level, and create your first repository.

Course: [Git & GitHub](https://devops.rajeev.pro/courses/git), lesson 1. About 20 minutes, beginner. Source: https://devops.rajeev.pro/courses/git/01-version-control-and-setup

## What you will learn

- Explain what version control gives a team that shared folders and zip files can't
- Install Git and check which version you have
- Set your name, email and default branch once, at the right config level
- Use a different email for one repository without changing the rest
- Create a repository and explain what the `.git` folder is

## Why version control exists

Picture a team without it. The code lives in a shared folder. Someone copies it to
`app-final-v2-fixed.zip` before a big change. Two people edit the same file and one of them
silently overwrites the other. Production breaks on Friday and nobody can say what changed
since Tuesday.

A **version control system** fixes all of that. It records every change as a snapshot with
who made it, when, and why. That gives you four things you'll use every single day:

- **History.** See exactly what changed, line by line, and who changed it.
- **Undo.** Go back to any earlier version of a file or of the whole project.
- **Parallel work.** Everyone works on their own branch and merges when ready, instead of editing the same copy.
- **A trigger for automation.** Every CI/CD pipeline starts with "a commit was pushed". No version control, no pipeline.

**Git** is the version control system almost everyone uses now. It's **distributed**: every
clone is a full copy of the history, so you can commit, branch and look at history with no
network at all. GitHub, GitLab and Bitbucket are places to host and share Git repositories;
Git itself runs on your machine.

**How it works, in one picture.** Every time you save a version (a **commit**), Git stores a
snapshot of the whole project plus a note: who, when, why, and which commit came before it. Those
notes link the commits into a chain, so Git can walk back through every version ever saved. A
**branch** is just a name that points at one commit in that chain. Everything else in this course
builds on that one idea.

In this lesson you'll install Git, tell it who you are, and create your first repository.

## Install Git

| System          | Command                                                        |
| --------------- | -------------------------------------------------------------- |
| Ubuntu / Debian | `sudo apt update && sudo apt install git`                      |
| Fedora / RHEL   | `sudo dnf install git`                                         |
| macOS           | `brew install git`, or `xcode-select --install`                |
| Windows         | Install Git for Windows from git-scm.com, or use it inside WSL |

```sh
$ git --version
git version 2.x.x        # any recent 2.x is fine for this course
```

## Tell Git who you are

**Why it matters.** Every commit permanently stores the author's name and email. Here is a real
commit, opened up with `git cat-file`:

```sh
$ git cat-file -p HEAD
tree 89807efe1600c4786b7f695c30a8d13438baf314
author Rajeev Kumar <you@example.com> <timestamp>
committer Rajeev Kumar <you@example.com> <timestamp>

Add README
```

Three things follow from that:

- **It's permanent.** Fixing the email later means rewriting history, which is painful once
  others have the commits.
- **GitHub links commits to you by email.** If the commit email matches one on your GitHub
  account, the commit shows your avatar and counts on your profile. If it doesn't, the commit
  looks like it came from a stranger.
- **Teammates use it.** `git log` and `git blame` show who changed a line, so they know whom to ask.

So set your name and email **once**, before your first commit. If you don't, Git guesses from your
machine's username and hostname, and you end up with commits from `rajeev@laptop.localdomain`
in the history forever.

```sh
$ git config --global user.name "Your Name"
$ git config --global user.email "you@example.com"
$ git config --global init.defaultBranch main     # new repos start on "main"
$ git config --global core.editor "nano"          # the editor Git opens for commit messages
$ git config --global --list
user.name=Your Name
user.email=you@example.com
init.defaultBranch=main
core.editor=nano
```

> **Keep your email private on GitHub.** Commit emails are public in every repository you push to. GitHub gives each account a `noreply` address you can use as `user.email` instead. The resources at the end of this lesson show where to find yours.

## System, global and local config

Git reads settings from three places, in this order. **The last one wins**, so the setting
closest to the repository is the one that counts.

> **Figure.** Git config levels: system settings in /etc/gitconfig apply to every user, global settings in ~/.gitconfig apply to all your repositories, local settings in .git/config apply to one repository. Local overrides global, which overrides system.
>
> Three levels of Git config. When the same key is set twice, the closer level wins.

| Level  | Flag       | File                 | Applies to                |
| ------ | ---------- | -------------------- | ------------------------- |
| System | `--system` | `/etc/gitconfig`     | Every user on the machine |
| Global | `--global` | `~/.gitconfig`       | All of your repositories  |
| Local  | (none)     | `<repo>/.git/config` | This one repository only  |

The everyday use: your global email is personal, and one client or work repository needs your
work address. Set it locally in that repository and nothing else changes.

```sh
$ cd ~/work/client-api
$ git config user.email "you@company.com"         # no flag = local, this repo only
$ git config --show-origin user.email             # which file did this value come from?
file:.git/config	you@company.com
```

`--show-origin` is the fastest way to answer "why is Git using that email?"

## Your first repository

```sh
$ mkdir -p ~/projects/hello && cd ~/projects/hello
$ git init
Initialized empty Git repository in /home/rajeev/projects/hello/.git/
$ git status
On branch main

No commits yet

nothing to commit (create/copy files and use "git add" to track)
$ ls -a
.  ..  .git
```

That `.git` folder **is** the repository: every commit, every branch and the repo's own config
live inside it. Here's what `git init` created:

```sh
$ ls -F .git
HEAD config description hooks/ info/ objects/ refs/
```

- **`objects/`** holds the content: every version of every file, and every commit.
- **`refs/`** holds the names: branches and tags, each pointing at a commit.
- **`HEAD`** says which branch you're on right now.
- **`config`** is this repository's own settings (the "local" level from the section above).

You never edit these files by hand; Git commands do it for you. The files you _do_ edit sit next
to `.git`, in the **working directory**. Git watches them, but nothing is saved into history
until you commit. The next lesson shows how a change travels from the working directory into a
commit.

> **Never delete .git to start over.** Deleting `.git` deletes the whole history of that project. If something looks broken, there is almost always a Git command that fixes it, and you'll learn them in *Undoing changes*.

> **At work.** Check `git config user.email` in a new work repository before your first commit. Many companies only accept commits from company addresses, and some block pushes that use anything else.

> **Video.** [Beginner Git commands you need to know (WITH EXAMPLES)](https://www.youtube.com/watch?v=rE2zRhZdjFU&t=109s) (GitHub)

## Mission: Use your work email in one repo only

You use a personal email everywhere. A new work project, ~/work/payments, must use you@company.com, and nothing else on your machine should change. Create the repo, set the email at the right level, and prove both values.

- You need: Global email: you@example.com
- You'll have: ~/work/payments/.git/config

```sh
$ mkdir -p ~/work/payments && cd ~/work/payments
$ git init
$ git config user.email "you@company.com"
$ git config --show-origin user.email
file:.git/config	you@company.com
$ cd ~ && git config --show-origin user.email
file:/home/rajeev/.gitconfig	you@example.com
```

The local value lives in `~/work/payments/.git/config` and only applies there. Outside the
repository, Git falls back to your global `~/.gitconfig`.

## Try it

- Install Git and run `git --version`.
- Set your global `user.name`, `user.email` and `init.defaultBranch main`.
- Run `git config --global --list` and check all three values.
- Create `~/projects/hello`, run `git init` in it, and read the output of `git status`.
- Inside `hello`, set a local `user.email` and confirm with `git config --show-origin user.email` which file it comes from.

## Quiz

1. Your global email is personal, but one work repo has a local `user.email` set to your work address. Which one do commits in that repo use?
   - The global one, because it was set first
   - **The local one, because the closest level wins** (answer)
   - Git asks you every time
   Why: Git reads system, then global, then local config. The last one read wins, so a repo's own `.git/config` overrides `~/.gitconfig`.

2. Where does `git config --global` write its settings?
   - In `.git/config` of the current repo
   - In `/etc/gitconfig`
   - **In `~/.gitconfig` in your home directory** (answer)
   Why: `--global` means "for this user, in every repo": `~/.gitconfig` (or `~/.config/git/config`). `--system` writes `/etc/gitconfig`, and plain `git config` writes the repo's `.git/config`.

3. What does `git init` actually create?
   - **A `.git` folder that holds the whole history and settings of the repository** (answer)
   - A copy of the project on GitHub
   - A first commit with all your files
   Why: `git init` only creates the `.git` folder. Nothing is committed and nothing is uploaded until you do it yourself.

4. A teammate deletes the `.git` folder in their project to "clean it up". What did they lose?
   - Nothing, Git keeps a backup in the cloud
   - Only the settings
   - **The entire local history, every branch and every commit not pushed anywhere else** (answer)
   Why: The `.git` folder is the repository. The files you see are just one checked-out version of it. Anything not pushed to a remote is gone.

## Resources

- [Pro Git, chapter 1.1, About version control](https://git-scm.com/book/en/v2/Getting-Started-About-Version-Control) (git-scm.com)
- [Pro Git, Installing Git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) (git-scm.com)
- [Pro Git, First-time Git setup](https://git-scm.com/book/en/v2/Getting-Started-First-Time-Git-Setup) (git-scm.com)
- [git config reference](https://git-scm.com/docs/git-config) (Git docs)
- [git init reference](https://git-scm.com/docs/git-init) (Git docs)
- [Setting your commit email address on GitHub](https://docs.github.com/en/account-and-profile/setting-up-and-managing-your-personal-account-on-github/managing-email-preferences/setting-your-commit-email-address) (GitHub Docs)
