use std::{
collections::HashSet,
path::{Path, PathBuf},
};
use toml_edit::{InlineTable, Item, Value};
use crate::{
data::{BindingSelector, RawKey},
Result,
};
use crate::recipe::schema::{self as grammar, Schema};
use super::{
codec::{field, invalid, Codec},
keys::{selector_record, selector_shape, single_selector_schema, SELECTOR_FIELDS},
};
#[derive(Debug, Clone, PartialEq, Eq)]
#[must_use]
pub struct BindingSource {
pub(super) source: Source,
invalid_option: Option<&'static str>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) enum Source {
Reference {
name: String,
selector: BindingSelector,
},
File(FileSource),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) struct FileSource {
pub(super) path: PathBuf,
pub(super) format: Option<String>,
pub(super) delimiter: Option<String>,
pub(super) encoding: Option<String>,
pub(super) has_header: Option<bool>,
pub(super) schema: Vec<(String, String)>,
pub(super) null_values: NullValues,
pub(super) key_map: Vec<(RawKey, BindingSelector)>,
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub(super) enum NullValues {
#[default]
None,
All(Vec<String>),
Fields(Vec<(String, Vec<String>)>),
}
impl BindingSource {
pub fn file(path: impl AsRef<Path>) -> Self {
Self {
invalid_option: None,
source: Source::File(FileSource {
path: path.as_ref().to_owned(),
format: None,
delimiter: None,
encoding: None,
has_header: None,
schema: Vec::new(),
null_values: NullValues::None,
key_map: Vec::new(),
}),
}
}
pub fn binding(name: impl Into<String>) -> Self {
Self {
invalid_option: None,
source: Source::Reference {
name: name.into(),
selector: BindingSelector::Whole,
},
}
}
pub fn key(self, key: impl Into<RawKey>) -> Self {
self.selector(BindingSelector::Key(key.into()))
}
pub fn selector(mut self, selection: impl Into<BindingSelector>) -> Self {
if let Source::Reference { selector, .. } = &mut self.source {
*selector = selection.into();
} else {
self.invalid_option = Some("selector");
}
self
}
pub fn format(mut self, format: impl Into<String>) -> Self {
if let Some(file) = self.file_option("format") {
file.format = Some(format.into());
}
self
}
pub fn delimiter(mut self, delimiter: impl Into<String>) -> Self {
if let Some(file) = self.file_option("delimiter") {
file.delimiter = Some(delimiter.into());
}
self
}
pub fn encoding(mut self, encoding: impl Into<String>) -> Self {
if let Some(file) = self.file_option("encoding") {
file.encoding = Some(encoding.into());
}
self
}
pub fn has_header(mut self, has_header: bool) -> Self {
if let Some(file) = self.file_option("has_header") {
file.has_header = Some(has_header);
}
self
}
pub fn schema<K: Into<String>, V: Into<String>>(
mut self,
entries: impl IntoIterator<Item = (K, V)>,
) -> Self {
if let Some(file) = self.file_option("schema") {
file.schema = entries
.into_iter()
.map(|(key, value)| (key.into(), value.into()))
.collect();
}
self
}
pub fn null_values<S: Into<String>>(mut self, values: impl IntoIterator<Item = S>) -> Self {
if let Some(file) = self.file_option("null_values") {
file.null_values = NullValues::All(values.into_iter().map(Into::into).collect());
}
self
}
pub fn field_null_values<K: Into<String>, S: Into<String>, V: IntoIterator<Item = S>>(
mut self,
entries: impl IntoIterator<Item = (K, V)>,
) -> Self {
if let Some(file) = self.file_option("null_values") {
file.null_values = NullValues::Fields(
entries
.into_iter()
.map(|(key, values)| (key.into(), values.into_iter().map(Into::into).collect()))
.collect(),
);
}
self
}
pub fn key_map<K: Into<RawKey>, V: Into<BindingSelector>>(
mut self,
entries: impl IntoIterator<Item = (K, V)>,
) -> Self {
if let Some(file) = self.file_option("key_map") {
file.key_map = entries
.into_iter()
.map(|(key, value)| (key.into(), value.into()))
.collect();
}
self
}
fn file_option(&mut self, name: &'static str) -> Option<&mut FileSource> {
if let Source::File(file) = &mut self.source {
Some(file)
} else {
self.invalid_option = Some(name);
None
}
}
pub fn path(&self) -> Option<&Path> {
match &self.source {
Source::File(file) => Some(&file.path),
Source::Reference { .. } => None,
}
}
pub fn reference(&self) -> Option<(&str, &BindingSelector)> {
match &self.source {
Source::Reference { name, selector } => Some((name, selector)),
Source::File(_) => None,
}
}
pub(super) fn validate(&self) -> Result<()> {
if let Some(option) = self.invalid_option {
return Err(invalid(format!(
"incompatible binding source option {option:?}"
)));
}
let Source::File(file) = &self.source else {
return Ok(());
};
file.path
.to_str()
.ok_or_else(|| invalid("recipe paths require valid Unicode"))?;
let mut keys = HashSet::new();
for (key, selector) in &file.key_map {
if !keys.insert(key) {
return Err(invalid("duplicate logical key_map target"));
}
if !matches!(
selector,
BindingSelector::Key(_) | BindingSelector::Index(_)
) {
return Err(invalid("key_map entries select one actual key or position"));
}
}
let mut names = HashSet::new();
if file.schema.iter().any(|(name, _)| !names.insert(name)) {
return Err(invalid("duplicate text schema field"));
}
if let NullValues::Fields(fields) = &file.null_values {
names.clear();
if fields.iter().any(|(name, _)| !names.insert(name)) {
return Err(invalid("duplicate null_values field"));
}
}
Ok(())
}
pub(super) fn rebase(&mut self, base: &Path) {
if let Source::File(file) = &mut self.source {
file.path = rebase(&file.path, base);
}
}
}
impl From<String> for BindingSelector {
fn from(value: String) -> Self {
Self::Key(value.into())
}
}
impl From<&str> for BindingSelector {
fn from(value: &str) -> Self {
Self::Key(value.into())
}
}
impl From<&String> for BindingSelector {
fn from(value: &String) -> Self {
Self::Key(value.into())
}
}
impl From<RawKey> for BindingSelector {
fn from(value: RawKey) -> Self {
Self::Key(value)
}
}
impl<K: Into<RawKey>> From<Vec<K>> for BindingSelector {
fn from(values: Vec<K>) -> Self {
Self::Keys(values.into_iter().map(Into::into).collect())
}
}
impl<K: Clone + Into<RawKey>> From<&[K]> for BindingSelector {
fn from(values: &[K]) -> Self {
Self::Keys(values.iter().cloned().map(Into::into).collect())
}
}
impl<K: Clone + Into<RawKey>> From<&Vec<K>> for BindingSelector {
fn from(values: &Vec<K>) -> Self {
Self::from(values.as_slice())
}
}
impl<K: Into<RawKey>, const N: usize> From<[K; N]> for BindingSelector {
fn from(values: [K; N]) -> Self {
Self::Keys(values.into_iter().map(Into::into).collect())
}
}
impl From<std::ops::RangeFull> for BindingSelector {
fn from(_: std::ops::RangeFull) -> Self {
Self::All
}
}
mod sealed {
pub trait SourceInput {}
}
pub trait BindingSourceInput: sealed::SourceInput {
#[doc(hidden)]
fn into_source(self) -> Option<BindingSource>;
}
impl sealed::SourceInput for BindingSource {}
impl BindingSourceInput for BindingSource {
fn into_source(self) -> Option<BindingSource> {
Some(self)
}
}
impl sealed::SourceInput for Option<BindingSource> {}
impl BindingSourceInput for Option<BindingSource> {
fn into_source(self) -> Option<BindingSource> {
self
}
}
macro_rules! path_inputs {
($($type:ty),+) => {$(
impl sealed::SourceInput for $type {}
impl BindingSourceInput for $type {
fn into_source(self)->Option<BindingSource> { Some(BindingSource::file(self)) }
}
)+};
}
path_inputs!(&str, String, &String, &Path, PathBuf, &PathBuf);
fn encode_map<T: Codec>(entries: &[(String, T)]) -> Value {
let mut record = InlineTable::new();
for (key, value) in entries {
record.insert(key, value.encode());
}
record.into()
}
fn decode_map<T: Codec>(item: Option<&Item>) -> Result<Vec<(String, T)>> {
let Some(item) = item else {
return Ok(Vec::new());
};
let fields = item
.as_table_like()
.ok_or_else(|| invalid("expected a field mapping"))?;
fields
.iter()
.map(|(name, value)| T::decode(value, None).map(|value| (name.to_owned(), value)))
.collect()
}
fn decode_key_map(item: Option<&Item>) -> Result<Vec<(RawKey, BindingSelector)>> {
let Some(item) = item else {
return Ok(Vec::new());
};
if let Some(table) = item.as_table_like() {
return table
.iter()
.map(|(key, value)| Ok((key.into(), BindingSelector::decode(value, None)?)))
.collect();
}
let Some(array) = item.as_array() else {
return Err(invalid("expected key_map table or array"));
};
array
.iter()
.map(|entry| {
let entry = Item::Value(entry.clone());
let fields = grammar::record_fields(&entry, KEY_MAP_ENTRY_FIELDS)?;
Ok((field(fields, "key", None)?, field(fields, "source", None)?))
})
.collect()
}
const BINDING_REFERENCE_FIELDS: &[grammar::Field] = &[grammar::mandatory::<String>("binding")];
const KEY_MAP_ENTRY_FIELDS: &[grammar::Field] = &[
grammar::mandatory::<RawKey>("key"),
grammar::custom("source", true, single_selector_schema),
];
const FILE_SOURCE_FIELDS: &[grammar::Field] = &[
grammar::mandatory::<String>("path"),
grammar::optional::<Option<String>>("format"),
grammar::optional::<Option<String>>("delimiter"),
grammar::optional::<Option<String>>("encoding"),
grammar::optional::<bool>("has_header"),
grammar::custom("schema", false, |ctx| {
grammar::dictionary(ctx.reference::<String>())
}),
grammar::custom("null_values", false, |ctx| {
grammar::any_of([
ctx.reference::<Vec<String>>(),
grammar::dictionary(ctx.reference::<Vec<String>>()),
])
}),
grammar::custom("key_map", false, |ctx| {
grammar::any_of([
grammar::dictionary(single_selector_schema(ctx)),
grammar::array(grammar::record(ctx, KEY_MAP_ENTRY_FIELDS)),
])
}),
];
pub(super) fn file_source_schema(ctx: &mut Schema) -> serde_json::Value {
grammar::record(ctx, FILE_SOURCE_FIELDS)
}
impl Codec for BindingSource {
fn schema(ctx: &mut Schema) -> serde_json::Value {
grammar::one_of([
file_source_schema(ctx),
selector_shape(ctx, BINDING_REFERENCE_FIELDS, SELECTOR_FIELDS),
])
}
fn encode(&self) -> Value {
match &self.source {
Source::Reference { name, selector } => {
let mut fields = selector_record(selector);
fields.insert("binding", name.encode());
fields.into()
}
Source::File(file) => {
let mut fields = InlineTable::new();
fields.insert(
"path",
Value::from(file.path.to_string_lossy().into_owned()),
);
for (key, value) in [
("format", &file.format),
("delimiter", &file.delimiter),
("encoding", &file.encoding),
] {
if let Some(value) = value {
fields.insert(key, value.encode());
}
}
if let Some(header) = file.has_header {
fields.insert("has_header", header.encode());
}
if !file.schema.is_empty() {
fields.insert("schema", encode_map(&file.schema));
}
match &file.null_values {
NullValues::None => {}
NullValues::All(values) => {
fields.insert("null_values", values.encode());
}
NullValues::Fields(fields_values) => {
fields.insert("null_values", encode_map(fields_values));
}
}
if !file.key_map.is_empty() {
let values: toml_edit::Array = file
.key_map
.iter()
.map(|(key, selector)| {
let mut entry = InlineTable::new();
entry.insert("key", key.encode());
entry.insert("source", selector.encode());
Value::from(entry)
})
.collect();
fields.insert("key_map", Value::Array(values));
}
fields.into()
}
}
}
fn decode(item: &Item, _: Option<Self>) -> Result<Self> {
let fields = item
.as_table_like()
.ok_or_else(|| invalid("binding declaration must be a table"))?;
let source = if fields.contains_key("binding") {
let mut allowed = SELECTOR_FIELDS.to_vec();
allowed.extend_from_slice(BINDING_REFERENCE_FIELDS);
let fields = grammar::record_fields(item, &allowed)?;
let mut selector = InlineTable::new();
for (name, value) in fields.iter() {
if name != "binding" {
selector.insert(name, item_value(value)?);
}
}
Source::Reference {
name: field(fields, "binding", None)?,
selector: BindingSelector::decode(&Item::Value(selector.into()), None)?,
}
} else {
let fields = grammar::record_fields(item, FILE_SOURCE_FIELDS)?;
let null_values = match fields.get("null_values") {
None => NullValues::None,
Some(value) if value.is_array() => {
NullValues::All(Vec::<String>::decode(value, None)?)
}
Some(value) => NullValues::Fields(decode_map(Some(value))?),
};
Source::File(FileSource {
path: PathBuf::from(field::<String>(fields, "path", None)?),
format: field(fields, "format", Some(None))?,
delimiter: field(fields, "delimiter", Some(None))?,
encoding: field(fields, "encoding", Some(None))?,
has_header: fields
.get("has_header")
.map(|value| bool::decode(value, None))
.transpose()?,
schema: decode_map(fields.get("schema"))?,
null_values,
key_map: decode_key_map(fields.get("key_map"))?,
})
};
let result = Self {
source,
invalid_option: None,
};
result.validate()?;
Ok(result)
}
}
pub(super) fn item_value(item: &Item) -> Result<Value> {
let mut copy = item.clone();
copy.make_value();
copy.into_value()
.map_err(|_| invalid("expected a declaration value"))
}
fn fixed_base(path: &Path) -> bool {
let Some(first) = path.components().next() else {
return true;
};
if path.is_absolute() {
return false;
}
let first = first.as_os_str().to_string_lossy();
!first.starts_with('~') && !first.starts_with("${")
}
pub(super) fn rebase(path: &Path, base: &Path) -> PathBuf {
if fixed_base(path) {
base.join(path)
} else {
path.to_owned()
}
}
pub(super) fn expand_path(path: &Path, base: &Path) -> Result<PathBuf> {
let expression = path
.to_str()
.ok_or_else(|| invalid("recipe paths require valid Unicode"))?;
let mut text = String::new();
let mut rest = expression;
if rest == "~" || rest.starts_with("~/") || (cfg!(windows) && rest.starts_with("~\\\\")) {
let key = if cfg!(windows) { "USERPROFILE" } else { "HOME" };
text.push_str(&std::env::var(key).map_err(|_| invalid("home directory is not defined"))?);
rest = &rest[1..];
}
while let Some(index) = rest.find("${") {
text.push_str(&rest[..index]);
let suffix = &rest[index + 2..];
let end = suffix
.find('}')
.ok_or_else(|| invalid("unterminated path variable"))?;
let name = &suffix[..end];
if name.is_empty() {
return Err(invalid("empty path variable"));
}
text.push_str(
&std::env::var(name)
.map_err(|_| invalid(format!("path variable {name:?} is not defined")))?,
);
rest = &suffix[end + 1..];
}
text.push_str(rest);
let path = PathBuf::from(text);
Ok(if path.is_absolute() {
path
} else {
base.join(path)
})
}