diff --git a/README.md b/README.md index 42296bb..566fa15 100644 --- a/README.md +++ b/README.md @@ -30,7 +30,8 @@ comline generate # write generated code for each configured target | Command | What it does | |---|---| | `comline new [--git]` | Scaffold `/` with `config.idp`, `comline.toml`, `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 add ` / `comline add --git --commit --version ` | Add a dependency to `config.idp`: resolved first (a git pin is fetched), then written with its content `hash` pinned. `--no-hash` skips the pin. | +| `comline check` | Parse, resolve and validate every schema. No `.comline/` writes (beyond fetching git dependencies), 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 ] [--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 ``). | diff --git a/docs/cli.md b/docs/cli.md index 4944063..2bf5801 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -14,6 +14,7 @@ This is the long-form reference. For a two-minute tour see the - [Versioning model](#versioning-model) - [Commands](#commands) - [`new`](#comline-new) + - [`add`](#comline-add) - [`check`](#comline-check) - [`build`](#comline-build) - [`generate`](#comline-generate) @@ -139,6 +140,40 @@ comline new my-api comline new my-api --git ``` +### `comline add` + +``` +comline add [--no-hash] +comline add --git --commit --version [--no-hash] +``` + +Declare another Comline package as a dependency, imported under ``: +`use ::models::Thing`. It is resolved first, the way `check` resolves it, +so an entry that wouldn't resolve is never written: + +- `` — a package on disk, relative to this package's directory (written to + `config.idp` as given); +- `--git --commit --version ` — a commit of a git + repository, fetched into `.comline/deps-cache/` with the `git` binary. + `--version` is the version that commit stands for. + +The entry goes into `config.idp`'s `dependencies` block, created at the end of +the file if there isn't one, in the file's own indentation; every other line is +left as written. Its `hash` is pinned to the content just compiled, so if the +dependency changes later, `check` and `build` fail until the pin is updated. + +- `--no-hash` — don't pin the hash (say, a path dependency still being worked + on). + +```bash +comline add shared_types ../shared-types +comline add net --git https://github.com/acme/net --commit 4f2c9e1 --version 1.2.0 +``` + +Exit `0` once added, `1` if the dependency doesn't resolve or can't be added +(the name is already declared, isn't an identifier, or is already one of this +package's own namespaces), `2` if the directory is not a Comline project. + ### `comline check` ``` @@ -146,8 +181,9 @@ 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. +first error found. It writes **nothing** to `.comline/` (beyond fetching git +dependencies into `.comline/deps-cache/`) and does **not** bump the version — +safe to run from editors, pre-commit hooks and CI lint steps. ```bash comline check diff --git a/src/cli.rs b/src/cli.rs index f2739a9..5e0f02c 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -172,6 +172,49 @@ pass `--force`.")] git: bool, }, + /// Add a dependency to `config.idp`, resolved and pinned + #[command(long_about = "\ +Declare another Comline package as a dependency. It is resolved first, the way \ +`check` resolves it (a git pin is fetched into `.comline/deps-cache/`, then \ +compiled), so an entry that wouldn't resolve is never written. Its entry then \ +goes into `config.idp`'s `dependencies` block, with `hash` pinned to the content \ +just compiled: if the dependency changes later, the build fails until the pin is \ +updated. The rest of `config.idp` is left as written. + +Its schemas are imported under NAME: `use NAME::models::Thing`. + +Examples: + comline add shared_types ../shared-types + comline add net --git https://github.com/acme/net --commit 4f2c9e1 --version 1.2.0")] + Add { + /// Name to import it under (`use ::...`) + name: String, + + /// A package on disk, relative to this package's directory + #[arg( + value_name = "DIR", + required_unless_present = "git", + conflicts_with = "git" + )] + dir: Option, + + /// Fetch it from this git repository instead + #[arg(long, value_name = "URI", requires_all = ["commit", "version"])] + git: Option, + + /// Commit to pin (with `--git`) + #[arg(long, value_name = "SHA", requires = "git")] + commit: Option, + + /// Version that commit stands for (with `--git`) + #[arg(long, value_name = "VERSION", requires = "git")] + version: Option, + + /// Don't pin its content hash (say, a path dependency still being worked on) + #[arg(long)] + no_hash: bool, + }, + /// Print a shell completion script to stdout #[command(long_about = "\ Write a completion script for the given shell to stdout. diff --git a/src/commands/add.rs b/src/commands/add.rs new file mode 100644 index 0000000..65106fc --- /dev/null +++ b/src/commands/add.rs @@ -0,0 +1,541 @@ +//! `comline add` — declare a dependency in `config.idp`, resolved and pinned. +//! +//! The dependency is resolved first, the way `comline check` resolves it (a +//! git pin is fetched into `.comline/deps-cache/`, then compiled), so an entry +//! that wouldn't resolve is never written. Its entry then goes into +//! `config.idp` as a text edit, in the file's own indentation, leaving every +//! other line as written, and with `hash` pinned to the content just compiled. + +use std::path::{Path, PathBuf}; + +use comline_core::package::config::dependency::{ + DependencyConfig, DependencySource, DEPS_CACHE_DIR, +}; +use comline_core::package::config::idl::grammar as config_grammar; +use comline_core::package::deps; +use comline_core::package::layout::SCHEMAS_DIR; +use miette::{IntoDiagnostic, Result, WrapErr}; + +use crate::commands::{core_err, ensure_project}; +use crate::ui; + +/// Where the dependency comes from. +pub enum Source { + /// A package on disk, relative to this one. + Path(PathBuf), + /// A commit of a git repository, and the version it stands for. + Git { + uri: String, + commit: String, + version: String, + }, +} + +impl Source { + /// From the command line: a `DIR`, or `--git` with its `--commit` and + /// `--version` (clap enforces which combinations get here). + pub fn from_args( + dir: Option, + git: Option, + commit: Option, + version: Option, + ) -> Result { + match (dir, git, commit, version) { + (Some(dir), None, None, None) => Ok(Source::Path(dir)), + (None, Some(uri), Some(commit), Some(version)) => Ok(Source::Git { + uri, + commit, + version, + }), + _ => Err(miette::miette!( + "give either a DIR, or --git with --commit and --version" + )), + } + } +} + +pub fn run(work_dir: &Path, name: &str, source: Source, pin: bool) -> Result<()> { + ensure_project(work_dir)?; + if !is_identifier(name) { + return Err(miette::miette!( + "`{name}` can't name a dependency: it's imported as `use {name}::…`, so it must be \ + an identifier (letters, digits and `_`, not starting with a digit)" + )); + } + + let manifest_path = work_dir.join("config.idp"); + let manifest = std::fs::read_to_string(&manifest_path) + .into_diagnostic() + .wrap_err("failed to read config.idp")?; + let declared = declared_dependencies(&manifest)?; + if declared.iter().any(|d| d.name == name) { + return Err(miette::miette!( + "`{name}` is already a dependency in config.idp" + )); + } + // A dependency's schemas merge in under its name, next to the package's own. + let schemas = work_dir.join(SCHEMAS_DIR); + if schemas.join(format!("{name}.ids")).exists() || schemas.join(name).is_dir() { + return Err(miette::miette!( + "this package already has a `{name}` namespace in {SCHEMAS_DIR}/; pick another name, \ + or `use {name}::…` would mean both" + )); + } + + if let Source::Path(dir) = &source { + if !work_dir.join(dir).join("config.idp").exists() { + return Err(miette::miette!( + "`{}` isn't a Comline package (no config.idp there); a dependency's path is \ + relative to this package's directory", + dir.display() + )); + } + } + + let mut dependency = DependencyConfig { + name: name.to_string(), + source: match &source { + Source::Path(dir) => DependencySource::Path { + path: dir.clone(), + hash: None, + }, + Source::Git { + uri, + commit, + version, + } => DependencySource::Git { + version: version.clone(), + uri: uri.clone(), + commit: commit.clone(), + hash: None, + }, + }, + }; + // Before fetching anything: the entry has to be writable. + entry_fields(&dependency)?; + + ui::step(format!("Resolving {name}{}", ui::at_path(work_dir))); + let spinner = ui::spinner(match source { + Source::Path(_) => "compiling", + Source::Git { .. } => "fetching and compiling", + }); + let cache_dir = work_dir.join(DEPS_CACHE_DIR); + let resolve = || deps::resolve(&dependency, work_dir, &cache_dir); + // `resolve` warns that an entry without a hash is trusted and suggests + // the very pin this command writes next: keep that out of a normal run. + let resolved = if ui::verbose() { + resolve() + } else { + tracing::subscriber::with_default(tracing::subscriber::NoSubscriber::default(), resolve) + }; + ui::finish_spinner(spinner); + let resolved = resolved.map_err(|e| core_err("couldn't resolve the dependency", e))?; + + let hash = pin.then(|| format!("blake3:{}", resolved.content_hash.to_hex())); + match &mut dependency.source { + DependencySource::Path { hash: h, .. } | DependencySource::Git { hash: h, .. } => { + *h = hash.clone() + } + DependencySource::Registry { .. } => { + unreachable!("`comline add` never builds a registry source") + } + } + + let fields = entry_fields(&dependency)?; + let updated = with_dependency(&manifest, name, &fields); + verify(&updated, &declared, &dependency).map_err(|problem| { + miette::miette!( + "couldn't add the entry to config.idp safely ({problem}); add it by hand:\n{}", + entry_lines(name, &fields, " ", " ").join("\n") + ) + })?; + std::fs::write(&manifest_path, updated) + .into_diagnostic() + .wrap_err("failed to write config.idp")?; + + ui::success(format!("Added {name} to config.idp")); + match &hash { + Some(hash) => ui::detail(format!("pinned: hash = \"{hash}\"")), + None => ui::note("not pinned (--no-hash): a change to it won't fail the build"), + } + if let Source::Git { .. } = source { + ui::detail(format!("fetched into {}", resolved.resolved_path.display())); + } + ui::detail(format!("import its schemas as `use {name}::…`")); + Ok(()) +} + +fn declared_dependencies(manifest: &str) -> Result> { + let congregation = config_grammar::parse(manifest).map_err(|_| { + miette::miette!("config.idp doesn't parse; fix it before adding a dependency") + })?; + let declared = DependencyConfig::parse_dependencies(&congregation.assignments) + .map_err(|e| miette::miette!("config.idp: {e}"))?; + Ok(declared.into_values().collect()) +} + +/// The entry's `key = "value"` lines, in the order the docs write them. +fn entry_fields(dependency: &DependencyConfig) -> Result> { + let mut fields = match &dependency.source { + // `/` works as a separator everywhere, and a `\` would need escaping + // that `config.idp` strings don't undo. + DependencySource::Path { path, .. } => { + vec![("path", path.to_string_lossy().replace('\\', "/"))] + } + DependencySource::Git { + version, + uri, + commit, + .. + } => { + vec![ + ("version", version.clone()), + ("uri", uri.clone()), + ("commit", commit.clone()), + ] + } + DependencySource::Registry { .. } => { + unreachable!("`comline add` never builds a registry source") + } + }; + if let Some(hash) = dependency.declared_hash() { + fields.push(("hash", hash.to_string())); + } + if let Some((key, _)) = fields.iter().find(|(_, value)| value.contains(['"', '\\'])) { + return Err(miette::miette!( + "the dependency's `{key}` can't contain `\"` or `\\`" + )); + } + Ok(fields) +} + +/// `manifest` with the entry `name = { fields }` added to its top-level +/// `dependencies` block, or in a new block at the end. Every other line is +/// left as written; the entry follows the block's own indentation. +fn with_dependency(manifest: &str, name: &str, fields: &[(&str, String)]) -> String { + let Some((open, close)) = dependencies_block(manifest) else { + let entry = entry_lines(name, fields, " ", " ").join("\n"); + return format!( + "{}\n\ndependencies = {{\n{entry}\n}}\n", + manifest.trim_end() + ); + }; + + let block_indent = indent_of(manifest, open); + let inner = &manifest[open + 1..close]; + // The first entry's line sets the indentation; an empty block gets one + // level more than its own line. + let first_entry = inner + .find(|c: char| !c.is_whitespace()) + .map(|i| open + 1 + i); + let entry_indent = match first_entry { + Some(at) if manifest[open..at].contains('\n') => indent_of(manifest, at).to_string(), + _ => format!("{block_indent}{}", unit(block_indent)), + }; + let step = entry_indent + .strip_prefix(block_indent) + .filter(|s| !s.is_empty()) + .unwrap_or(unit(block_indent)); + let mut entry = entry_lines(name, fields, &entry_indent, step).join("\n"); + // Entries already separated by blank lines get one before this one too. + if first_entry.is_some() && has_blank_line(inner.trim()) { + entry.insert(0, '\n'); + } + + let line_start = manifest[..close].rfind('\n').map_or(0, |i| i + 1); + if manifest[line_start..close].trim().is_empty() { + // `}` on its own line: the entry goes on the lines before it. + format!( + "{}{entry}\n{}", + &manifest[..line_start], + &manifest[line_start..] + ) + } else { + // `}` after other text (`dependencies = {}`): break the line. + format!( + "{}\n{entry}\n{block_indent}{}", + manifest[..close].trim_end(), + &manifest[close..] + ) + } +} + +fn entry_lines(name: &str, fields: &[(&str, String)], indent: &str, step: &str) -> Vec { + let mut lines = vec![format!("{indent}{name} = {{")]; + lines.extend( + fields + .iter() + .map(|(key, value)| format!("{indent}{step}{key} = \"{value}\"")), + ); + lines.push(format!("{indent}}}")); + lines +} + +/// Byte offsets of the `{` and matching `}` of the top-level +/// `dependencies = { ... }`, skipping strings and comments. +fn dependencies_block(manifest: &str) -> Option<(usize, usize)> { + let tokens = tokens(manifest); + let mut depth = 0usize; + for (i, &(token, _)) in tokens.iter().enumerate() { + match token { + Token::Open => depth += 1, + Token::Close => depth = depth.saturating_sub(1), + Token::Word("dependencies") if depth == 0 => { + if let [(Token::Equals, _), (Token::Open, open), ..] = tokens[i + 1..] { + let mut inner_depth = 0usize; + for &(token, at) in &tokens[i + 2..] { + match token { + Token::Open => inner_depth += 1, + Token::Close if inner_depth == 1 => return Some((open, at)), + Token::Close => inner_depth -= 1, + _ => {} + } + } + return None; + } + } + _ => {} + } + } + None +} + +#[derive(Debug, Clone, Copy, PartialEq)] +enum Token<'a> { + Word(&'a str), + Equals, + /// `{` or `[`. + Open, + /// `}` or `]`. + Close, + Other, +} + +/// `config.idp`'s tokens with their byte offsets, minus whitespace, comments +/// (`//`, `/* */`) and string contents. +fn tokens(text: &str) -> Vec<(Token<'_>, usize)> { + let bytes = text.as_bytes(); + let is_word = + |b: u8| b.is_ascii_alphanumeric() || matches!(b, b'_' | b':' | b'#' | b'@' | b'.'); + let mut tokens = Vec::new(); + let mut i = 0; + while i < bytes.len() { + let b = bytes[i]; + match b { + b'/' if bytes.get(i + 1) == Some(&b'/') => { + i = text[i..].find('\n').map_or(bytes.len(), |n| i + n); + } + b'/' if bytes.get(i + 1) == Some(&b'*') => { + i = text[i + 2..] + .find("*/") + .map_or(bytes.len(), |n| i + 2 + n + 2); + } + b'"' => { + i += 1; + while i < bytes.len() && bytes[i] != b'"' { + i += if bytes[i] == b'\\' { 2 } else { 1 }; + } + tokens.push((Token::Other, i)); + i += 1; + } + b'{' | b'[' => { + tokens.push((Token::Open, i)); + i += 1; + } + b'}' | b']' => { + tokens.push((Token::Close, i)); + i += 1; + } + b'=' => { + tokens.push((Token::Equals, i)); + i += 1; + } + _ if is_word(b) => { + let start = i; + while i < bytes.len() && is_word(bytes[i]) { + i += 1; + } + tokens.push((Token::Word(&text[start..i]), start)); + } + _ if b.is_ascii_whitespace() => i += 1, + _ => { + tokens.push((Token::Other, i)); + i += 1; + } + } + } + tokens +} + +/// The leading whitespace of the line `at` is on. +fn indent_of(text: &str, at: usize) -> &str { + let start = text[..at].rfind('\n').map_or(0, |i| i + 1); + let line = &text[start..]; + &line[..line.len() - line.trim_start_matches([' ', '\t']).len()] +} + +/// One indentation level, in the file's own style: a tab if the line is +/// tab-indented, else four spaces. +fn unit(indent: &str) -> &'static str { + if indent.starts_with('\t') { + "\t" + } else { + " " + } +} + +fn has_blank_line(text: &str) -> bool { + text.lines().any(|line| line.trim().is_empty()) +} + +/// Whether `updated` declares exactly what was declared before plus +/// `dependency`, as `comline check` will read it. +fn verify( + updated: &str, + before: &[DependencyConfig], + dependency: &DependencyConfig, +) -> Result<(), String> { + let after = declared_dependencies(updated).map_err(|e| e.to_string())?; + let Some(added) = after.iter().find(|d| d.name == dependency.name) else { + return Err("the new entry isn't read back".to_string()); + }; + if after.len() != before.len() + 1 { + return Err("other entries changed".to_string()); + } + let same = match (&added.source, &dependency.source) { + (DependencySource::Path { path: a, .. }, DependencySource::Path { path: b, .. }) => { + a.to_string_lossy().replace('\\', "/") == b.to_string_lossy().replace('\\', "/") + } + ( + DependencySource::Git { + version: va, + uri: ua, + commit: ca, + .. + }, + DependencySource::Git { + version: vb, + uri: ub, + commit: cb, + .. + }, + ) => (va, ua, ca) == (vb, ub, cb), + _ => false, + }; + match same && added.declared_hash() == dependency.declared_hash() { + true => Ok(()), + false => Err("the entry reads back differently".to_string()), + } +} + +fn is_identifier(name: &str) -> bool { + name.starts_with(|c: char| c.is_ascii_alphabetic() || c == '_') + && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') +} + +#[cfg(test)] +mod tests { + use super::*; + + fn fields() -> Vec<(&'static str, String)> { + vec![ + ("path", "../shared".to_string()), + ("hash", "blake3:abc".to_string()), + ] + } + + const HEAD: &str = "congregation app\nspecification_version = 1\n"; + + #[test] + fn a_manifest_without_dependencies_gets_a_block_at_the_end() { + let manifest = format!("{HEAD}\ncode_generation = {{\n languages = {{\n rust#1.70.0 = {{}}\n }}\n}}\n"); + assert_eq!( + with_dependency(&manifest, "shared", &fields()), + format!( + "{}\n\ndependencies = {{\n shared = {{\n path = \"../shared\"\n hash = \"blake3:abc\"\n }}\n}}\n", + manifest.trim_end() + ) + ); + } + + #[test] + fn an_entry_goes_last_in_the_block_in_its_indentation() { + let manifest = format!( + "{HEAD}\ndependencies = {{\n net = {{\n version = \"1.0.0\"\n uri = \"x\"\n commit = \"c\"\n }}\n}}\n\n// after\n" + ); + let updated = with_dependency(&manifest, "shared", &fields()); + assert_eq!( + updated, + format!( + "{HEAD}\ndependencies = {{\n net = {{\n version = \"1.0.0\"\n uri = \"x\"\n commit = \"c\"\n }}\n shared = {{\n path = \"../shared\"\n hash = \"blake3:abc\"\n }}\n}}\n\n// after\n" + ) + ); + } + + #[test] + fn blank_lines_between_entries_are_kept_up() { + let manifest = format!( + "{HEAD}dependencies = {{\n a = {{\n path = \"../a\"\n }}\n\n b = {{\n path = \"../b\"\n }}\n}}\n" + ); + let updated = with_dependency(&manifest, "c", &[("path", "../c".to_string())]); + assert!( + updated.ends_with(" }\n\n c = {\n path = \"../c\"\n }\n}\n"), + "{updated}" + ); + } + + #[test] + fn an_empty_block_and_tabs() { + let manifest = format!("{HEAD}dependencies = {{}}\n"); + assert_eq!( + with_dependency(&manifest, "a", &[("path", "../a".to_string())]), + format!("{HEAD}dependencies = {{\n a = {{\n path = \"../a\"\n }}\n}}\n") + ); + + let manifest = + format!("{HEAD}dependencies = {{\n\ta = {{\n\t\tpath = \"../a\"\n\t}}\n}}\n"); + let updated = with_dependency(&manifest, "b", &[("path", "../b".to_string())]); + assert!( + updated.ends_with("\t}\n\tb = {\n\t\tpath = \"../b\"\n\t}\n}\n"), + "{updated:?}" + ); + } + + #[test] + fn braces_in_strings_and_comments_and_nested_keys_are_skipped() { + let manifest = format!( + "{HEAD}// dependencies = {{ not = this }}\nnotes = \"dependencies = {{\"\n/* }} */\nmeta = {{\n dependencies = {{}}\n}}\n\ndependencies = {{\n a = {{\n path = \"../a\" // a }}\n }}\n}}\n" + ); + let (open, close) = dependencies_block(&manifest).unwrap(); + assert_eq!( + &manifest[open..=close], + "{\n a = {\n path = \"../a\" // a }\n }\n}" + ); + } + + #[test] + fn every_edit_reads_back_with_cores_parser() { + for manifest in [ + HEAD.to_string(), + format!("{HEAD}dependencies = {{}}\n"), + format!("{HEAD}\ndependencies = {{\n net = {{\n version = \"1.0.0\"\n uri = \"x\"\n commit = \"c\"\n }}\n}}\n"), + ] { + let before = declared_dependencies(&manifest).unwrap(); + let dependency = DependencyConfig { + name: "shared".to_string(), + source: DependencySource::Path { path: "../shared".into(), hash: Some("blake3:abc".to_string()) }, + }; + let updated = with_dependency(&manifest, "shared", &entry_fields(&dependency).unwrap()); + assert_eq!(verify(&updated, &before, &dependency), Ok(()), "{updated}"); + } + } + + #[test] + fn names_must_be_identifiers() { + assert!(is_identifier("shared_types")); + assert!(is_identifier("_x1")); + for bad in ["shared-types", "1st", "", "a::b", "naïve"] { + assert!(!is_identifier(bad), "{bad}"); + } + } +} diff --git a/src/commands/mod.rs b/src/commands/mod.rs index fdc9e10..18825ad 100644 --- a/src/commands/mod.rs +++ b/src/commands/mod.rs @@ -1,6 +1,7 @@ //! One module per subcommand. Each exposes a `run(...)` that returns //! `miette::Result<()>`; `main` maps the error to an exit code. +pub mod add; pub mod build; pub mod check; pub mod clean; diff --git a/src/main.rs b/src/main.rs index d174cb9..00b9706 100644 --- a/src/main.rs +++ b/src/main.rs @@ -135,6 +135,17 @@ fn run(cli: Cli) -> Result<()> { 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::Add { + name, + dir, + git, + commit, + version, + no_hash, + } => { + let source = commands::add::Source::from_args(dir, git, commit, version)?; + commands::add::run(&work_dir, &name, source, !no_hash) + } Commands::Completions { shell } => commands::completions::run(shell), Commands::Targets => commands::targets::run(), } diff --git a/src/ui.rs b/src/ui.rs index 7952eac..54f7edb 100644 --- a/src/ui.rs +++ b/src/ui.rs @@ -41,7 +41,8 @@ fn quiet() -> bool { QUIET.load(Ordering::Relaxed) } -fn verbose() -> bool { +/// Whether `-v` was given: `comline-core`'s diagnostics are wanted. +pub fn verbose() -> bool { VERBOSE.load(Ordering::Relaxed) } diff --git a/tests/cli/add.rs b/tests/cli/add.rs new file mode 100644 index 0000000..3679e56 --- /dev/null +++ b/tests/cli/add.rs @@ -0,0 +1,249 @@ +//! `comline add` + +use std::fs; +use std::path::{Path, PathBuf}; +use std::process::Command as Process; + +use predicates::prelude::*; + +use crate::util::*; + +/// A minimal package at `dir`, declaring `Thing` in `src/models.ids`. +fn write_package(dir: &Path, name: &str) { + fs::create_dir_all(dir.join("src")).unwrap(); + fs::write( + dir.join("config.idp"), + format!("congregation {name}\nspecification_version = 1\n"), + ) + .unwrap(); + fs::write( + dir.join("src/models.ids"), + "struct Thing {\n id: u64\n}\n", + ) + .unwrap(); +} + +/// The fixture project, with a `shared` package next to it. +fn project_with_sibling(temp: &Path) -> PathBuf { + let project = fixture_project(temp); + write_package(&temp.join("shared"), "shared"); + project +} + +fn uses_thing_from(project: &Path, dependency: &str) { + fs::write( + project.join("src/holder.ids"), + format!("use {dependency}::models::Thing\n\nstruct Holder {{\n thing: Thing\n}}\n"), + ) + .unwrap(); +} + +fn check(project: &Path) -> assert_cmd::assert::Assert { + comline_cmd().current_dir(project).arg("check").assert() +} + +#[test] +fn adds_a_path_dependency_pinned_and_importable() { + let temp = tempfile::tempdir().unwrap(); + let project = project_with_sibling(temp.path()); + let before = fs::read_to_string(project.join("config.idp")).unwrap(); + + comline_cmd() + .current_dir(&project) + .args(["add", "shared", "../shared"]) + .assert() + .success() + .stderr(predicate::str::contains("Added shared to config.idp")) + .stderr(predicate::str::contains("pinned: hash = \"blake3:")) + .stderr(predicate::str::contains("trusting").not()); + + let after = fs::read_to_string(project.join("config.idp")).unwrap(); + assert!( + after.starts_with(before.trim_end()), + "the rest is left as written:\n{after}" + ); + assert!(after.contains("dependencies = {\n shared = {\n path = \"../shared\"\n hash = \"blake3:"), "{after}"); + + uses_thing_from(&project, "shared"); + check(&project).success(); + + // The pin catches a change to the dependency. + fs::write( + temp.path().join("shared/src/models.ids"), + "struct Thing {\n id: u64\n name: str\n}\n", + ) + .unwrap(); + check(&project) + .failure() + .stderr(predicate::str::contains("hash mismatch")); +} + +#[test] +fn no_hash_leaves_it_unpinned() { + let temp = tempfile::tempdir().unwrap(); + let project = project_with_sibling(temp.path()); + + comline_cmd() + .current_dir(&project) + .args(["add", "shared", "../shared", "--no-hash"]) + .assert() + .success() + .stderr(predicate::str::contains("not pinned")); + + assert!(!fs::read_to_string(project.join("config.idp")) + .unwrap() + .contains("hash =")); + fs::write( + temp.path().join("shared/src/models.ids"), + "struct Thing {\n id: u64\n name: str\n}\n", + ) + .unwrap(); + uses_thing_from(&project, "shared"); + check(&project).success(); +} + +#[test] +fn refuses_what_it_cant_add_and_leaves_config_idp_alone() { + let temp = tempfile::tempdir().unwrap(); + let project = project_with_sibling(temp.path()); + comline_cmd() + .current_dir(&project) + .args(["add", "shared", "../shared"]) + .assert() + .success(); + let before = fs::read_to_string(project.join("config.idp")).unwrap(); + + for (args, message) in [ + ( + vec!["add", "shared", "../shared"], + "`shared` is already a dependency", + ), + ( + vec!["add", "elsewhere", "../nowhere"], + "`../nowhere` isn't a Comline package", + ), + ( + vec!["add", "shared-types", "../shared"], + "must be an identifier", + ), + // The fixture's own `src/other.ids`. + ( + vec!["add", "other", "../shared"], + "already has a `other` namespace", + ), + ] { + comline_cmd() + .current_dir(&project) + .args(&args) + .assert() + .failure() + .code(1) + .stderr(predicate::str::contains(message)); + assert_eq!( + fs::read_to_string(project.join("config.idp")).unwrap(), + before, + "{args:?}" + ); + } +} + +#[test] +fn a_package_that_doesnt_compile_isnt_added() { + let temp = tempfile::tempdir().unwrap(); + let project = project_with_sibling(temp.path()); + fs::write(temp.path().join("shared/src/models.ids"), "struct Broken {").unwrap(); + let before = fs::read_to_string(project.join("config.idp")).unwrap(); + + comline_cmd() + .current_dir(&project) + .args(["add", "shared", "../shared"]) + .assert() + .failure() + .stderr(predicate::str::contains("couldn't resolve the dependency")); + assert_eq!( + fs::read_to_string(project.join("config.idp")).unwrap(), + before + ); +} + +#[test] +fn git_needs_a_commit_and_a_version() { + let temp = tempfile::tempdir().unwrap(); + let project = fixture_project(temp.path()); + + comline_cmd() + .current_dir(&project) + .args(["add", "net", "--git", "https://example.test/net"]) + .assert() + .failure() + .code(2) + .stderr(predicate::str::contains("--commit")); +} + +fn git(dir: &Path, args: &[&str]) -> String { + let output = Process::new("git") + .args([ + "-c", + "user.name=test", + "-c", + "user.email=test@example.test", + "-c", + "commit.gpgsign=false", + ]) + .args(args) + .current_dir(dir) + .output() + .expect("git runs"); + assert!( + output.status.success(), + "git {args:?}: {}", + String::from_utf8_lossy(&output.stderr) + ); + String::from_utf8(output.stdout).unwrap().trim().to_string() +} + +#[test] +fn adds_a_git_dependency_at_a_pinned_commit() { + let temp = tempfile::tempdir().unwrap(); + let project = fixture_project(temp.path()); + let repo = temp.path().join("net"); + write_package(&repo, "net"); + git(&repo, &["init", "--quiet"]); + git(&repo, &["add", "."]); + git(&repo, &["commit", "--quiet", "-m", "net"]); + let commit = git(&repo, &["rev-parse", "HEAD"]); + let uri = format!("file://{}", repo.display()); + + comline_cmd() + .current_dir(&project) + .args([ + "add", + "net", + "--git", + &uri, + "--commit", + &commit, + "--version", + "1.0.0", + ]) + .assert() + .success() + .stderr(predicate::str::contains("fetched into")); + + let config = fs::read_to_string(project.join("config.idp")).unwrap(); + assert!( + config.contains(&format!( + " net = {{\n version = \"1.0.0\"\n uri = \"{uri}\"\n commit = \"{commit}\"\n hash = \"blake3:" + )), + "{config}" + ); + assert_eq!( + fs::read_dir(project.join(".comline/deps-cache")) + .unwrap() + .count(), + 1 + ); + + uses_thing_from(&project, "net"); + check(&project).success(); +} diff --git a/tests/cli/main.rs b/tests/cli/main.rs index 414a82b..ec10c66 100644 --- a/tests/cli/main.rs +++ b/tests/cli/main.rs @@ -6,6 +6,7 @@ mod util; +mod add; mod build; mod check; mod clean;