OXYGENHUB
# 42ccf504aa50 oxygen / crates / oxy-core / src / repo / config.rs
12.3 KiB · Rust · last changed Several remotes and no origin: a default, and the right comparison 28 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
    pub(super) fn default_for_user() -> Config {
59
        let user = std::env::var("USER").unwrap_or_else(|_| "unknown".into());
60
        Config {
61
            repo_layer: BTreeMap::new(),
62
            author_name: std::env::var("OXY_AUTHOR_NAME").unwrap_or_else(|_| user.clone()),
63
            author_email: std::env::var("OXY_AUTHOR_EMAIL")
64
                .unwrap_or_else(|_| format!("{user}@localhost")),
65
            author_key: None,
66
            signer_key: std::env::var("OXY_SIGNER")
67
                .ok()
68
                .and_then(|v| KeyId::from_hex(&v)),
69
            sign_changes: false,
70
            bookmark: "main".into(),
71
            remotes: BTreeMap::new(),
72
            remote_tokens: BTreeMap::new(),
73
            remote_cas: BTreeMap::new(),
74
            default_remote: None,
75
            op_retention_days: 90,
76
            gc_grace_days: 14,
77
            checkpoint_interval: 256,
78
            max_blob: None,
79
            sparse_paths: Vec::new(),
80
            semantic_deps: false,
81
            revsets: BTreeMap::new(),
82
            storage_url: None,
83
            storage_cache: DEFAULT_STORAGE_CACHE,
84
        }
85
    }
86
87
    /// Set a key in the repository layer, as `oxy config` does.
88
    pub fn set(&mut self, key: &str, value: &str) -> Result<()> {
89
        self.apply(key, value)?;
90
        if value.is_empty() {
91
            self.repo_layer.remove(key);
92
        } else {
93
            self.repo_layer.insert(key.to_string(), value.to_string());
94
        }
95
        Ok(())
96
    }
97
98
    /// Set a key in the user file without touching any repository.
99
    pub fn set_user(user_path: &Path, key: &str, value: &str) -> Result<()> {
100
        Config::default_for_user().apply(key, value)?;
101
        let mut entries = read_config_file(user_path)?;
102
        if value.is_empty() {
103
            entries.remove(key);
104
        } else {
105
            entries.insert(key.to_string(), value.to_string());
106
        }
107
        if let Some(parent) = user_path.parent() {
108
            fs::create_dir_all(parent)?;
109
        }
110
        write_config_file(user_path, &entries)
111
    }
112
113
    /// Apply a key to the effective values.
114
    pub(super) fn apply(&mut self, key: &str, value: &str) -> Result<()> {
115
        match key {
116
            "author.name" => self.author_name = value.into(),
117
            "author.email" => self.author_email = value.into(),
118
            "author.key" => {
119
                self.author_key = if value.is_empty() {
120
                    None
121
                } else {
122
                    Some(KeyId::from_hex(value).ok_or_else(|| {
123
                        RepoError::Msg("author.key must be a 64-character hex KeyId".into())
124
                    })?)
125
                }
126
            }
127
            "author.signer" => {
128
                self.signer_key = if value.is_empty() {
129
                    None
130
                } else {
131
                    Some(KeyId::from_hex(value).ok_or_else(|| {
132
                        RepoError::Msg("author.signer must be a 64-character hex KeyId".into())
133
                    })?)
134
                }
135
            }
136
            "core.sign" => {
137
                self.sign_changes = match value {
138
                    "change" => true,
139
                    "seal" => false,
140
                    _ => return fail("core.sign must be \"change\" or \"seal\""),
141
                }
142
            }
143
            "workspace.bookmark" => self.bookmark = value.into(),
144
            // Read by the credential store from the user file.
145
            "auth.helper" => {}
146
            "core.op-retention" => self.op_retention_days = parse_days(value)?,
147
            "core.gc-grace" => self.gc_grace_days = parse_days(value)?,
148
            "filter.max-blob" => {
149
                self.max_blob = if value.is_empty() {
150
                    None
151
                } else {
152
                    Some(parse_size(value)?)
153
                }
154
            }
155
            "storage.url" => {
156
                self.storage_url = (!value.is_empty()).then(|| value.to_string());
157
            }
158
            "storage.cache" => {
159
                self.storage_cache = if value.is_empty() {
160
                    DEFAULT_STORAGE_CACHE
161
                } else {
162
                    parse_size(value)?
163
                }
164
            }
165
            "core.remote" => {
166
                self.default_remote = (!value.is_empty()).then(|| value.to_string());
167
            }
168
            "hooks.semantic-deps" => self.semantic_deps = matches!(value, "true" | "1" | "yes"),
169
            "filter.paths" => {
170
                self.sparse_paths = value
171
                    .split(',')
172
                    .map(|p| {
173
                        p.trim()
174
                            .trim_start_matches("./")
175
                            .trim_matches('/')
176
                            .to_string()
177
                    })
178
                    .filter(|p| !p.is_empty())
179
                    .collect();
180
            }
181
            "core.checkpoint-interval" => {
182
                self.checkpoint_interval = value
183
                    .parse()
184
                    .map_err(|_| RepoError::Msg(format!("expected a number, got {value:?}")))?;
185
            }
186
            k if k.starts_with("remote.") => {
187
                let rest = &k["remote.".len()..];
188
                let Some((name, field)) = rest.rsplit_once('.') else {
189
                    return fail(format!("unknown configuration key {key:?}"));
190
                };
191
                if name.is_empty() || name.contains('/') {
192
                    return fail(format!("invalid remote name in {key:?}"));
193
                }
194
                let map = match field {
195
                    "url" => &mut self.remotes,
196
                    "token" => &mut self.remote_tokens,
197
                    "ca" => &mut self.remote_cas,
198
                    _ => return fail(format!("unknown configuration key {key:?}")),
199
                };
200
                if value.is_empty() {
201
                    map.remove(name);
202
                    if field == "url" {
203
                        self.remote_tokens.remove(name);
204
                        self.remote_cas.remove(name);
205
                    }
206
                } else {
207
                    map.insert(name.to_string(), value.into());
208
                }
209
            }
210
            k if k.starts_with("revset.") => {
211
                let name = &k["revset.".len()..];
212
                if name.is_empty()
213
                    || !name
214
                        .chars()
215
                        .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
216
                {
217
                    return fail(format!(
218
                        "a revset's name is letters, digits, _ and -: {key:?}"
219
                    ));
220
                }
221
                if value.is_empty() {
222
                    self.revsets.remove(name);
223
                } else {
224
                    crate::revset::parse(value)
225
                        .map_err(|e| RepoError::Msg(format!("{key} = {value:?}: {e}")))?;
226
                    self.revsets.insert(name.to_string(), value.into());
227
                }
228
            }
229
            _ => return fail(format!("unknown configuration key {key:?}")),
230
        }
231
        Ok(())
232
    }
