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