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