From Zero to Senior · The LabالعربيةGitHub

Chapter 15

Git and GitHub

6 examples · 3 projects · 5 exercises

In this chapter you will learn to

  • explain what version control is and why every developer uses it
  • save snapshots of your project with git add and git commit
  • look at the history, see what changed and undo mistakes
  • work on new features safely in branches
  • put your project on GitHub and understand how teams work together

Examples

15.2 Setting up Git

Download Git from git-scm.com and install it with the default options (on a Mac, it may already be installed: try git --version). Then tell Git your name and email, which it writes on every snapshot you make:

config.sh⤓ File
Terminal session from the book
# Tell Git who you are (once per computer)
$ git config --global user.name "Sara Khan"
$ git config --global user.email "sara@example.com"
$ git config --global init.defaultBranch main

15.3 Your first commit

Here is the whole process for the profile site from Chapter 7, run in its folder:

first-commit.sh⤓ File
Terminal session from the book
# Start tracking this folder
$ git init
Initialized empty Git repository in /Users/sara/code-from-zero/profile/.git/
$ git status --short
?? index.html
?? style.css
# Choose what goes into the next snapshot
$ git add index.html style.css
$ git status --short
A  index.html
A  style.css
# Save the snapshot with a message
$ git commit -m "Add profile page"
[main (root-commit) 96c0a17] Add profile page
 2 files changed, 2 insertions(+)
 create mode 100644 index.html
 create mode 100644 style.css

15.4 History and differences

Now edit index.html, add a line, and ask Git what changed:

history.sh⤓ File
Terminal session from the book
# Edit index.html in VS Code, then:
# What changed since the last commit?
$ git diff
diff --git a/index.html b/index.html
index 5ab23b1..96fec82 100644
--- a/index.html
+++ b/index.html
@@ -1 +1,2 @@
 <h1>Sara Khan</h1>
+<p>Beginner web developer</p>
$ git commit -am "Add tagline"
[main 8be4da4] Add tagline
 1 file changed, 1 insertion(+)
# The history, newest first
$ git log --oneline
8be4da4 Add tagline
96c0a17 Add profile page

15.5 Branches

A branch is a separate line of work. The main branch, main, holds the version that works. When you start a new feature, you create a branch for it, work and commit there freely, and when it is ready you merge it back into main:

branch.sh⤓ File
Terminal session from the book
# A new branch for a new feature
$ git switch -c contact
Switched to a new branch 'contact'
# Create contact.html, then:
$ git add contact.html
$ git commit -m "Add contact section"
[contact 857eb74] Add contact section
 1 file changed, 1 insertion(+)
 create mode 100644 contact.html
# Back to the main branch: contact.html disappears from the folder
$ git switch main
Switched to branch 'main'
# Bring the feature in
$ git merge contact
Updating 8be4da4..857eb74
Fast-forward
 contact.html | 1 +
 1 file changed, 1 insertion(+)
 create mode 100644 contact.html
$ git log --oneline --graph
* 857eb74 Add contact section
* 8be4da4 Add tagline
* 96c0a17 Add profile page

15.6 GitHub: your code online

Create a free account on github.com, click New repository, give it a name, and leave it empty. GitHub then shows you its address. Connect your local repository to it and send your commits:

github.sh⤓ File
Terminal session from the book
# Connect the folder to an empty repository you created on github.com
$ git remote add origin https://github.com/sara-khan/profile.git
$ git push -u origin main
Enumerating objects: 11, done.
Writing objects: 100% (11/11), 1.02 KiB | 1.02 MiB/s, done.
To https://github.com/sara-khan/profile.git
 * [new branch]      main -> main
branch 'main' set up to track 'origin/main'.
# Later, on any computer:
$ git clone https://github.com/sara-khan/profile.git
$ git pull

Some files do not belong in a repository: downloaded packages that can be reinstalled, system files, logs, and above all secrets such as passwords and API keys. List them in a file called .gitignore and Git will never track them:

.gitignore-example.txt⤓ File
# Files Git should never track
node_modules/
.env
.DS_Store
*.log

Practice projects

Project 15.1 · Easy

A learning journal under version control

Start a repository for a journal of what you learn, and save one commit per day.

