LEARN · DEEP GUIDE
Git & GitHub
Save history and collaborate safely
The problem of changing files
A project is a changing collection of files. An editor can save today's text, but that alone does not preserve yesterday's working version, explain who changed a wiring assumption, or combine two people's improvements. Copying folders named final, final2, and actually-final saves some states but leaves their relationships ambiguous. Version control gives those states an explicit identity and history.
Git maintains a repository containing objects and references. Your working tree is the editable collection of files checked out from that history, plus local changes. Git can compare it with a recorded state, prepare another state, and connect the new state to its parents. GitHub hosts Git repositories and adds review, issues, releases, and automation. You can use Git locally without GitHub, and a GitHub account does not automatically save uncommitted files on your computer.
A commit represents a snapshot with metadata and parent relationships. Thinking in snapshots explains why a commit can reconstruct the project even when its displayed patch mentions only two files. Internally, Git reuses unchanged content efficiently; it does not need a physically separate copy of every file for every commit. The patch is a comparison between states, not the sole substance of the state.
Working tree, index, and commit
The working tree holds the files you edit now. The index, also called the staging area, records the file contents selected for the next commit. The current commit is a previously recorded snapshot. These three states can differ. git add path copies the current relevant content into the index. Editing the file again changes the working copy without automatically changing that staged version.
Suppose timing.cpp initially uses 500 ms. You edit it to 250 ms and stage it, then edit it to 100 ms without staging again. The working file contains 100 ms, the index contains 250 ms, and the current commit contains 500 ms. A normal git commit records the staged 250 ms version. This is why the staging area is more than a vague “list of changed filenames.”
git diff ordinarily compares tracked working files with the index. git diff --staged compares the index with the current commit. git diff HEAD shows the net tracked-file difference from the current commit to the working tree. Newly untracked files need separate inspection or staging before they appear in ordinary diff output. Review the staged comparison before recording a commit.
git status
git diff
git add src/timing.cpp
git diff --staged
git commit -m "Use a shorter indicator interval"These commands do not upload anything. They inspect, choose, inspect again, and record a local snapshot. The commit message should identify the behavior or reason that the change captures. A focused commit preserves a decision that a future reader can understand.
- working treegit add → index →
- staging areagit commit → snapshot →
- local commitgit push → refs →
- remote commit
Each area is independent. Editing the working tree after staging leaves the staged copy unchanged; push transfers committed history.
add copies selected working content into the index; commit records its tree; push requests remote ref updates.
Later file edits need not be in the index; no arrow uploads uncommitted working text.
Diagram labels
working tree · staging area · local commit · remote commit
Objects, hashes, and history
A blob stores file content. A tree describes names, modes, and objects within a directory. A commit names a tree, its parent commit or commits, and metadata such as author and message. A reference is a name that points to an object, commonly a commit. You do not need to manipulate these plumbing objects daily, but their model explains ordinary Git behavior.
An object identifier is a cryptographic hash derived from its encoded content. Existing repositories commonly use SHA-1 identifiers; Git also supports a SHA-256 object format. A short displayed identifier is an abbreviation and must be unambiguous in the relevant repository. The identifier is not a version number that increases chronologically. Changing a commit's tree, parent, message, or metadata produces another identifier.
Parent links form a directed graph. A normal commit has one parent, an initial commit has none, and a merge commit commonly has two. History therefore branches and rejoins; it is not inherently a single numbered list. A commit can be reachable from several branch names at once.
git log --oneline -8
git log --graph --oneline --decorate --all
git show <commit>
git log --oneline -- src/main.cppAngle-bracket placeholders in examples must be replaced with real values. git show lets you inspect a commit before choosing it as a recovery target. A displayed date describes metadata, while ancestry determines whether one history incorporates another.
Lines join commits to their parents. A pull request proposes integration between branch tips; this example shows a merge commit with two parents.
Draw commit parent edges, movable branch labels, and the PR as a hosted integration proposal between branch tips.
A PR is distinct from a branch reference, and merge creates or advances history according to ancestry.
Diagram labels
main commit · feature commits · merge result
Branches and HEAD
A branch is fundamentally a movable reference to a commit. It is not a folder containing a second project. When a new commit is created on the current branch, that branch reference ordinarily advances to it. Different branches can point to the same commit until their work diverges.
HEAD usually names the current branch symbolically. Through that branch it identifies the current commit. In detached HEAD state it points directly to a commit. You can inspect an old version there, but new commits are not attached to a named branch unless you create one. To retain useful detached work, create a branch before leaving it.
git branch --show-current
git switch -c feature/button-state
git statusswitch -c creates a branch from the current commit and selects it. It does not publish a GitHub branch, create a pull request, or provide an independent untracked-file storage area. Git may carry local modifications across a switch when safe or refuse a switch that would overwrite them. Inspect status before changing context.
For simultaneous independent directories, Git worktrees provide separate checkouts associated with one repository. They solve a different problem from merely naming a branch. Most club work needs one checkout and a deliberate branch; a worktree becomes useful when a long-running build and another branch must coexist.
A is parent of B and C; main points to B, feature points to C, HEAD symbolically names feature.
Branch movement changes refs, not existing commit contents.
Diagram labels
commit A · commit B · commit C · main · feature · HEAD
Creating or cloning a repository
git init starts a repository in an existing directory. It does not import a remote history. git clone URL creates a new checkout from another repository, obtains history according to the clone options, and normally configures a remote called origin. Clone from the parent folder where the new repository directory should live.
git clone https://github.com/PrejudiceNeutrino/arduinoPractice.git
cd arduinoPractice
git status
git remote -vThat workflow is appropriate when moving the existing practice project to a laptop. Initializing a new repository and pasting files would lose the connected history unless carefully integrated. Cloning copies committed content, not another machine's unsaved editor buffers or uncommitted changes.
If git status already reports a repository in a supposedly new folder, inspect git rev-parse --show-toplevel. A parent directory may already be a repository. A mistaken root changes what git add . covers and which project is being committed. Directory context is part of correctness.
Tracked, ignored, and untracked files
A tracked path is represented in Git's index. An untracked file is present on disk but has not been added to that tracked state. Modified, staged, and committed describe differences between the three states, not mutually exclusive permanent categories. A file can have staged changes and later unstaged changes at once.
In short status, the first column describes index state and the second working-tree state. M means staged modification, M means an unstaged modification, MM means both, and ?? means untracked. Full git status spells those states out when the compact notation is unfamiliar.
A .gitignore file excludes matching untracked paths from ordinary discovery and staging. It does not stop tracking a path already in the index. Generated PlatformIO .pio/ content ordinarily belongs in ignore rules; source files and dependency configuration belong in history. Removing a previously tracked generated file from the index changes tracking and should be reviewed as a real repository change.
Credentials should not be committed. Deleting them in a later commit does not erase earlier objects, and ignore rules do not scrub history. That distinction follows directly from snapshots retaining past states.
Remotes and remote-tracking references
A remote is a named connection configuration for another repository. origin is a conventional name chosen during cloning, not a special synonym for GitHub or the source of absolute truth. git remote -v shows configured fetch and push destinations. Verify them when setting up a new machine or encountering unexpected publication behavior.
origin/main is a local remote-tracking reference recording the fetched view of the remote's main. It is not a live network query each time you read it. Until a fetch updates that view, it can be stale. Your local main, local origin/main, and actual remote main can point to different commits.
An upstream associates a local branch with a branch used for comparisons and default operations. git push -u origin feature/button-state publishes that branch and sets its upstream when successful. An upstream does not force automatic synchronization, and a clean working tree does not imply the branch has been pushed.
Fetch, pull, and push
git fetch origin obtains needed objects and updates configured remote-tracking references. It ordinarily leaves the current branch, index, and working files unchanged. You can then inspect what arrived before deciding how to integrate it. That makes fetch a useful first step when histories appear unexpected.
git pull fetches and then integrates according to options and configuration. Integration can use a fast-forward, merge, or rebase, or refuse to proceed under the chosen policy. Calling it merely “download updates” hides the operation that can change your current branch and files. git pull --ff-only allows the branch to advance only when there is no divergent local history requiring integration.
git push requests updates to remote references and transfers necessary objects. It does not send uncommitted working files. A normal branch push commonly requires the remote's existing tip to be an ancestor of the proposed tip; this protects changes the sender has not incorporated. Authentication and permission checks are separate from that history check.
git status
git fetch origin
git log --graph --oneline --decorate -12 --all
git pull --ff-onlyUse the last command only after confirming that advancing the checked-out branch is the intended operation. If it fails because the branches diverged, do not automatically add --force. Choose a merge or rebase after inspecting both histories. The official pull documentation describes those integration choices.
Merge and conflicts
A fast-forward occurs when the current tip is already an ancestor of the target. Git can move the branch reference forward without creating a merge commit. If both branches have unique commits, a normal merge can combine their changes and record a commit with both parent histories. The merge base is a common ancestor used to reason about changes from each side.
Conflicts occur when Git cannot determine a satisfactory automatic combination. The conflict can concern overlapping text, deletion versus modification, renames, or other structural cases. Resolving it means producing a correct final file state, not merely deleting the visible marker lines. Two individually reasonable edits can combine into invalid firmware or mismatched wiring documentation.
git status
git diff
# Edit each conflict into the intended combined result.
git add path/to/resolved-file
git diff --staged
git commitSome operations use their own continuation command; follow status instructions. During a normal unresolved merge, git merge --abort attempts to restore the pre-merge state. Starting with a clean or deliberately preserved working tree makes recovery more predictable. Never assume abort can rescue every mixture of pre-existing edits and subsequent modifications.
After resolving source and metadata conflicts, run the relevant validators. Git can establish that text is resolved; it cannot infer whether a concept ID points to the right anchor or whether changed code drives the intended electrical circuit.
GitHub collaboration
A pull request proposes integrating one branch's changes into another and provides a place for comparison, discussion, checks, and review. It is not the branch itself. A branch can exist without a PR, and closing a PR does not necessarily delete its branch. The base branch determines the comparison and eventual integration target.
Review examines whether the proposed result solves the problem and preserves contracts. A useful PR description identifies the changed behavior and relevant verification. For a content pass, it should explain what the corpus now teaches and which IDs and source assets remain stable. Review of a large generated diff requires actual reading, not just green schema checks.
An issue tracks a problem or planned work without itself changing repository files. A fork is a repository copy under another namespace that can support contribution when direct branch permissions are absent. A release attaches publication information and assets to a version reference, commonly a tag. GitHub Actions runs configured workflows on events; a workflow result is evidence about its checks, not proof of every real-world behavior.
Restore, reset, and revert
Undo commands act on different states. git restore --staged file restores the selected index path from the default source, normally HEAD, while leaving the working file alone. It unstages the change. git restore file ordinarily replaces the working file from the index and can discard unstaged edits. The latter can lose work even though it does not rewrite branch history.
Commit-form git reset --soft target moves the current branch to the target while keeping index and working files. --mixed, the default mode for that form, also resets the index to the target and leaves working files. --hard additionally updates tracked working files to the target and can remove obstructing untracked paths. Hard reset is not a general cleanup or harmless synchronization command. Path-form reset affects selected index paths without the same branch movement, so always read the command form.
git revert commit applies an inverse change and records a new commit. It preserves the existing history, which is why it is normally preferable for undoing shared changes. Reverting can conflict with subsequent work; it does not simply guarantee returning every file to an earlier snapshot. Reverting a merge needs a selected mainline parent and careful understanding of future merges.
| Operation | Branch/history | Index | Working files |
|---|---|---|---|
restore --staged file | Unchanged | Selected paths restored | Preserved |
restore file | Unchanged | Unchanged | Selected paths restored, edits may be lost |
reset --soft target | Tip moved | Preserved | Preserved |
reset --mixed target | Tip moved | Reset to target | Preserved |
reset --hard target | Tip moved | Reset to target | Reset, local work may be lost |
revert commit | New inverse commit | Updated by operation | Updated by operation |
References: restore, reset. Inspect state and preserve useful work before choosing a destructive operation.
Reflog, stash, and cleanup
A reflog records local reference movements. If a branch tip moved unexpectedly, git reflog may reveal a formerly reachable commit. Inspect it, then create a recovery branch at the identified commit rather than immediately replacing the current state. Reflog availability and retention are local and finite; it is not a permanent remote backup.
git reflog
git show <recovered-commit>
git branch recovery/indicator <recovered-commit>Reflog can recover recorded objects that remain available. It generally cannot recover arbitrary unstaged text discarded by restore or hard reset. An editor's local history may help with that separate problem, but it is not Git history.
git stash push -m "reason" sets aside tracked local work in a Git-managed form. -u additionally includes untracked files; ignored files require another deliberate option. Applying a stash can conflict with the current branch. stash pop removes the stash only when the application succeeds under its rules; inspect the result before assuming work was cleanly transferred.
git clean removes untracked paths and has options affecting directories and ignored files. Preview with a dry-run command such as git clean -n and inspect the exact scope. An untracked project file is not disposable merely because Git has never recorded it. Cleaning caches and deleting untracked original work are different consequences of the same command family.
Rebase and rewritten history
Rebase replays selected changes onto a new base, creating new commits with new parent relationships. Because the parent is part of a commit's identity, the rewritten commits receive different hashes even when a patch looks similar. Rebase is useful for keeping an unpublished feature series on a newer base or organizing a local sequence before review.
During a replay conflict, resolve the intended result, stage it, and use git rebase --continue; --abort abandons the operation under its recovery rules. A skipped commit drops that replayed change and needs a reason. Rebase is not inherently “better merging.” It preserves a different history shape and can alter how reviewers interpret the sequence.
Rewriting a branch that others already use makes their recorded ancestry disagree with the new branch. Coordinate before doing so. git push --force-with-lease can reject a forced update when the remote tip does not match the expected state; it protects against certain unexpected concurrent updates, but does not make rewriting agreed shared history automatically acceptable. Explicit lease expectations provide stronger clarity than assuming a remote-tracking reference was never refreshed by another process.
Reference: rebase. For ordinary club collaboration, focused commits and normal merges are sufficient unless the workflow has a clear reason to rewrite.
Tags, releases, and canonical snapshots
A tag names a version that is intended to remain stable. A lightweight tag is a direct reference; an annotated tag has its own object with metadata and can carry a message or signature. A GitHub release is publication metadata associated with a tag and may include downloadable artifacts. Creating a local tag does not necessarily publish it with a normal branch push.
For reproducible content work, record the inspected commit SHA. A URL naming a branch can change as that branch advances; a URL naming a commit identifies a specific recorded version. The Learn source ledger retains earlier snapshots and records this pass's starting Engineering Club, personal-notes, and arduinoPractice SHAs. A final commit cannot meaningfully contain its own hash as mutable authored content; report that hash after committing.
Canonical inventory facts belong to the inventory package. Canonical lab source belongs to its code assets. A Learn pass can link to both without editing or copying their ownership records. Git's comparison tools establish exactly whether those protected paths changed. A clean working tree only says the local files and index match the checked-out state; the scope comparison establishes whether the recorded change stayed within its contract.
Engineering Club workflow and command reference
Start on the verified base, create a focused feature branch, inspect the data and source contracts, make the authorized changes, review the diff, and run the applicable validators. Then commit and publish the feature branch for review. Merge into main is a separate decision. A branch name communicates intent but does not protect the branch from accidental edits; status and scope checks do.
| Intent | Command and effect |
|---|---|
| Inspect state | git status |
| Review working / staged changes | git diff / git diff --staged |
| Choose next snapshot content | git add path |
| Record selected content | git commit -m "message" |
| Inspect history | git log --graph --oneline --decorate --all |
| Create and select a branch | git switch -c name |
| Update remote view | git fetch origin |
| Advance without divergent integration | git pull --ff-only |
| Publish and set upstream | git push -u origin name |
| Integrate another history | git merge branch |
| Unstage while preserving edits | git restore --staged path |
| Undo a shared change | git revert commit |
| Find previous local reference positions | git reflog |
| List local branches | git branch |
| Replay local changes onto a chosen base | git rebase base (rewrites selected commits) |
| Restore an unstaged file from the index | git restore path (discards its unstaged edits) |
| Move a tip while retaining prepared/local work | git reset --soft target (commit form) |
Two-dot commit ranges such as A..B select commits reachable from B but not A in history-oriented commands. Diff uses its own comparison semantics; do not assume every command interprets punctuation identically. When uncertain, ask which states or objects the command reads and which it changes. That question scales from a one-file practice program to the club's source and provenance system.