cotis-cli 0.1.0-alpha

Plugin host for Cotis build, check, and run routines
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
//! Install routines from local projects, crates.io, or GitHub releases.
//!
//! Parses `path:`, `crate:`, and `gh:` install specs, builds or downloads cdylibs, validates the
//! plugin ABI, writes `descriptor.json`, and optionally runs `cotis_plugin_finish_installation`.
//!
//! ## Version naming
//!
//! | Source | Cache version directory | Routine name |
//! |--------|-------------------------|--------------|
//! | `path:` | Always `"dev"` | cdylib stem or alias |
//! | `crate:` | Crate version string | cdylib stem (alias ignored) |
//! | `gh:` | Release `tag_name` | repo name or alias |
//!
//! ## Overwrite
//!
//! Unless `overwrite` is true, install fails if the target plugin file already exists.
//! Use `-f` / `--overwrite` / `--fo` on the CLI, or `update` / `reinstall` which always overwrite.

use std::fs;
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};

use directories::ProjectDirs;
use log::{debug, info};
use reqwest::blocking::Client;
use serde::Deserialize;
use tempfile::TempDir;

use crate::plugin::{LoadedPlugin, PluginDescriptor};
use crate::routines::{
    descriptor_path, host_target_triple, platform_library_filename, plugin_library_path,
};

/// Parsed install source for [`install`].
#[derive(Debug, Clone)]
pub enum InstallSpec {
    /// Local Cargo project directory (`path:<dir>`).
    LocalPath(PathBuf),
    /// crates.io crate (`crate:<name>@<version>`).
    Crate {
        /// Crate name on crates.io.
        name: String,
        /// Exact crate version to download and build.
        version: String,
    },
    /// GitHub release (`gh:<owner>/<repo>@<tag|latest>`).
    Github {
        /// Repository owner.
        owner: String,
        /// Repository name.
        repo: String,
        /// Release tag, or `"latest"` for the newest release.
        tag: String,
    },
}

/// Parse an install spec string into [`InstallSpec`].
///
/// Accepted forms:
/// - `path:<directory>`
/// - `crate:<name>@<version>`
/// - `gh:<owner>/<repo>@<tagOrLatest>`
///
/// # Errors
///
/// Returns an error if the prefix is unknown or required components are missing.
///
/// # Examples
///
/// ```
/// use cotis_cli::install::{parse_install_spec, InstallSpec};
/// use std::path::PathBuf;
///
/// match parse_install_spec("path:./my-routine").unwrap() {
///     InstallSpec::LocalPath(p) => assert_eq!(p, PathBuf::from("./my-routine")),
///     _ => panic!("expected LocalPath"),
/// }
///
/// match parse_install_spec("crate:my-routine@0.2.0").unwrap() {
///     InstallSpec::Crate { name, version } => {
///         assert_eq!(name, "my-routine");
///         assert_eq!(version, "0.2.0");
///     }
///     _ => panic!("expected Crate"),
/// }
///
/// match parse_install_spec("gh:org/repo@latest").unwrap() {
///     InstallSpec::Github { owner, repo, tag } => {
///         assert_eq!(owner, "org");
///         assert_eq!(repo, "repo");
///         assert_eq!(tag, "latest");
///     }
///     _ => panic!("expected Github"),
/// }
///
/// assert!(parse_install_spec("invalid").is_err());
/// ```
pub fn parse_install_spec(s: &str) -> Result<InstallSpec, String> {
    if let Some(rest) = s.strip_prefix("path:") {
        return Ok(InstallSpec::LocalPath(PathBuf::from(rest)));
    }
    if let Some(rest) = s.strip_prefix("crate:") {
        let (name, version) = rest
            .split_once('@')
            .ok_or_else(|| "Expected crate:<name>@<version>".to_string())?;
        return Ok(InstallSpec::Crate {
            name: name.to_string(),
            version: version.to_string(),
        });
    }
    if let Some(rest) = s.strip_prefix("gh:") {
        let (repo_part, tag) = rest
            .split_once('@')
            .ok_or_else(|| "Expected gh:<owner>/<repo>@<tagOrLatest>".to_string())?;
        let (owner, repo) = repo_part
            .split_once('/')
            .ok_or_else(|| "Expected gh:<owner>/<repo>@...".to_string())?;
        return Ok(InstallSpec::Github {
            owner: owner.to_string(),
            repo: repo.to_string(),
            tag: tag.to_string(),
        });
    }
    Err("Unknown install spec. Use path:, crate:, or gh:".to_string())
}

