6.1: Git & Version Control

Learn Git version control to track changes, collaborate with others, and maintain a complete history of your code. Master essential Git commands, branching strategies, and how to use GitHub for hosting and sharing your projects.

1. Introduction to Version Control

What is Version Control?

Version control is a system that tracks changes to files over time. Think of it as a sophisticated "undo" system that records every change, lets you revert to previous versions, enables collaboration, and creates a complete history of your project.

Git is the most widely used version control system for tracking code changes. The purpose and function of Git in web development:

  1. Version control - Track all changes to code over time
  2. Collaboration - Multiple developers can work on same project
  3. Backup - Code is stored safely and can be recovered
  4. Branching - Experiment with features without affecting main code
  5. History - See who changed what and when
  6. Deployment - Required for modern hosting platforms

Analogy from Python development:

If you've worked on Python projects, you might have done this:

my-project-v1.py
my-project-v2.py
my-project-v2-fixed.py
my-project-v3-final.py
my-project-v3-final-REALLY.py

Version control replaces this chaos with a clean, organized history.

Why Git?

Git is the most popular version control system in the world. It's:

  • Distributed: Everyone has a full copy of the repository
  • Fast: Operations are performed locally
  • Flexible: Supports many workflows
  • Industry standard: Used by virtually all tech companies

Popular platforms using Git:

  • GitHub (most popular)
  • GitLab
  • Bitbucket

2. Installing and Configuring Git

Installation

macOS:

# Check if Git is already installed
git --version

# If not installed, install via Homebrew
brew install git

# Or install Xcode Command Line Tools
xcode-select --install

Windows:

# Download from https://git-scm.com/download/win
# Run the installer with default settings

Linux (Ubuntu/Debian):

sudo apt update
sudo apt install git

Verify installation:

git --version
# Should output: git version 2.x.x

Initial Configuration

After installing Git, configure your identity. This information will be included in all your commits.

Set your name:

git config --global user.name "Your Name"

Set your email:

git config --global user.email "your.email@example.com"

Set default branch name to 'main':

git config --global init.defaultBranch main

Verify configuration:

git config --list

Optional but recommended settings:

Set default editor (VS Code):

git config --global core.editor "code --wait"

Enable colored output:

git config --global color.ui auto

3. Creating Your First Repository

Initialize a Local Repository

A repository (or "repo") is a project tracked by Git.

Create a new project folder:

mkdir my-website
cd my-website

Initialize Git:

git init

This creates a hidden .git folder that stores all version control information.

Check repository status:

git status

You should see:

On branch main
No commits yet
nothing to commit (create/copy files and use "git add" to track)

Understanding Git Workflow

Git has three main areas:

  1. Working Directory: Where you edit files
  2. Staging Area: Files prepared for commit
  3. Repository: Permanent history of commits

The Git workflow:

Working Directory → (git add) → Staging Area → (git commit) → Repository

4. Making Your First Commit

Create a File

Create a simple HTML file:

echo "<!DOCTYPE html>
<html lang=\"en\">
<head>
  <meta charset=\"UTF-8\">
  <title>My First Website</title>
</head>
<body>
  <h1>Hello, Git!</h1>
</body>
</html>" > index.html

Check status:

git status

You'll see:

Untracked files:
  (use "git add <file>..." to include in what will be committed)
        index.html

Stage Files

Add the file to the staging area:

git add index.html

Stage all files:

git add .

Check status again:

git status

Now the file is staged:

Changes to be committed:
  (use "git restore --staged <file>..." to unstage)
        new file:   index.html

Commit Changes

A commit is a snapshot of your project at a specific point in time.

Make your first commit:

git commit -m "Initial commit: Add homepage"

Commit message format:

  • Short, descriptive summary (50 characters or less)
  • Present tense ("Add feature" not "Added feature")
  • Clear about what changed

Good commit messages:

git commit -m "Add navigation menu"
git commit -m "Fix responsive layout bug"
git commit -m "Update contact form validation"

Bad commit messages:

git commit -m "stuff"
git commit -m "changes"
git commit -m "asdfasdf"

View Commit History

git log

Compact view:

git log --oneline

Graphical view:

git log --graph --oneline --all

5. Working with Changes

Modifying Files

Edit your index.html:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>My Portfolio</title>
</head>
<body>
  <h1>Welcome to My Portfolio</h1>
  <p>This is my first deployed website!</p>
</body>
</html>

Check what changed:

git diff

This shows line-by-line changes (red = removed, green = added).

Stage and Commit

git add index.html
git commit -m "Update homepage with portfolio content"

Unstaging Files

If you accidentally staged a file:

git restore --staged <filename>

Discarding Changes

To discard changes in your working directory:

git restore <filename>

Warning: This permanently discards your changes!


6. Working with GitHub

What is GitHub?

