1. Introduction

What is Version Control

Version control records changes to files over time, allowing you to recall specific versions later. It lets you revert entire projects, compare changes, see who modified what, and recover from mistakes. A Version Control System (VCS) manages the evolution of a project, storing every version of every file and metadata (author, timestamp, message).

Why Version Control Matters

Without it, teams rely on file copies (project_final_v2_OLD) or shared folders. This leads to confusion and lost work. Version control brings:

  • Collaboration: Multiple people work on the same files without overwriting.
  • History: Every change is logged with author, date, and an explanation.
  • Recovery: Rollback to any previous version.
  • Branching: Isolate new ideas without breaking stable code.
  • Traceability: Link changes to issues or features.
  • CI/CD backbone: Automated build, test, and deployment rely on version control.

History of Git

Linus Torvalds created Git in 2005 for Linux kernel development after the free BitKeeper license was revoked. Goals: speed, simplicity, strong support for parallel branches, fully distributed, and ability to handle massive projects.

Why Linus Torvalds Created Git

He needed a DVCS that was fast, reliable, and allowed thousands of contributors to work independently without a single point of failure. Existing open-source tools (CVS, SVN) were centralized and slow. Torvalds wanted trivial branching and merging and complete data integrity.


Why Developers Use Git

  • Industry standard in all software domains
  • GitHub/GitLab enabled cloud-based collaboration
  • Branching and merging are cheap and easy
  • Works offline; full history locally
  • Free and open-source with huge community

Git vs GitHub

Git is the version control engine; GitHub is a web platform that hosts Git repositories and adds issue tracking, pull requests, CI/CD, project boards, and social features. GitLab and Bitbucket offer similar services.

Git vs GitLab

GitLab includes built-in container registry, Kubernetes integration, and robust CI/CD, plus self-hosting options.

Git vs Bitbucket

Bitbucket integrates tightly with Jira and supports Git LFS natively.

Distributed vs Centralized Version Control

  • Centralized (CVCS): One central server; clients check out files. Server is a single point of failure; network needed for most operations.
  • Distributed (DVCS): Every clone is a full repository. Work offline; push/pull to sync. More resilient and flexible.

Real-world Examples

  • Linux kernel (30M+ lines, thousands of contributors)
  • Android, Windows (Microsoft uses Git with VFS for Git)
  • Facebook, Netflix, Amazon, Apple
  • Almost every modern open-source project (React, Kubernetes, TensorFlow)

Companies Using Git

All major tech companies and most enterprises. Microsoft's GitHub acquisition cemented Git's place. Git is also used in non-tech industries like banking and healthcare.

Career Benefits

Version control skills are mandatory. Mastering Git shows you can collaborate, manage code professionally, and are ready for DevOps and CI/CD roles.

Common Misconceptions

  • "GitHub is Git" – GitHub is just a hosting service.
  • "Git stores differences" – It stores snapshots of all files.
  • "You need internet to use Git" – All core commands work offline.
  • "Branches are copies" – Branches are just movable pointers to commits.
  • "Merge conflicts are scary" – With good practices they're routine.
  • Summary: Version control is essential; Git is the dominant DVCS; GitHub is a collaboration platform. The distinction matters.
  • Key Takeaways: VCS tracks history; Git is distributed; GitHub adds web interface and collaboration.
  • Common Mistakes: Confusing Git and GitHub; neglecting the command line.
  • Practice Exercises: Research a project that migrated from SVN to Git. List three reasons.
  • Mini Project: Create a GitHub account (if not done) and explore trending repositories.
  • Interview Questions: Explain version control to a non-technical person. Distributed vs centralized?
  • Professional Tips: Bookmark the official Git documentation at https://git-scm.com/doc.
  • Recommended Next Steps: Install Git.

2. Installing Git

Windows

Download from https://git-scm.com/download/win. Run the installer and follow these recommendations:

  • Components: "Git Bash Here", "Git GUI Here", associate .git config.
  • Default editor: choose VS Code if installed, or Nano.
  • PATH: "Git from the command line and also from 3rd-party software".
  • HTTPS backend: OpenSSL.
  • Line endings: "Checkout Windows-style, commit Unix-style".
  • Terminal: MinTTY.
  • Extra: enable file system caching, enable Credential Manager.

Alternatively, use winget: winget install --id Git.Git -e --source winget or Chocolatey: choco install git.

Linux (Debian/Ubuntu)

bash

sudo apt update
sudo apt install git-all

For Fedora: sudo dnf install git-all, Arch: sudo pacman -S git.

macOS

Homebrew: brew install git. Xcode Command Line Tools include Git but may be outdated. Binary installer from git-scm.com also available.

Verifying Installation

bash

git --version

Should display something like git version 2.45.0.

Git Configuration

Git settings are stored at three levels: system (/etc/gitconfig), global (~/.gitconfig), and local (.git/config in repo). Local overrides global overrides system.

Set your identity globally:

bash

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

Set default branch name to main:

bash

git config --global init.defaultBranch main

Setting Username and Email (details)

These are required for commits. Use an email linked to your GitHub account for contributions to be attributed. To keep your email private, use GitHub's no-reply address.

Config Levels in Detail

To set a repository-specific email:

bash

git config user.email "project@example.com"

List all settings and their source: git config --list --show-origin.

Git Editors

Configure editor for commit messages and rebase:

bash

git config --global core.editor "code --wait"   # VS Code
# Or "nano", "vim", "atom --wait", etc.

VS Code Integration

VS Code has excellent built-in Git support. You can stage, commit, diff, and push from the GUI, but learning the CLI gives you full control.

💡 Professional Tip: Always set name and email before first commit; otherwise Git will prompt you and may use your system's hostname.
  • Summary: Install Git, set name/email/editor. Config levels: system, global, local.
  • Key Takeaways: Global identity ensures proper attribution; default branch can be set to main.
  • Common Mistakes: Missing identity config; not linking email to GitHub.
  • Practice Exercises: Install Git, set global config, check git config --global --list.
  • Mini Project: Create a .gitconfig file manually with your favorite aliases.
  • Interview Questions: Where does Git store global configuration? How do you override a setting for one repo?
  • Professional Tips: On macOS/Linux, set core.autocrlf input to avoid line-ending issues; on Windows, keep true.
  • Recommended Next Steps: Git fundamentals.

3. Git Fundamentals

Repository

A Git repository is a directory containing your project files plus the .git folder that holds the entire history. Create with git init or git clone.

Working Directory

The working tree is the set of files you edit. It reflects the current branch's latest commit. Switching branches changes the working directory content.

Staging Area (Index)

An intermediate layer where you build the next commit. git add moves changes from working directory to staging. This allows selective commits.

Local Repository

The .git directory stores all commits, branches, tags. When you commit, a new snapshot is added to this local database.

Remote Repository

A version of the project hosted on another machine (e.g., GitHub). You push local changes to it and pull others' changes from it.

Commit

A commit is a snapshot of the staging area with metadata (author, date, message) and parent pointers. Identified by a 40-character SHA-1 hash. It's immutable; changing it creates a new commit with a new hash.

History

The commit graph is a Directed Acyclic Graph (DAG). git log walks this graph.

Snapshots, Not Differences

Git stores whole files (blobs) compressed. If a file doesn't change, the commit points to the same blob. This makes branching and diffing extremely fast.

SHA Hashes

Git uses SHA-1 (moving to SHA-256) to identify objects. The hash is derived from the object's content, ensuring integrity and uniqueness. A changed file produces a new blob and a new tree, cascading to a new commit hash.

Git Object Model

Four object types:

  • Blob: file content.
  • Tree: directory listing, maps names to blobs and subtrees.
  • Commit: points to a tree and parent commit(s), holds metadata.
  • Tag: points to a commit (annotated tags).

Text diagram of commit structure:

text

Commit: a1b2c3d...
├── tree: 4e5f6g...
│   ├── blob: "README.md"  (hash: 123abcd...)
│   └── tree: "src"
│       ├── blob: "main.py" (hash: 456efgh...)
│       └── blob: "utils.py" (hash: 789ijkl...)
├── parent: commit 9z8y7x... (previous commit)
├── author: John Doe <john@example.com>
└── message: "Add initial source files"

How Git Stores Data

When you git add, Git compresses the file into a blob and stores it in .git/objects/. It also updates the index. On commit, Git creates a tree from the index and a commit object referencing that tree and the parent commit. Objects are eventually packed into packfiles for efficiency.

