From bc900a4fce2b9121ee82aa29c5060e02227f6275 Mon Sep 17 00:00:00 2001 From: Kinflou Date: Sun, 30 Aug 2026 23:27:04 +0800 Subject: [PATCH] feat: split comline clean into clean (code) + reset (history) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit comline clean deleted .comline/ — the entire version history — with no confirmation and no way back, in the same gesture that removes regenerable generated code. Nothing else holds the history (no publish yet), so a build afterwards silently restarted at 0.0.1. - comline clean now removes only generated code; .comline/ is never touched. - comline reset (new) deletes .comline/ + generated code. On a TTY it prints how many versions will be lost and requires typing `reset`; without a TTY it refuses (exit 2) unless --force. --dry-run on either lists without deleting. - CliError::ConfirmationRequired -> exit 2. - clean.rs::generated_files is now pub(crate), shared with reset. - tests: clean.rs rewritten (code-only semantics); new reset.rs. - docs/cli.md + README updated; versioning-model section now states the history has no other copy and only reset discards it. All: cargo fmt --check, clippy -D warnings, 36 integration tests green. --- README.md | 5 +- docs/cli.md | 48 ++++++++++++++++--- src/cli.rs | 27 +++++++++-- src/commands/clean.rs | 17 ++++--- src/commands/mod.rs | 1 + src/commands/reset.rs | 105 ++++++++++++++++++++++++++++++++++++++++++ src/error.rs | 5 ++ src/main.rs | 1 + tests/cli/clean.rs | 49 ++++++++++++++++---- tests/cli/main.rs | 1 + tests/cli/reset.rs | 81 ++++++++++++++++++++++++++++++++ 11 files changed, 311 insertions(+), 29 deletions(-) create mode 100644 src/commands/reset.rs create mode 100644 tests/cli/reset.rs diff --git a/README.md b/README.md index a40046b..53d75c9 100644 --- a/README.md +++ b/README.md @@ -34,7 +34,8 @@ comline generate # write generated code for each configured target | `comline build [--release] [--watch]` | Compile, validate, and freeze a new immutable version into `.comline/`. Prints the changelog and the version bump. | | `comline generate [--target ] [--out ] [--layout ] [--mode ] [--watch]` | Validate (no freeze), then write generated code. Output location/layout come from `comline.toml` `[generate]`; targets from there or `config.idp`. | | `comline diff ` | Show the schema changes between two built versions. Each argument is a version (`0.2.0`), a commit hash, or `HEAD` (the default for ``). | -| `comline clean [--dry-run]` | Remove `.comline/` and the `generate` output (the output root, or the individual files). | +| `comline clean [--dry-run]` | Remove the `generate` output (the output root, or the individual files). Leaves `.comline/` alone. | +| `comline reset [--force] [--dry-run]` | Discard the version history: delete `.comline/` and generated code. Asks for confirmation on a terminal; needs `--force` otherwise. No undo — the next build restarts at `0.0.1`. | | `comline completions ` | Print a shell completion script to stdout. | Global flags: `--path ` to run outside the current directory, `-v`/`-vv` for @@ -62,7 +63,7 @@ demand. |---|---| | `0` | success | | `1` | the command ran but failed | -| `2` | a precondition was not met (not a Comline project, nothing built yet) or a usage error | +| `2` | a precondition was not met (not a Comline project, nothing built yet, `reset` not confirmed) or a usage error | ## Development diff --git a/docs/cli.md b/docs/cli.md index a27b609..af2b6e6 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -19,6 +19,7 @@ This is the long-form reference. For a two-minute tour see the - [`generate`](#comline-generate) - [`diff`](#comline-diff) - [`clean`](#comline-clean) + - [`reset`](#comline-reset) - [`completions`](#comline-completions) - [Global flags](#global-flags) - [Output and exit codes](#output-and-exit-codes) @@ -111,6 +112,11 @@ The first build is version `0.0.1`. A build with no schema changes keeps the current version and does not add a commit. `comline diff` runs this same comparison between any two stored versions on demand. +The chain in `.comline/` is the only copy of this history — there is no publish +step yet. [`comline clean`](#comline-clean) does **not** touch it; only +[`comline reset`](#comline-reset) discards it, after which the next build starts +over at `0.0.1`. + ## Commands Every command accepts the [global flags](#global-flags). Run `comline @@ -272,21 +278,49 @@ argument matches no stored version (the error lists the versions that exist). comline clean [--dry-run] ``` -Remove build artifacts: the `.comline/` store, and what `generate` would have -written — the whole output root when it is a dedicated directory (e.g. -`generated/`), otherwise just the individual generated files. The next `build` -starts a fresh version history at `0.0.1`. +Remove what `generate` wrote — the whole output root when it is a dedicated +directory (e.g. `generated/`), otherwise just the individual generated files. +Resolved the same way `generate` resolves output (`comline.toml` `[generate]`, +else `config.idp`'s declared languages). + +Does **not** touch `.comline/`. Generated code is regenerable; the version +history is not — [`comline reset`](#comline-reset) is the command for that. - `--dry-run` — list what would be removed without deleting anything. -Generated-file cleanup needs the project to compile; if it doesn't, `.comline/` -is still removed and a note is printed. +Needs the project to compile to know what `generate` would have written; if it +does not, there is nothing to clean. ```bash comline clean --dry-run comline clean ``` +### `comline reset` + +``` +comline reset [--force] [--dry-run] +``` + +Delete `.comline/` — every frozen version and the commit chain — **and** +generated code. This cannot be undone, and since nothing else holds the history, +the next `build` starts over at `0.0.1`. + +Guarded: + +- on a terminal, you are shown how many versions will be lost and must type + `reset` to proceed; +- without a terminal (CI, scripts) it refuses with exit `2` unless `--force` is + given. +- `--dry-run` — list what would be removed, and the history that would be lost, + without deleting anything. No confirmation needed. + +```bash +comline reset --dry-run +comline reset # asks for confirmation +comline reset --force # scripted +``` + ### `comline completions` ``` @@ -334,7 +368,7 @@ Exit codes are stable for scripting and CI: |---|---| | `0` | success | | `1` | the command ran but failed — invalid schema, unresolved `diff` argument, a generator or filesystem error | -| `2` | a precondition was not met — the directory is not a Comline project, or nothing has been built yet. `clap` also exits `2` for usage errors. | +| `2` | a precondition was not met — the directory is not a Comline project, nothing has been built yet, or a destructive command (`reset`) was not confirmed. `clap` also exits `2` for usage errors. | ```bash if ! comline check --quiet; then diff --git a/src/cli.rs b/src/cli.rs index e999d1e..2340784 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -131,16 +131,37 @@ Examples: new: String, }, - /// Remove build artifacts: the `.comline/` store and generated files + /// Remove generated code #[command(long_about = "\ -Delete the project's `.comline/` content-addressable store and any files left \ -by `generate`. The next `build` starts a fresh version history at 0.0.1.")] +Remove the files `comline generate` writes — the whole output root when it is a \ +dedicated directory (e.g. `generated/`), otherwise the individual generated \ +files. Does not touch `.comline/`; use `comline reset` to discard the version \ +history.")] Clean { /// List what would be removed without deleting anything #[arg(long)] dry_run: bool, }, + /// Discard the version history (delete `.comline/`) + #[command(long_about = "\ +Delete the project's `.comline/` content-addressable store — every frozen \ +version and the commit chain. Generated code is removed too. This cannot be \ +undone and nothing else holds the history, so the next `build` starts over at \ +0.0.1. + +Requires confirmation: on a terminal you are asked to type `reset`; otherwise \ +pass `--force`.")] + Reset { + /// Skip the confirmation prompt + #[arg(long)] + force: bool, + + /// List what would be removed without deleting anything + #[arg(long)] + dry_run: bool, + }, + /// Create a new Comline project in a new directory New { /// Project name; also the directory that gets created diff --git a/src/commands/clean.rs b/src/commands/clean.rs index 2c79f29..f99c340 100644 --- a/src/commands/clean.rs +++ b/src/commands/clean.rs @@ -1,4 +1,7 @@ -//! `comline clean` — remove build artifacts. +//! `comline clean` — remove generated code. +//! +//! Only the output of `comline generate`. The `.comline/` store (the version +//! history) is left alone — [`super::reset`] is the command that discards that. use std::path::{Path, PathBuf}; @@ -15,13 +18,7 @@ pub fn run(work_dir: &Path, dry_run: bool) -> Result<()> { ui::step(format!("Cleaning{}", ui::at_path(work_dir))); - let mut targets: Vec = Vec::new(); - - let cas = work_dir.join(".comline"); - if cas.exists() { - targets.push(cas); - } - targets.extend(generated_files(work_dir)); + let mut targets: Vec = generated_files(work_dir); targets.sort(); targets.dedup(); @@ -53,7 +50,9 @@ pub fn run(work_dir: &Path, dry_run: bool) -> Result<()> { /// declared languages). For each target this is the whole output root when it is /// a real sub-directory, otherwise the individual rendered files. Empty if the /// project does not currently compile or `comline.toml` does not parse. -fn generated_files(work_dir: &Path) -> Vec { +/// +/// Shared with [`super::reset`], which removes these too. +pub(crate) fn generated_files(work_dir: &Path) -> Vec { let cfg = match ComlineToml::load(work_dir) { Ok(cfg) => cfg, Err(e) => { diff --git a/src/commands/mod.rs b/src/commands/mod.rs index e7ed9ac..c58ac60 100644 --- a/src/commands/mod.rs +++ b/src/commands/mod.rs @@ -8,6 +8,7 @@ pub mod completions; pub mod diff; pub mod generate; pub mod new; +pub mod reset; use std::path::Path; diff --git a/src/commands/reset.rs b/src/commands/reset.rs new file mode 100644 index 0000000..528109d --- /dev/null +++ b/src/commands/reset.rs @@ -0,0 +1,105 @@ +//! `comline reset` — discard the version history. +//! +//! Deletes `.comline/` (every frozen version and the commit chain) plus +//! generated code. Irreversible, and — since there is no `publish` yet — +//! nothing else holds the history, so the next `build` starts over at 0.0.1. +//! Guarded by a typed confirmation unless `--force`. + +use std::io::{self, IsTerminal, Write}; +use std::path::{Path, PathBuf}; + +use miette::{IntoDiagnostic, Result, WrapErr}; + +use crate::commands::{clean, ensure_project}; +use crate::error::CliError; +use crate::history; +use crate::ui; + +pub fn run(work_dir: &Path, force: bool, dry_run: bool) -> Result<()> { + ensure_project(work_dir)?; + + ui::step(format!("Resetting{}", ui::at_path(work_dir))); + + let cas = work_dir.join(".comline"); + let mut targets: Vec = Vec::new(); + if cas.exists() { + targets.push(cas); + } + targets.extend(clean::generated_files(work_dir)); + targets.sort(); + targets.dedup(); + + if targets.is_empty() { + ui::success("Nothing to reset"); + return Ok(()); + } + + // History summary for the prompt — best effort; the store may exist but be + // unreadable, and the reset should still be allowed to clear it. + let summary = match history::load(work_dir).ok().as_deref() { + Some([head, rest @ ..]) => { + format!( + "{} version(s), currently {}", + rest.len() + 1, + head.commit.version + ) + } + _ => "an unreadable or empty store".to_string(), + }; + + if dry_run { + for target in &targets { + let shown = target.strip_prefix(work_dir).unwrap_or(target).display(); + ui::detail(format!("would remove {shown}")); + } + ui::note(format!("would discard {summary}")); + ui::success("Dry run complete — nothing was deleted"); + return Ok(()); + } + + if !force && !confirm(&summary)? { + return Ok(()); + } + + for target in &targets { + let shown = target.strip_prefix(work_dir).unwrap_or(target).display(); + remove(target).wrap_err_with(|| format!("failed to remove `{}`", target.display()))?; + ui::detail(format!("removed {shown}")); + } + + ui::success("Reset complete — the next `build` starts a new history at 0.0.1"); + Ok(()) +} + +/// Typed confirmation. Returns `Ok(false)` if the user declines. Refuses with a +/// precondition error when stdin is not a terminal — a script that means it +/// passes `--force`. +fn confirm(summary: &str) -> Result { + if !io::stdin().is_terminal() { + return Err(CliError::ConfirmationRequired.into()); + } + + ui::warn(format!( + "This permanently deletes the version history ({summary}) and cannot be undone." + )); + print!("Type `reset` to confirm: "); + io::stdout().flush().into_diagnostic()?; + + let mut line = String::new(); + io::stdin().read_line(&mut line).into_diagnostic()?; + + if line.trim() == "reset" { + Ok(true) + } else { + ui::note("Cancelled — nothing was deleted"); + Ok(false) + } +} + +fn remove(path: &Path) -> Result<()> { + if path.is_dir() { + std::fs::remove_dir_all(path).into_diagnostic() + } else { + std::fs::remove_file(path).into_diagnostic() + } +} diff --git a/src/error.rs b/src/error.rs index bd4e95d..38e26bb 100644 --- a/src/error.rs +++ b/src/error.rs @@ -31,6 +31,10 @@ pub enum CliError { #[error("no builds found in `{}` — run `comline build` first", .0.display())] NothingBuilt(PathBuf), + + #[error("refusing to delete the version history without confirmation")] + #[diagnostic(help("re-run in a terminal to confirm, or pass `--force`"))] + ConfirmationRequired, } /// Map a finished-command error to its process exit code. @@ -38,6 +42,7 @@ pub fn exit_code_for(report: &miette::Report) -> i32 { match report.downcast_ref::() { Some(CliError::NotAProject(_)) => EXIT_PRECONDITION, Some(CliError::NothingBuilt(_)) => EXIT_PRECONDITION, + Some(CliError::ConfirmationRequired) => EXIT_PRECONDITION, None => EXIT_FAILURE, } } diff --git a/src/main.rs b/src/main.rs index bab1113..14126fe 100644 --- a/src/main.rs +++ b/src/main.rs @@ -107,6 +107,7 @@ fn run(cli: Cli) -> Result<()> { } Commands::Diff { old, new } => commands::diff::run(&work_dir, &old, &new), Commands::Clean { dry_run } => commands::clean::run(&work_dir, dry_run), + Commands::Reset { force, dry_run } => commands::reset::run(&work_dir, force, dry_run), Commands::New { name, git } => commands::new::run(&work_dir, &name, git), Commands::Completions { shell } => commands::completions::run(shell), } diff --git a/tests/cli/clean.rs b/tests/cli/clean.rs index 4ba2aa6..9e29c1f 100644 --- a/tests/cli/clean.rs +++ b/tests/cli/clean.rs @@ -1,37 +1,49 @@ -//! `comline clean` +//! `comline clean` — removes generated code only, never `.comline/`. use predicates::prelude::*; use crate::util::*; #[test] -fn removes_the_cas_store() { +fn removes_generated_code_but_keeps_the_store() { let temp = tempfile::tempdir().unwrap(); let project = fixture_project(temp.path()); + comline_cmd() .current_dir(&project) .arg("build") .assert() .success(); - assert!(project.join(".comline").exists()); + comline_cmd() + .current_dir(&project) + .args(["generate", "--target", "rust"]) + .assert() + .success(); + assert!(project.join("generated/rust/main.rs").exists()); + assert!(project.join(".comline").is_dir()); comline_cmd() .current_dir(&project) .arg("clean") .assert() .success() - .stderr(predicate::str::contains("Clean complete")); + .stderr(predicate::str::contains("removed generated")); - assert!(!project.join(".comline").exists()); + assert!(!project.join("generated").exists()); + assert!( + project.join(".comline").is_dir(), + "clean must not touch .comline/" + ); } #[test] -fn dry_run_keeps_everything() { +fn dry_run_lists_without_deleting() { let temp = tempfile::tempdir().unwrap(); let project = fixture_project(temp.path()); + comline_cmd() .current_dir(&project) - .arg("build") + .args(["generate", "--target", "rust"]) .assert() .success(); @@ -42,5 +54,26 @@ fn dry_run_keeps_everything() { .success() .stderr(predicate::str::contains("would remove")); - assert!(project.join(".comline").exists()); + assert!(project.join("generated/rust/main.rs").exists()); +} + +#[test] +fn nothing_to_clean_when_no_generated_code() { + let temp = tempfile::tempdir().unwrap(); + let project = fixture_project(temp.path()); + + comline_cmd() + .current_dir(&project) + .arg("build") + .assert() + .success(); + + comline_cmd() + .current_dir(&project) + .arg("clean") + .assert() + .success() + .stderr(predicate::str::contains("Nothing to clean")); + + assert!(project.join(".comline").is_dir()); } diff --git a/tests/cli/main.rs b/tests/cli/main.rs index aae5e69..6f96ab3 100644 --- a/tests/cli/main.rs +++ b/tests/cli/main.rs @@ -13,3 +13,4 @@ mod diff; mod generate; mod global; mod new; +mod reset; diff --git a/tests/cli/reset.rs b/tests/cli/reset.rs new file mode 100644 index 0000000..a2f2786 --- /dev/null +++ b/tests/cli/reset.rs @@ -0,0 +1,81 @@ +//! `comline reset` — discards the version history (`.comline/`) behind a guard. + +use predicates::prelude::*; + +use crate::util::*; + +#[test] +fn force_removes_the_store_and_generated_code() { + let temp = tempfile::tempdir().unwrap(); + let project = fixture_project(temp.path()); + + comline_cmd() + .current_dir(&project) + .arg("build") + .assert() + .success(); + comline_cmd() + .current_dir(&project) + .args(["generate", "--target", "rust"]) + .assert() + .success(); + assert!(project.join(".comline").is_dir()); + assert!(project.join("generated/rust/main.rs").exists()); + + comline_cmd() + .current_dir(&project) + .args(["reset", "--force"]) + .assert() + .success() + .stderr(predicate::str::contains("Reset complete")); + + assert!(!project.join(".comline").exists()); + assert!(!project.join("generated").exists()); +} + +#[test] +fn without_force_and_no_tty_it_refuses() { + let temp = tempfile::tempdir().unwrap(); + let project = fixture_project(temp.path()); + + comline_cmd() + .current_dir(&project) + .arg("build") + .assert() + .success(); + + comline_cmd() + .current_dir(&project) + .arg("reset") + .assert() + .failure() + .code(2) + .stderr(predicate::str::contains("without confirmation")); + + assert!( + project.join(".comline").is_dir(), + "a refused reset must leave .comline/ intact" + ); +} + +#[test] +fn dry_run_keeps_everything() { + let temp = tempfile::tempdir().unwrap(); + let project = fixture_project(temp.path()); + + comline_cmd() + .current_dir(&project) + .arg("build") + .assert() + .success(); + + comline_cmd() + .current_dir(&project) + .args(["reset", "--dry-run"]) + .assert() + .success() + .stderr(predicate::str::contains("would remove .comline")) + .stderr(predicate::str::contains("currently 0.0.1")); + + assert!(project.join(".comline").is_dir()); +}