/// Normalizes `--cdylib-name` / `--dll-name`: trim and strip a trailing platform suffix if present.
///
/// # Errors
///
/// Returns an error if the stem is empty before or after stripping.
///
/// # Examples
///
/// ```
/// use cotis_cli::install::normalize_cdylib_stem;
///
/// assert_eq!(normalize_cdylib_stem("my_plugin").unwrap(), "my_plugin");
/// assert_eq!(normalize_cdylib_stem("my_plugin.dll").unwrap(), "my_plugin");
/// assert_eq!(normalize_cdylib_stem("  libfoo.so  ").unwrap(), "libfoo");
/// assert!(normalize_cdylib_stem("").is_err());
/// assert!(normalize_cdylib_stem(".dll").is_err());
/// ```
pub fn normalize_cdylib_stem(s: &str) -> Result<String, String> {
    let s = s.trim();
    if s.is_empty() {
        return Err("cdylib name must not be empty".to_string());
    }
    let lower = s.to_ascii_lowercase();
    let base = if lower.ends_with(".dll") {
        &s[..s.len() - 4]
    } else if lower.ends_with(".dylib") {
        &s[..s.len() - 6]
    } else if lower.ends_with(".so") {
        &s[..s.len() - 3]
    } else {
        s
    };
    let base = base.trim();
    if base.is_empty() {
        return Err("cdylib name must not be empty after stripping suffix".to_string());
    }
    Ok(base.to_string())
}

/// Install a routine into the cotis-cli cache.
///
/// Builds or downloads the cdylib, copies it to the cache, validates the plugin ABI, writes
/// `descriptor.json`, and runs `cotis_plugin_finish_installation` when requested by the descriptor.
///
/// `alias_override` sets the routine cache name for `path:` and `gh:` installs (ignored for `crate:`).
/// `cdylib_name_override` overrides cargo metadata cdylib detection for `path:` and `crate:` only.
///
/// # Errors
///
/// Returns an error for missing paths, failed cargo builds, HTTP failures, missing cdylib artifacts,
/// already-installed routines (when `overwrite` is false), incompatible plugins, or failed
/// finish-installation hooks.
pub fn install(
    proj_dirs: &ProjectDirs,
    spec: InstallSpec,
    alias_override: Option<&str>,
    cdylib_name_override: Option<&str>,
    overwrite: bool,
) -> Result<PluginDescriptor, String> {
    match spec {
        InstallSpec::LocalPath(path) => install_from_local_project(
            proj_dirs,
            &path,
            alias_override,
            cdylib_name_override,
            overwrite,
        ),
        InstallSpec::Crate { name, version } => {
            install_from_crates_io(proj_dirs, &name, &version, cdylib_name_override, overwrite)
        }
        InstallSpec::Github { owner, repo, tag } => {
            if cdylib_name_override.is_some() {
                return Err(
                    "--cdylib-name applies only to path: and crate: installs (GitHub uses release assets)."
                        .to_string(),
                );
            }
            install_from_github_release(proj_dirs, &owner, &repo, &tag, alias_override, overwrite)
        }
    }
}

fn install_from_local_project(
    proj_dirs: &ProjectDirs,
    path: &Path,
    alias_override: Option<&str>,
    cdylib_name_override: Option<&str>,
    overwrite: bool,
) -> Result<PluginDescriptor, String> {
    if !path.exists() {
        return Err(format!("Local path does not exist: {}", path.display()));
    }
    let path =
        fs::canonicalize(path).map_err(|e| format!("Failed to resolve project path: {e}"))?;
    debug!("Installing from local project {}", path.display());

    let target = host_target_triple()?;

    let build_target_dir = proj_dirs.cache_dir().join("installs").join("local-project");
    fs::create_dir_all(&build_target_dir)
        .map_err(|e| format!("Failed to create build dir: {e}"))?;

    let cdylib_name = match cdylib_name_override {
        Some(stem) => stem.to_string(),
        None => cargo_cdylib_name(&path)?,
    };
    let routine_name = alias_override.unwrap_or(&cdylib_name).to_string();

    cargo_build_cdylib(&path, &build_target_dir, true)?;

    let src = build_target_dir
        .join("release")
        .join(platform_library_filename(&cdylib_name));
    if !src.exists() {
        return Err(format!(
            "Expected built library not found at {}",
            src.display()
        ));
    }

    let dest = plugin_library_path(proj_dirs, &routine_name, "dev", &target);
    if dest.exists() && !overwrite {
        return Err(format!(
            "{routine_name} already installed (use -f / --overwrite / --fo to overwrite)"
        ));
    }
    fs::create_dir_all(dest.parent().unwrap())
        .map_err(|e| format!("Failed to create plugin dir: {e}"))?;
    fs::copy(&src, &dest).map_err(|e| format!("Failed to copy plugin: {e}"))?;

    let plugin = unsafe { LoadedPlugin::load(&dest) }?;
    plugin.ensure_compatible()?;
    let desc = plugin.descriptor()?;
    let desc_path = descriptor_path(proj_dirs, &routine_name, "dev", &target);
    fs::write(&desc_path, serde_json::to_vec_pretty(&desc).unwrap())
        .map_err(|e| format!("Failed to write descriptor: {e}"))?;

    run_finish_installation(proj_dirs, &plugin, &desc, Some(path.as_path()))?;

    info!("Installed {routine_name} ({}) for {target}", desc.version);
    Ok(desc)
}

