cell-sheet-tui 0.4.0

A terminal spreadsheet editor with Vim-like keybindings
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
//! Non-interactive CLI surface (issue #6).
//!
//! Lets users run `cell` headlessly to read/eval/write cells from shell
//! pipelines, Makefiles, and CI without launching the TUI. Operations apply in
//! a fixed order: writes → save → reads → evals. Results print to stdout, one
//! per `--read`/`--eval` flag, and ranges render as TSV (rows separated by
//! `\n`, columns by `\t`).

use std::io::Write;
use std::path::{Path, PathBuf};

use cell_sheet_core::formula::ast::{CellRef, Expr};
use cell_sheet_core::formula::deps::{mark_dirty, recalculate, set_formula, DepGraph};
use cell_sheet_core::formula::{eval, parser};
use cell_sheet_core::io::{cell_format, csv as csv_io};
use cell_sheet_core::model::{CellPos, CellValue, Sheet};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Format {
    Csv,
    Tsv,
    Cell,
}

impl Format {
    fn from_path(path: &Path) -> Self {
        match path
            .extension()
            .and_then(|e| e.to_str())
            .unwrap_or("")
            .to_lowercase()
            .as_str()
        {
            "tsv" => Format::Tsv,
            "cell" => Format::Cell,
            _ => Format::Csv,
        }
    }
}

/// Magic header for the native `.cell` text format. Both the existing
/// writer (`write_cell_format`) and reader (`read_cell_format`) anchor on
/// `# cell v1` as the first line, so detecting it on a stdin byte stream
/// is unambiguous and safe to use to dispatch between the cell-format and
/// CSV/TSV readers.
const CELL_FORMAT_MAGIC: &[u8] = b"# cell v";

/// Detect whether a stdin byte stream is in the native `.cell` format.
/// Returns `Format::Cell` when the first line begins with the cell-format
/// magic header, otherwise `Format::Csv` (CSV/TSV both go through
/// `csv_io::read_csv`, with the delimiter sniffed separately).
fn detect_stdin_format(data: &[u8]) -> Format {
    if data.starts_with(CELL_FORMAT_MAGIC) {
        Format::Cell
    } else {
        Format::Csv
    }
}

#[derive(Debug)]
pub struct Options {
    pub file: PathBuf,
    /// Raw bytes read from stdin when no FILE was given and stdin is not a TTY.
    pub stdin_data: Option<Vec<u8>>,
    pub reads: Vec<String>,
    pub evals: Vec<String>,
    pub writes: Vec<(String, String)>,
    pub delimiter: Option<u8>,
}

fn resolve_delimiter(
    path: &Path,
    format: Format,
    explicit: Option<u8>,
) -> Result<u8, Box<dyn std::error::Error>> {
    if let Some(d) = explicit {
        return Ok(d);
    }
    match format {
        Format::Tsv => Ok(b'\t'),
        Format::Cell => Ok(b','), // unused — .cell files don't use a delimiter
        Format::Csv => {
            use std::io::Read as _;
            let mut buf = vec![0u8; 4096];
            let mut file = std::fs::File::open(path)?;
            let n = file.read(&mut buf)?;
            Ok(csv_io::sniff_delimiter(&buf[..n]))
        }
    }
}

/// Run the requested headless operations and write their textual results to
/// `out`. Errors are returned with a human-readable message; callers are
/// responsible for emitting them to stderr and choosing an exit code.
pub fn run<W: Write>(opts: &Options, out: &mut W) -> Result<(), String> {
    let (mut sheet, mut deps, file_ctx) = if let Some(ref data) = opts.stdin_data {
        if !opts.writes.is_empty() {
            return Err(
                "cannot use --write when reading from stdin; provide a FILE argument instead"
                    .to_string(),
            );
        }
        let format = detect_stdin_format(data);
        if matches!(format, Format::Cell) && opts.delimiter.is_some() {
            return Err(
                "--delimiter has no effect on .cell-format input piped to stdin".to_string(),
            );
        }
        let delimiter = opts
            .delimiter
            .unwrap_or_else(|| csv_io::sniff_delimiter(data));
        let (sheet, deps) = load_from_bytes(data, format, delimiter)
            .map_err(|e| format!("failed to parse stdin: {e}"))?;
        (sheet, deps, None::<(Format, u8)>)
    } else {
        let format = Format::from_path(&opts.file);
        let delimiter = resolve_delimiter(&opts.file, format, opts.delimiter)
            .map_err(|e| format!("failed to read {}: {e}", opts.file.display()))?;
        let (sheet, deps) = load(&opts.file, format, delimiter)
            .map_err(|e| format!("failed to read {}: {e}", opts.file.display()))?;
        (sheet, deps, Some((format, delimiter)))
    };

    if !opts.writes.is_empty() {
        // Only reachable when opts.stdin_data is None (stdin + writes already errored above).
        let (format, delimiter) = file_ctx
            .ok_or_else(|| "internal error: --write reached without a file path".to_string())?;
        for (idx, (ref_str, value)) in opts.writes.iter().enumerate() {
            let pos = parse_single_ref(ref_str).ok_or_else(|| {
                format!(
                    "invalid cell reference for --write #{}: {ref_str:?}",
                    idx + 1
                )
            })?;
            apply_write(&mut sheet, &mut deps, pos, value);
        }
        recalculate(&mut sheet, &deps);
        save(&opts.file, format, &sheet, delimiter)
            .map_err(|e| format!("failed to write {}: {e}", opts.file.display()))?;
    }

    for ref_str in &opts.reads {
        let rendered = render_read(&sheet, ref_str)?;
        writeln!(out, "{rendered}").map_err(|e| format!("write error: {e}"))?;
    }

    for expr in &opts.evals {
        let formula = expr.strip_prefix('=').unwrap_or(expr);
        let value = eval::evaluate(formula, &sheet);
        if let CellValue::Error(err) = &value {
            return Err(format!("evaluation error in {expr:?}: {err}"));
        }
        writeln!(out, "{value}").map_err(|e| format!("write error: {e}"))?;
    }

    Ok(())
}

