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
//! Configuration processing
//!
//! This module is the root of processing tree of TOML configuration file.

use super::workspace::WSConfig;
use super::ConfigOptions;
use super::IDMaps;
use super::{Globals, GlobalsFinal, GlobalsLogReady, LogStatus};
use anyhow::Result as AResult;
use serde::Deserialize;
use std::collections::HashMap;
use std::path::PathBuf;

#[derive(Deserialize)]
struct Config {
    workspace: WSConfig,
    vars: Vars,
    idmaps: IDMaps,
}

#[derive(Deserialize, Debug)]
pub(super) struct Vars {
    paths: HashMap<String, String>,
}

impl GlobalsLogReady {
    pub fn config(self, cfg: String) -> AResult<GlobalsFinal> {
        let deser: Config = toml::from_str(&cfg)?;
        let vars = deser.vars;
        let idmaps = deser.idmaps;
        let config_text = cfg;
        let workspace = deser.workspace.verify(&vars)?;
        let cfg = ConfigOptions {
            vars,
            idmaps,
            config_text,
            workspace,
        };
        let cli = self.cli;
        let multi = self.multi;
        Ok(GlobalsFinal { cfg, cli, multi })
    }
}

impl Vars {
    pub(super) fn resolve_path(&self, path: &str) -> PathBuf {
        let mut newstr = path.to_string();
        for (var, val) in self.paths.iter() {
            newstr = newstr.replace(&format!("${{{var}}}"), val);
        }
        newstr = shellexpand::tilde(&newstr).to_string();
        PathBuf::from(newstr)
    }
}

impl<T: LogStatus> Globals<T, ConfigOptions> {
    #[inline]
    pub fn resolve_path(&self, path: &str) -> PathBuf {
        self.cfg.vars.resolve_path(path)
    }

    #[inline]
    pub fn text(&self) -> &str {
        &self.cfg.config_text
    }
}