Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <lang>] [--out <dir>] [--layout <tpl>] [--mode <m>] [--watch]` | Validate (no freeze), then write generated code. Output location/layout come from `comline.toml` `[generate]`; targets from there or `config.idp`. |
| `comline diff <old> <new>` | Show the schema changes between two built versions. Each argument is a version (`0.2.0`), a commit hash, or `HEAD` (the default for `<new>`). |
| `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 <shell>` | Print a shell completion script to stdout. |

Global flags: `--path <dir>` to run outside the current directory, `-v`/`-vv` for
Expand Down Expand Up @@ -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

Expand Down
48 changes: 41 additions & 7 deletions docs/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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 <cmd>
Expand Down Expand Up @@ -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`

```
Expand Down Expand Up @@ -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
Expand Down
27 changes: 24 additions & 3 deletions src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
17 changes: 8 additions & 9 deletions src/commands/clean.rs
Original file line number Diff line number Diff line change
@@ -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};

Expand All @@ -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<PathBuf> = Vec::new();

let cas = work_dir.join(".comline");
if cas.exists() {
targets.push(cas);
}
targets.extend(generated_files(work_dir));
let mut targets: Vec<PathBuf> = generated_files(work_dir);
targets.sort();
targets.dedup();

Expand Down Expand Up @@ -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<PathBuf> {
///
/// Shared with [`super::reset`], which removes these too.
pub(crate) fn generated_files(work_dir: &Path) -> Vec<PathBuf> {
let cfg = match ComlineToml::load(work_dir) {
Ok(cfg) => cfg,
Err(e) => {
Expand Down
1 change: 1 addition & 0 deletions src/commands/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ pub mod completions;
pub mod diff;
pub mod generate;
pub mod new;
pub mod reset;

use std::path::Path;

Expand Down
105 changes: 105 additions & 0 deletions src/commands/reset.rs
Original file line number Diff line number Diff line change
@@ -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<PathBuf> = 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<bool> {
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()
}
}
5 changes: 5 additions & 0 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,18 @@ 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.
pub fn exit_code_for(report: &miette::Report) -> i32 {
match report.downcast_ref::<CliError>() {
Some(CliError::NotAProject(_)) => EXIT_PRECONDITION,
Some(CliError::NothingBuilt(_)) => EXIT_PRECONDITION,
Some(CliError::ConfirmationRequired) => EXIT_PRECONDITION,
None => EXIT_FAILURE,
}
}
1 change: 1 addition & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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),
}
Expand Down
Loading
Loading