You will practise: git init, add, commit, commit -am, log --oneline and show.

Steps
  1. Make a new folder called journal, open it in VS Code, and run git init in its terminal.
  2. Create journal.md with a heading. Add it and make your first commit.
  3. Each day, add one line about what you learned and commit it with a short message. -am adds and commits in one step, but only for files Git already tracks.
  4. Read your history with git log --oneline.
  5. Look inside the last commit with git show --stat. Then try plain git show to see the exact line you added.

Hint: keep this journal for the rest of the book. In a few weeks, git log will be a diary of your progress, and the habit of small, frequent commits is exactly what teams expect.

Solution
journal.sh⤓ File
Terminal session from the book
# A new folder for your journal
$ git init
Initialized empty Git repository in /Users/sara/code/journal/.git/
# Create journal.md with a heading, then:
$ git add journal.md
$ git commit -q -m "Start the journal"
# Add the Day 1 line, then:
$ git commit -q -am "Day 1"
# Add the Day 2 line, then:
$ git commit -q -am "Day 2"
# Three snapshots, newest first
$ git log --oneline
31670a5 Day 2
62eacf9 Day 1
b7c860c Start the journal
# What exactly changed in the last commit?
$ git show --stat --format=%s HEAD
Day 2

 journal.md | 1 +
 1 file changed, 1 insertion(+)

Project 15.2 · Medium

Two ways to undo

Make two mistakes on purpose, one not yet committed and one already committed, and undo each with the right tool.

You will practise: git status --short, git restore for uncommitted changes, and git revert for commits.

Steps
  1. Replace the whole contents of journal.md with one silly line, and save. git status --short shows M: modified.
  2. Run git restore journal.md. The file goes back to the last commit, and the status is clean again.
  3. Write Day 3 properly and commit it.
  4. Now create quote.md, add it and commit it. Pretend you regret this commit.
  5. Run git revert --no-edit HEAD. Git makes a new commit that does the opposite, and the file disappears.
  6. Read git log --oneline: the mistake and its undo are both in the history, so nobody is surprised.

Hint: restore throws away work that was never saved, so there is no way back; use it with care. revert is always safe, even after you have pushed, because it adds history instead of erasing it.

Solution
undo.sh⤓ File
Terminal session from the book
# Oops: an edit you did not mean to make
$ git status --short
 M journal.md
# Throw away the change in this file
$ git restore journal.md
$ git status --short
# Now write Day 3 properly, then:
$ git commit -q -am "Day 3"
# A commit you regret, already saved
$ git add quote.md
$ git commit -q -m "Add a random quote"
# Undo it with a new commit, keeping the history honest
$ git revert --no-edit HEAD
[main 8a28f85] Revert "Add a random quote"
 1 file changed, 1 deletion(-)
 delete mode 100644 quote.md
$ git log --oneline
8a28f85 Revert "Add a random quote"
4b00ed1 Add a random quote
30896b9 Day 3
31670a5 Day 2
62eacf9 Day 1
b7c860c Start the journal

Project 15.3 · Challenge

Create a merge conflict, then solve it

Conflicts frighten beginners only until they have solved one. Create one on purpose, read it, and resolve it calmly.

You will practise: branches, git switch -c, fast-forward and real merges, conflict markers, and finishing a merge.

Steps
  1. On main, add a title line at the top of the journal and commit it.
  2. Create a branch personal, change the title, and commit. Go back to main.
  3. Create a second branch ambitious from main, change the same title line differently, and commit. Go back to main.
  4. Merge personal: it is a fast-forward, because main had not moved. Then merge ambitious: Git cannot choose between two changes to the same line, so it stops.
  5. Open the file. Between <<<<<<< and ======= is your version (HEAD); between ======= and >>>>>>> is the incoming one.
  6. Write the line you really want, delete all three marker lines, then git add and git commit. The graph shows the two branches joining.

Hint: a conflict is not an error. It is Git politely asking a human to decide. VS Code shows buttons above each conflict (“Accept Current”, “Accept Incoming”, “Accept Both”), but always read the result before you commit.

