Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: added mise settings add #2741

Merged
merged 2 commits into from
Oct 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions docs/.vitepress/cli_commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,9 @@ export const commands: { [key: string]: Command } = {
settings: {
hide: false,
subcommands: {
add: {
hide: false,
},
get: {
hide: false,
},
Expand Down
1 change: 1 addition & 0 deletions docs/cli/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ Answer yes to all confirmation prompts
* [`mise self-update [FLAGS] [VERSION]`](/cli/self-update.md)
* [`mise set [--file <FILE>] [-g --global] [ENV_VARS]...`](/cli/set.md)
* [`mise settings [--keys] <SUBCOMMAND>`](/cli/settings.md)
* [`mise settings add <SETTING> <VALUE>`](/cli/settings/add.md)
* [`mise settings get <SETTING>`](/cli/settings/get.md)
* [`mise settings ls [--keys]`](/cli/settings/ls.md)
* [`mise settings set <SETTING> <VALUE>`](/cli/settings/set.md)
Expand Down
1 change: 1 addition & 0 deletions docs/cli/settings.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ Only display key names for each setting

## Subcommands

* [`mise settings add <SETTING> <VALUE>`](/cli/settings/add.md)
* [`mise settings get <SETTING>`](/cli/settings/get.md)
* [`mise settings ls [--keys]`](/cli/settings/ls.md)
* [`mise settings set <SETTING> <VALUE>`](/cli/settings/set.md)
Expand Down
22 changes: 22 additions & 0 deletions docs/cli/settings/add.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# `mise settings add`

**Usage**: `mise settings add <SETTING> <VALUE>`

Adds a setting to the configuration file

Used with an array setting, this will append the value to the array.
This modifies the contents of ~/.config/mise/config.toml

## Arguments

### `<SETTING>`

The setting to set

### `<VALUE>`

The value to set

Examples:

mise settings add disable_hints python_multi
2 changes: 1 addition & 1 deletion docs/cli/settings/set.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

**Usage**: `mise settings set <SETTING> <VALUE>`

**Aliases**: add, create
**Aliases**: create

Add/update a setting

Expand Down
14 changes: 13 additions & 1 deletion mise.usage.kdl
Original file line number Diff line number Diff line change
Expand Up @@ -951,6 +951,18 @@ By default, this command modifies `mise.toml` in the current directory."
}
cmd "settings" help="Manage settings" {
flag "--keys" help="Only display key names for each setting"
cmd "add" help="Adds a setting to the configuration file" {
long_help r"Adds a setting to the configuration file

Used with an array setting, this will append the value to the array.
This modifies the contents of ~/.config/mise/config.toml"
after_long_help r"Examples:

$ mise settings add disable_hints python_multi
"
arg "<SETTING>" help="The setting to set"
arg "<VALUE>" help="The value to set"
}
cmd "get" help="Show a current setting" {
long_help r"Show a current setting

Expand Down Expand Up @@ -981,7 +993,7 @@ but managed separately with `mise aliases`"
flag "--keys" help="Only display key names for each setting"
}
cmd "set" help="Add/update a setting" {
alias "add" "create"
alias "create"
long_help r"Add/update a setting

This modifies the contents of ~/.config/mise/config.toml"
Expand Down
3 changes: 1 addition & 2 deletions src/cli/run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,7 @@ use crate::config::{Config, Settings, CONFIG};
use crate::errors::Error;
use crate::errors::Error::ScriptFailed;
use crate::file::display_path;
use crate::task::Deps;
use crate::task::{GetMatchingExt, Task};
use crate::task::{Deps, GetMatchingExt, Task};
use crate::toolset::{InstallOptions, ToolsetBuilder};
use crate::ui::{ctrlc, prompt, style};
use crate::{dirs, env, file, ui};
Expand Down
43 changes: 43 additions & 0 deletions src/cli/settings/add.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
use eyre::Result;

use crate::cli::settings::set::set;

/// Adds a setting to the configuration file
///
/// Used with an array setting, this will append the value to the array.
/// This modifies the contents of ~/.config/mise/config.toml
#[derive(Debug, clap::Args)]
#[clap(after_long_help = AFTER_LONG_HELP, verbatim_doc_comment)]
pub struct SettingsAdd {
/// The setting to set
#[clap()]
pub setting: String,
/// The value to set
pub value: String,
}

impl SettingsAdd {
pub fn run(self) -> Result<()> {
set(&self.setting, &self.value, true)
}
}

static AFTER_LONG_HELP: &str = color_print::cstr!(
r#"<bold><underline>Examples:</underline></bold>

$ <bold>mise settings add disable_hints python_multi</bold>
"#
);

#[cfg(test)]
pub mod tests {
use crate::test::reset;

#[test]
fn test_settings_add() {
reset();
assert_cli_snapshot!("settings", "add", "disable_hints", "a", @"");
assert_cli_snapshot!("settings", "add", "disable_hints", "b", @"");
assert_cli_snapshot!("settings", "get", "disable_hints", @r#"["a", "b"]"#);
}
}
3 changes: 3 additions & 0 deletions src/cli/settings/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use clap::Subcommand;
use eyre::Result;

mod add;
mod get;
mod ls;
mod set;
Expand All @@ -19,6 +20,7 @@ pub struct Settings {

#[derive(Debug, Subcommand)]
enum Commands {
Add(add::SettingsAdd),
Get(get::SettingsGet),
Ls(ls::SettingsLs),
Set(set::SettingsSet),
Expand All @@ -28,6 +30,7 @@ enum Commands {
impl Commands {
pub fn run(self) -> Result<()> {
match self {
Self::Add(cmd) => cmd.run(),
Self::Get(cmd) => cmd.run(),
Self::Ls(cmd) => cmd.run(),
Self::Set(cmd) => cmd.run(),
Expand Down
91 changes: 56 additions & 35 deletions src/cli/settings/set.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use crate::{env, file};
///
/// This modifies the contents of ~/.config/mise/config.toml
#[derive(Debug, clap::Args)]
#[clap(visible_aliases = ["add", "create"], after_long_help = AFTER_LONG_HELP, verbatim_doc_comment)]
#[clap(visible_aliases = ["create"], after_long_help = AFTER_LONG_HELP, verbatim_doc_comment)]
pub struct SettingsSet {
/// The setting to set
#[clap()]
Expand All @@ -19,44 +19,65 @@ pub struct SettingsSet {

impl SettingsSet {
pub fn run(self) -> Result<()> {
let value = if let Some(meta) = SETTINGS_META.get(&self.setting) {
match meta.type_ {
SettingsType::Bool => parse_bool(&self.value)?,
SettingsType::Integer => parse_i64(&self.value)?,
SettingsType::Duration => parse_duration(&self.value)?,
SettingsType::Url | SettingsType::Path | SettingsType::String => self.value.into(),
SettingsType::ListString => parse_list_by_comma(&self.value)?,
SettingsType::ListPath => parse_list_by_colon(&self.value)?,
}
} else {
bail!("Unknown setting: {}", self.setting);
};
set(&self.setting, &self.value, false)
}
}

let path = &*env::MISE_GLOBAL_CONFIG_FILE;
file::create_dir_all(path.parent().unwrap())?;
let raw = file::read_to_string(path).unwrap_or_default();
let mut config: DocumentMut = raw.parse()?;
if !config.contains_key("settings") {
config["settings"] = toml_edit::Item::Table(toml_edit::Table::new());
}
let settings = config["settings"].as_table_mut().unwrap();
if self.setting.as_str().contains(".") {
let mut parts = self.setting.splitn(2, '.');
let status = settings
.entry(parts.next().unwrap())
.or_insert(toml_edit::Item::Table(toml_edit::Table::new()))
.as_table_mut()
.unwrap();
status.insert(parts.next().unwrap(), toml_edit::Item::Value(value));
} else {
settings.insert(&self.setting, toml_edit::Item::Value(value));
pub fn set(key: &str, value: &str, add: bool) -> Result<()> {
let value = if let Some(meta) = SETTINGS_META.get(key) {
match meta.type_ {
SettingsType::Bool => parse_bool(value)?,
SettingsType::Integer => parse_i64(value)?,
SettingsType::Duration => parse_duration(value)?,
SettingsType::Url | SettingsType::Path | SettingsType::String => value.into(),
SettingsType::ListString => parse_list_by_comma(value)?,
SettingsType::ListPath => parse_list_by_colon(value)?,
}
} else {
bail!("Unknown setting: {}", key);
};

let path = &*env::MISE_GLOBAL_CONFIG_FILE;
file::create_dir_all(path.parent().unwrap())?;
let raw = file::read_to_string(path).unwrap_or_default();
let mut config: DocumentMut = raw.parse()?;
if !config.contains_key("settings") {
config["settings"] = toml_edit::Item::Table(toml_edit::Table::new());
}
let settings = config["settings"].as_table_mut().unwrap();
if key.contains(".") {
let (parent, child) = key.split_once('.').unwrap();

let parent_table = settings
.entry(parent)
.or_insert(toml_edit::Item::Table(toml_edit::Table::new()))
.as_table_mut()
.unwrap();
let value = match parent_table.get(child).map(|c| c.as_array()) {
Some(Some(array)) if add => {
let mut array = array.clone();
array.extend(value.as_array().unwrap().iter().cloned());
array.into()
}
_ => value,
};
parent_table.insert(child, value.into());
} else {
let value = match settings.get(key).map(|c| c.as_array()) {
Some(Some(array)) if add => {
let mut array = array.clone();
array.extend(value.as_array().unwrap().iter().cloned());
array.into()
}
_ => value,
};
settings.insert(key, value.into());
}

// validate
let _: SettingsFile = toml::from_str(&config.to_string())?;
// validate
let _: SettingsFile = toml::from_str(&config.to_string())?;

file::write(path, config.to_string())
}
file::write(path, config.to_string())
}

fn parse_list_by_comma(value: &str) -> Result<toml_edit::Value> {
Expand Down
3 changes: 1 addition & 2 deletions src/cli/tasks/deps.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@ use itertools::Itertools;
use petgraph::dot::Dot;

use crate::config::{Config, Settings};
use crate::task::Deps;
use crate::task::Task;
use crate::task::{Deps, Task};
use crate::ui::style::{self};
use crate::ui::tree::print_tree;

Expand Down
2 changes: 1 addition & 1 deletion src/output.rs
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ macro_rules! hint {
.to_string()
.as_str();
let cmd = console::style($example_cmd).bold().for_stderr();
let disable_single = console::style(format!("mise settings set disable_hints {}", $id))
let disable_single = console::style(format!("mise settings add disable_hints {}", $id))
.bold()
.for_stderr();
let disable_all = console::style("mise settings set disable_hints \"*\"")
Expand Down
Loading