233
234
    /// Defaults, then the user file if it exists, then the repository file.
235
    pub(super) fn load(user_path: Option<&Path>, repo_path: &Path) -> Result<Config> {
236
        let mut c = Config::default_for_user();
237
        if let Some(u) = user_path {
238
            for (k, v) in read_config_file(u)? {
239
                let _ = c.apply(&k, &v);
240
            }
241
        }
242
        for (k, v) in read_config_file(repo_path)? {
243
            if c.apply(&k, &v).is_ok() {
244
                c.repo_layer.insert(k, v);
245
            }
246
        }
247
        Ok(c)
248
    }
249
250
    pub(super) fn save(&self, path: &Path) -> Result<()> {
251
        write_config_file(path, &self.repo_layer)
252
    }
253
254
    /// Keys explicitly set for this repository.
255
    pub fn repo_layer(&self) -> &BTreeMap<String, String> {
256
        &self.repo_layer
257
    }
258
}
259
260
/// A byte count with an optional `K`, `M`, or `G` suffix (binary units).
261
/// `storage.cache` when unset: 2 GiB.
262
pub const DEFAULT_STORAGE_CACHE: u64 = 2 << 30;
263
264
pub fn parse_size(v: &str) -> Result<u64> {
265
    let v = v.trim();
266
    let (num, mult) = match v.chars().last() {
267
        Some('K' | 'k') => (&v[..v.len() - 1], 1u64 << 10),
268
        Some('M' | 'm') => (&v[..v.len() - 1], 1u64 << 20),
269
        Some('G' | 'g') => (&v[..v.len() - 1], 1u64 << 30),
270
        _ => (v, 1),
271
    };
272
    let n: u64 = num
273
        .trim()
274
        .parse()
275
        .map_err(|_| RepoError::Msg(format!("expected a size like 1M, got {v:?}")))?;
276
    Ok(n * mult)
277
}
278
279
/// A count of days, optionally suffixed `d`.
280
fn parse_days(v: &str) -> Result<u64> {
281
    v.trim_end_matches('d')
282
        .parse()
283
        .map_err(|_| RepoError::Msg(format!("expected a number of days, got {v:?}")))
284
}
285
286
/// Read `key = "value"` lines; a missing file is empty.
287
pub fn read_config_file(path: &Path) -> Result<BTreeMap<String, String>> {
288
    let text = match fs::read_to_string(path) {
289
        Ok(t) => t,
290
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(BTreeMap::new()),
291
        Err(e) => return Err(e.into()),
292
    };
293
    let mut out = BTreeMap::new();
294
    for line in text.lines() {
295
        let line = line.trim();
296
        if line.is_empty() || line.starts_with('#') {
297
            continue;
298
        }
299
        let Some((k, v)) = line.split_once('=') else {
300
            continue;
301
        };
302
        out.insert(k.trim().to_string(), v.trim().trim_matches('"').to_string());
303
    }
304
    Ok(out)
305
}
306
307
fn write_config_file(path: &Path, entries: &BTreeMap<String, String>) -> Result<()> {
308
    let text: String = entries
309
        .iter()
310
        .map(|(k, v)| format!("{k} = \"{v}\"\n"))
311
        .collect();
312
    write_atomic(path, text.as_bytes())
313
}