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