stem/descriptor/
export.rs1use std::collections::BTreeSet;
2
3use serde_json::Value;
4
5use crate::descriptor::parsing::Descriptor;
6use crate::error::{Error, Result};
7
8fn descriptor_fields(descriptor: &Descriptor) -> Result<serde_json::Map<String, Value>> {
9 match serde_json::to_value(descriptor) {
10 Ok(Value::Object(fields)) => Ok(fields),
11 Ok(_) => Err(Error::invalid_input(
12 "Unable to export a descriptor that has no attributes",
13 )),
14 Err(error) => Err(Error::invalid_input(format!(
15 "Unable to export a descriptor: {error}"
16 ))),
17 }
18}
19
20fn csv_cell(value: Option<&Value>) -> String {
21 let text = match value {
22 None | Some(Value::Null) => String::new(),
23 Some(Value::String(text)) => text.clone(),
24 Some(other) => other.to_string(),
25 };
26 match text.contains(['"', ',', '\n', '\r']) {
27 true => format!("\"{}\"", text.replace('"', "\"\"")),
28 false => text,
29 }
30}
31
32pub fn export_csv(
33 descriptors: &[Descriptor],
34 included_fields: &[&str],
35 excluded_fields: &[&str],
36 header: bool,
37) -> Result<String> {
38 let Some(first) = descriptors.first() else {
39 return Ok(String::new());
40 };
41 let kind = first.type_annotation().name;
42 let first_fields = descriptor_fields(first)?;
43 let available: BTreeSet<&String> = first_fields.keys().collect();
44 let mut columns: Vec<String> = match included_fields.is_empty() {
45 true => available.iter().map(|field| (*field).clone()).collect(),
46 false => {
47 for field in included_fields {
48 if !available
49 .iter()
50 .any(|candidate| candidate.as_str() == *field)
51 {
52 return Err(Error::invalid_input(format!(
53 "{kind} does not have a '{field}' attribute, valid fields are: \
54 {}",
55 available
56 .iter()
57 .map(|field| field.as_str())
58 .collect::<Vec<_>>()
59 .join(", ")
60 )));
61 }
62 }
63 included_fields
64 .iter()
65 .map(|field| field.to_string())
66 .collect()
67 }
68 };
69 columns.retain(|column| !excluded_fields.contains(&column.as_str()));
70 let mut lines = Vec::new();
71 if header {
72 lines.push(columns.join(","));
73 }
74 for descriptor in descriptors {
75 if descriptor.type_annotation().name != kind {
76 return Err(Error::invalid_input(format!(
77 "To export a descriptor CSV all of the descriptors must be of the same \
78 type. First descriptor was a {kind} but we later got a {}.",
79 descriptor.type_annotation().name
80 )));
81 }
82 let fields = descriptor_fields(descriptor)?;
83 let cells: Vec<String> = columns
84 .iter()
85 .map(|column| csv_cell(fields.get(column)))
86 .collect();
87 lines.push(cells.join(","));
88 }
89 Ok(lines.join("\n") + "\n")
90}