diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c22823f..e9ed50c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -28,7 +28,9 @@ jobs: os: [ubuntu-latest, windows-latest] steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - uses: actions/setup-node@v7 # TODO: pin to a reviewed full commit SHA. + with: + persist-credentials: false + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: node-version: ${{ matrix.node }} cache: npm @@ -60,7 +62,9 @@ jobs: gate: check steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - uses: actions/setup-node@v7 # TODO: pin to a reviewed full commit SHA. + with: + persist-credentials: false + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: node-version: 22 cache: npm diff --git a/AGENTS.md b/AGENTS.md index c92ee01..5b3e731 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -19,9 +19,13 @@ Reference projects, usually checked out next to this repo (read-only, copy from npm run typecheck && npm test && npm run build node scripts/scaffold-check.mjs # scaffold + fmt + clippy -D warnings + test node scripts/scaffold-check.mjs --gate check # faster: cargo check only +node scripts/scaffold-check.mjs --gate fmt # cargo fmt --check only, no build +node scripts/scaffold-check.mjs --gate doc # cargo doc --no-deps, RUSTDOCFLAGS=-D warnings ``` -Presets: `rustaman strobe cli tui lib minimal`. Override any answer with `--set features.tray=true`. +Presets: `rustaman strobe cli tui lib minimal`. Override any answer with `--set features.tray=true` +(split on the first `=`), the project name with `--name `. The doc gate is not part of the +default full gate; run it too when you touch doc comments. An existing `CARGO_TARGET_DIR` is used. ## Rules diff --git a/CHANGELOG.md b/CHANGELOG.md index 0c105a8..28cb365 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,79 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- On Windows the target folder in the review hint, the `cd` line and the recreate command uses `/` + separators (`out/app`, `D:/proj/app`), so Git Bash no longer eats the backslashes and the + recreate command needs no quoting for them. +- A workspace without the changelog generator no longer mentions `cargo xtask changelog` in + `docs/decisions/D1.md`. +- A workspace scaffolded `--without changelogGen` no longer ships `cargo xtask changelog`, which + would have rewritten the hand-edited CHANGELOG.md: the module, command and help text are gated. +- Generated projects are `cargo fmt --check` clean for every project name from 1 to 64 characters: + lines that grew with the name (GUI `build.rs`, `main.rs`, `config.rs`, the screenshot and brand + examples, CLI `main.rs` and tests, the TUI log path) now name the crate through a short alias + (`use as app;`) or a constant, so rustfmt's layout no longer depends on the name. + GUI projects of 14+ characters, workspaces of 16+, used to fail. `test/name-length.test.ts` + guards it. +- Projects with long names pass their own header check: `Dependencies:` lines name "the library + crate" instead of its (up to 68-character) path, and the check no longer counts the `Module:` + line, whose value is the file's path, against the 100-column limit. +- `RUSTDOCFLAGS="-D warnings" cargo doc --no-deps` passes on eframe GUI projects (a private and a + redundant intra-doc link in `src/gui/run.rs`) and with `--with tray` off Windows (`src/tray.rs` + linked the Windows-only `win::tray`), and for a `cli` with SQLite (`src/db.rs` linked the private + `MIGRATIONS`). +- Generated docs say what the project has: the `unsafe` boundary check names `src/win/` (plus + `src/gui/run/` on winit-glow) instead of a `src/gui/run/` an eframe project doesn't have, and + the app and shortcut docs mention the tray and command palette only when they are enabled. +- Project names that cannot build are refused up front, on the command line and in the name + prompt: Rust keywords from every edition (`fn`, `type`, `gen`, `try` …), Cargo-reserved names + (`build`, `deps` …), Windows device names (`con`, `nul` …), and names over 64 characters (the + crates.io limit, which `--bin` now shares). A long name used to die mid-write. +- A target folder whose name can't be a crate name (`create-rust-app MyDir -y`) still gets the + default crate name, but a one-line note on stderr now says so and points at `--name`. +- An MSRV newer than the pinned toolchain, or older than the edition allows (2024 needs 1.85), + is an argument error (exit 2), whether it came from `--msrv`, `--toolchain`, `--set` or a preset. + It used to scaffold a project cargo then refused to build. +- Options the chosen kind ignores (`--preset lib --with tray`, `--preset lib --bin foo`, + `--preset cli --gui winit-glow`, `subcommands` on a TUI or without clap) each print a one-line + note on stderr instead of vanishing silently; `--quiet` hides them. `--json` reports `guiStack` + as `""` for kinds without a GUI, as it already did `themeBase`. +- An empty tagline reads as the project name everywhere: the README's bold line used to come out + as `****` while `Cargo.toml` already fell back to the name. +- Scaffolding into a folder that holds only a fresh `git init` makes the first commit there, + staging the generated files by path (anything else in the folder stays untracked). Inside some + other repository git is still skipped, and the finished summary no longer promises a commit. +- A write that fails midway no longer leaves a partial project: a folder the run created is + removed, and in an existing folder only the files the run added are, with the error saying + which. `--force` lists the existing files it overwrote on stderr. +- The "again without prompts" command recreates the same project: it carries `--accent`, + `--author`, `--github`, display name and email, names the real target folder, and adds `--name` + when the crate name differs from the folder's. +- `--help`, the README and CONTRACTS say what `--json` does without `--dry-run`: it writes the + files but skips fetch, git, cargo check and `--open`. +- Esc inside Customize steps back instead of quitting the run: on the Customize menu it returns + to the review, inside a section (or "Start over from a preset") it reopens the menu and drops + only that section's edits. The footer there says `esc back`. Ctrl-C still quits everywhere, + and Esc on the name, kind and review screens still cancels. +- Ctrl-C during the run steps (writing, `cargo fetch`, `git init`, `cargo check`) shows the + cursor again, settles the spinner line and says the partly created folder was left in place, + then exits 130. The cursor used to stay hidden, with no message. +- "Start over from a preset" uses the preset you pick even when `--kind` or `--preset` was given; + it used to keep the flag's kind (`--kind lib`, start over as a desktop app: still a library). +- With a positional folder, the review's "Create it" hint names that folder + (`create-rust-app fl-dir`, renamed in Customize: `writes ./fl-dir`, not the new name). +- The Licence + Rust prompts cross-check what you type, as the flags do: an MSRV older than the + edition allows, or a toolchain older than the MSRV, is refused inline with the reason; spaces + around a version are trimmed. A long message wraps on the rail instead of past the edge. +- Lists taller than the terminal scroll: the window follows the focused row, with "↑ n more" / + "↓ n more" lines, and no stale frame lines are left in the scrollback after a choice. +- At 40 columns no option row, footer or prompt message wraps: descriptions shorten, then drop, + then labels are cut with an ellipsis, and footers drop their least useful hints first. The + terminal size is read on every frame, so a resize is honoured. +- Without colour (`NO_COLOR`, `--no-color`) the focused multi-select row gets a `›` mark (`>` in + ASCII) and the text cursor shows as a caret glyph, where both used to be invisible. + `--no-color` now emits no colour escape codes at all: the text prompt's inverse-video cursor + ignored the flag. + - A release build of a GUI app run from a terminal prints its `--help`, `--version`, usage errors and headless output: it attaches to the parent console just before printing (`src/win/console.rs`). Opening the window never attaches, so closing the terminal doesn't close @@ -32,9 +105,32 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 committed what was there, printed success and exited 0. Occupied folders are now refused before any question (unless `--force`), and a failed write stops the run with exit code 1. - Animated prompts no longer flicker. +- Generated workflows check out with `persist-credentials: false`, so the job token is not left + in `.git/config` for build scripts to read (zizmor `artipacked`). No step needed it: `gh` + authenticates with `GH_TOKEN`. +- The generated release build no longer restores `Swatinem/rust-cache`: the Actions cache is + writable from any branch's CI, so a tagged build could have shipped a poisoned entry (zizmor + `cache-poisoning`, high). +- A fresh project's `CHANGELOG.md` is what its generator writes: `cargo run --example changelog -- + --check` passes straight after scaffolding and regenerating is a no-op (`cargo xtask changelog` + on workspaces too). Both generators share the header, `Unreleased` entries carry no commit hash + (released ones still do), and CLAUDE.md / CONTRIBUTING.md say the file is generated and name + the command whenever the generator ships. +- Generated docs: the README says a theme is eleven colours, as the themes do; CLAUDE.md and + CONTRIBUTING.md no longer claim a check enforces `assert!` messages, and list every place the + header check walks (`benches/`, `build.rs` too) with each module-name form; the GUI README lists + the Linux runtime libraries; CONTRIBUTING says attestation needs a public repository or GitHub + Enterprise Cloud; the release workflow's matrix comment says what else a new target needs. +- This repo's docs match the code: CONTRACTS lists `post.fetch` and every binary extension the + engine copies raw, PLAN's `npm pack` check names `dist/` and `templates/`, and the changelog's + CI line names Node 22 and 26 (the `engines` floor is 22.18). +- This repo's CI pins `actions/setup-node` to a full commit SHA (v7.1.0) and checks out without + persisting the token. ### Changed +- TUI projects build on ratatui 0.30 and crossterm 0.29 (were 0.29 and 0.28); the templates needed + no code changes, and the scaffold still builds on the 1.98 MSRV. - The classic Windows console gets 24-bit colour, block letters and a glyph set its font can draw, instead of an ASCII fallback. - Motion: shimmering focused option, cycling marker, wave spinner, live file and crate counters, @@ -53,6 +149,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- `scaffold-check` gains `--gate fmt` (rustfmt only, no build), `--gate doc` (`cargo doc --no-deps` + with `RUSTDOCFLAGS=-D warnings`, opt-in) and `--name `; it splits `--set` on the first `=` + and keeps an existing `CARGO_TARGET_DIR`. - `--with subcommands` on desktop apps: `app ` runs a headless job (`themes`, `paths` to start with) and exits, a bare run opens the window as before, and `tests/cli.rs` covers both paths. - `--base `: lay the signature theme's accent on any shipped theme's surfaces, e.g. @@ -69,7 +168,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - README documents `--set`, `--bin` and `--preset custom`. - Project README covering presets, CLI flags, Rust conventions, and contributing. - MIT license, copyright 2026 Lawrence Norton. -- Node 20, 22, and 26 CI on Linux and Windows, plus per-preset Rust scaffold checks. +- Node 22 and 26 CI on Linux and Windows, plus per-preset Rust scaffold checks. - Weekly Dependabot updates for npm dependencies and GitHub Actions. - In-process preset e2e checks for rendered tokens, directives, unique destinations, and path-derived Rust module headers. diff --git a/README.md b/README.md index a8fe7d5..e9258df 100644 --- a/README.md +++ b/README.md @@ -86,14 +86,14 @@ create-rust-app [dir] [options] | Flag | Meaning | |---|---| | `[dir]` | Target directory (defaults to the project name) | -| `--name ` | Crate / project name, `^[a-z][a-z0-9-]*$` | -| `--bin ` | Executable name when it differs from the crate (writes `[[bin]]`; clap, README and release follow it) | +| `--name ` | Crate / project name, `^[a-z][a-z0-9-]*$`, at most 64 characters; not a Rust keyword (`fn`, `type`, `gen` …), `test`/`std`/`core`/`alloc`/`proc-macro`, a Cargo-reserved name (`build`, `deps`, `examples`, `incremental`) or a Windows device name (`con`, `nul` …) | +| `--bin ` | Executable name when it differs from the crate (writes `[[bin]]`; clap, README and release follow it). Lowercase letters, digits, `-` and `_`, at most 64 characters, same Cargo and Windows reserved names | | `--preset

` | `rustaman` `strobe` `cli` `tui` `lib` `minimal`, or `custom` for no preset (the defaults) | | `--kind ` | `cli` `gui` `tui` `lib` `workspace` | | `--gui ` | `eframe` (wgpu) or `winit-glow` (winit + glutin + egui_glow) | | `--base ` | Surfaces the signature theme lays your accent on: any shipped theme id, e.g. `graphite` for neutral greys (default `midnight`) | | `--edition ` | `2024` or `2021` | -| `--msrv ` | `rust-version` in Cargo.toml (default `1.98`) | +| `--msrv ` | `rust-version` in Cargo.toml (default `1.98`); no newer than `--toolchain`, and at least `1.85` for edition 2024 (`1.56` for 2021) | | `--toolchain ` | Exact channel pinned in `rust-toolchain.toml` and CI (default `1.99.1`) | | `--license ` | `MIT`, `MIT+CommonsClause`, `Apache-2.0`, `MIT OR Apache-2.0` | | `--author ` | Author for Cargo.toml, LICENSE, headers | @@ -110,10 +110,10 @@ create-rust-app [dir] [options] | `--no-cargo-check` | Skip `cargo check` even if a preset turns it on | | `--open ` | Open the project in `code` or `cursor` when done | | `--dry-run` | Print the plan, write nothing | -| `--json` | Machine-readable output | +| `--json` | Machine-readable output: prints only `{ answers, files }` on stdout (notes go to stderr). Without `--dry-run` it still writes the files, but skips `cargo fetch`, git, `cargo check` and `--open`; `answers.post` shows what was asked, not what ran | | `--no-color` | Plain output (also honoured: `NO_COLOR`, non-TTY, `CI`) | | `--quiet` | Only errors | -| `--force` | Write into a non-empty directory | +| `--force` | Write into a non-empty directory; lists the existing files it overwrote on stderr | | `--help`, `--version` | The usual | A non-TTY stdin implies `--yes`. Answer flags apply left to right, so a later `--set` or diff --git a/docs/CONTRACTS.md b/docs/CONTRACTS.md index 25675fb..bfc62f0 100644 --- a/docs/CONTRACTS.md +++ b/docs/CONTRACTS.md @@ -12,18 +12,21 @@ bin/create-rust-app.ts entry; imports src/cli.ts and calls main(process.argv src/cli.ts main(argv): args → answers → ctx → plan → write → post → summary src/args.ts parseArgv(argv) → { dir, flags, overrides } (node:util parseArgs) src/presets.ts PRESETS: Record>; DEFAULTS: Answers -src/prompts.ts ask(partial, caps, targetCheck) → Answers (@clack/core) +src/prompts.ts ask(partial, caps, targetCheck, dir?) → Answers (@clack/core) src/context.ts buildContext(answers) → Ctx (CORE, exists) src/engine/directives.ts applyDirectives(text, flags) → text (CORE, exists) src/engine/render.ts renderText(text, ctx, dest) → text (CORE, exists) src/engine/groups.ts GROUPS: [{ id, when(ctx) }] (CORE, exists) src/engine/plan.ts buildPlan(ctx) → Promise (CORE, exists) -src/engine/write.ts writePlan(plan, targetDir, {force, dryRun, onFile}); targetProblem(dir) +src/engine/write.ts writePlan(plan, targetDir, {force, dryRun, onFile}); targetProblem(dir); existingFiles(plan, dir) + (on a failed write, writePlan removes the target if it created it, else only what it added) src/gen/header.ts moduleFor(dest, ctx) → string (CORE, exists) src/gen/index.ts generate(ctx) → PlanEntry[] (Cargo.toml, deny.toml …) src/gen/cargo.ts, deps.ts, deny.ts src/post/{git,cargo,open}.ts -src/reproduce.ts reproduceCommand(answers, dir?) → string +src/reproduce.ts reproduceCommand(answers, dir?) → string; shownTarget(dir, name, cwd?) → string + (dir = the real target as shownTarget prints it; adds --name when it differs + from the folder's name; carries every answer that differs from the preset) src/ui/{tty,glyphs,rainbow,banner,theme,labels,choose,rail,motion,spinner}.ts templates//files/** template files; templates//manifest.js optional test/*.test.ts node --test @@ -46,16 +49,38 @@ test/*.test.ts node --test commandPalette, screenshotExample, demo, subcommands }, // all bool; subcommands: cli or GUI kinds, with clap tooling: { ci, release, cargoDeny, dependabot, toolchainPin, agentDocs, headerCheck, unsafeCheck, changelogGen, issueTemplates, codeowners, securityMd }, // all bool - post: { git: bool, cargoCheck: bool, open: 'none'|'code'|'cursor' }, + post: { git: bool, fetch: bool, cargoCheck: bool, open: 'none'|'code'|'cursor' }, preset: string | null, } ``` +## Validation (src/context.ts, shared by flags, `--set` and prompts) + +- `validateName(name) → string | null`: `^[a-z][a-z0-9-]*$`, at most `MAX_NAME_LENGTH` (64, the + crates.io limit), no trailing or doubled dash, not `test core std alloc proc-macro`, not a Rust + keyword (`RUST_KEYWORDS`: strict and reserved, editions 2015–2024), not Cargo-reserved + (`CARGO_RESERVED`: `deps examples build incremental`), not a Windows device name (`WINDOWS_DEVICE_RE`). +- `validateBin(bin) → string | null`: `^[a-z][a-z0-9_-]*$`, at most 64, the same Cargo and Windows rules. +- `validateRustVersions(msrv, toolchain, edition) → string | null`: cross-field, run by `src/cli.ts` + after flags, `--set` and preset defaults resolve (and again after the prompts); exit 2. `msrv` ≤ + `toolchain` (numeric compare) and `msrv` ≥ `EDITION_MIN_RUST[edition]` (2021: 1.56, 2024: 1.85). + +## `--json` + +Prints `{ answers: ReportedAnswers, files: string[] }` and nothing else on stdout; notes and errors +go to stderr. Without `--dry-run` it writes the files but runs no post-step (fetch, git, cargo check, +open); `answers.post` echoes the request, not what ran. Whether it should run them is undecided. + ## Ctx = Answers + derived `buildContext(answers)` first applies `effectiveAnswers(answers)` (src/context.ts): options the kind never generates are set to `false` (desktop features and `unsafeCheck` without a GUI; `config` for -`lib`, `tui`, and `cli` without serde). The Ctx and `--json` both carry these effective values. +`lib`, `tui`, and `cli` without serde). The Ctx and `--json` both carry these effective values; +`--json` reports `reportedAnswers(answers)` (type `ReportedAnswers`), which also reads `guiStack: ''` +without a GUI, like `themeBase`. The Ctx keeps a stack value there; no flag or token reads it. +`ignoredOptions(overrides, answers) → string[]` names each explicitly given option the kind drops +(`--with tray` on a lib, `--bin` on a lib, `--gui` without a GUI, `subcommands` without clap or on a +TUI/lib …); a non-interactive run prints each as a `note:` line on stderr unless `--quiet`. It then adds: `crate` (snake), `Name` (Pascal), `NAME` (SCREAMING), `year`, `appCrate` (workspace: `-app`, else ``), `flags: Set`, `tokens`. @@ -92,7 +117,8 @@ Unknown tokens throw (so a typo fails tests loudly). - Optional `templates//manifest.js`: `export default function (ctx, files) → files'` where `files` is `[{ src, dest }]` (absolute src, relative dest). Use it to drop or rename files. Without a manifest all files are included. -- Binary files (`.png .ico .ttf .otf .woff2 .zip`) are copied raw. Everything else is text and goes +- Binary files (`.png .ico .ttf .otf .woff .woff2 .zip .jpg .jpeg .gif .wav`, case-insensitive; + `BINARY` in `src/engine/plan.ts`) are copied raw. Everything else is text and goes through `renderText`. - Line directives work in any text file. A line whose trimmed content, after an optional comment leader (`//`, `#`, ` src/main.rs:17:7`. +- Root cause: `src/context.ts:11` only rejects `test core std alloc proc-macro self crate super`; no Rust keyword list. +- Logs: `s4-name-00.txt` (match), `s4-name-01.txt` (async), `s4-name-02.txt` (type), `s4-name-keyword-create.txt`. + +### F3 — Ctrl-C during the run steps leaves the cursor hidden, prints nothing, leaves a partial project (bug) +- Keys: rustaman, Create, Ctrl-C ~1s into `cargo fetch`. Exit 130 (killed by SIGINT), `cursor_visible_at_end=false` + (last `ESC[?25l` never followed by `?25h`), spinner line left unterminated, no message. `projects/interactive/cx-fetch` + left with all files but no Cargo.lock / git. +- Root cause: `src/ui/rail.ts:273` hides the cursor and relies on `finally` (`:281`) which never runs on SIGINT; + `tasks()` has no SIGINT handler (unlike `src/ui/spinner.ts:48` and `src/ui/banner.ts:102`, which do). +- Log: `logs/interactive/s3-ctrlc-during-fetch.{txt,raw,meta.json}`. + +### F4 — With a positional dir, renaming in Customize makes the review and the reproduce command lie (bug) +- Command `create-rust-app fl-dir --preset cli`; Customize → Name → `fl-renamed`. Review: `Create it writes ./fl-renamed`. + Actual: `Wrote 30 files to fl-dir`; reproduce line: `npx … fl-renamed --preset cli …` (would write elsewhere). +- Root cause: hint `src/prompts.ts:149` uses `a.name`; target is `resolve(dir ?? answers.name)` at `src/cli.ts:222`; + reproduce takes the name as positional. +- Log: `logs/interactive/s7-dir-and-rename.txt`. + +### F5 — Esc inside any Customize section or the Customize menu quits the whole program, discarding all edits (friction, high) +- Keys: review → Customize → (menu | Crates | Command line | GUI runtime | App features | Tooling | Licence | MSRV | After | + Name | tagline | Start over) → Esc. Every one: exit 130, "Nothing written.". The menu has a "Back to review" row, + but Esc, the obvious "back" key, cancels. Footer says only `esc cancel`, which doesn't say it cancels the whole run. + "Start over from a preset" can't be backed out of either: you pick a preset or quit. +- Root cause: every section prompt goes through `got()` (`src/prompts.ts:38-44`), which throws `Cancelled`; + `customize()` (`src/prompts.ts:175` onwards) never treats a cancel as "back to review". +- Logs: `s3-custmenu-esc.txt`, `s3-sect-{crates,cmdline,app,appfeat,tooling,licence,msrv,after,details,tagline,preset}-esc.txt`. + +### F6 — No length limit on the name; a 300-char name passes validation then fails at write (bug, low) +- Typed 300×`a`: accepted, review shown, Create → `✖ Writing 30 files failed: ENAMETOOLONG … mkdir '<300-char path>'`, exit 1. + No dir left behind (good). +- Root cause: `src/context.ts:8-14` (no max length; the target check `src/engine/write.ts:6` only tests existence). +- Log: `logs/interactive/s4-name-long.txt`. + +### F7 — Cargo-reserved / Windows-device names accepted as project name although rejected as command name (bug) +- `build`, `deps`, `con`, `nul` accepted at the name prompt (`s4-name-11..14`). As the command name, `deps` and `con` + are rejected (`s4-details-invalid`). The binary defaults to the crate name, so `con` ends up as `con.exe`. + `cargo new build` → `error: invalid package name 'build'`; `cargo new con` warns that it won't work on Windows. +- Root cause: `validateName` (`src/context.ts:8`) doesn't apply the `validateBin` rules (`src/context.ts:17-24`); + `effectiveAnswers` clears `bin` when it equals the crate name (`src/context.ts:65`), so `buildContext` (`:76`) never checks it. +- Logs: `s4-name-11.txt`…`s4-name-14.txt`, `s4-details-invalid.txt`. + +### F8 — MSRV and toolchain are validated only for shape: MSRV 9.0 with toolchain 1.0.0 and edition 2024 is accepted (bug, medium) +- Customize → Licence + Rust → MSRV `9.0`, toolchain `1.0.0`. Written: `rust-version = "9.0"`, `channel = "1.0.0"`. + Shape errors are inline and clear ("Use a version like 1.98", "Use an exact version like 1.99.1"); a leading space + (` 1.98`) is rejected without trimming (nit); `stable`/`nightly-…` are rejected, which is defensible. +- Root cause: `src/prompts.ts:240-241` (regex only; no MSRV ≤ toolchain check, no edition 2024 ⇒ ≥1.85 check, no trim). +- Log: `logs/interactive/s4-rust-invalid.txt`; project `projects/interactive/rv-cli`. + +### F9 — An empty tagline is written two different ways (bug, low) +- Customize → tagline cleared → Create. `Cargo.toml description = "dv-cli"` (falls back to the name), README has `****` (empty bold). +- Root cause: `src/context.ts:121` (`tagline: a.tagline || ''`) vs the fallback in `src/gen/cargo.ts:130`; template `templates/base/files/README.md:5`. + The tagline is also not shown on the review screen, so the user can't spot it. +- Log: `logs/interactive/s4-details-invalid.txt`; project `projects/interactive/dv-cli`. + +### F10 — At 40 columns, option rows overflow and wrap (bug, medium) +- `s5-narrow-40`: kind picker rows like `│ ● Desktop app recommended egui +` / `wg…` and Customize menu rows wrap onto + two lines. Footers (`space toggle · a all · enter confirm` / `· esc cancel`) and long messages also wrap. +- Root cause: `src/ui/choose.ts:38` `room = Math.max(10, cols - indent - labelW - 6)`: the minimum of 10 forces rows + wider than the terminal. Footers at `src/ui/choose.ts:74,121` aren't clipped. The review note itself degrades well + (licence moves into the body). +- Logs: `s5-narrow-40.txt`, `s5-tiny-40x10.txt`. + +### F11 — Lists taller than the terminal: no scrolling, focused row and message off-screen, stale frames left behind (bug, medium) +- `s5-short-10` (100×10): App features (15 lines + footer) and Tooling show only the bottom; with the cursor on `Themes` + (top) the focused row and the `◆ App features` message are off-screen, so space toggles a row you can't see. The theme + list (11 lines) loses its message too. After submit/cancel, the active frame's top lines stay in scrollback above the + echo (`s5-tiny-40x10` final: `◼ CODEOWNERS …` / `guardrails` above `■ Tooling`). +- Root cause: `pick`/`pickMany` render every option (`src/ui/choose.ts:68-75`, `107-122`) with no window. @clack/core's + primitives don't window; @clack/prompts does it with `maxItems`/`limitOptions`, checked via Context7 (/bombshell-dev/clack), but that package isn't a dependency. +- Logs: `s5-short-10.txt`, `s5-tiny-40x10.txt`. + +### F12 — Without colour, the multiselect focus and the text cursor position are invisible (bug, medium a11y) +- `NO_COLOR=1`, Tooling, cursor moved to `Dependabot`: every row renders identically; nothing marks the focused row. + Single-select is fine (●/○). In the name prompt, after ← ←, the input shows `nc-env` with no cursor mark (the `█` + appears only when the cursor is at the end). +- Root cause: focus is shown only through `shimmer()` → `bold()`, which returns plain text at tier `none` + (`src/ui/choose.ts:118`, `src/ui/motion.ts:32`, `src/ui/rainbow.ts:122`). The text cursor uses clack's + `userInputWithCursor` (`src/ui/rail.ts:176`) = `util.styleText('inverse')`, which honours NO_COLOR. +- Log: `logs/interactive/s6-no-color-env.txt` (snap "tooling multiselect cursor on row 3", "text cursor moved left"). + +### F13 — `--no-color` still emits `ESC[7m … ESC[27m` (bug, low) +- `--no-color`, edit the name with ←: 3× `ESC[7m`/`ESC[27m` in the raw stream (`nc-fla\x1b[7mg\x1b[27m`). NO_COLOR env: 0 SGR. +- Root cause: same `userInputWithCursor` (`src/ui/rail.ts:176`): node's `styleText` sees NO_COLOR but not our flag. +- Log: `logs/interactive/s6-no-color-flag.raw` (+ `.meta.json` `esc_sgr_count: 6`). + +### F14 — With `--kind`, "Start over from a preset" ignores the preset you pick (bug, medium) +- `--name fl-lib --kind lib` → Customize → Start over → pick "Desktop app" → review still `fl-lib · library`, crates unchanged. +- Root cause: `src/prompts.ts:158` `resolveAnswers(preset, { ...partial, … })`: the CLI `kind` overrides the picked + preset's kind. Also, with `--kind lib` and no preset, the base is the GUI defaults (MIT, not the lib preset's dual licence). +- Log: `logs/interactive/s7-kind-lib-repick.txt`. + +### F15 — The review omits values the user edits: MSRV, tagline, author/owner, theme base, accent (friction) +- s2: MSRV changed to 1.90, tagline changed, theme changed to Graphite; none appear on the review (only "pinned 1.92.0", + and only while Pinned toolchain is on). Every value that did appear matched the written files (licence, edition, + toolchain in `rust-toolchain.toml` and every `ci.yml` job, release.yml dropped, tray.rs, winit+glow deps, + SQLite/tokio/ureq/tracing, `[[bin]] custy`, git commit). +- Root cause: `reviewLines` sections (`src/prompts.ts:82-89`, title facts `:105`). +- Log: `logs/interactive/s2-customize-gui.txt`; project `projects/interactive/cust-app2`. + +### F16 — The "not empty" error suggests `--force`, which can't be used mid-prompt, and wraps a full absolute path (friction) +- Name `hp-cli` (exists): `└ /home/user/cra-dogfood/projects/interactive/hp-cli is not empty. Pick another directory or pass` / `--force.` +- Root cause: message from `src/engine/write.ts:9`, reused as the prompt validator (`src/prompts.ts:125` via `src/cli.ts`). +- Log: `logs/interactive/s4-name-08.txt`. + +### F17 — Keyboard hint nits (nit) +- `a all` toggles: when everything is selected, `a` clears all (`s8-keys` "after a"). `i` (invert), j/k and h/l work but + aren't advertised. Home/End/PgDn/Tab do nothing (fine). Space on a single select does nothing (fine). +- Root cause: footer text `src/ui/choose.ts:121`; behaviour is @clack/core's `toggleAll`. +- Log: `logs/interactive/s8-keys.txt`. + +### F18 — Flags are asked again inside Customize, contrary to PLAN §4 "Flags are never asked again" (nit / contract) +- `--msrv 1.90 --license Apache-2.0` → Customize → Licence + Rust asks both again (prefilled correctly). `--no-git` → + After creating offers git again; turning it on did run git. Prefill is consistent, so this is mostly a doc/contract mismatch. +- Root cause: `customize()` doesn't consult `given()` (`src/prompts.ts:117`, `:234-262`). +- Logs: `s7-msrv-flag.txt`, `s2-customize-gui.txt`. + +### F19 — Smaller nits +- Choosing "Cancel" on the review exits 130, the same as Ctrl-C (a deliberate choice could be 0). `src/prompts.ts:155`. Log `s3-review-canceloption.txt`. +- The cancel output draws an extra empty rail line (`│`,`│`,`└ Nothing written.`): the prompt's cancel frame and `cancel()` each add one. `src/ui/choose.ts:67` + `src/ui/rail.ts:247`. +- Layout uses the column count read at startup; after a resize to 40 cols, rows hard-wrap (`caps.columns` fixed in `src/ui/tty.ts:166`). Log `s5-resize.txt`. +- At 40 cols the banner tagline is clipped without an ellipsis ("…at the speed of"). Log `s5-narrow-40.txt`. +- Each Customize round reprints a full review box, so the transcript grows long (cosmetic). + +## Verified OK +- Terminal state restored after every prompt-time cancel (Esc and Ctrl-C at every stage): `icanon echo isig` on, cursor visible, no directory created. +- Validation messages are inline (warning colour, under the input), specific, and the prompt recovers as soon as you type. +- `--name X --preset Y` skips both prompts; a positional valid dir supplies the name; `--name BadName` and `--preset bogus` fail before any prompt (exit 2). +- `NO_COLOR=1` output has 0 SGR sequences; single-select stays legible (●/○). +- The escaping of a tagline with `"` and `\` is correct in Cargo.toml (`"Says \"hi\" \\ there"`) and README. diff --git a/docs/dogfood/evidence/4-validation.md b/docs/dogfood/evidence/4-validation.md new file mode 100644 index 0000000..78a0a43 --- /dev/null +++ b/docs/dogfood/evidence/4-validation.md @@ -0,0 +1,198 @@ +# 4 — Re-validation after fixes (create-rust-app @ 58847b6 vs before-run @ db3693d) + +Date 2026-11-21. Branch `claude/jolly-curie-lpi8jt`, HEAD `58847b6` (repo untouched: `git status` clean throughout). +Toolchains 1.99.1 (pin) / 1.98 (MSRV); cargo-deny 0.22.0, actionlint 1.7.12, zizmor 1.32.0 `--offline` (same as before). + +## How it was run + +- Scripts (adapted from the before run, paths only + additions): `/home/user/cra-dogfood/scripts/after/` + - `matrix-lib.sh` (same helpers; `P=projects/matrix-after`, `L=logs/matrix-after`, `CARGO_TARGET_DIR=target-matrix-after`) + - `matrix-all.sh` (whole matrix, sequential, one target dir; adds long-name variants, `example changelog --check` + regen-diff, + strobe changelog with `git diff --exit-code CHANGELOG.md`, full gate set on **every** GUI combo, clippy-win, fmt name-length probe) + - `edge.sh` (before-run edge cases unchanged + additions), `jsoncheck.sh`, `recreate.exp`, `table.mjs` (builds the table from `results.tsv`). +- Logs: `/home/user/cra-dogfood/logs/matrix-after//.log`, raw `results.tsv`, `driver.log`, table `table.md`; + edge `edge/.log` + `edge/summary.tsv`; JSON `jsoncheck/`; recreate `recreate/`; friction `friction/`; baseline `baseline/`; + default-output diff before↔after `outdiff/.diff`. +- Projects: `/home/user/cra-dogfood/projects/matrix-after/` (same combo/dir names as before). `target-matrix` (old, 2.8 GB) deleted first. +- For attribution, the before commit was rebuilt out of tree (`git archive db3693d` → scratchpad, `npm ci && npm run build`) and used + to scaffold every preset with default answers for a before↔after output diff. +- Builds were fast (warm registry/build caches; whole matrix ≈ 10 min). Logs confirm real compiles (e.g. `rustaman/msrv.log` compiles eframe on 1.98 in 52 s). + +## 1. Baseline (`logs/matrix-after/baseline/`) + +| step | exit | +|---|---| +| `npm ci` | 0 | +| `npm run typecheck` | 0 | +| `npm test` | 0 — **164 tests, 164 pass, 0 fail** (`npm_test.log`) | +| `npm run build` | 0 | + +## 2. After table + +Same format as 3a. Exit codes in parentheses; zizmor 13 = highest finding medium, 14 = high. "–" = not run. + +| combo | scaffold | fmt | clippy | clippy-allfeat | clippy-win | check | test | deny | doc | msrv | actionlint | zizmor | extra | +|---|---|---|---|---|---|---|---|---|---|---|---|---|---| +| cli | PASS | PASS | PASS | PASS | PASS | – | PASS | PASS | PASS | PASS | PASS | FAIL(13) | example-changelog-check: PASS, example-changelog-regen: PASS | +| rustaman | PASS | PASS | PASS | PASS | PASS | – | PASS | PASS | PASS | PASS | PASS | FAIL(13) | example-changelog-check: PASS, example-changelog-regen: PASS | +| lib | PASS | PASS | PASS | PASS | – | – | PASS | PASS | PASS | PASS | PASS | FAIL(13) | example-changelog-check: PASS, example-changelog-regen: PASS | +| minimal | PASS | PASS | PASS | PASS | – | – | PASS | N/A(no deny.toml) | PASS | PASS | PASS | PASS | example-changelog: N/A(no example) | +| tui | PASS | PASS | PASS | PASS | – | – | PASS | PASS | PASS | PASS | PASS | FAIL(13) | example-changelog-check: PASS, example-changelog-regen: PASS | +| lib-publish | PASS | – | – | – | – | – | – | – | – | – | – | – | publish-dry-run: PASS | +| cli-subcmd-bin | PASS | PASS | PASS | PASS | – | – | PASS | PASS | PASS | PASS | PASS | FAIL(13) | run-help: PASS | +| cli-tokio-reqwest | PASS | PASS | PASS | PASS | – | – | PASS | PASS | PASS | PASS | PASS | FAIL(13) | | +| cli-ed2021 | PASS | PASS | PASS | PASS | – | – | PASS | PASS | PASS | PASS | PASS | FAIL(13) | | +| cli-tracing | PASS | PASS | PASS | PASS | – | – | PASS | PASS | PASS | PASS | PASS | FAIL(13) | | +| strobe | PASS | PASS | PASS | PASS | PASS | – | PASS | PASS | PASS | PASS | PASS | FAIL(13) | xtask-ci: PASS, xtask-changelog: PASS (CHANGELOG.md unchanged) | +| minimal-lic-MIT | PASS | – | – | – | – | – | – | FAIL(4) | – | – | – | – | inspect: PASS | +| minimal-lic-MIT_CommonsClause | PASS | – | – | – | – | – | – | FAIL(4) | – | – | – | – | inspect: PASS | +| minimal-lic-Apache_2_0 | PASS | – | – | – | – | – | – | FAIL(4) | – | – | – | – | inspect: PASS | +| minimal-lic-MIT_OR_Apache_2_0 | PASS | – | – | – | – | – | – | FAIL(4) | – | – | – | – | inspect: PASS | +| lic1-deny | PASS | – | – | – | – | – | – | PASS | – | – | – | – | inspect: PASS, publish-dry-run: FAIL(101) | +| lic2-deny | PASS | – | – | – | – | – | – | PASS | – | – | – | – | inspect: PASS, publish-dry-run: FAIL(101) | +| lic3-deny | PASS | – | – | – | – | – | – | PASS | – | – | – | – | inspect: PASS, publish-dry-run: FAIL(101) | +| lic4-deny | PASS | – | – | – | – | – | – | PASS | – | – | – | – | inspect: PASS, publish-dry-run: FAIL(101) | +| rustaman-tray-si | PASS | PASS | PASS | PASS | PASS | – | PASS | PASS | PASS | PASS | PASS | FAIL(13) | example-changelog-check: PASS, example-changelog-regen: PASS | +| rustaman-nodemo | PASS | PASS | PASS | PASS | – | – | PASS | PASS | PASS | PASS | PASS | FAIL(13) | | +| rustaman-glow | PASS | PASS | PASS | PASS | PASS | – | PASS | PASS | PASS | PASS | PASS | FAIL(13) | | +| rustaman-graphite | PASS | PASS | PASS | PASS | – | – | PASS | PASS | PASS | PASS | PASS | FAIL(13) | inspect: PASS | +| custom | PASS | PASS | PASS | PASS | – | – | PASS | PASS | PASS | PASS | PASS | FAIL(13) | example-changelog-check: PASS, example-changelog-regen: PASS | +| long-rustaman | PASS | PASS | PASS | – | – | – | PASS | – | PASS | – | – | – | example-changelog-check: PASS, example-changelog-regen: PASS | +| long-strobe | PASS | PASS | PASS | – | – | – | PASS | – | PASS | – | – | – | xtask-changelog: PASS (unchanged), xtask-ci: PASS | +| long-cli | PASS | PASS | PASS | – | – | – | PASS | – | PASS | – | – | – | example-changelog-check: PASS, example-changelog-regen: PASS | +| long-tui | PASS | PASS | PASS | – | – | – | PASS | – | PASS | – | – | – | example-changelog-check: PASS, example-changelog-regen: PASS | + +Notes on cells: +- `long-*` use `--name a-very-long-project-name-used-to-probe-rustfmt-width-limits-abcd` (64 chars, the new maximum), dir `long-`. + long-strobe's app crate becomes `-app` (68 chars); harmless because the workspace sets `publish = false`, but it exceeds the + crates.io cap the name validator cites (observation, not a failure). +- `example-changelog-check` = `cargo run --example changelog -- --check` on the fresh git-initialised scaffold; + `-regen` = run the generator then `git diff --exit-code CHANGELOG.md` (a fresh scaffold must not change). +- `minimal-lic-*` deny FAIL(4) and `lic*-deny` publish-dry-run FAIL(101) are the same **expected** results as before (no deny.toml on minimal; + binaries write `publish = false`). The `minimal-lic-*` crates are still named `my-app` (uppercase dir names), but the scaffold now + prints `note: the folder name "minimal-lic-MIT" can't be a crate name, so the crate is named "my-app"` (`minimal-lic-MIT/scaffold.log`, finding 6). +- `rustaman-graphite` inspect: `#ff9f6e` reaches `src/lib.rs:54`, Graphite base in `src/theme/mod.rs` (`rustaman-graphite/inspect.log`). +- Remaining zizmor FAIL(13) everywhere = `dependabot-cooldown` (medium) only, + `use-trusted-publishing` (info) on lib (`/zizmor.log`). + +### Name-length fmt probe (`logs/matrix-after/fmtlen--/fmt.log`) + +| preset | 2 | 8 | 16 | 24 | 64 (long-*) | +|---|---|---|---|---|---| +| rustaman | PASS | PASS | PASS | PASS | PASS | +| strobe | PASS | PASS | PASS | PASS | PASS | +| cli / tui | PASS | PASS | PASS | PASS | PASS | +| lib / minimal | PASS | PASS | PASS | PASS | – | + +### `--dry-run --json` (`logs/matrix-after/jsoncheck/summary.tsv`, `normalized-summary.txt`) + +All 7 presets: exit 0, single valid JSON doc starting `{`, 0 bytes stderr, nothing written; plan list == real `-y --no-git --no-fetch` +run after normalising the project name (58/68/30/31/30/17/57 files — identical counts to before). + +## 3. Before → after cell diff + +Counting executed cells in the 24 comparable rows (excluding N/A and "–"): **before 156 PASS / 31 FAIL → after 165 PASS / 22 FAIL** +(+1 new `rustaman-graphite inspect` PASS). All new cells (long-name rows, example-changelog cells, upgraded GUI gates): 40 more, all PASS. +Total after: 206 PASS / 22 FAIL, of which 8 FAIL are expected-by-design (4 deny-without-config, 4 publish of binaries). + +| combo | gate | before | after | why | +|---|---|---|---|---| +| rustaman | doc | FAIL(101) | PASS | 5bcdfde (run.rs links) | +| rustaman-tray-si | fmt | FAIL(1) | PASS | b51a54a/ac959a0 (name-width) | +| rustaman-tray-si | doc | FAIL(101) | PASS | 5bcdfde (tray.rs link) | +| rustaman-nodemo | fmt | FAIL(1) | PASS | b51a54a | +| rustaman-nodemo | doc | FAIL(101) | PASS | 5bcdfde | +| rustaman-graphite | fmt | FAIL(1) | PASS | b51a54a | +| rustaman-graphite | doc | FAIL(101) | PASS | 5bcdfde | +| custom | doc | FAIL(101) | PASS | 5bcdfde | +| minimal | zizmor | FAIL(13) | PASS | eff8d91 (persist-credentials) | +| cli, rustaman, tui, cli-subcmd-bin, cli-tokio-reqwest, cli-ed2021, cli-tracing, strobe, rustaman-tray-si, rustaman-nodemo, rustaman-glow, rustaman-graphite, custom | zizmor | FAIL(14) | FAIL(13) | c67252a (no release cache), eff8d91; dependabot-cooldown remains | +| lib | zizmor | FAIL(13) | FAIL(13) | artipacked gone; dependabot-cooldown + trusted-publishing (info) remain | +| rustaman-graphite, custom | clippy-allfeat | – | PASS | gate set upgraded (was `check` only) | +| rustaman-graphite, custom | check | PASS | – | replaced by full gates | +| rustaman-tray-si, rustaman-nodemo, rustaman-glow | (all gates in one pass) | partly via probe | all PASS | full set run directly | + +No cell went PASS → FAIL. + +## 4. Edge cases (`logs/matrix-after/edge/summary.tsv`; same ids as before + additions) + +| case | before | after | +|---|---|---| +| `--name fn/async/type` | exit 0, code doesn't compile | exit 2 "is a Rust keyword, so it can't name a crate" ✔ (also match, mod, use, self, crate, super, loop, dyn; `Self` rejected by the lowercase rule) | +| `--name` 300 chars (minimal) | exit 0, cargo "File name too long" | exit 2 "Use at most 64 characters (the crates.io limit); this one has 300" ✔ | +| `--name` 260 chars (rustaman) | exit 1 mid-write, partial project | exit 2 at validation, nothing written ✔ (`name-long-gui.log`) | +| `--name` 64 / 65 chars | – | 64 accepted / 65 rejected ✔ | +| positional `MyDir`, `sub2/Weird_Dir`, 70×`b` | crate silently `my-app` | crate still `my-app`, but stderr: `note: the folder name "MyDir" can't be a crate name, so the crate is named "my-app" (set it with --name).` ✔ | +| `--json` without `--dry-run` | writes files, skips post-steps, JSON `post.git:true` | **unchanged behaviour**; `--help` now says "Still writes the files unless --dry-run, but skips fetch, git, cargo check and open"; JSON still reports `"post":{"git":true,"fetch":true,…}` with no .git / Cargo.lock (`json-nodry-git.log`) | +| `--msrv 1.100 --toolchain 1.99.1` | exit 0, cargo fails | exit 2 "msrv 1.100 is newer than toolchain 1.99.1 …", nothing written ✔; `--msrv 1.80 --edition 2024` also rejected; `--msrv 1.99 --toolchain 1.99.1` accepted | +| ignored flags (`lib --with tray`, `tui --with subcommands`, `minimal --with subcommands`, `lib --bin foo`, `cli --gui winit-glow`) | silent | `note: … is ignored: ` on stderr ✔; with `--json` stdout stays a pure JSON doc ✔ and `guiStack` is `""` for cli ✔ (`notice-*.log`, `fix-n3b/n5b.log`). `--quiet` also suppresses the notes (`fix-n7b.log`, stdout+stderr empty) | +| `--force` over colliding file | silent overwrite | stderr `note: --force overwrote 1 existing file: README.md` ✔; JSON mode stdout still valid ✔ | +| failed write | partial project left | `error: Writing src/main.rs failed: EISDIR … Removed the 14 files this run created …; files that were there before are kept.` — verified only `keep.txt` and the blocker remain (`write-fail-cleanup.log`) ✔ | +| dir with only `git init` (`.` and named) | nothing committed | `git: first commit on master in the existing repository`, one commit ✔ (`dir-dot-gitonly.log`, `dir-gitonly-named.log`); inside a parent repo: "git skipped: already inside a git repository", summary truthful ✔ | +| error prefix in non-TTY | `✖` for arg errors, `error:` later | unchanged (`nontty-error-prefix.log` ✖, `nontty-error-prefix2.log` error:; msrv cross-check also prints `error:`) | +| NO_COLOR / --no-color / help / error (pty) | 0 ESC | 0 ESC ✔ (control run 9 ESC) | +| `--quiet` | silent stdout | unchanged ✔ | +| non-TTY stdin, no `-y` | defaults | unchanged ✔ | +| `nocolor-dryrun` (interactive in a pty with stdin at EOF) | recorded 1 ESC | 1 ESC, but the process **hung** until killed; the before build (`db3693d`, rebuilt out of tree) hangs identically under `timeout 40 script …` (rc 124 both), so not a regression — environment/pty artefact | +| everything else in the before table (name rules, --set validation, unknown flags, bins, --no-git, --no-fetch, file target, two positionals, …) | ✔ | identical exit codes and messages (joined summary) | +| `scaffold-check minimal --set tagline=a=b --out --gate fmt` with `CARGO_TARGET_DIR` set | `description = "a"` | `description = "a=b"`, exit 0; `/.scratch` untouched (mtimes 2026-11-20) ✔ (`scaffold-check/set-eq.log`) | + +### Recreate command (`logs/matrix-after/recreate/`) + +Interactive run via expect (`scripts/after/recreate.exp`) with `--preset rustaman --base graphite --accent '#ff9f6e' --author 'Jane Q' --github janeq --with tray --no-fetch` +printed: `npx github:freeknet/create-rust-app rc2 --preset rustaman --with tray --base graphite --author "Jane Q" --github janeq --accent "#ff9f6e" --no-fetch -y`. +Run with local dist: `diff -r -x .git -x target -x Cargo.lock` → **identical (0 lines)** (`diff-rc2.txt`; before: 14 files differed). +`-y` runs still don't print the command (`rc2-local.log`). + +## 5. Per-finding status (1–19) + +| # | status | evidence | +|---|---|---| +| 1 fmt fails for names ≥14 chars (GUI) | **fixed** | fmtlen all PASS; long-* (64) fmt PASS; tray-si/nodemo/graphite fmt PASS | +| 2 eframe rustdoc `-D warnings` | **fixed** | doc PASS on rustaman, custom, nodemo, graphite, tray-si, long-rustaman | +| 3 tray broken intra-doc link | **fixed** | `rustaman-tray-si/doc.log` PASS | +| 4 keywords accepted | **fixed** | `edge/name-kw-*.log` exit 2 | +| 5 no length limit / partial write | **fixed** | 64 max enforced; failed write cleans up (`write-fail-cleanup.log`) | +| 6 positional dir → silent `my-app` | **fixed** (now a stderr note; crate still `my-app`) | `edge/name-positional-*.log` | +| 7 `--json` w/o `--dry-run` skips post-steps | **partly** — documented in `--help`, but JSON still claims `post.git/fetch: true` | `edge/json-nodry-git.log` | +| 8 recreate drops accent/author/github | **fixed** | `recreate/diff-rc2.txt` empty | +| 9 msrv > toolchain accepted | **fixed** | `edge/msrv-gt-toolchain.log`, exit 2 | +| 10 zizmor | **partly** — cache-poisoning (high) and artipacked gone; `dependabot-cooldown` (medium, `dependabot.yml:16,38`, template not touched) and lib `use-trusted-publishing` (info) remain → exit 13 on 14 combos | `/zizmor.log` | +| 11 changelog generators vs shipped file | **fixed** (shipped file == generator output for example and xtask; `--check` passes; regen leaves file unchanged on 11 combos). Residual: released entries still formatted differently (example links hashes, xtask prints bare hash) | `*/example-changelog-*.log`, `strobe/xtask-changelog.log` | +| 12 `--force` silent overwrite | **fixed** (lists overwritten files) | `edge/force-notice.log` | +| 13 inapplicable flags silently dropped | **fixed** (notes; guiStack blanked) | `edge/notice-*.log` | +| 14 git-only dir: no commit | **fixed** | `edge/dir-dot-gitonly.log` | +| 15 inconsistent error prefix | **unchanged** | `edge/nontty-error-prefix{,2}.log` | +| 16 author identity defaults | **unchanged** (`src/presets.ts` still `Lawrence Norton`/`lnorton89`) | `edge/json-nodry.log` answers | +| 17 scaffold-check target dir / `--set` | **fixed** (both) | `scaffold-check/set-eq.log` | +| 18 `-y` finish screen lacks recreate command | **unchanged** (info) | `recreate/rc2-local.log` | +| 19 Windows code not compiled on Linux | **unchanged** (info); clippy-win PASS on rustaman, tray-si, strobe, glow, cli | `/clippy-win.log` | + +## 6. Friction re-check on a real project (`logs/matrix-after/friction/`) + +`create-rust-app real-logscan --name logscan --preset cli --with subcommands -y` (with fetch + git; one commit `feat: scaffold logscan with create-rust-app`). +On the untouched scaffold: + +| claim | result | +|---|---| +| `cargo run --example changelog -- --check` passes | **confirmed** — "CHANGELOG.md matches the git history.", exit 0 (`changelog-check.log`) | +| zizmor findings | default persona exit 13: 2× `dependabot-cooldown` (medium) only, 7 suppressed (`zizmor.log`). `--persona=pedantic`: + 1 `template-injection` (help), 2 `undocumented-permissions` (help), 4 `superfluous-actions` (info) (`zizmor-pedantic.log`) | +| `RUSTDOCFLAGS=-D warnings cargo doc` passes | **confirmed**, exit 0 (`doc.log`) | +| CLAUDE.md / CONTRIBUTING / README agree with the generator | **confirmed**: both say generated, never hand-edit, `--check` compares released sections only (matches `examples/changelog.rs:50`), CI does not run it (no workflow mentions changelog), `--release vX` flow and unparsed subjects → catch-all (`OTHER = "Other"`). README only links the file. Shipped CHANGELOG.md is byte-identical to a regeneration | +| header-banner docs list the dirs the check walks | **confirmed for CLAUDE.md:88 and CONTRIBUTING.md:79** (`src/`, `tests/`, `examples/`, `benches/`, `build.rs` = the loop at `src/header_check.rs:214` + build.rs at :230). Residual (pre-existing, unchanged since db3693d): `src/header_check.rs`'s own banner (line 6) and `//!` doc (line 15) still say "src/, tests/ and examples/" | + +Header test on a copy (`projects/matrix-after/real-logscan-hdr`): added `src/scan.rs` with a correct banner (`Module: scan`) → `cargo test` exit 0 +(`header-good.log`); added `src/parse.rs` declaring `Module: scan` → exit 101 with +`1 file header problem(s) across 11 file(s): src/parse.rs: declares \`Module: scan\` but sits at \`parse\`` (`header-bad.log`). Clear. + +## 7. Regressions + +**None found.** +- No matrix cell went PASS → FAIL; no edge case got worse. +- Default-answer output diff before↔after for all 6 presets (`logs/matrix-after/outdiff/.diff`; 4–18 files per preset) was read in full: + every change maps to a fix commit — workflows (eff8d91, c67252a), name-width rewrites `use as app;`, `BIN`/`NAME` consts, + `env!("CARGO_PKG_NAME")`, split `REPO` string (b51a54a, ac959a0, 92d5f6f), rustdoc links (5bcdfde), docs naming only present features (9209843, c11038a), + CHANGELOG/PREAMBLE and hash-less Unreleased (6d57531), TUI ratatui 0.30 / crossterm 0.29 (80e32b1). Values are equivalent (e.g. config dir still ``). + +Minor new observation (not a gate failure; hypothesis-grade impact): `templates/guards/files/src/unsafe_check.rs` (9209843) now tells eframe projects +"unsafe code must live under src/win/" while the check itself still also accepts `src/gui/run/` — message/doc and logic disagree for non-winit-glow projects. +Repro: read `projects/matrix-after/rustaman/src/unsafe_check.rs` (const `ALLOWED` vs the `starts_with` test). `git log --oneline db3693d..58847b6 -- templates/guards/files/src/unsafe_check.rs` → `9209843`. diff --git a/docs/dogfood/evidence/ENV.md b/docs/dogfood/evidence/ENV.md new file mode 100644 index 0000000..415c890 --- /dev/null +++ b/docs/dogfood/evidence/ENV.md @@ -0,0 +1,43 @@ +# Dogfood environment (phase 0, 2026-11-20) + +OS: Ubuntu 24.04.5 LTS (container), Linux 6.18. Logs: `logs/phase0/`. + +## Versions +| Tool | Version | +|---|---| +| node | v22.23.5 | +| npm | 10.9.9 | +| rustup | 1.28.2 at start, self-updated to 1.29.3 during `toolchain install` | +| cargo / rustc (default stable) | 1.97.0 (2026-07-07) | +| go | /usr/local/go/bin/go (used for actionlint) | + +## Rust toolchains +- `stable` = 1.97.0 (default; older than the 1.98 MSRV, so plain `cargo +stable` on generated code may fail rust-version) +- `1.99.1` — installed (rustc 1.99.1 58cf8f9c3 2026-10-13), profile minimal + rustfmt + clippy. Log: rustup-1.99.1.log +- `1.98` — installed, resolves to 1.98.1 (48a229cea 2026-09-01), + rustfmt + clippy. Log: rustup-1.98.log +- Generated projects' `rust-toolchain.toml` auto-selects 1.99.1 (verified in `.scratch/minimal`). +- No Windows MSVC target installed (rust-toolchain.toml lists `x86_64-pc-windows-msvc`; not added by minimal install). + +## Tools +| Tool | Status | +|---|---| +| cargo-deny | 0.22.0 installed (`cargo install --locked`) | +| cargo-msrv | 0.19.6 installed | +| zizmor | 1.32.0 installed | +| actionlint | 1.7.12 installed via `go install` to /usr/local/bin | +| xvfb-run | present (/usr/bin/xvfb-run) | +| script | present (util-linux) | +| expect | 5.45.4 installed via apt | + +## GUI system libs +Before: runtime .so files present (libxkbcommon, libwayland-client, libX11, libGL, libvulkan) but dev/pkg-config +files missing for xkbcommon, wayland, xcursor, xrandr, xi, gtk3, appindicator, gl, egl. +Installed via apt (log apt-install.log): libxkbcommon-dev libwayland-dev libx11-dev libxcursor-dev libxrandr-dev +libxi-dev libgtk-3-dev libayatana-appindicator3-dev libgl1-mesa-dev libegl1-mesa-dev libxdo-dev expect. +After (env-probe-after.txt): all resolve via pkg-config (xkbcommon 1.6.0, wayland 1.22.0, gtk3 3.24.41, +ayatana-appindicator3 0.5.90, gl 1.2, egl 1.5). Note: repo CI installs libxinerama-dev too (not installed here). + +## Reference projects +`../rustaman` and `../strobe` (/home/user/rustaman, /home/user/strobe): NOT present. + +## Nothing failed to install. diff --git a/docs/dogfood/evidence/friction-deskpulse-monitor.md b/docs/dogfood/evidence/friction-deskpulse-monitor.md new file mode 100644 index 0000000..5ed0b36 --- /dev/null +++ b/docs/dogfood/evidence/friction-deskpulse-monitor.md @@ -0,0 +1,189 @@ +# Friction log: deskpulse-monitor (rustaman preset, real GUI feature build) + +Scaffold command (log: `logs/real-gui/scaffold.log`, 1 s, 58 files, git commit, `cargo fetch`): + +``` +create-rust-app deskpulse-monitor --preset rustaman --name deskpulse-monitor \ + --author "Dogfood Tester" --github dogfood-tester \ + --set tagline="Live system load, memory and uptime at a glance" -y +``` + +Costs are rough wall-clock for me plus attempt counts. Repo paths are relative to +`/home/user/create-rust-app`. + +## Timeline (appended as I go) + +### 0. Baseline: untouched scaffold + +- **`cargo fmt --check` FAILS on the untouched scaffold (CONFIRMED).** Log: + `logs/real-gui/baseline-fmt.log`. Two lines exceed 100 columns once the 17-char name is + substituted; the generator substitutes tokens and never runs rustfmt (no `rustfmt`/`cargo fmt` + anywhere in `src/**`). + - `templates/gui/files/src/config.rs:178` — `format!("@@name@@-config-{}", ...)` + - `templates/gui/files/examples/screenshot.rs:38` — `@@appCrateSnake@@::config::Config::default()` + Any name over ~12 chars breaks it. Fix in the generator: run `cargo fmt` as a post-step, or + pre-break these lines so they fit with the longest plausible name. Cost: 2 min (a user just runs + `cargo fmt`, but CI would be red on the very first push). +- **`RUSTDOCFLAGS="-D warnings" cargo doc --no-deps` FAILS on the untouched scaffold (CONFIRMED).** + Log: `logs/real-gui/baseline-doc.log`. Two rustdoc lints, both in + `templates/gui/files/src/gui/run.rs`: + - `:20` `[`backends`]` links to a private fn from public module docs (`private_intra_doc_links`). + - `:13` `[`App`](super::app::App)` is a `redundant_explicit_links` (App is imported). + CI (`templates/github/files/_github/workflows/ci.yml`) never runs `cargo doc`, which is why this + went unnoticed. Cost: 3 min. +- **zizmor fails on the untouched scaffold**: exit 14, 1 high (`cache-poisoning`, rust-cache in the + tag-triggered release build, generated `release.yml:116` = template `release.yml:120`) + 7 medium `artipacked` (every `actions/checkout` + lacks `persist-credentials: false`: ci.yml:39,57,70,105; release.yml:51,107,202). Log: + `logs/real-gui/baseline-zizmor.log` (run `--offline`). Same finding as other presets. +- Green on the untouched scaffold: clippy -D warnings, `cargo test` (87 lib + 3 integration tests), + `cargo deny check` (but 9 duplicate-crate + 3 license-not-encountered warnings of noise), + `cargo +1.98 build`, actionlint. First GUI build ~4 min on 4 cores. +- Versions: eframe/egui/egui_kittest 0.37.0 = current on crates.io (2026-10-15); windows-sys 0.61 + current (0.61.2); toml 1.2, dirs 7 current. Nothing outdated. +- Minimal user fix applied as commit `e718a83` (`cargo fmt`, and the two doc links rewritten). + +### 1. Reading the generated docs (~10 min) + +AGENTS.md -> CLAUDE.md -> docs/ARCHITECTURE.md is a good chain. ARCHITECTURE.md's **"Adding a page"** +section is accurate and was all I needed. Inaccurate or misleading statements: + +- CLAUDE.md and README.md: *"All of these are clean on `main` and enforced by CI"* — false on a + fresh scaffold (`cargo fmt --check` fails, see 0). `templates/base/files/CLAUDE.md:84`, + `templates/base/files/README.md:215`. +- CLAUDE.md/AGENTS.md: *"Required unsafe code belongs only under `src/win/`"*, but + `src/unsafe_check.rs` docs and error say *"unsafe code must live under src/win/ or src/gui/run/"*; + `src/gui/run/` does not exist in this preset (it is `src/gui/run.rs`, so even the allowance would + not match it). `templates/guards/files/src/unsafe_check.rs:12,87,89`. +- README: *"A theme is thirteen colours"*; ARCHITECTURE.md, `themes.toml` and `theme/mod.rs` say + **eleven**. `templates/base/files/README.md:137` vs `templates/gui/files/docs/ARCHITECTURE.md:65`. +- `gui::app` docs: *"a shortcut, a button, the tray menu and the command palette cannot drift apart"* + and `PAGE_KEYS` doc *"(and its command palette entry)"* — the rustaman preset has neither tray nor + command palette. `templates/gui/files/src/gui/app/mod.rs:22`, `templates/gui/files/src/gui/ui/mod.rs:232`. +- Nothing documents Linux runtime requirements (see 6). + +### 2. Adding new modules: header banner + `header_check` (~2 min, 1 attempt; helped) + +Wrote 5 new files (`monitor/mod.rs`, `monitor/job.rs`, `gui/app/monitor.rs`, `gui/ui/monitor.rs`, +`win/system.rs`) by copying a neighbour's banner as CLAUDE.md says; all passed first time. A +deliberate mistake (`Module: job`, empty `Dependencies:`) gives exact, actionable messages +(`logs/real-gui/header-check-experiment.log`): *"declares `Module: job` but sits at `monitor::job`"*, +*"`Dependencies:` is empty"*. Verdict: helps; zero real friction. Writing `Dependencies:` is a +small but useful prompt. + +### 3. Adding a page (~10 min; 2 existing files must change, docs accurate) + +Touched for registration: `src/gui/app/mod.rs` (variant, `ALL` array length 3->4, `label`, `key`, +`glyph`, plus 3 new `Action` variants and their `apply` arms) and `src/gui/ui/mod.rs` (glyph const, +`pub mod monitor;`, one `match` arm, `SHORTCUTS` "Ctrl+1…3" -> "Ctrl+1…4"). The exhaustive matches +mean the compiler walks you through it; `every_page_has_a_numbered_shortcut` catches the shortcut +text, as documented. Sidebar, Ctrl+N, headless draw test and the screenshot example picked the page +up automatically (screenshot example rendered `monitor.png` with no change). Good design. +- Nit: the `SHORTCUTS` "Ctrl+1…N" string is hand-maintained; could be derived from `Page::ALL.len()`. +- No command palette in the rustaman preset (`commandPalette` off), so nothing to register there. +- Demo content: left the Overview cards (`CARDS` in `gui/app/mod.rs`) in place; they are clearly + marked "Replace these with your own views" and isolated, so easy to delete later. +- egui 0.37 deprecates `egui::Id::new` (my first draft used it, `-D warnings` made it an error); + the scaffold already uses `Id::unique`, so copying neighbours avoids it. 1 extra attempt. + +### 4. Persisted settings (~8 min; easy) + +Added `monitor_interval_secs`, `monitor_show_swap`, `monitor_show_history` to `Config`. The +"every field `Option`, parsed independently" design meant: no migration, no version number, old +config files load unchanged (tested), an out-of-range interval is dropped like any bad value +(tested). Four edits in `config.rs` (struct, `parse`, round-trip test) plus `remember_choices` in +the app. The only repetition is that every field is listed twice (struct + `parse`); a forgotten +`parse` line silently never loads — the round-trip test catches it if you extend it. +- Caveat (scaffold design, not fixed): config is only saved in `App::on_exit`; a crash or SIGTERM + loses every change of the session. + +### 5. The `unsafe` boundary with a real platform call (~25 min; clear error, awkward boundary) + +- Wrong place first: `GetTickCount64` inside `src/monitor/mod.rs` (`#[cfg(windows)]`). Caught on + Linux even though the code is cfg'd out (the check is textual — good): + `src/monitor/mod.rs:137: unsafe code must live under src/win/ or src/gui/run/` + (`logs/real-gui/unsafe-wrong-place.log`). Clear and immediate. +- Right place: `src/win/system.rs` with two private leaves (`GlobalMemoryStatusEx`, + `GetTickCount64`), safe public `memory()`/`uptime()`, plus feature + `Win32_System_SystemInformation` in Cargo.toml (generator list: `templates/gui/deps.js:29`). + Passed unsafe_check first time; type-checked with + `cargo clippy --target x86_64-pc-windows-msvc` (`logs/real-gui/clippy-windows.log`, exit 0). +- **Top friction: the boundary is Windows-only.** `src/win/` is `#[cfg(windows)] pub mod win;`, so + there is no sanctioned home for unix FFI. I tried `libc::getloadavg` for a macOS/BSD fallback + (`logs/real-gui/unsafe-wrong-place-unix.log`): rejected outside `src/win/`, and inside `src/win/` + it would never compile on unix. The only ways forward are editing `unsafe_check.rs`'s allow-list + or dropping the feature. I dropped it (non-Linux, non-Windows platforms show "not available") + rather than weaken the check. Suggest a platform-neutral boundary (`src/sys/{win,unix}/`) or + documenting how to extend the allow-list. `templates/guards/files/src/unsafe_check.rs:87`. +- Nit: `enclosing_function` only recognises `fn`/`pub fn`/`pub(crate) fn`/`unsafe fn` prefixes, so + a leaf declared `pub(super) fn` or `const fn` is attributed to the previous function and can + trigger a false "leaf wrapper contains 2 unsafe operations". `unsafe_check.rs:52-60`. + +### 6. Running under xvfb (~15 min, 3 attempts; environment, but undocumented) + +- Attempt 1: panic `Library libxkbcommon-x11.so could not be loaded` (`logs/real-gui/xvfb-run.log`). + winit dlopens it; the container had only `libxkbcommon-dev`. +- Installed `libxkbcommon-x11-0` + `mesa-vulkan-drivers` (lavapipe). Note wgpu on Linux uses + `Backends::PRIMARY` (Vulkan), so `LIBGL_ALWAYS_SOFTWARE=1` alone does nothing; a Vulkan ICD is + needed. Then the app ran 8 s cleanly (`xvfb-run2.log`), screenshot of the live window + `logs/real-gui/xvfb-monitor.png`, thread list shows `monitor-sampler` (`xvfb-threads.log`). + The app opened on the Monitor page at 1 s because both were in the config file: persistence works. +- `cargo run --example screenshot` worked once lavapipe was present and rendered the new page + (`logs/real-gui/screenshot-example-monitor.png`). Useful. +- README/CONTRIBUTING never mention Linux runtime needs (xkbcommon-x11, a Vulkan driver). + `templates/base/files/README.md`. + +### 7. Adding a dependency + cargo-deny (~3 min; no block) + +`libc` (MIT OR Apache-2.0) passes `cargo deny check` (`logs/real-gui/deny-with-libc.log`); later +removed with the unix FFI (see 5). The only new crate surface kept is a windows-sys feature. Deny +output is noisy: 9 duplicate-crate warnings and 3 `license-not-encountered` on every run. + +### 8. Lint strictness on GUI code (~5 min; mild) + +`usize as f32`, `u64 as f64`, `f64 as f32`, float arithmetic and slicing all passed: the lint +table enables no pedantic cast lints, so no `#[expect]` was needed anywhere. Indexing I avoided by +habit (`.get()`), matching the scaffold. One borrow-check error (draining while borrowing +`self.sampler`), not lint-related. Verdict: strict where it matters (`unwrap`, wildcard arms, +`allow`), not noisy for drawing code. + +### 9. CI / release review (step 6, ~15 min) and the zizmor fix (~5 min) + +- ci.yml: works for this project. Linux job needs no `apt-get` because `wayland-sys` is built with + `dlopen` and x11/xkbcommon are dlopened; tests that need `/proc` run on ubuntu; Windows job + links/tests the `src/win/system.rs` path; Linux job cross-clippies Windows. Never runs + `cargo doc`, so the rustdoc failure in 0 is invisible to CI. +- release.yml: tag `v*` -> draft -> Windows-only build -> zip + CycloneDX SBOM + sha256 -> attest + -> undraft. Paths (`target/x86_64-pc-windows-msvc/release/deskpulse-monitor.exe`), the tag/version + check, artifact names (`release-assets-`, `pattern` + `merge-multiple`), and permissions + (`contents: write` only on draft/publish, `id-token`+`attestations` only on publish) are right. + winresource needs `rc.exe`, present on windows-latest. cargo-cyclonedx 0.5.9 exists (0.5.10 is + newest). Would work for a public repo. Caveats: + - **No Linux artifact**, though this app's main data source is Linux `/proc`. The comment says + "adding a target later is an entry rather than a rewrite", but the Package step hardcodes + `.exe` and `7z` (`templates/github/files/_github/workflows/release.yml:143,145,160`), so a + Linux entry also needs Package-step changes. + - Artifact attestations fail on a **private** repo without GitHub Enterprise Cloud. +- zizmor fix as a user: `persist-credentials: false` on all 7 checkouts and removed rust-cache from + the release build (commit `976ad96`). actionlint + zizmor then clean. + +## Deleted or rewritten from the scaffold +- Nothing deleted. Rewrote the README's placeholder intro, two doc-links in `gui/run.rs`, the + workflow checkouts / release cache. Updated ARCHITECTURE.md module map and CHANGELOG (as CLAUDE.md + requires). + +## What helped +- Action/apply pattern + exhaustive matches made the page, settings and toggles a guided edit. +- Forgiving per-field config: new settings with zero migration work. +- Header and unsafe checks give file:line messages that say exactly what to fix. +- Headless page test + screenshot example covered the new page for free. +- `cargo clippy --target x86_64-pc-windows-msvc` documented in CLAUDE.md let me verify Windows FFI + from Linux. + +## Missing +- A home for non-Windows FFI; a "background job" pattern (I wrote `monitor::job` from scratch — + the scaffold has no worker/channel/repaint example); Linux runtime deps in README; `cargo doc` in + CI; a post-generate `cargo fmt`. + +## Final gates (logs `logs/real-gui/final-*.log`, summary `final-summary.txt`) +fmt, clippy -D warnings (+ Windows target), test (113+3), deny, doc -D warnings, `+1.98 build`, +actionlint, zizmor: all exit 0. diff --git a/docs/dogfood/evidence/friction-humandur.md b/docs/dogfood/evidence/friction-humandur.md new file mode 100644 index 0000000..08459d4 --- /dev/null +++ b/docs/dogfood/evidence/friction-humandur.md @@ -0,0 +1,226 @@ +# Friction log: `humandur` (real library on the `lib` preset) + +Started 2026-11-20 19:27 UTC. Kept as I went; time/attempt costs are rough wall-clock. +Logs: `/home/user/cra-dogfood/logs/real-lib/`. Project: `/home/user/cra-dogfood/projects/real/humandur`. + +## 0. Scaffold (0.6 s, 1 attempt) + +Command (also in `logs/real-lib/scaffold.log`): + +``` +create-rust-app humandur --preset lib --name humandur --author "Dogfood Tester" \ + --github dogfood-tester --license "MIT OR Apache-2.0" \ + --set tagline="Parse and format human-readable durations" --with thiserror --no-color -y +``` + +Baseline gates on the untouched scaffold (`logs/real-lib/baseline/`): fmt, clippy, test, deny, doc +(-D warnings), `cargo +1.98 test`, `cargo package --list` all exit 0. Good starting point. + +First impressions while reading the scaffold: + +- **F0.1 lib preset ships unused, non-optional runtime deps** (~5 min to notice and remove). `[dependencies]` + has `log`, `serde` (derive), `toml` that the library code never uses; every downstream user would + compile serde_derive + toml for nothing. For a library, serde should be an *optional feature*, and + `toml` has no business being a lib dependency at all. The summary line even says + `crates anyhow / log / serde + toml / thiserror` although I only passed `--with thiserror`. + Cause: `src/presets.ts:20` (DEFAULTS `serde: true, logging: 'log'`) is not overridden by the lib preset at + `src/presets.ts:53`, and `src/gen/deps.ts:30` always pairs serde with `toml` (and never makes it optional), + `src/gen/deps.ts:27` adds `log` unconditionally. +- **F0.2 `keywords = []`, `categories = []`** emitted empty in Cargo.toml. Fine as a TODO, but nothing + (doc, comment, check) tells you to fill them before publishing; crates.io search/categorisation suffers. +- **F0.3 Tagline used as a sentence without a full stop**: CLAUDE.md "Humandur is a Rust library crate. + Parse and format human-readable durations" (no period), CONTRIBUTING "Thanks for considering a + contribution to Humandur: Parse and format human-readable durations" (no period), lib.rs `//! Humandur: Parse ...`. +- **F0.4 `examples/changelog.rs` (724 lines) in a library's `examples/`** - a repo tool, not an example of the + library's API. It is shipped in the crate package and shows up as a docs.rs/`cargo run --example` example. +- **F0.5 Changelog policy contradiction.** CLAUDE.md/CONTRIBUTING: "Every user-visible change adds a line under + `## [Unreleased]` in the same commit" (hand-maintained). `examples/changelog.rs` docs: "The changelog is + derived, not authored ... Released sections are rewritten on every run. Prose added to one is lost". + Also changelog.rs says "the GitHub release body, which `.github/workflows/release.yml` owns" - this lib + project has no release.yml, only publish.yml. +- **F0.6 CONTRIBUTING's Windows linker paragraph** ("CI and the release build use `link.exe`, ... a change to + what ships") is binary-app advice; a library ships source. +- **F0.7 `[profile.release]` with `panic = "abort"`, fat LTO, `strip` in a library manifest** (and CLAUDE.md's + "Things that are deliberate: `panic = "abort"` ... Smaller, faster binaries"). Profiles in a library's + manifest are ignored by every dependent; for a lib this is noise that reads like policy. + `src/gen/cargo.ts:41` (profiles), `templates/base/files/CLAUDE.md:146,248`. +- **F0.8 `rust-toolchain.toml` adds `targets = ["x86_64-pc-windows-msvc"]`** for a pure library: every + contributor's rustup downloads a Windows std they never use. `templates/base/files/rust-toolchain.toml:11`. + +## 1. Writing the crate (~20 min, the cheap part) + +Deleted `src/version.rs`; rewrote `src/lib.rs`, `src/error.rs`, `examples/basic.rs`, `tests/api.rs`; added +`src/{unit,parse,format,human,serde_support}.rs`, `tests/roundtrip.rs`. 19 files changed in one commit +(`686d1d6`), staged by path as CLAUDE.md asks. + +### Header banner rule / `header_check` (helped; 0 failed attempts, ~2 min) + +- Wrote 7 new files with banners copied from the CLAUDE.md example; `header_check` passed first time. +- Probed the failure path on purpose (`benches/probe.rs` with `Module: probe`, `examples/noheader.rs` + without banner): messages are precise and list all files at once: + `benches/probe.rs: declares `Module: probe` but sits at `probe (benchmark)``. Good. +- Coverage: walks `src/`, `tests/`, `examples/`, `benches/` and `build.rs`. CLAUDE.md + (`templates/base/files/CLAUDE.md:172`) says only `src/`, `tests/` and `examples/`, and documents the + `(integration test)` suffix but not `(example)` / `(benchmark)` - you learn those from the error. +- "does not open with the header rule" does not print the rule or point at CLAUDE.md; a one-line hint + ("copy the banner from src/lib.rs") would make it self-serve. `templates/guards/files/src/header_check.rs:156`. +- Note: the check runs only under `cargo test --lib`; `cargo test --test api` alone skips it (fine). + +### Lint strictness (low friction; 1 failed attempt, ~3 min) + +- The table is *not* pedantic: no `arithmetic_side_effects`, `indexing_slicing`, `cast_*`, + `missing_errors_doc`, `must_use_candidate`. Exact parsing with `u128` arithmetic, `%`, `/`, `as`-free + conversions produced **zero** lint hits in `src/`. (I used checked ops / `try_from` by choice.) +- The one hit: `clippy::wildcard_enum_match_arm` in `tests/api.rs` on a downstream-style match over my own + `#[non_exhaustive] ErrorKind`, where a `_` arm is *mandatory* from outside the crate. Clippy's suggestion + (`ErrorKind::A | ErrorKind::B | ... | _`) is acceptable and arguably the point, so no `#[expect]` was needed. + But the scaffold's own `src/error.rs` doc ("every downstream `match` already needs a wildcard arm") + doesn't mention that house-style consumers must also enumerate every variant. The note + "requested on the command line with `-D clippy::wildcard-enum-match-arm`" is misleading (it is in + `[lints]`; that's Cargo/clippy wording, not the scaffold's). +- `missing_docs` is `deny` but only covers public items; it pushed nothing unreasonable. +- CLAUDE.md says "no `unwrap` ... not even in tests". True for `#[test]` (clippy `--all-targets`), but + **doctests are never clippy-linted**, so an `unwrap()` in a doc example would pass every gate. Worth one + sentence. `templates/base/files/CLAUDE.md:~140`. +- `#[expect(..., reason)]` path: never needed, so untested here. + +### Dependencies and features (~5 min, 1 attempt) + +- Removed `log`, `toml` and non-optional `serde` (F0.1); added `serde` as `optional = true, + default-features = false, features = ["std"]` behind `serde = ["dep:serde"]`. +- `proptest = { version = "1.12", default-features = false, features = ["std"] }` (latest, MSRV 1.88) and + `serde_json` as dev-deps. **cargo-deny passed first time** - proptest's tree (rand 0.10, chacha20, + regex-syntax, unarray, bit-set...) is all on the allow-list. No change to deny.toml needed. Chose proptest + (not a hand-rolled generator) because nothing blocked it. +- Every `cargo deny check` prints **13 `license-not-encountered` warnings** (MPL-2.0, OFL-1.1, Ubuntu-font-1.0, + Zlib, ... ). The allow-list is the GUI one (fonts!) applied to a lib; for a library, allowing MPL-2.0 is also + a policy choice a user may not want silently. `src/gen/deny.ts:6-7`. +- Running `cargo deny check --all-features` locally fails (`unexpected argument`): the flag goes *before* the + subcommand (`cargo deny --all-features check`); `deny.toml` already sets `[graph] all-features = true`, so CI's + `arguments: --all-features` is redundant but harmless. +- Versions pinned by the scaffold are current as of today (thiserror 2 -> 2.0.21, serde 1 -> 1.0.229, + toml 1.2 -> 1.2.1, anyhow 1 -> 1.0.104). Major-only specs (`"1"`, `"2"`) mean the real minimum is untested + (no `-Z minimal-versions` job); I tightened mine to the versions I actually tested. + +## 2. Gates (all green at the end; logs in `logs/real-lib/`) + +| Gate | Result | +|---|---| +| `cargo fmt --check` | pass after one `cargo fmt` (2 diffs in my code) | +| clippy `--all-features` / `--no-default-features` (+ on 1.98) | pass | +| `cargo test` default / `--all-features` / `--no-default-features` (header_check, toolchain_pin, 18 doctests, 6 proptests) | pass | +| `cargo deny check` (+ `--all-features`) | pass (13 noise warnings) | +| `RUSTDOCFLAGS=-D warnings cargo doc --no-deps` both configs | pass | +| `cargo +1.98 build` / `test` both configs; `cargo msrv verify` | pass | +| `cargo publish --dry-run --allow-dirty`; tests inside the extracted `.crate` | pass | +| actionlint | pass (also on the untouched scaffold) | +| zizmor (default persona) | scaffold: **5 medium `artipacked` + 1 info `use-trusted-publishing`, exit 13**; after my fixes: 0 findings | + +Not run: a real docs.rs build (`--cfg docsrs` needs nightly; none installed). + +## 3. Packaging (`cargo package --list`) (~5 min) + +Untouched scaffold ships **everything**: `.github/**` (workflows, issue forms, CODEOWNERS, dependabot), +`AGENTS.md`, `CLAUDE.md`, `deny.toml`, `.editorconfig`, `.gitattributes`, `examples/changelog.rs` (724-line +repo tool), `src/header_check.rs`, `tests/toolchain_pin.rs`, `rust-toolchain.toml`. Licence files and README are +present (good). There is no `include`/`exclude` and no doc telling you to curate the package. + +I added an `exclude` list (`.github/`, agent docs, `deny.toml`, editor files, `examples/changelog.rs`). Things I +could *not* cleanly exclude: +- `rust-toolchain.toml`: `tests/toolchain_pin.rs` errors ("rust-toolchain.toml not found") if it is missing, so + excluding it breaks `cargo test` from the published crate (distro packagers / crater run these). + `templates/guards/files/tests/toolchain_pin.rs:17-27`. +- `tests/toolchain_pin.rs` itself ships but is vacuous without `.github/` (passes, checks nothing). +Verified `cargo test --all-features` passes inside `target/package/humandur-0.1.0` (`packaged-crate-test.log`). + +## 4. CI / release verdict for a library (~10 min) + +Generated `ci.yml` (`templates/github/files/_github/workflows/ci.yml`): fmt, cargo-deny, then *identical* +clippy+test jobs on Windows and Linux with `--all-features` only. +- **No MSRV job**, although `rust-version = "1.98"` is a public promise and README shows an MSRV badge. +- **No `--no-default-features` / feature matrix**: an optional feature that breaks the default build passes CI. +- **No docs job** (`RUSTDOCFLAGS=-D warnings cargo doc`), despite "docs.rs ready" in the README. +- **No package/publish-dry-run job** on PRs; the only dry run is in the manual publish workflow, i.e. at release time. +- Windows job is reasonable for a lib only if it has OS-specific code; costs a 60-minute runner otherwise. +- **`actions/checkout` without `persist-credentials: false`** (zizmor `artipacked`, medium) at + `ci.yml:39,58,74,125` and `publish.yml:33`. + +**The toolchain-pin test blocks the obvious MSRV job** (top friction, ~10 min including reading the test): +`tests/toolchain_pin.rs` (`every_workflow_pins_the_same_toolchain_as_the_repo`) asserts that *every* +`toolchain:` key in every workflow equals `rust-toolchain.toml`'s channel, so +`dtolnay/rust-toolchain` with `toolchain: "1.98"` fails `cargo test`. I did not weaken the test; I installed +the MSRV with `rustup toolchain install "$(sed ... Cargo.toml)"` and `cargo +$MSRV test`, which sidesteps the +check (and reads the version from `rust-version`, so it can't drift). A real user would more likely just +delete/relax the test. Fix in the generator: emit an MSRV job and let the test accept `rust-version`. +`templates/guards/files/tests/toolchain_pin.rs:83-106`. + +`publish.yml` (selected for libs by `templates/github/manifest.js:15`): sensible shape (manual +`workflow_dispatch`, ref/version check, dry run, no binary artifacts, correct for a lib). Gaps: +- Uses a long-lived `CARGO_REGISTRY_TOKEN` secret; crates.io trusted publishing exists (zizmor flags it). + I switched to `rust-lang/crates-io-auth-action@3268eb4 # v1.0.6` with job-scoped `id-token: write`. + `templates/github/files/_github/workflows/publish.yml:9,61-62`. +- Runs no tests before publishing (`cargo publish` only builds). Added both feature configs. +- Ref check accepts a *branch* named `v0.1.0`; added a `github.ref_type == tag` check. +- No GitHub release / changelog body for libs (fine, but changelog.rs docs point at a release.yml that + isn't generated - F0.5). +- zizmor pedantic: 6 `superfluous-actions` infos (dtolnay/rust-toolchain where rustup is preinstalled); + `undocumented-permissions` after my `permissions:` block until I added per-line comments. + +Cargo.toml metadata for crates.io: description, license, repository, readme, rust-version, edition, +docs.rs metadata all present (good). `keywords`/`categories` empty (F0.2; filled in). No `exclude` (section 3). +`documentation`/`homepage` absent, which is fine (crates.io defaults to docs.rs). + +## 5. Generated docs accuracy (quotes) + +- CLAUDE.md: "`src/header_check.rs` walks `src/`, `tests/` and `examples/`" - it also walks `benches/` and `build.rs`. +- CLAUDE.md + CONTRIBUTING: "Every user-visible change adds a line under `## [Unreleased]`" vs. + `examples/changelog.rs`: "The changelog is derived, not authored". **The pristine scaffold fails its own + `cargo run --example changelog -- --check`** ("CHANGELOG.md is out of date with the git history"), and + running the generator rewrites the header ("This file is generated") and replaces my hand-written + Unreleased lines with commit subjects. Root cause: `templates/base/files/CHANGELOG.md:5` and + `templates/base/files/CLAUDE.md:~229` only switch to the "generated" wording for `changelogGen & workspace`, + while single-crate projects still get the generator (`templates/guards/files/examples/changelog.rs`). + `--check` also dumps a 20-frame anyhow backtrace (RUST_BACKTRACE set in this env, but it's an expected + user error, not a bug). Log: `changelog-example.log`. +- `examples/changelog.rs:49,347`: "`.github/workflows/release.yml` owns" the release body - libs get `publish.yml`. +- CLAUDE.md "Errors are one `thiserror` enum" - a positioned parse error is naturally a struct + kind enum; + I reworded it (`templates/base/files/CLAUDE.md:~250`). +- CLAUDE.md/CONTRIBUTING/lib.rs tagline sentences missing a full stop (F0.3). +- README "What's inside: Typed errors. One `Error` enum and a `Result` alias" - placeholder-ish marketing for + the template's Version type; had to rewrite the whole section anyway. +- AGENTS.md handoff list omits `cargo deny check` and doc/MSRV checks that CI (after my changes) runs; the + README/CLAUDE lists include deny. Minor inconsistency across the three docs. +- Accurate and useful: the commit-by-path rule, the banner example, the toolchain-pin explanation, + "examples are compiled by `cargo test`". + +## 6. Deleted / rewritten from the scaffold + +Deleted `src/version.rs` (template demo), `log`/`toml`/non-optional `serde` deps. Rewrote lib.rs, error.rs, +basic example, api test, README body, CHANGELOG lines, CLAUDE.md error bullet + tagline, CONTRIBUTING release +step, ci.yml (+msrv, docs, package jobs, no-default-features steps, persist-credentials), publish.yml +(trusted publishing, tests, tag check). Kept `examples/changelog.rs` but excluded it from the package. +Nothing in the lint table, deny.toml policy or the guard tests was weakened. + +## 7. What the scaffold should arguably provide for `--preset lib` + +1. MSRV + `--no-default-features` + docs + `cargo publish --dry-run` CI jobs; toolchain-pin test that accepts + `rust-version`. +2. serde as an optional feature (or not at all), no `toml`/`log` by default. +3. A curated `exclude`/`include` in Cargo.toml and a `keywords`/`categories` reminder. +4. `persist-credentials: false` on every checkout; trusted publishing in publish.yml. +5. Changelog docs that match the generator actually shipped (or no generator for single crates). +6. A lib-appropriate deny allow-list (no font licences; MPL as an explicit decision). +7. No release profile / Windows target / Windows-linker prose for libraries. + +## Time summary (ranked) + +| Item | Cost | +|---|---| +| CI gaps for a lib + toolchain-pin test blocking an MSRV job | ~15 min | +| Package contents / exclude (and rust-toolchain.toml coupling) | ~5-8 min | +| Unused non-optional serde/toml/log deps; turning serde into a feature | ~5 min | +| Changelog policy contradiction (incl. a self-inflicted `git checkout` revert while probing) | ~5 min | +| zizmor artipacked + trusted publishing | ~5 min | +| wildcard_enum_match_arm on non_exhaustive enum in tests | ~2 min, 1 retry | +| Header banners | ~0 (helped) | +| cargo-deny with proptest | ~0 (just noise warnings) | diff --git a/docs/dogfood/evidence/friction-logscan.md b/docs/dogfood/evidence/friction-logscan.md new file mode 100644 index 0000000..fc10c30 --- /dev/null +++ b/docs/dogfood/evidence/friction-logscan.md @@ -0,0 +1,238 @@ +# Friction log: building `logscan` on a fresh `cli` scaffold + +Dogfood run, 2026-11-20. create-rust-app built from `/home/user/create-rust-app` (dist). +Project: `/home/user/cra-dogfood/projects/real/logscan`. Logs: `/home/user/cra-dogfood/logs/real-cli/`. + +Cost notation: `[~Nm, K attempts]` = rough wall-clock minutes spent / number of tries. + +## 0. Scaffold (`scaffold.log`) + +Command: + +``` +node dist/bin/create-rust-app.js logscan --name logscan --preset cli --with subcommands \ + --author "Dogfood Tester" --github dogfood-tester --license "MIT OR Apache-2.0" \ + --set tagline="Parse, filter and summarise log files" -y --no-color +``` + +`[~1m, 1 attempt]` Clean. 31 files, git init + first commit, cargo fetch. + +- Minor: the summary prints `then git init + first commit / cargo fetch` *after* both have already run; + reads like a to-do list rather than a record of what happened. +- Minor: the tagline is pasted verbatim into sentences that need a full stop, so the generated docs read + `Logscan is a command-line tool in Rust. Parse, filter and summarise log files` (CLAUDE.md line 3), + `Thanks for considering a contribution to Logscan: Parse, filter and summarise log files` (CONTRIBUTING.md) + and `//! Logscan: Parse, filter and summarise log files` (src/lib.rs). The `--help` example + (`--set tagline="A useful app"`) has no full stop either, so every user hits this. +- Scaffold-pinned crate versions checked against crates.io (2026-11-20): anyhow 1, clap 4 (4.6.9), + dirs 7 (7.0.0), env_logger 0.11 (0.11.11), log 0.4, serde 1, toml 1.2 (1.2.1), tempfile 3 (3.27.0). + **All current; nothing outdated.** + +## 1. Following the generated docs (README / AGENTS.md / CLAUDE.md / CONTRIBUTING.md) + +`[~10m reading]` Overall the docs are good: the header-banner rule, the lint rules, `#[expect]` policy and +"commit by path" are all clearly stated, and CLAUDE.md's banner example was enough to write nine new +files that passed `header_check` first time. Inaccuracies found: + +- **CHANGELOG policy contradicts the shipped generator** `[~6m]`. CLAUDE.md ("`CHANGELOG.md` moves with the + code: Every user-visible change adds a line under `## [Unreleased]`") and CONTRIBUTING.md ("Add a line + under `## [Unreleased]` in the same pull request") describe a *hand-written* changelog, and the + generated CHANGELOG.md says "Entries follow the conventional-commit subjects". But the scaffold also + ships `examples/changelog.rs`, which says "The changelog is derived, not authored", and + **`cargo run --example changelog -- --check` fails on the untouched fresh scaffold** ("CHANGELOG.md is + out of date with the git history"). Regenerating rewrites the header to "**This file is generated.**", + lower-cases the display name (`logscan` vs `Logscan`) and replaces the hand-written entry with the raw + commit subject. So the single-crate `cli` preset documents one policy and ships a tool enforcing the + other. Nobody runs `--check` in CI, so it is a latent trap rather than a red gate. + Responsible: `templates/base/files/CHANGELOG.md:5-12` (`@if changelogGen & workspace` - the + generated-file wording is only used for workspaces), `templates/base/files/CLAUDE.md:220-235` + (`@elif changelogGen` = manual policy for single crates), `templates/base/files/CONTRIBUTING.md:177-188`, + vs `templates/guards/files/examples/changelog.rs` (mounted for any `changelogGen`, + `src/engine/groups.ts:24`) whose output header is at `templates/guards/files/examples/changelog.rs:588`. + CLAUDE.md's Commands block (`templates/base/files/CLAUDE.md:48-50`) only lists the changelog command for + workspaces (`cargo xtask changelog`); single crates are never told the example exists. +- **README placeholder**: "Logscan is a command-line tool. Describe here what it does and who it is for" + (`templates/base/files/README.md:31`). Expected, but the "What's inside" section then describes the + *scaffold* (clap, env_logger, forgiving config) as if they were product features; a user has to rewrite + the whole top half. I replaced it with real usage. +- **Tagline without a full stop** (see section 0), `templates/base/files/CLAUDE.md:6`, + `templates/base/files/CONTRIBUTING.md:3`, `templates/cli/files/src/lib.rs:33`. +- CLAUDE.md Commands lists `cargo run # the app, debug` - with `subcommands` on, a bare `cargo run` is a + usage error (exit 2). Harmless but slightly wrong for this preset. +- CLAUDE.md says the lint ban applies "not even in tests"; CONTRIBUTING agrees. Accurate (clippy's + `unwrap_used` is denied in tests too), and the scaffold's own tests show the `-> anyhow::Result<()>` + + `let ... else { bail! }` pattern, which made it easy to follow. + +## 2. Things the scaffold shape made me rewrite + +- **`run(args, out)` has no stdin and no TTY/colour information** `[~10m]`. `src/lib.rs`'s entry point + takes only args and a `Write`, and `config::load()` is called *inside* the command (reads the real + user config dir during in-process tests). A log tool needs stdin, needs to know whether stdout is a + terminal (colour), and tests need to inject config. I replaced it with an `Io { stdin, stdout, + terminal, config }` struct, moved `config::load()` and terminal detection to `main.rs`, and rewrote + all of `tests/cli.rs`. Responsible: `templates/cli/files/src/lib.rs` (`run` signature), + `templates/cli/files/src/main.rs`, `templates/cli/files/src/cli.rs` (`hello` calls `config::load()`). + A scaffolded CLI arguably should pass a stdin reader through from day one. +- **`main` returns `anyhow::Result`** `[~5m]`: errors print as Rust's `Debug` form + (`Error: ...` + `Caused by:` block, plus a full backtrace when `RUST_BACKTRACE=1` is set, as it is in + this environment). For a user-facing CLI I rewrote `main` to print one `logscan: error: ctx: cause` + line and exit 1. Also **no broken-pipe handling**: `logscan parse big.log | head` would print + "Error: Broken pipe". Added `is_broken_pipe` + quiet exit 0 (and a test). Responsible: + `templates/cli/files/src/main.rs`. Both are things every CLI built on this needs. +- `hello`/`sum` placeholder commands, their tests and the greeting/name config fields: deleted/replaced + (expected; the module docs say to). The forgiving per-field config parser and atomic save were kept + and reused for `color`/`top` defaults - genuinely useful. +- **`*.log` in the generated `.gitignore` silently ignores test fixtures** `[~3m, caught only because I + checked git status]`. My `tests/fixtures/*.log` files were invisible to git, so the tests that pass + locally would fail in CI on a missing file. Fixed with `!tests/fixtures/*.log`. Responsible: + `templates/base/files/_gitignore:4`. Any project that processes logs (or keeps `.log` golden files) + hits this; consider dropping the rule or adding the negation by default. + +## 3. Adding modules: header banner + `header_check` + +`[~0m extra, 1 attempt]` Nine new `src/*.rs` and one `tests/binary.rs`, all passed `header_check` on the +first run. Copying an existing banner as CLAUDE.md says, and the path->`Module:` rule +(`tests/x.rs` -> `x (integration test)`) is documented precisely. Helped rather than obstructed. I did +not need the error messages; reading `src/header_check.rs` they are specific (`declares Module: X but +sits at Y`, `header line exceeds 100 columns`). One oddity: the rule for `src/bin/helper.rs` is +`-helper (binary crate root)` (`templates/guards/files/src/header_check.rs`, `module_for`), but +Cargo names that binary `helper`, not `logscan-helper`. + +## 4. Dependencies + cargo-deny + +`[~3m, 1 attempt]` Added `regex 1.13`, `serde_json 1.0`, `jiff 1.0` (no default features, `std,serde`), +`anstyle 1.0`. `cargo deny check` passed immediately: licences ok, advisories ok, sources ok. + +- Noise: **the fresh scaffold already emits 11 `license-not-encountered` warnings** (OFL-1.1, + Ubuntu-font-1.0, MPL-2.0, Zlib, BSL-1.0, ... in a CLI with no fonts or GUI deps). Real warnings (like + my duplicate `jiff 0.2` via env_logger vs `jiff 1.0`) drown in them. Responsible: + `templates/base/files/deny.toml` (or wherever the allow-list is generated); it is the GUI list applied + to every kind. Not a failure, just noise. +- `deny.toml` `[graph] targets` includes `x86_64-pc-windows-msvc` and `rust-toolchain.toml` adds the + MSVC target for a CLI preset, so every Linux developer's rustup downloads the Windows std on first + build. Minor. +- `multiple-versions = "warn"`: jiff 0.2 (env_logger) + 1.0 (mine) is a duplicate. Fine as a warning. + +## 5. Lint strictness + +`[~5m total, 2 attempts]` Surprisingly little friction on ~1,500 lines of new code: + +- `warnings = "deny"` promoted `private_interfaces` to an error when a `pub` method of the (necessarily + public) `style` module took the crate-private `Level`. Fix: narrow to `pub(crate)`. 1 attempt. +- `unreachable_pub = "forbid"` forced a sweep of every `pub` in private modules to `pub(crate)` before + the first build. Expected and documented; one `sed`. +- `RUSTDOCFLAGS="-D warnings" cargo doc` failed once: `rustdoc::private_intra_doc_links` (module doc of a + public module linked a `pub(crate)` type). Note **CI never runs `cargo doc`**, so this class of error + would rot silently in a generated project (see 7). +- `clippy::too_many_arguments` would have fired on a flat `filter(...)` helper; I restructured into a + `#[derive(clap::Args)] FilterArgs` struct instead of reaching for `#[expect]`. In the end I needed + **zero `#[expect]`s**, so the expect path was never exercised for real. +- Docs inaccuracy: CLAUDE.md says "Suppress with `#[expect(lint, reason = "...")]`, never `#[allow]`" + as a general rule, but `unused_imports`, `unused_must_use`, `unreachable_patterns` and `unreachable_pub` + are `forbid` in `[lints.rust]`, and **`forbid` lints cannot be `#[expect]`ed at all** (rustc errors + "incompatible with previous forbid"). Worth one sentence in `templates/base/files/CLAUDE.md` (lint + section, ~line 135-150). +- `wildcard_enum_match_arm` made me write `(Some(_) | None, true) | (None, false)` in one tuple match; + slightly awkward but fine. + +## 6. Gates (final state, logs in `/home/user/cra-dogfood/logs/real-cli/`) + +| Gate | Result | Log | +|---|---|---| +| `cargo fmt --all -- --check` | pass | `fmt.log` | +| `cargo clippy --all-targets --all-features -- -D warnings` | pass (also for `--target x86_64-pc-windows-msvc`) | `clippy.log`, `clippy-windows-target.log` | +| `cargo test --all-features` (67 tests incl. 8 header_check + toolchain_pin) | pass | `test.log` | +| `cargo deny check` | pass (13 warnings: 11 unused licences, 2 duplicate jiff) | `deny.log` | +| `RUSTDOCFLAGS="-D warnings" cargo doc --no-deps` | pass on attempt 2 | `doc.attempt1.log`, `doc.log` | +| `cargo +1.98 build` / `cargo +1.98 test` (MSRV) | pass | `msrv.log`, `msrv-test.log` | +| `actionlint` | pass, also on the unmodified generated workflows (but see note) | `actionlint.generated.log`, `actionlint.log` | +| `zizmor` | **generated workflows FAIL** (exit 14: 7x medium `artipacked`, 1x high `cache-poisoning`); pass after my fix | `zizmor.online-attempt.log`, `zizmor.attempt1-generated.log`, `zizmor.log`, `zizmor-pedantic.log` | + +No lint table, deny policy or guard test was weakened. The only scaffold policy files changed were +`.gitignore` (un-ignore fixtures) and the two workflows (made *stricter*). + +- **zizmor out of the box** `[~8m]`: plain `zizmor .github/workflows/` dies with a 401 (online audits need a + GitHub token); `--offline` is needed in a sandbox. Then it fails the generated workflows: + - `artipacked` on every `actions/checkout` (no `persist-credentials: false`): + `templates/github/files/_github/workflows/ci.yml:39,58,74,125` and + `templates/github/files/_github/workflows/release.yml:51,111,231`. None of the jobs push with git + (`gh` uses `GH_TOKEN`), so `persist-credentials: false` is free. + - `cache-poisoning` (high): `Swatinem/rust-cache` in the tag-triggered release build, + `templates/github/files/_github/workflows/release.yml:120`. A release binary built from a cache that + PR runs can write to is exactly the risk the file's own SHA-pinning comments argue against. I removed + the step. + - The generator repo has no actionlint/zizmor check of its output at all (`grep -r zizmor` in the repo: + nothing), which is how this shipped. +- **actionlint caveat**: `shellcheck` is not installed in this environment, so actionlint silently skipped + the `run:` scripts. It would likely flag `gh release upload "$TAG" $(find . -type f) --clobber` + (SC2046, `release.yml` "Upload and undraft") - harmless with these file names. + +## 7. Step 5: would `ci.yml` / `release.yml` work for logscan? + +Verified locally where possible: the tag/version `awk` prints `0.1.0` from this `Cargo.toml`; installing +`cargo-cyclonedx 0.5.9 --locked` and running the exact SBOM command with +`--target x86_64-pc-windows-msvc --override-filename logscan.cdx` writes `logscan.cdx.json` +(CycloneDX 1.3, 52 components), which is the path the next step copies (`sbom-sim.log`). + +**ci.yml - works**, with gaps: +- fmt, cargo-deny (action, `--all-features`), Windows (clippy, test, `cargo build --release --bins`) and + Linux (clippy, test) jobs all map onto commands that pass here. Toolchain `1.99.1` matches + `rust-toolchain.toml` (and `tests/toolchain_pin.rs` enforces it). Permissions `contents: read`. +- Gap: **MSRV is declared (`rust-version = "1.98"`) but never built in CI**, and **`cargo doc -D warnings` + is not run**; both were gates in this exercise and both could regress unnoticed. + (`templates/github/files/_github/workflows/ci.yml`). +- My own Windows-only trap, which the scaffold's config design invites: `dirs::config_dir()` on Windows + ignores env vars, so integration tests that spawn the binary cannot isolate the user config via + `XDG_CONFIG_HOME`/`APPDATA`. I added a `LOGSCAN_CONFIG` override. The scaffold's config module could ship + that hook (`templates/cli/files/src/config.rs`, `config_path`). + +**release.yml - would run green on a public repo, but ships the wrong thing for a CLI:** +- Correct: `v*` tag trigger + `workflow_dispatch` with tag input; tag-vs-Cargo.toml check before any + build; draft -> build -> attest -> publish ordering; per-job permissions (only `draft`/`publish` get + `contents: write`, only `publish` gets `id-token`/`attestations: write`); binary path + `target/x86_64-pc-windows-msvc/release/logscan.exe` matches the crate name; artifact name + `release-assets-` and `pattern:` + `merge-multiple` download are right; both attest actions + point at files that exist (`dist/*.zip`, `dist/logscan-${TAG}-sbom.cdx.json`). +- **Only `x86_64-pc-windows-msvc` is built for the `cli` preset** - no Linux or macOS binary for a + command-line tool. And the comment "adding a target later is an entry rather than a rewrite" is not + true: Package hard-codes `logscan.exe` and `7z ... -tzip`, and the SBOM is named + `logscan-${TAG}-sbom.cdx.json` without the target, so two matrix entries would collide under + `merge-multiple: true` and `attest-sbom` takes a single `sbom-path`. Responsible: + `templates/github/files/_github/workflows/release.yml:105-106` (matrix), `:145` (package, `.exe`), + `:187` (SBOM name without target) and `:256-259` (`attest-sbom` single `sbom-path`). +- `actions/attest-build-provenance` / `attest-sbom` only work on public repos (or GitHub Enterprise + Cloud private repos); a private repo on a personal plan fails the `publish` job after the draft is + made. Not mentioned in CONTRIBUTING's "Cutting a release". +- `cargo install cargo-cyclonedx` compiles from source on every release (a few minutes on Windows); + acceptable. +- zizmor findings above (now fixed in my copy). + +## 8. What I had to build that the scaffold could provide + +- stdin plumbing + TTY/`NO_COLOR` colour decision + `--color` flag (every CLI needs these; the + scaffold's `run(args, out)` has neither) `[~15m]`. +- single-line error printing and broken-pipe-is-success in `main` `[~5m]`. +- an integration test that spawns the real binary (`CARGO_BIN_EXE_`) with a hermetic env; the + scaffold only has in-process tests, which cannot see exit codes of `main`, stderr, or colour detection + `[~10m]`. +- a config-path env override for test isolation (see 7) `[~5m]`. + +## 9. What helped + +- `header_check` + the CLAUDE.md example: zero failed attempts across 10 new files. +- Strict lints caught nothing I disagreed with; the tests-return-`Result` pattern was easy to follow. +- The forgiving config parser and atomic save, reused as-is for `color`/`top`. +- cargo-deny's allow-list covered regex/jiff/serde_json/anstyle (MIT/Apache/Unlicense) without edits. +- SHA-pinned actions, least-privilege permissions, the tag/version check and the toolchain-pin test are + all genuinely good. + +## Ranked by time cost (rough) + +1. Scaffold `run()` shape: no stdin/TTY/config injection; rewrote lib/main/tests (~25m incl. section 8). +2. Windows test isolation / config dir (~10m). +3. zizmor failures on generated workflows + offline flag (~8m). +4. CHANGELOG policy vs `examples/changelog.rs --check` failing on a fresh scaffold (~6m). +5. `main` error format + broken pipe (~5m). +6. Lints: private_interfaces / unreachable_pub sweep / rustdoc private link (~5m). +7. `*.log` gitignore hiding fixtures (~3m, but would have cost a red CI run). +8. deny.toml noise (11 warnings on a fresh scaffold) (~2m). diff --git a/docs/dogfood/evidence/friction-tailview.md b/docs/dogfood/evidence/friction-tailview.md new file mode 100644 index 0000000..3f93b8f --- /dev/null +++ b/docs/dogfood/evidence/friction-tailview.md @@ -0,0 +1,197 @@ +# Friction log: tailview (tui preset, real app build) + +Scaffold command (log: `logs/real-tui/scaffold.log`): + +``` +create-rust-app tailview --preset tui --name tailview --author "Dogfood Tester" \ + --github dogfood-tester --set tagline="Follow log files live in your terminal" --no-color -y +``` + +2 s, 31 files, git commit + `cargo fetch` done. I then followed README / AGENTS.md / CLAUDE.md / +CONTRIBUTING.md as the guide. + +**What got built:** `tailview FILE...`, a live multi-file tail viewer. It has `tail -F` semantics +(handles truncation, rotation, and files that don't exist yet, starting from a backward-read +backlog), a notify-woken background reader thread with a 250 ms polling fallback that sends to the +UI over an mpsc channel, follow/pause with an unseen-line counter, scrolling, a live regex filter +(smart case, invalid regex falls back to a literal match with the error in the status bar, match +highlighting), a help popup, a status bar plus key hints, per-file tags, a buffer capped by +`--max-lines`, and replacement of control characters (a log can't inject escape sequences). +Modules: `tail.rs`, `reader.rs` (new); `app.rs`, `ui.rs`, `lib.rs` (rewritten). There are 43 tests: +state transitions, tail edge cases, a real-thread reader test, and `TestBackend` render tests that +check text, a highlight cell's background, and cursor position. +New deps: `notify 8`, `regex 1`, dev `tempfile 3`. Bumped `ratatui 0.29→0.30` and `crossterm 0.28→0.29`. +Dropped `serde` and `toml`, which were unused. + +Costs are rough wall-clock for an experienced user, plus attempt counts. **Ranked by cost:** + +| # | Item | Cost | +|---|------|------| +| 1 | Release workflow is Windows-only; adding a target needs four coupled edits | ~25 min | +| 2 | Changelog: the docs and `examples/changelog.rs` contradict each other; `--check` fails on a pristine scaffold | ~15 min | +| 3 | zizmor fails on the untouched scaffold (8 findings) | ~10 min | +| 4 | Scaffold pins ratatui 0.29 / crossterm 0.28 (current: 0.30.2 / 0.29.0) | ~5 min (no breakage) | +| 5 | `cargo doc -D warnings` (my gate) failed once; CI doesn't run rustdoc or MSRV | ~3 min, 1 attempt | +| 6 | Unused serde + toml in the tui preset; default author is someone else's name | ~3 min | +| 7 | Event loop has no slot for background work (channel drained after each tick) | ~3 min | +| 8 | Temp-file logger at a predictable `/tmp` path | 0 min (noticed, left) | +| — | Header banner, cargo-deny, lint table: **zero friction** (see below) | 0 | + +--- + +## 1. Release workflow: Windows-only, and "adding a target is an entry" is false (~25 min) + +The generated `release.yml` builds exactly one target, `x86_64-pc-windows-msvc`, for a **terminal** +app whose users are mostly on Linux/macOS. Template: `templates/github/files/_github/workflows/release.yml:105-106` +(the matrix is the same for every kind). `rust-toolchain.toml` also lists only the Windows target +(`templates/base/files/rust-toolchain.toml:11`). + +The template comment at `release.yml:103-104` reads: *"The matrix stays a matrix so adding a target +later is an entry rather than a rewrite."* That is false. Adding `ubuntu-latest / +x86_64-unknown-linux-gnu` also required these changes: +- `release.yml:143/145`: `cp target/${TARGET}/release/@@bin@@.exe` hard-codes `.exe`. +- The Package step only zips with `7z`. I added `tar.gz` for non-Windows. +- `release.yml:184/187`: the SBOM is written as `@@name@@-${TAG}-sbom.cdx.json` with no target in the + name. With two matrix jobs and `merge-multiple: true`, one SBOM silently overwrites the other. + The SBOMs really do differ by target: I checked with cargo-cyclonedx 0.5.9 locally (179 vs 171 + components; `windows-sys` appears only in the Windows SBOM). +- `release.yml:259`: `attest-sbom` takes a single `sbom-path`, so I needed one step per target. +- Checksums, upload and attest globs only cover `*.zip`. + +Done in this project's commit `9b6c00b`. actionlint and zizmor are clean afterwards. + +## 2. CHANGELOG: two conflicting systems (~15 min) + +- CLAUDE.md ("`CHANGELOG.md` moves with the code") and CONTRIBUTING ("Changelog") say to + **hand-add** a line under `## [Unreleased]` in each commit. I did that. +- But the scaffold also ships `examples/changelog.rs`. It **regenerates** the file from git + (header: *"**This file is generated.** … edits to them do not survive"*), and its `--check` + mode fails: + - on my project, because the hand-written entries are discarded (`logs/real-tui/changelog-regen.diff`); + - **on the pristine scaffold commit too** (`pristine_check_exit=1`). The generator writes + `All notable changes to @@name@@` (`templates/guards/files/examples/changelog.rs:586`), while the + template writes `@@displayName@@` (`templates/base/files/CHANGELOG.md:3`). The template also + picks the "generated" header only for `changelogGen & workspace` (`CHANGELOG.md:5`; + `CLAUDE.md:220/229` likewise). +- None of the single-crate docs (README, CLAUDE.md, CONTRIBUTING) mention `examples/changelog.rs`. + `docs/PLAN.md:75-77` says the changelog is *generated*, so the single-crate docs contradict the plan. +- Kept the hand-edited version, since that's what the docs say. Log: `logs/real-tui/changelog-check.log`. + +## 3. zizmor fails out of the box (~10 min) + +`zizmor --offline` on the untouched scaffold: exit 14, 7× medium `artipacked` (every +`actions/checkout` lacks `persist-credentials: false`) and 1× high `cache-poisoning` +(`Swatinem/rust-cache` in the tag-triggered release build). Log: `logs/real-tui/baseline-zizmor.log`. +- Templates: every checkout in `templates/github/files/_github/workflows/ci.yml:39,58,74,125` and + in `release.yml` (draft, build, publish), plus the rust-cache step in `release.yml:119-121`. +- Fix (not a weakening): add `persist-credentials: false`; `gh` uses `GH_TOKEN`, not the git + credential. Removed rust-cache from the release build, since releases should build cold. +- Online zizmor needs a GitHub token (HTTP 401). That's environment, not scaffold. +- This hurts more because the workflow comments brag about supply-chain hardening (SHA pins, + least privilege), yet the most common zizmor finding ships. + +## 4. Outdated ratatui / crossterm pins (~5 min) + +`templates/tui/deps.js:8-9` pins `ratatui 0.29` / `crossterm 0.28`. crates.io currently has +ratatui 0.30.2 / crossterm 0.29.0. Bumping both together kept a single crossterm in the lock. +The scaffold's `terminal.rs` / `event.rs` compiled unchanged on 0.30. The one 0.30 change I hit, +`TestBackend` error type → `Infallible`, works with `?` into anyhow. The deps.js comment +explaining the pin is fine but needs updating. The scaffold could also re-export through +`ratatui::crossterm` to make version skew impossible. + +## 5. Docs / CI gate gaps (~3 min, 1 attempt) + +- `RUSTDOCFLAGS="-D warnings" cargo doc` failed once on a private intra-doc link + (`[`filter_action`]` in a pub item's doc). Easy fix, but **no generated gate runs rustdoc**: not + CI, not CLAUDE.md "Commands", even though `missing_docs` is denied, so docs clearly matter. +- The README badge says `rust 1.98+` and `Cargo.toml` says `rust-version = "1.98"`, but nothing + checks the MSRV. CI uses only the 1.99.1 pin. (`cargo +1.98 build`/`test` passed here.) +- Neither actionlint nor zizmor runs in CI. With both added, (3) would have been caught at + generation time. +- `CLAUDE.md` puts *"Tests return `anyhow::Result<()>`, and every `assert!` carries a message"* + under "Rules the build enforces". Nothing enforces either; they're conventions. +- `event.rs` doc says *"an idle app uses no CPU"*, but it redraws at 10 Hz forever (rainbow tick). + Cheap, but not "no CPU". (`templates/tui/files/src/event.rs`) + +## 6. Preset defaults (~3 min) + +- The tui preset includes `serde` + `toml` (`src/presets.ts:20`, base DEFAULTS), but no generated + code uses either. I removed them. +- `src/presets.ts:8-9`: the default `author` / `github` are `Lawrence Norton` / `lnorton89`, and + `git config user.name` is ignored (checked with `--json -y`). A user who runs + `npx create-rust-app x -y` gets a stranger's name in LICENSE, CODEOWNERS and Cargo `authors`. + `--help` doesn't show the default. (I passed `--author`, so I wasn't hit.) +- `deny.toml` passes but prints 7–10 `license-not-encountered` warnings on every run (`src/gen/deny.ts` + has a GUI-oriented superset allow-list: `OFL-1.1`, `Ubuntu-font-1.0`, …). It's noise, not a blocker. + +## 7. TUI skeleton: a good base, mostly kept + +- **Kept unchanged:** `terminal.rs` (guard + chained panic hook; the restore is correct, verified + under a pty: `icanon echo` before *and* after), `event.rs`, `main.rs`, `logging.rs`, the + `header_check.rs` banner format, and the title-bar colour helpers. +- **Rewritten:** the `app.rs` demo checklist became the log state. I kept and extended its + `BINDINGS` single-source table (hints + help pane + key lookup); that pattern was the most + useful thing in the scaffold. `ui.rs` got a new layout. In `lib.rs`, the run loop now drains the + reader channel after each event. +- **Missing:** `Events` only knows terminal input + tick, with no slot for a background + source. Every "TUI that shows live data" needs this, so the channel is drained after each wait + and latency is bounded by the tick. A `Event::App(T)` variant fed by an mpsc, or a documented + pattern, would help. There's also no viewport-from-terminal-size helper for paging, and no + `tempfile` dev-dep for tests that touch files. +- The panic hook restores the terminal on *any* thread's panic. In debug (unwind), a panicking + background thread would restore the terminal while the UI keeps drawing. That's a non-issue in + release (`panic = "abort"`), but worth a doc line once threads are involved. +- The scaffold doesn't use ratatui 0.30's `ratatui::try_init` / `DefaultTerminal`. That's fine, + since the hand-rolled version is clearer, but it's dated. + +## 8. Logging to a predictable temp path (noticed, not changed) + +`templates/tui/files/src/logging.rs:29,34`: `File::create(std::env::temp_dir().join("@@name@@.log"))`. +On Linux that's world-writable `/tmp`, and `File::create` follows symlinks and truncates. Another +local user can pre-create `/tmp/tailview.log -> ~/.bashrc`. Most distros mitigate this with +`fs.protected_symlinks`, but the right place is the user's state/cache dir, or `create_new` plus a +per-user name. + +## Zero-friction items (worth saying) + +- **Header banner + `header_check`:** I added two new files and passed on the first attempt + (0 failures) by copying a neighbour's banner, as CLAUDE.md suggests. I also probed the error + messages deliberately: `src/view/mod.rs: does not open with the header rule` and + `declares \`Module: tail_other\` but sits at \`view::tail2\``. They're clear and list every + problem at once. It helped. One nit: "does not open with the header rule" could print the rule + line itself. +- **cargo-deny:** `notify` (CC0-1.0), `regex`, and `tempfile` with all their transitive deps passed + `cargo deny check` with no changes. Licences, bans, sources and advisories were all OK. +- **Lint table:** **zero** lints fired on ~2,000 lines of TUI code (casts, `u16` cursor maths, + VecDeque windowing, usize arithmetic). I never needed `#[expect]`. That's because the table + denies panicking APIs and wildcards but enables no `cast_*`, `indexing_slicing`, + `arithmetic_side_effects` or `pedantic` (the template's own `as u8` in `hsl_to_rgb` passes). I wrote + `try_from`/`saturating_*`/`.get()` by habit, but nothing required it. "Strict" here really + means "no panics, no wildcards, documented". The `#[expect]` path is documented clearly but went + unused. +- Windows cross-clippy (`--target x86_64-pc-windows-msvc`) is clean (`logs/real-tui/clippy-windows.log`). + +## Gates (final, all in `logs/real-tui/`) + +fmt ✔ · clippy -D warnings ✔ · test ✔ (40 lib + 3 toolchain_pin, incl. header_check) · deny ✔ · +doc -D warnings ✔ (after 1 fix) · `cargo +1.98 build` ✔ (+ `test` ✔) · actionlint ✔ · zizmor ✔ +(after fixes in item 3). Smoke: `smoke.typescript` (raw pty capture), `smoke-rendered.txt` (pyte-rendered +frames: live append, help pane, filter prompt, filtered view), `smoke-restore.typescript` +(stty `icanon echo` before/after, EXIT=0), `smoke-errors.log` (no tty → "could not set up the +terminal: No such device or address", exit 1; no args → usage, exit 2). + +## Workflow verdict (step 5) + +- **ci.yml:** correct as generated. It runs on push to main and on PRs, read-only token, SHA-pinned + actions, per-job timeouts, fmt / deny / clippy+test on Windows+Linux, and a release build on + Windows (catches `panic = "abort"` issues). `arguments: --all-features` is a valid global + cargo-deny flag. Gaps: no MSRV, rustdoc, actionlint or zizmor job; fails zizmor (item 3). +- **release.yml:** the `v*` tag trigger, the tag-vs-`Cargo.toml` check, draft → build → publish + sequencing, scoped permissions (`contents: write` only on draft/publish; + `id-token`/`attestations: write` only on publish), the artifact naming per target, + `download-artifact` with `pattern` + `merge-multiple`, provenance attestation, and the + cargo-cyclonedx 0.5.9 flags (verified locally) are all right. **It would work, but it only + ships a Windows `.zip`** for a TUI. Adding a target breaks SBOM naming and attestation (item 1). + Also: artifact attestations need a public repo or GitHub Enterprise Cloud, so on a private repo + on a free/Team plan, `publish` fails at the attest step and leaves a draft. Nothing in the docs says so. + `gh release upload $(find . -type f)` is unquoted but safe with these filenames. diff --git a/docs/dogfood/evidence/research.md b/docs/dogfood/evidence/research.md new file mode 100644 index 0000000..5e68129 --- /dev/null +++ b/docs/dogfood/evidence/research.md @@ -0,0 +1,115 @@ +# create-rust-app: npm name and dependency-version research + +Date: 2026-11-20. Raw output: `/home/user/cra-dogfood/logs/research/`. Nothing was published and there was no `npm login`. The repository was not modified. + +## 1. npm name + +### `create-rust-app` +- `npm view create-rust-app --json` returned E404 "Unpublished on 2025-06-19T21:40:46.066Z" (`npm-view-create-rust-app.json`). +- The registry document (`curl-create-rust-app.json`, HTTP 200) is a tombstone. It was created 2022-03-12. Its only version, `0.0.0`, was unpublished on 2025-06-19. It lists no maintainers or owner and has no security-holding marker. This is a normal unpublish, not a security hold. +- The npm unpublish policy (https://docs.npmjs.com/policies/unpublish) says that after a full unpublish you "may not publish any new versions of that package until 24 hours have passed". It also says "Once `package@version` has been used, you can never use it again", so `0.0.0` can never be reused. The page does not say whether a *different* account may claim the name. That was not verified, because only a real publish would test it. +- Confusion risk: crates.io has a well-known, unrelated `create-rust-app` crate (v11.0.3, 2025-06-22; `crate-create-rust-app.json`). It does the same job, generating Rust projects. npm's guidelines (https://docs.npmjs.com/package-name-guidelines) ask that unscoped names "Will not confuse others about authorship". **Do not take this name**, even if npm would allow it. + +### npm similarity rules +- npm's "moniker" rule (https://blog.npmjs.org/post/168978377570/new-package-moniker-rules): "we remove punctuation from its name and compare it to existing package names". For example, `react-native` blocks `reactnative`, `react_native` and `react.native`. +- https://docs.npmjs.com/threats-and-mitigations: "npm is able to detect typosquat attacks and block the publishing of these packages." +- Scoped names are not compared against unscoped names, and the docs encourage scopes. +- So `create-rustapp` could collide with the `create-rust-app` tombstone, if tombstones count. That is unverified, so avoid it. + +### `npm create` / `npm init` mapping +Sources: https://docs.npmjs.com/cli/v11/commands/npm-init, confirmed through Context7 `/npm/cli`. +- `npm init foo` -> `npm exec create-foo` +- `npm init @usr/foo` -> `npm exec @usr/create-foo` +- `npm init @usr` -> `npm exec @usr/create` + +`create` is an alias of `init`. + +### Candidates (raw results: `candidates.txt`, `reg-*.json`) +| Package | Registry | Similar / notes | Invocation | +|---|---|---|---| +| create-rust-app | unpublished 2025-06-19 | crates.io crate of the same name | `npm create rust-app` | +| create-rust-app-kit | **404 free** | none | `npm create rust-app-kit` | +| create-rusty-app | **404 free** | none | `npm create rusty-app` | +| create-rustaman | **404 free** | named after a reference app, so a misleading name | `npm create rustaman` | +| create-ferris-app | **404 free** | none | `npm create ferris-app` | +| create-ferris | **404 free** | none | `npm create ferris` | +| create-rust-project | **404 free** | none | `npm create rust-project` | +| create-rust-scaffold | **404 free** | none | `npm create rust-scaffold` | +| create-rust-template | **404 free** | none | `npm create rust-template` | +| create-crate | **404 free** | none | `npm create crate` | +| create-oxide-app | **404 free** | none | `npm create oxide-app` | +| create-rustapp | 404 | likely blocked by the punctuation rule against create-rust-app | (avoid) | +| create-rs-app | taken (1.0.5, ahoward2, 2022, unrelated) | n/a | n/a | +| create-cargo-app | taken (0.0.0, chen7david, 2023) | n/a | n/a | +| create-rust | taken (0.0.2, liruifengv, "create a Rust project") | n/a | n/a | +| create-rs | taken (0.1.5, 2023) | n/a | n/a | +| create-cargo | taken (1.0.0, 2025-08) | n/a | n/a | +| create-rust-starter | unpublished 2026-05-19 | tombstone | (avoid) | +| @freeknet/create-rust-app | **404 free** | scoped, so no similarity check | `npm create @freeknet/rust-app` | +| @freeknet/create-rust | **404 free** | scoped | `npm create @freeknet/rust` | +| @freeknet/create | **404 free** | scoped | `npm create @freeknet` | + +Scope ownership: `registry.npmjs.org/-/org/freeknet/package` returned 404, and the npmjs.com profile and org pages returned 403 (bot wall; `scope-freeknet.txt`). So it is **not verified** whether an npm user or org named `freeknet` exists or who holds it. A scoped publish needs that scope. Check it while logged in before deciding. + +Not checked: the Rust Foundation trademark policy on using "Rust" in package names. + +### Recommendation +1. **`@freeknet/create-rust-app`** (`npm create @freeknet/rust-app`). It keeps the current name and makes authorship clear. Scoped names are exempt from the similarity check and avoid the crates.io confusion. It needs the `freeknet` npm scope and `--access public`. +2. **`create-rust-app-kit`** (`npm create rust-app-kit`). It is free and unscoped, has no similar name once punctuation is removed, and is closest to the current brand. +3. **`@freeknet/create`** (`npm create @freeknet`). It is the shortest invocation, and the same scope can hold other generators later. It needs the scope, like option 1. + +## 2. Template dependency versions + +MSRV is 1.98 (`src/presets.ts:14`) and the pinned toolchain is 1.99.1 (`src/presets.ts:15`). Data comes from the crates.io API (`crates-latest.txt`, `crate-*.json`). The latest stable Rust is 1.100.0 (2026-11-09; `rust-stable.txt`). The local cargo is 1.97.0, so I used the crates.io API instead of `cargo info`. + +| Crate | Pin | Latest stable | Pin admits latest? | Latest's rust-version > 1.98? | +|---|---|---|---|---| +| anyhow | 1 | 1.0.104 | yes | no (1.68) | +| thiserror | 2 | 2.0.21 | yes | no (1.77) | +| clap | 4 | 4.6.9 | yes | no (1.85) | +| log | 0.4 | 0.4.35 | yes | no (1.71) | +| env_logger | 0.11 | 0.11.12 | yes | no (1.85) | +| tracing | 0.1 | 0.1.44 | yes | no (1.65) | +| tracing-subscriber | 0.3 | 0.3.23 | yes | no (1.65) | +| serde | 1 | 1.0.229 | yes | no (1.56) | +| toml | 1.2 | 1.2.1 | yes | no (1.85) | +| dirs | 7 | 7.0.0 | yes | none declared | +| tokio | 1 | 1.54.1 | yes | no (1.85) | +| ureq | 3 | 3.5.2 | yes | no (1.85) | +| reqwest | 0.13 | 0.13.5 | yes | no (1.85) | +| **rusqlite** | 0.41 | **0.43.0** | **no** | no (1.89) | +| tempfile | 3 | 3.27.0 | yes | no (1.63) | +| windows-sys | 0.61 | 0.61.2 | yes | no (1.71) | +| egui / eframe / egui_glow / egui-winit / egui_kittest | 0.37 | 0.37.0 | yes | no (1.95) | +| winit | 0.30 | 0.30.13 | yes | no (1.70) | +| glow | 0.17 | 0.18.0 | no; **keep it**: egui_glow 0.37 and eframe 0.37 require `glow ^0.17.0` | none declared | +| glutin | 0.32 | 0.32.3 | yes | no (1.71) | +| glutin-winit | 0.5 | 0.5.0 | yes | no (1.70) | +| raw-window-handle | 0.6 | 0.6.2 | yes | no (1.64) | +| winresource | 0.1 | 0.1.34 | yes | none declared | +| **ratatui** | 0.29 | **0.30.2** | **no** | no (1.88) | +| **crossterm** | 0.28 | **0.29.0** | **no** | no (1.63) | +| **cargo-cyclonedx** (`cargo install --version 0.5.9`, release.yml:175) | =0.5.9 | **0.5.10** | no (exact pin) | no (1.86) | + +Notes: +- ratatui 0.30.2's default backend is `ratatui-crossterm` with `crossterm_0_29` (`ratatui-crossterm-features.txt`). The comment in `templates/tui/deps.js` ties crossterm to ratatui's version, so bump both together, to 0.30 and 0.29. That is a breaking API change, so re-run `scaffold-check tui` after. +- No crate's latest version needs Rust above 1.98. The highest requirement is egui 0.37, at 1.95. + +### GitHub Actions (`actions-latest.txt`, `sha-to-tag.txt`, `rust-toolchain-pinned.txt`) +| Action | Pinned SHA / comment | Tag check | Latest | Status | +|---|---|---|---|---| +| actions/checkout | 3d3c42e5 # v7.0.1 | SHA = v7.0.1 | v7.0.1 | current | +| dtolnay/rust-toolchain | 683b588c # master, 2026-10 | commit 2026-10-15, "Add 1.99.1 patch release"; ancestor of master | master df2a88e (2026-11-14) | 2 commits behind; Rust 1.100.0 was released after the pin; no major version (branch-pinned) | +| EmbarkStudios/cargo-deny-action | 3c634983 # v2.1.1 | SHA = v2.1.1 | v2.1.3 | 2 patches behind, same major | +| Swatinem/rust-cache | d1527c8f # v2.9.3 | SHA = v2.9.3 | v2.9.3 | current | +| actions/upload-artifact | cf430e03 # v7.0.2 | SHA = v7.0.2 | v7.0.2 | current | +| actions/download-artifact | 9000827c # v8.0.2 | SHA = v8.0.2 | v8.0.2 | current | +| actions/attest-build-provenance | 4d101475 # v4.2.2 | SHA = v4.2.2 | v4.2.2 | current | +| actions/attest-sbom | c6043329 # v4.1.0 | SHA = v4.1.0 | v4.1.0 | current | + +Every pinned SHA matches its version comment. No action is more than one major version behind. + +Aside: the default toolchain is 1.99.1, and stable is now 1.100.0. + +## Network +No call was blocked by the proxy. The npmjs.com website pages returned 403, which looked like the site's bot protection rather than the proxy. The registry API worked. diff --git a/scripts/scaffold-check.ts b/scripts/scaffold-check.ts index 510ac7c..5f4b4f6 100644 --- a/scripts/scaffold-check.ts +++ b/scripts/scaffold-check.ts @@ -2,14 +2,19 @@ /** * Dev loop for template work, independent of the interactive CLI: * - * node scripts/scaffold-check.mjs [--out DIR] [--set key.path=value ...] [--gate none|check|clippy|full] + * node scripts/scaffold-check.mjs [--name NAME] [--out DIR] [--set key.path=value ...] + * [--gate none|fmt|check|clippy|doc|full] * * Scaffolds the preset into DIR (default .scratch/), then runs the gate: + * none → scaffold only (and the unrendered-token check) + * fmt → cargo fmt --check (no build, seconds) * check → cargo check --all-targets * clippy → cargo fmt --check + cargo clippy --all-targets --all-features -- -D warnings + * doc → cargo doc --no-deps with RUSTDOCFLAGS=-D warnings (not part of full) * full → clippy + cargo test --all-features (default) - * Exits non-zero on the first failure. Uses a shared CARGO_TARGET_DIR (.scratch/target) so - * repeated runs are fast. + * `--name` sets the project name (default demo-); `--set` splits on the first `=`, so + * values may contain `=`. Exits non-zero on the first failure. Uses CARGO_TARGET_DIR when it is + * set, else a shared .scratch/target, so repeated runs are fast. */ import { spawnSync } from 'node:child_process'; import { rm } from 'node:fs/promises'; @@ -20,27 +25,32 @@ import { buildPlan } from '../src/engine/plan.ts'; import { writePlan } from '../src/engine/write.ts'; import type { PartialAnswers, PlanEntry } from '../src/types.ts'; -const args = process.argv.slice(2); -const preset = args.find((a: string) => !a.startsWith('--') && !args[args.indexOf(a) - 1]?.startsWith('--')); -if (!preset) { - console.error('usage: scaffold-check.mjs [--out DIR] [--set a.b=v] [--gate none|check|clippy|full]'); - process.exit(2); +export const GATES = ['none', 'fmt', 'check', 'clippy', 'doc', 'full'] as const; +export type Gate = (typeof GATES)[number]; + +export interface CheckArgs { + preset: string; + gate: Gate; + out: string | undefined; + overrides: Record; } -/** @param {string} f */ -const opt = (f: string) => { const i = args.indexOf(f); return i >= 0 ? args[i + 1] : undefined; }; -const gate = opt('--gate') ?? 'full'; -const root = resolve(import.meta.dirname, '..'); -const out = resolve(opt('--out') ?? join(root, '.scratch', preset)); -/** @type {any} */ -const overrides: Record = { name: `demo-${preset}`.replace(/[^a-z0-9-]/g, '-') }; -for (let i = 0; i < args.length; i++) { - if (args[i] !== '--set') continue; - const [path, raw] = (args[i + 1] ?? '').split('='); +const USAGE = + 'usage: scaffold-check.mjs [--name NAME] [--out DIR] [--set a.b=v] [--gate none|fmt|check|clippy|doc|full]'; + +/** `key.path=value` → [['key', 'path'], value]; only the first `=` separates key from value. */ +export function parseSet(spec: string): [string[], string | boolean] { + const eq = spec.indexOf('='); + const path = eq < 0 ? spec : spec.slice(0, eq); + const raw = eq < 0 ? '' : spec.slice(eq + 1); if (!path) throw new Error('--set requires a key'); const value = raw === 'true' ? true : raw === 'false' ? false : raw; - const keys = path.split('.'); - let o = overrides; + return [path.split('.'), value]; +} + +/** Sets `value` at `keys` inside `target`, creating intermediate objects. */ +function assign(target: Record, keys: string[], value: unknown) { + let o = target; for (const k of keys.slice(0, -1)) { const next = o[k]; if (!next || typeof next !== 'object') o[k] = {}; @@ -50,30 +60,97 @@ for (let i = 0; i < args.length; i++) { if (last !== undefined) o[last] = value; } -const ctx = buildContext(resolveAnswers(preset, overrides as PartialAnswers)); -const plan = await buildPlan(ctx); -await rm(out, { recursive: true, force: true }); -await writePlan(plan, out, { force: true }); -console.log(`scaffolded ${plan.length} files → ${out}`); +/** Parses the command line (without `node` and the script path). Throws with a usage message. */ +export function parseArgs(argv: readonly string[]): CheckArgs { + let preset: string | undefined; + let gate: string = 'full'; + let out: string | undefined; + let name: string | undefined; + const sets: string[] = []; + for (let i = 0; i < argv.length; i++) { + const a = argv[i] ?? ''; + if (a === '--gate' || a === '--out' || a === '--set' || a === '--name') { + const v = argv[++i]; + if (v === undefined) throw new Error(`${a} needs a value\n${USAGE}`); + if (a === '--gate') gate = v; + else if (a === '--out') out = v; + else if (a === '--name') name = v; + else sets.push(v); + } else if (a.startsWith('--')) throw new Error(`unknown option ${a}\n${USAGE}`); + else if (preset === undefined) preset = a; + else throw new Error(`unexpected argument ${a}\n${USAGE}`); + } + if (!preset) throw new Error(USAGE); + if (!(GATES as readonly string[]).includes(gate)) throw new Error(`unknown gate ${gate}\n${USAGE}`); + const overrides: Record = { name: `demo-${preset}`.replace(/[^a-z0-9-]/g, '-') }; + for (const spec of sets) { + const [keys, value] = parseSet(spec); + assign(overrides, keys, value); + } + if (name !== undefined) overrides.name = name; + return { preset, gate: gate as Gate, out, overrides }; +} -const leftovers = plan.filter((e: PlanEntry) => 'content' in e && /@@[A-Za-z]+@@|^\s*(\/\/|#)\s*@(if|end|else|elif)\b/m.test(e.content)); -if (leftovers.length) { - console.error('unrendered tokens/directives in:', leftovers.map((e: PlanEntry) => e.dest).join(', ')); - process.exit(1); +/** The cargo invocations a gate runs, in order. */ +export function gateCommands(gate: Gate): string[][] { + const fmt = ['fmt', '--all', '--', '--check']; + const clippy = ['clippy', '--all-targets', '--all-features', '--', '-D', 'warnings']; + switch (gate) { + case 'none': return []; + case 'fmt': return [fmt]; + case 'check': return [['check', '--all-targets']]; + case 'clippy': return [fmt, clippy]; + case 'doc': return [['doc', '--no-deps']]; + case 'full': return [fmt, clippy, ['test', '--all-features']]; + } } -if (gate === 'none') process.exit(0); -const env = { ...process.env, CARGO_TARGET_DIR: join(root, '.scratch', 'target'), CARGO_TERM_COLOR: 'always' }; -/** @param {string[]} cmd */ -const run = (cmd: string[]) => { - console.log(`\n$ cargo ${cmd.join(' ')}`); - const r = spawnSync('cargo', cmd, { cwd: out, stdio: 'inherit', env }); - if (r.status !== 0) { console.error(`\nFAILED: cargo ${cmd.join(' ')} (preset ${preset})`); process.exit(r.status ?? 1); } -}; -if (gate === 'check') run(['check', '--all-targets']); -else { - run(['fmt', '--all', '--', '--check']); - run(['clippy', '--all-targets', '--all-features', '--', '-D', 'warnings']); - if (gate === 'full') run(['test', '--all-features']); +/** Environment for the cargo runs: an existing CARGO_TARGET_DIR is kept. */ +export function cargoEnv(base: NodeJS.ProcessEnv, root: string, gate: Gate): NodeJS.ProcessEnv { + const env: NodeJS.ProcessEnv = { + ...base, + CARGO_TARGET_DIR: base.CARGO_TARGET_DIR || join(root, '.scratch', 'target'), + CARGO_TERM_COLOR: 'always', + }; + if (gate === 'doc') env.RUSTDOCFLAGS = [base.RUSTDOCFLAGS, '-D warnings'].filter(Boolean).join(' '); + return env; } -console.log(`\nOK ${preset} (${gate})`); + +async function main() { + let parsed: CheckArgs; + try { + parsed = parseArgs(process.argv.slice(2)); + } catch (e) { + console.error(e instanceof Error ? e.message : String(e)); + process.exit(2); + } + const { preset, gate, overrides } = parsed; + const root = resolve(import.meta.dirname, '..'); + const out = resolve(parsed.out ?? join(root, '.scratch', preset)); + + const ctx = buildContext(resolveAnswers(preset, overrides as PartialAnswers)); + const plan = await buildPlan(ctx); + await rm(out, { recursive: true, force: true }); + await writePlan(plan, out, { force: true }); + console.log(`scaffolded ${plan.length} files → ${out}`); + + const leftovers = plan.filter((e: PlanEntry) => 'content' in e && /@@[A-Za-z]+@@|^\s*(\/\/|#)\s*@(if|end|else|elif)\b/m.test(e.content)); + if (leftovers.length) { + console.error('unrendered tokens/directives in:', leftovers.map((e: PlanEntry) => e.dest).join(', ')); + process.exit(1); + } + + const env = cargoEnv(process.env, root, gate); + for (const cmd of gateCommands(gate)) { + console.log(`\n$ cargo ${cmd.join(' ')}`); + const r = spawnSync('cargo', cmd, { cwd: out, stdio: 'inherit', env }); + if (r.status !== 0) { + console.error(`\nFAILED: cargo ${cmd.join(' ')} (preset ${preset})`); + process.exit(r.status ?? 1); + } + } + console.log(`\nOK ${preset} (${gate})`); +} + +// Run when executed (directly or through scaffold-check.mjs), not when a test imports it. +if (/scaffold-check\.(?:ts|mjs|js)$/.test(process.argv[1] ?? '')) await main(); diff --git a/src/args.ts b/src/args.ts index 9114f09..6f04a50 100644 --- a/src/args.ts +++ b/src/args.ts @@ -217,7 +217,8 @@ export async function renderHelp(caps: unknown) { ' --no-cargo-check Skip cargo check', ' --open code | cursor (default: none)', ' --dry-run Show planned files; write nothing and skip post-steps', - ' --json Emit only { answers, files } JSON; no prompts', + ' --json Emit only { answers, files } JSON; no prompts. Still writes the', + ' files unless --dry-run, but skips fetch, git, cargo check and open', ' --no-color Plain terminal output', ' --quiet Suppress banner, progress and summary', ' --force Allow writing into a nonempty directory', diff --git a/src/cli.ts b/src/cli.ts index c8cbc55..c4a5513 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -2,12 +2,13 @@ import type { Answers, Caps } from './types.ts'; type Node = Map; /** main(argv): args → answers → ctx → plan → write → post → summary. */ import { readFile } from 'node:fs/promises'; -import { basename, resolve, relative } from 'node:path'; +import { basename, resolve } from 'node:path'; +import { shownTarget } from './reproduce.ts'; import { parseArgv, optionalUi, renderHelp } from './args.ts'; -import { resolveAnswers } from './presets.ts'; -import { buildContext, effectiveAnswers, validateName } from './context.ts'; +import { DEFAULTS, resolveAnswers } from './presets.ts'; +import { buildContext, effectiveAnswers, ignoredOptions, reportedAnswers, validateName, validateRustVersions } from './context.ts'; import { buildPlan } from './engine/plan.ts'; -import { targetProblem, writePlan } from './engine/write.ts'; +import { existingFiles, targetProblem, writePlan } from './engine/write.ts'; import { initRepo } from './post/git.ts'; import { cargoCheck } from './post/cargo.ts'; import { openEditor } from './post/open.ts'; @@ -78,9 +79,23 @@ export function nextCommands(a: Answers, shown: string): [string, string][] { return out; } +/** The crate name a positional folder supplies when no `--name` is given: its basename, if valid. */ +export function nameFromFolder(dir: string): string | null { + const base = basename(resolve(dir)); + return validateName(base) ? null : base; +} + +/** The one-line `--force` report: how many existing files were overwritten, and which. */ +export function overwriteNotice(files: string[], max = 20): string { + const shown = files.slice(0, max).join(', '); + const more = files.length > max ? `, and ${files.length - max} more` : ''; + return `--force overwrote ${files.length} existing file${files.length === 1 ? '' : 's'}: ${shown}${more}`; +} + /** Interactive run: ticked steps with timings, then the next-steps box and a sign-off. */ -async function runInteractive({ caps, answers, plan, target, shown, force }: { +async function runInteractive({ caps, answers, plan, target, shown, force, overwrites, notice }: { caps: Caps; answers: Answers; plan: PlanEntry[]; target: string; shown: string; force: boolean; + overwrites: string[]; notice: (s: string) => void; }) { const { dim, paint } = await import('./ui/rainbow.ts'); const { box, cancel, log, outro, tasks } = await import('./ui/rail.ts'); @@ -106,25 +121,29 @@ async function runInteractive({ caps, answers, plan, target, shown, force }: { : { ok, message: ok ? `${label} done` : `${label} failed ${dim(caps, '(run it in the project for details)')}` }; }; + let wrote = false; const finished = await tasks(caps, [ { title: `Writing ${plan.length} files`, required: true, run: async (update) => { await writePlan(plan, target, { force, onFile: (dest, i, n) => update(`${String(i).padStart(String(n).length)}/${n} ${dest}`) }); - return { ok: true, message: `Wrote ${plan.length} files to ${shown}` }; + wrote = true; + return { ok: true, message: `Wrote ${plan.length} files to ${shown}${overwrites.length ? `${g.sep}overwrote ${overwrites.length}` : ''}` }; }, }, // Fetch first: it writes Cargo.lock, which belongs in the first commit (#11). { title: 'cargo fetch', enabled: answers.post.fetch, run: cargoTask('cargo fetch', cargoFetch) }, { title: 'git init', enabled: answers.post.git, run: async () => { - const r = initRepo(target, answers); + const r = initRepo(target, answers, plan.map((e) => e.dest)); return r.ok === true - ? { ok: true, message: `Initialised git${g.sep}first commit on main` } + ? { ok: true, message: r.initialised ? `Initialised git${g.sep}first commit on ${r.branch}` : `First commit on ${r.branch} in the existing repository` } : { ok: r.ok, message: `git ${r.ok === false ? 'failed' : 'skipped'} ${dim(caps, `(${r.reason ?? ''})`)}` }; }, }, { title: 'cargo check', enabled: answers.post.cargoCheck, run: cargoTask('cargo check', cargoCheck) }, - ]); + ], { interrupted: `Interrupted. The partly created folder ${shown} was left in place.` }); + // After the task rail, so the list doesn't tear through its live lines. + if (wrote && overwrites.length) notice(overwriteNotice(overwrites)); if (!finished) { cancel(caps, 'Stopped: nothing after the failed step ran.'); return false; @@ -135,7 +154,7 @@ async function runInteractive({ caps, answers, plan, target, shown, force }: { const pad = Math.max(...cmds.map(([c]) => c.length)) + 3; // The notes are the first thing to go when the box would not fit the terminal. box(caps, 'next', cmds.map(([c, note]) => (note ? `${c.padEnd(pad)}${dim(caps, `# ${note}`)}` : c)), cmds.map(([c]) => c)); - log(caps, [dim(caps, 'again without prompts:'), dim(caps, reproduceCommand(answers, shown === '.' ? '.' : undefined))]); + log(caps, [dim(caps, 'again without prompts:'), dim(caps, reproduceCommand(answers, shown))]); await outro(caps, 'build something luminous'); return true; } @@ -185,13 +204,23 @@ export async function main(argv: string[]) { const interactive = !flags.yes && !json && Boolean(process.stdin.isTTY) && Boolean(process.stdout.isTTY); /** @param {string} s */ const log = (s: string) => { if (!quiet) console.log(s); }; + // One-line notices go to stderr so --json stays pure; only --quiet silences them. + const notice = (s: string) => { if (!flags.quiet) console.error(`note: ${s}`); }; // A positional dir with no --name supplies the name when it is a valid crate name. if (dir && overrides.name === undefined) { const base = basename(resolve(dir)); - if (!validateName(base)) overrides.name = base; + const fromFolder = nameFromFolder(dir); + if (fromFolder) overrides.name = fromFolder; + // Otherwise the default name applies; the prompt asks for one, a scripted run says so. + else if (!interactive) notice(`the folder name "${base}" can't be a crate name, so the crate is named "${DEFAULTS.name}" (set it with --name).`); } + // Fail before asking anything on Rust versions the flags already contradict (exit 2). + const early = resolveAnswers(overrides.preset, overrides); + const earlyVersions = validateRustVersions(early.msrv, early.toolchain, early.edition); + if (earlyVersions) throw new Exit(2, earlyVersions); + // Fail before asking anything: a folder we can't write into shouldn't cost the user a walkthrough. const writes = !flags['dry-run'] && !flags.force; const knownTarget = dir ?? overrides.name; @@ -211,22 +240,33 @@ export async function main(argv: string[]) { if (interactive) { const { ask } = await import('./prompts.ts'); // With no directory given the target is ./, so the name prompt checks that folder. - answers = await ask(overrides, caps, writes && !dir ? (name) => targetProblem(resolve(name)) : () => null); + answers = await ask(overrides, caps, writes && !dir ? (name) => targetProblem(resolve(name)) : () => null, dir); } else { answers = resolveAnswers(overrides.preset, overrides); } + // Cross-field checks, after flags, --set and preset defaults have all applied. + const versionProblem = validateRustVersions(answers.msrv, answers.toolchain, answers.edition); + if (versionProblem) throw new Exit(2, versionProblem); + // Explicit options this kind never generates are dropped, not errors; a scripted run says so. + if (!interactive) for (const line of ignoredOptions(overrides, answers)) notice(line); const ctx = buildContext(answers); const plan = await buildPlan(ctx); const dests = plan.map((e: PlanEntry) => e.dest); const target = resolve(dir ?? answers.name); - const rel = relative(process.cwd(), target); - const shown = rel.startsWith('..') ? target : rel || '.'; + // The real target folder, as the finish screen and the recreate command name it (B9). + const shown = shownTarget(dir, answers.name); + // Files --force is about to replace, reported once the write succeeds. + const overwrites = flags.force && !flags['dry-run'] ? existingFiles(plan, target) : []; + const reportOverwrites = () => { if (overwrites.length) notice(overwriteNotice(overwrites)); }; if (json) { - if (!flags['dry-run']) await writePlan(plan, target, { force: Boolean(flags.force) }); - // Report what was generated: options this kind never uses read false (#6). - console.log(JSON.stringify({ answers: effectiveAnswers(answers), files: dests }, null, 2)); + if (!flags['dry-run']) { + await writePlan(plan, target, { force: Boolean(flags.force) }); + reportOverwrites(); + } + // Report what was generated: options this kind never uses read false (#6), and no GUI stack. + console.log(JSON.stringify({ answers: reportedAnswers(answers), files: dests }, null, 2)); return 0; } if (flags['dry-run']) { @@ -237,10 +277,11 @@ export async function main(argv: string[]) { if (interactive) { // The review screen already confirmed; this is the run + finish. - return (await runInteractive({ caps, answers, plan, target, shown, force: Boolean(flags.force) })) ? 0 : 1; + return (await runInteractive({ caps, answers, plan, target, shown, force: Boolean(flags.force), overwrites, notice })) ? 0 : 1; } await writePlan(plan, target, { force: Boolean(flags.force) }); + reportOverwrites(); // Post-steps. const spinMod = await optionalUi('spinner'); @@ -266,11 +307,15 @@ export async function main(argv: string[]) { } /** @type {boolean | undefined} */ let gitDone: boolean | undefined; + // Whether "git init + first commit" in the summary below is what happened. + let gitInitialised = false; if (answers.post.git) { - const r = initRepo(target, answers); + const r = initRepo(target, answers, dests); gitDone = r.ok === true; + gitInitialised = r.ok === true && r.initialised === true; if (r.ok === false) log(`warning: ${r.reason}`); else if (r.ok === null) log(`git skipped: ${r.reason}`); + else if (!r.initialised) log(`git: first commit on ${r.branch} in the existing repository`); } /** @type {boolean | null} */ let cargoChecked: boolean | null = null; @@ -292,7 +337,8 @@ export async function main(argv: string[]) { // Same words as the interactive review, without prompts or a file dump (--dry-run lists files). const { reviewLines } = await import('./prompts.ts'); const { dim } = await import('./ui/rainbow.ts'); - const { title, body } = reviewLines(caps, answers); + // The summary reports what ran: no "git init" line when git was skipped or the repo existed. + const { title, body } = reviewLines(caps, { ...answers, post: { ...answers.post, git: gitInitialised } }); const ok = (await import('./ui/glyphs.ts')).glyphs(caps).ok; const checks = [gitDone && 'git', cargoChecked === true && 'cargo check'].filter(Boolean).join(' · '); console.log(`\n${ok} ${title} ${dim(caps, `${dests.length} files${checks ? ` · ${checks}` : ''}`)}\n`); diff --git a/src/context.ts b/src/context.ts index c81e64f..2ed30ca 100644 --- a/src/context.ts +++ b/src/context.ts @@ -1,25 +1,95 @@ -import type { Answers, Ctx, TokenKey } from './types.ts'; +import type { Answers, Ctx, PartialAnswers, ReportedAnswers, TokenKey } from './types.ts'; import { DEFAULT_BASE, shippedTheme } from './gen/themes.ts'; /** Answers → Ctx (see docs/CONTRACTS.md). */ export const NAME_RE = /^[a-z][a-z0-9-]*$/; +/** crates.io refuses longer package names; the binary name gets the same cap. */ +export const MAX_NAME_LENGTH = 64; + +/** + * Rust keywords from the Reference (strict and reserved, every edition through 2024). A crate + * name is a Rust identifier once dashes become underscores, so none of these can be one; Cargo + * refuses them too. Weak keywords (`union`, `macro_rules`, `raw`, `safe`) are ordinary identifiers. + */ +export const RUST_KEYWORDS: readonly string[] = [ + // strict, 2015 + 'as', 'break', 'const', 'continue', 'crate', 'else', 'enum', 'extern', 'false', 'fn', 'for', 'if', + 'impl', 'in', 'let', 'loop', 'match', 'mod', 'move', 'mut', 'pub', 'ref', 'return', 'self', + 'static', 'struct', 'super', 'trait', 'true', 'type', 'unsafe', 'use', 'where', 'while', + // strict, 2018+ + 'async', 'await', 'dyn', + // reserved, 2015 + 'abstract', 'become', 'box', 'do', 'final', 'macro', 'override', 'priv', 'typeof', 'unsized', + 'virtual', 'yield', + // reserved, 2018+ and 2024+ + 'try', 'gen', +]; + +/** Crates every program already has in scope: a crate of the same name shadows them. */ +const BUILTIN_CRATES: readonly string[] = ['test', 'core', 'std', 'alloc', 'proc-macro']; + +/** Cargo refuses these as package and target names: they collide with directories under target/. */ +export const CARGO_RESERVED: readonly string[] = ['deps', 'examples', 'build', 'incremental']; + +/** Every project builds a Windows .exe, and Windows treats these as devices, not files. */ +export const WINDOWS_DEVICE_RE = /^(con|prn|aux|nul|com\d|lpt\d)$/; + +const tooLong = (name: string) => + `Use at most ${MAX_NAME_LENGTH} characters (the crates.io limit); this one has ${name.length}.`; + +/** Rules a crate name and a binary name share: Cargo's reserved names and Windows device names. */ +function reservedProblem(name: string): string | null { + if (CARGO_RESERVED.includes(name)) return `"${name}" is reserved by Cargo.`; + if (WINDOWS_DEVICE_RE.test(name)) return `"${name}" is a reserved device name on Windows.`; + return null; +} + /** @param {string} name */ export function validateName(name: string) { + if (name.length > MAX_NAME_LENGTH) return tooLong(name); if (!NAME_RE.test(name)) return 'Use lowercase letters, digits, and dashes, starting with a letter.'; if (name.endsWith('-') || name.includes('--')) return 'No trailing or doubled dashes.'; - if (['test', 'core', 'std', 'alloc', 'proc-macro', 'self', 'crate', 'super'].includes(name)) - return `"${name}" is reserved in Rust.`; - return null; + if (BUILTIN_CRATES.includes(name)) return `"${name}" is reserved in Rust.`; + if (RUST_KEYWORDS.includes(name)) return `"${name}" is a Rust keyword, so it can't name a crate.`; + return reservedProblem(name); } /** A binary name: what users type, so the same rules as a crate name plus underscores. */ export function validateBin(bin: string) { + if (bin.length > MAX_NAME_LENGTH) return tooLong(bin); if (!/^[a-z][a-z0-9_-]*$/.test(bin)) return 'Use lowercase letters, digits, dashes and underscores, starting with a letter.'; - // Cargo refuses these as target names: they collide with directories under target/. - if (['deps', 'examples', 'build', 'incremental'].includes(bin)) return `"${bin}" is reserved by Cargo.`; - // Every project builds a Windows .exe, and Windows treats these as devices, not files. - if (/^(con|prn|aux|nul|com\d|lpt\d)$/.test(bin)) return `"${bin}" is a reserved device name on Windows.`; + return reservedProblem(bin); +} + +/** The first Rust release that accepts each edition (2021: 1.56.0, 2024: 1.85.0). */ +export const EDITION_MIN_RUST: Record = { 2021: '1.56', 2024: '1.85' }; + +/** `1.98` / `1.99.1` → [1, 98, 0] / [1, 99, 1]; null when it isn't a Rust version number. */ +function versionParts(v: string): number[] | null { + if (!/^\d+\.\d+(?:\.\d+)?$/.test(v)) return null; + const parts = v.split('.').map(Number); + return parts.length === 2 ? [...parts, 0] : parts; +} + +function compareVersions(a: number[], b: number[]): number { + for (let i = 0; i < 3; i++) if ((a[i] ?? 0) !== (b[i] ?? 0)) return (a[i] ?? 0) - (b[i] ?? 0); + return 0; +} + +/** + * Cross-field check of the Rust versions: the pinned toolchain must be able to build the crate + * (`msrv` ≤ `toolchain`) and the MSRV must know the edition. Returns the problem, or null. + */ +export function validateRustVersions(msrv: string, toolchain: string, edition: Answers['edition']): string | null { + const m = versionParts(msrv); + const t = versionParts(toolchain); + if (!m) return `msrv "${msrv}" is not a Rust version number, such as 1.98.`; + if (!t) return `toolchain "${toolchain}" is not a Rust version number, such as 1.99.1.`; + const needed = EDITION_MIN_RUST[edition]; + const n = versionParts(needed); + if (n && compareVersions(m, n) < 0) return `edition ${edition} needs Rust ${needed} or newer, but msrv is ${msrv}. Raise --msrv or pick another --edition.`; + if (compareVersions(m, t) > 0) return `msrv ${msrv} is newer than toolchain ${toolchain}, so the pinned toolchain can't build the crate. Lower --msrv or raise --toolchain.`; return null; } @@ -66,6 +136,44 @@ export function effectiveAnswers(a: Answers): Answers { return out; } +/** + * What `--json` reports: the effective answers, with `guiStack` blanked like `themeBase` for kinds + * without a GUI. The Ctx keeps a stack value (no flag reads it without a GUI), so files don't change. + */ +export function reportedAnswers(a: Answers): ReportedAnswers { + const out: ReportedAnswers = effectiveAnswers(a); + if (!(a.kind === 'gui' || a.kind === 'workspace')) out.guiStack = ''; + return out; +} + +const KIND_WORDS: Record = { + cli: 'a command-line tool', gui: 'a desktop app', tui: 'a terminal UI', lib: 'a library', workspace: 'a desktop workspace', +}; + +/** + * Options the user set explicitly (`overrides`: flags and `--set`) that the chosen kind never + * generates, one human sentence each, e.g. `tray is ignored: a library has no desktop window.` + * Only options turned on, or given a value, count; asking for `false` is never ignored. + */ +export function ignoredOptions(overrides: PartialAnswers, answers: Answers): string[] { + const eff = effectiveAnswers(answers); + const hasGui = answers.kind === 'gui' || answers.kind === 'workspace'; + const kind = KIND_WORDS[answers.kind]; + const out: string[] = []; + if (overrides.guiStack !== undefined && !hasGui) out.push(`--gui ${overrides.guiStack} is ignored: ${kind} has no desktop window.`); + if (overrides.themeBase !== undefined && !hasGui) out.push(`--base ${overrides.themeBase} is ignored: ${kind} has no desktop window.`); + if (overrides.bin && answers.kind === 'lib') out.push(`--bin ${overrides.bin} is ignored: a library has no executable.`); + for (const [k, v] of Object.entries(overrides.features ?? {}) as [keyof Answers['features'], boolean][]) { + if (v !== true || eff.features[k]) continue; + let why = `${kind} has no desktop window`; + if (k === 'config') why = answers.kind === 'cli' ? 'a command-line tool reads a config file only with serde' : `${kind} ships no config file`; + if (k === 'subcommands') why = answers.kind === 'cli' || hasGui ? 'subcommands need clap (--with clap)' : `${kind} has no command line to add them to`; + out.push(`${k} is ignored: ${why}.`); + } + if (overrides.tooling?.unsafeCheck === true && !eff.tooling.unsafeCheck) out.push(`unsafeCheck is ignored: only the desktop kinds have an unsafe boundary to check.`); + return out; +} + /** * @param {any} raw Answers */ @@ -105,6 +213,8 @@ export function buildContext(raw: Answers): Ctx { } const appCrate = workspace ? `${a.name}-app` : a.name; + // Resolved once so Cargo.toml, README and doc comments agree: an empty tagline reads as the name. + const tagline = a.tagline.trim() ? a.tagline : a.name; const year = String(new Date().getFullYear()); /** @type {Record} */ const tokens: Record = { @@ -118,7 +228,7 @@ export function buildContext(raw: Answers): Ctx { appCrate, appCrateSnake: toSnake(appCrate), displayName: a.displayName || toPascal(a.name), - tagline: a.tagline || '', + tagline, author: a.author || '', github: a.github || '', email: a.email || '', @@ -147,6 +257,7 @@ export function buildContext(raw: Answers): Ctx { return { ...a, + tagline, crate: tokens.crate, Name: tokens.Name, NAME: tokens.NAME, diff --git a/src/engine/write.ts b/src/engine/write.ts index ddc3df6..9a06226 100644 --- a/src/engine/write.ts +++ b/src/engine/write.ts @@ -1,5 +1,5 @@ -import { mkdir, readdir, writeFile, copyFile } from 'node:fs/promises'; -import { existsSync, readdirSync } from 'node:fs'; +import { mkdir, readdir, writeFile, copyFile, rm } from 'node:fs/promises'; +import { existsSync, readdirSync, statSync } from 'node:fs'; import { dirname, join } from 'node:path'; /** Why `dir` can't be scaffolded into, or null if it can. A lone `.git` doesn't count as content. */ @@ -18,11 +18,24 @@ export async function isEmptyDir(dir: string) { return entries.filter((e: unknown) => e !== '.git').length === 0; } +/** The plan's dests that already exist as files under `target`: what `--force` would overwrite. */ +export function existingFiles(plan: PlanEntry[], target: string): string[] { + return plan.map((e) => e.dest).filter((dest) => { + try { return statSync(join(target, ...dest.split('/'))).isFile(); } catch { return false; } + }); +} + +const plural = (n: number, word: string) => `${n} ${word}${n === 1 ? '' : 's'}`; + /** * @param {import('./plan.ts').PlanEntry[]} plan * @param {string} target * @param {{ force?: boolean, dryRun?: boolean }} [opts] * @returns {Promise} dests written (or that would be) + * + * If a write fails, what this run made is removed before the error is thrown: the whole target + * when this run created it, otherwise only the files and folders it added (files it had already + * overwritten under --force can't be restored, and the error says how many). The error says which. */ export async function writePlan(plan: PlanEntry[], target: string, opts: { force?: boolean; dryRun?: boolean; onFile?: (dest: string, i: number, n: number) => void } | undefined = {}) { const dests = plan.map((e: PlanEntry) => e.dest); @@ -30,12 +43,46 @@ export async function writePlan(plan: PlanEntry[], target: string, opts: { force if (!opts.force && !(await isEmptyDir(target))) { throw new Error(`${target} is not empty. Pick another directory or pass --force.`); } - for (const [i, e] of plan.entries()) { - opts.onFile?.(e.dest, i + 1, plan.length); - const out = join(target, ...e.dest.split('/')); - await mkdir(dirname(out), { recursive: true }); - if ('copyFrom' in e) await copyFile(e.copyFrom, out); - else await writeFile(out, e.content.endsWith('\n') ? e.content : e.content + '\n'); + const targetExisted = existsSync(target); + /** The topmost folder this run created for the target itself (it may include missing parents). */ + let createdRoot: string | undefined; + if (!targetExisted) createdRoot = await mkdir(target, { recursive: true }); + const createdDirs: string[] = []; + const createdFiles: string[] = []; + let overwritten = 0; + let current = ''; + try { + for (const [i, e] of plan.entries()) { + current = e.dest; + opts.onFile?.(e.dest, i + 1, plan.length); + const out = join(target, ...e.dest.split('/')); + const made = await mkdir(dirname(out), { recursive: true }); + if (made) createdDirs.push(made); + const existed = existsSync(out); + if ('copyFrom' in e) await copyFile(e.copyFrom, out); + else await writeFile(out, e.content.endsWith('\n') ? e.content : e.content + '\n'); + if (existed) overwritten++; + else createdFiles.push(out); + } + } catch (error) { + const why = error instanceof Error ? error.message : String(error); + let cleanup: string; + try { + if (createdRoot) { + await rm(createdRoot, { recursive: true, force: true, maxRetries: 3 }); + cleanup = `Removed ${createdRoot}, which this run created.`; + } else { + // Folders first (everything under one was made by this run), then files elsewhere. + for (const dir of createdDirs.reverse()) await rm(dir, { recursive: true, force: true, maxRetries: 3 }); + for (const file of createdFiles) await rm(file, { force: true }); + cleanup = `Removed the ${plural(createdFiles.length, 'file')} this run created in ${target}; files that were there before are kept` + + (overwritten ? `, but ${plural(overwritten, 'existing file')} had already been overwritten.` : '.'); + } + } catch (cleanupError) { + const detail = cleanupError instanceof Error ? cleanupError.message : String(cleanupError); + cleanup = `Cleaning up failed too (${detail}); check ${createdRoot ?? target} by hand.`; + } + throw new Error(`Writing ${current} failed: ${why}. ${cleanup}`, { cause: error }); } return dests; } diff --git a/src/gen/cargo.ts b/src/gen/cargo.ts index 63c6ea1..1d0f9d4 100644 --- a/src/gen/cargo.ts +++ b/src/gen/cargo.ts @@ -127,7 +127,7 @@ export function singleManifest(ctx: Ctx, deps: Dep[]) { 'version = "0.1.0"', `edition = ${q(ctx.edition)}`, `rust-version = ${q(ctx.msrv)}`, - `description = ${q(ctx.tagline || ctx.name)}`, + `description = ${q(ctx.tagline)}`, `authors = ${authors(ctx)}`, licenseLines(ctx), repoUrl(ctx) && `repository = ${q(repoUrl(ctx))}`, @@ -210,7 +210,7 @@ workspace = true return [ { dest: 'Cargo.toml', content: root }, - { dest: `crates/${ctx.appCrate}/Cargo.toml`, content: member(ctx.appCrate, ctx.tagline || ctx.name, deps.filter((d: Dep) => (d.crate ?? 'app') === 'app')) }, + { dest: `crates/${ctx.appCrate}/Cargo.toml`, content: member(ctx.appCrate, ctx.tagline, deps.filter((d: Dep) => (d.crate ?? 'app') === 'app')) }, { dest: 'crates/xtask/Cargo.toml', content: member('xtask', `Project automation for ${ctx.name}: \`cargo xtask \`.`, deps.filter((d: Dep) => d.crate === 'xtask')) }, ]; } diff --git a/src/post/git.ts b/src/post/git.ts index b244824..b46eea4 100644 --- a/src/post/git.ts +++ b/src/post/git.ts @@ -1,8 +1,11 @@ /** Post-step: `git init -b main` + initial commit. */ import { spawnSync } from 'node:child_process'; +import { existsSync } from 'node:fs'; +import { join } from 'node:path'; /** @param {string[]} args @param {string} cwd */ -const git = (args: string[], cwd: string) => spawnSync('git', args, { cwd, encoding: 'utf8', windowsHide: true }); +const git = (args: string[], cwd: string, input?: string) => + spawnSync('git', args, { cwd, encoding: 'utf8', windowsHide: true, ...(input === undefined ? {} : { input }) }); /** True when the git executable is on PATH. */ export function hasGit() { @@ -17,14 +20,40 @@ export function insideRepo(dir: string) { } /** - * Initialise a repository and commit the scaffold. + * What the git step will do in `dir` (which must exist): `init` a new repository, `commit` into a + * repository whose root is `dir` and that has no commits yet (a fresh `git init`), or `skip` + * because `dir` is inside some other repository, or git is missing. + */ +export function repoState(dir: string): { action: 'init' | 'commit' } | { action: 'skip'; reason: string } { + if (!hasGit()) return { action: 'skip', reason: 'git not found on PATH' }; + if (!insideRepo(dir)) return { action: 'init' }; + const atRoot = git(['rev-parse', '--show-cdup'], dir); + const hasCommits = git(['rev-parse', '--verify', '-q', 'HEAD'], dir).status === 0; + if (atRoot.status === 0 && atRoot.stdout.trim() === '' && !hasCommits) return { action: 'commit' }; + return { action: 'skip', reason: 'already inside a git repository' }; +} + +export interface GitResult { + /** true = committed, false = a git command failed, null = skipped. */ + ok: boolean | null; + reason?: string; + /** Whether this run created the repository (false: it committed into a fresh, empty one). */ + initialised?: boolean; + /** The branch the first commit landed on. */ + branch?: string; +} + +/** + * Initialise a repository and commit the scaffold. In a fresh repository whose root is `dir` (only + * `git init` so far) it skips `init` and commits just the generated `files` (plus `Cargo.lock` once + * fetched), staged by path, so nothing else in the folder is swept into the commit. * @param {string} dir target directory (already written) - * @param {{ name: string, author?: string, email?: string, github?: string }} answers - * @returns {{ ok: boolean | null, reason?: string }} null = skipped + * @param {string[]} [files] the generated paths, POSIX-relative to `dir` */ -export function initRepo(dir: string, answers: { name: string; author?: string; email?: string; github?: string; }) { - if (!hasGit()) return { ok: null, reason: 'git not found on PATH' }; - if (insideRepo(dir)) return { ok: null, reason: 'already inside a git repository' }; +export function initRepo(dir: string, answers: { name: string; author?: string; email?: string; github?: string; }, files?: string[]): GitResult { + const state = repoState(dir); + if (state.action === 'skip') return { ok: null, reason: state.reason }; + if (state.action === 'commit' && !files) return { ok: null, reason: 'already inside a git repository' }; /** @type {string[]} */ const identity: string[] = []; if (!git(['config', 'user.name'], dir).stdout?.trim()) identity.push('-c', `user.name=${answers.author || 'create-rust-app'}`); @@ -32,17 +61,20 @@ export function initRepo(dir: string, answers: { name: string; author?: string; const email = answers.email || (answers.github ? `${answers.github}@users.noreply.github.com` : 'create-rust-app@localhost'); identity.push('-c', `user.email=${email}`); } - const steps = [ - ['init', '-q', '-b', 'main'], - ['add', '-A'], - [...identity, 'commit', '-q', '--no-verify', '-m', `feat: scaffold ${answers.name} with create-rust-app`], - ]; - for (const args of steps) { - const r = git(args, dir); + const message = `feat: scaffold ${answers.name} with create-rust-app`; + const paths = [...(files ?? []), ...(files && !files.includes('Cargo.lock') && existsSync(join(dir, 'Cargo.lock')) ? ['Cargo.lock'] : [])]; + // NUL-separated on stdin: no command-line length limit, no shell quoting. + const pathspec = ['--pathspec-from-file=-', '--pathspec-file-nul']; + const steps: [string[], string?][] = state.action === 'init' + ? [[['init', '-q', '-b', 'main']], [['add', '-A']], [[...identity, 'commit', '-q', '--no-verify', '-m', message]]] + : [[['add', ...pathspec], paths.join('\0')], [[...identity, 'commit', '-q', '--no-verify', '-m', message, ...pathspec], paths.join('\0')]]; + for (const [args, input] of steps) { + const r = git(args, dir, input); if (r.error || r.status !== 0) { const detail = (r.stderr || r.error?.message || '').trim().split('\n').pop(); return { ok: false, reason: `git ${args.filter((a: string) => a !== '-c' && !a.includes('=')).join(' ')} failed${detail ? `: ${detail}` : ''}` }; } } - return { ok: true }; + const branch = git(['symbolic-ref', '--short', 'HEAD'], dir).stdout?.trim() || 'main'; + return { ok: true, initialised: state.action === 'init', branch }; } diff --git a/src/prompts.ts b/src/prompts.ts index cd7e3b5..0966197 100644 --- a/src/prompts.ts +++ b/src/prompts.ts @@ -12,9 +12,11 @@ import { NOTE_FRAME, NOTE_TITLE_FRAME, cancel, note, text } from './ui/rail.ts'; import { glyphs } from './ui/glyphs.ts'; import { PRESETS, resolveAnswers } from './presets.ts'; import { shippedThemes } from './gen/themes.ts'; -import { effectiveAnswers, validateBin, validateName } from './context.ts'; +import path from 'node:path'; +import { effectiveAnswers, validateBin, validateName, validateRustVersions } from './context.ts'; +import { shownTarget } from './reproduce.ts'; import { dim, hex, bold } from './ui/rainbow.ts'; -import { pick, pickMany } from './ui/choose.ts'; +import { BACK, pick, pickMany } from './ui/choose.ts'; import type { Item } from './ui/choose.ts'; import { STOPS } from './ui/theme.ts'; import { clip, width, wrap } from './ui/tty.ts'; @@ -31,10 +33,10 @@ export class Cancelled extends Error { const RECOMMENDED = 'rustaman'; const PRESET_ORDER = ['rustaman', 'strobe', 'cli', 'tui', 'lib', 'minimal']; -/** Unwrap a prompt result, turning Ctrl-C / Esc into a clean cancel. */ /** Terminal caps for the running flow (set by ask), so a cancel anywhere renders consistently. */ let flowCaps: Caps | null = null; +/** Unwrap a prompt result, turning Ctrl-C / Esc into a clean cancel. */ function got(value: T): Exclude { if (isCancel(value) || typeof value === 'symbol') { if (flowCaps) cancel(flowCaps, 'Nothing written.'); @@ -43,6 +45,15 @@ function got(value: T): Exclude { return value as Exclude; } +/** Esc inside Customize: leave the current section (or the preset re-pick) without keeping its edits. */ +class Back extends Error {} + +/** Unwrap a Customize prompt: Esc (BACK) steps back a level, Ctrl-C still cancels the run. */ +function sect(value: T): Exclude { + if (value === BACK) throw new Back(); + return got(value); +} + /** Catalogue entries → choose.ts items (description as hint, catalogue group as header). */ function items(cat: Record, keys: K[], withGroups = false): Item[] { return keys.map((k) => ({ value: k, label: cat[k].label, hint: cat[k].hint, ...(withGroups ? { group: cat[k].group } : {}) })); @@ -111,8 +122,55 @@ export function reviewLines(caps: Caps, a: Answers): { title: string; body: stri return { title, body: [...top, ...rows].join('\n') }; } -/** Explicit command-line answers only; the preset's answers stay editable defaults. */ -export async function ask(partial: PartialAnswers, caps: Caps, targetCheck: (name: string) => string | null = () => null): Promise { +/** + * Answers after an explicit "Start over from a preset": the preset picked there wins over `--kind` + * and `--preset`; every other command-line answer still applies. + */ +export function startOver(partial: PartialAnswers, preset: string, name: string): Answers { + const rest: PartialAnswers = { ...partial }; + delete rest.kind; + delete rest.preset; + return resolveAnswers(preset, { ...rest, name }); +} + +/** The review's "Create it" hint: the folder the run really writes (the positional dir if given). */ +export function writesHint(dir: string | undefined, name: string, cwd?: string, p: typeof path = path): string { + const shown = shownTarget(dir, name, cwd, p); + return `writes ${p.isAbsolute(shown) || shown === '.' ? shown : `./${shown}`}`; +} + +/** + * The MSRV / toolchain / edition cross-check (validateRustVersions, shared with the flags), with its + * advice worded for the Licence + Rust prompts rather than for `--msrv` / `--edition`. Trims first. + */ +export function promptVersionProblem(msrv: string, toolchain: string, edition: Answers['edition']): string | null { + const problem = validateRustVersions(msrv.trim(), toolchain.trim(), edition); + return problem + ?.replace('Raise --msrv or pick another --edition.', 'Raise the MSRV, or press esc and pick another edition.') + .replace('Lower --msrv or raise --toolchain.', 'Raise the toolchain, or press esc and lower the MSRV.') ?? null; +} + +/** The MSRV prompt's check: shape, then the edition's minimum (the toolchain is asked next). */ +export function msrvProblem(v: string, edition: Answers['edition']): string | undefined { + const msrv = v.trim(); + if (!/^\d+\.\d+(?:\.\d+)?$/.test(msrv)) return 'Use a version like 1.98'; + // The toolchain is the next question, so here only the edition's minimum can fail: check the + // MSRV against itself as the toolchain. + return promptVersionProblem(msrv, msrv.split('.').length === 2 ? `${msrv}.0` : msrv, edition) ?? undefined; +} + +/** The toolchain prompt's check: shape, then not older than the MSRV just given. */ +export function toolchainProblem(v: string, msrv: string, edition: Answers['edition']): string | undefined { + const toolchain = v.trim(); + if (!/^\d+\.\d+\.\d+$/.test(toolchain)) return 'Use an exact version like 1.99.1'; + return promptVersionProblem(msrv, toolchain, edition) ?? undefined; +} + +/** + * Explicit command-line answers only; the preset's answers stay editable defaults. `dir` is the + * positional target folder, when one was given. + */ +export async function ask(partial: PartialAnswers, caps: Caps, targetCheck: (name: string) => string | null = () => null, dir?: string): Promise { flowCaps = caps; const given = (path: string) => path.split('.').reduce((o, k) => o && typeof o === 'object' ? (o as Record)[k] : undefined, partial) !== undefined; @@ -126,9 +184,10 @@ export async function ask(partial: PartialAnswers, caps: Caps, targetCheck: (nam })); // ── 2. what are you building ───────────────────────────────────────────── - const pickPreset = async (initial: string) => got(await pick(caps, { + const pickPreset = async (initial: string, back = false) => (back ? sect : got)(await pick(caps, { message: 'What are you building?', initialValue: initial, + back, options: (PRESET_ORDER.map((id) => ({ value: id, label: PRESETS[id]?.label ?? id, hint: PRESETS[id]?.hint ?? '', ...(id === RECOMMENDED ? { tag: 'recommended' } : {}), @@ -146,7 +205,7 @@ export async function ask(partial: PartialAnswers, caps: Caps, targetCheck: (nam message: 'Ready?', initialValue: 'create', options: ([ - { value: 'create', label: 'Create it', hint: `writes ./${a.name}` }, + { value: 'create', label: 'Create it', hint: writesHint(dir, a.name) }, { value: 'customize', label: 'Customize…', hint: 'crates, features, tooling, licence, Rust version' }, { value: 'cancel', label: 'Cancel', hint: 'nothing is written' }, ]), @@ -154,15 +213,33 @@ export async function ask(partial: PartialAnswers, caps: Caps, targetCheck: (nam if (next === 'create') return a; if (next === 'cancel') got(Symbol.for('clack:cancel')); a = await customize(caps, a, targetCheck, async () => { - preset = await pickPreset(preset ?? RECOMMENDED); - return resolveAnswers(preset, { ...partial, name: a.name }); + preset = await pickPreset(preset ?? RECOMMENDED, true); + return startOver(partial, preset, a.name); }); } } -/** One section at a time, then back to the review. */ +/** + * One section at a time, then back to the review. Esc on the menu returns to the review unchanged; + * Esc inside a section (or the preset re-pick) drops that section's edits and reopens the menu. + */ async function customize(caps: Caps, a: Answers, targetCheck: (name: string) => string | null, repick: () => Promise): Promise { - const sections: Item[] = ([ + for (;;) { + const which = await pick(caps, { message: 'Customize what?', options: menu(a), back: true }); + if (which === BACK) return a; + const choice = got(which); + if (choice === 'back') return a; + try { + return choice === 'preset' ? await repick() : await section(caps, a, choice, targetCheck); + } catch (e) { + if (!(e instanceof Back)) throw e; + } + } +} + +/** The Customize menu's rows for these answers. */ +function menu(a: Answers): Item[] { + return [ { value: 'crates', label: 'Crates', hint: 'logging, async, HTTP, serde, SQLite…' }, ...(isGui(a) ? [{ value: 'app', label: 'App', hint: 'GUI runtime, theme base, tray, palette…' }] : []), { value: 'tooling', label: 'Tooling', hint: 'CI, releases, guardrails, docs' }, @@ -171,15 +248,16 @@ async function customize(caps: Caps, a: Answers, targetCheck: (name: string) => { value: 'details', label: a.kind === 'lib' ? 'Name + tagline' : 'Name, command + tagline', hint: `${a.name}${effectiveAnswers(a).bin ? ` (runs as ${a.bin})` : ''} — ${a.tagline}` }, { value: 'preset', label: 'Start over from a preset', hint: 'resets everything else' }, { value: 'back', label: 'Back to review', hint: '' }, - ]); - const which = got(await pick(caps, { message: 'Customize what?', options: sections })); - const out: Answers = structuredClone(a); + ]; +} - if (which === 'preset') return repick(); +/** One Customize section on a copy of the answers; every prompt here offers Esc to go back. */ +async function section(caps: Caps, a: Answers, which: string, targetCheck: (name: string) => string | null): Promise { + const out: Answers = structuredClone(a); if (which === 'crates') { const toggles = (Object.keys(CRATE_TOGGLES) as (keyof typeof CRATE_TOGGLES)[]).filter((k) => !(k === 'clap' && a.kind === 'lib')); - const picked = got(await pickMany(caps, { + const picked = sect(await pickMany(caps, { back: true, message: 'Crates', options: items(CRATE_TOGGLES, toggles), initialValues: toggles.filter((k) => out.crates[k]), @@ -187,7 +265,7 @@ async function customize(caps: Caps, a: Answers, targetCheck: (name: string) => for (const k of toggles) out.crates[k] = picked.includes(k); if ((a.kind === 'cli' || isGui(a)) && out.crates.clap) { const gui = isGui(a); - out.features.subcommands = got(await pick(caps, { + out.features.subcommands = sect(await pick(caps, { back: true, message: 'Command line', initialValue: out.features.subcommands, options: ([ gui @@ -199,19 +277,19 @@ async function customize(caps: Caps, a: Answers, targetCheck: (name: string) => ]), })); } - out.crates.logging = got(await pick(caps, { message: 'Logging', initialValue: out.crates.logging, options: items(LOGGING, ['log', 'env_logger', 'tracing']) })); - out.crates.async = got(await pick(caps, { message: 'Async runtime', initialValue: out.crates.async, options: items(ASYNC, ['none', 'tokio']) })); - out.crates.http = got(await pick(caps, { message: 'HTTP client', initialValue: out.crates.http, options: items(HTTP, ['none', 'ureq', 'reqwest']) })); + out.crates.logging = sect(await pick(caps, { back: true, message: 'Logging', initialValue: out.crates.logging, options: items(LOGGING, ['log', 'env_logger', 'tracing']) })); + out.crates.async = sect(await pick(caps, { back: true, message: 'Async runtime', initialValue: out.crates.async, options: items(ASYNC, ['none', 'tokio']) })); + out.crates.http = sect(await pick(caps, { back: true, message: 'HTTP client', initialValue: out.crates.http, options: items(HTTP, ['none', 'ureq', 'reqwest']) })); } if (which === 'app') { - out.guiStack = got(await pick(caps, { message: 'GUI runtime', initialValue: out.guiStack, options: items(STACKS, ['eframe', 'winit-glow']) })); - out.themeBase = got(await pick(caps, { + out.guiStack = sect(await pick(caps, { back: true, message: 'GUI runtime', initialValue: out.guiStack, options: items(STACKS, ['eframe', 'winit-glow']) })); + out.themeBase = sect(await pick(caps, { back: true, message: 'Signature theme surfaces (your accent on these)', initialValue: out.themeBase, options: shippedThemes().map((t) => ({ value: t.id, label: t.name, hint: `${t.mode} · ${t.app} / ${t.panel}` })), })); const keys = Object.values(grouped(DESKTOP)).flat(); - const picked = got(await pickMany(caps, { + const picked = sect(await pickMany(caps, { back: true, message: 'App features', options: items(FEATURES, keys, true), initialValues: keys.filter((k) => out.features[k]), @@ -223,7 +301,7 @@ async function customize(caps: Caps, a: Answers, targetCheck: (name: string) => const groups = grouped(TOOLING); if (!isGui(a)) groups['guardrails'] = (groups['guardrails'] ?? []).filter((k) => k !== 'unsafeCheck'); const keys = Object.values(groups).flat(); - const picked = got(await pickMany(caps, { + const picked = sect(await pickMany(caps, { back: true, message: 'Tooling', options: items(TOOLING, keys, true), initialValues: keys.filter((k) => out.tooling[k]), @@ -232,13 +310,13 @@ async function customize(caps: Caps, a: Answers, targetCheck: (name: string) => } if (which === 'rust') { - out.license = got(await pick(caps, { message: 'Licence', initialValue: out.license, options: items(LICENSES, ['MIT', 'MIT OR Apache-2.0', 'Apache-2.0', 'MIT+CommonsClause']) })); - out.edition = got(await pick(caps, { + out.license = sect(await pick(caps, { back: true, message: 'Licence', initialValue: out.license, options: items(LICENSES, ['MIT', 'MIT OR Apache-2.0', 'Apache-2.0', 'MIT+CommonsClause']) })); + out.edition = sect(await pick(caps, { back: true, message: 'Rust edition', initialValue: out.edition, options: ([{ value: '2024' as const, label: '2024', hint: 'current' }, { value: '2021' as const, label: '2021', hint: 'for older toolchains' }]), })); - out.msrv = got(await text(caps, { message: 'Minimum supported Rust (rust-version)', initialValue: out.msrv, validate: (v) => (/^\d+\.\d+(?:\.\d+)?$/.test(v ?? '') ? undefined : 'Use a version like 1.98') })); - out.toolchain = got(await text(caps, { message: 'Pinned toolchain (rust-toolchain.toml + CI)', initialValue: out.toolchain, validate: (v) => (/^\d+\.\d+\.\d+$/.test(v ?? '') ? undefined : 'Use an exact version like 1.99.1') })); + out.msrv = sect(await text(caps, { back: true, message: 'Minimum supported Rust (rust-version)', initialValue: out.msrv, validate: (v) => msrvProblem(v ?? '', out.edition) })).trim(); + out.toolchain = sect(await text(caps, { back: true, message: 'Pinned toolchain (rust-toolchain.toml + CI)', initialValue: out.toolchain, validate: (v) => toolchainProblem(v ?? '', out.msrv, out.edition) })).trim(); } if (which === 'after') { @@ -247,7 +325,7 @@ async function customize(caps: Caps, a: Answers, targetCheck: (name: string) => { value: 'fetch', label: 'cargo fetch', hint: 'download crates now (seconds)' }, { value: 'cargoCheck', label: 'cargo check', hint: 'compile once to prove it builds (minutes for GUI)' }, ]); - const picked = got(await pickMany(caps, { + const picked = sect(await pickMany(caps, { back: true, message: 'After creating', options: steps, initialValues: (['git', 'fetch', 'cargoCheck'] as const).filter((k) => out.post[k]), @@ -255,24 +333,24 @@ async function customize(caps: Caps, a: Answers, targetCheck: (name: string) => out.post.git = picked.includes('git'); out.post.fetch = picked.includes('fetch'); out.post.cargoCheck = picked.includes('cargoCheck'); - out.post.open = got(await pick(caps, { + out.post.open = sect(await pick(caps, { back: true, message: 'Open it in an editor?', initialValue: out.post.open, options: ([{ value: 'none' as const, label: 'No', hint: '' }, { value: 'code' as const, label: 'VS Code', hint: 'code' }, { value: 'cursor' as const, label: 'Cursor', hint: 'cursor' }]), })); } if (which === 'details') { - out.name = got(await text(caps, { message: 'Project name', initialValue: out.name, validate: (v) => validateName(v ?? '') ?? targetCheck(v ?? '') ?? undefined })); + out.name = sect(await text(caps, { back: true, message: 'Project name', initialValue: out.name, validate: (v) => validateName(v ?? '') ?? targetCheck(v ?? '') ?? undefined })); if (out.kind !== 'lib') { // The executable is named after its crate unless this differs; then a [[bin]] table names it. const crateBin = out.kind === 'workspace' ? `${out.name}-app` : out.name; - const bin = got(await text(caps, { + const bin = sect(await text(caps, { back: true, message: 'Command name (what users type)', initialValue: out.bin || crateBin, placeholder: crateBin, validate: (v) => (v ? validateBin(v) ?? undefined : undefined), })); out.bin = bin === crateBin ? '' : bin; } - out.tagline = got(await text(caps, { message: 'One-line description', initialValue: out.tagline, placeholder: 'A Rust app.' })); + out.tagline = sect(await text(caps, { back: true, message: 'One-line description', initialValue: out.tagline, placeholder: 'A Rust app.' })); } return out; } diff --git a/src/reproduce.ts b/src/reproduce.ts index 63fa34f..fec7e1f 100644 --- a/src/reproduce.ts +++ b/src/reproduce.ts @@ -2,6 +2,7 @@ * The command that recreates a set of answers without prompts, printed on the finish screen. * It lists only what differs from the chosen preset, so the common case stays one short line. */ +import path, { basename, resolve } from 'node:path'; import { resolveAnswers } from './presets.ts'; import { effectiveAnswers } from './context.ts'; import type { Answers } from './types.ts'; @@ -13,11 +14,37 @@ import type { Answers } from './types.ts'; */ export const RUN_COMMAND = 'npx github:freeknet/create-rust-app'; -const quote = (v: string) => (/^[\w.@/:+-]+$/.test(v) ? v : `"${v.replace(/"/g, '\\"')}"`); +/** A POSIX-shell word: bare when safe, else double-quoted with `" \ $ \`` escaped. */ +const quote = (v: string) => (/^[\w.@/:+-]+$/.test(v) ? v : `"${v.replace(/["\\$`]/g, '\\$&')}"`); +/** + * The target folder as the finish screen and the recreate command name it: `dir` (the positional) + * or `./`, relative to `cwd` when inside it, else absolute; `.` for `cwd` itself. + * Separators are always `/`: the result goes into `cd …` and the POSIX-quoted recreate command, and + * a Windows backslash would be eaten by Git Bash (`cd out\x` is `cd outx`) or doubled by the + * quoting, while `/` works in Git Bash, PowerShell, cmd and Node alike. `p` is `node:path` (or its + * `win32` / `posix` variant, so tests can exercise either platform). + */ +export function shownTarget(dir: string | undefined, name: string, cwd: string = process.cwd(), p: typeof path = path): string { + const target = p.resolve(cwd, dir ?? name); + const rel = p.relative(cwd, target); + const shown = rel.startsWith('..') || p.isAbsolute(rel) ? target : rel || '.'; + return p.sep === '\\' ? shown.replaceAll('\\', '/') : shown; +} + +/** + * @param raw the answers as resolved (not yet effective) + * @param dir the real target directory as shown to the user (see `shownTarget`); defaults to + * `./`. `--name` is added whenever the name differs from the folder's own name. + * Every answer that changes the output is carried: anything differing from what a fresh run with + * the same preset would default to becomes a flag or a `--set`. + */ export function reproduceCommand(raw: Answers, dir?: string): string { const preset = resolveAnswers(raw.preset, { name: raw.name }); - const parts = [RUN_COMMAND, quote(dir ?? raw.name)]; + const folder = dir ?? raw.name; + const parts = [RUN_COMMAND, quote(folder)]; + // The CLI names the crate after a positional folder only when the folder's name is the name. + if (basename(resolve(folder)) !== raw.name) parts.push('--name', quote(raw.name)); if (raw.preset) parts.push('--preset', raw.preset); if (raw.kind !== preset.kind) parts.push('--kind', raw.kind); // Compare what each would generate for this kind, so options it never uses aren't listed. @@ -46,11 +73,16 @@ export function reproduceCommand(raw: Answers, dir?: string): string { if (a[k] !== base[k]) parts.push(`--${k}`, quote(a[k])); } if (a.bin) parts.push('--bin', quote(a.bin)); - if (a.tagline !== base.tagline) parts.push('--set', `tagline=${quote(a.tagline)}`); - if (!a.post.git) parts.push('--no-git'); - if (!a.post.fetch) parts.push('--no-fetch'); - if (a.post.cargoCheck) parts.push('--cargo-check'); - if (a.post.open !== 'none') parts.push('--open', a.post.open); + for (const k of ['author', 'github', 'accent'] as const) { + if (a[k] !== base[k]) parts.push(`--${k}`, quote(a[k])); + } + for (const k of ['displayName', 'tagline', 'email'] as const) { + if (a[k] !== base[k]) parts.push('--set', `${k}=${quote(a[k])}`); + } + if (a.post.git !== base.post.git) parts.push(...(a.post.git ? ['--set', 'post.git=true'] : ['--no-git'])); + if (a.post.fetch !== base.post.fetch) parts.push(...(a.post.fetch ? ['--set', 'post.fetch=true'] : ['--no-fetch'])); + if (a.post.cargoCheck !== base.post.cargoCheck) parts.push(a.post.cargoCheck ? '--cargo-check' : '--no-cargo-check'); + if (a.post.open !== base.post.open) parts.push('--open', a.post.open); parts.push('-y'); return parts.join(' '); } diff --git a/src/types.ts b/src/types.ts index 48b9ad4..f4a8d09 100644 --- a/src/types.ts +++ b/src/types.ts @@ -36,6 +36,9 @@ export interface Answers { preset: string | null; } +/** The answers `--json` reports: `guiStack` reads '' (like `themeBase`) for kinds without a GUI. */ +export type ReportedAnswers = Omit & { guiStack: Answers['guiStack'] | '' }; + export type PartialAnswers = { [K in keyof Answers]?: Answers[K] extends object ? Partial : Answers[K]; }; diff --git a/src/ui/choose.ts b/src/ui/choose.ts index 4dd6c0e..2dec2f7 100644 --- a/src/ui/choose.ts +++ b/src/ui/choose.ts @@ -5,13 +5,13 @@ * row, and echo the full label after submit. We want every description visible while choosing and a * short, clean echo afterwards, grouped headers without selectable group rows, and our palette. */ -import { MultiSelectPrompt, SelectPrompt } from '@clack/core'; +import { MultiSelectPrompt, SelectPrompt, isCancel } from '@clack/core'; import type { Readable, Writable } from 'node:stream'; import { glyphs } from './glyphs.ts'; import { live, shimmer } from './motion.ts'; import { bold, dim, hex } from './rainbow.ts'; import { STOPS } from './theme.ts'; -import { width, wrap } from './tty.ts'; +import { clip, liveColumns, liveRows, width, wrap } from './tty.ts'; import type { Caps } from '../types.ts'; export interface Item { value: V; label: string; hint?: string; tag?: string; group?: string } @@ -32,17 +32,120 @@ function chrome(caps: Caps) { }; } -/** Lay out `label tag description` rows so descriptions share a column, clipped to the terminal. */ -function layout(caps: Caps, items: Item[], indent: number) { - const labelW = Math.max(...items.map((i) => width(i.label) + (i.tag ? width(i.tag) + 2 : 0))); - const room = Math.max(10, caps.columns - indent - labelW - 6); +/** `text` clipped to `max` cells, ending in an ellipsis when anything was cut. */ +export function clipEllipsis(caps: Caps, text: string, max: number) { + if (width(text) <= max) return text; + const ell = glyphs(caps).ellipsis; + return max <= width(ell) ? clip(text, Math.max(0, max)) : `${clip(text, max - width(ell))}${ell}`; +} + +/** + * Lay out `label tag description` rows so descriptions share a column, fitted to `columns`. + * `prefix` is the width drawn before the label (rail, marks). Where the description column has its + * usual room the rows are as they always were; on a narrow terminal the description is shortened, + * then dropped, then the tag, and only then is the label cut, so no row wraps. + */ +export function layout(caps: Caps, items: Item[], indent: number, columns: number, prefix: number) { + const tagW = (i: Item) => (i.tag ? width(i.tag) + 2 : 0); + const labelW = Math.max(...items.map((i) => width(i.label) + tagW(i))); + const room = columns - indent - labelW - 6; + const tag = (i: Item) => (i.tag ? ` ${hex(caps, AMBER, i.tag)}` : ''); + const gap = (i: Item) => ' '.repeat(labelW - width(i.label) - tagW(i) + 3); + if (room >= 10) { + return items.map((i) => { + const hint = i.hint && width(i.hint) > room ? `${i.hint.slice(0, room - 1)}${glyphs(caps).ellipsis}` : (i.hint ?? ''); + return { label: i.label, tag: tag(i), gap: gap(i), hint }; + }); + } + // One spare column: a line exactly as wide as the terminal wraps in some terminals. + const avail = Math.max(1, columns - prefix - 1); + const hintRoom = avail - labelW - 3; return items.map((i) => { - const used = width(i.label) + (i.tag ? width(i.tag) + 2 : 0); - const hint = i.hint && width(i.hint) > room ? `${i.hint.slice(0, room - 1)}${glyphs(caps).ellipsis}` : (i.hint ?? ''); - return { label: i.label, tag: i.tag ? ` ${hex(caps, AMBER, i.tag)}` : '', gap: ' '.repeat(labelW - used + 3), hint }; + if (i.hint && hintRoom >= 8) return { label: i.label, tag: tag(i), gap: gap(i), hint: clipEllipsis(caps, i.hint, hintRoom) }; + if (width(i.label) + tagW(i) <= avail) return { label: i.label, tag: tag(i), gap: '', hint: '' }; + return { label: clipEllipsis(caps, i.label, avail), tag: '', gap: '', hint: '' }; }); } +/** + * A footer's `a · b · c` parts fitted to `room` cells: parts are dropped in `dropOrder` (indexes) + * until the rest fits; a single part that still doesn't fit is cut with an ellipsis. + */ +export function fitFooter(caps: Caps, parts: string[], dropOrder: number[], room: number) { + const keep = parts.map(() => true); + const line = () => parts.filter((_, i) => keep[i]).join(' · '); + for (const i of dropOrder) { + if (width(line()) <= room) break; + if (keep.filter(Boolean).length > 1) keep[i] = false; + } + return clipEllipsis(caps, line(), room); +} + +/** + * The first visible line of a list window of `room` lines over `total`, scrolled as little as + * possible from `prev` so that lines `top`..`bottom` (the focused row, and its group header when + * there is one) are on screen. + */ +export function windowStart(total: number, top: number, bottom: number, room: number, prev: number) { + const last = Math.max(0, total - room); + let start = Math.min(Math.max(0, prev), last); + if (bottom >= start + room) start = bottom - room + 1; + if (top < start) start = top; + return Math.max(0, Math.min(start, last)); +} + +/** + * Fit a list's body lines to the terminal height. The frame (rail, message, body, footer: `chrome` + * is everything but the body) stays below `rows` lines, so @clack/core can always erase the whole + * previous frame; a taller one leaves its top lines in the scrollback. When the body doesn't fit, a + * window of it is shown between "more above" / "more below" lines. Returns the lines and the start. + */ +export function windowBody(caps: Caps, body: string[], top: number, bottom: number, rows: number, chrome: number, prev: number) { + if (body.length + chrome <= rows - 1) return { lines: body, start: 0 }; + const g = glyphs(caps); + const rail = hex(caps, CYAN, g.bar); + const room = Math.max(1, rows - 1 - chrome - 2); + const start = windowStart(body.length, top, bottom, room, prev); + const below = Math.max(0, body.length - start - room); + const more = (arrow: string, n: number) => (n ? `${rail} ${dim(caps, `${arrow} ${n} more`)}` : rail); + return { lines: [more(g.up, start), ...body.slice(start, start + room), more(g.down, below)], start }; +} + +/** The prompt's message after its mark, wrapped onto rail lines when it is wider than the terminal. */ +function messageLines(caps: Caps, mark: string, message: string, columns: number) { + if (width(message) + 3 <= columns) return [`${mark} ${message}`]; + const c = chrome(caps); + return wrap(message, Math.max(1, columns - 4)).map((l, i) => `${i === 0 ? mark : c.live()} ${l}`); +} + +/** + * What a prompt opened with `back: true` resolves to when Esc is pressed. Ctrl-C still resolves to + * clack's cancel symbol. @clack/core maps both keys to one cancel action, but it emits the `key` + * event before acting on it, so the prompt can tell them apart. + */ +export const BACK: unique symbol = Symbol('create-rust-app:back'); + +/** Remember whether the key that ended a prompt was Esc. */ +export function escWatch(prompt: { on(event: 'key', cb: (key: string | undefined, info: { name?: string | undefined }) => void): void }) { + const seen = { esc: false }; + prompt.on('key', (_key, info) => { seen.esc = info?.name === 'escape'; }); + return seen; +} + +/** Resolve Esc to BACK on a `back` prompt; everything else (Ctrl-C included) passes through. */ +export function settle(result: Promise, seen: { esc: boolean }, back: boolean | undefined): Promise { + return back ? result.then((v) => (isCancel(v) && seen.esc ? BACK : v)) : result; +} + +/** The frame a `back` prompt leaves behind on Esc: a dim, closed step rather than a red cancel. */ +export function backFrame(caps: Caps, message: string) { + const c = chrome(caps); + return `${c.bar()}\n${dim(caps, c.g.done)} ${dim(caps, message)}\n${c.bar()}`; +} + +/** The Esc part of a footer: Esc steps back inside Customize, and cancels the run elsewhere. */ +export const escHint = (back: boolean | undefined) => (back ? 'esc back' : 'esc cancel'); + const echo = (caps: Caps, lines: string[]) => { const c = chrome(caps); return lines.map((l) => `${c.bar()} ${dim(caps, l)}`).join('\n'); @@ -52,76 +155,103 @@ const echo = (caps: Caps, lines: string[]) => { /** Optional streams (tests drive prompts in-process with these). */ export type Io = { input?: Readable; output?: Writable }; -export function pick(caps: Caps, o: { message: string; options: Item[]; initialValue?: V; footer?: string; io?: Io }) { +export function pick(caps: Caps, o: { message: string; options: Item[]; initialValue?: V; footer?: string; back?: boolean; io?: Io }) { const c = chrome(caps); - const rows = layout(caps, o.options, 6); + const out = o.io?.output ?? process.stdout; + const prefix = width(`${c.g.bar} ${c.g.radioOn} `); const anim = { t: 0 }; + let start = 0; const prompt = new SelectPrompt>({ ...(o.io ?? {}), options: o.options, ...(o.initialValue !== undefined ? { initialValue: o.initialValue } : {}), render() { + // The size is read on every frame, so a resize is honoured. + const columns = liveColumns(out, caps.columns); const head = `${c.bar()}\n`; const chosen = this.options[this.cursor]; - if (this.state === 'submit') return `${head}${c.done()} ${o.message}\n${echo(caps, [chosen?.label ?? ''])}`; - if (this.state === 'cancel') return `${head}${hex(caps, RED, c.g.cancel)} ${o.message}\n${c.bar()}`; + if (this.state === 'submit') return `${head}${messageLines(caps, c.done(), o.message, columns).join('\n')}\n${echo(caps, [clipEllipsis(caps, chosen?.label ?? '', Math.max(1, columns - 4))])}`; + if (this.state === 'cancel') return o.back && seen.esc ? backFrame(caps, o.message) : `${head}${messageLines(caps, hex(caps, RED, c.g.cancel), o.message, columns).join('\n')}\n${c.bar()}`; + const rows = layout(caps, o.options, 6, columns, prefix); const body = rows.map((r, i) => { const on = i === this.cursor; const dot = on ? hex(caps, GREEN, c.g.radioOn) : dim(caps, c.g.radioOff); const label = on ? shimmer(caps, r.label, anim.t) : r.label; return `${c.live()} ${dot} ${label}${r.tag}${r.gap}${on ? r.hint : dim(caps, r.hint)}`; }); - const footer = `${c.live(c.g.barEnd)} ${dim(caps, o.footer ?? `${c.g.up}${c.g.down} move · enter select · esc cancel`)}`; - return `${head}${c.live(c.g.step)} ${o.message}\n${body.join('\n')}\n${footer}`; + const parts = o.footer ? [o.footer] : [`${c.g.up}${c.g.down} move`, 'enter select', escHint(o.back)]; + const footer = `${c.live(c.g.barEnd)} ${dim(caps, fitFooter(caps, parts, [1, 0], Math.max(1, columns - 4)))}`; + const message = messageLines(caps, c.live(c.g.step), o.message, columns); + const win = windowBody(caps, body, this.cursor, this.cursor, liveRows(out), message.length + 2, start); + start = win.start; + return `${head}${message.join('\n')}\n${win.lines.join('\n')}\n${footer}`; }, }); + const seen = escWatch(prompt); live(caps, prompt, anim); - return prompt.prompt() as Promise; + return settle(prompt.prompt() as Promise, seen, o.back); } /** * Multiple choice, optionally grouped (`item.group`). Group names render as coloured headers; only * items are selectable. Resolves to the selected values, or clack's cancel symbol. */ -export function pickMany(caps: Caps, o: { message: string; options: Item[]; initialValues?: V[]; io?: Io }) { +export function pickMany(caps: Caps, o: { message: string; options: Item[]; initialValues?: V[]; back?: boolean; io?: Io }) { const c = chrome(caps); + const out = o.io?.output ?? process.stdout; const grouped = o.options.some((i) => i.group); - const rows = layout(caps, o.options, grouped ? 8 : 6); + // Without colour the focused row can't be told apart by style, so a focus mark gets its own column. + const mark = caps.tier === 'none'; + const prefix = width(`${c.g.bar} ${mark ? `${c.g.focus} ` : ''}${grouped ? ' ' : ''}${c.g.boxOn} `); const groupColor = new Map(); for (const i of o.options) if (i.group && !groupColor.has(i.group)) groupColor.set(i.group, STOPS[(groupColor.size * 2 + 1) % STOPS.length] ?? CYAN); const anim = { t: 0 }; + let start = 0; const prompt = new MultiSelectPrompt>({ ...(o.io ?? {}), options: o.options, initialValues: o.initialValues ?? [], required: false, render() { + const columns = liveColumns(out, caps.columns); const head = `${c.bar()}\n`; const selected = new Set(this.value ?? []); if (this.state === 'submit') { const names = o.options.filter((i) => selected.has(i.value)).map((i) => i.label); - const lines = names.length ? wrap(names.join(c.g.sep.trim() ? c.g.sep : ' '), Math.max(20, caps.columns - 6)) : ['none']; - return `${head}${c.done()} ${o.message}\n${echo(caps, lines)}`; + const lines = names.length ? wrap(names.join(c.g.sep.trim() ? c.g.sep : ' '), columns >= 26 ? columns - 6 : Math.max(1, columns - 4)) : ['none']; + return `${head}${messageLines(caps, c.done(), o.message, columns).join('\n')}\n${echo(caps, lines)}`; } - if (this.state === 'cancel') return `${head}${hex(caps, RED, c.g.cancel)} ${o.message}\n${c.bar()}`; - const out: string[] = []; + if (this.state === 'cancel') return o.back && seen.esc ? backFrame(caps, o.message) : `${head}${messageLines(caps, hex(caps, RED, c.g.cancel), o.message, columns).join('\n')}\n${c.bar()}`; + const rows = layout(caps, o.options, grouped ? 8 : 6, columns, prefix); + const body: string[] = []; let lastGroup: string | undefined; + let top = 0; + let focus = 0; o.options.forEach((item, i) => { + const on = i === this.cursor; if (item.group && item.group !== lastGroup) { lastGroup = item.group; - out.push(`${c.live()} ${hex(caps, groupColor.get(item.group) ?? CYAN, item.group)}`); - } + // Scrolling up to the first row of a group brings its header along. + if (on) top = body.length; + body.push(`${c.live()} ${hex(caps, groupColor.get(item.group) ?? CYAN, clipEllipsis(caps, item.group, Math.max(1, columns - 4)))}`); + } else if (on) top = body.length; const r = rows[i]; if (!r) return; - const on = i === this.cursor; + if (on) focus = body.length; const box = selected.has(item.value) ? hex(caps, GREEN, c.g.boxOn) : dim(caps, c.g.boxOff); const label = on ? shimmer(caps, r.label, anim.t) : r.label; - out.push(`${c.live()} ${grouped ? ' ' : ''}${box} ${label}${r.gap}${on ? r.hint : dim(caps, r.hint)}`); + const pointer = mark ? `${on ? c.g.focus : ' '.repeat(width(c.g.focus))} ` : ''; + body.push(`${c.live()} ${pointer}${grouped ? ' ' : ''}${box} ${label}${r.gap}${on ? r.hint : dim(caps, r.hint)}`); }); - const footer = `${c.live(c.g.barEnd)} ${dim(caps, 'space toggle · a all · enter confirm · esc cancel')}`; - return `${head}${c.live(c.g.step)} ${o.message}\n${out.join('\n')}\n${footer}`; + const parts = ['space toggle', 'a all', 'enter confirm', escHint(o.back)]; + const footer = `${c.live(c.g.barEnd)} ${dim(caps, fitFooter(caps, parts, [1, 2, 0], Math.max(1, columns - 4)))}`; + const message = messageLines(caps, c.live(c.g.step), o.message, columns); + const win = windowBody(caps, body, top, focus, liveRows(out), message.length + 2, start); + start = win.start; + return `${head}${message.join('\n')}\n${win.lines.join('\n')}\n${footer}`; }, }); + const seen = escWatch(prompt); live(caps, prompt, anim); - return prompt.prompt() as Promise; + return settle(prompt.prompt() as Promise, seen, o.back); } diff --git a/src/ui/glyphs.ts b/src/ui/glyphs.ts index 3e9ff3a..880e8fc 100644 --- a/src/ui/glyphs.ts +++ b/src/ui/glyphs.ts @@ -16,6 +16,8 @@ export interface Glyphs { radioOn: string; radioOff: string; boxOn: string; boxOff: string; ok: string; fail: string; tl: string; tr: string; bl: string; br: string; h: string; v: string; tee: string; rule: string; spinner: string[]; sep: string; ellipsis: string; up: string; down: string; cursor: string; + /** Focus mark and in-text caret for when colour is off and can't show either. */ + focus: string; caret: string; } const FULL: Glyphs = { @@ -23,12 +25,13 @@ const FULL: Glyphs = { radioOn: '●', radioOff: '○', boxOn: '◼', boxOff: '◻', ok: '✔', fail: '✖', tl: '╭', tr: '╮', bl: '╰', br: '╯', h: '─', v: '│', tee: '├', rule: '━', spinner: ['⣾', '⣽', '⣻', '⢿', '⡿', '⣟', '⣯', '⣷'], sep: ' · ', ellipsis: '…', up: '↑', down: '↓', cursor: '█', + focus: '›', caret: '▏', }; const CONSOLE: Glyphs = { ...FULL, step: '♦', done: '◊', boxOn: '■', boxOff: '□', ok: '√', fail: '×', - spinner: ['░', '▒', '▓', '█', '▓', '▒'], + spinner: ['░', '▒', '▓', '█', '▓', '▒'], caret: '|', }; const ASCII: Glyphs = { @@ -36,6 +39,7 @@ const ASCII: Glyphs = { radioOn: '>', radioOff: ' ', boxOn: '[x]', boxOff: '[ ]', ok: '[ok]', fail: '[x]', tl: '+', tr: '+', bl: '+', br: '+', h: '-', v: '|', tee: '+', rule: '=', spinner: ['-', '\\', '|', '/'], sep: ' / ', ellipsis: '...', up: 'up', down: 'down', cursor: '_', + focus: '>', caret: '|', }; export function glyphs(caps: Pick): Glyphs { diff --git a/src/ui/rail.ts b/src/ui/rail.ts index 71b6956..bac122f 100644 --- a/src/ui/rail.ts +++ b/src/ui/rail.ts @@ -7,8 +7,9 @@ import { TextPrompt } from '@clack/core'; import { bold, dim, hex } from './rainbow.ts'; import { glyphs } from './glyphs.ts'; -import { width } from './tty.ts'; +import { liveColumns, width, wrap } from './tty.ts'; import { cascade, live, marker, sparkle, wave } from './motion.ts'; +import { backFrame, escHint, escWatch, settle } from './choose.ts'; import type { Caps } from '../types.ts'; export const COLORS = { live: '#7cf7ff', done: '#b6ff6e', rail: '#6f6a85', warn: '#ffd36e', error: '#ff6b7c' }; @@ -26,14 +27,23 @@ export function rail(caps: Caps) { }; } +/** Text with a visible cursor and no escape codes: a caret before the cursor cell, a block at the end. */ +export function plainCursor(caps: Caps, value: string, cursor: number) { + const g = glyphs(caps); + return cursor >= value.length ? `${value}${g.cursor}` : `${value.slice(0, cursor)}${g.caret}${value.slice(cursor)}`; +} + /** Free-text prompt. Resolves to the value or the cancel symbol. */ export function text(caps: Caps, o: { message: string; placeholder?: string; defaultValue?: string; initialValue?: string; validate?: (v: string) => string | undefined; + /** Esc resolves to BACK (choose.ts) instead of cancelling; Ctrl-C still cancels. */ + back?: boolean; io?: import('./choose.ts').Io; }) { const r = rail(caps); const anim = { t: 0 }; + const out = o.io?.output ?? process.stdout; const prompt = new TextPrompt({ ...(o.io ?? {}), ...(o.initialValue !== undefined ? { initialValue: o.initialValue } : {}), @@ -42,21 +52,28 @@ export function text(caps: Caps, o: { render() { const head = `${r.bar()}\n`; if (this.state === 'submit') return `${head}${r.done()} ${o.message}\n${r.bar()} ${dim(caps, this.value ?? '')}`; - if (this.state === 'cancel') return `${head}${r.error(r.g.cancel)} ${o.message}\n${r.bar()}`; + if (this.state === 'cancel') return o.back && seen.esc ? backFrame(caps, o.message) : `${head}${r.error(r.g.cancel)} ${o.message}\n${r.bar()}`; // Only one line may change per animation tick (see motion.ts): here that's the marker, so the // cursor in front of the placeholder stays steady. + // clack's cursor is an inverse-video cell (and sees NO_COLOR but not --no-color): without + // colour draw a caret glyph instead, so the position stays visible with no escape codes. const input = this.userInput - ? this.userInputWithCursor + ? (caps.tier === 'none' ? plainCursor(caps, this.userInput, this.cursor) : this.userInputWithCursor) : `${hex(caps, COLORS.live, r.g.cursor)}${dim(caps, o.placeholder ?? '')}`; const err = this.state === 'error'; const color = err ? COLORS.warn : COLORS.live; const step = err ? hex(caps, color, r.g.step) : marker(caps, r.g.step, anim.t); - const foot = err ? hex(caps, COLORS.warn, this.error) : dim(caps, 'enter confirm · esc cancel'); - return `${head}${step} ${o.message}\n${hex(caps, color, r.g.bar)} ${input}\n${hex(caps, color, r.g.barEnd)} ${foot}`; + // A long error wraps onto further rail lines instead of past the terminal's edge. + const foot = err + ? wrap(this.error, Math.max(10, liveColumns(out, caps.columns) - 4)).map((l) => hex(caps, COLORS.warn, l)) + : [dim(caps, `enter confirm · ${escHint(o.back)}`)]; + const tail = foot.map((l, i) => `${hex(caps, color, i === foot.length - 1 ? r.g.barEnd : r.g.bar)} ${l}`).join('\n'); + return `${head}${step} ${o.message}\n${hex(caps, color, r.g.bar)} ${input}\n${tail}`; }, }); + const seen = escWatch(prompt); live(caps, prompt, anim); - return prompt.prompt() as Promise; + return settle(prompt.prompt() as Promise, seen, o.back); } /** @@ -127,38 +144,57 @@ export interface Task { title: string; enabled?: boolean; required?: boolean; ru * Run tasks one after another. Each shows a spinner line while running and settles into * `◇ message 0.4s` (or a warning mark when it failed or was skipped). Returns false, without * running anything further, as soon as a `required` task fails. + * + * Ctrl-C while they run never reaches a `finally`, so a SIGINT handler is installed for the + * duration: it stops the spinner, shows the cursor again, settles the spinner line, prints + * `interrupted` (what was left behind) and exits 130. */ -export async function tasks(caps: Caps, list: Task[]) { +export async function tasks(caps: Caps, list: Task[], o: { interrupted?: string } = {}) { const r = rail(caps); - for (const t of list) { - if (t.enabled === false) continue; - const t0 = performance.now(); - let msg = t.title; - let frame = 0; - const draw = () => { - const spin = wave(caps, frame++); - const line = `${spin} ${msg}`; - const max = Math.max(10, caps.columns - 1); - write(`\r\x1b[2K${width(line) > max ? `${line.slice(0, max - 1)}${r.g.ellipsis}` : line}`); - }; - write(`${r.bar()}\n`); - const timer = caps.tty && caps.animate ? setInterval(draw, 90) : null; - if (caps.tty) { write('\x1b[?25l'); draw(); } - let result: { ok: boolean | null; message: string }; - try { - result = await t.run((m) => { msg = `${t.title} ${dim(caps, m)}`; }); - } catch (e) { - result = { ok: false, message: `${t.title} failed: ${e instanceof Error ? e.message : String(e)}` }; - } finally { - if (timer) clearInterval(timer); - if (caps.tty) write('\x1b[?25h'); + let timer: ReturnType | null = null; + let running = ''; + const onSigint = () => { + if (timer) clearInterval(timer); + write(`${caps.tty ? '\r\x1b[2K\x1b[?25h' : ''}${r.error(r.g.cancel)} ${running} ${dim(caps, '(interrupted)')}\n`); + cancel(caps, o.interrupted ?? 'Interrupted.'); + process.exit(130); + }; + process.on('SIGINT', onSigint); + try { + for (const t of list) { + if (t.enabled === false) continue; + const t0 = performance.now(); + let msg = t.title; + let frame = 0; + running = t.title; + const draw = () => { + const spin = wave(caps, frame++); + const line = `${spin} ${msg}`; + const max = Math.max(10, caps.columns - 1); + write(`\r\x1b[2K${width(line) > max ? `${line.slice(0, max - 1)}${r.g.ellipsis}` : line}`); + }; + write(`${r.bar()}\n`); + timer = caps.tty && caps.animate ? setInterval(draw, 90) : null; + if (caps.tty) { write('\x1b[?25l'); draw(); } + let result: { ok: boolean | null; message: string }; + try { + result = await t.run((m) => { msg = `${t.title} ${dim(caps, m)}`; }); + } catch (e) { + result = { ok: false, message: `${t.title} failed: ${e instanceof Error ? e.message : String(e)}` }; + } finally { + if (timer) clearInterval(timer); + timer = null; + if (caps.tty) write('\x1b[?25h'); + } + const secs = dim(caps, `${((performance.now() - t0) / 1000).toFixed(1)}s`); + const mark = result.ok === true ? r.done() : hex(caps, COLORS.warn, result.ok === null ? r.g.done : r.g.fail); + write(`${caps.tty ? '\r\x1b[2K' : ''}${mark} ${result.message} ${secs}\n`); + if (t.required && result.ok !== true) return false; } - const secs = dim(caps, `${((performance.now() - t0) / 1000).toFixed(1)}s`); - const mark = result.ok === true ? r.done() : hex(caps, COLORS.warn, result.ok === null ? r.g.done : r.g.fail); - write(`${caps.tty ? '\r\x1b[2K' : ''}${mark} ${result.message} ${secs}\n`); - if (t.required && result.ok !== true) return false; + return true; + } finally { + process.removeListener('SIGINT', onSigint); } - return true; } export { bold }; diff --git a/src/ui/tty.ts b/src/ui/tty.ts index 2be6088..5463a38 100644 --- a/src/ui/tty.ts +++ b/src/ui/tty.ts @@ -65,6 +65,20 @@ export function columns(value: number | undefined) { return Number.isFinite(value) && Number(value) > 0 ? Math.max(1, Math.floor(Number(value))) : 80; } +/** + * The terminal's current size, read at render time so a resize is honoured. Streams that aren't a + * terminal (tests, pipes) have no size: columns fall back to `fallback`, rows to Infinity (nothing + * to window). + */ +export function liveColumns(out: unknown, fallback: number): number { + const c = (out as { columns?: unknown } | null | undefined)?.columns; + return typeof c === 'number' && c > 0 ? Math.floor(c) : fallback; +} +export function liveRows(out: unknown): number { + const r = (out as { rows?: unknown } | null | undefined)?.rows; + return typeof r === 'number' && r > 0 ? Math.floor(r) : Infinity; +} + /** Presentation-only ASCII conversion; colour helpers never alter input text. @param {string} text */ export function ascii(text: string) { return text.replace(/[◆◇━─│╭╮╰╯┌┐└┘├┤┬┴┼✔✖…·›●○⣾⣽⣻⢿⡿⣟⣯⣷]/gu, (char: string) => { diff --git a/templates/base/files/CHANGELOG.md b/templates/base/files/CHANGELOG.md index 8554487..b2bceb8 100644 --- a/templates/base/files/CHANGELOG.md +++ b/templates/base/files/CHANGELOG.md @@ -1,15 +1,46 @@ + # Changelog -All notable changes to @@displayName@@, newest first. +All notable changes to @@name@@, newest first. - **This file is generated.** It is rebuilt from the git history by `cargo xtask changelog`, so released sections are rewritten in place and edits to them do not survive. See `CONTRIBUTING.md`. + +The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), +and the project follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [Unreleased] + +### Added + +- scaffold @@name@@ with create-rust-app + +# Changelog + +All notable changes to @@name@@, newest first. + +**This file is generated.** It is rebuilt from the git history by +`cargo run --example changelog`, so released sections are rewritten in +place and edits to them do not survive. See `CONTRIBUTING.md`. + +The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), +and the project follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [Unreleased] + +### Added + +- scaffold @@name@@ with create-rust-app + +[Unreleased]: https://github.com/@@github@@/@@name@@/commits/HEAD +# Changelog + +All notable changes to @@displayName@@, newest first. + Entries follow the conventional-commit subjects in the git history (`feat:` under Added, `fix:` under Fixed, and so on). See `CONTRIBUTING.md`. - The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the project follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html). @@ -19,3 +50,4 @@ and the project follows [Semantic Versioning](https://semver.org/spec/v2.0.0.htm ### Added - Project scaffolded with create-rust-app. + diff --git a/templates/base/files/CLAUDE.md b/templates/base/files/CLAUDE.md index fdd067f..c95ad4c 100644 --- a/templates/base/files/CLAUDE.md +++ b/templates/base/files/CLAUDE.md @@ -74,6 +74,9 @@ cargo run --example screenshot # see the UI, without a window cargo run # the app, debug cargo run --release # the app, as shipped + +cargo run --example changelog # regenerate CHANGELOG.md + cargo deny check # licences, advisories, sources @@ -142,8 +145,11 @@ unlinted. A violation is a build failure. Denied in `[lints]` in `Cargo.toml`, so a violation is a build failure. Use `?`, `let ... else`, or an explicit fallback. Tests return -`anyhow::Result<()>`, and every `assert!` carries a message. Release builds -use `panic = "abort"`, so a panic is a crash, not an unwound error. +`anyhow::Result<()>`. Release builds use `panic = "abort"`, so a panic is a +crash, not an unwound error. + +By convention, not by any check, every `assert!` carries a message saying +what failed: a bare `assertion failed` in CI tells nobody anything. The same block denies `wildcard_enum_match_arm` (name every variant: that is what catches a new variant silently doing nothing), `missing_docs`, @@ -169,16 +175,21 @@ blank line, then the module's `//!` docs: //! The config file: every field optional, parsed independently. ``` -`src/header_check.rs` walks `src/`, `tests/` and `examples/` and fails the -build for a file missing one, so a new file needs its header in the same -commit that adds it. `Module:` is checked against the path the file sits at: +`src/header_check.rs` walks `src/`, `tests/`, `examples/`, `benches/` and +`build.rs` and fails the test run for a file missing one, so a new file +needs its header in the same commit that adds it. `Module:` is checked +against the path the file sits at: `src/foo/mod.rs` is `@@appCrateSnake@@::foo`, `src/lib.rs` is -`@@appCrate@@ (library crate root)`, and `tests/x.rs` is -`x (integration test)`. +`@@appCrate@@ (library crate root)`, `src/main.rs` is +`@@appCrate@@ (binary crate root)`, `tests/x.rs` is `x (integration test)`, +`examples/x.rs` is `x (example)`, `benches/x.rs` is `x (benchmark)`, and +`build.rs` is `build (build script)`. `src/foo/mod.rs` is `foo`, `src/lib.rs` is `@@name@@ (library crate root)`, -and `tests/x.rs` is `x (integration test)`. +`src/main.rs` is `@@name@@ (binary crate root)`, `tests/x.rs` is +`x (integration test)`, `examples/x.rs` is `x (example)`, `benches/x.rs` is +`x (benchmark)`, and `build.rs` is `build (build script)`. Copy an existing header and fix all three fields. The banner is plain `//`, not `//!`; the reasoning belongs in the `//!` block below it. @@ -223,11 +234,25 @@ note saying what would clear it. `cargo xtask changelog` rebuilds it from `git tag` plus conventional-commit subjects, so an edit to a released section does not survive. Prose for a -release belongs in the GitHub release body. **Never amend or rebase a -commit after tagging it**: the tag keeps pointing at the discarded copy, -and every release range computed from it is then wrong. +release belongs in the GitHub release body. `cargo xtask changelog --check` +compares the released sections with the history; CI does not run it, so +run it before a release. **Never amend or rebase a commit after tagging +it**: the tag keeps pointing at the discarded copy, and every release range +computed from it is then wrong. +### `CHANGELOG.md` is generated: never hand-edit it + +`cargo run --example changelog` rebuilds it from `git tag` plus +conventional-commit subjects, so an edit to a released section does not +survive. Prose for a release belongs in the GitHub release body. +`cargo run --example changelog -- --check` compares the released sections +with the history; CI does not run it, so run it before a release. +**Never amend or rebase a commit after tagging it**: the tag keeps pointing +at the discarded copy, and every release range computed from it is then +wrong. + + ### `CHANGELOG.md` moves with the code Every user-visible change adds a line under `## [Unreleased]` in the same diff --git a/templates/base/files/CONTRIBUTING.md b/templates/base/files/CONTRIBUTING.md index 1344fb1..247bf1d 100644 --- a/templates/base/files/CONTRIBUTING.md +++ b/templates/base/files/CONTRIBUTING.md @@ -133,7 +133,8 @@ version: - **No `unwrap`, `expect`, `panic!`, `todo!` or `unreachable!`, including in tests.** Use `let ... else`, `?`, or an explicit fallback. Tests return - `anyhow::Result<()>`, and every `assert!` carries a message. + `anyhow::Result<()>`. (Every `assert!` also carries a message; that one + is a convention review keeps, not something the build checks.) - **`match` arms list every variant** (`wildcard_enum_match_arm` is denied), and suppressions are `#[expect(lint, reason = "...")]`, never `#[allow]`, so they cannot outlive what they suppressed. @@ -142,9 +143,11 @@ version: - **Every source file opens with a module header banner**: a ruled block naming `Module:`, `Description:` and `Dependencies:`, then the `//!` docs. - `src/header_check.rs` walks `src/`, `tests/` and `examples/` and fails the - build for a file missing one, checking `Module:` against the path the file - actually sits at. + `src/header_check.rs` walks `src/`, `tests/`, `examples/`, `benches/` and + `build.rs` and fails the build for a file missing one, checking `Module:` + against the path the file actually sits at (`tests/x.rs` is + `x (integration test)`, `examples/x.rs` is `x (example)`, `benches/x.rs` + is `x (benchmark)`, `build.rs` is `build (build script)`). - **Every `unsafe` block is a safe leaf wrapper.** One named, private, safe @@ -180,7 +183,17 @@ every entry is a conventional-commit subject, grouped under the release tag that shipped it. That is the other reason the commit prefixes matter: a subject that does not parse still appears, but in a catch-all section rather than the right one. Never hand-edit a released section; prose for a -release belongs in the GitHub release body. +release belongs in the GitHub release body. `cargo xtask changelog --check` +compares the released sections with the history. + +`CHANGELOG.md` is rebuilt from the git history by +`cargo run --example changelog`: every entry is a conventional-commit +subject, grouped under the release tag that shipped it. That is the other +reason the commit prefixes matter: a subject that does not parse still +appears, but in a catch-all section rather than the right one. Never +hand-edit a released section; prose for a release belongs in the GitHub +release body. `cargo run --example changelog -- --check` compares the +released sections with the history. `CHANGELOG.md` follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). Add a line under `## [Unreleased]` in the same pull request as the change, @@ -190,9 +203,20 @@ Fixed, and so on. ## Cutting a release + +1. On a release branch off `main`: bump `version` in `Cargo.toml` and + commit. The changelog follows the tag: once the tag is pushed (step 3), + run `cargo xtask changelog` and commit the result. A commit that touches + only `CHANGELOG.md` is left out of every section. + +1. On a release branch off `main`: bump `version` in `Cargo.toml` and + commit, then run `cargo run --example changelog -- --release v0.2.0`, + which writes the section for the tag about to be cut, and commit that. + 1. On a release branch off `main`: bump `version` in `Cargo.toml`, move the `Unreleased` entries under a new `## [x.y.z] - YYYY-MM-DD` heading in `CHANGELOG.md`, and commit. + 2. Open the pull request and let the checks pass. 3. Merge (a merge commit, so the history the changelog describes survives), then tag the merge commit, annotated: @@ -201,6 +225,11 @@ Fixed, and so on. 4. The push triggers `.github/workflows/release.yml`: it checks the tag against `Cargo.toml`, builds the release archive with an SBOM and checksums, attests them, and publishes the GitHub release. + The attestation steps need a public repository, or a private one on + GitHub Enterprise Cloud: on the Free, Pro and Team plans GitHub offers + artifact attestations for public repositories only, so in a private + repository on those plans the attest steps fail and the release stays a + draft. 4. Run `.github/workflows/publish.yml` from the tag (`gh workflow run publish.yml --ref v0.2.0`). It checks the tag against diff --git a/templates/base/files/README.md b/templates/base/files/README.md index 3594f31..bc5342e 100644 --- a/templates/base/files/README.md +++ b/templates/base/files/README.md @@ -88,6 +88,27 @@ right one automatically. Needs Rust @@msrv@@ or newer. + + +### Linux runtime libraries + +Windows needs nothing extra. On Linux the window needs system libraries +that a minimal install or a container may not have. On Debian or Ubuntu: + +- To build: `libxcb-render0-dev libxcb-shape0-dev libxcb-xfixes0-dev + libxkbcommon-dev` (the list in eframe's README). +- To run under X11 (including `xvfb`): `libxkbcommon-x11-0`. + +- A Vulkan driver, because wgpu renders through Vulkan on Linux: + `mesa-vulkan-drivers` (it includes a software renderer, so it also works + without a GPU). + +- An OpenGL driver, which the `egui_glow` renderer draws through (Mesa + provides one). + + +Without them the app fails at startup, before the window opens. + ## What's inside @@ -134,7 +155,7 @@ Needs Rust @@msrv@@ or newer. -- **Themes, or write your own.** A theme is thirteen colours in a TOML +- **Themes, or write your own.** A theme is eleven colours in a TOML file; everything else is derived, and every theme is checked against WCAG contrast as a test. diff --git a/templates/cli/files/src/config.rs b/templates/cli/files/src/config.rs index f4b2596..a5a49a0 100644 --- a/templates/cli/files/src/config.rs +++ b/templates/cli/files/src/config.rs @@ -47,7 +47,7 @@ pub struct Config { /// config directory (a stripped-down container, for one). #[must_use] pub fn config_path() -> Option { - dirs::config_dir().map(|dir| dir.join("@@name@@").join("config.toml")) + dirs::config_dir().map(|dir| dir.join(env!("CARGO_PKG_NAME")).join("config.toml")) } /// Loads the saved config, or the defaults if there is nothing readable. diff --git a/templates/cli/files/src/db.rs b/templates/cli/files/src/db.rs index 5068a61..b94f2d5 100644 --- a/templates/cli/files/src/db.rs +++ b/templates/cli/files/src/db.rs @@ -17,7 +17,7 @@ //! that records it in the `migrations` table, so a crash midway leaves the //! database at the previous version rather than half-upgraded, and //! reopening is always safe. To change the schema, add an entry to -//! [`MIGRATIONS`]; never edit one that has shipped. +//! `MIGRATIONS`; never edit one that has shipped. use anyhow::Context as _; diff --git a/templates/cli/files/src/main.rs b/templates/cli/files/src/main.rs index d02b94f..d28c28d 100644 --- a/templates/cli/files/src/main.rs +++ b/templates/cli/files/src/main.rs @@ -3,7 +3,7 @@ // Description: Entry point: hands the process arguments and stdout to the // library and turns its result into an exit code. // -// Dependencies: @@crate@@ (the library), anyhow +// Dependencies: the library crate, anyhow // ============================================================================ //! Entry point for `@@bin@@`. @@ -13,13 +13,15 @@ //! returned from `main` prints its whole context chain to stderr and exits //! with code 1. +use @@crate@@ as app; + // @if async_tokio #[tokio::main] async fn main() -> anyhow::Result { - @@crate@@::run(std::env::args_os(), &mut std::io::stdout().lock()).await + app::run(std::env::args_os(), &mut std::io::stdout().lock()).await } // @else fn main() -> anyhow::Result { - @@crate@@::run(std::env::args_os(), &mut std::io::stdout().lock()) + app::run(std::env::args_os(), &mut std::io::stdout().lock()) } // @end diff --git a/templates/cli/files/tests/cli.rs b/templates/cli/files/tests/cli.rs index e8cd5c1..889cb39 100644 --- a/templates/cli/files/tests/cli.rs +++ b/templates/cli/files/tests/cli.rs @@ -3,7 +3,7 @@ // Description: End-to-end checks of the command line, through the same // entry point the binary calls. // -// Dependencies: @@crate@@ (the library), anyhow +// Dependencies: the library crate, anyhow // ============================================================================ //! End-to-end checks of the command line. @@ -14,32 +14,37 @@ use std::process::ExitCode; +use @@crate@@ as app; + /// Exit code 0, named for the assertions below. const SUCCESS: ExitCode = ExitCode::SUCCESS; + +/// The program name, the first argument the parser sees. +const BIN: &str = "@@bin@@"; // @if async_tokio /// Runs the program with `args` and returns its exit code and stdout. async fn run(args: &[&str]) -> anyhow::Result<(ExitCode, String)> { let mut out = Vec::new(); - let code = @@crate@@::run(args.iter().copied(), &mut out).await?; + let code = app::run(args.iter().copied(), &mut out).await?; Ok((code, String::from_utf8(out)?)) } #[tokio::test] async fn the_default_action_greets() -> anyhow::Result<()> { - let (code, out) = run(&["@@bin@@"]).await?; + let (code, out) = run(&[BIN]).await?; // @else /// Runs the program with `args` and returns its exit code and stdout. fn run(args: &[&str]) -> anyhow::Result<(ExitCode, String)> { let mut out = Vec::new(); - let code = @@crate@@::run(args.iter().copied(), &mut out)?; + let code = app::run(args.iter().copied(), &mut out)?; Ok((code, String::from_utf8(out)?)) } #[test] fn the_default_action_greets() -> anyhow::Result<()> { - let (code, out) = run(&["@@bin@@"])?; + let (code, out) = run(&[BIN])?; // @end assert_eq!(code, SUCCESS, "a bare run succeeds"); assert!(out.ends_with("!\n"), "one line: {out:?}"); @@ -50,11 +55,11 @@ fn the_default_action_greets() -> anyhow::Result<()> { // @if async_tokio #[tokio::test] async fn a_name_is_greeted() -> anyhow::Result<()> { - let (code, out) = run(&["@@bin@@", "--name", "Ferris"]).await?; + let (code, out) = run(&[BIN, "--name", "Ferris"]).await?; // @else #[test] fn a_name_is_greeted() -> anyhow::Result<()> { - let (code, out) = run(&["@@bin@@", "--name", "Ferris"])?; + let (code, out) = run(&[BIN, "--name", "Ferris"])?; // @end assert_eq!(code, SUCCESS, "a valid flag succeeds"); assert!(out.contains("Ferris"), "--name is used: {out:?}"); @@ -64,11 +69,11 @@ fn a_name_is_greeted() -> anyhow::Result<()> { // @if async_tokio #[tokio::test] async fn an_unknown_flag_is_a_usage_error() -> anyhow::Result<()> { - let (code, out) = run(&["@@bin@@", "--no-such-flag"]).await?; + let (code, out) = run(&[BIN, "--no-such-flag"]).await?; // @else #[test] fn an_unknown_flag_is_a_usage_error() -> anyhow::Result<()> { - let (code, out) = run(&["@@bin@@", "--no-such-flag"])?; + let (code, out) = run(&[BIN, "--no-such-flag"])?; // @end assert_eq!(code, ExitCode::from(2), "usage errors exit 2"); assert!(out.is_empty(), "nothing ran: {out:?}"); @@ -78,11 +83,11 @@ fn an_unknown_flag_is_a_usage_error() -> anyhow::Result<()> { // @if async_tokio #[tokio::test] async fn version_is_not_an_error() -> anyhow::Result<()> { - let (code, _) = run(&["@@bin@@", "--version"]).await?; + let (code, _) = run(&[BIN, "--version"]).await?; // @else #[test] fn version_is_not_an_error() -> anyhow::Result<()> { - let (code, _) = run(&["@@bin@@", "--version"])?; + let (code, _) = run(&[BIN, "--version"])?; // @end assert_eq!(code, SUCCESS, "--version exits 0"); Ok(()) @@ -92,11 +97,11 @@ fn version_is_not_an_error() -> anyhow::Result<()> { // @if async_tokio #[tokio::test] async fn arguments_are_ignored_without_a_parser() -> anyhow::Result<()> { - let (code, out) = run(&["@@bin@@", "--anything"]).await?; + let (code, out) = run(&[BIN, "--anything"]).await?; // @else #[test] fn arguments_are_ignored_without_a_parser() -> anyhow::Result<()> { - let (code, out) = run(&["@@bin@@", "--anything"])?; + let (code, out) = run(&[BIN, "--anything"])?; // @end assert_eq!(code, SUCCESS, "every run succeeds"); assert!(!out.is_empty(), "the default runs: {out:?}"); diff --git a/templates/cli/files/tests/cli_subcommands.rs b/templates/cli/files/tests/cli_subcommands.rs index 8ceeace..658e462 100644 --- a/templates/cli/files/tests/cli_subcommands.rs +++ b/templates/cli/files/tests/cli_subcommands.rs @@ -3,7 +3,7 @@ // Description: End-to-end checks of the command line, through the same // entry point the binary calls. // -// Dependencies: @@crate@@ (the library), anyhow +// Dependencies: the library crate, anyhow // ============================================================================ //! End-to-end checks of the command line. @@ -14,9 +14,14 @@ use std::process::ExitCode; +use @@crate@@ as app; + /// Exit code 0, named for the assertions below. const SUCCESS: ExitCode = ExitCode::SUCCESS; +/// The program name, the first argument the parser sees. +const BIN: &str = "@@bin@@"; + /// Exit code 2: the arguments were refused. fn usage_error() -> ExitCode { ExitCode::from(2) @@ -26,25 +31,25 @@ fn usage_error() -> ExitCode { /// Runs the program with `args` and returns its exit code and stdout. async fn run(args: &[&str]) -> anyhow::Result<(ExitCode, String)> { let mut out = Vec::new(); - let code = @@crate@@::run(args.iter().copied(), &mut out).await?; + let code = app::run(args.iter().copied(), &mut out).await?; Ok((code, String::from_utf8(out)?)) } #[tokio::test] async fn a_bare_run_is_a_usage_error() -> anyhow::Result<()> { - let (code, out) = run(&["@@bin@@"]).await?; + let (code, out) = run(&[BIN]).await?; // @else /// Runs the program with `args` and returns its exit code and stdout. fn run(args: &[&str]) -> anyhow::Result<(ExitCode, String)> { let mut out = Vec::new(); - let code = @@crate@@::run(args.iter().copied(), &mut out)?; + let code = app::run(args.iter().copied(), &mut out)?; Ok((code, String::from_utf8(out)?)) } #[test] fn a_bare_run_is_a_usage_error() -> anyhow::Result<()> { - let (code, out) = run(&["@@bin@@"])?; + let (code, out) = run(&[BIN])?; // @end assert_eq!(code, usage_error(), "a subcommand is required"); assert!(out.is_empty(), "nothing ran: {out:?}"); @@ -54,11 +59,11 @@ fn a_bare_run_is_a_usage_error() -> anyhow::Result<()> { // @if async_tokio #[tokio::test] async fn hello_greets_the_named_person() -> anyhow::Result<()> { - let (code, out) = run(&["@@bin@@", "hello", "--name", "Ferris"]).await?; + let (code, out) = run(&[BIN, "hello", "--name", "Ferris"]).await?; // @else #[test] fn hello_greets_the_named_person() -> anyhow::Result<()> { - let (code, out) = run(&["@@bin@@", "hello", "--name", "Ferris"])?; + let (code, out) = run(&[BIN, "hello", "--name", "Ferris"])?; // @end assert_eq!(code, SUCCESS, "hello succeeds"); assert!(out.contains("Ferris"), "--name is used: {out:?}"); @@ -68,11 +73,11 @@ fn hello_greets_the_named_person() -> anyhow::Result<()> { // @if async_tokio #[tokio::test] async fn sum_prints_the_total() -> anyhow::Result<()> { - let (code, out) = run(&["@@bin@@", "sum", "2", "40", "-5"]).await?; + let (code, out) = run(&[BIN, "sum", "2", "40", "-5"]).await?; // @else #[test] fn sum_prints_the_total() -> anyhow::Result<()> { - let (code, out) = run(&["@@bin@@", "sum", "2", "40", "-5"])?; + let (code, out) = run(&[BIN, "sum", "2", "40", "-5"])?; // @end assert_eq!(code, SUCCESS, "sum succeeds"); assert_eq!(out, "37\n", "the total, on its own line"); @@ -83,12 +88,12 @@ fn sum_prints_the_total() -> anyhow::Result<()> { #[tokio::test] async fn sum_reports_overflow_as_an_error() -> anyhow::Result<()> { let max = i64::MAX.to_string(); - let result = run(&["@@bin@@", "sum", &max, "1"]).await; + let result = run(&[BIN, "sum", &max, "1"]).await; // @else #[test] fn sum_reports_overflow_as_an_error() -> anyhow::Result<()> { let max = i64::MAX.to_string(); - let result = run(&["@@bin@@", "sum", &max, "1"]); + let result = run(&[BIN, "sum", &max, "1"]); // @end assert!(result.is_err(), "overflow fails, it never wraps"); Ok(()) @@ -97,11 +102,11 @@ fn sum_reports_overflow_as_an_error() -> anyhow::Result<()> { // @if async_tokio #[tokio::test] async fn sum_rejects_a_non_number() -> anyhow::Result<()> { - let (code, out) = run(&["@@bin@@", "sum", "two"]).await?; + let (code, out) = run(&[BIN, "sum", "two"]).await?; // @else #[test] fn sum_rejects_a_non_number() -> anyhow::Result<()> { - let (code, out) = run(&["@@bin@@", "sum", "two"])?; + let (code, out) = run(&[BIN, "sum", "two"])?; // @end assert_eq!(code, usage_error(), "clap refuses it before anything runs"); assert!(out.is_empty(), "nothing ran: {out:?}"); @@ -111,11 +116,11 @@ fn sum_rejects_a_non_number() -> anyhow::Result<()> { // @if async_tokio #[tokio::test] async fn version_is_not_an_error() -> anyhow::Result<()> { - let (code, _) = run(&["@@bin@@", "--version"]).await?; + let (code, _) = run(&[BIN, "--version"]).await?; // @else #[test] fn version_is_not_an_error() -> anyhow::Result<()> { - let (code, _) = run(&["@@bin@@", "--version"])?; + let (code, _) = run(&[BIN, "--version"])?; // @end assert_eq!(code, SUCCESS, "--version exits 0"); Ok(()) diff --git a/templates/github/files/_github/workflows/ci.yml b/templates/github/files/_github/workflows/ci.yml index 92891b1..af9a8fb 100644 --- a/templates/github/files/_github/workflows/ci.yml +++ b/templates/github/files/_github/workflows/ci.yml @@ -36,7 +36,13 @@ jobs: # risk the moment the workflow holds a write-capable token. Update # deliberately, with a diff of the new SHA, not silently on the next # run. The versions are in the trailing comments. + # + # `persist-credentials: false` everywhere: no step pushes or tags, so + # the token checkout would otherwise leave in .git/config is only + # something a build script could read. - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false # The version matches rust-toolchain.toml, so CI and a local checkout # run the same rustfmt and the same clippy. `@stable` would mean CI # silently moving to each new release on its own. @@ -56,6 +62,8 @@ jobs: # downloads the advisory database and scans the lockfile. steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false - uses: EmbarkStudios/cargo-deny-action@3c6349835b2b7b196a839186cb8b78e02f7b5f25 # v2.1.1 with: command: check @@ -72,6 +80,8 @@ jobs: # @end steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false - uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # master, 2026-10 with: @@ -123,6 +133,8 @@ jobs: # @end steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false - uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # master, 2026-10 with: diff --git a/templates/github/files/_github/workflows/publish.yml b/templates/github/files/_github/workflows/publish.yml index 118a87a..84cba86 100644 --- a/templates/github/files/_github/workflows/publish.yml +++ b/templates/github/files/_github/workflows/publish.yml @@ -31,6 +31,8 @@ jobs: timeout-minutes: 30 steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false - uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # master, 2026-10 with: diff --git a/templates/github/files/_github/workflows/release.yml b/templates/github/files/_github/workflows/release.yml index f438014..62e6edc 100644 --- a/templates/github/files/_github/workflows/release.yml +++ b/templates/github/files/_github/workflows/release.yml @@ -48,9 +48,13 @@ jobs: TAG: ${{ inputs.tag || github.ref_name }} run: echo "tag=${TAG}" >> "$GITHUB_OUTPUT" + # Every checkout here drops its credential: nothing pushes or tags + # through git, and `gh` authenticates with `GH_TOKEN`, not with the + # token checkout would otherwise leave in .git/config. - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: ref: ${{ steps.resolve.outputs.tag }} + persist-credentials: false # A tag that disagrees with Cargo.toml would ship a binary whose # `--version` contradicts its release page, and cannot be fixed @@ -100,8 +104,12 @@ jobs: fail-fast: false matrix: include: - # The matrix stays a matrix so adding a target later is an entry - # rather than a rewrite. + # One target today, kept as a matrix so another can be added + # without restructuring the job. An entry alone is not enough: + # Package copies a hard-coded `.exe` and zips with `7z`, and the + # SBOM file name carries no target, so a second entry would + # collide with this one's at publish. Parameterise all three + # before adding a target. - os: windows-latest target: x86_64-pc-windows-msvc steps: @@ -111,15 +119,16 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: ref: ${{ needs.draft.outputs.tag }} + persist-credentials: false - uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # master, 2026-10 with: toolchain: "@@toolchain@@" targets: ${{ matrix.target }} - - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 - with: - key: release-${{ matrix.target }} + # No build cache, deliberately: the Actions cache is written by any + # branch's CI, so a release that restored it could ship whatever a + # poisoned entry put there. A release builds from scratch. - name: Build # @if workspace @@ -231,6 +240,7 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: ref: ${{ needs.draft.outputs.tag }} + persist-credentials: false - name: Download archives uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 diff --git a/templates/guards/files/examples/changelog.rs b/templates/guards/files/examples/changelog.rs index 4dd36d4..88dad1c 100644 --- a/templates/guards/files/examples/changelog.rs +++ b/templates/guards/files/examples/changelog.rs @@ -49,9 +49,12 @@ //! `.github/workflows/release.yml` owns. //! - **`--check` compares released sections only.** The `Unreleased` //! section is deliberately exempt, because its content changes with -//! every merge — and a squash or rebase rewrites the very hashes it -//! would be pinned to. Gating a pull request on it would fail every -//! pull request for no signal. +//! every merge. Gating a pull request on it would fail every pull +//! request for no signal. +//! - **`Unreleased` entries carry no commit hash.** A squash or rebase +//! rewrites hashes before they ship; released entries link theirs. It +//! also lets the scaffolded file, written before its own commit +//! existed, match what this generates from that first commit. //! //! - **A version tag no branch can reach is a hard error under `--check`.** //! Each release is computed as `..`, so a tag left pointing @@ -75,8 +78,24 @@ use anyhow::{Context, Result, bail}; const CHANGELOG: &str = "CHANGELOG.md"; /// Used to build the commit and compare links. Taken from `Cargo.toml`'s -/// `repository` field rather than guessed. -const REPO: &str = "https://github.com/@@github@@/@@name@@"; +/// `repository` field rather than guessed. Split so the line stays within +/// rustfmt's width for any project name. +const REPO: &str = "https://github.com/\ + @@github@@/@@name@@"; + +/// Everything above the `Unreleased` heading. The scaffolded +/// `CHANGELOG.md` opens with exactly this text, so a fresh project already +/// matches its own history. +const PREAMBLE: &str = "# Changelog\n\ + \n\ + All notable changes to @@name@@, newest first.\n\ + \n\ + **This file is generated.** It is rebuilt from the git history by\n\ + `cargo run --example changelog`, so released sections are rewritten in\n\ + place and edits to them do not survive. See `CONTRIBUTING.md`.\n\ + \n\ + The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),\n\ + and the project follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html).\n"; /// Heading for commits that have not shipped in a tagged release yet. const UNRELEASED: &str = "## [Unreleased]"; @@ -582,17 +601,7 @@ fn parse_subject(hash: &str, short: &str, subject: &str) -> Commit { fn render(releases: &[Release], unreleased: &[Commit]) -> String { let mut out = String::new(); - out.push_str("# Changelog\n\n"); - out.push_str("All notable changes to @@name@@, newest first.\n\n"); - out.push_str( - "**This file is generated.** It is rebuilt from the git history by\n\ - `cargo run --example changelog`, so released sections are rewritten in\n\ - place and edits to them do not survive. See `CONTRIBUTING.md`.\n\n", - ); - out.push_str( - "The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),\n\ - and the project follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html).\n", - ); + out.push_str(PREAMBLE); out.push('\n'); out.push_str(UNRELEASED); @@ -600,7 +609,7 @@ fn render(releases: &[Release], unreleased: &[Commit]) -> String { if unreleased.is_empty() { out.push_str("\nNothing yet — the latest release is the tip of `main`.\n"); } else { - push_sections(&mut out, unreleased); + push_sections(&mut out, unreleased, false); } for release in releases { @@ -608,7 +617,7 @@ fn render(releases: &[Release], unreleased: &[Commit]) -> String { if release.commits.is_empty() { out.push_str("\nNo commits recorded against this tag.\n"); } else { - push_sections(&mut out, &release.commits); + push_sections(&mut out, &release.commits, true); } } @@ -617,8 +626,10 @@ fn render(releases: &[Release], unreleased: &[Commit]) -> String { } /// The `### Heading` blocks for one release, in `SECTIONS` order, skipping -/// any heading nothing landed under. -fn push_sections(out: &mut String, commits: &[Commit]) { +/// any heading nothing landed under. `linked` adds each commit's short +/// hash and a link to it; the `Unreleased` section goes without, because +/// a squash or rebase rewrites those hashes before they ship. +fn push_sections(out: &mut String, commits: &[Commit], linked: bool) { let mut order: Vec<&str> = vec![BREAKING]; order.extend(SECTIONS.iter().map(|(heading, _)| *heading)); order.push(OTHER); @@ -634,10 +645,14 @@ fn push_sections(out: &mut String, commits: &[Commit]) { Some(scope) => format!("**{scope}:** "), None => String::new(), }; - out.push_str(&format!( - "- {scope}{} ([`{}`]({REPO}/commit/{}))\n", - commit.summary, commit.short, commit.hash - )); + if linked { + out.push_str(&format!( + "- {scope}{} ([`{}`]({REPO}/commit/{}))\n", + commit.summary, commit.short, commit.hash + )); + } else { + out.push_str(&format!("- {scope}{}\n", commit.summary)); + } } } } diff --git a/templates/guards/files/src/header_check.rs b/templates/guards/files/src/header_check.rs index 1a782e6..c25bfdd 100644 --- a/templates/guards/files/src/header_check.rs +++ b/templates/guards/files/src/header_check.rs @@ -51,7 +51,9 @@ mod tests { const REQUIRED: [&str; 3] = ["Module", "Description", "Dependencies"]; /// rustfmt's default `max_width`. A header that runs past it wraps in - /// an editor and stops lining up, which is the whole point of it. + /// an editor and stops lining up, which is the whole point of it. The + /// `Module:` line is exempt: its value is the file's path, which a long + /// crate name can push past the limit and nothing in the file can shorten. const MAX_WIDTH: usize = 100; /// Every `.rs` file under `root`, found iteratively. @@ -175,7 +177,7 @@ mod tests { "{relative}: non-comment line inside header: {line}" )); } - if line.chars().count() > MAX_WIDTH { + if line.chars().count() > MAX_WIDTH && !line.starts_with("// Module:") { found.push(format!( "{relative}: header line exceeds {MAX_WIDTH} columns" )); @@ -402,4 +404,25 @@ mod tests { ); Ok(()) } + + #[test] + fn a_long_module_line_is_not_a_width_problem() -> Result<()> { + // The Module value is the file's path; a long crate name can push it + // past the width, and nothing in the file could shorten it. + let long = "x".repeat(MAX_WIDTH); + let text = format!( + "{RULE}\n\ + // Module: {long}::color\n\ + // Description: Colour maths.\n\ + //\n\ + // Dependencies: None.\n\ + {RULE}\n" + ); + let found = problems("src/color.rs", &text); + assert!( + !found.iter().any(|problem| problem.contains("columns")), + "got {found:?}" + ); + Ok(()) + } } diff --git a/templates/guards/files/src/unsafe_check.rs b/templates/guards/files/src/unsafe_check.rs index 3a9255d..0ce199e 100644 --- a/templates/guards/files/src/unsafe_check.rs +++ b/templates/guards/files/src/unsafe_check.rs @@ -9,9 +9,13 @@ //! //! Compiler lints verify local mechanics such as safety comments. This //! test enforces repository-level rules the compiler cannot express: -//! unsafe stays under `src/win/` or `src/gui/run/`, tests never need it, and unsafe APIs -//! are forbidden, and one function cannot accumulate multiple unsafe -//! operations. +// @if gui_winit_glow +//! unsafe stays under `src/win/` or `src/gui/run/`, tests never need it, +// @else +//! unsafe stays under `src/win/`, tests never need it, +// @end +//! unsafe APIs are forbidden, and one function cannot accumulate multiple +//! unsafe operations. #[cfg(test)] mod tests { @@ -20,6 +24,13 @@ mod tests { use std::fs; use std::path::{Path, PathBuf}; + /// Where unsafe code may live, as the failure message names it. + // @if gui_winit_glow + const ALLOWED: &str = "src/win/ or src/gui/run/"; + // @else + const ALLOWED: &str = "src/win/"; + // @end + /// Finds every Rust source below `root`. fn rust_sources(root: &Path) -> Result> { let mut pending = vec![root.to_path_buf()]; @@ -85,9 +96,7 @@ mod tests { } let location = format!("{relative}:{}", index + 1); if !relative.starts_with("src/win/") && !relative.starts_with("src/gui/run/") { - failures.push(format!( - "{location}: unsafe code must live under src/win/ or src/gui/run/" - )); + failures.push(format!("{location}: unsafe code must live under {ALLOWED}")); } if test_start.is_some_and(|start| index > start) { failures.push(format!("{location}: test code must use safe wrappers")); diff --git a/templates/gui-features/files/src/tray.rs b/templates/gui-features/files/src/tray.rs index 0afda93..4711dea 100644 --- a/templates/gui-features/files/src/tray.rs +++ b/templates/gui-features/files/src/tray.rs @@ -8,7 +8,7 @@ //! The tray icon. //! -//! On Windows the icon lives in [`crate::win::tray`]: a left click restores +//! On Windows the icon lives in `crate::win::tray`: a left click restores //! and focuses the window, a right click offers Open and Exit, and Exit //! closes the window the way its own close button does, so the app still //! shuts down normally and saves its preferences. Elsewhere there is no diff --git a/templates/gui-features/files/src/win/single_instance.rs b/templates/gui-features/files/src/win/single_instance.rs index d978e74..48307af 100644 --- a/templates/gui-features/files/src/win/single_instance.rs +++ b/templates/gui-features/files/src/win/single_instance.rs @@ -79,7 +79,7 @@ mod tests { #[test] fn a_second_claim_is_refused_until_the_first_is_released() { - let id = format!("@@name@@-test-{}", std::process::id()); + let id = format!("{}-test-{}", crate::APP_ID, std::process::id()); let first = acquire(&id); assert!(first.is_some(), "the first claim must succeed"); assert!(acquire(&id).is_none(), "a second claim must be refused"); diff --git a/templates/gui/files/build.rs b/templates/gui/files/build.rs index b655dfe..ebb097a 100644 --- a/templates/gui/files/build.rs +++ b/templates/gui/files/build.rs @@ -25,9 +25,17 @@ //! Release builds fail if the resources cannot be embedded: a distributable //! binary without its manifest is not a valid release. +/// The project name: the icon and manifest under `assets/` are named after it. +const NAME: &str = "@@name@@"; + +/// The product name Explorer, Task Manager and the Properties dialog show. +const PRODUCT: &str = "@@displayName@@"; + fn main() { - println!("cargo:rerun-if-changed=assets/@@name@@.ico"); - println!("cargo:rerun-if-changed=assets/@@name@@.manifest"); + let icon = format!("assets/{NAME}.ico"); + let manifest = format!("assets/{NAME}.manifest"); + println!("cargo:rerun-if-changed={icon}"); + println!("cargo:rerun-if-changed={manifest}"); println!("cargo:rerun-if-changed=build.rs"); // The *target*, not the host: `cfg(windows)` in a build script describes @@ -36,12 +44,12 @@ fn main() { return; } let mut resource = winresource::WindowsResource::new(); - resource.set_icon("assets/@@name@@.ico"); - resource.set_manifest_file("assets/@@name@@.manifest"); + resource.set_icon(&icon); + resource.set_manifest_file(&manifest); // `FileDescription` is what Task Manager and Explorer show as the // program's name, so it holds the product name, not a sentence. - resource.set("ProductName", "@@displayName@@"); - resource.set("FileDescription", "@@displayName@@"); + resource.set("ProductName", PRODUCT); + resource.set("FileDescription", PRODUCT); resource.set("Comments", env!("CARGO_PKG_DESCRIPTION")); resource.set("LegalCopyright", "Copyright (c) @@year@@ @@author@@"); diff --git a/templates/gui/files/examples/brand_assets.rs b/templates/gui/files/examples/brand_assets.rs index 0ef28af..b255e3a 100644 --- a/templates/gui/files/examples/brand_assets.rs +++ b/templates/gui/files/examples/brand_assets.rs @@ -3,7 +3,7 @@ // Description: Writes the mark's derived files: the multi-size .ico that // build.rs embeds in the executable. // -// Dependencies: @@appCrateSnake@@::brand (the geometry and the rasteriser); std only +// Dependencies: the library crate's brand module (the geometry and the rasteriser); std only // ============================================================================ //! `cargo run --example brand_assets` @@ -18,6 +18,8 @@ use std::path::Path; +use @@appCrateSnake@@::brand; + /// The sizes Windows picks from: title bar, taskbar, Explorer, Alt-Tab. const SIZES: [u32; 5] = [16, 24, 32, 48, 64]; @@ -27,7 +29,7 @@ fn main() -> anyhow::Result<()> { .join("@@name@@.ico"); let images: Vec<(u32, Vec)> = SIZES .iter() - .map(|&edge| (edge, @@appCrateSnake@@::brand::rasterise(edge))) + .map(|&edge| (edge, brand::rasterise(edge))) .collect(); std::fs::write(&out, ico(&images)?)?; println!("wrote {}", out.display()); diff --git a/templates/gui/files/examples/screenshot.rs b/templates/gui/files/examples/screenshot.rs index 82d627e..6c1db9a 100644 --- a/templates/gui/files/examples/screenshot.rs +++ b/templates/gui/files/examples/screenshot.rs @@ -15,7 +15,9 @@ //! on demand, and a directory of stale committed PNGs is what makes someone //! trust a picture that is three changes out of date. -use @@appCrateSnake@@::gui::app::{Action, App, Page}; +use @@appCrateSnake@@::gui; + +use gui::app::{Action, App, Page}; fn main() -> anyhow::Result<()> { let out = std::env::args().nth(1).map_or_else( @@ -27,7 +29,7 @@ fn main() -> anyhow::Result<()> { std::path::PathBuf::from, ); std::fs::create_dir_all(&out)?; - let [width, height] = @@appCrateSnake@@::gui::DEFAULT_SIZE; + let [width, height] = gui::DEFAULT_SIZE; for page in Page::ALL { let mut harness = egui_kittest::Harness::builder() .with_size(egui::vec2(width, height)) @@ -35,7 +37,7 @@ fn main() -> anyhow::Result<()> { |ui, app: &mut Option| { let app = app.get_or_insert_with(|| { // @if config - let mut app = App::new(ui.ctx(), @@appCrateSnake@@::config::Config::default()); + let mut app = App::new(ui.ctx(), Default::default()); // @else let mut app = App::new(ui.ctx()); // @end diff --git a/templates/gui/files/src/cli.rs b/templates/gui/files/src/cli.rs index 5ec2abb..e12aefe 100644 --- a/templates/gui/files/src/cli.rs +++ b/templates/gui/files/src/cli.rs @@ -156,7 +156,8 @@ impl Cli { "-h" | "--help" => return Ok(Parsed::Print(help())), "-V" | "--version" => { return Ok(Parsed::Print(format!( - "@@name@@ {}", + "{} {}", + crate::APP_ID, env!("CARGO_PKG_VERSION") ))); } @@ -177,8 +178,9 @@ impl Cli { /// The `--help` text. fn help() -> String { let mut text = format!( - "{}\n\nUsage: @@name@@ [OPTIONS]\n\nOptions:\n", - crate::TAGLINE + "{}\n\nUsage: {} [OPTIONS]\n\nOptions:\n", + crate::TAGLINE, + crate::APP_ID ); // @if config // @if themes @@ -198,9 +200,12 @@ mod tests { // @if clap use clap::Parser as _; + /// The program name the parser sees first. + const BIN: &str = "@@bin@@"; + /// Parses `args` after a program name. fn parse(args: &[&str]) -> Result { - Cli::try_parse_from(std::iter::once("@@bin@@").chain(args.iter().copied())) + Cli::try_parse_from(std::iter::once(BIN).chain(args.iter().copied())) } // @else diff --git a/templates/gui/files/src/config.rs b/templates/gui/files/src/config.rs index 1d8661e..38fd9d5 100644 --- a/templates/gui/files/src/config.rs +++ b/templates/gui/files/src/config.rs @@ -175,7 +175,8 @@ mod tests { #[test] fn a_save_replaces_the_previous_file_and_leaves_no_temporary() -> anyhow::Result<()> { - let dir = std::env::temp_dir().join(format!("@@name@@-config-{}", std::process::id())); + let name = format!("{}-config-{}", crate::APP_ID, std::process::id()); + let dir = std::env::temp_dir().join(name); let path = dir.join("config.toml"); for theme in ["first", "second"] { let config = Config { diff --git a/templates/gui/files/src/gui/app/mod.rs b/templates/gui/files/src/gui/app/mod.rs index 448637b..1fa5f4b 100644 --- a/templates/gui/files/src/gui/app/mod.rs +++ b/templates/gui/files/src/gui/app/mod.rs @@ -19,8 +19,19 @@ //! 3. on a normal quit, calls [`App::on_exit`]. //! //! Every change of state a user can cause goes through [`Action`] and +// @if tray & commandPalette //! [`App::apply`], so a shortcut, a button, the tray menu and the command //! palette cannot drift apart in what "open settings" means. +// @elif tray +//! [`App::apply`], so a shortcut, a button and the tray menu cannot drift +//! apart in what "open settings" means. +// @elif commandPalette +//! [`App::apply`], so a shortcut, a button and the command palette cannot +//! drift apart in what "open settings" means. +// @else +//! [`App::apply`], so a shortcut and a button cannot drift apart in what +//! "open settings" means. +// @end use crate::gui::ui::{self, glyph}; use crate::theme::Palette; diff --git a/templates/gui/files/src/gui/run.rs b/templates/gui/files/src/gui/run.rs index 99bcc4b..99dccc2 100644 --- a/templates/gui/files/src/gui/run.rs +++ b/templates/gui/files/src/gui/run.rs @@ -10,14 +10,14 @@ //! The runtime. //! //! The only file in the crate that names eframe. [`run`] opens the window -//! and hands each frame to [`App`](super::app::App), which uses egui alone. +//! and hands each frame to [`App`], which uses egui alone. //! //! ## eframe on wgpu, not glow //! //! eframe's glow path goes through WGL on Windows, which fails on machines //! with a stale or hybrid OpenGL driver — common on switchable-graphics //! laptops. wgpu talks to D3D12 instead, and on Windows it is pinned to -//! D3D12 alone ([`backends`]): leaving Vulkan in the set lets wgpu pick a +//! D3D12 alone (`backends`): leaving Vulkan in the set lets wgpu pick a //! vendor ICD, which is the same class of driver the switch away from GL was //! made to avoid. `WGPU_BACKEND` still overrides it. diff --git a/templates/gui/files/src/gui/ui/mod.rs b/templates/gui/files/src/gui/ui/mod.rs index fc40cda..f14ae53 100644 --- a/templates/gui/files/src/gui/ui/mod.rs +++ b/templates/gui/files/src/gui/ui/mod.rs @@ -229,7 +229,11 @@ fn shortcuts(ui: &Ui, actions: &mut Vec) { } /// Ctrl+1, Ctrl+2, … open the pages in sidebar order, so a new page gets +// @if commandPalette /// its shortcut (and its command palette entry) without further wiring. +// @else +/// its shortcut without further wiring. +// @end const PAGE_KEYS: [Key; 9] = [ Key::Num1, Key::Num2, diff --git a/templates/gui/files/src/main.rs b/templates/gui/files/src/main.rs index 9949ea1..86cc269 100644 --- a/templates/gui/files/src/main.rs +++ b/templates/gui/files/src/main.rs @@ -3,7 +3,7 @@ // Description: Entry point: parses the command line, loads preferences, and // hands off to the desktop front end. // -// Dependencies: anyhow; @@appCrateSnake@@::{cli, gui} +// Dependencies: anyhow; the library crate (cli, gui) // ============================================================================ // No console window behind the GUI in a release build: Windows gives a @@ -36,6 +36,7 @@ //! startup failure would look like the program refusing to open. See //! [`report`]. +use @@appCrateSnake@@ as app; use @@appCrateSnake@@::cli::Cli; fn main() -> std::process::ExitCode { @@ -61,8 +62,8 @@ fn main() -> std::process::ExitCode { }; // @else let cli = match Cli::parse_from(std::env::args().skip(1)) { - Ok(@@appCrateSnake@@::cli::Parsed::Run(cli)) => cli, - Ok(@@appCrateSnake@@::cli::Parsed::Print(text)) => { + Ok(app::cli::Parsed::Run(cli)) => cli, + Ok(app::cli::Parsed::Print(text)) => { borrow_console(); println!("{text}"); return std::process::ExitCode::SUCCESS; @@ -89,10 +90,10 @@ fn main() -> std::process::ExitCode { // A second launch hands focus to the first window and leaves, rather // than opening a second copy that fights the first over the config file. #[cfg(windows)] - let _instance = match @@appCrateSnake@@::win::single_instance::acquire(@@appCrateSnake@@::APP_ID) { + let _instance = match app::win::single_instance::acquire(app::APP_ID) { Some(guard) => guard, None => { - @@appCrateSnake@@::win::single_instance::focus_existing(@@appCrateSnake@@::NAME); + app::win::single_instance::focus_existing(app::NAME); return std::process::ExitCode::SUCCESS; } }; @@ -113,13 +114,13 @@ fn main() -> std::process::ExitCode { /// to a console is closed with it and gets its Ctrl+C. fn borrow_console() { #[cfg(windows)] - @@appCrateSnake@@::win::console::attach_parent(); + app::win::console::attach_parent(); } // @if subcommands /// Runs a headless job. A failure goes to stderr only: the caller is a /// terminal or a script, not someone looking for a dialog. -fn headless(command: @@appCrateSnake@@::cli::Command) -> std::process::ExitCode { +fn headless(command: app::cli::Command) -> std::process::ExitCode { match command.run(&mut std::io::stdout().lock()) { Ok(()) => std::process::ExitCode::SUCCESS, Err(error) => { @@ -134,9 +135,9 @@ fn headless(command: @@appCrateSnake@@::cli::Command) -> std::process::ExitCode fn run(cli: Cli) -> anyhow::Result<()> { // @if config let mut config = if cli.reset { - @@appCrateSnake@@::config::Config::default() + app::config::Config::default() } else { - @@appCrateSnake@@::config::load() + app::config::load() }; // @if themes if let Some(theme) = cli.theme { @@ -146,7 +147,7 @@ fn run(cli: Cli) -> anyhow::Result<()> { if let Some(font) = cli.font { config.font = Some(font); } - @@appCrateSnake@@::gui::run::run(config) + app::gui::run::run(config) // @else // @if subcommands // main() has taken any subcommand; only the window is left to open. @@ -154,7 +155,7 @@ fn run(cli: Cli) -> anyhow::Result<()> { // @else let Cli {} = cli; // @end - @@appCrateSnake@@::gui::run::run() + app::gui::run::run() // @end } @@ -166,5 +167,5 @@ fn run(cli: Cli) -> anyhow::Result<()> { fn report(message: &str) { eprintln!("{message}"); #[cfg(windows)] - @@appCrateSnake@@::win::dialog::show_error(message, @@appCrateSnake@@::NAME); + app::win::dialog::show_error(message, app::NAME); } diff --git a/templates/gui/files/tests/cli.rs b/templates/gui/files/tests/cli.rs index b0470a0..5c3c003 100644 --- a/templates/gui/files/tests/cli.rs +++ b/templates/gui/files/tests/cli.rs @@ -3,7 +3,7 @@ // Description: The command line's two paths: a bare run opens the window, // a subcommand runs a headless job. // -// Dependencies: @@appCrateSnake@@::cli, clap, anyhow +// Dependencies: the library crate's cli module, clap, anyhow // ============================================================================ //! The command line's two paths. @@ -14,9 +14,12 @@ use @@appCrateSnake@@::cli::{Cli, Command}; +/// The program name the parser sees first. +const BIN: &str = "@@bin@@"; + /// Parses `args` after a program name. fn parse(args: &[&str]) -> Result { - let argv = std::iter::once("@@bin@@").chain(args.iter().copied()); + let argv = std::iter::once(BIN).chain(args.iter().copied()); ::try_parse_from(argv) } diff --git a/templates/tui/deps.js b/templates/tui/deps.js index 36b7a18..8df91fc 100644 --- a/templates/tui/deps.js +++ b/templates/tui/deps.js @@ -1,10 +1,10 @@ // @ts-check /** - * The terminal UI stack. crossterm is pinned to the version ratatui 0.29 builds on, so - * both name the same `KeyEvent` type. + * The terminal UI stack. crossterm is pinned to the version ratatui 0.30's default backend + * (`crossterm_0_29`) builds on, so both name the same `KeyEvent` type. * @param {import('../../src/types.ts').Ctx} _ctx @returns {import('../../src/types.ts').Dep[]} */ export default (_ctx) => [ - { name: 'ratatui', version: '0.29' }, - { name: 'crossterm', version: '0.28' }, + { name: 'ratatui', version: '0.30' }, + { name: 'crossterm', version: '0.29' }, ]; diff --git a/templates/tui/files/src/logging.rs b/templates/tui/files/src/logging.rs index e164660..4dd4c13 100644 --- a/templates/tui/files/src/logging.rs +++ b/templates/tui/files/src/logging.rs @@ -26,7 +26,7 @@ use std::path::PathBuf; /// Where the log file goes. fn log_path() -> PathBuf { - std::env::temp_dir().join("@@name@@.log") + std::env::temp_dir().join(concat!(env!("CARGO_PKG_NAME"), ".log")) } /// Installs the file logger, unless one is already installed. diff --git a/templates/tui/files/src/main.rs b/templates/tui/files/src/main.rs index 638ca99..7ef096c 100644 --- a/templates/tui/files/src/main.rs +++ b/templates/tui/files/src/main.rs @@ -3,7 +3,7 @@ // Description: Entry point: hands the process arguments to the library and // turns its result into an exit code. // -// Dependencies: @@crate@@ (the library), anyhow +// Dependencies: the library crate, anyhow // ============================================================================ //! Entry point for `@@bin@@`. diff --git a/templates/workspace/files/crates/xtask/src/changelog.rs b/templates/workspace/files/crates/xtask/src/changelog.rs index c3196e3..4bbe765 100644 --- a/templates/workspace/files/crates/xtask/src/changelog.rs +++ b/templates/workspace/files/crates/xtask/src/changelog.rs @@ -9,11 +9,26 @@ //! Merge commits and commits touching only CHANGELOG.md are excluded. //! `--check` compares released entries only: Unreleased changes on every commit. //! Regeneration replaces the file, so release prose belongs in release notes. +//! Unreleased entries carry no hash, so the scaffolded file, written before +//! its own commit existed, is exactly what this generates from that commit. use anyhow::bail; use anyhow::{Context as _, Result}; use std::process::Command; +/// Everything above the Unreleased heading. The scaffolded `CHANGELOG.md` +/// opens with exactly this text. +const PREAMBLE: &str = "# Changelog\n\ + \n\ + All notable changes to @@name@@, newest first.\n\ + \n\ + **This file is generated.** It is rebuilt from the git history by\n\ + `cargo xtask changelog`, so released sections are rewritten in place and\n\ + edits to them do not survive. See `CONTRIBUTING.md`.\n\ + \n\ + The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),\n\ + and the project follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html).\n"; + const HEADINGS: &[&str] = &[ "Breaking changes", "Added", @@ -89,7 +104,10 @@ fn subject_parts(subject: &str) -> (&str, String) { (heading, summary) } -fn push_commits(out: &mut String, range: &str) -> Result<()> { +/// Appends the `### Heading` blocks for `range`. `hashed` adds each commit's +/// short hash; Unreleased goes without, because a squash or rebase rewrites +/// those hashes before they ship. +fn push_commits(out: &mut String, range: &str, hashed: bool) -> Result<()> { let log = git(&[ "log", "--no-merges", @@ -105,7 +123,12 @@ fn push_commits(out: &mut String, range: &str) -> Result<()> { .filter_map(|line| line.split_once('\u{1f}')) .map(|(hash, subject)| { let (heading, summary) = subject_parts(subject); - (heading, format!("- {summary} (`{hash}`)\n")) + let entry = if hashed { + format!("- {summary} (`{hash}`)\n") + } else { + format!("- {summary}\n") + }; + (heading, entry) }) .collect(); for heading in HEADINGS { @@ -147,17 +170,12 @@ pub(crate) fn run(check: bool) -> Result<()> { .filter_map(|tag| version(tag).map(|v| (v, tag))) .collect(); releases.sort_by_key(|entry| std::cmp::Reverse(entry.0)); - let mut out = String::from( - "# Changelog\n\n\ - All notable changes to @@name@@. Generated by `cargo xtask changelog`.\n\n\ - The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/)\n\ - and [Semantic Versioning](https://semver.org/spec/v2.0.0.html).\n\n\ - ## [Unreleased]\n", - ); + let mut out = String::from(PREAMBLE); + out.push_str("\n## [Unreleased]\n"); let range = releases .first() .map_or_else(|| "HEAD".to_owned(), |(_, tag)| format!("{tag}..HEAD")); - push_commits(&mut out, &range)?; + push_commits(&mut out, &range, false)?; for (index, (_, tag)) in releases.iter().enumerate() { let date = git(&["log", "-1", "--format=%cs", tag, "--"])?; out.push_str(&format!( @@ -168,7 +186,7 @@ pub(crate) fn run(check: bool) -> Result<()> { let range = releases .get(index + 1) .map_or_else(|| (*tag).to_owned(), |(_, prev)| format!("{prev}..{tag}")); - push_commits(&mut out, &range)?; + push_commits(&mut out, &range, true)?; } if check { let existing = std::fs::read_to_string("CHANGELOG.md") diff --git a/templates/workspace/files/crates/xtask/src/main.rs b/templates/workspace/files/crates/xtask/src/main.rs index 25a81fd..5c7b7c1 100644 --- a/templates/workspace/files/crates/xtask/src/main.rs +++ b/templates/workspace/files/crates/xtask/src/main.rs @@ -2,15 +2,24 @@ // Module: @@module@@ // Description: Workspace automation behind the cargo xtask alias. // +// @if changelogGen // Dependencies: anyhow; std; changelog and ci modules +// @else +// Dependencies: anyhow; std; the ci module +// @end // ============================================================================ //! Run repository automation from any directory inside the workspace. //! +// @if changelogGen //! `cargo xtask ci` checks the workspace; `cargo xtask changelog` regenerates //! CHANGELOG.md from conventional commits and reachable version tags. mod changelog; +// @else +//! `cargo xtask ci` checks the workspace. + +// @end mod ci; use anyhow::bail; @@ -21,7 +30,11 @@ use std::process::ExitCode; fn run() -> Result<()> { let args: Vec = std::env::args().skip(1).collect(); if args.is_empty() || matches!(args[0].as_str(), "--help" | "-h" | "help") { + // @if changelogGen println!("Usage: cargo xtask "); + // @else + println!("Usage: cargo xtask ci"); + // @end return Ok(()); } // Cargo's runtime manifest path also handles checkouts sharing a target dir. @@ -34,8 +47,10 @@ fn run() -> Result<()> { std::env::set_current_dir(root).context("could not enter the workspace root")?; match args[0].as_str() { "ci" if args.len() == 1 => ci::run(), + // @if changelogGen "changelog" if args.len() == 1 => changelog::run(false), "changelog" if args.len() == 2 && args[1] == "--check" => changelog::run(true), + // @end _ => bail!("unknown command or arguments; run `cargo xtask --help`"), } } diff --git a/templates/workspace/files/docs/decisions/D1.md b/templates/workspace/files/docs/decisions/D1.md index 2f080ae..2dccb2a 100644 --- a/templates/workspace/files/docs/decisions/D1.md +++ b/templates/workspace/files/docs/decisions/D1.md @@ -4,9 +4,14 @@ Keep the desktop app in `crates/@@appCrate@@` and repository automation in `crates/xtask`. The root manifest owns dependency versions, package metadata, lint policy and build profiles. Members inherit them instead of drifting apart. + `cargo xtask ci` runs the local checks; `cargo xtask changelog` rebuilds the changelog from conventional commits. A Rust tool works on Windows and Linux and is checked alongside the app by workspace builds. + +`cargo xtask ci` runs the local checks. A Rust tool works on Windows and Linux +and is checked alongside the app by workspace builds. + New reusable components can become sibling crates when a real boundary emerges. Do not split modules into crates solely to grow the workspace. diff --git a/templates/workspace/manifest.js b/templates/workspace/manifest.js new file mode 100644 index 0000000..9d08e9f --- /dev/null +++ b/templates/workspace/manifest.js @@ -0,0 +1,10 @@ +// @ts-check +/** + * The xtask `changelog` command regenerates CHANGELOG.md, so it ships only with `changelogGen`; + * without it the file is hand-edited and nothing may rewrite it. + * @param {import('../../src/types.ts').Ctx} ctx + * @param {{ src: string, dest: string }[]} files + */ +export default function (ctx, files) { + return files.filter(({ dest }) => dest !== 'crates/xtask/src/changelog.rs' || ctx.flags.has('changelogGen')); +} diff --git a/test/args.test.ts b/test/args.test.ts index 784ff2b..c7fcd24 100644 --- a/test/args.test.ts +++ b/test/args.test.ts @@ -61,6 +61,15 @@ test('renderHelp: plain text lists flags and short names', async () => { } }); +test('renderHelp: --json says it writes files but skips the post-steps', async () => { + const help = await renderHelp({ tier: 'none', unicode: false, tty: false, columns: 80, animate: false }); + const lines = help.split('\n'); + const at = lines.findIndex((l) => l.trimStart().startsWith('--json')); + const text = lines.slice(at, at + 2).join(' '); + assert.match(text, /writes the\s+files unless --dry-run/); + assert.match(text, /skips fetch, git, cargo check and open/); +}); + test('parseArgv: --bin takes a command name and refuses bad ones (#8)', () => { assert.equal(parseArgv(['--bin', 'ave']).overrides.bin, 'ave'); assert.equal(parseArgv(['--bin', 'my_tool-2']).overrides.bin, 'my_tool-2', 'underscores and digits are fine'); diff --git a/test/changelog.test.ts b/test/changelog.test.ts new file mode 100644 index 0000000..1564d87 --- /dev/null +++ b/test/changelog.test.ts @@ -0,0 +1,77 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import { buildContext } from '../src/context.ts'; +import { buildPlan } from '../src/engine/plan.ts'; +import { resolveAnswers } from '../src/presets.ts'; +import type { PlanEntry } from '../src/types.ts'; + +/** The value of `const : &str = "...";` in rendered Rust, escapes resolved. */ +function rustStr(source: string, name: string): string { + const match = new RegExp('const ' + name + ': &str = "((?:[^"\\\\]|\\\\.)*)";', 's').exec(source); + assert.ok(match?.[1] !== undefined, 'no const ' + name); + return match[1].replace(/\\(\n\s*|n|"|\\)/g, (_all: string, esc: string) => { + if (esc === 'n') return '\n'; + if (esc === '"' || esc === '\\') return esc; + return ''; + }); +} + +/** The subject the scaffold's first commit is made with, for `name`. */ +function firstSubject(name: string): string { + const git = readFileSync(new URL('../src/post/git.ts', import.meta.url), 'utf8'); + const match = /const message = `([^`]*)`/.exec(git); + assert.ok(match?.[1] !== undefined, 'first commit message not found in src/post/git.ts'); + return match[1].replace('${answers.name}', name); +} + +async function files(preset: string, overrides: Record = {}): Promise> { + const ctx = buildContext(resolveAnswers(preset, { name: 'log-' + preset, ...overrides })); + const out = new Map(); + for (const entry of (await buildPlan(ctx)) as PlanEntry[]) { + if ('content' in entry) out.set(entry.dest, entry.content); + } + return out; +} + +const SINGLE = ['cli', 'tui', 'lib', 'rustaman']; + +for (const preset of SINGLE) { + test('changelog: ' + preset + ' ships exactly what examples/changelog.rs generates from the first commit', async () => { + const plan = await files(preset); + const generator = plan.get('examples/changelog.rs'); + assert.ok(generator !== undefined, preset + ': examples/changelog.rs is shipped'); + const subject = firstSubject('log-' + preset); + assert.match(subject, /^feat: /, 'the first commit lands under Added'); + const expected = + rustStr(generator, 'PREAMBLE') + + '\n## [Unreleased]\n\n### Added\n\n- ' + subject.slice('feat: '.length) + '\n' + + '\n[Unreleased]: ' + rustStr(generator, 'REPO') + '/commits/HEAD\n'; + assert.equal(plan.get('CHANGELOG.md'), expected); + assert.match(plan.get('CLAUDE.md') ?? '', /`cargo run --example changelog` rebuilds it/); + assert.match(plan.get('CONTRIBUTING.md') ?? '', /rebuilt from the git history by\n`cargo run --example changelog`/); + }); +} + +test('changelog: strobe ships exactly what `cargo xtask changelog` generates from the first commit', async () => { + const plan = await files('strobe'); + const generator = plan.get('crates/xtask/src/changelog.rs'); + assert.ok(generator !== undefined, 'xtask changelog is shipped'); + const subject = firstSubject('log-strobe'); + const expected = + rustStr(generator, 'PREAMBLE') + '\n## [Unreleased]\n\n### Added\n\n- ' + subject.slice('feat: '.length) + '\n'; + assert.equal(plan.get('CHANGELOG.md'), expected); + assert.match(plan.get('CLAUDE.md') ?? '', /`cargo xtask changelog` rebuilds it/); +}); + +for (const preset of [...SINGLE, 'strobe']) { + test('changelog: ' + preset + ' without the generator keeps the hand-edited wording', async () => { + const plan = await files(preset, { tooling: { changelogGen: false } }); + assert.equal(plan.has('examples/changelog.rs'), false, preset + ': no generator example'); + const changelog = plan.get('CHANGELOG.md') ?? ''; + assert.doesNotMatch(changelog, /generated/i); + assert.match(changelog, /Entries follow the conventional-commit subjects/); + assert.doesNotMatch(plan.get('CLAUDE.md') ?? '', /CHANGELOG.md` is generated/); + assert.doesNotMatch(plan.get('CONTRIBUTING.md') ?? '', /rebuilt from the git history/); + }); +} diff --git a/test/core.test.ts b/test/core.test.ts index a4a0a5c..aa3a132 100644 --- a/test/core.test.ts +++ b/test/core.test.ts @@ -98,6 +98,26 @@ test('template deps.js never pins a different version of a base crate', async () } }); +test('an empty tagline is resolved once: Cargo.toml and README agree (B18)', async () => { + const { buildPlan } = await import('../src/engine/plan.ts'); + for (const [preset, tagline] of [['cli', ''], ['strobe', ''], ['lib', ' ']] as const) { + const ctx = buildContext(resolveAnswers(preset, { name: 'tag-less', tagline })); + assert.equal(ctx.tagline, 'tag-less', `${preset}: ctx.tagline falls back to the name`); + assert.equal(ctx.tokens.tagline, 'tag-less', `${preset}: the token too`); + const plan = await buildPlan(ctx); + const text = (dest: string) => { + const e = plan.find((p) => p.dest === dest); + return e && 'content' in e ? e.content : ''; + }; + assert.match(text('README.md'), /^\*\*tag-less\*\*$/m, `${preset}: README bold line is the name, not ****`); + assert.doesNotMatch(text('README.md'), /^\*\*\*\*$/m); + const manifest = preset === 'strobe' ? 'crates/tag-less-app/Cargo.toml' : 'Cargo.toml'; + assert.match(text(manifest), /^description = "tag-less"$/m, `${preset}: Cargo description is the name`); + } + const given = buildContext(resolveAnswers('cli', { name: 'x-y', tagline: 'Fast grep' })); + assert.equal(given.tokens.tagline, 'Fast grep', 'a real tagline is untouched'); +}); + test('GUI_ONLY_FEATURES covers every desktop feature label except the shared settings file', async () => { const { GUI_ONLY_FEATURES } = await import('../src/context.ts'); const { DESKTOP } = await import('../src/ui/labels.ts'); diff --git a/test/docs.test.ts b/test/docs.test.ts new file mode 100644 index 0000000..4cf673c --- /dev/null +++ b/test/docs.test.ts @@ -0,0 +1,76 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import { buildContext } from '../src/context.ts'; +import { buildPlan } from '../src/engine/plan.ts'; +import { resolveAnswers } from '../src/presets.ts'; +import type { PlanEntry } from '../src/types.ts'; + +async function files(preset: string): Promise> { + const ctx = buildContext(resolveAnswers(preset, { name: 'doc-' + preset })); + const out = new Map(); + for (const entry of (await buildPlan(ctx)) as PlanEntry[]) { + if ('content' in entry) out.set(entry.dest, entry.content); + } + return out; +} + +const WORDS = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen']; + +test('docs: every count of theme colours matches the colours a shipped theme states', async () => { + const themes = readFileSync(new URL('../templates/gui/files/assets/themes.toml', import.meta.url), 'utf8'); + const first = themes.split('[[theme]]')[1] ?? ''; + const colours = first.split('\n').filter((line: string) => /^\w+ = "#[0-9a-f]{6}"$/.test(line)).length; + const word = WORDS[colours]; + assert.ok(word !== undefined, 'colour count in range'); + const plan = await files('rustaman'); + for (const [dest, content] of plan) { + // A theme's colour count is in the tens; smaller counts elsewhere are about other things. + for (const match of content.matchAll(/\b(ten|eleven|twelve|thirteen)\b\**\s+colours\b/gi)) { + assert.equal(match[1]?.toLowerCase(), word, dest + ': "' + match[0] + '"'); + } + } + assert.match(plan.get('README.md') ?? '', new RegExp('A theme is ' + word + ' colours')); +}); + +test('docs: header-banner docs name every place the check walks', async () => { + const check = readFileSync(new URL('../templates/guards/files/src/header_check.rs', import.meta.url), 'utf8'); + const areas = /for area in \[([^\]]*)\]/.exec(check)?.[1]?.match(/"(\w+)"/g)?.map((a: string) => a.slice(1, -1) + '/') ?? []; + assert.ok(areas.length > 0, 'areas found in header_check.rs'); + assert.match(check, /root\.join\("build\.rs"\)/, 'build.rs is checked'); + for (const preset of ['cli', 'strobe']) { + const plan = await files(preset); + for (const dest of ['CLAUDE.md', 'CONTRIBUTING.md']) { + const text = (plan.get(dest) ?? '').replace(/\s+/g, ' '); + for (const place of [...areas, 'build.rs']) assert.ok(text.includes('`' + place + '`'), preset + ' ' + dest + ': ' + place); + for (const name of ['(integration test)', '(example)', '(benchmark)', '(build script)']) { + assert.ok(text.includes(name), preset + ' ' + dest + ': ' + name); + } + } + } +}); + +test('docs: nothing claims a check enforces assert! messages', async () => { + for (const preset of ['cli', 'strobe']) { + const plan = await files(preset); + for (const dest of ['CLAUDE.md', 'CONTRIBUTING.md']) { + const text = (plan.get(dest) ?? '').replace(/\s+/g, ' '); + assert.match(text, /not (by any check|something the build checks)/, preset + ' ' + dest); + } + } +}); + +test('docs: release docs say attestation needs a public repository or Enterprise Cloud', async () => { + for (const preset of ['cli', 'rustaman', 'strobe']) { + const text = ((await files(preset)).get('CONTRIBUTING.md') ?? '').replace(/\s+/g, ' '); + assert.match(text, /public repository, or a private one on GitHub Enterprise Cloud/, preset); + } +}); + +test('docs: the GUI README lists the Linux runtime libraries for its renderer', async () => { + const eframe = (await files('rustaman')).get('README.md') ?? ''; + assert.match(eframe, /libxkbcommon-x11-0/); + assert.match(eframe, /mesa-vulkan-drivers/); + const cli = (await files('cli')).get('README.md') ?? ''; + assert.doesNotMatch(cli, /Linux runtime libraries/); +}); diff --git a/test/e2e.test.ts b/test/e2e.test.ts index a249f10..a5a6b96 100644 --- a/test/e2e.test.ts +++ b/test/e2e.test.ts @@ -139,7 +139,9 @@ test('--bin names the executable everywhere it is named, and only there (#8)', a assert.match(text(cli, 'src/cli.rs'), /#\[command\(name = "ln"/, 'clap shows the command name'); assert.match(text(cli, 'README.md'), /puts `ln` on your PATH/, 'README'); assert.match(text(cli, '.github/workflows/release.yml'), /release\/ln\.exe/, 'release packages the right exe'); - assert.match(text(cli, 'src/config.rs'), /join\("long-name"\)/, 'the config dir stays the app name'); + // The config dir is the package name (`long-name`), read at compile time, not the binary's. + assert.match(text(cli, 'src/config.rs'), /join\(env!\("CARGO_PKG_NAME"\)\)/, 'the config dir stays the app name'); + assert.doesNotMatch(text(cli, 'src/config.rs'), /join\("ln"\)/, 'not the binary name'); const ws = await plan('strobe', { bin: 'ln' }); assert.match(text(ws, 'crates/long-name-app/Cargo.toml'), /\[\[bin\]\]\nname = "ln"/, 'workspace app crate gets [[bin]]'); diff --git a/test/failure.test.ts b/test/failure.test.ts index e94a43a..b36e945 100644 --- a/test/failure.test.ts +++ b/test/failure.test.ts @@ -32,8 +32,23 @@ function assertUntouched(existing: string) { assert.equal(readFileSync(join(existing, 'precious.txt'), 'utf8'), 'mine'); } -/** Run the real CLI on a TTY; resolves once it exits. Returns its exit code and plain-text output. */ -async function runTty(args: string[], cwd: string, steps: { wait: number; keys?: string }[] = []) { +const plain = (raw: string) => raw.replace(/\x1b\[[0-9;?]*[A-Za-z]/g, ''); // eslint-disable-line no-control-regex + +/** + * Run the real CLI on a TTY; resolves once it exits. Returns its exit code and plain-text output. + * Each step waits until the output matches `after`, then types `keys`, so a slow start (a loaded CI + * runner) can't make keys arrive before the prompt that should read them. + */ +async function runTty(args: string[], cwd: string, steps: { after: RegExp; keys: string }[] = []) { + // On Windows node-pty gives ConPTY's output worker 5 s to connect and otherwise reports exit + // code -1 without ever starting the CLI. That is the harness failing, not the CLI, so try again. + for (let attempt = 1; ; attempt++) { + const r = await runTtyOnce(args, cwd, steps); + if (!(r.code === -1 && r.out === '' && attempt < 3)) return r; + } +} + +async function runTtyOnce(args: string[], cwd: string, steps: { after: RegExp; keys: string }[]) { const proc = pty.spawn(process.execPath, [BIN, ...args], { name: 'xterm-256color', cols: 100, rows: 40, cwd, env: { ...process.env, CI: '', NO_COLOR: '1' } as Record, @@ -42,15 +57,15 @@ async function runTty(args: string[], cwd: string, steps: { wait: number; keys?: let code: number | undefined; proc.onData((d) => { out += d; }); proc.onExit((e) => { code = e.exitCode; }); + const deadline = Date.now() + 30000; for (const s of steps) { - await sleep(s.wait); - if (s.keys && code === undefined) proc.write(s.keys); + while (code === undefined && Date.now() < deadline && !s.after.test(plain(out))) await sleep(50); + if (code !== undefined) break; + proc.write(s.keys); } - const deadline = Date.now() + 20000; while (code === undefined && Date.now() < deadline) await sleep(50); if (code === undefined) proc.kill(); - // eslint-disable-next-line no-control-regex - return { code, out: out.replace(/\x1b\[[0-9;?]*[A-Za-z]/g, '') }; + return { code, out: plain(out) }; } test('targetProblem: missing and empty folders are fine, occupied ones are not', (t) => { @@ -106,9 +121,9 @@ test('interactive: an occupied folder is refused before any question', async (t) test('interactive: the name prompt refuses an occupied folder, and Ctrl-C leaves it untouched', async (t) => { const { work, existing } = fixture(t); const { code, out } = await runTty([], work, [ - { wait: 1800, keys: 'existing' }, - { wait: 300, keys: '\r' }, - { wait: 600, keys: '\x03' }, + { after: /Project name/, keys: 'existing' }, + { after: /existing/, keys: '\r' }, + { after: /not empty/, keys: '\x03' }, ]); assert.match(out, /not empty/, 'the prompt explains why'); assert.ok(!out.includes('What are you building?'), 'it did not move on'); diff --git a/test/git.test.ts b/test/git.test.ts new file mode 100644 index 0000000..4a17f93 --- /dev/null +++ b/test/git.test.ts @@ -0,0 +1,68 @@ +/** The git post-step: a fresh, empty repository gets the first commit; another repo is left alone. */ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { spawnSync } from 'node:child_process'; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { repoState } from '../src/post/git.ts'; + +const BIN = fileURLToPath(new URL('../bin/create-rust-app.ts', import.meta.url)); +const ID = ['-c', 'user.name=Test', '-c', 'user.email=test@example.com']; +const git = (args: string[], cwd: string) => spawnSync('git', args, { cwd, encoding: 'utf8' }); +const run = (args: string[], cwd: string) => spawnSync(process.execPath, [BIN, ...args], { + encoding: 'utf8', cwd, env: { ...process.env, NO_COLOR: '1' }, stdio: ['ignore', 'pipe', 'pipe'], +}); +const files = (cwd: string) => JSON.parse(run(['.', '--name', 'fresh-repo', '--preset', 'minimal', '--dry-run', '--json'], cwd).stdout).files as string[]; + +function work(t: { after(fn: () => void): void }) { + const dir = mkdtempSync(join(tmpdir(), 'cra-git-')); + t.after(() => rmSync(dir, { recursive: true, force: true, maxRetries: 3 })); + return dir; +} + +test('a folder holding only a fresh git init gets the first commit of the generated files (B19)', (t) => { + const d = join(work(t), 'fresh-repo'); + mkdirSync(d); + git(['init', '-q', '-b', 'trunk'], d); + assert.deepEqual(repoState(d), { action: 'commit' }); + const r = run(['.', '--preset', 'minimal', '-y', '--no-fetch'], d); + assert.equal(r.status, 0, r.stderr); + assert.doesNotMatch(r.stdout, /git skipped/); + assert.match(r.stdout, /first commit/); + assert.equal(git(['rev-list', '--count', 'HEAD'], d).stdout.trim(), '1', 'one commit'); + assert.equal(git(['symbolic-ref', '--short', 'HEAD'], d).stdout.trim(), 'trunk', 'the repo keeps its branch'); + assert.deepEqual(git(['ls-files'], d).stdout.trim().split('\n').sort(), files(d).sort(), 'exactly the generated files'); + assert.equal(git(['status', '--porcelain'], d).stdout, '', 'clean tree'); +}); + +test('with --force, only generated files are committed into the fresh repo; the user\'s stay untracked', (t) => { + const d = join(work(t), 'fresh-repo'); + mkdirSync(d); + git(['init', '-q'], d); + writeFileSync(join(d, 'notes.txt'), 'mine'); + const r = run(['.', '--preset', 'minimal', '-y', '--no-fetch', '--force', '--quiet'], d); + assert.equal(r.status, 0, r.stderr); + assert.ok(!git(['ls-files'], d).stdout.split('\n').includes('notes.txt'), 'notes.txt is not committed'); + assert.equal(git(['status', '--porcelain'], d).stdout.trim(), '?? notes.txt'); +}); + +test('inside another repository git is skipped and the summary does not promise a commit', (t) => { + const parent = work(t); + git(['init', '-q'], parent); + writeFileSync(join(parent, 'README'), 'x'); + git(['add', 'README'], parent); + git([...ID, 'commit', '-q', '-m', 'init'], parent); + const r = run(['child', '--preset', 'minimal', '-y', '--no-fetch'], parent); + assert.equal(r.status, 0, r.stderr); + assert.match(r.stdout, /git skipped: already inside a git repository/); + assert.doesNotMatch(r.stdout, /git init \+ first commit/, 'the finished summary is truthful'); + assert.equal(git(['rev-list', '--count', 'HEAD'], parent).stdout.trim(), '1', 'parent repo untouched'); + assert.equal(repoState(join(parent, 'child')).action, 'skip'); + // A fresh repo nested in another one is still its own root: it gets the commit. + const nested = join(parent, 'nested'); + mkdirSync(nested); + git(['init', '-q'], nested); + assert.deepEqual(repoState(nested), { action: 'commit' }); +}); diff --git a/test/name-length.test.ts b/test/name-length.test.ts new file mode 100644 index 0000000..520db4e --- /dev/null +++ b/test/name-length.test.ts @@ -0,0 +1,102 @@ +// Generated Rust must be rustfmt-stable for every valid project name (1 to 64 characters). +// rustfmt reflows a statement once it crosses 100 columns, and re-joins one that fits, so a +// line whose length grows with the name must stay within 100 columns at the longest name. +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { spawnSync } from 'node:child_process'; +import { mkdtemp, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { buildContext } from '../src/context.ts'; +import { buildPlan } from '../src/engine/plan.ts'; +import { writePlan } from '../src/engine/write.ts'; +import { resolveAnswers } from '../src/presets.ts'; +import type { PartialAnswers, PlanEntry } from '../src/types.ts'; +import type { TestContext } from 'node:test'; + +const SHORT = 'a'; +const LONG = 'abcdefghij'.repeat(6) + 'abcd'; // 64 characters, the crates.io limit +const LONG_DASHED = 'ab-cd-ef-gh-'.repeat(5) + 'ij-k'; // 64, with dashes (Pascal/snake forms differ) + +const COMBOS: [string, PartialAnswers][] = [ + ['rustaman', {}], + ['rustaman', { features: { tray: true, singleInstance: true, commandPalette: true, subcommands: true } }], + ['rustaman', { features: { demo: false } }], + ['rustaman', { guiStack: 'winit-glow' }], + ['rustaman', { crates: { clap: false } }], + ['strobe', {}], + ['strobe', { features: { tray: true, singleInstance: true } }], + ['cli', {}], + ['cli', { features: { subcommands: true }, crates: { async: 'tokio', sqlite: true } }], + ['cli', { crates: { async: 'tokio' } }], + ['tui', {}], + ['lib', {}], + ['minimal', {}], +]; + +const label = (preset: string, over: PartialAnswers) => preset + (Object.keys(over).length ? ' ' + JSON.stringify(over) : ''); + +async function rustFiles(preset: string, over: PartialAnswers, name: string) { + const plan = await buildPlan(buildContext(resolveAnswers(preset, { ...over, name }))); + const files = new Map(); + for (const e of plan) { + if (!e.dest.endsWith('.rs') || !('content' in e)) continue; + // Workspace paths carry the name (crates/-app/...); key by a name-free path. + files.set(e.dest.replace(`crates/${name}-`, 'crates/-'), e.content); + } + return files; +} + +for (const [preset, over] of COMBOS) { + for (const long of [LONG, LONG_DASHED]) { + test(`name length: ${label(preset, over)} keeps name-dependent lines within 100 columns (${long.includes('-') ? 'dashed' : 'plain'})`, async () => { + const short = await rustFiles(preset, over, SHORT); + const wide = await rustFiles(preset, over, long); + assert.deepEqual([...wide.keys()].sort(), [...short.keys()].sort(), 'same files for both names'); + const problems: string[] = []; + for (const [dest, text] of wide) { + const a = (short.get(dest) ?? '').split('\n'); + const b = text.split('\n'); + assert.equal(b.length, a.length, `${dest}: line count must not depend on the name`); + b.forEach((line, i) => { + // rustfmt leaves doc comments (wrap_comments is off) and tool attributes such as + // `#[command(name = "…")]` as written. Plain `//` lines stay in: the header check + // holds banner lines to 100 columns, except `Module:`, whose value is the path. + const t = line.trimStart(); + if (line === a[i] || t.startsWith('#[') || t.startsWith('///') || t.startsWith('//!')) return; + if (t.startsWith('// Module:')) return; + // A line ending in `\` continues a multi-line string literal, which rustfmt never touches. + if (line.endsWith('\\')) return; + if (line.length > 100) problems.push(`${dest}:${i + 1} (${line.length} cols): ${line.trim()}`); + }); + } + assert.deepEqual(problems, [], 'name-dependent lines over 100 columns'); + }); + } +} + +const hasRustfmt = spawnSync('rustfmt', ['--version'], { stdio: 'ignore' }).status === 0; + +for (const preset of ['rustaman', 'strobe', 'cli', 'tui', 'lib', 'minimal']) { + test(`name length: ${preset} is rustfmt-clean with 1- and 64-character names`, async (t: TestContext) => { + if (!hasRustfmt) { + t.skip('rustfmt is not installed'); + return; + } + for (const name of [SHORT, LONG, LONG_DASHED]) { + const ctx = buildContext(resolveAnswers(preset, { name })); + const plan = await buildPlan(ctx); + const dir = await mkdtemp(join(tmpdir(), 'cra-fmt-')); + try { + await writePlan(plan, dir, { force: true }); + const files = plan + .filter((e: PlanEntry) => e.dest.endsWith('.rs')) + .map((e: PlanEntry) => join(dir, e.dest)); + const r = spawnSync('rustfmt', ['--check', '--edition', ctx.edition, ...files], { encoding: 'utf8' }); + assert.equal(r.status, 0, `${preset} named ${name}:\n${r.stdout}${r.stderr}`); + } finally { + await rm(dir, { recursive: true, force: true }); + } + } + }); +} diff --git a/test/notices.test.ts b/test/notices.test.ts new file mode 100644 index 0000000..d0a3c01 --- /dev/null +++ b/test/notices.test.ts @@ -0,0 +1,68 @@ +/** One-line stderr notices for choices the CLI makes on the user's behalf. */ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { spawnSync } from 'node:child_process'; +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const BIN = fileURLToPath(new URL('../bin/create-rust-app.ts', import.meta.url)); +const run = (args: string[], cwd?: string) => spawnSync(process.execPath, [BIN, ...args], { + encoding: 'utf8', env: { ...process.env, NO_COLOR: '1' }, stdio: ['ignore', 'pipe', 'pipe'], ...(cwd ? { cwd } : {}), +}); + +test('a positional folder that is not a crate name says which name is used (B7)', (t) => { + const work = mkdtempSync(join(tmpdir(), 'cra-notice-')); + t.after(() => rmSync(work, { recursive: true, force: true })); + const r = run(['MyDir', '--preset', 'minimal', '--dry-run', '--json'], work); + assert.equal(r.status, 0, r.stderr); + assert.equal(JSON.parse(r.stdout).answers.name, 'my-app', 'the documented default still applies; stdout is pure JSON'); + assert.match(r.stderr, /note: the folder name "MyDir" can't be a crate name, so the crate is named "my-app" \(set it with --name\)\./); + assert.equal(r.stderr.trim().split('\n').length, 1, 'one line'); + + const quiet = run(['MyDir', '--preset', 'minimal', '--dry-run', '--quiet'], work); + assert.equal(quiet.status, 0, quiet.stderr); + assert.equal(quiet.stderr, '', '--quiet suppresses it'); + + const named = run(['MyDir', '--name', 'my-dir', '--preset', 'minimal', '--dry-run', '--json'], work); + assert.equal(named.stderr, '', 'no notice once --name is given'); + const valid = run(['good-dir', '--preset', 'minimal', '--dry-run', '--json'], work); + assert.equal(valid.stderr, '', 'no notice when the folder name is the crate name'); +}); + +test('explicit options the kind ignores get one stderr line each, not an error (F17)', () => { + const cases: [string[], RegExp][] = [ + [['--preset', 'lib', '--with', 'tray'], /^note: tray is ignored: a library has no desktop window\.$/], + [['--preset', 'tui', '--with', 'subcommands'], /^note: subcommands is ignored: a terminal UI has no command line/], + [['--preset', 'minimal', '--with', 'subcommands'], /^note: subcommands is ignored: subcommands need clap/], + [['--preset', 'lib', '--bin', 'foo'], /^note: --bin foo is ignored: a library has no executable\.$/], + [['--preset', 'cli', '--gui', 'winit-glow'], /^note: --gui winit-glow is ignored: a command-line tool has no desktop window\.$/], + [['--preset', 'cli', '--set', 'features.tray=true'], /^note: tray is ignored/], + ]; + for (const [args, re] of cases) { + const r = run([...args, '--dry-run', '--json']); + assert.equal(r.status, 0, `${args.join(' ')} still succeeds: ${r.stderr}`); + JSON.parse(r.stdout); + const lines = r.stderr.trim().split('\n'); + assert.equal(lines.length, 1, `one line for ${args.join(' ')}: ${r.stderr}`); + assert.match(lines[0] ?? '', re); + assert.equal(run([...args, '--dry-run', '--quiet']).stderr, '', '--quiet suppresses it'); + } + const both = run(['--preset', 'lib', '--with', 'tray,palette', '--dry-run', '--json']); + assert.equal(both.stderr.trim().split('\n').length, 2, 'one line per ignored option'); + for (const args of [['--preset', 'cli', '--without', 'tray'], ['--preset', 'rustaman', '--with', 'tray'], ['--preset', 'cli', '--with', 'subcommands']]) { + assert.equal(run([...args, '--dry-run', '--json']).stderr, '', `nothing ignored: ${args.join(' ')}`); + } +}); + +test('--json blanks guiStack like themeBase for kinds without a GUI (B20)', () => { + for (const preset of ['cli', 'tui', 'lib', 'minimal']) { + const out = JSON.parse(run(['--preset', preset, '--gui', 'winit-glow', '--dry-run', '--json']).stdout); + assert.equal(out.answers.guiStack, '', `${preset}: no GUI stack`); + assert.equal(out.answers.themeBase, '', `${preset}: no theme base`); + } + for (const [preset, stack] of [['rustaman', 'eframe'], ['strobe', 'winit-glow']] as const) { + assert.equal(JSON.parse(run(['--preset', preset, '--dry-run', '--json']).stdout).answers.guiStack, stack); + } +}); diff --git a/test/prompts.test.ts b/test/prompts.test.ts new file mode 100644 index 0000000..ff8f96e --- /dev/null +++ b/test/prompts.test.ts @@ -0,0 +1,263 @@ +/** + * Interactive prompt behaviour that doesn't need a terminal: prompts are driven in-process through + * streams, and the pure layout / validation helpers are called directly. + */ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { PassThrough, Writable } from 'node:stream'; +import { spawnSync } from 'node:child_process'; +import { posix, win32 } from 'node:path'; +import { msrvProblem, promptVersionProblem, startOver, toolchainProblem, writesHint } from '../src/prompts.ts'; +import { validateRustVersions } from '../src/context.ts'; +import { width } from '../src/ui/tty.ts'; +import { stripVTControlCharacters } from 'node:util'; +import { isCancel } from '@clack/core'; +import { BACK, clipEllipsis, fitFooter, layout, pick, pickMany, windowBody, windowStart } from '../src/ui/choose.ts'; +import { glyphs } from '../src/ui/glyphs.ts'; +import { plainCursor, tasks, text } from '../src/ui/rail.ts'; +import type { Caps } from '../src/types.ts'; + +const caps: Caps = { tier: 'truecolor', glyphs: 'full', unicode: true, tty: true, columns: 100, animate: false }; +const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); + +function harness() { + const input = new PassThrough(); + let out = ''; + const output = new Writable({ write(chunk, _enc, cb) { out += chunk.toString(); cb(); } }); + return { io: { input, output }, input, read: () => out }; +} + +/** Every line a prompt drew: raw output split at newlines and cursor moves, controls stripped. */ +const drawn = (raw: string) => raw.split(/\r?\n|\r|\x1b\[\d*[ABCDEFGJK]/).map((l) => stripVTControlCharacters(l)); + +type Start = (io: ReturnType['io']) => Promise; + +/** Start a prompt, press `key` once it has rendered, and return what it resolved to plus its output. */ +async function press(start: Start, key: string) { + const h = harness(); + const done = start(h.io); + await sleep(30); + h.input.write(key); + const value = await done; + return { value, out: stripVTControlCharacters(h.read()) }; +} + +const options = [{ value: 'a', label: 'Alpha', hint: 'first' }, { value: 'b', label: 'Beta', hint: 'second' }]; +const prompts: Record Start> = { + pick: (back: boolean) => (io: ReturnType['io']) => pick(caps, { message: 'Pick', options, back, io }), + pickMany: (back: boolean) => (io: ReturnType['io']) => pickMany(caps, { message: 'Many', options, back, io }), + text: (back: boolean) => (io: ReturnType['io']) => text(caps, { message: 'Name', initialValue: 'x', back, io }), +}; + +for (const [name, make] of Object.entries(prompts)) { + test(`${name}: Esc on a back prompt resolves to BACK and says "esc back"`, async () => { + const r = await press(make(true), '\x1b'); + assert.equal(r.value, BACK); + assert.match(r.out, /esc back/); + assert.doesNotMatch(r.out, /esc cancel/); + }); + test(`${name}: Ctrl-C on a back prompt still cancels`, async () => { + const r = await press(make(true), '\x03'); + assert.notEqual(r.value, BACK); + assert.ok(isCancel(r.value)); + }); + test(`${name}: Esc outside Customize still cancels and says "esc cancel"`, async () => { + const r = await press(make(false), '\x1b'); + assert.notEqual(r.value, BACK); + assert.ok(isCancel(r.value)); + assert.match(r.out, /esc cancel/); + }); +} + +test('"Start over from a preset" wins over --kind and --preset, keeps the other flags (B12)', () => { + const lib = startOver({ kind: 'lib', name: 'fl-lib' }, 'rustaman', 'fl-lib'); + assert.equal(lib.kind, 'gui'); + assert.equal(lib.preset, 'rustaman'); + assert.equal(lib.name, 'fl-lib'); + const flagged = startOver({ preset: 'cli', kind: 'cli', edition: '2021', license: 'Apache-2.0' }, 'lib', 'renamed'); + assert.equal(flagged.kind, 'lib'); + assert.equal(flagged.preset, 'lib'); + assert.equal(flagged.name, 'renamed'); + assert.equal(flagged.edition, '2021', 'flags other than --kind / --preset still apply'); + assert.equal(flagged.license, 'Apache-2.0'); +}); + +test('the review hint names the folder the run writes, including a positional dir (B9)', () => { + const cwd = '/work/projects'; + assert.equal(writesHint(undefined, 'hp-cli', cwd, posix), 'writes ./hp-cli'); + assert.equal(writesHint('fl-dir', 'fl-renamed', cwd, posix), 'writes ./fl-dir'); + assert.equal(writesHint('.', 'here', cwd, posix), 'writes .'); + assert.equal(writesHint('../elsewhere', 'x', cwd, posix), 'writes /work/elsewhere'); + // Windows: / separators, and a drive-absolute path is not given a ./ prefix. + const wcwd = 'C:\\work\\projects'; + assert.equal(writesHint('out\\fl-dir', 'x', wcwd, win32), 'writes ./out/fl-dir'); + assert.equal(writesHint('..\\elsewhere', 'x', wcwd, win32), 'writes C:/work/elsewhere'); +}); + +test('Licence + Rust prompts cross-check MSRV, toolchain and edition, worded for the prompt (B10)', () => { + assert.equal(msrvProblem('1.9x', '2024'), 'Use a version like 1.98'); + assert.equal(msrvProblem(' 1.98 ', '2024'), undefined, 'whitespace is trimmed before validating'); + const old = msrvProblem('1.80', '2024'); + assert.match(old ?? '', /^edition 2024 needs Rust 1\.85 or newer, but msrv is 1\.80\./); + assert.doesNotMatch(old ?? '', /--/, 'no flag advice inside the prompt'); + assert.equal(msrvProblem('1.80', '2021'), undefined); + assert.equal(toolchainProblem('stable', '1.98', '2024'), 'Use an exact version like 1.99.1'); + assert.equal(toolchainProblem(' 1.99.1 ', '1.98', '2024'), undefined); + const newer = toolchainProblem('1.0.0', '9.0', '2021'); + assert.match(newer ?? '', /^msrv 9\.0 is newer than toolchain 1\.0\.0, so the pinned toolchain can't build the crate\./); + assert.doesNotMatch(newer ?? '', /--/); + assert.equal(promptVersionProblem('1.98', '1.99.1', '2024'), null); + // The command line keeps its own wording. + assert.match(validateRustVersions('9.0', '1.0.0', '2021') ?? '', /Lower --msrv or raise --toolchain\.$/); +}); + +test('a long validation error wraps on the rail instead of past the edge', async () => { + const h = harness(); + Object.assign(h.io.output, { columns: 40 }); + const done = text(caps, { message: 'Pinned toolchain', initialValue: '1.0.0', validate: () => toolchainProblem('1.0.0', '9.0', '2021'), io: h.io }); + await sleep(30); + h.input.write('\r'); + await sleep(30); + h.input.write('\x03'); + await done; + const frames = drawn(h.read()); + assert.ok(frames.some((l) => l.includes('msrv 9.0 is newer')), 'the error is shown'); + for (const l of frames) assert.ok(width(l) <= 40, `wider than 40 columns: ${JSON.stringify(l)}`); +}); + +test('list window: scrolls as little as possible and keeps the focused row (and its header) visible (B14)', () => { + assert.equal(windowStart(20, 0, 0, 5, 0), 0); + assert.equal(windowStart(20, 4, 4, 5, 0), 0, 'still inside the window: no scroll'); + assert.equal(windowStart(20, 5, 5, 5, 0), 1, 'one past the bottom scrolls by one'); + assert.equal(windowStart(20, 19, 19, 5, 0), 15); + assert.equal(windowStart(20, 10, 10, 5, 12), 10, 'moving up past the top scrolls to the row'); + assert.equal(windowStart(20, 9, 10, 5, 12), 9, 'a group header above the focused row comes along'); + assert.equal(windowStart(20, 3, 3, 5, 99), 3, 'a stale start is clamped'); + assert.equal(windowStart(3, 0, 2, 5, 0), 0, 'shorter than the room'); +}); + +test('windowBody keeps the frame below the terminal height and says what is hidden', () => { + const body = Array.from({ length: 15 }, (_, i) => `row ${i}`); + const plainCaps: Caps = { ...caps, tier: 'none' }; + const fits = windowBody(plainCaps, body, 0, 0, 40, 3, 0); + assert.deepEqual(fits.lines, body, 'no window when it fits'); + const w = windowBody(plainCaps, body, 14, 14, 10, 3, 0); + assert.ok(w.lines.length + 3 <= 9, `frame of ${w.lines.length + 3} lines in a 10-row terminal`); + assert.match(w.lines[0] ?? '', /↑ \d+ more/); + assert.ok(w.lines.includes('row 14'), 'focused row visible'); + assert.equal(w.lines.at(-1), '│', 'nothing below the last row'); +}); + +test('rows, footers and messages fit 40 columns: hint first, then the label is cut (B15)', () => { + const items = [ + { value: 'gui', label: 'Desktop app', tag: 'recommended', hint: 'egui + wgpu, themes, tray, palette, settings' }, + { value: 'lib', label: 'Library', hint: 'a crate for other crates' }, + { value: 'long', label: 'A label far too long to fit in forty columns at all', hint: 'x' }, + ]; + for (const glyphSet of ['full', 'ascii'] as const) { + const c: Caps = { ...caps, glyphs: glyphSet, unicode: glyphSet !== 'ascii' }; + const prefix = width(`${glyphs(c).bar} ${glyphs(c).radioOn} `); + for (const r of layout(c, items, 6, 40, prefix)) { + assert.ok(prefix + width(`${r.label}${r.tag}${r.gap}${r.hint}`) <= 39, `row too wide: ${r.label}${r.tag}${r.gap}${r.hint}`); + } + } + const wide = layout(caps, items.slice(0, 2), 6, 100, 5); + assert.equal(wide[0]?.hint, items[0]?.hint, 'a wide terminal keeps every description'); + assert.equal(fitFooter(caps, ['space toggle', 'a all', 'enter confirm', 'esc back'], [1, 2, 0], 36), 'space toggle · esc back'); + assert.equal(fitFooter(caps, ['↑↓ move', 'enter select', 'esc cancel'], [1, 0], 36), '↑↓ move · enter select · esc cancel'); + assert.equal(clipEllipsis(caps, 'abcdefghij', 6), 'abcde…'); +}); + +test('a tall multi-select in a 40×10 terminal: every frame fits, the focused row stays visible', async () => { + const h = harness(); + Object.assign(h.io.output, { columns: 40, rows: 10 }); + const opts = Array.from({ length: 14 }, (_, i) => ({ value: i, label: `Option number ${i}`, hint: 'a description that will not fit here', group: i < 7 ? 'first group' : 'second group' })); + const done = pickMany(caps, { message: 'Signature theme surfaces (your accent on these)', options: opts, back: true, io: h.io }); + await sleep(30); + for (let i = 0; i < 13; i++) { h.input.write('\x1b[B'); await sleep(5); } + await sleep(30); + const last = drawn(h.read()).join('\n'); + h.input.write('\r'); + await done; + assert.match(last, /Option number 13/, 'the focused (last) row is drawn'); + assert.match(last, /↑ \d+ more/); + for (const l of drawn(h.read())) assert.ok(width(l) <= 40, `wider than 40 columns: ${JSON.stringify(l)}`); +}); + +test('without colour the text cursor is a glyph, not inverse video (B16, B17)', () => { + const full: Caps = { ...caps, tier: 'none' }; + assert.equal(plainCursor(full, 'nc-flag', 7), 'nc-flag█'); + assert.equal(plainCursor(full, 'nc-flag', 5), 'nc-fl▏ag'); + assert.equal(plainCursor({ ...full, glyphs: 'ascii', unicode: false }, 'abc', 1), 'a|bc'); + assert.equal(plainCursor({ ...full, glyphs: 'ascii', unicode: false }, 'abc', 3), 'abc_'); +}); + +test('no colour: focused multi-select row is marked, and no frame has an SGR sequence (B16, B17)', async () => { + const none: Caps = { ...caps, tier: 'none' }; + const sgr = /\x1b\[[0-9;]*m/; + const h = harness(); + const many = pickMany(none, { message: 'Tooling', options: [...options, { value: 'c', label: 'Gamma', hint: 'third', group: 'g' }], initialValues: ['a'], io: h.io }); + await sleep(30); + h.input.write('\x1b[B'); + await sleep(30); + const frame = drawn(h.read()); + h.input.write('\r'); + await many; + assert.ok(frame.some((l) => /^│ › +◻ Beta/.test(l)), `focused row marked: ${frame.join(' / ')}`); + assert.ok(frame.some((l) => /^│ {6}◼ Alpha/.test(l)), 'other rows keep the column, unmarked'); + assert.doesNotMatch(h.read(), sgr); + + const t = harness(); + const typed = text(none, { message: 'Project name', io: t.io }); + await sleep(30); + t.input.write('nc-flag'); + t.input.write('\x1b[D'); + await sleep(30); + t.input.write('\x1b[D'); + await sleep(30); + t.input.write('\r'); + await typed; + assert.doesNotMatch(t.read(), sgr); + assert.match(stripVTControlCharacters(t.read()), /nc-fl▏ag/); + + const p = harness(); + const one = pick(none, { message: 'Pick', options, io: p.io }); + await sleep(30); + p.input.write('\r'); + await one; + assert.doesNotMatch(p.read(), sgr); +}); + +/** Run a script against src/ui/rail.ts in a child process (real signals, real exit codes, own stdout). */ +function child(body: string) { + const rail = new URL('../src/ui/rail.ts', import.meta.url).href; + const script = `import { tasks } from ${JSON.stringify(rail)};\nconst caps = ${JSON.stringify({ ...caps, tty: true })};\n${body}`; + return spawnSync(process.execPath, ['--input-type=module', '-e', script], { encoding: 'utf8', timeout: 20000 }); +} + +// On Windows `process.kill(pid, 'SIGINT')` is TerminateProcess (exit status 1), never a catchable +// signal; a real console Ctrl-C there still emits 'SIGINT', so emit the event the handler listens to. +// Elsewhere a real signal is sent. +const sendSigint = process.platform === 'win32' ? `process.emit('SIGINT', 'SIGINT')` : `process.kill(process.pid, 'SIGINT')`; + +test('Ctrl-C during the run steps restores the cursor, says what was left and exits 130 (B11)', () => { + const r = child(` + setTimeout(() => ${sendSigint}, 100); + // A step that never finishes and keeps the process alive, like cargo fetch would. + await tasks(caps, [{ title: 'cargo fetch', run: () => new Promise(() => { setInterval(() => {}, 1000); }) }], + { interrupted: 'Interrupted. The partly created folder demo was left in place.' });`); + assert.equal(r.status, 130); + assert.ok(r.stdout.lastIndexOf('\x1b[?25h') > r.stdout.lastIndexOf('\x1b[?25l'), 'cursor shown again'); + const plain = stripVTControlCharacters(r.stdout); + assert.match(plain, /cargo fetch \(interrupted\)/); + assert.match(plain, /The partly created folder demo was left in place\./); +}); + +test('the run steps remove their SIGINT handler when they finish', () => { + const r = child(` + const before = process.listenerCount('SIGINT'); + await tasks(caps, [{ title: 'step', run: async () => ({ ok: true, message: 'done' }) }]); + console.log('listeners', before, process.listenerCount('SIGINT'));`); + assert.equal(r.status, 0, r.stderr); + assert.match(r.stdout, /listeners 0 0/); +}); diff --git a/test/reproduce.test.ts b/test/reproduce.test.ts new file mode 100644 index 0000000..7740fff --- /dev/null +++ b/test/reproduce.test.ts @@ -0,0 +1,96 @@ +/** The recreate command carries every answer that changes the output, and names the real folder. */ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { posix, win32 } from 'node:path'; +import { parseArgv } from '../src/args.ts'; +import { resolveAnswers } from '../src/presets.ts'; +import { effectiveAnswers, reportedAnswers } from '../src/context.ts'; +import { RUN_COMMAND, reproduceCommand, shownTarget } from '../src/reproduce.ts'; +import { nameFromFolder } from '../src/cli.ts'; +import type { Answers, PartialAnswers } from '../src/types.ts'; + +/** POSIX-shell word splitting for what reproduceCommand emits: bare words and "…" with \ escapes. */ +function shellWords(cmd: string): string[] { + const out: string[] = []; + let word: string | null = null; + for (let i = 0; i < cmd.length; i++) { + const c = cmd[i] ?? ''; + if (c === ' ') { if (word !== null) out.push(word); word = null; continue; } + word ??= ''; + if (c !== '"') { word += c; continue; } + for (i++; i < cmd.length && cmd[i] !== '"'; i++) word += cmd[i] === '\\' ? cmd[++i] ?? '' : cmd[i]; + } + if (word !== null) out.push(word); + return out; +} + +/** Run the printed command back through the CLI's own steps: parseArgv, positional name, resolveAnswers. */ +function replay(cmd: string): Answers { + assert.ok(cmd.startsWith(`${RUN_COMMAND} `), cmd); + const { dir, overrides } = parseArgv(shellWords(cmd.slice(RUN_COMMAND.length + 1))); + if (dir && overrides.name === undefined) { + const fromFolder = nameFromFolder(dir); + if (fromFolder) overrides.name = fromFolder; + } + return resolveAnswers(overrides.preset ?? null, overrides); +} + +const SETS: [string | null, PartialAnswers][] = [ + ['rustaman', { name: 'jane-app', accent: '#ff9f6e', author: 'Jane Q', github: 'janeq', features: { tray: true } }], + ['strobe', { name: 'ws', displayName: 'Work Space', email: 'jq@example.com', themeBase: 'graphite', guiStack: 'eframe' }], + ['cli', { name: 'neon', tagline: 'Says "hi" for $5 `now` \\ ok', bin: 'nd', crates: { async: 'tokio', sqlite: true }, features: { subcommands: true } }], + ['cli', { name: 'quiet-one', tagline: '', post: { git: false, fetch: false, cargoCheck: true, open: 'code' } }], + ['tui', { name: 'tv', edition: '2021', msrv: '1.80', toolchain: '1.90.0', license: 'Apache-2.0', features: { tray: true } }], + ['lib', { name: 'dur', bin: 'ignored', crates: { thiserror: false, serde: false }, tooling: { release: true, ci: false } }], + ['minimal', { name: 'mini', guiStack: 'winit-glow', crates: { clap: true }, features: { subcommands: true } }], + [null, { name: 'custom-gui', kind: 'gui', guiStack: 'winit-glow', author: '', github: '', accent: '#123abc' }], + ['rustaman', { name: 'as-cli', kind: 'cli', crates: { logging: 'tracing', http: 'ureq' } }], +]; + +test('round trip: the recreate command reproduces the effective answers (B8)', () => { + for (const [preset, over] of SETS) { + const raw = resolveAnswers(preset, over); + for (const dir of [undefined, raw.name, 'some/other-folder', 'Not A Crate', '.']) { + const cmd = reproduceCommand(raw, dir); + const back = replay(cmd); + assert.deepEqual(reportedAnswers(back), reportedAnswers(raw), `${preset}/${raw.name} in ${dir}: ${cmd}`); + if (raw.kind === 'gui' || raw.kind === 'workspace') assert.deepEqual(effectiveAnswers(back), effectiveAnswers(raw), cmd); + } + } +}); + +test('the recreate command carries accent, author, GitHub handle, display name and email (B8)', () => { + const raw = resolveAnswers('rustaman', { name: 'jane-app', accent: '#ff9f6e', author: 'Jane Q', github: 'janeq', displayName: 'Jane', email: 'j@q.dev' }); + const cmd = reproduceCommand(raw); + for (const part of ['--accent "#ff9f6e"', '--author "Jane Q"', '--github janeq', '--set displayName=Jane', '--set email=j@q.dev']) { + assert.ok(cmd.includes(part), `${part} in ${cmd}`); + } + assert.equal(reproduceCommand(resolveAnswers('rustaman', { name: 'x' })), `${RUN_COMMAND} x --preset rustaman -y`, 'defaults add nothing'); +}); + +test('the recreate command names the real folder, and --name when it differs (B9)', () => { + const raw = resolveAnswers('cli', { name: 'fl-renamed' }); + assert.equal(reproduceCommand(raw, 'fl-dir'), `${RUN_COMMAND} fl-dir --name fl-renamed --preset cli -y`); + assert.equal(reproduceCommand(raw, 'out/fl-renamed'), `${RUN_COMMAND} out/fl-renamed --preset cli -y`, 'no --name when the folder supplies it'); + assert.equal(reproduceCommand(raw), `${RUN_COMMAND} fl-renamed --preset cli -y`); + // Each platform's path rules, explicitly, so both run on every OS. + const cwd = '/work'; + assert.equal(shownTarget('fl-dir', 'fl-renamed', cwd, posix), 'fl-dir', 'the positional wins over the name'); + assert.equal(shownTarget(undefined, 'fl-renamed', cwd, posix), 'fl-renamed'); + assert.equal(shownTarget('.', 'x', cwd, posix), '.'); + assert.equal(shownTarget('out/sub', 'x', cwd, posix), 'out/sub'); + assert.equal(shownTarget('../elsewhere', 'x', cwd, posix), '/elsewhere', 'outside cwd: absolute'); +}); + +test('on Windows the shown folder uses / so cd and the recreate command survive any shell (B9)', () => { + const cwd = 'C:\\work'; + assert.equal(shownTarget('fl-dir', 'fl-renamed', cwd, win32), 'fl-dir'); + assert.equal(shownTarget('.', 'x', cwd, win32), '.'); + assert.equal(shownTarget('out\\sub', 'x', cwd, win32), 'out/sub', 'a backslash positional'); + assert.equal(shownTarget('out/sub', 'x', cwd, win32), 'out/sub'); + assert.equal(shownTarget('..\\elsewhere', 'x', cwd, win32), 'C:/elsewhere', 'outside cwd: absolute, drive kept'); + assert.equal(shownTarget('D:\\proj\\app', 'x', cwd, win32), 'D:/proj/app', 'another drive'); + // A /-separated folder needs no quoting, and its basename still supplies the name. + const raw = resolveAnswers('cli', { name: 'sub' }); + assert.equal(reproduceCommand(raw, shownTarget('out\\sub', 'sub', cwd, win32)), `${RUN_COMMAND} out/sub --preset cli -y`); +}); diff --git a/test/scaffold-check.test.ts b/test/scaffold-check.test.ts new file mode 100644 index 0000000..b0dc595 --- /dev/null +++ b/test/scaffold-check.test.ts @@ -0,0 +1,49 @@ +import { test } from 'node:test'; +import { join } from 'node:path'; +import assert from 'node:assert/strict'; +import { cargoEnv, gateCommands, parseArgs, parseSet } from '../scripts/scaffold-check.ts'; + +test('scaffold-check --set splits on the first = only', () => { + assert.deepEqual(parseSet('tagline=a=b'), [['tagline'], 'a=b']); + assert.deepEqual(parseSet('features.tray=true'), [['features', 'tray'], true]); + assert.deepEqual(parseSet('crates.serde=false'), [['crates', 'serde'], false]); + assert.deepEqual(parseSet('tagline='), [['tagline'], '']); + assert.throws(() => parseSet('=x'), /requires a key/); + const { overrides } = parseArgs(['cli', '--set', 'tagline=x = y', '--set', 'features.tray=true']); + assert.equal(overrides.tagline, 'x = y'); + assert.deepEqual(overrides.features, { tray: true }); +}); + +test('scaffold-check parses preset, --name, --out and --gate', () => { + const a = parseArgs(['--gate', 'fmt', 'rustaman', '--name', 'x', '--out', '/tmp/o']); + assert.equal(a.preset, 'rustaman'); + assert.equal(a.gate, 'fmt'); + assert.equal(a.out, '/tmp/o'); + assert.equal(a.overrides.name, 'x'); + const d = parseArgs(['strobe']); + assert.equal(d.gate, 'full'); + assert.equal(d.overrides.name, 'demo-strobe'); + // --name wins over --set name=…, whatever the order. + assert.equal(parseArgs(['cli', '--name', 'a', '--set', 'name=b']).overrides.name, 'a'); + assert.throws(() => parseArgs([]), /usage/); + assert.throws(() => parseArgs(['cli', '--gate', 'bogus']), /unknown gate/); + assert.throws(() => parseArgs(['cli', '--name']), /needs a value/); + assert.throws(() => parseArgs(['cli', '--frobnicate']), /unknown option/); +}); + +test('scaffold-check gates: doc is opt-in, fmt builds nothing', () => { + assert.deepEqual(gateCommands('fmt'), [['fmt', '--all', '--', '--check']]); + assert.deepEqual(gateCommands('doc'), [['doc', '--no-deps']]); + assert.ok(!gateCommands('full').some((c) => c[0] === 'doc')); + assert.deepEqual(gateCommands('full').map((c) => c[0]), ['fmt', 'clippy', 'test']); + assert.deepEqual(gateCommands('none'), []); +}); + +test('scaffold-check keeps an existing CARGO_TARGET_DIR', () => { + assert.equal(cargoEnv({ CARGO_TARGET_DIR: '/shared/target' }, '/repo', 'full').CARGO_TARGET_DIR, '/shared/target'); + // The platform's own separators: cargo gets a native path (`\repo\.scratch\target` on Windows). + assert.equal(cargoEnv({}, '/repo', 'full').CARGO_TARGET_DIR, join('/repo', '.scratch', 'target')); + assert.equal(cargoEnv({}, '/repo', 'doc').RUSTDOCFLAGS, '-D warnings'); + assert.equal(cargoEnv({ RUSTDOCFLAGS: '--cfg x' }, '/repo', 'doc').RUSTDOCFLAGS, '--cfg x -D warnings'); + assert.equal(cargoEnv({}, '/repo', 'full').RUSTDOCFLAGS, undefined); +}); diff --git a/test/validation.test.ts b/test/validation.test.ts new file mode 100644 index 0000000..0b50ae9 --- /dev/null +++ b/test/validation.test.ts @@ -0,0 +1,76 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { MAX_NAME_LENGTH, RUST_KEYWORDS, validateBin, validateName } from '../src/context.ts'; +import { parseArgv } from '../src/args.ts'; + +test('validateName: Rust keywords from every edition are rejected (B4)', () => { + for (const kw of ['fn', 'async', 'type', 'match', 'mod', 'use', 'gen', 'try', 'dyn', 'await', 'yield', 'self', 'crate', 'super']) { + assert.match(validateName(kw) ?? '', /keyword/, `${kw} is rejected as a keyword`); + } + for (const kw of RUST_KEYWORDS) assert.ok(validateName(kw), `${kw} rejected`); + // Weak keywords are ordinary identifiers. + for (const ok of ['union', 'raw', 'safe', 'fn-tool', 'my-type']) assert.equal(validateName(ok), null, `${ok} allowed`); +}); + +test('validateName: Cargo-reserved and Windows device names are rejected like --bin (B5)', () => { + for (const name of ['build', 'deps', 'examples', 'incremental']) { + assert.match(validateName(name) ?? '', /reserved by Cargo/, name); + assert.match(validateBin(name) ?? '', /reserved by Cargo/, name); + } + for (const name of ['con', 'nul', 'prn', 'aux', 'com1', 'lpt9']) { + assert.match(validateName(name) ?? '', /device name on Windows/, name); + assert.match(validateBin(name) ?? '', /device name on Windows/, name); + } +}); + +test('validateName / validateBin: at most 64 characters (B6)', () => { + assert.equal(MAX_NAME_LENGTH, 64); + assert.equal(validateName('a'.repeat(64)), null, '64 is fine'); + assert.match(validateName('a'.repeat(65)) ?? '', /at most 64 characters.*65/); + assert.match(validateName('a'.repeat(260)) ?? '', /at most 64 characters/); + assert.equal(validateBin('b'.repeat(64)), null); + assert.match(validateBin('b'.repeat(65)) ?? '', /at most 64 characters/); +}); + +test('parseArgv: --name and --bin apply the shared rules', () => { + assert.throws(() => parseArgv(['--name', 'fn']), /Invalid project name: "fn" is a Rust keyword/); + assert.throws(() => parseArgv(['--name', 'build']), /Invalid project name: "build" is reserved by Cargo/); + assert.throws(() => parseArgv(['--name', 'con']), /Invalid project name: .*Windows/); + assert.throws(() => parseArgv(['--name', 'x'.repeat(260)]), /Invalid project name: Use at most 64/); + assert.throws(() => parseArgv(['--bin', 'x'.repeat(65)]), /Invalid binary name: Use at most 64/); + assert.throws(() => parseArgv(['--set', 'name=gen']), /keyword/); +}); + +test('validateRustVersions: msrv must not be newer than the toolchain, nor older than the edition (B10)', async () => { + const { validateRustVersions } = await import('../src/context.ts'); + assert.equal(validateRustVersions('1.98', '1.99.1', '2024'), null, 'defaults pass'); + assert.equal(validateRustVersions('1.99.1', '1.99.1', '2024'), null, 'equal is fine'); + assert.equal(validateRustVersions('1.85', '1.85.0', '2024'), null, '2024 from 1.85'); + assert.equal(validateRustVersions('1.56', '1.99.1', '2021'), null, '2021 from 1.56'); + assert.match(validateRustVersions('1.100', '1.99.1', '2024') ?? '', /msrv 1\.100 is newer than toolchain 1\.99\.1/, 'numeric, not string, compare'); + assert.match(validateRustVersions('9.0', '1.0.0', '2021') ?? '', /newer than toolchain/); + assert.match(validateRustVersions('1.99.2', '1.99.1', '2024') ?? '', /newer than toolchain/, 'patch level counts'); + assert.match(validateRustVersions('1.84', '1.99.1', '2024') ?? '', /edition 2024 needs Rust 1\.85/); + assert.match(validateRustVersions('1.55', '1.99.1', '2021') ?? '', /edition 2021 needs Rust 1\.56/); + assert.match(validateRustVersions('x', '1.99.1', '2024') ?? '', /not a Rust version/); +}); + +test('CLI: contradictory Rust versions exit 2 from flags, --set and preset defaults (B10)', async () => { + const { spawnSync } = await import('node:child_process'); + const { fileURLToPath } = await import('node:url'); + const bin = fileURLToPath(new URL('../bin/create-rust-app.ts', import.meta.url)); + const run = (args: string[]) => spawnSync(process.execPath, [bin, ...args], { encoding: 'utf8', env: { ...process.env, NO_COLOR: '1' }, stdio: ['ignore', 'pipe', 'pipe'] }); + for (const args of [ + ['--msrv', '1.100', '--toolchain', '1.99.1'], + ['--set', 'msrv=1.100'], + ['--toolchain', '1.97.0'], + ['--msrv', '1.80'], + ['--preset', 'lib', '--msrv', '1.84'], + ]) { + const r = run([...args, '--dry-run', '-y']); + assert.equal(r.status, 2, `${args.join(' ')} exits 2; stderr ${r.stderr}`); + assert.match(r.stderr, /newer than toolchain|needs Rust 1\.85/); + } + const ok = run(['--msrv', '1.80', '--edition', '2021', '--dry-run', '-y', '--quiet']); + assert.equal(ok.status, 0, ok.stderr); +}); diff --git a/test/workflows.test.ts b/test/workflows.test.ts new file mode 100644 index 0000000..76b713e --- /dev/null +++ b/test/workflows.test.ts @@ -0,0 +1,60 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { buildContext } from '../src/context.ts'; +import { buildPlan } from '../src/engine/plan.ts'; +import { PRESETS, resolveAnswers } from '../src/presets.ts'; +import type { PlanEntry } from '../src/types.ts'; + +/** Rendered `.github/workflows/*.yml` files of a preset, by dest. */ +async function workflows(preset: string): Promise> { + const ctx = buildContext(resolveAnswers(preset, { name: 'flow-' + preset })); + const plan = await buildPlan(ctx); + const out = new Map(); + for (const entry of plan) { + if (entry.dest.startsWith('.github/workflows/') && 'content' in entry) out.set(entry.dest, entry.content); + } + return out; +} + +/** The step starting at `lines[start]` (a `- uses:` / `- name:` line), up to the next step or job. */ +function stepAt(lines: string[], start: number): string[] { + const indent = (lines[start] ?? '').search(/\S/); + const step = [lines[start] ?? '']; + for (const line of lines.slice(start + 1)) { + const at = line.search(/\S/); + if (at >= 0 && at <= indent && !line.trimStart().startsWith('#')) break; + step.push(line); + } + return step; +} + +/** The lines of one job (` :` at two spaces) in a workflow. */ +function job(content: string, id: string): string[] { + const lines = content.split('\n'); + const start = lines.indexOf(' ' + id + ':'); + assert.ok(start >= 0, 'no job ' + id); + const end = lines.findIndex((line: string, i: number) => i > start && /^ {2}[a-z][\w-]*:$/.test(line)); + return lines.slice(start, end < 0 ? undefined : end); +} + +for (const preset of Object.keys(PRESETS)) { + test('workflows: every checkout in ' + preset + ' drops its credential (zizmor artipacked)', async () => { + for (const [dest, content] of await workflows(preset)) { + const lines = content.split('\n'); + lines.forEach((line: string, i: number) => { + if (!/^\s*- uses: actions\/checkout@/.test(line)) return; + const step = stepAt(lines, i).join('\n'); + assert.match(step, /^\s+persist-credentials: false$/m, preset + ': ' + dest + ':' + (i + 1)); + }); + } + }); + + test('workflows: the tag-triggered release build in ' + preset + ' reads no cache (zizmor cache-poisoning)', async () => { + const release = (await workflows(preset)).get('.github/workflows/release.yml'); + if (release === undefined) return; + for (const id of ['draft', 'build', 'publish']) { + const body = job(release, id).join('\n'); + assert.doesNotMatch(body, /rust-cache|actions\/cache|cache: /, preset + ': release.yml job ' + id); + } + }); +} diff --git a/test/write.test.ts b/test/write.test.ts new file mode 100644 index 0000000..4d28953 --- /dev/null +++ b/test/write.test.ts @@ -0,0 +1,86 @@ +/** writePlan cleans up after a failed write; --force reports what it overwrote. */ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { spawnSync } from 'node:child_process'; +import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { existingFiles, writePlan } from '../src/engine/write.ts'; +import { overwriteNotice } from '../src/cli.ts'; +import type { PlanEntry } from '../src/types.ts'; + +const BIN = fileURLToPath(new URL('../bin/create-rust-app.ts', import.meta.url)); + +function work(t: { after(fn: () => void): void }) { + const dir = mkdtempSync(join(tmpdir(), 'cra-write-')); + t.after(() => rmSync(dir, { recursive: true, force: true, maxRetries: 3 })); + return dir; +} + +test('a failed write removes the target folder this run created, parents included (B6)', async (t) => { + const base = work(t); + const target = join(base, 'parent', 'proj'); + // 'a' is a file, so 'a/b' cannot be written: a deterministic failure midway. + const plan: PlanEntry[] = [{ dest: 'ok.txt', content: 'x' }, { dest: 'a', content: 'x' }, { dest: 'a/b', content: 'x' }]; + await assert.rejects(writePlan(plan, target), (e: Error) => { + assert.match(e.message, /^Writing a\/b failed: /); + assert.match(e.message, /Removed .*parent, which this run created\.$/); + return true; + }); + assert.deepEqual(readdirSync(base), [], 'nothing is left behind'); +}); + +test('a failed write into an existing folder removes only what this run added (B6)', async (t) => { + const target = work(t); + writeFileSync(join(target, 'keep.txt'), 'mine'); + mkdirSync(join(target, 'src')); + writeFileSync(join(target, 'src', 'user.rs'), 'mine'); + const plan: PlanEntry[] = [ + { dest: 'new.txt', content: 'x' }, + { dest: 'src/gen.rs', content: 'x' }, + { dest: 'deep/dir/f.txt', content: 'x' }, + { dest: 'keep.txt', content: 'replaced' }, + { dest: 'new.txt/bad', content: 'x' }, + ]; + await assert.rejects(writePlan(plan, target, { force: true }), (e: Error) => { + assert.match(e.message, /^Writing new\.txt\/bad failed: /); + assert.match(e.message, /Removed the 3 files this run created in .*; files that were there before are kept, but 1 existing file had already been overwritten\.$/); + return true; + }); + assert.deepEqual(readdirSync(target).sort(), ['keep.txt', 'src'], 'new.txt and deep/ are gone'); + assert.deepEqual(readdirSync(join(target, 'src')), ['user.rs'], 'the user\'s file stays, gen.rs is gone'); + assert.equal(readFileSync(join(target, 'keep.txt'), 'utf8'), 'replaced\n', 'an overwritten file is reported, not restored'); +}); + +test('existingFiles lists what --force would overwrite; overwriteNotice says how many and which (F18)', (t) => { + const target = work(t); + writeFileSync(join(target, 'README.md'), 'mine'); + mkdirSync(join(target, 'src')); + const plan: PlanEntry[] = [{ dest: 'README.md', content: '' }, { dest: 'src', content: '' }, { dest: 'Cargo.toml', content: '' }]; + assert.deepEqual(existingFiles(plan, target), ['README.md'], 'files only'); + assert.equal(overwriteNotice(['a', 'b']), '--force overwrote 2 existing files: a, b'); + assert.equal(overwriteNotice(['a']), '--force overwrote 1 existing file: a'); + assert.equal(overwriteNotice(['a', 'b', 'c'], 2), '--force overwrote 3 existing files: a, b, and 1 more'); +}); + +test('CLI: --force lists overwritten files on stderr unless --quiet (F18)', (t) => { + const base = work(t); + const run = (dir: string, extra: string[]) => spawnSync(process.execPath, [BIN, dir, '--preset', 'minimal', '-y', '--no-git', '--no-fetch', '--force', ...extra], { + encoding: 'utf8', cwd: base, env: { ...process.env, NO_COLOR: '1' }, stdio: ['ignore', 'pipe', 'pipe'], + }); + for (const [dir, extra] of [['loud', []], ['json', ['--json']], ['hush', ['--quiet']]] as const) { + mkdirSync(join(base, dir)); + writeFileSync(join(base, dir, 'README.md'), 'mine'); + writeFileSync(join(base, dir, 'Cargo.toml'), 'mine'); + writeFileSync(join(base, dir, 'notes.txt'), 'mine'); + const r = run(dir, [...extra]); + assert.equal(r.status, 0, r.stderr); + if (dir === 'hush') assert.equal(r.stderr, '', '--quiet hides it'); + else assert.match(r.stderr, /note: --force overwrote 2 existing files: (Cargo\.toml, README\.md|README\.md, Cargo\.toml)\n/); + if (dir === 'json') JSON.parse(r.stdout); + assert.ok(existsSync(join(base, dir, 'notes.txt'))); + } + const fresh = run('fresh', []); + assert.doesNotMatch(fresh.stderr, /overwrote/, 'nothing to report in a new folder'); +}); diff --git a/test/xtask.test.ts b/test/xtask.test.ts new file mode 100644 index 0000000..103f800 --- /dev/null +++ b/test/xtask.test.ts @@ -0,0 +1,24 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { buildContext } from '../src/context.ts'; +import { buildPlan } from '../src/engine/plan.ts'; +import { resolveAnswers } from '../src/presets.ts'; +import type { PlanEntry } from '../src/types.ts'; + +const text = (plan: PlanEntry[], dest: string) => { + const e = plan.find((x: PlanEntry) => x.dest === dest); + return e && 'content' in e ? e.content : undefined; +}; + +test('workspace xtask ships the changelog command only with changelogGen', async () => { + const on = await buildPlan(buildContext(resolveAnswers('strobe', { name: 'ws' }))); + assert.ok(text(on, 'crates/xtask/src/changelog.rs') !== undefined, 'generator present by default'); + assert.match(text(on, 'crates/xtask/src/main.rs') ?? '', /^mod changelog;$/m); + assert.match(text(on, 'crates/xtask/src/main.rs') ?? '', /"changelog" if args\.len\(\) == 1/); + + const off = await buildPlan(buildContext(resolveAnswers('strobe', { name: 'ws', tooling: { changelogGen: false } }))); + assert.equal(text(off, 'crates/xtask/src/changelog.rs'), undefined, 'no generator to rewrite a hand-edited CHANGELOG.md'); + const main = text(off, 'crates/xtask/src/main.rs') ?? ''; + assert.doesNotMatch(main, /changelog/i, 'no module, command or help text for it'); + assert.match(main, /^mod ci;$/m, 'ci stays'); +});