genpac 0.1.0

Sandbox for Gentoo ebuild development using bubblewrap
// Copyright (C) 2023 Gokul Das B
// SPDX-License-Identifier: GPL-3.0-or-later
//! CLI module for sandbox subcommand

use super::{BWParams, ModConfig};
use crate::GlobalsFinal;
use anyhow::Result as AResult;
use clap::Args;
use std::path::PathBuf;

/// Enter sandboxed environment
#[derive(Args)]
pub struct SubCmdArgs {
    /// Chroot to enter
    #[arg(value_name = "CHROOT")]
    path: PathBuf,

    /// Command to execute inside sandbox (default from config file)
    #[arg(trailing_var_arg = true, num_args(0..))]
    command: Vec<String>,
}

impl SubCmdArgs {
    pub fn handle(&self, globals: GlobalsFinal) -> AResult<()> {
        let sboxcfg = ModConfig::new(&globals)?;

        // Verify chroot
        let chroot = match globals.chroot(&self.path).verify(true) {
            Ok(x) => x,
            Err(msg) => anyhow::bail!(msg),
        };

        // Use command from CLI if supplied. If not, use from config file
        let command = if self.command.is_empty() {
            sboxcfg.command.clone()
        } else {
            self.command.join(" ")
        };

        let tmpfs_size = sboxcfg.tmpfs_size;
        let mounts = sboxcfg
            .mountpaths()?
            .map(|(x, y)| (x.clone(), y.clone()))
            .collect();
        let bwparams = BWParams {
            chroot,
            tmpfs_size,
            command,
            mounts,
        };

        bwparams.dispatch(&globals)?;
        Ok(())
    }
}