use clap::Parser;
use hermit::Error;
use hermit::ExitStatus;
use crate::global_opts::GlobalOpts;
use crate::podman_store::PodmanStore;
use crate::podman_store::ResolvedImage;
use crate::run::RunOpts;
#[derive(Debug, Parser)]
pub struct OciOpts {
#[clap(subcommand)]
command: OciSubcommand,
}
#[derive(Debug, Parser)]
enum OciSubcommand {
#[clap(name = "ls")]
Ls(LsOpts),
#[clap(name = "inspect")]
Inspect(InspectOpts),
#[clap(name = "pull")]
Pull(PullOpts),
#[clap(name = "run", trailing_var_arg = true)]
Run(Box<OciRunOpts>),
}
#[derive(Debug, Parser)]
struct LsOpts {
#[clap(long, short = 'a')]
all: bool,
}
#[derive(Debug, Parser)]
struct InspectOpts {
image: String,
}
#[derive(Debug, Parser)]
struct PullOpts {
image: String,
}
#[derive(Debug, Parser)]
struct OciRunOpts {
#[clap(value_name = "IMAGE")]
image_ref: String,
#[clap(long)]
pull: bool,
#[clap(flatten)]
run: RunOpts,
}
fn require_store() -> Result<PodmanStore, Error> {
PodmanStore::probe()?.ok_or_else(|| {
Error::msg(
"No local OCI image store found. `hermit oci` reads the \
containers/storage store that podman and buildah share, so it \
needs a rootless `podman` on PATH.",
)
})
}
impl OciOpts {
pub(crate) fn capture_default_run_epoch(
&mut self,
capture_now: impl FnOnce() -> std::time::SystemTime,
) {
if let OciSubcommand::Run(opts) = &mut self.command {
opts.run.capture_default_epoch(capture_now);
}
}
#[cfg(test)]
pub(crate) fn run_epoch_capture_for_test(&self) -> (String, bool, bool) {
let OciSubcommand::Run(opts) = &self.command else {
panic!("expected oci run")
};
let (epoch, captured) = opts.run.epoch_capture_for_test();
(epoch, captured, opts.run.reports_virtual_epoch_for_test())
}
pub fn main(&mut self, global: &GlobalOpts) -> Result<ExitStatus, Error> {
match &mut self.command {
OciSubcommand::Ls(opts) => opts.main(),
OciSubcommand::Inspect(opts) => opts.main(),
OciSubcommand::Pull(opts) => opts.main(),
OciSubcommand::Run(opts) => opts.main(global),
}
}
}
impl LsOpts {
fn main(&self) -> Result<ExitStatus, Error> {
let store = require_store()?;
let images = store.list(self.all)?;
if images.is_empty() {
println!("No images in the local store at {}", store.graph_root());
return Ok(ExitStatus::SUCCESS);
}
println!("{:<14} {:<48} {:>10}", "IMAGE ID", "NAME", "SIZE");
for image in &images {
println!(
"{:<14} {:<48} {:>10}",
short_id(&image.id),
image.display_name(),
human_size(image.size),
);
}
Ok(ExitStatus::SUCCESS)
}
}
impl InspectOpts {
fn main(&self) -> Result<ExitStatus, Error> {
let store = require_store()?;
let image = store.resolve(&self.image)?;
report(&store, &image)?;
Ok(ExitStatus::SUCCESS)
}
}
impl PullOpts {
fn main(&self) -> Result<ExitStatus, Error> {
let store = require_store()?;
let image = store.pull(&self.image)?;
report(&store, &image)?;
Ok(ExitStatus::SUCCESS)
}
}
fn report(store: &PodmanStore, image: &ResolvedImage) -> Result<(), Error> {
println!("reference: {}", image.reference);
println!("image id: {}", image.id);
println!(
"digest: {}",
image
.digest
.as_deref()
.unwrap_or("<none> (locally built; not pushed or pulled)")
);
println!("store: {}", store.graph_root());
let config = store.config(image)?;
println!(
"workdir: {}",
config
.workdir
.as_deref()
.unwrap_or("/ (image declares none)")
);
if config.env.is_empty() {
println!("env: <none declared>");
} else {
println!("env:");
for (key, value) in &config.env {
println!(" {key}={value}");
}
}
if !config.entrypoint.is_empty() {
println!("entrypoint: {:?}", config.entrypoint);
}
if !config.cmd.is_empty() {
println!(
"cmd: {:?} (informational; hermit requires an explicit program)",
config.cmd
);
}
match store.overlay_dirs(image) {
Ok(dirs) => {
println!("layers: {} (topmost first)", dirs.len());
for dir in &dirs {
println!(" {dir}");
}
}
Err(e) => println!("layers: <unavailable> ({e})"),
}
Ok(())
}
impl OciRunOpts {
fn main(&mut self, global: &GlobalOpts) -> Result<ExitStatus, Error> {
if let Some(flag) = self.run.image() {
return Err(Error::msg(format!(
"`hermit oci run` takes the image as a positional argument; drop \
`--image {flag}` and pass {:?} once. `--image` on `hermit run` \
bypasses reference resolution, which is what `hermit oci run` \
exists to do.",
self.image_ref
)));
}
let store = require_store()?;
let image = if self.pull {
store.pull(&self.image_ref)?
} else {
store.resolve(&self.image_ref)?
};
tracing::info!(
"Resolved OCI reference {} to image id {}",
image.reference,
image.id
);
self.run.set_image(image.id.clone());
self.run.main(global)
}
}
fn short_id(id: &str) -> &str {
id.get(..12).unwrap_or(id)
}
fn human_size(bytes: u64) -> String {
const UNITS: [(&str, u64); 4] = [
("GB", 1_000_000_000),
("MB", 1_000_000),
("kB", 1_000),
("B", 1),
];
for (suffix, scale) in UNITS {
if bytes >= scale {
return if scale == 1 {
format!("{bytes} {suffix}")
} else {
format!("{:.1} {suffix}", bytes as f64 / scale as f64)
};
}
}
"0 B".to_string()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn short_id_truncates_to_podman_width_without_panicking() {
let id = "1ee23df5e47b5b7331304af929f5461f9f516f5c166c3031832d2adfd22f323c";
assert_eq!(short_id(id), "1ee23df5e47b");
assert_eq!(short_id("abc"), "abc");
assert_eq!(short_id(""), "");
}
#[test]
fn human_size_uses_the_decimal_convention_podman_prints() {
assert_eq!(human_size(0), "0 B");
assert_eq!(human_size(512), "512 B");
assert_eq!(human_size(1_500), "1.5 kB");
assert_eq!(human_size(80_659_122), "80.7 MB");
assert_eq!(human_size(2_500_000_000), "2.5 GB");
}
#[test]
fn oci_run_parses_image_then_forwarded_run_args() {
let opts = OciOpts::try_parse_from([
"oci",
"run",
"restored-ubuntu:24.04",
"--strict",
"--",
"/bin/echo",
"hi",
])
.expect("oci run should parse an image followed by run options");
match opts.command {
OciSubcommand::Run(run) => {
assert_eq!(run.image_ref, "restored-ubuntu:24.04");
assert!(!run.pull, "--pull must default off so run never downloads");
}
other => panic!("expected the run subcommand, got {other:?}"),
}
}
#[test]
fn oci_ls_defaults_to_hiding_intermediate_images() {
let opts = OciOpts::try_parse_from(["oci", "ls"]).expect("oci ls should parse");
match opts.command {
OciSubcommand::Ls(ls) => assert!(!ls.all),
other => panic!("expected the ls subcommand, got {other:?}"),
}
let opts = OciOpts::try_parse_from(["oci", "ls", "--all"]).expect("oci ls --all");
match opts.command {
OciSubcommand::Ls(ls) => assert!(ls.all),
other => panic!("expected the ls subcommand, got {other:?}"),
}
}
}