GitHub is a cloud-based hosting service for Git repositories. It provides:

  • Remote backup of your code
  • Collaboration tools
  • Project management features
  • Free hosting for static websites (GitHub Pages)

Create a GitHub Account

  1. Go to https://github.com
  2. Sign up for a free account
  3. Verify your email address

Create a Remote Repository

On GitHub:

  1. Click the "+" icon → "New repository"
  2. Name your repository (e.g., "my-website")
  3. Keep it public (for free hosting)
  4. Don't initialize with README, .gitignore, or license
  5. Click "Create repository"

Connect Local to Remote

GitHub will show you commands. Use the first set:

git remote add origin https://github.com/yourusername/my-website.git
git branch -M main
git push -u origin main

Explanation:

  • git remote add origin <url>: Connects your local repo to GitHub
  • git branch -M main: Renames branch to 'main' (if needed)
  • git push -u origin main: Uploads your code to GitHub

Verify remote connection:

git remote -v

Push Changes

After making new commits locally:

git push

This uploads your latest commits to GitHub.

Pull Changes

To download changes from GitHub:

git pull

7. Branching Basics

What are Branches?

Branches let you work on features without affecting the main code.

Main branch: Production-ready code Feature branches: Experimental work

Create a Branch

git branch feature-contact-form

Switch to the branch:

git checkout feature-contact-form

Create and switch in one command:

git checkout -b feature-contact-form

Modern syntax (Git 2.23+):

git switch -c feature-contact-form

Work on a Branch

Make changes:

<!-- Add to index.html -->
<section>
  <h2>Contact Me</h2>
  <form>
    <input type="email" placeholder="Your email">
    <button type="submit">Send</button>
  </form>
</section>

Commit on the branch:

git add index.html
git commit -m "Add contact form section"

Merge a Branch

Switch back to main:

git checkout main

Merge the feature branch:

git merge feature-contact-form

Delete the feature branch (optional):

git branch -d feature-contact-form

View Branches

List all branches:

git branch

List remote branches:

git branch -r

8. Common Git Workflows

Basic Solo Workflow

# Start work
git pull                    # Get latest changes

# Make changes
# ... edit files ...

# Save work
git add .
git commit -m "Add new feature"
git push

Feature Branch Workflow

# Create feature branch
git checkout -b feature-name

# Work on feature
git add .
git commit -m "Implement feature"

# Switch back to main
git checkout main

# Merge feature
git merge feature-name

# Push to GitHub
git push

# Delete feature branch
git branch -d feature-name

9. .gitignore File

What is .gitignore?

A .gitignore file tells Git which files to never track.

Common files to ignore:

  • Dependency folders (node_modules)
  • Environment variables (.env)
  • Build outputs (dist, build)
  • IDE settings (.vscode, .idea)
  • OS files (.DS_Store, Thumbs.db)

Create .gitignore

Create a file named .gitignore in your project root:

# Node.js
node_modules/
npm-debug.log

# Environment variables
.env
.env.local

# Build outputs
dist/
build/
.nuxt/
.output/

# IDE
.vscode/
.idea/
*.swp
*.swo

# OS
.DS_Store
Thumbs.db

# Logs
*.log
logs/

Add and commit:

git add .gitignore
git commit -m "Add .gitignore file"

10. Preparing for Deployment

Clean Repository Checklist

Before deploying, ensure:

1. All changes are committed:

git status
# Should show: "nothing to commit, working tree clean"

2. Sensitive data is not committed:

  • Check for API keys, passwords, tokens
  • Use environment variables instead
  • Add .env to .gitignore

3. Dependencies are documented:

For Node.js projects, ensure package.json exists:

{
  "name": "my-website",
  "version": "1.0.0",
  "scripts": {
    "dev": "vite",
    "build": "vite build"
  },
  "dependencies": {
    "vue": "^3.5.0"
  }
}

4. Build configuration is correct:

Ensure your build command works:

npm run build

5. README.md is present:

Create a README explaining your project:

echo "# My Website

A simple portfolio website built with HTML, CSS, and JavaScript.

## Local Development

