use std::collections::BTreeMap;
use std::fmt;
use std::path::{Path, PathBuf};
use toml_edit::{Array, DocumentMut, Item, Table, TableLike, Value as EditValue};
use crate::config::{Config, check_value, cross_key_errors};
use crate::error::{ConfigError, Origin, suggestion};
use crate::module::{Choice, Modules, Needs, Plan};
use crate::value::{Value, ValueType};
const REDACTED: &str = "<redacted>";
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Field {
pub key: String,
pub ty: ValueType,
pub description: String,
pub prompt: String,
pub example: Option<String>,
pub hint: Option<String>,
pub section: String,
pub advanced: bool,
pub secret: bool,
pub source: Option<String>,
pub restart: bool,
pub editable: bool,
pub choices: Vec<String>,
pub provider: Option<String>,
pub current: Option<String>,
pub staged: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct FileOnly {
pub key: String,
pub kind: &'static str,
pub description: String,
}
pub struct Session<'a> {
config: &'a Config,
modules: Option<&'a Modules>,
staged: BTreeMap<String, Value>,
}
impl fmt::Debug for Session<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Session")
.field("config", self.config)
.field("staged", &self.staged)
.finish()
}
}
impl<'a> Session<'a> {
pub fn new(config: &'a Config, modules: Option<&'a Modules>) -> Self {
Session {
config,
modules,
staged: BTreeMap::new(),
}
}
pub fn schema(&self) -> &crate::schema::Schema {
self.config.schema()
}
pub fn plain(&self, key: &str) -> Option<String> {
let def = self.config.schema().get(key)?;
let v = self.staged.get(key).or_else(|| self.config.value(key))?;
if def.secret {
return Some(REDACTED.to_owned());
}
Some(match v {
Value::String(s) | Value::Enum(s) => s.clone(),
Value::Path(p) => p.display().to_string(),
other => other.shown(),
})
}
pub fn fields(&self) -> Vec<Field> {
self.config
.schema()
.values()
.iter()
.map(|d| Field {
key: d.key.clone(),
ty: d.ty,
description: d.description.clone(),
prompt: d.question().to_owned(),
example: d.example.clone(),
hint: d.hint.clone(),
section: d.section_title().to_owned(),
advanced: d.advanced,
secret: d.secret,
source: d.source.clone(),
restart: d.restart,
editable: !d.secret,
choices: d.choices.clone(),
provider: d.provider.clone(),
current: self.config.value(&d.key).map(|v| shown(d.secret, v)),
staged: self.staged.get(&d.key).map(Value::shown),
})
.collect()
}
pub fn file_only(&self) -> Vec<FileOnly> {
let schema = self.config.schema();
let tables = schema.tables().iter().map(|t| FileOnly {
key: t.key.clone(),
kind: "table",
description: t.description.clone(),
});
let maps = schema.maps().iter().map(|m| FileOnly {
key: m.key.clone(),
kind: "map",
description: m.description.clone(),
});
tables.chain(maps).collect()
}
pub fn choices(&self, key: &str, needs: &Needs) -> Vec<Choice> {
let Some(def) = self.config.schema().get(key) else {
return Vec::new();
};
if let Some(m) = def
.provider
.as_deref()
.and_then(|p| self.modules.and_then(|m| m.get(p)))
{
return m.list_choices(needs);
}
def.choices.iter().map(|c| Choice::new(c, "")).collect()
}
pub fn stage(&mut self, key: &str, text: &str) -> Result<(), ConfigError> {
let schema = self.config.schema();
let Some(def) = schema.get(key) else {
if schema.table(key).is_some() || schema.map(key).is_some() {
return Err(ConfigError::FileOnly {
key: key.to_owned(),
});
}
let known = schema.all_keys();
return Err(ConfigError::UnknownKey {
key: key.to_owned(),
suggestion: suggestion(key, known),
origin: Origin::Edit,
});
};
if def.secret {
return Err(ConfigError::SecretInForbiddenSource {
key: key.to_owned(),
origin: Origin::Edit,
});
}
let value = Value::parse_text(def.ty, text).ok_or_else(|| ConfigError::WrongType {
key: key.to_owned(),
expected: def.ty.name(),
found: format!("{text:?}"),
origin: Origin::Edit,
})?;
check_value(def, &value, self.modules, &Origin::Edit)?;
self.check_across_keys(key, &value)?;
if self.config.value(key) == Some(&value) {
self.staged.remove(key);
} else {
self.staged.insert(key.to_owned(), value);
}
Ok(())
}
fn check_across_keys(&self, key: &str, value: &Value) -> Result<(), ConfigError> {
let Some(modules) = self.modules else {
return Ok(());
};
let errors = cross_key_errors(self.config.schema(), modules, |k| {
if k == key {
Some((Origin::Edit, value))
} else if let Some(v) = self.staged.get(k) {
Some((Origin::Edit, v))
} else {
self.config.value(k).map(|v| (Origin::Default, v))
}
});
match errors
.into_iter()
.find(|e| matches!(e, ConfigError::ModuleRejected { key: k, .. } if k == key))
{
Some(e) => Err(e),
None => Ok(()),
}
}
pub fn unstage(&mut self, key: &str) {
self.staged.remove(key);
}
pub fn review(&self) -> Review {
let schema = self.config.schema();
let mut changes = Vec::new();
let mut restart = Vec::new();
let mut plan = Plan::default();
let mut values = Vec::new();
for def in schema.values() {
let Some(new) = self.staged.get(&def.key) else {
continue;
};
let old = self.config.value(&def.key);
changes.push(Change {
key: def.key.clone(),
from: old.map(Value::shown),
to: new.shown(),
});
if def.restart {
restart.push(def.key.clone());
}
if let (Some(old), Some(m)) = (
old,
def.provider
.as_deref()
.and_then(|p| self.modules.and_then(|m| m.get(p))),
) {
plan.actions.extend(m.on_change(old, new).actions);
}
values.push((def.key.clone(), new.clone()));
}
Review {
changes,
restart,
plan,
values,
}
}
}
fn shown(secret: bool, v: &Value) -> String {
if secret {
REDACTED.to_owned()
} else {
v.shown()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Change {
pub key: String,
pub from: Option<String>,
pub to: String,
}
#[derive(Debug, Clone)]
pub struct Review {
changes: Vec<Change>,
restart: Vec<String>,
plan: Plan,
values: Vec<(String, Value)>,
}
impl Review {
pub fn is_empty(&self) -> bool {
self.changes.is_empty()
}
pub fn changes(&self) -> &[Change] {
&self.changes
}
pub fn restart_needed(&self) -> &[String] {
&self.restart
}
pub fn plan(&self) -> &Plan {
&self.plan
}
pub fn confirm(self) -> Confirmed {
Confirmed {
changes: self.changes,
plan: self.plan,
values: self.values,
}
}
}
#[derive(Debug, Clone)]
pub struct Confirmed {
changes: Vec<Change>,
plan: Plan,
values: Vec<(String, Value)>,
}
#[derive(Debug, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum EditError {
#[error("the file is not valid TOML: {0}")]
Parse(String),
#[error("`{0}` cannot be set: part of its path is not a table in the file")]
NotATable(String),
}
pub fn save_with_backup(file: &Path, existing: &str, text: &str) -> Result<(), String> {
if file.exists() {
let mut bak = file.to_path_buf().into_os_string();
bak.push(".bak");
let bak = PathBuf::from(bak);
if bak.exists() {
return Err(format!("{} exists; move it away first", bak.display()));
}
std::fs::write(&bak, existing)
.map_err(|e| format!("cannot write {}: {e}", bak.display()))?;
}
std::fs::write(file, text).map_err(|e| format!("cannot write {}: {e}", file.display()))
}
impl Confirmed {
pub fn changes(&self) -> &[Change] {
&self.changes
}
pub fn plan(&self) -> &Plan {
&self.plan
}
pub fn file_text(&self, existing: &str) -> Result<String, EditError> {
let mut doc: DocumentMut = existing
.parse()
.map_err(|e: toml_edit::TomlError| EditError::Parse(e.message().to_owned()))?;
for (key, value) in &self.values {
set(doc.as_table_mut(), key, value)?;
}
Ok(doc.to_string())
}
}
fn edit_value(v: &Value) -> EditValue {
match v {
Value::String(s) | Value::Enum(s) => EditValue::from(s.as_str()),
Value::Path(p) => EditValue::from(p.to_string_lossy().as_ref()),
Value::Int(i) => EditValue::from(*i),
Value::Float(f) => EditValue::from(*f),
Value::Bool(b) => EditValue::from(*b),
Value::List(l) => EditValue::Array(l.iter().map(String::as_str).collect::<Array>()),
Value::Rows(_) | Value::Map(_) => v
.to_toml()
.to_string()
.parse::<EditValue>()
.unwrap_or_else(|_| EditValue::from("")),
}
}
fn set(root: &mut Table, key: &str, value: &Value) -> Result<(), EditError> {
let mut parts: Vec<&str> = key.split('.').collect();
let leaf = parts.pop().unwrap_or_default();
let mut table: &mut dyn TableLike = root;
for part in parts {
let item = table.entry(part).or_insert_with(|| {
let mut t = Table::new();
t.set_implicit(true);
Item::Table(t)
});
table = item
.as_table_like_mut()
.ok_or_else(|| EditError::NotATable(key.to_owned()))?;
}
let mut new = edit_value(value);
if let Some(old) = table.get(leaf).and_then(Item::as_value) {
*new.decor_mut() = old.decor().clone();
}
table.insert(leaf, Item::Value(new));
Ok(())
}