Skip to main content

rig_tools/
spill.rs

1//! Output a tool cut, kept whole in a file the model can `read` or
2//! `search`, so cut-off output is never gone for good.
3
4use std::fs::{self, File, OpenOptions};
5use std::io;
6use std::path::PathBuf;
7
8/// The directory where tools keep output they cut, each in a file of its
9/// own whose path, the handle, the cut output names.
10#[derive(Clone, Debug)]
11pub struct Spill(pub PathBuf);
12
13impl Spill {
14    /// A new empty file for `tool`'s output, `<tool>-<n>.txt` with the
15    /// first free `n`, and its path.
16    pub fn create(&self, tool: &str) -> io::Result<(PathBuf, File)> {
17        fs::create_dir_all(&self.0)?;
18        let mut n = 1_u64;
19        loop {
20            let path = self.0.join(format!("{tool}-{n}.txt"));
21            match OpenOptions::new().write(true).create_new(true).open(&path) {
22                Ok(file) => return Ok((path, file)),
23                Err(error) if error.kind() == io::ErrorKind::AlreadyExists => n += 1,
24                Err(error) => return Err(error),
25            }
26        }
27    }
28}