forge
Explore
Log in

Don't you dare go Hollow

kur

Clone
★ 0

0 watching0 forksRustAGPL-3.073.7 KiB6ae6238Tahinli21 days ago5 commits

config.rs315 lines, 10.4 KiBHistoryRawDownload
1//! Config file: TOML parsing, validation, and reading the forge token.
2
3use crate::{Res, migrate};
4use serde::Deserialize;
5use std::collections::HashSet;
6use std::env;
7use std::ffi::OsString;
8use std::fs::{self, OpenOptions};
9use std::io::{self, Write};
10use std::os::unix::fs::OpenOptionsExt;
11use std::path::{Path, PathBuf};
12
13/// Top-level keys; must match the `Raw` fields.
14const KNOWN_TOP_KEYS: &[&str] = &["forge", "token_file", "state_dir", "app"];
15/// Keys in each `[[app]]` table; must match the `App` fields.
16const KNOWN_APP_KEYS: &[&str] = &[
17 "name",
18 "repo",
19 "asset",
20 "path",
21 "unit",
22 "prerelease",
23 "unpack",
24 "check",
25 "health_url",
26 "health_timeout_secs",
27];
28
29/// Raw TOML shape; `apps` comes from the `[[app]]` tables.
30#[derive(Deserialize)]
31struct Raw {
32 forge: String,
33 token_file: Option<PathBuf>,
34 state_dir: Option<PathBuf>,
35 #[serde(default, rename = "app")]
36 apps: Vec<App>,
37}
38
39/// One `[[app]]` table.
40#[derive(Deserialize)]
41pub struct App {
42 pub name: String,
43 pub repo: String,
44 pub asset: String,
45 pub path: PathBuf,
46 pub unit: Option<String>,
47 #[serde(default)]
48 pub prerelease: bool,
49 #[serde(default)]
50 pub unpack: bool,
51 pub check: Option<Vec<String>>,
52 pub health_url: Option<String>,
53 #[serde(default = "default_health_timeout")]
54 pub health_timeout_secs: u64,
55}
56
57fn default_health_timeout() -> u64 {
58 30
59}
60
61/// Validated configuration.
62pub struct Config {
63 /// Forge base URL without a trailing slash.
64 pub forge: String,
65 /// Forge token, trimmed; sent only to forge URLs.
66 pub token: Option<String>,
67 pub state_dir: PathBuf,
68 pub apps: Vec<App>,
69 /// Non-fatal notices, such as unknown keys.
70 pub warnings: Vec<String>,
71 /// One message per key renamed by `migrate::RENAMES`.
72 pub migrated: Vec<String>,
73}
74
75impl App {
76 /// Asset file name for this host, with `{arch}` expanded.
77 pub fn asset_name(&self) -> String {
78 self.asset.replace("{arch}", std::env::consts::ARCH)
79 }
80
81 /// `path` with `suffix` appended, in the same directory (e.g. `.kur-new`, `.prev`).
82 pub fn sibling(&self, suffix: &str) -> PathBuf {
83 let mut name = self.path.clone().into_os_string();
84 name.push(suffix);
85 PathBuf::from(name)
86 }
87}
88
89/// Value of environment variable `name`, or None if it is unset or empty.
90fn env_value(name: &str) -> Option<OsString> {
91 env::var_os(name).filter(|value| !value.is_empty())
92}
93
94/// `$HOME`, if set and not empty.
95pub(crate) fn home_dir() -> Option<PathBuf> {
96 env_value("HOME").map(PathBuf::from)
97}
98
99/// Config path for a run: `cli` (from `--config`), else `KUR_CONFIG`, else `default_path()`.
100pub fn config_path(cli: Option<PathBuf>) -> Res<PathBuf> {
101 match cli.or_else(|| env_value("KUR_CONFIG").map(PathBuf::from)) {
102 Some(path) => Ok(path),
103 None => default_path(),
104 }
105}
106
107/// Config file used when neither `--config` nor `KUR_CONFIG` is set:
108/// `$XDG_CONFIG_HOME/kur/kur.toml`, else `$HOME/.config/kur/kur.toml`.
109pub fn default_path() -> Res<PathBuf> {
110 Ok(config_base()?.join("kur").join("kur.toml"))
111}
112
113/// `$XDG_CONFIG_HOME`, else `$HOME/.config`. Base for kur's config and the systemd user units.
114pub(crate) fn config_base() -> Res<PathBuf> {
115 match env_value("XDG_CONFIG_HOME") {
116 Some(dir) => Ok(PathBuf::from(dir)),
117 None => home_dir().map(|home| home.join(".config")).ok_or_else(|| {
118 "neither XDG_CONFIG_HOME nor HOME is set; use --config or KUR_CONFIG".to_string()
119 }),
120 }
121}
122
123/// Default `state_dir`: `$XDG_STATE_HOME/kur`, else `$HOME/.local/state/kur`.
124fn default_state_dir() -> Res<PathBuf> {
125 let base = match env_value("XDG_STATE_HOME") {
126 Some(dir) => PathBuf::from(dir),
127 None => home_dir()
128 .ok_or_else(|| {
129 "neither XDG_STATE_HOME nor HOME is set; set state_dir in the config".to_string()
130 })?
131 .join(".local")
132 .join("state"),
133 };
134 let dir = base.join("kur");
135 if !dir.is_absolute() {
136 return Err("state_dir must be absolute".into());
137 }
138 Ok(dir)
139}
140
141/// Expands a leading `~/` to `$HOME/` (and nothing else), then requires an absolute path.
142/// `what` names the setting in error messages.
143fn absolute_path(path: &Path, what: &str) -> Res<PathBuf> {
144 let expanded = match path.to_str().and_then(|s| s.strip_prefix("~/")) {
145 Some(rest) => home_dir()
146 .ok_or_else(|| format!("{what}: cannot expand ~/ because HOME is not set"))?
147 .join(rest.trim_start_matches('/')),
148 None => path.to_path_buf(),
149 };
150 if !expanded.is_absolute() {
151 return Err(format!("{what} must be absolute"));
152 }
153 Ok(expanded)
154}
155
156/// Reads and validates the config file at `path`, renaming keys listed in `migrate::RENAMES`.
157/// If anything was renamed and `write` is set, the file is rewritten once the config is valid.
158pub fn load(path: &Path, write: bool) -> Res<Config> {
159 let mut text =
160 fs::read_to_string(path).map_err(|e| format!("cannot read {}: {e}", path.display()))?;
161 // If the text does not parse, skip migration; the toml::from_str below reports the error.
162 let mut migrated = Vec::new();
163 if let Ok(mut doc) = text.parse::<toml_edit::DocumentMut>() {
164 migrated = migrate::apply(&mut doc, migrate::RENAMES);
165 if !migrated.is_empty() {
166 text = doc.to_string();
167 }
168 }
169 let table: toml::Table =
170 toml::from_str(&text).map_err(|e| format!("{}: {e}", path.display()))?;
171 let mut warnings = unknown_key_warnings(&table);
172 let mut raw: Raw = toml::from_str(&text).map_err(|e| format!("{}: {e}", path.display()))?;
173
174 let forge = raw.forge.trim_end_matches('/').to_string();
175 if !forge.starts_with("https://") && !forge.starts_with("http://") {
176 return Err("forge must start with https:// or http://".into());
177 }
178 if raw.apps.is_empty() {
179 return Err("no [[app]] entries in config".into());
180 }
181 let mut names = HashSet::new();
182 for app in &raw.apps {
183 if !valid_name(&app.name) {
184 return Err(format!("invalid app name {:?}", app.name));
185 }
186 if !names.insert(app.name.as_str()) {
187 return Err(format!("duplicate app name {}", app.name));
188 }
189 let parts: Vec<&str> = app.repo.split('/').collect();
190 if parts.len() != 2 || parts.iter().any(|p| p.is_empty()) {
191 return Err(format!("{}: repo must be owner/name", app.name));
192 }
193 if app.unpack && app.check.is_some() {
194 return Err(format!("{}: check cannot be used with unpack", app.name));
195 }
196 }
197 for app in &mut raw.apps {
198 app.path = absolute_path(&app.path, &format!("{}: path", app.name))?;
199 }
200
201 let token_file = raw
202 .token_file
203 .as_deref()
204 .map(|file| absolute_path(file, "token_file"))
205 .transpose()?;
206 let token = token_file.as_deref().map(read_token).transpose()?;
207 let state_dir = match raw.state_dir.as_deref() {
208 Some(dir) => absolute_path(dir, "state_dir")?,
209 None => default_state_dir()?,
210 };
211 if !migrated.is_empty()
212 && write
213 && let Err(e) = rewrite_config(path, &text)
214 {
215 warnings.push(format!("could not rewrite config: {e}"));
216 }
217 Ok(Config {
218 forge,
219 token,
220 state_dir,
221 apps: raw.apps,
222 warnings,
223 migrated,
224 })
225}
226
227/// Replaces the config at `path` with `text`, keeping the original as `<path>.bak`.
228/// The temp file is removed if anything fails, and the original is left in place.
229fn rewrite_config(path: &Path, text: &str) -> io::Result<()> {
230 let tmp = with_suffix(path, ".kur-tmp");
231 let result = write_and_swap(path, &tmp, text);
232 if result.is_err() {
233 let _ = fs::remove_file(&tmp);
234 }
235 result
236}
237
238fn write_and_swap(path: &Path, tmp: &Path, text: &str) -> io::Result<()> {
239 // fs::copy keeps the original's permission bits on the backup.
240 fs::copy(path, with_suffix(path, ".bak"))?;
241 let perms = fs::metadata(path)?.permissions();
242 // 0600 from creation, so the config is never readable by others before the final mode is set.
243 let mut file = OpenOptions::new()
244 .write(true)
245 .create(true)
246 .truncate(true)
247 .mode(0o600)
248 .open(tmp)?;
249 file.write_all(text.as_bytes())?;
250 file.set_permissions(perms)?;
251 file.sync_all()?;
252 drop(file);
253 fs::rename(tmp, path)?;
254 let parent = match path.parent() {
255 Some(dir) if !dir.as_os_str().is_empty() => dir,
256 _ => Path::new("."),
257 };
258 fs::File::open(parent)?.sync_all()
259}
260
261/// `path` with `suffix` appended to its file name.
262fn with_suffix(path: &Path, suffix: &str) -> PathBuf {
263 let mut name = path.as_os_str().to_owned();
264 name.push(suffix);
265 PathBuf::from(name)
266}
267
268/// One warning per key that is not in the known lists, at the top level and in each `[[app]]`.
269fn unknown_key_warnings(table: &toml::Table) -> Vec<String> {
270 let mut warnings = Vec::new();
271 for key in table.keys() {
272 if !KNOWN_TOP_KEYS.contains(&key.as_str()) {
273 warnings.push(format!("unknown key {key:?}"));
274 }
275 }
276 if let Some(toml::Value::Array(apps)) = table.get("app") {
277 for (index, app) in apps.iter().enumerate() {
278 let Some(app) = app.as_table() else {
279 continue;
280 };
281 let label = match app.get("name").and_then(toml::Value::as_str) {
282 Some(name) => name.to_string(),
283 None => format!("#{}", index + 1),
284 };
285 for key in app.keys() {
286 if !KNOWN_APP_KEYS.contains(&key.as_str()) {
287 warnings.push(format!("unknown key {key:?} in [[app]] {label}"));
288 }
289 }
290 }
291 }
292 warnings
293}
294
295/// Matches `^[a-z0-9][a-z0-9_-]{0,39}$`.
296fn valid_name(name: &str) -> bool {
297 let bytes = name.as_bytes();
298 !bytes.is_empty()
299 && bytes.len() <= 40
300 && (bytes[0].is_ascii_lowercase() || bytes[0].is_ascii_digit())
301 && bytes
302 .iter()
303 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || *b == b'_' || *b == b'-')
304}
305
306/// Reads the token file, trimmed. The token is never included in error messages.
307fn read_token(path: &Path) -> Res<String> {
308 let text =
309 fs::read_to_string(path).map_err(|e| format!("token_file {}: {e}", path.display()))?;
310 let token = text.trim();
311 if token.is_empty() {
312 return Err(format!("token_file {} is empty", path.display()));
313 }
314 Ok(token.to_string())
315}