From c2a9bcfde98738a32f182d5d93d2f2a8794c3318 Mon Sep 17 00:00:00 2001 From: Kinflou Date: Tue, 20 Oct 2026 16:43:44 +0800 Subject: [PATCH] comline accept, and comline add asking before it accepts @unverified protocols Both show what each protocol gives up and why, then ask on a terminal (default no). Without one they refuse, naming the flag: --yes for accept, --accept-unverified for add. accept writes accept_unverified into the dependency's entry (replacing one already there), reads it back with core's parser and resolves it before writing; add writes it into the new entry. Accepting is never inherited or silent. --- src/cli.rs | 34 ++++ src/commands/accept.rs | 388 +++++++++++++++++++++++++++++++++++++++++ src/commands/add.rs | 80 ++++++--- src/commands/mod.rs | 1 + src/error.rs | 7 + src/main.rs | 4 +- tests/cli/accept.rs | 140 +++++++++++++++ tests/cli/main.rs | 1 + 8 files changed, 634 insertions(+), 21 deletions(-) create mode 100644 src/commands/accept.rs create mode 100644 tests/cli/accept.rs diff --git a/src/cli.rs b/src/cli.rs index 8a80c50..a69d01b 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -210,6 +210,10 @@ updated. The rest of `config.idp` is left as written. Its schemas are imported under NAME: `use NAME::models::Thing`. +If it has `@unverified` protocols, what each gives up is shown and, on a \ +terminal, you are asked to accept it (see `comline accept`); otherwise pass \ +`--accept-unverified`. Nothing is written unless it's accepted. + Examples: comline add shared_types ../shared-types comline add net --git https://github.com/acme/net --commit 4f2c9e1 --version 1.2.0")] @@ -240,6 +244,36 @@ Examples: /// Don't pin its content hash (say, a path dependency still being worked on) #[arg(long)] no_hash: bool, + + /// Accept what its `@unverified` protocols give up without being asked + #[arg(long)] + accept_unverified: bool, + }, + + /// Accept what a dependency's `@unverified` protocols give up + #[command(long_about = "\ +A protocol marked `@unverified` gives up guarantees Comline otherwise gives its \ +peers (a `none` handshake gives up schema and encoding agreement), and a \ +package depending on it has to accept that in its own `config.idp`, for exactly \ +what's given up. This shows what each protocol gives up and why, then writes \ +`accept_unverified` into the dependency's entry. The rest of `config.idp` is \ +left as written. + +Run it again when a dependency's update gives up more: the build stops until \ +the new set is accepted. + +Requires confirmation: on a terminal you are asked; otherwise pass `--yes`. + +Examples: + comline accept billing every unverified protocol in `billing` + comline accept billing::Billing just `Billing`")] + Accept { + /// The dependency, or one protocol in it: `NAME` or `NAME::PROTOCOL` + target: String, + + /// Accept without being asked + #[arg(long, short)] + yes: bool, }, /// Print a shell completion script to stdout diff --git a/src/commands/accept.rs b/src/commands/accept.rs new file mode 100644 index 0000000..22a6d5d --- /dev/null +++ b/src/commands/accept.rs @@ -0,0 +1,388 @@ +//! `comline accept` — accept what a dependency's `@unverified` protocols give +//! up, by writing `accept_unverified` into its `config.idp` entry. +//! +//! Accepting is a choice the consumer writes down, so it's never silent: what +//! each protocol gives up, and why, is shown first, and on a terminal the +//! user is asked (default no). Without a terminal there's nobody to ask, and +//! it takes a flag. `comline add` uses the same steps for a new dependency. + +use std::collections::BTreeMap; +use std::io::{self, IsTerminal, Write}; +use std::path::Path; + +use comline_core::package::config::dependency::{DependencyConfig, DEPS_CACHE_DIR}; +use comline_core::package::deps; +use comline_core::schema::ir::frozen::unit::Guarantee; +use comline_core::schema::ir::unverified; +use miette::{IntoDiagnostic, Result, WrapErr}; + +use crate::commands::add::{ + declared_dependencies, dependencies_block, indent_of, tokens, unit, Token, +}; +use crate::commands::{core_err, ensure_project}; +use crate::error::CliError; +use crate::ui; + +/// One `@unverified` protocol in a dependency, as its own build froze it. +#[derive(Debug, Clone, PartialEq)] +pub struct Unverified { + pub protocol: String, + pub set: Vec, + pub reason: Option, +} + +/// What a dependency's package gives up: every `@unverified` protocol in it, +/// compiled as its own package (with its own settings and defaults). +pub fn unverified_in(package_dir: &Path) -> Result> { + let compile = || comline_core::package::build::compile_package(package_dir); + let context = quietly(compile).map_err(|e| core_err("couldn't compile the dependency", e))?; + let mut found = Vec::new(); + for schema in &context.schema_contexts { + let schema = schema.borrow(); + let frozen = schema.frozen_schema.borrow(); + let Some(units) = frozen.as_ref() else { + continue; + }; + for (protocol, set, reason) in unverified::protocols(units) { + found.push(Unverified { + protocol: protocol.to_string(), + set: set.to_vec(), + reason: reason.map(str::to_string), + }); + } + } + Ok(found) +} + +/// Run `f` with core's tracing warnings (an unpinned dependency, say) kept +/// out of a normal run. +pub fn quietly(f: impl FnOnce() -> T) -> T { + if ui::verbose() { + f() + } else { + tracing::subscriber::with_default(tracing::subscriber::NoSubscriber::default(), f) + } +} + +/// Show what `dependency` gives up, then decide: `yes` accepts; otherwise a +/// terminal is asked (default no), and anything else is refused with +/// [`CliError::AcceptanceRequired`]. `Ok(false)` when the user declines. +pub fn decide( + dependency: &str, + protocols: &[Unverified], + yes: bool, + flag: &'static str, +) -> Result { + ui::warn(format!( + "{dependency} has {} unverified protocol{}:", + protocols.len(), + if protocols.len() == 1 { "" } else { "s" } + )); + for p in protocols { + let reason = p + .reason + .as_deref() + .map(|r| format!(": \"{r}\"")) + .unwrap_or_default(); + ui::detail(format!( + "{} gives up {}{reason}", + p.protocol, + unverified::describe(&p.set) + )); + } + if yes { + return Ok(true); + } + if !io::stdin().is_terminal() { + return Err(CliError::AcceptanceRequired { flag }.into()); + } + let names: Vec<&str> = protocols.iter().map(|p| p.protocol.as_str()).collect(); + print!("Accept {}? [y/N] ", names.join(", ")); + io::stdout().flush().into_diagnostic()?; + let mut line = String::new(); + io::stdin().read_line(&mut line).into_diagnostic()?; + Ok(matches!( + line.trim().to_ascii_lowercase().as_str(), + "y" | "yes" + )) +} + +/// `{ A = ["schema_agreement"], B = [...] }`, as `config.idp` reads it. +pub fn render(accepted: &BTreeMap>) -> String { + let entries: Vec = accepted + .iter() + .map(|(protocol, set)| format!("{protocol} = {}", unverified::written(set))) + .collect(); + format!("{{ {} }}", entries.join(" ")) +} + +/// `comline accept DEPENDENCY[::PROTOCOL]`. +pub fn run(work_dir: &Path, target: &str, yes: bool) -> Result<()> { + ensure_project(work_dir)?; + let (name, only) = match target.split_once("::") { + Some((name, protocol)) => (name, Some(protocol)), + None => (target, None), + }; + + 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)?; + let Some(dependency) = declared.iter().find(|d| d.name == name) else { + return Err(miette::miette!("`{name}` isn't a dependency in config.idp")); + }; + let Some(dir) = dependency + .package_dir(work_dir) + .filter(|d| d.join("config.idp").exists()) + else { + return Err(miette::miette!( + "`{name}` isn't fetched yet; run `comline check` to fetch it first" + )); + }; + + ui::step(format!("Checking {name}{}", ui::at_path(work_dir))); + let mut wanted = unverified_in(&dir)?; + if let Some(protocol) = only { + wanted.retain(|p| p.protocol == protocol); + if wanted.is_empty() { + return Err(miette::miette!( + "`{name}` has no unverified protocol `{protocol}`" + )); + } + } + wanted.retain(|p| dependency.accept_unverified.get(&p.protocol) != Some(&p.set)); + if wanted.is_empty() { + ui::success(format!( + "Nothing to accept: {target} is already accepted as it stands" + )); + return Ok(()); + } + + if !decide(name, &wanted, yes, "--yes")? { + ui::note("Not accepted: config.idp is unchanged"); + return Ok(()); + } + + let mut accepted = dependency.accept_unverified.clone(); + for p in &wanted { + accepted.insert(p.protocol.clone(), p.set.clone()); + } + let updated = with_acceptance(&manifest, name, &accepted) + .and_then(|updated| verify(&updated, &declared, name, &accepted).map(|()| updated)) + .map_err(|problem| { + miette::miette!( + "couldn't write the acceptance into config.idp safely ({problem}); add it to \ + `{name}`'s entry by hand:\n accept_unverified = {}", + render(&accepted) + ) + })?; + + // The edit reads back; check it now resolves as the build will. + let mut check = dependency.clone(); + check.accept_unverified = accepted.clone(); + let cache_dir = work_dir.join(DEPS_CACHE_DIR); + quietly(|| deps::resolve(&check, work_dir, &cache_dir)) + .map_err(|e| core_err("the dependency still doesn't resolve", e))?; + + std::fs::write(&manifest_path, updated) + .into_diagnostic() + .wrap_err("failed to write config.idp")?; + let names: Vec<&str> = wanted.iter().map(|p| p.protocol.as_str()).collect(); + ui::success(format!( + "Accepted {} from {name} in config.idp", + names.join(", ") + )); + Ok(()) +} + +/// `manifest` with `name`'s entry carrying `accept_unverified = accepted`, +/// replacing one already there. Every other byte is left as written. +pub fn with_acceptance( + manifest: &str, + name: &str, + accepted: &BTreeMap>, +) -> Result { + let (block_open, block_close) = + dependencies_block(manifest).ok_or("no `dependencies` block")?; + let (entry_open, entry_close) = entry(manifest, block_open, block_close, name) + .ok_or_else(|| format!("no `{name} = {{ ... }}` entry in it"))?; + let line = format!("accept_unverified = {}", render(accepted)); + + if let Some((start, end)) = existing(manifest, entry_open, entry_close) { + return Ok(format!( + "{}{line}{}", + &manifest[..start], + &manifest[end + 1..] + )); + } + + let line_start = manifest[..entry_close].rfind('\n').map_or(0, |i| i + 1); + if manifest[line_start..entry_close].trim().is_empty() { + // `}` on its own line: a new line before it, indented like the fields. + let close_indent = indent_of(manifest, entry_close); + let field_indent = format!("{close_indent}{}", unit(close_indent)); + Ok(format!( + "{}{field_indent}{line}\n{}", + &manifest[..line_start], + &manifest[line_start..] + )) + } else { + // A one-line entry (`a = { path = "../a" }`): keep it on one line. + Ok(format!( + "{} {line} {}", + manifest[..entry_close].trim_end(), + &manifest[entry_close..] + )) + } +} + +/// The `{` and `}` of `name = { ... }` directly inside the block. +fn entry(manifest: &str, open: usize, close: usize, name: &str) -> Option<(usize, usize)> { + let toks: Vec<_> = tokens(manifest) + .into_iter() + .filter(|&(_, at)| at > open && at < close) + .collect(); + let mut depth = 0usize; + for (i, &(token, _)) in toks.iter().enumerate() { + match token { + Token::Open => depth += 1, + Token::Close => depth = depth.saturating_sub(1), + Token::Word(word) if depth == 0 && word == name => { + if let [(Token::Equals, _), (Token::Open, entry_open), ..] = toks[i + 1..] { + return matching(&toks[i + 2..]).map(|entry_close| (entry_open, entry_close)); + } + } + _ => {} + } + } + None +} + +/// The span of an `accept_unverified = { ... }` directly inside an entry: +/// from the key to its closing `}`. +fn existing(manifest: &str, open: usize, close: usize) -> Option<(usize, usize)> { + let toks: Vec<_> = tokens(manifest) + .into_iter() + .filter(|&(_, at)| at > open && at < close) + .collect(); + let mut depth = 0usize; + for (i, &(token, at)) in toks.iter().enumerate() { + match token { + Token::Open => depth += 1, + Token::Close => depth = depth.saturating_sub(1), + Token::Word("accept_unverified") if depth == 0 => { + if let [(Token::Equals, _), (Token::Open, _), ..] = toks[i + 1..] { + return matching(&toks[i + 2..]).map(|end| (at, end)); + } + } + _ => {} + } + } + None +} + +/// Given tokens starting at an opening bracket, the offset of its match. +fn matching(toks: &[(Token<'_>, usize)]) -> Option { + let mut depth = 0usize; + for &(token, at) in toks { + match token { + Token::Open => depth += 1, + Token::Close if depth == 1 => return Some(at), + Token::Close => depth -= 1, + _ => {} + } + } + None +} + +/// Whether `updated` declares the same dependencies as before, with only +/// `name`'s acceptance changed to `accepted`. +fn verify( + updated: &str, + before: &[DependencyConfig], + name: &str, + accepted: &BTreeMap>, +) -> Result<(), String> { + let after = declared_dependencies(updated).map_err(|e| e.to_string())?; + if after.len() != before.len() { + return Err("other entries changed".to_string()); + } + for old in before { + let Some(new) = after.iter().find(|d| d.name == old.name) else { + return Err(format!("`{}` isn't read back", old.name)); + }; + let expected = if old.name == name { + accepted + } else { + &old.accept_unverified + }; + if &new.accept_unverified != expected + || format!("{:?}", new.source) != format!("{:?}", old.source) + { + return Err(format!("`{}` reads back differently", old.name)); + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + const HEAD: &str = "congregation app\nspecification_version = 1\n"; + + fn both() -> BTreeMap> { + BTreeMap::from([( + "Billing".to_string(), + vec![Guarantee::SchemaAgreement, Guarantee::EncodingAgreement], + )]) + } + + fn check(manifest: &str, expected: &str) { + let before = declared_dependencies(manifest).unwrap(); + let updated = with_acceptance(manifest, "billing", &both()).unwrap(); + assert_eq!(updated, expected); + assert_eq!( + verify(&updated, &before, "billing", &both()), + Ok(()), + "{updated}" + ); + } + + #[test] + fn a_line_goes_before_the_entrys_closing_brace() { + check( + &format!("{HEAD}dependencies = {{\n billing = {{\n path = \"../billing\"\n }}\n other = {{\n path = \"../o\"\n }}\n}}\n"), + &format!("{HEAD}dependencies = {{\n billing = {{\n path = \"../billing\"\n accept_unverified = {{ Billing = [\"schema_agreement\", \"encoding_agreement\"] }}\n }}\n other = {{\n path = \"../o\"\n }}\n}}\n"), + ); + } + + #[test] + fn a_one_line_entry_stays_on_one_line() { + check( + &format!("{HEAD}dependencies = {{\n billing = {{ path = \"../billing\" }}\n}}\n"), + &format!("{HEAD}dependencies = {{\n billing = {{ path = \"../billing\" accept_unverified = {{ Billing = [\"schema_agreement\", \"encoding_agreement\"] }} }}\n}}\n"), + ); + } + + #[test] + fn an_existing_acceptance_is_replaced_in_place() { + check( + &format!("{HEAD}dependencies = {{\n billing = {{\n accept_unverified = {{ Billing = [\"schema_agreement\"] }} // old\n path = \"../billing\"\n }}\n}}\n"), + &format!("{HEAD}dependencies = {{\n billing = {{\n accept_unverified = {{ Billing = [\"schema_agreement\", \"encoding_agreement\"] }} // old\n path = \"../billing\"\n }}\n}}\n"), + ); + } + + #[test] + fn a_missing_entry_is_reported() { + let manifest = format!("{HEAD}dependencies = {{\n other = {{ path = \"../o\" }}\n}}\n"); + assert_eq!( + with_acceptance(&manifest, "billing", &both()), + Err("no `billing = { ... }` entry in it".to_string()) + ); + // A key of that name nested deeper isn't the entry. + let nested = format!("{HEAD}dependencies = {{\n other = {{ billing = {{}} }}\n}}\n"); + assert!(with_acceptance(&nested, "billing", &both()).is_err()); + } +} diff --git a/src/commands/add.rs b/src/commands/add.rs index 6faf593..d91e74e 100644 --- a/src/commands/add.rs +++ b/src/commands/add.rs @@ -16,7 +16,7 @@ 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::commands::{accept, core_err, ensure_project}; use crate::ui; /// Where the dependency comes from. @@ -54,7 +54,13 @@ impl Source { } } -pub fn run(work_dir: &Path, name: &str, source: Source, pin: bool) -> Result<()> { +pub fn run( + work_dir: &Path, + name: &str, + source: Source, + pin: bool, + accept_unverified: bool, +) -> Result<()> { ensure_project(work_dir)?; if !is_identifier(name) { return Err(miette::miette!( @@ -121,15 +127,34 @@ pub fn run(work_dir: &Path, name: &str, source: Source, pin: bool) -> Result<()> 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) + let resolve = |dependency: &DependencyConfig| { + accept::quietly(|| deps::resolve(dependency, work_dir, &cache_dir)) }; + let mut resolved = resolve(&dependency); ui::finish_spinner(spinner); + // A dependency with `@unverified` protocols resolves only once they're + // accepted: show what they give up and ask, then try again. + if resolved.is_err() { + let unverified = match dependency.package_dir(work_dir) { + Some(dir) if dir.join("config.idp").exists() => { + accept::unverified_in(&dir).unwrap_or_default() + } + _ => vec![], + }; + if !unverified.is_empty() { + if !accept::decide(name, &unverified, accept_unverified, "--accept-unverified")? { + ui::note(format!("Not accepted: {name} wasn't added")); + return Ok(()); + } + dependency.accept_unverified = unverified + .into_iter() + .map(|p| (p.protocol, p.set)) + .collect(); + resolved = resolve(&dependency); + } + } 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())); @@ -166,7 +191,7 @@ pub fn run(work_dir: &Path, name: &str, source: Source, pin: bool) -> Result<()> Ok(()) } -fn declared_dependencies(manifest: &str) -> Result> { +pub(crate) 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") })?; @@ -202,7 +227,17 @@ fn entry_fields(dependency: &DependencyConfig) -> Result Str } } +/// The key whose value [`entry_fields`] renders itself, unquoted. +const ACCEPT_UNVERIFIED: &str = "accept_unverified"; + 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.extend(fields.iter().map(|(key, value)| match *key { + ACCEPT_UNVERIFIED => format!("{indent}{step}{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)> { +pub(crate) fn dependencies_block(manifest: &str) -> Option<(usize, usize)> { let tokens = tokens(manifest); let mut depth = 0usize; for (i, &(token, _)) in tokens.iter().enumerate() { @@ -302,7 +339,7 @@ fn dependencies_block(manifest: &str) -> Option<(usize, usize)> { } #[derive(Debug, Clone, Copy, PartialEq)] -enum Token<'a> { +pub(crate) enum Token<'a> { Word(&'a str), Equals, /// `{` or `[`. @@ -314,7 +351,7 @@ enum Token<'a> { /// `config.idp`'s tokens with their byte offsets, minus whitespace, comments /// (`//`, `/* */`) and string contents. -fn tokens(text: &str) -> Vec<(Token<'_>, usize)> { +pub(crate) 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'.'); @@ -369,7 +406,7 @@ fn tokens(text: &str) -> Vec<(Token<'_>, usize)> { } /// The leading whitespace of the line `at` is on. -fn indent_of(text: &str, at: usize) -> &str { +pub(crate) 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()] @@ -377,7 +414,7 @@ fn indent_of(text: &str, at: usize) -> &str { /// 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 { +pub(crate) fn unit(indent: &str) -> &'static str { if indent.starts_with('\t') { "\t" } else { @@ -423,7 +460,10 @@ fn verify( ) => (va, ua, ca) == (vb, ub, cb), _ => false, }; - match same && added.declared_hash() == dependency.declared_hash() { + match same + && added.declared_hash() == dependency.declared_hash() + && added.accept_unverified == dependency.accept_unverified + { true => Ok(()), false => Err("the entry reads back differently".to_string()), } diff --git a/src/commands/mod.rs b/src/commands/mod.rs index 9a96463..ebb0e0a 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 accept; pub mod add; pub mod build; pub mod check; diff --git a/src/error.rs b/src/error.rs index 38e26bb..8215c1d 100644 --- a/src/error.rs +++ b/src/error.rs @@ -35,6 +35,12 @@ pub enum CliError { #[error("refusing to delete the version history without confirmation")] #[diagnostic(help("re-run in a terminal to confirm, or pass `--force`"))] ConfirmationRequired, + + #[error( + "refusing to accept unverified protocols without confirmation: re-run in a terminal \ + to be asked, or pass `{flag}` to accept them" + )] + AcceptanceRequired { flag: &'static str }, } /// Map a finished-command error to its process exit code. @@ -43,6 +49,7 @@ pub fn exit_code_for(report: &miette::Report) -> i32 { Some(CliError::NotAProject(_)) => EXIT_PRECONDITION, Some(CliError::NothingBuilt(_)) => EXIT_PRECONDITION, Some(CliError::ConfirmationRequired) => EXIT_PRECONDITION, + Some(CliError::AcceptanceRequired { .. }) => EXIT_PRECONDITION, None => EXIT_FAILURE, } } diff --git a/src/main.rs b/src/main.rs index 7048053..d61ab30 100644 --- a/src/main.rs +++ b/src/main.rs @@ -154,10 +154,12 @@ fn run(cli: Cli) -> Result<()> { commit, version, no_hash, + accept_unverified, } => { let source = commands::add::Source::from_args(dir, git, commit, version)?; - commands::add::run(&work_dir, &name, source, !no_hash) + commands::add::run(&work_dir, &name, source, !no_hash, accept_unverified) } + Commands::Accept { target, yes } => commands::accept::run(&work_dir, &target, yes), Commands::Completions { shell } => commands::completions::run(shell), Commands::Targets { features, json } => commands::targets::run(features, json), } diff --git a/tests/cli/accept.rs b/tests/cli/accept.rs new file mode 100644 index 0000000..6a02a24 --- /dev/null +++ b/tests/cli/accept.rs @@ -0,0 +1,140 @@ +//! `comline accept`, and `comline add` on a dependency with `@unverified` +//! protocols. + +use std::fs; +use std::path::Path; + +use predicates::prelude::*; + +use crate::util::*; + +const PRECONDITION: i32 = 2; + +/// A package at `dir` whose listed protocols run no handshake, each marked. +fn write_unverified_package(dir: &Path, protocols: &[&str]) { + fs::create_dir_all(dir.join("src")).unwrap(); + fs::write( + dir.join("config.idp"), + "congregation billing\nspecification_version = 1\n\ + settings = { annotations = { unverified = { allowed = true } } }\n", + ) + .unwrap(); + let schema: String = protocols + .iter() + .map(|p| { + format!( + "@handshake = \"none\"\n@unverified = \"the 2009 gateway\"\n\ + protocol {p} {{\n function ping();\n}}\n\n" + ) + }) + .collect(); + fs::write(dir.join("src/api.ids"), schema).unwrap(); +} + +fn comline(project: &Path, args: &[&str]) -> assert_cmd::assert::Assert { + comline_cmd().current_dir(project).args(args).assert() +} + +#[test] +fn add_shows_what_is_given_up_and_needs_it_accepted() { + let temp = tempfile::tempdir().unwrap(); + let project = fixture_project(temp.path()); + write_unverified_package(&temp.path().join("billing"), &["Billing"]); + let before = fs::read_to_string(project.join("config.idp")).unwrap(); + + // No terminal to ask: refused, with what it gives up and the way through. + comline(&project, &["add", "billing", "../billing"]) + .failure() + .code(PRECONDITION) + .stderr(predicate::str::contains( + "Billing gives up schema agreement and encoding agreement: \"the 2009 gateway\"", + )) + .stderr(predicate::str::contains("--accept-unverified")); + assert_eq!( + fs::read_to_string(project.join("config.idp")).unwrap(), + before + ); + + comline( + &project, + &["add", "billing", "../billing", "--accept-unverified"], + ) + .success() + .stderr(predicate::str::contains("Added billing to config.idp")); + let after = fs::read_to_string(project.join("config.idp")).unwrap(); + assert!( + after.contains( + " accept_unverified = { Billing = [\"schema_agreement\", \"encoding_agreement\"] }\n" + ), + "{after}" + ); + comline(&project, &["check"]).success(); +} + +#[test] +fn accept_takes_in_what_an_update_gives_up() { + let temp = tempfile::tempdir().unwrap(); + let project = fixture_project(temp.path()); + let billing = temp.path().join("billing"); + write_unverified_package(&billing, &["Billing"]); + comline( + &project, + &[ + "add", + "billing", + "../billing", + "--no-hash", + "--accept-unverified", + ], + ) + .success(); + + // The dependency now gives up more: the build stops until it's accepted. + write_unverified_package(&billing, &["Billing", "Ledger"]); + comline(&project, &["check"]) + .failure() + .stderr(predicate::str::contains("protocol `Ledger` is unverified")); + + comline(&project, &["accept", "billing"]) + .failure() + .code(PRECONDITION) + .stderr(predicate::str::contains("Ledger gives up")) + .stderr(predicate::str::contains("Billing gives up").not()) + .stderr(predicate::str::contains("--yes")); + + comline(&project, &["accept", "billing", "--yes"]) + .success() + .stderr(predicate::str::contains("Accepted Ledger from billing")); + let manifest = fs::read_to_string(project.join("config.idp")).unwrap(); + assert!( + manifest.contains( + "accept_unverified = { Billing = [\"schema_agreement\", \"encoding_agreement\"] \ + Ledger = [\"schema_agreement\", \"encoding_agreement\"] }" + ), + "{manifest}" + ); + comline(&project, &["check"]).success(); + + comline(&project, &["accept", "billing::Ledger", "--yes"]) + .success() + .stderr(predicate::str::contains("Nothing to accept")); +} + +#[test] +fn accept_refuses_what_it_cant_find() { + let temp = tempfile::tempdir().unwrap(); + let project = fixture_project(temp.path()); + write_unverified_package(&temp.path().join("billing"), &["Billing"]); + comline( + &project, + &["add", "billing", "../billing", "--accept-unverified"], + ) + .success(); + + comline(&project, &["accept", "nope", "--yes"]) + .failure() + .stderr(predicate::str::contains("`nope` isn't a dependency")); + comline(&project, &["accept", "billing::Nope", "--yes"]) + .failure() + .stderr(predicate::str::contains("no unverified protocol `Nope`")); +} diff --git a/tests/cli/main.rs b/tests/cli/main.rs index ec10c66..d530fc7 100644 --- a/tests/cli/main.rs +++ b/tests/cli/main.rs @@ -6,6 +6,7 @@ mod util; +mod accept; mod add; mod build; mod check;