xonecas.ioDon't click! Sean Caetano Martin Sign in
cast / src / workspace / mod.rs 125 lines3.6 kB Raw
1pub mod sidebar;
2pub mod title;
3pub mod welcome;
4
5use crate::paths;
6use crate::workflow::store;
7use std::collections::HashMap;
8use std::path::{Path, PathBuf};
9
10pub const MOUNT: &str = "/cast";
11
12pub struct Workspace {
13    pub dir: PathBuf,
14    pub state: PathBuf,
15    pub prompts: Vec<String>,
16    pub titles: HashMap<String, String>,
17    pub workflows: Vec<(String, u32, bool)>,
18}
19
20impl Workspace {
21    pub fn open(dir: &Path) -> Workspace {
22        let mut ws = Workspace {
23            dir: dir.to_path_buf(),
24            state: paths::state(dir),
25            prompts: vec![],
26            titles: HashMap::new(),
27            workflows: vec![],
28        };
29        ws.rescan();
30        ws
31    }
32
33    pub fn rescan(&mut self) {
34        self.prompts = names(&self.state.join("prompts"), Some("md"));
35        self.titles = self
36            .prompts
37            .iter()
38            .filter_map(|s| Some((s.clone(), title::title(&self.read_prompt(s))?)))
39            .collect();
40        self.workflows = names(&self.state.join("workflows"), None)
41            .into_iter()
42            .filter_map(|stem| {
43                let v = *store::versions(&self.state, &stem).last()?;
44                let approved = store::load(&self.state, &stem, v).is_some_and(|w| w.approved);
45                Some((stem, v, approved))
46            })
47            .collect();
48    }
49
50    pub fn resolve(&self, link: &str) -> PathBuf {
51        resolve(&self.dir, &self.state, link)
52    }
53
54    pub fn prompt_path(&self, stem: &str) -> PathBuf {
55        self.state.join("prompts").join(format!("{stem}.md"))
56    }
57
58    pub fn read_prompt(&self, stem: &str) -> String {
59        std::fs::read_to_string(self.prompt_path(stem)).unwrap_or_default()
60    }
61
62    pub fn write_prompt(&mut self, stem: &str, text: &str) -> std::io::Result<()> {
63        let path = self.prompt_path(stem);
64        std::fs::create_dir_all(path.parent().unwrap_or(&self.state))?;
65        std::fs::write(path, text)?;
66        match title::title(text) {
67            Some(t) => self.titles.insert(stem.to_string(), t),
68            None => self.titles.remove(stem),
69        };
70        Ok(())
71    }
72
73    pub fn new_prompt(&mut self) -> String {
74        let stem = (1..)
75            .map(|n| format!("prompt-{n}"))
76            .find(|s| !self.prompt_path(s).exists())
77            .unwrap_or_default();
78        let _ = self.write_prompt(
79            &stem,
80            &format!("# {stem}\n\nDescribe what you want built.\n"),
81        );
82        self.rescan();
83        stem
84    }
85
86    pub fn run_dir(stem: &str, version: u32) -> String {
87        format!("{MOUNT}/runs/{stem}-v{version}")
88    }
89
90    pub fn evidence_dir(stem: &str, version: u32, task: &str) -> String {
91        format!("{}/{task}", Workspace::run_dir(stem, version))
92    }
93}
94
95pub fn resolve(dir: &Path, state: &Path, link: &str) -> PathBuf {
96    match link.strip_prefix(MOUNT).and_then(|l| l.strip_prefix('/')) {
97        Some(rest) => state.join(rest),
98        None => dir.join(link),
99    }
100}
101
102pub fn summary(dir: &Path) -> (usize, usize) {
103    let cast = paths::state(dir);
104    (
105        names(&cast.join("prompts"), Some("md")).len(),
106        names(&cast.join("workflows"), None).len(),
107    )
108}
109
110fn names(dir: &Path, ext: Option<&str>) -> Vec<String> {
111    let mut out: Vec<String> = std::fs::read_dir(dir)
112        .into_iter()
113        .flatten()
114        .flatten()
115        .map(|e| e.path())
116        .filter(|p| ext.is_none_or(|x| p.extension().is_some_and(|e| e == x)))
117        .filter_map(|p| p.file_stem().map(|s| s.to_string_lossy().into_owned()))
118        .collect();
119    out.sort();
120    out
121}
122
123#[cfg(test)]
124#[path = "tests.rs"]
125mod tests;