fn install_from_crates_io(
    proj_dirs: &ProjectDirs,
    crate_name: &str,
    version: &str,
    cdylib_name_override: Option<&str>,
    overwrite: bool,
) -> Result<PluginDescriptor, String> {
    let target = host_target_triple()?;
    debug!("Installing from crates.io {crate_name}@{version}");

    let tmp = TempDir::new().map_err(|e| format!("Failed to create temp dir: {e}"))?;
    let tarball = download_crates_io(crate_name, version, tmp.path())?;
    let src_dir = extract_crate_tarball(&tarball, tmp.path())?;

    let build_target_dir = proj_dirs
        .cache_dir()
        .join("installs")
        .join(format!("crate-{crate_name}-{version}"));
    fs::create_dir_all(&build_target_dir)
        .map_err(|e| format!("Failed to create build dir: {e}"))?;
    cargo_build_cdylib(&src_dir, &build_target_dir, true)?;

    let cdylib_name = match cdylib_name_override {
        Some(stem) => stem.to_string(),
        None => cargo_cdylib_name(&src_dir)?,
    };
    let src = build_target_dir
        .join("release")
        .join(platform_library_filename(&cdylib_name));
    if !src.exists() {
        return Err(format!(
            "Expected built library not found at {}",
            src.display()
        ));
    }

    let routine_name = cdylib_name.clone();
    let dest = plugin_library_path(proj_dirs, &routine_name, version, &target);
    if dest.exists() && !overwrite {
        return Err(format!(
            "{routine_name}@{version} already installed (use -f / --overwrite / --fo to overwrite)"
        ));
    }
    fs::create_dir_all(dest.parent().unwrap())
        .map_err(|e| format!("Failed to create plugin dir: {e}"))?;
    fs::copy(&src, &dest).map_err(|e| format!("Failed to copy plugin: {e}"))?;

    let plugin = unsafe { LoadedPlugin::load(&dest) }?;
    plugin.ensure_compatible()?;
    let desc = plugin.descriptor()?;
    let desc_path = descriptor_path(proj_dirs, &routine_name, version, &target);
    fs::write(&desc_path, serde_json::to_vec_pretty(&desc).unwrap())
        .map_err(|e| format!("Failed to write descriptor: {e}"))?;

    run_finish_installation(proj_dirs, &plugin, &desc, None)?;

    info!("Installed {routine_name}@{version} for {target}");
    Ok(desc)
}

