OXYGENHUB
# 3b1dc8a974a3 oxygen / crates / oxy-core / src / repo / config.rs
9.3 KiB · Rust · last changed Unbound hosted repositories adopt the first pusher's id 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
    /// `core.sign`: sign every change at commit (`true`) or leave signing to
17
    /// push-time seals (`false`, the spec default).
18
    pub sign_changes: bool,
19
    pub bookmark: String,
20
    /// `remote.<name>.url`.
21
    pub remotes: BTreeMap<String, String>,
22
    /// `remote.<name>.token`: bearer token for HTTP pushes.
23
    pub remote_tokens: BTreeMap<String, String>,
24
    /// `remote.<name>.ca`: PEM file of extra roots to trust for that remote.
25
    pub remote_cas: BTreeMap<String, String>,
26
    /// `core.op-retention`: days for which operations keep their states reachable (spec §12.1, §21).
27
    pub op_retention_days: u64,
28
    /// `core.gc-grace`: days an unreachable object survives, protecting concurrent writers (spec §21).
29
    pub gc_grace_days: u64,
30
    /// `core.checkpoint-interval`: changes between automatic checkpoints (spec §11).
31
    pub checkpoint_interval: u64,
32
    /// `filter.max-blob`: blobs larger than this many bytes are fetched lazily (spec §17).
33
    pub max_blob: Option<u64>,
34
    /// `filter.paths`: only these subtrees are materialized (spec §17); empty means everything.
35
    pub sparse_paths: Vec<String>,
36
    /// `hooks.semantic-deps`: run the semantic-deps hook at commit (spec §20).
37
    pub semantic_deps: bool,
