Skip to main content

rustxform_reader/
lib.rs

1//! Read an XLSForm source into a raw [`Workbook`] of string rows.
2//!
3//! Three input shapes are supported:
4//! - **Markdown** and **CSV** use the "first column selects the sheet"
5//!   convention: a row whose first cell is non-empty opens a new sheet, and
6//!   rows whose first cell is empty add cells (from column 2) to it.
7//! - **XLSX/XLS** map each worksheet directly to a [`Sheet`].
8//!
9//! ```text
10//! | survey  |         |      |           |
11//! |         | type    | name | label     |
12//! |         | text    | q1   | Question  |
13//! ```
14
15use std::io::Cursor;
16
17/// A raw workbook: an ordered collection of named sheets.
18#[derive(Debug, Clone, Default, PartialEq, Eq)]
19pub struct Workbook {
20    /// Sheets in source order (typically `survey`, `choices`, `settings`).
21    pub sheets: Vec<Sheet>,
22}
23
24impl Workbook {
25    /// Return the sheet with the given name, if present.
26    #[must_use]
27    pub fn sheet(&self, name: &str) -> Option<&Sheet> {
28        self.sheets.iter().find(|s| s.name == name)
29    }
30}
31
32/// A single worksheet: a name and a grid of string cells.
33#[derive(Debug, Clone, PartialEq, Eq)]
34pub struct Sheet {
35    /// Sheet name.
36    pub name: String,
37    /// Rows of cells; the first row is conventionally the header.
38    pub rows: Vec<Vec<String>>,
39}
40
41/// An error produced while reading a workbook.
42#[derive(Debug, thiserror::Error)]
43pub enum ReadError {
44    /// Failed to open or read a spreadsheet (XLSX/XLS).
45    #[error("spreadsheet error: {0}")]
46    Spreadsheet(String),
47    /// Failed to parse CSV input.
48    #[error("csv error: {0}")]
49    Csv(String),
50}
51
52/// Read a Markdown table workbook.
53///
54/// # Errors
55///
56/// Infallible for Markdown; returns `Result` for a uniform reader API.
57pub fn read_markdown(src: &str) -> Result<Workbook, ReadError> {
58    let rows = src.lines().filter_map(|line| {
59        let line = line.trim();
60        line.starts_with('|').then(|| split_pipe_row(line))
61    });
62    Ok(assemble(rows))
63}
64
65/// Read a CSV workbook using the same "first column selects the sheet"
66/// convention as Markdown.
67///
68/// # Errors
69///
70/// Returns [`ReadError::Csv`] if the CSV cannot be parsed.
71pub fn read_csv(src: &str) -> Result<Workbook, ReadError> {
72    let mut reader = csv::ReaderBuilder::new()
73        .has_headers(false)
74        .flexible(true)
75        .from_reader(src.as_bytes());
76
77    let mut rows: Vec<Vec<String>> = Vec::new();
78    for record in reader.records() {
79        let record = record.map_err(|e| ReadError::Csv(e.to_string()))?;
80        rows.push(record.iter().map(|c| c.trim().to_owned()).collect());
81    }
82    Ok(assemble(rows))
83}
84
85/// Read an XLSX or XLS workbook, mapping each worksheet to a [`Sheet`].
86///
87/// # Errors
88///
89/// Returns [`ReadError::Spreadsheet`] if the workbook cannot be read.
90pub fn read_xlsx(bytes: &[u8]) -> Result<Workbook, ReadError> {
91    use calamine::Reader;
92
93    let mut book = calamine::open_workbook_auto_from_rs(Cursor::new(bytes))
94        .map_err(|e| ReadError::Spreadsheet(e.to_string()))?;
95
96    let mut workbook = Workbook::default();
97    for name in book.sheet_names() {
98        let range = book
99            .worksheet_range(&name)
100            .map_err(|e| ReadError::Spreadsheet(e.to_string()))?;
101        let rows = range
102            .rows()
103            .map(|row| row.iter().map(cell_to_string).collect())
104            .collect();
105        workbook.sheets.push(Sheet { name, rows });
106    }
107    Ok(workbook)
108}
109
110/// Assemble rows into sheets using the first-column-selects-the-sheet rule.
111fn assemble(rows: impl IntoIterator<Item = Vec<String>>) -> Workbook {
112    let mut workbook = Workbook::default();
113    for cells in rows {
114        if is_separator(&cells) {
115            continue;
116        }
117        let first = cells.first().map(String::as_str).unwrap_or_default();
118        if first.is_empty() {
119            if let Some(sheet) = workbook.sheets.last_mut() {
120                sheet.rows.push(cells[1..].to_vec());
121            }
122        } else {
123            workbook.sheets.push(Sheet {
124                name: first.to_owned(),
125                rows: Vec::new(),
126            });
127        }
128    }
129    workbook
130}
131
132/// Split `| a | b | c |` into trimmed cells `[a, b, c]`.
133fn split_pipe_row(line: &str) -> Vec<String> {
134    let trimmed = line
135        .strip_prefix('|')
136        .unwrap_or(line)
137        .strip_suffix('|')
138        .unwrap_or(line);
139    trimmed.split('|').map(|c| c.trim().to_owned()).collect()
140}
141
142/// A Markdown separator row such as `|---|:--:|` carries no data.
143fn is_separator(cells: &[String]) -> bool {
144    let has_dash = cells.iter().any(|c| c.contains('-'));
145    has_dash
146        && cells
147            .iter()
148            .all(|c| c.chars().all(|ch| ch == '-' || ch == ':'))
149}
150
151/// Render a spreadsheet cell as a string, as XLSForm authoring expects.
152fn cell_to_string(cell: &calamine::Data) -> String {
153    use calamine::Data;
154    match cell {
155        Data::String(s) => s.clone(),
156        Data::Int(i) => i.to_string(),
157        Data::Float(f) if f.fract() == 0.0 => (*f as i64).to_string(),
158        Data::Float(f) => f.to_string(),
159        Data::Bool(b) => b.to_string(),
160        Data::DateTimeIso(s) | Data::DurationIso(s) => s.clone(),
161        _ => String::new(),
162    }
163}
164
165#[cfg(test)]
166mod tests {
167    use super::*;
168
169    #[test]
170    fn splits_sheets_headers_and_rows() {
171        let src = "\
172| survey |         |      |           |
173|        | type    | name | label     |
174|        | text    | q1   | Question  |
175| settings |            |         |
176|          | form_title | form_id |
177|          | Demo       | demo    |
178";
179        let wb = read_markdown(src).unwrap();
180        assert_eq!(wb.sheets.len(), 2);
181
182        let survey = wb.sheet("survey").unwrap();
183        assert_eq!(survey.rows[0], ["type", "name", "label"]);
184        assert_eq!(survey.rows[1], ["text", "q1", "Question"]);
185
186        let settings = wb.sheet("settings").unwrap();
187        assert_eq!(settings.rows[1], ["Demo", "demo"]);
188    }
189
190    #[test]
191    fn skips_separator_rows() {
192        let src = "\
193| survey |      |
194|        | type | name |
195|        | ---  | ---  |
196|        | text | q1   |
197";
198        let survey = read_markdown(src).unwrap().sheet("survey").unwrap().clone();
199        assert_eq!(survey.rows.len(), 2);
200        assert_eq!(survey.rows[1], ["text", "q1"]);
201    }
202
203    #[test]
204    fn csv_uses_the_same_sheet_convention() {
205        let src = "survey,,\n,type,name\n,text,q1\nsettings,\n,form_id\n,demo\n";
206        let wb = read_csv(src).unwrap();
207        assert_eq!(wb.sheet("survey").unwrap().rows[1], ["text", "q1"]);
208        assert_eq!(wb.sheet("settings").unwrap().rows[1], ["demo"]);
209    }
210}