fn install_from_github_release(
    proj_dirs: &ProjectDirs,
    owner: &str,
    repo: &str,
    tag: &str,
    alias_override: Option<&str>,
    overwrite: bool,
) -> Result<PluginDescriptor, String> {
    let target = host_target_triple()?;
    debug!("Installing from GitHub {owner}/{repo}@{tag}");

    let client = Client::builder()
        .user_agent("cotis-cli")
        .build()
        .map_err(|e| format!("Failed to build HTTP client: {e}"))?;

    let release = github_release(&client, owner, repo, tag)?;
    let ext = if cfg!(windows) {
        ".dll"
    } else if cfg!(target_os = "macos") {
        ".dylib"
    } else {
        ".so"
    };

    // Prefer an asset whose name contains the host triple and matching extension;
    // otherwise take the first asset with a matching extension.
    let asset = release
        .assets
        .iter()
        .find(|a| a.name.contains(&target) && a.name.ends_with(ext))
        .or_else(|| release.assets.iter().find(|a| a.name.ends_with(ext)))
        .ok_or_else(|| "No matching release asset found for this platform".to_string())?;

    let routine_name = alias_override.unwrap_or(repo).to_string();
    let version = release.tag_name.clone();

    let dest = plugin_library_path(proj_dirs, &routine_name, &version, &target);
    if dest.exists() && !overwrite {
        return Err(format!(
            "{routine_name}@{version} already installed (use -f / --overwrite / --fo to overwrite)"
        ));
    }
    fs::create_dir_all(dest.parent().unwrap())
        .map_err(|e| format!("Failed to create plugin dir: {e}"))?;

    debug!("Downloading asset {} -> {}", asset.name, dest.display());
    let mut resp = client
        .get(&asset.browser_download_url)
        .send()
        .map_err(|e| format!("Failed to download asset: {e}"))?;
    if !resp.status().is_success() {
        return Err(format!("Asset download failed with HTTP {}", resp.status()));
    }
    let mut out =
        fs::File::create(&dest).map_err(|e| format!("Failed to create output file: {e}"))?;
    let mut buf = Vec::new();
    resp.read_to_end(&mut buf)
        .map_err(|e| format!("Failed to read download: {e}"))?;
    out.write_all(&buf)
        .map_err(|e| format!("Failed to write plugin file: {e}"))?;

    let plugin = unsafe { LoadedPlugin::load(&dest) }?;
    plugin.ensure_compatible()?;
    let desc = plugin.descriptor()?;
    let desc_path = descriptor_path(proj_dirs, &routine_name, &version, &target);
    fs::write(&desc_path, serde_json::to_vec_pretty(&desc).unwrap())
        .map_err(|e| format!("Failed to write descriptor: {e}"))?;

    run_finish_installation(proj_dirs, &plugin, &desc, None)?;

    info!("Installed {routine_name}@{version} for {target}");
    Ok(desc)
}

fn run_finish_installation(
    proj_dirs: &ProjectDirs,
    plugin: &LoadedPlugin,
    desc: &PluginDescriptor,
    local_install_project_dir: Option<&Path>,
) -> Result<(), String> {
    if !desc.finish_installation {
        return Ok(());
    }

    // SAFETY: `cotis-cli install` runs single-threaded; env is restored immediately after the plugin hook returns.
    unsafe {
        std::env::set_var(
            "COTIS_CLI_CACHE_DIR",
            proj_dirs.cache_dir().to_string_lossy().into_owned(),
        );
        if let Some(p) = local_install_project_dir {
            std::env::set_var(
                "COTIS_CLI_INSTALL_PROJECT_DIR",
                p.to_string_lossy().into_owned(),
            );
        } else {
            std::env::remove_var("COTIS_CLI_INSTALL_PROJECT_DIR");
        }
    }

    plugin.finish_installation_if_requested(desc)?;

    unsafe {
        std::env::remove_var("COTIS_CLI_INSTALL_PROJECT_DIR");
    }
    Ok(())
}

fn cargo_build_cdylib(project_dir: &Path, target_dir: &Path, release: bool) -> Result<(), String> {
    let mut cmd = Command::new("cargo");
    cmd.current_dir(project_dir);
    cmd.args([
        "build",
        "--lib",
        "--target-dir",
        target_dir.to_str().unwrap(),
    ]);
    if release {
        cmd.arg("--release");
    }
    cmd.stdout(Stdio::inherit());
    cmd.stderr(Stdio::inherit());
    let st = cmd
        .status()
        .map_err(|e| format!("Failed to run cargo build: {e}"))?;
    if !st.success() {
        return Err("cargo build failed".to_string());
    }
    Ok(())
}

