use crate::cli::config::ConfigCommand;
use crate::config::{doctor, keys, paths, secret, store, Config, Fallback, KeySpec, Resolved};
use crate::error::{Failure, Result};
use crate::output::Envelope;
use serde_json::{json, Value};
use std::path::Path;
pub fn execute(
command: &ConfigCommand,
config_dir: Option<&Path>,
dry_run: bool,
) -> Result<Envelope> {
match command {
ConfigCommand::Set(args) => set(
config_dir,
required(args.key.as_deref(), "key", "config set output.format json")?,
required(
args.value.as_deref(),
"value",
"config set output.format json",
)?,
dry_run,
),
ConfigCommand::Get(args) => get(
config_dir,
required(args.key.as_deref(), "key", "config get output.format")?,
),
ConfigCommand::List(args) => list(config_dir, args.stored_only),
ConfigCommand::Path => path(config_dir),
ConfigCommand::Unset(args) => unset(
config_dir,
required(args.key.as_deref(), "key", "config unset output.format")?,
dry_run,
),
ConfigCommand::Doctor => diagnose(config_dir),
}
}
fn required<'a>(given: Option<&'a str>, what: &str, example: &str) -> Result<&'a str> {
given.ok_or_else(|| {
Failure::usage(
"config.argument_missing",
format!("this command needs a {what} to work on"),
)
.with_detail("detail", what)
.with_hint(format!("as in `{example}`"))
})
}
fn set(config_dir: Option<&Path>, name: &str, raw: &str, dry_run: bool) -> Result<Envelope> {
let entry = keys::spec(name).ok_or_else(|| keys::unknown_key(name))?;
let value = keys::validate(entry.name, raw)?;
let file = paths::config_file(config_dir)?;
if !dry_run {
store::store(&file, entry.name, raw)?;
}
Ok(Envelope::new(
"config set",
json!({
"key": entry.name,
"value": rendered(entry, Some(&value)),
"path": file.display().to_string(),
"simulated": dry_run,
}),
))
}
fn get(config_dir: Option<&Path>, name: &str) -> Result<Envelope> {
let entry = keys::spec(name).ok_or_else(|| keys::unknown_key(name))?;
let config = Config::load(config_dir)?;
let resolved = config.resolve(entry.name)?;
if resolved.value.is_none() {
return Err(no_value(entry));
}
Ok(Envelope::new("config get", row(entry, &resolved)))
}
fn list(config_dir: Option<&Path>, stored_only: bool) -> Result<Envelope> {
let config = Config::load(config_dir)?;
let mut rows = Vec::new();
for (entry, resolved) in config.resolve_all() {
if stored_only && !config.is_stored(entry.name) {
continue;
}
match resolved {
Ok(resolved) => rows.push(row(entry, &resolved)),
Err(failure) => rows.push(json!({
"key": entry.name,
"about": entry.about,
"problem": failure.message(),
})),
}
}
Ok(Envelope::new("config list", json!({ "rows": rows })))
}
fn path(config_dir: Option<&Path>) -> Result<Envelope> {
let file = paths::config_file(config_dir)?;
let directory = paths::config_dir(config_dir)?;
Ok(Envelope::new(
"config path",
json!({
"path": file.display().to_string(),
"directory": directory.display().to_string(),
"exists": file.exists(),
}),
))
}
fn unset(config_dir: Option<&Path>, name: &str, dry_run: bool) -> Result<Envelope> {
let entry = keys::spec(name).ok_or_else(|| keys::unknown_key(name))?;
let file = paths::config_file(config_dir)?;
let removed = if dry_run {
Config::load(config_dir)?.is_stored(entry.name)
} else {
store::remove(&file, entry.name)?
};
let fallback = entry.default_value()?;
Ok(Envelope::new(
"config unset",
json!({
"key": entry.name,
"removed": removed,
"value": rendered(entry, fallback.as_ref()),
"origin": crate::config::Origin::Default.as_str(),
"simulated": dry_run,
}),
))
}
fn diagnose(config_dir: Option<&Path>) -> Result<Envelope> {
let report = doctor::run(config_dir)?;
let findings = serde_json::to_value(&report.findings).map_err(|error| {
Failure::config(
"config.report_not_serialisable",
"the diagnosis could not be written out",
)
.with_cause(error.to_string())
})?;
Ok(Envelope::new(
"config doctor",
json!({
"path": report.file,
"exists": report.file_exists,
"clean": report.is_clean(),
"rows": findings,
}),
))
}
fn row(entry: &KeySpec, resolved: &Resolved) -> Value {
json!({
"key": entry.name,
"value": rendered(entry, resolved.value.as_ref()),
"origin": resolved.origin.as_str(),
"domain": entry.domain.described(),
"about": entry.about,
})
}
fn rendered(entry: &KeySpec, value: Option<&keys::Value>) -> Value {
let Some(value) = value else {
return Value::Null;
};
if is_credential(entry.name) {
return Value::from(secret::redact(&value.to_string()));
}
Value::from(value)
}
fn is_credential(name: &str) -> bool {
name.starts_with("secret.") && name != "secret.storage_mode"
}
fn no_value(entry: &KeySpec) -> Failure {
let (decided, decided_by) = match entry.fallback {
Fallback::Server => (
"server",
"the server decides this one, so it has no stored value",
),
Fallback::Host => (
"host",
"the host decides this one, so it has no stored value",
),
Fallback::Builtin(_) | Fallback::Absent => ("unstored", "no value was ever stored for it"),
};
Failure::absence("config.no_value", format!("`{}`", entry.name))
.with_detail("detail", entry.name)
.with_detail("decided", decided)
.with_detail("setting", entry.name)
.with_hint(format!(
"{decided_by}; use `config set {}` to give it one",
entry.name
))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::cli::config::{KeyArgs, ListArgs, SetArgs};
fn scratch() -> tempfile::TempDir {
tempfile::tempdir().expect("scratch directory")
}
fn run(dir: &tempfile::TempDir, command: &ConfigCommand) -> Result<Envelope> {
execute(command, Some(dir.path()), false)
}
#[test]
fn a_simulated_write_changes_nothing_on_disk() {
let dir = scratch();
let asked = setting("output.format", "tsv");
let answered = execute(&asked, Some(dir.path()), true).expect("the value is admissible");
assert_eq!(answered.data["simulated"], true);
assert_eq!(answered.data["value"], "tsv");
let stored = Config::load(Some(dir.path())).expect("the location loads");
assert!(
!stored.is_stored("output.format"),
"the simulation wrote the value it was only asked to describe"
);
}
#[test]
fn a_simulated_write_still_checks_the_value() {
let dir = scratch();
let asked = setting("output.format", "yaml");
execute(&asked, Some(dir.path()), true).expect_err("no such shape is published");
}
#[test]
fn a_simulated_removal_leaves_the_value_where_it_was() {
let dir = scratch();
run(&dir, &setting("output.format", "tsv")).expect("stores");
let asked = ConfigCommand::Unset(KeyArgs {
key: Some("output.format".to_owned()),
});
let answered = execute(&asked, Some(dir.path()), true).expect("the key exists");
assert_eq!(answered.data["simulated"], true);
assert_eq!(
answered.data["removed"], true,
"the simulation must still say the key was there to remove"
);
let stored = Config::load(Some(dir.path())).expect("the location loads");
assert!(
stored.is_stored("output.format"),
"the simulation removed the value it was only asked to describe"
);
}
fn setting(key: &str, value: &str) -> ConfigCommand {
ConfigCommand::Set(SetArgs {
key: Some(key.to_owned()),
value: Some(value.to_owned()),
})
}
fn reading(key: &str) -> ConfigCommand {
ConfigCommand::Get(KeyArgs {
key: Some(key.to_owned()),
})
}
#[test]
fn a_written_setting_is_read_back_with_its_origin() {
let dir = scratch();
run(&dir, &setting("output.format", "ndjson")).expect("writes");
let envelope = run(&dir, &reading("output.format")).expect("reads");
assert_eq!(envelope.data["value"], "ndjson");
assert_eq!(envelope.data["origin"], "stored");
}
#[test]
fn nothing_written_means_the_builtin_value_is_reported() {
let dir = scratch();
let envelope = run(&dir, &reading("limits.retries")).expect("reads");
assert_eq!(envelope.data["value"], 2);
assert_eq!(envelope.data["origin"], "default");
}
#[test]
fn a_value_outside_the_domain_never_reaches_the_file() {
let dir = scratch();
let failure = run(&dir, &setting("output.format", "yaml")).expect_err("must refuse");
assert_eq!(failure.code(), "config.value_outside_domain");
let file = paths::config_file(Some(dir.path())).expect("location");
assert!(!file.exists(), "a refused value created the file anyway");
}
#[test]
fn an_unknown_setting_is_an_absence_of_that_name() {
let dir = scratch();
let failure = run(&dir, &reading("output.nonsense")).expect_err("must refuse");
assert_eq!(failure.code(), "config.unknown_key");
}
#[test]
fn the_list_uses_the_payload_key_the_output_pipeline_looks_for() {
let dir = scratch();
let envelope =
run(&dir, &ConfigCommand::List(ListArgs { stored_only: false })).expect("lists");
assert_eq!(envelope.payload_array_key(), Some("rows"));
assert_eq!(
envelope.data["rows"].as_array().map(Vec::len),
Some(keys::all().len())
);
}
#[test]
fn listing_only_what_was_written_leaves_the_rest_out() {
let dir = scratch();
run(&dir, &setting("log.to_file", "true")).expect("writes");
let envelope =
run(&dir, &ConfigCommand::List(ListArgs { stored_only: true })).expect("lists");
let rows = envelope.data["rows"].as_array().expect("array");
assert_eq!(rows.len(), 1);
assert_eq!(rows[0]["key"], "log.to_file");
assert_eq!(rows[0]["origin"], "stored");
}
#[test]
fn removing_a_setting_returns_it_to_the_builtin_value() {
let dir = scratch();
run(&dir, &setting("limits.retries", "9")).expect("writes");
let envelope = run(
&dir,
&ConfigCommand::Unset(KeyArgs {
key: Some("limits.retries".to_owned()),
}),
)
.expect("removes");
assert_eq!(envelope.data["removed"], true);
assert_eq!(envelope.data["value"], 2);
let after = run(&dir, &reading("limits.retries")).expect("reads");
assert_eq!(after.data["origin"], "default");
}
#[test]
fn removing_something_never_written_says_so_without_failing() {
let dir = scratch();
let envelope = run(
&dir,
&ConfigCommand::Unset(KeyArgs {
key: Some("limits.retries".to_owned()),
}),
)
.expect("removes nothing");
assert_eq!(envelope.data["removed"], false);
}
#[test]
fn a_setting_decided_by_the_server_reports_the_absence_of_a_value() {
let dir = scratch();
let failure = run(&dir, &reading("conn.timezone")).expect_err("must report");
assert_eq!(failure.code(), "config.no_value");
assert_eq!(failure.category(), crate::error::Category::Absence);
}
#[test]
fn the_location_is_reported_with_whether_anything_is_there() {
let dir = scratch();
let before = run(&dir, &ConfigCommand::Path).expect("reports");
assert_eq!(before.data["exists"], false);
run(&dir, &setting("output.format", "json")).expect("writes");
let after = run(&dir, &ConfigCommand::Path).expect("reports");
assert_eq!(after.data["exists"], true);
}
#[test]
fn the_diagnosis_lists_its_findings_under_the_published_payload_key() {
let dir = scratch();
let file = paths::config_file(Some(dir.path())).expect("location");
std::fs::create_dir_all(dir.path()).expect("directory");
std::fs::write(&file, "\"output.nonsense\" = \"1\"\n").expect("writes");
let envelope = run(&dir, &ConfigCommand::Doctor).expect("examines");
assert_eq!(envelope.data["clean"], false);
assert_eq!(envelope.payload_array_key(), Some("rows"));
assert_eq!(envelope.data["rows"][0]["kind"], "unknown_key");
}
#[test]
fn a_clean_location_is_reported_as_clean() {
let dir = scratch();
run(&dir, &setting("output.format", "json")).expect("writes");
let envelope = run(&dir, &ConfigCommand::Doctor).expect("examines");
assert_eq!(envelope.data["clean"], true);
}
}