OXYGENHUB
# c6e69e4b8d8f oxygen / crates / oxy-core / src / repo / config.rs
12.5 KiB · Rust · last changed A missing author identity says what is wrong and what to do 27 days ago source blame history raw
1
//! Layered configuration: defaults, the user file, the repository file.
2
3
use super::*;
4
5
/// Effective settings: defaults, then the user file (`~/.config/oxy/config.toml`,
6
/// spec §19), then the repository file (`.oxy/config`). Both files are
7
/// `key = "value"` lines. `save` writes only the repository layer.
8
#[derive(Clone, Debug, PartialEq, Eq)]
9
pub struct Config {
10
    /// Keys set in the repository file (or via `set`), written by `save`.
11
    repo_layer: BTreeMap<String, String>,
12
    pub author_name: String,
13
    pub author_email: String,
14
    /// The KeyId of the author's identity, once `create_identity` has run.
15
    pub author_key: Option<KeyId>,
16
    /// `author.signer` (or `$OXY_SIGNER`): the key that signs and seals in
17
    /// place of `author.key`, whose identity lists it as a delegate. An
18
    /// agent sets it to its own key, so its changes carry the human as
19
    /// author and the agent's signature (spec §14.2, agent workflows §2).
20
    pub signer_key: Option<KeyId>,
21
    /// `core.sign`: sign every change at commit (`true`) or leave signing to
22
    /// push-time seals (`false`, the spec default).
23
    pub sign_changes: bool,
24
    pub bookmark: String,
25
    /// `remote.<name>.url`.
26
    pub remotes: BTreeMap<String, String>,
27
    /// `remote.<name>.token`: bearer token for HTTP pushes.
28
    pub remote_tokens: BTreeMap<String, String>,
29
    /// `remote.<name>.ca`: PEM file of extra roots to trust for that remote.
30
    pub remote_cas: BTreeMap<String, String>,
31
    /// `core.remote`: the remote `pull`, `fetch` and `push` use when none is
32
    /// named, for a repository whose remotes include no `origin`.
33
    pub default_remote: Option<String>,
34
    /// `core.op-retention`: days for which operations keep their states reachable (spec §12.1, §21).
35
    pub op_retention_days: u64,
36
    /// `core.gc-grace`: days an unreachable object survives, protecting concurrent writers (spec §21).
37
    pub gc_grace_days: u64,
38
    /// `core.checkpoint-interval`: changes between automatic checkpoints (spec §11).
39
    pub checkpoint_interval: u64,
40
    /// `filter.max-blob`: blobs larger than this many bytes are fetched lazily (spec §17).
41
    pub max_blob: Option<u64>,
42
    /// `filter.paths`: only these subtrees are materialized (spec §17); empty means everything.
43
    pub sparse_paths: Vec<String>,
44
    /// `hooks.semantic-deps`: run the semantic-deps hook at commit (spec §20).
45
    pub semantic_deps: bool,
46
    /// `revset.<name>`: a saved revset, used as `name()`.
47
    pub revsets: BTreeMap<String, String>,
48
    /// `storage.url`: the store the repository's objects and operation
49
    /// head are kept on (`dir://`, `s3://`, …) instead of `.oxy/objects`
50
    /// (oxygen#68).
51
    pub storage_url: Option<String>,
52
    /// `storage.cache`: the most the local cache in front of that store
53
    /// holds, in bytes.
54
    pub storage_cache: u64,
55
}
56
57
impl Config {
58
    /// Whether the repository's own file sets `key` (as against the user
59
    /// config or a default).
60
    pub fn is_repo_set(&self, key: &str) -> bool {
61
        self.repo_layer.contains_key(key)
62
    }
63
64
    pub(super) fn default_for_user() -> Config {
65
        let user = std::env::var("USER").unwrap_or_else(|_| "unknown".into());
66
        Config {
67
            repo_layer: BTreeMap::new(),
68
            author_name: std::env::var("OXY_AUTHOR_NAME").unwrap_or_else(|_| user.clone()),
69
            author_email: std::env::var("OXY_AUTHOR_EMAIL")
70
                .unwrap_or_else(|_| format!("{user}@localhost")),
71
            author_key: None,
72
            signer_key: std::env::var("OXY_SIGNER")
73
                .ok()
74
                .and_then(|v| KeyId::from_hex(&v)),
75
            sign_changes: false,
76
            bookmark: "main".into(),
77
            remotes: BTreeMap::new(),
78
            remote_tokens: BTreeMap::new(),
79
            remote_cas: BTreeMap::new(),
80
            default_remote: None,
81
            op_retention_days: 90,
82
            gc_grace_days: 14,
83
            checkpoint_interval: 256,
84
            max_blob: None,
85
            sparse_paths: Vec::new(),
86
            semantic_deps: false,
87
            revsets: BTreeMap::new(),
88
            storage_url: None,
89
            storage_cache: DEFAULT_STORAGE_CACHE,
90
        }
91
    }
92
93
    /// Set a key in the repository layer, as `oxy config` does.
94
    pub fn set(&mut self, key: &str, value: &str) -> Result<()> {
95
        self.apply(key, value)?;
96
        if value.is_empty() {
97
            self.repo_layer.remove(key);
98
        } else {
99
            self.repo_layer.insert(key.to_string(), value.to_string());
100
        }
101
        Ok(())
102
    }
103
104
    /// Set a key in the user file without touching any repository.
105
    pub fn set_user(user_path: &Path, key: &str, value: &str) -> Result<()> {
106
        Config::default_for_user().apply(key, value)?;
107
        let mut entries = read_config_file(user_path)?;
108
        if value.is_empty() {
109
            entries.remove(key);
110
        } else {
111
            entries.insert(key.to_string(), value.to_string());
112
        }
113
        if let Some(parent) = user_path.parent() {
114
            fs::create_dir_all(parent)?;
115
        }
116
        write_config_file(user_path, &entries)
117
    }
118
119
    /// Apply a key to the effective values.
120
    pub(super) fn apply(&mut self, key: &str, value: &str) -> Result<()> {
121
        match key {
122
            "author.name" => self.author_name = value.into(),
123
            "author.email" => self.author_email = value.into(),
124
            "author.key" => {
125
                self.author_key = if value.is_empty() {
126
                    None
127
                } else {
128
                    Some(KeyId::from_hex(value).ok_or_else(|| {
129
                        RepoError::Msg("author.key must be a 64-character hex KeyId".into())
130
                    })?)
131
                }
132
            }
133
            "author.signer" => {
134
                self.signer_key = if value.is_empty() {
135
                    None
136
                } else {
137
                    Some(KeyId::from_hex(value).ok_or_else(|| {
138
                        RepoError::Msg("author.signer must be a 64-character hex KeyId".into())
139
                    })?)
140
                }
141
            }
142
            "core.sign" => {
143
                self.sign_changes = match value {
144
                    "change" => true,
145
                    "seal" => false,
146
                    _ => return fail("core.sign must be \"change\" or \"seal\""),
147
                }
148
            }
149
            "workspace.bookmark" => self.bookmark = value.into(),
150
            // Read by the credential store from the user file.
151
            "auth.helper" => {}
152
            "core.op-retention" => self.op_retention_days = parse_days(value)?,
153
            "core.gc-grace" => self.gc_grace_days = parse_days(value)?,
154
            "filter.max-blob" => {
155
                self.max_blob = if value.is_empty() {
156
                    None
157
                } else {
158
                    Some(parse_size(value)?)
159
                }
160
            }
161
            "storage.url" => {
162
                self.storage_url = (!value.is_empty()).then(|| value.to_string());
163
            }
164
            "storage.cache" => {
165
                self.storage_cache = if value.is_empty() {
166
                    DEFAULT_STORAGE_CACHE
167
                } else {
168
                    parse_size(value)?
169
                }
170
            }
171
            "core.remote" => {
172
                self.default_remote = (!value.is_empty()).then(|| value.to_string());
173
            }
174
            "hooks.semantic-deps" => self.semantic_deps = matches!(value, "true" | "1" | "yes"),
175
            "filter.paths" => {
176
                self.sparse_paths = value
177
                    .split(',')
178
                    .map(|p| {
179
                        p.trim()
180
                            .trim_start_matches("./")
181
                            .trim_matches('/')
182
                            .to_string()
183
                    })
184
                    .filter(|p| !p.is_empty())
185
                    .collect();
186
            }
187
            "core.checkpoint-interval" => {
188
                self.checkpoint_interval = value
189
                    .parse()
190
                    .map_err(|_| RepoError::Msg(format!("expected a number, got {value:?}")))?;
191
            }
192
            k if k.starts_with("remote.") => {
193
                let rest = &k["remote.".len()..];
194
                let Some((name, field)) = rest.rsplit_once('.') else {
195
                    return fail(format!("unknown configuration key {key:?}"));
196
                };
197
                if name.is_empty() || name.contains('/') {
198
                    return fail(format!("invalid remote name in {key:?}"));
199
                }
200
                let map = match field {
201
                    "url" => &mut self.remotes,
202
                    "token" => &mut self.remote_tokens,
203
                    "ca" => &mut self.remote_cas,
204
                    _ => return fail(format!("unknown configuration key {key:?}")),
205
                };
206
                if value.is_empty() {
207
                    map.remove(name);
208
                    if field == "url" {
209
                        self.remote_tokens.remove(name);
210
                        self.remote_cas.remove(name);
211
                    }
212
                } else {
213
                    map.insert(name.to_string(), value.into());
214
                }
215
            }
216
            k if k.starts_with("revset.") => {
217
                let name = &k["revset.".len()..];
218
                if name.is_empty()
219
                    || !name
220
                        .chars()
221
                        .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
222
                {
223
                    return fail(format!(
224
                        "a revset's name is letters, digits, _ and -: {key:?}"
225
                    ));
226
                }
227
                if value.is_empty() {
228
                    self.revsets.remove(name);
229
                } else {
230
                    crate::revset::parse(value)
231
                        .map_err(|e| RepoError::Msg(format!("{key} = {value:?}: {e}")))?;
232
                    self.revsets.insert(name.to_string(), value.into());
233
                }
234
            }
235
            _ => return fail(format!("unknown configuration key {key:?}")),
236
        }
237
        Ok(())
238
    }
239
240
    /// Defaults, then the user file if it exists, then the repository file.
241
    pub(super) fn load(user_path: Option<&Path>, repo_path: &Path) -> Result<Config> {
242
        let mut c = Config::default_for_user();
243
        if let Some(u) = user_path {
244
            for (k, v) in read_config_file(u)? {
245
                let _ = c.apply(&k, &v);
246
            }
247
        }
248
        for (k, v) in read_config_file(repo_path)? {
249
            if c.apply(&k, &v).is_ok() {
250
                c.repo_layer.insert(k, v);
251
            }
252
        }
253
        Ok(c)
254
    }
255
256
    pub(super) fn save(&self, path: &Path) -> Result<()> {
257
        write_config_file(path, &self.repo_layer)
258
    }
259
260
    /// Keys explicitly set for this repository.
261
    pub fn repo_layer(&self) -> &BTreeMap<String, String> {
262
        &self.repo_layer
263
    }
264
}
265
266
/// A byte count with an optional `K`, `M`, or `G` suffix (binary units).
267
/// `storage.cache` when unset: 2 GiB.
268
pub const DEFAULT_STORAGE_CACHE: u64 = 2 << 30;
269
270
pub fn parse_size(v: &str) -> Result<u64> {
271
    let v = v.trim();
272
    let (num, mult) = match v.chars().last() {
273
        Some('K' | 'k') => (&v[..v.len() - 1], 1u64 << 10),
274
        Some('M' | 'm') => (&v[..v.len() - 1], 1u64 << 20),
275
        Some('G' | 'g') => (&v[..v.len() - 1], 1u64 << 30),
276
        _ => (v, 1),
277
    };
278
    let n: u64 = num
279
        .trim()
280
        .parse()
281
        .map_err(|_| RepoError::Msg(format!("expected a size like 1M, got {v:?}")))?;
282
    Ok(n * mult)
283
}
284
285
/// A count of days, optionally suffixed `d`.
286
fn parse_days(v: &str) -> Result<u64> {
287
    v.trim_end_matches('d')
288
        .parse()
289
        .map_err(|_| RepoError::Msg(format!("expected a number of days, got {v:?}")))
290
}
291
292
/// Read `key = "value"` lines; a missing file is empty.
293
pub fn read_config_file(path: &Path) -> Result<BTreeMap<String, String>> {
294
    let text = match fs::read_to_string(path) {
295
        Ok(t) => t,
296
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(BTreeMap::new()),
297
        Err(e) => return Err(e.into()),
298
    };
299
    let mut out = BTreeMap::new();
300
    for line in text.lines() {
301
        let line = line.trim();
302
        if line.is_empty() || line.starts_with('#') {
303
            continue;
304
        }
305
        let Some((k, v)) = line.split_once('=') else {
306
            continue;
307
        };
308
        out.insert(k.trim().to_string(), v.trim().trim_matches('"').to_string());
309
    }
310
    Ok(out)
311
}
312
313
fn write_config_file(path: &Path, entries: &BTreeMap<String, String>) -> Result<()> {
314
    let text: String = entries
315
        .iter()
316
        .map(|(k, v)| format!("{k} = \"{v}\"\n"))
317
        .collect();
318
    write_atomic(path, text.as_bytes())
319
}