Git and GitHub Roadmap
Git is the version control tool behind almost every software project, and GitHub is where much of that code is hosted, reviewed and deployed. Every engineering role uses them daily, from front-end developers to data scientists and platform engineers. Interviewers rarely run a whole round on Git, but questions about merge versus rebase, undoing a pushed commit or resolving a conflict come up often, and fumbling them is a bad sign.
This roadmap takes you from your first commit to the topics experienced engineers are expected to handle: rewriting history safely, recovering lost work, bisecting bugs, hooks, CI with GitHub Actions and automation through the API. Each topic explains the idea, shows the commands and ends with an exercise. Core topics are needed by everyone, recommended ones by most working engineers, and optional ones are worth knowing about.
Do every exercise in a real terminal. Git is learned by breaking scratch repositories and fixing them, not by reading.
- Level
- Beginner to advanced
- Time
- 6–9 weeks at about 6 hours a week; the first three stages take about two weeks
- Scope
- 65 topics in 8 stages
- Before you start
- Basic use of a terminal: changing directories, listing files and running commands. The Shell and Bash Roadmap covers this.; A code editor and any small project you can put under version control
What you will be able to do
- Use Git daily with confidence: staging, committing, branching, merging and syncing with remotes.
- Explain how Git stores history and what branches, HEAD and tags really are.
- Choose between merge, rebase and squash, and undo any mistake with restore, revert, reset or the reflog.
- Contribute to team and open-source projects through forks, pull requests and code review.
- Write GitHub Actions workflows that test, build and deploy code securely.
- Automate GitHub with the CLI, APIs and webhooks, and secure repositories with GitHub's tools.
The roadmap at a glance
- Stage 1Version Control FoundationsBeginner · 1 week · 10 topics
- Stage 2Branching, Merging and TagsBeginner · 1 week · 8 topics
- Stage 3Remotes and GitHub EssentialsBeginner · 1 week · 6 topics
- Stage 4Collaboration on GitHubIntermediate · 1–2 weeks · 8 topics
- Stage 5Undoing Changes and Rewriting HistoryIntermediate · 1–2 weeks · 10 topics
- Stage 6Advanced Git Tools and InternalsAdvanced · 1–2 weeks · 8 topics
- Stage 7Automation with GitHub ActionsIntermediate · 1–2 weeks · 7 topics
- Stage 8The GitHub Platform and AutomationAdvanced · 1–2 weeks · 8 topics
Stage 1 Version Control Foundations
Goal. Install Git, create a repository, record changes in small commits and read the history.
What is Version Control? Core
Version control is a system that records every change to a set of files, along with who made it, when and why. You can go back to any earlier state, compare two points in time and work on several ideas in parallel without copying folders called final-v2-really-final.
Why use version control? It gives you a safety net for experiments, a shared source of truth for a team, an audit trail for every line, and the base that code review, CI and deployment tools build on. Even solo projects benefit: you stop being afraid of breaking things.
Its history matters too: early tools such as RCS tracked single files, CVS and Subversion added a central server, and Git, written for the Linux kernel, made every copy a full repository.
Practice. Write three sentences explaining to a non-programmer what problem version control solves.
Git vs Other VCS Recommended
Centralised systems such as Subversion keep the full history on one server; your machine holds only a working copy, so most operations need the network. Git is distributed: every clone contains the whole history, so commits, diffs, logs and branches are local and fast, and any clone can restore a lost server.
Git also treats branches as cheap pointers rather than directory copies, which is why branch-per-feature workflows became normal. Mercurial is a similar distributed tool with a smaller user base today. Perforce is still common for very large binary-heavy repositories such as games.
Keep Git and GitHub apart in your head: Git is the version control tool; GitHub is a hosting and collaboration service built around it, alongside GitLab and Bitbucket.
Practice. List two operations that need a network connection in Subversion but not in Git.
Installing Git Locally Core
Installation and setup take a few minutes. On macOS, run git --version; the system offers the command line tools, or use Homebrew. On Debian or Ubuntu use sudo apt install git; on Windows install Git for Windows, which includes Git Bash.
git --version
git config --global user.name "Asha Patel"
git config --global user.email "asha@example.com"
git config --global init.defaultBranch main
git config --global core.editor "code --wait"The name and email are stamped into every commit, so use the email linked to your GitHub account. Setting init.defaultBranch to main matches the modern default on GitHub.
Practice. Install Git, set your identity and default branch, and print your settings with git config --list.
git config and Local vs Global Config Core
git config reads and writes settings at three levels. System settings apply to every user on the machine, global settings live in ~/.gitconfig and apply to all your repositories, and local settings live in .git/config inside one repository. The most specific level wins, so a local setting overrides a global one.
git config --global pull.rebase true
git config --local user.email "asha@work.example"
git config --list --show-origin # where each value comes from
git config --global alias.lg "log --oneline --graph --all"A common use of the local level is a work email in work repositories. Aliases save typing for long commands you run daily.
Practice. Create an alias for a one-line graph log and set a different email in one test repository only.
What is a Repository Core
A repository is a project folder plus its full history. The history lives in a hidden .git directory holding every commit, branch and tag; the files you edit are the working directory, a checkout of one version.
You get a repository in two ways. git init turns the current folder into a new, empty repository. Cloning repositories with git clone copies an existing one, history included, and sets up a remote called origin pointing back to where it came from.
mkdir notes && cd notes && git init
git clone git@github.com:octo-org/website.git
git clone --depth 1 git@github.com:octo-org/website.git # shallow cloneDeleting .git deletes the history, so never do that by accident.
Practice. Run git init in a new folder, then list the contents of .git and identify HEAD, objects and refs.
Working Directory, Staging Area and Committing Changes Core
Git has three places a change can live. The working directory is the files on disk. The staging area, which Git also calls the index, holds a draft of your next commit. The repository holds commits. Unstaged changes are edits Git has noticed but you have not added; staged changes are queued for the next commit.
git status # what changed and where
git add app.py # stage a whole file
git add -p # stage selected hunks
git commit -m "Add login form validation"
git restore --staged app.py # unstage, keep the editStaging lets you split messy work into focused commits. Each commit is a snapshot of the whole project with a unique hash, author, message and parent pointer.
Practice. Edit two unrelated things in one file and use git add -p to commit them separately.
Commit Messages Core
A commit message is written for the person reading history later, often you. Use a short subject line of around 50 characters in the imperative mood ("Fix rounding in invoice totals"), a blank line, then a body that explains why the change was needed and anything surprising.
Fix rounding in invoice totals
Totals were rounded per line, so a 3-line invoice could be
out by a penny. Round once on the final sum instead.
Refs #412Many teams use Conventional Commits prefixes such as feat: and fix: so tools can build changelogs. Avoid messages like "wip" or "stuff"; they make history useless for debugging.
Practice. Rewrite five vague commit messages from an old project in the subject plus body format.
.gitignore Core
A .gitignore file lists patterns Git should not track: build output, dependency folders, logs, editor files and, above all, secrets such as .env. Commit the file so the whole team shares it.
node_modules/
dist/
*.log
.env
!.env.exampleA trailing slash matches directories, * matches within a name, and ! re-includes a file. Ignore rules only affect untracked files: if a file is already committed, you must run git rm --cached file to stop tracking it. Personal patterns, such as your editor's files, belong in a global ignore file set with core.excludesFile.
Practice. Add a .gitignore to a project, accidentally commit a log file, then stop tracking it without deleting it.
Viewing Commit History Core
git log shows commits newest first. Its options turn it into a search tool, and these git log options are worth memorising.
git log --oneline --graph --all # compact branch graph
git log -p app.py # patches touching a file
git log --author="Asha" --since="2 weeks ago"
git log -S "calculateTax" # commits adding or removing a string
git log main..feature # commits on feature not on main
git show 3f9c2a1 # one commit in full
git blame -L 40,60 app.py # who last changed each lineThe -S search, sometimes called the pickaxe, is how you find when a function appeared or vanished. git blame is for context, not blame: follow the commit to read why a line exists.
Practice. Find the commit that first introduced a specific function name in any open-source repository you clone.
Viewing Diffs Core
git diff shows line changes. Which two things it compares depends on the arguments.
git diff # working directory vs staging area
git diff --staged # staging area vs last commit
git diff HEAD~3 HEAD # between commits
git diff main..feature # between branches (tips)
git diff main...feature # feature's changes since it forked
git diff --stat # summary of files changedThe three-dot form is what a pull request shows: changes on the branch since the merge base, ignoring later work on main. Configure a difftool or use your editor's diff view for big changes, but be fluent in the terminal output too.
Practice. On a repository with two branches, compare the output of the two-dot and three-dot diff and explain the difference.
Stage 2 Branching, Merging and Tags
Goal. Work on parallel branches, merge them, resolve conflicts and mark releases with tags.
Branching Basics Core
A branch is a movable pointer to a commit. Creating one costs almost nothing, so you make a branch for every feature or fix and keep main releasable.
git branch # list local branches
git switch -c feature/login # creating branch and switching
git switch main # checkout branch (modern form)
git branch -m old-name new-name # renaming branch
git branch -d feature/login # deleting branch (merged only)
git branch -D spike/test # force delete
git push origin --delete feature/logingit checkout still works for switching branches, but it also restores files, which confused people. Git added git switch for branches and git restore for files; prefer them in new habits.
Practice. Create, rename and delete a branch locally and on your GitHub remote.
HEAD and Detached HEAD Core
HEAD is Git's answer to "where am I?". Normally it points to a branch name, and the branch points to a commit; when you commit, the branch moves forward and HEAD follows.
If you check out a commit hash or a tag directly, HEAD points straight at a commit. That is a detached HEAD state. You can look around and even commit, but no branch records those commits, so once you switch away they are only reachable through the reflog.
git switch --detach v1.2.0 # inspect an old release
git switch -c hotfix/1.2.1 # keep work: give it a branchHEAD~1 means the parent of HEAD, and HEAD~3 three commits back. HEAD^2 is the second parent of a merge commit.
Practice. Detach HEAD at an old commit, make a commit, switch back to main, then recover the commit onto a new branch.
Merging Basics Core
Merging joins the history of one branch into another. Switch to the branch that should receive the work, then merge the other one in.
git switch main
git merge feature/login
git merge --no-ff feature/login # always create a merge commit
git merge --abort # give up during a conflictGit finds the merge base, the last common ancestor, and combines the changes made on each side since then. If both sides changed different lines, the result is automatic. A merge commit has two parents and records that the branches came together, which keeps the true shape of history.
Practice. Create two branches that edit different files, merge both into main and view the graph.
Fast-Forward vs Non-FF Core
If main has not moved since you branched, Git can merge by simply sliding the main pointer forward to your branch tip. That is a fast-forward: no merge commit, and history stays a straight line.
If both branches have new commits, a fast-forward is impossible and Git creates a merge commit with two parents. You can also force a merge commit with --no-ff to keep a visible record that a feature branch existed, or refuse anything but a fast-forward with --ff-only.
git config --global pull.ff only # never create surprise merges on pull
git merge --ff-only origin/mainTeams choose based on whether they value a linear log or an explicit record of feature boundaries.
Practice. Reproduce both a fast-forward and a non-fast-forward merge and compare the graphs.
Handling Conflicts Core
A conflict happens when both sides changed the same lines, or one side edited a file the other deleted. Git stops, marks the file and waits for you.
<<<<<<< HEAD
const limit = 50;
=======
const limit = 100;
>>>>>>> feature/limitsEdit the file into the correct final version, which may combine both sides, remove the markers, run the tests, then git add the file and git commit (or git rebase --continue during a rebase). Use your editor's merge view for large conflicts. Setting merge.conflictStyle to zdiff3 also shows the original base text, which makes intent clearer. Small, frequently merged branches are the best way to avoid conflicts in the first place.
Practice. Create a deliberate conflict between two branches and resolve it using the diff3 style.
Git Stash Basics Core
A stash shelves uncommitted changes so you can switch context with a clean working directory, for example to fix an urgent bug, then bring the work back.
git stash push -m "half-done search filter"
git stash push -u # include untracked files
git stash list
git stash pop # reapply latest and drop it
git stash apply stash@{1}
git stash drop stash@{1}Stashes are local and easy to forget, so treat them as short-term. For anything you will not return to within a day, commit to a work-in-progress branch instead. A pop that conflicts keeps the stash so you do not lose it.
Practice. Stash a change, switch branches and make a commit, then return and pop the stash.
Branch Naming Recommended
Branch names are read in pull requests, CI logs and deploy tools, so make them descriptive and consistent. A common convention is a type prefix plus a short slug, often with a ticket number: feature/1234-csv-export, fix/login-timeout, chore/upgrade-node.
Use lowercase and hyphens, avoid spaces and personal names, and keep them short. Long-lived branches such as main, develop or release/2.4 should be protected on GitHub. Delete feature branches after merging; GitHub can do this automatically.
Practice. Write a branch naming guide of five rules for a small team and rename two of your branches to follow it.
Tagging Core
A tag is a fixed name for one commit, used for releases. Lightweight tags are bare pointers. Annotated tags are stored objects with a tagger, date and message and can be signed; use them for releases.
git tag -a v1.4.0 -m "Release 1.4.0"
git tag # managing tags: list
git tag -d v1.4.0-rc1 # delete locally
git push origin v1.4.0 # pushing tags one at a time
git push origin --tags
git switch --detach v1.4.0 # checkout tags to inspectTags are not pushed by default. Checking out a tag gives a detached HEAD because tags never move. Semantic versioning, MAJOR.MINOR.PATCH, is the usual naming scheme.
Practice. Tag three releases in a toy project, push them, then delete a mistaken tag both locally and on the remote.
Stage 3 Remotes and GitHub Essentials
Goal. Publish repositories on GitHub, authenticate securely and sync work between machines.
GitHub Essentials Core
GitHub hosts Git repositories and adds collaboration features: pull requests, issues, Actions, Pages and more. Creating account access is free; pick a professional username because it appears in every URL and commit link.
Setting up profile details means a real name or handle, a photo, a short bio and, importantly, two-factor authentication. Your profile README lives in a repository that shares your username, and its README.md shows on your profile page; use it for a short introduction and pinned projects rather than badges and counters.
Learn the GitHub interface: the Code tab with branch selector and file browser, the history view, Issues, Pull requests, Actions, Settings, and the . key shortcut that opens a web editor.
Practice. Create or tidy your GitHub account, enable two-factor authentication and write a five-line profile README.
Authentication with SSH Keys and Tokens Core
GitHub no longer accepts account passwords for Git over HTTPS. Use either SSH keys or HTTPS with a personal access token, usually stored by a credential manager.
ssh-keygen -t ed25519 -C "asha@example.com"
cat ~/.ssh/id_ed25519.pub # paste into GitHub settings
ssh -T git@github.com # test the connectionThe private key never leaves your machine; protect it with a passphrase and an SSH agent. For tokens, prefer fine-grained personal access tokens scoped to specific repositories with an expiry date. The GitHub CLI's gh auth login can set either method up for you. You can also sign commits with an SSH or GPG key so GitHub shows them as verified.
Practice. Generate an ed25519 key, add it to GitHub and push to a repository over SSH.
Creating Repositories Core
Create a repository on GitHub from the web interface or with gh repo create. Decide early: private vs public. Public repositories are visible to everyone and are how open source and portfolios work; private ones are visible only to people you add. Never assume private means safe for secrets.
A project README is the front door: what the project does, how to install and run it, how to test it, and how to contribute. It is written in Markdown, GitHub's formatting language for READMEs, issues and comments.
# Invoice CLI
Creates PDF invoices from a CSV file.
## Usage
```bash
invoice build data.csv --out invoices/
```
- [x] CSV import
- [ ] Email deliveryRepository management starts here: add a licence file and a .gitignore at creation time; GitHub offers templates for both.
Practice. Create a public repository with a README, licence and .gitignore, and push an existing local project to it.
Git Remotes Core
A remote is a named URL for another copy of the repository. origin is the default name for the one you cloned from. Managing remotes is a few commands.
git remote -v
git remote add origin git@github.com:asha/invoice-cli.git
git remote add upstream git@github.com:octo-org/invoice-cli.git
git remote set-url origin git@github.com:asha/invoice.git
git remote rename origin github
git remote remove oldGit keeps remote-tracking branches such as origin/main: read-only bookmarks of where each remote branch was at your last fetch. A local branch can track one of them, so git status tells you if you are ahead or behind.
Practice. Add a second remote to a repository and push the same branch to both.
Pushing and Pulling Changes Core
Pushing/pulling changes moves commits between your repository and a remote. git push uploads your branch; the first time, set its upstream with -u. git pull is two steps in one: git fetch then a merge or rebase.
git push -u origin feature/export
git fetch origin # fetch without merge
git log HEAD..origin/main # what arrived
git pull --rebase # replay my commits on top
git fetch --prune # drop deleted remote branchesFetching first lets you inspect incoming work before it touches your branch. If the remote has commits you do not have, Git rejects your push; pull or rebase, resolve anything that conflicts, then push again. Do not reach for force push as the first fix.
Practice. Make conflicting commits from two clones of one repository and practise fetch, inspect, rebase and push.
Forking vs Cloning Core
Cloning makes a local copy of a repository. Forking makes a server-side copy under your own GitHub account. You fork when you cannot push to the original, which is the normal situation for open-source contributions.
gh repo fork octo-org/parser --clone
git remote -v # origin = your fork, upstream = original
git fetch upstream
git switch main && git merge --ff-only upstream/main
git push origin mainYour fork falls behind the original over time, so sync it regularly from upstream before starting a new branch. Inside a company, teams usually clone a shared repository and push branches to it directly instead of forking.
Practice. Fork a small open-source project, keep it in sync with upstream and push a branch to your fork.
Stage 4 Collaboration on GitHub
Goal. Propose, review and merge changes through pull requests and organise work with issues and projects.
Pull Requests Core
A pull request (PR) asks to merge one branch into another and gives the team a place to discuss and review it. Push your branch, open the PR, and CI runs against it.
Good PR guidelines: keep PRs small and about one thing; write a description covering what changed, why, how it was tested and screenshots for UI work; link the issue with Closes #123 so it closes on merge; and open a draft PR early when you want feedback on direction.
gh pr create --fill --draft
gh pr checks
gh pr ready
gh pr merge --squash --delete-branchWhen a PR is merged, GitHub offers three buttons: a merge commit, squash and merge, or rebase and merge. Repositories can enable only the ones the team agrees on.
Practice. Open a draft PR with a full description and a linked issue, then mark it ready and merge it.
Code Reviews Core
Code reviews catch bugs, spread knowledge and keep a codebase consistent. As a reviewer, read the description first, check correctness and tests before style, comment on specific lines, and say clearly what blocks approval versus what is optional. Use suggestion blocks for small fixes the author can apply in one click.
As an author, review your own diff before asking, reply to every comment, and push follow-up commits rather than force pushing mid-review so reviewers can see what changed.
Mentions with @name or @org/team notify people; reactions acknowledge comments without noise; saved replies store text you type often. A CODEOWNERS file requests reviews from the right people automatically. The Code Review Roadmap goes deeper.
Practice. Review a classmate's or open-source PR, leaving one blocking comment, one suggestion and one question.
PR from a Fork and Contribution Guidelines Core
To contribute to a project you do not own, fork it, clone your fork, create a branch from the latest upstream main, push to your fork and open a PR against the original. Enable "allow edits by maintainers" so they can make small fixes.
Before writing code, read the project's contribution guidelines, usually in CONTRIBUTING.md: how to set up, coding style, test commands, commit rules, and whether to open an issue first. Also read the code of conduct. Issues labelled "good first issue" are a good start.
Workflows from forks run with limited permissions and without your secrets, which protects maintainers from malicious PRs. Expect a maintainer to approve the first CI run.
Practice. Find a good first issue in a project you use, comment to claim it and submit a PR from your fork.
Issues and Issue Management Core
Issues track bugs, tasks and ideas. A good bug report includes steps to reproduce, expected and actual behaviour, and environment details. Issue templates and issue forms in .github/ISSUE_TEMPLATE make reporters supply that information.
Issue management keeps the list useful: triage new issues, close duplicates with a link, assign owners and milestones, and use sub-issues for larger pieces of work. Labelling issues/PRs with a small, agreed set such as bug, enhancement, needs-triage and good first issue lets people filter quickly.
Reference issues from commits and PRs: Fixes #88 in a merged PR closes the issue automatically, and any #88 creates a cross-link.
Practice. Add a bug report issue form and five labels to a repository, then triage three issues.
GitHub Projects and Project Planning Recommended
GitHub Projects are planning boards built from issues and pull requests across repositories. Each project can have several views: a table, Kanban boards with columns such as Todo, In progress and Done, and a timeline view that teams use for roadmaps.
Custom fields such as priority, size, iteration and target date let you sort and group work. Built-in workflows can move an item to Done when its PR merges, so the board stays honest without manual updates.
For project planning, keep issues small enough to finish in a few days, group them under milestones or iterations, and review the board in a regular team meeting. A board nobody updates is worse than none.
Practice. Create a project with table, board and roadmap views for one of your repositories and plan two weeks of work.
Discussions, Wikis and Documentation Optional
GitHub Discussions is a forum attached to a repository for questions, ideas and announcements that are not actionable tasks. Moving open-ended questions there keeps the issue list focused. Answers can be marked as accepted, like a Q&A site.
GitHub Wikis give each repository a simple set of Markdown pages, stored in a separate Git repository. They suit loose notes, but because they are not reviewed through pull requests, many teams prefer documentation in a docs/ folder next to the code, published with GitHub Pages.
Whatever you choose, documentation should live where contributors will update it as the code changes.
Practice. Enable Discussions on a repository, move one question-style issue there and add a docs folder with a getting started page.
Organizations, Teams and Collaborators Recommended
On a personal repository you add collaborators, who get write access. GitHub Organizations are shared accounts for companies and open-source groups; they hold many repositories with central billing, security policies and member management.
Collaborators/members: organisation members belong to the organisation, while outside collaborators are given access to specific repositories only. Teams within organization accounts group members, can be nested, and receive a permission level per repository such as read, triage, write, maintain or admin. Mentioning a team requests review from all of them.
Follow least privilege: give write access to the teams that need it, keep admins few, and require two-factor authentication for every member.
Practice. Create a free organisation, add two teams with different permissions and give one team write access to a repository.
Working in a Team Core
A branching workflow is the agreement on how work flows into production. GitHub flow is the common default: short-lived branches off main, a PR for each, CI must pass, review, merge, deploy. Trunk-based development pushes branches to live for hours rather than days, using feature flags to hide unfinished work. Git flow adds develop, release and hotfix branches; it suits versioned products with scheduled releases more than web services.
Protect main with branch protection rules or rulesets: require PRs, passing status checks, approvals and up-to-date branches, and block force pushes. A merge queue tests PRs against the latest main in order, so busy repositories do not break.
Practice. Write down the workflow your team (or an imagined team) uses and configure matching rules on main.
Stage 5 Undoing Changes and Rewriting History
Goal. Undo any mistake safely, clean up history before review and recover work that seems lost.
Undoing Changes Core
Pick the undo tool by where the mistake lives.
| Situation | Command |
|---|---|
| Discard edits to a file | git restore file |
| Unstage a file | git restore --staged file |
| Fix the last commit | git commit --amend |
| Undo local commits | git reset |
| Undo a pushed commit | git revert |
The key rule: rewriting commits is fine while they exist only on your machine or your own branch. Once others may have based work on them, add a new commit that reverses the change instead. git restore on unstaged edits is one of the few commands that can lose work permanently, because those edits were never committed.
Practice. Make one mistake of each type in the table and undo it with the matching command.
git revert Core
git revert creates a new commit that applies the inverse of an earlier one. History is not rewritten, so it is safe on shared branches such as main, and it leaves a clear record that the change was backed out.
git revert 3f9c2a1
git revert --no-edit HEAD~2..HEAD # several commits
git revert -m 1 9ab31e0 # a merge commit, keep parent 1Reverting a merge needs -m to say which parent is the mainline. Beware: if you later want to re-merge that branch, Git thinks its commits are already in, so you must revert the revert first. GitHub's PR page has a Revert button that opens a PR doing exactly this.
Practice. Revert a bad commit on main through a pull request, then revert the revert.
git reset: --soft, --mixed and --hard Core
git reset moves the current branch pointer to another commit. Its mode decides what happens to the staging area and working directory.
--soft: move the branch only. The undone commits' changes stay staged, ready to recommit.--mixed(the default): move the branch and reset the staging area. Changes stay in your files, unstaged.--hard: move the branch and overwrite staging and working directory. Uncommitted work is gone.
git reset --soft HEAD~3 # squash last 3 commits into one
git reset HEAD~1 # undo last commit, keep edits
git reset --hard origin/main # match the remote exactlyUse reset only on commits you have not shared. Committed work removed by --hard can still be recovered through the reflog for a while.
Practice. Use each reset mode on a scratch repository and describe the state of git status after each.
git commit --amend Core
git commit --amend replaces the last commit with a new one that combines it with whatever is staged now. Use it to fix a typo in the message, add a forgotten file or drop a debug print.
git add forgotten_test.py
git commit --amend --no-edit
git commit --amend -m "Fix rounding in invoice totals"Amending creates a new commit with a new hash; the old one is not edited in place. If you already pushed the original, pushing the amended one needs a force push, which is fine on your own feature branch and wrong on a shared branch.
Practice. Commit without a test file, then amend the commit to include it and compare the hashes.
Rebase Core
git rebase replays your branch's commits one by one on top of another commit, creating new commits with new hashes. The result looks as if you started your work from the latest main.
git switch feature/export
git fetch origin
git rebase origin/main
# fix conflicts, then
git add . && git rebase --continue
git rebase --abort # back to where you startedLinear vs non-linear history is the trade-off behind merge strategies. Merging keeps a non-linear graph that shows exactly what happened; rebasing gives a linear history that is easier to read and bisect. The golden rule: do not rebase commits other people already have, because their copies will diverge from yours.
Practice. Rebase a feature branch onto an updated main, resolving at least one conflict on the way.
Interactive Rebase, Squash and Clean Git History Recommended
Interactive rebase lets you edit a series of commits before you share them: reorder, reword, combine or drop them.
git rebase -i HEAD~4
# pick a1b2c3 Add CSV parser
# fixup d4e5f6 typo
# reword 789abc Add export command
# drop 0fedcb debug loggingSquash combines a commit into the one above it and keeps both messages for editing; fixup does the same and discards the message. Create fixups as you go with git commit --fixup a1b2c3, then run git rebase -i --autosquash main.
A clean Git history has commits that each build, pass tests and do one thing. That makes review, revert and bisect easy. Many teams skip this and squash-merge the whole PR into a single commit instead.
Practice. Make six messy commits, then use interactive rebase with autosquash to turn them into two clean ones.
git push --force Core
After a rebase or amend, your local branch and the remote branch have diverged, and a normal push is rejected. git push --force overwrites the remote branch with yours, discarding any commits on the remote that you do not have.
git push --force-with-lease origin feature/exportUse --force-with-lease instead. It only overwrites if the remote is still where your last fetch saw it, so it refuses if a teammate pushed in the meantime. Never force push to main or other shared branches; branch protection should block it anyway. If you force pushed over someone's work, their commits are still in their clone and in the reflog of whoever had them.
Practice. Simulate a teammate's push to your branch and see --force-with-lease refuse to overwrite it.
Git Reflog Core
The reflog is a local log of every position HEAD and each branch has had: commits, checkouts, resets, rebases and merges. It is how you recover from almost any mistake.
git reflog
# 4c1d2e0 HEAD@{0}: reset: moving to HEAD~3
# 9f8e7d6 HEAD@{1}: commit: Add export command
git branch rescue 9f8e7d6 # or
git reset --hard HEAD@{1}Commits that no branch points to are not deleted at once; they stay until garbage collection, by default for weeks. The reflog is private to your clone and is not pushed, and it cannot recover changes that were never committed or stashed. Commit often and you can rarely lose work.
Practice. Run git reset --hard to throw away three commits, then recover them with the reflog.
Cherry Picking Commits Recommended
Cherry-pick copies the changes of one or more existing commits onto your current branch as new commits. The classic use is backporting a fix from main to a release branch.
git switch release/2.3
git cherry-pick -x 3f9c2a1 # -x records the source hash
git cherry-pick a1b2c3..d4e5f6
git cherry-pick --continue # after resolving a conflictBecause the copies get new hashes, Git does not know they are the same change, which can cause duplicate-looking commits or conflicts at the next merge. Use it for targeted fixes, not as a regular way to move features between branches.
Practice. Backport a single bug-fix commit from main to a release branch with cherry-pick -x.
Rewriting History at Scale Optional
Sometimes you must rewrite a whole repository's history: remove a leaked password, strip a huge file or extract a subdirectory into its own repository. git filter-branch did this for years but is slow and easy to misuse, and Git's own documentation now warns against it. The recommended tool is git filter-repo, a separate install.
git filter-repo --path secrets.env --invert-paths
git filter-repo --subdirectory-filter services/billingEvery commit hash after the change point changes, so all collaborators must re-clone. For a leaked secret, rotate the credential first: once pushed, assume it is compromised, whatever you do to the history.
Practice. In a throwaway repository, commit a fake secret several commits back and remove it from all history with filter-repo.
Stage 6 Advanced Git Tools and Internals
Goal. Debug with bisect, manage large and multi-repository projects, automate checks with hooks and explain how Git stores data.
Git Internals: Objects and References Recommended
Git is a content-addressed store. There are four object types: blobs hold file contents, trees hold directory listings pointing to blobs and other trees, commits point to one tree plus parent commits and metadata, and annotated tags point to an object with a message. Each object is named by a hash of its content, SHA-1 by default with SHA-256 supported for new repositories.
git cat-file -p HEAD # the commit object
git cat-file -p HEAD^{tree} # its tree
cat .git/HEAD # ref: refs/heads/mainBranches and tags are references: small files containing a commit hash. That is why branches are cheap and why identical files are stored only once.
Practice. Use git cat-file to walk from HEAD to the contents of one file by hand.
Git Bisect Recommended
git bisect finds the commit that introduced a bug by binary search. You mark one good and one bad commit; Git checks out the midpoint and you report whether it is good or bad, halving the range each time. A thousand commits need about ten steps.
git bisect start
git bisect bad # current commit is broken
git bisect good v2.1.0
git bisect run ./test-bug.sh # automate with an exit code
git bisect resetWith run, your script exits 0 for good and non-zero for bad, and Git does the whole search. This is why commits that each build and pass tests are valuable.
Practice. Introduce a bug ten commits back in a toy project and find it with git bisect run.
Git Worktree Optional
A worktree is an extra working directory attached to the same repository. You can have main checked out in one folder and a feature branch in another, sharing one object store, without stashing or cloning again.
git worktree add ../app-hotfix hotfix/1.2.1
git worktree list
git worktree remove ../app-hotfixWorktrees help when you review a PR while a long build runs, or when several coding agents work on separate branches of one repository at the same time. One branch can be checked out in only one worktree at a time.
Practice. Create a worktree for a review branch, run its tests there while editing main elsewhere, then remove it.
Submodules Optional
A submodule embeds another Git repository inside yours at a specific commit. The parent repository records only the URL, in .gitmodules, and the pinned commit hash.
git submodule add git@github.com:octo-org/shared-ui.git vendor/ui
git clone --recurse-submodules git@github.com:octo-org/app.git
git submodule update --init --recursive
git submodule update --remote vendor/ui # move to latestSubmodules are a common source of confusion: forgetting to initialise them, or committing a pointer to a commit nobody pushed. Prefer a package manager for shared libraries. Use submodules when you must pin exact source from another repository, such as firmware or vendored code.
Practice. Add a submodule to a project, update it to a newer commit and clone the parent with submodules.
Git LFS Optional
Git stores every version of every file in full history, so large binaries such as videos, design files or datasets bloat clones quickly. Git Large File Storage replaces them in the repository with small pointer files and keeps the real content on a separate server.
git lfs install
git lfs track "*.psd"
git add .gitattributes design.psd
git commit -m "Track design files with LFS"GitHub supports LFS with storage and bandwidth quotas. Set it up before large files enter history; moving existing files needs a history rewrite with git lfs migrate. For machine learning data, dedicated data versioning tools are often a better fit.
Practice. Track one binary file type with LFS and confirm the repository stores only a pointer.
Git Attributes Optional
A .gitattributes file assigns behaviour to paths. The most important use is line endings: Windows uses CRLF and other systems LF, and mixed endings create noisy diffs.
* text=auto eol=lf
*.bat text eol=crlf
*.png binary
package-lock.json -diff linguist-generated
*.psd filter=lfs diff=lfs merge=lfs -textAttributes also mark files as binary, set merge drivers, hide generated files from GitHub diffs and language statistics, and connect LFS. Commit the file so every clone behaves the same.
Practice. Add a .gitattributes that normalises line endings and marks lock files as generated.
Git Patch Optional
A patch is a commit or diff saved as text so it can travel without a shared remote. The Linux kernel and some other projects still review patches by email.
git format-patch -2 -o outgoing/ # last two commits as files
git am outgoing/*.patch # apply as commits
git diff > quick.patch
git apply --check quick.patch # test before applyingformat-patch keeps author, date and message, and git am recreates the commits. git apply applies a plain diff to your working directory without committing. Patches are also handy for moving work between machines that cannot reach the same remote.
Practice. Export two commits as patches and apply them to a fresh clone with git am.
Git Hooks Recommended
Git hooks are scripts Git runs at points in its workflow. A non-zero exit from a "pre" hook stops the action.
Client vs server hooks: client hooks run on your machine and include pre-commit (lint and format staged files), commit-msg (check the message format), pre-push (run quick tests) and post-checkout (refresh dependencies after switching). Server hooks such as pre-receive and post-update run on the hosting server; GitHub does not let you install them, so use branch rules and Actions instead.
#!/bin/sh
# .git/hooks/commit-msg
grep -qE '^(feat|fix|docs|chore): ' "$1" || {
echo "Use a type prefix such as fix:"; exit 1; }Hooks in .git/hooks are not committed. Share them with core.hooksPath or a framework such as pre-commit or Husky, and remember anyone can skip them with --no-verify, so CI must still enforce the rules.
Practice. Write a commit-msg hook that rejects messages without a type prefix and share it through core.hooksPath.
Stage 7 Automation with GitHub Actions
Goal. Write CI workflows that test, build and deploy code on every push and pull request.
GitHub Actions and YAML Syntax Core
GitHub Actions runs automated workflows defined in YAML files under .github/workflows/. A workflow has triggers, one or more jobs, and steps inside each job. Steps either run shell commands or use a reusable action.
name: CI
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
- run: npm ci
- run: npm testYAML syntax basics matter: indentation with spaces defines structure, key: value maps, - starts a list item, and | starts a multi-line string. Most broken workflows are indentation errors.
Practice. Add a CI workflow to a project that installs dependencies and runs the tests on every pull request.
Workflow Triggers Core
The on key decides when a workflow runs.
on:
push:
branches: [main]
paths: ["src/**"]
pull_request:
workflow_dispatch: # manual Run button
schedule:
- cron: "0 6 * * 1" # 06:00 UTC every Monday
release:
types: [published]Branch and path filters stop unrelated changes from running expensive jobs. Scheduled workflows use cron syntax in UTC and run on the default branch; they are useful for nightly tests, dependency checks or stale issue clean-up. workflow_call makes a workflow reusable by other workflows.
Practice. Add a manual trigger and a weekly schedule to a workflow and run it both ways.
Workflow Runners Core
A runner is the machine that executes a job. GitHub-hosted runners are fresh virtual machines with Linux, Windows or macOS images and common tools preinstalled; each job gets a clean one. Self-hosted runners are your own machines, used for special hardware, private networks or cost reasons.
Jobs run in parallel by default; use needs to order them. A matrix runs one job across combinations, such as three language versions on two operating systems.
strategy:
matrix:
python: ["3.11", "3.12"]
os: [ubuntu-latest, windows-latest]
runs-on: ${{ matrix.os }}Never attach self-hosted runners to public repositories: anyone opening a PR could run code on them.
Practice. Add a test matrix across two language versions and make a deploy job that needs the test job.
Workflow Context, Secrets and Env Vars Core
Expressions in ${{ }} read contexts: github (event, ref, SHA, actor), env, secrets, matrix, steps and needs outputs. Use them in if: conditions, for example running a deploy only on main.
Secrets and env vars are set at repository, environment or organisation level. Secrets are encrypted, masked in logs and not passed to workflows triggered from forks. Environments such as production can require approval before a job that uses their secrets runs.
if: github.ref == 'refs/heads/main'
environment: production
env:
API_URL: ${{ vars.API_URL }}
TOKEN: ${{ secrets.DEPLOY_TOKEN }}Prefer OpenID Connect to long-lived cloud keys: the workflow exchanges a short-lived token with your cloud provider instead of storing a password.
Practice. Store a secret, use it in a step that runs only on main, and confirm it is masked in the log.
Caching Dependencies and Storing Artifacts Recommended
Caching dependencies saves minutes per run. Many setup actions cache for you with one option; for anything else use actions/cache with a key built from the lock file hash, so the cache refreshes only when dependencies change.
- uses: actions/setup-node@v4
with: { node-version: 20, cache: npm }
- run: npm ci && npm run build
- uses: actions/upload-artifact@v4
with:
name: dist
path: dist/Storing artifacts is different: artifacts are outputs of a run, such as build bundles, test reports or coverage files, kept for a set number of days and downloadable from the run page or by a later job. Caches speed things up; artifacts pass results on.
Practice. Add dependency caching to a workflow, compare run times, and upload the test report as an artifact.
Marketplace Actions and Workflow Security Recommended
Marketplace actions are reusable steps published by GitHub and the community: checkout, language setup, cloud logins, deploy tools and more. Each one is code you run with access to your repository, so choose well-maintained actions from verified creators.
Pin third-party actions to a full commit SHA, not a moving tag, so a compromised release cannot change what runs. Set least-privilege permissions for the automatic token at the top of each workflow.
permissions:
contents: read
pull-requests: writeBe careful with pull_request_target, which runs with secrets in the context of the base repository; never check out and run untrusted PR code inside it. Keep Dependabot updating your action versions.
Practice. Audit one workflow: pin its actions to SHAs and add a minimal permissions block.
Workflow Status and Debugging Core
Every run reports a workflow status of queued, in progress, success, failure, cancelled or skipped. Statuses appear on commits and PRs as checks, and branch rules can require specific checks to pass before merging. Add a status badge to the README so visitors see whether main is green.
When a run fails, read the first failing step's log rather than the last line. Re-run failed jobs, enable debug logging with the ACTIONS_STEP_DEBUG secret, and reproduce locally where possible. Use concurrency to cancel older runs of the same branch, and timeout-minutes so a hung job does not burn your minutes.
Practice. Make a workflow fail on purpose, diagnose it from the logs, fix it and require the check on main.
Stage 8 The GitHub Platform and Automation
Goal. Script GitHub, publish sites and packages, keep repositories secure and know the wider platform.
GitHub CLI Recommended
The GitHub CLI, gh, brings pull requests, issues, releases, Actions and more to the terminal, and is easy to use in automation.
gh auth login
gh repo clone octo-org/api
gh pr list --author "@me"
gh pr checkout 128
gh issue create --title "Export fails on empty file" --label bug
gh run watch
gh api repos/octo-org/api/releases --jq '.[0].tag_name'gh pr checkout fetches a PR, even from a fork, into a local branch for testing. gh api calls any REST or GraphQL endpoint with your stored credentials, which makes quick scripts trivial.
Practice. Open, check out, review and merge a PR using only the gh command.
REST API and GraphQL API Recommended
The GitHub API comes in two forms and exposes almost everything. The REST API has a URL per resource, such as a repository's issues or a PR's reviews, with JSON responses and pagination. The GraphQL API lets you request exactly the fields you need, across related objects, in one call.
gh api repos/octo-org/api/issues -f title="Flaky test" -f body="See run 512"
gh api graphql -f query='
query { viewer { login repositories(first: 5) { nodes { name } } } }'Both use tokens, and both have rate limits; check the response headers and back off when close. For use in automation, prefer a GitHub App or the workflow's built-in token over a personal token, so actions are not tied to one person's account.
Practice. Write a script that lists all open PRs older than a week across your repositories using either API.
Webhooks, GitHub Apps and OAuth Apps Optional
Webhooks send an HTTP POST to your server when events happen: a push, a new issue, a PR review. Verify the signature header with your webhook secret before trusting the payload, and respond quickly, doing slow work in a background job.
When creating apps for GitHub, choose the type. GitHub Apps act as themselves, are installed on chosen repositories with fine-grained permissions, get short-lived tokens and receive webhooks. OAuth Apps act on behalf of a user with that user's access, mainly for "sign in with GitHub". GitHub recommends Apps for most integrations.
The GitHub Marketplace lists published apps and actions, such as CI services, code quality tools and project bots, that organisations can install.
Practice. Register a small GitHub App that comments on new issues, receiving events through a webhook.
GitHub Pages and Deploying Static Websites Recommended
GitHub Pages hosts static sites, HTML, CSS and JavaScript with no server code, straight from a repository. It suits portfolios, project documentation and blogs.
The modern approach is deploying static websites with an Actions workflow: build with one of the static site generators such as Jekyll, Hugo, Astro or Eleventy, then publish with the official Pages deploy action. You can also publish a branch or docs/ folder directly.
Custom domains are set in the repository's Pages settings with a CNAME DNS record for subdomains or A records for apex domains; enforce HTTPS once the certificate is issued. Pages sites are public on free plans, so do not publish anything private.
Practice. Publish a portfolio site with GitHub Pages using a workflow and a static site generator.
GitHub Releases and Packages Recommended
GitHub Releases turn a tag into a release page with notes and downloadable files such as binaries. GitHub can generate release notes from merged PRs, grouped by label.
gh release create v1.5.0 --generate-notes dist/*.tar.gzGitHub Packages is a registry for container images, npm, Maven, NuGet and RubyGems packages, linked to repositories and using the same permissions. A common workflow builds and pushes a Docker image to the container registry whenever a release is published, authenticating with the workflow token.
Practice. Automate a release workflow that tags, builds and attaches an artefact when you push a version tag.
GitHub Security Core
GitHub security features protect code and supply chain. Dependabot alerts warn about vulnerable dependencies and Dependabot can open update PRs. Secret scanning detects committed credentials, and push protection blocks them before they land. Code scanning runs static analysis such as CodeQL and shows findings on PRs.
Account and repository hygiene matter as much: require two-factor authentication, use rulesets to protect branches and tags, require signed commits where needed, keep a SECURITY.md with a private reporting route, and review access regularly. If a secret leaks, revoke it first, then clean history.
Practice. Enable Dependabot, secret scanning with push protection and CodeQL on one repository and fix the first alert.
Codespaces, Copilot and GitHub Models Optional
GitHub Codespaces are cloud development environments. A .devcontainer/devcontainer.json defines the image, tools and extensions, so a new contributor gets a working setup in a browser or editor in minutes.
GitHub Copilot is an AI coding assistant that offers completions, chat, PR summaries and agent-style tasks. Use it to speed up routine code, but review its output as carefully as a colleague's, because it can be confidently wrong. GitHub Models gives access to hosted AI models for experimenting and prototyping from GitHub. The AI-Assisted Coding Roadmap covers working with these tools well.
Practice. Add a dev container configuration to a project and open it in a codespace.
Community and Education Features Optional
GitHub Gists are small repositories for sharing snippets or single files; they can be public or secret but secret only means unlisted. GitHub Sponsors lets people fund maintainers. CITATION files, CITATION.cff, tell researchers how to cite your software, and GitHub shows a cite button for them.
GitHub Education offers free tools for learning. The Student Developer Pack bundles offers from many developer tools for verified students, the Campus Program supports schools and student clubs, and GitHub Classroom lets teachers distribute assignments as repositories and collect them automatically.
None of these are needed for interviews, but they are useful to know about and to use if you qualify.
Practice. Create a gist for a script you reuse and add a CITATION.cff to one of your projects.
Projects to build
Build these in order. Each one should end up in a public repository with a short README that explains your decisions.
- Personal dotfiles repositoryBeginner
Put your shell, editor and Git configuration under version control with a clear README. Make small commits with good messages, use a .gitignore for machine-specific files, and tag a v1.0 when it works on a second machine.
git init · Commit messages · .gitignore · Tagging · Pushing to GitHub
- Open-source contributionIntermediate
Find a project with good first issues, fork it, follow its contribution guidelines and land a merged pull request. Keep your fork synced with upstream and respond to review comments with clean follow-up commits.
Forking · PR from a fork · Code reviews · Rebase · Contribution guidelines
- Team repository with full CIIntermediate
With one or two friends, build a small app in a shared organisation repository. Protect main, require reviews and passing checks, run tests in a matrix with caching, and track work on a project board linked to issues.
GitHub Organizations · Branch protection · GitHub Actions · GitHub Projects · Issues
- Release automation pipelineAdvanced
Automate releases for a library or CLI: pushing a version tag builds artefacts, publishes a package or container image, creates a GitHub Release with generated notes and deploys documentation to GitHub Pages. Pin actions, use least-privilege permissions and an approval environment for production.
Workflow triggers · GitHub Releases · GitHub Packages · GitHub Pages · Workflow security
- Repository health botAdvanced
Build a GitHub App that listens to webhooks and labels new issues, reminds reviewers about PRs older than three days and posts a weekly summary using the GraphQL API. Verify webhook signatures and respect rate limits.
GitHub Apps · Webhooks · GraphQL API · REST API · Automation
Interview questions
Try to answer each question out loud before you open the answer.
What is the difference between Git and GitHub?Junior
Git is a version control tool that keeps the full history on my machine; it records snapshots of a project, manages branches and merges, and works fully offline. GitHub is a hosting service for Git repositories that adds collaboration around them: pull requests and review, issues, project boards, Actions for CI and CD, package hosting and security scanning. You can use Git without GitHub, for example with GitLab or a plain server over SSH.
Explain the working directory, the staging area and a commit.Junior
The working directory is the files on disk as I edit them. The staging area, or index, is the draft of my next commit; git add copies changes into it. A commit takes a snapshot of what is staged and stores it permanently with a hash, author, message and parent. The staging step lets me commit only part of my work, so I can split unrelated changes into separate, focused commits.
What is the difference between git fetch and git pull?Junior
git fetch downloads new commits and updates remote-tracking branches such as origin/main, but does not touch my local branches or files. git pull runs a fetch and then integrates the remote branch into my current branch with a merge, or a rebase if configured. I often fetch first and look at the incoming log so I know what I am about to integrate, and I set pull to rebase or fast-forward only to avoid surprise merge commits.
What is the difference between merge and rebase, and when do you use each?Mid
Both bring changes from one branch into another. Merge creates a merge commit with two parents and keeps history exactly as it happened, which is non-linear. Rebase replays my commits on top of the target, creating new commits and a linear history. I rebase my own local or feature branch onto the latest main to keep it current and clean, and I never rebase commits others have already pulled. For integrating into main I follow the team's rule, often squash or a merge commit through the PR.
How do you undo a commit that has already been pushed to main?Mid
I use git revert <hash>, which adds a new commit applying the inverse change, and push it through a normal PR. That keeps history intact for everyone who already pulled. I would not reset and force push a shared branch, because it rewrites history others depend on and branch protection should block it. If the commit is a merge, I pass -m 1, and I remember that re-merging the same branch later needs the revert reverted first.
Explain git reset --soft, --mixed and --hard.Mid
All three move the current branch pointer to a target commit. Soft stops there, so the removed commits' changes remain staged. Mixed, the default, also resets the staging area, leaving the changes as unstaged edits in my files. Hard also overwrites the working directory, so uncommitted changes are lost. I use soft to squash recent commits, mixed to redo staging, and hard only when I am sure, knowing committed work can still be found in the reflog.
How do you resolve a merge conflict?Junior
I run git status to see the conflicted files, open each one and look at the markers: my side between <<<<<<< and =======, theirs after it. I work out the intended result, which often combines both, remove the markers, and run the tests. Then I git add the files and finish with git commit or git rebase --continue. If it goes wrong I can abort. For tricky ones I talk to the other author rather than guessing.
I accidentally ran git reset --hard and lost commits. Can you recover them?Mid
Usually yes. Git does not delete commits immediately; they become unreachable but stay in the object store until garbage collection. git reflog shows every position HEAD has had, so I find the entry before the reset and run git reset --hard HEAD@{1} or create a branch at that hash. What cannot be recovered is work that was never committed or stashed, which is why I commit often.
What is a detached HEAD and how do you get out of it?Junior
Normally HEAD points to a branch, which points to a commit. Detached HEAD means HEAD points directly at a commit, which happens when I check out a hash or tag. I can inspect code and even commit, but no branch tracks new commits, so they are easy to lose. To keep work, I create a branch with git switch -c name; otherwise I just switch back to a branch.
Why is git push --force dangerous and what should you use instead?Mid
Force push replaces the remote branch with my local one, discarding any commits there that I do not have, including a teammate's work. I use --force-with-lease, which only succeeds if the remote branch is still at the commit I last fetched, so it refuses when someone else has pushed. I only force push to my own feature branches after a rebase or amend, never to main or other shared branches, which should be protected.
How would you find which commit introduced a bug?Mid
I use git bisect. I mark the current commit bad and a known release good, and Git binary searches the commits between them, so a thousand commits take about ten checks. If I can write a script that exits 0 when the bug is absent and non-zero when present, git bisect run automates the whole search. Then I read that commit's diff and message to understand the cause. Small commits that each build make this work well.
How does Git store data internally?Senior
Git is a content-addressed object store. Blobs hold file contents, trees map names to blobs and subtrees, and commits point to a root tree, parent commits, author and message. Each object's name is the hash of its content, so identical files are stored once and any change to history changes every later hash. Branches and tags are references, small files holding a commit hash, and HEAD usually refers to a branch. Objects are compressed and packed with deltas for storage and transfer.
What branching strategy would you recommend for a team shipping a web service several times a day?Senior
Trunk-based development or GitHub flow: short-lived branches off main, merged through small PRs within a day or two, with CI, required review and branch protection. Unfinished features hide behind feature flags rather than long-lived branches, and main is always deployable, ideally deployed automatically. A merge queue keeps main green when many PRs land. Git flow with develop and release branches adds overhead that suits versioned products with scheduled releases, not continuous delivery.
How do you remove a secret that was committed and pushed?Senior
First, revoke and rotate the secret, because once pushed it must be treated as compromised; forks, clones and caches may already hold it. Then remove it from the code and, if policy requires, from history with git filter-repo, force push, and ask collaborators to re-clone. Finally, prevent repeats: move secrets to a secret manager or environment variables, add the file to .gitignore, and enable secret scanning with push protection.
Common mistakes
- Committing secrets, build output or
node_modules; set up a.gitignorebefore the first commit and rotate any secret that slips through. - Making huge commits with messages like "updates"; commit one logical change at a time with a message that explains why.
- Rebasing or force pushing branches other people use; rebase only your own branches and use
--force-with-lease. - Running
git reset --hardorgit restorewithout checkinggit status; look first, and stash or commit anything you might want. - Letting feature branches live for weeks and then fighting huge conflicts; merge or rebase from main often and keep PRs small.
- Panicking and deleting the repository after a mistake; check
git reflog, which can recover almost any committed state. - Relying on local hooks to enforce rules; anyone can skip them, so enforce the same checks in CI and branch protection.
- Using third-party Actions on moving tags with default broad permissions; pin to SHAs and declare minimal permissions.
Ready-for-interview checklist
- I can explain the working directory, staging area and repository, and stage part of a file.
- I can create, switch, rename and delete branches locally and on a remote.
- I can resolve merge conflicts during a merge and during a rebase.
- I can explain fast-forward and three-way merges and the difference between merge and rebase.
- I can choose the right tool among restore, revert, reset and amend for a given mistake.
- I can recover lost commits with the reflog.
- I can clean up a branch with interactive rebase before review.
- I can open, review and merge a pull request, including one from a fork.
- I can find a bad commit with git bisect.
- I can write a GitHub Actions workflow with triggers, a matrix, caching, secrets and artifacts.
- I can explain how Git stores objects and what a branch and HEAD are.
- I can secure a repository with branch protection, Dependabot, secret scanning and least-privilege tokens.
Related roadmaps
- Shell and Bash RoadmapPipelines, text processing, scripting and automation.
- Linux RoadmapFilesystem, processes, permissions, networking and troubleshooting.
- Code Review RoadmapHow to review and be reviewed: what to look for and how to say it.
- Docker RoadmapImages, containers, networking, volumes, Compose and security.
- Software Design and Architecture RoadmapClean code, SOLID, design patterns, DDD and architecture styles.
FAQ
How long does it take to learn Git and GitHub?
You can learn the daily basics, committing, branching, pushing and opening pull requests, in a week of regular practice. Being comfortable with rebasing, recovery and Actions takes about one to two months of real project use. Most people learn the advanced parts when a problem forces them to, so the drills in this roadmap help you get there sooner.
Should I learn Git commands or use a graphical client?
Learn the command line first. Interviews, servers, CI logs and documentation all use commands, and graphical clients hide what is happening, which makes recovery harder. Once you understand the model, an editor's Git panel or a GUI client is fine for viewing diffs and staging hunks.
Is it better to merge or rebase?
Neither is always better. Rebase your own feature branch to keep it up to date and its history clean, and merge or squash when integrating into a shared branch, following your team's convention. The rule that matters is to avoid rewriting commits other people already have.
Do employers look at my GitHub profile?
Some do, especially for junior roles and open-source-heavy companies. A few well-documented projects with clear READMEs, sensible commits and passing CI say more than a busy contribution graph. Make sure nothing embarrassing or secret is public.
Do I need to know GitLab or Bitbucket too?
The Git part is identical everywhere. The platforms differ in naming and features: GitLab calls pull requests merge requests and has its own CI file format. If you understand GitHub's pull requests and Actions well, switching takes a few days.