14 Version Control with Git and GitHub
A textbook is never truly finished when its first draft is written. A corrected equation, a revised dataset, or a new computational exercise may change several files at once. Version control makes these changes traceable. Instead of maintaining folders called final, final-new, and final-revised, an author can maintain one working project and a documented history of its development.
14.1 Learning objectives
After completing this chapter, you should be able to distinguish Git from GitHub, create commits and branches, resolve conflicts, collaborate through pull requests, recover earlier revisions, protect sensitive information, identify releases, and configure an automated rendering check.
14.2 The mental model: snapshots, not backup folders
Git is a local version-control system. GitHub is a hosting and collaboration service for Git repositories. A repository can exist entirely on a laptop without an internet connection. A remote copy provides an additional location for committed work, but neither Git nor GitHub automatically protects uncommitted files or ignored datasets. Maintain independent backups of important research materials.
A working tree contains the files you edit. The staging area contains the proposed next snapshot. A commit records that snapshot, its parent, author metadata and a message. A branch is a movable reference to a commit; HEAD usually identifies the current branch. A remote-tracking branch records the last known state of a remote branch, not necessarily its current state.
Consider a health-science mathematics textbook in which an author changes the unit of a waiting-time variable from seconds to minutes. The chapter explanation, dataset documentation, figure axis and computational script may all require changes. A single coherent commit can capture the complete correction. A reviewer can then inspect the changes together rather than reconstructing them from email attachments.
14.3 Establishing a repository
Install Git from https://git-scm.com/ and open a terminal. Check the installation and configure your identity. Use an institutional address only if you are comfortable with it appearing in commit metadata; GitHub provides a no-reply address for privacy.
git --version
git config --global user.name "Your Name"
git config --global user.email "YOUR_EMAIL"In a new practice directory, create a Quarto book with quarto create project book or use the supplied repository template. Change into the project directory before initializing Git. Do not initialize a nested repository inside an existing repository unless that is intentional.
git init -b main
git status
git add _quarto.yml index.qmd .gitignore
git diff --cached
git commit -m "Initialize textbook project"git diff shows unstaged tracked changes; git diff --cached shows staged changes. Neither displays the contents of every untracked file. Inspect git status and new files separately. Prefer explicit file names when staging early in your learning. A broad git add . can accidentally stage private notes or generated files.
14.4 What belongs in the repository?
Track source chapters, configuration, bibliography, reusable code, dependency specifications, and small public or synthetic datasets. Generated HTML and PDF files are often better stored as deployment artifacts or release assets rather than committed to the source branch. Some publishing workflows deliberately track generated files on a separate branch; choose one policy and document it.
/.quarto/
/_book/
/_site/
/.Rproj.user/
.Rhistory
.RData
.venv/
__pycache__/
.ipynb_checkpoints/
.env
/data/private/
A .gitignore file prevents matching untracked files from being added by default. It does not remove previously tracked files, erase history, or guarantee confidentiality. Never put identifiable patient records, API keys, passwords, or restricted student data into a practice repository. Use synthetic data instead. If a secret is committed, revoke or rotate it immediately and coordinate history cleanup with the repository administrator; deleting the latest copy is insufficient.
14.5 Connecting to GitHub
Create an empty repository in your GitHub account. For unpublished manuscripts, start with a private repository unless you have permission to publish the source. Do not initialize the remote with a README if you already have an independent local history. Replace the placeholder URL with your actual repository URL.
git remote add origin https://github.com/OWNER/REPOSITORY.git
git push -u origin mainAuthenticate using an approved credential manager, browser-based GitHub CLI login, or SSH. Do not embed access tokens in repository URLs or scripts. The -u option establishes an upstream branch for subsequent pushes and pulls. To work on a different computer, clone the repository rather than copying an arbitrary working directory.
git clone https://github.com/OWNER/REPOSITORY.gitBefore editing, inspect the status and synchronize a clean local main branch using git pull --ff-only. If it fails, inspect the divergent histories instead of forcing a push. git fetch origin retrieves remote history without integrating it into the working branch.
14.6 A worked textbook revision
Suppose a draft reports the mean of five synthetic clinic waiting times, 10, 12, 15, 18 and 25 minutes, as 15 minutes. The correct mean is 16 minutes; 15 is the median. A correction should address the narrative and the reproducible calculation.
14.6.1 R implementation
wait <- c(10, 12, 15, 18, 25)
mean(wait)
median(wait)
stopifnot(mean(wait) == 16, median(wait) == 15)14.6.2 Python implementation
from statistics import mean, median
wait = [10, 12, 15, 18, 25]
assert mean(wait) == 16
assert median(wait) == 15
print(mean(wait), median(wait))The assertion is a small regression test: if the data change without a corresponding revision to the expected result, the check fails. In real research, avoid hard-coding expectations derived from the same faulty computation; independently verify them.
Create a branch before editing the chapter and adding the check script.
git switch -c fix/waiting-time-summary
# Edit the manuscript and test script in your editor.
git diff
git add models.qmd check.py
git diff --cached
python check.py
git commit -m "Correct waiting-time mean and add regression check"
git push -u origin fix/waiting-time-summaryOn GitHub, open a pull request targeting main. Explain the original error, the corrected value, the affected files and the tests performed. Ask a reviewer to verify the calculation and interpretation. A successful render does not prove the mathematics is correct; a mathematical review remains necessary.
14.7 Branches, merges and conflicts
A branch permits changes without immediately modifying the main manuscript. When two branches edit different paragraphs, Git can often merge them automatically. When they edit the same lines, Git may require human judgment. For example, one reviewer changes a confidence interval while another changes the interpretation of that interval. Both changes may be needed.
git switch main
git pull --ff-only
git merge fix/waiting-time-summaryThis local merge is an alternative to merging through a pull request, not an additional required step. If a conflict occurs, run git status, open the affected file, and inspect the conflict markers. The text between <<<<<<< and ======= represents one side, and the text between ======= and >>>>>>> represents the other. Edit the file into the scientifically correct final version, removing all markers. Run the relevant tests, stage the resolved files and complete the merge with git commit. To abandon an in-progress merge, use git merge --abort; begin merges with a clean working tree to make recovery easier.
Do not select an entire side merely because it is newer. In a statistical manuscript, a conflict can reveal inconsistent denominators, incompatible model specifications or contradictory conclusions. Resolve the scientific issue first, then the textual issue.
14.8 Reviewing and recovering history
git log --oneline --graph --all
git show HEAD
git log -- models.qmd
git diff HEAD~1 HEAD -- models.qmdThe last command assumes at least two commits. To inspect an earlier file without changing the working tree, use git show COMMIT:models.qmd, replacing COMMIT with an actual hash. To restore a file from an earlier revision, first ensure your current work is committed or backed up, then use git restore --source=COMMIT -- models.qmd. This overwrites the working copy of that file. Review and commit the restoration if appropriate.
For a published mistake, git revert COMMIT creates a new commit that reverses the specified commit. This preserves shared history and is usually preferable to rewriting a shared branch. Avoid git reset --hard and force-pushing in beginner collaboration workflows because they can discard work or disrupt other contributors.
14.9 Editions and releases
A branch continues to move as changes are committed; a tag identifies a particular revision. A release can attach rendered books, supplementary datasets, and a changelog to a tagged revision. Adopt a documented version policy: for example, v1.0.0 for the first edition, v1.0.1 for a correction, and v1.1.0 for an expanded compatible edition. This is a local publishing convention, not a universal academic requirement.
git switch main
git pull --ff-only
git tag -a v1.0.0 -m "First reviewed textbook release"
git push origin v1.0.0Create a GitHub release from that tag only after reviewing the rendered output and confirming permissions for every asset. Record the commit, Quarto version, package environment, date, and known limitations. A tag alone does not archive a computational environment or create a DOI. A separate archival service may be appropriate for citable research software.
14.10 Automated validation with GitHub Actions
Continuous integration (CI) runs defined checks when changes are proposed or pushed. A minimal workflow for a book with static code examples can install Quarto and render HTML. Executable R and Python chapters require the corresponding runtimes and dependencies as well. The supplied workflow is intentionally a validation example, not a deployment workflow.
name: Validate textbook
on:
push:
branches: [main]
pull_request:
permissions:
contents: read
jobs:
render:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: quarto-dev/quarto-actions/setup@v2
- run: python3 check.py
- run: quarto render --to htmlSave this as .github/workflows/validate.yml at the repository root. The example assumes check.py exists at that root. For production, review action versions and pin trusted actions to reviewed commit hashes. Do not give pull-request code access to publishing credentials. A green check indicates that the specified commands completed, not that every link, figure, claim or accessibility requirement was validated. Add review gates appropriate to the project.
14.11 Reproducible environments and large files
Record R dependencies using renv and Python dependencies using a reviewed requirements or lock file. A Git commit captures the source but does not capture every installed library or operating-system dependency. Record the Quarto and language versions, and test from a fresh clone. For large generated books and images, consider release assets or Git LFS where appropriate; LFS has storage and bandwidth policies and is not a privacy mechanism. Avoid committing repeated binary revisions of large PDFs when source changes are sufficient.
14.12 Guided practice
14.12.1 Practice 1: Inspect a snapshot
Create a local repository from the supplied template. Commit the original files, change one sentence, and compare git diff with git diff --cached before and after staging. Explain which version would be committed.
14.12.2 Practice 2: Correct a mathematical claim
Change the waiting-time narrative to report the correct mean and median. Run both language checks if available. Create a branch and commit the correction. Write a pull request description identifying the error and verification.
14.12.3 Practice 3: Resolve a conflict
In a disposable local repository, create two branches from the same commit. Change the same sentence differently on each branch and commit both. Merge one into the other. Resolve the conflict by writing a sentence that is mathematically correct and includes the units. Inspect the final history.
14.12.4 Practice 4: Prepare a release
Render the template as HTML, inspect navigation and mathematical notation, and create a local annotated tag. Write release notes listing changes and known limitations. Do not publish the practice repository unless you intend to make its contents available.
14.13 Troubleshooting
| Symptom | Diagnostic and response |
|---|---|
| Nothing to commit | Inspect status; confirm the file was saved and is not ignored. |
| Push rejected | Fetch and inspect divergence; integrate changes without force-pushing. |
| Authentication failed | Check remote URL and approved credentials; never paste tokens into source. |
| Merge conflict | Inspect status, resolve content, test, stage and commit. |
| CI cannot find a file | Check exact path, capitalization and whether the file was committed. |
| Local render succeeds but CI fails | Compare runtime versions, dependencies and working directory. |
| Private file already tracked | Restrict access, assess exposure, rotate secrets and coordinate remediation. |
14.14 Designing repositories for a textbook series
A repository boundary is a decision about responsibility, not merely a folder boundary. A series of publications labeled Book 1, Book 2, Book 3 and Book 4 may share a visual identity but have different release schedules and software dependencies. Give each book its own repository when it can be built, reviewed and released independently. Keep the shared theme in a separate template repository and record which template revision each book adopts. A change to the template should not silently alter every published book. Instead, migrate one book, test its representative chapters, and then adopt the change elsewhere.
A monorepository can be reasonable when books must be released together or share substantial source material. Its advantage is that a single commit can update all dependent manuscripts. Its disadvantage is that permissions, build times and release boundaries become coupled. Neither architecture is inherently more reproducible: the decisive question is whether an independent reviewer can identify and rebuild a specific edition.
| Resource | Recommended location | Reason |
|---|---|---|
| Chapter source and exercises | Book repository | Reviewed together with solutions |
| Small synthetic datasets | Book repository | Portable, inspectable examples |
| Shared design template | Template repository | Controlled migration |
| Large restricted clinical data | Approved secure storage | Access and retention controls |
| Rendered public website | Deployment output | Derived from reviewed source |
| Release manifest | Book repository or release assets | Identifies source and build inputs |
Use relative paths within the project. Avoid hard-coded home directories and local drive letters. Track environment specifications, but do not track entire virtual environments. A lockfile describes dependencies; it does not contain all external system libraries or guarantee that a remote package server will remain available. Document those limitations in the release notes.
14.15 A correction that changes mathematical meaning
Suppose an author reports that the mean of five fictional outpatient waiting times, 10, 12, 15, 18 and 25 minutes, is 15 minutes. The calculation is incorrect: the sum is 80 and the mean is 16, while the median is 15. The correction must distinguish the two statistics rather than merely replacing every occurrence of 15 with 16. A worked solution, figure caption and assessment key may legitimately retain the median of 15.
A reviewer should ask which quantity is being estimated, whether the observations are independent, whether missing values were excluded, and whether units remain consistent. Git cannot answer these questions. It can, however, show exactly which statements and calculations changed. A coherent correction commit includes the narrative, a numerical assertion and any affected solution. Unrelated spelling changes can be reviewed separately.
14.15.1 Independent R verification
w <- c(10, 12, 15, 18, 25)
stopifnot(mean(w) == 16, median(w) == 15)14.15.2 Independent Python verification
from statistics import mean, median
w = [10, 12, 15, 18, 25]
assert mean(w) == 16
assert median(w) == 15A numerical assertion is a regression test: it helps prevent a previously corrected defect from returning. If the data are intentionally revised, update the expected result only after independently checking the new calculation. Do not change a test merely to make a failing build green.
14.16 Reading differences as a scientific reviewer
Start with git status --short and git diff --stat to establish scope. Then inspect git diff for unstaged edits and git diff --cached for the proposed commit. A staged file can also contain later unstaged changes; staging is not a permanent property of the filename. Use git show HEAD to inspect the most recent committed snapshot. For a proposed branch, git diff main...correction compares the branch tip with the common ancestor, helping isolate the proposed contribution. Fetch before comparing against a remote-tracking branch so the reference is not unnecessarily stale.
Review the meaning of each change, not just the line count. A one-character change from > to >= can alter a clinical threshold denominator. A changed minus sign can reverse an effect estimate. A renamed figure identifier can break a cross-reference in a different chapter. Conversely, a large generated HTML diff may contain little substantive information. Review the source and regenerate derived outputs instead of attempting to resolve generated HTML conflicts by hand.
14.17 Collaboration laboratory: a conflict between two valid edits
Two collaborators begin from a common chapter. One corrects the mean to 16; the other changes the sentence to discuss the median of 15. Both edits are scientifically valid, but they modify the same line. Git may report a conflict because it cannot infer that the intended final sentence should include both quantities.
git switch main
git switch -c correct-mean
# Edit the sentence and commit.
git switch main
git switch -c clarify-median
# Edit the same sentence and commit.
git merge correct-meanDuring a conflict, inspect git status and the conflict markers in the source. The two sides are not necessarily alternatives from which one must be chosen. Write the combined scientific statement, remove all conflict markers, run the numerical check, stage the resolution, and commit. If the intended integration is unclear, use git merge --abort to return to the pre-merge state when safe, and consult the collaborator. Do not discard uncommitted work to make a conflict disappear.
The accompanying isolated laboratory performs this workflow with actual Git commands and checks the final sentence. It uses a temporary directory and local author settings, so it does not modify the reader’s existing repositories or global identity.
14.18 Reviewing a pull request
A pull request is a proposal to integrate changes, not evidence that those changes are correct. A useful description states the problem, affected chapters, proposed correction, verification performed and remaining limitations. For the waiting-time example, the reviewer should see the original incorrect claim, the corrected mean and median, the data used and the test output. If a full Quarto render is unavailable, state that explicitly rather than claiming publication readiness.
Assign review responsibilities according to expertise. A mathematical reviewer checks derivations and numerical results; an instructional reviewer checks the alignment of examples and exercises; a technical reviewer checks paths, dependencies and rendering. In a small team, one person may perform multiple roles, but record which checks actually occurred. A protected default branch and required status checks can help enforce the agreed workflow; they do not replace expert review. Availability of repository protection features depends on the hosting plan and configuration.
14.20 Continuous integration as a layered evidence system
A useful validation pipeline begins with inexpensive checks: source structure, file paths, expected numerical results and configuration parsing. It then installs the declared computational dependencies and renders the relevant publication formats. Finally, it records artifacts for human review. A successful HTML build does not demonstrate that a PDF fits its page margins or that a theorem is valid.
For a public textbook repository, a pull-request workflow should normally have read-only repository permissions and no deployment credentials. Keep publication in a separate workflow triggered by an approved branch or release. Do not execute untrusted contributions with privileged credentials. Review third-party actions and their version references; for stronger supply-chain control, pin reviewed actions to full commit hashes and maintain an update process.
The example workflow below is a starting point, not a deployed service. It checks a small synthetic dataset before rendering. A real book may require R, Python, a TeX distribution, system libraries and more extensive tests. Install these explicitly and document their versions.
name: Validate textbook
on: [push, pull_request]
permissions:
contents: read
jobs:
check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: '3.12'
- run: python check.py
- uses: quarto-dev/quarto-actions/setup@v2
- run: quarto render --to html14.21 Releasing a textbook edition
A release is an identified snapshot with an explicit acceptance decision. Use an annotated tag such as v1.0.0 to identify the reviewed source commit. Decide what the version means for your series: a major version may denote a substantially reorganized curriculum, a minor version may introduce a new chapter, and a patch may correct an equation or typographical error. This is a local convention, not a universal rule for textbooks.
Record the source commit, dataset fingerprints, environment versions, formats reviewed and known limitations. A tag is not immutable by itself: repository permissions and release policies should prevent accidental movement. If a released edition contains a defect, preserve the historical identifier and issue a new correction release rather than silently replacing the original. A website may display the latest edition while linking to archived editions where available.
14.22 Extended guided practice
- Explain why a template change should not automatically rebuild every book in a series.
- Identify the source files affected by a change from seconds to minutes.
- Compute the mean and median of the laboratory data and explain the original error.
- Stage a file, edit it again, and compare staged and unstaged differences.
- Explain the difference between a branch comparison and a comparison with its common ancestor.
- Resolve the two valid edits in the supplied conflict laboratory.
- Inspect the first tagged edition without changing the current working tree.
- Explain why a revert and a backup solve different problems.
- Design a read-only pull-request validation workflow and identify two checks it cannot perform.
- Draft a release manifest for an HTML edition whose PDF has not been inspected.
14.23 Extended project: a reviewed correction release
Create a disposable repository for a two-chapter quantitative textbook. Establish a baseline edition, introduce a documented mathematical correction on a branch, resolve a conflict, and run independent numerical checks. Prepare a release manifest, review the source differences and identify the checks that require a human reviewer. Submit a source archive and sanitized history; remote publication is optional. Use only synthetic data.
| Criterion | Points |
|---|---|
| Repository boundaries and coherent history | 6 |
| Mathematical correction and regression tests | 8 |
| Conflict resolution and review evidence | 6 |
| Release manifest and recovery demonstration | 5 |
| Privacy, CI permissions and documented limitations | 5 |
| Total | 30 |
14.24 Chapter summary
Version control connects scientific reasoning to an auditable history of changes. Use small coherent commits, review differences, isolate revisions in branches, and validate results before merging. Treat a release as a reviewed snapshot rather than a substitute for backups or reproducibility. Protect confidential material before staging files.
14.25 Review exercises
- Distinguish Git from GitHub.
- Explain the working tree, staging area and commit.
- Why inspect staged differences before committing?
- What does
git fetchdo? - Why use
git pull --ff-onlyon a clean main branch? - Explain why
.gitignorecannot remove a secret from history. - Identify three files that should be tracked in a Quarto book.
- Identify three files that should normally be excluded.
- Explain the purpose of a feature branch.
- Describe the steps for resolving a merge conflict.
- Distinguish a tag from a branch.
- Explain why a revert is useful in shared history.
- Compute the mean and median of the five waiting times.
- Explain why a successful render is not a mathematical review.
- Identify two causes of differences between local and CI rendering.
- Describe a safe response to accidentally committing a credential.
14.26 Applied project: A version-controlled academic textbook
Create a local or private repository containing a two-page Quarto book, a synthetic dataset, a reproducible calculation, a README and an appropriate ignore file. Make at least three coherent commits, implement one correction on a branch, document a review and merge, configure a rendering check, and create a release tag. Submit a repository link only if access is authorized; otherwise submit a source archive and a text export of the Git history. Never submit credentials or confidential data.
| Criterion | Points |
|---|---|
| Repository organization and documentation | 5 |
| Meaningful commits and branch workflow | 5 |
| Correct reproducible calculation | 5 |
| Validation and review evidence | 5 |
| Release notes and privacy safeguards | 5 |
| Total | 25 |
14.27 Further reading
14.28 Supplemental assessment
- Conceptual (4 points). Distinguish working tree, staging area and committed snapshot.
- Technical (8 points). In a temporary Git repository commit a report with mean 15, correct it to 16, and inspect git diff before and after staging.
- Applied (8 points). Create a reviewed correction release and demonstrate retrieval of the original version.
See the student assessment packet in the source package for submission guidance and any required datasets.
14.29 Looking ahead
Use reviewed revisions to prepare a public deployment in Chapter 15.
14.30 Interactive learning lab
Explore the activity below, then explain what changed and why.