Skip to main content

byob_sheets/
store.rs

1//! Artifacts on disk (`.byob/artifacts/<id>/artifact.json` + version files, as byob writes
2//! them), what a tool's `sheet` argument names, and the live workbooks in memory.
3
4use std::collections::BTreeMap;
5use std::hash::{Hash, Hasher};
6use std::path::{Component, Path, PathBuf};
7use std::time::{Instant, SystemTime, UNIX_EPOCH};
8
9use serde_json::Value;
10
11use crate::SheetError;
12use crate::book::{Book, file_format};
13use crate::text::{pystr, repr_str};
14
15pub const XLSX: &str = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
16pub const CSV: &str = "text/csv";
17pub const TSV: &str = "text/tab-separated-values";
18const SHEET_SUFFIXES: [&str; 4] = [".xlsx", ".csv", ".tsv", ".tab"];
19
20fn id_ok(s: &str) -> bool {
21    let b = s.as_bytes();
22    !b.is_empty() && b.len() <= 128 && b[0].is_ascii_alphanumeric() && b.iter().all(|c| c.is_ascii_alphanumeric() || matches!(c, b'.' | b'_' | b'-'))
23}
24
25fn art_dir(ws: &str, aid: &str) -> PathBuf {
26    Path::new(ws).join(".byob").join("artifacts").join(aid)
27}
28
29pub fn read_meta(ws: &str, aid: &str) -> Option<Value> {
30    if !id_ok(aid) || aid.contains("..") {
31        return None;
32    }
33    let text = std::fs::read(art_dir(ws, aid).join("artifact.json")).ok()?;
34    let v: Value = serde_json::from_slice(&text).ok()?;
35    v.is_object().then_some(v)
36}
37
38pub fn metas(ws: &str) -> Vec<Value> {
39    let root = Path::new(ws).join(".byob").join("artifacts");
40    let Ok(rd) = std::fs::read_dir(&root) else { return Vec::new() };
41    let mut ids: Vec<String> = rd.flatten().map(|e| e.file_name().to_string_lossy().into_owned()).collect();
42    ids.sort();
43    let mut out = Vec::new();
44    for aid in ids {
45        if let Some(mut m) = read_meta(ws, &aid) {
46            if let Some(o) = m.as_object_mut() {
47                o.entry("id").or_insert(Value::String(aid));
48            }
49            out.push(m);
50        }
51    }
52    out
53}
54
55pub fn s<'a>(v: &'a Value, k: &str) -> Option<&'a str> {
56    v.get(k).and_then(Value::as_str)
57}
58
59/// Python's truthiness of a JSON value.
60pub fn truthy(v: Option<&Value>) -> bool {
61    match v {
62        None | Some(Value::Null) => false,
63        Some(Value::Bool(b)) => *b,
64        Some(Value::Number(n)) => n.as_f64().is_some_and(|f| f != 0.0),
65        Some(Value::String(t)) => !t.is_empty(),
66        Some(Value::Array(a)) => !a.is_empty(),
67        Some(Value::Object(o)) => !o.is_empty(),
68    }
69}
70
71/// `meta.get(k) or fallback` as text.
72fn or_text(v: &Value, k: &str, fallback: &str) -> String {
73    match v.get(k) {
74        Some(x) if truthy(Some(x)) => pystr(x),
75        _ => fallback.to_owned(),
76    }
77}
78
79/// (n, absolute path) of the newest version whose file exists.
80pub(crate) fn latest(ws: &str, meta: &Value) -> (Option<i64>, Option<PathBuf>) {
81    let mut vs: Vec<&Value> = meta.get("versions").and_then(Value::as_array).into_iter().flatten().filter(|v| v.is_object()).collect();
82    let key = |v: &Value| v.get("n").and_then(Value::as_i64).filter(|_| v.get("n").is_some_and(Value::is_i64)).unwrap_or(-1);
83    vs.sort_by_key(|v| std::cmp::Reverse(key(v)));
84    for v in vs {
85        if let Some(p) = s(v, "path").filter(|p| !p.is_empty()) {
86            let ap = if Path::new(p).is_absolute() { PathBuf::from(p) } else { Path::new(ws).join(p) };
87            if ap.is_file() {
88                return (v.get("n").and_then(Value::as_i64), Some(ap));
89            }
90        }
91    }
92    (Some(0), None)
93}
94
95pub fn sheet_format(content_type: Option<&str>, path: &str) -> Option<&'static str> {
96    let ct = content_type.unwrap_or_default().split(';').next().unwrap_or_default().trim();
97    match ct {
98        XLSX => return Some("xlsx"),
99        CSV => return Some("csv"),
100        TSV => return Some("tsv"),
101        _ => {}
102    }
103    let low = path.to_lowercase();
104    if !path.is_empty() && SHEET_SUFFIXES.iter().any(|x| low.ends_with(x)) {
105        return Some(file_format(path));
106    }
107    None
108}
109
110fn is_sheet_meta(m: &Value) -> bool {
111    sheet_format(s(m, "content_type"), &or_text(m, "filename", "")).is_some()
112}
113
114/// `stem.xlsx` of a file name.
115pub fn xlsx_name(filename: &str, fallback: &str) -> String {
116    let base = Path::new(filename).file_name().map(|f| f.to_string_lossy().into_owned()).unwrap_or_default();
117    let stem = splitext(&base).0;
118    format!("{}.xlsx", if stem.is_empty() { fallback } else { stem })
119}
120
121/// Python's `os.path.splitext` of a base name.
122pub fn splitext(base: &str) -> (&str, &str) {
123    let lead = base.len() - base.trim_start_matches('.').len();
124    match base[lead..].rfind('.') {
125        Some(i) => base.split_at(lead + i),
126        None => (base, ""),
127    }
128}
129
130/// What a tool's `sheet` argument named: an artifact or a workspace file.
131#[derive(Debug, Clone)]
132pub struct Source {
133    pub artifact: bool,
134    pub path: PathBuf,
135    pub fmt: &'static str,
136    pub aid: String,
137    pub meta: Value,
138    pub version: Option<i64>,
139    pub rel: String,
140    pub note: String,
141}
142
143fn version_text(v: Option<i64>) -> String {
144    v.map_or_else(|| "None".into(), |n| n.to_string())
145}
146
147impl Source {
148    pub fn label(&self) -> String {
149        if self.artifact {
150            format!("\"{}\" ({}, version {})", or_text(&self.meta, "title", &self.aid), self.aid, version_text(self.version))
151        } else {
152            self.rel.clone()
153        }
154    }
155
156    pub fn title(&self) -> String {
157        if self.artifact {
158            return or_text(&self.meta, "title", &self.aid);
159        }
160        let base = Path::new(&self.rel).file_name().map(|f| f.to_string_lossy().into_owned()).unwrap_or_default();
161        splitext(&base).0.to_owned()
162    }
163}
164
165fn artifact_source(ws: &str, meta: &Value, note: String) -> Result<Source, SheetError> {
166    let aid = or_text(meta, "id", "");
167    let (n, path) = latest(ws, meta);
168    let Some(path) = path else { return Err(SheetError::Msg(format!("Artifact {aid} has no saved version on disk."))) };
169    let Some(fmt) = sheet_format(s(meta, "content_type"), &path.to_string_lossy()) else {
170        return Err(SheetError::Msg(format!("{aid} is a {} artifact, not a spreadsheet.", or_text(meta, "content_type", "non-spreadsheet"))));
171    };
172    Ok(Source { artifact: true, path, fmt, aid, meta: meta.clone(), version: n, rel: String::new(), note })
173}
174
175/// Whether artifact `m` is one of `chat`'s (any chat's when there's none, as byob's own
176/// artifact tools: an artifact belongs to the chat that made it, though it's kept in the
177/// folder every chat of a project shares).
178fn in_chat(m: &Value, chat: Option<&str>) -> bool {
179    chat.is_none() || s(m, "chat") == chat
180}
181
182/// The workspace file artifact `m` was made from: its first version's note "From rel", alone
183/// or with the notes of later saves in the same request that byob joins on ("From rel;
184/// write_cells; fill D2:D").
185fn made_from(m: &Value) -> Option<&str> {
186    let first = m.get("versions").and_then(Value::as_array).and_then(|v| v.first())?;
187    let rest = s(first, "note")?.strip_prefix("From ")?;
188    let rel = rest.split_once("; ").map_or(rest, |(rel, _)| rel);
189    (!rel.is_empty() && !rel.starts_with("artifact ")).then_some(rel)
190}
191
192/// Whether artifact `m` was made from workspace file `rel` (see [`made_from`]; exact, so a
193/// file name with "; " in it still matches).
194fn made_from_file(m: &Value, rel: &str) -> bool {
195    let first = m.get("versions").and_then(Value::as_array).and_then(|v| v.first());
196    let Some(rest) = first.and_then(|v| s(v, "note")).and_then(|n| n.strip_prefix("From ")).and_then(|n| n.strip_prefix(rel)) else { return false };
197    rest.is_empty() || rest.starts_with("; ")
198}
199
200/// When an artifact's first version was saved (byob's `created_at`, ms), for "newest".
201fn created(m: &Value) -> i64 {
202    m.get("versions").and_then(Value::as_array).and_then(|v| v.first()).and_then(|v| v.get("created_at")).and_then(Value::as_i64).unwrap_or(0)
203}
204
205/// The newest spreadsheet of `chat` a write (or create_sheet from=) made from workspace file
206/// `rel`, if any.
207fn derived(ws: &str, chat: Option<&str>, rel: &str) -> Option<Value> {
208    metas(ws).into_iter().filter(|m| in_chat(m, chat) && is_sheet_meta(m) && made_from_file(m, rel)).max_by_key(created)
209}
210
211fn sheet_artifacts(ws: &str, chat: Option<&str>) -> Vec<Value> {
212    metas(ws).into_iter().filter(|m| is_sheet_meta(m) && in_chat(m, chat)).collect()
213}
214
215/// A lexically normalized absolute path (Python's `os.path.abspath`).
216fn normalize(p: &Path) -> PathBuf {
217    let abs = if p.is_absolute() { p.to_path_buf() } else { std::env::current_dir().unwrap_or_default().join(p) };
218    let mut out = PathBuf::new();
219    for c in abs.components() {
220        match c {
221            Component::ParentDir => {
222                out.pop();
223            }
224            Component::CurDir => {}
225            other => out.push(other.as_os_str()),
226        }
227    }
228    out
229}
230
231/// Python's `os.path.relpath(path, start)`, with `/` between components on every platform:
232/// it is shown to the model and kept in artifact notes, so it reads the same everywhere. A
233/// path with nothing in common with `start` (another drive) comes back whole, `/`-separated.
234pub fn relpath(path: &Path, start: &Path) -> String {
235    let (p, s) = (normalize(path), normalize(start));
236    let pc: Vec<Component> = p.components().collect();
237    let sc: Vec<Component> = s.components().collect();
238    let common = pc.iter().zip(&sc).take_while(|(a, b)| a == b).count();
239    if common == 0 {
240        return p.to_string_lossy().replace('\\', "/");
241    }
242    let mut out: Vec<String> = vec!["..".to_owned(); sc.len() - common];
243    out.extend(pc[common..].iter().map(|c| c.as_os_str().to_string_lossy().into_owned()));
244    if out.is_empty() { ".".into() } else { out.join("/") }
245}
246
247/// The [`Source`] for a tool's `sheet` argument (an artifact id, a workspace path, or an
248/// artifact's filename or title).
249pub fn resolve(ws: &str, chat: Option<&str>, arg: Option<&Value>, follow: bool) -> Result<Source, SheetError> {
250    let Some(arg) = arg.and_then(Value::as_str).filter(|a| !a.trim().is_empty()) else {
251        return Err(SheetError::Msg("Give `sheet`: an artifact id (like budget-3f2a) or a workspace path of an .xlsx, .csv or .tsv file.".into()));
252    };
253    let mut s0 = arg.trim().trim_matches(|c| c == '"' || c == '\'' || c == '`').to_owned();
254    if let Some(i) = s0.rfind('@') {
255        let (head, tail) = (&s0[..i], &s0[i + 1..]);
256        if !head.is_empty() && !tail.is_empty() && tail.chars().all(|c| c.is_ascii_digit()) {
257            s0 = head.to_owned();
258        }
259    }
260    if let Some(rest) = s0.strip_prefix("artifact:") {
261        s0 = rest.to_owned();
262    }
263    let s1 = s0.as_str();
264    if id_ok(s1)
265        && let Some(mut meta) = read_meta(ws, s1)
266    {
267        if !in_chat(&meta, chat) {
268            let copy = match made_from(&meta) {
269                Some(rel) => format!(" It was made from {rel}: pass {rel} as `sheet` to work on that file in this chat."),
270                None => String::new(),
271            };
272            return Err(SheetError::Msg(format!("Artifact {s1} belongs to another chat; sheet tools only use this chat's artifacts.{copy}")));
273        }
274        // A live file: the person's own file, which its versions only follow. Saving the
275        // sheet over it put an .xlsx in front of the file, and the next snapshot of the CSV
276        // went in as a broken .xlsx; the file is what's meant (a write imports a copy).
277        if let Some(rel) = meta.get("live").and_then(Value::as_str).filter(|r| !r.is_empty()) {
278            let rel = format!("./{}", rel.trim_start_matches("./"));
279            return resolve(ws, chat, Some(&Value::String(rel)), follow);
280        }
281        if let Some(o) = meta.as_object_mut() {
282            o.entry("id").or_insert(Value::String(s1.to_owned()));
283        }
284        return artifact_source(ws, &meta, String::new());
285    }
286    // Files only inside the workspace (or a folder it links), like read_file: the sheet
287    // tools run without asking. Not a path there may still be a title (below).
288    let inside = byob_tools::sandbox::resolve_follow(Path::new(ws), s1);
289    let path = inside.as_ref().map(|r| r.abs.clone()).unwrap_or_default();
290    if inside.is_ok() && path.is_file() {
291        let low = path.to_string_lossy().to_lowercase();
292        if !SHEET_SUFFIXES.iter().any(|x| low.ends_with(x)) {
293            return Err(SheetError::Msg(format!("{s1} isn't a spreadsheet file; use an .xlsx, .csv or .tsv file.")));
294        }
295        let root = Path::new(ws).canonicalize().unwrap_or_else(|_| PathBuf::from(ws));
296        let rel = relpath(&path, &root);
297        if follow && let Some(d) = derived(ws, chat, &rel) {
298            let id = or_text(&d, "id", "");
299            return artifact_source(
300                ws,
301                &d,
302                format!("({rel} is open in this chat as artifact {id}, so this uses that artifact, not the file. Pass {id} as `sheet` from now on.)"),
303            );
304        }
305        let fmt = file_format(&path.to_string_lossy());
306        return Ok(Source { artifact: false, path, fmt, aid: String::new(), meta: Value::Null, version: None, rel, note: String::new() });
307    }
308    let low = s1.to_lowercase();
309    let mut found: Vec<Value> = metas(ws)
310        .into_iter()
311        .filter(|m| {
312            let f = or_text(m, "filename", "");
313            in_chat(m, chat) && is_sheet_meta(m) && [f.to_lowercase(), or_text(m, "title", "").to_lowercase(), splitext(&f).0.to_lowercase()].contains(&low)
314        })
315        .collect();
316    found.sort_by_key(|m| std::cmp::Reverse(created(m)));
317    if let Some(m) = found.first() {
318        let id = or_text(m, "id", "");
319        return artifact_source(ws, m, format!("({s1} is artifact {id} in this chat; using that. Pass {id} as `sheet` from now on.)"));
320    }
321    if let Err(e) = inside {
322        return Err(SheetError::Msg(format!("No spreadsheet {}: {e}.", repr_str(s1))));
323    }
324    let have = sheet_artifacts(ws, chat);
325    let mut hint = String::new();
326    if !have.is_empty() {
327        let list: Vec<String> = have
328            .iter()
329            .take(10)
330            .map(|m| {
331                let f = m.get("filename").filter(|f| truthy(Some(f))).or_else(|| m.get("title")).map_or_else(|| "None".into(), pystr);
332                format!("{} ({f})", m.get("id").map_or_else(|| "None".into(), pystr))
333            })
334            .collect();
335        hint = format!(" Spreadsheets in this chat: {}.", list.join(", "));
336    }
337    Err(SheetError::Msg(format!("No spreadsheet {}: it isn't an artifact id or a file in the workspace.{hint} To make one, call create_sheet.", repr_str(s1))))
338}
339
340// ---- workbooks in memory -----------------------------------------------------------------
341
342fn sha(data: &[u8]) -> u64 {
343    let mut h = std::collections::hash_map::DefaultHasher::new();
344    data.hash(&mut h);
345    h.finish()
346}
347
348fn file_sha(path: &Path) -> Option<u64> {
349    std::fs::read(path).ok().map(|d| sha(&d))
350}
351
352type Stat = (PathBuf, u64, i128);
353
354fn stat(path: &Path) -> Option<Stat> {
355    let m = std::fs::metadata(path).ok()?;
356    let t = m.modified().ok()?.duration_since(UNIX_EPOCH).map(|d| i128::try_from(d.as_nanos()).unwrap_or(0)).unwrap_or(0);
357    Some((path.to_path_buf(), m.len(), t))
358}
359
360/// The live workbook of one artifact: tool writes and grid edits go into it.
361pub struct Entry {
362    pub book: Book,
363    sha: Option<u64>,
364    stat: Option<Stat>,
365    /// The version our state builds on.
366    base: i64,
367    /// Versions we wrote that byob may not have stored yet: (sha, when).
368    ours: Vec<(u64, Instant)>,
369    /// Cells the user changed in the grid since the model's last write.
370    pub user_edits: Vec<String>,
371}
372
373impl Entry {
374    pub fn wrote(&mut self, data: &[u8], base: Option<i64>) {
375        let h = sha(data);
376        self.sha = Some(h);
377        self.ours.retain(|(x, _)| *x != h);
378        self.ours.push((h, Instant::now()));
379        if self.ours.len() > 32 {
380            let drop = self.ours.len() - 32;
381            self.ours.drain(..drop);
382        }
383        self.stat = None;
384        if let Some(b) = base {
385            self.base = self.base.max(b);
386        }
387    }
388
389    pub fn user_edited(&mut self, label: String) {
390        self.user_edits.retain(|l| *l != label);
391        self.user_edits.push(label);
392        if self.user_edits.len() > 200 {
393            let drop = self.user_edits.len() - 200;
394            self.user_edits.drain(..drop);
395        }
396    }
397}
398
399/// Workbooks kept between calls.
400#[derive(Default)]
401pub struct Store {
402    pub entries: BTreeMap<String, Entry>,
403    old: Vec<(PathBuf, Book)>,
404    files: Vec<(PathBuf, Option<Stat>, Book)>,
405    tmp: Option<PathBuf>,
406    tmp_files: Vec<PathBuf>,
407    tmp_n: u64,
408}
409
410fn load(path: &Path, fmt: &str) -> Result<Book, SheetError> {
411    Book::load(path, Some(fmt))
412}
413
414impl Store {
415    /// The live workbook of artifact `aid`, whose latest version (as far as the caller knows)
416    /// is `version` at `path`. The one in memory wins while that file is what we last wrote,
417    /// or older than what our state builds on, or one of ours byob is still storing;
418    /// otherwise (a restore, a file changed elsewhere) it is loaded from the file.
419    pub fn artifact_entry(&mut self, aid: &str, path: &Path, fmt: &str, version: Option<i64>) -> Result<&mut Entry, SheetError> {
420        let sig = stat(path);
421        let keep = match self.entries.get_mut(aid) {
422            Some(e) if sig.is_some() && e.stat == sig => true,
423            Some(e) => {
424                let v = version.unwrap_or(0);
425                let h = file_sha(path);
426                if h == e.sha {
427                    e.stat = sig.clone();
428                    e.base = e.base.max(v);
429                    true
430                } else {
431                    v <= e.base || h.is_some_and(|h| e.ours.iter().any(|(x, t)| *x == h && t.elapsed().as_secs_f64() < 10.0))
432                }
433            }
434            None => false,
435        };
436        if !keep {
437            let book = match load(path, fmt) {
438                Ok(b) => b,
439                Err(SheetError::Io(e)) => return Err(SheetError::Msg(format!("Artifact {aid}'s file couldn't be read ({e})."))),
440                Err(e) => return Err(e),
441            };
442            let e = Entry { book, sha: file_sha(path), stat: sig, base: version.unwrap_or(0), ours: Vec::new(), user_edits: Vec::new() };
443            self.entries.insert(aid.to_owned(), e);
444        }
445        self.entries.get_mut(aid).ok_or_else(|| SheetError::Msg(format!("Artifact {aid} isn't loaded.")))
446    }
447
448    /// Drop artifact `aid`'s live workbook (byob undid versions of it): the next use loads
449    /// its latest version from disk. (Older versions' workbooks stay cached: version numbers
450    /// are never reused.)
451    pub fn forget(&mut self, aid: &str) {
452        self.entries.remove(aid);
453    }
454
455    /// An older version's workbook (read-only views), cached (6).
456    pub fn version_book(&mut self, path: &Path, fmt: &str) -> Result<&mut Book, SheetError> {
457        let book = match self.old.iter().position(|(p, _)| p == path) {
458            Some(i) => self.old.remove(i).1,
459            None => load(path, fmt)?,
460        };
461        self.old.push((path.to_path_buf(), book));
462        while self.old.len() > 6 {
463            self.old.remove(0);
464        }
465        self.old.last_mut().map(|(_, b)| b).ok_or_else(|| SheetError::Msg("no workbook".into()))
466    }
467
468    /// A workspace file's workbook, cached while the file is unchanged (6).
469    pub fn file_book(&mut self, path: &Path, fmt: &str) -> Result<&mut Book, SheetError> {
470        let sig = stat(path);
471        let i = self.files.iter().position(|(p, st, _)| p == path && *st == sig);
472        let i = match i {
473            Some(i) => i,
474            None => {
475                let b = load(path, fmt)?;
476                self.files.retain(|(p, ..)| p != path);
477                self.files.push((path.to_path_buf(), sig, b));
478                while self.files.len() > 6 {
479                    self.files.remove(0);
480                }
481                self.files.len() - 1
482            }
483        };
484        self.files.get_mut(i).map(|(.., b)| b).ok_or_else(|| SheetError::Msg("no workbook".into()))
485    }
486
487    pub fn read_book(&mut self, src: &Source) -> Result<&mut Book, SheetError> {
488        if src.artifact {
489            return Ok(&mut self.artifact_entry(&src.aid, &src.path, src.fmt, src.version)?.book);
490        }
491        self.file_book(&src.path, src.fmt)
492    }
493
494    /// Write the bytes for byob to copy (it copies them right after our reply).
495    pub fn save_tmp(&mut self, data: &[u8], filename: &str) -> Result<String, SheetError> {
496        if self.tmp.as_ref().is_none_or(|d| !d.is_dir()) {
497            // Unique per store in this process too: two stores made in the same instant
498            // (macOS clocks tick in microseconds) shared a folder and overwrote each other's files.
499            static STORES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
500            let n = STORES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
501            let nanos = SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.as_nanos());
502            let dir = std::env::temp_dir().join(format!("byob-sheets-{}-{nanos:x}-{n}", std::process::id()));
503            std::fs::create_dir_all(&dir).map_err(|e| SheetError::Io(e.to_string()))?;
504            self.tmp = Some(dir);
505        }
506        let dir = self.tmp.clone().unwrap_or_else(std::env::temp_dir);
507        self.tmp_n += 1;
508        let base =
509            Path::new(if filename.is_empty() { "sheet.xlsx" } else { filename }).file_name().map(|f| f.to_string_lossy().into_owned()).unwrap_or_default();
510        let mut name = String::new();
511        let mut bad = false;
512        for ch in base.chars() {
513            if ch.is_ascii_alphanumeric() || matches!(ch, '.' | '_' | '-') {
514                name.push(ch);
515                bad = false;
516            } else if !bad {
517                name.push('_');
518                bad = true;
519            }
520        }
521        let path = dir.join(format!("{}-{name}", self.tmp_n));
522        std::fs::write(&path, data).map_err(|e| SheetError::Io(e.to_string()))?;
523        self.tmp_files.push(path.clone());
524        while self.tmp_files.len() > 16 {
525            let old = self.tmp_files.remove(0);
526            let _ = std::fs::remove_file(old);
527        }
528        Ok(path.to_string_lossy().into_owned())
529    }
530
531    /// Remove the temporary folder (on shutdown).
532    pub fn cleanup(&mut self) {
533        if let Some(d) = self.tmp.take() {
534            let _ = std::fs::remove_dir_all(d);
535        }
536    }
537}
538
539#[cfg(test)]
540mod tests {
541    use super::*;
542
543    #[test]
544    fn stores_never_share_a_temporary_folder() {
545        // Regression: the folder was named by process and time alone, and two stores made in
546        // the same microsecond (parallel tests on macOS) wrote each other's files.
547        let (mut a, mut b) = (Store::default(), Store::default());
548        let pa = a.save_tmp(b"a", "Budget.xlsx").unwrap();
549        let pb = b.save_tmp(b"b", "Budget.xlsx").unwrap();
550        assert_ne!(Path::new(&pa).parent(), Path::new(&pb).parent());
551        assert_eq!((std::fs::read(&pa).unwrap(), std::fs::read(&pb).unwrap()), (b"a".to_vec(), b"b".to_vec()));
552        a.cleanup();
553        b.cleanup();
554    }
555
556    #[test]
557    fn relpath_uses_forward_slashes_everywhere() {
558        let ws = std::env::temp_dir().join("ws");
559        assert_eq!(relpath(&ws.join("data").join("sales.csv"), &ws), "data/sales.csv");
560        assert_eq!(relpath(&ws.join("a").join("b").join("c.tsv"), &ws), "a/b/c.tsv");
561        assert_eq!(relpath(&ws.join("x.csv"), &ws.join("sub").join("dir")), "../../x.csv");
562        assert_eq!(relpath(&ws, &ws), ".");
563    }
564
565    /// Regression: `sheet` was any path on the computer (absolute, or climbing out with
566    /// `..`), so the sheet tools, which run without asking, read spreadsheets outside the
567    /// workspace that read_file refuses.
568    #[test]
569    fn only_files_inside_the_workspace_are_sheets() {
570        let outer = tempfile::tempdir().unwrap();
571        let ws = outer.path().join("ws");
572        std::fs::create_dir(&ws).unwrap();
573        std::fs::write(outer.path().join("secret.csv"), "a,b\n1,2\n").unwrap();
574        std::fs::write(ws.join("mine.csv"), "a,b\n1,2\n").unwrap();
575        let ws_s = ws.to_string_lossy().into_owned();
576        let abs = outer.path().join("secret.csv").to_string_lossy().into_owned();
577        for arg in [abs.as_str(), "../secret.csv"] {
578            let Err(SheetError::Msg(e)) = resolve(&ws_s, Some("c"), Some(&Value::String(arg.into())), true) else { panic!("{arg} was read") };
579            assert!(e.contains("outside the workspace"), "{e}");
580        }
581        let src = resolve(&ws_s, Some("c"), Some(&Value::String("mine.csv".into())), true).unwrap();
582        assert_eq!(src.rel, "mine.csv");
583        let inside = ws.join("mine.csv").to_string_lossy().into_owned();
584        assert_eq!(resolve(&ws_s, Some("c"), Some(&Value::String(inside)), true).unwrap().rel, "mine.csv");
585    }
586}