Skip to main content

sapphire_framework_server/
selection.rs

1//! Which workspace this host's server serves (#215): `<config dir>/workspace.toml`.
2//!
3//! One server, one workspace. The choice belongs to the host, not to the workspace, so it
4//! lives in the application's config directory, and a restarted server comes back to it.
5
6use std::path::{Path, PathBuf};
7
8use indexmap::IndexMap;
9use sapphire_workspace::AppContext;
10use serde::{Deserialize, Serialize};
11
12use crate::error::{Error, Result};
13
14/// The file's name inside the application's config directory.
15pub const SELECTION_FILE: &str = "workspace.toml";
16
17/// The host-wide list the server kept before #215, read once to migrate.
18const LEGACY_LIST_FILE: &str = "workspaces.toml";
19
20/// What `workspace.toml` holds.
21#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
22pub struct Selection {
23    /// The workspace's canonical root.
24    pub root: PathBuf,
25    /// Whether sync is on for it.
26    #[serde(default)]
27    pub sync: bool,
28}
29
30/// The selection file, read and written whole.
31#[derive(Clone, Debug)]
32pub struct SelectionFile {
33    path: PathBuf,
34}
35
36impl SelectionFile {
37    /// `ctx`'s application's file.
38    pub fn for_app(ctx: &AppContext) -> SelectionFile {
39        SelectionFile::at(ctx.config_dir().join(SELECTION_FILE))
40    }
41
42    /// The file at an explicit path: fixtures that run several hosts in one process.
43    pub fn at(path: PathBuf) -> SelectionFile {
44        SelectionFile { path }
45    }
46
47    /// The selection, or `None` when there is none yet.
48    ///
49    /// With no file but the list an older server kept beside it, the list's first synced
50    /// workspace — else its first one whose marker is still there — is the selection, and
51    /// is written down. An unreadable file is an error: never overwrite what we cannot read.
52    pub fn load(&self, app_name: &str) -> Result<Option<Selection>> {
53        match std::fs::read_to_string(&self.path) {
54            Ok(text) => toml::from_str(&text)
55                .map(Some)
56                .map_err(|e| Error::Config(format!("{}: {e}", self.path.display()))),
57            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
58                let legacy = self.path.with_file_name(LEGACY_LIST_FILE);
59                let migrated = migrate(&legacy, app_name)?;
60                if let Some(selection) = &migrated {
61                    tracing::info!(
62                        root = %selection.root.display(),
63                        "one workspace per server now; {} becomes this server's workspace",
64                        selection.root.display()
65                    );
66                    self.save(selection)?;
67                }
68                Ok(migrated)
69            }
70            Err(e) => Err(Error::Io(e)),
71        }
72    }
73
74    /// Write it, via a sibling temp file and a rename.
75    pub fn save(&self, selection: &Selection) -> Result<()> {
76        if let Some(dir) = self.path.parent() {
77            std::fs::create_dir_all(dir).map_err(Error::Io)?;
78        }
79        let text = toml::to_string_pretty(selection)
80            .map_err(|e| Error::Config(format!("{}: {e}", self.path.display())))?;
81        let tmp = self.path.with_extension("toml.tmp");
82        std::fs::write(&tmp, text).map_err(Error::Io)?;
83        std::fs::rename(&tmp, &self.path).map_err(Error::Io)
84    }
85}
86
87/// The selection an older server's list implies, if it has one.
88fn migrate(legacy: &Path, app_name: &str) -> Result<Option<Selection>> {
89    #[derive(Deserialize)]
90    struct Entry {
91        root: PathBuf,
92        #[serde(default)]
93        synced: bool,
94    }
95    #[derive(Default, Deserialize)]
96    struct List {
97        #[serde(default)]
98        workspace: IndexMap<String, Entry>,
99    }
100    let list: List = match std::fs::read_to_string(legacy) {
101        Ok(text) => toml::from_str(&text)
102            .map_err(|e| Error::Config(format!("{}: {e}", legacy.display())))?,
103        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
104        Err(e) => return Err(Error::Io(e)),
105    };
106    let marker = format!(".{app_name}");
107    let entries: Vec<Entry> = list.workspace.into_values().collect();
108    let chosen = entries
109        .iter()
110        .find(|e| e.synced)
111        .or_else(|| entries.iter().find(|e| e.root.join(&marker).is_dir()));
112    Ok(chosen.map(|e| Selection {
113        root: e.root.clone(),
114        sync: e.synced,
115    }))
116}
117
118/// The registry id a workspace root carries in its marker's `config.toml`: its directory
119/// name, slugified.
120pub(crate) fn slug(root: &Path) -> String {
121    let base: String = root
122        .file_name()
123        .map(|n| n.to_string_lossy().into_owned())
124        .unwrap_or_else(|| "workspace".to_owned())
125        .trim()
126        .to_lowercase()
127        .chars()
128        .map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })
129        .collect();
130    let base = base.trim_matches('-').to_owned();
131    if base.is_empty() {
132        "workspace".to_owned()
133    } else {
134        base
135    }
136}
137
138#[cfg(test)]
139mod tests {
140    use super::*;
141
142    fn file(tmp: &tempfile::TempDir) -> SelectionFile {
143        SelectionFile::at(tmp.path().join("config").join(SELECTION_FILE))
144    }
145
146    #[test]
147    fn no_file_is_no_selection_and_a_saved_one_reads_back() {
148        let tmp = tempfile::tempdir().unwrap();
149        let f = file(&tmp);
150        assert_eq!(f.load("app").unwrap(), None);
151        let s = Selection {
152            root: PathBuf::from("/x/notes"),
153            sync: true,
154        };
155        f.save(&s).unwrap();
156        assert_eq!(f.load("app").unwrap(), Some(s));
157    }
158
159    #[test]
160    fn a_corrupt_file_is_an_error() {
161        let tmp = tempfile::tempdir().unwrap();
162        std::fs::create_dir_all(tmp.path().join("config")).unwrap();
163        std::fs::write(tmp.path().join("config").join(SELECTION_FILE), "root = [").unwrap();
164        assert!(file(&tmp).load("app").is_err());
165    }
166
167    #[test]
168    fn the_old_list_migrates_to_its_synced_workspace() {
169        let tmp = tempfile::tempdir().unwrap();
170        let config = tmp.path().join("config");
171        std::fs::create_dir_all(&config).unwrap();
172        std::fs::write(
173            config.join(LEGACY_LIST_FILE),
174            "[workspace.a]\nroot = \"/x/a\"\n\n[workspace.b]\nroot = \"/x/b\"\nsynced = true\n",
175        )
176        .unwrap();
177        let f = file(&tmp);
178        let s = f.load("app").unwrap().unwrap();
179        assert_eq!(s.root, PathBuf::from("/x/b"));
180        assert!(s.sync);
181        assert!(config.join(SELECTION_FILE).is_file(), "written down");
182    }
183
184    #[test]
185    fn without_a_synced_one_the_first_reachable_workspace_migrates() {
186        let tmp = tempfile::tempdir().unwrap();
187        let config = tmp.path().join("config");
188        std::fs::create_dir_all(&config).unwrap();
189        let here = tmp.path().join("here");
190        std::fs::create_dir_all(here.join(".app")).unwrap();
191        std::fs::write(
192            config.join(LEGACY_LIST_FILE),
193            format!(
194                "[workspace.gone]\nroot = \"/x/gone\"\n\n[workspace.here]\nroot = {:?}\n",
195                here.display().to_string()
196            ),
197        )
198        .unwrap();
199        let s = file(&tmp).load("app").unwrap().unwrap();
200        assert_eq!(s.root, here);
201        assert!(!s.sync);
202    }
203
204    #[test]
205    fn slugs_are_lowercase_dashed_names() {
206        assert_eq!(slug(Path::new("/x/My Notes!")), "my-notes");
207        assert_eq!(slug(Path::new("/")), "workspace");
208    }
209}