Skip to main content

astrs_cli/command/
hub.rs

1//! `astrs hub` — the local client for the AstRS package index (blueprint
2//! §22's "hub/package index"), pulled forward from the 0.2.0 roadmap into
3//! this release.
4//!
5//! ```text
6//!   astrs hub init <dir>     scaffold a self-hostable index repo layout
7//!   astrs hub update         clone/pull the index repo into the local cache
8//!   astrs hub search <term>  list packages whose name/description match
9//!   astrs hub info <name>    show one package's published versions
10//! ```
11//!
12//! # What this module does *not* do
13//!
14//! Resolving a manifest's `hub:` source into a `git clone`/`checkout` pair
15//! — reading the very index this module manages — is
16//! `astrs_coordinator::hub_index`'s job, called from
17//! `astrs_coordinator::graph_bridge` at dataflow-start time, not from here:
18//! a standalone `astrs coordinator` process (never running any CLI verb at
19//! all) resolves `hub:` sources for manifests submitted to it over the
20//! wire, so the resolution logic cannot live behind a CLI-only module. This
21//! module and that one agree on exactly one thing —
22//! [`astrs_coordinator::hub_index::cache_dir_from_env`], the local index
23//! clone's location — which is why `update` clones/pulls into precisely
24//! that directory rather than computing its own.
25//!
26//! # Index URL resolution
27//!
28//! [`resolve_index_url`]: an explicit `--index` argument, then
29//! [`astrs_coordinator::hub_index::ENV_HUB_INDEX`], then the `[hub] index`
30//! key of the config file at [`default_config_path`], then
31//! [`astrs_coordinator::hub_index::DEFAULT_INDEX_URL`] — which may not
32//! exist yet (this is a roadmap item pulled forward), so `update` against
33//! it fails with the system `git` binary's own clear "repository not
34//! found" message rather than anything this module invents.
35
36use std::io::Write;
37use std::path::{Path, PathBuf};
38use std::process::Command;
39
40use astrs_coordinator::CoordinatorError;
41use astrs_coordinator::hub_index::{self, IndexPackage};
42use serde::Deserialize;
43
44use crate::error::CliError;
45
46/// The file name a `[hub]` section is read from, under [`default_config_path`].
47pub const CONFIG_FILE_NAME: &str = "config.toml";
48
49/// The `README.md` an `astrs hub init` scaffold gets, explaining the
50/// layout well enough that a self-hoster does not need to re-read this
51/// module's docs.
52const INDEX_README: &str = "\
53# AstRS package index
54
55A minimal, git-hosted index for `hub:` manifest sources (blueprint §22).
56
57## Layout
58
59    packages/<name>.json
60
61Each file is one package:
62
63```json
64{
65  \"name\": \"yolo-detector\",
66  \"description\": \"A YOLO-family object detector node.\",
67  \"versions\": [
68    { \"version\": \"v0.3.0\", \"git\": \"https://example.invalid/yolo\", \"rev\": \"a1b2c3d\" },
69    { \"version\": \"v0.3.1\", \"git\": \"https://example.invalid/yolo\", \"rev\": \"d4e5f6a\", \"subdir\": \"nodes/yolo\" }
70  ]
71}
72```
73
74`versions` is append-only, oldest first: publishing a new version means
75appending an entry, never rewriting one already there. `hub: <name>` with
76no `@rev` resolves to the last (newest) entry; `hub: <name>@<version>`
77must match a `version` string exactly.
78
79`rev` is the exact git commit/tag/branch that `version` resolves to —
80always required, so a published version stays reproducible even if a
81branch it once pointed at moves on. `subdir` is optional: the package's
82own directory within `git`, for a repository that hosts more than one
83package. Leave it out when the whole repository *is* the package.
84
85## Publishing
86
87Add or edit a `packages/<name>.json` file, commit, and push. Anyone
88running `astrs hub update` against this repository's URL picks up the
89change on their next update.
90";
91
92/// Where `astrs hub`'s config file lives, honoring `XDG_CONFIG_HOME` first.
93///
94/// Falls back to `$HOME/.config/astrs/config.toml`, then a fixed name
95/// under [`std::env::temp_dir`] — the same shape
96/// [`hub_index::cache_dir_from_env`] uses for the index cache itself.
97#[must_use]
98pub fn default_config_path() -> PathBuf {
99    if let Some(xdg) = non_empty_var("XDG_CONFIG_HOME") {
100        return PathBuf::from(xdg).join("astrs").join(CONFIG_FILE_NAME);
101    }
102    if let Some(home) = non_empty_var("HOME") {
103        return PathBuf::from(home)
104            .join(".config")
105            .join("astrs")
106            .join(CONFIG_FILE_NAME);
107    }
108    std::env::temp_dir().join(format!("astrs-{CONFIG_FILE_NAME}"))
109}
110
111fn non_empty_var(name: &str) -> Option<String> {
112    std::env::var(name).ok().filter(|value| !value.is_empty())
113}
114
115/// The `[hub]` section of `astrs`'s config file — the only section this
116/// release reads or writes.
117#[derive(Debug, Default, Deserialize)]
118struct ConfigFile {
119    #[serde(default)]
120    hub: Option<HubConfigSection>,
121}
122
123/// The `[hub]` section itself.
124#[derive(Debug, Default, Deserialize)]
125struct HubConfigSection {
126    #[serde(default)]
127    index: Option<String>,
128}
129
130/// Reads the `[hub] index` key from the config file at `path`.
131///
132/// A missing file is not an error (§22's config-file key is optional, one
133/// of three ways to name an index URL) — only a *present but unparsable*
134/// file is.
135///
136/// # Errors
137///
138/// [`CliError::Coordinator`] if `path` exists but is not valid TOML, or
139/// does not match [`ConfigFile`]'s shape.
140fn read_config_index(path: &Path) -> Result<Option<String>, CliError> {
141    let text = match std::fs::read_to_string(path) {
142        Ok(text) => text,
143        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
144        Err(source) => return Err(CliError::io(path, source)),
145    };
146    let config: ConfigFile = toml::from_str(&text).map_err(|source| {
147        CoordinatorError::invalid(format!("`{}` is not valid TOML: {source}", path.display()))
148    })?;
149    Ok(config.hub.and_then(|hub| hub.index))
150}
151
152/// Resolves the index repository URL: `explicit` (an `astrs hub update
153/// --index` argument), then [`hub_index::ENV_HUB_INDEX`], then the `[hub]
154/// index` key of the config file at `config_path`, then
155/// [`hub_index::DEFAULT_INDEX_URL`].
156///
157/// # Errors
158///
159/// As `read_config_index`, this module's own private config-file reader.
160pub fn resolve_index_url(explicit: Option<&str>, config_path: &Path) -> Result<String, CliError> {
161    if let Some(explicit) = explicit {
162        return Ok(explicit.to_owned());
163    }
164    if let Ok(env) = std::env::var(hub_index::ENV_HUB_INDEX)
165        && !env.trim().is_empty()
166    {
167        return Ok(env);
168    }
169    if let Some(from_config) = read_config_index(config_path)? {
170        return Ok(from_config);
171    }
172    Ok(hub_index::DEFAULT_INDEX_URL.to_owned())
173}
174
175/// Runs the system `git` binary (blueprint §2.2: shell out, never
176/// `git2`/`libgit2`) and returns its stdout.
177///
178/// # Errors
179///
180/// [`CliError::Coordinator`] if `git` cannot be spawned at all (not
181/// installed, not on `PATH`), or exits non-zero — its stderr, trimmed, is
182/// folded into the message so the failure is actionable without
183/// re-running the command by hand.
184fn run_git(working_dir: Option<&Path>, args: &[&str]) -> Result<String, CliError> {
185    let mut command = Command::new("git");
186    command.args(args);
187    if let Some(dir) = working_dir {
188        command.current_dir(dir);
189    }
190    let output = command.output().map_err(|source| {
191        CoordinatorError::invalid(format!(
192            "could not run the system `git` binary (is it installed and on `PATH`?): {source}"
193        ))
194    })?;
195    if !output.status.success() {
196        let stderr = String::from_utf8_lossy(&output.stderr);
197        return Err(CoordinatorError::invalid(format!(
198            "`git {}` failed: {}",
199            args.join(" "),
200            stderr.trim()
201        ))
202        .into());
203    }
204    Ok(String::from_utf8_lossy(&output.stdout).into_owned())
205}
206
207/// Counts `packages/*.json` entries under a local index clone, for
208/// [`UpdateReport`] — best-effort: a cache directory that turns out not to
209/// have a readable `packages/` at all just counts as zero rather than
210/// failing an update that otherwise succeeded.
211fn count_packages(cache_dir: &Path) -> usize {
212    std::fs::read_dir(cache_dir.join("packages"))
213        .map(|entries| {
214            entries
215                .filter_map(Result::ok)
216                .filter(|entry| {
217                    entry.path().extension().and_then(std::ffi::OsStr::to_str) == Some("json")
218                })
219                .count()
220        })
221        .unwrap_or(0)
222}
223
224/// `astrs hub update` arguments, independent of `clap`.
225#[derive(Debug, Clone, Default)]
226pub struct UpdateArgs {
227    /// An explicit index URL, overriding the environment/config-file/
228    /// default resolution (see [`resolve_index_url`]).
229    pub index: Option<String>,
230    /// The local index clone's directory. `None` resolves through
231    /// [`hub_index::cache_dir_from_env`] — overridable here mainly for
232    /// tests, which never touch the real cache directory.
233    pub cache_dir: Option<PathBuf>,
234    /// The config file [`resolve_index_url`] reads. `None` resolves
235    /// through [`default_config_path`] — same rationale as `cache_dir`.
236    pub config_path: Option<PathBuf>,
237    /// Emit JSON rather than a human-readable summary.
238    pub json: bool,
239}
240
241/// What `astrs hub update` did.
242#[derive(Debug, Clone, PartialEq, Eq)]
243pub struct UpdateReport {
244    /// The index URL that was cloned or pulled.
245    pub index_url: String,
246    /// The local directory it was cloned/pulled into.
247    pub cache_dir: PathBuf,
248    /// `true` for a fresh clone, `false` for a pull against an existing
249    /// clone.
250    pub cloned: bool,
251    /// How many `packages/*.json` entries the index has after updating.
252    pub package_count: usize,
253}
254
255/// Clones the index repository if the local cache does not have it yet,
256/// or fast-forward pulls it if it does.
257///
258/// # Errors
259///
260/// - As [`resolve_index_url`].
261/// - [`CliError::Coordinator`] if `git clone`/`git pull --ff-only` fails —
262///   including "repository not found", the expected failure against
263///   [`hub_index::DEFAULT_INDEX_URL`] before it exists.
264/// - [`CliError::Io`] if the cache directory's parent cannot be created.
265pub fn update(out: &mut dyn Write, args: &UpdateArgs) -> Result<UpdateReport, CliError> {
266    let cache_dir = args
267        .cache_dir
268        .clone()
269        .unwrap_or_else(hub_index::cache_dir_from_env);
270    let config_path = args.config_path.clone().unwrap_or_else(default_config_path);
271    let index_url = resolve_index_url(args.index.as_deref(), &config_path)?;
272
273    let cloned = !cache_dir.join(".git").is_dir();
274    if cloned {
275        if let Some(parent) = cache_dir.parent()
276            && !parent.as_os_str().is_empty()
277        {
278            std::fs::create_dir_all(parent).map_err(|source| CliError::io(parent, source))?;
279        }
280        let cache_dir_text = cache_dir.display().to_string();
281        run_git(None, &["clone", &index_url, &cache_dir_text])?;
282    } else {
283        run_git(Some(&cache_dir), &["pull", "--ff-only"])?;
284    }
285
286    let report = UpdateReport {
287        index_url,
288        package_count: count_packages(&cache_dir),
289        cache_dir,
290        cloned,
291    };
292    print_update_report(out, args.json, &report);
293    Ok(report)
294}
295
296fn print_update_report(out: &mut dyn Write, json: bool, report: &UpdateReport) {
297    if json {
298        emit_json(
299            out,
300            &serde_json::json!({
301                "index_url": report.index_url,
302                "cache_dir": report.cache_dir.display().to_string(),
303                "cloned": report.cloned,
304                "package_count": report.package_count,
305            }),
306        );
307        return;
308    }
309    let verb = if report.cloned { "cloned" } else { "updated" };
310    let _ = writeln!(
311        out,
312        "{verb} {} into {} ({} package{})",
313        report.index_url,
314        report.cache_dir.display(),
315        report.package_count,
316        if report.package_count == 1 { "" } else { "s" }
317    );
318    let _ = out.flush();
319}
320
321/// `astrs hub search` arguments, independent of `clap`.
322#[derive(Debug, Clone)]
323pub struct SearchArgs {
324    /// The term to match against a package's name or description
325    /// (case-insensitive); an empty term matches every package.
326    pub term: String,
327    /// As [`UpdateArgs::cache_dir`].
328    pub cache_dir: Option<PathBuf>,
329    /// Emit JSON rather than a human-readable list.
330    pub json: bool,
331}
332
333/// Lists every package in the local index whose name or description
334/// matches `args.term`.
335///
336/// # Errors
337///
338/// [`CliError::Coordinator`] if the local index has not been fetched yet
339/// (naming `astrs hub update`) or cannot be listed.
340pub fn search(out: &mut dyn Write, args: &SearchArgs) -> Result<Vec<IndexPackage>, CliError> {
341    let cache_dir = args
342        .cache_dir
343        .clone()
344        .unwrap_or_else(hub_index::cache_dir_from_env);
345    let hits = hub_index::search(&cache_dir, &args.term).map_err(CoordinatorError::from)?;
346    print_search_results(out, args.json, &args.term, &hits);
347    Ok(hits)
348}
349
350fn print_search_results(out: &mut dyn Write, json: bool, term: &str, hits: &[IndexPackage]) {
351    if json {
352        emit_json(
353            out,
354            &serde_json::json!({
355                "term": term,
356                "results": hits.iter().map(package_summary_json).collect::<Vec<_>>(),
357            }),
358        );
359        return;
360    }
361    if hits.is_empty() {
362        let _ = writeln!(out, "no packages match `{term}`");
363    } else {
364        for package in hits {
365            let latest = package
366                .versions
367                .last()
368                .map_or("(no versions)", |v| v.version.as_str());
369            let _ = writeln!(
370                out,
371                "{:<24} {latest:<10} {}",
372                package.name, package.description
373            );
374        }
375    }
376    let _ = out.flush();
377}
378
379fn package_summary_json(package: &IndexPackage) -> serde_json::Value {
380    serde_json::json!({
381        "name": package.name,
382        "description": package.description,
383        "latest_version": package.versions.last().map(|v| v.version.clone()),
384        "version_count": package.versions.len(),
385    })
386}
387
388/// `astrs hub info` arguments, independent of `clap`.
389#[derive(Debug, Clone)]
390pub struct InfoArgs {
391    /// The package name to show.
392    pub name: String,
393    /// As [`UpdateArgs::cache_dir`].
394    pub cache_dir: Option<PathBuf>,
395    /// Emit JSON rather than a human-readable listing.
396    pub json: bool,
397}
398
399/// Shows one package's description and every published version.
400///
401/// # Errors
402///
403/// [`CliError::Coordinator`] if the package (or the index itself) is not
404/// found, or its entry is not valid JSON — see
405/// [`hub_index::HubIndexError`].
406pub fn info(out: &mut dyn Write, args: &InfoArgs) -> Result<IndexPackage, CliError> {
407    let cache_dir = args
408        .cache_dir
409        .clone()
410        .unwrap_or_else(hub_index::cache_dir_from_env);
411    let package =
412        hub_index::read_package(&cache_dir, &args.name).map_err(CoordinatorError::from)?;
413    print_package_info(out, args.json, &package);
414    Ok(package)
415}
416
417fn print_package_info(out: &mut dyn Write, json: bool, package: &IndexPackage) {
418    if json {
419        emit_json(
420            out,
421            &serde_json::json!({
422                "name": package.name,
423                "description": package.description,
424                "versions": package.versions.iter().map(|v| serde_json::json!({
425                    "version": v.version,
426                    "git": v.git,
427                    "rev": v.rev,
428                    "subdir": v.subdir,
429                })).collect::<Vec<_>>(),
430            }),
431        );
432        return;
433    }
434    let _ = writeln!(out, "{}", package.name);
435    let _ = writeln!(out, "  {}", package.description);
436    let _ = writeln!(out, "  versions (oldest first):");
437    for version in &package.versions {
438        match &version.subdir {
439            Some(subdir) => {
440                let _ = writeln!(
441                    out,
442                    "    {:<10} {} @ {}  (subdir: {subdir})",
443                    version.version, version.git, version.rev
444                );
445            }
446            None => {
447                let _ = writeln!(
448                    out,
449                    "    {:<10} {} @ {}",
450                    version.version, version.git, version.rev
451                );
452            }
453        }
454    }
455    let _ = out.flush();
456}
457
458/// `astrs hub init` arguments, independent of `clap`.
459#[derive(Debug, Clone)]
460pub struct InitArgs {
461    /// The directory to scaffold the index repo layout into.
462    pub dir: PathBuf,
463    /// Scaffold into a non-empty directory anyway.
464    pub force: bool,
465    /// Emit JSON rather than a human-readable confirmation.
466    pub json: bool,
467}
468
469/// Scaffolds a valid, self-hostable index repo layout at `args.dir`: a
470/// `packages/` directory, an explanatory `README.md`, and a `git init` so
471/// it is ready for `git add -A && git commit` — see `INDEX_README` for
472/// exactly what gets written.
473///
474/// # Errors
475///
476/// - [`CliError::TargetExists`] if `args.dir` already exists and is
477///   non-empty, unless `args.force` is set.
478/// - [`CliError::Io`] if the layout cannot be written.
479/// - [`CliError::Coordinator`] if `git init` fails.
480pub fn init(out: &mut dyn Write, args: &InitArgs) -> Result<PathBuf, CliError> {
481    if args.dir.exists() && !args.force {
482        let non_empty = std::fs::read_dir(&args.dir)
483            .map(|mut entries| entries.next().is_some())
484            .unwrap_or(false);
485        if non_empty {
486            return Err(CliError::TargetExists {
487                path: args.dir.display().to_string(),
488            });
489        }
490    }
491
492    let packages_dir = args.dir.join("packages");
493    std::fs::create_dir_all(&packages_dir).map_err(|source| CliError::io(&packages_dir, source))?;
494    // An empty directory is not something git tracks; a placeholder keeps
495    // `packages/` present in the very first commit.
496    std::fs::write(packages_dir.join(".gitkeep"), b"")
497        .map_err(|source| CliError::io(&packages_dir, source))?;
498    let readme_path = args.dir.join("README.md");
499    std::fs::write(&readme_path, INDEX_README)
500        .map_err(|source| CliError::io(&readme_path, source))?;
501
502    run_git(Some(&args.dir), &["init", "--quiet"])?;
503
504    if args.json {
505        emit_json(
506            out,
507            &serde_json::json!({ "initialized": args.dir.display().to_string() }),
508        );
509    } else {
510        let _ = writeln!(out, "initialized a package index at {}", args.dir.display());
511        let _ = writeln!(
512            out,
513            "  add packages under packages/<name>.json, then `git add -A && git commit`"
514        );
515        let _ = out.flush();
516    }
517    Ok(args.dir.clone())
518}
519
520/// Writes one JSON object.
521///
522/// Duplicated from `command::token`'s own copy rather than shared — see
523/// that module's docs on this crate's small-per-module-helper convention.
524fn emit_json(out: &mut dyn Write, value: &serde_json::Value) {
525    let _ = writeln!(
526        out,
527        "{}",
528        serde_json::to_string_pretty(value).unwrap_or_else(|_| "{}".to_owned())
529    );
530    let _ = out.flush();
531}
532
533#[cfg(test)]
534mod tests {
535    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
536    use super::*;
537
538    fn scratch(name: &str) -> PathBuf {
539        let dir = std::env::temp_dir().join(format!("astrs-cli-hub-{}-{name}", std::process::id()));
540        let _ = std::fs::remove_dir_all(&dir);
541        std::fs::create_dir_all(&dir).unwrap();
542        dir
543    }
544
545    fn run(dir: &Path, args: &[&str]) {
546        let status = Command::new("git")
547            .args(args)
548            .current_dir(dir)
549            .status()
550            .unwrap();
551        assert!(status.success(), "git {args:?} failed in {}", dir.display());
552    }
553
554    /// Builds a real git repository at `dir` with a valid index layout
555    /// (one `yolo-detector` package, two versions) already committed —
556    /// the fixture every `update`/`search`/`info` end-to-end test clones
557    /// or pulls from over `file://`.
558    fn build_index_repo(dir: &Path) {
559        std::fs::create_dir_all(dir.join("packages")).unwrap();
560        std::fs::write(
561            dir.join("packages").join("yolo-detector.json"),
562            serde_json::to_string(&IndexPackage {
563                name: "yolo-detector".to_owned(),
564                description: "A YOLO-family object detector node.".to_owned(),
565                versions: vec![
566                    hub_index::IndexVersion {
567                        version: "v0.3.0".to_owned(),
568                        git: "https://example.invalid/yolo".to_owned(),
569                        rev: "a1b2c3d".to_owned(),
570                        subdir: None,
571                    },
572                    hub_index::IndexVersion {
573                        version: "v0.3.1".to_owned(),
574                        git: "https://example.invalid/yolo".to_owned(),
575                        rev: "d4e5f6a".to_owned(),
576                        subdir: None,
577                    },
578                ],
579            })
580            .unwrap(),
581        )
582        .unwrap();
583        run(dir, &["init", "--quiet", "--initial-branch=main"]);
584        run(dir, &["config", "user.email", "test@astrs.invalid"]);
585        run(dir, &["config", "user.name", "astrs-cli tests"]);
586        run(dir, &["add", "-A"]);
587        run(dir, &["commit", "--quiet", "-m", "seed index"]);
588    }
589
590    fn file_url(dir: &Path) -> String {
591        format!("file://{}", dir.display())
592    }
593
594    #[test]
595    fn update_clones_a_fresh_index_and_then_pulls_it() {
596        let origin = scratch("update-origin");
597        build_index_repo(&origin);
598        let cache = scratch("update-cache");
599        std::fs::remove_dir_all(&cache).unwrap(); // update must create it
600
601        let mut out = Vec::new();
602        let report = update(
603            &mut out,
604            &UpdateArgs {
605                index: Some(file_url(&origin)),
606                cache_dir: Some(cache.clone()),
607                config_path: Some(scratch("update-config-unused").join("config.toml")),
608                json: false,
609            },
610        )
611        .unwrap();
612        assert!(report.cloned);
613        assert_eq!(report.package_count, 1);
614        assert!(cache.join("packages").join("yolo-detector.json").is_file());
615        assert!(
616            String::from_utf8(out).unwrap().contains("cloned"),
617            "human report should say it cloned"
618        );
619
620        // A second commit lands upstream…
621        std::fs::write(
622            origin.join("packages").join("lidar-slam.json"),
623            serde_json::to_string(&IndexPackage {
624                name: "lidar-slam".to_owned(),
625                description: "SLAM from a spinning lidar.".to_owned(),
626                versions: vec![hub_index::IndexVersion {
627                    version: "v1".to_owned(),
628                    git: "https://example.invalid/slam".to_owned(),
629                    rev: "abc".to_owned(),
630                    subdir: None,
631                }],
632            })
633            .unwrap(),
634        )
635        .unwrap();
636        run(&origin, &["add", "-A"]);
637        run(&origin, &["commit", "--quiet", "-m", "add lidar-slam"]);
638
639        // …and a second `update` pulls it in, not re-cloning.
640        let mut out = Vec::new();
641        let report = update(
642            &mut out,
643            &UpdateArgs {
644                index: Some(file_url(&origin)),
645                cache_dir: Some(cache.clone()),
646                config_path: None,
647                json: false,
648            },
649        )
650        .unwrap();
651        assert!(!report.cloned, "the second update pulls, it does not clone");
652        assert_eq!(report.package_count, 2);
653        assert!(cache.join("packages").join("lidar-slam.json").is_file());
654    }
655
656    #[test]
657    fn update_against_a_nonexistent_repository_is_a_clear_error() {
658        let cache = scratch("update-missing-remote");
659        std::fs::remove_dir_all(&cache).unwrap();
660        let nowhere = scratch("update-missing-remote-origin");
661        std::fs::remove_dir_all(&nowhere).unwrap(); // never created
662
663        let error = update(
664            &mut Vec::new(),
665            &UpdateArgs {
666                index: Some(file_url(&nowhere)),
667                cache_dir: Some(cache),
668                config_path: Some(scratch("update-missing-remote-config").join("config.toml")),
669                json: false,
670            },
671        )
672        .unwrap_err();
673        assert!(matches!(error, CliError::Coordinator(_)), "{error}");
674        assert!(!error.to_string().is_empty());
675    }
676
677    #[test]
678    fn search_and_info_read_the_freshly_updated_cache() {
679        let origin = scratch("search-info-origin");
680        build_index_repo(&origin);
681        let cache = scratch("search-info-cache");
682        std::fs::remove_dir_all(&cache).unwrap();
683        update(
684            &mut Vec::new(),
685            &UpdateArgs {
686                index: Some(file_url(&origin)),
687                cache_dir: Some(cache.clone()),
688                config_path: Some(scratch("search-info-config").join("config.toml")),
689                json: false,
690            },
691        )
692        .unwrap();
693
694        let mut out = Vec::new();
695        let hits = search(
696            &mut out,
697            &SearchArgs {
698                term: "yolo".to_owned(),
699                cache_dir: Some(cache.clone()),
700                json: false,
701            },
702        )
703        .unwrap();
704        assert_eq!(hits.len(), 1);
705        assert_eq!(hits[0].name, "yolo-detector");
706        assert!(String::from_utf8(out).unwrap().contains("yolo-detector"));
707
708        let mut out = Vec::new();
709        let package = info(
710            &mut out,
711            &InfoArgs {
712                name: "yolo-detector".to_owned(),
713                cache_dir: Some(cache),
714                json: false,
715            },
716        )
717        .unwrap();
718        assert_eq!(package.versions.len(), 2);
719        let printed = String::from_utf8(out).unwrap();
720        assert!(printed.contains("v0.3.0"));
721        assert!(printed.contains("v0.3.1"));
722    }
723
724    #[test]
725    fn search_before_any_update_names_the_update_command() {
726        let cache = scratch("search-no-update");
727        std::fs::remove_dir_all(&cache).unwrap();
728
729        let error = search(
730            &mut Vec::new(),
731            &SearchArgs {
732                term: String::new(),
733                cache_dir: Some(cache),
734                json: false,
735            },
736        )
737        .unwrap_err();
738        assert!(error.to_string().contains("astrs hub update"), "{error}");
739    }
740
741    #[test]
742    fn info_on_an_unknown_package_names_search_and_update() {
743        let origin = scratch("info-unknown-origin");
744        build_index_repo(&origin);
745        let cache = scratch("info-unknown-cache");
746        std::fs::remove_dir_all(&cache).unwrap();
747        update(
748            &mut Vec::new(),
749            &UpdateArgs {
750                index: Some(file_url(&origin)),
751                cache_dir: Some(cache.clone()),
752                config_path: Some(scratch("info-unknown-config").join("config.toml")),
753                json: false,
754            },
755        )
756        .unwrap();
757
758        let error = info(
759            &mut Vec::new(),
760            &InfoArgs {
761                name: "does-not-exist".to_owned(),
762                cache_dir: Some(cache),
763                json: false,
764            },
765        )
766        .unwrap_err();
767        let message = error.to_string();
768        assert!(message.contains("astrs hub search"), "{message}");
769        assert!(message.contains("astrs hub update"), "{message}");
770    }
771
772    #[test]
773    fn init_scaffolds_a_layout_update_can_then_clone_from() {
774        let repo_dir = scratch("init-then-clone-repo");
775        std::fs::remove_dir_all(&repo_dir).unwrap();
776
777        init(
778            &mut Vec::new(),
779            &InitArgs {
780                dir: repo_dir.clone(),
781                force: false,
782                json: false,
783            },
784        )
785        .unwrap();
786        assert!(repo_dir.join("packages").is_dir());
787        assert!(repo_dir.join("README.md").is_file());
788        assert!(repo_dir.join(".git").is_dir());
789
790        // Self-hosting: add a package by hand, commit, and prove another
791        // machine's `astrs hub update` can clone it back out again.
792        std::fs::write(
793            repo_dir.join("packages").join("yolo-detector.json"),
794            serde_json::to_string(&IndexPackage {
795                name: "yolo-detector".to_owned(),
796                description: "detector".to_owned(),
797                versions: vec![hub_index::IndexVersion {
798                    version: "v1".to_owned(),
799                    git: "https://example.invalid/yolo".to_owned(),
800                    rev: "cafe".to_owned(),
801                    subdir: None,
802                }],
803            })
804            .unwrap(),
805        )
806        .unwrap();
807        run(&repo_dir, &["config", "user.email", "test@astrs.invalid"]);
808        run(&repo_dir, &["config", "user.name", "astrs-cli tests"]);
809        run(&repo_dir, &["add", "-A"]);
810        run(&repo_dir, &["commit", "--quiet", "-m", "add yolo-detector"]);
811
812        let cache = scratch("init-then-clone-cache");
813        std::fs::remove_dir_all(&cache).unwrap();
814        let report = update(
815            &mut Vec::new(),
816            &UpdateArgs {
817                index: Some(file_url(&repo_dir)),
818                cache_dir: Some(cache),
819                config_path: Some(scratch("init-then-clone-config").join("config.toml")),
820                json: false,
821            },
822        )
823        .unwrap();
824        assert_eq!(report.package_count, 1);
825    }
826
827    #[test]
828    fn init_refuses_a_nonempty_directory_without_force() {
829        let dir = scratch("init-nonempty");
830        std::fs::write(dir.join("keep.txt"), b"pre-existing").unwrap();
831
832        let error = init(
833            &mut Vec::new(),
834            &InitArgs {
835                dir: dir.clone(),
836                force: false,
837                json: false,
838            },
839        )
840        .unwrap_err();
841        assert!(matches!(error, CliError::TargetExists { .. }), "{error}");
842
843        // `--force` proceeds anyway.
844        init(
845            &mut Vec::new(),
846            &InitArgs {
847                dir,
848                force: true,
849                json: false,
850            },
851        )
852        .unwrap();
853    }
854
855    #[test]
856    fn resolve_index_url_prefers_explicit_then_env_then_config_then_default() {
857        let config_dir = scratch("resolve-index-url");
858        let config_path = config_dir.join("config.toml");
859
860        // Nothing set anywhere: the built-in default.
861        assert_eq!(
862            resolve_index_url(None, &config_path).unwrap(),
863            hub_index::DEFAULT_INDEX_URL
864        );
865
866        // The config file's `[hub] index` key wins over the default.
867        std::fs::write(
868            &config_path,
869            "[hub]\nindex = \"https://example.invalid/from-config\"\n",
870        )
871        .unwrap();
872        assert_eq!(
873            resolve_index_url(None, &config_path).unwrap(),
874            "https://example.invalid/from-config"
875        );
876
877        // An explicit argument wins over everything.
878        assert_eq!(
879            resolve_index_url(Some("https://example.invalid/explicit"), &config_path).unwrap(),
880            "https://example.invalid/explicit"
881        );
882    }
883
884    #[test]
885    fn a_malformed_config_file_is_a_clear_error() {
886        let config_dir = scratch("resolve-index-url-malformed");
887        let config_path = config_dir.join("config.toml");
888        std::fs::write(&config_path, "not = [valid toml").unwrap();
889
890        let error = resolve_index_url(None, &config_path).unwrap_err();
891        assert!(matches!(error, CliError::Coordinator(_)), "{error}");
892    }
893
894    #[test]
895    fn json_output_carries_the_same_fields_as_the_report() {
896        let origin = scratch("json-output-origin");
897        build_index_repo(&origin);
898        let cache = scratch("json-output-cache");
899        std::fs::remove_dir_all(&cache).unwrap();
900
901        let mut out = Vec::new();
902        let report = update(
903            &mut out,
904            &UpdateArgs {
905                index: Some(file_url(&origin)),
906                cache_dir: Some(cache),
907                config_path: Some(scratch("json-output-config").join("config.toml")),
908                json: true,
909            },
910        )
911        .unwrap();
912        let value: serde_json::Value = serde_json::from_slice(&out).unwrap();
913        assert_eq!(value["index_url"], report.index_url);
914        assert_eq!(value["package_count"], 1);
915        assert_eq!(value["cloned"], true);
916    }
917}