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