Skip to main content

trumly_fs/
library.rs

1//! Where packs come from. Several places are searched and merged; the first place to have a pack's name wins:
2//!
3//! 1. `--packs DIR` / `$TRUMLY_PACKS` (source `custom`)
4//! 2. `./packs` next to the model you run from (`project`)
5//! 3. `~/.trumly/packs`, your own and exported packs (`yours`)
6//! 4. `~/.trumly/community`, packs from other people, unverified (`community`)
7//! 5. the official packs baked into the binary (`built-in`)
8
9use std::fs;
10use std::path::{Path, PathBuf};
11
12use crate::pack::{list_packs, pack_from_texts, Pack};
13
14// The packs embedded by build.rs. Hidden from the docs: it is generated data, not API.
15#[doc(hidden)]
16mod embedded {
17    include!(concat!(env!("OUT_DIR"), "/embedded.rs"));
18}
19use embedded::EMBEDDED;
20
21#[derive(Debug, Clone)]
22pub struct Entry {
23    pub pack: Pack,
24    /// `custom`, `project`, `yours`, `community` or `built-in`
25    pub source: &'static str,
26}
27
28#[derive(Debug)]
29pub struct Library {
30    pub entries: Vec<Entry>,
31    /// where an export goes: the first folder above that can be written to
32    pub export_dir: PathBuf,
33}
34
35impl Library {
36    pub fn packs(&self) -> Vec<Pack> {
37        self.entries.iter().map(|e| e.pack.clone()).collect()
38    }
39    pub fn source_of(&self, name: &str) -> Option<&'static str> {
40        self.entries.iter().find(|e| e.pack.name == name).map(|e| e.source)
41    }
42}
43
44/// The official packs, from the binary.
45pub fn builtin() -> Result<Vec<Pack>, String> {
46    EMBEDDED
47        .iter()
48        .map(|(name, files)| pack_from_texts(&format!("built-in/{name}"), files.iter().map(|(s, t)| (s.to_string(), t.to_string())).collect()))
49        .collect()
50}
51
52fn home() -> Option<PathBuf> {
53    crate::telemetry::trumly_home()
54}
55
56/// Merge every place packs live. `explicit` is `--packs`; `$TRUMLY_PACKS` stands in when it is `None`.
57pub fn load(explicit: Option<&Path>) -> Result<Library, String> {
58    let explicit = explicit.map(Path::to_path_buf).or_else(|| std::env::var_os("TRUMLY_PACKS").map(PathBuf::from));
59    let yours = home().map(|h| h.join("packs"));
60    let community = home().map(|h| h.join("community"));
61    let project = PathBuf::from("packs");
62    let mut places: Vec<(&'static str, PathBuf)> = Vec::new();
63    if let Some(e) = &explicit {
64        places.push(("custom", e.clone()));
65    } else {
66        places.push(("project", project.clone()));
67    }
68    if let Some(y) = &yours {
69        places.push(("yours", y.clone()));
70    }
71    if let Some(c) = &community {
72        places.push(("community", c.clone()));
73    }
74    let mut entries: Vec<Entry> = Vec::new();
75    for (source, dir) in &places {
76        if dir.is_dir() {
77            for pack in list_packs(dir)? {
78                if !entries.iter().any(|e| e.pack.name == pack.name) {
79                    entries.push(Entry { pack, source });
80                }
81            }
82        }
83    }
84    for pack in builtin()? {
85        if !entries.iter().any(|e| e.pack.name == pack.name) {
86            entries.push(Entry { pack, source: "built-in" });
87        }
88    }
89    entries.sort_by(|a, b| a.pack.name.cmp(&b.pack.name));
90    let export_dir = match &explicit {
91        Some(e) => e.clone(),
92        None if project.is_dir() => project,
93        None => yours.unwrap_or_else(|| PathBuf::from("packs")),
94    };
95    Ok(Library { entries, export_dir })
96}
97
98/// Export a pack made in the model to the library's export folder. A name that belongs to an official pack is refused,
99/// so a local copy cannot quietly stand in for it.
100pub fn export(model: &Path, lib: &Library, name: &str) -> Result<(usize, PathBuf), String> {
101    if builtin()?.iter().any(|p| p.name == name) {
102        return Err(format!("'{name}' is the name of an official pack. Give yours a different name."));
103    }
104    fs::create_dir_all(&lib.export_dir).map_err(|e| format!("cannot create {}: {e}", lib.export_dir.display()))?;
105    let n = crate::pack::export(model, &lib.export_dir, name)?;
106    Ok((n, lib.export_dir.join(name)))
107}
108
109/// A pack's name as it may appear in usage data: official names as they are, anything else just "custom".
110pub fn public_name(name: &str) -> String {
111    if builtin().is_ok_and(|b| b.iter().any(|p| p.name == name)) { name.to_string() } else { "custom".to_string() }
112}