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
//! Global CLI parsing
//!
//! This section contains the top most layer of CLI parsing, including global options. Subcommands
//! and their options are managed by cli.rs in corresponding submodules.

use super::{CliOptions, GlobalsNew, NotReady};
use crate::SubCommands;
use clap::{ArgAction, Args, Parser};

#[derive(Parser)]
#[command(author, version, about, long_about = None)]
pub struct Cli {
    #[command(flatten)]
    opts: Options,

    #[command(subcommand)]
    subcmd: SubCommands,
}

#[derive(Args)]
struct Options {
    /// Provide extra information (upto 2 levels)
    #[arg(short, long, action = ArgAction::Count, global = true, conflicts_with = "quiet")]
    verbose: u8,

    /// Supress all info output, except errors
    #[arg(short, long, global = true)]
    quiet: bool,

    /// Display steps to be taken without executing it (implies verbose)
    #[arg(short = 'n', long, global = true, conflicts_with = "quiet")]
    dry_run: bool,
}

impl Cli {
    /// Collect all global information and emit a struct
    pub fn globals(&self) -> GlobalsNew {
        use log::LevelFilter::*;
        let dry_run = self.opts.dry_run;
        let verbose = self.opts.verbose;
        let quiet = self.opts.quiet;

        let log_level = if verbose >= 2 {
            Trace
        } else if verbose == 1 || dry_run {
            Debug
        } else if quiet {
            Warn
        } else {
            Info
        };

        let cli = CliOptions { dry_run, log_level };
        GlobalsNew {
            cli,
            multi: NotReady,
            cfg: NotReady,
        }
    }

    /// Yield subcommand and invalidate the parsed struct
    pub fn subcmd(self) -> SubCommands {
        self.subcmd
    }
}