summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authoraur-build <aur-build@localhost>2026-11-19 14:15:23 +0000
committeraur-build <aur-build@localhost>2026-11-19 14:15:28 +0000
commit8096fde8d98cdde4e110865ebb15ad034b92ff27 (patch)
treef3d207f4216280d46866af6441b30e6cc80d84c0
parent153e72cc797c1e45a60f4896d00163fb4bdf3056 (diff)
downloadaur-build-8096fde8d98cdde4e110865ebb15ad034b92ff27.tar.gz
aur-build-8096fde8d98cdde4e110865ebb15ad034b92ff27.zip
config: the root is the directory config.json lives in
`--root` names a directory and `init` writes config.json inside it, so the root was already named by where the config lived. The `root` field in the file was treated as a second source of truth instead: a relative one was re-joined onto the config's own directory, and `init` saved whatever it had been handed. So `--root runtime` wrote `"root": "runtime"`, and every command after `init` resolved it to `runtime/runtime/` — a second tree with its own empty database, while `init` had created and migrated the first one. The user-visible half was a path like `runtime/runtime/repo/aur-build/os/x86_64/…` in an error message. Compounding it, the CLI fell back to a default config whenever loading failed, so a typo'd `--root` produced a fresh empty server that answered every command as though it were the one you meant. `load` now sets the root to the directory it found the config in, absolutized, and a missing config is an error for every command except `init` — the only one that runs before one exists.
-rw-r--r--docs/DECISIONS.md23
-rw-r--r--src/config.rs33
-rw-r--r--src/main.rs17
-rw-r--r--tests/config.rs134
4 files changed, 195 insertions, 12 deletions
diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md
index bded52a..58d694a 100644
--- a/docs/DECISIONS.md
+++ b/docs/DECISIONS.md
@@ -427,3 +427,26 @@ missing.
the rejection has to be updated if pacman's rule changes. That is the correct
failure: a shim drifting from its tool should break a test loudly, not let a
production path go untested.
+## The root is the directory `config.json` lives in
+
+`--root` selects a directory and `init` writes `config.json` inside it, so the
+root is already named by the location of the config. The `root` field in the file
+was treated as a second source of truth: a relative one was re-joined onto the
+config's own directory, and `init` saved whatever it had been handed. So
+`--root runtime` wrote `"root": "runtime"`, and every command after `init`
+resolved that to `runtime/runtime/` — a second tree, with its own empty database,
+while `init` had created and migrated the first one. Compounding it, the CLI fell
+back to a default config whenever loading failed, so a typo'd `--root` produced a
+fresh empty server that answered every command as if it were the real one.
+
+**Choice.** `Config::load` sets the root to the directory it found the config in,
+absolutized; the field in the file is a record for whoever is reading the tree,
+and `save` writes it absolute so it stays readable. A missing config is an error
+for every command except `init`, which is the only one that runs before one
+exists.
+
+**Cost.** A hand-edited absolute `root` in a config file no longer relocates a
+tree — you move the directory and point `--root` at it, which is how the CLI
+already worked. And an existing tree that was already split by the doubling keeps
+its two databases until someone notices and moves the rows; the fix stops the
+bleeding rather than reconstructing what went into the wrong tree.
diff --git a/src/config.rs b/src/config.rs
index bda99e9..00ac3e4 100644
--- a/src/config.rs
+++ b/src/config.rs
@@ -167,8 +167,19 @@ impl Config {
/// `anyhow::Result` here meant two error vocabularies in one crate, and the
/// one thing a caller can actually branch on — "there is no config yet, run
/// init" — arrived as an opaque string.
+ ///
+ /// **The root is the directory the config file was found in.** The `root`
+ /// field inside the file is written for whoever is looking at the tree, not
+ /// as a second source of truth: `load` is only ever handed the directory it
+ /// then reads the config from, so a field that disagreed with its own
+ /// location could only ever contradict it. Honouring a relative field by
+ /// re-joining it onto the config's directory is what turned `--root runtime`
+ /// (which `init` used to save verbatim) into `runtime/runtime/…` — every
+ /// command after `init` ran against a second tree with its own database,
+ /// while `init` had created and migrated the first one.
pub fn load(root: &Path) -> crate::error::Result<Self> {
- let p = root.join("config.json");
+ let dir = absolute(root)?;
+ let p = dir.join("config.json");
if !p.exists() {
return Err(crate::error::Error::not_found(format!(
"no config at {}; run `aur-build init`",
@@ -177,19 +188,20 @@ impl Config {
}
let s = std::fs::read_to_string(&p)?;
let mut cfg: Config = serde_json::from_str(&s)?;
- // root inside the config file is relative to the config's directory
- // unless it is absolute; that keeps a moved tree usable.
- if !cfg.root.is_absolute() {
- cfg.root = root.join(&cfg.root);
- }
+ cfg.root = dir;
Ok(cfg)
}
pub fn save(&self) -> crate::error::Result<()> {
std::fs::create_dir_all(&self.root)?;
+ let mut out = self.clone();
+ // Absolutize on the way out, so a config written by a process that was
+ // handed a relative `--root` can never be misread — by the next command,
+ // or by a person editing it by hand.
+ out.root = absolute(&self.root)?;
std::fs::write(
self.root.join("config.json"),
- serde_json::to_string_pretty(self)? + "\n",
+ serde_json::to_string_pretty(&out)? + "\n",
)?;
Ok(())
}
@@ -319,6 +331,13 @@ impl Config {
}
}
+/// Absolutize a path without resolving symlinks and without requiring it to
+/// exist, both of which `canonicalize` insists on — and `init` saves its config
+/// before the tree under it is complete.
+fn absolute(p: &Path) -> crate::error::Result<PathBuf> {
+ Ok(std::path::absolute(p)?)
+}
+
/// Filesystem-safe slug for a URL, used in cache filenames.
pub fn slug(url: &str) -> String {
url.chars()
diff --git a/src/main.rs b/src/main.rs
index 91c086b..9e3b1e0 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -118,12 +118,19 @@ enum Cmd {
fn main() -> anyhow::Result<()> {
let cli = Cli::parse();
- let cfg = match &cli.root {
- Some(r) => Config::load(r).unwrap_or_else(|_| Config {
- root: r.clone(),
+ // `init` is the only command that runs before a config exists. For everything
+ // else a missing config is the error it sounds like, not a reason to invent
+ // one: the old unconditional fallback turned a typo'd `--root` into a fresh
+ // empty server at the wrong path, whose commands then "succeeded" against a
+ // database with no subscriptions and no releases in it.
+ let root = cli.root.clone().unwrap_or_else(|| Config::default().root);
+ let cfg = if matches!(cli.cmd, Cmd::Init { .. }) {
+ Config::load(&root).unwrap_or_else(|_| Config {
+ root: root.clone(),
..Config::default()
- }),
- None => Config::load(&Config::default().root)?,
+ })
+ } else {
+ Config::load(&root)?
};
if let Cmd::Serve { bind } = &cli.cmd {
let mut cfg = cfg;
diff --git a/tests/config.rs b/tests/config.rs
new file mode 100644
index 0000000..c62c4c9
--- /dev/null
+++ b/tests/config.rs
@@ -0,0 +1,134 @@
+//! The server root: one directory, named once.
+//!
+//! `--root` selects the directory and `config.json` lives inside it, so the root
+//! *is* wherever the config was found; the `root` field in the file is a record
+//! of that, not a second knob. Re-joining a relative field onto the config's own
+//! directory is what made `--root runtime` become `runtime/runtime/…`: `init`
+//! created and migrated one tree, and every command after it ran against a
+//! second one with its own empty database.
+
+use std::path::{Path, PathBuf};
+use std::process::Command;
+
+use aur_build::config::Config;
+
+/// The exact shape of the bug: a relative `--root`, saved verbatim, read back by
+/// the next command. Relative to the crate root here, which is the cwd cargo
+/// gives a test — the same situation as running `--root runtime` from a directory
+/// that is not `/`.
+#[test]
+fn a_relative_root_is_absolutized_once_and_never_doubled() {
+ let rel = PathBuf::from("target").join("config-root-test").join("runtime");
+ let _ = std::fs::remove_dir_all(&rel);
+
+ let cfg = Config {
+ root: rel.clone(),
+ ..Config::default()
+ };
+ cfg.save().unwrap();
+ let reloaded = Config::load(&rel).unwrap();
+
+ assert!(
+ reloaded.root.is_absolute(),
+ "a saved root must come back absolute, not relative: {}",
+ reloaded.root.display()
+ );
+ assert_eq!(reloaded.root, std::path::absolute(&rel).unwrap());
+ assert!(
+ !rel.join("runtime").exists(),
+ "the root must never be joined onto itself: {}",
+ rel.join("runtime").display()
+ );
+ // Everything derived hangs off the one root, so the database cannot end up in
+ // a second tree while the config sits in the first.
+ assert!(reloaded.db_path().starts_with(&reloaded.root));
+ assert!(reloaded.repo_arch_dir().starts_with(&reloaded.root));
+
+ std::fs::remove_dir_all(&rel).unwrap();
+}
+
+/// The legacy shape on disk: a config written by an `init` that saved
+/// `--root runtime` verbatim. Loading it must not resurrect the doubled tree.
+#[test]
+fn a_stale_relative_root_in_the_file_is_ignored() {
+ let tmp = tempfile::tempdir().unwrap();
+ std::fs::write(
+ tmp.path().join("config.json"),
+ "{\n \"root\": \"runtime\"\n}\n",
+ )
+ .unwrap();
+ let cfg = Config::load(tmp.path()).unwrap();
+ assert_eq!(cfg.root, std::path::absolute(tmp.path()).unwrap());
+ assert!(!cfg.root.join("runtime").exists());
+}
+
+#[test]
+fn a_root_with_no_config_is_an_error_not_a_fresh_server() {
+ let tmp = tempfile::tempdir().unwrap();
+ let err = Config::load(tmp.path()).unwrap_err();
+ assert!(
+ err.to_string().contains("run `aur-build init`"),
+ "the caller must be able to branch on \"there is no config yet\": {err}"
+ );
+}
+
+/// The CLI half of the same rule. The old fallback invented a default config for
+/// *any* command, so a typo'd `--root` quietly produced an empty server whose
+/// commands reported success against a database with nothing in it.
+#[test]
+fn the_cli_refuses_a_root_that_was_never_initialized() {
+ let tmp = tempfile::tempdir().unwrap();
+ let out = Command::new(env!("CARGO_BIN_EXE_aur-build"))
+ .args(["--root", &tmp.path().display().to_string(), "packages"])
+ .output()
+ .unwrap();
+ assert!(
+ !out.status.success(),
+ "a root with no config must fail, not answer from an empty server"
+ );
+ assert!(
+ out.stdout.is_empty(),
+ "nothing may be printed as though the server existed: {}",
+ String::from_utf8_lossy(&out.stdout)
+ );
+ let err = String::from_utf8_lossy(&out.stderr);
+ assert!(err.contains("init"), "{err}");
+}
+
+/// …and `init` is still allowed to run where there is no config yet, which is the
+/// only reason the fallback existed.
+#[test]
+fn init_still_runs_where_there_is_no_config_yet() {
+ let tmp = tempfile::tempdir().unwrap();
+ let root = tmp.path().join("runtime");
+ let out = Command::new(env!("CARGO_BIN_EXE_aur-build"))
+ .args(["--root", &root.display().to_string(), "init", "--repo", "aur"])
+ .output()
+ .unwrap();
+ assert!(
+ out.status.success(),
+ "{}",
+ String::from_utf8_lossy(&out.stderr)
+ );
+ assert!(root.join("config.json").exists());
+ assert!(root.join("aur-build.db").exists());
+
+ // And the command after it agrees about where the tree is.
+ let cfg = Config::load(&root).unwrap();
+ assert_eq!(cfg.root, std::path::absolute(&root).unwrap());
+ assert!(!root.join("runtime").exists(), "no doubled tree");
+}
+
+/// A root that exists but holds nothing but a config still resolves to itself,
+/// whichever way it was spelled.
+#[test]
+fn an_absolute_root_is_used_verbatim() {
+ let tmp = tempfile::tempdir().unwrap();
+ let dir: &Path = tmp.path();
+ std::fs::write(
+ dir.join("config.json"),
+ format!("{{\n \"root\": \"{}\"\n}}\n", dir.display()),
+ )
+ .unwrap();
+ assert_eq!(Config::load(dir).unwrap().root, dir);
+}