OXYGENHUB
◆ identical-sides oxygen / crates / oxy-core / src / repo / config.rs
15.9 KiB · Rust · last changed author.for: a keyless home follows its owner's newest identity (refs #82) 10 days ago source blame history raw
98286406 Andy McCall ↶ 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>,
ff1a64f8 Andy McCall ↶ 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>,
c895bc52 Andy McCall ↶ 21
    /// `author.signer = "keyless"`: sign with fresh keys the hub certifies
22
    /// under the agent's grant, keeping no key on disk (spec §14.7,
23
    /// oxygenhub#241).
24
    pub signer_keyless: bool,
25
    /// `keyless.hub`: the hub that certifies them (default: the default
26
    /// remote's hub).
27
    pub keyless_hub: Option<String>,
2452b440 Andy McCall ↶ 28
    /// `author.for` (oxygen#82): in a keyless agent's home, the account it
29
    /// acts for; the home then authors as that person's newest identity,
30
    /// which the hub names with each certificate, rather than a pinned
31
    /// `author.key` that goes stale with every rotation.
32
    pub author_for: Option<String>,
98286406 Andy McCall ↶ 33
    /// `core.sign`: sign every change at commit (`true`) or leave signing to
34
    /// push-time seals (`false`, the spec default).
35
    pub sign_changes: bool,
36
    pub bookmark: String,
37
    /// `remote.<name>.url`.
38
    pub remotes: BTreeMap<String, String>,
39
    /// `remote.<name>.token`: bearer token for HTTP pushes.
40
    pub remote_tokens: BTreeMap<String, String>,
2b5ee371 Andy McCall ↶ 41
    /// `remote.<name>.ca`: PEM file of extra roots to trust for that remote.
42
    pub remote_cas: BTreeMap<String, String>,
42ccf504 Andy McCall ↶ 43
    /// `core.remote`: the remote `pull`, `fetch` and `push` use when none is
44
    /// named, for a repository whose remotes include no `origin`.
45
    pub default_remote: Option<String>,
d6e0d5b8 Andy McCall ↶ 46
    /// `git.claim`: a Git import authors the commits whose Git author email
47
    /// is this repository's identity's with its key (oxygen#97).
48
    pub git_claim: bool,
ba160f60 Andy McCall ↶ 49
    /// `core.op-retention`: days for which operations keep their states reachable (spec §12.1, §21).
50
    pub op_retention_days: u64,
51
    /// `core.gc-grace`: days an unreachable object survives, protecting concurrent writers (spec §21).
52
    pub gc_grace_days: u64,
b689779e Andy McCall ↶ 53
    /// `core.snapshot-retention`: days for which past operations keep their
54
    /// working copies reachable (oxygen#98); each workspace's current one is
55
    /// always kept. A file only ever in a working copy goes with it.
56
    pub snapshot_retention_days: u64,
57
    /// `snapshot.max-new-file-size`: a new, untracked file larger than this
58
    /// is left out of working-copy snapshots and named instead (oxygen#98);
59
    /// 0 takes in files of any size.
60
    pub max_new_file: u64,
252e8cb2 Andy McCall ↶ 61
    /// `core.checkpoint-interval`: changes between automatic checkpoints (spec §11).
62
    pub checkpoint_interval: u64,
cb8b8082 Andy McCall ↶ 63
    /// `push.batch-bytes`: about how many bytes of changes and their texts
64
    /// one request of a long push carries (spec §16.3).
65
    pub push_batch_bytes: u64,
b3c5a59a Andy McCall ↶ 66
    /// `filter.max-blob`: blobs larger than this many bytes are fetched lazily (spec §17).
67
    pub max_blob: Option<u64>,
7421309f Andy McCall ↶ 68
    /// `filter.paths`: only these subtrees are materialized (spec §17); empty means everything.
69
    pub sparse_paths: Vec<String>,
6d3eefbc Andy McCall ↶ 70
    /// `hooks.semantic-deps`: run the semantic-deps hook at commit (spec §20).
71
    pub semantic_deps: bool,
