From 850cac9193e8c3178ab60e716855c619a105f1f0 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 19:56:09 +0000 Subject: [PATCH 01/40] docs: add dogfood findings and fix plan Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01W2BaQjmXXv2ZSgkAnMH1eA --- docs/dogfood/FINDINGS.md | 156 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 156 insertions(+) create mode 100644 docs/dogfood/FINDINGS.md diff --git a/docs/dogfood/FINDINGS.md b/docs/dogfood/FINDINGS.md new file mode 100644 index 0000000..a021e2d --- /dev/null +++ b/docs/dogfood/FINDINGS.md @@ -0,0 +1,156 @@ +# Dogfood findings, November 2026 + +Findings from using create-rust-app end to end at commit `db3693d`: a 24-combination +scaffold matrix, 60+ scripted interactive runs through a pseudo-terminal, and four real +projects built on fresh scaffolds (a CLI log analyser, a TUI tail viewer, a duration-parsing +library and a GUI monitor page). + +**Evidence.** The per-agent reports and friction logs are copied into +[`evidence/`](evidence/). They cite raw logs by paths such as `logs/matrix/rustaman/doc.log`; +those lived in a scratch directory outside the repo (`../cra-dogfood/`) and are not kept. +Every finding below names the repro command and the root cause `file:line` at `db3693d`. +Anything not reproduced is marked *hypothesis*. + +Baseline before any change: `npm ci`, `npm run typecheck`, `npm test` (58/58), `npm run build` +and `scaffold-check minimal --gate check` all pass. + +## 1. Bugs + +Severity: **H** breaks a stated gate in normal use, **M** wrong output or silent misbehaviour, +**L** polish. + +| # | Sev | Bug | Repro | Expected / actual | Root cause | +|---|---|---|---|---|---| +| B1 | H | GUI projects fail `cargo fmt --check` when the name has 14+ characters | `create-rust-app x --name abcdefghijklmn --preset rustaman -y --no-git --no-fetch && cd x && cargo fmt --all -- --check` | CONTRACTS says generated projects are fmt-clean under every flag combination; exit 1. Strobe fails by 16 characters. | Lines that grow with the name cross 100 columns: `templates/gui/files/src/config.rs:178`, `templates/gui/files/examples/screenshot.rs:38`, `templates/gui/files/src/main.rs:92,169`. The repo's own checks use `demo-rustaman` (13 characters), one under the threshold. | +| B2 | H | eframe GUI projects fail `RUSTDOCFLAGS="-D warnings" cargo doc --no-deps` | `--preset rustaman -y`, then the doc command | Clean docs; exit 101 (`private_intra_doc_links`, `redundant_explicit_links`). Affects rustaman and custom; winit-glow passes. | `templates/gui/files/src/gui/run.rs:13,20` | +| B3 | M | `--with tray` breaks docs off Windows | `--preset rustaman --with tray -y`, doc command on Linux | Exit 101, `broken_intra_doc_links` | `templates/gui-features/files/src/tray.rs:11` links a `cfg(windows)` module | +| B4 | M | Rust keywords accepted as project names | `--name fn --preset minimal -y && cargo check` | Rejected like `test`/`std`; scaffold succeeds, then `expected identifier, found '::'` at `src/main.rs:17` | `src/context.ts:11` reserved list has no keywords | +| B5 | M | Cargo-reserved and Windows device names accepted as project names | name prompt or `--name build` / `deps` / `con` / `nul` | `--bin` rejects these; `--name` accepts them, and the binary defaults to the crate name | `validateName` (`src/context.ts:8`) does not apply the `validateBin` rules (`src/context.ts:17-24`) | +| B6 | M | No length limit on names; a long GUI name dies mid-write | `--name <260 chars> --preset rustaman -y` | Rejected up front (crates.io caps names at 64); `ENAMETOOLONG` during write, exit 1, partial project left behind | `src/context.ts:5` (`NAME_RE` unbounded); `src/engine/write.ts:33-38` has no cleanup on failure | +| B7 | M | A positional directory that is not a valid crate name silently becomes `my-app` | `create-rust-app MyDir --preset minimal -y` | An error or a notice; directory `MyDir`, crate `my-app`, nothing said | `src/cli.ts:190-193` | +| B8 | M | The recreate command drops `--accent`, `--author`, `--github` | Interactive run with `--preset rustaman --accent '#ff9f6e' --author 'Jane Q' --github janeq --with tray`, then run the printed command | Identical project; 14 files differ (LICENSE, CODEOWNERS, repository URLs, accent constant) | `src/reproduce.ts:18-55` has no branch for these answers | +| B9 | M | With a positional directory, renaming in Customize makes the review and the recreate command name the wrong folder | `create-rust-app fl-dir --preset cli`, Customize → Name → `fl-renamed` | Review says "writes ./fl-renamed"; files go to `fl-dir`; recreate command points at `fl-renamed` | `src/prompts.ts:149` uses `a.name`; target is `resolve(dir ?? answers.name)` at `src/cli.ts:222` | +| B10 | M | `--msrv` newer than `--toolchain` accepted | `--msrv 1.100 --toolchain 1.99.1 -y && cargo check` | Rejected; scaffolds, then cargo refuses to build. The prompt accepts MSRV 9.0 with toolchain 1.0.0. | `src/args.ts:93-94` and `src/prompts.ts:240-241` check the format only | +| B11 | M | Ctrl-C during `cargo fetch` leaves the cursor hidden and a half-finished folder, with no message | rustaman, Create, Ctrl-C one second into the fetch | Cursor restored and a line saying what was left; neither | `src/ui/rail.ts:273` hides the cursor and relies on `finally` (`:281`), which does not run on SIGINT. `src/ui/spinner.ts:48` and `src/ui/banner.ts:102` do install a handler. | +| B12 | M | With `--kind`, "Start over from a preset" ignores the preset picked | `--name fl-lib --kind lib`, Customize → Start over → Desktop app | A desktop app; still a library | `src/prompts.ts:158`: the flag's `kind` overrides the chosen preset | +| B13 | M | A fresh single-crate scaffold fails its own changelog check | `--preset cli -y && cargo run --example changelog -- --check` | Pass; fails, and running the generator rewrites the header | Header text differs: `templates/base/files/CHANGELOG.md:3` (`@@displayName@@`, hand-written wording) against `templates/guards/files/examples/changelog.rs:586-592` (`@@name@@`, "This file is generated"). The workspace generator differs again: `templates/workspace/files/crates/xtask/src/changelog.rs:152`. | +| B14 | M | Lists taller than the terminal do not scroll | 100×10 terminal, Customize → App features | Focused row stays visible; the row and the prompt message are off-screen and old frames are left behind | `src/ui/choose.ts:68-75,107-122` render every option with no window | +| B15 | M | At 40 columns option rows wrap | 40-column terminal, kind picker | Rows clipped to the width; rows and footers wrap | `src/ui/choose.ts:38` forces a minimum of 10 columns for the hint; footers at `:74,121` are not clipped | +| B16 | M | Without colour, multi-select focus and the text cursor are invisible | `NO_COLOR=1`, Customize → Tooling | Some non-colour marker; every row renders the same | Focus is shown only through `bold()`: `src/ui/choose.ts:118`, `src/ui/motion.ts:32` | +| B17 | L | `--no-color` still emits `ESC[7m` | `--no-color`, move the cursor left in the name prompt | No escape sequences | `src/ui/rail.ts:176` uses clack's `userInputWithCursor`, which sees `NO_COLOR` but not the flag | +| B18 | L | An empty tagline is written two ways | Customize → clear the tagline | Consistent; `Cargo.toml` falls back to the name, README gets `****` | `src/context.ts:121` against `src/gen/cargo.ts:130`; `templates/base/files/README.md:5` | +| B19 | L | A directory holding only a fresh `git init` gets no commit, but the summary says it will | `git init d && cd d && create-rust-app . --preset minimal -y` | First commit, or a summary that says git is skipped | `src/engine/write.ts:9` ignores a lone `.git`; `src/post/git.ts:28` then skips | +| B20 | L | `--json` reports `guiStack` for kinds without a GUI | `--preset cli --gui winit-glow --dry-run --json` | Blanked like `themeBase` | `src/context.ts:52-57` | +| B21 | L | `scaffold-check --set` cuts values at the first `=`, and it overrides `CARGO_TARGET_DIR` | `node scripts/scaffold-check.mjs cli --set tagline=a=b` | `description = "a=b"`; gets `"a"` | `scripts/scaffold-check.ts:39,66` | +| B22 | L | The TUI log file is created at a predictable `/tmp` path with `File::create`, which follows symlinks | read `templates/tui/files/src/logging.rs:29,34` | A per-user directory or `create_new` | Same lines. *Not exploited; reasoning from the code.* | + +`--json` without `--dry-run` writes the files, skips fetch and git, and still reports +`post.git: true` (`src/cli.ts:226-230`). Whether it should run the post-steps is a +behaviour decision, so it is in the backlog (P3); the help text is fixed in the meantime. + +## 2. Friction + +Ranked by the time it cost across the four real projects and the interactive walk. + +| # | Friction | Cost | Evidence | +|---|---|---|---| +| F1 | **Release workflow is Windows-only for every kind**, and its comment says another target is "just an entry". It is not: `.exe`, `7z` and a target-less SBOM name are hard-coded. | ~25 min (tui), ~15 min (gui), noted by cli | `templates/github/files/_github/workflows/release.yml:103-106,143-145,160,184-187,256-259` | +| F2 | **The CLI skeleton's `run(args, out)` has no stdin, terminal info or config injection**, and `config::load()` runs inside the command. A CLI that reads stdin rewrites lib, main and tests. | ~25 min (cli) | `templates/cli/files/src/lib.rs:70`, `templates/cli/files/src/cli_subcommands.rs:132` | +| F3 | **The `unsafe` boundary has no home for non-Windows FFI.** `src/win/` compiles only on Windows, so a `libc` call has nowhere allowed to live. The error also names `src/gui/run/`, which does not exist. | ~25 min (gui) | `templates/guards/files/src/unsafe_check.rs:12,87,89` | +| F4 | **Changelog docs contradict the shipped generator** (see B13). CLAUDE.md and CONTRIBUTING say to hand-edit; `examples/changelog.rs` regenerates the file. | ~15 min (tui), ~6 min (cli), ~5 min (lib) | `templates/base/files/CLAUDE.md` changelog section, `templates/base/files/CHANGELOG.md:5-12` | +| F5 | **CI has no MSRV, rustdoc or package job, and `tests/toolchain_pin.rs` rejects the usual MSRV job** because any workflow `toolchain:` other than the pin fails the test. | ~15 min (lib), ~3 min (tui) | `templates/guards/files/tests/toolchain_pin.rs:83-106`, `templates/github/files/_github/workflows/ci.yml` | +| F6 | **Generated workflows fail zizmor out of the box** (section 3). | ~10 min per project | `logs/matrix//zizmor.log` | +| F7 | **Linux runtime libraries are not in the README.** The GUI crashed under xvfb until `libxkbcommon-x11-0` and a Vulkan driver were installed. | ~15 min (gui) | `templates/base/files/README.md` | +| F8 | **Esc inside any Customize section quits the whole run** and discards every edit. The footer says only `esc cancel`. | every interactive user | `src/prompts.ts:38-44`, `customize()` from `:175` | +| F9 | **The author is never asked and never shown.** Every project is stamped "Lawrence Norton" / `@lnorton89` in LICENSE, CODEOWNERS and `Cargo.toml`; `git config user.name` is ignored. | every user who is not the author | `src/presets.ts:9-10`; no prompt in `src/prompts.ts`; not in `reviewLines` (`src/prompts.ts:54-112`) | +| F10 | **Wrong statements in generated docs.** "All of these are clean on main" is false on a fresh GUI scaffold (B1, B2); README says thirteen colours where the other docs say eleven; doc comments mention a tray and command palette the preset lacks; CLAUDE.md says every `assert!` carries a message, which nothing checks. | ~10 min (gui) | `templates/base/files/README.md:137,215`, `templates/gui/files/src/gui/app/mod.rs:22`, `templates/gui/files/src/gui/ui/mod.rs:232` | +| F11 | **The lib preset carries dependencies a library never uses** (`log`, `toml`, non-optional `serde`), and the crate package ships `.github/`, AGENTS.md, CLAUDE.md, deny.toml and a 724-line `examples/changelog.rs`. | ~10 min (lib) | `src/presets.ts:20,53`, `src/gen/deps.ts:27,30`; no `exclude` in `src/gen/cargo.ts` | +| F12 | **Windows test isolation for CLI config.** `dirs::config_dir()` ignores environment variables on Windows, so tests cannot redirect it. | ~10 min (cli) | `templates/cli/files/src/config.rs` | +| F13 | **`main` prints errors in Debug form** and does not handle a closed pipe. | ~5 min (cli) | `templates/cli/files/src/main.rs:22` | +| F14 | **`*.log` in `.gitignore` hid test fixtures**; CI would have failed on a clean checkout. | ~3 min (cli) | `templates/base/files/_gitignore:4` | +| F15 | **cargo-deny prints 11–13 unused-licence warnings on every run**, from an allow-list sized for the GUI dependency tree. | noise on every run | `src/gen/deny.ts:4-8` | +| F16 | **The review omits values the user edited**: MSRV, tagline, theme base, accent. | interactive users | `src/prompts.ts:82-89,105` | +| F17 | **Inapplicable flags are dropped silently**: `--preset lib --with tray`, `--preset tui --with subcommands`, `--preset lib --bin foo`, `--preset cli --gui winit-glow`. | scripted users | `src/context.ts:52-57`; no notice in `src/args.ts` or `src/cli.ts` | +| F18 | **`--force` overwrites colliding files without listing them.** | scripted users | `src/engine/write.ts:27-38` | +| F19 | Smaller: the "not empty" error suggests `--force` mid-prompt (`src/engine/write.ts:9`); `-y` runs do not print the recreate command (`src/cli.ts:138`); argument errors print `✖` while later errors print `error:` (`src/cli.ts:26`); attestation needs a public repo or Enterprise Cloud and the docs do not say so; header docs omit `benches/` and `build.rs`. | minutes | reports 3a and 3b | + +**What helped, in every project:** the header banner check (new files passed first time +and its messages say exactly what to fix); cargo-deny accepted every new crate unchanged +(regex, jiff, serde_json, anstyle, notify, tempfile, proptest, libc); the TUI skeleton +(`terminal.rs`, `event.rs`, `logging.rs` kept unchanged); adding a GUI page touched two +files and ARCHITECTURE.md described it accurately; persisted settings needed no migration. + +## 3. Template quality + +**Crate versions.** Scaffold pins were checked against crates.io during the builds. +ratatui `0.29` and crossterm `0.28` are behind (`templates/tui/deps.js:8-9`); the tail viewer +moved to ratatui 0.30 and crossterm 0.29 with no code changes. eframe/egui 0.37, +windows-sys 0.61 and the CLI crates are current. egui 0.37 deprecates `Id::new`, which the +templates do not use in a way that warns. + +**Workflows.** actionlint is clean on every combination. zizmor 1.32 fails all 15 +combinations that have workflows (exit 14 with `release.yml`, 13 for lib and minimal): + +| zizmor audit | Level | Where | +|---|---|---| +| `cache-poisoning` | high | `Swatinem/rust-cache` in the tag-triggered release build: `templates/github/files/_github/workflows/release.yml:120` | +| `artipacked` | medium | `actions/checkout` without `persist-credentials: false`: `ci.yml:39,58,74,125`, `release.yml:51,111,231`, `publish.yml:33` | +| `dependabot-cooldown` | medium | no `cooldown:` in `templates/github/files/_github/dependabot.yml:16,38` | +| `use-trusted-publishing` | info | `cargo publish` with a stored token: `publish.yml:62` | + +`release.yml` was read step by step in all four projects: tag/version check, permissions, +binary name, artifact names, SBOM and attestation steps line up. It builds only a Windows +artifact (F1). `publish.yml` for libraries runs no tests before publishing and accepts a +branch named like a tag. + +**MSRV.** Every combination builds on 1.98. No MSRV breakage found. + +**This repo's own files.** `CHANGELOG.md` says CI covers Node 20, 22 and 26, while +`.github/workflows/ci.yml` has 22 and 26. `docs/PLAN.md` §5 says `npm pack` lists `bin/ src/ +templates/`, while `package.json` `files` is `dist` and `templates`. `ci.yml` uses +`actions/setup-node@v7` unpinned, against the house rule. `docs/CONTRACTS.md` omits +`post.fetch` and has a shorter binary-extension list than `src/engine/plan.ts:18`. +PLAN §5 mentions preset snapshots; there are none. + +## 4. Feature backlog + +Ranked by value ÷ effort. "Changes defaults" items are proposals only. + +| # | Item | Problem and evidence | Proposed design | Files | Changes defaults? | +|---|---|---|---|---|---| +| P1 | **Ask for, or derive, the author** | F9: every project is stamped with the template author's name. | Default `author` from `git config user.name`, `github` from `gh`/remote or blank; add both to the review and a Customize row. Pairs with P5. | `src/presets.ts:9-10`, `src/prompts.ts`, `src/cli.ts` | Yes | +| P2 | **Snapshot tests of generated trees** | B1–B3 shipped because the checks use one short name per preset and never run rustdoc. | `node --test` snapshots of the `--dry-run --json` file list plus hashes of rendered text per preset, with a long-name variant; `scaffold-check --gate doc`. The long-name and doc gates land in Phase 3; snapshots are the follow-up. | `test/`, `scripts/scaffold-check.ts` | No | +| P3 | **`--json` runs post-steps, or says it did not** | `src/cli.ts:226-230`: files written, git and fetch skipped, JSON reports them on. | Run the post-steps quietly and add a `post` result object, or make `--json` imply `--dry-run`. | `src/cli.ts`, `docs/CONTRACTS.md` | Yes (behaviour) | +| P4 | **Cross-platform release matrix** | F1: a CLI or TUI ships only a Windows zip. | Per-target `ext`/`archive` matrix fields, target in the SBOM name, Linux and macOS entries on for `cli`/`tui`, opt-in for GUI. | `templates/github/files/_github/workflows/release.yml` | Yes | +| P5 | **Saved answer profile** | F9, B8: author, handle, licence and accent are retyped or wrong on every run. | `~/.config/create-rust-app/config.toml` read under the preset layer; `--no-config` to skip; `--save-profile` to write it. | `src/presets.ts`, `src/args.ts`, new `src/profile.ts` | No (opt-in file) | +| P6 | **CI jobs for MSRV, rustdoc and package, and a toolchain-pin test that allows an MSRV job** | F5: both libraries and binaries hit doc failures CI never ran. | `--with msrvJob,docJob` tooling features; `toolchain_pin.rs` accepts the pin or `rust-version`. | `templates/github/…/ci.yml`, `templates/guards/files/tests/toolchain_pin.rs`, `src/types.ts` | Yes if on by default; no as opt-in | +| P7 | **A non-Windows `unsafe` home** | F3: no allowed place for unix FFI. | Allow `src/sys/` (or `src/unix/`) as a second boundary directory under the same rules. | `templates/guards/files/src/unsafe_check.rs`, generated docs | Yes (convention) | +| P8 | **`doctor` command** | F7 and the Phase 0 setup: missing GUI runtime libs, toolchains and cargo tools are found one crash at a time. | `create-rust-app doctor [dir]`: rustup toolchains against the pin, cargo-deny, Windows target, Linux GUI libs through `pkg-config`/`ldconfig`. | new `src/doctor.ts`, `src/args.ts` | No | +| P9 | **Library packaging and lean lib preset** | F11. | `exclude` in `[package]` for libs; drop `log`/`toml`, make `serde` an optional feature. | `src/gen/cargo.ts`, `src/presets.ts`, `src/gen/deps.ts` | Yes | +| P10 | **CLI skeleton with injectable I/O** | F2, F12, F13. | `run(args, &mut Io)` carrying stdin, stdout, stderr, terminal flags and a config path; `main` prints `Display` and exits 0 on a closed pipe; a `_CONFIG` override. | `templates/cli/files/src/{lib,main,config,cli_subcommands}.rs` | Yes (generated layout) | +| P11 | **Workflow hardening that changes behaviour** | Section 3: Dependabot cooldown, crates.io trusted publishing, tests before publish. | `cooldown: default-days: 7`; `rust-lang/crates-io-auth-action`; a test step in `publish.yml`. | `templates/github/files/_github/**` | Yes | +| P12 | **`upgrade`/`diff` command** | Template fixes such as B1–B3 never reach existing projects. | Write `.create-rust-app.json` (answers and tool version) at scaffold time; `diff` re-renders with those answers and shows drift per file. | `src/cli.ts`, new `src/diff.ts` | Additive file in output: yes | +| P13 | **`add` subcommand** | Users who start minimal cannot add `tray`, `subcommands` or tooling later. Needs the answers file from P12; edits to user-modified files are the hard part. | Start with tooling groups that only add files (ci, release, dependabot, cargoDeny). | `src/engine/plan.ts`, `src/cli.ts` | No | +| P14 | **Review shows everything edited; warn on dropped flags; list `--force` overwrites** | F16–F18. Warnings land in Phase 3; the review layout is a proposal. | Add MSRV, tagline, accent, base and author rows. | `src/prompts.ts:54-112` | Review layout: yes | +| P15 | **Trim the cargo-deny allow-list per kind** | F15. | Compose the list from the groups in use. | `src/gen/deny.ts` | Yes | +| P16 | **TUI log file location** | B22. | `dirs::state_dir()`/cache dir, or `create_new` with a per-process name. | `templates/tui/files/src/logging.rs` | Yes (file location) | +| P17 | **`.gitignore` `*.log`** | F14. | Anchor it (`/*.log`) so fixtures under `tests/` are tracked. | `templates/base/files/_gitignore:4` | Yes | +| P18 | **New presets: axum service, wasm, `no_std`; macOS GUI** | No dogfood evidence either way; each is a new template group with its own lint and CI story. macOS CI targets depend on P4. | One preset at a time, axum first (largest audience, reuses the cli group). | `templates/`, `src/presets.ts` | No | +| P19 | **npm name** | `src/reproduce.ts:9-14`: the tool runs from GitHub because the `create-rust-app` name is not this project's. | See REPORT.md for the name research. | `package.json`, `src/reproduce.ts` | Owner decision | +| P20 | **Third-party template groups** | No evidence of demand. The group format (`manifest.js`, `deps.js`) executes code, so loading external groups is a trust decision. | Defer until P12 fixes the answers file and the group API is documented as stable. | `src/engine/groups.ts` | No | + +## 5. Fix plan (Phase 3) + +In scope: bug fixes, missing validation, better errors, docs, tests. Nothing here changes a +flag, a default answer, the lint table, the banner format, licence options or file layout. + +| Order | Item | Covers | Size | +|---|---|---|---| +| 1 | GUI templates fmt-clean for any valid name; doc-link fixes; `scaffold-check` gains `--gate doc`, a `--name` override, respects `CARGO_TARGET_DIR`, splits `--set` on the first `=`; long-name regression case | B1, B2, B3, B21 | medium | +| 2 | Name validation: Rust keywords, Cargo and Windows reserved names, 64-character cap; notice when a positional directory cannot be the crate name; `--msrv` ≤ `--toolchain`; warn on flags the kind ignores; blank `guiStack` for non-GUI kinds; empty tagline handled once; commit into a fresh empty repo; `--json` help text | B4–B7, B10, B18–B20, F17 | medium | +| 3 | Recreate command carries accent, author, GitHub handle and the real target directory | B8, B9 | small | +| 4 | Workflows: `persist-credentials: false` on every checkout, no cache in the release build; changelog generator and shipped CHANGELOG agree, docs say one thing | B13, F4, F6 (part) | medium | +| 5 | Generated-doc corrections: colour count, tray/palette mentions, `unsafe_check` message path, Linux runtime libraries, attestation requirement, release-target comment, header docs | F3 (message), F7, F10, F19 | small | +| 6 | TUI pins: ratatui 0.30, crossterm 0.29 | section 3 | small | +| 7 | Interactive: Esc in Customize goes back, Ctrl-C during tasks restores the terminal, `--kind` no longer overrides a re-picked preset, MSRV/toolchain cross-check in the prompt, windowed lists, clipped rows, non-colour focus marker, `--no-color` honoured by the text cursor | B11, B12, B14–B17, F8 | medium | +| 8 | This repo's docs: CHANGELOG Node versions, PLAN `npm pack` list, CONTRACTS `post.fetch` and binary extensions, pin `setup-node` | section 3 | small | From d9e175b959fe7c3e22b518ef9334cf53e43d7e16 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 19:59:33 +0000 Subject: [PATCH 02/40] build: scaffold-check gains fmt/doc gates and --name, keeps CARGO_TARGET_DIR --set now splits on the first '=' only, so values may contain '='. The doc gate stays opt-in so the default full gate keeps its documented steps. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01W2BaQjmXXv2ZSgkAnMH1eA --- AGENTS.md | 6 +- CHANGELOG.md | 3 + scripts/scaffold-check.ts | 163 ++++++++++++++++++++++++++---------- test/scaffold-check.test.ts | 47 +++++++++++ 4 files changed, 175 insertions(+), 44 deletions(-) create mode 100644 test/scaffold-check.test.ts 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..c1e3781 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -53,6 +53,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. 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/test/scaffold-check.test.ts b/test/scaffold-check.test.ts new file mode 100644 index 0000000..4fdd0ae --- /dev/null +++ b/test/scaffold-check.test.ts @@ -0,0 +1,47 @@ +import { test } from 'node:test'; +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'); + assert.equal(cargoEnv({}, '/repo', 'full').CARGO_TARGET_DIR, '/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); +}); From eff8d91b198b65daed59c9292ec94a02cce3652c Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 19:59:47 +0000 Subject: [PATCH 03/40] ci: drop the checkout credential in generated workflows Every actions/checkout in ci.yml, release.yml and publish.yml sets persist-credentials: false (zizmor artipacked). No later step uses the persisted git credential: nothing pushes or tags, and gh reads GH_TOKEN. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01W2BaQjmXXv2ZSgkAnMH1eA --- CHANGELOG.md | 3 ++ .../github/files/_github/workflows/ci.yml | 12 ++++++ .../files/_github/workflows/publish.yml | 2 + .../files/_github/workflows/release.yml | 6 +++ test/workflows.test.ts | 42 +++++++++++++++++++ 5 files changed, 65 insertions(+) create mode 100644 test/workflows.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 0c105a8..a990f41 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -32,6 +32,9 @@ 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`. ### Changed 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..d3d1b1c 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 @@ -111,6 +115,7 @@ 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: @@ -231,6 +236,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/test/workflows.test.ts b/test/workflows.test.ts new file mode 100644 index 0000000..1395648 --- /dev/null +++ b/test/workflows.test.ts @@ -0,0 +1,42 @@ +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; +} + +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)); + }); + } + }); +} From c67252a97785fd91a8a732ac6d476d8ad25a7bbf Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 20:00:14 +0000 Subject: [PATCH 04/40] ci: build generated releases without the Actions cache The tag-triggered release build restored Swatinem/rust-cache, which any branch's CI can write (zizmor cache-poisoning, high). The release now builds from scratch; PLAN.md records both workflow hardening rules. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01W2BaQjmXXv2ZSgkAnMH1eA --- CHANGELOG.md | 3 +++ docs/PLAN.md | 8 +++++--- .../github/files/_github/workflows/release.yml | 6 +++--- test/workflows.test.ts | 18 ++++++++++++++++++ 4 files changed, 29 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a990f41..320937d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -35,6 +35,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - 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). ### Changed diff --git a/docs/PLAN.md b/docs/PLAN.md index 8468930..05b1835 100644 --- a/docs/PLAN.md +++ b/docs/PLAN.md @@ -54,9 +54,11 @@ acid wording anywhere. The look is psychedelic rainbow, nerdy, slick. `windows` (clippy `--all-targets --all-features -- -D warnings`, test, `cargo build --release --bins`), `linux` (clippy + test; GUI projects also `cargo clippy … --target x86_64-pc-windows-msvc`). Actions pinned to full SHAs with version comments: - - `actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1` + - `actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1`, always with + `persist-credentials: false` (nothing pushes; `gh` reads `GH_TOKEN`) - `dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # master, 2026-10` with `toolchain: ""` - - `Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3` + - `Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3` (CI only: the release + build restores no cache, so a poisoned entry cannot reach a shipped binary) - `EmbarkStudios/cargo-deny-action@3c6349835b2b7b196a839186cb8b78e02f7b5f25 # v2.1.1` - `actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2` - `actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2` @@ -65,7 +67,7 @@ acid wording anywhere. The look is psychedelic rainbow, nerdy, slick. - Release (`release.yml`, on tag `v*` + `workflow_dispatch` input `tag`): job `draft` (contents: write; `gh release create "$TAG" --draft --title " $TAG" --generate-notes`, reuse if exists) → `build` matrix `[{os: windows-latest, target: x86_64-pc-windows-msvc}]` - (build `--release --bins --target`, package `dist/--/` with exe + README + LICENSE + (no build cache; build `--release --bins --target`, package `dist/--/` with exe + README + LICENSE (+ themes.toml for GUI), `7z a -tzip`; SBOM via `cargo install cargo-cyclonedx --version 0.5.9 --locked && cargo cyclonedx --format json`; sha256; upload `release-assets-`) → `publish` (contents/id-token/attestations: write; download `pattern: release-assets-*` `merge-multiple: true`; diff --git a/templates/github/files/_github/workflows/release.yml b/templates/github/files/_github/workflows/release.yml index d3d1b1c..9464411 100644 --- a/templates/github/files/_github/workflows/release.yml +++ b/templates/github/files/_github/workflows/release.yml @@ -122,9 +122,9 @@ jobs: 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 diff --git a/test/workflows.test.ts b/test/workflows.test.ts index 1395648..76b713e 100644 --- a/test/workflows.test.ts +++ b/test/workflows.test.ts @@ -28,6 +28,15 @@ function stepAt(lines: string[], start: number): string[] { 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)) { @@ -39,4 +48,13 @@ for (const preset of Object.keys(PRESETS)) { }); } }); + + 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); + } + }); } From 3ce7a929099a0ad3520bedb482a86d21636f791b Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 20:00:44 +0000 Subject: [PATCH 05/40] ci: pin setup-node and drop the checkout credential in this repo's CI actions/setup-node is pinned to the v7.1.0 commit (949feb2) per the house rule, and both checkouts set persist-credentials: false. zizmor now reports only dependabot-cooldown, an owner decision. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01W2BaQjmXXv2ZSgkAnMH1eA --- .github/workflows/ci.yml | 8 ++++++-- CHANGELOG.md | 2 ++ 2 files changed, 8 insertions(+), 2 deletions(-) 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/CHANGELOG.md b/CHANGELOG.md index 320937d..5cd1dd5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -38,6 +38,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - 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). +- This repo's CI pins `actions/setup-node` to a full commit SHA (v7.1.0) and checks out without + persisting the token. ### Changed From 0d5b1b2b8fec0cf17b69c49f72ad080f7ce85ebf Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 20:01:11 +0000 Subject: [PATCH 06/40] fix(validate): reject Rust keywords, reserved names and names over 64 characters Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01W2BaQjmXXv2ZSgkAnMH1eA --- CHANGELOG.md | 5 ++++ README.md | 4 +-- docs/CONTRACTS.md | 8 ++++++ src/context.ts | 55 +++++++++++++++++++++++++++++++++++------ test/validation.test.ts | 42 +++++++++++++++++++++++++++++++ 5 files changed, 104 insertions(+), 10 deletions(-) create mode 100644 test/validation.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 0c105a8..0b27fa6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- 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 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 diff --git a/README.md b/README.md index a8fe7d5..efe93d9 100644 --- a/README.md +++ b/README.md @@ -86,8 +86,8 @@ 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) | diff --git a/docs/CONTRACTS.md b/docs/CONTRACTS.md index 25675fb..8d7aec8 100644 --- a/docs/CONTRACTS.md +++ b/docs/CONTRACTS.md @@ -51,6 +51,14 @@ test/*.test.ts node --test } ``` +## 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. + ## Ctx = Answers + derived `buildContext(answers)` first applies `effectiveAnswers(answers)` (src/context.ts): options the kind diff --git a/src/context.ts b/src/context.ts index c81e64f..dcdb1d3 100644 --- a/src/context.ts +++ b/src/context.ts @@ -4,23 +4,62 @@ import { DEFAULT_BASE, shippedTheme } from './gen/themes.ts'; 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 null; + return reservedProblem(bin); } /** @param {string} s */ diff --git a/test/validation.test.ts b/test/validation.test.ts new file mode 100644 index 0000000..1b3b452 --- /dev/null +++ b/test/validation.test.ts @@ -0,0 +1,42 @@ +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/); +}); From 99f54391c976147fd3148ce810cb2b71b6dae622 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 20:01:53 +0000 Subject: [PATCH 07/40] fix(cli): note when a positional folder name can't be the crate name Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01W2BaQjmXXv2ZSgkAnMH1eA --- CHANGELOG.md | 2 ++ src/cli.ts | 6 +++++- test/notices.test.ts | 32 ++++++++++++++++++++++++++++++++ 3 files changed, 39 insertions(+), 1 deletion(-) create mode 100644 test/notices.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 0b27fa6..b7c04ce 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 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`. - 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 diff --git a/src/cli.ts b/src/cli.ts index c8cbc55..61373f9 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -4,7 +4,7 @@ type Node = Map; import { readFile } from 'node:fs/promises'; import { basename, resolve, relative } from 'node:path'; import { parseArgv, optionalUi, renderHelp } from './args.ts'; -import { resolveAnswers } from './presets.ts'; +import { DEFAULTS, resolveAnswers } from './presets.ts'; import { buildContext, effectiveAnswers, validateName } from './context.ts'; import { buildPlan } from './engine/plan.ts'; import { targetProblem, writePlan } from './engine/write.ts'; @@ -185,11 +185,15 @@ 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; + // 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: a folder we can't write into shouldn't cost the user a walkthrough. diff --git a/test/notices.test.ts b/test/notices.test.ts new file mode 100644 index 0000000..2079e02 --- /dev/null +++ b/test/notices.test.ts @@ -0,0 +1,32 @@ +/** 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'); +}); From 7a38d56354a14970a47dd8cacfd8214a6b9cf599 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 20:03:16 +0000 Subject: [PATCH 08/40] fix(args): reject an MSRV newer than the toolchain or older than the edition Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01W2BaQjmXXv2ZSgkAnMH1eA --- CHANGELOG.md | 3 +++ README.md | 2 +- docs/CONTRACTS.md | 3 +++ src/cli.ts | 10 +++++++++- src/context.ts | 31 +++++++++++++++++++++++++++++++ test/validation.test.ts | 34 ++++++++++++++++++++++++++++++++++ 6 files changed, 81 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b7c04ce..8b7d66f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 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. - 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 diff --git a/README.md b/README.md index efe93d9..376f117 100644 --- a/README.md +++ b/README.md @@ -93,7 +93,7 @@ create-rust-app [dir] [options] | `--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 | diff --git a/docs/CONTRACTS.md b/docs/CONTRACTS.md index 8d7aec8..94a7957 100644 --- a/docs/CONTRACTS.md +++ b/docs/CONTRACTS.md @@ -58,6 +58,9 @@ test/*.test.ts node --test 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). ## Ctx = Answers + derived diff --git a/src/cli.ts b/src/cli.ts index 61373f9..f47b84c 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -5,7 +5,7 @@ import { readFile } from 'node:fs/promises'; import { basename, resolve, relative } from 'node:path'; import { parseArgv, optionalUi, renderHelp } from './args.ts'; import { DEFAULTS, resolveAnswers } from './presets.ts'; -import { buildContext, effectiveAnswers, validateName } from './context.ts'; +import { buildContext, effectiveAnswers, validateName, validateRustVersions } from './context.ts'; import { buildPlan } from './engine/plan.ts'; import { targetProblem, writePlan } from './engine/write.ts'; import { initRepo } from './post/git.ts'; @@ -196,6 +196,11 @@ export async function main(argv: string[]) { 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; @@ -219,6 +224,9 @@ export async function main(argv: string[]) { } 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); const ctx = buildContext(answers); const plan = await buildPlan(ctx); diff --git a/src/context.ts b/src/context.ts index dcdb1d3..f9b77f8 100644 --- a/src/context.ts +++ b/src/context.ts @@ -62,6 +62,37 @@ export function validateBin(bin: string) { 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; +} + /** @param {string} s */ export const toSnake = (s: string) => s.replace(/-/g, '_'); /** @param {string} s */ diff --git a/test/validation.test.ts b/test/validation.test.ts index 1b3b452..0b50ae9 100644 --- a/test/validation.test.ts +++ b/test/validation.test.ts @@ -40,3 +40,37 @@ test('parseArgv: --name and --bin apply the shared rules', () => { 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); +}); From 166fe1d9c8a8bb340aced3164711d85ba25fa02c Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 04:03:03 +0000 Subject: [PATCH 09/40] fix(cli): note options the kind ignores; blank guiStack in --json without a GUI Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01W2BaQjmXXv2ZSgkAnMH1eA --- CHANGELOG.md | 4 ++++ docs/CONTRACTS.md | 7 ++++++- src/cli.ts | 8 +++++--- src/context.ts | 40 +++++++++++++++++++++++++++++++++++++++- src/types.ts | 3 +++ test/notices.test.ts | 36 ++++++++++++++++++++++++++++++++++++ 6 files changed, 93 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8b7d66f..82b0245 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - 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`. - 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 diff --git a/docs/CONTRACTS.md b/docs/CONTRACTS.md index 94a7957..2976c53 100644 --- a/docs/CONTRACTS.md +++ b/docs/CONTRACTS.md @@ -66,7 +66,12 @@ test/*.test.ts node --test `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`. diff --git a/src/cli.ts b/src/cli.ts index f47b84c..1f47e4d 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -5,7 +5,7 @@ import { readFile } from 'node:fs/promises'; import { basename, resolve, relative } from 'node:path'; import { parseArgv, optionalUi, renderHelp } from './args.ts'; import { DEFAULTS, resolveAnswers } from './presets.ts'; -import { buildContext, effectiveAnswers, validateName, validateRustVersions } from './context.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 { initRepo } from './post/git.ts'; @@ -227,6 +227,8 @@ export async function main(argv: string[]) { // 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); @@ -237,8 +239,8 @@ export async function main(argv: string[]) { 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)); + // 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']) { diff --git a/src/context.ts b/src/context.ts index f9b77f8..0ed44a2 100644 --- a/src/context.ts +++ b/src/context.ts @@ -1,4 +1,4 @@ -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). */ @@ -136,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 */ 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/test/notices.test.ts b/test/notices.test.ts index 2079e02..d0a3c01 100644 --- a/test/notices.test.ts +++ b/test/notices.test.ts @@ -30,3 +30,39 @@ test('a positional folder that is not a crate name says which name is used (B7)' 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); + } +}); From ae820f74b689839c6247822813bf43d6ed14debd Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 04:03:40 +0000 Subject: [PATCH 10/40] fix(context): resolve an empty tagline once so README and Cargo.toml agree Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01W2BaQjmXXv2ZSgkAnMH1eA --- CHANGELOG.md | 2 ++ src/context.ts | 5 ++++- src/gen/cargo.ts | 4 ++-- test/core.test.ts | 20 ++++++++++++++++++++ 4 files changed, 28 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 82b0245..2c0998a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,6 +22,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 `--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. - 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 diff --git a/src/context.ts b/src/context.ts index 0ed44a2..2ed30ca 100644 --- a/src/context.ts +++ b/src/context.ts @@ -213,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 = { @@ -226,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 || '', @@ -255,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/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/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'); From 7445c64b05b0b08947a1b430a23bec6c61043d30 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 04:05:07 +0000 Subject: [PATCH 11/40] fix(git): commit into a fresh empty repository; truthful summary when skipped Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01W2BaQjmXXv2ZSgkAnMH1eA --- CHANGELOG.md | 3 +++ src/cli.ts | 13 ++++++--- src/post/git.ts | 62 ++++++++++++++++++++++++++++++++----------- test/git.test.ts | 68 ++++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 127 insertions(+), 19 deletions(-) create mode 100644 test/git.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 2c0998a..b081b11 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,6 +24,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 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 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 diff --git a/src/cli.ts b/src/cli.ts index 1f47e4d..3c5c59d 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -117,9 +117,9 @@ async function runInteractive({ caps, answers, plan, target, shown, force }: { { 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 ?? ''})`)}` }; }, }, @@ -280,11 +280,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; @@ -306,7 +310,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/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/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' }); +}); From b51a54a5ff4d7e9811c5acef9865e15ebe4a9c4e Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 04:05:10 +0000 Subject: [PATCH 12/40] fix: keep generated Rust rustfmt-stable for any project name length Lines whose length grew with @@name@@ / @@appCrateSnake@@ crossed rustfmt's 100 columns for names of 14+ characters (GUI) or 16+ (workspace). They now go through a crate alias, a constant or env!("CARGO_PKG_NAME"), so the layout is the same for 1- and 64-character names. Adds a node test that compares rendered lines between a 1- and a 64-character name, plus a rustfmt check that skips without rustfmt. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01W2BaQjmXXv2ZSgkAnMH1eA --- CHANGELOG.md | 6 + templates/cli/files/src/config.rs | 2 +- templates/cli/files/src/main.rs | 6 +- templates/cli/files/tests/cli.rs | 29 +++-- templates/cli/files/tests/cli_subcommands.rs | 33 +++--- .../files/src/win/single_instance.rs | 2 +- templates/gui/files/build.rs | 20 +++- templates/gui/files/examples/brand_assets.rs | 4 +- templates/gui/files/examples/screenshot.rs | 8 +- templates/gui/files/src/cli.rs | 13 ++- templates/gui/files/src/config.rs | 3 +- templates/gui/files/src/main.rs | 23 ++-- templates/gui/files/tests/cli.rs | 5 +- templates/tui/files/src/logging.rs | 2 +- test/name-length.test.ts | 103 ++++++++++++++++++ 15 files changed, 201 insertions(+), 58 deletions(-) create mode 100644 test/name-length.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index c1e3781..c8153d2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- 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. - 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 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/main.rs b/templates/cli/files/src/main.rs index d02b94f..4ac48a1 100644 --- a/templates/cli/files/src/main.rs +++ b/templates/cli/files/src/main.rs @@ -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..75f0833 100644 --- a/templates/cli/files/tests/cli.rs +++ b/templates/cli/files/tests/cli.rs @@ -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..1145564 100644 --- a/templates/cli/files/tests/cli_subcommands.rs +++ b/templates/cli/files/tests/cli_subcommands.rs @@ -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/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..2f33289 100644 --- a/templates/gui/files/examples/brand_assets.rs +++ b/templates/gui/files/examples/brand_assets.rs @@ -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/main.rs b/templates/gui/files/src/main.rs index 9949ea1..31f9718 100644 --- a/templates/gui/files/src/main.rs +++ b/templates/gui/files/src/main.rs @@ -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..1861327 100644 --- a/templates/gui/files/tests/cli.rs +++ b/templates/gui/files/tests/cli.rs @@ -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/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/test/name-length.test.ts b/test/name-length.test.ts new file mode 100644 index 0000000..9aa6044 --- /dev/null +++ b/test/name-length.test.ts @@ -0,0 +1,103 @@ +// 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) + +// The changelog generators are owned by the changelog work (fix-plan row 4): `REPO` and the +// header string grow with the name. Remove these once that lands. +const KNOWN = new Set(['examples/changelog.rs', 'crates/xtask/src/changelog.rs']); + +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) { + if ([...KNOWN].some((k) => dest.endsWith(k))) continue; + 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 comments (wrap_comments is off) and tool attributes such as + // `#[command(name = "…")]` as written. + const t = line.trimStart(); + if (line === a[i] || t.startsWith('//') || t.startsWith('#[')) 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']) { + 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') && ![...KNOWN].some((k) => e.dest.endsWith(k))) + .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 }); + } + } + }); +} From 6d5753143b448e0f38890ffacfdec9425678a255 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 04:06:21 +0000 Subject: [PATCH 13/40] fix: ship the CHANGELOG.md each project's generator writes The scaffolded CHANGELOG.md now equals what examples/changelog.rs (single crate) or cargo xtask changelog (workspace) generate from the scaffold's first commit, so --check passes and regenerating is a no-op. Both generators keep the header in one PREAMBLE const, Unreleased entries drop the commit hash (a squash rewrites it; released entries keep theirs), and the REPO literal is split to stay rustfmt-clean for 64-character names. CLAUDE.md and CONTRIBUTING.md say the file is generated and name the right command whenever changelogGen is on; the hand-edited wording stays when it is off. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01W2BaQjmXXv2ZSgkAnMH1eA --- CHANGELOG.md | 5 ++ templates/base/files/CHANGELOG.md | 38 ++++++++- templates/base/files/CLAUDE.md | 23 +++++- templates/base/files/CONTRIBUTING.md | 23 +++++- templates/guards/files/examples/changelog.rs | 63 +++++++++------ .../files/crates/xtask/src/changelog.rs | 40 +++++++--- test/changelog.test.ts | 77 +++++++++++++++++++ 7 files changed, 227 insertions(+), 42 deletions(-) create mode 100644 test/changelog.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 5cd1dd5..9e3b139 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -38,6 +38,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - 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. - This repo's CI pins `actions/setup-node` to a full commit SHA (v7.1.0) and checks out without persisting the token. 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..859106a 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 @@ -223,11 +226,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..8931772 100644 --- a/templates/base/files/CONTRIBUTING.md +++ b/templates/base/files/CONTRIBUTING.md @@ -180,7 +180,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 +200,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: 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/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/test/changelog.test.ts b/test/changelog.test.ts new file mode 100644 index 0000000..b069e4c --- /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 = /'-m', `([^`]*)`/.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/); + }); +} From 9505f95cdfef22df99169c3242465ae4a22ca498 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 04:06:56 +0000 Subject: [PATCH 14/40] fix(write): clean up after a failed write; list files --force overwrote Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01W2BaQjmXXv2ZSgkAnMH1eA --- CHANGELOG.md | 3 ++ README.md | 2 +- docs/CONTRACTS.md | 3 +- src/cli.ts | 29 ++++++++++++--- src/engine/write.ts | 63 ++++++++++++++++++++++++++++----- test/write.test.ts | 86 +++++++++++++++++++++++++++++++++++++++++++++ 6 files changed, 171 insertions(+), 15 deletions(-) create mode 100644 test/write.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index b081b11..73eee7d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -27,6 +27,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - 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. - 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 diff --git a/README.md b/README.md index 376f117..3e81e99 100644 --- a/README.md +++ b/README.md @@ -113,7 +113,7 @@ create-rust-app [dir] [options] | `--json` | Machine-readable output | | `--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 2976c53..d8c96bf 100644 --- a/docs/CONTRACTS.md +++ b/docs/CONTRACTS.md @@ -18,7 +18,8 @@ src/engine/directives.ts applyDirectives(text, flags) → text (CORE, 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 diff --git a/src/cli.ts b/src/cli.ts index 3c5c59d..da13c63 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -7,7 +7,7 @@ import { parseArgv, optionalUi, renderHelp } from './args.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 +78,17 @@ export function nextCommands(a: Answers, shown: string): [string, string][] { return out; } +/** 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,11 +114,13 @@ 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). @@ -125,6 +135,8 @@ async function runInteractive({ caps, answers, plan, target, shown, force }: { }, { title: 'cargo check', enabled: answers.post.cargoCheck, run: cargoTask('cargo check', cargoCheck) }, ]); + // 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; @@ -236,9 +248,15 @@ export async function main(argv: string[]) { const target = resolve(dir ?? answers.name); const rel = relative(process.cwd(), target); const shown = rel.startsWith('..') ? target : rel || '.'; + // 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) }); + 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; @@ -251,10 +269,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'); 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/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'); +}); From 5bcdfde9dbc6868527bc123b6c7e461772835c7e Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 04:07:15 +0000 Subject: [PATCH 15/40] fix: GUI rustdoc builds cleanly under -D warnings run.rs linked the private `backends` fn and spelled an explicit link rustdoc considers redundant; tray.rs linked the cfg(windows) win::tray module, which doesn't exist when documenting on Linux. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01W2BaQjmXXv2ZSgkAnMH1eA --- CHANGELOG.md | 3 +++ templates/gui-features/files/src/tray.rs | 2 +- templates/gui/files/src/gui/run.rs | 4 ++-- 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c8153d2..62894c0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 (`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. +- `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`). - 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 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/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. From 9209843522d7258152756df1859402401ccfe6e4 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 04:07:15 +0000 Subject: [PATCH 16/40] fix: generated docs name only what the project has unsafe_check's message and module doc named src/gui/run/, which only the winit-glow stack has; they now name src/win/ (plus src/gui/run/ on winit-glow). What the check allows is unchanged. The App and PAGE_KEYS docs mention the tray and command palette only when those features are on. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01W2BaQjmXXv2ZSgkAnMH1eA --- CHANGELOG.md | 3 +++ templates/guards/files/src/unsafe_check.rs | 21 +++++++++++++++------ templates/gui/files/src/gui/app/mod.rs | 11 +++++++++++ templates/gui/files/src/gui/ui/mod.rs | 4 ++++ 4 files changed, 33 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 62894c0..7dd1253 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - `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`). +- 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. - 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 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/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/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, From 80e32b1d51a46726a813bf6fbe786bc44ac358cd Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 04:08:13 +0000 Subject: [PATCH 17/40] build: bump the TUI template to ratatui 0.30 and crossterm 0.29 ratatui 0.30's default crossterm backend builds on crossterm 0.29, so the pair still shares one KeyEvent type. The template uses a concrete backend and no From conversions, so no code changes were needed. Full scaffold-check tui and an MSRV 1.98 build pass. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01W2BaQjmXXv2ZSgkAnMH1eA --- CHANGELOG.md | 2 ++ templates/tui/deps.js | 8 ++++---- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7dd1253..d6d63ab 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -47,6 +47,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### 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, 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' }, ]; From c11038af2216bbcba2c1c109d069b91e3ef770b3 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 04:08:45 +0000 Subject: [PATCH 18/40] docs: correct statements in generated docs README: eleven theme colours (the count every theme states) and a Linux runtime libraries note for GUI projects (libxkbcommon-x11-0, plus mesa-vulkan-drivers for wgpu or an OpenGL driver for glow). CLAUDE.md and CONTRIBUTING.md: assert! messages are a convention, not a check; the header check walks src/, tests/, examples/, benches/ and build.rs, with each module-name form. CONTRIBUTING: attestation needs a public repository or GitHub Enterprise Cloud. release.yml: the matrix comment says what a new target needs besides an entry. No behaviour change. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01W2BaQjmXXv2ZSgkAnMH1eA --- CHANGELOG.md | 5 ++ templates/base/files/CLAUDE.md | 24 ++++-- templates/base/files/CONTRIBUTING.md | 16 +++- templates/base/files/README.md | 23 +++++- .../files/_github/workflows/release.yml | 8 +- test/docs.test.ts | 76 +++++++++++++++++++ 6 files changed, 137 insertions(+), 15 deletions(-) create mode 100644 test/docs.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 9e3b139..f818bca 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -43,6 +43,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 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 CI pins `actions/setup-node` to a full commit SHA (v7.1.0) and checks out without persisting the token. diff --git a/templates/base/files/CLAUDE.md b/templates/base/files/CLAUDE.md index 859106a..c95ad4c 100644 --- a/templates/base/files/CLAUDE.md +++ b/templates/base/files/CLAUDE.md @@ -145,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`, @@ -172,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. diff --git a/templates/base/files/CONTRIBUTING.md b/templates/base/files/CONTRIBUTING.md index 8931772..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 @@ -222,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/github/files/_github/workflows/release.yml b/templates/github/files/_github/workflows/release.yml index 9464411..62e6edc 100644 --- a/templates/github/files/_github/workflows/release.yml +++ b/templates/github/files/_github/workflows/release.yml @@ -104,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: 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/); +}); From 7712459a8649380c8fafd35bb24276d9f6b66589 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 04:08:51 +0000 Subject: [PATCH 19/40] fix(reproduce): carry author, GitHub, accent and the real target folder Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01W2BaQjmXXv2ZSgkAnMH1eA --- CHANGELOG.md | 3 ++ docs/CONTRACTS.md | 4 ++- src/cli.ts | 18 +++++++--- src/reproduce.ts | 41 +++++++++++++++++---- test/reproduce.test.ts | 81 ++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 134 insertions(+), 13 deletions(-) create mode 100644 test/reproduce.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 73eee7d..372f968 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -30,6 +30,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - 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. - 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 diff --git a/docs/CONTRACTS.md b/docs/CONTRACTS.md index d8c96bf..79ca955 100644 --- a/docs/CONTRACTS.md +++ b/docs/CONTRACTS.md @@ -24,7 +24,9 @@ src/gen/header.ts moduleFor(dest, ctx) → string (CORE, 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 diff --git a/src/cli.ts b/src/cli.ts index da13c63..ea02307 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -2,7 +2,8 @@ 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 { DEFAULTS, resolveAnswers } from './presets.ts'; import { buildContext, effectiveAnswers, ignoredOptions, reportedAnswers, validateName, validateRustVersions } from './context.ts'; @@ -78,6 +79,12 @@ 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(', '); @@ -147,7 +154,7 @@ async function runInteractive({ caps, answers, plan, target, shown, force, overw 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; } @@ -203,7 +210,8 @@ export async function main(argv: string[]) { // 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).`); } @@ -246,8 +254,8 @@ export async function main(argv: string[]) { 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)); }; diff --git a/src/reproduce.ts b/src/reproduce.ts index 63fa34f..51ea67a 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 { basename, isAbsolute, relative, resolve } from 'node:path'; import { resolveAnswers } from './presets.ts'; import { effectiveAnswers } from './context.ts'; import type { Answers } from './types.ts'; @@ -13,11 +14,32 @@ 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. + */ +export function shownTarget(dir: string | undefined, name: string, cwd: string = process.cwd()): string { + const target = resolve(cwd, dir ?? name); + const rel = relative(cwd, target); + return rel.startsWith('..') || isAbsolute(rel) ? target : rel || '.'; +} + +/** + * @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 +68,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/test/reproduce.test.ts b/test/reproduce.test.ts new file mode 100644 index 0000000..a99bbc8 --- /dev/null +++ b/test/reproduce.test.ts @@ -0,0 +1,81 @@ +/** 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 { join } 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`); + const cwd = join('/', 'work'); + assert.equal(shownTarget('fl-dir', 'fl-renamed', cwd), 'fl-dir', 'the positional wins over the name'); + assert.equal(shownTarget(undefined, 'fl-renamed', cwd), 'fl-renamed'); + assert.equal(shownTarget('.', 'x', cwd), '.'); + assert.equal(shownTarget('../elsewhere', 'x', cwd), join('/', 'elsewhere'), 'outside cwd: absolute'); +}); From 4a651acf41eab1872cfa6d00c597ca7892c481bb Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 04:09:14 +0000 Subject: [PATCH 20/40] docs: align this repo's docs with the code CHANGELOG's CI line says Node 22 and 26, which is what ci.yml runs and what engines (>=22.18) allows. PLAN section 5: npm pack ships dist/ and templates/, and no preset snapshots exist yet. CONTRACTS: post.fetch in Answers and the full binary-extension list from src/engine/plan.ts. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01W2BaQjmXXv2ZSgkAnMH1eA --- CHANGELOG.md | 5 ++++- docs/CONTRACTS.md | 5 +++-- docs/PLAN.md | 5 +++-- 3 files changed, 10 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f818bca..a4e1c74 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 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. @@ -87,7 +90,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/docs/CONTRACTS.md b/docs/CONTRACTS.md index 25675fb..b01c603 100644 --- a/docs/CONTRACTS.md +++ b/docs/CONTRACTS.md @@ -46,7 +46,7 @@ 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, } ``` @@ -92,7 +92,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 (`//`, `#`, ` `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. From b66cd195d71f26170d618fecbc372148cd3e687e Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 04:22:28 +0000 Subject: [PATCH 29/40] fix(prompts): Esc inside Customize steps back instead of quitting Esc on the Customize menu returns to the review; Esc inside a section or the preset re-pick reopens the menu and drops only that section's edits. Ctrl-C still quits everywhere. @clack/core maps both keys to cancel, so prompts opened with back: true watch the key event and resolve Esc to BACK. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01W2BaQjmXXv2ZSgkAnMH1eA --- CHANGELOG.md | 4 +++ docs/CONTRACTS.md | 7 ++-- src/prompts.ts | 85 +++++++++++++++++++++++++++++--------------- src/ui/choose.ts | 48 ++++++++++++++++++++----- src/ui/rail.ts | 10 ++++-- test/prompts.test.ts | 61 +++++++++++++++++++++++++++++++ 6 files changed, 172 insertions(+), 43 deletions(-) create mode 100644 test/prompts.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 611d340..533794a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -35,6 +35,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 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. - 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 diff --git a/docs/CONTRACTS.md b/docs/CONTRACTS.md index dcc8d93..ba94914 100644 --- a/docs/CONTRACTS.md +++ b/docs/CONTRACTS.md @@ -210,10 +210,11 @@ bannerFrame(caps, frame) → string[]; showBanner(caps) → Promise // labels.ts: the words for every option; prompts, review and --help all read these FEATURES, TOOLING, CRATE_TOGGLES, LOGGING, ASYNC, HTTP, LICENSES, STACKS, KINDS, grouped(catalogue) // choose.ts -pick(caps, { message, options: Item[], initialValue?, io? }) → value | cancel symbol -pickMany(caps, { message, options: Item[], initialValues?, io? }) → values | cancel symbol +pick(caps, { message, options: Item[], initialValue?, back?, io? }) → value | cancel symbol | BACK +pickMany(caps, { message, options: Item[], initialValues?, back?, io? }) → values | cancel symbol | BACK +// back: true → Esc resolves to BACK (footer `esc back`); Ctrl-C always resolves to the cancel symbol // rail.ts -text(caps, { message, placeholder?, defaultValue?, initialValue?, validate?, io? }) → string | cancel symbol +text(caps, { message, placeholder?, defaultValue?, initialValue?, validate?, back?, io? }) → string | cancel symbol | BACK note(caps, title, body); box(caps, title, lines); log(caps, lines); outro(caps, msg); cancel(caps, msg) tasks(caps, Task[]) → Promise // false as soon as a `required` task fails; later tasks don't run // motion.ts: one animated line per prompt diff --git a/src/prompts.ts b/src/prompts.ts index cd7e3b5..6a2973f 100644 --- a/src/prompts.ts +++ b/src/prompts.ts @@ -14,7 +14,7 @@ import { PRESETS, resolveAnswers } from './presets.ts'; import { shippedThemes } from './gen/themes.ts'; import { effectiveAnswers, validateBin, validateName } from './context.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 +31,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 +43,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 } : {}) })); @@ -126,9 +135,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' } : {}), @@ -154,15 +164,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); + preset = await pickPreset(preset ?? RECOMMENDED, true); return resolveAnswers(preset, { ...partial, name: 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 +199,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 +216,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 +228,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 +252,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 +261,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) => (/^\d+\.\d+(?:\.\d+)?$/.test(v ?? '') ? undefined : 'Use a version like 1.98') })); + out.toolchain = sect(await text(caps, { back: true, 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') })); } if (which === 'after') { @@ -247,7 +276,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 +284,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/ui/choose.ts b/src/ui/choose.ts index 4dd6c0e..d9a26a3 100644 --- a/src/ui/choose.ts +++ b/src/ui/choose.ts @@ -5,7 +5,7 @@ * 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'; @@ -43,6 +43,34 @@ function layout(caps: Caps, items: Item[], indent: number) { }); } +/** + * 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,7 +80,7 @@ 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 anim = { t: 0 }; @@ -64,26 +92,27 @@ export function pick(caps: Caps, o: { message: string; options: Item[]; in 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 === 'cancel') return o.back && seen.esc ? backFrame(caps, o.message) : `${head}${hex(caps, RED, c.g.cancel)} ${o.message}\n${c.bar()}`; 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`)}`; + const footer = `${c.live(c.g.barEnd)} ${dim(caps, o.footer ?? `${c.g.up}${c.g.down} move · enter select · ${escHint(o.back)}`)}`; return `${head}${c.live(c.g.step)} ${o.message}\n${body.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 grouped = o.options.some((i) => i.group); const rows = layout(caps, o.options, grouped ? 8 : 6); @@ -103,7 +132,7 @@ export function pickMany(caps: Caps, o: { message: string; options: Item[] 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)}`; } - if (this.state === 'cancel') return `${head}${hex(caps, RED, c.g.cancel)} ${o.message}\n${c.bar()}`; + if (this.state === 'cancel') return o.back && seen.esc ? backFrame(caps, o.message) : `${head}${hex(caps, RED, c.g.cancel)} ${o.message}\n${c.bar()}`; const out: string[] = []; let lastGroup: string | undefined; o.options.forEach((item, i) => { @@ -118,10 +147,11 @@ export function pickMany(caps: Caps, o: { message: string; options: Item[] 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 footer = `${c.live(c.g.barEnd)} ${dim(caps, 'space toggle · a all · enter confirm · esc cancel')}`; + const footer = `${c.live(c.g.barEnd)} ${dim(caps, `space toggle · a all · enter confirm · ${escHint(o.back)}`)}`; return `${head}${c.live(c.g.step)} ${o.message}\n${out.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/rail.ts b/src/ui/rail.ts index 71b6956..2a436a2 100644 --- a/src/ui/rail.ts +++ b/src/ui/rail.ts @@ -9,6 +9,7 @@ import { bold, dim, hex } from './rainbow.ts'; import { glyphs } from './glyphs.ts'; import { width } 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' }; @@ -30,6 +31,8 @@ export function rail(caps: Caps) { 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); @@ -42,7 +45,7 @@ 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. const input = this.userInput @@ -51,12 +54,13 @@ export function text(caps: Caps, o: { 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'); + const foot = err ? hex(caps, COLORS.warn, this.error) : dim(caps, `enter confirm · ${escHint(o.back)}`); return `${head}${step} ${o.message}\n${hex(caps, color, r.g.bar)} ${input}\n${hex(caps, color, r.g.barEnd)} ${foot}`; }, }); + 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/test/prompts.test.ts b/test/prompts.test.ts new file mode 100644 index 0000000..9a20e8b --- /dev/null +++ b/test/prompts.test.ts @@ -0,0 +1,61 @@ +/** + * 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 { stripVTControlCharacters } from 'node:util'; +import { isCancel } from '@clack/core'; +import { BACK, pick, pickMany } from '../src/ui/choose.ts'; +import { 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 }; +} + +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/); + }); +} From f1f08c93dec645c6e0ef0e361f2ec78af71aa3d8 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 04:24:26 +0000 Subject: [PATCH 30/40] fix(ui): restore the terminal when Ctrl-C interrupts the run steps tasks() hid the cursor and relied on finally, which never runs on SIGINT. A SIGINT handler now lives for the duration of tasks(): it shows the cursor, settles the spinner line, says the partly created folder was left in place and exits 130. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01W2BaQjmXXv2ZSgkAnMH1eA --- CHANGELOG.md | 3 ++ docs/CONTRACTS.md | 1 + src/cli.ts | 2 +- src/ui/rail.ts | 75 +++++++++++++++++++++++++++----------------- test/prompts.test.ts | 32 ++++++++++++++++++- 5 files changed, 83 insertions(+), 30 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 533794a..1dc9773 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -39,6 +39,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 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. - 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 diff --git a/docs/CONTRACTS.md b/docs/CONTRACTS.md index ba94914..1856ad7 100644 --- a/docs/CONTRACTS.md +++ b/docs/CONTRACTS.md @@ -217,6 +217,7 @@ pickMany(caps, { message, options: Item[], initialValues?, back?, io? }) → val text(caps, { message, placeholder?, defaultValue?, initialValue?, validate?, back?, io? }) → string | cancel symbol | BACK note(caps, title, body); box(caps, title, lines); log(caps, lines); outro(caps, msg); cancel(caps, msg) tasks(caps, Task[]) → Promise // false as soon as a `required` task fails; later tasks don't run +// tasks(caps, list, { interrupted }): Ctrl-C restores the cursor, prints `interrupted`, exits 130 // motion.ts: one animated line per prompt live(caps, prompt, state); marker(caps, glyph, t); shimmer(caps, text, t); wave(caps, frame) cascade(caps, lines); sparkle(caps, prefix, text) diff --git a/src/cli.ts b/src/cli.ts index ea02307..0a41b9f 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -141,7 +141,7 @@ async function runInteractive({ caps, answers, plan, target, shown, force, overw }, }, { 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) { diff --git a/src/ui/rail.ts b/src/ui/rail.ts index 2a436a2..748100d 100644 --- a/src/ui/rail.ts +++ b/src/ui/rail.ts @@ -131,38 +131,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/test/prompts.test.ts b/test/prompts.test.ts index 9a20e8b..5d26213 100644 --- a/test/prompts.test.ts +++ b/test/prompts.test.ts @@ -5,10 +5,11 @@ import { test } from 'node:test'; import assert from 'node:assert/strict'; import { PassThrough, Writable } from 'node:stream'; +import { spawnSync } from 'node:child_process'; import { stripVTControlCharacters } from 'node:util'; import { isCancel } from '@clack/core'; import { BACK, pick, pickMany } from '../src/ui/choose.ts'; -import { text } from '../src/ui/rail.ts'; +import { 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 }; @@ -59,3 +60,32 @@ for (const [name, make] of Object.entries(prompts)) { assert.match(r.out, /esc cancel/); }); } + +/** 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 }); +} + +test('Ctrl-C during the run steps restores the cursor, says what was left and exits 130 (B11)', () => { + const r = child(` + setTimeout(() => process.kill(process.pid, 'SIGINT'), 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/); +}); From 8cf43518291ee832610619403ad40e5a1ff4ecc6 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 04:25:31 +0000 Subject: [PATCH 31/40] fix(prompts): a re-picked preset beats --kind; review hint names the real folder MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Start over from a preset dropped the picked preset's kind in favour of the --kind flag. The re-pick now wins over --kind and --preset (other flags still apply). The review's 'writes ./…' hint uses shownTarget, so a positional dir is named even after a rename; ask() takes the dir. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01W2BaQjmXXv2ZSgkAnMH1eA --- CHANGELOG.md | 4 ++++ docs/CONTRACTS.md | 2 +- src/cli.ts | 2 +- src/prompts.ts | 30 ++++++++++++++++++++++++++---- test/prompts.test.ts | 23 +++++++++++++++++++++++ 5 files changed, 55 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1dc9773..c4c2820 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -42,6 +42,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - 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). - 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 diff --git a/docs/CONTRACTS.md b/docs/CONTRACTS.md index 1856ad7..871fc1e 100644 --- a/docs/CONTRACTS.md +++ b/docs/CONTRACTS.md @@ -12,7 +12,7 @@ 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) diff --git a/src/cli.ts b/src/cli.ts index 0a41b9f..c4a5513 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -240,7 +240,7 @@ 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); } diff --git a/src/prompts.ts b/src/prompts.ts index 6a2973f..9baba4d 100644 --- a/src/prompts.ts +++ b/src/prompts.ts @@ -12,7 +12,9 @@ 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 { isAbsolute } from 'node:path'; import { effectiveAnswers, validateBin, validateName } from './context.ts'; +import { shownTarget } from './reproduce.ts'; import { dim, hex, bold } from './ui/rainbow.ts'; import { BACK, pick, pickMany } from './ui/choose.ts'; import type { Item } from './ui/choose.ts'; @@ -120,8 +122,28 @@ 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): string { + const shown = shownTarget(dir, name, cwd); + return `writes ${isAbsolute(shown) || shown === '.' ? shown : `./${shown}`}`; +} + +/** + * 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; @@ -156,7 +178,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' }, ]), @@ -165,7 +187,7 @@ export async function ask(partial: PartialAnswers, caps: Caps, targetCheck: (nam if (next === 'cancel') got(Symbol.for('clack:cancel')); a = await customize(caps, a, targetCheck, async () => { preset = await pickPreset(preset ?? RECOMMENDED, true); - return resolveAnswers(preset, { ...partial, name: a.name }); + return startOver(partial, preset, a.name); }); } } diff --git a/test/prompts.test.ts b/test/prompts.test.ts index 5d26213..db377f3 100644 --- a/test/prompts.test.ts +++ b/test/prompts.test.ts @@ -6,6 +6,8 @@ import { test } from 'node:test'; import assert from 'node:assert/strict'; import { PassThrough, Writable } from 'node:stream'; import { spawnSync } from 'node:child_process'; +import { resolve } from 'node:path'; +import { startOver, writesHint } from '../src/prompts.ts'; import { stripVTControlCharacters } from 'node:util'; import { isCancel } from '@clack/core'; import { BACK, pick, pickMany } from '../src/ui/choose.ts'; @@ -61,6 +63,27 @@ for (const [name, make] of Object.entries(prompts)) { }); } +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 = resolve('/work/projects'); + assert.equal(writesHint(undefined, 'hp-cli', cwd), 'writes ./hp-cli'); + assert.equal(writesHint('fl-dir', 'fl-renamed', cwd), 'writes ./fl-dir'); + assert.equal(writesHint('.', 'here', cwd), 'writes .'); + assert.equal(writesHint('../elsewhere', 'x', cwd), `writes ${resolve('/work/elsewhere')}`); +}); + /** 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; From abcd6b083864b6734bc2b6687a62866bfc5bcbc3 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 04:27:00 +0000 Subject: [PATCH 32/40] fix(prompts): cross-check MSRV, toolchain and edition in Licence + Rust The prompts only checked each version's shape, so MSRV 9.0 with toolchain 1.0.0 got through. They now run validateRustVersions (worded for the prompt rather than for --msrv), trim whitespace first, and the text prompt wraps a long error onto rail lines. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01W2BaQjmXXv2ZSgkAnMH1eA --- CHANGELOG.md | 3 +++ src/prompts.ts | 33 ++++++++++++++++++++++++++++++--- src/ui/rail.ts | 11 ++++++++--- src/ui/tty.ts | 14 ++++++++++++++ test/prompts.test.ts | 38 +++++++++++++++++++++++++++++++++++++- 5 files changed, 92 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c4c2820..900c8cd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -46,6 +46,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 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. - 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 diff --git a/src/prompts.ts b/src/prompts.ts index 9baba4d..f8d5582 100644 --- a/src/prompts.ts +++ b/src/prompts.ts @@ -13,7 +13,7 @@ import { glyphs } from './ui/glyphs.ts'; import { PRESETS, resolveAnswers } from './presets.ts'; import { shippedThemes } from './gen/themes.ts'; import { isAbsolute } from 'node:path'; -import { effectiveAnswers, validateBin, validateName } from './context.ts'; +import { effectiveAnswers, validateBin, validateName, validateRustVersions } from './context.ts'; import { shownTarget } from './reproduce.ts'; import { dim, hex, bold } from './ui/rainbow.ts'; import { BACK, pick, pickMany } from './ui/choose.ts'; @@ -139,6 +139,33 @@ export function writesHint(dir: string | undefined, name: string, cwd?: string): return `writes ${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. @@ -288,8 +315,8 @@ async function section(caps: Caps, a: Answers, which: string, targetCheck: (name 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 = sect(await text(caps, { back: true, 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 = sect(await text(caps, { back: true, 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') { diff --git a/src/ui/rail.ts b/src/ui/rail.ts index 748100d..919d613 100644 --- a/src/ui/rail.ts +++ b/src/ui/rail.ts @@ -7,7 +7,7 @@ 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'; @@ -37,6 +37,7 @@ export function text(caps: Caps, o: { }) { 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 } : {}), @@ -54,8 +55,12 @@ export function text(caps: Caps, o: { 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 · ${escHint(o.back)}`); - 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); 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/test/prompts.test.ts b/test/prompts.test.ts index db377f3..0170197 100644 --- a/test/prompts.test.ts +++ b/test/prompts.test.ts @@ -7,7 +7,9 @@ import assert from 'node:assert/strict'; import { PassThrough, Writable } from 'node:stream'; import { spawnSync } from 'node:child_process'; import { resolve } from 'node:path'; -import { startOver, writesHint } from '../src/prompts.ts'; +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, pick, pickMany } from '../src/ui/choose.ts'; @@ -24,6 +26,9 @@ function harness() { 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. */ @@ -84,6 +89,37 @@ test('the review hint names the folder the run writes, including a positional di assert.equal(writesHint('../elsewhere', 'x', cwd), `writes ${resolve('/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)}`); +}); + /** 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; From 6eab8cbcb032c624d283255b59a011769460c337 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 04:38:13 +0000 Subject: [PATCH 33/40] fix(ui): window tall lists and fit option rows to narrow terminals pick/pickMany rendered every option at any height and forced a 10-column description, so lists taller than the terminal lost their focused row and left stale frames, and rows wrapped at 40 columns. Rows, footers and messages are now fitted to the live column count, and the body is windowed to the live row count around the focused row. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01W2BaQjmXXv2ZSgkAnMH1eA --- CHANGELOG.md | 5 ++ src/ui/choose.ts | 145 ++++++++++++++++++++++++++++++++++++------- test/prompts.test.ts | 62 +++++++++++++++++- 3 files changed, 187 insertions(+), 25 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 900c8cd..d7e393f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -49,6 +49,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - 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. - 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 diff --git a/src/ui/choose.ts b/src/ui/choose.ts index d9a26a3..5ba81e6 100644 --- a/src/ui/choose.ts +++ b/src/ui/choose.ts @@ -11,7 +11,7 @@ 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,92 @@ 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` @@ -82,25 +157,34 @@ export type Io = { input?: Readable; output?: Writable }; 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 o.back && seen.esc ? backFrame(caps, o.message) : `${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 · ${escHint(o.back)}`)}`; - 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); @@ -114,41 +198,54 @@ export function pick(caps: Caps, o: { message: string; options: Item[]; in */ 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); + const prefix = width(`${c.g.bar} ${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 o.back && seen.esc ? backFrame(caps, o.message) : `${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)}`); + body.push(`${c.live()} ${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 · ${escHint(o.back)}`)}`; - 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); diff --git a/test/prompts.test.ts b/test/prompts.test.ts index 0170197..9278f93 100644 --- a/test/prompts.test.ts +++ b/test/prompts.test.ts @@ -12,7 +12,8 @@ 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, pick, pickMany } from '../src/ui/choose.ts'; +import { BACK, clipEllipsis, fitFooter, layout, pick, pickMany, windowBody, windowStart } from '../src/ui/choose.ts'; +import { glyphs } from '../src/ui/glyphs.ts'; import { tasks, text } from '../src/ui/rail.ts'; import type { Caps } from '../src/types.ts'; @@ -120,6 +121,65 @@ test('a long validation error wraps on the rail instead of past the edge', async 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)}`); +}); + /** 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; From 78aa3671823c338eeaf6382c383d4a966cf61155 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 04:39:29 +0000 Subject: [PATCH 34/40] fix(ui): visible focus and text cursor without colour; --no-color emits no SGR With colour off, pickMany showed focus only through bold, and the text prompt used clack's inverse-video cursor, which sees NO_COLOR but not --no-color. A focus mark (glyphs.focus) now marks the focused row and a caret glyph the cursor position, with no escape codes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01W2BaQjmXXv2ZSgkAnMH1eA --- CHANGELOG.md | 4 ++++ src/ui/choose.ts | 7 +++++-- src/ui/glyphs.ts | 6 +++++- src/ui/rail.ts | 10 +++++++++- test/prompts.test.ts | 46 +++++++++++++++++++++++++++++++++++++++++++- 5 files changed, 68 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d7e393f..384ea85 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -54,6 +54,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - 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 diff --git a/src/ui/choose.ts b/src/ui/choose.ts index 5ba81e6..2dec2f7 100644 --- a/src/ui/choose.ts +++ b/src/ui/choose.ts @@ -200,7 +200,9 @@ export function pickMany(caps: Caps, o: { message: string; options: Item[] const c = chrome(caps); const out = o.io?.output ?? process.stdout; const grouped = o.options.some((i) => i.group); - const prefix = width(`${c.g.bar} ${grouped ? ' ' : ''}${c.g.boxOn} `); + // 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 }; @@ -238,7 +240,8 @@ export function pickMany(caps: Caps, o: { message: string; options: Item[] 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; - body.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 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)))}`; 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 919d613..bac122f 100644 --- a/src/ui/rail.ts +++ b/src/ui/rail.ts @@ -27,6 +27,12 @@ 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; @@ -49,8 +55,10 @@ export function text(caps: Caps, o: { 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; diff --git a/test/prompts.test.ts b/test/prompts.test.ts index 9278f93..869cd12 100644 --- a/test/prompts.test.ts +++ b/test/prompts.test.ts @@ -14,7 +14,7 @@ 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 { tasks, text } from '../src/ui/rail.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 }; @@ -180,6 +180,50 @@ test('a tall multi-select in a 40×10 terminal: every frame fits, the focused ro 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; From eed41b06f99a1fe7beea98d06c6bceb3bac50565 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 05:02:50 +0000 Subject: [PATCH 35/40] docs: add the dogfood report and evidence Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01W2BaQjmXXv2ZSgkAnMH1eA --- docs/dogfood/FINDINGS.md | 5 +- docs/dogfood/REPORT.md | 187 ++++++++++++++ docs/dogfood/evidence/3a-matrix.md | 216 ++++++++++++++++ docs/dogfood/evidence/3b-interactive.md | 169 +++++++++++++ docs/dogfood/evidence/4-validation.md | 198 +++++++++++++++ docs/dogfood/evidence/ENV.md | 43 ++++ .../evidence/friction-deskpulse-monitor.md | 189 ++++++++++++++ docs/dogfood/evidence/friction-humandur.md | 226 +++++++++++++++++ docs/dogfood/evidence/friction-logscan.md | 238 ++++++++++++++++++ docs/dogfood/evidence/friction-tailview.md | 197 +++++++++++++++ docs/dogfood/evidence/research.md | 115 +++++++++ 11 files changed, 1782 insertions(+), 1 deletion(-) create mode 100644 docs/dogfood/REPORT.md create mode 100644 docs/dogfood/evidence/3a-matrix.md create mode 100644 docs/dogfood/evidence/3b-interactive.md create mode 100644 docs/dogfood/evidence/4-validation.md create mode 100644 docs/dogfood/evidence/ENV.md create mode 100644 docs/dogfood/evidence/friction-deskpulse-monitor.md create mode 100644 docs/dogfood/evidence/friction-humandur.md create mode 100644 docs/dogfood/evidence/friction-logscan.md create mode 100644 docs/dogfood/evidence/friction-tailview.md create mode 100644 docs/dogfood/evidence/research.md diff --git a/docs/dogfood/FINDINGS.md b/docs/dogfood/FINDINGS.md index a021e2d..3890895 100644 --- a/docs/dogfood/FINDINGS.md +++ b/docs/dogfood/FINDINGS.md @@ -136,11 +136,14 @@ Ranked by value ÷ effort. "Changes defaults" items are proposals only. | P16 | **TUI log file location** | B22. | `dirs::state_dir()`/cache dir, or `create_new` with a per-process name. | `templates/tui/files/src/logging.rs` | Yes (file location) | | P17 | **`.gitignore` `*.log`** | F14. | Anchor it (`/*.log`) so fixtures under `tests/` are tracked. | `templates/base/files/_gitignore:4` | Yes | | P18 | **New presets: axum service, wasm, `no_std`; macOS GUI** | No dogfood evidence either way; each is a new template group with its own lint and CI story. macOS CI targets depend on P4. | One preset at a time, axum first (largest audience, reuses the cli group). | `templates/`, `src/presets.ts` | No | -| P19 | **npm name** | `src/reproduce.ts:9-14`: the tool runs from GitHub because the `create-rust-app` name is not this project's. | See REPORT.md for the name research. | `package.json`, `src/reproduce.ts` | Owner decision | +| P19 | **npm name** | `src/reproduce.ts:9-14`: the tool runs from GitHub because the `create-rust-app` name is not this project's. | `@freeknet/create-rust-app` (`npm create @freeknet/rust-app`), then `create-rust-app-kit`; research in REPORT.md. | `package.json`, `src/reproduce.ts` | Owner decision | | P20 | **Third-party template groups** | No evidence of demand. The group format (`manifest.js`, `deps.js`) executes code, so loading external groups is a trust decision. | Defer until P12 fixes the answers file and the group API is documented as stable. | `src/engine/groups.ts` | No | ## 5. Fix plan (Phase 3) +All eight rows were implemented; commits, the after-matrix and what was deferred are in +[REPORT.md](REPORT.md). + In scope: bug fixes, missing validation, better errors, docs, tests. Nothing here changes a flag, a default answer, the lint table, the banner format, licence options or file layout. diff --git a/docs/dogfood/REPORT.md b/docs/dogfood/REPORT.md new file mode 100644 index 0000000..e66a71e --- /dev/null +++ b/docs/dogfood/REPORT.md @@ -0,0 +1,187 @@ +# Dogfood report, November 2026 + +Before: `db3693d`. After: `58847b6` plus this report. Branch `claude/jolly-curie-lpi8jt`, +34 commits, no merges to `main`, no tags, no release, nothing published. + +The detailed findings are in [FINDINGS.md](FINDINGS.md). The agents' full reports are in +[`evidence/`](evidence/); they cite raw logs under `logs/…`, which lived in a scratch +directory outside the repo and were not kept. + +## Outcome + +- **Gate matrix:** 156 of 187 cells passed before; 165 of 187 pass after, and 40 new cells + (64-character names, changelog checks, full gates on every GUI combination) all pass. + No cell went from pass to fail. +- **Still failing, 22 cells:** 14 are zizmor's `dependabot-cooldown` (an owner decision, P11); + 8 are expected (`minimal` ships no `deny.toml`; binaries set `publish = false`). +- **Bugs:** 20 of the 22 in FINDINGS §1 are fixed. B22 (TUI log path) is deferred to the + backlog because the fix moves a file; the `--json` post-step behaviour is documented, not + changed. +- **Tests:** 58 before, 164 after. + +## Environment + +Ubuntu 24.04 container, Node 22.23.5, npm 10.9.9, rustup 1.29.3. Rust 1.99.1 (the pin) +and 1.98.1 (MSRV) with rustfmt and clippy; default stable was 1.97.0. cargo-deny 0.22.0, +cargo-msrv 0.19.6, zizmor 1.32.0 (run with `--offline`), actionlint 1.7.12 (no shellcheck, +so `run:` scripts were not linted), xvfb. GUI development libraries were installed through +apt. The reference projects `../rustaman` and `../strobe` were not present. Details: +[evidence/ENV.md](evidence/ENV.md). + +## Gate matrix, before and after + +Gates per combination: scaffold, fmt, clippy, clippy `--all-features`, test, cargo-deny, +rustdoc with `-D warnings`, MSRV build on 1.98, actionlint, zizmor. Full tables: +[evidence/3a-matrix.md](evidence/3a-matrix.md) (before) and +[evidence/4-validation.md](evidence/4-validation.md) (after). + +| Combination | Before | After | +|---|---|---| +| cli, tui, strobe, and the cli variants (subcommands + `--bin`, tokio + reqwest, edition 2021, tracing) | all Rust gates pass; zizmor fails (high) | all Rust gates pass; zizmor: `dependabot-cooldown` only | +| lib | all pass; zizmor fails (medium) | all pass; zizmor: `dependabot-cooldown`, plus info-level trusted publishing | +| minimal | all pass; zizmor fails (medium) | all pass, zizmor clean | +| rustaman | **doc fails**; zizmor fails | all Rust gates pass; zizmor: `dependabot-cooldown` only | +| rustaman `--with tray,singleInstance` | **fmt and doc fail** | pass | +| rustaman `--without demo` | **fmt and doc fail** | pass | +| rustaman `--base graphite --accent #ff9f6e` | **fmt and doc fail** | pass | +| rustaman `--gui winit-glow` | pass | pass | +| custom | **doc fails** | pass | +| strobe `cargo xtask ci`, `cargo xtask changelog` | pass, but the changelog run rewrote the header | pass, and CHANGELOG.md is unchanged | +| lib `cargo publish --dry-run` | pass | pass | +| each `--license` with cargo-deny | pass | pass | +| `--dry-run --json`, all 7 presets | valid, matches a real run | same | +| 64-character names: rustaman, strobe, cli, tui (fmt, clippy, test, doc) | not run; fmt failed from 14 characters on GUI kinds | all pass | +| `cargo run --example changelog -- --check` on a fresh single-crate scaffold | fails | passes | + +Baseline on the final branch: `npm ci`, `npm run typecheck`, `npm test` (164/164) and +`npm run build` all exit 0. + +## What was fixed + +| Finding | Fix | Commits | +|---|---|---| +| B1 fmt fails for names of 14+ characters | No generated line's width depends on the name: binaries alias the crate (`use as app;`), tests use constants or `env!("CARGO_PKG_NAME")`. Checked for every preset at 1 and 64 characters. | `b51a54a`, `ac959a0`, `92d5f6f`, `fbc3408` | +| B2, B3 rustdoc errors | GUI `run.rs`, tray and cli `db.rs` doc links corrected | `5bcdfde`, `019ffe7` | +| B4–B6 name validation | Rust keywords, Cargo and Windows reserved names and names over 64 characters are refused; a failed write removes what it created | `0d5b1b2`, `9505f95` | +| B7 positional folder silently renamed | A `note:` on stderr names the crate and points at `--name` | `99f5439` | +| B8, B9 recreate command | Carries accent, author, GitHub handle, display name, email and post-steps; names the real folder. Round-trip test over a spread of answers. | `7712459`, `8cf4351` | +| B10 MSRV newer than toolchain | Refused with exit 2, on the command line and in the prompt; also MSRV below what the edition needs | `7a38d56`, `abcd6b0` | +| B11 Ctrl-C during run steps | SIGINT handler restores the cursor, says what was left, exits 130 | `f1f08c9` | +| B12 `--kind` overriding a re-picked preset | The re-pick wins | `8cf4351` | +| B13, F4 changelog | The shipped CHANGELOG.md is what the project's generator writes; docs say one thing; `cargo xtask changelog` is generated only with the generator on | `6d57531`, `7b4b366`, `c052781`, `69684ec` | +| B14, B15 short and narrow terminals | Lists window to the terminal's rows; rows and footers clip to its width, read at render time | `6eab8cb` | +| B16, B17 no-colour focus | A focus glyph on multi-select rows, a caret for the text cursor, zero SGR with `--no-color` | `78aa367` | +| B18 empty tagline | Resolved once in the context | `ae820f7` | +| B19 fresh empty repository | First commit is made there, staged by path; the summary is truthful when git is skipped | `7445c64` | +| B20, F17 ignored options | A stderr note per ignored option; `guiStack` blank in `--json` for kinds without a GUI | `166fe1d` | +| F18 `--force` | Lists the files it overwrote | `9505f95` | +| B21 `scaffold-check` | `--set` splits on the first `=`; respects `CARGO_TARGET_DIR`; new `--gate fmt`, `--gate doc`, `--name` | `d9e175b` | +| F6 zizmor | `persist-credentials: false` on every checkout; no Actions cache in the release build. Generated workflows: 10 findings → 2 (rustaman, strobe, cli, tui), 8 → 3 (lib), 3 → 0 (minimal). | `eff8d91`, `c67252a` | +| F8 Esc in Customize | Steps back one level; Ctrl-C still quits | `b66cd19` | +| F7, F10, F19 generated docs | Colour count, tray and palette mentions, `assert!` wording, Linux runtime libraries, attestation requirement, release-target comment, header-check directories, `unsafe_check` message | `c11038a`, `9209843` | +| TUI pins | ratatui 0.30, crossterm 0.29 | `80e32b1` | +| This repo | `setup-node` pinned to a SHA, checkout credentials dropped, CHANGELOG/PLAN/CONTRACTS corrected, `--json` help text | `3ce7a92`, `4a651ac`, `8710457` | + +Every fix has a `node --test` regression test: `test/validation.test.ts`, +`notices.test.ts`, `git.test.ts`, `write.test.ts`, `reproduce.test.ts`, +`name-length.test.ts`, `scaffold-check.test.ts`, `xtask.test.ts`, `workflows.test.ts`, +`changelog.test.ts`, `docs.test.ts`, `prompts.test.ts`. + +## Changes that touch a convention + +Each was needed to make a stated gate pass, and each is small, but they change generated +output and are the owner's to confirm or revert. + +1. **`Unreleased` changelog entries carry no commit hash** (`6d57531`). A scaffolded + CHANGELOG.md cannot contain the hash of the commit that adds it, so this is what lets a + fresh project match its own generator. Released sections keep hashes and links. +2. **The header check exempts the `Module:` line from the 100-column limit** (`ac959a0`). + Its value is the file's path, which a 64-character crate name pushes past the limit. +3. **`Dependencies:` banner lines say "the library crate"** instead of repeating the crate + name, and binaries alias the crate as `app` (`b51a54a`, `ac959a0`). +4. **Esc inside Customize goes back instead of quitting** (`b66cd19`). +5. **`--json` reports `guiStack: ""`** for kinds without a GUI (`166fe1d`). +6. **An empty tagline reads as the project name** everywhere, where the README used to + show `****` (`ae820f7`). + +## Deferred, and why + +| Item | Why | +|---|---| +| Author defaults to the template author (F9, P1) | Changes a default answer | +| `--json` skipping post-steps while reporting them on (P3) | Behaviour decision; help, README and CONTRACTS now say what it does | +| Windows-only release workflow (F1, P4) | Changes the generated release matrix | +| CI jobs for MSRV and rustdoc; `toolchain_pin` rejecting an MSRV job (F5, P6) | Changes generated CI and a guard | +| No home for non-Windows `unsafe` (F3, P7) | Changes the boundary convention. The check's message now names `src/win/`, though for eframe it also accepts `src/gui/run/`. | +| Dependabot cooldown, trusted publishing, tests before publish (P11) | Changes release and update behaviour; the cause of every remaining zizmor finding | +| Lib packaging `exclude`, unused lib dependencies (F11, P9) | Changes the lib preset | +| CLI skeleton I/O injection, Debug error output, config override (F2, F12, F13, P10) | Changes generated layout | +| TUI log file in `/tmp` (B22, P16) | Moves a file | +| `*.log` in `.gitignore` (F14, P17), cargo-deny allow-list noise (F15, P15) | Change generated defaults | +| Review screen omitting edited values (F16, P14) | Review layout | +| rusqlite `0.41` → 0.43, cargo-cyclonedx 0.5.9 → 0.5.10, cargo-deny-action v2.1.1 → v2.1.3 | Found by the version research after the fix plan was set; not exercised by a dogfood build | +| Released changelog entries formatted differently by the example and the xtask generator | Cosmetic; found in validation | +| `header_check.rs`'s own banner omits `benches/` and `build.rs` | Cosmetic; the docs are correct | +| `--bin`, display name, tagline and author have no length cap, so a very long one can still push a line past 100 columns | Needs a decision on the caps | +| Inconsistent `✖` / `error:` prefix; `-y` runs not printing the recreate command | Minor; unchanged | + +## Ranked backlog + +Full entries with design and files are in FINDINGS §4. Top of the list: + +1. **P1 Ask for, or derive, the author.** Every project is stamped with the template + author's name and handle. +2. **P4 Cross-platform release matrix.** A CLI or TUI ships only a Windows zip. +3. **P11 Workflow hardening**: Dependabot cooldown, crates.io trusted publishing, tests + before publish. Clears the remaining zizmor findings. +4. **P6 CI jobs for MSRV and rustdoc**, with a toolchain-pin test that allows them. +5. **P2 Snapshot tests of generated trees.** The name-length and doc gates landed here; + per-preset snapshots are the follow-up. +6. P5 saved answer profile; P3 `--json` post-steps; P7 non-Windows `unsafe` home; + P10 CLI skeleton I/O; P9 lib packaging; P8 `doctor`; P12 `upgrade`/`diff`; P13 `add`. + +### npm name (P19) + +`create-rust-app` on npm is an unowned tombstone: one version, 0.0.0, published +2022-03-12 and unpublished 2025-06-19. npm's policy does not say whether another account +may claim an unpublished name, and crates.io has a well-known unrelated `create-rust-app` +generator, so the name invites confusion either way. Free at the time of checking: + +| Package | Invocation | Note | +|---|---|---| +| `@freeknet/create-rust-app` | `npm create @freeknet/rust-app` | Keeps the name, makes authorship clear. Needs the `freeknet` npm scope, whose ownership could not be confirmed. | +| `create-rust-app-kit` | `npm create rust-app-kit` | Unscoped, no similar name exists | +| `@freeknet/create` | `npm create @freeknet` | Shortest command; needs the scope | + +Also free: `create-rusty-app`, `create-ferris-app`, `create-rust-project`, +`create-rust-scaffold`, `create-crate`. Taken: `create-rs-app`, `create-cargo-app`, +`create-rust`, `create-rs`, `create-cargo`. Full table: +[evidence/research.md](evidence/research.md). + +## Friction logs, summarised + +Four projects were built on fresh scaffolds; all four pass every generated gate. + +| Project | What was built | Top friction | Log | +|---|---|---|---| +| `logscan` (cli, subcommands) | Log analyser: parse, filter, stats; files and stdin; 67 tests | `run(args, out)` has no stdin or terminal info (~25 min); Windows config isolation (~10 min); zizmor (~8 min); changelog check failing on the untouched scaffold (~6 min) | [friction-logscan.md](evidence/friction-logscan.md) | +| `tailview` (tui) | Live multi-file tail viewer with filter, follow/pause, help; 43 tests | Windows-only release workflow (~25 min); changelog contradiction (~15 min); zizmor (~10 min); outdated ratatui/crossterm pins (~5 min) | [friction-tailview.md](evidence/friction-tailview.md) | +| `humandur` (lib) | Duration parser with `serde` feature, 18 doctests, property tests | No MSRV/doc/package CI job and `toolchain_pin` blocking one (~15 min); package ships repo files (~8 min); unused dependencies (~5 min) | [friction-humandur.md](evidence/friction-humandur.md) | +| `deskpulse-monitor` (rustaman) | Monitor page, background sampler, persisted settings; ran under xvfb | No home for unix `unsafe` (~25 min); Linux runtime libraries undocumented (~15 min); workflows (~15 min); fmt and doc failures on the untouched scaffold | [friction-deskpulse-monitor.md](evidence/friction-deskpulse-monitor.md) | + +Re-check on a fresh `logscan` scaffold from the final branch: the changelog check passes, +rustdoc passes, zizmor reports only `dependabot-cooldown`, the changelog statements in +CLAUDE.md, CONTRIBUTING and README agree with the generator, and a wrong header fails +`cargo test` with "src/parse.rs: declares `Module: scan` but sits at `parse`". + +In every project the header check, cargo-deny's allow-list and the lint table cost almost +nothing: new files passed the header check first time, no added crate was blocked, and +`#[expect]` was rarely needed. + +## Process notes + +- The prompt asked for a local branch `improve/dogfood-2026-11` and no pushes. This ran in + an ephemeral cloud session configured for `claude/jolly-curie-lpi8jt`, whose stop hook + requires commits to be pushed, so the work is on that branch on the remote. No pull + request, tag, release or package was created. +- Subagent commits carry the attribution line of the model that wrote them. diff --git a/docs/dogfood/evidence/3a-matrix.md b/docs/dogfood/evidence/3a-matrix.md new file mode 100644 index 0000000..f2cff02 --- /dev/null +++ b/docs/dogfood/evidence/3a-matrix.md @@ -0,0 +1,216 @@ +# 3a — Scaffold matrix (create-rust-app @ db3693d, dist/ as built) + +Date 2026-11-20. Toolchains: 1.99.1 (pin, auto-selected by generated `rust-toolchain.toml`), 1.98.1 (MSRV). +cargo-deny 0.22.0, actionlint 1.7.12, zizmor 1.32.0 (`--offline`). + +## How it was run + +- Driver scripts (all in `/home/user/cra-dogfood/scripts/`): + - `matrix-lib.sh` (helpers: `scaffold`, `gate`, `gates`), `matrix-nongui.sh`, `matrix-gui.sh`, `matrix-lic.sh`, + `matrix-probe.sh` (name-length fmt probe, Windows-target clippy, upgrade of reduced GUI combos to full gates), + `edge.sh` (edge cases), `jsoncheck.sh` (`--dry-run --json`), `recreate.exp` (expect driver for the interactive finish screen). +- Gates were run **directly** with the built CLI (not `scripts/scaffold-check.mjs`), because scaffold-check hard-codes + `CARGO_TARGET_DIR=/.scratch/target` and writes into `/.scratch` by default (finding 17). +- Scaffold: `node dist/bin/create-rust-app.js -y` in `/home/user/cra-dogfood/projects/matrix/` (default post-steps: cargo fetch + git init/commit). +- Gates: `cargo fmt --all -- --check`; `cargo clippy --workspace --all-targets -- -D warnings`; same with `--all-features` (CONTRACTS' form); + `cargo test --workspace`; `cargo deny check`; `RUSTDOCFLAGS='-D warnings' cargo doc --no-deps --workspace`; `cargo +1.98 build --workspace`; + `actionlint .github/workflows/*.yml`; `zizmor --offline .github/`. Extra: `clippy-win` = clippy with `--target x86_64-pc-windows-msvc`. +- CARGO_TARGET_DIR: `/home/user/cra-dogfood/target-matrix` (non-GUI), `target-matrix-gui` (GUI, so the two drivers didn't block each other on the + build-dir lock), `target-edge` (edge/licence probes). The built CLI itself respects the env var (it only runs `cargo fetch`). +- Logs: `/home/user/cra-dogfood/logs/matrix//.log`; raw results `logs/matrix/results.tsv`; edge cases `logs/matrix/edge/.log` + (+ `summary.tsv`); JSON checks `logs/matrix/jsoncheck/`; recreate `logs/matrix/recreate/`. +- Builds were much faster than expected (warm registry/caches); no disk problems (58 GB free throughout). +- All combos got the full gate set except `rustaman-graphite` and `custom` (no `clippy-allfeat`), the licence combos (scaffold + deny + inspect, as asked), and `lib-publish`. + +## Pass/fail table + +Exit codes in parentheses. zizmor exit 13 = highest finding medium, 14 = high (zizmor docs). "–" = 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(14) | | +| rustaman | PASS | PASS | PASS | PASS | PASS | – | PASS | PASS | FAIL(101) | PASS | PASS | FAIL(14) | | +| lib | PASS | PASS | PASS | PASS | – | – | PASS | PASS | PASS | PASS | PASS | FAIL(13) | | +| minimal | PASS | PASS | PASS | PASS | – | – | PASS | N/A(no deny.toml) | PASS | PASS | PASS | FAIL(13) | | +| tui | PASS | PASS | PASS | PASS | – | – | PASS | PASS | PASS | PASS | PASS | FAIL(14) | | +| lib-publish | PASS | – | – | – | – | – | – | – | – | – | – | – | publish-dry-run: PASS | +| cli-subcmd-bin | PASS | PASS | PASS | PASS | – | – | PASS | PASS | PASS | PASS | PASS | FAIL(14) | run-help: PASS | +| cli-tokio-reqwest | PASS | PASS | PASS | PASS | – | – | PASS | PASS | PASS | PASS | PASS | FAIL(14) | | +| cli-ed2021 | PASS | PASS | PASS | PASS | – | – | PASS | PASS | PASS | PASS | PASS | FAIL(14) | | +| cli-tracing | PASS | PASS | PASS | PASS | – | – | PASS | PASS | PASS | PASS | PASS | FAIL(14) | | +| strobe | PASS | PASS | PASS | PASS | PASS | – | PASS | PASS | PASS | PASS | PASS | FAIL(14) | xtask-ci: PASS, xtask-changelog: PASS | +| 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 | FAIL(1) | PASS | PASS | PASS | – | PASS | PASS | FAIL(101) | PASS | PASS | FAIL(14) | | +| rustaman-nodemo | PASS | FAIL(1) | PASS | PASS | – | – | PASS | PASS | FAIL(101) | PASS | PASS | FAIL(14) | | +| rustaman-glow | PASS | PASS | PASS | PASS | PASS | – | PASS | PASS | PASS | PASS | PASS | FAIL(14) | | +| rustaman-graphite | PASS | FAIL(1) | PASS | – | – | PASS | PASS | PASS | FAIL(101) | PASS | PASS | FAIL(14) | | +| custom | PASS | PASS | PASS | – | – | PASS | PASS | PASS | FAIL(101) | PASS | PASS | FAIL(14) | | + +Notes on cells: +- `minimal` deny / `minimal-lic-*` deny FAIL(4): minimal has `cargoDeny` off, so there is no deny.toml and cargo-deny's built-in defaults allow no licence. Not a generator bug; re-run as `lic1..4-deny` (`--with cargoDeny`): all PASS. + Also note the `minimal-lic-*` crates were all named `my-app` because the uppercase dir name was silently rejected (finding 6). +- `lic*-deny` publish-dry-run FAIL(101): binary kinds write `publish = false` deliberately; expected. `lib-publish` (publishable) PASS. +- `clippy-win` was run on rustaman, rustaman-tray-si, strobe, rustaman-glow, cli: all PASS (Windows-only code such as tray/single-instance/`src/win/` is invisible to Linux clippy). + +### Name-length probe (fmt only; `--name` of N chars, nothing else changed) — `logs/matrix/fmtlen--/fmt.log` + +| preset | 2 | 8 | 16 | 24 | +|---|---|---|---|---| +| rustaman | PASS | PASS | FAIL | FAIL | +| strobe | PASS | PASS | FAIL | FAIL | +| cli / tui / lib / minimal | PASS | PASS | PASS | PASS | + +Threshold for rustaman: 13 chars PASS, 14 chars FAIL (`logs/matrix/fmtlen-threshold/summary.txt`). + +### `--dry-run --json` per preset (`logs/matrix/jsoncheck/summary.tsv`, `normalized-summary.txt`) + +All 7 (rustaman strobe cli tui lib minimal custom): exit 0, stdout is a single valid JSON document starting with `{`, 0 bytes on stderr, +no directory created. Plan file list == files written by a real `-y --no-git --no-fetch` run (58/68/30/31/30/17/57 files) after normalising +the project name. `--preset custom -y` works non-interactively (= defaults: eframe GUI without the screenshot example). + +### Edge cases (`logs/matrix/edge/summary.tsv`; each `.log` has command, exit, stdout, stderr) + +| case | exit | result | +|---|---|---| +| `--name ''`, `MyApp`, `1app`, `'my app'`, `a/b`, `../escape`, `app-` | 2 | rejected with clear message ✔ | +| `--name test`, `std` | 2 | "reserved in Rust" ✔ | +| `--name fn` / `async` / `type` | 0 | **accepted; generated code doesn't compile** (finding 4) | +| `--name` 300 chars (minimal) | 0 | accepted; cargo fails "File name too long" (finding 5) | +| `--name` 260 chars (rustaman) | 1 | ENAMETOOLONG mid-write, partial project left behind (finding 5) | +| positional `MyDir`, `sub2/Weird_Dir` | 0 | crate silently named `my-app` (finding 6) | +| positional `sub/dir/proj` | 0 | nested dirs created, name `proj` ✔ | +| non-empty dir, no `--force` | 1 | "is not empty. Pick another directory or pass --force." ✔ (checked before any prompt) | +| non-empty dir, `--force` | 0 | unrelated `keep.txt` kept; colliding `README.md` silently overwritten (finding 12) | +| target is a file | 1 | "exists and isn't a directory." ✔ | +| `--no-git` | 0 | no `.git` ✔ ; default run: one commit `feat: scaffold gd with create-rust-app` ✔ | +| `--no-fetch` | 0 | no Cargo.lock ✔ ; default writes Cargo.lock ✔ | +| `--with tray --without tray`, `--with sqlite --without sqlite` | 0 | last wins (documented) ✔ | +| `--preset lib --with tray`; `--preset tui --with subcommands`; `--preset minimal --with subcommands`; `--preset lib --bin foo` | 0 | silently dropped, no warning (finding 13) | +| `--preset cli --gui winit-glow` | 0 | accepted silently; JSON reports `guiStack: "winit-glow"` for a cli (finding 13) | +| `--dry-run --open code` | 0 | tree printed, nothing written, no editor ✔ | +| `--msrv 1.100 --toolchain 1.99.1` | 0 | accepted; `cargo check` fails "rustc 1.99.1 is not supported" (finding 9) | +| `--msrv latest`, `--toolchain 1.99` | 2 | rejected ✔ | +| `--set foo.bar=1`, `features.nope=true`, `__proto__.x=1` | 2 | "Unknown answer key" ✔ | +| `--set features.tray=yes` / `crates.http=curl` / `features=true` / `name=true` / `tagline=true` | 2 | type/choice errors ✔ (note: `tagline=true` can't be set — "tagline must be string", minor) | +| `--set 'tagline=a=b==c'`, quotes/backslashes in value | 0 | value kept intact and escaped correctly in Cargo.toml ✔ | +| `--set features.tray`, `--set =x` | 2 | "--set expects key.path=value." ✔ | +| unknown flag / feature / preset / accent / base / edition / license / open | 2 | clear errors with "Did you mean" ✔ | +| two positionals | 2 | ✔ | +| `NO_COLOR=1` (pty), `--no-color` (pty): run, error, help | 0 | 0 ESC bytes ✔ (control: same run without them has 9 ESC) | +| stdin `` names (13 chars for rustaman), one under the threshold, so tests can't see it. + +2. **(H) eframe GUI projects fail `RUSTDOCFLAGS=-D warnings cargo doc`.** Repro: `--preset rustaman -y`, then the doc gate → exit 101. + Errors: `rustdoc::private_intra_doc_links` (`[`backends`]` links a private fn) and `rustdoc::redundant_explicit_links` (`[`App`](super::app::App)`). + Affects rustaman, custom, rustaman-nodemo, rustaman-graphite, rustaman-tray-si; winit-glow (strobe, rustaman-glow) passes. + Logs: `logs/matrix/rustaman/doc.log` (+ same gate in those combos). Root cause: `templates/gui/files/src/gui/run.rs:13` and `:20`. + +3. **(M) `--with tray`: broken intra-doc link on non-Windows.** `//! … [`crate::win::tray`]` points at a `cfg(windows)` module, so docs on Linux fail + (`rustdoc::broken_intra_doc_links`). Log: `logs/matrix/rustaman-tray-si/doc.log`. Root cause: `templates/gui-features/files/src/tray.rs:11`. + +4. **(M) Rust keywords accepted as project names; generated code doesn't compile.** `--name fn|async|type --preset minimal -y` → exit 0, then + `cargo check`: `error: expected identifier, found `::`` at `src/main.rs:17` (`fn::run(…)`). Expected: rejected like `test`/`std`. + Logs: `logs/matrix/edge/name-kw-{fn,async,type}.log`, `edge/cargo-check-d4{,b,c}.log`. Root cause: `src/context.ts:11` reserved list has no keywords (`fn, async, type, match, mod, use, …`; `self/crate/super` are already there). + +5. **(M) No length limit on names.** 300-char `--name` scaffolds (exit 0), but `cargo check` fails "File name too long (os error 36)" + (`edge/cargo-check-d7.log`). With a GUI preset (260 chars) the CLI itself dies mid-write — `error: ENAMETOOLONG … copyfile … assets/@@name@@.ico`, exit 1 — + and leaves a partial project (`edge/name-long-gui.out`). Root cause: `src/context.ts:5` (`NAME_RE` unbounded); `src/engine/write.ts:33-38` writes in place with no cleanup on failure. (crates.io caps names at 64.) + +6. **(M) A positional dir that isn't a valid crate name silently becomes `my-app`.** `create-rust-app MyDir --preset minimal -y` → dir `MyDir`, crate `my-app`, no warning + (same for `sub2/Weird_Dir`; it also renamed all four `minimal-lic-*` matrix crates). Logs: `edge/name-positional-only-upper.log`, `edge/name-positional-path2.log`, + `logs/matrix/minimal-lic-MIT/deny.log` ("my-app v0.1.0"). Root cause: `src/cli.ts:190-193` (invalid basename is ignored instead of reported, or snake/lower-cased). + +7. **(M) `--json` without `--dry-run` writes files but skips all post-steps while reporting them on.** `create-rust-app j2 --preset minimal --json` → files written, no + Cargo.lock, no `.git`; JSON says `"post": {"git": true, "fetch": true}`. Help says only "Emit only { answers, files } JSON; no prompts". + Logs: `edge/json-nodry.log` (+ manual re-run without --no-git, recorded in this report). Root cause: `src/cli.ts:226-230` returns before the post-step block. + +8. **(M) The recreate command drops `--accent`, `--author`, `--github` (and email/displayName).** rc2 (above): recreated project differs in 14 files + (LICENSE copyright, CODEOWNERS, repository URLs, `ACCENT` in `src/lib.rs`). Log: `logs/matrix/recreate/rc2-command.txt`, `diff-rc2.txt`. + Root cause: `src/reproduce.ts:20-55` has no branch for `accent`, `author`, `github`, `email`, `displayName`. + +9. **(M) `--msrv` newer than `--toolchain` accepted.** `--msrv 1.100 --toolchain 1.99.1` → exit 0, `rust-version = "1.100"` + `channel = "1.99.1"`; `cargo check` + → "rustc 1.99.1 is not supported by … c5@0.1.0 requires rustc 1.100". Logs: `edge/msrv-gt-toolchain.log`, `edge/cargo-check-c5.log`. + Root cause: `src/args.ts:93-94` validate format only; no cross-field check (args or `buildContext`). + +10. **(M) zizmor fails every generated workflow set** (actionlint is clean everywhere). Exit 14 (high) for all kinds with `release.yml`; 13 for lib/minimal. + - `cache-poisoning` (high): `Swatinem/rust-cache` in the tag-triggered release build — `templates/github/files/_github/workflows/release.yml:120`. + - `artipacked` (medium): `actions/checkout` without `persist-credentials: false` — `ci.yml:39,58,74,125`, `release.yml:51,111,231`, `publish.yml:33`. + - `dependabot-cooldown` (medium): no `cooldown:` — `dependabot.yml:16,38`. + - `use-trusted-publishing` (info, lib): `publish.yml:62` (`cargo publish` with a token). + Logs: `logs/matrix//zizmor.log`. Remediations per zizmor docs (Context7 /zizmorcore/zizmor): `persist-credentials: false`, `cooldown: default-days: 7`, disable caching on tag refs. + +11. **(L) Changelog generators disagree with the shipped CHANGELOG.md.** Running the generator right after scaffolding rewrites the header: cli + (`cargo run --example changelog`) changes "Cli" → "cli" and swaps the intro paragraph; strobe (`cargo xtask changelog`) rewrites the header in different words again. + The two generators also differ from each other (example links commits, xtask doesn't). Logs: `logs/matrix/cli/example-changelog.log`, `logs/matrix/strobe/xtask-changelog.log` + (diffs via `git diff CHANGELOG.md` in those projects). Root cause: `templates/base/files/CHANGELOG.md:3` (`@@displayName@@`) vs + `templates/guards/files/examples/changelog.rs:586` (`@@name@@`) vs `templates/workspace/files/crates/xtask/src/changelog.rs:152`. + +12. **(L) `--force` silently overwrites colliding files.** Pre-existing `README.md` replaced, unrelated `keep.txt` kept; no list, no warning, no backup. + Log: `edge/nonempty-force.log`. Root cause: `src/engine/write.ts:27-38`. (Behaviour may be intended; it isn't documented beyond "Allow writing into a nonempty directory".) + +13. **(L) Conflicting or inapplicable flags are silently dropped.** `--preset lib --with tray`, `--preset tui --with subcommands`, `--preset minimal --with subcommands` + (no clap), `--preset lib --bin foo`, `--preset cli --gui winit-glow` all exit 0 with no notice. Also inconsistent: `effectiveAnswers` blanks `themeBase` for non-GUI kinds but + leaves `guiStack`, so `--json` reports `"guiStack": "winit-glow"` for a cli. Logs: `edge/lib-with-tray.log`, `edge/kind-tui-subcommands.log`, `edge/minimal-subcommands-noclap.log`, + `edge/bin-on-lib.log`, `edge/cli-gui-flag.log`. Root cause: `src/context.ts:52-57` (`effectiveAnswers`); no warnings in `src/args.ts`/`src/cli.ts`. + +14. **(L) Dir with only a fresh `git init`: allowed, but nothing is committed.** `targetProblem` deliberately ignores a lone `.git` (`src/engine/write.ts:9`), but `initRepo` then + skips because the dir is "already inside a git repository" (`src/post/git.ts:28`); the summary still lists "then git init + first commit". Log: `edge/dir-dot-gitonly.log`. + +15. **(L) Inconsistent error prefix in non-TTY.** Argument errors print `✖ …` (pre-detection `fallbackCaps` hard-codes `glyphs: 'full'` on non-Windows, `src/cli.ts:26`); errors after + capability detection print `error: …` (ascii). Compare `edge/name-upper.log` vs `edge/nonempty-noforce.log`. + +16. **(L, design) Defaults stamp the template author's identity on every project.** `-y` without `--author/--github` writes "Copyright (c) 2026 Lawrence Norton", + `* @lnorton89` in CODEOWNERS and `github.com/lnorton89/` URLs. Root cause: `src/presets.ts:9-10` (matches PLAN ★ defaults; risky for a public scaffolder — + suggest reading `git config user.name` or leaving blank). Evidence: `logs/matrix/lic1-deny/inspect.log`, `recreate/diff-rc2.txt`. + +17. **(L, dev tooling) `scripts/scaffold-check.ts`.** (a) Overrides any `CARGO_TARGET_DIR` with `/.scratch/target` (line 66) and defaults `--out` into the repo (line 33), + so it couldn't be used under the "never inside the repo" rule. (b) `--set` splits on every `=` (line 39): `--set tagline=a=b` produces `description = "a"` + (`logs/matrix/scaffold-check/set-eq.log`); the real CLI handles this correctly. + +18. **(Info)** The non-interactive (`-y`) finish screen doesn't print the "again without prompts" command (only `runInteractive` does, `src/cli.ts:138`); the + recreate check therefore needed an expect-driven interactive run. + +19. **(Info)** Windows-only code (tray, single instance, `src/win/`) is never compiled by Linux `clippy`/`test`; checked separately with + `--target x86_64-pc-windows-msvc` clippy: PASS (`logs/matrix//clippy-win.log`). + +## Verified OK (no finding) + +`--edition 2021` (all gates), `tracing` (`unused_imports = "deny" # forbid breaks the tracing macros (E0453)` present, clippy PASS — `logs/matrix/cli-tracing/`), +tokio+reqwest, subcommands + `--bin other-tool` (help shows `Usage: other-tool`, binary `target/debug/other-tool` exists), every MSRV build on 1.98, +lib `cargo publish --dry-run` (packages 33 files, verifies), strobe `cargo xtask ci` (fmt+clippy+test) and `cargo xtask changelog`, `--base graphite --accent #ff9f6e` +(accent reaches `src/lib.rs`, Graphite base in `src/theme/mod.rs`), licence files (MIT → LICENSE + `license = "MIT"`; Apache-2.0 → Apache text; dual → LICENSE-MIT + LICENSE-APACHE ++ `license = "MIT OR Apache-2.0"`; MIT+CommonsClause → Commons Clause + MIT text in LICENSE and `license-file = "LICENSE"`), cargo-deny PASS on every config that ships deny.toml, +`--dry-run --json` purity and plan/real parity, NO_COLOR/`--no-color`, `--quiet`, non-TTY defaults, `--set` validation incl. prototype keys. diff --git a/docs/dogfood/evidence/3b-interactive.md b/docs/dogfood/evidence/3b-interactive.md new file mode 100644 index 0000000..cf649cc --- /dev/null +++ b/docs/dogfood/evidence/3b-interactive.md @@ -0,0 +1,169 @@ +# 3b — Interactive prompt dogfood (create-rust-app) + +Date 2026-11-20 · CLI `dist/bin/create-rust-app.js` (@clack/core 1.6.0, node 22.23.5) · repo untouched. + +## Harness + +- `/home/user/cra-dogfood/pty/harness.py`: `pty.fork` + `bash -c "trap ':' INT; node … ; rc=$?; echo __EXIT=$rc; stty -a"`, + so the exit code and the tty mode **after** node exits are recorded inside the same pty. Keys are sent one at a time + with delays (escape sequences kept whole). Raw stream → `logs/interactive/.raw`; rendered with `pyte` + (installed into `pty/pylib`) → `.txt` (labelled screen snapshots + final scrollback); `.meta.json` has exit code, + `stty_raw_left`, `cursor_visible_at_end` (last `?25l` vs `?25h`), and SGR count. +- Scenarios: `pty/scen.py` (definitions), `pty/run.py ` (runner), `pty/snaps.py ` (snapshot tails). +- Projects: `/home/user/cra-dogfood/projects/interactive/`. Most runs use `--no-git --no-fetch --no-cargo-check` + (prompts stay interactive). + +## Scenario results + +| # | Scenario | Result | +|---|---|---| +| 1 | Happy path cli / rustaman | PASS (exit 0, files written, tty restored). Logs `s1-happy-cli`, `s1-happy-rustaman` | +| 2 | Customize every section, compare | PARTIAL — all values chosen in sections were written correctly; mismatches exist outside what the review shows (F1, F4, F9) | +| 3 | Cancel everywhere | PASS for prompts (exit 130, "Nothing written.", cursor shown, cooked tty, no dir) — but Esc in any section kills the whole run (F5); Ctrl-C during post-steps leaves cursor hidden + partial dir (F3) | +| 4 | Invalid input | PARTIAL — inline, clear, recoverable messages; but Rust keywords, Cargo-reserved/Windows names, 300-char names, MSRV>toolchain accepted (F2, F6, F7, F8) | +| 5 | 40 cols / 10 rows | FAIL-ish — rows wrap at 40 cols; lists taller than the viewport have no scrolling, focused row off-screen (F10, F11) | +| 6 | NO_COLOR / --no-color | PARTIAL — 0 SGR under NO_COLOR; `--no-color` leaks `ESC[7m`; multiselect focus and text cursor invisible without colour (F12, F13) | +| 7 | Flags + interactive | PARTIAL — `--name/--preset` skip correctly, bad flags fail before prompting; positional dir + rename lies (F4); `--kind` overrides "Start over" choice (F14) | +| 8 | Keyboard | PASS mostly — arrows, j/k/h/l, space, a, i work; Home/PgDn/Tab ignored (fine); hint wording nits (F17) | + +## Findings + +### F1 — Author / GitHub owner are hard-coded to the repo author; never asked, never shown (bug, high) +- Scenario 1/2: any interactive run. `hp-cli/LICENSE`: `Copyright (c) 2026 Lawrence Norton`; `.github/CODEOWNERS`: `* @lnorton89`; + `Cargo.toml` `authors`/`repository` likewise. `git config user.name` was set in this environment and ignored. +- Expected: ask (or derive from `git config`) and show on the review; actual: no prompt, no review line, Customize has no section for it. +- Root cause: `src/presets.ts:9-10` (`DEFAULTS.author/github`), no prompt in `src/prompts.ts:115-278`, not in `reviewLines` (`src/prompts.ts:54-112`). +- Log: `logs/interactive/s1-happy-cli.txt`; project `projects/interactive/hp-cli`. + +### F2 — Rust keywords accepted as the project name; generated project does not compile (bug) +- Keys: `fn⏎` (also `match`, `async`, `type` accepted). `s4-name-00..02` show the kind picker appearing instead of an error. +- `s4-name-keyword-create` wrote `projects/interactive/fn`; `cargo check` → `error: expected identifier, found '::' --> 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. From f84bd9402429f2573a42ebc366ee7f54ad715989 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 05:03:04 +0000 Subject: [PATCH 36/40] docs: correct the commit count in the dogfood report Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01W2BaQjmXXv2ZSgkAnMH1eA --- docs/dogfood/REPORT.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/dogfood/REPORT.md b/docs/dogfood/REPORT.md index e66a71e..2865479 100644 --- a/docs/dogfood/REPORT.md +++ b/docs/dogfood/REPORT.md @@ -1,7 +1,7 @@ # Dogfood report, November 2026 Before: `db3693d`. After: `58847b6` plus this report. Branch `claude/jolly-curie-lpi8jt`, -34 commits, no merges to `main`, no tags, no release, nothing published. +35 commits plus four merge commits, nothing merged to `main`, no tags, no release, nothing published. The detailed findings are in [FINDINGS.md](FINDINGS.md). The agents' full reports are in [`evidence/`](evidence/); they cite raw logs under `logs/…`, which lived in a scratch From 2170a4de8f9864bdb5d3f232004d53f23eb9f517 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 05:24:03 +0000 Subject: [PATCH 37/40] fix: show the target folder with / separators on Windows The review hint, the cd line and the recreate command printed backslash paths on Windows, which Git Bash eats and the POSIX quoting doubled. shownTarget and writesHint take a path module so tests cover win32 rules on every OS. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01W2BaQjmXXv2ZSgkAnMH1eA --- CHANGELOG.md | 3 +++ src/prompts.ts | 8 ++++---- src/reproduce.ts | 15 ++++++++++----- test/prompts.test.ts | 16 ++++++++++------ test/reproduce.test.ts | 27 +++++++++++++++++++++------ 5 files changed, 48 insertions(+), 21 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8d0b9e7..28cb365 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,9 @@ 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 diff --git a/src/prompts.ts b/src/prompts.ts index f8d5582..0966197 100644 --- a/src/prompts.ts +++ b/src/prompts.ts @@ -12,7 +12,7 @@ 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 { isAbsolute } from 'node:path'; +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'; @@ -134,9 +134,9 @@ export function startOver(partial: PartialAnswers, preset: string, name: string) } /** 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): string { - const shown = shownTarget(dir, name, cwd); - return `writes ${isAbsolute(shown) || shown === '.' ? shown : `./${shown}`}`; +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}`}`; } /** diff --git a/src/reproduce.ts b/src/reproduce.ts index 51ea67a..fec7e1f 100644 --- a/src/reproduce.ts +++ b/src/reproduce.ts @@ -2,7 +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 { basename, isAbsolute, relative, resolve } from 'node:path'; +import path, { basename, resolve } from 'node:path'; import { resolveAnswers } from './presets.ts'; import { effectiveAnswers } from './context.ts'; import type { Answers } from './types.ts'; @@ -20,11 +20,16 @@ const quote = (v: string) => (/^[\w.@/:+-]+$/.test(v) ? v : `"${v.replace(/["\\$ /** * 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()): string { - const target = resolve(cwd, dir ?? name); - const rel = relative(cwd, target); - return rel.startsWith('..') || isAbsolute(rel) ? target : rel || '.'; +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; } /** diff --git a/test/prompts.test.ts b/test/prompts.test.ts index 869cd12..09fb3cc 100644 --- a/test/prompts.test.ts +++ b/test/prompts.test.ts @@ -6,7 +6,7 @@ import { test } from 'node:test'; import assert from 'node:assert/strict'; import { PassThrough, Writable } from 'node:stream'; import { spawnSync } from 'node:child_process'; -import { resolve } from 'node:path'; +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'; @@ -83,11 +83,15 @@ test('"Start over from a preset" wins over --kind and --preset, keeps the other }); test('the review hint names the folder the run writes, including a positional dir (B9)', () => { - const cwd = resolve('/work/projects'); - assert.equal(writesHint(undefined, 'hp-cli', cwd), 'writes ./hp-cli'); - assert.equal(writesHint('fl-dir', 'fl-renamed', cwd), 'writes ./fl-dir'); - assert.equal(writesHint('.', 'here', cwd), 'writes .'); - assert.equal(writesHint('../elsewhere', 'x', cwd), `writes ${resolve('/work/elsewhere')}`); + 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)', () => { diff --git a/test/reproduce.test.ts b/test/reproduce.test.ts index a99bbc8..7740fff 100644 --- a/test/reproduce.test.ts +++ b/test/reproduce.test.ts @@ -1,7 +1,7 @@ /** 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 { join } from 'node:path'; +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'; @@ -73,9 +73,24 @@ test('the recreate command names the real folder, and --name when it differs (B9 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`); - const cwd = join('/', 'work'); - assert.equal(shownTarget('fl-dir', 'fl-renamed', cwd), 'fl-dir', 'the positional wins over the name'); - assert.equal(shownTarget(undefined, 'fl-renamed', cwd), 'fl-renamed'); - assert.equal(shownTarget('.', 'x', cwd), '.'); - assert.equal(shownTarget('../elsewhere', 'x', cwd), join('/', 'elsewhere'), 'outside cwd: absolute'); + // 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`); }); From 380e65e0d62b7078deabdb43059736a96bacf374 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 05:24:28 +0000 Subject: [PATCH 38/40] test: emit SIGINT in the Ctrl-C test on Windows process.kill(pid, 'SIGINT') is TerminateProcess on Windows (exit 1), so the handler never ran; a console Ctrl-C there emits the event instead. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01W2BaQjmXXv2ZSgkAnMH1eA --- test/prompts.test.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/test/prompts.test.ts b/test/prompts.test.ts index 09fb3cc..ff8f96e 100644 --- a/test/prompts.test.ts +++ b/test/prompts.test.ts @@ -235,9 +235,14 @@ function child(body: string) { 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(() => process.kill(process.pid, 'SIGINT'), 100); + 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.' });`); From b929a360391a293f982966be8e8f4386bb19220d Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 05:24:28 +0000 Subject: [PATCH 39/40] test: expect a native CARGO_TARGET_DIR path in scaffold-check Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01W2BaQjmXXv2ZSgkAnMH1eA --- test/scaffold-check.test.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/test/scaffold-check.test.ts b/test/scaffold-check.test.ts index 4fdd0ae..b0dc595 100644 --- a/test/scaffold-check.test.ts +++ b/test/scaffold-check.test.ts @@ -1,4 +1,5 @@ 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'; @@ -40,7 +41,8 @@ test('scaffold-check gates: doc is opt-in, fmt builds nothing', () => { test('scaffold-check keeps an existing CARGO_TARGET_DIR', () => { assert.equal(cargoEnv({ CARGO_TARGET_DIR: '/shared/target' }, '/repo', 'full').CARGO_TARGET_DIR, '/shared/target'); - assert.equal(cargoEnv({}, '/repo', 'full').CARGO_TARGET_DIR, '/repo/.scratch/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); From fa62f7a69ef1aebaaef008e5e7a311937c7da634 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 05:28:07 +0000 Subject: [PATCH 40/40] test: wait for the prompt and retry a ConPTY that never started On a loaded Windows runner node-pty's ConPTY output worker can miss its 5 s connect timeout and report exit code -1 without starting the CLI, and fixed sleeps could type before the name prompt was drawn. Steps now wait for the expected output, and a pty that never started is spawned again. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01W2BaQjmXXv2ZSgkAnMH1eA --- test/failure.test.ts | 35 +++++++++++++++++++++++++---------- 1 file changed, 25 insertions(+), 10 deletions(-) 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');