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