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