Incremental engine for long horizon agents π Star if you like it!
Rust agentic-data-frameworkaiai-agentschange-data-capturecodebase-intelligencecontext-engineeringdata-engineeringdata-indexingdata-processingetlhelp-wantedindexingknowledge-graphllmlong-horizon-agentpythonragreal-timerustsemantic-search
fix(cli): show cargo's compile errors, and exit 1 when no app matches (#2788)
LJ π₯₯π΄76346b00f9d2
diff --git a/rust/cli/src/build.rs b/rust/cli/src/build.rsindex 6ba42ed7..6e736c87 100644--- a/rust/cli/src/build.rs+++ b/rust/cli/src/build.rs@@ -4,6 +4,7 @@ use std::path::{Path, PathBuf};use std::process::Stdio;use serde::Deserialize;+use tokio::io::AsyncReadExt as _;use crate::error::{CliError, CliResult, fail};@@ -94,10 +95,21 @@ pub async fn build(manifest: &Path, opts: &BuildOpts) -> CliResult<PathBuf> {cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::inherit());- let output = cmd.output().await.map_err(fail("could not run cargo"))?;- let stdout = String::from_utf8_lossy(&output.stdout);+ // Not `cmd.output()`: tokio's `output` pipes stderr too, overriding the+ // `inherit` above, which would swallow cargo's compile errors.+ let mut child = cmd.spawn().map_err(fail("could not run cargo"))?;+ let mut stdout = Vec::new();+ child+ .stdout+ .take()+ .expect("cargo's stdout is piped")+ .read_to_end(&mut stdout)+ .await+ .map_err(fail("reading cargo's output"))?;+ let status = child.wait().await.map_err(fail("waiting for cargo"))?;+ let stdout = String::from_utf8_lossy(&stdout);let (artifacts, finished_ok) = parse_messages(&stdout);- if !output.status.success() || finished_ok == Some(false) {+ if !status.success() || finished_ok == Some(false) {return Err(CliError::failure(format!("building {} failed",manifest.display()diff --git a/rust/cli/src/commands.rs b/rust/cli/src/commands.rsindex 9dd8bd6f..8fd5d871 100644--- a/rust/cli/src/commands.rs+++ b/rust/cli/src/commands.rs@@ -48,7 +48,7 @@ fn pick_app(requested: Option<&str>, apps: &[AppInfo]) -> CliResult<AppInfo> {.find(|a| a.name == name).cloned().ok_or_else(|| {- CliError::usage(format!(+ CliError::failure(format!("No app named '{name}'. Available apps: {}",app_names(apps.iter().filter(usable))))@@ -57,10 +57,10 @@ fn pick_app(requested: Option<&str>, apps: &[AppInfo]) -> CliResult<AppInfo> {let registered: Vec<&AppInfo> = apps.iter().filter(|a| a.registered).collect();match registered.as_slice() {[one] => Ok((*one).clone()),- [] => Err(CliError::usage(+ [] => Err(CliError::failure("No apps found in the target binary. Make sure it has a #[cocoindex::app] function.",)),- many => Err(CliError::usage(format!(+ many => Err(CliError::failure(format!("Multiple apps found: {}. Please specify which app to use with ':app_name' syntax.",app_names(many.iter().copied())))),@@ -116,7 +116,7 @@ pub async fn ls(target: Option<String>, db: Option<PathBuf>, build: BuildOpts) -(None, None) => match std::env::var_os(DB_PATH_ENV) {Some(db) => Some(PathBuf::from(db)),None => {- return Err(CliError::usage(+ return Err(CliError::failure("Please specify either APP_TARGET or --db option (or set COCOINDEX_DB environment variable).\n \cocoindex ls ./my_crate # List apps of a crate\n \cocoindex ls --db ./my.db # List apps from database",@@ -132,7 +132,7 @@ pub async fn ls(target: Option<String>, db: Option<PathBuf>, build: BuildOpts) -if names.is_empty() {println!("No persisted apps found in the database.");} else {- println!("{}:", db.display());+ println!("{}:", format_db_path(&db.display().to_string()));for name in names {println!(" {name}");}@@ -206,20 +206,20 @@ pub async fn show(args: ShowArgs) -> CliResult<()> {second.clone()};if (mode.recursive || mode.parents) && stable_path.is_none() {- return Err(CliError::usage(+ return Err(CliError::failure("-r/--recursive and -p/--parents require a stable_path argument.",));}if mode.target_states && (stable_path.is_some() || mode.long || mode.recursive || mode.parents){- return Err(CliError::usage(+ return Err(CliError::failure("--target-states cannot be combined with stable_path, -l, -r or -p.",));}let (db_path, app) = if db_mode {let (Some(db), Some(app)) = (db, app_name) else {- return Err(CliError::usage(+ return Err(CliError::failure("Both --db and --app-name are required when APP_TARGET is not specified.",));};@@ -516,7 +516,7 @@ mod tests {fn several_apps_need_a_name() {let apps = vec![app("A", true, false), app("B", true, true)];let err = pick_app(None, &apps).unwrap_err();- assert_eq!(err.code, 2);+ assert_eq!(err.code, 1);assert!(err.message.contains("Multiple apps found: A, B"));let err = pick_app(None, &[]).unwrap_err();assert!(err.message.contains("No apps found"));diff --git a/rust/cli/src/error.rs b/rust/cli/src/error.rsindex 7ea02aad..ddb94361 100644--- a/rust/cli/src/error.rs+++ b/rust/cli/src/error.rs@@ -1,5 +1,9 @@//! CLI errors carry the process exit code: 1 for failures, 2 for usage and//! protocol errors (the same codes as the Python CLI and the protocol child).+//! As in the Python CLI, a usage error is a malformed command line (options+//! that cannot go together, a TARGET that does not exist); an app that is not+//! found, or a combination of arguments checked after parsing, is a failure,+//! like Python's `click.ClickException`.use std::fmt::Display;diff --git a/rust/cli/tests/e2e.rs b/rust/cli/tests/e2e.rsindex 50e8352a..b3a36aa2 100644--- a/rust/cli/tests/e2e.rs+++ b/rust/cli/tests/e2e.rs@@ -200,7 +200,8 @@ fn update_preview_ls_show_drop() {let ls_db = sb.cli(&["ls", "--db", &sb.db()]);assert_ok(&ls_db);- assert_eq!(stdout(&ls_db), format!("{}:\n FixtureApp\n", sb.db()));+ // Inside the working directory, the path shows relative, as in Python.+ assert_eq!(stdout(&ls_db), "./db:\n FixtureApp\n");// show, straight from the db.let show = sb.cli(&["show", "--db", &sb.db(), "--app-name", "FixtureApp"]);@@ -402,17 +403,19 @@ fn usage_errors() {assert_eq!(no_db.status.code(), Some(1));assert!(stderr(&no_db).contains("Database path does not exist"));+ // Checks after parsing, and an app that is not found, are failures (exit+ // 1), as the Python CLI's `click.ClickException`s are.let recursive = sb.cli(&["show", "-r", "--db", "x", "--app-name", "y"]);- assert_eq!(recursive.status.code(), Some(2));+ assert_eq!(recursive.status.code(), Some(1));assert!(stderr(&recursive).contains("require a stable_path"));let half = sb.cli(&["show", "--db", "x"]);- assert_eq!(half.status.code(), Some(2));+ assert_eq!(half.status.code(), Some(1));assert!(stderr(&half).contains("Both --db and --app-name are required"));// Two apps and no name.let ambiguous = sb.cli(&["update", FIXTURE]);- assert_eq!(ambiguous.status.code(), Some(2));+ assert_eq!(ambiguous.status.code(), Some(1));assert!(stderr(&ambiguous).contains("FixtureApp, never_run"),"{}",@@ -420,7 +423,7 @@ fn usage_errors() {);let unknown = sb.cli(&["update", &exe_target("Nope")]);- assert_eq!(unknown.status.code(), Some(2));+ assert_eq!(unknown.status.code(), Some(1));assert!(stderr(&unknown).contains("Nope"));}@@ -676,3 +679,62 @@ fn google_drive_sign_in_and_sign_out() {assert!(stdout(&out).contains("Signed out."), "{}", stdout(&out));assert!(!token.exists());}++/// `--full-reprocess` bypasses the memo, `--fingerprints` shows stored+/// target-state paths raw, and `--preview` refuses `--live`.+#[test]+fn full_reprocess_fingerprints_and_preview_live() {+ let sb = Sandbox::new(&[("a.txt", "alpha"), ("b.txt", "beta")]);+ assert_ok(&sb.cli(&["update", &exe_target("FixtureApp")]));+ let again = sb.cli(&["update", &exe_target("FixtureApp")]);+ assert!(stdout(&again).contains("2 unchanged"), "{}", stdout(&again));++ let full = sb.cli(&["update", "--full-reprocess", &exe_target("FixtureApp")]);+ assert_ok(&full);+ assert!(+ !stdout(&full).contains("unchanged"),+ "a full reprocess skips nothing: {}",+ stdout(&full)+ );+ assert_eq!(sb.out_files(), ["a.txt", "b.txt"]);++ let raw = sb.cli(&[+ "show",+ "--db",+ &sb.db(),+ "--app-name",+ "FixtureApp",+ "--target-states",+ "--fingerprints",+ ]);+ assert_ok(&raw);+ let text = stdout(&raw);+ assert!(text.starts_with("Target states:\n"), "{text}");+ assert!(+ !text.contains("localfs/file/["),+ "raw paths, not readable keys: {text}"+ );+ assert_eq!(text.matches("owner:/").count(), 2, "{text}");++ let both = sb.cli(&["update", "--preview", "-L", &exe_target("FixtureApp")]);+ assert_eq!(both.status.code(), Some(2));+ assert!(stderr(&both).contains("--preview and --live cannot be used together."));+}++/// A crate that does not compile fails with exit 1 (as the Python CLI does+/// for a module that does not import), with cargo's diagnostics on stderr.+#[test]+fn a_crate_that_does_not_build_fails() {+ let sb = Sandbox::new(&[("main.rs", "fn main() { let x: u32 = \"not a number\"; }\n")]);+ std::fs::write(+ sb.path("Cargo.toml"),+ "[package]\nname = \"broken_crate\"\nversion = \"0.1.0\"\nedition = \"2021\"\n\n[workspace]\n",+ )+ .unwrap();+ let crate_dir = sb.path("").display().to_string();+ let output = sb.cli(&["update", &crate_dir]);+ assert_eq!(output.status.code(), Some(1));+ let err = stderr(&output);+ assert!(err.contains("mismatched types"), "{err}");+ assert!(err.contains("failed"), "{err}");+}diff --git a/rust/sdk/cocoindex/src/cli/mod.rs b/rust/sdk/cocoindex/src/cli/mod.rsindex 387d703d..8ca21a1c 100644--- a/rust/sdk/cocoindex/src/cli/mod.rs+++ b/rust/sdk/cocoindex/src/cli/mod.rs@@ -96,8 +96,7 @@ pub async fn dispatch_to(args: Vec<String>, out: &mut (dyn Write + Send)) -> Exi};match outcome {Ok(code) => ExitCode::from(code),- Err(Failure::Usage(message)) => emitter.fail(message, EXIT_USAGE),- Err(Failure::Error(err)) => emitter.fail(err.to_string(), EXIT_ERROR),+ Err(err) => emitter.fail(err.to_string(), EXIT_ERROR),}}@@ -209,17 +208,6 @@ fn verb_name(verb: Verb) -> &'static str {// Verbs// ----------------------------------------------------------------------------enum Failure {- Usage(String),- Error(Error),-}--impl From<Error> for Failure {- fn from(err: Error) -> Self {- Failure::Error(err)- }-}-struct Emitter<'a> {out: &'a mut (dyn Write + Send),/// Set once a record could not be written.@@ -256,21 +244,18 @@ impl Emitter<'_> {}}-async fn open_environment() -> std::result::Result<Environment, Failure> {- Ok(Environment::from_registered().await?)+async fn open_environment() -> Result<Environment> {+ Environment::from_registered().await}-async fn run_ls(emitter: &mut Emitter<'_>) -> std::result::Result<u8, Failure> {+async fn run_ls(emitter: &mut Emitter<'_>) -> Result<u8> {let env = open_environment().await?;let outcome = list_apps(emitter, &env).await;env.shutdown().await;outcome}-async fn list_apps(- emitter: &mut Emitter<'_>,- env: &Environment,-) -> std::result::Result<u8, Failure> {+async fn list_apps(emitter: &mut Emitter<'_>, env: &Environment) -> Result<u8> {let persisted = env.persisted_app_names().await?;let mut apps: Vec<AppInfo> = registry::apps().iter()@@ -298,22 +283,21 @@ async fn list_apps(}/// The app an `update`/`drop` acts on: `--app NAME`, else the binary's only-/// registered app.-fn resolve_app(requested: Option<&str>) -> std::result::Result<&'static AppEntry, Failure> {+/// registered app. A name that matches nothing, or several apps and no name,+/// is a failure (exit 1), like the Python CLI's `ClickException`.+fn resolve_app(requested: Option<&str>) -> Result<&'static AppEntry> {let apps = registry::apps();match requested {Some(name) => registry::find_app(name).ok_or_else(|| {- Failure::Usage(format!(+ Error::engine(format!("no #[cocoindex::app] named `{name}` in this binary; available: {}",app_names(apps)))}),None => match apps {[only] => Ok(only),- [] => Err(Failure::Usage(- "this binary has no #[cocoindex::app]".to_string(),- )),- many => Err(Failure::Usage(format!(+ [] => Err(Error::engine("this binary has no #[cocoindex::app]")),+ many => Err(Error::engine(format!("this binary has several apps; pass the name: {}",app_names(many)))),@@ -366,19 +350,16 @@ fn emit_done(emitter: &mut Emitter<'_>, outcome: Outcome, stats: Option<RunStatsemitter.emit(&Event::Done { outcome, stats });}-fn emit_cancelled(emitter: &mut Emitter<'_>) -> std::result::Result<u8, Failure> {+fn emit_cancelled(emitter: &mut Emitter<'_>) -> Result<u8> {emit_done(emitter, Outcome::Cancelled, None);Ok(EXIT_OK)}/// A failed step after Ctrl-C is the cancellation surfacing (the engine/// reports a cancelled operation as an error), not a failure.-fn cancel_or(- emitter: &mut Emitter<'_>,- outcome: std::result::Result<u8, Failure>,-) -> std::result::Result<u8, Failure> {+fn cancel_or(emitter: &mut Emitter<'_>, outcome: Result<u8>) -> Result<u8> {match outcome {- Err(Failure::Error(_)) if cancelled() => emit_cancelled(emitter),+ Err(_) if cancelled() => emit_cancelled(emitter),other => other,}}@@ -410,10 +391,7 @@ async fn confirm(emitter: &mut Emitter<'_>, action: ConfirmAction, app: &str) ->}}-async fn run_update(- emitter: &mut Emitter<'_>,- args: &ChildArgs,-) -> std::result::Result<u8, Failure> {+async fn run_update(emitter: &mut Emitter<'_>, args: &ChildArgs) -> Result<u8> {let entry = resolve_app(args.app.as_deref())?;arm_cancellation();let Some(env) = until_cancelled(open_environment()).await else {@@ -434,7 +412,7 @@ async fn update_app(args: &ChildArgs,entry: &'static AppEntry,env: &Environment,-) -> std::result::Result<u8, Failure> {+) -> Result<u8> {let app = env.app(entry.name).await?;if args.reset&& env@@ -489,7 +467,7 @@ async fn update_app(Ok(EXIT_OK)}-async fn run_drop(emitter: &mut Emitter<'_>, args: &ChildArgs) -> std::result::Result<u8, Failure> {+async fn run_drop(emitter: &mut Emitter<'_>, args: &ChildArgs) -> Result<u8> {arm_cancellation();let Some(env) = until_cancelled(open_environment()).await else {return emit_cancelled(emitter);@@ -500,11 +478,7 @@ async fn run_drop(emitter: &mut Emitter<'_>, args: &ChildArgs) -> std::result::Rcancel_or(emitter, outcome)}-async fn drop_app(- emitter: &mut Emitter<'_>,- args: &ChildArgs,- env: &Environment,-) -> std::result::Result<u8, Failure> {+async fn drop_app(emitter: &mut Emitter<'_>, args: &ChildArgs, env: &Environment) -> Result<u8> {let persisted = env.persisted_app_names().await?;// A persisted app whose code is gone can still be dropped by name.let name: String = match &args.app {diff --git a/rust/sdk/cocoindex/tests/registered.rs b/rust/sdk/cocoindex/tests/registered.rsindex 69db0741..7bb96ced 100644--- a/rust/sdk/cocoindex/tests/registered.rs+++ b/rust/sdk/cocoindex/tests/registered.rs@@ -180,12 +180,12 @@ async fn registered_lifespan_apps_and_protocol() {}assert_eq!(std::fs::read_dir(&out).unwrap().count(), 5);- // --- protocol: errors are usage errors ----------------------------------+ // --- protocol: an app that is not found is a failure (exit 1) ----------let (code, events, _) = child(&["update", "--protocol", "1", "--app", "Nope"]).await;- assert_eq!(code, ExitCode::from(2));+ assert_eq!(code, ExitCode::from(1));assert!(matches!(events.last(), Some(Event::Error { message }) if message.contains("Nope")));let (code, _, _) = child(&["update", "--protocol", "1"]).await;- assert_eq!(code, ExitCode::from(2), "two apps: the name is required");+ assert_eq!(code, ExitCode::from(1), "two apps: the name is required");// --- protocol: drop ------------------------------------------------------let (code, events, _) = child(&["drop", "--protocol", "1", "--app", "app_two"]).await;