Solution
conflict.sh⤓ File
Terminal session from the book
# Add a title line at the top, then:
$ git commit -q -am "Add a title"
# Two branches change the same line
$ git switch -q -c personal
# Change the title on this branch, then:
$ git commit -q -am "Personal title"
$ git switch -q main
$ git switch -q -c ambitious
# Change the same line differently here, then:
$ git commit -q -am "Ambitious title"
$ git switch -q main
$ git merge personal
Updating 5ffca6e..d5dc855
Fast-forward
 journal.md | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
# Merging the second one causes a conflict
$ git merge ambitious
Auto-merging journal.md
CONFLICT (content): Merge conflict in journal.md
Automatic merge failed; fix conflicts and then commit the result.
# Git marks both versions inside the file
$ head -5 journal.md
<<<<<<< HEAD
Title: Sara’s learning journal
=======
Title: My road to senior
>>>>>>> ambitious
# Keep the line you want, delete the markers, then:
$ git add journal.md
$ git commit -q -m "Choose the final title"
$ git log --oneline --graph -4
*   9900c88 Choose the final title
|\  
| * fc23fdc Ambitious title
* | d5dc855 Personal title
|/  
* 5ffca6e Add a title

Exercises

Exercise 15.1 · Easy

Put your code-from-zero folder under Git, and make your first commit with everything you have written so far.
The book's short answer
git init, git add ., git commit -m "Add everything from chapters 1 to 14".
Show the solution
first-commit.sh⤓ File
Runs in a terminal: bash first-commit.sh
#!/usr/bin/env bash
# Exercise 15.1: put the book's folder under Git and make the first commit. Run: bash first-commit.sh
# It works in a temporary copy, with a few files standing in for chapters 1 to 14.
set -e
export GIT_AUTHOR_NAME="Sara Khan" GIT_AUTHOR_EMAIL="sara@example.com"
export GIT_COMMITTER_NAME="$GIT_AUTHOR_NAME" GIT_COMMITTER_EMAIL="$GIT_AUTHOR_EMAIL"
export GIT_CONFIG_GLOBAL=/dev/null  # ignore your own Git settings while the script runs
run() { local s="\$"; for a in "$@"; do if [[ $a == *" "* ]]; then s+=" \"$a\""; else s+=" $a"; fi; done; echo "$s"; "$@"; }
cd "$(mktemp -d)"
mkdir -p code-from-zero/chapter-01 code-from-zero/chapter-05
echo 'console.log("Hello, world!");' > code-from-zero/chapter-01/hello.js
echo '<h1>Sara</h1>' > code-from-zero/chapter-05/profile.html
cd code-from-zero

run git init -q -b main
run git status --short
run git add .
run git commit -q -m "Add everything from chapters 1 to 14"
run git log --oneline --stat
Recorded output$ bash first-commit.sh
$ git init -q -b main
$ git status --short
?? chapter-01/
?? chapter-05/
$ git add .
$ git commit -q -m "Add everything from chapters 1 to 14"
$ git log --oneline --stat
247fa06 Add everything from chapters 1 to 14
 chapter-01/hello.js     | 1 +
 chapter-05/profile.html | 1 +
 2 files changed, 2 insertions(+)

Exercise 15.2 · Easy

Change one file, look at the change with git diff, then throw it away with git restore.
The book's short answer
git diff, then git restore file-name.
Show the solution
diff-restore.sh⤓ File
Runs in a terminal: bash diff-restore.sh
#!/usr/bin/env bash
# Exercise 15.2: change a file, see the change with git diff, then throw it away with git restore.
set -e
export GIT_AUTHOR_NAME="Sara Khan" GIT_AUTHOR_EMAIL="sara@example.com"
export GIT_COMMITTER_NAME="$GIT_AUTHOR_NAME" GIT_COMMITTER_EMAIL="$GIT_AUTHOR_EMAIL"
export GIT_CONFIG_GLOBAL=/dev/null  # ignore your own Git settings while the script runs
run() { local s="\$"; for a in "$@"; do if [[ $a == *" "* ]]; then s+=" \"$a\""; else s+=" $a"; fi; done; echo "$s"; "$@"; }
cd "$(mktemp -d)"
git init -q -b main
printf '<h1>Sara Khan</h1>\n<p>Beginner web developer</p>\n' > index.html
git add . && git commit -q -m "Add profile page"

