greentic_dev/
pack_temp.rs

1use std::fs;
2use std::path::{Path, PathBuf};
3
4use anyhow::{Context, Result, bail};
5use tempfile::TempDir;
6
7use packc::BuildArgs;
8use packc::build::{self, BuildOptions};
9
10/// Ensure we have a concrete .gtpack on disk. If the input is already a file, reuse it.
11/// If it is a directory, shell out to packc to build a temporary .gtpack and return its path.
12pub fn materialize_pack_path(input: &Path, verbose: bool) -> Result<(Option<TempDir>, PathBuf)> {
13    let metadata =
14        fs::metadata(input).with_context(|| format!("unable to read input {}", input.display()))?;
15    if metadata.is_file() {
16        return Ok((None, input.to_path_buf()));
17    }
18    if metadata.is_dir() {
19        let temp = TempDir::new().context("failed to create temporary directory for pack build")?;
20        let pack_path = temp.path().join("pack.gtpack");
21        build_packc_temp(input, &pack_path, verbose)?;
22        return Ok((Some(temp), pack_path));
23    }
24    bail!(
25        "input {} is neither a file nor a directory",
26        input.display()
27    );
28}
29
30fn build_packc_temp(source: &Path, gtpack_out: &Path, verbose: bool) -> Result<()> {
31    let _ = verbose;
32    // Use packc library to build a temporary gtpack.
33    let build_args = BuildArgs {
34        input: source.to_path_buf(),
35        component_out: Some(gtpack_out.with_extension("wasm")),
36        manifest: Some(gtpack_out.with_extension("cbor")),
37        sbom: Some(gtpack_out.with_extension("cdx.json")),
38        gtpack_out: Some(gtpack_out.to_path_buf()),
39        dry_run: false,
40    };
41    let opts = BuildOptions::from_args(build_args)?;
42    build::run(&opts).context("packc build failed for temporary .gtpack")
43}