Skip to main content

packc/cli/
mod.rs

1#![forbid(unsafe_code)]
2
3use std::{convert::TryFrom, path::PathBuf};
4
5use anyhow::Result;
6use clap::{Parser, Subcommand};
7use greentic_types::{EnvId, TenantCtx, TenantId};
8use tokio::runtime::Runtime;
9
10pub mod components;
11pub mod config;
12pub mod gui;
13pub mod input;
14pub mod inspect;
15pub mod lint;
16pub mod plan;
17pub mod providers;
18pub mod resolve;
19pub mod sign;
20pub mod update;
21pub mod verify;
22
23use crate::telemetry::set_current_tenant_ctx;
24use crate::{build, new, runtime};
25
26#[derive(Debug, Parser)]
27#[command(name = "greentic-pack", about = "Greentic pack CLI", version)]
28pub struct Cli {
29    /// Logging filter (overrides PACKC_LOG)
30    #[arg(long = "log", default_value = "info", global = true)]
31    pub verbosity: String,
32
33    /// Force offline mode (disables any network activity)
34    #[arg(long, global = true)]
35    pub offline: bool,
36
37    /// Override cache directory (defaults to pack_dir/.packc or GREENTIC_PACK_CACHE_DIR)
38    #[arg(long = "cache-dir", global = true)]
39    pub cache_dir: Option<PathBuf>,
40
41    /// Optional config overrides in TOML/JSON (greentic-config layer)
42    #[arg(long = "config-override", value_name = "FILE", global = true)]
43    pub config_override: Option<PathBuf>,
44
45    /// Emit machine-readable JSON output where applicable
46    #[arg(long, global = true)]
47    pub json: bool,
48
49    #[command(subcommand)]
50    pub command: Command,
51}
52
53#[allow(clippy::large_enum_variant)]
54#[derive(Debug, Subcommand)]
55pub enum Command {
56    /// Build a pack component and supporting artifacts
57    Build(BuildArgs),
58    /// Lint a pack manifest, flows, and templates
59    Lint(self::lint::LintArgs),
60    /// Sync pack.yaml components with files under components/
61    Components(self::components::ComponentsArgs),
62    /// Sync pack.yaml components and flows with files under the pack root
63    Update(self::update::UpdateArgs),
64    /// Scaffold a new pack directory
65    New(new::NewArgs),
66    /// Sign a pack manifest using an Ed25519 private key
67    Sign(self::sign::SignArgs),
68    /// Verify a pack's manifest signature
69    Verify(self::verify::VerifyArgs),
70    /// GUI-related tooling
71    #[command(subcommand)]
72    Gui(self::gui::GuiCommand),
73    /// Diagnose a pack archive (.gtpack) or source directory (runs validation)
74    Doctor(self::inspect::InspectArgs),
75    /// Deprecated alias for `doctor`
76    Inspect(self::inspect::InspectArgs),
77    /// Inspect resolved configuration (provenance and warnings)
78    Config(self::config::ConfigArgs),
79    /// Generate a DeploymentPlan from a pack archive or source directory.
80    Plan(self::plan::PlanArgs),
81    /// Provider extension helpers.
82    #[command(subcommand)]
83    Providers(self::providers::ProvidersCommand),
84    /// Resolve component references and write pack.lock.json
85    Resolve(self::resolve::ResolveArgs),
86}
87
88#[derive(Debug, Clone, Parser)]
89pub struct BuildArgs {
90    /// Root directory of the pack (must contain pack.yaml)
91    #[arg(long = "in", value_name = "DIR")]
92    pub input: PathBuf,
93
94    /// Skip running `packc update` before building (default: update first)
95    #[arg(long = "no-update", default_value_t = false)]
96    pub no_update: bool,
97
98    /// Output path for the built Wasm component (legacy; writes a stub)
99    #[arg(long = "out", value_name = "FILE")]
100    pub component_out: Option<PathBuf>,
101
102    /// Output path for the generated manifest (CBOR); defaults to dist/manifest.cbor
103    #[arg(long, value_name = "FILE")]
104    pub manifest: Option<PathBuf>,
105
106    /// Output path for the generated SBOM (legacy; writes a stub JSON)
107    #[arg(long, value_name = "FILE")]
108    pub sbom: Option<PathBuf>,
109
110    /// Output path for the generated & canonical .gtpack archive (default: dist/<pack_dir>.gtpack)
111    #[arg(long = "gtpack-out", value_name = "FILE")]
112    pub gtpack_out: Option<PathBuf>,
113
114    /// Optional path to pack.lock.json (default: <pack_dir>/pack.lock.json)
115    #[arg(long = "lock", value_name = "FILE")]
116    pub lock: Option<PathBuf>,
117
118    /// Bundle strategy for component artifacts (cache=embed wasm, none=refs only)
119    #[arg(long = "bundle", value_enum, default_value = "cache")]
120    pub bundle: crate::build::BundleMode,
121
122    /// When set, the command validates input without writing artifacts
123    #[arg(long)]
124    pub dry_run: bool,
125
126    /// Optional JSON file with additional secret requirements (migration bridge)
127    #[arg(long = "secrets-req", value_name = "FILE")]
128    pub secrets_req: Option<PathBuf>,
129
130    /// Default secret scope to apply when missing (dev-only), format: env/tenant[/team]
131    #[arg(long = "default-secret-scope", value_name = "ENV/TENANT[/TEAM]")]
132    pub default_secret_scope: Option<String>,
133
134    /// Allow OCI component refs in extensions to be tag-based (default requires sha256 digest)
135    #[arg(long = "allow-oci-tags", default_value_t = false)]
136    pub allow_oci_tags: bool,
137}
138
139pub fn run() -> Result<()> {
140    Runtime::new()?.block_on(run_with_cli(Cli::parse(), false))
141}
142
143/// Resolve the logging filter to use for telemetry initialisation.
144pub fn resolve_env_filter(cli: &Cli) -> String {
145    std::env::var("PACKC_LOG").unwrap_or_else(|_| cli.verbosity.clone())
146}
147
148/// Execute the CLI using a pre-parsed argument set.
149pub async fn run_with_cli(cli: Cli, warn_inspect_alias: bool) -> Result<()> {
150    let runtime = runtime::resolve_runtime(
151        Some(std::env::current_dir()?.as_path()),
152        cli.cache_dir.as_deref(),
153        cli.offline,
154        cli.config_override.as_deref(),
155    )?;
156
157    // Install telemetry according to resolved config.
158    crate::telemetry::install_with_config("packc", &runtime.resolved.config.telemetry)?;
159
160    set_current_tenant_ctx(&TenantCtx::new(
161        EnvId::try_from("local").expect("static env id"),
162        TenantId::try_from("packc").expect("static tenant id"),
163    ));
164
165    match cli.command {
166        Command::Build(args) => {
167            build::run(&build::BuildOptions::from_args(args, &runtime)?).await?
168        }
169        Command::Lint(args) => self::lint::handle(args, cli.json)?,
170        Command::Components(args) => self::components::handle(args, cli.json)?,
171        Command::Update(args) => self::update::handle(args, cli.json)?,
172        Command::New(args) => new::handle(args, cli.json, &runtime).await?,
173        Command::Sign(args) => self::sign::handle(args, cli.json)?,
174        Command::Verify(args) => self::verify::handle(args, cli.json)?,
175        Command::Gui(cmd) => self::gui::handle(cmd, cli.json, &runtime).await?,
176        Command::Inspect(args) | Command::Doctor(args) => {
177            if warn_inspect_alias {
178                eprintln!("WARNING: `inspect` is deprecated; use `doctor`.");
179            }
180            self::inspect::handle(args, cli.json, &runtime).await?
181        }
182        Command::Config(args) => self::config::handle(args, cli.json, &runtime)?,
183        Command::Plan(args) => self::plan::handle(&args)?,
184        Command::Providers(cmd) => self::providers::run(cmd)?,
185        Command::Resolve(args) => self::resolve::handle(args, &runtime, true).await?,
186    }
187
188    Ok(())
189}