Lines
100 %
Functions
53.13 %
Branches
//! Descriptor writer: deterministic plist text read by the clients.
use crate::descriptor::{Action, Field, Form, Kind};
/// Quote a string for a nomiscript literal.
#[must_use]
pub fn escape_str(s: &str) -> String {
let mut out = String::with_capacity(s.len() + 2);
out.push('"');
for ch in s.chars() {
match ch {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
other => out.push(other),
}
out
fn flag(value: bool) -> &'static str {
if value { "t" } else { "nil" }
fn action_symbol(action: Action) -> &'static str {
match action {
Action::Mutation => "mutation",
Action::Query => "query",
Action::LoadMutation => "load-mutation",
fn kind_sexpr(kind: Kind) -> String {
match kind {
Kind::Text { multiline, suggest } => format!(
":kind text{}{}",
if multiline { " :multiline t" } else { "" },
suggest.map_or_else(String::new, |s| format!(" :suggest {}", s.name()))
),
Kind::Select {
source,
fills,
empty,
} => format!(
":kind select :source {}{}{}",
source.name(),
fills.map_or_else(String::new, |cell| format!(" :fills {cell}")),
empty.map_or_else(String::new, |hint| format!(" :empty {}", escape_str(hint)))
Kind::Amount => ":kind amount".to_string(),
Kind::Date {
range_end,
whole_day,
":kind date{}{}",
if range_end { " :range-end t" } else { "" },
if whole_day { " :whole-day t" } else { "" }
Kind::Rows { fields, .. } => format!(":kind rows :fields {}", fields_sexpr(fields)),
Kind::Hidden => ":kind hidden".to_string(),
Kind::Choice { options, default } => format!(
":kind choice :options {}{}",
options_sexpr(options),
default.map_or_else(String::new, |key| format!(" :default {}", escape_str(key)))
fn options_sexpr(options: &[(&str, &str)]) -> String {
let items: Vec<String> = options
.iter()
.map(|(key, label)| format!("({} {})", escape_str(key), escape_str(label)))
.collect();
format!("({})", items.join(" "))
fn field_sexpr(field: &Field) -> String {
format!(
"(:key {} :label {} {} :required {}{}{})",
escape_str(field.key),
escape_str(field.label),
kind_sexpr(field.kind),
flag(field.required),
field
.nested_under()
.map(|parent| format!(" :nested-under {}", escape_str(parent)))
.unwrap_or_default(),
if field.is_paging() { " :paging t" } else { "" }
)
fn fields_sexpr(fields: &[Field]) -> String {
let items: Vec<String> = fields.iter().map(field_sexpr).collect();
pub fn descriptor_sexpr(form: &Form) -> String {
"(:name {} :title {} :action {} :fields {})",
escape_str(form.name),
escape_str(form.title),
action_symbol(form.action),
fields_sexpr(form.fields)
pub fn descriptors_sexpr(forms: &[&Form]) -> String {
let items: Vec<String> = forms.iter().map(|form| descriptor_sexpr(form)).collect();