Skip to main content

deepdoc_core/extract/
csv.rs

1//! CSV extractor — one table, the first record as its header.
2
3use std::path::Path;
4
5use crate::detect::{Format, Sniff};
6use crate::error::{Error, Result};
7use crate::extract::{ExtractOpts, Extractor};
8use crate::model::{Block, Document, Metadata, Row};
9
10pub struct CsvExtractor;
11
12impl Extractor for CsvExtractor {
13    fn name(&self) -> &'static str {
14        "csv"
15    }
16
17    fn supports(&self, _path: &Path, sniff: &Sniff) -> bool {
18        crate::detect::detect(sniff) == Some(Format::Csv)
19    }
20
21    fn extract(&self, path: &Path, _opts: &ExtractOpts) -> Result<Document> {
22        let raw = std::fs::read(path).map_err(|e| Error::io(path, e))?;
23        let blocks = parse(&raw).map_err(|message| Error::parse(path, message))?;
24
25        Ok(Document {
26            meta: Metadata {
27                source_format: Some(Format::Csv),
28                source_path: Some(path.display().to_string()),
29                ..Metadata::default()
30            },
31            blocks,
32        })
33    }
34}
35
36/// Parse CSV bytes into a single table block. Pure.
37pub fn parse(raw: &[u8]) -> std::result::Result<Vec<Block>, String> {
38    let mut reader = csv::ReaderBuilder::new()
39        // Ragged rows are common in exported data; keep them rather than fail.
40        .flexible(true)
41        // Headers are handled here, not by the reader, so the first record is
42        // available like any other.
43        .has_headers(false)
44        .from_reader(raw);
45
46    let mut records = Vec::new();
47    for record in reader.records() {
48        let record = record.map_err(|e| e.to_string())?;
49        records.push(Row::from_texts(record.iter()));
50    }
51
52    if records.is_empty() {
53        return Ok(Vec::new());
54    }
55
56    let header = records.remove(0);
57    Ok(vec![Block::Table {
58        header: Some(header),
59        rows: records,
60    }])
61}
62
63#[cfg(test)]
64mod tests {
65    use super::*;
66
67    #[test]
68    fn first_record_becomes_the_header() {
69        let blocks = parse(b"name,qty\nbolt,4\nnut,8\n").unwrap();
70        assert_eq!(
71            blocks,
72            vec![Block::Table {
73                header: Some(Row::from_texts(["name", "qty"])),
74                rows: vec![
75                    Row::from_texts(["bolt", "4"]),
76                    Row::from_texts(["nut", "8"])
77                ],
78            }]
79        );
80    }
81
82    #[test]
83    fn quoted_fields_keep_their_commas_and_newlines() {
84        let blocks = parse(b"a,b\n\"x,y\",\"line1\nline2\"\n").unwrap();
85        let Block::Table { rows, .. } = &blocks[0] else {
86            panic!("expected a table");
87        };
88        assert_eq!(rows[0], Row::from_texts(["x,y", "line1\nline2"]));
89    }
90
91    #[test]
92    fn ragged_rows_are_kept() {
93        let blocks = parse(b"a,b,c\n1,2\n").unwrap();
94        let Block::Table { rows, .. } = &blocks[0] else {
95            panic!("expected a table");
96        };
97        assert_eq!(rows[0], Row::from_texts(["1", "2"]));
98    }
99
100    #[test]
101    fn empty_input_yields_no_blocks() {
102        assert!(parse(b"").unwrap().is_empty());
103    }
104}