Git Architecture

High-level commands (porcelain: add, commit, log) are built on low-level plumbing (cat-file, hash-object). This design makes Git scriptable.

  • Summary: A Git repo has three trees: working dir, staging, and commits (local DB). Commits are snapshots linked by hashes.
  • Key Takeaways: Understand the three areas; staging enables fine control; everything is content-addressable.
  • Common Mistakes: Thinking git commit directly commits working directory changes; not understanding the index.
  • Practice Exercises: git init a folder, inspect .git/objects (empty). Create a file, stage, commit, then look at objects again.
  • Mini Project: Use git cat-file -p <commit-hash> to explore the commit, tree, and blob objects.
  • Interview Questions: Explain the three areas of a Git repository. What is a commit hash and why is it unique?
  • Professional Tips: Never commit secrets; even if removed, they remain in history until cleaned.
  • Recommended Next Steps: Creating repositories.

4. Creating Repositories

git init

bash

mkdir my-project
cd my-project
git init

This creates the .git directory and sets the default branch. To specify branch name: git init --initial-branch=main.

git clone

bash

git clone https://github.com/user/repo.git

This creates a repo folder, downloads the full history, and checks out the latest commit. For a custom directory: git clone <url> my-folder.

Repository Structure

Inside .git:

  • HEAD → points to current branch
  • config → repo-specific settings
  • objects/ → all data (blobs, trees, commits, tags)
  • refs/ → branch and tag pointers
  • index → staging area
  • hooks/ → scripts
  • logs/ → reflog

The rest of the folder is the working tree.

Repository Best Practices

  • One project per repository; avoid nested repos unless using submodules.
  • Add .gitignore early.
  • Include a README.md describing the project.
  • Avoid committing large binaries; use Git LFS.
  • Commit often in logical units.
  • Summary: init for new local repo, clone for existing remote. The .git folder is the heart.
  • Key Takeaways: Repo = working tree + .git; clones are full copies.
  • Common Mistakes: Initializing inside an existing non-empty directory; forgetting to add a README.
  • Practice Exercises: Create two repos: one via init, one via clone of a public repo. Compare .git structures.
  • Mini Project: Initialize a project with a README and a .gitignore, then make the first commit.
  • Interview Questions: What's the difference between git init and git clone? What does the .git folder contain?
  • Professional Tips: Use git clone --depth 1 for a shallow clone if you don't need full history.
  • Recommended Next Steps: Basic commands.

5. Basic Git Commands

git status

Shows the state of working directory and staging area.

bash

git status

Output tells you: branch, changes not staged, changes to be committed, untracked files.

Options: -s for short format, -b for branch info.

git add

Stages changes for the next commit.

  • git add file.txt
  • git add . (all modified/new files in current dir)
  • git add -A (all changes including deletions)
  • git add -p (interactive partial staging)
  • Staged files appear under "Changes to be committed".

git commit

Creates a new snapshot from the staging area.

bash

git commit -m "Add feature X"

Without -m, editor opens for detailed message.

Amend last commit: git commit --amend (rewrites commit; never amend pushed commits).

git log

Shows commit history.

bash

git log --oneline --graph --all

Filter: --author="John", --since="1 week ago", --grep="bug".

git diff

Shows differences between states.

  • Working dir vs staging: git diff
  • Staging vs last commit: git diff --staged
  • Between branches: git diff main..feature
  • For a specific commit: git diff HEAD~1 HEAD

git restore

Reverts changes in working tree or staging.

  • Discard uncommitted changes: git restore file.txt
  • Unstage: git restore --staged file.txt
  • Restore from older commit: git restore --source=HEAD~2 file.txt

git rm

Removes files and stages the deletion.

  • git rm file.txt (delete and stage)
  • git rm --cached file.txt (stop tracking, keep local)
  • git rm -f (force if modified)

git mv

Move/rename and stage.

bash

git mv old.txt new.txt

git show

Displays info about a Git object (commit, tag).

bash

git show HEAD

Shows commit message and diff.

git help

Opens manual.

bash

git help commit
git commit --help
⚠️ Warning: git add . stages everything, including files not yet in .gitignore. Always check with git status.
  • Summary: status, add, commit, log, diff, restore are daily drivers. Master them.
  • Key Takeaways: Staging is central; logging and diffing give visibility; unstage/discard safely.
  • Common Mistakes: Committing without a message; git add . capturing too much; losing changes with restore.
  • Practice Exercises: Create a project, make changes, stage only some, commit, diff, log, restore a file, amend.
  • Mini Project: Track a small text project with meaningful commits and use log --graph.
  • Interview Questions: How do you unstage a file? What does git diff --staged show? Explain git restore.
  • Professional Tips: Use git commit -v to see the diff in your editor while writing message.
  • Recommended Next Steps: Tracking changes and ignoring files.

6. Tracking Changes

File States

  • Modified: changed but not staged.
  • Staged: marked for next commit.
  • Untracked: not in last commit and not staged.

.gitignore

A file listing patterns for files Git should ignore.

text

# Example .gitignore
node_modules/
.env
*.log
dist/

Rules: blank lines ignored; # comments; ! negates; patterns apply recursively.

Global ignore: git config --global core.excludesfile ~/.gitignore_global

Ignoring Tracked Files

If a file is already tracked, adding to .gitignore won't stop tracking. You must first git rm --cached file.txt, then commit.

Best Practices

  • Create .gitignore before first commit.
  • Use GitHub's templates (e.g., Python, Node).
  • Never commit secrets, IDE personal settings, or build artifacts.
  • Summary: .gitignore keeps unwanted files out; staging controls what gets committed.
  • Key Takeaways: Tracked vs untracked; ignore patterns are powerful; global ignore for OS files.
  • Common Mistakes: Forgetting to add .gitignore, committing large binaries, ignoring already-tracked files incorrectly.
  • Practice Exercises: Create a repo, add files, write a .gitignore, commit, verify ignored files don't appear.
  • Mini Project: Set up a global gitignore for .DS_Store and Thumbs.db. Test it across repos.
  • Interview Questions: How do you ignore files that are already committed? What is a global gitignore?
  • Professional Tips: Use git check-ignore -v filename to debug which rule ignores a file.
  • Recommended Next Steps: Commit best practices.

7. Commit Best Practices

Atomic Commits

A commit should represent one logical change. If you fix a bug and refactor a function, make two commits. This makes history clear and allows reverting without side effects.

Good Commit Messages

Structure:

text

<subject> (50 chars max, imperative, capitalize, no period)

<body> (wrap at 72 chars, explain what and why, not how)

Example:

text

Fix login crash on empty password

The login handler didn't check for null input, causing a segfault.
Added guard clause to return 400 Bad Request.

Fixes: #421

Conventional Commits

Format: <type>[optional scope]: <description>

Types: feat, fix, docs, style, refactor, test, chore, perf, ci, build.

Example: feat(auth): add OAuth2 support

Enables automated changelogs and versioning.

Semantic Commit Messages

Same idea: prefix messages with standardized keywords to communicate intent.

Team Commit Standards

  • Agree on a convention.
  • Never commit broken code to main/shared branches.
  • Run tests locally before committing.
  • Keep commits small and focused.

Professional Examples

text

feat: implement search API
fix: correct date parsing in report
docs: update API documentation
refactor: extract payment service
test: add unit tests for auth module
ci: configure GitHub Actions for CI
💡 Professional Insight: A clean, well-documented commit history is a sign of a skilled developer. Use interactive rebase to polish before sharing.
  • Summary: Write meaningful commits with conventional prefixes. Atomic commits aid maintainability.
  • Key Takeaways: Subject line imperative, 50 chars; separate body; use conventional types.
  • Common Mistakes: "fix", "update", "stuff" messages; mixing unrelated changes.
  • Practice Exercises: Rewrite the last three commits of a test repo using conventional style and rebase.
  • Mini Project: Install commitlint (Node.js project) to enforce conventional commits on every commit.
  • Interview Questions: What makes a good commit message? What are conventional commits?
  • Professional Tips: Use a .gitmessage template to guide your team.
  • Recommended Next Steps: Branching.

8. Branching

Why Branches Exist

A branch is a lightweight pointer to a commit. Branching allows parallel lines of development. The default branch is often main. Creating a branch is instant (just a new pointer).

Text diagram of branching:

text

A---B---C  main
     \
      D---E  feature

