use std::io::Write;
use std::path::Path;
use serde_json::{Value, json};
use crate::config::{Config, ValueSource};
use super::{Cli, ConfigAction, Failure, Fallible, Outcome, write_envelope};
const DEFAULT_TOML: &str = include_str!("../../config/default.toml");
pub(super) fn run(cli: &Cli, action: &ConfigAction, out: &mut dyn Write) -> Fallible<Outcome> {
match action {
ConfigAction::Show => show(cli, out),
ConfigAction::Init { force } => init(cli, *force, out),
}
}
fn show(cli: &Cli, out: &mut dyn Write) -> Fallible<Outcome> {
let cfg = super::resolve_config(cli)?;
let read_from = config_file_read(&cfg);
if cli.json {
let mut object = serde_json::Map::new();
for (key, source) in cfg.sources() {
object.insert(
key.to_string(),
json!({
"value": value_of(&cfg, key)?,
"source": kind_of(&source),
"origin": origin_of(&source),
}),
);
}
write_envelope(out, "config", read_from.as_deref(), Value::Object(object))?;
return Ok(Outcome::Found);
}
if cli.quiet {
return Ok(Outcome::Found);
}
for (key, source) in cfg.sources() {
writeln!(
out,
"{key} = {} # {}",
value_of(&cfg, key)?,
describe(&source)
)?;
}
Ok(Outcome::Found)
}
fn config_file_read(cfg: &Config) -> Option<String> {
if let Some(path) = cfg.sources().find_map(|(_, source)| match source {
ValueSource::File(path) => Some(path),
_ => None,
}) {
return Some(path.display().to_string());
}
cfg.config_file()
.filter(|path| path.exists())
.map(|path| path.display().to_string())
}
fn value_of(cfg: &Config, key: &str) -> Fallible<Value> {
Ok(match key {
"data_dir" => json!(cfg.data_dir().display().to_string()),
"model_dir" => json!(cfg.model_dir().display().to_string()),
"models.embedding" => json!(cfg.embedding_model()),
"summary.n" => json!(cfg.summary_n()),
"summary.method" => json!(cfg.summary_method()),
"keyphrases.n" => json!(cfg.keyphrases_n()),
"keyphrases.method" => json!(cfg.keyphrases_method()),
"clusters.threshold" => json!(cfg.clusters_threshold()),
other => {
return Err(Failure::refused(
"config_key_unrendered",
format!(
"config show cannot render `{other}`: the key is resolved but has no reader here"
),
));
}
})
}
fn describe(source: &ValueSource) -> String {
match source {
ValueSource::Argument => "command line".to_string(),
ValueSource::Environment(name) => format!("environment variable `{name}`"),
ValueSource::File(path) => path.display().to_string(),
ValueSource::Default => "default".to_string(),
}
}
fn kind_of(source: &ValueSource) -> &'static str {
match source {
ValueSource::Argument => "argument",
ValueSource::Environment(_) => "environment",
ValueSource::File(_) => "file",
ValueSource::Default => "default",
}
}
fn origin_of(source: &ValueSource) -> Value {
match source {
ValueSource::Environment(name) => json!(name),
ValueSource::File(path) => json!(path.display().to_string()),
ValueSource::Argument | ValueSource::Default => Value::Null,
}
}
fn init(cli: &Cli, force: bool, out: &mut dyn Write) -> Fallible<Outcome> {
let path = Config::config_file_path().ok_or_else(|| {
Failure::refused(
"no_config_file_location",
"cannot locate a config file: set MATRA_CONFIG_FILE, XDG_CONFIG_HOME, or HOME",
)
})?;
write_defaults(&path, force)?;
let shown = path.display().to_string();
if cli.json {
write_envelope(out, "config", Some(&shown), json!({ "path": shown }))?;
} else if !cli.quiet {
writeln!(out, "{shown}")?;
}
Ok(Outcome::Found)
}
fn write_defaults(path: &Path, force: bool) -> Fallible<()> {
if !force && path.exists() {
return Err(Failure::refused(
"config_file_exists",
format!(
"{} already exists; pass --force to overwrite it",
path.display()
),
));
}
let parent = path
.parent()
.filter(|p| !p.as_os_str().is_empty())
.unwrap_or(Path::new("."));
std::fs::create_dir_all(parent)
.map_err(|e| io_at("create the config directory", parent, &e))?;
let temp = parent.join(format!(
".{}.{}.tmp",
path.file_name()
.and_then(|n| n.to_str())
.unwrap_or("config.toml"),
std::process::id()
));
let mut file = std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&temp)
.map_err(|e| io_at("create the temporary file", &temp, &e))?;
let written = file
.write_all(DEFAULT_TOML.as_bytes())
.and_then(|()| file.sync_all());
drop(file);
if let Err(e) = written {
let _ = std::fs::remove_file(&temp);
return Err(io_at("write the config to", &temp, &e).into());
}
let arrived = if force {
std::fs::rename(&temp, path)
} else {
std::fs::hard_link(&temp, path)
};
if let Err(e) = arrived {
let _ = std::fs::remove_file(&temp);
if e.kind() == std::io::ErrorKind::AlreadyExists {
return Err(Failure::refused(
"config_file_exists",
format!(
"{} already exists; pass --force to overwrite it",
path.display()
),
));
}
return Err(io_at("move the config into place at", path, &e).into());
}
if !force {
let _ = std::fs::remove_file(&temp);
}
Ok(())
}
fn io_at(operation: &str, path: &Path, error: &std::io::Error) -> crate::domain::Error {
crate::domain::Error::Io(std::io::Error::new(
error.kind(),
format!("cannot {operation} {}: {error}", path.display()),
))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn every_resolved_key_can_be_rendered() {
let cfg = Config::from_sources(
|key| match key {
"HOME" => Some("/tmp/matra-test-home".to_string()),
_ => None,
},
None,
)
.expect("defaults resolve");
for (key, _) in cfg.sources() {
value_of(&cfg, key).unwrap_or_else(|e| panic!("{key}: {e}"));
}
}
#[test]
fn an_unknown_key_is_loud() {
let cfg = Config::from_sources(
|key| match key {
"HOME" => Some("/tmp/matra-test-home".to_string()),
_ => None,
},
None,
)
.expect("defaults resolve");
assert!(value_of(&cfg, "not.a.key").is_err());
}
#[test]
fn the_named_file_is_the_one_this_configuration_would_read() {
let dir = tempfile::tempdir().expect("temp dir");
let expected = dir.path().join(".config").join("matra").join("config.toml");
std::fs::create_dir_all(expected.parent().expect("a parent")).expect("config dir");
std::fs::write(&expected, b"").expect("config file");
let cfg = Config::from_sources(
|key| match key {
"HOME" => Some(dir.path().display().to_string()),
_ => None,
},
Some(""),
)
.expect("defaults resolve");
assert!(
cfg.sources()
.all(|(_, source)| !matches!(source, ValueSource::File(_))),
"an empty file supplies no value, so only the fallback can name it"
);
assert_eq!(config_file_read(&cfg), Some(expected.display().to_string()));
}
#[test]
fn no_config_file_means_no_config_file_in_the_envelope() {
let dir = tempfile::tempdir().expect("temp dir");
let home = dir.path().join("home");
std::fs::create_dir_all(&home).expect("home");
let cfg = Config::from_sources(
|key| match key {
"HOME" => Some(home.display().to_string()),
_ => None,
},
None,
)
.expect("defaults resolve");
assert_eq!(
config_file_read(&cfg),
None,
"nothing was read, so nothing is named"
);
}
#[test]
fn a_config_file_that_supplied_a_value_is_named() {
let dir = tempfile::tempdir().expect("temp dir");
let expected = dir.path().join(".config").join("matra").join("config.toml");
let cfg = Config::from_sources(
|key| match key {
"HOME" => Some(dir.path().display().to_string()),
_ => None,
},
Some("[summary]\nn = 7\n"),
)
.expect("resolve with a file");
assert_eq!(
config_file_read(&cfg),
Some(expected.display().to_string()),
"the file that supplied a value is the file that was read"
);
}
#[test]
fn defaults_written_once_and_refused_twice() {
let dir = tempfile::tempdir().expect("temp dir");
let path = dir.path().join("nested").join("config.toml");
write_defaults(&path, false).expect("first write");
assert_eq!(
std::fs::read_to_string(&path).expect("read back"),
DEFAULT_TOML
);
let refused = write_defaults(&path, false).expect_err("second write refused");
assert!(refused.to_string().contains("--force"), "{refused}");
write_defaults(&path, true).expect("forced write");
assert_eq!(
std::fs::read_to_string(&path).expect("read back"),
DEFAULT_TOML
);
}
#[test]
fn no_temp_file_is_left_behind() {
let dir = tempfile::tempdir().expect("temp dir");
let path = dir.path().join("config.toml");
write_defaults(&path, false).expect("first write");
let _ = write_defaults(&path, false);
let leftovers: Vec<_> = std::fs::read_dir(dir.path())
.expect("list")
.filter_map(|e| e.ok())
.map(|e| e.file_name().to_string_lossy().into_owned())
.filter(|name| name.ends_with(".tmp"))
.collect();
assert!(leftovers.is_empty(), "left behind: {leftovers:?}");
}
#[test]
fn a_filesystem_failure_names_the_operation_and_the_path() {
let dir = tempfile::tempdir().expect("temp dir");
let blocked = dir.path().join("not-a-directory");
std::fs::write(&blocked, b"x").expect("write the blocker");
let path = blocked.join("matra").join("config.toml");
let err = write_defaults(&path, false).expect_err("the directory cannot be created");
let message = err.to_string();
assert!(
message.contains("create the config directory"),
"names the operation: {message}"
);
assert!(
message.contains(&blocked.join("matra").display().to_string()),
"names the path: {message}"
);
}
}