Skip to main content

lux_cli/
config.rs

1use inquire::Confirm;
2use lux_lib::config::{Config, ConfigBuilder};
3use miette::{miette, Context, IntoDiagnostic, Result};
4
5#[derive(clap::Subcommand)]
6pub enum ConfigCmd {
7    /// Initialise a new config file
8    Init(Init),
9    /// Edit the current config file.
10    Edit,
11    /// Show the current config.
12    /// This includes options picked up from CLI flags.
13    Show,
14}
15
16#[derive(clap::Args)]
17pub struct Init {
18    /// Initialise the default config for this system.
19    /// If this flag is not set, an empty config file will be created.
20    #[arg(long, conflicts_with = "current")]
21    default: bool,
22
23    /// Initialise the config file using the current config,
24    /// with options picked up from CLI flags.
25    #[arg(long, conflicts_with = "default")]
26    current: bool,
27}
28
29pub fn config(cmd: ConfigCmd, config: Config) -> Result<()> {
30    match cmd {
31        ConfigCmd::Init(init) => {
32            let config_file = ConfigBuilder::config_file()?;
33            if !config_file.is_file() && !config.no_prompt()
34                || Confirm::new("Config already exists. Overwrite?")
35                    .with_default(false)
36                    .prompt()
37                    .into_diagnostic()
38                    .wrap_err("error prompting to overwrite config")?
39            {
40                std::fs::create_dir_all(
41                    config_file
42                        .parent()
43                        .ok_or_else(|| miette!("error getting lux config parent directory"))?,
44                )
45                .into_diagnostic()?;
46                let content = if init.default {
47                    let cfg: ConfigBuilder = ConfigBuilder::default().build()?.into();
48                    toml::to_string(&cfg).into_diagnostic()?
49                } else if init.current {
50                    let cfg: ConfigBuilder = config.into();
51                    toml::to_string(&cfg).into_diagnostic()?
52                } else {
53                    String::default()
54                };
55                std::fs::write(&config_file, content).into_diagnostic()?;
56                print!("Config initialised at {}", config_file.display());
57            }
58        }
59        ConfigCmd::Edit => {
60            let config_file = ConfigBuilder::config_file()?;
61            if !config_file.is_file() {
62                return Err(miette!(
63                    "
64No config file found.
65Use 'lux config init', 'lux config init --default', or 'lux config init --current'
66to initialise a config file.
67"
68                ));
69            }
70            edit::edit_file(config_file).into_diagnostic()?;
71        }
72        ConfigCmd::Show => {
73            let cfg: ConfigBuilder = config.into();
74            print!("{}", toml::to_string(&cfg).into_diagnostic()?);
75        }
76    }
77    Ok(())
78}