echo "# A change we will regret:"
printf '<h1>Sara Khan</h1>\n<p>Oops, I deleted my tagline</p>\n' > index.html
run git diff --no-color
run git restore index.html
run git status --short
run cat index.html
echo "# Clean again: the file is back to the last commit."
Recorded output$ bash diff-restore.sh
# A change we will regret:
$ git diff --no-color
diff --git a/index.html b/index.html
index 96fec82..cba4b83 100644
--- a/index.html
+++ b/index.html
@@ -1,2 +1,2 @@
 <h1>Sara Khan</h1>
-<p>Beginner web developer</p>
+<p>Oops, I deleted my tagline</p>
$ git restore index.html
$ git status --short
$ cat index.html
<h1>Sara Khan</h1>
<p>Beginner web developer</p>
# Clean again: the file is back to the last commit.

Exercise 15.3 · Medium

Create a branch called dark-mode, add a dark theme to your profile page there in two commits, and merge it into main.
The book's short answer
git switch -c dark-mode, two commits, git switch main, git merge dark-mode.
Show the solution
dark-mode.sh⤓ File
Runs in a terminal: bash dark-mode.sh
#!/usr/bin/env bash
# Exercise 15.3: a dark-mode branch with two commits, merged into main.
set -e
export GIT_AUTHOR_NAME="Sara Khan" GIT_AUTHOR_EMAIL="sara@example.com"
export GIT_COMMITTER_NAME="$GIT_AUTHOR_NAME" GIT_COMMITTER_EMAIL="$GIT_AUTHOR_EMAIL"
export GIT_CONFIG_GLOBAL=/dev/null  # ignore your own Git settings while the script runs
run() { local s="\$"; for a in "$@"; do if [[ $a == *" "* ]]; then s+=" \"$a\""; else s+=" $a"; fi; done; echo "$s"; "$@"; }
cd "$(mktemp -d)"
git init -q -b main
printf '<link rel="stylesheet" href="style.css">\n<h1>Sara Khan</h1>\n' > index.html
printf 'body { color: #1e1b2e; }\n' > style.css
git add . && git commit -q -m "Add profile page"

run git switch -c dark-mode
printf 'body.dark { color: white; background: #0f0d1a; }\n' > dark.css
run git add dark.css
run git commit -q -m "Add dark theme styles"
printf '<link rel="stylesheet" href="style.css">\n<link rel="stylesheet" href="dark.css">\n<h1>Sara Khan</h1>\n<button id="theme">Night mode</button>\n' > index.html
run git commit -q -am "Add the night mode button"
run git switch main
run git merge -q dark-mode
run git log --oneline --graph
Recorded output$ bash dark-mode.sh
$ git switch -c dark-mode
Switched to a new branch 'dark-mode'
$ git add dark.css
$ git commit -q -m "Add dark theme styles"
$ git commit -q -am "Add the night mode button"
$ git switch main
Switched to branch 'main'
$ git merge -q dark-mode
$ git log --oneline --graph
* 4e21bde Add the night mode button
* 5600423 Add dark theme styles
* 8f6f039 Add profile page

Exercise 15.4 · Medium

Create a repository on GitHub and push your profile site to it. Open the repository page and click on a commit to see its changes.
The book's short answer
git remote add origin … and git push -u origin main, as in Section 15.6.
Show the solution
push.sh⤓ File
Runs in a terminal: bash push.sh
#!/usr/bin/env bash
# Exercise 15.4: push to a remote repository.
# On GitHub you create the repository on the website, then copy its address, such as https://github.com/sara/profile.git.
# So that this script runs anywhere, the "GitHub" here is an empty repository in a folder. The commands are exactly the same.
set -e
export GIT_AUTHOR_NAME="Sara Khan" GIT_AUTHOR_EMAIL="sara@example.com"
export GIT_COMMITTER_NAME="$GIT_AUTHOR_NAME" GIT_COMMITTER_EMAIL="$GIT_AUTHOR_EMAIL"
export GIT_CONFIG_GLOBAL=/dev/null  # ignore your own Git settings while the script runs
run() { local s="\$"; for a in "$@"; do if [[ $a == *" "* ]]; then s+=" \"$a\""; else s+=" $a"; fi; done; echo "$s"; "$@"; }
cd "$(mktemp -d)"
git init -q --bare github-profile.git
mkdir profile && cd profile
git init -q -b main
printf '<h1>Sara Khan</h1>\n' > index.html
git add . && git commit -q -m "Add profile page"

