nedots 0.1.3

A tool to manage configuration files/(ne)dots.
use std::path::Path;

use anyhow::Ok;

use crate::paths::MakeDirs;

#[derive(Debug, clap::Args)]
pub(crate) struct GatherCmd {
    /// Only gather this source. Any unique portion of a path in `sources` is
    /// valid. E.g. given a list of [ "/home/user/.bashrc", "/home/user/.zshrc" ],
    /// ".bashrc" or ".zshrc" may be used as a key.
    key: Option<String>,
}

impl super::Command for GatherCmd {
    fn run(
        &self,
        _: &super::nedots::RootCmd,
        config: &crate::config::Config,
    ) -> anyhow::Result<()> {
        if let Some(key) = &self.key {
            match config.get_sources_as_hashmap().get(key.as_str()) {
                Some(val) => {
                    gather(val, &config.get_dst_from_src(val)?)?;
                }
                None => {
                    log::error!("❌ {} not found", key);
                }
            }
        } else {
            for source in &config.sources {
                gather(source, &config.get_dst_from_src(source)?)?;
            }
        }

        Ok(())
    }
}

fn gather(src: &Path, dst: &Path) -> anyhow::Result<()> {
    gather_file(src, dst)?;
    log::info!(
        "👍 Gathered {} -> {}",
        console::style(src.display()).green().bold(),
        console::style(dst.display()).green().bold()
    );
    Ok(())
}

pub(crate) fn gather_file(src: &Path, dst: &Path) -> anyhow::Result<()> {
    log::trace!("Gathering {} -> {}", src.display(), dst.display());

    if src.is_dir() {
        // When given a directory as `src`, we've been asked to copy the
        // contents of a directory into the `dst` path - we want to create
        // the same directory structure as defined in `src`, so we call `gather`
        // once again, this time with the `src` directory name appended to
        // `dst`.
        for entry in src.read_dir()? {
            let path = entry?.path();
            gather_file(&path, &dst.join(path.file_name().unwrap()))?;
        }
    } else {
        // When we have a file as `src`, we'll quickly sanity check that the
        // file has a file_name. We're going to panic here because this should
        // never happen.
        if src.file_name().is_none() {
            log::error!(
                "{} is not a directory, and has no file_name!",
                src.display()
            );
            panic!()
        };

        let parent = dst.parent().unwrap();
        if !parent.exists() {
            parent.make_all_dirs()?;
        }

        if let Err(err) = std::fs::copy(src, dst) {
            log::warn!("{}", err);
            log::warn!("{} => {}", src.display(), dst.display());
        }
    }

    Ok(())
}