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 processing for archive extractor

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

/// Extract stage-3 archive into empty chroot
#[derive(Args)]
pub struct SubCmdArgs {
    /// Archive to extract from
    archive: PathBuf,

    /// Chroot to extract into
    chroot: PathBuf,
}

impl SubCmdArgs {
    pub fn handle(&self, globals: GlobalsFinal) -> AResult<()> {
        if !self.archive.is_file() {
            let msg = format!("Couldn't find archive file {}", self.archive.display());
            log::error!("{msg}");
            anyhow::bail!(msg);
        }
        let chroot = globals.chroot(&self.chroot).verify(true)?;

        // Don't overwrite a non-empty chroot
        let chrdir: &Path = &chroot;
        if chrdir.read_dir()?.count() != 0 {
            let msg = format!("Chroot {} is not empty", chroot);
            log::error!("{msg}");
            anyhow::bail!(msg);
        }

        let params = bwrap::BWParams {
            chroot,
            archive: &self.archive,
        };
        params.dispatch(&globals)?;
        Ok(())
    }
}