diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 7fc7a9e..f7e6404 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -2,7 +2,7 @@ version: 2 updates: - package-ecosystem: "github-actions" directory: "/" - target-branch: "master" + target-branch: "main" schedule: interval: "weekly" commit-message: diff --git a/.github/workflows/qemu-image.yml b/.github/workflows/qemu-image.yml index 519d4eb..09896c5 100644 --- a/.github/workflows/qemu-image.yml +++ b/.github/workflows/qemu-image.yml @@ -60,10 +60,14 @@ jobs: - name: Restore and save Nix store uses: nix-community/cache-nix-action@v7 with: - primary-key: nix-${{ matrix.arch }}-${{ hashFiles('flake.lock') }} - restore-prefixes-first-match: nix-${{ matrix.arch }}- + primary-key: nix-${{ matrix.arch }}-${{ hashFiles('flake.lock') }}-${{ github.sha }} + restore-prefixes-first-match: | + nix-${{ matrix.arch }}-${{ hashFiles('flake.lock') }}- + nix-${{ matrix.arch }}- save: ${{ github.ref == 'refs/heads/main' }} gc-max-store-size-linux: 4G + - name: Build all tutorials and integration tests + run: make tutorials - name: Build image run: nix build .#qemu-image --out-link result - name: Check image, offline exercises, and web rollback diff --git a/.github/workflows/slides.yml b/.github/workflows/slides.yml new file mode 100644 index 0000000..28962c6 --- /dev/null +++ b/.github/workflows/slides.yml @@ -0,0 +1,39 @@ +name: "[Slides] Build PDFs" + +on: + push: + branches: [main] + pull_request: + workflow_dispatch: + +concurrency: + group: slides-${{ github.ref }} + cancel-in-progress: true + +jobs: + build: + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v6 + - uses: cachix/install-nix-action@v31 + - name: Enable unprivileged user namespaces + run: sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0 + - name: Restore and save Nix store + uses: nix-community/cache-nix-action@v7 + with: + primary-key: slides-${{ hashFiles('flake.lock') }}-${{ github.sha }} + restore-prefixes-first-match: | + slides-${{ hashFiles('flake.lock') }}- + slides- + save: ${{ github.ref == 'refs/heads/main' }} + gc-max-store-size-linux: 2G + - name: Build and validate PDFs + run: make slides-check + - name: Link PDF artifacts + run: nix build .#slides --out-link result-slides + - name: Upload slides + uses: actions/upload-artifact@v6 + with: + name: nix-training-slides + path: result-slides/*.pdf + if-no-files-found: error diff --git a/00-getting-started/README.md b/00-getting-started/README.md index 0a8674e..f536e4e 100644 --- a/00-getting-started/README.md +++ b/00-getting-started/README.md @@ -1,9 +1,23 @@ # 00 · Getting started with a flake -**Goal:** build and run a package before unpacking the language behind it. Allow 10–15 minutes. +**Goal:** build and run a package before unpacking the language behind it. Allow +10 minutes in the core workshop; keep the Git note as post-workshop reference. Use the [training VM](../README.md#training-vm), or an existing Nix installation with `nix-command` and `flakes` enabled. On another installation, add `experimental-features = nix-command flakes` to `~/.config/nix/nix.conf` (create the file if needed). The supplied VM already enables both. +## Words you'll see + +> `flake.nix` is a file that declares inputs and outputs with a standard structure. +> +> — [nix.dev, Flakes](https://nix.dev/concepts/flakes.html) + +- **flake**: a directory with a `flake.nix`. This directory is one. +- **input**: something the flake depends on. Here, the nixpkgs package collection. +- **output**: something the flake provides. Here, a package called `default`. +- **store path**: a read-only directory under `/nix/store` that holds a build result. + +The [glossary](../GLOSSARY.md) has the official definitions. You don't need them yet: run the commands first. + ## Run the example From the repository root: @@ -52,4 +66,4 @@ Inside a Git repository, Nix normally sees tracked files, including their curren --- Sources: - -- +- diff --git a/01-nix-language/README.md b/01-nix-language/README.md index 0492633..895f3a1 100644 --- a/01-nix-language/README.md +++ b/01-nix-language/README.md @@ -1,15 +1,29 @@ # The Nix Language -The Nix language exists to create and compose **derivations**, which are precise descriptions of how to turn existing files into new ones. It is: +> The Nix language is designed for conveniently creating and composing derivations – precise descriptions of how contents of existing files are used to derive new files. It is a domain-specific, purely functional, lazily evaluated, dynamically typed programming language. +> +> — [nix.dev, Nix language basics](https://nix.dev/tutorials/nix-language) -- **Domain-specific:** it has path primitives, indented strings and interpolation, and string contexts for linking files. -- **Declarative:** there are no sequential steps. Dependencies flow only through data. -- **Pure:** values never change, and the same inputs give the same outputs. -- **Functional:** functions are ordinary values. -- **Lazy:** values are computed only when they are needed. -- **Dynamically typed:** type errors show up at evaluation time. +If you know JSON, you already know half of it. nix.dev puts it this way: -## Reading Order +> If you are familiar with JSON, imagine the Nix language as JSON with functions. + +What each of those words means in practice: + +- **Domain-specific:** built for describing files and builds. It has path values (`./site.json`), multi-line strings, and `${ }` interpolation. +- **Purely functional:** values never change once created, and functions have no side effects. +- **Lazily evaluated:** a value is computed only when something needs it. +- **Dynamically typed:** type mistakes show up when you evaluate the code, not before. + +A *derivation* is a build recipe; see the [glossary](../GLOSSARY.md). + +## Three-hour workshop + +Use the [30-minute guided language lab](workshop.md). It teaches the constructs +needed to read the package recipes in module 03. The files below are reference +material and are not required during the timed workshop. + +## Extended reading order **Prerequisite:** [00 · Getting started](../00-getting-started/README.md). Keep its `flake.nix` open: `inputs` is an attribute set, `outputs` is a function, and `forAllSystems` applies another function to each supported system. You can use the supplied scaffold while learning these pieces. @@ -38,5 +52,5 @@ Try expressions interactively with `nix repl`. From `00-getting-started/`, use ` --- Sources: -- +- - For a gentler tutorial, see diff --git a/01-nix-language/builtins.md b/01-nix-language/builtins.md index 758937d..05b0e18 100644 --- a/01-nix-language/builtins.md +++ b/01-nix-language/builtins.md @@ -2,7 +2,7 @@ > Every primitive lives in the global `builtins` set. A few are also bound at the top level. This note groups the most useful ones. The manual has the full list of ~120. -**Available without the `builtins.` prefix:** `derivation`, `import`, `map`, `toString`, `throw`, `abort`, `removeAttrs`, `baseNameOf`, `dirOf`, `isNull`, `fetchGit`, `fetchTarball`, `fetchTree`, `fromTOML`, `placeholder`, `scopedImport`, `break`, `true`, `false`, `null`. +**Available without the `builtins.` prefix:** `derivation`, `derivationStrict`, `abort`, `baseNameOf`, `break`, `dirOf`, `false`, `fetchGit`, `fetchMercurial`, `fetchTarball`, `fetchTree`, `fromTOML`, `import`, `isNull`, `map`, `null`, `placeholder`, `removeAttrs`, `scopedImport`, `throw`, `toString`, `true` (the list in the [2.35 manual](https://nix.dev/manual/nix/2.35/language/builtins.html)). ## By category @@ -57,4 +57,4 @@ builtins.trace "evaluating x" 42 # prints trace, returns 4 - [../03-derivations/debugging.md](../03-derivations/debugging.md): `trace` and the debugger in practice --- -Source: +Source: diff --git a/01-nix-language/operators.md b/01-nix-language/operators.md index bef1f9c..a87d299 100644 --- a/01-nix-language/operators.md +++ b/01-nix-language/operators.md @@ -50,4 +50,4 @@ Enable them with `extra-experimental-features = pipe-operators`. - [strings.md](strings.md): what gets copied to the store --- -Source: +Source: diff --git a/01-nix-language/scope.md b/01-nix-language/scope.md index 04ce796..b5cc974 100644 --- a/01-nix-language/scope.md +++ b/01-nix-language/scope.md @@ -36,5 +36,5 @@ Syntax: `` --- Sources: -- -- +- +- diff --git a/01-nix-language/strings.md b/01-nix-language/strings.md index 46a3e76..c76602d 100644 --- a/01-nix-language/strings.md +++ b/01-nix-language/strings.md @@ -17,7 +17,7 @@ What an interpolated expression is allowed to evaluate to: |---|---| | string | itself | | path | **copied to the store**. You get the store path: `"${./foo}"` → `"/nix/store/…-foo"` | -| derivation | the store path of its first output: `"${pkgs.hello}"` → `"/nix/store/…-hello-2.12.1"` | +| derivation | the store path of its first output: `"${pkgs.hello}"` -> `"/nix/store/-hello-"` | | set with `__toString` | `__toString self` (this takes precedence) | | set with `outPath` | the value of `outPath` (this is how derivations and flake inputs work) | | anything else | `error: cannot coerce a set to a string` | @@ -53,5 +53,5 @@ Idiomatic Nix never touches context directly. It matters when you wonder *why* a --- Sources: -- -- +- +- diff --git a/01-nix-language/syntax.md b/01-nix-language/syntax.md index efdd0b9..20c3597 100644 --- a/01-nix-language/syntax.md +++ b/01-nix-language/syntax.md @@ -72,5 +72,5 @@ with pkgs; [ git curl ] # bring set attributes into scope --- Sources: -- -- +- +- diff --git a/01-nix-language/types.md b/01-nix-language/types.md index 064db4f..4606b2e 100644 --- a/01-nix-language/types.md +++ b/01-nix-language/types.md @@ -43,4 +43,4 @@ builtins.typeOf (x: x) # "lambda" - [../02-nix-store/store-paths.md](../02-nix-store/store-paths.md): what a path becomes once it is copied to the store --- -Source: +Source: diff --git a/01-nix-language/workshop.md b/01-nix-language/workshop.md new file mode 100644 index 0000000..36416fb --- /dev/null +++ b/01-nix-language/workshop.md @@ -0,0 +1,178 @@ +# Read Nix Package Recipes - 30 Minutes + +The goal is to read the package expressions used later in the workshop. Nix is +a small expression language; most apparent complexity comes from the packaging +and module libraries built with it. + +Run the examples in `nix repl`. Use `:p` before an expression when laziness +hides nested values, and `:q` to exit. + +## 0-5 Minutes: Values and Attribute Sets + +> An attribute set is a collection of name-value-pairs, where names must be unique. +> +> — [nix.dev, Nix language basics](https://nix.dev/tutorials/nix-language#attribute-set) + +Nix data is close to JSON, but lists use spaces and assignments end in +semicolons. + +```nix +{ + name = "training-site"; + enabled = true; + topics = [ "language" "store" "packages" ]; + server.port = 8080; +} +``` + +Try: + +```nix +({ server.port = 8080; }).server.port +({ port = 8080; }).port or 80 +({ port = 8080; }) ? port +``` + +An attribute set groups named values. A list is ordered. Neither is mutated. + +## 5-9 Minutes: Local Names + +> `let` expressions allow assigning names to values for repeated use. +> +> — [nix.dev, Nix language basics](https://nix.dev/tutorials/nix-language#let-in) + +`let` introduces names for one expression. Definitions are not sequential. + +```nix +let + greeting = "Hello"; + audience = "Gambiconf"; +in +{ + message = "${greeting}, ${audience}!"; + length = builtins.stringLength greeting; +} +``` + +`inherit` avoids repeating `name = name`: + +```nix +let name = "training-site"; version = "1"; +in { inherit name version; } +``` + +## 9-17 Minutes: Functions + +> A function always takes exactly one argument. Argument and function body are separated by a colon (`:`). +> +> — [nix.dev, Nix language basics](https://nix.dev/tutorials/nix-language#functions) + +Function application uses whitespace: `f x` calls `f` with `x`. + +```nix +(x: x + 1) 2 +(name: "Hello, ${name}!") "Gambiconf" +``` + +Packages normally take an attribute set so dependencies are named: + +```nix +let + makeMessage = { greeting, audience ? "world" }: + "${greeting}, ${audience}!"; +in +makeMessage { greeting = "Hello"; audience = "Nix"; } +``` + +Read the punctuation aloud: + +- `{ greeting, audience ? "world" }:` declares a function. +- `{ greeting = "Hello"; audience = "Nix"; }` is its argument. +- `makeMessage { ... }` applies the function. + +This is the shape used by `callPackage`: dependency names in a package +function are matched with names in the nixpkgs package set. + +## 17-21 Minutes: Strings, Shell, and Paths + +Indented strings are convenient for builder shell code: + +```nix +let output = "index.html"; +in '' + mkdir -p "$out" + printf '%s\n' "ready" > "$out/${output}" +'' +``` + +`${output}` is Nix interpolation. `$out` is left for the builder's shell. A +path such as `./site.json` is a Nix path value, not the string +`"./site.json"`. Using a path as a derivation input makes its contents part of +the build description. + +## 21-24 Minutes: Laziness + +> The Nix language uses lazy evaluation, and `nix repl` by default only computes values when needed. +> +> — [nix.dev, Nix language basics](https://nix.dev/tutorials/nix-language#interactive-evaluation) + +Nix evaluates values when they are demanded: + +```nix +({ used = 1; broken = builtins.throw "not demanded"; }).used +``` + +This permits large package sets and recursive composition without evaluating +or building every package. Laziness does not mean a derivation builds during +ordinary language evaluation. + +## 24-26 Minutes: Builtins and nixpkgs Libraries + +> Nix comes with many functions that are built into the language. They are implemented in C++ as part of the Nix language interpreter. +> +> — [nix.dev, Nix language basics](https://nix.dev/tutorials/nix-language#builtins) + +`builtins` is part of the Nix evaluator. `lib` and build helpers come from +nixpkgs. + +```nix +builtins.map (x: x * 2) [ 1 2 3 ] +builtins.attrNames { jq = 1; nginx = 2; } +``` + +Later expressions use `pkgs.runCommand`, `pkgs.callPackage`, and +`pkgs.lib.genAttrs`. These are library functions, not language syntax. + +## 26-30 Minutes: Read a Real Recipe + +Open `../03-derivations/01-gnu-hello/hello.nix` and identify: + +1. The outer function and its two named dependencies. +2. The call to `stdenv.mkDerivation`. +3. The attribute set passed to that function. +4. The fetcher call and its attribute-set argument. +5. Boolean, string, and interpolated-string values. + +Then open that exercise's `flake.nix`. Do not unpack every output yet. Find +where nixpkgs is pinned, where a package set is selected for `system`, and where +the Hello function receives its dependencies. + +Checkpoint: explain why `hello.nix` is a function that returns a derivation, +rather than a derivation that somehow imports its own dependencies. + +## Reference Material + +The full language notes cover features intentionally omitted from the timed +path: + +- [Types](types.md) +- [Syntax](syntax.md) +- [Operators](operators.md) +- [Scope](scope.md) +- [Strings and context](strings.md) +- [Builtins](builtins.md) + +--- +Sources: +- +- diff --git a/02-nix-store/README.md b/02-nix-store/README.md index 151e5ad..a7fc153 100644 --- a/02-nix-store/README.md +++ b/02-nix-store/README.md @@ -1,34 +1,69 @@ # 02 · The Nix Store -The Nix store is an abstraction for **immutable file system data that can depend on other such data**. The familiar `/nix/store` directory is one kind of store. Binary caches, remote machines, and daemons are others. +> The Nix store is an abstraction to store immutable file system data (such as software packages) that can have dependencies on other such data. +> +> — [Nix Reference Manual 2.35, Nix Store](https://nix.dev/manual/nix/2.35/store/index.html) + +In plain words: a place where build results are kept read-only, together with a record of which results need which others. The familiar `/nix/store` directory is one kind of store; binary caches and remote machines are others. Terms such as *store path*, *reference* and *closure* are defined in the [glossary](../GLOSSARY.md). **Prerequisite:** [01 · The Nix Language](../01-nix-language/README.md) -## Inspect something you already built +## 15-minute core lab From `00-getting-started/`: ```sh nix build -readlink result +readlink -f result nix path-info --closure-size ./result nix store ls ./result/bin nix-store --query --references ./result +nix path-info --recursive ./result +nix-store --query --roots "$(readlink -f result)" ``` -The result is immutable and references other store objects. The `nix-store` query is a low-level inspection tool; builds and dependency selection throughout this course use the flake CLI. Do not collect the workshop's preloaded dependencies while following the exercises. +Follow the observations in this order: + +1. `result` is a convenient symlink; the realised output is an immutable store + object. +2. Direct references are other store paths mentioned by that output. +3. The runtime closure is the output plus every transitively referenced store + object needed to use it. +4. The closure size approximates what must already exist or be transferred to + deploy that output to an empty compatible store. +5. A GC root keeps an object, and therefore its reachable closure, alive. + +Build-time and runtime closures differ. A compiler can be required to build +GNU Hello without being referenced by the installed executable. Module 03 will +enter the build environment separately and compare it with the program's +runtime output. + +When Nix realises a derivation, it checks the local store, then configured +substituters such as a binary cache, before building missing outputs. A cache +serves already-built store objects; it is not a remote machine executing the +build. + +The `nix-store` queries above are low-level inspection tools; builds and +dependency selection throughout this course use the flake CLI. Do not run +garbage collection in the workshop image because it contains the offline +exercise closures. + +Checkpoint: point to the output path, one direct reference, the complete +runtime closure, and the root that keeps the output alive. + +## Extended reading order + +Start with what you can see from the command line: -## Reading order -The store model, bottom-up: -1. [file-system-objects.md](file-system-objects.md): files, directories, and symlinks; flat vs NAR hashing -2. [store-objects.md](store-objects.md): FSO + references, closures, immutability, content addressing -3. [store-paths.md](store-paths.md): `/nix/store/-` and why the store dir matters -4. [store-types.md](store-types.md): local, daemon, HTTP, S3, SSH stores; URL syntax; `auto` +1. [store-paths.md](store-paths.md): `/nix/store/-` and why the store dir matters +2. [store-objects.md](store-objects.md): references, closures, immutability +3. [profiles-and-gc.md](profiles-and-gc.md): generations, atomic rollbacks, garbage collection +4. [substituters.md](substituters.md): serving and consuming binaries over HTTP and SSH -Using the store day to day: +Then go deeper into the model: -5. [profiles-and-gc.md](profiles-and-gc.md): generations, atomic rollbacks, garbage collection -6. [substituters.md](substituters.md): serving and consuming binaries over HTTP and SSH +5. [file-system-objects.md](file-system-objects.md): files, directories, and symlinks; flat vs NAR hashing +6. [store-types.md](store-types.md): local, daemon, HTTP, S3, SSH stores; URL syntax; `auto` ## Mental model ``` @@ -43,5 +78,5 @@ file system object ──(+ references)──▶ store object ──(hash)── --- Sources: -- -- +- +- diff --git a/02-nix-store/file-system-objects.md b/02-nix-store/file-system-objects.md index abb51b1..624759e 100644 --- a/02-nix-store/file-system-objects.md +++ b/02-nix-store/file-system-objects.md @@ -38,5 +38,5 @@ NAR fixes all of this: one tree has exactly one serialization. --- Sources: -- -- +- +- diff --git a/02-nix-store/profiles-and-gc.md b/02-nix-store/profiles-and-gc.md index 46b6c6a..829f128 100644 --- a/02-nix-store/profiles-and-gc.md +++ b/02-nix-store/profiles-and-gc.md @@ -47,6 +47,6 @@ nix-collect-garbage -d # delete old gens of ALL profiles, then --- Sources: -- -- -- +- +- +- diff --git a/02-nix-store/store-objects.md b/02-nix-store/store-objects.md index 13e5edc..67ecc03 100644 --- a/02-nix-store/store-objects.md +++ b/02-nix-store/store-objects.md @@ -43,5 +43,5 @@ Unless an object is *input-addressed* (see [../03-derivations/](../03-derivation --- Sources: -- -- +- +- diff --git a/02-nix-store/store-paths.md b/02-nix-store/store-paths.md index 6a2152b..461c890 100644 --- a/02-nix-store/store-paths.md +++ b/02-nix-store/store-paths.md @@ -30,4 +30,4 @@ nix store ls -lR $(nix eval --raw nixpkgs#hello.outPath) - [../01-nix-language/strings.md](../01-nix-language/strings.md): how a store path turns up in a string --- -Source: +Source: diff --git a/02-nix-store/store-types.md b/02-nix-store/store-types.md index 25c63ab..3781e98 100644 --- a/02-nix-store/store-types.md +++ b/02-nix-store/store-types.md @@ -34,4 +34,4 @@ When no store is specified (`auto`), Nix picks the first match: - [../03-derivations/distributed-builds.md](../03-derivations/distributed-builds.md): stores used as remote builders --- -Source: +Source: diff --git a/02-nix-store/substituters.md b/02-nix-store/substituters.md index 6ab372b..f40bc34 100644 --- a/02-nix-store/substituters.md +++ b/02-nix-store/substituters.md @@ -5,6 +5,8 @@ ## How substitution works To realise path `P`, Nix asks each substituter in `substituters` (ordered by priority) whether it has `P`. If one does, Nix downloads it. If none do, **Nix builds from source**. The check is a request for `https://cache/.narinfo`. +The commands below are quoted from the manual, which uses the classic `nix-env` CLI. With flakes, `nix shell nixpkgs#nix-serve` replaces `nix-env -iA nixpkgs.nix-serve`, and `nix build --substituters …` replaces `nix-env -iA … --substituters …`. + ## Over HTTP: `nix-serve` ```sh # server @@ -60,5 +62,5 @@ nix.sshServe.keys = [ "ssh-ed25519 AAAA… bob@example.org" ]; --- Sources: -- -- +- +- diff --git a/03-derivations/00-raw-derivation/README.md b/03-derivations/00-raw-derivation/README.md index aab437e..1ff4be7 100644 --- a/03-derivations/00-raw-derivation/README.md +++ b/03-derivations/00-raw-derivation/README.md @@ -1,4 +1,4 @@ -# A raw derivation · 5 minutes +# A raw derivation - 10 minutes From this directory: @@ -9,15 +9,26 @@ cat result readlink result ``` -Expected: a JSON description containing the builder, arguments and environment, followed by an output containing `Hello from a derivation!`. The output is a **file**, not a directory. +Expected: a JSON description containing the builder, arguments, environment, +inputs, and predicted output, followed by an output containing +`Hello from a derivation!`. The output is a **file**, not a directory. Open `greeting.nix`. `system` comes from the flake's per-system scaffold, and the builder is Bash in the store. Its builtin `printf` needs no external command or `PATH`. `GREETING` becomes an environment variable; Nix supplies `$out`. Change `GREETING`, inspect `nix derivation show`, then build again. Both the derivation and output paths change. An unchanged build reuses its result. +Keep this pipeline in view: + +```text +Nix expression --evaluate/instantiate--> .drv build plan --realise--> output +``` + +The `.drv` is not a compiled executable and is not the output. It is the +store-resident build plan Nix can schedule, substitute, or execute. + **Troubleshoot:** replace the build command with `exit 1`, run `nix build -L`, and inspect the failure. Restore the command before continuing. Host paths such as `/bin/sh` are not a portable substitute for a declared builder in the store. **Next:** [GNU Hello](../01-gnu-hello/README.md). --- -Source: +Source: diff --git a/03-derivations/01-gnu-hello/README.md b/03-derivations/01-gnu-hello/README.md index ae285c5..5601127 100644 --- a/03-derivations/01-gnu-hello/README.md +++ b/03-derivations/01-gnu-hello/README.md @@ -1,4 +1,4 @@ -# Build GNU Hello · 10–15 minutes +# Build GNU Hello - 30 minutes This recipe is adapted from [Hausdorff Labs' GNU Hello example](https://github.com/hausdorff-labs/nixos-presentation/tree/main/examples/hello): the same version, source archive, hash and enabled checks, with a standalone flake supplying dependencies. @@ -18,9 +18,32 @@ Expected: `Hello, world!`, then your greeting. The build logs show unpacking, co Look for `configure`, `make`, the test results and installation under `$out`. Running `nix build` again reuses the available output. Changing the runtime greeting does not change the derivation. -## Hash experiment +Inspect the runtime closure and compare it with the build environment: -In `hello.nix`, temporarily replace `sha256` with `""`, then run `nix build -L`. The fetcher reports a mismatch and the hash it actually computed. Restore the supplied hash and build again. A cached archive with the correct hash is not evidence that arbitrary network access is available to normal builders. +```sh +nix path-info --closure-size ./result +nix path-info --recursive ./result +``` + +The source fetcher's hash identifies expected source contents. Do not replace +it with an empty hash in the offline workshop: changing the fixed-output +identity can require a network fetch even when the correct source was preloaded. + +## Diagnose a deterministic failure + +Temporarily add this attribute inside `stdenv.mkDerivation` in `hello.nix`: + +```nix +postCheck = '' + echo "Deliberate workshop failure" >&2 + false +''; +``` + +Run `nix build -L`, find the failed check after the ordinary upstream tests, +and inspect `nix log .#hello`. Remove `postCheck` and rebuild before continuing. +This failure needs no network and demonstrates that checks are part of the +package build. ## Enter the build environment @@ -32,6 +55,10 @@ exit This enters the package's build environment without running its complete build. It is different from installing Hello as a shell tool. Module 04 returns to this distinction. +Checkpoint: identify the pinned source, automatic stdenv phases, upstream +check, installed output, runtime closure, and compiler-bearing build +environment. + **Next:** [build a static site](../02-static-site/README.md). --- diff --git a/03-derivations/02-static-site/README.md b/03-derivations/02-static-site/README.md index 70f6aec..474b1c8 100644 --- a/03-derivations/02-static-site/README.md +++ b/03-derivations/02-static-site/README.md @@ -1,4 +1,4 @@ -# Build a static site · 5–10 minutes +# Package and check a static site - 20 minutes ```sh nix build -L @@ -10,6 +10,10 @@ Expected: an HTML page with `Hello, Gambiconf!` and three topics. A derivation c Open `site.nix`: `runCommand` uses a standard environment **without a compiler**; `nativeBuildInputs` provides the build-time `jq` tool; `${./site.json}` and `${./render.jq}` declare local file inputs. +The flake uses `callPackage` to supply `runCommand` and `jq` by matching the +function arguments in `site.nix` with names in nixpkgs. You'll apply the same +refactor to GNU Hello in the [next step](../../06-nixpkgs/packaging.md#simplify-the-wrapper). + ## Experiments 1. Edit the title in `site.json` and rebuild. Observe the changed store path. @@ -17,7 +21,22 @@ Open `site.nix`: `runCommand` uses a standard environment **without a compiler** 3. Temporarily remove `jq` from `nativeBuildInputs`. The build fails with a missing command even if jq is installed on your host. Restore it. 4. Put malformed JSON in the fixture and read the failure with `nix build -L`. Restore valid JSON. -The fixture and renderer are version-controlled local files; building the page itself makes no network requests. The first invocation can still fetch nixpkgs and tools if they are not already present. +Restore the original title, then run the package-level content check: + +```sh +nix flake check -L +``` + +Now change the title once more and observe the check fail even though the site +package itself still builds. Restore `Hello, Gambiconf!` and make the check +pass. A package build proves the artifact can be produced; a check asserts a +property expected of that artifact. + +The fixture and renderer are version-controlled local files; building the page +itself makes no network requests. The first invocation can still fetch nixpkgs +and tools if they are not already present. Nix controls the declared build +environment, but deterministic inputs and instructions are still required for +bit-for-bit reproducible output. Module 04 performs this same transformation in a writable development environment. Module 07 serves a self-contained copy with nginx. diff --git a/03-derivations/02-static-site/flake.nix b/03-derivations/02-static-site/flake.nix index f9e3760..aa0247a 100644 --- a/03-derivations/02-static-site/flake.nix +++ b/03-derivations/02-static-site/flake.nix @@ -11,18 +11,42 @@ "aarch64-linux" "aarch64-darwin" ]; + mkSite = + system: + let + pkgs = nixpkgs.legacyPackages.${system}; + in + pkgs.callPackage ./site.nix { }; in { packages = forAllSystems ( system: let - pkgs = nixpkgs.legacyPackages.${system}; - site = import ./site.nix { inherit (pkgs) runCommand jq; }; + site = mkSite system; in { inherit site; default = site; } ); + + checks = forAllSystems ( + system: + let + pkgs = nixpkgs.legacyPackages.${system}; + site = mkSite system; + in + { + site-content = + pkgs.runCommand "training-site-content-check" + { + nativeBuildInputs = [ pkgs.gnugrep ]; + } + '' + grep -F '

