use std::collections::BTreeMap;
use onetaskgraph_plugin_api::{ProjectedValue, SourceError, SourceName};
use serde_json::Value;
const SUMMARY: &str = "Fields";
#[derive(
Debug, Clone, Default, PartialEq, Eq, serde::Deserialize, serde::Serialize, schemars::JsonSchema,
)]
#[schemars(rename = "LinearMetadataField")]
#[serde(deny_unknown_fields)]
pub struct MetadataFieldConfig {
pub field: String, pub key: String, #[serde(default, skip_serializing_if = "Vec::is_empty")]
#[schemars(!skip_serializing_if)]
pub path: Vec<String>,
}
#[derive(Debug, Clone)]
pub(crate) struct MetadataField {
field: ShownField,
key: ShownKey,
path: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct ShownField(String);
#[derive(Debug, Clone, PartialEq, Eq)]
struct ShownKey(String);
impl MetadataField {
pub(crate) fn resolve(
configured: Vec<MetadataFieldConfig>,
instance: &SourceName,
) -> Result<Vec<Self>, SourceError> {
let mut resolved: Vec<Self> = Vec::with_capacity(configured.len());
for (index, entry) in configured.into_iter().enumerate() {
if let Some(why) = ProjectedValue::entry_refusal(
&entry.field,
&entry.key,
resolved.iter().map(|other| other.field.0.as_str()),
"field",
)
.or_else(|| {
entry.field.contains(char::is_control).then(|| {
"names a field holding a line break or another control character, which \
cannot stand on one line of the Fields section; next: name it on one line"
.to_owned()
})
}) {
return Err(SourceError::Config {
message: format!(
"metadata_fields[{index}] of source {instance} (field {:?}, key {:?}) \
{why}",
entry.field, entry.key
),
});
}
resolved.push(Self {
field: ShownField(entry.field),
key: ShownKey(entry.key),
path: entry.path,
});
}
Ok(resolved)
}
pub(crate) fn field(&self) -> &str {
&self.field.0
}
pub(crate) fn key(&self) -> &str {
&self.key.0
}
pub(crate) fn path(&self) -> &[String] {
&self.path
}
fn bullet(
&self,
metadata: &BTreeMap<String, Value>,
instance: &SourceName,
) -> Result<Option<String>, SourceError> {
let value = match ProjectedValue::read(metadata, &self.key.0, &self.path) {
Ok(Some(value)) if !value.is_empty() => value,
Ok(_) => return Ok(None),
Err(found) => {
return Err(SourceError::Refused {
message: format!(
"source {instance} shows metadata key {:?} at path {} as the field {:?} \
of an item's Fields section, and this item holds {found} there; only a \
string, an array of strings, an object of string values, null or \
nothing can be shown; next: store one of those there, or remove the \
value",
self.key.0,
serde_json::to_string(&self.path)
.unwrap_or_else(|_| format!("{:?}", self.path)),
self.field.0
),
});
}
};
let head = format!("* **{}**:", markdown_escaped(&self.field.0));
let nested = |lines: Vec<String>| {
lines
.iter()
.map(|line| format!("\n * {}", code_span(line)))
.collect::<String>()
};
Ok(Some(match value {
ProjectedValue::Text(text) if !text.contains('\n') => {
format!("{head} {}", code_span(&text))
}
ProjectedValue::Text(text) => {
format!(
"{head}{}",
nested(text.split('\n').map(str::to_owned).collect())
)
}
ProjectedValue::List(list) => format!("{head}{}", nested(list)),
ProjectedValue::Map(map) => format!(
"{head}{}",
nested(
map.iter()
.map(|(key, value)| format!("{key}: {value}"))
.collect()
)
),
}))
}
}
fn markdown_escaped(text: &str) -> String {
let mut escaped = String::with_capacity(text.len());
for character in text.chars() {
if "\\`*_[]<>#!|&~".contains(character) {
escaped.push('\\');
}
escaped.push(character);
}
escaped
}
fn code_span(text: &str) -> String {
let text = text.replace("\r\n", " ").replace(['\n', '\r'], " ");
let text = if text.is_empty() { " " } else { text.as_str() };
let mut longest = 0;
let mut run = 0;
for character in text.chars() {
run = if character == '`' { run + 1 } else { 0 };
longest = longest.max(run);
}
let fence = "`".repeat(longest + 1);
let padded = text.starts_with('`')
|| text.ends_with('`')
|| (text.starts_with(' ') && text.ends_with(' ') && !text.trim().is_empty());
if padded {
format!("{fence} {text} {fence}")
} else {
format!("{fence}{text}{fence}")
}
}
pub(crate) fn section(
fields: &[MetadataField],
metadata: &BTreeMap<String, Value>,
instance: &SourceName,
) -> Result<Option<String>, SourceError> {
let mut bullets = Vec::new();
for field in fields {
if let Some(bullet) = field.bullet(metadata, instance)? {
bullets.push(bullet);
}
}
Ok((!bullets.is_empty()).then(|| format!("+++ {SUMMARY}\n\n{}\n\n+++", bullets.join("\n"))))
}