Git and GitHub — Commits, Branches and Pull Requests

Track changes with Git, branch and merge, resolve conflicts, and collaborate through GitHub pull requests and code review.

Est. 40 min Updated Suggest a fix
// Part 01 — Version history

Git Records Changes as a Graph

Git is a distributed version-control system. A repository stores snapshots (commits) and relationships between them, so you can review how a project changed, collaborate in parallel, and recover from many mistakes. Each developer has a local copy of the repository history; GitHub hosts a remote copy and adds collaboration features such as issues, pull requests, and review discussions. Git and GitHub are related but not the same product.

A commit is a named snapshot with metadata and a parent commit. A branch is a movable name pointing at a commit; switching branches changes the working tree to the selected history. Git's index (staging area) lets you choose exactly which changes become the next commit. This separation is useful: inspect a diff, stage a coherent change, inspect the staged diff, then commit with a message describing why the change was made.

AreaWhat it containsUseful check
Working treeFiles currently changed or untrackedgit status
Index / staging areaSelected changes for the next commitgit diff --staged
Local repositoryCommits and branches on this machinegit log --oneline --graph
Remote repositoryShared history hosted elsewheregit remote -v
💡 Note
A commit is not a backup by itself. Push important commits to an authorized remote and follow your team's backup and branch-protection practices.
// Part 02 — Start a repository

Inspect, Stage, and Commit a Focused Change

Clone a project from its approved remote, or initialize a new local repository in a project directory. Always check git status before staging. git add selects file changes, and git diff --cachedshows what will enter the commit. Prefer adding the specific files you intend to change instead of blindly staging everything, especially when generated output or local configuration may be present.

bash
git clone https://github.com/example/team-api.git
cd team-api
git status --short

# After editing a file, inspect and stage just that path.
git diff -- app/health.py
git add app/health.py
git diff --cached
git commit -m "Add readiness check"

Write a concise commit message that describes the change, not the keystrokes. Several small, coherent commits are easier to review and revert than one large commit mixing unrelated fixes. Avoid committing secrets, credentials, local databases, editor files, or build output. If a sensitive value was accidentally committed, removing it in a later commit does not erase it from history; follow the organization's incident process to rotate the secret.

⚠️ Important
Never add an API key to Git to make a local app work. Put secret values in an approved secret store or local environment file excluded by .gitignore, and rotate any credential that has already been exposed.
// Part 03 — Ignore local files

Use .gitignore for Generated and Private Data

A .gitignore file tells Git which untracked paths to leave out of normal status reporting. It does not remove a file that is already tracked. Add rules that match the project, such as a local virtual environment, temporary logs, or a development environment file. Do not ignore source files or configuration templates needed by the whole team; commit a safe example file with placeholder values when useful.

.gitignore
bash
# Local Python environment and bytecode
.venv/
__pycache__/
*.py[cod]

# Local configuration and logs
.env
.env.*.local
*.log

# Build output
build/
dist/

Check which rule applies with git check-ignore -v path. If a file is already tracked, Git continues to track it even after adding a matching rule. Review the status and history before changing index state, and never assume that adding .env to ignore rules retroactively removes leaked values from old commits.

bash
git check-ignore -v .env
# If a local file is already tracked, stop tracking it but keep the worktree copy:
git rm --cached .env
git status --short
// Part 04 — Branches

Do Independent Work on a Named Branch

Branches let a developer make a focused change without moving the shared default branch directly. Create a branch with a clear name, make commits, then bring in updates from the shared branch as the work progresses. Teams may use short-lived feature branches, trunk-based development, or another documented workflow; use the repository's rules rather than inventing a parallel process.

bash
git switch -c feature/health-check
git status
git add app/health.py
git commit -m "Add readiness check"

# Switch back to the shared branch when the working tree is clean.
git switch main
git log --oneline --decorate -5

Merging combines histories by creating a commit with both lines of development as parents (unless Git can fast forward the branch pointer). Rebasing replays commits onto a new base, creating new commit identities and a more linear history. Do not rebase commits other people may already have based their work on unless your team explicitly coordinates it. A useful rule is to rebase your private work when appropriate, but merge shared work according to the team's policy.

OperationHistory resultGood fit
MergePreserves the relationship between historiesIntegrating shared or reviewed branch work
RebaseReplays commits onto a different baseCleaning up private local work before sharing
Fast-forwardMoves a branch pointer without a merge commitNo diverging commits need to be joined
🎯 Pro Tip
A clean history is useful, but preserving reviewability and teammates' work is more important than forcing every branch into a particular shape.
// Part 05 — Remotes and pull requests

Share Work for Review

A remote is a named URL for another repository, often named origin. fetch updates remote references without changing your current files; pull fetches and integrates according to its configured behavior. Push publishes your local branch. Authentication and permissions are handled by your configured Git credential manager or SSH setup; never put a token directly into a command or remote URL that may be saved in shell history.

bash
git remote -v
git fetch origin
git log --oneline --graph --decorate --all -12
git push -u origin feature/health-check