38
}
39
40
impl Config {
41
    pub(super) fn default_for_user() -> Config {
42
        let user = std::env::var("USER").unwrap_or_else(|_| "unknown".into());
43
        Config {
44
            repo_layer: BTreeMap::new(),
45
            author_name: std::env::var("OXY_AUTHOR_NAME").unwrap_or_else(|_| user.clone()),
46
            author_email: std::env::var("OXY_AUTHOR_EMAIL")
47
                .unwrap_or_else(|_| format!("{user}@localhost")),
48
            author_key: None,
49
            sign_changes: false,
50
            bookmark: "main".into(),
51
            remotes: BTreeMap::new(),
52
            remote_tokens: BTreeMap::new(),
53
            remote_cas: BTreeMap::new(),
54
            op_retention_days: 90,
55
            gc_grace_days: 14,
56
            checkpoint_interval: 256,
57
            max_blob: None,
58
            sparse_paths: Vec::new(),
59
            semantic_deps: false,
60
        }
61
    }
62
63
    /// Set a key in the repository layer, as `oxy config` does.
64
    pub fn set(&mut self, key: &str, value: &str) -> Result<()> {
65
        self.apply(key, value)?;
66
        if value.is_empty() {
67
            self.repo_layer.remove(key);
68
        } else {
69
            self.repo_layer.insert(key.to_string(), value.to_string());
70
        }
71
        Ok(())
72
    }
73
74
    /// Set a key in the user file without touching any repository.
75
    pub fn set_user(user_path: &Path, key: &str, value: &str) -> Result<()> {
76
        Config::default_for_user().apply(key, value)?;
77
        let mut entries = read_config_file(user_path)?;
78
        if value.is_empty() {
79
            entries.remove(key);
80
        } else {
81
            entries.insert(key.to_string(), value.to_string());
82
        }
83
        if let Some(parent) = user_path.parent() {
84
            fs::create_dir_all(parent)?;
85
        }
86
        write_config_file(user_path, &entries)
87
    }
88
89
    /// Apply a key to the effective values.
90
    pub(super) fn apply(&mut self, key: &str, value: &str) -> Result<()> {
91
        match key {
92
            "author.name" => self.author_name = value.into(),
93
            "author.email" => self.author_email = value.into(),
94
            "author.key" => {
95
                self.author_key = if value.is_empty() {
96
                    None
97
                } else {
98
                    Some(KeyId::from_hex(value).ok_or_else(|| {
99
                        RepoError::Msg("author.key must be a 64-character hex KeyId".into())
100
                    })?)
101
                }
102
            }
103
            "core.sign" => {
104
                self.sign_changes = match value {
105
                    "change" => true,
106
                    "seal" => false,
107
                    _ => return fail("core.sign must be \"change\" or \"seal\""),
108
                }
109
            }
110
            "workspace.bookmark" => self.bookmark = value.into(),
111
            "core.op-retention" => self.op_retention_days = parse_days(value)?,
112
            "core.gc-grace" => self.gc_grace_days = parse_days(value)?,
113
            "filter.max-blob" => {
114
                self.max_blob = if value.is_empty() {
115
                    None
116
                } else {
117
                    Some(parse_size(value)?)
118
                }
119
            }
120
            "hooks.semantic-deps" => self.semantic_deps = matches!(value, "true" | "1" | "yes"),
121
            "filter.paths" => {
122
                self.sparse_paths = value
123
                    .split(',')
124
                    .map(|p| {
125
                        p.trim()
126
                            .trim_start_matches("./")
127
                            .trim_matches('/')
128
                            .to_string()
129
                    })
130
                    .filter(|p| !p.is_empty())
131
                    .collect();
132
            }
133
            "core.checkpoint-interval" => {
134
                self.checkpoint_interval = value
135
                    .parse()
136
                    .map_err(|_| RepoError::Msg(format!("expected a number, got {value:?}")))?;
137
            }
138
            k if k.starts_with("remote.") => {
139
                let rest = &k["remote.".len()..];
140
                let Some((name, field)) = rest.rsplit_once('.') else {
141
                    return fail(format!("unknown configuration key {key:?}"));
142
                };
143
                if name.is_empty() || name.contains('/') {
144
                    return fail(format!("invalid remote name in {key:?}"));
145
                }
146
                let map = match field {
147
                    "url" => &mut self.remotes,
148
                    "token" => &mut self.remote_tokens,
149
                    "ca" => &mut self.remote_cas,
150
                    _ => return fail(format!("unknown configuration key {key:?}")),
151
                };
152
                if value.is_empty() {
153
                    map.remove(name);
154
                    if field == "url" {
155
                        self.remote_tokens.remove(name);
156
                        self.remote_cas.remove(name);
157
                    }
158
                } else {
159
                    map.insert(name.to_string(), value.into());
160
                }
161
            }
162
            _ => return fail(format!("unknown configuration key {key:?}")),
163
        }
164
        Ok(())
165
    }
166
167
    /// Defaults, then the user file if it exists, then the repository file.
168
    pub(super) fn load(user_path: Option<&Path>, repo_path: &Path) -> Result<Config> {
169
        let mut c = Config::default_for_user();
170
        if let Some(u) = user_path {
171
            for (k, v) in read_config_file(u)? {
172
                let _ = c.apply(&k, &v);
173
            }
174
        }
175
        for (k, v) in read_config_file(repo_path)? {
176
            if c.apply(&k, &v).is_ok() {
177
                c.repo_layer.insert(k, v);
178
            }
179
        }
180
        Ok(c)
181
    }
182
183
    pub(super) fn save(&self, path: &Path) -> Result<()> {
184
        write_config_file(path, &self.repo_layer)
185
    }
186
187
    /// Keys explicitly set for this repository.
188
    pub fn repo_layer(&self) -> &BTreeMap<String, String> {
189
        &self.repo_layer
190
    }
191
}
192
193
/// A byte count with an optional `K`, `M`, or `G` suffix (binary units).
194
pub fn parse_size(v: &str) -> Result<u64> {
195
    let v = v.trim();
196
    let (num, mult) = match v.chars().last() {
197
        Some('K' | 'k') => (&v[..v.len() - 1], 1u64 << 10),
198
        Some('M' | 'm') => (&v[..v.len() - 1], 1u64 << 20),
199
        Some('G' | 'g') => (&v[..v.len() - 1], 1u64 << 30),
200
        _ => (v, 1),
201
    };
202
    let n: u64 = num
203
        .trim()
204
        .parse()
205
        .map_err(|_| RepoError::Msg(format!("expected a size like 1M, got {v:?}")))?;
206
    Ok(n * mult)
207
}
208
209
/// A count of days, optionally suffixed `d`.
210
fn parse_days(v: &str) -> Result<u64> {
211
    v.trim_end_matches('d')
212
        .parse()
213
        .map_err(|_| RepoError::Msg(format!("expected a number of days, got {v:?}")))
214
}
215
216
/// Read `key = "value"` lines; a missing file is empty.
217
pub fn read_config_file(path: &Path) -> Result<BTreeMap<String, String>> {
218
    let text = match fs::read_to_string(path) {
219
        Ok(t) => t,
220
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(BTreeMap::new()),
221
        Err(e) => return Err(e.into()),
222
    };
223
    let mut out = BTreeMap::new();
224
    for line in text.lines() {
225
        let line = line.trim();
226
        if line.is_empty() || line.starts_with('#') {
227
            continue;
228
        }
229
        let Some((k, v)) = line.split_once('=') else {
230
            continue;
231
        };
232
        out.insert(k.trim().to_string(), v.trim().trim_matches('"').to_string());
233
    }
234
    Ok(out)
235
}
236
237
fn write_config_file(path: &Path, entries: &BTreeMap<String, String>) -> Result<()> {
238
    let text: String = entries
239
        .iter()
240
        .map(|(k, v)| format!("{k} = \"{v}\"\n"))
241
        .collect();
242
    write_atomic(path, text.as_bytes())
243
}