Skip to main content

surjection_core/remote/
config.rs

1//! `state/remotes.toml` (SPEC 9.6): this machine's remotes. Machine-local
2//! and never synced, because URLs, mount paths and auth differ per
3//! machine; the store, the spec and the binary carry no remote. No remote
4//! exists until the user adds one, and none is ranked: they keep the order
5//! they were added in.
6
7use std::path::Path;
8
9use serde::{Deserialize, Serialize};
10
11use crate::error::{CoreError, ErrorCode};
12use crate::fs::Fs;
13use crate::model::SCHEMA_VERSION;
14use crate::remote::git::GitAuth;
15
16/// The file in `state/`.
17pub const REMOTES_FILE: &str = "remotes.toml";
18/// Archives kept by an `archive` folder remote unless `keep` says otherwise.
19pub const DEFAULT_KEEP: u32 = 10;
20
21/// What a remote is.
22#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
23#[serde(rename_all = "lowercase")]
24pub enum RemoteKind {
25    /// Any git URL, through the system git (M13).
26    Git,
27    /// A local or network directory.
28    Folder,
29}
30
31impl RemoteKind {
32    pub const fn as_str(self) -> &'static str {
33        match self {
34            RemoteKind::Git => "git",
35            RemoteKind::Folder => "folder",
36        }
37    }
38}
39
40/// How a folder remote holds a machine's store.
41#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
42#[serde(rename_all = "kebab-case")]
43pub enum FolderMode {
44    /// A bare repository per machine (`store.git`), pulled from.
45    #[default]
46    RepoPerMachine,
47    /// The HEAD tree as plain files (`latest/`), export only.
48    Mirror,
49    /// Zips of the HEAD tree (`archives/`), export only.
50    Archive,
51}
52
53impl FolderMode {
54    pub const fn as_str(self) -> &'static str {
55        match self {
56            FolderMode::RepoPerMachine => "repo-per-machine",
57            FolderMode::Mirror => "mirror",
58            FolderMode::Archive => "archive",
59        }
60    }
61
62    pub fn parse(text: &str) -> Result<Self, CoreError> {
63        match text {
64            "repo-per-machine" => Ok(Self::RepoPerMachine),
65            "mirror" => Ok(Self::Mirror),
66            "archive" => Ok(Self::Archive),
67            other => Err(CoreError::new(
68                ErrorCode::InvalidValue,
69                format!(
70                    "unknown folder mode {other:?}; expected repo-per-machine, mirror or archive"
71                ),
72            )),
73        }
74    }
75}
76
77/// One `[[remote]]`.
78#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
79pub struct RemoteConfig {
80    pub name: String,
81    pub kind: RemoteKind,
82    /// Folder remotes: the path as the user typed it.
83    #[serde(default, skip_serializing_if = "Option::is_none")]
84    pub path: Option<String>,
85    #[serde(default, skip_serializing_if = "Option::is_none")]
86    pub mode: Option<FolderMode>,
87    /// Archive mode: how many archives to keep.
88    #[serde(default, skip_serializing_if = "Option::is_none")]
89    pub keep: Option<u32>,
90    /// Git remotes (M13).
91    #[serde(default, skip_serializing_if = "Option::is_none")]
92    pub url: Option<String>,
93    #[serde(default, skip_serializing_if = "Option::is_none")]
94    pub auth: Option<String>,
95    #[serde(default, skip_serializing_if = "Option::is_none")]
96    pub username: Option<String>,
97    /// `manual`, `on-commit` or `interval:15m` (SPEC 9.8).
98    #[serde(default, skip_serializing_if = "Option::is_none")]
99    pub push: Option<String>,
100    /// `manual`, `on-start` or `interval:15m`.
101    #[serde(default, skip_serializing_if = "Option::is_none")]
102    pub pull: Option<String>,
103    #[serde(flatten)]
104    pub extra: toml::Table,
105}
106
107impl RemoteConfig {
108    /// A folder remote at `path`.
109    pub fn folder(name: &str, path: &str, mode: FolderMode) -> Self {
110        Self {
111            name: name.to_owned(),
112            kind: RemoteKind::Folder,
113            path: Some(path.to_owned()),
114            mode: Some(mode),
115            keep: None,
116            url: None,
117            auth: None,
118            username: None,
119            push: Some("on-commit".to_owned()),
120            pull: Some("manual".to_owned()),
121            extra: toml::Table::new(),
122        }
123    }
124
125    /// A git remote at `url` (SPEC 9.6 example: push on commit, pull on
126    /// start).
127    pub fn git(name: &str, url: &str, auth: GitAuth) -> Self {
128        Self {
129            name: name.to_owned(),
130            kind: RemoteKind::Git,
131            path: None,
132            mode: None,
133            keep: None,
134            url: Some(url.to_owned()),
135            auth: Some(auth.as_str().to_owned()),
136            username: None,
137            push: Some("on-commit".to_owned()),
138            pull: Some("on-start".to_owned()),
139            extra: toml::Table::new(),
140        }
141    }
142
143    pub fn folder_mode(&self) -> FolderMode {
144        self.mode.unwrap_or_default()
145    }
146}
147
148/// `state/remotes.toml`.
149#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
150pub struct RemotesFile {
151    pub schema: i64,
152    #[serde(default, rename = "remote")]
153    pub remotes: Vec<RemoteConfig>,
154    #[serde(flatten)]
155    pub extra: toml::Table,
156}
157
158impl Default for RemotesFile {
159    fn default() -> Self {
160        Self {
161            schema: SCHEMA_VERSION,
162            remotes: Vec::new(),
163            extra: toml::Table::new(),
164        }
165    }
166}
167
168impl RemotesFile {
169    /// The remotes of this machine; none when the file is absent.
170    pub fn load(fs: &dyn Fs, state_dir: &Path) -> Result<Self, CoreError> {
171        let path = state_dir.join(REMOTES_FILE);
172        if !fs.exists(&path) {
173            return Ok(Self::default());
174        }
175        let text = fs.read_to_string(&path).map_err(|err| {
176            CoreError::new(ErrorCode::IoError, format!("cannot read file: {err}")).with_path(&path)
177        })?;
178        let file: Self = toml::from_str(&text).map_err(|err| {
179            CoreError::new(ErrorCode::ParseError, err.message().to_owned()).with_path(&path)
180        })?;
181        if file.schema != SCHEMA_VERSION {
182            return Err(CoreError::new(
183                ErrorCode::UnsupportedSchema,
184                format!("schema {} is not read by this build", file.schema),
185            )
186            .with_path(&path));
187        }
188        Ok(file)
189    }
190
191    pub fn save(&self, fs: &dyn Fs, state_dir: &Path) -> Result<(), CoreError> {
192        let text = toml::to_string_pretty(self).map_err(|err| {
193            CoreError::new(
194                ErrorCode::InvalidValue,
195                format!("cannot write remotes: {err}"),
196            )
197        })?;
198        crate::apply::write_atomic(fs, &state_dir.join(REMOTES_FILE), text.as_bytes())
199    }
200
201    pub fn get(&self, name: &str) -> Option<&RemoteConfig> {
202        self.remotes.iter().find(|remote| remote.name == name)
203    }
204
205    /// Adds a remote; `already_exists` when the name is taken.
206    pub fn add(&mut self, remote: RemoteConfig) -> Result<(), CoreError> {
207        check_name(&remote.name)?;
208        if self.get(&remote.name).is_some() {
209            return Err(CoreError::new(
210                ErrorCode::AlreadyExists,
211                format!("a remote named {:?} exists already", remote.name),
212            ));
213        }
214        self.remotes.push(remote);
215        Ok(())
216    }
217
218    /// Removes a remote; `not_found` when there is none.
219    pub fn remove(&mut self, name: &str) -> Result<RemoteConfig, CoreError> {
220        let index = self
221            .remotes
222            .iter()
223            .position(|remote| remote.name == name)
224            .ok_or_else(|| not_found(name))?;
225        Ok(self.remotes.remove(index))
226    }
227
228    /// The named remote, or every remote when `name` is `None`.
229    pub fn select(&self, name: Option<&str>) -> Result<Vec<&RemoteConfig>, CoreError> {
230        match name {
231            Some(name) => self
232                .get(name)
233                .map(|r| vec![r])
234                .ok_or_else(|| not_found(name)),
235            None => Ok(self.remotes.iter().collect()),
236        }
237    }
238}
239
240fn not_found(name: &str) -> CoreError {
241    CoreError::new(ErrorCode::NotFound, format!("no remote named {name:?}"))
242}
243
244/// Remote names: 1 to 64 letters, digits, `.`, `_` or `-`, not starting
245/// with `.` or `-`, and valid in a git ref (`refs/remotes/<name>/main`):
246/// no `..`, no trailing `.`, no `.lock` ending.
247pub fn check_name(name: &str) -> Result<(), CoreError> {
248    let valid = !name.is_empty()
249        && name.len() <= 64
250        && name
251            .bytes()
252            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-'))
253        && !name.starts_with(['.', '-'])
254        && !name.ends_with('.')
255        && !name.contains("..")
256        && !name.ends_with(".lock");
257    if valid {
258        Ok(())
259    } else {
260        Err(CoreError::new(
261            ErrorCode::InvalidValue,
262            format!("invalid remote name {name:?}: letters, digits, '.', '_' or '-'"),
263        ))
264    }
265}