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