Open a pull request (PR) on GitHub to propose a branch for integration. A good PR explains the problem, the solution, how it was tested, and any operational risk. Reviewers check correctness, maintainability, tests, and rollout impact. CI checks can run linting and tests. Respond to feedback with follow-up commits, then use the merge method allowed by repository policy. A PR is a conversation and review boundary, not just a button to merge code.

  1. Fetch the latest shared history and confirm the target branch.
  2. Push your named feature branch and open a PR with a focused description.
  3. Review automated checks and address feedback with small, understandable changes.
  4. Merge using repository policy, then remove the finished branch when appropriate.
📌 Real World Example
For a production change to an API used by a payments or delivery workflow, describe the health-check behavior, tests, and rollback plan in the PR. Reviewers need the impact, not only a list of changed files.
// Part 06 — Conflict resolution

Resolve Conflicts by Understanding Both Changes

A merge conflict happens when Git cannot combine overlapping edits automatically. Git marks the affected file with conflict delimiters that show the competing versions. Do not simply choose the current branch or incoming branch everywhere: inspect each conflict in context, understand both intentions, and create the combined result. Remove all conflict markers, run relevant tests, and stage the resolved file to tell Git the conflict is handled.

bash
git fetch origin
git merge origin/main
# Edit each conflicted file, remove markers, and preserve the intended behavior.
git diff --check
git diff -- app/health.py
git add app/health.py
git status
git commit

During a rebase conflict, resolve and stage the files, then use git rebase --continue to replay the next commit. If the operation is not going as expected, git merge --abort or git rebase --abortcan return to the state before that operation. Check status and read the command's output before proceeding; do not mix recovery instructions for a merge and a rebase.

⚠️ Important
Conflict markers left in source code can break a build. Search for <<<<<<< before finishing a conflict and run the project's checks after resolving it.
// Part 07 — Undo carefully

Choose an Undo Command That Matches the Situation

Git has several ways to undo work, and they affect different places. git restore can discard unstaged edits; restoring a staged path can remove it from the index. git revert creates a new commit that reverses an earlier commit, making it a safer choice for already-shared history. git reset moves a branch pointer and can make commits hard to find; do not use it casually on work that has been pushed or shared.

bash
# Review first; discard only a specific unstaged change you are sure you do not need.
git diff -- app/health.py
git restore -- app/health.py

# Undo a published commit by adding a new inverse commit.
git revert <commit-id>

# Check current state after any recovery operation.
git status

If you have not committed, inspect git diff and git diff --staged before changing state. If a commit is already public, prefer a history-preserving correction and coordinate with the team. If you have lost a local commit, git reflog may show recent branch movements; consult a teammate before rewriting shared history or force-pushing.

// Part 08 — Pitfalls

Common Mistakes

Using git add . without reviewing status

Why: Unrelated, generated, or private files can enter the commit.

Fix: Stage explicit paths, then inspect git diff --staged.

Rebasing a branch other people are using

Why: Rebase creates new commit IDs and changes the shared history.

Fix: Coordinate with teammates and follow branch policy; do not rewrite shared work.

Assuming .gitignore removes a tracked secret

Why: Ignore rules apply to untracked files, not existing history.

Fix: Remove tracking appropriately, rotate exposed credentials, and follow incident response.

Resolving every conflict by taking one side

Why: Both sides may contain necessary behavior.

Fix: Understand the intent, combine changes, and run tests before committing.

// Part 09 — Practice

Collaborate on a Small Feature

Practice

Create a reviewable change and recover safely

  1. Initialize a practice repository, add a .gitignore for local logs and environment files, and create a first commit.
  2. Make a named feature branch, change one file, and inspect both unstaged and staged diffs before committing.
  3. Create a second branch that changes the same lines; merge it and resolve the conflict by combining both intentions.
  4. Inspect remote URLs and history in a repository you are authorized to access; do not expose credentials in a URL.
  5. Use git revert on a disposable commit and compare its history with restoring an unstaged edit.
  6. Draft a pull-request summary with the reason for the change, validation performed, and rollout considerations.

Hint: Use a local practice repository first. Before any undo command, inspect git status and the relevant diff.

🎯 Key Takeaways

  • ✓Git tracks snapshots and branch relationships locally; GitHub hosts collaboration and review workflows.
  • ✓Stage and inspect a focused diff before making a commit.
  • ✓Keep generated files and secrets out of commits; .gitignore does not erase already tracked history.
  • ✓Merge preserves history relationships, while rebase rewrites commit identities and should not rewrite shared work.
  • ✓Pull requests provide a place to explain, test, and review changes before integration.
  • ✓Use restore, revert, and reset only after identifying whether work is unstaged, staged, local, or shared.

Next

What comes next

Your scripts and application changes are now reviewable. Next, package an application and its runtime into a container image.

Lesson 04 · Docker Fundamentals — Images, Containers and Dockerfiles →

HELP US IMPROVE

How was this lesson?

Your note is shared with the Chaduvuko team for review. Please don’t include personal or sensitive information.

Choose your feedback

Spotted a mistake or something unclear? Suggest a fix on GitHub or email us. Select the text first and it is quoted for you.

Share

Discussion

0

Have a better approach? Found something outdated? Share it — your knowledge helps everyone learning here.

Continue with GitHub
Loading...