fn load(
    path: &Path,
    format: Format,
    delimiter: u8,
) -> Result<(Sheet, DepGraph), Box<dyn std::error::Error>> {
    let mut sheet = match format {
        Format::Csv | Format::Tsv => {
            let file = std::fs::File::open(path)?;
            csv_io::read_csv(file, delimiter)?
        }
        Format::Cell => {
            let file = std::fs::File::open(path)?;
            cell_format::read_cell_format(file)?
        }
    };
    let mut deps = DepGraph::new();

    let formula_cells: Vec<_> = sheet
        .cells
        .iter()
        .filter(|(_, cell)| cell.raw.starts_with('='))
        .map(|(pos, cell)| (*pos, cell.raw.clone()))
        .collect();
    for (pos, raw) in formula_cells {
        set_formula(&mut sheet, &mut deps, pos, &raw);
    }
    recalculate(&mut sheet, &deps);

    Ok((sheet, deps))
}

fn load_from_bytes(
    data: &[u8],
    format: Format,
    delimiter: u8,
) -> Result<(Sheet, DepGraph), Box<dyn std::error::Error>> {
    let mut sheet = match format {
        Format::Cell => cell_format::read_cell_format(data)?,
        Format::Csv | Format::Tsv => csv_io::read_csv(data, delimiter)?,
    };
    let mut deps = DepGraph::new();

    let formula_cells: Vec<_> = sheet
        .cells
        .iter()
        .filter(|(_, cell)| cell.raw.starts_with('='))
        .map(|(pos, cell)| (*pos, cell.raw.clone()))
        .collect();
    for (pos, raw) in formula_cells {
        set_formula(&mut sheet, &mut deps, pos, &raw);
    }
    recalculate(&mut sheet, &deps);

    Ok((sheet, deps))
}

fn save(
    path: &Path,
    format: Format,
    sheet: &Sheet,
    delimiter: u8,
) -> Result<(), Box<dyn std::error::Error>> {
    let file = std::fs::File::create(path)?;
    match format {
        Format::Csv | Format::Tsv => csv_io::write_csv(sheet, file, delimiter)?,
        Format::Cell => cell_format::write_cell_format(sheet, file)?,
    }
    Ok(())
}

fn apply_write(sheet: &mut Sheet, deps: &mut DepGraph, pos: CellPos, value: &str) {
    if value.starts_with('=') {
        set_formula(sheet, deps, pos, value);
    } else {
        // Drop any prior formula edges so dependents don't keep tracking this cell.
        deps.remove(pos);
        sheet.set_cell(pos, value);
    }
    mark_dirty(sheet, deps, pos);
}

/// Parse a single A1-style reference like "A1" or "AB12". 1-indexed rows.
/// Internally reuses the formula parser so behaviour stays in sync with
/// formulas typed inside the TUI.
fn parse_single_ref(s: &str) -> Option<CellPos> {
    let trimmed = s.trim();
    let expr = parser::parse(trimmed).ok()?;
    match expr {
        Expr::CellRef(CellRef { row, col, .. }) => Some((row, col)),
        _ => None,
    }
}