\`\`\`bash
npm install
npm run dev
\`\`\`

## Deployment

This site is deployed on Netlify.
" > README.md

git add README.md
git commit -m "Add README documentation"
git push

11. Handling Merge Conflicts

What is a Merge Conflict?

A conflict occurs when Git can't automatically merge changes.

Example scenario:

# You edit line 5 of index.html
# Your teammate also edits line 5 of index.html differently
# When you try to merge, Git doesn't know which version to keep

Resolving Conflicts

When a conflict occurs, Git marks the file:

<<<<<<< HEAD
<h1>My Portfolio</h1>
=======
<h1>Welcome to My Site</h1>
>>>>>>> feature-branch

To resolve:

  1. Open the conflicted file
  2. Choose which version to keep (or combine both)
  3. Remove conflict markers (<<<<<<<, =======, >>>>>>>)
  4. Save the file
  5. Stage and commit:
git add index.html
git commit -m "Resolve merge conflict in header"

12. Useful Git Commands

Status and History

git status                  # Show current changes
git log                     # Show commit history
git log --oneline           # Compact commit history
git log --graph --all       # Visual branch history

Making Changes

git add <file>             # Stage specific file
git add .                  # Stage all changes
git commit -m "message"    # Commit staged changes
git commit -am "message"   # Stage and commit (tracked files only)

Branches

git branch                 # List branches
git branch <name>          # Create branch
git checkout <name>        # Switch branch
git checkout -b <name>     # Create and switch
git merge <branch>         # Merge branch into current
git branch -d <branch>     # Delete branch

Remote Operations

git remote -v              # List remote repositories
git push                   # Upload commits
git pull                   # Download commits
git clone <url>            # Copy remote repository
git fetch                  # Download without merging

Undoing Changes

git restore <file>         # Discard working changes
git restore --staged <file> # Unstage file
git reset HEAD~1           # Undo last commit (keep changes)
git reset --hard HEAD~1    # Undo last commit (discard changes)

Warning: --hard permanently deletes changes!


13. Knowledge Check

Question 1: What is the difference between git add and git commit?

Show answer `git add` stages files (prepares them for commit), while `git commit` saves the staged changes to the repository with a message.

Question 2: How do you upload your local commits to GitHub?

Show answer Use `git push` to upload your commits to the remote repository on GitHub.

Question 3: What should you include in a .gitignore file?

Show answer Files that should never be tracked by Git: node_modules, .env files, build outputs, IDE settings, OS files, and sensitive data.

Question 4: What command shows you which files have been changed?

Show answer `git status` shows changed files, and `git diff` shows the specific line-by-line changes.

Question 5: How do you create a new branch and switch to it in one command?

Show answer `git checkout -b branch-name` or `git switch -c branch-name` (modern syntax).

Question 6: What happens when you run git pull?

Show answer Git downloads commits from the remote repository and merges them into your current branch.

14. Practical Exercises

Exercise 6.1.1: Initialize a Repository

  1. Create a new project folder
  2. Initialize Git
  3. Create an index.html file
  4. Stage and commit the file
  5. Check your commit history

Exercise 6.1.2: Make Multiple Commits

  1. Edit your index.html (add a header section)
  2. Commit the changes
  3. Add a new styles.css file
  4. Commit the CSS file
  5. View your commit log

Exercise 6.1.3: Connect to GitHub

  1. Create a GitHub account (if you don't have one)
  2. Create a new repository on GitHub
  3. Connect your local repository to GitHub
  4. Push your commits to GitHub
  5. Verify the files appear on GitHub

Exercise 6.1.4: Work with Branches

  1. Create a new branch called feature-footer
  2. Add a footer to your index.html
  3. Commit the changes on the branch
  4. Switch back to main
  5. Merge the feature-footer branch
  6. Push to GitHub

Exercise 6.1.5: Create a .gitignore

  1. Create a .gitignore file
  2. Add common exclusions (node_modules, .env, etc.)
  3. Create a dummy .env file
  4. Verify Git ignores it (git status should not show it)
  5. Commit the .gitignore file

15. Key Takeaways

  • Version control tracks changes to files over time
  • Git is the industry-standard distributed version control system
  • Three stages: Working Directory → Staging Area → Repository
  • Commits are snapshots of your project with descriptive messages
  • GitHub provides remote hosting and collaboration features
  • Branches allow isolated development of features
  • .gitignore prevents tracking of unnecessary or sensitive files
  • Always commit before deploying to production
  • Write clear commit messages for better project history
  • Push regularly to back up your work on GitHub

16. Common Mistakes to Avoid

Committing Sensitive Data

Bad:

git add .env
git commit -m "Add config"

Good:

# Add .env to .gitignore first
echo ".env" >> .gitignore
git add .gitignore
git commit -m "Ignore environment variables"

Vague Commit Messages

Bad:

git commit -m "updates"
git commit -m "fix"
git commit -m "aaa"

Good:

git commit -m "Fix mobile navigation menu toggle"
git commit -m "Add email validation to contact form"
git commit -m "Update homepage hero section styling"

Not Pulling Before Pushing

Bad:

# Make changes
git push  # May fail if remote has changes

Good:

git pull   # Get latest changes first
# Make changes
git push

Tracking Build Files

Bad:

git add dist/
git add node_modules/

Good:

# Add to .gitignore
echo "dist/
node_modules/" >> .gitignore

17. Next Steps

Excellent work! You now understand Git fundamentals and can manage your code with version control.

In Lesson 6.2: Frontend Deployment (Netlify/Vercel), you'll learn how to deploy your static websites to production using modern hosting platforms.

Ready to put your website live on the internet? Let's go!


Further Resources

Official Documentation:

Interactive Learning:

Cheat Sheets:

Best Practices: