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