fn cargo_cdylib_name(project_dir: &Path) -> Result<String, String> {
    #[derive(Deserialize)]
    struct Metadata {
        packages: Vec<Package>,
    }
    #[derive(Deserialize)]
    struct Package {
        manifest_path: String,
        targets: Vec<Target>,
    }
    #[derive(Deserialize)]
    struct Target {
        kind: Vec<String>,
        name: String,
    }

    let project_dir = fs::canonicalize(project_dir).map_err(|e| {
        format!(
            "Failed to resolve project directory {}: {e}",
            project_dir.display()
        )
    })?;
    let expected_manifest = fs::canonicalize(project_dir.join("Cargo.toml")).map_err(|e| {
        format!(
            "Expected Cargo.toml at {}: {e}",
            project_dir.join("Cargo.toml").display()
        )
    })?;

    let out = Command::new("cargo")
        .current_dir(&project_dir)
        .args(["metadata", "--no-deps", "--format-version", "1"])
        .stderr(Stdio::inherit())
        .output()
        .map_err(|e| format!("Failed to run cargo metadata: {e}"))?;
    if !out.status.success() {
        return Err("cargo metadata failed".to_string());
    }
    let md: Metadata = serde_json::from_slice(&out.stdout)
        .map_err(|e| format!("Failed to parse cargo metadata: {e}"))?;

    let pkg = md
        .packages
        .iter()
        .find(|p| {
            Path::new(&p.manifest_path).canonicalize().ok().as_ref() == Some(&expected_manifest)
        })
        .ok_or_else(|| {
            format!(
                "cargo metadata has no package with manifest {} (workspace root mis-detected?)",
                expected_manifest.display()
            )
        })?;

    let name = pkg
        .targets
        .iter()
        .find(|t| t.kind.iter().any(|k| k == "cdylib"))
        .map(|t| t.name.clone())
        .ok_or_else(|| {
            "No cdylib target found (is [lib] crate-type = [\"cdylib\"] set?)".to_string()
        })?;
    Ok(name)
}

fn download_crates_io(crate_name: &str, version: &str, out_dir: &Path) -> Result<PathBuf, String> {
    let url = format!("https://crates.io/api/v1/crates/{crate_name}/{version}/download");
    let client = Client::builder()
        .user_agent("cotis-cli")
        .build()
        .map_err(|e| format!("Failed to build HTTP client: {e}"))?;
    let mut resp = client
        .get(url)
        .send()
        .map_err(|e| format!("Failed to download crate: {e}"))?;
    if !resp.status().is_success() {
        return Err(format!("Crate download failed with HTTP {}", resp.status()));
    }
    let tar_path = out_dir.join(format!("{crate_name}-{version}.crate.tar.gz"));
    let mut file =
        fs::File::create(&tar_path).map_err(|e| format!("Failed to create tarball file: {e}"))?;
    let mut buf = Vec::new();
    resp.read_to_end(&mut buf)
        .map_err(|e| format!("Failed to read tarball: {e}"))?;
    file.write_all(&buf)
        .map_err(|e| format!("Failed to write tarball: {e}"))?;
    Ok(tar_path)
}

fn extract_crate_tarball(tar_gz_path: &Path, out_dir: &Path) -> Result<PathBuf, String> {
    use flate2::read::GzDecoder;
    use tar::Archive;

    let f = fs::File::open(tar_gz_path).map_err(|e| format!("Failed to open tarball: {e}"))?;
    let gz = GzDecoder::new(f);
    let mut ar = Archive::new(gz);
    ar.unpack(out_dir)
        .map_err(|e| format!("Failed to unpack tarball: {e}"))?;

    let mut dirs = fs::read_dir(out_dir)
        .map_err(|e| format!("Failed to read extracted dir: {e}"))?
        .filter_map(|e| e.ok())
        .filter(|e| e.path().is_dir())
        .collect::<Vec<_>>();
    if dirs.len() != 1 {
        return Err("Unexpected tarball layout after extract".to_string());
    }
    Ok(dirs.remove(0).path())
}

#[derive(Debug, Deserialize)]
struct GithubRelease {
    tag_name: String,
    assets: Vec<GithubAsset>,
}

#[derive(Debug, Deserialize)]
struct GithubAsset {
    name: String,
    browser_download_url: String,
}

fn github_release(
    client: &Client,
    owner: &str,
    repo: &str,
    tag: &str,
) -> Result<GithubRelease, String> {
    let url = if tag == "latest" {
        format!("https://api.github.com/repos/{owner}/{repo}/releases/latest")
    } else {
        format!("https://api.github.com/repos/{owner}/{repo}/releases/tags/{tag}")
    };
    let resp = client
        .get(url)
        .send()
        .map_err(|e| format!("Failed to query GitHub release: {e}"))?;
    if !resp.status().is_success() {
        return Err(format!("GitHub API error HTTP {}", resp.status()));
    }
    resp.json::<GithubRelease>()
        .map_err(|e| format!("Failed to parse GitHub release JSON: {e}"))
}