Hello, Gambiconf!

' ${site}/index.html + touch "$out" + ''; + } + ); }; } diff --git a/03-derivations/README.md b/03-derivations/README.md index fbc9561..439f88a 100644 --- a/03-derivations/README.md +++ b/03-derivations/README.md @@ -1,6 +1,24 @@ # 03 · Derivations -A **derivation** is the bridge between the language and the store. A Nix expression evaluates to a derivation, which is written to the store as a `.drv` file. **Realising** it runs a sandboxed builder whose outputs become new store objects, or downloads those outputs from a substituter. +> A derivation can be thought of as a pure function that produces new store objects from existing store objects. +> +> Derivations are implemented as operating system processes that run in a sandbox. This sandbox by default only allows reading from store objects specified as inputs, and only allows writing to designated outputs to be captured as store objects. +> +> — [Nix Reference Manual 2.35, Glossary](https://nix.dev/manual/nix/2.35/glossary.html) + +In plain words: a derivation is a build recipe that Nix runs in isolation. A Nix expression evaluates to a derivation, which is written to the store as a `.drv` file. Then Nix **realises** it: + +> Ensure a store path is valid. +> +> This can be achieved by: +> +> - Fetching a pre-built store object from a substituter +> - Building the corresponding store derivation +> - Delegating to a remote machine and retrieving the outputs +> +> — [Nix Reference Manual 2.35, Glossary](https://nix.dev/manual/nix/2.35/glossary.html) + +In other words, `nix build` either downloads the result or builds it. ``` .nix ──evaluate──▶ derivation ──instantiate──▶ /nix/store/…-foo.drv ──realise──▶ /nix/store/…-foo @@ -9,22 +27,18 @@ A **derivation** is the bridge between the language and the store. A Nix express **Prerequisites:** [01 · Language](../01-nix-language/README.md), [02 · Store](../02-nix-store/README.md) -## Reading order -1. [derivations.md](derivations.md): `name`/`system`/`builder`, outputs, and how attributes become env vars -2. [advanced-attributes.md](advanced-attributes.md): output checks, structured attrs, fixed-output and content-addressed derivations -3. [import-from-derivation.md](import-from-derivation.md): when evaluation waits on a build, and why that hurts -4. [distributed-builds.md](distributed-builds.md): remote builders, `max-jobs` vs `cores` -5. [debugging.md](debugging.md): `--show-trace`, `nix repl`, tracing, and keeping failed builds - -## Try it +## Core workshop path -Run these standalone flakes in order, using their supplied locks: +Read [derivations.md](derivations.md) through the evaluation, instantiation, +and realisation distinction, then run these standalone flakes in order using +their supplied locks. | Exercise | Time | Result | |---|---|---| -| [00 · Raw derivation](00-raw-derivation/README.md) | 5 min | A text file built by a declared Bash | -| [01 · GNU Hello](01-gnu-hello/README.md) | 10–15 min | A compiled and checked executable | -| [02 · Static site](02-static-site/README.md) | 5–10 min | HTML generated from local JSON | +| [00 · Raw derivation](00-raw-derivation/README.md) | 10 min | Inspect a `.drv` and build a text file | +| [01 · GNU Hello](01-gnu-hello/README.md) | 30 min | Compile, check, inspect, and debug an executable | +| [02 · Static site](02-static-site/README.md) | 20 min | Package local data and verify generated HTML | +| [`callPackage` refactor](../06-nixpkgs/packaging.md#simplify-the-wrapper) | 10 min | Let nixpkgs inject recipe dependencies | From the raw-derivation directory: @@ -34,15 +48,33 @@ nix build -L cat result ``` -Keep advanced attributes, IFD and distributed builds as reference or extension material after the core exercises. [Module 06](../06-nixpkgs/README.md) deepens the packaging model with `callPackage` and an optional `icat` challenge from nix.dev. +For failures, use `nix build -L`, then `nix log` on the failed or named +derivation. Change one input at a time and restore deliberate failures before +continuing. + +## Extension material + +These topics are intentionally outside the three-hour workshop: + +1. [Advanced attributes](advanced-attributes.md): output checks, structured + attributes, fixed-output and content-addressed derivations. +2. [Import from derivation](import-from-derivation.md): evaluation that waits + on builds and its performance cost. +3. [Distributed builds](distributed-builds.md): remote builders and + `max-jobs` versus `cores`. +4. [Debugging](debugging.md): evaluation tracing and preserving failed build + directories. + +[Module 06](../06-nixpkgs/README.md) continues with overrides, overlays, and an +optional dependency-debugging package after the core `callPackage` refactor. **Next:** [04 · Shells](../04-shells/README.md) shows how to use derivations as development environments. --- Sources: -- -- -- -- -- +- +- +- +- +- - diff --git a/03-derivations/advanced-attributes.md b/03-derivations/advanced-attributes.md index 73e7d4f..d230658 100644 --- a/03-derivations/advanced-attributes.md +++ b/03-derivations/advanced-attributes.md @@ -45,21 +45,24 @@ unsafeDiscardReferences.out = true; # skip reference scanning, e.g. for disk i - `outputHashAlgo`: `"sha256"`, `"sha512"`, `"sha1"`, `"blake3"`, or `null` when `outputHash` is SRI (`"sha256-…="`). - Convert hash formats with `builtins.convertHash` or `nix hash convert`. +> A store derivation where a cryptographic hash of the output is determined in advance using the `outputHash` attribute, and where the `builder` executable has access to the network. +> +> — [Nix Reference Manual 2.35, Glossary: fixed-output derivation](https://nix.dev/manual/nix/2.35/glossary.html) + +In practice you don't write these attributes yourself. Nixpkgs fetchers set them for you, as in the GNU Hello exercise: + ```nix -# a hand-rolled fixed-output fetch -derivation { - name = "src.tar.gz"; - system = builtins.currentSystem; - builder = "/bin/sh"; - args = [ "-c" "curl -L https://… -o $out" ]; - outputHash = "sha256-AAAA…="; - outputHashMode = "flat"; -} +src = fetchurl { + url = "https://ftp.gnu.org/gnu/hello/hello-${version}.tar.gz"; + sha256 = "1ayhp9v4m4rdhjmnl2bq3cibrbqqkgjbl3s7yk2nhlh8vj3ay16g"; +}; ``` +From `01-gnu-hello/`, `nix derivation show .#hello.src` shows that the source's `out` output carries a fixed `hash` (in SRI form) and `"method": "flat"`. A hand-written fixed-output derivation would still need its downloader (and TLS certificates) from the store; a host `/bin/sh` with `curl` is not a declared builder. + ## See also - [derivations.md](derivations.md) - [../02-nix-store/store-objects.md](../02-nix-store/store-objects.md): the content-addressing methods --- -Source: +Source: diff --git a/03-derivations/debugging.md b/03-derivations/debugging.md index 91011a1..4f3a093 100644 --- a/03-derivations/debugging.md +++ b/03-derivations/debugging.md @@ -46,11 +46,19 @@ The source page leaves these sections as TODO. They are filled in here from the - `builtins.trace "msg" value`, `lib.debug.traceVal`, and `lib.debug.traceSeq` print during evaluation (see [../01-nix-language/builtins.md](../01-nix-language/builtins.md)). - `nix eval --debugger …` or `builtins.break` gives you an interactive debugger at the error or breakpoint. - `NIX_DEBUG=7` (set as a derivation attribute) makes stdenv's setup scripts very verbose, printing every command. -- `nix build --keep-failed` keeps the build dir for inspection. Adding `breakpointHook` to `nativeBuildInputs` pauses a failing build so you can attach with `cntr`. +- `nix build --keep-failed` keeps the build dir for inspection. +- `breakpointHook` (Linux only), as described in the Nixpkgs manual: + + > This hook makes a build pause instead of stopping when a failure occurs. It prevents Nix from cleaning up the build environment immediately and allows the user to attach to the build environment. Upon a build error, it will print instructions that can be used to enter the environment for debugging. The `breakpointHook` is only available on Linux. To use it, add `breakpointHook` to `nativeBuildInputs` in the package to be inspected. + > + > — [Nixpkgs manual, breakpointHook](https://nixos.org/manual/nixpkgs/unstable/#breakpointhook) ## See also - [import-from-derivation.md](import-from-derivation.md) - [../05-flakes/](../05-flakes/README.md): flake refs used by `:lf` --- -Source: +Sources: +- (community guide; structure of this note) +- (official `nix repl` reference) +- diff --git a/03-derivations/derivations.md b/03-derivations/derivations.md index a4b8ab3..80a72c5 100644 --- a/03-derivations/derivations.md +++ b/03-derivations/derivations.md @@ -65,4 +65,4 @@ The runnable [raw derivation flake](00-raw-derivation/README.md) supplies Bash a - [../06-nixpkgs/stdenv.md](../06-nixpkgs/stdenv.md): `stdenv.mkDerivation`, the wrapper you'll really use --- -Source: +Source: diff --git a/03-derivations/distributed-builds.md b/03-derivations/distributed-builds.md index 4f8d13e..5848ad3 100644 --- a/03-derivations/distributed-builds.md +++ b/03-derivations/distributed-builds.md @@ -52,5 +52,5 @@ On a 24-core machine: --- Sources: -- -- +- +- diff --git a/03-derivations/import-from-derivation.md b/03-derivations/import-from-derivation.md index 20ab4f4..555495c 100644 --- a/03-derivations/import-from-derivation.md +++ b/03-derivations/import-from-derivation.md @@ -42,4 +42,4 @@ Generating Nix code from a lock file (e.g. `cabal2nix`, some `*2nix` tools), or - [debugging.md](debugging.md) --- -Source: +Source: diff --git a/04-shells/README.md b/04-shells/README.md index 89cc7b5..8725c43 100644 --- a/04-shells/README.md +++ b/04-shells/README.md @@ -4,15 +4,18 @@ Use the same locked flake interface to enter a development environment: **`nix d **Prerequisites:** [03 · Derivations](../03-derivations/README.md). -## Hands-on order +## Three-hour workshop -1. [Plain flake shell](plain-flake-shell/README.md), 10 minutes: a compiler-free jq workspace with local data. -2. From the GNU Hello exercise, `nix develop .#hello`: enter an existing package's build environment and reuse its dependencies. -3. [Devenv flake shell](devenv-shell/README.md), optional 5–10 minutes: the same task with named project commands. +1. [Plain flake shell](plain-flake-shell/README.md), 10 minutes: a + compiler-free jq workspace with local data. +2. From the GNU Hello exercise, `nix develop .#hello`: contrast a package's + compiler-bearing build environment with the tool-only project shell. +3. Read the [devenv comparison](devenv-shell/README.md) as an instructor-led + code walkthrough. Run it only if its additional closure was prewarmed. The core shell adds only jq. Avoid language toolchains, dependency installation from npm/PyPI, API calls and background services during this introduction. The supplied locks share the training image's nixpkgs revision; devenv has additional framework dependencies and should be warmed separately. -## Reading order +## Extended reading order 1. [declarative-shells.md](declarative-shells.md): `devShells`, `mkShellNoCC`, variables and hooks. 2. [ad-hoc-shells.md](ad-hoc-shells.md): temporary tools with `nix shell` and explicit input selection. @@ -31,5 +34,5 @@ nix shell --inputs-from . nixpkgs#jq # temporary tools using this flake's input --- Sources: -- +- - diff --git a/04-shells/ad-hoc-shells.md b/04-shells/ad-hoc-shells.md index 21f81a2..b2e55d4 100644 --- a/04-shells/ad-hoc-shells.md +++ b/04-shells/ad-hoc-shells.md @@ -24,5 +24,5 @@ You may encounter `nix-shell -p jq` in older documentation. It uses the lookup-p --- Sources: -- -- +- +- diff --git a/04-shells/declarative-shells.md b/04-shells/declarative-shells.md index b7f9c2a..72baf9c 100644 --- a/04-shells/declarative-shells.md +++ b/04-shells/declarative-shells.md @@ -8,7 +8,7 @@ pkgs.mkShellNoCC { packages = [ pkgs.jq ]; REPORT_TITLE = "Gambiconf training"; shellHook = '' - printf 'Try: bash report.sh\n' + printf 'Try: bash report.sh, or jq -r -f render.jq site.json\n' ''; } ``` diff --git a/04-shells/devenv-shell/README.md b/04-shells/devenv-shell/README.md index c5946f2..5b741ed 100644 --- a/04-shells/devenv-shell/README.md +++ b/04-shells/devenv-shell/README.md @@ -1,4 +1,9 @@ -# The same workspace with devenv · optional, 5–10 minutes +# The same workspace with devenv - optional, 5-10 minutes + +In the three-hour workshop, compare `devenv.nix` with the plain shell's +`devshell.nix`. Identify `packages`, `env`, named `scripts`, and the startup +hook. Running the commands below is optional because devenv's additional input +graph is not included in the minimal offline image. From this directory: diff --git a/04-shells/nix-shell-vs-nix-develop.md b/04-shells/nix-shell-vs-nix-develop.md index b82d43b..cb95dda 100644 --- a/04-shells/nix-shell-vs-nix-develop.md +++ b/04-shells/nix-shell-vs-nix-develop.md @@ -41,6 +41,6 @@ Older projects may use `nix-shell`, `shell.nix`, or `#! nix-shell` scripts. They --- Sources: -- -- -- +- +- +- diff --git a/04-shells/plain-flake-shell/README.md b/04-shells/plain-flake-shell/README.md index aabb9a9..339fd6a 100644 --- a/04-shells/plain-flake-shell/README.md +++ b/04-shells/plain-flake-shell/README.md @@ -37,5 +37,5 @@ From `03-derivations/01-gnu-hello/`, run `nix develop .#hello`. Unlike this tool --- Sources: -- +- - diff --git a/05-flakes/README.md b/05-flakes/README.md index 45c4949..0920735 100644 --- a/05-flakes/README.md +++ b/05-flakes/README.md @@ -4,7 +4,11 @@ You have used flakes since [module 00](../00-getting-started/README.md). Now mai **Prerequisites:** [01 · Language](../01-nix-language/README.md), [03 · Derivations](../03-derivations/README.md), [04 · Development shells](../04-shells/README.md). -## Workshop +## Extended workshop + +The three-hour core introduces inputs, locks, packages, shells, checks, and +NixOS configurations where they are used. This composition exercise is a +15-20-minute follow-up rather than part of the timed core. Work through the standalone [composition example](composition/README.md), 15–20 minutes: @@ -28,4 +32,4 @@ Keep early flake wrappers thin. Package recipes remain ordinary functions; flake --- Sources: - -- +- diff --git a/05-flakes/composition/README.md b/05-flakes/composition/README.md index 88c6dd5..12fe33c 100644 --- a/05-flakes/composition/README.md +++ b/05-flakes/composition/README.md @@ -1,6 +1,6 @@ # Compose two flakes · 15–20 minutes -This directory contains a consumer flake and a bundled `site/` flake copied from module 03. Copy the **whole directory** to keep the example standalone. Relative path inputs in this form require the course's Nix 2.34 or newer. +This directory contains a consumer flake and a bundled `site/` flake copied from module 03. Copy the **whole directory** to keep the example standalone. `path:./site` is resolved relative to the directory containing this `flake.nix`, and must stay inside the same source tree ([Nix manual 2.35, path inputs](https://nix.dev/manual/nix/2.35/command-ref/new-cli/nix3-flake.html#path-fetcher)). Use the training guest's Nix 2.35; very old Nix releases rejected relative path inputs. ```sh nix flake metadata @@ -43,5 +43,5 @@ Larger repositories can use flake-parts to organize these per-system outputs. Th --- Sources: -- +- - diff --git a/05-flakes/composition/flake.nix b/05-flakes/composition/flake.nix index 36e160c..4cdb476 100644 --- a/05-flakes/composition/flake.nix +++ b/05-flakes/composition/flake.nix @@ -48,10 +48,15 @@ pkgs = nixpkgs.legacyPackages.${system}; in { - page = pkgs.runCommand "check-training-page" { } '' - grep -F '

Hello, Gambiconf!

' ${site.packages.${system}.default}/index.html - touch "$out" - ''; + page = + pkgs.runCommand "check-training-page" + { + nativeBuildInputs = [ pkgs.gnugrep ]; + } + '' + grep -F '

Hello, Gambiconf!

' ${site.packages.${system}.default}/index.html + touch "$out" + ''; } ); }; diff --git a/05-flakes/composition/site/flake.nix b/05-flakes/composition/site/flake.nix index 7c167b3..3f1cc78 100644 --- a/05-flakes/composition/site/flake.nix +++ b/05-flakes/composition/site/flake.nix @@ -14,9 +14,7 @@ in { packages = forAllSystems (system: { - default = import ./site.nix { - inherit (nixpkgs.legacyPackages.${system}) runCommand jq; - }; + default = nixpkgs.legacyPackages.${system}.callPackage ./site.nix { }; }); }; } diff --git a/05-flakes/flake-commands.md b/05-flakes/flake-commands.md index 05bcc54..a73b3b4 100644 --- a/05-flakes/flake-commands.md +++ b/05-flakes/flake-commands.md @@ -53,5 +53,5 @@ Useful flags (on most commands): `--override-input nixpkgs github:NixOS/nixpkgs/ --- Sources: -- +- - diff --git a/05-flakes/flake-schema.md b/05-flakes/flake-schema.md index 764b371..0e8fd91 100644 --- a/05-flakes/flake-schema.md +++ b/05-flakes/flake-schema.md @@ -74,4 +74,4 @@ Flakes have no `system` argument, so you generate per-system outputs yourself. T - [../07-nixos/configuration.md](../07-nixos/configuration.md): `nixosConfigurations` --- -Source: (sections "Flake format", "Flake inputs", "Lock files"). Output conventions are summarised from `nix flake check`. +Source: (sections "Flake format", "Flake inputs", "Lock files"). Output conventions are summarised from `nix flake check`. diff --git a/06-nixpkgs/README.md b/06-nixpkgs/README.md index 9cda7c5..b63e23c 100644 --- a/06-nixpkgs/README.md +++ b/06-nixpkgs/README.md @@ -4,11 +4,22 @@ **Prerequisites:** [03 · Derivations](../03-derivations/README.md) and [01 · Language](../01-nix-language/README.md) -## Reading order -1. [callpackage.md](callpackage.md): recipes as functions, automatic arguments, `callPackageWith` -2. [packaging.md](packaging.md): refactor module 03's Hello wrapper, then build the optional standalone [icat flake](icat/README.md) and diagnose missing dependencies -3. [stdenv.md](stdenv.md): `mkDerivation`, phases and hooks, `nativeBuildInputs` vs `buildInputs`, `finalAttrs` -4. [overrides-and-overlays.md](overrides-and-overlays.md): `override` / `overrideAttrs` / overlays (`final` vs `prev`) +## Three-hour workshop + +Complete only the [`callPackage` refactor](packaging.md#simplify-the-wrapper) +after the module 03 packages. It connects package functions to the nixpkgs +package set without opening the larger customization topics below. + +## Extended reading order + +1. [callpackage.md](callpackage.md): recipes as functions, automatic + arguments, and `callPackageWith`. +2. [packaging.md](packaging.md): build the optional standalone + [icat flake](icat/README.md) and diagnose missing dependencies. +3. [stdenv.md](stdenv.md): phases, hooks, dependency categories, and + `finalAttrs`. +4. [overrides and overlays](overrides-and-overlays.md): `override`, + `overrideAttrs`, and package-set overlays. ## Anatomy of a recipe ```nix diff --git a/06-nixpkgs/callpackage.md b/06-nixpkgs/callpackage.md index e1770ab..1ad912b 100644 --- a/06-nixpkgs/callpackage.md +++ b/06-nixpkgs/callpackage.md @@ -21,7 +21,13 @@ rec { nix run .#hello-folks # Hello, folks! ``` - For each function argument, `callPackage` passes `pkgs.` if it exists. The second argument supplies or overrides specific values. -- Real-world use: `callPackage ./go-program.nix { buildGoModule = buildGo121Module; }` swaps the toolchain. +- Real-world use, as nix.dev describes it: + + > For example, functions which represent Go programs often have a parameter `buildGoModule`. It is common to find expressions like `callPackage ./go-program.nix { buildGoModule = buildGo116Module; }` to change the default Go compiler version. + > + > — [nix.dev, Package parameters and overrides with `callPackage`](https://nix.dev/tutorials/callpackage) + + `buildGo116Module` has since been removed from nixpkgs. The course's pin provides builders such as `buildGo126Module` and `buildGo127Module`; the pattern is the same. - `.override` changes the **function arguments**, whether they were filled in automatically or passed explicitly (see [overrides-and-overlays.md](overrides-and-overlays.md)). ## Your own package set with `callPackageWith` diff --git a/06-nixpkgs/icat/README.md b/06-nixpkgs/icat/README.md index 9450ef2..9c75978 100644 --- a/06-nixpkgs/icat/README.md +++ b/06-nixpkgs/icat/README.md @@ -24,4 +24,4 @@ Start from the working recipe, making one temporary edit at a time: The tutorial uses the older `xorg.libX11` name; this pin provides `libx11`. Fetching from GitHub hashes the unpacked source tree, unlike `fetchurl`'s archive-byte hash in Hello. -This example downloads image and X11 libraries, so it is an extension rather than part of the small-download core or default VM preload. +This example downloads image and X11 libraries, so it is an extension rather than part of the small-download core. Its closure is preloaded in the training image so the optional exercise also works offline. diff --git a/06-nixpkgs/packaging.md b/06-nixpkgs/packaging.md index 05dd06c..fe6eb11 100644 --- a/06-nixpkgs/packaging.md +++ b/06-nixpkgs/packaging.md @@ -4,7 +4,20 @@ You already compiled [GNU Hello](../03-derivations/01-gnu-hello/README.md) with ## Simplify the wrapper -Inside that flake's per-system definition, replace: +Work in the GNU Hello exercise directory: + +```sh +cd ~/nix-training/03-derivations/01-gnu-hello +``` + +Before editing, record the package's derivation path: + +```sh +before=$(nix path-info --derivation .#hello) +printf '%s\n' "$before" +``` + +In `flake.nix`, inside the per-system `let` block, replace: ```nix hello = import ./hello.nix { @@ -18,7 +31,17 @@ with: hello = pkgs.callPackage ./hello.nix { }; ``` -Run `nix build` and `nix run`. The derivation is the same: dependency injection changed, not the package's build inputs. Continue with [callpackage.md](callpackage.md) for overrides. +Run `nix build` and `nix run`, then compare the build plan: + +```sh +after=$(nix path-info --derivation .#hello) +test "$before" = "$after" +``` + +The derivation is the same: dependency injection changed, not the package's +build inputs. `callPackage` inspects the package function's argument names and +supplies matching attributes from nixpkgs. Continue with +[callpackage.md](callpackage.md) for overrides after the core workshop. ## A package with dependencies diff --git a/06-nixpkgs/stdenv.md b/06-nixpkgs/stdenv.md index 4d317ec..1701e8d 100644 --- a/06-nixpkgs/stdenv.md +++ b/06-nixpkgs/stdenv.md @@ -67,7 +67,15 @@ The shell env differs slightly from the sandbox (TMPDIR, writable outputs, impur ## Other useful attributes - `enableParallelBuilding = true` passes `-j$NIX_BUILD_CORES` (the default for cmake, meson, qmake). - `NIX_DEBUG = 1…7` controls verbosity: at 1+ the compiler and linker wrappers print full command lines, at 6+ you get `set -x` in setup, and at 7 also in the wrappers. -- `__structuredAttrs = true` is now preferred (and required for new top-level packages). Env vars go in `env = { … };`. +- `__structuredAttrs = true`. The Nixpkgs manual says: + + > `__structuredAttrs` is a complete replacement for the way attributes are handled currently, and is the preferred default. + > + > All new top level packages must enable `__structuredAttrs`. + > + > — [Nixpkgs manual, `__structuredAttrs`](https://nixos.org/manual/nixpkgs/unstable/#var-stdenv-__structuredAttrs) + + With it enabled, attributes meant as environment variables go in `env = { … };`. - `doCheck`, `separateDebugInfo`, `meta`, `passthru`. ## See also diff --git a/07-nixos/README.md b/07-nixos/README.md index 755dc67..de46e3f 100644 --- a/07-nixos/README.md +++ b/07-nixos/README.md @@ -4,18 +4,22 @@ NixOS applies the same dependency model to a system: packages, `/etc`, services, **Prerequisites:** [06 · Nixpkgs](../06-nixpkgs/README.md). Flakes have been the course interface since module 00. -## Thirty-minute hands-on lab +## 23-minute workshop capstone Use the standalone [web-server lab](web-server/README.md) inside the updated training image: 1. Inspect its flake and imported modules. 2. Switch to a system serving the static page from module 03. -3. Change the page and switch again. -4. Roll back and observe the original page. +3. Change the page to the prebuilt second version and switch again. +4. Roll back and observe the original page and system generation. -The image preloads the core sources and tools and supplies `nixos-rebuild`. Boot with at least 2 GiB RAM before starting the lab (`make run VM_MEMORY=2048`). The core package/shell exercises and this switch/rollback workflow are checked offline by the image workflow. Optional devenv and icat extensions are not preloaded. +The image preloads the core sources and tools, the optional `icat` exercise, and `nixos-rebuild`. Boot with at least 2 GiB RAM before starting the lab (`make run VM_MEMORY=2048`). The core package/shell exercises, `icat`, and this switch/rollback workflow are checked offline by the image workflow. The optional devenv extension is not preloaded. -## Reading order +The [two-machine integration test](vm-testing.md) is a short instructor +walkthrough in the core workshop. Run it on a prewarmed Linux host rather than +nested inside the training guest. + +## Extended reading order 1. [configuration.md](configuration.md): system outputs, building versus activation, and VM entry points. 2. [module-system.md](module-system.md): options, types, merging and imports. diff --git a/07-nixos/vm-testing.md b/07-nixos/vm-testing.md index 02e4809..1802ea4 100644 --- a/07-nixos/vm-testing.md +++ b/07-nixos/vm-testing.md @@ -1,6 +1,14 @@ # Integration testing with NixOS VMs -The web-server flake includes an optional **two-machine test**, separate from the thirty-minute hands-on lab. `testers.runNixOSTest` boots a server using the same `web-server.nix` module and a client that requests the page through the virtual network. +The web-server flake includes an optional **two-machine test**, separate from +the system switch lab. `testers.runNixOSTest` boots a server using the same +`web-server.nix` module and a client that requests the page through the virtual +network. + +In the three-hour workshop, read `test.nix` and identify `nodes`, +`testScript`, service readiness, port readiness, and the client assertion. The +instructor may demonstrate the build on a prewarmed Linux host with KVM. Do not +run it nested inside the training guest. From `web-server/`, on a matching Linux builder with KVM: diff --git a/07-nixos/web-server/README.md b/07-nixos/web-server/README.md index c597823..3cbfabe 100644 --- a/07-nixos/web-server/README.md +++ b/07-nixos/web-server/README.md @@ -1,10 +1,10 @@ -# A web server, two generations, and rollback · 30 minutes +# A web server, two generations, and rollback - 23 minutes Run this lab **inside the downloadable training guest**, logged in as `gambi`. It describes that guest's disk layout and credentials. It is not a configuration for your host. The directory is standalone and includes its own page recipe, fixture and lock. -The prepared image provides `/home/gambi/nix-training`, nixpkgs, the core build environments, rebuild tooling and **both exact web-system versions** used below. Boot it before starting the clock. Existing images published before this lab need rebuilding or a new release. +The prepared image provides `/home/gambi/nix-training`, nixpkgs, the core build environments, rebuild tooling and **both exact web-system versions** used below. Boot it before starting the clock. -## 0–5 minutes: inspect the configuration +## 0-3 minutes: inspect the configuration ```sh cd ~/nix-training/07-nixos/web-server @@ -15,7 +15,7 @@ nix eval --offline ".#nixosConfigurations.$host.config.services.nginx.enable" Read `configuration.nix` and its imports. `guest.nix` preserves access and the installed state version; `disk.nix` matches the image's partitions; `web-server.nix` adds nginx and a firewall rule. `root = site` passes a built store directory to a system service. -## 5–15 minutes: activate version one +## 3-9 minutes: activate version one ```sh sudo nixos-rebuild switch --offline --flake ".#$host" @@ -34,7 +34,7 @@ ssh -N -L 8080:127.0.0.1:80 gambiconf Open `http://localhost:8080`. This tunnels through the existing SSH forwarding; QEMU needs no additional port mapping. A localhost request or SSH tunnel does not test the guest's ingress firewall rule. -## 15–22 minutes: change the page +## 9-15 minutes: change the page Edit only the title in `site.json` to `Version two` with `nano site.json`, then: @@ -46,7 +46,7 @@ readlink /run/current-system Expected: the new heading and a different system store path. Both specified states are prebuilt, so this exercise needs no downloads. The site recipe normalizes JSON before building: changing whitespace in your editor does not invalidate the prepared version. Other titles or configuration changes can require additional build tools; warm those separately for an extended demo. -## 22–27 minutes: roll back +## 15-20 minutes: roll back ```sh sudo nixos-rebuild switch --rollback --flake ".#$host" @@ -56,7 +56,7 @@ readlink /run/current-system Expected: version one's heading and system path return. Keep the two switches adjacent so the previous generation is version one. The flake reference also lets `nixos-rebuild` resolve its own tool from the pin, without falling back to a legacy channel lookup. -## 27–30 minutes: explain what changed +## 20-23 minutes: explain what changed - The system generation selects a page, nginx configuration and service definitions together. - The site is generated during a build, not at service startup. diff --git a/07-nixos/web-server/test.nix b/07-nixos/web-server/test.nix index 1c9628d..5901f56 100644 --- a/07-nixos/web-server/test.nix +++ b/07-nixos/web-server/test.nix @@ -10,9 +10,14 @@ }; testScript = '' start_all() - server.wait_for_unit("nginx.service") - server.wait_for_open_port(80) - client.wait_for_unit("network.target") - client.wait_until_succeeds("curl --fail --silent --show-error --max-time 5 http://server/ | grep -F '

Hello, Gambiconf!

'") + with subtest("nginx becomes ready"): + server.wait_for_unit("nginx.service", timeout=60) + server.wait_for_open_port(80, timeout=30) + with subtest("client receives generated content"): + client.wait_until_succeeds( + "curl --fail --silent --show-error --max-time 5 http://server/ | grep -F '

Hello, Gambiconf!

'" + " && curl --fail --silent --show-error --max-time 5 http://server/ | grep -F '
  • NixOS
  • '", + timeout=60, + ) ''; } diff --git a/08-declarative-infra/README.md b/08-declarative-infra/README.md index 70b1589..776a2ff 100644 --- a/08-declarative-infra/README.md +++ b/08-declarative-infra/README.md @@ -1,5 +1,10 @@ # 08 · Declarative Infrastructure +> **Advanced follow-up:** this module is not part of the three-hour workshop. +> It involves privileged remote access, disk installation, cloud state and +> billing, signing keys, and public services. Use a separate sandbox with +> reviewed plans, explicit teardown, and rollback procedures. + This module puts everything together: **provision machines, install NixOS on them, deploy updates, and share build results** across a fleet, all from version-controlled Nix code. **Prerequisites:** [07 · NixOS](../07-nixos/README.md), plus [02 · Store](../02-nix-store/README.md) for caching concepts diff --git a/FACILITATOR.md b/FACILITATOR.md new file mode 100644 index 0000000..3b0b566 --- /dev/null +++ b/FACILITATOR.md @@ -0,0 +1,108 @@ +# Facilitator Guide + +This guide supports the instructor-led path in [WORKSHOP.md](WORKSHOP.md). The +learner clock assumes image download, QEMU boot, and SSH login have already +been tested. + +## Audience and Scope + +The core audience is developers familiar with a Unix shell and ordinary source +builds but new to Nix. The language segment teaches enough to read package +recipes. It deliberately excludes a complete syntax survey, overlays, +cross-compilation, distributed builds, and deployment to real machines. + +The hard stop is three hours. Prefer dropping the devenv demonstration or +shortening discussion over rushing the packaging labs or rollback capstone. + +## Preflight + +Run this before distributing an image: + +```sh +make test +``` + +For an interactive rehearsal: + +```sh +make run +ssh -p 2222 gambi@127.0.0.1 +cd ~/nix-training +``` + +Confirm that: + +- The guest has at least 2 GiB RAM. +- `~/nix-training` is writable. +- The supplied locks are unchanged. +- Core builds and the plain shell work with guest networking restricted. +- Both specified web-system generations switch and roll back. +- Port 2222 is free for learners and port 2223 is free for acceptance checks. + +Do not build the training image during the workshop. Do not depend on a cold +devenv download; the optional `icat` exercise is preloaded. Do not run the NixOS +integration test nested inside the guest. + +## Timing and Hard Stops + +| End | Segment | Hard stop | +|---|---|---| +| 0:10 | First build | Learners found the store path | +| 0:40 | Language | Learners can read the Hello recipe shape | +| 0:55 | Store | References and closures distinguished | +| 1:05 | Raw derivation | `.drv` and output inspected | +| 1:35 | GNU Hello | Package built and phases identified | +| 1:55 | Local site | Missing dependency diagnosed and restored | +| 2:05 | `callPackage` and check | Static-site check passes | +| 2:15 | Break ends | All core files restored | +| 2:25 | Shell | Build and development environments contrasted | +| 2:37 | devenv and VM-test demos | No student nested VM build | +| 3:00 | NixOS capstone | Version two observed, then rolled back | + +## Teaching Thread + +Keep returning to one question: "Which inputs determine this artifact, and +where can we observe that relationship?" + +Use these comparisons: + +- Nix data resembles JSON, with functions and path values added. +- A package recipe is a function from dependencies to a derivation. +- A `.drv` is a build plan, not the build result. +- A runtime closure is deployable data, not the complete build toolchain. +- A cache substitutes an already-known output; a remote builder executes work. +- A shell supports editing; a derivation produces the final artifact. +- A NixOS test builds behavior into a derivation by running QEMU machines. +- A NixOS generation selects immutable system artifacts atomically. + +Do not claim that Nix automatically guarantees bit-reproducible outputs. +Reproducibility also requires deterministic source, instructions, and build +behavior. + +## QEMU Notes + +The image uses full-system QEMU, not user-mode emulation. KVM on Linux and HVF +on macOS accelerate compatible guests; TCG is the portable, slower fallback. +The launcher uses a disposable snapshot and binds SSH forwarding to localhost. + +If boot fails, record the QEMU version, architecture, firmware path, +accelerator, and image path. Check image integrity with `qemu-img check` before +changing the command. Use `VM_FIRMWARE` when the packaged EDK2 firmware cannot +be discovered. + +## Demonstration Fallbacks + +- If devenv is cold, compare the two Nix files without entering the shell. +- If KVM is unavailable, read `test.nix` and show previously captured successful + output; do not spend the workshop waiting for TCG. +- If a learner corrupts an exercise, pair them with a working VM or restart the + disposable guest. +- If the NixOS switch is slow, continue explaining generations while it builds; + do not change the title away from either prebuilt value. + +## Extended Material + +Module 05 composition, `icat`, overlays, advanced derivations, and module 08 +are post-workshop material. Module 08 includes privileged, stateful, billable, +or destructive operations and requires a separate environment, reviewed plans, +credentials, teardown instructions, and rollback procedures. diff --git a/GLOSSARY.md b/GLOSSARY.md new file mode 100644 index 0000000..a82a39c --- /dev/null +++ b/GLOSSARY.md @@ -0,0 +1,197 @@ +# Glossary + +Words you will meet in the first hour of the course. Each entry quotes the +official definition word for word and then adds one plain-language line of our +own, marked **In this course**. Omitted text is marked with `…`. + +Quoted material keeps its original license: the +[Nix Reference Manual](https://nix.dev/manual/nix/2.35/) is LGPL-2.1, +[nix.dev](https://nix.dev/) is CC-BY-SA-4.0, and the +[NixOS manual](https://nixos.org/manual/nixos/unstable/) is MIT. Follow the +links for the full text. + +## Nix and its language + +**Nix** + +> Nix is a purely functional package manager. This means that it treats packages like values in a purely functional programming language — packages are built by functions that don’t have side-effects, and they never change after they have been built. +> +> — [Nix Reference Manual 2.35, Introduction](https://nix.dev/manual/nix/2.35/introduction.html) + +In this course: the tool behind every `nix …` command you run. + +**Nix language** + +> The Nix language is designed for conveniently creating and composing derivations – precise descriptions of how contents of existing files are used to derive new files. It is a domain-specific, purely functional, lazily evaluated, dynamically typed programming language. +> +> — [nix.dev, Nix language basics](https://nix.dev/tutorials/nix-language) + +In this course: the language of every `.nix` file. Module 01 teaches enough of it to read package recipes. + +**Nix expression** + +> A syntactically valid use of the Nix language. +> +> — [Nix Reference Manual 2.35, Glossary](https://nix.dev/manual/nix/2.35/glossary.html) + +In this course: `hello.nix`, `flake.nix`, and anything you type into `nix repl`. + +**Nixpkgs** + +> The largest, most up-to-date software distribution in the world, and written in the Nix language. +> +> — [nix.dev, Nix language basics](https://nix.dev/tutorials/nix-language) + +In this course: the `nixpkgs` input that every exercise flake locks. + +## Building + +**derivation** + +> A derivation can be thought of as a pure function that produces new store objects from existing store objects. +> +> Derivations are implemented as operating system processes that run in a sandbox. This sandbox by default only allows reading from store objects specified as inputs, and only allows writing to designated outputs to be captured as store objects. +> +> — [Nix Reference Manual 2.35, Glossary](https://nix.dev/manual/nix/2.35/glossary.html) + +In this course: a build recipe. Module 03 inspects one before building it. + +**instantiate** + +> Translate a derivation expression into a store derivation. +> +> — [Nix Reference Manual 2.35, Glossary](https://nix.dev/manual/nix/2.35/glossary.html) + +In this course: the step that writes a `.drv` file. `nix derivation show` prints it. + +**realise** + +> Ensure a store path is valid. +> +> This can be achieved by: +> +> - Fetching a pre-built store object from a substituter +> - Building the corresponding store derivation +> - Delegating to a remote machine and retrieving the outputs +> +> — [Nix Reference Manual 2.35, Glossary](https://nix.dev/manual/nix/2.35/glossary.html) + +In this course: what `nix build` does. It either downloads or builds. + +**fixed-output derivation (FOD)** + +> A store derivation where a cryptographic hash of the output is determined in advance using the `outputHash` attribute, and where the `builder` executable has access to the network. +> +> — [Nix Reference Manual 2.35, Glossary](https://nix.dev/manual/nix/2.35/glossary.html) + +In this course: what `fetchurl` produces. The `sha256` in `hello.nix` is the hash declared in advance. + +**purity** + +> The assumption that equal Nix derivations when run always produce the same output. This cannot be guaranteed in general (e.g., a builder can rely on external inputs such as the network or the system time) but the Nix model assumes it. +> +> — [Nix Reference Manual 2.35, Glossary](https://nix.dev/manual/nix/2.35/glossary.html) + +In this course: this is why we never promise bit-for-bit reproducibility. + +## The store + +**store** + +> The Nix store is an abstraction to store immutable file system data (such as software packages) that can have dependencies on other such data. +> +> — [Nix Reference Manual 2.35, Nix Store](https://nix.dev/manual/nix/2.35/store/index.html) + +In this course: usually the `/nix/store` directory. + +**store object** + +> A store object consists of a file system object, references to other store objects, and other metadata. It can be referred to by a store path. +> +> — [Nix Reference Manual 2.35, Glossary](https://nix.dev/manual/nix/2.35/glossary.html) + +**store path** + +> The location of a store object in the file system, i.e., an immediate child of the Nix store directory. +> +> Example: `/nix/store/jf6gn2dzna4nmsfbdxsd7kwhsk6gnnlr-git-2.38.1` +> +> — [Nix Reference Manual 2.35, Glossary](https://nix.dev/manual/nix/2.35/glossary.html) + +In this course: the target of the `result` symlink that `nix build` creates. + +**reference** + +> An edge from one store object to another. +> +> — [Nix Reference Manual 2.35, Glossary](https://nix.dev/manual/nix/2.35/glossary.html) + +**closure** + +> The closure of a store path is the set of store paths that are directly or indirectly “reachable” from that store path; that is, it’s the closure of the path under the references relation. For a package, the closure of its derivation is equivalent to the build-time dependencies, while the closure of its output path is equivalent to its runtime dependencies. For correct deployment it is necessary to deploy whole closures, since otherwise at runtime files could be missing. +> +> — [Nix Reference Manual 2.35, Glossary](https://nix.dev/manual/nix/2.35/glossary.html) + +In this course: `nix path-info --recursive ./result` lists it. + +**substituter** + +> An additional store from which Nix can obtain store objects instead of building them. Often the substituter is a binary cache, but any store can serve as substituter. +> +> — [Nix Reference Manual 2.35, Glossary](https://nix.dev/manual/nix/2.35/glossary.html) + +In this course: `cache.nixos.org` is why most builds finish in seconds. + +**profile** + +> A symlink to the current user environment of a user, e.g., `/nix/var/nix/profiles/default`. +> +> — [Nix Reference Manual 2.35, Glossary](https://nix.dev/manual/nix/2.35/glossary.html) + +In this course: NixOS system generations work the same way. Switching a symlink is what makes rollback instant. + +## Flakes + +**flake** + +> Flakes are the unit for packaging Nix code in a reproducible and discoverable way. They can have dependencies on other flakes, making it possible to have multi-repository Nix projects. +> +> — [Nix Reference Manual 2.35, `nix flake`](https://nix.dev/manual/nix/2.35/command-ref/new-cli/nix3-flake.html) + +> `flake.nix` is a file that declares inputs and outputs with a standard structure. +> +> — [nix.dev, Flakes](https://nix.dev/concepts/flakes.html) + +In this course: every exercise directory is a flake. + +**flake.lock** + +> Inputs specified in `flake.nix` are typically “unlocked” in the sense that they don’t specify an exact revision. To ensure reproducibility, Nix will automatically generate and use a lock file called `flake.lock` in the flake’s directory. +> +> — [Nix Reference Manual 2.35, `nix flake`, Lock files](https://nix.dev/manual/nix/2.35/command-ref/new-cli/nix3-flake.html#lock-files) + +In this course: keep every supplied lock unchanged during the workshop. + +## NixOS + +**NixOS** + +> A Linux distribution that can be configured fully declaratively and is based on Nix and Nixpkgs. +> +> — [nix.dev, Nix language basics](https://nix.dev/tutorials/nix-language) + +**NixOS module** + +> Each NixOS module is a file that handles one logical aspect of the configuration, such as a specific kind of hardware, a service, or network settings. A module configuration does not have to handle everything from scratch; it can use the functionality provided by other modules for its implementation. Thus a module can declare options that can be used by other modules, and conversely can define options provided by other modules in its own implementation. +> +> — [NixOS manual, Writing NixOS Modules](https://nixos.org/manual/nixos/unstable/#sec-writing-modules) + +In this course: `web-server.nix` in module 07 is a module that defines nginx options. + +**rollback** + +> After running `nixos-rebuild` to switch to a new configuration, you may find that the new configuration doesn’t work very well. In that case, there are several ways to return to a previous configuration. +> +> — [NixOS manual, Rolling Back Configuration Changes](https://nixos.org/manual/nixos/unstable/#sec-rollback) + +In this course: `sudo nixos-rebuild switch --rollback` in the capstone lab. diff --git a/Makefile b/Makefile index 4d197e6..7190d3c 100644 --- a/Makefile +++ b/Makefile @@ -2,7 +2,7 @@ HOST_OS ?= $(shell uname -s) HOST_ARCH ?= $(shell uname -m) VM_SSH_PORT ?= 2222 TEST_SSH_PORT ?= 2223 -VM_MEMORY ?= 1024 +VM_MEMORY ?= 2048 ifneq ($(filter $(HOST_ARCH),arm64 aarch64),) VM_ARCH := aarch64 @@ -21,14 +21,31 @@ $(error Unsupported host OS: $(HOST_OS)) endif .DEFAULT_GOAL := help -.PHONY: help image vm run test +.PHONY: help tutorials slides slides-check slides-preview image vm run test help: @printf '%s\n' \ + 'make tutorials Build and check every native tutorial output' \ + 'make slides Build the seven module PDFs and combined deck (Linux only)' \ + 'make slides-check Build and validate slide PDFs (Linux only)' \ + 'make slides-preview Serve the Markdown decks with live reload (Linux only)' \ 'make image Build or download the $(VM_ARCH) qcow2 image' \ 'make vm Build the NixOS VM launcher (Linux only)' \ - 'make run Boot the image in QEMU (SSH on localhost:$(VM_SSH_PORT))' \ - 'make test Check the image, boot, SSH login, and sudo access' + 'make run Boot the image in disposable QEMU state (SSH on localhost:$(VM_SSH_PORT))' \ + 'make test Check boot, SSH, offline workshop exercises, and NixOS rollback' + +tutorials: + bash scripts/build-tutorials.sh + +slides: + nix build .#slides --out-link result-slides + +slides-check: + nix build .#checks.$$(nix eval --impure --raw --expr builtins.currentSystem).slides --no-link + +slides-preview: + nix develop .#slides --command marp --server \ + --theme-set slides/theme/nix-training.css slides ifeq ($(HOST_OS),Darwin) image: $(VM_IMAGE) @@ -63,5 +80,5 @@ else endif test: image - VM_ARCH='$(VM_ARCH)' VM_SSH_PORT='$(TEST_SSH_PORT)' \ + VM_ARCH='$(VM_ARCH)' VM_SSH_PORT='$(TEST_SSH_PORT)' VM_MEMORY='$(VM_MEMORY)' \ nix develop .#ci --command bash scripts/check-vm-image.sh '$(VM_IMAGE)' diff --git a/README.md b/README.md index 9c41b55..c75f828 100644 --- a/README.md +++ b/README.md @@ -4,14 +4,42 @@ Notes and tutorials for our Nix training, originally created for [Gambiconf 2026](https://gambiconf.dev/ "Gambiconf 2026"). -## What is Nix? +## Three-hour workshop -Nix is a **purely functional package manager**. It treats packages like values in a functional language: they are built by side-effect-free functions and never change after they are built. Each package lives in its own directory in the **Nix store**: +For the instructor-led course, follow [Nix in Three Hours](WORKSHOP.md). It +contains the required reading, hands-on checkpoints, and hard time boundaries. +Instructors should also use the [facilitator guide](FACILITATOR.md). The numbered +modules below remain the extended course and reference library. +## PDF slides + +The instructor decks for modules 01 through 07 are authored as Markdown under +[`slides/`](slides/README.md). The existing module notes remain the canonical, +detailed material. On Linux, build the seven individual PDFs and the combined +deck with: + +```sh +make slides +make slides-check ``` -/nix/store/q06x3jll2yfzckz2bzqak089p43ixkkq-firefox-33.1/ - └─ hash of the full build dependency graph ─┘ -``` + +`make slides-preview` starts Marp's local preview server. CI publishes the PDFs +as a workflow artifact; generated files are not committed or added to the +training image closure. + +## What is Nix? + +> Nix is a purely functional package manager. This means that it treats packages like values in a purely functional programming language — packages are built by functions that don’t have side-effects, and they never change after they have been built. Nix stores packages in the Nix store, usually the directory `/nix/store`, where each package has its own unique subdirectory such as +> +> ``` +> /nix/store/q06x3jll2yfzckz2bzqak089p43ixkkq-firefox-33.1/ +> ``` +> +> where `q06x3jll2yfz…` is a unique identifier for the package that captures all its dependencies (it’s a cryptographic hash of the package’s build dependency graph). This enables many powerful features. +> +> — [Nix Reference Manual 2.35, Introduction](https://nix.dev/manual/nix/2.35/introduction.html) + +In plain words: every build gets its own read-only folder, and the folder's name is derived from everything that went into the build. New terms are defined in the [glossary](GLOSSARY.md). That one idea leads to the rest: @@ -44,11 +72,12 @@ Nix runs on Linux, macOS and even Windows [Through NixOS-WSL](https://github.com ## How to use this repo -- Start at **00** and work through the modules in order. Flakes are the course's interface from the first exercise; module 05 explores them in depth. +- For the three-hour session, follow [WORKSHOP.md](WORKSHOP.md). For the extended course, start at **00** and work through the modules in order. Flakes are the course's interface from the first exercise; module 05 explores them in depth. - Each runnable exercise has a standalone `flake.nix` and `flake.lock`. Run its commands **inside its directory**. The root flake maintains this repository and builds the training VM. - Keep the supplied locks during the workshop. Examples share the root nixpkgs source and revision so cached dependencies can be reused. This pin supports x86_64 Linux, ARM64 Linux and Apple Silicon macOS; Intel Mac participants use the x86_64 guest. - Every note ends with the upstream **Source** links. The notes are condensed summaries, and the manual remains the authority. -- Nix manual pages are cited at version **2.34**. +- Nix manual pages are cited at version **2.35**, the Nix release the training guest runs (`nix --version`). +- New to the vocabulary? The [glossary](GLOSSARY.md) quotes the official definitions of the terms used in the early modules. - Use `nix build`, `nix run`, `nix develop` and `nix repl` (`:lf .`) as you go. Traditional commands appear only where they help explain an existing interface or inspect low-level state. ## Training VM @@ -83,10 +112,10 @@ The launcher uses your host's Nix store and writes guest state to `nix-training. Run a downloaded file directly with QEMU, or use `make run` to select the correct command. This example is for x86_64; for a local build, use `result/nix-training-x86_64.qcow2` as the drive path: ```sh -qemu-system-x86_64 -m 1024 -machine q35 -drive if=pflash,format=raw,readonly=on,file=/path/to/edk2-x86_64-code.fd -drive file=nix-training-x86_64.qcow2,format=qcow2,if=virtio -nic user,hostfwd=tcp:127.0.0.1:2222-:22 -nographic +qemu-system-x86_64 -m 2048 -machine q35 -drive if=pflash,format=raw,readonly=on,file=/path/to/edk2-x86_64-code.fd -drive file=nix-training-x86_64.qcow2,format=qcow2,if=virtio -nic user,hostfwd=tcp:127.0.0.1:2222-:22 -nographic ``` -Log in on the console as `gambi` with password `gambi`, or connect with `ssh -p 2222 gambi@127.0.0.1`. The updated image creates a writable `~/nix-training` workspace and preloads the pinned nixpkgs source, core exercise tools, Hello's compiler environment and both specified web-lab system versions. Start with `cd ~/nix-training/00-getting-started`. Keep the supplied locks and use at least 2 GiB RAM for the NixOS lab; optional devenv and icat need additional downloads. The guest enables `nix-command` and `flakes`. You can also add this to `~/.ssh/config`: +Log in on the console as `gambi` with password `gambi`, or connect with `ssh -p 2222 gambi@127.0.0.1`. The updated image creates a writable `~/nix-training` workspace and preloads the pinned nixpkgs source, core exercise tools, Hello's compiler environment, the optional `icat` exercise and both specified web-lab system versions. Start with `cd ~/nix-training/00-getting-started`. Keep the supplied locks and use at least 2 GiB RAM for the NixOS lab; optional devenv needs additional downloads. The guest enables `nix-command` and `flakes`. You can also add this to `~/.ssh/config`: ``` Host gambiconf @@ -104,4 +133,4 @@ ssh gambiconf ``` --- -Source: +Source: diff --git a/README.pt-br.md b/README.pt-br.md index db5e004..ec3cf8b 100644 --- a/README.pt-br.md +++ b/README.pt-br.md @@ -6,15 +6,29 @@ Material do treinamento de Nix criado para a [Gambiconf 2026](https://gambiconf. ## Como seguir o curso -Comece pelo módulo **00**. Usamos flakes desde o primeiro exercício, com `nix build`, `nix run` e `nix develop`. O módulo 05 aprofunda o que você já terá utilizado. +Para o workshop de três horas, siga [Nix in Three Hours](WORKSHOP.md). O roteiro +marca o conteúdo obrigatório, os exercícios práticos e os limites de tempo. O +[guia do instrutor](FACILITATOR.md) cobre preparação e alternativas para as +demonstrações. Os textos desses dois guias estão em inglês. + +Para o curso estendido, comece pelo módulo **00**. Usamos flakes desde o +primeiro exercício, com `nix build`, `nix run` e `nix develop`. O módulo 05 +aprofunda o que você já terá utilizado. Cada exemplo executável tem seu próprio `flake.nix` e `flake.lock` e pode ser copiado separadamente. Execute os comandos **dentro do diretório do exemplo**. O flake da raiz serve para manter o repositório e construir a VM do curso. Mantenha os arquivos de lock fornecidos: todos os exemplos usam a mesma revisão do nixpkgs para reaproveitar downloads. A revisão suporta Linux x86_64, Linux ARM64 e macOS Apple Silicon. Em um Mac Intel, faça os exercícios na VM Linux x86_64. +## Slides em PDF + +Os slides dos módulos 01 a 07 são escritos em Markdown no diretório +[`slides/`](slides/README.md). Os textos dos módulos continuam sendo a fonte +detalhada e canônica. No Linux, `make slides` gera os sete PDFs e a apresentação +completa; `make slides-check` valida os arquivos gerados. + ## Módulos -Os textos dos módulos estão em inglês. +Os textos dos módulos estão em inglês. O [glossário](GLOSSARY.md), também em inglês, cita as definições oficiais dos termos usados nos primeiros módulos. As páginas do manual do Nix são citadas na versão 2.35, a mesma usada pela VM do treinamento. | # | Módulo | Conteúdo | |---|---|---| @@ -25,7 +39,7 @@ Os textos dos módulos estão em inglês. | 04 | [Ambientes de desenvolvimento](04-shells/README.md) | `devShells`, ferramentas leves e ambientes de compilação | | 05 | [Flakes em profundidade](05-flakes/README.md) | composição, atualização de inputs, sistemas e checks | | 06 | [Nixpkgs](06-nixpkgs/README.md) | empacotamento, `callPackage`, overrides e overlays | -| 07 | [NixOS](07-nixos/README.md) | configuração, servidor web, gerações e rollback | +| 07 | [NixOS](07-nixos/README.md) | configuração do sistema, sistema de módulos, servidor web, gerações, rollback e testes com VMs | | 08 | [Infraestrutura declarativa](08-declarative-infra/README.md) | instalação remota, Terraform e cache binário | ## VM do treinamento @@ -34,6 +48,6 @@ As [releases](https://github.com/PerplexSystems/nix-training/releases/latest) of Pull requests constroem e validam as duas arquiteturas, sem enviar imagens para o armazenamento de artefatos do Actions. Na branch `main`, cada imagem validada é anexada diretamente a uma release em rascunho. A release só é publicada e marcada como mais recente quando os dois jobs passam e os dois arquivos estão completos. Execuções interrompidas podem deixar um rascunho não publicado; repetir os jobs que falharam reutiliza esse rascunho. -A imagem atualizada inclui um diretório editável `~/nix-training`, o nixpkgs fixado, as dependências dos exercícios principais e as ferramentas de rebuild. Comece com `cd ~/nix-training/00-getting-started`. Os exemplos opcionais de devenv e icat exigem downloads adicionais. `make test VM_MEMORY=2048` verifica os exercícios principais offline e o ciclo de switch/rollback do servidor web. +A imagem atualizada inclui um diretório editável `~/nix-training`, o nixpkgs fixado, as dependências dos exercícios principais, o exercício opcional de `icat` e as ferramentas de rebuild. Comece com `cd ~/nix-training/00-getting-started`. O exemplo opcional de devenv exige downloads adicionais. `make test VM_MEMORY=2048` verifica os exercícios principais offline e o ciclo de switch/rollback do servidor web. Consulte [Training VM](README.md#training-vm) para os comandos de construção, requisitos do QEMU e configuração de SSH. diff --git a/WORKSHOP.md b/WORKSHOP.md new file mode 100644 index 0000000..dcaf4a3 --- /dev/null +++ b/WORKSHOP.md @@ -0,0 +1,164 @@ +# Nix in Three Hours + +This is the instructor-led core workshop for developers who are comfortable +with a Unix shell and code but are new to Nix. The numbered modules contain +additional reference material; follow only the links on this page during the +timed session. + +## Outcomes + +After the workshop, you should be able to: + +1. Read the structure of a package recipe written in the Nix language. +2. Distinguish evaluation, derivation instantiation, and realisation. +3. Inspect a store path, its references, and its runtime closure. +4. Package upstream source and a local project with declared dependencies. +5. Use `callPackage`, a development shell, and a flake check. +6. Recognize a NixOS VM test and deploy a package as a NixOS service. +7. Switch between NixOS generations and roll back. + +## Before the Clock Starts + +Use the current [training VM](README.md#training-vm), booted with at least 2 +GiB of memory. The image contains the pinned source and all core dependencies. + +```sh +make run +ssh -p 2222 gambi@127.0.0.1 +cd ~/nix-training +nix --version +``` + +The password is `gambi`. Keep every supplied `flake.lock`, do not run garbage +collection, and run commands from the directory named by each exercise. The VM +uses a disposable disk overlay, so exiting QEMU is the final reset mechanism. + +## 0:00-0:10 - Build Before Theory + +Complete [00 - Getting started](00-getting-started/README.md). Stop after the +small experiment; the Git note is reference material. + +Checkpoint: + +```sh +readlink -f result +``` + +The result must be a path under `/nix/store`. Be ready to identify the flake +input, lock file, selected package output, and `result` symlink. + +## 0:10-0:40 - Read the Nix Language + +Complete the [guided language lab](01-nix-language/workshop.md). Its purpose is +to make package expressions readable, not to survey every language feature. + +Checkpoint: explain this expression as an outer function, a function call, and +an attribute-set argument: + +```nix +{ stdenv, fetchurl }: +stdenv.mkDerivation { + pname = "hello"; + version = "2.12"; + src = fetchurl { /* pinned source */ }; +} +``` + +## 0:40-0:55 - Follow an Artifact into the Store + +Complete the [core store lab](02-nix-store/README.md#15-minute-core-lab). + +Checkpoint: distinguish a direct reference from the complete runtime closure, +and explain why a compiler can be needed to build a program without being +needed to run it. + +## 0:55-2:05 - Derivations and Packaging + +Work through the core path in [03 - Derivations](03-derivations/README.md): + +| Time | Exercise | Focus | +|---|---|---| +| 0:55-1:05 | [Raw derivation](03-derivations/00-raw-derivation/README.md) | `.nix` to `.drv` to output | +| 1:05-1:35 | [GNU Hello](03-derivations/01-gnu-hello/README.md) | source, hash, stdenv phases, checks | +| 1:35-1:55 | [Static site](03-derivations/02-static-site/README.md) | local inputs and missing dependencies | +| 1:55-2:05 | [`callPackage`](06-nixpkgs/packaging.md#simplify-the-wrapper) | dependency injection and package check | + +For every failure, read the first meaningful error and `nix log` before editing +another attribute. Restore each deliberate failure before continuing. + +Checkpoint: + +```sh +cd ~/nix-training/03-derivations/02-static-site +nix flake check -L +``` + +The package and its generated-content check must pass. + +## 2:05-2:15 - Break and Buffer + +Use this time for slower evaluations or to restore exercise files. Do not start +an optional module if the core package check is not passing. + +## 2:15-2:25 - Development Environment + +In the [plain development shell](04-shells/plain-flake-shell/README.md), +run the opening interactive block and the "Run a command without opening an +interactive shell" block. Skip its experiments unless time remains. + +Checkpoint: explain the difference between `nix build`, `nix develop`, and +`nix develop .#hello`. An interactive shell is writable and can inherit host +state; it is not proof that a sandboxed package has declared every dependency. + +## 2:25-2:30 - devenv Comparison + +The instructor compares `04-shells/plain-flake-shell/devshell.nix` with +`04-shells/devenv-shell/devenv.nix`. Focus on packages, environment variables, +named scripts, and the startup hook. The devenv closure is not part of the +offline core image, so this is a code walkthrough unless it was prewarmed. + +## 2:30-2:37 - NixOS Tests Use QEMU + +Read `07-nixos/web-server/test.nix` with the instructor and identify its server, +client, readiness checks, and observable HTTP assertion. The instructor may run +`nix flake check -L` on a prewarmed Linux host with KVM. Do not run a nested VM +test inside the training guest. + +## 2:37-3:00 - NixOS Service and Rollback + +Complete the [web server lab](07-nixos/web-server/README.md). Keep its two +switches adjacent and use exactly `Version two` for the second title so both +states use the image's prebuilt closures. + +Final checkpoint: + +```text +site.json + render.jq + -> package in /nix/store + -> nginx document root + -> NixOS system generation + -> QEMU guest behavior + -> rollback to the previous generation +``` + +Rollback changes the selected system generation. It does not revert the edited +workspace file or arbitrary mutable service data. + +## Continue After the Workshop + +- [Flake composition](05-flakes/composition/README.md) +- [`icat` dependency-debugging challenge](06-nixpkgs/icat/README.md) +- [NixOS VM testing](07-nixos/vm-testing.md) +- [Advanced derivation topics](03-derivations/README.md#extension-material) +- [Declarative infrastructure](08-declarative-infra/README.md) + +## External References + +- [Nix language basics](https://nix.dev/tutorials/nix-language) +- [Packaging existing software](https://nix.dev/tutorials/packaging-existing-software) +- [`callPackage`](https://nix.dev/tutorials/callpackage) +- [NixOS integration tests](https://nix.dev/tutorials/nixos/integration-testing-using-virtual-machines) +- [Reproducible Builds definition](https://reproducible-builds.org/docs/definition/) + +Nix records and isolates build inputs, but it cannot by itself make a +nondeterministic upstream build bit-for-bit reproducible. diff --git a/flake.nix b/flake.nix index 3053747..dbba7f4 100644 --- a/flake.nix +++ b/flake.nix @@ -29,7 +29,11 @@ inputs.devenv.flakeModule inputs.treefmt-nix.flakeModule ]; - systems = nixpkgs.lib.systems.flakeExposed; + systems = [ + "x86_64-linux" + "aarch64-linux" + "aarch64-darwin" + ]; flake.nixosConfigurations = let @@ -56,6 +60,24 @@ system, ... }: + let + slides = pkgs.callPackage ./slides { }; + slidesSource = lib.fileset.toSource { + root = ./.; + fileset = lib.fileset.unions [ + ./01-nix-language + ./02-nix-store + ./03-derivations + ./04-shells + ./05-flakes + ./06-nixpkgs + ./07-nixos + ./slides + ./WORKSHOP.md + ./FACILITATOR.md + ]; + }; + in { packages = lib.optionalAttrs (system == "x86_64-linux") { @@ -63,8 +85,29 @@ } // lib.optionalAttrs (system == "aarch64-linux") { qemu-image = self.nixosConfigurations.training-image-aarch64.config.system.build.image; + } + // lib.optionalAttrs pkgs.stdenv.hostPlatform.isLinux { + inherit slides; }; + checks = lib.optionalAttrs pkgs.stdenv.hostPlatform.isLinux { + slides = + pkgs.runCommand "nix-training-slides-check" + { + nativeBuildInputs = [ + pkgs.gnugrep + pkgs.poppler-utils + pkgs.python3 + pkgs.qpdf + ]; + } + '' + python3 ${./scripts/check-slides.py} ${slidesSource} + bash ${./scripts/check-slides-pdf.sh} ${slides} + touch "$out" + ''; + }; + # nix fmt + nix flake check (auto-wired by flakeModule) treefmt = { projectRootFile = "flake.nix"; @@ -88,6 +131,26 @@ echo "Entering CI shell..." ''; }; + } + // lib.optionalAttrs pkgs.stdenv.hostPlatform.isLinux { + slides = pkgs.mkShellNoCC { + name = "slides-shell"; + packages = [ + pkgs.chromium + pkgs.inter + pkgs.jetbrains-mono + pkgs.marp-cli + pkgs.poppler-utils + pkgs.qpdf + ]; + + FONTCONFIG_FILE = pkgs.makeFontsConf { + fontDirectories = [ + pkgs.inter + pkgs.jetbrains-mono + ]; + }; + }; }; devenv.shells.default = { diff --git a/nixos/training-image.nix b/nixos/training-image.nix index 3c3a81d..92445d3 100644 --- a/nixos/training-image.nix +++ b/nixos/training-image.nix @@ -83,6 +83,10 @@ in }; }; + # The repart module describes its intermediate raw artifact by default. + # Match the public image metadata to the converted artifact below. + image.extension = lib.mkForce "qcow2"; + # Convert the raw repart image to a compressed qcow2 within the same # derivation, so the large raw file never lands in the Nix store. system.build.image = lib.mkForce ( diff --git a/nixos/training-preload.nix b/nixos/training-preload.nix index a69f1e3..148e256 100644 --- a/nixos/training-preload.nix +++ b/nixos/training-preload.nix @@ -18,6 +18,33 @@ let inherit (pkgs) bash; }; site = import ../03-derivations/02-static-site/site.nix { inherit (pkgs) runCommand jq; }; + siteContentCheck = + pkgs.runCommand "training-site-content-check" + { + nativeBuildInputs = [ pkgs.gnugrep ]; + } + '' + grep -F '

    Hello, Gambiconf!

    ' ${site}/index.html + touch "$out" + ''; + compositionApp = pkgs.writeShellApplication { + name = "show-site"; + runtimeInputs = [ pkgs.coreutils ]; + text = "cat ${site}/index.html"; + }; + compositionCheck = + pkgs.runCommand "check-training-page" + { + nativeBuildInputs = [ pkgs.gnugrep ]; + } + '' + grep -F '

    Hello, Gambiconf!

    ' ${site}/index.html + touch "$out" + ''; + icat = pkgs.callPackage ../06-nixpkgs/icat/icat.nix { }; + # Retain icat's source and compiler environment so the optional dependency + # debugging exercise can create new derivations without network access. + icatEnvironment = pkgs.mkShell { inputsFrom = [ icat ]; }; webSystem = nixpkgs.lib.nixosSystem { inherit system; modules = [ ../07-nixos/web-server/configuration.nix ]; @@ -52,6 +79,7 @@ let ../08-declarative-infra ../nixos ../scripts + ../slides ../.github ../.envrc ../.gitignore @@ -61,6 +89,9 @@ let ../LICENSE ../README.md ../README.pt-br.md + ../WORKSHOP.md + ../FACILITATOR.md + ../GLOSSARY.md ]; }; in @@ -96,6 +127,12 @@ in jsonEnvironment greeting site + siteContentCheck + compositionApp + compositionCheck + icat + icat.src + icatEnvironment webSystem.config.system.build.toplevel webSystemV2.config.system.build.toplevel ]; diff --git a/scripts/build-tutorials.sh b/scripts/build-tutorials.sh new file mode 100755 index 0000000..d6250a0 --- /dev/null +++ b/scripts/build-tutorials.sh @@ -0,0 +1,45 @@ +#!/usr/bin/env bash +set -euo pipefail + +repo=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd) +system=$(nix eval --impure --raw --expr builtins.currentSystem) + +build() { + nix build --no-link "$1" +} + +build "$repo/00-getting-started" +build "$repo/03-derivations/00-raw-derivation" +build "$repo/03-derivations/01-gnu-hello#hello" +build "$repo/03-derivations/02-static-site#site" +nix flake check -L "$repo/03-derivations/02-static-site" + +( + cd "$repo/04-shells/plain-flake-shell" + # shellcheck disable=SC2016 # Expand inside the development shell. + nix develop --command bash -c 'test "$REPORT_TITLE" = "Gambiconf training"; jq --version' +) +( + cd "$repo/03-derivations/01-gnu-hello" + nix develop .#hello --command bash -c 'command -v cc; command -v make' +) +( + cd "$repo/04-shells/devenv-shell" + nix develop --no-pure-eval --command report +) + +build "$repo/05-flakes/composition/site" +build "$repo/05-flakes/composition" +nix flake check -L "$repo/05-flakes/composition" +nix run "$repo/05-flakes/composition" >/dev/null + +build "$repo#checks.$system.treefmt" + +if [[ $(uname -s) == Linux ]]; then + build "$repo/06-nixpkgs/icat#icat" + host="web-lab-${system%%-linux}" + build "$repo/07-nixos/web-server#nixosConfigurations.$host.config.system.build.toplevel" + build "$repo/07-nixos/web-server#checks.$system.web" +fi + +echo 'All native tutorial outputs built successfully.' diff --git a/scripts/check-slides-pdf.sh b/scripts/check-slides-pdf.sh new file mode 100644 index 0000000..b41ee1b --- /dev/null +++ b/scripts/check-slides-pdf.sh @@ -0,0 +1,27 @@ +#!/usr/bin/env bash +set -euo pipefail + +slides=${1:?slides output directory required} + +set -- "$slides"/*.pdf +test "$#" -eq 8 + +for pdf in "$@"; do + qpdf --check "$pdf" +done + +pdfinfo "$slides/nix-training.pdf" | grep -Eq '^Pages:[[:space:]]+75$' +pdffonts "$slides/nix-training.pdf" | grep -Fq 'Inter' +pdffonts "$slides/nix-training.pdf" | grep -Fq 'JetBrainsMono' + +pdftotext "$slides/nix-training.pdf" slides.txt +for heading in \ + '01 - The Nix Language' \ + '02 - The Nix Store' \ + '03 - Derivations' \ + '04 - Development Shells' \ + '05 - Flakes in depth' \ + '06 - Nixpkgs' \ + '07 - NixOS'; do + grep -Fq "$heading" slides.txt +done diff --git a/scripts/check-slides.py b/scripts/check-slides.py new file mode 100644 index 0000000..911b08d --- /dev/null +++ b/scripts/check-slides.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +import re +import sys +from pathlib import Path + + +DECKS = [ + "01-nix-language.md", + "02-nix-store.md", + "03-derivations.md", + "04-shells.md", + "05-flakes.md", + "06-nixpkgs.md", + "07-nixos.md", +] +SOURCE = re.compile(r"") +IMAGE = re.compile(r"!\[[^]]*]\(([^)]+)\)") + + +def check_deck(root: Path, name: str) -> int: + path = root / "slides" / name + text = path.read_text(encoding="ascii") + if not text.startswith("---\n") or "marp: true" not in text[:300]: + raise ValueError(f"{path}: missing Marp frontmatter") + + parts = text.split("\n---\n") + if len(parts) < 2: + raise ValueError(f"{path}: no slides found") + + slides = parts[1:] + for number, slide in enumerate(slides, start=1): + sources = SOURCE.findall(slide) + if not sources: + raise ValueError(f"{path}: slide {number} has no Source comment") + for source in sources: + if not (path.parent / source).resolve().is_file(): + raise ValueError(f"{path}: slide {number} source does not exist: {source}") + + for image in IMAGE.findall(slide): + if image.startswith(("http://", "https://")): + raise ValueError(f"{path}: slide {number} uses a remote image: {image}") + if not (path.parent / image).resolve().is_file(): + raise ValueError(f"{path}: slide {number} image does not exist: {image}") + + return len(slides) + + +def main() -> int: + root = Path(sys.argv[1] if len(sys.argv) > 1 else ".").resolve() + total = sum(check_deck(root, deck) for deck in DECKS) + if total != 75: + raise ValueError(f"expected 75 slides, found {total}") + print(f"Validated {len(DECKS)} Markdown decks and {total} slides.") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/check-workshop.sh b/scripts/check-workshop.sh index ea9b528..8e2a3f0 100644 --- a/scripts/check-workshop.sh +++ b/scripts/check-workshop.sh @@ -8,13 +8,76 @@ build() { starter=$(build 00-getting-started) test "$("$starter/bin/hello")" = 'Hello, world!' +# shellcheck disable=SC2016 # This is a Nix expression, not shell interpolation. +nix eval --json --expr 'let f = { greeting, audience ? "world" }: "${greeting}, ${audience}!"; in f { greeting = "Hello"; audience = "Nix"; }' \ + | grep -F '"Hello, Nix!"' +nix path-info --recursive "$starter" >/dev/null greeting=$(build 03-derivations/00-raw-derivation) test "$(<"$greeting")" = 'Hello from a derivation!' + +( + cd "$repo/03-derivations/00-raw-derivation" + cp greeting.nix greeting.nix.workshop-backup + trap 'mv greeting.nix.workshop-backup greeting.nix' EXIT + sed -i 's/Hello from a derivation!/Hello from an offline edit!/' greeting.nix + changed_greeting=$(nix build --offline --no-link --print-out-paths) + test "$(<"$changed_greeting")" = 'Hello from an offline edit!' +) + hello=$(build 03-derivations/01-gnu-hello) test "$("$hello/bin/hello" --greeting='Hello, Gambiconf!')" = 'Hello, Gambiconf!' + +( + cd "$repo/03-derivations/01-gnu-hello" + cp hello.nix hello.nix.workshop-backup + trap 'mv hello.nix.workshop-backup hello.nix; rm -f failed-build.log' EXIT + sed -i '/doCheck = true;/a\ postCheck = "echo Deliberate workshop failure >&2; false";' hello.nix + if nix build --offline --no-link -L >failed-build.log 2>&1; then + echo 'The deliberate Hello check unexpectedly passed.' >&2 + exit 1 + fi + grep -F 'Deliberate workshop failure' failed-build.log +) + +( + # The callPackage refactor in 06-nixpkgs/packaging.md must keep the same derivation. + cd "$repo/03-derivations/01-gnu-hello" + cp flake.nix flake.nix.workshop-backup + trap 'mv flake.nix.workshop-backup flake.nix' EXIT + before=$(nix path-info --offline --derivation .#hello) + sed -i '/hello = import \.\/hello\.nix {/,/};/c\ hello = pkgs.callPackage ./hello.nix { };' flake.nix + grep -F 'hello = pkgs.callPackage ./hello.nix { };' flake.nix + if grep -F 'import ./hello.nix' flake.nix; then exit 1; fi + after=$(nix path-info --offline --derivation .#hello) + test "$before" = "$after" +) + site=$(build 03-derivations/02-static-site) grep -F '

    Hello, Gambiconf!

    ' "$site/index.html" +( + cd "$repo/03-derivations/02-static-site" + cp site.json site.json.workshop-backup + trap 'mv site.json.workshop-backup site.json' EXIT + sed -i 's/Hello, Gambiconf!/Offline package edit/' site.json + changed_site=$(nix build --offline --no-link --print-out-paths) + grep -F '

    Offline package edit

    ' "$changed_site/index.html" +) + +( + cd "$repo/03-derivations/02-static-site" + nix flake check --offline -L +) + +( + cd "$repo/05-flakes/composition" + nix flake check --offline -L + nix run --offline | grep -F '

    Hello, Gambiconf!

    ' +) + +icat=$(build 06-nixpkgs/icat) +test -x "$icat/bin/icat" + ( cd "$repo/04-shells/plain-flake-shell" # shellcheck disable=SC2016 # Expand these variables inside the development shell. @@ -28,4 +91,4 @@ grep -F '

    Hello, Gambiconf!

    ' "$site/index.html" nix develop --offline "$repo/03-derivations/01-gnu-hello#hello" \ --command bash -c 'command -v cc && command -v make' -echo 'Core package and development-shell exercises passed offline.' +echo 'Core and optional package, check, and development-shell exercises passed offline.' diff --git a/scripts/run-vm.sh b/scripts/run-vm.sh index 3e9dbf5..5abcbbe 100644 --- a/scripts/run-vm.sh +++ b/scripts/run-vm.sh @@ -4,7 +4,7 @@ set -euo pipefail image=${1:?Usage: run-vm.sh IMAGE.qcow2} arch=${VM_ARCH:-$(uname -m)} ssh_port=${VM_SSH_PORT:-2222} -memory=${VM_MEMORY:-1024} +memory=${VM_MEMORY:-2048} case "$arch" in arm64 | aarch64) arch=aarch64 ;; diff --git a/slides/01-nix-language.md b/slides/01-nix-language.md new file mode 100644 index 0000000..9d9c5db --- /dev/null +++ b/slides/01-nix-language.md @@ -0,0 +1,264 @@ +--- +marp: true +theme: nix-training +paginate: true +size: 16:9 +title: "01 - The Nix Language" +description: "A 30-minute guided lab for reading Nix package recipes" +--- + + + + +# 01 - The Nix Language + +## Read package recipes in 30 minutes + +Values -> functions -> GNU Hello + + + +--- + + + + + +# The timed path + +| Time | Focus | +|---|---| +| 0-5 | Values and attribute sets | +| 5-9 | Local names | +| 9-17 | Functions | +| 17-21 | Strings, shell, and paths | +| 21-24 | Laziness | +| 24-26 | Builtins and nixpkgs libraries | +| 26-30 | Read GNU Hello | + +Run examples in `nix repl`. Use `:p` to force nested values and `:q` to exit. + +--- + + + + +# 0-5: Values and attribute sets + +```nix +{ + name = "training-site"; + enabled = true; + topics = [ "language" "store" "packages" ]; + server.port = 8080; +} +``` + +```nix +({ server.port = 8080; }).server.port +({ port = 8080; }).port or 80 +({ port = 8080; }) ? port +``` + +An attribute set groups named values. A list is ordered. Neither is mutated. + +--- + + + + +# 5-9: Local names + +`let` introduces names for one expression. Definitions are not sequential. + +```nix +let + greeting = "Hello"; + audience = "Gambiconf"; +in +{ + message = "${greeting}, ${audience}!"; + length = builtins.stringLength greeting; +} +``` + +`inherit` avoids repeating `name = name`: + +```nix +let name = "training-site"; version = "1"; +in { inherit name version; } +``` + +--- + + + + +# 9-17: Functions + +Every function takes one argument. Application uses whitespace. + +```nix +(x: x + 1) 2 +(name: "Hello, ${name}!") "Gambiconf" +``` + +Packages usually take an attribute set so dependencies have names: + +```nix +let + makeMessage = { greeting, audience ? "world" }: + "${greeting}, ${audience}!"; +in +makeMessage { greeting = "Hello"; audience = "Nix"; } +``` + +--- + + + + +# 17-21: Strings, shell, and paths + +```nix +let output = "index.html"; +in '' + mkdir -p "$out" + printf '%s\n' "ready" > "$out/${output}" +'' +``` + +- `${output}` is Nix interpolation. +- `$out` is left for the builder's shell. +- `./site.json` is a path value, not the string `"./site.json"`. +- A path used as a derivation input becomes part of the build description. + +--- + + + + +# 21-24: Laziness + +Nix evaluates values when they are demanded: + +```nix +({ + used = 1; + broken = builtins.throw "not demanded"; +}).used +``` + +- The result is `1`. +- Large package sets need not evaluate every package. +- Evaluation does not build a derivation. + + + +--- + + + + +# 24-26: Builtins versus libraries + +`builtins` is part of the Nix evaluator: + +```nix +builtins.map (x: x * 2) [ 1 2 3 ] +builtins.attrNames { jq = 1; nginx = 2; } +``` + +These come from nixpkgs, not the language: + +```nix +pkgs.runCommand +pkgs.callPackage +pkgs.lib.genAttrs +``` + +--- + + + + + +# 26-30: Read GNU Hello + +Open `../03-derivations/01-gnu-hello/hello.nix` and find: + +1. The outer function and its two dependencies. +2. The call to `stdenv.mkDerivation`. +3. The attribute set passed to it. +4. The `fetchurl` call and its argument. +5. Boolean, string, and interpolated-string values. + +```nix +src = fetchurl { + url = "https://ftp.gnu.org/gnu/hello/hello-${version}.tar.gz"; + sha256 = "1ayhp9v4m4rdhjmnl2bq3cibrbqqkgjbl3s7yk2nhlh8vj3ay16g"; +}; +``` + +--- + + + + + +# Follow the dependencies + +Open the exercise's `flake.nix` and locate: + +```nix +inputs.nixpkgs.url = + "https://channels.nixos.org/nixpkgs-unstable/nixexprs.tar.zst"; +``` + +```nix +pkgs = nixpkgs.legacyPackages.${system}; +hello = import ./hello.nix { + inherit (pkgs) stdenv fetchurl; +}; +``` + +Checkpoint: why is `hello.nix` a function that returns a derivation? + +--- + + + + + +# Recap: read the shape + +```text +named dependencies + | + v +function -> mkDerivation call -> attribute-set argument +``` + +- Nix data resembles JSON, with functions and path values added. +- A package recipe is a function from dependencies to a derivation. +- Values are immutable and evaluated lazily. +- A derivation description is not a realised build output. + +--- + + + + + +# Appendix: language reference + +Not part of the timed path: + +- `types.md`: ten value types and special path behavior +- `syntax.md`: control flow, assertions, `with`, and identifiers +- `operators.md`: precedence, shallow `//`, and experimental pipes +- `scope.md`: static scope and impure lookup paths +- `strings.md`: escaping and advanced string context +- `builtins.md`: categorized evaluator primitives + +Use the module notes as canonical reference material. diff --git a/slides/02-nix-store.md b/slides/02-nix-store.md new file mode 100644 index 0000000..81f6498 --- /dev/null +++ b/slides/02-nix-store.md @@ -0,0 +1,155 @@ +--- +marp: true +theme: nix-training +paginate: true +size: 16:9 +title: "02 - The Nix Store" +description: "A 15-minute lab on store paths, closures, and garbage-collection roots" +--- + + + + +# 02 - The Nix Store + +## Follow an artifact and its dependencies + +Store path -> references -> closure -> roots + +--- + + + + +# Core lab: exact commands + +From `00-getting-started/`: + +```bash +nix build +readlink -f result +nix path-info --closure-size ./result +nix store ls ./result/bin +nix-store --query --references ./result +nix path-info --recursive ./result +nix-store --query --roots "$(readlink -f result)" +``` + +Do not run garbage collection in the workshop image. + + + +--- + + + +# Store path anatomy + +```text +/nix/store/- +|--------| |------| |----| +store dir opaque readable + identity label +``` + +- A store path identifies exactly one store object. +- The digest is 20 bytes, rendered as 32 Nix32 characters. +- Its computation depends on the path kind; treat it as opaque. +- The store directory is part of the digest. +- Store paths are obtained by adding or building objects, not inventing them. + +--- + + + +# References form a closure graph + +```text +result + |---> runtime library + | `---> loader + `---> data file +``` + +- A reference is one direct edge to another store object. +- The runtime closure is the output plus all transitive references. +- A store holds an object only when it also holds every referenced object. +- `--references` shows direct edges; `--recursive` follows the closure. + + + +--- + + + + +# Runtime is not build time + +```text +compiler + source + build tools + | + v + realised output + | + v + runtime references and closure +``` + +- A compiler can be required to build GNU Hello. +- The installed executable need not reference that compiler. +- The runtime closure is deployable data, not the full build toolchain. +- Module 03 inspects the build environment separately. + +--- + + + + +# Profiles, roots, and reachability + +```text +profile -> generation -> user environment -> packages +result -------------------------------> output +``` + +- A profile is a symlink chain into immutable store objects. +- Switching its selected generation is atomic. +- A GC root keeps every reachable object alive. +- Old generations can keep old packages alive. +- Uninstalling or upgrading does not immediately delete store objects. + +--- + + + + +# Name each observation + +1. `result` is a convenient symlink; `readlink -f` finds the output. +2. `nix store ls` inspects files inside that output. +3. `--references` reports direct dependencies. +4. `--recursive` reports the complete runtime closure. +5. `--closure-size` estimates required storage or transfer. +6. `--roots` identifies what keeps the output alive. + +Checkpoint: point to one output, one direct reference, its closure, and its root. + +--- + + + + + +# Recap: artifact to reachability + +```text +file system object + references -> store object -> store path + -> closure +root -> reachable objects stay alive +``` + +- Store objects are immutable file-system data plus references. +- Direct references and transitive closures answer different questions. +- Runtime dependencies can be smaller than build dependencies. +- Profiles and result links are roots into the graph. +- A substituter serves existing objects; a remote builder executes work. diff --git a/slides/03-derivations.md b/slides/03-derivations.md new file mode 100644 index 0000000..26d89ce --- /dev/null +++ b/slides/03-derivations.md @@ -0,0 +1,401 @@ +--- +marp: true +theme: nix-training +paginate: true +size: 16:9 +title: "03 - Derivations" +description: "From Nix evaluation to realised artifacts, with GNU Hello and a checked static site" +--- + + + + +# 03 - Derivations + +## From expression to artifact + +Evaluation, build plans, isolated builds, and checks + + + +--- + + + + +# One question throughout + +> Which inputs determine this artifact, and where can we observe that relationship? + +By the end, you can: + +- distinguish evaluation, instantiation, and realisation +- read a raw derivation and an `stdenv` package +- separate build dependencies from runtime references +- diagnose a build or check failure from its log + + + +--- + + + +# Three distinct steps + +```text +.nix expression + | evaluate + v +derivation value --instantiate--> .drv build plan + | realise + v + output in /nix/store +``` + +- Evaluation computes values. +- Instantiation records the build plan. +- Realisation builds locally or obtains the output from a substituter. + + + +--- + + + +# The primitive + +```nix +{ bash, system }: + +builtins.derivation { + name = "greeting"; + inherit system; + builder = "${bash}/bin/bash"; + GREETING = "Hello from a derivation!"; + args = [ + "-c" + ''printf '%s\n' "$GREETING" > "$out"'' + ]; +} +``` + +Nix supplies `$out`; extra attributes become builder environment variables. + + + +--- + + + + +# Demo: inspect before building + +From `03-derivations/00-raw-derivation/`: + +```sh +nix derivation show +nix build -L +cat result +readlink result +``` + +Observe: + +- JSON describes builder, arguments, environment, inputs, and output. +- `result` points to a store object containing one file. +- Rebuilding unchanged inputs reuses the result. + + + +--- + + + + +# Exercise: change, fail, restore + +1. Change `GREETING` and inspect the derivation again. +2. Build and compare the new derivation and output paths. +3. Replace the build command with `exit 1`. +4. Run `nix build -L` and read the first meaningful error. +5. Restore the original command before continuing. + +```text +changed input -> changed build plan -> changed output identity +``` + + + +--- + + + + +# Prefer higher-level builders + +```text +builtins.derivation + ^ + | +stdenv.mkDerivation runCommand + ^ ^ + | | +compiled packages small generated artifacts +``` + +All produce derivations. The wrappers provide conventions so recipes stay small. + + + +--- + + + +# `stdenv` supplies a phase pipeline + +Typical phases for GNU Hello: + +```text +unpack -> patch -> configure -> build -> check -> install -> fixup +``` + +- Hooks and package attributes can adjust the phases. +- `doCheck = true` enables upstream tests. +- `$out` is the installation destination. +- Logs reveal which phase was running when a build failed. + + + +--- + + + +# GNU Hello: the complete recipe + +```nix +{ stdenv, fetchurl }: + +let + version = "2.12"; +in +stdenv.mkDerivation { + pname = "hello"; + inherit version; + + src = fetchurl { + url = "https://ftp.gnu.org/gnu/hello/hello-${version}.tar.gz"; + sha256 = "1ayhp9v4m4rdhjmnl2bq3cibrbqqkgjbl3s7yk2nhlh8vj3ay16g"; + }; + + doCheck = true; +} +``` + + + +--- + + + + +# Demo: build, run, inspect + +From `03-derivations/01-gnu-hello/`: + +```sh +nix flake show +nix build -L +./result/bin/hello +nix run -- --greeting="Hello, Gambiconf!" +nix log .#hello +``` + +Find `configure`, `make`, tests, and installation in the log. + + + +--- + + + + +# Exercise: fail in `postCheck` + +Temporarily add inside `stdenv.mkDerivation`: + +```nix +postCheck = '' + echo "Deliberate workshop failure" >&2 + false +''; +``` + +Then: + +```sh +nix build -L +nix log .#hello +``` + +Remove `postCheck` and rebuild before continuing. + + + +--- + + + +# Build dependencies are not runtime references + +```text +source + compiler + make + build scripts + | + v + /nix/store/...-hello-2.12 + | + v + runtime references and closure +``` + +```sh +nix path-info --closure-size ./result +nix path-info --recursive ./result +``` + +The compiler can be required to build Hello without being in its runtime closure. + + + +--- + + + + +# Demo: enter the build environment + +```sh +nix develop .#hello +type -a cc make +exit +``` + +This exposes the package's build environment without completing its normal build. + +It does **not** mean "install Hello into my shell." + + + +--- + + + + +# Derivations can produce data + +```nix +{ runCommand, jq }: + +runCommand "training-site" { nativeBuildInputs = [ jq ]; } '' + mkdir -p "$out" + jq --exit-status --raw-output \ + --from-file ${./render.jq} ${./site.json} > "$out/index.html" +'' +``` + +- `runCommand` uses a standard environment without a compiler. +- Local path interpolation declares the fixture and renderer as inputs. +- `jq` is a build-time tool. + + + +--- + + + + +# Exercise: prove dependency isolation + +From `03-derivations/02-static-site/`: + +```sh +nix build -L +cat result/index.html +readlink result +``` + +Then try one failure at a time: + +- Remove `jq` from `nativeBuildInputs`. +- Put malformed JSON in `site.json`. + +Read the log, restore the file, and rebuild. + + + +--- + + + +# Build success and checks answer different questions + +```text +nix build + Can the artifact be produced? + +nix flake check -L + Does the artifact satisfy the declared property? +``` + +The repository's `site-content` check asserts: + +```sh +grep -F '

    Hello, Gambiconf!

    ' ${site}/index.html +touch "$out" +``` + +Change the title: the package can build while the content check fails. + + + +--- + + + + +# Recap + +- A Nix expression evaluates to a derivation value. +- A `.drv` records a build plan; realisation produces its output. +- `stdenv.mkDerivation` supplies conventional package phases. +- Build dependencies can be absent from the runtime closure. +- `nix develop .#hello` exposes a package build environment. +- `runCommand` is useful for small generated artifacts. +- Build logs and flake checks make failures observable. + +```sh +cd 03-derivations/02-static-site +nix flake check -L +``` + + + +--- + + + + +# Appendix: derivation controls + +Use these when a concrete package requires them: + +| Need | Mechanism | +|---|---| +| Multiple independently consumed results | `outputs` | +| Limit direct or closure references | `allowedReferences`, `allowedRequisites` | +| Pass large values outside the environment | `passAsFile` | +| Require a capable builder | `requiredSystemFeatures` | +| Verify fetched content | fixed-output derivation attributes | + +Also see `__structuredAttrs` and per-output `outputChecks` in the canonical reference. + + diff --git a/slides/04-shells.md b/slides/04-shells.md new file mode 100644 index 0000000..0836837 --- /dev/null +++ b/slides/04-shells.md @@ -0,0 +1,168 @@ +--- +marp: true +theme: nix-training +paginate: true +size: 16:9 +title: "04 - Development Shells" +description: "Choosing Nix commands and defining a lightweight, repeatable development workspace" +--- + + + + +# 04 - Development Shells + +## Repeatable tools for a writable workspace + + + +--- + + + + +# Artifact vs workspace + +| Derivation build | Development shell | +|---|---| +| Produces an immutable store output | Provides tools and variables | +| Uses declared build inputs | Can see mutable project files | +| Normally runs in the build sandbox | Can access home, network, and host tools | +| Demonstrates package dependency closure | Does not prove build isolation | + +The same renderer can write to `$out/index.html` in a build or `./index.html` in a shell. + + + +--- + + + +# Select the command by intent + +| Intent | Command | +|---|---| +| Build the current package | `nix build` | +| Enter the current project workspace | `nix develop` | +| Enter Hello's build environment | `nix develop .#hello` | +| Add a temporary locked tool | `nix shell --inputs-from . nixpkgs#jq` | +| Run a packaged program | `nix run` | + +`nix-shell` is the legacy `shell.nix` / `default.nix` interface. + + + +--- + + + +# A compiler-free project shell + +```nix +{ pkgs }: + +pkgs.mkShellNoCC { + packages = [ pkgs.jq ]; + REPORT_TITLE = "Gambiconf training"; + shellHook = '' + printf 'Try: bash report.sh, or jq -r -f render.jq site.json\n' + ''; +} +``` + +- `packages` adds tools. +- Extra string attributes become environment variables. +- `shellHook` runs when the shell starts. +- Use `mkShell` instead when the workspace needs a compiler. + + + +--- + + + + +# Demo: interactive and noninteractive + +From `04-shells/plain-flake-shell/`: + +```sh +nix develop +printf '%s\n' "$REPORT_TITLE" +bash report.sh +exit +``` + +Run one command without opening an interactive shell: + +```sh +nix develop --command bash report.sh +nix develop --command bash -c \ + 'jq -r -f render.jq site.json > index.html' +``` + + + +--- + + + + +# Exercise: expose host impurity + +1. Exit the shell. +2. Inspect `command -v jq` and `REPORT_TITLE`. +3. Temporarily remove jq from `packages`. +4. Re-enter and try the report. +5. Restore jq. + +A host-installed jq may make the command succeed. + +```text +shell success != proof of complete package dependencies +``` + +The module 03 sandboxed build is the stronger dependency test. + + + +--- + + + + +# The same workspace with devenv + +| Plain `mkShellNoCC` | `devenv.nix` | +|---|---| +| `packages = [ pkgs.jq ];` | `packages = [ pkgs.jq ];` | +| `REPORT_TITLE = ...;` | `env.REPORT_TITLE = ...;` | +| `shellHook = ...;` | `enterShell = ...;` | +| shell commands | named `report` and `render` scripts | + +The exercise uses `devenv.lib.mkShell` and requires `--no-pure-eval` to discover its working directory. + +Devenv adds framework inputs, so this is a walkthrough unless prewarmed. + + + +--- + + + + +# Recap + +- Build artifacts with `nix build`. +- Define repeatable project tools with `devShells` and `mkShellNoCC`. +- Use `nix develop --command` for noninteractive workspace commands. +- Use `nix develop .#hello` for a package's build environment. +- Expect interactive shells to see writable files and host state. +- Reach for devenv when named scripts and richer workspace features justify it. + +```text +derivation -> immutable artifact +devShell -> productive workspace +``` + + diff --git a/slides/05-flakes.md b/slides/05-flakes.md new file mode 100644 index 0000000..1223057 --- /dev/null +++ b/slides/05-flakes.md @@ -0,0 +1,180 @@ +--- +marp: true +theme: nix-training +paginate: true +size: 16:9 +title: "05 - Flakes in depth" +description: "Inputs, lock graphs, output schemas, composition, and flake checks" +--- + + + + +# 05 - Flakes in depth + +## Pin dependencies, publish outputs, compose projects + + + +--- + + + + +# One contract, two directions + +```nix +{ + inputs.nixpkgs.url = + "https://channels.nixos.org/nixpkgs-unstable/nixexprs.tar.zst"; + + outputs = { self, nixpkgs }: { + packages.x86_64-linux.default = + nixpkgs.legacyPackages.x86_64-linux.hello; + }; +} +``` + +- `inputs`: dependencies Nix resolves and locks +- `outputs`: values and artifacts consumers can address +- `self`: this flake's source and outputs + + + +--- + + + +# The lock file is a graph + +```text +root +|-- nixpkgs -> locked revision + NAR hash +`-- site + `-- nixpkgs -> follows root/nixpkgs +``` + +- `original`: the requested reference +- `locked`: the resolved immutable source +- `inputs`: edges to other nodes +- The consumer lock governs its complete dependency graph + +`nix flake lock` fills missing entries. `nix flake update nixpkgs` requests an update. + + + +--- + + + + +# Pure evaluation has boundaries + +- No ambient `NIX_PATH` +- No `builtins.currentSystem` +- No reading outside the flake source +- `--impure` is an explicit escape hatch + +Inside a Git worktree, the flake source includes only tracked files. + +```sh +git add new-package.nix +nix flake show +``` + +If Nix says a new file is missing, check Git visibility before debugging the expression. + + + +--- + + + +# Schema carries the system dimension + +```text +packages.. nix build .#name +apps.. nix run .#name +devShells.. nix develop .#name +checks.. nix flake check +nixosConfigurations. +``` + +```nix +forAllSystems = nixpkgs.lib.genAttrs [ + "x86_64-linux" + "aarch64-linux" + "aarch64-darwin" +]; +``` + +Generating keys does not cross-compile. Each build still needs a suitable builder. + + + +--- + + + + +# Compose outputs, share inputs + +```nix +inputs.site = { + url = "path:./site"; + inputs.nixpkgs.follows = "nixpkgs"; +}; + +packages = forAllSystems (system: { + default = site.packages.${system}.default; +}); +``` + +- The consumer reuses the producer's package output +- `follows` makes both flakes use the root nixpkgs node +- The producer remains independently usable with its own lock + + + +--- + + + + +# Inspect, build, then break the check + +```sh +cd 05-flakes/composition +nix flake metadata +nix flake show +nix build +nix run +nix flake check -L +``` + +Then change the title in `site/site.json`. + +- `metadata`: resolved reference and lock graph +- `show`: output schema +- `check`: content contract; the changed heading must fail + +Repair the expected heading, rerun the check, then restore both edits. + + + +--- + + + + +# Flake operating model + +1. Declare dependency references in `inputs`. +2. Commit and review `flake.lock` as a graph. +3. Publish conventional, system-indexed outputs. +4. Compose outputs directly; use `follows` deliberately. +5. Use `metadata`, `show`, and `check` for different questions. + +Keep early wrappers thin. Package recipes remain ordinary Nix functions. + + diff --git a/slides/06-nixpkgs.md b/slides/06-nixpkgs.md new file mode 100644 index 0000000..2629594 --- /dev/null +++ b/slides/06-nixpkgs.md @@ -0,0 +1,196 @@ +--- +marp: true +theme: nix-training +paginate: true +size: 16:9 +title: "06 - Nixpkgs" +description: "Package recipes, callPackage, dependency categories, overrides, and overlays" +--- + + + + +# 06 - Nixpkgs + +## A package collection and a library for building packages + + + +--- + + + + +# Nixpkgs connects recipes to dependencies + +```nix +{ stdenv, fetchurl }: + +stdenv.mkDerivation { + pname = "hello"; + version = "2.12"; + src = fetchurl { /* fixed source */ }; + doCheck = true; +} +``` + +- A recipe is a function of its dependencies +- nixpkgs provides package values, builders, fetchers, and `lib` +- `stdenv.mkDerivation` adds the standard build phases and toolchain + + + +--- + + + +# `callPackage` performs dependency injection + +For each function argument, it looks for the same name in `pkgs`. + +```nix +hello = pkgs.callPackage ./hello.nix { }; +``` + +Explicit values in the second argument win: + +```nix +hello = pkgs.callPackage ./hello.nix { + audience = "people"; +}; +``` + +The result is overridable because nixpkgs retains the function application. + + + +--- + + + + +# Refactor explicit import to `callPackage` + +```nix +# Before +hello = import ./hello.nix { + inherit (pkgs) stdenv fetchurl; +}; + +# After +hello = pkgs.callPackage ./hello.nix { }; +``` + +The recipe does not change. Only its caller changes. + + + +--- + + + + +# Prove it is the same derivation + +```sh +before=$(nix path-info --derivation .#hello) +# Refactor the wrapper, then: +nix build +nix run +after=$(nix path-info --derivation .#hello) +test "$before" = "$after" +``` + +If the paths match: + +- dependency injection changed +- build inputs did not change +- the derivation identity stayed the same + + + +--- + + + +# Classify dependencies by role + +| Attribute | Role | Examples | +|---|---|---| +| `nativeBuildInputs` | executed while building | `cmake`, `pkg-config` | +| `buildInputs` | linked into or used by output | `zlib`, `openssl` | +| `nativeCheckInputs` | test tools | test runner hooks | +| `checkInputs` | test libraries | test-only libraries | +| `propagatedBuildInputs` | needed by dependents | Python libraries | + +`strictDeps = true` helps expose incorrect placement, especially when cross-compiling. + + + +--- + + + + +# Customize at the narrowest scope + +```nix +pkg.override { withRuby = false; } + +pkg.overrideAttrs (final: prev: { + patches = (prev.patches or [ ]) ++ [ ./fix.patch ]; +}) + +final: prev: { + hello = prev.hello.overrideAttrs { separateDebugInfo = true; }; +} +``` + +- `override`: change recipe function arguments +- `overrideAttrs`: change `mkDerivation` attributes +- overlay: change or extend the package set for all consumers + +In an overlay, use `prev` for the package being replaced and `final` for dependencies. + + + +--- + + + + +# Package workflow + +1. Express the recipe as a function of dependencies. +2. Let `callPackage` wire matching names from `pkgs`. +3. Verify refactors by comparing derivation paths. +4. Put tools and target libraries in the correct dependency lists. +5. Use `override`, `overrideAttrs`, or an overlay according to scope. + +Fix the first meaningful build failure; do not add dependencies blindly. + + + +--- + + + + +# Appendix: diagnose `icat` + +```sh +cd 06-nixpkgs/icat +nix build -L +nix run -- sample.ppm +``` + +One temporary edit at a time: + +1. Remove `imlib2`: find the missing header. +2. Restore it; remove `libx11`: inspect the X11 failure. +3. Restore both; remove `installPhase`: compilation succeeds, install fails. +4. Restore the phase and its pre/post hooks. + +This pin names the X11 dependency `libx11`, not `xorg.libX11`. + + diff --git a/slides/07-nixos.md b/slides/07-nixos.md new file mode 100644 index 0000000..6ab0790 --- /dev/null +++ b/slides/07-nixos.md @@ -0,0 +1,270 @@ +--- +marp: true +theme: nix-training +paginate: true +size: 16:9 +title: "07 - NixOS" +description: "Modules, system closures, service tests, generations, and rollback" +--- + + + + +# 07 - NixOS + +## Build and activate an operating system as a closure + + + +--- + + + + +# A system is more than a package list + +The evaluated configuration selects one immutable system closure: + +- packages and command paths +- generated files under `/etc` +- users and permissions +- service units and configuration +- kernel, initrd, and boot settings + +```text +configuration -> evaluation -> system closure -> activation +``` + +`nixosConfigurations.` exposes the evaluated system through a flake. + + + +--- + + + +# `nixosSystem` starts the import graph + +```nix +mkLab = system: nixpkgs.lib.nixosSystem { + inherit system; + modules = [ ./configuration.nix ]; +}; +``` + +```nix +imports = [ + ./guest.nix + ./disk.nix + ./web-server.nix +]; +``` + +The lab exposes `web-lab-x86_64` and `web-lab-aarch64`. + + + +--- + + + +# Modules declare, define, and merge options + +```nix +options.site.enable = lib.mkOption { + type = lib.types.bool; + default = false; +}; + +config = lib.mkIf config.site.enable { + services.nginx.enable = true; +}; +``` + +- Types validate definitions and control merging +- Lists concatenate; attribute sets merge +- Conflicting scalar definitions fail +- `mkDefault` and `mkForce` adjust priority +- `config` is the lazy merged result of all modules + + + +--- + + + + +# Data becomes a served system artifact + +```text +site.json + | +site.nix + render.jq + | +training-site derivation + | +services.nginx.virtualHosts.training.root + | +NixOS system closure +``` + +```nix +root = site; +networking.firewall.allowedTCPPorts = [ 80 ]; +``` + +The page is generated during the build, not at nginx startup. + + + +--- + + + +# Build and activation are separate decisions + +| Action | Effect | +|---|---| +| `build` | Build only | +| `test` | Activate temporarily; keep boot default | +| `switch` | Activate and select for future boots | +| `boot` | Select for next boot; do not activate now | + +```sh +host="web-lab-$(uname -m)" +nix build ".#nixosConfigurations.$host.config.system.build.toplevel" +sudo nixos-rebuild switch --offline --flake ".#$host" +``` + + + +--- + + + + +# Test readiness and behavior + +```python +start_all() +server.wait_for_unit("nginx.service", timeout=60) +server.wait_for_open_port(80, timeout=30) +client.wait_until_succeeds( + "curl --fail --silent http://server/ | grep -F 'NixOS'", + timeout=60, +) +``` + +The two-machine test covers: + +- service readiness +- network port readiness +- client-visible generated content +- firewall and document root together + + + +--- + + + + +# Generation V1: activate and observe + +```sh +sudo nixos-rebuild switch --offline --flake ".#$host" +systemctl status nginx --no-pager +curl --fail http://localhost/ +readlink /run/current-system +``` + +Expected heading: `Hello, Gambiconf!` + +Record the current system path. It includes the selected page, nginx configuration, and service definitions. + + + +--- + + + + +# Generation V2: change one source value + +Edit only the title in `site.json` to `Version two`. + +```sh +sudo nixos-rebuild switch --offline --flake ".#$host" +curl --fail http://localhost/ +readlink /run/current-system +``` + +Observe: + +- a new heading +- a different site derivation +- a different system store path +- V1 remains available as the previous generation + + + +--- + + + + +# Roll back the system generation + +```sh +sudo nixos-rebuild switch --rollback --flake ".#$host" +curl --fail http://localhost/ +readlink /run/current-system +``` + +Expected: + +- V1 heading returns +- V1 system path returns +- the running service uses the prior closure + +Rollback changes the selected system generation. It does not rebuild from the edited source. + + + +--- + + + +# Know the rollback boundary + +Rollback restores declarative system artifacts selected by the generation. + +It does **not** restore: + +- `site.json` in the workspace +- databases or arbitrary mutable service data +- files outside the system closure +- the previous `flake.lock` or workspace files + +A later rebuild still reads the edited `site.json` and can recreate V2. + +`system.stateVersion` is a compatibility baseline, not an update mechanism. + + + +--- + + + + +# NixOS operating model + +1. `nixosSystem` evaluates an imported module graph. +2. Typed options merge into one lazy configuration. +3. Packages, files, and services form a system closure. +4. Build before choosing `test`, `switch`, or `boot`. +5. Test externally visible behavior after readiness. +6. Generations make system rollback fast and explicit. +7. Back up mutable data separately. + + diff --git a/slides/README.md b/slides/README.md new file mode 100644 index 0000000..394f95f --- /dev/null +++ b/slides/README.md @@ -0,0 +1,31 @@ +# Training slides + +The seven decks in this directory are concise presentation companions to the +canonical module notes. They do not replace the detailed Markdown under +`01-nix-language` through `07-nixos`. + +Build every individual PDF and the merged `nix-training.pdf` on Linux: + +```sh +make slides +``` + +Validate PDF structure, page count, fonts and expected module text: + +```sh +make slides-check +``` + +For authoring, start Marp's local preview server: + +```sh +make slides-preview +``` + +The Markdown files use the shared `theme/nix-training.css` theme. Keep slide +content concise, add a `Source` comment pointing at the canonical note, and put +deep reference material after the core recap as appendix slides. Generated PDFs +belong in `result-slides` and are not committed. + +PDF rendering uses Chromium and is exposed as a Linux flake package. The slide +Markdown remains readable and editable on every platform. diff --git a/slides/default.nix b/slides/default.nix new file mode 100644 index 0000000..cdc56cc --- /dev/null +++ b/slides/default.nix @@ -0,0 +1,79 @@ +{ + lib, + stdenvNoCC, + marp-cli, + chromium, + qpdf, + fontconfig, + inter, + jetbrains-mono, + makeFontsConf, +}: + +stdenvNoCC.mkDerivation { + pname = "nix-training-slides"; + version = "1"; + + src = lib.fileset.toSource { + root = ./.; + fileset = lib.fileset.unions [ + ./01-nix-language.md + ./02-nix-store.md + ./03-derivations.md + ./04-shells.md + ./05-flakes.md + ./06-nixpkgs.md + ./07-nixos.md + ./theme + ]; + }; + + nativeBuildInputs = [ + marp-cli + chromium + qpdf + fontconfig + ]; + + FONTCONFIG_FILE = makeFontsConf { + fontDirectories = [ + inter + jetbrains-mono + ]; + }; + + buildPhase = '' + runHook preBuild + + export HOME="$TMPDIR/home" + export XDG_CACHE_HOME="$TMPDIR/cache" + export XDG_CONFIG_HOME="$TMPDIR/config" + mkdir -p "$HOME" "$XDG_CACHE_HOME" "$XDG_CONFIG_HOME" rendered + + for source in [0-9][0-9]-*.md; do + marp \ + --browser-path ${chromium}/bin/chromium \ + --pdf \ + --pdf-outlines \ + --theme-set theme/nix-training.css \ + --output "rendered/''${source%.md}.pdf" \ + "$source" + done + + qpdf --empty --pages rendered/[0-9][0-9]-*.pdf -- rendered/nix-training.pdf + + runHook postBuild + ''; + + installPhase = '' + runHook preInstall + mkdir -p "$out" + cp rendered/*.pdf "$out/" + runHook postInstall + ''; + + meta = { + description = "Markdown-authored PDF slides for the Nix training modules"; + platforms = lib.platforms.linux; + }; +} diff --git a/slides/theme/nix-training.css b/slides/theme/nix-training.css new file mode 100644 index 0000000..32ee55d --- /dev/null +++ b/slides/theme/nix-training.css @@ -0,0 +1,248 @@ +/* @theme nix-training */ + +@import "default"; + +:root { + --ink: #17212b; + --muted: #52606d; + --paper: #f7f4ec; + --panel: #ebe6da; + --blue: #315c8c; + --green: #3d7055; + --orange: #b85c32; + --yellow: #e2b93b; +} + +section { + background: + linear-gradient(90deg, var(--blue) 0 10px, transparent 10px), + var(--paper); + color: var(--ink); + font-family: "Inter", sans-serif; + font-size: 27px; + line-height: 1.3; + padding: 50px 64px 46px 76px; +} + +section::after { + color: var(--muted); + font-size: 16px; + right: 30px; +} + +h1, +h2, +h3 { + color: var(--blue); + font-weight: 750; + letter-spacing: -0.025em; +} + +h1 { + font-size: 46px; + margin: 0 0 24px; +} + +h2 { + font-size: 31px; +} + +p, +ul, +ol, +table, +pre, +blockquote { + margin-top: 16px; + margin-bottom: 16px; +} + +li { + margin: 7px 0; +} + +strong { + color: var(--orange); +} + +a { + color: var(--blue); +} + +code { + font-family: "JetBrains Mono", monospace; +} + +pre { + background: #1f2933; + border-left: 6px solid var(--yellow); + border-radius: 4px; + color: #f5f7fa; + font-size: 20px; + line-height: 1.28; + padding: 16px 20px; +} + +pre code { + background: transparent; + color: inherit; +} + +.hljs-keyword, +.hljs-built_in, +.hljs-meta { + color: #ff9d72; +} + +.hljs-string, +.hljs-attr, +.hljs-variable, +.hljs-template-variable { + color: #a8d8ff; +} + +.hljs-number, +.hljs-literal { + color: #f8d47a; +} + +.hljs-title, +.hljs-function, +.hljs-section { + color: #9ee6b8; +} + +.hljs-comment, +.hljs-quote { + color: #9fb3c8; +} + +table { + border-collapse: collapse; + font-size: 22px; + width: 100%; +} + +th { + background: var(--blue); + color: white; +} + +th, +td { + border: 1px solid #c9c2b4; + padding: 9px 13px; +} + +tbody tr:nth-child(even) { + background: #efeade; +} + +blockquote { + border-left: 6px solid var(--green); + color: var(--ink); + font-size: 32px; + font-weight: 650; + padding-left: 24px; +} + +section.title { + background: + radial-gradient(circle at 82% 20%, #3f79ad 0 9%, transparent 9.5%), + linear-gradient(135deg, #17212b 0 58%, #315c8c 58% 100%); + color: white; + padding: 100px 90px; +} + +section.title::after { + display: none; +} + +section.title h1, +section.title h2 { + color: white; +} + +section.title h1 { + font-size: 64px; + margin-bottom: 20px; +} + +section.title h2 { + font-size: 34px; + font-weight: 500; +} + +section.title p { + color: #dce8f2; + font-size: 25px; +} + +section.section { + background: + linear-gradient(90deg, var(--green) 0 14px, transparent 14px), + #edf1e9; +} + +section.section h1 { + color: var(--green); +} + +section.exercise, +section.demo, +section.recap, +section.appendix { + padding-top: 74px; +} + +section.exercise::before, +section.demo::before, +section.recap::before, +section.appendix::before { + color: white; + font-size: 14px; + font-weight: 800; + left: 76px; + letter-spacing: 0.14em; + padding: 5px 10px; + position: absolute; + top: 28px; +} + +section.exercise::before { + background: var(--orange); + content: "EXERCISE"; +} + +section.demo::before { + background: var(--blue); + content: "LIVE DEMO"; +} + +section.recap::before { + background: var(--green); + content: "RECAP"; +} + +section.appendix::before { + background: var(--muted); + content: "APPENDIX"; +} + +section.exercise { + background: + linear-gradient(90deg, var(--orange) 0 10px, transparent 10px), + #fbf0e9; +} + +section.recap { + background: + linear-gradient(90deg, var(--green) 0 10px, transparent 10px), + #edf1e9; +} + +section.appendix { + background: + linear-gradient(90deg, var(--muted) 0 10px, transparent 10px), + #f1f3f4; +} diff --git a/tests/test_publish_vm_release.py b/tests/test_publish_vm_release.py index 7325040..1dada8e 100644 --- a/tests/test_publish_vm_release.py +++ b/tests/test_publish_vm_release.py @@ -15,7 +15,7 @@ class PublishVmReleaseTests(unittest.TestCase): - def setUp(self): + def setUp(self) -> None: self.temp = tempfile.TemporaryDirectory() self.addCleanup(self.temp.cleanup) self.root = Path(self.temp.name) @@ -31,15 +31,29 @@ def setUp(self): import sys args = sys.argv[1:] -with open(os.environ["MOCK_LOG"], "a") as calls: +with open(os.environ["MOCK_LOG"], "a", encoding="utf-8") as calls: calls.write(json.dumps(args) + "\\n") if len(args) > 1 and args[1] == os.environ.get("MOCK_FAIL_COMMAND"): sys.exit(1) +repo = os.environ["GH_REPO"] if args[:2] == ["release", "view"]: - print(Path(os.environ["MOCK_RELEASE"]).read_text()) -elif args[:2] not in (["release", "create"], ["release", "upload"], ["release", "edit"]): + if len(args) != 7 or args[3:] != ["--repo", repo, "--json", "isDraft,targetCommitish,assets"]: + sys.exit("Malformed release view") + print(Path(os.environ["MOCK_RELEASE"]).read_text(encoding="utf-8")) +elif args[:2] == ["release", "create"]: + required = ["--repo", repo, "--target", os.environ["GITHUB_SHA"], "--draft"] + if len(args) < 3 or any(value not in args for value in required): + sys.exit("Malformed release create") +elif args[:2] == ["release", "upload"]: + if len(args) != 7 or args[4:] != ["--repo", repo, "--clobber"]: + sys.exit("Malformed release upload") +elif args[:2] == ["release", "edit"]: + if len(args) != 7 or args[3:] != ["--repo", repo, "--draft=false", "--latest"]: + sys.exit("Malformed release edit") +else: sys.exit("Unexpected gh command") -""" +""", + encoding="utf-8", ) gh.chmod(0o755) self.env = os.environ | { @@ -65,20 +79,33 @@ def setUp(self): self.image = self.root / "nix-training-x86_64.qcow2" self.image.write_bytes(b"checked image") - def run_script(self, *args, success=True, release=None, **env): - self.release_path.write_text(json.dumps(self.release if release is None else release)) - self.calls_path.write_text("") + def run_script( + self, + *args: object, + success: bool = True, + release: dict[str, object] | None = None, + **env: str, + ) -> list[list[str]]: + self.release_path.write_text( + json.dumps(self.release if release is None else release), encoding="utf-8" + ) + self.calls_path.write_text("", encoding="utf-8") + self.output_path.write_text("", encoding="utf-8") result = subprocess.run( ["bash", str(SCRIPT), *map(str, args)], env=self.env | env, capture_output=True, text=True, + timeout=20, ) if success: self.assertEqual(result.returncode, 0, result.stderr) else: - self.assertNotEqual(result.returncode, 0, result.stdout) - return [json.loads(line) for line in self.calls_path.read_text().splitlines()] + self.assertNotEqual(result.returncode, 0, result.stderr) + return [ + json.loads(line) + for line in self.calls_path.read_text(encoding="utf-8").splitlines() + ] def test_prepare_creates_draft_and_exports_attempt_specific_tag(self): calls = self.run_script("prepare") @@ -87,7 +114,7 @@ def test_prepare_creates_draft_and_exports_attempt_specific_tag(self): self.assertIn("--draft", calls[0]) self.assertNotIn("--latest", calls[0]) self.assertIn(SHA, calls[0]) - self.assertEqual(self.output_path.read_text(), f"tag={TAG}\n") + self.assertEqual(self.output_path.read_text(encoding="utf-8"), f"tag={TAG}\n") def test_full_rerun_uses_a_new_draft(self): calls = self.run_script("prepare", GITHUB_RUN_ATTEMPT="2") diff --git a/tests/test_web_readiness.py b/tests/test_web_readiness.py index cb01be9..2874107 100644 --- a/tests/test_web_readiness.py +++ b/tests/test_web_readiness.py @@ -15,7 +15,7 @@ class WebReadinessTests(unittest.TestCase): - def setUp(self): + def setUp(self) -> None: self.temp = tempfile.TemporaryDirectory() self.addCleanup(self.temp.cleanup) self.root = Path(self.temp.name) @@ -32,10 +32,12 @@ def setUp(self): import sys calls = Path(os.environ["MOCK_CURL_CALLS"]) -attempt = len(calls.read_text().splitlines()) if calls.exists() else 0 -with calls.open("a") as log: +attempt = len(calls.read_text(encoding="utf-8").splitlines()) if calls.exists() else 0 +with calls.open("a", encoding="utf-8") as log: log.write(json.dumps(sys.argv[1:]) + "\\n") -responses = json.loads(Path(os.environ["MOCK_RESPONSES"]).read_text()) +responses = json.loads(Path(os.environ["MOCK_RESPONSES"]).read_text(encoding="utf-8")) +if not responses: + sys.exit("MOCK_RESPONSES must not be empty") response = responses[min(attempt, len(responses) - 1)] print(response.get("body", "")) print(response.get("error", ""), file=sys.stderr) @@ -50,13 +52,16 @@ def setUp(self): "MOCK_CURL_CALLS": str(self.calls), } - def write_command(self, name, text): + def write_command(self, name: str, text: str) -> None: command = self.bin / name - command.write_text(text) + command.write_text(text, encoding="utf-8") command.chmod(0o755) - def probe(self, responses, timeout="5"): - self.responses.write_text(json.dumps(responses)) + def probe( + self, responses: list[dict[str, object]], timeout: str = "5" + ) -> tuple[subprocess.CompletedProcess[str], list[list[str]]]: + self.responses.write_text(json.dumps(responses), encoding="utf-8") + self.calls.write_text("", encoding="utf-8") result = subprocess.run( [ "bash", "-Eeuo", "pipefail", "-c", @@ -68,16 +73,35 @@ def probe(self, responses, timeout="5"): text=True, timeout=10, ) - calls = [json.loads(line) for line in self.calls.read_text().splitlines()] if self.calls.exists() else [] + calls = [ + json.loads(line) + for line in self.calls.read_text(encoding="utf-8").splitlines() + ] return result, calls + def assert_curl_call(self, call: list[str], *, max_time: str) -> None: + self.assertEqual( + call, + [ + "--fail", + "--silent", + "--show-error", + "--noproxy", + "*", + "--connect-timeout", + "5", + "--max-time", + max_time, + "http://localhost/", + ], + ) + def test_immediate_ready_page(self): result, calls = self.probe([{"body": HEADING}], timeout="0") self.assertEqual(result.returncode, 0, result.stderr) self.assertEqual(len(calls), 1) self.assertIn(HEADING, result.stdout) - self.assertIn("--show-error", calls[0]) - self.assertIn("--max-time", calls[0]) + self.assert_curl_call(calls[0], max_time="1") def test_connection_refused_then_stale_content_then_ready(self): result, calls = self.probe([ @@ -130,7 +154,7 @@ def test_diagnostics_preserve_rebuild_failure_and_fixture(self): self.write_command("journalctl", "#!/usr/bin/env bash\necho MOCK_NGINX_JOURNAL\nexit 1\n") fixture = self.root / "07-nixos/web-server/site.json" fixture.parent.mkdir(parents=True) - fixture.write_text('{"title": "Original fixture"}\n') + fixture.write_text('{"title": "Original fixture"}\n', encoding="utf-8") result = subprocess.run( ["bash", str(WEB_CHECK), str(self.root)], env=self.env, @@ -142,7 +166,9 @@ def test_diagnostics_preserve_rebuild_failure_and_fixture(self): self.assertIn("switching to version one", result.stderr) self.assertIn("MOCK_NGINX_STATUS", result.stderr) self.assertIn("MOCK_NGINX_JOURNAL", result.stderr) - self.assertEqual(fixture.read_text(), '{"title": "Original fixture"}\n') + self.assertEqual( + fixture.read_text(encoding="utf-8"), '{"title": "Original fixture"}\n' + ) if __name__ == "__main__":