1use std::{
5 collections::HashSet,
6 path::{Path, PathBuf},
7};
8
9use toml_edit::{InlineTable, Item, Value};
10
11use crate::{
12 data::{BindingSelector, RawKey},
13 Result,
14};
15
16use crate::recipe::schema::{self as grammar, Schema};
17
18use super::{
19 codec::{field, invalid, Codec},
20 keys::{selector_record, selector_shape, single_selector_schema, SELECTOR_FIELDS},
21};
22
23#[derive(Debug, Clone, PartialEq, Eq)]
25#[must_use]
26pub struct BindingSource {
27 pub(super) source: Source,
28 invalid_option: Option<&'static str>,
29}
30
31#[derive(Debug, Clone, PartialEq, Eq)]
32pub(super) enum Source {
33 Reference {
34 name: String,
35 selector: BindingSelector,
36 },
37 File(FileSource),
38}
39
40#[derive(Debug, Clone, PartialEq, Eq)]
41pub(super) struct FileSource {
42 pub(super) path: PathBuf,
43 pub(super) format: Option<String>,
44 pub(super) delimiter: Option<String>,
45 pub(super) encoding: Option<String>,
46 pub(super) has_header: Option<bool>,
47 pub(super) schema: Vec<(String, String)>,
48 pub(super) null_values: NullValues,
49 pub(super) key_map: Vec<(RawKey, BindingSelector)>,
50}
51
52#[derive(Debug, Clone, PartialEq, Eq, Default)]
53pub(super) enum NullValues {
54 #[default]
55 None,
56 All(Vec<String>),
57 Fields(Vec<(String, Vec<String>)>),
58}
59
60impl BindingSource {
61 pub fn file(path: impl AsRef<Path>) -> Self {
63 Self {
64 invalid_option: None,
65 source: Source::File(FileSource {
66 path: path.as_ref().to_owned(),
67 format: None,
68 delimiter: None,
69 encoding: None,
70 has_header: None,
71 schema: Vec::new(),
72 null_values: NullValues::None,
73 key_map: Vec::new(),
74 }),
75 }
76 }
77
78 pub fn binding(name: impl Into<String>) -> Self {
80 Self {
81 invalid_option: None,
82 source: Source::Reference {
83 name: name.into(),
84 selector: BindingSelector::Whole,
85 },
86 }
87 }
88
89 pub fn key(self, key: impl Into<RawKey>) -> Self {
91 self.selector(BindingSelector::Key(key.into()))
92 }
93
94 pub fn selector(mut self, selection: impl Into<BindingSelector>) -> Self {
96 if let Source::Reference { selector, .. } = &mut self.source {
97 *selector = selection.into();
98 } else {
99 self.invalid_option = Some("selector");
100 }
101 self
102 }
103
104 pub fn format(mut self, format: impl Into<String>) -> Self {
106 if let Some(file) = self.file_option("format") {
107 file.format = Some(format.into());
108 }
109 self
110 }
111
112 pub fn delimiter(mut self, delimiter: impl Into<String>) -> Self {
114 if let Some(file) = self.file_option("delimiter") {
115 file.delimiter = Some(delimiter.into());
116 }
117 self
118 }
119
120 pub fn encoding(mut self, encoding: impl Into<String>) -> Self {
122 if let Some(file) = self.file_option("encoding") {
123 file.encoding = Some(encoding.into());
124 }
125 self
126 }
127
128 pub fn has_header(mut self, has_header: bool) -> Self {
130 if let Some(file) = self.file_option("has_header") {
131 file.has_header = Some(has_header);
132 }
133 self
134 }
135
136 pub fn schema<K: Into<String>, V: Into<String>>(
138 mut self,
139 entries: impl IntoIterator<Item = (K, V)>,
140 ) -> Self {
141 if let Some(file) = self.file_option("schema") {
142 file.schema = entries
143 .into_iter()
144 .map(|(key, value)| (key.into(), value.into()))
145 .collect();
146 }
147 self
148 }
149
150 pub fn null_values<S: Into<String>>(mut self, values: impl IntoIterator<Item = S>) -> Self {
152 if let Some(file) = self.file_option("null_values") {
153 file.null_values = NullValues::All(values.into_iter().map(Into::into).collect());
154 }
155 self
156 }
157
158 pub fn field_null_values<K: Into<String>, S: Into<String>, V: IntoIterator<Item = S>>(
160 mut self,
161 entries: impl IntoIterator<Item = (K, V)>,
162 ) -> Self {
163 if let Some(file) = self.file_option("null_values") {
164 file.null_values = NullValues::Fields(
165 entries
166 .into_iter()
167 .map(|(key, values)| (key.into(), values.into_iter().map(Into::into).collect()))
168 .collect(),
169 );
170 }
171 self
172 }
173
174 pub fn key_map<K: Into<RawKey>, V: Into<BindingSelector>>(
176 mut self,
177 entries: impl IntoIterator<Item = (K, V)>,
178 ) -> Self {
179 if let Some(file) = self.file_option("key_map") {
180 file.key_map = entries
181 .into_iter()
182 .map(|(key, value)| (key.into(), value.into()))
183 .collect();
184 }
185 self
186 }
187
188 fn file_option(&mut self, name: &'static str) -> Option<&mut FileSource> {
189 if let Source::File(file) = &mut self.source {
190 Some(file)
191 } else {
192 self.invalid_option = Some(name);
193 None
194 }
195 }
196
197 pub fn path(&self) -> Option<&Path> {
199 match &self.source {
200 Source::File(file) => Some(&file.path),
201 Source::Reference { .. } => None,
202 }
203 }
204
205 pub fn reference(&self) -> Option<(&str, &BindingSelector)> {
207 match &self.source {
208 Source::Reference { name, selector } => Some((name, selector)),
209 Source::File(_) => None,
210 }
211 }
212
213 pub(super) fn validate(&self) -> Result<()> {
214 if let Some(option) = self.invalid_option {
215 return Err(invalid(format!(
216 "incompatible binding source option {option:?}"
217 )));
218 }
219 let Source::File(file) = &self.source else {
220 return Ok(());
221 };
222 file.path
223 .to_str()
224 .ok_or_else(|| invalid("recipe paths require valid Unicode"))?;
225 let mut keys = HashSet::new();
226 for (key, selector) in &file.key_map {
227 if !keys.insert(key) {
228 return Err(invalid("duplicate logical key_map target"));
229 }
230 if !matches!(
231 selector,
232 BindingSelector::Key(_) | BindingSelector::Index(_)
233 ) {
234 return Err(invalid("key_map entries select one actual key or position"));
235 }
236 }
237 let mut names = HashSet::new();
238 if file.schema.iter().any(|(name, _)| !names.insert(name)) {
239 return Err(invalid("duplicate text schema field"));
240 }
241 if let NullValues::Fields(fields) = &file.null_values {
242 names.clear();
243 if fields.iter().any(|(name, _)| !names.insert(name)) {
244 return Err(invalid("duplicate null_values field"));
245 }
246 }
247 Ok(())
248 }
249
250 pub(super) fn rebase(&mut self, base: &Path) {
251 if let Source::File(file) = &mut self.source {
252 file.path = rebase(&file.path, base);
253 }
254 }
255}
256
257impl From<String> for BindingSelector {
258 fn from(value: String) -> Self {
259 Self::Key(value.into())
260 }
261}
262impl From<&str> for BindingSelector {
263 fn from(value: &str) -> Self {
264 Self::Key(value.into())
265 }
266}
267impl From<&String> for BindingSelector {
268 fn from(value: &String) -> Self {
269 Self::Key(value.into())
270 }
271}
272impl From<RawKey> for BindingSelector {
273 fn from(value: RawKey) -> Self {
274 Self::Key(value)
275 }
276}
277impl<K: Into<RawKey>> From<Vec<K>> for BindingSelector {
278 fn from(values: Vec<K>) -> Self {
279 Self::Keys(values.into_iter().map(Into::into).collect())
280 }
281}
282impl<K: Clone + Into<RawKey>> From<&[K]> for BindingSelector {
283 fn from(values: &[K]) -> Self {
284 Self::Keys(values.iter().cloned().map(Into::into).collect())
285 }
286}
287impl<K: Clone + Into<RawKey>> From<&Vec<K>> for BindingSelector {
288 fn from(values: &Vec<K>) -> Self {
289 Self::from(values.as_slice())
290 }
291}
292impl<K: Into<RawKey>, const N: usize> From<[K; N]> for BindingSelector {
293 fn from(values: [K; N]) -> Self {
294 Self::Keys(values.into_iter().map(Into::into).collect())
295 }
296}
297impl From<std::ops::RangeFull> for BindingSelector {
298 fn from(_: std::ops::RangeFull) -> Self {
299 Self::All
300 }
301}
302
303mod sealed {
304 pub trait SourceInput {}
305}
306
307pub trait BindingSourceInput: sealed::SourceInput {
310 #[doc(hidden)]
311 fn into_source(self) -> Option<BindingSource>;
312}
313impl sealed::SourceInput for BindingSource {}
314impl BindingSourceInput for BindingSource {
315 fn into_source(self) -> Option<BindingSource> {
316 Some(self)
317 }
318}
319impl sealed::SourceInput for Option<BindingSource> {}
320impl BindingSourceInput for Option<BindingSource> {
321 fn into_source(self) -> Option<BindingSource> {
322 self
323 }
324}
325macro_rules! path_inputs {
326 ($($type:ty),+) => {$(
327 impl sealed::SourceInput for $type {}
328 impl BindingSourceInput for $type {
329 fn into_source(self)->Option<BindingSource> { Some(BindingSource::file(self)) }
330 }
331 )+};
332}
333path_inputs!(&str, String, &String, &Path, PathBuf, &PathBuf);
334
335fn encode_map<T: Codec>(entries: &[(String, T)]) -> Value {
336 let mut record = InlineTable::new();
337 for (key, value) in entries {
338 record.insert(key, value.encode());
339 }
340 record.into()
341}
342fn decode_map<T: Codec>(item: Option<&Item>) -> Result<Vec<(String, T)>> {
343 let Some(item) = item else {
344 return Ok(Vec::new());
345 };
346 let fields = item
347 .as_table_like()
348 .ok_or_else(|| invalid("expected a field mapping"))?;
349 fields
350 .iter()
351 .map(|(name, value)| T::decode(value, None).map(|value| (name.to_owned(), value)))
352 .collect()
353}
354
355fn decode_key_map(item: Option<&Item>) -> Result<Vec<(RawKey, BindingSelector)>> {
356 let Some(item) = item else {
357 return Ok(Vec::new());
358 };
359 if let Some(table) = item.as_table_like() {
360 return table
361 .iter()
362 .map(|(key, value)| Ok((key.into(), BindingSelector::decode(value, None)?)))
363 .collect();
364 }
365 let Some(array) = item.as_array() else {
366 return Err(invalid("expected key_map table or array"));
367 };
368 array
369 .iter()
370 .map(|entry| {
371 let entry = Item::Value(entry.clone());
372 let fields = grammar::record_fields(&entry, KEY_MAP_ENTRY_FIELDS)?;
373 Ok((field(fields, "key", None)?, field(fields, "source", None)?))
374 })
375 .collect()
376}
377
378const BINDING_REFERENCE_FIELDS: &[grammar::Field] = &[grammar::mandatory::<String>("binding")];
379const KEY_MAP_ENTRY_FIELDS: &[grammar::Field] = &[
380 grammar::mandatory::<RawKey>("key"),
381 grammar::custom("source", true, single_selector_schema),
382];
383const FILE_SOURCE_FIELDS: &[grammar::Field] = &[
384 grammar::mandatory::<String>("path"),
385 grammar::optional::<Option<String>>("format"),
386 grammar::optional::<Option<String>>("delimiter"),
387 grammar::optional::<Option<String>>("encoding"),
388 grammar::optional::<bool>("has_header"),
389 grammar::custom("schema", false, |ctx| {
390 grammar::dictionary(ctx.reference::<String>())
391 }),
392 grammar::custom("null_values", false, |ctx| {
393 grammar::any_of([
394 ctx.reference::<Vec<String>>(),
395 grammar::dictionary(ctx.reference::<Vec<String>>()),
396 ])
397 }),
398 grammar::custom("key_map", false, |ctx| {
399 grammar::any_of([
400 grammar::dictionary(single_selector_schema(ctx)),
401 grammar::array(grammar::record(ctx, KEY_MAP_ENTRY_FIELDS)),
402 ])
403 }),
404];
405
406pub(super) fn file_source_schema(ctx: &mut Schema) -> serde_json::Value {
407 grammar::record(ctx, FILE_SOURCE_FIELDS)
408}
409
410impl Codec for BindingSource {
411 fn schema(ctx: &mut Schema) -> serde_json::Value {
412 grammar::one_of([
413 file_source_schema(ctx),
414 selector_shape(ctx, BINDING_REFERENCE_FIELDS, SELECTOR_FIELDS),
415 ])
416 }
417
418 fn encode(&self) -> Value {
419 match &self.source {
420 Source::Reference { name, selector } => {
421 let mut fields = selector_record(selector);
422 fields.insert("binding", name.encode());
423 fields.into()
424 }
425 Source::File(file) => {
426 let mut fields = InlineTable::new();
427 fields.insert(
428 "path",
429 Value::from(file.path.to_string_lossy().into_owned()),
430 );
431 for (key, value) in [
432 ("format", &file.format),
433 ("delimiter", &file.delimiter),
434 ("encoding", &file.encoding),
435 ] {
436 if let Some(value) = value {
437 fields.insert(key, value.encode());
438 }
439 }
440 if let Some(header) = file.has_header {
441 fields.insert("has_header", header.encode());
442 }
443 if !file.schema.is_empty() {
444 fields.insert("schema", encode_map(&file.schema));
445 }
446 match &file.null_values {
447 NullValues::None => {}
448 NullValues::All(values) => {
449 fields.insert("null_values", values.encode());
450 }
451 NullValues::Fields(fields_values) => {
452 fields.insert("null_values", encode_map(fields_values));
453 }
454 }
455 if !file.key_map.is_empty() {
456 let values: toml_edit::Array = file
457 .key_map
458 .iter()
459 .map(|(key, selector)| {
460 let mut entry = InlineTable::new();
461 entry.insert("key", key.encode());
462 entry.insert("source", selector.encode());
463 Value::from(entry)
464 })
465 .collect();
466 fields.insert("key_map", Value::Array(values));
467 }
468 fields.into()
469 }
470 }
471 }
472
473 fn decode(item: &Item, _: Option<Self>) -> Result<Self> {
474 let fields = item
475 .as_table_like()
476 .ok_or_else(|| invalid("binding declaration must be a table"))?;
477 let source = if fields.contains_key("binding") {
478 let mut allowed = SELECTOR_FIELDS.to_vec();
479 allowed.extend_from_slice(BINDING_REFERENCE_FIELDS);
480 let fields = grammar::record_fields(item, &allowed)?;
481 let mut selector = InlineTable::new();
482 for (name, value) in fields.iter() {
483 if name != "binding" {
484 selector.insert(name, item_value(value)?);
485 }
486 }
487 Source::Reference {
488 name: field(fields, "binding", None)?,
489 selector: BindingSelector::decode(&Item::Value(selector.into()), None)?,
490 }
491 } else {
492 let fields = grammar::record_fields(item, FILE_SOURCE_FIELDS)?;
493 let null_values = match fields.get("null_values") {
494 None => NullValues::None,
495 Some(value) if value.is_array() => {
496 NullValues::All(Vec::<String>::decode(value, None)?)
497 }
498 Some(value) => NullValues::Fields(decode_map(Some(value))?),
499 };
500 Source::File(FileSource {
501 path: PathBuf::from(field::<String>(fields, "path", None)?),
502 format: field(fields, "format", Some(None))?,
503 delimiter: field(fields, "delimiter", Some(None))?,
504 encoding: field(fields, "encoding", Some(None))?,
505 has_header: fields
506 .get("has_header")
507 .map(|value| bool::decode(value, None))
508 .transpose()?,
509 schema: decode_map(fields.get("schema"))?,
510 null_values,
511 key_map: decode_key_map(fields.get("key_map"))?,
512 })
513 };
514 let result = Self {
515 source,
516 invalid_option: None,
517 };
518 result.validate()?;
519 Ok(result)
520 }
521}
522
523pub(super) fn item_value(item: &Item) -> Result<Value> {
524 let mut copy = item.clone();
525 copy.make_value();
526 copy.into_value()
527 .map_err(|_| invalid("expected a declaration value"))
528}
529
530fn fixed_base(path: &Path) -> bool {
531 let Some(first) = path.components().next() else {
532 return true;
533 };
534 if path.is_absolute() {
535 return false;
536 }
537 let first = first.as_os_str().to_string_lossy();
538 !first.starts_with('~') && !first.starts_with("${")
539}
540
541pub(super) fn rebase(path: &Path, base: &Path) -> PathBuf {
542 if fixed_base(path) {
543 base.join(path)
544 } else {
545 path.to_owned()
546 }
547}
548
549pub(super) fn expand_path(path: &Path, base: &Path) -> Result<PathBuf> {
550 let expression = path
551 .to_str()
552 .ok_or_else(|| invalid("recipe paths require valid Unicode"))?;
553 let mut text = String::new();
554 let mut rest = expression;
555 if rest == "~" || rest.starts_with("~/") || (cfg!(windows) && rest.starts_with("~\\\\")) {
556 let key = if cfg!(windows) { "USERPROFILE" } else { "HOME" };
557 text.push_str(&std::env::var(key).map_err(|_| invalid("home directory is not defined"))?);
558 rest = &rest[1..];
559 }
560 while let Some(index) = rest.find("${") {
561 text.push_str(&rest[..index]);
562 let suffix = &rest[index + 2..];
563 let end = suffix
564 .find('}')
565 .ok_or_else(|| invalid("unterminated path variable"))?;
566 let name = &suffix[..end];
567 if name.is_empty() {
568 return Err(invalid("empty path variable"));
569 }
570 text.push_str(
571 &std::env::var(name)
572 .map_err(|_| invalid(format!("path variable {name:?} is not defined")))?,
573 );
574 rest = &suffix[end + 1..];
575 }
576 text.push_str(rest);
577 let path = PathBuf::from(text);
578 Ok(if path.is_absolute() {
579 path
580 } else {
581 base.join(path)
582 })
583}