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/// A workspace root's directory name, slugified: `workspace.init`'s `workspace_id`.
132pub(crate) fn slug(root: &Path) -> String {
133    let base: String = root
134        .file_name()
135        .map(|n| n.to_string_lossy().into_owned())
136        .unwrap_or_else(|| "workspace".to_owned())
137        .trim()
138        .to_lowercase()
139        .chars()
140        .map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })
141        .collect();
142    let base = base.trim_matches('-').to_owned();
143    if base.is_empty() {
144        "workspace".to_owned()
145    } else {
146        base
147    }
148}
149
150#[cfg(test)]
151mod tests {
152    use super::*;
153
154    fn file(tmp: &tempfile::TempDir) -> SelectionFile {
155        SelectionFile::at(tmp.path().join("config").join(SELECTION_FILE))
156    }
157
158    #[test]
159    fn no_file_is_no_selection_and_a_saved_one_reads_back() {
160        let tmp = tempfile::tempdir().unwrap();
161        let f = file(&tmp);
162        assert_eq!(f.load("app").unwrap(), None);
163        let s = Selection {
164            root: PathBuf::from("/x/notes"),
165            sync: true,
166        };
167        f.save(&s).unwrap();
168        assert_eq!(f.load("app").unwrap(), Some(s));
169    }
170
171    #[test]
172    fn a_corrupt_file_is_an_error() {
173        let tmp = tempfile::tempdir().unwrap();
174        std::fs::create_dir_all(tmp.path().join("config")).unwrap();
175        std::fs::write(tmp.path().join("config").join(SELECTION_FILE), "root = [").unwrap();
176        assert!(file(&tmp).load("app").is_err());
177    }
178
179    #[test]
180    fn the_old_list_migrates_to_its_synced_workspace() {
181        let tmp = tempfile::tempdir().unwrap();
182        let config = tmp.path().join("config");
183        std::fs::create_dir_all(&config).unwrap();
184        std::fs::write(
185            config.join(LEGACY_LIST_FILE),
186            "[workspace.a]\nroot = \"/x/a\"\n\n[workspace.b]\nroot = \"/x/b\"\nsynced = true\n",
187        )
188        .unwrap();
189        let f = file(&tmp);
190        let s = f.load("app").unwrap().unwrap();
191        assert_eq!(s.root, PathBuf::from("/x/b"));
192        assert!(s.sync);
193        assert!(config.join(SELECTION_FILE).is_file(), "written down");
194    }
195
196    #[test]
197    fn a_cleared_selection_stays_cleared_beside_the_old_list() {
198        let tmp = tempfile::tempdir().unwrap();
199        let config = tmp.path().join("config");
200        std::fs::create_dir_all(&config).unwrap();
201        std::fs::write(
202            config.join(LEGACY_LIST_FILE),
203            "[workspace.a]\nroot = \"/x/a\"\nsynced = true\n",
204        )
205        .unwrap();
206        let f = file(&tmp);
207        assert!(f.load("app").unwrap().is_some(), "migrated");
208        f.clear().unwrap();
209        assert_eq!(f.load("app").unwrap(), None, "not migrated again");
210    }
211
212    #[test]
213    fn without_a_synced_one_the_first_reachable_workspace_migrates() {
214        let tmp = tempfile::tempdir().unwrap();
215        let config = tmp.path().join("config");
216        std::fs::create_dir_all(&config).unwrap();
217        let here = tmp.path().join("here");
218        std::fs::create_dir_all(here.join(".app")).unwrap();
219        std::fs::write(
220            config.join(LEGACY_LIST_FILE),
221            format!(
222                "[workspace.gone]\nroot = \"/x/gone\"\n\n[workspace.here]\nroot = {:?}\n",
223                here.display().to_string()
224            ),
225        )
226        .unwrap();
227        let s = file(&tmp).load("app").unwrap().unwrap();
228        assert_eq!(s.root, here);
229        assert!(!s.sync);
230    }
231
232    #[test]
233    fn slugs_are_lowercase_dashed_names() {
234        assert_eq!(slug(Path::new("/x/My Notes!")), "my-notes");
235        assert_eq!(slug(Path::new("/")), "workspace");
236    }
237}