use std::ffi::OsString;
use std::fmt;
use crumbkit::schemars::{Schema, SchemaGenerator};
use crumbkit::serde::Serializer;
use crumbkit::{Batch, Document, Failure, Recovery, Row, Shown};
use schemars::JsonSchema;
use serde::Serialize;
use starmap::{
Bindings, Bound, BuiltIns, Cache, Choices, Mode, Name, SecretRef, Source, Spec, Type, Unset,
Value, Variable,
};
use crate::cli::{ExplainArgs, SpecFile};
use crate::codes::VARIABLE_UNKNOWN;
use crate::mode;
use crate::spec::{self, SpecFailure};
#[cfg(test)]
mod tests;
pub(crate) const EXPLAIN: Document<Batch<Explained, UnknownVariable>> = Document::new(
"starmap",
"explain",
1,
"Each variable that a spec declares, with its rules and the value it has in this shell.",
);
const DOTS: &str = "••••••••";
#[derive(Debug, Serialize, JsonSchema)]
pub(crate) struct Explained {
name: String,
#[serde(rename = "type")]
kind: String,
unset: String,
source: String,
value: Cell,
show: String,
bind: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
cache: Option<String>,
purpose: String,
#[serde(skip_serializing_if = "Option::is_none")]
effect: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
check: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
enumeration: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
values: Option<Values>,
#[serde(skip_serializing_if = "Option::is_none")]
group: Option<String>,
}
impl Row for Explained {
const COLUMNS: &'static [&'static str] = &["name", "type", "unset", "source", "value"];
const LONG_COLUMNS: &'static [&'static str] = &[
"show", "bind", "cache", "purpose", "effect", "values", "check", "group",
];
const UNCUT_COLUMNS: &'static [&'static str] = &["name"];
}
#[derive(Debug)]
pub(crate) struct Cell(CellJson);
#[derive(Debug, Serialize, JsonSchema)]
struct CellJson {
state: State,
#[serde(skip_serializing_if = "Option::is_none")]
text: Option<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, JsonSchema)]
#[serde(rename_all = "lowercase")]
enum State {
Set,
Default,
Unset,
Invalid,
}
impl Cell {
fn new(state: State, text: Option<String>) -> Self {
Self(CellJson { state, text })
}
}
impl fmt::Display for Cell {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
let text = self.0.text.as_deref().unwrap_or(DOTS);
match self.0.state {
State::Set => formatter.write_str(text),
State::Default => write!(formatter, "{text} (default)"),
State::Unset => formatter.write_str("unset"),
State::Invalid => write!(formatter, "{text} (invalid)"),
}
}
}
impl Shown for Cell {
fn json<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
self.0.serialize(serializer)
}
fn schema(generator: &mut SchemaGenerator) -> Schema {
CellJson::json_schema(generator)
}
}
crumbkit::shown!(Cell);
#[derive(Debug)]
pub(crate) struct Values(Vec<Described>);
#[derive(Debug, Serialize, JsonSchema)]
struct Described {
value: String,
description: String,
}
impl Values {
pub(crate) fn of(ty: &Type) -> Option<Self> {
let Type::Enumeration(choices) = ty else {
return None;
};
choices.name()?;
Some(Self(described(choices)))
}
}
fn described(choices: &Choices) -> Vec<Described> {
choices
.iter()
.map(|choice| Described {
value: choice.to_string(),
description: choices.description(choice).unwrap_or_default().to_owned(),
})
.collect()
}
impl fmt::Display for Values {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
for (index, described) in self.0.iter().enumerate() {
if index > 0 {
formatter.write_str("; ")?;
}
write!(formatter, "{}: {}", described.value, described.description)?;
}
Ok(())
}
}
impl Shown for Values {
fn json<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
self.0.serialize(serializer)
}
fn schema(generator: &mut SchemaGenerator) -> Schema {
Vec::<Described>::json_schema(generator)
}
}
crumbkit::shown!(Values);
#[derive(Debug, Failure)]
#[failure(
code = VARIABLE_UNKNOWN,
recovery = list_again(file),
field(name = name.as_str()),
field(file = file.as_str()),
)]
pub(crate) struct UnknownVariable {
name: Name,
file: String,
}
impl fmt::Display for UnknownVariable {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "{} does not declare {}", self.file, self.name)
}
}
fn list_again(file: &str) -> Recovery {
Recovery::Run(SpecFile::call(&["explain"], file))
}
impl std::error::Error for UnknownVariable {}
pub(crate) fn explain(
args: &ExplainArgs,
vars: Vec<(OsString, OsString)>,
) -> Result<Batch<Explained, UnknownVariable>, SpecFailure> {
let spec = spec::open(&args.file.spec)?.spec;
let file = args.file.spec.display().to_string();
let bindings = starmap::capture(&spec, vars);
let names: Vec<Name> = if args.names.is_empty() {
spec.variables().map(|(name, _)| name.clone()).collect()
} else {
args.names.clone()
};
let (_, note) = mode::decide(&spec, &bindings);
let mut note = format!("{note} Values come from this shell, and explain resolves no bind.");
if args.names.is_empty() {
note.push(' ');
note.push_str(&built_ins_sentence(BuiltIns::current()));
}
let mut batch = Batch::new(&["explain"], "names", &names).note(note);
for name in names {
batch.push(row(&spec, &file, &bindings, name));
}
Ok(batch)
}
fn built_ins_sentence(built_ins: &BuiltIns) -> String {
let names: Vec<&str> = built_ins.names().collect();
format!(
"starmap run --only-declared also passes these built-in variables from the shell: {}.",
names.join(", ")
)
}
fn row(
spec: &Spec,
file: &str,
bindings: &Bindings,
name: Name,
) -> Result<Explained, UnknownVariable> {
let Some(variable) = spec.variable(&name) else {
return Err(UnknownVariable {
name,
file: file.to_owned(),
});
};
Ok(Explained {
kind: type_text(variable.value_type()),
unset: unset_text(variable),
source: source_text(variable.source()),
value: cell(variable, bindings.get(&name)),
show: variable.show().to_string(),
bind: bind_text(variable.source()),
cache: cache_text(variable.source()).map(str::to_owned),
purpose: variable.purpose().to_owned(),
effect: variable.effect().map(str::to_owned),
check: variable.check().map(str::to_owned),
enumeration: enumeration_name(variable.value_type()),
values: Values::of(variable.value_type()),
group: spec.group_of(&name).map(|group| group.name().to_string()),
name: name.as_str().to_owned(),
})
}
fn cell(variable: &Variable, bound: Option<&Bound>) -> Cell {
match bound {
Some(Bound::Plain(raw)) => match variable.value_type().parse(raw) {
Ok(Some(_)) => return Cell::new(State::Set, Some(raw.to_string_lossy().into_owned())),
Ok(None) => {}
Err(_) => {
return Cell::new(State::Invalid, Some(raw.to_string_lossy().into_owned()));
}
},
Some(Bound::Secret(secret)) => {
let state = match variable.value_type().check_secret(secret) {
Ok(()) => State::Set,
Err(_) => State::Invalid,
};
return Cell::new(state, None);
}
Some(_) => return Cell::new(State::Invalid, None),
None => {}
}
match variable.unset().in_mode(Mode::Local) {
Unset::Default(value) => Cell::new(State::Default, Some(value_text(value))),
Unset::Required | Unset::Optional => Cell::new(State::Unset, None),
}
}
pub(crate) fn value_text(value: &Value) -> String {
match value {
Value::Path(path) => path.display().to_string(),
Value::Port(port) => port.to_string(),
Value::Url(url) => url.to_string(),
Value::SocketAddress(address) => address.to_string(),
Value::Boolean(boolean) => boolean.to_string(),
Value::Integer(number) => number.to_string(),
Value::Choice(choice) => choice.to_string(),
Value::String(string) => string.clone(),
Value::Bytes { .. } => value.to_string(),
_ => "a value".to_owned(),
}
}
pub(crate) fn type_text(ty: &Type) -> String {
match ty {
Type::Path { absolute: false } => "path".to_owned(),
Type::Path { absolute: true } => "absolute path".to_owned(),
Type::Port => "port".to_owned(),
Type::Url { schemes: None } => "url".to_owned(),
Type::Url {
schemes: Some(schemes),
} => format!("url ({schemes})"),
Type::SocketAddress => "ip socket address".to_owned(),
Type::Boolean => "boolean".to_owned(),
Type::Integer(range) => format!("integer {}..={}", range.min(), range.max()),
Type::Enumeration(choices) => match choices.name() {
Some(name) => format!("{name}: one of {choices}"),
None => format!("one of {choices}"),
},
Type::String { pattern: None } => "string".to_owned(),
Type::String {
pattern: Some(pattern),
} => format!("string matching {pattern}"),
Type::Bytes(rule) => rule.to_string(),
_ => "another type".to_owned(),
}
}
fn enumeration_name(ty: &Type) -> Option<String> {
match ty {
Type::Enumeration(choices) => choices.name().map(ToString::to_string),
_ => None,
}
}
pub(crate) fn unset_text(variable: &Variable) -> String {
let word = |unset: &Unset| match unset {
Unset::Required => "required".to_owned(),
Unset::Optional => "optional".to_owned(),
Unset::Default(value) => format!("default {}", value_text(value)),
};
let local = variable.unset().in_mode(Mode::Local);
let production = variable.unset().in_mode(Mode::Production);
if local == production {
word(local)
} else {
format!("{}; production {}", word(local), word(production))
}
}
pub(crate) fn source_text(source: &Source) -> String {
match source {
Source::Setting { bind: None } => "setting".to_owned(),
Source::Setting { bind: Some(_) } => "setting, path bind".to_owned(),
Source::Secret { bind: None } => "secret".to_owned(),
Source::Secret { bind: Some(bind) } => match bind.reference() {
SecretRef::OnePassword(_) => "secret, 1Password".to_owned(),
_ => "secret".to_owned(),
},
Source::Generated { .. } => "generated".to_owned(),
Source::Inherited => "inherited".to_owned(),
Source::Provided(reference) => format!("provided {}", reference.kind()),
_ => "another source".to_owned(),
}
}
pub(crate) fn cache_text(source: &Source) -> Option<&'static str> {
match source {
Source::Secret { bind: Some(bind) } if bind.cache() == Cache::Never => Some("never"),
_ => None,
}
}
pub(crate) fn bind_text(source: &Source) -> Option<String> {
match source {
Source::Setting {
bind: Some(template),
} => Some(template.as_str().to_owned()),
Source::Secret { bind: Some(bind) } => match bind.reference() {
SecretRef::OnePassword(reference) => Some(reference.to_string()),
_ => None,
},
Source::Generated { bytes, encoding } => {
Some(format!("{} random bytes as {encoding}", bytes.get()))
}
Source::Provided(reference) => {
let mut text = reference.kind().to_string();
for (key, value) in reference.qualifiers() {
text.push_str(&format!(" {key}={value}"));
}
Some(text)
}
_ => None,
}
}