use std::path::Path;
use std::process::ExitCode;
use serde_json::{Map, Value, json};
use tinystore::Store;
use tinystore::config::Config;
use crate::asked::{self, Asked, Done, Refused, Verb, failed, wrong};
use crate::{help, reach};
const VERBS: [Verb; 3] = [
Verb { word: "explain", command: &help::CONFIG_EXPLAIN, run: explain },
Verb { word: "update", command: &help::CONFIG_UPDATE, run: update },
Verb { word: "reset", command: &help::CONFIG_RESET, run: reset },
];
pub(crate) fn run(args: &[String]) -> ExitCode {
asked::run_verb("config", &VERBS, args)
}
fn explain(asked: Asked) -> Done {
let (dir, rest) = asked.placed("config", "explain", true)?;
let [name] = &rest[..] else {
return Err(wrong("explain takes a config's name: explain chat"));
};
let (_store, config) = kept(&dir, name)?;
let explained = config.explain();
let version = config.get().version();
if asked.has("--json") {
let settings: Vec<Value> = explained
.settings
.iter()
.map(|line| json!({ "path": line.path, "value": line.value, "from": line.from, "over": line.over }))
.collect();
return outln!(
"{}",
json!({ "name": name, "version": version, "settings": settings, "notes": explained.notes })
);
}
outln!("config {name} · version {version}")?;
for line in explained.to_string().lines() {
outln!(" {line}")?;
}
asked::say("config explain", "the program's own files and environment are its own: its value may differ");
Ok(())
}
fn update(asked: Asked) -> Done {
let (dir, rest) = asked.placed("config", "update", false)?;
let Some((name, pairs)) = rest.split_first().filter(|(_, pairs)| !pairs.is_empty()) else {
return Err(wrong("update takes a config and its settings: update chat model.max_tokens=2048"));
};
reach::store_at(&dir)?;
let mut paths = Map::new();
for pair in pairs {
let (path, value) = given(pair)?;
paths.insert(path, value);
}
let (named, sent) = (name.clone(), changes_of(&dir, name, &paths)?);
let version = reach::write(&dir, "config update", move |client| {
let (config, version) = client.config(&named)?;
client.update_config(config, version, &sent)
})?;
outln!("updated config {name} to version {version}: {}", pairs.join(" "))
}
fn reset(asked: Asked) -> Done {
let (dir, rest) = asked.placed("config", "reset", false)?;
let (Some(name), path, None) = (rest.first(), rest.get(1), rest.get(2)) else {
return Err(wrong("reset takes a config and a setting at most: reset chat model.max_tokens"));
};
reach::store_at(&dir)?;
kept(&dir, name)?;
let (named, at) = (name.clone(), path.cloned().unwrap_or_default());
let version = reach::write(&dir, "config reset", move |client| {
let (config, _) = client.config(&named)?;
client.reset_config(config, &at)
})?;
match path {
Some(path) => outln!("reset {path} of config {name}: version {version}"),
None => outln!("reset every change of config {name}: version {version}"),
}
}
fn kept(dir: &Path, name: &str) -> Result<(Store, Config<Value>), Refused> {
asked::existing(dir)?;
let store = Store::open_beside(dir).map_err(failed)?;
match tinystore::client::config_kept(&store, name).map_err(failed)? {
Some(config) => Ok((store, config)),
None => {
let known = tinystore::client::configs(&store).unwrap_or_default();
let names: Vec<&str> = known.iter().map(String::as_str).collect();
let held = if known.is_empty() { "none".to_owned() } else { known.join(", ") };
Err(failed(format!(
"{} keeps no config {name}{}: a program opens it first; it keeps {held}",
dir.display(),
crate::meant(name, &names)
)))
}
}
}
fn given(pair: &str) -> Result<(String, Value), Refused> {
if let Some((path, json)) = pair.split_once(":=") {
let value = serde_json::from_str(json).map_err(|error| wrong(format!("{pair}: JSON after :=, {error}")))?;
return Ok((path.to_owned(), value));
}
let Some((path, text)) = pair.split_once('=') else {
return Err(wrong(format!("{pair}: a setting and its value, as model.max_tokens=2048")));
};
Ok((path.to_owned(), Value::String(text.to_owned())))
}
pub(crate) fn changes_of(dir: &Path, name: &str, paths: &Map<String, Value>) -> Result<String, Refused> {
let (_store, config) = kept(dir, name)?;
let mut changes = Map::new();
for (path, value) in paths {
let value = match value {
Value::String(text) => tinystore::client::config_value(&config, path, text).map_err(wrong)?,
other => other.clone(),
};
nested(&mut changes, path, value)?;
}
Ok(Value::Object(changes).to_string())
}
fn nested(changes: &mut Map<String, Value>, path: &str, value: Value) -> Result<(), Refused> {
let (groups, setting) = path.rsplit_once('.').map_or(("", path), |(groups, setting)| (groups, setting));
let mut at = changes;
for group in groups.split('.').filter(|group| !group.is_empty()) {
let entry = at.entry(group.to_owned()).or_insert_with(|| Value::Object(Map::new()));
let Value::Object(inner) = entry else {
return Err(wrong(format!("{path}: {group} was given a value, and is a group here")));
};
at = inner;
}
at.insert(setting.to_owned(), value);
Ok(())
}