| @@ -2070,6 +2070,7 @@ dependencies = [ |
| 2070 | "nix 0.31.4", | 2070 | "nix 0.31.4", |
| 2071 | "oci-client", | 2071 | "oci-client", |
| 2072 | "oci-spec", | 2072 | "oci-spec", |
| | 2073 | + "rand 0.10.4", |
| 2073 | "reqwest", | 2074 | "reqwest", |
| 2074 | "seccompiler", | 2075 | "seccompiler", |
| 2075 | "serde", | 2076 | "serde", |
| @@ -14,7 +14,6 @@ pub fn emit_identity() { |
| 14 | if env::var("PROFILE").as_deref() != Ok("release") { | 14 | if env::var("PROFILE").as_deref() != Ok("release") { |
| 15 | println!("cargo:rustc-env=FORGE_GIT_SHA=unknown"); | 15 | println!("cargo:rustc-env=FORGE_GIT_SHA=unknown"); |
| 16 | println!("cargo:rustc-env=FORGE_GIT_DATE=unknown"); | 16 | println!("cargo:rustc-env=FORGE_GIT_DATE=unknown"); |
| 17 | - println!("cargo:rustc-env=FORGE_GIT_DIRTY=0"); | | |
| 18 | return; | 17 | return; |
| 19 | } | 18 | } |
| 20 | | 19 | |
| @@ -39,8 +38,6 @@ pub fn emit_identity() { |
| 39 | let date = git(&["show", "-s", "--format=%cs", "HEAD"]) | 38 | let date = git(&["show", "-s", "--format=%cs", "HEAD"]) |
| 40 | .or_else(|| env::var("FORGE_BUILD_DATE").ok().filter(|s| !s.is_empty())) | 39 | .or_else(|| env::var("FORGE_BUILD_DATE").ok().filter(|s| !s.is_empty())) |
| 41 | .unwrap_or_else(|| "unknown".into()); | 40 | .unwrap_or_else(|| "unknown".into()); |
| 42 | - let dirty = git(&["status", "--porcelain", "--untracked-files=no"]).is_some(); | | |
| 43 | println!("cargo:rustc-env=FORGE_GIT_SHA={sha}"); | 41 | println!("cargo:rustc-env=FORGE_GIT_SHA={sha}"); |
| 44 | println!("cargo:rustc-env=FORGE_GIT_DATE={date}"); | 42 | println!("cargo:rustc-env=FORGE_GIT_DATE={date}"); |
| 45 | - println!("cargo:rustc-env=FORGE_GIT_DIRTY={}", u8::from(dirty)); | | |
| 46 | } | 43 | } |
| @@ -5,17 +5,12 @@ pub const VERSION: &str = env!("CARGO_PKG_VERSION"); |
| 5 | struct Identity { | 5 | struct Identity { |
| 6 | commit: &'static str, | 6 | commit: &'static str, |
| 7 | date: &'static str, | 7 | date: &'static str, |
| 8 | - dirty: bool, | | |
| 9 | } | 8 | } |
| 10 | | 9 | |
| 11 | static IDENTITY: OnceLock<Identity> = OnceLock::new(); | 10 | static IDENTITY: OnceLock<Identity> = OnceLock::new(); |
| 12 | | 11 | |
| 13 | -pub fn set_identity(commit: &'static str, date: &'static str, dirty: bool) { | 12 | +pub fn set_identity(commit: &'static str, date: &'static str) { |
| 14 | - let _ = IDENTITY.set(Identity { | 13 | + let _ = IDENTITY.set(Identity { commit, date }); |
| 15 | - commit, | | |
| 16 | - date, | | |
| 17 | - dirty, | | |
| 18 | - }); | | |
| 19 | } | 14 | } |
| 20 | | 15 | |
| 21 | pub fn commit() -> &'static str { | 16 | pub fn commit() -> &'static str { |
| @@ -26,23 +21,17 @@ pub fn date() -> &'static str { |
| 26 | IDENTITY.get().map_or("unknown", |i| i.date) | 21 | IDENTITY.get().map_or("unknown", |i| i.date) |
| 27 | } | 22 | } |
| 28 | | 23 | |
| 29 | -pub fn dirty() -> bool { | | |
| 30 | - IDENTITY.get().is_some_and(|i| i.dirty) | | |
| 31 | -} | | |
| 32 | - | | |
| 33 | pub fn display() -> String { | 24 | pub fn display() -> String { |
| 34 | - format_build(VERSION, commit(), date(), dirty()) | 25 | + format_build(VERSION, commit(), date()) |
| 35 | } | 26 | } |
| 36 | | 27 | |
| 37 | -pub fn format_build(version: &str, commit: &str, date: &str, dirty: bool) -> String { | 28 | +pub fn format_build(version: &str, commit: &str, date: &str) -> String { |
| 38 | - let dirty = if dirty { "-dirty" } else { "" }; | 29 | + format!("{version} ({commit}, {date})") |
| 39 | - format!("{version} ({commit}{dirty}, {date})") | | |
| 40 | } | 30 | } |
| 41 | | 31 | |
| 42 | pub fn commit_of(build: &str) -> Option<&str> { | 32 | pub fn commit_of(build: &str) -> Option<&str> { |
| 43 | let inner = build.split_once('(')?.1; | 33 | let inner = build.split_once('(')?.1; |
| 44 | let commit = inner.split([',', ')']).next()?.trim(); | 34 | let commit = inner.split([',', ')']).next()?.trim(); |
| 45 | - let commit = commit.strip_suffix("-dirty").unwrap_or(commit); | | |
| 46 | (!commit.is_empty() && commit != "unknown").then_some(commit) | 35 | (!commit.is_empty() && commit != "unknown").then_some(commit) |
| 47 | } | 36 | } |
| 48 | | 37 | |
| @@ -67,15 +56,13 @@ mod tests { |
| 67 | | 56 | |
| 68 | #[test] | 57 | #[test] |
| 69 | fn up_to_date_compares_the_commit_only() { | 58 | fn up_to_date_compares_the_commit_only() { |
| 70 | - let server = format_build("0.1.0", "cf8e648", "2026-10-20", false); | 59 | + let server = format_build("0.1.0", "cf8e648", "2026-10-20"); |
| 71 | assert_eq!(server, "0.1.0 (cf8e648, 2026-10-20)"); | 60 | assert_eq!(server, "0.1.0 (cf8e648, 2026-10-20)"); |
| 72 | - let same = format_build("0.1.0", "cf8e648", "2026-10-20", true); | 61 | + let older = format_build("0.1.0", "4d21658", "2026-10-19"); |
| 73 | - assert_eq!(compare(Some(&same), &server), Freshness::UpToDate); | | |
| 74 | - let older = format_build("0.1.0", "4d21658", "2026-10-19", false); | | |
| 75 | assert_eq!(compare(Some(&older), &server), Freshness::Outdated); | 62 | assert_eq!(compare(Some(&older), &server), Freshness::Outdated); |
| 76 | assert_eq!(compare(None, &server), Freshness::Unknown); | 63 | assert_eq!(compare(None, &server), Freshness::Unknown); |
| 77 | assert_eq!(compare(Some("0.1.0"), &server), Freshness::Unknown); | 64 | assert_eq!(compare(Some("0.1.0"), &server), Freshness::Unknown); |
| 78 | - let unknown = format_build("0.1.0", "unknown", "unknown", false); | 65 | + let unknown = format_build("0.1.0", "unknown", "unknown"); |
| 79 | - assert_eq!(compare(Some(&same), &unknown), Freshness::Unknown); | 66 | + assert_eq!(compare(Some(&server), &unknown), Freshness::Unknown); |
| 80 | } | 67 | } |
| 81 | } | 68 | } |
| @@ -1,22 +1,34 @@ |
| 1 | use std::collections::{BTreeMap, BTreeSet}; | 1 | use std::collections::{BTreeMap, BTreeSet}; |
| 2 | | 2 | |
| 3 | -use globset::{Glob, GlobBuilder}; | | |
| 4 | use serde::{Deserialize, Serialize}; | 3 | use serde::{Deserialize, Serialize}; |
| 5 | | 4 | |
| 6 | use crate::error::ConfigError; | 5 | use crate::error::ConfigError; |
| 7 | | 6 | |
| 8 | -const MAX_CONFIG_BYTES: usize = 64 * 1024; | 7 | +mod artifact; |
| | 8 | +mod cache; |
| | 9 | +mod job; |
| | 10 | +mod matrix; |
| | 11 | +mod memory; |
| | 12 | +mod release; |
| | 13 | +mod schedule; |
| | 14 | +mod trigger; |
| | 15 | +mod workflow; |
| | 16 | + |
| | 17 | +pub use job::JobSpec; |
| | 18 | +pub use matrix::{MatrixSpec, MatrixValue}; |
| | 19 | +pub use release::{Prerelease, ReleaseNotes, ReleaseSpec}; |
| | 20 | +pub use trigger::Triggers; |
| | 21 | + |
| | 22 | +use job::{is_job_name, validate_job}; |
| | 23 | +use matrix::{combinations, interpolate}; |
| | 24 | +use release::validate_release; |
| | 25 | +use schedule::validate_schedules; |
| | 26 | +use trigger::{matches_any, validate_trigger_glob}; |
| | 27 | +use workflow::validate_workflow_name; |
| | 28 | + |
| | 29 | +pub const MAX_CONFIG_BYTES: usize = 64 * 1024; |
| 9 | const MAX_JOBS: usize = 20; | 30 | const MAX_JOBS: usize = 20; |
| 10 | -const DEFAULT_TIMEOUT_MINUTES: u32 = 60; | 31 | +pub const DEFAULT_TIMEOUT_MINUTES: u32 = 60; |
| 11 | -const TIMEOUT_RANGE_MINUTES: std::ops::RangeInclusive<u32> = 1..=360; | | |
| 12 | -const MAX_WORKFLOW_NAME_CHARS: usize = 40; | | |
| 13 | -const MAX_CACHE_ENTRIES: usize = 8; | | |
| 14 | -const MAX_CACHE_PATH_CHARS: usize = 200; | | |
| 15 | -const MAX_RELEASE_ASSETS: usize = 32; | | |
| 16 | -const MAX_RELEASE_TITLE_CHARS: usize = 200; | | |
| 17 | - | | |
| 18 | -const MAX_SCHEDULES: usize = 8; | | |
| 19 | -const MAX_MATRIX_VALUE_CHARS: usize = 64; | | |
| 20 | | 32 | |
| 21 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] | 33 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 22 | pub struct CiConfig { | 34 | pub struct CiConfig { |
| @@ -32,192 +44,6 @@ pub struct CiConfig { |
| 32 | pub warnings: Vec<String>, | 44 | pub warnings: Vec<String>, |
| 33 | } | 45 | } |
| 34 | | 46 | |
| 35 | -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] | | |
| 36 | -#[serde(default)] | | |
| 37 | -pub struct ReleaseSpec { | | |
| 38 | - pub assets: Vec<String>, | | |
| 39 | - pub prerelease: Prerelease, | | |
| 40 | - pub draft: bool, | | |
| 41 | - pub notes: ReleaseNotes, | | |
| 42 | - pub title: String, | | |
| 43 | -} | | |
| 44 | - | | |
| 45 | -impl Default for ReleaseSpec { | | |
| 46 | - fn default() -> Self { | | |
| 47 | - Self { | | |
| 48 | - assets: Vec::new(), | | |
| 49 | - prerelease: Prerelease::Auto, | | |
| 50 | - draft: false, | | |
| 51 | - notes: ReleaseNotes::Commits, | | |
| 52 | - title: "{tag}".to_string(), | | |
| 53 | - } | | |
| 54 | - } | | |
| 55 | -} | | |
| 56 | - | | |
| 57 | -#[derive(Debug, Clone, Copy, PartialEq, Eq)] | | |
| 58 | -pub enum Prerelease { | | |
| 59 | - Auto, | | |
| 60 | - Always, | | |
| 61 | - Never, | | |
| 62 | -} | | |
| 63 | - | | |
| 64 | -impl Serialize for Prerelease { | | |
| 65 | - fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { | | |
| 66 | - match self { | | |
| 67 | - Prerelease::Auto => serializer.serialize_str("auto"), | | |
| 68 | - Prerelease::Always => serializer.serialize_bool(true), | | |
| 69 | - Prerelease::Never => serializer.serialize_bool(false), | | |
| 70 | - } | | |
| 71 | - } | | |
| 72 | -} | | |
| 73 | - | | |
| 74 | -impl<'de> Deserialize<'de> for Prerelease { | | |
| 75 | - fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { | | |
| 76 | - #[derive(Deserialize)] | | |
| 77 | - #[serde(untagged)] | | |
| 78 | - enum Raw { | | |
| 79 | - Flag(bool), | | |
| 80 | - Text(String), | | |
| 81 | - } | | |
| 82 | - match Raw::deserialize(deserializer)? { | | |
| 83 | - Raw::Flag(true) => Ok(Prerelease::Always), | | |
| 84 | - Raw::Flag(false) => Ok(Prerelease::Never), | | |
| 85 | - Raw::Text(text) if text == "auto" => Ok(Prerelease::Auto), | | |
| 86 | - Raw::Text(text) => Err(serde::de::Error::custom(format!( | | |
| 87 | - "prerelease must be \"auto\", true or false, got {text:?}" | | |
| 88 | - ))), | | |
| 89 | - } | | |
| 90 | - } | | |
| 91 | -} | | |
| 92 | - | | |
| 93 | -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] | | |
| 94 | -#[serde(rename_all = "lowercase")] | | |
| 95 | -pub enum ReleaseNotes { | | |
| 96 | - Commits, | | |
| 97 | - #[serde(rename = "none")] | | |
| 98 | - Off, | | |
| 99 | -} | | |
| 100 | - | | |
| 101 | -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] | | |
| 102 | -#[serde(default)] | | |
| 103 | -pub struct Triggers { | | |
| 104 | - pub push: Vec<String>, | | |
| 105 | - pub tags: Vec<String>, | | |
| 106 | - pub pull_request: bool, | | |
| 107 | - pub manual: bool, | | |
| 108 | - pub cancel_superseded: bool, | | |
| 109 | - pub merge_queue: bool, | | |
| 110 | - pub schedule: Vec<String>, | | |
| 111 | -} | | |
| 112 | - | | |
| 113 | -impl Default for Triggers { | | |
| 114 | - fn default() -> Self { | | |
| 115 | - Self { | | |
| 116 | - push: Vec::new(), | | |
| 117 | - tags: Vec::new(), | | |
| 118 | - pull_request: false, | | |
| 119 | - manual: true, | | |
| 120 | - cancel_superseded: true, | | |
| 121 | - merge_queue: false, | | |
| 122 | - schedule: Vec::new(), | | |
| 123 | - } | | |
| 124 | - } | | |
| 125 | -} | | |
| 126 | - | | |
| 127 | -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] | | |
| 128 | -pub struct JobSpec { | | |
| 129 | - pub image: String, | | |
| 130 | - pub run: String, | | |
| 131 | - #[serde(default)] | | |
| 132 | - pub needs: Vec<String>, | | |
| 133 | - #[serde(default)] | | |
| 134 | - pub secrets: Vec<String>, | | |
| 135 | - #[serde(default)] | | |
| 136 | - pub env: BTreeMap<String, String>, | | |
| 137 | - #[serde(default)] | | |
| 138 | - pub artifacts: Vec<String>, | | |
| 139 | - #[serde(default)] | | |
| 140 | - pub runs_on: Vec<String>, | | |
| 141 | - #[serde(default)] | | |
| 142 | - pub cache: Vec<String>, | | |
| 143 | - #[serde(default = "default_timeout_minutes")] | | |
| 144 | - pub timeout_minutes: u32, | | |
| 145 | - #[serde(default = "default_network")] | | |
| 146 | - pub network: bool, | | |
| 147 | - #[serde( | | |
| 148 | - default, | | |
| 149 | - deserialize_with = "deserialize_memory", | | |
| 150 | - skip_serializing_if = "Option::is_none" | | |
| 151 | - )] | | |
| 152 | - pub memory: Option<u64>, | | |
| 153 | - #[serde(default, skip_serializing_if = "Option::is_none")] | | |
| 154 | - pub matrix: Option<MatrixSpec>, | | |
| 155 | -} | | |
| 156 | - | | |
| 157 | -#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] | | |
| 158 | -pub struct MatrixValue(pub String); | | |
| 159 | - | | |
| 160 | -impl Serialize for MatrixValue { | | |
| 161 | - fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { | | |
| 162 | - serializer.serialize_str(&self.0) | | |
| 163 | - } | | |
| 164 | -} | | |
| 165 | - | | |
| 166 | -impl<'de> Deserialize<'de> for MatrixValue { | | |
| 167 | - fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { | | |
| 168 | - #[derive(Deserialize)] | | |
| 169 | - #[serde(untagged)] | | |
| 170 | - enum Raw { | | |
| 171 | - Text(String), | | |
| 172 | - Int(i64), | | |
| 173 | - Flag(bool), | | |
| 174 | - } | | |
| 175 | - Ok(MatrixValue(match Raw::deserialize(deserializer)? { | | |
| 176 | - Raw::Text(text) => text, | | |
| 177 | - Raw::Int(n) => n.to_string(), | | |
| 178 | - Raw::Flag(b) => b.to_string(), | | |
| 179 | - })) | | |
| 180 | - } | | |
| 181 | -} | | |
| 182 | - | | |
| 183 | -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] | | |
| 184 | -pub struct MatrixSpec { | | |
| 185 | - #[serde(default)] | | |
| 186 | - pub exclude: Vec<BTreeMap<String, MatrixValue>>, | | |
| 187 | - #[serde(default)] | | |
| 188 | - pub include: Vec<BTreeMap<String, MatrixValue>>, | | |
| 189 | - #[serde(flatten)] | | |
| 190 | - pub axes: BTreeMap<String, Vec<MatrixValue>>, | | |
| 191 | -} | | |
| 192 | - | | |
| 193 | -const MEMORY_RANGE_BYTES: std::ops::RangeInclusive<u64> = (64 << 20)..=(1024 << 30); | | |
| 194 | - | | |
| 195 | -fn deserialize_memory<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<u64>, D::Error> { | | |
| 196 | - #[derive(Deserialize)] | | |
| 197 | - #[serde(untagged)] | | |
| 198 | - enum Raw { | | |
| 199 | - Bytes(u64), | | |
| 200 | - Text(String), | | |
| 201 | - } | | |
| 202 | - match Option::<Raw>::deserialize(d)? { | | |
| 203 | - None => Ok(None), | | |
| 204 | - Some(Raw::Bytes(n)) => Ok(Some(n)), | | |
| 205 | - Some(Raw::Text(text)) => crate::size::parse_size(&text).map(Some).ok_or_else(|| { | | |
| 206 | - serde::de::Error::custom(format!( | | |
| 207 | - "memory must be a size such as 4g or 512m, got {text:?}" | | |
| 208 | - )) | | |
| 209 | - }), | | |
| 210 | - } | | |
| 211 | -} | | |
| 212 | - | | |
| 213 | -fn default_timeout_minutes() -> u32 { | | |
| 214 | - DEFAULT_TIMEOUT_MINUTES | | |
| 215 | -} | | |
| 216 | - | | |
| 217 | -fn default_network() -> bool { | | |
| 218 | - true | | |
| 219 | -} | | |
| 220 | - | | |
| 221 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] | 47 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 222 | pub enum Event<'a> { | 48 | pub enum Event<'a> { |
| 223 | Push { branch: &'a str }, | 49 | Push { branch: &'a str }, |
| @@ -360,18 +186,7 @@ impl CiConfig { |
| 360 | for pattern in &self.on.tags { | 186 | for pattern in &self.on.tags { |
| 361 | validate_trigger_glob("tag", pattern)?; | 187 | validate_trigger_glob("tag", pattern)?; |
| 362 | } | 188 | } |
| 363 | - if self.on.schedule.len() > MAX_SCHEDULES { | 189 | + validate_schedules(&self.on.schedule)?; |
| 364 | - return Err(ConfigError::TooManySchedules { | | |
| 365 | - count: self.on.schedule.len(), | | |
| 366 | - max: MAX_SCHEDULES, | | |
| 367 | - }); | | |
| 368 | - } | | |
| 369 | - for expr in &self.on.schedule { | | |
| 370 | - crate::cron::parse(expr).map_err(|reason| ConfigError::InvalidSchedule { | | |
| 371 | - expr: expr.clone(), | | |
| 372 | - reason, | | |
| 373 | - })?; | | |
| 374 | - } | | |
| 375 | for (name, job) in &self.jobs { | 190 | for (name, job) in &self.jobs { |
| 376 | validate_job(name, job, &self.jobs)?; | 191 | validate_job(name, job, &self.jobs)?; |
| 377 | } | 192 | } |
| @@ -392,251 +207,6 @@ impl CiConfig { |
| 392 | } | 207 | } |
| 393 | } | 208 | } |
| 394 | | 209 | |
| 395 | -impl ReleaseSpec { | | |
| 396 | - pub fn is_prerelease(&self, tag: &str) -> bool { | | |
| 397 | - match self.prerelease { | | |
| 398 | - Prerelease::Auto => tag.contains('-'), | | |
| 399 | - Prerelease::Always => true, | | |
| 400 | - Prerelease::Never => false, | | |
| 401 | - } | | |
| 402 | - } | | |
| 403 | - | | |
| 404 | - pub fn title_for(&self, tag: &str) -> String { | | |
| 405 | - self.title.trim().replace("{tag}", tag) | | |
| 406 | - } | | |
| 407 | - | | |
| 408 | - pub fn asset_matches(&self, job: &str, artifact_name: &str) -> bool { | | |
| 409 | - self.assets.iter().any(|asset| { | | |
| 410 | - asset_selector(asset).is_some_and(|(selected_job, glob)| { | | |
| 411 | - names_job(selected_job, job) && matches_any(&[glob.to_string()], artifact_name) | | |
| 412 | - }) | | |
| 413 | - }) | | |
| 414 | - } | | |
| 415 | -} | | |
| 416 | - | | |
| 417 | -fn asset_selector(asset: &str) -> Option<(&str, &str)> { | | |
| 418 | - asset.split_once(':') | | |
| 419 | -} | | |
| 420 | - | | |
| 421 | -fn matches_any(globs: &[String], value: &str) -> bool { | | |
| 422 | - globs | | |
| 423 | - .iter() | | |
| 424 | - .any(|pattern| build_glob(pattern).is_ok_and(|g| g.compile_matcher().is_match(value))) | | |
| 425 | -} | | |
| 426 | - | | |
| 427 | -fn build_glob(pattern: &str) -> Result<Glob, globset::Error> { | | |
| 428 | - GlobBuilder::new(pattern).literal_separator(true).build() | | |
| 429 | -} | | |
| 430 | - | | |
| 431 | -fn validate_trigger_glob(kind: &'static str, pattern: &str) -> Result<(), ConfigError> { | | |
| 432 | - let invalid = |reason: String| ConfigError::InvalidTriggerGlob { | | |
| 433 | - kind, | | |
| 434 | - pattern: pattern.to_string(), | | |
| 435 | - reason, | | |
| 436 | - }; | | |
| 437 | - if pattern.is_empty() { | | |
| 438 | - return Err(invalid("pattern is empty".into())); | | |
| 439 | - } | | |
| 440 | - build_glob(pattern) | | |
| 441 | - .map(|_| ()) | | |
| 442 | - .map_err(|e| invalid(e.to_string())) | | |
| 443 | -} | | |
| 444 | - | | |
| 445 | -fn validate_workflow_name(name: &str) -> Result<(), ConfigError> { | | |
| 446 | - let invalid = |reason: &str| ConfigError::InvalidWorkflowName { | | |
| 447 | - name: name.to_string(), | | |
| 448 | - reason: reason.to_string(), | | |
| 449 | - }; | | |
| 450 | - let trimmed = name.trim(); | | |
| 451 | - if trimmed.is_empty() { | | |
| 452 | - return Err(invalid("must not be empty")); | | |
| 453 | - } | | |
| 454 | - if trimmed.chars().count() > MAX_WORKFLOW_NAME_CHARS { | | |
| 455 | - return Err(invalid(&format!( | | |
| 456 | - "must be at most {MAX_WORKFLOW_NAME_CHARS} characters" | | |
| 457 | - ))); | | |
| 458 | - } | | |
| 459 | - if trimmed.chars().any(char::is_control) { | | |
| 460 | - return Err(invalid("must not contain control characters")); | | |
| 461 | - } | | |
| 462 | - Ok(()) | | |
| 463 | -} | | |
| 464 | - | | |
| 465 | -fn is_job_name(name: &str) -> bool { | | |
| 466 | - let Some((first, rest)) = name.as_bytes().split_first() else { | | |
| 467 | - return false; | | |
| 468 | - }; | | |
| 469 | - rest.len() <= 39 | | |
| 470 | - && (first.is_ascii_lowercase() || first.is_ascii_digit()) | | |
| 471 | - && rest | | |
| 472 | - .iter() | | |
| 473 | - .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || *b == b'_' || *b == b'-') | | |
| 474 | -} | | |
| 475 | - | | |
| 476 | -fn is_env_name(name: &str) -> bool { | | |
| 477 | - let Some((first, rest)) = name.as_bytes().split_first() else { | | |
| 478 | - return false; | | |
| 479 | - }; | | |
| 480 | - rest.len() <= 63 | | |
| 481 | - && (first.is_ascii_uppercase() || *first == b'_') | | |
| 482 | - && rest | | |
| 483 | - .iter() | | |
| 484 | - .all(|b| b.is_ascii_uppercase() || b.is_ascii_digit() || *b == b'_') | | |
| 485 | -} | | |
| 486 | - | | |
| 487 | -fn is_runner_label(label: &str) -> bool { | | |
| 488 | - (1..=64).contains(&label.len()) | | |
| 489 | - && label | | |
| 490 | - .bytes() | | |
| 491 | - .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_' || b == b'.') | | |
| 492 | -} | | |
| 493 | - | | |
| 494 | -fn validate_artifact(job: &str, pattern: &str) -> Result<(), ConfigError> { | | |
| 495 | - let invalid = |reason: &str| ConfigError::InvalidArtifactGlob { | | |
| 496 | - job: job.to_string(), | | |
| 497 | - pattern: pattern.to_string(), | | |
| 498 | - reason: reason.to_string(), | | |
| 499 | - }; | | |
| 500 | - if pattern.is_empty() { | | |
| 501 | - return Err(invalid("pattern is empty")); | | |
| 502 | - } | | |
| 503 | - if pattern.starts_with('/') || pattern.starts_with('\\') { | | |
| 504 | - return Err(invalid("must be relative")); | | |
| 505 | - } | | |
| 506 | - if pattern.split(['/', '\\']).any(|part| part == "..") { | | |
| 507 | - return Err(invalid("must not contain \"..\"")); | | |
| 508 | - } | | |
| 509 | - build_glob(pattern) | | |
| 510 | - .map(|_| ()) | | |
| 511 | - .map_err(|e| invalid(&e.to_string())) | | |
| 512 | -} | | |
| 513 | - | | |
| 514 | -fn validate_cache(job: &str, entries: &[String]) -> Result<(), ConfigError> { | | |
| 515 | - if entries.len() > MAX_CACHE_ENTRIES { | | |
| 516 | - return Err(ConfigError::TooManyCacheEntries { | | |
| 517 | - job: job.to_string(), | | |
| 518 | - count: entries.len(), | | |
| 519 | - max: MAX_CACHE_ENTRIES, | | |
| 520 | - }); | | |
| 521 | - } | | |
| 522 | - let mut seen = BTreeSet::new(); | | |
| 523 | - for path in entries { | | |
| 524 | - validate_cache_path(job, path)?; | | |
| 525 | - if !seen.insert(path.as_str()) { | | |
| 526 | - return Err(ConfigError::DuplicateCachePath { | | |
| 527 | - job: job.to_string(), | | |
| 528 | - path: path.clone(), | | |
| 529 | - }); | | |
| 530 | - } | | |
| 531 | - } | | |
| 532 | - Ok(()) | | |
| 533 | -} | | |
| 534 | - | | |
| 535 | -fn validate_cache_path(job: &str, path: &str) -> Result<(), ConfigError> { | | |
| 536 | - let invalid = |reason: &str| ConfigError::InvalidCachePath { | | |
| 537 | - job: job.to_string(), | | |
| 538 | - path: path.to_string(), | | |
| 539 | - reason: reason.to_string(), | | |
| 540 | - }; | | |
| 541 | - if path.is_empty() { | | |
| 542 | - return Err(invalid("must not be empty")); | | |
| 543 | - } | | |
| 544 | - if path.chars().count() > MAX_CACHE_PATH_CHARS { | | |
| 545 | - return Err(invalid(&format!( | | |
| 546 | - "must be at most {MAX_CACHE_PATH_CHARS} characters" | | |
| 547 | - ))); | | |
| 548 | - } | | |
| 549 | - if path.starts_with('/') { | | |
| 550 | - return Err(invalid("must be relative")); | | |
| 551 | - } | | |
| 552 | - if path.contains('\\') { | | |
| 553 | - return Err(invalid("must not contain a backslash")); | | |
| 554 | - } | | |
| 555 | - if path.chars().any(|c| "*?[]{}".contains(c)) { | | |
| 556 | - return Err(invalid("must not contain glob characters")); | | |
| 557 | - } | | |
| 558 | - if path.chars().any(char::is_control) { | | |
| 559 | - return Err(invalid("must not contain control characters")); | | |
| 560 | - } | | |
| 561 | - for part in path.split('/') { | | |
| 562 | - match part { | | |
| 563 | - "" => return Err(invalid("must not contain empty components")), | | |
| 564 | - "." | ".." => return Err(invalid("must not contain \".\" or \"..\" components")), | | |
| 565 | - _ if part.eq_ignore_ascii_case(".git") => { | | |
| 566 | - return Err(invalid("must not be inside .git")); | | |
| 567 | - } | | |
| 568 | - _ => {} | | |
| 569 | - } | | |
| 570 | - } | | |
| 571 | - Ok(()) | | |
| 572 | -} | | |
| 573 | - | | |
| 574 | -fn validate_release( | | |
| 575 | - release: &ReleaseSpec, | | |
| 576 | - on: &Triggers, | | |
| 577 | - jobs: &BTreeMap<String, JobSpec>, | | |
| 578 | -) -> Result<(), ConfigError> { | | |
| 579 | - if on.tags.is_empty() { | | |
| 580 | - return Err(ConfigError::ReleaseWithoutTags); | | |
| 581 | - } | | |
| 582 | - if release.assets.len() > MAX_RELEASE_ASSETS { | | |
| 583 | - return Err(ConfigError::TooManyReleaseAssets { | | |
| 584 | - count: release.assets.len(), | | |
| 585 | - max: MAX_RELEASE_ASSETS, | | |
| 586 | - }); | | |
| 587 | - } | | |
| 588 | - for asset in &release.assets { | | |
| 589 | - validate_release_asset(asset, jobs)?; | | |
| 590 | - } | | |
| 591 | - validate_release_title(&release.title) | | |
| 592 | -} | | |
| 593 | - | | |
| 594 | -fn validate_release_asset( | | |
| 595 | - asset: &str, | | |
| 596 | - jobs: &BTreeMap<String, JobSpec>, | | |
| 597 | -) -> Result<(), ConfigError> { | | |
| 598 | - let invalid = |reason: String| ConfigError::InvalidReleaseAsset { | | |
| 599 | - asset: asset.to_string(), | | |
| 600 | - reason, | | |
| 601 | - }; | | |
| 602 | - let Some((job, glob)) = asset_selector(asset) else { | | |
| 603 | - return Err(invalid("must be \"job:glob\"".into())); | | |
| 604 | - }; | | |
| 605 | - let Some((_, spec)) = jobs.iter().find(|(name, _)| names_job(job, name)) else { | | |
| 606 | - return Err(invalid(format!("job {job:?} is not defined"))); | | |
| 607 | - }; | | |
| 608 | - if spec.artifacts.is_empty() { | | |
| 609 | - return Err(invalid(format!("job {job:?} declares no artifacts"))); | | |
| 610 | - } | | |
| 611 | - if glob.is_empty() { | | |
| 612 | - return Err(invalid("glob must not be empty".into())); | | |
| 613 | - } | | |
| 614 | - if glob.contains('/') { | | |
| 615 | - return Err(invalid( | | |
| 616 | - "glob must not contain \"/\", artifact names are flattened".into(), | | |
| 617 | - )); | | |
| 618 | - } | | |
| 619 | - build_glob(glob) | | |
| 620 | - .map(|_| ()) | | |
| 621 | - .map_err(|e| invalid(e.to_string())) | | |
| 622 | -} | | |
| 623 | - | | |
| 624 | -fn validate_release_title(title: &str) -> Result<(), ConfigError> { | | |
| 625 | - let invalid = |reason: String| ConfigError::InvalidReleaseTitle(reason); | | |
| 626 | - if title.trim().is_empty() { | | |
| 627 | - return Err(invalid("must not be empty".into())); | | |
| 628 | - } | | |
| 629 | - if title.trim().chars().count() > MAX_RELEASE_TITLE_CHARS { | | |
| 630 | - return Err(invalid(format!( | | |
| 631 | - "must be at most {MAX_RELEASE_TITLE_CHARS} characters" | | |
| 632 | - ))); | | |
| 633 | - } | | |
| 634 | - if title.chars().any(char::is_control) { | | |
| 635 | - return Err(invalid("must not contain control characters".into())); | | |
| 636 | - } | | |
| 637 | - Ok(()) | | |
| 638 | -} | | |
| 639 | - | | |
| 640 | fn names_job(selected: &str, job: &str) -> bool { | 210 | fn names_job(selected: &str, job: &str) -> bool { |
| 641 | selected == job | 211 | selected == job |
| 642 | || job | 212 | || job |
| @@ -644,245 +214,6 @@ fn names_job(selected: &str, job: &str) -> bool { |
| 644 | .is_some_and(|rest| rest.starts_with(" (")) | 214 | .is_some_and(|rest| rest.starts_with(" (")) |
| 645 | } | 215 | } |
| 646 | | 216 | |
| 647 | -fn is_matrix_key(key: &str) -> bool { | | |
| 648 | - let Some((first, rest)) = key.as_bytes().split_first() else { | | |
| 649 | - return false; | | |
| 650 | - }; | | |
| 651 | - rest.len() <= 31 | | |
| 652 | - && first.is_ascii_lowercase() | | |
| 653 | - && rest | | |
| 654 | - .iter() | | |
| 655 | - .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || *b == b'_') | | |
| 656 | -} | | |
| 657 | - | | |
| 658 | -type Combination = (String, BTreeMap<String, String>); | | |
| 659 | - | | |
| 660 | -fn combinations(job: &str, matrix: &MatrixSpec) -> Result<Vec<Combination>, ConfigError> { | | |
| 661 | - let bad = |reason: String| ConfigError::InvalidMatrix { | | |
| 662 | - job: job.to_string(), | | |
| 663 | - reason, | | |
| 664 | - }; | | |
| 665 | - if matrix.axes.is_empty() { | | |
| 666 | - return Err(bad( | | |
| 667 | - "needs at least one axis, e.g. rust = [\"stable\"]".into() | | |
| 668 | - )); | | |
| 669 | - } | | |
| 670 | - let mut total: usize = 1; | | |
| 671 | - for (key, values) in &matrix.axes { | | |
| 672 | - if !is_matrix_key(key) { | | |
| 673 | - return Err(bad(format!( | | |
| 674 | - "axis name {key:?} must match ^[a-z][a-z0-9_]{{0,31}}$" | | |
| 675 | - ))); | | |
| 676 | - } | | |
| 677 | - if values.is_empty() { | | |
| 678 | - return Err(bad(format!("axis {key:?} has no values"))); | | |
| 679 | - } | | |
| 680 | - for (i, value) in values.iter().enumerate() { | | |
| 681 | - validate_matrix_value(&value.0).map_err(|r| bad(format!("axis {key:?}: {r}")))?; | | |
| 682 | - if values[..i].contains(value) { | | |
| 683 | - return Err(bad(format!("axis {key:?} lists {:?} twice", value.0))); | | |
| 684 | - } | | |
| 685 | - } | | |
| 686 | - total = total.saturating_mul(values.len()); | | |
| 687 | - if total > MAX_JOBS { | | |
| 688 | - return Err(ConfigError::MatrixTooLarge { | | |
| 689 | - job: job.to_string(), | | |
| 690 | - count: total, | | |
| 691 | - max: MAX_JOBS, | | |
| 692 | - }); | | |
| 693 | - } | | |
| 694 | - } | | |
| 695 | - let mut combos: Vec<BTreeMap<String, String>> = vec![BTreeMap::new()]; | | |
| 696 | - for (key, values) in &matrix.axes { | | |
| 697 | - combos = combos | | |
| 698 | - .into_iter() | | |
| 699 | - .flat_map(|base| { | | |
| 700 | - values.iter().map(move |value| { | | |
| 701 | - let mut next = base.clone(); | | |
| 702 | - next.insert(key.clone(), value.0.clone()); | | |
| 703 | - next | | |
| 704 | - }) | | |
| 705 | - }) | | |
| 706 | - .collect(); | | |
| 707 | - } | | |
| 708 | - for entry in &matrix.exclude { | | |
| 709 | - for key in entry.keys() { | | |
| 710 | - if !matrix.axes.contains_key(key) { | | |
| 711 | - return Err(bad(format!("exclude names {key:?}, which is not an axis"))); | | |
| 712 | - } | | |
| 713 | - } | | |
| 714 | - combos.retain(|combo| !entry.iter().all(|(k, v)| combo.get(k) == Some(&v.0))); | | |
| 715 | - } | | |
| 716 | - for entry in &matrix.include { | | |
| 717 | - let mut combo = BTreeMap::new(); | | |
| 718 | - for (key, value) in entry { | | |
| 719 | - if !is_matrix_key(key) { | | |
| 720 | - return Err(bad(format!( | | |
| 721 | - "include key {key:?} must match ^[a-z][a-z0-9_]{{0,31}}$" | | |
| 722 | - ))); | | |
| 723 | - } | | |
| 724 | - validate_matrix_value(&value.0).map_err(|r| bad(format!("include {key:?}: {r}")))?; | | |
| 725 | - combo.insert(key.clone(), value.0.clone()); | | |
| 726 | - } | | |
| 727 | - if let Some(missing) = matrix.axes.keys().find(|k| !combo.contains_key(*k)) { | | |
| 728 | - return Err(bad(format!("an include entry must set axis {missing:?}"))); | | |
| 729 | - } | | |
| 730 | - let same_axes = |other: &BTreeMap<String, String>| { | | |
| 731 | - matrix.axes.keys().all(|k| other.get(k) == combo.get(k)) | | |
| 732 | - }; | | |
| 733 | - if !combos.iter().any(same_axes) { | | |
| 734 | - combos.push(combo); | | |
| 735 | - } | | |
| 736 | - } | | |
| 737 | - if combos.is_empty() { | | |
| 738 | - return Err(bad("exclude removes every combination".into())); | | |
| 739 | - } | | |
| 740 | - if combos.len() > MAX_JOBS { | | |
| 741 | - return Err(ConfigError::MatrixTooLarge { | | |
| 742 | - job: job.to_string(), | | |
| 743 | - count: combos.len(), | | |
| 744 | - max: MAX_JOBS, | | |
| 745 | - }); | | |
| 746 | - } | | |
| 747 | - Ok(combos | | |
| 748 | - .into_iter() | | |
| 749 | - .map(|combo| { | | |
| 750 | - let suffix = matrix | | |
| 751 | - .axes | | |
| 752 | - .keys() | | |
| 753 | - .filter_map(|k| combo.get(k).map(String::as_str)) | | |
| 754 | - .collect::<Vec<_>>() | | |
| 755 | - .join(", "); | | |
| 756 | - (suffix, combo) | | |
| 757 | - }) | | |
| 758 | - .collect()) | | |
| 759 | -} | | |
| 760 | - | | |
| 761 | -fn validate_matrix_value(value: &str) -> Result<(), String> { | | |
| 762 | - if value.is_empty() { | | |
| 763 | - return Err("values must not be empty".into()); | | |
| 764 | - } | | |
| 765 | - if value.chars().count() > MAX_MATRIX_VALUE_CHARS { | | |
| 766 | - return Err(format!( | | |
| 767 | - "values must be at most {MAX_MATRIX_VALUE_CHARS} characters" | | |
| 768 | - )); | | |
| 769 | - } | | |
| 770 | - if value | | |
| 771 | - .chars() | | |
| 772 | - .any(|c| c.is_control() || matches!(c, ',' | '(' | ')')) | | |
| 773 | - { | | |
| 774 | - return Err(format!( | | |
| 775 | - "{value:?} must not contain control characters, commas or parentheses" | | |
| 776 | - )); | | |
| 777 | - } | | |
| 778 | - Ok(()) | | |
| 779 | -} | | |
| 780 | - | | |
| 781 | -fn interpolate( | | |
| 782 | - job: &str, | | |
| 783 | - text: &str, | | |
| 784 | - vars: &BTreeMap<String, String>, | | |
| 785 | -) -> Result<String, ConfigError> { | | |
| 786 | - let mut out = String::with_capacity(text.len()); | | |
| 787 | - let mut rest = text; | | |
| 788 | - while let Some(at) = rest.find("${") { | | |
| 789 | - out.push_str(&rest[..at]); | | |
| 790 | - let after = &rest[at + 2..]; | | |
| 791 | - let found = if let Some(body) = after.strip_prefix('{') { | | |
| 792 | - body.find("}}") | | |
| 793 | - .map(|end| (body[..end].trim(), &body[end + 2..])) | | |
| 794 | - } else { | | |
| 795 | - after | | |
| 796 | - .find('}') | | |
| 797 | - .map(|end| (after[..end].trim(), &after[end + 1..])) | | |
| 798 | - }; | | |
| 799 | - match found.and_then(|(inner, tail)| Some((inner.strip_prefix("matrix.")?, tail))) { | | |
| 800 | - Some((key, tail)) => { | | |
| 801 | - let value = vars.get(key).ok_or_else(|| ConfigError::InvalidMatrix { | | |
| 802 | - job: job.to_string(), | | |
| 803 | - reason: format!("`matrix.{key}` is not an axis or include key"), | | |
| 804 | - })?; | | |
| 805 | - out.push_str(value); | | |
| 806 | - rest = tail; | | |
| 807 | - } | | |
| 808 | - None => { | | |
| 809 | - out.push_str("${"); | | |
| 810 | - rest = after; | | |
| 811 | - } | | |
| 812 | - } | | |
| 813 | - } | | |
| 814 | - out.push_str(rest); | | |
| 815 | - Ok(out) | | |
| 816 | -} | | |
| 817 | - | | |
| 818 | -fn validate_job( | | |
| 819 | - name: &str, | | |
| 820 | - job: &JobSpec, | | |
| 821 | - all: &BTreeMap<String, JobSpec>, | | |
| 822 | -) -> Result<(), ConfigError> { | | |
| 823 | - if job.image.is_empty() || job.image.chars().any(char::is_whitespace) { | | |
| 824 | - return Err(ConfigError::InvalidImage { | | |
| 825 | - job: name.to_string(), | | |
| 826 | - }); | | |
| 827 | - } | | |
| 828 | - if job.run.trim().is_empty() { | | |
| 829 | - return Err(ConfigError::EmptyRun { | | |
| 830 | - job: name.to_string(), | | |
| 831 | - }); | | |
| 832 | - } | | |
| 833 | - for need in &job.needs { | | |
| 834 | - if !all.contains_key(need) { | | |
| 835 | - return Err(ConfigError::UnknownNeed { | | |
| 836 | - job: name.to_string(), | | |
| 837 | - need: need.clone(), | | |
| 838 | - }); | | |
| 839 | - } | | |
| 840 | - } | | |
| 841 | - for secret in &job.secrets { | | |
| 842 | - if !is_env_name(secret) { | | |
| 843 | - return Err(ConfigError::InvalidSecretName { | | |
| 844 | - job: name.to_string(), | | |
| 845 | - name: secret.clone(), | | |
| 846 | - }); | | |
| 847 | - } | | |
| 848 | - } | | |
| 849 | - for key in job.env.keys() { | | |
| 850 | - if !is_env_name(key) { | | |
| 851 | - return Err(ConfigError::InvalidEnvName { | | |
| 852 | - job: name.to_string(), | | |
| 853 | - name: key.clone(), | | |
| 854 | - }); | | |
| 855 | - } | | |
| 856 | - } | | |
| 857 | - for pattern in &job.artifacts { | | |
| 858 | - validate_artifact(name, pattern)?; | | |
| 859 | - } | | |
| 860 | - for label in &job.runs_on { | | |
| 861 | - if !is_runner_label(label) { | | |
| 862 | - return Err(ConfigError::InvalidRunsOn { | | |
| 863 | - job: name.to_string(), | | |
| 864 | - label: label.clone(), | | |
| 865 | - }); | | |
| 866 | - } | | |
| 867 | - } | | |
| 868 | - validate_cache(name, &job.cache)?; | | |
| 869 | - if !TIMEOUT_RANGE_MINUTES.contains(&job.timeout_minutes) { | | |
| 870 | - return Err(ConfigError::InvalidTimeout { | | |
| 871 | - job: name.to_string(), | | |
| 872 | - value: job.timeout_minutes, | | |
| 873 | - }); | | |
| 874 | - } | | |
| 875 | - if let Some(memory) = job.memory | | |
| 876 | - && !MEMORY_RANGE_BYTES.contains(&memory) | | |
| 877 | - { | | |
| 878 | - return Err(ConfigError::InvalidMemory { | | |
| 879 | - job: name.to_string(), | | |
| 880 | - value: crate::size::format_size(memory), | | |
| 881 | - }); | | |
| 882 | - } | | |
| 883 | - Ok(()) | | |
| 884 | -} | | |
| 885 | - | | |
| 886 | #[cfg(test)] | 217 | #[cfg(test)] |
| 887 | mod tests { | 218 | mod tests { |
| 888 | use super::*; | 219 | use super::*; |
| @@ -907,11 +238,11 @@ cargo fmt --check |
| 907 | artifacts = ["target/release/forge"] | 238 | artifacts = ["target/release/forge"] |
| 908 | "#; | 239 | "#; |
| 909 | | 240 | |
| 910 | - fn job_toml(body: &str) -> String { | 241 | + pub(super) fn job_toml(body: &str) -> String { |
| 911 | format!("[jobs.build]\nimage = \"docker.io/rust:1\"\nrun = \"cargo build\"\n{body}\n") | 242 | format!("[jobs.build]\nimage = \"docker.io/rust:1\"\nrun = \"cargo build\"\n{body}\n") |
| 912 | } | 243 | } |
| 913 | | 244 | |
| 914 | - fn err_of(text: &str) -> ConfigError { | 245 | + pub(super) fn err_of(text: &str) -> ConfigError { |
| 915 | match parse_config(text) { | 246 | match parse_config(text) { |
| 916 | Ok(_) => panic!("expected an error for:\n{text}"), | 247 | Ok(_) => panic!("expected an error for:\n{text}"), |
| 917 | Err(e) => e, | 248 | Err(e) => e, |
| @@ -953,13 +284,6 @@ artifacts = ["target/release/forge"] |
| 953 | !parse_config(&job_toml("network = false")).unwrap().jobs["build"].network, | 284 | !parse_config(&job_toml("network = false")).unwrap().jobs["build"].network, |
| 954 | "network = false is honoured" | 285 | "network = false is honoured" |
| 955 | ); | 286 | ); |
| 956 | - let release = release_of(&release_toml("")); | | |
| 957 | - assert!(release.assets.is_empty()); | | |
| 958 | - assert_eq!(release.prerelease, Prerelease::Auto); | | |
| 959 | - assert!(!release.draft); | | |
| 960 | - assert_eq!(release.notes, ReleaseNotes::Commits); | | |
| 961 | - assert_eq!(release.title, "{tag}"); | | |
| 962 | - assert_eq!(release, ReleaseSpec::default()); | | |
| 963 | } | 287 | } |
| 964 | | 288 | |
| 965 | #[test] | 289 | #[test] |
| @@ -1022,47 +346,6 @@ artifacts = ["target/release/forge"] |
| 1022 | )); | 346 | )); |
| 1023 | } | 347 | } |
| 1024 | | 348 | |
| 1025 | - #[test] | | |
| 1026 | - fn memory_is_parsed_to_bytes() { | | |
| 1027 | - let cfg = parse_config(&job_toml("memory = \"4g\"")).unwrap(); | | |
| 1028 | - assert_eq!(cfg.jobs["build"].memory, Some(4 << 30)); | | |
| 1029 | - let cfg = parse_config(&job_toml("memory = \"512M\"")).unwrap(); | | |
| 1030 | - assert_eq!(cfg.jobs["build"].memory, Some(512 << 20)); | | |
| 1031 | - assert_eq!( | | |
| 1032 | - parse_config(&job_toml("")).unwrap().jobs["build"].memory, | | |
| 1033 | - None | | |
| 1034 | - ); | | |
| 1035 | - let job = &parse_config(&job_toml("memory = \"4g\"")).unwrap().jobs["build"]; | | |
| 1036 | - let json = serde_json::to_string(job).unwrap(); | | |
| 1037 | - assert!(json.contains("\"memory\":4294967296"), "{json}"); | | |
| 1038 | - let back: JobSpec = serde_json::from_str(&json).unwrap(); | | |
| 1039 | - assert_eq!(back.memory, Some(4 << 30)); | | |
| 1040 | - let old = json.replace(",\"memory\":4294967296", ""); | | |
| 1041 | - assert_eq!(serde_json::from_str::<JobSpec>(&old).unwrap().memory, None); | | |
| 1042 | - } | | |
| 1043 | - | | |
| 1044 | - #[test] | | |
| 1045 | - fn bad_memory_is_an_error() { | | |
| 1046 | - for bad in ["\"lots\"", "\"0\"", "\"-1g\"", "true"] { | | |
| 1047 | - assert!( | | |
| 1048 | - matches!( | | |
| 1049 | - err_of(&job_toml(&format!("memory = {bad}"))), | | |
| 1050 | - ConfigError::Toml(_) | | |
| 1051 | - ), | | |
| 1052 | - "{bad}" | | |
| 1053 | - ); | | |
| 1054 | - } | | |
| 1055 | - for bad in ["\"1m\"", "\"2t\""] { | | |
| 1056 | - assert!( | | |
| 1057 | - matches!( | | |
| 1058 | - err_of(&job_toml(&format!("memory = {bad}"))), | | |
| 1059 | - ConfigError::InvalidMemory { .. } | | |
| 1060 | - ), | | |
| 1061 | - "{bad}" | | |
| 1062 | - ); | | |
| 1063 | - } | | |
| 1064 | - } | | |
| 1065 | - | | |
| 1066 | #[test] | 349 | #[test] |
| 1067 | fn no_jobs_is_an_error() { | 350 | fn no_jobs_is_an_error() { |
| 1068 | assert_eq!(err_of("[on]\nmanual = true\n"), ConfigError::NoJobs); | 351 | assert_eq!(err_of("[on]\nmanual = true\n"), ConfigError::NoJobs); |
| @@ -1154,201 +437,6 @@ artifacts = ["target/release/forge"] |
| 1154 | ); | 437 | ); |
| 1155 | } | 438 | } |
| 1156 | | 439 | |
| 1157 | - #[test] | | |
| 1158 | - fn image_and_run_validation() { | | |
| 1159 | - let cases = [ | | |
| 1160 | - ("image", "[jobs.b]\nimage = \"\"\nrun = \"r\"\n"), | | |
| 1161 | - ("image", "[jobs.b]\nimage = \"a b\"\nrun = \"r\"\n"), | | |
| 1162 | - ("run", "[jobs.b]\nimage = \"i\"\nrun = \" \\n \"\n"), | | |
| 1163 | - ]; | | |
| 1164 | - for (want, text) in cases { | | |
| 1165 | - let got = match err_of(text) { | | |
| 1166 | - ConfigError::InvalidImage { .. } => "image", | | |
| 1167 | - ConfigError::EmptyRun { .. } => "run", | | |
| 1168 | - other => panic!("case {text:?}: unexpected error {other:?}"), | | |
| 1169 | - }; | | |
| 1170 | - assert_eq!(got, want, "case {text:?}"); | | |
| 1171 | - } | | |
| 1172 | - } | | |
| 1173 | - | | |
| 1174 | - #[test] | | |
| 1175 | - fn secret_and_env_names() { | | |
| 1176 | - let long = "A".repeat(65); | | |
| 1177 | - for bad in ["deploy", "1KEY", "A-B", "", long.as_str()] { | | |
| 1178 | - let text = job_toml(&format!("secrets = [{bad:?}]")); | | |
| 1179 | - assert!( | | |
| 1180 | - matches!(err_of(&text), ConfigError::InvalidSecretName { .. }), | | |
| 1181 | - "secret {bad:?} should be rejected" | | |
| 1182 | - ); | | |
| 1183 | - } | | |
| 1184 | - let text = job_toml("secrets = [\"_OK_1\"]"); | | |
| 1185 | - assert!(parse_config(&text).is_ok()); | | |
| 1186 | - let text = job_toml("[jobs.build.env]\n\"lower\" = \"x\""); | | |
| 1187 | - assert!(matches!(err_of(&text), ConfigError::InvalidEnvName { .. })); | | |
| 1188 | - let text = job_toml("[jobs.build.env]\nRUST_LOG = \"info\""); | | |
| 1189 | - assert!(parse_config(&text).is_ok()); | | |
| 1190 | - } | | |
| 1191 | - | | |
| 1192 | - #[test] | | |
| 1193 | - fn artifact_validation() { | | |
| 1194 | - for bad in ["/etc/passwd", "..", "a/../b", "\\\\x", "", "a/[b"] { | | |
| 1195 | - let text = job_toml(&format!("artifacts = [{bad:?}]")); | | |
| 1196 | - assert!( | | |
| 1197 | - matches!(err_of(&text), ConfigError::InvalidArtifactGlob { .. }), | | |
| 1198 | - "artifact {bad:?} should be rejected" | | |
| 1199 | - ); | | |
| 1200 | - } | | |
| 1201 | - let text = job_toml("artifacts = [\"target/release/*\", \"dist/**/*.tar\"]"); | | |
| 1202 | - assert!(parse_config(&text).is_ok()); | | |
| 1203 | - } | | |
| 1204 | - | | |
| 1205 | - #[test] | | |
| 1206 | - fn runs_on_validation() { | | |
| 1207 | - let text = job_toml("runs_on = [\"linux\", \"x86_64\"]"); | | |
| 1208 | - assert_eq!( | | |
| 1209 | - parse_config(&text).unwrap().jobs["build"].runs_on, | | |
| 1210 | - vec!["linux".to_string(), "x86_64".to_string()] | | |
| 1211 | - ); | | |
| 1212 | - let text = job_toml("runs_on = [\"has space\"]"); | | |
| 1213 | - assert!(matches!(err_of(&text), ConfigError::InvalidRunsOn { .. })); | | |
| 1214 | - let text = job_toml("runs_on = [\"\"]"); | | |
| 1215 | - assert!(matches!(err_of(&text), ConfigError::InvalidRunsOn { .. })); | | |
| 1216 | - } | | |
| 1217 | - | | |
| 1218 | - #[test] | | |
| 1219 | - fn cache_accepts_relative_directories() { | | |
| 1220 | - let text = job_toml("cache = [\"target\", \".cargo-home\", \"a/b/c\"]"); | | |
| 1221 | - assert_eq!( | | |
| 1222 | - parse_config(&text).unwrap().jobs["build"].cache, | | |
| 1223 | - vec![ | | |
| 1224 | - "target".to_string(), | | |
| 1225 | - ".cargo-home".to_string(), | | |
| 1226 | - "a/b/c".to_string() | | |
| 1227 | - ] | | |
| 1228 | - ); | | |
| 1229 | - let at_limit = "x".repeat(MAX_CACHE_PATH_CHARS); | | |
| 1230 | - let text = job_toml(&format!("cache = [{at_limit:?}]")); | | |
| 1231 | - assert!(parse_config(&text).is_ok()); | | |
| 1232 | - } | | |
| 1233 | - | | |
| 1234 | - #[test] | | |
| 1235 | - fn cache_rejects_bad_paths() { | | |
| 1236 | - let long = "x".repeat(MAX_CACHE_PATH_CHARS + 1); | | |
| 1237 | - let bad = [ | | |
| 1238 | - "".to_string(), | | |
| 1239 | - "/abs".to_string(), | | |
| 1240 | - "a\\b".to_string(), | | |
| 1241 | - "..".to_string(), | | |
| 1242 | - "a/../b".to_string(), | | |
| 1243 | - "./target".to_string(), | | |
| 1244 | - ".".to_string(), | | |
| 1245 | - "a//b".to_string(), | | |
| 1246 | - "target/".to_string(), | | |
| 1247 | - ".git".to_string(), | | |
| 1248 | - ".git/objects".to_string(), | | |
| 1249 | - "sub/.GIT/x".to_string(), | | |
| 1250 | - "target/*".to_string(), | | |
| 1251 | - "t?rget".to_string(), | | |
| 1252 | - "[t]".to_string(), | | |
| 1253 | - "{a,b}".to_string(), | | |
| 1254 | - long, | | |
| 1255 | - ]; | | |
| 1256 | - let text = job_toml(r#"cache = ["a\u0007b"]"#); | | |
| 1257 | - assert!(matches!( | | |
| 1258 | - err_of(&text), | | |
| 1259 | - ConfigError::InvalidCachePath { .. } | | |
| 1260 | - )); | | |
| 1261 | - for path in bad { | | |
| 1262 | - let text = job_toml(&format!("cache = [{path:?}]")); | | |
| 1263 | - assert!( | | |
| 1264 | - matches!(err_of(&text), ConfigError::InvalidCachePath { .. }), | | |
| 1265 | - "cache path {path:?} should be rejected" | | |
| 1266 | - ); | | |
| 1267 | - } | | |
| 1268 | - } | | |
| 1269 | - | | |
| 1270 | - #[test] | | |
| 1271 | - fn cache_rejects_duplicates_and_too_many_entries() { | | |
| 1272 | - let text = job_toml("cache = [\"target\", \"target\"]"); | | |
| 1273 | - assert!(matches!( | | |
| 1274 | - err_of(&text), | | |
| 1275 | - ConfigError::DuplicateCachePath { .. } | | |
| 1276 | - )); | | |
| 1277 | - let entries: Vec<String> = (0..=MAX_CACHE_ENTRIES).map(|i| format!("d{i}")).collect(); | | |
| 1278 | - let text = job_toml(&format!("cache = {entries:?}")); | | |
| 1279 | - assert_eq!( | | |
| 1280 | - err_of(&text), | | |
| 1281 | - ConfigError::TooManyCacheEntries { | | |
| 1282 | - job: "build".into(), | | |
| 1283 | - count: MAX_CACHE_ENTRIES + 1, | | |
| 1284 | - max: MAX_CACHE_ENTRIES | | |
| 1285 | - } | | |
| 1286 | - ); | | |
| 1287 | - let text = job_toml(&format!("cache = {:?}", &entries[..MAX_CACHE_ENTRIES])); | | |
| 1288 | - assert!(parse_config(&text).is_ok()); | | |
| 1289 | - } | | |
| 1290 | - | | |
| 1291 | - #[test] | | |
| 1292 | - fn timeout_validation() { | | |
| 1293 | - assert_eq!( | | |
| 1294 | - parse_config(&job_toml("timeout_minutes = 1")).unwrap().jobs["build"].timeout_minutes, | | |
| 1295 | - 1 | | |
| 1296 | - ); | | |
| 1297 | - assert_eq!( | | |
| 1298 | - parse_config(&job_toml("timeout_minutes = 360")) | | |
| 1299 | - .unwrap() | | |
| 1300 | - .jobs["build"] | | |
| 1301 | - .timeout_minutes, | | |
| 1302 | - 360 | | |
| 1303 | - ); | | |
| 1304 | - for bad in [0, 361] { | | |
| 1305 | - let text = job_toml(&format!("timeout_minutes = {bad}")); | | |
| 1306 | - assert_eq!( | | |
| 1307 | - err_of(&text), | | |
| 1308 | - ConfigError::InvalidTimeout { | | |
| 1309 | - job: "build".into(), | | |
| 1310 | - value: bad | | |
| 1311 | - } | | |
| 1312 | - ); | | |
| 1313 | - } | | |
| 1314 | - } | | |
| 1315 | - | | |
| 1316 | - #[test] | | |
| 1317 | - fn branch_and_tag_globs_match_only_their_event_kind() { | | |
| 1318 | - let text = format!("[on]\npush = [\"main\", \"release/*\"]\n{}", job_toml("")); | | |
| 1319 | - let cfg = parse_config(&text).unwrap(); | | |
| 1320 | - assert!(cfg.triggered_by(&Event::Push { branch: "main" })); | | |
| 1321 | - assert!(cfg.triggered_by(&Event::Push { | | |
| 1322 | - branch: "release/1.0" | | |
| 1323 | - })); | | |
| 1324 | - assert!(!cfg.triggered_by(&Event::Push { | | |
| 1325 | - branch: "release/1.0/x" | | |
| 1326 | - })); | | |
| 1327 | - assert!(!cfg.triggered_by(&Event::Push { branch: "mainx" })); | | |
| 1328 | - assert!(!cfg.triggered_by(&Event::Push { branch: "feature" })); | | |
| 1329 | - assert!(!cfg.triggered_by(&Event::Tag { tag: "v1" })); | | |
| 1330 | - | | |
| 1331 | - let text = format!("[on]\ntags = [\"v*\"]\n{}", job_toml("")); | | |
| 1332 | - let cfg = parse_config(&text).unwrap(); | | |
| 1333 | - assert!(cfg.triggered_by(&Event::Tag { tag: "v1.2.3" })); | | |
| 1334 | - assert!(!cfg.triggered_by(&Event::Tag { tag: "release-1" })); | | |
| 1335 | - assert!(!cfg.triggered_by(&Event::Push { branch: "v1" })); | | |
| 1336 | - } | | |
| 1337 | - | | |
| 1338 | - #[test] | | |
| 1339 | - fn invalid_trigger_globs_are_rejected() { | | |
| 1340 | - let text = format!("[on]\npush = [\"[\"]\n{}", job_toml("")); | | |
| 1341 | - assert!(matches!( | | |
| 1342 | - err_of(&text), | | |
| 1343 | - ConfigError::InvalidTriggerGlob { kind: "branch", .. } | | |
| 1344 | - )); | | |
| 1345 | - let text = format!("[on]\ntags = [\"\"]\n{}", job_toml("")); | | |
| 1346 | - assert!(matches!( | | |
| 1347 | - err_of(&text), | | |
| 1348 | - ConfigError::InvalidTriggerGlob { kind: "tag", .. } | | |
| 1349 | - )); | | |
| 1350 | - } | | |
| 1351 | - | | |
| 1352 | #[test] | 440 | #[test] |
| 1353 | fn job_order_is_topological_and_stable() { | 441 | fn job_order_is_topological_and_stable() { |
| 1354 | let text = "[jobs.lint]\nimage = \"i\"\nrun = \"r\"\nneeds = [\"test\"]\n\ | 442 | let text = "[jobs.lint]\nimage = \"i\"\nrun = \"r\"\nneeds = [\"test\"]\n\ |
| @@ -1369,383 +457,4 @@ artifacts = ["target/release/forge"] |
| 1369 | let cfg = parse_config(EXAMPLE).unwrap(); | 457 | let cfg = parse_config(EXAMPLE).unwrap(); |
| 1370 | assert_eq!(cfg.job_order(), vec!["test", "lint"]); | 458 | assert_eq!(cfg.job_order(), vec!["test", "lint"]); |
| 1371 | } | 459 | } |
| 1372 | - | | |
| 1373 | - #[test] | | |
| 1374 | - fn workflow_name_is_optional_and_kept() { | | |
| 1375 | - assert_eq!(parse_config(&job_toml("")).unwrap().name, None); | | |
| 1376 | - let cfg = parse_config(&format!("name = \"build\"\n{}", job_toml(""))).unwrap(); | | |
| 1377 | - assert_eq!(cfg.name.as_deref(), Some("build")); | | |
| 1378 | - } | | |
| 1379 | - | | |
| 1380 | - #[test] | | |
| 1381 | - fn workflow_name_must_be_one_non_blank_line() { | | |
| 1382 | - for text in [ | | |
| 1383 | - "name = \"\"", | | |
| 1384 | - "name = \" \"", | | |
| 1385 | - "name = \"a\\u0007b\"", | | |
| 1386 | - "name = \"a\\nb\"", | | |
| 1387 | - ] { | | |
| 1388 | - let err = err_of(&format!("{text}\n{}", job_toml(""))); | | |
| 1389 | - assert!( | | |
| 1390 | - matches!(err, ConfigError::InvalidWorkflowName { .. }), | | |
| 1391 | - "{text}: {err:?}" | | |
| 1392 | - ); | | |
| 1393 | - } | | |
| 1394 | - } | | |
| 1395 | - | | |
| 1396 | - #[test] | | |
| 1397 | - fn workflow_name_length_is_capped_after_trimming() { | | |
| 1398 | - let at_limit = "n".repeat(MAX_WORKFLOW_NAME_CHARS); | | |
| 1399 | - let ok = format!("name = \" {at_limit} \"\n{}", job_toml("")); | | |
| 1400 | - assert!(parse_config(&ok).is_ok()); | | |
| 1401 | - let over = "n".repeat(MAX_WORKFLOW_NAME_CHARS + 1); | | |
| 1402 | - let err = err_of(&format!("name = \"{over}\"\n{}", job_toml(""))); | | |
| 1403 | - assert!(matches!(err, ConfigError::InvalidWorkflowName { .. })); | | |
| 1404 | - } | | |
| 1405 | - | | |
| 1406 | - #[test] | | |
| 1407 | - fn workflow_name_must_be_a_string() { | | |
| 1408 | - assert!(matches!( | | |
| 1409 | - err_of(&format!("name = 3\n{}", job_toml(""))), | | |
| 1410 | - ConfigError::Toml(_) | | |
| 1411 | - )); | | |
| 1412 | - } | | |
| 1413 | - | | |
| 1414 | - fn release_toml(release: &str) -> String { | | |
| 1415 | - format!( | | |
| 1416 | - "[on]\ntags = [\"v*\"]\n{}\n[release]\n{release}\n", | | |
| 1417 | - job_toml("artifacts = [\"dist/*\"]") | | |
| 1418 | - ) | | |
| 1419 | - } | | |
| 1420 | - | | |
| 1421 | - fn release_of(text: &str) -> ReleaseSpec { | | |
| 1422 | - parse_config(text).unwrap().release.expect("release set") | | |
| 1423 | - } | | |
| 1424 | - | | |
| 1425 | - #[test] | | |
| 1426 | - fn release_full_table_parses() { | | |
| 1427 | - let text = release_toml( | | |
| 1428 | - "assets = [\"build:dist_*\", \"build:SHA256SUMS\"]\n\ | | |
| 1429 | - prerelease = true\ndraft = true\nnotes = \"none\"\ntitle = \"Release {tag}\"", | | |
| 1430 | - ); | | |
| 1431 | - let release = release_of(&text); | | |
| 1432 | - assert_eq!( | | |
| 1433 | - release.assets, | | |
| 1434 | - vec!["build:dist_*".to_string(), "build:SHA256SUMS".to_string()] | | |
| 1435 | - ); | | |
| 1436 | - assert_eq!(release.prerelease, Prerelease::Always); | | |
| 1437 | - assert!(release.draft); | | |
| 1438 | - assert_eq!(release.notes, ReleaseNotes::Off); | | |
| 1439 | - assert_eq!(release.title, "Release {tag}"); | | |
| 1440 | - } | | |
| 1441 | - | | |
| 1442 | - #[test] | | |
| 1443 | - fn release_prerelease_and_notes_values() { | | |
| 1444 | - assert_eq!( | | |
| 1445 | - release_of(&release_toml("prerelease = \"auto\"")).prerelease, | | |
| 1446 | - Prerelease::Auto | | |
| 1447 | - ); | | |
| 1448 | - assert_eq!( | | |
| 1449 | - release_of(&release_toml("prerelease = false")).prerelease, | | |
| 1450 | - Prerelease::Never | | |
| 1451 | - ); | | |
| 1452 | - assert_eq!( | | |
| 1453 | - release_of(&release_toml("notes = \"commits\"")).notes, | | |
| 1454 | - ReleaseNotes::Commits | | |
| 1455 | - ); | | |
| 1456 | - for bad in ["prerelease = \"yes\"", "notes = \"all\""] { | | |
| 1457 | - assert!( | | |
| 1458 | - matches!(err_of(&release_toml(bad)), ConfigError::Toml(_)), | | |
| 1459 | - "{bad}" | | |
| 1460 | - ); | | |
| 1461 | - } | | |
| 1462 | - } | | |
| 1463 | - | | |
| 1464 | - #[test] | | |
| 1465 | - fn release_unknown_keys_are_ignored_with_a_warning() { | | |
| 1466 | - let cfg = parse_config(&release_toml("bogus = 1")).unwrap(); | | |
| 1467 | - assert_eq!(cfg.warnings.len(), 1); | | |
| 1468 | - assert!( | | |
| 1469 | - cfg.warnings[0].contains("`release.bogus`"), | | |
| 1470 | - "{:?}", | | |
| 1471 | - cfg.warnings | | |
| 1472 | - ); | | |
| 1473 | - assert!(cfg.release.is_some()); | | |
| 1474 | - } | | |
| 1475 | - | | |
| 1476 | - #[test] | | |
| 1477 | - fn release_requires_tags() { | | |
| 1478 | - let text = format!("[release]\n{}", job_toml("artifacts = [\"dist/*\"]")); | | |
| 1479 | - assert_eq!(err_of(&text), ConfigError::ReleaseWithoutTags); | | |
| 1480 | - } | | |
| 1481 | - | | |
| 1482 | - #[test] | | |
| 1483 | - fn release_asset_must_be_job_and_glob() { | | |
| 1484 | - for bad in ["build", ":dist_*", "build:", "ghost:dist_*", "build:a/b"] { | | |
| 1485 | - let text = release_toml(&format!("assets = [{bad:?}]")); | | |
| 1486 | - assert!( | | |
| 1487 | - matches!(err_of(&text), ConfigError::InvalidReleaseAsset { .. }), | | |
| 1488 | - "asset {bad:?} should be rejected: {:?}", | | |
| 1489 | - err_of(&text) | | |
| 1490 | - ); | | |
| 1491 | - } | | |
| 1492 | - let text = release_toml("assets = [\"build:[\"]"); | | |
| 1493 | - assert!(matches!( | | |
| 1494 | - err_of(&text), | | |
| 1495 | - ConfigError::InvalidReleaseAsset { .. } | | |
| 1496 | - )); | | |
| 1497 | - } | | |
| 1498 | - | | |
| 1499 | - #[test] | | |
| 1500 | - fn release_asset_job_must_declare_artifacts() { | | |
| 1501 | - let text = format!( | | |
| 1502 | - "[on]\ntags = [\"v*\"]\n{}\n[release]\nassets = [\"build:x\"]\n", | | |
| 1503 | - job_toml("") | | |
| 1504 | - ); | | |
| 1505 | - match err_of(&text) { | | |
| 1506 | - ConfigError::InvalidReleaseAsset { asset, reason } => { | | |
| 1507 | - assert_eq!(asset, "build:x"); | | |
| 1508 | - assert!(reason.contains("no artifacts"), "{reason}"); | | |
| 1509 | - } | | |
| 1510 | - other => panic!("unexpected error {other:?}"), | | |
| 1511 | - } | | |
| 1512 | - } | | |
| 1513 | - | | |
| 1514 | - #[test] | | |
| 1515 | - fn release_assets_are_capped() { | | |
| 1516 | - let entries: Vec<String> = (0..=MAX_RELEASE_ASSETS) | | |
| 1517 | - .map(|_| "build:dist_*".to_string()) | | |
| 1518 | - .collect(); | | |
| 1519 | - let text = release_toml(&format!("assets = {entries:?}")); | | |
| 1520 | - assert_eq!( | | |
| 1521 | - err_of(&text), | | |
| 1522 | - ConfigError::TooManyReleaseAssets { | | |
| 1523 | - count: MAX_RELEASE_ASSETS + 1, | | |
| 1524 | - max: MAX_RELEASE_ASSETS | | |
| 1525 | - } | | |
| 1526 | - ); | | |
| 1527 | - let text = release_toml(&format!("assets = {:?}", &entries[..MAX_RELEASE_ASSETS])); | | |
| 1528 | - assert!(parse_config(&text).is_ok()); | | |
| 1529 | - } | | |
| 1530 | - | | |
| 1531 | - #[test] | | |
| 1532 | - fn release_title_validation() { | | |
| 1533 | - for bad in ["", " ", "a\\u0007b"] { | | |
| 1534 | - let text = release_toml(&format!("title = \"{bad}\"")); | | |
| 1535 | - assert!( | | |
| 1536 | - matches!(err_of(&text), ConfigError::InvalidReleaseTitle(_)), | | |
| 1537 | - "title {bad:?} should be rejected" | | |
| 1538 | - ); | | |
| 1539 | - } | | |
| 1540 | - let over = "t".repeat(MAX_RELEASE_TITLE_CHARS + 1); | | |
| 1541 | - let text = release_toml(&format!("title = \"{over}\"")); | | |
| 1542 | - assert!(matches!(err_of(&text), ConfigError::InvalidReleaseTitle(_))); | | |
| 1543 | - let at_limit = "t".repeat(MAX_RELEASE_TITLE_CHARS); | | |
| 1544 | - assert!(parse_config(&release_toml(&format!("title = \"{at_limit}\""))).is_ok()); | | |
| 1545 | - } | | |
| 1546 | - | | |
| 1547 | - #[test] | | |
| 1548 | - fn release_title_for_fills_tag() { | | |
| 1549 | - assert_eq!(ReleaseSpec::default().title_for("v1.2.0"), "v1.2.0"); | | |
| 1550 | - let release = release_of(&release_toml("title = \"Release {tag}\"")); | | |
| 1551 | - assert_eq!(release.title_for("v1.2.0"), "Release v1.2.0"); | | |
| 1552 | - let fixed = release_of(&release_toml("title = \"Stable\"")); | | |
| 1553 | - assert_eq!(fixed.title_for("v1.2.0"), "Stable"); | | |
| 1554 | - } | | |
| 1555 | - | | |
| 1556 | - #[test] | | |
| 1557 | - fn release_prerelease_auto_logic() { | | |
| 1558 | - let auto = ReleaseSpec::default(); | | |
| 1559 | - assert!(auto.is_prerelease("v1.2.0-rc1")); | | |
| 1560 | - assert!(auto.is_prerelease("v2.0.0-beta.3")); | | |
| 1561 | - assert!(!auto.is_prerelease("v1.2.0")); | | |
| 1562 | - let always = release_of(&release_toml("prerelease = true")); | | |
| 1563 | - assert!(always.is_prerelease("v1.2.0")); | | |
| 1564 | - let never = release_of(&release_toml("prerelease = false")); | | |
| 1565 | - assert!(!never.is_prerelease("v1.2.0-rc1")); | | |
| 1566 | - } | | |
| 1567 | - | | |
| 1568 | - #[test] | | |
| 1569 | - fn release_asset_matching() { | | |
| 1570 | - let release = release_of(&release_toml( | | |
| 1571 | - "assets = [\"build:forge-*-linux-*\", \"build:SHA256SUMS\"]", | | |
| 1572 | - )); | | |
| 1573 | - assert!(release.asset_matches("build", "forge-1.2.0-linux-x86_64")); | | |
| 1574 | - assert!(release.asset_matches("build", "SHA256SUMS")); | | |
| 1575 | - assert!(!release.asset_matches("build", "forge-1.2.0-darwin-arm64")); | | |
| 1576 | - assert!(!release.asset_matches("build", "SHA256SUMS.sig")); | | |
| 1577 | - assert!(!release.asset_matches("lint", "SHA256SUMS")); | | |
| 1578 | - assert!(!ReleaseSpec::default().asset_matches("build", "SHA256SUMS")); | | |
| 1579 | - } | | |
| 1580 | - | | |
| 1581 | - #[test] | | |
| 1582 | - fn wants_release_only_for_matching_tags() { | | |
| 1583 | - let text = release_toml(""); | | |
| 1584 | - let cfg = parse_config(&text).unwrap(); | | |
| 1585 | - assert!(cfg.wants_release(&Event::Tag { tag: "v1.2.0" })); | | |
| 1586 | - assert!(!cfg.wants_release(&Event::Tag { tag: "release-1" })); | | |
| 1587 | - assert!(!cfg.wants_release(&Event::Push { branch: "main" })); | | |
| 1588 | - assert!(!cfg.wants_release(&Event::Manual)); | | |
| 1589 | - assert!(!cfg.wants_release(&Event::PullRequest)); | | |
| 1590 | - | | |
| 1591 | - let without = parse_config(&format!("[on]\ntags = [\"v*\"]\n{}", job_toml(""))).unwrap(); | | |
| 1592 | - assert!(without.release.is_none()); | | |
| 1593 | - assert!(!without.wants_release(&Event::Tag { tag: "v1.2.0" })); | | |
| 1594 | - } | | |
| 1595 | - | | |
| 1596 | - fn matrix_toml(matrix: &str, extra: &str) -> String { | | |
| 1597 | - format!( | | |
| 1598 | - "[jobs.test]\nimage = \"rust:${{{{ matrix.rust }}}}\"\nrun = \"cargo +${{matrix.rust}} test --target $MATRIX_TARGET\"\nruns_on = [\"${{{{ matrix.target }}}}\"]\nmatrix = {matrix}\n{extra}\n" | | |
| 1599 | - ) | | |
| 1600 | - } | | |
| 1601 | - | | |
| 1602 | - const GRID: &str = r#"{ rust = ["stable", "1.85"], target = ["x86_64", "aarch64"] }"#; | | |
| 1603 | - | | |
| 1604 | - #[test] | | |
| 1605 | - fn schedule_is_parsed_and_validated() { | | |
| 1606 | - let cfg = parse_config(&format!( | | |
| 1607 | - "[on]\nschedule = [\"0 3 * * *\", \"*/15 * * * 1\"]\n{}", | | |
| 1608 | - job_toml("") | | |
| 1609 | - )) | | |
| 1610 | - .unwrap(); | | |
| 1611 | - assert_eq!(cfg.on.schedule.len(), 2); | | |
| 1612 | - assert!(cfg.warnings.is_empty()); | | |
| 1613 | - assert!(cfg.triggered_by(&Event::Schedule)); | | |
| 1614 | - let none = parse_config(&job_toml("")).unwrap(); | | |
| 1615 | - assert!(!none.triggered_by(&Event::Schedule)); | | |
| 1616 | - for bad in ["0 0 3 * * *", "nope", "70 3 * * *", ""] { | | |
| 1617 | - let text = format!("[on]\nschedule = [\"{bad}\"]\n{}", job_toml("")); | | |
| 1618 | - assert!( | | |
| 1619 | - matches!(err_of(&text), ConfigError::InvalidSchedule { .. }), | | |
| 1620 | - "{bad}" | | |
| 1621 | - ); | | |
| 1622 | - } | | |
| 1623 | - let many = ["\"0 3 * * *\""; MAX_SCHEDULES + 1].join(", "); | | |
| 1624 | - let text = format!("[on]\nschedule = [{many}]\n{}", job_toml("")); | | |
| 1625 | - assert!(matches!( | | |
| 1626 | - err_of(&text), | | |
| 1627 | - ConfigError::TooManySchedules { .. } | | |
| 1628 | - )); | | |
| 1629 | - } | | |
| 1630 | - | | |
| 1631 | - #[test] | | |
| 1632 | - fn a_matrix_expands_into_named_jobs() { | | |
| 1633 | - let cfg = parse_config(&matrix_toml(GRID, "")).unwrap(); | | |
| 1634 | - let names: Vec<&str> = cfg.jobs.keys().map(String::as_str).collect(); | | |
| 1635 | - assert_eq!( | | |
| 1636 | - names, | | |
| 1637 | - [ | | |
| 1638 | - "test (1.85, aarch64)", | | |
| 1639 | - "test (1.85, x86_64)", | | |
| 1640 | - "test (stable, aarch64)", | | |
| 1641 | - "test (stable, x86_64)" | | |
| 1642 | - ] | | |
| 1643 | - ); | | |
| 1644 | - let job = &cfg.jobs["test (stable, x86_64)"]; | | |
| 1645 | - assert_eq!(job.image, "rust:stable"); | | |
| 1646 | - assert_eq!(job.run, "cargo +stable test --target $MATRIX_TARGET"); | | |
| 1647 | - assert_eq!(job.runs_on, vec!["x86_64".to_string()]); | | |
| 1648 | - assert_eq!(job.env["MATRIX_RUST"], "stable"); | | |
| 1649 | - assert_eq!(job.env["MATRIX_TARGET"], "x86_64"); | | |
| 1650 | - assert!(job.matrix.is_none()); | | |
| 1651 | - } | | |
| 1652 | - | | |
| 1653 | - #[test] | | |
| 1654 | - fn matrix_exclude_and_include() { | | |
| 1655 | - let m = r#"{ rust = ["stable", "1.85"], target = ["x86_64", "aarch64"], exclude = [{ rust = "1.85", target = "aarch64" }], include = [{ rust = "nightly", target = "x86_64", flag = "-Z" }] }"#; | | |
| 1656 | - let cfg = parse_config(&matrix_toml(m, "")).unwrap(); | | |
| 1657 | - assert_eq!(cfg.jobs.len(), 4); | | |
| 1658 | - assert!(!cfg.jobs.contains_key("test (1.85, aarch64)")); | | |
| 1659 | - let extra = &cfg.jobs["test (nightly, x86_64)"]; | | |
| 1660 | - assert_eq!(extra.env["MATRIX_FLAG"], "-Z"); | | |
| 1661 | - let m = | | |
| 1662 | - r#"{ rust = ["stable", "1.85"], target = ["x86_64"], exclude = [{ rust = "1.85" }] }"#; | | |
| 1663 | - let cfg = parse_config(&matrix_toml(m, "")).unwrap(); | | |
| 1664 | - assert_eq!( | | |
| 1665 | - cfg.jobs.keys().collect::<Vec<_>>(), | | |
| 1666 | - ["test (stable, x86_64)"] | | |
| 1667 | - ); | | |
| 1668 | - let m = r#"{ rust = ["stable"], target = ["x86_64"], include = [{ rust = "stable", target = "x86_64" }] }"#; | | |
| 1669 | - assert_eq!(parse_config(&matrix_toml(m, "")).unwrap().jobs.len(), 1); | | |
| 1670 | - } | | |
| 1671 | - | | |
| 1672 | - #[test] | | |
| 1673 | - fn needs_on_a_matrix_job_waits_for_every_combination() { | | |
| 1674 | - let text = format!( | | |
| 1675 | - "{}\n[jobs.ship]\nimage = \"img\"\nrun = \"true\"\nneeds = [\"test\"]\n", | | |
| 1676 | - matrix_toml(GRID, "") | | |
| 1677 | - ); | | |
| 1678 | - let cfg = parse_config(&text).unwrap(); | | |
| 1679 | - assert_eq!(cfg.jobs["ship"].needs.len(), 4); | | |
| 1680 | - let order = cfg.job_order(); | | |
| 1681 | - assert_eq!(order.last(), Some(&"ship")); | | |
| 1682 | - let text = format!( | | |
| 1683 | - "[jobs.setup]\nimage = \"img\"\nrun = \"true\"\n{}", | | |
| 1684 | - matrix_toml(GRID, "needs = [\"setup\"]") | | |
| 1685 | - ); | | |
| 1686 | - let cfg = parse_config(&text).unwrap(); | | |
| 1687 | - assert_eq!(cfg.jobs["test (stable, x86_64)"].needs, ["setup"]); | | |
| 1688 | - } | | |
| 1689 | - | | |
| 1690 | - #[test] | | |
| 1691 | - fn matrix_errors_are_clear() { | | |
| 1692 | - let big = r#"{ a = [1,2,3,4,5], b = [1,2,3,4,5] }"#; | | |
| 1693 | - let text = format!("[jobs.t]\nimage = \"i\"\nrun = \"x\"\nmatrix = {big}\n"); | | |
| 1694 | - let e = err_of(&text); | | |
| 1695 | - assert_eq!( | | |
| 1696 | - e, | | |
| 1697 | - ConfigError::MatrixTooLarge { | | |
| 1698 | - job: "t".into(), | | |
| 1699 | - count: 25, | | |
| 1700 | - max: MAX_JOBS | | |
| 1701 | - } | | |
| 1702 | - ); | | |
| 1703 | - assert!(e.to_string().contains("limit is 20")); | | |
| 1704 | - let mut text = String::new(); | | |
| 1705 | - for i in 0..MAX_JOBS - 1 { | | |
| 1706 | - text.push_str(&format!("[jobs.j{i}]\nimage = \"img\"\nrun = \"true\"\n")); | | |
| 1707 | - } | | |
| 1708 | - text.push_str("[jobs.m]\nimage = \"i\"\nrun = \"x\"\nmatrix = { a = [1, 2] }\n"); | | |
| 1709 | - assert!(matches!(err_of(&text), ConfigError::TooManyJobs { .. })); | | |
| 1710 | - for bad in [ | | |
| 1711 | - "{}", | | |
| 1712 | - "{ a = [] }", | | |
| 1713 | - "{ a = [\"x\", \"x\"] }", | | |
| 1714 | - "{ A = [\"x\"] }", | | |
| 1715 | - "{ a = [\"x,y\"] }", | | |
| 1716 | - "{ a = [\"x\"], exclude = [{ b = \"1\" }] }", | | |
| 1717 | - "{ a = [\"x\"], exclude = [{ a = \"x\" }] }", | | |
| 1718 | - "{ a = [\"x\"], include = [{ b = \"1\" }] }", | | |
| 1719 | - ] { | | |
| 1720 | - let text = format!("[jobs.t]\nimage = \"i\"\nrun = \"x\"\nmatrix = {bad}\n"); | | |
| 1721 | - assert!( | | |
| 1722 | - matches!(err_of(&text), ConfigError::InvalidMatrix { .. }), | | |
| 1723 | - "{bad}" | | |
| 1724 | - ); | | |
| 1725 | - } | | |
| 1726 | - let text = | | |
| 1727 | - "[jobs.t]\nimage = \"i\"\nrun = \"echo ${matrix.nope}\"\nmatrix = { a = [\"x\"] }\n"; | | |
| 1728 | - assert!(matches!(err_of(text), ConfigError::InvalidMatrix { .. })); | | |
| 1729 | - let text = "[jobs.\"t (x)\"]\nimage = \"i\"\nrun = \"x\"\n"; | | |
| 1730 | - assert!(matches!(err_of(text), ConfigError::InvalidJobName(_))); | | |
| 1731 | - } | | |
| 1732 | - | | |
| 1733 | - #[test] | | |
| 1734 | - fn shell_variables_are_left_alone() { | | |
| 1735 | - let text = "[jobs.t]\nimage = \"i\"\nrun = \"echo ${HOME} ${{ secrets.X }} ${matrix.a}\"\nmatrix = { a = [\"x\"] }\n"; | | |
| 1736 | - let cfg = parse_config(text).unwrap(); | | |
| 1737 | - assert_eq!(cfg.jobs["t (x)"].run, "echo ${HOME} ${{ secrets.X }} x"); | | |
| 1738 | - } | | |
| 1739 | - | | |
| 1740 | - #[test] | | |
| 1741 | - fn release_assets_can_name_a_matrix_job() { | | |
| 1742 | - let text = format!( | | |
| 1743 | - "[on]\ntags = [\"v*\"]\n[release]\nassets = [\"test:*.tar\"]\n{}", | | |
| 1744 | - matrix_toml(GRID, "artifacts = [\"out/a.tar\"]") | | |
| 1745 | - ); | | |
| 1746 | - let cfg = parse_config(&text).unwrap(); | | |
| 1747 | - let release = cfg.release.unwrap(); | | |
| 1748 | - assert!(release.asset_matches("test (stable, x86_64)", "a.tar")); | | |
| 1749 | - assert!(!release.asset_matches("testing", "a.tar")); | | |
| 1750 | - } | | |
| 1751 | } | 460 | } |
| @@ -0,0 +1,43 @@ |
| | 1 | +use crate::error::ConfigError; |
| | 2 | + |
| | 3 | +use super::trigger::build_glob; |
| | 4 | + |
| | 5 | +pub(super) fn validate_artifact(job: &str, pattern: &str) -> Result<(), ConfigError> { |
| | 6 | + let invalid = |reason: &str| ConfigError::InvalidArtifactGlob { |
| | 7 | + job: job.to_string(), |
| | 8 | + pattern: pattern.to_string(), |
| | 9 | + reason: reason.to_string(), |
| | 10 | + }; |
| | 11 | + if pattern.is_empty() { |
| | 12 | + return Err(invalid("pattern is empty")); |
| | 13 | + } |
| | 14 | + if pattern.starts_with('/') || pattern.starts_with('\\') { |
| | 15 | + return Err(invalid("must be relative")); |
| | 16 | + } |
| | 17 | + if pattern.split(['/', '\\']).any(|part| part == "..") { |
| | 18 | + return Err(invalid("must not contain \"..\"")); |
| | 19 | + } |
| | 20 | + build_glob(pattern) |
| | 21 | + .map(|_| ()) |
| | 22 | + .map_err(|e| invalid(&e.to_string())) |
| | 23 | +} |
| | 24 | + |
| | 25 | +#[cfg(test)] |
| | 26 | +mod tests { |
| | 27 | + use crate::config::parse_config; |
| | 28 | + use crate::config::tests::{err_of, job_toml}; |
| | 29 | + use crate::error::ConfigError; |
| | 30 | + |
| | 31 | + #[test] |
| | 32 | + fn artifact_validation() { |
| | 33 | + for bad in ["/etc/passwd", "..", "a/../b", "\\\\x", "", "a/[b"] { |
| | 34 | + let text = job_toml(&format!("artifacts = [{bad:?}]")); |
| | 35 | + assert!( |
| | 36 | + matches!(err_of(&text), ConfigError::InvalidArtifactGlob { .. }), |
| | 37 | + "artifact {bad:?} should be rejected" |
| | 38 | + ); |
| | 39 | + } |
| | 40 | + let text = job_toml("artifacts = [\"target/release/*\", \"dist/**/*.tar\"]"); |
| | 41 | + assert!(parse_config(&text).is_ok()); |
| | 42 | + } |
| | 43 | +} |
| @@ -0,0 +1,147 @@ |
| | 1 | +use std::collections::BTreeSet; |
| | 2 | + |
| | 3 | +use crate::error::ConfigError; |
| | 4 | + |
| | 5 | +const MAX_CACHE_ENTRIES: usize = 8; |
| | 6 | +const MAX_CACHE_PATH_CHARS: usize = 200; |
| | 7 | + |
| | 8 | +pub(super) fn validate_cache(job: &str, entries: &[String]) -> Result<(), ConfigError> { |
| | 9 | + if entries.len() > MAX_CACHE_ENTRIES { |
| | 10 | + return Err(ConfigError::TooManyCacheEntries { |
| | 11 | + job: job.to_string(), |
| | 12 | + count: entries.len(), |
| | 13 | + max: MAX_CACHE_ENTRIES, |
| | 14 | + }); |
| | 15 | + } |
| | 16 | + let mut seen = BTreeSet::new(); |
| | 17 | + for path in entries { |
| | 18 | + validate_cache_path(job, path)?; |
| | 19 | + if !seen.insert(path.as_str()) { |
| | 20 | + return Err(ConfigError::DuplicateCachePath { |
| | 21 | + job: job.to_string(), |
| | 22 | + path: path.clone(), |
| | 23 | + }); |
| | 24 | + } |
| | 25 | + } |
| | 26 | + Ok(()) |
| | 27 | +} |
| | 28 | + |
| | 29 | +fn validate_cache_path(job: &str, path: &str) -> Result<(), ConfigError> { |
| | 30 | + let invalid = |reason: &str| ConfigError::InvalidCachePath { |
| | 31 | + job: job.to_string(), |
| | 32 | + path: path.to_string(), |
| | 33 | + reason: reason.to_string(), |
| | 34 | + }; |
| | 35 | + if path.is_empty() { |
| | 36 | + return Err(invalid("must not be empty")); |
| | 37 | + } |
| | 38 | + if path.chars().count() > MAX_CACHE_PATH_CHARS { |
| | 39 | + return Err(invalid(&format!( |
| | 40 | + "must be at most {MAX_CACHE_PATH_CHARS} characters" |
| | 41 | + ))); |
| | 42 | + } |
| | 43 | + if path.starts_with('/') { |
| | 44 | + return Err(invalid("must be relative")); |
| | 45 | + } |
| | 46 | + if path.contains('\\') { |
| | 47 | + return Err(invalid("must not contain a backslash")); |
| | 48 | + } |
| | 49 | + if path.chars().any(|c| "*?[]{}".contains(c)) { |
| | 50 | + return Err(invalid("must not contain glob characters")); |
| | 51 | + } |
| | 52 | + if path.chars().any(char::is_control) { |
| | 53 | + return Err(invalid("must not contain control characters")); |
| | 54 | + } |
| | 55 | + for part in path.split('/') { |
| | 56 | + match part { |
| | 57 | + "" => return Err(invalid("must not contain empty components")), |
| | 58 | + "." | ".." => return Err(invalid("must not contain \".\" or \"..\" components")), |
| | 59 | + _ if part.eq_ignore_ascii_case(".git") => { |
| | 60 | + return Err(invalid("must not be inside .git")); |
| | 61 | + } |
| | 62 | + _ => {} |
| | 63 | + } |
| | 64 | + } |
| | 65 | + Ok(()) |
| | 66 | +} |
| | 67 | + |
| | 68 | +#[cfg(test)] |
| | 69 | +mod tests { |
| | 70 | + use super::{MAX_CACHE_ENTRIES, MAX_CACHE_PATH_CHARS}; |
| | 71 | + use crate::config::parse_config; |
| | 72 | + use crate::config::tests::{err_of, job_toml}; |
| | 73 | + use crate::error::ConfigError; |
| | 74 | + |
| | 75 | + #[test] |
| | 76 | + fn cache_accepts_relative_directories() { |
| | 77 | + let text = job_toml("cache = [\"target\", \".cargo-home\", \"a/b/c\"]"); |
| | 78 | + assert_eq!( |
| | 79 | + parse_config(&text).unwrap().jobs["build"].cache, |
| | 80 | + vec![ |
| | 81 | + "target".to_string(), |
| | 82 | + ".cargo-home".to_string(), |
| | 83 | + "a/b/c".to_string() |
| | 84 | + ] |
| | 85 | + ); |
| | 86 | + let at_limit = "x".repeat(MAX_CACHE_PATH_CHARS); |
| | 87 | + let text = job_toml(&format!("cache = [{at_limit:?}]")); |
| | 88 | + assert!(parse_config(&text).is_ok()); |
| | 89 | + } |
| | 90 | + |
| | 91 | + #[test] |
| | 92 | + fn cache_rejects_bad_paths() { |
| | 93 | + let long = "x".repeat(MAX_CACHE_PATH_CHARS + 1); |
| | 94 | + let bad = [ |
| | 95 | + "".to_string(), |
| | 96 | + "/abs".to_string(), |
| | 97 | + "a\\b".to_string(), |
| | 98 | + "..".to_string(), |
| | 99 | + "a/../b".to_string(), |
| | 100 | + "./target".to_string(), |
| | 101 | + ".".to_string(), |
| | 102 | + "a//b".to_string(), |
| | 103 | + "target/".to_string(), |
| | 104 | + ".git".to_string(), |
| | 105 | + ".git/objects".to_string(), |
| | 106 | + "sub/.GIT/x".to_string(), |
| | 107 | + "target/*".to_string(), |
| | 108 | + "t?rget".to_string(), |
| | 109 | + "[t]".to_string(), |
| | 110 | + "{a,b}".to_string(), |
| | 111 | + long, |
| | 112 | + ]; |
| | 113 | + let text = job_toml(r#"cache = ["a\u0007b"]"#); |
| | 114 | + assert!(matches!( |
| | 115 | + err_of(&text), |
| | 116 | + ConfigError::InvalidCachePath { .. } |
| | 117 | + )); |
| | 118 | + for path in bad { |
| | 119 | + let text = job_toml(&format!("cache = [{path:?}]")); |
| | 120 | + assert!( |
| | 121 | + matches!(err_of(&text), ConfigError::InvalidCachePath { .. }), |
| | 122 | + "cache path {path:?} should be rejected" |
| | 123 | + ); |
| | 124 | + } |
| | 125 | + } |
| | 126 | + |
| | 127 | + #[test] |
| | 128 | + fn cache_rejects_duplicates_and_too_many_entries() { |
| | 129 | + let text = job_toml("cache = [\"target\", \"target\"]"); |
| | 130 | + assert!(matches!( |
| | 131 | + err_of(&text), |
| | 132 | + ConfigError::DuplicateCachePath { .. } |
| | 133 | + )); |
| | 134 | + let entries: Vec<String> = (0..=MAX_CACHE_ENTRIES).map(|i| format!("d{i}")).collect(); |
| | 135 | + let text = job_toml(&format!("cache = {entries:?}")); |
| | 136 | + assert_eq!( |
| | 137 | + err_of(&text), |
| | 138 | + ConfigError::TooManyCacheEntries { |
| | 139 | + job: "build".into(), |
| | 140 | + count: MAX_CACHE_ENTRIES + 1, |
| | 141 | + max: MAX_CACHE_ENTRIES |
| | 142 | + } |
| | 143 | + ); |
| | 144 | + let text = job_toml(&format!("cache = {:?}", &entries[..MAX_CACHE_ENTRIES])); |
| | 145 | + assert!(parse_config(&text).is_ok()); |
| | 146 | + } |
| | 147 | +} |
| @@ -0,0 +1,228 @@ |
| | 1 | +use std::collections::BTreeMap; |
| | 2 | + |
| | 3 | +use serde::{Deserialize, Serialize}; |
| | 4 | + |
| | 5 | +use crate::error::ConfigError; |
| | 6 | + |
| | 7 | +use super::DEFAULT_TIMEOUT_MINUTES; |
| | 8 | +use super::artifact::validate_artifact; |
| | 9 | +use super::cache::validate_cache; |
| | 10 | +use super::matrix::MatrixSpec; |
| | 11 | +use super::memory::{MEMORY_RANGE_BYTES, deserialize_memory}; |
| | 12 | + |
| | 13 | +const TIMEOUT_RANGE_MINUTES: std::ops::RangeInclusive<u32> = 1..=360; |
| | 14 | + |
| | 15 | +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| | 16 | +pub struct JobSpec { |
| | 17 | + pub image: String, |
| | 18 | + pub run: String, |
| | 19 | + #[serde(default)] |
| | 20 | + pub needs: Vec<String>, |
| | 21 | + #[serde(default)] |
| | 22 | + pub secrets: Vec<String>, |
| | 23 | + #[serde(default)] |
| | 24 | + pub env: BTreeMap<String, String>, |
| | 25 | + #[serde(default)] |
| | 26 | + pub artifacts: Vec<String>, |
| | 27 | + #[serde(default)] |
| | 28 | + pub runs_on: Vec<String>, |
| | 29 | + #[serde(default)] |
| | 30 | + pub cache: Vec<String>, |
| | 31 | + #[serde(default = "default_timeout_minutes")] |
| | 32 | + pub timeout_minutes: u32, |
| | 33 | + #[serde(default = "default_network")] |
| | 34 | + pub network: bool, |
| | 35 | + #[serde( |
| | 36 | + default, |
| | 37 | + deserialize_with = "deserialize_memory", |
| | 38 | + skip_serializing_if = "Option::is_none" |
| | 39 | + )] |
| | 40 | + pub memory: Option<u64>, |
| | 41 | + #[serde(default, skip_serializing_if = "Option::is_none")] |
| | 42 | + pub matrix: Option<MatrixSpec>, |
| | 43 | +} |
| | 44 | + |
| | 45 | +fn default_timeout_minutes() -> u32 { |
| | 46 | + DEFAULT_TIMEOUT_MINUTES |
| | 47 | +} |
| | 48 | + |
| | 49 | +fn default_network() -> bool { |
| | 50 | + true |
| | 51 | +} |
| | 52 | + |
| | 53 | +pub(super) fn is_job_name(name: &str) -> bool { |
| | 54 | + let Some((first, rest)) = name.as_bytes().split_first() else { |
| | 55 | + return false; |
| | 56 | + }; |
| | 57 | + rest.len() <= 39 |
| | 58 | + && (first.is_ascii_lowercase() || first.is_ascii_digit()) |
| | 59 | + && rest |
| | 60 | + .iter() |
| | 61 | + .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || *b == b'_' || *b == b'-') |
| | 62 | +} |
| | 63 | + |
| | 64 | +fn is_env_name(name: &str) -> bool { |
| | 65 | + let Some((first, rest)) = name.as_bytes().split_first() else { |
| | 66 | + return false; |
| | 67 | + }; |
| | 68 | + rest.len() <= 63 |
| | 69 | + && (first.is_ascii_uppercase() || *first == b'_') |
| | 70 | + && rest |
| | 71 | + .iter() |
| | 72 | + .all(|b| b.is_ascii_uppercase() || b.is_ascii_digit() || *b == b'_') |
| | 73 | +} |
| | 74 | + |
| | 75 | +fn is_runner_label(label: &str) -> bool { |
| | 76 | + (1..=64).contains(&label.len()) |
| | 77 | + && label |
| | 78 | + .bytes() |
| | 79 | + .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_' || b == b'.') |
| | 80 | +} |
| | 81 | + |
| | 82 | +pub(super) fn validate_job( |
| | 83 | + name: &str, |
| | 84 | + job: &JobSpec, |
| | 85 | + all: &BTreeMap<String, JobSpec>, |
| | 86 | +) -> Result<(), ConfigError> { |
| | 87 | + if job.image.is_empty() || job.image.chars().any(char::is_whitespace) { |
| | 88 | + return Err(ConfigError::InvalidImage { |
| | 89 | + job: name.to_string(), |
| | 90 | + }); |
| | 91 | + } |
| | 92 | + if job.run.trim().is_empty() { |
| | 93 | + return Err(ConfigError::EmptyRun { |
| | 94 | + job: name.to_string(), |
| | 95 | + }); |
| | 96 | + } |
| | 97 | + for need in &job.needs { |
| | 98 | + if !all.contains_key(need) { |
| | 99 | + return Err(ConfigError::UnknownNeed { |
| | 100 | + job: name.to_string(), |
| | 101 | + need: need.clone(), |
| | 102 | + }); |
| | 103 | + } |
| | 104 | + } |
| | 105 | + for secret in &job.secrets { |
| | 106 | + if !is_env_name(secret) { |
| | 107 | + return Err(ConfigError::InvalidSecretName { |
| | 108 | + job: name.to_string(), |
| | 109 | + name: secret.clone(), |
| | 110 | + }); |
| | 111 | + } |
| | 112 | + } |
| | 113 | + for key in job.env.keys() { |
| | 114 | + if !is_env_name(key) { |
| | 115 | + return Err(ConfigError::InvalidEnvName { |
| | 116 | + job: name.to_string(), |
| | 117 | + name: key.clone(), |
| | 118 | + }); |
| | 119 | + } |
| | 120 | + } |
| | 121 | + for pattern in &job.artifacts { |
| | 122 | + validate_artifact(name, pattern)?; |
| | 123 | + } |
| | 124 | + for label in &job.runs_on { |
| | 125 | + if !is_runner_label(label) { |
| | 126 | + return Err(ConfigError::InvalidRunsOn { |
| | 127 | + job: name.to_string(), |
| | 128 | + label: label.clone(), |
| | 129 | + }); |
| | 130 | + } |
| | 131 | + } |
| | 132 | + validate_cache(name, &job.cache)?; |
| | 133 | + if !TIMEOUT_RANGE_MINUTES.contains(&job.timeout_minutes) { |
| | 134 | + return Err(ConfigError::InvalidTimeout { |
| | 135 | + job: name.to_string(), |
| | 136 | + value: job.timeout_minutes, |
| | 137 | + }); |
| | 138 | + } |
| | 139 | + if let Some(memory) = job.memory |
| | 140 | + && !MEMORY_RANGE_BYTES.contains(&memory) |
| | 141 | + { |
| | 142 | + return Err(ConfigError::InvalidMemory { |
| | 143 | + job: name.to_string(), |
| | 144 | + value: crate::size::format_size(memory), |
| | 145 | + }); |
| | 146 | + } |
| | 147 | + Ok(()) |
| | 148 | +} |
| | 149 | + |
| | 150 | +#[cfg(test)] |
| | 151 | +mod tests { |
| | 152 | + use crate::config::parse_config; |
| | 153 | + use crate::config::tests::{err_of, job_toml}; |
| | 154 | + use crate::error::ConfigError; |
| | 155 | + |
| | 156 | + #[test] |
| | 157 | + fn image_and_run_validation() { |
| | 158 | + let cases = [ |
| | 159 | + ("image", "[jobs.b]\nimage = \"\"\nrun = \"r\"\n"), |
| | 160 | + ("image", "[jobs.b]\nimage = \"a b\"\nrun = \"r\"\n"), |
| | 161 | + ("run", "[jobs.b]\nimage = \"i\"\nrun = \" \\n \"\n"), |
| | 162 | + ]; |
| | 163 | + for (want, text) in cases { |
| | 164 | + let got = match err_of(text) { |
| | 165 | + ConfigError::InvalidImage { .. } => "image", |
| | 166 | + ConfigError::EmptyRun { .. } => "run", |
| | 167 | + other => panic!("case {text:?}: unexpected error {other:?}"), |
| | 168 | + }; |
| | 169 | + assert_eq!(got, want, "case {text:?}"); |
| | 170 | + } |
| | 171 | + } |
| | 172 | + |
| | 173 | + #[test] |
| | 174 | + fn secret_and_env_names() { |
| | 175 | + let long = "A".repeat(65); |
| | 176 | + for bad in ["deploy", "1KEY", "A-B", "", long.as_str()] { |
| | 177 | + let text = job_toml(&format!("secrets = [{bad:?}]")); |
| | 178 | + assert!( |
| | 179 | + matches!(err_of(&text), ConfigError::InvalidSecretName { .. }), |
| | 180 | + "secret {bad:?} should be rejected" |
| | 181 | + ); |
| | 182 | + } |
| | 183 | + let text = job_toml("secrets = [\"_OK_1\"]"); |
| | 184 | + assert!(parse_config(&text).is_ok()); |
| | 185 | + let text = job_toml("[jobs.build.env]\n\"lower\" = \"x\""); |
| | 186 | + assert!(matches!(err_of(&text), ConfigError::InvalidEnvName { .. })); |
| | 187 | + let text = job_toml("[jobs.build.env]\nRUST_LOG = \"info\""); |
| | 188 | + assert!(parse_config(&text).is_ok()); |
| | 189 | + } |
| | 190 | + |
| | 191 | + #[test] |
| | 192 | + fn runs_on_validation() { |
| | 193 | + let text = job_toml("runs_on = [\"linux\", \"x86_64\"]"); |
| | 194 | + assert_eq!( |
| | 195 | + parse_config(&text).unwrap().jobs["build"].runs_on, |
| | 196 | + vec!["linux".to_string(), "x86_64".to_string()] |
| | 197 | + ); |
| | 198 | + let text = job_toml("runs_on = [\"has space\"]"); |
| | 199 | + assert!(matches!(err_of(&text), ConfigError::InvalidRunsOn { .. })); |
| | 200 | + let text = job_toml("runs_on = [\"\"]"); |
| | 201 | + assert!(matches!(err_of(&text), ConfigError::InvalidRunsOn { .. })); |
| | 202 | + } |
| | 203 | + |
| | 204 | + #[test] |
| | 205 | + fn timeout_validation() { |
| | 206 | + assert_eq!( |
| | 207 | + parse_config(&job_toml("timeout_minutes = 1")).unwrap().jobs["build"].timeout_minutes, |
| | 208 | + 1 |
| | 209 | + ); |
| | 210 | + assert_eq!( |
| | 211 | + parse_config(&job_toml("timeout_minutes = 360")) |
| | 212 | + .unwrap() |
| | 213 | + .jobs["build"] |
| | 214 | + .timeout_minutes, |
| | 215 | + 360 |
| | 216 | + ); |
| | 217 | + for bad in [0, 361] { |
| | 218 | + let text = job_toml(&format!("timeout_minutes = {bad}")); |
| | 219 | + assert_eq!( |
| | 220 | + err_of(&text), |
| | 221 | + ConfigError::InvalidTimeout { |
| | 222 | + job: "build".into(), |
| | 223 | + value: bad |
| | 224 | + } |
| | 225 | + ); |
| | 226 | + } |
| | 227 | + } |
| | 228 | +} |
| @@ -0,0 +1,355 @@ |
| | 1 | +use std::collections::BTreeMap; |
| | 2 | + |
| | 3 | +use serde::{Deserialize, Serialize}; |
| | 4 | + |
| | 5 | +use crate::error::ConfigError; |
| | 6 | + |
| | 7 | +use super::MAX_JOBS; |
| | 8 | + |
| | 9 | +const MAX_MATRIX_VALUE_CHARS: usize = 64; |
| | 10 | + |
| | 11 | +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] |
| | 12 | +pub struct MatrixValue(pub String); |
| | 13 | + |
| | 14 | +impl Serialize for MatrixValue { |
| | 15 | + fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { |
| | 16 | + serializer.serialize_str(&self.0) |
| | 17 | + } |
| | 18 | +} |
| | 19 | + |
| | 20 | +impl<'de> Deserialize<'de> for MatrixValue { |
| | 21 | + fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { |
| | 22 | + #[derive(Deserialize)] |
| | 23 | + #[serde(untagged)] |
| | 24 | + enum Raw { |
| | 25 | + Text(String), |
| | 26 | + Int(i64), |
| | 27 | + Flag(bool), |
| | 28 | + } |
| | 29 | + Ok(MatrixValue(match Raw::deserialize(deserializer)? { |
| | 30 | + Raw::Text(text) => text, |
| | 31 | + Raw::Int(n) => n.to_string(), |
| | 32 | + Raw::Flag(b) => b.to_string(), |
| | 33 | + })) |
| | 34 | + } |
| | 35 | +} |
| | 36 | + |
| | 37 | +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] |
| | 38 | +pub struct MatrixSpec { |
| | 39 | + #[serde(default)] |
| | 40 | + pub exclude: Vec<BTreeMap<String, MatrixValue>>, |
| | 41 | + #[serde(default)] |
| | 42 | + pub include: Vec<BTreeMap<String, MatrixValue>>, |
| | 43 | + #[serde(flatten)] |
| | 44 | + pub axes: BTreeMap<String, Vec<MatrixValue>>, |
| | 45 | +} |
| | 46 | + |
| | 47 | +fn is_matrix_key(key: &str) -> bool { |
| | 48 | + let Some((first, rest)) = key.as_bytes().split_first() else { |
| | 49 | + return false; |
| | 50 | + }; |
| | 51 | + rest.len() <= 31 |
| | 52 | + && first.is_ascii_lowercase() |
| | 53 | + && rest |
| | 54 | + .iter() |
| | 55 | + .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || *b == b'_') |
| | 56 | +} |
| | 57 | + |
| | 58 | +type Combination = (String, BTreeMap<String, String>); |
| | 59 | + |
| | 60 | +pub(super) fn combinations( |
| | 61 | + job: &str, |
| | 62 | + matrix: &MatrixSpec, |
| | 63 | +) -> Result<Vec<Combination>, ConfigError> { |
| | 64 | + let bad = |reason: String| ConfigError::InvalidMatrix { |
| | 65 | + job: job.to_string(), |
| | 66 | + reason, |
| | 67 | + }; |
| | 68 | + if matrix.axes.is_empty() { |
| | 69 | + return Err(bad( |
| | 70 | + "needs at least one axis, e.g. rust = [\"stable\"]".into() |
| | 71 | + )); |
| | 72 | + } |
| | 73 | + let mut total: usize = 1; |
| | 74 | + for (key, values) in &matrix.axes { |
| | 75 | + if !is_matrix_key(key) { |
| | 76 | + return Err(bad(format!( |
| | 77 | + "axis name {key:?} must match ^[a-z][a-z0-9_]{{0,31}}$" |
| | 78 | + ))); |
| | 79 | + } |
| | 80 | + if values.is_empty() { |
| | 81 | + return Err(bad(format!("axis {key:?} has no values"))); |
| | 82 | + } |
| | 83 | + for (i, value) in values.iter().enumerate() { |
| | 84 | + validate_matrix_value(&value.0).map_err(|r| bad(format!("axis {key:?}: {r}")))?; |
| | 85 | + if values[..i].contains(value) { |
| | 86 | + return Err(bad(format!("axis {key:?} lists {:?} twice", value.0))); |
| | 87 | + } |
| | 88 | + } |
| | 89 | + total = total.saturating_mul(values.len()); |
| | 90 | + if total > MAX_JOBS { |
| | 91 | + return Err(ConfigError::MatrixTooLarge { |
| | 92 | + job: job.to_string(), |
| | 93 | + count: total, |
| | 94 | + max: MAX_JOBS, |
| | 95 | + }); |
| | 96 | + } |
| | 97 | + } |
| | 98 | + let mut combos: Vec<BTreeMap<String, String>> = vec![BTreeMap::new()]; |
| | 99 | + for (key, values) in &matrix.axes { |
| | 100 | + combos = combos |
| | 101 | + .into_iter() |
| | 102 | + .flat_map(|base| { |
| | 103 | + values.iter().map(move |value| { |
| | 104 | + let mut next = base.clone(); |
| | 105 | + next.insert(key.clone(), value.0.clone()); |
| | 106 | + next |
| | 107 | + }) |
| | 108 | + }) |
| | 109 | + .collect(); |
| | 110 | + } |
| | 111 | + for entry in &matrix.exclude { |
| | 112 | + for key in entry.keys() { |
| | 113 | + if !matrix.axes.contains_key(key) { |
| | 114 | + return Err(bad(format!("exclude names {key:?}, which is not an axis"))); |
| | 115 | + } |
| | 116 | + } |
| | 117 | + combos.retain(|combo| !entry.iter().all(|(k, v)| combo.get(k) == Some(&v.0))); |
| | 118 | + } |
| | 119 | + for entry in &matrix.include { |
| | 120 | + let mut combo = BTreeMap::new(); |
| | 121 | + for (key, value) in entry { |
| | 122 | + if !is_matrix_key(key) { |
| | 123 | + return Err(bad(format!( |
| | 124 | + "include key {key:?} must match ^[a-z][a-z0-9_]{{0,31}}$" |
| | 125 | + ))); |
| | 126 | + } |
| | 127 | + validate_matrix_value(&value.0).map_err(|r| bad(format!("include {key:?}: {r}")))?; |
| | 128 | + combo.insert(key.clone(), value.0.clone()); |
| | 129 | + } |
| | 130 | + if let Some(missing) = matrix.axes.keys().find(|k| !combo.contains_key(*k)) { |
| | 131 | + return Err(bad(format!("an include entry must set axis {missing:?}"))); |
| | 132 | + } |
| | 133 | + let same_axes = |other: &BTreeMap<String, String>| { |
| | 134 | + matrix.axes.keys().all(|k| other.get(k) == combo.get(k)) |
| | 135 | + }; |
| | 136 | + if !combos.iter().any(same_axes) { |
| | 137 | + combos.push(combo); |
| | 138 | + } |
| | 139 | + } |
| | 140 | + if combos.is_empty() { |
| | 141 | + return Err(bad("exclude removes every combination".into())); |
| | 142 | + } |
| | 143 | + if combos.len() > MAX_JOBS { |
| | 144 | + return Err(ConfigError::MatrixTooLarge { |
| | 145 | + job: job.to_string(), |
| | 146 | + count: combos.len(), |
| | 147 | + max: MAX_JOBS, |
| | 148 | + }); |
| | 149 | + } |
| | 150 | + Ok(combos |
| | 151 | + .into_iter() |
| | 152 | + .map(|combo| { |
| | 153 | + let suffix = matrix |
| | 154 | + .axes |
| | 155 | + .keys() |
| | 156 | + .filter_map(|k| combo.get(k).map(String::as_str)) |
| | 157 | + .collect::<Vec<_>>() |
| | 158 | + .join(", "); |
| | 159 | + (suffix, combo) |
| | 160 | + }) |
| | 161 | + .collect()) |
| | 162 | +} |
| | 163 | + |
| | 164 | +fn validate_matrix_value(value: &str) -> Result<(), String> { |
| | 165 | + if value.is_empty() { |
| | 166 | + return Err("values must not be empty".into()); |
| | 167 | + } |
| | 168 | + if value.chars().count() > MAX_MATRIX_VALUE_CHARS { |
| | 169 | + return Err(format!( |
| | 170 | + "values must be at most {MAX_MATRIX_VALUE_CHARS} characters" |
| | 171 | + )); |
| | 172 | + } |
| | 173 | + if value |
| | 174 | + .chars() |
| | 175 | + .any(|c| c.is_control() || matches!(c, ',' | '(' | ')')) |
| | 176 | + { |
| | 177 | + return Err(format!( |
| | 178 | + "{value:?} must not contain control characters, commas or parentheses" |
| | 179 | + )); |
| | 180 | + } |
| | 181 | + Ok(()) |
| | 182 | +} |
| | 183 | + |
| | 184 | +pub(super) fn interpolate( |
| | 185 | + job: &str, |
| | 186 | + text: &str, |
| | 187 | + vars: &BTreeMap<String, String>, |
| | 188 | +) -> Result<String, ConfigError> { |
| | 189 | + let mut out = String::with_capacity(text.len()); |
| | 190 | + let mut rest = text; |
| | 191 | + while let Some(at) = rest.find("${") { |
| | 192 | + out.push_str(&rest[..at]); |
| | 193 | + let after = &rest[at + 2..]; |
| | 194 | + let found = if let Some(body) = after.strip_prefix('{') { |
| | 195 | + body.find("}}") |
| | 196 | + .map(|end| (body[..end].trim(), &body[end + 2..])) |
| | 197 | + } else { |
| | 198 | + after |
| | 199 | + .find('}') |
| | 200 | + .map(|end| (after[..end].trim(), &after[end + 1..])) |
| | 201 | + }; |
| | 202 | + match found.and_then(|(inner, tail)| Some((inner.strip_prefix("matrix.")?, tail))) { |
| | 203 | + Some((key, tail)) => { |
| | 204 | + let value = vars.get(key).ok_or_else(|| ConfigError::InvalidMatrix { |
| | 205 | + job: job.to_string(), |
| | 206 | + reason: format!("`matrix.{key}` is not an axis or include key"), |
| | 207 | + })?; |
| | 208 | + out.push_str(value); |
| | 209 | + rest = tail; |
| | 210 | + } |
| | 211 | + None => { |
| | 212 | + out.push_str("${"); |
| | 213 | + rest = after; |
| | 214 | + } |
| | 215 | + } |
| | 216 | + } |
| | 217 | + out.push_str(rest); |
| | 218 | + Ok(out) |
| | 219 | +} |
| | 220 | + |
| | 221 | +#[cfg(test)] |
| | 222 | +mod tests { |
| | 223 | + use super::*; |
| | 224 | + use crate::config::parse_config; |
| | 225 | + use crate::config::tests::err_of; |
| | 226 | + |
| | 227 | + fn matrix_toml(matrix: &str, extra: &str) -> String { |
| | 228 | + format!( |
| | 229 | + "[jobs.test]\nimage = \"rust:${{{{ matrix.rust }}}}\"\nrun = \"cargo +${{matrix.rust}} test --target $MATRIX_TARGET\"\nruns_on = [\"${{{{ matrix.target }}}}\"]\nmatrix = {matrix}\n{extra}\n" |
| | 230 | + ) |
| | 231 | + } |
| | 232 | + |
| | 233 | + const GRID: &str = r#"{ rust = ["stable", "1.85"], target = ["x86_64", "aarch64"] }"#; |
| | 234 | + |
| | 235 | + #[test] |
| | 236 | + fn a_matrix_expands_into_named_jobs() { |
| | 237 | + let cfg = parse_config(&matrix_toml(GRID, "")).unwrap(); |
| | 238 | + let names: Vec<&str> = cfg.jobs.keys().map(String::as_str).collect(); |
| | 239 | + assert_eq!( |
| | 240 | + names, |
| | 241 | + [ |
| | 242 | + "test (1.85, aarch64)", |
| | 243 | + "test (1.85, x86_64)", |
| | 244 | + "test (stable, aarch64)", |
| | 245 | + "test (stable, x86_64)" |
| | 246 | + ] |
| | 247 | + ); |
| | 248 | + let job = &cfg.jobs["test (stable, x86_64)"]; |
| | 249 | + assert_eq!(job.image, "rust:stable"); |
| | 250 | + assert_eq!(job.run, "cargo +stable test --target $MATRIX_TARGET"); |
| | 251 | + assert_eq!(job.runs_on, vec!["x86_64".to_string()]); |
| | 252 | + assert_eq!(job.env["MATRIX_RUST"], "stable"); |
| | 253 | + assert_eq!(job.env["MATRIX_TARGET"], "x86_64"); |
| | 254 | + assert!(job.matrix.is_none()); |
| | 255 | + } |
| | 256 | + |
| | 257 | + #[test] |
| | 258 | + fn matrix_exclude_and_include() { |
| | 259 | + let m = r#"{ rust = ["stable", "1.85"], target = ["x86_64", "aarch64"], exclude = [{ rust = "1.85", target = "aarch64" }], include = [{ rust = "nightly", target = "x86_64", flag = "-Z" }] }"#; |
| | 260 | + let cfg = parse_config(&matrix_toml(m, "")).unwrap(); |
| | 261 | + assert_eq!(cfg.jobs.len(), 4); |
| | 262 | + assert!(!cfg.jobs.contains_key("test (1.85, aarch64)")); |
| | 263 | + let extra = &cfg.jobs["test (nightly, x86_64)"]; |
| | 264 | + assert_eq!(extra.env["MATRIX_FLAG"], "-Z"); |
| | 265 | + let m = |
| | 266 | + r#"{ rust = ["stable", "1.85"], target = ["x86_64"], exclude = [{ rust = "1.85" }] }"#; |
| | 267 | + let cfg = parse_config(&matrix_toml(m, "")).unwrap(); |
| | 268 | + assert_eq!( |
| | 269 | + cfg.jobs.keys().collect::<Vec<_>>(), |
| | 270 | + ["test (stable, x86_64)"] |
| | 271 | + ); |
| | 272 | + let m = r#"{ rust = ["stable"], target = ["x86_64"], include = [{ rust = "stable", target = "x86_64" }] }"#; |
| | 273 | + assert_eq!(parse_config(&matrix_toml(m, "")).unwrap().jobs.len(), 1); |
| | 274 | + } |
| | 275 | + |
| | 276 | + #[test] |
| | 277 | + fn needs_on_a_matrix_job_waits_for_every_combination() { |
| | 278 | + let text = format!( |
| | 279 | + "{}\n[jobs.ship]\nimage = \"img\"\nrun = \"true\"\nneeds = [\"test\"]\n", |
| | 280 | + matrix_toml(GRID, "") |
| | 281 | + ); |
| | 282 | + let cfg = parse_config(&text).unwrap(); |
| | 283 | + assert_eq!(cfg.jobs["ship"].needs.len(), 4); |
| | 284 | + let order = cfg.job_order(); |
| | 285 | + assert_eq!(order.last(), Some(&"ship")); |
| | 286 | + let text = format!( |
| | 287 | + "[jobs.setup]\nimage = \"img\"\nrun = \"true\"\n{}", |
| | 288 | + matrix_toml(GRID, "needs = [\"setup\"]") |
| | 289 | + ); |
| | 290 | + let cfg = parse_config(&text).unwrap(); |
| | 291 | + assert_eq!(cfg.jobs["test (stable, x86_64)"].needs, ["setup"]); |
| | 292 | + } |
| | 293 | + |
| | 294 | + #[test] |
| | 295 | + fn matrix_errors_are_clear() { |
| | 296 | + let big = r#"{ a = [1,2,3,4,5], b = [1,2,3,4,5] }"#; |
| | 297 | + let text = format!("[jobs.t]\nimage = \"i\"\nrun = \"x\"\nmatrix = {big}\n"); |
| | 298 | + let e = err_of(&text); |
| | 299 | + assert_eq!( |
| | 300 | + e, |
| | 301 | + ConfigError::MatrixTooLarge { |
| | 302 | + job: "t".into(), |
| | 303 | + count: 25, |
| | 304 | + max: MAX_JOBS |
| | 305 | + } |
| | 306 | + ); |
| | 307 | + assert!(e.to_string().contains("limit is 20")); |
| | 308 | + let mut text = String::new(); |
| | 309 | + for i in 0..MAX_JOBS - 1 { |
| | 310 | + text.push_str(&format!("[jobs.j{i}]\nimage = \"img\"\nrun = \"true\"\n")); |
| | 311 | + } |
| | 312 | + text.push_str("[jobs.m]\nimage = \"i\"\nrun = \"x\"\nmatrix = { a = [1, 2] }\n"); |
| | 313 | + assert!(matches!(err_of(&text), ConfigError::TooManyJobs { .. })); |
| | 314 | + for bad in [ |
| | 315 | + "{}", |
| | 316 | + "{ a = [] }", |
| | 317 | + "{ a = [\"x\", \"x\"] }", |
| | 318 | + "{ A = [\"x\"] }", |
| | 319 | + "{ a = [\"x,y\"] }", |
| | 320 | + "{ a = [\"x\"], exclude = [{ b = \"1\" }] }", |
| | 321 | + "{ a = [\"x\"], exclude = [{ a = \"x\" }] }", |
| | 322 | + "{ a = [\"x\"], include = [{ b = \"1\" }] }", |
| | 323 | + ] { |
| | 324 | + let text = format!("[jobs.t]\nimage = \"i\"\nrun = \"x\"\nmatrix = {bad}\n"); |
| | 325 | + assert!( |
| | 326 | + matches!(err_of(&text), ConfigError::InvalidMatrix { .. }), |
| | 327 | + "{bad}" |
| | 328 | + ); |
| | 329 | + } |
| | 330 | + let text = |
| | 331 | + "[jobs.t]\nimage = \"i\"\nrun = \"echo ${matrix.nope}\"\nmatrix = { a = [\"x\"] }\n"; |
| | 332 | + assert!(matches!(err_of(text), ConfigError::InvalidMatrix { .. })); |
| | 333 | + let text = "[jobs.\"t (x)\"]\nimage = \"i\"\nrun = \"x\"\n"; |
| | 334 | + assert!(matches!(err_of(text), ConfigError::InvalidJobName(_))); |
| | 335 | + } |
| | 336 | + |
| | 337 | + #[test] |
| | 338 | + fn shell_variables_are_left_alone() { |
| | 339 | + let text = "[jobs.t]\nimage = \"i\"\nrun = \"echo ${HOME} ${{ secrets.X }} ${matrix.a}\"\nmatrix = { a = [\"x\"] }\n"; |
| | 340 | + let cfg = parse_config(text).unwrap(); |
| | 341 | + assert_eq!(cfg.jobs["t (x)"].run, "echo ${HOME} ${{ secrets.X }} x"); |
| | 342 | + } |
| | 343 | + |
| | 344 | + #[test] |
| | 345 | + fn release_assets_can_name_a_matrix_job() { |
| | 346 | + let text = format!( |
| | 347 | + "[on]\ntags = [\"v*\"]\n[release]\nassets = [\"test:*.tar\"]\n{}", |
| | 348 | + matrix_toml(GRID, "artifacts = [\"out/a.tar\"]") |
| | 349 | + ); |
| | 350 | + let cfg = parse_config(&text).unwrap(); |
| | 351 | + let release = cfg.release.unwrap(); |
| | 352 | + assert!(release.asset_matches("test (stable, x86_64)", "a.tar")); |
| | 353 | + assert!(!release.asset_matches("testing", "a.tar")); |
| | 354 | + } |
| | 355 | +} |
| @@ -0,0 +1,69 @@ |
| | 1 | +use serde::{Deserialize, Deserializer}; |
| | 2 | + |
| | 3 | +pub(super) const MEMORY_RANGE_BYTES: std::ops::RangeInclusive<u64> = (64 << 20)..=(1024 << 30); |
| | 4 | + |
| | 5 | +pub(super) fn deserialize_memory<'de, D: Deserializer<'de>>(d: D) -> Result<Option<u64>, D::Error> { |
| | 6 | + #[derive(Deserialize)] |
| | 7 | + #[serde(untagged)] |
| | 8 | + enum Raw { |
| | 9 | + Bytes(u64), |
| | 10 | + Text(String), |
| | 11 | + } |
| | 12 | + match Option::<Raw>::deserialize(d)? { |
| | 13 | + None => Ok(None), |
| | 14 | + Some(Raw::Bytes(n)) => Ok(Some(n)), |
| | 15 | + Some(Raw::Text(text)) => crate::size::parse_size(&text).map(Some).ok_or_else(|| { |
| | 16 | + serde::de::Error::custom(format!( |
| | 17 | + "memory must be a size such as 4g or 512m, got {text:?}" |
| | 18 | + )) |
| | 19 | + }), |
| | 20 | + } |
| | 21 | +} |
| | 22 | + |
| | 23 | +#[cfg(test)] |
| | 24 | +mod tests { |
| | 25 | + use crate::config::tests::{err_of, job_toml}; |
| | 26 | + use crate::config::{JobSpec, parse_config}; |
| | 27 | + use crate::error::ConfigError; |
| | 28 | + |
| | 29 | + #[test] |
| | 30 | + fn memory_is_parsed_to_bytes() { |
| | 31 | + let cfg = parse_config(&job_toml("memory = \"4g\"")).unwrap(); |
| | 32 | + assert_eq!(cfg.jobs["build"].memory, Some(4 << 30)); |
| | 33 | + let cfg = parse_config(&job_toml("memory = \"512M\"")).unwrap(); |
| | 34 | + assert_eq!(cfg.jobs["build"].memory, Some(512 << 20)); |
| | 35 | + assert_eq!( |
| | 36 | + parse_config(&job_toml("")).unwrap().jobs["build"].memory, |
| | 37 | + None |
| | 38 | + ); |
| | 39 | + let job = &parse_config(&job_toml("memory = \"4g\"")).unwrap().jobs["build"]; |
| | 40 | + let json = serde_json::to_string(job).unwrap(); |
| | 41 | + assert!(json.contains("\"memory\":4294967296"), "{json}"); |
| | 42 | + let back: JobSpec = serde_json::from_str(&json).unwrap(); |
| | 43 | + assert_eq!(back.memory, Some(4 << 30)); |
| | 44 | + let old = json.replace(",\"memory\":4294967296", ""); |
| | 45 | + assert_eq!(serde_json::from_str::<JobSpec>(&old).unwrap().memory, None); |
| | 46 | + } |
| | 47 | + |
| | 48 | + #[test] |
| | 49 | + fn bad_memory_is_an_error() { |
| | 50 | + for bad in ["\"lots\"", "\"0\"", "\"-1g\"", "true"] { |
| | 51 | + assert!( |
| | 52 | + matches!( |
| | 53 | + err_of(&job_toml(&format!("memory = {bad}"))), |
| | 54 | + ConfigError::Toml(_) |
| | 55 | + ), |
| | 56 | + "{bad}" |
| | 57 | + ); |
| | 58 | + } |
| | 59 | + for bad in ["\"1m\"", "\"2t\""] { |
| | 60 | + assert!( |
| | 61 | + matches!( |
| | 62 | + err_of(&job_toml(&format!("memory = {bad}"))), |
| | 63 | + ConfigError::InvalidMemory { .. } |
| | 64 | + ), |
| | 65 | + "{bad}" |
| | 66 | + ); |
| | 67 | + } |
| | 68 | + } |
| | 69 | +} |
| @@ -0,0 +1,369 @@ |
| | 1 | +use std::collections::BTreeMap; |
| | 2 | + |
| | 3 | +use serde::{Deserialize, Serialize}; |
| | 4 | + |
| | 5 | +use crate::error::ConfigError; |
| | 6 | + |
| | 7 | +use super::trigger::{build_glob, matches_any}; |
| | 8 | +use super::{JobSpec, Triggers, names_job}; |
| | 9 | + |
| | 10 | +const MAX_RELEASE_ASSETS: usize = 32; |
| | 11 | +const MAX_RELEASE_TITLE_CHARS: usize = 200; |
| | 12 | + |
| | 13 | +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| | 14 | +#[serde(default)] |
| | 15 | +pub struct ReleaseSpec { |
| | 16 | + pub assets: Vec<String>, |
| | 17 | + pub prerelease: Prerelease, |
| | 18 | + pub draft: bool, |
| | 19 | + pub notes: ReleaseNotes, |
| | 20 | + pub title: String, |
| | 21 | +} |
| | 22 | + |
| | 23 | +impl Default for ReleaseSpec { |
| | 24 | + fn default() -> Self { |
| | 25 | + Self { |
| | 26 | + assets: Vec::new(), |
| | 27 | + prerelease: Prerelease::Auto, |
| | 28 | + draft: false, |
| | 29 | + notes: ReleaseNotes::Commits, |
| | 30 | + title: "{tag}".to_string(), |
| | 31 | + } |
| | 32 | + } |
| | 33 | +} |
| | 34 | + |
| | 35 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| | 36 | +pub enum Prerelease { |
| | 37 | + Auto, |
| | 38 | + Always, |
| | 39 | + Never, |
| | 40 | +} |
| | 41 | + |
| | 42 | +impl Serialize for Prerelease { |
| | 43 | + fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { |
| | 44 | + match self { |
| | 45 | + Prerelease::Auto => serializer.serialize_str("auto"), |
| | 46 | + Prerelease::Always => serializer.serialize_bool(true), |
| | 47 | + Prerelease::Never => serializer.serialize_bool(false), |
| | 48 | + } |
| | 49 | + } |
| | 50 | +} |
| | 51 | + |
| | 52 | +impl<'de> Deserialize<'de> for Prerelease { |
| | 53 | + fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { |
| | 54 | + #[derive(Deserialize)] |
| | 55 | + #[serde(untagged)] |
| | 56 | + enum Raw { |
| | 57 | + Flag(bool), |
| | 58 | + Text(String), |
| | 59 | + } |
| | 60 | + match Raw::deserialize(deserializer)? { |
| | 61 | + Raw::Flag(true) => Ok(Prerelease::Always), |
| | 62 | + Raw::Flag(false) => Ok(Prerelease::Never), |
| | 63 | + Raw::Text(text) if text == "auto" => Ok(Prerelease::Auto), |
| | 64 | + Raw::Text(text) => Err(serde::de::Error::custom(format!( |
| | 65 | + "prerelease must be \"auto\", true or false, got {text:?}" |
| | 66 | + ))), |
| | 67 | + } |
| | 68 | + } |
| | 69 | +} |
| | 70 | + |
| | 71 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] |
| | 72 | +#[serde(rename_all = "lowercase")] |
| | 73 | +pub enum ReleaseNotes { |
| | 74 | + Commits, |
| | 75 | + #[serde(rename = "none")] |
| | 76 | + Off, |
| | 77 | +} |
| | 78 | + |
| | 79 | +impl ReleaseSpec { |
| | 80 | + pub fn is_prerelease(&self, tag: &str) -> bool { |
| | 81 | + match self.prerelease { |
| | 82 | + Prerelease::Auto => tag.contains('-'), |
| | 83 | + Prerelease::Always => true, |
| | 84 | + Prerelease::Never => false, |
| | 85 | + } |
| | 86 | + } |
| | 87 | + |
| | 88 | + pub fn title_for(&self, tag: &str) -> String { |
| | 89 | + self.title.trim().replace("{tag}", tag) |
| | 90 | + } |
| | 91 | + |
| | 92 | + pub fn asset_matches(&self, job: &str, artifact_name: &str) -> bool { |
| | 93 | + self.assets.iter().any(|asset| { |
| | 94 | + asset_selector(asset).is_some_and(|(selected_job, glob)| { |
| | 95 | + names_job(selected_job, job) && matches_any(&[glob.to_string()], artifact_name) |
| | 96 | + }) |
| | 97 | + }) |
| | 98 | + } |
| | 99 | +} |
| | 100 | + |
| | 101 | +fn asset_selector(asset: &str) -> Option<(&str, &str)> { |
| | 102 | + asset.split_once(':') |
| | 103 | +} |
| | 104 | + |
| | 105 | +pub(super) fn validate_release( |
| | 106 | + release: &ReleaseSpec, |
| | 107 | + on: &Triggers, |
| | 108 | + jobs: &BTreeMap<String, JobSpec>, |
| | 109 | +) -> Result<(), ConfigError> { |
| | 110 | + if on.tags.is_empty() { |
| | 111 | + return Err(ConfigError::ReleaseWithoutTags); |
| | 112 | + } |
| | 113 | + if release.assets.len() > MAX_RELEASE_ASSETS { |
| | 114 | + return Err(ConfigError::TooManyReleaseAssets { |
| | 115 | + count: release.assets.len(), |
| | 116 | + max: MAX_RELEASE_ASSETS, |
| | 117 | + }); |
| | 118 | + } |
| | 119 | + for asset in &release.assets { |
| | 120 | + validate_release_asset(asset, jobs)?; |
| | 121 | + } |
| | 122 | + validate_release_title(&release.title) |
| | 123 | +} |
| | 124 | + |
| | 125 | +fn validate_release_asset( |
| | 126 | + asset: &str, |
| | 127 | + jobs: &BTreeMap<String, JobSpec>, |
| | 128 | +) -> Result<(), ConfigError> { |
| | 129 | + let invalid = |reason: String| ConfigError::InvalidReleaseAsset { |
| | 130 | + asset: asset.to_string(), |
| | 131 | + reason, |
| | 132 | + }; |
| | 133 | + let Some((job, glob)) = asset_selector(asset) else { |
| | 134 | + return Err(invalid("must be \"job:glob\"".into())); |
| | 135 | + }; |
| | 136 | + let Some((_, spec)) = jobs.iter().find(|(name, _)| names_job(job, name)) else { |
| | 137 | + return Err(invalid(format!("job {job:?} is not defined"))); |
| | 138 | + }; |
| | 139 | + if spec.artifacts.is_empty() { |
| | 140 | + return Err(invalid(format!("job {job:?} declares no artifacts"))); |
| | 141 | + } |
| | 142 | + if glob.is_empty() { |
| | 143 | + return Err(invalid("glob must not be empty".into())); |
| | 144 | + } |
| | 145 | + if glob.contains('/') { |
| | 146 | + return Err(invalid( |
| | 147 | + "glob must not contain \"/\", artifact names are flattened".into(), |
| | 148 | + )); |
| | 149 | + } |
| | 150 | + build_glob(glob) |
| | 151 | + .map(|_| ()) |
| | 152 | + .map_err(|e| invalid(e.to_string())) |
| | 153 | +} |
| | 154 | + |
| | 155 | +fn validate_release_title(title: &str) -> Result<(), ConfigError> { |
| | 156 | + let invalid = |reason: String| ConfigError::InvalidReleaseTitle(reason); |
| | 157 | + if title.trim().is_empty() { |
| | 158 | + return Err(invalid("must not be empty".into())); |
| | 159 | + } |
| | 160 | + if title.trim().chars().count() > MAX_RELEASE_TITLE_CHARS { |
| | 161 | + return Err(invalid(format!( |
| | 162 | + "must be at most {MAX_RELEASE_TITLE_CHARS} characters" |
| | 163 | + ))); |
| | 164 | + } |
| | 165 | + if title.chars().any(char::is_control) { |
| | 166 | + return Err(invalid("must not contain control characters".into())); |
| | 167 | + } |
| | 168 | + Ok(()) |
| | 169 | +} |
| | 170 | + |
| | 171 | +#[cfg(test)] |
| | 172 | +mod tests { |
| | 173 | + use super::*; |
| | 174 | + use crate::config::tests::{err_of, job_toml}; |
| | 175 | + use crate::config::{Event, parse_config}; |
| | 176 | + |
| | 177 | + fn release_toml(release: &str) -> String { |
| | 178 | + format!( |
| | 179 | + "[on]\ntags = [\"v*\"]\n{}\n[release]\n{release}\n", |
| | 180 | + job_toml("artifacts = [\"dist/*\"]") |
| | 181 | + ) |
| | 182 | + } |
| | 183 | + |
| | 184 | + fn release_of(text: &str) -> ReleaseSpec { |
| | 185 | + parse_config(text).unwrap().release.expect("release set") |
| | 186 | + } |
| | 187 | + |
| | 188 | + #[test] |
| | 189 | + fn release_defaults_apply() { |
| | 190 | + let release = release_of(&release_toml("")); |
| | 191 | + assert!(release.assets.is_empty()); |
| | 192 | + assert_eq!(release.prerelease, Prerelease::Auto); |
| | 193 | + assert!(!release.draft); |
| | 194 | + assert_eq!(release.notes, ReleaseNotes::Commits); |
| | 195 | + assert_eq!(release.title, "{tag}"); |
| | 196 | + assert_eq!(release, ReleaseSpec::default()); |
| | 197 | + } |
| | 198 | + |
| | 199 | + #[test] |
| | 200 | + fn release_full_table_parses() { |
| | 201 | + let text = release_toml( |
| | 202 | + "assets = [\"build:dist_*\", \"build:SHA256SUMS\"]\n\ |
| | 203 | + prerelease = true\ndraft = true\nnotes = \"none\"\ntitle = \"Release {tag}\"", |
| | 204 | + ); |
| | 205 | + let release = release_of(&text); |
| | 206 | + assert_eq!( |
| | 207 | + release.assets, |
| | 208 | + vec!["build:dist_*".to_string(), "build:SHA256SUMS".to_string()] |
| | 209 | + ); |
| | 210 | + assert_eq!(release.prerelease, Prerelease::Always); |
| | 211 | + assert!(release.draft); |
| | 212 | + assert_eq!(release.notes, ReleaseNotes::Off); |
| | 213 | + assert_eq!(release.title, "Release {tag}"); |
| | 214 | + } |
| | 215 | + |
| | 216 | + #[test] |
| | 217 | + fn release_prerelease_and_notes_values() { |
| | 218 | + assert_eq!( |
| | 219 | + release_of(&release_toml("prerelease = \"auto\"")).prerelease, |
| | 220 | + Prerelease::Auto |
| | 221 | + ); |
| | 222 | + assert_eq!( |
| | 223 | + release_of(&release_toml("prerelease = false")).prerelease, |
| | 224 | + Prerelease::Never |
| | 225 | + ); |
| | 226 | + assert_eq!( |
| | 227 | + release_of(&release_toml("notes = \"commits\"")).notes, |
| | 228 | + ReleaseNotes::Commits |
| | 229 | + ); |
| | 230 | + for bad in ["prerelease = \"yes\"", "notes = \"all\""] { |
| | 231 | + assert!( |
| | 232 | + matches!(err_of(&release_toml(bad)), ConfigError::Toml(_)), |
| | 233 | + "{bad}" |
| | 234 | + ); |
| | 235 | + } |
| | 236 | + } |
| | 237 | + |
| | 238 | + #[test] |
| | 239 | + fn release_unknown_keys_are_ignored_with_a_warning() { |
| | 240 | + let cfg = parse_config(&release_toml("bogus = 1")).unwrap(); |
| | 241 | + assert_eq!(cfg.warnings.len(), 1); |
| | 242 | + assert!( |
| | 243 | + cfg.warnings[0].contains("`release.bogus`"), |
| | 244 | + "{:?}", |
| | 245 | + cfg.warnings |
| | 246 | + ); |
| | 247 | + assert!(cfg.release.is_some()); |
| | 248 | + } |
| | 249 | + |
| | 250 | + #[test] |
| | 251 | + fn release_requires_tags() { |
| | 252 | + let text = format!("[release]\n{}", job_toml("artifacts = [\"dist/*\"]")); |
| | 253 | + assert_eq!(err_of(&text), ConfigError::ReleaseWithoutTags); |
| | 254 | + } |
| | 255 | + |
| | 256 | + #[test] |
| | 257 | + fn release_asset_must_be_job_and_glob() { |
| | 258 | + for bad in ["build", ":dist_*", "build:", "ghost:dist_*", "build:a/b"] { |
| | 259 | + let text = release_toml(&format!("assets = [{bad:?}]")); |
| | 260 | + assert!( |
| | 261 | + matches!(err_of(&text), ConfigError::InvalidReleaseAsset { .. }), |
| | 262 | + "asset {bad:?} should be rejected: {:?}", |
| | 263 | + err_of(&text) |
| | 264 | + ); |
| | 265 | + } |
| | 266 | + let text = release_toml("assets = [\"build:[\"]"); |
| | 267 | + assert!(matches!( |
| | 268 | + err_of(&text), |
| | 269 | + ConfigError::InvalidReleaseAsset { .. } |
| | 270 | + )); |
| | 271 | + } |
| | 272 | + |
| | 273 | + #[test] |
| | 274 | + fn release_asset_job_must_declare_artifacts() { |
| | 275 | + let text = format!( |
| | 276 | + "[on]\ntags = [\"v*\"]\n{}\n[release]\nassets = [\"build:x\"]\n", |
| | 277 | + job_toml("") |
| | 278 | + ); |
| | 279 | + match err_of(&text) { |
| | 280 | + ConfigError::InvalidReleaseAsset { asset, reason } => { |
| | 281 | + assert_eq!(asset, "build:x"); |
| | 282 | + assert!(reason.contains("no artifacts"), "{reason}"); |
| | 283 | + } |
| | 284 | + other => panic!("unexpected error {other:?}"), |
| | 285 | + } |
| | 286 | + } |
| | 287 | + |
| | 288 | + #[test] |
| | 289 | + fn release_assets_are_capped() { |
| | 290 | + let entries: Vec<String> = (0..=MAX_RELEASE_ASSETS) |
| | 291 | + .map(|_| "build:dist_*".to_string()) |
| | 292 | + .collect(); |
| | 293 | + let text = release_toml(&format!("assets = {entries:?}")); |
| | 294 | + assert_eq!( |
| | 295 | + err_of(&text), |
| | 296 | + ConfigError::TooManyReleaseAssets { |
| | 297 | + count: MAX_RELEASE_ASSETS + 1, |
| | 298 | + max: MAX_RELEASE_ASSETS |
| | 299 | + } |
| | 300 | + ); |
| | 301 | + let text = release_toml(&format!("assets = {:?}", &entries[..MAX_RELEASE_ASSETS])); |
| | 302 | + assert!(parse_config(&text).is_ok()); |
| | 303 | + } |
| | 304 | + |
| | 305 | + #[test] |
| | 306 | + fn release_title_validation() { |
| | 307 | + for bad in ["", " ", "a\\u0007b"] { |
| | 308 | + let text = release_toml(&format!("title = \"{bad}\"")); |
| | 309 | + assert!( |
| | 310 | + matches!(err_of(&text), ConfigError::InvalidReleaseTitle(_)), |
| | 311 | + "title {bad:?} should be rejected" |
| | 312 | + ); |
| | 313 | + } |
| | 314 | + let over = "t".repeat(MAX_RELEASE_TITLE_CHARS + 1); |
| | 315 | + let text = release_toml(&format!("title = \"{over}\"")); |
| | 316 | + assert!(matches!(err_of(&text), ConfigError::InvalidReleaseTitle(_))); |
| | 317 | + let at_limit = "t".repeat(MAX_RELEASE_TITLE_CHARS); |
| | 318 | + assert!(parse_config(&release_toml(&format!("title = \"{at_limit}\""))).is_ok()); |
| | 319 | + } |
| | 320 | + |
| | 321 | + #[test] |
| | 322 | + fn release_title_for_fills_tag() { |
| | 323 | + assert_eq!(ReleaseSpec::default().title_for("v1.2.0"), "v1.2.0"); |
| | 324 | + let release = release_of(&release_toml("title = \"Release {tag}\"")); |
| | 325 | + assert_eq!(release.title_for("v1.2.0"), "Release v1.2.0"); |
| | 326 | + let fixed = release_of(&release_toml("title = \"Stable\"")); |
| | 327 | + assert_eq!(fixed.title_for("v1.2.0"), "Stable"); |
| | 328 | + } |
| | 329 | + |
| | 330 | + #[test] |
| | 331 | + fn release_prerelease_auto_logic() { |
| | 332 | + let auto = ReleaseSpec::default(); |
| | 333 | + assert!(auto.is_prerelease("v1.2.0-rc1")); |
| | 334 | + assert!(auto.is_prerelease("v2.0.0-beta.3")); |
| | 335 | + assert!(!auto.is_prerelease("v1.2.0")); |
| | 336 | + let always = release_of(&release_toml("prerelease = true")); |
| | 337 | + assert!(always.is_prerelease("v1.2.0")); |
| | 338 | + let never = release_of(&release_toml("prerelease = false")); |
| | 339 | + assert!(!never.is_prerelease("v1.2.0-rc1")); |
| | 340 | + } |
| | 341 | + |
| | 342 | + #[test] |
| | 343 | + fn release_asset_matching() { |
| | 344 | + let release = release_of(&release_toml( |
| | 345 | + "assets = [\"build:forge-*-linux-*\", \"build:SHA256SUMS\"]", |
| | 346 | + )); |
| | 347 | + assert!(release.asset_matches("build", "forge-1.2.0-linux-x86_64")); |
| | 348 | + assert!(release.asset_matches("build", "SHA256SUMS")); |
| | 349 | + assert!(!release.asset_matches("build", "forge-1.2.0-darwin-arm64")); |
| | 350 | + assert!(!release.asset_matches("build", "SHA256SUMS.sig")); |
| | 351 | + assert!(!release.asset_matches("lint", "SHA256SUMS")); |
| | 352 | + assert!(!ReleaseSpec::default().asset_matches("build", "SHA256SUMS")); |
| | 353 | + } |
| | 354 | + |
| | 355 | + #[test] |
| | 356 | + fn wants_release_only_for_matching_tags() { |
| | 357 | + let text = release_toml(""); |
| | 358 | + let cfg = parse_config(&text).unwrap(); |
| | 359 | + assert!(cfg.wants_release(&Event::Tag { tag: "v1.2.0" })); |
| | 360 | + assert!(!cfg.wants_release(&Event::Tag { tag: "release-1" })); |
| | 361 | + assert!(!cfg.wants_release(&Event::Push { branch: "main" })); |
| | 362 | + assert!(!cfg.wants_release(&Event::Manual)); |
| | 363 | + assert!(!cfg.wants_release(&Event::PullRequest)); |
| | 364 | + |
| | 365 | + let without = parse_config(&format!("[on]\ntags = [\"v*\"]\n{}", job_toml(""))).unwrap(); |
| | 366 | + assert!(without.release.is_none()); |
| | 367 | + assert!(!without.wants_release(&Event::Tag { tag: "v1.2.0" })); |
| | 368 | + } |
| | 369 | +} |
| @@ -0,0 +1,55 @@ |
| | 1 | +use crate::error::ConfigError; |
| | 2 | + |
| | 3 | +const MAX_SCHEDULES: usize = 8; |
| | 4 | + |
| | 5 | +pub(super) fn validate_schedules(exprs: &[String]) -> Result<(), ConfigError> { |
| | 6 | + if exprs.len() > MAX_SCHEDULES { |
| | 7 | + return Err(ConfigError::TooManySchedules { |
| | 8 | + count: exprs.len(), |
| | 9 | + max: MAX_SCHEDULES, |
| | 10 | + }); |
| | 11 | + } |
| | 12 | + for expr in exprs { |
| | 13 | + crate::cron::parse(expr).map_err(|reason| ConfigError::InvalidSchedule { |
| | 14 | + expr: expr.clone(), |
| | 15 | + reason, |
| | 16 | + })?; |
| | 17 | + } |
| | 18 | + Ok(()) |
| | 19 | +} |
| | 20 | + |
| | 21 | +#[cfg(test)] |
| | 22 | +mod tests { |
| | 23 | + use super::MAX_SCHEDULES; |
| | 24 | + use crate::config::Event; |
| | 25 | + use crate::config::parse_config; |
| | 26 | + use crate::config::tests::{err_of, job_toml}; |
| | 27 | + use crate::error::ConfigError; |
| | 28 | + |
| | 29 | + #[test] |
| | 30 | + fn schedule_is_parsed_and_validated() { |
| | 31 | + let cfg = parse_config(&format!( |
| | 32 | + "[on]\nschedule = [\"0 3 * * *\", \"*/15 * * * 1\"]\n{}", |
| | 33 | + job_toml("") |
| | 34 | + )) |
| | 35 | + .unwrap(); |
| | 36 | + assert_eq!(cfg.on.schedule.len(), 2); |
| | 37 | + assert!(cfg.warnings.is_empty()); |
| | 38 | + assert!(cfg.triggered_by(&Event::Schedule)); |
| | 39 | + let none = parse_config(&job_toml("")).unwrap(); |
| | 40 | + assert!(!none.triggered_by(&Event::Schedule)); |
| | 41 | + for bad in ["0 0 3 * * *", "nope", "70 3 * * *", ""] { |
| | 42 | + let text = format!("[on]\nschedule = [\"{bad}\"]\n{}", job_toml("")); |
| | 43 | + assert!( |
| | 44 | + matches!(err_of(&text), ConfigError::InvalidSchedule { .. }), |
| | 45 | + "{bad}" |
| | 46 | + ); |
| | 47 | + } |
| | 48 | + let many = ["\"0 3 * * *\""; MAX_SCHEDULES + 1].join(", "); |
| | 49 | + let text = format!("[on]\nschedule = [{many}]\n{}", job_toml("")); |
| | 50 | + assert!(matches!( |
| | 51 | + err_of(&text), |
| | 52 | + ConfigError::TooManySchedules { .. } |
| | 53 | + )); |
| | 54 | + } |
| | 55 | +} |
| @@ -0,0 +1,97 @@ |
| | 1 | +use globset::{Glob, GlobBuilder}; |
| | 2 | +use serde::{Deserialize, Serialize}; |
| | 3 | + |
| | 4 | +use crate::error::ConfigError; |
| | 5 | + |
| | 6 | +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| | 7 | +#[serde(default)] |
| | 8 | +pub struct Triggers { |
| | 9 | + pub push: Vec<String>, |
| | 10 | + pub tags: Vec<String>, |
| | 11 | + pub pull_request: bool, |
| | 12 | + pub manual: bool, |
| | 13 | + pub cancel_superseded: bool, |
| | 14 | + pub merge_queue: bool, |
| | 15 | + pub schedule: Vec<String>, |
| | 16 | +} |
| | 17 | + |
| | 18 | +impl Default for Triggers { |
| | 19 | + fn default() -> Self { |
| | 20 | + Self { |
| | 21 | + push: Vec::new(), |
| | 22 | + tags: Vec::new(), |
| | 23 | + pull_request: false, |
| | 24 | + manual: true, |
| | 25 | + cancel_superseded: true, |
| | 26 | + merge_queue: false, |
| | 27 | + schedule: Vec::new(), |
| | 28 | + } |
| | 29 | + } |
| | 30 | +} |
| | 31 | + |
| | 32 | +pub(super) fn matches_any(globs: &[String], value: &str) -> bool { |
| | 33 | + globs |
| | 34 | + .iter() |
| | 35 | + .any(|pattern| build_glob(pattern).is_ok_and(|g| g.compile_matcher().is_match(value))) |
| | 36 | +} |
| | 37 | + |
| | 38 | +pub(super) fn build_glob(pattern: &str) -> Result<Glob, globset::Error> { |
| | 39 | + GlobBuilder::new(pattern).literal_separator(true).build() |
| | 40 | +} |
| | 41 | + |
| | 42 | +pub(super) fn validate_trigger_glob(kind: &'static str, pattern: &str) -> Result<(), ConfigError> { |
| | 43 | + let invalid = |reason: String| ConfigError::InvalidTriggerGlob { |
| | 44 | + kind, |
| | 45 | + pattern: pattern.to_string(), |
| | 46 | + reason, |
| | 47 | + }; |
| | 48 | + if pattern.is_empty() { |
| | 49 | + return Err(invalid("pattern is empty".into())); |
| | 50 | + } |
| | 51 | + build_glob(pattern) |
| | 52 | + .map(|_| ()) |
| | 53 | + .map_err(|e| invalid(e.to_string())) |
| | 54 | +} |
| | 55 | + |
| | 56 | +#[cfg(test)] |
| | 57 | +mod tests { |
| | 58 | + use crate::config::tests::{err_of, job_toml}; |
| | 59 | + use crate::config::{Event, parse_config}; |
| | 60 | + use crate::error::ConfigError; |
| | 61 | + |
| | 62 | + #[test] |
| | 63 | + fn branch_and_tag_globs_match_only_their_event_kind() { |
| | 64 | + let text = format!("[on]\npush = [\"main\", \"release/*\"]\n{}", job_toml("")); |
| | 65 | + let cfg = parse_config(&text).unwrap(); |
| | 66 | + assert!(cfg.triggered_by(&Event::Push { branch: "main" })); |
| | 67 | + assert!(cfg.triggered_by(&Event::Push { |
| | 68 | + branch: "release/1.0" |
| | 69 | + })); |
| | 70 | + assert!(!cfg.triggered_by(&Event::Push { |
| | 71 | + branch: "release/1.0/x" |
| | 72 | + })); |
| | 73 | + assert!(!cfg.triggered_by(&Event::Push { branch: "mainx" })); |
| | 74 | + assert!(!cfg.triggered_by(&Event::Push { branch: "feature" })); |
| | 75 | + assert!(!cfg.triggered_by(&Event::Tag { tag: "v1" })); |
| | 76 | + |
| | 77 | + let text = format!("[on]\ntags = [\"v*\"]\n{}", job_toml("")); |
| | 78 | + let cfg = parse_config(&text).unwrap(); |
| | 79 | + assert!(cfg.triggered_by(&Event::Tag { tag: "v1.2.3" })); |
| | 80 | + assert!(!cfg.triggered_by(&Event::Tag { tag: "release-1" })); |
| | 81 | + assert!(!cfg.triggered_by(&Event::Push { branch: "v1" })); |
| | 82 | + } |
| | 83 | + |
| | 84 | + #[test] |
| | 85 | + fn invalid_trigger_globs_are_rejected() { |
| | 86 | + let text = format!("[on]\npush = [\"[\"]\n{}", job_toml("")); |
| | 87 | + assert!(matches!( |
| | 88 | + err_of(&text), |
| | 89 | + ConfigError::InvalidTriggerGlob { kind: "branch", .. } |
| | 90 | + )); |
| | 91 | + let text = format!("[on]\ntags = [\"\"]\n{}", job_toml("")); |
| | 92 | + assert!(matches!( |
| | 93 | + err_of(&text), |
| | 94 | + ConfigError::InvalidTriggerGlob { kind: "tag", .. } |
| | 95 | + )); |
| | 96 | + } |
| | 97 | +} |
| @@ -0,0 +1,72 @@ |
| | 1 | +use crate::error::ConfigError; |
| | 2 | + |
| | 3 | +const MAX_WORKFLOW_NAME_CHARS: usize = 40; |
| | 4 | + |
| | 5 | +pub(super) fn validate_workflow_name(name: &str) -> Result<(), ConfigError> { |
| | 6 | + let invalid = |reason: &str| ConfigError::InvalidWorkflowName { |
| | 7 | + name: name.to_string(), |
| | 8 | + reason: reason.to_string(), |
| | 9 | + }; |
| | 10 | + let trimmed = name.trim(); |
| | 11 | + if trimmed.is_empty() { |
| | 12 | + return Err(invalid("must not be empty")); |
| | 13 | + } |
| | 14 | + if trimmed.chars().count() > MAX_WORKFLOW_NAME_CHARS { |
| | 15 | + return Err(invalid(&format!( |
| | 16 | + "must be at most {MAX_WORKFLOW_NAME_CHARS} characters" |
| | 17 | + ))); |
| | 18 | + } |
| | 19 | + if trimmed.chars().any(char::is_control) { |
| | 20 | + return Err(invalid("must not contain control characters")); |
| | 21 | + } |
| | 22 | + Ok(()) |
| | 23 | +} |
| | 24 | + |
| | 25 | +#[cfg(test)] |
| | 26 | +mod tests { |
| | 27 | + use super::MAX_WORKFLOW_NAME_CHARS; |
| | 28 | + use crate::config::parse_config; |
| | 29 | + use crate::config::tests::{err_of, job_toml}; |
| | 30 | + use crate::error::ConfigError; |
| | 31 | + |
| | 32 | + #[test] |
| | 33 | + fn workflow_name_is_optional_and_kept() { |
| | 34 | + assert_eq!(parse_config(&job_toml("")).unwrap().name, None); |
| | 35 | + let cfg = parse_config(&format!("name = \"build\"\n{}", job_toml(""))).unwrap(); |
| | 36 | + assert_eq!(cfg.name.as_deref(), Some("build")); |
| | 37 | + } |
| | 38 | + |
| | 39 | + #[test] |
| | 40 | + fn workflow_name_must_be_one_non_blank_line() { |
| | 41 | + for text in [ |
| | 42 | + "name = \"\"", |
| | 43 | + "name = \" \"", |
| | 44 | + "name = \"a\\u0007b\"", |
| | 45 | + "name = \"a\\nb\"", |
| | 46 | + ] { |
| | 47 | + let err = err_of(&format!("{text}\n{}", job_toml(""))); |
| | 48 | + assert!( |
| | 49 | + matches!(err, ConfigError::InvalidWorkflowName { .. }), |
| | 50 | + "{text}: {err:?}" |
| | 51 | + ); |
| | 52 | + } |
| | 53 | + } |
| | 54 | + |
| | 55 | + #[test] |
| | 56 | + fn workflow_name_length_is_capped_after_trimming() { |
| | 57 | + let at_limit = "n".repeat(MAX_WORKFLOW_NAME_CHARS); |
| | 58 | + let ok = format!("name = \" {at_limit} \"\n{}", job_toml("")); |
| | 59 | + assert!(parse_config(&ok).is_ok()); |
| | 60 | + let over = "n".repeat(MAX_WORKFLOW_NAME_CHARS + 1); |
| | 61 | + let err = err_of(&format!("name = \"{over}\"\n{}", job_toml(""))); |
| | 62 | + assert!(matches!(err, ConfigError::InvalidWorkflowName { .. })); |
| | 63 | + } |
| | 64 | + |
| | 65 | + #[test] |
| | 66 | + fn workflow_name_must_be_a_string() { |
| | 67 | + assert!(matches!( |
| | 68 | + err_of(&format!("name = 3\n{}", job_toml(""))), |
| | 69 | + ConfigError::Toml(_) |
| | 70 | + )); |
| | 71 | + } |
| | 72 | +} |
| @@ -0,0 +1,2 @@ |
| | 1 | +ALTER TABLE ci_runners ADD COLUMN registered_labels TEXT NOT NULL DEFAULT '[]'; |
| | 2 | +UPDATE ci_runners SET registered_labels = COALESCE(json_extract(reported_config, '$.labels'), labels); |
| @@ -0,0 +1 @@ |
| | 1 | +UPDATE milestones SET title = title WHERE 0; |
| @@ -8,6 +8,62 @@ pub enum AlertKind { |
| 8 | Replication, | 8 | Replication, |
| 9 | } | 9 | } |
| 10 | | 10 | |
| | 11 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| | 12 | +pub enum AlertTopic { |
| | 13 | + RunnerOffline, |
| | 14 | + BackupFailed, |
| | 15 | + BackupVerifyFailed, |
| | 16 | + BackupOverdue, |
| | 17 | + FsckFailed, |
| | 18 | + DiskLow, |
| | 19 | + CiKilled, |
| | 20 | + SelfUpdateRestart, |
| | 21 | + SelfUpdateFailed, |
| | 22 | + Replication, |
| | 23 | +} |
| | 24 | + |
| | 25 | +impl AlertTopic { |
| | 26 | + pub const ALL: [Self; 10] = [ |
| | 27 | + Self::RunnerOffline, |
| | 28 | + Self::BackupFailed, |
| | 29 | + Self::BackupVerifyFailed, |
| | 30 | + Self::BackupOverdue, |
| | 31 | + Self::FsckFailed, |
| | 32 | + Self::DiskLow, |
| | 33 | + Self::CiKilled, |
| | 34 | + Self::SelfUpdateRestart, |
| | 35 | + Self::SelfUpdateFailed, |
| | 36 | + Self::Replication, |
| | 37 | + ]; |
| | 38 | + |
| | 39 | + pub fn kind(self) -> AlertKind { |
| | 40 | + match self { |
| | 41 | + Self::RunnerOffline => AlertKind::RunnerOffline, |
| | 42 | + Self::BackupFailed |
| | 43 | + | Self::BackupVerifyFailed |
| | 44 | + | Self::BackupOverdue |
| | 45 | + | Self::FsckFailed => AlertKind::Backup, |
| | 46 | + Self::DiskLow => AlertKind::Disk, |
| | 47 | + Self::CiKilled => AlertKind::CiKilled, |
| | 48 | + Self::SelfUpdateRestart | Self::SelfUpdateFailed => AlertKind::SelfUpdate, |
| | 49 | + Self::Replication => AlertKind::Replication, |
| | 50 | + } |
| | 51 | + } |
| | 52 | +} |
| | 53 | + |
| | 54 | +string_enum!(AlertTopic { |
| | 55 | + RunnerOffline = "runner_offline", |
| | 56 | + BackupFailed = "backup_failed", |
| | 57 | + BackupVerifyFailed = "backup_verify_failed", |
| | 58 | + BackupOverdue = "backup_overdue", |
| | 59 | + FsckFailed = "fsck_failed", |
| | 60 | + DiskLow = "disk_low", |
| | 61 | + CiKilled = "ci_killed", |
| | 62 | + SelfUpdateRestart = "self_update_restart", |
| | 63 | + SelfUpdateFailed = "self_update_failed", |
| | 64 | + Replication = "replication", |
| | 65 | +}); |
| | 66 | + |
| 11 | pub fn is_kill_signature(exit_code: Option<i64>, message: Option<&str>) -> bool { | 67 | pub fn is_kill_signature(exit_code: Option<i64>, message: Option<&str>) -> bool { |
| 12 | if matches!(exit_code, Some(137) | Some(-9)) { | 68 | if matches!(exit_code, Some(137) | Some(-9)) { |
| 13 | return true; | 69 | return true; |
| @@ -11,13 +11,9 @@ macro_rules! audit_actions { |
| 11 | | 11 | |
| 12 | impl AuditAction { | 12 | impl AuditAction { |
| 13 | pub const ALL: &'static [AuditAction] = &[$(AuditAction::$variant,)*]; | 13 | pub const ALL: &'static [AuditAction] = &[$(AuditAction::$variant,)*]; |
| 14 | - | | |
| 15 | - pub fn as_str(self) -> &'static str { | | |
| 16 | - match self { | | |
| 17 | - $(AuditAction::$variant => $name,)* | | |
| 18 | - } | | |
| 19 | - } | | |
| 20 | } | 14 | } |
| | 15 | + |
| | 16 | + string_enum!(AuditAction { $($variant = $name),* }); |
| 21 | }; | 17 | }; |
| 22 | } | 18 | } |
| 23 | | 19 | |
| @@ -130,15 +126,6 @@ audit_actions! { |
| 130 | PasskeyLogin => "passkey_login", | 126 | PasskeyLogin => "passkey_login", |
| 131 | } | 127 | } |
| 132 | | 128 | |
| 133 | -impl AuditAction { | | |
| 134 | - pub fn parse(name: &str) -> Option<AuditAction> { | | |
| 135 | - AuditAction::ALL | | |
| 136 | - .iter() | | |
| 137 | - .copied() | | |
| 138 | - .find(|action| action.as_str() == name) | | |
| 139 | - } | | |
| 140 | -} | | |
| 141 | - | | |
| 142 | #[derive(Debug, Clone, PartialEq, Eq)] | 129 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 143 | pub struct AuditEntry { | 130 | pub struct AuditEntry { |
| 144 | pub id: String, | 131 | pub id: String, |
| @@ -218,12 +205,12 @@ mod tests { |
| 218 | fn names_are_unique_and_round_trip() { | 205 | fn names_are_unique_and_round_trip() { |
| 219 | let mut names: Vec<&str> = AuditAction::ALL.iter().map(|a| a.as_str()).collect(); | 206 | let mut names: Vec<&str> = AuditAction::ALL.iter().map(|a| a.as_str()).collect(); |
| 220 | for action in AuditAction::ALL { | 207 | for action in AuditAction::ALL { |
| 221 | - assert_eq!(AuditAction::parse(action.as_str()), Some(*action)); | 208 | + assert_eq!(action.as_str().parse::<AuditAction>().ok(), Some(*action)); |
| 222 | } | 209 | } |
| 223 | names.sort(); | 210 | names.sort(); |
| 224 | names.dedup(); | 211 | names.dedup(); |
| 225 | assert_eq!(names.len(), AuditAction::ALL.len()); | 212 | assert_eq!(names.len(), AuditAction::ALL.len()); |
| 226 | - assert_eq!(AuditAction::parse("nope"), None); | 213 | + assert!("nope".parse::<AuditAction>().is_err()); |
| 227 | } | 214 | } |
| 228 | | 215 | |
| 229 | #[test] | 216 | #[test] |
| @@ -1,12 +1,9 @@ |
| 1 | use std::collections::BTreeMap; | 1 | use std::collections::BTreeMap; |
| 2 | -use std::str::FromStr; | | |
| 3 | | 2 | |
| 4 | use forge_ci::proto::{MAX_CONCURRENCY, MIN_CONCURRENCY}; | 3 | use forge_ci::proto::{MAX_CONCURRENCY, MIN_CONCURRENCY}; |
| 5 | | 4 | |
| 6 | pub use forge_ci::proto::RestartMode; | 5 | pub use forge_ci::proto::RestartMode; |
| 7 | | 6 | |
| 8 | -use crate::error::{Error, Result}; | | |
| 9 | - | | |
| 10 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] | 7 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 11 | pub enum RunState { | 8 | pub enum RunState { |
| 12 | WaitingApproval, | 9 | WaitingApproval, |
| @@ -18,19 +15,17 @@ pub enum RunState { |
| 18 | Error, | 15 | Error, |
| 19 | } | 16 | } |
| 20 | | 17 | |
| 21 | -impl RunState { | 18 | +string_enum!(RunState { |
| 22 | - pub fn as_str(self) -> &'static str { | 19 | + WaitingApproval = "waiting_approval", |
| 23 | - match self { | 20 | + Queued = "queued", |
| 24 | - RunState::WaitingApproval => "waiting_approval", | 21 | + Running = "running", |
| 25 | - RunState::Queued => "queued", | 22 | + Success = "success", |
| 26 | - RunState::Running => "running", | 23 | + Failure = "failure", |
| 27 | - RunState::Success => "success", | 24 | + Cancelled = "cancelled", |
| 28 | - RunState::Failure => "failure", | 25 | + Error = "error", |
| 29 | - RunState::Cancelled => "cancelled", | 26 | +}); |
| 30 | - RunState::Error => "error", | | |
| 31 | - } | | |
| 32 | - } | | |
| 33 | | 27 | |
| | 28 | +impl RunState { |
| 34 | pub fn is_terminal(self) -> bool { | 29 | pub fn is_terminal(self) -> bool { |
| 35 | matches!( | 30 | matches!( |
| 36 | self, | 31 | self, |
| @@ -39,23 +34,6 @@ impl RunState { |
| 39 | } | 34 | } |
| 40 | } | 35 | } |
| 41 | | 36 | |
| 42 | -impl FromStr for RunState { | | |
| 43 | - type Err = Error; | | |
| 44 | - | | |
| 45 | - fn from_str(s: &str) -> Result<Self> { | | |
| 46 | - Ok(match s { | | |
| 47 | - "waiting_approval" => RunState::WaitingApproval, | | |
| 48 | - "queued" => RunState::Queued, | | |
| 49 | - "running" => RunState::Running, | | |
| 50 | - "success" => RunState::Success, | | |
| 51 | - "failure" => RunState::Failure, | | |
| 52 | - "cancelled" => RunState::Cancelled, | | |
| 53 | - "error" => RunState::Error, | | |
| 54 | - other => return Err(Error::Database(format!("unknown CI run state {other:?}"))), | | |
| 55 | - }) | | |
| 56 | - } | | |
| 57 | -} | | |
| 58 | - | | |
| 59 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] | 37 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 60 | pub enum JobState { | 38 | pub enum JobState { |
| 61 | Blocked, | 39 | Blocked, |
| @@ -68,20 +46,18 @@ pub enum JobState { |
| 68 | Skipped, | 46 | Skipped, |
| 69 | } | 47 | } |
| 70 | | 48 | |
| 71 | -impl JobState { | 49 | +string_enum!(JobState { |
| 72 | - pub fn as_str(self) -> &'static str { | 50 | + Blocked = "blocked", |
| 73 | - match self { | 51 | + Queued = "queued", |
| 74 | - JobState::Blocked => "blocked", | 52 | + Running = "running", |
| 75 | - JobState::Queued => "queued", | 53 | + Success = "success", |
| 76 | - JobState::Running => "running", | 54 | + Failure = "failure", |
| 77 | - JobState::Success => "success", | 55 | + Cancelled = "cancelled", |
| 78 | - JobState::Failure => "failure", | 56 | + Error = "error", |
| 79 | - JobState::Cancelled => "cancelled", | 57 | + Skipped = "skipped", |
| 80 | - JobState::Error => "error", | 58 | +}); |
| 81 | - JobState::Skipped => "skipped", | | |
| 82 | - } | | |
| 83 | - } | | |
| 84 | | 59 | |
| | 60 | +impl JobState { |
| 85 | pub fn is_terminal(self) -> bool { | 61 | pub fn is_terminal(self) -> bool { |
| 86 | matches!( | 62 | matches!( |
| 87 | self, | 63 | self, |
| @@ -94,24 +70,6 @@ impl JobState { |
| 94 | } | 70 | } |
| 95 | } | 71 | } |
| 96 | | 72 | |
| 97 | -impl FromStr for JobState { | | |
| 98 | - type Err = Error; | | |
| 99 | - | | |
| 100 | - fn from_str(s: &str) -> Result<Self> { | | |
| 101 | - Ok(match s { | | |
| 102 | - "blocked" => JobState::Blocked, | | |
| 103 | - "queued" => JobState::Queued, | | |
| 104 | - "running" => JobState::Running, | | |
| 105 | - "success" => JobState::Success, | | |
| 106 | - "failure" => JobState::Failure, | | |
| 107 | - "cancelled" => JobState::Cancelled, | | |
| 108 | - "error" => JobState::Error, | | |
| 109 | - "skipped" => JobState::Skipped, | | |
| 110 | - other => return Err(Error::Database(format!("unknown CI job state {other:?}"))), | | |
| 111 | - }) | | |
| 112 | - } | | |
| 113 | -} | | |
| 114 | - | | |
| 115 | #[derive(Debug, Clone, PartialEq, Eq)] | 73 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 116 | pub struct CiRunner { | 74 | pub struct CiRunner { |
| 117 | pub id: String, | 75 | pub id: String, |
| @@ -6,14 +6,21 @@ use serde::{Deserialize, Deserializer}; |
| 6 | | 6 | |
| 7 | use crate::error::{Error, Result}; | 7 | use crate::error::{Error, Result}; |
| 8 | | 8 | |
| 9 | -#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)] | 9 | +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)] |
| 10 | #[serde(rename_all = "lowercase")] | 10 | #[serde(rename_all = "lowercase")] |
| 11 | pub enum Registration { | 11 | pub enum Registration { |
| | 12 | + #[default] |
| 12 | Closed, | 13 | Closed, |
| 13 | Invite, | 14 | Invite, |
| 14 | Open, | 15 | Open, |
| 15 | } | 16 | } |
| 16 | | 17 | |
| | 18 | +string_enum!(Registration { |
| | 19 | + Closed = "closed", |
| | 20 | + Invite = "invite", |
| | 21 | + Open = "open", |
| | 22 | +}); |
| | 23 | + |
| 17 | fn deserialize_trusted_proxies<'de, D: Deserializer<'de>>( | 24 | fn deserialize_trusted_proxies<'de, D: Deserializer<'de>>( |
| 18 | deserializer: D, | 25 | deserializer: D, |
| 19 | ) -> std::result::Result<Vec<IpNet>, D::Error> { | 26 | ) -> std::result::Result<Vec<IpNet>, D::Error> { |
| @@ -166,7 +173,7 @@ impl AlertsConfig { |
| 166 | #[serde(deny_unknown_fields, default)] | 173 | #[serde(deny_unknown_fields, default)] |
| 167 | pub struct BannerConfig { | 174 | pub struct BannerConfig { |
| 168 | pub message: String, | 175 | pub message: String, |
| 169 | - pub level: String, | 176 | + pub level: BannerLevel, |
| 170 | pub expires: String, | 177 | pub expires: String, |
| 171 | } | 178 | } |
| 172 | | 179 | |
| @@ -174,12 +181,25 @@ impl Default for BannerConfig { |
| 174 | fn default() -> Self { | 181 | fn default() -> Self { |
| 175 | BannerConfig { | 182 | BannerConfig { |
| 176 | message: String::new(), | 183 | message: String::new(), |
| 177 | - level: "info".into(), | 184 | + level: BannerLevel::Info, |
| 178 | expires: String::new(), | 185 | expires: String::new(), |
| 179 | } | 186 | } |
| 180 | } | 187 | } |
| 181 | } | 188 | } |
| 182 | | 189 | |
| | 190 | +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)] |
| | 191 | +#[serde(rename_all = "lowercase")] |
| | 192 | +pub enum BannerLevel { |
| | 193 | + #[default] |
| | 194 | + Info, |
| | 195 | + Warning, |
| | 196 | +} |
| | 197 | + |
| | 198 | +string_enum!(BannerLevel { |
| | 199 | + Info = "info", |
| | 200 | + Warning = "warning", |
| | 201 | +}); |
| | 202 | + |
| 183 | impl BannerConfig { | 203 | impl BannerConfig { |
| 184 | pub fn expires_unix(&self) -> Option<i64> { | 204 | pub fn expires_unix(&self) -> Option<i64> { |
| 185 | parse_banner_expiry(&self.expires) | 205 | parse_banner_expiry(&self.expires) |
| @@ -261,6 +281,11 @@ pub enum OrgCreation { |
| 261 | Admin, | 281 | Admin, |
| 262 | } | 282 | } |
| 263 | | 283 | |
| | 284 | +string_enum!(OrgCreation { |
| | 285 | + All = "all", |
| | 286 | + Admin = "admin", |
| | 287 | +}); |
| | 288 | + |
| 264 | #[derive(Debug, Clone, Default, Deserialize)] | 289 | #[derive(Debug, Clone, Default, Deserialize)] |
| 265 | #[serde(deny_unknown_fields, default)] | 290 | #[serde(deny_unknown_fields, default)] |
| 266 | pub struct MailConfig { | 291 | pub struct MailConfig { |
| @@ -275,6 +300,11 @@ pub enum MailTransport { |
| 275 | Log, | 300 | Log, |
| 276 | } | 301 | } |
| 277 | | 302 | |
| | 303 | +string_enum!(MailTransport { |
| | 304 | + Smtp = "smtp", |
| | 305 | + Log = "log", |
| | 306 | +}); |
| | 307 | + |
| 278 | #[derive(Debug, Clone, Deserialize)] | 308 | #[derive(Debug, Clone, Deserialize)] |
| 279 | #[serde(deny_unknown_fields, default)] | 309 | #[serde(deny_unknown_fields, default)] |
| 280 | pub struct CiConfig { | 310 | pub struct CiConfig { |
| @@ -450,6 +480,12 @@ pub enum StorageBackend { |
| 450 | R2, | 480 | R2, |
| 451 | } | 481 | } |
| 452 | | 482 | |
| | 483 | +string_enum!(StorageBackend { |
| | 484 | + Fs = "fs", |
| | 485 | + S3 = "s3", |
| | 486 | + R2 = "r2", |
| | 487 | +}); |
| | 488 | + |
| 453 | #[derive(Debug, Clone, Default, Deserialize)] | 489 | #[derive(Debug, Clone, Default, Deserialize)] |
| 454 | #[serde(deny_unknown_fields, default)] | 490 | #[serde(deny_unknown_fields, default)] |
| 455 | pub struct S3Config { | 491 | pub struct S3Config { |
| @@ -468,19 +504,38 @@ pub struct S3Config { |
| 468 | pub struct R2Config { | 504 | pub struct R2Config { |
| 469 | pub account_id: String, | 505 | pub account_id: String, |
| 470 | pub bucket: String, | 506 | pub bucket: String, |
| 471 | - pub jurisdiction: String, | 507 | + pub jurisdiction: R2Jurisdiction, |
| 472 | pub prefix: String, | 508 | pub prefix: String, |
| 473 | pub access_key_id: String, | 509 | pub access_key_id: String, |
| 474 | pub secret_access_key_file: PathBuf, | 510 | pub secret_access_key_file: PathBuf, |
| 475 | } | 511 | } |
| 476 | | 512 | |
| | 513 | +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)] |
| | 514 | +#[serde(rename_all = "lowercase")] |
| | 515 | +pub enum R2Jurisdiction { |
| | 516 | + #[default] |
| | 517 | + #[serde(rename = "")] |
| | 518 | + Global, |
| | 519 | + Eu, |
| | 520 | + Fedramp, |
| | 521 | +} |
| | 522 | + |
| | 523 | +string_enum!(R2Jurisdiction { |
| | 524 | + Global = "", |
| | 525 | + Eu = "eu", |
| | 526 | + Fedramp = "fedramp", |
| | 527 | +}); |
| | 528 | + |
| 477 | impl R2Config { | 529 | impl R2Config { |
| 478 | pub fn endpoint(&self) -> String { | 530 | pub fn endpoint(&self) -> String { |
| 479 | - match self.jurisdiction.as_str() { | 531 | + match self.jurisdiction { |
| 480 | - "" => format!("https://{}.r2.cloudflarestorage.com", self.account_id), | 532 | + R2Jurisdiction::Global => { |
| | 533 | + format!("https://{}.r2.cloudflarestorage.com", self.account_id) |
| | 534 | + } |
| 481 | jurisdiction => format!( | 535 | jurisdiction => format!( |
| 482 | - "https://{}.{jurisdiction}.r2.cloudflarestorage.com", | 536 | + "https://{}.{}.r2.cloudflarestorage.com", |
| 483 | - self.account_id | 537 | + self.account_id, |
| | 538 | + jurisdiction.as_str() |
| 484 | ), | 539 | ), |
| 485 | } | 540 | } |
| 486 | } | 541 | } |
| @@ -553,12 +608,6 @@ impl StorageConfig { |
| 553 | require("storage.r2", "bucket", &r2.bucket)?; | 608 | require("storage.r2", "bucket", &r2.bucket)?; |
| 554 | require("storage.r2", "access_key_id", &r2.access_key_id)?; | 609 | require("storage.r2", "access_key_id", &r2.access_key_id)?; |
| 555 | check_secret_file("storage.r2", &r2.secret_access_key_file)?; | 610 | check_secret_file("storage.r2", &r2.secret_access_key_file)?; |
| 556 | - if !matches!(r2.jurisdiction.as_str(), "" | "eu" | "fedramp") { | | |
| 557 | - return Err(Error::Config(format!( | | |
| 558 | - "[storage.r2] jurisdiction must be \"eu\", \"fedramp\", or left empty, not \"{}\"", | | |
| 559 | - r2.jurisdiction | | |
| 560 | - ))); | | |
| 561 | - } | | |
| 562 | Ok(()) | 611 | Ok(()) |
| 563 | } | 612 | } |
| 564 | } | 613 | } |
| @@ -1023,17 +1072,26 @@ mod tests { |
| 1023 | #[test] | 1072 | #[test] |
| 1024 | fn r2_endpoint_follows_jurisdiction() { | 1073 | fn r2_endpoint_follows_jurisdiction() { |
| 1025 | let cases = [ | 1074 | let cases = [ |
| 1026 | - ("", "https://acct.r2.cloudflarestorage.com"), | 1075 | + ( |
| 1027 | - ("eu", "https://acct.eu.r2.cloudflarestorage.com"), | 1076 | + R2Jurisdiction::Global, |
| 1028 | - ("fedramp", "https://acct.fedramp.r2.cloudflarestorage.com"), | 1077 | + "https://acct.r2.cloudflarestorage.com", |
| | 1078 | + ), |
| | 1079 | + ( |
| | 1080 | + R2Jurisdiction::Eu, |
| | 1081 | + "https://acct.eu.r2.cloudflarestorage.com", |
| | 1082 | + ), |
| | 1083 | + ( |
| | 1084 | + R2Jurisdiction::Fedramp, |
| | 1085 | + "https://acct.fedramp.r2.cloudflarestorage.com", |
| | 1086 | + ), |
| 1029 | ]; | 1087 | ]; |
| 1030 | for (jurisdiction, expected) in cases { | 1088 | for (jurisdiction, expected) in cases { |
| 1031 | let cfg = R2Config { | 1089 | let cfg = R2Config { |
| 1032 | account_id: "acct".into(), | 1090 | account_id: "acct".into(), |
| 1033 | - jurisdiction: jurisdiction.into(), | 1091 | + jurisdiction, |
| 1034 | ..R2Config::default() | 1092 | ..R2Config::default() |
| 1035 | }; | 1093 | }; |
| 1036 | - assert_eq!(cfg.endpoint(), expected, "jurisdiction `{jurisdiction}`"); | 1094 | + assert_eq!(cfg.endpoint(), expected, "jurisdiction {jurisdiction:?}"); |
| 1037 | } | 1095 | } |
| 1038 | } | 1096 | } |
| 1039 | | 1097 | |
| @@ -15,16 +15,14 @@ pub const DISCUSSION_CATEGORIES: &[DiscussionCategory] = &[ |
| 15 | DiscussionCategory::Announcements, | 15 | DiscussionCategory::Announcements, |
| 16 | ]; | 16 | ]; |
| 17 | | 17 | |
| 18 | -impl DiscussionCategory { | 18 | +string_enum!(DiscussionCategory { |
| 19 | - pub fn as_str(self) -> &'static str { | 19 | + General = "general", |
| 20 | - match self { | 20 | + Ideas = "ideas", |
| 21 | - DiscussionCategory::General => "general", | 21 | + Qa = "qa", |
| 22 | - DiscussionCategory::Ideas => "ideas", | 22 | + Announcements = "announcements", |
| 23 | - DiscussionCategory::Qa => "qa", | 23 | +}); |
| 24 | - DiscussionCategory::Announcements => "announcements", | | |
| 25 | - } | | |
| 26 | - } | | |
| 27 | | 24 | |
| | 25 | +impl DiscussionCategory { |
| 28 | pub fn label(self) -> &'static str { | 26 | pub fn label(self) -> &'static str { |
| 29 | match self { | 27 | match self { |
| 30 | DiscussionCategory::General => "General", | 28 | DiscussionCategory::General => "General", |
| @@ -33,13 +31,6 @@ impl DiscussionCategory { |
| 33 | DiscussionCategory::Announcements => "Announcements", | 31 | DiscussionCategory::Announcements => "Announcements", |
| 34 | } | 32 | } |
| 35 | } | 33 | } |
| 36 | - | | |
| 37 | - pub fn parse(name: &str) -> Option<DiscussionCategory> { | | |
| 38 | - DISCUSSION_CATEGORIES | | |
| 39 | - .iter() | | |
| 40 | - .copied() | | |
| 41 | - .find(|c| c.as_str() == name) | | |
| 42 | - } | | |
| 43 | } | 34 | } |
| 44 | | 35 | |
| 45 | #[derive(Debug, Clone, PartialEq, Eq)] | 36 | #[derive(Debug, Clone, PartialEq, Eq)] |
| @@ -70,22 +61,10 @@ pub enum DiscussionReason { |
| 70 | Reply, | 61 | Reply, |
| 71 | } | 62 | } |
| 72 | | 63 | |
| 73 | -impl DiscussionReason { | 64 | +string_enum!(DiscussionReason { |
| 74 | - pub fn as_str(self) -> &'static str { | 65 | + Mention = "mention", |
| 75 | - match self { | 66 | + Reply = "reply", |
| 76 | - DiscussionReason::Mention => "mention", | 67 | +}); |
| 77 | - DiscussionReason::Reply => "reply", | | |
| 78 | - } | | |
| 79 | - } | | |
| 80 | - | | |
| 81 | - pub fn parse(name: &str) -> Option<DiscussionReason> { | | |
| 82 | - match name { | | |
| 83 | - "mention" => Some(DiscussionReason::Mention), | | |
| 84 | - "reply" => Some(DiscussionReason::Reply), | | |
| 85 | - _ => None, | | |
| 86 | - } | | |
| 87 | - } | | |
| 88 | -} | | |
| 89 | | 68 | |
| 90 | #[derive(Debug, Clone, PartialEq, Eq)] | 69 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 91 | pub struct DiscussionNotification { | 70 | pub struct DiscussionNotification { |
| @@ -13,26 +13,10 @@ pub enum IssueState { |
| 13 | Closed, | 13 | Closed, |
| 14 | } | 14 | } |
| 15 | | 15 | |
| 16 | -impl IssueState { | 16 | +string_enum!(IssueState { |
| 17 | - pub fn as_str(&self) -> &'static str { | 17 | + Open = "open", |
| 18 | - match self { | 18 | + Closed = "closed", |
| 19 | - IssueState::Open => "open", | 19 | +}); |
| 20 | - IssueState::Closed => "closed", | | |
| 21 | - } | | |
| 22 | - } | | |
| 23 | -} | | |
| 24 | - | | |
| 25 | -impl std::str::FromStr for IssueState { | | |
| 26 | - type Err = Error; | | |
| 27 | - | | |
| 28 | - fn from_str(s: &str) -> Result<Self> { | | |
| 29 | - match s { | | |
| 30 | - "open" => Ok(IssueState::Open), | | |
| 31 | - "closed" => Ok(IssueState::Closed), | | |
| 32 | - other => Err(Error::Invalid(format!("issue state {other:?}"))), | | |
| 33 | - } | | |
| 34 | - } | | |
| 35 | -} | | |
| 36 | | 20 | |
| 37 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] | 21 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 38 | pub enum StateReason { | 22 | pub enum StateReason { |
| @@ -40,26 +24,10 @@ pub enum StateReason { |
| 40 | NotPlanned, | 24 | NotPlanned, |
| 41 | } | 25 | } |
| 42 | | 26 | |
| 43 | -impl StateReason { | 27 | +string_enum!(StateReason { |
| 44 | - pub fn as_str(&self) -> &'static str { | 28 | + Completed = "completed", |
| 45 | - match self { | 29 | + NotPlanned = "not_planned", |
| 46 | - StateReason::Completed => "completed", | 30 | +}); |
| 47 | - StateReason::NotPlanned => "not_planned", | | |
| 48 | - } | | |
| 49 | - } | | |
| 50 | -} | | |
| 51 | - | | |
| 52 | -impl std::str::FromStr for StateReason { | | |
| 53 | - type Err = Error; | | |
| 54 | - | | |
| 55 | - fn from_str(s: &str) -> Result<Self> { | | |
| 56 | - match s { | | |
| 57 | - "completed" => Ok(StateReason::Completed), | | |
| 58 | - "not_planned" => Ok(StateReason::NotPlanned), | | |
| 59 | - other => Err(Error::Invalid(format!("state reason {other:?}"))), | | |
| 60 | - } | | |
| 61 | - } | | |
| 62 | -} | | |
| 63 | | 31 | |
| 64 | #[derive(Debug, Clone, PartialEq)] | 32 | #[derive(Debug, Clone, PartialEq)] |
| 65 | pub struct Issue { | 33 | pub struct Issue { |
| @@ -167,28 +135,11 @@ pub enum IssueSort { |
| 167 | RecentlyUpdated, | 135 | RecentlyUpdated, |
| 168 | } | 136 | } |
| 169 | | 137 | |
| 170 | -impl IssueSort { | 138 | +string_enum!(IssueSort { |
| 171 | - pub fn as_str(&self) -> &'static str { | 139 | + Newest = "newest", |
| 172 | - match self { | 140 | + Oldest = "oldest", |
| 173 | - IssueSort::Newest => "newest", | 141 | + RecentlyUpdated = "updated", |
| 174 | - IssueSort::Oldest => "oldest", | 142 | +}); |
| 175 | - IssueSort::RecentlyUpdated => "updated", | | |
| 176 | - } | | |
| 177 | - } | | |
| 178 | -} | | |
| 179 | - | | |
| 180 | -impl std::str::FromStr for IssueSort { | | |
| 181 | - type Err = Error; | | |
| 182 | - | | |
| 183 | - fn from_str(s: &str) -> Result<Self> { | | |
| 184 | - match s { | | |
| 185 | - "newest" => Ok(IssueSort::Newest), | | |
| 186 | - "oldest" => Ok(IssueSort::Oldest), | | |
| 187 | - "updated" => Ok(IssueSort::RecentlyUpdated), | | |
| 188 | - other => Err(Error::Invalid(format!("sort {other:?}"))), | | |
| 189 | - } | | |
| 190 | - } | | |
| 191 | -} | | |
| 192 | | 143 | |
| 193 | #[derive(Debug, Clone, PartialEq)] | 144 | #[derive(Debug, Clone, PartialEq)] |
| 194 | pub struct IssueListItem { | 145 | pub struct IssueListItem { |
| @@ -1,11 +1,5 @@ |
| | 1 | +use crate::signed_token; |
| 1 | use base64::prelude::{BASE64_URL_SAFE_NO_PAD, Engine as _}; | 2 | use base64::prelude::{BASE64_URL_SAFE_NO_PAD, Engine as _}; |
| 2 | -use hmac::{Hmac, KeyInit, Mac}; | | |
| 3 | -use sha2::Sha256; | | |
| 4 | -use subtle::ConstantTimeEq; | | |
| 5 | - | | |
| 6 | -type HmacSha256 = Hmac<Sha256>; | | |
| 7 | - | | |
| 8 | -const MAC_LEN: usize = 32; | | |
| 9 | | 3 | |
| 10 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] | 4 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 11 | pub enum LfsOp { | 5 | pub enum LfsOp { |
| @@ -14,43 +8,28 @@ pub enum LfsOp { |
| 14 | Any, | 8 | Any, |
| 15 | } | 9 | } |
| 16 | | 10 | |
| 17 | -impl LfsOp { | 11 | +string_enum!(LfsOp { |
| 18 | - pub fn as_str(self) -> &'static str { | 12 | + Download = "download", |
| 19 | - match self { | 13 | + Upload = "upload", |
| 20 | - LfsOp::Download => "download", | 14 | + Any = "any", |
| 21 | - LfsOp::Upload => "upload", | 15 | +}); |
| 22 | - LfsOp::Any => "any", | 16 | + |
| 23 | - } | 17 | +fn framing<'a>(repo_id: &'a str, op: &'a str, expires: &'a str) -> [&'a [u8]; 6] { |
| 24 | - } | 18 | + [ |
| 25 | - | 19 | + b"lfs\0", |
| 26 | - fn parse(s: &str) -> Option<LfsOp> { | 20 | + repo_id.as_bytes(), |
| 27 | - match s { | 21 | + b"\0", |
| 28 | - "download" => Some(LfsOp::Download), | 22 | + op.as_bytes(), |
| 29 | - "upload" => Some(LfsOp::Upload), | 23 | + b"\0", |
| 30 | - "any" => Some(LfsOp::Any), | 24 | + expires.as_bytes(), |
| 31 | - _ => None, | 25 | + ] |
| 32 | - } | | |
| 33 | - } | | |
| 34 | -} | | |
| 35 | - | | |
| 36 | -fn mac_for(key: &[u8; 32], repo_id: &str, op: &str, expires_unix: i64) -> HmacSha256 { | | |
| 37 | - let mut mac = | | |
| 38 | - <HmacSha256 as KeyInit>::new_from_slice(key).expect("HMAC accepts any key length"); | | |
| 39 | - mac.update(b"lfs\0"); | | |
| 40 | - mac.update(repo_id.as_bytes()); | | |
| 41 | - mac.update(b"\0"); | | |
| 42 | - mac.update(op.as_bytes()); | | |
| 43 | - mac.update(b"\0"); | | |
| 44 | - mac.update(expires_unix.to_string().as_bytes()); | | |
| 45 | - mac | | |
| 46 | } | 26 | } |
| 47 | | 27 | |
| 48 | pub fn issue(key: &[u8; 32], repo_id: &str, op: LfsOp, expires_unix: i64) -> String { | 28 | pub fn issue(key: &[u8; 32], repo_id: &str, op: LfsOp, expires_unix: i64) -> String { |
| 49 | - let tag = mac_for(key, repo_id, op.as_str(), expires_unix) | 29 | + let expires = expires_unix.to_string(); |
| 50 | - .finalize() | 30 | + let tag = signed_token::mac(key, &framing(repo_id, op.as_str(), &expires)); |
| 51 | - .into_bytes(); | | |
| 52 | format!( | 31 | format!( |
| 53 | - "{expires_unix}.{}.{}", | 32 | + "{expires}.{}.{}", |
| 54 | op.as_str(), | 33 | op.as_str(), |
| 55 | BASE64_URL_SAFE_NO_PAD.encode(tag) | 34 | BASE64_URL_SAFE_NO_PAD.encode(tag) |
| 56 | ) | 35 | ) |
| @@ -63,16 +42,13 @@ pub fn verify(key: &[u8; 32], token: &str, repo_id: &str, wanted: LfsOp, now_uni |
| 63 | else { | 42 | else { |
| 64 | return false; | 43 | return false; |
| 65 | }; | 44 | }; |
| 66 | - let Ok(expires) = expires_str.parse::<i64>() else { | 45 | + let Some(expires) = signed_token::parse_expiry(expires_str) else { |
| 67 | return false; | 46 | return false; |
| 68 | }; | 47 | }; |
| 69 | - if expires.to_string() != expires_str { | | |
| 70 | - return false; | | |
| 71 | - } | | |
| 72 | if now_unix >= expires { | 48 | if now_unix >= expires { |
| 73 | return false; | 49 | return false; |
| 74 | } | 50 | } |
| 75 | - let Some(token_op) = LfsOp::parse(op_str) else { | 51 | + let Ok(token_op) = op_str.parse::<LfsOp>() else { |
| 76 | return false; | 52 | return false; |
| 77 | }; | 53 | }; |
| 78 | let satisfies = token_op == LfsOp::Any || token_op == wanted; | 54 | let satisfies = token_op == LfsOp::Any || token_op == wanted; |
| @@ -82,18 +58,13 @@ pub fn verify(key: &[u8; 32], token: &str, repo_id: &str, wanted: LfsOp, now_uni |
| 82 | let Ok(tag) = BASE64_URL_SAFE_NO_PAD.decode(mac_str) else { | 58 | let Ok(tag) = BASE64_URL_SAFE_NO_PAD.decode(mac_str) else { |
| 83 | return false; | 59 | return false; |
| 84 | }; | 60 | }; |
| 85 | - if tag.len() != MAC_LEN { | 61 | + signed_token::verify(key, &framing(repo_id, op_str, expires_str), &tag) |
| 86 | - return false; | | |
| 87 | - } | | |
| 88 | - let expected = mac_for(key, repo_id, op_str, expires) | | |
| 89 | - .finalize() | | |
| 90 | - .into_bytes(); | | |
| 91 | - bool::from(expected.as_slice().ct_eq(&tag)) | | |
| 92 | } | 62 | } |
| 93 | | 63 | |
| 94 | #[cfg(test)] | 64 | #[cfg(test)] |
| 95 | mod tests { | 65 | mod tests { |
| 96 | use super::*; | 66 | use super::*; |
| | 67 | + use crate::signed_token::MAC_LEN; |
| 97 | | 68 | |
| 98 | const KEY: [u8; 32] = [7; 32]; | 69 | const KEY: [u8; 32] = [7; 32]; |
| 99 | const OTHER_KEY: [u8; 32] = [9; 32]; | 70 | const OTHER_KEY: [u8; 32] = [9; 32]; |
| @@ -1,3 +1,29 @@ |
| | 1 | +macro_rules! string_enum { |
| | 2 | + ($name:ident { $($variant:ident = $text:literal),+ $(,)? }) => { |
| | 3 | + impl $name { |
| | 4 | + pub const fn as_str(self) -> &'static str { |
| | 5 | + match self { |
| | 6 | + $(Self::$variant => $text),+ |
| | 7 | + } |
| | 8 | + } |
| | 9 | + } |
| | 10 | + |
| | 11 | + impl std::str::FromStr for $name { |
| | 12 | + type Err = crate::error::Error; |
| | 13 | + |
| | 14 | + fn from_str(s: &str) -> std::result::Result<Self, Self::Err> { |
| | 15 | + match s { |
| | 16 | + $($text => Ok(Self::$variant),)+ |
| | 17 | + other => Err(crate::error::Error::Invalid(format!( |
| | 18 | + "{}: {other:?}", |
| | 19 | + stringify!($name) |
| | 20 | + ))), |
| | 21 | + } |
| | 22 | + } |
| | 23 | + } |
| | 24 | + }; |
| | 25 | +} |
| | 26 | + |
| 1 | pub mod advisories; | 27 | pub mod advisories; |
| 2 | pub mod alerts; | 28 | pub mod alerts; |
| 3 | pub mod audit; | 29 | pub mod audit; |
| @@ -28,6 +54,7 @@ pub mod releases; |
| 28 | pub mod reviews; | 54 | pub mod reviews; |
| 29 | pub mod secret; | 55 | pub mod secret; |
| 30 | pub mod server_settings; | 56 | pub mod server_settings; |
| | 57 | +pub mod signed_token; |
| 31 | pub mod store; | 58 | pub mod store; |
| 32 | pub mod suggestions; | 59 | pub mod suggestions; |
| 33 | pub mod time; | 60 | pub mod time; |
| @@ -25,24 +25,11 @@ pub enum Security { |
| 25 | Plain, | 25 | Plain, |
| 26 | } | 26 | } |
| 27 | | 27 | |
| 28 | -impl Security { | 28 | +string_enum!(Security { |
| 29 | - pub fn as_str(self) -> &'static str { | 29 | + StartTls = "starttls", |
| 30 | - match self { | 30 | + Tls = "tls", |
| 31 | - Security::StartTls => "starttls", | 31 | + Plain = "none", |
| 32 | - Security::Tls => "tls", | 32 | +}); |
| 33 | - Security::Plain => "none", | | |
| 34 | - } | | |
| 35 | - } | | |
| 36 | - | | |
| 37 | - pub fn parse(s: &str) -> Option<Security> { | | |
| 38 | - match s { | | |
| 39 | - "starttls" => Some(Security::StartTls), | | |
| 40 | - "tls" => Some(Security::Tls), | | |
| 41 | - "none" => Some(Security::Plain), | | |
| 42 | - _ => None, | | |
| 43 | - } | | |
| 44 | - } | | |
| 45 | -} | | |
| 46 | | 33 | |
| 47 | #[derive(Debug, Clone, PartialEq, Eq)] | 34 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 48 | pub struct MailSettings { | 35 | pub struct MailSettings { |
| @@ -121,23 +108,17 @@ impl MailKind { |
| 121 | MailKind::Test, | 108 | MailKind::Test, |
| 122 | MailKind::Other, | 109 | MailKind::Other, |
| 123 | ]; | 110 | ]; |
| 124 | - | | |
| 125 | - pub fn as_str(self) -> &'static str { | | |
| 126 | - match self { | | |
| 127 | - MailKind::Verification => "verification", | | |
| 128 | - MailKind::PasswordReset => "password_reset", | | |
| 129 | - MailKind::Invite => "invite", | | |
| 130 | - MailKind::Notification => "notification", | | |
| 131 | - MailKind::Test => "test", | | |
| 132 | - MailKind::Other => "other", | | |
| 133 | - } | | |
| 134 | - } | | |
| 135 | - | | |
| 136 | - pub fn parse(s: &str) -> Option<MailKind> { | | |
| 137 | - MailKind::ALL.into_iter().find(|kind| kind.as_str() == s) | | |
| 138 | - } | | |
| 139 | } | 111 | } |
| 140 | | 112 | |
| | 113 | +string_enum!(MailKind { |
| | 114 | + Verification = "verification", |
| | 115 | + PasswordReset = "password_reset", |
| | 116 | + Invite = "invite", |
| | 117 | + Notification = "notification", |
| | 118 | + Test = "test", |
| | 119 | + Other = "other", |
| | 120 | +}); |
| | 121 | + |
| 141 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] | 122 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 142 | pub enum MailState { | 123 | pub enum MailState { |
| 143 | Queued, | 124 | Queued, |
| @@ -157,23 +138,17 @@ impl MailState { |
| 157 | MailState::Failed, | 138 | MailState::Failed, |
| 158 | MailState::Discarded, | 139 | MailState::Discarded, |
| 159 | ]; | 140 | ]; |
| 160 | - | | |
| 161 | - pub fn as_str(self) -> &'static str { | | |
| 162 | - match self { | | |
| 163 | - MailState::Queued => "queued", | | |
| 164 | - MailState::Retrying => "retrying", | | |
| 165 | - MailState::Sending => "sending", | | |
| 166 | - MailState::Sent => "sent", | | |
| 167 | - MailState::Failed => "failed", | | |
| 168 | - MailState::Discarded => "discarded", | | |
| 169 | - } | | |
| 170 | - } | | |
| 171 | - | | |
| 172 | - pub fn parse(s: &str) -> Option<MailState> { | | |
| 173 | - MailState::ALL.into_iter().find(|state| state.as_str() == s) | | |
| 174 | - } | | |
| 175 | } | 141 | } |
| 176 | | 142 | |
| | 143 | +string_enum!(MailState { |
| | 144 | + Queued = "queued", |
| | 145 | + Retrying = "retrying", |
| | 146 | + Sending = "sending", |
| | 147 | + Sent = "sent", |
| | 148 | + Failed = "failed", |
| | 149 | + Discarded = "discarded", |
| | 150 | +}); |
| | 151 | + |
| 177 | #[derive(Clone, PartialEq, Eq)] | 152 | #[derive(Clone, PartialEq, Eq)] |
| 178 | pub struct OutgoingMail { | 153 | pub struct OutgoingMail { |
| 179 | pub to: String, | 154 | pub to: String, |
| @@ -415,17 +390,17 @@ mod tests { |
| 415 | #[test] | 390 | #[test] |
| 416 | fn enum_names_round_trip_and_unknown_names_are_refused() { | 391 | fn enum_names_round_trip_and_unknown_names_are_refused() { |
| 417 | for s in [Security::StartTls, Security::Tls, Security::Plain] { | 392 | for s in [Security::StartTls, Security::Tls, Security::Plain] { |
| 418 | - assert_eq!(Security::parse(s.as_str()), Some(s)); | 393 | + assert_eq!(s.as_str().parse::<Security>().ok(), Some(s)); |
| 419 | } | 394 | } |
| 420 | - assert_eq!(Security::parse("ssl"), None); | 395 | + assert!("ssl".parse::<Security>().is_err()); |
| 421 | for kind in MailKind::ALL { | 396 | for kind in MailKind::ALL { |
| 422 | - assert_eq!(MailKind::parse(kind.as_str()), Some(kind)); | 397 | + assert_eq!(kind.as_str().parse::<MailKind>().ok(), Some(kind)); |
| 423 | } | 398 | } |
| 424 | - assert_eq!(MailKind::parse("spam"), None); | 399 | + assert!("spam".parse::<MailKind>().is_err()); |
| 425 | for state in MailState::ALL { | 400 | for state in MailState::ALL { |
| 426 | - assert_eq!(MailState::parse(state.as_str()), Some(state)); | 401 | + assert_eq!(state.as_str().parse::<MailState>().ok(), Some(state)); |
| 427 | } | 402 | } |
| 428 | - assert_eq!(MailState::parse("gave up"), None); | 403 | + assert!("gave up".parse::<MailState>().is_err()); |
| 429 | } | 404 | } |
| 430 | | 405 | |
| 431 | #[test] | 406 | #[test] |
| @@ -1,4 +1,3 @@ |
| 1 | -use crate::error::{Error, Result}; | | |
| 2 | use crate::pulls::MergeStyle; | 1 | use crate::pulls::MergeStyle; |
| 3 | | 2 | |
| 4 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] | 3 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| @@ -10,36 +9,13 @@ pub enum QueueState { |
| 10 | Removed, | 9 | Removed, |
| 11 | } | 10 | } |
| 12 | | 11 | |
| 13 | -impl QueueState { | 12 | +string_enum!(QueueState { |
| 14 | - pub fn as_str(self) -> &'static str { | 13 | + Queued = "queued", |
| 15 | - match self { | 14 | + Testing = "testing", |
| 16 | - QueueState::Queued => "queued", | 15 | + Merging = "merging", |
| 17 | - QueueState::Testing => "testing", | 16 | + Failed = "failed", |
| 18 | - QueueState::Merging => "merging", | 17 | + Removed = "removed", |
| 19 | - QueueState::Failed => "failed", | 18 | +}); |
| 20 | - QueueState::Removed => "removed", | | |
| 21 | - } | | |
| 22 | - } | | |
| 23 | -} | | |
| 24 | - | | |
| 25 | -impl std::str::FromStr for QueueState { | | |
| 26 | - type Err = Error; | | |
| 27 | - | | |
| 28 | - fn from_str(s: &str) -> Result<Self> { | | |
| 29 | - Ok(match s { | | |
| 30 | - "queued" => QueueState::Queued, | | |
| 31 | - "testing" => QueueState::Testing, | | |
| 32 | - "merging" => QueueState::Merging, | | |
| 33 | - "failed" => QueueState::Failed, | | |
| 34 | - "removed" => QueueState::Removed, | | |
| 35 | - other => { | | |
| 36 | - return Err(Error::Database(format!( | | |
| 37 | - "unknown merge queue state {other}" | | |
| 38 | - ))); | | |
| 39 | - } | | |
| 40 | - }) | | |
| 41 | - } | | |
| 42 | -} | | |
| 43 | | 19 | |
| 44 | #[derive(Debug, Clone, PartialEq, Eq)] | 20 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 45 | pub struct QueueEntry { | 21 | pub struct QueueEntry { |
| @@ -6,28 +6,10 @@ pub enum MirrorDirection { |
| 6 | Push, | 6 | Push, |
| 7 | } | 7 | } |
| 8 | | 8 | |
| 9 | -impl MirrorDirection { | 9 | +string_enum!(MirrorDirection { |
| 10 | - pub fn as_str(self) -> &'static str { | 10 | + Pull = "pull", |
| 11 | - match self { | 11 | + Push = "push", |
| 12 | - MirrorDirection::Pull => "pull", | 12 | +}); |
| 13 | - MirrorDirection::Push => "push", | | |
| 14 | - } | | |
| 15 | - } | | |
| 16 | -} | | |
| 17 | - | | |
| 18 | -impl std::str::FromStr for MirrorDirection { | | |
| 19 | - type Err = crate::error::Error; | | |
| 20 | - | | |
| 21 | - fn from_str(s: &str) -> Result<Self, Self::Err> { | | |
| 22 | - match s { | | |
| 23 | - "pull" => Ok(MirrorDirection::Pull), | | |
| 24 | - "push" => Ok(MirrorDirection::Push), | | |
| 25 | - other => Err(crate::error::Error::Database(format!( | | |
| 26 | - "unknown mirror direction {other:?}" | | |
| 27 | - ))), | | |
| 28 | - } | | |
| 29 | - } | | |
| 30 | -} | | |
| 31 | | 13 | |
| 32 | #[derive(Debug, Clone, PartialEq, Eq)] | 14 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 33 | pub struct Mirror { | 15 | pub struct Mirror { |
| @@ -147,55 +147,18 @@ impl std::fmt::Debug for Session { |
| 147 | } | 147 | } |
| 148 | } | 148 | } |
| 149 | | 149 | |
| 150 | -impl Visibility { | 150 | +string_enum!(Visibility { |
| 151 | - pub fn as_str(&self) -> &'static str { | 151 | + Public = "public", |
| 152 | - match self { | 152 | + Private = "private", |
| 153 | - Visibility::Public => "public", | 153 | +}); |
| 154 | - Visibility::Private => "private", | 154 | + |
| 155 | - } | 155 | +string_enum!(Role { |
| 156 | - } | 156 | + Read = "read", |
| 157 | -} | 157 | + Triage = "triage", |
| 158 | - | 158 | + Write = "write", |
| 159 | -impl std::str::FromStr for Visibility { | 159 | + Maintain = "maintain", |
| 160 | - type Err = crate::error::Error; | 160 | + Admin = "admin", |
| 161 | - | 161 | +}); |
| 162 | - fn from_str(s: &str) -> Result<Self, Self::Err> { | | |
| 163 | - match s { | | |
| 164 | - "public" => Ok(Visibility::Public), | | |
| 165 | - "private" => Ok(Visibility::Private), | | |
| 166 | - other => Err(crate::error::Error::Invalid(format!( | | |
| 167 | - "visibility {other:?}" | | |
| 168 | - ))), | | |
| 169 | - } | | |
| 170 | - } | | |
| 171 | -} | | |
| 172 | - | | |
| 173 | -impl Role { | | |
| 174 | - pub fn as_str(&self) -> &'static str { | | |
| 175 | - match self { | | |
| 176 | - Role::Read => "read", | | |
| 177 | - Role::Triage => "triage", | | |
| 178 | - Role::Write => "write", | | |
| 179 | - Role::Maintain => "maintain", | | |
| 180 | - Role::Admin => "admin", | | |
| 181 | - } | | |
| 182 | - } | | |
| 183 | -} | | |
| 184 | - | | |
| 185 | -impl std::str::FromStr for Role { | | |
| 186 | - type Err = crate::error::Error; | | |
| 187 | - | | |
| 188 | - fn from_str(s: &str) -> Result<Self, Self::Err> { | | |
| 189 | - match s { | | |
| 190 | - "read" => Ok(Role::Read), | | |
| 191 | - "triage" => Ok(Role::Triage), | | |
| 192 | - "write" => Ok(Role::Write), | | |
| 193 | - "maintain" => Ok(Role::Maintain), | | |
| 194 | - "admin" => Ok(Role::Admin), | | |
| 195 | - other => Err(crate::error::Error::Invalid(format!("role {other:?}"))), | | |
| 196 | - } | | |
| 197 | - } | | |
| 198 | -} | | |
| 199 | | 162 | |
| 200 | #[cfg(test)] | 163 | #[cfg(test)] |
| 201 | mod tests { | 164 | mod tests { |
| @@ -8,24 +8,11 @@ pub enum WatchLevel { |
| 8 | Ignoring, | 8 | Ignoring, |
| 9 | } | 9 | } |
| 10 | | 10 | |
| 11 | -impl WatchLevel { | 11 | +string_enum!(WatchLevel { |
| 12 | - pub fn as_str(self) -> &'static str { | 12 | + Watching = "watching", |
| 13 | - match self { | 13 | + Participating = "participating", |
| 14 | - WatchLevel::Watching => "watching", | 14 | + Ignoring = "ignoring", |
| 15 | - WatchLevel::Participating => "participating", | 15 | +}); |
| 16 | - WatchLevel::Ignoring => "ignoring", | | |
| 17 | - } | | |
| 18 | - } | | |
| 19 | - | | |
| 20 | - pub fn parse(s: &str) -> Option<WatchLevel> { | | |
| 21 | - match s { | | |
| 22 | - "watching" => Some(WatchLevel::Watching), | | |
| 23 | - "participating" => Some(WatchLevel::Participating), | | |
| 24 | - "ignoring" => Some(WatchLevel::Ignoring), | | |
| 25 | - _ => None, | | |
| 26 | - } | | |
| 27 | - } | | |
| 28 | -} | | |
| 29 | | 16 | |
| 30 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] | 17 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 31 | pub enum SubState { | 18 | pub enum SubState { |
| @@ -33,22 +20,10 @@ pub enum SubState { |
| 33 | Ignored, | 20 | Ignored, |
| 34 | } | 21 | } |
| 35 | | 22 | |
| 36 | -impl SubState { | 23 | +string_enum!(SubState { |
| 37 | - pub fn as_str(self) -> &'static str { | 24 | + Subscribed = "subscribed", |
| 38 | - match self { | 25 | + Ignored = "ignored", |
| 39 | - SubState::Subscribed => "subscribed", | 26 | +}); |
| 40 | - SubState::Ignored => "ignored", | | |
| 41 | - } | | |
| 42 | - } | | |
| 43 | - | | |
| 44 | - pub fn parse(s: &str) -> Option<SubState> { | | |
| 45 | - match s { | | |
| 46 | - "subscribed" => Some(SubState::Subscribed), | | |
| 47 | - "ignored" => Some(SubState::Ignored), | | |
| 48 | - _ => None, | | |
| 49 | - } | | |
| 50 | - } | | |
| 51 | -} | | |
| 52 | | 27 | |
| 53 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] | 28 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 54 | pub enum Reason { | 29 | pub enum Reason { |
| @@ -62,34 +37,18 @@ pub enum Reason { |
| 62 | Watching, | 37 | Watching, |
| 63 | } | 38 | } |
| 64 | | 39 | |
| 65 | -impl Reason { | 40 | +string_enum!(Reason { |
| 66 | - pub fn as_str(self) -> &'static str { | 41 | + Mention = "mention", |
| 67 | - match self { | 42 | + Assign = "assign", |
| 68 | - Reason::Mention => "mention", | 43 | + ReviewRequested = "review_requested", |
| 69 | - Reason::Assign => "assign", | 44 | + Author = "author", |
| 70 | - Reason::ReviewRequested => "review_requested", | 45 | + Comment = "comment", |
| 71 | - Reason::Author => "author", | 46 | + StateChange = "state_change", |
| 72 | - Reason::Comment => "comment", | 47 | + Subscribed = "subscribed", |
| 73 | - Reason::StateChange => "state_change", | 48 | + Watching = "watching", |
| 74 | - Reason::Subscribed => "subscribed", | 49 | +}); |
| 75 | - Reason::Watching => "watching", | | |
| 76 | - } | | |
| 77 | - } | | |
| 78 | - | | |
| 79 | - pub fn parse(s: &str) -> Option<Reason> { | | |
| 80 | - match s { | | |
| 81 | - "mention" => Some(Reason::Mention), | | |
| 82 | - "assign" => Some(Reason::Assign), | | |
| 83 | - "review_requested" => Some(Reason::ReviewRequested), | | |
| 84 | - "author" => Some(Reason::Author), | | |
| 85 | - "comment" => Some(Reason::Comment), | | |
| 86 | - "state_change" => Some(Reason::StateChange), | | |
| 87 | - "subscribed" => Some(Reason::Subscribed), | | |
| 88 | - "watching" => Some(Reason::Watching), | | |
| 89 | - _ => None, | | |
| 90 | - } | | |
| 91 | - } | | |
| 92 | | 50 | |
| | 51 | +impl Reason { |
| 93 | pub fn rank(self) -> u8 { | 52 | pub fn rank(self) -> u8 { |
| 94 | match self { | 53 | match self { |
| 95 | Reason::Mention => 8, | 54 | Reason::Mention => 8, |
| @@ -1,10 +1,6 @@ |
| | 1 | +use crate::signed_token; |
| 1 | use base64::prelude::{BASE64_URL_SAFE_NO_PAD, Engine as _}; | 2 | use base64::prelude::{BASE64_URL_SAFE_NO_PAD, Engine as _}; |
| 2 | -use hmac::{Hmac, KeyInit, Mac}; | | |
| 3 | use serde_json::Value; | 3 | use serde_json::Value; |
| 4 | -use sha2::Sha256; | | |
| 5 | -use subtle::ConstantTimeEq; | | |
| 6 | - | | |
| 7 | -type HmacSha256 = Hmac<Sha256>; | | |
| 8 | | 4 | |
| 9 | pub const MANIFEST_MEDIA_TYPES: [&str; 4] = [ | 5 | pub const MANIFEST_MEDIA_TYPES: [&str; 4] = [ |
| 10 | "application/vnd.oci.image.manifest.v1+json", | 6 | "application/vnd.oci.image.manifest.v1+json", |
| @@ -134,17 +130,13 @@ fn descriptor_size(descriptor: &Value) -> u64 { |
| 134 | descriptor.get("size").and_then(Value::as_u64).unwrap_or(0) | 130 | descriptor.get("size").and_then(Value::as_u64).unwrap_or(0) |
| 135 | } | 131 | } |
| 136 | | 132 | |
| 137 | -fn mac_for(key: &[u8; 32], payload: &[u8]) -> HmacSha256 { | 133 | +fn framing(payload: &[u8]) -> [&[u8]; 2] { |
| 138 | - let mut mac = | 134 | + [b"oci\0", payload] |
| 139 | - <HmacSha256 as KeyInit>::new_from_slice(key).expect("HMAC accepts any key length"); | | |
| 140 | - mac.update(b"oci\0"); | | |
| 141 | - mac.update(payload); | | |
| 142 | - mac | | |
| 143 | } | 135 | } |
| 144 | | 136 | |
| 145 | pub fn issue_token(key: &[u8; 32], subject: Option<&str>, expires_unix: i64) -> String { | 137 | pub fn issue_token(key: &[u8; 32], subject: Option<&str>, expires_unix: i64) -> String { |
| 146 | let payload = format!("oci1|{}|{expires_unix}", subject.unwrap_or("")); | 138 | let payload = format!("oci1|{}|{expires_unix}", subject.unwrap_or("")); |
| 147 | - let tag = mac_for(key, payload.as_bytes()).finalize().into_bytes(); | 139 | + let tag = signed_token::mac(key, &framing(payload.as_bytes())); |
| 148 | format!( | 140 | format!( |
| 149 | "{}.{}", | 141 | "{}.{}", |
| 150 | BASE64_URL_SAFE_NO_PAD.encode(payload.as_bytes()), | 142 | BASE64_URL_SAFE_NO_PAD.encode(payload.as_bytes()), |
| @@ -156,8 +148,7 @@ pub fn verify_token(key: &[u8; 32], token: &str, now_unix: i64) -> Option<Option |
| 156 | let (payload_b64, mac_b64) = token.split_once('.')?; | 148 | let (payload_b64, mac_b64) = token.split_once('.')?; |
| 157 | let payload = BASE64_URL_SAFE_NO_PAD.decode(payload_b64).ok()?; | 149 | let payload = BASE64_URL_SAFE_NO_PAD.decode(payload_b64).ok()?; |
| 158 | let tag = BASE64_URL_SAFE_NO_PAD.decode(mac_b64).ok()?; | 150 | let tag = BASE64_URL_SAFE_NO_PAD.decode(mac_b64).ok()?; |
| 159 | - let expected = mac_for(key, &payload).finalize().into_bytes(); | 151 | + if !signed_token::verify(key, &framing(&payload), &tag) { |
| 160 | - if !bool::from(expected.as_slice().ct_eq(&tag)) { | | |
| 161 | return None; | 152 | return None; |
| 162 | } | 153 | } |
| 163 | let payload = std::str::from_utf8(&payload).ok()?; | 154 | let payload = std::str::from_utf8(&payload).ok()?; |
| @@ -166,7 +157,7 @@ pub fn verify_token(key: &[u8; 32], token: &str, now_unix: i64) -> Option<Option |
| 166 | return None; | 157 | return None; |
| 167 | } | 158 | } |
| 168 | let subject = parts.next()?; | 159 | let subject = parts.next()?; |
| 169 | - let expires: i64 = parts.next()?.parse().ok()?; | 160 | + let expires = signed_token::parse_expiry(parts.next()?)?; |
| 170 | if parts.next().is_some() || now_unix >= expires { | 161 | if parts.next().is_some() || now_unix >= expires { |
| 171 | return None; | 162 | return None; |
| 172 | } | 163 | } |
| @@ -1,4 +1,3 @@ |
| 1 | -use crate::error::{Error, Result}; | | |
| 2 | use crate::issues::Issue; | 1 | use crate::issues::Issue; |
| 3 | use crate::model::Id; | 2 | use crate::model::Id; |
| 4 | | 3 | |
| @@ -11,32 +10,13 @@ pub enum Mergeable { |
| 11 | UpToDate, | 10 | UpToDate, |
| 12 | } | 11 | } |
| 13 | | 12 | |
| 14 | -impl Mergeable { | 13 | +string_enum!(Mergeable { |
| 15 | - pub fn as_str(&self) -> &'static str { | 14 | + Unknown = "unknown", |
| 16 | - match self { | 15 | + Clean = "clean", |
| 17 | - Mergeable::Unknown => "unknown", | 16 | + Conflict = "conflict", |
| 18 | - Mergeable::Clean => "clean", | 17 | + Merged = "merged", |
| 19 | - Mergeable::Conflict => "conflict", | 18 | + UpToDate = "up_to_date", |
| 20 | - Mergeable::Merged => "merged", | 19 | +}); |
| 21 | - Mergeable::UpToDate => "up_to_date", | | |
| 22 | - } | | |
| 23 | - } | | |
| 24 | -} | | |
| 25 | - | | |
| 26 | -impl std::str::FromStr for Mergeable { | | |
| 27 | - type Err = Error; | | |
| 28 | - | | |
| 29 | - fn from_str(s: &str) -> Result<Self> { | | |
| 30 | - match s { | | |
| 31 | - "unknown" => Ok(Mergeable::Unknown), | | |
| 32 | - "clean" => Ok(Mergeable::Clean), | | |
| 33 | - "conflict" => Ok(Mergeable::Conflict), | | |
| 34 | - "merged" => Ok(Mergeable::Merged), | | |
| 35 | - "up_to_date" => Ok(Mergeable::UpToDate), | | |
| 36 | - other => Err(Error::Invalid(format!("mergeable {other:?}"))), | | |
| 37 | - } | | |
| 38 | - } | | |
| 39 | -} | | |
| 40 | | 20 | |
| 41 | #[derive(Debug, Clone, PartialEq)] | 21 | #[derive(Debug, Clone, PartialEq)] |
| 42 | pub struct PullRequest { | 22 | pub struct PullRequest { |
| @@ -56,6 +36,19 @@ pub struct PullRequest { |
| 56 | pub auto_merge: Option<AutoMerge>, | 36 | pub auto_merge: Option<AutoMerge>, |
| 57 | } | 37 | } |
| 58 | | 38 | |
| | 39 | +#[derive(Debug, Clone, Copy)] |
| | 40 | +pub struct NewPull<'a> { |
| | 41 | + pub repo_id: &'a str, |
| | 42 | + pub author_id: &'a str, |
| | 43 | + pub title: &'a str, |
| | 44 | + pub body: &'a str, |
| | 45 | + pub base_branch: &'a str, |
| | 46 | + pub head_repo_id: &'a str, |
| | 47 | + pub head_branch: &'a str, |
| | 48 | + pub head_oid: &'a str, |
| | 49 | + pub base_oid: &'a str, |
| | 50 | +} |
| | 51 | + |
| 59 | #[derive(Debug, Clone, PartialEq, Eq)] | 52 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 60 | pub struct AutoMerge { | 53 | pub struct AutoMerge { |
| 61 | pub style: MergeStyle, | 54 | pub style: MergeStyle, |
| @@ -70,30 +63,12 @@ pub enum MergeStyle { |
| 70 | Rebase, | 63 | Rebase, |
| 71 | } | 64 | } |
| 72 | | 65 | |
| 73 | -impl MergeStyle { | 66 | +string_enum!(MergeStyle { |
| 74 | - pub fn as_str(&self) -> &'static str { | 67 | + Merge = "merge", |
| 75 | - match self { | 68 | + Squash = "squash", |
| 76 | - MergeStyle::Merge => "merge", | 69 | + FastForward = "ff", |
| 77 | - MergeStyle::Squash => "squash", | 70 | + Rebase = "rebase", |
| 78 | - MergeStyle::FastForward => "ff", | 71 | +}); |
| 79 | - MergeStyle::Rebase => "rebase", | | |
| 80 | - } | | |
| 81 | - } | | |
| 82 | -} | | |
| 83 | - | | |
| 84 | -impl std::str::FromStr for MergeStyle { | | |
| 85 | - type Err = Error; | | |
| 86 | - | | |
| 87 | - fn from_str(s: &str) -> Result<Self> { | | |
| 88 | - match s { | | |
| 89 | - "merge" => Ok(MergeStyle::Merge), | | |
| 90 | - "squash" => Ok(MergeStyle::Squash), | | |
| 91 | - "ff" => Ok(MergeStyle::FastForward), | | |
| 92 | - "rebase" => Ok(MergeStyle::Rebase), | | |
| 93 | - other => Err(Error::Invalid(format!("merge style {other:?}"))), | | |
| 94 | - } | | |
| 95 | - } | | |
| 96 | -} | | |
| 97 | | 72 | |
| 98 | #[cfg(test)] | 73 | #[cfg(test)] |
| 99 | mod tests { | 74 | mod tests { |
| @@ -1,51 +1,36 @@ |
| | 1 | +use crate::signed_token; |
| 1 | use base64::prelude::{BASE64_URL_SAFE_NO_PAD, Engine as _}; | 2 | use base64::prelude::{BASE64_URL_SAFE_NO_PAD, Engine as _}; |
| 2 | -use hmac::{Hmac, KeyInit, Mac}; | | |
| 3 | -use sha2::Sha256; | | |
| 4 | | 3 | |
| 5 | -type HmacSha256 = Hmac<Sha256>; | 4 | +fn framing<'a>(repo_id: &'a str, expires: &'a str) -> [&'a [u8]; 4] { |
| 6 | - | 5 | + [b"raw-v1:", repo_id.as_bytes(), b":", expires.as_bytes()] |
| 7 | -const MAC_LEN: usize = 32; | | |
| 8 | - | | |
| 9 | -fn mac_for(key: &[u8; 32], repo_id: &str, expires_unix: i64) -> HmacSha256 { | | |
| 10 | - let mut mac = | | |
| 11 | - <HmacSha256 as KeyInit>::new_from_slice(key).expect("HMAC accepts any key length"); | | |
| 12 | - mac.update(b"raw-v1:"); | | |
| 13 | - mac.update(repo_id.as_bytes()); | | |
| 14 | - mac.update(b":"); | | |
| 15 | - mac.update(expires_unix.to_string().as_bytes()); | | |
| 16 | - mac | | |
| 17 | } | 6 | } |
| 18 | | 7 | |
| 19 | pub fn sign_raw(key: &[u8; 32], repo_id: &str, expires_unix: i64) -> String { | 8 | pub fn sign_raw(key: &[u8; 32], repo_id: &str, expires_unix: i64) -> String { |
| 20 | - let tag = mac_for(key, repo_id, expires_unix).finalize().into_bytes(); | 9 | + let expires = expires_unix.to_string(); |
| 21 | - format!("{expires_unix}.{}", BASE64_URL_SAFE_NO_PAD.encode(tag)) | 10 | + let tag = signed_token::mac(key, &framing(repo_id, &expires)); |
| | 11 | + format!("{expires}.{}", BASE64_URL_SAFE_NO_PAD.encode(tag)) |
| 22 | } | 12 | } |
| 23 | | 13 | |
| 24 | pub fn verify_raw(key: &[u8; 32], token: &str, repo_id: &str, now_unix: i64) -> bool { | 14 | pub fn verify_raw(key: &[u8; 32], token: &str, repo_id: &str, now_unix: i64) -> bool { |
| 25 | let Some((expires_str, mac_str)) = token.split_once('.') else { | 15 | let Some((expires_str, mac_str)) = token.split_once('.') else { |
| 26 | return false; | 16 | return false; |
| 27 | }; | 17 | }; |
| 28 | - let Ok(expires) = expires_str.parse::<i64>() else { | 18 | + let Some(expires) = signed_token::parse_expiry(expires_str) else { |
| 29 | return false; | 19 | return false; |
| 30 | }; | 20 | }; |
| 31 | - if expires.to_string() != expires_str { | | |
| 32 | - return false; | | |
| 33 | - } | | |
| 34 | if now_unix >= expires { | 21 | if now_unix >= expires { |
| 35 | return false; | 22 | return false; |
| 36 | } | 23 | } |
| 37 | let Ok(tag) = BASE64_URL_SAFE_NO_PAD.decode(mac_str) else { | 24 | let Ok(tag) = BASE64_URL_SAFE_NO_PAD.decode(mac_str) else { |
| 38 | return false; | 25 | return false; |
| 39 | }; | 26 | }; |
| 40 | - if tag.len() != MAC_LEN { | 27 | + signed_token::verify(key, &framing(repo_id, expires_str), &tag) |
| 41 | - return false; | | |
| 42 | - } | | |
| 43 | - mac_for(key, repo_id, expires).verify_slice(&tag).is_ok() | | |
| 44 | } | 28 | } |
| 45 | | 29 | |
| 46 | #[cfg(test)] | 30 | #[cfg(test)] |
| 47 | mod tests { | 31 | mod tests { |
| 48 | use super::*; | 32 | use super::*; |
| | 33 | + use crate::signed_token::MAC_LEN; |
| 49 | | 34 | |
| 50 | const KEY: [u8; 32] = [7; 32]; | 35 | const KEY: [u8; 32] = [7; 32]; |
| 51 | const OTHER_KEY: [u8; 32] = [9; 32]; | 36 | const OTHER_KEY: [u8; 32] = [9; 32]; |
| @@ -24,19 +24,6 @@ impl Reaction { |
| 24 | Reaction::Eyes, | 24 | Reaction::Eyes, |
| 25 | ]; | 25 | ]; |
| 26 | | 26 | |
| 27 | - pub fn name(self) -> &'static str { | | |
| 28 | - match self { | | |
| 29 | - Reaction::PlusOne => "+1", | | |
| 30 | - Reaction::MinusOne => "-1", | | |
| 31 | - Reaction::Laugh => "laugh", | | |
| 32 | - Reaction::Hooray => "hooray", | | |
| 33 | - Reaction::Confused => "confused", | | |
| 34 | - Reaction::Heart => "heart", | | |
| 35 | - Reaction::Rocket => "rocket", | | |
| 36 | - Reaction::Eyes => "eyes", | | |
| 37 | - } | | |
| 38 | - } | | |
| 39 | - | | |
| 40 | pub fn emoji(self) -> &'static str { | 27 | pub fn emoji(self) -> &'static str { |
| 41 | match self { | 28 | match self { |
| 42 | Reaction::PlusOne => "\u{1f44d}", | 29 | Reaction::PlusOne => "\u{1f44d}", |
| @@ -49,12 +36,19 @@ impl Reaction { |
| 49 | Reaction::Eyes => "\u{1f440}", | 36 | Reaction::Eyes => "\u{1f440}", |
| 50 | } | 37 | } |
| 51 | } | 38 | } |
| 52 | - | | |
| 53 | - pub fn parse(name: &str) -> Option<Reaction> { | | |
| 54 | - Reaction::ALL.into_iter().find(|r| r.name() == name) | | |
| 55 | - } | | |
| 56 | } | 39 | } |
| 57 | | 40 | |
| | 41 | +string_enum!(Reaction { |
| | 42 | + PlusOne = "+1", |
| | 43 | + MinusOne = "-1", |
| | 44 | + Laugh = "laugh", |
| | 45 | + Hooray = "hooray", |
| | 46 | + Confused = "confused", |
| | 47 | + Heart = "heart", |
| | 48 | + Rocket = "rocket", |
| | 49 | + Eyes = "eyes", |
| | 50 | +}); |
| | 51 | + |
| 58 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] | 52 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 59 | pub enum ReactionTarget { | 53 | pub enum ReactionTarget { |
| 60 | Issue, | 54 | Issue, |
| @@ -63,16 +57,12 @@ pub enum ReactionTarget { |
| 63 | DiscussionComment, | 57 | DiscussionComment, |
| 64 | } | 58 | } |
| 65 | | 59 | |
| 66 | -impl ReactionTarget { | 60 | +string_enum!(ReactionTarget { |
| 67 | - pub fn as_str(self) -> &'static str { | 61 | + Issue = "issue", |
| 68 | - match self { | 62 | + Comment = "comment", |
| 69 | - ReactionTarget::Issue => "issue", | 63 | + Discussion = "discussion", |
| 70 | - ReactionTarget::Comment => "comment", | 64 | + DiscussionComment = "discussion_comment", |
| 71 | - ReactionTarget::Discussion => "discussion", | 65 | +}); |
| 72 | - ReactionTarget::DiscussionComment => "discussion_comment", | | |
| 73 | - } | | |
| 74 | - } | | |
| 75 | -} | | |
| 76 | | 66 | |
| 77 | #[derive(Debug, Clone, PartialEq, Eq)] | 67 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 78 | pub struct ReactionSummary { | 68 | pub struct ReactionSummary { |
| @@ -1,4 +1,3 @@ |
| 1 | -use crate::error::{Error, Result}; | | |
| 2 | use crate::model::Id; | 1 | use crate::model::Id; |
| 3 | | 2 | |
| 4 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] | 3 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| @@ -10,32 +9,13 @@ pub enum ReviewState { |
| 10 | Dismissed, | 9 | Dismissed, |
| 11 | } | 10 | } |
| 12 | | 11 | |
| 13 | -impl ReviewState { | 12 | +string_enum!(ReviewState { |
| 14 | - pub fn as_str(&self) -> &'static str { | 13 | + Pending = "pending", |
| 15 | - match self { | 14 | + Commented = "commented", |
| 16 | - ReviewState::Pending => "pending", | 15 | + Approved = "approved", |
| 17 | - ReviewState::Commented => "commented", | 16 | + ChangesRequested = "changes_requested", |
| 18 | - ReviewState::Approved => "approved", | 17 | + Dismissed = "dismissed", |
| 19 | - ReviewState::ChangesRequested => "changes_requested", | 18 | +}); |
| 20 | - ReviewState::Dismissed => "dismissed", | | |
| 21 | - } | | |
| 22 | - } | | |
| 23 | -} | | |
| 24 | - | | |
| 25 | -impl std::str::FromStr for ReviewState { | | |
| 26 | - type Err = Error; | | |
| 27 | - | | |
| 28 | - fn from_str(s: &str) -> Result<Self> { | | |
| 29 | - match s { | | |
| 30 | - "pending" => Ok(ReviewState::Pending), | | |
| 31 | - "commented" => Ok(ReviewState::Commented), | | |
| 32 | - "approved" => Ok(ReviewState::Approved), | | |
| 33 | - "changes_requested" => Ok(ReviewState::ChangesRequested), | | |
| 34 | - "dismissed" => Ok(ReviewState::Dismissed), | | |
| 35 | - other => Err(Error::Invalid(format!("review state {other:?}"))), | | |
| 36 | - } | | |
| 37 | - } | | |
| 38 | -} | | |
| 39 | | 19 | |
| 40 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] | 20 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] |
| 41 | pub enum Side { | 21 | pub enum Side { |
| @@ -43,26 +23,10 @@ pub enum Side { |
| 43 | New, | 23 | New, |
| 44 | } | 24 | } |
| 45 | | 25 | |
| 46 | -impl Side { | 26 | +string_enum!(Side { |
| 47 | - pub fn as_str(&self) -> &'static str { | 27 | + Old = "old", |
| 48 | - match self { | 28 | + New = "new", |
| 49 | - Side::Old => "old", | 29 | +}); |
| 50 | - Side::New => "new", | | |
| 51 | - } | | |
| 52 | - } | | |
| 53 | -} | | |
| 54 | - | | |
| 55 | -impl std::str::FromStr for Side { | | |
| 56 | - type Err = Error; | | |
| 57 | - | | |
| 58 | - fn from_str(s: &str) -> Result<Self> { | | |
| 59 | - match s { | | |
| 60 | - "old" => Ok(Side::Old), | | |
| 61 | - "new" => Ok(Side::New), | | |
| 62 | - other => Err(Error::Invalid(format!("diff side {other:?}"))), | | |
| 63 | - } | | |
| 64 | - } | | |
| 65 | -} | | |
| 66 | | 30 | |
| 67 | #[derive(Debug, Clone, PartialEq)] | 31 | #[derive(Debug, Clone, PartialEq)] |
| 68 | pub struct Review { | 32 | pub struct Review { |
| @@ -97,8 +97,7 @@ pub fn open(key: &[u8; 32], sealed: &str) -> Result<Vec<u8>> { |
| 97 | return Err(Error::Crypto("sealed value is too short".into())); | 97 | return Err(Error::Crypto("sealed value is too short".into())); |
| 98 | } | 98 | } |
| 99 | let (nonce, ciphertext) = blob.split_at(NONCE_LEN); | 99 | let (nonce, ciphertext) = blob.split_at(NONCE_LEN); |
| 100 | - let nonce = <[u8; NONCE_LEN]>::try_from(nonce) | 100 | + let nonce: [u8; NONCE_LEN] = nonce.try_into().expect("split_at yields NONCE_LEN bytes"); |
| 101 | - .map_err(|_| Error::Crypto("sealed value has a bad nonce".into()))?; | | |
| 102 | let cipher = XChaCha20Poly1305::new(key.into()); | 101 | let cipher = XChaCha20Poly1305::new(key.into()); |
| 103 | cipher | 102 | cipher |
| 104 | .decrypt(&XNonce::from(nonce), ciphertext) | 103 | .decrypt(&XNonce::from(nonce), ciphertext) |
| @@ -5,7 +5,9 @@ use std::sync::{Arc, RwLock}; |
| 5 | use ipnet::IpNet; | 5 | use ipnet::IpNet; |
| 6 | | 6 | |
| 7 | use crate::advisories::KNOWN_ECOSYSTEMS; | 7 | use crate::advisories::KNOWN_ECOSYSTEMS; |
| 8 | -use crate::config::{Config, MailTransport, OrgCreation, Registration, StorageBackend}; | 8 | +use crate::config::{ |
| | 9 | + BannerLevel, Config, MailTransport, OrgCreation, R2Jurisdiction, Registration, StorageBackend, |
| | 10 | +}; |
| 9 | use crate::error::{Error, Result}; | 11 | use crate::error::{Error, Result}; |
| 10 | | 12 | |
| 11 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] | 13 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| @@ -34,23 +36,17 @@ impl Group { |
| 34 | Group::Integrations, | 36 | Group::Integrations, |
| 35 | Group::Alerts, | 37 | Group::Alerts, |
| 36 | ]; | 38 | ]; |
| 37 | - | | |
| 38 | - pub fn slug(self) -> &'static str { | | |
| 39 | - match self { | | |
| 40 | - Group::General => "general", | | |
| 41 | - Group::Limits => "limits", | | |
| 42 | - Group::Storage => "storage", | | |
| 43 | - Group::Backups => "backups", | | |
| 44 | - Group::Integrations => "integrations", | | |
| 45 | - Group::Alerts => "alerts", | | |
| 46 | - } | | |
| 47 | - } | | |
| 48 | - | | |
| 49 | - pub fn parse(slug: &str) -> Option<Group> { | | |
| 50 | - Group::ALL.into_iter().find(|g| g.slug() == slug) | | |
| 51 | - } | | |
| 52 | } | 39 | } |
| 53 | | 40 | |
| | 41 | +string_enum!(Group { |
| | 42 | + General = "general", |
| | 43 | + Limits = "limits", |
| | 44 | + Storage = "storage", |
| | 45 | + Backups = "backups", |
| | 46 | + Integrations = "integrations", |
| | 47 | + Alerts = "alerts", |
| | 48 | +}); |
| | 49 | + |
| 54 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] | 50 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 55 | pub enum Ty { | 51 | pub enum Ty { |
| 56 | Bool, | 52 | Bool, |
| @@ -71,6 +67,9 @@ pub struct Field { |
| 71 | pub ty: Ty, | 67 | pub ty: Ty, |
| 72 | pub label: &'static str, | 68 | pub label: &'static str, |
| 73 | pub help: &'static str, | 69 | pub help: &'static str, |
| | 70 | + get: fn(&Config) -> String, |
| | 71 | + set: fn(&mut Config, &str), |
| | 72 | + check: fn(&str) -> Option<String>, |
| 74 | } | 73 | } |
| 75 | | 74 | |
| 76 | impl Field { | 75 | impl Field { |
| @@ -79,6 +78,34 @@ impl Field { |
| 79 | } | 78 | } |
| 80 | } | 79 | } |
| 81 | | 80 | |
| | 81 | +fn no_check(_: &str) -> Option<String> { |
| | 82 | + None |
| | 83 | +} |
| | 84 | + |
| | 85 | +fn expires_check(raw: &str) -> Option<String> { |
| | 86 | + (!raw.is_empty() && crate::config::parse_banner_expiry(raw).is_none()) |
| | 87 | + .then(|| "must look like 2026-12-31 18:00".to_owned()) |
| | 88 | +} |
| | 89 | + |
| | 90 | +fn message_check(raw: &str) -> Option<String> { |
| | 91 | + (raw.chars().count() > 300).then(|| "must be at most 300 characters".to_owned()) |
| | 92 | +} |
| | 93 | + |
| | 94 | +fn proxies_check(raw: &str) -> Option<String> { |
| | 95 | + split_list(raw) |
| | 96 | + .into_iter() |
| | 97 | + .find(|item| item.parse::<IpNet>().is_err() && item.parse::<IpAddr>().is_err()) |
| | 98 | + .map(|item| format!("invalid trusted proxy `{item}`")) |
| | 99 | +} |
| | 100 | + |
| | 101 | +fn ecosystems_check(raw: &str) -> Option<String> { |
| | 102 | + split_list(raw) |
| | 103 | + .into_iter() |
| | 104 | + .find(|item| !KNOWN_ECOSYSTEMS.contains(&item.as_str())) |
| | 105 | + .map(|item| format!("unknown ecosystem `{item}`")) |
| | 106 | +} |
| | 107 | + |
| | 108 | +#[allow(clippy::too_many_arguments)] |
| 82 | const fn f( | 109 | const fn f( |
| 83 | key: &'static str, | 110 | key: &'static str, |
| 84 | group: Group, | 111 | group: Group, |
| @@ -86,6 +113,8 @@ const fn f( |
| 86 | ty: Ty, | 113 | ty: Ty, |
| 87 | label: &'static str, | 114 | label: &'static str, |
| 88 | help: &'static str, | 115 | help: &'static str, |
| | 116 | + get: fn(&Config) -> String, |
| | 117 | + set: fn(&mut Config, &str), |
| 89 | ) -> Field { | 118 | ) -> Field { |
| 90 | Field { | 119 | Field { |
| 91 | key, | 120 | key, |
| @@ -94,18 +123,33 @@ const fn f( |
| 94 | ty, | 123 | ty, |
| 95 | label, | 124 | label, |
| 96 | help, | 125 | help, |
| | 126 | + get, |
| | 127 | + set, |
| | 128 | + check: no_check, |
| 97 | } | 129 | } |
| 98 | } | 130 | } |
| 99 | | 131 | |
| 100 | use Group::{Alerts, Backups, General, Integrations, Limits, Storage}; | 132 | use Group::{Alerts, Backups, General, Integrations, Limits, Storage}; |
| 101 | use Kind::{Live as L, ReadOnly as R, Restart as X}; | 133 | use Kind::{Live as L, ReadOnly as R, Restart as X}; |
| 102 | | 134 | |
| 103 | -const REGISTRATION: &[&str] = &["closed", "invite", "open"]; | 135 | +const REGISTRATION: &[&str] = &[ |
| 104 | -const BANNER_LEVEL: &[&str] = &["info", "warning"]; | 136 | + Registration::Closed.as_str(), |
| 105 | -const ORG_CREATION: &[&str] = &["all", "admin"]; | 137 | + Registration::Invite.as_str(), |
| 106 | -const MAIL_TRANSPORT: &[&str] = &["smtp", "log"]; | 138 | + Registration::Open.as_str(), |
| 107 | -const BACKEND: &[&str] = &["fs", "s3", "r2"]; | 139 | +]; |
| 108 | -const JURISDICTION: &[&str] = &["", "eu", "fedramp"]; | 140 | +const BANNER_LEVEL: &[&str] = &[BannerLevel::Info.as_str(), BannerLevel::Warning.as_str()]; |
| | 141 | +const ORG_CREATION: &[&str] = &[OrgCreation::All.as_str(), OrgCreation::Admin.as_str()]; |
| | 142 | +const MAIL_TRANSPORT: &[&str] = &[MailTransport::Smtp.as_str(), MailTransport::Log.as_str()]; |
| | 143 | +const BACKEND: &[&str] = &[ |
| | 144 | + StorageBackend::Fs.as_str(), |
| | 145 | + StorageBackend::S3.as_str(), |
| | 146 | + StorageBackend::R2.as_str(), |
| | 147 | +]; |
| | 148 | +const JURISDICTION: &[&str] = &[ |
| | 149 | + R2Jurisdiction::Global.as_str(), |
| | 150 | + R2Jurisdiction::Eu.as_str(), |
| | 151 | + R2Jurisdiction::Fedramp.as_str(), |
| | 152 | +]; |
| 109 | const MB: Ty = Ty::Uint(1, 1_048_576); | 153 | const MB: Ty = Ty::Uint(1, 1_048_576); |
| 110 | const PORT: Ty = Ty::Uint(1, 65_535); | 154 | const PORT: Ty = Ty::Uint(1, 65_535); |
| 111 | | 155 | |
| @@ -117,6 +161,8 @@ pub static FIELDS: &[Field] = &[ |
| 117 | Ty::Choice(REGISTRATION), | 161 | Ty::Choice(REGISTRATION), |
| 118 | "Registration", | 162 | "Registration", |
| 119 | "Who may create an account: closed, invite only, or open.", | 163 | "Who may create an account: closed, invite only, or open.", |
| | 164 | + |c| c.registration.as_str().into(), |
| | 165 | + |c, v| c.registration = v.parse().unwrap_or_default(), |
| 120 | ), | 166 | ), |
| 121 | f( | 167 | f( |
| 122 | "orgs.creation", | 168 | "orgs.creation", |
| @@ -125,15 +171,22 @@ pub static FIELDS: &[Field] = &[ |
| 125 | Ty::Choice(ORG_CREATION), | 171 | Ty::Choice(ORG_CREATION), |
| 126 | "Organization creation", | 172 | "Organization creation", |
| 127 | "Who may create an organization: all signed-in people, or admins only.", | 173 | "Who may create an organization: all signed-in people, or admins only.", |
| | 174 | + |c| c.orgs.creation.as_str().into(), |
| | 175 | + |c, v| c.orgs.creation = v.parse().unwrap_or_default(), |
| 128 | ), | 176 | ), |
| 129 | - f( | 177 | + Field { |
| 130 | - "banner.message", | 178 | + check: message_check, |
| 131 | - General, | 179 | + ..f( |
| 132 | - L, | 180 | + "banner.message", |
| 133 | - Ty::Text, | 181 | + General, |
| 134 | - "Announcement banner", | 182 | + L, |
| 135 | - "One line shown under the header on every page. Empty hides it.", | 183 | + Ty::Text, |
| 136 | - ), | 184 | + "Announcement banner", |
| | 185 | + "One line shown under the header on every page. Empty hides it.", |
| | 186 | + |c| c.banner.message.clone(), |
| | 187 | + |c, v| c.banner.message = v.to_owned(), |
| | 188 | + ) |
| | 189 | + }, |
| 137 | f( | 190 | f( |
| 138 | "banner.level", | 191 | "banner.level", |
| 139 | General, | 192 | General, |
| @@ -141,23 +194,50 @@ pub static FIELDS: &[Field] = &[ |
| 141 | Ty::Choice(BANNER_LEVEL), | 194 | Ty::Choice(BANNER_LEVEL), |
| 142 | "Banner level", | 195 | "Banner level", |
| 143 | "Info or warning.", | 196 | "Info or warning.", |
| | 197 | + |c| c.banner.level.as_str().into(), |
| | 198 | + |c, v| c.banner.level = v.parse().unwrap_or_default(), |
| 144 | ), | 199 | ), |
| 145 | - f( | 200 | + Field { |
| 146 | - "banner.expires", | 201 | + check: expires_check, |
| 147 | - General, | 202 | + ..f( |
| 148 | - L, | 203 | + "banner.expires", |
| 149 | - Ty::Text, | 204 | + General, |
| 150 | - "Banner expires (UTC)", | 205 | + L, |
| 151 | - "As YYYY-MM-DD HH:MM. Empty keeps the banner until it is cleared.", | 206 | + Ty::Text, |
| 152 | - ), | 207 | + "Banner expires (UTC)", |
| 153 | - f( | 208 | + "As YYYY-MM-DD HH:MM. Empty keeps the banner until it is cleared.", |
| 154 | - "trusted_proxies", | 209 | + |c| c.banner.expires.clone(), |
| 155 | - General, | 210 | + |c, v| c.banner.expires = v.to_owned(), |
| 156 | - L, | 211 | + ) |
| 157 | - Ty::List, | 212 | + }, |
| 158 | - "Trusted proxies", | 213 | + Field { |
| 159 | - "Addresses or CIDR networks whose X-Forwarded-For header is trusted. Comma separated.", | 214 | + check: proxies_check, |
| 160 | - ), | 215 | + ..f( |
| | 216 | + "trusted_proxies", |
| | 217 | + General, |
| | 218 | + L, |
| | 219 | + Ty::List, |
| | 220 | + "Trusted proxies", |
| | 221 | + "Addresses or CIDR networks whose X-Forwarded-For header is trusted. Comma separated.", |
| | 222 | + |c| { |
| | 223 | + c.trusted_proxies |
| | 224 | + .iter() |
| | 225 | + .map(ToString::to_string) |
| | 226 | + .collect::<Vec<_>>() |
| | 227 | + .join(", ") |
| | 228 | + }, |
| | 229 | + |c, v| { |
| | 230 | + c.trusted_proxies = split_list(v) |
| | 231 | + .iter() |
| | 232 | + .filter_map(|e| { |
| | 233 | + e.parse::<IpNet>() |
| | 234 | + .ok() |
| | 235 | + .or_else(|| e.parse::<IpAddr>().ok().map(IpNet::from)) |
| | 236 | + }) |
| | 237 | + .collect() |
| | 238 | + }, |
| | 239 | + ) |
| | 240 | + }, |
| 161 | f( | 241 | f( |
| 162 | "base_url", | 242 | "base_url", |
| 163 | General, | 243 | General, |
| @@ -165,6 +245,8 @@ pub static FIELDS: &[Field] = &[ |
| 165 | Ty::Text, | 245 | Ty::Text, |
| 166 | "Base URL", | 246 | "Base URL", |
| 167 | "Public URL used in links and clone URLs.", | 247 | "Public URL used in links and clone URLs.", |
| | 248 | + |c| c.base_url.clone(), |
| | 249 | + |c, v| c.base_url = v.to_owned(), |
| 168 | ), | 250 | ), |
| 169 | f( | 251 | f( |
| 170 | "user_content_base_url", | 252 | "user_content_base_url", |
| @@ -173,6 +255,8 @@ pub static FIELDS: &[Field] = &[ |
| 173 | Ty::Text, | 255 | Ty::Text, |
| 174 | "User content URL", | 256 | "User content URL", |
| 175 | "Separate origin that serves raw user files.", | 257 | "Separate origin that serves raw user files.", |
| | 258 | + |c| c.user_content_base_url.clone(), |
| | 259 | + |c, v| c.user_content_base_url = v.to_owned(), |
| 176 | ), | 260 | ), |
| 177 | f( | 261 | f( |
| 178 | "ssh_public_host", | 262 | "ssh_public_host", |
| @@ -181,6 +265,8 @@ pub static FIELDS: &[Field] = &[ |
| 181 | Ty::Text, | 265 | Ty::Text, |
| 182 | "SSH host shown", | 266 | "SSH host shown", |
| 183 | "Host in SSH clone URLs.", | 267 | "Host in SSH clone URLs.", |
| | 268 | + |c| c.ssh_public_host.clone(), |
| | 269 | + |c, v| c.ssh_public_host = v.to_owned(), |
| 184 | ), | 270 | ), |
| 185 | f( | 271 | f( |
| 186 | "ssh_public_port", | 272 | "ssh_public_port", |
| @@ -189,6 +275,8 @@ pub static FIELDS: &[Field] = &[ |
| 189 | PORT, | 275 | PORT, |
| 190 | "SSH port shown", | 276 | "SSH port shown", |
| 191 | "Port in SSH clone URLs.", | 277 | "Port in SSH clone URLs.", |
| | 278 | + |c| c.ssh_public_port.to_string(), |
| | 279 | + |c, v| c.ssh_public_port = n(v) as u16, |
| 192 | ), | 280 | ), |
| 193 | f( | 281 | f( |
| 194 | "listen", | 282 | "listen", |
| @@ -197,6 +285,8 @@ pub static FIELDS: &[Field] = &[ |
| 197 | Ty::Addr, | 285 | Ty::Addr, |
| 198 | "HTTP listen address", | 286 | "HTTP listen address", |
| 199 | "Set in the config file.", | 287 | "Set in the config file.", |
| | 288 | + |c| c.listen.to_string(), |
| | 289 | + |_, _| {}, |
| 200 | ), | 290 | ), |
| 201 | f( | 291 | f( |
| 202 | "user_content_listen", | 292 | "user_content_listen", |
| @@ -205,6 +295,8 @@ pub static FIELDS: &[Field] = &[ |
| 205 | Ty::Addr, | 295 | Ty::Addr, |
| 206 | "User content listen address", | 296 | "User content listen address", |
| 207 | "Set in the config file.", | 297 | "Set in the config file.", |
| | 298 | + |c| c.user_content_listen.to_string(), |
| | 299 | + |_, _| {}, |
| 208 | ), | 300 | ), |
| 209 | f( | 301 | f( |
| 210 | "ssh_listen", | 302 | "ssh_listen", |
| @@ -213,6 +305,8 @@ pub static FIELDS: &[Field] = &[ |
| 213 | Ty::Addr, | 305 | Ty::Addr, |
| 214 | "SSH listen address", | 306 | "SSH listen address", |
| 215 | "Set in the config file.", | 307 | "Set in the config file.", |
| | 308 | + |c| c.ssh_listen.to_string(), |
| | 309 | + |_, _| {}, |
| 216 | ), | 310 | ), |
| 217 | f( | 311 | f( |
| 218 | "database", | 312 | "database", |
| @@ -221,6 +315,8 @@ pub static FIELDS: &[Field] = &[ |
| 221 | Ty::Path, | 315 | Ty::Path, |
| 222 | "Database file", | 316 | "Database file", |
| 223 | "Set in the config file.", | 317 | "Set in the config file.", |
| | 318 | + |c| c.database.to_string_lossy().into_owned(), |
| | 319 | + |_, _| {}, |
| 224 | ), | 320 | ), |
| 225 | f( | 321 | f( |
| 226 | "data_dir", | 322 | "data_dir", |
| @@ -229,6 +325,8 @@ pub static FIELDS: &[Field] = &[ |
| 229 | Ty::Path, | 325 | Ty::Path, |
| 230 | "Data directory", | 326 | "Data directory", |
| 231 | "Set in the config file.", | 327 | "Set in the config file.", |
| | 328 | + |c| c.data_dir.to_string_lossy().into_owned(), |
| | 329 | + |_, _| {}, |
| 232 | ), | 330 | ), |
| 233 | f( | 331 | f( |
| 234 | "ci.enabled", | 332 | "ci.enabled", |
| @@ -237,6 +335,8 @@ pub static FIELDS: &[Field] = &[ |
| 237 | Ty::Bool, | 335 | Ty::Bool, |
| 238 | "CI enabled", | 336 | "CI enabled", |
| 239 | "When off, pushes and pull requests create no runs.", | 337 | "When off, pushes and pull requests create no runs.", |
| | 338 | + |c| c.ci.enabled.to_string(), |
| | 339 | + |c, v| c.ci.enabled = b(v), |
| 240 | ), | 340 | ), |
| 241 | f( | 341 | f( |
| 242 | "ci.max_log_mb", | 342 | "ci.max_log_mb", |
| @@ -245,6 +345,8 @@ pub static FIELDS: &[Field] = &[ |
| 245 | MB, | 345 | MB, |
| 246 | "Largest job log (MiB)", | 346 | "Largest job log (MiB)", |
| 247 | "A longer log is truncated.", | 347 | "A longer log is truncated.", |
| | 348 | + |c| c.ci.max_log_mb.to_string(), |
| | 349 | + |c, v| c.ci.max_log_mb = n(v), |
| 248 | ), | 350 | ), |
| 249 | f( | 351 | f( |
| 250 | "ci.max_artifact_mb", | 352 | "ci.max_artifact_mb", |
| @@ -253,6 +355,8 @@ pub static FIELDS: &[Field] = &[ |
| 253 | MB, | 355 | MB, |
| 254 | "Largest artifact (MiB)", | 356 | "Largest artifact (MiB)", |
| 255 | "", | 357 | "", |
| | 358 | + |c| c.ci.max_artifact_mb.to_string(), |
| | 359 | + |c, v| c.ci.max_artifact_mb = n(v), |
| 256 | ), | 360 | ), |
| 257 | f( | 361 | f( |
| 258 | "ci.max_artifacts_per_job", | 362 | "ci.max_artifacts_per_job", |
| @@ -261,6 +365,8 @@ pub static FIELDS: &[Field] = &[ |
| 261 | Ty::Uint(1, 100_000), | 365 | Ty::Uint(1, 100_000), |
| 262 | "Artifacts per job", | 366 | "Artifacts per job", |
| 263 | "", | 367 | "", |
| | 368 | + |c| c.ci.max_artifacts_per_job.to_string(), |
| | 369 | + |c, v| c.ci.max_artifacts_per_job = n(v) as u32, |
| 264 | ), | 370 | ), |
| 265 | f( | 371 | f( |
| 266 | "ci.max_job_artifacts_mb", | 372 | "ci.max_job_artifacts_mb", |
| @@ -269,6 +375,8 @@ pub static FIELDS: &[Field] = &[ |
| 269 | MB, | 375 | MB, |
| 270 | "Largest total of one job's artifacts (MiB)", | 376 | "Largest total of one job's artifacts (MiB)", |
| 271 | "", | 377 | "", |
| | 378 | + |c| c.ci.max_job_artifacts_mb.to_string(), |
| | 379 | + |c, v| c.ci.max_job_artifacts_mb = n(v), |
| 272 | ), | 380 | ), |
| 273 | f( | 381 | f( |
| 274 | "ci.log_retention_days", | 382 | "ci.log_retention_days", |
| @@ -277,6 +385,8 @@ pub static FIELDS: &[Field] = &[ |
| 277 | Ty::Uint(1, 36_500), | 385 | Ty::Uint(1, 36_500), |
| 278 | "Log retention (days)", | 386 | "Log retention (days)", |
| 279 | "", | 387 | "", |
| | 388 | + |c| c.ci.log_retention_days.to_string(), |
| | 389 | + |c, v| c.ci.log_retention_days = n(v), |
| 280 | ), | 390 | ), |
| 281 | f( | 391 | f( |
| 282 | "ci.artifact_retention_days", | 392 | "ci.artifact_retention_days", |
| @@ -285,6 +395,8 @@ pub static FIELDS: &[Field] = &[ |
| 285 | Ty::Uint(1, 36_500), | 395 | Ty::Uint(1, 36_500), |
| 286 | "Artifact retention (days)", | 396 | "Artifact retention (days)", |
| 287 | "", | 397 | "", |
| | 398 | + |c| c.ci.artifact_retention_days.to_string(), |
| | 399 | + |c, v| c.ci.artifact_retention_days = n(v), |
| 288 | ), | 400 | ), |
| 289 | f( | 401 | f( |
| 290 | "ci.artifact_keep_runs", | 402 | "ci.artifact_keep_runs", |
| @@ -293,6 +405,8 @@ pub static FIELDS: &[Field] = &[ |
| 293 | Ty::Uint(0, 100_000), | 405 | Ty::Uint(0, 100_000), |
| 294 | "Artifact runs kept per repo", | 406 | "Artifact runs kept per repo", |
| 295 | "0 keeps all.", | 407 | "0 keeps all.", |
| | 408 | + |c| c.ci.artifact_keep_runs.to_string(), |
| | 409 | + |c, v| c.ci.artifact_keep_runs = n(v) as u32, |
| 296 | ), | 410 | ), |
| 297 | f( | 411 | f( |
| 298 | "ci.artifact_max_total_mb", | 412 | "ci.artifact_max_total_mb", |
| @@ -301,6 +415,8 @@ pub static FIELDS: &[Field] = &[ |
| 301 | Ty::Uint(0, 100_000_000), | 415 | Ty::Uint(0, 100_000_000), |
| 302 | "Artifact disk limit (MiB)", | 416 | "Artifact disk limit (MiB)", |
| 303 | "Oldest runs' artifacts go first. 0 is no limit.", | 417 | "Oldest runs' artifacts go first. 0 is no limit.", |
| | 418 | + |c| c.ci.artifact_max_total_mb.to_string(), |
| | 419 | + |c, v| c.ci.artifact_max_total_mb = n(v), |
| 304 | ), | 420 | ), |
| 305 | f( | 421 | f( |
| 306 | "ci.registration_token_hours", | 422 | "ci.registration_token_hours", |
| @@ -309,6 +425,8 @@ pub static FIELDS: &[Field] = &[ |
| 309 | Ty::Uint(1, 8_760), | 425 | Ty::Uint(1, 8_760), |
| 310 | "Runner token lifetime (hours)", | 426 | "Runner token lifetime (hours)", |
| 311 | "How long a runner registration token stays valid.", | 427 | "How long a runner registration token stays valid.", |
| | 428 | + |c| c.ci.registration_token_hours.to_string(), |
| | 429 | + |c, v| c.ci.registration_token_hours = n(v) as u32, |
| 312 | ), | 430 | ), |
| 313 | f( | 431 | f( |
| 314 | "lfs.max_object_mb", | 432 | "lfs.max_object_mb", |
| @@ -317,6 +435,8 @@ pub static FIELDS: &[Field] = &[ |
| 317 | MB, | 435 | MB, |
| 318 | "Largest LFS object (MiB)", | 436 | "Largest LFS object (MiB)", |
| 319 | "", | 437 | "", |
| | 438 | + |c| c.lfs.max_object_mb.to_string(), |
| | 439 | + |c, v| c.lfs.max_object_mb = n(v), |
| 320 | ), | 440 | ), |
| 321 | f( | 441 | f( |
| 322 | "releases.max_asset_mb", | 442 | "releases.max_asset_mb", |
| @@ -325,6 +445,8 @@ pub static FIELDS: &[Field] = &[ |
| 325 | MB, | 445 | MB, |
| 326 | "Largest release asset (MiB)", | 446 | "Largest release asset (MiB)", |
| 327 | "", | 447 | "", |
| | 448 | + |c| c.releases.max_asset_mb.to_string(), |
| | 449 | + |c, v| c.releases.max_asset_mb = n(v), |
| 328 | ), | 450 | ), |
| 329 | f( | 451 | f( |
| 330 | "storage.backend", | 452 | "storage.backend", |
| @@ -333,6 +455,8 @@ pub static FIELDS: &[Field] = &[ |
| 333 | Ty::Choice(BACKEND), | 455 | Ty::Choice(BACKEND), |
| 334 | "Backend", | 456 | "Backend", |
| 335 | "Where release assets and CI artifacts live: fs, r2 or s3.", | 457 | "Where release assets and CI artifacts live: fs, r2 or s3.", |
| | 458 | + |c| c.storage.backend.as_str().into(), |
| | 459 | + |c, v| c.storage.backend = v.parse().unwrap_or_default(), |
| 336 | ), | 460 | ), |
| 337 | f( | 461 | f( |
| 338 | "storage.r2.account_id", | 462 | "storage.r2.account_id", |
| @@ -341,8 +465,19 @@ pub static FIELDS: &[Field] = &[ |
| 341 | Ty::Text, | 465 | Ty::Text, |
| 342 | "R2 account id", | 466 | "R2 account id", |
| 343 | "32 character hex string from the Cloudflare dashboard.", | 467 | "32 character hex string from the Cloudflare dashboard.", |
| | 468 | + |c| c.storage.r2.account_id.clone(), |
| | 469 | + |c, v| c.storage.r2.account_id = v.to_owned(), |
| | 470 | + ), |
| | 471 | + f( |
| | 472 | + "storage.r2.bucket", |
| | 473 | + Storage, |
| | 474 | + X, |
| | 475 | + Ty::Text, |
| | 476 | + "R2 bucket", |
| | 477 | + "", |
| | 478 | + |c| c.storage.r2.bucket.clone(), |
| | 479 | + |c, v| c.storage.r2.bucket = v.to_owned(), |
| 344 | ), | 480 | ), |
| 345 | - f("storage.r2.bucket", Storage, X, Ty::Text, "R2 bucket", ""), | | |
| 346 | f( | 481 | f( |
| 347 | "storage.r2.jurisdiction", | 482 | "storage.r2.jurisdiction", |
| 348 | Storage, | 483 | Storage, |
| @@ -350,6 +485,8 @@ pub static FIELDS: &[Field] = &[ |
| 350 | Ty::Choice(JURISDICTION), | 485 | Ty::Choice(JURISDICTION), |
| 351 | "R2 jurisdiction", | 486 | "R2 jurisdiction", |
| 352 | "eu, fedramp, or empty for the global default.", | 487 | "eu, fedramp, or empty for the global default.", |
| | 488 | + |c| c.storage.r2.jurisdiction.as_str().into(), |
| | 489 | + |c, v| c.storage.r2.jurisdiction = v.parse().unwrap_or_default(), |
| 353 | ), | 490 | ), |
| 354 | f( | 491 | f( |
| 355 | "storage.r2.prefix", | 492 | "storage.r2.prefix", |
| @@ -358,6 +495,8 @@ pub static FIELDS: &[Field] = &[ |
| 358 | Ty::Text, | 495 | Ty::Text, |
| 359 | "R2 key prefix", | 496 | "R2 key prefix", |
| 360 | "", | 497 | "", |
| | 498 | + |c| c.storage.r2.prefix.clone(), |
| | 499 | + |c, v| c.storage.r2.prefix = v.to_owned(), |
| 361 | ), | 500 | ), |
| 362 | f( | 501 | f( |
| 363 | "storage.r2.access_key_id", | 502 | "storage.r2.access_key_id", |
| @@ -366,6 +505,8 @@ pub static FIELDS: &[Field] = &[ |
| 366 | Ty::Text, | 505 | Ty::Text, |
| 367 | "R2 access key id", | 506 | "R2 access key id", |
| 368 | "", | 507 | "", |
| | 508 | + |c| c.storage.r2.access_key_id.clone(), |
| | 509 | + |c, v| c.storage.r2.access_key_id = v.to_owned(), |
| 369 | ), | 510 | ), |
| 370 | f( | 511 | f( |
| 371 | "storage.r2.secret_access_key_file", | 512 | "storage.r2.secret_access_key_file", |
| @@ -374,9 +515,35 @@ pub static FIELDS: &[Field] = &[ |
| 374 | Ty::Path, | 515 | Ty::Path, |
| 375 | "R2 secret key file", | 516 | "R2 secret key file", |
| 376 | "Path of the file that holds the secret access key. The key itself is never read here.", | 517 | "Path of the file that holds the secret access key. The key itself is never read here.", |
| | 518 | + |c| { |
| | 519 | + c.storage |
| | 520 | + .r2 |
| | 521 | + .secret_access_key_file |
| | 522 | + .to_string_lossy() |
| | 523 | + .into_owned() |
| | 524 | + }, |
| | 525 | + |c, v| c.storage.r2.secret_access_key_file = v.into(), |
| | 526 | + ), |
| | 527 | + f( |
| | 528 | + "storage.s3.bucket", |
| | 529 | + Storage, |
| | 530 | + X, |
| | 531 | + Ty::Text, |
| | 532 | + "S3 bucket", |
| | 533 | + "", |
| | 534 | + |c| c.storage.s3.bucket.clone(), |
| | 535 | + |c, v| c.storage.s3.bucket = v.to_owned(), |
| | 536 | + ), |
| | 537 | + f( |
| | 538 | + "storage.s3.region", |
| | 539 | + Storage, |
| | 540 | + X, |
| | 541 | + Ty::Text, |
| | 542 | + "S3 region", |
| | 543 | + "", |
| | 544 | + |c| c.storage.s3.region.clone(), |
| | 545 | + |c, v| c.storage.s3.region = v.to_owned(), |
| 377 | ), | 546 | ), |
| 378 | - f("storage.s3.bucket", Storage, X, Ty::Text, "S3 bucket", ""), | | |
| 379 | - f("storage.s3.region", Storage, X, Ty::Text, "S3 region", ""), | | |
| 380 | f( | 547 | f( |
| 381 | "storage.s3.endpoint", | 548 | "storage.s3.endpoint", |
| 382 | Storage, | 549 | Storage, |
| @@ -384,6 +551,8 @@ pub static FIELDS: &[Field] = &[ |
| 384 | Ty::Text, | 551 | Ty::Text, |
| 385 | "S3 endpoint", | 552 | "S3 endpoint", |
| 386 | "Leave empty for AWS.", | 553 | "Leave empty for AWS.", |
| | 554 | + |c| c.storage.s3.endpoint.clone(), |
| | 555 | + |c, v| c.storage.s3.endpoint = v.to_owned(), |
| 387 | ), | 556 | ), |
| 388 | f( | 557 | f( |
| 389 | "storage.s3.prefix", | 558 | "storage.s3.prefix", |
| @@ -392,6 +561,8 @@ pub static FIELDS: &[Field] = &[ |
| 392 | Ty::Text, | 561 | Ty::Text, |
| 393 | "S3 key prefix", | 562 | "S3 key prefix", |
| 394 | "", | 563 | "", |
| | 564 | + |c| c.storage.s3.prefix.clone(), |
| | 565 | + |c, v| c.storage.s3.prefix = v.to_owned(), |
| 395 | ), | 566 | ), |
| 396 | f( | 567 | f( |
| 397 | "storage.s3.access_key_id", | 568 | "storage.s3.access_key_id", |
| @@ -400,6 +571,8 @@ pub static FIELDS: &[Field] = &[ |
| 400 | Ty::Text, | 571 | Ty::Text, |
| 401 | "S3 access key id", | 572 | "S3 access key id", |
| 402 | "", | 573 | "", |
| | 574 | + |c| c.storage.s3.access_key_id.clone(), |
| | 575 | + |c, v| c.storage.s3.access_key_id = v.to_owned(), |
| 403 | ), | 576 | ), |
| 404 | f( | 577 | f( |
| 405 | "storage.s3.secret_access_key_file", | 578 | "storage.s3.secret_access_key_file", |
| @@ -408,6 +581,14 @@ pub static FIELDS: &[Field] = &[ |
| 408 | Ty::Path, | 581 | Ty::Path, |
| 409 | "S3 secret key file", | 582 | "S3 secret key file", |
| 410 | "Path of the file that holds the secret access key.", | 583 | "Path of the file that holds the secret access key.", |
| | 584 | + |c| { |
| | 585 | + c.storage |
| | 586 | + .s3 |
| | 587 | + .secret_access_key_file |
| | 588 | + .to_string_lossy() |
| | 589 | + .into_owned() |
| | 590 | + }, |
| | 591 | + |c, v| c.storage.s3.secret_access_key_file = v.into(), |
| 411 | ), | 592 | ), |
| 412 | f( | 593 | f( |
| 413 | "storage.s3.allow_http", | 594 | "storage.s3.allow_http", |
| @@ -416,6 +597,8 @@ pub static FIELDS: &[Field] = &[ |
| 416 | Ty::Bool, | 597 | Ty::Bool, |
| 417 | "S3 allow http", | 598 | "S3 allow http", |
| 418 | "", | 599 | "", |
| | 600 | + |c| c.storage.s3.allow_http.to_string(), |
| | 601 | + |c, v| c.storage.s3.allow_http = b(v), |
| 419 | ), | 602 | ), |
| 420 | f( | 603 | f( |
| 421 | "storage.s3.virtual_hosted_style", | 604 | "storage.s3.virtual_hosted_style", |
| @@ -424,6 +607,8 @@ pub static FIELDS: &[Field] = &[ |
| 424 | Ty::Bool, | 607 | Ty::Bool, |
| 425 | "S3 virtual hosted style", | 608 | "S3 virtual hosted style", |
| 426 | "", | 609 | "", |
| | 610 | + |c| c.storage.s3.virtual_hosted_style.to_string(), |
| | 611 | + |c, v| c.storage.s3.virtual_hosted_style = b(v), |
| 427 | ), | 612 | ), |
| 428 | f( | 613 | f( |
| 429 | "backup.dir", | 614 | "backup.dir", |
| @@ -432,6 +617,8 @@ pub static FIELDS: &[Field] = &[ |
| 432 | Ty::Path, | 617 | Ty::Path, |
| 433 | "Backup directory", | 618 | "Backup directory", |
| 434 | "Empty turns scheduled backups off.", | 619 | "Empty turns scheduled backups off.", |
| | 620 | + |c| c.backup.dir.to_string_lossy().into_owned(), |
| | 621 | + |c, v| c.backup.dir = v.into(), |
| 435 | ), | 622 | ), |
| 436 | f( | 623 | f( |
| 437 | "backup.interval_hours", | 624 | "backup.interval_hours", |
| @@ -440,6 +627,8 @@ pub static FIELDS: &[Field] = &[ |
| 440 | Ty::Uint(1, 8_760), | 627 | Ty::Uint(1, 8_760), |
| 441 | "Backup interval (hours)", | 628 | "Backup interval (hours)", |
| 442 | "", | 629 | "", |
| | 630 | + |c| c.backup.interval_hours.to_string(), |
| | 631 | + |c, v| c.backup.interval_hours = n(v), |
| 443 | ), | 632 | ), |
| 444 | f( | 633 | f( |
| 445 | "backup.keep", | 634 | "backup.keep", |
| @@ -448,6 +637,8 @@ pub static FIELDS: &[Field] = &[ |
| 448 | Ty::Uint(1, 10_000), | 637 | Ty::Uint(1, 10_000), |
| 449 | "Backup sets kept", | 638 | "Backup sets kept", |
| 450 | "", | 639 | "", |
| | 640 | + |c| c.backup.keep.to_string(), |
| | 641 | + |c, v| c.backup.keep = n(v) as usize, |
| 451 | ), | 642 | ), |
| 452 | f( | 643 | f( |
| 453 | "backup.fsck_interval_days", | 644 | "backup.fsck_interval_days", |
| @@ -456,6 +647,8 @@ pub static FIELDS: &[Field] = &[ |
| 456 | Ty::Uint(1, 3_650), | 647 | Ty::Uint(1, 3_650), |
| 457 | "fsck interval (days)", | 648 | "fsck interval (days)", |
| 458 | "", | 649 | "", |
| | 650 | + |c| c.backup.fsck_interval_days.to_string(), |
| | 651 | + |c, v| c.backup.fsck_interval_days = n(v), |
| 459 | ), | 652 | ), |
| 460 | f( | 653 | f( |
| 461 | "backup.healthcheck_url", | 654 | "backup.healthcheck_url", |
| @@ -464,6 +657,8 @@ pub static FIELDS: &[Field] = &[ |
| 464 | Ty::Secret, | 657 | Ty::Secret, |
| 465 | "Backup healthcheck URL", | 658 | "Backup healthcheck URL", |
| 466 | "May hold a token, so it is write-only.", | 659 | "May hold a token, so it is write-only.", |
| | 660 | + |c| c.backup.healthcheck_url.clone(), |
| | 661 | + |c, v| c.backup.healthcheck_url = v.to_owned(), |
| 467 | ), | 662 | ), |
| 468 | f( | 663 | f( |
| 469 | "replication.target", | 664 | "replication.target", |
| @@ -472,6 +667,8 @@ pub static FIELDS: &[Field] = &[ |
| 472 | Ty::Text, | 667 | Ty::Text, |
| 473 | "Replication target", | 668 | "Replication target", |
| 474 | "Empty turns standby replication off.", | 669 | "Empty turns standby replication off.", |
| | 670 | + |c| c.replication.target.clone(), |
| | 671 | + |c, v| c.replication.target = v.to_owned(), |
| 475 | ), | 672 | ), |
| 476 | f( | 673 | f( |
| 477 | "replication.ssh_port", | 674 | "replication.ssh_port", |
| @@ -480,6 +677,8 @@ pub static FIELDS: &[Field] = &[ |
| 480 | PORT, | 677 | PORT, |
| 481 | "Replication SSH port", | 678 | "Replication SSH port", |
| 482 | "", | 679 | "", |
| | 680 | + |c| c.replication.ssh_port.to_string(), |
| | 681 | + |c, v| c.replication.ssh_port = n(v) as u16, |
| 483 | ), | 682 | ), |
| 484 | f( | 683 | f( |
| 485 | "replication.identity_file", | 684 | "replication.identity_file", |
| @@ -488,6 +687,8 @@ pub static FIELDS: &[Field] = &[ |
| 488 | Ty::Path, | 687 | Ty::Path, |
| 489 | "Replication identity file", | 688 | "Replication identity file", |
| 490 | "", | 689 | "", |
| | 690 | + |c| c.replication.identity_file.to_string_lossy().into_owned(), |
| | 691 | + |c, v| c.replication.identity_file = v.into(), |
| 491 | ), | 692 | ), |
| 492 | f( | 693 | f( |
| 493 | "replication.known_hosts_file", | 694 | "replication.known_hosts_file", |
| @@ -496,6 +697,13 @@ pub static FIELDS: &[Field] = &[ |
| 496 | Ty::Path, | 697 | Ty::Path, |
| 497 | "Replication known hosts file", | 698 | "Replication known hosts file", |
| 498 | "", | 699 | "", |
| | 700 | + |c| { |
| | 701 | + c.replication |
| | 702 | + .known_hosts_file |
| | 703 | + .to_string_lossy() |
| | 704 | + .into_owned() |
| | 705 | + }, |
| | 706 | + |c, v| c.replication.known_hosts_file = v.into(), |
| 499 | ), | 707 | ), |
| 500 | f( | 708 | f( |
| 501 | "replication.db_snapshot_minutes", | 709 | "replication.db_snapshot_minutes", |
| @@ -504,6 +712,8 @@ pub static FIELDS: &[Field] = &[ |
| 504 | Ty::Uint(1, 525_600), | 712 | Ty::Uint(1, 525_600), |
| 505 | "Database snapshot (minutes)", | 713 | "Database snapshot (minutes)", |
| 506 | "", | 714 | "", |
| | 715 | + |c| c.replication.db_snapshot_minutes.to_string(), |
| | 716 | + |c, v| c.replication.db_snapshot_minutes = n(v), |
| 507 | ), | 717 | ), |
| 508 | f( | 718 | f( |
| 509 | "replication.reconcile_minutes", | 719 | "replication.reconcile_minutes", |
| @@ -512,6 +722,8 @@ pub static FIELDS: &[Field] = &[ |
| 512 | Ty::Uint(1, 525_600), | 722 | Ty::Uint(1, 525_600), |
| 513 | "Reconcile (minutes)", | 723 | "Reconcile (minutes)", |
| 514 | "", | 724 | "", |
| | 725 | + |c| c.replication.reconcile_minutes.to_string(), |
| | 726 | + |c, v| c.replication.reconcile_minutes = n(v), |
| 515 | ), | 727 | ), |
| 516 | f( | 728 | f( |
| 517 | "replication.healthcheck_url", | 729 | "replication.healthcheck_url", |
| @@ -520,6 +732,8 @@ pub static FIELDS: &[Field] = &[ |
| 520 | Ty::Secret, | 732 | Ty::Secret, |
| 521 | "Replication healthcheck URL", | 733 | "Replication healthcheck URL", |
| 522 | "May hold a token, so it is write-only.", | 734 | "May hold a token, so it is write-only.", |
| | 735 | + |c| c.replication.healthcheck_url.clone(), |
| | 736 | + |c, v| c.replication.healthcheck_url = v.to_owned(), |
| 523 | ), | 737 | ), |
| 524 | f( | 738 | f( |
| 525 | "webhooks.allow_http", | 739 | "webhooks.allow_http", |
| @@ -528,6 +742,8 @@ pub static FIELDS: &[Field] = &[ |
| 528 | Ty::Bool, | 742 | Ty::Bool, |
| 529 | "Allow http webhooks", | 743 | "Allow http webhooks", |
| 530 | "Permit http:// hook URLs besides https://.", | 744 | "Permit http:// hook URLs besides https://.", |
| | 745 | + |c| c.webhooks.allow_http.to_string(), |
| | 746 | + |c, v| c.webhooks.allow_http = b(v), |
| 531 | ), | 747 | ), |
| 532 | f( | 748 | f( |
| 533 | "webhooks.allowed_hosts", | 749 | "webhooks.allowed_hosts", |
| @@ -536,6 +752,8 @@ pub static FIELDS: &[Field] = &[ |
| 536 | Ty::List, | 752 | Ty::List, |
| 537 | "Webhook allowed hosts", | 753 | "Webhook allowed hosts", |
| 538 | "Hostnames or CIDR networks reachable even when they resolve to internal addresses. Comma separated.", | 754 | "Hostnames or CIDR networks reachable even when they resolve to internal addresses. Comma separated.", |
| | 755 | + |c| c.webhooks.allowed_hosts.join(", "), |
| | 756 | + |c, v| c.webhooks.allowed_hosts = split_list(v), |
| 539 | ), | 757 | ), |
| 540 | f( | 758 | f( |
| 541 | "mail.transport", | 759 | "mail.transport", |
| @@ -544,6 +762,8 @@ pub static FIELDS: &[Field] = &[ |
| 544 | Ty::Choice(MAIL_TRANSPORT), | 762 | Ty::Choice(MAIL_TRANSPORT), |
| 545 | "Mail transport", | 763 | "Mail transport", |
| 546 | "smtp sends mail, log writes it to a directory. The SMTP account is on the Mail page.", | 764 | "smtp sends mail, log writes it to a directory. The SMTP account is on the Mail page.", |
| | 765 | + |c| c.mail.transport.as_str().into(), |
| | 766 | + |c, v| c.mail.transport = v.parse().unwrap_or_default(), |
| 547 | ), | 767 | ), |
| 548 | f( | 768 | f( |
| 549 | "advisories.enabled", | 769 | "advisories.enabled", |
| @@ -552,15 +772,22 @@ pub static FIELDS: &[Field] = &[ |
| 552 | Ty::Bool, | 772 | Ty::Bool, |
| 553 | "Security advisories", | 773 | "Security advisories", |
| 554 | "Download OSV dumps and scan lockfiles.", | 774 | "Download OSV dumps and scan lockfiles.", |
| | 775 | + |c| c.advisories.enabled.to_string(), |
| | 776 | + |c, v| c.advisories.enabled = b(v), |
| 555 | ), | 777 | ), |
| 556 | - f( | 778 | + Field { |
| 557 | - "advisories.ecosystems", | 779 | + check: ecosystems_check, |
| 558 | - Integrations, | 780 | + ..f( |
| 559 | - X, | 781 | + "advisories.ecosystems", |
| 560 | - Ty::List, | 782 | + Integrations, |
| 561 | - "Advisory ecosystems", | 783 | + X, |
| 562 | - "Any of crates.io, npm, Go. Comma separated.", | 784 | + Ty::List, |
| 563 | - ), | 785 | + "Advisory ecosystems", |
| | 786 | + "Any of crates.io, npm, Go. Comma separated.", |
| | 787 | + |c| c.advisories.ecosystems.join(", "), |
| | 788 | + |c, v| c.advisories.ecosystems = split_list(v), |
| | 789 | + ) |
| | 790 | + }, |
| 564 | f( | 791 | f( |
| 565 | "advisories.refresh_hours", | 792 | "advisories.refresh_hours", |
| 566 | Integrations, | 793 | Integrations, |
| @@ -568,6 +795,8 @@ pub static FIELDS: &[Field] = &[ |
| 568 | Ty::Uint(1, 8_760), | 795 | Ty::Uint(1, 8_760), |
| 569 | "Advisory refresh (hours)", | 796 | "Advisory refresh (hours)", |
| 570 | "", | 797 | "", |
| | 798 | + |c| c.advisories.refresh_hours.to_string(), |
| | 799 | + |c, v| c.advisories.refresh_hours = n(v), |
| 571 | ), | 800 | ), |
| 572 | f( | 801 | f( |
| 573 | "self_update.enabled", | 802 | "self_update.enabled", |
| @@ -576,6 +805,8 @@ pub static FIELDS: &[Field] = &[ |
| 576 | Ty::Bool, | 805 | Ty::Bool, |
| 577 | "Self-update", | 806 | "Self-update", |
| 578 | "Deploy the artifact of a green run of the forge's own repo.", | 807 | "Deploy the artifact of a green run of the forge's own repo.", |
| | 808 | + |c| c.self_update.enabled.to_string(), |
| | 809 | + |c, v| c.self_update.enabled = b(v), |
| 579 | ), | 810 | ), |
| 580 | f( | 811 | f( |
| 581 | "self_update.repo", | 812 | "self_update.repo", |
| @@ -584,6 +815,8 @@ pub static FIELDS: &[Field] = &[ |
| 584 | Ty::Text, | 815 | Ty::Text, |
| 585 | "Self-update repo", | 816 | "Self-update repo", |
| 586 | "As owner/name.", | 817 | "As owner/name.", |
| | 818 | + |c| c.self_update.repo.clone(), |
| | 819 | + |c, v| c.self_update.repo = v.to_owned(), |
| 587 | ), | 820 | ), |
| 588 | f( | 821 | f( |
| 589 | "self_update.branch", | 822 | "self_update.branch", |
| @@ -592,6 +825,8 @@ pub static FIELDS: &[Field] = &[ |
| 592 | Ty::Text, | 825 | Ty::Text, |
| 593 | "Self-update branch", | 826 | "Self-update branch", |
| 594 | "", | 827 | "", |
| | 828 | + |c| c.self_update.branch.clone(), |
| | 829 | + |c, v| c.self_update.branch = v.to_owned(), |
| 595 | ), | 830 | ), |
| 596 | f( | 831 | f( |
| 597 | "self_update.job", | 832 | "self_update.job", |
| @@ -600,6 +835,8 @@ pub static FIELDS: &[Field] = &[ |
| 600 | Ty::Text, | 835 | Ty::Text, |
| 601 | "Self-update job", | 836 | "Self-update job", |
| 602 | "", | 837 | "", |
| | 838 | + |c| c.self_update.job.clone(), |
| | 839 | + |c, v| c.self_update.job = v.to_owned(), |
| 603 | ), | 840 | ), |
| 604 | f( | 841 | f( |
| 605 | "self_update.artifact", | 842 | "self_update.artifact", |
| @@ -608,6 +845,8 @@ pub static FIELDS: &[Field] = &[ |
| 608 | Ty::Text, | 845 | Ty::Text, |
| 609 | "Self-update artifact", | 846 | "Self-update artifact", |
| 610 | "{target} becomes this server's arch-os, e.g. forge-{target} is forge-x86_64-linux.", | 847 | "{target} becomes this server's arch-os, e.g. forge-{target} is forge-x86_64-linux.", |
| | 848 | + |c| c.self_update.artifact.clone(), |
| | 849 | + |c, v| c.self_update.artifact = v.to_owned(), |
| 611 | ), | 850 | ), |
| 612 | f( | 851 | f( |
| 613 | "alerts.enabled", | 852 | "alerts.enabled", |
| @@ -616,6 +855,8 @@ pub static FIELDS: &[Field] = &[ |
| 616 | Ty::Bool, | 855 | Ty::Bool, |
| 617 | "Admin alerts", | 856 | "Admin alerts", |
| 618 | "Master switch. Off raises and sends nothing.", | 857 | "Master switch. Off raises and sends nothing.", |
| | 858 | + |c| c.alerts.enabled.to_string(), |
| | 859 | + |c, v| c.alerts.enabled = b(v), |
| 619 | ), | 860 | ), |
| 620 | f( | 861 | f( |
| 621 | "alerts.email", | 862 | "alerts.email", |
| @@ -624,6 +865,8 @@ pub static FIELDS: &[Field] = &[ |
| 624 | Ty::Bool, | 865 | Ty::Bool, |
| 625 | "Email alerts", | 866 | "Email alerts", |
| 626 | "Also email the admins who have a verified address.", | 867 | "Also email the admins who have a verified address.", |
| | 868 | + |c| c.alerts.email.to_string(), |
| | 869 | + |c, v| c.alerts.email = b(v), |
| 627 | ), | 870 | ), |
| 628 | f( | 871 | f( |
| 629 | "alerts.runner_offline_minutes", | 872 | "alerts.runner_offline_minutes", |
| @@ -632,6 +875,8 @@ pub static FIELDS: &[Field] = &[ |
| 632 | Ty::Uint(1, 1_440), | 875 | Ty::Uint(1, 1_440), |
| 633 | "Runner offline after (minutes)", | 876 | "Runner offline after (minutes)", |
| 634 | "A runner with no heartbeat for this long raises an alert.", | 877 | "A runner with no heartbeat for this long raises an alert.", |
| | 878 | + |c| c.alerts.runner_offline_minutes.to_string(), |
| | 879 | + |c, v| c.alerts.runner_offline_minutes = n(v), |
| 635 | ), | 880 | ), |
| 636 | f( | 881 | f( |
| 637 | "alerts.disk_free_percent", | 882 | "alerts.disk_free_percent", |
| @@ -640,6 +885,8 @@ pub static FIELDS: &[Field] = &[ |
| 640 | Ty::Uint(1, 90), | 885 | Ty::Uint(1, 90), |
| 641 | "Low disk space (percent free)", | 886 | "Low disk space (percent free)", |
| 642 | "Alert when the data directory has less than this free.", | 887 | "Alert when the data directory has less than this free.", |
| | 888 | + |c| c.alerts.disk_free_percent.to_string(), |
| | 889 | + |c, v| c.alerts.disk_free_percent = n(v), |
| 643 | ), | 890 | ), |
| 644 | f( | 891 | f( |
| 645 | "alerts.disk_free_gib", | 892 | "alerts.disk_free_gib", |
| @@ -648,6 +895,8 @@ pub static FIELDS: &[Field] = &[ |
| 648 | Ty::Uint(0, 100_000), | 895 | Ty::Uint(0, 100_000), |
| 649 | "Low disk space (GiB free)", | 896 | "Low disk space (GiB free)", |
| 650 | "Also alert under this many GiB. 0 turns this check off.", | 897 | "Also alert under this many GiB. 0 turns this check off.", |
| | 898 | + |c| c.alerts.disk_free_gib.to_string(), |
| | 899 | + |c, v| c.alerts.disk_free_gib = n(v), |
| 651 | ), | 900 | ), |
| 652 | f( | 901 | f( |
| 653 | "alerts.on_runner_offline", | 902 | "alerts.on_runner_offline", |
| @@ -656,6 +905,8 @@ pub static FIELDS: &[Field] = &[ |
| 656 | Ty::Bool, | 905 | Ty::Bool, |
| 657 | "Runner offline alerts", | 906 | "Runner offline alerts", |
| 658 | "", | 907 | "", |
| | 908 | + |c| c.alerts.on_runner_offline.to_string(), |
| | 909 | + |c, v| c.alerts.on_runner_offline = b(v), |
| 659 | ), | 910 | ), |
| 660 | f( | 911 | f( |
| 661 | "alerts.on_backup", | 912 | "alerts.on_backup", |
| @@ -664,6 +915,8 @@ pub static FIELDS: &[Field] = &[ |
| 664 | Ty::Bool, | 915 | Ty::Bool, |
| 665 | "Backup alerts", | 916 | "Backup alerts", |
| 666 | "Failed, unverified or overdue backups, and failed fsck runs.", | 917 | "Failed, unverified or overdue backups, and failed fsck runs.", |
| | 918 | + |c| c.alerts.on_backup.to_string(), |
| | 919 | + |c, v| c.alerts.on_backup = b(v), |
| 667 | ), | 920 | ), |
| 668 | f( | 921 | f( |
| 669 | "alerts.on_disk", | 922 | "alerts.on_disk", |
| @@ -672,6 +925,8 @@ pub static FIELDS: &[Field] = &[ |
| 672 | Ty::Bool, | 925 | Ty::Bool, |
| 673 | "Disk space alerts", | 926 | "Disk space alerts", |
| 674 | "", | 927 | "", |
| | 928 | + |c| c.alerts.on_disk.to_string(), |
| | 929 | + |c, v| c.alerts.on_disk = b(v), |
| 675 | ), | 930 | ), |
| 676 | f( | 931 | f( |
| 677 | "alerts.on_ci_killed", | 932 | "alerts.on_ci_killed", |
| @@ -680,6 +935,8 @@ pub static FIELDS: &[Field] = &[ |
| 680 | Ty::Bool, | 935 | Ty::Bool, |
| 681 | "Killed CI job alerts", | 936 | "Killed CI job alerts", |
| 682 | "Jobs killed by SIGKILL or the OOM killer, once per run.", | 937 | "Jobs killed by SIGKILL or the OOM killer, once per run.", |
| | 938 | + |c| c.alerts.on_ci_killed.to_string(), |
| | 939 | + |c, v| c.alerts.on_ci_killed = b(v), |
| 683 | ), | 940 | ), |
| 684 | f( | 941 | f( |
| 685 | "alerts.on_self_update", | 942 | "alerts.on_self_update", |
| @@ -688,6 +945,8 @@ pub static FIELDS: &[Field] = &[ |
| 688 | Ty::Bool, | 945 | Ty::Bool, |
| 689 | "Self-update alerts", | 946 | "Self-update alerts", |
| 690 | "Deployed, failed, and server restarted.", | 947 | "Deployed, failed, and server restarted.", |
| | 948 | + |c| c.alerts.on_self_update.to_string(), |
| | 949 | + |c, v| c.alerts.on_self_update = b(v), |
| 691 | ), | 950 | ), |
| 692 | f( | 951 | f( |
| 693 | "alerts.on_replication", | 952 | "alerts.on_replication", |
| @@ -696,6 +955,8 @@ pub static FIELDS: &[Field] = &[ |
| 696 | Ty::Bool, | 955 | Ty::Bool, |
| 697 | "Replication alerts", | 956 | "Replication alerts", |
| 698 | "Standby failing or lagging.", | 957 | "Standby failing or lagging.", |
| | 958 | + |c| c.alerts.on_replication.to_string(), |
| | 959 | + |c, v| c.alerts.on_replication = b(v), |
| 699 | ), | 960 | ), |
| 700 | ]; | 961 | ]; |
| 701 | | 962 | |
| @@ -753,14 +1014,8 @@ pub fn normalize(field: &Field, raw: &str) -> Result<String> { |
| 753 | "must be one line of at most 1024 characters", | 1014 | "must be one line of at most 1024 characters", |
| 754 | )); | 1015 | )); |
| 755 | } | 1016 | } |
| 756 | - if field.key == "banner.expires" | 1017 | + if let Some(why) = (field.check)(raw) { |
| 757 | - && !raw.is_empty() | 1018 | + return Err(invalid(field, &why)); |
| 758 | - && crate::config::parse_banner_expiry(raw).is_none() | | |
| 759 | - { | | |
| 760 | - return Err(invalid(field, "must look like 2026-12-31 18:00")); | | |
| 761 | - } | | |
| 762 | - if field.key == "banner.message" && raw.chars().count() > 300 { | | |
| 763 | - return Err(invalid(field, "must be at most 300 characters")); | | |
| 764 | } | 1019 | } |
| 765 | Ok(raw.to_owned()) | 1020 | Ok(raw.to_owned()) |
| 766 | } | 1021 | } |
| @@ -772,19 +1027,8 @@ pub fn normalize(field: &Field, raw: &str) -> Result<String> { |
| 772 | { | 1027 | { |
| 773 | return Err(invalid(field, "has an entry that is too long")); | 1028 | return Err(invalid(field, "has an entry that is too long")); |
| 774 | } | 1029 | } |
| 775 | - if field.key == "trusted_proxies" { | 1030 | + if let Some(why) = (field.check)(raw) { |
| 776 | - for item in &items { | 1031 | + return Err(invalid(field, &why)); |
| 777 | - if item.parse::<IpNet>().is_err() && item.parse::<IpAddr>().is_err() { | | |
| 778 | - return Err(invalid(field, &format!("invalid trusted proxy `{item}`"))); | | |
| 779 | - } | | |
| 780 | - } | | |
| 781 | - } | | |
| 782 | - if field.key == "advisories.ecosystems" { | | |
| 783 | - for item in &items { | | |
| 784 | - if !KNOWN_ECOSYSTEMS.contains(&item.as_str()) { | | |
| 785 | - return Err(invalid(field, &format!("unknown ecosystem `{item}`"))); | | |
| 786 | - } | | |
| 787 | - } | | |
| 788 | } | 1032 | } |
| 789 | Ok(items.join(", ")) | 1033 | Ok(items.join(", ")) |
| 790 | } | 1034 | } |
| @@ -799,121 +1043,8 @@ fn n(v: &str) -> u64 { |
| 799 | v.parse().unwrap_or_default() | 1043 | v.parse().unwrap_or_default() |
| 800 | } | 1044 | } |
| 801 | | 1045 | |
| 802 | -fn choice<T: Copy>(v: &str, table: &[(&str, T)], fallback: T) -> T { | | |
| 803 | - table | | |
| 804 | - .iter() | | |
| 805 | - .find(|(name, _)| *name == v) | | |
| 806 | - .map_or(fallback, |(_, t)| *t) | | |
| 807 | -} | | |
| 808 | - | | |
| 809 | -fn backend_name(b: StorageBackend) -> &'static str { | | |
| 810 | - match b { | | |
| 811 | - StorageBackend::Fs => "fs", | | |
| 812 | - StorageBackend::S3 => "s3", | | |
| 813 | - StorageBackend::R2 => "r2", | | |
| 814 | - } | | |
| 815 | -} | | |
| 816 | - | | |
| 817 | pub fn get(cfg: &Config, key: &str) -> String { | 1046 | pub fn get(cfg: &Config, key: &str) -> String { |
| 818 | - let path = |p: &std::path::Path| p.to_string_lossy().into_owned(); | 1047 | + field(key).map_or_else(String::new, |f| (f.get)(cfg)) |
| 819 | - let list = |v: &[String]| v.join(", "); | | |
| 820 | - match key { | | |
| 821 | - "registration" => match cfg.registration { | | |
| 822 | - Registration::Closed => "closed", | | |
| 823 | - Registration::Invite => "invite", | | |
| 824 | - Registration::Open => "open", | | |
| 825 | - } | | |
| 826 | - .into(), | | |
| 827 | - "orgs.creation" => match cfg.orgs.creation { | | |
| 828 | - OrgCreation::All => "all", | | |
| 829 | - OrgCreation::Admin => "admin", | | |
| 830 | - } | | |
| 831 | - .into(), | | |
| 832 | - "trusted_proxies" => cfg | | |
| 833 | - .trusted_proxies | | |
| 834 | - .iter() | | |
| 835 | - .map(ToString::to_string) | | |
| 836 | - .collect::<Vec<_>>() | | |
| 837 | - .join(", "), | | |
| 838 | - "banner.message" => cfg.banner.message.clone(), | | |
| 839 | - "banner.level" => cfg.banner.level.clone(), | | |
| 840 | - "banner.expires" => cfg.banner.expires.clone(), | | |
| 841 | - "alerts.enabled" => cfg.alerts.enabled.to_string(), | | |
| 842 | - "alerts.email" => cfg.alerts.email.to_string(), | | |
| 843 | - "alerts.runner_offline_minutes" => cfg.alerts.runner_offline_minutes.to_string(), | | |
| 844 | - "alerts.disk_free_percent" => cfg.alerts.disk_free_percent.to_string(), | | |
| 845 | - "alerts.disk_free_gib" => cfg.alerts.disk_free_gib.to_string(), | | |
| 846 | - "alerts.on_runner_offline" => cfg.alerts.on_runner_offline.to_string(), | | |
| 847 | - "alerts.on_backup" => cfg.alerts.on_backup.to_string(), | | |
| 848 | - "alerts.on_disk" => cfg.alerts.on_disk.to_string(), | | |
| 849 | - "alerts.on_ci_killed" => cfg.alerts.on_ci_killed.to_string(), | | |
| 850 | - "alerts.on_self_update" => cfg.alerts.on_self_update.to_string(), | | |
| 851 | - "alerts.on_replication" => cfg.alerts.on_replication.to_string(), | | |
| 852 | - "base_url" => cfg.base_url.clone(), | | |
| 853 | - "user_content_base_url" => cfg.user_content_base_url.clone(), | | |
| 854 | - "ssh_public_host" => cfg.ssh_public_host.clone(), | | |
| 855 | - "ssh_public_port" => cfg.ssh_public_port.to_string(), | | |
| 856 | - "listen" => cfg.listen.to_string(), | | |
| 857 | - "user_content_listen" => cfg.user_content_listen.to_string(), | | |
| 858 | - "ssh_listen" => cfg.ssh_listen.to_string(), | | |
| 859 | - "database" => path(&cfg.database), | | |
| 860 | - "data_dir" => path(&cfg.data_dir), | | |
| 861 | - "ci.enabled" => cfg.ci.enabled.to_string(), | | |
| 862 | - "ci.max_log_mb" => cfg.ci.max_log_mb.to_string(), | | |
| 863 | - "ci.max_artifact_mb" => cfg.ci.max_artifact_mb.to_string(), | | |
| 864 | - "ci.max_artifacts_per_job" => cfg.ci.max_artifacts_per_job.to_string(), | | |
| 865 | - "ci.max_job_artifacts_mb" => cfg.ci.max_job_artifacts_mb.to_string(), | | |
| 866 | - "ci.log_retention_days" => cfg.ci.log_retention_days.to_string(), | | |
| 867 | - "ci.artifact_retention_days" => cfg.ci.artifact_retention_days.to_string(), | | |
| 868 | - "ci.artifact_keep_runs" => cfg.ci.artifact_keep_runs.to_string(), | | |
| 869 | - "ci.artifact_max_total_mb" => cfg.ci.artifact_max_total_mb.to_string(), | | |
| 870 | - "ci.registration_token_hours" => cfg.ci.registration_token_hours.to_string(), | | |
| 871 | - "lfs.max_object_mb" => cfg.lfs.max_object_mb.to_string(), | | |
| 872 | - "releases.max_asset_mb" => cfg.releases.max_asset_mb.to_string(), | | |
| 873 | - "storage.backend" => backend_name(cfg.storage.backend).into(), | | |
| 874 | - "storage.r2.account_id" => cfg.storage.r2.account_id.clone(), | | |
| 875 | - "storage.r2.bucket" => cfg.storage.r2.bucket.clone(), | | |
| 876 | - "storage.r2.jurisdiction" => cfg.storage.r2.jurisdiction.clone(), | | |
| 877 | - "storage.r2.prefix" => cfg.storage.r2.prefix.clone(), | | |
| 878 | - "storage.r2.access_key_id" => cfg.storage.r2.access_key_id.clone(), | | |
| 879 | - "storage.r2.secret_access_key_file" => path(&cfg.storage.r2.secret_access_key_file), | | |
| 880 | - "storage.s3.bucket" => cfg.storage.s3.bucket.clone(), | | |
| 881 | - "storage.s3.region" => cfg.storage.s3.region.clone(), | | |
| 882 | - "storage.s3.endpoint" => cfg.storage.s3.endpoint.clone(), | | |
| 883 | - "storage.s3.prefix" => cfg.storage.s3.prefix.clone(), | | |
| 884 | - "storage.s3.access_key_id" => cfg.storage.s3.access_key_id.clone(), | | |
| 885 | - "storage.s3.secret_access_key_file" => path(&cfg.storage.s3.secret_access_key_file), | | |
| 886 | - "storage.s3.allow_http" => cfg.storage.s3.allow_http.to_string(), | | |
| 887 | - "storage.s3.virtual_hosted_style" => cfg.storage.s3.virtual_hosted_style.to_string(), | | |
| 888 | - "backup.dir" => path(&cfg.backup.dir), | | |
| 889 | - "backup.interval_hours" => cfg.backup.interval_hours.to_string(), | | |
| 890 | - "backup.keep" => cfg.backup.keep.to_string(), | | |
| 891 | - "backup.fsck_interval_days" => cfg.backup.fsck_interval_days.to_string(), | | |
| 892 | - "backup.healthcheck_url" => cfg.backup.healthcheck_url.clone(), | | |
| 893 | - "replication.target" => cfg.replication.target.clone(), | | |
| 894 | - "replication.ssh_port" => cfg.replication.ssh_port.to_string(), | | |
| 895 | - "replication.identity_file" => path(&cfg.replication.identity_file), | | |
| 896 | - "replication.known_hosts_file" => path(&cfg.replication.known_hosts_file), | | |
| 897 | - "replication.db_snapshot_minutes" => cfg.replication.db_snapshot_minutes.to_string(), | | |
| 898 | - "replication.reconcile_minutes" => cfg.replication.reconcile_minutes.to_string(), | | |
| 899 | - "replication.healthcheck_url" => cfg.replication.healthcheck_url.clone(), | | |
| 900 | - "webhooks.allow_http" => cfg.webhooks.allow_http.to_string(), | | |
| 901 | - "webhooks.allowed_hosts" => list(&cfg.webhooks.allowed_hosts), | | |
| 902 | - "mail.transport" => match cfg.mail.transport { | | |
| 903 | - MailTransport::Smtp => "smtp", | | |
| 904 | - MailTransport::Log => "log", | | |
| 905 | - } | | |
| 906 | - .into(), | | |
| 907 | - "advisories.enabled" => cfg.advisories.enabled.to_string(), | | |
| 908 | - "advisories.ecosystems" => list(&cfg.advisories.ecosystems), | | |
| 909 | - "advisories.refresh_hours" => cfg.advisories.refresh_hours.to_string(), | | |
| 910 | - "self_update.enabled" => cfg.self_update.enabled.to_string(), | | |
| 911 | - "self_update.repo" => cfg.self_update.repo.clone(), | | |
| 912 | - "self_update.branch" => cfg.self_update.branch.clone(), | | |
| 913 | - "self_update.job" => cfg.self_update.job.clone(), | | |
| 914 | - "self_update.artifact" => cfg.self_update.artifact.clone(), | | |
| 915 | - _ => String::new(), | | |
| 916 | - } | | |
| 917 | } | 1048 | } |
| 918 | | 1049 | |
| 919 | pub fn set(cfg: &mut Config, key: &str, raw: &str) -> Result<()> { | 1050 | pub fn set(cfg: &mut Config, key: &str, raw: &str) -> Result<()> { |
| @@ -922,124 +1053,7 @@ pub fn set(cfg: &mut Config, key: &str, raw: &str) -> Result<()> { |
| 922 | return Err(invalid(field, "is read-only")); | 1053 | return Err(invalid(field, "is read-only")); |
| 923 | } | 1054 | } |
| 924 | let v = normalize(field, raw)?; | 1055 | let v = normalize(field, raw)?; |
| 925 | - let v = v.as_str(); | 1056 | + (field.set)(cfg, &v); |
| 926 | - let p = || std::path::PathBuf::from(v); | | |
| 927 | - let s = || v.to_owned(); | | |
| 928 | - match key { | | |
| 929 | - "registration" => { | | |
| 930 | - cfg.registration = choice( | | |
| 931 | - v, | | |
| 932 | - &[ | | |
| 933 | - ("closed", Registration::Closed), | | |
| 934 | - ("invite", Registration::Invite), | | |
| 935 | - ("open", Registration::Open), | | |
| 936 | - ], | | |
| 937 | - Registration::Closed, | | |
| 938 | - ) | | |
| 939 | - } | | |
| 940 | - "orgs.creation" => { | | |
| 941 | - cfg.orgs.creation = choice( | | |
| 942 | - v, | | |
| 943 | - &[("all", OrgCreation::All), ("admin", OrgCreation::Admin)], | | |
| 944 | - OrgCreation::All, | | |
| 945 | - ) | | |
| 946 | - } | | |
| 947 | - "trusted_proxies" => { | | |
| 948 | - cfg.trusted_proxies = split_list(v) | | |
| 949 | - .iter() | | |
| 950 | - .filter_map(|e| { | | |
| 951 | - e.parse::<IpNet>() | | |
| 952 | - .ok() | | |
| 953 | - .or_else(|| e.parse::<IpAddr>().ok().map(IpNet::from)) | | |
| 954 | - }) | | |
| 955 | - .collect() | | |
| 956 | - } | | |
| 957 | - "banner.message" => cfg.banner.message = s(), | | |
| 958 | - "banner.level" => cfg.banner.level = s(), | | |
| 959 | - "banner.expires" => cfg.banner.expires = s(), | | |
| 960 | - "alerts.enabled" => cfg.alerts.enabled = b(v), | | |
| 961 | - "alerts.email" => cfg.alerts.email = b(v), | | |
| 962 | - "alerts.runner_offline_minutes" => cfg.alerts.runner_offline_minutes = n(v), | | |
| 963 | - "alerts.disk_free_percent" => cfg.alerts.disk_free_percent = n(v), | | |
| 964 | - "alerts.disk_free_gib" => cfg.alerts.disk_free_gib = n(v), | | |
| 965 | - "alerts.on_runner_offline" => cfg.alerts.on_runner_offline = b(v), | | |
| 966 | - "alerts.on_backup" => cfg.alerts.on_backup = b(v), | | |
| 967 | - "alerts.on_disk" => cfg.alerts.on_disk = b(v), | | |
| 968 | - "alerts.on_ci_killed" => cfg.alerts.on_ci_killed = b(v), | | |
| 969 | - "alerts.on_self_update" => cfg.alerts.on_self_update = b(v), | | |
| 970 | - "alerts.on_replication" => cfg.alerts.on_replication = b(v), | | |
| 971 | - "base_url" => cfg.base_url = s(), | | |
| 972 | - "user_content_base_url" => cfg.user_content_base_url = s(), | | |
| 973 | - "ssh_public_host" => cfg.ssh_public_host = s(), | | |
| 974 | - "ssh_public_port" => cfg.ssh_public_port = n(v) as u16, | | |
| 975 | - "ci.enabled" => cfg.ci.enabled = b(v), | | |
| 976 | - "ci.max_log_mb" => cfg.ci.max_log_mb = n(v), | | |
| 977 | - "ci.max_artifact_mb" => cfg.ci.max_artifact_mb = n(v), | | |
| 978 | - "ci.max_artifacts_per_job" => cfg.ci.max_artifacts_per_job = n(v) as u32, | | |
| 979 | - "ci.max_job_artifacts_mb" => cfg.ci.max_job_artifacts_mb = n(v), | | |
| 980 | - "ci.log_retention_days" => cfg.ci.log_retention_days = n(v), | | |
| 981 | - "ci.artifact_retention_days" => cfg.ci.artifact_retention_days = n(v), | | |
| 982 | - "ci.artifact_keep_runs" => cfg.ci.artifact_keep_runs = n(v) as u32, | | |
| 983 | - "ci.artifact_max_total_mb" => cfg.ci.artifact_max_total_mb = n(v), | | |
| 984 | - "ci.registration_token_hours" => cfg.ci.registration_token_hours = n(v) as u32, | | |
| 985 | - "lfs.max_object_mb" => cfg.lfs.max_object_mb = n(v), | | |
| 986 | - "releases.max_asset_mb" => cfg.releases.max_asset_mb = n(v), | | |
| 987 | - "storage.backend" => { | | |
| 988 | - cfg.storage.backend = choice( | | |
| 989 | - v, | | |
| 990 | - &[ | | |
| 991 | - ("fs", StorageBackend::Fs), | | |
| 992 | - ("s3", StorageBackend::S3), | | |
| 993 | - ("r2", StorageBackend::R2), | | |
| 994 | - ], | | |
| 995 | - StorageBackend::Fs, | | |
| 996 | - ) | | |
| 997 | - } | | |
| 998 | - "storage.r2.account_id" => cfg.storage.r2.account_id = s(), | | |
| 999 | - "storage.r2.bucket" => cfg.storage.r2.bucket = s(), | | |
| 1000 | - "storage.r2.jurisdiction" => cfg.storage.r2.jurisdiction = s(), | | |
| 1001 | - "storage.r2.prefix" => cfg.storage.r2.prefix = s(), | | |
| 1002 | - "storage.r2.access_key_id" => cfg.storage.r2.access_key_id = s(), | | |
| 1003 | - "storage.r2.secret_access_key_file" => cfg.storage.r2.secret_access_key_file = p(), | | |
| 1004 | - "storage.s3.bucket" => cfg.storage.s3.bucket = s(), | | |
| 1005 | - "storage.s3.region" => cfg.storage.s3.region = s(), | | |
| 1006 | - "storage.s3.endpoint" => cfg.storage.s3.endpoint = s(), | | |
| 1007 | - "storage.s3.prefix" => cfg.storage.s3.prefix = s(), | | |
| 1008 | - "storage.s3.access_key_id" => cfg.storage.s3.access_key_id = s(), | | |
| 1009 | - "storage.s3.secret_access_key_file" => cfg.storage.s3.secret_access_key_file = p(), | | |
| 1010 | - "storage.s3.allow_http" => cfg.storage.s3.allow_http = b(v), | | |
| 1011 | - "storage.s3.virtual_hosted_style" => cfg.storage.s3.virtual_hosted_style = b(v), | | |
| 1012 | - "backup.dir" => cfg.backup.dir = p(), | | |
| 1013 | - "backup.interval_hours" => cfg.backup.interval_hours = n(v), | | |
| 1014 | - "backup.keep" => cfg.backup.keep = n(v) as usize, | | |
| 1015 | - "backup.fsck_interval_days" => cfg.backup.fsck_interval_days = n(v), | | |
| 1016 | - "backup.healthcheck_url" => cfg.backup.healthcheck_url = s(), | | |
| 1017 | - "replication.target" => cfg.replication.target = s(), | | |
| 1018 | - "replication.ssh_port" => cfg.replication.ssh_port = n(v) as u16, | | |
| 1019 | - "replication.identity_file" => cfg.replication.identity_file = p(), | | |
| 1020 | - "replication.known_hosts_file" => cfg.replication.known_hosts_file = p(), | | |
| 1021 | - "replication.db_snapshot_minutes" => cfg.replication.db_snapshot_minutes = n(v), | | |
| 1022 | - "replication.reconcile_minutes" => cfg.replication.reconcile_minutes = n(v), | | |
| 1023 | - "replication.healthcheck_url" => cfg.replication.healthcheck_url = s(), | | |
| 1024 | - "webhooks.allow_http" => cfg.webhooks.allow_http = b(v), | | |
| 1025 | - "webhooks.allowed_hosts" => cfg.webhooks.allowed_hosts = split_list(v), | | |
| 1026 | - "mail.transport" => { | | |
| 1027 | - cfg.mail.transport = choice( | | |
| 1028 | - v, | | |
| 1029 | - &[("smtp", MailTransport::Smtp), ("log", MailTransport::Log)], | | |
| 1030 | - MailTransport::Smtp, | | |
| 1031 | - ) | | |
| 1032 | - } | | |
| 1033 | - "advisories.enabled" => cfg.advisories.enabled = b(v), | | |
| 1034 | - "advisories.ecosystems" => cfg.advisories.ecosystems = split_list(v), | | |
| 1035 | - "advisories.refresh_hours" => cfg.advisories.refresh_hours = n(v), | | |
| 1036 | - "self_update.enabled" => cfg.self_update.enabled = b(v), | | |
| 1037 | - "self_update.repo" => cfg.self_update.repo = s(), | | |
| 1038 | - "self_update.branch" => cfg.self_update.branch = s(), | | |
| 1039 | - "self_update.job" => cfg.self_update.job = s(), | | |
| 1040 | - "self_update.artifact" => cfg.self_update.artifact = s(), | | |
| 1041 | - _ => return Err(Error::Invalid(format!("unknown setting `{key}`"))), | | |
| 1042 | - } | | |
| 1043 | Ok(()) | 1057 | Ok(()) |
| 1044 | } | 1058 | } |
| 1045 | | 1059 | |
| @@ -0,0 +1,25 @@ |
| | 1 | +use hmac::{Hmac, KeyInit, Mac}; |
| | 2 | +use sha2::Sha256; |
| | 3 | +use subtle::ConstantTimeEq; |
| | 4 | + |
| | 5 | +type HmacSha256 = Hmac<Sha256>; |
| | 6 | + |
| | 7 | +pub const MAC_LEN: usize = 32; |
| | 8 | + |
| | 9 | +pub fn mac(key: &[u8; 32], parts: &[&[u8]]) -> Vec<u8> { |
| | 10 | + let mut mac = |
| | 11 | + <HmacSha256 as KeyInit>::new_from_slice(key).expect("HMAC accepts any key length"); |
| | 12 | + for part in parts { |
| | 13 | + mac.update(part); |
| | 14 | + } |
| | 15 | + mac.finalize().into_bytes().to_vec() |
| | 16 | +} |
| | 17 | + |
| | 18 | +pub fn verify(key: &[u8; 32], parts: &[&[u8]], tag: &[u8]) -> bool { |
| | 19 | + tag.len() == MAC_LEN && bool::from(mac(key, parts).as_slice().ct_eq(tag)) |
| | 20 | +} |
| | 21 | + |
| | 22 | +pub fn parse_expiry(text: &str) -> Option<i64> { |
| | 23 | + let value: i64 = text.parse().ok()?; |
| | 24 | + (value.to_string() == text).then_some(value) |
| | 25 | +} |
| @@ -2,13 +2,14 @@ use turso::{Row, Value}; |
| 2 | | 2 | |
| 3 | use super::finish; | 3 | use super::finish; |
| 4 | use super::{Store, col_int, col_text, db_err, fetch_all, fetch_opt, new_id, text}; | 4 | use super::{Store, col_int, col_text, db_err, fetch_all, fetch_opt, new_id, text}; |
| | 5 | +use crate::alerts::AlertTopic; |
| 5 | use crate::error::Result; | 6 | use crate::error::Result; |
| 6 | use crate::time::now_stamp; | 7 | use crate::time::now_stamp; |
| 7 | | 8 | |
| 8 | #[derive(Debug, Clone, PartialEq, Eq)] | 9 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 9 | pub struct AdminAlert { | 10 | pub struct AdminAlert { |
| 10 | pub key: String, | 11 | pub key: String, |
| 11 | - pub kind: String, | 12 | + pub kind: AlertTopic, |
| 12 | pub subject: String, | 13 | pub subject: String, |
| 13 | pub detail: String, | 14 | pub detail: String, |
| 14 | pub raised_at: String, | 15 | pub raised_at: String, |
| @@ -18,7 +19,7 @@ pub struct AdminAlert { |
| 18 | pub struct AdminNotice { | 19 | pub struct AdminNotice { |
| 19 | pub id: String, | 20 | pub id: String, |
| 20 | pub alert_key: String, | 21 | pub alert_key: String, |
| 21 | - pub kind: String, | 22 | + pub kind: AlertTopic, |
| 22 | pub subject: String, | 23 | pub subject: String, |
| 23 | pub detail: String, | 24 | pub detail: String, |
| 24 | pub resolved: bool, | 25 | pub resolved: bool, |
| @@ -31,7 +32,7 @@ const NOTICE_COLS: &str = "id, alert_key, kind, subject, detail, resolved, unrea |
| 31 | fn map_alert(row: &Row) -> Result<AdminAlert> { | 32 | fn map_alert(row: &Row) -> Result<AdminAlert> { |
| 32 | Ok(AdminAlert { | 33 | Ok(AdminAlert { |
| 33 | key: col_text(row, 0)?, | 34 | key: col_text(row, 0)?, |
| 34 | - kind: col_text(row, 1)?, | 35 | + kind: super::issues::parse_db(&col_text(row, 1)?)?, |
| 35 | subject: col_text(row, 2)?, | 36 | subject: col_text(row, 2)?, |
| 36 | detail: col_text(row, 3)?, | 37 | detail: col_text(row, 3)?, |
| 37 | raised_at: col_text(row, 4)?, | 38 | raised_at: col_text(row, 4)?, |
| @@ -42,7 +43,7 @@ fn map_notice(row: &Row) -> Result<AdminNotice> { |
| 42 | Ok(AdminNotice { | 43 | Ok(AdminNotice { |
| 43 | id: col_text(row, 0)?, | 44 | id: col_text(row, 0)?, |
| 44 | alert_key: col_text(row, 1)?, | 45 | alert_key: col_text(row, 1)?, |
| 45 | - kind: col_text(row, 2)?, | 46 | + kind: super::issues::parse_db(&col_text(row, 2)?)?, |
| 46 | subject: col_text(row, 3)?, | 47 | subject: col_text(row, 3)?, |
| 47 | detail: col_text(row, 4)?, | 48 | detail: col_text(row, 4)?, |
| 48 | resolved: col_int(row, 5)? != 0, | 49 | resolved: col_int(row, 5)? != 0, |
| @@ -55,7 +56,7 @@ impl Store { |
| 55 | pub async fn raise_alert( | 56 | pub async fn raise_alert( |
| 56 | &self, | 57 | &self, |
| 57 | key: &str, | 58 | key: &str, |
| 58 | - kind: &str, | 59 | + kind: AlertTopic, |
| 59 | subject: &str, | 60 | subject: &str, |
| 60 | detail: &str, | 61 | detail: &str, |
| 61 | ) -> Result<bool> { | 62 | ) -> Result<bool> { |
| @@ -90,7 +91,7 @@ impl Store { |
| 90 | updated_at = excluded.updated_at", | 91 | updated_at = excluded.updated_at", |
| 91 | vec![ | 92 | vec![ |
| 92 | text(key), | 93 | text(key), |
| 93 | - text(kind), | 94 | + text(kind.as_str()), |
| 94 | text(subject), | 95 | text(subject), |
| 95 | text(detail), | 96 | text(detail), |
| 96 | text(&now), | 97 | text(&now), |
| @@ -137,7 +138,7 @@ impl Store { |
| 137 | pub async fn record_alert_event( | 138 | pub async fn record_alert_event( |
| 138 | &self, | 139 | &self, |
| 139 | key: &str, | 140 | key: &str, |
| 140 | - kind: &str, | 141 | + kind: AlertTopic, |
| 141 | subject: &str, | 142 | subject: &str, |
| 142 | detail: &str, | 143 | detail: &str, |
| 143 | ) -> Result<bool> { | 144 | ) -> Result<bool> { |
| @@ -149,7 +150,7 @@ impl Store { |
| 149 | raised_at, resolved_at, updated_at) VALUES (?1, ?2, ?3, ?4, 'event', ?5, NULL, ?5)", | 150 | raised_at, resolved_at, updated_at) VALUES (?1, ?2, ?3, ?4, 'event', ?5, NULL, ?5)", |
| 150 | vec![ | 151 | vec![ |
| 151 | text(key), | 152 | text(key), |
| 152 | - text(kind), | 153 | + text(kind.as_str()), |
| 153 | text(subject), | 154 | text(subject), |
| 154 | text(detail), | 155 | text(detail), |
| 155 | text(&now), | 156 | text(&now), |
| @@ -172,12 +173,12 @@ impl Store { |
| 172 | .await | 173 | .await |
| 173 | } | 174 | } |
| 174 | | 175 | |
| 175 | - pub async fn active_alert_keys(&self, kind: &str) -> Result<Vec<String>> { | 176 | + pub async fn active_alert_keys(&self, kind: AlertTopic) -> Result<Vec<String>> { |
| 176 | let conn = self.read_conn().await; | 177 | let conn = self.read_conn().await; |
| 177 | fetch_all( | 178 | fetch_all( |
| 178 | &conn, | 179 | &conn, |
| 179 | "SELECT key FROM admin_alerts WHERE state = 'active' AND kind = ?1", | 180 | "SELECT key FROM admin_alerts WHERE state = 'active' AND kind = ?1", |
| 180 | - (kind.to_owned(),), | 181 | + (kind.as_str().to_owned(),), |
| 181 | |row| col_text(row, 0), | 182 | |row| col_text(row, 0), |
| 182 | ) | 183 | ) |
| 183 | .await | 184 | .await |
| @@ -187,7 +188,7 @@ impl Store { |
| 187 | &self, | 188 | &self, |
| 188 | user_id: &str, | 189 | user_id: &str, |
| 189 | alert_key: &str, | 190 | alert_key: &str, |
| 190 | - kind: &str, | 191 | + kind: AlertTopic, |
| 191 | subject: &str, | 192 | subject: &str, |
| 192 | detail: &str, | 193 | detail: &str, |
| 193 | resolved: bool, | 194 | resolved: bool, |
| @@ -200,7 +201,7 @@ impl Store { |
| 200 | text(&new_id()), | 201 | text(&new_id()), |
| 201 | text(user_id), | 202 | text(user_id), |
| 202 | text(alert_key), | 203 | text(alert_key), |
| 203 | - text(kind), | 204 | + text(kind.as_str()), |
| 204 | text(subject), | 205 | text(subject), |
| 205 | text(detail), | 206 | text(detail), |
| 206 | Value::Integer(i64::from(resolved)), | 207 | Value::Integer(i64::from(resolved)), |
| @@ -289,6 +290,7 @@ impl Store { |
| 289 | | 290 | |
| 290 | #[cfg(test)] | 291 | #[cfg(test)] |
| 291 | mod tests { | 292 | mod tests { |
| | 293 | + use crate::alerts::AlertTopic; |
| 292 | use crate::store::Store; | 294 | use crate::store::Store; |
| 293 | | 295 | |
| 294 | async fn store() -> (Store, tempfile::TempDir) { | 296 | async fn store() -> (Store, tempfile::TempDir) { |
| @@ -300,13 +302,18 @@ mod tests { |
| 300 | async fn an_alert_is_raised_once_until_it_resolves(store: &Store) { | 302 | async fn an_alert_is_raised_once_until_it_resolves(store: &Store) { |
| 301 | assert!( | 303 | assert!( |
| 302 | store | 304 | store |
| 303 | - .raise_alert("runner_offline:r1", "runner_offline", "ci-1", "") | 305 | + .raise_alert("runner_offline:r1", AlertTopic::RunnerOffline, "ci-1", "") |
| 304 | .await | 306 | .await |
| 305 | .unwrap() | 307 | .unwrap() |
| 306 | ); | 308 | ); |
| 307 | assert!( | 309 | assert!( |
| 308 | !store | 310 | !store |
| 309 | - .raise_alert("runner_offline:r1", "runner_offline", "ci-1", "later") | 311 | + .raise_alert( |
| | 312 | + "runner_offline:r1", |
| | 313 | + AlertTopic::RunnerOffline, |
| | 314 | + "ci-1", |
| | 315 | + "later" |
| | 316 | + ) |
| 310 | .await | 317 | .await |
| 311 | .unwrap(), | 318 | .unwrap(), |
| 312 | "still active: not raised again" | 319 | "still active: not raised again" |
| @@ -329,7 +336,7 @@ mod tests { |
| 329 | | 336 | |
| 330 | assert!( | 337 | assert!( |
| 331 | store | 338 | store |
| 332 | - .raise_alert("runner_offline:r1", "runner_offline", "ci-1", "") | 339 | + .raise_alert("runner_offline:r1", AlertTopic::RunnerOffline, "ci-1", "") |
| 333 | .await | 340 | .await |
| 334 | .unwrap(), | 341 | .unwrap(), |
| 335 | "a new failure after the resolution is raised again" | 342 | "a new failure after the resolution is raised again" |
| @@ -339,13 +346,13 @@ mod tests { |
| 339 | async fn events_fire_once_and_are_never_active(store: &Store) { | 346 | async fn events_fire_once_and_are_never_active(store: &Store) { |
| 340 | assert!( | 347 | assert!( |
| 341 | store | 348 | store |
| 342 | - .record_alert_event("ci_killed:run1", "ci_killed", "ci-1", "") | 349 | + .record_alert_event("ci_killed:run1", AlertTopic::CiKilled, "ci-1", "") |
| 343 | .await | 350 | .await |
| 344 | .unwrap() | 351 | .unwrap() |
| 345 | ); | 352 | ); |
| 346 | assert!( | 353 | assert!( |
| 347 | !store | 354 | !store |
| 348 | - .record_alert_event("ci_killed:run1", "ci_killed", "ci-1", "") | 355 | + .record_alert_event("ci_killed:run1", AlertTopic::CiKilled, "ci-1", "") |
| 349 | .await | 356 | .await |
| 350 | .unwrap() | 357 | .unwrap() |
| 351 | ); | 358 | ); |
| @@ -3,6 +3,7 @@ use std::collections::{BTreeSet, HashMap}; |
| 3 | use tokio::sync::mpsc; | 3 | use tokio::sync::mpsc; |
| 4 | use turso::{Row, Value}; | 4 | use turso::{Row, Value}; |
| 5 | | 5 | |
| | 6 | +use super::issues::parse_db; |
| 6 | use super::{Store, col_int, col_text, db_err, fetch_all, fetch_opt, finish}; | 7 | use super::{Store, col_int, col_text, db_err, fetch_all, fetch_opt, finish}; |
| 7 | use crate::advisories::{Advisory, Dependency, Range, affects}; | 8 | use crate::advisories::{Advisory, Dependency, Range, affects}; |
| 8 | use crate::error::{Error, Result}; | 9 | use crate::error::{Error, Result}; |
| @@ -15,24 +16,11 @@ pub enum AlertState { |
| 15 | Fixed, | 16 | Fixed, |
| 16 | } | 17 | } |
| 17 | | 18 | |
| 18 | -impl AlertState { | 19 | +string_enum!(AlertState { |
| 19 | - pub fn as_str(self) -> &'static str { | 20 | + Open = "open", |
| 20 | - match self { | 21 | + Dismissed = "dismissed", |
| 21 | - AlertState::Open => "open", | 22 | + Fixed = "fixed", |
| 22 | - AlertState::Dismissed => "dismissed", | 23 | +}); |
| 23 | - AlertState::Fixed => "fixed", | | |
| 24 | - } | | |
| 25 | - } | | |
| 26 | - | | |
| 27 | - fn parse(raw: &str) -> Result<Self> { | | |
| 28 | - match raw { | | |
| 29 | - "open" => Ok(AlertState::Open), | | |
| 30 | - "dismissed" => Ok(AlertState::Dismissed), | | |
| 31 | - "fixed" => Ok(AlertState::Fixed), | | |
| 32 | - other => Err(Error::Database(format!("unknown alert state {other:?}"))), | | |
| 33 | - } | | |
| 34 | - } | | |
| 35 | -} | | |
| 36 | | 24 | |
| 37 | #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] | 25 | #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] |
| 38 | pub struct AlertKey { | 26 | pub struct AlertKey { |
| @@ -100,7 +88,7 @@ fn key_of(row: &Row, offset: usize) -> Result<AlertKey> { |
| 100 | fn map_alert(row: &Row) -> Result<Alert> { | 88 | fn map_alert(row: &Row) -> Result<Alert> { |
| 101 | Ok(Alert { | 89 | Ok(Alert { |
| 102 | key: key_of(row, 0)?, | 90 | key: key_of(row, 0)?, |
| 103 | - state: AlertState::parse(&col_text(row, 4)?)?, | 91 | + state: parse_db(&col_text(row, 4)?)?, |
| 104 | summary: col_text(row, 5)?, | 92 | summary: col_text(row, 5)?, |
| 105 | severity: col_text(row, 6)?, | 93 | severity: col_text(row, 6)?, |
| 106 | created_at: col_text(row, 7)?, | 94 | created_at: col_text(row, 7)?, |
| @@ -250,7 +238,7 @@ impl Store { |
| 250 | "SELECT advisory_id, ecosystem, package, version, state FROM repo_alerts \ | 238 | "SELECT advisory_id, ecosystem, package, version, state FROM repo_alerts \ |
| 251 | WHERE repo_id = ?1", | 239 | WHERE repo_id = ?1", |
| 252 | (rid.clone(),), | 240 | (rid.clone(),), |
| 253 | - |row| Ok((key_of(row, 0)?, AlertState::parse(&col_text(row, 4)?)?)), | 241 | + |row| Ok((key_of(row, 0)?, parse_db(&col_text(row, 4)?)?)), |
| 254 | ) | 242 | ) |
| 255 | .await? | 243 | .await? |
| 256 | .into_iter() | 244 | .into_iter() |
| @@ -1,8 +1,9 @@ |
| 1 | use turso::{Row, Value}; | 1 | use turso::{Row, Value}; |
| 2 | | 2 | |
| | 3 | +use super::issues::parse_db; |
| 3 | use super::{Store, col_opt_text, col_text, db_err, fetch_all}; | 4 | use super::{Store, col_opt_text, col_text, db_err, fetch_all}; |
| 4 | -use crate::audit::{AuditAction, AuditCursor, AuditEntry, AuditFilter}; | 5 | +use crate::audit::{AuditCursor, AuditEntry, AuditFilter}; |
| 5 | -use crate::error::{Error, Result}; | 6 | +use crate::error::Result; |
| 6 | | 7 | |
| 7 | const AUDIT_COLS: &str = "id, at, actor_id, actor_name, action, target_kind, target_id, \ | 8 | const AUDIT_COLS: &str = "id, at, actor_id, actor_name, action, target_kind, target_id, \ |
| 8 | target_name, ip, data"; | 9 | target_name, ip, data"; |
| @@ -15,8 +16,7 @@ fn map_audit(row: &Row) -> Result<AuditEntry> { |
| 15 | at: col_text(row, 1)?, | 16 | at: col_text(row, 1)?, |
| 16 | actor_id: col_opt_text(row, 2)?, | 17 | actor_id: col_opt_text(row, 2)?, |
| 17 | actor_name: col_text(row, 3)?, | 18 | actor_name: col_text(row, 3)?, |
| 18 | - action: AuditAction::parse(&action) | 19 | + action: parse_db(&action)?, |
| 19 | - .ok_or_else(|| Error::Database(format!("unknown audit action {action:?}")))?, | | |
| 20 | target_kind: col_text(row, 5)?, | 20 | target_kind: col_text(row, 5)?, |
| 21 | target_id: col_text(row, 6)?, | 21 | target_id: col_text(row, 6)?, |
| 22 | target_name: col_text(row, 7)?, | 22 | target_name: col_text(row, 7)?, |
| @@ -1,5 +1,6 @@ |
| 1 | use turso::{Row, Value}; | 1 | use turso::{Row, Value}; |
| 2 | | 2 | |
| | 3 | +use super::issues::parse_db; |
| 3 | use super::{Store, col_opt_int, col_opt_text, col_text, db_err, fetch_all, new_id}; | 4 | use super::{Store, col_opt_int, col_opt_text, col_text, db_err, fetch_all, new_id}; |
| 4 | use crate::error::{Error, Result}; | 5 | use crate::error::{Error, Result}; |
| 5 | use crate::time::now_stamp; | 6 | use crate::time::now_stamp; |
| @@ -13,22 +14,10 @@ pub enum RunKind { |
| 13 | Fsck, | 14 | Fsck, |
| 14 | } | 15 | } |
| 15 | | 16 | |
| 16 | -impl RunKind { | 17 | +string_enum!(RunKind { |
| 17 | - pub fn as_str(self) -> &'static str { | 18 | + Backup = "backup", |
| 18 | - match self { | 19 | + Fsck = "fsck", |
| 19 | - RunKind::Backup => "backup", | 20 | +}); |
| 20 | - RunKind::Fsck => "fsck", | | |
| 21 | - } | | |
| 22 | - } | | |
| 23 | - | | |
| 24 | - pub fn parse(text: &str) -> Option<RunKind> { | | |
| 25 | - match text { | | |
| 26 | - "backup" => Some(RunKind::Backup), | | |
| 27 | - "fsck" => Some(RunKind::Fsck), | | |
| 28 | - _ => None, | | |
| 29 | - } | | |
| 30 | - } | | |
| 31 | -} | | |
| 32 | | 21 | |
| 33 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] | 22 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 34 | pub enum RunTrigger { | 23 | pub enum RunTrigger { |
| @@ -37,24 +26,11 @@ pub enum RunTrigger { |
| 37 | Cli, | 26 | Cli, |
| 38 | } | 27 | } |
| 39 | | 28 | |
| 40 | -impl RunTrigger { | 29 | +string_enum!(RunTrigger { |
| 41 | - pub fn as_str(self) -> &'static str { | 30 | + Schedule = "schedule", |
| 42 | - match self { | 31 | + Manual = "manual", |
| 43 | - RunTrigger::Schedule => "schedule", | 32 | + Cli = "cli", |
| 44 | - RunTrigger::Manual => "manual", | 33 | +}); |
| 45 | - RunTrigger::Cli => "cli", | | |
| 46 | - } | | |
| 47 | - } | | |
| 48 | - | | |
| 49 | - pub fn parse(text: &str) -> Option<RunTrigger> { | | |
| 50 | - match text { | | |
| 51 | - "schedule" => Some(RunTrigger::Schedule), | | |
| 52 | - "manual" => Some(RunTrigger::Manual), | | |
| 53 | - "cli" => Some(RunTrigger::Cli), | | |
| 54 | - _ => None, | | |
| 55 | - } | | |
| 56 | - } | | |
| 57 | -} | | |
| 58 | | 34 | |
| 59 | #[derive(Debug, Clone, PartialEq, Eq)] | 35 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 60 | pub struct BackupRun { | 36 | pub struct BackupRun { |
| @@ -70,17 +46,13 @@ pub struct BackupRun { |
| 70 | } | 46 | } |
| 71 | | 47 | |
| 72 | fn map_run(row: &Row) -> Result<BackupRun> { | 48 | fn map_run(row: &Row) -> Result<BackupRun> { |
| 73 | - let kind = col_text(row, 1)?; | | |
| 74 | - let trigger = col_text(row, 8)?; | | |
| 75 | let bytes = col_opt_int(row, 6)? | 49 | let bytes = col_opt_int(row, 6)? |
| 76 | .map(|n| u64::try_from(n).map_err(|_| Error::Database("negative run size".into()))) | 50 | .map(|n| u64::try_from(n).map_err(|_| Error::Database("negative run size".into()))) |
| 77 | .transpose()?; | 51 | .transpose()?; |
| 78 | Ok(BackupRun { | 52 | Ok(BackupRun { |
| 79 | id: col_text(row, 0)?, | 53 | id: col_text(row, 0)?, |
| 80 | - kind: RunKind::parse(&kind) | 54 | + kind: parse_db(&col_text(row, 1)?)?, |
| 81 | - .ok_or_else(|| Error::Database(format!("unknown run kind {kind:?}")))?, | 55 | + trigger: parse_db(&col_text(row, 8)?)?, |
| 82 | - trigger: RunTrigger::parse(&trigger) | | |
| 83 | - .ok_or_else(|| Error::Database(format!("unknown run trigger {trigger:?}")))?, | | |
| 84 | started_at: col_text(row, 2)?, | 56 | started_at: col_text(row, 2)?, |
| 85 | finished_at: col_opt_text(row, 3)?, | 57 | finished_at: col_opt_text(row, 3)?, |
| 86 | ok: col_opt_int(row, 4)?.map(|n| n != 0), | 58 | ok: col_opt_int(row, 4)?.map(|n| n != 0), |
| @@ -3,6 +3,7 @@ use std::time::Duration; |
| 3 | | 3 | |
| 4 | use turso::{Connection, Row, Value}; | 4 | use turso::{Connection, Row, Value}; |
| 5 | | 5 | |
| | 6 | +use super::issues::parse_db; |
| 6 | use super::{ | 7 | use super::{ |
| 7 | Store, col_blob, col_bool, col_int, col_opt_int, col_opt_text, col_text, db_err, fetch_all, | 8 | Store, col_blob, col_bool, col_int, col_opt_int, col_opt_text, col_text, db_err, fetch_all, |
| 8 | fetch_opt, finish, insert_err, missing_row, new_id, opt_int_value, opt_text, text, | 9 | fetch_opt, finish, insert_err, missing_row, new_id, opt_int_value, opt_text, text, |
| @@ -102,7 +103,7 @@ fn map_run(row: &Row) -> Result<CiRun> { |
| 102 | commit_oid: col_text(row, 5)?, | 103 | commit_oid: col_text(row, 5)?, |
| 103 | pull_number: col_opt_int(row, 6)?, | 104 | pull_number: col_opt_int(row, 6)?, |
| 104 | actor_id: col_text(row, 7)?, | 105 | actor_id: col_text(row, 7)?, |
| 105 | - state: col_text(row, 8)?.parse::<RunState>()?, | 106 | + state: parse_db(&col_text(row, 8)?)?, |
| 106 | config_error: col_opt_text(row, 9)?, | 107 | config_error: col_opt_text(row, 9)?, |
| 107 | created_at: col_text(row, 10)?, | 108 | created_at: col_text(row, 10)?, |
| 108 | finished_at: col_opt_text(row, 11)?, | 109 | finished_at: col_opt_text(row, 11)?, |
| @@ -115,7 +116,7 @@ fn map_job(row: &Row) -> Result<CiJob> { |
| 115 | run_id: col_text(row, 1)?, | 116 | run_id: col_text(row, 1)?, |
| 116 | name: col_text(row, 2)?, | 117 | name: col_text(row, 2)?, |
| 117 | spec_json: col_text(row, 3)?, | 118 | spec_json: col_text(row, 3)?, |
| 118 | - state: col_text(row, 4)?.parse::<JobState>()?, | 119 | + state: parse_db(&col_text(row, 4)?)?, |
| 119 | runner_id: col_opt_text(row, 5)?, | 120 | runner_id: col_opt_text(row, 5)?, |
| 120 | exit_code: col_opt_int(row, 6)?, | 121 | exit_code: col_opt_int(row, 6)?, |
| 121 | message: col_opt_text(row, 7)?, | 122 | message: col_opt_text(row, 7)?, |
| @@ -333,7 +334,7 @@ async fn recompute_run(conn: &Connection, run_id: &str, now: &str) -> Result<()> |
| 333 | conn, | 334 | conn, |
| 334 | "SELECT state FROM ci_jobs WHERE run_id = ?1", | 335 | "SELECT state FROM ci_jobs WHERE run_id = ?1", |
| 335 | (run_id.to_string(),), | 336 | (run_id.to_string(),), |
| 336 | - |row| col_text(row, 0)?.parse::<JobState>(), | 337 | + |row| parse_db(&col_text(row, 0)?), |
| 337 | ) | 338 | ) |
| 338 | .await?; | 339 | .await?; |
| 339 | let active = | 340 | let active = |
| @@ -498,8 +499,8 @@ impl Store { |
| 498 | )); | 499 | )); |
| 499 | } | 500 | } |
| 500 | tx.execute( | 501 | tx.execute( |
| 501 | - "INSERT INTO ci_runners (id, name, labels, secret_hash, created_at, disabled) \ | 502 | + "INSERT INTO ci_runners (id, name, labels, registered_labels, secret_hash, created_at, disabled) \ |
| 502 | - VALUES (?1, ?2, ?3, ?4, ?5, 0)", | 503 | + VALUES (?1, ?2, ?3, ?3, ?4, ?5, 0)", |
| 503 | vec![ | 504 | vec![ |
| 504 | text(&id), | 505 | text(&id), |
| 505 | text(name), | 506 | text(name), |
| @@ -683,25 +684,21 @@ impl Store { |
| 683 | .map_err(|e| Error::Database(e.to_string()))?, | 684 | .map_err(|e| Error::Database(e.to_string()))?, |
| 684 | ) | 685 | ) |
| 685 | }; | 686 | }; |
| 686 | - let labels = if key == "labels" { | 687 | + if key == "labels" { |
| 687 | let chosen = runner | 688 | let chosen = runner |
| 688 | .config_overrides | 689 | .config_overrides |
| 689 | .get("labels") | 690 | .get("labels") |
| 690 | - .or_else(|| runner.reported_config.get("labels")); | 691 | + .or_else(|| runner.reported_config.get("labels")) |
| 691 | - chosen.and_then(|v| serde_json::from_value::<Vec<String>>(v.clone()).ok()) | 692 | + .and_then(|v| serde_json::from_value::<Vec<String>>(v.clone()).ok()) |
| 692 | - } else { | 693 | + .map(|labels| serde_json::to_string(&labels)) |
| 693 | - None | 694 | + .transpose() |
| 694 | - }; | 695 | + .map_err(|e| Error::Database(e.to_string()))?; |
| 695 | - if let Some(labels) = labels { | | |
| 696 | conn.execute( | 696 | conn.execute( |
| 697 | - "UPDATE ci_runners SET config_overrides = ?2, labels = ?3 WHERE id = ?1", | 697 | + "UPDATE ci_runners SET config_overrides = ?2, labels = COALESCE(?3, registered_labels) WHERE id = ?1", |
| 698 | ( | 698 | ( |
| 699 | id.to_string(), | 699 | id.to_string(), |
| 700 | overrides, | 700 | overrides, |
| 701 | - text( | 701 | + chosen.map_or(Value::Null, |json| text(&json)), |
| 702 | - &serde_json::to_string(&labels) | | |
| 703 | - .map_err(|e| Error::Database(e.to_string()))?, | | |
| 704 | - ), | | |
| 705 | ), | 702 | ), |
| 706 | ) | 703 | ) |
| 707 | .await | 704 | .await |
| @@ -1777,10 +1774,41 @@ impl Store { |
| 1777 | name: &str, | 1774 | name: &str, |
| 1778 | size: i64, | 1775 | size: i64, |
| 1779 | sha256: &str, | 1776 | sha256: &str, |
| | 1777 | + ) -> Result<CiArtifact> { |
| | 1778 | + self.add_artifact_within(job_id, name, size, sha256, u64::MAX, u64::MAX) |
| | 1779 | + .await |
| | 1780 | + } |
| | 1781 | + |
| | 1782 | + pub async fn add_artifact_within( |
| | 1783 | + &self, |
| | 1784 | + job_id: &str, |
| | 1785 | + name: &str, |
| | 1786 | + size: i64, |
| | 1787 | + sha256: &str, |
| | 1788 | + max_count: u64, |
| | 1789 | + max_bytes: u64, |
| 1780 | ) -> Result<CiArtifact> { | 1790 | ) -> Result<CiArtifact> { |
| 1781 | if size < 0 { | 1791 | if size < 0 { |
| 1782 | return Err(Error::Invalid("an artifact size cannot be negative".into())); | 1792 | return Err(Error::Invalid("an artifact size cannot be negative".into())); |
| 1783 | } | 1793 | } |
| | 1794 | + let conn = self.inner.conn.lock().await; |
| | 1795 | + let (count, used) = fetch_opt( |
| | 1796 | + &conn, |
| | 1797 | + "SELECT COUNT(*), COALESCE(SUM(size), 0) FROM ci_artifacts WHERE job_id = ?1", |
| | 1798 | + (job_id.to_string(),), |
| | 1799 | + |row| Ok((col_int(row, 0)?, col_int(row, 1)?)), |
| | 1800 | + ) |
| | 1801 | + .await? |
| | 1802 | + .unwrap_or((0, 0)); |
| | 1803 | + if u64::try_from(count).unwrap_or(0) >= max_count { |
| | 1804 | + return Err(Error::Invalid("the job has too many artifacts".into())); |
| | 1805 | + } |
| | 1806 | + let total = u64::try_from(used.saturating_add(size)).unwrap_or(u64::MAX); |
| | 1807 | + if total > max_bytes { |
| | 1808 | + return Err(Error::Invalid( |
| | 1809 | + "the job's artifacts have reached their total size limit".into(), |
| | 1810 | + )); |
| | 1811 | + } |
| 1784 | let artifact = CiArtifact { | 1812 | let artifact = CiArtifact { |
| 1785 | id: new_id(), | 1813 | id: new_id(), |
| 1786 | job_id: job_id.to_string(), | 1814 | job_id: job_id.to_string(), |
| @@ -1789,7 +1817,6 @@ impl Store { |
| 1789 | sha256: sha256.to_string(), | 1817 | sha256: sha256.to_string(), |
| 1790 | created_at: now_stamp(), | 1818 | created_at: now_stamp(), |
| 1791 | }; | 1819 | }; |
| 1792 | - let conn = self.inner.conn.lock().await; | | |
| 1793 | conn.execute( | 1820 | conn.execute( |
| 1794 | "INSERT INTO ci_artifacts (id, job_id, name, size, sha256, created_at) \ | 1821 | "INSERT INTO ci_artifacts (id, job_id, name, size, sha256, created_at) \ |
| 1795 | VALUES (?1, ?2, ?3, ?4, ?5, ?6)", | 1822 | VALUES (?1, ?2, ?3, ?4, ?5, ?6)", |
| @@ -2,6 +2,7 @@ use std::collections::HashMap; |
| 2 | | 2 | |
| 3 | use turso::{Row, Value}; | 3 | use turso::{Row, Value}; |
| 4 | | 4 | |
| | 5 | +use super::issues::parse_db; |
| 5 | use super::{Store, col_opt_text, col_text, db_err, fetch_all, fetch_opt, missing_row, new_id}; | 6 | use super::{Store, col_opt_text, col_text, db_err, fetch_all, fetch_opt, missing_row, new_id}; |
| 6 | use crate::error::{Error, Result}; | 7 | use crate::error::{Error, Result}; |
| 7 | use crate::time::now_stamp; | 8 | use crate::time::now_stamp; |
| @@ -22,26 +23,12 @@ pub enum StatusState { |
| 22 | Error, | 23 | Error, |
| 23 | } | 24 | } |
| 24 | | 25 | |
| 25 | -impl StatusState { | 26 | +string_enum!(StatusState { |
| 26 | - pub fn as_str(self) -> &'static str { | 27 | + Pending = "pending", |
| 27 | - match self { | 28 | + Success = "success", |
| 28 | - StatusState::Pending => "pending", | 29 | + Failure = "failure", |
| 29 | - StatusState::Success => "success", | 30 | + Error = "error", |
| 30 | - StatusState::Failure => "failure", | 31 | +}); |
| 31 | - StatusState::Error => "error", | | |
| 32 | - } | | |
| 33 | - } | | |
| 34 | - | | |
| 35 | - pub fn parse(text: &str) -> Option<StatusState> { | | |
| 36 | - match text { | | |
| 37 | - "pending" => Some(StatusState::Pending), | | |
| 38 | - "success" => Some(StatusState::Success), | | |
| 39 | - "failure" => Some(StatusState::Failure), | | |
| 40 | - "error" => Some(StatusState::Error), | | |
| 41 | - _ => None, | | |
| 42 | - } | | |
| 43 | - } | | |
| 44 | -} | | |
| 45 | | 32 | |
| 46 | #[derive(Debug, Clone, PartialEq, Eq)] | 33 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 47 | pub struct CommitStatus { | 34 | pub struct CommitStatus { |
| @@ -272,13 +259,8 @@ impl Store { |
| 272 | } | 259 | } |
| 273 | } | 260 | } |
| 274 | | 261 | |
| 275 | -fn parse_state(text: &str) -> Result<StatusState> { | | |
| 276 | - StatusState::parse(text) | | |
| 277 | - .ok_or_else(|| Error::Database(format!("unknown commit status state: {text}"))) | | |
| 278 | -} | | |
| 279 | - | | |
| 280 | fn map_status(row: &Row) -> Result<CommitStatus> { | 262 | fn map_status(row: &Row) -> Result<CommitStatus> { |
| 281 | - let state = parse_state(&col_text(row, 4)?)?; | 263 | + let state = parse_db(&col_text(row, 4)?)?; |
| 282 | Ok(CommitStatus { | 264 | Ok(CommitStatus { |
| 283 | id: col_text(row, 0)?, | 265 | id: col_text(row, 0)?, |
| 284 | repo_id: col_text(row, 1)?, | 266 | repo_id: col_text(row, 1)?, |
| @@ -189,6 +189,7 @@ impl Store { |
| 189 | #[cfg(test)] | 189 | #[cfg(test)] |
| 190 | mod tests { | 190 | mod tests { |
| 191 | use crate::model::Visibility; | 191 | use crate::model::Visibility; |
| | 192 | + use crate::pulls::NewPull; |
| 192 | | 193 | |
| 193 | use super::*; | 194 | use super::*; |
| 194 | | 195 | |
| @@ -332,17 +333,17 @@ mod tests { |
| 332 | .await | 333 | .await |
| 333 | .unwrap(); | 334 | .unwrap(); |
| 334 | let pull = store | 335 | let pull = store |
| 335 | - .create_pull( | 336 | + .create_pull(&NewPull { |
| 336 | - &demo.id, | 337 | + repo_id: &demo.id, |
| 337 | - &tahinli.id, | 338 | + author_id: &tahinli.id, |
| 338 | - "change", | 339 | + title: "change", |
| 339 | - "", | 340 | + body: "", |
| 340 | - "main", | 341 | + base_branch: "main", |
| 341 | - &demo.id, | 342 | + head_repo_id: &demo.id, |
| 342 | - "topic", | 343 | + head_branch: "topic", |
| 343 | - OID, | 344 | + head_oid: OID, |
| 344 | - OID, | 345 | + base_oid: OID, |
| 345 | - ) | 346 | + }) |
| 346 | .await | 347 | .await |
| 347 | .unwrap(); | 348 | .unwrap(); |
| 348 | set_created_at(&store, "issues", &pull.issue.id, day2).await; | 349 | set_created_at(&store, "issues", &pull.issue.id, day2).await; |
| @@ -2,12 +2,13 @@ use turso::transaction::Transaction; |
| 2 | use turso::{Connection, Row, Value}; | 2 | use turso::{Connection, Row, Value}; |
| 3 | | 3 | |
| 4 | use super::finish; | 4 | use super::finish; |
| | 5 | +use super::issues::parse_db; |
| 5 | use super::{ | 6 | use super::{ |
| 6 | Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, insert_err, new_id, | 7 | Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, insert_err, new_id, |
| 7 | }; | 8 | }; |
| 8 | use crate::discussions::{ | 9 | use crate::discussions::{ |
| 9 | Discussion, DiscussionCategory, DiscussionComment, DiscussionFilter, DiscussionListItem, | 10 | Discussion, DiscussionCategory, DiscussionComment, DiscussionFilter, DiscussionListItem, |
| 10 | - DiscussionNotification, DiscussionReason, validate_comment, validate_discussion, | 11 | + DiscussionNotification, validate_comment, validate_discussion, |
| 11 | }; | 12 | }; |
| 12 | use crate::error::{Error, Result}; | 13 | use crate::error::{Error, Result}; |
| 13 | use crate::time::now_stamp; | 14 | use crate::time::now_stamp; |
| @@ -23,8 +24,7 @@ fn map_discussion(row: &Row) -> Result<Discussion> { |
| 23 | id: col_text(row, 0)?, | 24 | id: col_text(row, 0)?, |
| 24 | repo_id: col_text(row, 1)?, | 25 | repo_id: col_text(row, 1)?, |
| 25 | number: col_int(row, 2)?, | 26 | number: col_int(row, 2)?, |
| 26 | - category: DiscussionCategory::parse(&category) | 27 | + category: parse_db(&category)?, |
| 27 | - .ok_or_else(|| Error::Database(format!("stored category {category:?}")))?, | | |
| 28 | title: col_text(row, 4)?, | 28 | title: col_text(row, 4)?, |
| 29 | body: col_text(row, 5)?, | 29 | body: col_text(row, 5)?, |
| 30 | author_id: col_text(row, 6)?, | 30 | author_id: col_text(row, 6)?, |
| @@ -52,8 +52,7 @@ fn map_discussion_note(row: &Row) -> Result<DiscussionNotification> { |
| 52 | repo_name: col_text(row, 3)?, | 52 | repo_name: col_text(row, 3)?, |
| 53 | number: col_int(row, 4)?, | 53 | number: col_int(row, 4)?, |
| 54 | title: col_text(row, 5)?, | 54 | title: col_text(row, 5)?, |
| 55 | - reason: DiscussionReason::parse(&reason) | 55 | + reason: parse_db(&reason)?, |
| 56 | - .ok_or_else(|| Error::Database(format!("unknown discussion reason {reason:?}")))?, | | |
| 57 | last_actor_name: col_opt_text(row, 7)?, | 56 | last_actor_name: col_opt_text(row, 7)?, |
| 58 | unread: col_int(row, 8)? != 0, | 57 | unread: col_int(row, 8)? != 0, |
| 59 | updated_at: col_text(row, 9)?, | 58 | updated_at: col_text(row, 9)?, |
| @@ -689,6 +688,7 @@ async fn upsert_discussion_notification( |
| 689 | #[cfg(test)] | 688 | #[cfg(test)] |
| 690 | mod tests { | 689 | mod tests { |
| 691 | use super::*; | 690 | use super::*; |
| | 691 | + use crate::discussions::DiscussionReason; |
| 692 | use crate::model::{User, Visibility}; | 692 | use crate::model::{User, Visibility}; |
| 693 | | 693 | |
| 694 | struct Fixture { | 694 | struct Fixture { |
| @@ -10,15 +10,11 @@ pub enum EditTarget { |
| 10 | ReviewComment, | 10 | ReviewComment, |
| 11 | } | 11 | } |
| 12 | | 12 | |
| 13 | -impl EditTarget { | 13 | +string_enum!(EditTarget { |
| 14 | - pub fn as_str(self) -> &'static str { | 14 | + Issue = "issue", |
| 15 | - match self { | 15 | + Comment = "comment", |
| 16 | - Self::Issue => "issue", | 16 | + ReviewComment = "review_comment", |
| 17 | - Self::Comment => "comment", | 17 | +}); |
| 18 | - Self::ReviewComment => "review_comment", | | |
| 19 | - } | | |
| 20 | - } | | |
| 21 | -} | | |
| 22 | | 18 | |
| 23 | #[derive(Debug, Clone, PartialEq)] | 19 | #[derive(Debug, Clone, PartialEq)] |
| 24 | pub struct EditVersion { | 20 | pub struct EditVersion { |
| @@ -13,23 +13,11 @@ pub enum ExportState { |
| 13 | Failed, | 13 | Failed, |
| 14 | } | 14 | } |
| 15 | | 15 | |
| 16 | -impl ExportState { | 16 | +string_enum!(ExportState { |
| 17 | - pub fn as_str(self) -> &'static str { | 17 | + Building = "building", |
| 18 | - match self { | 18 | + Ready = "ready", |
| 19 | - ExportState::Building => "building", | 19 | + Failed = "failed", |
| 20 | - ExportState::Ready => "ready", | 20 | +}); |
| 21 | - ExportState::Failed => "failed", | | |
| 22 | - } | | |
| 23 | - } | | |
| 24 | - | | |
| 25 | - fn parse(s: &str) -> Self { | | |
| 26 | - match s { | | |
| 27 | - "ready" => ExportState::Ready, | | |
| 28 | - "failed" => ExportState::Failed, | | |
| 29 | - _ => ExportState::Building, | | |
| 30 | - } | | |
| 31 | - } | | |
| 32 | -} | | |
| 33 | | 21 | |
| 34 | #[derive(Debug, Clone, PartialEq)] | 22 | #[derive(Debug, Clone, PartialEq)] |
| 35 | pub struct DataExport { | 23 | pub struct DataExport { |
| @@ -49,7 +37,9 @@ fn map_export(row: &Row) -> Result<DataExport> { |
| 49 | Ok(DataExport { | 37 | Ok(DataExport { |
| 50 | id: col_text(row, 0)?, | 38 | id: col_text(row, 0)?, |
| 51 | user_id: col_text(row, 1)?, | 39 | user_id: col_text(row, 1)?, |
| 52 | - state: ExportState::parse(&col_text(row, 2)?), | 40 | + state: col_text(row, 2)? |
| | 41 | + .parse::<ExportState>() |
| | 42 | + .unwrap_or(ExportState::Building), |
| 53 | size: col_int(row, 3)?, | 43 | size: col_int(row, 3)?, |
| 54 | error: col_opt_text(row, 4)?, | 44 | error: col_opt_text(row, 4)?, |
| 55 | created_at: col_text(row, 5)?, | 45 | created_at: col_text(row, 5)?, |
| @@ -1,7 +1,8 @@ |
| 1 | use turso::{Row, Value}; | 1 | use turso::{Row, Value}; |
| 2 | | 2 | |
| | 3 | +use super::issues::parse_db; |
| 3 | use super::{Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, new_id, text}; | 4 | use super::{Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, new_id, text}; |
| 4 | -use crate::error::{Error, Result}; | 5 | +use crate::error::Result; |
| 5 | use crate::time::now_stamp; | 6 | use crate::time::now_stamp; |
| 6 | | 7 | |
| 7 | pub const MAX_EVENTS: i64 = 500; | 8 | pub const MAX_EVENTS: i64 = 500; |
| @@ -14,29 +15,17 @@ pub enum ImportState { |
| 14 | Failed, | 15 | Failed, |
| 15 | } | 16 | } |
| 16 | | 17 | |
| 17 | -impl ImportState { | 18 | +string_enum!(ImportState { |
| 18 | - pub fn as_str(self) -> &'static str { | 19 | + Queued = "queued", |
| 19 | - match self { | 20 | + Running = "running", |
| 20 | - ImportState::Queued => "queued", | 21 | + Done = "done", |
| 21 | - ImportState::Running => "running", | 22 | + Failed = "failed", |
| 22 | - ImportState::Done => "done", | 23 | +}); |
| 23 | - ImportState::Failed => "failed", | | |
| 24 | - } | | |
| 25 | - } | | |
| 26 | | 24 | |
| | 25 | +impl ImportState { |
| 27 | pub fn is_finished(self) -> bool { | 26 | pub fn is_finished(self) -> bool { |
| 28 | matches!(self, ImportState::Done | ImportState::Failed) | 27 | matches!(self, ImportState::Done | ImportState::Failed) |
| 29 | } | 28 | } |
| 30 | - | | |
| 31 | - fn parse(s: &str) -> Result<Self> { | | |
| 32 | - match s { | | |
| 33 | - "queued" => Ok(ImportState::Queued), | | |
| 34 | - "running" => Ok(ImportState::Running), | | |
| 35 | - "done" => Ok(ImportState::Done), | | |
| 36 | - "failed" => Ok(ImportState::Failed), | | |
| 37 | - other => Err(Error::Database(format!("unknown import state `{other}`"))), | | |
| 38 | - } | | |
| 39 | - } | | |
| 40 | } | 29 | } |
| 41 | | 30 | |
| 42 | #[derive(Debug, Clone, PartialEq)] | 31 | #[derive(Debug, Clone, PartialEq)] |
| @@ -83,7 +72,7 @@ fn map_job(row: &Row) -> Result<ImportJob> { |
| 83 | source: col_text(row, 3)?, | 72 | source: col_text(row, 3)?, |
| 84 | source_ref: col_text(row, 4)?, | 73 | source_ref: col_text(row, 4)?, |
| 85 | options: col_text(row, 5)?, | 74 | options: col_text(row, 5)?, |
| 86 | - state: ImportState::parse(&col_text(row, 6)?)?, | 75 | + state: parse_db(&col_text(row, 6)?)?, |
| 87 | stage: col_text(row, 7)?, | 76 | stage: col_text(row, 7)?, |
| 88 | done: col_int(row, 8)?, | 77 | done: col_int(row, 8)?, |
| 89 | total: col_int(row, 9)?, | 78 | total: col_int(row, 9)?, |
| @@ -163,6 +163,97 @@ pub(super) async fn insert_event( |
| 163 | Ok(()) | 163 | Ok(()) |
| 164 | } | 164 | } |
| 165 | | 165 | |
| | 166 | +fn check_body(body: &str) -> Result<()> { |
| | 167 | + validate_body(body)?; |
| | 168 | + if body.trim().is_empty() { |
| | 169 | + return Err(Error::Invalid("comment is empty".into())); |
| | 170 | + } |
| | 171 | + Ok(()) |
| | 172 | +} |
| | 173 | + |
| | 174 | +async fn insert_comment( |
| | 175 | + tx: &Connection, |
| | 176 | + issue_id: &str, |
| | 177 | + author_id: &str, |
| | 178 | + body: &str, |
| | 179 | +) -> Result<Comment> { |
| | 180 | + load_issue(tx, issue_id).await?; |
| | 181 | + let now = now_stamp(); |
| | 182 | + let comment = Comment { |
| | 183 | + id: new_id(), |
| | 184 | + issue_id: issue_id.to_string(), |
| | 185 | + author_id: author_id.to_string(), |
| | 186 | + body: body.to_string(), |
| | 187 | + created_at: now.clone(), |
| | 188 | + updated_at: now.clone(), |
| | 189 | + edited: false, |
| | 190 | + }; |
| | 191 | + tx.execute( |
| | 192 | + "INSERT INTO comments (id, issue_id, author_id, body, created_at, updated_at, edited) \ |
| | 193 | + VALUES (?1, ?2, ?3, ?4, ?5, ?6, 0)", |
| | 194 | + ( |
| | 195 | + comment.id.clone(), |
| | 196 | + comment.issue_id.clone(), |
| | 197 | + comment.author_id.clone(), |
| | 198 | + comment.body.clone(), |
| | 199 | + comment.created_at.clone(), |
| | 200 | + comment.updated_at.clone(), |
| | 201 | + ), |
| | 202 | + ) |
| | 203 | + .await |
| | 204 | + .map_err(db_err)?; |
| | 205 | + tx.execute( |
| | 206 | + "UPDATE issues SET comment_count = comment_count + 1, updated_at = ?2 WHERE id = ?1", |
| | 207 | + (issue_id.to_string(), now), |
| | 208 | + ) |
| | 209 | + .await |
| | 210 | + .map_err(db_err)?; |
| | 211 | + Ok(comment) |
| | 212 | +} |
| | 213 | + |
| | 214 | +async fn apply_issue_state( |
| | 215 | + tx: &Connection, |
| | 216 | + issue_id: &str, |
| | 217 | + actor_id: Option<&str>, |
| | 218 | + state: IssueState, |
| | 219 | + reason: Option<StateReason>, |
| | 220 | + mut data: Map<String, Json>, |
| | 221 | +) -> Result<bool> { |
| | 222 | + let current = load_issue(tx, issue_id).await?; |
| | 223 | + if current.state == state { |
| | 224 | + return Ok(false); |
| | 225 | + } |
| | 226 | + let now = now_stamp(); |
| | 227 | + let (reason_value, closed_at, kind) = match state { |
| | 228 | + IssueState::Open => (None, None, "reopened"), |
| | 229 | + IssueState::Closed => { |
| | 230 | + if let Some(r) = reason { |
| | 231 | + data.insert("reason".into(), Json::from(r.as_str())); |
| | 232 | + } |
| | 233 | + ( |
| | 234 | + reason.map(|r| r.as_str().to_string()), |
| | 235 | + Some(now.clone()), |
| | 236 | + "closed", |
| | 237 | + ) |
| | 238 | + } |
| | 239 | + }; |
| | 240 | + tx.execute( |
| | 241 | + "UPDATE issues SET state = ?2, state_reason = ?3, closed_at = ?4, updated_at = ?5 \ |
| | 242 | + WHERE id = ?1", |
| | 243 | + ( |
| | 244 | + issue_id.to_string(), |
| | 245 | + state.as_str().to_string(), |
| | 246 | + reason_value, |
| | 247 | + closed_at, |
| | 248 | + now, |
| | 249 | + ), |
| | 250 | + ) |
| | 251 | + .await |
| | 252 | + .map_err(db_err)?; |
| | 253 | + insert_event(tx, issue_id, actor_id, kind, &Json::Object(data)).await?; |
| | 254 | + Ok(true) |
| | 255 | +} |
| | 256 | + |
| 166 | pub(super) async fn load_issue(conn: &Connection, issue_id: &str) -> Result<Issue> { | 257 | pub(super) async fn load_issue(conn: &Connection, issue_id: &str) -> Result<Issue> { |
| 167 | fetch_opt( | 258 | fetch_opt( |
| 168 | conn, | 259 | conn, |
| @@ -503,43 +594,38 @@ impl Store { |
| 503 | reason: Option<StateReason>, | 594 | reason: Option<StateReason>, |
| 504 | data: Json, | 595 | data: Json, |
| 505 | ) -> Result<bool> { | 596 | ) -> Result<bool> { |
| 506 | - let mut data = event_data(data)?; | 597 | + let data = event_data(data)?; |
| 507 | let conn = self.inner.conn.lock().await; | 598 | let conn = self.inner.conn.lock().await; |
| 508 | let tx = conn.unchecked_transaction().await.map_err(db_err)?; | 599 | let tx = conn.unchecked_transaction().await.map_err(db_err)?; |
| 509 | - let outcome: Result<bool> = async { | 600 | + let outcome = apply_issue_state(&tx, issue_id, actor_id, state, reason, data).await; |
| 510 | - let current = load_issue(&tx, issue_id).await?; | 601 | + finish(tx, outcome).await |
| 511 | - if current.state == state { | 602 | + } |
| 512 | - return Ok(false); | 603 | + |
| 513 | - } | 604 | + pub async fn comment_and_set_state( |
| 514 | - let now = now_stamp(); | 605 | + &self, |
| 515 | - let (reason_value, closed_at, kind) = match state { | 606 | + issue_id: &str, |
| 516 | - IssueState::Open => (None, None, "reopened"), | 607 | + author_id: &str, |
| 517 | - IssueState::Closed => { | 608 | + body: Option<&str>, |
| 518 | - if let Some(r) = reason { | 609 | + change: Option<(IssueState, Option<StateReason>)>, |
| 519 | - data.insert("reason".into(), Json::from(r.as_str())); | 610 | + ) -> Result<(Option<Comment>, bool)> { |
| 520 | - } | 611 | + if let Some(body) = body { |
| 521 | - ( | 612 | + check_body(body)?; |
| 522 | - reason.map(|r| r.as_str().to_string()), | 613 | + } |
| 523 | - Some(now.clone()), | 614 | + let conn = self.inner.conn.lock().await; |
| 524 | - "closed", | 615 | + let tx = conn.unchecked_transaction().await.map_err(db_err)?; |
| 525 | - ) | 616 | + let outcome: Result<(Option<Comment>, bool)> = async { |
| | 617 | + let comment = match body { |
| | 618 | + Some(body) => Some(insert_comment(&tx, issue_id, author_id, body).await?), |
| | 619 | + None => None, |
| | 620 | + }; |
| | 621 | + let changed = match change { |
| | 622 | + Some((state, reason)) => { |
| | 623 | + apply_issue_state(&tx, issue_id, Some(author_id), state, reason, Map::new()) |
| | 624 | + .await? |
| 526 | } | 625 | } |
| | 626 | + None => false, |
| 527 | }; | 627 | }; |
| 528 | - tx.execute( | 628 | + Ok((comment, changed)) |
| 529 | - "UPDATE issues SET state = ?2, state_reason = ?3, closed_at = ?4, updated_at = ?5 \ | | |
| 530 | - WHERE id = ?1", | | |
| 531 | - ( | | |
| 532 | - issue_id.to_string(), | | |
| 533 | - state.as_str().to_string(), | | |
| 534 | - reason_value, | | |
| 535 | - closed_at, | | |
| 536 | - now, | | |
| 537 | - ), | | |
| 538 | - ) | | |
| 539 | - .await | | |
| 540 | - .map_err(db_err)?; | | |
| 541 | - insert_event(&tx, issue_id, actor_id, kind, &Json::Object(data)).await?; | | |
| 542 | - Ok(true) | | |
| 543 | } | 629 | } |
| 544 | .await; | 630 | .await; |
| 545 | finish(tx, outcome).await | 631 | finish(tx, outcome).await |
| @@ -597,47 +683,10 @@ impl Store { |
| 597 | author_id: &str, | 683 | author_id: &str, |
| 598 | body: &str, | 684 | body: &str, |
| 599 | ) -> Result<Comment> { | 685 | ) -> Result<Comment> { |
| 600 | - validate_body(body)?; | 686 | + check_body(body)?; |
| 601 | - if body.trim().is_empty() { | | |
| 602 | - return Err(Error::Invalid("comment is empty".into())); | | |
| 603 | - } | | |
| 604 | let conn = self.inner.conn.lock().await; | 687 | let conn = self.inner.conn.lock().await; |
| 605 | let tx = conn.unchecked_transaction().await.map_err(db_err)?; | 688 | let tx = conn.unchecked_transaction().await.map_err(db_err)?; |
| 606 | - let outcome: Result<Comment> = async { | 689 | + let outcome = insert_comment(&tx, issue_id, author_id, body).await; |
| 607 | - load_issue(&tx, issue_id).await?; | | |
| 608 | - let now = now_stamp(); | | |
| 609 | - let comment = Comment { | | |
| 610 | - id: new_id(), | | |
| 611 | - issue_id: issue_id.to_string(), | | |
| 612 | - author_id: author_id.to_string(), | | |
| 613 | - body: body.to_string(), | | |
| 614 | - created_at: now.clone(), | | |
| 615 | - updated_at: now.clone(), | | |
| 616 | - edited: false, | | |
| 617 | - }; | | |
| 618 | - tx.execute( | | |
| 619 | - "INSERT INTO comments (id, issue_id, author_id, body, created_at, updated_at, edited) \ | | |
| 620 | - VALUES (?1, ?2, ?3, ?4, ?5, ?6, 0)", | | |
| 621 | - ( | | |
| 622 | - comment.id.clone(), | | |
| 623 | - comment.issue_id.clone(), | | |
| 624 | - comment.author_id.clone(), | | |
| 625 | - comment.body.clone(), | | |
| 626 | - comment.created_at.clone(), | | |
| 627 | - comment.updated_at.clone(), | | |
| 628 | - ), | | |
| 629 | - ) | | |
| 630 | - .await | | |
| 631 | - .map_err(db_err)?; | | |
| 632 | - tx.execute( | | |
| 633 | - "UPDATE issues SET comment_count = comment_count + 1, updated_at = ?2 WHERE id = ?1", | | |
| 634 | - (issue_id.to_string(), now), | | |
| 635 | - ) | | |
| 636 | - .await | | |
| 637 | - .map_err(db_err)?; | | |
| 638 | - Ok(comment) | | |
| 639 | - } | | |
| 640 | - .await; | | |
| 641 | finish(tx, outcome).await | 690 | finish(tx, outcome).await |
| 642 | } | 691 | } |
| 643 | | 692 | |
| @@ -4,7 +4,7 @@ use jiff::civil::Date; |
| 4 | use serde_json::json; | 4 | use serde_json::json; |
| 5 | use turso::{Connection, Row}; | 5 | use turso::{Connection, Row}; |
| 6 | | 6 | |
| 7 | -use super::issues::insert_event; | 7 | +use super::issues::{insert_event, parse_db}; |
| 8 | use super::{ | 8 | use super::{ |
| 9 | Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, finish, insert_err, | 9 | Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, finish, insert_err, |
| 10 | new_id, | 10 | new_id, |
| @@ -630,7 +630,7 @@ fn map_milestone(row: &Row) -> Result<Milestone> { |
| 630 | title: col_text(row, 2)?, | 630 | title: col_text(row, 2)?, |
| 631 | description: col_text(row, 3)?, | 631 | description: col_text(row, 3)?, |
| 632 | due_on: col_opt_text(row, 4)?, | 632 | due_on: col_opt_text(row, 4)?, |
| 633 | - state: col_text(row, 5)?.parse()?, | 633 | + state: parse_db(&col_text(row, 5)?)?, |
| 634 | created_at: col_text(row, 6)?, | 634 | created_at: col_text(row, 6)?, |
| 635 | closed_at: col_opt_text(row, 7)?, | 635 | closed_at: col_opt_text(row, 7)?, |
| 636 | open_issues: col_int(row, 8)?, | 636 | open_issues: col_int(row, 8)?, |
| @@ -7,7 +7,7 @@ use super::{ |
| 7 | use crate::error::{Error, Result}; | 7 | use crate::error::{Error, Result}; |
| 8 | use crate::mail::{ | 8 | use crate::mail::{ |
| 9 | MailKind, MailPassword, MailSettings, MailSettingsUpdate, MailState, MailStatus, OutboxEntry, | 9 | MailKind, MailPassword, MailSettings, MailSettingsUpdate, MailState, MailStatus, OutboxEntry, |
| 10 | - OutgoingMail, Security, validate_settings, | 10 | + OutgoingMail, validate_settings, |
| 11 | }; | 11 | }; |
| 12 | use crate::secret; | 12 | use crate::secret; |
| 13 | | 13 | |
| @@ -42,8 +42,9 @@ fn map_settings(row: &Row) -> Result<MailSettings> { |
| 42 | Ok(MailSettings { | 42 | Ok(MailSettings { |
| 43 | host: col_text(row, 0)?, | 43 | host: col_text(row, 0)?, |
| 44 | port: u16::try_from(port).map_err(|_| Error::Database("bad SMTP port".into()))?, | 44 | port: u16::try_from(port).map_err(|_| Error::Database("bad SMTP port".into()))?, |
| 45 | - security: Security::parse(&security) | 45 | + security: security |
| 46 | - .ok_or_else(|| Error::Database(format!("unknown mail security {security}")))?, | 46 | + .parse() |
| | 47 | + .map_err(|_| Error::Database(format!("unknown mail security {security}")))?, |
| 47 | username: col_text(row, 3)?, | 48 | username: col_text(row, 3)?, |
| 48 | from_addr: col_text(row, 4)?, | 49 | from_addr: col_text(row, 4)?, |
| 49 | from_name: col_text(row, 5)?, | 50 | from_name: col_text(row, 5)?, |
| @@ -70,8 +71,9 @@ fn map_outbox(row: &Row) -> Result<OutboxEntry> { |
| 70 | last_error: col_opt_text(row, 9)?, | 71 | last_error: col_opt_text(row, 9)?, |
| 71 | message_id: col_opt_text(row, 10)?, | 72 | message_id: col_opt_text(row, 10)?, |
| 72 | in_reply_to: col_opt_text(row, 11)?, | 73 | in_reply_to: col_opt_text(row, 11)?, |
| 73 | - kind: MailKind::parse(&kind) | 74 | + kind: kind |
| 74 | - .ok_or_else(|| Error::Database(format!("unknown mail kind {kind}")))?, | 75 | + .parse() |
| | 76 | + .map_err(|_| Error::Database(format!("unknown mail kind {kind}")))?, |
| 75 | user_id: col_opt_text(row, 13)?, | 77 | user_id: col_opt_text(row, 13)?, |
| 76 | lease_until: col_opt_text(row, 14)?, | 78 | lease_until: col_opt_text(row, 14)?, |
| 77 | discarded_at: col_opt_text(row, 15)?, | 79 | discarded_at: col_opt_text(row, 15)?, |
| @@ -389,7 +391,7 @@ mod tests { |
| 389 | use std::time::Duration; | 391 | use std::time::Duration; |
| 390 | | 392 | |
| 391 | use super::*; | 393 | use super::*; |
| 392 | - use crate::mail::MailState; | 394 | + use crate::mail::{MailState, Security}; |
| 393 | use crate::time::{now_stamp, stamp_after}; | 395 | use crate::time::{now_stamp, stamp_after}; |
| 394 | | 396 | |
| 395 | const KEY: [u8; 32] = [7u8; 32]; | 397 | const KEY: [u8; 32] = [7u8; 32]; |
| @@ -1,5 +1,6 @@ |
| 1 | use turso::Value; | 1 | use turso::Value; |
| 2 | | 2 | |
| | 3 | +use super::issues::parse_db; |
| 3 | use super::{Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, finish, new_id}; | 4 | use super::{Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, finish, new_id}; |
| 4 | use crate::error::{Error, Result}; | 5 | use crate::error::{Error, Result}; |
| 5 | use crate::merge_queue::{QueueEntry, QueueState}; | 6 | use crate::merge_queue::{QueueEntry, QueueState}; |
| @@ -129,6 +130,17 @@ impl Store { |
| 129 | Ok(out) | 130 | Ok(out) |
| 130 | } | 131 | } |
| 131 | | 132 | |
| | 133 | + pub async fn queue_testing_all(&self) -> Result<Vec<QueueEntry>> { |
| | 134 | + let conn = self.read_conn().await; |
| | 135 | + fetch_all( |
| | 136 | + &conn, |
| | 137 | + &format!("SELECT {QUEUE_COLS} FROM merge_queue WHERE state = 'testing'"), |
| | 138 | + (), |
| | 139 | + map_entry, |
| | 140 | + ) |
| | 141 | + .await |
| | 142 | + } |
| | 143 | + |
| 132 | pub async fn queue_testing_on(&self, repo_id: &str, oid: &str) -> Result<Vec<QueueEntry>> { | 144 | pub async fn queue_testing_on(&self, repo_id: &str, oid: &str) -> Result<Vec<QueueEntry>> { |
| 133 | let conn = self.read_conn().await; | 145 | let conn = self.read_conn().await; |
| 134 | fetch_all( | 146 | fetch_all( |
| @@ -224,7 +236,7 @@ fn map_entry(row: &turso::Row) -> Result<QueueEntry> { |
| 224 | merge_style: col_text(row, 5)? | 236 | merge_style: col_text(row, 5)? |
| 225 | .parse::<MergeStyle>() | 237 | .parse::<MergeStyle>() |
| 226 | .map_err(|e| Error::Database(e.to_string()))?, | 238 | .map_err(|e| Error::Database(e.to_string()))?, |
| 227 | - state: col_text(row, 6)?.parse::<QueueState>()?, | 239 | + state: parse_db(&col_text(row, 6)?)?, |
| 228 | seq: col_int(row, 7)?, | 240 | seq: col_int(row, 7)?, |
| 229 | enqueued_by: col_text(row, 8)?, | 241 | enqueued_by: col_text(row, 8)?, |
| 230 | enqueued_at: col_text(row, 9)?, | 242 | enqueued_at: col_text(row, 9)?, |
| @@ -1,8 +1,13 @@ |
| | 1 | +use std::collections::HashSet; |
| | 2 | + |
| 1 | use turso::Connection; | 3 | use turso::Connection; |
| 2 | | 4 | |
| 3 | use crate::error::{Error, Result}; | 5 | use crate::error::{Error, Result}; |
| | 6 | +use crate::names::normalize_name; |
| 4 | use crate::time::now_stamp; | 7 | use crate::time::now_stamp; |
| 5 | | 8 | |
| | 9 | +const MILESTONE_TITLE_REPAIR: i64 = 76; |
| | 10 | + |
| 6 | pub const MIGRATIONS: &[(u32, &str)] = &[ | 11 | pub const MIGRATIONS: &[(u32, &str)] = &[ |
| 7 | (1, include_str!("../../migrations/0001_init.sql")), | 12 | (1, include_str!("../../migrations/0001_init.sql")), |
| 8 | (2, include_str!("../../migrations/0002_profile.sql")), | 13 | (2, include_str!("../../migrations/0002_profile.sql")), |
| @@ -126,6 +131,14 @@ pub const MIGRATIONS: &[(u32, &str)] = &[ |
| 126 | 74, | 131 | 74, |
| 127 | include_str!("../../migrations/0074_failed_runs_dismissed.sql"), | 132 | include_str!("../../migrations/0074_failed_runs_dismissed.sql"), |
| 128 | ), | 133 | ), |
| | 134 | + ( |
| | 135 | + 75, |
| | 136 | + include_str!("../../migrations/0075_runner_registered_labels.sql"), |
| | 137 | + ), |
| | 138 | + ( |
| | 139 | + 76, |
| | 140 | + include_str!("../../migrations/0076_milestone_title_repair.sql"), |
| | 141 | + ), |
| 129 | ]; | 142 | ]; |
| 130 | | 143 | |
| 131 | pub fn latest_schema_version() -> u32 { | 144 | pub fn latest_schema_version() -> u32 { |
| @@ -151,6 +164,9 @@ pub async fn migrate(conn: &Connection) -> Result<()> { |
| 151 | } | 164 | } |
| 152 | let tx = conn.unchecked_transaction().await.map_err(migration_err)?; | 165 | let tx = conn.unchecked_transaction().await.map_err(migration_err)?; |
| 153 | tx.execute_batch(sql).await.map_err(migration_err)?; | 166 | tx.execute_batch(sql).await.map_err(migration_err)?; |
| | 167 | + if version == MILESTONE_TITLE_REPAIR { |
| | 168 | + repair_swapped_milestone_titles(&tx).await?; |
| | 169 | + } |
| 154 | tx.execute( | 170 | tx.execute( |
| 155 | "INSERT INTO schema_migrations (version, applied_at) VALUES (?1, ?2)", | 171 | "INSERT INTO schema_migrations (version, applied_at) VALUES (?1, ?2)", |
| 156 | (version, now_stamp()), | 172 | (version, now_stamp()), |
| @@ -163,6 +179,49 @@ pub async fn migrate(conn: &Connection) -> Result<()> { |
| 163 | Ok(()) | 179 | Ok(()) |
| 164 | } | 180 | } |
| 165 | | 181 | |
| | 182 | +async fn repair_swapped_milestone_titles(conn: &Connection) -> Result<()> { |
| | 183 | + let mut rows = conn |
| | 184 | + .query( |
| | 185 | + "SELECT id, repo_id, title, title_folded FROM milestones", |
| | 186 | + (), |
| | 187 | + ) |
| | 188 | + .await |
| | 189 | + .map_err(migration_err)?; |
| | 190 | + let mut taken = HashSet::new(); |
| | 191 | + let mut swapped = Vec::new(); |
| | 192 | + while let Some(row) = rows.next().await.map_err(migration_err)? { |
| | 193 | + let id: String = row.get(0).map_err(migration_err)?; |
| | 194 | + let repo: String = row.get(1).map_err(migration_err)?; |
| | 195 | + let title: String = row.get(2).map_err(migration_err)?; |
| | 196 | + let folded: String = row.get(3).map_err(migration_err)?; |
| | 197 | + if folded != normalize_name(&title) { |
| | 198 | + swapped.push((id, repo.clone(), folded.clone())); |
| | 199 | + } |
| | 200 | + taken.insert((repo, folded)); |
| | 201 | + } |
| | 202 | + drop(rows); |
| | 203 | + for (id, repo, raw) in swapped { |
| | 204 | + let folded = normalize_name(&raw); |
| | 205 | + taken.remove(&(repo.clone(), raw.clone())); |
| | 206 | + if taken.contains(&(repo.clone(), folded.clone())) { |
| | 207 | + taken.insert((repo, raw)); |
| | 208 | + tracing::warn!( |
| | 209 | + id, |
| | 210 | + "milestone title repair skipped: folded name already in use" |
| | 211 | + ); |
| | 212 | + continue; |
| | 213 | + } |
| | 214 | + conn.execute( |
| | 215 | + "UPDATE milestones SET title = ?2, title_folded = ?3 WHERE id = ?1", |
| | 216 | + (id, raw, folded.clone()), |
| | 217 | + ) |
| | 218 | + .await |
| | 219 | + .map_err(migration_err)?; |
| | 220 | + taken.insert((repo, folded)); |
| | 221 | + } |
| | 222 | + Ok(()) |
| | 223 | +} |
| | 224 | + |
| 166 | async fn applied_versions(conn: &Connection) -> Result<Vec<i64>> { | 225 | async fn applied_versions(conn: &Connection) -> Result<Vec<i64>> { |
| 167 | let mut rows = conn | 226 | let mut rows = conn |
| 168 | .query("SELECT version FROM schema_migrations ORDER BY version", ()) | 227 | .query("SELECT version FROM schema_migrations ORDER BY version", ()) |
| @@ -1,5 +1,6 @@ |
| 1 | use turso::{Row, Value}; | 1 | use turso::{Row, Value}; |
| 2 | | 2 | |
| | 3 | +use super::issues::parse_db; |
| 3 | use super::{ | 4 | use super::{ |
| 4 | Store, col_bool, col_int, col_opt_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, | 5 | Store, col_bool, col_int, col_opt_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, |
| 5 | finish, insert_err, missing_row, new_id, opt_text, | 6 | finish, insert_err, missing_row, new_id, opt_text, |
| @@ -22,7 +23,7 @@ fn map_mirror(row: &Row) -> Result<Mirror> { |
| 22 | Ok(Mirror { | 23 | Ok(Mirror { |
| 23 | id: col_text(row, 0)?, | 24 | id: col_text(row, 0)?, |
| 24 | repo_id: col_text(row, 1)?, | 25 | repo_id: col_text(row, 1)?, |
| 25 | - direction: col_text(row, 2)?.parse::<MirrorDirection>()?, | 26 | + direction: parse_db(&col_text(row, 2)?)?, |
| 26 | url: col_text(row, 3)?, | 27 | url: col_text(row, 3)?, |
| 27 | username: col_text(row, 4)?, | 28 | username: col_text(row, 4)?, |
| 28 | has_secret: col_bool(row, 5)?, | 29 | has_secret: col_bool(row, 5)?, |
| @@ -239,12 +240,12 @@ impl Store { |
| 239 | .await | 240 | .await |
| 240 | } | 241 | } |
| 241 | | 242 | |
| 242 | - pub async fn next_mirror_due(&self) -> Result<Option<String>> { | 243 | + pub async fn next_mirror_due(&self, now: &str) -> Result<Option<String>> { |
| 243 | let conn = self.read_conn().await; | 244 | let conn = self.read_conn().await; |
| 244 | fetch_opt( | 245 | fetch_opt( |
| 245 | &conn, | 246 | &conn, |
| 246 | - "SELECT MIN(next_sync_at) FROM repo_mirrors WHERE enabled = 1", | 247 | + "SELECT MIN(next_sync_at) FROM repo_mirrors WHERE enabled = 1 AND next_sync_at > ?1", |
| 247 | - (), | 248 | + (now.to_string(),), |
| 248 | |row| col_opt_text(row, 0), | 249 | |row| col_opt_text(row, 0), |
| 249 | ) | 250 | ) |
| 250 | .await | 251 | .await |
| @@ -557,7 +558,7 @@ mod tests { |
| 557 | #[tokio::test] | 558 | #[tokio::test] |
| 558 | async fn due_mirrors_are_earliest_first_and_skip_disabled() { | 559 | async fn due_mirrors_are_earliest_first_and_skip_disabled() { |
| 559 | let (store, _tahinli, repo, _dir) = setup().await; | 560 | let (store, _tahinli, repo, _dir) = setup().await; |
| 560 | - assert_eq!(store.next_mirror_due().await.unwrap(), None); | 561 | + assert_eq!(store.next_mirror_due(&now_stamp()).await.unwrap(), None); |
| 561 | let late = store | 562 | let late = store |
| 562 | .create_mirror(&push(&repo, "https://late.example/r.git")) | 563 | .create_mirror(&push(&repo, "https://late.example/r.git")) |
| 563 | .await | 564 | .await |
| @@ -602,10 +603,23 @@ mod tests { |
| 602 | .await | 603 | .await |
| 603 | .unwrap(); | 604 | .unwrap(); |
| 604 | assert_eq!( | 605 | assert_eq!( |
| 605 | - store.next_mirror_due().await.unwrap().as_deref(), | 606 | + store |
| | 607 | + .next_mirror_due("2019-06-01T00:00:00.000000000Z") |
| | 608 | + .await |
| | 609 | + .unwrap() |
| | 610 | + .as_deref(), |
| 606 | Some("2020-01-01T00:00:00.000000000Z"), | 611 | Some("2020-01-01T00:00:00.000000000Z"), |
| 607 | "a disabled mirror is ignored" | 612 | "a disabled mirror is ignored" |
| 608 | ); | 613 | ); |
| | 614 | + assert_eq!( |
| | 615 | + store |
| | 616 | + .next_mirror_due("2020-01-01T12:00:00.000000000Z") |
| | 617 | + .await |
| | 618 | + .unwrap() |
| | 619 | + .as_deref(), |
| | 620 | + Some("2020-01-02T00:00:00.000000000Z"), |
| | 621 | + "a past due mirror is not a wake time" |
| | 622 | + ); |
| 609 | | 623 | |
| 610 | let now = now_stamp(); | 624 | let now = now_stamp(); |
| 611 | let due: Vec<String> = store | 625 | let due: Vec<String> = store |
| @@ -623,7 +623,7 @@ impl Store { |
| 623 | name.to_string(), | 623 | name.to_string(), |
| 624 | normalize_name(name), | 624 | normalize_name(name), |
| 625 | description.to_string(), | 625 | description.to_string(), |
| 626 | - visibility_str(visibility), | 626 | + visibility.as_str(), |
| 627 | default_branch.to_string(), | 627 | default_branch.to_string(), |
| 628 | now_stamp(), | 628 | now_stamp(), |
| 629 | fork_of.map(str::to_string), | 629 | fork_of.map(str::to_string), |
| @@ -701,7 +701,7 @@ impl Store { |
| 701 | .await | 701 | .await |
| 702 | .map_err(db_err)?; | 702 | .map_err(db_err)?; |
| 703 | match rows.next().await.map_err(db_err)? { | 703 | match rows.next().await.map_err(db_err)? { |
| 704 | - Some(row) => Ok(Some(parse_role(&col_text(&row, 0)?)?)), | 704 | + Some(row) => Ok(Some(issues::parse_db(&col_text(&row, 0)?)?)), |
| 705 | None => Ok(None), | 705 | None => Ok(None), |
| 706 | } | 706 | } |
| 707 | } | 707 | } |
| @@ -725,7 +725,7 @@ impl Store { |
| 725 | let conn = self.inner.conn.lock().await; | 725 | let conn = self.inner.conn.lock().await; |
| 726 | conn.execute( | 726 | conn.execute( |
| 727 | "INSERT OR REPLACE INTO collaborators (repo_id, user_id, role) VALUES (?1, ?2, ?3)", | 727 | "INSERT OR REPLACE INTO collaborators (repo_id, user_id, role) VALUES (?1, ?2, ?3)", |
| 728 | - (repo_id.to_string(), user_id.to_string(), role_str(role)), | 728 | + (repo_id.to_string(), user_id.to_string(), role.as_str()), |
| 729 | ) | 729 | ) |
| 730 | .await | 730 | .await |
| 731 | .map_err(db_err)?; | 731 | .map_err(db_err)?; |
| @@ -1160,7 +1160,7 @@ fn map_repo(row: &Row) -> Result<Repo> { |
| 1160 | owner_name: col_text(row, 2)?, | 1160 | owner_name: col_text(row, 2)?, |
| 1161 | name: col_text(row, 3)?, | 1161 | name: col_text(row, 3)?, |
| 1162 | description: col_text(row, 4)?, | 1162 | description: col_text(row, 4)?, |
| 1163 | - visibility: parse_visibility(&col_text(row, 5)?)?, | 1163 | + visibility: issues::parse_db(&col_text(row, 5)?)?, |
| 1164 | default_branch: col_text(row, 6)?, | 1164 | default_branch: col_text(row, 6)?, |
| 1165 | archived: col_bool(row, 7)?, | 1165 | archived: col_bool(row, 7)?, |
| 1166 | created_at: col_text(row, 8)?, | 1166 | created_at: col_text(row, 8)?, |
| @@ -1168,42 +1168,6 @@ fn map_repo(row: &Row) -> Result<Repo> { |
| 1168 | }) | 1168 | }) |
| 1169 | } | 1169 | } |
| 1170 | | 1170 | |
| 1171 | -fn visibility_str(v: Visibility) -> &'static str { | | |
| 1172 | - match v { | | |
| 1173 | - Visibility::Public => "public", | | |
| 1174 | - Visibility::Private => "private", | | |
| 1175 | - } | | |
| 1176 | -} | | |
| 1177 | - | | |
| 1178 | -fn parse_visibility(s: &str) -> Result<Visibility> { | | |
| 1179 | - match s { | | |
| 1180 | - "public" => Ok(Visibility::Public), | | |
| 1181 | - "private" => Ok(Visibility::Private), | | |
| 1182 | - other => Err(Error::Database(format!("unknown visibility {other:?}"))), | | |
| 1183 | - } | | |
| 1184 | -} | | |
| 1185 | - | | |
| 1186 | -fn role_str(r: Role) -> &'static str { | | |
| 1187 | - match r { | | |
| 1188 | - Role::Read => "read", | | |
| 1189 | - Role::Triage => "triage", | | |
| 1190 | - Role::Write => "write", | | |
| 1191 | - Role::Maintain => "maintain", | | |
| 1192 | - Role::Admin => "admin", | | |
| 1193 | - } | | |
| 1194 | -} | | |
| 1195 | - | | |
| 1196 | -fn parse_role(s: &str) -> Result<Role> { | | |
| 1197 | - match s { | | |
| 1198 | - "read" => Ok(Role::Read), | | |
| 1199 | - "triage" => Ok(Role::Triage), | | |
| 1200 | - "write" => Ok(Role::Write), | | |
| 1201 | - "maintain" => Ok(Role::Maintain), | | |
| 1202 | - "admin" => Ok(Role::Admin), | | |
| 1203 | - other => Err(Error::Database(format!("unknown role {other:?}"))), | | |
| 1204 | - } | | |
| 1205 | -} | | |
| 1206 | - | | |
| 1207 | impl Store { | 1171 | impl Store { |
| 1208 | pub async fn delete_repo(&self, repo_id: &str) -> Result<()> { | 1172 | pub async fn delete_repo(&self, repo_id: &str) -> Result<()> { |
| 1209 | let conn = self.inner.conn.lock().await; | 1173 | let conn = self.inner.conn.lock().await; |
| @@ -2205,7 +2169,7 @@ impl Store { |
| 2205 | WHERE collaborators.repo_id = ?1 ORDER BY users.username_folded" | 2169 | WHERE collaborators.repo_id = ?1 ORDER BY users.username_folded" |
| 2206 | ), | 2170 | ), |
| 2207 | (repo_id.to_string(),), | 2171 | (repo_id.to_string(),), |
| 2208 | - |row| Ok((map_user(row)?, parse_role(&col_text(row, 19)?)?)), | 2172 | + |row| Ok((map_user(row)?, issues::parse_db(&col_text(row, 19)?)?)), |
| 2209 | ) | 2173 | ) |
| 2210 | .await | 2174 | .await |
| 2211 | } | 2175 | } |
| @@ -1,6 +1,7 @@ |
| 1 | use turso::transaction::Transaction; | 1 | use turso::transaction::Transaction; |
| 2 | use turso::{Row, Value}; | 2 | use turso::{Row, Value}; |
| 3 | | 3 | |
| | 4 | +use super::issues::parse_db; |
| 4 | use super::repo_listing::VIEWER_ACCESS; | 5 | use super::repo_listing::VIEWER_ACCESS; |
| 5 | use super::{ | 6 | use super::{ |
| 6 | Store, USER_COLS, col_int, col_text, db_err, fetch_all, fetch_opt, finish, map_user, new_id, | 7 | Store, USER_COLS, col_int, col_text, db_err, fetch_all, fetch_opt, finish, map_user, new_id, |
| @@ -31,15 +32,18 @@ const NOTIFICATION_SELECT: &str = "SELECT n.id, n.repo_id, o.username, r.name, n |
| 31 | LEFT JOIN users a ON a.id = n.last_actor_id"; | 32 | LEFT JOIN users a ON a.id = n.last_actor_id"; |
| 32 | | 33 | |
| 33 | fn watch_level_from(s: &str) -> Result<WatchLevel> { | 34 | fn watch_level_from(s: &str) -> Result<WatchLevel> { |
| 34 | - WatchLevel::parse(s).ok_or_else(|| Error::Database(format!("unknown watch level {s:?}"))) | 35 | + s.parse() |
| | 36 | + .map_err(|_| Error::Database(format!("unknown watch level {s:?}"))) |
| 35 | } | 37 | } |
| 36 | | 38 | |
| 37 | fn sub_state_from(s: &str) -> Result<SubState> { | 39 | fn sub_state_from(s: &str) -> Result<SubState> { |
| 38 | - SubState::parse(s).ok_or_else(|| Error::Database(format!("unknown subscription state {s:?}"))) | 40 | + s.parse() |
| | 41 | + .map_err(|_| Error::Database(format!("unknown subscription state {s:?}"))) |
| 39 | } | 42 | } |
| 40 | | 43 | |
| 41 | fn reason_from(s: &str) -> Result<Reason> { | 44 | fn reason_from(s: &str) -> Result<Reason> { |
| 42 | - Reason::parse(s).ok_or_else(|| Error::Database(format!("unknown notification reason {s:?}"))) | 45 | + s.parse() |
| | 46 | + .map_err(|_| Error::Database(format!("unknown notification reason {s:?}"))) |
| 43 | } | 47 | } |
| 44 | | 48 | |
| 45 | fn map_notification(row: &Row) -> Result<Notification> { | 49 | fn map_notification(row: &Row) -> Result<Notification> { |
| @@ -53,7 +57,7 @@ fn map_notification(row: &Row) -> Result<Notification> { |
| 53 | number: col_int(row, 5)?, | 57 | number: col_int(row, 5)?, |
| 54 | is_pull: kind == "pull", | 58 | is_pull: kind == "pull", |
| 55 | title: col_text(row, 7)?, | 59 | title: col_text(row, 7)?, |
| 56 | - issue_state: col_text(row, 8)?.parse()?, | 60 | + issue_state: parse_db(&col_text(row, 8)?)?, |
| 57 | reason: reason_from(&col_text(row, 9)?)?, | 61 | reason: reason_from(&col_text(row, 9)?)?, |
| 58 | last_activity: col_text(row, 10)?, | 62 | last_activity: col_text(row, 10)?, |
| 59 | last_actor_name: match row.get_value(11).map_err(db_err)? { | 63 | last_actor_name: match row.get_value(11).map_err(db_err)? { |
| @@ -1,9 +1,10 @@ |
| 1 | use turso::{Connection, IntoParams}; | 1 | use turso::{Connection, IntoParams}; |
| 2 | | 2 | |
| 3 | use super::finish; | 3 | use super::finish; |
| | 4 | +use super::issues::parse_db; |
| 4 | use super::{ | 5 | use super::{ |
| 5 | REPO_COLS, Store, USER_COLS, col_int, col_text, db_err, fetch_all, fetch_opt, insert_err, | 6 | REPO_COLS, Store, USER_COLS, col_int, col_text, db_err, fetch_all, fetch_opt, insert_err, |
| 6 | - map_repo, map_user, missing_row, new_id, parse_role, role_str, | 7 | + map_repo, map_user, missing_row, new_id, |
| 7 | }; | 8 | }; |
| 8 | use crate::authz::max_role; | 9 | use crate::authz::max_role; |
| 9 | use crate::error::{Error, Result}; | 10 | use crate::error::{Error, Result}; |
| @@ -20,22 +21,10 @@ pub enum OrgMemberRole { |
| 20 | Member, | 21 | Member, |
| 21 | } | 22 | } |
| 22 | | 23 | |
| 23 | -impl OrgMemberRole { | 24 | +string_enum!(OrgMemberRole { |
| 24 | - pub fn as_str(self) -> &'static str { | 25 | + Owner = "owner", |
| 25 | - match self { | 26 | + Member = "member", |
| 26 | - OrgMemberRole::Owner => "owner", | 27 | +}); |
| 27 | - OrgMemberRole::Member => "member", | | |
| 28 | - } | | |
| 29 | - } | | |
| 30 | - | | |
| 31 | - pub fn parse(s: &str) -> Result<Self> { | | |
| 32 | - match s { | | |
| 33 | - "owner" => Ok(OrgMemberRole::Owner), | | |
| 34 | - "member" => Ok(OrgMemberRole::Member), | | |
| 35 | - other => Err(Error::Database(format!("org member role {other:?}"))), | | |
| 36 | - } | | |
| 37 | - } | | |
| 38 | -} | | |
| 39 | | 28 | |
| 40 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] | 29 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 41 | pub enum DefaultRepoRole { | 30 | pub enum DefaultRepoRole { |
| @@ -44,24 +33,13 @@ pub enum DefaultRepoRole { |
| 44 | Write, | 33 | Write, |
| 45 | } | 34 | } |
| 46 | | 35 | |
| 47 | -impl DefaultRepoRole { | 36 | +string_enum!(DefaultRepoRole { |
| 48 | - pub fn as_str(self) -> &'static str { | 37 | + None = "none", |
| 49 | - match self { | 38 | + Read = "read", |
| 50 | - DefaultRepoRole::None => "none", | 39 | + Write = "write", |
| 51 | - DefaultRepoRole::Read => "read", | 40 | +}); |
| 52 | - DefaultRepoRole::Write => "write", | | |
| 53 | - } | | |
| 54 | - } | | |
| 55 | - | | |
| 56 | - pub fn parse(s: &str) -> Result<Self> { | | |
| 57 | - match s { | | |
| 58 | - "none" => Ok(DefaultRepoRole::None), | | |
| 59 | - "read" => Ok(DefaultRepoRole::Read), | | |
| 60 | - "write" => Ok(DefaultRepoRole::Write), | | |
| 61 | - other => Err(Error::Database(format!("default repo role {other:?}"))), | | |
| 62 | - } | | |
| 63 | - } | | |
| 64 | | 41 | |
| | 42 | +impl DefaultRepoRole { |
| 65 | fn role(self) -> Option<Role> { | 43 | fn role(self) -> Option<Role> { |
| 66 | match self { | 44 | match self { |
| 67 | DefaultRepoRole::None => None, | 45 | DefaultRepoRole::None => None, |
| @@ -96,7 +74,7 @@ fn map_team(row: &turso::Row) -> Result<Team> { |
| 96 | org_id: col_text(row, 1)?, | 74 | org_id: col_text(row, 1)?, |
| 97 | name: col_text(row, 2)?, | 75 | name: col_text(row, 2)?, |
| 98 | description: col_text(row, 3)?, | 76 | description: col_text(row, 3)?, |
| 99 | - role: parse_role(&col_text(row, 4)?)?, | 77 | + role: parse_db(&col_text(row, 4)?)?, |
| 100 | all_repos: col_int(row, 5)? != 0, | 78 | all_repos: col_int(row, 5)? != 0, |
| 101 | created_at: col_text(row, 6)?, | 79 | created_at: col_text(row, 6)?, |
| 102 | }) | 80 | }) |
| @@ -141,7 +119,7 @@ async fn member_role( |
| 141 | conn, | 119 | conn, |
| 142 | "SELECT role FROM org_members WHERE org_id = ?1 AND user_id = ?2 LIMIT 1", | 120 | "SELECT role FROM org_members WHERE org_id = ?1 AND user_id = ?2 LIMIT 1", |
| 143 | (org_id.to_string(), user_id.to_string()), | 121 | (org_id.to_string(), user_id.to_string()), |
| 144 | - |row| col_text(row, 0).and_then(|s| OrgMemberRole::parse(&s)), | 122 | + |row| col_text(row, 0).and_then(|s| parse_db(&s)), |
| 145 | ) | 123 | ) |
| 146 | .await | 124 | .await |
| 147 | } | 125 | } |
| @@ -219,7 +197,7 @@ impl Store { |
| 219 | (org_id.to_string(),), | 197 | (org_id.to_string(),), |
| 220 | |row| { | 198 | |row| { |
| 221 | Ok(OrgSettings { | 199 | Ok(OrgSettings { |
| 222 | - default_repo_role: DefaultRepoRole::parse(&col_text(row, 0)?)?, | 200 | + default_repo_role: parse_db(&col_text(row, 0)?)?, |
| 223 | members_can_create_repos: col_int(row, 1)? != 0, | 201 | members_can_create_repos: col_int(row, 1)? != 0, |
| 224 | }) | 202 | }) |
| 225 | }, | 203 | }, |
| @@ -256,7 +234,7 @@ impl Store { |
| 256 | ORDER BY (org_role = 'owner') DESC, username_folded" | 234 | ORDER BY (org_role = 'owner') DESC, username_folded" |
| 257 | ), | 235 | ), |
| 258 | (org_id.to_string(),), | 236 | (org_id.to_string(),), |
| 259 | - |row| Ok((map_user(row)?, OrgMemberRole::parse(&col_text(row, 19)?)?)), | 237 | + |row| Ok((map_user(row)?, parse_db(&col_text(row, 19)?)?)), |
| 260 | ) | 238 | ) |
| 261 | .await | 239 | .await |
| 262 | } | 240 | } |
| @@ -371,7 +349,7 @@ impl Store { |
| 371 | (SELECT org_id FROM org_members WHERE user_id = ?1) ORDER BY username_folded" | 349 | (SELECT org_id FROM org_members WHERE user_id = ?1) ORDER BY username_folded" |
| 372 | ), | 350 | ), |
| 373 | (user_id.to_string(),), | 351 | (user_id.to_string(),), |
| 374 | - |row| Ok((map_user(row)?, OrgMemberRole::parse(&col_text(row, 19)?)?)), | 352 | + |row| Ok((map_user(row)?, parse_db(&col_text(row, 19)?)?)), |
| 375 | ) | 353 | ) |
| 376 | .await | 354 | .await |
| 377 | } | 355 | } |
| @@ -460,7 +438,7 @@ impl Store { |
| 460 | display.clone(), | 438 | display.clone(), |
| 461 | folded, | 439 | folded, |
| 462 | description.to_string(), | 440 | description.to_string(), |
| 463 | - role_str(role).to_string(), | 441 | + role.as_str().to_string(), |
| 464 | i64::from(all_repos), | 442 | i64::from(all_repos), |
| 465 | created_at.clone(), | 443 | created_at.clone(), |
| 466 | ), | 444 | ), |
| @@ -497,7 +475,7 @@ impl Store { |
| 497 | display, | 475 | display, |
| 498 | folded, | 476 | folded, |
| 499 | description.to_string(), | 477 | description.to_string(), |
| 500 | - role_str(role).to_string(), | 478 | + role.as_str().to_string(), |
| 501 | i64::from(all_repos), | 479 | i64::from(all_repos), |
| 502 | ), | 480 | ), |
| 503 | ) | 481 | ) |
| @@ -657,7 +635,7 @@ impl Store { |
| 657 | &conn, | 635 | &conn, |
| 658 | "SELECT default_repo_role FROM org_settings WHERE org_id = ?1 LIMIT 1", | 636 | "SELECT default_repo_role FROM org_settings WHERE org_id = ?1 LIMIT 1", |
| 659 | (org_id.to_string(),), | 637 | (org_id.to_string(),), |
| 660 | - |row| col_text(row, 0).and_then(|s| DefaultRepoRole::parse(&s)), | 638 | + |row| col_text(row, 0).and_then(|s| parse_db::<DefaultRepoRole>(&s)), |
| 661 | ) | 639 | ) |
| 662 | .await? | 640 | .await? |
| 663 | .ok_or(Error::NotFound)? | 641 | .ok_or(Error::NotFound)? |
| @@ -668,7 +646,7 @@ impl Store { |
| 668 | WHERE t.org_id = ?1 AND tm.user_id = ?2 AND (t.all_repos = 1 OR EXISTS \ | 646 | WHERE t.org_id = ?1 AND tm.user_id = ?2 AND (t.all_repos = 1 OR EXISTS \ |
| 669 | (SELECT 1 FROM team_repos tr WHERE tr.team_id = t.id AND tr.repo_id = ?3))", | 647 | (SELECT 1 FROM team_repos tr WHERE tr.team_id = t.id AND tr.repo_id = ?3))", |
| 670 | (org_id.to_string(), user_id.to_string(), repo_id.to_string()), | 648 | (org_id.to_string(), user_id.to_string(), repo_id.to_string()), |
| 671 | - |row| parse_role(&col_text(row, 0)?), | 649 | + |row| parse_db(&col_text(row, 0)?), |
| 672 | ) | 650 | ) |
| 673 | .await?; | 651 | .await?; |
| 674 | Ok(team_roles | 652 | Ok(team_roles |
| @@ -9,7 +9,7 @@ use super::{ |
| 9 | use crate::error::{Error, Result}; | 9 | use crate::error::{Error, Result}; |
| 10 | use crate::issues::{IssueFilter, IssueListItem, IssueState, validate_body, validate_title}; | 10 | use crate::issues::{IssueFilter, IssueListItem, IssueState, validate_body, validate_title}; |
| 11 | use crate::model::{Id, Repo}; | 11 | use crate::model::{Id, Repo}; |
| 12 | -use crate::pulls::{AutoMerge, MergeStyle, Mergeable, PullRequest}; | 12 | +use crate::pulls::{AutoMerge, MergeStyle, Mergeable, NewPull, PullRequest}; |
| 13 | use crate::time::now_stamp; | 13 | use crate::time::now_stamp; |
| 14 | | 14 | |
| 15 | const PULL_COLS: &str = "i.id, i.repo_id, i.number, i.title, i.body, i.state, i.state_reason, \ | 15 | const PULL_COLS: &str = "i.id, i.repo_id, i.number, i.title, i.body, i.state, i.state_reason, \ |
| @@ -90,19 +90,18 @@ pub(super) async fn delete_repo_pull_rows(tx: &Transaction<'_>, repo_id: &str) - |
| 90 | } | 90 | } |
| 91 | | 91 | |
| 92 | impl Store { | 92 | impl Store { |
| 93 | - #[allow(clippy::too_many_arguments)] | 93 | + pub async fn create_pull(&self, new: &NewPull<'_>) -> Result<PullRequest> { |
| 94 | - pub async fn create_pull( | 94 | + let NewPull { |
| 95 | - &self, | 95 | + repo_id, |
| 96 | - repo_id: &str, | 96 | + author_id, |
| 97 | - author_id: &str, | 97 | + title, |
| 98 | - title: &str, | 98 | + body, |
| 99 | - body: &str, | 99 | + base_branch, |
| 100 | - base_branch: &str, | 100 | + head_repo_id, |
| 101 | - head_repo_id: &str, | 101 | + head_branch, |
| 102 | - head_branch: &str, | 102 | + head_oid, |
| 103 | - head_oid: &str, | 103 | + base_oid, |
| 104 | - base_oid: &str, | 104 | + } = *new; |
| 105 | - ) -> Result<PullRequest> { | | |
| 106 | let title = validate_title(title)?; | 105 | let title = validate_title(title)?; |
| 107 | validate_body(body)?; | 106 | validate_body(body)?; |
| 108 | let conn = self.inner.conn.lock().await; | 107 | let conn = self.inner.conn.lock().await; |
| @@ -167,6 +166,17 @@ impl Store { |
| 167 | finish(tx, outcome).await | 166 | finish(tx, outcome).await |
| 168 | } | 167 | } |
| 169 | | 168 | |
| | 169 | + pub async fn delete_new_pull(&self, issue_id: &str) -> Result<()> { |
| | 170 | + let conn = self.inner.conn.lock().await; |
| | 171 | + conn.execute( |
| | 172 | + "DELETE FROM issues WHERE id = ?1 AND kind = 'pull'", |
| | 173 | + (issue_id.to_string(),), |
| | 174 | + ) |
| | 175 | + .await |
| | 176 | + .map_err(db_err)?; |
| | 177 | + Ok(()) |
| | 178 | + } |
| | 179 | + |
| 170 | pub async fn pull_by_number(&self, repo_id: &str, number: i64) -> Result<Option<PullRequest>> { | 180 | pub async fn pull_by_number(&self, repo_id: &str, number: i64) -> Result<Option<PullRequest>> { |
| 171 | let conn = self.read_conn().await; | 181 | let conn = self.read_conn().await; |
| 172 | fetch_opt( | 182 | fetch_opt( |
| @@ -608,17 +618,17 @@ mod tests { |
| 608 | title: &str, | 618 | title: &str, |
| 609 | ) -> PullRequest { | 619 | ) -> PullRequest { |
| 610 | fx.store | 620 | fx.store |
| 611 | - .create_pull( | 621 | + .create_pull(&NewPull { |
| 612 | - &repo.id, | 622 | + repo_id: &repo.id, |
| 613 | - &fx.tahinli.id, | 623 | + author_id: &fx.tahinli.id, |
| 614 | title, | 624 | title, |
| 615 | - "", | 625 | + body: "", |
| 616 | - "main", | 626 | + base_branch: "main", |
| 617 | - head_repo, | 627 | + head_repo_id: head_repo, |
| 618 | head_branch, | 628 | head_branch, |
| 619 | - &"a".repeat(40), | 629 | + head_oid: &"a".repeat(40), |
| 620 | - &"b".repeat(40), | 630 | + base_oid: &"b".repeat(40), |
| 621 | - ) | 631 | + }) |
| 622 | .await | 632 | .await |
| 623 | .unwrap() | 633 | .unwrap() |
| 624 | } | 634 | } |
| @@ -898,17 +908,17 @@ mod tests { |
| 898 | let first = open_pull(&fx, &repo, &repo.id, "feature", "first").await; | 908 | let first = open_pull(&fx, &repo, &repo.id, "feature", "first").await; |
| 899 | let second = fx | 909 | let second = fx |
| 900 | .store | 910 | .store |
| 901 | - .create_pull( | 911 | + .create_pull(&NewPull { |
| 902 | - &repo.id, | 912 | + repo_id: &repo.id, |
| 903 | - &fx.bob.id, | 913 | + author_id: &fx.bob.id, |
| 904 | - "second", | 914 | + title: "second", |
| 905 | - "", | 915 | + body: "", |
| 906 | - "main", | 916 | + base_branch: "main", |
| 907 | - &repo.id, | 917 | + head_repo_id: &repo.id, |
| 908 | - "feature", | 918 | + head_branch: "feature", |
| 909 | - &"c".repeat(40), | 919 | + head_oid: &"c".repeat(40), |
| 910 | - &"b".repeat(40), | 920 | + base_oid: &"b".repeat(40), |
| 911 | - ) | 921 | + }) |
| 912 | .await; | 922 | .await; |
| 913 | match second { | 923 | match second { |
| 914 | Err(Error::Conflict(msg)) => assert!( | 924 | Err(Error::Conflict(msg)) => assert!( |
| @@ -1314,17 +1324,17 @@ mod tests { |
| 1314 | let incoming = open_pull(&fx, &source, &fork.id, "topic", "incoming").await; | 1324 | let incoming = open_pull(&fx, &source, &fork.id, "topic", "incoming").await; |
| 1315 | let outgoing = fx | 1325 | let outgoing = fx |
| 1316 | .store | 1326 | .store |
| 1317 | - .create_pull( | 1327 | + .create_pull(&NewPull { |
| 1318 | - &fork.id, | 1328 | + repo_id: &fork.id, |
| 1319 | - &fx.bob.id, | 1329 | + author_id: &fx.bob.id, |
| 1320 | - "outgoing", | 1330 | + title: "outgoing", |
| 1321 | - "", | 1331 | + body: "", |
| 1322 | - "main", | 1332 | + base_branch: "main", |
| 1323 | - &source.id, | 1333 | + head_repo_id: &source.id, |
| 1324 | - "main", | 1334 | + head_branch: "main", |
| 1325 | - &"a".repeat(40), | 1335 | + head_oid: &"a".repeat(40), |
| 1326 | - &"b".repeat(40), | 1336 | + base_oid: &"b".repeat(40), |
| 1327 | - ) | 1337 | + }) |
| 1328 | .await | 1338 | .await |
| 1329 | .unwrap(); | 1339 | .unwrap(); |
| 1330 | | 1340 | |
| @@ -42,7 +42,7 @@ impl Store { |
| 42 | kind.as_str().to_string(), | 42 | kind.as_str().to_string(), |
| 43 | target_id.to_string(), | 43 | target_id.to_string(), |
| 44 | user_id.to_string(), | 44 | user_id.to_string(), |
| 45 | - reaction.name().to_string(), | 45 | + reaction.as_str().to_string(), |
| 46 | ), | 46 | ), |
| 47 | ) | 47 | ) |
| 48 | .await | 48 | .await |
| @@ -57,7 +57,7 @@ impl Store { |
| 57 | kind.as_str().to_string(), | 57 | kind.as_str().to_string(), |
| 58 | target_id.to_string(), | 58 | target_id.to_string(), |
| 59 | user_id.to_string(), | 59 | user_id.to_string(), |
| 60 | - reaction.name().to_string(), | 60 | + reaction.as_str().to_string(), |
| 61 | now_stamp(), | 61 | now_stamp(), |
| 62 | ), | 62 | ), |
| 63 | ) | 63 | ) |
| @@ -106,7 +106,7 @@ impl Store { |
| 106 | ) | 106 | ) |
| 107 | .await?; | 107 | .await?; |
| 108 | for (target, emoji, user_id, username) in rows { | 108 | for (target, emoji, user_id, username) in rows { |
| 109 | - let Some(reaction) = Reaction::parse(&emoji) else { | 109 | + let Ok(reaction) = emoji.parse::<Reaction>() else { |
| 110 | continue; | 110 | continue; |
| 111 | }; | 111 | }; |
| 112 | grouped | 112 | grouped |
| @@ -2,7 +2,7 @@ use turso::{Row, Value}; |
| 2 | | 2 | |
| 3 | use super::{Store, col_opt_text, col_text, db_err, fetch_all, fetch_opt}; | 3 | use super::{Store, col_opt_text, col_text, db_err, fetch_all, fetch_opt}; |
| 4 | use crate::error::Result; | 4 | use crate::error::Result; |
| 5 | -use crate::time::now_stamp; | 5 | +use crate::time::{now_stamp, stamp_to_unix}; |
| 6 | | 6 | |
| 7 | pub const DB_SUBJECT: &str = "db"; | 7 | pub const DB_SUBJECT: &str = "db"; |
| 8 | | 8 | |
| @@ -17,6 +17,36 @@ pub struct ReplicationStatus { |
| 17 | pub refs_sha256: Option<String>, | 17 | pub refs_sha256: Option<String>, |
| 18 | } | 18 | } |
| 19 | | 19 | |
| | 20 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| | 21 | +pub enum ReplicationHealth { |
| | 22 | + Ok, |
| | 23 | + Lagging, |
| | 24 | + Error, |
| | 25 | + Never, |
| | 26 | +} |
| | 27 | + |
| | 28 | +pub fn window_secs(minutes: u64) -> i64 { |
| | 29 | + i64::try_from(minutes.saturating_mul(120)).unwrap_or(i64::MAX) |
| | 30 | +} |
| | 31 | + |
| | 32 | +pub fn replication_health( |
| | 33 | + status: Option<&ReplicationStatus>, |
| | 34 | + now: i64, |
| | 35 | + window: i64, |
| | 36 | +) -> ReplicationHealth { |
| | 37 | + match status { |
| | 38 | + None => ReplicationHealth::Never, |
| | 39 | + Some(s) if s.last_error.is_some() => ReplicationHealth::Error, |
| | 40 | + Some(s) => match s.last_ok_at.as_deref() { |
| | 41 | + None => ReplicationHealth::Never, |
| | 42 | + Some(ok) => match stamp_to_unix(ok) { |
| | 43 | + Some(ok) if now.saturating_sub(ok) <= window => ReplicationHealth::Ok, |
| | 44 | + _ => ReplicationHealth::Lagging, |
| | 45 | + }, |
| | 46 | + }, |
| | 47 | + } |
| | 48 | +} |
| | 49 | + |
| 20 | fn map_status(row: &Row) -> Result<ReplicationStatus> { | 50 | fn map_status(row: &Row) -> Result<ReplicationStatus> { |
| 21 | Ok(ReplicationStatus { | 51 | Ok(ReplicationStatus { |
| 22 | subject: col_text(row, 0)?, | 52 | subject: col_text(row, 0)?, |
| @@ -190,4 +220,49 @@ mod tests { |
| 190 | assert_eq!(healed.last_error, None, "success clears the error"); | 220 | assert_eq!(healed.last_error, None, "success clears the error"); |
| 191 | assert_eq!(healed.refs_sha256.as_deref(), Some("abc"), "refs hash kept"); | 221 | assert_eq!(healed.refs_sha256.as_deref(), Some("abc"), "refs hash kept"); |
| 192 | } | 222 | } |
| | 223 | + |
| | 224 | + #[test] |
| | 225 | + fn health_reads_errors_before_age() { |
| | 226 | + let now = stamp_to_unix("2026-06-02T00:00:00Z").unwrap(); |
| | 227 | + let window = window_secs(30); |
| | 228 | + let fresh = ReplicationStatus { |
| | 229 | + subject: "r".into(), |
| | 230 | + last_ok_at: Some("2026-06-01T23:30:00Z".into()), |
| | 231 | + last_error: None, |
| | 232 | + last_attempt_at: None, |
| | 233 | + refs_sha256: None, |
| | 234 | + }; |
| | 235 | + assert_eq!( |
| | 236 | + replication_health(Some(&fresh), now, window), |
| | 237 | + ReplicationHealth::Ok |
| | 238 | + ); |
| | 239 | + let old = ReplicationStatus { |
| | 240 | + last_ok_at: Some("2025-06-01T00:00:00Z".into()), |
| | 241 | + ..fresh.clone() |
| | 242 | + }; |
| | 243 | + assert_eq!( |
| | 244 | + replication_health(Some(&old), now, window), |
| | 245 | + ReplicationHealth::Lagging |
| | 246 | + ); |
| | 247 | + let failing = ReplicationStatus { |
| | 248 | + last_error: Some("boom".into()), |
| | 249 | + ..fresh.clone() |
| | 250 | + }; |
| | 251 | + assert_eq!( |
| | 252 | + replication_health(Some(&failing), now, window), |
| | 253 | + ReplicationHealth::Error |
| | 254 | + ); |
| | 255 | + assert_eq!( |
| | 256 | + replication_health(None, now, window), |
| | 257 | + ReplicationHealth::Never |
| | 258 | + ); |
| | 259 | + let never_ok = ReplicationStatus { |
| | 260 | + last_ok_at: None, |
| | 261 | + ..fresh.clone() |
| | 262 | + }; |
| | 263 | + assert_eq!( |
| | 264 | + replication_health(Some(&never_ok), now, window), |
| | 265 | + ReplicationHealth::Never |
| | 266 | + ); |
| | 267 | + } |
| 193 | } | 268 | } |
| @@ -36,7 +36,7 @@ fn map_review(row: &Row) -> Result<Review> { |
| 36 | created_at: col_text(row, 8)?, | 36 | created_at: col_text(row, 8)?, |
| 37 | submitted_at: col_opt_text(row, 9)?, | 37 | submitted_at: col_opt_text(row, 9)?, |
| 38 | dismissed_from: col_opt_text(row, 10)? | 38 | dismissed_from: col_opt_text(row, 10)? |
| 39 | - .map(|state| state.parse::<ReviewState>()) | 39 | + .map(|state| parse_db(&state)) |
| 40 | .transpose()?, | 40 | .transpose()?, |
| 41 | }) | 41 | }) |
| 42 | } | 42 | } |
| @@ -803,6 +803,7 @@ impl Store { |
| 803 | mod tests { | 803 | mod tests { |
| 804 | use super::*; | 804 | use super::*; |
| 805 | use crate::model::{User, Visibility}; | 805 | use crate::model::{User, Visibility}; |
| | 806 | + use crate::pulls::NewPull; |
| 806 | | 807 | |
| 807 | fn oid(c: char) -> String { | 808 | fn oid(c: char) -> String { |
| 808 | c.to_string().repeat(40) | 809 | c.to_string().repeat(40) |
| @@ -847,17 +848,17 @@ mod tests { |
| 847 | let head = format!("feature-{topic}"); | 848 | let head = format!("feature-{topic}"); |
| 848 | let pull = fx | 849 | let pull = fx |
| 849 | .store | 850 | .store |
| 850 | - .create_pull( | 851 | + .create_pull(&NewPull { |
| 851 | - &fx.repo_id, | 852 | + repo_id: &fx.repo_id, |
| 852 | - &fx.tahinli.id, | 853 | + author_id: &fx.tahinli.id, |
| 853 | - "change", | 854 | + title: "change", |
| 854 | - "", | 855 | + body: "", |
| 855 | - "main", | 856 | + base_branch: "main", |
| 856 | - &fx.repo_id, | 857 | + head_repo_id: &fx.repo_id, |
| 857 | - &head, | 858 | + head_branch: &head, |
| 858 | - &oid('a'), | 859 | + head_oid: &oid('a'), |
| 859 | - &oid('b'), | 860 | + base_oid: &oid('b'), |
| 860 | - ) | 861 | + }) |
| 861 | .await | 862 | .await |
| 862 | .unwrap(); | 863 | .unwrap(); |
| 863 | pull.issue.id.clone() | 864 | pull.issue.id.clone() |
| @@ -2,6 +2,7 @@ use std::time::Duration; |
| 2 | | 2 | |
| 3 | use turso::{Row, Value}; | 3 | use turso::{Row, Value}; |
| 4 | | 4 | |
| | 5 | +use super::issues::parse_db; |
| 5 | use super::needs::{failing_runs_params, failing_runs_sql}; | 6 | use super::needs::{failing_runs_params, failing_runs_sql}; |
| 6 | use super::notifications::{readable_params, readable_repo}; | 7 | use super::notifications::{readable_params, readable_repo}; |
| 7 | use super::{Store, col_int, col_opt_text, col_text, fetch_all}; | 8 | use super::{Store, col_int, col_opt_text, col_text, fetch_all}; |
| @@ -72,7 +73,7 @@ fn map_actor_run(row: &Row) -> Result<ActorRun> { |
| 72 | repo: col_text(row, 1)?, | 73 | repo: col_text(row, 1)?, |
| 73 | number: col_int(row, 2)?, | 74 | number: col_int(row, 2)?, |
| 74 | git_ref: col_text(row, 3)?, | 75 | git_ref: col_text(row, 3)?, |
| 75 | - state: col_text(row, 4)?.parse::<RunState>()?, | 76 | + state: parse_db(&col_text(row, 4)?)?, |
| 76 | created_at: col_text(row, 5)?, | 77 | created_at: col_text(row, 5)?, |
| 77 | finished_at: col_opt_text(row, 6)?, | 78 | finished_at: col_opt_text(row, 6)?, |
| 78 | jobs_total: count_from(col_int(row, 7)?)?, | 79 | jobs_total: count_from(col_int(row, 7)?)?, |
| @@ -126,7 +127,7 @@ impl Store { |
| 126 | let conn = self.read_conn().await; | 127 | let conn = self.read_conn().await; |
| 127 | fetch_all(&conn, &sql, params, |row| { | 128 | fetch_all(&conn, &sql, params, |row| { |
| 128 | let reason_text = col_text(row, 5)?; | 129 | let reason_text = col_text(row, 5)?; |
| 129 | - let reason = Reason::parse(&reason_text).ok_or_else(|| { | 130 | + let reason = reason_text.parse::<Reason>().map_err(|_| { |
| 130 | Error::Database(format!("unknown notification reason {reason_text:?}")) | 131 | Error::Database(format!("unknown notification reason {reason_text:?}")) |
| 131 | })?; | 132 | })?; |
| 132 | Ok(WaitingItem { | 133 | Ok(WaitingItem { |
| @@ -1,8 +1,8 @@ |
| 1 | use std::collections::HashMap; | 1 | use std::collections::HashMap; |
| 2 | -use std::str::FromStr; | | |
| 3 | | 2 | |
| 4 | use turso::Value; | 3 | use turso::Value; |
| 5 | | 4 | |
| | 5 | +use super::issues::parse_db; |
| 6 | use super::{ | 6 | use super::{ |
| 7 | SSH_KEY_COLS, Store, col_opt_text, col_text, db_err, fetch_all, fetch_opt, insert_err, | 7 | SSH_KEY_COLS, Store, col_opt_text, col_text, db_err, fetch_all, fetch_opt, insert_err, |
| 8 | map_ssh_key, new_id, | 8 | map_ssh_key, new_id, |
| @@ -46,53 +46,18 @@ pub enum SigKind { |
| 46 | Gpg, | 46 | Gpg, |
| 47 | } | 47 | } |
| 48 | | 48 | |
| 49 | -impl SigStatus { | 49 | +string_enum!(SigStatus { |
| 50 | - pub fn as_str(self) -> &'static str { | 50 | + Verified = "verified", |
| 51 | - match self { | 51 | + Unverified = "unverified", |
| 52 | - SigStatus::Verified => "verified", | 52 | + Unsigned = "unsigned", |
| 53 | - SigStatus::Unverified => "unverified", | 53 | + UnknownKey = "unknown_key", |
| 54 | - SigStatus::Unsigned => "unsigned", | 54 | + Bad = "bad", |
| 55 | - SigStatus::UnknownKey => "unknown_key", | 55 | +}); |
| 56 | - SigStatus::Bad => "bad", | | |
| 57 | - } | | |
| 58 | - } | | |
| 59 | -} | | |
| 60 | - | | |
| 61 | -impl FromStr for SigStatus { | | |
| 62 | - type Err = Error; | | |
| 63 | - | | |
| 64 | - fn from_str(s: &str) -> Result<Self> { | | |
| 65 | - match s { | | |
| 66 | - "verified" => Ok(SigStatus::Verified), | | |
| 67 | - "unverified" => Ok(SigStatus::Unverified), | | |
| 68 | - "unsigned" => Ok(SigStatus::Unsigned), | | |
| 69 | - "unknown_key" => Ok(SigStatus::UnknownKey), | | |
| 70 | - "bad" => Ok(SigStatus::Bad), | | |
| 71 | - other => Err(Error::Database(format!("unknown signature status {other}"))), | | |
| 72 | - } | | |
| 73 | - } | | |
| 74 | -} | | |
| 75 | | 56 | |
| 76 | -impl SigKind { | 57 | +string_enum!(SigKind { |
| 77 | - pub fn as_str(self) -> &'static str { | 58 | + Ssh = "ssh", |
| 78 | - match self { | 59 | + Gpg = "gpg", |
| 79 | - SigKind::Ssh => "ssh", | 60 | +}); |
| 80 | - SigKind::Gpg => "gpg", | | |
| 81 | - } | | |
| 82 | - } | | |
| 83 | -} | | |
| 84 | - | | |
| 85 | -impl FromStr for SigKind { | | |
| 86 | - type Err = Error; | | |
| 87 | - | | |
| 88 | - fn from_str(s: &str) -> Result<Self> { | | |
| 89 | - match s { | | |
| 90 | - "ssh" => Ok(SigKind::Ssh), | | |
| 91 | - "gpg" => Ok(SigKind::Gpg), | | |
| 92 | - other => Err(Error::Database(format!("unknown signature kind {other}"))), | | |
| 93 | - } | | |
| 94 | - } | | |
| 95 | -} | | |
| 96 | | 61 | |
| 97 | fn map_gpg_key(row: &turso::Row) -> Result<GpgKey> { | 62 | fn map_gpg_key(row: &turso::Row) -> Result<GpgKey> { |
| 98 | let emails_json = col_text(row, 4)?; | 63 | let emails_json = col_text(row, 4)?; |
| @@ -110,10 +75,8 @@ fn map_gpg_key(row: &turso::Row) -> Result<GpgKey> { |
| 110 | | 75 | |
| 111 | fn map_cached(row: &turso::Row) -> Result<(String, CachedSig)> { | 76 | fn map_cached(row: &turso::Row) -> Result<(String, CachedSig)> { |
| 112 | let oid = col_text(row, 0)?; | 77 | let oid = col_text(row, 0)?; |
| 113 | - let status = col_text(row, 1)?.parse::<SigStatus>()?; | 78 | + let status = parse_db(&col_text(row, 1)?)?; |
| 114 | - let kind = col_opt_text(row, 2)? | 79 | + let kind = col_opt_text(row, 2)?.map(|k| parse_db(&k)).transpose()?; |
| 115 | - .map(|k| k.parse::<SigKind>()) | | |
| 116 | - .transpose()?; | | |
| 117 | Ok(( | 80 | Ok(( |
| 118 | oid, | 81 | oid, |
| 119 | CachedSig { | 82 | CachedSig { |
| @@ -1,6 +1,7 @@ |
| 1 | use serde::{Deserialize, Serialize}; | 1 | use serde::{Deserialize, Serialize}; |
| 2 | use turso::Connection; | 2 | use turso::Connection; |
| 3 | | 3 | |
| | 4 | +use super::issues::parse_db; |
| 4 | use super::{Store, col_int, col_text, db_err, fetch_all, fetch_opt, finish, new_id}; | 5 | use super::{Store, col_int, col_text, db_err, fetch_all, fetch_opt, finish, new_id}; |
| 5 | use crate::error::{Error, Result}; | 6 | use crate::error::{Error, Result}; |
| 6 | use crate::time::now_stamp; | 7 | use crate::time::now_stamp; |
| @@ -25,23 +26,14 @@ impl SnippetVisibility { |
| 25 | SnippetVisibility::Unlisted, | 26 | SnippetVisibility::Unlisted, |
| 26 | SnippetVisibility::Private, | 27 | SnippetVisibility::Private, |
| 27 | ]; | 28 | ]; |
| 28 | - | | |
| 29 | - pub fn as_str(self) -> &'static str { | | |
| 30 | - match self { | | |
| 31 | - SnippetVisibility::Public => "public", | | |
| 32 | - SnippetVisibility::Unlisted => "unlisted", | | |
| 33 | - SnippetVisibility::Private => "private", | | |
| 34 | - } | | |
| 35 | - } | | |
| 36 | - | | |
| 37 | - pub fn parse(name: &str) -> Option<SnippetVisibility> { | | |
| 38 | - SnippetVisibility::ALL | | |
| 39 | - .iter() | | |
| 40 | - .copied() | | |
| 41 | - .find(|v| v.as_str() == name) | | |
| 42 | - } | | |
| 43 | } | 29 | } |
| 44 | | 30 | |
| | 31 | +string_enum!(SnippetVisibility { |
| | 32 | + Public = "public", |
| | 33 | + Unlisted = "unlisted", |
| | 34 | + Private = "private", |
| | 35 | +}); |
| | 36 | + |
| 45 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] | 37 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 46 | pub struct SnippetFile { | 38 | pub struct SnippetFile { |
| 47 | pub name: String, | 39 | pub name: String, |
| @@ -174,8 +166,7 @@ fn map_snippet(row: &turso::Row) -> Result<Snippet> { |
| 174 | owner_name: col_text(row, 2)?, | 166 | owner_name: col_text(row, 2)?, |
| 175 | title: col_text(row, 3)?, | 167 | title: col_text(row, 3)?, |
| 176 | description: col_text(row, 4)?, | 168 | description: col_text(row, 4)?, |
| 177 | - visibility: SnippetVisibility::parse(&visibility) | 169 | + visibility: parse_db(&visibility)?, |
| 178 | - .ok_or_else(|| Error::Database(format!("unknown snippet visibility {visibility}")))?, | | |
| 179 | created_at: col_text(row, 6)?, | 170 | created_at: col_text(row, 6)?, |
| 180 | updated_at: col_text(row, 7)?, | 171 | updated_at: col_text(row, 7)?, |
| 181 | files: Vec::new(), | 172 | files: Vec::new(), |
| @@ -188,8 +179,7 @@ fn summary_row(row: &turso::Row) -> Result<SnippetSummary> { |
| 188 | id: col_text(row, 0)?, | 179 | id: col_text(row, 0)?, |
| 189 | owner_name: col_text(row, 1)?, | 180 | owner_name: col_text(row, 1)?, |
| 190 | title: col_text(row, 2)?, | 181 | title: col_text(row, 2)?, |
| 191 | - visibility: SnippetVisibility::parse(&visibility) | 182 | + visibility: parse_db(&visibility)?, |
| 192 | - .ok_or_else(|| Error::Database(format!("unknown snippet visibility {visibility}")))?, | | |
| 193 | updated_at: col_text(row, 4)?, | 183 | updated_at: col_text(row, 4)?, |
| 194 | file_count: u64::try_from(col_int(row, 5)?).unwrap_or(0), | 184 | file_count: u64::try_from(col_int(row, 5)?).unwrap_or(0), |
| 195 | }) | 185 | }) |
| @@ -487,25 +477,9 @@ mod tests { |
| 487 | #[test] | 477 | #[test] |
| 488 | fn visibility_names_round_trip() { | 478 | fn visibility_names_round_trip() { |
| 489 | for v in SnippetVisibility::ALL { | 479 | for v in SnippetVisibility::ALL { |
| 490 | - assert_eq!( | 480 | + assert_eq!(v.as_str().parse::<SnippetVisibility>().ok(), Some(v)); |
| 491 | - SnippetVisibility::parse(v.as_str()), | | |
| 492 | - Some(v), | | |
| 493 | - "round trip {v:?}" | | |
| 494 | - ); | | |
| 495 | - } | | |
| 496 | - for (v, literal) in [ | | |
| 497 | - (SnippetVisibility::Public, "public"), | | |
| 498 | - (SnippetVisibility::Unlisted, "unlisted"), | | |
| 499 | - (SnippetVisibility::Private, "private"), | | |
| 500 | - ] { | | |
| 501 | - assert_eq!(v.as_str(), literal, "stored literal of {v:?}"); | | |
| 502 | - assert_eq!( | | |
| 503 | - SnippetVisibility::parse(literal), | | |
| 504 | - Some(v), | | |
| 505 | - "parse {literal}" | | |
| 506 | - ); | | |
| 507 | } | 481 | } |
| 508 | - assert_eq!(SnippetVisibility::parse("secret"), None); | 482 | + assert!("secret".parse::<SnippetVisibility>().is_err()); |
| 509 | } | 483 | } |
| 510 | | 484 | |
| 511 | #[tokio::test] | 485 | #[tokio::test] |
| @@ -2,6 +2,7 @@ use std::time::Duration; |
| 2 | | 2 | |
| 3 | use turso::{Connection, Row, Value}; | 3 | use turso::{Connection, Row, Value}; |
| 4 | | 4 | |
| | 5 | +use super::issues::parse_db; |
| 5 | use super::{ | 6 | use super::{ |
| 6 | Store, col_blob, col_bool, col_int, col_opt_int, col_opt_text, col_text, db_err, fetch_all, | 7 | Store, col_blob, col_bool, col_int, col_opt_int, col_opt_text, col_text, db_err, fetch_all, |
| 7 | fetch_opt, finish, new_id, opt_int_value, opt_text, | 8 | fetch_opt, finish, new_id, opt_int_value, opt_text, |
| @@ -26,10 +27,8 @@ fn map_webhook(row: &Row) -> Result<Webhook> { |
| 26 | .map_err(|e| Error::Database(format!("bad webhook events JSON: {e}")))?; | 27 | .map_err(|e| Error::Database(format!("bad webhook events JSON: {e}")))?; |
| 27 | let events = names | 28 | let events = names |
| 28 | .iter() | 29 | .iter() |
| 29 | - .map(|name| { | 30 | + .map(String::as_str) |
| 30 | - WebhookEvent::parse(name) | 31 | + .map(parse_db) |
| 31 | - .ok_or_else(|| Error::Database(format!("unknown webhook event {name:?}"))) | | |
| 32 | - }) | | |
| 33 | .collect::<Result<Vec<_>>>()?; | 32 | .collect::<Result<Vec<_>>>()?; |
| 34 | Ok(Webhook { | 33 | Ok(Webhook { |
| 35 | id: col_text(row, 0)?, | 34 | id: col_text(row, 0)?, |
| @@ -49,13 +48,11 @@ fn map_delivery(row: &Row) -> Result<Delivery> { |
| 49 | id: col_text(row, 0)?, | 48 | id: col_text(row, 0)?, |
| 50 | hook_id: col_text(row, 1)?, | 49 | hook_id: col_text(row, 1)?, |
| 51 | guid: col_text(row, 2)?, | 50 | guid: col_text(row, 2)?, |
| 52 | - event: WebhookEvent::parse(&event) | 51 | + event: parse_db(&event)?, |
| 53 | - .ok_or_else(|| Error::Database(format!("unknown webhook event {event:?}")))?, | | |
| 54 | action: col_text(row, 4)?, | 52 | action: col_text(row, 4)?, |
| 55 | request_headers: col_text(row, 5)?, | 53 | request_headers: col_text(row, 5)?, |
| 56 | request_body: col_text(row, 6)?, | 54 | request_body: col_text(row, 6)?, |
| 57 | - state: DeliveryState::parse(&state) | 55 | + state: parse_db(&state)?, |
| 58 | - .ok_or_else(|| Error::Database(format!("unknown delivery state {state:?}")))?, | | |
| 59 | attempt: u32::try_from(col_int(row, 8)?) | 56 | attempt: u32::try_from(col_int(row, 8)?) |
| 60 | .map_err(|_| Error::Database("negative delivery attempt count".into()))?, | 57 | .map_err(|_| Error::Database("negative delivery attempt count".into()))?, |
| 61 | next_attempt_at: col_opt_text(row, 9)?, | 58 | next_attempt_at: col_opt_text(row, 9)?, |
| @@ -297,11 +294,7 @@ impl Store { |
| 297 | let conn = self.read_conn().await; | 294 | let conn = self.read_conn().await; |
| 298 | fetch_all(&conn, &sql, (repo_id.to_string(),), |row| { | 295 | fetch_all(&conn, &sql, (repo_id.to_string(),), |row| { |
| 299 | let last = match col_opt_text(row, 7)? { | 296 | let last = match col_opt_text(row, 7)? { |
| 300 | - Some(s) => Some(( | 297 | + Some(s) => Some((parse_db(&s)?, col_text(row, 8)?)), |
| 301 | - DeliveryState::parse(&s) | | |
| 302 | - .ok_or_else(|| Error::Database(format!("unknown delivery state {s:?}")))?, | | |
| 303 | - col_text(row, 8)?, | | |
| 304 | - )), | | |
| 305 | None => None, | 298 | None => None, |
| 306 | }; | 299 | }; |
| 307 | Ok((map_webhook(row)?, last)) | 300 | Ok((map_webhook(row)?, last)) |
| @@ -1,5 +1,6 @@ |
| 1 | use std::time::Duration; | 1 | use std::time::Duration; |
| 2 | | 2 | |
| | 3 | +use jiff::{Timestamp, tz::TimeZone}; |
| 3 | use time::{ | 4 | use time::{ |
| 4 | OffsetDateTime, SignedDuration, | 5 | OffsetDateTime, SignedDuration, |
| 5 | format_description::{FormatItem, well_known::Rfc3339}, | 6 | format_description::{FormatItem, well_known::Rfc3339}, |
| @@ -17,14 +18,10 @@ pub fn now_stamp() -> String { |
| 17 | format_stamp(OffsetDateTime::now_utc()) | 18 | format_stamp(OffsetDateTime::now_utc()) |
| 18 | } | 19 | } |
| 19 | | 20 | |
| 20 | -pub fn unix_now() -> u64 { | 21 | +pub fn now_unix() -> i64 { |
| 21 | std::time::SystemTime::now() | 22 | std::time::SystemTime::now() |
| 22 | .duration_since(std::time::UNIX_EPOCH) | 23 | .duration_since(std::time::UNIX_EPOCH) |
| 23 | - .map_or(0, |d| d.as_secs()) | 24 | + .map_or(0, |d| i64::try_from(d.as_secs()).unwrap_or(0)) |
| 24 | -} | | |
| 25 | - | | |
| 26 | -pub fn now_unix() -> i64 { | | |
| 27 | - i64::try_from(unix_now()).unwrap_or(0) | | |
| 28 | } | 25 | } |
| 29 | | 26 | |
| 30 | pub fn stamp_after(after: Duration) -> String { | 27 | pub fn stamp_after(after: Duration) -> String { |
| @@ -49,6 +46,39 @@ pub fn stamp_to_unix(stamp: &str) -> Option<i64> { |
| 49 | .map(OffsetDateTime::unix_timestamp) | 46 | .map(OffsetDateTime::unix_timestamp) |
| 50 | } | 47 | } |
| 51 | | 48 | |
| | 49 | +pub fn iso_time(unix: i64) -> String { |
| | 50 | + Timestamp::from_second(unix) |
| | 51 | + .map(|t| { |
| | 52 | + t.to_zoned_datetime(TimeZone::UTC) |
| | 53 | + .strftime("%Y-%m-%dT%H:%M:%SZ") |
| | 54 | + .to_string() |
| | 55 | + }) |
| | 56 | + .unwrap_or_default() |
| | 57 | +} |
| | 58 | + |
| | 59 | +pub fn civil_from_days(days: i64) -> (i64, i64, i64) { |
| | 60 | + let z = days + 719_468; |
| | 61 | + let era = z.div_euclid(146_097); |
| | 62 | + let doe = z.rem_euclid(146_097); |
| | 63 | + let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365; |
| | 64 | + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); |
| | 65 | + let mp = (5 * doy + 2) / 153; |
| | 66 | + let d = doy - (153 * mp + 2) / 5 + 1; |
| | 67 | + let m = if mp < 10 { mp + 3 } else { mp - 9 }; |
| | 68 | + let y = yoe + era * 400 + i64::from(m <= 2); |
| | 69 | + (y, m, d) |
| | 70 | +} |
| | 71 | + |
| | 72 | +pub fn days_from_civil(year: i64, month: i64, day: i64) -> i64 { |
| | 73 | + let y = if month <= 2 { year - 1 } else { year }; |
| | 74 | + let era = y.div_euclid(400); |
| | 75 | + let yoe = y - era * 400; |
| | 76 | + let mp = (month + 9) % 12; |
| | 77 | + let doy = (153 * mp + 2) / 5 + day - 1; |
| | 78 | + let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; |
| | 79 | + era * 146_097 + doe - 719_468 |
| | 80 | +} |
| | 81 | + |
| 52 | const MIN_SLEEP: Duration = Duration::from_secs(1); | 82 | const MIN_SLEEP: Duration = Duration::from_secs(1); |
| 53 | | 83 | |
| 54 | pub fn sleep_until(next_due: Option<&str>, now: OffsetDateTime, backstop: Duration) -> Duration { | 84 | pub fn sleep_until(next_due: Option<&str>, now: OffsetDateTime, backstop: Duration) -> Duration { |
| @@ -34,8 +34,8 @@ pub fn hotp(secret: &[u8], counter: u64) -> u32 { |
| 34 | binary % 10u32.pow(DIGITS as u32) | 34 | binary % 10u32.pow(DIGITS as u32) |
| 35 | } | 35 | } |
| 36 | | 36 | |
| 37 | -pub fn step_for(unix_secs: u64) -> u64 { | 37 | +pub fn step_for(unix_secs: i64) -> u64 { |
| 38 | - unix_secs / STEP_SECS | 38 | + unix_secs.unsigned_abs() / STEP_SECS |
| 39 | } | 39 | } |
| 40 | | 40 | |
| 41 | pub fn code_at(secret: &[u8], step: u64) -> String { | 41 | pub fn code_at(secret: &[u8], step: u64) -> String { |
| @@ -23,26 +23,20 @@ impl WebhookEvent { |
| 23 | WebhookEvent::Ping, | 23 | WebhookEvent::Ping, |
| 24 | WebhookEvent::Release, | 24 | WebhookEvent::Release, |
| 25 | ]; | 25 | ]; |
| 26 | - | | |
| 27 | - pub fn as_str(self) -> &'static str { | | |
| 28 | - match self { | | |
| 29 | - WebhookEvent::Push => "push", | | |
| 30 | - WebhookEvent::PullRequest => "pull_request", | | |
| 31 | - WebhookEvent::Issues => "issues", | | |
| 32 | - WebhookEvent::IssueComment => "issue_comment", | | |
| 33 | - WebhookEvent::PullRequestReview => "pull_request_review", | | |
| 34 | - WebhookEvent::Create => "create", | | |
| 35 | - WebhookEvent::Delete => "delete", | | |
| 36 | - WebhookEvent::Ping => "ping", | | |
| 37 | - WebhookEvent::Release => "release", | | |
| 38 | - } | | |
| 39 | - } | | |
| 40 | - | | |
| 41 | - pub fn parse(s: &str) -> Option<WebhookEvent> { | | |
| 42 | - WebhookEvent::ALL.into_iter().find(|e| e.as_str() == s) | | |
| 43 | - } | | |
| 44 | } | 26 | } |
| 45 | | 27 | |
| | 28 | +string_enum!(WebhookEvent { |
| | 29 | + Push = "push", |
| | 30 | + PullRequest = "pull_request", |
| | 31 | + Issues = "issues", |
| | 32 | + IssueComment = "issue_comment", |
| | 33 | + PullRequestReview = "pull_request_review", |
| | 34 | + Create = "create", |
| | 35 | + Delete = "delete", |
| | 36 | + Ping = "ping", |
| | 37 | + Release = "release", |
| | 38 | +}); |
| | 39 | + |
| 46 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] | 40 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 47 | pub enum DeliveryState { | 41 | pub enum DeliveryState { |
| 48 | Pending, | 42 | Pending, |
| @@ -51,26 +45,12 @@ pub enum DeliveryState { |
| 51 | GaveUp, | 45 | GaveUp, |
| 52 | } | 46 | } |
| 53 | | 47 | |
| 54 | -impl DeliveryState { | 48 | +string_enum!(DeliveryState { |
| 55 | - pub fn as_str(self) -> &'static str { | 49 | + Pending = "pending", |
| 56 | - match self { | 50 | + Ok = "ok", |
| 57 | - DeliveryState::Pending => "pending", | 51 | + Failed = "failed", |
| 58 | - DeliveryState::Ok => "ok", | 52 | + GaveUp = "gave_up", |
| 59 | - DeliveryState::Failed => "failed", | 53 | +}); |
| 60 | - DeliveryState::GaveUp => "gave_up", | | |
| 61 | - } | | |
| 62 | - } | | |
| 63 | - | | |
| 64 | - pub fn parse(s: &str) -> Option<DeliveryState> { | | |
| 65 | - match s { | | |
| 66 | - "pending" => Some(DeliveryState::Pending), | | |
| 67 | - "ok" => Some(DeliveryState::Ok), | | |
| 68 | - "failed" => Some(DeliveryState::Failed), | | |
| 69 | - "gave_up" => Some(DeliveryState::GaveUp), | | |
| 70 | - _ => None, | | |
| 71 | - } | | |
| 72 | - } | | |
| 73 | -} | | |
| 74 | | 54 | |
| 75 | #[derive(Debug, Clone, PartialEq, Eq)] | 55 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 76 | pub struct Webhook { | 56 | pub struct Webhook { |
| @@ -1,4 +1,4 @@ |
| 1 | -use crate::common::{Http, Resp, cookie_named, input_value, launch_with, pick_ports}; | 1 | +use crate::common::{Http, Resp, cookie_named, input_value, launch_with, provision}; |
| 2 | use std::fs; | 2 | use std::fs; |
| 3 | use std::path::{Path, PathBuf}; | 3 | use std::path::{Path, PathBuf}; |
| 4 | use std::time::Duration; | 4 | use std::time::Duration; |
| @@ -120,7 +120,7 @@ async fn forgot(http: &Http, email: &str) -> Resp { |
| 120 | async fn reset_link_sets_a_new_password_once() { | 120 | async fn reset_link_sets_a_new_password_once() { |
| 121 | let root = tempfile::tempdir().expect("temp dir"); | 121 | let root = tempfile::tempdir().expect("temp dir"); |
| 122 | let dir = root.path().to_path_buf(); | 122 | let dir = root.path().to_path_buf(); |
| 123 | - let ports = pick_ports(); | 123 | + let (_, ports) = provision(&dir, LOG_TRANSPORT, &[]); |
| 124 | seed(&dir).await; | 124 | seed(&dir).await; |
| 125 | let (_server, ports) = launch_with(&dir, ports, LOG_TRANSPORT).await; | 125 | let (_server, ports) = launch_with(&dir, ports, LOG_TRANSPORT).await; |
| 126 | let http = Http::new(ports.http); | 126 | let http = Http::new(ports.http); |
| @@ -168,7 +168,7 @@ async fn reset_link_sets_a_new_password_once() { |
| 168 | async fn an_unverified_address_gets_no_reset_mail_and_the_same_answer() { | 168 | async fn an_unverified_address_gets_no_reset_mail_and_the_same_answer() { |
| 169 | let root = tempfile::tempdir().expect("temp dir"); | 169 | let root = tempfile::tempdir().expect("temp dir"); |
| 170 | let dir = root.path().to_path_buf(); | 170 | let dir = root.path().to_path_buf(); |
| 171 | - let ports = pick_ports(); | 171 | + let (_, ports) = provision(&dir, LOG_TRANSPORT, &[]); |
| 172 | seed(&dir).await; | 172 | seed(&dir).await; |
| 173 | let (_server, ports) = launch_with(&dir, ports, LOG_TRANSPORT).await; | 173 | let (_server, ports) = launch_with(&dir, ports, LOG_TRANSPORT).await; |
| 174 | let http = Http::new(ports.http); | 174 | let http = Http::new(ports.http); |
| @@ -1,15 +1,12 @@ |
| 1 | use crate::common::{ | 1 | use crate::common::{ |
| 2 | - Http, Resp, Server, input_value, launch_with, login, pick_ports, run_admin, tool_on_path, | 2 | + BOB_CMD, Http, PW, Resp, Server, TAHINLI_CMD, boot_forge, commit_file, create_token, csrf_for, |
| 3 | - write_config_with, | 3 | + git_text, login, temp_dir, tool_on_path, |
| 4 | }; | 4 | }; |
| 5 | use std::fs; | 5 | use std::fs; |
| 6 | use std::io::{Cursor, Write}; | 6 | use std::io::{Cursor, Write}; |
| 7 | -use std::path::{Path, PathBuf}; | 7 | +use std::path::PathBuf; |
| 8 | -use std::process::{Command, Output}; | | |
| 9 | use std::time::{Duration, Instant}; | 8 | use std::time::{Duration, Instant}; |
| 10 | | 9 | |
| 11 | -const TAHINLI_PW: &str = "tahinli-password-123"; | | |
| 12 | -const BOB_PW: &str = "bob-password-123"; | | |
| 13 | const ADVISORIES_TOML: &str = "\n[advisories]\nenabled = true\necosystems = [\"crates.io\"]\n"; | 10 | const ADVISORIES_TOML: &str = "\n[advisories]\nenabled = true\necosystems = [\"crates.io\"]\n"; |
| 14 | const SCAN_TIMEOUT: Duration = Duration::from_secs(30); | 11 | const SCAN_TIMEOUT: Duration = Duration::from_secs(30); |
| 15 | | 12 | |
| @@ -27,36 +24,6 @@ const OSV_RECORD: &str = r#"{ |
| 27 | const LOCK_OLD: &str = "version = 4\n\n[[package]]\nname = \"demo\"\nversion = \"1.0.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\n"; | 24 | const LOCK_OLD: &str = "version = 4\n\n[[package]]\nname = \"demo\"\nversion = \"1.0.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\n"; |
| 28 | const LOCK_FIXED: &str = "version = 4\n\n[[package]]\nname = \"demo\"\nversion = \"2.0.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\n"; | 25 | const LOCK_FIXED: &str = "version = 4\n\n[[package]]\nname = \"demo\"\nversion = \"2.0.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\n"; |
| 29 | | 26 | |
| 30 | -fn git(cwd: &Path, args: &[&str]) -> String { | | |
| 31 | - let out: Output = Command::new("git") | | |
| 32 | - .current_dir(cwd) | | |
| 33 | - .args(["-c", "credential.helper="]) | | |
| 34 | - .args(args) | | |
| 35 | - .env("GIT_TERMINAL_PROMPT", "0") | | |
| 36 | - .env("GIT_AUTHOR_NAME", "tahinli") | | |
| 37 | - .env("GIT_AUTHOR_EMAIL", "tahinli@example.test") | | |
| 38 | - .env("GIT_COMMITTER_NAME", "tahinli") | | |
| 39 | - .env("GIT_COMMITTER_EMAIL", "tahinli@example.test") | | |
| 40 | - .output() | | |
| 41 | - .expect("run git"); | | |
| 42 | - assert!( | | |
| 43 | - out.status.success(), | | |
| 44 | - "git {args:?} failed:\n{}", | | |
| 45 | - String::from_utf8_lossy(&out.stderr) | | |
| 46 | - ); | | |
| 47 | - String::from_utf8_lossy(&out.stdout).trim().to_owned() | | |
| 48 | -} | | |
| 49 | - | | |
| 50 | -fn commit_lock(repo: &Path, contents: &str, message: &str) -> String { | | |
| 51 | - fs::write(repo.join("Cargo.lock"), contents).expect("write Cargo.lock"); | | |
| 52 | - git(repo, &["add", "Cargo.lock"]); | | |
| 53 | - git( | | |
| 54 | - repo, | | |
| 55 | - &["-c", "commit.gpgsign=false", "commit", "-q", "-m", message], | | |
| 56 | - ); | | |
| 57 | - git(repo, &["rev-parse", "HEAD"]) | | |
| 58 | -} | | |
| 59 | - | | |
| 60 | fn dump_zip() -> Vec<u8> { | 27 | fn dump_zip() -> Vec<u8> { |
| 61 | let mut buf = Cursor::new(Vec::new()); | 28 | let mut buf = Cursor::new(Vec::new()); |
| 62 | { | 29 | { |
| @@ -82,20 +49,13 @@ async fn boot() -> Booted { |
| 82 | if !tool_on_path("git") { | 49 | if !tool_on_path("git") { |
| 83 | panic!("`git` was not found on PATH"); | 50 | panic!("`git` was not found on PATH"); |
| 84 | } | 51 | } |
| 85 | - let root = tempfile::Builder::new() | 52 | + let root = temp_dir("adv2e"); |
| 86 | - .prefix("adv2e") | | |
| 87 | - .tempdir_in("/tmp") | | |
| 88 | - .expect("temp dir"); | | |
| 89 | let dir = root.path().to_path_buf(); | 53 | let dir = root.path().to_path_buf(); |
| 90 | let dump_dir = dir.join("advisories").join("crates.io"); | 54 | let dump_dir = dir.join("advisories").join("crates.io"); |
| 91 | fs::create_dir_all(&dump_dir).expect("dump dir"); | 55 | fs::create_dir_all(&dump_dir).expect("dump dir"); |
| 92 | fs::write(dump_dir.join("all.zip"), dump_zip()).expect("write dump"); | 56 | fs::write(dump_dir.join("all.zip"), dump_zip()).expect("write dump"); |
| 93 | | 57 | |
| 94 | - let ports = pick_ports(); | 58 | + let (server, ports) = boot_forge(&dir, ADVISORIES_TOML, &[TAHINLI_CMD, BOB_CMD]).await; |
| 95 | - let config = write_config_with(&dir, ports, ADVISORIES_TOML); | | |
| 96 | - run_admin(&config, "tahinli", &["--admin"], TAHINLI_PW); | | |
| 97 | - run_admin(&config, "bob", &[], BOB_PW); | | |
| 98 | - let (server, ports) = launch_with(&dir, ports, ADVISORIES_TOML).await; | | |
| 99 | Booted { | 59 | Booted { |
| 100 | _server: server, | 60 | _server: server, |
| 101 | _root: root, | 61 | _root: root, |
| @@ -105,37 +65,8 @@ async fn boot() -> Booted { |
| 105 | } | 65 | } |
| 106 | } | 66 | } |
| 107 | | 67 | |
| 108 | -async fn create_token(http: &Http, session: &str) -> String { | | |
| 109 | - let page = http.get_cookie("/settings/keys", session).await; | | |
| 110 | - assert_eq!(page.status, 200, "GET /settings/keys"); | | |
| 111 | - let csrf = input_value(&page.body, "csrf"); | | |
| 112 | - let res = http | | |
| 113 | - .post_form( | | |
| 114 | - "/settings/tokens", | | |
| 115 | - &[ | | |
| 116 | - ("csrf", &csrf), | | |
| 117 | - ("name", "advisory-token"), | | |
| 118 | - ("expires", "30"), | | |
| 119 | - ], | | |
| 120 | - Some(session), | | |
| 121 | - ) | | |
| 122 | - .await; | | |
| 123 | - assert_eq!(res.status, 200, "create token: {}", res.body); | | |
| 124 | - let doc = scraper::Html::parse_document(&res.body); | | |
| 125 | - let selector = scraper::Selector::parse("pre.code code").expect("selector"); | | |
| 126 | - doc.select(&selector) | | |
| 127 | - .next() | | |
| 128 | - .expect("token shown after creation") | | |
| 129 | - .text() | | |
| 130 | - .collect::<String>() | | |
| 131 | - .trim() | | |
| 132 | - .to_owned() | | |
| 133 | -} | | |
| 134 | - | | |
| 135 | async fn new_repo(http: &Http, session: &str, name: &str) { | 68 | async fn new_repo(http: &Http, session: &str, name: &str) { |
| 136 | - let page = http.get_cookie("/new", session).await; | 69 | + let csrf = csrf_for(http, "/new", session).await; |
| 137 | - assert_eq!(page.status, 200, "GET /new"); | | |
| 138 | - let csrf = input_value(&page.body, "csrf"); | | |
| 139 | let res = http | 70 | let res = http |
| 140 | .post_form( | 71 | .post_form( |
| 141 | "/new", | 72 | "/new", |
| @@ -173,9 +104,7 @@ async fn wait_for_text(http: &Http, session: &str, text: &str) -> String { |
| 173 | } | 104 | } |
| 174 | | 105 | |
| 175 | async fn post_alert_action(http: &Http, session: &str, action: &str) -> Resp { | 106 | async fn post_alert_action(http: &Http, session: &str, action: &str) -> Resp { |
| 176 | - let page = security_page(http, session).await; | 107 | + let csrf = csrf_for(http, "/tahinli/app/security", session).await; |
| 177 | - assert_eq!(page.status, 200, "GET security page"); | | |
| 178 | - let csrf = input_value(&page.body, "csrf"); | | |
| 179 | http.post_form( | 108 | http.post_form( |
| 180 | &format!("/tahinli/app/security/{action}"), | 109 | &format!("/tahinli/app/security/{action}"), |
| 181 | &[ | 110 | &[ |
| @@ -193,8 +122,8 @@ async fn post_alert_action(http: &Http, session: &str, action: &str) -> Resp { |
| 193 | #[tokio::test] | 122 | #[tokio::test] |
| 194 | async fn advisory_alert_opens_on_push_and_follows_dismiss_reopen_and_fix() { | 123 | async fn advisory_alert_opens_on_push_and_follows_dismiss_reopen_and_fix() { |
| 195 | let b = boot().await; | 124 | let b = boot().await; |
| 196 | - let tahinli = login(&b.http, "tahinli", TAHINLI_PW).await; | 125 | + let tahinli = login(&b.http, "tahinli", PW).await; |
| 197 | - let token = create_token(&b.http, &tahinli).await; | 126 | + let token = create_token(&b.http, &tahinli, "advisory-token").await; |
| 198 | new_repo(&b.http, &tahinli, "app").await; | 127 | new_repo(&b.http, &tahinli, "app").await; |
| 199 | | 128 | |
| 200 | let work = b.dir.join("app-work"); | 129 | let work = b.dir.join("app-work"); |
| @@ -202,12 +131,12 @@ async fn advisory_alert_opens_on_push_and_follows_dismiss_reopen_and_fix() { |
| 202 | "http://tahinli:{token}@127.0.0.1:{}/tahinli/app.git", | 131 | "http://tahinli:{token}@127.0.0.1:{}/tahinli/app.git", |
| 203 | b.port | 132 | b.port |
| 204 | ); | 133 | ); |
| 205 | - git( | 134 | + git_text( |
| 206 | &b.dir, | 135 | &b.dir, |
| 207 | &["clone", "-q", &remote, work.to_str().expect("utf-8 path")], | 136 | &["clone", "-q", &remote, work.to_str().expect("utf-8 path")], |
| 208 | ); | 137 | ); |
| 209 | - commit_lock(&work, LOCK_OLD, "lock demo 1.0.0"); | 138 | + commit_file(&work, "Cargo.lock", LOCK_OLD, "lock demo 1.0.0"); |
| 210 | - git(&work, &["push", "-q", "origin", "HEAD:refs/heads/main"]); | 139 | + git_text(&work, &["push", "-q", "origin", "HEAD:refs/heads/main"]); |
| 211 | | 140 | |
| 212 | let page = wait_for_text(&b.http, &tahinli, "RUSTSEC-TEST-0001").await; | 141 | let page = wait_for_text(&b.http, &tahinli, "RUSTSEC-TEST-0001").await; |
| 213 | assert!(page.contains(">Open</span>"), "the alert is open"); | 142 | assert!(page.contains(">Open</span>"), "the alert is open"); |
| @@ -222,11 +151,11 @@ async fn advisory_alert_opens_on_push_and_follows_dismiss_reopen_and_fix() { |
| 222 | assert_eq!(reopened.status, 303, "reopen: {}", reopened.body); | 151 | assert_eq!(reopened.status, 303, "reopen: {}", reopened.body); |
| 223 | wait_for_text(&b.http, &tahinli, ">Open</span>").await; | 152 | wait_for_text(&b.http, &tahinli, ">Open</span>").await; |
| 224 | | 153 | |
| 225 | - let bob = login(&b.http, "bob", BOB_PW).await; | 154 | + let bob = login(&b.http, "bob", PW).await; |
| 226 | let refused = security_page(&b.http, &bob).await; | 155 | let refused = security_page(&b.http, &bob).await; |
| 227 | assert_eq!(refused.status, 404, "a reader without Write gets 404"); | 156 | assert_eq!(refused.status, 404, "a reader without Write gets 404"); |
| 228 | | 157 | |
| 229 | - commit_lock(&work, LOCK_FIXED, "lock demo 2.0.0"); | 158 | + commit_file(&work, "Cargo.lock", LOCK_FIXED, "lock demo 2.0.0"); |
| 230 | - git(&work, &["push", "-q", "origin", "HEAD:refs/heads/main"]); | 159 | + git_text(&work, &["push", "-q", "origin", "HEAD:refs/heads/main"]); |
| 231 | wait_for_text(&b.http, &tahinli, ">Fixed</span>").await; | 160 | wait_for_text(&b.http, &tahinli, ">Fixed</span>").await; |
| 232 | } | 161 | } |
| @@ -1,19 +1,12 @@ |
| 1 | use crate::common::{ | 1 | use crate::common::{ |
| 2 | - Http, Ports, Server, describe, input_value, launch, login, pick_ports, relaunch, run_admin, | 2 | + Http, PW, Ports, Server, TAHINLI_CMD, boot_forge, commit_file, create_repo, create_token, |
| 3 | - tool_on_path, write_config, | 3 | + describe, git, login, ok, path_str, relaunch, temp_dir, tool_on_path, |
| 4 | }; | 4 | }; |
| 5 | -use std::fs; | | |
| 6 | use std::path::{Path, PathBuf}; | 5 | use std::path::{Path, PathBuf}; |
| 7 | -use std::process::{Command, Output}; | 6 | +use std::process::Output; |
| 8 | | 7 | |
| 9 | use forge_core::Store; | 8 | use forge_core::Store; |
| 10 | | 9 | |
| 11 | -const TAHINLI_PW: &str = "tahinli-password-123"; | | |
| 12 | - | | |
| 13 | -fn ok(out: &Output, what: &str) { | | |
| 14 | - assert!(out.status.success(), "{what} failed:\n{}", describe(out)); | | |
| 15 | -} | | |
| 16 | - | | |
| 17 | fn rejected(out: &Output, what: &str) -> String { | 10 | fn rejected(out: &Output, what: &str) -> String { |
| 18 | assert!( | 11 | assert!( |
| 19 | !out.status.success(), | 12 | !out.status.success(), |
| @@ -23,51 +16,6 @@ fn rejected(out: &Output, what: &str) -> String { |
| 23 | describe(out) | 16 | describe(out) |
| 24 | } | 17 | } |
| 25 | | 18 | |
| 26 | -fn git(cwd: &Path, args: &[&str]) -> Output { | | |
| 27 | - Command::new("git") | | |
| 28 | - .current_dir(cwd) | | |
| 29 | - .args(["-c", "credential.helper="]) | | |
| 30 | - .args(args) | | |
| 31 | - .env("GIT_TERMINAL_PROMPT", "0") | | |
| 32 | - .output() | | |
| 33 | - .expect("run git") | | |
| 34 | -} | | |
| 35 | - | | |
| 36 | -fn path_str(path: &Path) -> &str { | | |
| 37 | - path.to_str().expect("utf-8 path") | | |
| 38 | -} | | |
| 39 | - | | |
| 40 | -fn set_identity(repo: &Path) { | | |
| 41 | - ok( | | |
| 42 | - &git(repo, &["config", "user.name", "tahinli"]), | | |
| 43 | - "set user.name", | | |
| 44 | - ); | | |
| 45 | - ok( | | |
| 46 | - &git(repo, &["config", "user.email", "tahinli@example.com"]), | | |
| 47 | - "set user.email", | | |
| 48 | - ); | | |
| 49 | -} | | |
| 50 | - | | |
| 51 | -fn commit_file(repo: &Path, name: &str, content: &str, message: &str) -> String { | | |
| 52 | - fs::write(repo.join(name), content).expect("write file"); | | |
| 53 | - set_identity(repo); | | |
| 54 | - ok(&git(repo, &["add", name]), "git add"); | | |
| 55 | - ok( | | |
| 56 | - &git( | | |
| 57 | - repo, | | |
| 58 | - &["-c", "commit.gpgsign=false", "commit", "-q", "-m", message], | | |
| 59 | - ), | | |
| 60 | - "git commit", | | |
| 61 | - ); | | |
| 62 | - head_sha(repo) | | |
| 63 | -} | | |
| 64 | - | | |
| 65 | -fn head_sha(repo: &Path) -> String { | | |
| 66 | - let out = git(repo, &["rev-parse", "HEAD"]); | | |
| 67 | - ok(&out, "rev-parse HEAD"); | | |
| 68 | - String::from_utf8_lossy(&out.stdout).trim().to_owned() | | |
| 69 | -} | | |
| 70 | - | | |
| 71 | fn remote_sha(repo: &Path, reference: &str) -> String { | 19 | fn remote_sha(repo: &Path, reference: &str) -> String { |
| 72 | let out = git(repo, &["ls-remote", "origin", reference]); | 20 | let out = git(repo, &["ls-remote", "origin", reference]); |
| 73 | ok(&out, "ls-remote"); | 21 | ok(&out, "ls-remote"); |
| @@ -78,55 +26,6 @@ fn remote_sha(repo: &Path, reference: &str) -> String { |
| 78 | .to_owned() | 26 | .to_owned() |
| 79 | } | 27 | } |
| 80 | | 28 | |
| 81 | -async fn create_token(http: &Http, session: &str, name: &str) -> String { | | |
| 82 | - let page = http.get_cookie("/settings/keys", session).await; | | |
| 83 | - assert_eq!(page.status, 200, "GET /settings/keys"); | | |
| 84 | - let csrf = input_value(&page.body, "csrf"); | | |
| 85 | - let res = http | | |
| 86 | - .post_form( | | |
| 87 | - "/settings/tokens", | | |
| 88 | - &[("csrf", &csrf), ("name", name), ("expires", "30")], | | |
| 89 | - Some(session), | | |
| 90 | - ) | | |
| 91 | - .await; | | |
| 92 | - assert_eq!(res.status, 200, "create token: {}", res.body); | | |
| 93 | - let doc = scraper::Html::parse_document(&res.body); | | |
| 94 | - let selector = scraper::Selector::parse("pre.code code").expect("selector"); | | |
| 95 | - let token: String = doc | | |
| 96 | - .select(&selector) | | |
| 97 | - .next() | | |
| 98 | - .expect("token shown after creation") | | |
| 99 | - .text() | | |
| 100 | - .collect(); | | |
| 101 | - let token = token.trim().to_owned(); | | |
| 102 | - assert!(token.starts_with("forge_"), "unexpected token shape"); | | |
| 103 | - token | | |
| 104 | -} | | |
| 105 | - | | |
| 106 | -async fn create_repo(http: &Http, session: &str, name: &str) { | | |
| 107 | - let page = http.get_cookie("/new", session).await; | | |
| 108 | - assert_eq!(page.status, 200, "GET /new"); | | |
| 109 | - let csrf = input_value(&page.body, "csrf"); | | |
| 110 | - let res = http | | |
| 111 | - .post_form( | | |
| 112 | - "/new", | | |
| 113 | - &[ | | |
| 114 | - ("csrf", &csrf), | | |
| 115 | - ("name", name), | | |
| 116 | - ("description", ""), | | |
| 117 | - ("visibility", "private"), | | |
| 118 | - ("default_branch", "main"), | | |
| 119 | - ], | | |
| 120 | - Some(session), | | |
| 121 | - ) | | |
| 122 | - .await; | | |
| 123 | - assert_eq!(res.status, 303, "create repo {name}: {}", res.body); | | |
| 124 | - assert_eq!( | | |
| 125 | - res.location().as_deref(), | | |
| 126 | - Some(format!("/tahinli/{name}").as_str()) | | |
| 127 | - ); | | |
| 128 | -} | | |
| 129 | - | | |
| 130 | struct Ctx { | 29 | struct Ctx { |
| 131 | dir: PathBuf, | 30 | dir: PathBuf, |
| 132 | config: PathBuf, | 31 | config: PathBuf, |
| @@ -171,26 +70,19 @@ async fn branch_protection_end_to_end() { |
| 171 | return; | 70 | return; |
| 172 | } | 71 | } |
| 173 | | 72 | |
| 174 | - let root = tempfile::Builder::new() | 73 | + let root = temp_dir("fbp"); |
| 175 | - .prefix("fbp") | | |
| 176 | - .tempdir_in("/tmp") | | |
| 177 | - .expect("temp dir"); | | |
| 178 | let dir = root.path().to_path_buf(); | 74 | let dir = root.path().to_path_buf(); |
| 179 | - let ports = pick_ports(); | 75 | + let (server, ports) = boot_forge(&dir, "", &[TAHINLI_CMD]).await; |
| 180 | - let config = write_config(&dir, ports); | | |
| 181 | - run_admin(&config, "tahinli", &["--admin"], TAHINLI_PW); | | |
| 182 | - | | |
| 183 | - let (server, ports) = launch(&dir, ports).await; | | |
| 184 | let ctx = Ctx { | 76 | let ctx = Ctx { |
| 185 | log: dir.join("serve.log"), | 77 | log: dir.join("serve.log"), |
| 186 | http: Http::new(ports.http), | 78 | http: Http::new(ports.http), |
| 187 | ports, | 79 | ports, |
| 188 | - config, | 80 | + config: dir.join("forge.toml"), |
| 189 | dir, | 81 | dir, |
| 190 | }; | 82 | }; |
| 191 | - let tahinli = login(&ctx.http, "tahinli", TAHINLI_PW).await; | 83 | + let tahinli = login(&ctx.http, "tahinli", PW).await; |
| 192 | let token = create_token(&ctx.http, &tahinli, "bp-token").await; | 84 | let token = create_token(&ctx.http, &tahinli, "bp-token").await; |
| 193 | - create_repo(&ctx.http, &tahinli, "bp").await; | 85 | + create_repo(&ctx.http, &tahinli, "bp", "private").await; |
| 194 | | 86 | |
| 195 | drop(server); | 87 | drop(server); |
| 196 | let repo_id = { | 88 | let repo_id = { |
| @@ -1,7 +1,9 @@ |
| 1 | -use crate::common::{boot_admin, describe, input_value, tool_on_path}; | 1 | +use crate::common::{ |
| | 2 | + PW, TAHINLI_CMD, attr_values, boot_forge, element_texts, git, head_sha, input_value, ok, |
| | 3 | + open_stream, path_str, set_identity, temp_dir, tool_on_path, |
| | 4 | +}; |
| 2 | use std::fs; | 5 | use std::fs; |
| 3 | use std::path::Path; | 6 | use std::path::Path; |
| 4 | -use std::process::{Command, Output}; | | |
| 5 | use std::time::Duration; | 7 | use std::time::Duration; |
| 6 | | 8 | |
| 7 | use reqwest::header::{ | 9 | use reqwest::header::{ |
| @@ -9,7 +11,6 @@ use reqwest::header::{ |
| 9 | LOCATION, SET_COOKIE, X_CONTENT_TYPE_OPTIONS, | 11 | LOCATION, SET_COOKIE, X_CONTENT_TYPE_OPTIONS, |
| 10 | }; | 12 | }; |
| 11 | | 13 | |
| 12 | -const TAHINLI_PW: &str = "tahinli-password-123"; | | |
| 13 | const PNG: &[u8] = b"\x89PNG\r\n\x1a\n\x00\x00\x00\x00IEND\xaeB`\x82"; | 14 | const PNG: &[u8] = b"\x89PNG\r\n\x1a\n\x00\x00\x00\x00IEND\xaeB`\x82"; |
| 14 | | 15 | |
| 15 | struct Resp { | 16 | struct Resp { |
| @@ -70,6 +71,10 @@ impl Http { |
| 70 | .await | 71 | .await |
| 71 | } | 72 | } |
| 72 | | 73 | |
| | 74 | + async fn stream(&self, path: &str, cookie: Option<&str>) -> reqwest::Response { |
| | 75 | + open_stream(&self.client, &format!("{}{path}", self.base), cookie).await |
| | 76 | + } |
| | 77 | + |
| 73 | async fn send(&self, req: reqwest::RequestBuilder, cookie: Option<&str>) -> Resp { | 78 | async fn send(&self, req: reqwest::RequestBuilder, cookie: Option<&str>) -> Resp { |
| 74 | let req = match cookie { | 79 | let req = match cookie { |
| 75 | Some(cookie) => req.header(COOKIE, cookie), | 80 | Some(cookie) => req.header(COOKIE, cookie), |
| @@ -95,22 +100,6 @@ fn cookie_named(resp: &Resp, suffix: &str) -> Option<String> { |
| 95 | }) | 100 | }) |
| 96 | } | 101 | } |
| 97 | | 102 | |
| 98 | -fn attr_values(body: &str, selector: &str, attr: &str) -> Vec<String> { | | |
| 99 | - let doc = scraper::Html::parse_document(body); | | |
| 100 | - let selector = scraper::Selector::parse(selector).expect("selector"); | | |
| 101 | - doc.select(&selector) | | |
| 102 | - .filter_map(|el| el.value().attr(attr).map(str::to_owned)) | | |
| 103 | - .collect() | | |
| 104 | -} | | |
| 105 | - | | |
| 106 | -fn element_texts(body: &str, selector: &str) -> Vec<String> { | | |
| 107 | - let doc = scraper::Html::parse_document(body); | | |
| 108 | - let selector = scraper::Selector::parse(selector).expect("selector"); | | |
| 109 | - doc.select(&selector) | | |
| 110 | - .map(|el| el.text().collect::<String>()) | | |
| 111 | - .collect() | | |
| 112 | -} | | |
| 113 | - | | |
| 114 | fn assert_latest_bar(body: &str, what: &str, subject: &str, oid: &str, count: &str) { | 103 | fn assert_latest_bar(body: &str, what: &str, subject: &str, oid: &str, count: &str) { |
| 115 | assert_eq!( | 104 | assert_eq!( |
| 116 | element_texts(body, ".head-sub").len(), | 105 | element_texts(body, ".head-sub").len(), |
| @@ -132,35 +121,6 @@ fn assert_latest_bar(body: &str, what: &str, subject: &str, oid: &str, count: &s |
| 132 | ); | 121 | ); |
| 133 | } | 122 | } |
| 134 | | 123 | |
| 135 | -fn ok(out: &Output, what: &str) { | | |
| 136 | - assert!(out.status.success(), "{what} failed:\n{}", describe(out)); | | |
| 137 | -} | | |
| 138 | - | | |
| 139 | -fn git(cwd: &Path, args: &[&str]) -> Output { | | |
| 140 | - Command::new("git") | | |
| 141 | - .current_dir(cwd) | | |
| 142 | - .args(["-c", "credential.helper="]) | | |
| 143 | - .args(args) | | |
| 144 | - .env("GIT_TERMINAL_PROMPT", "0") | | |
| 145 | - .output() | | |
| 146 | - .expect("run git") | | |
| 147 | -} | | |
| 148 | - | | |
| 149 | -fn path_str(path: &Path) -> &str { | | |
| 150 | - path.to_str().expect("utf-8 path") | | |
| 151 | -} | | |
| 152 | - | | |
| 153 | -fn set_identity(repo: &Path) { | | |
| 154 | - ok( | | |
| 155 | - &git(repo, &["config", "user.name", "tahinli"]), | | |
| 156 | - "set user.name", | | |
| 157 | - ); | | |
| 158 | - ok( | | |
| 159 | - &git(repo, &["config", "user.email", "tahinli@example.com"]), | | |
| 160 | - "set user.email", | | |
| 161 | - ); | | |
| 162 | -} | | |
| 163 | - | | |
| 164 | fn write_fixtures(work: &Path) { | 124 | fn write_fixtures(work: &Path) { |
| 165 | fs::create_dir_all(work.join("src")).expect("create src"); | 125 | fs::create_dir_all(work.join("src")).expect("create src"); |
| 166 | fs::write( | 126 | fs::write( |
| @@ -190,12 +150,6 @@ fn commit_all(repo: &Path, message: &str) { |
| 190 | ); | 150 | ); |
| 191 | } | 151 | } |
| 192 | | 152 | |
| 193 | -fn head_sha(repo: &Path) -> String { | | |
| 194 | - let out = git(repo, &["rev-parse", "HEAD"]); | | |
| 195 | - ok(&out, "rev-parse HEAD"); | | |
| 196 | - String::from_utf8_lossy(&out.stdout).trim().to_owned() | | |
| 197 | -} | | |
| 198 | - | | |
| 199 | fn push_fixtures(dir: &Path, url: &str, work: &Path) -> String { | 153 | fn push_fixtures(dir: &Path, url: &str, work: &Path) -> String { |
| 200 | ok(&git(dir, &["clone", url, path_str(work)]), "https clone"); | 154 | ok(&git(dir, &["clone", url, path_str(work)]), "https clone"); |
| 201 | write_fixtures(work); | 155 | write_fixtures(work); |
| @@ -297,13 +251,14 @@ async fn browse_end_to_end() { |
| 297 | return; | 251 | return; |
| 298 | } | 252 | } |
| 299 | | 253 | |
| 300 | - let (root, _server, ports) = boot_admin("fbrw", TAHINLI_PW).await; | 254 | + let root = temp_dir("fbrw"); |
| | 255 | + let (_server, ports) = boot_forge(root.path(), "", &[TAHINLI_CMD]).await; |
| 301 | let dir = root.path().to_path_buf(); | 256 | let dir = root.path().to_path_buf(); |
| 302 | let http = Http::new(ports.http); | 257 | let http = Http::new(ports.http); |
| 303 | let raw = Http::new(ports.content); | 258 | let raw = Http::new(ports.content); |
| 304 | let raw_base = raw.base.clone(); | 259 | let raw_base = raw.base.clone(); |
| 305 | | 260 | |
| 306 | - let tahinli = login(&http, "tahinli", TAHINLI_PW).await; | 261 | + let tahinli = login(&http, "tahinli", PW).await; |
| 307 | let token = create_token(&http, &tahinli, "browse-token").await; | 262 | let token = create_token(&http, &tahinli, "browse-token").await; |
| 308 | create_repo(&http, &tahinli, "pub", "public").await; | 263 | create_repo(&http, &tahinli, "pub", "public").await; |
| 309 | create_repo(&http, &tahinli, "priv", "private").await; | 264 | create_repo(&http, &tahinli, "priv", "private").await; |
| @@ -556,19 +511,6 @@ async fn browse_end_to_end() { |
| 556 | assert_no_cookie(&login_page, "raw /login"); | 511 | assert_no_cookie(&login_page, "raw /login"); |
| 557 | } | 512 | } |
| 558 | | 513 | |
| 559 | -async fn open_stream(http: &Http, path: &str, cookie: Option<&str>) -> reqwest::Response { | | |
| 560 | - let mut req = http.client.get(format!("{}{path}", http.base)); | | |
| 561 | - if let Some(cookie) = cookie { | | |
| 562 | - req = req.header(COOKIE, cookie); | | |
| 563 | - } | | |
| 564 | - let mut res = req.send().await.expect("stream request"); | | |
| 565 | - if res.status().is_success() { | | |
| 566 | - let retry = next_chunk(&mut res).await.expect("the retry field"); | | |
| 567 | - assert!(retry.contains("retry: 1000"), "{retry}"); | | |
| 568 | - } | | |
| 569 | - res | | |
| 570 | -} | | |
| 571 | - | | |
| 572 | async fn next_chunk(res: &mut reqwest::Response) -> Option<String> { | 514 | async fn next_chunk(res: &mut reqwest::Response) -> Option<String> { |
| 573 | let chunk = tokio::time::timeout(Duration::from_secs(2), res.chunk()) | 515 | let chunk = tokio::time::timeout(Duration::from_secs(2), res.chunk()) |
| 574 | .await | 516 | .await |
| @@ -584,11 +526,12 @@ async fn code_view_stream_follows_pushes() { |
| 584 | return; | 526 | return; |
| 585 | } | 527 | } |
| 586 | | 528 | |
| 587 | - let (root, _server, ports) = boot_admin("fliv", TAHINLI_PW).await; | 529 | + let root = temp_dir("fliv"); |
| | 530 | + let (_server, ports) = boot_forge(root.path(), "", &[TAHINLI_CMD]).await; |
| 588 | let dir = root.path().to_path_buf(); | 531 | let dir = root.path().to_path_buf(); |
| 589 | let http = Http::new(ports.http); | 532 | let http = Http::new(ports.http); |
| 590 | | 533 | |
| 591 | - let tahinli = login(&http, "tahinli", TAHINLI_PW).await; | 534 | + let tahinli = login(&http, "tahinli", PW).await; |
| 592 | let token = create_token(&http, &tahinli, "live-token").await; | 535 | let token = create_token(&http, &tahinli, "live-token").await; |
| 593 | create_repo(&http, &tahinli, "pub", "public").await; | 536 | create_repo(&http, &tahinli, "pub", "public").await; |
| 594 | create_repo(&http, &tahinli, "priv", "private").await; | 537 | create_repo(&http, &tahinli, "priv", "private").await; |
| @@ -627,7 +570,7 @@ async fn code_view_stream_follows_pushes() { |
| 627 | "a commit page does not follow a branch" | 570 | "a commit page does not follow a branch" |
| 628 | ); | 571 | ); |
| 629 | | 572 | |
| 630 | - let mut stream = open_stream(&http, "/tahinli/pub/events?ref_name=main", None).await; | 573 | + let mut stream = http.stream("/tahinli/pub/events?ref_name=main", None).await; |
| 631 | assert_eq!(stream.status().as_u16(), 200); | 574 | assert_eq!(stream.status().as_u16(), 200); |
| 632 | assert_eq!( | 575 | assert_eq!( |
| 633 | stream.headers().get(CONTENT_TYPE).unwrap(), | 576 | stream.headers().get(CONTENT_TYPE).unwrap(), |
| @@ -675,13 +618,13 @@ async fn code_view_stream_follows_pushes() { |
| 675 | assert!(deleted.contains("event: changed"), "{deleted}"); | 618 | assert!(deleted.contains("event: changed"), "{deleted}"); |
| 676 | | 619 | |
| 677 | let private = "/tahinli/priv/events?ref_name=main"; | 620 | let private = "/tahinli/priv/events?ref_name=main"; |
| 678 | - let anonymous = open_stream(&http, private, None).await; | 621 | + let anonymous = http.stream(private, None).await; |
| 679 | assert_eq!( | 622 | assert_eq!( |
| 680 | anonymous.status().as_u16(), | 623 | anonymous.status().as_u16(), |
| 681 | 404, | 624 | 404, |
| 682 | "private stream without a session" | 625 | "private stream without a session" |
| 683 | ); | 626 | ); |
| 684 | - let member = open_stream(&http, private, Some(tahinli.as_str())).await; | 627 | + let member = http.stream(private, Some(tahinli.as_str())).await; |
| 685 | assert_eq!( | 628 | assert_eq!( |
| 686 | member.status().as_u16(), | 629 | member.status().as_u16(), |
| 687 | 200, | 630 | 200, |
| @@ -708,10 +651,11 @@ async fn issue_streams_follow_writes() { |
| 708 | return; | 651 | return; |
| 709 | } | 652 | } |
| 710 | | 653 | |
| 711 | - let (_root, _server, ports) = boot_admin("filive", TAHINLI_PW).await; | 654 | + let _root = temp_dir("filive"); |
| | 655 | + let (_server, ports) = boot_forge(_root.path(), "", &[TAHINLI_CMD]).await; |
| 712 | let http = Http::new(ports.http); | 656 | let http = Http::new(ports.http); |
| 713 | | 657 | |
| 714 | - let tahinli = login(&http, "tahinli", TAHINLI_PW).await; | 658 | + let tahinli = login(&http, "tahinli", PW).await; |
| 715 | create_repo(&http, &tahinli, "pub", "public").await; | 659 | create_repo(&http, &tahinli, "pub", "public").await; |
| 716 | create_repo(&http, &tahinli, "priv", "private").await; | 660 | create_repo(&http, &tahinli, "priv", "private").await; |
| 717 | | 661 | |
| @@ -722,7 +666,7 @@ async fn issue_streams_follow_writes() { |
| 722 | .contains(r#"data-live="/tahinli/pub/issues/live""#), | 666 | .contains(r#"data-live="/tahinli/pub/issues/live""#), |
| 723 | "the list follows the repo" | 667 | "the list follows the repo" |
| 724 | ); | 668 | ); |
| 725 | - let mut list = open_stream(&http, "/tahinli/pub/issues/live", None).await; | 669 | + let mut list = http.stream("/tahinli/pub/issues/live", None).await; |
| 726 | assert_eq!(list.status().as_u16(), 200); | 670 | assert_eq!(list.status().as_u16(), 200); |
| 727 | | 671 | |
| 728 | let new_page = http.get("/tahinli/pub/issues/new", Some(&tahinli)).await; | 672 | let new_page = http.get("/tahinli/pub/issues/new", Some(&tahinli)).await; |
| @@ -736,7 +680,7 @@ async fn issue_streams_follow_writes() { |
| 736 | .await; | 680 | .await; |
| 737 | assert_changed(&mut list, "creating an issue").await; | 681 | assert_changed(&mut list, "creating an issue").await; |
| 738 | | 682 | |
| 739 | - let mut issue = open_stream(&http, "/tahinli/pub/issues/1/live", None).await; | 683 | + let mut issue = http.stream("/tahinli/pub/issues/1/live", None).await; |
| 740 | assert_eq!(issue.status().as_u16(), 200); | 684 | assert_eq!(issue.status().as_u16(), 200); |
| 741 | let view = http.get("/tahinli/pub/issues/1", Some(&tahinli)).await; | 685 | let view = http.get("/tahinli/pub/issues/1", Some(&tahinli)).await; |
| 742 | assert!( | 686 | assert!( |
| @@ -808,19 +752,21 @@ async fn issue_streams_follow_writes() { |
| 808 | assert_changed(&mut issue, what).await; | 752 | assert_changed(&mut issue, what).await; |
| 809 | } | 753 | } |
| 810 | | 754 | |
| 811 | - let anonymous = open_stream(&http, "/tahinli/priv/issues/live", None).await; | 755 | + let anonymous = http.stream("/tahinli/priv/issues/live", None).await; |
| 812 | assert_eq!( | 756 | assert_eq!( |
| 813 | anonymous.status().as_u16(), | 757 | anonymous.status().as_u16(), |
| 814 | 404, | 758 | 404, |
| 815 | "private list without a session" | 759 | "private list without a session" |
| 816 | ); | 760 | ); |
| 817 | - let anonymous_issue = open_stream(&http, "/tahinli/priv/issues/1/live", None).await; | 761 | + let anonymous_issue = http.stream("/tahinli/priv/issues/1/live", None).await; |
| 818 | assert_eq!( | 762 | assert_eq!( |
| 819 | anonymous_issue.status().as_u16(), | 763 | anonymous_issue.status().as_u16(), |
| 820 | 404, | 764 | 404, |
| 821 | "private issue without a session" | 765 | "private issue without a session" |
| 822 | ); | 766 | ); |
| 823 | - let member = open_stream(&http, "/tahinli/priv/issues/live", Some(tahinli.as_str())).await; | 767 | + let member = http |
| | 768 | + .stream("/tahinli/priv/issues/live", Some(tahinli.as_str())) |
| | 769 | + .await; |
| 824 | assert_eq!(member.status().as_u16(), 200, "private list for its owner"); | 770 | assert_eq!(member.status().as_u16(), 200, "private list for its owner"); |
| 825 | } | 771 | } |
| 826 | | 772 | |
| @@ -831,11 +777,12 @@ async fn browsing_pages_stream_their_changes() { |
| 831 | return; | 777 | return; |
| 832 | } | 778 | } |
| 833 | | 779 | |
| 834 | - let (root, _server, ports) = boot_admin("flive", TAHINLI_PW).await; | 780 | + let root = temp_dir("flive"); |
| | 781 | + let (_server, ports) = boot_forge(root.path(), "", &[TAHINLI_CMD]).await; |
| 835 | let dir = root.path().to_path_buf(); | 782 | let dir = root.path().to_path_buf(); |
| 836 | let http = Http::new(ports.http); | 783 | let http = Http::new(ports.http); |
| 837 | | 784 | |
| 838 | - let tahinli = login(&http, "tahinli", TAHINLI_PW).await; | 785 | + let tahinli = login(&http, "tahinli", PW).await; |
| 839 | let token = create_token(&http, &tahinli, "live-pages-token").await; | 786 | let token = create_token(&http, &tahinli, "live-pages-token").await; |
| 840 | create_repo(&http, &tahinli, "pub", "public").await; | 787 | create_repo(&http, &tahinli, "pub", "public").await; |
| 841 | let pub_url = format!( | 788 | let pub_url = format!( |
| @@ -848,13 +795,15 @@ async fn browsing_pages_stream_their_changes() { |
| 848 | "/notifications/events", | 795 | "/notifications/events", |
| 849 | "/notifications/events?all=1&user=tahinli", | 796 | "/notifications/events?all=1&user=tahinli", |
| 850 | ] { | 797 | ] { |
| 851 | - let anonymous = open_stream(&http, path, None).await; | 798 | + let anonymous = http.stream(path, None).await; |
| 852 | assert_eq!(anonymous.status().as_u16(), 401, "anonymous {path}"); | 799 | assert_eq!(anonymous.status().as_u16(), 401, "anonymous {path}"); |
| 853 | } | 800 | } |
| 854 | - let inbox = open_stream(&http, "/notifications/events", Some(tahinli.as_str())).await; | 801 | + let inbox = http |
| | 802 | + .stream("/notifications/events", Some(tahinli.as_str())) |
| | 803 | + .await; |
| 855 | assert_eq!(inbox.status().as_u16(), 200, "inbox stream for its owner"); | 804 | assert_eq!(inbox.status().as_u16(), 200, "inbox stream for its owner"); |
| 856 | | 805 | |
| 857 | - let mut header = open_stream(&http, "/tahinli/pub/events", None).await; | 806 | + let mut header = http.stream("/tahinli/pub/events", None).await; |
| 858 | assert_eq!(header.status().as_u16(), 200); | 807 | assert_eq!(header.status().as_u16(), 200); |
| 859 | let page = http.get("/tahinli/pub", Some(&tahinli)).await; | 808 | let page = http.get("/tahinli/pub", Some(&tahinli)).await; |
| 860 | let csrf = input_value(&page.body(), "csrf"); | 809 | let csrf = input_value(&page.body(), "csrf"); |
| @@ -877,7 +826,7 @@ async fn browsing_pages_stream_their_changes() { |
| 877 | ok(&git(&work, &["push", "-q", "origin", "main"]), "push main"); | 826 | ok(&git(&work, &["push", "-q", "origin", "main"]), "push main"); |
| 878 | assert_ne!(pushed, head_sha(&work), "the second push moved main"); | 827 | assert_ne!(pushed, head_sha(&work), "the second push moved main"); |
| 879 | | 828 | |
| 880 | - let mut explore = open_stream(&http, "/explore/events", None).await; | 829 | + let mut explore = http.stream("/explore/events", None).await; |
| 881 | assert_eq!(explore.status().as_u16(), 200); | 830 | assert_eq!(explore.status().as_u16(), 200); |
| 882 | create_repo(&http, &tahinli, "lib", "public").await; | 831 | create_repo(&http, &tahinli, "lib", "public").await; |
| 883 | let listed = next_chunk(&mut explore) | 832 | let listed = next_chunk(&mut explore) |
| @@ -885,13 +834,13 @@ async fn browsing_pages_stream_their_changes() { |
| 885 | .expect("event for a new public repo"); | 834 | .expect("event for a new public repo"); |
| 886 | assert!(listed.contains("event: changed"), "{listed}"); | 835 | assert!(listed.contains("event: changed"), "{listed}"); |
| 887 | | 836 | |
| 888 | - let mut profile = open_stream(&http, "/users/tahinli/events", None).await; | 837 | + let mut profile = http.stream("/users/tahinli/events", None).await; |
| 889 | assert_eq!(profile.status().as_u16(), 200); | 838 | assert_eq!(profile.status().as_u16(), 200); |
| 890 | create_repo(&http, &tahinli, "tools", "public").await; | 839 | create_repo(&http, &tahinli, "tools", "public").await; |
| 891 | let changed = next_chunk(&mut profile) | 840 | let changed = next_chunk(&mut profile) |
| 892 | .await | 841 | .await |
| 893 | .expect("event for a new repo of the profile"); | 842 | .expect("event for a new repo of the profile"); |
| 894 | assert!(changed.contains("event: changed"), "{changed}"); | 843 | assert!(changed.contains("event: changed"), "{changed}"); |
| 895 | - let missing = open_stream(&http, "/users/nobody/events", None).await; | 844 | + let missing = http.stream("/users/nobody/events", None).await; |
| 896 | assert_eq!(missing.status().as_u16(), 404, "profile of an unknown user"); | 845 | assert_eq!(missing.status().as_u16(), 404, "profile of an unknown user"); |
| 897 | } | 846 | } |
| @@ -1,5 +1,6 @@ |
| 1 | use crate::common::{ | 1 | use crate::common::{ |
| 2 | - FAST_CLAIMS, Http, Server, input_value, launch_with, login, pick_ports, run_admin, write_config, | 2 | + BOB_CMD, FAST_CLAIMS, Http, PW, Server, TAHINLI_CMD, boot_forge, clone, commit, create_repo, |
| | 3 | + create_token, csrf_for, first_text, git_text, git_text_env, login, temp_dir, |
| 3 | }; | 4 | }; |
| 4 | use forge_ci::proto::{JobAssignment, Outcome, RegisterRequest}; | 5 | use forge_ci::proto::{JobAssignment, Outcome, RegisterRequest}; |
| 5 | use forge_runner::client::ForgeClient; | 6 | use forge_runner::client::ForgeClient; |
| @@ -14,9 +15,9 @@ use std::sync::Arc; |
| 14 | use std::time::{Duration, Instant}; | 15 | use std::time::{Duration, Instant}; |
| 15 | use tokio_util::sync::CancellationToken; | 16 | use tokio_util::sync::CancellationToken; |
| 16 | | 17 | |
| 17 | -const TAHINLI_PW: &str = "tahinli-password-123"; | | |
| 18 | -const BOB_PW: &str = "bob-password-4567"; | | |
| 19 | const BOB_EMAIL: &str = "bob@users.noreply.127.0.0.1"; | 18 | const BOB_EMAIL: &str = "bob@users.noreply.127.0.0.1"; |
| | 19 | +const TAHINLI: (&str, &str) = ("tahinli", "tahinli@example.test"); |
| | 20 | +const BOB: (&str, &str) = ("bob", BOB_EMAIL); |
| 20 | const REPO_PATH: &str = "/tahinli/r"; | 21 | const REPO_PATH: &str = "/tahinli/r"; |
| 21 | const SECRET_VALUE: &str = "supersecretvalue"; | 22 | const SECRET_VALUE: &str = "supersecretvalue"; |
| 22 | const LABELS: &[&str] = &["linux"]; | 23 | const LABELS: &[&str] = &["linux"]; |
| @@ -75,127 +76,12 @@ run = "echo never" |
| 75 | needs = ["broken"] | 76 | needs = ["broken"] |
| 76 | "#; | 77 | "#; |
| 77 | | 78 | |
| 78 | -fn first_text(body: &str, selector: &str) -> String { | | |
| 79 | - let doc = scraper::Html::parse_document(body); | | |
| 80 | - let selector = scraper::Selector::parse(selector).expect("selector"); | | |
| 81 | - doc.select(&selector) | | |
| 82 | - .next() | | |
| 83 | - .unwrap_or_else(|| panic!("no element matches {selector:?}")) | | |
| 84 | - .text() | | |
| 85 | - .collect::<String>() | | |
| 86 | - .trim() | | |
| 87 | - .to_owned() | | |
| 88 | -} | | |
| 89 | - | | |
| 90 | -fn git_env(cwd: &Path, args: &[&str], env: &[(&str, &str)]) -> String { | | |
| 91 | - let mut cmd = Command::new("git"); | | |
| 92 | - cmd.current_dir(cwd) | | |
| 93 | - .args(["-c", "credential.helper="]) | | |
| 94 | - .args(args) | | |
| 95 | - .env("GIT_TERMINAL_PROMPT", "0"); | | |
| 96 | - for (key, value) in env { | | |
| 97 | - cmd.env(key, value); | | |
| 98 | - } | | |
| 99 | - let out = cmd.output().expect("run git"); | | |
| 100 | - assert!( | | |
| 101 | - out.status.success(), | | |
| 102 | - "git {args:?} failed:\n{}", | | |
| 103 | - String::from_utf8_lossy(&out.stderr) | | |
| 104 | - ); | | |
| 105 | - String::from_utf8_lossy(&out.stdout).trim().to_owned() | | |
| 106 | -} | | |
| 107 | - | | |
| 108 | -fn git(cwd: &Path, args: &[&str]) -> String { | | |
| 109 | - git_env(cwd, args, &[]) | | |
| 110 | -} | | |
| 111 | - | | |
| 112 | -fn commit( | | |
| 113 | - repo: &Path, | | |
| 114 | - file: &str, | | |
| 115 | - contents: &str, | | |
| 116 | - message: &str, | | |
| 117 | - who: &str, | | |
| 118 | - email: &str, | | |
| 119 | -) -> String { | | |
| 120 | - let path = repo.join(file); | | |
| 121 | - if let Some(parent) = path.parent() { | | |
| 122 | - fs::create_dir_all(parent).expect("create dir"); | | |
| 123 | - } | | |
| 124 | - fs::write(&path, contents).expect("write file"); | | |
| 125 | - git(repo, &["add", file]); | | |
| 126 | - git_env( | | |
| 127 | - repo, | | |
| 128 | - &["-c", "commit.gpgsign=false", "commit", "-q", "-m", message], | | |
| 129 | - &[ | | |
| 130 | - ("GIT_AUTHOR_NAME", who), | | |
| 131 | - ("GIT_AUTHOR_EMAIL", email), | | |
| 132 | - ("GIT_COMMITTER_NAME", who), | | |
| 133 | - ("GIT_COMMITTER_EMAIL", email), | | |
| 134 | - ], | | |
| 135 | - ); | | |
| 136 | - git(repo, &["rev-parse", "HEAD"]) | | |
| 137 | -} | | |
| 138 | - | | |
| 139 | -fn clone(url: &str, into: &Path) -> PathBuf { | | |
| 140 | - let parent = into.parent().expect("clone target has a parent"); | | |
| 141 | - git( | | |
| 142 | - parent, | | |
| 143 | - &["clone", "-q", url, into.to_str().expect("utf-8 path")], | | |
| 144 | - ); | | |
| 145 | - into.to_path_buf() | | |
| 146 | -} | | |
| 147 | - | | |
| 148 | fn remote(port: u16, user: &str, token: &str, owner: &str, repo: &str) -> String { | 79 | fn remote(port: u16, user: &str, token: &str, owner: &str, repo: &str) -> String { |
| 149 | format!("http://{user}:{token}@127.0.0.1:{port}/{owner}/{repo}.git") | 80 | format!("http://{user}:{token}@127.0.0.1:{port}/{owner}/{repo}.git") |
| 150 | } | 81 | } |
| 151 | | 82 | |
| 152 | -async fn csrf_from(http: &Http, path: &str, session: &str) -> String { | | |
| 153 | - let page = http.get(path, Some(session)).await; | | |
| 154 | - assert_eq!(page.status, 200, "GET {path}"); | | |
| 155 | - input_value(&page.body, "csrf") | | |
| 156 | -} | | |
| 157 | - | | |
| 158 | -async fn create_token(http: &Http, session: &str, name: &str) -> String { | | |
| 159 | - let csrf = csrf_from(http, "/settings/keys", session).await; | | |
| 160 | - let res = http | | |
| 161 | - .post_form( | | |
| 162 | - "/settings/tokens", | | |
| 163 | - &[("csrf", &csrf), ("name", name), ("expires", "30")], | | |
| 164 | - Some(session), | | |
| 165 | - ) | | |
| 166 | - .await; | | |
| 167 | - assert_eq!(res.status, 200, "create token: {}", res.body); | | |
| 168 | - let token = first_text(&res.body, "pre.code code"); | | |
| 169 | - assert!(token.starts_with("forge_"), "unexpected token shape"); | | |
| 170 | - token | | |
| 171 | -} | | |
| 172 | - | | |
| 173 | -async fn create_repo(http: &Http, session: &str, name: &str) { | | |
| 174 | - let page = http.get("/new", Some(session)).await; | | |
| 175 | - assert_eq!(page.status, 200, "GET /new"); | | |
| 176 | - let csrf = input_value(&page.body, "csrf"); | | |
| 177 | - let res = http | | |
| 178 | - .post_form( | | |
| 179 | - "/new", | | |
| 180 | - &[ | | |
| 181 | - ("csrf", &csrf), | | |
| 182 | - ("name", name), | | |
| 183 | - ("description", ""), | | |
| 184 | - ("visibility", "public"), | | |
| 185 | - ("default_branch", "main"), | | |
| 186 | - ], | | |
| 187 | - Some(session), | | |
| 188 | - ) | | |
| 189 | - .await; | | |
| 190 | - assert_eq!(res.status, 303, "create repo {name}: {}", res.body); | | |
| 191 | - assert_eq!( | | |
| 192 | - res.location().as_deref(), | | |
| 193 | - Some(format!("/tahinli/{name}").as_str()) | | |
| 194 | - ); | | |
| 195 | -} | | |
| 196 | - | | |
| 197 | async fn set_secret(http: &Http, session: &str, name: &str, value: &str) { | 83 | async fn set_secret(http: &Http, session: &str, name: &str, value: &str) { |
| 198 | - let csrf = csrf_from(http, &format!("{REPO_PATH}/settings/secrets"), session).await; | 84 | + let csrf = csrf_for(http, &format!("{REPO_PATH}/settings/secrets"), session).await; |
| 199 | let res = http | 85 | let res = http |
| 200 | .post_form( | 86 | .post_form( |
| 201 | &format!("{REPO_PATH}/settings/secrets"), | 87 | &format!("{REPO_PATH}/settings/secrets"), |
| @@ -220,17 +106,9 @@ fn server_log(b: &Booted) -> String { |
| 220 | } | 106 | } |
| 221 | | 107 | |
| 222 | async fn boot() -> Booted { | 108 | async fn boot() -> Booted { |
| 223 | - let root = tempfile::Builder::new() | 109 | + let root = temp_dir("ci2e"); |
| 224 | - .prefix("ci2e") | | |
| 225 | - .tempdir_in("/tmp") | | |
| 226 | - .expect("temp dir"); | | |
| 227 | let dir = root.path().to_path_buf(); | 110 | let dir = root.path().to_path_buf(); |
| 228 | - let ports = pick_ports(); | 111 | + let (server, ports) = boot_forge(&dir, FAST_CLAIMS, &[TAHINLI_CMD, BOB_CMD]).await; |
| 229 | - let config = write_config(&dir, ports); | | |
| 230 | - | | |
| 231 | - run_admin(&config, "tahinli", &["--admin"], TAHINLI_PW); | | |
| 232 | - run_admin(&config, "bob", &[], BOB_PW); | | |
| 233 | - let (server, ports) = launch_with(&dir, ports, FAST_CLAIMS).await; | | |
| 234 | Booted { | 112 | Booted { |
| 235 | _server: server, | 113 | _server: server, |
| 236 | _root: root, | 114 | _root: root, |
| @@ -268,9 +146,7 @@ impl Worker { |
| 268 | } | 146 | } |
| 269 | | 147 | |
| 270 | async fn register_runner(b: &Booted, admin_session: &str, name: &str) -> Worker { | 148 | async fn register_runner(b: &Booted, admin_session: &str, name: &str) -> Worker { |
| 271 | - let page = b.http.get("/admin/runners", Some(admin_session)).await; | 149 | + let csrf = csrf_for(&b.http, "/admin/runners", admin_session).await; |
| 272 | - assert_eq!(page.status, 200, "GET /admin/runners"); | | |
| 273 | - let csrf = input_value(&page.body, "csrf"); | | |
| 274 | let res = b | 150 | let res = b |
| 275 | .http | 151 | .http |
| 276 | .post_form( | 152 | .post_form( |
| @@ -381,24 +257,17 @@ fn job_id_of(status: &Status) -> String { |
| 381 | } | 257 | } |
| 382 | | 258 | |
| 383 | fn push_ci_config(work: &Path, contents: &str) -> String { | 259 | fn push_ci_config(work: &Path, contents: &str) -> String { |
| 384 | - let sha = commit( | 260 | + let sha = commit(work, ".forge/ci.toml", contents, "add ci", TAHINLI); |
| 385 | - work, | 261 | + git_text(work, &["push", "-q", "origin", "HEAD:refs/heads/main"]); |
| 386 | - ".forge/ci.toml", | | |
| 387 | - contents, | | |
| 388 | - "add ci", | | |
| 389 | - "tahinli", | | |
| 390 | - "tahinli@example.test", | | |
| 391 | - ); | | |
| 392 | - git(work, &["push", "-q", "origin", "HEAD:refs/heads/main"]); | | |
| 393 | sha | 262 | sha |
| 394 | } | 263 | } |
| 395 | | 264 | |
| 396 | #[tokio::test] | 265 | #[tokio::test] |
| 397 | async fn push_run_masks_secrets_keeps_artifacts_and_skips_dependants() { | 266 | async fn push_run_masks_secrets_keeps_artifacts_and_skips_dependants() { |
| 398 | let b = boot().await; | 267 | let b = boot().await; |
| 399 | - let tahinli = login(&b.http, "tahinli", TAHINLI_PW).await; | 268 | + let tahinli = login(&b.http, "tahinli", PW).await; |
| 400 | let token = create_token(&b.http, &tahinli, "ci-token").await; | 269 | let token = create_token(&b.http, &tahinli, "ci-token").await; |
| 401 | - create_repo(&b.http, &tahinli, "r").await; | 270 | + create_repo(&b.http, &tahinli, "r", "public").await; |
| 402 | set_secret(&b.http, &tahinli, "MY_SECRET", SECRET_VALUE).await; | 271 | set_secret(&b.http, &tahinli, "MY_SECRET", SECRET_VALUE).await; |
| 403 | let worker = register_runner(&b, &tahinli, "runner-a").await; | 272 | let worker = register_runner(&b, &tahinli, "runner-a").await; |
| 404 | | 273 | |
| @@ -485,9 +354,9 @@ async fn push_run_masks_secrets_keeps_artifacts_and_skips_dependants() { |
| 485 | #[tokio::test] | 354 | #[tokio::test] |
| 486 | async fn run_page_lists_a_jobs_steps_and_a_step_opens_its_part_of_the_log() { | 355 | async fn run_page_lists_a_jobs_steps_and_a_step_opens_its_part_of_the_log() { |
| 487 | let b = boot().await; | 356 | let b = boot().await; |
| 488 | - let tahinli = login(&b.http, "tahinli", TAHINLI_PW).await; | 357 | + let tahinli = login(&b.http, "tahinli", PW).await; |
| 489 | let token = create_token(&b.http, &tahinli, "ci-token").await; | 358 | let token = create_token(&b.http, &tahinli, "ci-token").await; |
| 490 | - create_repo(&b.http, &tahinli, "r").await; | 359 | + create_repo(&b.http, &tahinli, "r", "public").await; |
| 491 | let worker = register_runner(&b, &tahinli, "runner-a").await; | 360 | let worker = register_runner(&b, &tahinli, "runner-a").await; |
| 492 | | 361 | |
| 493 | let work = clone( | 362 | let work = clone( |
| @@ -538,9 +407,9 @@ async fn run_page_lists_a_jobs_steps_and_a_step_opens_its_part_of_the_log() { |
| 538 | #[tokio::test] | 407 | #[tokio::test] |
| 539 | async fn fork_pull_waits_for_approval_and_runs_without_secrets() { | 408 | async fn fork_pull_waits_for_approval_and_runs_without_secrets() { |
| 540 | let b = boot().await; | 409 | let b = boot().await; |
| 541 | - let tahinli = login(&b.http, "tahinli", TAHINLI_PW).await; | 410 | + let tahinli = login(&b.http, "tahinli", PW).await; |
| 542 | let token = create_token(&b.http, &tahinli, "ci-token").await; | 411 | let token = create_token(&b.http, &tahinli, "ci-token").await; |
| 543 | - create_repo(&b.http, &tahinli, "r").await; | 412 | + create_repo(&b.http, &tahinli, "r", "public").await; |
| 544 | set_secret(&b.http, &tahinli, "MY_SECRET", SECRET_VALUE).await; | 413 | set_secret(&b.http, &tahinli, "MY_SECRET", SECRET_VALUE).await; |
| 545 | let worker = register_runner(&b, &tahinli, "runner-a").await; | 414 | let worker = register_runner(&b, &tahinli, "runner-a").await; |
| 546 | | 415 | |
| @@ -552,9 +421,9 @@ async fn fork_pull_waits_for_approval_and_runs_without_secrets() { |
| 552 | wait_statuses(&b.http, &token, &base_sha, &["ci/build"]).await; | 421 | wait_statuses(&b.http, &token, &base_sha, &["ci/build"]).await; |
| 553 | worker.drain().await; | 422 | worker.drain().await; |
| 554 | | 423 | |
| 555 | - let bob = login(&b.http, "bob", BOB_PW).await; | 424 | + let bob = login(&b.http, "bob", PW).await; |
| 556 | let bob_token = create_token(&b.http, &bob, "bob-token").await; | 425 | let bob_token = create_token(&b.http, &bob, "bob-token").await; |
| 557 | - let csrf = csrf_from(&b.http, "/settings/keys", &bob).await; | 426 | + let csrf = csrf_for(&b.http, "/settings/keys", &bob).await; |
| 558 | let fork = b | 427 | let fork = b |
| 559 | .http | 428 | .http |
| 560 | .post_form(&format!("{REPO_PATH}/fork"), &[("csrf", &csrf)], Some(&bob)) | 429 | .post_form(&format!("{REPO_PATH}/fork"), &[("csrf", &csrf)], Some(&bob)) |
| @@ -565,16 +434,15 @@ async fn fork_pull_waits_for_approval_and_runs_without_secrets() { |
| 565 | &remote(b.port, "bob", &bob_token, "bob", "r"), | 434 | &remote(b.port, "bob", &bob_token, "bob", "r"), |
| 566 | &b.dir.join("bob-work"), | 435 | &b.dir.join("bob-work"), |
| 567 | ); | 436 | ); |
| 568 | - git(&bob_work, &["checkout", "-q", "-b", "bob-feature"]); | 437 | + git_text(&bob_work, &["checkout", "-q", "-b", "bob-feature"]); |
| 569 | let head = commit( | 438 | let head = commit( |
| 570 | &bob_work, | 439 | &bob_work, |
| 571 | ".forge/ci.toml", | 440 | ".forge/ci.toml", |
| 572 | CI_TOML_FORK, | 441 | CI_TOML_FORK, |
| 573 | "print the secret", | 442 | "print the secret", |
| 574 | - "bob", | 443 | + BOB, |
| 575 | - BOB_EMAIL, | | |
| 576 | ); | 444 | ); |
| 577 | - git( | 445 | + git_text( |
| 578 | &bob_work, | 446 | &bob_work, |
| 579 | &["push", "-q", "origin", "HEAD:refs/heads/bob-feature"], | 447 | &["push", "-q", "origin", "HEAD:refs/heads/bob-feature"], |
| 580 | ); | 448 | ); |
| @@ -587,7 +455,7 @@ async fn fork_pull_waits_for_approval_and_runs_without_secrets() { |
| 587 | ) | 455 | ) |
| 588 | .await; | 456 | .await; |
| 589 | assert_eq!(compare.status, 200, "GET compare"); | 457 | assert_eq!(compare.status, 200, "GET compare"); |
| 590 | - let csrf = csrf_from(&b.http, "/settings/keys", &bob).await; | 458 | + let csrf = csrf_for(&b.http, "/settings/keys", &bob).await; |
| 591 | let open = b | 459 | let open = b |
| 592 | .http | 460 | .http |
| 593 | .post_form( | 461 | .post_form( |
| @@ -623,7 +491,10 @@ async fn fork_pull_waits_for_approval_and_runs_without_secrets() { |
| 623 | .http | 491 | .http |
| 624 | .post_form( | 492 | .post_form( |
| 625 | &format!("{REPO_PATH}/ci/runs/2/approve"), | 493 | &format!("{REPO_PATH}/ci/runs/2/approve"), |
| 626 | - &[("csrf", &input_value(&run_page.body, "csrf"))], | 494 | + &[( |
| | 495 | + "csrf", |
| | 496 | + &csrf_for(&b.http, &format!("{REPO_PATH}/ci/runs/2"), &tahinli).await, |
| | 497 | + )], |
| 627 | Some(&tahinli), | 498 | Some(&tahinli), |
| 628 | ) | 499 | ) |
| 629 | .await; | 500 | .await; |
| @@ -652,9 +523,9 @@ async fn fork_pull_waits_for_approval_and_runs_without_secrets() { |
| 652 | #[tokio::test] | 523 | #[tokio::test] |
| 653 | async fn live_log_streams_until_the_job_finishes() { | 524 | async fn live_log_streams_until_the_job_finishes() { |
| 654 | let b = boot().await; | 525 | let b = boot().await; |
| 655 | - let tahinli = login(&b.http, "tahinli", TAHINLI_PW).await; | 526 | + let tahinli = login(&b.http, "tahinli", PW).await; |
| 656 | let token = create_token(&b.http, &tahinli, "ci-token").await; | 527 | let token = create_token(&b.http, &tahinli, "ci-token").await; |
| 657 | - create_repo(&b.http, &tahinli, "r").await; | 528 | + create_repo(&b.http, &tahinli, "r", "public").await; |
| 658 | let worker = register_runner(&b, &tahinli, "runner-a").await; | 529 | let worker = register_runner(&b, &tahinli, "runner-a").await; |
| 659 | | 530 | |
| 660 | let release = b.dir.join("release"); | 531 | let release = b.dir.join("release"); |
| @@ -717,18 +588,12 @@ run = "echo started; i=0; while [ ! -f {} ] && [ $i -lt 100 ]; do sleep 0.1; i=$ |
| 717 | #[tokio::test] | 588 | #[tokio::test] |
| 718 | async fn ci_job_token_clones_the_repos_wiki_read_only() { | 589 | async fn ci_job_token_clones_the_repos_wiki_read_only() { |
| 719 | let b = boot().await; | 590 | let b = boot().await; |
| 720 | - let tahinli = login(&b.http, "tahinli", TAHINLI_PW).await; | 591 | + let tahinli = login(&b.http, "tahinli", PW).await; |
| 721 | let token = create_token(&b.http, &tahinli, "ci-token").await; | 592 | let token = create_token(&b.http, &tahinli, "ci-token").await; |
| 722 | - create_repo(&b.http, &tahinli, "r").await; | 593 | + create_repo(&b.http, &tahinli, "r", "public").await; |
| 723 | let worker = register_runner(&b, &tahinli, "runner-a").await; | 594 | let worker = register_runner(&b, &tahinli, "runner-a").await; |
| 724 | | 595 | |
| 725 | - let csrf = input_value( | 596 | + let csrf = csrf_for(&b.http, &format!("{REPO_PATH}/wiki/-/new"), &tahinli).await; |
| 726 | - &b.http | | |
| 727 | - .get(&format!("{REPO_PATH}/wiki/-/new"), Some(&tahinli)) | | |
| 728 | - .await | | |
| 729 | - .body, | | |
| 730 | - "csrf", | | |
| 731 | - ); | | |
| 732 | let saved = b | 597 | let saved = b |
| 733 | .http | 598 | .http |
| 734 | .post_form( | 599 | .post_form( |
| @@ -770,8 +635,8 @@ run = "echo started; sleep 5; echo done" |
| 770 | assert!(home.contains("Welcome from the wiki"), "{home}"); | 635 | assert!(home.contains("Welcome from the wiki"), "{home}"); |
| 771 | | 636 | |
| 772 | fs::write(job_wiki.join("Home.md"), "# changed by a job\n").expect("write"); | 637 | fs::write(job_wiki.join("Home.md"), "# changed by a job\n").expect("write"); |
| 773 | - git(&job_wiki, &["add", "Home.md"]); | 638 | + git_text(&job_wiki, &["add", "Home.md"]); |
| 774 | - git_env( | 639 | + git_text_env( |
| 775 | &job_wiki, | 640 | &job_wiki, |
| 776 | &[ | 641 | &[ |
| 777 | "-c", | 642 | "-c", |
| @@ -96,20 +96,7 @@ impl Http { |
| 96 | } | 96 | } |
| 97 | | 97 | |
| 98 | pub async fn stream(&self, path: &str, cookie: Option<&str>) -> reqwest::Response { | 98 | pub async fn stream(&self, path: &str, cookie: Option<&str>) -> reqwest::Response { |
| 99 | - let mut req = self.client.get(format!("{}{path}", self.base)); | 99 | + open_stream(&self.client, &format!("{}{path}", self.base), cookie).await |
| 100 | - if let Some(cookie) = cookie { | | |
| 101 | - req = req.header(COOKIE, cookie); | | |
| 102 | - } | | |
| 103 | - let mut res = req.send().await.expect("stream request"); | | |
| 104 | - if res.status().is_success() { | | |
| 105 | - let retry = tokio::time::timeout(Duration::from_secs(5), res.chunk()) | | |
| 106 | - .await | | |
| 107 | - .expect("the retry field") | | |
| 108 | - .expect("stream chunk") | | |
| 109 | - .expect("stream still open"); | | |
| 110 | - assert!(String::from_utf8_lossy(&retry).contains("retry: 1000")); | | |
| 111 | - } | | |
| 112 | - res | | |
| 113 | } | 100 | } |
| 114 | | 101 | |
| 115 | pub async fn send(&self, req: reqwest::RequestBuilder, cookie: Option<&str>) -> Resp { | 102 | pub async fn send(&self, req: reqwest::RequestBuilder, cookie: Option<&str>) -> Resp { |
| @@ -162,3 +149,30 @@ pub async fn login(http: &Http, username: &str, password: &str) -> String { |
| 162 | assert_eq!(res.status, 303, "login as {username}: {}", res.body); | 149 | assert_eq!(res.status, 303, "login as {username}: {}", res.body); |
| 163 | cookie_named(&res, "forge_session").expect("session cookie after login") | 150 | cookie_named(&res, "forge_session").expect("session cookie after login") |
| 164 | } | 151 | } |
| | 152 | + |
| | 153 | +pub async fn csrf_for(http: &Http, path: &str, session: &str) -> String { |
| | 154 | + let page = http.get(path, Some(session)).await; |
| | 155 | + assert_eq!(page.status, 200, "GET {path}"); |
| | 156 | + input_value(&page.body, "csrf") |
| | 157 | +} |
| | 158 | + |
| | 159 | +pub async fn open_stream( |
| | 160 | + client: &reqwest::Client, |
| | 161 | + url: &str, |
| | 162 | + cookie: Option<&str>, |
| | 163 | +) -> reqwest::Response { |
| | 164 | + let mut req = client.get(url); |
| | 165 | + if let Some(cookie) = cookie { |
| | 166 | + req = req.header(COOKIE, cookie); |
| | 167 | + } |
| | 168 | + let mut res = req.send().await.expect("stream request"); |
| | 169 | + if res.status().is_success() { |
| | 170 | + let retry = tokio::time::timeout(Duration::from_secs(5), res.chunk()) |
| | 171 | + .await |
| | 172 | + .expect("the retry field") |
| | 173 | + .expect("stream chunk") |
| | 174 | + .expect("stream still open"); |
| | 175 | + assert!(String::from_utf8_lossy(&retry).contains("retry: 1000")); |
| | 176 | + } |
| | 177 | + res |
| | 178 | +} |
| @@ -5,11 +5,9 @@ use std::process::{Child, Command, ExitStatus, Output, Stdio}; |
| 5 | use std::sync::OnceLock; | 5 | use std::sync::OnceLock; |
| 6 | use std::time::{Duration, Instant}; | 6 | use std::time::{Duration, Instant}; |
| 7 | | 7 | |
| 8 | -use tempfile::TempDir; | | |
| 9 | - | | |
| 10 | mod http; | 8 | mod http; |
| 11 | | 9 | |
| 12 | -pub use http::{Http, Resp, cookie_named, login, with_cookie}; | 10 | +pub use http::{Http, Resp, cookie_named, csrf_for, login, open_stream, with_cookie}; |
| 13 | | 11 | |
| 14 | pub fn bin() -> &'static str { | 12 | pub fn bin() -> &'static str { |
| 15 | static BIN: OnceLock<String> = OnceLock::new(); | 13 | static BIN: OnceLock<String> = OnceLock::new(); |
| @@ -78,6 +76,62 @@ pub fn input_value(body: &str, name: &str) -> String { |
| 78 | .to_owned() | 76 | .to_owned() |
| 79 | } | 77 | } |
| 80 | | 78 | |
| | 79 | +pub fn first_text(body: &str, selector: &str) -> String { |
| | 80 | + let doc = scraper::Html::parse_document(body); |
| | 81 | + let selector = scraper::Selector::parse(selector).expect("selector"); |
| | 82 | + doc.select(&selector) |
| | 83 | + .next() |
| | 84 | + .unwrap_or_else(|| panic!("no element matches {selector:?}")) |
| | 85 | + .text() |
| | 86 | + .collect::<String>() |
| | 87 | + .trim() |
| | 88 | + .to_owned() |
| | 89 | +} |
| | 90 | + |
| | 91 | +pub fn form_action(body: &str, suffix: &str) -> String { |
| | 92 | + let doc = scraper::Html::parse_document(body); |
| | 93 | + let selector = scraper::Selector::parse("form").expect("selector"); |
| | 94 | + doc.select(&selector) |
| | 95 | + .filter_map(|el| el.value().attr("action")) |
| | 96 | + .find(|action| action.ends_with(suffix)) |
| | 97 | + .unwrap_or_else(|| panic!("no form ending in {suffix} on page")) |
| | 98 | + .to_owned() |
| | 99 | +} |
| | 100 | + |
| | 101 | +pub fn attr_values(body: &str, selector: &str, attr: &str) -> Vec<String> { |
| | 102 | + let doc = scraper::Html::parse_document(body); |
| | 103 | + let selector = scraper::Selector::parse(selector).expect("selector"); |
| | 104 | + doc.select(&selector) |
| | 105 | + .filter_map(|el| el.value().attr(attr).map(str::to_owned)) |
| | 106 | + .collect() |
| | 107 | +} |
| | 108 | + |
| | 109 | +pub fn element_texts(body: &str, selector: &str) -> Vec<String> { |
| | 110 | + let doc = scraper::Html::parse_document(body); |
| | 111 | + let selector = scraper::Selector::parse(selector).expect("selector"); |
| | 112 | + doc.select(&selector) |
| | 113 | + .map(|el| el.text().collect::<String>()) |
| | 114 | + .collect() |
| | 115 | +} |
| | 116 | + |
| | 117 | +pub fn attr_of(body: &str, selector: &str, attr: &str) -> Option<String> { |
| | 118 | + let doc = scraper::Html::parse_document(body); |
| | 119 | + let selector = scraper::Selector::parse(selector).expect("selector"); |
| | 120 | + doc.select(&selector) |
| | 121 | + .next() |
| | 122 | + .and_then(|el| el.value().attr(attr)) |
| | 123 | + .map(str::to_owned) |
| | 124 | +} |
| | 125 | + |
| | 126 | +pub fn text_or_empty(body: &str, selector: &str) -> String { |
| | 127 | + let doc = scraper::Html::parse_document(body); |
| | 128 | + let selector = scraper::Selector::parse(selector).expect("selector"); |
| | 129 | + doc.select(&selector) |
| | 130 | + .next() |
| | 131 | + .map(|el| el.text().collect::<String>().trim().to_owned()) |
| | 132 | + .unwrap_or_default() |
| | 133 | +} |
| | 134 | + |
| 81 | pub fn temp_dir(prefix: &str) -> tempfile::TempDir { | 135 | pub fn temp_dir(prefix: &str) -> tempfile::TempDir { |
| 82 | tempfile::Builder::new() | 136 | tempfile::Builder::new() |
| 83 | .prefix(prefix) | 137 | .prefix(prefix) |
| @@ -85,6 +139,11 @@ pub fn temp_dir(prefix: &str) -> tempfile::TempDir { |
| 85 | .expect("temp dir") | 139 | .expect("temp dir") |
| 86 | } | 140 | } |
| 87 | | 141 | |
| | 142 | +pub async fn assert_quiet(res: &mut reqwest::Response, what: &str) { |
| | 143 | + let got = tokio::time::timeout(Duration::from_secs(2), res.chunk()).await; |
| | 144 | + assert!(got.is_err(), "{what}: the stream sent an event"); |
| | 145 | +} |
| | 146 | + |
| 88 | pub fn free_port() -> u16 { | 147 | pub fn free_port() -> u16 { |
| 89 | std::net::TcpListener::bind("127.0.0.1:0") | 148 | std::net::TcpListener::bind("127.0.0.1:0") |
| 90 | .expect("bind free port") | 149 | .expect("bind free port") |
| @@ -117,10 +176,6 @@ pub fn tool_on_path(name: &str) -> bool { |
| 117 | .is_ok() | 176 | .is_ok() |
| 118 | } | 177 | } |
| 119 | | 178 | |
| 120 | -pub fn write_config(dir: &Path, ports: Ports) -> PathBuf { | | |
| 121 | - write_config_with(dir, ports, "") | | |
| 122 | -} | | |
| 123 | - | | |
| 124 | pub fn write_config_with(dir: &Path, ports: Ports, extra: &str) -> PathBuf { | 179 | pub fn write_config_with(dir: &Path, ports: Ports, extra: &str) -> PathBuf { |
| 125 | let d = dir.display(); | 180 | let d = dir.display(); |
| 126 | let Ports { | 181 | let Ports { |
| @@ -148,7 +203,19 @@ pub fn write_config_with(dir: &Path, ports: Ports, extra: &str) -> PathBuf { |
| 148 | | 203 | |
| 149 | pub const FAST_CLAIMS: &str = "[ci]\nclaim_wait_ms = 50\n"; | 204 | pub const FAST_CLAIMS: &str = "[ci]\nclaim_wait_ms = 50\n"; |
| 150 | | 205 | |
| 151 | -pub fn git(cwd: &Path, args: &[&str], env: &[(&str, &str)]) -> Output { | 206 | +pub fn git(cwd: &Path, args: &[&str]) -> Output { |
| | 207 | + git_env(cwd, args, &[]) |
| | 208 | +} |
| | 209 | + |
| | 210 | +pub fn ok(out: &Output, what: &str) { |
| | 211 | + assert!(out.status.success(), "{what} failed:\n{}", describe(out)); |
| | 212 | +} |
| | 213 | + |
| | 214 | +pub fn path_str(path: &Path) -> &str { |
| | 215 | + path.to_str().expect("utf-8 path") |
| | 216 | +} |
| | 217 | + |
| | 218 | +pub fn git_env(cwd: &Path, args: &[&str], env: &[(&str, &str)]) -> Output { |
| 152 | let mut cmd = Command::new("git"); | 219 | let mut cmd = Command::new("git"); |
| 153 | cmd.current_dir(cwd) | 220 | cmd.current_dir(cwd) |
| 154 | .args(["-c", "credential.helper="]) | 221 | .args(["-c", "credential.helper="]) |
| @@ -160,6 +227,78 @@ pub fn git(cwd: &Path, args: &[&str], env: &[(&str, &str)]) -> Output { |
| 160 | cmd.output().expect("run git") | 227 | cmd.output().expect("run git") |
| 161 | } | 228 | } |
| 162 | | 229 | |
| | 230 | +pub fn git_text(cwd: &Path, args: &[&str]) -> String { |
| | 231 | + git_text_env(cwd, args, &[]) |
| | 232 | +} |
| | 233 | + |
| | 234 | +pub fn git_text_env(cwd: &Path, args: &[&str], env: &[(&str, &str)]) -> String { |
| | 235 | + let out = git_env(cwd, args, env); |
| | 236 | + assert!( |
| | 237 | + out.status.success(), |
| | 238 | + "git {args:?} failed:\n{}", |
| | 239 | + describe(&out) |
| | 240 | + ); |
| | 241 | + String::from_utf8_lossy(&out.stdout).trim().to_owned() |
| | 242 | +} |
| | 243 | + |
| | 244 | +pub fn set_identity(repo: &Path) { |
| | 245 | + ok( |
| | 246 | + &git(repo, &["config", "user.name", "tahinli"]), |
| | 247 | + "set user.name", |
| | 248 | + ); |
| | 249 | + ok( |
| | 250 | + &git(repo, &["config", "user.email", "tahinli@example.com"]), |
| | 251 | + "set user.email", |
| | 252 | + ); |
| | 253 | +} |
| | 254 | + |
| | 255 | +pub fn head_sha(repo: &Path) -> String { |
| | 256 | + git_text(repo, &["rev-parse", "HEAD"]) |
| | 257 | +} |
| | 258 | + |
| | 259 | +pub fn commit_file(repo: &Path, name: &str, content: &str, message: &str) -> String { |
| | 260 | + let file = repo.join(name); |
| | 261 | + fs::create_dir_all(file.parent().expect("parent")).expect("create dir"); |
| | 262 | + fs::write(&file, content).expect("write file"); |
| | 263 | + set_identity(repo); |
| | 264 | + ok(&git(repo, &["add", name]), "git add"); |
| | 265 | + ok( |
| | 266 | + &git( |
| | 267 | + repo, |
| | 268 | + &["-c", "commit.gpgsign=false", "commit", "-q", "-m", message], |
| | 269 | + ), |
| | 270 | + "git commit", |
| | 271 | + ); |
| | 272 | + head_sha(repo) |
| | 273 | +} |
| | 274 | + |
| | 275 | +pub fn commit(repo: &Path, file: &str, contents: &str, message: &str, who: (&str, &str)) -> String { |
| | 276 | + let (name, email) = who; |
| | 277 | + let path = repo.join(file); |
| | 278 | + if let Some(parent) = path.parent() { |
| | 279 | + fs::create_dir_all(parent).expect("create dir"); |
| | 280 | + } |
| | 281 | + fs::write(&path, contents).expect("write file"); |
| | 282 | + git_text(repo, &["add", file]); |
| | 283 | + git_text_env( |
| | 284 | + repo, |
| | 285 | + &["-c", "commit.gpgsign=false", "commit", "-q", "-m", message], |
| | 286 | + &[ |
| | 287 | + ("GIT_AUTHOR_NAME", name), |
| | 288 | + ("GIT_AUTHOR_EMAIL", email), |
| | 289 | + ("GIT_COMMITTER_NAME", name), |
| | 290 | + ("GIT_COMMITTER_EMAIL", email), |
| | 291 | + ], |
| | 292 | + ); |
| | 293 | + git_text(repo, &["rev-parse", "HEAD"]) |
| | 294 | +} |
| | 295 | + |
| | 296 | +pub fn clone(url: &str, into: &Path) -> PathBuf { |
| | 297 | + let parent = into.parent().expect("clone target has a parent"); |
| | 298 | + git_text(parent, &["clone", "-q", url, path_str(into)]); |
| | 299 | + into.to_path_buf() |
| | 300 | +} |
| | 301 | + |
| 163 | pub async fn create_token(http: &Http, session: &str, name: &str) -> String { | 302 | pub async fn create_token(http: &Http, session: &str, name: &str) -> String { |
| 164 | let page = http.get_cookie("/settings/keys", session).await; | 303 | let page = http.get_cookie("/settings/keys", session).await; |
| 165 | assert_eq!(page.status, 200, "GET /settings/keys"); | 304 | assert_eq!(page.status, 200, "GET /settings/keys"); |
| @@ -211,7 +350,7 @@ pub async fn create_repo(http: &Http, session: &str, name: &str, visibility: &st |
| 211 | | 350 | |
| 212 | pub const PW: &str = "tahinli-password-123"; | 351 | pub const PW: &str = "tahinli-password-123"; |
| 213 | | 352 | |
| 214 | -pub fn admin(config: &Path, args: &[&str]) { | 353 | +pub fn admin(config: &Path, args: &[&str]) -> Output { |
| 215 | let out = Command::new(bin()) | 354 | let out = Command::new(bin()) |
| 216 | .arg("--config") | 355 | .arg("--config") |
| 217 | .arg(config) | 356 | .arg(config) |
| @@ -225,6 +364,7 @@ pub fn admin(config: &Path, args: &[&str]) { |
| 225 | "admin {args:?} failed:\n{}", | 364 | "admin {args:?} failed:\n{}", |
| 226 | describe(&out) | 365 | describe(&out) |
| 227 | ); | 366 | ); |
| | 367 | + out |
| 228 | } | 368 | } |
| 229 | | 369 | |
| 230 | pub fn init_bare(data_dir: &Path, repo_id: &str) { | 370 | pub fn init_bare(data_dir: &Path, repo_id: &str) { |
| @@ -257,32 +397,21 @@ pub async fn next_changed(res: &mut reqwest::Response, what: &str) { |
| 257 | assert!(text.contains("event: changed"), "{what}: {text}"); | 397 | assert!(text.contains("event: changed"), "{what}: {text}"); |
| 258 | } | 398 | } |
| 259 | | 399 | |
| 260 | -pub fn run_admin(config: &Path, username: &str, extra: &[&str], password: &str) { | 400 | +pub const TAHINLI_CMD: &[&str] = &["create-user", "tahinli", "--admin"]; |
| 261 | - let out = Command::new(bin()) | 401 | +pub const BOB_CMD: &[&str] = &["create-user", "bob"]; |
| 262 | - .arg("--config") | | |
| 263 | - .arg(config) | | |
| 264 | - .args(["admin", "create-user", username]) | | |
| 265 | - .args(extra) | | |
| 266 | - .env("FORGE_PASSWORD", password) | | |
| 267 | - .output() | | |
| 268 | - .expect("run admin create-user"); | | |
| 269 | - assert!( | | |
| 270 | - out.status.success(), | | |
| 271 | - "create-user {username} failed:\n{}", | | |
| 272 | - describe(&out) | | |
| 273 | - ); | | |
| 274 | -} | | |
| 275 | | 402 | |
| 276 | -pub async fn boot_admin(prefix: &str, password: &str) -> (TempDir, Server, Ports) { | 403 | +pub fn provision(dir: &Path, extra: &str, admin_cmds: &[&[&str]]) -> (PathBuf, Ports) { |
| 277 | - let root = tempfile::Builder::new() | | |
| 278 | - .prefix(prefix) | | |
| 279 | - .tempdir_in("/tmp") | | |
| 280 | - .expect("temp dir"); | | |
| 281 | let ports = pick_ports(); | 404 | let ports = pick_ports(); |
| 282 | - let config = write_config(root.path(), ports); | 405 | + let config = write_config_with(dir, ports, extra); |
| 283 | - run_admin(&config, "tahinli", &["--admin"], password); | 406 | + for args in admin_cmds { |
| 284 | - let (server, ports) = launch(root.path(), ports).await; | 407 | + admin(&config, args); |
| 285 | - (root, server, ports) | 408 | + } |
| | 409 | + (config, ports) |
| | 410 | +} |
| | 411 | + |
| | 412 | +pub async fn boot_forge(dir: &Path, extra: &str, admin_cmds: &[&[&str]]) -> (Server, Ports) { |
| | 413 | + let (_, ports) = provision(dir, extra, admin_cmds); |
| | 414 | + launch_with(dir, ports, extra).await |
| 286 | } | 415 | } |
| 287 | | 416 | |
| 288 | pub async fn launch(dir: &Path, ports: Ports) -> (Server, Ports) { | 417 | pub async fn launch(dir: &Path, ports: Ports) -> (Server, Ports) { |
| @@ -1,35 +1,13 @@ |
| 1 | -use std::process::Command; | | |
| 2 | use std::time::Duration; | 1 | use std::time::Duration; |
| 3 | | 2 | |
| 4 | -use crate::common::{bin, describe, launch, pick_ports, write_config}; | 3 | +use crate::common::boot_forge; |
| 5 | use reqwest::header::ACCEPT_LANGUAGE; | 4 | use reqwest::header::ACCEPT_LANGUAGE; |
| 6 | | 5 | |
| 7 | -const PW: &str = "tahinli-password-123"; | | |
| 8 | - | | |
| 9 | -fn admin(config: &std::path::Path, args: &[&str]) { | | |
| 10 | - let out = Command::new(bin()) | | |
| 11 | - .arg("--config") | | |
| 12 | - .arg(config) | | |
| 13 | - .arg("admin") | | |
| 14 | - .args(args) | | |
| 15 | - .env("FORGE_PASSWORD", PW) | | |
| 16 | - .output() | | |
| 17 | - .expect("run admin command"); | | |
| 18 | - assert!( | | |
| 19 | - out.status.success(), | | |
| 20 | - "admin {args:?} failed:\n{}", | | |
| 21 | - describe(&out) | | |
| 22 | - ); | | |
| 23 | -} | | |
| 24 | - | | |
| 25 | #[tokio::test] | 6 | #[tokio::test] |
| 26 | async fn snippets_page_follows_the_browser_language() { | 7 | async fn snippets_page_follows_the_browser_language() { |
| 27 | let root = tempfile::tempdir().expect("temp dir"); | 8 | let root = tempfile::tempdir().expect("temp dir"); |
| 28 | let dir = root.path().to_path_buf(); | 9 | let dir = root.path().to_path_buf(); |
| 29 | - let ports = pick_ports(); | 10 | + let (_server, ports) = boot_forge(&dir, "", &[&["create-user", "tahinli"]]).await; |
| 30 | - let config = write_config(&dir, ports); | | |
| 31 | - admin(&config, &["create-user", "tahinli"]); | | |
| 32 | - let (_server, ports) = launch(&dir, ports).await; | | |
| 33 | | 11 | |
| 34 | let client = reqwest::Client::builder() | 12 | let client = reqwest::Client::builder() |
| 35 | .timeout(Duration::from_secs(60)) | 13 | .timeout(Duration::from_secs(60)) |
| @@ -1,34 +1,7 @@ |
| 1 | use crate::common::{ | 1 | use crate::common::{ |
| 2 | - Http, input_value, launch, login, pick_ports, run_admin, tool_on_path, write_config, | 2 | + BOB_CMD, Http, PW, TAHINLI_CMD, boot_forge, create_repo, csrf_for, login, tool_on_path, |
| 3 | }; | 3 | }; |
| 4 | | 4 | |
| 5 | -const TAHINLI_PW: &str = "tahinli-password-123"; | | |
| 6 | -const BOB_PW: &str = "bob-password-4567"; | | |
| 7 | - | | |
| 8 | -async fn create_repo(http: &Http, session: &str, name: &str) { | | |
| 9 | - let page = http.get("/new", Some(session)).await; | | |
| 10 | - assert_eq!(page.status, 200, "GET /new"); | | |
| 11 | - let csrf = input_value(&page.body, "csrf"); | | |
| 12 | - let res = http | | |
| 13 | - .post_form( | | |
| 14 | - "/new", | | |
| 15 | - &[ | | |
| 16 | - ("csrf", &csrf), | | |
| 17 | - ("name", name), | | |
| 18 | - ("description", ""), | | |
| 19 | - ("visibility", "public"), | | |
| 20 | - ("default_branch", "main"), | | |
| 21 | - ], | | |
| 22 | - Some(session), | | |
| 23 | - ) | | |
| 24 | - .await; | | |
| 25 | - assert_eq!(res.status, 303, "create repo {name}: {}", res.body); | | |
| 26 | - assert_eq!( | | |
| 27 | - res.location().as_deref(), | | |
| 28 | - Some(format!("/tahinli/{name}").as_str()) | | |
| 29 | - ); | | |
| 30 | -} | | |
| 31 | - | | |
| 32 | fn anchored_id(location: Option<&str>) -> String { | 5 | fn anchored_id(location: Option<&str>) -> String { |
| 33 | location | 6 | location |
| 34 | .and_then(|l| l.rsplit_once("#comment-")) | 7 | .and_then(|l| l.rsplit_once("#comment-")) |
| @@ -45,17 +18,11 @@ async fn discussions_create_reply_answer_lock_and_toggle() { |
| 45 | | 18 | |
| 46 | let root = tempfile::tempdir().expect("temp dir"); | 19 | let root = tempfile::tempdir().expect("temp dir"); |
| 47 | let dir = root.path().to_path_buf(); | 20 | let dir = root.path().to_path_buf(); |
| 48 | - let ports = pick_ports(); | 21 | + let (_server, ports) = boot_forge(&dir, "", &[TAHINLI_CMD, BOB_CMD]).await; |
| 49 | - let config = write_config(&dir, ports); | | |
| 50 | - | | |
| 51 | - run_admin(&config, "tahinli", &["--admin"], TAHINLI_PW); | | |
| 52 | - run_admin(&config, "bob", &[], BOB_PW); | | |
| 53 | - | | |
| 54 | - let (_server, ports) = launch(&dir, ports).await; | | |
| 55 | let http = Http::new(ports.http); | 22 | let http = Http::new(ports.http); |
| 56 | - let tahinli = login(&http, "tahinli", TAHINLI_PW).await; | 23 | + let tahinli = login(&http, "tahinli", PW).await; |
| 57 | - let bob = login(&http, "bob", BOB_PW).await; | 24 | + let bob = login(&http, "bob", PW).await; |
| 58 | - create_repo(&http, &tahinli, "pub").await; | 25 | + create_repo(&http, &tahinli, "pub", "public").await; |
| 59 | | 26 | |
| 60 | let repo_page = http.get("/tahinli/pub", Some(tahinli.as_str())).await; | 27 | let repo_page = http.get("/tahinli/pub", Some(tahinli.as_str())).await; |
| 61 | assert_eq!(repo_page.status, 200); | 28 | assert_eq!(repo_page.status, 200); |
| @@ -71,11 +38,7 @@ async fn discussions_create_reply_answer_lock_and_toggle() { |
| 71 | "list while off" | 38 | "list while off" |
| 72 | ); | 39 | ); |
| 73 | | 40 | |
| 74 | - let settings = http | 41 | + let csrf = csrf_for(&http, "/tahinli/pub/settings", &tahinli).await; |
| 75 | - .get("/tahinli/pub/settings", Some(tahinli.as_str())) | | |
| 76 | - .await; | | |
| 77 | - assert_eq!(settings.status, 200, "GET settings"); | | |
| 78 | - let csrf = input_value(&settings.body, "csrf"); | | |
| 79 | let res = http | 42 | let res = http |
| 80 | .post_form( | 43 | .post_form( |
| 81 | "/tahinli/pub/settings/discussions", | 44 | "/tahinli/pub/settings/discussions", |
| @@ -90,11 +53,7 @@ async fn discussions_create_reply_answer_lock_and_toggle() { |
| 90 | "the Discussions tab is missing after turning it on" | 53 | "the Discussions tab is missing after turning it on" |
| 91 | ); | 54 | ); |
| 92 | | 55 | |
| 93 | - let form = http | 56 | + let csrf = csrf_for(&http, "/tahinli/pub/discussions/new", &tahinli).await; |
| 94 | - .get("/tahinli/pub/discussions/new", Some(tahinli.as_str())) | | |
| 95 | - .await; | | |
| 96 | - assert_eq!(form.status, 200, "GET new discussion"); | | |
| 97 | - let csrf = input_value(&form.body, "csrf"); | | |
| 98 | let res = http | 57 | let res = http |
| 99 | .post_form( | 58 | .post_form( |
| 100 | "/tahinli/pub/discussions/new", | 59 | "/tahinli/pub/discussions/new", |
| @@ -114,9 +73,7 @@ async fn discussions_create_reply_answer_lock_and_toggle() { |
| 114 | ); | 73 | ); |
| 115 | let discussion = "/tahinli/pub/discussions/1"; | 74 | let discussion = "/tahinli/pub/discussions/1"; |
| 116 | | 75 | |
| 117 | - let page = http.get(discussion, Some(bob.as_str())).await; | 76 | + let csrf_bob = csrf_for(&http, discussion, &bob).await; |
| 118 | - assert_eq!(page.status, 200, "GET discussion as bob"); | | |
| 119 | - let csrf_bob = input_value(&page.body, "csrf"); | | |
| 120 | let res = http | 77 | let res = http |
| 121 | .post_form( | 78 | .post_form( |
| 122 | &format!("{discussion}/comments"), | 79 | &format!("{discussion}/comments"), |
| @@ -159,8 +116,7 @@ async fn discussions_create_reply_answer_lock_and_toggle() { |
| 159 | res.body | 116 | res.body |
| 160 | ); | 117 | ); |
| 161 | | 118 | |
| 162 | - let page = http.get(discussion, Some(tahinli.as_str())).await; | 119 | + let csrf_tahinli = csrf_for(&http, discussion, &tahinli).await; |
| 163 | - let csrf_tahinli = input_value(&page.body, "csrf"); | | |
| 164 | let res = http | 120 | let res = http |
| 165 | .post_form( | 121 | .post_form( |
| 166 | &format!("{discussion}/answer"), | 122 | &format!("{discussion}/answer"), |
| @@ -179,8 +135,7 @@ async fn discussions_create_reply_answer_lock_and_toggle() { |
| 179 | "the answered badge is missing after marking an answer" | 135 | "the answered badge is missing after marking an answer" |
| 180 | ); | 136 | ); |
| 181 | | 137 | |
| 182 | - let page = http.get(discussion, Some(tahinli.as_str())).await; | 138 | + let csrf_tahinli = csrf_for(&http, discussion, &tahinli).await; |
| 183 | - let csrf_tahinli = input_value(&page.body, "csrf"); | | |
| 184 | let res = http | 139 | let res = http |
| 185 | .post_form( | 140 | .post_form( |
| 186 | &format!("{discussion}/lock"), | 141 | &format!("{discussion}/lock"), |
| @@ -206,10 +161,7 @@ async fn discussions_create_reply_answer_lock_and_toggle() { |
| 206 | .await; | 161 | .await; |
| 207 | assert_eq!(res.status, 403, "bob locks a discussion"); | 162 | assert_eq!(res.status, 403, "bob locks a discussion"); |
| 208 | | 163 | |
| 209 | - let settings = http | 164 | + let csrf = csrf_for(&http, "/tahinli/pub/settings", &tahinli).await; |
| 210 | - .get("/tahinli/pub/settings", Some(tahinli.as_str())) | | |
| 211 | - .await; | | |
| 212 | - let csrf = input_value(&settings.body, "csrf"); | | |
| 213 | let res = http | 165 | let res = http |
| 214 | .post_form( | 166 | .post_form( |
| 215 | "/tahinli/pub/settings/discussions", | 167 | "/tahinli/pub/settings/discussions", |
| @@ -1,6 +1,6 @@ |
| 1 | use crate::common::{ | 1 | use crate::common::{ |
| 2 | - Http, create_repo, create_token, describe, git, input_value, launch, login, pick_ports, | 2 | + BOB_CMD, Http, PW, TAHINLI_CMD, boot_forge, commit_file, create_repo, create_token, csrf_for, |
| 3 | - run_admin, tool_on_path, write_config, | 3 | + describe, git, git_env, head_sha, login, ok, path_str, set_identity, tool_on_path, |
| 4 | }; | 4 | }; |
| 5 | use std::fs; | 5 | use std::fs; |
| 6 | use std::path::{Path, PathBuf}; | 6 | use std::path::{Path, PathBuf}; |
| @@ -8,13 +8,6 @@ use std::process::{Command, Output}; |
| 8 | | 8 | |
| 9 | use reqwest::header::WWW_AUTHENTICATE; | 9 | use reqwest::header::WWW_AUTHENTICATE; |
| 10 | | 10 | |
| 11 | -const TAHINLI_PW: &str = "tahinli-password-123"; | | |
| 12 | -const BOB_PW: &str = "bob-password-4567"; | | |
| 13 | - | | |
| 14 | -fn ok(out: &Output, what: &str) { | | |
| 15 | - assert!(out.status.success(), "{what} failed:\n{}", describe(out)); | | |
| 16 | -} | | |
| 17 | - | | |
| 18 | fn rejected(out: &Output, what: &str) -> String { | 11 | fn rejected(out: &Output, what: &str) -> String { |
| 19 | assert!( | 12 | assert!( |
| 20 | !out.status.success(), | 13 | !out.status.success(), |
| @@ -24,10 +17,6 @@ fn rejected(out: &Output, what: &str) -> String { |
| 24 | describe(out) | 17 | describe(out) |
| 25 | } | 18 | } |
| 26 | | 19 | |
| 27 | -fn path_str(path: &Path) -> &str { | | |
| 28 | - path.to_str().expect("utf-8 path") | | |
| 29 | -} | | |
| 30 | - | | |
| 31 | fn ssh_opts(key: &Path, ssh_port: u16) -> Vec<String> { | 20 | fn ssh_opts(key: &Path, ssh_port: u16) -> Vec<String> { |
| 32 | [ | 21 | [ |
| 33 | "-i", | 22 | "-i", |
| @@ -63,37 +52,6 @@ fn gen_key(path: &Path) { |
| 63 | ok(&out, "ssh-keygen"); | 52 | ok(&out, "ssh-keygen"); |
| 64 | } | 53 | } |
| 65 | | 54 | |
| 66 | -fn set_identity(repo: &Path) { | | |
| 67 | - ok( | | |
| 68 | - &git(repo, &["config", "user.name", "tahinli"], &[]), | | |
| 69 | - "set user.name", | | |
| 70 | - ); | | |
| 71 | - ok( | | |
| 72 | - &git(repo, &["config", "user.email", "tahinli@example.com"], &[]), | | |
| 73 | - "set user.email", | | |
| 74 | - ); | | |
| 75 | -} | | |
| 76 | - | | |
| 77 | -fn commit_file(repo: &Path, name: &str, content: &str, message: &str) { | | |
| 78 | - fs::write(repo.join(name), content).expect("write file"); | | |
| 79 | - set_identity(repo); | | |
| 80 | - ok(&git(repo, &["add", name], &[]), "git add"); | | |
| 81 | - ok( | | |
| 82 | - &git( | | |
| 83 | - repo, | | |
| 84 | - &["-c", "commit.gpgsign=false", "commit", "-q", "-m", message], | | |
| 85 | - &[], | | |
| 86 | - ), | | |
| 87 | - "git commit", | | |
| 88 | - ); | | |
| 89 | -} | | |
| 90 | - | | |
| 91 | -fn head_sha(repo: &Path) -> String { | | |
| 92 | - let out = git(repo, &["rev-parse", "HEAD"], &[]); | | |
| 93 | - ok(&out, "rev-parse HEAD"); | | |
| 94 | - String::from_utf8_lossy(&out.stdout).trim().to_owned() | | |
| 95 | -} | | |
| 96 | - | | |
| 97 | fn find_file(dir: &Path, name: &str) -> bool { | 55 | fn find_file(dir: &Path, name: &str) -> bool { |
| 98 | std::fs::read_dir(dir).is_ok_and(|entries| { | 56 | std::fs::read_dir(dir).is_ok_and(|entries| { |
| 99 | entries.flatten().any(|entry| { | 57 | entries.flatten().any(|entry| { |
| @@ -107,9 +65,7 @@ fn read(path: PathBuf) -> String { |
| 107 | } | 65 | } |
| 108 | | 66 | |
| 109 | async fn add_key(http: &Http, session: &str, public_key: &str) { | 67 | async fn add_key(http: &Http, session: &str, public_key: &str) { |
| 110 | - let page = http.get_cookie("/settings/keys", session).await; | 68 | + let csrf = csrf_for(http, "/settings/keys", session).await; |
| 111 | - assert_eq!(page.status, 200, "GET /settings/keys"); | | |
| 112 | - let csrf = input_value(&page.body, "csrf"); | | |
| 113 | let res = http | 69 | let res = http |
| 114 | .post_form( | 70 | .post_form( |
| 115 | "/settings/keys", | 71 | "/settings/keys", |
| @@ -135,22 +91,13 @@ async fn git_end_to_end() { |
| 135 | } | 91 | } |
| 136 | } | 92 | } |
| 137 | | 93 | |
| 138 | - let root = tempfile::Builder::new() | 94 | + let root = crate::common::temp_dir("fe2e"); |
| 139 | - .prefix("fe2e") | | |
| 140 | - .tempdir_in("/tmp") | | |
| 141 | - .expect("temp dir"); | | |
| 142 | let dir = root.path().to_path_buf(); | 95 | let dir = root.path().to_path_buf(); |
| 143 | - let ports = pick_ports(); | 96 | + let (_server, ports) = boot_forge(&dir, "", &[TAHINLI_CMD, BOB_CMD]).await; |
| 144 | - let config = write_config(&dir, ports); | | |
| 145 | - | | |
| 146 | - run_admin(&config, "tahinli", &["--admin"], TAHINLI_PW); | | |
| 147 | - run_admin(&config, "bob", &[], BOB_PW); | | |
| 148 | - | | |
| 149 | - let (_server, ports) = launch(&dir, ports).await; | | |
| 150 | let http = Http::new(ports.http); | 97 | let http = Http::new(ports.http); |
| 151 | let (http_port, ssh_port) = (ports.http, ports.ssh); | 98 | let (http_port, ssh_port) = (ports.http, ports.ssh); |
| 152 | | 99 | |
| 153 | - let tahinli = login(&http, "tahinli", TAHINLI_PW).await; | 100 | + let tahinli = login(&http, "tahinli", PW).await; |
| 154 | let tahinli_token = create_token(&http, &tahinli, "e2e-token").await; | 101 | let tahinli_token = create_token(&http, &tahinli, "e2e-token").await; |
| 155 | | 102 | |
| 156 | let key = dir.join("id"); | 103 | let key = dir.join("id"); |
| @@ -164,19 +111,19 @@ async fn git_end_to_end() { |
| 164 | let pub_url = format!("http://tahinli:{tahinli_token}@127.0.0.1:{http_port}/tahinli/pub.git"); | 111 | let pub_url = format!("http://tahinli:{tahinli_token}@127.0.0.1:{http_port}/tahinli/pub.git"); |
| 165 | let pub_work = dir.join("pub-work"); | 112 | let pub_work = dir.join("pub-work"); |
| 166 | ok( | 113 | ok( |
| 167 | - &git(&dir, &["clone", &pub_url, path_str(&pub_work)], &[]), | 114 | + &git(&dir, &["clone", &pub_url, path_str(&pub_work)]), |
| 168 | "https clone of empty public repo", | 115 | "https clone of empty public repo", |
| 169 | ); | 116 | ); |
| 170 | commit_file(&pub_work, "hello.txt", "hello over https\n", "https commit"); | 117 | commit_file(&pub_work, "hello.txt", "hello over https\n", "https commit"); |
| 171 | ok( | 118 | ok( |
| 172 | - &git(&pub_work, &["push", "origin", "HEAD:main"], &[]), | 119 | + &git(&pub_work, &["push", "origin", "HEAD:main"]), |
| 173 | "https push", | 120 | "https push", |
| 174 | ); | 121 | ); |
| 175 | let pushed_main = head_sha(&pub_work); | 122 | let pushed_main = head_sha(&pub_work); |
| 176 | | 123 | |
| 177 | let pub_verify = dir.join("pub-verify"); | 124 | let pub_verify = dir.join("pub-verify"); |
| 178 | ok( | 125 | ok( |
| 179 | - &git(&dir, &["clone", &pub_url, path_str(&pub_verify)], &[]), | 126 | + &git(&dir, &["clone", &pub_url, path_str(&pub_verify)]), |
| 180 | "https fresh clone", | 127 | "https fresh clone", |
| 181 | ); | 128 | ); |
| 182 | assert_eq!(read(pub_verify.join("hello.txt")), "hello over https\n"); | 129 | assert_eq!(read(pub_verify.join("hello.txt")), "hello over https\n"); |
| @@ -184,7 +131,7 @@ async fn git_end_to_end() { |
| 184 | let anon_url = format!("http://127.0.0.1:{http_port}/tahinli/pub.git"); | 131 | let anon_url = format!("http://127.0.0.1:{http_port}/tahinli/pub.git"); |
| 185 | let pub_anon = dir.join("pub-anon"); | 132 | let pub_anon = dir.join("pub-anon"); |
| 186 | ok( | 133 | ok( |
| 187 | - &git(&dir, &["clone", &anon_url, path_str(&pub_anon)], &[]), | 134 | + &git(&dir, &["clone", &anon_url, path_str(&pub_anon)]), |
| 188 | "anonymous clone of public repo", | 135 | "anonymous clone of public repo", |
| 189 | ); | 136 | ); |
| 190 | assert_eq!(read(pub_anon.join("hello.txt")), "hello over https\n"); | 137 | assert_eq!(read(pub_anon.join("hello.txt")), "hello over https\n"); |
| @@ -193,7 +140,6 @@ async fn git_end_to_end() { |
| 193 | &git( | 140 | &git( |
| 194 | &dir, | 141 | &dir, |
| 195 | &["clone", "--depth", "1", &anon_url, path_str(&pub_shallow)], | 142 | &["clone", "--depth", "1", &anon_url, path_str(&pub_shallow)], |
| 196 | - &[], | | |
| 197 | ), | 143 | ), |
| 198 | "anonymous shallow clone", | 144 | "anonymous shallow clone", |
| 199 | ); | 145 | ); |
| @@ -203,7 +149,7 @@ async fn git_end_to_end() { |
| 203 | let priv_ssh_url = format!("ssh://git@127.0.0.1:{ssh_port}/tahinli/priv.git"); | 149 | let priv_ssh_url = format!("ssh://git@127.0.0.1:{ssh_port}/tahinli/priv.git"); |
| 204 | let priv_work = dir.join("priv-work"); | 150 | let priv_work = dir.join("priv-work"); |
| 205 | ok( | 151 | ok( |
| 206 | - &git( | 152 | + &git_env( |
| 207 | &dir, | 153 | &dir, |
| 208 | &["clone", &priv_ssh_url, path_str(&priv_work)], | 154 | &["clone", &priv_ssh_url, path_str(&priv_work)], |
| 209 | &ssh_env, | 155 | &ssh_env, |
| @@ -212,12 +158,12 @@ async fn git_end_to_end() { |
| 212 | ); | 158 | ); |
| 213 | commit_file(&priv_work, "secret.txt", "over ssh\n", "ssh commit"); | 159 | commit_file(&priv_work, "secret.txt", "over ssh\n", "ssh commit"); |
| 214 | ok( | 160 | ok( |
| 215 | - &git(&priv_work, &["push", "origin", "HEAD:main"], &ssh_env), | 161 | + &git_env(&priv_work, &["push", "origin", "HEAD:main"], &ssh_env), |
| 216 | "ssh push", | 162 | "ssh push", |
| 217 | ); | 163 | ); |
| 218 | let priv_verify = dir.join("priv-verify"); | 164 | let priv_verify = dir.join("priv-verify"); |
| 219 | ok( | 165 | ok( |
| 220 | - &git( | 166 | + &git_env( |
| 221 | &dir, | 167 | &dir, |
| 222 | &["clone", &priv_ssh_url, path_str(&priv_verify)], | 168 | &["clone", &priv_ssh_url, path_str(&priv_verify)], |
| 223 | &ssh_env, | 169 | &ssh_env, |
| @@ -228,7 +174,7 @@ async fn git_end_to_end() { |
| 228 | | 174 | |
| 229 | let priv_https_anon = format!("http://127.0.0.1:{http_port}/tahinli/priv.git"); | 175 | let priv_https_anon = format!("http://127.0.0.1:{http_port}/tahinli/priv.git"); |
| 230 | rejected( | 176 | rejected( |
| 231 | - &git(&dir, &["clone", &priv_https_anon, "anon-priv"], &[]), | 177 | + &git(&dir, &["clone", &priv_https_anon, "anon-priv"]), |
| 232 | "anonymous clone of private repo", | 178 | "anonymous clone of private repo", |
| 233 | ); | 179 | ); |
| 234 | let refs_path = "/tahinli/priv.git/info/refs?service=git-upload-pack"; | 180 | let refs_path = "/tahinli/priv.git/info/refs?service=git-upload-pack"; |
| @@ -239,7 +185,7 @@ async fn git_end_to_end() { |
| 239 | "401 must carry WWW-Authenticate" | 185 | "401 must carry WWW-Authenticate" |
| 240 | ); | 186 | ); |
| 241 | | 187 | |
| 242 | - let bob = login(&http, "bob", BOB_PW).await; | 188 | + let bob = login(&http, "bob", PW).await; |
| 243 | let bob_page = http.get_cookie("/tahinli/priv", &bob).await; | 189 | let bob_page = http.get_cookie("/tahinli/priv", &bob).await; |
| 244 | assert_eq!(bob_page.status, 404, "bob's web view of tahinli/priv"); | 190 | assert_eq!(bob_page.status, 404, "bob's web view of tahinli/priv"); |
| 245 | let bob_token = create_token(&http, &bob, "bob-token").await; | 191 | let bob_token = create_token(&http, &bob, "bob-token").await; |
| @@ -253,11 +199,11 @@ async fn git_end_to_end() { |
| 253 | let wrong_url = | 199 | let wrong_url = |
| 254 | format!("http://tahinli:forge_notarealtoken@127.0.0.1:{http_port}/tahinli/priv.git"); | 200 | format!("http://tahinli:forge_notarealtoken@127.0.0.1:{http_port}/tahinli/priv.git"); |
| 255 | rejected( | 201 | rejected( |
| 256 | - &git(&dir, &["clone", &wrong_url, "wrong-token-clone"], &[]), | 202 | + &git(&dir, &["clone", &wrong_url, "wrong-token-clone"]), |
| 257 | "clone with wrong token", | 203 | "clone with wrong token", |
| 258 | ); | 204 | ); |
| 259 | | 205 | |
| 260 | - let delete = git(&pub_verify, &["push", "origin", "--delete", "main"], &[]); | 206 | + let delete = git(&pub_verify, &["push", "origin", "--delete", "main"]); |
| 261 | let text = rejected(&delete, "deleting main"); | 207 | let text = rejected(&delete, "deleting main"); |
| 262 | assert!( | 208 | assert!( |
| 263 | text.contains("deleting protected branch 'main' is not allowed"), | 209 | text.contains("deleting protected branch 'main' is not allowed"), |
| @@ -277,18 +223,17 @@ async fn git_end_to_end() { |
| 277 | "-m", | 223 | "-m", |
| 278 | "rewritten", | 224 | "rewritten", |
| 279 | ], | 225 | ], |
| 280 | - &[], | | |
| 281 | ), | 226 | ), |
| 282 | "amend commit", | 227 | "amend commit", |
| 283 | ); | 228 | ); |
| 284 | - let force = git(&pub_verify, &["push", "-f", "origin", "HEAD:main"], &[]); | 229 | + let force = git(&pub_verify, &["push", "-f", "origin", "HEAD:main"]); |
| 285 | let text = rejected(&force, "force-push to main"); | 230 | let text = rejected(&force, "force-push to main"); |
| 286 | assert!( | 231 | assert!( |
| 287 | text.contains("force-push to protected branch 'main' is not allowed"), | 232 | text.contains("force-push to protected branch 'main' is not allowed"), |
| 288 | "force-push message: {text}" | 233 | "force-push message: {text}" |
| 289 | ); | 234 | ); |
| 290 | | 235 | |
| 291 | - let ls = git(&dir, &["ls-remote", &pub_url, "refs/heads/main"], &[]); | 236 | + let ls = git(&dir, &["ls-remote", &pub_url, "refs/heads/main"]); |
| 292 | ok(&ls, "ls-remote main"); | 237 | ok(&ls, "ls-remote main"); |
| 293 | let remote_main = String::from_utf8_lossy(&ls.stdout); | 238 | let remote_main = String::from_utf8_lossy(&ls.stdout); |
| 294 | assert!( | 239 | assert!( |
| @@ -297,11 +242,7 @@ async fn git_end_to_end() { |
| 297 | ); | 242 | ); |
| 298 | | 243 | |
| 299 | ok( | 244 | ok( |
| 300 | - &git( | 245 | + &git(&pub_verify, &["push", "origin", "HEAD:refs/heads/scratch"]), |
| 301 | - &pub_verify, | | |
| 302 | - &["push", "origin", "HEAD:refs/heads/scratch"], | | |
| 303 | - &[], | | |
| 304 | - ), | | |
| 305 | "push scratch", | 246 | "push scratch", |
| 306 | ); | 247 | ); |
| 307 | let overwritten = head_sha(&pub_verify); | 248 | let overwritten = head_sha(&pub_verify); |
| @@ -323,12 +264,11 @@ async fn git_end_to_end() { |
| 323 | "-m", | 264 | "-m", |
| 324 | "rewritten again", | 265 | "rewritten again", |
| 325 | ], | 266 | ], |
| 326 | - &[], | | |
| 327 | ), | 267 | ), |
| 328 | "amend again", | 268 | "amend again", |
| 329 | ); | 269 | ); |
| 330 | ok( | 270 | ok( |
| 331 | - &git(&pub_verify, &["push", "-f", "origin", "HEAD:scratch"], &[]), | 271 | + &git(&pub_verify, &["push", "-f", "origin", "HEAD:scratch"]), |
| 332 | "force-push scratch", | 272 | "force-push scratch", |
| 333 | ); | 273 | ); |
| 334 | assert_eq!( | 274 | assert_eq!( |
| @@ -346,7 +286,7 @@ async fn git_end_to_end() { |
| 346 | let rogue_cmd = ssh_command(&rogue, ssh_port); | 286 | let rogue_cmd = ssh_command(&rogue, ssh_port); |
| 347 | let rogue_env = [("GIT_SSH_COMMAND", rogue_cmd.as_str())]; | 287 | let rogue_env = [("GIT_SSH_COMMAND", rogue_cmd.as_str())]; |
| 348 | let text = rejected( | 288 | let text = rejected( |
| 349 | - &git(&dir, &["clone", &priv_ssh_url, "rogue-clone"], &rogue_env), | 289 | + &git_env(&dir, &["clone", &priv_ssh_url, "rogue-clone"], &rogue_env), |
| 350 | "clone with unregistered key", | 290 | "clone with unregistered key", |
| 351 | ); | 291 | ); |
| 352 | assert!( | 292 | assert!( |
| @@ -390,22 +330,14 @@ async fn suspended_user_token_is_refused_over_http_git() { |
| 390 | eprintln!("SKIP git_e2e: `git` was not found on PATH"); | 330 | eprintln!("SKIP git_e2e: `git` was not found on PATH"); |
| 391 | return; | 331 | return; |
| 392 | } | 332 | } |
| 393 | - let root = tempfile::Builder::new() | 333 | + let root = crate::common::temp_dir("fe2s"); |
| 394 | - .prefix("fe2s") | | |
| 395 | - .tempdir_in("/tmp") | | |
| 396 | - .expect("temp dir"); | | |
| 397 | let dir = root.path().to_path_buf(); | 334 | let dir = root.path().to_path_buf(); |
| 398 | - let ports = pick_ports(); | 335 | + let (_server, ports) = boot_forge(&dir, "", &[TAHINLI_CMD, BOB_CMD]).await; |
| 399 | - let config = write_config(&dir, ports); | | |
| 400 | - run_admin(&config, "tahinli", &["--admin"], TAHINLI_PW); | | |
| 401 | - run_admin(&config, "bob", &[], BOB_PW); | | |
| 402 | - let (_server, ports) = launch(&dir, ports).await; | | |
| 403 | let http = Http::new(ports.http); | 336 | let http = Http::new(ports.http); |
| 404 | | 337 | |
| 405 | - let bob = login(&http, "bob", BOB_PW).await; | 338 | + let bob = login(&http, "bob", PW).await; |
| 406 | let bob_token = create_token(&http, &bob, "suspend-token").await; | 339 | let bob_token = create_token(&http, &bob, "suspend-token").await; |
| 407 | - let page = http.get_cookie("/new", &bob).await; | 340 | + let csrf = csrf_for(&http, "/new", &bob).await; |
| 408 | - let csrf = input_value(&page.body, "csrf"); | | |
| 409 | let created = http | 341 | let created = http |
| 410 | .post_form( | 342 | .post_form( |
| 411 | "/new", | 343 | "/new", |
| @@ -426,16 +358,16 @@ async fn suspended_user_token_is_refused_over_http_git() { |
| 426 | ); | 358 | ); |
| 427 | let work = dir.join("work"); | 359 | let work = dir.join("work"); |
| 428 | ok( | 360 | ok( |
| 429 | - &git(&dir, &["clone", &url, path_str(&work)], &[]), | 361 | + &git(&dir, &["clone", &url, path_str(&work)]), |
| 430 | "clone before suspension", | 362 | "clone before suspension", |
| 431 | ); | 363 | ); |
| 432 | commit_file(&work, "a.txt", "one\n", "first"); | 364 | commit_file(&work, "a.txt", "one\n", "first"); |
| 433 | ok( | 365 | ok( |
| 434 | - &git(&work, &["push", "origin", "HEAD:main"], &[]), | 366 | + &git(&work, &["push", "origin", "HEAD:main"]), |
| 435 | "push before suspension", | 367 | "push before suspension", |
| 436 | ); | 368 | ); |
| 437 | | 369 | |
| 438 | - let tahinli = login(&http, "tahinli", TAHINLI_PW).await; | 370 | + let tahinli = login(&http, "tahinli", PW).await; |
| 439 | let list = http.get_cookie("/admin/users", &tahinli).await; | 371 | let list = http.get_cookie("/admin/users", &tahinli).await; |
| 440 | assert_eq!(list.status, 200, "GET /admin/users"); | 372 | assert_eq!(list.status, 200, "GET /admin/users"); |
| 441 | let doc = scraper::Html::parse_document(&list.body); | 373 | let doc = scraper::Html::parse_document(&list.body); |
| @@ -453,7 +385,7 @@ async fn suspended_user_token_is_refused_over_http_git() { |
| 453 | .to_owned(); | 385 | .to_owned(); |
| 454 | let detail = http.get_cookie(&bob_href, &tahinli).await; | 386 | let detail = http.get_cookie(&bob_href, &tahinli).await; |
| 455 | assert_eq!(detail.status, 200, "GET {bob_href}"); | 387 | assert_eq!(detail.status, 200, "GET {bob_href}"); |
| 456 | - let csrf = input_value(&detail.body, "csrf"); | 388 | + let csrf = csrf_for(&http, &bob_href, &tahinli).await; |
| 457 | let res = http | 389 | let res = http |
| 458 | .post_form( | 390 | .post_form( |
| 459 | &format!("{bob_href}/suspend"), | 391 | &format!("{bob_href}/suspend"), |
| @@ -465,12 +397,12 @@ async fn suspended_user_token_is_refused_over_http_git() { |
| 465 | | 397 | |
| 466 | commit_file(&work, "b.txt", "two\n", "second"); | 398 | commit_file(&work, "b.txt", "two\n", "second"); |
| 467 | rejected( | 399 | rejected( |
| 468 | - &git(&work, &["push", "origin", "HEAD:main"], &[]), | 400 | + &git(&work, &["push", "origin", "HEAD:main"]), |
| 469 | "push with a suspended user's token", | 401 | "push with a suspended user's token", |
| 470 | ); | 402 | ); |
| 471 | let again = dir.join("again"); | 403 | let again = dir.join("again"); |
| 472 | rejected( | 404 | rejected( |
| 473 | - &git(&dir, &["clone", &url, path_str(&again)], &[]), | 405 | + &git(&dir, &["clone", &url, path_str(&again)]), |
| 474 | "clone with a suspended user's token", | 406 | "clone with a suspended user's token", |
| 475 | ); | 407 | ); |
| 476 | } | 408 | } |
| @@ -1,29 +1,6 @@ |
| 1 | -use std::path::Path; | 1 | +use crate::common::{Http, PW, Server, input_value, launch, login, provision}; |
| 2 | -use std::process::Command; | | |
| 3 | - | | |
| 4 | -use crate::common::{ | | |
| 5 | - Http, Server, bin, describe, input_value, launch, login, pick_ports, write_config, | | |
| 6 | -}; | | |
| 7 | use forge_core::Store; | 2 | use forge_core::Store; |
| 8 | | 3 | |
| 9 | -const PW: &str = "tahinli-password-123"; | | |
| 10 | - | | |
| 11 | -fn admin(config: &Path, args: &[&str]) { | | |
| 12 | - let out = Command::new(bin()) | | |
| 13 | - .arg("--config") | | |
| 14 | - .arg(config) | | |
| 15 | - .arg("admin") | | |
| 16 | - .args(args) | | |
| 17 | - .env("FORGE_PASSWORD", PW) | | |
| 18 | - .output() | | |
| 19 | - .expect("run admin command"); | | |
| 20 | - assert!( | | |
| 21 | - out.status.success(), | | |
| 22 | - "admin {args:?} failed:\n{}", | | |
| 23 | - describe(&out) | | |
| 24 | - ); | | |
| 25 | -} | | |
| 26 | - | | |
| 27 | struct Env { | 4 | struct Env { |
| 28 | _root: tempfile::TempDir, | 5 | _root: tempfile::TempDir, |
| 29 | _server: Server, | 6 | _server: Server, |
| @@ -37,9 +14,7 @@ where |
| 37 | { | 14 | { |
| 38 | let root = tempfile::tempdir().expect("temp dir"); | 15 | let root = tempfile::tempdir().expect("temp dir"); |
| 39 | let dir = root.path().to_path_buf(); | 16 | let dir = root.path().to_path_buf(); |
| 40 | - let ports = pick_ports(); | 17 | + let (_, ports) = provision(&dir, "", &[&["create-user", "tahinli"]]); |
| 41 | - let config = write_config(&dir, ports); | | |
| 42 | - admin(&config, &["create-user", "tahinli"]); | | |
| 43 | let store = Store::open(&dir.join("forge.db")) | 18 | let store = Store::open(&dir.join("forge.db")) |
| 44 | .await | 19 | .await |
| 45 | .expect("open store"); | 20 | .expect("open store"); |
| @@ -1,109 +1,12 @@ |
| 1 | use crate::common::{ | 1 | use crate::common::{ |
| 2 | - Http, input_value, launch, login, pick_ports, relaunch, run_admin, tool_on_path, write_config, | 2 | + BOB_CMD, Http, PW, TAHINLI_CMD, boot_forge, commit_file, create_repo, create_token, git_text, |
| | 3 | + login, relaunch, text_or_empty, tool_on_path, |
| 3 | }; | 4 | }; |
| 4 | -use std::fs; | | |
| 5 | use std::future::Future; | 5 | use std::future::Future; |
| 6 | -use std::path::Path; | | |
| 7 | -use std::process::{Command, Output}; | | |
| 8 | use std::time::{Duration, Instant}; | 6 | use std::time::{Duration, Instant}; |
| 9 | | 7 | |
| 10 | use forge_core::Store; | 8 | use forge_core::Store; |
| 11 | | 9 | |
| 12 | -const TAHINLI_PW: &str = "tahinli-password-123"; | | |
| 13 | -const BOB_PW: &str = "bob-password-4567"; | | |
| 14 | - | | |
| 15 | -fn git(cwd: &Path, args: &[&str]) -> String { | | |
| 16 | - let out = git_output(cwd, args, &[]); | | |
| 17 | - assert!( | | |
| 18 | - out.status.success(), | | |
| 19 | - "git {args:?} failed:\n{}", | | |
| 20 | - String::from_utf8_lossy(&out.stderr) | | |
| 21 | - ); | | |
| 22 | - String::from_utf8_lossy(&out.stdout).trim().to_owned() | | |
| 23 | -} | | |
| 24 | - | | |
| 25 | -fn git_output(cwd: &Path, args: &[&str], env: &[(&str, &str)]) -> Output { | | |
| 26 | - let mut cmd = Command::new("git"); | | |
| 27 | - cmd.current_dir(cwd) | | |
| 28 | - .args(["-c", "credential.helper="]) | | |
| 29 | - .args(args) | | |
| 30 | - .env("GIT_TERMINAL_PROMPT", "0"); | | |
| 31 | - for (key, value) in env { | | |
| 32 | - cmd.env(key, value); | | |
| 33 | - } | | |
| 34 | - cmd.output().expect("run git") | | |
| 35 | -} | | |
| 36 | - | | |
| 37 | -fn commit_file(repo: &Path, name: &str, message: &str) -> String { | | |
| 38 | - fs::write(repo.join(name), message).expect("write file"); | | |
| 39 | - git(repo, &["add", name]); | | |
| 40 | - git( | | |
| 41 | - repo, | | |
| 42 | - &[ | | |
| 43 | - "-c", | | |
| 44 | - "user.name=tahinli", | | |
| 45 | - "-c", | | |
| 46 | - "user.email=tahinli@example.test", | | |
| 47 | - "-c", | | |
| 48 | - "commit.gpgsign=false", | | |
| 49 | - "commit", | | |
| 50 | - "-q", | | |
| 51 | - "-m", | | |
| 52 | - message, | | |
| 53 | - ], | | |
| 54 | - ); | | |
| 55 | - git(repo, &["rev-parse", "HEAD"]) | | |
| 56 | -} | | |
| 57 | - | | |
| 58 | -async fn create_token(http: &Http, session: &str, name: &str) -> String { | | |
| 59 | - let page = http.get_cookie("/settings/keys", session).await; | | |
| 60 | - assert_eq!(page.status, 200, "GET /settings/keys"); | | |
| 61 | - let csrf = input_value(&page.body, "csrf"); | | |
| 62 | - let res = http | | |
| 63 | - .post_form( | | |
| 64 | - "/settings/tokens", | | |
| 65 | - &[("csrf", &csrf), ("name", name), ("expires", "30")], | | |
| 66 | - Some(session), | | |
| 67 | - ) | | |
| 68 | - .await; | | |
| 69 | - assert_eq!(res.status, 200, "create token: {}", res.body); | | |
| 70 | - let doc = scraper::Html::parse_document(&res.body); | | |
| 71 | - let selector = scraper::Selector::parse("pre.code code").expect("selector"); | | |
| 72 | - let token: String = doc | | |
| 73 | - .select(&selector) | | |
| 74 | - .next() | | |
| 75 | - .expect("token shown after creation") | | |
| 76 | - .text() | | |
| 77 | - .collect(); | | |
| 78 | - let token = token.trim().to_owned(); | | |
| 79 | - assert!(token.starts_with("forge_"), "unexpected token shape"); | | |
| 80 | - token | | |
| 81 | -} | | |
| 82 | - | | |
| 83 | -async fn create_repo(http: &Http, session: &str, name: &str) { | | |
| 84 | - let page = http.get_cookie("/new", session).await; | | |
| 85 | - assert_eq!(page.status, 200, "GET /new"); | | |
| 86 | - let csrf = input_value(&page.body, "csrf"); | | |
| 87 | - let res = http | | |
| 88 | - .post_form( | | |
| 89 | - "/new", | | |
| 90 | - &[ | | |
| 91 | - ("csrf", &csrf), | | |
| 92 | - ("name", name), | | |
| 93 | - ("description", ""), | | |
| 94 | - ("visibility", "public"), | | |
| 95 | - ("default_branch", "main"), | | |
| 96 | - ], | | |
| 97 | - Some(session), | | |
| 98 | - ) | | |
| 99 | - .await; | | |
| 100 | - assert_eq!(res.status, 303, "create repo {name}: {}", res.body); | | |
| 101 | - assert_eq!( | | |
| 102 | - res.location().as_deref(), | | |
| 103 | - Some(format!("/tahinli/{name}").as_str()) | | |
| 104 | - ); | | |
| 105 | -} | | |
| 106 | - | | |
| 107 | async fn eventually<F, Fut>(what: &str, mut check: F) | 10 | async fn eventually<F, Fut>(what: &str, mut check: F) |
| 108 | where | 11 | where |
| 109 | F: FnMut() -> Fut, | 12 | F: FnMut() -> Fut, |
| @@ -127,15 +30,6 @@ async fn issue_page(http: &Http, session: &str, number: u32) -> String { |
| 127 | res.body | 30 | res.body |
| 128 | } | 31 | } |
| 129 | | 32 | |
| 130 | -fn state_badge(body: &str) -> String { | | |
| 131 | - let doc = scraper::Html::parse_document(body); | | |
| 132 | - let selector = scraper::Selector::parse(".issue-badge").expect("selector"); | | |
| 133 | - doc.select(&selector) | | |
| 134 | - .next() | | |
| 135 | - .map(|el| el.text().collect::<String>().trim().to_owned()) | | |
| 136 | - .unwrap_or_default() | | |
| 137 | -} | | |
| 138 | - | | |
| 139 | #[tokio::test] | 33 | #[tokio::test] |
| 140 | async fn pushes_close_and_reference_issues() { | 34 | async fn pushes_close_and_reference_issues() { |
| 141 | if !tool_on_path("git") { | 35 | if !tool_on_path("git") { |
| @@ -143,24 +37,16 @@ async fn pushes_close_and_reference_issues() { |
| 143 | return; | 37 | return; |
| 144 | } | 38 | } |
| 145 | | 39 | |
| 146 | - let root = tempfile::Builder::new() | 40 | + let root = crate::common::temp_dir("ice2e"); |
| 147 | - .prefix("ice2e") | | |
| 148 | - .tempdir_in("/tmp") | | |
| 149 | - .expect("temp dir"); | | |
| 150 | let dir = root.path().to_path_buf(); | 41 | let dir = root.path().to_path_buf(); |
| 151 | - let ports = pick_ports(); | 42 | + let config = dir.join("forge.toml"); |
| 152 | - let config = write_config(&dir, ports); | | |
| 153 | let log_path = dir.join("serve.log"); | 43 | let log_path = dir.join("serve.log"); |
| 154 | - | 44 | + let (mut server, ports) = boot_forge(&dir, "", &[TAHINLI_CMD, BOB_CMD]).await; |
| 155 | - run_admin(&config, "tahinli", &["--admin"], TAHINLI_PW); | | |
| 156 | - run_admin(&config, "bob", &[], BOB_PW); | | |
| 157 | - | | |
| 158 | - let (mut server, ports) = launch(&dir, ports).await; | | |
| 159 | let http_port = ports.http; | 45 | let http_port = ports.http; |
| 160 | let http = Http::new(http_port); | 46 | let http = Http::new(http_port); |
| 161 | - let tahinli = login(&http, "tahinli", TAHINLI_PW).await; | 47 | + let tahinli = login(&http, "tahinli", PW).await; |
| 162 | let token = create_token(&http, &tahinli, "issue-close-token").await; | 48 | let token = create_token(&http, &tahinli, "issue-close-token").await; |
| 163 | - create_repo(&http, &tahinli, "pub").await; | 49 | + create_repo(&http, &tahinli, "pub", "public").await; |
| 164 | | 50 | |
| 165 | drop(server); | 51 | drop(server); |
| 166 | { | 52 | { |
| @@ -185,34 +71,39 @@ async fn pushes_close_and_reference_issues() { |
| 185 | } | 71 | } |
| 186 | } | 72 | } |
| 187 | server = relaunch(&config, &log_path, ports).await; | 73 | server = relaunch(&config, &log_path, ports).await; |
| 188 | - let tahinli = login(&http, "tahinli", TAHINLI_PW).await; | 74 | + let tahinli = login(&http, "tahinli", PW).await; |
| 189 | | 75 | |
| 190 | let url = format!("http://tahinli:{token}@127.0.0.1:{http_port}/tahinli/pub.git"); | 76 | let url = format!("http://tahinli:{token}@127.0.0.1:{http_port}/tahinli/pub.git"); |
| 191 | let work = dir.join("work"); | 77 | let work = dir.join("work"); |
| 192 | - git( | 78 | + git_text( |
| 193 | &dir, | 79 | &dir, |
| 194 | &["clone", "-q", &url, work.to_str().expect("utf-8 path")], | 80 | &["clone", "-q", &url, work.to_str().expect("utf-8 path")], |
| 195 | ); | 81 | ); |
| 196 | - let base = commit_file(&work, "base.txt", "base commit"); | 82 | + let base = commit_file(&work, "base.txt", "base commit", "base commit"); |
| 197 | - git(&work, &["push", "-q", "origin", "HEAD:refs/heads/main"]); | 83 | + git_text(&work, &["push", "-q", "origin", "HEAD:refs/heads/main"]); |
| 198 | | 84 | |
| 199 | - git(&work, &["checkout", "-q", "-b", "topic"]); | 85 | + git_text(&work, &["checkout", "-q", "-b", "topic"]); |
| 200 | - let topic_oid = commit_file(&work, "topic.txt", "fixes #3 on a topic branch"); | 86 | + let topic_oid = commit_file( |
| 201 | - git(&work, &["push", "-q", "origin", "HEAD:refs/heads/topic"]); | 87 | + &work, |
| | 88 | + "topic.txt", |
| | 89 | + "fixes #3 on a topic branch", |
| | 90 | + "fixes #3 on a topic branch", |
| | 91 | + ); |
| | 92 | + git_text(&work, &["push", "-q", "origin", "HEAD:refs/heads/topic"]); |
| 202 | | 93 | |
| 203 | - git(&work, &["checkout", "-q", "-B", "mainline", &base]); | 94 | + git_text(&work, &["checkout", "-q", "-B", "mainline", &base]); |
| 204 | - let main_oid = commit_file(&work, "main.txt", "Fixes #1, refs #2"); | 95 | + let main_oid = commit_file(&work, "main.txt", "Fixes #1, refs #2", "Fixes #1, refs #2"); |
| 205 | - git( | 96 | + git_text( |
| 206 | &work, | 97 | &work, |
| 207 | &["push", "-q", "origin", "HEAD:refs/heads/dup-of-main"], | 98 | &["push", "-q", "origin", "HEAD:refs/heads/dup-of-main"], |
| 208 | ); | 99 | ); |
| 209 | - git(&work, &["push", "-q", "origin", "HEAD:refs/heads/main"]); | 100 | + git_text(&work, &["push", "-q", "origin", "HEAD:refs/heads/main"]); |
| 210 | | 101 | |
| 211 | let commit_link = format!("/commit/{main_oid}"); | 102 | let commit_link = format!("/commit/{main_oid}"); |
| 212 | let link_ref = commit_link.as_str(); | 103 | let link_ref = commit_link.as_str(); |
| 213 | let (http_ref, tahinli_ref) = (&http, tahinli.as_str()); | 104 | let (http_ref, tahinli_ref) = (&http, tahinli.as_str()); |
| 214 | eventually("#1 closed by the push", || async move { | 105 | eventually("#1 closed by the push", || async move { |
| 215 | - state_badge(&issue_page(http_ref, tahinli_ref, 1).await) == "Closed" | 106 | + text_or_empty(&issue_page(http_ref, tahinli_ref, 1).await, ".issue-badge") == "Closed" |
| 216 | }) | 107 | }) |
| 217 | .await; | 108 | .await; |
| 218 | let page1 = issue_page(&http, &tahinli, 1).await; | 109 | let page1 = issue_page(&http, &tahinli, 1).await; |
| @@ -227,7 +118,11 @@ async fn pushes_close_and_reference_issues() { |
| 227 | }) | 118 | }) |
| 228 | .await; | 119 | .await; |
| 229 | let page2 = issue_page(&http, &tahinli, 2).await; | 120 | let page2 = issue_page(&http, &tahinli, 2).await; |
| 230 | - assert_eq!(state_badge(&page2), "Open", "#2 is only referenced"); | 121 | + assert_eq!( |
| | 122 | + text_or_empty(&page2, ".issue-badge"), |
| | 123 | + "Open", |
| | 124 | + "#2 is only referenced" |
| | 125 | + ); |
| 231 | | 126 | |
| 232 | tokio::time::sleep(Duration::from_secs(2)).await; | 127 | tokio::time::sleep(Duration::from_secs(2)).await; |
| 233 | let page2 = issue_page(&http, &tahinli, 2).await; | 128 | let page2 = issue_page(&http, &tahinli, 2).await; |
| @@ -238,7 +133,7 @@ async fn pushes_close_and_reference_issues() { |
| 238 | ); | 133 | ); |
| 239 | let page3 = issue_page(&http, &tahinli, 3).await; | 134 | let page3 = issue_page(&http, &tahinli, 3).await; |
| 240 | assert_eq!( | 135 | assert_eq!( |
| 241 | - state_badge(&page3), | 136 | + text_or_empty(&page3, ".issue-badge"), |
| 242 | "Open", | 137 | "Open", |
| 243 | "#3 must not be closed from topic" | 138 | "#3 must not be closed from topic" |
| 244 | ); | 139 | ); |
| @@ -1,33 +1,11 @@ |
| 1 | use crate::common::{ | 1 | use crate::common::{ |
| 2 | - Http, describe, input_value, launch, login, pick_ports, run_admin, write_config, | 2 | + Http, PW, TAHINLI_CMD, boot_forge, create_repo, create_token, git_env, login, ok, path_str, |
| 3 | }; | 3 | }; |
| 4 | use std::fs; | 4 | use std::fs; |
| 5 | -use std::path::Path; | 5 | +use std::process::Command; |
| 6 | -use std::process::{Command, Output}; | | |
| 7 | | 6 | |
| 8 | -const TAHINLI_PW: &str = "tahinli-password-123"; | | |
| 9 | const FILE_SIZE: usize = 100 * 1024; | 7 | const FILE_SIZE: usize = 100 * 1024; |
| 10 | | 8 | |
| 11 | -fn ok(out: &Output, what: &str) { | | |
| 12 | - assert!(out.status.success(), "{what} failed:\n{}", describe(out)); | | |
| 13 | -} | | |
| 14 | - | | |
| 15 | -fn git(cwd: &Path, args: &[&str], env: &[(&str, &str)]) -> Output { | | |
| 16 | - let mut cmd = Command::new("git"); | | |
| 17 | - cmd.current_dir(cwd) | | |
| 18 | - .args(["-c", "credential.helper="]) | | |
| 19 | - .args(args) | | |
| 20 | - .env("GIT_TERMINAL_PROMPT", "0"); | | |
| 21 | - for (key, value) in env { | | |
| 22 | - cmd.env(key, value); | | |
| 23 | - } | | |
| 24 | - cmd.output().expect("run git") | | |
| 25 | -} | | |
| 26 | - | | |
| 27 | -fn path_str(path: &Path) -> &str { | | |
| 28 | - path.to_str().expect("utf-8 path") | | |
| 29 | -} | | |
| 30 | - | | |
| 31 | fn git_lfs_installed() -> bool { | 9 | fn git_lfs_installed() -> bool { |
| 32 | Command::new("git") | 10 | Command::new("git") |
| 33 | .args(["lfs", "version"]) | 11 | .args(["lfs", "version"]) |
| @@ -41,55 +19,6 @@ fn payload() -> Vec<u8> { |
| 41 | .collect() | 19 | .collect() |
| 42 | } | 20 | } |
| 43 | | 21 | |
| 44 | -async fn create_token(http: &Http, session: &str, name: &str) -> String { | | |
| 45 | - let page = http.get("/settings/keys", Some(session)).await; | | |
| 46 | - assert_eq!(page.status, 200, "GET /settings/keys"); | | |
| 47 | - let csrf = input_value(&page.body, "csrf"); | | |
| 48 | - let res = http | | |
| 49 | - .post_form( | | |
| 50 | - "/settings/tokens", | | |
| 51 | - &[("csrf", &csrf), ("name", name), ("expires", "30")], | | |
| 52 | - Some(session), | | |
| 53 | - ) | | |
| 54 | - .await; | | |
| 55 | - assert_eq!(res.status, 200, "create token: {}", res.body); | | |
| 56 | - let doc = scraper::Html::parse_document(&res.body); | | |
| 57 | - let selector = scraper::Selector::parse("pre.code code").expect("selector"); | | |
| 58 | - let token: String = doc | | |
| 59 | - .select(&selector) | | |
| 60 | - .next() | | |
| 61 | - .expect("token shown after creation") | | |
| 62 | - .text() | | |
| 63 | - .collect(); | | |
| 64 | - let token = token.trim().to_owned(); | | |
| 65 | - assert!(token.starts_with("forge_"), "unexpected token shape"); | | |
| 66 | - token | | |
| 67 | -} | | |
| 68 | - | | |
| 69 | -async fn create_repo(http: &Http, session: &str, name: &str, visibility: &str) { | | |
| 70 | - let page = http.get("/new", Some(session)).await; | | |
| 71 | - assert_eq!(page.status, 200, "GET /new"); | | |
| 72 | - let csrf = input_value(&page.body, "csrf"); | | |
| 73 | - let res = http | | |
| 74 | - .post_form( | | |
| 75 | - "/new", | | |
| 76 | - &[ | | |
| 77 | - ("csrf", &csrf), | | |
| 78 | - ("name", name), | | |
| 79 | - ("description", ""), | | |
| 80 | - ("visibility", visibility), | | |
| 81 | - ("default_branch", "main"), | | |
| 82 | - ], | | |
| 83 | - Some(session), | | |
| 84 | - ) | | |
| 85 | - .await; | | |
| 86 | - assert_eq!(res.status, 303, "create repo {name}: {}", res.body); | | |
| 87 | - assert_eq!( | | |
| 88 | - res.location().as_deref(), | | |
| 89 | - Some(format!("/tahinli/{name}").as_str()) | | |
| 90 | - ); | | |
| 91 | -} | | |
| 92 | - | | |
| 93 | #[tokio::test] | 22 | #[tokio::test] |
| 94 | async fn lfs_end_to_end() { | 23 | async fn lfs_end_to_end() { |
| 95 | if !git_lfs_installed() { | 24 | if !git_lfs_installed() { |
| @@ -97,19 +26,12 @@ async fn lfs_end_to_end() { |
| 97 | return; | 26 | return; |
| 98 | } | 27 | } |
| 99 | | 28 | |
| 100 | - let root = tempfile::Builder::new() | 29 | + let root = crate::common::temp_dir("flfs"); |
| 101 | - .prefix("flfs") | | |
| 102 | - .tempdir_in("/tmp") | | |
| 103 | - .expect("temp dir"); | | |
| 104 | let dir = root.path().to_path_buf(); | 30 | let dir = root.path().to_path_buf(); |
| 105 | - let ports = pick_ports(); | 31 | + let (_server, ports) = boot_forge(&dir, "", &[TAHINLI_CMD]).await; |
| 106 | - let config = write_config(&dir, ports); | | |
| 107 | - run_admin(&config, "tahinli", &["--admin"], TAHINLI_PW); | | |
| 108 | - | | |
| 109 | - let (_server, ports) = launch(&dir, ports).await; | | |
| 110 | let http = Http::new(ports.http); | 32 | let http = Http::new(ports.http); |
| 111 | | 33 | |
| 112 | - let session = login(&http, "tahinli", TAHINLI_PW).await; | 34 | + let session = login(&http, "tahinli", PW).await; |
| 113 | let token = create_token(&http, &session, "lfs-e2e").await; | 35 | let token = create_token(&http, &session, "lfs-e2e").await; |
| 114 | create_repo(&http, &session, "lfs", "public").await; | 36 | create_repo(&http, &session, "lfs", "public").await; |
| 115 | | 37 | |
| @@ -125,15 +47,15 @@ async fn lfs_end_to_end() { |
| 125 | | 47 | |
| 126 | let work = dir.join("work"); | 48 | let work = dir.join("work"); |
| 127 | ok( | 49 | ok( |
| 128 | - &git(&dir, &["clone", &url, path_str(&work)], &iso), | 50 | + &git_env(&dir, &["clone", &url, path_str(&work)], &iso), |
| 129 | "clone of empty repo", | 51 | "clone of empty repo", |
| 130 | ); | 52 | ); |
| 131 | ok( | 53 | ok( |
| 132 | - &git(&work, &["config", "user.name", "tahinli"], &iso), | 54 | + &git_env(&work, &["config", "user.name", "tahinli"], &iso), |
| 133 | "user.name", | 55 | "user.name", |
| 134 | ); | 56 | ); |
| 135 | ok( | 57 | ok( |
| 136 | - &git( | 58 | + &git_env( |
| 137 | &work, | 59 | &work, |
| 138 | &["config", "user.email", "tahinli@example.com"], | 60 | &["config", "user.email", "tahinli@example.com"], |
| 139 | &iso, | 61 | &iso, |
| @@ -141,21 +63,21 @@ async fn lfs_end_to_end() { |
| 141 | "user.email", | 63 | "user.email", |
| 142 | ); | 64 | ); |
| 143 | ok( | 65 | ok( |
| 144 | - &git(&work, &["lfs", "install", "--local"], &iso), | 66 | + &git_env(&work, &["lfs", "install", "--local"], &iso), |
| 145 | "git lfs install", | 67 | "git lfs install", |
| 146 | ); | 68 | ); |
| 147 | ok( | 69 | ok( |
| 148 | - &git(&work, &["lfs", "track", "*.bin"], &iso), | 70 | + &git_env(&work, &["lfs", "track", "*.bin"], &iso), |
| 149 | "git lfs track", | 71 | "git lfs track", |
| 150 | ); | 72 | ); |
| 151 | let content = payload(); | 73 | let content = payload(); |
| 152 | fs::write(work.join("data.bin"), &content).expect("write data.bin"); | 74 | fs::write(work.join("data.bin"), &content).expect("write data.bin"); |
| 153 | ok( | 75 | ok( |
| 154 | - &git(&work, &["add", ".gitattributes", "data.bin"], &iso), | 76 | + &git_env(&work, &["add", ".gitattributes", "data.bin"], &iso), |
| 155 | "git add", | 77 | "git add", |
| 156 | ); | 78 | ); |
| 157 | ok( | 79 | ok( |
| 158 | - &git( | 80 | + &git_env( |
| 159 | &work, | 81 | &work, |
| 160 | &[ | 82 | &[ |
| 161 | "-c", | 83 | "-c", |
| @@ -170,21 +92,21 @@ async fn lfs_end_to_end() { |
| 170 | "git commit", | 92 | "git commit", |
| 171 | ); | 93 | ); |
| 172 | ok( | 94 | ok( |
| 173 | - &git(&work, &["push", "origin", "HEAD:main"], &iso), | 95 | + &git_env(&work, &["push", "origin", "HEAD:main"], &iso), |
| 174 | "git push", | 96 | "git push", |
| 175 | ); | 97 | ); |
| 176 | | 98 | |
| 177 | let verify = dir.join("verify"); | 99 | let verify = dir.join("verify"); |
| 178 | let smudge = [iso[0], iso[1], ("GIT_LFS_SKIP_SMUDGE", "0")]; | 100 | let smudge = [iso[0], iso[1], ("GIT_LFS_SKIP_SMUDGE", "0")]; |
| 179 | ok( | 101 | ok( |
| 180 | - &git(&dir, &["clone", &url, path_str(&verify)], &smudge), | 102 | + &git_env(&dir, &["clone", &url, path_str(&verify)], &smudge), |
| 181 | "clone for verification", | 103 | "clone for verification", |
| 182 | ); | 104 | ); |
| 183 | ok( | 105 | ok( |
| 184 | - &git(&verify, &["lfs", "install", "--local"], &iso), | 106 | + &git_env(&verify, &["lfs", "install", "--local"], &iso), |
| 185 | "git lfs install in verify clone", | 107 | "git lfs install in verify clone", |
| 186 | ); | 108 | ); |
| 187 | - ok(&git(&verify, &["lfs", "pull"], &smudge), "git lfs pull"); | 109 | + ok(&git_env(&verify, &["lfs", "pull"], &smudge), "git lfs pull"); |
| 188 | let fetched = fs::read(verify.join("data.bin")).expect("read fetched data.bin"); | 110 | let fetched = fs::read(verify.join("data.bin")).expect("read fetched data.bin"); |
| 189 | assert!( | 111 | assert!( |
| 190 | fetched == content, | 112 | fetched == content, |
| @@ -1,6 +1,6 @@ |
| 1 | use crate::common::{ | 1 | use crate::common::{ |
| 2 | - FAST_CLAIMS, Http, Server, input_value, launch_with, login, pick_ports, run_admin, | 2 | + BOB_CMD, FAST_CLAIMS, Http, PW, Server, TAHINLI_CMD, boot_forge, clone, commit, create_repo, |
| 3 | - tool_on_path, write_config, | 3 | + create_token, csrf_for, first_text, git_text, login, temp_dir, tool_on_path, |
| 4 | }; | 4 | }; |
| 5 | use forge_ci::proto::{JobAssignment, RegisterRequest}; | 5 | use forge_ci::proto::{JobAssignment, RegisterRequest}; |
| 6 | use forge_runner::client::ForgeClient; | 6 | use forge_runner::client::ForgeClient; |
| @@ -10,134 +10,17 @@ use forge_runner::runner::{RunOptions, Runner}; |
| 10 | use std::collections::BTreeMap; | 10 | use std::collections::BTreeMap; |
| 11 | use std::fs; | 11 | use std::fs; |
| 12 | use std::path::{Path, PathBuf}; | 12 | use std::path::{Path, PathBuf}; |
| 13 | -use std::process::Command; | | |
| 14 | use std::sync::Arc; | 13 | use std::sync::Arc; |
| 15 | use tokio_util::sync::CancellationToken; | 14 | use tokio_util::sync::CancellationToken; |
| 16 | | 15 | |
| 17 | -const TAHINLI_PW: &str = "tahinli-password-123"; | 16 | +const TAHINLI: (&str, &str) = ("tahinli", "tahinli@example.test"); |
| 18 | -const BOB_PW: &str = "bob-password-4567"; | | |
| 19 | const REPO_PATH: &str = "/tahinli/r"; | 17 | const REPO_PATH: &str = "/tahinli/r"; |
| 20 | const LABELS: &[&str] = &["linux"]; | 18 | const LABELS: &[&str] = &["linux"]; |
| 21 | | 19 | |
| 22 | -fn first_text(body: &str, selector: &str) -> String { | | |
| 23 | - let doc = scraper::Html::parse_document(body); | | |
| 24 | - let selector = scraper::Selector::parse(selector).expect("selector"); | | |
| 25 | - doc.select(&selector) | | |
| 26 | - .next() | | |
| 27 | - .unwrap_or_else(|| panic!("no element matches {selector:?}")) | | |
| 28 | - .text() | | |
| 29 | - .collect::<String>() | | |
| 30 | - .trim() | | |
| 31 | - .to_owned() | | |
| 32 | -} | | |
| 33 | - | | |
| 34 | -fn git_env(cwd: &Path, args: &[&str], env: &[(&str, &str)]) -> String { | | |
| 35 | - let mut cmd = Command::new("git"); | | |
| 36 | - cmd.current_dir(cwd) | | |
| 37 | - .args(["-c", "credential.helper="]) | | |
| 38 | - .args(args) | | |
| 39 | - .env("GIT_TERMINAL_PROMPT", "0"); | | |
| 40 | - for (key, value) in env { | | |
| 41 | - cmd.env(key, value); | | |
| 42 | - } | | |
| 43 | - let out = cmd.output().expect("run git"); | | |
| 44 | - assert!( | | |
| 45 | - out.status.success(), | | |
| 46 | - "git {args:?} failed:\n{}", | | |
| 47 | - String::from_utf8_lossy(&out.stderr) | | |
| 48 | - ); | | |
| 49 | - String::from_utf8_lossy(&out.stdout).trim().to_owned() | | |
| 50 | -} | | |
| 51 | - | | |
| 52 | -fn git(cwd: &Path, args: &[&str]) -> String { | | |
| 53 | - git_env(cwd, args, &[]) | | |
| 54 | -} | | |
| 55 | - | | |
| 56 | -fn commit( | | |
| 57 | - repo: &Path, | | |
| 58 | - file: &str, | | |
| 59 | - contents: &str, | | |
| 60 | - message: &str, | | |
| 61 | - who: &str, | | |
| 62 | - email: &str, | | |
| 63 | -) -> String { | | |
| 64 | - let path = repo.join(file); | | |
| 65 | - if let Some(parent) = path.parent() { | | |
| 66 | - fs::create_dir_all(parent).expect("create dir"); | | |
| 67 | - } | | |
| 68 | - fs::write(&path, contents).expect("write file"); | | |
| 69 | - git(repo, &["add", file]); | | |
| 70 | - git_env( | | |
| 71 | - repo, | | |
| 72 | - &["-c", "commit.gpgsign=false", "commit", "-q", "-m", message], | | |
| 73 | - &[ | | |
| 74 | - ("GIT_AUTHOR_NAME", who), | | |
| 75 | - ("GIT_AUTHOR_EMAIL", email), | | |
| 76 | - ("GIT_COMMITTER_NAME", who), | | |
| 77 | - ("GIT_COMMITTER_EMAIL", email), | | |
| 78 | - ], | | |
| 79 | - ); | | |
| 80 | - git(repo, &["rev-parse", "HEAD"]) | | |
| 81 | -} | | |
| 82 | - | | |
| 83 | -fn clone(url: &str, into: &Path) -> PathBuf { | | |
| 84 | - let parent = into.parent().expect("clone target has a parent"); | | |
| 85 | - git( | | |
| 86 | - parent, | | |
| 87 | - &["clone", "-q", url, into.to_str().expect("utf-8 path")], | | |
| 88 | - ); | | |
| 89 | - into.to_path_buf() | | |
| 90 | -} | | |
| 91 | - | | |
| 92 | fn remote(port: u16, user: &str, token: &str, owner: &str, repo: &str) -> String { | 20 | fn remote(port: u16, user: &str, token: &str, owner: &str, repo: &str) -> String { |
| 93 | format!("http://{user}:{token}@127.0.0.1:{port}/{owner}/{repo}.git") | 21 | format!("http://{user}:{token}@127.0.0.1:{port}/{owner}/{repo}.git") |
| 94 | } | 22 | } |
| 95 | | 23 | |
| 96 | -async fn csrf_from(http: &Http, path: &str, session: &str) -> String { | | |
| 97 | - let page = http.get(path, Some(session)).await; | | |
| 98 | - assert_eq!(page.status, 200, "GET {path}"); | | |
| 99 | - input_value(&page.body, "csrf") | | |
| 100 | -} | | |
| 101 | - | | |
| 102 | -async fn create_token(http: &Http, session: &str, name: &str) -> String { | | |
| 103 | - let csrf = csrf_from(http, "/settings/keys", session).await; | | |
| 104 | - let res = http | | |
| 105 | - .post_form( | | |
| 106 | - "/settings/tokens", | | |
| 107 | - &[("csrf", &csrf), ("name", name), ("expires", "30")], | | |
| 108 | - Some(session), | | |
| 109 | - ) | | |
| 110 | - .await; | | |
| 111 | - assert_eq!(res.status, 200, "create token: {}", res.body); | | |
| 112 | - let token = first_text(&res.body, "pre.code code"); | | |
| 113 | - assert!(token.starts_with("forge_"), "unexpected token shape"); | | |
| 114 | - token | | |
| 115 | -} | | |
| 116 | - | | |
| 117 | -async fn create_repo(http: &Http, session: &str, name: &str) { | | |
| 118 | - let page = http.get("/new", Some(session)).await; | | |
| 119 | - assert_eq!(page.status, 200, "GET /new"); | | |
| 120 | - let csrf = input_value(&page.body, "csrf"); | | |
| 121 | - let res = http | | |
| 122 | - .post_form( | | |
| 123 | - "/new", | | |
| 124 | - &[ | | |
| 125 | - ("csrf", &csrf), | | |
| 126 | - ("name", name), | | |
| 127 | - ("description", ""), | | |
| 128 | - ("visibility", "public"), | | |
| 129 | - ("default_branch", "main"), | | |
| 130 | - ], | | |
| 131 | - Some(session), | | |
| 132 | - ) | | |
| 133 | - .await; | | |
| 134 | - assert_eq!(res.status, 303, "create repo {name}: {}", res.body); | | |
| 135 | - assert_eq!( | | |
| 136 | - res.location().as_deref(), | | |
| 137 | - Some(format!("/tahinli/{name}").as_str()) | | |
| 138 | - ); | | |
| 139 | -} | | |
| 140 | - | | |
| 141 | struct Booted { | 24 | struct Booted { |
| 142 | _server: Server, | 25 | _server: Server, |
| 143 | _root: tempfile::TempDir, | 26 | _root: tempfile::TempDir, |
| @@ -152,17 +35,9 @@ fn server_log(b: &Booted) -> String { |
| 152 | } | 35 | } |
| 153 | | 36 | |
| 154 | async fn boot() -> Booted { | 37 | async fn boot() -> Booted { |
| 155 | - let root = tempfile::Builder::new() | 38 | + let root = temp_dir("ci2e"); |
| 156 | - .prefix("ci2e") | | |
| 157 | - .tempdir_in("/tmp") | | |
| 158 | - .expect("temp dir"); | | |
| 159 | let dir = root.path().to_path_buf(); | 39 | let dir = root.path().to_path_buf(); |
| 160 | - let ports = pick_ports(); | 40 | + let (server, ports) = boot_forge(&dir, FAST_CLAIMS, &[TAHINLI_CMD, BOB_CMD]).await; |
| 161 | - let config = write_config(&dir, ports); | | |
| 162 | - | | |
| 163 | - run_admin(&config, "tahinli", &["--admin"], TAHINLI_PW); | | |
| 164 | - run_admin(&config, "bob", &[], BOB_PW); | | |
| 165 | - let (server, ports) = launch_with(&dir, ports, FAST_CLAIMS).await; | | |
| 166 | Booted { | 41 | Booted { |
| 167 | _server: server, | 42 | _server: server, |
| 168 | _root: root, | 43 | _root: root, |
| @@ -200,9 +75,7 @@ impl Worker { |
| 200 | } | 75 | } |
| 201 | | 76 | |
| 202 | async fn register_runner(b: &Booted, admin_session: &str, name: &str) -> Worker { | 77 | async fn register_runner(b: &Booted, admin_session: &str, name: &str) -> Worker { |
| 203 | - let page = b.http.get("/admin/runners", Some(admin_session)).await; | 78 | + let csrf = csrf_for(&b.http, "/admin/runners", admin_session).await; |
| 204 | - assert_eq!(page.status, 200, "GET /admin/runners"); | | |
| 205 | - let csrf = input_value(&page.body, "csrf"); | | |
| 206 | let res = b | 79 | let res = b |
| 207 | .http | 80 | .http |
| 208 | .post_form( | 81 | .post_form( |
| @@ -287,7 +160,7 @@ run = "if [ -f a.txt ] && [ -f b.txt ]; then echo both files present; exit 1; fi |
| 287 | "#; | 160 | "#; |
| 288 | | 161 | |
| 289 | async fn require_merge_queue(http: &Http, session: &str) { | 162 | async fn require_merge_queue(http: &Http, session: &str) { |
| 290 | - let csrf = csrf_from(http, &format!("{REPO_PATH}/settings"), session).await; | 163 | + let csrf = csrf_for(http, &format!("{REPO_PATH}/settings"), session).await; |
| 291 | let res = http | 164 | let res = http |
| 292 | .post_form( | 165 | .post_form( |
| 293 | &format!("{REPO_PATH}/settings/branches"), | 166 | &format!("{REPO_PATH}/settings/branches"), |
| @@ -309,22 +182,14 @@ async fn require_merge_queue(http: &Http, session: &str) { |
| 309 | } | 182 | } |
| 310 | | 183 | |
| 311 | async fn open_pull(http: &Http, session: &str, work: &Path, branch: &str, file: &str) -> i64 { | 184 | async fn open_pull(http: &Http, session: &str, work: &Path, branch: &str, file: &str) -> i64 { |
| 312 | - git(work, &["fetch", "-q", "origin"]); | 185 | + git_text(work, &["fetch", "-q", "origin"]); |
| 313 | let start = "origin/main"; | 186 | let start = "origin/main"; |
| 314 | - git(work, &["checkout", "-q", "-B", branch, start]); | 187 | + git_text(work, &["checkout", "-q", "-B", branch, start]); |
| 315 | - let author = "tahinli@example.test"; | 188 | + commit(work, file, "change\n", &format!("add {file}"), TAHINLI); |
| 316 | - commit( | | |
| 317 | - work, | | |
| 318 | - file, | | |
| 319 | - "change\n", | | |
| 320 | - &format!("add {file}"), | | |
| 321 | - "tahinli", | | |
| 322 | - author, | | |
| 323 | - ); | | |
| 324 | let target = format!("HEAD:refs/heads/{branch}"); | 189 | let target = format!("HEAD:refs/heads/{branch}"); |
| 325 | - git(work, &["push", "-q", "-f", "origin", &target]); | 190 | + git_text(work, &["push", "-q", "-f", "origin", &target]); |
| 326 | | 191 | |
| 327 | - let csrf = csrf_from(http, &format!("{REPO_PATH}/pulls"), session).await; | 192 | + let csrf = csrf_for(http, &format!("{REPO_PATH}/pulls"), session).await; |
| 328 | let res = http | 193 | let res = http |
| 329 | .post_form( | 194 | .post_form( |
| 330 | &format!("{REPO_PATH}/pulls"), | 195 | &format!("{REPO_PATH}/pulls"), |
| @@ -348,7 +213,7 @@ async fn open_pull(http: &Http, session: &str, work: &Path, branch: &str, file: |
| 348 | } | 213 | } |
| 349 | | 214 | |
| 350 | async fn enqueue(http: &Http, session: &str, number: i64) { | 215 | async fn enqueue(http: &Http, session: &str, number: i64) { |
| 351 | - let csrf = csrf_from(http, &format!("{REPO_PATH}/pulls/{number}"), session).await; | 216 | + let csrf = csrf_for(http, &format!("{REPO_PATH}/pulls/{number}"), session).await; |
| 352 | let res = http | 217 | let res = http |
| 353 | .post_form( | 218 | .post_form( |
| 354 | &format!("{REPO_PATH}/pulls/{number}/merge-queue"), | 219 | &format!("{REPO_PATH}/pulls/{number}/merge-queue"), |
| @@ -368,7 +233,7 @@ async fn pull_page(http: &Http, session: &str, number: i64) -> String { |
| 368 | } | 233 | } |
| 369 | | 234 | |
| 370 | async fn setup_queue_repo(b: &Booted, tahinli: &str, token: &str) -> (Worker, PathBuf) { | 235 | async fn setup_queue_repo(b: &Booted, tahinli: &str, token: &str) -> (Worker, PathBuf) { |
| 371 | - create_repo(&b.http, tahinli, "r").await; | 236 | + create_repo(&b.http, tahinli, "r", "public").await; |
| 372 | require_merge_queue(&b.http, tahinli).await; | 237 | require_merge_queue(&b.http, tahinli).await; |
| 373 | let worker = register_runner(b, tahinli, "runner-a").await; | 238 | let worker = register_runner(b, tahinli, "runner-a").await; |
| 374 | let work = clone( | 239 | let work = clone( |
| @@ -380,10 +245,9 @@ async fn setup_queue_repo(b: &Booted, tahinli: &str, token: &str) -> (Worker, Pa |
| 380 | ".forge/ci.toml", | 245 | ".forge/ci.toml", |
| 381 | CI_TOML_QUEUE, | 246 | CI_TOML_QUEUE, |
| 382 | "add queue ci", | 247 | "add queue ci", |
| 383 | - "tahinli", | 248 | + TAHINLI, |
| 384 | - "tahinli@example.test", | | |
| 385 | ); | 249 | ); |
| 386 | - git(&work, &["push", "-q", "origin", "HEAD:refs/heads/main"]); | 250 | + git_text(&work, &["push", "-q", "origin", "HEAD:refs/heads/main"]); |
| 387 | (worker, work) | 251 | (worker, work) |
| 388 | } | 252 | } |
| 389 | | 253 | |
| @@ -394,7 +258,7 @@ async fn merge_queue_lands_the_first_pull_and_kicks_out_the_conflicting_second() |
| 394 | return; | 258 | return; |
| 395 | } | 259 | } |
| 396 | let b = boot().await; | 260 | let b = boot().await; |
| 397 | - let tahinli = login(&b.http, "tahinli", TAHINLI_PW).await; | 261 | + let tahinli = login(&b.http, "tahinli", PW).await; |
| 398 | let token = create_token(&b.http, &tahinli, "mq-token").await; | 262 | let token = create_token(&b.http, &tahinli, "mq-token").await; |
| 399 | let (worker, work) = setup_queue_repo(&b, &tahinli, &token).await; | 263 | let (worker, work) = setup_queue_repo(&b, &tahinli, &token).await; |
| 400 | | 264 | |
| @@ -414,9 +278,9 @@ async fn merge_queue_lands_the_first_pull_and_kicks_out_the_conflicting_second() |
| 414 | let ran = worker.drain().await; | 278 | let ran = worker.drain().await; |
| 415 | assert_eq!(ran, 2, "one candidate run each: {}", server_log(&b)); | 279 | assert_eq!(ran, 2, "one candidate run each: {}", server_log(&b)); |
| 416 | | 280 | |
| 417 | - git(&work, &["fetch", "-q", "origin"]); | 281 | + git_text(&work, &["fetch", "-q", "origin"]); |
| 418 | - let main_tip = git(&work, &["rev-parse", "origin/main"]); | 282 | + let main_tip = git_text(&work, &["rev-parse", "origin/main"]); |
| 419 | - let files = git(&work, &["ls-tree", "--name-only", "origin/main"]); | 283 | + let files = git_text(&work, &["ls-tree", "--name-only", "origin/main"]); |
| 420 | assert!(files.contains("a.txt"), "first pull landed: {files}"); | 284 | assert!(files.contains("a.txt"), "first pull landed: {files}"); |
| 421 | assert!( | 285 | assert!( |
| 422 | !files.contains("b.txt"), | 286 | !files.contains("b.txt"), |
| @@ -464,7 +328,7 @@ async fn pushing_to_a_queued_pull_removes_it_from_the_queue() { |
| 464 | return; | 328 | return; |
| 465 | } | 329 | } |
| 466 | let b = boot().await; | 330 | let b = boot().await; |
| 467 | - let tahinli = login(&b.http, "tahinli", TAHINLI_PW).await; | 331 | + let tahinli = login(&b.http, "tahinli", PW).await; |
| 468 | let token = create_token(&b.http, &tahinli, "mq-token").await; | 332 | let token = create_token(&b.http, &tahinli, "mq-token").await; |
| 469 | let (_worker, work) = setup_queue_repo(&b, &tahinli, &token).await; | 333 | let (_worker, work) = setup_queue_repo(&b, &tahinli, &token).await; |
| 470 | | 334 | |
| @@ -473,15 +337,8 @@ async fn pushing_to_a_queued_pull_removes_it_from_the_queue() { |
| 473 | let queued = pull_page(&b.http, &tahinli, number).await; | 337 | let queued = pull_page(&b.http, &tahinli, number).await; |
| 474 | assert!(queued.contains("Position 1 in the merge queue"), "queued"); | 338 | assert!(queued.contains("Position 1 in the merge queue"), "queued"); |
| 475 | | 339 | |
| 476 | - commit( | 340 | + commit(&work, "c.txt", "changed again\n", "more", TAHINLI); |
| 477 | - &work, | 341 | + git_text(&work, &["push", "-q", "origin", "HEAD:refs/heads/three"]); |
| 478 | - "c.txt", | | |
| 479 | - "changed again\n", | | |
| 480 | - "more", | | |
| 481 | - "tahinli", | | |
| 482 | - "tahinli@example.test", | | |
| 483 | - ); | | |
| 484 | - git(&work, &["push", "-q", "origin", "HEAD:refs/heads/three"]); | | |
| 485 | | 342 | |
| 486 | let after = pull_page(&b.http, &tahinli, number).await; | 343 | let after = pull_page(&b.http, &tahinli, number).await; |
| 487 | assert!( | 344 | assert!( |
| @@ -1,14 +1,13 @@ |
| 1 | use crate::common::{ | 1 | use crate::common::{ |
| 2 | - Http, Server, input_value, launch_with, login, pick_ports, run_admin, tool_on_path, | 2 | + self, Http, PW, Server, TAHINLI_CMD, boot_forge, clone, create_token, csrf_for, git_env, |
| 3 | - write_config_with, | 3 | + git_text_env, login, temp_dir, tool_on_path, |
| 4 | }; | 4 | }; |
| 5 | use std::collections::BTreeSet; | 5 | use std::collections::BTreeSet; |
| 6 | use std::fs; | 6 | use std::fs; |
| 7 | use std::path::{Path, PathBuf}; | 7 | use std::path::{Path, PathBuf}; |
| 8 | -use std::process::{Command, Output}; | 8 | +use std::process::Output; |
| 9 | use std::time::{Duration, Instant}; | 9 | use std::time::{Duration, Instant}; |
| 10 | | 10 | |
| 11 | -const TAHINLI_PW: &str = "tahinli-password-123"; | | |
| 12 | const WEBHOOK_TOML: &str = "\n[webhooks]\nallow_http = true\nallowed_hosts = [\"127.0.0.1\"]\n\n[mirrors]\npush_debounce_secs = 0\n"; | 11 | const WEBHOOK_TOML: &str = "\n[webhooks]\nallow_http = true\nallowed_hosts = [\"127.0.0.1\"]\n\n[mirrors]\npush_debounce_secs = 0\n"; |
| 13 | const SYNC_TIMEOUT: Duration = Duration::from_secs(30); | 12 | const SYNC_TIMEOUT: Duration = Duration::from_secs(30); |
| 14 | const PUSH_TIMEOUT: Duration = Duration::from_secs(90); | 13 | const PUSH_TIMEOUT: Duration = Duration::from_secs(90); |
| @@ -23,65 +22,33 @@ fn form_actions(body: &str, suffix: &str) -> Vec<String> { |
| 23 | .collect() | 22 | .collect() |
| 24 | } | 23 | } |
| 25 | | 24 | |
| 26 | -const GIT_HERMETIC_ENV: &[(&str, &str)] = &[ | | |
| 27 | - ("GIT_AUTHOR_NAME", "tahinli"), | | |
| 28 | - ("GIT_AUTHOR_EMAIL", "tahinli@example.com"), | | |
| 29 | - ("GIT_COMMITTER_NAME", "tahinli"), | | |
| 30 | - ("GIT_COMMITTER_EMAIL", "tahinli@example.com"), | | |
| 31 | - ("GIT_CONFIG_GLOBAL", "/dev/null"), | | |
| 32 | - ("GIT_CONFIG_NOSYSTEM", "1"), | | |
| 33 | -]; | | |
| 34 | - | | |
| 35 | fn git_output(cwd: &Path, args: &[&str], env: &[(&str, &str)]) -> Output { | 25 | fn git_output(cwd: &Path, args: &[&str], env: &[(&str, &str)]) -> Output { |
| 36 | - let mut cmd = Command::new("git"); | 26 | + let all: Vec<(&str, &str)> = GIT_HERMETIC_ENV.iter().chain(env).copied().collect(); |
| 37 | - cmd.current_dir(cwd) | 27 | + git_env(cwd, args, &all) |
| 38 | - .args(["-c", "credential.helper="]) | | |
| 39 | - .args(args) | | |
| 40 | - .env("GIT_TERMINAL_PROMPT", "0"); | | |
| 41 | - for (key, value) in GIT_HERMETIC_ENV.iter().chain(env) { | | |
| 42 | - cmd.env(key, value); | | |
| 43 | - } | | |
| 44 | - cmd.output().expect("run git") | | |
| 45 | -} | | |
| 46 | - | | |
| 47 | -fn git_env(cwd: &Path, args: &[&str], env: &[(&str, &str)]) -> String { | | |
| 48 | - let out = git_output(cwd, args, env); | | |
| 49 | - assert!( | | |
| 50 | - out.status.success(), | | |
| 51 | - "git {args:?} failed:\n{}", | | |
| 52 | - String::from_utf8_lossy(&out.stderr) | | |
| 53 | - ); | | |
| 54 | - String::from_utf8_lossy(&out.stdout).trim().to_owned() | | |
| 55 | } | 28 | } |
| 56 | | 29 | |
| 57 | fn git(cwd: &Path, args: &[&str]) -> String { | 30 | fn git(cwd: &Path, args: &[&str]) -> String { |
| 58 | - git_env(cwd, args, &[]) | 31 | + git_text_env(cwd, args, GIT_HERMETIC_ENV) |
| 59 | } | 32 | } |
| 60 | | 33 | |
| 61 | fn commit(repo: &Path, file: &str, contents: &str, message: &str) -> String { | 34 | fn commit(repo: &Path, file: &str, contents: &str, message: &str) -> String { |
| 62 | - fs::write(repo.join(file), contents).expect("write file"); | 35 | + common::commit( |
| 63 | - git(repo, &["add", file]); | | |
| 64 | - git_env( | | |
| 65 | repo, | 36 | repo, |
| 66 | - &["-c", "commit.gpgsign=false", "commit", "-q", "-m", message], | 37 | + file, |
| 67 | - &[ | 38 | + contents, |
| 68 | - ("GIT_AUTHOR_NAME", "tahinli"), | 39 | + message, |
| 69 | - ("GIT_AUTHOR_EMAIL", "tahinli@example.test"), | 40 | + ("tahinli", "tahinli@example.test"), |
| 70 | - ("GIT_COMMITTER_NAME", "tahinli"), | 41 | + ) |
| 71 | - ("GIT_COMMITTER_EMAIL", "tahinli@example.test"), | | |
| 72 | - ], | | |
| 73 | - ); | | |
| 74 | - git(repo, &["rev-parse", "HEAD"]) | | |
| 75 | } | 42 | } |
| 76 | | 43 | |
| 77 | -fn clone(url: &str, into: &Path) -> PathBuf { | 44 | +const GIT_HERMETIC_ENV: &[(&str, &str)] = &[ |
| 78 | - let parent = into.parent().expect("clone target has a parent"); | 45 | + ("GIT_AUTHOR_NAME", "tahinli"), |
| 79 | - git( | 46 | + ("GIT_AUTHOR_EMAIL", "tahinli@example.com"), |
| 80 | - parent, | 47 | + ("GIT_COMMITTER_NAME", "tahinli"), |
| 81 | - &["clone", "-q", url, into.to_str().expect("utf-8 path")], | 48 | + ("GIT_COMMITTER_EMAIL", "tahinli@example.com"), |
| 82 | - ); | 49 | + ("GIT_CONFIG_GLOBAL", "/dev/null"), |
| 83 | - into.to_path_buf() | 50 | + ("GIT_CONFIG_NOSYSTEM", "1"), |
| 84 | -} | 51 | +]; |
| 85 | | 52 | |
| 86 | fn remote(port: u16, token: &str, owner: &str, repo: &str) -> String { | 53 | fn remote(port: u16, token: &str, owner: &str, repo: &str) -> String { |
| 87 | format!("http://tahinli:{token}@127.0.0.1:{port}/{owner}/{repo}.git") | 54 | format!("http://tahinli:{token}@127.0.0.1:{port}/{owner}/{repo}.git") |
| @@ -127,39 +94,8 @@ async fn wait_for(what: &str, check: impl Fn() -> bool) { |
| 127 | } | 94 | } |
| 128 | } | 95 | } |
| 129 | | 96 | |
| 130 | -async fn csrf_token(http: &Http, session: &str) -> String { | | |
| 131 | - let page = http.get_cookie("/settings/keys", session).await; | | |
| 132 | - assert_eq!(page.status, 200, "GET /settings/keys"); | | |
| 133 | - input_value(&page.body, "csrf") | | |
| 134 | -} | | |
| 135 | - | | |
| 136 | -async fn create_token(http: &Http, session: &str, name: &str) -> String { | | |
| 137 | - let csrf = csrf_token(http, session).await; | | |
| 138 | - let res = http | | |
| 139 | - .post_form( | | |
| 140 | - "/settings/tokens", | | |
| 141 | - &[("csrf", &csrf), ("name", name), ("expires", "30")], | | |
| 142 | - Some(session), | | |
| 143 | - ) | | |
| 144 | - .await; | | |
| 145 | - assert_eq!(res.status, 200, "create token: {}", res.body); | | |
| 146 | - let doc = scraper::Html::parse_document(&res.body); | | |
| 147 | - let selector = scraper::Selector::parse("pre.code code").expect("selector"); | | |
| 148 | - let token: String = doc | | |
| 149 | - .select(&selector) | | |
| 150 | - .next() | | |
| 151 | - .expect("token shown after creation") | | |
| 152 | - .text() | | |
| 153 | - .collect(); | | |
| 154 | - let token = token.trim().to_owned(); | | |
| 155 | - assert!(token.starts_with("forge_"), "unexpected token shape"); | | |
| 156 | - token | | |
| 157 | -} | | |
| 158 | - | | |
| 159 | async fn new_repo(http: &Http, session: &str, name: &str, mirror: Option<(&str, &str, &str)>) { | 97 | async fn new_repo(http: &Http, session: &str, name: &str, mirror: Option<(&str, &str, &str)>) { |
| 160 | - let page = http.get_cookie("/new", session).await; | 98 | + let csrf = csrf_for(http, "/new", session).await; |
| 161 | - assert_eq!(page.status, 200, "GET /new"); | | |
| 162 | - let csrf = input_value(&page.body, "csrf"); | | |
| 163 | let mut form = vec![ | 99 | let mut form = vec![ |
| 164 | ("csrf", csrf.as_str()), | 100 | ("csrf", csrf.as_str()), |
| 165 | ("name", name), | 101 | ("name", name), |
| @@ -185,9 +121,7 @@ async fn new_repo(http: &Http, session: &str, name: &str, mirror: Option<(&str, |
| 185 | | 121 | |
| 186 | async fn add_push_mirror(http: &Http, session: &str, repo: &str, url: &str, secret: &str) { | 122 | async fn add_push_mirror(http: &Http, session: &str, repo: &str, url: &str, secret: &str) { |
| 187 | let path = format!("/tahinli/{repo}/settings/mirrors"); | 123 | let path = format!("/tahinli/{repo}/settings/mirrors"); |
| 188 | - let page = http.get_cookie(&path, session).await; | 124 | + let csrf = csrf_for(http, &path, session).await; |
| 189 | - assert_eq!(page.status, 200, "GET {path}"); | | |
| 190 | - let csrf = input_value(&page.body, "csrf"); | | |
| 191 | let res = http | 125 | let res = http |
| 192 | .post_form( | 126 | .post_form( |
| 193 | &path, | 127 | &path, |
| @@ -212,7 +146,7 @@ async fn sync_now(http: &Http, session: &str, repo: &str) { |
| 212 | .into_iter() | 146 | .into_iter() |
| 213 | .next() | 147 | .next() |
| 214 | .expect("a sync form on the mirrors page"); | 148 | .expect("a sync form on the mirrors page"); |
| 215 | - let csrf = input_value(&page.body, "csrf"); | 149 | + let csrf = csrf_for(http, &path, session).await; |
| 216 | let res = http | 150 | let res = http |
| 217 | .post_form(&action, &[("csrf", &csrf)], Some(session)) | 151 | .post_form(&action, &[("csrf", &csrf)], Some(session)) |
| 218 | .await; | 152 | .await; |
| @@ -231,16 +165,9 @@ async fn boot() -> Booted { |
| 231 | if !tool_on_path("git") { | 165 | if !tool_on_path("git") { |
| 232 | panic!("`git` was not found on PATH"); | 166 | panic!("`git` was not found on PATH"); |
| 233 | } | 167 | } |
| 234 | - let root = tempfile::Builder::new() | 168 | + let root = temp_dir("mr2e"); |
| 235 | - .prefix("mr2e") | | |
| 236 | - .tempdir_in("/tmp") | | |
| 237 | - .expect("temp dir"); | | |
| 238 | let dir = root.path().to_path_buf(); | 169 | let dir = root.path().to_path_buf(); |
| 239 | - let ports = pick_ports(); | 170 | + let (server, ports) = boot_forge(&dir, WEBHOOK_TOML, &[TAHINLI_CMD]).await; |
| 240 | - let config = write_config_with(&dir, ports, WEBHOOK_TOML); | | |
| 241 | - | | |
| 242 | - run_admin(&config, "tahinli", &["--admin"], TAHINLI_PW); | | |
| 243 | - let (server, ports) = launch_with(&dir, ports, WEBHOOK_TOML).await; | | |
| 244 | Booted { | 171 | Booted { |
| 245 | _server: server, | 172 | _server: server, |
| 246 | _root: root, | 173 | _root: root, |
| @@ -257,7 +184,7 @@ fn server_log(b: &Booted) -> String { |
| 257 | #[tokio::test] | 184 | #[tokio::test] |
| 258 | async fn pull_and_push_mirrors_sync_over_smart_http() { | 185 | async fn pull_and_push_mirrors_sync_over_smart_http() { |
| 259 | let b = boot().await; | 186 | let b = boot().await; |
| 260 | - let session = login(&b.http, "tahinli", TAHINLI_PW).await; | 187 | + let session = login(&b.http, "tahinli", PW).await; |
| 261 | let token = create_token(&b.http, &session, "mirror-token").await; | 188 | let token = create_token(&b.http, &session, "mirror-token").await; |
| 262 | let port = b.http_port; | 189 | let port = b.http_port; |
| 263 | | 190 | |
| @@ -1,5 +1,4 @@ |
| 1 | -use crate::common::{Server, bin, describe, launch, pick_ports, tool_on_path, write_config}; | 1 | +use crate::common::{Server, describe, launch, provision, tool_on_path}; |
| 2 | -use std::path::Path; | | |
| 3 | use std::process::Command; | 2 | use std::process::Command; |
| 4 | use std::time::Duration; | 3 | use std::time::Duration; |
| 5 | | 4 | |
| @@ -8,7 +7,6 @@ use forge_core::token::{generate_token, hash_token}; |
| 8 | use forge_core::{Store, User}; | 7 | use forge_core::{Store, User}; |
| 9 | use sha2::{Digest, Sha256}; | 8 | use sha2::{Digest, Sha256}; |
| 10 | | 9 | |
| 11 | -const PW: &str = "tahinli-password-123"; | | |
| 12 | const MANIFEST_TYPE: &str = "application/vnd.oci.image.manifest.v1+json"; | 10 | const MANIFEST_TYPE: &str = "application/vnd.oci.image.manifest.v1+json"; |
| 13 | | 11 | |
| 14 | struct Resp { | 12 | struct Resp { |
| @@ -107,22 +105,6 @@ impl Http { |
| 107 | } | 105 | } |
| 108 | } | 106 | } |
| 109 | | 107 | |
| 110 | -fn admin(config: &Path, args: &[&str]) { | | |
| 111 | - let out = Command::new(bin()) | | |
| 112 | - .arg("--config") | | |
| 113 | - .arg(config) | | |
| 114 | - .arg("admin") | | |
| 115 | - .args(args) | | |
| 116 | - .env("FORGE_PASSWORD", PW) | | |
| 117 | - .output() | | |
| 118 | - .expect("run admin command"); | | |
| 119 | - assert!( | | |
| 120 | - out.status.success(), | | |
| 121 | - "admin {args:?} failed:\n{}", | | |
| 122 | - describe(&out) | | |
| 123 | - ); | | |
| 124 | -} | | |
| 125 | - | | |
| 126 | struct Env { | 108 | struct Env { |
| 127 | _root: tempfile::TempDir, | 109 | _root: tempfile::TempDir, |
| 128 | _server: Server, | 110 | _server: Server, |
| @@ -135,15 +117,13 @@ where |
| 135 | F: FnOnce(Store) -> Fut, | 117 | F: FnOnce(Store) -> Fut, |
| 136 | Fut: std::future::Future<Output = ()>, | 118 | Fut: std::future::Future<Output = ()>, |
| 137 | { | 119 | { |
| 138 | - let root = tempfile::Builder::new() | 120 | + let root = crate::common::temp_dir("foci"); |
| 139 | - .prefix("foci") | | |
| 140 | - .tempdir_in("/tmp") | | |
| 141 | - .expect("temp dir"); | | |
| 142 | let dir = root.path().to_path_buf(); | 121 | let dir = root.path().to_path_buf(); |
| 143 | - let ports = pick_ports(); | 122 | + let (_, ports) = provision( |
| 144 | - let config = write_config(&dir, ports); | 123 | + &dir, |
| 145 | - admin(&config, &["create-user", "tahinli"]); | 124 | + "", |
| 146 | - admin(&config, &["create-user", "bob"]); | 125 | + &[&["create-user", "tahinli"], &["create-user", "bob"]], |
| | 126 | + ); |
| 147 | let store = Store::open(&dir.join("forge.db")) | 127 | let store = Store::open(&dir.join("forge.db")) |
| 148 | .await | 128 | .await |
| 149 | .expect("open store"); | 129 | .expect("open store"); |
| @@ -1,9 +1,5 @@ |
| 1 | -use crate::common::{ | 1 | +use crate::common::{Http, PW, Resp, Server, cookie_named, input_value, launch, provision}; |
| 2 | - Http, Resp, Server, bin, cookie_named, describe, input_value, launch, pick_ports, write_config, | | |
| 3 | -}; | | |
| 4 | use std::future::Future; | 2 | use std::future::Future; |
| 5 | -use std::path::Path; | | |
| 6 | -use std::process::Command; | | |
| 7 | use std::time::Duration; | 3 | use std::time::Duration; |
| 8 | | 4 | |
| 9 | use forge_core::token::hash_token; | 5 | use forge_core::token::hash_token; |
| @@ -12,26 +8,9 @@ use forge_core::{Store, Visibility}; |
| 12 | static SERIAL: std::sync::LazyLock<tokio::sync::Mutex<()>> = | 8 | static SERIAL: std::sync::LazyLock<tokio::sync::Mutex<()>> = |
| 13 | std::sync::LazyLock::new(|| tokio::sync::Mutex::new(())); | 9 | std::sync::LazyLock::new(|| tokio::sync::Mutex::new(())); |
| 14 | | 10 | |
| 15 | -const PW: &str = "tahinli-password-123"; | | |
| 16 | const ORG_TOKEN: &str = "forge_org_token_for_tests_0123456789"; | 11 | const ORG_TOKEN: &str = "forge_org_token_for_tests_0123456789"; |
| 17 | const ORG_SESSION: &str = "org-session-token-for-tests-0123456789"; | 12 | const ORG_SESSION: &str = "org-session-token-for-tests-0123456789"; |
| 18 | | 13 | |
| 19 | -fn admin(config: &Path, args: &[&str]) { | | |
| 20 | - let out = Command::new(bin()) | | |
| 21 | - .arg("--config") | | |
| 22 | - .arg(config) | | |
| 23 | - .arg("admin") | | |
| 24 | - .args(args) | | |
| 25 | - .env("FORGE_PASSWORD", PW) | | |
| 26 | - .output() | | |
| 27 | - .expect("run admin command"); | | |
| 28 | - assert!( | | |
| 29 | - out.status.success(), | | |
| 30 | - "admin {args:?} failed:\n{}", | | |
| 31 | - describe(&out) | | |
| 32 | - ); | | |
| 33 | -} | | |
| 34 | - | | |
| 35 | async fn try_login(http: &Http, username: &str) -> Resp { | 14 | async fn try_login(http: &Http, username: &str) -> Resp { |
| 36 | let page = http.get("/login", None).await; | 15 | let page = http.get("/login", None).await; |
| 37 | assert_eq!(page.status, 200, "GET /login"); | 16 | assert_eq!(page.status, 200, "GET /login"); |
| @@ -63,11 +42,11 @@ where |
| 63 | { | 42 | { |
| 64 | let root = tempfile::tempdir().expect("temp dir"); | 43 | let root = tempfile::tempdir().expect("temp dir"); |
| 65 | let dir = root.path().to_path_buf(); | 44 | let dir = root.path().to_path_buf(); |
| 66 | - let ports = pick_ports(); | 45 | + let (_, ports) = provision( |
| 67 | - let config = write_config(&dir, ports); | 46 | + &dir, |
| 68 | - for user in ["dana", "tahinli"] { | 47 | + "", |
| 69 | - admin(&config, &["create-user", user]); | 48 | + &[&["create-user", "dana"], &["create-user", "tahinli"]], |
| 70 | - } | 49 | + ); |
| 71 | let store = Store::open(&dir.join("forge.db")) | 50 | let store = Store::open(&dir.join("forge.db")) |
| 72 | .await | 51 | .await |
| 73 | .expect("open store"); | 52 | .expect("open store"); |
| @@ -1,9 +1,7 @@ |
| 1 | use crate::common::{ | 1 | use crate::common::{ |
| 2 | - Http, bin, describe, input_value, launch, login, pick_ports, tool_on_path, write_config, | 2 | + Http, PW, assert_quiet, csrf_for, init_bare, launch, login, next_changed, provision, temp_dir, |
| | 3 | + tool_on_path, |
| 3 | }; | 4 | }; |
| 4 | -use std::path::Path; | | |
| 5 | -use std::process::{Command, Output}; | | |
| 6 | -use std::time::Duration; | | |
| 7 | | 5 | |
| 8 | use forge_core::store::orgs::{DefaultRepoRole, OrgMemberRole, OrgSettings}; | 6 | use forge_core::store::orgs::{DefaultRepoRole, OrgMemberRole, OrgSettings}; |
| 9 | use forge_core::{Role, Store, Visibility}; | 7 | use forge_core::{Role, Store, Visibility}; |
| @@ -11,8 +9,6 @@ use forge_core::{Role, Store, Visibility}; |
| 11 | static SERIAL: std::sync::LazyLock<tokio::sync::Mutex<()>> = | 9 | static SERIAL: std::sync::LazyLock<tokio::sync::Mutex<()>> = |
| 12 | std::sync::LazyLock::new(|| tokio::sync::Mutex::new(())); | 10 | std::sync::LazyLock::new(|| tokio::sync::Mutex::new(())); |
| 13 | | 11 | |
| 14 | -const PW: &str = "tahinli-password-123"; | | |
| 15 | - | | |
| 16 | fn live_url(body: &str) -> Option<String> { | 12 | fn live_url(body: &str) -> Option<String> { |
| 17 | let doc = scraper::Html::parse_document(body); | 13 | let doc = scraper::Html::parse_document(body); |
| 18 | let selector = scraper::Selector::parse("[data-live]").expect("selector"); | 14 | let selector = scraper::Selector::parse("[data-live]").expect("selector"); |
| @@ -22,51 +18,6 @@ fn live_url(body: &str) -> Option<String> { |
| 22 | .map(str::to_owned) | 18 | .map(str::to_owned) |
| 23 | } | 19 | } |
| 24 | | 20 | |
| 25 | -fn admin(config: &Path, args: &[&str]) -> Output { | | |
| 26 | - let out = Command::new(bin()) | | |
| 27 | - .arg("--config") | | |
| 28 | - .arg(config) | | |
| 29 | - .arg("admin") | | |
| 30 | - .args(args) | | |
| 31 | - .env("FORGE_PASSWORD", PW) | | |
| 32 | - .output() | | |
| 33 | - .expect("run admin command"); | | |
| 34 | - assert!( | | |
| 35 | - out.status.success(), | | |
| 36 | - "admin {args:?} failed:\n{}", | | |
| 37 | - describe(&out) | | |
| 38 | - ); | | |
| 39 | - out | | |
| 40 | -} | | |
| 41 | - | | |
| 42 | -async fn csrf_for(http: &Http, session: &str) -> String { | | |
| 43 | - let page = http.get("/settings/keys", Some(session)).await; | | |
| 44 | - assert_eq!(page.status, 200, "GET /settings/keys"); | | |
| 45 | - input_value(&page.body, "csrf") | | |
| 46 | -} | | |
| 47 | - | | |
| 48 | -async fn next_changed(res: &mut reqwest::Response, what: &str) { | | |
| 49 | - let chunk = tokio::time::timeout(Duration::from_secs(5), res.chunk()) | | |
| 50 | - .await | | |
| 51 | - .unwrap_or_else(|_| panic!("no event after {what}")) | | |
| 52 | - .expect("stream chunk") | | |
| 53 | - .expect("stream still open"); | | |
| 54 | - let text = String::from_utf8_lossy(&chunk); | | |
| 55 | - assert!(text.contains("event: changed"), "{what}: {text}"); | | |
| 56 | -} | | |
| 57 | - | | |
| 58 | -async fn assert_quiet(res: &mut reqwest::Response, what: &str) { | | |
| 59 | - let got = tokio::time::timeout(Duration::from_secs(2), res.chunk()).await; | | |
| 60 | - assert!(got.is_err(), "{what}: the stream sent an event"); | | |
| 61 | -} | | |
| 62 | - | | |
| 63 | -fn short_temp_dir() -> tempfile::TempDir { | | |
| 64 | - tempfile::Builder::new() | | |
| 65 | - .prefix("orgl") | | |
| 66 | - .tempdir_in("/tmp") | | |
| 67 | - .expect("temp dir") | | |
| 68 | -} | | |
| 69 | - | | |
| 70 | #[tokio::test] | 21 | #[tokio::test] |
| 71 | async fn org_pages_follow_writes_live_and_refuse_outsiders() { | 22 | async fn org_pages_follow_writes_live_and_refuse_outsiders() { |
| 72 | let _guard = SERIAL.lock().await; | 23 | let _guard = SERIAL.lock().await; |
| @@ -74,15 +25,18 @@ async fn org_pages_follow_writes_live_and_refuse_outsiders() { |
| 74 | eprintln!("SKIP orgs_live_e2e: `git` was not found on PATH"); | 25 | eprintln!("SKIP orgs_live_e2e: `git` was not found on PATH"); |
| 75 | return; | 26 | return; |
| 76 | } | 27 | } |
| 77 | - let root = short_temp_dir(); | 28 | + let root = temp_dir("orgl"); |
| 78 | let dir = root.path().to_path_buf(); | 29 | let dir = root.path().to_path_buf(); |
| 79 | - let ports = pick_ports(); | 30 | + let (_, ports) = provision( |
| 80 | - let config = write_config(&dir, ports); | 31 | + &dir, |
| 81 | - | 32 | + "", |
| 82 | - admin(&config, &["create-user", "tahinli", "--admin"]); | 33 | + &[ |
| 83 | - for name in ["bob", "carol", "dana"] { | 34 | + &["create-user", "tahinli", "--admin"], |
| 84 | - admin(&config, &["create-user", name]); | 35 | + &["create-user", "bob"], |
| 85 | - } | 36 | + &["create-user", "carol"], |
| | 37 | + &["create-user", "dana"], |
| | 38 | + ], |
| | 39 | + ); |
| 86 | | 40 | |
| 87 | { | 41 | { |
| 88 | let store = Store::open(&dir.join("forge.db")) | 42 | let store = Store::open(&dir.join("forge.db")) |
| @@ -106,7 +60,7 @@ async fn org_pages_follow_writes_live_and_refuse_outsiders() { |
| 106 | let tahinli = login(&http, "tahinli", PW).await; | 60 | let tahinli = login(&http, "tahinli", PW).await; |
| 107 | let bob = login(&http, "bob", PW).await; | 61 | let bob = login(&http, "bob", PW).await; |
| 108 | let dana = login(&http, "dana", PW).await; | 62 | let dana = login(&http, "dana", PW).await; |
| 109 | - let csrf = csrf_for(&http, &tahinli).await; | 63 | + let csrf = csrf_for(&http, "/settings/keys", &tahinli).await; |
| 110 | | 64 | |
| 111 | let members = http.get("/org/acme/members", Some(&tahinli)).await; | 65 | let members = http.get("/org/acme/members", Some(&tahinli)).await; |
| 112 | assert_eq!(members.status, 200, "GET members"); | 66 | assert_eq!(members.status, 200, "GET members"); |
| @@ -224,17 +178,6 @@ async fn org_pages_follow_writes_live_and_refuse_outsiders() { |
| 224 | next_changed(&mut bob_members, "adding dana").await; | 178 | next_changed(&mut bob_members, "adding dana").await; |
| 225 | } | 179 | } |
| 226 | | 180 | |
| 227 | -fn init_bare(data_dir: &Path, repo_id: &str) { | | |
| 228 | - let path = forge_git::repo::repo_path(data_dir, repo_id).expect("repo path"); | | |
| 229 | - std::fs::create_dir_all(path.parent().expect("parent")).expect("create repo parent"); | | |
| 230 | - let out = Command::new("git") | | |
| 231 | - .args(["init", "--bare", "--quiet"]) | | |
| 232 | - .arg(&path) | | |
| 233 | - .output() | | |
| 234 | - .expect("run git init"); | | |
| 235 | - assert!(out.status.success(), "git init --bare: {}", describe(&out)); | | |
| 236 | -} | | |
| 237 | - | | |
| 238 | #[tokio::test] | 181 | #[tokio::test] |
| 239 | async fn private_linked_repo_is_hidden_from_a_viewer_who_cannot_read_it() { | 182 | async fn private_linked_repo_is_hidden_from_a_viewer_who_cannot_read_it() { |
| 240 | let _guard = SERIAL.lock().await; | 183 | let _guard = SERIAL.lock().await; |
| @@ -242,13 +185,16 @@ async fn private_linked_repo_is_hidden_from_a_viewer_who_cannot_read_it() { |
| 242 | eprintln!("SKIP orgs_live_e2e: `git` was not found on PATH"); | 185 | eprintln!("SKIP orgs_live_e2e: `git` was not found on PATH"); |
| 243 | return; | 186 | return; |
| 244 | } | 187 | } |
| 245 | - let root = short_temp_dir(); | 188 | + let root = temp_dir("orgl"); |
| 246 | let dir = root.path().to_path_buf(); | 189 | let dir = root.path().to_path_buf(); |
| 247 | - let ports = pick_ports(); | 190 | + let (_, ports) = provision( |
| 248 | - let config = write_config(&dir, ports); | 191 | + &dir, |
| 249 | - | 192 | + "", |
| 250 | - admin(&config, &["create-user", "tahinli", "--admin"]); | 193 | + &[ |
| 251 | - admin(&config, &["create-user", "bob"]); | 194 | + &["create-user", "tahinli", "--admin"], |
| | 195 | + &["create-user", "bob"], |
| | 196 | + ], |
| | 197 | + ); |
| 252 | | 198 | |
| 253 | let team_id = { | 199 | let team_id = { |
| 254 | let store = Store::open(&dir.join("forge.db")) | 200 | let store = Store::open(&dir.join("forge.db")) |
| @@ -295,7 +241,7 @@ async fn private_linked_repo_is_hidden_from_a_viewer_who_cannot_read_it() { |
| 295 | let http = Http::new(ports.http); | 241 | let http = Http::new(ports.http); |
| 296 | let tahinli = login(&http, "tahinli", PW).await; | 242 | let tahinli = login(&http, "tahinli", PW).await; |
| 297 | let bob = login(&http, "bob", PW).await; | 243 | let bob = login(&http, "bob", PW).await; |
| 298 | - let csrf = csrf_for(&http, &tahinli).await; | 244 | + let csrf = csrf_for(&http, "/settings/keys", &tahinli).await; |
| 299 | let team_page = format!("/org/acme/teams/{team_id}"); | 245 | let team_page = format!("/org/acme/teams/{team_id}"); |
| 300 | | 246 | |
| 301 | let owner_view = http.get(&team_page, Some(&tahinli)).await; | 247 | let owner_view = http.get(&team_page, Some(&tahinli)).await; |
| @@ -1,10 +1,7 @@ |
| 1 | use crate::common::{ | 1 | use crate::common::{ |
| 2 | - Http, Resp, bin, describe, input_value, launch, launch_with, login, pick_ports, temp_dir, | 2 | + Http, PW, Resp, attr_of, attr_values, boot_forge, commit_file, create_token, csrf_for, |
| 3 | - tool_on_path, write_config, | 3 | + describe, git, init_bare, launch, login, provision, temp_dir, tool_on_path, |
| 4 | }; | 4 | }; |
| 5 | -use std::fs; | | |
| 6 | -use std::path::Path; | | |
| 7 | -use std::process::{Command, Output}; | | |
| 8 | | 5 | |
| 9 | use forge_core::store::orgs::{DefaultRepoRole, OrgMemberRole, OrgSettings}; | 6 | use forge_core::store::orgs::{DefaultRepoRole, OrgMemberRole, OrgSettings}; |
| 10 | use forge_core::{Role, Store, Visibility}; | 7 | use forge_core::{Role, Store, Visibility}; |
| @@ -13,60 +10,6 @@ use reqwest::header::LOCATION; |
| 13 | static SERIAL: std::sync::LazyLock<tokio::sync::Mutex<()>> = | 10 | static SERIAL: std::sync::LazyLock<tokio::sync::Mutex<()>> = |
| 14 | std::sync::LazyLock::new(|| tokio::sync::Mutex::new(())); | 11 | std::sync::LazyLock::new(|| tokio::sync::Mutex::new(())); |
| 15 | | 12 | |
| 16 | -const PW: &str = "tahinli-password-123"; | | |
| 17 | - | | |
| 18 | -fn selected_value(body: &str, name: &str) -> Option<String> { | | |
| 19 | - let doc = scraper::Html::parse_document(body); | | |
| 20 | - let selector = scraper::Selector::parse(&format!("select[name=\"{name}\"] option[selected]")) | | |
| 21 | - .expect("selector"); | | |
| 22 | - doc.select(&selector) | | |
| 23 | - .next() | | |
| 24 | - .and_then(|el| el.value().attr("value")) | | |
| 25 | - .map(str::to_owned) | | |
| 26 | -} | | |
| 27 | - | | |
| 28 | -fn owner_options(body: &str) -> Vec<String> { | | |
| 29 | - let doc = scraper::Html::parse_document(body); | | |
| 30 | - let selector = scraper::Selector::parse("select[name=\"owner\"] option").expect("selector"); | | |
| 31 | - doc.select(&selector) | | |
| 32 | - .filter_map(|el| el.value().attr("value").map(str::to_owned)) | | |
| 33 | - .collect() | | |
| 34 | -} | | |
| 35 | - | | |
| 36 | -fn admin(config: &Path, args: &[&str]) -> Output { | | |
| 37 | - let out = Command::new(bin()) | | |
| 38 | - .arg("--config") | | |
| 39 | - .arg(config) | | |
| 40 | - .arg("admin") | | |
| 41 | - .args(args) | | |
| 42 | - .env("FORGE_PASSWORD", PW) | | |
| 43 | - .output() | | |
| 44 | - .expect("run admin command"); | | |
| 45 | - assert!( | | |
| 46 | - out.status.success(), | | |
| 47 | - "admin {args:?} failed:\n{}", | | |
| 48 | - describe(&out) | | |
| 49 | - ); | | |
| 50 | - out | | |
| 51 | -} | | |
| 52 | - | | |
| 53 | -async fn csrf_for(http: &Http, session: &str) -> String { | | |
| 54 | - let page = http.get("/settings/keys", Some(session)).await; | | |
| 55 | - assert_eq!(page.status, 200, "GET /settings/keys"); | | |
| 56 | - input_value(&page.body, "csrf") | | |
| 57 | -} | | |
| 58 | - | | |
| 59 | -fn init_bare(data_dir: &Path, repo_id: &str) { | | |
| 60 | - let path = forge_git::repo::repo_path(data_dir, repo_id).expect("repo path"); | | |
| 61 | - fs::create_dir_all(path.parent().expect("parent")).expect("create repo parent"); | | |
| 62 | - let out = Command::new("git") | | |
| 63 | - .args(["init", "--bare", "--quiet"]) | | |
| 64 | - .arg(&path) | | |
| 65 | - .output() | | |
| 66 | - .expect("run git init"); | | |
| 67 | - assert!(out.status.success(), "git init --bare: {}", describe(&out)); | | |
| 68 | -} | | |
| 69 | - | | |
| 70 | fn notice_location(redirect: &Resp) -> String { | 13 | fn notice_location(redirect: &Resp) -> String { |
| 71 | redirect.header(LOCATION).expect("notice redirect") | 14 | redirect.header(LOCATION).expect("notice redirect") |
| 72 | } | 15 | } |
| @@ -80,13 +23,17 @@ async fn org_members_teams_and_access_end_to_end() { |
| 80 | } | 23 | } |
| 81 | let root = temp_dir("forg"); | 24 | let root = temp_dir("forg"); |
| 82 | let dir = root.path().to_path_buf(); | 25 | let dir = root.path().to_path_buf(); |
| 83 | - let ports = pick_ports(); | 26 | + let (_, ports) = provision( |
| 84 | - let config = write_config(&dir, ports); | 27 | + &dir, |
| 85 | - | 28 | + "", |
| 86 | - admin(&config, &["create-user", "root", "--admin"]); | 29 | + &[ |
| 87 | - for name in ["tahinli", "bob", "carol", "dana"] { | 30 | + &["create-user", "root", "--admin"], |
| 88 | - admin(&config, &["create-user", name]); | 31 | + &["create-user", "tahinli"], |
| 89 | - } | 32 | + &["create-user", "bob"], |
| | 33 | + &["create-user", "carol"], |
| | 34 | + &["create-user", "dana"], |
| | 35 | + ], |
| | 36 | + ); |
| 90 | | 37 | |
| 91 | let (tahinli_id, team_id) = { | 38 | let (tahinli_id, team_id) = { |
| 92 | let store = Store::open(&dir.join("forge.db")) | 39 | let store = Store::open(&dir.join("forge.db")) |
| @@ -154,7 +101,7 @@ async fn org_members_teams_and_access_end_to_end() { |
| 154 | "members get no add form" | 101 | "members get no add form" |
| 155 | ); | 102 | ); |
| 156 | | 103 | |
| 157 | - let bob_csrf = csrf_for(&http, &bob).await; | 104 | + let bob_csrf = csrf_for(&http, "/settings/keys", &bob).await; |
| 158 | let res = http | 105 | let res = http |
| 159 | .post_form( | 106 | .post_form( |
| 160 | "/org/acme/members/add", | 107 | "/org/acme/members/add", |
| @@ -168,7 +115,7 @@ async fn org_members_teams_and_access_end_to_end() { |
| 168 | .await; | 115 | .await; |
| 169 | assert_eq!(res.status, 403, "member add is refused: {}", res.body); | 116 | assert_eq!(res.status, 403, "member add is refused: {}", res.body); |
| 170 | | 117 | |
| 171 | - let tahinli_csrf = csrf_for(&http, &tahinli).await; | 118 | + let tahinli_csrf = csrf_for(&http, "/settings/keys", &tahinli).await; |
| 172 | let res = http | 119 | let res = http |
| 173 | .post_form( | 120 | .post_form( |
| 174 | "/org/acme/members/add", | 121 | "/org/acme/members/add", |
| @@ -264,11 +211,15 @@ async fn org_members_teams_and_access_end_to_end() { |
| 264 | | 211 | |
| 265 | let tahinli_new = http.get("/new", Some(&tahinli)).await; | 212 | let tahinli_new = http.get("/new", Some(&tahinli)).await; |
| 266 | assert!( | 213 | assert!( |
| 267 | - owner_options(&tahinli_new.body).contains(&"acme".to_string()), | 214 | + attr_values(&tahinli_new.body, "select[name=\"owner\"] option", "value") |
| | 215 | + .contains(&"acme".to_string()), |
| 268 | "owner choice lists acme" | 216 | "owner choice lists acme" |
| 269 | ); | 217 | ); |
| 270 | let bob_new = http.get("/new", Some(&bob)).await; | 218 | let bob_new = http.get("/new", Some(&bob)).await; |
| 271 | - assert_eq!(owner_options(&bob_new.body), vec!["bob".to_string()]); | 219 | + assert_eq!( |
| | 220 | + attr_values(&bob_new.body, "select[name=\"owner\"] option", "value"), |
| | 221 | + vec!["bob".to_string()] |
| | 222 | + ); |
| 272 | let res = http | 223 | let res = http |
| 273 | .post_form( | 224 | .post_form( |
| 274 | "/new", | 225 | "/new", |
| @@ -299,13 +250,16 @@ async fn org_settings_delete_and_audit_end_to_end() { |
| 299 | } | 250 | } |
| 300 | let root = temp_dir("forg"); | 251 | let root = temp_dir("forg"); |
| 301 | let dir = root.path().to_path_buf(); | 252 | let dir = root.path().to_path_buf(); |
| 302 | - let ports = pick_ports(); | 253 | + let (_, ports) = provision( |
| 303 | - let config = write_config(&dir, ports); | 254 | + &dir, |
| 304 | - | 255 | + "", |
| 305 | - admin(&config, &["create-user", "root", "--admin"]); | 256 | + &[ |
| 306 | - for name in ["tahinli", "bob", "dana"] { | 257 | + &["create-user", "root", "--admin"], |
| 307 | - admin(&config, &["create-user", name]); | 258 | + &["create-user", "tahinli"], |
| 308 | - } | 259 | + &["create-user", "bob"], |
| | 260 | + &["create-user", "dana"], |
| | 261 | + ], |
| | 262 | + ); |
| 309 | { | 263 | { |
| 310 | let store = Store::open(&dir.join("forge.db")) | 264 | let store = Store::open(&dir.join("forge.db")) |
| 311 | .await | 265 | .await |
| @@ -347,7 +301,7 @@ async fn org_settings_delete_and_audit_end_to_end() { |
| 347 | "outsider" | 301 | "outsider" |
| 348 | ); | 302 | ); |
| 349 | | 303 | |
| 350 | - let csrf = csrf_for(&http, &tahinli).await; | 304 | + let csrf = csrf_for(&http, "/settings/keys", &tahinli).await; |
| 351 | let res = http | 305 | let res = http |
| 352 | .post_form( | 306 | .post_form( |
| 353 | settings, | 307 | settings, |
| @@ -371,7 +325,12 @@ async fn org_settings_delete_and_audit_end_to_end() { |
| 371 | "display name on the profile" | 325 | "display name on the profile" |
| 372 | ); | 326 | ); |
| 373 | assert_eq!( | 327 | assert_eq!( |
| 374 | - selected_value(&shown.body, "default_repo_role").as_deref(), | 328 | + attr_of( |
| | 329 | + &shown.body, |
| | 330 | + "select[name=\"default_repo_role\"] option[selected]", |
| | 331 | + "value" |
| | 332 | + ) |
| | 333 | + .as_deref(), |
| 375 | Some("write"), | 334 | Some("write"), |
| 376 | "default role saved" | 335 | "default role saved" |
| 377 | ); | 336 | ); |
| @@ -449,12 +408,15 @@ async fn org_creation_can_be_limited_to_admins() { |
| 449 | let _guard = SERIAL.lock().await; | 408 | let _guard = SERIAL.lock().await; |
| 450 | let root = temp_dir("forg"); | 409 | let root = temp_dir("forg"); |
| 451 | let dir = root.path().to_path_buf(); | 410 | let dir = root.path().to_path_buf(); |
| 452 | - let ports = pick_ports(); | 411 | + let (_server, ports) = boot_forge( |
| 453 | - let config = write_config(&dir, ports); | 412 | + &dir, |
| 454 | - admin(&config, &["create-user", "root", "--admin"]); | 413 | + "[orgs]\ncreation = \"admin\"\n", |
| 455 | - admin(&config, &["create-user", "tahinli"]); | 414 | + &[ |
| 456 | - | 415 | + &["create-user", "root", "--admin"], |
| 457 | - let (_server, ports) = launch_with(&dir, ports, "[orgs]\ncreation = \"admin\"\n").await; | 416 | + &["create-user", "tahinli"], |
| | 417 | + ], |
| | 418 | + ) |
| | 419 | + .await; |
| 458 | let http = Http::new(ports.http); | 420 | let http = Http::new(ports.http); |
| 459 | let tahinli = login(&http, "tahinli", PW).await; | 421 | let tahinli = login(&http, "tahinli", PW).await; |
| 460 | let root_session = login(&http, "root", PW).await; | 422 | let root_session = login(&http, "root", PW).await; |
| @@ -480,7 +442,7 @@ async fn org_creation_can_be_limited_to_admins() { |
| 480 | 403, | 442 | 403, |
| 481 | "a person may not create orgs under the admin policy" | 443 | "a person may not create orgs under the admin policy" |
| 482 | ); | 444 | ); |
| 483 | - let csrf = csrf_for(&http, &tahinli).await; | 445 | + let csrf = csrf_for(&http, "/settings/keys", &tahinli).await; |
| 484 | let res = http | 446 | let res = http |
| 485 | .post_form( | 447 | .post_form( |
| 486 | "/org/new", | 448 | "/org/new", |
| @@ -495,7 +457,7 @@ async fn org_creation_can_be_limited_to_admins() { |
| 495 | 200, | 457 | 200, |
| 496 | "an admin may create orgs" | 458 | "an admin may create orgs" |
| 497 | ); | 459 | ); |
| 498 | - let root_csrf = csrf_for(&http, &root_session).await; | 460 | + let root_csrf = csrf_for(&http, "/settings/keys", &root_session).await; |
| 499 | let res = http | 461 | let res = http |
| 500 | .post_form( | 462 | .post_form( |
| 501 | "/org/new", | 463 | "/org/new", |
| @@ -518,70 +480,6 @@ async fn org_creation_can_be_limited_to_admins() { |
| 518 | assert!(profile.body.contains("Organization"), "marked as an org"); | 480 | assert!(profile.body.contains("Organization"), "marked as an org"); |
| 519 | } | 481 | } |
| 520 | | 482 | |
| 521 | -fn git(cwd: &Path, args: &[&str]) -> Output { | | |
| 522 | - Command::new("git") | | |
| 523 | - .current_dir(cwd) | | |
| 524 | - .args(["-c", "credential.helper="]) | | |
| 525 | - .args(args) | | |
| 526 | - .env("GIT_TERMINAL_PROMPT", "0") | | |
| 527 | - .output() | | |
| 528 | - .expect("run git") | | |
| 529 | -} | | |
| 530 | - | | |
| 531 | -fn commit_file(repo: &Path, name: &str, content: &str) { | | |
| 532 | - fs::write(repo.join(name), content).expect("write file"); | | |
| 533 | - let out = git(repo, &["add", name]); | | |
| 534 | - assert!(out.status.success(), "git add: {}", describe(&out)); | | |
| 535 | - let out = git( | | |
| 536 | - repo, | | |
| 537 | - &[ | | |
| 538 | - "-c", | | |
| 539 | - "user.name=forge", | | |
| 540 | - "-c", | | |
| 541 | - "user.email=forge@example.test", | | |
| 542 | - "-c", | | |
| 543 | - "commit.gpgsign=false", | | |
| 544 | - "commit", | | |
| 545 | - "-q", | | |
| 546 | - "-m", | | |
| 547 | - "push over https", | | |
| 548 | - ], | | |
| 549 | - ); | | |
| 550 | - assert!(out.status.success(), "git commit: {}", describe(&out)); | | |
| 551 | -} | | |
| 552 | - | | |
| 553 | -async fn create_token(http: &Http, session: &str) -> String { | | |
| 554 | - let csrf = csrf_for(http, session).await; | | |
| 555 | - let res = http | | |
| 556 | - .post_form( | | |
| 557 | - "/settings/tokens", | | |
| 558 | - &[("csrf", &csrf), ("name", "e2e"), ("expires", "30")], | | |
| 559 | - Some(session), | | |
| 560 | - ) | | |
| 561 | - .await; | | |
| 562 | - assert_eq!(res.status, 200, "create token: {}", res.body); | | |
| 563 | - let doc = scraper::Html::parse_document(&res.body); | | |
| 564 | - let selector = scraper::Selector::parse("pre.code code").expect("selector"); | | |
| 565 | - doc.select(&selector) | | |
| 566 | - .next() | | |
| 567 | - .expect("token shown after creation") | | |
| 568 | - .text() | | |
| 569 | - .collect::<String>() | | |
| 570 | - .trim() | | |
| 571 | - .to_owned() | | |
| 572 | -} | | |
| 573 | - | | |
| 574 | -fn first_option(body: &str, name: &str) -> String { | | |
| 575 | - let doc = scraper::Html::parse_document(body); | | |
| 576 | - let selector = | | |
| 577 | - scraper::Selector::parse(&format!("select[name=\"{name}\"] option")).expect("selector"); | | |
| 578 | - doc.select(&selector) | | |
| 579 | - .next() | | |
| 580 | - .and_then(|el| el.value().attr("value")) | | |
| 581 | - .unwrap_or_else(|| panic!("no option in select {name}")) | | |
| 582 | - .to_owned() | | |
| 583 | -} | | |
| 584 | - | | |
| 585 | #[tokio::test] | 483 | #[tokio::test] |
| 586 | async fn org_member_pushes_over_https_through_a_write_team() { | 484 | async fn org_member_pushes_over_https_through_a_write_team() { |
| 587 | let _guard = SERIAL.lock().await; | 485 | let _guard = SERIAL.lock().await; |
| @@ -591,13 +489,16 @@ async fn org_member_pushes_over_https_through_a_write_team() { |
| 591 | } | 489 | } |
| 592 | let root = temp_dir("forg"); | 490 | let root = temp_dir("forg"); |
| 593 | let dir = root.path().to_path_buf(); | 491 | let dir = root.path().to_path_buf(); |
| 594 | - let ports = pick_ports(); | 492 | + let (_, ports) = provision( |
| 595 | - let config = write_config(&dir, ports); | 493 | + &dir, |
| 596 | - | 494 | + "", |
| 597 | - admin(&config, &["create-user", "root", "--admin"]); | 495 | + &[ |
| 598 | - for name in ["tahinli", "bob", "dana"] { | 496 | + &["create-user", "root", "--admin"], |
| 599 | - admin(&config, &["create-user", name]); | 497 | + &["create-user", "tahinli"], |
| 600 | - } | 498 | + &["create-user", "bob"], |
| | 499 | + &["create-user", "dana"], |
| | 500 | + ], |
| | 501 | + ); |
| 601 | { | 502 | { |
| 602 | let store = Store::open(&dir.join("forge.db")) | 503 | let store = Store::open(&dir.join("forge.db")) |
| 603 | .await | 504 | .await |
| @@ -631,7 +532,7 @@ async fn org_member_pushes_over_https_through_a_write_team() { |
| 631 | let bob = login(&http, "bob", PW).await; | 532 | let bob = login(&http, "bob", PW).await; |
| 632 | let dana = login(&http, "dana", PW).await; | 533 | let dana = login(&http, "dana", PW).await; |
| 633 | | 534 | |
| 634 | - let csrf = csrf_for(&http, &tahinli).await; | 535 | + let csrf = csrf_for(&http, "/settings/keys", &tahinli).await; |
| 635 | let res = http | 536 | let res = http |
| 636 | .post_form( | 537 | .post_form( |
| 637 | "/new", | 538 | "/new", |
| @@ -665,7 +566,8 @@ async fn org_member_pushes_over_https_through_a_write_team() { |
| 665 | let team_url = location.split('?').next().expect("team path").to_owned(); | 566 | let team_url = location.split('?').next().expect("team path").to_owned(); |
| 666 | let team = http.get(&team_url, Some(&tahinli)).await; | 567 | let team = http.get(&team_url, Some(&tahinli)).await; |
| 667 | assert_eq!(team.status, 200, "team page"); | 568 | assert_eq!(team.status, 200, "team page"); |
| 668 | - let repo_id = first_option(&team.body, "repo_id"); | 569 | + let repo_id = attr_of(&team.body, "select[name=\"repo_id\"] option", "value") |
| | 570 | + .expect("an option in select repo_id"); |
| 669 | let res = http | 571 | let res = http |
| 670 | .post_form( | 572 | .post_form( |
| 671 | &format!("{team_url}/repos/add"), | 573 | &format!("{team_url}/repos/add"), |
| @@ -683,8 +585,8 @@ async fn org_member_pushes_over_https_through_a_write_team() { |
| 683 | .await; | 585 | .await; |
| 684 | assert_eq!(res.status, 303, "bob joins writers"); | 586 | assert_eq!(res.status, 303, "bob joins writers"); |
| 685 | | 587 | |
| 686 | - let bob_token = create_token(&http, &bob).await; | 588 | + let bob_token = create_token(&http, &bob, "e2e").await; |
| 687 | - let dana_token = create_token(&http, &dana).await; | 589 | + let dana_token = create_token(&http, &dana, "e2e").await; |
| 688 | let bob_url = format!( | 590 | let bob_url = format!( |
| 689 | "http://bob:{bob_token}@127.0.0.1:{}/acme/pushme.git", | 591 | "http://bob:{bob_token}@127.0.0.1:{}/acme/pushme.git", |
| 690 | ports.http | 592 | ports.http |
| @@ -701,7 +603,7 @@ async fn org_member_pushes_over_https_through_a_write_team() { |
| 701 | let work_str = work.to_str().expect("utf8 path"); | 603 | let work_str = work.to_str().expect("utf8 path"); |
| 702 | let clone = git(&dir, &["clone", &bob_url, work_str]); | 604 | let clone = git(&dir, &["clone", &bob_url, work_str]); |
| 703 | assert!(clone.status.success(), "bob clones: {}", describe(&clone)); | 605 | assert!(clone.status.success(), "bob clones: {}", describe(&clone)); |
| 704 | - commit_file(&work, "hello.txt", "hello over https\n"); | 606 | + commit_file(&work, "hello.txt", "hello over https\n", "push over https"); |
| 705 | let push = git(&work, &["push", "origin", "HEAD:main"]); | 607 | let push = git(&work, &["push", "origin", "HEAD:main"]); |
| 706 | assert!(push.status.success(), "bob pushes: {}", describe(&push)); | 608 | assert!(push.status.success(), "bob pushes: {}", describe(&push)); |
| 707 | } | 609 | } |
| @@ -1,4 +1,4 @@ |
| 1 | -use crate::common::{Server, bin, describe, launch, pick_ports, write_config}; | 1 | +use crate::common::{Server, launch, provision}; |
| 2 | use std::io::Write; | 2 | use std::io::Write; |
| 3 | use std::path::Path; | 3 | use std::path::Path; |
| 4 | use std::process::Command; | 4 | use std::process::Command; |
| @@ -9,8 +9,6 @@ use forge_core::token::{generate_token, hash_token}; |
| 9 | use forge_core::{Store, User}; | 9 | use forge_core::{Store, User}; |
| 10 | use sha2::{Digest, Sha256}; | 10 | use sha2::{Digest, Sha256}; |
| 11 | | 11 | |
| 12 | -const PW: &str = "tahinli-password-123"; | | |
| 13 | - | | |
| 14 | const DEMO_INDEX: &str = "/api/packages/tahinli/cargo/de/mo/demo-crate"; | 12 | const DEMO_INDEX: &str = "/api/packages/tahinli/cargo/de/mo/demo-crate"; |
| 15 | const PUBLISH: &str = "/api/packages/tahinli/cargo/api/v1/crates/new"; | 13 | const PUBLISH: &str = "/api/packages/tahinli/cargo/api/v1/crates/new"; |
| 16 | | 14 | |
| @@ -81,22 +79,6 @@ impl Http { |
| 81 | } | 79 | } |
| 82 | } | 80 | } |
| 83 | | 81 | |
| 84 | -fn admin(config: &Path, args: &[&str]) { | | |
| 85 | - let out = Command::new(bin()) | | |
| 86 | - .arg("--config") | | |
| 87 | - .arg(config) | | |
| 88 | - .arg("admin") | | |
| 89 | - .args(args) | | |
| 90 | - .env("FORGE_PASSWORD", PW) | | |
| 91 | - .output() | | |
| 92 | - .expect("run admin command"); | | |
| 93 | - assert!( | | |
| 94 | - out.status.success(), | | |
| 95 | - "admin {args:?} failed:\n{}", | | |
| 96 | - describe(&out) | | |
| 97 | - ); | | |
| 98 | -} | | |
| 99 | - | | |
| 100 | struct Env { | 82 | struct Env { |
| 101 | _root: tempfile::TempDir, | 83 | _root: tempfile::TempDir, |
| 102 | _server: Server, | 84 | _server: Server, |
| @@ -108,15 +90,13 @@ where |
| 108 | F: FnOnce(Store) -> Fut, | 90 | F: FnOnce(Store) -> Fut, |
| 109 | Fut: std::future::Future<Output = ()>, | 91 | Fut: std::future::Future<Output = ()>, |
| 110 | { | 92 | { |
| 111 | - let root = tempfile::Builder::new() | 93 | + let root = crate::common::temp_dir("fpk"); |
| 112 | - .prefix("fpk") | | |
| 113 | - .tempdir_in("/tmp") | | |
| 114 | - .expect("temp dir"); | | |
| 115 | let dir = root.path().to_path_buf(); | 94 | let dir = root.path().to_path_buf(); |
| 116 | - let ports = pick_ports(); | 95 | + let (_, ports) = provision( |
| 117 | - let config = write_config(&dir, ports); | 96 | + &dir, |
| 118 | - admin(&config, &["create-user", "tahinli"]); | 97 | + "", |
| 119 | - admin(&config, &["create-user", "bob"]); | 98 | + &[&["create-user", "tahinli"], &["create-user", "bob"]], |
| | 99 | + ); |
| 120 | let store = Store::open(&dir.join("forge.db")) | 100 | let store = Store::open(&dir.join("forge.db")) |
| 121 | .await | 101 | .await |
| 122 | .expect("open store"); | 102 | .expect("open store"); |
| @@ -1,85 +1,25 @@ |
| 1 | use crate::common::{ | 1 | use crate::common::{ |
| 2 | - Http, Resp, Server, create_token, input_value, launch, login, pick_ports, run_admin, | 2 | + BOB_CMD, Http, PW, Resp, Server, TAHINLI_CMD, assert_quiet, boot_forge, clone, commit, |
| 3 | - tool_on_path, write_config, | 3 | + create_repo, create_token, csrf_for, git_text, login, next_changed, temp_dir, text_or_empty, |
| | 4 | + tool_on_path, |
| 4 | }; | 5 | }; |
| 5 | use std::fs; | 6 | use std::fs; |
| 6 | use std::path::{Path, PathBuf}; | 7 | use std::path::{Path, PathBuf}; |
| 7 | -use std::process::{Command, Output}; | | |
| 8 | use std::time::{Duration, Instant}; | 8 | use std::time::{Duration, Instant}; |
| 9 | | 9 | |
| 10 | -use reqwest::header::{AUTHORIZATION, CONTENT_TYPE, COOKIE}; | 10 | +use reqwest::header::{AUTHORIZATION, CONTENT_TYPE}; |
| 11 | | 11 | |
| 12 | -const TAHINLI_PW: &str = "tahinli-password-123"; | | |
| 13 | -const BOB_PW: &str = "bob-password-4567"; | | |
| 14 | const BOB_EMAIL: &str = "bob@users.noreply.127.0.0.1"; | 12 | const BOB_EMAIL: &str = "bob@users.noreply.127.0.0.1"; |
| 15 | const REPO_PATH: &str = "/tahinli/r"; | 13 | const REPO_PATH: &str = "/tahinli/r"; |
| 16 | const TAHINLI: (&str, &str) = ("tahinli", "tahinli@example.test"); | 14 | const TAHINLI: (&str, &str) = ("tahinli", "tahinli@example.test"); |
| 17 | const BOB: (&str, &str) = ("bob", BOB_EMAIL); | 15 | const BOB: (&str, &str) = ("bob", BOB_EMAIL); |
| 18 | | 16 | |
| 19 | -fn state_badge(body: &str) -> String { | | |
| 20 | - let doc = scraper::Html::parse_document(body); | | |
| 21 | - let selector = | | |
| 22 | - scraper::Selector::parse(".head-sub > .badge, .head-sub > .issue-badge").expect("selector"); | | |
| 23 | - doc.select(&selector) | | |
| 24 | - .next() | | |
| 25 | - .map(|el| el.text().collect::<String>().trim().to_owned()) | | |
| 26 | - .unwrap_or_default() | | |
| 27 | -} | | |
| 28 | - | | |
| 29 | -fn git_env(cwd: &Path, args: &[&str], env: &[(&str, &str)]) -> String { | | |
| 30 | - let mut cmd = Command::new("git"); | | |
| 31 | - cmd.current_dir(cwd) | | |
| 32 | - .args(["-c", "credential.helper="]) | | |
| 33 | - .args(args) | | |
| 34 | - .env("GIT_TERMINAL_PROMPT", "0"); | | |
| 35 | - for (key, value) in env { | | |
| 36 | - cmd.env(key, value); | | |
| 37 | - } | | |
| 38 | - let out: Output = cmd.output().expect("run git"); | | |
| 39 | - assert!( | | |
| 40 | - out.status.success(), | | |
| 41 | - "git {args:?} failed:\n{}", | | |
| 42 | - String::from_utf8_lossy(&out.stderr) | | |
| 43 | - ); | | |
| 44 | - String::from_utf8_lossy(&out.stdout).trim().to_owned() | | |
| 45 | -} | | |
| 46 | - | | |
| 47 | -fn git(cwd: &Path, args: &[&str]) -> String { | | |
| 48 | - git_env(cwd, args, &[]) | | |
| 49 | -} | | |
| 50 | - | | |
| 51 | -fn commit(repo: &Path, file: &str, contents: &str, message: &str, who: (&str, &str)) -> String { | | |
| 52 | - let (name, email) = who; | | |
| 53 | - fs::write(repo.join(file), contents).expect("write file"); | | |
| 54 | - git(repo, &["add", file]); | | |
| 55 | - git_env( | | |
| 56 | - repo, | | |
| 57 | - &["-c", "commit.gpgsign=false", "commit", "-q", "-m", message], | | |
| 58 | - &[ | | |
| 59 | - ("GIT_AUTHOR_NAME", name), | | |
| 60 | - ("GIT_AUTHOR_EMAIL", email), | | |
| 61 | - ("GIT_COMMITTER_NAME", name), | | |
| 62 | - ("GIT_COMMITTER_EMAIL", email), | | |
| 63 | - ], | | |
| 64 | - ); | | |
| 65 | - git(repo, &["rev-parse", "HEAD"]) | | |
| 66 | -} | | |
| 67 | - | | |
| 68 | -fn clone(url: &str, into: &Path) -> PathBuf { | | |
| 69 | - let parent = into.parent().expect("clone target has a parent"); | | |
| 70 | - git( | | |
| 71 | - parent, | | |
| 72 | - &["clone", "-q", url, into.to_str().expect("utf-8 path")], | | |
| 73 | - ); | | |
| 74 | - into.to_path_buf() | | |
| 75 | -} | | |
| 76 | - | | |
| 77 | fn remote(port: u16, user: &str, token: &str, owner: &str, repo: &str) -> String { | 17 | fn remote(port: u16, user: &str, token: &str, owner: &str, repo: &str) -> String { |
| 78 | format!("http://{user}:{token}@127.0.0.1:{port}/{owner}/{repo}.git") | 18 | format!("http://{user}:{token}@127.0.0.1:{port}/{owner}/{repo}.git") |
| 79 | } | 19 | } |
| 80 | | 20 | |
| 81 | fn remote_sha(dir: &Path, url: &str, branch: &str) -> String { | 21 | fn remote_sha(dir: &Path, url: &str, branch: &str) -> String { |
| 82 | - let out = git(dir, &["ls-remote", url, &format!("refs/heads/{branch}")]); | 22 | + let out = git_text(dir, &["ls-remote", url, &format!("refs/heads/{branch}")]); |
| 83 | out.split_whitespace() | 23 | out.split_whitespace() |
| 84 | .next() | 24 | .next() |
| 85 | .unwrap_or_else(|| panic!("branch {branch} missing on remote")) | 25 | .unwrap_or_else(|| panic!("branch {branch} missing on remote")) |
| @@ -87,40 +27,10 @@ fn remote_sha(dir: &Path, url: &str, branch: &str) -> String { |
| 87 | } | 27 | } |
| 88 | | 28 | |
| 89 | fn parent_count(dir: &Path, commit: &str) -> usize { | 29 | fn parent_count(dir: &Path, commit: &str) -> usize { |
| 90 | - let line = git(dir, &["rev-list", "--parents", "-n1", commit]); | 30 | + let line = git_text(dir, &["rev-list", "--parents", "-n1", commit]); |
| 91 | line.split_whitespace().count() - 1 | 31 | line.split_whitespace().count() - 1 |
| 92 | } | 32 | } |
| 93 | | 33 | |
| 94 | -async fn csrf_token(http: &Http, session: &str) -> String { | | |
| 95 | - let page = http.get_cookie("/settings/keys", session).await; | | |
| 96 | - assert_eq!(page.status, 200, "GET /settings/keys"); | | |
| 97 | - input_value(&page.body, "csrf") | | |
| 98 | -} | | |
| 99 | - | | |
| 100 | -async fn create_repo(http: &Http, session: &str, name: &str) { | | |
| 101 | - let page = http.get_cookie("/new", session).await; | | |
| 102 | - assert_eq!(page.status, 200, "GET /new"); | | |
| 103 | - let csrf = input_value(&page.body, "csrf"); | | |
| 104 | - let res = http | | |
| 105 | - .post_form( | | |
| 106 | - "/new", | | |
| 107 | - &[ | | |
| 108 | - ("csrf", &csrf), | | |
| 109 | - ("name", name), | | |
| 110 | - ("description", ""), | | |
| 111 | - ("visibility", "public"), | | |
| 112 | - ("default_branch", "main"), | | |
| 113 | - ], | | |
| 114 | - Some(session), | | |
| 115 | - ) | | |
| 116 | - .await; | | |
| 117 | - assert_eq!(res.status, 303, "create repo {name}: {}", res.body); | | |
| 118 | - assert_eq!( | | |
| 119 | - res.location().as_deref(), | | |
| 120 | - Some(format!("/tahinli/{name}").as_str()) | | |
| 121 | - ); | | |
| 122 | -} | | |
| 123 | - | | |
| 124 | struct Booted { | 34 | struct Booted { |
| 125 | _server: Server, | 35 | _server: Server, |
| 126 | _root: tempfile::TempDir, | 36 | _root: tempfile::TempDir, |
| @@ -137,17 +47,9 @@ async fn boot() -> Booted { |
| 137 | if !tool_on_path("git") { | 47 | if !tool_on_path("git") { |
| 138 | panic!("`git` was not found on PATH"); | 48 | panic!("`git` was not found on PATH"); |
| 139 | } | 49 | } |
| 140 | - let root = tempfile::Builder::new() | 50 | + let root = temp_dir("pr2e"); |
| 141 | - .prefix("pr2e") | | |
| 142 | - .tempdir_in("/tmp") | | |
| 143 | - .expect("temp dir"); | | |
| 144 | let dir = root.path().to_path_buf(); | 51 | let dir = root.path().to_path_buf(); |
| 145 | - let ports = pick_ports(); | 52 | + let (server, ports) = boot_forge(&dir, "", &[TAHINLI_CMD, BOB_CMD]).await; |
| 146 | - let config = write_config(&dir, ports); | | |
| 147 | - | | |
| 148 | - run_admin(&config, "tahinli", &["--admin"], TAHINLI_PW); | | |
| 149 | - run_admin(&config, "bob", &[], BOB_PW); | | |
| 150 | - let (server, ports) = launch(&dir, ports).await; | | |
| 151 | Booted { | 53 | Booted { |
| 152 | _server: server, | 54 | _server: server, |
| 153 | _root: root, | 55 | _root: root, |
| @@ -158,15 +60,15 @@ async fn boot() -> Booted { |
| 158 | } | 60 | } |
| 159 | | 61 | |
| 160 | async fn tahinli_repo_with_main(b: &Booted) -> (String, String, PathBuf) { | 62 | async fn tahinli_repo_with_main(b: &Booted) -> (String, String, PathBuf) { |
| 161 | - let tahinli = login(&b.http, "tahinli", TAHINLI_PW).await; | 63 | + let tahinli = login(&b.http, "tahinli", PW).await; |
| 162 | let token = create_token(&b.http, &tahinli, "pulls-token").await; | 64 | let token = create_token(&b.http, &tahinli, "pulls-token").await; |
| 163 | - create_repo(&b.http, &tahinli, "r").await; | 65 | + create_repo(&b.http, &tahinli, "r", "public").await; |
| 164 | let work = clone( | 66 | let work = clone( |
| 165 | &remote(b.http_port, "tahinli", &token, "tahinli", "r"), | 67 | &remote(b.http_port, "tahinli", &token, "tahinli", "r"), |
| 166 | &b.dir.join("tahinli-work"), | 68 | &b.dir.join("tahinli-work"), |
| 167 | ); | 69 | ); |
| 168 | commit(&work, "base.txt", "base\n", "base commit", TAHINLI); | 70 | commit(&work, "base.txt", "base\n", "base commit", TAHINLI); |
| 169 | - git(&work, &["push", "-q", "origin", "HEAD:refs/heads/main"]); | 71 | + git_text(&work, &["push", "-q", "origin", "HEAD:refs/heads/main"]); |
| 170 | (tahinli, token, work) | 72 | (tahinli, token, work) |
| 171 | } | 73 | } |
| 172 | | 74 | |
| @@ -175,7 +77,7 @@ async fn open_pull(http: &Http, session: &str, base: &str, head: &str, title: &s |
| 175 | .get_cookie(&format!("{REPO_PATH}/compare/{base}...{head}"), session) | 77 | .get_cookie(&format!("{REPO_PATH}/compare/{base}...{head}"), session) |
| 176 | .await; | 78 | .await; |
| 177 | assert_eq!(compare.status, 200, "GET compare {base}...{head}"); | 79 | assert_eq!(compare.status, 200, "GET compare {base}...{head}"); |
| 178 | - let csrf = csrf_token(http, session).await; | 80 | + let csrf = csrf_for(http, "/settings/keys", session).await; |
| 179 | let res = http | 81 | let res = http |
| 180 | .post_form( | 82 | .post_form( |
| 181 | &format!("{REPO_PATH}/pulls"), | 83 | &format!("{REPO_PATH}/pulls"), |
| @@ -199,11 +101,7 @@ async fn open_pull(http: &Http, session: &str, base: &str, head: &str, title: &s |
| 199 | } | 101 | } |
| 200 | | 102 | |
| 201 | async fn open_issue(http: &Http, session: &str, title: &str) -> u32 { | 103 | async fn open_issue(http: &Http, session: &str, title: &str) -> u32 { |
| 202 | - let page = http | 104 | + let csrf = csrf_for(http, &format!("{REPO_PATH}/issues/new"), session).await; |
| 203 | - .get_cookie(&format!("{REPO_PATH}/issues/new"), session) | | |
| 204 | - .await; | | |
| 205 | - assert_eq!(page.status, 200, "GET issues/new"); | | |
| 206 | - let csrf = input_value(&page.body, "csrf"); | | |
| 207 | let res = http | 105 | let res = http |
| 208 | .post_form( | 106 | .post_form( |
| 209 | &format!("{REPO_PATH}/issues/new"), | 107 | &format!("{REPO_PATH}/issues/new"), |
| @@ -243,7 +141,7 @@ async fn wait_page( |
| 243 | } | 141 | } |
| 244 | | 142 | |
| 245 | async fn merge(http: &Http, session: &str, number: u32, style: &str) -> Resp { | 143 | async fn merge(http: &Http, session: &str, number: u32, style: &str) -> Resp { |
| 246 | - let csrf = csrf_token(http, session).await; | 144 | + let csrf = csrf_for(http, "/settings/keys", session).await; |
| 247 | http.post_form( | 145 | http.post_form( |
| 248 | &format!("{REPO_PATH}/pulls/{number}/merge"), | 146 | &format!("{REPO_PATH}/pulls/{number}/merge"), |
| 249 | &[("csrf", &csrf), ("style", style), ("message", "")], | 147 | &[("csrf", &csrf), ("style", style), ("message", "")], |
| @@ -260,9 +158,9 @@ async fn same_repo_pull_merges_and_closes_issue() { |
| 260 | let issue = open_issue(&b.http, &tahinli, "add x").await; | 158 | let issue = open_issue(&b.http, &tahinli, "add x").await; |
| 261 | assert_eq!(issue, 1); | 159 | assert_eq!(issue, 1); |
| 262 | | 160 | |
| 263 | - git(&work, &["checkout", "-q", "-b", "feature"]); | 161 | + git_text(&work, &["checkout", "-q", "-b", "feature"]); |
| 264 | let feature_head = commit(&work, "x.txt", "x\n", "Add x\n\nFixes #1", TAHINLI); | 162 | let feature_head = commit(&work, "x.txt", "x\n", "Add x\n\nFixes #1", TAHINLI); |
| 265 | - git(&work, &["push", "-q", "origin", "HEAD:refs/heads/feature"]); | 163 | + git_text(&work, &["push", "-q", "origin", "HEAD:refs/heads/feature"]); |
| 266 | | 164 | |
| 267 | let compare = b | 165 | let compare = b |
| 268 | .http | 166 | .http |
| @@ -295,7 +193,7 @@ async fn same_repo_pull_merges_and_closes_issue() { |
| 295 | "main tip is a merge commit with two parents" | 193 | "main tip is a merge commit with two parents" |
| 296 | ); | 194 | ); |
| 297 | assert!( | 195 | assert!( |
| 298 | - git(&check, &["log", "--format=%s", "-n", "5"]).contains("Add x"), | 196 | + git_text(&check, &["log", "--format=%s", "-n", "5"]).contains("Add x"), |
| 299 | "feature commit reachable from main" | 197 | "feature commit reachable from main" |
| 300 | ); | 198 | ); |
| 301 | | 199 | |
| @@ -303,14 +201,17 @@ async fn same_repo_pull_merges_and_closes_issue() { |
| 303 | .http | 201 | .http |
| 304 | .get_cookie(&format!("{REPO_PATH}/pulls/2"), &tahinli) | 202 | .get_cookie(&format!("{REPO_PATH}/pulls/2"), &tahinli) |
| 305 | .await; | 203 | .await; |
| 306 | - assert_eq!(state_badge(&pr.body), "Merged"); | 204 | + assert_eq!( |
| | 205 | + text_or_empty(&pr.body, ".head-sub > .badge, .head-sub > .issue-badge"), |
| | 206 | + "Merged" |
| | 207 | + ); |
| 307 | | 208 | |
| 308 | wait_page( | 209 | wait_page( |
| 309 | &b.http, | 210 | &b.http, |
| 310 | &tahinli, | 211 | &tahinli, |
| 311 | &format!("{REPO_PATH}/issues/1"), | 212 | &format!("{REPO_PATH}/issues/1"), |
| 312 | "issue closed", | 213 | "issue closed", |
| 313 | - |body| state_badge(body) == "Closed", | 214 | + |body| text_or_empty(body, ".head-sub > .badge, .head-sub > .issue-badge") == "Closed", |
| 314 | ) | 215 | ) |
| 315 | .await; | 216 | .await; |
| 316 | } | 217 | } |
| @@ -320,13 +221,13 @@ async fn push_to_head_branch_updates_open_pull() { |
| 320 | let b = boot().await; | 221 | let b = boot().await; |
| 321 | let (tahinli, _token, work) = tahinli_repo_with_main(&b).await; | 222 | let (tahinli, _token, work) = tahinli_repo_with_main(&b).await; |
| 322 | | 223 | |
| 323 | - git(&work, &["checkout", "-q", "-b", "feature2"]); | 224 | + git_text(&work, &["checkout", "-q", "-b", "feature2"]); |
| 324 | commit(&work, "one.txt", "1\n", "first on feature2", TAHINLI); | 225 | commit(&work, "one.txt", "1\n", "first on feature2", TAHINLI); |
| 325 | - git(&work, &["push", "-q", "origin", "HEAD:refs/heads/feature2"]); | 226 | + git_text(&work, &["push", "-q", "origin", "HEAD:refs/heads/feature2"]); |
| 326 | let number = open_pull(&b.http, &tahinli, "main", "feature2", "Feature two").await; | 227 | let number = open_pull(&b.http, &tahinli, "main", "feature2", "Feature two").await; |
| 327 | | 228 | |
| 328 | let second = commit(&work, "two.txt", "2\n", "second on feature2", TAHINLI); | 229 | let second = commit(&work, "two.txt", "2\n", "second on feature2", TAHINLI); |
| 329 | - git(&work, &["push", "-q", "origin", "HEAD:refs/heads/feature2"]); | 230 | + git_text(&work, &["push", "-q", "origin", "HEAD:refs/heads/feature2"]); |
| 330 | | 231 | |
| 331 | let path = format!("{REPO_PATH}/pulls/{number}"); | 232 | let path = format!("{REPO_PATH}/pulls/{number}"); |
| 332 | let page = wait_page(&b.http, &tahinli, &path, "head_updated event", |body| { | 233 | let page = wait_page(&b.http, &tahinli, &path, "head_updated event", |body| { |
| @@ -351,46 +252,14 @@ async fn push_to_head_branch_updates_open_pull() { |
| 351 | assert!(commits.body.contains(&second[..7]), "new commit sha shown"); | 252 | assert!(commits.body.contains(&second[..7]), "new commit sha shown"); |
| 352 | } | 253 | } |
| 353 | | 254 | |
| 354 | -async fn open_stream(http: &Http, path: &str, session: Option<&str>) -> reqwest::Response { | | |
| 355 | - let mut req = http.client.get(format!("{}{path}", http.base)); | | |
| 356 | - if let Some(session) = session { | | |
| 357 | - req = req.header(COOKIE, session); | | |
| 358 | - } | | |
| 359 | - let mut res = req.send().await.expect("stream request"); | | |
| 360 | - if res.status().is_success() { | | |
| 361 | - let retry = tokio::time::timeout(Duration::from_secs(5), res.chunk()) | | |
| 362 | - .await | | |
| 363 | - .expect("the retry field") | | |
| 364 | - .expect("stream chunk") | | |
| 365 | - .expect("stream still open"); | | |
| 366 | - assert!(String::from_utf8_lossy(&retry).contains("retry: 1000")); | | |
| 367 | - } | | |
| 368 | - res | | |
| 369 | -} | | |
| 370 | - | | |
| 371 | -async fn next_changed(res: &mut reqwest::Response, what: &str) { | | |
| 372 | - let chunk = tokio::time::timeout(Duration::from_secs(5), res.chunk()) | | |
| 373 | - .await | | |
| 374 | - .unwrap_or_else(|_| panic!("no event after {what}")) | | |
| 375 | - .expect("stream chunk") | | |
| 376 | - .expect("stream still open"); | | |
| 377 | - let text = String::from_utf8_lossy(&chunk); | | |
| 378 | - assert!(text.contains("event: changed"), "{what}: {text}"); | | |
| 379 | -} | | |
| 380 | - | | |
| 381 | -async fn assert_quiet(res: &mut reqwest::Response, what: &str) { | | |
| 382 | - let got = tokio::time::timeout(Duration::from_secs(2), res.chunk()).await; | | |
| 383 | - assert!(got.is_err(), "{what}: the stream sent an event"); | | |
| 384 | -} | | |
| 385 | - | | |
| 386 | #[tokio::test] | 255 | #[tokio::test] |
| 387 | async fn pull_pages_follow_writes_live() { | 256 | async fn pull_pages_follow_writes_live() { |
| 388 | let b = boot().await; | 257 | let b = boot().await; |
| 389 | let (tahinli, token, work) = tahinli_repo_with_main(&b).await; | 258 | let (tahinli, token, work) = tahinli_repo_with_main(&b).await; |
| 390 | | 259 | |
| 391 | - git(&work, &["checkout", "-q", "-b", "live"]); | 260 | + git_text(&work, &["checkout", "-q", "-b", "live"]); |
| 392 | let first = commit(&work, "live.txt", "live\n", "first on live", TAHINLI); | 261 | let first = commit(&work, "live.txt", "live\n", "first on live", TAHINLI); |
| 393 | - git(&work, &["push", "-q", "origin", "HEAD:refs/heads/live"]); | 262 | + git_text(&work, &["push", "-q", "origin", "HEAD:refs/heads/live"]); |
| 394 | let number = open_pull(&b.http, &tahinli, "main", "live", "Live pull").await; | 263 | let number = open_pull(&b.http, &tahinli, "main", "live", "Live pull").await; |
| 395 | let pull = format!("{REPO_PATH}/pulls/{number}"); | 264 | let pull = format!("{REPO_PATH}/pulls/{number}"); |
| 396 | let list = format!("{REPO_PATH}/pulls"); | 265 | let list = format!("{REPO_PATH}/pulls"); |
| @@ -409,13 +278,19 @@ async fn pull_pages_follow_writes_live() { |
| 409 | "pull list follows its stream" | 278 | "pull list follows its stream" |
| 410 | ); | 279 | ); |
| 411 | | 280 | |
| 412 | - let mut pull_events = open_stream(&b.http, &format!("{pull}/events"), Some(&tahinli)).await; | 281 | + let mut pull_events = b |
| | 282 | + .http |
| | 283 | + .stream(&format!("{pull}/events"), Some(&tahinli)) |
| | 284 | + .await; |
| 413 | assert_eq!(pull_events.status().as_u16(), 200, "pull stream"); | 285 | assert_eq!(pull_events.status().as_u16(), 200, "pull stream"); |
| 414 | - let mut list_events = open_stream(&b.http, &format!("{list}/events"), Some(&tahinli)).await; | 286 | + let mut list_events = b |
| | 287 | + .http |
| | 288 | + .stream(&format!("{list}/events"), Some(&tahinli)) |
| | 289 | + .await; |
| 415 | assert_eq!(list_events.status().as_u16(), 200, "list stream"); | 290 | assert_eq!(list_events.status().as_u16(), 200, "list stream"); |
| 416 | assert_quiet(&mut pull_events, "connecting to the pull stream").await; | 291 | assert_quiet(&mut pull_events, "connecting to the pull stream").await; |
| 417 | | 292 | |
| 418 | - let csrf = csrf_token(&b.http, &tahinli).await; | 293 | + let csrf = csrf_for(&b.http, "/settings/keys", &tahinli).await; |
| 419 | let res = b | 294 | let res = b |
| 420 | .http | 295 | .http |
| 421 | .post_form( | 296 | .post_form( |
| @@ -432,7 +307,7 @@ async fn pull_pages_follow_writes_live() { |
| 432 | next_changed(&mut pull_events, "a comment").await; | 307 | next_changed(&mut pull_events, "a comment").await; |
| 433 | next_changed(&mut list_events, "a comment").await; | 308 | next_changed(&mut list_events, "a comment").await; |
| 434 | | 309 | |
| 435 | - let csrf = csrf_token(&b.http, &tahinli).await; | 310 | + let csrf = csrf_for(&b.http, "/settings/keys", &tahinli).await; |
| 436 | let res = b | 311 | let res = b |
| 437 | .http | 312 | .http |
| 438 | .post_form( | 313 | .post_form( |
| @@ -450,7 +325,7 @@ async fn pull_pages_follow_writes_live() { |
| 450 | next_changed(&mut pull_events, "a review").await; | 325 | next_changed(&mut pull_events, "a review").await; |
| 451 | | 326 | |
| 452 | let second = commit(&work, "second.txt", "2\n", "second on live", TAHINLI); | 327 | let second = commit(&work, "second.txt", "2\n", "second on live", TAHINLI); |
| 453 | - git(&work, &["push", "-q", "origin", "HEAD:refs/heads/live"]); | 328 | + git_text(&work, &["push", "-q", "origin", "HEAD:refs/heads/live"]); |
| 454 | next_changed(&mut pull_events, "a push to the head").await; | 329 | next_changed(&mut pull_events, "a push to the head").await; |
| 455 | next_changed(&mut list_events, "a push to the head").await; | 330 | next_changed(&mut list_events, "a push to the head").await; |
| 456 | | 331 | |
| @@ -475,7 +350,7 @@ async fn pull_pages_follow_writes_live() { |
| 475 | next_changed(&mut pull_events, "the merge").await; | 350 | next_changed(&mut pull_events, "the merge").await; |
| 476 | next_changed(&mut list_events, "the merge").await; | 351 | next_changed(&mut list_events, "the merge").await; |
| 477 | | 352 | |
| 478 | - let csrf = csrf_token(&b.http, &tahinli).await; | 353 | + let csrf = csrf_for(&b.http, "/settings/keys", &tahinli).await; |
| 479 | let res = b | 354 | let res = b |
| 480 | .http | 355 | .http |
| 481 | .post_form( | 356 | .post_form( |
| @@ -491,11 +366,14 @@ async fn pull_pages_follow_writes_live() { |
| 491 | ) | 366 | ) |
| 492 | .await; | 367 | .await; |
| 493 | assert_eq!(res.status, 303, "create private repo: {}", res.body); | 368 | assert_eq!(res.status, 303, "create private repo: {}", res.body); |
| 494 | - let anonymous = open_stream(&b.http, "/tahinli/priv/pulls/events", None).await; | 369 | + let anonymous = b.http.stream("/tahinli/priv/pulls/events", None).await; |
| 495 | assert_eq!(anonymous.status().as_u16(), 404, "private list, anonymous"); | 370 | assert_eq!(anonymous.status().as_u16(), 404, "private list, anonymous"); |
| 496 | - let anonymous = open_stream(&b.http, "/tahinli/priv/pulls/1/events", None).await; | 371 | + let anonymous = b.http.stream("/tahinli/priv/pulls/1/events", None).await; |
| 497 | assert_eq!(anonymous.status().as_u16(), 404, "private pull, anonymous"); | 372 | assert_eq!(anonymous.status().as_u16(), 404, "private pull, anonymous"); |
| 498 | - let member = open_stream(&b.http, "/tahinli/priv/pulls/events", Some(&tahinli)).await; | 373 | + let member = b |
| | 374 | + .http |
| | 375 | + .stream("/tahinli/priv/pulls/events", Some(&tahinli)) |
| | 376 | + .await; |
| 499 | assert_eq!(member.status().as_u16(), 200, "private list, owner"); | 377 | assert_eq!(member.status().as_u16(), 200, "private list, owner"); |
| 500 | } | 378 | } |
| 501 | | 379 | |
| @@ -504,10 +382,10 @@ async fn fork_pull_squash_merge_credits_contributor() { |
| 504 | let b = boot().await; | 382 | let b = boot().await; |
| 505 | let (tahinli, tahinli_token, _work) = tahinli_repo_with_main(&b).await; | 383 | let (tahinli, tahinli_token, _work) = tahinli_repo_with_main(&b).await; |
| 506 | | 384 | |
| 507 | - let bob = login(&b.http, "bob", BOB_PW).await; | 385 | + let bob = login(&b.http, "bob", PW).await; |
| 508 | let bob_token = create_token(&b.http, &bob, "bob-token").await; | 386 | let bob_token = create_token(&b.http, &bob, "bob-token").await; |
| 509 | | 387 | |
| 510 | - let csrf = csrf_token(&b.http, &bob).await; | 388 | + let csrf = csrf_for(&b.http, "/settings/keys", &bob).await; |
| 511 | let fork = b | 389 | let fork = b |
| 512 | .http | 390 | .http |
| 513 | .post_form(&format!("{REPO_PATH}/fork"), &[("csrf", &csrf)], Some(&bob)) | 391 | .post_form(&format!("{REPO_PATH}/fork"), &[("csrf", &csrf)], Some(&bob)) |
| @@ -517,9 +395,9 @@ async fn fork_pull_squash_merge_credits_contributor() { |
| 517 | | 395 | |
| 518 | let bob_url = remote(b.http_port, "bob", &bob_token, "bob", "r"); | 396 | let bob_url = remote(b.http_port, "bob", &bob_token, "bob", "r"); |
| 519 | let bob_work = clone(&bob_url, &b.dir.join("bob-work")); | 397 | let bob_work = clone(&bob_url, &b.dir.join("bob-work")); |
| 520 | - git(&bob_work, &["checkout", "-q", "-b", "bob-feature"]); | 398 | + git_text(&bob_work, &["checkout", "-q", "-b", "bob-feature"]); |
| 521 | let bob_head = commit(&bob_work, "bob.txt", "bob\n", "Bob change", BOB); | 399 | let bob_head = commit(&bob_work, "bob.txt", "bob\n", "Bob change", BOB); |
| 522 | - git( | 400 | + git_text( |
| 523 | &bob_work, | 401 | &bob_work, |
| 524 | &["push", "-q", "origin", "HEAD:refs/heads/bob-feature"], | 402 | &["push", "-q", "origin", "HEAD:refs/heads/bob-feature"], |
| 525 | ); | 403 | ); |
| @@ -536,12 +414,12 @@ async fn fork_pull_squash_merge_credits_contributor() { |
| 536 | let check = clone(&tahinli_url, &b.dir.join("check")); | 414 | let check = clone(&tahinli_url, &b.dir.join("check")); |
| 537 | assert_eq!(parent_count(&check, "HEAD"), 1, "squash makes one parent"); | 415 | assert_eq!(parent_count(&check, "HEAD"), 1, "squash makes one parent"); |
| 538 | assert_ne!( | 416 | assert_ne!( |
| 539 | - git(&check, &["rev-parse", "HEAD"]), | 417 | + git_text(&check, &["rev-parse", "HEAD"]), |
| 540 | bob_head, | 418 | bob_head, |
| 541 | "main has a new squash commit, not bob's commit" | 419 | "main has a new squash commit, not bob's commit" |
| 542 | ); | 420 | ); |
| 543 | - assert_eq!(git(&check, &["log", "-1", "--format=%an"]), "bob"); | 421 | + assert_eq!(git_text(&check, &["log", "-1", "--format=%an"]), "bob"); |
| 544 | - assert_eq!(git(&check, &["log", "-1", "--format=%ae"]), BOB_EMAIL); | 422 | + assert_eq!(git_text(&check, &["log", "-1", "--format=%ae"]), BOB_EMAIL); |
| 545 | } | 423 | } |
| 546 | | 424 | |
| 547 | #[tokio::test] | 425 | #[tokio::test] |
| @@ -549,14 +427,14 @@ async fn conflicting_pull_cannot_merge() { |
| 549 | let b = boot().await; | 427 | let b = boot().await; |
| 550 | let (tahinli, token, work) = tahinli_repo_with_main(&b).await; | 428 | let (tahinli, token, work) = tahinli_repo_with_main(&b).await; |
| 551 | | 429 | |
| 552 | - git(&work, &["checkout", "-q", "-b", "conflict"]); | 430 | + git_text(&work, &["checkout", "-q", "-b", "conflict"]); |
| 553 | commit(&work, "shared.txt", "branch side\n", "branch edit", TAHINLI); | 431 | commit(&work, "shared.txt", "branch side\n", "branch edit", TAHINLI); |
| 554 | - git(&work, &["push", "-q", "origin", "HEAD:refs/heads/conflict"]); | 432 | + git_text(&work, &["push", "-q", "origin", "HEAD:refs/heads/conflict"]); |
| 555 | let number = open_pull(&b.http, &tahinli, "main", "conflict", "Conflicting").await; | 433 | let number = open_pull(&b.http, &tahinli, "main", "conflict", "Conflicting").await; |
| 556 | | 434 | |
| 557 | - git(&work, &["checkout", "-q", "main"]); | 435 | + git_text(&work, &["checkout", "-q", "main"]); |
| 558 | let main_head = commit(&work, "shared.txt", "main side\n", "main edit", TAHINLI); | 436 | let main_head = commit(&work, "shared.txt", "main side\n", "main edit", TAHINLI); |
| 559 | - git(&work, &["push", "-q", "origin", "HEAD:refs/heads/main"]); | 437 | + git_text(&work, &["push", "-q", "origin", "HEAD:refs/heads/main"]); |
| 560 | | 438 | |
| 561 | let path = format!("{REPO_PATH}/pulls/{number}"); | 439 | let path = format!("{REPO_PATH}/pulls/{number}"); |
| 562 | let page = wait_page(&b.http, &tahinli, &path, "conflict detection", |body| { | 440 | let page = wait_page(&b.http, &tahinli, &path, "conflict detection", |body| { |
| @@ -1,50 +1,10 @@ |
| 1 | use crate::common::{ | 1 | use crate::common::{ |
| 2 | - Http, bin, describe, input_value, launch, login, pick_ports, tool_on_path, with_cookie, | 2 | + Http, PW, csrf_for, init_bare, launch, login, provision, tool_on_path, with_cookie, |
| 3 | - write_config, | | |
| 4 | }; | 3 | }; |
| 5 | -use std::fs; | | |
| 6 | -use std::path::Path; | | |
| 7 | -use std::process::{Command, Output}; | | |
| 8 | | 4 | |
| 9 | use forge_core::{Role, Store, Visibility}; | 5 | use forge_core::{Role, Store, Visibility}; |
| 10 | use reqwest::header::LOCATION; | 6 | use reqwest::header::LOCATION; |
| 11 | | 7 | |
| 12 | -const PW: &str = "tahinli-password-123"; | | |
| 13 | - | | |
| 14 | -fn admin(config: &Path, args: &[&str]) -> Output { | | |
| 15 | - let out = Command::new(bin()) | | |
| 16 | - .arg("--config") | | |
| 17 | - .arg(config) | | |
| 18 | - .arg("admin") | | |
| 19 | - .args(args) | | |
| 20 | - .env("FORGE_PASSWORD", PW) | | |
| 21 | - .output() | | |
| 22 | - .expect("run admin command"); | | |
| 23 | - assert!( | | |
| 24 | - out.status.success(), | | |
| 25 | - "admin {args:?} failed:\n{}", | | |
| 26 | - describe(&out) | | |
| 27 | - ); | | |
| 28 | - out | | |
| 29 | -} | | |
| 30 | - | | |
| 31 | -async fn csrf_for(http: &Http, session: &str) -> String { | | |
| 32 | - let page = http.get("/settings/keys", Some(session)).await; | | |
| 33 | - assert_eq!(page.status, 200, "GET /settings/keys"); | | |
| 34 | - input_value(&page.body, "csrf") | | |
| 35 | -} | | |
| 36 | - | | |
| 37 | -fn init_bare(data_dir: &Path, repo_id: &str) { | | |
| 38 | - let path = forge_git::repo::repo_path(data_dir, repo_id).expect("repo path"); | | |
| 39 | - fs::create_dir_all(path.parent().expect("parent")).expect("create repo parent"); | | |
| 40 | - let out = Command::new("git") | | |
| 41 | - .args(["init", "--bare", "--quiet"]) | | |
| 42 | - .arg(&path) | | |
| 43 | - .output() | | |
| 44 | - .expect("run git init"); | | |
| 45 | - assert!(out.status.success(), "git init --bare: {}", describe(&out)); | | |
| 46 | -} | | |
| 47 | - | | |
| 48 | async fn shown_role(http: &Http, session: &str, username: &str) -> Option<String> { | 8 | async fn shown_role(http: &Http, session: &str, username: &str) -> Option<String> { |
| 49 | let page = http | 9 | let page = http |
| 50 | .get("/olivia/priv/settings/collaborators", Some(session)) | 10 | .get("/olivia/priv/settings/collaborators", Some(session)) |
| @@ -68,19 +28,21 @@ async fn repo_collaborators_end_to_end() { |
| 68 | return; | 28 | return; |
| 69 | } | 29 | } |
| 70 | | 30 | |
| 71 | - let root = tempfile::Builder::new() | 31 | + let root = crate::common::temp_dir("frc"); |
| 72 | - .prefix("frc") | | |
| 73 | - .tempdir_in("/tmp") | | |
| 74 | - .expect("temp dir"); | | |
| 75 | let dir = root.path().to_path_buf(); | 32 | let dir = root.path().to_path_buf(); |
| 76 | | 33 | |
| 77 | - let ports = pick_ports(); | 34 | + let (_, ports) = provision( |
| 78 | - let config = write_config(&dir, ports); | 35 | + &dir, |
| 79 | - | 36 | + "", |
| 80 | - admin(&config, &["create-user", "root", "--admin"]); | 37 | + &[ |
| 81 | - for name in ["olivia", "bob", "carol", "dana", "wendy"] { | 38 | + &["create-user", "root", "--admin"], |
| 82 | - admin(&config, &["create-user", name]); | 39 | + &["create-user", "olivia"], |
| 83 | - } | 40 | + &["create-user", "bob"], |
| | 41 | + &["create-user", "carol"], |
| | 42 | + &["create-user", "dana"], |
| | 43 | + &["create-user", "wendy"], |
| | 44 | + ], |
| | 45 | + ); |
| 84 | | 46 | |
| 85 | let (bob_id, carol_id, dana_id) = { | 47 | let (bob_id, carol_id, dana_id) = { |
| 86 | let store = Store::open(&dir.join("forge.db")) | 48 | let store = Store::open(&dir.join("forge.db")) |
| @@ -142,7 +104,7 @@ async fn repo_collaborators_end_to_end() { |
| 142 | let owner_page = http.get(page, Some(&olivia)).await; | 104 | let owner_page = http.get(page, Some(&olivia)).await; |
| 143 | assert_eq!(owner_page.status, 200, "owner page"); | 105 | assert_eq!(owner_page.status, 200, "owner page"); |
| 144 | | 106 | |
| 145 | - let csrf = csrf_for(&http, &olivia).await; | 107 | + let csrf = csrf_for(&http, "/settings/keys", &olivia).await; |
| 146 | let res = http | 108 | let res = http |
| 147 | .post_form( | 109 | .post_form( |
| 148 | add, | 110 | add, |
| @@ -273,7 +235,7 @@ async fn repo_collaborators_end_to_end() { |
| 273 | "CSRF failure added bob" | 235 | "CSRF failure added bob" |
| 274 | ); | 236 | ); |
| 275 | | 237 | |
| 276 | - let carol_csrf = csrf_for(&http, &carol).await; | 238 | + let carol_csrf = csrf_for(&http, "/settings/keys", &carol).await; |
| 277 | assert_eq!(http.get(page, Some(&carol)).await.status, 200, "carol page"); | 239 | assert_eq!(http.get(page, Some(&carol)).await.status, 200, "carol page"); |
| 278 | let res = http | 240 | let res = http |
| 279 | .post_form( | 241 | .post_form( |
| @@ -1,74 +1,13 @@ |
| 1 | use crate::common::{ | 1 | use crate::common::{ |
| 2 | - Http, Resp, bin, describe, input_value, launch, login, pick_ports, tool_on_path, write_config, | 2 | + Http, PW, Resp, commit_file, create_token, csrf_for, form_action, git, init_bare, launch, |
| | 3 | + login, ok, path_str, provision, tool_on_path, |
| 3 | }; | 4 | }; |
| 4 | -use std::fs; | | |
| 5 | -use std::path::Path; | | |
| 6 | -use std::process::{Command, Output}; | | |
| 7 | | 5 | |
| 8 | use forge_core::{Role, Store, Visibility}; | 6 | use forge_core::{Role, Store, Visibility}; |
| 9 | use reqwest::header::LOCATION; | 7 | use reqwest::header::LOCATION; |
| 10 | | 8 | |
| 11 | -const PW: &str = "tahinli-password-123"; | | |
| 12 | - | | |
| 13 | -fn form_action(body: &str, suffix: &str) -> String { | | |
| 14 | - let doc = scraper::Html::parse_document(body); | | |
| 15 | - let selector = scraper::Selector::parse("form").expect("selector"); | | |
| 16 | - doc.select(&selector) | | |
| 17 | - .filter_map(|el| el.value().attr("action")) | | |
| 18 | - .find(|action| action.ends_with(suffix)) | | |
| 19 | - .unwrap_or_else(|| panic!("no form ending in {suffix} on page")) | | |
| 20 | - .to_owned() | | |
| 21 | -} | | |
| 22 | - | | |
| 23 | -fn admin(config: &Path, args: &[&str]) { | | |
| 24 | - let out = Command::new(bin()) | | |
| 25 | - .arg("--config") | | |
| 26 | - .arg(config) | | |
| 27 | - .arg("admin") | | |
| 28 | - .args(args) | | |
| 29 | - .env("FORGE_PASSWORD", PW) | | |
| 30 | - .output() | | |
| 31 | - .expect("run admin command"); | | |
| 32 | - assert!( | | |
| 33 | - out.status.success(), | | |
| 34 | - "admin {args:?} failed:\n{}", | | |
| 35 | - describe(&out) | | |
| 36 | - ); | | |
| 37 | -} | | |
| 38 | - | | |
| 39 | -async fn csrf_for(http: &Http, session: &str) -> String { | | |
| 40 | - let page = http.get("/settings/keys", Some(session)).await; | | |
| 41 | - assert_eq!(page.status, 200, "GET /settings/keys"); | | |
| 42 | - input_value(&page.body, "csrf") | | |
| 43 | -} | | |
| 44 | - | | |
| 45 | -async fn create_token(http: &Http, session: &str, name: &str) -> String { | | |
| 46 | - let csrf = csrf_for(http, session).await; | | |
| 47 | - let res = http | | |
| 48 | - .post_form( | | |
| 49 | - "/settings/tokens", | | |
| 50 | - &[("csrf", &csrf), ("name", name), ("expires", "30")], | | |
| 51 | - Some(session), | | |
| 52 | - ) | | |
| 53 | - .await; | | |
| 54 | - assert_eq!(res.status, 200, "create token: {}", res.body); | | |
| 55 | - let doc = scraper::Html::parse_document(&res.body); | | |
| 56 | - let selector = scraper::Selector::parse("pre.code code").expect("selector"); | | |
| 57 | - let token: String = doc | | |
| 58 | - .select(&selector) | | |
| 59 | - .next() | | |
| 60 | - .expect("token shown after creation") | | |
| 61 | - .text() | | |
| 62 | - .collect(); | | |
| 63 | - let token = token.trim().to_owned(); | | |
| 64 | - assert!(token.starts_with("forge_"), "unexpected token shape"); | | |
| 65 | - token | | |
| 66 | -} | | |
| 67 | - | | |
| 68 | async fn create_repo_web(http: &Http, session: &str, name: &str) -> Resp { | 9 | async fn create_repo_web(http: &Http, session: &str, name: &str) -> Resp { |
| 69 | - let page = http.get("/new", Some(session)).await; | 10 | + let csrf = csrf_for(http, "/new", session).await; |
| 70 | - assert_eq!(page.status, 200, "GET /new"); | | |
| 71 | - let csrf = input_value(&page.body, "csrf"); | | |
| 72 | http.post_form( | 11 | http.post_form( |
| 73 | "/new", | 12 | "/new", |
| 74 | &[ | 13 | &[ |
| @@ -83,54 +22,6 @@ async fn create_repo_web(http: &Http, session: &str, name: &str) -> Resp { |
| 83 | .await | 22 | .await |
| 84 | } | 23 | } |
| 85 | | 24 | |
| 86 | -fn init_bare(data_dir: &Path, repo_id: &str) { | | |
| 87 | - let path = forge_git::repo::repo_path(data_dir, repo_id).expect("repo path"); | | |
| 88 | - fs::create_dir_all(path.parent().expect("parent")).expect("create repo parent"); | | |
| 89 | - let out = Command::new("git") | | |
| 90 | - .args(["init", "--bare", "--quiet", "--initial-branch=main"]) | | |
| 91 | - .arg(&path) | | |
| 92 | - .output() | | |
| 93 | - .expect("run git init"); | | |
| 94 | - assert!(out.status.success(), "git init --bare: {}", describe(&out)); | | |
| 95 | -} | | |
| 96 | - | | |
| 97 | -fn git(cwd: &Path, args: &[&str]) -> Output { | | |
| 98 | - Command::new("git") | | |
| 99 | - .current_dir(cwd) | | |
| 100 | - .args(["-c", "credential.helper="]) | | |
| 101 | - .args(args) | | |
| 102 | - .env("GIT_TERMINAL_PROMPT", "0") | | |
| 103 | - .output() | | |
| 104 | - .expect("run git") | | |
| 105 | -} | | |
| 106 | - | | |
| 107 | -fn ok(out: &Output, what: &str) { | | |
| 108 | - assert!(out.status.success(), "{what} failed:\n{}", describe(out)); | | |
| 109 | -} | | |
| 110 | - | | |
| 111 | -fn path_str(path: &Path) -> &str { | | |
| 112 | - path.to_str().expect("utf-8 path") | | |
| 113 | -} | | |
| 114 | - | | |
| 115 | -fn commit_file(repo: &Path, name: &str, content: &str, message: &str) { | | |
| 116 | - let file = repo.join(name); | | |
| 117 | - fs::create_dir_all(file.parent().expect("parent")).expect("create dir"); | | |
| 118 | - fs::write(&file, content).expect("write file"); | | |
| 119 | - ok(&git(repo, &["config", "user.name", "bob"]), "set user.name"); | | |
| 120 | - ok( | | |
| 121 | - &git(repo, &["config", "user.email", "bob@example.com"]), | | |
| 122 | - "set user.email", | | |
| 123 | - ); | | |
| 124 | - ok(&git(repo, &["add", name]), "git add"); | | |
| 125 | - ok( | | |
| 126 | - &git( | | |
| 127 | - repo, | | |
| 128 | - &["-c", "commit.gpgsign=false", "commit", "-q", "-m", message], | | |
| 129 | - ), | | |
| 130 | - "git commit", | | |
| 131 | - ); | | |
| 132 | -} | | |
| 133 | - | | |
| 134 | #[tokio::test] | 25 | #[tokio::test] |
| 135 | async fn repo_rename_end_to_end() { | 26 | async fn repo_rename_end_to_end() { |
| 136 | if !tool_on_path("git") { | 27 | if !tool_on_path("git") { |
| @@ -138,18 +29,19 @@ async fn repo_rename_end_to_end() { |
| 138 | return; | 29 | return; |
| 139 | } | 30 | } |
| 140 | | 31 | |
| 141 | - let root = tempfile::Builder::new() | 32 | + let root = crate::common::temp_dir("frn"); |
| 142 | - .prefix("frn") | | |
| 143 | - .tempdir_in("/tmp") | | |
| 144 | - .expect("temp dir"); | | |
| 145 | let dir = root.path().to_path_buf(); | 33 | let dir = root.path().to_path_buf(); |
| 146 | - let ports = pick_ports(); | 34 | + let (_, ports) = provision( |
| 147 | - let config = write_config(&dir, ports); | 35 | + &dir, |
| 148 | - | 36 | + "", |
| 149 | - admin(&config, &["create-user", "tahinli", "--admin"]); | 37 | + &[ |
| 150 | - for name in ["bob", "carol", "dave", "eve"] { | 38 | + &["create-user", "tahinli", "--admin"], |
| 151 | - admin(&config, &["create-user", name]); | 39 | + &["create-user", "bob"], |
| 152 | - } | 40 | + &["create-user", "carol"], |
| | 41 | + &["create-user", "dave"], |
| | 42 | + &["create-user", "eve"], |
| | 43 | + ], |
| | 44 | + ); |
| 153 | { | 45 | { |
| 154 | let store = Store::open(&dir.join("forge.db")) | 46 | let store = Store::open(&dir.join("forge.db")) |
| 155 | .await | 47 | .await |
| @@ -213,7 +105,7 @@ async fn repo_rename_end_to_end() { |
| 213 | let tree = http.get("/bob/pub/tree/main/src", None).await; | 105 | let tree = http.get("/bob/pub/tree/main/src", None).await; |
| 214 | assert_eq!(tree.status, 200, "tree before rename"); | 106 | assert_eq!(tree.status, 200, "tree before rename"); |
| 215 | | 107 | |
| 216 | - let csrf = csrf_for(&http, &bob).await; | 108 | + let csrf = csrf_for(&http, "/settings/keys", &bob).await; |
| 217 | let renamed = http | 109 | let renamed = http |
| 218 | .post_form( | 110 | .post_form( |
| 219 | "/bob/pub/settings/rename", | 111 | "/bob/pub/settings/rename", |
| @@ -287,7 +179,7 @@ async fn repo_rename_end_to_end() { |
| 287 | ); | 179 | ); |
| 288 | assert!(new_clone.join("src/lib.rs").exists()); | 180 | assert!(new_clone.join("src/lib.rs").exists()); |
| 289 | | 181 | |
| 290 | - let csrf = csrf_for(&http, &bob).await; | 182 | + let csrf = csrf_for(&http, "/settings/keys", &bob).await; |
| 291 | let taken = http | 183 | let taken = http |
| 292 | .post_form( | 184 | .post_form( |
| 293 | "/bob/newpub/settings/rename", | 185 | "/bob/newpub/settings/rename", |
| @@ -312,7 +204,7 @@ async fn repo_rename_end_to_end() { |
| 312 | "name unchanged after rejected renames" | 204 | "name unchanged after rejected renames" |
| 313 | ); | 205 | ); |
| 314 | | 206 | |
| 315 | - let carol_csrf = csrf_for(&http, &carol).await; | 207 | + let carol_csrf = csrf_for(&http, "/settings/keys", &carol).await; |
| 316 | let carol_rename = http | 208 | let carol_rename = http |
| 317 | .post_form( | 209 | .post_form( |
| 318 | "/bob/newpub/settings/rename", | 210 | "/bob/newpub/settings/rename", |
| @@ -323,7 +215,7 @@ async fn repo_rename_end_to_end() { |
| 323 | assert_eq!(carol_rename.status, 403, "write collaborator rename"); | 215 | assert_eq!(carol_rename.status, 403, "write collaborator rename"); |
| 324 | assert_eq!(http.get("/bob/newpub", None).await.status, 200); | 216 | assert_eq!(http.get("/bob/newpub", None).await.status, 200); |
| 325 | | 217 | |
| 326 | - let dave_csrf = csrf_for(&http, &dave).await; | 218 | + let dave_csrf = csrf_for(&http, "/settings/keys", &dave).await; |
| 327 | let dave_transfer = http | 219 | let dave_transfer = http |
| 328 | .post_form( | 220 | .post_form( |
| 329 | "/bob/newpub/settings/transfer", | 221 | "/bob/newpub/settings/transfer", |
| @@ -338,7 +230,7 @@ async fn repo_rename_end_to_end() { |
| 338 | assert_eq!(dave_transfer.status, 403, "admin collaborator transfer"); | 230 | assert_eq!(dave_transfer.status, 403, "admin collaborator transfer"); |
| 339 | assert_eq!(http.get("/bob/newpub", None).await.status, 200); | 231 | assert_eq!(http.get("/bob/newpub", None).await.status, 200); |
| 340 | | 232 | |
| 341 | - let csrf = csrf_for(&http, &bob).await; | 233 | + let csrf = csrf_for(&http, "/settings/keys", &bob).await; |
| 342 | let transfer_wrong = http | 234 | let transfer_wrong = http |
| 343 | .post_form( | 235 | .post_form( |
| 344 | "/bob/newpub/settings/transfer", | 236 | "/bob/newpub/settings/transfer", |
| @@ -379,7 +271,7 @@ async fn repo_rename_end_to_end() { |
| 379 | assert!(offered.body.contains("Pending transfer to carol")); | 271 | assert!(offered.body.contains("Pending transfer to carol")); |
| 380 | let inbox = http.get("/notifications", Some(&carol)).await; | 272 | let inbox = http.get("/notifications", Some(&carol)).await; |
| 381 | let accept_action = form_action(&inbox.body, "/accept"); | 273 | let accept_action = form_action(&inbox.body, "/accept"); |
| 382 | - let carol_accept_csrf = csrf_for(&http, &carol).await; | 274 | + let carol_accept_csrf = csrf_for(&http, "/settings/keys", &carol).await; |
| 383 | let accepted = http | 275 | let accepted = http |
| 384 | .post_form( | 276 | .post_form( |
| 385 | &accept_action, | 277 | &accept_action, |
| @@ -431,7 +323,7 @@ async fn repo_rename_end_to_end() { |
| 431 | "the other old name still redirects" | 323 | "the other old name still redirects" |
| 432 | ); | 324 | ); |
| 433 | | 325 | |
| 434 | - let csrf = csrf_for(&http, &bob).await; | 326 | + let csrf = csrf_for(&http, "/settings/keys", &bob).await; |
| 435 | let secret_rename = http | 327 | let secret_rename = http |
| 436 | .post_form( | 328 | .post_form( |
| 437 | "/bob/secret/settings/rename", | 329 | "/bob/secret/settings/rename", |
| @@ -1,50 +1,14 @@ |
| 1 | use crate::common::{ | 1 | use crate::common::{ |
| 2 | - Http, bin, cookie_named, describe, input_value, launch, login, pick_ports, tool_on_path, | 2 | + Http, PW, admin, attr_of, cookie_named, csrf_for, describe, init_bare, input_value, launch, |
| 3 | - with_cookie, write_config, | 3 | + login, provision, tool_on_path, with_cookie, |
| 4 | }; | 4 | }; |
| 5 | use std::fs; | 5 | use std::fs; |
| 6 | use std::path::{Path, PathBuf}; | 6 | use std::path::{Path, PathBuf}; |
| 7 | -use std::process::{Command, Output}; | 7 | +use std::process::Command; |
| 8 | | 8 | |
| 9 | use forge_core::{Role, Store, Visibility}; | 9 | use forge_core::{Role, Store, Visibility}; |
| 10 | use reqwest::header::LOCATION; | 10 | use reqwest::header::LOCATION; |
| 11 | | 11 | |
| 12 | -const PW: &str = "tahinli-password-123"; | | |
| 13 | - | | |
| 14 | -fn admin(config: &Path, args: &[&str]) -> Output { | | |
| 15 | - let out = Command::new(bin()) | | |
| 16 | - .arg("--config") | | |
| 17 | - .arg(config) | | |
| 18 | - .arg("admin") | | |
| 19 | - .args(args) | | |
| 20 | - .env("FORGE_PASSWORD", PW) | | |
| 21 | - .output() | | |
| 22 | - .expect("run admin command"); | | |
| 23 | - assert!( | | |
| 24 | - out.status.success(), | | |
| 25 | - "admin {args:?} failed:\n{}", | | |
| 26 | - describe(&out) | | |
| 27 | - ); | | |
| 28 | - out | | |
| 29 | -} | | |
| 30 | - | | |
| 31 | -async fn csrf_for(http: &Http, session: &str) -> String { | | |
| 32 | - let page = http.get("/settings/keys", Some(session)).await; | | |
| 33 | - assert_eq!(page.status, 200, "GET /settings/keys"); | | |
| 34 | - input_value(&page.body, "csrf") | | |
| 35 | -} | | |
| 36 | - | | |
| 37 | -fn init_bare(data_dir: &Path, repo_id: &str) { | | |
| 38 | - let path = forge_git::repo::repo_path(data_dir, repo_id).expect("repo path"); | | |
| 39 | - fs::create_dir_all(path.parent().expect("parent")).expect("create repo parent"); | | |
| 40 | - let out = Command::new("git") | | |
| 41 | - .args(["init", "--bare", "--quiet"]) | | |
| 42 | - .arg(&path) | | |
| 43 | - .output() | | |
| 44 | - .expect("run git init"); | | |
| 45 | - assert!(out.status.success(), "git init --bare: {}", describe(&out)); | | |
| 46 | -} | | |
| 47 | - | | |
| 48 | fn trash_entries(data_dir: &Path, repo_id: &str) -> Vec<PathBuf> { | 12 | fn trash_entries(data_dir: &Path, repo_id: &str) -> Vec<PathBuf> { |
| 49 | let prefix = format!("{}-", repo_id.to_ascii_lowercase()); | 13 | let prefix = format!("{}-", repo_id.to_ascii_lowercase()); |
| 50 | let Ok(read) = fs::read_dir(data_dir.join(forge_git::repo::TRASH_DIR)) else { | 14 | let Ok(read) = fs::read_dir(data_dir.join(forge_git::repo::TRASH_DIR)) else { |
| @@ -67,18 +31,18 @@ async fn repo_settings_end_to_end() { |
| 67 | return; | 31 | return; |
| 68 | } | 32 | } |
| 69 | | 33 | |
| 70 | - let root = tempfile::Builder::new() | 34 | + let root = crate::common::temp_dir("frs"); |
| 71 | - .prefix("frs") | | |
| 72 | - .tempdir_in("/tmp") | | |
| 73 | - .expect("temp dir"); | | |
| 74 | let dir = root.path().to_path_buf(); | 35 | let dir = root.path().to_path_buf(); |
| 75 | | 36 | |
| 76 | - let ports = pick_ports(); | 37 | + let (config, ports) = provision( |
| 77 | - let config = write_config(&dir, ports); | 38 | + &dir, |
| 78 | - | 39 | + "", |
| 79 | - admin(&config, &["create-user", "tahinli", "--admin"]); | 40 | + &[ |
| 80 | - admin(&config, &["create-user", "bob"]); | 41 | + &["create-user", "tahinli", "--admin"], |
| 81 | - admin(&config, &["create-user", "carol"]); | 42 | + &["create-user", "bob"], |
| | 43 | + &["create-user", "carol"], |
| | 44 | + ], |
| | 45 | + ); |
| 82 | | 46 | |
| 83 | let (public_id, private_id) = { | 47 | let (public_id, private_id) = { |
| 84 | let store = Store::open(&dir.join("forge.db")) | 48 | let store = Store::open(&dir.join("forge.db")) |
| @@ -125,7 +89,7 @@ async fn repo_settings_end_to_end() { |
| 125 | !carol_page.body.contains("/bob/priv/settings/delete\""), | 89 | !carol_page.body.contains("/bob/priv/settings/delete\""), |
| 126 | "admin collaborator must not see the delete form" | 90 | "admin collaborator must not see the delete form" |
| 127 | ); | 91 | ); |
| 128 | - let carol_csrf = csrf_for(&http, &carol).await; | 92 | + let carol_csrf = csrf_for(&http, "/settings/keys", &carol).await; |
| 129 | let carol_delete = http | 93 | let carol_delete = http |
| 130 | .post_form( | 94 | .post_form( |
| 131 | "/bob/priv/settings/delete", | 95 | "/bob/priv/settings/delete", |
| @@ -156,7 +120,7 @@ async fn repo_settings_end_to_end() { |
| 156 | "Settings tab shows to an Admin collaborator" | 120 | "Settings tab shows to an Admin collaborator" |
| 157 | ); | 121 | ); |
| 158 | | 122 | |
| 159 | - let owner_csrf = csrf_for(&http, &bob).await; | 123 | + let owner_csrf = csrf_for(&http, "/settings/keys", &bob).await; |
| 160 | let wrong = http | 124 | let wrong = http |
| 161 | .post_form( | 125 | .post_form( |
| 162 | "/bob/pub/settings/delete", | 126 | "/bob/pub/settings/delete", |
| @@ -235,7 +199,7 @@ async fn repo_settings_end_to_end() { |
| 235 | | 199 | |
| 236 | let admin_page = http.get("/bob/priv/settings", Some(&tahinli)).await; | 200 | let admin_page = http.get("/bob/priv/settings", Some(&tahinli)).await; |
| 237 | assert_eq!(admin_page.status, 200, "admin settings page"); | 201 | assert_eq!(admin_page.status, 200, "admin settings page"); |
| 238 | - let admin_csrf = csrf_for(&http, &tahinli).await; | 202 | + let admin_csrf = csrf_for(&http, "/settings/keys", &tahinli).await; |
| 239 | let admin_delete = http | 203 | let admin_delete = http |
| 240 | .post_form( | 204 | .post_form( |
| 241 | "/bob/priv/settings/delete", | 205 | "/bob/priv/settings/delete", |
| @@ -282,14 +246,9 @@ async fn repo_settings_deletes_rows_when_repo_dir_is_missing() { |
| 282 | return; | 246 | return; |
| 283 | } | 247 | } |
| 284 | | 248 | |
| 285 | - let root = tempfile::Builder::new() | 249 | + let root = crate::common::temp_dir("frm"); |
| 286 | - .prefix("frm") | | |
| 287 | - .tempdir_in("/tmp") | | |
| 288 | - .expect("temp dir"); | | |
| 289 | let dir = root.path().to_path_buf(); | 250 | let dir = root.path().to_path_buf(); |
| 290 | - let ports = pick_ports(); | 251 | + let (_, ports) = provision(&dir, "", &[&["create-user", "bob"]]); |
| 291 | - let config = write_config(&dir, ports); | | |
| 292 | - admin(&config, &["create-user", "bob"]); | | |
| 293 | | 252 | |
| 294 | let (repo_id, bare_dir) = { | 253 | let (repo_id, bare_dir) = { |
| 295 | let store = Store::open(&dir.join("forge.db")) | 254 | let store = Store::open(&dir.join("forge.db")) |
| @@ -309,7 +268,7 @@ async fn repo_settings_deletes_rows_when_repo_dir_is_missing() { |
| 309 | let (server, ports) = launch(&dir, ports).await; | 268 | let (server, ports) = launch(&dir, ports).await; |
| 310 | let http = Http::new(ports.http); | 269 | let http = Http::new(ports.http); |
| 311 | let bob = login(&http, "bob", PW).await; | 270 | let bob = login(&http, "bob", PW).await; |
| 312 | - let csrf = csrf_for(&http, &bob).await; | 271 | + let csrf = csrf_for(&http, "/settings/keys", &bob).await; |
| 313 | let deleted = http | 272 | let deleted = http |
| 314 | .post_form( | 273 | .post_form( |
| 315 | "/bob/gone/settings/delete", | 274 | "/bob/gone/settings/delete", |
| @@ -380,18 +339,18 @@ async fn branch_protection_end_to_end() { |
| 380 | return; | 339 | return; |
| 381 | } | 340 | } |
| 382 | | 341 | |
| 383 | - let root = tempfile::Builder::new() | 342 | + let root = crate::common::temp_dir("frb"); |
| 384 | - .prefix("frb") | | |
| 385 | - .tempdir_in("/tmp") | | |
| 386 | - .expect("temp dir"); | | |
| 387 | let dir = root.path().to_path_buf(); | 343 | let dir = root.path().to_path_buf(); |
| 388 | - let ports = pick_ports(); | 344 | + let (_, ports) = provision( |
| 389 | - let config = write_config(&dir, ports); | 345 | + &dir, |
| 390 | - | 346 | + "", |
| 391 | - admin(&config, &["create-user", "tahinli", "--admin"]); | 347 | + &[ |
| 392 | - admin(&config, &["create-user", "bob"]); | 348 | + &["create-user", "tahinli", "--admin"], |
| 393 | - admin(&config, &["create-user", "carol"]); | 349 | + &["create-user", "bob"], |
| 394 | - admin(&config, &["create-user", "dan"]); | 350 | + &["create-user", "carol"], |
| | 351 | + &["create-user", "dan"], |
| | 352 | + ], |
| | 353 | + ); |
| 395 | | 354 | |
| 396 | { | 355 | { |
| 397 | let store = Store::open(&dir.join("forge.db")) | 356 | let store = Store::open(&dir.join("forge.db")) |
| @@ -446,7 +405,7 @@ async fn branch_protection_end_to_end() { |
| 446 | "main", | 405 | "main", |
| 447 | "pattern is prefilled with the default branch" | 406 | "pattern is prefilled with the default branch" |
| 448 | ); | 407 | ); |
| 449 | - let owner_csrf = csrf_for(&http, &bob).await; | 408 | + let owner_csrf = csrf_for(&http, "/settings/keys", &bob).await; |
| 450 | | 409 | |
| 451 | let added = http | 410 | let added = http |
| 452 | .post_form( | 411 | .post_form( |
| @@ -602,7 +561,7 @@ async fn branch_protection_end_to_end() { |
| 602 | .get("/bob/app/settings?section=branches", Some(&dan)) | 561 | .get("/bob/app/settings?section=branches", Some(&dan)) |
| 603 | .await; | 562 | .await; |
| 604 | assert_eq!(dan_page.status, 403, "write collaborator settings page"); | 563 | assert_eq!(dan_page.status, 403, "write collaborator settings page"); |
| 605 | - let dan_csrf = csrf_for(&http, &dan).await; | 564 | + let dan_csrf = csrf_for(&http, "/settings/keys", &dan).await; |
| 606 | let dan_save = http | 565 | let dan_save = http |
| 607 | .post_form( | 566 | .post_form( |
| 608 | "/bob/app/settings/branches", | 567 | "/bob/app/settings/branches", |
| @@ -638,7 +597,7 @@ async fn branch_protection_end_to_end() { |
| 638 | .contains("href=\"/bob/app/settings\""), | 597 | .contains("href=\"/bob/app/settings\""), |
| 639 | "Settings tab shows for an Admin collaborator" | 598 | "Settings tab shows for an Admin collaborator" |
| 640 | ); | 599 | ); |
| 641 | - let carol_csrf = csrf_for(&http, &carol).await; | 600 | + let carol_csrf = csrf_for(&http, "/settings/keys", &carol).await; |
| 642 | let carol_save = http | 601 | let carol_save = http |
| 643 | .post_form( | 602 | .post_form( |
| 644 | "/bob/app/settings/branches", | 603 | "/bob/app/settings/branches", |
| @@ -746,13 +705,11 @@ fn git_head(data_dir: &Path, repo_id: &str) -> String { |
| 746 | } | 705 | } |
| 747 | | 706 | |
| 748 | fn selected_branch(body: &str) -> Option<String> { | 707 | fn selected_branch(body: &str) -> Option<String> { |
| 749 | - let doc = scraper::Html::parse_document(body); | 708 | + attr_of( |
| 750 | - let selector = | 709 | + body, |
| 751 | - scraper::Selector::parse("select[name=\"default_branch\"] option[selected]").expect("sel"); | 710 | + "select[name=\"default_branch\"] option[selected]", |
| 752 | - doc.select(&selector) | 711 | + "value", |
| 753 | - .next() | 712 | + ) |
| 754 | - .and_then(|el| el.value().attr("value")) | | |
| 755 | - .map(str::to_owned) | | |
| 756 | } | 713 | } |
| 757 | | 714 | |
| 758 | #[tokio::test] | 715 | #[tokio::test] |
| @@ -762,17 +719,17 @@ async fn general_settings_end_to_end() { |
| 762 | return; | 719 | return; |
| 763 | } | 720 | } |
| 764 | | 721 | |
| 765 | - let root = tempfile::Builder::new() | 722 | + let root = crate::common::temp_dir("fgen"); |
| 766 | - .prefix("fgen") | | |
| 767 | - .tempdir_in("/tmp") | | |
| 768 | - .expect("temp dir"); | | |
| 769 | let dir = root.path().to_path_buf(); | 723 | let dir = root.path().to_path_buf(); |
| 770 | - let ports = pick_ports(); | 724 | + let (_, ports) = provision( |
| 771 | - let config = write_config(&dir, ports); | 725 | + &dir, |
| 772 | - | 726 | + "", |
| 773 | - admin(&config, &["create-user", "tahinli", "--admin"]); | 727 | + &[ |
| 774 | - admin(&config, &["create-user", "bob"]); | 728 | + &["create-user", "tahinli", "--admin"], |
| 775 | - admin(&config, &["create-user", "carol"]); | 729 | + &["create-user", "bob"], |
| | 730 | + &["create-user", "carol"], |
| | 731 | + ], |
| | 732 | + ); |
| 776 | | 733 | |
| 777 | let gen_id = { | 734 | let gen_id = { |
| 778 | let store = Store::open(&dir.join("forge.db")) | 735 | let store = Store::open(&dir.join("forge.db")) |
| @@ -823,7 +780,7 @@ async fn general_settings_end_to_end() { |
| 823 | .contains("href=\"/bob/gen/settings?section=danger\"") | 780 | .contains("href=\"/bob/gen/settings?section=danger\"") |
| 824 | ); | 781 | ); |
| 825 | | 782 | |
| 826 | - let csrf = csrf_for(&http, &bob).await; | 783 | + let csrf = csrf_for(&http, "/settings/keys", &bob).await; |
| 827 | let saved = http | 784 | let saved = http |
| 828 | .post_form( | 785 | .post_form( |
| 829 | "/bob/gen/settings/general", | 786 | "/bob/gen/settings/general", |
| @@ -907,7 +864,7 @@ async fn general_settings_end_to_end() { |
| 907 | .await; | 864 | .await; |
| 908 | assert!(long_page.body.contains("at most 350 characters")); | 865 | assert!(long_page.body.contains("at most 350 characters")); |
| 909 | | 866 | |
| 910 | - let vis_csrf = csrf_for(&http, &bob).await; | 867 | + let vis_csrf = csrf_for(&http, "/settings/keys", &bob).await; |
| 911 | let no_ack = http | 868 | let no_ack = http |
| 912 | .post_form( | 869 | .post_form( |
| 913 | "/bob/gen/settings/visibility", | 870 | "/bob/gen/settings/visibility", |
| @@ -961,7 +918,7 @@ async fn general_settings_end_to_end() { |
| 961 | "anonymous on public" | 918 | "anonymous on public" |
| 962 | ); | 919 | ); |
| 963 | | 920 | |
| 964 | - let arch_csrf = csrf_for(&http, &bob).await; | 921 | + let arch_csrf = csrf_for(&http, "/settings/keys", &bob).await; |
| 965 | let archive = http | 922 | let archive = http |
| 966 | .post_form( | 923 | .post_form( |
| 967 | "/bob/gen/settings/archive", | 924 | "/bob/gen/settings/archive", |
| @@ -996,7 +953,7 @@ async fn general_settings_end_to_end() { |
| 996 | | 953 | |
| 997 | let carol_page = http.get("/bob/gen/settings", Some(&carol)).await; | 954 | let carol_page = http.get("/bob/gen/settings", Some(&carol)).await; |
| 998 | assert_eq!(carol_page.status, 403, "write collaborator settings page"); | 955 | assert_eq!(carol_page.status, 403, "write collaborator settings page"); |
| 999 | - let carol_csrf = csrf_for(&http, &carol).await; | 956 | + let carol_csrf = csrf_for(&http, "/settings/keys", &carol).await; |
| 1000 | let carol_general = http | 957 | let carol_general = http |
| 1001 | .post_form( | 958 | .post_form( |
| 1002 | "/bob/gen/settings/general", | 959 | "/bob/gen/settings/general", |
| @@ -1055,7 +1012,7 @@ async fn general_settings_end_to_end() { |
| 1055 | "empty repo notice" | 1012 | "empty repo notice" |
| 1056 | ); | 1013 | ); |
| 1057 | assert!(selected_branch(&empty_page.body).is_none()); | 1014 | assert!(selected_branch(&empty_page.body).is_none()); |
| 1058 | - let empty_csrf = csrf_for(&http, &bob).await; | 1015 | + let empty_csrf = csrf_for(&http, "/settings/keys", &bob).await; |
| 1059 | let empty_save = http | 1016 | let empty_save = http |
| 1060 | .post_form( | 1017 | .post_form( |
| 1061 | "/bob/empty/settings/general", | 1018 | "/bob/empty/settings/general", |
| @@ -1,49 +1,13 @@ |
| 1 | use crate::common::{ | 1 | use crate::common::{ |
| 2 | - Http, Resp, bin, describe, input_value, launch, login, pick_ports, tool_on_path, write_config, | 2 | + Http, PW, Resp, csrf_for, form_action, init_bare, launch, login, provision, tool_on_path, |
| 3 | }; | 3 | }; |
| 4 | -use std::fs; | | |
| 5 | -use std::process::Command; | | |
| 6 | | 4 | |
| 7 | use forge_core::store::orgs::OrgMemberRole; | 5 | use forge_core::store::orgs::OrgMemberRole; |
| 8 | use forge_core::{Store, Visibility}; | 6 | use forge_core::{Store, Visibility}; |
| 9 | use reqwest::header::LOCATION; | 7 | use reqwest::header::LOCATION; |
| 10 | | 8 | |
| 11 | -const PW: &str = "tahinli-password-123"; | | |
| 12 | - | | |
| 13 | -fn form_action(body: &str, suffix: &str) -> String { | | |
| 14 | - let doc = scraper::Html::parse_document(body); | | |
| 15 | - let selector = scraper::Selector::parse("form").expect("selector"); | | |
| 16 | - doc.select(&selector) | | |
| 17 | - .filter_map(|el| el.value().attr("action")) | | |
| 18 | - .find(|action| action.ends_with(suffix)) | | |
| 19 | - .unwrap_or_else(|| panic!("no form ending in {suffix} on page")) | | |
| 20 | - .to_owned() | | |
| 21 | -} | | |
| 22 | - | | |
| 23 | -fn admin(config: &std::path::Path, args: &[&str]) { | | |
| 24 | - let out = Command::new(bin()) | | |
| 25 | - .arg("--config") | | |
| 26 | - .arg(config) | | |
| 27 | - .arg("admin") | | |
| 28 | - .args(args) | | |
| 29 | - .env("FORGE_PASSWORD", PW) | | |
| 30 | - .output() | | |
| 31 | - .expect("run admin command"); | | |
| 32 | - assert!( | | |
| 33 | - out.status.success(), | | |
| 34 | - "admin {args:?} failed:\n{}", | | |
| 35 | - describe(&out) | | |
| 36 | - ); | | |
| 37 | -} | | |
| 38 | - | | |
| 39 | -async fn csrf_for(http: &Http, session: &str) -> String { | | |
| 40 | - let page = http.get("/settings/keys", Some(session)).await; | | |
| 41 | - assert_eq!(page.status, 200, "GET /settings/keys"); | | |
| 42 | - input_value(&page.body, "csrf") | | |
| 43 | -} | | |
| 44 | - | | |
| 45 | async fn offer(http: &Http, session: &str, owner: &str, repo: &str, to: &str) -> Resp { | 9 | async fn offer(http: &Http, session: &str, owner: &str, repo: &str, to: &str) -> Resp { |
| 46 | - let csrf = csrf_for(http, session).await; | 10 | + let csrf = csrf_for(http, "/settings/keys", session).await; |
| 47 | http.post_form( | 11 | http.post_form( |
| 48 | &format!("/{owner}/{repo}/settings/transfer"), | 12 | &format!("/{owner}/{repo}/settings/transfer"), |
| 49 | &[ | 13 | &[ |
| @@ -59,7 +23,7 @@ async fn offer(http: &Http, session: &str, owner: &str, repo: &str, to: &str) -> |
| 59 | async fn act_from(http: &Http, session: &str, page: &str, suffix: &str) -> Resp { | 23 | async fn act_from(http: &Http, session: &str, page: &str, suffix: &str) -> Resp { |
| 60 | let body = http.get(page, Some(session)).await.body; | 24 | let body = http.get(page, Some(session)).await.body; |
| 61 | let action = form_action(&body, suffix); | 25 | let action = form_action(&body, suffix); |
| 62 | - let csrf = csrf_for(http, session).await; | 26 | + let csrf = csrf_for(http, "/settings/keys", session).await; |
| 63 | http.post_form(&action, &[("csrf", &csrf)], Some(session)) | 27 | http.post_form(&action, &[("csrf", &csrf)], Some(session)) |
| 64 | .await | 28 | .await |
| 65 | } | 29 | } |
| @@ -71,18 +35,19 @@ async fn repo_transfer_offers_declines_cancels_and_org_targets() { |
| 71 | return; | 35 | return; |
| 72 | } | 36 | } |
| 73 | | 37 | |
| 74 | - let root = tempfile::Builder::new() | 38 | + let root = crate::common::temp_dir("frt"); |
| 75 | - .prefix("frt") | | |
| 76 | - .tempdir_in("/tmp") | | |
| 77 | - .expect("temp dir"); | | |
| 78 | let dir = root.path().to_path_buf(); | 39 | let dir = root.path().to_path_buf(); |
| 79 | - let ports = pick_ports(); | 40 | + let (_, ports) = provision( |
| 80 | - let config = write_config(&dir, ports); | 41 | + &dir, |
| 81 | - | 42 | + "", |
| 82 | - admin(&config, &["create-user", "tahinli", "--admin"]); | 43 | + &[ |
| 83 | - for name in ["bob", "carol", "dave", "eve"] { | 44 | + &["create-user", "tahinli", "--admin"], |
| 84 | - admin(&config, &["create-user", name]); | 45 | + &["create-user", "bob"], |
| 85 | - } | 46 | + &["create-user", "carol"], |
| | 47 | + &["create-user", "dave"], |
| | 48 | + &["create-user", "eve"], |
| | 49 | + ], |
| | 50 | + ); |
| 86 | { | 51 | { |
| 87 | let store = Store::open(&dir.join("forge.db")) | 52 | let store = Store::open(&dir.join("forge.db")) |
| 88 | .await | 53 | .await |
| @@ -108,14 +73,7 @@ async fn repo_transfer_offers_declines_cancels_and_org_targets() { |
| 108 | .await | 73 | .await |
| 109 | .expect("eve member"); | 74 | .expect("eve member"); |
| 110 | for repo in [&priv_repo, &pub_repo] { | 75 | for repo in [&priv_repo, &pub_repo] { |
| 111 | - let path = forge_git::repo::repo_path(&dir, &repo.id).expect("repo path"); | 76 | + init_bare(&dir, &repo.id); |
| 112 | - fs::create_dir_all(path.parent().expect("parent")).expect("create parent"); | | |
| 113 | - let out = Command::new("git") | | |
| 114 | - .args(["init", "--bare", "--quiet", "--initial-branch=main"]) | | |
| 115 | - .arg(&path) | | |
| 116 | - .output() | | |
| 117 | - .expect("run git init"); | | |
| 118 | - assert!(out.status.success(), "git init: {}", describe(&out)); | | |
| 119 | } | 77 | } |
| 120 | } | 78 | } |
| 121 | | 79 | |
| @@ -1,24 +1,4 @@ |
| 1 | -use crate::common::{Http, Server, bin, describe, launch, login, pick_ports, write_config}; | 1 | +use crate::common::{Http, PW, Server, boot_forge, login}; |
| 2 | -use std::path::Path; | | |
| 3 | -use std::process::Command; | | |
| 4 | - | | |
| 5 | -const PW: &str = "tahinli-password-123"; | | |
| 6 | - | | |
| 7 | -fn admin(config: &Path, args: &[&str]) { | | |
| 8 | - let out = Command::new(bin()) | | |
| 9 | - .arg("--config") | | |
| 10 | - .arg(config) | | |
| 11 | - .arg("admin") | | |
| 12 | - .args(args) | | |
| 13 | - .env("FORGE_PASSWORD", PW) | | |
| 14 | - .output() | | |
| 15 | - .expect("run admin command"); | | |
| 16 | - assert!( | | |
| 17 | - out.status.success(), | | |
| 18 | - "admin {args:?} failed:\n{}", | | |
| 19 | - describe(&out) | | |
| 20 | - ); | | |
| 21 | -} | | |
| 22 | | 2 | |
| 23 | struct Env { | 3 | struct Env { |
| 24 | _root: tempfile::TempDir, | 4 | _root: tempfile::TempDir, |
| @@ -29,10 +9,7 @@ struct Env { |
| 29 | async fn start() -> Env { | 9 | async fn start() -> Env { |
| 30 | let root = tempfile::tempdir().expect("temp dir"); | 10 | let root = tempfile::tempdir().expect("temp dir"); |
| 31 | let dir = root.path().to_path_buf(); | 11 | let dir = root.path().to_path_buf(); |
| 32 | - let ports = pick_ports(); | 12 | + let (server, ports) = boot_forge(&dir, "", &[&["create-user", "tahinli", "--admin"]]).await; |
| 33 | - let config = write_config(&dir, ports); | | |
| 34 | - admin(&config, &["create-user", "tahinli", "--admin"]); | | |
| 35 | - let (server, ports) = launch(&dir, ports).await; | | |
| 36 | let http = Http::new(ports.http); | 13 | let http = Http::new(ports.http); |
| 37 | Env { | 14 | Env { |
| 38 | _root: root, | 15 | _root: root, |
| @@ -1,13 +1,8 @@ |
| 1 | -use crate::common::{ | 1 | +use crate::common::{Http, PW, Server, boot_forge, csrf_for, login, next_changed}; |
| 2 | - Http, Server, bin, describe, input_value, launch, login, next_changed, pick_ports, write_config, | 2 | +use std::path::PathBuf; |
| 3 | -}; | | |
| 4 | -use std::path::{Path, PathBuf}; | | |
| 5 | -use std::process::Command; | | |
| 6 | | 3 | |
| 7 | use reqwest::header::{CONTENT_TYPE, LOCATION}; | 4 | use reqwest::header::{CONTENT_TYPE, LOCATION}; |
| 8 | | 5 | |
| 9 | -const PW: &str = "tahinli-password-123"; | | |
| 10 | - | | |
| 11 | fn path_of(url: &str) -> String { | 6 | fn path_of(url: &str) -> String { |
| 12 | let rest = url.split_once("//").map_or(url, |(_, r)| r); | 7 | let rest = url.split_once("//").map_or(url, |(_, r)| r); |
| 13 | match rest.find('/') { | 8 | match rest.find('/') { |
| @@ -26,22 +21,6 @@ fn link_href(body: &str, text: &str) -> String { |
| 26 | .to_owned() | 21 | .to_owned() |
| 27 | } | 22 | } |
| 28 | | 23 | |
| 29 | -fn admin(config: &Path, args: &[&str]) { | | |
| 30 | - let out = Command::new(bin()) | | |
| 31 | - .arg("--config") | | |
| 32 | - .arg(config) | | |
| 33 | - .arg("admin") | | |
| 34 | - .args(args) | | |
| 35 | - .env("FORGE_PASSWORD", PW) | | |
| 36 | - .output() | | |
| 37 | - .expect("run admin command"); | | |
| 38 | - assert!( | | |
| 39 | - out.status.success(), | | |
| 40 | - "admin {args:?} failed:\n{}", | | |
| 41 | - describe(&out) | | |
| 42 | - ); | | |
| 43 | -} | | |
| 44 | - | | |
| 45 | struct Env { | 24 | struct Env { |
| 46 | _root: tempfile::TempDir, | 25 | _root: tempfile::TempDir, |
| 47 | _server: Server, | 26 | _server: Server, |
| @@ -52,11 +31,12 @@ struct Env { |
| 52 | async fn start() -> Env { | 31 | async fn start() -> Env { |
| 53 | let root = tempfile::tempdir().expect("temp dir"); | 32 | let root = tempfile::tempdir().expect("temp dir"); |
| 54 | let dir: PathBuf = root.path().to_path_buf(); | 33 | let dir: PathBuf = root.path().to_path_buf(); |
| 55 | - let ports = pick_ports(); | 34 | + let (server, ports) = boot_forge( |
| 56 | - let config = write_config(&dir, ports); | 35 | + &dir, |
| 57 | - admin(&config, &["create-user", "tahinli"]); | 36 | + "", |
| 58 | - admin(&config, &["create-user", "bob"]); | 37 | + &[&["create-user", "tahinli"], &["create-user", "bob"]], |
| 59 | - let (server, ports) = launch(&dir, ports).await; | 38 | + ) |
| | 39 | + .await; |
| 60 | Env { | 40 | Env { |
| 61 | _root: root, | 41 | _root: root, |
| 62 | _server: server, | 42 | _server: server, |
| @@ -72,9 +52,7 @@ async fn create( |
| 72 | visibility: &str, | 52 | visibility: &str, |
| 73 | files: &[(&str, &str)], | 53 | files: &[(&str, &str)], |
| 74 | ) -> String { | 54 | ) -> String { |
| 75 | - let page = http.get("/snippets/new", Some(cookie)).await; | 55 | + let csrf = csrf_for(http, "/snippets/new", cookie).await; |
| 76 | - assert_eq!(page.status, 200, "GET /snippets/new"); | | |
| 77 | - let csrf = input_value(&page.body, "csrf"); | | |
| 78 | let mut form: Vec<(String, String)> = vec![ | 56 | let mut form: Vec<(String, String)> = vec![ |
| 79 | ("csrf".into(), csrf), | 57 | ("csrf".into(), csrf), |
| 80 | ("title".into(), title.into()), | 58 | ("title".into(), title.into()), |
| @@ -133,7 +111,7 @@ async fn snippet_streams_follow_writes() { |
| 133 | assert_eq!(item_events.status().as_u16(), 200, "snippet stream"); | 111 | assert_eq!(item_events.status().as_u16(), 200, "snippet stream"); |
| 134 | | 112 | |
| 135 | let edit_path = format!("/snippets/{id}/edit"); | 113 | let edit_path = format!("/snippets/{id}/edit"); |
| 136 | - let csrf = input_value(&env.app.get(&edit_path, Some(&tahinli)).await.body, "csrf"); | 114 | + let csrf = csrf_for(&env.app, &edit_path, &tahinli).await; |
| 137 | let saved = env | 115 | let saved = env |
| 138 | .app | 116 | .app |
| 139 | .post_form( | 117 | .post_form( |
| @@ -163,13 +141,7 @@ async fn snippet_streams_follow_writes() { |
| 163 | .await; | 141 | .await; |
| 164 | next_changed(&mut list_events, "a create").await; | 142 | next_changed(&mut list_events, "a create").await; |
| 165 | | 143 | |
| 166 | - let csrf = input_value( | 144 | + let csrf = csrf_for(&env.app, &format!("/snippets/{other}"), &tahinli).await; |
| 167 | - &env.app | | |
| 168 | - .get(&format!("/snippets/{other}"), Some(&tahinli)) | | |
| 169 | - .await | | |
| 170 | - .body, | | |
| 171 | - "csrf", | | |
| 172 | - ); | | |
| 173 | let deleted = env | 145 | let deleted = env |
| 174 | .app | 146 | .app |
| 175 | .post_form( | 147 | .post_form( |
| @@ -233,9 +205,7 @@ async fn create_edit_and_revisions() { |
| 233 | assert!(view.body.contains("hello"), "file contents are shown"); | 205 | assert!(view.body.contains("hello"), "file contents are shown"); |
| 234 | | 206 | |
| 235 | let edit_path = format!("/snippets/{id}/edit"); | 207 | let edit_path = format!("/snippets/{id}/edit"); |
| 236 | - let page = env.app.get(&edit_path, Some(&tahinli)).await; | 208 | + let csrf = csrf_for(&env.app, &edit_path, &tahinli).await; |
| 237 | - assert_eq!(page.status, 200, "GET edit"); | | |
| 238 | - let csrf = input_value(&page.body, "csrf"); | | |
| 239 | let saved = env | 209 | let saved = env |
| 240 | .app | 210 | .app |
| 241 | .post_form( | 211 | .post_form( |
| @@ -317,8 +287,7 @@ async fn private_snippet_is_hidden_from_others() { |
| 317 | .get(&format!("/snippets/{id}/edit"), Some(&bob)) | 287 | .get(&format!("/snippets/{id}/edit"), Some(&bob)) |
| 318 | .await; | 288 | .await; |
| 319 | assert_eq!(page.status, 404, "bob cannot open the editor"); | 289 | assert_eq!(page.status, 404, "bob cannot open the editor"); |
| 320 | - let bob_page = env.app.get("/snippets/new", Some(&bob)).await; | 290 | + let bob_csrf = csrf_for(&env.app, "/snippets/new", &bob).await; |
| 321 | - let bob_csrf = input_value(&bob_page.body, "csrf"); | | |
| 322 | let res = env | 291 | let res = env |
| 323 | .app | 292 | .app |
| 324 | .post_form( | 293 | .post_form( |
| @@ -414,11 +383,7 @@ async fn unlisted_is_by_link_only_and_delete_removes_it() { |
| 414 | 200 | 383 | 200 |
| 415 | ); | 384 | ); |
| 416 | | 385 | |
| 417 | - let page = env | 386 | + let csrf = csrf_for(&env.app, &format!("/snippets/{id}"), &tahinli).await; |
| 418 | - .app | | |
| 419 | - .get(&format!("/snippets/{id}"), Some(&tahinli)) | | |
| 420 | - .await; | | |
| 421 | - let csrf = input_value(&page.body, "csrf"); | | |
| 422 | let res = env | 387 | let res = env |
| 423 | .app | 388 | .app |
| 424 | .post_form( | 389 | .post_form( |
| @@ -438,8 +403,7 @@ async fn unlisted_is_by_link_only_and_delete_removes_it() { |
| 438 | async fn bad_input_redisplays_the_form_with_an_error() { | 403 | async fn bad_input_redisplays_the_form_with_an_error() { |
| 439 | let env = start().await; | 404 | let env = start().await; |
| 440 | let tahinli = login(&env.app, "tahinli", PW).await; | 405 | let tahinli = login(&env.app, "tahinli", PW).await; |
| 441 | - let page = env.app.get("/snippets/new", Some(&tahinli)).await; | 406 | + let csrf = csrf_for(&env.app, "/snippets/new", &tahinli).await; |
| 442 | - let csrf = input_value(&page.body, "csrf"); | | |
| 443 | let res = env | 407 | let res = env |
| 444 | .app | 408 | .app |
| 445 | .post_form( | 409 | .post_form( |
| @@ -1,6 +1,5 @@ |
| 1 | use crate::common::{ | 1 | use crate::common::{ |
| 2 | - Http, PW, Resp, Server, admin, describe, init_bare, input_value, launch, login, pick_ports, | 2 | + Http, PW, Resp, Server, csrf_for, describe, init_bare, launch, login, provision, tool_on_path, |
| 3 | - tool_on_path, write_config, | | |
| 4 | }; | 3 | }; |
| 5 | use std::path::{Path, PathBuf}; | 4 | use std::path::{Path, PathBuf}; |
| 6 | use std::process::{Command, Stdio}; | 5 | use std::process::{Command, Stdio}; |
| @@ -19,15 +18,13 @@ where |
| 19 | F: FnOnce(PathBuf, Store) -> Fut, | 18 | F: FnOnce(PathBuf, Store) -> Fut, |
| 20 | Fut: std::future::Future<Output = ()>, | 19 | Fut: std::future::Future<Output = ()>, |
| 21 | { | 20 | { |
| 22 | - let root = tempfile::Builder::new() | 21 | + let root = crate::common::temp_dir("fst"); |
| 23 | - .prefix("fst") | | |
| 24 | - .tempdir_in("/tmp") | | |
| 25 | - .expect("temp dir"); | | |
| 26 | let dir = root.path().to_path_buf(); | 22 | let dir = root.path().to_path_buf(); |
| 27 | - let ports = pick_ports(); | 23 | + let (_, ports) = provision( |
| 28 | - let config = write_config(&dir, ports); | 24 | + &dir, |
| 29 | - admin(&config, &["create-user", "tahinli"]); | 25 | + "", |
| 30 | - admin(&config, &["create-user", "bob"]); | 26 | + &[&["create-user", "tahinli"], &["create-user", "bob"]], |
| | 27 | + ); |
| 31 | let store = Store::open(&dir.join("forge.db")) | 28 | let store = Store::open(&dir.join("forge.db")) |
| 32 | .await | 29 | .await |
| 33 | .expect("open store"); | 30 | .expect("open store"); |
| @@ -139,7 +136,7 @@ async fn star_round_trip_shows_the_count() { |
| 139 | "star button with zero: {}", | 136 | "star button with zero: {}", |
| 140 | page.body | 137 | page.body |
| 141 | ); | 138 | ); |
| 142 | - let csrf = input_value(&page.body, "csrf"); | 139 | + let csrf = csrf_for(&env.http, "/tahinli/pub", &bob).await; |
| 143 | | 140 | |
| 144 | let res = post_star(&env.http, "/tahinli/pub/star", &csrf, Some(&bob), None).await; | 141 | let res = post_star(&env.http, "/tahinli/pub/star", &csrf, Some(&bob), None).await; |
| 145 | assert_eq!(res.status, 303, "star: {}", res.body); | 142 | assert_eq!(res.status, 303, "star: {}", res.body); |
| @@ -231,8 +228,7 @@ async fn explore_lists_public_repos_and_searches_literally() { |
| 231 | assert_eq!(repo_names(&page.body), vec!["tahinli/pct%x".to_owned()]); | 228 | assert_eq!(repo_names(&page.body), vec!["tahinli/pct%x".to_owned()]); |
| 232 | | 229 | |
| 233 | let bob = login(&env.http, "bob", PW).await; | 230 | let bob = login(&env.http, "bob", PW).await; |
| 234 | - let page = env.http.get("/tahinli/pub", Some(&bob)).await; | 231 | + let csrf = csrf_for(&env.http, "/tahinli/pub", &bob).await; |
| 235 | - let csrf = input_value(&page.body, "csrf"); | | |
| 236 | let res = post_star(&env.http, "/tahinli/pub/star", &csrf, Some(&bob), None).await; | 232 | let res = post_star(&env.http, "/tahinli/pub/star", &csrf, Some(&bob), None).await; |
| 237 | assert_eq!(res.status, 303); | 233 | assert_eq!(res.status, 303); |
| 238 | let by_name = repo_names(&env.http.get("/explore?sort=name", None).await.body); | 234 | let by_name = repo_names(&env.http.get("/explore?sort=name", None).await.body); |
| @@ -1,19 +1,11 @@ |
| 1 | -use crate::common::{ | 1 | +use crate::common::{Http, PW, Server, attr_of, boot_forge, cookie_named, csrf_for, login}; |
| 2 | - Http, Server, bin, cookie_named, describe, input_value, launch, login, pick_ports, write_config, | | |
| 3 | -}; | | |
| 4 | -use std::path::Path; | | |
| 5 | -use std::process::Command; | | |
| 6 | | 2 | |
| 7 | -const PW: &str = "tahinli-password-123"; | 3 | +fn html_attr(body: &str, name: &str) -> Option<String> { |
| 8 | - | 4 | + attr_of(body, "html", name) |
| 9 | -fn html_theme(body: &str) -> Option<String> { | | |
| 10 | - let doc = scraper::Html::parse_document(body); | | |
| 11 | - doc.root_element().attr("data-theme").map(str::to_owned) | | |
| 12 | } | 5 | } |
| 13 | | 6 | |
| 14 | -fn html_attr(body: &str, name: &str) -> Option<String> { | 7 | +fn html_theme(body: &str) -> Option<String> { |
| 15 | - let doc = scraper::Html::parse_document(body); | 8 | + html_attr(body, "data-theme") |
| 16 | - doc.root_element().attr(name).map(str::to_owned) | | |
| 17 | } | 9 | } |
| 18 | | 10 | |
| 19 | fn html_colours(body: &str) -> [Option<String>; 4] { | 11 | fn html_colours(body: &str) -> [Option<String>; 4] { |
| @@ -35,26 +27,21 @@ fn checked_colours(body: &str) -> [Option<String>; 4] { |
| 35 | } | 27 | } |
| 36 | | 28 | |
| 37 | fn checked_radio(body: &str, name: &str) -> Option<String> { | 29 | fn checked_radio(body: &str, name: &str) -> Option<String> { |
| 38 | - let doc = scraper::Html::parse_document(body); | 30 | + attr_of( |
| 39 | - let selector = | 31 | + body, |
| 40 | - scraper::Selector::parse(&format!("input[type=\"radio\"][name=\"{name}\"][checked]")) | 32 | + &format!("input[type=\"radio\"][name=\"{name}\"][checked]"), |
| 41 | - .expect("selector"); | 33 | + "value", |
| 42 | - doc.select(&selector) | 34 | + ) |
| 43 | - .next() | | |
| 44 | - .and_then(|el| el.value().attr("value")) | | |
| 45 | - .map(str::to_owned) | | |
| 46 | } | 35 | } |
| 47 | | 36 | |
| 48 | fn selected_option(body: &str, select: &str) -> Option<String> { | 37 | fn selected_option(body: &str, select: &str) -> Option<String> { |
| 49 | - let doc = scraper::Html::parse_document(body); | 38 | + attr_of( |
| 50 | - let selector = scraper::Selector::parse(&format!( | 39 | + body, |
| 51 | - "select[name=\"{select}\"] option[selected], input[name=\"{select}\"][checked], button[name=\"{select}\"][aria-pressed=\"true\"]" | 40 | + &format!( |
| 52 | - )) | 41 | + "select[name=\"{select}\"] option[selected], input[name=\"{select}\"][checked], button[name=\"{select}\"][aria-pressed=\"true\"]" |
| 53 | - .expect("selector"); | 42 | + ), |
| 54 | - doc.select(&selector) | 43 | + "value", |
| 55 | - .next() | 44 | + ) |
| 56 | - .and_then(|el| el.value().attr("value")) | | |
| 57 | - .map(str::to_owned) | | |
| 58 | } | 45 | } |
| 59 | | 46 | |
| 60 | fn theme_button(body: &str) -> (String, String) { | 47 | fn theme_button(body: &str) -> (String, String) { |
| @@ -81,22 +68,6 @@ fn theme_button(body: &str) -> (String, String) { |
| 81 | (value, label) | 68 | (value, label) |
| 82 | } | 69 | } |
| 83 | | 70 | |
| 84 | -fn admin(config: &Path, args: &[&str]) { | | |
| 85 | - let out = Command::new(bin()) | | |
| 86 | - .arg("--config") | | |
| 87 | - .arg(config) | | |
| 88 | - .arg("admin") | | |
| 89 | - .args(args) | | |
| 90 | - .env("FORGE_PASSWORD", PW) | | |
| 91 | - .output() | | |
| 92 | - .expect("run admin command"); | | |
| 93 | - assert!( | | |
| 94 | - out.status.success(), | | |
| 95 | - "admin {args:?} failed:\n{}", | | |
| 96 | - describe(&out) | | |
| 97 | - ); | | |
| 98 | -} | | |
| 99 | - | | |
| 100 | struct Env { | 71 | struct Env { |
| 101 | _root: tempfile::TempDir, | 72 | _root: tempfile::TempDir, |
| 102 | _server: Server, | 73 | _server: Server, |
| @@ -106,10 +77,7 @@ struct Env { |
| 106 | async fn start() -> Env { | 77 | async fn start() -> Env { |
| 107 | let root = tempfile::tempdir().expect("temp dir"); | 78 | let root = tempfile::tempdir().expect("temp dir"); |
| 108 | let dir = root.path().to_path_buf(); | 79 | let dir = root.path().to_path_buf(); |
| 109 | - let ports = pick_ports(); | 80 | + let (server, ports) = boot_forge(&dir, "", &[&["create-user", "tahinli"]]).await; |
| 110 | - let config = write_config(&dir, ports); | | |
| 111 | - admin(&config, &["create-user", "tahinli"]); | | |
| 112 | - let (server, ports) = launch(&dir, ports).await; | | |
| 113 | let http = Http::new(ports.http); | 81 | let http = Http::new(ports.http); |
| 114 | Env { | 82 | Env { |
| 115 | _root: root, | 83 | _root: root, |
| @@ -134,7 +102,7 @@ async fn appearance_setting_persists_and_renders_the_html_attribute() { |
| 134 | Some("light"), | 102 | Some("light"), |
| 135 | "the default is light, which renders data-theme=light" | 103 | "the default is light, which renders data-theme=light" |
| 136 | ); | 104 | ); |
| 137 | - let csrf = input_value(&page.body, "csrf"); | 105 | + let csrf = csrf_for(&env.http, "/settings/appearance", &session).await; |
| 138 | | 106 | |
| 139 | let saved = env | 107 | let saved = env |
| 140 | .http | 108 | .http |
| @@ -205,7 +173,7 @@ async fn light_and_dark_colours_save_independently_and_render_on_html() { |
| 205 | let defaults = ["sage", "sage", "ink", "ink"].map(str::to_owned); | 173 | let defaults = ["sage", "sage", "ink", "ink"].map(str::to_owned); |
| 206 | assert_eq!(checked_colours(&page.body), defaults.clone().map(Some)); | 174 | assert_eq!(checked_colours(&page.body), defaults.clone().map(Some)); |
| 207 | assert_eq!(html_colours(&page.body), defaults.map(Some)); | 175 | assert_eq!(html_colours(&page.body), defaults.map(Some)); |
| 208 | - let csrf = input_value(&page.body, "csrf"); | 176 | + let csrf = csrf_for(&env.http, "/settings/appearance", &session).await; |
| 209 | | 177 | |
| 210 | let saved = env | 178 | let saved = env |
| 211 | .http | 179 | .http |
| @@ -325,8 +293,7 @@ async fn a_save_without_colour_fields_keeps_the_stored_colours() { |
| 325 | let env = start().await; | 293 | let env = start().await; |
| 326 | let session = login(&env.http, "tahinli", PW).await; | 294 | let session = login(&env.http, "tahinli", PW).await; |
| 327 | | 295 | |
| 328 | - let page = env.http.get("/settings/appearance", Some(&session)).await; | 296 | + let csrf = csrf_for(&env.http, "/settings/appearance", &session).await; |
| 329 | - let csrf = input_value(&page.body, "csrf"); | | |
| 330 | let saved = env | 297 | let saved = env |
| 331 | .http | 298 | .http |
| 332 | .post_form( | 299 | .post_form( |
| @@ -392,8 +359,7 @@ async fn appearance_save_without_a_valid_csrf_token_is_403() { |
| 392 | async fn unoffered_theme_or_language_is_rejected_and_nothing_is_saved() { | 359 | async fn unoffered_theme_or_language_is_rejected_and_nothing_is_saved() { |
| 393 | let env = start().await; | 360 | let env = start().await; |
| 394 | let session = login(&env.http, "tahinli", PW).await; | 361 | let session = login(&env.http, "tahinli", PW).await; |
| 395 | - let page = env.http.get("/settings/appearance", Some(&session)).await; | 362 | + let csrf = csrf_for(&env.http, "/settings/appearance", &session).await; |
| 396 | - let csrf = input_value(&page.body, "csrf"); | | |
| 397 | for form in [ | 363 | for form in [ |
| 398 | [ | 364 | [ |
| 399 | ("csrf", csrf.as_str()), | 365 | ("csrf", csrf.as_str()), |
| @@ -493,8 +459,7 @@ async fn appearance_page_needs_a_session() { |
| 493 | async fn signed_in_toggle_saves_the_preference_and_returns_to_back() { | 459 | async fn signed_in_toggle_saves_the_preference_and_returns_to_back() { |
| 494 | let env = start().await; | 460 | let env = start().await; |
| 495 | let session = login(&env.http, "tahinli", PW).await; | 461 | let session = login(&env.http, "tahinli", PW).await; |
| 496 | - let page = env.http.get("/settings/appearance", Some(&session)).await; | 462 | + let csrf = csrf_for(&env.http, "/settings/appearance", &session).await; |
| 497 | - let csrf = input_value(&page.body, "csrf"); | | |
| 498 | let saved = env | 463 | let saved = env |
| 499 | .http | 464 | .http |
| 500 | .post_form( | 465 | .post_form( |
| @@ -548,8 +513,7 @@ async fn signed_in_toggle_saves_the_preference_and_returns_to_back() { |
| 548 | async fn theme_toggle_with_an_unsafe_back_returns_to_the_root() { | 513 | async fn theme_toggle_with_an_unsafe_back_returns_to_the_root() { |
| 549 | let env = start().await; | 514 | let env = start().await; |
| 550 | let session = login(&env.http, "tahinli", PW).await; | 515 | let session = login(&env.http, "tahinli", PW).await; |
| 551 | - let page = env.http.get("/settings/appearance", Some(&session)).await; | 516 | + let csrf = csrf_for(&env.http, "/settings/appearance", &session).await; |
| 552 | - let csrf = input_value(&page.body, "csrf"); | | |
| 553 | for back in ["//evil.com", "https://evil.com", "/\\evil"] { | 517 | for back in ["//evil.com", "https://evil.com", "/\\evil"] { |
| 554 | let res = env | 518 | let res = env |
| 555 | .http | 519 | .http |
| @@ -610,7 +574,7 @@ async fn theme_button_cycles_light_dark_auto_light_for_signed_in_users() { |
| 610 | let back = "/settings/appearance"; | 574 | let back = "/settings/appearance"; |
| 611 | | 575 | |
| 612 | let page = env.http.get(back, Some(&session)).await; | 576 | let page = env.http.get(back, Some(&session)).await; |
| 613 | - let csrf = input_value(&page.body, "csrf"); | 577 | + let csrf = csrf_for(&env.http, back, &session).await; |
| 614 | assert_eq!(html_theme(&page.body).as_deref(), Some("light")); | 578 | assert_eq!(html_theme(&page.body).as_deref(), Some("light")); |
| 615 | | 579 | |
| 616 | let step = env | 580 | let step = env |
| @@ -691,7 +655,7 @@ async fn appearance_sidebar_side_saves_and_renders_on_html() { |
| 691 | html_attr(&page.body, "data-sidebar").as_deref(), | 655 | html_attr(&page.body, "data-sidebar").as_deref(), |
| 692 | Some("left") | 656 | Some("left") |
| 693 | ); | 657 | ); |
| 694 | - let csrf = input_value(&page.body, "csrf"); | 658 | + let csrf = csrf_for(&env.http, "/settings/appearance", &session).await; |
| 695 | | 659 | |
| 696 | let saved = env | 660 | let saved = env |
| 697 | .http | 661 | .http |
| @@ -1,33 +1,13 @@ |
| 1 | use crate::common::{ | 1 | use crate::common::{ |
| 2 | - Http, Resp, Server, bin, cookie_named, describe, input_value, launch, login, pick_ports, | 2 | + Http, PW, Resp, Server, cookie_named, csrf_for, input_value, launch, login, provision, |
| 3 | - write_config, | | |
| 4 | }; | 3 | }; |
| 5 | use std::fs; | 4 | use std::fs; |
| 6 | use std::future::Future; | 5 | use std::future::Future; |
| 7 | -use std::path::{Path, PathBuf}; | 6 | +use std::path::PathBuf; |
| 8 | -use std::process::Command; | | |
| 9 | | 7 | |
| 10 | use forge_core::{Store, Visibility}; | 8 | use forge_core::{Store, Visibility}; |
| 11 | use reqwest::header::LOCATION; | 9 | use reqwest::header::LOCATION; |
| 12 | | 10 | |
| 13 | -const PW: &str = "tahinli-password-123"; | | |
| 14 | - | | |
| 15 | -fn admin(config: &Path, args: &[&str]) { | | |
| 16 | - let out = Command::new(bin()) | | |
| 17 | - .arg("--config") | | |
| 18 | - .arg(config) | | |
| 19 | - .arg("admin") | | |
| 20 | - .args(args) | | |
| 21 | - .env("FORGE_PASSWORD", PW) | | |
| 22 | - .output() | | |
| 23 | - .expect("run admin command"); | | |
| 24 | - assert!( | | |
| 25 | - out.status.success(), | | |
| 26 | - "admin {args:?} failed:\n{}", | | |
| 27 | - describe(&out) | | |
| 28 | - ); | | |
| 29 | -} | | |
| 30 | - | | |
| 31 | async fn try_login(http: &Http, username: &str) -> Resp { | 11 | async fn try_login(http: &Http, username: &str) -> Resp { |
| 32 | let page = http.get("/login", None).await; | 12 | let page = http.get("/login", None).await; |
| 33 | assert_eq!(page.status, 200, "GET /login"); | 13 | assert_eq!(page.status, 200, "GET /login"); |
| @@ -60,11 +40,15 @@ where |
| 60 | { | 40 | { |
| 61 | let root = tempfile::tempdir().expect("temp dir"); | 41 | let root = tempfile::tempdir().expect("temp dir"); |
| 62 | let dir = root.path().to_path_buf(); | 42 | let dir = root.path().to_path_buf(); |
| 63 | - let ports = pick_ports(); | 43 | + let (_, ports) = provision( |
| 64 | - let config = write_config(&dir, ports); | 44 | + &dir, |
| 65 | - for user in ["dana", "tahinli", "bob"] { | 45 | + "", |
| 66 | - admin(&config, &["create-user", user]); | 46 | + &[ |
| 67 | - } | 47 | + &["create-user", "dana"], |
| | 48 | + &["create-user", "tahinli"], |
| | 49 | + &["create-user", "bob"], |
| | 50 | + ], |
| | 51 | + ); |
| 68 | let store = Store::open(&dir.join("forge.db")) | 52 | let store = Store::open(&dir.join("forge.db")) |
| 69 | .await | 53 | .await |
| 70 | .expect("open store"); | 54 | .expect("open store"); |
| @@ -117,7 +101,7 @@ async fn admin_delete_moves_content_to_ghost_and_pages_still_render() { |
| 117 | let page = http.get(&path, Some(&dana)).await; | 101 | let page = http.get(&path, Some(&dana)).await; |
| 118 | assert_eq!(page.status, 200, "{}", page.body); | 102 | assert_eq!(page.status, 200, "{}", page.body); |
| 119 | assert!(page.body.contains("Delete user"), "{}", page.body); | 103 | assert!(page.body.contains("Delete user"), "{}", page.body); |
| 120 | - let csrf = input_value(&page.body, "csrf"); | 104 | + let csrf = csrf_for(http, &path, &dana).await; |
| 121 | | 105 | |
| 122 | let wrong = http | 106 | let wrong = http |
| 123 | .post_form( | 107 | .post_form( |
| @@ -162,9 +146,7 @@ async fn self_delete_refuses_wrong_password_and_owned_repos() { |
| 162 | let http = &env.http; | 146 | let http = &env.http; |
| 163 | | 147 | |
| 164 | let tahinli = login(http, "tahinli", PW).await; | 148 | let tahinli = login(http, "tahinli", PW).await; |
| 165 | - let security = http.get("/settings/security", Some(&tahinli)).await; | 149 | + let csrf = csrf_for(http, "/settings/security", &tahinli).await; |
| 166 | - assert_eq!(security.status, 200); | | |
| 167 | - let csrf = input_value(&security.body, "csrf"); | | |
| 168 | let wrong = http | 150 | let wrong = http |
| 169 | .post_form( | 151 | .post_form( |
| 170 | "/settings/security/delete", | 152 | "/settings/security/delete", |
| @@ -188,8 +170,7 @@ async fn self_delete_refuses_wrong_password_and_owned_repos() { |
| 188 | ); | 170 | ); |
| 189 | | 171 | |
| 190 | let bob = login(http, "bob", PW).await; | 172 | let bob = login(http, "bob", PW).await; |
| 191 | - let security = http.get("/settings/security", Some(&bob)).await; | 173 | + let csrf = csrf_for(http, "/settings/security", &bob).await; |
| 192 | - let csrf = input_value(&security.body, "csrf"); | | |
| 193 | let refused = http | 174 | let refused = http |
| 194 | .post_form( | 175 | .post_form( |
| 195 | "/settings/security/delete", | 176 | "/settings/security/delete", |
| @@ -221,8 +202,7 @@ async fn self_delete_with_correct_password_signs_out_and_removes_login() { |
| 221 | let env = start(seed_issue_by_tahinli).await; | 202 | let env = start(seed_issue_by_tahinli).await; |
| 222 | let http = &env.http; | 203 | let http = &env.http; |
| 223 | let tahinli = login(http, "tahinli", PW).await; | 204 | let tahinli = login(http, "tahinli", PW).await; |
| 224 | - let security = http.get("/settings/security", Some(&tahinli)).await; | 205 | + let csrf = csrf_for(http, "/settings/security", &tahinli).await; |
| 225 | - let csrf = input_value(&security.body, "csrf"); | | |
| 226 | let done = http | 206 | let done = http |
| 227 | .post_form( | 207 | .post_form( |
| 228 | "/settings/security/delete", | 208 | "/settings/security/delete", |
| @@ -1,108 +1,11 @@ |
| 1 | use crate::common::{ | 1 | use crate::common::{ |
| 2 | - Http, Resp, bin, describe, input_value, launch, login, pick_ports, write_config, | 2 | + Http, PW, Resp, commit_file, create_token, csrf_for, git, init_bare, launch, login, |
| | 3 | + next_changed, ok, path_str, provision, |
| 3 | }; | 4 | }; |
| 4 | use std::fs; | 5 | use std::fs; |
| 5 | -use std::path::Path; | | |
| 6 | -use std::process::{Command, Output}; | | |
| 7 | -use std::time::Duration; | | |
| 8 | | 6 | |
| 9 | use forge_core::{Role, Store, Visibility}; | 7 | use forge_core::{Role, Store, Visibility}; |
| 10 | -use reqwest::header::{COOKIE, LOCATION}; | 8 | +use reqwest::header::LOCATION; |
| 11 | - | | |
| 12 | -const PW: &str = "tahinli-password-123"; | | |
| 13 | - | | |
| 14 | -fn admin(config: &Path, args: &[&str]) { | | |
| 15 | - let out = Command::new(bin()) | | |
| 16 | - .arg("--config") | | |
| 17 | - .arg(config) | | |
| 18 | - .arg("admin") | | |
| 19 | - .args(args) | | |
| 20 | - .env("FORGE_PASSWORD", PW) | | |
| 21 | - .output() | | |
| 22 | - .expect("run admin command"); | | |
| 23 | - assert!( | | |
| 24 | - out.status.success(), | | |
| 25 | - "admin {args:?} failed:\n{}", | | |
| 26 | - describe(&out) | | |
| 27 | - ); | | |
| 28 | -} | | |
| 29 | - | | |
| 30 | -async fn csrf_for(http: &Http, session: &str) -> String { | | |
| 31 | - let page = http.get("/settings/keys", Some(session)).await; | | |
| 32 | - assert_eq!(page.status, 200, "GET /settings/keys"); | | |
| 33 | - input_value(&page.body, "csrf") | | |
| 34 | -} | | |
| 35 | - | | |
| 36 | -async fn create_token(http: &Http, session: &str, name: &str) -> String { | | |
| 37 | - let csrf = csrf_for(http, session).await; | | |
| 38 | - let res = http | | |
| 39 | - .post_form( | | |
| 40 | - "/settings/tokens", | | |
| 41 | - &[("csrf", &csrf), ("name", name), ("expires", "30")], | | |
| 42 | - Some(session), | | |
| 43 | - ) | | |
| 44 | - .await; | | |
| 45 | - assert_eq!(res.status, 200, "create token: {}", res.body); | | |
| 46 | - let doc = scraper::Html::parse_document(&res.body); | | |
| 47 | - let selector = scraper::Selector::parse("pre.code code").expect("selector"); | | |
| 48 | - let token: String = doc | | |
| 49 | - .select(&selector) | | |
| 50 | - .next() | | |
| 51 | - .expect("token shown after creation") | | |
| 52 | - .text() | | |
| 53 | - .collect(); | | |
| 54 | - let token = token.trim().to_owned(); | | |
| 55 | - assert!(token.starts_with("forge_"), "unexpected token shape"); | | |
| 56 | - token | | |
| 57 | -} | | |
| 58 | - | | |
| 59 | -fn init_bare(data_dir: &Path, repo_id: &str) { | | |
| 60 | - let path = forge_git::repo::repo_path(data_dir, repo_id).expect("repo path"); | | |
| 61 | - fs::create_dir_all(path.parent().expect("parent")).expect("create repo parent"); | | |
| 62 | - let out = Command::new("git") | | |
| 63 | - .args(["init", "--bare", "--quiet", "--initial-branch=main"]) | | |
| 64 | - .arg(&path) | | |
| 65 | - .output() | | |
| 66 | - .expect("run git init"); | | |
| 67 | - assert!(out.status.success(), "git init --bare: {}", describe(&out)); | | |
| 68 | -} | | |
| 69 | - | | |
| 70 | -fn git(cwd: &Path, args: &[&str]) -> Output { | | |
| 71 | - Command::new("git") | | |
| 72 | - .current_dir(cwd) | | |
| 73 | - .args(["-c", "credential.helper="]) | | |
| 74 | - .args(args) | | |
| 75 | - .env("GIT_TERMINAL_PROMPT", "0") | | |
| 76 | - .output() | | |
| 77 | - .expect("run git") | | |
| 78 | -} | | |
| 79 | - | | |
| 80 | -fn ok(out: &Output, what: &str) { | | |
| 81 | - assert!(out.status.success(), "{what} failed:\n{}", describe(out)); | | |
| 82 | -} | | |
| 83 | - | | |
| 84 | -fn path_str(path: &Path) -> &str { | | |
| 85 | - path.to_str().expect("utf-8 path") | | |
| 86 | -} | | |
| 87 | - | | |
| 88 | -fn commit_file(repo: &Path, name: &str, content: &str, message: &str) { | | |
| 89 | - let file = repo.join(name); | | |
| 90 | - fs::create_dir_all(file.parent().expect("parent")).expect("create dir"); | | |
| 91 | - fs::write(&file, content).expect("write file"); | | |
| 92 | - ok(&git(repo, &["config", "user.name", "bob"]), "set user.name"); | | |
| 93 | - ok( | | |
| 94 | - &git(repo, &["config", "user.email", "bob@example.com"]), | | |
| 95 | - "set user.email", | | |
| 96 | - ); | | |
| 97 | - ok(&git(repo, &["add", name]), "git add"); | | |
| 98 | - ok( | | |
| 99 | - &git( | | |
| 100 | - repo, | | |
| 101 | - &["-c", "commit.gpgsign=false", "commit", "-q", "-m", message], | | |
| 102 | - ), | | |
| 103 | - "git commit", | | |
| 104 | - ); | | |
| 105 | -} | | |
| 106 | | 9 | |
| 107 | async fn get_ok(http: &Http, path: &str, session: Option<&str>) -> Resp { | 10 | async fn get_ok(http: &Http, path: &str, session: Option<&str>) -> Resp { |
| 108 | let res = http.get(path, session).await; | 11 | let res = http.get(path, session).await; |
| @@ -112,18 +15,18 @@ async fn get_ok(http: &Http, path: &str, session: Option<&str>) -> Resp { |
| 112 | | 15 | |
| 113 | #[tokio::test] | 16 | #[tokio::test] |
| 114 | async fn wiki_end_to_end() { | 17 | async fn wiki_end_to_end() { |
| 115 | - let root = tempfile::Builder::new() | 18 | + let root = crate::common::temp_dir("fwk"); |
| 116 | - .prefix("fwk") | | |
| 117 | - .tempdir_in("/tmp") | | |
| 118 | - .expect("temp dir"); | | |
| 119 | let dir = root.path().to_path_buf(); | 19 | let dir = root.path().to_path_buf(); |
| 120 | - let ports = pick_ports(); | 20 | + let (_, ports) = provision( |
| 121 | - let config = write_config(&dir, ports); | 21 | + &dir, |
| 122 | - | 22 | + "", |
| 123 | - admin(&config, &["create-user", "tahinli", "--admin"]); | 23 | + &[ |
| 124 | - for name in ["bob", "carol", "dave"] { | 24 | + &["create-user", "tahinli", "--admin"], |
| 125 | - admin(&config, &["create-user", name]); | 25 | + &["create-user", "bob"], |
| 126 | - } | 26 | + &["create-user", "carol"], |
| | 27 | + &["create-user", "dave"], |
| | 28 | + ], |
| | 29 | + ); |
| 127 | { | 30 | { |
| 128 | let store = Store::open(&dir.join("forge.db")) | 31 | let store = Store::open(&dir.join("forge.db")) |
| 129 | .await | 32 | .await |
| @@ -154,10 +57,7 @@ async fn wiki_end_to_end() { |
| 154 | let empty = get_ok(&http, "/bob/proj/wiki", Some(&bob)).await; | 57 | let empty = get_ok(&http, "/bob/proj/wiki", Some(&bob)).await; |
| 155 | assert!(empty.body.contains("no pages yet"), "{}", empty.body); | 58 | assert!(empty.body.contains("no pages yet"), "{}", empty.body); |
| 156 | | 59 | |
| 157 | - let csrf = input_value( | 60 | + let csrf = csrf_for(&http, "/bob/proj/wiki/-/new", &bob).await; |
| 158 | - &http.get("/bob/proj/wiki/-/new", Some(&bob)).await.body, | | |
| 159 | - "csrf", | | |
| 160 | - ); | | |
| 161 | let saved = http | 61 | let saved = http |
| 162 | .post_form( | 62 | .post_form( |
| 163 | "/bob/proj/wiki/-/new", | 63 | "/bob/proj/wiki/-/new", |
| @@ -224,13 +124,7 @@ async fn wiki_end_to_end() { |
| 224 | assert!(audit.body.contains("carol"), "the pusher is named"); | 124 | assert!(audit.body.contains("carol"), "the pusher is named"); |
| 225 | assert!(audit.body.contains("bob/proj"), "the repo is named"); | 125 | assert!(audit.body.contains("bob/proj"), "the repo is named"); |
| 226 | | 126 | |
| 227 | - let stale_csrf = input_value( | 127 | + let stale_csrf = csrf_for(&http, "/bob/proj/wiki/Home/edit", &carol).await; |
| 228 | - &http | | |
| 229 | - .get("/bob/proj/wiki/Home/edit", Some(&carol)) | | |
| 230 | - .await | | |
| 231 | - .body, | | |
| 232 | - "csrf", | | |
| 233 | - ); | | |
| 234 | let stale = http | 128 | let stale = http |
| 235 | .post_form( | 129 | .post_form( |
| 236 | "/bob/proj/wiki/Home/edit", | 130 | "/bob/proj/wiki/Home/edit", |
| @@ -284,7 +178,7 @@ async fn wiki_end_to_end() { |
| 284 | let off = http | 178 | let off = http |
| 285 | .post_form( | 179 | .post_form( |
| 286 | "/bob/proj/settings/wiki", | 180 | "/bob/proj/settings/wiki", |
| 287 | - &[("csrf", &input_value(&settings.body, "csrf"))], | 181 | + &[("csrf", &csrf_for(&http, "/bob/proj/settings", &bob).await)], |
| 288 | Some(&bob), | 182 | Some(&bob), |
| 289 | ) | 183 | ) |
| 290 | .await; | 184 | .await; |
| @@ -301,46 +195,19 @@ async fn wiki_end_to_end() { |
| 301 | drop(server); | 195 | drop(server); |
| 302 | } | 196 | } |
| 303 | | 197 | |
| 304 | -async fn open_wiki_stream(http: &Http, path: &str, cookie: Option<&str>) -> reqwest::Response { | | |
| 305 | - let mut req = http.client.get(format!("{}{path}", http.base)); | | |
| 306 | - if let Some(cookie) = cookie { | | |
| 307 | - req = req.header(COOKIE, cookie); | | |
| 308 | - } | | |
| 309 | - let mut res = req.send().await.expect("stream request"); | | |
| 310 | - assert_eq!(res.status().as_u16(), 200, "stream {path}"); | | |
| 311 | - let retry = tokio::time::timeout(Duration::from_secs(5), res.chunk()) | | |
| 312 | - .await | | |
| 313 | - .expect("the retry field") | | |
| 314 | - .expect("stream chunk") | | |
| 315 | - .expect("stream still open"); | | |
| 316 | - assert!(String::from_utf8_lossy(&retry).contains("retry: 1000")); | | |
| 317 | - res | | |
| 318 | -} | | |
| 319 | - | | |
| 320 | -async fn next_wiki_change(res: &mut reqwest::Response, what: &str) { | | |
| 321 | - let chunk = tokio::time::timeout(Duration::from_secs(5), res.chunk()) | | |
| 322 | - .await | | |
| 323 | - .unwrap_or_else(|_| panic!("no event after {what}")) | | |
| 324 | - .expect("stream chunk") | | |
| 325 | - .expect("stream still open"); | | |
| 326 | - let text = String::from_utf8_lossy(&chunk); | | |
| 327 | - assert!(text.contains("event: changed"), "{what}: {text}"); | | |
| 328 | -} | | |
| 329 | - | | |
| 330 | #[tokio::test] | 198 | #[tokio::test] |
| 331 | async fn wiki_streams_follow_saves_and_pushes() { | 199 | async fn wiki_streams_follow_saves_and_pushes() { |
| 332 | - let root = tempfile::Builder::new() | 200 | + let root = crate::common::temp_dir("fwl"); |
| 333 | - .prefix("fwl") | | |
| 334 | - .tempdir_in("/tmp") | | |
| 335 | - .expect("temp dir"); | | |
| 336 | let dir = root.path().to_path_buf(); | 201 | let dir = root.path().to_path_buf(); |
| 337 | - let ports = pick_ports(); | 202 | + let (_, ports) = provision( |
| 338 | - let config = write_config(&dir, ports); | 203 | + &dir, |
| 339 | - | 204 | + "", |
| 340 | - admin(&config, &["create-user", "tahinli", "--admin"]); | 205 | + &[ |
| 341 | - for name in ["bob", "dave"] { | 206 | + &["create-user", "tahinli", "--admin"], |
| 342 | - admin(&config, &["create-user", name]); | 207 | + &["create-user", "bob"], |
| 343 | - } | 208 | + &["create-user", "dave"], |
| | 209 | + ], |
| | 210 | + ); |
| 344 | { | 211 | { |
| 345 | let store = Store::open(&dir.join("forge.db")) | 212 | let store = Store::open(&dir.join("forge.db")) |
| 346 | .await | 213 | .await |
| @@ -371,11 +238,9 @@ async fn wiki_streams_follow_saves_and_pushes() { |
| 371 | "page list follows the wiki stream" | 238 | "page list follows the wiki stream" |
| 372 | ); | 239 | ); |
| 373 | | 240 | |
| 374 | - let mut wiki_events = open_wiki_stream(&http, "/bob/proj/wiki/-/events", Some(&bob)).await; | 241 | + let mut wiki_events = http.stream("/bob/proj/wiki/-/events", Some(&bob)).await; |
| 375 | - let csrf = input_value( | 242 | + assert_eq!(wiki_events.status().as_u16(), 200, "stream wiki events"); |
| 376 | - &http.get("/bob/proj/wiki/-/new", Some(&bob)).await.body, | 243 | + let csrf = csrf_for(&http, "/bob/proj/wiki/-/new", &bob).await; |
| 377 | - "csrf", | | |
| 378 | - ); | | |
| 379 | let created = http | 244 | let created = http |
| 380 | .post_form( | 245 | .post_form( |
| 381 | "/bob/proj/wiki/-/new", | 246 | "/bob/proj/wiki/-/new", |
| @@ -390,7 +255,7 @@ async fn wiki_streams_follow_saves_and_pushes() { |
| 390 | ) | 255 | ) |
| 391 | .await; | 256 | .await; |
| 392 | assert_eq!(created.status, 303, "create Home: {}", created.body); | 257 | assert_eq!(created.status, 303, "create Home: {}", created.body); |
| 393 | - next_wiki_change(&mut wiki_events, "a web save").await; | 258 | + next_changed(&mut wiki_events, "a web save").await; |
| 394 | | 259 | |
| 395 | let home = get_ok(&http, "/bob/proj/wiki/Home", Some(&bob)).await; | 260 | let home = get_ok(&http, "/bob/proj/wiki/Home", Some(&bob)).await; |
| 396 | assert!( | 261 | assert!( |
| @@ -398,7 +263,12 @@ async fn wiki_streams_follow_saves_and_pushes() { |
| 398 | .contains(r#"data-live="/bob/proj/wiki/Home/events""#), | 263 | .contains(r#"data-live="/bob/proj/wiki/Home/events""#), |
| 399 | "wiki page follows its stream" | 264 | "wiki page follows its stream" |
| 400 | ); | 265 | ); |
| 401 | - let mut home_events = open_wiki_stream(&http, "/bob/proj/wiki/Home/events", Some(&bob)).await; | 266 | + let mut home_events = http.stream("/bob/proj/wiki/Home/events", Some(&bob)).await; |
| | 267 | + assert_eq!( |
| | 268 | + home_events.status().as_u16(), |
| | 269 | + 200, |
| | 270 | + "stream wiki home events" |
| | 271 | + ); |
| 402 | let token = create_token(&http, &bob, "wiki-live").await; | 272 | let token = create_token(&http, &bob, "wiki-live").await; |
| 403 | let work = dir.join("wiki-live-work"); | 273 | let work = dir.join("wiki-live-work"); |
| 404 | let url = format!( | 274 | let url = format!( |
| @@ -414,7 +284,7 @@ async fn wiki_streams_follow_saves_and_pushes() { |
| 414 | &git(&work, &["push", "-q", "origin", "HEAD:main"]), | 284 | &git(&work, &["push", "-q", "origin", "HEAD:main"]), |
| 415 | "push to wiki", | 285 | "push to wiki", |
| 416 | ); | 286 | ); |
| 417 | - next_wiki_change(&mut home_events, "a push to the wiki").await; | 287 | + next_changed(&mut home_events, "a push to the wiki").await; |
| 418 | | 288 | |
| 419 | for path in ["/bob/vault/wiki/-/events", "/bob/vault/wiki/Home/events"] { | 289 | for path in ["/bob/vault/wiki/-/events", "/bob/vault/wiki/Home/events"] { |
| 420 | let res = http.get(path, Some(&dave)).await; | 290 | let res = http.get(path, Some(&dave)).await; |
| @@ -320,9 +320,10 @@ pub async fn new_commits( |
| 320 | repo: &Path, | 320 | repo: &Path, |
| 321 | old: Option<&str>, | 321 | old: Option<&str>, |
| 322 | new: &str, | 322 | new: &str, |
| | 323 | + skip: usize, |
| 323 | max: usize, | 324 | max: usize, |
| 324 | ) -> Result<Vec<CommitInfo>> { | 325 | ) -> Result<Vec<CommitInfo>> { |
| 325 | - new_commits_with(env, repo, ObjectSource::default(), old, new, max).await | 326 | + new_commits_with(env, repo, ObjectSource::default(), old, new, skip, max).await |
| 326 | } | 327 | } |
| 327 | | 328 | |
| 328 | pub async fn new_commits_with( | 329 | pub async fn new_commits_with( |
| @@ -331,6 +332,7 @@ pub async fn new_commits_with( |
| 331 | src: ObjectSource<'_>, | 332 | src: ObjectSource<'_>, |
| 332 | old: Option<&str>, | 333 | old: Option<&str>, |
| 333 | new: &str, | 334 | new: &str, |
| | 335 | + skip: usize, |
| 334 | max: usize, | 336 | max: usize, |
| 335 | ) -> Result<Vec<CommitInfo>> { | 337 | ) -> Result<Vec<CommitInfo>> { |
| 336 | validate_oid(new)?; | 338 | validate_oid(new)?; |
| @@ -350,6 +352,7 @@ pub async fn new_commits_with( |
| 350 | .arg("-z") | 352 | .arg("-z") |
| 351 | .arg("--no-color") | 353 | .arg("--no-color") |
| 352 | .arg(COMMIT_FORMAT) | 354 | .arg(COMMIT_FORMAT) |
| | 355 | + .user_opt("--skip", &skip.to_string())? |
| 353 | .user_opt("--max-count", &max.to_string())? | 356 | .user_opt("--max-count", &max.to_string())? |
| 354 | .objects(src)? | 357 | .objects(src)? |
| 355 | .user_revs(&revs)?; | 358 | .user_revs(&revs)?; |
| @@ -451,7 +451,7 @@ pub async fn range_log_with( |
| 451 | ) -> Result<Vec<CommitInfo>> { | 451 | ) -> Result<Vec<CommitInfo>> { |
| 452 | validate_oid(base_oid)?; | 452 | validate_oid(base_oid)?; |
| 453 | validate_oid(head_oid)?; | 453 | validate_oid(head_oid)?; |
| 454 | - new_commits_with(env, repo, src, Some(base_oid), head_oid, max).await | 454 | + new_commits_with(env, repo, src, Some(base_oid), head_oid, 0, max).await |
| 455 | } | 455 | } |
| 456 | | 456 | |
| 457 | #[derive(Debug, Clone, PartialEq, Eq)] | 457 | #[derive(Debug, Clone, PartialEq, Eq)] |
| @@ -1,6 +1,6 @@ |
| 1 | use std::path::{Path, PathBuf}; | 1 | use std::path::{Path, PathBuf}; |
| 2 | | 2 | |
| 3 | -use forge_core::time::unix_now; | 3 | +use forge_core::time::now_unix; |
| 4 | | 4 | |
| 5 | use crate::command::{GitCommand, GitEnv}; | 5 | use crate::command::{GitCommand, GitEnv}; |
| 6 | use crate::error::{Error, Result}; | 6 | use crate::error::{Error, Result}; |
| @@ -36,7 +36,7 @@ pub struct TrashEntry { |
| 36 | | 36 | |
| 37 | pub async fn move_to_trash(data_dir: &Path, repo_id: &str) -> Result<PathBuf> { | 37 | pub async fn move_to_trash(data_dir: &Path, repo_id: &str) -> Result<PathBuf> { |
| 38 | let src = repo_path(data_dir, repo_id)?; | 38 | let src = repo_path(data_dir, repo_id)?; |
| 39 | - let name = format!("{}-{}.git", repo_id.to_ascii_lowercase(), unix_now()); | 39 | + let name = format!("{}-{}.git", repo_id.to_ascii_lowercase(), now_unix()); |
| 40 | trash_dir(data_dir, &src, &name).await | 40 | trash_dir(data_dir, &src, &name).await |
| 41 | } | 41 | } |
| 42 | | 42 | |
| @@ -45,7 +45,7 @@ pub async fn move_wiki_to_trash(data_dir: &Path, repo_id: &str) -> Result<Option |
| 45 | if !tokio::fs::try_exists(&src).await? { | 45 | if !tokio::fs::try_exists(&src).await? { |
| 46 | return Ok(None); | 46 | return Ok(None); |
| 47 | } | 47 | } |
| 48 | - let name = format!("{}.wiki-{}.git", repo_id.to_ascii_lowercase(), unix_now()); | 48 | + let name = format!("{}.wiki-{}.git", repo_id.to_ascii_lowercase(), now_unix()); |
| 49 | trash_dir(data_dir, &src, &name).await.map(Some) | 49 | trash_dir(data_dir, &src, &name).await.map(Some) |
| 50 | } | 50 | } |
| 51 | | 51 | |
| @@ -13,6 +13,7 @@ test-host-executor = [] |
| 13 | [dependencies] | 13 | [dependencies] |
| 14 | clap = { workspace = true, features = ["string"] } | 14 | clap = { workspace = true, features = ["string"] } |
| 15 | forge-ci.workspace = true | 15 | forge-ci.workspace = true |
| | 16 | +rand = { workspace = true } |
| 16 | reqwest = { workspace = true, features = ["json"] } | 17 | reqwest = { workspace = true, features = ["json"] } |
| 17 | serde = { workspace = true } | 18 | serde = { workspace = true } |
| 18 | sha2 = { workspace = true } | 19 | sha2 = { workspace = true } |
| @@ -7,9 +7,9 @@ use tokio::io::AsyncWriteExt; |
| 7 | use tokio::process::Command; | 7 | use tokio::process::Command; |
| 8 | | 8 | |
| 9 | use crate::config::{Limits, UsernsMode}; | 9 | use crate::config::{Limits, UsernsMode}; |
| 10 | -use crate::sandbox::SandboxRequest; | | |
| 11 | use crate::sandbox::helper::job_cgroup_base; | 10 | use crate::sandbox::helper::job_cgroup_base; |
| 12 | use crate::sandbox::idmap::IdMap; | 11 | use crate::sandbox::idmap::IdMap; |
| | 12 | +use crate::sandbox::{SandboxRequest, new_token, strip_line}; |
| 13 | | 13 | |
| 14 | const PROBE_SCRIPT: &str = "grep '^Seccomp:' /proc/self/status; true"; | 14 | const PROBE_SCRIPT: &str = "grep '^Seccomp:' /proc/self/status; true"; |
| 15 | const PROBE_SUBUID_SCRIPT: &str = "grep '^Seccomp:' /proc/self/status; \ | 15 | const PROBE_SUBUID_SCRIPT: &str = "grep '^Seccomp:' /proc/self/status; \ |
| @@ -128,6 +128,7 @@ struct Probe { |
| 128 | status: ExitStatus, | 128 | status: ExitStatus, |
| 129 | stdout: String, | 129 | stdout: String, |
| 130 | stderr: String, | 130 | stderr: String, |
| | 131 | + token: String, |
| 131 | } | 132 | } |
| 132 | | 133 | |
| 133 | async fn run_probe(helper: &Path, work_dir: &Path, map: &IdMap) -> Result<Probe, String> { | 134 | async fn run_probe(helper: &Path, work_dir: &Path, map: &IdMap) -> Result<Probe, String> { |
| @@ -147,7 +148,9 @@ async fn run_probe(helper: &Path, work_dir: &Path, map: &IdMap) -> Result<Probe, |
| 147 | } else { | 148 | } else { |
| 148 | PROBE_SCRIPT | 149 | PROBE_SCRIPT |
| 149 | }; | 150 | }; |
| | 151 | + let token = new_token(); |
| 150 | let request = SandboxRequest { | 152 | let request = SandboxRequest { |
| | 153 | + token: token.clone(), |
| 151 | job_id: "forge-check".to_owned(), | 154 | job_id: "forge-check".to_owned(), |
| 152 | rootfs, | 155 | rootfs, |
| 153 | job_dir: root.join("job"), | 156 | job_dir: root.join("job"), |
| @@ -182,13 +185,14 @@ async fn run_probe(helper: &Path, work_dir: &Path, map: &IdMap) -> Result<Probe, |
| 182 | status: output.status, | 185 | status: output.status, |
| 183 | stdout: String::from_utf8_lossy(&output.stdout).into_owned(), | 186 | stdout: String::from_utf8_lossy(&output.stdout).into_owned(), |
| 184 | stderr: String::from_utf8_lossy(&output.stderr).into_owned(), | 187 | stderr: String::from_utf8_lossy(&output.stderr).into_owned(), |
| | 188 | + token, |
| 185 | }) | 189 | }) |
| 186 | } | 190 | } |
| 187 | | 191 | |
| 188 | -fn sandbox_lines(stderr: &str) -> Vec<&str> { | 192 | +fn sandbox_lines<'a>(stderr: &'a str, token: &str) -> Vec<&'a str> { |
| 189 | stderr | 193 | stderr |
| 190 | .lines() | 194 | .lines() |
| 191 | - .filter_map(|line| line.strip_prefix("forge-sandbox: ")) | 195 | + .filter_map(|line| strip_line(line, token)) |
| 192 | .collect() | 196 | .collect() |
| 193 | } | 197 | } |
| 194 | | 198 | |
| @@ -265,7 +269,7 @@ fn report(probe: Result<&Probe, &str>, controllers: Result<&[String], &str>) -> |
| 265 | } | 269 | } |
| 266 | }; | 270 | }; |
| 267 | | 271 | |
| 268 | - let setup_errors = sandbox_lines(&probe.stderr); | 272 | + let setup_errors = sandbox_lines(&probe.stderr, &probe.token); |
| 269 | let userns_error = setup_errors | 273 | let userns_error = setup_errors |
| 270 | .iter() | 274 | .iter() |
| 271 | .find(|l| l.contains("user namespaces unavailable")); | 275 | .find(|l| l.contains("user namespaces unavailable")); |
| @@ -367,7 +371,7 @@ fn ownership_line(probe: &Probe) -> Line { |
| 367 | let reason = probe | 371 | let reason = probe |
| 368 | .stderr | 372 | .stderr |
| 369 | .lines() | 373 | .lines() |
| 370 | - .find(|l| !l.starts_with("forge-sandbox: ") && !l.trim().is_empty()) | 374 | + .find(|l| strip_line(l, &probe.token).is_none() && !l.trim().is_empty()) |
| 371 | .unwrap_or("no output"); | 375 | .unwrap_or("no output"); |
| 372 | Line::fail( | 376 | Line::fail( |
| 373 | NAME, | 377 | NAME, |
| @@ -431,6 +435,7 @@ mod tests { |
| 431 | status: ExitStatus::from_raw(0), | 435 | status: ExitStatus::from_raw(0), |
| 432 | stdout: stdout.to_owned(), | 436 | stdout: stdout.to_owned(), |
| 433 | stderr: stderr.to_owned(), | 437 | stderr: stderr.to_owned(), |
| | 438 | + token: "t".to_owned(), |
| 434 | } | 439 | } |
| 435 | } | 440 | } |
| 436 | | 441 | |
| @@ -447,7 +452,7 @@ mod tests { |
| 447 | | 452 | |
| 448 | #[test] | 453 | #[test] |
| 449 | fn missing_userns_is_reported_with_its_reason() { | 454 | fn missing_userns_is_reported_with_its_reason() { |
| 450 | - let p = probe("", "forge-sandbox: user namespaces unavailable: EPERM\n"); | 455 | + let p = probe("", "forge-sandbox[t]: user namespaces unavailable: EPERM\n"); |
| 451 | let lines = report(Ok(&p), Ok(&all())); | 456 | let lines = report(Ok(&p), Ok(&all())); |
| 452 | let userns = lines | 457 | let userns = lines |
| 453 | .iter() | 458 | .iter() |
| @@ -466,8 +471,8 @@ mod tests { |
| 466 | fn overlay_and_limit_warnings_are_failures() { | 471 | fn overlay_and_limit_warnings_are_failures() { |
| 467 | let p = probe( | 472 | let p = probe( |
| 468 | "Seccomp:\t2\n", | 473 | "Seccomp:\t2\n", |
| 469 | - "forge-sandbox: warning: overlay mount failed (EPERM), copying the rootfs instead\n\ | 474 | + "forge-sandbox[t]: warning: overlay mount failed (EPERM), copying the rootfs instead\n\ |
| 470 | - forge-sandbox: warning: resource limits unavailable: cgroup\n", | 475 | + forge-sandbox[t]: warning: resource limits unavailable: cgroup\n", |
| 471 | ); | 476 | ); |
| 472 | let lines = report(Ok(&p), Ok(&all())); | 477 | let lines = report(Ok(&p), Ok(&all())); |
| 473 | let overlay = lines | 478 | let overlay = lines |
| @@ -139,7 +139,7 @@ fn hidden_dispatch(args: &[OsString]) -> i32 { |
| 139 | Some(b"__sandbox-map") => crate::sandbox::idmap::map_helper_main(&args[1..]), | 139 | Some(b"__sandbox-map") => crate::sandbox::idmap::map_helper_main(&args[1..]), |
| 140 | Some(b"__sandbox-unpack") => crate::oci::unpack_helper_main(), | 140 | Some(b"__sandbox-unpack") => crate::oci::unpack_helper_main(), |
| 141 | _ => { | 141 | _ => { |
| 142 | - eprintln!("forge-sandbox: unknown helper command"); | 142 | + crate::sandbox::report("unknown helper command"); |
| 143 | 125 | 143 | 125 |
| 144 | } | 144 | } |
| 145 | } | 145 | } |
| @@ -23,11 +23,9 @@ use crate::oci::{ImageError, ImageStore, PreparedImage, RegistryAuth}; |
| 23 | use crate::oom::{OomEvents, OomSink}; | 23 | use crate::oom::{OomEvents, OomSink}; |
| 24 | use crate::sandbox::helper::EXIT_SETUP_FAILED; | 24 | use crate::sandbox::helper::EXIT_SETUP_FAILED; |
| 25 | use crate::sandbox::idmap::{IdMap, remove_tree}; | 25 | use crate::sandbox::idmap::{IdMap, remove_tree}; |
| 26 | -use crate::sandbox::{SandboxRequest, job_cgroup_path}; | 26 | +use crate::sandbox::{SandboxRequest, job_cgroup_path, new_token, strip_line}; |
| 27 | use crate::workspace::validate_job_id; | 27 | use crate::workspace::validate_job_id; |
| 28 | | 28 | |
| 29 | -const SANDBOX_PREFIX: &[u8] = b"forge-sandbox: "; | | |
| 30 | - | | |
| 31 | const READER_GRACE: Duration = Duration::from_secs(10); | 29 | const READER_GRACE: Duration = Duration::from_secs(10); |
| 32 | const STOP_GRACE: Duration = Duration::from_secs(30); | 30 | const STOP_GRACE: Duration = Duration::from_secs(30); |
| 33 | | 31 | |
| @@ -318,20 +316,20 @@ struct Supervised { |
| 318 | async fn tap_sandbox_errors( | 316 | async fn tap_sandbox_errors( |
| 319 | mut lines: mpsc::Receiver<Vec<u8>>, | 317 | mut lines: mpsc::Receiver<Vec<u8>>, |
| 320 | logs: mpsc::Sender<Vec<u8>>, | 318 | logs: mpsc::Sender<Vec<u8>>, |
| | 319 | + token: String, |
| 321 | ) -> (Option<String>, Option<OomEvents>) { | 320 | ) -> (Option<String>, Option<OomEvents>) { |
| 322 | let mut found = None; | 321 | let mut found = None; |
| 323 | let mut oom = None; | 322 | let mut oom = None; |
| 324 | while let Some(chunk) = lines.recv().await { | 323 | while let Some(chunk) = lines.recv().await { |
| 325 | - if chunk.starts_with(SANDBOX_PREFIX) | 324 | + let text = String::from_utf8_lossy(&chunk).into_owned(); |
| 326 | - && let Some(events) = OomEvents::from_line(&String::from_utf8_lossy(&chunk)) | 325 | + if let Some(message) = strip_line(&text, &token) { |
| 327 | - { | 326 | + if let Some(events) = OomEvents::from_line(message) { |
| 328 | - oom = Some(events); | 327 | + oom = Some(events); |
| 329 | - continue; | 328 | + continue; |
| 330 | - } | 329 | + } |
| 331 | - let is_error = chunk.starts_with(SANDBOX_PREFIX) | 330 | + if !message.starts_with("warning:") { |
| 332 | - && !chunk[SANDBOX_PREFIX.len()..].starts_with(b"warning:"); | 331 | + found = Some(message.trim_end().to_owned()); |
| 333 | - if is_error { | 332 | + } |
| 334 | - found = Some(String::from_utf8_lossy(&chunk).trim_end().to_owned()); | | |
| 335 | } | 333 | } |
| 336 | if logs.send(chunk).await.is_err() { | 334 | if logs.send(chunk).await.is_err() { |
| 337 | break; | 335 | break; |
| @@ -346,6 +344,7 @@ async fn supervise( |
| 346 | cancel: CancellationToken, | 344 | cancel: CancellationToken, |
| 347 | stopper: Stopper, | 345 | stopper: Stopper, |
| 348 | cleanup: Option<JobCleanup>, | 346 | cleanup: Option<JobCleanup>, |
| | 347 | + token: String, |
| 349 | ) -> Supervised { | 348 | ) -> Supervised { |
| 350 | let mut readers: Vec<JoinHandle<()>> = Vec::new(); | 349 | let mut readers: Vec<JoinHandle<()>> = Vec::new(); |
| 351 | if let Some(out) = child.stdout.take() { | 350 | if let Some(out) = child.stdout.take() { |
| @@ -355,7 +354,7 @@ async fn supervise( |
| 355 | if let Some(err) = child.stderr.take() { | 354 | if let Some(err) = child.stderr.take() { |
| 356 | let (tx, rx) = mpsc::channel(64); | 355 | let (tx, rx) = mpsc::channel(64); |
| 357 | readers.push(tokio::spawn(forward_lines(err, tx))); | 356 | readers.push(tokio::spawn(forward_lines(err, tx))); |
| 358 | - tap = Some(tokio::spawn(tap_sandbox_errors(rx, logs.clone()))); | 357 | + tap = Some(tokio::spawn(tap_sandbox_errors(rx, logs.clone(), token))); |
| 359 | } | 358 | } |
| 360 | drop(logs); | 359 | drop(logs); |
| 361 | | 360 | |
| @@ -453,6 +452,7 @@ impl Executor for PodmanExecutor { |
| 453 | container: inv.container, | 452 | container: inv.container, |
| 454 | }, | 453 | }, |
| 455 | None, | 454 | None, |
| | 455 | + new_token(), |
| 456 | ) | 456 | ) |
| 457 | .await, | 457 | .await, |
| 458 | ) | 458 | ) |
| @@ -495,6 +495,7 @@ impl Executor for HostExecutor { |
| 495 | req.cancel, | 495 | req.cancel, |
| 496 | Stopper::ProcessGroup { pid }, | 496 | Stopper::ProcessGroup { pid }, |
| 497 | None, | 497 | None, |
| | 498 | + new_token(), |
| 498 | ) | 499 | ) |
| 499 | .await, | 500 | .await, |
| 500 | ) | 501 | ) |
| @@ -631,7 +632,9 @@ impl<I: ImageSource> BuiltinExecutor<I> { |
| 631 | } else { | 632 | } else { |
| 632 | None | 633 | None |
| 633 | }; | 634 | }; |
| | 635 | + let token = new_token(); |
| 634 | let request = SandboxRequest { | 636 | let request = SandboxRequest { |
| | 637 | + token: token.clone(), |
| 635 | job_id: job.job_id.clone(), | 638 | job_id: job.job_id.clone(), |
| 636 | rootfs: image.rootfs, | 639 | rootfs: image.rootfs, |
| 637 | job_dir, | 640 | job_dir, |
| @@ -704,6 +707,7 @@ impl<I: ImageSource> BuiltinExecutor<I> { |
| 704 | idmap: self.idmap.clone(), | 707 | idmap: self.idmap.clone(), |
| 705 | helper: self.helper.clone(), | 708 | helper: self.helper.clone(), |
| 706 | }), | 709 | }), |
| | 710 | + token, |
| 707 | ) | 711 | ) |
| 708 | .await; | 712 | .await; |
| 709 | if let Some(watcher) = watcher { | 713 | if let Some(watcher) = watcher { |
| @@ -734,8 +738,7 @@ impl<I: ImageSource> BuiltinExecutor<I> { |
| 734 | message: None, | 738 | message: None, |
| 735 | }, | 739 | }, |
| 736 | Some(EXIT_SETUP_FAILED) if sandbox_error.is_some() => { | 740 | Some(EXIT_SETUP_FAILED) if sandbox_error.is_some() => { |
| 737 | - let line = sandbox_error.unwrap_or_default(); | 741 | + let reason = sandbox_error.unwrap_or_default(); |
| 738 | - let reason = line.strip_prefix("forge-sandbox: ").unwrap_or(&line); | | |
| 739 | ExecResult { | 742 | ExecResult { |
| 740 | outcome: Outcome::Error, | 743 | outcome: Outcome::Error, |
| 741 | exit_code: Some(EXIT_SETUP_FAILED), | 744 | exit_code: Some(EXIT_SETUP_FAILED), |
| @@ -1,11 +1,7 @@ |
| 1 | use std::process::ExitCode; | 1 | use std::process::ExitCode; |
| 2 | | 2 | |
| 3 | fn main() -> ExitCode { | 3 | fn main() -> ExitCode { |
| 4 | - forge_ci::build::set_identity( | 4 | + forge_ci::build::set_identity(env!("FORGE_GIT_SHA"), env!("FORGE_GIT_DATE")); |
| 5 | - env!("FORGE_GIT_SHA"), | | |
| 6 | - env!("FORGE_GIT_DATE"), | | |
| 7 | - matches!(env!("FORGE_GIT_DIRTY").as_bytes(), b"1"), | | |
| 8 | - ); | | |
| 9 | if forge_runner::cli::is_sandbox_invocation() { | 5 | if forge_runner::cli::is_sandbox_invocation() { |
| 10 | std::process::exit(forge_runner::cli::hidden_main()); | 6 | std::process::exit(forge_runner::cli::hidden_main()); |
| 11 | } | 7 | } |
| @@ -46,7 +46,7 @@ pub fn unpack_helper_main() -> i32 { |
| 46 | match run_helper() { | 46 | match run_helper() { |
| 47 | Ok(()) => 0, | 47 | Ok(()) => 0, |
| 48 | Err(message) => { | 48 | Err(message) => { |
| 49 | - eprintln!("forge-sandbox: {message}"); | 49 | + crate::sandbox::report(message); |
| 50 | 125 | 50 | 125 |
| 51 | } | 51 | } |
| 52 | } | 52 | } |
| @@ -154,14 +154,11 @@ impl ImageStore { |
| 154 | let now = SystemTime::now(); | 154 | let now = SystemTime::now(); |
| 155 | let mut stats = GcStats::default(); | 155 | let mut stats = GcStats::default(); |
| 156 | let mut live_layers: HashSet<String> = HashSet::new(); | 156 | let mut live_layers: HashSet<String> = HashSet::new(); |
| | 157 | + let mut live_rootfs: HashSet<PathBuf> = HashSet::new(); |
| 157 | | 158 | |
| 158 | - for dir in ["rootfs", "blobs/sha256", "meta", "tags"] { | 159 | + for dir in ["blobs/sha256", "meta", "tags"] { |
| 159 | for path in entries(&self.root.join(dir))? { | 160 | for path in entries(&self.root.join(dir))? { |
| 160 | - let is_temp = path | 161 | + if is_stale_temp(&path, now) { |
| 161 | - .file_name() | | |
| 162 | - .and_then(|name| name.to_str()) | | |
| 163 | - .is_some_and(|name| TEMP_PREFIXES.iter().any(|p| name.starts_with(p))); | | |
| 164 | - if is_temp && modified(&path).is_some_and(|t| older_than(t, now, STALE_TEMP_AGE)) { | | |
| 165 | self.remove_entry(&path)?; | 162 | self.remove_entry(&path)?; |
| 166 | stats.temp_removed += 1; | 163 | stats.temp_removed += 1; |
| 167 | } | 164 | } |
| @@ -180,8 +177,20 @@ impl ImageStore { |
| 180 | remove_file_if_exists(&meta_file)?; | 177 | remove_file_if_exists(&meta_file)?; |
| 181 | remove_file_if_exists(&self.stamp_path(&hex))?; | 178 | remove_file_if_exists(&self.stamp_path(&hex))?; |
| 182 | stats.images_removed += 1; | 179 | stats.images_removed += 1; |
| 183 | - } else if let Ok(meta) = serde_json::from_slice::<ImageMeta>(&fs::read(&meta_file)?) { | 180 | + } else { |
| 184 | - live_layers.extend(meta.layers); | 181 | + live_rootfs.insert(self.rootfs_path(&hex)); |
| | 182 | + if let Ok(meta) = serde_json::from_slice::<ImageMeta>(&fs::read(&meta_file)?) { |
| | 183 | + live_layers.extend(meta.layers); |
| | 184 | + } |
| | 185 | + } |
| | 186 | + } |
| | 187 | + |
| | 188 | + for path in entries(&self.root.join("rootfs"))? { |
| | 189 | + if is_stale_temp(&path, now) || (!is_temp(&path) && !live_rootfs.contains(&path)) { |
| | 190 | + tracing::warn!( |
| | 191 | + "rootfs {} is not removed, delete it by hand", |
| | 192 | + path.display() |
| | 193 | + ); |
| 185 | } | 194 | } |
| 186 | } | 195 | } |
| 187 | | 196 | |
| @@ -250,6 +259,16 @@ fn entries(dir: &Path) -> io::Result<Vec<PathBuf>> { |
| 250 | } | 259 | } |
| 251 | } | 260 | } |
| 252 | | 261 | |
| | 262 | +fn is_temp(path: &Path) -> bool { |
| | 263 | + path.file_name() |
| | 264 | + .and_then(|name| name.to_str()) |
| | 265 | + .is_some_and(|name| TEMP_PREFIXES.iter().any(|p| name.starts_with(p))) |
| | 266 | +} |
| | 267 | + |
| | 268 | +fn is_stale_temp(path: &Path, now: SystemTime) -> bool { |
| | 269 | + is_temp(path) && modified(path).is_some_and(|t| older_than(t, now, STALE_TEMP_AGE)) |
| | 270 | +} |
| | 271 | + |
| 253 | fn file_stem(path: &Path) -> Option<String> { | 272 | fn file_stem(path: &Path) -> Option<String> { |
| 254 | path.file_stem() | 273 | path.file_stem() |
| 255 | .and_then(|name| name.to_str()) | 274 | .and_then(|name| name.to_str()) |
| @@ -433,9 +452,9 @@ mod tests { |
| 433 | set_age(&stale_meta_tmp, two_hours); | 452 | set_age(&stale_meta_tmp, two_hours); |
| 434 | | 453 | |
| 435 | let stats = store.gc(7).expect("gc"); | 454 | let stats = store.gc(7).expect("gc"); |
| 436 | - assert_eq!(stats.temp_removed, 3); | 455 | + assert_eq!(stats.temp_removed, 2); |
| 437 | assert_eq!(stats.blobs_removed, 0); | 456 | assert_eq!(stats.blobs_removed, 0); |
| 438 | - assert!(!stale_dir.exists()); | 457 | + assert!(stale_dir.is_dir()); |
| 439 | assert!(fresh_dir.is_dir()); | 458 | assert!(fresh_dir.is_dir()); |
| 440 | assert!(!stale_blob_tmp.exists()); | 459 | assert!(!stale_blob_tmp.exists()); |
| 441 | assert!(fresh_blob_tmp.is_file()); | 460 | assert!(fresh_blob_tmp.is_file()); |
| @@ -1,8 +1,6 @@ |
| 1 | use std::sync::Arc; | 1 | use std::sync::Arc; |
| 2 | use std::sync::atomic::{AtomicU32, Ordering}; | 2 | use std::sync::atomic::{AtomicU32, Ordering}; |
| 3 | | 3 | |
| 4 | -pub const LINE_PREFIX: &str = "forge-sandbox: oom-events "; | | |
| 5 | - | | |
| 6 | #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] | 4 | #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] |
| 7 | pub struct OomEvents { | 5 | pub struct OomEvents { |
| 8 | pub oom: u64, | 6 | pub oom: u64, |
| @@ -36,11 +34,11 @@ impl OomEvents { |
| 36 | } | 34 | } |
| 37 | | 35 | |
| 38 | pub fn to_line(&self) -> String { | 36 | pub fn to_line(&self) -> String { |
| 39 | - format!("{LINE_PREFIX}oom={} oom_kill={}", self.oom, self.oom_kill) | 37 | + format!("oom-events oom={} oom_kill={}", self.oom, self.oom_kill) |
| 40 | } | 38 | } |
| 41 | | 39 | |
| 42 | pub fn from_line(line: &str) -> Option<Self> { | 40 | pub fn from_line(line: &str) -> Option<Self> { |
| 43 | - let rest = line.trim_end().strip_prefix(LINE_PREFIX)?; | 41 | + let rest = line.trim_end().strip_prefix("oom-events ")?; |
| 44 | let mut events = Self::default(); | 42 | let mut events = Self::default(); |
| 45 | for pair in rest.split_whitespace() { | 43 | for pair in rest.split_whitespace() { |
| 46 | let (key, value) = pair.split_once('=')?; | 44 | let (key, value) = pair.split_once('=')?; |
| @@ -118,16 +116,10 @@ mod tests { |
| 118 | oom: 1, | 116 | oom: 1, |
| 119 | oom_kill: 2, | 117 | oom_kill: 2, |
| 120 | }; | 118 | }; |
| 121 | - assert_eq!( | 119 | + assert_eq!(events.to_line(), "oom-events oom=1 oom_kill=2"); |
| 122 | - events.to_line(), | | |
| 123 | - "forge-sandbox: oom-events oom=1 oom_kill=2" | | |
| 124 | - ); | | |
| 125 | assert_eq!(OomEvents::from_line(&events.to_line()), Some(events)); | 120 | assert_eq!(OomEvents::from_line(&events.to_line()), Some(events)); |
| 126 | - assert_eq!(OomEvents::from_line("forge-sandbox: setup failed"), None); | 121 | + assert_eq!(OomEvents::from_line("setup failed"), None); |
| 127 | - assert_eq!( | 122 | + assert_eq!(OomEvents::from_line("oom-events oom=x"), None); |
| 128 | - OomEvents::from_line("forge-sandbox: oom-events oom=x"), | | |
| 129 | - None | | |
| 130 | - ); | | |
| 131 | } | 123 | } |
| 132 | | 124 | |
| 133 | #[test] | 125 | #[test] |
| @@ -473,7 +473,10 @@ impl Runner { |
| 473 | }; | 473 | }; |
| 474 | } | 474 | } |
| 475 | | 475 | |
| 476 | - if self.restart.jobs_cancelled() && result.outcome == Outcome::Cancelled { | 476 | + if self.restart.jobs_cancelled() |
| | 477 | + && shutdown.is_cancelled() |
| | 478 | + && result.outcome == Outcome::Cancelled |
| | 479 | + { |
| 477 | result.message = Some("cancelled because an admin restarted the runner".to_owned()); | 480 | result.message = Some("cancelled because an admin restarted the runner".to_owned()); |
| 478 | } | 481 | } |
| 479 | | 482 | |
| @@ -25,7 +25,7 @@ use super::idmap::enter_mapped_userns; |
| 25 | use super::net; | 25 | use super::net; |
| 26 | use super::seccomp::build_filter; | 26 | use super::seccomp::build_filter; |
| 27 | use super::spec::{HOSTNAME, build_spec}; | 27 | use super::spec::{HOSTNAME, build_spec}; |
| 28 | -use super::{SandboxError, SandboxRequest}; | 28 | +use super::{SandboxError, SandboxRequest, bind_token, report}; |
| 29 | use crate::workspace::validate_job_id; | 29 | use crate::workspace::validate_job_id; |
| 30 | | 30 | |
| 31 | pub const EXIT_SETUP_FAILED: i32 = 125; | 31 | pub const EXIT_SETUP_FAILED: i32 = 125; |
| @@ -41,7 +41,7 @@ pub fn helper_main() -> i32 { |
| 41 | match run() { | 41 | match run() { |
| 42 | Ok(code) => code, | 42 | Ok(code) => code, |
| 43 | Err(e) => { | 43 | Err(e) => { |
| 44 | - eprintln!("forge-sandbox: {e}"); | 44 | + report(e); |
| 45 | EXIT_SETUP_FAILED | 45 | EXIT_SETUP_FAILED |
| 46 | } | 46 | } |
| 47 | } | 47 | } |
| @@ -77,6 +77,7 @@ impl Layout { |
| 77 | fn run() -> Result<i32, SandboxError> { | 77 | fn run() -> Result<i32, SandboxError> { |
| 78 | let req: SandboxRequest = serde_json::from_reader(io::stdin().lock()) | 78 | let req: SandboxRequest = serde_json::from_reader(io::stdin().lock()) |
| 79 | .map_err(|e| SandboxError::Invalid(format!("cannot read request: {e}")))?; | 79 | .map_err(|e| SandboxError::Invalid(format!("cannot read request: {e}")))?; |
| | 80 | + bind_token(&req.token); |
| 80 | validate_request(&req)?; | 81 | validate_request(&req)?; |
| 81 | let signals = install_signal_handlers()?; | 82 | let signals = install_signal_handlers()?; |
| 82 | | 83 | |
| @@ -523,7 +524,7 @@ fn report_oom(cgroup: Option<&Path>) { |
| 523 | }; | 524 | }; |
| 524 | let events = crate::oom::OomEvents::parse_memory_events(&text); | 525 | let events = crate::oom::OomEvents::parse_memory_events(&text); |
| 525 | if events.any() { | 526 | if events.any() { |
| 526 | - eprintln!("{}", events.to_line()); | 527 | + report(events.to_line()); |
| 527 | } | 528 | } |
| 528 | } | 529 | } |
| 529 | | 530 | |
| @@ -541,5 +542,5 @@ fn cleanup(layout: &Layout) { |
| 541 | } | 542 | } |
| 542 | | 543 | |
| 543 | fn warn(message: impl std::fmt::Display) { | 544 | fn warn(message: impl std::fmt::Display) { |
| 544 | - eprintln!("forge-sandbox: warning: {message}"); | 545 | + report(format!("warning: {message}")); |
| 545 | } | 546 | } |
| @@ -332,7 +332,7 @@ pub fn map_helper_main(args: &[OsString]) -> i32 { |
| 332 | match map_helper(args) { | 332 | match map_helper(args) { |
| 333 | Ok(()) => 0, | 333 | Ok(()) => 0, |
| 334 | Err(message) => { | 334 | Err(message) => { |
| 335 | - eprintln!("forge-sandbox: {message}"); | 335 | + super::report(message); |
| 336 | 125 | 336 | 125 |
| 337 | } | 337 | } |
| 338 | } | 338 | } |
| @@ -391,7 +391,7 @@ pub fn rm_helper_main(args: &[OsString]) -> i32 { |
| 391 | match rm_helper(args) { | 391 | match rm_helper(args) { |
| 392 | Ok(()) => 0, | 392 | Ok(()) => 0, |
| 393 | Err(message) => { | 393 | Err(message) => { |
| 394 | - eprintln!("forge-sandbox: {message}"); | 394 | + super::report(message); |
| 395 | 125 | 395 | 125 |
| 396 | } | 396 | } |
| 397 | } | 397 | } |
| @@ -5,7 +5,9 @@ pub mod net; |
| 5 | pub mod seccomp; | 5 | pub mod seccomp; |
| 6 | pub mod spec; | 6 | pub mod spec; |
| 7 | | 7 | |
| | 8 | +use std::fmt::Display; |
| 8 | use std::path::PathBuf; | 9 | use std::path::PathBuf; |
| | 10 | +use std::sync::OnceLock; |
| 9 | | 11 | |
| 10 | use serde::{Deserialize, Serialize}; | 12 | use serde::{Deserialize, Serialize}; |
| 11 | | 13 | |
| @@ -15,8 +17,30 @@ use idmap::IdMap; |
| 15 | pub use helper::{BOX_NAME, helper_main, job_cgroup_base, job_cgroup_path}; | 17 | pub use helper::{BOX_NAME, helper_main, job_cgroup_base, job_cgroup_path}; |
| 16 | pub use spec::build_spec; | 18 | pub use spec::build_spec; |
| 17 | | 19 | |
| | 20 | +static TOKEN: OnceLock<String> = OnceLock::new(); |
| | 21 | + |
| | 22 | +pub fn new_token() -> String { |
| | 23 | + let mut bytes = [0u8; 16]; |
| | 24 | + rand::fill(&mut bytes); |
| | 25 | + hex::encode(bytes) |
| | 26 | +} |
| | 27 | + |
| | 28 | +pub fn bind_token(token: &str) { |
| | 29 | + let _ = TOKEN.set(token.to_owned()); |
| | 30 | +} |
| | 31 | + |
| | 32 | +pub fn report(message: impl Display) { |
| | 33 | + let token = TOKEN.get().map_or("", String::as_str); |
| | 34 | + eprintln!("forge-sandbox[{token}]: {message}"); |
| | 35 | +} |
| | 36 | + |
| | 37 | +pub fn strip_line<'a>(text: &'a str, token: &str) -> Option<&'a str> { |
| | 38 | + text.strip_prefix(&format!("forge-sandbox[{token}]: ")) |
| | 39 | +} |
| | 40 | + |
| 18 | #[derive(Serialize, Deserialize)] | 41 | #[derive(Serialize, Deserialize)] |
| 19 | pub struct SandboxRequest { | 42 | pub struct SandboxRequest { |
| | 43 | + pub token: String, |
| 20 | pub job_id: String, | 44 | pub job_id: String, |
| 21 | pub rootfs: PathBuf, | 45 | pub rootfs: PathBuf, |
| 22 | pub job_dir: PathBuf, | 46 | pub job_dir: PathBuf, |
| @@ -148,7 +148,7 @@ pub fn net_helper_main(args: &[OsString]) -> i32 { |
| 148 | match net_helper(args) { | 148 | match net_helper(args) { |
| 149 | Ok(()) => 0, | 149 | Ok(()) => 0, |
| 150 | Err(message) => { | 150 | Err(message) => { |
| 151 | - eprintln!("forge-sandbox: {message}"); | 151 | + super::report(message); |
| 152 | 125 | 152 | 125 |
| 153 | } | 153 | } |
| 154 | } | 154 | } |
| @@ -390,6 +390,7 @@ mod tests { |
| 390 | | 390 | |
| 391 | fn request(network: bool) -> SandboxRequest { | 391 | fn request(network: bool) -> SandboxRequest { |
| 392 | SandboxRequest { | 392 | SandboxRequest { |
| | 393 | + token: String::new(), |
| 393 | job_id: "job_01".to_owned(), | 394 | job_id: "job_01".to_owned(), |
| 394 | rootfs: PathBuf::from("/var/lib/forge/rootfs"), | 395 | rootfs: PathBuf::from("/var/lib/forge/rootfs"), |
| 395 | job_dir: PathBuf::from("/var/lib/forge/jobs/job_01"), | 396 | job_dir: PathBuf::from("/var/lib/forge/jobs/job_01"), |
| @@ -8,8 +8,8 @@ use std::os::unix::fs::MetadataExt; |
| 8 | | 8 | |
| 9 | use forge_runner::check; | 9 | use forge_runner::check; |
| 10 | use forge_runner::config::Limits; | 10 | use forge_runner::config::Limits; |
| 11 | -use forge_runner::sandbox::SandboxRequest; | | |
| 12 | use forge_runner::sandbox::idmap::{IdMap, UsernsMode}; | 11 | use forge_runner::sandbox::idmap::{IdMap, UsernsMode}; |
| | 12 | +use forge_runner::sandbox::{SandboxRequest, new_token}; |
| 13 | | 13 | |
| 14 | use crate::common::can_run; | 14 | use crate::common::can_run; |
| 15 | | 15 | |
| @@ -25,6 +25,7 @@ fn request(dir: &Path, rootfs: &Path, run: &str, network: bool) -> SandboxReques |
| 25 | let workspace = dir.join("workspace"); | 25 | let workspace = dir.join("workspace"); |
| 26 | fs::create_dir_all(&workspace).expect("create workspace"); | 26 | fs::create_dir_all(&workspace).expect("create workspace"); |
| 27 | SandboxRequest { | 27 | SandboxRequest { |
| | 28 | + token: new_token(), |
| 28 | job_id: "job_01".to_owned(), | 29 | job_id: "job_01".to_owned(), |
| 29 | rootfs: rootfs.to_owned(), | 30 | rootfs: rootfs.to_owned(), |
| 30 | job_dir: dir.join("jobs/job_01"), | 31 | job_dir: dir.join("jobs/job_01"), |
| @@ -260,7 +261,7 @@ fn setup_failure_exits_125_with_a_reason() { |
| 260 | let out = run_helper(&req); | 261 | let out = run_helper(&req); |
| 261 | assert_eq!(out.status.code(), Some(125)); | 262 | assert_eq!(out.status.code(), Some(125)); |
| 262 | assert!( | 263 | assert!( |
| 263 | - stderr_of(&out).contains("forge-sandbox: "), | 264 | + stderr_of(&out).contains("forge-sandbox["), |
| 264 | "stderr: {}", | 265 | "stderr: {}", |
| 265 | stderr_of(&out) | 266 | stderr_of(&out) |
| 266 | ); | 267 | ); |
| @@ -21,14 +21,29 @@ pub struct RepoPath { |
| 21 | pub name: String, | 21 | pub name: String, |
| 22 | } | 22 | } |
| 23 | | 23 | |
| 24 | -pub(crate) fn parse_exec(cmd: &str) -> Result<(GitService, RepoPath), ParseError> { | 24 | +#[derive(Debug, Clone, PartialEq, Eq)] |
| | 25 | +pub(crate) enum ExecCommand { |
| | 26 | + Git(GitService, RepoPath), |
| | 27 | + LfsAuthenticate(RepoPath, LfsOperation), |
| | 28 | +} |
| | 29 | + |
| | 30 | +pub(crate) fn parse_command(cmd: &str) -> Result<ExecCommand, ParseError> { |
| | 31 | + if cmd.starts_with(LFS_AUTHENTICATE_PREFIX) { |
| | 32 | + let (path, operation) = parse_lfs_authenticate(cmd)?; |
| | 33 | + return Ok(ExecCommand::LfsAuthenticate(path, operation)); |
| | 34 | + } |
| | 35 | + let (service, path) = parse_exec(cmd)?; |
| | 36 | + Ok(ExecCommand::Git(service, path)) |
| | 37 | +} |
| | 38 | + |
| | 39 | +fn parse_exec(cmd: &str) -> Result<(GitService, RepoPath), ParseError> { |
| 25 | let (service, rest) = split_service(cmd)?; | 40 | let (service, rest) = split_service(cmd)?; |
| 26 | let raw = unquote_argument(rest)?; | 41 | let raw = unquote_argument(rest)?; |
| 27 | let path = normalize_path(raw)?; | 42 | let path = normalize_path(raw)?; |
| 28 | Ok((service, path)) | 43 | Ok((service, path)) |
| 29 | } | 44 | } |
| 30 | | 45 | |
| 31 | -pub(crate) const LFS_AUTHENTICATE_PREFIX: &str = "git-lfs-authenticate "; | 46 | +const LFS_AUTHENTICATE_PREFIX: &str = "git-lfs-authenticate "; |
| 32 | | 47 | |
| 33 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] | 48 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 34 | pub enum LfsOperation { | 49 | pub enum LfsOperation { |
| @@ -36,7 +51,7 @@ pub enum LfsOperation { |
| 36 | Upload, | 51 | Upload, |
| 37 | } | 52 | } |
| 38 | | 53 | |
| 39 | -pub(crate) fn parse_lfs_authenticate(cmd: &str) -> Result<(RepoPath, LfsOperation), ParseError> { | 54 | +fn parse_lfs_authenticate(cmd: &str) -> Result<(RepoPath, LfsOperation), ParseError> { |
| 40 | let rest = cmd | 55 | let rest = cmd |
| 41 | .strip_prefix(LFS_AUTHENTICATE_PREFIX) | 56 | .strip_prefix(LFS_AUTHENTICATE_PREFIX) |
| 42 | .ok_or(ParseError::UnsupportedCommand)?; | 57 | .ok_or(ParseError::UnsupportedCommand)?; |
| @@ -26,7 +26,7 @@ use tokio::sync::{Notify, Semaphore, mpsc}; |
| 26 | | 26 | |
| 27 | use crate::backend::GitBackend; | 27 | use crate::backend::GitBackend; |
| 28 | use crate::error::{Error, Result}; | 28 | use crate::error::{Error, Result}; |
| 29 | -use crate::parse::{LFS_AUTHENTICATE_PREFIX, parse_exec, parse_lfs_authenticate}; | 29 | +use crate::parse::{ExecCommand, LfsOperation, RepoPath, parse_command}; |
| 30 | | 30 | |
| 31 | const PUMP_CHUNK: usize = 32 * 1024; | 31 | const PUMP_CHUNK: usize = 32 * 1024; |
| 32 | const STDIN_QUEUE: usize = 8; | 32 | const STDIN_QUEUE: usize = 8; |
| @@ -179,13 +179,20 @@ fn load_or_create_host_key(path: &Path) -> Result<PrivateKey> { |
| 179 | if let Some(parent) = path.parent() { | 179 | if let Some(parent) = path.parent() { |
| 180 | std::fs::create_dir_all(parent)?; | 180 | std::fs::create_dir_all(parent)?; |
| 181 | } | 181 | } |
| 182 | - let mut file = OpenOptions::new() | 182 | + let tmp = path.with_extension(format!("{}.tmp", std::process::id())); |
| | 183 | + let _ = std::fs::remove_file(&tmp); |
| | 184 | + let written = OpenOptions::new() |
| 183 | .write(true) | 185 | .write(true) |
| 184 | .create_new(true) | 186 | .create_new(true) |
| 185 | .mode(0o600) | 187 | .mode(0o600) |
| 186 | - .open(path)?; | 188 | + .open(&tmp) |
| 187 | - file.write_all(pem.as_bytes())?; | 189 | + .and_then(|mut file| { |
| 188 | - file.sync_all()?; | 190 | + file.write_all(pem.as_bytes())?; |
| | 191 | + file.sync_all() |
| | 192 | + }); |
| | 193 | + let linked = written.and_then(|()| std::fs::hard_link(&tmp, path)); |
| | 194 | + let _ = std::fs::remove_file(&tmp); |
| | 195 | + linked?; |
| 189 | std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))?; | 196 | std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))?; |
| 190 | tracing::info!(path = %path.display(), "generated ssh host key"); | 197 | tracing::info!(path = %path.display(), "generated ssh host key"); |
| 191 | Ok(key) | 198 | Ok(key) |
| @@ -216,15 +223,12 @@ impl<B: GitBackend> Client<B> { |
| 216 | session: &mut Session, | 223 | session: &mut Session, |
| 217 | channel: ChannelId, | 224 | channel: ChannelId, |
| 218 | user_id: &str, | 225 | user_id: &str, |
| 219 | - command: &str, | 226 | + path: &RepoPath, |
| | 227 | + operation: LfsOperation, |
| 220 | ) -> std::result::Result<(), russh::Error> { | 228 | ) -> std::result::Result<(), russh::Error> { |
| 221 | - let (path, operation) = match parse_lfs_authenticate(command) { | | |
| 222 | - Ok(parsed) => parsed, | | |
| 223 | - Err(e) => return reject_exec(session, channel, &e.to_string()), | | |
| 224 | - }; | | |
| 225 | let reply = match self | 229 | let reply = match self |
| 226 | .backend | 230 | .backend |
| 227 | - .lfs_authenticate(user_id, &path, operation) | 231 | + .lfs_authenticate(user_id, path, operation) |
| 228 | .await | 232 | .await |
| 229 | { | 233 | { |
| 230 | Ok(reply) => reply, | 234 | Ok(reply) => reply, |
| @@ -317,13 +321,13 @@ impl<B: GitBackend> Handler for Client<B> { |
| 317 | Ok(command) => command, | 321 | Ok(command) => command, |
| 318 | Err(_) => return reject_exec(session, channel, "invalid command"), | 322 | Err(_) => return reject_exec(session, channel, "invalid command"), |
| 319 | }; | 323 | }; |
| 320 | - if command.starts_with(LFS_AUTHENTICATE_PREFIX) { | 324 | + let (service, path) = match parse_command(command) { |
| 321 | - return self | 325 | + Ok(ExecCommand::Git(service, path)) => (service, path), |
| 322 | - .exec_lfs_authenticate(session, channel, &user_id, command) | 326 | + Ok(ExecCommand::LfsAuthenticate(path, operation)) => { |
| 323 | - .await; | 327 | + return self |
| 324 | - } | 328 | + .exec_lfs_authenticate(session, channel, &user_id, &path, operation) |
| 325 | - let (service, path) = match parse_exec(command) { | 329 | + .await; |
| 326 | - Ok(parsed) => parsed, | 330 | + } |
| 327 | Err(e) => return reject_exec(session, channel, &e.to_string()), | 331 | Err(e) => return reject_exec(session, channel, &e.to_string()), |
| 328 | }; | 332 | }; |
| 329 | | 333 | |
| @@ -8,6 +8,6 @@ pub(crate) use forge_web_app::{ |
| 8 | web_push, webhooks, | 8 | web_push, webhooks, |
| 9 | }; | 9 | }; |
| 10 | #[cfg(test)] | 10 | #[cfg(test)] |
| 11 | -pub(crate) use forge_web_app::{blobs, ci, notify_hub, packages_live, release_ops, replication}; | 11 | +pub(crate) use forge_web_app::{blobs, release_ops, replication}; |
| 12 | | 12 | |
| 13 | pub mod pages; | 13 | pub mod pages; |
| @@ -1,5 +1,5 @@ |
| 1 | use forge_core::Store; | 1 | use forge_core::Store; |
| 2 | -use forge_core::config::BannerConfig; | 2 | +use forge_core::config::{BannerConfig, BannerLevel}; |
| 3 | use topcoat::router::request::Request; | 3 | use topcoat::router::request::Request; |
| 4 | use topcoat::router::{Body, Router, to_bytes}; | 4 | use topcoat::router::{Body, Router, to_bytes}; |
| 5 | | 5 | |
| @@ -271,7 +271,7 @@ async fn banner_shows_on_pages_and_a_dismissal_hides_it() { |
| 271 | let dir = tempfile::tempdir().unwrap(); | 271 | let dir = tempfile::tempdir().unwrap(); |
| 272 | let banner = BannerConfig { | 272 | let banner = BannerConfig { |
| 273 | message: "Maintenance tonight".into(), | 273 | message: "Maintenance tonight".into(), |
| 274 | - level: "warning".into(), | 274 | + level: BannerLevel::Warning, |
| 275 | expires: String::new(), | 275 | expires: String::new(), |
| 276 | }; | 276 | }; |
| 277 | let fx = fixture(dir.path(), Some(banner)).await; | 277 | let fx = fixture(dir.path(), Some(banner)).await; |
| @@ -281,7 +281,7 @@ async fn banner_shows_on_pages_and_a_dismissal_hides_it() { |
| 281 | assert!(body.contains("site-banner warning"), "{body}"); | 281 | assert!(body.contains("site-banner warning"), "{body}"); |
| 282 | assert!(body.contains("Maintenance tonight")); | 282 | assert!(body.contains("Maintenance tonight")); |
| 283 | } | 283 | } |
| 284 | - let hash = crate::views::banner_hash("Maintenance tonight", "warning"); | 284 | + let hash = crate::views::banner_hash("Maintenance tonight", BannerLevel::Warning); |
| 285 | let req = Request::builder() | 285 | let req = Request::builder() |
| 286 | .method("GET") | 286 | .method("GET") |
| 287 | .uri("/explore") | 287 | .uri("/explore") |
| @@ -315,7 +315,7 @@ async fn expired_banner_is_not_shown() { |
| 315 | let dir = tempfile::tempdir().unwrap(); | 315 | let dir = tempfile::tempdir().unwrap(); |
| 316 | let banner = BannerConfig { | 316 | let banner = BannerConfig { |
| 317 | message: "Old news".into(), | 317 | message: "Old news".into(), |
| 318 | - level: "info".into(), | 318 | + level: BannerLevel::Info, |
| 319 | expires: "2020-01-01 00:00".into(), | 319 | expires: "2020-01-01 00:00".into(), |
| 320 | }; | 320 | }; |
| 321 | let fx = fixture(dir.path(), Some(banner)).await; | 321 | let fx = fixture(dir.path(), Some(banner)).await; |
| @@ -29,7 +29,7 @@ use crate::views::{alert, enc, human_size, rel_time, shell, stamp_unix}; |
| 29 | const RUN_LIMIT: u32 = 20; | 29 | const RUN_LIMIT: u32 = 20; |
| 30 | | 30 | |
| 31 | #[query_params(error = bad_request)] | 31 | #[query_params(error = bad_request)] |
| 32 | -pub(crate) struct NoticeQuery { | 32 | +struct NoticeQuery { |
| 33 | notice: Option<String>, | 33 | notice: Option<String>, |
| 34 | } | 34 | } |
| 35 | | 35 | |
| @@ -4,7 +4,9 @@ use std::time::Duration; |
| 4 | | 4 | |
| 5 | use forge_core::mail::MailState; | 5 | use forge_core::mail::MailState; |
| 6 | use forge_core::store::backup_runs::RunKind; | 6 | use forge_core::store::backup_runs::RunKind; |
| 7 | -use forge_core::store::replication::DB_SUBJECT; | 7 | +use forge_core::store::replication::{ |
| | 8 | + DB_SUBJECT, ReplicationHealth, replication_health, window_secs, |
| | 9 | +}; |
| 8 | use forge_core::time::stamp_to_unix; | 10 | use forge_core::time::stamp_to_unix; |
| 9 | use tokio::process::Command; | 11 | use tokio::process::Command; |
| 10 | use topcoat::Result; | 12 | use topcoat::Result; |
| @@ -21,6 +23,7 @@ use crate::i18n::{self, Lang}; |
| 21 | use crate::live::{Topic, stream_changes}; | 23 | use crate::live::{Topic, stream_changes}; |
| 22 | use crate::pages::admin_users::admin_only; | 24 | use crate::pages::admin_users::admin_only; |
| 23 | use crate::state::AppState; | 25 | use crate::state::AppState; |
| | 26 | +use crate::views::paging::{paginate, requested_page}; |
| 24 | use crate::views::parts::{SubPart, head}; | 27 | use crate::views::parts::{SubPart, head}; |
| 25 | use crate::views::repo_list::{PageLink, pager, pager_links}; | 28 | use crate::views::repo_list::{PageLink, pager, pager_links}; |
| 26 | use crate::views::{human_size, now_unix, rel_time, shell}; | 29 | use crate::views::{human_size, now_unix, rel_time, shell}; |
| @@ -342,15 +345,13 @@ async fn gather(state: &AppState, lang: Lang) -> Result<Health> { |
| 342 | match state.store.replication_status(DB_SUBJECT).await? { | 345 | match state.store.replication_status(DB_SUBJECT).await? { |
| 343 | Some(status) => { | 346 | Some(status) => { |
| 344 | let ok_unix = status.last_ok_at.as_deref().and_then(stamp_to_unix); | 347 | let ok_unix = status.last_ok_at.as_deref().and_then(stamp_to_unix); |
| 345 | - let window = live.replication.db_snapshot_minutes.saturating_mul(120); | 348 | + let window = window_secs(live.replication.db_snapshot_minutes); |
| 346 | - let lagging = ok_unix.is_none_or(|t| (now - t).max(0) as u64 > window); | 349 | + let (value, dot) = match replication_health(Some(&status), now, window) { |
| 347 | - let errored = status.last_error.is_some(); | 350 | + ReplicationHealth::Error => (at(lang, A::Error), Dot::Bad), |
| 348 | - let (value, dot) = if errored { | 351 | + ReplicationHealth::Lagging | ReplicationHealth::Never => { |
| 349 | - (at(lang, A::Error), Dot::Bad) | 352 | + (at(lang, A::Lagging), Dot::Bad) |
| 350 | - } else if lagging { | 353 | + } |
| 351 | - (at(lang, A::Lagging), Dot::Bad) | 354 | + ReplicationHealth::Ok => (at(lang, A::Ok), Dot::Ok), |
| 352 | - } else { | | |
| 353 | - (at(lang, A::Ok), Dot::Ok) | | |
| 354 | }; | 355 | }; |
| 355 | Service { | 356 | Service { |
| 356 | label: at(lang, A::Replication), | 357 | label: at(lang, A::Replication), |
| @@ -382,15 +383,7 @@ async fn gather(state: &AppState, lang: Lang) -> Result<Health> { |
| 382 | || at(lang, A::Unavailable).to_owned(), | 383 | || at(lang, A::Unavailable).to_owned(), |
| 383 | |secs| duration_short_in(lang, secs), | 384 | |secs| duration_short_in(lang, secs), |
| 384 | ); | 385 | ); |
| 385 | - let build = format!( | 386 | + let build = forge_ci::build::commit(); |
| 386 | - "{}{}", | | |
| 387 | - forge_ci::build::commit(), | | |
| 388 | - if forge_ci::build::dirty() { | | |
| 389 | - "-dirty" | | |
| 390 | - } else { | | |
| 391 | - "" | | |
| 392 | - } | | |
| 393 | - ); | | |
| 394 | let meta = meta_line( | 387 | let meta = meta_line( |
| 395 | lang, | 388 | lang, |
| 396 | &uptime, | 389 | &uptime, |
| @@ -424,8 +417,8 @@ async fn alert_rows(state: &AppState, lang: Lang) -> Result<Vec<AlertRow>> { |
| 424 | .await? | 417 | .await? |
| 425 | .into_iter() | 418 | .into_iter() |
| 426 | .map(|alert| AlertRow { | 419 | .map(|alert| AlertRow { |
| 427 | - title: alert_text::title(lang, &alert.kind, &alert.subject, false), | 420 | + title: alert_text::title(lang, alert.kind, &alert.subject, false), |
| 428 | - body: alert_text::body(lang, &alert.kind, &alert.subject, &alert.detail, false), | 421 | + body: alert_text::body(lang, alert.kind, &alert.subject, &alert.detail, false), |
| 429 | stamp: alert.raised_at.clone(), | 422 | stamp: alert.raised_at.clone(), |
| 430 | }) | 423 | }) |
| 431 | .collect()) | 424 | .collect()) |
| @@ -549,26 +542,17 @@ async fn health_page(cx: &Cx) -> Result<impl View> { |
| 549 | let health = gather(state, lang).await?; | 542 | let health = gather(state, lang).await?; |
| 550 | let all = alert_rows(state, lang).await?; | 543 | let all = alert_rows(state, lang).await?; |
| 551 | let total = all.len(); | 544 | let total = all.len(); |
| 552 | - let pages = total.div_ceil(ALERTS_PER_PAGE).max(1); | 545 | + let (alerts, page, pages) = paginate( |
| 553 | - let page = query | 546 | + all, |
| 554 | - .page | 547 | + requested_page(query.page.as_deref()), |
| 555 | - .as_deref() | 548 | + ALERTS_PER_PAGE as u64, |
| 556 | - .and_then(|p| p.parse::<usize>().ok()) | 549 | + ); |
| 557 | - .unwrap_or(1) | 550 | + let nav = pager_links(page, pages, |n| format!("/admin/health?page={n}")); |
| 558 | - .clamp(1, pages); | | |
| 559 | - let alerts: Vec<AlertRow> = all | | |
| 560 | - .into_iter() | | |
| 561 | - .skip((page - 1) * ALERTS_PER_PAGE) | | |
| 562 | - .take(ALERTS_PER_PAGE) | | |
| 563 | - .collect(); | | |
| 564 | - let nav = pager_links(page as u64, pages as u64, |n| { | | |
| 565 | - format!("/admin/health?page={n}") | | |
| 566 | - }); | | |
| 567 | let title = at(lang, A::Health); | 551 | let title = at(lang, A::Health); |
| 568 | Ok(view! { | 552 | Ok(view! { |
| 569 | shell(title: title, viewer: Some(&viewer), | 553 | shell(title: title, viewer: Some(&viewer), |
| 570 | health_view(lang: lang, health: health, alerts: alerts, total: total, | 554 | health_view(lang: lang, health: health, alerts: alerts, total: total, |
| 571 | - page: page as u64, pages: pages as u64, nav: nav)) | 555 | + page: page, pages: pages, nav: nav)) |
| 572 | }) | 556 | }) |
| 573 | } | 557 | } |
| 574 | | 558 | |
| @@ -1,11 +1,9 @@ |
| 1 | use std::fmt::Debug; | 1 | use std::fmt::Debug; |
| 2 | -use std::time::Duration; | | |
| 3 | | 2 | |
| 4 | -use bytes::Bytes; | | |
| 5 | use forge_core::AuditAction; | 3 | use forge_core::AuditAction; |
| 6 | use forge_core::store::backup_runs::RunKind; | 4 | use forge_core::store::backup_runs::RunKind; |
| 7 | use forge_core::store::replication::DB_SUBJECT; | 5 | use forge_core::store::replication::DB_SUBJECT; |
| 8 | -use futures_util::{Stream, StreamExt}; | 6 | +use futures_util::Stream; |
| 9 | use serde_json::Value; | 7 | use serde_json::Value; |
| 10 | use topcoat::router::request::Request; | 8 | use topcoat::router::request::Request; |
| 11 | use topcoat::router::{Body, Router}; | 9 | use topcoat::router::{Body, Router}; |
| @@ -14,6 +12,7 @@ use crate::audit::{self, Actor, Target}; |
| 14 | use crate::auth::SESSION_COOKIE; | 12 | use crate::auth::SESSION_COOKIE; |
| 15 | use crate::live::{Topic, admin}; | 13 | use crate::live::{Topic, admin}; |
| 16 | use crate::state::AppState; | 14 | use crate::state::AppState; |
| | 15 | +use crate::test_support::fixture::{next_event as next_event_or_end, next_frame}; |
| 17 | use crate::test_support::{app_router, create_session, test_state}; | 16 | use crate::test_support::{app_router, create_session, test_state}; |
| 18 | | 17 | |
| 19 | const ADMIN_TOKEN: &str = "admin-live-admin-session"; | 18 | const ADMIN_TOKEN: &str = "admin-live-admin-session"; |
| @@ -76,28 +75,14 @@ async fn open(app: &Router, uri: &str, token: Option<&str>) -> topcoat::router:: |
| 76 | .await | 75 | .await |
| 77 | } | 76 | } |
| 78 | | 77 | |
| 79 | -async fn next_frame<S, E>(frames: &mut S) -> Option<Vec<u8>> | | |
| 80 | -where | | |
| 81 | - S: Stream<Item = Result<Bytes, E>> + Unpin, | | |
| 82 | - E: Debug, | | |
| 83 | -{ | | |
| 84 | - let frame = tokio::time::timeout(Duration::from_secs(5), frames.next()) | | |
| 85 | - .await | | |
| 86 | - .expect("a frame within five seconds")?; | | |
| 87 | - Some(frame.expect("data").to_vec()) | | |
| 88 | -} | | |
| 89 | - | | |
| 90 | async fn next_event<S, E>(frames: &mut S) -> Vec<u8> | 78 | async fn next_event<S, E>(frames: &mut S) -> Vec<u8> |
| 91 | where | 79 | where |
| 92 | - S: Stream<Item = Result<Bytes, E>> + Unpin, | 80 | + S: Stream<Item = Result<bytes::Bytes, E>> + Unpin, |
| 93 | E: Debug, | 81 | E: Debug, |
| 94 | { | 82 | { |
| 95 | - loop { | 83 | + next_event_or_end(frames) |
| 96 | - let bytes = next_frame(frames).await.expect("an event before the end"); | 84 | + .await |
| 97 | - if !bytes.starts_with(b"retry: ") { | 85 | + .expect("an event before the end") |
| 98 | - return bytes; | | |
| 99 | - } | | |
| 100 | - } | | |
| 101 | } | 86 | } |
| 102 | | 87 | |
| 103 | fn changed(data: &str) -> Vec<u8> { | 88 | fn changed(data: &str) -> Vec<u8> { |
| @@ -253,7 +238,7 @@ async fn backups_replication_health_and_server_send_for_their_changes() { |
| 253 | | 238 | |
| 254 | crate::alerts::raise( | 239 | crate::alerts::raise( |
| 255 | &fx.state, | 240 | &fx.state, |
| 256 | - crate::alerts::AlertTopic::RunnerOffline, | 241 | + forge_core::alerts::AlertTopic::RunnerOffline, |
| 257 | "runner-offline:tahinli-ci", | 242 | "runner-offline:tahinli-ci", |
| 258 | "tahinli-ci", | 243 | "tahinli-ci", |
| 259 | "silent for an hour", | 244 | "silent for an hour", |
| @@ -32,7 +32,7 @@ use crate::views::{enc, rel_time, shell}; |
| 32 | const LIST_LIMIT: u32 = 100; | 32 | const LIST_LIMIT: u32 = 100; |
| 33 | | 33 | |
| 34 | #[query_params(error = bad_request)] | 34 | #[query_params(error = bad_request)] |
| 35 | -pub(crate) struct NoticeQuery { | 35 | +struct NoticeQuery { |
| 36 | notice: Option<String>, | 36 | notice: Option<String>, |
| 37 | tab: Option<String>, | 37 | tab: Option<String>, |
| 38 | state: Option<String>, | 38 | state: Option<String>, |
| @@ -317,7 +317,10 @@ async fn mail_page(cx: &Cx) -> Result<impl View> { |
| 317 | } else { | 317 | } else { |
| 318 | Tab::Settings | 318 | Tab::Settings |
| 319 | }; | 319 | }; |
| 320 | - let filter = query.state.as_deref().and_then(MailState::parse); | 320 | + let filter = query |
| | 321 | + .state |
| | 322 | + .as_deref() |
| | 323 | + .and_then(|state| state.parse::<MailState>().ok()); |
| 321 | let data = page_data(state, lang, tab, filter).await?; | 324 | let data = page_data(state, lang, tab, filter).await?; |
| 322 | let csrf = viewer.1.csrf_token.clone(); | 325 | let csrf = viewer.1.csrf_token.clone(); |
| 323 | let title = g::t(lang, K::Mail); | 326 | let title = g::t(lang, K::Mail); |
| @@ -401,8 +404,11 @@ async fn save_settings( |
| 401 | .trim() | 404 | .trim() |
| 402 | .parse() | 405 | .parse() |
| 403 | .map_err(|_| Error::Invalid(g::t(lang, K::ErrPortRange).to_owned()))?; | 406 | .map_err(|_| Error::Invalid(g::t(lang, K::ErrPortRange).to_owned()))?; |
| 404 | - let security = Security::parse(form.security.trim()) | 407 | + let security = form |
| 405 | - .ok_or_else(|| Error::Invalid(g::t(lang, K::ErrChooseSecurity).to_owned()))?; | 408 | + .security |
| | 409 | + .trim() |
| | 410 | + .parse::<Security>() |
| | 411 | + .map_err(|_| Error::Invalid(g::t(lang, K::ErrChooseSecurity).to_owned()))?; |
| 406 | let password = (!form.password.is_empty()).then_some(form.password.as_str()); | 412 | let password = (!form.password.is_empty()).then_some(form.password.as_str()); |
| 407 | let update = MailSettingsUpdate { | 413 | let update = MailSettingsUpdate { |
| 408 | host: form.host.trim(), | 414 | host: form.host.trim(), |
| @@ -555,7 +561,10 @@ async fn queue_action(cx: &Cx, form: QueueForm, action: QueueAction) -> Result<R |
| 555 | if done { | 561 | if done { |
| 556 | live::bump(); | 562 | live::bump(); |
| 557 | } | 563 | } |
| 558 | - let filter = MailState::parse(&form.state) | 564 | + let filter = form |
| | 565 | + .state |
| | 566 | + .parse::<MailState>() |
| | 567 | + .ok() |
| 559 | .map_or_else(String::new, |s| format!("&state={}", s.as_str())); | 568 | .map_or_else(String::new, |s| format!("&state={}", s.as_str())); |
| 560 | let location = format!( | 569 | let location = format!( |
| 561 | "/admin/mail?tab=queue{filter}¬ice={}", | 570 | "/admin/mail?tab=queue{filter}¬ice={}", |
| @@ -1,9 +1,10 @@ |
| 1 | use std::collections::HashMap; | 1 | use std::collections::HashMap; |
| 2 | -use std::time::Duration; | | |
| 3 | | 2 | |
| 4 | use forge_core::server_settings::Group; | 3 | use forge_core::server_settings::Group; |
| 5 | -use forge_core::store::replication::{DB_SUBJECT, ReplicationStatus}; | 4 | +use forge_core::store::replication::{ |
| 6 | -use forge_core::time::stamp_ago; | 5 | + DB_SUBJECT, ReplicationHealth, ReplicationStatus, replication_health, window_secs, |
| | 6 | +}; |
| | 7 | +use forge_core::time::now_unix; |
| 7 | use forge_core::{AuditAction, Error}; | 8 | use forge_core::{AuditAction, Error}; |
| 8 | use serde::Deserialize; | 9 | use serde::Deserialize; |
| 9 | use topcoat::Result; | 10 | use topcoat::Result; |
| @@ -29,12 +30,13 @@ use crate::pages::admin_users::admin_only; |
| 29 | use crate::pages::issues_list::list_href; | 30 | use crate::pages::issues_list::list_href; |
| 30 | use crate::state::AppState; | 31 | use crate::state::AppState; |
| 31 | use crate::views::find::{Finder, finder_field}; | 32 | use crate::views::find::{Finder, finder_field}; |
| | 33 | +use crate::views::paging::{paginate, requested_page}; |
| 32 | use crate::views::parts::{head, post_act}; | 34 | use crate::views::parts::{head, post_act}; |
| 33 | use crate::views::repo_list::{PageLink, pager, pager_links}; | 35 | use crate::views::repo_list::{PageLink, pager, pager_links}; |
| 34 | use crate::views::{alert, enc, rel_time_or_never, shell}; | 36 | use crate::views::{alert, enc, rel_time_or_never, shell}; |
| 35 | | 37 | |
| 36 | #[query_params(error = bad_request)] | 38 | #[query_params(error = bad_request)] |
| 37 | -pub(crate) struct NoticeQuery { | 39 | +struct NoticeQuery { |
| 38 | notice: Option<String>, | 40 | notice: Option<String>, |
| 39 | q: Option<String>, | 41 | q: Option<String>, |
| 40 | exact: Option<String>, | 42 | exact: Option<String>, |
| @@ -45,80 +47,63 @@ pub(crate) struct NoticeQuery { |
| 45 | | 47 | |
| 46 | const REPO_ROWS: usize = 10; | 48 | const REPO_ROWS: usize = 10; |
| 47 | | 49 | |
| 48 | -const HEALTH_MENU: [Health; 4] = [Health::Error, Health::Lagging, Health::Never, Health::Ok]; | 50 | +const HEALTH_MENU: [ReplicationHealth; 4] = [ |
| 49 | - | 51 | + ReplicationHealth::Error, |
| 50 | -#[derive(Debug, Clone, Copy, PartialEq, Eq)] | 52 | + ReplicationHealth::Lagging, |
| 51 | -enum Health { | 53 | + ReplicationHealth::Never, |
| 52 | - Ok, | 54 | + ReplicationHealth::Ok, |
| 53 | - Lagging, | 55 | +]; |
| 54 | - Error, | 56 | + |
| 55 | - Never, | 57 | +fn health_dot(health: ReplicationHealth) -> &'static str { |
| 56 | -} | 58 | + match health { |
| 57 | - | 59 | + ReplicationHealth::Ok => "health-dot ok", |
| 58 | -impl Health { | 60 | + ReplicationHealth::Lagging => "health-dot warn", |
| 59 | - fn dot(self) -> &'static str { | 61 | + ReplicationHealth::Error => "health-dot bad", |
| 60 | - match self { | 62 | + ReplicationHealth::Never => "health-dot", |
| 61 | - Health::Ok => "health-dot ok", | | |
| 62 | - Health::Lagging => "health-dot warn", | | |
| 63 | - Health::Error => "health-dot bad", | | |
| 64 | - Health::Never => "health-dot", | | |
| 65 | - } | | |
| 66 | - } | | |
| 67 | - | | |
| 68 | - fn tone(self) -> &'static str { | | |
| 69 | - match self { | | |
| 70 | - Health::Ok | Health::Never => "", | | |
| 71 | - Health::Lagging => "warn", | | |
| 72 | - Health::Error => "bad", | | |
| 73 | - } | | |
| 74 | } | 63 | } |
| | 64 | +} |
| 75 | | 65 | |
| 76 | - fn key(self) -> &'static str { | 66 | +fn health_tone(health: ReplicationHealth) -> &'static str { |
| 77 | - match self { | 67 | + match health { |
| 78 | - Health::Ok => "ok", | 68 | + ReplicationHealth::Ok | ReplicationHealth::Never => "", |
| 79 | - Health::Lagging => "lagging", | 69 | + ReplicationHealth::Lagging => "warn", |
| 80 | - Health::Error => "error", | 70 | + ReplicationHealth::Error => "bad", |
| 81 | - Health::Never => "never", | | |
| 82 | - } | | |
| 83 | } | 71 | } |
| | 72 | +} |
| 84 | | 73 | |
| 85 | - fn from_key(key: &str) -> Option<Health> { | 74 | +fn health_slug(health: ReplicationHealth) -> &'static str { |
| 86 | - HEALTH_MENU.into_iter().find(|h| h.key() == key) | 75 | + match health { |
| | 76 | + ReplicationHealth::Ok => "ok", |
| | 77 | + ReplicationHealth::Lagging => "lagging", |
| | 78 | + ReplicationHealth::Error => "error", |
| | 79 | + ReplicationHealth::Never => "never", |
| 87 | } | 80 | } |
| | 81 | +} |
| 88 | | 82 | |
| 89 | - fn label(self, lang: Lang) -> &'static str { | 83 | +fn health_from_slug(slug: &str) -> Option<ReplicationHealth> { |
| 90 | - match self { | 84 | + HEALTH_MENU.into_iter().find(|h| health_slug(*h) == slug) |
| 91 | - Health::Ok => g::t(lang, K::HealthOk), | | |
| 92 | - Health::Lagging => g::t(lang, K::HealthLagging), | | |
| 93 | - Health::Error => g::t(lang, K::HealthError), | | |
| 94 | - Health::Never => g::t(lang, K::HealthNever), | | |
| 95 | - } | | |
| 96 | - } | | |
| 97 | } | 85 | } |
| 98 | | 86 | |
| 99 | -fn health(status: Option<&ReplicationStatus>, cutoff: &str) -> Health { | 87 | +fn health_text(health: ReplicationHealth, lang: Lang) -> &'static str { |
| 100 | - match status { | 88 | + match health { |
| 101 | - None => Health::Never, | 89 | + ReplicationHealth::Ok => g::t(lang, K::HealthOk), |
| 102 | - Some(s) if s.last_error.is_some() => Health::Error, | 90 | + ReplicationHealth::Lagging => g::t(lang, K::HealthLagging), |
| 103 | - Some(s) => match s.last_ok_at.as_deref() { | 91 | + ReplicationHealth::Error => g::t(lang, K::HealthError), |
| 104 | - None => Health::Never, | 92 | + ReplicationHealth::Never => g::t(lang, K::HealthNever), |
| 105 | - Some(ok) if ok >= cutoff => Health::Ok, | | |
| 106 | - Some(_) => Health::Lagging, | | |
| 107 | - }, | | |
| 108 | } | 93 | } |
| 109 | } | 94 | } |
| 110 | | 95 | |
| 111 | struct RepoRow { | 96 | struct RepoRow { |
| 112 | name: String, | 97 | name: String, |
| 113 | - kind: Health, | 98 | + kind: ReplicationHealth, |
| 114 | last_ok: Option<String>, | 99 | last_ok: Option<String>, |
| 115 | error: String, | 100 | error: String, |
| 116 | } | 101 | } |
| 117 | | 102 | |
| 118 | -fn repo_row(name: String, status: Option<&ReplicationStatus>, cutoff: &str) -> RepoRow { | 103 | +fn repo_row(name: String, status: Option<&ReplicationStatus>, now: i64, window: i64) -> RepoRow { |
| 119 | RepoRow { | 104 | RepoRow { |
| 120 | name, | 105 | name, |
| 121 | - kind: health(status, cutoff), | 106 | + kind: replication_health(status, now, window), |
| 122 | last_ok: status.and_then(|s| s.last_ok_at.clone()), | 107 | last_ok: status.and_then(|s| s.last_ok_at.clone()), |
| 123 | error: status | 108 | error: status |
| 124 | .and_then(|s| s.last_error.clone()) | 109 | .and_then(|s| s.last_error.clone()) |
| @@ -138,8 +123,9 @@ struct PageData { |
| 138 | | 123 | |
| 139 | async fn page_data(state: &AppState, lang: Lang) -> forge_core::Result<PageData> { | 124 | async fn page_data(state: &AppState, lang: Lang) -> forge_core::Result<PageData> { |
| 140 | let config = &state.config.replication; | 125 | let config = &state.config.replication; |
| 141 | - let db_cutoff = stamp_ago(Duration::from_secs(config.db_snapshot_minutes * 60 * 2)); | 126 | + let now = now_unix(); |
| 142 | - let repo_cutoff = stamp_ago(Duration::from_secs(config.reconcile_minutes * 60 * 2)); | 127 | + let db_window = window_secs(config.db_snapshot_minutes); |
| | 128 | + let repo_window = window_secs(config.reconcile_minutes); |
| 143 | | 129 | |
| 144 | let statuses: HashMap<String, ReplicationStatus> = state | 130 | let statuses: HashMap<String, ReplicationStatus> = state |
| 145 | .store | 131 | .store |
| @@ -158,20 +144,20 @@ async fn page_data(state: &AppState, lang: Lang) -> forge_core::Result<PageData> |
| 158 | Some(repo) => format!("{}/{}", repo.owner_name, repo.name), | 144 | Some(repo) => format!("{}/{}", repo.owner_name, repo.name), |
| 159 | None => id.clone(), | 145 | None => id.clone(), |
| 160 | }; | 146 | }; |
| 161 | - repos.push(repo_row(name, status, &repo_cutoff)); | 147 | + repos.push(repo_row(name, status, now, repo_window)); |
| 162 | } | 148 | } |
| 163 | for status in statuses.values() { | 149 | for status in statuses.values() { |
| 164 | if status.subject != DB_SUBJECT && !ids.contains(&status.subject) { | 150 | if status.subject != DB_SUBJECT && !ids.contains(&status.subject) { |
| 165 | let name = g::deleted_repo_name(lang, &status.subject); | 151 | let name = g::deleted_repo_name(lang, &status.subject); |
| 166 | - repos.push(repo_row(name, Some(status), &repo_cutoff)); | 152 | + repos.push(repo_row(name, Some(status), now, repo_window)); |
| 167 | } | 153 | } |
| 168 | } | 154 | } |
| 169 | | 155 | |
| 170 | - let db_health = health(db, &db_cutoff); | 156 | + let db_health = replication_health(db, now, db_window); |
| 171 | Ok(PageData { | 157 | Ok(PageData { |
| 172 | enabled: config.enabled(), | 158 | enabled: config.enabled(), |
| 173 | - db_dot: db_health.dot(), | 159 | + db_dot: health_dot(db_health), |
| 174 | - db_health: db_health.label(lang), | 160 | + db_health: health_text(db_health, lang), |
| 175 | db_last_ok: db.and_then(|s| s.last_ok_at.clone()), | 161 | db_last_ok: db.and_then(|s| s.last_ok_at.clone()), |
| 176 | db_last_attempt: db.and_then(|s| s.last_attempt_at.clone()), | 162 | db_last_attempt: db.and_then(|s| s.last_attempt_at.clone()), |
| 177 | db_error: db.and_then(|s| s.last_error.clone()).unwrap_or_default(), | 163 | db_error: db.and_then(|s| s.last_error.clone()).unwrap_or_default(), |
| @@ -259,7 +245,7 @@ async fn replication_view( |
| 259 | <select name="health" data-autosubmit="true"> | 245 | <select name="health" data-autosubmit="true"> |
| 260 | <option value="" selected=(health.is_none())>(all_label)</option> | 246 | <option value="" selected=(health.is_none())>(all_label)</option> |
| 261 | for h in HEALTH_MENU { | 247 | for h in HEALTH_MENU { |
| 262 | - <option value=(h.key()) selected=(health == Some(h))>(h.label(lang))</option> | 248 | + <option value=(health_slug(h)) selected=(health == Some(h))>(health_text(h, lang))</option> |
| 263 | } | 249 | } |
| 264 | </select> | 250 | </select> |
| 265 | </label> | 251 | </label> |
| @@ -270,7 +256,7 @@ async fn replication_view( |
| 270 | for row in rows.into_iter() { | 256 | for row in rows.into_iter() { |
| 271 | <div class="line" data-kb-row=""> | 257 | <div class="line" data-kb-row=""> |
| 272 | <span class="name">(row.name.as_str())</span> | 258 | <span class="name">(row.name.as_str())</span> |
| 273 | - <span class="val"><span class=(row.kind.dot()) aria-hidden="true"></span> <span class=(row.kind.tone())>(row.kind.label(lang))</span> " · " (g::t(lang, K::LastSuccess)) ": " rel_time_or_never(lang: lang, stamp: row.last_ok.as_deref())</span> | 259 | + <span class="val"><span class=(health_dot(row.kind)) aria-hidden="true"></span> <span class=(health_tone(row.kind))>(health_text(row.kind, lang))</span> " · " (g::t(lang, K::LastSuccess)) ": " rel_time_or_never(lang: lang, stamp: row.last_ok.as_deref())</span> |
| 274 | </div> | 260 | </div> |
| 275 | if !row.error.is_empty() { | 261 | if !row.error.is_empty() { |
| 276 | alert(message: row.error.as_str()) | 262 | alert(message: row.error.as_str()) |
| @@ -292,7 +278,7 @@ async fn page_fingerprint(state: &AppState) -> Result<String> { |
| 292 | .map(|row| { | 278 | .map(|row| { |
| 293 | ( | 279 | ( |
| 294 | &row.name, | 280 | &row.name, |
| 295 | - row.kind.label(Lang::En), | 281 | + health_text(row.kind, Lang::En), |
| 296 | &row.last_ok, | 282 | &row.last_ok, |
| 297 | &row.error, | 283 | &row.error, |
| 298 | ) | 284 | ) |
| @@ -323,7 +309,7 @@ async fn replication_events(cx: &Cx) -> Result<Response> { |
| 323 | struct RepoList { | 309 | struct RepoList { |
| 324 | has_repos: bool, | 310 | has_repos: bool, |
| 325 | finder: Finder, | 311 | finder: Finder, |
| 326 | - health: Option<Health>, | 312 | + health: Option<ReplicationHealth>, |
| 327 | rows: Vec<RepoRow>, | 313 | rows: Vec<RepoRow>, |
| 328 | page: u64, | 314 | page: u64, |
| 329 | pages: u64, | 315 | pages: u64, |
| @@ -336,26 +322,19 @@ fn repo_list(repos: Vec<RepoRow>, query: &NoticeQuery) -> RepoList { |
| 336 | query.exact.as_deref(), | 322 | query.exact.as_deref(), |
| 337 | query.case.as_deref(), | 323 | query.case.as_deref(), |
| 338 | ); | 324 | ); |
| 339 | - let health = query.health.as_deref().and_then(Health::from_key); | 325 | + let health = query.health.as_deref().and_then(health_from_slug); |
| 340 | let has_repos = !repos.is_empty(); | 326 | let has_repos = !repos.is_empty(); |
| 341 | let matching: Vec<RepoRow> = repos | 327 | let matching: Vec<RepoRow> = repos |
| 342 | .into_iter() | 328 | .into_iter() |
| 343 | .filter(|row| health.is_none_or(|h| row.kind == h)) | 329 | .filter(|row| health.is_none_or(|h| row.kind == h)) |
| 344 | .filter(|row| finder.matches_any(&[row.name.as_str(), row.error.as_str()])) | 330 | .filter(|row| finder.matches_any(&[row.name.as_str(), row.error.as_str()])) |
| 345 | .collect(); | 331 | .collect(); |
| 346 | - let pages = (matching.len() as u64).div_ceil(REPO_ROWS as u64).max(1); | 332 | + let (rows, page, pages) = paginate( |
| 347 | - let page = query | 333 | + matching, |
| 348 | - .page | 334 | + requested_page(query.page.as_deref()), |
| 349 | - .as_deref() | 335 | + REPO_ROWS as u64, |
| 350 | - .and_then(|p| p.parse::<u64>().ok()) | 336 | + ); |
| 351 | - .unwrap_or(1) | 337 | + let health_key = health.map_or("", health_slug); |
| 352 | - .clamp(1, pages); | | |
| 353 | - let rows = matching | | |
| 354 | - .into_iter() | | |
| 355 | - .skip((page - 1) as usize * REPO_ROWS) | | |
| 356 | - .take(REPO_ROWS) | | |
| 357 | - .collect(); | | |
| 358 | - let health_key = health.map_or("", Health::key); | | |
| 359 | let nav = pager_links(page, pages, |n| { | 338 | let nav = pager_links(page, pages, |n| { |
| 360 | let number = n.to_string(); | 339 | let number = n.to_string(); |
| 361 | let mut params = finder.params(); | 340 | let mut params = finder.params(); |
| @@ -678,28 +657,4 @@ mod tests { |
| 678 | .any(|e| e.action == AuditAction::ReplicationReconcileStarted) | 657 | .any(|e| e.action == AuditAction::ReplicationReconcileStarted) |
| 679 | ); | 658 | ); |
| 680 | } | 659 | } |
| 681 | - | | |
| 682 | - #[test] | | |
| 683 | - fn health_reads_errors_before_age() { | | |
| 684 | - let cutoff = "2026-01-01T00:00:00.000000000Z"; | | |
| 685 | - let fresh = ReplicationStatus { | | |
| 686 | - subject: "r".into(), | | |
| 687 | - last_ok_at: Some("2026-06-01T00:00:00.000000000Z".into()), | | |
| 688 | - last_error: None, | | |
| 689 | - last_attempt_at: None, | | |
| 690 | - refs_sha256: None, | | |
| 691 | - }; | | |
| 692 | - assert_eq!(health(Some(&fresh), cutoff), Health::Ok); | | |
| 693 | - let old = ReplicationStatus { | | |
| 694 | - last_ok_at: Some("2025-06-01T00:00:00.000000000Z".into()), | | |
| 695 | - ..fresh.clone() | | |
| 696 | - }; | | |
| 697 | - assert_eq!(health(Some(&old), cutoff), Health::Lagging); | | |
| 698 | - let failing = ReplicationStatus { | | |
| 699 | - last_error: Some("boom".into()), | | |
| 700 | - ..fresh.clone() | | |
| 701 | - }; | | |
| 702 | - assert_eq!(health(Some(&failing), cutoff), Health::Error); | | |
| 703 | - assert_eq!(health(None, cutoff), Health::Never); | | |
| 704 | - } | | |
| 705 | } | 660 | } |
| @@ -66,10 +66,10 @@ async fn custom_css_route(cx: &Cx) -> Result<(StatusCode, HeaderMap, String)> { |
| 66 | if let Some(query) = uri(cx).query() { | 66 | if let Some(query) = uri(cx).query() { |
| 67 | for (key, value) in form_urlencoded::parse(query.as_bytes()) { | 67 | for (key, value) in form_urlencoded::parse(query.as_bytes()) { |
| 68 | let (slot, default_vivid) = match key.as_ref() { | 68 | let (slot, default_vivid) = match key.as_ref() { |
| 69 | - "al" => (0, 50), | 69 | + "al" => (0, accent::ACCENT_VIVID), |
| 70 | - "ad" => (1, 50), | 70 | + "ad" => (1, accent::ACCENT_VIVID), |
| 71 | - "bl" => (2, 30), | 71 | + "bl" => (2, accent::BASE_VIVID), |
| 72 | - "bd" => (3, 30), | 72 | + "bd" => (3, accent::BASE_VIVID), |
| 73 | _ => continue, | 73 | _ => continue, |
| 74 | }; | 74 | }; |
| 75 | if let Some((hue, vivid)) = accent::custom_of(&value, default_vivid) { | 75 | if let Some((hue, vivid)) = accent::custom_of(&value, default_vivid) { |
| @@ -15,6 +15,7 @@ use crate::pages::issues_list::list_href; |
| 15 | use crate::pages::settings_security::security_rail_for; | 15 | use crate::pages::settings_security::security_rail_for; |
| 16 | use crate::state::AppState; | 16 | use crate::state::AppState; |
| 17 | use crate::views::find::{Finder, finder_field}; | 17 | use crate::views::find::{Finder, finder_field}; |
| | 18 | +use crate::views::paging::{paginate, requested_page}; |
| 18 | use crate::views::parts::{RailItem, head, rail}; | 19 | use crate::views::parts::{RailItem, head, rail}; |
| 19 | use crate::views::repo_list::{PageLink, pager, pager_links}; | 20 | use crate::views::repo_list::{PageLink, pager, pager_links}; |
| 20 | use crate::views::{rel_time, shell}; | 21 | use crate::views::{rel_time, shell}; |
| @@ -302,23 +303,6 @@ fn fold_groups(entries: &[AuditEntry], lang: Lang, finder: &Finder) -> Vec<Group |
| 302 | groups | 303 | groups |
| 303 | } | 304 | } |
| 304 | | 305 | |
| 305 | -fn requested_page(query: &AuditQuery) -> u64 { | | |
| 306 | - query | | |
| 307 | - .page | | |
| 308 | - .as_deref() | | |
| 309 | - .and_then(|p| p.parse::<u64>().ok()) | | |
| 310 | - .unwrap_or(1) | | |
| 311 | - .max(1) | | |
| 312 | -} | | |
| 313 | - | | |
| 314 | -fn page_of(groups: Vec<Group>, page: u64) -> (Vec<Group>, u64, u64) { | | |
| 315 | - let pages = (groups.len() as u64).div_ceil(PAGE_ROWS as u64).max(1); | | |
| 316 | - let page = page.clamp(1, pages); | | |
| 317 | - let start = (page - 1) as usize * PAGE_ROWS; | | |
| 318 | - let shown: Vec<Group> = groups.into_iter().skip(start).take(PAGE_ROWS).collect(); | | |
| 319 | - (shown, page, pages) | | |
| 320 | -} | | |
| 321 | - | | |
| 322 | fn nav_for( | 306 | fn nav_for( |
| 323 | page: u64, | 307 | page: u64, |
| 324 | pages: u64, | 308 | pages: u64, |
| @@ -615,9 +599,9 @@ async fn admin_audit_page(cx: &Cx) -> Result<impl View> { |
| 615 | span.apply(&mut filter, &viewer.0.timezone); | 599 | span.apply(&mut filter, &viewer.0.timezone); |
| 616 | let mut notice: Option<String> = None; | 600 | let mut notice: Option<String> = None; |
| 617 | if !action.is_empty() { | 601 | if !action.is_empty() { |
| 618 | - match AuditAction::parse(&action) { | 602 | + match action.parse::<AuditAction>() { |
| 619 | - Some(known) => filter.action = Some(known), | 603 | + Ok(known) => filter.action = Some(known), |
| 620 | - None => notice = Some(g::no_action_named(lang, &action)), | 604 | + Err(_) => notice = Some(g::no_action_named(lang, &action)), |
| 621 | } | 605 | } |
| 622 | } | 606 | } |
| 623 | if !actor.is_empty() { | 607 | if !actor.is_empty() { |
| @@ -633,7 +617,11 @@ async fn admin_audit_page(cx: &Cx) -> Result<impl View> { |
| 633 | }; | 617 | }; |
| 634 | let groups = fold_groups(&entries, lang, &finder); | 618 | let groups = fold_groups(&entries, lang, &finder); |
| 635 | let total = groups.iter().map(|group| group.rows.len()).sum(); | 619 | let total = groups.iter().map(|group| group.rows.len()).sum(); |
| 636 | - let (groups, page, pages) = page_of(groups, requested_page(query)); | 620 | + let (groups, page, pages) = paginate( |
| | 621 | + groups, |
| | 622 | + requested_page(query.page.as_deref()), |
| | 623 | + PAGE_ROWS as u64, |
| | 624 | + ); |
| 637 | let mut params = keep_params(&finder, &action, &actor); | 625 | let mut params = keep_params(&finder, &action, &actor); |
| 638 | params.extend(span.params()); | 626 | params.extend(span.params()); |
| 639 | let nav = nav_for(page, pages, "/admin/audit", ¶ms); | 627 | let nav = nav_for(page, pages, "/admin/audit", ¶ms); |
| @@ -650,9 +638,9 @@ async fn admin_audit_page(cx: &Cx) -> Result<impl View> { |
| 650 | async fn first_page_fingerprint(store: &Store, action: &str, actor: &str) -> Result<String> { | 638 | async fn first_page_fingerprint(store: &Store, action: &str, actor: &str) -> Result<String> { |
| 651 | let mut filter = AuditFilter::default(); | 639 | let mut filter = AuditFilter::default(); |
| 652 | if !action.is_empty() { | 640 | if !action.is_empty() { |
| 653 | - match AuditAction::parse(action) { | 641 | + match action.parse::<AuditAction>() { |
| 654 | - Some(known) => filter.action = Some(known), | 642 | + Ok(known) => filter.action = Some(known), |
| 655 | - None => return Ok(String::new()), | 643 | + Err(_) => return Ok(String::new()), |
| 656 | } | 644 | } |
| 657 | } | 645 | } |
| 658 | if !actor.is_empty() { | 646 | if !actor.is_empty() { |
| @@ -698,13 +686,17 @@ async fn own_log_page(cx: &Cx) -> Result<impl View> { |
| 698 | ..Default::default() | 686 | ..Default::default() |
| 699 | }; | 687 | }; |
| 700 | span.apply(&mut filter, &viewer.0.timezone); | 688 | span.apply(&mut filter, &viewer.0.timezone); |
| 701 | - if let Some(known) = AuditAction::parse(&action) { | 689 | + if let Ok(known) = action.parse::<AuditAction>() { |
| 702 | filter.action = Some(known); | 690 | filter.action = Some(known); |
| 703 | } | 691 | } |
| 704 | let entries = store.list_audit_page(&filter, 0, SEARCH_CAP).await?; | 692 | let entries = store.list_audit_page(&filter, 0, SEARCH_CAP).await?; |
| 705 | let groups = fold_groups(&entries, lang, &finder); | 693 | let groups = fold_groups(&entries, lang, &finder); |
| 706 | let total = groups.iter().map(|group| group.rows.len()).sum(); | 694 | let total = groups.iter().map(|group| group.rows.len()).sum(); |
| 707 | - let (groups, page, pages) = page_of(groups, requested_page(query)); | 695 | + let (groups, page, pages) = paginate( |
| | 696 | + groups, |
| | 697 | + requested_page(query.page.as_deref()), |
| | 698 | + PAGE_ROWS as u64, |
| | 699 | + ); |
| 708 | let mut params = keep_params(&finder, &action, ""); | 700 | let mut params = keep_params(&finder, &action, ""); |
| 709 | params.extend(span.params()); | 701 | params.extend(span.params()); |
| 710 | let nav = nav_for(page, pages, "/settings/security/log", ¶ms); | 702 | let nav = nav_for(page, pages, "/settings/security/log", ¶ms); |
| @@ -47,31 +47,31 @@ async fn dismiss(cx: &Cx, Form(form): Form<DismissForm>) -> Result<SeeOther> { |
| 47 | #[cfg(test)] | 47 | #[cfg(test)] |
| 48 | mod tests { | 48 | mod tests { |
| 49 | use crate::views::view_for; | 49 | use crate::views::view_for; |
| 50 | - use forge_core::config::BannerConfig; | 50 | + use forge_core::config::{BannerConfig, BannerLevel}; |
| 51 | | 51 | |
| 52 | - fn config(message: &str, level: &str, expires: &str) -> BannerConfig { | 52 | + fn config(message: &str, level: BannerLevel, expires: &str) -> BannerConfig { |
| 53 | BannerConfig { | 53 | BannerConfig { |
| 54 | message: message.into(), | 54 | message: message.into(), |
| 55 | - level: level.into(), | 55 | + level, |
| 56 | expires: expires.into(), | 56 | expires: expires.into(), |
| 57 | } | 57 | } |
| 58 | } | 58 | } |
| 59 | | 59 | |
| 60 | #[test] | 60 | #[test] |
| 61 | fn empty_and_expired_banners_are_hidden() { | 61 | fn empty_and_expired_banners_are_hidden() { |
| 62 | - assert!(view_for(&config("", "info", ""), 0, None).is_none()); | 62 | + assert!(view_for(&config("", BannerLevel::Info, ""), 0, None).is_none()); |
| 63 | let expiry = forge_core::config::parse_banner_expiry("2026-12-31 18:00").unwrap(); | 63 | let expiry = forge_core::config::parse_banner_expiry("2026-12-31 18:00").unwrap(); |
| 64 | - let cfg = config("maintenance", "warning", "2026-12-31 18:00"); | 64 | + let cfg = config("maintenance", BannerLevel::Warning, "2026-12-31 18:00"); |
| 65 | assert!(view_for(&cfg, expiry - 1, None).is_some()); | 65 | assert!(view_for(&cfg, expiry - 1, None).is_some()); |
| 66 | assert!(view_for(&cfg, expiry, None).is_none()); | 66 | assert!(view_for(&cfg, expiry, None).is_none()); |
| 67 | } | 67 | } |
| 68 | | 68 | |
| 69 | #[test] | 69 | #[test] |
| 70 | fn a_dismissed_hash_hides_only_that_message() { | 70 | fn a_dismissed_hash_hides_only_that_message() { |
| 71 | - let cfg = config("maintenance tonight", "info", ""); | 71 | + let cfg = config("maintenance tonight", BannerLevel::Info, ""); |
| 72 | let shown = view_for(&cfg, 0, None).unwrap(); | 72 | let shown = view_for(&cfg, 0, None).unwrap(); |
| 73 | assert!(view_for(&cfg, 0, Some(&shown.hash)).is_none()); | 73 | assert!(view_for(&cfg, 0, Some(&shown.hash)).is_none()); |
| 74 | - let changed = config("maintenance tomorrow", "info", ""); | 74 | + let changed = config("maintenance tomorrow", BannerLevel::Info, ""); |
| 75 | assert!(view_for(&changed, 0, Some(&shown.hash)).is_some()); | 75 | assert!(view_for(&changed, 0, Some(&shown.hash)).is_some()); |
| 76 | } | 76 | } |
| 77 | | 77 | |
| @@ -13,9 +13,10 @@ use crate::live::{Topic, stream_changes}; |
| 13 | use crate::pages::issues_list::list_href; | 13 | use crate::pages::issues_list::list_href; |
| 14 | use crate::state::AppState; | 14 | use crate::state::AppState; |
| 15 | use crate::views::find::{Finder, finder_field}; | 15 | use crate::views::find::{Finder, finder_field}; |
| | 16 | +use crate::views::paging::{paginate, requested_page}; |
| 16 | use crate::views::parts::head; | 17 | use crate::views::parts::head; |
| 17 | use crate::views::repo_list::{ | 18 | use crate::views::repo_list::{ |
| 18 | - PageLink, RepoRow, SortLink, pager, pager_links, repo_rows, sort_chips, | 19 | + PageLink, RepoRow, SortLink, pager, pager_links, pick_sort, repo_rows, sort_chips, |
| 19 | }; | 20 | }; |
| 20 | use crate::views::{now_unix, shell}; | 21 | use crate::views::{now_unix, shell}; |
| 21 | | 22 | |
| @@ -56,7 +57,7 @@ async fn org_listing( |
| 56 | state: &AppState, | 57 | state: &AppState, |
| 57 | finder: &Finder, | 58 | finder: &Finder, |
| 58 | page: u64, | 59 | page: u64, |
| 59 | -) -> Result<(Vec<User>, u64, u64)> { | 60 | +) -> Result<(Vec<User>, u64, u64, u64)> { |
| 60 | let mut all: Vec<User> = state | 61 | let mut all: Vec<User> = state |
| 61 | .store | 62 | .store |
| 62 | .list_orgs() | 63 | .list_orgs() |
| @@ -71,13 +72,8 @@ async fn org_listing( |
| 71 | .collect(); | 72 | .collect(); |
| 72 | all.sort_by_key(|org| org.username.to_lowercase()); | 73 | all.sort_by_key(|org| org.username.to_lowercase()); |
| 73 | let total = all.len() as u64; | 74 | let total = all.len() as u64; |
| 74 | - let page = page.clamp(1, total.div_ceil(PER_PAGE).max(1)); | 75 | + let (shown, page, pages) = paginate(all, page, PER_PAGE); |
| 75 | - let shown = all | 76 | + Ok((shown, total, pages, page)) |
| 76 | - .into_iter() | | |
| 77 | - .skip(((page - 1) * PER_PAGE) as usize) | | |
| 78 | - .take(PER_PAGE as usize) | | |
| 79 | - .collect(); | | |
| 80 | - Ok((shown, total, page)) | | |
| 81 | } | 77 | } |
| 82 | | 78 | |
| 83 | fn explore_href(finder: &Finder, sort: &str, page: u64) -> String { | 79 | fn explore_href(finder: &Finder, sort: &str, page: u64) -> String { |
| @@ -88,28 +84,14 @@ fn explore_href(finder: &Finder, sort: &str, page: u64) -> String { |
| 88 | list_href("/explore", ¶ms) | 84 | list_href("/explore", ¶ms) |
| 89 | } | 85 | } |
| 90 | | 86 | |
| 91 | -fn sort_key(raw: Option<&str>) -> &'static str { | | |
| 92 | - SORTS | | |
| 93 | - .iter() | | |
| 94 | - .map(|(key, _)| *key) | | |
| 95 | - .find(|key| Some(*key) == raw) | | |
| 96 | - .unwrap_or(SORTS[0].0) | | |
| 97 | -} | | |
| 98 | - | | |
| 99 | fn listing_args(query: &ExploreQuery) -> (Finder, &'static str, u64) { | 87 | fn listing_args(query: &ExploreQuery) -> (Finder, &'static str, u64) { |
| 100 | let finder = Finder::new( | 88 | let finder = Finder::new( |
| 101 | query.q.as_deref(), | 89 | query.q.as_deref(), |
| 102 | query.exact.as_deref(), | 90 | query.exact.as_deref(), |
| 103 | query.case.as_deref(), | 91 | query.case.as_deref(), |
| 104 | ); | 92 | ); |
| 105 | - let sort = sort_key(query.sort.as_deref()); | 93 | + let sort = pick_sort(query.sort.as_deref(), &SORTS); |
| 106 | - let page = query | 94 | + (finder, sort, requested_page(query.page.as_deref())) |
| 107 | - .page | | |
| 108 | - .as_deref() | | |
| 109 | - .and_then(|p| p.parse::<u64>().ok()) | | |
| 110 | - .unwrap_or(1) | | |
| 111 | - .max(1); | | |
| 112 | - (finder, sort, page) | | |
| 113 | } | 95 | } |
| 114 | | 96 | |
| 115 | async fn listing( | 97 | async fn listing( |
| @@ -117,7 +99,7 @@ async fn listing( |
| 117 | finder: &Finder, | 99 | finder: &Finder, |
| 118 | sort: &'static str, | 100 | sort: &'static str, |
| 119 | page: u64, | 101 | page: u64, |
| 120 | -) -> Result<(Vec<(Repo, u64, String)>, u64, u64)> { | 102 | +) -> Result<(Vec<(Repo, u64, String)>, u64, u64, u64)> { |
| 121 | let sort_kind = match sort { | 103 | let sort_kind = match sort { |
| 122 | "stars" => RepoSort::MostStars, | 104 | "stars" => RepoSort::MostStars, |
| 123 | "name" => RepoSort::Name, | 105 | "name" => RepoSort::Name, |
| @@ -135,13 +117,8 @@ async fn listing( |
| 135 | }) | 117 | }) |
| 136 | .collect(); | 118 | .collect(); |
| 137 | let total = matching.len() as u64; | 119 | let total = matching.len() as u64; |
| 138 | - let page = page.clamp(1, total.div_ceil(PER_PAGE).max(1)); | 120 | + let (shown, page, pages) = paginate(matching, page, PER_PAGE); |
| 139 | - let shown = matching | 121 | + Ok((shown, total, pages, page)) |
| 140 | - .into_iter() | | |
| 141 | - .skip(((page - 1) * PER_PAGE) as usize) | | |
| 142 | - .take(PER_PAGE as usize) | | |
| 143 | - .collect(); | | |
| 144 | - Ok((shown, total, page)) | | |
| 145 | } | 122 | } |
| 146 | | 123 | |
| 147 | #[page("/explore")] | 124 | #[page("/explore")] |
| @@ -152,12 +129,12 @@ async fn explore_page(cx: &Cx) -> Result<impl View> { |
| 152 | let lang = i18n::lang(cx, viewer.as_ref().map(|(u, _)| u)); | 129 | let lang = i18n::lang(cx, viewer.as_ref().map(|(u, _)| u)); |
| 153 | let state = context::<AppState>(cx); | 130 | let state = context::<AppState>(cx); |
| 154 | let on_orgs = orgs_tab(query); | 131 | let on_orgs = orgs_tab(query); |
| 155 | - let (listed, org_page, total, page) = if on_orgs { | 132 | + let (listed, org_page, total, pages, page) = if on_orgs { |
| 156 | - let (orgs, total, page) = org_listing(state, &finder, page).await?; | 133 | + let (orgs, total, pages, page) = org_listing(state, &finder, page).await?; |
| 157 | - (Vec::new(), orgs, total, page) | 134 | + (Vec::new(), orgs, total, pages, page) |
| 158 | } else { | 135 | } else { |
| 159 | - let (repos, total, page) = listing(state, &finder, sort, page).await?; | 136 | + let (repos, total, pages, page) = listing(state, &finder, sort, page).await?; |
| 160 | - (repos, Vec::new(), total, page) | 137 | + (repos, Vec::new(), total, pages, page) |
| 161 | }; | 138 | }; |
| 162 | let (_, repos_all) = state | 139 | let (_, repos_all) = state |
| 163 | .store | 140 | .store |
| @@ -182,7 +159,6 @@ async fn explore_page(cx: &Cx) -> Result<impl View> { |
| 182 | let avatar = crate::views::avatar_url(&org.username, hash.as_deref()); | 159 | let avatar = crate::views::avatar_url(&org.username, hash.as_deref()); |
| 183 | orgs.push((org.username, avatar)); | 160 | orgs.push((org.username, avatar)); |
| 184 | } | 161 | } |
| 185 | - let pages = total.div_ceil(PER_PAGE).max(1); | | |
| 186 | let sort_links: Vec<SortLink> = SORTS | 162 | let sort_links: Vec<SortLink> = SORTS |
| 187 | .iter() | 163 | .iter() |
| 188 | .map(|(key, label)| SortLink { | 164 | .map(|(key, label)| SortLink { |
| @@ -242,12 +218,12 @@ async fn explore_fingerprint( |
| 242 | on_orgs: bool, | 218 | on_orgs: bool, |
| 243 | ) -> Result<String> { | 219 | ) -> Result<String> { |
| 244 | if on_orgs { | 220 | if on_orgs { |
| 245 | - let (orgs, total, _) = org_listing(state, finder, page).await?; | 221 | + let (orgs, total, _, _) = org_listing(state, finder, page).await?; |
| 246 | let mut lines = vec![total.to_string()]; | 222 | let mut lines = vec![total.to_string()]; |
| 247 | lines.extend(orgs.into_iter().map(|org| format!("org {}", org.username))); | 223 | lines.extend(orgs.into_iter().map(|org| format!("org {}", org.username))); |
| 248 | return Ok(lines.join("\n")); | 224 | return Ok(lines.join("\n")); |
| 249 | } | 225 | } |
| 250 | - let (listed, total, _) = listing(state, finder, sort, page).await?; | 226 | + let (listed, total, _, _) = listing(state, finder, sort, page).await?; |
| 251 | let mut lines = vec![total.to_string()]; | 227 | let mut lines = vec![total.to_string()]; |
| 252 | for (repo, stars, activity) in listed { | 228 | for (repo, stars, activity) in listed { |
| 253 | lines.push(format!( | 229 | lines.push(format!( |
| @@ -27,6 +27,7 @@ use crate::live::{changed_event, events_response}; |
| 27 | use crate::pages::new_repo::{owner_choices, repo_owner}; | 27 | use crate::pages::new_repo::{owner_choices, repo_owner}; |
| 28 | use crate::pages::repo_ctx::still_readable; | 28 | use crate::pages::repo_ctx::still_readable; |
| 29 | use crate::state::AppState; | 29 | use crate::state::AppState; |
| | 30 | +use crate::views::paging::{paginate, requested_page}; |
| 30 | use crate::views::parts::{SubPart, head}; | 31 | use crate::views::parts::{SubPart, head}; |
| 31 | use crate::views::repo_list::{PageLink, pager, pager_links}; | 32 | use crate::views::repo_list::{PageLink, pager, pager_links}; |
| 32 | use crate::views::{alert, csrf_field, rel_time, shell, user_facing_message}; | 33 | use crate::views::{alert, csrf_field, rel_time, shell, user_facing_message}; |
| @@ -1067,20 +1068,10 @@ async fn jobs_page(cx: &Cx) -> Result<impl View> { |
| 1067 | let state = context::<AppState>(cx); | 1068 | let state = context::<AppState>(cx); |
| 1068 | let query = query_params::<JobsQuery>(cx)?; | 1069 | let query = query_params::<JobsQuery>(cx)?; |
| 1069 | let all = state.store.list_import_jobs(&viewer.0.id, 1000).await?; | 1070 | let all = state.store.list_import_jobs(&viewer.0.id, 1000).await?; |
| 1070 | - let pages = (all.len() as u64).div_ceil(HISTORY_ROWS).max(1); | 1071 | + let (shown, page, pages) = paginate(all, requested_page(query.page.as_deref()), HISTORY_ROWS); |
| 1071 | - let page = query | | |
| 1072 | - .page | | |
| 1073 | - .as_deref() | | |
| 1074 | - .and_then(|p| p.parse::<u64>().ok()) | | |
| 1075 | - .unwrap_or(1) | | |
| 1076 | - .clamp(1, pages); | | |
| 1077 | let user = state.store.user_by_id(&viewer.0.id).await?; | 1072 | let user = state.store.user_by_id(&viewer.0.id).await?; |
| 1078 | let mut rows = Vec::new(); | 1073 | let mut rows = Vec::new(); |
| 1079 | - for job in all | 1074 | + for job in shown { |
| 1080 | - .into_iter() | | |
| 1081 | - .skip(((page - 1) * HISTORY_ROWS) as usize) | | |
| 1082 | - .take(HISTORY_ROWS as usize) | | |
| 1083 | - { | | |
| 1084 | let repo = job_repo(state, user.as_ref(), &job).await?; | 1075 | let repo = job_repo(state, user.as_ref(), &job).await?; |
| 1085 | rows.push((job, repo)); | 1076 | rows.push((job, repo)); |
| 1086 | } | 1077 | } |
| @@ -14,7 +14,7 @@ use topcoat::view::{View, component, view}; |
| 14 | | 14 | |
| 15 | use crate::audit::{self, Actor, Target}; | 15 | use crate::audit::{self, Actor, Target}; |
| 16 | use crate::auth::{ | 16 | use crate::auth::{ |
| 17 | - check_csrf, check_pre_csrf, clear_pending_login, clear_pre_csrf, current_user, | 17 | + CsrfForm, check_csrf, check_pre_csrf, clear_pending_login, clear_pre_csrf, current_user, |
| 18 | hash_password_async, login, logout, pending_login, pre_csrf_token, safe_next, | 18 | hash_password_async, login, logout, pending_login, pre_csrf_token, safe_next, |
| 19 | set_pending_login, two_factor_enabled, verify_password_async, verify_second_factor, | 19 | set_pending_login, two_factor_enabled, verify_password_async, verify_second_factor, |
| 20 | }; | 20 | }; |
| @@ -52,12 +52,6 @@ struct LoginForm { |
| 52 | precsrf: String, | 52 | precsrf: String, |
| 53 | } | 53 | } |
| 54 | | 54 | |
| 55 | -#[derive(Deserialize)] | | |
| 56 | -struct CsrfForm { | | |
| 57 | - #[serde(default)] | | |
| 58 | - csrf: String, | | |
| 59 | -} | | |
| 60 | - | | |
| 61 | #[derive(Deserialize)] | 55 | #[derive(Deserialize)] |
| 62 | struct TwoFactorForm { | 56 | struct TwoFactorForm { |
| 63 | #[serde(default)] | 57 | #[serde(default)] |
| @@ -725,11 +719,7 @@ mod tests { |
| 725 | } | 719 | } |
| 726 | | 720 | |
| 727 | fn live_code(shared: &[u8], ahead: u64) -> String { | 721 | fn live_code(shared: &[u8], ahead: u64) -> String { |
| 728 | - let now = std::time::SystemTime::now() | 722 | + totp::code_at(shared, totp::step_for(forge_core::time::now_unix()) + ahead) |
| 729 | - .duration_since(std::time::UNIX_EPOCH) | | |
| 730 | - .unwrap() | | |
| 731 | - .as_secs(); | | |
| 732 | - totp::code_at(shared, totp::step_for(now) + ahead) | | |
| 733 | } | 723 | } |
| 734 | | 724 | |
| 735 | fn both(pending: &str, precsrf_cookie: &str) -> String { | 725 | fn both(pending: &str, precsrf_cookie: &str) -> String { |
| @@ -1,7 +1,6 @@ |
| 1 | use forge_core::User; | 1 | use forge_core::User; |
| 2 | use forge_core::authz::{Action, authorize}; | 2 | use forge_core::authz::{Action, authorize}; |
| 3 | use forge_core::store::needs::Verdict; | 3 | use forge_core::store::needs::Verdict; |
| 4 | -use serde::Deserialize; | | |
| 5 | use topcoat::Result; | 4 | use topcoat::Result; |
| 6 | use topcoat::context::{Cx, context}; | 5 | use topcoat::context::{Cx, context}; |
| 7 | use topcoat::router::content::Form; | 6 | use topcoat::router::content::Form; |
| @@ -10,13 +9,14 @@ use topcoat::router::response::Response; |
| 10 | use topcoat::router::{Body, StatusCode, page, query_params, route}; | 9 | use topcoat::router::{Body, StatusCode, page, query_params, route}; |
| 11 | use topcoat::view::{View, component, view}; | 10 | use topcoat::view::{View, component, view}; |
| 12 | | 11 | |
| 13 | -use crate::auth::{current_user, require_csrf, require_user}; | 12 | +use crate::auth::{CsrfForm, current_user, require_csrf, require_user}; |
| 14 | use crate::i18n::authoring::{self as ga}; | 13 | use crate::i18n::authoring::{self as ga}; |
| 15 | use crate::i18n::needs::{self as ni, K}; | 14 | use crate::i18n::needs::{self as ni, K}; |
| 16 | use crate::i18n::{self, Lang}; | 15 | use crate::i18n::{self, Lang}; |
| 17 | use crate::live::{Topic, stream_wakes}; | 16 | use crate::live::{Topic, stream_wakes}; |
| 18 | use crate::pages::ci_runs::run_href; | 17 | use crate::pages::ci_runs::run_href; |
| 19 | use crate::state::AppState; | 18 | use crate::state::AppState; |
| | 19 | +use crate::views::paging::{page_count, requested_page}; |
| 20 | use crate::views::parts::{head, post_act}; | 20 | use crate::views::parts::{head, post_act}; |
| 21 | use crate::views::repo_list::{PageLink, pager, pager_links}; | 21 | use crate::views::repo_list::{PageLink, pager, pager_links}; |
| 22 | use crate::views::{rel_time, repo_href, shell}; | 22 | use crate::views::{rel_time, repo_href, shell}; |
| @@ -308,11 +308,8 @@ async fn load_full( |
| 308 | requested: Option<&str>, | 308 | requested: Option<&str>, |
| 309 | ) -> Result<NeedSection> { | 309 | ) -> Result<NeedSection> { |
| 310 | let total = section.total(state, &user.id).await?; | 310 | let total = section.total(state, &user.id).await?; |
| 311 | - let pages = total.div_ceil(PER_PAGE).max(1); | 311 | + let pages = page_count(total, PER_PAGE); |
| 312 | - let page = requested | 312 | + let page = requested_page(requested).clamp(1, pages); |
| 313 | - .and_then(|p| p.parse::<u64>().ok()) | | |
| 314 | - .unwrap_or(1) | | |
| 315 | - .clamp(1, pages); | | |
| 316 | let offset = (page - 1) * PER_PAGE; | 313 | let offset = (page - 1) * PER_PAGE; |
| 317 | let rows = section | 314 | let rows = section |
| 318 | .rows(state, user, lang, PER_PAGE as i64, offset as i64) | 315 | .rows(state, user, lang, PER_PAGE as i64, offset as i64) |
| @@ -438,12 +435,6 @@ async fn needs_you(cx: &Cx) -> Result<impl View> { |
| 438 | }) | 435 | }) |
| 439 | } | 436 | } |
| 440 | | 437 | |
| 441 | -#[derive(Deserialize)] | | |
| 442 | -struct CsrfForm { | | |
| 443 | - #[serde(default)] | | |
| 444 | - csrf: String, | | |
| 445 | -} | | |
| 446 | - | | |
| 447 | #[route(POST "/needs-you/runs/dismiss")] | 438 | #[route(POST "/needs-you/runs/dismiss")] |
| 448 | async fn dismiss_failed_runs(cx: &Cx, Form(form): Form<CsrfForm>) -> Result<SeeOther> { | 439 | async fn dismiss_failed_runs(cx: &Cx, Form(form): Form<CsrfForm>) -> Result<SeeOther> { |
| 449 | let (user, _) = require_csrf(cx, &form.csrf).await?; | 440 | let (user, _) = require_csrf(cx, &form.csrf).await?; |
| @@ -4,7 +4,6 @@ use forge_core::{Role, Session, User}; |
| 4 | use topcoat::Result; | 4 | use topcoat::Result; |
| 5 | use topcoat::context::{Cx, context}; | 5 | use topcoat::context::{Cx, context}; |
| 6 | use topcoat::router::error::{forbidden, not_found}; | 6 | use topcoat::router::error::{forbidden, not_found}; |
| 7 | -use topcoat::router::request::uri; | | |
| 8 | use topcoat::view::{View, component, view}; | 7 | use topcoat::view::{View, component, view}; |
| 9 | | 8 | |
| 10 | use crate::auth::{check_csrf, require_user}; | 9 | use crate::auth::{check_csrf, require_user}; |
| @@ -12,7 +11,7 @@ use crate::i18n::Lang; |
| 12 | use crate::i18n::orgs::{self as g, K}; | 11 | use crate::i18n::orgs::{self as g, K}; |
| 13 | use crate::pages::packages; | 12 | use crate::pages::packages; |
| 14 | use crate::state::AppState; | 13 | use crate::state::AppState; |
| 15 | -use crate::views::{alert, profile_items}; | 14 | +use crate::views::{notice_line, profile_items, query_value}; |
| 16 | | 15 | |
| 17 | const NOTICE_PARAM: &str = "notice"; | 16 | const NOTICE_PARAM: &str = "notice"; |
| 18 | | 17 | |
| @@ -139,10 +138,7 @@ pub fn notice_href(back: &str, word: &'static str) -> String { |
| 139 | } | 138 | } |
| 140 | | 139 | |
| 141 | pub fn take_notice(cx: &Cx, lang: Lang) -> Option<(&'static str, bool)> { | 140 | pub fn take_notice(cx: &Cx, lang: Lang) -> Option<(&'static str, bool)> { |
| 142 | - let query = uri(cx).query()?; | 141 | + let value = query_value(cx, NOTICE_PARAM)?; |
| 143 | - let value = query | | |
| 144 | - .split('&') | | |
| 145 | - .find_map(|pair| pair.strip_prefix(NOTICE_PARAM)?.strip_prefix('='))?; | | |
| 146 | NOTICES | 142 | NOTICES |
| 147 | .iter() | 143 | .iter() |
| 148 | .find(|(word, _, _)| *word == value) | 144 | .find(|(word, _, _)| *word == value) |
| @@ -208,11 +204,7 @@ pub async fn org_tabs( |
| 208 | pub async fn org_notice(cx: &Cx, notice: Option<(&'static str, bool)>) -> Result<impl View> { | 204 | pub async fn org_notice(cx: &Cx, notice: Option<(&'static str, bool)>) -> Result<impl View> { |
| 209 | Ok(view! { | 205 | Ok(view! { |
| 210 | if let Some((text, is_error)) = notice { | 206 | if let Some((text, is_error)) = notice { |
| 211 | - if is_error { | 207 | + notice_line(text: text, is_error: is_error) |
| 212 | - alert(message: text) | | |
| 213 | - } else { | | |
| 214 | - <p class="state" role="status">(text)</p> | | |
| 215 | - } | | |
| 216 | } | 208 | } |
| 217 | }) | 209 | }) |
| 218 | } | 210 | } |
| @@ -160,7 +160,7 @@ async fn org_members_add(cx: &Cx, Form(form): Form<AddForm>) -> Result<SeeOther> |
| 160 | let state = context::<AppState>(cx); | 160 | let state = context::<AppState>(cx); |
| 161 | let back = ctx.href("/members"); | 161 | let back = ctx.href("/members"); |
| 162 | | 162 | |
| 163 | - let Some(role) = OrgMemberRole::parse(form.role.trim()).ok() else { | 163 | + let Some(role) = form.role.trim().parse::<OrgMemberRole>().ok() else { |
| 164 | return Ok(see_other(notice_href(&back, "invalid_role"))); | 164 | return Ok(see_other(notice_href(&back, "invalid_role"))); |
| 165 | }; | 165 | }; |
| 166 | let username = form.username.trim(); | 166 | let username = form.username.trim(); |
| @@ -210,7 +210,7 @@ async fn org_members_role(cx: &Cx, Form(form): Form<RoleForm>) -> Result<SeeOthe |
| 210 | let state = context::<AppState>(cx); | 210 | let state = context::<AppState>(cx); |
| 211 | let back = ctx.href("/members"); | 211 | let back = ctx.href("/members"); |
| 212 | | 212 | |
| 213 | - let Some(role) = OrgMemberRole::parse(form.role.trim()).ok() else { | 213 | + let Some(role) = form.role.trim().parse::<OrgMemberRole>().ok() else { |
| 214 | return Ok(see_other(notice_href(&back, "invalid_role"))); | 214 | return Ok(see_other(notice_href(&back, "invalid_role"))); |
| 215 | }; | 215 | }; |
| 216 | let user_id = form.user_id.trim(); | 216 | let user_id = form.user_id.trim(); |
| @@ -10,6 +10,7 @@ use topcoat::router::{page, path_param, route}; |
| 10 | use topcoat::view::{View, component, view}; | 10 | use topcoat::view::{View, component, view}; |
| 11 | | 11 | |
| 12 | use crate::audit::{self, Actor, Target}; | 12 | use crate::audit::{self, Actor, Target}; |
| | 13 | +use crate::auth::CsrfForm; |
| 13 | use crate::i18n::orgs::{self as g, K}; | 14 | use crate::i18n::orgs::{self as g, K}; |
| 14 | use crate::i18n::{self, Key, Lang, t}; | 15 | use crate::i18n::{self, Key, Lang, t}; |
| 15 | use crate::live::Topic; | 16 | use crate::live::Topic; |
| @@ -38,12 +39,6 @@ struct SettingsForm { |
| 38 | members_can_create: String, | 39 | members_can_create: String, |
| 39 | } | 40 | } |
| 40 | | 41 | |
| 41 | -#[derive(Deserialize)] | | |
| 42 | -struct CsrfForm { | | |
| 43 | - #[serde(default)] | | |
| 44 | - csrf: String, | | |
| 45 | -} | | |
| 46 | - | | |
| 47 | #[derive(Deserialize)] | 42 | #[derive(Deserialize)] |
| 48 | struct DeleteForm { | 43 | struct DeleteForm { |
| 49 | #[serde(default)] | 44 | #[serde(default)] |
| @@ -144,7 +139,7 @@ async fn settings_body( |
| 144 | </div> | 139 | </div> |
| 145 | <div class="acts asks"> | 140 | <div class="acts asks"> |
| 146 | <button type="submit" class="danger small">(g::t(lang, K::DeleteOrg))</button> | 141 | <button type="submit" class="danger small">(g::t(lang, K::DeleteOrg))</button> |
| 147 | - <button type="button" class="act" data-close-details="">(crate::i18n::s(lang, "Cancel", "Vazgeç"))</button> | 142 | + <button type="button" class="act" data-close-details="">(crate::i18n::t(lang, crate::i18n::Key::Cancel))</button> |
| 148 | </div> | 143 | </div> |
| 149 | </form> | 144 | </form> |
| 150 | </details> | 145 | </details> |
| @@ -196,7 +191,7 @@ async fn org_settings_save(cx: &Cx, Form(form): Form<SettingsForm>) -> Result<Se |
| 196 | if description.chars().count() > MAX_DESCRIPTION_CHARS { | 191 | if description.chars().count() > MAX_DESCRIPTION_CHARS { |
| 197 | return Ok(see_other(notice_href(&back, "description_length"))); | 192 | return Ok(see_other(notice_href(&back, "description_length"))); |
| 198 | } | 193 | } |
| 199 | - let Ok(default_repo_role) = DefaultRepoRole::parse(form.default_repo_role.trim()) else { | 194 | + let Ok(default_repo_role) = form.default_repo_role.trim().parse::<DefaultRepoRole>() else { |
| 200 | return Ok(see_other(notice_href(&back, "invalid_role"))); | 195 | return Ok(see_other(notice_href(&back, "invalid_role"))); |
| 201 | }; | 196 | }; |
| 202 | let members_can_create_repos = !form.members_can_create.is_empty(); | 197 | let members_can_create_repos = !form.members_can_create.is_empty(); |
| @@ -9,6 +9,7 @@ use topcoat::router::{page, path_param, route}; |
| 9 | use topcoat::view::{View, component, view}; | 9 | use topcoat::view::{View, component, view}; |
| 10 | | 10 | |
| 11 | use crate::audit::{self, Actor, Target}; | 11 | use crate::audit::{self, Actor, Target}; |
| | 12 | +use crate::auth::CsrfForm; |
| 12 | use crate::i18n::orgs::{self as g, K}; | 13 | use crate::i18n::orgs::{self as g, K}; |
| 13 | use crate::i18n::{self, Lang}; | 14 | use crate::i18n::{self, Lang}; |
| 14 | use crate::pages::org_ctx::{ | 15 | use crate::pages::org_ctx::{ |
| @@ -24,12 +25,6 @@ path_param!(team); |
| 24 | | 25 | |
| 25 | const MAX_TEAM_DESCRIPTION_CHARS: usize = 350; | 26 | const MAX_TEAM_DESCRIPTION_CHARS: usize = 350; |
| 26 | | 27 | |
| 27 | -#[derive(Deserialize)] | | |
| 28 | -struct CsrfForm { | | |
| 29 | - #[serde(default)] | | |
| 30 | - csrf: String, | | |
| 31 | -} | | |
| 32 | - | | |
| 33 | #[derive(Deserialize)] | 28 | #[derive(Deserialize)] |
| 34 | struct TeamForm { | 29 | struct TeamForm { |
| 35 | #[serde(default)] | 30 | #[serde(default)] |
| @@ -26,7 +26,7 @@ use webauthn_rs_proto::ResidentKeyRequirement; |
| 26 | use crate::api; | 26 | use crate::api; |
| 27 | use crate::audit::{self, Actor, Target}; | 27 | use crate::audit::{self, Actor, Target}; |
| 28 | use crate::auth::{ | 28 | use crate::auth::{ |
| 29 | - check_pre_csrf, clear_pending_login, clear_pre_csrf, login, require_csrf, safe_next, | 29 | + CsrfForm, check_pre_csrf, clear_pending_login, clear_pre_csrf, login, require_csrf, safe_next, |
| 30 | }; | 30 | }; |
| 31 | use crate::client_ip::client_ip; | 31 | use crate::client_ip::client_ip; |
| 32 | use crate::i18n::{self, Key, Lang, s, t}; | 32 | use crate::i18n::{self, Key, Lang, s, t}; |
| @@ -178,12 +178,6 @@ struct FinishForm { |
| 178 | credential: String, | 178 | credential: String, |
| 179 | } | 179 | } |
| 180 | | 180 | |
| 181 | -#[derive(Deserialize)] | | |
| 182 | -struct CsrfForm { | | |
| 183 | - #[serde(default)] | | |
| 184 | - csrf: String, | | |
| 185 | -} | | |
| 186 | - | | |
| 187 | #[derive(Deserialize)] | 181 | #[derive(Deserialize)] |
| 188 | struct RenameForm { | 182 | struct RenameForm { |
| 189 | #[serde(default)] | 183 | #[serde(default)] |
| @@ -593,6 +587,13 @@ pub async fn build_panel(state: &AppState, user_id: &str) -> forge_core::Result< |
| 593 | }) | 587 | }) |
| 594 | } | 588 | } |
| 595 | | 589 | |
| | 590 | +struct PasskeyEntry { |
| | 591 | + item: PasskeyItem, |
| | 592 | + rename_action: String, |
| | 593 | + delete_action: String, |
| | 594 | + field: String, |
| | 595 | +} |
| | 596 | + |
| 596 | #[component] | 597 | #[component] |
| 597 | pub async fn passkeys_panel( | 598 | pub async fn passkeys_panel( |
| 598 | cx: &Cx, | 599 | cx: &Cx, |
| @@ -605,13 +606,18 @@ pub async fn passkeys_panel( |
| 605 | let count_text = format!("{} {}", items.len(), s(lang, "passkeys", "geçiş anahtarı")); | 606 | let count_text = format!("{} {}", items.len(), s(lang, "passkeys", "geçiş anahtarı")); |
| 606 | let usable = problem.is_none(); | 607 | let usable = problem.is_none(); |
| 607 | let problem_text = problem.map(|why| why.message(lang)); | 608 | let problem_text = problem.map(|why| why.message(lang)); |
| 608 | - let rows: Vec<(PasskeyItem, String, String, String)> = items | 609 | + let rows: Vec<PasskeyEntry> = items |
| 609 | .into_iter() | 610 | .into_iter() |
| 610 | .map(|item| { | 611 | .map(|item| { |
| 611 | let rename_action = format!("/settings/security/passkeys/{}/rename", item.id); | 612 | let rename_action = format!("/settings/security/passkeys/{}/rename", item.id); |
| 612 | let delete_action = format!("/settings/security/passkeys/{}/delete", item.id); | 613 | let delete_action = format!("/settings/security/passkeys/{}/delete", item.id); |
| 613 | let field = format!("passkey-name-{}", item.id); | 614 | let field = format!("passkey-name-{}", item.id); |
| 614 | - (item, rename_action, delete_action, field) | 615 | + PasskeyEntry { |
| | 616 | + item, |
| | 617 | + rename_action, |
| | 618 | + delete_action, |
| | 619 | + field, |
| | 620 | + } |
| 615 | }) | 621 | }) |
| 616 | .collect(); | 622 | .collect(); |
| 617 | Ok(view! { | 623 | Ok(view! { |
| @@ -625,7 +631,7 @@ pub async fn passkeys_panel( |
| 625 | if let Some(text) = problem_text { | 631 | if let Some(text) = problem_text { |
| 626 | <p class="hint topic-warn">(text)</p> | 632 | <p class="hint topic-warn">(text)</p> |
| 627 | } | 633 | } |
| 628 | - for (item, rename_action, delete_action, field) in rows.into_iter() { | 634 | + for PasskeyEntry { item, rename_action, delete_action, field } in rows { |
| 629 | <details class="row-open"> | 635 | <details class="row-open"> |
| 630 | <summary class="line"> | 636 | <summary class="line"> |
| 631 | <span class="name">(item.name.as_str())</span> | 637 | <span class="name">(item.name.as_str())</span> |
| @@ -29,9 +29,10 @@ use crate::render::markdown::render_markdown; |
| 29 | use crate::state::AppState; | 29 | use crate::state::AppState; |
| 30 | use crate::views::find::{Finder, finder_field}; | 30 | use crate::views::find::{Finder, finder_field}; |
| 31 | use crate::views::heatmap::{Calendar, DayDetail, contribution_calendar}; | 31 | use crate::views::heatmap::{Calendar, DayDetail, contribution_calendar}; |
| | 32 | +use crate::views::paging::{page_count, paginate, requested_page}; |
| 32 | use crate::views::parts::{SubPart, head}; | 33 | use crate::views::parts::{SubPart, head}; |
| 33 | use crate::views::repo_list::{ | 34 | use crate::views::repo_list::{ |
| 34 | - PageLink, RepoRow, SortLink, pager, pager_links, private_fact, repo_rows, sort_chips, | 35 | + PageLink, RepoRow, SortLink, pager, pager_links, pick_sort, private_fact, repo_rows, sort_chips, |
| 35 | }; | 36 | }; |
| 36 | use crate::views::{ | 37 | use crate::views::{ |
| 37 | NavItem, avatar_url, enc, now_unix, profile_items, repo_href, shell, user_href, | 38 | NavItem, avatar_url, enc, now_unix, profile_items, repo_href, shell, user_href, |
| @@ -68,14 +69,6 @@ const SORTS: [(&str, K); 3] = [ |
| 68 | ("stars", K::SortMostStars), | 69 | ("stars", K::SortMostStars), |
| 69 | ]; | 70 | ]; |
| 70 | | 71 | |
| 71 | -fn sort_key(raw: Option<&str>) -> &'static str { | | |
| 72 | - SORTS | | |
| 73 | - .iter() | | |
| 74 | - .map(|(key, _)| *key) | | |
| 75 | - .find(|key| Some(*key) == raw) | | |
| 76 | - .unwrap_or(SORTS[0].0) | | |
| 77 | -} | | |
| 78 | - | | |
| 79 | #[derive(Clone, Copy, PartialEq, Eq)] | 72 | #[derive(Clone, Copy, PartialEq, Eq)] |
| 80 | pub enum Tab { | 73 | pub enum Tab { |
| 81 | Overview, | 74 | Overview, |
| @@ -145,8 +138,8 @@ async fn profile_page(cx: &Cx) -> Result<impl View> { |
| 145 | query.exact.as_deref(), | 138 | query.exact.as_deref(), |
| 146 | query.case.as_deref(), | 139 | query.case.as_deref(), |
| 147 | ); | 140 | ); |
| 148 | - let page = page_number(query.page.as_deref()); | 141 | + let page = requested_page(query.page.as_deref()); |
| 149 | - let sort = sort_key(query.sort.as_deref()); | 142 | + let sort = pick_sort(query.sort.as_deref(), &SORTS); |
| 150 | | 143 | |
| 151 | let owned = RepoScope::OwnedBy(&user.id); | 144 | let owned = RepoScope::OwnedBy(&user.id); |
| 152 | let starred = RepoScope::StarredBy(&user.id); | 145 | let starred = RepoScope::StarredBy(&user.id); |
| @@ -233,8 +226,7 @@ async fn profile_page(cx: &Cx) -> Result<impl View> { |
| 233 | .collect() | 226 | .collect() |
| 234 | }; | 227 | }; |
| 235 | let snippet_total = snippets.len() as u64; | 228 | let snippet_total = snippets.len() as u64; |
| 236 | - let snippet_pages = snippet_total.div_ceil(PER_PAGE).max(1); | 229 | + let (snippets, snippet_page, snippet_pages) = paginate(snippets, page, PER_PAGE); |
| 237 | - let snippet_page = page.min(snippet_pages); | | |
| 238 | let snippet_pager = pager_links(snippet_page, snippet_pages, |n| { | 230 | let snippet_pager = pager_links(snippet_page, snippet_pages, |n| { |
| 239 | profile_href( | 231 | profile_href( |
| 240 | &user.username, | 232 | &user.username, |
| @@ -244,11 +236,6 @@ async fn profile_page(cx: &Cx) -> Result<impl View> { |
| 244 | n, | 236 | n, |
| 245 | ) | 237 | ) |
| 246 | }); | 238 | }); |
| 247 | - let snippets: Vec<ListRow> = snippets | | |
| 248 | - .into_iter() | | |
| 249 | - .skip(((snippet_page - 1) * PER_PAGE) as usize) | | |
| 250 | - .take(PER_PAGE as usize) | | |
| 251 | - .collect(); | | |
| 252 | | 239 | |
| 253 | let (orgs, org_create_allowed) = match actor { | 240 | let (orgs, org_create_allowed) = match actor { |
| 254 | Some(viewer_user) if tab == Tab::Organizations => { | 241 | Some(viewer_user) if tab == Tab::Organizations => { |
| @@ -310,12 +297,7 @@ async fn profile_page(cx: &Cx) -> Result<impl View> { |
| 310 | }) | 297 | }) |
| 311 | .collect(); | 298 | .collect(); |
| 312 | let total = matching.len() as u64; | 299 | let total = matching.len() as u64; |
| 313 | - let page = page.min(total.div_ceil(PER_PAGE).max(1)); | 300 | + let (shown, _, _) = paginate(matching, page, PER_PAGE); |
| 314 | - let shown = matching | | |
| 315 | - .into_iter() | | |
| 316 | - .skip(((page - 1) * PER_PAGE) as usize) | | |
| 317 | - .take(PER_PAGE as usize) | | |
| 318 | - .collect(); | | |
| 319 | (shown, total) | 301 | (shown, total) |
| 320 | }; | 302 | }; |
| 321 | let tz = actor.map_or("UTC", |u| u.timezone.as_str()); | 303 | let tz = actor.map_or("UTC", |u| u.timezone.as_str()); |
| @@ -330,7 +312,7 @@ async fn profile_page(cx: &Cx) -> Result<impl View> { |
| 330 | } else { | 312 | } else { |
| 331 | g::repo_count(lang, total) | 313 | g::repo_count(lang, total) |
| 332 | }; | 314 | }; |
| 333 | - let pages = total.div_ceil(PER_PAGE).max(1); | 315 | + let pages = page_count(total, PER_PAGE); |
| 334 | let page = page.min(pages); | 316 | let page = page.min(pages); |
| 335 | Listing { | 317 | Listing { |
| 336 | rows: listed | 318 | rows: listed |
| @@ -517,10 +499,6 @@ struct Listing { |
| 517 | empty: &'static str, | 499 | empty: &'static str, |
| 518 | } | 500 | } |
| 519 | | 501 | |
| 520 | -fn page_number(raw: Option<&str>) -> u64 { | | |
| 521 | - raw.and_then(|p| p.parse::<u64>().ok()).unwrap_or(1).max(1) | | |
| 522 | -} | | |
| 523 | - | | |
| 524 | fn profile_href(name: &str, tab: &str, finder: &Finder, sort: &str, page: u64) -> String { | 502 | fn profile_href(name: &str, tab: &str, finder: &Finder, sort: &str, page: u64) -> String { |
| 525 | let mut href = format!("/{}?tab={tab}", enc(name)); | 503 | let mut href = format!("/{}?tab={tab}", enc(name)); |
| 526 | if !finder.is_empty() { | 504 | if !finder.is_empty() { |
| @@ -128,9 +128,9 @@ async fn org_pins_save(cx: &Cx, RawForm(raw): RawForm) -> Result<SeeOther> { |
| 128 | | 128 | |
| 129 | #[cfg(test)] | 129 | #[cfg(test)] |
| 130 | mod tests { | 130 | mod tests { |
| | 131 | + use crate::test_support::fixture::{Reply, send_form}; |
| 131 | use forge_core::{Store, Visibility}; | 132 | use forge_core::{Store, Visibility}; |
| 132 | - use topcoat::router::request::Request; | 133 | + use topcoat::router::Router; |
| 133 | - use topcoat::router::{Body, Router, to_bytes}; | | |
| 134 | | 134 | |
| 135 | use crate::auth::SESSION_COOKIE; | 135 | use crate::auth::SESSION_COOKIE; |
| 136 | | 136 | |
| @@ -142,12 +142,6 @@ mod tests { |
| 142 | _dir: tempfile::TempDir, | 142 | _dir: tempfile::TempDir, |
| 143 | } | 143 | } |
| 144 | | 144 | |
| 145 | - struct Reply { | | |
| 146 | - status: u16, | | |
| 147 | - location: Option<String>, | | |
| 148 | - body: String, | | |
| 149 | - } | | |
| 150 | - | | |
| 151 | async fn site() -> Site { | 145 | async fn site() -> Site { |
| 152 | let dir = tempfile::tempdir().expect("tempdir"); | 146 | let dir = tempfile::tempdir().expect("tempdir"); |
| 153 | let state = crate::test_support::test_state(dir.path()).await; | 147 | let state = crate::test_support::test_state(dir.path()).await; |
| @@ -172,30 +166,10 @@ mod tests { |
| 172 | cookie: Option<&str>, | 166 | cookie: Option<&str>, |
| 173 | fields: &[(&str, &str)], | 167 | fields: &[(&str, &str)], |
| 174 | ) -> Reply { | 168 | ) -> Reply { |
| 175 | - let mut builder = Request::builder().method(method).uri(uri); | 169 | + let form = form_urlencoded::Serializer::new(String::new()) |
| 176 | - if let Some(cookie) = cookie { | | |
| 177 | - builder = builder.header("cookie", cookie); | | |
| 178 | - } | | |
| 179 | - let body = form_urlencoded::Serializer::new(String::new()) | | |
| 180 | .extend_pairs(fields) | 170 | .extend_pairs(fields) |
| 181 | .finish(); | 171 | .finish(); |
| 182 | - builder = builder.header("content-type", "application/x-www-form-urlencoded"); | 172 | + send_form(&site.router, method, uri, cookie, Some(form)).await |
| 183 | - let res = site | | |
| 184 | - .router | | |
| 185 | - .handle(builder.body(Body::from(body)).expect("request")) | | |
| 186 | - .await; | | |
| 187 | - let status = res.status().as_u16(); | | |
| 188 | - let location = res | | |
| 189 | - .headers() | | |
| 190 | - .get("location") | | |
| 191 | - .and_then(|v| v.to_str().ok()) | | |
| 192 | - .map(str::to_owned); | | |
| 193 | - let bytes = to_bytes(res.into_body(), usize::MAX).await.expect("body"); | | |
| 194 | - Reply { | | |
| 195 | - status, | | |
| 196 | - location, | | |
| 197 | - body: String::from_utf8_lossy(&bytes).into_owned(), | | |
| 198 | - } | | |
| 199 | } | 173 | } |
| 200 | | 174 | |
| 201 | struct Seed { | 175 | struct Seed { |
| @@ -12,7 +12,10 @@ use topcoat::router::error::{SeeOther, see_other}; |
| 12 | use topcoat::router::{page, route}; | 12 | use topcoat::router::{page, route}; |
| 13 | use topcoat::view::{View, component, view}; | 13 | use topcoat::view::{View, component, view}; |
| 14 | | 14 | |
| 15 | -use crate::accent::{self, custom_id, custom_of, hue_of, preset_accent_hue, preset_base_hue}; | 15 | +use crate::accent::{ |
| | 16 | + self, ACCENT_VIVID, BASE_VIVID, custom_id, custom_of, hue_of, preset_accent_hue, |
| | 17 | + preset_base_hue, |
| | 18 | +}; |
| 16 | use crate::audit::{self, Actor, Target}; | 19 | use crate::audit::{self, Actor, Target}; |
| 17 | use crate::auth::{require_csrf, require_user}; | 20 | use crate::auth::{require_csrf, require_user}; |
| 18 | use crate::custom_colour; | 21 | use crate::custom_colour; |
| @@ -72,9 +75,6 @@ struct Stripe { |
| 72 | hex: String, | 75 | hex: String, |
| 73 | } | 76 | } |
| 74 | | 77 | |
| 75 | -const ACCENT_VIVID: u8 = 50; | | |
| 76 | -const BASE_VIVID: u8 = 30; | | |
| 77 | - | | |
| 78 | fn row_lightness(base: bool, dark: bool) -> f64 { | 78 | fn row_lightness(base: bool, dark: bool) -> f64 { |
| 79 | match (base, dark) { | 79 | match (base, dark) { |
| 80 | (false, true) => 0.75, | 80 | (false, true) => 0.75, |
| @@ -9,7 +9,6 @@ use http::header::{ |
| 9 | }; | 9 | }; |
| 10 | use http_body::Frame; | 10 | use http_body::Frame; |
| 11 | use http_body_util::StreamBody; | 11 | use http_body_util::StreamBody; |
| 12 | -use serde::Deserialize; | | |
| 13 | use tokio_util::io::ReaderStream; | 12 | use tokio_util::io::ReaderStream; |
| 14 | use topcoat::Result; | 13 | use topcoat::Result; |
| 15 | use topcoat::context::{Cx, context}; | 14 | use topcoat::context::{Cx, context}; |
| @@ -19,7 +18,7 @@ use topcoat::router::response::Response; |
| 19 | use topcoat::router::{Body, HeaderMap, StatusCode, page, path_param, query_params, route}; | 18 | use topcoat::router::{Body, HeaderMap, StatusCode, page, path_param, query_params, route}; |
| 20 | use topcoat::view::{View, component, view}; | 19 | use topcoat::view::{View, component, view}; |
| 21 | | 20 | |
| 22 | -use crate::auth::{require_csrf, require_user, two_factor_enabled}; | 21 | +use crate::auth::{CsrfForm, require_csrf, require_user, two_factor_enabled}; |
| 23 | use crate::exporter; | 22 | use crate::exporter; |
| 24 | use crate::i18n::migrate::{self as g, K}; | 23 | use crate::i18n::migrate::{self as g, K}; |
| 25 | use crate::i18n::{self, Key, Lang}; | 24 | use crate::i18n::{self, Key, Lang}; |
| @@ -30,12 +29,6 @@ use crate::views::{alert, csrf_field, human_size, rel_time, shell}; |
| 30 | | 29 | |
| 31 | path_param!(export_id); | 30 | path_param!(export_id); |
| 32 | | 31 | |
| 33 | -#[derive(Deserialize)] | | |
| 34 | -struct CsrfForm { | | |
| 35 | - #[serde(default)] | | |
| 36 | - csrf: String, | | |
| 37 | -} | | |
| 38 | - | | |
| 39 | #[query_params(error = bad_request)] | 32 | #[query_params(error = bad_request)] |
| 40 | struct SeenQuery { | 33 | struct SeenQuery { |
| 41 | v: Option<String>, | 34 | v: Option<String>, |
| @@ -1,8 +1,8 @@ |
| 1 | use forge_core::Store; | 1 | use forge_core::Store; |
| 2 | -use topcoat::router::request::Request; | 2 | +use topcoat::router::Router; |
| 3 | -use topcoat::router::{Body, Router, to_bytes}; | | |
| 4 | | 3 | |
| 5 | use crate::auth::SESSION_COOKIE; | 4 | use crate::auth::SESSION_COOKIE; |
| | 5 | +use crate::test_support::fixture::{Reply, send}; |
| 6 | | 6 | |
| 7 | const CSRF: &str = "gpg-test-csrf"; | 7 | const CSRF: &str = "gpg-test-csrf"; |
| 8 | const TOKEN: &str = "gpg-test-token"; | 8 | const TOKEN: &str = "gpg-test-token"; |
| @@ -15,12 +15,6 @@ struct Site { |
| 15 | _dir: tempfile::TempDir, | 15 | _dir: tempfile::TempDir, |
| 16 | } | 16 | } |
| 17 | | 17 | |
| 18 | -struct Reply { | | |
| 19 | - status: u16, | | |
| 20 | - location: Option<String>, | | |
| 21 | - body: String, | | |
| 22 | -} | | |
| 23 | - | | |
| 24 | async fn site() -> (Site, bool) { | 18 | async fn site() -> (Site, bool) { |
| 25 | let dir = tempfile::tempdir().expect("tempdir"); | 19 | let dir = tempfile::tempdir().expect("tempdir"); |
| 26 | let state = crate::test_support::test_state(dir.path()).await; | 20 | let state = crate::test_support::test_state(dir.path()).await; |
| @@ -49,37 +43,7 @@ async fn call( |
| 49 | cookie: Option<&str>, | 43 | cookie: Option<&str>, |
| 50 | fields: Option<&[(&str, &str)]>, | 44 | fields: Option<&[(&str, &str)]>, |
| 51 | ) -> Reply { | 45 | ) -> Reply { |
| 52 | - let mut builder = Request::builder().method(method).uri(uri); | 46 | + send(&site.router, method, uri, cookie, fields).await |
| 53 | - if let Some(cookie) = cookie { | | |
| 54 | - builder = builder.header("cookie", cookie); | | |
| 55 | - } | | |
| 56 | - let body = match fields { | | |
| 57 | - Some(fields) => { | | |
| 58 | - builder = builder.header("content-type", "application/x-www-form-urlencoded"); | | |
| 59 | - Body::from( | | |
| 60 | - form_urlencoded::Serializer::new(String::new()) | | |
| 61 | - .extend_pairs(fields) | | |
| 62 | - .finish(), | | |
| 63 | - ) | | |
| 64 | - } | | |
| 65 | - None => Body::empty(), | | |
| 66 | - }; | | |
| 67 | - let res = site | | |
| 68 | - .router | | |
| 69 | - .handle(builder.body(body).expect("request")) | | |
| 70 | - .await; | | |
| 71 | - let status = res.status().as_u16(); | | |
| 72 | - let location = res | | |
| 73 | - .headers() | | |
| 74 | - .get("location") | | |
| 75 | - .and_then(|v| v.to_str().ok()) | | |
| 76 | - .map(str::to_owned); | | |
| 77 | - let bytes = to_bytes(res.into_body(), usize::MAX).await.expect("body"); | | |
| 78 | - Reply { | | |
| 79 | - status, | | |
| 80 | - location, | | |
| 81 | - body: String::from_utf8_lossy(&bytes).into_owned(), | | |
| 82 | - } | | |
| 83 | } | 47 | } |
| 84 | | 48 | |
| 85 | #[tokio::test] | 49 | #[tokio::test] |
| @@ -16,7 +16,7 @@ use topcoat::router::{BodyLimit, page, query_params, route}; |
| 16 | use topcoat::view::{View, component, view}; | 16 | use topcoat::view::{View, component, view}; |
| 17 | | 17 | |
| 18 | use crate::audit::{self, Actor, Target}; | 18 | use crate::audit::{self, Actor, Target}; |
| 19 | -use crate::auth::{require_csrf, require_user}; | 19 | +use crate::auth::{CsrfForm, require_csrf, require_user}; |
| 20 | use crate::i18n::{self, Key, Lang, about_too_long, display_name_too_long, t}; | 20 | use crate::i18n::{self, Key, Lang, about_too_long, display_name_too_long, t}; |
| 21 | use crate::live::Topic; | 21 | use crate::live::Topic; |
| 22 | use crate::state::AppState; | 22 | use crate::state::AppState; |
| @@ -46,12 +46,6 @@ struct ProfileForm { |
| 46 | timezone: String, | 46 | timezone: String, |
| 47 | } | 47 | } |
| 48 | | 48 | |
| 49 | -#[derive(Deserialize)] | | |
| 50 | -struct CsrfForm { | | |
| 51 | - #[serde(default)] | | |
| 52 | - csrf: String, | | |
| 53 | -} | | |
| 54 | - | | |
| 55 | struct Draft { | 49 | struct Draft { |
| 56 | display_name: String, | 50 | display_name: String, |
| 57 | username: String, | 51 | username: String, |
| @@ -15,7 +15,7 @@ use topcoat::view::{View, component, view}; |
| 15 | | 15 | |
| 16 | use crate::audit::{self, Actor, Target}; | 16 | use crate::audit::{self, Actor, Target}; |
| 17 | use crate::auth::{ | 17 | use crate::auth::{ |
| 18 | - hash_password_async, logout, require_csrf, require_user, two_factor_enabled, | 18 | + CsrfForm, hash_password_async, logout, require_csrf, require_user, two_factor_enabled, |
| 19 | verify_password_async, verify_second_factor, | 19 | verify_password_async, verify_second_factor, |
| 20 | }; | 20 | }; |
| 21 | use crate::i18n::packages::{self as pk, K as PK}; | 21 | use crate::i18n::packages::{self as pk, K as PK}; |
| @@ -41,12 +41,6 @@ struct SecurityQuery { |
| 41 | part: Option<String>, | 41 | part: Option<String>, |
| 42 | } | 42 | } |
| 43 | | 43 | |
| 44 | -#[derive(Deserialize)] | | |
| 45 | -struct CsrfForm { | | |
| 46 | - #[serde(default)] | | |
| 47 | - csrf: String, | | |
| 48 | -} | | |
| 49 | - | | |
| 50 | #[derive(Deserialize)] | 44 | #[derive(Deserialize)] |
| 51 | struct PasswordForm { | 45 | struct PasswordForm { |
| 52 | #[serde(default)] | 46 | #[serde(default)] |
| @@ -846,7 +840,7 @@ async fn two_factor_confirm(cx: &Cx, Form(form): Form<EnrollForm>) -> Result<imp |
| 846 | match totp::verify( | 840 | match totp::verify( |
| 847 | &shared, | 841 | &shared, |
| 848 | form.code.trim(), | 842 | form.code.trim(), |
| 849 | - totp::step_for(forge_core::time::unix_now()), | 843 | + totp::step_for(forge_core::time::now_unix()), |
| 850 | totp_state.last_step, | 844 | totp_state.last_step, |
| 851 | ) { | 845 | ) { |
| 852 | Some(step) => { | 846 | Some(step) => { |
| @@ -1002,25 +996,20 @@ async fn two_factor_recovery(cx: &Cx, Form(form): Form<CodeForm>) -> Result<impl |
| 1002 | | 996 | |
| 1003 | #[cfg(test)] | 997 | #[cfg(test)] |
| 1004 | mod tests { | 998 | mod tests { |
| 1005 | - use std::sync::Arc; | | |
| 1006 | - | | |
| 1007 | use forge_core::time::stamp_after; | 999 | use forge_core::time::stamp_after; |
| 1008 | use forge_core::token::hash_token; | 1000 | use forge_core::token::hash_token; |
| 1009 | - use forge_core::{Config, Registration, Store, User, secret, totp}; | 1001 | + use forge_core::{User, secret, totp}; |
| 1010 | - use forge_git::GitEnv; | | |
| 1011 | - use topcoat::cookie::CookieLayer; | | |
| 1012 | use topcoat::router::request::Request; | 1002 | use topcoat::router::request::Request; |
| 1013 | - use topcoat::router::{Body, Router, RouterBuilderDiscoverExt, to_bytes}; | 1003 | + use topcoat::router::{Body, Router, to_bytes}; |
| 1014 | | 1004 | |
| 1015 | use crate::auth::{SESSION_COOKIE, hash_password_async}; | 1005 | use crate::auth::{SESSION_COOKIE, hash_password_async}; |
| 1016 | use crate::state::AppState; | 1006 | use crate::state::AppState; |
| 1017 | - use crate::throttle::{LOGIN_USER_LIMIT, Throttle, user_key}; | 1007 | + use crate::throttle::{LOGIN_USER_LIMIT, user_key}; |
| 1018 | | 1008 | |
| 1019 | const TOKEN: &str = "security-test-session"; | 1009 | const TOKEN: &str = "security-test-session"; |
| 1020 | const OTHER_TOKEN: &str = "security-test-other-session"; | 1010 | const OTHER_TOKEN: &str = "security-test-other-session"; |
| 1021 | const CSRF: &str = "security-test-csrf"; | 1011 | const CSRF: &str = "security-test-csrf"; |
| 1022 | const PASSWORD: &str = "current password 1"; | 1012 | const PASSWORD: &str = "current password 1"; |
| 1023 | - const KEY: [u8; 32] = [7u8; 32]; | | |
| 1024 | | 1013 | |
| 1025 | struct Fixture { | 1014 | struct Fixture { |
| 1026 | router: Router, | 1015 | router: Router, |
| @@ -1031,81 +1020,15 @@ mod tests { |
| 1031 | | 1020 | |
| 1032 | async fn fixture() -> Fixture { | 1021 | async fn fixture() -> Fixture { |
| 1033 | let dir = tempfile::tempdir().unwrap(); | 1022 | let dir = tempfile::tempdir().unwrap(); |
| 1034 | - let path = dir.path().to_path_buf(); | 1023 | + let state = crate::test_support::test_state(dir.path()).await; |
| 1035 | - let store = Store::open(&path.join("forge.db")).await.unwrap(); | | |
| 1036 | - let config = Config { | | |
| 1037 | - database: path.join("forge.db"), | | |
| 1038 | - data_dir: path.clone(), | | |
| 1039 | - listen: "127.0.0.1:7660".parse().unwrap(), | | |
| 1040 | - base_url: "https://forge.test/".into(), | | |
| 1041 | - user_content_base_url: "https://forge.test".into(), | | |
| 1042 | - ssh_listen: "127.0.0.1:2222".parse().unwrap(), | | |
| 1043 | - user_content_listen: "127.0.0.1:7661".parse().unwrap(), | | |
| 1044 | - ssh_public_host: "forge.test".into(), | | |
| 1045 | - ssh_public_port: 22, | | |
| 1046 | - registration: Registration::Closed, | | |
| 1047 | - trusted_proxies: Vec::new(), | | |
| 1048 | - webhooks: Default::default(), | | |
| 1049 | - backup: Default::default(), | | |
| 1050 | - releases: Default::default(), | | |
| 1051 | - storage: Default::default(), | | |
| 1052 | - replication: Default::default(), | | |
| 1053 | - lfs: Default::default(), | | |
| 1054 | - ci: Default::default(), | | |
| 1055 | - advisories: Default::default(), | | |
| 1056 | - mail: Default::default(), | | |
| 1057 | - orgs: Default::default(), | | |
| 1058 | - self_update: Default::default(), | | |
| 1059 | - banner: Default::default(), | | |
| 1060 | - alerts: Default::default(), | | |
| 1061 | - mirrors: Default::default(), | | |
| 1062 | - ssh_auth_rejection_secs: 1, | | |
| 1063 | - }; | | |
| 1064 | - let config = Arc::new(config); | | |
| 1065 | - let state = AppState { | | |
| 1066 | - settings: crate::state::settings_for(&config), | | |
| 1067 | - config, | | |
| 1068 | - store: store.clone(), | | |
| 1069 | - git: Arc::new(GitEnv { | | |
| 1070 | - git_bin: "git".into(), | | |
| 1071 | - data_dir: path.clone(), | | |
| 1072 | - }), | | |
| 1073 | - key: Arc::new(KEY), | | |
| 1074 | - internal_token: Arc::from("test-token"), | | |
| 1075 | - admin_token: Arc::from("test-admin-token"), | | |
| 1076 | - jobs: Arc::new(crate::backup::Jobs::default()), | | |
| 1077 | - internal_socket: path.join("internal.sock"), | | |
| 1078 | - throttle: Arc::new(Throttle::default()), | | |
| 1079 | - webhook_waker: Arc::new(tokio::sync::Notify::new()), | | |
| 1080 | - mirror_waker: Arc::new(tokio::sync::Notify::new()), | | |
| 1081 | - blobs: crate::blobs::BlobStore::open(&path.join("blobs")).expect("blob store"), | | |
| 1082 | - replication: Arc::new(crate::replication::ReplicationQueue::default()), | | |
| 1083 | - ci_waker: Arc::new(tokio::sync::Notify::new()), | | |
| 1084 | - mailer: Arc::new(crate::mail::FakeMailer::default()), | | |
| 1085 | - mail_waker: Arc::new(tokio::sync::Notify::new()), | | |
| 1086 | - notify_hub: Arc::new(crate::notify_hub::NotifyHub::new()), | | |
| 1087 | - ci_live: Arc::new(crate::ci::CiLive::default()), | | |
| 1088 | - runner_logs: Arc::new(crate::ci::runner_log::RunnerLogs::default()), | | |
| 1089 | - runner_metrics: Arc::new(crate::ci::runner_metrics::RunnerMetrics::default()), | | |
| 1090 | - live: Arc::new(crate::live::LiveHub::default()), | | |
| 1091 | - push_live: Arc::new(crate::web_push::PushLive::default()), | | |
| 1092 | - packages_live: Arc::new(crate::packages_live::PackagesLive::default()), | | |
| 1093 | - }; | | |
| 1094 | let hash = hash_password_async(PASSWORD.into()).await.unwrap(); | 1024 | let hash = hash_password_async(PASSWORD.into()).await.unwrap(); |
| 1095 | - let user = store | 1025 | + let user = state |
| | 1026 | + .store |
| 1096 | .create_user("tahinli", None, &hash, false) | 1027 | .create_user("tahinli", None, &hash, false) |
| 1097 | .await | 1028 | .await |
| 1098 | .unwrap(); | 1029 | .unwrap(); |
| 1099 | - let expiry = stamp_after(std::time::Duration::from_secs(3600)); | 1030 | + crate::test_support::create_session(&state.store, &user.id, TOKEN, CSRF).await; |
| 1100 | - store | 1031 | + let router = crate::test_support::app_router(state.clone()); |
| 1101 | - .create_session(&user.id, &hash_token(TOKEN), CSRF, &expiry, None, None) | | |
| 1102 | - .await | | |
| 1103 | - .unwrap(); | | |
| 1104 | - let router = Router::builder() | | |
| 1105 | - .discover() | | |
| 1106 | - .layer(CookieLayer::new()) | | |
| 1107 | - .with(state.clone()) | | |
| 1108 | - .build(); | | |
| 1109 | Fixture { | 1032 | Fixture { |
| 1110 | router, | 1033 | router, |
| 1111 | state, | 1034 | state, |
| @@ -1146,12 +1069,12 @@ mod tests { |
| 1146 | } | 1069 | } |
| 1147 | | 1070 | |
| 1148 | fn now_code(shared: &[u8]) -> String { | 1071 | fn now_code(shared: &[u8]) -> String { |
| 1149 | - totp::code_at(shared, totp::step_for(forge_core::time::unix_now())) | 1072 | + totp::code_at(shared, totp::step_for(forge_core::time::now_unix())) |
| 1150 | } | 1073 | } |
| 1151 | | 1074 | |
| 1152 | async fn enable_totp_directly(fx: &Fixture) -> Vec<u8> { | 1075 | async fn enable_totp_directly(fx: &Fixture) -> Vec<u8> { |
| 1153 | let shared = totp::new_secret(); | 1076 | let shared = totp::new_secret(); |
| 1154 | - let sealed = secret::seal(&KEY, &shared).unwrap(); | 1077 | + let sealed = secret::seal(&fx.state.key, &shared).unwrap(); |
| 1155 | fx.state | 1078 | fx.state |
| 1156 | .store | 1079 | .store |
| 1157 | .set_totp_secret(&fx.user.id, &sealed) | 1080 | .set_totp_secret(&fx.user.id, &sealed) |
| @@ -1466,7 +1389,7 @@ mod tests { |
| 1466 | .unwrap(); | 1389 | .unwrap(); |
| 1467 | assert!(!pending.enabled); | 1390 | assert!(!pending.enabled); |
| 1468 | let sealed = pending.sealed_secret.expect("secret stored"); | 1391 | let sealed = pending.sealed_secret.expect("secret stored"); |
| 1469 | - let shared = secret::open(&KEY, &sealed).unwrap(); | 1392 | + let shared = secret::open(&fx.state.key, &sealed).unwrap(); |
| 1470 | | 1393 | |
| 1471 | let page = send(&fx.router, "GET", "/settings/security", true, "").await; | 1394 | let page = send(&fx.router, "GET", "/settings/security", true, "").await; |
| 1472 | assert!( | 1395 | assert!( |
| @@ -1591,7 +1514,7 @@ mod tests { |
| 1591 | .enabled | 1514 | .enabled |
| 1592 | ); | 1515 | ); |
| 1593 | | 1516 | |
| 1594 | - let next = totp::code_at(&shared, totp::step_for(forge_core::time::unix_now()) + 1); | 1517 | + let next = totp::code_at(&shared, totp::step_for(forge_core::time::now_unix()) + 1); |
| 1595 | let disable = format!("csrf={CSRF}¤t_password={PASSWORD}&code={next}"); | 1518 | let disable = format!("csrf={CSRF}¤t_password={PASSWORD}&code={next}"); |
| 1596 | let reply = send( | 1519 | let reply = send( |
| 1597 | &fx.router, | 1520 | &fx.router, |
| @@ -7,7 +7,7 @@ use topcoat::router::error::{SeeOther, see_other}; |
| 7 | use topcoat::router::route; | 7 | use topcoat::router::route; |
| 8 | | 8 | |
| 9 | use crate::audit::{self, Actor, Target}; | 9 | use crate::audit::{self, Actor, Target}; |
| 10 | -use crate::auth::{logout, require_csrf, require_user}; | 10 | +use crate::auth::{CsrfForm, logout, require_csrf, require_user}; |
| 11 | use crate::i18n::{Key, Lang, t}; | 11 | use crate::i18n::{Key, Lang, t}; |
| 12 | use crate::state::AppState; | 12 | use crate::state::AppState; |
| 13 | use crate::web_push::agent_label_in; | 13 | use crate::web_push::agent_label_in; |
| @@ -20,12 +20,6 @@ struct RevokeForm { |
| 20 | id: String, | 20 | id: String, |
| 21 | } | 21 | } |
| 22 | | 22 | |
| 23 | -#[derive(Deserialize)] | | |
| 24 | -struct CsrfForm { | | |
| 25 | - #[serde(default)] | | |
| 26 | - csrf: String, | | |
| 27 | -} | | |
| 28 | - | | |
| 29 | pub(crate) fn session_label(lang: Lang, session: &Session) -> String { | 23 | pub(crate) fn session_label(lang: Lang, session: &Session) -> String { |
| 30 | session.user_agent.as_deref().map_or_else( | 24 | session.user_agent.as_deref().map_or_else( |
| 31 | || t(lang, Key::UnknownBrowser).to_owned(), | 25 | || t(lang, Key::UnknownBrowser).to_owned(), |
| @@ -586,9 +586,9 @@ async fn snippet_create(cx: &Cx, Form(form): Form<HashMap<String, String>>) -> R |
| 586 | if step.is_none() { | 586 | if step.is_none() { |
| 587 | let store = &context::<AppState>(cx).store; | 587 | let store = &context::<AppState>(cx).store; |
| 588 | let files = draft.saved_files(); | 588 | let files = draft.saved_files(); |
| 589 | - let saved = match SnippetVisibility::parse(&draft.visibility) { | 589 | + let saved = match draft.visibility.parse::<SnippetVisibility>() { |
| 590 | - None => Err(g::t(lang, K::ChooseVisibility).to_owned()), | 590 | + Err(_) => Err(g::t(lang, K::ChooseVisibility).to_owned()), |
| 591 | - Some(visibility) => match store | 591 | + Ok(visibility) => match store |
| 592 | .create_snippet( | 592 | .create_snippet( |
| 593 | &user.id, | 593 | &user.id, |
| 594 | &draft.title, | 594 | &draft.title, |
| @@ -675,9 +675,9 @@ async fn snippet_update(cx: &Cx, Form(form): Form<HashMap<String, String>>) -> R |
| 675 | if step.is_none() { | 675 | if step.is_none() { |
| 676 | let store = &context::<AppState>(cx).store; | 676 | let store = &context::<AppState>(cx).store; |
| 677 | let files = draft.saved_files(); | 677 | let files = draft.saved_files(); |
| 678 | - let saved = match SnippetVisibility::parse(&draft.visibility) { | 678 | + let saved = match draft.visibility.parse::<SnippetVisibility>() { |
| 679 | - None => Err(g::t(lang, K::ChooseVisibility).to_owned()), | 679 | + Err(_) => Err(g::t(lang, K::ChooseVisibility).to_owned()), |
| 680 | - Some(visibility) => match store | 680 | + Ok(visibility) => match store |
| 681 | .update_snippet( | 681 | .update_snippet( |
| 682 | &user.id, | 682 | &user.id, |
| 683 | &snippet_id, | 683 | &snippet_id, |
| @@ -1,11 +1,15 @@ |
| 1 | use std::sync::OnceLock; | 1 | use std::sync::OnceLock; |
| 2 | use std::sync::atomic::{AtomicBool, Ordering}; | 2 | use std::sync::atomic::{AtomicBool, Ordering}; |
| 3 | | 3 | |
| 4 | -use forge_core::alerts::{self, AlertKind}; | 4 | +use forge_core::alerts::{self, AlertKind, AlertTopic}; |
| 5 | use forge_core::mail::{MailKind, OutgoingMail}; | 5 | use forge_core::mail::{MailKind, OutgoingMail}; |
| 6 | use forge_core::store::backup_runs::RunKind; | 6 | use forge_core::store::backup_runs::RunKind; |
| | 7 | +use forge_core::store::replication::{ |
| | 8 | + DB_SUBJECT, ReplicationHealth, replication_health, window_secs, |
| | 9 | +}; |
| 7 | use forge_core::time::stamp_to_unix; | 10 | use forge_core::time::stamp_to_unix; |
| 8 | | 11 | |
| | 12 | +use crate::backup::scheduler::BackupSetError; |
| 9 | use crate::i18n::{self, alerts as text}; | 13 | use crate::i18n::{self, alerts as text}; |
| 10 | use crate::mail; | 14 | use crate::mail; |
| 11 | use crate::notify_hub::publish_unread; | 15 | use crate::notify_hub::publish_unread; |
| @@ -19,77 +23,11 @@ fn started() -> i64 { |
| 19 | *STARTED.get_or_init(now_unix) | 23 | *STARTED.get_or_init(now_unix) |
| 20 | } | 24 | } |
| 21 | | 25 | |
| 22 | -#[derive(Clone, Copy, PartialEq, Eq)] | | |
| 23 | -pub enum AlertTopic { | | |
| 24 | - RunnerOffline, | | |
| 25 | - BackupFailed, | | |
| 26 | - BackupVerifyFailed, | | |
| 27 | - BackupOverdue, | | |
| 28 | - FsckFailed, | | |
| 29 | - DiskLow, | | |
| 30 | - CiKilled, | | |
| 31 | - SelfUpdateRestart, | | |
| 32 | - SelfUpdateFailed, | | |
| 33 | - Replication, | | |
| 34 | -} | | |
| 35 | - | | |
| 36 | -impl AlertTopic { | | |
| 37 | - const ALL: [Self; 10] = [ | | |
| 38 | - Self::RunnerOffline, | | |
| 39 | - Self::BackupFailed, | | |
| 40 | - Self::BackupVerifyFailed, | | |
| 41 | - Self::BackupOverdue, | | |
| 42 | - Self::FsckFailed, | | |
| 43 | - Self::DiskLow, | | |
| 44 | - Self::CiKilled, | | |
| 45 | - Self::SelfUpdateRestart, | | |
| 46 | - Self::SelfUpdateFailed, | | |
| 47 | - Self::Replication, | | |
| 48 | - ]; | | |
| 49 | - | | |
| 50 | - fn as_str(self) -> &'static str { | | |
| 51 | - match self { | | |
| 52 | - Self::RunnerOffline => "runner_offline", | | |
| 53 | - Self::BackupFailed => "backup_failed", | | |
| 54 | - Self::BackupVerifyFailed => "backup_verify_failed", | | |
| 55 | - Self::BackupOverdue => "backup_overdue", | | |
| 56 | - Self::FsckFailed => "fsck_failed", | | |
| 57 | - Self::DiskLow => "disk_low", | | |
| 58 | - Self::CiKilled => "ci_killed", | | |
| 59 | - Self::SelfUpdateRestart => "self_update_restart", | | |
| 60 | - Self::SelfUpdateFailed => "self_update_failed", | | |
| 61 | - Self::Replication => "replication", | | |
| 62 | - } | | |
| 63 | - } | | |
| 64 | - | | |
| 65 | - fn parse(stored: &str) -> Option<Self> { | | |
| 66 | - Self::ALL.into_iter().find(|t| t.as_str() == stored) | | |
| 67 | - } | | |
| 68 | - | | |
| 69 | - fn kind(self) -> AlertKind { | | |
| 70 | - match self { | | |
| 71 | - Self::RunnerOffline => AlertKind::RunnerOffline, | | |
| 72 | - Self::BackupFailed | | |
| 73 | - | Self::BackupVerifyFailed | | |
| 74 | - | Self::BackupOverdue | | |
| 75 | - | Self::FsckFailed => AlertKind::Backup, | | |
| 76 | - Self::DiskLow => AlertKind::Disk, | | |
| 77 | - Self::CiKilled => AlertKind::CiKilled, | | |
| 78 | - Self::SelfUpdateRestart | Self::SelfUpdateFailed => AlertKind::SelfUpdate, | | |
| 79 | - Self::Replication => AlertKind::Replication, | | |
| 80 | - } | | |
| 81 | - } | | |
| 82 | -} | | |
| 83 | - | | |
| 84 | pub async fn raise(state: &AppState, topic: AlertTopic, key: &str, subject: &str, detail: &str) { | 26 | pub async fn raise(state: &AppState, topic: AlertTopic, key: &str, subject: &str, detail: &str) { |
| 85 | if !state.live().alerts.kind_enabled(topic.kind()) { | 27 | if !state.live().alerts.kind_enabled(topic.kind()) { |
| 86 | return; | 28 | return; |
| 87 | } | 29 | } |
| 88 | - match state | 30 | + match state.store.raise_alert(key, topic, subject, detail).await { |
| 89 | - .store | | |
| 90 | - .raise_alert(key, topic.as_str(), subject, detail) | | |
| 91 | - .await | | |
| 92 | - { | | |
| 93 | Ok(true) => { | 31 | Ok(true) => { |
| 94 | if topic == AlertTopic::RunnerOffline { | 32 | if topic == AlertTopic::RunnerOffline { |
| 95 | OFFLINE_ACTIVE.store(true, Ordering::Relaxed); | 33 | OFFLINE_ACTIVE.store(true, Ordering::Relaxed); |
| @@ -105,12 +43,8 @@ pub async fn resolve(state: &AppState, key: &str) { |
| 105 | match state.store.resolve_alert(key).await { | 43 | match state.store.resolve_alert(key).await { |
| 106 | Ok(Some(alert)) => { | 44 | Ok(Some(alert)) => { |
| 107 | crate::live::admin().bump(&crate::live::Topic::AdminHealth); | 45 | crate::live::admin().bump(&crate::live::Topic::AdminHealth); |
| 108 | - let Some(topic) = AlertTopic::parse(&alert.kind) else { | 46 | + if state.live().alerts.kind_enabled(alert.kind.kind()) { |
| 109 | - tracing::error!(key, kind = %alert.kind, "alerts: resolved an unknown topic"); | 47 | + deliver(state, key, alert.kind, &alert.subject, &alert.detail, true).await; |
| 110 | - return; | | |
| 111 | - }; | | |
| 112 | - if state.live().alerts.kind_enabled(topic.kind()) { | | |
| 113 | - deliver(state, key, topic, &alert.subject, &alert.detail, true).await; | | |
| 114 | } | 48 | } |
| 115 | } | 49 | } |
| 116 | Ok(None) => {} | 50 | Ok(None) => {} |
| @@ -124,7 +58,7 @@ pub async fn event(state: &AppState, topic: AlertTopic, key: &str, subject: &str |
| 124 | } | 58 | } |
| 125 | match state | 59 | match state |
| 126 | .store | 60 | .store |
| 127 | - .record_alert_event(key, topic.as_str(), subject, detail) | 61 | + .record_alert_event(key, topic, subject, detail) |
| 128 | .await | 62 | .await |
| 129 | { | 63 | { |
| 130 | Ok(true) => deliver(state, key, topic, subject, detail, false).await, | 64 | Ok(true) => deliver(state, key, topic, subject, detail, false).await, |
| @@ -155,7 +89,7 @@ async fn deliver( |
| 155 | for admin in admins.into_iter().filter(|u| !u.is_org()) { | 89 | for admin in admins.into_iter().filter(|u| !u.is_org()) { |
| 156 | if let Err(e) = state | 90 | if let Err(e) = state |
| 157 | .store | 91 | .store |
| 158 | - .add_admin_notice(&admin.id, key, topic.as_str(), subject, detail, resolved) | 92 | + .add_admin_notice(&admin.id, key, topic, subject, detail, resolved) |
| 159 | .await | 93 | .await |
| 160 | { | 94 | { |
| 161 | tracing::error!(error = %e, key, "alerts: writing an inbox row failed"); | 95 | tracing::error!(error = %e, key, "alerts: writing an inbox row failed"); |
| @@ -185,10 +119,10 @@ async fn deliver( |
| 185 | } | 119 | } |
| 186 | } | 120 | } |
| 187 | let lang = i18n::resolve(Some(admin.language.as_str()), &http::HeaderMap::new()); | 121 | let lang = i18n::resolve(Some(admin.language.as_str()), &http::HeaderMap::new()); |
| 188 | - let title = text::title(lang, topic.as_str(), subject, resolved); | 122 | + let title = text::title(lang, topic, subject, resolved); |
| 189 | let body = text::mail_body( | 123 | let body = text::mail_body( |
| 190 | lang, | 124 | lang, |
| 191 | - &text::body(lang, topic.as_str(), subject, detail, resolved), | 125 | + &text::body(lang, topic, subject, detail, resolved), |
| 192 | &format!("{base}/admin/health"), | 126 | &format!("{base}/admin/health"), |
| 193 | &format!("{base}/admin/server?tab=alerts"), | 127 | &format!("{base}/admin/server?tab=alerts"), |
| 194 | ); | 128 | ); |
| @@ -217,7 +151,11 @@ pub async fn runner_seen(state: &AppState, runner_id: &str) { |
| 217 | return; | 151 | return; |
| 218 | } | 152 | } |
| 219 | resolve(state, &format!("runner_offline:{runner_id}")).await; | 153 | resolve(state, &format!("runner_offline:{runner_id}")).await; |
| 220 | - match state.store.active_alert_keys("runner_offline").await { | 154 | + match state |
| | 155 | + .store |
| | 156 | + .active_alert_keys(AlertTopic::RunnerOffline) |
| | 157 | + .await |
| | 158 | + { |
| 221 | Ok(keys) if keys.is_empty() => OFFLINE_ACTIVE.store(false, Ordering::Relaxed), | 159 | Ok(keys) if keys.is_empty() => OFFLINE_ACTIVE.store(false, Ordering::Relaxed), |
| 222 | Ok(_) => {} | 160 | Ok(_) => {} |
| 223 | Err(e) => tracing::error!(error = %e, "alerts: reading the active alerts failed"), | 161 | Err(e) => tracing::error!(error = %e, "alerts: reading the active alerts failed"), |
| @@ -255,28 +193,36 @@ pub async fn job_ended( |
| 255 | .await; | 193 | .await; |
| 256 | } | 194 | } |
| 257 | | 195 | |
| 258 | -pub async fn backup_finished(state: &AppState, outcome: Result<(), &str>) { | 196 | +pub async fn backup_finished(state: &AppState, outcome: Result<(), &BackupSetError>) { |
| 259 | match outcome { | 197 | match outcome { |
| 260 | Ok(()) => { | 198 | Ok(()) => { |
| 261 | - resolve(state, "backup_failed").await; | 199 | + resolve(state, AlertTopic::BackupFailed.as_str()).await; |
| 262 | - resolve(state, "backup_verify_failed").await; | 200 | + resolve(state, AlertTopic::BackupVerifyFailed.as_str()).await; |
| 263 | - resolve(state, "backup_overdue").await; | 201 | + resolve(state, AlertTopic::BackupOverdue.as_str()).await; |
| 264 | } | 202 | } |
| 265 | - Err(error) => { | 203 | + Err(failure) => { |
| 266 | - let topic = if error.contains("failed verification") { | 204 | + let (topic, error) = match failure { |
| 267 | - AlertTopic::BackupVerifyFailed | 205 | + BackupSetError::Failed(error) => (AlertTopic::BackupFailed, error), |
| 268 | - } else { | 206 | + BackupSetError::Verify(error) => (AlertTopic::BackupVerifyFailed, error), |
| 269 | - AlertTopic::BackupFailed | | |
| 270 | }; | 207 | }; |
| 271 | - raise(state, topic, topic.as_str(), "", error).await; | 208 | + raise(state, topic, topic.as_str(), "", &error.to_string()).await; |
| 272 | } | 209 | } |
| 273 | } | 210 | } |
| 274 | } | 211 | } |
| 275 | | 212 | |
| 276 | pub async fn fsck_finished(state: &AppState, outcome: Result<(), &str>) { | 213 | pub async fn fsck_finished(state: &AppState, outcome: Result<(), &str>) { |
| 277 | match outcome { | 214 | match outcome { |
| 278 | - Ok(()) => resolve(state, "fsck_failed").await, | 215 | + Ok(()) => resolve(state, AlertTopic::FsckFailed.as_str()).await, |
| 279 | - Err(error) => raise(state, AlertTopic::FsckFailed, "fsck_failed", "", error).await, | 216 | + Err(error) => { |
| | 217 | + raise( |
| | 218 | + state, |
| | 219 | + AlertTopic::FsckFailed, |
| | 220 | + AlertTopic::FsckFailed.as_str(), |
| | 221 | + "", |
| | 222 | + error, |
| | 223 | + ) |
| | 224 | + .await |
| | 225 | + } |
| 280 | } | 226 | } |
| 281 | } | 227 | } |
| 282 | | 228 | |
| @@ -284,7 +230,7 @@ pub async fn self_update_deployed(state: &AppState, version: &str) { |
| 284 | raise( | 230 | raise( |
| 285 | state, | 231 | state, |
| 286 | AlertTopic::SelfUpdateRestart, | 232 | AlertTopic::SelfUpdateRestart, |
| 287 | - "self_update_restart", | 233 | + AlertTopic::SelfUpdateRestart.as_str(), |
| 288 | version, | 234 | version, |
| 289 | "", | 235 | "", |
| 290 | ) | 236 | ) |
| @@ -304,11 +250,18 @@ pub async fn self_update_failed(state: &AppState, run_id: &str, error: &str) { |
| 304 | | 250 | |
| 305 | pub async fn on_boot(state: &AppState) { | 251 | pub async fn on_boot(state: &AppState) { |
| 306 | started(); | 252 | started(); |
| 307 | - match state.store.active_alert_keys("runner_offline").await { | 253 | + match state |
| | 254 | + .store |
| | 255 | + .active_alert_keys(AlertTopic::RunnerOffline) |
| | 256 | + .await |
| | 257 | + { |
| 308 | Ok(keys) => OFFLINE_ACTIVE.store(!keys.is_empty(), Ordering::Relaxed), | 258 | Ok(keys) => OFFLINE_ACTIVE.store(!keys.is_empty(), Ordering::Relaxed), |
| 309 | Err(e) => tracing::error!(error = %e, "alerts: reading the active alerts failed"), | 259 | Err(e) => tracing::error!(error = %e, "alerts: reading the active alerts failed"), |
| 310 | } | 260 | } |
| 311 | - if let Ok(Some(alert)) = state.store.resolve_alert("self_update_restart").await | 261 | + if let Ok(Some(alert)) = state |
| | 262 | + .store |
| | 263 | + .resolve_alert(AlertTopic::SelfUpdateRestart.as_str()) |
| | 264 | + .await |
| 312 | && state.live().alerts.kind_enabled(AlertKind::SelfUpdate) | 265 | && state.live().alerts.kind_enabled(AlertKind::SelfUpdate) |
| 313 | { | 266 | { |
| 314 | { | 267 | { |
| @@ -317,7 +270,7 @@ pub async fn on_boot(state: &AppState) { |
| 317 | .unwrap_or(alert.subject.clone()); | 270 | .unwrap_or(alert.subject.clone()); |
| 318 | deliver( | 271 | deliver( |
| 319 | state, | 272 | state, |
| 320 | - "self_update_restart", | 273 | + AlertTopic::SelfUpdateRestart.as_str(), |
| 321 | AlertTopic::SelfUpdateRestart, | 274 | AlertTopic::SelfUpdateRestart, |
| 322 | &version, | 275 | &version, |
| 323 | "", | 276 | "", |
| @@ -359,7 +312,11 @@ pub async fn check_runners(state: &AppState, now: i64) { |
| 359 | let since = seen.map_or_else(String::new, |t| forge_core::tz::format_in_tz(t, "UTC")); | 312 | let since = seen.map_or_else(String::new, |t| forge_core::tz::format_in_tz(t, "UTC")); |
| 360 | raise(state, AlertTopic::RunnerOffline, &key, &runner.name, &since).await; | 313 | raise(state, AlertTopic::RunnerOffline, &key, &runner.name, &since).await; |
| 361 | } | 314 | } |
| 362 | - match state.store.active_alert_keys("runner_offline").await { | 315 | + match state |
| | 316 | + .store |
| | 317 | + .active_alert_keys(AlertTopic::RunnerOffline) |
| | 318 | + .await |
| | 319 | + { |
| 363 | Ok(active) => { | 320 | Ok(active) => { |
| 364 | for key in active.into_iter().filter(|k| !offline.contains(k)) { | 321 | for key in active.into_iter().filter(|k| !offline.contains(k)) { |
| 365 | resolve(state, &key).await; | 322 | resolve(state, &key).await; |
| @@ -392,7 +349,7 @@ async fn check_disk(state: &AppState) { |
| 392 | let live = state.live(); | 349 | let live = state.live(); |
| 393 | let cfg = &live.alerts; | 350 | let cfg = &live.alerts; |
| 394 | if !cfg.kind_enabled(AlertKind::Disk) { | 351 | if !cfg.kind_enabled(AlertKind::Disk) { |
| 395 | - resolve(state, "disk_low").await; | 352 | + resolve(state, AlertTopic::DiskLow.as_str()).await; |
| 396 | return; | 353 | return; |
| 397 | } | 354 | } |
| 398 | let dir = live.data_dir.clone(); | 355 | let dir = live.data_dir.clone(); |
| @@ -416,20 +373,20 @@ async fn check_disk(state: &AppState) { |
| 416 | raise( | 373 | raise( |
| 417 | state, | 374 | state, |
| 418 | AlertTopic::DiskLow, | 375 | AlertTopic::DiskLow, |
| 419 | - "disk_low", | 376 | + AlertTopic::DiskLow.as_str(), |
| 420 | &dir.to_string_lossy(), | 377 | &dir.to_string_lossy(), |
| 421 | &detail, | 378 | &detail, |
| 422 | ) | 379 | ) |
| 423 | .await; | 380 | .await; |
| 424 | } else { | 381 | } else { |
| 425 | - resolve(state, "disk_low").await; | 382 | + resolve(state, AlertTopic::DiskLow.as_str()).await; |
| 426 | } | 383 | } |
| 427 | } | 384 | } |
| 428 | | 385 | |
| 429 | async fn check_backup_overdue(state: &AppState, now: i64) { | 386 | async fn check_backup_overdue(state: &AppState, now: i64) { |
| 430 | let live = state.live(); | 387 | let live = state.live(); |
| 431 | if !live.backup.enabled() || !live.alerts.kind_enabled(AlertKind::Backup) { | 388 | if !live.backup.enabled() || !live.alerts.kind_enabled(AlertKind::Backup) { |
| 432 | - resolve(state, "backup_overdue").await; | 389 | + resolve(state, AlertTopic::BackupOverdue.as_str()).await; |
| 433 | return; | 390 | return; |
| 434 | } | 391 | } |
| 435 | let last_ok = match state.store.last_ok(RunKind::Backup).await { | 392 | let last_ok = match state.store.last_ok(RunKind::Backup).await { |
| @@ -448,20 +405,20 @@ async fn check_backup_overdue(state: &AppState, now: i64) { |
| 448 | raise( | 405 | raise( |
| 449 | state, | 406 | state, |
| 450 | AlertTopic::BackupOverdue, | 407 | AlertTopic::BackupOverdue, |
| 451 | - "backup_overdue", | 408 | + AlertTopic::BackupOverdue.as_str(), |
| 452 | "", | 409 | "", |
| 453 | &detail, | 410 | &detail, |
| 454 | ) | 411 | ) |
| 455 | .await; | 412 | .await; |
| 456 | } else { | 413 | } else { |
| 457 | - resolve(state, "backup_overdue").await; | 414 | + resolve(state, AlertTopic::BackupOverdue.as_str()).await; |
| 458 | } | 415 | } |
| 459 | } | 416 | } |
| 460 | | 417 | |
| 461 | async fn check_replication(state: &AppState, now: i64) { | 418 | async fn check_replication(state: &AppState, now: i64) { |
| 462 | let live = state.live(); | 419 | let live = state.live(); |
| 463 | if !live.replication.enabled() || !live.alerts.kind_enabled(AlertKind::Replication) { | 420 | if !live.replication.enabled() || !live.alerts.kind_enabled(AlertKind::Replication) { |
| 464 | - resolve(state, "replication").await; | 421 | + resolve(state, AlertTopic::Replication.as_str()).await; |
| 465 | return; | 422 | return; |
| 466 | } | 423 | } |
| 467 | let rows = match state.store.list_replication_status().await { | 424 | let rows = match state.store.list_replication_status().await { |
| @@ -471,25 +428,32 @@ async fn check_replication(state: &AppState, now: i64) { |
| 471 | return; | 428 | return; |
| 472 | } | 429 | } |
| 473 | }; | 430 | }; |
| 474 | - let window = | 431 | + let window = window_secs(live.replication.db_snapshot_minutes); |
| 475 | - i64::try_from(live.replication.db_snapshot_minutes.saturating_mul(120)).unwrap_or(i64::MAX); | | |
| 476 | let mut problem: Option<String> = None; | 432 | let mut problem: Option<String> = None; |
| 477 | for row in &rows { | 433 | for row in &rows { |
| 478 | if let Some(error) = &row.last_error { | 434 | if let Some(error) = &row.last_error { |
| 479 | problem = Some(format!("{}: {error}.", row.subject)); | 435 | problem = Some(format!("{}: {error}.", row.subject)); |
| 480 | break; | 436 | break; |
| 481 | } | 437 | } |
| 482 | - if row.subject == forge_core::store::replication::DB_SUBJECT { | 438 | + if row.subject == DB_SUBJECT { |
| 483 | - let ok = row.last_ok_at.as_deref().and_then(stamp_to_unix); | 439 | + if replication_health(Some(row), now, window) != ReplicationHealth::Ok { |
| 484 | - if ok.is_none_or(|t| now.saturating_sub(t) > window) { | | |
| 485 | problem = Some("The database snapshot has not reached the standby in time.".into()); | 440 | problem = Some("The database snapshot has not reached the standby in time.".into()); |
| 486 | break; | 441 | break; |
| 487 | } | 442 | } |
| 488 | } | 443 | } |
| 489 | } | 444 | } |
| 490 | match problem { | 445 | match problem { |
| 491 | - Some(detail) => raise(state, AlertTopic::Replication, "replication", "", &detail).await, | 446 | + Some(detail) => { |
| 492 | - None => resolve(state, "replication").await, | 447 | + raise( |
| | 448 | + state, |
| | 449 | + AlertTopic::Replication, |
| | 450 | + AlertTopic::Replication.as_str(), |
| | 451 | + "", |
| | 452 | + &detail, |
| | 453 | + ) |
| | 454 | + .await; |
| | 455 | + } |
| | 456 | + None => resolve(state, AlertTopic::Replication.as_str()).await, |
| 493 | } | 457 | } |
| 494 | } | 458 | } |
| 495 | | 459 | |
| @@ -547,8 +511,22 @@ mod tests { |
| 547 | let tahinli = admin(&state, "tahinli", true).await; | 511 | let tahinli = admin(&state, "tahinli", true).await; |
| 548 | let second = admin(&state, "tahinli2", false).await; | 512 | let second = admin(&state, "tahinli2", false).await; |
| 549 | | 513 | |
| 550 | - raise(&state, AlertTopic::DiskLow, "disk_low", "/data", "4% free").await; | 514 | + raise( |
| 551 | - raise(&state, AlertTopic::DiskLow, "disk_low", "/data", "3% free").await; | 515 | + &state, |
| | 516 | + AlertTopic::DiskLow, |
| | 517 | + AlertTopic::DiskLow.as_str(), |
| | 518 | + "/data", |
| | 519 | + "4% free", |
| | 520 | + ) |
| | 521 | + .await; |
| | 522 | + raise( |
| | 523 | + &state, |
| | 524 | + AlertTopic::DiskLow, |
| | 525 | + AlertTopic::DiskLow.as_str(), |
| | 526 | + "/data", |
| | 527 | + "3% free", |
| | 528 | + ) |
| | 529 | + .await; |
| 552 | assert_eq!(inbox(&state, &tahinli).await.len(), 1, "deduplicated"); | 530 | assert_eq!(inbox(&state, &tahinli).await.len(), 1, "deduplicated"); |
| 553 | assert_eq!(inbox(&state, &second).await.len(), 1); | 531 | assert_eq!(inbox(&state, &second).await.len(), 1); |
| 554 | assert_eq!(state.store.active_alerts().await.unwrap().len(), 1); | 532 | assert_eq!(state.store.active_alerts().await.unwrap().len(), 1); |
| @@ -558,8 +536,8 @@ mod tests { |
| 558 | "only the verified admin is mailed" | 536 | "only the verified admin is mailed" |
| 559 | ); | 537 | ); |
| 560 | | 538 | |
| 561 | - resolve(&state, "disk_low").await; | 539 | + resolve(&state, AlertTopic::DiskLow.as_str()).await; |
| 562 | - resolve(&state, "disk_low").await; | 540 | + resolve(&state, AlertTopic::DiskLow.as_str()).await; |
| 563 | let rows = inbox(&state, &tahinli).await; | 541 | let rows = inbox(&state, &tahinli).await; |
| 564 | assert_eq!(rows.len(), 2, "raised and resolved, once each"); | 542 | assert_eq!(rows.len(), 2, "raised and resolved, once each"); |
| 565 | assert!(rows.iter().any(|r| r.resolved)); | 543 | assert!(rows.iter().any(|r| r.resolved)); |
| @@ -567,7 +545,14 @@ mod tests { |
| 567 | assert_eq!(queued_mail(&state).await, 2); | 545 | assert_eq!(queued_mail(&state).await, 2); |
| 568 | assert_eq!(state.store.unread_count(&tahinli).await.unwrap(), 2); | 546 | assert_eq!(state.store.unread_count(&tahinli).await.unwrap(), 2); |
| 569 | | 547 | |
| 570 | - raise(&state, AlertTopic::DiskLow, "disk_low", "/data", "2% free").await; | 548 | + raise( |
| | 549 | + &state, |
| | 550 | + AlertTopic::DiskLow, |
| | 551 | + AlertTopic::DiskLow.as_str(), |
| | 552 | + "/data", |
| | 553 | + "2% free", |
| | 554 | + ) |
| | 555 | + .await; |
| 571 | assert_eq!( | 556 | assert_eq!( |
| 572 | inbox(&state, &tahinli).await.len(), | 557 | inbox(&state, &tahinli).await.len(), |
| 573 | 3, | 558 | 3, |
| @@ -583,13 +568,27 @@ mod tests { |
| 583 | let mut config = (*state.config).clone(); | 568 | let mut config = (*state.config).clone(); |
| 584 | config.alerts.on_disk = false; | 569 | config.alerts.on_disk = false; |
| 585 | state.set_config(config.clone()); | 570 | state.set_config(config.clone()); |
| 586 | - raise(&state, AlertTopic::DiskLow, "disk_low", "/data", "4% free").await; | 571 | + raise( |
| | 572 | + &state, |
| | 573 | + AlertTopic::DiskLow, |
| | 574 | + AlertTopic::DiskLow.as_str(), |
| | 575 | + "/data", |
| | 576 | + "4% free", |
| | 577 | + ) |
| | 578 | + .await; |
| 587 | assert!(inbox(&state, &tahinli).await.is_empty()); | 579 | assert!(inbox(&state, &tahinli).await.is_empty()); |
| 588 | | 580 | |
| 589 | config.alerts.on_disk = true; | 581 | config.alerts.on_disk = true; |
| 590 | config.alerts.email = false; | 582 | config.alerts.email = false; |
| 591 | state.set_config(config.clone()); | 583 | state.set_config(config.clone()); |
| 592 | - raise(&state, AlertTopic::DiskLow, "disk_low", "/data", "4% free").await; | 584 | + raise( |
| | 585 | + &state, |
| | 586 | + AlertTopic::DiskLow, |
| | 587 | + AlertTopic::DiskLow.as_str(), |
| | 588 | + "/data", |
| | 589 | + "4% free", |
| | 590 | + ) |
| | 591 | + .await; |
| 593 | assert_eq!(inbox(&state, &tahinli).await.len(), 1); | 592 | assert_eq!(inbox(&state, &tahinli).await.len(), 1); |
| 594 | assert_eq!(queued_mail(&state).await, 0); | 593 | assert_eq!(queued_mail(&state).await, 0); |
| 595 | | 594 | |
| @@ -598,7 +597,7 @@ mod tests { |
| 598 | raise( | 597 | raise( |
| 599 | &state, | 598 | &state, |
| 600 | AlertTopic::BackupFailed, | 599 | AlertTopic::BackupFailed, |
| 601 | - "backup_failed", | 600 | + AlertTopic::BackupFailed.as_str(), |
| 602 | "", | 601 | "", |
| 603 | "boom", | 602 | "boom", |
| 604 | ) | 603 | ) |
| @@ -19,6 +19,7 @@ use topcoat::router::{StatusCode, path_param, route}; |
| 19 | use crate::api::{self, Refusal}; | 19 | use crate::api::{self, Refusal}; |
| 20 | use crate::client_ip::client_ip; | 20 | use crate::client_ip::client_ip; |
| 21 | use crate::state::AppState; | 21 | use crate::state::AppState; |
| | 22 | +use crate::views::query_value; |
| 22 | | 23 | |
| 23 | path_param!(owner); | 24 | path_param!(owner); |
| 24 | path_param!(repo); | 25 | path_param!(repo); |
| @@ -63,13 +64,6 @@ pub fn user_json(base: &str, id: &str, name: &str) -> Value { |
| 63 | }) | 64 | }) |
| 64 | } | 65 | } |
| 65 | | 66 | |
| 66 | -fn query_value(cx: &Cx, key: &str) -> Option<String> { | | |
| 67 | - let query = uri(cx).query()?; | | |
| 68 | - form_urlencoded::parse(query.as_bytes()) | | |
| 69 | - .find(|(k, _)| k == key) | | |
| 70 | - .map(|(_, v)| v.into_owned()) | | |
| 71 | -} | | |
| 72 | - | | |
| 73 | fn effective_headers(cx: &Cx) -> HeaderMap { | 67 | fn effective_headers(cx: &Cx) -> HeaderMap { |
| 74 | let mut map = headers(cx).clone(); | 68 | let mut map = headers(cx).clone(); |
| 75 | if !map.contains_key(AUTHORIZATION) | 69 | if !map.contains_key(AUTHORIZATION) |
| @@ -582,7 +576,7 @@ async fn reactions_json( |
| 582 | }; | 576 | }; |
| 583 | out.push(json!({ | 577 | out.push(json!({ |
| 584 | "user": user_json(&ctx.base, &user.id, username), | 578 | "user": user_json(&ctx.base, &user.id, username), |
| 585 | - "reaction": summary.reaction.name(), | 579 | + "reaction": summary.reaction.as_str(), |
| 586 | "created_at": created_at, | 580 | "created_at": created_at, |
| 587 | })); | 581 | })); |
| 588 | } | 582 | } |
| @@ -40,7 +40,7 @@ async fn report_status(cx: &Cx, body: Body) -> topcoat::Result<Response> { |
| 40 | Ok(report) => report, | 40 | Ok(report) => report, |
| 41 | Err(res) => return Ok(*res), | 41 | Err(res) => return Ok(*res), |
| 42 | }; | 42 | }; |
| 43 | - let Some(status_state) = StatusState::parse(&report.state) else { | 43 | + let Ok(status_state) = report.state.parse::<StatusState>() else { |
| 44 | return Ok(api::error( | 44 | return Ok(api::error( |
| 45 | StatusCode::UNPROCESSABLE_ENTITY, | 45 | StatusCode::UNPROCESSABLE_ENTITY, |
| 46 | "state must be one of pending, success, failure, error", | 46 | "state must be one of pending, success, failure, error", |
| @@ -2,9 +2,10 @@ use std::sync::{Arc, OnceLock}; |
| 2 | use std::time::Duration; | 2 | use std::time::Duration; |
| 3 | | 3 | |
| 4 | use forge_core::password::{hash_password, verify_password}; | 4 | use forge_core::password::{hash_password, verify_password}; |
| 5 | -use forge_core::time::{stamp_after, unix_now}; | 5 | +use forge_core::time::{now_unix, stamp_after}; |
| 6 | use forge_core::token::{constant_time_eq, hash_token, random_b64url}; | 6 | use forge_core::token::{constant_time_eq, hash_token, random_b64url}; |
| 7 | use forge_core::{Session, Store, User, secret, totp}; | 7 | use forge_core::{Session, Store, User, secret, totp}; |
| | 8 | +use serde::Deserialize; |
| 8 | use tokio::sync::Semaphore; | 9 | use tokio::sync::Semaphore; |
| 9 | use topcoat::Result; | 10 | use topcoat::Result; |
| 10 | use topcoat::context::{Cx, context}; | 11 | use topcoat::context::{Cx, context}; |
| @@ -169,6 +170,12 @@ pub async fn require_user(cx: &Cx) -> Result<(User, Session)> { |
| 169 | } | 170 | } |
| 170 | } | 171 | } |
| 171 | | 172 | |
| | 173 | +#[derive(Deserialize)] |
| | 174 | +pub struct CsrfForm { |
| | 175 | + #[serde(default)] |
| | 176 | + pub csrf: String, |
| | 177 | +} |
| | 178 | + |
| 172 | pub async fn require_csrf(cx: &Cx, submitted: &str) -> Result<(User, Session)> { | 179 | pub async fn require_csrf(cx: &Cx, submitted: &str) -> Result<(User, Session)> { |
| 173 | let (user, session) = require_user(cx).await?; | 180 | let (user, session) = require_user(cx).await?; |
| 174 | if check_csrf(&session, submitted) { | 181 | if check_csrf(&session, submitted) { |
| @@ -189,7 +196,7 @@ pub fn set_pending_login( |
| 189 | user_id: &str, | 196 | user_id: &str, |
| 190 | next: &str, | 197 | next: &str, |
| 191 | ) -> forge_core::Result<()> { | 198 | ) -> forge_core::Result<()> { |
| 192 | - let expires = unix_now() + PENDING_2FA_TTL.as_secs(); | 199 | + let expires = now_unix().saturating_add_unsigned(PENDING_2FA_TTL.as_secs()); |
| 193 | let sealed = secret::seal(key, format!("{expires}|{user_id}|{next}").as_bytes())?; | 200 | let sealed = secret::seal(key, format!("{expires}|{user_id}|{next}").as_bytes())?; |
| 194 | let max_age = time::Duration::seconds(i64::try_from(PENDING_2FA_TTL.as_secs()).unwrap_or(0)); | 201 | let max_age = time::Duration::seconds(i64::try_from(PENDING_2FA_TTL.as_secs()).unwrap_or(0)); |
| 195 | session_jar(cx).add( | 202 | session_jar(cx).add( |
| @@ -209,10 +216,10 @@ pub fn pending_login(cx: &Cx, key: &[u8; 32]) -> Option<PendingLogin> { |
| 209 | let plain = secret::open(key, cookie.value()).ok()?; | 216 | let plain = secret::open(key, cookie.value()).ok()?; |
| 210 | let text = String::from_utf8(plain).ok()?; | 217 | let text = String::from_utf8(plain).ok()?; |
| 211 | let mut parts = text.splitn(3, '|'); | 218 | let mut parts = text.splitn(3, '|'); |
| 212 | - let expires: u64 = parts.next()?.parse().ok()?; | 219 | + let expires: i64 = parts.next()?.parse().ok()?; |
| 213 | let user_id = parts.next()?; | 220 | let user_id = parts.next()?; |
| 214 | let next = parts.next()?; | 221 | let next = parts.next()?; |
| 215 | - if unix_now() >= expires { | 222 | + if now_unix() >= expires { |
| 216 | return None; | 223 | return None; |
| 217 | } | 224 | } |
| 218 | Some(PendingLogin { | 225 | Some(PendingLogin { |
| @@ -258,7 +265,7 @@ pub async fn verify_second_factor( |
| 258 | let shared = secret::open(key, sealed)?; | 265 | let shared = secret::open(key, sealed)?; |
| 259 | let is_totp = input.len() == totp::DIGITS && input.bytes().all(|b| b.is_ascii_digit()); | 266 | let is_totp = input.len() == totp::DIGITS && input.bytes().all(|b| b.is_ascii_digit()); |
| 260 | if is_totp { | 267 | if is_totp { |
| 261 | - return match totp::verify(&shared, input, totp::step_for(unix_now()), state.last_step) { | 268 | + return match totp::verify(&shared, input, totp::step_for(now_unix()), state.last_step) { |
| 262 | Some(step) => store.accept_totp_step(user_id, step).await, | 269 | Some(step) => store.accept_totp_step(user_id, step).await, |
| 263 | None => Ok(false), | 270 | None => Ok(false), |
| 264 | }; | 271 | }; |
| @@ -386,7 +393,7 @@ mod tests { |
| 386 | let org = store.create_org("acme", &tahinli.id).await.unwrap(); | 393 | let org = store.create_org("acme", &tahinli.id).await.unwrap(); |
| 387 | let shared = forge_core::totp::new_secret(); | 394 | let shared = forge_core::totp::new_secret(); |
| 388 | let sealed = forge_core::secret::seal(&key, &shared).unwrap(); | 395 | let sealed = forge_core::secret::seal(&key, &shared).unwrap(); |
| 389 | - let code = forge_core::totp::code_at(&shared, forge_core::totp::step_for(unix_now())); | 396 | + let code = forge_core::totp::code_at(&shared, forge_core::totp::step_for(now_unix())); |
| 390 | let recovery = forge_core::totp::recovery_code_hash("aaaa-bbbb"); | 397 | let recovery = forge_core::totp::recovery_code_hash("aaaa-bbbb"); |
| 391 | for id in [&org.id, &tahinli.id] { | 398 | for id in [&org.id, &tahinli.id] { |
| 392 | store.set_totp_secret(id, &sealed).await.unwrap(); | 399 | store.set_totp_secret(id, &sealed).await.unwrap(); |
| @@ -213,11 +213,9 @@ pub async fn backup_job( |
| 213 | healthcheck::start(url).await; | 213 | healthcheck::start(url).await; |
| 214 | } | 214 | } |
| 215 | | 215 | |
| 216 | - let outcome = backup_set(state, &opts).await; | 216 | + let set = backup_set(state, &opts).await; |
| 217 | - match &outcome { | 217 | + crate::alerts::backup_finished(state, set.as_ref().map(|_| ())).await; |
| 218 | - Ok(_) => crate::alerts::backup_finished(state, Ok(())).await, | 218 | + let outcome = set.map_err(BackupSetError::into_error); |
| 219 | - Err(e) => crate::alerts::backup_finished(state, Err(&e.to_string())).await, | | |
| 220 | - } | | |
| 221 | match &outcome { | 219 | match &outcome { |
| 222 | Ok(summary) => { | 220 | Ok(summary) => { |
| 223 | let path = summary.path.to_string_lossy().into_owned(); | 221 | let path = summary.path.to_string_lossy().into_owned(); |
| @@ -246,19 +244,39 @@ pub async fn backup_job( |
| 246 | outcome | 244 | outcome |
| 247 | } | 245 | } |
| 248 | | 246 | |
| 249 | -async fn backup_set(state: &AppState, opts: &BackupOptions) -> Result<BackupSummary> { | 247 | +pub enum BackupSetError { |
| | 248 | + Failed(Error), |
| | 249 | + Verify(Error), |
| | 250 | +} |
| | 251 | + |
| | 252 | +impl BackupSetError { |
| | 253 | + fn into_error(self) -> Error { |
| | 254 | + match self { |
| | 255 | + Self::Failed(e) | Self::Verify(e) => e, |
| | 256 | + } |
| | 257 | + } |
| | 258 | +} |
| | 259 | + |
| | 260 | +async fn backup_set( |
| | 261 | + state: &AppState, |
| | 262 | + opts: &BackupOptions, |
| | 263 | +) -> std::result::Result<BackupSummary, BackupSetError> { |
| 250 | let source = BackupSource { | 264 | let source = BackupSource { |
| 251 | store: state.store.clone(), | 265 | store: state.store.clone(), |
| 252 | git: (*state.git).clone(), | 266 | git: (*state.git).clone(), |
| 253 | base_url: state.config.base_url.clone(), | 267 | base_url: state.config.base_url.clone(), |
| 254 | }; | 268 | }; |
| 255 | - let summary = create_backup(&source, opts).await?; | 269 | + let summary = create_backup(&source, opts) |
| 256 | - let report = verify_backup(&summary.path, &source.git).await?; | 270 | + .await |
| | 271 | + .map_err(BackupSetError::Failed)?; |
| | 272 | + let report = verify_backup(&summary.path, &source.git) |
| | 273 | + .await |
| | 274 | + .map_err(BackupSetError::Failed)?; |
| 257 | if !report.is_ok() { | 275 | if !report.is_ok() { |
| 258 | - return Err(Error::Invalid(format!( | 276 | + return Err(BackupSetError::Verify(Error::Invalid(format!( |
| 259 | "the new backup set failed verification: {}", | 277 | "the new backup set failed verification: {}", |
| 260 | report.problems.join("; ") | 278 | report.problems.join("; ") |
| 261 | - ))); | 279 | + )))); |
| 262 | } | 280 | } |
| 263 | Ok(summary) | 281 | Ok(summary) |
| 264 | } | 282 | } |
| @@ -22,9 +22,10 @@ use topcoat::router::{Body, HeaderMap, StatusCode, path_param, route}; |
| 22 | | 22 | |
| 23 | use crate::api::{self, Refusal}; | 23 | use crate::api::{self, Refusal}; |
| 24 | use crate::ci::{artifact_key, log_path}; | 24 | use crate::ci::{artifact_key, log_path}; |
| | 25 | +use crate::i18n::Lang; |
| 25 | use crate::self_update; | 26 | use crate::self_update; |
| 26 | use crate::state::AppState; | 27 | use crate::state::AppState; |
| 27 | -use crate::views::{bytes_text, https_clone_url}; | 28 | +use crate::views::{https_clone_url, human_size}; |
| 28 | | 29 | |
| 29 | path_param!(job_id); | 30 | path_param!(job_id); |
| 30 | path_param!(artifact_name); | 31 | path_param!(artifact_name); |
| @@ -437,8 +438,8 @@ fn idle_text(skips: &QueueSkips, free: Option<u64>) -> Option<String> { |
| 437 | parts.push(format!( | 438 | parts.push(format!( |
| 438 | "{} waiting for memory: smallest needs {}, {} free", | 439 | "{} waiting for memory: smallest needs {}, {} free", |
| 439 | skips.too_big, | 440 | skips.too_big, |
| 440 | - bytes_text(need), | 441 | + human_size(Lang::En, need), |
| 441 | - bytes_text(free) | 442 | + human_size(Lang::En, free) |
| 442 | )); | 443 | )); |
| 443 | } | 444 | } |
| 444 | if let (Some(need), Some(free)) = (skips.starved_need, free) { | 445 | if let (Some(need), Some(free)) = (skips.starved_need, free) { |
| @@ -447,8 +448,8 @@ fn idle_text(skips: &QueueSkips, free: Option<u64>) -> Option<String> { |
| 447 | starts until running jobs finish and it fits", | 448 | starts until running jobs finish and it fits", |
| 448 | skips.held_behind, | 449 | skips.held_behind, |
| 449 | forge_core::ci::STARVE_AFTER_SECS / 60, | 450 | forge_core::ci::STARVE_AFTER_SECS / 60, |
| 450 | - bytes_text(need), | 451 | + human_size(Lang::En, need), |
| 451 | - bytes_text(free) | 452 | + human_size(Lang::En, free) |
| 452 | )); | 453 | )); |
| 453 | } | 454 | } |
| 454 | Some(parts.join("; ")) | 455 | Some(parts.join("; ")) |
| @@ -969,6 +970,7 @@ async fn upload(state: &AppState, job: &CiJob, name: &str, body: Body) -> Result |
| 969 | .max_artifact_mb | 970 | .max_artifact_mb |
| 970 | .saturating_mul(MIB) | 971 | .saturating_mul(MIB) |
| 971 | .min(left); | 972 | .min(left); |
| | 973 | + let job_bytes = state.live().ci.max_job_artifacts_mb.saturating_mul(MIB); |
| 972 | let temp_key = format!("ci/tmp/{}", ulid::Ulid::generate()); | 974 | let temp_key = format!("ci/tmp/{}", ulid::Ulid::generate()); |
| 973 | let mut writer = state | 975 | let mut writer = state |
| 974 | .blobs | 976 | .blobs |
| @@ -996,7 +998,14 @@ async fn upload(state: &AppState, job: &CiJob, name: &str, body: Body) -> Result |
| 996 | | 998 | |
| 997 | let artifact = match state | 999 | let artifact = match state |
| 998 | .store | 1000 | .store |
| 999 | - .add_artifact(&job.id, name, size as i64, &sha256) | 1001 | + .add_artifact_within( |
| | 1002 | + &job.id, |
| | 1003 | + name, |
| | 1004 | + size as i64, |
| | 1005 | + &sha256, |
| | 1006 | + u64::from(max_artifacts), |
| | 1007 | + job_bytes, |
| | 1008 | + ) |
| 1000 | .await | 1009 | .await |
| 1001 | { | 1010 | { |
| 1002 | Ok(artifact) => artifact, | 1011 | Ok(artifact) => artifact, |
| @@ -1003,21 +1003,17 @@ async fn job_token_reads_over_smart_http_but_never_pushes() { |
| 1003 | .await | 1003 | .await |
| 1004 | .unwrap() | 1004 | .unwrap() |
| 1005 | .expect("repo"); | 1005 | .expect("repo"); |
| 1006 | - let (_, secret) = { | | |
| 1007 | - let token = fx | | |
| 1008 | - .store | | |
| 1009 | - .create_registration_token( | | |
| 1010 | - &fx.store.user_by_username(OWNER).await.unwrap().unwrap().id, | | |
| 1011 | - 24, | | |
| 1012 | - ) | | |
| 1013 | - .await | | |
| 1014 | - .unwrap(); | | |
| 1015 | - fx.store | | |
| 1016 | - .register_runner(&token, "runner", &[]) | | |
| 1017 | - .await | | |
| 1018 | - .unwrap() | | |
| 1019 | - }; | | |
| 1020 | let owner_id = fx.store.user_by_username(OWNER).await.unwrap().unwrap().id; | 1006 | let owner_id = fx.store.user_by_username(OWNER).await.unwrap().unwrap().id; |
| | 1007 | + let token = fx |
| | 1008 | + .store |
| | 1009 | + .create_registration_token(&owner_id, 24) |
| | 1010 | + .await |
| | 1011 | + .unwrap(); |
| | 1012 | + let (_, secret) = fx |
| | 1013 | + .store |
| | 1014 | + .register_runner(&token, "runner", &[]) |
| | 1015 | + .await |
| | 1016 | + .unwrap(); |
| 1021 | fx.store | 1017 | fx.store |
| 1022 | .create_run( | 1018 | .create_run( |
| 1023 | &NewRun { | 1019 | &NewRun { |
| @@ -1,4 +1,4 @@ |
| 1 | -use forge_ci::config::{CiConfig, Event, parse_config}; | 1 | +use forge_ci::config::{CiConfig, Event, MAX_CONFIG_BYTES, parse_config}; |
| 2 | use forge_core::authz::{Action, authorize}; | 2 | use forge_core::authz::{Action, authorize}; |
| 3 | use forge_core::ci::{CiRun, NewJob, NewRun}; | 3 | use forge_core::ci::{CiRun, NewJob, NewRun}; |
| 4 | use forge_core::store::commit_status::StatusState; | 4 | use forge_core::store::commit_status::StatusState; |
| @@ -12,7 +12,6 @@ use crate::internal::is_zero_oid; |
| 12 | use crate::state::AppState; | 12 | use crate::state::AppState; |
| 13 | | 13 | |
| 14 | pub const CONFIG_PATH: &str = ".forge/ci.toml"; | 14 | pub const CONFIG_PATH: &str = ".forge/ci.toml"; |
| 15 | -const MAX_CONFIG_BYTES: usize = 64 * 1024; | | |
| 16 | const MAX_WARNING_LINES: usize = 20; | 15 | const MAX_WARNING_LINES: usize = 20; |
| 17 | const MIB: u64 = 1024 * 1024; | 16 | const MIB: u64 = 1024 * 1024; |
| 18 | | 17 | |
| @@ -430,7 +429,7 @@ fn plan_jobs(cfg: &CiConfig) -> forge_core::Result<Vec<PlannedJob>> { |
| 430 | Ok(jobs) | 429 | Ok(jobs) |
| 431 | } | 430 | } |
| 432 | | 431 | |
| 433 | -pub(super) async fn config_at(state: &AppState, repo_id: &str, commit: &str) -> Option<CiConfig> { | 432 | +pub async fn config_at(state: &AppState, repo_id: &str, commit: &str) -> Option<CiConfig> { |
| 434 | match load(state, repo_id, commit).await { | 433 | match load(state, repo_id, commit).await { |
| 435 | Loaded::Valid(config) => Some(config), | 434 | Loaded::Valid(config) => Some(config), |
| 436 | Loaded::Missing | Loaded::Invalid(_) => None, | 435 | Loaded::Missing | Loaded::Invalid(_) => None, |
| @@ -548,7 +547,7 @@ pub(super) mod tests { |
| 548 | use forge_core::ci::{CiJob, CiRunner, JobState, RunState}; | 547 | use forge_core::ci::{CiJob, CiRunner, JobState, RunState}; |
| 549 | use forge_core::store::commit_status::{CommitStatus, StatusState}; | 548 | use forge_core::store::commit_status::{CommitStatus, StatusState}; |
| 550 | use forge_core::time::stamp_after; | 549 | use forge_core::time::stamp_after; |
| 551 | - use forge_core::{User, Visibility}; | 550 | + use forge_core::{NewPull, User, Visibility}; |
| 552 | use forge_git::repo::{init_bare, repo_path}; | 551 | use forge_git::repo::{init_bare, repo_path}; |
| 553 | use tempfile::TempDir; | 552 | use tempfile::TempDir; |
| 554 | | 553 | |
| @@ -920,17 +919,17 @@ run = "make" |
| 920 | let pr = fx | 919 | let pr = fx |
| 921 | .state | 920 | .state |
| 922 | .store | 921 | .store |
| 923 | - .create_pull( | 922 | + .create_pull(&NewPull { |
| 924 | - &fx.repo.id, | 923 | + repo_id: &fx.repo.id, |
| 925 | author_id, | 924 | author_id, |
| 926 | - "Change", | 925 | + title: "Change", |
| 927 | - "", | 926 | + body: "", |
| 928 | - "main", | 927 | + base_branch: "main", |
| 929 | head_repo_id, | 928 | head_repo_id, |
| 930 | - branch, | 929 | + head_branch: branch, |
| 931 | head_oid, | 930 | head_oid, |
| 932 | - head_oid, | 931 | + base_oid: head_oid, |
| 933 | - ) | 932 | + }) |
| 934 | .await | 933 | .await |
| 935 | .expect("create pull"); | 934 | .expect("create pull"); |
| 936 | on_pull_event(&fx.state, &fx.repo, &pr, author_id).await; | 935 | on_pull_event(&fx.state, &fx.repo, &pr, author_id).await; |
| @@ -4,7 +4,7 @@ use std::time::{Duration, SystemTime}; |
| 4 | use forge_core::Store; | 4 | use forge_core::Store; |
| 5 | use serde::{Deserialize, Serialize}; | 5 | use serde::{Deserialize, Serialize}; |
| 6 | | 6 | |
| 7 | -use super::{is_sha256_hex, lfs_root, tmp_dir}; | 7 | +use super::{is_sha256_hex, lfs_root, lock, tmp_dir}; |
| 8 | | 8 | |
| 9 | pub const GC_MIN_AGE: Duration = Duration::from_secs(24 * 60 * 60); | 9 | pub const GC_MIN_AGE: Duration = Duration::from_secs(24 * 60 * 60); |
| 10 | | 10 | |
| @@ -46,6 +46,7 @@ pub async fn gc( |
| 46 | .await | 46 | .await |
| 47 | .map_err(|e| forge_core::Error::Io(std::io::Error::other(e)))??; | 47 | .map_err(|e| forge_core::Error::Io(std::io::Error::other(e)))??; |
| 48 | for candidate in objects { | 48 | for candidate in objects { |
| | 49 | + let _lock = lock().await; |
| 49 | summary.checked += 1; | 50 | summary.checked += 1; |
| 50 | if !is_older_than(candidate.modified, now, min_age) { | 51 | if !is_older_than(candidate.modified, now, min_age) { |
| 51 | continue; | 52 | continue; |
| @@ -6,9 +6,16 @@ mod routes; |
| 6 | use std::path::{Path, PathBuf}; | 6 | use std::path::{Path, PathBuf}; |
| 7 | | 7 | |
| 8 | use forge_core::Result; | 8 | use forge_core::Result; |
| | 9 | +use tokio::sync::{Mutex, MutexGuard}; |
| 9 | | 10 | |
| 10 | use crate::state::AppState; | 11 | use crate::state::AppState; |
| 11 | | 12 | |
| | 13 | +static LOCK: Mutex<()> = Mutex::const_new(()); |
| | 14 | + |
| | 15 | +pub async fn lock() -> MutexGuard<'static, ()> { |
| | 16 | + LOCK.lock().await |
| | 17 | +} |
| | 18 | + |
| 12 | pub fn is_sha256_hex(oid: &str) -> bool { | 19 | pub fn is_sha256_hex(oid: &str) -> bool { |
| 13 | oid.len() == 64 | 20 | oid.len() == 64 |
| 14 | && oid | 21 | && oid |
| @@ -1,5 +1,5 @@ |
| 1 | use std::net::IpAddr; | 1 | use std::net::IpAddr; |
| 2 | -use std::path::Path; | 2 | +use std::path::{Path, PathBuf}; |
| 3 | use std::sync::atomic::{AtomicU64, Ordering}; | 3 | use std::sync::atomic::{AtomicU64, Ordering}; |
| 4 | | 4 | |
| 5 | use forge_core::Action; | 5 | use forge_core::Action; |
| @@ -19,7 +19,7 @@ use topcoat::router::request::headers; |
| 19 | use topcoat::router::response::Response; | 19 | use topcoat::router::response::Response; |
| 20 | use topcoat::router::{Body, HeaderMap, StatusCode, path_param, route, to_bytes}; | 20 | use topcoat::router::{Body, HeaderMap, StatusCode, path_param, route, to_bytes}; |
| 21 | | 21 | |
| 22 | -use super::{is_sha256_hex, object_path, tmp_dir}; | 22 | +use super::{is_sha256_hex, lock, object_path, tmp_dir}; |
| 23 | use crate::access::{AccessError, find_repo, resolve_repo_for}; | 23 | use crate::access::{AccessError, find_repo, resolve_repo_for}; |
| 24 | use crate::client_ip::client_ip; | 24 | use crate::client_ip::client_ip; |
| 25 | use crate::git_http::{access_error, authenticate}; | 25 | use crate::git_http::{access_error, authenticate}; |
| @@ -247,10 +247,14 @@ async fn put_object(cx: &Cx, body: Body) -> topcoat::Result<Response> { |
| 247 | )); | 247 | )); |
| 248 | } | 248 | } |
| 249 | | 249 | |
| 250 | - let size = match receive_object(&state.config.data_dir, body, oid, max).await { | 250 | + let (temp, size) = match receive_object(&state.config.data_dir, body, oid, max).await { |
| 251 | - Ok(size) => size, | 251 | + Ok(received) => received, |
| 252 | Err(response) => return Ok(*response), | 252 | Err(response) => return Ok(*response), |
| 253 | }; | 253 | }; |
| | 254 | + let _lock = lock().await; |
| | 255 | + if let Err(response) = place_object(&state.config.data_dir, &temp, oid).await { |
| | 256 | + return Ok(*response); |
| | 257 | + } |
| 254 | if let Err(e) = state.store.insert_lfs_object(&repo.id, oid, size).await { | 258 | if let Err(e) = state.store.insert_lfs_object(&repo.id, oid, size).await { |
| 255 | return Ok(server_error(e)); | 259 | return Ok(server_error(e)); |
| 256 | } | 260 | } |
| @@ -354,7 +358,7 @@ async fn receive_object( |
| 354 | body: Body, | 358 | body: Body, |
| 355 | oid: &str, | 359 | oid: &str, |
| 356 | max: u64, | 360 | max: u64, |
| 357 | -) -> Result<u64, Box<Response>> { | 361 | +) -> Result<(PathBuf, u64), Box<Response>> { |
| 358 | let dir = tmp_dir(data_dir); | 362 | let dir = tmp_dir(data_dir); |
| 359 | tokio::fs::create_dir_all(&dir) | 363 | tokio::fs::create_dir_all(&dir) |
| 360 | .await | 364 | .await |
| @@ -373,18 +377,22 @@ async fn receive_object( |
| 373 | let _ = tokio::fs::remove_file(&temp).await; | 377 | let _ = tokio::fs::remove_file(&temp).await; |
| 374 | return Err(unprocessable("the content does not match the oid")); | 378 | return Err(unprocessable("the content does not match the oid")); |
| 375 | } | 379 | } |
| | 380 | + Ok((temp, size)) |
| | 381 | +} |
| 376 | | 382 | |
| | 383 | +async fn place_object(data_dir: &Path, temp: &Path, oid: &str) -> Result<(), Box<Response>> { |
| 377 | let target = object_path(data_dir, oid); | 384 | let target = object_path(data_dir, oid); |
| 378 | - if let Some(parent) = target.parent() { | 385 | + if let Some(parent) = target.parent() |
| 379 | - tokio::fs::create_dir_all(parent) | 386 | + && let Err(e) = tokio::fs::create_dir_all(parent).await |
| 380 | - .await | 387 | + { |
| 381 | - .map_err(|e| Box::new(server_error(e)))?; | 388 | + let _ = tokio::fs::remove_file(temp).await; |
| | 389 | + return Err(Box::new(server_error(e))); |
| 382 | } | 390 | } |
| 383 | - if let Err(e) = tokio::fs::rename(&temp, &target).await { | 391 | + if let Err(e) = tokio::fs::rename(temp, &target).await { |
| 384 | - let _ = tokio::fs::remove_file(&temp).await; | 392 | + let _ = tokio::fs::remove_file(temp).await; |
| 385 | return Err(Box::new(server_error(e))); | 393 | return Err(Box::new(server_error(e))); |
| 386 | } | 394 | } |
| 387 | - Ok(size) | 395 | + Ok(()) |
| 388 | } | 396 | } |
| 389 | | 397 | |
| 390 | async fn write_and_hash(temp: &Path, body: Body, max: u64) -> Result<(u64, String), Box<Response>> { | 398 | async fn write_and_hash(temp: &Path, body: Body, max: u64) -> Result<(u64, String), Box<Response>> { |
| @@ -55,6 +55,5 @@ pub mod build_info { |
| 55 | pub const BUILD_SHA: &str = env!("FORGE_BUILD_SHA"); | 55 | pub const BUILD_SHA: &str = env!("FORGE_BUILD_SHA"); |
| 56 | pub const GIT_SHA: &str = env!("FORGE_GIT_SHA"); | 56 | pub const GIT_SHA: &str = env!("FORGE_GIT_SHA"); |
| 57 | pub const GIT_DATE: &str = env!("FORGE_GIT_DATE"); | 57 | pub const GIT_DATE: &str = env!("FORGE_GIT_DATE"); |
| 58 | - pub const GIT_DIRTY: bool = matches!(env!("FORGE_GIT_DIRTY").as_bytes(), b"1"); | | |
| 59 | pub const MAIN_CSS: &str = include_str!(concat!(env!("OUT_DIR"), "/main.css")); | 58 | pub const MAIN_CSS: &str = include_str!(concat!(env!("OUT_DIR"), "/main.css")); |
| 60 | } | 59 | } |
| @@ -1,12 +1,16 @@ |
| | 1 | +use std::time::Duration; |
| | 2 | + |
| | 3 | +use forge_ci::config::DEFAULT_TIMEOUT_MINUTES; |
| 1 | use forge_core::merge_queue::{QueueEntry, QueueState, test_ref_name}; | 4 | use forge_core::merge_queue::{QueueEntry, QueueState, test_ref_name}; |
| 2 | use forge_core::protection::effective; | 5 | use forge_core::protection::effective; |
| 3 | use forge_core::store::commit_status::StatusState; | 6 | use forge_core::store::commit_status::StatusState; |
| | 7 | +use forge_core::time::stamp_ago; |
| 4 | use forge_core::{Action, IssueState, MergeStyle, Mergeable, PullRequest, Repo, User, authorize}; | 8 | use forge_core::{Action, IssueState, MergeStyle, Mergeable, PullRequest, Repo, User, authorize}; |
| 5 | use forge_git::browse::default_branch_commit; | 9 | use forge_git::browse::default_branch_commit; |
| 6 | use forge_git::pulls::{set_ref, update_ref_cas}; | 10 | use forge_git::pulls::{set_ref, update_ref_cas}; |
| 7 | use forge_git::repo::repo_path; | 11 | use forge_git::repo::repo_path; |
| 8 | | 12 | |
| 9 | -use crate::ci::schedule::merge_queue_run; | 13 | +use crate::ci::schedule::{config_at, merge_queue_run}; |
| 10 | use crate::merge::{ | 14 | use crate::merge::{ |
| 11 | ERR_CONFLICT, ERR_DRAFT, ERR_HEAD_MISSING, ERR_NEEDS_CHECKS, ERR_NOT_UP_TO_DATE, | 15 | ERR_CONFLICT, ERR_DRAFT, ERR_HEAD_MISSING, ERR_NEEDS_CHECKS, ERR_NOT_UP_TO_DATE, |
| 12 | ERR_QUEUE_ALREADY, finish_merge, merge_commit, merge_gate, | 16 | ERR_QUEUE_ALREADY, finish_merge, merge_commit, merge_gate, |
| @@ -225,9 +229,52 @@ async fn start( |
| 225 | pr.issue.number, | 229 | pr.issue.number, |
| 226 | ) | 230 | ) |
| 227 | .await?; | 231 | .await?; |
| | 232 | + schedule_timeout(state, repo, &entry.id, &entry.branch, &tested); |
| 228 | Ok(true) | 233 | Ok(true) |
| 229 | } | 234 | } |
| 230 | | 235 | |
| | 236 | +pub fn spawn_resume(state: AppState) { |
| | 237 | + tokio::spawn(async move { |
| | 238 | + let entries = match state.store.queue_testing_all().await { |
| | 239 | + Ok(entries) => entries, |
| | 240 | + Err(e) => { |
| | 241 | + tracing::error!(error = %e, "merge queue: listing testing entries failed"); |
| | 242 | + return; |
| | 243 | + } |
| | 244 | + }; |
| | 245 | + for entry in entries { |
| | 246 | + let repo = match state.store.repo_by_id(&entry.repo_id).await { |
| | 247 | + Ok(Some(repo)) => repo, |
| | 248 | + Ok(None) => continue, |
| | 249 | + Err(e) => { |
| | 250 | + tracing::error!(error = %e, repo_id = %entry.repo_id, "merge queue: loading a repo failed"); |
| | 251 | + continue; |
| | 252 | + } |
| | 253 | + }; |
| | 254 | + let tested = entry.tested_oid.clone().unwrap_or_default(); |
| | 255 | + schedule_timeout(&state, &repo, &entry.id, &entry.branch, &tested); |
| | 256 | + } |
| | 257 | + }); |
| | 258 | +} |
| | 259 | + |
| | 260 | +fn schedule_timeout(state: &AppState, repo: &Repo, entry_id: &str, branch: &str, tested: &str) { |
| | 261 | + let state = state.clone(); |
| | 262 | + let repo = repo.clone(); |
| | 263 | + let entry_id = entry_id.to_string(); |
| | 264 | + let branch = branch.to_string(); |
| | 265 | + let tested = tested.to_string(); |
| | 266 | + tokio::spawn(async move { |
| | 267 | + tokio::time::sleep(check_timeout(&state, &repo.id, &tested).await).await; |
| | 268 | + match evaluate(&state, &repo, &entry_id).await { |
| | 269 | + Ok(true) => advance(&state, &repo, &branch).await, |
| | 270 | + Ok(false) => {} |
| | 271 | + Err(e) => { |
| | 272 | + tracing::error!(error = %e, repo_id = %repo.id, "merge queue: timeout check failed"); |
| | 273 | + } |
| | 274 | + } |
| | 275 | + }); |
| | 276 | +} |
| | 277 | + |
| 231 | pub async fn evaluate(state: &AppState, repo: &Repo, entry_id: &str) -> forge_core::Result<bool> { | 278 | pub async fn evaluate(state: &AppState, repo: &Repo, entry_id: &str) -> forge_core::Result<bool> { |
| 232 | let Some(entry) = state.store.queue_entry(entry_id).await? else { | 279 | let Some(entry) = state.store.queue_entry(entry_id).await? else { |
| 233 | return Ok(true); | 280 | return Ok(true); |
| @@ -271,7 +318,7 @@ pub async fn evaluate(state: &AppState, repo: &Repo, entry_id: &str) -> forge_co |
| 271 | let rule = effective(&rules, &repo.default_branch, &entry.branch); | 318 | let rule = effective(&rules, &repo.default_branch, &entry.branch); |
| 272 | if !rule.required_checks.is_empty() { | 319 | if !rule.required_checks.is_empty() { |
| 273 | let statuses = state.store.statuses_for(&repo.id, &tested).await?; | 320 | let statuses = state.store.statuses_for(&repo.id, &tested).await?; |
| 274 | - let mut waiting = false; | 321 | + let mut missing: Option<&String> = None; |
| 275 | for context in &rule.required_checks { | 322 | for context in &rule.required_checks { |
| 276 | match statuses | 323 | match statuses |
| 277 | .iter() | 324 | .iter() |
| @@ -285,16 +332,34 @@ pub async fn evaluate(state: &AppState, repo: &Repo, entry_id: &str) -> forge_co |
| 285 | fail(state, repo, &entry, &pr, "checks_failed", &text).await?; | 332 | fail(state, repo, &entry, &pr, "checks_failed", &text).await?; |
| 286 | return Ok(true); | 333 | return Ok(true); |
| 287 | } | 334 | } |
| 288 | - _ => waiting = true, | 335 | + _ => { |
| | 336 | + missing.get_or_insert(context); |
| | 337 | + } |
| 289 | } | 338 | } |
| 290 | } | 339 | } |
| 291 | - if waiting { | 340 | + if let Some(context) = missing { |
| | 341 | + let timeout = check_timeout(state, &repo.id, &tested).await; |
| | 342 | + if entry.updated_at <= stamp_ago(timeout) { |
| | 343 | + let text = format!( |
| | 344 | + "the required check {context} was not reported on the merge candidate in time." |
| | 345 | + ); |
| | 346 | + fail(state, repo, &entry, &pr, "checks_missing", &text).await?; |
| | 347 | + return Ok(true); |
| | 348 | + } |
| 292 | return Ok(false); | 349 | return Ok(false); |
| 293 | } | 350 | } |
| 294 | } | 351 | } |
| 295 | land(state, repo, &entry, &pr).await | 352 | land(state, repo, &entry, &pr).await |
| 296 | } | 353 | } |
| 297 | | 354 | |
| | 355 | +async fn check_timeout(state: &AppState, repo_id: &str, commit: &str) -> Duration { |
| | 356 | + let minutes = config_at(state, repo_id, commit) |
| | 357 | + .await |
| | 358 | + .and_then(|cfg| cfg.jobs.values().map(|job| job.timeout_minutes).max()) |
| | 359 | + .unwrap_or(DEFAULT_TIMEOUT_MINUTES); |
| | 360 | + Duration::from_secs(60 * u64::from(minutes)) |
| | 361 | +} |
| | 362 | + |
| 298 | async fn land( | 363 | async fn land( |
| 299 | state: &AppState, | 364 | state: &AppState, |
| 300 | repo: &Repo, | 365 | repo: &Repo, |
| @@ -23,15 +23,17 @@ async fn run(state: AppState) { |
| 23 | let mut running_mirrors: HashSet<String> = HashSet::new(); | 23 | let mut running_mirrors: HashSet<String> = HashSet::new(); |
| 24 | let mut running_repos: HashSet<String> = HashSet::new(); | 24 | let mut running_repos: HashSet<String> = HashSet::new(); |
| 25 | loop { | 25 | loop { |
| | 26 | + let now = now_stamp(); |
| 26 | claim( | 27 | claim( |
| 27 | &state, | 28 | &state, |
| 28 | &policy, | 29 | &policy, |
| | 30 | + &now, |
| 29 | &done_tx, | 31 | &done_tx, |
| 30 | &mut running_mirrors, | 32 | &mut running_mirrors, |
| 31 | &mut running_repos, | 33 | &mut running_repos, |
| 32 | ) | 34 | ) |
| 33 | .await; | 35 | .await; |
| 34 | - let nap = match state.store.next_mirror_due().await { | 36 | + let nap = match state.store.next_mirror_due(&now).await { |
| 35 | Ok(next) => sleep_until(next.as_deref(), OffsetDateTime::now_utc(), BACKSTOP), | 37 | Ok(next) => sleep_until(next.as_deref(), OffsetDateTime::now_utc(), BACKSTOP), |
| 36 | Err(e) => { | 38 | Err(e) => { |
| 37 | tracing::error!(error = %e, "mirrors: could not read the next due time"); | 39 | tracing::error!(error = %e, "mirrors: could not read the next due time"); |
| @@ -52,11 +54,12 @@ async fn run(state: AppState) { |
| 52 | async fn claim( | 54 | async fn claim( |
| 53 | state: &AppState, | 55 | state: &AppState, |
| 54 | policy: &WebhookPolicy, | 56 | policy: &WebhookPolicy, |
| | 57 | + now: &str, |
| 55 | done_tx: &mpsc::UnboundedSender<(String, String)>, | 58 | done_tx: &mpsc::UnboundedSender<(String, String)>, |
| 56 | running_mirrors: &mut HashSet<String>, | 59 | running_mirrors: &mut HashSet<String>, |
| 57 | running_repos: &mut HashSet<String>, | 60 | running_repos: &mut HashSet<String>, |
| 58 | ) { | 61 | ) { |
| 59 | - let due = match state.store.due_mirrors(&now_stamp(), CLAIM_BATCH).await { | 62 | + let due = match state.store.due_mirrors(now, CLAIM_BATCH).await { |
| 60 | Ok(due) => due, | 63 | Ok(due) => due, |
| 61 | Err(e) => { | 64 | Err(e) => { |
| 62 | tracing::error!(error = %e, "mirrors: could not list due mirrors"); | 65 | tracing::error!(error = %e, "mirrors: could not list due mirrors"); |
| @@ -1,7 +1,7 @@ |
| 1 | use forge_core::User; | 1 | use forge_core::User; |
| 2 | use forge_core::oci as rules; | 2 | use forge_core::oci as rules; |
| 3 | use forge_core::packages::{KIND_OCI, Package}; | 3 | use forge_core::packages::{KIND_OCI, Package}; |
| 4 | -use forge_core::time::unix_now; | 4 | +use forge_core::time::now_unix; |
| 5 | use http::header::{AUTHORIZATION, HeaderValue, WWW_AUTHENTICATE}; | 5 | use http::header::{AUTHORIZATION, HeaderValue, WWW_AUTHENTICATE}; |
| 6 | use topcoat::context::{Cx, context}; | 6 | use topcoat::context::{Cx, context}; |
| 7 | use topcoat::router::StatusCode; | 7 | use topcoat::router::StatusCode; |
| @@ -37,7 +37,7 @@ pub async fn caller(cx: &Cx) -> Result<Caller, Refusal> { |
| 37 | if let Some(bearer) = value.strip_prefix("Bearer ").map(str::trim) | 37 | if let Some(bearer) = value.strip_prefix("Bearer ").map(str::trim) |
| 38 | && !bearer.starts_with("forge_") | 38 | && !bearer.starts_with("forge_") |
| 39 | { | 39 | { |
| 40 | - let now = unix_now() as i64; | 40 | + let now = now_unix(); |
| 41 | return match rules::verify_token(&state.key, bearer, now) { | 41 | return match rules::verify_token(&state.key, bearer, now) { |
| 42 | Some(Some(user_id)) => match state.store.user_by_id(&user_id).await { | 42 | Some(Some(user_id)) => match state.store.user_by_id(&user_id).await { |
| 43 | Ok(Some(user)) if !user.is_org() => Ok(Caller { user: Some(user) }), | 43 | Ok(Some(user)) if !user.is_org() => Ok(Caller { user: Some(user) }), |
| @@ -1,4 +1,4 @@ |
| 1 | -use std::time::Duration; | 1 | +use std::time::{Duration, SystemTime}; |
| 2 | | 2 | |
| 3 | use tokio::sync::{Mutex, MutexGuard}; | 3 | use tokio::sync::{Mutex, MutexGuard}; |
| 4 | | 4 | |
| @@ -13,6 +13,27 @@ pub async fn lock() -> MutexGuard<'static, ()> { |
| 13 | LOCK.lock().await | 13 | LOCK.lock().await |
| 14 | } | 14 | } |
| 15 | | 15 | |
| | 16 | +pub async fn sweep_orphans(state: &AppState) -> forge_core::Result<usize> { |
| | 17 | + let cutoff = SystemTime::now() - GRACE; |
| | 18 | + let mut removed = 0; |
| | 19 | + for key in state.blobs.keys_older_than("oci/", cutoff).await? { |
| | 20 | + let Some(hex) = key.strip_prefix("oci/") else { |
| | 21 | + continue; |
| | 22 | + }; |
| | 23 | + let _guard = lock().await; |
| | 24 | + if state |
| | 25 | + .store |
| | 26 | + .oci_digest_linked(&format!("sha256:{hex}")) |
| | 27 | + .await? |
| | 28 | + { |
| | 29 | + continue; |
| | 30 | + } |
| | 31 | + state.blobs.delete(&key).await?; |
| | 32 | + removed += 1; |
| | 33 | + } |
| | 34 | + Ok(removed) |
| | 35 | +} |
| | 36 | + |
| 16 | pub async fn sweep(state: &AppState, package_id: &str) -> forge_core::Result<usize> { | 37 | pub async fn sweep(state: &AppState, package_id: &str) -> forge_core::Result<usize> { |
| 17 | let _guard = lock().await; | 38 | let _guard = lock().await; |
| 18 | let linked_before = forge_core::time::stamp_ago(GRACE); | 39 | let linked_before = forge_core::time::stamp_ago(GRACE); |
| @@ -13,9 +13,7 @@ use crate::pulls_sync; |
| 13 | use crate::state::AppState; | 13 | use crate::state::AppState; |
| 14 | use crate::webhooks::emit::{Sender, emit_item_action, emit_ref_update, lookup_sender}; | 14 | use crate::webhooks::emit::{Sender, emit_item_action, emit_ref_update, lookup_sender}; |
| 15 | | 15 | |
| 16 | -const MAX_PUSH_COMMITS: usize = 500; | 16 | +const COMMIT_PAGE: usize = 100; |
| 17 | -const MAX_NEW_BRANCH_COMMITS: usize = 50; | | |
| 18 | -const MAX_COAUTHOR_COMMITS: usize = 200; | | |
| 19 | | 17 | |
| 20 | pub async fn after_ref_update( | 18 | pub async fn after_ref_update( |
| 21 | state: &AppState, | 19 | state: &AppState, |
| @@ -94,19 +92,32 @@ async fn pushed_commits( |
| 94 | repo_dir: &Path, | 92 | repo_dir: &Path, |
| 95 | old: &str, | 93 | old: &str, |
| 96 | new: &str, | 94 | new: &str, |
| 97 | - max_update: usize, | | |
| 98 | ) -> Option<Vec<CommitInfo>> { | 95 | ) -> Option<Vec<CommitInfo>> { |
| 99 | let old = (!is_zero_oid(old)).then_some(old); | 96 | let old = (!is_zero_oid(old)).then_some(old); |
| 100 | - let max = if old.is_some() { | 97 | + let mut commits: Vec<CommitInfo> = Vec::new(); |
| 101 | - max_update | 98 | + loop { |
| 102 | - } else { | 99 | + let page = match history::new_commits( |
| 103 | - MAX_NEW_BRANCH_COMMITS | 100 | + &state.git, |
| 104 | - }; | 101 | + repo_dir, |
| 105 | - match history::new_commits(&state.git, repo_dir, old, new, max).await { | 102 | + old, |
| 106 | - Ok(commits) => Some(commits), | 103 | + new, |
| 107 | - Err(e) => { | 104 | + commits.len(), |
| 108 | - tracing::error!(error = %e, repo_id = %repo.id, "pushed commits: listing failed"); | 105 | + COMMIT_PAGE, |
| 109 | - None | 106 | + ) |
| | 107 | + .await |
| | 108 | + { |
| | 109 | + Ok(page) => page, |
| | 110 | + Err(e) => { |
| | 111 | + tracing::error!(error = %e, repo_id = %repo.id, "pushed commits: listing failed"); |
| | 112 | + return None; |
| | 113 | + } |
| | 114 | + }; |
| | 115 | + let full = page.len() == COMMIT_PAGE; |
| | 116 | + let mut older = page; |
| | 117 | + older.append(&mut commits); |
| | 118 | + commits = older; |
| | 119 | + if !full { |
| | 120 | + return Some(commits); |
| 110 | } | 121 | } |
| 111 | } | 122 | } |
| 112 | } | 123 | } |
| @@ -120,9 +131,7 @@ async fn close_from_pushed_commits( |
| 120 | old: String, | 131 | old: String, |
| 121 | new: String, | 132 | new: String, |
| 122 | ) { | 133 | ) { |
| 123 | - let Some(commits) = | 134 | + let Some(commits) = pushed_commits(&state, &repo, &repo_dir, &old, &new).await else { |
| 124 | - pushed_commits(&state, &repo, &repo_dir, &old, &new, MAX_PUSH_COMMITS).await | | |
| 125 | - else { | | |
| 126 | return; | 135 | return; |
| 127 | }; | 136 | }; |
| 128 | let actor = (!actor_id.is_empty()).then_some(actor_id.as_str()); | 137 | let actor = (!actor_id.is_empty()).then_some(actor_id.as_str()); |
| @@ -142,9 +151,7 @@ async fn credit_coauthors( |
| 142 | old: String, | 151 | old: String, |
| 143 | new: String, | 152 | new: String, |
| 144 | ) { | 153 | ) { |
| 145 | - let Some(commits) = | 154 | + let Some(commits) = pushed_commits(&state, &repo, &repo_dir, &old, &new).await else { |
| 146 | - pushed_commits(&state, &repo, &repo_dir, &old, &new, MAX_COAUTHOR_COMMITS).await | | |
| 147 | - else { | | |
| 148 | return; | 155 | return; |
| 149 | }; | 156 | }; |
| 150 | let actor = (!actor_id.is_empty()).then_some(actor_id.as_str()); | 157 | let actor = (!actor_id.is_empty()).then_some(actor_id.as_str()); |
| @@ -45,6 +45,9 @@ async fn sweep(state: &AppState) { |
| 45 | Err(e) => tracing::error!(error = %e, repo_id = %id, "prune failed"), | 45 | Err(e) => tracing::error!(error = %e, repo_id = %id, "prune failed"), |
| 46 | } | 46 | } |
| 47 | } | 47 | } |
| | 48 | + if let Err(e) = crate::oci::gc::sweep_orphans(state).await { |
| | 49 | + tracing::error!(error = %e, "prune: oci orphan sweep failed"); |
| | 50 | + } |
| 48 | } | 51 | } |
| 49 | | 52 | |
| 50 | async fn blank_unreachable_messages(state: &AppState, repo_id: &str, dir: &Path) { | 53 | async fn blank_unreachable_messages(state: &AppState, repo_id: &str, dir: &Path) { |
| @@ -312,7 +312,7 @@ pub async fn refresh_mergeability( |
| 312 | mod tests { | 312 | mod tests { |
| 313 | use std::path::{Path, PathBuf}; | 313 | use std::path::{Path, PathBuf}; |
| 314 | | 314 | |
| 315 | - use forge_core::{IssueState, Visibility}; | 315 | + use forge_core::{IssueState, NewPull, Visibility}; |
| 316 | use forge_git::repo::{init_bare, repo_path}; | 316 | use forge_git::repo::{init_bare, repo_path}; |
| 317 | use tempfile::TempDir; | 317 | use tempfile::TempDir; |
| 318 | | 318 | |
| @@ -440,17 +440,17 @@ mod tests { |
| 440 | let pr = fx | 440 | let pr = fx |
| 441 | .state | 441 | .state |
| 442 | .store | 442 | .store |
| 443 | - .create_pull( | 443 | + .create_pull(&NewPull { |
| 444 | - &fx.repo.id, | 444 | + repo_id: &fx.repo.id, |
| 445 | - &fx.owner_id, | 445 | + author_id: &fx.owner_id, |
| 446 | - "Feature", | 446 | + title: "Feature", |
| 447 | - "", | 447 | + body: "", |
| 448 | - "main", | 448 | + base_branch: "main", |
| 449 | - &fx.repo.id, | 449 | + head_repo_id: &fx.repo.id, |
| 450 | - "feature", | 450 | + head_branch: "feature", |
| 451 | - &f1, | 451 | + head_oid: &f1, |
| 452 | - &base, | 452 | + base_oid: &base, |
| 453 | - ) | 453 | + }) |
| 454 | .await | 454 | .await |
| 455 | .expect("create pull"); | 455 | .expect("create pull"); |
| 456 | let number = pr.issue.number; | 456 | let number = pr.issue.number; |
| @@ -492,17 +492,17 @@ mod tests { |
| 492 | let pr = fx | 492 | let pr = fx |
| 493 | .state | 493 | .state |
| 494 | .store | 494 | .store |
| 495 | - .create_pull( | 495 | + .create_pull(&NewPull { |
| 496 | - &fx.repo.id, | 496 | + repo_id: &fx.repo.id, |
| 497 | - &fx.owner_id, | 497 | + author_id: &fx.owner_id, |
| 498 | - "Feature", | 498 | + title: "Feature", |
| 499 | - "", | 499 | + body: "", |
| 500 | - "main", | 500 | + base_branch: "main", |
| 501 | - &fx.repo.id, | 501 | + head_repo_id: &fx.repo.id, |
| 502 | - "feature", | 502 | + head_branch: "feature", |
| 503 | - &f1, | 503 | + head_oid: &f1, |
| 504 | - &base, | 504 | + base_oid: &base, |
| 505 | - ) | 505 | + }) |
| 506 | .await | 506 | .await |
| 507 | .expect("create pull"); | 507 | .expect("create pull"); |
| 508 | let zero = "0".repeat(40); | 508 | let zero = "0".repeat(40); |
| @@ -540,17 +540,17 @@ mod tests { |
| 540 | let pr = fx | 540 | let pr = fx |
| 541 | .state | 541 | .state |
| 542 | .store | 542 | .store |
| 543 | - .create_pull( | 543 | + .create_pull(&NewPull { |
| 544 | - &fx.repo.id, | 544 | + repo_id: &fx.repo.id, |
| 545 | - &fx.owner_id, | 545 | + author_id: &fx.owner_id, |
| 546 | - "Feature", | 546 | + title: "Feature", |
| 547 | - "", | 547 | + body: "", |
| 548 | - "main", | 548 | + base_branch: "main", |
| 549 | - &fx.repo.id, | 549 | + head_repo_id: &fx.repo.id, |
| 550 | - "feature", | 550 | + head_branch: "feature", |
| 551 | - &f1, | 551 | + head_oid: &f1, |
| 552 | - &base, | 552 | + base_oid: &base, |
| 553 | - ) | 553 | + }) |
| 554 | .await | 554 | .await |
| 555 | .expect("create pull"); | 555 | .expect("create pull"); |
| 556 | assert_eq!(pr.mergeable, Mergeable::Unknown); | 556 | assert_eq!(pr.mergeable, Mergeable::Unknown); |
| @@ -580,17 +580,17 @@ mod tests { |
| 580 | let pr = fx | 580 | let pr = fx |
| 581 | .state | 581 | .state |
| 582 | .store | 582 | .store |
| 583 | - .create_pull( | 583 | + .create_pull(&NewPull { |
| 584 | - &fx.repo.id, | 584 | + repo_id: &fx.repo.id, |
| 585 | - &fx.owner_id, | 585 | + author_id: &fx.owner_id, |
| 586 | - "Feature", | 586 | + title: "Feature", |
| 587 | - "", | 587 | + body: "", |
| 588 | - "main", | 588 | + base_branch: "main", |
| 589 | - &fx.repo.id, | 589 | + head_repo_id: &fx.repo.id, |
| 590 | - "feature", | 590 | + head_branch: "feature", |
| 591 | - &f1, | 591 | + head_oid: &f1, |
| 592 | - &base, | 592 | + base_oid: &base, |
| 593 | - ) | 593 | + }) |
| 594 | .await | 594 | .await |
| 595 | .expect("create pull"); | 595 | .expect("create pull"); |
| 596 | let store = &fx.state.store; | 596 | let store = &fx.state.store; |
| @@ -651,17 +651,17 @@ mod tests { |
| 651 | let pr = fx | 651 | let pr = fx |
| 652 | .state | 652 | .state |
| 653 | .store | 653 | .store |
| 654 | - .create_pull( | 654 | + .create_pull(&NewPull { |
| 655 | - &fx.repo.id, | 655 | + repo_id: &fx.repo.id, |
| 656 | - &fx.owner_id, | 656 | + author_id: &fx.owner_id, |
| 657 | - "Feature", | 657 | + title: "Feature", |
| 658 | - "", | 658 | + body: "", |
| 659 | - "main", | 659 | + base_branch: "main", |
| 660 | - &fx.repo.id, | 660 | + head_repo_id: &fx.repo.id, |
| 661 | - "feature", | 661 | + head_branch: "feature", |
| 662 | - &f1, | 662 | + head_oid: &f1, |
| 663 | - &base, | 663 | + base_oid: &base, |
| 664 | - ) | 664 | + }) |
| 665 | .await | 665 | .await |
| 666 | .expect("create pull"); | 666 | .expect("create pull"); |
| 667 | | 667 | |
| @@ -716,17 +716,17 @@ mod tests { |
| 716 | let pr = fx | 716 | let pr = fx |
| 717 | .state | 717 | .state |
| 718 | .store | 718 | .store |
| 719 | - .create_pull( | 719 | + .create_pull(&NewPull { |
| 720 | - &fx.repo.id, | 720 | + repo_id: &fx.repo.id, |
| 721 | - &fx.owner_id, | 721 | + author_id: &fx.owner_id, |
| 722 | - "Feature", | 722 | + title: "Feature", |
| 723 | - "", | 723 | + body: "", |
| 724 | - "main", | 724 | + base_branch: "main", |
| 725 | - &fx.repo.id, | 725 | + head_repo_id: &fx.repo.id, |
| 726 | - "feature", | 726 | + head_branch: "feature", |
| 727 | - &f1, | 727 | + head_oid: &f1, |
| 728 | - &base, | 728 | + base_oid: &base, |
| 729 | - ) | 729 | + }) |
| 730 | .await | 730 | .await |
| 731 | .expect("create pull"); | 731 | .expect("create pull"); |
| 732 | let store = &fx.state.store; | 732 | let store = &fx.state.store; |
| @@ -782,17 +782,17 @@ mod tests { |
| 782 | let pr = fx | 782 | let pr = fx |
| 783 | .state | 783 | .state |
| 784 | .store | 784 | .store |
| 785 | - .create_pull( | 785 | + .create_pull(&NewPull { |
| 786 | - &fx.repo.id, | 786 | + repo_id: &fx.repo.id, |
| 787 | - &fx.owner_id, | 787 | + author_id: &fx.owner_id, |
| 788 | - "Feature", | 788 | + title: "Feature", |
| 789 | - "", | 789 | + body: "", |
| 790 | - "main", | 790 | + base_branch: "main", |
| 791 | - &fx.repo.id, | 791 | + head_repo_id: &fx.repo.id, |
| 792 | - "feature", | 792 | + head_branch: "feature", |
| 793 | - &f1, | 793 | + head_oid: &f1, |
| 794 | - &base, | 794 | + base_oid: &base, |
| 795 | - ) | 795 | + }) |
| 796 | .await | 796 | .await |
| 797 | .expect("create pull"); | 797 | .expect("create pull"); |
| 798 | fx.state | 798 | fx.state |
| @@ -1,5 +1,10 @@ |
| | 1 | +use std::fmt::Debug; |
| 1 | use std::path::{Path, PathBuf}; | 2 | use std::path::{Path, PathBuf}; |
| 2 | use std::process::Command; | 3 | use std::process::Command; |
| | 4 | +use std::time::Duration; |
| | 5 | + |
| | 6 | +use bytes::Bytes; |
| | 7 | +use futures_util::{Stream, StreamExt}; |
| 3 | | 8 | |
| 4 | use forge_core::{Store, Visibility}; | 9 | use forge_core::{Store, Visibility}; |
| 5 | | 10 | |
| @@ -149,3 +154,81 @@ pub async fn get(router: &Router, uri: &str) -> (u16, http::HeaderMap, Vec<u8>) |
| 149 | .to_vec(); | 154 | .to_vec(); |
| 150 | (status, headers, body) | 155 | (status, headers, body) |
| 151 | } | 156 | } |
| | 157 | + |
| | 158 | +pub struct Reply { |
| | 159 | + pub status: u16, |
| | 160 | + pub location: Option<String>, |
| | 161 | + pub body: String, |
| | 162 | +} |
| | 163 | + |
| | 164 | +pub async fn send( |
| | 165 | + router: &Router, |
| | 166 | + method: &str, |
| | 167 | + uri: &str, |
| | 168 | + cookie: Option<&str>, |
| | 169 | + fields: Option<&[(&str, &str)]>, |
| | 170 | +) -> Reply { |
| | 171 | + let form = fields.map(|fields| { |
| | 172 | + form_urlencoded::Serializer::new(String::new()) |
| | 173 | + .extend_pairs(fields) |
| | 174 | + .finish() |
| | 175 | + }); |
| | 176 | + send_form(router, method, uri, cookie, form).await |
| | 177 | +} |
| | 178 | + |
| | 179 | +pub async fn send_form( |
| | 180 | + router: &Router, |
| | 181 | + method: &str, |
| | 182 | + uri: &str, |
| | 183 | + cookie: Option<&str>, |
| | 184 | + form: Option<String>, |
| | 185 | +) -> Reply { |
| | 186 | + let mut builder = Request::builder().method(method).uri(uri); |
| | 187 | + if let Some(cookie) = cookie { |
| | 188 | + builder = builder.header("cookie", cookie); |
| | 189 | + } |
| | 190 | + let body = match form { |
| | 191 | + Some(form) => { |
| | 192 | + builder = builder.header("content-type", "application/x-www-form-urlencoded"); |
| | 193 | + Body::from(form) |
| | 194 | + } |
| | 195 | + None => Body::empty(), |
| | 196 | + }; |
| | 197 | + let res = router.handle(builder.body(body).expect("request")).await; |
| | 198 | + let status = res.status().as_u16(); |
| | 199 | + let location = res |
| | 200 | + .headers() |
| | 201 | + .get("location") |
| | 202 | + .and_then(|v| v.to_str().ok()) |
| | 203 | + .map(str::to_owned); |
| | 204 | + let bytes = to_bytes(res.into_body(), usize::MAX).await.expect("body"); |
| | 205 | + Reply { |
| | 206 | + status, |
| | 207 | + location, |
| | 208 | + body: String::from_utf8_lossy(&bytes).into_owned(), |
| | 209 | + } |
| | 210 | +} |
| | 211 | + |
| | 212 | +pub async fn next_frame<S, E>(frames: &mut S) -> Option<Vec<u8>> |
| | 213 | +where |
| | 214 | + S: Stream<Item = Result<Bytes, E>> + Unpin, |
| | 215 | + E: Debug, |
| | 216 | +{ |
| | 217 | + let frame = tokio::time::timeout(Duration::from_secs(5), frames.next()) |
| | 218 | + .await |
| | 219 | + .expect("a frame within five seconds")?; |
| | 220 | + Some(frame.expect("data").to_vec()) |
| | 221 | +} |
| | 222 | + |
| | 223 | +pub async fn next_event<S, E>(frames: &mut S) -> Option<Vec<u8>> |
| | 224 | +where |
| | 225 | + S: Stream<Item = Result<Bytes, E>> + Unpin, |
| | 226 | + E: Debug, |
| | 227 | +{ |
| | 228 | + loop { |
| | 229 | + let bytes = next_frame(frames).await?; |
| | 230 | + if !bytes.starts_with(b"retry: ") { |
| | 231 | + return Some(bytes); |
| | 232 | + } |
| | 233 | + } |
| | 234 | +} |
| @@ -779,7 +779,7 @@ async fn inline_comment_form(cx: &Cx, form: InlineForm, lang: Lang) -> Result<im |
| 779 | if let Some(text) = suggest_line { | 779 | if let Some(text) = suggest_line { |
| 780 | <button type="button" class="act" data-suggest=(text.as_str())>(suggest_label)</button> | 780 | <button type="button" class="act" data-suggest=(text.as_str())>(suggest_label)</button> |
| 781 | } | 781 | } |
| 782 | - <a class="act" href=(cancel_href.as_str())>(g::t(lang, K::CancelLink))</a> | 782 | + <a class="act" href=(cancel_href.as_str())>(crate::i18n::t(lang, crate::i18n::Key::Cancel))</a> |
| 783 | </div> | 783 | </div> |
| 784 | </form> | 784 | </form> |
| 785 | }) | 785 | }) |
| @@ -3,6 +3,7 @@ pub mod commit_status; |
| 3 | pub mod diff; | 3 | pub mod diff; |
| 4 | pub mod find; | 4 | pub mod find; |
| 5 | pub mod heatmap; | 5 | pub mod heatmap; |
| | 6 | +pub mod paging; |
| 6 | pub mod parts; | 7 | pub mod parts; |
| 7 | pub mod repo_list; | 8 | pub mod repo_list; |
| 8 | pub mod review_thread; | 9 | pub mod review_thread; |
| @@ -12,7 +13,7 @@ use std::collections::HashMap; |
| 12 | use std::sync::OnceLock; | 13 | use std::sync::OnceLock; |
| 13 | | 14 | |
| 14 | use forge_core::ci::RunState; | 15 | use forge_core::ci::RunState; |
| 15 | -use forge_core::config::BannerConfig; | 16 | +use forge_core::config::{BannerConfig, BannerLevel}; |
| 16 | use forge_core::store::shell_activity::{ActorRun, ActorRuns, InboxKinds}; | 17 | use forge_core::store::shell_activity::{ActorRun, ActorRuns, InboxKinds}; |
| 17 | use forge_core::store::user_prefs::SOUND; | 18 | use forge_core::store::user_prefs::SOUND; |
| 18 | use forge_core::token::hash_token; | 19 | use forge_core::token::hash_token; |
| @@ -1122,31 +1123,27 @@ pub fn repo_href(owner: &str, repo: &str, section: &str, rest: &str) -> String { |
| 1122 | href | 1123 | href |
| 1123 | } | 1124 | } |
| 1124 | | 1125 | |
| 1125 | -pub use forge_core::time::now_unix; | 1126 | +pub use forge_core::time::{civil_from_days, days_from_civil, iso_time, now_unix}; |
| 1126 | | 1127 | |
| 1127 | -pub fn iso_time(unix: i64) -> String { | 1128 | +pub fn query_value(cx: &Cx, key: &str) -> Option<String> { |
| 1128 | - let days = unix.div_euclid(86_400); | 1129 | + let query = uri(cx).query()?; |
| 1129 | - let secs = unix.rem_euclid(86_400); | 1130 | + form_urlencoded::parse(query.as_bytes()) |
| 1130 | - let (y, m, d) = civil_from_days(days); | 1131 | + .find(|(name, _)| name == key) |
| 1131 | - format!( | 1132 | + .map(|(_, value)| value.into_owned()) |
| 1132 | - "{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}Z", | | |
| 1133 | - secs / 3600, | | |
| 1134 | - secs % 3600 / 60, | | |
| 1135 | - secs % 60 | | |
| 1136 | - ) | | |
| 1137 | } | 1133 | } |
| 1138 | | 1134 | |
| 1139 | -fn civil_from_days(days: i64) -> (i64, i64, i64) { | 1135 | +pub fn take_notice_cookie<K: Copy>( |
| 1140 | - let z = days + 719_468; | 1136 | + cx: &Cx, |
| 1141 | - let era = z.div_euclid(146_097); | 1137 | + cookie: &str, |
| 1142 | - let doe = z.rem_euclid(146_097); | 1138 | + notices: &[(&str, K, bool)], |
| 1143 | - let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365; | 1139 | +) -> Option<(K, bool)> { |
| 1144 | - let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); | 1140 | + let jar = cookies(cx); |
| 1145 | - let mp = (5 * doy + 2) / 153; | 1141 | + let value = jar.get(cookie)?.value().to_owned(); |
| 1146 | - let d = doy - (153 * mp + 2) / 5 + 1; | 1142 | + jar.remove(topcoat::cookie::Cookie::build((cookie.to_owned(), "")).path("/")); |
| 1147 | - let m = if mp < 10 { mp + 3 } else { mp - 9 }; | 1143 | + notices |
| 1148 | - let y = yoe + era * 400 + i64::from(m <= 2); | 1144 | + .iter() |
| 1149 | - (y, m, d) | 1145 | + .find(|(word, _, _)| *word == value) |
| | 1146 | + .map(|(_, key, is_error)| (*key, *is_error)) |
| 1150 | } | 1147 | } |
| 1151 | | 1148 | |
| 1152 | pub fn relative_time(lang: Lang, unix: i64, now: i64) -> String { | 1149 | pub fn relative_time(lang: Lang, unix: i64, now: i64) -> String { |
| @@ -1512,16 +1509,6 @@ pub fn stamp_unix(stamp: &str) -> i64 { |
| 1512 | days_from_civil(y, mo, d) * 86_400 + h * 3_600 + mi * 60 + s | 1509 | days_from_civil(y, mo, d) * 86_400 + h * 3_600 + mi * 60 + s |
| 1513 | } | 1510 | } |
| 1514 | | 1511 | |
| 1515 | -fn days_from_civil(year: i64, month: i64, day: i64) -> i64 { | | |
| 1516 | - let y = if month <= 2 { year - 1 } else { year }; | | |
| 1517 | - let era = y.div_euclid(400); | | |
| 1518 | - let yoe = y - era * 400; | | |
| 1519 | - let mp = (month + 9) % 12; | | |
| 1520 | - let doy = (153 * mp + 2) / 5 + day - 1; | | |
| 1521 | - let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; | | |
| 1522 | - era * 146_097 + doe - 719_468 | | |
| 1523 | -} | | |
| 1524 | - | | |
| 1525 | pub fn highlight_css_text() -> &'static str { | 1512 | pub fn highlight_css_text() -> &'static str { |
| 1526 | highlight_css() | 1513 | highlight_css() |
| 1527 | } | 1514 | } |
| @@ -1584,8 +1571,8 @@ pub struct BannerView { |
| 1584 | pub expires: Option<i64>, | 1571 | pub expires: Option<i64>, |
| 1585 | } | 1572 | } |
| 1586 | | 1573 | |
| 1587 | -pub fn banner_hash(message: &str, level: &str) -> String { | 1574 | +pub fn banner_hash(message: &str, level: BannerLevel) -> String { |
| 1588 | - hash_token(&format!("{level}\n{message}"))[..16].to_owned() | 1575 | + hash_token(&format!("{}\n{message}", level.as_str()))[..16].to_owned() |
| 1589 | } | 1576 | } |
| 1590 | | 1577 | |
| 1591 | pub fn view_for(config: &BannerConfig, now: i64, dismissed: Option<&str>) -> Option<BannerView> { | 1578 | pub fn view_for(config: &BannerConfig, now: i64, dismissed: Option<&str>) -> Option<BannerView> { |
| @@ -1593,13 +1580,13 @@ pub fn view_for(config: &BannerConfig, now: i64, dismissed: Option<&str>) -> Opt |
| 1593 | return None; | 1580 | return None; |
| 1594 | } | 1581 | } |
| 1595 | let message = config.message.trim().to_owned(); | 1582 | let message = config.message.trim().to_owned(); |
| 1596 | - let hash = banner_hash(&message, &config.level); | 1583 | + let hash = banner_hash(&message, config.level); |
| 1597 | if dismissed == Some(hash.as_str()) { | 1584 | if dismissed == Some(hash.as_str()) { |
| 1598 | return None; | 1585 | return None; |
| 1599 | } | 1586 | } |
| 1600 | Some(BannerView { | 1587 | Some(BannerView { |
| 1601 | message, | 1588 | message, |
| 1602 | - warning: config.level == "warning", | 1589 | + warning: config.level == BannerLevel::Warning, |
| 1603 | hash, | 1590 | hash, |
| 1604 | expires: config.expires_unix(), | 1591 | expires: config.expires_unix(), |
| 1605 | }) | 1592 | }) |
| @@ -1640,11 +1627,6 @@ pub fn sound_attr(prefs: Option<&HashMap<String, String>>) -> Option<&'static st |
| 1640 | (stored == "on").then_some("on") | 1627 | (stored == "on").then_some("on") |
| 1641 | } | 1628 | } |
| 1642 | | 1629 | |
| 1643 | -pub fn bytes_text(bytes: u64) -> String { | | |
| 1644 | - let gib = bytes as f64 / (1u64 << 30) as f64; | | |
| 1645 | - format!("{gib:.1} GiB") | | |
| 1646 | -} | | |
| 1647 | - | | |
| 1648 | pub fn https_clone_url(config: &Config, owner: &str, name: &str) -> String { | 1630 | pub fn https_clone_url(config: &Config, owner: &str, name: &str) -> String { |
| 1649 | format!( | 1631 | format!( |
| 1650 | "{}/{owner}/{name}.git", | 1632 | "{}/{owner}/{name}.git", |
| @@ -0,0 +1,18 @@ |
| | 1 | +pub fn requested_page(raw: Option<&str>) -> u64 { |
| | 2 | + raw.and_then(|p| p.parse::<u64>().ok()).unwrap_or(1).max(1) |
| | 3 | +} |
| | 4 | + |
| | 5 | +pub fn page_count(total: u64, per_page: u64) -> u64 { |
| | 6 | + total.div_ceil(per_page).max(1) |
| | 7 | +} |
| | 8 | + |
| | 9 | +pub fn paginate<T>(items: Vec<T>, page: u64, per_page: u64) -> (Vec<T>, u64, u64) { |
| | 10 | + let pages = page_count(items.len() as u64, per_page); |
| | 11 | + let page = page.clamp(1, pages); |
| | 12 | + let shown = items |
| | 13 | + .into_iter() |
| | 14 | + .skip(((page - 1) * per_page) as usize) |
| | 15 | + .take(per_page as usize) |
| | 16 | + .collect(); |
| | 17 | + (shown, page, pages) |
| | 18 | +} |
| @@ -13,6 +13,13 @@ pub fn private_fact(lang: Lang, visibility: Visibility) -> Option<String> { |
| 13 | .then(|| format!("{} \u{b7} ", i18n::visibility_label(lang, visibility))) | 13 | .then(|| format!("{} \u{b7} ", i18n::visibility_label(lang, visibility))) |
| 14 | } | 14 | } |
| 15 | | 15 | |
| | 16 | +pub fn pick_sort<T>(raw: Option<&str>, keys: &[(&'static str, T)]) -> &'static str { |
| | 17 | + keys.iter() |
| | 18 | + .map(|(key, _)| *key) |
| | 19 | + .find(|key| Some(*key) == raw) |
| | 20 | + .unwrap_or(keys[0].0) |
| | 21 | +} |
| | 22 | + |
| 16 | pub struct RepoRow { | 23 | pub struct RepoRow { |
| 17 | href: String, | 24 | href: String, |
| 18 | title: String, | 25 | title: String, |
| @@ -5,7 +5,7 @@ use topcoat::view::{View, component, view}; |
| 5 | | 5 | |
| 6 | use super::{repo_href, short_oid}; | 6 | use super::{repo_href, short_oid}; |
| 7 | use crate::i18n::Lang; | 7 | use crate::i18n::Lang; |
| 8 | -use crate::i18n::timeline::{self as tl, K}; | 8 | +use crate::i18n::timeline as tl; |
| 9 | | 9 | |
| 10 | pub const MIN_BAR_PERCENT: u32 = 6; | 10 | pub const MIN_BAR_PERCENT: u32 = 6; |
| 11 | | 11 | |
| @@ -52,7 +52,7 @@ pub async fn history_strip( |
| 52 | let max = bars.iter().map(|bar| bar.lines).max().unwrap_or(0); | 52 | let max = bars.iter().map(|bar| bar.lines).max().unwrap_or(0); |
| 53 | let newest = bars.len().saturating_sub(1); | 53 | let newest = bars.len().saturating_sub(1); |
| 54 | let heading = tl::last_commits(lang, bars.len()); | 54 | let heading = tl::last_commits(lang, bars.len()); |
| 55 | - let aria = tl::t(lang, K::Timeline); | 55 | + let aria = crate::i18n::t(lang, crate::i18n::Key::Timeline); |
| 56 | let items: Vec<BarView> = bars | 56 | let items: Vec<BarView> = bars |
| 57 | .into_iter() | 57 | .into_iter() |
| 58 | .enumerate() | 58 | .enumerate() |
| @@ -439,7 +439,7 @@ async fn new_commits( |
| 439 | } else { | 439 | } else { |
| 440 | MAX_NEW_REF_COMMITS | 440 | MAX_NEW_REF_COMMITS |
| 441 | }; | 441 | }; |
| 442 | - let commits = match forge_git::history::new_commits(&state.git, &dir, old, new, max).await { | 442 | + let commits = match forge_git::history::new_commits(&state.git, &dir, old, new, 0, max).await { |
| 443 | Ok(commits) => commits, | 443 | Ok(commits) => commits, |
| 444 | Err(e) => { | 444 | Err(e) => { |
| 445 | tracing::error!(error = %e, repo_id = %repo.id, "webhooks: listing push commits failed"); | 445 | tracing::error!(error = %e, repo_id = %repo.id, "webhooks: listing push commits failed"); |
| @@ -459,7 +459,7 @@ async fn new_commits( |
| 459 | mod tests { | 459 | mod tests { |
| 460 | use super::*; | 460 | use super::*; |
| 461 | use crate::test_support::{KEY, test_state}; | 461 | use crate::test_support::{KEY, test_state}; |
| 462 | - use forge_core::Visibility; | 462 | + use forge_core::{NewPull, Visibility}; |
| 463 | | 463 | |
| 464 | async fn fixture(dir: &std::path::Path) -> (AppState, Repo, [String; 3]) { | 464 | async fn fixture(dir: &std::path::Path) -> (AppState, Repo, [String; 3]) { |
| 465 | let state = test_state(dir).await; | 465 | let state = test_state(dir).await; |
| @@ -671,9 +671,17 @@ mod tests { |
| 671 | let zeros = "1".repeat(40); | 671 | let zeros = "1".repeat(40); |
| 672 | let pr = state | 672 | let pr = state |
| 673 | .store | 673 | .store |
| 674 | - .create_pull( | 674 | + .create_pull(&NewPull { |
| 675 | - &repo.id, &owner.id, "Title", "", "main", &repo.id, "feat", &zeros, &zeros, | 675 | + repo_id: &repo.id, |
| 676 | - ) | 676 | + author_id: &owner.id, |
| | 677 | + title: "Title", |
| | 678 | + body: "", |
| | 679 | + base_branch: "main", |
| | 680 | + head_repo_id: &repo.id, |
| | 681 | + head_branch: "feat", |
| | 682 | + head_oid: &zeros, |
| | 683 | + base_oid: &zeros, |
| | 684 | + }) |
| 677 | .await | 685 | .await |
| 678 | .expect("pr"); | 686 | .expect("pr"); |
| 679 | let hook = hook_for( | 687 | let hook = hook_for( |
| @@ -1,6 +1,9 @@ |
| 1 | use crate::accent_palette::{BASE_DEFAULT, BASES, Base, DEFAULT, PALETTES, Palette}; | 1 | use crate::accent_palette::{BASE_DEFAULT, BASES, Base, DEFAULT, PALETTES, Palette}; |
| 2 | use crate::custom_colour; | 2 | use crate::custom_colour; |
| 3 | | 3 | |
| | 4 | +pub const ACCENT_VIVID: u8 = 50; |
| | 5 | +pub const BASE_VIVID: u8 = 30; |
| | 6 | + |
| 4 | pub fn resolve(stored: &str) -> &'static Palette { | 7 | pub fn resolve(stored: &str) -> &'static Palette { |
| 5 | PALETTES | 8 | PALETTES |
| 6 | .iter() | 9 | .iter() |
| @@ -56,7 +59,7 @@ pub fn custom_id(hue: u16, vivid: u8) -> String { |
| 56 | } | 59 | } |
| 57 | | 60 | |
| 58 | pub fn hue_of(id: &str) -> Option<u16> { | 61 | pub fn hue_of(id: &str) -> Option<u16> { |
| 59 | - custom_of(id, 50).map(|(hue, _)| hue) | 62 | + custom_of(id, ACCENT_VIVID).map(|(hue, _)| hue) |
| 60 | } | 63 | } |
| 61 | | 64 | |
| 62 | fn canonical_number(digits: &str, max: u16) -> Option<u16> { | 65 | fn canonical_number(digits: &str, max: u16) -> Option<u16> { |
| @@ -161,8 +164,8 @@ mod tests { |
| 161 | let hues = (0..360u16).map(|hue| { | 164 | let hues = (0..360u16).map(|hue| { |
| 162 | ( | 165 | ( |
| 163 | format!("hue-{hue}"), | 166 | format!("hue-{hue}"), |
| 164 | - accent_tokens(hue, 50, false), | 167 | + accent_tokens(hue, ACCENT_VIVID, false), |
| 165 | - accent_tokens(hue, 50, true), | 168 | + accent_tokens(hue, ACCENT_VIVID, true), |
| 166 | ) | 169 | ) |
| 167 | }); | 170 | }); |
| 168 | presets.chain(hues).collect() | 171 | presets.chain(hues).collect() |
| @@ -175,8 +178,8 @@ mod tests { |
| 175 | let hues = (0..360u16).map(|hue| { | 178 | let hues = (0..360u16).map(|hue| { |
| 176 | ( | 179 | ( |
| 177 | format!("hue-{hue}"), | 180 | format!("hue-{hue}"), |
| 178 | - base_tokens(hue, 30, false), | 181 | + base_tokens(hue, BASE_VIVID, false), |
| 179 | - base_tokens(hue, 30, true), | 182 | + base_tokens(hue, BASE_VIVID, true), |
| 180 | ) | 183 | ) |
| 181 | }); | 184 | }); |
| 182 | presets.chain(hues).collect() | 185 | presets.chain(hues).collect() |
| @@ -1,5 +1,6 @@ |
| 1 | use std::path::Path; | 1 | use std::path::Path; |
| 2 | use std::sync::Arc; | 2 | use std::sync::Arc; |
| | 3 | +use std::time::SystemTime; |
| 3 | | 4 | |
| 4 | use bytes::Bytes; | 5 | use bytes::Bytes; |
| 5 | use forge_core::config::{R2Config, S3Config, StorageBackend, StorageConfig}; | 6 | use forge_core::config::{R2Config, S3Config, StorageBackend, StorageConfig}; |
| @@ -160,6 +161,17 @@ impl BlobStore { |
| 160 | .map_err(storage_err) | 161 | .map_err(storage_err) |
| 161 | } | 162 | } |
| 162 | | 163 | |
| | 164 | + pub async fn keys_older_than(&self, prefix: &str, cutoff: SystemTime) -> Result<Vec<String>> { |
| | 165 | + let mut listing = self.store.list(Some(&ObjectPath::from(prefix))); |
| | 166 | + let mut keys = Vec::new(); |
| | 167 | + while let Some(meta) = listing.try_next().await.map_err(storage_err)? { |
| | 168 | + if SystemTime::from(meta.last_modified) < cutoff { |
| | 169 | + keys.push(meta.location.to_string()); |
| | 170 | + } |
| | 171 | + } |
| | 172 | + Ok(keys) |
| | 173 | + } |
| | 174 | + |
| 163 | pub async fn delete(&self, key: &str) -> Result<()> { | 175 | pub async fn delete(&self, key: &str) -> Result<()> { |
| 164 | match self.store.delete(&ObjectPath::from(key)).await { | 176 | match self.store.delete(&ObjectPath::from(key)).await { |
| 165 | Ok(()) | Err(object_store::Error::NotFound { .. }) => Ok(()), | 177 | Ok(()) | Err(object_store::Error::NotFound { .. }) => Ok(()), |
| @@ -206,6 +218,7 @@ impl BlobWriter { |
| 206 | | 218 | |
| 207 | #[cfg(test)] | 219 | #[cfg(test)] |
| 208 | mod tests { | 220 | mod tests { |
| | 221 | + use forge_core::config::R2Jurisdiction; |
| 209 | use object_store::memory::InMemory; | 222 | use object_store::memory::InMemory; |
| 210 | | 223 | |
| 211 | use super::*; | 224 | use super::*; |
| @@ -271,7 +284,7 @@ mod tests { |
| 271 | let r2 = R2Config { | 284 | let r2 = R2Config { |
| 272 | account_id: "0123abcd".into(), | 285 | account_id: "0123abcd".into(), |
| 273 | bucket: "forge".into(), | 286 | bucket: "forge".into(), |
| 274 | - jurisdiction: "eu".into(), | 287 | + jurisdiction: R2Jurisdiction::Eu, |
| 275 | prefix: "/forge/".into(), | 288 | prefix: "/forge/".into(), |
| 276 | access_key_id: "AKIA".into(), | 289 | access_key_id: "AKIA".into(), |
| 277 | secret_access_key_file: secret, | 290 | secret_access_key_file: secret, |
| @@ -69,7 +69,7 @@ const NEUTRAL_CHROMA: f64 = 0.012; |
| 69 | const GAMUT_EPS: f64 = 1e-6; | 69 | const GAMUT_EPS: f64 = 1e-6; |
| 70 | | 70 | |
| 71 | fn accent_factor(vivid: u8) -> f64 { | 71 | fn accent_factor(vivid: u8) -> f64 { |
| 72 | - if vivid == 50 { | 72 | + if vivid == crate::accent::ACCENT_VIVID { |
| 73 | return 1.0; | 73 | return 1.0; |
| 74 | } | 74 | } |
| 75 | (0.03 + 0.16 * f64::from(vivid) / 100.0) / 0.11 | 75 | (0.03 + 0.16 * f64::from(vivid) / 100.0) / 0.11 |
| @@ -104,7 +104,7 @@ pub fn accent_tokens(hue: u16, vivid: u8, dark: bool) -> OwnedTokens { |
| 104 | } | 104 | } |
| 105 | | 105 | |
| 106 | pub fn base_tokens(hue: u16, vivid: u8, dark: bool) -> OwnedBaseTokens { | 106 | pub fn base_tokens(hue: u16, vivid: u8, dark: bool) -> OwnedBaseTokens { |
| 107 | - let mut factor = f64::from(vivid) / 30.0; | 107 | + let mut factor = f64::from(vivid) / f64::from(crate::accent::BASE_VIVID); |
| 108 | let mut tokens = base_tokens_at(hue, factor, dark); | 108 | let mut tokens = base_tokens_at(hue, factor, dark); |
| 109 | for _ in 0..10 { | 109 | for _ in 0..10 { |
| 110 | if base_is_readable(&tokens) { | 110 | if base_is_readable(&tokens) { |
| @@ -357,14 +357,14 @@ mod tests { |
| 357 | fn every_hue_gives_hex_colours_with_the_right_token_names_and_keyed_rules() { | 357 | fn every_hue_gives_hex_colours_with_the_right_token_names_and_keyed_rules() { |
| 358 | for hue in 0..360 { | 358 | for hue in 0..360 { |
| 359 | for dark in [false, true] { | 359 | for dark in [false, true] { |
| 360 | - let accent = accent_tokens(hue, 50, dark); | 360 | + let accent = accent_tokens(hue, crate::accent::ACCENT_VIVID, dark); |
| 361 | let names: Vec<&str> = accent.decls().iter().map(|(n, _)| *n).collect(); | 361 | let names: Vec<&str> = accent.decls().iter().map(|(n, _)| *n).collect(); |
| 362 | let expected: Vec<&str> = TOKEN_VARS.iter().map(|t| t.name).collect(); | 362 | let expected: Vec<&str> = TOKEN_VARS.iter().map(|t| t.name).collect(); |
| 363 | assert_eq!(names, expected); | 363 | assert_eq!(names, expected); |
| 364 | for (name, value) in accent.decls() { | 364 | for (name, value) in accent.decls() { |
| 365 | assert!(is_hex_colour(value), "{hue} {dark} {name}: {value}"); | 365 | assert!(is_hex_colour(value), "{hue} {dark} {name}: {value}"); |
| 366 | } | 366 | } |
| 367 | - let base = base_tokens(hue, 30, dark); | 367 | + let base = base_tokens(hue, crate::accent::BASE_VIVID, dark); |
| 368 | let names: Vec<&str> = base.decls().iter().map(|(n, _)| *n).collect(); | 368 | let names: Vec<&str> = base.decls().iter().map(|(n, _)| *n).collect(); |
| 369 | let expected: Vec<&str> = BASE_TOKEN_VARS.iter().map(|t| t.name).collect(); | 369 | let expected: Vec<&str> = BASE_TOKEN_VARS.iter().map(|t| t.name).collect(); |
| 370 | assert_eq!(names, expected); | 370 | assert_eq!(names, expected); |
| @@ -403,8 +403,9 @@ mod tests { |
| 403 | | 403 | |
| 404 | #[test] | 404 | #[test] |
| 405 | fn legacy_and_explicit_default_vividness_give_the_same_accent() { | 405 | fn legacy_and_explicit_default_vividness_give_the_same_accent() { |
| 406 | - let legacy = crate::accent::custom_of("hue-215", 50).unwrap(); | 406 | + let legacy = crate::accent::custom_of("hue-215", crate::accent::ACCENT_VIVID).unwrap(); |
| 407 | - let explicit = crate::accent::custom_of("hue-215-v50", 50).unwrap(); | 407 | + let explicit = |
| | 408 | + crate::accent::custom_of("hue-215-v50", crate::accent::ACCENT_VIVID).unwrap(); |
| 408 | assert_eq!(legacy, explicit); | 409 | assert_eq!(legacy, explicit); |
| 409 | for dark in [false, true] { | 410 | for dark in [false, true] { |
| 410 | let a = accent_tokens(legacy.0, legacy.1, dark); | 411 | let a = accent_tokens(legacy.0, legacy.1, dark); |
| @@ -1,158 +1,55 @@ |
| 1 | use super::Lang; | 1 | use super::Lang; |
| 2 | | 2 | |
| 3 | -#[derive(Clone, Copy, Debug, PartialEq, Eq)] | 3 | +strings! { |
| 4 | -pub enum A { | 4 | + A; |
| 5 | - Active, | 5 | + Active => "Active", "Etkin"; |
| 6 | - Suspended, | 6 | + Suspended => "Suspended", "Askıda"; |
| 7 | - LastLogin, | 7 | + LastLogin => "Last sign-in", "Son giriş"; |
| 8 | - Repositories, | 8 | + Repositories => "Repositories", "Depolar"; |
| 9 | - TwoFactor, | 9 | + TwoFactor => "Two-factor", "İki adımlı doğrulama"; |
| 10 | - On, | 10 | + On => "On", "Açık"; |
| 11 | - Off, | 11 | + Off => "Off", "Kapalı"; |
| 12 | - Administrator, | 12 | + Administrator => "Administrator", "Yönetici"; |
| 13 | - Suspend, | 13 | + Suspend => "Suspend", "Askıya al"; |
| 14 | - Unsuspend, | 14 | + Unsuspend => "Lift suspension", "Askıyı kaldır"; |
| 15 | - SuspendReason, | 15 | + SuspendReason => "Reason shown on the login page", "Giriş sayfasında gösterilen neden"; |
| 16 | - GrantAdmin, | 16 | + GrantAdmin => "Make administrator", "Yönetici yap"; |
| 17 | - RevokeAdmin, | 17 | + RevokeAdmin => "Remove administrator", "Yöneticiliği kaldır"; |
| 18 | - AdminHelp, | 18 | + AdminHelp => "The last administrator cannot be demoted.", "Son yönetici yetkisiz bırakılamaz."; |
| 19 | - GenerateLink, | 19 | + GenerateLink => "Generate reset link", "Sıfırlama bağlantısı üret"; |
| 20 | - ResetLinkReady, | 20 | + ResetLinkReady => "One-time reset link. It is shown only now:", "Tek kullanımlık sıfırlama bağlantısı. Yalnızca şimdi gösterilir:"; |
| 21 | - OkSuspended, | 21 | + OkSuspended => "Account suspended.", "Hesap askıya alındı."; |
| 22 | - OkUnsuspended, | 22 | + OkUnsuspended => "Suspension lifted.", "Askı kaldırıldı."; |
| 23 | - OkAdminOn, | 23 | + OkAdminOn => "Administrator rights granted.", "Yönetici yetkisi verildi."; |
| 24 | - OkAdminOff, | 24 | + OkAdminOff => "Administrator rights removed.", "Yönetici yetkisi kaldırıldı."; |
| 25 | - Ok2faDisabled, | 25 | + Ok2faDisabled => "Two-factor disabled.", "İki adımlı doğrulama kapatıldı."; |
| 26 | - ErrSelf, | 26 | + ErrSelf => "You cannot do this to your own account.", "Bunu kendi hesabınıza yapamazsınız."; |
| 27 | - ErrNoEmail, | 27 | + ErrNoEmail => "Nothing to do.", "Yapılacak bir şey yok."; |
| 28 | - AccountSuspended, | 28 | + AccountSuspended => "This account is suspended.", "Bu hesap askıya alındı."; |
| 29 | - Dismiss, | 29 | + Dismiss => "Dismiss", "Kapat"; |
| 30 | - Health, | 30 | + Health => "Health", "Sağlık"; |
| 31 | - BackupDirectory, | 31 | + BackupDirectory => "Backup directory", "Yedek dizini"; |
| 32 | - DatabaseFile, | 32 | + DatabaseFile => "Database file", "Veritabanı dosyası"; |
| 33 | - Free, | 33 | + Free => "free of", "boş, toplam"; |
| 34 | - CiQueue, | 34 | + CiQueue => "CI queue", "CI kuyruğu"; |
| 35 | - QueuedJobs, | 35 | + QueuedJobs => "queued", "bekleyen"; |
| 36 | - RunnersOnline, | 36 | + RunnersOnline => "runners online", "çalıştırıcı çevrim içi"; |
| 37 | - MailQueue, | 37 | + MailQueue => "Mail queue", "Posta kuyruğu"; |
| 38 | - Pending, | 38 | + Pending => "pending", "bekleyen"; |
| 39 | - Failed, | 39 | + Failed => "failed", "başarısız"; |
| 40 | - LastBackup, | 40 | + LastBackup => "Last backup", "Son yedek"; |
| 41 | - Replication, | 41 | + Replication => "Replication", "Çoğaltma"; |
| 42 | - NotConfigured, | 42 | + NotConfigured => "Not configured", "Ayarlanmamış"; |
| 43 | - Unavailable, | 43 | + Unavailable => "Unavailable", "Alınamadı"; |
| 44 | - Never, | 44 | + Never => "Never", "Hiç"; |
| 45 | - Ok, | 45 | + Ok => "OK", "Tamam"; |
| 46 | - Error, | 46 | + Error => "Error", "Hata"; |
| 47 | - Lagging, | 47 | + Lagging => "Lagging", "Geride"; |
| 48 | - Storage, | 48 | + Storage => "Storage", "Depolama"; |
| 49 | - Services, | 49 | + Services => "Services", "Hizmetler"; |
| 50 | - Fine, | 50 | + Fine => "Everything looks fine", "Her şey yolunda"; |
| 51 | - DiskUsed, | 51 | + DiskUsed => "used", "kullanıldı"; |
| 52 | - Joined, | 52 | + Joined => "Joined", "Katılım"; |
| 53 | -} | | |
| 54 | - | | |
| 55 | -pub fn t(lang: Lang, key: A) -> &'static str { | | |
| 56 | - use A::*; | | |
| 57 | - use Lang::*; | | |
| 58 | - match (key, lang) { | | |
| 59 | - (Active, En) => "Active", | | |
| 60 | - (Active, Tr) => "Etkin", | | |
| 61 | - (Suspended, En) => "Suspended", | | |
| 62 | - (Suspended, Tr) => "Askıda", | | |
| 63 | - (LastLogin, En) => "Last sign-in", | | |
| 64 | - (LastLogin, Tr) => "Son giriş", | | |
| 65 | - (Repositories, En) => "Repositories", | | |
| 66 | - (Repositories, Tr) => "Depolar", | | |
| 67 | - (TwoFactor, En) => "Two-factor", | | |
| 68 | - (TwoFactor, Tr) => "İki adımlı doğrulama", | | |
| 69 | - (On, En) => "On", | | |
| 70 | - (On, Tr) => "Açık", | | |
| 71 | - (Off, En) => "Off", | | |
| 72 | - (Off, Tr) => "Kapalı", | | |
| 73 | - (Administrator, En) => "Administrator", | | |
| 74 | - (Administrator, Tr) => "Yönetici", | | |
| 75 | - (Suspend, En) => "Suspend", | | |
| 76 | - (Suspend, Tr) => "Askıya al", | | |
| 77 | - (Unsuspend, En) => "Lift suspension", | | |
| 78 | - (Unsuspend, Tr) => "Askıyı kaldır", | | |
| 79 | - (SuspendReason, En) => "Reason shown on the login page", | | |
| 80 | - (SuspendReason, Tr) => "Giriş sayfasında gösterilen neden", | | |
| 81 | - (GrantAdmin, En) => "Make administrator", | | |
| 82 | - (GrantAdmin, Tr) => "Yönetici yap", | | |
| 83 | - (RevokeAdmin, En) => "Remove administrator", | | |
| 84 | - (RevokeAdmin, Tr) => "Yöneticiliği kaldır", | | |
| 85 | - (AdminHelp, En) => "The last administrator cannot be demoted.", | | |
| 86 | - (AdminHelp, Tr) => "Son yönetici yetkisiz bırakılamaz.", | | |
| 87 | - (GenerateLink, En) => "Generate reset link", | | |
| 88 | - (GenerateLink, Tr) => "Sıfırlama bağlantısı üret", | | |
| 89 | - (ResetLinkReady, En) => "One-time reset link. It is shown only now:", | | |
| 90 | - (ResetLinkReady, Tr) => "Tek kullanımlık sıfırlama bağlantısı. Yalnızca şimdi gösterilir:", | | |
| 91 | - (OkSuspended, En) => "Account suspended.", | | |
| 92 | - (OkSuspended, Tr) => "Hesap askıya alındı.", | | |
| 93 | - (OkUnsuspended, En) => "Suspension lifted.", | | |
| 94 | - (OkUnsuspended, Tr) => "Askı kaldırıldı.", | | |
| 95 | - (OkAdminOn, En) => "Administrator rights granted.", | | |
| 96 | - (OkAdminOn, Tr) => "Yönetici yetkisi verildi.", | | |
| 97 | - (OkAdminOff, En) => "Administrator rights removed.", | | |
| 98 | - (OkAdminOff, Tr) => "Yönetici yetkisi kaldırıldı.", | | |
| 99 | - (Ok2faDisabled, En) => "Two-factor disabled.", | | |
| 100 | - (Ok2faDisabled, Tr) => "İki adımlı doğrulama kapatıldı.", | | |
| 101 | - (ErrSelf, En) => "You cannot do this to your own account.", | | |
| 102 | - (ErrSelf, Tr) => "Bunu kendi hesabınıza yapamazsınız.", | | |
| 103 | - (ErrNoEmail, En) => "Nothing to do.", | | |
| 104 | - (ErrNoEmail, Tr) => "Yapılacak bir şey yok.", | | |
| 105 | - (AccountSuspended, En) => "This account is suspended.", | | |
| 106 | - (AccountSuspended, Tr) => "Bu hesap askıya alındı.", | | |
| 107 | - (Dismiss, En) => "Dismiss", | | |
| 108 | - (Dismiss, Tr) => "Kapat", | | |
| 109 | - (Health, En) => "Health", | | |
| 110 | - (Health, Tr) => "Sağlık", | | |
| 111 | - (BackupDirectory, En) => "Backup directory", | | |
| 112 | - (BackupDirectory, Tr) => "Yedek dizini", | | |
| 113 | - (DatabaseFile, En) => "Database file", | | |
| 114 | - (DatabaseFile, Tr) => "Veritabanı dosyası", | | |
| 115 | - (Free, En) => "free of", | | |
| 116 | - (Free, Tr) => "boş, toplam", | | |
| 117 | - (CiQueue, En) => "CI queue", | | |
| 118 | - (CiQueue, Tr) => "CI kuyruğu", | | |
| 119 | - (QueuedJobs, En) => "queued", | | |
| 120 | - (QueuedJobs, Tr) => "bekleyen", | | |
| 121 | - (RunnersOnline, En) => "runners online", | | |
| 122 | - (RunnersOnline, Tr) => "çalıştırıcı çevrim içi", | | |
| 123 | - (MailQueue, En) => "Mail queue", | | |
| 124 | - (MailQueue, Tr) => "Posta kuyruğu", | | |
| 125 | - (Pending, En) => "pending", | | |
| 126 | - (Pending, Tr) => "bekleyen", | | |
| 127 | - (Failed, En) => "failed", | | |
| 128 | - (Failed, Tr) => "başarısız", | | |
| 129 | - (LastBackup, En) => "Last backup", | | |
| 130 | - (LastBackup, Tr) => "Son yedek", | | |
| 131 | - (Replication, En) => "Replication", | | |
| 132 | - (Replication, Tr) => "Çoğaltma", | | |
| 133 | - (NotConfigured, En) => "Not configured", | | |
| 134 | - (NotConfigured, Tr) => "Ayarlanmamış", | | |
| 135 | - (Unavailable, En) => "Unavailable", | | |
| 136 | - (Unavailable, Tr) => "Alınamadı", | | |
| 137 | - (Never, En) => "Never", | | |
| 138 | - (Never, Tr) => "Hiç", | | |
| 139 | - (Ok, En) => "OK", | | |
| 140 | - (Ok, Tr) => "Tamam", | | |
| 141 | - (Error, En) => "Error", | | |
| 142 | - (Error, Tr) => "Hata", | | |
| 143 | - (Lagging, En) => "Lagging", | | |
| 144 | - (Lagging, Tr) => "Geride", | | |
| 145 | - (Storage, En) => "Storage", | | |
| 146 | - (Storage, Tr) => "Depolama", | | |
| 147 | - (Services, En) => "Services", | | |
| 148 | - (Services, Tr) => "Hizmetler", | | |
| 149 | - (Fine, En) => "Everything looks fine", | | |
| 150 | - (Fine, Tr) => "Her şey yolunda", | | |
| 151 | - (DiskUsed, En) => "used", | | |
| 152 | - (DiskUsed, Tr) => "kullanıldı", | | |
| 153 | - (Joined, En) => "Joined", | | |
| 154 | - (Joined, Tr) => "Katılım", | | |
| 155 | - } | | |
| 156 | } | 53 | } |
| 157 | | 54 | |
| 158 | pub fn suspended_message(lang: Lang, reason: &str) -> String { | 55 | pub fn suspended_message(lang: Lang, reason: &str) -> String { |
| @@ -3,415 +3,135 @@ use forge_core::store::backup_runs::{RunKind, RunTrigger}; |
| 3 | | 3 | |
| 4 | use super::Lang; | 4 | use super::Lang; |
| 5 | | 5 | |
| 6 | -#[derive(Clone, Copy, Debug, PartialEq, Eq)] | 6 | +strings! { |
| 7 | -pub enum K { | 7 | + K; |
| 8 | - ActionLabel, | 8 | + ActionLabel => "Action", "İşlem"; |
| 9 | - AddARunner, | 9 | + AddARunner => "Add a runner", "Çalıştırıcı ekle"; |
| 10 | - AdminArea, | 10 | + AdminArea => "Admin", "Yönetim"; |
| 11 | - Administrator, | 11 | + Administrator => "Administrator", "Yönetici"; |
| 12 | - AllActions, | 12 | + AllActions => "All actions", "Tüm işlemler"; |
| 13 | - Anonymous, | 13 | + Anonymous => "anonymous", "anonim"; |
| 14 | - AuditLog, | 14 | + AuditLog => "Audit log", "Denetim günlüğü"; |
| 15 | - BackToRunners, | 15 | + BackToRunners => "Back to runners", "Çalıştırıcılara dön"; |
| 16 | - BackToUsers, | 16 | + BackToUsers => "Back to users", "Kullanıcılara dön"; |
| 17 | - Backups, | 17 | + Backups => "Backups", "Yedeklemeler"; |
| 18 | - CiRunners, | 18 | + CiRunners => "CI runners", "CI çalıştırıcıları"; |
| 19 | - CopyTokenNow, | 19 | + CopyTokenNow => "Shown once.", "Bir kez gösterilir."; |
| 20 | - CreateRegistrationToken, | 20 | + CreateRegistrationToken => "Create registration token", "Kayıt belirteci oluştur"; |
| 21 | - CreateUser, | 21 | + CreateUser => "Create user", "Kullanıcı oluştur"; |
| 22 | - Database, | 22 | + Database => "Database", "Veritabanı"; |
| 23 | - DatabaseErrorPrefix, | 23 | + DatabaseErrorPrefix => "Database: ", "Veritabanı: "; |
| 24 | - DeleteAccountRest, | 24 | + DeleteAccountRest => ". This cannot be undone.", " hesabını siler. Bu işlem geri alınamaz."; |
| 25 | - DeletesAccount, | 25 | + DeletesAccount => "This deletes the account ", "Bu işlem "; |
| 26 | - DeleteOrgTitle, | 26 | + DeleteOrgTitle => "Delete organization", "Kuruluşu sil"; |
| 27 | - DeleteUser, | 27 | + DeleteUser => "Delete user", "Kullanıcıyı sil"; |
| 28 | - Directory, | 28 | + Directory => "Directory", "Dizin"; |
| 29 | - Disable, | 29 | + Disable => "Disable", "Devre dışı bırak"; |
| 30 | - Disabled, | 30 | + Disabled => "disabled", "devre dışı"; |
| 31 | - Enable, | 31 | + Enable => "Enable", "Etkinleştir"; |
| 32 | - ErrAccountCannotBeDeleted, | 32 | + OpenOrgSettings => "Open organization settings", "Kuruluş ayarlarını aç"; |
| 33 | - ErrBackupsNotConfigured, | 33 | + OrgNotAUser => " is an organization.", " bir kuruluştur."; |
| 34 | - ErrChooseSecurity, | 34 | + OrgReposFirst => "Repositories it still owns:", "Hâlâ sahip olduğu depolar:"; |
| 35 | - ErrInvalidUsername, | 35 | + ErrAccountCannotBeDeleted => "this account cannot be deleted", "bu hesap silinemez"; |
| 36 | - ErrNoAddressForTest, | 36 | + ErrBackupsNotConfigured => "backups are not configured: set [backup] dir in the config file", "yedeklemeler yapılandırılmamış: yapılandırma dosyasında [backup] dir ayarını yapın"; |
| 37 | - ErrPasswordTooLong, | 37 | + ErrChooseSecurity => "choose a security option", "bir güvenlik seçeneği seçin"; |
| 38 | - ErrPortRange, | 38 | + ErrInvalidUsername => "invalid username", "geçersiz kullanıcı adı"; |
| 39 | - ErrReplicationNotConfigured, | 39 | + ErrNoAddressForTest => "your account has no email address to send the test to", "hesabınızda test iletisinin gönderileceği bir e-posta adresi yok"; |
| 40 | - ErrTestNeedsMailOn, | 40 | + ErrPasswordTooLong => "password is too long", "parola çok uzun"; |
| 41 | - ErrTypeUsernameExactly, | 41 | + ErrPortRange => "the port must be a number from 1 to 65535", "bağlantı noktası 1 ile 65535 arasında bir sayı olmalı"; |
| 42 | - Filter, | 42 | + ErrReplicationNotConfigured => "replication is not configured: set [replication] target in the config file", "çoğaltma yapılandırılmamış: yapılandırma dosyasında [replication] target ayarını yapın"; |
| 43 | - FromAddress, | 43 | + ErrTestNeedsMailOn => "turn mail on and save the settings before sending a test", "test göndermeden önce e-postayı açın ve ayarları kaydedin"; |
| 44 | - FromName, | 44 | + ErrTypeUsernameExactly => "Type the username exactly to confirm.", "Onaylamak için kullanıcı adını tam olarak yazın."; |
| 45 | - Fsck, | 45 | + Filter => "Filter", "Filtrele"; |
| 46 | - Healthcheck, | 46 | + FromAddress => "From address", "Gönderen adresi"; |
| 47 | - HealthError, | 47 | + FromName => "From name", "Gönderen adı"; |
| 48 | - HealthLagging, | 48 | + Fsck => "Fsck", "Fsck"; |
| 49 | - HealthNever, | 49 | + Healthcheck => "Healthcheck", "Sağlık denetimi"; |
| 50 | - HealthOk, | 50 | + HealthError => "error", "hata"; |
| 51 | - Invites, | 51 | + HealthLagging => "lagging", "gecikmeli"; |
| 52 | - LastDbAttempt, | 52 | + HealthNever => "never replicated", "hiç çoğaltılmadı"; |
| 53 | - LastDbSnapshotShipped, | 53 | + HealthOk => "ok", "tamam"; |
| 54 | - LastSeen, | 54 | + Invites => "Invites", "Davetler"; |
| 55 | - LastSuccess, | 55 | + LastDbAttempt => "Last database attempt", "Son veritabanı denemesi"; |
| 56 | - ServerSettings, | 56 | + LastDbSnapshotShipped => "Last database snapshot shipped", "Son gönderilen veritabanı anlık görüntüsü"; |
| 57 | - SrvSaved, | 57 | + LastSeen => "Last seen", "Son görülme"; |
| 58 | - SrvNothingChanged, | 58 | + LastSuccess => "Last success", "Son başarı"; |
| 59 | - SrvResetDone, | 59 | + ServerSettings => "Server", "Sunucu"; |
| 60 | - SrvResetToFile, | 60 | + SrvSaved => "Server settings saved.", "Sunucu ayarları kaydedildi."; |
| 61 | - SrvRestartNeeded, | 61 | + SrvNothingChanged => "Nothing changed.", "Değişiklik yok."; |
| 62 | - SrvKindLive, | 62 | + SrvResetDone => "Back to the file value.", "Dosya değerine dönüldü."; |
| 63 | - SrvKindRestart, | 63 | + SrvResetToFile => "Reset to file value", "Dosya değerine sıfırla"; |
| 64 | - SrvKindReadOnly, | 64 | + SrvRestartNeeded => "restart needed", "yeniden başlatma gerekli"; |
| 65 | - SrvSecretSet, | 65 | + SrvKindLive => "live", "canlı"; |
| 66 | - SrvSecretNotSet, | 66 | + SrvKindRestart => "restart", "yeniden başlatma"; |
| 67 | - SrvFileValue, | 67 | + SrvKindReadOnly => "read-only", "salt okunur"; |
| 68 | - SrvEmpty, | 68 | + SrvSecretSet => "set", "ayarlı"; |
| 69 | - Mail, | 69 | + SrvSecretNotSet => "not set", "ayarlı değil"; |
| 70 | - MailHost, | 70 | + SrvFileValue => "File value", "Dosya değeri"; |
| 71 | - MailTabSettings, | 71 | + SrvEmpty => "(empty)", "(boş)"; |
| 72 | - MailTabQueue, | 72 | + Mail => "Mail", "E-posta"; |
| 73 | - MailFilterAll, | 73 | + MailTabSettings => "Settings", "Ayarlar"; |
| 74 | - MailRetryNow, | 74 | + MailTabQueue => "Queue", "Kuyruk"; |
| 75 | - MailDiscard, | 75 | + MailFilterAll => "All", "Tümü"; |
| 76 | - MailRetried, | 76 | + MailRetryNow => "Retry now", "Şimdi yeniden dene"; |
| 77 | - MailNotFailed, | 77 | + MailDiscard => "Discard", "Vazgeç"; |
| 78 | - MailDiscarded, | 78 | + MailRetried => "The message is queued for another try.", "Mesaj yeniden denenmek üzere kuyruğa alındı."; |
| 79 | - MailSentAt, | 79 | + MailNotFailed => "Only a failed message can be retried or discarded, and this one is not failed.", "Yalnızca başarısız bir mesaj yeniden denenebilir ya da vazgeçilebilir; bu mesaj başarısız değil."; |
| 80 | - MailNothingMatches, | 80 | + MailDiscarded => "The message was discarded.", "Mesajdan vazgeçildi."; |
| 81 | - MailQueueEmpty, | 81 | + MailSentAt => "Sent", "Gönderildi"; |
| 82 | - MailPort, | 82 | + MailNothingMatches => "No message is in this state.", "Bu durumda ileti yok."; |
| 83 | - MailSettingsSaved, | 83 | + MailQueueEmpty => "Nothing waiting to be sent.", "Gönderilmeyi bekleyen ileti yok."; |
| 84 | - MovedToGhost, | 84 | + MailHost => "Host", "Sunucu"; |
| 85 | - NoEntries, | 85 | + MailPort => "Port", "Bağlantı noktası"; |
| 86 | - NoReposYet, | 86 | + MailSettingsSaved => "Mail settings saved.", "E-posta ayarları kaydedildi."; |
| 87 | - NoRunnersYet, | 87 | + MovedToGhost => "Moved to the ghost user:", "Hayalet kullanıcıya taşınanlar:"; |
| 88 | - NoRunnerWithId, | 88 | + NoEntries => "No entries.", "Kayıt yok."; |
| 89 | - NoRunsYet, | 89 | + NoReposYet => "No repos yet.", "Henüz depo yok."; |
| 90 | - Older, | 90 | + NoRunnersYet => "No runners registered yet.", "Henüz kayıtlı çalıştırıcı yok."; |
| 91 | - RecentRuns, | 91 | + NoRunnerWithId => "No runner has that id. Nothing was changed.", "Bu kimlikte bir çalıştırıcı yok. Hiçbir şey değiştirilmedi."; |
| 92 | - ReconcileNow, | 92 | + NoRunsYet => "No runs yet.", "Henüz çalıştırma yok."; |
| 93 | - ReconcileStarted, | 93 | + RecentRuns => "Recent runs", "Son çalıştırmalar"; |
| 94 | - RegisterARunner, | 94 | + ReconcileNow => "Reconcile now", "Şimdi uzlaştır"; |
| 95 | - RegistrationToken, | 95 | + ReconcileStarted => "Reconcile started.", "Uzlaştırma başlatıldı."; |
| 96 | - RemovedWithAccount, | 96 | + RegisterARunner => "Register a runner", "Bir çalıştırıcı kaydet"; |
| 97 | - Replication, | 97 | + RegistrationToken => "Registration token", "Kayıt belirteci"; |
| 98 | - ReplicationOff, | 98 | + RemovedWithAccount => "Removed with the account:", "Hesapla birlikte silinenler:"; |
| 99 | - Repos, | 99 | + Replication => "Replication", "Çoğaltma"; |
| 100 | - Retention, | 100 | + ReplicationOff => "Replication is off.", "Çoğaltma kapalı."; |
| 101 | - Role, | 101 | + Repos => "Repos", "Depolar"; |
| 102 | - RoleAdmin, | 102 | + Retention => "Retention", "Saklama"; |
| 103 | - RoleOrganization, | 103 | + Role => "Role", "Rol"; |
| 104 | - RoleUser, | 104 | + RoleAdmin => "admin", "yönetici"; |
| 105 | - RunBackupNow, | 105 | + RoleOrganization => "organization", "kuruluş"; |
| 106 | - RunFsckNow, | 106 | + RoleUser => "user", "kullanıcı"; |
| 107 | - RunnerDeletedNotice, | 107 | + RunBackupNow => "Run backup now", "Şimdi yedekle"; |
| 108 | - RunnerDisabledNotice, | 108 | + RunFsckNow => "Run fsck now", "Şimdi fsck çalıştır"; |
| 109 | - RunnerEnabledNotice, | 109 | + RunnerDeletedNotice => "Runner deleted.", "Çalıştırıcı silindi."; |
| 110 | - Runners, | 110 | + RunnerDisabledNotice => "Runner disabled. It will not take new jobs.", "Çalıştırıcı devre dışı bırakıldı. Yeni iş almayacak."; |
| 111 | - ScheduledBackupsOff, | 111 | + RunnerEnabledNotice => "Runner enabled.", "Çalıştırıcı etkinleştirildi."; |
| 112 | - SecurityLogTitle, | 112 | + Runners => "Runners", "Çalıştırıcılar"; |
| 113 | - SecurityNone, | 113 | + ScheduledBackupsOff => "Scheduled backups are off.", "Zamanlanmış yedeklemeler kapalı."; |
| 114 | - SendMailCheckbox, | 114 | + SecurityLogTitle => "Security log", "Güvenlik günlüğü"; |
| 115 | - SendTestMailToMe, | 115 | + SecurityNone => "None (plain text)", "Yok (düz metin)"; |
| 116 | - Settings, | 116 | + SendMailCheckbox => "Send mail", "E-posta gönder"; |
| 117 | - SmtpServer, | 117 | + SendTestMailToMe => "Send test mail to me", "Bana test e-postası gönder"; |
| 118 | - Standby, | 118 | + Settings => "Settings", "Ayarlar"; |
| 119 | - StatusFailed, | 119 | + SmtpServer => "SMTP server", "SMTP sunucusu"; |
| 120 | - StatusInProgress, | 120 | + Standby => "Standby", "Bekleme kopyası"; |
| 121 | - StatusOk, | 121 | + StatusFailed => "failed", "başarısız"; |
| 122 | - TableLastError, | 122 | + StatusInProgress => "in progress", "sürüyor"; |
| 123 | - TableQueued, | 123 | + StatusOk => "ok", "tamam"; |
| 124 | - TableTries, | 124 | + TableLastError => "Last error", "Son hata"; |
| 125 | - TestQueued, | 125 | + TableQueued => "Queued", "Kuyruğa alındı"; |
| 126 | - Token, | 126 | + TableTries => "Tries", "Deneme"; |
| 127 | - TokenCreateFailed, | 127 | + TestQueued => "Test message queued. It appears in the list when it is sent.", "Test iletisi kuyruğa alındı. Gönderildiğinde listede görünür."; |
| 128 | - TransferOrDeleteFirst, | 128 | + Token => "Token", "Belirteç"; |
| 129 | - UnknownHost, | 129 | + TokenCreateFailed => "The registration token could not be created. Nothing was changed.", "Kayıt belirteci oluşturulamadı. Hiçbir şey değiştirilmedi."; |
| 130 | - Users, | 130 | + TransferOrDeleteFirst => "Transfer or delete these repositories first:", "Önce bu depoları devredin veya silin:"; |
| 131 | - OpenOrgSettings, | 131 | + UnknownHost => "unknown", "bilinmiyor"; |
| 132 | - OrgNotAUser, | 132 | + Users => "Users", "Kullanıcılar"; |
| 133 | - OrgReposFirst, | 133 | + ViewOrg => "View organization", "Kuruluşu görüntüle"; |
| 134 | - ViewOrg, | 134 | + WhatHappens => "What happens", "Ne olacak"; |
| 135 | - WhatHappens, | | |
| 136 | -} | | |
| 137 | - | | |
| 138 | -pub fn t(lang: Lang, key: K) -> &'static str { | | |
| 139 | - use K::*; | | |
| 140 | - use Lang::*; | | |
| 141 | - match (key, lang) { | | |
| 142 | - (ActionLabel, En) => "Action", | | |
| 143 | - (ActionLabel, Tr) => "İşlem", | | |
| 144 | - (AddARunner, En) => "Add a runner", | | |
| 145 | - (AddARunner, Tr) => "Çalıştırıcı ekle", | | |
| 146 | - (AdminArea, En) => "Admin", | | |
| 147 | - (AdminArea, Tr) => "Yönetim", | | |
| 148 | - (Administrator, En) => "Administrator", | | |
| 149 | - (Administrator, Tr) => "Yönetici", | | |
| 150 | - (AllActions, En) => "All actions", | | |
| 151 | - (AllActions, Tr) => "Tüm işlemler", | | |
| 152 | - (Anonymous, En) => "anonymous", | | |
| 153 | - (Anonymous, Tr) => "anonim", | | |
| 154 | - (AuditLog, En) => "Audit log", | | |
| 155 | - (AuditLog, Tr) => "Denetim günlüğü", | | |
| 156 | - (BackToRunners, En) => "Back to runners", | | |
| 157 | - (BackToRunners, Tr) => "Çalıştırıcılara dön", | | |
| 158 | - (BackToUsers, En) => "Back to users", | | |
| 159 | - (BackToUsers, Tr) => "Kullanıcılara dön", | | |
| 160 | - (Backups, En) => "Backups", | | |
| 161 | - (Backups, Tr) => "Yedeklemeler", | | |
| 162 | - (CiRunners, En) => "CI runners", | | |
| 163 | - (CiRunners, Tr) => "CI çalıştırıcıları", | | |
| 164 | - (CopyTokenNow, En) => "Shown once.", | | |
| 165 | - (CopyTokenNow, Tr) => "Bir kez gösterilir.", | | |
| 166 | - (CreateRegistrationToken, En) => "Create registration token", | | |
| 167 | - (CreateRegistrationToken, Tr) => "Kayıt belirteci oluştur", | | |
| 168 | - (CreateUser, En) => "Create user", | | |
| 169 | - (CreateUser, Tr) => "Kullanıcı oluştur", | | |
| 170 | - (Database, En) => "Database", | | |
| 171 | - (Database, Tr) => "Veritabanı", | | |
| 172 | - (DatabaseErrorPrefix, En) => "Database: ", | | |
| 173 | - (DatabaseErrorPrefix, Tr) => "Veritabanı: ", | | |
| 174 | - (DeleteAccountRest, En) => ". This cannot be undone.", | | |
| 175 | - (DeleteAccountRest, Tr) => " hesabını siler. Bu işlem geri alınamaz.", | | |
| 176 | - (DeletesAccount, En) => "This deletes the account ", | | |
| 177 | - (DeletesAccount, Tr) => "Bu işlem ", | | |
| 178 | - (DeleteOrgTitle, En) => "Delete organization", | | |
| 179 | - (DeleteOrgTitle, Tr) => "Kuruluşu sil", | | |
| 180 | - (DeleteUser, En) => "Delete user", | | |
| 181 | - (DeleteUser, Tr) => "Kullanıcıyı sil", | | |
| 182 | - (Directory, En) => "Directory", | | |
| 183 | - (Directory, Tr) => "Dizin", | | |
| 184 | - (Disable, En) => "Disable", | | |
| 185 | - (Disable, Tr) => "Devre dışı bırak", | | |
| 186 | - (Disabled, En) => "disabled", | | |
| 187 | - (Disabled, Tr) => "devre dışı", | | |
| 188 | - (Enable, En) => "Enable", | | |
| 189 | - (Enable, Tr) => "Etkinleştir", | | |
| 190 | - (OpenOrgSettings, En) => "Open organization settings", | | |
| 191 | - (OpenOrgSettings, Tr) => "Kuruluş ayarlarını aç", | | |
| 192 | - (OrgNotAUser, En) => " is an organization.", | | |
| 193 | - (OrgNotAUser, Tr) => " bir kuruluştur.", | | |
| 194 | - (OrgReposFirst, En) => "Repositories it still owns:", | | |
| 195 | - (OrgReposFirst, Tr) => "Hâlâ sahip olduğu depolar:", | | |
| 196 | - (ErrAccountCannotBeDeleted, En) => "this account cannot be deleted", | | |
| 197 | - (ErrAccountCannotBeDeleted, Tr) => "bu hesap silinemez", | | |
| 198 | - (ErrBackupsNotConfigured, En) => { | | |
| 199 | - "backups are not configured: set [backup] dir in the config file" | | |
| 200 | - } | | |
| 201 | - (ErrBackupsNotConfigured, Tr) => { | | |
| 202 | - "yedeklemeler yapılandırılmamış: yapılandırma dosyasında [backup] dir ayarını yapın" | | |
| 203 | - } | | |
| 204 | - (ErrChooseSecurity, En) => "choose a security option", | | |
| 205 | - (ErrChooseSecurity, Tr) => "bir güvenlik seçeneği seçin", | | |
| 206 | - (ErrInvalidUsername, En) => "invalid username", | | |
| 207 | - (ErrInvalidUsername, Tr) => "geçersiz kullanıcı adı", | | |
| 208 | - (ErrNoAddressForTest, En) => "your account has no email address to send the test to", | | |
| 209 | - (ErrNoAddressForTest, Tr) => { | | |
| 210 | - "hesabınızda test iletisinin gönderileceği bir e-posta adresi yok" | | |
| 211 | - } | | |
| 212 | - (ErrPasswordTooLong, En) => "password is too long", | | |
| 213 | - (ErrPasswordTooLong, Tr) => "parola çok uzun", | | |
| 214 | - (ErrPortRange, En) => "the port must be a number from 1 to 65535", | | |
| 215 | - (ErrPortRange, Tr) => "bağlantı noktası 1 ile 65535 arasında bir sayı olmalı", | | |
| 216 | - (ErrReplicationNotConfigured, En) => { | | |
| 217 | - "replication is not configured: set [replication] target in the config file" | | |
| 218 | - } | | |
| 219 | - (ErrReplicationNotConfigured, Tr) => { | | |
| 220 | - "çoğaltma yapılandırılmamış: yapılandırma dosyasında [replication] target ayarını yapın" | | |
| 221 | - } | | |
| 222 | - (ErrTestNeedsMailOn, En) => "turn mail on and save the settings before sending a test", | | |
| 223 | - (ErrTestNeedsMailOn, Tr) => "test göndermeden önce e-postayı açın ve ayarları kaydedin", | | |
| 224 | - (ErrTypeUsernameExactly, En) => "Type the username exactly to confirm.", | | |
| 225 | - (ErrTypeUsernameExactly, Tr) => "Onaylamak için kullanıcı adını tam olarak yazın.", | | |
| 226 | - (Filter, En) => "Filter", | | |
| 227 | - (Filter, Tr) => "Filtrele", | | |
| 228 | - (FromAddress, En) => "From address", | | |
| 229 | - (FromAddress, Tr) => "Gönderen adresi", | | |
| 230 | - (FromName, En) => "From name", | | |
| 231 | - (FromName, Tr) => "Gönderen adı", | | |
| 232 | - (Fsck, En) => "Fsck", | | |
| 233 | - (Fsck, Tr) => "Fsck", | | |
| 234 | - (Healthcheck, En) => "Healthcheck", | | |
| 235 | - (Healthcheck, Tr) => "Sağlık denetimi", | | |
| 236 | - (HealthError, En) => "error", | | |
| 237 | - (HealthError, Tr) => "hata", | | |
| 238 | - (HealthLagging, En) => "lagging", | | |
| 239 | - (HealthLagging, Tr) => "gecikmeli", | | |
| 240 | - (HealthNever, En) => "never replicated", | | |
| 241 | - (HealthNever, Tr) => "hiç çoğaltılmadı", | | |
| 242 | - (HealthOk, En) => "ok", | | |
| 243 | - (HealthOk, Tr) => "tamam", | | |
| 244 | - (Invites, En) => "Invites", | | |
| 245 | - (Invites, Tr) => "Davetler", | | |
| 246 | - (LastDbAttempt, En) => "Last database attempt", | | |
| 247 | - (LastDbAttempt, Tr) => "Son veritabanı denemesi", | | |
| 248 | - (LastDbSnapshotShipped, En) => "Last database snapshot shipped", | | |
| 249 | - (LastDbSnapshotShipped, Tr) => "Son gönderilen veritabanı anlık görüntüsü", | | |
| 250 | - (LastSeen, En) => "Last seen", | | |
| 251 | - (LastSeen, Tr) => "Son görülme", | | |
| 252 | - (LastSuccess, En) => "Last success", | | |
| 253 | - (LastSuccess, Tr) => "Son başarı", | | |
| 254 | - (ServerSettings, En) => "Server", | | |
| 255 | - (ServerSettings, Tr) => "Sunucu", | | |
| 256 | - (SrvSaved, En) => "Server settings saved.", | | |
| 257 | - (SrvSaved, Tr) => "Sunucu ayarları kaydedildi.", | | |
| 258 | - (SrvNothingChanged, En) => "Nothing changed.", | | |
| 259 | - (SrvNothingChanged, Tr) => "Değişiklik yok.", | | |
| 260 | - (SrvResetDone, En) => "Back to the file value.", | | |
| 261 | - (SrvResetDone, Tr) => "Dosya değerine dönüldü.", | | |
| 262 | - (SrvResetToFile, En) => "Reset to file value", | | |
| 263 | - (SrvResetToFile, Tr) => "Dosya değerine sıfırla", | | |
| 264 | - (SrvRestartNeeded, En) => "restart needed", | | |
| 265 | - (SrvRestartNeeded, Tr) => "yeniden başlatma gerekli", | | |
| 266 | - (SrvKindLive, En) => "live", | | |
| 267 | - (SrvKindLive, Tr) => "canlı", | | |
| 268 | - (SrvKindRestart, En) => "restart", | | |
| 269 | - (SrvKindRestart, Tr) => "yeniden başlatma", | | |
| 270 | - (SrvKindReadOnly, En) => "read-only", | | |
| 271 | - (SrvKindReadOnly, Tr) => "salt okunur", | | |
| 272 | - (SrvSecretSet, En) => "set", | | |
| 273 | - (SrvSecretSet, Tr) => "ayarlı", | | |
| 274 | - (SrvSecretNotSet, En) => "not set", | | |
| 275 | - (SrvSecretNotSet, Tr) => "ayarlı değil", | | |
| 276 | - (SrvFileValue, En) => "File value", | | |
| 277 | - (SrvFileValue, Tr) => "Dosya değeri", | | |
| 278 | - (SrvEmpty, En) => "(empty)", | | |
| 279 | - (SrvEmpty, Tr) => "(boş)", | | |
| 280 | - (Mail, En) => "Mail", | | |
| 281 | - (Mail, Tr) => "E-posta", | | |
| 282 | - (MailTabSettings, En) => "Settings", | | |
| 283 | - (MailTabSettings, Tr) => "Ayarlar", | | |
| 284 | - (MailTabQueue, En) => "Queue", | | |
| 285 | - (MailTabQueue, Tr) => "Kuyruk", | | |
| 286 | - (MailFilterAll, En) => "All", | | |
| 287 | - (MailFilterAll, Tr) => "Tümü", | | |
| 288 | - (MailRetryNow, En) => "Retry now", | | |
| 289 | - (MailRetryNow, Tr) => "Şimdi yeniden dene", | | |
| 290 | - (MailDiscard, En) => "Discard", | | |
| 291 | - (MailDiscard, Tr) => "Vazgeç", | | |
| 292 | - (MailRetried, En) => "The message is queued for another try.", | | |
| 293 | - (MailRetried, Tr) => "Mesaj yeniden denenmek üzere kuyruğa alındı.", | | |
| 294 | - (MailNotFailed, En) => { | | |
| 295 | - "Only a failed message can be retried or discarded, and this one is not failed." | | |
| 296 | - } | | |
| 297 | - (MailNotFailed, Tr) => { | | |
| 298 | - "Yalnızca başarısız bir mesaj yeniden denenebilir ya da vazgeçilebilir; bu mesaj başarısız değil." | | |
| 299 | - } | | |
| 300 | - (MailDiscarded, En) => "The message was discarded.", | | |
| 301 | - (MailDiscarded, Tr) => "Mesajdan vazgeçildi.", | | |
| 302 | - (MailSentAt, En) => "Sent", | | |
| 303 | - (MailSentAt, Tr) => "Gönderildi", | | |
| 304 | - (MailNothingMatches, En) => "No message is in this state.", | | |
| 305 | - (MailNothingMatches, Tr) => "Bu durumda ileti yok.", | | |
| 306 | - (MailQueueEmpty, En) => "Nothing waiting to be sent.", | | |
| 307 | - (MailQueueEmpty, Tr) => "Gönderilmeyi bekleyen ileti yok.", | | |
| 308 | - (MailHost, En) => "Host", | | |
| 309 | - (MailHost, Tr) => "Sunucu", | | |
| 310 | - (MailPort, En) => "Port", | | |
| 311 | - (MailPort, Tr) => "Bağlantı noktası", | | |
| 312 | - (MailSettingsSaved, En) => "Mail settings saved.", | | |
| 313 | - (MailSettingsSaved, Tr) => "E-posta ayarları kaydedildi.", | | |
| 314 | - (MovedToGhost, En) => "Moved to the ghost user:", | | |
| 315 | - (MovedToGhost, Tr) => "Hayalet kullanıcıya taşınanlar:", | | |
| 316 | - (NoEntries, En) => "No entries.", | | |
| 317 | - (NoEntries, Tr) => "Kayıt yok.", | | |
| 318 | - (NoReposYet, En) => "No repos yet.", | | |
| 319 | - (NoReposYet, Tr) => "Henüz depo yok.", | | |
| 320 | - (NoRunnersYet, En) => "No runners registered yet.", | | |
| 321 | - (NoRunnersYet, Tr) => "Henüz kayıtlı çalıştırıcı yok.", | | |
| 322 | - (NoRunnerWithId, En) => "No runner has that id. Nothing was changed.", | | |
| 323 | - (NoRunnerWithId, Tr) => "Bu kimlikte bir çalıştırıcı yok. Hiçbir şey değiştirilmedi.", | | |
| 324 | - (NoRunsYet, En) => "No runs yet.", | | |
| 325 | - (NoRunsYet, Tr) => "Henüz çalıştırma yok.", | | |
| 326 | - (Older, En) => "Older", | | |
| 327 | - (Older, Tr) => "Daha eski", | | |
| 328 | - (RecentRuns, En) => "Recent runs", | | |
| 329 | - (RecentRuns, Tr) => "Son çalıştırmalar", | | |
| 330 | - (ReconcileNow, En) => "Reconcile now", | | |
| 331 | - (ReconcileNow, Tr) => "Şimdi uzlaştır", | | |
| 332 | - (ReconcileStarted, En) => "Reconcile started.", | | |
| 333 | - (ReconcileStarted, Tr) => "Uzlaştırma başlatıldı.", | | |
| 334 | - (RegisterARunner, En) => "Register a runner", | | |
| 335 | - (RegisterARunner, Tr) => "Bir çalıştırıcı kaydet", | | |
| 336 | - (RegistrationToken, En) => "Registration token", | | |
| 337 | - (RegistrationToken, Tr) => "Kayıt belirteci", | | |
| 338 | - (RemovedWithAccount, En) => "Removed with the account:", | | |
| 339 | - (RemovedWithAccount, Tr) => "Hesapla birlikte silinenler:", | | |
| 340 | - (Replication, En) => "Replication", | | |
| 341 | - (Replication, Tr) => "Çoğaltma", | | |
| 342 | - (ReplicationOff, En) => "Replication is off.", | | |
| 343 | - (ReplicationOff, Tr) => "Çoğaltma kapalı.", | | |
| 344 | - (Repos, En) => "Repos", | | |
| 345 | - (Repos, Tr) => "Depolar", | | |
| 346 | - (Retention, En) => "Retention", | | |
| 347 | - (Retention, Tr) => "Saklama", | | |
| 348 | - (Role, En) => "Role", | | |
| 349 | - (Role, Tr) => "Rol", | | |
| 350 | - (RoleAdmin, En) => "admin", | | |
| 351 | - (RoleAdmin, Tr) => "yönetici", | | |
| 352 | - (RoleOrganization, En) => "organization", | | |
| 353 | - (RoleOrganization, Tr) => "kuruluş", | | |
| 354 | - (RoleUser, En) => "user", | | |
| 355 | - (RoleUser, Tr) => "kullanıcı", | | |
| 356 | - (RunBackupNow, En) => "Run backup now", | | |
| 357 | - (RunBackupNow, Tr) => "Şimdi yedekle", | | |
| 358 | - (RunFsckNow, En) => "Run fsck now", | | |
| 359 | - (RunFsckNow, Tr) => "Şimdi fsck çalıştır", | | |
| 360 | - (RunnerDeletedNotice, En) => "Runner deleted.", | | |
| 361 | - (RunnerDeletedNotice, Tr) => "Çalıştırıcı silindi.", | | |
| 362 | - (RunnerDisabledNotice, En) => "Runner disabled. It will not take new jobs.", | | |
| 363 | - (RunnerDisabledNotice, Tr) => "Çalıştırıcı devre dışı bırakıldı. Yeni iş almayacak.", | | |
| 364 | - (RunnerEnabledNotice, En) => "Runner enabled.", | | |
| 365 | - (RunnerEnabledNotice, Tr) => "Çalıştırıcı etkinleştirildi.", | | |
| 366 | - (Runners, En) => "Runners", | | |
| 367 | - (Runners, Tr) => "Çalıştırıcılar", | | |
| 368 | - (ScheduledBackupsOff, En) => "Scheduled backups are off.", | | |
| 369 | - (ScheduledBackupsOff, Tr) => "Zamanlanmış yedeklemeler kapalı.", | | |
| 370 | - (SecurityLogTitle, En) => "Security log", | | |
| 371 | - (SecurityLogTitle, Tr) => "Güvenlik günlüğü", | | |
| 372 | - (SecurityNone, En) => "None (plain text)", | | |
| 373 | - (SecurityNone, Tr) => "Yok (düz metin)", | | |
| 374 | - (SendMailCheckbox, En) => "Send mail", | | |
| 375 | - (SendMailCheckbox, Tr) => "E-posta gönder", | | |
| 376 | - (SendTestMailToMe, En) => "Send test mail to me", | | |
| 377 | - (SendTestMailToMe, Tr) => "Bana test e-postası gönder", | | |
| 378 | - (Settings, En) => "Settings", | | |
| 379 | - (Settings, Tr) => "Ayarlar", | | |
| 380 | - (SmtpServer, En) => "SMTP server", | | |
| 381 | - (SmtpServer, Tr) => "SMTP sunucusu", | | |
| 382 | - (Standby, En) => "Standby", | | |
| 383 | - (Standby, Tr) => "Bekleme kopyası", | | |
| 384 | - (StatusFailed, En) => "failed", | | |
| 385 | - (StatusFailed, Tr) => "başarısız", | | |
| 386 | - (StatusInProgress, En) => "in progress", | | |
| 387 | - (StatusInProgress, Tr) => "sürüyor", | | |
| 388 | - (StatusOk, En) => "ok", | | |
| 389 | - (StatusOk, Tr) => "tamam", | | |
| 390 | - (TableLastError, En) => "Last error", | | |
| 391 | - (TableLastError, Tr) => "Son hata", | | |
| 392 | - (TableQueued, En) => "Queued", | | |
| 393 | - (TableQueued, Tr) => "Kuyruğa alındı", | | |
| 394 | - (TableTries, En) => "Tries", | | |
| 395 | - (TableTries, Tr) => "Deneme", | | |
| 396 | - (TestQueued, En) => "Test message queued. It appears in the list when it is sent.", | | |
| 397 | - (TestQueued, Tr) => "Test iletisi kuyruğa alındı. Gönderildiğinde listede görünür.", | | |
| 398 | - (Token, En) => "Token", | | |
| 399 | - (Token, Tr) => "Belirteç", | | |
| 400 | - (TokenCreateFailed, En) => { | | |
| 401 | - "The registration token could not be created. Nothing was changed." | | |
| 402 | - } | | |
| 403 | - (TokenCreateFailed, Tr) => "Kayıt belirteci oluşturulamadı. Hiçbir şey değiştirilmedi.", | | |
| 404 | - (TransferOrDeleteFirst, En) => "Transfer or delete these repositories first:", | | |
| 405 | - (TransferOrDeleteFirst, Tr) => "Önce bu depoları devredin veya silin:", | | |
| 406 | - (UnknownHost, En) => "unknown", | | |
| 407 | - (UnknownHost, Tr) => "bilinmiyor", | | |
| 408 | - (Users, En) => "Users", | | |
| 409 | - (Users, Tr) => "Kullanıcılar", | | |
| 410 | - (ViewOrg, En) => "View organization", | | |
| 411 | - (ViewOrg, Tr) => "Kuruluşu görüntüle", | | |
| 412 | - (WhatHappens, En) => "What happens", | | |
| 413 | - (WhatHappens, Tr) => "Ne olacak", | | |
| 414 | - } | | |
| 415 | } | 135 | } |
| 416 | | 136 | |
| 417 | pub fn type_to_confirm(lang: Lang, name: &str) -> String { | 137 | pub fn type_to_confirm(lang: Lang, name: &str) -> String { |
| @@ -530,137 +250,6 @@ pub fn no_user_named(lang: Lang, actor: &str) -> String { |
| 530 | mod tests { | 250 | mod tests { |
| 531 | use super::*; | 251 | use super::*; |
| 532 | | 252 | |
| 533 | - const ALL: &[K] = &[ | | |
| 534 | - K::ActionLabel, | | |
| 535 | - K::AddARunner, | | |
| 536 | - K::AdminArea, | | |
| 537 | - K::Administrator, | | |
| 538 | - K::AllActions, | | |
| 539 | - K::Anonymous, | | |
| 540 | - K::AuditLog, | | |
| 541 | - K::BackToRunners, | | |
| 542 | - K::BackToUsers, | | |
| 543 | - K::Backups, | | |
| 544 | - K::CiRunners, | | |
| 545 | - K::CopyTokenNow, | | |
| 546 | - K::CreateRegistrationToken, | | |
| 547 | - K::CreateUser, | | |
| 548 | - K::Database, | | |
| 549 | - K::DatabaseErrorPrefix, | | |
| 550 | - K::DeleteAccountRest, | | |
| 551 | - K::DeletesAccount, | | |
| 552 | - K::DeleteOrgTitle, | | |
| 553 | - K::DeleteUser, | | |
| 554 | - K::Directory, | | |
| 555 | - K::Disable, | | |
| 556 | - K::Disabled, | | |
| 557 | - K::Enable, | | |
| 558 | - K::OpenOrgSettings, | | |
| 559 | - K::OrgNotAUser, | | |
| 560 | - K::OrgReposFirst, | | |
| 561 | - K::ErrAccountCannotBeDeleted, | | |
| 562 | - K::ErrBackupsNotConfigured, | | |
| 563 | - K::ErrChooseSecurity, | | |
| 564 | - K::ErrInvalidUsername, | | |
| 565 | - K::ErrNoAddressForTest, | | |
| 566 | - K::ErrPasswordTooLong, | | |
| 567 | - K::ErrPortRange, | | |
| 568 | - K::ErrReplicationNotConfigured, | | |
| 569 | - K::ErrTestNeedsMailOn, | | |
| 570 | - K::ErrTypeUsernameExactly, | | |
| 571 | - K::Filter, | | |
| 572 | - K::FromAddress, | | |
| 573 | - K::FromName, | | |
| 574 | - K::Fsck, | | |
| 575 | - K::Healthcheck, | | |
| 576 | - K::HealthError, | | |
| 577 | - K::HealthLagging, | | |
| 578 | - K::HealthNever, | | |
| 579 | - K::HealthOk, | | |
| 580 | - K::Invites, | | |
| 581 | - K::LastDbAttempt, | | |
| 582 | - K::LastDbSnapshotShipped, | | |
| 583 | - K::LastSeen, | | |
| 584 | - K::LastSuccess, | | |
| 585 | - K::ServerSettings, | | |
| 586 | - K::SrvSaved, | | |
| 587 | - K::SrvNothingChanged, | | |
| 588 | - K::SrvResetDone, | | |
| 589 | - K::SrvResetToFile, | | |
| 590 | - K::SrvRestartNeeded, | | |
| 591 | - K::SrvKindLive, | | |
| 592 | - K::SrvKindRestart, | | |
| 593 | - K::SrvKindReadOnly, | | |
| 594 | - K::SrvSecretSet, | | |
| 595 | - K::SrvSecretNotSet, | | |
| 596 | - K::SrvFileValue, | | |
| 597 | - K::SrvEmpty, | | |
| 598 | - K::Mail, | | |
| 599 | - K::MailHost, | | |
| 600 | - K::MailTabSettings, | | |
| 601 | - K::MailTabQueue, | | |
| 602 | - K::MailFilterAll, | | |
| 603 | - K::MailRetryNow, | | |
| 604 | - K::MailDiscard, | | |
| 605 | - K::MailRetried, | | |
| 606 | - K::MailNotFailed, | | |
| 607 | - K::MailDiscarded, | | |
| 608 | - K::MailSentAt, | | |
| 609 | - K::MailNothingMatches, | | |
| 610 | - K::MailPort, | | |
| 611 | - K::MailSettingsSaved, | | |
| 612 | - K::MovedToGhost, | | |
| 613 | - K::NoEntries, | | |
| 614 | - K::NoReposYet, | | |
| 615 | - K::NoRunnersYet, | | |
| 616 | - K::NoRunnerWithId, | | |
| 617 | - K::NoRunsYet, | | |
| 618 | - K::MailQueueEmpty, | | |
| 619 | - K::Older, | | |
| 620 | - K::RecentRuns, | | |
| 621 | - K::ReconcileNow, | | |
| 622 | - K::ReconcileStarted, | | |
| 623 | - K::RegisterARunner, | | |
| 624 | - K::RegistrationToken, | | |
| 625 | - K::RemovedWithAccount, | | |
| 626 | - K::Replication, | | |
| 627 | - K::ReplicationOff, | | |
| 628 | - K::Repos, | | |
| 629 | - K::Retention, | | |
| 630 | - K::Role, | | |
| 631 | - K::RoleAdmin, | | |
| 632 | - K::RoleOrganization, | | |
| 633 | - K::RoleUser, | | |
| 634 | - K::RunBackupNow, | | |
| 635 | - K::RunFsckNow, | | |
| 636 | - K::RunnerDeletedNotice, | | |
| 637 | - K::RunnerDisabledNotice, | | |
| 638 | - K::RunnerEnabledNotice, | | |
| 639 | - K::Runners, | | |
| 640 | - K::ScheduledBackupsOff, | | |
| 641 | - K::SecurityLogTitle, | | |
| 642 | - K::SecurityNone, | | |
| 643 | - K::SendMailCheckbox, | | |
| 644 | - K::SendTestMailToMe, | | |
| 645 | - K::Settings, | | |
| 646 | - K::SmtpServer, | | |
| 647 | - K::Standby, | | |
| 648 | - K::StatusFailed, | | |
| 649 | - K::StatusInProgress, | | |
| 650 | - K::StatusOk, | | |
| 651 | - K::TableLastError, | | |
| 652 | - K::TableQueued, | | |
| 653 | - K::TableTries, | | |
| 654 | - K::TestQueued, | | |
| 655 | - K::Token, | | |
| 656 | - K::TokenCreateFailed, | | |
| 657 | - K::TransferOrDeleteFirst, | | |
| 658 | - K::UnknownHost, | | |
| 659 | - K::Users, | | |
| 660 | - K::ViewOrg, | | |
| 661 | - K::WhatHappens, | | |
| 662 | - ]; | | |
| 663 | - | | |
| 664 | #[test] | 253 | #[test] |
| 665 | fn every_variant_has_text_in_both_languages() { | 254 | fn every_variant_has_text_in_both_languages() { |
| 666 | for key in ALL { | 255 | for key in ALL { |
| @@ -1,127 +1,170 @@ |
| 1 | use super::Lang; | 1 | use super::Lang; |
| | 2 | +use forge_core::alerts::AlertTopic; |
| 2 | | 3 | |
| 3 | -pub fn title(lang: Lang, topic: &str, subject: &str, resolved: bool) -> String { | 4 | +pub fn title(lang: Lang, topic: AlertTopic, subject: &str, resolved: bool) -> String { |
| 4 | match (lang, topic, resolved) { | 5 | match (lang, topic, resolved) { |
| 5 | - (Lang::En, "runner_offline", false) => format!("Runner {subject} is offline"), | 6 | + (Lang::En, AlertTopic::RunnerOffline, false) => format!("Runner {subject} is offline"), |
| 6 | - (Lang::En, "runner_offline", true) => format!("Runner {subject} is back online"), | 7 | + (Lang::En, AlertTopic::RunnerOffline, true) => format!("Runner {subject} is back online"), |
| 7 | - (Lang::Tr, "runner_offline", false) => format!("{subject} runner'ı çevrim dışı"), | 8 | + (Lang::Tr, AlertTopic::RunnerOffline, false) => format!("{subject} runner'ı çevrim dışı"), |
| 8 | - (Lang::Tr, "runner_offline", true) => format!("{subject} runner'ı yeniden çevrim içi"), | 9 | + (Lang::Tr, AlertTopic::RunnerOffline, true) => { |
| 9 | - | 10 | + format!("{subject} runner'ı yeniden çevrim içi") |
| 10 | - (Lang::En, "backup_failed", false) => "A backup failed".to_owned(), | 11 | + } |
| 11 | - (Lang::En, "backup_failed", true) => "Backups work again".to_owned(), | 12 | + |
| 12 | - (Lang::Tr, "backup_failed", false) => "Bir yedekleme başarısız oldu".to_owned(), | 13 | + (Lang::En, AlertTopic::BackupFailed, false) => "A backup failed".to_owned(), |
| 13 | - (Lang::Tr, "backup_failed", true) => "Yedeklemeler yeniden çalışıyor".to_owned(), | 14 | + (Lang::En, AlertTopic::BackupFailed, true) => "Backups work again".to_owned(), |
| 14 | - | 15 | + (Lang::Tr, AlertTopic::BackupFailed, false) => "Bir yedekleme başarısız oldu".to_owned(), |
| 15 | - (Lang::En, "backup_verify_failed", false) => "Backup verification failed".to_owned(), | 16 | + (Lang::Tr, AlertTopic::BackupFailed, true) => "Yedeklemeler yeniden çalışıyor".to_owned(), |
| 16 | - (Lang::En, "backup_verify_failed", true) => "Backup verification passes again".to_owned(), | 17 | + |
| 17 | - (Lang::Tr, "backup_verify_failed", false) => "Yedek doğrulaması başarısız oldu".to_owned(), | 18 | + (Lang::En, AlertTopic::BackupVerifyFailed, false) => { |
| 18 | - (Lang::Tr, "backup_verify_failed", true) => "Yedek doğrulaması yeniden başarılı".to_owned(), | 19 | + "Backup verification failed".to_owned() |
| 19 | - | 20 | + } |
| 20 | - (Lang::En, "backup_overdue", false) => "No recent backup".to_owned(), | 21 | + (Lang::En, AlertTopic::BackupVerifyFailed, true) => { |
| 21 | - (Lang::En, "backup_overdue", true) => "A backup finished, none overdue".to_owned(), | 22 | + "Backup verification passes again".to_owned() |
| 22 | - (Lang::Tr, "backup_overdue", false) => "Yakın zamanda yedek alınmadı".to_owned(), | 23 | + } |
| 23 | - (Lang::Tr, "backup_overdue", true) => "Bir yedek tamamlandı, gecikme yok".to_owned(), | 24 | + (Lang::Tr, AlertTopic::BackupVerifyFailed, false) => { |
| 24 | - | 25 | + "Yedek doğrulaması başarısız oldu".to_owned() |
| 25 | - (Lang::En, "fsck_failed", false) => "The integrity check found problems".to_owned(), | 26 | + } |
| 26 | - (Lang::En, "fsck_failed", true) => "The integrity check passes again".to_owned(), | 27 | + (Lang::Tr, AlertTopic::BackupVerifyFailed, true) => { |
| 27 | - (Lang::Tr, "fsck_failed", false) => "Bütünlük denetimi sorun buldu".to_owned(), | 28 | + "Yedek doğrulaması yeniden başarılı".to_owned() |
| 28 | - (Lang::Tr, "fsck_failed", true) => "Bütünlük denetimi yeniden başarılı".to_owned(), | 29 | + } |
| 29 | - | 30 | + |
| 30 | - (Lang::En, "disk_low", false) => "Disk space is low".to_owned(), | 31 | + (Lang::En, AlertTopic::BackupOverdue, false) => "No recent backup".to_owned(), |
| 31 | - (Lang::En, "disk_low", true) => "Disk space is back to normal".to_owned(), | 32 | + (Lang::En, AlertTopic::BackupOverdue, true) => "A backup finished, none overdue".to_owned(), |
| 32 | - (Lang::Tr, "disk_low", false) => "Disk alanı azaldı".to_owned(), | 33 | + (Lang::Tr, AlertTopic::BackupOverdue, false) => "Yakın zamanda yedek alınmadı".to_owned(), |
| 33 | - (Lang::Tr, "disk_low", true) => "Disk alanı normale döndü".to_owned(), | 34 | + (Lang::Tr, AlertTopic::BackupOverdue, true) => { |
| 34 | - | 35 | + "Bir yedek tamamlandı, gecikme yok".to_owned() |
| 35 | - (Lang::En, "ci_killed", _) => format!("A CI job was killed on runner {subject}"), | 36 | + } |
| 36 | - (Lang::Tr, "ci_killed", _) => format!("{subject} runner'ında bir CI işi öldürüldü"), | 37 | + |
| 37 | - | 38 | + (Lang::En, AlertTopic::FsckFailed, false) => { |
| 38 | - (Lang::En, "self_update_restart", false) => "Self-update deployed, restarting".to_owned(), | 39 | + "The integrity check found problems".to_owned() |
| 39 | - (Lang::En, "self_update_restart", true) => "Server restarted after self-update".to_owned(), | 40 | + } |
| 40 | - (Lang::Tr, "self_update_restart", false) => { | 41 | + (Lang::En, AlertTopic::FsckFailed, true) => "The integrity check passes again".to_owned(), |
| | 42 | + (Lang::Tr, AlertTopic::FsckFailed, false) => "Bütünlük denetimi sorun buldu".to_owned(), |
| | 43 | + (Lang::Tr, AlertTopic::FsckFailed, true) => "Bütünlük denetimi yeniden başarılı".to_owned(), |
| | 44 | + |
| | 45 | + (Lang::En, AlertTopic::DiskLow, false) => "Disk space is low".to_owned(), |
| | 46 | + (Lang::En, AlertTopic::DiskLow, true) => "Disk space is back to normal".to_owned(), |
| | 47 | + (Lang::Tr, AlertTopic::DiskLow, false) => "Disk alanı azaldı".to_owned(), |
| | 48 | + (Lang::Tr, AlertTopic::DiskLow, true) => "Disk alanı normale döndü".to_owned(), |
| | 49 | + |
| | 50 | + (Lang::En, AlertTopic::CiKilled, _) => format!("A CI job was killed on runner {subject}"), |
| | 51 | + (Lang::Tr, AlertTopic::CiKilled, _) => { |
| | 52 | + format!("{subject} runner'ında bir CI işi öldürüldü") |
| | 53 | + } |
| | 54 | + |
| | 55 | + (Lang::En, AlertTopic::SelfUpdateRestart, false) => { |
| | 56 | + "Self-update deployed, restarting".to_owned() |
| | 57 | + } |
| | 58 | + (Lang::En, AlertTopic::SelfUpdateRestart, true) => { |
| | 59 | + "Server restarted after self-update".to_owned() |
| | 60 | + } |
| | 61 | + (Lang::Tr, AlertTopic::SelfUpdateRestart, false) => { |
| 41 | "Kendini güncelleme dağıtıldı, yeniden başlıyor".to_owned() | 62 | "Kendini güncelleme dağıtıldı, yeniden başlıyor".to_owned() |
| 42 | } | 63 | } |
| 43 | - (Lang::Tr, "self_update_restart", true) => { | 64 | + (Lang::Tr, AlertTopic::SelfUpdateRestart, true) => { |
| 44 | "Sunucu kendini güncelledikten sonra yeniden başladı".to_owned() | 65 | "Sunucu kendini güncelledikten sonra yeniden başladı".to_owned() |
| 45 | } | 66 | } |
| 46 | | 67 | |
| 47 | - (Lang::En, "self_update_failed", _) => "Self-update failed".to_owned(), | 68 | + (Lang::En, AlertTopic::SelfUpdateFailed, _) => "Self-update failed".to_owned(), |
| 48 | - (Lang::Tr, "self_update_failed", _) => "Kendini güncelleme başarısız oldu".to_owned(), | 69 | + (Lang::Tr, AlertTopic::SelfUpdateFailed, _) => { |
| 49 | - | 70 | + "Kendini güncelleme başarısız oldu".to_owned() |
| 50 | - (Lang::En, "replication", false) => "Standby replication has a problem".to_owned(), | 71 | + } |
| 51 | - (Lang::En, "replication", true) => "Standby replication is healthy again".to_owned(), | | |
| 52 | - (Lang::Tr, "replication", false) => "Yedek sunucuya kopyalamada sorun var".to_owned(), | | |
| 53 | - (Lang::Tr, "replication", true) => "Yedek sunucuya kopyalama yeniden sağlıklı".to_owned(), | | |
| 54 | | 72 | |
| 55 | - (_, other, _) => other.to_owned(), | 73 | + (Lang::En, AlertTopic::Replication, false) => { |
| | 74 | + "Standby replication has a problem".to_owned() |
| | 75 | + } |
| | 76 | + (Lang::En, AlertTopic::Replication, true) => { |
| | 77 | + "Standby replication is healthy again".to_owned() |
| | 78 | + } |
| | 79 | + (Lang::Tr, AlertTopic::Replication, false) => { |
| | 80 | + "Yedek sunucuya kopyalamada sorun var".to_owned() |
| | 81 | + } |
| | 82 | + (Lang::Tr, AlertTopic::Replication, true) => { |
| | 83 | + "Yedek sunucuya kopyalama yeniden sağlıklı".to_owned() |
| | 84 | + } |
| 56 | } | 85 | } |
| 57 | } | 86 | } |
| 58 | | 87 | |
| 59 | -pub fn body(lang: Lang, topic: &str, subject: &str, detail: &str, resolved: bool) -> String { | 88 | +pub fn body(lang: Lang, topic: AlertTopic, subject: &str, detail: &str, resolved: bool) -> String { |
| 60 | match (lang, topic, resolved) { | 89 | match (lang, topic, resolved) { |
| 61 | - (Lang::En, "runner_offline", false) => format!( | 90 | + (Lang::En, AlertTopic::RunnerOffline, false) => format!( |
| 62 | "No heartbeat since {detail}. Queued jobs wait for another runner until it returns." | 91 | "No heartbeat since {detail}. Queued jobs wait for another runner until it returns." |
| 63 | ), | 92 | ), |
| 64 | - (Lang::Tr, "runner_offline", false) => format!( | 93 | + (Lang::Tr, AlertTopic::RunnerOffline, false) => format!( |
| 65 | "{detail} tarihinden beri sinyal yok. Sıradaki işler, geri dönene kadar başka bir runner bekler." | 94 | "{detail} tarihinden beri sinyal yok. Sıradaki işler, geri dönene kadar başka bir runner bekler." |
| 66 | ), | 95 | ), |
| 67 | - (Lang::En, "runner_offline", true) => format!("Runner {subject} checked in again."), | 96 | + (Lang::En, AlertTopic::RunnerOffline, true) => { |
| 68 | - (Lang::Tr, "runner_offline", true) => format!("{subject} runner'ı yeniden bağlandı."), | 97 | + format!("Runner {subject} checked in again.") |
| | 98 | + } |
| | 99 | + (Lang::Tr, AlertTopic::RunnerOffline, true) => { |
| | 100 | + format!("{subject} runner'ı yeniden bağlandı.") |
| | 101 | + } |
| 69 | | 102 | |
| 70 | - (Lang::En, "backup_failed", true) => "The latest backup succeeded.".to_owned(), | 103 | + (Lang::En, AlertTopic::BackupFailed, true) => "The latest backup succeeded.".to_owned(), |
| 71 | - (Lang::Tr, "backup_failed", true) => "Son yedekleme başarılı oldu.".to_owned(), | 104 | + (Lang::Tr, AlertTopic::BackupFailed, true) => "Son yedekleme başarılı oldu.".to_owned(), |
| 72 | - (Lang::En, "backup_verify_failed", true) => { | 105 | + (Lang::En, AlertTopic::BackupVerifyFailed, true) => { |
| 73 | "The latest backup set was verified.".to_owned() | 106 | "The latest backup set was verified.".to_owned() |
| 74 | } | 107 | } |
| 75 | - (Lang::Tr, "backup_verify_failed", true) => "Son yedek seti doğrulandı.".to_owned(), | 108 | + (Lang::Tr, AlertTopic::BackupVerifyFailed, true) => "Son yedek seti doğrulandı.".to_owned(), |
| 76 | - (Lang::En, "fsck_failed", true) => "The latest integrity check was clean.".to_owned(), | 109 | + (Lang::En, AlertTopic::FsckFailed, true) => { |
| 77 | - (Lang::Tr, "fsck_failed", true) => "Son bütünlük denetimi temiz çıktı.".to_owned(), | 110 | + "The latest integrity check was clean.".to_owned() |
| | 111 | + } |
| | 112 | + (Lang::Tr, AlertTopic::FsckFailed, true) => "Son bütünlük denetimi temiz çıktı.".to_owned(), |
| 78 | | 113 | |
| 79 | - (Lang::En, "backup_overdue", false) => format!( | 114 | + (Lang::En, AlertTopic::BackupOverdue, false) => format!( |
| 80 | "No backup has succeeded within twice the schedule interval. Last good backup: {detail}." | 115 | "No backup has succeeded within twice the schedule interval. Last good backup: {detail}." |
| 81 | ), | 116 | ), |
| 82 | - (Lang::Tr, "backup_overdue", false) => format!( | 117 | + (Lang::Tr, AlertTopic::BackupOverdue, false) => format!( |
| 83 | "Zamanlama aralığının iki katı içinde başarılı yedek yok. Son iyi yedek: {detail}." | 118 | "Zamanlama aralığının iki katı içinde başarılı yedek yok. Son iyi yedek: {detail}." |
| 84 | ), | 119 | ), |
| 85 | - (Lang::En, "backup_overdue", true) => "The backup schedule is back on track.".to_owned(), | 120 | + (Lang::En, AlertTopic::BackupOverdue, true) => { |
| 86 | - (Lang::Tr, "backup_overdue", true) => "Yedekleme takvimi yeniden yolunda.".to_owned(), | 121 | + "The backup schedule is back on track.".to_owned() |
| | 122 | + } |
| | 123 | + (Lang::Tr, AlertTopic::BackupOverdue, true) => { |
| | 124 | + "Yedekleme takvimi yeniden yolunda.".to_owned() |
| | 125 | + } |
| 87 | | 126 | |
| 88 | - (Lang::En, "disk_low", false) => format!("{subject}: {detail}."), | 127 | + (Lang::En, AlertTopic::DiskLow, false) => format!("{subject}: {detail}."), |
| 89 | - (Lang::Tr, "disk_low", false) => format!("{subject}: {detail}."), | 128 | + (Lang::Tr, AlertTopic::DiskLow, false) => format!("{subject}: {detail}."), |
| 90 | - (Lang::En, "disk_low", true) => format!("{subject} has enough free space again."), | 129 | + (Lang::En, AlertTopic::DiskLow, true) => { |
| 91 | - (Lang::Tr, "disk_low", true) => format!("{subject} yeniden yeterli boş alana sahip."), | 130 | + format!("{subject} has enough free space again.") |
| | 131 | + } |
| | 132 | + (Lang::Tr, AlertTopic::DiskLow, true) => { |
| | 133 | + format!("{subject} yeniden yeterli boş alana sahip.") |
| | 134 | + } |
| 92 | | 135 | |
| 93 | - (Lang::En, "ci_killed", _) => format!( | 136 | + (Lang::En, AlertTopic::CiKilled, _) => format!( |
| 94 | "{detail} ended with a kill signal, probably the out-of-memory killer. \ | 137 | "{detail} ended with a kill signal, probably the out-of-memory killer. \ |
| 95 | Consider lowering the concurrency of runner {subject}." | 138 | Consider lowering the concurrency of runner {subject}." |
| 96 | ), | 139 | ), |
| 97 | - (Lang::Tr, "ci_killed", _) => format!( | 140 | + (Lang::Tr, AlertTopic::CiKilled, _) => format!( |
| 98 | "{detail} bir öldürme sinyaliyle sona erdi, büyük olasılıkla bellek yetersizliği. \ | 141 | "{detail} bir öldürme sinyaliyle sona erdi, büyük olasılıkla bellek yetersizliği. \ |
| 99 | {subject} runner'ının eşzamanlılığını düşürmeyi düşünün." | 142 | {subject} runner'ının eşzamanlılığını düşürmeyi düşünün." |
| 100 | ), | 143 | ), |
| 101 | | 144 | |
| 102 | - (Lang::En, "self_update_restart", false) => { | 145 | + (Lang::En, AlertTopic::SelfUpdateRestart, false) => { |
| 103 | format!("Version {subject} is installed. The server is restarting to run it.") | 146 | format!("Version {subject} is installed. The server is restarting to run it.") |
| 104 | } | 147 | } |
| 105 | - (Lang::Tr, "self_update_restart", false) => { | 148 | + (Lang::Tr, AlertTopic::SelfUpdateRestart, false) => { |
| 106 | format!("{subject} sürümü kuruldu. Sunucu onu çalıştırmak için yeniden başlıyor.") | 149 | format!("{subject} sürümü kuruldu. Sunucu onu çalıştırmak için yeniden başlıyor.") |
| 107 | } | 150 | } |
| 108 | - (Lang::En, "self_update_restart", true) => { | 151 | + (Lang::En, AlertTopic::SelfUpdateRestart, true) => { |
| 109 | format!("The server is running version {subject}.") | 152 | format!("The server is running version {subject}.") |
| 110 | } | 153 | } |
| 111 | - (Lang::Tr, "self_update_restart", true) => { | 154 | + (Lang::Tr, AlertTopic::SelfUpdateRestart, true) => { |
| 112 | format!("Sunucu {subject} sürümünü çalıştırıyor.") | 155 | format!("Sunucu {subject} sürümünü çalıştırıyor.") |
| 113 | } | 156 | } |
| 114 | | 157 | |
| 115 | - (_, "self_update_failed", _) => detail.to_owned(), | 158 | + (_, AlertTopic::SelfUpdateFailed, _) => detail.to_owned(), |
| 116 | | 159 | |
| 117 | - (Lang::En, "replication", false) => { | 160 | + (Lang::En, AlertTopic::Replication, false) => { |
| 118 | format!("{detail} The standby may be behind until this is fixed.") | 161 | format!("{detail} The standby may be behind until this is fixed.") |
| 119 | } | 162 | } |
| 120 | - (Lang::Tr, "replication", false) => { | 163 | + (Lang::Tr, AlertTopic::Replication, false) => { |
| 121 | format!("{detail} Bu düzelene kadar yedek sunucu geride kalabilir.") | 164 | format!("{detail} Bu düzelene kadar yedek sunucu geride kalabilir.") |
| 122 | } | 165 | } |
| 123 | - (Lang::En, "replication", true) => "The standby is up to date.".to_owned(), | 166 | + (Lang::En, AlertTopic::Replication, true) => "The standby is up to date.".to_owned(), |
| 124 | - (Lang::Tr, "replication", true) => "Yedek sunucu güncel.".to_owned(), | 167 | + (Lang::Tr, AlertTopic::Replication, true) => "Yedek sunucu güncel.".to_owned(), |
| 125 | | 168 | |
| 126 | _ => detail.to_owned(), | 169 | _ => detail.to_owned(), |
| 127 | } | 170 | } |
| @@ -170,28 +213,15 @@ pub fn mail_body(lang: Lang, body: &str, health_url: &str, settings_url: &str) - |
| 170 | mod tests { | 213 | mod tests { |
| 171 | use super::*; | 214 | use super::*; |
| 172 | | 215 | |
| 173 | - const TOPICS: &[&str] = &[ | | |
| 174 | - "runner_offline", | | |
| 175 | - "backup_failed", | | |
| 176 | - "backup_verify_failed", | | |
| 177 | - "backup_overdue", | | |
| 178 | - "fsck_failed", | | |
| 179 | - "disk_low", | | |
| 180 | - "ci_killed", | | |
| 181 | - "self_update_restart", | | |
| 182 | - "self_update_failed", | | |
| 183 | - "replication", | | |
| 184 | - ]; | | |
| 185 | - | | |
| 186 | #[test] | 216 | #[test] |
| 187 | fn every_topic_is_worded_in_both_languages_without_em_dashes() { | 217 | fn every_topic_is_worded_in_both_languages_without_em_dashes() { |
| 188 | for lang in [Lang::En, Lang::Tr] { | 218 | for lang in [Lang::En, Lang::Tr] { |
| 189 | - for topic in TOPICS { | 219 | + for topic in AlertTopic::ALL { |
| 190 | for resolved in [false, true] { | 220 | for resolved in [false, true] { |
| 191 | let t = title(lang, topic, "tahinli-ci", resolved); | 221 | let t = title(lang, topic, "tahinli-ci", resolved); |
| 192 | let b = body(lang, topic, "tahinli-ci", "detail", resolved); | 222 | let b = body(lang, topic, "tahinli-ci", "detail", resolved); |
| 193 | - assert_ne!(t, *topic, "{topic} has a title"); | 223 | + assert_ne!(t, topic.as_str(), "{topic:?} has a title"); |
| 194 | - assert!(!b.is_empty(), "{topic} has a body"); | 224 | + assert!(!b.is_empty(), "{topic:?} has a body"); |
| 195 | assert!(!t.contains('\u{2014}') && !b.contains('\u{2014}')); | 225 | assert!(!t.contains('\u{2014}') && !b.contains('\u{2014}')); |
| 196 | } | 226 | } |
| 197 | } | 227 | } |
| @@ -1,44 +1,17 @@ |
| 1 | use super::Lang; | 1 | use super::Lang; |
| 2 | | 2 | |
| 3 | -#[derive(Clone, Copy, Debug, PartialEq, Eq)] | 3 | +strings! { |
| 4 | -pub enum K { | 4 | + K; |
| 5 | - Reviewers, | 5 | + Reviewers => "Reviewers", "İnceleyenler"; |
| 6 | - RequestReview, | 6 | + RequestReview => "Request review", "İnceleme iste"; |
| 7 | - ReviewerName, | 7 | + ReviewerName => "Username", "Kullanıcı adı"; |
| 8 | - WithdrawRequest, | 8 | + WithdrawRequest => "Withdraw request", "İsteği geri çek"; |
| 9 | - ReviewRequests, | 9 | + ReviewRequests => "Review requests", "İnceleme istekleri"; |
| 10 | - NoReviewRequests, | 10 | + NoReviewRequests => "Nobody is waiting for your review.", "İncelemenizi bekleyen yok."; |
| 11 | - ReviewerUnknown, | 11 | + ReviewerUnknown => "No such user.", "Böyle bir kullanıcı yok."; |
| 12 | - ReviewerNoAccess, | 12 | + ReviewerNoAccess => "That user cannot read this repository.", "Bu kullanıcı bu depoyu okuyamaz."; |
| 13 | - ReviewerIsAuthor, | 13 | + ReviewerIsAuthor => "The author cannot review their own pull request.", "Yazar kendi değişiklik isteğini inceleyemez."; |
| 14 | - ReviewerAlready, | 14 | + ReviewerAlready => "A review is already requested from that user.", "Bu kullanıcıdan zaten inceleme istendi."; |
| 15 | -} | | |
| 16 | - | | |
| 17 | -pub fn t(lang: Lang, key: K) -> &'static str { | | |
| 18 | - use K::*; | | |
| 19 | - use Lang::*; | | |
| 20 | - match (key, lang) { | | |
| 21 | - (Reviewers, En) => "Reviewers", | | |
| 22 | - (Reviewers, Tr) => "İnceleyenler", | | |
| 23 | - (RequestReview, En) => "Request review", | | |
| 24 | - (RequestReview, Tr) => "İnceleme iste", | | |
| 25 | - (ReviewerName, En) => "Username", | | |
| 26 | - (ReviewerName, Tr) => "Kullanıcı adı", | | |
| 27 | - (WithdrawRequest, En) => "Withdraw request", | | |
| 28 | - (WithdrawRequest, Tr) => "İsteği geri çek", | | |
| 29 | - (ReviewRequests, En) => "Review requests", | | |
| 30 | - (ReviewRequests, Tr) => "İnceleme istekleri", | | |
| 31 | - (NoReviewRequests, En) => "Nobody is waiting for your review.", | | |
| 32 | - (NoReviewRequests, Tr) => "İncelemenizi bekleyen yok.", | | |
| 33 | - (ReviewerUnknown, En) => "No such user.", | | |
| 34 | - (ReviewerUnknown, Tr) => "Böyle bir kullanıcı yok.", | | |
| 35 | - (ReviewerNoAccess, En) => "That user cannot read this repository.", | | |
| 36 | - (ReviewerNoAccess, Tr) => "Bu kullanıcı bu depoyu okuyamaz.", | | |
| 37 | - (ReviewerIsAuthor, En) => "The author cannot review their own pull request.", | | |
| 38 | - (ReviewerIsAuthor, Tr) => "Yazar kendi değişiklik isteğini inceleyemez.", | | |
| 39 | - (ReviewerAlready, En) => "A review is already requested from that user.", | | |
| 40 | - (ReviewerAlready, Tr) => "Bu kullanıcıdan zaten inceleme istendi.", | | |
| 41 | - } | | |
| 42 | } | 15 | } |
| 43 | | 16 | |
| 44 | pub fn tasks_progress(lang: Lang, done: usize, total: usize) -> String { | 17 | pub fn tasks_progress(lang: Lang, done: usize, total: usize) -> String { |
| @@ -1,24 +1,7 @@ |
| 1 | use super::Lang; | 1 | use super::Lang; |
| 2 | | 2 | |
| 3 | -macro_rules! strings { | | |
| 4 | - ($($key:ident => $en:expr, $tr:expr;)*) => { | | |
| 5 | - #[derive(Clone, Copy, Debug, PartialEq, Eq)] | | |
| 6 | - pub enum K { | | |
| 7 | - $($key,)* | | |
| 8 | - } | | |
| 9 | - | | |
| 10 | - pub fn t(lang: Lang, key: K) -> &'static str { | | |
| 11 | - match (key, lang) { | | |
| 12 | - $((K::$key, Lang::En) => $en, (K::$key, Lang::Tr) => $tr,)* | | |
| 13 | - } | | |
| 14 | - } | | |
| 15 | - | | |
| 16 | - #[cfg(test)] | | |
| 17 | - const ALL: &[K] = &[$(K::$key,)*]; | | |
| 18 | - }; | | |
| 19 | -} | | |
| 20 | - | | |
| 21 | strings! { | 3 | strings! { |
| | 4 | + K; |
| 22 | DiffView => "Diff view", "Fark görünümü"; | 5 | DiffView => "Diff view", "Fark görünümü"; |
| 23 | Unified => "Unified", "Birleşik"; | 6 | Unified => "Unified", "Birleşik"; |
| 24 | Split => "Split", "Bölünmüş"; | 7 | Split => "Split", "Bölünmüş"; |
| @@ -2,349 +2,114 @@ use forge_core::store::commit_status::StatusState; |
| 2 | | 2 | |
| 3 | use super::Lang; | 3 | use super::Lang; |
| 4 | | 4 | |
| 5 | -#[derive(Clone, Copy, Debug, PartialEq, Eq)] | 5 | +strings! { |
| 6 | -pub enum K { | 6 | + K; |
| 7 | - SearchWord, | 7 | + SearchWord => "search", "arama"; |
| 8 | - SearchFailed, | 8 | + SearchFailed => "The search could not run. Check the pattern; regex mode uses extended regular expressions.", "Arama çalıştırılamadı. Deseni kontrol edin; regex kipi genişletilmiş düzenli ifadeleri kullanır."; |
| 9 | - SearchCodePlaceholder, | 9 | + SearchCodePlaceholder => "Search code", "Kodda ara"; |
| 10 | - SearchButton, | 10 | + SearchButton => "Search", "Ara"; |
| 11 | - RefField, | 11 | + RefField => "Ref ", "Referans "; |
| 12 | - PathField, | 12 | + PathField => "Path ", "Yol "; |
| 13 | - MatchCase, | 13 | + MatchCase => " Match case", " Büyük/küçük harfe duyarlı"; |
| 14 | - RegexOption, | 14 | + RegexOption => " Regex", " Düzenli ifade"; |
| 15 | - SearchFilesAt, | 15 | + SearchFilesAt => "Search the files at ", "Dosyaları şurada ara: "; |
| 16 | - NoMatches, | 16 | + NoMatches => "No matches.", "Eşleşme yok."; |
| 17 | - ShowingFirst, | 17 | + ShowingFirst => " (showing the first ", " (ilk "; |
| 18 | - ShowingFirstEnd, | 18 | + ShowingFirstEnd => ")", " gösteriliyor)"; |
| 19 | - CloneTitle, | 19 | + CloneTitle => "Clone", "Klonla"; |
| 20 | - CopyCloneUrl, | 20 | + CopyCloneUrl => "Copy clone URL", "Klon adresini kopyala"; |
| 21 | - CloneCopied, | 21 | + CloneCopied => "Copied", "Kopyalandı"; |
| 22 | - CloneCopyFailed, | 22 | + CloneCopyFailed => "Copy failed", "Kopyalanamadı"; |
| 23 | - BranchesTitle, | 23 | + BranchesTitle => "Branches", "Dallar"; |
| 24 | - FilterRefs, | 24 | + FilterRefs => "Filter branches and tags", "Dal ve etiketleri süz"; |
| 25 | - ViewAllBranches, | 25 | + ViewAllBranches => "View all branches", "Tüm dalları gör"; |
| 26 | - ViewAllTags, | 26 | + ViewAllTags => "View all tags", "Tüm etiketleri gör"; |
| 27 | - EmptyRepoPush, | 27 | + EmptyRepoPush => "This repository is empty.", "Bu depo boş."; |
| 28 | - OverHttps, | 28 | + OverHttps => "Over HTTPS", "HTTPS üzerinden"; |
| 29 | - OverSsh, | 29 | + OverSsh => "Over SSH", "SSH üzerinden"; |
| 30 | - DownloadZip, | 30 | + DownloadZip => "Download ZIP", "ZIP olarak indir"; |
| 31 | - DownloadTarGz, | 31 | + DownloadTarGz => "Download tar.gz", "tar.gz olarak indir"; |
| 32 | - RecentPushes, | 32 | + RecentPushes => "Recent pushes", "Son gönderimler"; |
| 33 | - HadRecentPushes, | 33 | + HadRecentPushes => " had recent pushes ", " dalına son zamanlarda gönderim yapıldı "; |
| 34 | - CompareAndPr, | 34 | + CompareAndPr => "Compare & pull request", "Karşılaştır ve çekme isteği aç"; |
| 35 | - BranchLabel, | 35 | + BranchLabel => "Branch", "Dal"; |
| 36 | - KindDir, | 36 | + KindDir => "dir", "dizin"; |
| 37 | - KindFile, | 37 | + KindFile => "file", "dosya"; |
| 38 | - KindExec, | 38 | + KindExec => "exec", "çalıştırılabilir"; |
| 39 | - KindLink, | 39 | + KindLink => "link", "bağlantı"; |
| 40 | - KindSubmodule, | 40 | + KindSubmodule => "submodule", "alt modül"; |
| 41 | - Rendered, | 41 | + Rendered => "Rendered", "Önizleme"; |
| 42 | - SourceToggle, | 42 | + SourceToggle => "Source", "Kaynak"; |
| 43 | - HistoryLink, | 43 | + HistoryLink => "History", "Geçmiş"; |
| 44 | - RawLink, | 44 | + RawLink => "Raw", "Ham"; |
| 45 | - DownloadLink, | 45 | + DownloadLink => "Download", "İndir"; |
| 46 | - SymlinkPrefix, | 46 | + SymlinkPrefix => "Symbolic link → ", "Sembolik bağlantı → "; |
| 47 | - SubmodulePrefix, | 47 | + SubmodulePrefix => "Submodule at commit ", "Alt modül, şu commit'te: "; |
| 48 | - SubmoduleSuffix, | 48 | + SubmoduleSuffix => ". Its contents are not in this repository.", ". İçeriği bu depoda yok."; |
| 49 | - TruncatedPrefix, | 49 | + TruncatedPrefix => "Showing the first 1 MiB of this file. ", "Bu dosyanın ilk 1 MiB'ı gösteriliyor. "; |
| 50 | - ViewFullRaw, | 50 | + ViewFullRaw => "View raw", "Ham görüntüle"; |
| 51 | - LivePathGone, | 51 | + LivePathGone => "This path no longer exists in this ref.", "Bu yol bu referansta artık yok."; |
| 52 | - StatusAdded, | 52 | + StatusAdded => "added", "eklendi"; |
| 53 | - StatusDeleted, | 53 | + StatusDeleted => "deleted", "silindi"; |
| 54 | - StatusModified, | 54 | + StatusModified => "modified", "değiştirildi"; |
| 55 | - StatusRenamed, | 55 | + StatusRenamed => "renamed", "yeniden adlandırıldı"; |
| 56 | - StatusCopied, | 56 | + StatusCopied => "copied", "kopyalandı"; |
| 57 | - StatusTypeChanged, | 57 | + StatusTypeChanged => "type changed", "tür değiştirildi"; |
| 58 | - NoFileChanges, | 58 | + NoFileChanges => "No file changes.", "Dosya değişikliği yok."; |
| 59 | - BinaryFileChanged, | 59 | + BinaryFileChanged => "Binary file changed", "İkili dosya değiştirildi"; |
| 60 | - DiffTooLargePrefix, | 60 | + DiffTooLargePrefix => "Diff too large; ", "Fark çok büyük; "; |
| 61 | - ViewFile, | 61 | + ViewFile => "view file", "dosyayı görüntüle"; |
| 62 | - DiffTooLarge, | 62 | + DiffTooLarge => "Diff too large.", "Fark çok büyük."; |
| 63 | - CommentOnLine, | 63 | + CommentOnLine => "Comment on this line", "Bu satıra yorum yap"; |
| 64 | - AddReviewComment, | 64 | + AddReviewComment => "Add review comment", "İnceleme yorumu ekle"; |
| 65 | - StartReview, | 65 | + StartReview => "Start a review", "İnceleme başlat"; |
| 66 | - CommentLabel, | 66 | + CommentLabel => "Comment", "Yorum"; |
| 67 | - AddSingleComment, | 67 | + AddSingleComment => "Add single comment", "Tek yorum ekle"; |
| 68 | - CancelLink, | 68 | + ThisCommit => "this commit", "bu commit"; |
| 69 | - ThisCommit, | 69 | + ShowFullMessage => "Show full message", "Tam mesajı göster"; |
| 70 | - ShowFullMessage, | 70 | + CommitStatusPrefix => "Commit status: ", "Commit durumu: "; |
| 71 | - CommitStatusPrefix, | 71 | + StateSuccess => "success", "başarılı"; |
| 72 | - StateSuccess, | 72 | + StateFailure => "failure", "başarısız"; |
| 73 | - StateFailure, | 73 | + StateError => "error", "hata"; |
| 74 | - StateError, | 74 | + StatePending => "pending", "bekliyor"; |
| 75 | - StatePending, | 75 | + NoChecksReported => "No checks reported", "Hiç kontrol bildirilmedi"; |
| 76 | - NoChecksReported, | 76 | + AllChecksPassed => "All checks have passed", "Tüm kontroller geçti"; |
| 77 | - AllChecksPassed, | 77 | + ChecksPending => "Checks pending", "Kontroller bekliyor"; |
| 78 | - ChecksPending, | 78 | + SomeChecksFailed => "Some checks failed", "Bazı kontroller başarısız oldu"; |
| 79 | - SomeChecksFailed, | 79 | + ShowChecks => "Show checks", "Kontrolleri göster"; |
| 80 | - ShowChecks, | 80 | + DetailsLink => "Details", "Ayrıntılar"; |
| 81 | - DetailsLink, | 81 | + AuthorLabel => "Author ", "Yazar "; |
| 82 | - AuthorLabel, | 82 | + CommitterLabel => "Committer ", "Commit eden "; |
| 83 | - CommitterLabel, | 83 | + CoAuthorAnd => " and ", " ve "; |
| 84 | - CoAuthorAnd, | 84 | + CoAuthorsLabel => "Co-authors", "Ortak yazarlar"; |
| 85 | - CoAuthorsLabel, | 85 | + RootCommit => "Root commit (no parents)", "Kök commit (üst commit yok)"; |
| 86 | - RootCommit, | 86 | + CommitChangesLabel => "Changes in this commit", "Bu commit'teki değişiklikler"; |
| 87 | - CommitChangesLabel, | 87 | + ParentLabel => "Parent: ", "Üst commit: "; |
| 88 | - ParentLabel, | 88 | + BrowseFiles => "Browse files at this commit", "Bu commit'teki dosyalara göz at"; |
| 89 | - BrowseFiles, | 89 | + SigVerified => "Verified", "Doğrulandı"; |
| 90 | - SigVerified, | 90 | + SigUnverified => "Unverified", "Doğrulanmadı"; |
| 91 | - SigUnverified, | 91 | + CommitsOn => "Commits on ", "Referanstaki commit'ler: "; |
| 92 | - CommitsOn, | 92 | + FilteredTo => "Filtered to ", "Şuna göre filtrelendi: "; |
| 93 | - FilteredTo, | 93 | + ClearFilter => "Clear filter", "Filtreyi temizle"; |
| 94 | - ClearFilter, | 94 | + NoCommits => "No commits yet.", "Henüz commit yok."; |
| 95 | - NoCommits, | 95 | + NothingHere => "Nothing here yet.", "Henüz burada bir şey yok."; |
| 96 | - BrowseFilesShort, | 96 | + DefaultBadge => "default", "varsayılan"; |
| 97 | - NewerLink, | 97 | + TagsTitle => "Tags", "Etiketler"; |
| 98 | - OlderLink, | 98 | + ForkedFrom => "forked from ", "Şu depodan çatallandı: "; |
| 99 | - NothingHere, | 99 | + MirrorOf => "Mirror of ", "Yansı kaynağı: "; |
| 100 | - DefaultBadge, | 100 | + NotSyncedYet => "not synced yet", "henüz eşitlenmedi"; |
| 101 | - TagsTitle, | 101 | + ForkButton => "Fork", "Çatalla"; |
| 102 | - ForkedFrom, | 102 | + StarsAria => "Stars", "Yıldızlar"; |
| 103 | - MirrorOf, | 103 | + ArchivedNotice => "This repository is archived. It is read-only.", "Bu depo arşivlendi. Salt okunurdur."; |
| 104 | - NotSyncedYet, | 104 | + RepositoryNav => "Repository", "Depo"; |
| 105 | - ForkButton, | 105 | + TabIssues => "Issues", "Sorunlar"; |
| 106 | - StarsAria, | 106 | + TabPulls => "Pull requests", "Çekme istekleri"; |
| 107 | - ArchivedNotice, | 107 | + TabCommits => "Commits", "Commitler"; |
| 108 | - RepositoryNav, | 108 | + TabReleases => "Releases", "Sürümler"; |
| 109 | - TabIssues, | 109 | + TabCi => "CI", "CI"; |
| 110 | - TabPulls, | 110 | + TabDiscussions => "Discussions", "Tartışmalar"; |
| 111 | - TabCommits, | 111 | + TabWiki => "Wiki", "Wiki"; |
| 112 | - TabReleases, | 112 | + TabSettings => "Settings", "Ayarlar"; |
| 113 | - TabCi, | | |
| 114 | - TabDiscussions, | | |
| 115 | - TabWiki, | | |
| 116 | - TabSettings, | | |
| 117 | -} | | |
| 118 | - | | |
| 119 | -pub fn t(lang: Lang, key: K) -> &'static str { | | |
| 120 | - use K::*; | | |
| 121 | - use Lang::*; | | |
| 122 | - match (key, lang) { | | |
| 123 | - (SearchWord, En) => "search", | | |
| 124 | - (SearchWord, Tr) => "arama", | | |
| 125 | - (SearchFailed, En) => { | | |
| 126 | - "The search could not run. Check the pattern; regex mode uses extended regular expressions." | | |
| 127 | - } | | |
| 128 | - (SearchFailed, Tr) => { | | |
| 129 | - "Arama çalıştırılamadı. Deseni kontrol edin; regex kipi genişletilmiş düzenli ifadeleri kullanır." | | |
| 130 | - } | | |
| 131 | - (SearchCodePlaceholder, En) => "Search code", | | |
| 132 | - (SearchCodePlaceholder, Tr) => "Kodda ara", | | |
| 133 | - (SearchButton, En) => "Search", | | |
| 134 | - (SearchButton, Tr) => "Ara", | | |
| 135 | - (RefField, En) => "Ref ", | | |
| 136 | - (RefField, Tr) => "Referans ", | | |
| 137 | - (PathField, En) => "Path ", | | |
| 138 | - (PathField, Tr) => "Yol ", | | |
| 139 | - (MatchCase, En) => " Match case", | | |
| 140 | - (MatchCase, Tr) => " Büyük/küçük harfe duyarlı", | | |
| 141 | - (RegexOption, En) => " Regex", | | |
| 142 | - (RegexOption, Tr) => " Düzenli ifade", | | |
| 143 | - (SearchFilesAt, En) => "Search the files at ", | | |
| 144 | - (SearchFilesAt, Tr) => "Dosyaları şurada ara: ", | | |
| 145 | - (NoMatches, En) => "No matches.", | | |
| 146 | - (NoMatches, Tr) => "Eşleşme yok.", | | |
| 147 | - (ShowingFirst, En) => " (showing the first ", | | |
| 148 | - (ShowingFirst, Tr) => " (ilk ", | | |
| 149 | - (ShowingFirstEnd, En) => ")", | | |
| 150 | - (ShowingFirstEnd, Tr) => " gösteriliyor)", | | |
| 151 | - (CloneTitle, En) => "Clone", | | |
| 152 | - (CloneTitle, Tr) => "Klonla", | | |
| 153 | - (CopyCloneUrl, En) => "Copy clone URL", | | |
| 154 | - (CopyCloneUrl, Tr) => "Klon adresini kopyala", | | |
| 155 | - (CloneCopied, En) => "Copied", | | |
| 156 | - (CloneCopied, Tr) => "Kopyalandı", | | |
| 157 | - (CloneCopyFailed, En) => "Copy failed", | | |
| 158 | - (CloneCopyFailed, Tr) => "Kopyalanamadı", | | |
| 159 | - (BranchesTitle, En) => "Branches", | | |
| 160 | - (BranchesTitle, Tr) => "Dallar", | | |
| 161 | - (FilterRefs, En) => "Filter branches and tags", | | |
| 162 | - (FilterRefs, Tr) => "Dal ve etiketleri süz", | | |
| 163 | - (ViewAllBranches, En) => "View all branches", | | |
| 164 | - (ViewAllBranches, Tr) => "Tüm dalları gör", | | |
| 165 | - (ViewAllTags, En) => "View all tags", | | |
| 166 | - (ViewAllTags, Tr) => "Tüm etiketleri gör", | | |
| 167 | - (EmptyRepoPush, En) => "This repository is empty.", | | |
| 168 | - (EmptyRepoPush, Tr) => "Bu depo boş.", | | |
| 169 | - (OverHttps, En) => "Over HTTPS", | | |
| 170 | - (OverHttps, Tr) => "HTTPS üzerinden", | | |
| 171 | - (OverSsh, En) => "Over SSH", | | |
| 172 | - (OverSsh, Tr) => "SSH üzerinden", | | |
| 173 | - (DownloadZip, En) => "Download ZIP", | | |
| 174 | - (DownloadZip, Tr) => "ZIP olarak indir", | | |
| 175 | - (DownloadTarGz, En) => "Download tar.gz", | | |
| 176 | - (DownloadTarGz, Tr) => "tar.gz olarak indir", | | |
| 177 | - (RecentPushes, En) => "Recent pushes", | | |
| 178 | - (RecentPushes, Tr) => "Son gönderimler", | | |
| 179 | - (HadRecentPushes, En) => " had recent pushes ", | | |
| 180 | - (HadRecentPushes, Tr) => " dalına son zamanlarda gönderim yapıldı ", | | |
| 181 | - (CompareAndPr, En) => "Compare & pull request", | | |
| 182 | - (CompareAndPr, Tr) => "Karşılaştır ve çekme isteği aç", | | |
| 183 | - (BranchLabel, En) => "Branch", | | |
| 184 | - (BranchLabel, Tr) => "Dal", | | |
| 185 | - (KindDir, En) => "dir", | | |
| 186 | - (KindDir, Tr) => "dizin", | | |
| 187 | - (KindFile, En) => "file", | | |
| 188 | - (KindFile, Tr) => "dosya", | | |
| 189 | - (KindExec, En) => "exec", | | |
| 190 | - (KindExec, Tr) => "çalıştırılabilir", | | |
| 191 | - (KindLink, En) => "link", | | |
| 192 | - (KindLink, Tr) => "bağlantı", | | |
| 193 | - (KindSubmodule, En) => "submodule", | | |
| 194 | - (KindSubmodule, Tr) => "alt modül", | | |
| 195 | - (Rendered, En) => "Rendered", | | |
| 196 | - (Rendered, Tr) => "Önizleme", | | |
| 197 | - (SourceToggle, En) => "Source", | | |
| 198 | - (SourceToggle, Tr) => "Kaynak", | | |
| 199 | - (HistoryLink, En) => "History", | | |
| 200 | - (HistoryLink, Tr) => "Geçmiş", | | |
| 201 | - (RawLink, En) => "Raw", | | |
| 202 | - (RawLink, Tr) => "Ham", | | |
| 203 | - (DownloadLink, En) => "Download", | | |
| 204 | - (DownloadLink, Tr) => "İndir", | | |
| 205 | - (SymlinkPrefix, En) => "Symbolic link → ", | | |
| 206 | - (SymlinkPrefix, Tr) => "Sembolik bağlantı → ", | | |
| 207 | - (SubmodulePrefix, En) => "Submodule at commit ", | | |
| 208 | - (SubmodulePrefix, Tr) => "Alt modül, şu commit'te: ", | | |
| 209 | - (SubmoduleSuffix, En) => ". Its contents are not in this repository.", | | |
| 210 | - (SubmoduleSuffix, Tr) => ". İçeriği bu depoda yok.", | | |
| 211 | - (TruncatedPrefix, En) => "Showing the first 1 MiB of this file. ", | | |
| 212 | - (TruncatedPrefix, Tr) => "Bu dosyanın ilk 1 MiB'ı gösteriliyor. ", | | |
| 213 | - (ViewFullRaw, En) => "View raw", | | |
| 214 | - (ViewFullRaw, Tr) => "Ham görüntüle", | | |
| 215 | - (LivePathGone, En) => "This path no longer exists in this ref.", | | |
| 216 | - (LivePathGone, Tr) => "Bu yol bu referansta artık yok.", | | |
| 217 | - (StatusAdded, En) => "added", | | |
| 218 | - (StatusAdded, Tr) => "eklendi", | | |
| 219 | - (StatusDeleted, En) => "deleted", | | |
| 220 | - (StatusDeleted, Tr) => "silindi", | | |
| 221 | - (StatusModified, En) => "modified", | | |
| 222 | - (StatusModified, Tr) => "değiştirildi", | | |
| 223 | - (StatusRenamed, En) => "renamed", | | |
| 224 | - (StatusRenamed, Tr) => "yeniden adlandırıldı", | | |
| 225 | - (StatusCopied, En) => "copied", | | |
| 226 | - (StatusCopied, Tr) => "kopyalandı", | | |
| 227 | - (StatusTypeChanged, En) => "type changed", | | |
| 228 | - (StatusTypeChanged, Tr) => "tür değiştirildi", | | |
| 229 | - (NoFileChanges, En) => "No file changes.", | | |
| 230 | - (NoFileChanges, Tr) => "Dosya değişikliği yok.", | | |
| 231 | - (BinaryFileChanged, En) => "Binary file changed", | | |
| 232 | - (BinaryFileChanged, Tr) => "İkili dosya değiştirildi", | | |
| 233 | - (DiffTooLargePrefix, En) => "Diff too large; ", | | |
| 234 | - (DiffTooLargePrefix, Tr) => "Fark çok büyük; ", | | |
| 235 | - (ViewFile, En) => "view file", | | |
| 236 | - (ViewFile, Tr) => "dosyayı görüntüle", | | |
| 237 | - (DiffTooLarge, En) => "Diff too large.", | | |
| 238 | - (DiffTooLarge, Tr) => "Fark çok büyük.", | | |
| 239 | - (CommentOnLine, En) => "Comment on this line", | | |
| 240 | - (CommentOnLine, Tr) => "Bu satıra yorum yap", | | |
| 241 | - (AddReviewComment, En) => "Add review comment", | | |
| 242 | - (AddReviewComment, Tr) => "İnceleme yorumu ekle", | | |
| 243 | - (StartReview, En) => "Start a review", | | |
| 244 | - (StartReview, Tr) => "İnceleme başlat", | | |
| 245 | - (CommentLabel, En) => "Comment", | | |
| 246 | - (CommentLabel, Tr) => "Yorum", | | |
| 247 | - (AddSingleComment, En) => "Add single comment", | | |
| 248 | - (AddSingleComment, Tr) => "Tek yorum ekle", | | |
| 249 | - (CancelLink, En) => "Cancel", | | |
| 250 | - (CancelLink, Tr) => "İptal", | | |
| 251 | - (ThisCommit, En) => "this commit", | | |
| 252 | - (ThisCommit, Tr) => "bu commit", | | |
| 253 | - (ShowFullMessage, En) => "Show full message", | | |
| 254 | - (ShowFullMessage, Tr) => "Tam mesajı göster", | | |
| 255 | - (CommitStatusPrefix, En) => "Commit status: ", | | |
| 256 | - (CommitStatusPrefix, Tr) => "Commit durumu: ", | | |
| 257 | - (StateSuccess, En) => "success", | | |
| 258 | - (StateSuccess, Tr) => "başarılı", | | |
| 259 | - (StateFailure, En) => "failure", | | |
| 260 | - (StateFailure, Tr) => "başarısız", | | |
| 261 | - (StateError, En) => "error", | | |
| 262 | - (StateError, Tr) => "hata", | | |
| 263 | - (StatePending, En) => "pending", | | |
| 264 | - (StatePending, Tr) => "bekliyor", | | |
| 265 | - (NoChecksReported, En) => "No checks reported", | | |
| 266 | - (NoChecksReported, Tr) => "Hiç kontrol bildirilmedi", | | |
| 267 | - (AllChecksPassed, En) => "All checks have passed", | | |
| 268 | - (AllChecksPassed, Tr) => "Tüm kontroller geçti", | | |
| 269 | - (ChecksPending, En) => "Checks pending", | | |
| 270 | - (ChecksPending, Tr) => "Kontroller bekliyor", | | |
| 271 | - (SomeChecksFailed, En) => "Some checks failed", | | |
| 272 | - (SomeChecksFailed, Tr) => "Bazı kontroller başarısız oldu", | | |
| 273 | - (ShowChecks, En) => "Show checks", | | |
| 274 | - (ShowChecks, Tr) => "Kontrolleri göster", | | |
| 275 | - (DetailsLink, En) => "Details", | | |
| 276 | - (DetailsLink, Tr) => "Ayrıntılar", | | |
| 277 | - (AuthorLabel, En) => "Author ", | | |
| 278 | - (AuthorLabel, Tr) => "Yazar ", | | |
| 279 | - (CommitterLabel, En) => "Committer ", | | |
| 280 | - (CommitterLabel, Tr) => "Commit eden ", | | |
| 281 | - (CoAuthorAnd, En) => " and ", | | |
| 282 | - (CoAuthorAnd, Tr) => " ve ", | | |
| 283 | - (CoAuthorsLabel, En) => "Co-authors", | | |
| 284 | - (CoAuthorsLabel, Tr) => "Ortak yazarlar", | | |
| 285 | - (RootCommit, En) => "Root commit (no parents)", | | |
| 286 | - (RootCommit, Tr) => "Kök commit (üst commit yok)", | | |
| 287 | - (CommitChangesLabel, En) => "Changes in this commit", | | |
| 288 | - (CommitChangesLabel, Tr) => "Bu commit'teki değişiklikler", | | |
| 289 | - (ParentLabel, En) => "Parent: ", | | |
| 290 | - (ParentLabel, Tr) => "Üst commit: ", | | |
| 291 | - (BrowseFiles, En) => "Browse files at this commit", | | |
| 292 | - (BrowseFiles, Tr) => "Bu commit'teki dosyalara göz at", | | |
| 293 | - (SigVerified, En) => "Verified", | | |
| 294 | - (SigVerified, Tr) => "Doğrulandı", | | |
| 295 | - (SigUnverified, En) => "Unverified", | | |
| 296 | - (SigUnverified, Tr) => "Doğrulanmadı", | | |
| 297 | - (CommitsOn, En) => "Commits on ", | | |
| 298 | - (CommitsOn, Tr) => "Referanstaki commit'ler: ", | | |
| 299 | - (FilteredTo, En) => "Filtered to ", | | |
| 300 | - (FilteredTo, Tr) => "Şuna göre filtrelendi: ", | | |
| 301 | - (ClearFilter, En) => "Clear filter", | | |
| 302 | - (ClearFilter, Tr) => "Filtreyi temizle", | | |
| 303 | - (NoCommits, En) => "No commits yet.", | | |
| 304 | - (NoCommits, Tr) => "Henüz commit yok.", | | |
| 305 | - (BrowseFilesShort, En) => "Browse files", | | |
| 306 | - (BrowseFilesShort, Tr) => "Dosyalara göz at", | | |
| 307 | - (NewerLink, En) => "Newer", | | |
| 308 | - (NewerLink, Tr) => "Daha yeni", | | |
| 309 | - (OlderLink, En) => "Older", | | |
| 310 | - (OlderLink, Tr) => "Daha eski", | | |
| 311 | - (NothingHere, En) => "Nothing here yet.", | | |
| 312 | - (NothingHere, Tr) => "Henüz burada bir şey yok.", | | |
| 313 | - (DefaultBadge, En) => "default", | | |
| 314 | - (DefaultBadge, Tr) => "varsayılan", | | |
| 315 | - (TagsTitle, En) => "Tags", | | |
| 316 | - (TagsTitle, Tr) => "Etiketler", | | |
| 317 | - (ForkedFrom, En) => "forked from ", | | |
| 318 | - (ForkedFrom, Tr) => "Şu depodan çatallandı: ", | | |
| 319 | - (MirrorOf, En) => "Mirror of ", | | |
| 320 | - (MirrorOf, Tr) => "Yansı kaynağı: ", | | |
| 321 | - (NotSyncedYet, En) => "not synced yet", | | |
| 322 | - (NotSyncedYet, Tr) => "henüz eşitlenmedi", | | |
| 323 | - (ForkButton, En) => "Fork", | | |
| 324 | - (ForkButton, Tr) => "Çatalla", | | |
| 325 | - (StarsAria, En) => "Stars", | | |
| 326 | - (StarsAria, Tr) => "Yıldızlar", | | |
| 327 | - (ArchivedNotice, En) => "This repository is archived. It is read-only.", | | |
| 328 | - (ArchivedNotice, Tr) => "Bu depo arşivlendi. Salt okunurdur.", | | |
| 329 | - (RepositoryNav, En) => "Repository", | | |
| 330 | - (RepositoryNav, Tr) => "Depo", | | |
| 331 | - (TabIssues, En) => "Issues", | | |
| 332 | - (TabIssues, Tr) => "Sorunlar", | | |
| 333 | - (TabPulls, En) => "Pull requests", | | |
| 334 | - (TabPulls, Tr) => "Çekme istekleri", | | |
| 335 | - (TabCommits, En) => "Commits", | | |
| 336 | - (TabCommits, Tr) => "Commitler", | | |
| 337 | - (TabReleases, En) => "Releases", | | |
| 338 | - (TabReleases, Tr) => "Sürümler", | | |
| 339 | - (TabCi, En) => "CI", | | |
| 340 | - (TabCi, Tr) => "CI", | | |
| 341 | - (TabDiscussions, En) => "Discussions", | | |
| 342 | - (TabDiscussions, Tr) => "Tartışmalar", | | |
| 343 | - (TabWiki, En) => "Wiki", | | |
| 344 | - (TabWiki, Tr) => "Wiki", | | |
| 345 | - (TabSettings, En) => "Settings", | | |
| 346 | - (TabSettings, Tr) => "Ayarlar", | | |
| 347 | - } | | |
| 348 | } | 113 | } |
| 349 | | 114 | |
| 350 | pub fn match_summary(lang: Lang, matches: usize, files: usize) -> String { | 115 | pub fn match_summary(lang: Lang, matches: usize, files: usize) -> String { |
| @@ -489,119 +254,6 @@ pub fn mirror_sync_failed(lang: Lang) -> (&'static str, &'static str) { |
| 489 | mod tests { | 254 | mod tests { |
| 490 | use super::*; | 255 | use super::*; |
| 491 | | 256 | |
| 492 | - const ALL: &[K] = &[ | | |
| 493 | - K::SearchWord, | | |
| 494 | - K::SearchFailed, | | |
| 495 | - K::SearchCodePlaceholder, | | |
| 496 | - K::SearchButton, | | |
| 497 | - K::RefField, | | |
| 498 | - K::PathField, | | |
| 499 | - K::MatchCase, | | |
| 500 | - K::RegexOption, | | |
| 501 | - K::SearchFilesAt, | | |
| 502 | - K::NoMatches, | | |
| 503 | - K::ShowingFirst, | | |
| 504 | - K::ShowingFirstEnd, | | |
| 505 | - K::CloneTitle, | | |
| 506 | - K::CopyCloneUrl, | | |
| 507 | - K::CloneCopied, | | |
| 508 | - K::CloneCopyFailed, | | |
| 509 | - K::BranchesTitle, | | |
| 510 | - K::FilterRefs, | | |
| 511 | - K::ViewAllBranches, | | |
| 512 | - K::ViewAllTags, | | |
| 513 | - K::EmptyRepoPush, | | |
| 514 | - K::OverHttps, | | |
| 515 | - K::OverSsh, | | |
| 516 | - K::DownloadZip, | | |
| 517 | - K::DownloadTarGz, | | |
| 518 | - K::RecentPushes, | | |
| 519 | - K::HadRecentPushes, | | |
| 520 | - K::CompareAndPr, | | |
| 521 | - K::BranchLabel, | | |
| 522 | - K::KindDir, | | |
| 523 | - K::KindFile, | | |
| 524 | - K::KindExec, | | |
| 525 | - K::KindLink, | | |
| 526 | - K::KindSubmodule, | | |
| 527 | - K::Rendered, | | |
| 528 | - K::SourceToggle, | | |
| 529 | - K::HistoryLink, | | |
| 530 | - K::RawLink, | | |
| 531 | - K::DownloadLink, | | |
| 532 | - K::SymlinkPrefix, | | |
| 533 | - K::SubmodulePrefix, | | |
| 534 | - K::SubmoduleSuffix, | | |
| 535 | - K::TruncatedPrefix, | | |
| 536 | - K::ViewFullRaw, | | |
| 537 | - K::LivePathGone, | | |
| 538 | - K::StatusAdded, | | |
| 539 | - K::StatusDeleted, | | |
| 540 | - K::StatusModified, | | |
| 541 | - K::StatusRenamed, | | |
| 542 | - K::StatusCopied, | | |
| 543 | - K::StatusTypeChanged, | | |
| 544 | - K::NoFileChanges, | | |
| 545 | - K::BinaryFileChanged, | | |
| 546 | - K::DiffTooLargePrefix, | | |
| 547 | - K::ViewFile, | | |
| 548 | - K::DiffTooLarge, | | |
| 549 | - K::CommentOnLine, | | |
| 550 | - K::AddReviewComment, | | |
| 551 | - K::StartReview, | | |
| 552 | - K::CommentLabel, | | |
| 553 | - K::AddSingleComment, | | |
| 554 | - K::CancelLink, | | |
| 555 | - K::ThisCommit, | | |
| 556 | - K::ShowFullMessage, | | |
| 557 | - K::CommitStatusPrefix, | | |
| 558 | - K::StateSuccess, | | |
| 559 | - K::StateFailure, | | |
| 560 | - K::StateError, | | |
| 561 | - K::StatePending, | | |
| 562 | - K::NoChecksReported, | | |
| 563 | - K::AllChecksPassed, | | |
| 564 | - K::ChecksPending, | | |
| 565 | - K::SomeChecksFailed, | | |
| 566 | - K::ShowChecks, | | |
| 567 | - K::DetailsLink, | | |
| 568 | - K::AuthorLabel, | | |
| 569 | - K::CommitterLabel, | | |
| 570 | - K::CoAuthorAnd, | | |
| 571 | - K::CoAuthorsLabel, | | |
| 572 | - K::RootCommit, | | |
| 573 | - K::CommitChangesLabel, | | |
| 574 | - K::ParentLabel, | | |
| 575 | - K::BrowseFiles, | | |
| 576 | - K::SigVerified, | | |
| 577 | - K::SigUnverified, | | |
| 578 | - K::CommitsOn, | | |
| 579 | - K::FilteredTo, | | |
| 580 | - K::ClearFilter, | | |
| 581 | - K::NoCommits, | | |
| 582 | - K::BrowseFilesShort, | | |
| 583 | - K::NewerLink, | | |
| 584 | - K::OlderLink, | | |
| 585 | - K::NothingHere, | | |
| 586 | - K::DefaultBadge, | | |
| 587 | - K::TagsTitle, | | |
| 588 | - K::ForkedFrom, | | |
| 589 | - K::MirrorOf, | | |
| 590 | - K::NotSyncedYet, | | |
| 591 | - K::ForkButton, | | |
| 592 | - K::StarsAria, | | |
| 593 | - K::ArchivedNotice, | | |
| 594 | - K::RepositoryNav, | | |
| 595 | - K::TabIssues, | | |
| 596 | - K::TabPulls, | | |
| 597 | - K::TabCommits, | | |
| 598 | - K::TabReleases, | | |
| 599 | - K::TabCi, | | |
| 600 | - K::TabDiscussions, | | |
| 601 | - K::TabWiki, | | |
| 602 | - K::TabSettings, | | |
| 603 | - ]; | | |
| 604 | - | | |
| 605 | #[test] | 257 | #[test] |
| 606 | fn every_key_has_text_in_both_languages() { | 258 | fn every_key_has_text_in_both_languages() { |
| 607 | for key in ALL { | 259 | for key in ALL { |
| @@ -610,13 +262,6 @@ mod tests { |
| 610 | } | 262 | } |
| 611 | } | 263 | } |
| 612 | | 264 | |
| 613 | - #[test] | | |
| 614 | - fn all_lists_each_key_once() { | | |
| 615 | - for (i, key) in ALL.iter().enumerate() { | | |
| 616 | - assert!(!ALL[i + 1..].contains(key), "{key:?} is listed twice"); | | |
| 617 | - } | | |
| 618 | - } | | |
| 619 | - | | |
| 620 | #[test] | 265 | #[test] |
| 621 | fn turkish_differs_from_english_for_several_keys() { | 266 | fn turkish_differs_from_english_for_several_keys() { |
| 622 | let differing = ALL | 267 | let differing = ALL |
| @@ -2,287 +2,92 @@ use forge_core::discussions::DiscussionCategory; |
| 2 | | 2 | |
| 3 | use super::Lang; | 3 | use super::Lang; |
| 4 | | 4 | |
| 5 | -#[derive(Clone, Copy, Debug, PartialEq, Eq)] | 5 | +strings! { |
| 6 | -pub enum K { | 6 | + K; |
| 7 | - AllCategories, | 7 | + AllCategories => "All", "Tümü"; |
| 8 | - CategoriesNav, | 8 | + CategoriesNav => "Discussion categories", "Tartışma kategorileri"; |
| 9 | - NewDiscussion, | 9 | + NewDiscussion => "New discussion", "Yeni tartışma"; |
| 10 | - NoDiscussionsYet, | 10 | + NoDiscussionsYet => "No discussions here yet.", "Henüz tartışma yok."; |
| 11 | - Discussions, | 11 | + Discussions => "Discussions", "Tartışmalar"; |
| 12 | - Newer, | 12 | + Category => "Category", "Kategori"; |
| 13 | - Older, | 13 | + Title => "Title", "Başlık"; |
| 14 | - Category, | 14 | + Description => "Description", "Açıklama"; |
| 15 | - Title, | 15 | + StartDiscussion => "Start discussion", "Tartışma başlat"; |
| 16 | - Description, | 16 | + Save => "Save", "Kaydet"; |
| 17 | - StartDiscussion, | 17 | + Delete => "Delete", "Sil"; |
| 18 | - Cancel, | 18 | + Edit => "Edit", "Düzenle"; |
| 19 | - Save, | 19 | + EditComment => "Edit comment", "Yorumu düzenle"; |
| 20 | - Delete, | 20 | + CouldNotSave => "Could not save", "Kaydedilemedi"; |
| 21 | - Edit, | 21 | + CommentDeleted => "Comment deleted", "Yorum silindi"; |
| 22 | - EditComment, | 22 | + Answer => "Answer", "Cevap"; |
| 23 | - CouldNotSave, | 23 | + MarkAsAnswer => "Mark as answer", "Cevap olarak işaretle"; |
| 24 | - CommentDeleted, | 24 | + UnmarkAnswer => "Unmark answer", "Cevap işaretini kaldır"; |
| 25 | - Answer, | 25 | + Reply => "Reply", "Yanıtla"; |
| 26 | - MarkAsAnswer, | 26 | + DeleteDiscussion => "Delete discussion", "Tartışmayı sil"; |
| 27 | - UnmarkAnswer, | 27 | + Conversation => "Conversation", "Konuşma"; |
| 28 | - Reply, | 28 | + LockConversation => "Lock conversation", "Konuşmayı kilitle"; |
| 29 | - DeleteDiscussion, | 29 | + UnlockConversation => "Unlock conversation", "Konuşmanın kilidini aç"; |
| 30 | - Conversation, | 30 | + Answered => "Answered", "Cevaplandı"; |
| 31 | - LockConversation, | 31 | + Locked => "Locked", "Kilitli"; |
| 32 | - UnlockConversation, | 32 | + NoDescription => "_No description provided._", "_Açıklama eklenmedi._"; |
| 33 | - Answered, | 33 | + LockedNotice => "This conversation is locked. Only people with Triage access can comment.", "Bu konuşma kilitli. Yorum yalnızca Triage erişimi olanlar tarafından yapılabilir."; |
| 34 | - Locked, | 34 | + AddComment => "Add a comment", "Yorum ekle"; |
| 35 | - NoDescription, | 35 | + CommentButton => "Comment", "Yorum yap"; |
| 36 | - LockedNotice, | 36 | + ToCommentSuffix => " to comment.", "."; |
| 37 | - AddComment, | 37 | + ArchivedDiscussions => "This repository is archived, so its discussions are read-only.", "Bu depo arşivlendiği için tartışmalar salt okunur."; |
| 38 | - CommentButton, | 38 | + CategoryGeneral => "General", "Genel"; |
| 39 | - LogInLink, | 39 | + CategoryIdeas => "Ideas", "Fikirler"; |
| 40 | - ToCommentSuffix, | 40 | + CategoryQa => "Q&A", "Soru-cevap"; |
| 41 | - ArchivedDiscussions, | 41 | + CategoryAnnouncements => "Announcements", "Duyurular"; |
| 42 | - CategoryGeneral, | 42 | + |
| 43 | - CategoryIdeas, | 43 | + Wiki => "Wiki", "Wiki"; |
| 44 | - CategoryQa, | 44 | + Home => "Home", "Ana sayfa"; |
| 45 | - CategoryAnnouncements, | 45 | + AllPages => "All pages", "Tüm sayfalar"; |
| 46 | - Wiki, | 46 | + NewPage => "New page", "Yeni sayfa"; |
| 47 | - Home, | 47 | + History => "History", "Geçmiş"; |
| 48 | - AllPages, | 48 | + PageNav => "Page", "Sayfa"; |
| 49 | - NewPage, | 49 | + WikiNoPages => "This wiki has no pages yet.", "Bu wiki'de henüz sayfa yok."; |
| 50 | - History, | 50 | + CreateFirstPage => "Create the first page", "İlk sayfayı oluştur"; |
| 51 | - PageNav, | 51 | + NoPagesYet => "No pages yet. Create the first page to start the wiki.", "Henüz sayfa yok. İlk sayfayı oluşturarak wiki'yi başlatın."; |
| 52 | - WikiNoPages, | 52 | + BackToPage => "Back to page", "Sayfaya dön"; |
| 53 | - CreateFirstPage, | 53 | + NoChangesYet => "No changes yet.", "Henüz değişiklik yok."; |
| 54 | - NoPagesYet, | 54 | + PageName => "Page name", "Sayfa adı"; |
| 55 | - BackToPage, | 55 | + ContentMarkdown => "Content (Markdown)", "İçerik (Markdown)"; |
| 56 | - NoChangesYet, | 56 | + Summary => "Summary", "Özet"; |
| 57 | - PageName, | 57 | + SavePage => "Save page", "Sayfayı kaydet"; |
| 58 | - ContentMarkdown, | 58 | + PageNameRules => "Page names use letters, digits, - and _, up to 100 characters.", "Sayfa adları harf, rakam, - ve _ içerebilir; en fazla 100 karakter olabilir."; |
| 59 | - Summary, | 59 | + PageExists => "A page with that name already exists. Edit it instead.", "Bu adla bir sayfa zaten var. Bunun yerine onu düzenleyin."; |
| 60 | - SavePage, | 60 | + WikiConflict => "Someone else saved this wiki while you were editing. Your text is kept below; copy it, reload the page, and save again.", "Siz düzenlerken başka biri bu wiki'yi kaydetti. Metniniz aşağıda duruyor; kopyalayın, sayfayı yenileyin ve yeniden kaydedin."; |
| 61 | - PageNameRules, | 61 | + WikiPages => "Wiki pages", "Wiki sayfaları"; |
| 62 | - PageExists, | 62 | + |
| 63 | - WikiConflict, | 63 | + Snippets => "Snippets", "Parçacıklar"; |
| 64 | - WikiPages, | 64 | + NewSnippet => "New snippet", "Yeni parçacık"; |
| 65 | - Snippets, | 65 | + NoSnippets => "No snippets to show.", "Gösterilecek parçacık yok."; |
| 66 | - NewSnippet, | 66 | + Visibility => "Visibility", "Görünürlük"; |
| 67 | - NoSnippets, | 67 | + VisibilityPublic => "Public", "Herkese açık"; |
| 68 | - Visibility, | 68 | + VisibilityUnlisted => "Unlisted", "Listelenmez"; |
| 69 | - VisibilityPublic, | 69 | + VisibilityPrivate => "Private", "Özel"; |
| 70 | - VisibilityUnlisted, | 70 | + PublicOption => "Public: listed on /snippets", "Herkese açık: /snippets üzerinde listelenir"; |
| 71 | - VisibilityPrivate, | 71 | + UnlistedOption => "Unlisted: anyone with the link", "Listelenmez: bağlantıya sahip herkes"; |
| 72 | - PublicOption, | 72 | + PrivateOption => "Private: only you", "Özel: yalnızca siz"; |
| 73 | - UnlistedOption, | 73 | + FileLabel => "File ", "Dosya "; |
| 74 | - PrivateOption, | 74 | + FileNamePlaceholder => "file name, for example notes.md", "dosya adı, örneğin notes.md"; |
| 75 | - FileLabel, | 75 | + FileName => "File name", "Dosya adı"; |
| 76 | - FileNamePlaceholder, | 76 | + FileContents => "File contents", "Dosya içeriği"; |
| 77 | - FileName, | 77 | + Untitled => "untitled", "adsız"; |
| 78 | - FileContents, | 78 | + Files => "Files", "Dosyalar"; |
| 79 | - Untitled, | 79 | + SnippetTitlePlaceholder => "Snippet title", "Parçacık başlığı"; |
| 80 | - Files, | 80 | + DescriptionOptional => "Description (optional)", "Açıklama (isteğe bağlı)"; |
| 81 | - SnippetTitlePlaceholder, | 81 | + AddFile => "Add file", "Dosya ekle"; |
| 82 | - DescriptionOptional, | 82 | + RemoveFile => "Remove file", "Dosyayı kaldır"; |
| 83 | - AddFile, | 83 | + SaveSnippet => "Save snippet", "Parçacığı kaydet"; |
| 84 | - RemoveFile, | 84 | + EditSnippet => "Edit snippet", "Parçacığı düzenle"; |
| 85 | - SaveSnippet, | 85 | + Raw => "Raw", "Ham"; |
| 86 | - EditSnippet, | 86 | + Revisions => "Revisions", "Revizyonlar"; |
| 87 | - Raw, | 87 | + BackToSnippet => "Back to the snippet", "Parçacığa dön"; |
| 88 | - Revisions, | 88 | + NoRevisions => "No revisions.", "Revizyon yok."; |
| 89 | - BackToSnippet, | 89 | + RevisionLabel => "Revision ", "Revizyon "; |
| 90 | - NoRevisions, | 90 | + ChooseVisibility => "Choose a visibility.", "Bir görünürlük seçin."; |
| 91 | - RevisionLabel, | | |
| 92 | - ChooseVisibility, | | |
| 93 | -} | | |
| 94 | - | | |
| 95 | -pub fn t(lang: Lang, key: K) -> &'static str { | | |
| 96 | - use K::*; | | |
| 97 | - use Lang::*; | | |
| 98 | - match (key, lang) { | | |
| 99 | - (AllCategories, En) => "All", | | |
| 100 | - (AllCategories, Tr) => "Tümü", | | |
| 101 | - (CategoriesNav, En) => "Discussion categories", | | |
| 102 | - (CategoriesNav, Tr) => "Tartışma kategorileri", | | |
| 103 | - (NewDiscussion, En) => "New discussion", | | |
| 104 | - (NewDiscussion, Tr) => "Yeni tartışma", | | |
| 105 | - (NoDiscussionsYet, En) => "No discussions here yet.", | | |
| 106 | - (NoDiscussionsYet, Tr) => "Henüz tartışma yok.", | | |
| 107 | - (Discussions, En) => "Discussions", | | |
| 108 | - (Discussions, Tr) => "Tartışmalar", | | |
| 109 | - (Newer, En) => "Newer", | | |
| 110 | - (Newer, Tr) => "Daha yeni", | | |
| 111 | - (Older, En) => "Older", | | |
| 112 | - (Older, Tr) => "Daha eski", | | |
| 113 | - (Category, En) => "Category", | | |
| 114 | - (Category, Tr) => "Kategori", | | |
| 115 | - (Title, En) => "Title", | | |
| 116 | - (Title, Tr) => "Başlık", | | |
| 117 | - (Description, En) => "Description", | | |
| 118 | - (Description, Tr) => "Açıklama", | | |
| 119 | - (StartDiscussion, En) => "Start discussion", | | |
| 120 | - (StartDiscussion, Tr) => "Tartışma başlat", | | |
| 121 | - (Cancel, En) => "Cancel", | | |
| 122 | - (Cancel, Tr) => "İptal", | | |
| 123 | - (Save, En) => "Save", | | |
| 124 | - (Save, Tr) => "Kaydet", | | |
| 125 | - (Delete, En) => "Delete", | | |
| 126 | - (Delete, Tr) => "Sil", | | |
| 127 | - (Edit, En) => "Edit", | | |
| 128 | - (Edit, Tr) => "Düzenle", | | |
| 129 | - (EditComment, En) => "Edit comment", | | |
| 130 | - (EditComment, Tr) => "Yorumu düzenle", | | |
| 131 | - (CouldNotSave, En) => "Could not save", | | |
| 132 | - (CouldNotSave, Tr) => "Kaydedilemedi", | | |
| 133 | - (CommentDeleted, En) => "Comment deleted", | | |
| 134 | - (CommentDeleted, Tr) => "Yorum silindi", | | |
| 135 | - (Answer, En) => "Answer", | | |
| 136 | - (Answer, Tr) => "Cevap", | | |
| 137 | - (MarkAsAnswer, En) => "Mark as answer", | | |
| 138 | - (MarkAsAnswer, Tr) => "Cevap olarak işaretle", | | |
| 139 | - (UnmarkAnswer, En) => "Unmark answer", | | |
| 140 | - (UnmarkAnswer, Tr) => "Cevap işaretini kaldır", | | |
| 141 | - (Reply, En) => "Reply", | | |
| 142 | - (Reply, Tr) => "Yanıtla", | | |
| 143 | - (DeleteDiscussion, En) => "Delete discussion", | | |
| 144 | - (DeleteDiscussion, Tr) => "Tartışmayı sil", | | |
| 145 | - (Conversation, En) => "Conversation", | | |
| 146 | - (Conversation, Tr) => "Konuşma", | | |
| 147 | - (LockConversation, En) => "Lock conversation", | | |
| 148 | - (LockConversation, Tr) => "Konuşmayı kilitle", | | |
| 149 | - (UnlockConversation, En) => "Unlock conversation", | | |
| 150 | - (UnlockConversation, Tr) => "Konuşmanın kilidini aç", | | |
| 151 | - (Answered, En) => "Answered", | | |
| 152 | - (Answered, Tr) => "Cevaplandı", | | |
| 153 | - (Locked, En) => "Locked", | | |
| 154 | - (Locked, Tr) => "Kilitli", | | |
| 155 | - (NoDescription, En) => "_No description provided._", | | |
| 156 | - (NoDescription, Tr) => "_Açıklama eklenmedi._", | | |
| 157 | - (LockedNotice, En) => { | | |
| 158 | - "This conversation is locked. Only people with Triage access can comment." | | |
| 159 | - } | | |
| 160 | - (LockedNotice, Tr) => { | | |
| 161 | - "Bu konuşma kilitli. Yorum yalnızca Triage erişimi olanlar tarafından yapılabilir." | | |
| 162 | - } | | |
| 163 | - (AddComment, En) => "Add a comment", | | |
| 164 | - (AddComment, Tr) => "Yorum ekle", | | |
| 165 | - (CommentButton, En) => "Comment", | | |
| 166 | - (CommentButton, Tr) => "Yorum yap", | | |
| 167 | - (LogInLink, En) => "Log in", | | |
| 168 | - (LogInLink, Tr) => "giriş yapın", | | |
| 169 | - (ToCommentSuffix, En) => " to comment.", | | |
| 170 | - (ToCommentSuffix, Tr) => ".", | | |
| 171 | - (ArchivedDiscussions, En) => { | | |
| 172 | - "This repository is archived, so its discussions are read-only." | | |
| 173 | - } | | |
| 174 | - (ArchivedDiscussions, Tr) => "Bu depo arşivlendiği için tartışmalar salt okunur.", | | |
| 175 | - (CategoryGeneral, En) => "General", | | |
| 176 | - (CategoryGeneral, Tr) => "Genel", | | |
| 177 | - (CategoryIdeas, En) => "Ideas", | | |
| 178 | - (CategoryIdeas, Tr) => "Fikirler", | | |
| 179 | - (CategoryQa, En) => "Q&A", | | |
| 180 | - (CategoryQa, Tr) => "Soru-cevap", | | |
| 181 | - (CategoryAnnouncements, En) => "Announcements", | | |
| 182 | - (CategoryAnnouncements, Tr) => "Duyurular", | | |
| 183 | - | | |
| 184 | - (Wiki, En) => "Wiki", | | |
| 185 | - (Wiki, Tr) => "Wiki", | | |
| 186 | - (Home, En) => "Home", | | |
| 187 | - (Home, Tr) => "Ana sayfa", | | |
| 188 | - (AllPages, En) => "All pages", | | |
| 189 | - (AllPages, Tr) => "Tüm sayfalar", | | |
| 190 | - (NewPage, En) => "New page", | | |
| 191 | - (NewPage, Tr) => "Yeni sayfa", | | |
| 192 | - (History, En) => "History", | | |
| 193 | - (History, Tr) => "Geçmiş", | | |
| 194 | - (PageNav, En) => "Page", | | |
| 195 | - (PageNav, Tr) => "Sayfa", | | |
| 196 | - (WikiNoPages, En) => "This wiki has no pages yet.", | | |
| 197 | - (WikiNoPages, Tr) => "Bu wiki'de henüz sayfa yok.", | | |
| 198 | - (CreateFirstPage, En) => "Create the first page", | | |
| 199 | - (CreateFirstPage, Tr) => "İlk sayfayı oluştur", | | |
| 200 | - (NoPagesYet, En) => "No pages yet. Create the first page to start the wiki.", | | |
| 201 | - (NoPagesYet, Tr) => "Henüz sayfa yok. İlk sayfayı oluşturarak wiki'yi başlatın.", | | |
| 202 | - (BackToPage, En) => "Back to page", | | |
| 203 | - (BackToPage, Tr) => "Sayfaya dön", | | |
| 204 | - (NoChangesYet, En) => "No changes yet.", | | |
| 205 | - (NoChangesYet, Tr) => "Henüz değişiklik yok.", | | |
| 206 | - (PageName, En) => "Page name", | | |
| 207 | - (PageName, Tr) => "Sayfa adı", | | |
| 208 | - (ContentMarkdown, En) => "Content (Markdown)", | | |
| 209 | - (ContentMarkdown, Tr) => "İçerik (Markdown)", | | |
| 210 | - (Summary, En) => "Summary", | | |
| 211 | - (Summary, Tr) => "Özet", | | |
| 212 | - (SavePage, En) => "Save page", | | |
| 213 | - (SavePage, Tr) => "Sayfayı kaydet", | | |
| 214 | - (PageNameRules, En) => "Page names use letters, digits, - and _, up to 100 characters.", | | |
| 215 | - (PageNameRules, Tr) => { | | |
| 216 | - "Sayfa adları harf, rakam, - ve _ içerebilir; en fazla 100 karakter olabilir." | | |
| 217 | - } | | |
| 218 | - (PageExists, En) => "A page with that name already exists. Edit it instead.", | | |
| 219 | - (PageExists, Tr) => "Bu adla bir sayfa zaten var. Bunun yerine onu düzenleyin.", | | |
| 220 | - (WikiConflict, En) => { | | |
| 221 | - "Someone else saved this wiki while you were editing. Your text is kept below; copy it, reload the page, and save again." | | |
| 222 | - } | | |
| 223 | - (WikiConflict, Tr) => { | | |
| 224 | - "Siz düzenlerken başka biri bu wiki'yi kaydetti. Metniniz aşağıda duruyor; kopyalayın, sayfayı yenileyin ve yeniden kaydedin." | | |
| 225 | - } | | |
| 226 | - (WikiPages, En) => "Wiki pages", | | |
| 227 | - (WikiPages, Tr) => "Wiki sayfaları", | | |
| 228 | - | | |
| 229 | - (Snippets, En) => "Snippets", | | |
| 230 | - (Snippets, Tr) => "Parçacıklar", | | |
| 231 | - (NewSnippet, En) => "New snippet", | | |
| 232 | - (NewSnippet, Tr) => "Yeni parçacık", | | |
| 233 | - (NoSnippets, En) => "No snippets to show.", | | |
| 234 | - (NoSnippets, Tr) => "Gösterilecek parçacık yok.", | | |
| 235 | - (Visibility, En) => "Visibility", | | |
| 236 | - (Visibility, Tr) => "Görünürlük", | | |
| 237 | - (VisibilityPublic, En) => "Public", | | |
| 238 | - (VisibilityPublic, Tr) => "Herkese açık", | | |
| 239 | - (VisibilityUnlisted, En) => "Unlisted", | | |
| 240 | - (VisibilityUnlisted, Tr) => "Listelenmez", | | |
| 241 | - (VisibilityPrivate, En) => "Private", | | |
| 242 | - (VisibilityPrivate, Tr) => "Özel", | | |
| 243 | - (PublicOption, En) => "Public: listed on /snippets", | | |
| 244 | - (PublicOption, Tr) => "Herkese açık: /snippets üzerinde listelenir", | | |
| 245 | - (UnlistedOption, En) => "Unlisted: anyone with the link", | | |
| 246 | - (UnlistedOption, Tr) => "Listelenmez: bağlantıya sahip herkes", | | |
| 247 | - (PrivateOption, En) => "Private: only you", | | |
| 248 | - (PrivateOption, Tr) => "Özel: yalnızca siz", | | |
| 249 | - (FileLabel, En) => "File ", | | |
| 250 | - (FileLabel, Tr) => "Dosya ", | | |
| 251 | - (FileNamePlaceholder, En) => "file name, for example notes.md", | | |
| 252 | - (FileNamePlaceholder, Tr) => "dosya adı, örneğin notes.md", | | |
| 253 | - (FileName, En) => "File name", | | |
| 254 | - (FileName, Tr) => "Dosya adı", | | |
| 255 | - (FileContents, En) => "File contents", | | |
| 256 | - (FileContents, Tr) => "Dosya içeriği", | | |
| 257 | - (Untitled, En) => "untitled", | | |
| 258 | - (Untitled, Tr) => "adsız", | | |
| 259 | - (Files, En) => "Files", | | |
| 260 | - (Files, Tr) => "Dosyalar", | | |
| 261 | - (SnippetTitlePlaceholder, En) => "Snippet title", | | |
| 262 | - (SnippetTitlePlaceholder, Tr) => "Parçacık başlığı", | | |
| 263 | - (DescriptionOptional, En) => "Description (optional)", | | |
| 264 | - (DescriptionOptional, Tr) => "Açıklama (isteğe bağlı)", | | |
| 265 | - (AddFile, En) => "Add file", | | |
| 266 | - (AddFile, Tr) => "Dosya ekle", | | |
| 267 | - (RemoveFile, En) => "Remove file", | | |
| 268 | - (RemoveFile, Tr) => "Dosyayı kaldır", | | |
| 269 | - (SaveSnippet, En) => "Save snippet", | | |
| 270 | - (SaveSnippet, Tr) => "Parçacığı kaydet", | | |
| 271 | - (EditSnippet, En) => "Edit snippet", | | |
| 272 | - (EditSnippet, Tr) => "Parçacığı düzenle", | | |
| 273 | - (Raw, En) => "Raw", | | |
| 274 | - (Raw, Tr) => "Ham", | | |
| 275 | - (Revisions, En) => "Revisions", | | |
| 276 | - (Revisions, Tr) => "Revizyonlar", | | |
| 277 | - (BackToSnippet, En) => "Back to the snippet", | | |
| 278 | - (BackToSnippet, Tr) => "Parçacığa dön", | | |
| 279 | - (NoRevisions, En) => "No revisions.", | | |
| 280 | - (NoRevisions, Tr) => "Revizyon yok.", | | |
| 281 | - (RevisionLabel, En) => "Revision ", | | |
| 282 | - (RevisionLabel, Tr) => "Revizyon ", | | |
| 283 | - (ChooseVisibility, En) => "Choose a visibility.", | | |
| 284 | - (ChooseVisibility, Tr) => "Bir görünürlük seçin.", | | |
| 285 | - } | | |
| 286 | } | 91 | } |
| 287 | | 92 | |
| 288 | pub fn category_label(lang: Lang, category: DiscussionCategory) -> &'static str { | 93 | pub fn category_label(lang: Lang, category: DiscussionCategory) -> &'static str { |
| @@ -361,95 +166,6 @@ pub fn revisions_of(lang: Lang, title: &str) -> String { |
| 361 | mod tests { | 166 | mod tests { |
| 362 | use super::*; | 167 | use super::*; |
| 363 | | 168 | |
| 364 | - const ALL: &[K] = &[ | | |
| 365 | - K::AllCategories, | | |
| 366 | - K::CategoriesNav, | | |
| 367 | - K::NewDiscussion, | | |
| 368 | - K::NoDiscussionsYet, | | |
| 369 | - K::Discussions, | | |
| 370 | - K::Newer, | | |
| 371 | - K::Older, | | |
| 372 | - K::Category, | | |
| 373 | - K::Title, | | |
| 374 | - K::Description, | | |
| 375 | - K::StartDiscussion, | | |
| 376 | - K::Cancel, | | |
| 377 | - K::Save, | | |
| 378 | - K::Delete, | | |
| 379 | - K::Edit, | | |
| 380 | - K::EditComment, | | |
| 381 | - K::CouldNotSave, | | |
| 382 | - K::CommentDeleted, | | |
| 383 | - K::Answer, | | |
| 384 | - K::MarkAsAnswer, | | |
| 385 | - K::UnmarkAnswer, | | |
| 386 | - K::Reply, | | |
| 387 | - K::DeleteDiscussion, | | |
| 388 | - K::Conversation, | | |
| 389 | - K::LockConversation, | | |
| 390 | - K::UnlockConversation, | | |
| 391 | - K::Answered, | | |
| 392 | - K::Locked, | | |
| 393 | - K::NoDescription, | | |
| 394 | - K::LockedNotice, | | |
| 395 | - K::AddComment, | | |
| 396 | - K::CommentButton, | | |
| 397 | - K::LogInLink, | | |
| 398 | - K::ToCommentSuffix, | | |
| 399 | - K::ArchivedDiscussions, | | |
| 400 | - K::CategoryGeneral, | | |
| 401 | - K::CategoryIdeas, | | |
| 402 | - K::CategoryQa, | | |
| 403 | - K::CategoryAnnouncements, | | |
| 404 | - K::Wiki, | | |
| 405 | - K::Home, | | |
| 406 | - K::AllPages, | | |
| 407 | - K::NewPage, | | |
| 408 | - K::History, | | |
| 409 | - K::PageNav, | | |
| 410 | - K::WikiNoPages, | | |
| 411 | - K::CreateFirstPage, | | |
| 412 | - K::NoPagesYet, | | |
| 413 | - K::BackToPage, | | |
| 414 | - K::NoChangesYet, | | |
| 415 | - K::PageName, | | |
| 416 | - K::ContentMarkdown, | | |
| 417 | - K::Summary, | | |
| 418 | - K::SavePage, | | |
| 419 | - K::PageNameRules, | | |
| 420 | - K::PageExists, | | |
| 421 | - K::WikiConflict, | | |
| 422 | - K::WikiPages, | | |
| 423 | - K::Snippets, | | |
| 424 | - K::NewSnippet, | | |
| 425 | - K::NoSnippets, | | |
| 426 | - K::Visibility, | | |
| 427 | - K::VisibilityPublic, | | |
| 428 | - K::VisibilityUnlisted, | | |
| 429 | - K::VisibilityPrivate, | | |
| 430 | - K::PublicOption, | | |
| 431 | - K::UnlistedOption, | | |
| 432 | - K::PrivateOption, | | |
| 433 | - K::FileLabel, | | |
| 434 | - K::FileNamePlaceholder, | | |
| 435 | - K::FileName, | | |
| 436 | - K::FileContents, | | |
| 437 | - K::Untitled, | | |
| 438 | - K::Files, | | |
| 439 | - K::SnippetTitlePlaceholder, | | |
| 440 | - K::DescriptionOptional, | | |
| 441 | - K::AddFile, | | |
| 442 | - K::RemoveFile, | | |
| 443 | - K::SaveSnippet, | | |
| 444 | - K::EditSnippet, | | |
| 445 | - K::Raw, | | |
| 446 | - K::Revisions, | | |
| 447 | - K::BackToSnippet, | | |
| 448 | - K::NoRevisions, | | |
| 449 | - K::RevisionLabel, | | |
| 450 | - K::ChooseVisibility, | | |
| 451 | - ]; | | |
| 452 | - | | |
| 453 | #[test] | 169 | #[test] |
| 454 | fn every_key_has_both_languages() { | 170 | fn every_key_has_both_languages() { |
| 455 | for key in ALL { | 171 | for key in ALL { |
| @@ -1,383 +1,91 @@ |
| 1 | use super::Lang; | 1 | use super::Lang; |
| 2 | | 2 | |
| 3 | -#[derive(Clone, Copy, Debug, PartialEq, Eq)] | 3 | +strings! { |
| 4 | -pub enum K { | 4 | + K; |
| 5 | - ActiveField, | 5 | + ActiveField => "Active: deliver events to this URL", "Etkin: olaylar bu URL'ye teslim edilir"; |
| 6 | - AddPullMirror, | 6 | + AddPullMirror => "Add pull mirror", "Çekme yansısı ekle"; |
| 7 | - AddPushMirror, | 7 | + AddPushMirror => "Add push mirror", "Gönderme yansısı ekle"; |
| 8 | - AddWebhook, | 8 | + AddWebhook => "Add webhook", "Web kancası ekle"; |
| 9 | - ArchivedNotice, | 9 | + ArchivedNotice => "This repository is archived. Mirrors are read-only: they cannot be changed, synced or deleted.", "Bu depo arşivlenmiş. Yansılar salt okunurdur: değiştirilemez, eşitlenemez ya da silinemez."; |
| 10 | - BackToWebhooks, | 10 | + BackToWebhooks => "Back to webhooks", "Web kancalarına dön"; |
| 11 | - ClearSecret, | 11 | + ClearSecret => "Clear the stored password or token", "Kayıtlı parola veya belirteci temizle"; |
| 12 | - CreateWebhook, | 12 | + CreateWebhook => "Create webhook", "Web kancası oluştur"; |
| 13 | - CurrentUrl, | 13 | + CurrentUrl => "Current URL:", "Mevcut URL:"; |
| 14 | - Cancel, | 14 | + DeleteConfirm => "Delete it? This cannot be undone.", "Silinsin mi? Bu işlem geri alınamaz."; |
| 15 | - DeleteConfirm, | 15 | + DeleteMirror => "Delete mirror", "Yansıyı sil"; |
| 16 | - DeleteMirror, | 16 | + DeleteWebhook => "Delete webhook", "Web kancasını sil"; |
| 17 | - DeleteWebhook, | 17 | + DirectionPull => "Pull", "Çekme"; |
| 18 | - DirectionPull, | 18 | + DirectionPush => "Push", "Gönderme"; |
| 19 | - DirectionPush, | 19 | + EnabledField => "Enabled: sync on the interval and after pushes", "Etkin: aralıkla ve göndermelerden sonra eşitlenir"; |
| 20 | - EnabledField, | 20 | + ErrIntervalMax => "The sync interval can be at most one year.", "Eşitleme aralığı en fazla bir yıl olabilir."; |
| 21 | - ErrIntervalMax, | 21 | + ErrIntervalNotWhole => "The sync interval must be a whole number of minutes.", "Eşitleme aralığı dakika cinsinden tam sayı olmalıdır."; |
| 22 | - ErrIntervalNotWhole, | 22 | + ErrNoEvent => "Choose at least one event.", "En az bir olay seçin."; |
| 23 | - ErrNoEvent, | 23 | + ErrUrlMissing => "Enter the URL the events are sent to.", "Olayların gönderileceği URL'yi girin."; |
| 24 | - ErrUrlMissing, | 24 | + ErrUrlRequired => "Enter the URL of the repository to mirror.", "Yansılanacak deponun URL'sini girin."; |
| 25 | - ErrUrlRequired, | 25 | + ErrorLabel => "Error", "Hata"; |
| 26 | - ErrorLabel, | 26 | + EvCreate => "Branch and tag creation", "Dal ve etiket oluşturma"; |
| 27 | - EvCreate, | 27 | + EvDelete => "Branch and tag deletion", "Dal ve etiket silme"; |
| 28 | - EvDelete, | 28 | + EvIssueComment => "Comments on issues and pull requests", "Sorun ve çekme isteklerindeki yorumlar"; |
| 29 | - EvIssueComment, | 29 | + EvIssues => "Issues: opened, closed, reopened, edited, labels, assignees", "Sorunlar: açıldı, kapatıldı, yeniden açıldı, düzenlendi, etiketler, atananlar"; |
| 30 | - EvIssues, | 30 | + EvPullRequest => "Pull requests: opened, closed, reopened, merged, updated", "Çekme istekleri: açıldı, kapatıldı, yeniden açıldı, birleştirildi, güncellendi"; |
| 31 | - EvPullRequest, | 31 | + EvPullRequestReview => "Pull request reviews", "Çekme isteği incelemeleri"; |
| 32 | - EvPullRequestReview, | 32 | + EvPush => "Pushes to a branch or tag", "Bir dala veya etikete gönderimler"; |
| 33 | - EvPush, | 33 | + EvRelease => "Releases: published, updated, deleted", "Sürümler: yayımlandı, güncellendi, silindi"; |
| 34 | - EvRelease, | 34 | + Events => "Events", "Olaylar"; |
| 35 | - Events, | 35 | + HookArchivedNotice => "This repository is archived. Webhooks are read-only: hooks cannot be changed, tested or redelivered.", "Bu depo arşivlenmiş. Web kancaları salt okunurdur: değiştirilemez, test edilemez ya da yeniden teslim edilemez."; |
| 36 | - HookArchivedNotice, | 36 | + HookNoticeConfirm => "The delete was not confirmed. Nothing was deleted.", "Silme onaylanmadı. Hiçbir şey silinmedi."; |
| 37 | - HookNoticeConfirm, | 37 | + HookNoticeCreated => "Webhook created. A ping was queued.", "Web kancası oluşturuldu. Bir ping sıraya alındı."; |
| 38 | - HookNoticeCreated, | 38 | + HookNoticeDeleted => "Webhook deleted.", "Web kancası silindi."; |
| 39 | - HookNoticeDeleted, | 39 | + HookNoticeRedelivered => "The delivery was queued again.", "Teslimat yeniden sıraya alındı."; |
| 40 | - HookNoticeRedelivered, | 40 | + HookNoticeSaved => "Webhook saved.", "Web kancası kaydedildi."; |
| 41 | - HookNoticeSaved, | 41 | + HookNoticeTested => "A test ping was queued.", "Bir test pingi sıraya alındı."; |
| 42 | - HookNoticeTested, | 42 | + IntervalField => "Sync interval in minutes (0 = manual only, at least 10)", "Dakika cinsinden eşitleme aralığı (0 = yalnızca elle, en az 10)"; |
| 43 | - IntervalField, | 43 | + LastSync => "Last sync:", "Son eşitleme:"; |
| 44 | - LastSync, | 44 | + ManualOnly => "manual only", "yalnızca elle"; |
| 45 | - ManualOnly, | 45 | + Mirrors => "Mirrors", "Yansılar"; |
| 46 | - Mirrors, | 46 | + NoDeliveries => "No deliveries yet.", "Henüz teslimat yok."; |
| 47 | - NoDeliveries, | 47 | + NoMirrors => "No mirrors yet.", "Henüz yansı yok."; |
| 48 | - NoMirrors, | 48 | + NoWebhooks => "No webhooks yet. Add one to send events to another service.", "Henüz web kancası yok. Olayları başka bir servise göndermek için bir tane ekleyin."; |
| 49 | - NoWebhooks, | 49 | + NoneYet => "none yet", "henüz yok"; |
| 50 | - NoneYet, | 50 | + NoResponse => "no response", "yanıt yok"; |
| 51 | - NoResponse, | 51 | + NoticeCreated => "Push mirror created. It will be pushed after the next push or on its interval.", "Gönderme yansısı oluşturuldu. Bir sonraki göndermeden sonra ya da aralığı dolduğunda gönderilecek."; |
| 52 | - NoticeCreated, | 52 | + NoticeDeleted => "Mirror deleted.", "Yansı silindi."; |
| 53 | - NoticeDeleted, | 53 | + NoticePullCreated => "Pull mirror created. The first sync is queued.", "Çekme yansısı oluşturuldu. İlk eşitleme sıraya alındı."; |
| 54 | - NoticePullCreated, | 54 | + NoticePullNotEmpty => "A pull mirror can only be added to an empty repository. Nothing was changed.", "Çekme yansısı yalnızca boş bir depoya eklenebilir. Hiçbir şey değiştirilmedi."; |
| 55 | - NoticePullNotEmpty, | 55 | + NoticeSaved => "Mirror saved.", "Yansı kaydedildi."; |
| 56 | - NoticeSaved, | 56 | + NoticeSynced => "A sync was queued.", "Bir eşitleme sıraya alındı."; |
| 57 | - NoticeSynced, | 57 | + PayloadUrl => "Payload URL", "Yük URL'si"; |
| 58 | - PayloadUrl, | 58 | + PullMirror => "Pull mirror", "Çekme yansısı"; |
| 59 | - PullMirror, | 59 | + PushMirror => "Push mirror", "Gönderme yansısı"; |
| 60 | - PushMirror, | 60 | + RecentDeliveries => "Recent deliveries", "Son teslimatlar"; |
| 61 | - RecentDeliveries, | 61 | + Redeliver => "Redeliver", "Yeniden teslim et"; |
| 62 | - Redeliver, | 62 | + RemoteUrl => "Remote URL", "Uzak URL"; |
| 63 | - RemoteUrl, | 63 | + RepositoryUrl => "Repository URL", "Depo URL'si"; |
| 64 | - RepositoryUrl, | 64 | + RequestBody => "Request body", "İstek gövdesi"; |
| 65 | - RequestBody, | 65 | + RequestHeaders => "Request headers", "İstek üst bilgileri"; |
| 66 | - RequestHeaders, | 66 | + Response => "Response", "Yanıt"; |
| 67 | - Response, | 67 | + ResponseBody => "Response body", "Yanıt gövdesi"; |
| 68 | - ResponseBody, | 68 | + ResponseHeaders => "Response headers", "Yanıt üst bilgileri"; |
| 69 | - ResponseHeaders, | 69 | + SaveMirror => "Save mirror", "Yansıyı kaydet"; |
| 70 | - SaveMirror, | 70 | + SaveWebhook => "Save webhook", "Web kancasını kaydet"; |
| 71 | - SaveWebhook, | 71 | + Secret => "Secret", "Gizli anahtar"; |
| 72 | - Secret, | 72 | + SecretHintSet => "A secret is set. Leave the field blank to keep it, or type a new one to replace it.", "Bir gizli anahtar ayarlı. Olduğu gibi bırakmak için alanı boş bırakın ya da yenisini yazarak değiştirin."; |
| 73 | - SecretHintSet, | 73 | + SecretHintUnset => "No secret is set. Type one to add it.", "Gizli anahtar ayarlı değil. Eklemek için bir tane yazın."; |
| 74 | - SecretHintUnset, | 74 | + SecretOptional => "Password or token (optional)", "Parola veya belirteç (isteğe bağlı)"; |
| 75 | - SecretOptional, | 75 | + SendTestPing => "Send test ping", "Test pingi gönder"; |
| 76 | - SendTestPing, | 76 | + StateFailed => "failed, will retry", "başarısız, yeniden denenecek"; |
| 77 | - StateFailed, | 77 | + StateGaveUp => "gave up", "vazgeçildi"; |
| 78 | - StateGaveUp, | 78 | + StatePending => "pending", "beklemede"; |
| 79 | - StatePending, | 79 | + Status => "Status", "Durum"; |
| 80 | - Status, | 80 | + StatusFailed => "failed", "başarısız"; |
| 81 | - StatusFailed, | 81 | + StatusLower => "status", "durum"; |
| 82 | - StatusLower, | 82 | + StatusNotRun => "not run yet", "henüz çalışmadı"; |
| 83 | - StatusNotRun, | 83 | + StatusOk => "ok", "tamam"; |
| 84 | - StatusOk, | 84 | + SyncHeading => "Sync", "Eşitleme"; |
| 85 | - SyncHeading, | 85 | + SyncNow => "Sync now", "Şimdi eşitle"; |
| 86 | - SyncNow, | 86 | + Test => "Test", "Test"; |
| 87 | - Test, | 87 | + UsernameOptional => "Username (optional)", "Kullanıcı adı (isteğe bağlı)"; |
| 88 | - UsernameOptional, | 88 | + Webhooks => "Webhooks", "Web kancaları"; |
| 89 | - Webhooks, | | |
| 90 | -} | | |
| 91 | - | | |
| 92 | -#[cfg(test)] | | |
| 93 | -pub const ALL: &[K] = &[ | | |
| 94 | - K::ActiveField, | | |
| 95 | - K::AddPullMirror, | | |
| 96 | - K::AddPushMirror, | | |
| 97 | - K::AddWebhook, | | |
| 98 | - K::ArchivedNotice, | | |
| 99 | - K::BackToWebhooks, | | |
| 100 | - K::ClearSecret, | | |
| 101 | - K::CreateWebhook, | | |
| 102 | - K::CurrentUrl, | | |
| 103 | - K::DeleteConfirm, | | |
| 104 | - K::DeleteMirror, | | |
| 105 | - K::DeleteWebhook, | | |
| 106 | - K::DirectionPull, | | |
| 107 | - K::DirectionPush, | | |
| 108 | - K::EnabledField, | | |
| 109 | - K::ErrIntervalMax, | | |
| 110 | - K::ErrIntervalNotWhole, | | |
| 111 | - K::ErrNoEvent, | | |
| 112 | - K::ErrUrlMissing, | | |
| 113 | - K::ErrUrlRequired, | | |
| 114 | - K::ErrorLabel, | | |
| 115 | - K::EvCreate, | | |
| 116 | - K::EvDelete, | | |
| 117 | - K::EvIssueComment, | | |
| 118 | - K::EvIssues, | | |
| 119 | - K::EvPullRequest, | | |
| 120 | - K::EvPullRequestReview, | | |
| 121 | - K::EvPush, | | |
| 122 | - K::EvRelease, | | |
| 123 | - K::Events, | | |
| 124 | - K::HookArchivedNotice, | | |
| 125 | - K::HookNoticeConfirm, | | |
| 126 | - K::HookNoticeCreated, | | |
| 127 | - K::HookNoticeDeleted, | | |
| 128 | - K::HookNoticeRedelivered, | | |
| 129 | - K::HookNoticeSaved, | | |
| 130 | - K::HookNoticeTested, | | |
| 131 | - K::IntervalField, | | |
| 132 | - K::LastSync, | | |
| 133 | - K::ManualOnly, | | |
| 134 | - K::Mirrors, | | |
| 135 | - K::NoDeliveries, | | |
| 136 | - K::NoMirrors, | | |
| 137 | - K::NoWebhooks, | | |
| 138 | - K::NoneYet, | | |
| 139 | - K::NoResponse, | | |
| 140 | - K::NoticeCreated, | | |
| 141 | - K::NoticeDeleted, | | |
| 142 | - K::NoticePullCreated, | | |
| 143 | - K::NoticePullNotEmpty, | | |
| 144 | - K::NoticeSaved, | | |
| 145 | - K::NoticeSynced, | | |
| 146 | - K::PayloadUrl, | | |
| 147 | - K::PullMirror, | | |
| 148 | - K::PushMirror, | | |
| 149 | - K::RecentDeliveries, | | |
| 150 | - K::Redeliver, | | |
| 151 | - K::RemoteUrl, | | |
| 152 | - K::RepositoryUrl, | | |
| 153 | - K::RequestBody, | | |
| 154 | - K::RequestHeaders, | | |
| 155 | - K::Response, | | |
| 156 | - K::ResponseBody, | | |
| 157 | - K::ResponseHeaders, | | |
| 158 | - K::SaveMirror, | | |
| 159 | - K::SaveWebhook, | | |
| 160 | - K::Secret, | | |
| 161 | - K::SecretHintSet, | | |
| 162 | - K::SecretHintUnset, | | |
| 163 | - K::SecretOptional, | | |
| 164 | - K::SendTestPing, | | |
| 165 | - K::StateFailed, | | |
| 166 | - K::StateGaveUp, | | |
| 167 | - K::StatePending, | | |
| 168 | - K::Status, | | |
| 169 | - K::StatusFailed, | | |
| 170 | - K::StatusLower, | | |
| 171 | - K::StatusNotRun, | | |
| 172 | - K::StatusOk, | | |
| 173 | - K::SyncHeading, | | |
| 174 | - K::SyncNow, | | |
| 175 | - K::Test, | | |
| 176 | - K::UsernameOptional, | | |
| 177 | - K::Webhooks, | | |
| 178 | -]; | | |
| 179 | - | | |
| 180 | -pub fn t(lang: Lang, key: K) -> &'static str { | | |
| 181 | - use K::*; | | |
| 182 | - use Lang::*; | | |
| 183 | - match (key, lang) { | | |
| 184 | - (ActiveField, En) => "Active: deliver events to this URL", | | |
| 185 | - (ActiveField, Tr) => "Etkin: olaylar bu URL'ye teslim edilir", | | |
| 186 | - (AddPullMirror, En) => "Add pull mirror", | | |
| 187 | - (AddPullMirror, Tr) => "Çekme yansısı ekle", | | |
| 188 | - (AddPushMirror, En) => "Add push mirror", | | |
| 189 | - (AddPushMirror, Tr) => "Gönderme yansısı ekle", | | |
| 190 | - (AddWebhook, En) => "Add webhook", | | |
| 191 | - (AddWebhook, Tr) => "Web kancası ekle", | | |
| 192 | - (ArchivedNotice, En) => { | | |
| 193 | - "This repository is archived. Mirrors are read-only: they cannot be changed, synced or deleted." | | |
| 194 | - } | | |
| 195 | - (ArchivedNotice, Tr) => { | | |
| 196 | - "Bu depo arşivlenmiş. Yansılar salt okunurdur: değiştirilemez, eşitlenemez ya da silinemez." | | |
| 197 | - } | | |
| 198 | - (BackToWebhooks, En) => "Back to webhooks", | | |
| 199 | - (BackToWebhooks, Tr) => "Web kancalarına dön", | | |
| 200 | - (ClearSecret, En) => "Clear the stored password or token", | | |
| 201 | - (ClearSecret, Tr) => "Kayıtlı parola veya belirteci temizle", | | |
| 202 | - (CreateWebhook, En) => "Create webhook", | | |
| 203 | - (CreateWebhook, Tr) => "Web kancası oluştur", | | |
| 204 | - (CurrentUrl, En) => "Current URL:", | | |
| 205 | - (CurrentUrl, Tr) => "Mevcut URL:", | | |
| 206 | - (Cancel, En) => "Cancel", | | |
| 207 | - (Cancel, Tr) => "Vazgeç", | | |
| 208 | - (DeleteConfirm, En) => "Delete it? This cannot be undone.", | | |
| 209 | - (DeleteConfirm, Tr) => "Silinsin mi? Bu işlem geri alınamaz.", | | |
| 210 | - (DeleteMirror, En) => "Delete mirror", | | |
| 211 | - (DeleteMirror, Tr) => "Yansıyı sil", | | |
| 212 | - (DeleteWebhook, En) => "Delete webhook", | | |
| 213 | - (DeleteWebhook, Tr) => "Web kancasını sil", | | |
| 214 | - (DirectionPull, En) => "Pull", | | |
| 215 | - (DirectionPull, Tr) => "Çekme", | | |
| 216 | - (DirectionPush, En) => "Push", | | |
| 217 | - (DirectionPush, Tr) => "Gönderme", | | |
| 218 | - (EnabledField, En) => "Enabled: sync on the interval and after pushes", | | |
| 219 | - (EnabledField, Tr) => "Etkin: aralıkla ve göndermelerden sonra eşitlenir", | | |
| 220 | - (ErrIntervalMax, En) => "The sync interval can be at most one year.", | | |
| 221 | - (ErrIntervalMax, Tr) => "Eşitleme aralığı en fazla bir yıl olabilir.", | | |
| 222 | - (ErrIntervalNotWhole, En) => "The sync interval must be a whole number of minutes.", | | |
| 223 | - (ErrIntervalNotWhole, Tr) => "Eşitleme aralığı dakika cinsinden tam sayı olmalıdır.", | | |
| 224 | - (ErrNoEvent, En) => "Choose at least one event.", | | |
| 225 | - (ErrNoEvent, Tr) => "En az bir olay seçin.", | | |
| 226 | - (ErrUrlMissing, En) => "Enter the URL the events are sent to.", | | |
| 227 | - (ErrUrlMissing, Tr) => "Olayların gönderileceği URL'yi girin.", | | |
| 228 | - (ErrUrlRequired, En) => "Enter the URL of the repository to mirror.", | | |
| 229 | - (ErrUrlRequired, Tr) => "Yansılanacak deponun URL'sini girin.", | | |
| 230 | - (ErrorLabel, En) => "Error", | | |
| 231 | - (ErrorLabel, Tr) => "Hata", | | |
| 232 | - (EvCreate, En) => "Branch and tag creation", | | |
| 233 | - (EvCreate, Tr) => "Dal ve etiket oluşturma", | | |
| 234 | - (EvDelete, En) => "Branch and tag deletion", | | |
| 235 | - (EvDelete, Tr) => "Dal ve etiket silme", | | |
| 236 | - (EvIssueComment, En) => "Comments on issues and pull requests", | | |
| 237 | - (EvIssueComment, Tr) => "Sorun ve çekme isteklerindeki yorumlar", | | |
| 238 | - (EvIssues, En) => "Issues: opened, closed, reopened, edited, labels, assignees", | | |
| 239 | - (EvIssues, Tr) => { | | |
| 240 | - "Sorunlar: açıldı, kapatıldı, yeniden açıldı, düzenlendi, etiketler, atananlar" | | |
| 241 | - } | | |
| 242 | - (EvPullRequest, En) => "Pull requests: opened, closed, reopened, merged, updated", | | |
| 243 | - (EvPullRequest, Tr) => { | | |
| 244 | - "Çekme istekleri: açıldı, kapatıldı, yeniden açıldı, birleştirildi, güncellendi" | | |
| 245 | - } | | |
| 246 | - (EvPullRequestReview, En) => "Pull request reviews", | | |
| 247 | - (EvPullRequestReview, Tr) => "Çekme isteği incelemeleri", | | |
| 248 | - (EvPush, En) => "Pushes to a branch or tag", | | |
| 249 | - (EvPush, Tr) => "Bir dala veya etikete gönderimler", | | |
| 250 | - (EvRelease, En) => "Releases: published, updated, deleted", | | |
| 251 | - (EvRelease, Tr) => "Sürümler: yayımlandı, güncellendi, silindi", | | |
| 252 | - (Events, En) => "Events", | | |
| 253 | - (Events, Tr) => "Olaylar", | | |
| 254 | - (HookArchivedNotice, En) => { | | |
| 255 | - "This repository is archived. Webhooks are read-only: hooks cannot be changed, tested or redelivered." | | |
| 256 | - } | | |
| 257 | - (HookArchivedNotice, Tr) => { | | |
| 258 | - "Bu depo arşivlenmiş. Web kancaları salt okunurdur: değiştirilemez, test edilemez ya da yeniden teslim edilemez." | | |
| 259 | - } | | |
| 260 | - (HookNoticeConfirm, En) => "The delete was not confirmed. Nothing was deleted.", | | |
| 261 | - (HookNoticeConfirm, Tr) => "Silme onaylanmadı. Hiçbir şey silinmedi.", | | |
| 262 | - (HookNoticeCreated, En) => "Webhook created. A ping was queued.", | | |
| 263 | - (HookNoticeCreated, Tr) => "Web kancası oluşturuldu. Bir ping sıraya alındı.", | | |
| 264 | - (HookNoticeDeleted, En) => "Webhook deleted.", | | |
| 265 | - (HookNoticeDeleted, Tr) => "Web kancası silindi.", | | |
| 266 | - (HookNoticeRedelivered, En) => "The delivery was queued again.", | | |
| 267 | - (HookNoticeRedelivered, Tr) => "Teslimat yeniden sıraya alındı.", | | |
| 268 | - (HookNoticeSaved, En) => "Webhook saved.", | | |
| 269 | - (HookNoticeSaved, Tr) => "Web kancası kaydedildi.", | | |
| 270 | - (HookNoticeTested, En) => "A test ping was queued.", | | |
| 271 | - (HookNoticeTested, Tr) => "Bir test pingi sıraya alındı.", | | |
| 272 | - (IntervalField, En) => "Sync interval in minutes (0 = manual only, at least 10)", | | |
| 273 | - (IntervalField, Tr) => "Dakika cinsinden eşitleme aralığı (0 = yalnızca elle, en az 10)", | | |
| 274 | - (LastSync, En) => "Last sync:", | | |
| 275 | - (LastSync, Tr) => "Son eşitleme:", | | |
| 276 | - (ManualOnly, En) => "manual only", | | |
| 277 | - (ManualOnly, Tr) => "yalnızca elle", | | |
| 278 | - (Mirrors, En) => "Mirrors", | | |
| 279 | - (Mirrors, Tr) => "Yansılar", | | |
| 280 | - (NoDeliveries, En) => "No deliveries yet.", | | |
| 281 | - (NoDeliveries, Tr) => "Henüz teslimat yok.", | | |
| 282 | - (NoMirrors, En) => "No mirrors yet.", | | |
| 283 | - (NoMirrors, Tr) => "Henüz yansı yok.", | | |
| 284 | - (NoWebhooks, En) => "No webhooks yet. Add one to send events to another service.", | | |
| 285 | - (NoWebhooks, Tr) => { | | |
| 286 | - "Henüz web kancası yok. Olayları başka bir servise göndermek için bir tane ekleyin." | | |
| 287 | - } | | |
| 288 | - (NoneYet, En) => "none yet", | | |
| 289 | - (NoneYet, Tr) => "henüz yok", | | |
| 290 | - (NoResponse, En) => "no response", | | |
| 291 | - (NoResponse, Tr) => "yanıt yok", | | |
| 292 | - (NoticeCreated, En) => { | | |
| 293 | - "Push mirror created. It will be pushed after the next push or on its interval." | | |
| 294 | - } | | |
| 295 | - (NoticeCreated, Tr) => { | | |
| 296 | - "Gönderme yansısı oluşturuldu. Bir sonraki göndermeden sonra ya da aralığı dolduğunda gönderilecek." | | |
| 297 | - } | | |
| 298 | - (NoticeDeleted, En) => "Mirror deleted.", | | |
| 299 | - (NoticeDeleted, Tr) => "Yansı silindi.", | | |
| 300 | - (NoticePullCreated, En) => "Pull mirror created. The first sync is queued.", | | |
| 301 | - (NoticePullCreated, Tr) => "Çekme yansısı oluşturuldu. İlk eşitleme sıraya alındı.", | | |
| 302 | - (NoticePullNotEmpty, En) => { | | |
| 303 | - "A pull mirror can only be added to an empty repository. Nothing was changed." | | |
| 304 | - } | | |
| 305 | - (NoticePullNotEmpty, Tr) => { | | |
| 306 | - "Çekme yansısı yalnızca boş bir depoya eklenebilir. Hiçbir şey değiştirilmedi." | | |
| 307 | - } | | |
| 308 | - (NoticeSaved, En) => "Mirror saved.", | | |
| 309 | - (NoticeSaved, Tr) => "Yansı kaydedildi.", | | |
| 310 | - (NoticeSynced, En) => "A sync was queued.", | | |
| 311 | - (NoticeSynced, Tr) => "Bir eşitleme sıraya alındı.", | | |
| 312 | - (PayloadUrl, En) => "Payload URL", | | |
| 313 | - (PayloadUrl, Tr) => "Yük URL'si", | | |
| 314 | - (PullMirror, En) => "Pull mirror", | | |
| 315 | - (PullMirror, Tr) => "Çekme yansısı", | | |
| 316 | - (PushMirror, En) => "Push mirror", | | |
| 317 | - (PushMirror, Tr) => "Gönderme yansısı", | | |
| 318 | - (RecentDeliveries, En) => "Recent deliveries", | | |
| 319 | - (RecentDeliveries, Tr) => "Son teslimatlar", | | |
| 320 | - (Redeliver, En) => "Redeliver", | | |
| 321 | - (Redeliver, Tr) => "Yeniden teslim et", | | |
| 322 | - (RemoteUrl, En) => "Remote URL", | | |
| 323 | - (RemoteUrl, Tr) => "Uzak URL", | | |
| 324 | - (RepositoryUrl, En) => "Repository URL", | | |
| 325 | - (RepositoryUrl, Tr) => "Depo URL'si", | | |
| 326 | - (RequestBody, En) => "Request body", | | |
| 327 | - (RequestBody, Tr) => "İstek gövdesi", | | |
| 328 | - (RequestHeaders, En) => "Request headers", | | |
| 329 | - (RequestHeaders, Tr) => "İstek üst bilgileri", | | |
| 330 | - (Response, En) => "Response", | | |
| 331 | - (Response, Tr) => "Yanıt", | | |
| 332 | - (ResponseBody, En) => "Response body", | | |
| 333 | - (ResponseBody, Tr) => "Yanıt gövdesi", | | |
| 334 | - (ResponseHeaders, En) => "Response headers", | | |
| 335 | - (ResponseHeaders, Tr) => "Yanıt üst bilgileri", | | |
| 336 | - (SaveMirror, En) => "Save mirror", | | |
| 337 | - (SaveMirror, Tr) => "Yansıyı kaydet", | | |
| 338 | - (SaveWebhook, En) => "Save webhook", | | |
| 339 | - (SaveWebhook, Tr) => "Web kancasını kaydet", | | |
| 340 | - (Secret, En) => "Secret", | | |
| 341 | - (Secret, Tr) => "Gizli anahtar", | | |
| 342 | - (SecretHintSet, En) => { | | |
| 343 | - "A secret is set. Leave the field blank to keep it, or type a new one to replace it." | | |
| 344 | - } | | |
| 345 | - (SecretHintSet, Tr) => { | | |
| 346 | - "Bir gizli anahtar ayarlı. Olduğu gibi bırakmak için alanı boş bırakın ya da yenisini yazarak değiştirin." | | |
| 347 | - } | | |
| 348 | - (SecretHintUnset, En) => "No secret is set. Type one to add it.", | | |
| 349 | - (SecretHintUnset, Tr) => "Gizli anahtar ayarlı değil. Eklemek için bir tane yazın.", | | |
| 350 | - (SecretOptional, En) => "Password or token (optional)", | | |
| 351 | - (SecretOptional, Tr) => "Parola veya belirteç (isteğe bağlı)", | | |
| 352 | - (SendTestPing, En) => "Send test ping", | | |
| 353 | - (SendTestPing, Tr) => "Test pingi gönder", | | |
| 354 | - (StateFailed, En) => "failed, will retry", | | |
| 355 | - (StateFailed, Tr) => "başarısız, yeniden denenecek", | | |
| 356 | - (StateGaveUp, En) => "gave up", | | |
| 357 | - (StateGaveUp, Tr) => "vazgeçildi", | | |
| 358 | - (StatePending, En) => "pending", | | |
| 359 | - (StatePending, Tr) => "beklemede", | | |
| 360 | - (Status, En) => "Status", | | |
| 361 | - (Status, Tr) => "Durum", | | |
| 362 | - (StatusFailed, En) => "failed", | | |
| 363 | - (StatusFailed, Tr) => "başarısız", | | |
| 364 | - (StatusLower, En) => "status", | | |
| 365 | - (StatusLower, Tr) => "durum", | | |
| 366 | - (StatusNotRun, En) => "not run yet", | | |
| 367 | - (StatusNotRun, Tr) => "henüz çalışmadı", | | |
| 368 | - (StatusOk, En) => "ok", | | |
| 369 | - (StatusOk, Tr) => "tamam", | | |
| 370 | - (SyncHeading, En) => "Sync", | | |
| 371 | - (SyncHeading, Tr) => "Eşitleme", | | |
| 372 | - (SyncNow, En) => "Sync now", | | |
| 373 | - (SyncNow, Tr) => "Şimdi eşitle", | | |
| 374 | - (Test, En) => "Test", | | |
| 375 | - (Test, Tr) => "Test", | | |
| 376 | - (UsernameOptional, En) => "Username (optional)", | | |
| 377 | - (UsernameOptional, Tr) => "Kullanıcı adı (isteğe bağlı)", | | |
| 378 | - (Webhooks, En) => "Webhooks", | | |
| 379 | - (Webhooks, Tr) => "Web kancaları", | | |
| 380 | - } | | |
| 381 | } | 89 | } |
| 382 | | 90 | |
| 383 | pub fn interval_too_short(lang: Lang, min: u32) -> String { | 91 | pub fn interval_too_short(lang: Lang, min: u32) -> String { |
Diff too large; view file
| @@ -1,150 +1,143 @@ |
| 1 | use super::Lang; | 1 | use super::Lang; |
| 2 | | 2 | |
| 3 | -#[derive(Clone, Copy, Debug, PartialEq, Eq)] | 3 | +strings! { |
| 4 | -pub enum K { | 4 | + K; |
| 5 | - CouldNotSave, | 5 | + CouldNotSave => "Could not save", "Kaydedilemedi"; |
| 6 | - GoBack, | 6 | + GoBack => "Go back", "Geri dön"; |
| 7 | - Issues, | 7 | + Issues => "Issues", "Sorunlar"; |
| 8 | - Labels, | 8 | + Labels => "Labels", "Etiketler"; |
| 9 | - Milestones, | 9 | + Milestones => "Milestones", "Kilometre taşları"; |
| 10 | - Pinned, | 10 | + Pinned => "Pinned", "Sabitlenmiş"; |
| 11 | - Comment, | 11 | + Comment => "Comment", "Yorum"; |
| 12 | - Edit, | 12 | + Edit => "Edit", "Düzenle"; |
| 13 | - Delete, | 13 | + Delete => "Delete", "Sil"; |
| 14 | - Title, | 14 | + Title => "Title", "Başlık"; |
| 15 | - Description, | 15 | + Description => "Description", "Açıklama"; |
| 16 | - Cancel, | 16 | + Name => "Name", "Ad"; |
| 17 | - Name, | 17 | + Color => "Color", "Renk"; |
| 18 | - Color, | 18 | + Reason => "Reason", "Neden"; |
| 19 | - Reason, | 19 | + Open => "Open", "Açık"; |
| 20 | - Open, | 20 | + Closed => "Closed", "Kapalı"; |
| 21 | - Closed, | 21 | + Search => "Search", "Ara"; |
| 22 | - Search, | 22 | + Sort => "Sort", "Sırala"; |
| 23 | - Sort, | 23 | + Unknown => "unknown", "bilinmeyen"; |
| 24 | - Unknown, | 24 | + System => "system", "sistem"; |
| 25 | - System, | 25 | + Edited => "edited", "düzenlendi"; |
| 26 | - Edited, | 26 | + EditedBy => " edited ", " "; |
| 27 | - EditedBy, | 27 | + Raw => "Raw", "Ham"; |
| 28 | - Raw, | 28 | + |
| 29 | - | 29 | + IssuePages => "Issue pages", "Sorun sayfaları"; |
| 30 | - IssuePages, | 30 | + PinIssue => "Pin issue", "Sorunu sabitle"; |
| 31 | - PinIssue, | 31 | + UnpinIssue => "Unpin issue", "Sabitlemeyi kaldır"; |
| 32 | - UnpinIssue, | 32 | + PinnedTopNote => "Pinned to the top of the issue list.", "Sorun listesinin en üstünde sabitlendi."; |
| 33 | - PinnedTopNote, | 33 | + PinnedIssues => "Pinned issues", "Sabitlenmiş sorunlar"; |
| 34 | - PinnedIssues, | 34 | + |
| 35 | - | 35 | + LockOffTopic => "off-topic", "konu dışı"; |
| 36 | - LockOffTopic, | 36 | + LockTooHeated => "too heated", "tartışma kızıştı"; |
| 37 | - LockTooHeated, | 37 | + LockResolved => "resolved", "çözüldü"; |
| 38 | - LockResolved, | 38 | + LockSpam => "spam", "spam"; |
| 39 | - LockSpam, | 39 | + OptOffTopic => "Off-topic", "Konu dışı"; |
| 40 | - OptOffTopic, | 40 | + OptTooHeated => "Too heated", "Tartışma kızıştı"; |
| 41 | - OptTooHeated, | 41 | + OptResolved => "Resolved", "Çözüldü"; |
| 42 | - OptResolved, | 42 | + OptSpam => "Spam", "Spam"; |
| 43 | - OptSpam, | 43 | + ConversationLocked => "This conversation has been locked and limited to collaborators.", "Bu tartışma kilitlendi ve yalnızca katkıda bulunanlarla sınırlandı."; |
| 44 | - ConversationLocked, | 44 | + ArchivedIssuesReadOnly => "This repository is archived, so its issues are read-only.", "Bu depo arşivlenmiş, bu yüzden sorunları salt okunurdur."; |
| 45 | - ArchivedIssuesReadOnly, | 45 | + LogIn => "Log in", "Giriş yap"; |
| 46 | - LogIn, | 46 | + ToComment => " to comment.", "."; |
| 47 | - LogInLink, | 47 | + |
| 48 | - ToComment, | 48 | + ClosedCompleted => "closed this as completed", "bunu tamamlandı olarak kapattı"; |
| 49 | - | 49 | + ClosedNotPlanned => "closed this as not planned", "bunu planlanmadı olarak kapattı"; |
| 50 | - ClosedCompleted, | 50 | + ClosedThis => "closed this", "bunu kapattı"; |
| 51 | - ClosedNotPlanned, | 51 | + ReopenedThis => "reopened this", "bunu yeniden açtı"; |
| 52 | - ClosedThis, | 52 | + ReferencedThis => "referenced this", "buna atıfta bulundu"; |
| 53 | - ReopenedThis, | 53 | + LockedConversation => "locked this conversation", "bu tartışmayı kilitledi"; |
| 54 | - ReferencedThis, | 54 | + UnlockedConversation => "unlocked this conversation", "bu tartışmanın kilidini açtı"; |
| 55 | - LockedConversation, | 55 | + PinnedThisIssue => "pinned this issue", "bu sorunu sabitledi"; |
| 56 | - UnlockedConversation, | 56 | + UnpinnedThisIssue => "unpinned this issue", "bu sorunun sabitlemesini kaldırdı"; |
| 57 | - PinnedThisIssue, | 57 | + MergedCommit => "merged commit", "commit'i birleştirdi"; |
| 58 | - UnpinnedThisIssue, | 58 | + PushedNewCommits => "pushed new commits", "yeni commit'ler gönderdi"; |
| 59 | - MergedCommit, | 59 | + DeletedHeadBranch => "deleted the head branch", "kaynak dalını sildi"; |
| 60 | - PushedNewCommits, | 60 | + InCommit => " in", "commit'inde"; |
| 61 | - DeletedHeadBranch, | 61 | + ReviewDismissedPrefix => "dismissed a review: ", "bir incelemeyi iptal etti: "; |
| 62 | - InCommit, | 62 | + |
| 63 | - ReviewDismissedPrefix, | 63 | + StateClosedNotPlanned => "Closed as not planned", "Planlanmadı olarak kapalı"; |
| 64 | - | 64 | + SaveChanges => "Save changes", "Değişiklikleri kaydet"; |
| 65 | - StateClosedNotPlanned, | 65 | + EditComment => "Edit comment", "Yorumu düzenle"; |
| 66 | - SaveChanges, | 66 | + |
| 67 | - EditComment, | 67 | + ApprovedChanges => "approved these changes", "bu değişiklikleri onayladı"; |
| 68 | - SaveComment, | 68 | + RequestedChanges => "requested changes", "değişiklik istedi"; |
| 69 | - | 69 | + Reviewed => "reviewed", "inceledi"; |
| 70 | - ApprovedChanges, | 70 | + ApprovedDismissed => "approved these changes (dismissed)", "bu değişiklikleri onayladı (iptal edildi)"; |
| 71 | - RequestedChanges, | 71 | + RequestedDismissed => "requested changes (dismissed)", "değişiklik istedi (iptal edildi)"; |
| 72 | - Reviewed, | 72 | + ReviewedDismissed => "reviewed (dismissed)", "inceledi (iptal edildi)"; |
| 73 | - ApprovedDismissed, | 73 | + DismissedPrefix => "dismissed: ", "iptal edildi: "; |
| 74 | - RequestedDismissed, | 74 | + AddReaction => "React", "Tepki ver"; |
| 75 | - ReviewedDismissed, | 75 | + NoDescription => "_No description provided._", "_Açıklama girilmedi._"; |
| 76 | - DismissedPrefix, | 76 | + |
| 77 | - AddReaction, | 77 | + NoRepoLabels => "This repository has no labels yet.", "Bu depoda henüz etiket yok."; |
| 78 | - NoDescription, | 78 | + SaveLabels => "Save labels", "Etiketleri kaydet"; |
| 79 | - | 79 | + NoneYet => "None yet.", "Henüz yok."; |
| 80 | - NoRepoLabels, | 80 | + Assignees => "Assignees", "Atananlar"; |
| 81 | - SaveLabels, | 81 | + SaveAssignees => "Save assignees", "Atananları kaydet"; |
| 82 | - NoneYet, | 82 | + AssignToMe => "Assign to me", "Bana ata"; |
| 83 | - Assignees, | 83 | + MilestoneBox => "Milestone", "Kilometre taşı"; |
| 84 | - SaveAssignees, | 84 | + NoneOption => "None", "Yok"; |
| 85 | - AssignToMe, | 85 | + SaveMilestone => "Save milestone", "Kilometre taşını kaydet"; |
| 86 | - MilestoneBox, | 86 | + ConversationBox => "Conversation", "Tartışma"; |
| 87 | - NoneOption, | 87 | + Locked => "Locked", "Kilitli"; |
| 88 | - SaveMilestone, | 88 | + UnlockConversation => "Unlock conversation", "Tartışmanın kilidini aç"; |
| 89 | - ConversationBox, | 89 | + NoReason => "No reason", "Neden yok"; |
| 90 | - Locked, | 90 | + LockConversation => "Lock conversation", "Tartışmayı kilitle"; |
| 91 | - UnlockConversation, | 91 | + LockedToCollaborators => "Locked to collaborators", "Katkıda bulunanlarla sınırlı"; |
| 92 | - NoReason, | 92 | + |
| 93 | - LockConversation, | 93 | + AddComment => "Add a comment", "Yorum ekle"; |
| 94 | - LockedToCollaborators, | 94 | + CloseCompleted => "Close as completed", "Tamamlandı olarak kapat"; |
| 95 | - | 95 | + CloseNotPlanned => "Close as not planned", "Planlanmadı olarak kapat"; |
| 96 | - AddComment, | 96 | + CommentEmpty => "Comment cannot be empty.", "Yorum boş olamaz."; |
| 97 | - CloseCompleted, | 97 | + Add => "Add", "Ekle"; |
| 98 | - CloseNotPlanned, | 98 | + Close => "Close", "Kapat"; |
| 99 | - CommentEmpty, | 99 | + Reopen => "Reopen", "Yeniden aç"; |
| 100 | - Add, | 100 | + |
| 101 | - Close, | 101 | + LabelsArchived => "This repository is archived. Labels are read-only.", "Bu depo arşivlenmiş. Etiketler salt okunur."; |
| 102 | - Reopen, | 102 | + NoLabelsYet => "No labels yet.", "Henüz etiket yok."; |
| 103 | - | 103 | + AddDefaultLabels => "Add default labels", "Varsayılan etiketleri ekle"; |
| 104 | - LabelsArchived, | 104 | + SaveLabel => "Save label", "Etiketi kaydet"; |
| 105 | - NoLabelsYet, | 105 | + NewLabel => "New label", "Yeni etiket"; |
| 106 | - AddDefaultLabels, | 106 | + CreateLabel => "Create label", "Etiketi oluştur"; |
| 107 | - SaveLabel, | 107 | + OpenLabelCount => "open", "açık"; |
| 108 | - NewLabel, | 108 | + |
| 109 | - CreateLabel, | 109 | + MilestonesArchived => "This repository is archived. Milestones are read-only.", "Bu depo arşivlenmiş. Kilometre taşları salt okunur."; |
| 110 | - OpenLabelCount, | 110 | + Overdue => "overdue", "gecikmiş"; |
| 111 | - | 111 | + MilestoneState => "Milestone state", "Kilometre taşı durumu"; |
| 112 | - MilestonesArchived, | 112 | + NoClosedMilestones => "No closed milestones.", "Kapalı kilometre taşı yok."; |
| 113 | - Overdue, | 113 | + NoOpenMilestones => "No open milestones.", "Açık kilometre taşı yok."; |
| 114 | - MilestoneState, | 114 | + NewMilestone => "New milestone", "Yeni kilometre taşı"; |
| 115 | - NoClosedMilestones, | 115 | + DueDate => "Due date", "Bitiş tarihi"; |
| 116 | - NoOpenMilestones, | 116 | + CreateMilestone => "Create milestone", "Kilometre taşı oluştur"; |
| 117 | - NewMilestone, | 117 | + EditMilestone => "Edit milestone", "Kilometre taşını düzenle"; |
| 118 | - DueDate, | 118 | + BackToMilestones => "Back to milestones", "Kilometre taşlarına dön"; |
| 119 | - CreateMilestone, | 119 | + StateLabel => "State", "Durum"; |
| 120 | - EditMilestone, | 120 | + ClosedMilestoneCount => "closed", "kapalı"; |
| 121 | - BackToMilestones, | 121 | + OpenMilestoneCount => "open", "açık"; |
| 122 | - StateLabel, | 122 | + |
| 123 | - ClosedMilestoneCount, | 123 | + OpenIssue => "Open issue", "Açık sorun"; |
| 124 | - OpenMilestoneCount, | 124 | + ClosedIssue => "Closed issue", "Kapalı sorun"; |
| 125 | - | 125 | + SortNewest => "Newest", "En yeni"; |
| 126 | - OpenIssue, | 126 | + SortOldest => "Oldest", "En eski"; |
| 127 | - ClosedIssue, | 127 | + NewIssue => "New issue", "Yeni sorun"; |
| 128 | - SortNewest, | 128 | + NoIssuesMatch => "No issues match these filters.", "Bu filtrelerle eşleşen sorun yok."; |
| 129 | - SortOldest, | 129 | + NoIssuesYet => "No issues yet. Open one to start a conversation.", "Henüz sorun yok. Konuşmayı başlatmak için bir sorun açın."; |
| 130 | - SortUpdated, | 130 | + FiltersApplied => "Filters applied · ", "Filtreler uygulandı · "; |
| 131 | - NewIssue, | 131 | + ClearFilters => "Clear filters", "Filtreleri temizle"; |
| 132 | - NoIssuesMatch, | 132 | + ChooseTemplate => "Choose a template to start from.", "Başlamak için bir şablon seçin."; |
| 133 | - NoIssuesYet, | 133 | + BlankIssue => "Open a blank issue", "Boş bir sorun aç"; |
| 134 | - SearchTitles, | 134 | + SubmitNewIssue => "Submit new issue", "Yeni sorunu gönder"; |
| 135 | - FiltersApplied, | 135 | + |
| 136 | - ClearFilters, | 136 | + HistIssueDescription => "issue description", "sorun açıklaması"; |
| 137 | - ChooseTemplate, | 137 | + HistPullDescription => "pull request description", "çekme isteği açıklaması"; |
| 138 | - BlankIssue, | 138 | + HistComment => "comment", "yorum"; |
| 139 | - SubmitNewIssue, | 139 | + HistReviewComment => "review comment", "inceleme yorumu"; |
| 140 | - Newer, | 140 | + NoEarlierVersions => "No earlier versions.", "Önceki sürüm yok."; |
| 141 | - Older, | | |
| 142 | - | | |
| 143 | - HistIssueDescription, | | |
| 144 | - HistPullDescription, | | |
| 145 | - HistComment, | | |
| 146 | - HistReviewComment, | | |
| 147 | - NoEarlierVersions, | | |
| 148 | } | 141 | } |
| 149 | | 142 | |
| 150 | pub fn edited_after(lang: Lang) -> &'static str { | 143 | pub fn edited_after(lang: Lang) -> &'static str { |
| @@ -154,296 +147,6 @@ pub fn edited_after(lang: Lang) -> &'static str { |
| 154 | } | 147 | } |
| 155 | } | 148 | } |
| 156 | | 149 | |
| 157 | -pub fn t(lang: Lang, key: K) -> &'static str { | | |
| 158 | - match (key, lang) { | | |
| 159 | - (K::CouldNotSave, Lang::En) => "Could not save", | | |
| 160 | - (K::CouldNotSave, Lang::Tr) => "Kaydedilemedi", | | |
| 161 | - (K::GoBack, Lang::En) => "Go back", | | |
| 162 | - (K::GoBack, Lang::Tr) => "Geri dön", | | |
| 163 | - (K::Issues, Lang::En) => "Issues", | | |
| 164 | - (K::Issues, Lang::Tr) => "Sorunlar", | | |
| 165 | - (K::Labels, Lang::En) => "Labels", | | |
| 166 | - (K::Labels, Lang::Tr) => "Etiketler", | | |
| 167 | - (K::Milestones, Lang::En) => "Milestones", | | |
| 168 | - (K::Milestones, Lang::Tr) => "Kilometre taşları", | | |
| 169 | - (K::Pinned, Lang::En) => "Pinned", | | |
| 170 | - (K::Pinned, Lang::Tr) => "Sabitlenmiş", | | |
| 171 | - (K::Comment, Lang::En) => "Comment", | | |
| 172 | - (K::Comment, Lang::Tr) => "Yorum", | | |
| 173 | - (K::Edit, Lang::En) => "Edit", | | |
| 174 | - (K::Edit, Lang::Tr) => "Düzenle", | | |
| 175 | - (K::Delete, Lang::En) => "Delete", | | |
| 176 | - (K::Delete, Lang::Tr) => "Sil", | | |
| 177 | - (K::Title, Lang::En) => "Title", | | |
| 178 | - (K::Title, Lang::Tr) => "Başlık", | | |
| 179 | - (K::Description, Lang::En) => "Description", | | |
| 180 | - (K::Description, Lang::Tr) => "Açıklama", | | |
| 181 | - (K::Cancel, Lang::En) => "Cancel", | | |
| 182 | - (K::Cancel, Lang::Tr) => "İptal", | | |
| 183 | - (K::Name, Lang::En) => "Name", | | |
| 184 | - (K::Name, Lang::Tr) => "Ad", | | |
| 185 | - (K::Color, Lang::En) => "Color", | | |
| 186 | - (K::Color, Lang::Tr) => "Renk", | | |
| 187 | - (K::Reason, Lang::En) => "Reason", | | |
| 188 | - (K::Reason, Lang::Tr) => "Neden", | | |
| 189 | - (K::Open, Lang::En) => "Open", | | |
| 190 | - (K::Open, Lang::Tr) => "Açık", | | |
| 191 | - (K::Closed, Lang::En) => "Closed", | | |
| 192 | - (K::Closed, Lang::Tr) => "Kapalı", | | |
| 193 | - (K::Search, Lang::En) => "Search", | | |
| 194 | - (K::Search, Lang::Tr) => "Ara", | | |
| 195 | - (K::Sort, Lang::En) => "Sort", | | |
| 196 | - (K::Sort, Lang::Tr) => "Sırala", | | |
| 197 | - (K::Unknown, Lang::En) => "unknown", | | |
| 198 | - (K::Unknown, Lang::Tr) => "bilinmeyen", | | |
| 199 | - (K::System, Lang::En) => "system", | | |
| 200 | - (K::System, Lang::Tr) => "sistem", | | |
| 201 | - (K::Edited, Lang::En) => "edited", | | |
| 202 | - (K::Edited, Lang::Tr) => "düzenlendi", | | |
| 203 | - (K::EditedBy, Lang::En) => " edited ", | | |
| 204 | - (K::EditedBy, Lang::Tr) => " ", | | |
| 205 | - (K::Raw, Lang::En) => "Raw", | | |
| 206 | - (K::Raw, Lang::Tr) => "Ham", | | |
| 207 | - | | |
| 208 | - (K::IssuePages, Lang::En) => "Issue pages", | | |
| 209 | - (K::IssuePages, Lang::Tr) => "Sorun sayfaları", | | |
| 210 | - (K::PinIssue, Lang::En) => "Pin issue", | | |
| 211 | - (K::PinIssue, Lang::Tr) => "Sorunu sabitle", | | |
| 212 | - (K::UnpinIssue, Lang::En) => "Unpin issue", | | |
| 213 | - (K::UnpinIssue, Lang::Tr) => "Sabitlemeyi kaldır", | | |
| 214 | - (K::PinnedTopNote, Lang::En) => "Pinned to the top of the issue list.", | | |
| 215 | - (K::PinnedTopNote, Lang::Tr) => "Sorun listesinin en üstünde sabitlendi.", | | |
| 216 | - (K::PinnedIssues, Lang::En) => "Pinned issues", | | |
| 217 | - (K::PinnedIssues, Lang::Tr) => "Sabitlenmiş sorunlar", | | |
| 218 | - | | |
| 219 | - (K::LockOffTopic, Lang::En) => "off-topic", | | |
| 220 | - (K::LockOffTopic, Lang::Tr) => "konu dışı", | | |
| 221 | - (K::LockTooHeated, Lang::En) => "too heated", | | |
| 222 | - (K::LockTooHeated, Lang::Tr) => "tartışma kızıştı", | | |
| 223 | - (K::LockResolved, Lang::En) => "resolved", | | |
| 224 | - (K::LockResolved, Lang::Tr) => "çözüldü", | | |
| 225 | - (K::LockSpam, Lang::En) => "spam", | | |
| 226 | - (K::LockSpam, Lang::Tr) => "spam", | | |
| 227 | - (K::OptOffTopic, Lang::En) => "Off-topic", | | |
| 228 | - (K::OptOffTopic, Lang::Tr) => "Konu dışı", | | |
| 229 | - (K::OptTooHeated, Lang::En) => "Too heated", | | |
| 230 | - (K::OptTooHeated, Lang::Tr) => "Tartışma kızıştı", | | |
| 231 | - (K::OptResolved, Lang::En) => "Resolved", | | |
| 232 | - (K::OptResolved, Lang::Tr) => "Çözüldü", | | |
| 233 | - (K::OptSpam, Lang::En) => "Spam", | | |
| 234 | - (K::OptSpam, Lang::Tr) => "Spam", | | |
| 235 | - (K::ConversationLocked, Lang::En) => { | | |
| 236 | - "This conversation has been locked and limited to collaborators." | | |
| 237 | - } | | |
| 238 | - (K::ConversationLocked, Lang::Tr) => { | | |
| 239 | - "Bu tartışma kilitlendi ve yalnızca katkıda bulunanlarla sınırlandı." | | |
| 240 | - } | | |
| 241 | - (K::ArchivedIssuesReadOnly, Lang::En) => { | | |
| 242 | - "This repository is archived, so its issues are read-only." | | |
| 243 | - } | | |
| 244 | - (K::ArchivedIssuesReadOnly, Lang::Tr) => { | | |
| 245 | - "Bu depo arşivlenmiş, bu yüzden sorunları salt okunurdur." | | |
| 246 | - } | | |
| 247 | - (K::LogIn, Lang::En) => "Log in", | | |
| 248 | - (K::LogIn, Lang::Tr) => "Giriş yap", | | |
| 249 | - (K::LogInLink, Lang::En) => "Log in", | | |
| 250 | - (K::LogInLink, Lang::Tr) => "giriş yapın", | | |
| 251 | - (K::ToComment, Lang::En) => " to comment.", | | |
| 252 | - (K::ToComment, Lang::Tr) => ".", | | |
| 253 | - | | |
| 254 | - (K::ClosedCompleted, Lang::En) => "closed this as completed", | | |
| 255 | - (K::ClosedCompleted, Lang::Tr) => "bunu tamamlandı olarak kapattı", | | |
| 256 | - (K::ClosedNotPlanned, Lang::En) => "closed this as not planned", | | |
| 257 | - (K::ClosedNotPlanned, Lang::Tr) => "bunu planlanmadı olarak kapattı", | | |
| 258 | - (K::ClosedThis, Lang::En) => "closed this", | | |
| 259 | - (K::ClosedThis, Lang::Tr) => "bunu kapattı", | | |
| 260 | - (K::ReopenedThis, Lang::En) => "reopened this", | | |
| 261 | - (K::ReopenedThis, Lang::Tr) => "bunu yeniden açtı", | | |
| 262 | - (K::ReferencedThis, Lang::En) => "referenced this", | | |
| 263 | - (K::ReferencedThis, Lang::Tr) => "buna atıfta bulundu", | | |
| 264 | - (K::LockedConversation, Lang::En) => "locked this conversation", | | |
| 265 | - (K::LockedConversation, Lang::Tr) => "bu tartışmayı kilitledi", | | |
| 266 | - (K::UnlockedConversation, Lang::En) => "unlocked this conversation", | | |
| 267 | - (K::UnlockedConversation, Lang::Tr) => "bu tartışmanın kilidini açtı", | | |
| 268 | - (K::PinnedThisIssue, Lang::En) => "pinned this issue", | | |
| 269 | - (K::PinnedThisIssue, Lang::Tr) => "bu sorunu sabitledi", | | |
| 270 | - (K::UnpinnedThisIssue, Lang::En) => "unpinned this issue", | | |
| 271 | - (K::UnpinnedThisIssue, Lang::Tr) => "bu sorunun sabitlemesini kaldırdı", | | |
| 272 | - (K::MergedCommit, Lang::En) => "merged commit", | | |
| 273 | - (K::MergedCommit, Lang::Tr) => "commit'i birleştirdi", | | |
| 274 | - (K::PushedNewCommits, Lang::En) => "pushed new commits", | | |
| 275 | - (K::PushedNewCommits, Lang::Tr) => "yeni commit'ler gönderdi", | | |
| 276 | - (K::DeletedHeadBranch, Lang::En) => "deleted the head branch", | | |
| 277 | - (K::DeletedHeadBranch, Lang::Tr) => "kaynak dalını sildi", | | |
| 278 | - (K::InCommit, Lang::En) => " in", | | |
| 279 | - (K::InCommit, Lang::Tr) => "commit'inde", | | |
| 280 | - (K::ReviewDismissedPrefix, Lang::En) => "dismissed a review: ", | | |
| 281 | - (K::ReviewDismissedPrefix, Lang::Tr) => "bir incelemeyi iptal etti: ", | | |
| 282 | - | | |
| 283 | - (K::StateClosedNotPlanned, Lang::En) => "Closed as not planned", | | |
| 284 | - (K::StateClosedNotPlanned, Lang::Tr) => "Planlanmadı olarak kapalı", | | |
| 285 | - (K::SaveChanges, Lang::En) => "Save changes", | | |
| 286 | - (K::SaveChanges, Lang::Tr) => "Değişiklikleri kaydet", | | |
| 287 | - (K::EditComment, Lang::En) => "Edit comment", | | |
| 288 | - (K::EditComment, Lang::Tr) => "Yorumu düzenle", | | |
| 289 | - (K::SaveComment, Lang::En) => "Save comment", | | |
| 290 | - (K::SaveComment, Lang::Tr) => "Yorumu kaydet", | | |
| 291 | - | | |
| 292 | - (K::ApprovedChanges, Lang::En) => "approved these changes", | | |
| 293 | - (K::ApprovedChanges, Lang::Tr) => "bu değişiklikleri onayladı", | | |
| 294 | - (K::RequestedChanges, Lang::En) => "requested changes", | | |
| 295 | - (K::RequestedChanges, Lang::Tr) => "değişiklik istedi", | | |
| 296 | - (K::Reviewed, Lang::En) => "reviewed", | | |
| 297 | - (K::Reviewed, Lang::Tr) => "inceledi", | | |
| 298 | - (K::ApprovedDismissed, Lang::En) => "approved these changes (dismissed)", | | |
| 299 | - (K::ApprovedDismissed, Lang::Tr) => "bu değişiklikleri onayladı (iptal edildi)", | | |
| 300 | - (K::RequestedDismissed, Lang::En) => "requested changes (dismissed)", | | |
| 301 | - (K::RequestedDismissed, Lang::Tr) => "değişiklik istedi (iptal edildi)", | | |
| 302 | - (K::ReviewedDismissed, Lang::En) => "reviewed (dismissed)", | | |
| 303 | - (K::ReviewedDismissed, Lang::Tr) => "inceledi (iptal edildi)", | | |
| 304 | - (K::DismissedPrefix, Lang::En) => "dismissed: ", | | |
| 305 | - (K::DismissedPrefix, Lang::Tr) => "iptal edildi: ", | | |
| 306 | - (K::AddReaction, Lang::En) => "React", | | |
| 307 | - (K::AddReaction, Lang::Tr) => "Tepki ver", | | |
| 308 | - (K::NoDescription, Lang::En) => "_No description provided._", | | |
| 309 | - (K::NoDescription, Lang::Tr) => "_Açıklama girilmedi._", | | |
| 310 | - | | |
| 311 | - (K::NoRepoLabels, Lang::En) => "This repository has no labels yet.", | | |
| 312 | - (K::NoRepoLabels, Lang::Tr) => "Bu depoda henüz etiket yok.", | | |
| 313 | - (K::SaveLabels, Lang::En) => "Save labels", | | |
| 314 | - (K::SaveLabels, Lang::Tr) => "Etiketleri kaydet", | | |
| 315 | - (K::NoneYet, Lang::En) => "None yet.", | | |
| 316 | - (K::NoneYet, Lang::Tr) => "Henüz yok.", | | |
| 317 | - (K::Assignees, Lang::En) => "Assignees", | | |
| 318 | - (K::Assignees, Lang::Tr) => "Atananlar", | | |
| 319 | - (K::SaveAssignees, Lang::En) => "Save assignees", | | |
| 320 | - (K::SaveAssignees, Lang::Tr) => "Atananları kaydet", | | |
| 321 | - (K::AssignToMe, Lang::En) => "Assign to me", | | |
| 322 | - (K::AssignToMe, Lang::Tr) => "Bana ata", | | |
| 323 | - (K::MilestoneBox, Lang::En) => "Milestone", | | |
| 324 | - (K::MilestoneBox, Lang::Tr) => "Kilometre taşı", | | |
| 325 | - (K::NoneOption, Lang::En) => "None", | | |
| 326 | - (K::NoneOption, Lang::Tr) => "Yok", | | |
| 327 | - (K::SaveMilestone, Lang::En) => "Save milestone", | | |
| 328 | - (K::SaveMilestone, Lang::Tr) => "Kilometre taşını kaydet", | | |
| 329 | - (K::ConversationBox, Lang::En) => "Conversation", | | |
| 330 | - (K::ConversationBox, Lang::Tr) => "Tartışma", | | |
| 331 | - (K::Locked, Lang::En) => "Locked", | | |
| 332 | - (K::Locked, Lang::Tr) => "Kilitli", | | |
| 333 | - (K::UnlockConversation, Lang::En) => "Unlock conversation", | | |
| 334 | - (K::UnlockConversation, Lang::Tr) => "Tartışmanın kilidini aç", | | |
| 335 | - (K::NoReason, Lang::En) => "No reason", | | |
| 336 | - (K::NoReason, Lang::Tr) => "Neden yok", | | |
| 337 | - (K::LockConversation, Lang::En) => "Lock conversation", | | |
| 338 | - (K::LockConversation, Lang::Tr) => "Tartışmayı kilitle", | | |
| 339 | - (K::LockedToCollaborators, Lang::En) => "Locked to collaborators", | | |
| 340 | - (K::LockedToCollaborators, Lang::Tr) => "Katkıda bulunanlarla sınırlı", | | |
| 341 | - | | |
| 342 | - (K::AddComment, Lang::En) => "Add a comment", | | |
| 343 | - (K::AddComment, Lang::Tr) => "Yorum ekle", | | |
| 344 | - (K::CloseCompleted, Lang::En) => "Close as completed", | | |
| 345 | - (K::CloseCompleted, Lang::Tr) => "Tamamlandı olarak kapat", | | |
| 346 | - (K::CloseNotPlanned, Lang::En) => "Close as not planned", | | |
| 347 | - (K::CloseNotPlanned, Lang::Tr) => "Planlanmadı olarak kapat", | | |
| 348 | - (K::CommentEmpty, Lang::En) => "Comment cannot be empty.", | | |
| 349 | - (K::CommentEmpty, Lang::Tr) => "Yorum boş olamaz.", | | |
| 350 | - (K::Add, Lang::En) => "Add", | | |
| 351 | - (K::Add, Lang::Tr) => "Ekle", | | |
| 352 | - (K::Close, Lang::En) => "Close", | | |
| 353 | - (K::Close, Lang::Tr) => "Kapat", | | |
| 354 | - (K::Reopen, Lang::En) => "Reopen", | | |
| 355 | - (K::Reopen, Lang::Tr) => "Yeniden aç", | | |
| 356 | - | | |
| 357 | - (K::LabelsArchived, Lang::En) => "This repository is archived. Labels are read-only.", | | |
| 358 | - (K::LabelsArchived, Lang::Tr) => "Bu depo arşivlenmiş. Etiketler salt okunur.", | | |
| 359 | - (K::NoLabelsYet, Lang::En) => "No labels yet.", | | |
| 360 | - (K::NoLabelsYet, Lang::Tr) => "Henüz etiket yok.", | | |
| 361 | - (K::AddDefaultLabels, Lang::En) => "Add default labels", | | |
| 362 | - (K::AddDefaultLabels, Lang::Tr) => "Varsayılan etiketleri ekle", | | |
| 363 | - (K::SaveLabel, Lang::En) => "Save label", | | |
| 364 | - (K::SaveLabel, Lang::Tr) => "Etiketi kaydet", | | |
| 365 | - (K::NewLabel, Lang::En) => "New label", | | |
| 366 | - (K::NewLabel, Lang::Tr) => "Yeni etiket", | | |
| 367 | - (K::CreateLabel, Lang::En) => "Create label", | | |
| 368 | - (K::CreateLabel, Lang::Tr) => "Etiketi oluştur", | | |
| 369 | - (K::OpenLabelCount, Lang::En) => "open", | | |
| 370 | - (K::OpenLabelCount, Lang::Tr) => "açık", | | |
| 371 | - | | |
| 372 | - (K::MilestonesArchived, Lang::En) => { | | |
| 373 | - "This repository is archived. Milestones are read-only." | | |
| 374 | - } | | |
| 375 | - (K::MilestonesArchived, Lang::Tr) => "Bu depo arşivlenmiş. Kilometre taşları salt okunur.", | | |
| 376 | - (K::Overdue, Lang::En) => "overdue", | | |
| 377 | - (K::Overdue, Lang::Tr) => "gecikmiş", | | |
| 378 | - (K::MilestoneState, Lang::En) => "Milestone state", | | |
| 379 | - (K::MilestoneState, Lang::Tr) => "Kilometre taşı durumu", | | |
| 380 | - (K::NoClosedMilestones, Lang::En) => "No closed milestones.", | | |
| 381 | - (K::NoClosedMilestones, Lang::Tr) => "Kapalı kilometre taşı yok.", | | |
| 382 | - (K::NoOpenMilestones, Lang::En) => "No open milestones.", | | |
| 383 | - (K::NoOpenMilestones, Lang::Tr) => "Açık kilometre taşı yok.", | | |
| 384 | - (K::NewMilestone, Lang::En) => "New milestone", | | |
| 385 | - (K::NewMilestone, Lang::Tr) => "Yeni kilometre taşı", | | |
| 386 | - (K::DueDate, Lang::En) => "Due date", | | |
| 387 | - (K::DueDate, Lang::Tr) => "Bitiş tarihi", | | |
| 388 | - (K::CreateMilestone, Lang::En) => "Create milestone", | | |
| 389 | - (K::CreateMilestone, Lang::Tr) => "Kilometre taşı oluştur", | | |
| 390 | - (K::EditMilestone, Lang::En) => "Edit milestone", | | |
| 391 | - (K::EditMilestone, Lang::Tr) => "Kilometre taşını düzenle", | | |
| 392 | - (K::BackToMilestones, Lang::En) => "Back to milestones", | | |
| 393 | - (K::BackToMilestones, Lang::Tr) => "Kilometre taşlarına dön", | | |
| 394 | - (K::StateLabel, Lang::En) => "State", | | |
| 395 | - (K::StateLabel, Lang::Tr) => "Durum", | | |
| 396 | - (K::ClosedMilestoneCount, Lang::En) => "closed", | | |
| 397 | - (K::ClosedMilestoneCount, Lang::Tr) => "kapalı", | | |
| 398 | - (K::OpenMilestoneCount, Lang::En) => "open", | | |
| 399 | - (K::OpenMilestoneCount, Lang::Tr) => "açık", | | |
| 400 | - | | |
| 401 | - (K::OpenIssue, Lang::En) => "Open issue", | | |
| 402 | - (K::OpenIssue, Lang::Tr) => "Açık sorun", | | |
| 403 | - (K::ClosedIssue, Lang::En) => "Closed issue", | | |
| 404 | - (K::ClosedIssue, Lang::Tr) => "Kapalı sorun", | | |
| 405 | - (K::SortNewest, Lang::En) => "Newest", | | |
| 406 | - (K::SortNewest, Lang::Tr) => "En yeni", | | |
| 407 | - (K::SortOldest, Lang::En) => "Oldest", | | |
| 408 | - (K::SortOldest, Lang::Tr) => "En eski", | | |
| 409 | - (K::SortUpdated, Lang::En) => "Recently updated", | | |
| 410 | - (K::SortUpdated, Lang::Tr) => "Son güncellenen", | | |
| 411 | - (K::NewIssue, Lang::En) => "New issue", | | |
| 412 | - (K::NewIssue, Lang::Tr) => "Yeni sorun", | | |
| 413 | - (K::NoIssuesMatch, Lang::En) => "No issues match these filters.", | | |
| 414 | - (K::NoIssuesMatch, Lang::Tr) => "Bu filtrelerle eşleşen sorun yok.", | | |
| 415 | - (K::NoIssuesYet, Lang::En) => "No issues yet. Open one to start a conversation.", | | |
| 416 | - (K::NoIssuesYet, Lang::Tr) => "Henüz sorun yok. Konuşmayı başlatmak için bir sorun açın.", | | |
| 417 | - (K::SearchTitles, Lang::En) => "Search titles", | | |
| 418 | - (K::SearchTitles, Lang::Tr) => "Başlıklarda ara", | | |
| 419 | - (K::FiltersApplied, Lang::En) => "Filters applied · ", | | |
| 420 | - (K::FiltersApplied, Lang::Tr) => "Filtreler uygulandı · ", | | |
| 421 | - (K::ClearFilters, Lang::En) => "Clear filters", | | |
| 422 | - (K::ClearFilters, Lang::Tr) => "Filtreleri temizle", | | |
| 423 | - (K::ChooseTemplate, Lang::En) => "Choose a template to start from.", | | |
| 424 | - (K::ChooseTemplate, Lang::Tr) => "Başlamak için bir şablon seçin.", | | |
| 425 | - (K::BlankIssue, Lang::En) => "Open a blank issue", | | |
| 426 | - (K::BlankIssue, Lang::Tr) => "Boş bir sorun aç", | | |
| 427 | - (K::SubmitNewIssue, Lang::En) => "Submit new issue", | | |
| 428 | - (K::SubmitNewIssue, Lang::Tr) => "Yeni sorunu gönder", | | |
| 429 | - (K::Newer, Lang::En) => "Newer", | | |
| 430 | - (K::Newer, Lang::Tr) => "Daha yeni", | | |
| 431 | - (K::Older, Lang::En) => "Older", | | |
| 432 | - (K::Older, Lang::Tr) => "Daha eski", | | |
| 433 | - | | |
| 434 | - (K::HistIssueDescription, Lang::En) => "issue description", | | |
| 435 | - (K::HistIssueDescription, Lang::Tr) => "sorun açıklaması", | | |
| 436 | - (K::HistPullDescription, Lang::En) => "pull request description", | | |
| 437 | - (K::HistPullDescription, Lang::Tr) => "çekme isteği açıklaması", | | |
| 438 | - (K::HistComment, Lang::En) => "comment", | | |
| 439 | - (K::HistComment, Lang::Tr) => "yorum", | | |
| 440 | - (K::HistReviewComment, Lang::En) => "review comment", | | |
| 441 | - (K::HistReviewComment, Lang::Tr) => "inceleme yorumu", | | |
| 442 | - (K::NoEarlierVersions, Lang::En) => "No earlier versions.", | | |
| 443 | - (K::NoEarlierVersions, Lang::Tr) => "Önceki sürüm yok.", | | |
| 444 | - } | | |
| 445 | -} | | |
| 446 | - | | |
| 447 | pub fn comment_count(lang: Lang, n: i64) -> String { | 150 | pub fn comment_count(lang: Lang, n: i64) -> String { |
| 448 | match lang { | 151 | match lang { |
| 449 | Lang::En => format!("{n} comment{}", if n == 1 { "" } else { "s" }), | 152 | Lang::En => format!("{n} comment{}", if n == 1 { "" } else { "s" }), |
| @@ -793,142 +496,7 @@ pub fn commit_event_sides( |
| 793 | | 496 | |
| 794 | #[cfg(test)] | 497 | #[cfg(test)] |
| 795 | mod tests { | 498 | mod tests { |
| 796 | - use super::{K, Lang, commit_event_sides, t}; | | |
| 797 | - | | |
| 798 | - const ALL: &[K] = &[ | | |
| 799 | - K::CouldNotSave, | | |
| 800 | - K::GoBack, | | |
| 801 | - K::Issues, | | |
| 802 | - K::Labels, | | |
| 803 | - K::Milestones, | | |
| 804 | - K::Pinned, | | |
| 805 | - K::Comment, | | |
| 806 | - K::Edit, | | |
| 807 | - K::Delete, | | |
| 808 | - K::Title, | | |
| 809 | - K::Description, | | |
| 810 | - K::Cancel, | | |
| 811 | - K::Name, | | |
| 812 | - K::Color, | | |
| 813 | - K::Reason, | | |
| 814 | - K::Open, | | |
| 815 | - K::Closed, | | |
| 816 | - K::Search, | | |
| 817 | - K::Sort, | | |
| 818 | - K::Unknown, | | |
| 819 | - K::System, | | |
| 820 | - K::Edited, | | |
| 821 | - K::EditedBy, | | |
| 822 | - K::Raw, | | |
| 823 | - K::IssuePages, | | |
| 824 | - K::PinIssue, | | |
| 825 | - K::UnpinIssue, | | |
| 826 | - K::PinnedTopNote, | | |
| 827 | - K::PinnedIssues, | | |
| 828 | - K::LockOffTopic, | | |
| 829 | - K::LockTooHeated, | | |
| 830 | - K::LockResolved, | | |
| 831 | - K::LockSpam, | | |
| 832 | - K::OptOffTopic, | | |
| 833 | - K::OptTooHeated, | | |
| 834 | - K::OptResolved, | | |
| 835 | - K::OptSpam, | | |
| 836 | - K::ConversationLocked, | | |
| 837 | - K::ArchivedIssuesReadOnly, | | |
| 838 | - K::LogIn, | | |
| 839 | - K::LogInLink, | | |
| 840 | - K::ToComment, | | |
| 841 | - K::ClosedCompleted, | | |
| 842 | - K::ClosedNotPlanned, | | |
| 843 | - K::ClosedThis, | | |
| 844 | - K::ReopenedThis, | | |
| 845 | - K::ReferencedThis, | | |
| 846 | - K::LockedConversation, | | |
| 847 | - K::UnlockedConversation, | | |
| 848 | - K::PinnedThisIssue, | | |
| 849 | - K::UnpinnedThisIssue, | | |
| 850 | - K::MergedCommit, | | |
| 851 | - K::PushedNewCommits, | | |
| 852 | - K::DeletedHeadBranch, | | |
| 853 | - K::InCommit, | | |
| 854 | - K::ReviewDismissedPrefix, | | |
| 855 | - K::StateClosedNotPlanned, | | |
| 856 | - K::SaveChanges, | | |
| 857 | - K::EditComment, | | |
| 858 | - K::SaveComment, | | |
| 859 | - K::ApprovedChanges, | | |
| 860 | - K::RequestedChanges, | | |
| 861 | - K::Reviewed, | | |
| 862 | - K::ApprovedDismissed, | | |
| 863 | - K::RequestedDismissed, | | |
| 864 | - K::ReviewedDismissed, | | |
| 865 | - K::DismissedPrefix, | | |
| 866 | - K::AddReaction, | | |
| 867 | - K::NoDescription, | | |
| 868 | - K::NoRepoLabels, | | |
| 869 | - K::SaveLabels, | | |
| 870 | - K::NoneYet, | | |
| 871 | - K::Assignees, | | |
| 872 | - K::SaveAssignees, | | |
| 873 | - K::AssignToMe, | | |
| 874 | - K::MilestoneBox, | | |
| 875 | - K::NoneOption, | | |
| 876 | - K::SaveMilestone, | | |
| 877 | - K::ConversationBox, | | |
| 878 | - K::Locked, | | |
| 879 | - K::UnlockConversation, | | |
| 880 | - K::NoReason, | | |
| 881 | - K::LockConversation, | | |
| 882 | - K::LockedToCollaborators, | | |
| 883 | - K::AddComment, | | |
| 884 | - K::CloseCompleted, | | |
| 885 | - K::CloseNotPlanned, | | |
| 886 | - K::Add, | | |
| 887 | - K::Close, | | |
| 888 | - K::Reopen, | | |
| 889 | - K::CommentEmpty, | | |
| 890 | - K::LabelsArchived, | | |
| 891 | - K::NoLabelsYet, | | |
| 892 | - K::AddDefaultLabels, | | |
| 893 | - K::SaveLabel, | | |
| 894 | - K::NewLabel, | | |
| 895 | - K::CreateLabel, | | |
| 896 | - K::OpenLabelCount, | | |
| 897 | - K::MilestonesArchived, | | |
| 898 | - K::Overdue, | | |
| 899 | - K::MilestoneState, | | |
| 900 | - K::NoClosedMilestones, | | |
| 901 | - K::NoOpenMilestones, | | |
| 902 | - K::NewMilestone, | | |
| 903 | - K::DueDate, | | |
| 904 | - K::CreateMilestone, | | |
| 905 | - K::EditMilestone, | | |
| 906 | - K::BackToMilestones, | | |
| 907 | - K::StateLabel, | | |
| 908 | - K::ClosedMilestoneCount, | | |
| 909 | - K::OpenMilestoneCount, | | |