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, or no longer.
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 empty file is [`clear`](Self::clear)'s: no selection, and no
52    /// migration either. An unreadable file is an error: never overwrite what we cannot
53    /// read.
54    pub fn load(&self, app_name: &str) -> Result<Option<Selection>> {
55        match std::fs::read_to_string(&self.path) {
56            Ok(text) if text.trim().is_empty() => Ok(None),
57            Ok(text) => toml::from_str(&text)
58                .map(Some)
59                .map_err(|e| Error::Config(format!("{}: {e}", self.path.display()))),
60            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
61                let legacy = self.path.with_file_name(LEGACY_LIST_FILE);
62                let migrated = migrate(&legacy, app_name)?;
63                if let Some(selection) = &migrated {
64                    tracing::info!(
65                        root = %selection.root.display(),
66                        "one workspace per server now; {} becomes this server's workspace",
67                        selection.root.display()
68                    );
69                    self.save(selection)?;
70                }
71                Ok(migrated)
72            }
73            Err(e) => Err(Error::Io(e)),
74        }
75    }
76
77    /// Write it, via a sibling temp file and a rename.
78    pub fn save(&self, selection: &Selection) -> Result<()> {
79        let text = toml::to_string_pretty(selection)
80            .map_err(|e| Error::Config(format!("{}: {e}", self.path.display())))?;
81        self.write(&text)
82    }
83
84    /// Record that there is no selection. The file stays, empty, rather than going: a
85    /// missing file would migrate an older server's list back in.
86    pub fn clear(&self) -> Result<()> {
87        self.write("")
88    }
89
90    fn write(&self, text: &str) -> Result<()> {
91        if let Some(dir) = self.path.parent() {
92            std::fs::create_dir_all(dir).map_err(Error::Io)?;
93        }
94        let tmp = self.path.with_extension("toml.tmp");
95        std::fs::write(&tmp, text).map_err(Error::Io)?;
96        std::fs::rename(&tmp, &self.path).map_err(Error::Io)
97    }
98}
99
100/// The selection an older server's list implies, if it has one.
101fn migrate(legacy: &Path, app_name: &str) -> Result<Option<Selection>> {
102    #[derive(Deserialize)]
103    struct Entry {
104        root: PathBuf,
105        #[serde(default)]
106        synced: bool,
107    }
108    #[derive(Default, Deserialize)]
109    struct List {
110        #[serde(default)]
111        workspace: IndexMap<String, Entry>,
112    }
113    let list: List = match std::fs::read_to_string(legacy) {
114        Ok(text) => toml::from_str(&text)
115            .map_err(|e| Error::Config(format!("{}: {e}", legacy.display())))?,
116        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
117        Err(e) => return Err(Error::Io(e)),
118    };
119    let marker = format!(".{app_name}");
120    let entries: Vec<Entry> = list.workspace.into_values().collect();
121    let chosen = entries
122        .iter()
123        .find(|e| e.synced)
124        .or_else(|| entries.iter().find(|e| e.root.join(&marker).is_dir()));
125    Ok(chosen.map(|e| Selection {
126        root: e.root.clone(),
127        sync: e.synced,
128    }))
129}
130
131/// The registry id a workspace root carries in its marker's `config.toml`: its directory
132/// name, slugified.
133pub(crate) fn slug(root: &Path) -> String {
134    let base: String = root
135        .file_name()
136        .map(|n| n.to_string_lossy().into_owned())
137        .unwrap_or_else(|| "workspace".to_owned())
138        .trim()
139        .to_lowercase()
140        .chars()
141        .map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })
142        .collect();
143    let base = base.trim_matches('-').to_owned();
144    if base.is_empty() {
145        "workspace".to_owned()
146    } else {
147        base
148    }
149}
150
151#[cfg(test)]
152mod tests {
153    use super::*;
154
155    fn file(tmp: &tempfile::TempDir) -> SelectionFile {
156        SelectionFile::at(tmp.path().join("config").join(SELECTION_FILE))
157    }
158
159    #[test]
160    fn no_file_is_no_selection_and_a_saved_one_reads_back() {
161        let tmp = tempfile::tempdir().unwrap();
162        let f = file(&tmp);
163        assert_eq!(f.load("app").unwrap(), None);
164        let s = Selection {
165            root: PathBuf::from("/x/notes"),
166            sync: true,
167        };
168        f.save(&s).unwrap();
169        assert_eq!(f.load("app").unwrap(), Some(s));
170    }
171
172    #[test]
173    fn a_corrupt_file_is_an_error() {
174        let tmp = tempfile::tempdir().unwrap();
175        std::fs::create_dir_all(tmp.path().join("config")).unwrap();
176        std::fs::write(tmp.path().join("config").join(SELECTION_FILE), "root = [").unwrap();
177        assert!(file(&tmp).load("app").is_err());
178    }
179
180    #[test]
181    fn the_old_list_migrates_to_its_synced_workspace() {
182        let tmp = tempfile::tempdir().unwrap();
183        let config = tmp.path().join("config");
184        std::fs::create_dir_all(&config).unwrap();
185        std::fs::write(
186            config.join(LEGACY_LIST_FILE),
187            "[workspace.a]\nroot = \"/x/a\"\n\n[workspace.b]\nroot = \"/x/b\"\nsynced = true\n",
188        )
189        .unwrap();
190        let f = file(&tmp);
191        let s = f.load("app").unwrap().unwrap();
192        assert_eq!(s.root, PathBuf::from("/x/b"));
193        assert!(s.sync);
194        assert!(config.join(SELECTION_FILE).is_file(), "written down");
195    }
196
197    #[test]
198    fn a_cleared_selection_stays_cleared_beside_the_old_list() {
199        let tmp = tempfile::tempdir().unwrap();
200        let config = tmp.path().join("config");
201        std::fs::create_dir_all(&config).unwrap();
202        std::fs::write(
203            config.join(LEGACY_LIST_FILE),
204            "[workspace.a]\nroot = \"/x/a\"\nsynced = true\n",
205        )
206        .unwrap();
207        let f = file(&tmp);
208        assert!(f.load("app").unwrap().is_some(), "migrated");
209        f.clear().unwrap();
210        assert_eq!(f.load("app").unwrap(), None, "not migrated again");
211    }
212
213    #[test]
214    fn without_a_synced_one_the_first_reachable_workspace_migrates() {
215        let tmp = tempfile::tempdir().unwrap();
216        let config = tmp.path().join("config");
217        std::fs::create_dir_all(&config).unwrap();
218        let here = tmp.path().join("here");
219        std::fs::create_dir_all(here.join(".app")).unwrap();
220        std::fs::write(
221            config.join(LEGACY_LIST_FILE),
222            format!(
223                "[workspace.gone]\nroot = \"/x/gone\"\n\n[workspace.here]\nroot = {:?}\n",
224                here.display().to_string()
225            ),
226        )
227        .unwrap();
228        let s = file(&tmp).load("app").unwrap().unwrap();
229        assert_eq!(s.root, here);
230        assert!(!s.sync);
231    }
232
233    #[test]
234    fn slugs_are_lowercase_dashed_names() {
235        assert_eq!(slug(Path::new("/x/My Notes!")), "my-notes");
236        assert_eq!(slug(Path::new("/")), "workspace");
237    }
238}