diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5ccc96d..0ea931b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -21,3 +21,17 @@ jobs: run: cargo build --verbose - name: Run tests run: cargo test --verbose + + lint: + name: Lint + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Install Rust + uses: dtolnay/rust-toolchain@stable + with: + components: rustfmt, clippy + - name: rustfmt + run: cargo fmt --check + - name: clippy + run: cargo clippy --all-targets -- -D warnings diff --git a/Cargo.toml b/Cargo.toml old mode 100755 new mode 100644 index 7b8a160..fddac1a --- a/Cargo.toml +++ b/Cargo.toml @@ -3,17 +3,35 @@ name = "comline" version = "0.1.0" edition = "2021" license-file = "LICENSE" -repository = "https://github.com/ComlineProject/comline" -description = "A project in the works, patiently" +repository = "https://github.com/ComlineProject/cli" +description = "Command-line interface for Comline: build, validate, diff and generate code from Comline schemas" +readme = "README.md" +keywords = ["comline", "schema", "codegen", "idl", "cli"] +categories = ["command-line-utilities", "development-tools"] [dependencies] clap = { version = "4.5.4", features = ["derive", "cargo"] } +clap_complete = "4.5" miette = { version = "7.2.0", features = ["fancy"] } -tokio = { version = "1.37.0", features = ["full"] } +thiserror = "1.0" +anstream = "0.6" +anstyle = "1.0" +indicatif = "0.17" +notify-debouncer-mini = "0.4" tracing = "0.1.40" tracing-subscriber = { version = "0.3.18", features = ["env-filter", "fmt"] } -comline-core = { git = "https://github.com/ComlineProject/core" } +# NOTE: consumed via git until `comline-core` is published to crates.io. +# Publishing `comline` to crates.io is blocked on that release. +comline-core = { git = "https://github.com/ComlineProject/core", rev = "3455622e111c68a2ac0efeec9abfe7092a479fd4" } + +[target.'cfg(unix)'.dependencies] +libc = "0.2" + +[build-dependencies] +clap = { version = "4.5.4", features = ["derive"] } +clap_mangen = "0.2" +clap_complete = "4.5" [dev-dependencies] assert_cmd = "2.0" diff --git a/README.md b/README.md old mode 100755 new mode 100644 index e320cf1..424c034 --- a/README.md +++ b/README.md @@ -1,3 +1,76 @@ -# Comline -For the time being the project is in initial development and likely won't have -user-friendly tips or instructions. +# comline + +The command-line interface for [Comline](https://github.com/ComlineProject) — +build, validate, diff and generate code from Comline schemas. + +> Comline is in early development. The schema language and CLI surface may still +> change between versions. + +## Install + +`comline` is not on crates.io yet (it depends on `comline-core` via git until +that crate is published). Build it from this repository: + +```bash +git clone https://github.com/ComlineProject/cli +cargo install --path cli +``` + +## Quick start + +```bash +comline new my-api # scaffold a project +cd my-api +comline build # compile + freeze version 0.0.1 +comline generate # write generated code for each configured target +``` + +## Commands + +| Command | What it does | +|---|---| +| `comline new [--git]` | Scaffold `/` with `config.idp`, `src/main.ids` and a `.gitignore`. `--git` also runs `git init`. | +| `comline check` | Parse, resolve and validate every schema. No `.comline/` writes, no version bump — safe for editors, hooks and CI. | +| `comline build [--release] [--watch]` | Compile, validate, and freeze a new immutable version into `.comline/`. Prints the changelog and the version bump. | +| `comline generate [--target ] [--watch]` | Build, then run each configured code generator (or just ``). | +| `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 generated files. | +| `comline completions ` | Print a shell completion script to stdout. | + +Global flags: `--path ` to run outside the current directory, `-v`/`-vv` for +more log detail, `-q`/`--quiet` to silence everything but errors. + +See [`docs/cli.md`](docs/cli.md) for the full guide — every command and flag, the +versioning model, output and exit codes, watch mode, and packaging. + +## Versioning model + +Comline stores every build as an immutable commit in an append-only chain under +`.comline/` (content-addressable, git-inspired). Each `build` compares the new +schemas against the previous version and bumps automatically: + +- **major** — a breaking change (removed/retyped field, removed variant, …) +- **minor** — a new feature (added struct/enum/variant/field, …) +- **patch** — a modification (field made optional, docstring change, …) + +`comline diff` runs that same comparison between any two stored versions on +demand. + +## Exit codes + +| code | meaning | +|---|---| +| `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 | + +## Development + +```bash +cargo test +cargo fmt --check +cargo clippy --all-targets -- -D warnings +``` + +Man pages and completion scripts for all shells are generated into `OUT_DIR` +(`target/.../build/comline-*/out/{man,completions}/`) on every build. diff --git a/build.rs b/build.rs new file mode 100644 index 0000000..846a294 --- /dev/null +++ b/build.rs @@ -0,0 +1,66 @@ +//! Generates man pages and shell completions into `OUT_DIR` at build time so +//! packagers can install them. End users can also get completions at runtime via +//! `comline completions `. +//! +//! `src/cli.rs` is intentionally dependency-light so it can be shared here. + +use std::env; +use std::fs; +use std::io::Error; +use std::path::{Path, PathBuf}; + +use clap::{Command, CommandFactory}; +use clap_complete::Shell; + +#[path = "src/cli.rs"] +mod cli; + +fn main() -> Result<(), Error> { + println!("cargo:rerun-if-changed=src/cli.rs"); + println!("cargo:rerun-if-changed=build.rs"); + + let Some(out_dir) = env::var_os("OUT_DIR").map(PathBuf::from) else { + return Ok(()); + }; + + let man_dir = out_dir.join("man"); + fs::create_dir_all(&man_dir)?; + render_man_pages(&man_dir, &cli::Cli::command())?; + + let completions_dir = out_dir.join("completions"); + fs::create_dir_all(&completions_dir)?; + let mut command = cli::Cli::command(); + for shell in [ + Shell::Bash, + Shell::Zsh, + Shell::Fish, + Shell::PowerShell, + Shell::Elvish, + ] { + clap_complete::generate_to(shell, &mut command, "comline", &completions_dir)?; + } + + Ok(()) +} + +fn render_man_pages(dir: &Path, command: &Command) -> Result<(), Error> { + let name = command.get_name().to_string(); + write_man(&dir.join(format!("{name}.1")), command.clone(), &name)?; + + for sub in command.get_subcommands() { + if sub.get_name() == "help" { + continue; + } + let page = format!("{name}-{}", sub.get_name()); + write_man(&dir.join(format!("{page}.1")), sub.clone(), &page)?; + } + Ok(()) +} + +fn write_man(path: &Path, command: Command, title: &str) -> Result<(), Error> { + let mut buffer = Vec::new(); + clap_mangen::Man::new(command) + .title(title.to_uppercase()) + .render(&mut buffer)?; + fs::write(path, buffer) +} diff --git a/docs/cli.md b/docs/cli.md new file mode 100644 index 0000000..06955cc --- /dev/null +++ b/docs/cli.md @@ -0,0 +1,316 @@ +# comline CLI guide + +`comline` is the command-line interface to [Comline](https://github.com/ComlineProject). +It drives the everyday workflow around Comline schemas: scaffold a project, +validate it, freeze immutable versions, compare versions, and generate code — all +on top of `comline-core`. + +This is the long-form reference. For a two-minute tour see the +[README](../README.md). + +- [Overview](#overview) +- [Installation](#installation) +- [Project layout](#project-layout) +- [Versioning model](#versioning-model) +- [Commands](#commands) + - [`new`](#comline-new) + - [`check`](#comline-check) + - [`build`](#comline-build) + - [`generate`](#comline-generate) + - [`diff`](#comline-diff) + - [`clean`](#comline-clean) + - [`completions`](#comline-completions) +- [Global flags](#global-flags) +- [Output and exit codes](#output-and-exit-codes) +- [Watch mode](#watch-mode) +- [Shell completions and man pages](#shell-completions-and-man-pages) +- [Editor and pre-commit integration](#editor-and-pre-commit-integration) + +## Overview + +A Comline project is a directory with a package config (`config.idp`) and one or +more schema files (`src/**/*.ids`). Running a command takes those inputs through: + +**parse → resolve imports → validate → freeze into `.comline/` → generate code** + +`check` stops after validation. `build` goes through the freeze step and records +a new version. `generate` additionally runs the configured code generators. +`diff` reads two already-frozen versions and reports what changed between them. + +## Installation + +`comline` is not on crates.io yet — it depends on `comline-core` via a git URL +until that crate is published. Build it from source: + +```bash +git clone https://github.com/ComlineProject/cli +cargo install --path cli +``` + +This installs the `comline` binary into `~/.cargo/bin`. Man pages and shell +completions are generated during the build — see +[Shell completions and man pages](#shell-completions-and-man-pages). + +## Project layout + +`comline new my-api` creates: + +``` +my-api/ +├── config.idp # package config: name, spec version, code_generation targets +├── src/ +│ └── main.ids # a sample enum + struct to build on +└── .gitignore # ignores .comline/ +``` + +`config.idp` starts as: + +``` +congregation my_api +specification_version = 1 + +code_generation = { + languages = { + rust#1.70.0 = { package_versions=[all] } + } +} +``` + +The directory keeps the name you gave; the `congregation` name is that name +reduced to a valid Comline identifier (letters, digits and `_`), so +`comline new my-api` produces the directory `my-api/` with `congregation my_api`. + +After the first `comline build`, a `.comline/` directory appears next to +`config.idp`. It holds the content-addressable store (`objects/`) and the version +ref (`refs/heads/main`). It is build output — keep it out of version control (the +scaffold's `.gitignore` already does). + +## Versioning model + +Comline stores every build as an immutable commit in an **append-only chain** +under `.comline/`, git-inspired and content-addressed. There are no branches and +history is never rewritten, so any past version stays reproducible. + +Each `build` compares the new schemas against the previous version and bumps the +package version automatically, by the largest change it finds: + +| bump | when | examples | +|---|---|---| +| **major** | a breaking change | removed struct/enum/field/variant/function, changed field type, added a required field | +| **minor** | a new feature | added struct/enum/protocol/error, added a variant, added an optional field, new schema file | +| **patch** | a modification | field made optional, docstring-only change | + +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. + +## Commands + +Every command accepts the [global flags](#global-flags). Run `comline +--help` for the authoritative synopsis. + +### `comline new` + +``` +comline new [--git] +``` + +Scaffold `/` (see [Project layout](#project-layout)). Fails if the +directory already exists. + +- `--git` — also run `git init` in the new project. If `git` is missing or fails, + the project is still created and a warning is printed. + +```bash +comline new my-api +comline new my-api --git +``` + +### `comline check` + +``` +comline check +``` + +Parse, resolve and validate every schema and the package config, reporting the +first error found. It writes **nothing** to `.comline/` and does **not** bump the +version — safe to run from editors, pre-commit hooks and CI lint steps. + +```bash +comline check +comline --path ./services/users check +``` + +Exit `0` if valid, `1` if a schema or the config is invalid, `2` if the directory +is not a Comline project. + +### `comline build` + +``` +comline build [--release] [--watch] +``` + +Compile and validate every schema, then freeze the result into `.comline/`, +bumping the version per the [versioning model](#versioning-model). Prints the +version change, a grouped changelog, and the bump that was applied. + +- `--release` — reserved for future optimization work; currently a no-op (prints + a note). +- `--watch` — rebuild on change; see [Watch mode](#watch-mode). + +```bash +comline build +comline build --watch +``` + +### `comline generate` + +``` +comline generate [--target ] [--watch] +``` + +Build the project, then run every code generator configured in `config.idp`, +writing one file per schema namespace next to `config.idp` (e.g. `main.rust`, +`other.rust`). + +- `--target ` — only run the generator for `` (case-insensitive). + Errors if no configured target matches. Currently `rust` is the only generator + available. +- `--watch` — regenerate on change; see [Watch mode](#watch-mode). + +```bash +comline generate +comline generate --target rust +``` + +### `comline diff` + +``` +comline diff [] +``` + +Compare two frozen versions from `.comline/` and print the breaking changes, new +features and modifications between them — the same report `build` shows, on +demand. `` defaults to `HEAD`. + +Each argument is one of: + +- a **version string**, e.g. `0.2.0` +- a **commit hash** (full, or a prefix of 4+ characters) +- **`HEAD`** — the latest build + +```bash +comline diff 0.1.0 0.2.0 +comline diff 0.1.0 # 0.1.0 against HEAD +comline diff 0.0.1 HEAD +``` + +Fails with exit `2` if the project has never been built, and exit `1` if an +argument matches no stored version (the error lists the versions that exist). + +### `comline clean` + +``` +comline clean [--dry-run] +``` + +Remove build artifacts: the `.comline/` store, and the generated files `generate` +would have produced for the configured targets. The next `build` starts a fresh +version history at `0.0.1`. + +- `--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. + +```bash +comline clean --dry-run +comline clean +``` + +### `comline completions` + +``` +comline completions +``` + +Print a completion script for `` to **stdout**. Supported: `bash`, `zsh`, +`fish`, `powershell`, `elvish`. + +```bash +comline completions bash > /etc/bash_completion.d/comline +comline completions fish > ~/.config/fish/completions/comline.fish +comline completions zsh > ~/.zfunc/_comline +``` + +## Global flags + +| flag | effect | +|---|---| +| `-p`, `--path ` | Run against `` instead of the current directory. | +| `-v`, `-vv`, `-vvv` | Raise log verbosity. Default shows only warnings and errors from `comline-core`; `-v` adds info, `-vv` debug, `-vvv` trace. | +| `-q`, `--quiet` | Silence all progress output; only errors are printed. Conflicts with `-v`. | + +`RUST_LOG` overrides the verbosity flags entirely if set (standard +`tracing_subscriber` syntax, e.g. `RUST_LOG=comline_core=debug`). + +## Output and exit codes + +- **stderr** carries all human-facing output: progress steps, the changelog, + warnings, errors, and `-v` diagnostics. +- **stdout** is reserved for machine-readable payloads. Today only + `comline completions` writes there, so `comline completions fish | source` + and similar pipelines are clean. +- Color is applied through `anstream`: it is stripped automatically when stderr + is not a terminal or when `NO_COLOR` is set. +- The progress spinner is shown only on an interactive terminal, and is + suppressed under `-v` (so it doesn't fight the log output) and `--quiet`. + +Exit codes are stable for scripting and CI: + +| code | meaning | +|---|---| +| `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. | + +```bash +if ! comline check --quiet; then + echo "schemas are invalid" >&2 + exit 1 +fi +``` + +## Watch mode + +`comline build --watch` and `comline generate --watch` run the action once, then +re-run it whenever a file under `src/` changes or `config.idp` is modified +(300 ms debounce). A failing run is reported but does **not** stop the loop — +fix the error and save again. Press Ctrl-C to exit. + +```bash +comline generate --watch --target rust +``` + +## Shell completions and man pages + +Two paths, for two audiences: + +- **Users**: `comline completions ` (above) prints a script on demand. +- **Packagers**: every build also writes, into the crate's `OUT_DIR`: + - `man/comline.1` and `man/comline-.1` + - `completions/comline.{bash,zsh,fish,elv}` and `_comline` for PowerShell + + After `cargo build`, find them under + `target//build/comline-*/out/{man,completions}/`. + +## Editor and pre-commit integration + +Use `comline check` — it validates without writing to `.comline/` or bumping the +version, so it is safe to run on every save or in a hook. + +```sh +# .git/hooks/pre-commit +#!/bin/sh +exec comline check --quiet +``` diff --git a/examples/test_diff_api.rs b/examples/test_diff_api.rs deleted file mode 100644 index febfe7d..0000000 --- a/examples/test_diff_api.rs +++ /dev/null @@ -1,7 +0,0 @@ -use comline_core::schema::ir::diff::{ - analyze_schema_changes, BreakingChange, NewFeature, SchemaChanges, -}; - -fn main() { - println!("API test successful!"); -} diff --git a/src/changes.rs b/src/changes.rs new file mode 100644 index 0000000..062f659 --- /dev/null +++ b/src/changes.rs @@ -0,0 +1,138 @@ +//! Rendering for `comline_core`'s [`SchemaChanges`], shared by `build` and `diff`. + +use comline_core::schema::ir::diff::{BreakingChange, Modification, NewFeature, SchemaChanges}; + +use crate::ui; + +/// Print a grouped breaking / feature / modification changelog. +pub fn render(changes: &SchemaChanges) { + if !changes.breaking_changes.is_empty() { + ui::group(format!( + "🔴 Breaking changes ({})", + changes.breaking_changes.len() + )); + for change in &changes.breaking_changes { + ui::detail(breaking_line(change)); + } + } + + if !changes.new_features.is_empty() { + ui::group(format!("🟢 New features ({})", changes.new_features.len())); + for feature in &changes.new_features { + ui::detail(feature_line(feature)); + } + } + + if !changes.modifications.is_empty() { + ui::group(format!( + "🔵 Modifications ({})", + changes.modifications.len() + )); + for modification in &changes.modifications { + ui::detail(modification_line(modification)); + } + } + + if changes.is_empty() { + ui::detail("no schema changes"); + } +} + +fn count(n: usize, singular: &str) -> String { + if n == 1 { + format!("{n} {singular}") + } else { + format!("{n} {singular}s") + } +} + +fn breaking_line(change: &BreakingChange) -> String { + match change { + BreakingChange::RemovedStruct { name } => format!("❌ Removed struct `{name}`"), + BreakingChange::RemovedEnum { name } => format!("❌ Removed enum `{name}`"), + BreakingChange::RemovedField { + type_name, + field_name, + } => format!("❌ Removed field `{type_name}.{field_name}`"), + BreakingChange::ChangedFieldType { + type_name, + field_name, + old_type, + new_type, + } => format!("🔄 Changed `{type_name}.{field_name}`: {old_type} → {new_type}"), + BreakingChange::AddedRequiredField { + type_name, + field_name, + field_type, + } => format!("⚠️ Added required field `{type_name}.{field_name}`: {field_type}"), + BreakingChange::RemovedEnumVariant { enum_name, variant } => { + format!("❌ Removed `{enum_name}::{variant}`") + } + BreakingChange::RemovedFunction { + protocol_name, + function_name, + } => format!("❌ Removed function `{protocol_name}.{function_name}`"), + BreakingChange::ChangedFunctionSignature { + protocol_name, + function_name, + details, + } => format!("🔄 Changed signature of `{protocol_name}.{function_name}`: {details}"), + BreakingChange::RemovedProtocol { name } => format!("❌ Removed protocol `{name}`"), + BreakingChange::RemovedError { name } => format!("❌ Removed error `{name}`"), + } +} + +fn feature_line(feature: &NewFeature) -> String { + match feature { + NewFeature::AddedStruct { name, field_count } => { + format!( + "➕ Added struct `{name}` ({})", + count(*field_count, "field") + ) + } + NewFeature::AddedEnum { + name, + variant_count, + } => format!( + "➕ Added enum `{name}` ({})", + count(*variant_count, "variant") + ), + NewFeature::AddedField { + type_name, + field_name, + field_type, + optional, + } => { + let opt = if *optional { " (optional)" } else { "" }; + format!("➕ Added field `{type_name}.{field_name}`: {field_type}{opt}") + } + NewFeature::AddedEnumVariant { enum_name, variant } => { + format!("➕ Added variant `{enum_name}::{variant}`") + } + NewFeature::AddedFunction { + protocol_name, + function_name, + signature, + } => format!("➕ Added function `{protocol_name}.{function_name}`: {signature}"), + NewFeature::AddedProtocol { + name, + function_count, + } => format!( + "➕ Added protocol `{name}` ({})", + count(*function_count, "function") + ), + NewFeature::AddedError { name, field_count } => { + format!("➕ Added error `{name}` ({})", count(*field_count, "field")) + } + } +} + +fn modification_line(modification: &Modification) -> String { + match modification { + Modification::FieldMadeOptional { + type_name, + field_name, + } => format!("🔧 Made field `{type_name}.{field_name}` optional"), + Modification::DocstringChanged { name } => format!("📝 Docstring changed on `{name}`"), + } +} diff --git a/src/cli.rs b/src/cli.rs new file mode 100644 index 0000000..c080716 --- /dev/null +++ b/src/cli.rs @@ -0,0 +1,143 @@ +//! Command-line surface for `comline`. +//! +//! This module is intentionally self-contained (only `clap`, `clap_complete` and +//! `std`) so that `build.rs` can `#[path]`-include it to generate man pages and +//! shell completions from the exact same definitions the binary uses. + +use std::path::PathBuf; + +use clap::{Parser, Subcommand}; +use clap_complete::Shell; + +#[derive(Parser, Debug)] +#[command( + name = "comline", + version, + about = "Build, validate, diff and generate code from Comline schemas", + long_about = None, +)] +pub struct Cli { + /// Run against this directory instead of the current one + #[arg(short, long, global = true, value_name = "DIR")] + pub path: Option, + + /// Increase log verbosity (-v info, -vv debug, -vvv trace); surfaces comline-core diagnostics + #[arg( + short, + long, + global = true, + action = clap::ArgAction::Count, + conflicts_with = "quiet", + )] + pub verbose: u8, + + /// Silence progress output; only errors are printed + #[arg(short, long, global = true)] + pub quiet: bool, + + #[command(subcommand)] + pub command: Commands, +} + +#[derive(Subcommand, Debug)] +pub enum Commands { + /// Compile the project and freeze a new immutable version + #[command(long_about = "\ +Compile and validate every schema, then freeze the result into the project's \ +content-addressable store (`.comline/`). The project version is bumped \ +automatically to match the largest schema change since the last build \ +(major for breaking changes, minor for new features, patch for tweaks). + +Examples: + comline build + comline build --watch")] + Build { + /// Enable release optimizations (reserved; currently a no-op) + #[arg(short, long)] + release: bool, + + /// Rebuild automatically when a schema or `config.idp` changes + #[arg(short, long)] + watch: bool, + }, + + /// Validate the project without freezing a version or writing artifacts + #[command(long_about = "\ +Parse, resolve and validate every schema and the project config, reporting the \ +first error found. Unlike `build`, this never writes to `.comline/` and never \ +bumps the version, so it is safe to run in editors and pre-commit hooks.")] + Check, + + /// Compile the project and write generated code for each configured target + #[command(long_about = "\ +Build the project, then run every code generator configured in `config.idp`, \ +writing one file per schema namespace. + +Examples: + comline generate + comline generate --target rust + comline generate --watch")] + Generate { + /// Only generate for this language (e.g. `rust`); default: every configured target + #[arg(short, long, value_name = "LANG")] + target: Option, + + /// Regenerate automatically when a schema or `config.idp` changes + #[arg(short, long)] + watch: bool, + }, + + /// Show the schema changes between two built versions + #[command(long_about = "\ +Compare two frozen versions from the project's `.comline/` store and print the \ +breaking changes, new features and modifications between them — the same \ +report `build` shows, on demand. + +Each argument is a version string (`0.2.0`), a commit hash, or `HEAD`. + +Examples: + comline diff 0.1.0 0.2.0 + comline diff 0.1.0 # compares 0.1.0 against HEAD")] + Diff { + /// Base version: a version string, a commit hash, or `HEAD` + #[arg(value_name = "OLD")] + old: String, + + /// Target version: a version string, a commit hash, or `HEAD` + #[arg(value_name = "NEW", default_value = "HEAD")] + new: String, + }, + + /// Remove build artifacts: the `.comline/` store and generated files + #[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.")] + Clean { + /// 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 + name: String, + + /// Also run `git init` inside the new project + #[arg(long)] + git: bool, + }, + + /// Print a shell completion script to stdout + #[command(long_about = "\ +Write a completion script for the given shell to stdout. + +Examples: + comline completions bash > /etc/bash_completion.d/comline + comline completions fish > ~/.config/fish/completions/comline.fish")] + Completions { + /// Shell to generate completions for + #[arg(value_enum)] + shell: Shell, + }, +} diff --git a/src/commands.rs b/src/commands.rs deleted file mode 100644 index 0e3a7ef..0000000 --- a/src/commands.rs +++ /dev/null @@ -1,36 +0,0 @@ -use clap::{Parser, Subcommand}; -use std::path::PathBuf; - -#[derive(Parser, Debug)] -#[command(name = "comline", version, about = "Comline CLI", long_about = None)] -pub struct Cli { - /// Optional working directory - #[arg(short, long, global = true)] - pub path: Option, - - /// Enable verbose output (can be used multiple times: -v, -vv, -vvv) - #[arg(short, long, global = true, action = clap::ArgAction::Count)] - pub verbose: u8, - - #[command(subcommand)] - pub command: Commands, -} - -#[derive(Subcommand, Debug)] -pub enum Commands { - /// Build the current project - Build { - /// Enable release optimizations - #[arg(short, long)] - release: bool, - }, - /// Check the current project for errors - Check, - /// Compiles the current project and generates code - Generate, - /// Create a new Comline project - New { - /// The name of the project - name: String, - }, -} diff --git a/src/commands/build.rs b/src/commands/build.rs new file mode 100644 index 0000000..cf5f84c --- /dev/null +++ b/src/commands/build.rs @@ -0,0 +1,74 @@ +//! `comline build` — compile, validate and freeze a new immutable version. + +use std::path::Path; + +use comline_core::package::build::{self, VersionBump}; +use miette::Result; + +use crate::changes; +use crate::commands::{core_err, ensure_project}; +use crate::ui; +use crate::watch; + +pub fn run(work_dir: &Path, release: bool, watching: bool) -> Result<()> { + ensure_project(work_dir)?; + + if watching { + watch::run(work_dir, "build", || build_once(work_dir, release)) + } else { + build_once(work_dir, release) + } +} + +fn build_once(work_dir: &Path, release: bool) -> Result<()> { + if release { + ui::note("--release is reserved and currently has no effect"); + } + + ui::step("Building project"); + let spinner = ui::spinner("compiling schemas"); + let result = build::build(work_dir); + ui::finish_spinner(spinner); + + let result = result.map_err(|e| core_err("build failed", e))?; + + ui::success("Project built"); + + if result.is_initial_build() { + ui::detail(format!("📦 initial version {}", result.current_version)); + return Ok(()); + } + + let has_changes = result + .schema_changes + .as_ref() + .map(|c| !c.is_empty()) + .unwrap_or(false); + + if !has_changes { + ui::detail(format!( + "📦 version {} (no changes)", + result.current_version + )); + return Ok(()); + } + + if let Some(version_change) = result.version_change() { + ui::detail(format!("📦 version {version_change}")); + } + if let Some(changes) = &result.schema_changes { + changes::render(changes); + } + ui::detail(bump_line(result.version_bump)); + + Ok(()) +} + +fn bump_line(bump: VersionBump) -> &'static str { + match bump { + VersionBump::Major => "⬆️ major version bump (breaking changes)", + VersionBump::Minor => "⬆️ minor version bump (new features)", + VersionBump::Patch => "⬆️ patch version bump (modifications)", + VersionBump::None => "no version bump", + } +} diff --git a/src/commands/check.rs b/src/commands/check.rs new file mode 100644 index 0000000..7de841f --- /dev/null +++ b/src/commands/check.rs @@ -0,0 +1,22 @@ +//! `comline check` — validate the project without freezing a version. + +use std::path::Path; + +use miette::Result; + +use crate::commands::{core_err, ensure_project}; +use crate::ui; + +pub fn run(work_dir: &Path) -> Result<()> { + ensure_project(work_dir)?; + + ui::step("Validating project"); + let spinner = ui::spinner("compiling schemas"); + let outcome = comline_core::package::build::compile_package(work_dir); + ui::finish_spinner(spinner); + + outcome.map_err(|e| core_err("validation failed", e))?; + + ui::success("Check passed"); + Ok(()) +} diff --git a/src/commands/clean.rs b/src/commands/clean.rs new file mode 100644 index 0000000..8400800 --- /dev/null +++ b/src/commands/clean.rs @@ -0,0 +1,88 @@ +//! `comline clean` — remove build artifacts. + +use std::path::{Path, PathBuf}; + +use comline_core::package::build; +use comline_core::package::config::ir::frozen::FrozenUnit as ConfigUnit; +use miette::{IntoDiagnostic, Result, WrapErr}; + +use crate::commands::ensure_project; +use crate::ui; + +pub fn run(work_dir: &Path, dry_run: bool) -> Result<()> { + ensure_project(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)); + targets.sort(); + targets.dedup(); + + if targets.is_empty() { + ui::success("Nothing to clean"); + return Ok(()); + } + + for target in &targets { + let shown = target.strip_prefix(work_dir).unwrap_or(target).display(); + if dry_run { + ui::detail(format!("would remove {shown}")); + continue; + } + remove(target).wrap_err_with(|| format!("failed to remove `{}`", target.display()))?; + ui::detail(format!("removed {shown}")); + } + + ui::success(if dry_run { + "Dry run complete — nothing was deleted" + } else { + "Clean complete" + }); + Ok(()) +} + +/// Best-effort list of files `generate` would have written: `.` +/// next to `config.idp`, for every configured target. Returns an empty list if +/// the project does not currently compile. +fn generated_files(work_dir: &Path) -> Vec { + let Ok(context) = build::compile_package(work_dir) else { + ui::note("skipping generated-file cleanup: project does not compile"); + return Vec::new(); + }; + let Some(config_units) = &context.config_frozen else { + return Vec::new(); + }; + + let mut files = Vec::new(); + for unit in config_units { + let ConfigUnit::CodeGeneration(generation) = unit else { + continue; + }; + let Some((lang, version)) = generation.name.split_once('#') else { + continue; + }; + let Some((_, ext)) = comline_core::codelib_gen::find_generator(lang, version) else { + continue; + }; + for schema_ctx in &context.schema_contexts { + let schema_ctx = schema_ctx.borrow(); + let candidate = work_dir.join(format!("{}.{}", schema_ctx.namespace_joined(), ext)); + if candidate.is_file() { + files.push(candidate); + } + } + } + files +} + +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/commands/completions.rs b/src/commands/completions.rs new file mode 100644 index 0000000..ed27607 --- /dev/null +++ b/src/commands/completions.rs @@ -0,0 +1,14 @@ +//! `comline completions ` — print a completion script to stdout. + +use clap::CommandFactory; +use clap_complete::{generate, Shell}; +use miette::Result; + +use crate::cli::Cli; + +pub fn run(shell: Shell) -> Result<()> { + let mut command = Cli::command(); + let bin_name = command.get_name().to_string(); + generate(shell, &mut command, bin_name, &mut std::io::stdout()); + Ok(()) +} diff --git a/src/commands/diff.rs b/src/commands/diff.rs new file mode 100644 index 0000000..b25e03a --- /dev/null +++ b/src/commands/diff.rs @@ -0,0 +1,159 @@ +//! `comline diff ` — schema changelog between two frozen versions. +//! +//! Comline's CAS is an append-only linear commit chain (no branches), so we walk +//! it once from `refs/heads/main` and resolve each argument against that list. + +use std::path::Path; + +use comline_core::package::build::cas::objects::{Commit, EntryMode, Tree}; +use comline_core::package::build::cas::storage::Hash; +use comline_core::package::build::cas::{refs, ObjectStore}; +use comline_core::schema::ir::diff::{analyze_schema_changes, SchemaChanges}; +use comline_core::schema::ir::frozen::cas::blob::load_schema_from_tree; +use comline_core::schema::ir::frozen::unit::FrozenUnit; +use miette::Result; + +use crate::changes; +use crate::commands::ensure_project; +use crate::error::CliError; +use crate::ui; + +pub fn run(work_dir: &Path, old: &str, new: &str) -> Result<()> { + ensure_project(work_dir)?; + + if !refs::ref_exists(work_dir, refs::main_ref()) { + return Err(CliError::NothingBuilt(work_dir.to_path_buf()).into()); + } + + let store = ObjectStore::new(work_dir); + let head = refs::read_ref(work_dir, refs::main_ref()) + .map_err(|e| miette::miette!("failed to read HEAD ref: {e:#}"))?; + let history = walk_history(&store, head)?; + + let old_commit = resolve(&history, old)?; + let new_commit = resolve(&history, new)?; + + ui::step(format!( + "Diff {} → {}", + label(old, old_commit), + label(new, new_commit) + )); + + if old_commit.tree == new_commit.tree { + ui::detail("identical — no schema changes"); + return Ok(()); + } + + let old_schemas = load_schemas(&store, old_commit)?; + let new_schemas = load_schemas(&store, new_commit)?; + changes::render(&aggregate(&old_schemas, &new_schemas)); + Ok(()) +} + +struct HistoryEntry { + hash: Hash, + commit: Commit, +} + +/// Collect commits newest-first by following the first parent from `head`. +fn walk_history(store: &ObjectStore, head: Hash) -> Result> { + let mut entries = Vec::new(); + let mut next = Some(head); + while let Some(hash) = next { + let bytes = store + .read(&hash) + .map_err(|e| miette::miette!("failed to read commit {hash}: {e:#}"))?; + let commit = Commit::from_bytes(&bytes) + .map_err(|e| miette::miette!("corrupt commit {hash}: {e:#}"))?; + next = commit.parents.first().copied(); + entries.push(HistoryEntry { hash, commit }); + } + Ok(entries) +} + +/// Resolve `HEAD`, a version string, or a full/short commit hash to a commit. +fn resolve<'a>(history: &'a [HistoryEntry], spec: &str) -> Result<&'a Commit> { + if spec.eq_ignore_ascii_case("HEAD") { + return history + .first() + .map(|e| &e.commit) + .ok_or_else(|| miette::miette!("history is empty")); + } + if let Some(entry) = history.iter().find(|e| e.commit.version == spec) { + return Ok(&entry.commit); + } + if let Some(entry) = history.iter().find(|e| e.hash.to_hex() == spec) { + return Ok(&entry.commit); + } + if spec.len() >= 4 { + let mut matches = history.iter().filter(|e| e.hash.to_hex().starts_with(spec)); + if let (Some(entry), None) = (matches.next(), matches.next()) { + return Ok(&entry.commit); + } + } + + let available: Vec<&str> = history.iter().map(|e| e.commit.version.as_str()).collect(); + Err(miette::miette!( + "no built version matches `{spec}` (available: {})", + available.join(", ") + )) +} + +/// Load every schema's frozen units from a commit's root tree, in tree order. +fn load_schemas(store: &ObjectStore, commit: &Commit) -> Result>> { + let root_bytes = store + .read(&commit.tree) + .map_err(|e| miette::miette!("failed to read root tree: {e:#}"))?; + let root = + Tree::from_bytes(&root_bytes).map_err(|e| miette::miette!("corrupt root tree: {e:#}"))?; + + let mut schemas = Vec::new(); + for entry in &root.entries { + if entry.mode != EntryMode::Tree { + continue; + } + let sub_bytes = store + .read(&entry.hash) + .map_err(|e| miette::miette!("failed to read schema tree `{}`: {e:#}", entry.name))?; + let sub = Tree::from_bytes(&sub_bytes) + .map_err(|e| miette::miette!("corrupt schema tree `{}`: {e:#}", entry.name))?; + let units = load_schema_from_tree(store, &sub) + .map_err(|e| miette::miette!("failed to load schema `{}`: {e:#}", entry.name))?; + schemas.push(units); + } + Ok(schemas) +} + +/// Diff schema-by-schema (paired by position) and merge the results, treating +/// added/removed schema files as wholesale additions/removals. +fn aggregate(old: &[Vec], new: &[Vec]) -> SchemaChanges { + let mut merged = SchemaChanges::default(); + let common = old.len().min(new.len()); + + for i in 0..common { + extend(&mut merged, analyze_schema_changes(&old[i], &new[i])); + } + for schema in &new[common..] { + extend(&mut merged, analyze_schema_changes(&[], schema)); + } + for schema in &old[common..] { + extend(&mut merged, analyze_schema_changes(schema, &[])); + } + merged +} + +fn extend(into: &mut SchemaChanges, from: SchemaChanges) { + into.breaking_changes.extend(from.breaking_changes); + into.new_features.extend(from.new_features); + into.modifications.extend(from.modifications); +} + +fn label(spec: &str, commit: &Commit) -> String { + if spec.eq_ignore_ascii_case("HEAD") { + format!("HEAD ({})", commit.version) + } else if spec == commit.version { + commit.version.clone() + } else { + format!("{spec} ({})", commit.version) + } +} diff --git a/src/commands/generate.rs b/src/commands/generate.rs new file mode 100644 index 0000000..e072fff --- /dev/null +++ b/src/commands/generate.rs @@ -0,0 +1,88 @@ +//! `comline generate` — build, then run each configured code generator. + +use std::path::Path; + +use comline_core::package::build; +use comline_core::package::config::ir::frozen::FrozenUnit as ConfigUnit; +use miette::{IntoDiagnostic, Result, WrapErr}; + +use crate::commands::{core_err, ensure_project}; +use crate::ui; +use crate::watch; + +pub fn run(work_dir: &Path, target: Option<&str>, watching: bool) -> Result<()> { + ensure_project(work_dir)?; + + if watching { + watch::run(work_dir, "generate", || generate_once(work_dir, target)) + } else { + generate_once(work_dir, target) + } +} + +fn generate_once(work_dir: &Path, target: Option<&str>) -> Result<()> { + ui::step("Generating code"); + let spinner = ui::spinner("compiling schemas"); + let built = build::build(work_dir); + ui::finish_spinner(spinner); + let built = built.map_err(|e| core_err("code generation failed", e))?; + + let Some(config_units) = &built.context.config_frozen else { + ui::warn("no `code_generation` targets configured in config.idp"); + return Ok(()); + }; + + let mut matched_targets = 0usize; + let mut written = 0usize; + + for unit in config_units { + let ConfigUnit::CodeGeneration(generation) = unit else { + continue; + }; + let Some((lang, version)) = generation.name.split_once('#') else { + ui::warn(format!( + "skipping invalid language specifier `{}`", + generation.name + )); + continue; + }; + if let Some(wanted) = target { + if !wanted.eq_ignore_ascii_case(lang) { + continue; + } + } + matched_targets += 1; + + let Some((generator, ext)) = comline_core::codelib_gen::find_generator(lang, version) + else { + ui::warn(format!("no generator for `{lang}` (version `{version}`)")); + continue; + }; + + ui::detail(format!("target {lang} (v{version})")); + for schema_ctx in &built.context.schema_contexts { + let schema_ctx = schema_ctx.borrow(); + let Some(frozen_units) = schema_ctx.frozen_schema.borrow().clone() else { + continue; + }; + let output = generator(&frozen_units); + let file_name = format!("{}.{}", schema_ctx.namespace_joined(), ext); + std::fs::write(work_dir.join(&file_name), output) + .into_diagnostic() + .wrap_err_with(|| format!("failed to write `{file_name}`"))?; + ui::detail(format!(" wrote {file_name}")); + written += 1; + } + } + + if let Some(wanted) = target { + if matched_targets == 0 { + return Err(miette::miette!( + "no configured `code_generation` target matches `{wanted}`" + )); + } + } + + ui::success(format!("Generated {written} file(s)")); + Ok(()) +} diff --git a/src/commands/mod.rs b/src/commands/mod.rs new file mode 100644 index 0000000..e7ed9ac --- /dev/null +++ b/src/commands/mod.rs @@ -0,0 +1,31 @@ +//! One module per subcommand. Each exposes a `run(...)` that returns +//! `miette::Result<()>`; `main` maps the error to an exit code. + +pub mod build; +pub mod check; +pub mod clean; +pub mod completions; +pub mod diff; +pub mod generate; +pub mod new; + +use std::path::Path; + +use miette::Result; + +use crate::error::CliError; + +/// Fail with [`CliError::NotAProject`] unless `dir` contains a `config.idp`. +pub fn ensure_project(dir: &Path) -> Result<()> { + if comline_core::package::config::is_package_path(dir) { + Ok(()) + } else { + Err(CliError::NotAProject(dir.to_path_buf()).into()) + } +} + +/// Wrap a `comline-core` (`eyre`) error as a `miette` one for the reporting +/// path. `{:#}` renders the message plus its cause chain, without a backtrace. +pub fn core_err(context: &str, e: impl std::fmt::Display) -> miette::Report { + miette::miette!("{context}: {e:#}") +} diff --git a/src/commands/new.rs b/src/commands/new.rs new file mode 100644 index 0000000..477765a --- /dev/null +++ b/src/commands/new.rs @@ -0,0 +1,113 @@ +//! `comline new` — scaffold a new project directory. + +use std::path::Path; +use std::process::Command; + +use miette::{IntoDiagnostic, Result, WrapErr}; + +use crate::ui; + +const MAIN_IDS: &str = "\ +/// The language a greeting is written in. +enum Language { + English + Spanish + Japanese +} + +struct Greeting { + message: string + language: Language +} +"; + +const GITIGNORE: &str = "\ +# Comline build artifacts +.comline/ +"; + +pub fn run(work_dir: &Path, name: &str, git: bool) -> Result<()> { + let root = work_dir.join(name); + if root.exists() { + return Err(miette::miette!("`{}` already exists", root.display())); + } + + let package = package_ident(name); + + ui::step(format!("Creating project {name}")); + if package != name { + ui::note(format!( + "package name is `{package}` (the directory is `{name}`; \ + Comline names must be letters, digits and `_`)" + )); + } + + std::fs::create_dir_all(root.join("src")) + .into_diagnostic() + .wrap_err("failed to create project directories")?; + + write(&root.join("config.idp"), &config_idp(&package))?; + write(&root.join("src/main.ids"), MAIN_IDS)?; + write(&root.join(".gitignore"), GITIGNORE)?; + + if git { + git_init(&root); + } + + ui::success(format!("Created {}", root.display())); + ui::detail(format!("next: cd {name} && comline build")); + Ok(()) +} + +/// Turn a project name into a valid Comline identifier (`[A-Za-z_][A-Za-z0-9_]*`) +/// for use as the `congregation` name — the directory keeps the original name. +fn package_ident(name: &str) -> String { + let mut ident: String = name + .chars() + .map(|c| { + if c.is_ascii_alphanumeric() || c == '_' { + c + } else { + '_' + } + }) + .collect(); + if ident.is_empty() || ident.starts_with(|c: char| c.is_ascii_digit()) { + ident.insert(0, '_'); + } + ident +} + +fn config_idp(name: &str) -> String { + format!( + "\ +congregation {name} +specification_version = 1 + +code_generation = {{ + languages = {{ + rust#1.70.0 = {{ package_versions=[all] }} + }} +}} +" + ) +} + +fn write(path: &Path, contents: &str) -> Result<()> { + std::fs::write(path, contents) + .into_diagnostic() + .wrap_err_with(|| format!("failed to write `{}`", path.display())) +} + +fn git_init(root: &Path) { + match Command::new("git") + .arg("init") + .arg("-q") + .current_dir(root) + .status() + { + Ok(status) if status.success() => ui::detail("initialized a git repository"), + Ok(_) => ui::warn("`git init` exited with an error; skipping"), + Err(e) => ui::warn(format!("could not run `git init`: {e}")), + } +} diff --git a/src/error.rs b/src/error.rs new file mode 100644 index 0000000..bd4e95d --- /dev/null +++ b/src/error.rs @@ -0,0 +1,43 @@ +//! Error type and process exit codes. +//! +//! Exit codes are part of the CLI's contract with CI and shell scripts, so they +//! are fixed here rather than left to `main`'s `Result` sugar: +//! +//! | code | meaning | +//! |------|-----------------------------------------------------| +//! | 0 | success | +//! | 1 | the command ran but failed (build error, bad diff…) | +//! | 2 | preconditions not met (not a Comline project, …) | +//! | | (clap also exits 2 for usage errors) | + +use std::path::PathBuf; + +use miette::Diagnostic; +use thiserror::Error; + +/// The command ran but failed (build error, unresolved diff ref, …). +pub const EXIT_FAILURE: i32 = 1; +/// A precondition was not met (not a Comline project, nothing built yet, …). +pub const EXIT_PRECONDITION: i32 = 2; + +/// Errors the CLI raises itself (as opposed to errors bubbled up from +/// `comline-core`). Kept small on purpose — most failures are just +/// `miette::miette!(...)`. +#[derive(Debug, Error, Diagnostic)] +pub enum CliError { + #[error("`{}` is not a Comline project (no config.idp)", .0.display())] + #[diagnostic(help("run `comline new ` to scaffold one, or pass `--path `"))] + NotAProject(PathBuf), + + #[error("no builds found in `{}` — run `comline build` first", .0.display())] + NothingBuilt(PathBuf), +} + +/// Map a finished-command error to its process exit code. +pub fn exit_code_for(report: &miette::Report) -> i32 { + match report.downcast_ref::() { + Some(CliError::NotAProject(_)) => EXIT_PRECONDITION, + Some(CliError::NothingBuilt(_)) => EXIT_PRECONDITION, + None => EXIT_FAILURE, + } +} diff --git a/src/main.rs b/src/main.rs old mode 100755 new mode 100644 index e46bbc0..a13485b --- a/src/main.rs +++ b/src/main.rs @@ -1,263 +1,98 @@ +mod changes; +mod cli; mod commands; +mod error; +mod ui; +mod watch; -use clap::Parser; -use commands::{Cli, Commands}; -use miette::{Context, IntoDiagnostic, Result}; use std::env; -use std::fs; -use tracing::{error, info, warn}; +use std::process::ExitCode; + +use clap::Parser; +use miette::Result; use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; -/// Display schema changes in a user-friendly format -fn display_schema_changes(changes: &comline_core::schema::ir::diff::SchemaChanges) { - use comline_core::schema::ir::diff::{BreakingChange, NewFeature, Modification}; - - // Display breaking changes - if !changes.breaking_changes.is_empty() { - warn!("🔴 Breaking changes ({}):", changes.breaking_changes.len()); - for change in &changes.breaking_changes { - match change { - BreakingChange::RemovedStruct { name } => { - warn!(" ❌ Removed struct `{}`", name); - } - BreakingChange::RemovedEnum { name } => { - warn!(" ❌ Removed enum `{}`", name); - } - BreakingChange::RemovedField { type_name, field_name } => { - warn!(" ❌ Removed field `{}.{}`", type_name, field_name); - } - BreakingChange::ChangedFieldType { type_name, field_name, old_type, new_type } => { - warn!(" 🔄 Changed `{}.{}`: {} → {}", type_name, field_name, old_type, new_type); - } - BreakingChange::RemovedEnumVariant { enum_name, variant } => { - warn!(" ❌ Removed `{}::{}`", enum_name, variant); - } - BreakingChange::RemovedFunction { protocol_name, function_name } => { - warn!(" ❌ Removed function `{}.{}`", protocol_name, function_name); - } - BreakingChange::ChangedFunctionSignature { protocol_name, function_name, details } => { - warn!(" 🔄 Changed signature of `{}.{}`: {}", protocol_name, function_name, details); - } - BreakingChange::RemovedProtocol { name } => { - warn!(" ❌ Removed protocol `{}`", name); - } - } - } - } - - // Display new features - if !changes.new_features.is_empty() { - info!("🟢 New features ({}):", changes.new_features.len()); - for feature in &changes.new_features { - match feature { - NewFeature::AddedStruct { name, field_count } => { - info!(" ➕ Added struct `{}` ({} fields)", name, field_count); - } - NewFeature::AddedEnum { name, variant_count } => { - info!(" ➕ Added enum `{}` ({} variants)", name, variant_count); - } - NewFeature::AddedField { type_name, field_name, field_type, optional } => { - let opt_marker = if *optional { " (optional)" } else { "" }; - info!(" ➕ Added field `{}.{}`: {}{}", type_name, field_name, field_type, opt_marker); - } - NewFeature::AddedEnumVariant { enum_name, variant } => { - info!(" ➕ Added variant `{}::{}`", enum_name, variant); - } - NewFeature::AddedFunction { protocol_name, function_name, signature } => { - info!(" ➕ Added function `{}.{}`: {}", protocol_name, function_name, signature); - } - NewFeature::AddedProtocol { name, function_count } => { - info!(" ➕ Added protocol `{}` ({} functions)", name, function_count); - } - } - } - } - - // Display modifications - if !changes.modifications.is_empty() { - info!("🔵 Modifications ({}):", changes.modifications.len()); - for modification in &changes.modifications { - match modification { - Modification::FieldMadeOptional { type_name, field_name } => { - info!(" 🔧 Made field `{}.{}` optional", type_name, field_name); - } +use cli::{Cli, Commands}; + +fn main() -> ExitCode { + reset_sigpipe(); + + let cli = Cli::parse(); + + init_tracing(&cli); + ui::set_quiet(cli.quiet); + ui::set_verbose(cli.verbose > 0); + + match run(cli) { + Ok(()) => ExitCode::SUCCESS, + Err(report) => { + let code = error::exit_code_for(&report); + ui::error(format!("{report}")); + for cause in report.chain().skip(1) { + ui::error(format!(" caused by: {cause}")); } + ExitCode::from(code as u8) } } } -#[tokio::main] -async fn main() -> Result<()> { - let cli = Cli::parse(); - - // Set log level based on verbosity - let log_level = match cli.verbose { - 0 => "info", // Default: info + warn + error (shows our nice output) - 1 => "debug", // -v: debug + info + warn + error (shows core's debug output) - _ => "trace", // -vv+: everything including trace +/// `tracing` carries `comline-core` diagnostics only; the CLI's own output goes +/// through [`ui`]. Everything is written to stderr so stdout stays a clean +/// channel for payloads (`comline completions`). Verbosity is shifted down a +/// notch from the usual so the default run is quiet: `-v` shows info, `-vv` +/// debug, `-vvv` trace. `RUST_LOG` still overrides. +fn init_tracing(cli: &Cli) { + let level = if cli.quiet { + "error" + } else { + match cli.verbose { + 0 => "warn", + 1 => "info", + 2 => "debug", + _ => "trace", + } }; - + tracing_subscriber::registry() .with(tracing_subscriber::EnvFilter::new( - std::env::var("RUST_LOG").unwrap_or_else(|_| log_level.into()), + env::var("RUST_LOG") + .unwrap_or_else(|_| format!("comline={level},comline_core={level}")), )) - .with(tracing_subscriber::fmt::layer()) + .with(tracing_subscriber::fmt::layer().with_writer(std::io::stderr)) .init(); +} + +/// Rust ignores `SIGPIPE`, so writing to a closed pipe (`comline completions +/// fish | head`) surfaces as an `EPIPE` write error that downstream libraries +/// `.expect()` into a panic. Restore the default disposition so the process just +/// exits quietly instead, like every other Unix CLI. +#[cfg(unix)] +fn reset_sigpipe() { + // SAFETY: called once at startup, before any other threads exist. + unsafe { + libc::signal(libc::SIGPIPE, libc::SIG_DFL); + } +} +#[cfg(not(unix))] +fn reset_sigpipe() {} + +fn run(cli: Cli) -> Result<()> { let work_dir = match cli.path { - Some(p) => p, + Some(path) => path, None => env::current_dir() - .into_diagnostic() - .wrap_err("Failed to get current directory")?, + .map_err(|e| miette::miette!("failed to determine the current directory: {e}"))?, }; - match &cli.command { - Commands::Build { release } => { - info!("Building project... Release mode: {}", release); - - if !comline_core::package::config::is_package_path(&work_dir) { - miette::bail!("Current directory is not a Comline project (missing config.idp)"); - } - - match comline_core::package::build::build(&work_dir) { - Ok(build_result) => { - info!("✅ Project built successfully!"); - - // Display version information only if there are changes - if build_result.is_initial_build() { - info!("📦 Initial version: {}", build_result.current_version); - } else { - // Check if there are actual schema changes - let has_changes = build_result.schema_changes - .as_ref() - .map(|changes| !changes.is_empty()) - .unwrap_or(false); - - if has_changes { - if let Some(version_change) = build_result.version_change() { - info!("📦 Version: {}", version_change); - } - - // Display schema changes - if let Some(changes) = &build_result.schema_changes { - display_schema_changes(changes); - - // Display version bump type - match build_result.version_bump { - comline_core::package::build::VersionBump::Major => { - warn!("⬆️ Major version bump applied (breaking changes)"); - }, - comline_core::package::build::VersionBump::Minor => { - info!("⬆️ Minor version bump applied (new features)"); - }, - comline_core::package::build::VersionBump::Patch => { - info!("⬆️ Patch version bump applied (modifications)"); - }, - comline_core::package::build::VersionBump::None => { - info!("No version bump (no changes)"); - } - } - } - } else { - info!("📦 Version: {} (no changes)", build_result.current_version); - } - } - } - Err(e) => { - error!("Build failed: {:?}", e); - return Err(miette::miette!("Build failed: {:?}", e)); - } - } - } - Commands::Generate => { - info!("Generating code..."); - - if !comline_core::package::config::is_package_path(&work_dir) { - miette::bail!("Current directory is not a Comline project (missing config.idp)"); - } - - match comline_core::package::build::build(&work_dir) { - Ok(build_result) => { - if let Some(frozen_config) = &build_result.context.config_frozen { - for unit in frozen_config { - if let comline_core::package::config::ir::frozen::FrozenUnit::CodeGeneration(gen) = unit { - let lang_name_ver = &gen.name; - let parts: Vec<&str> = lang_name_ver.split('#').collect(); - if parts.len() != 2 { - warn!("Skipping invalid language specifier: {}", lang_name_ver); - continue; - } - let lang = parts[0]; - let version = parts[1]; - - if let Some((generator, ext)) = comline_core::codelib_gen::find_generator(lang, version) { - info!("Generating {} code...", lang); - for schema_ctx in &build_result.context.schema_contexts { - let schema_ctx = schema_ctx.borrow(); - // Clone the units to avoid borrowing issues with RefCell - let frozen_units_opt = schema_ctx.frozen_schema.borrow().clone(); - - if let Some(frozen_units) = frozen_units_opt { - let output = generator(&frozen_units); - // Assuming simple file naming strategy for now - let file_name = format!("{}.{}", schema_ctx.namespace_joined(), ext); - let file_path = work_dir.join(&file_name); - if let Err(e) = fs::write(&file_path, output) { - error!("Failed to write generated file {}: {:?}", file_name, e); - } else { - info!("Generated {}", file_name); - } - } - } - } else { - warn!("No generator found for {} version {}", lang, version); - } - } - } - } - info!("Code generation complete!"); - } - Err(e) => { - error!("Code generation failed: {:?}", e); - return Err(miette::miette!("Code generation failed: {:?}", e)); - } - } - } - Commands::Check => { - info!("Checking project..."); - - if !comline_core::package::config::is_package_path(&work_dir) { - miette::bail!("Current directory is not a Comline project (missing config.idp)"); - } - - // Using build() for check as well for now as it performs full validation - match comline_core::package::build::build(&work_dir) { - Ok(_) => info!("Check passed!"), - Err(e) => { - error!("Check failed: {:?}", e); - return Err(miette::miette!("Check failed: {:?}", e)); - } - } - } - Commands::New { name } => { - info!("Creating new project: {}", name); - let path = work_dir.join(name); - if path.exists() { - miette::bail!("Directory '{}' already exists", name); - } - fs::create_dir_all(&path) - .into_diagnostic() - .wrap_err("Failed to create project directory")?; - - let config_path = path.join("config.idp"); - let config_content = format!("congregation {}\nspecification_version = 1\n", name); - fs::write(&config_path, config_content) - .into_diagnostic() - .wrap_err("Failed to write config.idp")?; - - info!("Created new project at {}", path.display()); + match cli.command { + Commands::Build { release, watch } => commands::build::run(&work_dir, release, watch), + Commands::Check => commands::check::run(&work_dir), + Commands::Generate { target, watch } => { + commands::generate::run(&work_dir, target.as_deref(), watch) } + Commands::Diff { old, new } => commands::diff::run(&work_dir, &old, &new), + Commands::Clean { dry_run } => commands::clean::run(&work_dir, dry_run), + Commands::New { name, git } => commands::new::run(&work_dir, &name, git), + Commands::Completions { shell } => commands::completions::run(shell), } - - Ok(()) } diff --git a/src/ui.rs b/src/ui.rs new file mode 100644 index 0000000..c9740dd --- /dev/null +++ b/src/ui.rs @@ -0,0 +1,123 @@ +//! User-facing status output, decoupled from the `tracing` diagnostic layer. +//! +//! `tracing` (`-v` / `-vv`) carries diagnostics coming out of `comline-core`. +//! This module carries the CLI's own progress and result lines: colored, concise, +//! written to **stderr** so stdout stays clean for machine-readable payloads +//! (e.g. `comline completions`). Coloring goes through `anstream`, which strips +//! escapes automatically when stderr is not a terminal or `NO_COLOR` is set. + +use std::borrow::Cow; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::Duration; + +use anstyle::{AnsiColor, Color, Style}; +use indicatif::{ProgressBar, ProgressStyle}; + +static QUIET: AtomicBool = AtomicBool::new(false); +static VERBOSE: AtomicBool = AtomicBool::new(false); + +/// When set, everything except [`error`] is suppressed. +pub fn set_quiet(quiet: bool) { + QUIET.store(quiet, Ordering::Relaxed); +} + +/// When set, spinners are disabled so they don't fight the `tracing` output the +/// user asked for with `-v`. +pub fn set_verbose(verbose: bool) { + VERBOSE.store(verbose, Ordering::Relaxed); +} + +fn quiet() -> bool { + QUIET.load(Ordering::Relaxed) +} + +fn verbose() -> bool { + VERBOSE.load(Ordering::Relaxed) +} + +const GREEN: Style = Style::new() + .fg_color(Some(Color::Ansi(AnsiColor::Green))) + .bold(); +const RED: Style = Style::new() + .fg_color(Some(Color::Ansi(AnsiColor::Red))) + .bold(); +const YELLOW: Style = Style::new().fg_color(Some(Color::Ansi(AnsiColor::Yellow))); +const CYAN: Style = Style::new().fg_color(Some(Color::Ansi(AnsiColor::Cyan))); +const DIM: Style = Style::new().dimmed(); +const BOLD: Style = Style::new().bold(); + +/// A high-level step is starting, e.g. `• Building project`. +pub fn step(msg: impl AsRef) { + if quiet() { + return; + } + anstream::eprintln!("{CYAN}•{CYAN:#} {}", msg.as_ref()); +} + +/// A step finished successfully, e.g. `✓ Project built`. +pub fn success(msg: impl AsRef) { + if quiet() { + return; + } + anstream::eprintln!("{GREEN}✓{GREEN:#} {}", msg.as_ref()); +} + +/// A bold, symbol-free section header (e.g. a changelog group title). +pub fn group(msg: impl AsRef) { + if quiet() { + return; + } + anstream::eprintln!("{BOLD}{}{BOLD:#}", msg.as_ref()); +} + +/// An indented detail line under a step. +pub fn detail(msg: impl AsRef) { + if quiet() { + return; + } + anstream::eprintln!(" {}", msg.as_ref()); +} + +/// A dimmed, purely informational line. +pub fn note(msg: impl AsRef) { + if quiet() { + return; + } + anstream::eprintln!("{DIM}{}{DIM:#}", msg.as_ref()); +} + +/// A non-fatal warning. +pub fn warn(msg: impl AsRef) { + if quiet() { + return; + } + anstream::eprintln!("{YELLOW}warning{YELLOW:#} {}", msg.as_ref()); +} + +/// A fatal error. Always printed, even under `--quiet`. +pub fn error(msg: impl AsRef) { + anstream::eprintln!("{RED}error{RED:#} {}", msg.as_ref()); +} + +/// A steady-tick spinner for a long-running step, drawn on stderr. +/// +/// Returns a hidden bar (a no-op) under `--quiet`, under `-v`, or when stderr is +/// not a terminal, so callers can use it unconditionally. Pass the returned bar +/// to [`finish_spinner`] when the step ends. +pub fn spinner(msg: impl Into>) -> ProgressBar { + if quiet() || verbose() { + return ProgressBar::hidden(); + } + let pb = ProgressBar::new_spinner(); + if let Ok(style) = ProgressStyle::with_template("{spinner:.cyan} {msg}") { + pb.set_style(style); + } + pb.enable_steady_tick(Duration::from_millis(90)); + pb.set_message(msg); + pb +} + +/// Clear a spinner created by [`spinner`]. +pub fn finish_spinner(pb: ProgressBar) { + pb.finish_and_clear(); +} diff --git a/src/watch.rs b/src/watch.rs new file mode 100644 index 0000000..c7b8cbd --- /dev/null +++ b/src/watch.rs @@ -0,0 +1,68 @@ +//! Shared `--watch` loop for `build` and `generate`. + +use std::path::Path; +use std::sync::mpsc::channel; +use std::time::Duration; + +use miette::{IntoDiagnostic, Result, WrapErr}; +use notify_debouncer_mini::notify::RecursiveMode; +use notify_debouncer_mini::{new_debouncer, DebounceEventResult}; + +use crate::ui; + +/// Run `action` once, then again on every debounced change under `/src` or +/// to `/config.idp`, until the process is interrupted (Ctrl-C). +/// +/// A failing run is reported but does not stop the loop — the point of `--watch` +/// is to keep going while you fix the error. +pub fn run(work_dir: &Path, label: &str, mut action: impl FnMut() -> Result<()>) -> Result<()> { + report(label, action()); + + let (tx, rx) = channel::(); + let mut debouncer = new_debouncer(Duration::from_millis(300), tx) + .into_diagnostic() + .wrap_err("failed to start file watcher")?; + + let src = work_dir.join("src"); + if src.is_dir() { + debouncer + .watcher() + .watch(&src, RecursiveMode::Recursive) + .into_diagnostic() + .wrap_err_with(|| format!("failed to watch `{}`", src.display()))?; + } + let config = work_dir.join("config.idp"); + if config.is_file() { + debouncer + .watcher() + .watch(&config, RecursiveMode::NonRecursive) + .into_diagnostic() + .wrap_err_with(|| format!("failed to watch `{}`", config.display()))?; + } + + ui::note(format!( + "watching {} — press Ctrl-C to stop", + work_dir.display() + )); + + for result in rx { + match result { + Ok(events) if !events.is_empty() => { + ui::note("── change detected, re-running ──"); + report(label, action()); + } + Ok(_) => {} + Err(e) => ui::warn(format!("watch error: {e}")), + } + } + Ok(()) +} + +fn report(label: &str, result: Result<()>) { + if let Err(report) = result { + ui::error(format!("{label} failed: {report}")); + for cause in report.chain().skip(1) { + ui::error(format!(" caused by: {cause}")); + } + } +} diff --git a/tests/cli_tests.rs b/tests/cli_tests.rs index 863f2e7..e241d99 100644 --- a/tests/cli_tests.rs +++ b/tests/cli_tests.rs @@ -1,146 +1,366 @@ use assert_cmd::Command; use predicates::prelude::*; use std::fs; +use std::path::{Path, PathBuf}; + +/// Build a `Command` for the `comline` binary under test. +/// +/// Uses the `CARGO_BIN_EXE_comline` path Cargo exports for integration tests, +/// which works regardless of a custom `CARGO_TARGET_DIR` (unlike the deprecated +/// `Command::cargo_bin`). +fn comline_cmd() -> Command { + Command::new(env!("CARGO_BIN_EXE_comline")) +} + +/// Copy `tests/fixtures/simple_project` (two schema files) into a temp dir. +fn fixture_project(temp: &Path) -> PathBuf { + let dest = temp.join("proj"); + let src = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/simple_project"); + copy_dir(&src, &dest); + dest +} + +fn copy_dir(from: &Path, to: &Path) { + fs::create_dir_all(to).unwrap(); + for entry in fs::read_dir(from).unwrap() { + let entry = entry.unwrap(); + let target = to.join(entry.file_name()); + if entry.file_type().unwrap().is_dir() { + copy_dir(&entry.path(), &target); + } else { + fs::copy(entry.path(), &target).unwrap(); + } + } +} + +// --------------------------------------------------------------------------- +// new +// --------------------------------------------------------------------------- #[test] -fn test_new_project_creation() { - let temp_dir = tempfile::tempdir().unwrap(); - let project_name = "my_test_project"; +fn new_scaffolds_a_buildable_project() { + let temp = tempfile::tempdir().unwrap(); - let mut cmd = Command::cargo_bin("comline").unwrap(); - cmd.current_dir(&temp_dir) - .arg("new") - .arg(project_name) + comline_cmd() + .current_dir(&temp) + .args(["new", "my_api"]) + .assert() + .success() + .stderr(predicate::str::contains("Created")); + + let root = temp.path().join("my_api"); + assert!(root.join("config.idp").exists()); + assert!(root.join("src/main.ids").exists()); + assert!(root.join(".gitignore").exists()); + + let config = fs::read_to_string(root.join("config.idp")).unwrap(); + assert!(config.contains("congregation my_api")); + assert!(config.contains("code_generation")); + + // the scaffold must actually build + comline_cmd() + .current_dir(&root) + .arg("build") .assert() .success(); +} - let project_path = temp_dir.path().join(project_name); - assert!(project_path.exists()); - assert!(project_path.join("config.idp").exists()); +#[test] +fn new_refuses_an_existing_directory() { + let temp = tempfile::tempdir().unwrap(); + fs::create_dir(temp.path().join("taken")).unwrap(); - let config_content = fs::read_to_string(project_path.join("config.idp")).unwrap(); - assert!(config_content.contains(&format!("congregation {}", project_name))); - assert!(config_content.contains("specification_version = 1")); + comline_cmd() + .current_dir(&temp) + .args(["new", "taken"]) + .assert() + .failure() + .stderr(predicate::str::contains("already exists")); } #[test] -fn test_check_valid_project() { - let temp_dir = tempfile::tempdir().unwrap(); - let project_name = "valid_project"; +fn new_sanitizes_a_hyphenated_name_into_a_valid_package() { + let temp = tempfile::tempdir().unwrap(); - // Create a valid project first - let mut cmd = Command::cargo_bin("comline").unwrap(); - cmd.current_dir(&temp_dir) - .arg("new") - .arg(project_name) + comline_cmd() + .current_dir(&temp) + .args(["new", "my-api"]) .assert() .success(); - let project_path = temp_dir.path().join(project_name); + let root = temp.path().join("my-api"); + assert!(root.is_dir(), "directory keeps the original name"); + + let config = fs::read_to_string(root.join("config.idp")).unwrap(); + assert!(config.contains("congregation my_api")); - // Run check - let mut cmd_check = Command::cargo_bin("comline").unwrap(); - cmd_check - .current_dir(&project_path) + // the sanitized scaffold must still build + comline_cmd() + .current_dir(&root) + .arg("build") + .assert() + .success(); +} + +// --------------------------------------------------------------------------- +// check +// --------------------------------------------------------------------------- + +#[test] +fn check_passes_on_a_valid_project_without_writing_cas() { + let temp = tempfile::tempdir().unwrap(); + let project = fixture_project(temp.path()); + + comline_cmd() + .current_dir(&project) .arg("check") .assert() .success() - .stdout(predicate::str::contains("Check passed!")); + .stderr(predicate::str::contains("Check passed")); + + assert!( + !project.join(".comline").exists(), + "check must not create the CAS store" + ); } #[test] -fn test_build_project() { - let temp_dir = tempfile::tempdir().unwrap(); - let project_name = "buildable_project"; +fn check_without_config_fails_with_precondition_code() { + let temp = tempfile::tempdir().unwrap(); - // Create a valid project first - let mut cmd = Command::cargo_bin("comline").unwrap(); - cmd.current_dir(&temp_dir) - .arg("new") - .arg(project_name) + comline_cmd() + .current_dir(&temp) + .arg("check") .assert() - .success(); + .failure() + .code(2) + .stderr(predicate::str::contains("is not a Comline project")); +} - let project_path = temp_dir.path().join(project_name); +#[test] +fn check_reports_a_broken_schema() { + let temp = tempfile::tempdir().unwrap(); + let project = fixture_project(temp.path()); + fs::write(project.join("src/main.ids"), "struct Broken {").unwrap(); - // Run build - let mut cmd_build = Command::cargo_bin("comline").unwrap(); - cmd_build - .current_dir(&project_path) - .arg("build") - .arg("--release") + comline_cmd() + .current_dir(&project) + .arg("check") .assert() - .success() - .stdout(predicate::str::contains("Project built successfully!")); + .failure() + .code(1) + .stderr(predicate::str::contains("validation failed")); } +// --------------------------------------------------------------------------- +// build +// --------------------------------------------------------------------------- + #[test] -fn test_generate_project() { - let temp_dir = tempfile::tempdir().unwrap(); - let project_name = "gen_project"; - let project_path = temp_dir.path().join(project_name); +fn build_freezes_an_initial_version() { + let temp = tempfile::tempdir().unwrap(); + let project = fixture_project(temp.path()); - // Copy fixture instead of creating new - let fixture_path = std::env::current_dir() - .unwrap() - .join("tests/fixtures/simple_project"); + comline_cmd() + .current_dir(&project) + .args(["build", "--release"]) + .assert() + .success() + .stderr(predicate::str::contains("Project built")) + .stderr(predicate::str::contains("initial version 0.0.1")); + + assert!(project.join(".comline").is_dir()); +} - // Simple recursive copy for Linux/Unix - std::process::Command::new("cp") - .arg("-r") - .arg(&fixture_path) - .arg(&project_path) - .status() - .expect("Failed to copy fixture"); +// --------------------------------------------------------------------------- +// generate +// --------------------------------------------------------------------------- - let mut cmd_gen = Command::cargo_bin("comline").unwrap(); - cmd_gen - .current_dir(&project_path) - .arg("generate") +#[test] +fn generate_writes_one_file_per_schema() { + let temp = tempfile::tempdir().unwrap(); + let project = fixture_project(temp.path()); + + comline_cmd() + .current_dir(&project) + .args(["generate", "--target", "rust"]) .assert() .success() - .stdout(predicate::str::contains("Code generation complete!")); + .stderr(predicate::str::contains("Generated")); + + assert!(project.join("main.rust").exists()); + assert!(project.join("other.rust").exists()); } #[test] -fn test_check_fail_no_config() { - let temp_dir = tempfile::tempdir().unwrap(); +fn generate_rejects_an_unconfigured_target() { + let temp = tempfile::tempdir().unwrap(); + let project = fixture_project(temp.path()); - let mut cmd = Command::cargo_bin("comline").unwrap(); - cmd.current_dir(&temp_dir) - .arg("check") + comline_cmd() + .current_dir(&project) + .args(["generate", "--target", "python"]) .assert() .failure() + .code(1) .stderr(predicate::str::contains( - "Comline project (missing config.idp)", + "no configured `code_generation` target", )); } +// --------------------------------------------------------------------------- +// diff +// --------------------------------------------------------------------------- + #[test] -fn test_custom_path() { - let temp_dir = tempfile::tempdir().unwrap(); - let project_name = "path_test_project"; - let project_path = temp_dir.path().join(project_name); +fn diff_reports_changes_between_two_versions() { + let temp = tempfile::tempdir().unwrap(); + let project = fixture_project(temp.path()); - // Copy fixture - let fixture_path = std::env::current_dir() - .unwrap() - .join("tests/fixtures/simple_project"); + comline_cmd() + .current_dir(&project) + .arg("build") + .assert() + .success(); + + // add a struct, then rebuild to bump the version + let schema = project.join("src/main.ids"); + let mut text = fs::read_to_string(&schema).unwrap(); + text.push_str("\nstruct Added {\n x: string\n}\n"); + fs::write(&schema, text).unwrap(); + + comline_cmd() + .current_dir(&project) + .arg("build") + .assert() + .success(); - std::process::Command::new("cp") - .arg("-r") - .arg(&fixture_path) - .arg(&project_path) - .status() - .expect("Failed to copy fixture"); + comline_cmd() + .current_dir(&project) + .args(["diff", "0.0.1", "HEAD"]) + .assert() + .success() + .stderr(predicate::str::contains("New features")) + .stderr(predicate::str::contains("Added")); +} + +#[test] +fn diff_without_a_build_fails_with_precondition_code() { + let temp = tempfile::tempdir().unwrap(); + let project = fixture_project(temp.path()); + + comline_cmd() + .current_dir(&project) + .args(["diff", "0.0.1", "HEAD"]) + .assert() + .failure() + .code(2) + .stderr(predicate::str::contains("no builds found")); +} + +#[test] +fn diff_rejects_an_unknown_ref() { + 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(["diff", "9.9.9"]) + .assert() + .failure() + .code(1) + .stderr(predicate::str::contains("no built version matches")); +} + +// --------------------------------------------------------------------------- +// clean +// --------------------------------------------------------------------------- + +#[test] +fn clean_removes_the_cas_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) + .arg("clean") + .assert() + .success() + .stderr(predicate::str::contains("Clean complete")); + + assert!(!project.join(".comline").exists()); +} + +#[test] +fn clean_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(["clean", "--dry-run"]) + .assert() + .success() + .stderr(predicate::str::contains("would remove")); + + assert!(project.join(".comline").exists()); +} + +// --------------------------------------------------------------------------- +// completions / global flags +// --------------------------------------------------------------------------- + +#[test] +fn completions_are_written_to_stdout() { + comline_cmd() + .args(["completions", "bash"]) + .assert() + .success() + .stdout(predicate::str::contains("comline")) + .stderr(predicate::str::is_empty()); +} + +#[test] +fn quiet_build_is_silent_on_success() { + let temp = tempfile::tempdir().unwrap(); + let project = fixture_project(temp.path()); + + comline_cmd() + .current_dir(&project) + .args(["--quiet", "build"]) + .assert() + .success() + .stdout(predicate::str::is_empty()) + .stderr(predicate::str::is_empty()); +} + +#[test] +fn path_flag_runs_outside_the_cwd() { + let temp = tempfile::tempdir().unwrap(); + let project = fixture_project(temp.path()); - // Run check from a neutral directory (temp_dir root), pointing to the project - let mut cmd = Command::cargo_bin("comline").unwrap(); - cmd.current_dir(&temp_dir) + comline_cmd() + .current_dir(&temp) .arg("--path") - .arg(&project_path) + .arg(&project) .arg("check") .assert() .success() - .stdout(predicate::str::contains("Check passed!")); + .stderr(predicate::str::contains("Check passed")); }