Skip to main content

lux_cli/
config.rs

1use eyre::{eyre, Context, OptionExt, Result};
2use inquire::Confirm;
3use lux_lib::config::{Config, ConfigBuilder};
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()
34                || Confirm::new("Config already exists. Overwrite?")
35                    .with_default(false)
36                    .prompt()
37                    .wrap_err("error prompting to overwrite config")?
38            {
39                std::fs::create_dir_all(
40                    config_file
41                        .parent()
42                        .ok_or_eyre("error getting lux config parent directory")?,
43                )?;
44                let content = if init.default {
45                    let cfg: ConfigBuilder = ConfigBuilder::default().build()?.into();
46                    toml::to_string(&cfg)?
47                } else if init.current {
48                    let cfg: ConfigBuilder = config.into();
49                    toml::to_string(&cfg)?
50                } else {
51                    String::default()
52                };
53                std::fs::write(&config_file, content)?;
54                print!("Config initialised at {}", config_file.display());
55            }
56        }
57        ConfigCmd::Edit => {
58            let config_file = ConfigBuilder::config_file()?;
59            if !config_file.is_file() {
60                return Err(eyre!(
61                    "
62No config file found.
63Use 'lux config init', 'lux config init --default', or 'lux config init --current'
64to initialise a config file.
65"
66                ));
67            }
68            edit::edit_file(config_file)?;
69        }
70        ConfigCmd::Show => {
71            let cfg: ConfigBuilder = config.into();
72            print!("{}", toml::to_string(&cfg)?);
73        }
74    }
75    Ok(())
76}