ayun_console/commands/
publish.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
use crate::{
    traits::{ApplicationTrait, CommandTrait},
    STYLES,
};
use ayun_core::{support::copy, Error, Result};
use clap::{ArgMatches, Command};
use std::{path::PathBuf, str::FromStr};

pub enum Publish {
    Config,
    Deploy,
}

impl FromStr for Publish {
    type Err = Error;

    fn from_str(str: &str) -> std::result::Result<Self, Self::Err> {
        match str {
            "config" => Ok(Self::Config),
            "deploy" => Ok(Self::Deploy),
            _ => Err(Error::Message("Invalid publish command".to_string())),
        }
    }
}

impl CommandTrait for Publish {
    fn command() -> Command {
        Command::new("publish")
            .styles(STYLES)
            .about("Publish stub files from crate")
            .subcommand(Command::new("config").about("Publish config file from crate"))
            .subcommand(Command::new("deploy").about("Publish deploy file from crate"))
    }

    fn handle<A: ApplicationTrait>(arg_matches: ArgMatches) -> Result<()> {
        match arg_matches.subcommand() {
            Some((name, _arg_matches)) => match Self::from_str(name)? {
                Self::Config => publish("stubs/config/.config.toml.example", ".config.toml")?,
                Self::Deploy => publish("stubs/deploy/docker", "./")?,
            },
            None => Self::command().print_help()?,
        }

        Ok(())
    }
}

fn stub_path(str: &str) -> Result<PathBuf> {
    Ok(PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(str))
}

fn publish(from: &str, to: &str) -> Result<()> {
    let to = PathBuf::from(to);

    tracing::info!("publishing from {:?} to {:?}", from, to);

    copy(&stub_path(from)?, &to)?;

    tracing::info!("published success");

    Ok(())
}