fn parse_range_ref(s: &str) -> Option<(CellPos, CellPos)> {
    let trimmed = s.trim();
    let expr = parser::parse(trimmed).ok()?;
    match expr {
        Expr::CellRef(CellRef { row, col, .. }) => Some(((row, col), (row, col))),
        Expr::Range { start, end } => {
            let r1 = start.row.min(end.row);
            let r2 = start.row.max(end.row);
            let c1 = start.col.min(end.col);
            let c2 = start.col.max(end.col);
            Some(((r1, c1), (r2, c2)))
        }
        _ => None,
    }
}

fn render_read(sheet: &Sheet, ref_str: &str) -> Result<String, String> {
    let (start, end) = parse_range_ref(ref_str)
        .ok_or_else(|| format!("invalid cell reference for --read: {ref_str:?}"))?;

    let mut rows = Vec::with_capacity(end.0 - start.0 + 1);
    for r in start.0..=end.0 {
        let mut cols = Vec::with_capacity(end.1 - start.1 + 1);
        for c in start.1..=end.1 {
            let value = match sheet.get_cell((r, c)) {
                Some(cell) => cell.value.to_string(),
                None => String::new(),
            };
            cols.push(value);
        }
        rows.push(cols.join("\t"));
    }
    Ok(rows.join("\n"))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parse_single_ref_basic() {
        assert_eq!(parse_single_ref("A1"), Some((0, 0)));
        assert_eq!(parse_single_ref("B3"), Some((2, 1)));
        assert_eq!(parse_single_ref("AA10"), Some((9, 26)));
    }

    #[test]
    fn parse_single_ref_rejects_garbage() {
        assert_eq!(parse_single_ref("not-a-ref"), None);
        assert_eq!(parse_single_ref(""), None);
        assert_eq!(parse_single_ref("A1:B2"), None);
    }

    #[test]
    fn parse_range_ref_normalises_corners() {
        assert_eq!(
            parse_range_ref("B3:A1"),
            Some(((0, 0), (2, 1))),
            "range corners should be normalised so iteration is forward"
        );
    }

    #[test]
    fn run_reads_from_stdin_data() {
        let opts = Options {
            file: PathBuf::new(),
            stdin_data: Some(b"10,20\n30,40\n".to_vec()),
            reads: vec!["A1".to_string()],
            evals: vec![],
            writes: vec![],
            delimiter: None,
        };
        let mut out = Vec::new();
        run(&opts, &mut out).unwrap();
        assert_eq!(String::from_utf8(out).unwrap(), "10\n");
    }

    #[test]
    fn run_evals_from_stdin_data() {
        let opts = Options {
            file: PathBuf::new(),
            stdin_data: Some(b"1\n2\n3\n4\n".to_vec()),
            reads: vec![],
            evals: vec!["=SUM(A1:A4)".to_string()],
            writes: vec![],
            delimiter: None,
        };
        let mut out = Vec::new();
        run(&opts, &mut out).unwrap();
        assert_eq!(String::from_utf8(out).unwrap(), "10\n");
    }

    #[test]
    fn run_rejects_write_with_stdin_data() {
        let opts = Options {
            file: PathBuf::new(),
            stdin_data: Some(b"10,20\n".to_vec()),
            reads: vec![],
            evals: vec![],
            writes: vec![("A1".to_string(), "99".to_string())],
            delimiter: None,
        };
        let mut out = Vec::new();
        let err = run(&opts, &mut out).unwrap_err();
        assert!(err.contains("--write"), "expected --write in error: {err}");
    }

    #[test]
    fn run_stdin_empty_produces_empty_sheet() {
        let opts = Options {
            file: PathBuf::new(),
            stdin_data: Some(vec![]),
            reads: vec!["A1".to_string()],
            evals: vec![],
            writes: vec![],
            delimiter: None,
        };
        let mut out = Vec::new();
        run(&opts, &mut out).unwrap();
        // Empty stdin yields an empty sheet; A1 is blank → empty string
        assert_eq!(String::from_utf8(out).unwrap(), "\n");
    }

    #[test]
    fn run_stdin_respects_explicit_delimiter() {
        let opts = Options {
            file: PathBuf::new(),
            stdin_data: Some(b"a|b|c\n".to_vec()),
            reads: vec!["B1".to_string()],
            evals: vec![],
            writes: vec![],
            delimiter: Some(b'|'),
        };
        let mut out = Vec::new();
        run(&opts, &mut out).unwrap();
        assert_eq!(String::from_utf8(out).unwrap(), "b\n");
    }

    #[test]
    fn run_sniffs_tsv_from_stdin_data() {
        let opts = Options {
            file: PathBuf::new(),
            stdin_data: Some(b"hello\tworld\n".to_vec()),
            reads: vec!["B1".to_string()],
            evals: vec![],
            writes: vec![],
            delimiter: None,
        };
        let mut out = Vec::new();
        run(&opts, &mut out).unwrap();
        assert_eq!(String::from_utf8(out).unwrap(), "world\n");
    }
}