Skip to main content

grex_cli/cli/verbs/
add.rs

1use crate::cli::args::{AddArgs, GlobalFlags};
2use anyhow::{Context, Result};
3use grex_core::add::{add_pack, infer_path_from_url, AddOpts, AddReport, AddRequest};
4use grex_core::import::classify;
5use grex_core::manifest::{ensure_event_log_migrated, find_workspace_root};
6use tokio_util::sync::CancellationToken;
7
8pub fn run(args: AddArgs, global: &GlobalFlags, _cancel: &CancellationToken) -> Result<()> {
9    let path = args.path.unwrap_or_else(|| infer_path_from_url(&args.url));
10    let pack_type = classify(&args.url).as_str().to_string();
11    // Resolve the workspace root by walking up from cwd looking for a
12    // `.grex/` marker. Falls back to cwd when no marker is found, so a
13    // fresh workspace just uses the user's directory. This fixes the
14    // v1.x cwd-relative bug where running `grex add` from a subdir
15    // created a stray event log in the subdir instead of writing to
16    // the parent workspace's log.
17    let cwd = std::env::current_dir().context("resolve cwd for workspace root")?;
18    let workspace = find_workspace_root(&cwd);
19    let manifest = ensure_event_log_migrated(&workspace).context("migrate v1.x event log")?;
20    let report = add_pack(
21        &manifest,
22        AddRequest::new(args.url, path, pack_type),
23        AddOpts::new(global.dry_run),
24    )
25    .context("grex add failed")?;
26
27    if global.json {
28        emit_json(&report)?;
29    } else {
30        emit_human(&report);
31    }
32    Ok(())
33}
34
35fn emit_human(report: &AddReport) {
36    let prefix = if report.dry_run { "DRY-RUN: would add" } else { "added" };
37    println!(
38        "{prefix} {path:<32} {kind:<12} {url}",
39        path = report.path,
40        kind = report.pack_type,
41        url = if report.url.is_empty() { "-" } else { &report.url },
42    );
43}
44
45fn emit_json(report: &AddReport) -> Result<()> {
46    let out = serde_json::json!({
47        "dry_run": report.dry_run,
48        "id": report.id,
49        "url": report.url,
50        "path": report.path,
51        "type": report.pack_type,
52        "appended": report.appended,
53    });
54    println!("{}", serde_json::to_string(&out)?);
55    Ok(())
56}