run git remote add origin ../github-profile.git
run git push -q -u origin main
run git remote -v
echo "# What the remote has now (on GitHub: the repository page, and a click on the commit):"
run git --git-dir=../github-profile.git log --oneline --stat main
Recorded output$ bash push.sh
$ git remote add origin ../github-profile.git
$ git push -q -u origin main
$ git remote -v
origin	../github-profile.git (fetch)
origin	../github-profile.git (push)
# What the remote has now (on GitHub: the repository page, and a click on the commit):
$ git --git-dir=../github-profile.git log --oneline --stat main
e4aee43 Add profile page
 index.html | 1 +
 1 file changed, 1 insertion(+)

Exercise 15.5 · Challenge

Make a merge conflict on purpose: change the same line of index.html differently on two branches, merge them, and resolve the conflict.
The book's short answer
Change the same line on main and on another branch, merge, edit the file to keep the right version, delete the markers, then git add and git commit.
Show the solution
conflict.sh⤓ File
Runs in a terminal: bash conflict.sh
#!/usr/bin/env bash
# Exercise 15.5: a merge conflict made on purpose, and resolved.
set -e
export GIT_AUTHOR_NAME="Sara Khan" GIT_AUTHOR_EMAIL="sara@example.com"
export GIT_COMMITTER_NAME="$GIT_AUTHOR_NAME" GIT_COMMITTER_EMAIL="$GIT_AUTHOR_EMAIL"
export GIT_CONFIG_GLOBAL=/dev/null  # ignore your own Git settings while the script runs
run() { local s="\$"; for a in "$@"; do if [[ $a == *" "* ]]; then s+=" \"$a\""; else s+=" $a"; fi; done; echo "$s"; "$@"; }
cd "$(mktemp -d)"
git init -q -b main
printf '<h1>Sara Khan</h1>\n<p>Web developer</p>\n' > index.html
git add . && git commit -q -m "Add profile page"

echo "# The same line, changed differently on two branches:"
run git switch -q -c tagline
printf '<h1>Sara Khan</h1>\n<p>Frontend developer from Alexandria</p>\n' > index.html
run git commit -q -am "Tagline: frontend"
run git switch -q main
printf '<h1>Sara Khan</h1>\n<p>Junior web developer</p>\n' > index.html
run git commit -q -am "Tagline: junior"

run git merge tagline || true
run cat index.html

echo "# Resolve: keep the right text and delete the three marker lines (<<<<<<<, =======, >>>>>>>)."
printf '<h1>Sara Khan</h1>\n<p>Junior frontend developer from Alexandria</p>\n' > index.html
run git add index.html
run git commit -q -m "Merge tagline: keep both ideas"
run git log --oneline --graph
run cat index.html
Recorded output$ bash conflict.sh
# The same line, changed differently on two branches:
$ git switch -q -c tagline
$ git commit -q -am "Tagline: frontend"
$ git switch -q main
$ git commit -q -am "Tagline: junior"
$ git merge tagline
Auto-merging index.html
CONFLICT (content): Merge conflict in index.html
Automatic merge failed; fix conflicts and then commit the result.
$ cat index.html
<h1>Sara Khan</h1>
<<<<<<< HEAD
<p>Junior web developer</p>
=======
<p>Frontend developer from Alexandria</p>
>>>>>>> tagline
# Resolve: keep the right text and delete the three marker lines (<<<<<<<, =======, >>>>>>>).
$ git add index.html
$ git commit -q -m "Merge tagline: keep both ideas"
$ git log --oneline --graph
*   329250f Merge tagline: keep both ideas
|\  
| * 823c873 Tagline: frontend
* | 762d6b8 Tagline: junior
|/  
* dca3ee4 Add profile page
$ cat index.html
<h1>Sara Khan</h1>
<p>Junior frontend developer from Alexandria</p>