Here, main points to C, feature points to E.

Creating and Switching Branches

Create: git branch feature-x

Switch: git switch feature-x (new) or git checkout feature-x

Create and switch: git switch -c feature-x / git checkout -b feature-x

List branches: git branch (current marked with *)

Deleting Branches

  • Delete merged branch: git branch -d feature-x
  • Force delete: git branch -D feature-x

Renaming

  • Rename current branch: git branch -m new-name
  • Rename any branch: git branch -m old new

Comparing Branches

  • List commits in feature not in main: git log main..feature
  • Diff tips: git diff main..feature
  • Merged branches: git branch --merged
  • Unmerged: git branch --no-merged

Branch Strategies

Git Flow

Two long-lived branches: master (production) and develop. Temporary branches: feature/*, release/*, hotfix/*.

text

master    A---B------F---------J---K
           \        /         /
develop     C---D---E---G---H---I
                 \     /   /   /
feature-x       D---E   /   /
                       /   /
release-1.0           G---H
                           \
hotfix-1.0.1               I---J

GitHub Flow

Single main branch, always deployable. Short-lived feature branches off main, merged via pull request. Simple for continuous deployment.

Trunk-Based Development

All developers commit directly to main (or short-lived branches lasting <24h). Feature flags hide incomplete work. Used by Google, Facebook.

Choose based on release cadence and team size.

  • Summary: Branches enable parallel work. Git Flow, GitHub Flow, Trunk-Based are common models.
  • Key Takeaways: Branches are cheap pointers; switching changes working tree; delete merged branches.
  • Common Mistakes: Working directly on main; long-lived branches causing huge merges; leaving stale branches.
  • Practice Exercises: Create a feature branch, make two commits, switch back to main and observe differences, merge.
  • Mini Project: Simulate Git Flow by creating develop and feature branches, then merge via a release branch.
  • Interview Questions: What is a branch? Compare Git Flow and GitHub Flow. How to delete a remote branch?
  • Professional Tips: Keep feature branches short (max few days). Merge main into feature often to reduce conflicts.
  • Recommended Next Steps: Merging.

9. Merging

Fast-Forward Merge

If the target branch hasn't diverged, Git simply moves the pointer forward. No new commit.

Before:

text

A---B  main
     \
      C---D  feature

After git merge feature:

text

A---B---C---D  main, feature

Use git merge --no-ff to force a merge commit even in fast-forward case, preserving branch history.

Three-Way Merge

When both branches have new commits, Git creates a new merge commit with two parents.

Before:

text

A---B---C  main
     \
      D---E  feature

After git merge feature:

text

A---B---C---M  main
     \     /
      D---E

Commit M ties the histories together.

Merge Conflicts

When the same part of a file is modified differently, Git cannot auto-merge. Markers appear:

text

<<<<<<< HEAD
your changes
=======
their changes
>>>>>>> feature

Resolve by editing the file, removing markers, then git add and git commit. To abort: git merge --abort.

Resolving Conflicts

  • Manual editing, then stage.
  • Visual tools: git mergetool (e.g., VS Code, Beyond Compare).
  • Use git checkout --ours or --theirs for quick resolution, but be careful.

Merge Strategies

  • recursive: default, handles renames.
  • ours: keep target branch version for conflicted files.
  • theirs: keep merging branch version (via -X theirs).
  • octopus: merges more than two branches.

Merge Tools

Configure: git config --global merge.tool vscode. Launch with git mergetool.

Professional Workflow

Before merging feature to main:

  1. Merge main into feature (git merge main while on feature) to test integration.
  2. Resolve conflicts in feature branch.
  3. Open Pull Request.
  4. After approval, merge (fast-forward or merge commit depending on policy).
⚠️ Warning: Reverting a merge commit is complex; it's usually better to fix the original branch and re-merge.
  • Summary: Merging integrates branches; fast-forward for linear, three-way for diverged; conflicts resolved manually.
  • Key Takeaways: git merge --no-ff to keep branch identity; always update feature with target branch first.
  • Common Mistakes: Not updating feature with main before merging, causing big conflicts. Panic during conflicts.
  • Practice Exercises: Create two branches from same base, change same file line, merge and resolve. Abort a conflict merge.
  • Mini Project: Simulate a feature merge with --no-ff into main after updating feature with main.
  • Interview Questions: How do you resolve a merge conflict? What is a fast-forward merge?
  • Professional Tips: Use git mergetool for visual conflict resolution. git log --merge shows commits involved in conflict.
  • Recommended Next Steps: Rebasing.

10. Rebasing

What is Rebase

Rebase replays commits from one branch onto another, creating a linear history.

Before:

text

A---B---C  main
     \
      D---E  feature

After git rebase main (from feature):

text

A---B---C  main
         \
          D'---E'  feature

Commits D' and E' are new, with new hashes, because their parent changed.

Merge vs Rebase

  • Merge: preserves exact branching history, safe for public branches.
  • Rebase: linear, cleaner history; rewrites commits, so only for private branches.

Interactive Rebase

git rebase -i <commit> opens editor to reorder, squash, edit, or drop commits.

Example: squash last 3 commits:

bash

git rebase -i HEAD~3

Change pick to squash (or s) for commits to combine.

Squashing Commits

Combines multiple commits into one. Cleans up feature branch before merging.

Editing and Reordering

Mark a commit with edit to stop and amend it. Reorder lines to change order, but careful – reordering may cause conflicts.

When Not to Rebase

  • Never rebase commits pushed to a shared repository (others may have built on them).
  • Golden rule: rebase only local, unpublished commits.

If you must fix a pushed branch after an accidental rebase, use git push --force-with-lease and alert your team.

Text diagram: rebase workflow.

text

Original:
      main: A---B---C
                 \
      feature:    D---E
After rebase feature onto main:
      main: A---B---C
                     \
      feature:        D'---E'
  • Summary: Rebase creates linear history; interactive rebase polishes commits; never rebase public commits.
  • Key Takeaways: Rewriting history is powerful but dangerous if shared; squash for clean PRs.
  • Common Mistakes: Rebasing pushed branches; forgetting to force push after amend/rebase; resolving same conflict repeatedly.
  • Practice Exercises: Create a branch, make 3 messy commits, use rebase -i to squash and reword. Rebase onto main.
  • Mini Project: Take a real feature branch, clean it with interactive rebase, then merge with --no-ff.
  • Interview Questions: Merge vs rebase? When is rebase inappropriate? Explain interactive rebase.
  • Professional Tips: git pull --rebase to avoid unnecessary merge commits when syncing.
  • Recommended Next Steps: Undoing changes.

11. Undoing Changes

git restore (recap)

Discard working changes or unstage.

git reset

Moves branch pointer backwards, optionally modifying staging/working directory.

  • --soft: HEAD moves, staging and working kept (changes stay staged).
  • --mixed (default): HEAD moves, staging reset, working kept (changes unstaged).
  • --hard: HEAD moves, staging and working reset to match commit – all local changes lost.

bash

git reset --soft HEAD~1   # undo commit, keep changes staged
git reset HEAD~1          # undo commit, unstage changes
git reset --hard HEAD~1   # DANGER: destroy last commit and all changes

To unstage a file: git reset file (same as git restore --staged file).

git revert

Creates a new commit that undoes a previous commit. Safe for public history.

bash

git revert abc123

This applies the inverse of the changes from commit abc123.

Recovering Deleted Work: HEAD, Detached HEAD, Reflog

  • HEAD: pointer to current branch/commit.
  • Detached HEAD: when you checkout a specific commit (not a branch). Commits here are unreferenced when you switch away.
  • Reflog: records every HEAD movement locally. Use git reflog to find "lost" commits.

Recovery after hard reset:

bash

git reflog                  # find the hash before reset
git reset --hard <hash>     # restore

Or create a branch: git branch recovery <hash>

  • Summary: Reset rewrites local history; revert safely undoes commits; reflog saves you from mistakes.
  • Key Takeaways: Soft/mixed/hard reset; --hard is dangerous; reflog is local and ephemeral but invaluable.
  • Common Mistakes: Running git reset --hard without checking status; not knowing about reflog recovery.
  • Practice Exercises: Make commits, reset soft/mixed/hard, recover with reflog. Revert a commit and check log.
  • Mini Project: Simulate an accidental hard reset on a feature branch, then recover the lost work.
  • Interview Questions: git reset vs git revert? How would you recover a deleted commit?
  • Professional Tips: Alias git undo = reset --soft HEAD~1 for quick uncommit.
  • Recommended Next Steps: Stashing.

12. Stashing

git stash

Saves uncommitted changes temporarily, cleaning the working directory.

bash

git stash push -m "WIP on login"
  • Include untracked: git stash -u
  • Include ignored: git stash -a

Applying and Popping

  • git stash apply – reapplies latest stash, keeps it in stash list.
  • git stash pop – applies and removes from list.
  • Apply specific stash: git stash apply stash@{2}.

Listing, Dropping, Clearing

  • git stash list
  • git stash drop stash@{1}
  • git stash clear (removes all)

Multiple Stashes

Stashes are a stack. You can name them for context.

Practical Workflow

  1. Mid-feature, urgent bug: git stash or git stash -u.
  2. Switch to hotfix branch, fix, commit.
  3. Switch back to feature, git stash pop.
  4. Continue.
⚠️ Warning: Stashes are local only; not a replacement for commits. Long-lived stashes can be forgotten.
  • Summary: Stashing saves work-in-progress for quick context switches.
  • Key Takeaways: Stash stack, apply vs pop, include untracked with -u.
  • Common Mistakes: Accumulating many stashes and forgetting about them; popping without checking stack.
  • Practice Exercises: Modify files, stash, create a new branch, commit something, pop stash back.
  • Mini Project: Simulate interrupt-driven development: stash uncommitted work, fix a typo on main, pop and continue.
  • Interview Questions: How do you save uncommitted changes to switch branches? Difference between stash apply and pop?
  • Professional Tips: Use git stash push -m "description" for clarity. git stash show -p stash@{0} to view stash contents.
  • Recommended Next Steps: Tags.

13. Tags

Annotated Tags

Full objects with tagger name, email, date, message; can be GPG signed. Used for releases.

bash

git tag -a v1.0.0 -m "Release version 1.0.0"

Lightweight Tags

Just a pointer to a commit, no extra metadata.

bash

git tag v1.0.0-light

Versioning

Tags mark specific commits as important, often for release points. They don't move.

Push tags to remote:

bash

git push origin v1.0.0
git push --tags  # all tags

Delete remote tag: git push origin --delete v1.0.0

Semantic Versioning (SemVer)

MAJOR.MINOR.PATCH (e.g., 2.3.1). Tags follow this: v2.3.1.

Releases on GitHub

Push a tag, then on GitHub create a Release from that tag. Add release notes and binaries.

  • Summary: Tags mark releases; annotated tags are recommended.
  • Key Takeaways: Use annotated for public releases; light for temporary markers; push tags explicitly.
  • Common Mistakes: Forgetting to push tags; using lightweight for releases.
  • Practice Exercises: Create an annotated tag, push, delete locally, delete remotely, recreate.
  • Mini Project: Tag your project v1.0.0, push, then create a GitHub Release.
  • Interview Questions: Annotated vs lightweight tag? How to delete a remote tag?
  • Professional Tips: git describe gives the nearest tag and distance, useful for build scripts.
  • Recommended Next Steps: Remote repositories.

14. Remote Repositories

Origin

The default remote name after cloning. Points back to the source URL. You can rename or add others.

Fetch

Downloads new data from remote but does not merge into your working branch. Updates remote-tracking branches (origin/main).

bash

git fetch origin

Pull

git pull = fetch + merge (or rebase if --rebase). It integrates remote changes into current branch.

bash

git pull origin main
git pull --rebase

Push

Uploads local commits to remote.

bash

git push origin main

If remote has newer commits, push is rejected. First pull, integrate, then push.

Remote URLs

List: git remote -v

Add: git remote add upstream https://github.com/orig/repo.git

Change: git remote set-url origin git@github.com:user/repo.git

Upstream Tracking

Setting upstream links local branch to remote. Then git push/pull without arguments.

bash

git push -u origin feature

Tracking Branches

Remote-tracking branches are read-only snapshots of the remote state. You work on local branches and sync.

Multiple Remotes

In forking: origin = your fork, upstream = original. Fetch from upstream, merge, push to origin.

  • Summary: Remotes enable collaboration. Fetch/pull/push sync changes.
  • Key Takeaways: Pull = fetch+merge; set upstream for convenience; multiple remotes for forks.
  • Common Mistakes: Force push without --force-with-lease; merging without reviewing fetched changes.
  • Practice Exercises: Create a GitHub repo, add remote, push, clone. Add a second remote, fetch from it.
  • Mini Project: Fork a repo on GitHub, clone, add upstream remote, sync your fork.
  • Interview Questions: Difference between fetch and pull? What is an upstream branch?
  • Professional Tips: Use git fetch --prune to clean up deleted remote branches.
  • Recommended Next Steps: GitHub fundamentals.

15. GitHub Fundamentals

Creating a GitHub Account

Go to github.com, sign up. Choose professional username. Enable 2FA.

Repositories

Create via + icon. Choose public or private. A repo contains code, issues, PRs, wiki, projects, actions.

Public vs Private

  • Public: visible to everyone. Free unlimited public repos.
  • Private: you control access. Free for individuals with limited collaborators.

Repository Settings

Access via Settings tab:

  • Default branch
  • Features (Issues, Wiki, Projects, Discussions)
  • Merge options: merge commit, squash merging, rebase merging
  • Branch protection rules
  • GitHub Pages source

Repository Structure (GitHub web view)

  • Code: files, commits, branches, tags.
  • Issues: bug and task tracking.
  • Pull requests: code review and merge.
  • Actions: CI/CD workflows.
  • Projects: kanban boards.
  • Wiki: documentation.
  • Security: Dependabot, secret scanning, advisories.
  • Insights: traffic, contributors.

README

README.md is the front page. Use markdown. Include project description, installation, usage, contribution guidelines, license.

LICENSE

Choosing a license is crucial. Without one, copyright restrictions apply. Common: MIT, Apache 2.0, GPLv3. Add when creating repo or later via file.

Topics

Add topics (tags) to improve discoverability: python, web, cli.

Descriptions

Short text under repo name; used in search and social previews.

Pinned Repositories

Pin up to 6 repos to your profile to showcase work.

  • Summary: GitHub hosts Git repos with rich collaboration features. Setup includes README, license, topics.
  • Key Takeaways: Public/private repos; README essential; licensing matters.
  • Common Mistakes: No README; no license; not setting up 2FA.
  • Practice Exercises: Create a public repo, add README, license, topics. Pin it on your profile.
  • Mini Project: Build a profile repository (username/username) with bio, skills, and links.
  • Interview Questions: What is a GitHub repository? Why add a license?
  • Professional Tips: Use .github repository for organization-wide defaults (issue templates, contributing guide).
  • Recommended Next Steps: Collaboration.

16. GitHub Collaboration

Forking

Fork creates a personal copy of another user's repo on GitHub. Clone your fork, make changes, then open a Pull Request to the original repo.

Workflow:

  1. Fork via GitHub UI.
  2. git clone https://github.com/your-username/repo.git
  3. cd repo; git remote add upstream https://github.com/original-owner/repo.git
  4. git fetch upstream
  5. Create branch, commit, push to your fork.
  6. Open PR from your fork's branch to upstream's main.

Cloning

Cloning is the action to get a local copy. For collaboration on repos you have push access, you clone directly.

Issues

Track tasks, bugs, enhancements. Best practices:

  • Clear title and description.
  • Steps to reproduce for bugs.
  • Use labels: bug, enhancement, help wanted, good first issue.
  • Assign to team members.
  • Link to related PRs.

Discussions

Forum space for Q&A and community conversations, separate from issues. Enable in repo settings.

Labels

Custom labels to categorize. Example: bug (red), feature (blue), documentation (orange). Use to filter.

Milestones

Group issues/PRs by goal or release. Track progress.

Projects

Kanban boards (like Trello) built into GitHub. Columns: To Do, In Progress, Done. Automate with workflow triggers.

Code Owners

CODEOWNERS file in .github/ defines individuals/teams responsible for specific paths. Automatically requested for review on PRs.

Review Requests

On pull requests, request specific team members to review.

  • Summary: GitHub collaboration revolves around forks, issues, pull requests, and reviews.
  • Key Takeaways: Fork for contribution; issues manage work; labels and milestones organize.
  • Common Mistakes: Not syncing fork; opening PR without issue; ignoring CODEOWNERS.
  • Practice Exercises: Fork a public repo, create an issue, fork and clone, fix it, open a PR.
  • Mini Project: Set up a project board for your own repo, create issues, link PRs, automate moves.
  • Interview Questions: Describe forking workflow. How do code owners work?
  • Professional Tips: Always sync your fork before starting new work: git fetch upstream && git checkout main && git merge upstream/main.
  • Recommended Next Steps: Pull requests.

17. Pull Requests

Creating PRs

On GitHub, after pushing a branch, you can open a Pull Request. Choose base (target) and compare (your branch). Fill title and description, referencing issues (Closes #5).

Review Process

Reviewers can:

  • Comment inline on code.
  • Approve.
  • Request changes.

Conversation tab for general discussion. Commits tab shows history.

Code Review

Best practices for reviewer: be respectful, give constructive feedback, suggest alternatives. For author: keep PRs small, provide context.

Approving & Requesting Changes

After review, approve or request changes. Only approved PRs can merge (if branch protection enabled). Use re-request review after updates.

Draft PRs

Open as draft to indicate work in progress; cannot be merged. Good for early feedback.

Merge Options

When merging PR:

  • Create a merge commit: retains all commits and adds merge commit.
  • Squash and merge: combine all commits into one, then merge. Clean history.
  • Rebase and merge: rebase branch onto base, then fast-forward; linear history without separate merge commit.

Best Practices

  • Small, focused PRs (under 400 lines).
  • Link to issue.
  • Include tests.
  • Ensure CI passes.
  • Request appropriate reviewers.
  • Respond to feedback quickly.
  • Summary: Pull requests are the heart of collaboration. Review, approve, merge.
  • Key Takeaways: Draft PRs for early review; squash merge for clean main history; request changes professionally.
  • Common Mistakes: Giant PRs that are hard to review; ignoring CI failures; not updating after base branch changes.
  • Practice Exercises: In a test repo, create a branch, push, open PR, review as another account, merge.
  • Mini Project: Contribute to a real open source project by finding a good first issue, opening a PR, and addressing review.
  • Interview Questions: Describe the pull request workflow. What is squash merging?
  • Professional Tips: Use pull request templates (.github/PULL_REQUEST_TEMPLATE.md) to standardize descriptions.
  • Recommended Next Steps: Open source contribution.

18. Open Source Contribution

Finding Projects

  • GitHub Explore, trending.
  • Labels: good first issue, help wanted.
  • Look for active projects with contributing guidelines.

Understanding Contribution Guidelines

Read CONTRIBUTING.md. Follow code style, commit conventions, PR template.

Fork Workflow (detailed)

  1. Fork repo.
  2. Clone fork locally.
  3. Add upstream remote.
  4. Create a branch: git switch -c fix-typo.
  5. Make changes, commit (conventional style).
  6. Push to your fork: git push -u origin fix-typo.
  7. Open PR to upstream's main branch.
  8. Discuss, make requested changes.
  9. Once merged, sync your fork: git fetch upstream && git checkout main && git merge upstream/main && git push origin main.

Submitting Pull Requests

  • Clear title and description.
  • Reference issue if exists.
  • Mention if it's work in progress (draft) or ready.
  • Be patient and respond to feedback.

Issue Reporting

Before reporting, search for existing issues. Provide:

  • Steps to reproduce.
  • Expected vs actual behavior.
  • Environment details (OS, version).
  • Screenshots/logs if possible.

Professional Etiquette

  • Be respectful and constructive.
  • Read the project's rules.
  • Don't demand merges.
  • Thank maintainers.

Hacktoberfest

Annual event encouraging open source contributions. Sign up, make PRs in October, earn swag. Quality over quantity.

  • Summary: Open source contribution boosts skills and resume. Use fork-and-PR model.
  • Key Takeaways: Always read CONTRIBUTING; sync fork; be polite; small steps.
  • Common Mistakes: Skipping guidelines; not syncing fork; large unannounced changes.
  • Practice Exercises: Find a beginner-friendly project, make a documentation fix, submit a PR.
  • Mini Project: Participate in Hacktoberfest (or simulate) with at least 2 accepted PRs.
  • Interview Questions: How would you contribute to an open source project? Describe the fork workflow.
  • Professional Tips: Build your own open source tool; it’s a great portfolio piece.
  • Recommended Next Steps: GitHub Actions.

19. GitHub Actions

Introduction

GitHub Actions automates software workflows: build, test, deploy. Defined in YAML files inside .github/workflows/.

Workflows

A workflow is an automated process triggered by events (push, PR, schedule). Consists of one or more jobs.

YAML Basics

yaml

name: CI
on: [push, pull_request]
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Run tests
        run: npm test

Triggers (Events)

  • push: on push to branches.
  • pull_request: on PR open, synchronize, reopen.
  • schedule: cron syntax for timed runs.
  • workflow_dispatch: manual trigger.

Jobs

A job runs on a runner (virtual machine). Default jobs run in parallel. Use needs to sequence.

Steps

Individual tasks within a job. Can run commands or use actions from marketplace.

Actions Marketplace

Reusable building blocks: actions/checkout, actions/setup-node, etc. Use uses: action@version.

Secrets

Store sensitive data (API keys) in repository Settings > Secrets and use ${{ secrets.NAME }}.

Environment Variables

Define at workflow, job, or step level via env.

Build, Test, Deploy (CI/CD)

  • CI: run linters, tests on every PR to ensure quality.
  • CD: deploy to staging/production on push to main.

Example full CI/CD:

yaml

name: CI/CD Pipeline
on:
  push:
    branches: [ main ]
  pull_request:
    branches: [ main ]
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: '3.11'
      - run: pip install -r requirements.txt
      - run: pytest
  deploy:
    needs: test
    if: github.ref == 'refs/heads/main'
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - run: echo "Deploy to production"
  • Summary: GitHub Actions automates CI/CD via YAML workflows triggered by events.
  • Key Takeaways: Workflows, jobs, steps; marketplace actions; secrets for sensitive data.
  • Common Mistakes: Exposing secrets in logs; forgetting actions/checkout first step; infinite loop on push triggers.
  • Practice Exercises: Create a workflow that runs on push, prints "Hello World", uses a marketplace action to checkout.
  • Mini Project: Set up a Python CI that installs dependencies and runs pytest on every PR.
  • Interview Questions: What is GitHub Actions? Explain a CI/CD pipeline.
  • Professional Tips: Cache dependencies with actions/cache to speed up builds.
  • Recommended Next Steps: GitHub Pages.

20. GitHub Pages

Hosting Static Websites

GitHub Pages serves static files from a branch. In repo Settings > Pages, choose branch and folder (root or /docs). The site is published at https://username.github.io/repository (or custom domain).

Custom Domains

Set in Pages settings; add CNAME record. Enforce HTTPS with Let's Encrypt (GitHub provides).

Deploying Documentation

Use static site generators (Jekyll, Hugo, MkDocs) and GitHub Actions to build and deploy to gh-pages branch.

Portfolio Deployment

Create username.github.io repo – its content becomes your personal site.

Workflow example:

yaml

name: Deploy to GitHub Pages
on:
  push:
    branches: [ main ]
jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
      - run: npm ci && npm run build
      - uses: peaceiris/actions-gh-pages@v3
        with:
          github_token: ${{ secrets.GITHUB_TOKEN }}
          publish_dir: ./build
  • Summary: GitHub Pages hosts static sites for free. Great for portfolios and docs.
  • Key Takeaways: Branch deployment; custom domains; automated via Actions.
  • Common Mistakes: Forgetting to set source branch; not building before deploy; relative links broken.
  • Practice Exercises: Create a simple HTML site, deploy via Pages from main branch.
  • Mini Project: Build a personal portfolio with React and deploy to GitHub Pages using Actions.
  • Interview Questions: How do you deploy a static site on GitHub? What is the default domain for Pages?
  • Professional Tips: Use gh-pages branch for deployment output, keeping source separate.
  • Recommended Next Steps: Security.

21. GitHub Security

Two-Factor Authentication (2FA)

Enable in account settings. Use TOTP app or security key. Essential for all accounts.

SSH Keys

Generate SSH key pair: ssh-keygen -t ed25519 -C "email@example.com". Add public key to GitHub Settings > SSH and GPG keys. Clone using SSH URL: git@github.com:user/repo.git.

Personal Access Tokens (PAT)

Replace password for HTTPS Git operations and API. Create in Settings > Developer settings > Personal access tokens. Use fine-grained tokens with repo and permission scopes.

Secrets Management

For Actions, store tokens and keys in repository secrets. Never hardcode in code.

Branch Protection

In repo Settings > Branches, add rule for main:

  • Require pull request reviews before merging.
  • Require status checks (CI) to pass.
  • Require branches to be up to date.
  • Disallow force pushes.

Code Scanning (CodeQL)

GitHub's static analysis tool. Enable via Security > Code scanning. Finds vulnerabilities.

Dependabot

Automated dependency updates. Create dependabot.yml in .github/:

yaml

version: 2
updates:
  - package-ecosystem: "pip"
    directory: "/"
    schedule:
      interval: "weekly"

Secret Scanning

GitHub scans repos for known secret patterns (AWS keys, tokens). Alerts when found. Push protection (prevent commits with secrets) available for some patterns.

Security Best Practices

  • Never commit secrets; use environment variables or secrets management.
  • Regularly review dependabot alerts.
  • Enable branch protection.
  • Audit access.
  • Summary: GitHub provides tools to secure code and accounts: 2FA, SSH, branch protection, scanning, Dependabot.
  • Key Takeaways: Use SSH or PAT; enforce reviews; automated security scanning.
  • Common Mistakes: Committing tokens; not enabling 2FA; ignoring dependabot alerts.
  • Practice Exercises: Enable 2FA, generate SSH key and add to GitHub, create a PAT.
  • Mini Project: Add branch protection to a repo; set up Dependabot; fix a vulnerability found by CodeQL.
  • Interview Questions: What is branch protection? How does Dependabot help?
  • Professional Tips: Use fine-grained PATs with minimum necessary scopes.
  • Recommended Next Steps: Advanced Git.

22. Advanced Git

Cherry Pick

Apply a specific commit from another branch to current.

bash

git cherry-pick <commit-hash>

Useful for backporting hotfixes.

Bisect

Binary search through history to find the commit that introduced a bug.

bash

git bisect start
git bisect bad          # current commit is bad
git bisect good v1.0.0  # tag known good
# Git checks out middle commit; test, mark good/bad
git bisect good/bad
# repeat until culprit found
git bisect reset

Submodules

Include another Git repo as a subdirectory. git submodule add <url> <path>. Cloning with submodules: git clone --recurse-submodules. Updates require separate commit in parent.

Subtrees

Alternative to submodules; merges external repo into a subdirectory as regular files. Simpler but less explicit.

Git Hooks

Scripts triggered by Git events (pre-commit, post-commit, pre-push). Stored in .git/hooks/. Use to lint, test before commit. Share via repo (use tools like pre-commit framework).

Aliases

Create shortcuts:

bash

git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.ci commit
git config --global alias.st status
git config --global alias.unstage 'reset HEAD --'
git config --global alias.last 'log -1 HEAD'

Sparse Checkout

Check out only a subset of files from a repo. Useful for monorepos.

bash

git clone --filter=blob:none --sparse <url>
cd repo
git sparse-checkout set dir1 dir2

Worktrees

Work on multiple branches simultaneously in separate directories, sharing the same repository data.

bash

git worktree add ../project-hotfix hotfix-branch

Clean up: git worktree remove ../project-hotfix

Garbage Collection

git gc optimizes repository by packing objects and removing unreachable ones. Runs automatically occasionally.

Packfiles

Git packs many loose objects into a single indexed file for efficiency. git verify-pack to inspect.

Git Internals

Use plumbing commands to see raw objects: git cat-file -p <hash>. Refs are stored in .git/refs/. HEAD is a text file pointing to current branch. This knowledge demystifies Git’s behavior.

  • Summary: Advanced techniques for specific scenarios: cherry-pick, bisect, submodules, hooks, worktrees.
  • Key Takeaways: Chery-pick for selective changes; bisect for debugging; submodules for dependencies.
  • Common Mistakes: Misusing cherry-pick instead of merge; forgetting to update submodules; ignoring hooks.
  • Practice Exercises: Cherry-pick a commit from another branch. Use bisect to find a known bad commit in a test repo.
  • Mini Project: Set up a pre-commit hook that runs a linter. Use submodule to include a library.
  • Interview Questions: What is cherry-pick? Explain git bisect. How do submodules differ from subtrees?
  • Professional Tips: Use git worktree for hotfixes without stashing your current work.
  • Recommended Next Steps: Git in teams.

23. Git in Teams

Agile/Scrum Workflow

In Agile, work is broken into sprints. Git branches reflect user stories or bugs. Pull requests tied to tasks. Continuous integration ensures readiness.

Branch Policies

Enforce via GitHub branch protection: require reviews, status checks, linear history.

Release Management

Use tags for releases. Git Flow or trunk-based with release branches. Automate with CI/CD.

Hotfixes

Critical bugs fixed on a hotfix branch off main (or master), then merged to main and develop (if Git Flow). Cherry-pick if needed.

Code Reviews

Mandatory for team quality. Use PR checklists, maintain constructive tone.

Monorepos

Single repository with multiple projects. Use sparse checkout, tooling like Bazel or Lerna. Git scales with VFS for Git or Scalar.

Large Teams

  • Use CODEOWNERS for review automation.
  • Squash merge to keep history clean.
  • Rebase feature branches onto main before merging.
  • Automate as much as possible (CI, linting, tests).
  • Summary: Team workflows rely on branch policies, code reviews, and CI. Adapt to team size.
  • Key Takeaways: Protect main; review everything; automate quality.
  • Common Mistakes: Direct pushes to main; ignoring branch protection; inconsistent release process.
  • Practice Exercises: Set up branch protection that requires PR and passing CI in a team repo simulation.
  • Mini Project: With a partner, simulate a full sprint: create issues, branches, PRs, review, merge, release.
  • Interview Questions: How do you manage releases in a team using Git? What is a monorepo and its challenges?
  • Professional Tips: Use GitHub’s required status checks to enforce that all comments are resolved and tests pass.
  • Recommended Next Steps: DevOps integration.

24. DevOps Integration

Git with Docker

Dockerfile and source in Git. CI builds image, tags with commit SHA, pushes to registry. Deploy containers from that image.

Git with Kubernetes

Git as single source of truth. Tools like ArgoCD or Flux synchronize cluster state with Git repo (GitOps). Any change to repo triggers deployment.

GitHub Actions for Terraform

Infrastructure as Code: run terraform plan on PR, terraform apply on merge to main. Use cloud provider secrets.

Cloud Deployment

Using Actions, deploy to AWS, Azure, GCP. Example: build and push to S3, invalidate CloudFront cache.

Infrastructure as Code (IaC)

Store Terraform/CloudFormation/Pulumi code in Git. Changes go through PR review and CI/CD pipeline.

CI/CD Pipelines (detailed)

A typical pipeline:

  • On push to PR: lint, unit test, build, integration test.
  • On merge to main: all above plus deploy to staging, smoke tests, deploy to production with approval.

GitHub Actions can orchestrate everything.

  • Summary: Git is the backbone of modern DevOps: CI/CD, GitOps, IaC.
  • Key Takeaways: Git triggers automation; version everything; use short-lived branches for changes.
  • Common Mistakes: Not testing infrastructure changes; manual deployments; hardcoding secrets.
  • Practice Exercises: Write a workflow that builds a Docker image and pushes to Docker Hub.
  • Mini Project: Set up a simple CI/CD pipeline: on push to main, test, build Docker image, deploy to a cloud service.
  • Interview Questions: What is GitOps? How do you manage infrastructure with Git?
  • Professional Tips: Use github.ref condition to differentiate between dev/staging/production environments.
  • Recommended Next Steps: IDE integration.

25. IDE Integration

VS Code

Built-in Git: source control tab shows changes, stage, commit, sync. Extensions: GitLens (blame, history), Git Graph (visual branch/commit graph).

Visual Studio

Git Changes window, Team Explorer. Full integration with GitHub/Azure DevOps.

PyCharm / IntelliJ IDEA

VCS menu: commit dialog, branch management, merge conflict resolver, GitHub PR integration.

Terminal Integration

All IDEs have integrated terminals; use CLI for full power.

Git GUI Tools

  • GitKraken
  • Sourcetree
  • GitHub Desktop

Useful for visualizing history, but knowing CLI is essential.

  • Summary: Modern IDEs embed Git workflows; use them to boost productivity.
  • Key Takeaways: Learn CLI first, then leverage IDE features; GitLens enriches blame/history.
  • Common Mistakes: Over-reliance on GUI without understanding underlying commands.
  • Practice Exercises: In VS Code, stage, commit, and push using only the GUI. Then check the command line equivalent.
  • Mini Project: Use GitLens to explore the history of a complex open-source project.
  • Professional Tips: Configure user settings in IDE to match global Git config (name/email).
  • Recommended Next Steps: Troubleshooting.

26. Troubleshooting

Common Errors

  • "Please tell me who you are": set user.name and user.email.
  • Merge conflicts: resolve and commit.
  • Detached HEAD: create a branch to save work: git switch -c new-branch.
  • Rejected pushes: pull first, integrate, push.
  • Accidental git add .: use git reset to unstage.
  • Forgotten branch push: check with git branch -avv.

Authentication Problems

  • HTTPS: ensure PAT is not expired; update credential manager.
  • SSH: verify key added to agent (ssh-add -l), public key on GitHub.

Detached HEAD

When git checkout <commit>, HEAD is detached. Any new commits will not belong to a branch. To save, create a branch immediately.

Rejected Pushes (Non-fast-forward)

Remote has new commits. Fetch, merge/rebase, then push.

Corrupted Repository

Run git fsck to check integrity. Recover objects from another clone or backup. git reflog may help.

Large Files and Git LFS

For binary assets, use Git Large File Storage. Install git-lfs, track patterns (git lfs track "*.psd"), and commit .gitattributes. LFS stores file pointers in repo and blobs on a separate server.

Recovery Techniques

  • Recover lost commit with reflog: git reflog, then git checkout <hash> or git branch recovery <hash>.
  • Revert a merge: git revert -m 1 <merge-commit>.
  • Unstage file: git restore --staged file.
  • Discard uncommitted: git restore file or git checkout -- file.
  • Summary: Most Git problems have straightforward solutions; reflog and stash are safety nets.
  • Key Takeaways: Stay calm; use git status; reflog is your friend; learn recovery commands.
  • Common Mistakes: Force pushing without understanding; deleting branches prematurely.
  • Practice Exercises: Simulate a detached HEAD commit, then recover it. Induce a merge conflict, abort, and retry.
  • Mini Project: "Disaster recovery drill": delete a branch, use reflog to restore. Corrupt a file, restore from git.
  • Interview Questions: How to recover a lost commit? What to do when push is rejected?
  • Professional Tips: Always have an alias for git reflog and keep local repo backups.
  • Recommended Next Steps: Professional best practices.

27. Professional Best Practices

Repository Organization

  • Clear directory structure (src, docs, tests, scripts).
  • .gitignore in root.
  • README, LICENSE, CONTRIBUTING, CHANGELOG.

Branch Naming

Use conventions: feature/add-login, bugfix/issue-42, chore/update-deps, hotfix/1.2.1.

Commit Standards

Enforce conventional commits. Use commit hooks (commitlint) and CI checks.

Documentation

  • README.md: project overview, setup, usage.
  • CONTRIBUTING.md: how to contribute.
  • CHANGELOG.md: release notes.
  • Code comments and API docs.

Release Management

  • Semantic versioning with tags.
  • Automated release notes via conventional commits.
  • Branch strategy determines when releases happen.

Security

  • Never commit secrets.
  • Use Dependabot and CodeQL.
  • Regularly rotate PATs and deploy keys.

Backup Strategy

Git is distributed, so every clone is a backup. For extra safety, mirror to another remote: git remote add backup <url>; git push --mirror backup.

Workflow Selection

  • Small team continuous deployment: GitHub Flow.
  • Scheduled releases with multiple versions: Git Flow.
  • High-trust team with feature flags: trunk-based.
  • Summary: Professionalism means consistent conventions, security, documentation, and automated quality.
  • Key Takeaways: Branch naming, commit standards, release process, security scanning.
  • Common Mistakes: Inconsistent workflow; no documentation; neglecting security.
  • Practice Exercises: Create a CONTRIBUTING.md and a pull request template for a repo.
  • Mini Project: Set up a complete release workflow: conventional commits, GitHub Actions to publish release notes on tag push.
  • Interview Questions: How do you organize a repository? What release strategy do you prefer?
  • Professional Tips: Automate as much as possible; use issue/PR templates to save time.
  • Recommended Next Steps: Interview preparation.

28. Interview Preparation

Beginner Questions

  • What is version control? Why Git?
  • Explain the Git workflow: working directory, staging, repository.
  • How do you create a repository? Clone?
  • What is a commit? How to write a good message?
  • Difference between git pull and git fetch?
  • How to undo a commit?

Intermediate Questions

  • Explain branching and merging. Fast-forward vs three-way.
  • What is a merge conflict? How to resolve?
  • What is rebase? When to avoid?
  • Explain git reset modes.
  • What is .gitignore? How to ignore tracked files?
  • Describe GitHub pull request flow.

Advanced Questions

  • Git object model: blob, tree, commit, tag.
  • How does Git store data? (snapshots, packfiles)
  • What is the reflog? How to recover lost commits?
  • Difference between merge and rebase? Golden rule?
  • Explain Git Flow, GitHub Flow, trunk-based development.
  • What is interactive rebase? Cherry-pick?
  • What is a detached HEAD?
  • How to use git bisect?
  • Submodules vs subtrees.

Scenario-Based Questions

  • You accidentally committed a secret. What do you do?
  • A critical bug is in production. How do you hotfix?
  • Your team's feature branch has fallen behind main by 50 commits. How to integrate?
  • A colleague force-pushed to main and broke things. Recover.
  • You want to contribute to an open-source project. Describe the process.

Common Coding Interview Topics

  • Git isn't coding, but you may be asked to demonstrate branching/merging during pair programming.
  • Understanding version control is expected.
  • Summary: Prepare with conceptual and scenario-based questions. Demonstrate deep understanding.
  • Key Takeaways: Know the "why" behind commands; real-world scenarios test practical knowledge.
  • Common Mistakes: Superficial knowledge; not knowing recovery procedures.
  • Practice Exercises: Write out answers to the above. Teach Git to someone else.
  • Mini Project: Create a "Git interview questions" repo with detailed answers and diagrams (text).
  • Recommended Next Steps: Real-world projects.

29. Real-World Projects

1. Personal Portfolio Repository

  • Problem: Showcase your work.
  • Structure: README.md with bio, skills, projects list. Separate repos for each project.
  • Commands: git init, git remote add, git push.
  • GitHub: Create repository username, pin projects.
  • Improvements: Use GitHub Pages for a static site.

2. Open Source Contribution

  • Problem: Contribute a bug fix to a real project.
  • Planning: Find issue with good first issue label, read CONTRIBUTING.
  • Workflow: Fork, clone, branch fix-xxx, commit, push, PR.
  • Best Practices: Atomic commit, follow their code style.
  • Improvements: Continue contributing, become maintainer.

3. Team Collaboration Simulation

  • Problem: Simulate a team of 3-4 working on a group project.
  • Setup: Shared repo, branch protection, project board.
  • Workflow: Each feature on separate branch, PR with review.
  • Commands: git fetch, git merge, git rebase, conflict resolution.
  • Improvements: Enforce conventional commits, require CI.

4. Documentation Repository

  • Problem: Host team/project documentation.
  • Structure: MkDocs or Docusaurus source in main, deploy to gh-pages via Actions.
  • Workflow: PRs for doc changes, preview deployment.
  • Commands: git worktree for concurrent edits, git stash.
  • Improvements: Add search, versioning.

5. Static Website Deployment with GitHub Pages

  • Problem: Deploy a personal blog.
  • Plan: Use Jekyll or Hugo. GitHub Actions to build and deploy.
  • Commands: git tag to version releases.
  • Improvements: Custom domain, HTTPS.

6. CI/CD Pipeline for a Python App

  • Problem: Automate testing and deployment.
  • Setup: .github/workflows/ci.yml: on PR run pytest; on push to main deploy to Heroku/DigitalOcean.
  • Commands: git push triggers pipeline.
  • Improvements: Add linting, coverage reporting, staging environment.

7. GitHub Pages Personal Website

  • Problem: Create online resume.
  • Implementation: Use username.github.io repo, push HTML/CSS or generated static site.
  • Deploy: Automatically via Pages or Actions.
  • Improvements: Use a static site generator, add blog.

8. Issue Tracking Workflow

  • Problem: Manage tasks with GitHub Issues & Projects.
  • Setup: Create labels, milestones, project board. Automate movement with Actions.
  • Workflow: Bug report -> triage -> assign -> fix -> PR -> close.
  • Improvements: Add issue forms (YAML templates).

9. Release Workflow with Semantic Versioning

  • Problem: Release a library with changelogs.
  • Tools: semantic-release, commitlint, conventional commits.
  • Workflow: On push to main, semantic-release analyzes commits, bumps version, creates tag and GitHub Release.
  • Improvements: Add release notes generation.

10. Versioned Software Project

  • Problem: Maintain a CLI tool with multiple versions.
  • Plan: Use Git Flow. main for stable, develop for next release. Tags for versions.
  • Workflow: Feature branches -> develop, release branch -> main.
  • Improvements: Support backport hotfixes with cherry-pick.

11. Professional Team Project (Monorepo)

  • Problem: Manage multi-service application.
  • Structure: /services/*, shared libraries. Sparse checkout for CI.
  • Workflow: Trunk-based, feature flags, CI builds only changed services.
  • Commands: git sparse-checkout, git bisect to find regressions.
  • Improvements: Use Dependabot for each ecosystem.

12. Automation Workflow with GitHub Actions

  • Problem: Automate repetitive tasks: label triage, stale issue closer.
  • Implementation: Workflows triggered by schedule or issue events.
  • Example: Auto-assign reviewer, close issues after 30 days of inactivity with comment.
  • Improvements: Use GitHub Script API for complex actions.

13. Fork-and-Pull Open Source Workflow (Detailed)

  • Problem: Contribute a major feature to upstream.
  • Steps: Fork, sync, feature branch, multiple PRs if needed, keep branch updated with upstream.
  • Commands: git rebase upstream/main, git push --force-with-lease on your fork branch.
  • Best Practices: Discuss design in an issue first.

14. Monorepo Setup with CI

  • Problem: Multiple frontend and backend services in one repo.
  • Structure: apps/web, apps/api, packages/shared. CI matrix to test only changed parts.
  • Commands: git diff --name-only HEAD~1 to detect changes.
  • Improvements: Use tools like Nx or Turborepo for orchestration.

15. Complete Production Workflow

  • Scenario: E-commerce site with microservices.
  • Git: GitHub Flow with environment branches (main for prod, staging pre-release).
  • CI: On PR: test, build containers.
  • CD: On merge to main: deploy to staging, smoke tests, manual approval, deploy to prod.
  • Secrets: Store cloud credentials in GitHub secrets.
  • Monitoring: Rollback with git revert and redeploy.
  • Summary: Apply Git/GitHub to real projects ranging from personal portfolio to enterprise CI/CD.
  • Key Takeaways: Choose a workflow that fits the project; automation reduces errors; real-world practice solidifies skills.
  • Common Mistakes: Overcomplicating early; ignoring security and testing.
  • Practice: Pick at least 3 projects and implement them fully.
  • Recommended Next Steps: Git command reference.

SPECIAL CHAPTER: Git Command Reference (Alphabetical)

This reference includes the most important commands with typical usage.

  • git add – Stage changes.
  • git add <file>, git add ., git add -p
  • Common options: -A (all), -u (update tracked), --intent-to-add (record empty file).
  • git branch – List, create, delete branches.
  • git branch, git branch <name>, git branch -d <name>, git branch -m <old> <new>
  • Options: -v (verbose), -r (remote), --merged, --no-merged.
  • git checkout – Switch branches or restore files (older; switch/restore preferred).
  • git checkout <branch>, git checkout -b <new-branch>, git checkout -- <file> (discard changes).
  • git cherry-pick – Apply specific commit to current branch.
  • git cherry-pick <hash>, git cherry-pick --continue after conflict.
  • git clone – Clone a repository.
  • git clone <url>, git clone --depth 1 (shallow), --branch <name>.
  • git commit – Record changes.
  • git commit -m "message", git commit --amend, git commit -a (skip staging tracked files).
  • git config – Get/set configuration.
  • git config --global user.name "Name", git config --list.
  • git diff – Show changes.
  • git diff, git diff --staged, git diff <branch>, git diff HEAD~1.
  • git fetch – Download objects and refs from remote.
  • git fetch origin, git fetch --all, git fetch --prune.
  • git init – Create new repo.
  • git init, git init --initial-branch=main.
  • git log – Show commit history.
  • git log --oneline --graph --all, --author=, --grep=, --since=.
  • git merge – Join branches.
  • git merge <branch>, git merge --no-ff, --abort.
  • git pull – Fetch and integrate.
  • git pull, git pull --rebase.
  • git push – Update remote refs.
  • git push origin main, git push -u origin <branch>, git push --tags, git push --force-with-lease.
  • git rebase – Reapply commits.
  • git rebase main, git rebase -i HEAD~3, --continue, --abort.
  • git reflog – Show log of HEAD changes.
  • git reflog, git reflog <branch>.
  • git reset – Reset current HEAD.
  • git reset --soft HEAD~1, --mixed, --hard, git reset <file>.
  • git restore – Restore working tree files (preferred over checkout).
  • git restore <file>, git restore --staged <file>, --source=<commit>.
  • git revert – Revert a commit.
  • git revert <hash>, --no-commit.
  • git rm – Remove files from working tree and index.
  • git rm <file>, git rm --cached <file>.
  • git show – Show various Git objects.
  • git show HEAD, git show <tag>, git show <hash>:path/file.
  • git stash – Stash changes.
  • git stash, git stash pop, git stash list, git stash push -m "msg", git stash -u.
  • git status – Working tree status.
  • git status, git status -s.
  • git switch – Switch branches (newer command).
  • git switch main, git switch -c new-branch, git switch - (previous branch).
  • git tag – Manage tags.
  • git tag, git tag -a v1.0 -m "message", git push origin v1.0, git tag -d v1.0.
  • git worktree – Manage multiple working trees.
  • git worktree add <path> <branch>, git worktree list, git worktree remove <path>.

*Professional Tip: Create aliases for frequently used commands to save time. For example, git lg for a pretty log.

Final Section: Roadmap, Resources, Career, Capstone

Git Learning Roadmap

  1. Basics: init, clone, add, commit, status, log, diff.
  2. Branching & merging, conflict resolution.
  3. Remote collaboration: fetch, pull, push, fork, pull requests.
  4. Rewriting history: amend, rebase, interactive rebase.
  5. Advanced: bisect, reflog, submodules, worktrees, hooks.
  6. DevOps integration: CI/CD, GitHub Actions.

GitHub Learning Roadmap

  1. Profile & repository setup, README, license.
  2. Issues, pull requests, code review.
  3. GitHub Actions for CI/CD.
  4. Project management with Projects & Discussions.
  5. Security: dependabot, code scanning, branch protection.

Official Documentation

Recommended Books

  • Pro Git by Scott Chacon and Ben Straub
  • Git for Teams by Emma Jane Hogbin Westby
  • Learn Git in a Month of Lunches by Rick Umali

Cheat Sheets

Open Source Contribution Guide

  • Start with good first issue labels.
  • Read CONTRIBUTING.md.
  • Communicate before coding.
  • Be respectful and patient.

Career Opportunities

  • Roles: Software Engineer, DevOps Engineer, SRE, QA, Technical Writer.
  • Certifications: GitHub Foundations, GitHub Actions, GitLab Certified Associate (GitLab). While not mandatory, they demonstrate knowledge.
  • Daily Professional Workflow:
  • git pull (or fetch) to start day.
  • Create feature branch.
  • Commit atomically with clear messages.
  • Push regularly.
  • Open PR, request review.
  • Address feedback.
  • Merge and delete branch.
  • Review teammates' PRs.

Final Capstone Project

Build a full-stack web application (or any software) using:

  • Git for version control with proper branching (GitHub Flow).
  • GitHub repository with README, issues, project board.
  • Conventional commits.
  • GitHub Actions for CI (lint, test) and CD (deploy to cloud).
  • Branch protection and code review.
  • Tagged releases with semantic versioning.
  • Contribute a fix to an open-source dependency using fork-PR workflow.

This capstone will touch every skill in this masterclass. Complete it, and you are truly a Git and GitHub professional.

You have completed the Git & GitHub Complete Masterclass 2026. Embrace version control as a daily habit, and you’ll build better software, collaborate effectively, and accelerate your career.