47ce8b8e Andy McCall ↶ 72
    /// `revset.<name>`: a saved revset, used as `name()`.
73
    pub revsets: BTreeMap<String, String>,
d069701a Andy McCall ↶ 74
    /// `storage.url`: the store the repository's objects and operation
75
    /// head are kept on (`dir://`, `s3://`, …) instead of `.oxy/objects`
76
    /// (oxygen#68).
77
    pub storage_url: Option<String>,
78
    /// `storage.cache`: the most the local cache in front of that store
79
    /// holds, in bytes.
80
    pub storage_cache: u64,
98286406 Andy McCall ↶ 81
}
82
83
impl Config {
cbe8499a Andy McCall ↶ 84
    /// Whether the repository's own file sets `key` (as against the user
85
    /// config or a default).
86
    pub fn is_repo_set(&self, key: &str) -> bool {
87
        self.repo_layer.contains_key(key)
88
    }
89
98286406 Andy McCall ↶ 90
    pub(super) fn default_for_user() -> Config {
91
        let user = std::env::var("USER").unwrap_or_else(|_| "unknown".into());
92
        Config {
93
            repo_layer: BTreeMap::new(),
94
            author_name: std::env::var("OXY_AUTHOR_NAME").unwrap_or_else(|_| user.clone()),
75167672 Andy McCall 95
            author_email: std::env::var("OXY_AUTHOR_EMAIL")
96
                .unwrap_or_else(|_| format!("{user}@localhost")),
98286406 Andy McCall ↶ 97
            author_key: None,
ff1a64f8 Andy McCall ↶ 98
            signer_key: std::env::var("OXY_SIGNER")
99
                .ok()
100
                .and_then(|v| KeyId::from_hex(&v)),
c895bc52 Andy McCall ↶ 101
            signer_keyless: std::env::var("OXY_SIGNER").is_ok_and(|v| v == "keyless"),
102
            keyless_hub: None,
2452b440 Andy McCall ↶ 103
            author_for: None,
98286406 Andy McCall ↶ 104
            sign_changes: false,
105
            bookmark: "main".into(),
106
            remotes: BTreeMap::new(),
107
            remote_tokens: BTreeMap::new(),
2b5ee371 Andy McCall ↶ 108
            remote_cas: BTreeMap::new(),
42ccf504 Andy McCall ↶ 109
            default_remote: None,
d6e0d5b8 Andy McCall ↶ 110
            git_claim: false,
ba160f60 Andy McCall ↶ 111
            op_retention_days: 90,
112
            gc_grace_days: 14,
b689779e Andy McCall ↶ 113
            max_new_file: 100 << 20,
114
            snapshot_retention_days: 7,
252e8cb2 Andy McCall ↶ 115
            checkpoint_interval: 256,
d3b27090 Andy McCall ↶ 116
            // Well under the 100 MB a proxy in front of a hub may take
117
            // (oxygen#133).
118
            push_batch_bytes: 64 << 20,
b3c5a59a Andy McCall ↶ 119
            max_blob: None,
7421309f Andy McCall ↶ 120
            sparse_paths: Vec::new(),
6d3eefbc Andy McCall ↶ 121
            semantic_deps: false,
47ce8b8e Andy McCall ↶ 122
            revsets: BTreeMap::new(),
d069701a Andy McCall ↶ 123
            storage_url: None,
124
            storage_cache: DEFAULT_STORAGE_CACHE,
98286406 Andy McCall ↶ 125
        }
126
    }
127
128
    /// Set a key in the repository layer, as `oxy config` does.
129
    pub fn set(&mut self, key: &str, value: &str) -> Result<()> {
130
        self.apply(key, value)?;
131
        if value.is_empty() {
132
            self.repo_layer.remove(key);
133
        } else {
134
            self.repo_layer.insert(key.to_string(), value.to_string());
135
        }
136
        Ok(())
137
    }
138
139
    /// Set a key in the user file without touching any repository.
140
    pub fn set_user(user_path: &Path, key: &str, value: &str) -> Result<()> {
141
        Config::default_for_user().apply(key, value)?;
142
        let mut entries = read_config_file(user_path)?;
143
        if value.is_empty() {
144
            entries.remove(key);
145
        } else {
146
            entries.insert(key.to_string(), value.to_string());
147
        }
148
        if let Some(parent) = user_path.parent() {
149
            fs::create_dir_all(parent)?;
150
        }
151
        write_config_file(user_path, &entries)
152
    }
153
154
    /// Apply a key to the effective values.
155
    pub(super) fn apply(&mut self, key: &str, value: &str) -> Result<()> {
156
        match key {
157
            "author.name" => self.author_name = value.into(),
158
            "author.email" => self.author_email = value.into(),
159
            "author.key" => {
160
                self.author_key = if value.is_empty() {
161
                    None
162
                } else {
75167672 Andy McCall 163
                    Some(KeyId::from_hex(value).ok_or_else(|| {
164
                        RepoError::Msg("author.key must be a 64-character hex KeyId".into())
165
                    })?)
98286406 Andy McCall ↶ 166
                }
167
            }
ff1a64f8 Andy McCall ↶ 168
            "author.signer" => {
c895bc52 Andy McCall ↶ 169
                self.signer_keyless = value == "keyless";
170
                self.signer_key = if value.is_empty() || self.signer_keyless {
ff1a64f8 Andy McCall ↶ 171
                    None
172
                } else {
173
                    Some(KeyId::from_hex(value).ok_or_else(|| {
c895bc52 Andy McCall ↶ 174
                        RepoError::Msg(
175
                            "author.signer must be a 64-character hex KeyId, or \"keyless\"".into(),
176
                        )
ff1a64f8 Andy McCall ↶ 177
                    })?)
178
                }
179
            }
98286406 Andy McCall ↶ 180
            "core.sign" => {
181
                self.sign_changes = match value {
182
                    "change" => true,
c9635448 Andy McCall ↶ 183
                    // Empty: unset, the default.
184
                    "seal" | "" => false,
98286406 Andy McCall ↶ 185
                    _ => return fail("core.sign must be \"change\" or \"seal\""),
186
                }
187
            }
188
            "workspace.bookmark" => self.bookmark = value.into(),
c895bc52 Andy McCall ↶ 189
            "keyless.hub" => self.keyless_hub = (!value.is_empty()).then(|| value.to_string()),
2452b440 Andy McCall ↶ 190
            "author.for" => self.author_for = (!value.is_empty()).then(|| value.to_string()),
ff1f62fe Andy McCall ↶ 191
            // Read by the credential store from the user file.
192
            "auth.helper" => {}
ba160f60 Andy McCall ↶ 193
            "core.op-retention" => self.op_retention_days = parse_days(value)?,
194
            "core.gc-grace" => self.gc_grace_days = parse_days(value)?,
b689779e Andy McCall ↶ 195
            "snapshot.max-new-file-size" => self.max_new_file = parse_size(value)?,
196
            "core.snapshot-retention" => self.snapshot_retention_days = parse_days(value)?,
75167672 Andy McCall 197
            "filter.max-blob" => {
198
                self.max_blob = if value.is_empty() {
199
                    None
200
                } else {
201
                    Some(parse_size(value)?)
202
                }
203
            }
d069701a Andy McCall ↶ 204
            "storage.url" => {
205
                self.storage_url = (!value.is_empty()).then(|| value.to_string());
206
            }
207
            "storage.cache" => {
208
                self.storage_cache = if value.is_empty() {
209
                    DEFAULT_STORAGE_CACHE
210
                } else {
211
                    parse_size(value)?
212
                }
213
            }
42ccf504 Andy McCall ↶ 214
            "core.remote" => {
215
                self.default_remote = (!value.is_empty()).then(|| value.to_string());
216
            }
6d3eefbc Andy McCall ↶ 217
            "hooks.semantic-deps" => self.semantic_deps = matches!(value, "true" | "1" | "yes"),
d6e0d5b8 Andy McCall ↶ 218
            "git.claim" => self.git_claim = matches!(value, "true" | "1" | "yes"),
7421309f Andy McCall ↶ 219
            "filter.paths" => {
220
                self.sparse_paths = value
221
                    .split(',')
75167672 Andy McCall 222
                    .map(|p| {
223
                        p.trim()
224
                            .trim_start_matches("./")
225
                            .trim_matches('/')
226
                            .to_string()
227
                    })
7421309f Andy McCall ↶ 228
                    .filter(|p| !p.is_empty())
229
                    .collect();
230
            }
252e8cb2 Andy McCall ↶ 231
            "core.checkpoint-interval" => {
75167672 Andy McCall 232
                self.checkpoint_interval = value
233
                    .parse()
234
                    .map_err(|_| RepoError::Msg(format!("expected a number, got {value:?}")))?;
252e8cb2 Andy McCall ↶ 235
            }
cb8b8082 Andy McCall ↶ 236
            "push.batch-bytes" => {
237
                self.push_batch_bytes = value.parse().ok().filter(|n| *n > 0).ok_or_else(|| {
238
                    RepoError::Msg(format!("expected a number of bytes, got {value:?}"))
239
                })?;
240
            }
2b5ee371 Andy McCall ↶ 241
            k if k.starts_with("remote.") => {
242
                let rest = &k["remote.".len()..];
243
                let Some((name, field)) = rest.rsplit_once('.') else {
244
                    return fail(format!("unknown configuration key {key:?}"));
98286406 Andy McCall ↶ 245
                };
246
                if name.is_empty() || name.contains('/') {
247
                    return fail(format!("invalid remote name in {key:?}"));
248
                }
2b5ee371 Andy McCall ↶ 249
                let map = match field {
250
                    "url" => &mut self.remotes,
251
                    "token" => &mut self.remote_tokens,
252
                    "ca" => &mut self.remote_cas,
253
                    _ => return fail(format!("unknown configuration key {key:?}")),
254
                };
98286406 Andy McCall ↶ 255
                if value.is_empty() {
256
                    map.remove(name);
2b5ee371 Andy McCall ↶ 257
                    if field == "url" {
98286406 Andy McCall ↶ 258
                        self.remote_tokens.remove(name);
2b5ee371 Andy McCall ↶ 259
                        self.remote_cas.remove(name);
98286406 Andy McCall ↶ 260
                    }
261
                } else {
262
                    map.insert(name.to_string(), value.into());
263
                }
264
            }
47ce8b8e Andy McCall ↶ 265
            k if k.starts_with("revset.") => {
266
                let name = &k["revset.".len()..];
267
                if name.is_empty()
268
                    || !name
269
                        .chars()
270
                        .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
271
                {
272
                    return fail(format!(
273
                        "a revset's name is letters, digits, _ and -: {key:?}"
274
                    ));
275
                }
276
                if value.is_empty() {
277
                    self.revsets.remove(name);
278
                } else {
279
                    crate::revset::parse(value)
280
                        .map_err(|e| RepoError::Msg(format!("{key} = {value:?}: {e}")))?;
281
                    self.revsets.insert(name.to_string(), value.into());
282
                }
283
            }
98286406 Andy McCall ↶ 284
            _ => return fail(format!("unknown configuration key {key:?}")),
285
        }
286
        Ok(())
287
    }
288
289
    /// Defaults, then the user file if it exists, then the repository file.
290
    pub(super) fn load(user_path: Option<&Path>, repo_path: &Path) -> Result<Config> {
291
        let mut c = Config::default_for_user();
292
        if let Some(u) = user_path {
293
            for (k, v) in read_config_file(u)? {
294
                let _ = c.apply(&k, &v);
295
            }
296
        }
297
        for (k, v) in read_config_file(repo_path)? {
298
            if c.apply(&k, &v).is_ok() {
299
                c.repo_layer.insert(k, v);
300
            }
301
        }
2452b440 Andy McCall ↶ 302
        // author.for (oxygen#82): the identity the hub last named as the
303
        // person's newest, kept in the home; a repository's own
304
        // author.key pin still wins.
305
        if c.author_for.is_some() && !c.repo_layer.contains_key("author.key") {
306
            if let Some(k) = user_path
307
                .and_then(Path::parent)
308
                .and_then(|home| fs::read_to_string(home.join("keys").join(AUTHOR_FOR_FILE)).ok())
309
                .and_then(|s| KeyId::from_hex(s.trim()))
310
            {
311
                c.author_key = Some(k);
312
            }
313
        }
98286406 Andy McCall ↶ 314
        Ok(c)
315
    }
316
317
    pub(super) fn save(&self, path: &Path) -> Result<()> {
318
        write_config_file(path, &self.repo_layer)
319
    }
320
321
    /// Keys explicitly set for this repository.
322
    pub fn repo_layer(&self) -> &BTreeMap<String, String> {
323
        &self.repo_layer
324
    }
325
}
2452b440 Andy McCall ↶ 326
327
/// In a home's `keys/`: the key of the identity `author.for` follows,
328
/// as the hub last named it (oxygen#82).
329
pub const AUTHOR_FOR_FILE: &str = "author.for";
98286406 Andy McCall ↶ 330
b3c5a59a Andy McCall ↶ 331
/// A byte count with an optional `K`, `M`, or `G` suffix (binary units).
d069701a Andy McCall ↶ 332
/// `storage.cache` when unset: 2 GiB.
333
pub const DEFAULT_STORAGE_CACHE: u64 = 2 << 30;
334
b3c5a59a Andy McCall ↶ 335
pub fn parse_size(v: &str) -> Result<u64> {
336
    let v = v.trim();
337
    let (num, mult) = match v.chars().last() {
338
        Some('K' | 'k') => (&v[..v.len() - 1], 1u64 << 10),
339
        Some('M' | 'm') => (&v[..v.len() - 1], 1u64 << 20),
340
        Some('G' | 'g') => (&v[..v.len() - 1], 1u64 << 30),
341
        _ => (v, 1),
342
    };
75167672 Andy McCall 343
    let n: u64 = num
344
        .trim()
345
        .parse()
346
        .map_err(|_| RepoError::Msg(format!("expected a size like 1M, got {v:?}")))?;
b3c5a59a Andy McCall ↶ 347
    Ok(n * mult)
348
}
349
ba160f60 Andy McCall ↶ 350
/// A count of days, optionally suffixed `d`.
351
fn parse_days(v: &str) -> Result<u64> {
75167672 Andy McCall 352
    v.trim_end_matches('d')
353
        .parse()
354
        .map_err(|_| RepoError::Msg(format!("expected a number of days, got {v:?}")))
ba160f60 Andy McCall ↶ 355
}
356
98286406 Andy McCall ↶ 357
/// Read `key = "value"` lines; a missing file is empty.
358
pub fn read_config_file(path: &Path) -> Result<BTreeMap<String, String>> {
359
    let text = match fs::read_to_string(path) {
360
        Ok(t) => t,
361
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(BTreeMap::new()),
362
        Err(e) => return Err(e.into()),
363
    };
364
    let mut out = BTreeMap::new();
365
    for line in text.lines() {
366
        let line = line.trim();
367
        if line.is_empty() || line.starts_with('#') {
368
            continue;
369
        }
75167672 Andy McCall 370
        let Some((k, v)) = line.split_once('=') else {
371
            continue;
372
        };
98286406 Andy McCall ↶ 373
        out.insert(k.trim().to_string(), v.trim().trim_matches('"').to_string());
374
    }
375
    Ok(out)
376
}
377
378
fn write_config_file(path: &Path, entries: &BTreeMap<String, String>) -> Result<()> {
75167672 Andy McCall 379
    let text: String = entries
380
        .iter()
381
        .map(|(k, v)| format!("{k} = \"{v}\"\n"))
382
        .collect();
98286406 Andy McCall ↶ 383
    write_atomic(path, text.as_bytes())
384
}