forge
Explore
Log in

Don't you dare go Hollow

Leftover cross-crate simplification (signed-token helper, NewPull, settings table, row helpers, strings! i18n macro, csrf form, RepoCtx helpers, shared page and e2e helpers, ci config split, one time helper set)

Browse files at this commit

c3c44bbf95fe87870dd035a3af3e213d7948ae0cAhmet Kaan GümüşParent: 7e521ed
Some checks failed
Show checks
  • ✗ci/buildjob was cancelledDetails
  • refactor
    • leftover cross-crate simplification (signed-token helper, NewPull, settings table, row helpers, strings! i18n macro, csrf form, RepoCtx helpers, shared page and e2e helpers, ci config split, one time helper set)
    • fixes: runner reported labels survive override clears, milestone titles repaired from the swapped update bug, runner helper lines can no longer be spoofed by job output, rootfs GC no longer touches other id ranges, restart only labels jobs it cancelled, artifact quota re-checked in the store write, LFS gc and upload share a lock, OCI orphan blobs swept, mirror worker no longer spins on syncing mirrors, merge queue fails missing checks after the job timeout and resumes after restart, post_update walks every pushed commit, close-with-comment is one transaction, pull create is retry-safe
Show full message
♻️ refactor: leftover cross-crate simplification (signed-token helper, NewPull, settings table, row helpers, strings! i18n macro, csrf form, RepoCtx helpers, shared page and e2e helpers, ci config split, one time helper set); fixes: runner reported labels survive override clears, milestone titles repaired from the swapped update bug, runner helper lines can no longer be spoofed by job output, rootfs GC no longer touches other id ranges, restart only labels jobs it cancelled, artifact quota re-checked in the store write, LFS gc and upload share a lock, OCI orphan blobs swept, mirror worker no longer spins on syncing mirrors, merge queue fails missing checks after the job timeout and resumes after restart, post_update walks every pushed commit, close-with-comment is one transaction, pull create is retry-safe

269 changed files +7316 -14474

Cargo.lockmodified+1 -0
@@ -2070,6 +2070,7 @@ dependencies = [
20702070 "nix 0.31.4",
20712071 "oci-client",
20722072 "oci-spec",
2073+ "rand 0.10.4",
20732074 "reqwest",
20742075 "seccompiler",
20752076 "serde",
crates/forge-ci/build_identity.rsmodified+0 -3
@@ -14,7 +14,6 @@ pub fn emit_identity() {
1414 if env::var("PROFILE").as_deref() != Ok("release") {
1515 println!("cargo:rustc-env=FORGE_GIT_SHA=unknown");
1616 println!("cargo:rustc-env=FORGE_GIT_DATE=unknown");
17- println!("cargo:rustc-env=FORGE_GIT_DIRTY=0");
1817 return;
1918 }
2019
@@ -39,8 +38,6 @@ pub fn emit_identity() {
3938 let date = git(&["show", "-s", "--format=%cs", "HEAD"])
4039 .or_else(|| env::var("FORGE_BUILD_DATE").ok().filter(|s| !s.is_empty()))
4140 .unwrap_or_else(|| "unknown".into());
42- let dirty = git(&["status", "--porcelain", "--untracked-files=no"]).is_some();
4341 println!("cargo:rustc-env=FORGE_GIT_SHA={sha}");
4442 println!("cargo:rustc-env=FORGE_GIT_DATE={date}");
45- println!("cargo:rustc-env=FORGE_GIT_DIRTY={}", u8::from(dirty));
4643 }
crates/forge-ci/src/build.rsmodified+9 -22
@@ -5,17 +5,12 @@ pub const VERSION: &str = env!("CARGO_PKG_VERSION");
55 struct Identity {
66 commit: &'static str,
77 date: &'static str,
8- dirty: bool,
98 }
109
1110 static IDENTITY: OnceLock<Identity> = OnceLock::new();
1211
13-pub fn set_identity(commit: &'static str, date: &'static str, dirty: bool) {
14- let _ = IDENTITY.set(Identity {
15- commit,
16- date,
17- dirty,
18- });
12+pub fn set_identity(commit: &'static str, date: &'static str) {
13+ let _ = IDENTITY.set(Identity { commit, date });
1914 }
2015
2116 pub fn commit() -> &'static str {
@@ -26,23 +21,17 @@ pub fn date() -> &'static str {
2621 IDENTITY.get().map_or("unknown", |i| i.date)
2722 }
2823
29-pub fn dirty() -> bool {
30- IDENTITY.get().is_some_and(|i| i.dirty)
31-}
32-
3324 pub fn display() -> String {
34- format_build(VERSION, commit(), date(), dirty())
25+ format_build(VERSION, commit(), date())
3526 }
3627
37-pub fn format_build(version: &str, commit: &str, date: &str, dirty: bool) -> String {
38- let dirty = if dirty { "-dirty" } else { "" };
39- format!("{version} ({commit}{dirty}, {date})")
28+pub fn format_build(version: &str, commit: &str, date: &str) -> String {
29+ format!("{version} ({commit}, {date})")
4030 }
4131
4232 pub fn commit_of(build: &str) -> Option<&str> {
4333 let inner = build.split_once('(')?.1;
4434 let commit = inner.split([',', ')']).next()?.trim();
45- let commit = commit.strip_suffix("-dirty").unwrap_or(commit);
4635 (!commit.is_empty() && commit != "unknown").then_some(commit)
4736 }
4837
@@ -67,15 +56,13 @@ mod tests {
6756
6857 #[test]
6958 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");
7160 assert_eq!(server, "0.1.0 (cf8e648, 2026-10-20)");
72- let same = format_build("0.1.0", "cf8e648", "2026-10-20", true);
73- assert_eq!(compare(Some(&same), &server), Freshness::UpToDate);
74- let older = format_build("0.1.0", "4d21658", "2026-10-19", false);
61+ let older = format_build("0.1.0", "4d21658", "2026-10-19");
7562 assert_eq!(compare(Some(&older), &server), Freshness::Outdated);
7663 assert_eq!(compare(None, &server), Freshness::Unknown);
7764 assert_eq!(compare(Some("0.1.0"), &server), Freshness::Unknown);
78- let unknown = format_build("0.1.0", "unknown", "unknown", false);
79- assert_eq!(compare(Some(&same), &unknown), Freshness::Unknown);
65+ let unknown = format_build("0.1.0", "unknown", "unknown");
66+ assert_eq!(compare(Some(&server), &unknown), Freshness::Unknown);
8067 }
8168 }
crates/forge-ci/src/config.rsmodified+27 -1318
@@ -1,22 +1,34 @@
11 use std::collections::{BTreeMap, BTreeSet};
22
3-use globset::{Glob, GlobBuilder};
43 use serde::{Deserialize, Serialize};
54
65 use crate::error::ConfigError;
76
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;
930 const MAX_JOBS: usize = 20;
10-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;
31+pub const DEFAULT_TIMEOUT_MINUTES: u32 = 60;
2032
2133 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2234 pub struct CiConfig {
@@ -32,192 +44,6 @@ pub struct CiConfig {
3244 pub warnings: Vec<String>,
3345 }
3446
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-
22147 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
22248 pub enum Event<'a> {
22349 Push { branch: &'a str },
@@ -360,18 +186,7 @@ impl CiConfig {
360186 for pattern in &self.on.tags {
361187 validate_trigger_glob("tag", pattern)?;
362188 }
363- if self.on.schedule.len() > MAX_SCHEDULES {
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- }
189+ validate_schedules(&self.on.schedule)?;
375190 for (name, job) in &self.jobs {
376191 validate_job(name, job, &self.jobs)?;
377192 }
@@ -392,251 +207,6 @@ impl CiConfig {
392207 }
393208 }
394209
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-
640210 fn names_job(selected: &str, job: &str) -> bool {
641211 selected == job
642212 || job
@@ -644,245 +214,6 @@ fn names_job(selected: &str, job: &str) -> bool {
644214 .is_some_and(|rest| rest.starts_with(" ("))
645215 }
646216
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-
886217 #[cfg(test)]
887218 mod tests {
888219 use super::*;
@@ -907,11 +238,11 @@ cargo fmt --check
907238 artifacts = ["target/release/forge"]
908239 "#;
909240
910- fn job_toml(body: &str) -> String {
241+ pub(super) fn job_toml(body: &str) -> String {
911242 format!("[jobs.build]\nimage = \"docker.io/rust:1\"\nrun = \"cargo build\"\n{body}\n")
912243 }
913244
914- fn err_of(text: &str) -> ConfigError {
245+ pub(super) fn err_of(text: &str) -> ConfigError {
915246 match parse_config(text) {
916247 Ok(_) => panic!("expected an error for:\n{text}"),
917248 Err(e) => e,
@@ -953,13 +284,6 @@ artifacts = ["target/release/forge"]
953284 !parse_config(&job_toml("network = false")).unwrap().jobs["build"].network,
954285 "network = false is honoured"
955286 );
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());
963287 }
964288
965289 #[test]
@@ -1022,47 +346,6 @@ artifacts = ["target/release/forge"]
1022346 ));
1023347 }
1024348
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-
1066349 #[test]
1067350 fn no_jobs_is_an_error() {
1068351 assert_eq!(err_of("[on]\nmanual = true\n"), ConfigError::NoJobs);
@@ -1154,201 +437,6 @@ artifacts = ["target/release/forge"]
1154437 );
1155438 }
1156439
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-
1352440 #[test]
1353441 fn job_order_is_topological_and_stable() {
1354442 let text = "[jobs.lint]\nimage = \"i\"\nrun = \"r\"\nneeds = [\"test\"]\n\
@@ -1369,383 +457,4 @@ artifacts = ["target/release/forge"]
1369457 let cfg = parse_config(EXAMPLE).unwrap();
1370458 assert_eq!(cfg.job_order(), vec!["test", "lint"]);
1371459 }
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- }
1751460 }
crates/forge-ci/src/config/artifact.rsadded+43 -0
@@ -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+}
crates/forge-ci/src/config/cache.rsadded+147 -0
@@ -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+}
crates/forge-ci/src/config/job.rsadded+228 -0
@@ -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+}
crates/forge-ci/src/config/matrix.rsadded+355 -0
@@ -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+}
crates/forge-ci/src/config/memory.rsadded+69 -0
@@ -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+}
crates/forge-ci/src/config/release.rsadded+369 -0
@@ -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+}
crates/forge-ci/src/config/schedule.rsadded+55 -0
@@ -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+}
crates/forge-ci/src/config/trigger.rsadded+97 -0
@@ -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+}
crates/forge-ci/src/config/workflow.rsadded+72 -0
@@ -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+}
crates/forge-core/migrations/0075_runner_registered_labels.sqladded+2 -0
@@ -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);
crates/forge-core/migrations/0076_milestone_title_repair.sqladded+1 -0
@@ -0,0 +1 @@
1+UPDATE milestones SET title = title WHERE 0;
crates/forge-core/src/alerts.rsmodified+56 -0
@@ -8,6 +8,62 @@ pub enum AlertKind {
88 Replication,
99 }
1010
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+
1167 pub fn is_kill_signature(exit_code: Option<i64>, message: Option<&str>) -> bool {
1268 if matches!(exit_code, Some(137) | Some(-9)) {
1369 return true;
crates/forge-core/src/audit.rsmodified+4 -17
@@ -11,13 +11,9 @@ macro_rules! audit_actions {
1111
1212 impl AuditAction {
1313 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- }
2014 }
15+
16+ string_enum!(AuditAction { $($variant = $name),* });
2117 };
2218 }
2319
@@ -130,15 +126,6 @@ audit_actions! {
130126 PasskeyLogin => "passkey_login",
131127 }
132128
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-
142129 #[derive(Debug, Clone, PartialEq, Eq)]
143130 pub struct AuditEntry {
144131 pub id: String,
@@ -218,12 +205,12 @@ mod tests {
218205 fn names_are_unique_and_round_trip() {
219206 let mut names: Vec<&str> = AuditAction::ALL.iter().map(|a| a.as_str()).collect();
220207 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));
222209 }
223210 names.sort();
224211 names.dedup();
225212 assert_eq!(names.len(), AuditAction::ALL.len());
226- assert_eq!(AuditAction::parse("nope"), None);
213+ assert!("nope".parse::<AuditAction>().is_err());
227214 }
228215
229216 #[test]
crates/forge-core/src/ci.rsmodified+21 -63
@@ -1,12 +1,9 @@
11 use std::collections::BTreeMap;
2-use std::str::FromStr;
32
43 use forge_ci::proto::{MAX_CONCURRENCY, MIN_CONCURRENCY};
54
65 pub use forge_ci::proto::RestartMode;
76
8-use crate::error::{Error, Result};
9-
107 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
118 pub enum RunState {
129 WaitingApproval,
@@ -18,19 +15,17 @@ pub enum RunState {
1815 Error,
1916 }
2017
21-impl RunState {
22- pub fn as_str(self) -> &'static str {
23- match self {
24- RunState::WaitingApproval => "waiting_approval",
25- RunState::Queued => "queued",
26- RunState::Running => "running",
27- RunState::Success => "success",
28- RunState::Failure => "failure",
29- RunState::Cancelled => "cancelled",
30- RunState::Error => "error",
31- }
32- }
18+string_enum!(RunState {
19+ WaitingApproval = "waiting_approval",
20+ Queued = "queued",
21+ Running = "running",
22+ Success = "success",
23+ Failure = "failure",
24+ Cancelled = "cancelled",
25+ Error = "error",
26+});
3327
28+impl RunState {
3429 pub fn is_terminal(self) -> bool {
3530 matches!(
3631 self,
@@ -39,23 +34,6 @@ impl RunState {
3934 }
4035 }
4136
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-
5937 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
6038 pub enum JobState {
6139 Blocked,
@@ -68,20 +46,18 @@ pub enum JobState {
6846 Skipped,
6947 }
7048
71-impl JobState {
72- pub fn as_str(self) -> &'static str {
73- match self {
74- JobState::Blocked => "blocked",
75- JobState::Queued => "queued",
76- JobState::Running => "running",
77- JobState::Success => "success",
78- JobState::Failure => "failure",
79- JobState::Cancelled => "cancelled",
80- JobState::Error => "error",
81- JobState::Skipped => "skipped",
82- }
83- }
49+string_enum!(JobState {
50+ Blocked = "blocked",
51+ Queued = "queued",
52+ Running = "running",
53+ Success = "success",
54+ Failure = "failure",
55+ Cancelled = "cancelled",
56+ Error = "error",
57+ Skipped = "skipped",
58+});
8459
60+impl JobState {
8561 pub fn is_terminal(self) -> bool {
8662 matches!(
8763 self,
@@ -94,24 +70,6 @@ impl JobState {
9470 }
9571 }
9672
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-
11573 #[derive(Debug, Clone, PartialEq, Eq)]
11674 pub struct CiRunner {
11775 pub id: String,
crates/forge-core/src/config.rsmodified+77 -19
@@ -6,14 +6,21 @@ use serde::{Deserialize, Deserializer};
66
77 use crate::error::{Error, Result};
88
9-#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
9+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
1010 #[serde(rename_all = "lowercase")]
1111 pub enum Registration {
12+ #[default]
1213 Closed,
1314 Invite,
1415 Open,
1516 }
1617
18+string_enum!(Registration {
19+ Closed = "closed",
20+ Invite = "invite",
21+ Open = "open",
22+});
23+
1724 fn deserialize_trusted_proxies<'de, D: Deserializer<'de>>(
1825 deserializer: D,
1926 ) -> std::result::Result<Vec<IpNet>, D::Error> {
@@ -166,7 +173,7 @@ impl AlertsConfig {
166173 #[serde(deny_unknown_fields, default)]
167174 pub struct BannerConfig {
168175 pub message: String,
169- pub level: String,
176+ pub level: BannerLevel,
170177 pub expires: String,
171178 }
172179
@@ -174,12 +181,25 @@ impl Default for BannerConfig {
174181 fn default() -> Self {
175182 BannerConfig {
176183 message: String::new(),
177- level: "info".into(),
184+ level: BannerLevel::Info,
178185 expires: String::new(),
179186 }
180187 }
181188 }
182189
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+
183203 impl BannerConfig {
184204 pub fn expires_unix(&self) -> Option<i64> {
185205 parse_banner_expiry(&self.expires)
@@ -261,6 +281,11 @@ pub enum OrgCreation {
261281 Admin,
262282 }
263283
284+string_enum!(OrgCreation {
285+ All = "all",
286+ Admin = "admin",
287+});
288+
264289 #[derive(Debug, Clone, Default, Deserialize)]
265290 #[serde(deny_unknown_fields, default)]
266291 pub struct MailConfig {
@@ -275,6 +300,11 @@ pub enum MailTransport {
275300 Log,
276301 }
277302
303+string_enum!(MailTransport {
304+ Smtp = "smtp",
305+ Log = "log",
306+});
307+
278308 #[derive(Debug, Clone, Deserialize)]
279309 #[serde(deny_unknown_fields, default)]
280310 pub struct CiConfig {
@@ -450,6 +480,12 @@ pub enum StorageBackend {
450480 R2,
451481 }
452482
483+string_enum!(StorageBackend {
484+ Fs = "fs",
485+ S3 = "s3",
486+ R2 = "r2",
487+});
488+
453489 #[derive(Debug, Clone, Default, Deserialize)]
454490 #[serde(deny_unknown_fields, default)]
455491 pub struct S3Config {
@@ -468,19 +504,38 @@ pub struct S3Config {
468504 pub struct R2Config {
469505 pub account_id: String,
470506 pub bucket: String,
471- pub jurisdiction: String,
507+ pub jurisdiction: R2Jurisdiction,
472508 pub prefix: String,
473509 pub access_key_id: String,
474510 pub secret_access_key_file: PathBuf,
475511 }
476512
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+
477529 impl R2Config {
478530 pub fn endpoint(&self) -> String {
479- match self.jurisdiction.as_str() {
480- "" => format!("https://{}.r2.cloudflarestorage.com", self.account_id),
531+ match self.jurisdiction {
532+ R2Jurisdiction::Global => {
533+ format!("https://{}.r2.cloudflarestorage.com", self.account_id)
534+ }
481535 jurisdiction => format!(
482- "https://{}.{jurisdiction}.r2.cloudflarestorage.com",
483- self.account_id
536+ "https://{}.{}.r2.cloudflarestorage.com",
537+ self.account_id,
538+ jurisdiction.as_str()
484539 ),
485540 }
486541 }
@@ -553,12 +608,6 @@ impl StorageConfig {
553608 require("storage.r2", "bucket", &r2.bucket)?;
554609 require("storage.r2", "access_key_id", &r2.access_key_id)?;
555610 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- }
562611 Ok(())
563612 }
564613 }
@@ -1023,17 +1072,26 @@ mod tests {
10231072 #[test]
10241073 fn r2_endpoint_follows_jurisdiction() {
10251074 let cases = [
1026- ("", "https://acct.r2.cloudflarestorage.com"),
1027- ("eu", "https://acct.eu.r2.cloudflarestorage.com"),
1028- ("fedramp", "https://acct.fedramp.r2.cloudflarestorage.com"),
1075+ (
1076+ R2Jurisdiction::Global,
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+ ),
10291087 ];
10301088 for (jurisdiction, expected) in cases {
10311089 let cfg = R2Config {
10321090 account_id: "acct".into(),
1033- jurisdiction: jurisdiction.into(),
1091+ jurisdiction,
10341092 ..R2Config::default()
10351093 };
1036- assert_eq!(cfg.endpoint(), expected, "jurisdiction `{jurisdiction}`");
1094+ assert_eq!(cfg.endpoint(), expected, "jurisdiction {jurisdiction:?}");
10371095 }
10381096 }
10391097
crates/forge-core/src/discussions.rsmodified+11 -32
@@ -15,16 +15,14 @@ pub const DISCUSSION_CATEGORIES: &[DiscussionCategory] = &[
1515 DiscussionCategory::Announcements,
1616 ];
1717
18-impl DiscussionCategory {
19- pub fn as_str(self) -> &'static str {
20- match self {
21- DiscussionCategory::General => "general",
22- DiscussionCategory::Ideas => "ideas",
23- DiscussionCategory::Qa => "qa",
24- DiscussionCategory::Announcements => "announcements",
25- }
26- }
18+string_enum!(DiscussionCategory {
19+ General = "general",
20+ Ideas = "ideas",
21+ Qa = "qa",
22+ Announcements = "announcements",
23+});
2724
25+impl DiscussionCategory {
2826 pub fn label(self) -> &'static str {
2927 match self {
3028 DiscussionCategory::General => "General",
@@ -33,13 +31,6 @@ impl DiscussionCategory {
3331 DiscussionCategory::Announcements => "Announcements",
3432 }
3533 }
36-
37- pub fn parse(name: &str) -> Option<DiscussionCategory> {
38- DISCUSSION_CATEGORIES
39- .iter()
40- .copied()
41- .find(|c| c.as_str() == name)
42- }
4334 }
4435
4536 #[derive(Debug, Clone, PartialEq, Eq)]
@@ -70,22 +61,10 @@ pub enum DiscussionReason {
7061 Reply,
7162 }
7263
73-impl DiscussionReason {
74- pub fn as_str(self) -> &'static str {
75- match self {
76- DiscussionReason::Mention => "mention",
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-}
64+string_enum!(DiscussionReason {
65+ Mention = "mention",
66+ Reply = "reply",
67+});
8968
9069 #[derive(Debug, Clone, PartialEq, Eq)]
9170 pub struct DiscussionNotification {
crates/forge-core/src/issues.rsmodified+13 -62
@@ -13,26 +13,10 @@ pub enum IssueState {
1313 Closed,
1414 }
1515
16-impl IssueState {
17- pub fn as_str(&self) -> &'static str {
18- match self {
19- IssueState::Open => "open",
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-}
16+string_enum!(IssueState {
17+ Open = "open",
18+ Closed = "closed",
19+});
3620
3721 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
3822 pub enum StateReason {
@@ -40,26 +24,10 @@ pub enum StateReason {
4024 NotPlanned,
4125 }
4226
43-impl StateReason {
44- pub fn as_str(&self) -> &'static str {
45- match self {
46- StateReason::Completed => "completed",
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-}
27+string_enum!(StateReason {
28+ Completed = "completed",
29+ NotPlanned = "not_planned",
30+});
6331
6432 #[derive(Debug, Clone, PartialEq)]
6533 pub struct Issue {
@@ -167,28 +135,11 @@ pub enum IssueSort {
167135 RecentlyUpdated,
168136 }
169137
170-impl IssueSort {
171- pub fn as_str(&self) -> &'static str {
172- match self {
173- IssueSort::Newest => "newest",
174- IssueSort::Oldest => "oldest",
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-}
138+string_enum!(IssueSort {
139+ Newest = "newest",
140+ Oldest = "oldest",
141+ RecentlyUpdated = "updated",
142+});
192143
193144 #[derive(Debug, Clone, PartialEq)]
194145 pub struct IssueListItem {
crates/forge-core/src/lfs_token.rsmodified+23 -52
@@ -1,11 +1,5 @@
1+use crate::signed_token;
12 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;
93
104 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
115 pub enum LfsOp {
@@ -14,43 +8,28 @@ pub enum LfsOp {
148 Any,
159 }
1610
17-impl LfsOp {
18- pub fn as_str(self) -> &'static str {
19- match self {
20- LfsOp::Download => "download",
21- LfsOp::Upload => "upload",
22- LfsOp::Any => "any",
23- }
24- }
25-
26- fn parse(s: &str) -> Option<LfsOp> {
27- match s {
28- "download" => Some(LfsOp::Download),
29- "upload" => Some(LfsOp::Upload),
30- "any" => Some(LfsOp::Any),
31- _ => None,
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
11+string_enum!(LfsOp {
12+ Download = "download",
13+ Upload = "upload",
14+ Any = "any",
15+});
16+
17+fn framing<'a>(repo_id: &'a str, op: &'a str, expires: &'a str) -> [&'a [u8]; 6] {
18+ [
19+ b"lfs\0",
20+ repo_id.as_bytes(),
21+ b"\0",
22+ op.as_bytes(),
23+ b"\0",
24+ expires.as_bytes(),
25+ ]
4626 }
4727
4828 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)
50- .finalize()
51- .into_bytes();
29+ let expires = expires_unix.to_string();
30+ let tag = signed_token::mac(key, &framing(repo_id, op.as_str(), &expires));
5231 format!(
53- "{expires_unix}.{}.{}",
32+ "{expires}.{}.{}",
5433 op.as_str(),
5534 BASE64_URL_SAFE_NO_PAD.encode(tag)
5635 )
@@ -63,16 +42,13 @@ pub fn verify(key: &[u8; 32], token: &str, repo_id: &str, wanted: LfsOp, now_uni
6342 else {
6443 return false;
6544 };
66- let Ok(expires) = expires_str.parse::<i64>() else {
45+ let Some(expires) = signed_token::parse_expiry(expires_str) else {
6746 return false;
6847 };
69- if expires.to_string() != expires_str {
70- return false;
71- }
7248 if now_unix >= expires {
7349 return false;
7450 }
75- let Some(token_op) = LfsOp::parse(op_str) else {
51+ let Ok(token_op) = op_str.parse::<LfsOp>() else {
7652 return false;
7753 };
7854 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
8258 let Ok(tag) = BASE64_URL_SAFE_NO_PAD.decode(mac_str) else {
8359 return false;
8460 };
85- if tag.len() != MAC_LEN {
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))
61+ signed_token::verify(key, &framing(repo_id, op_str, expires_str), &tag)
9262 }
9363
9464 #[cfg(test)]
9565 mod tests {
9666 use super::*;
67+ use crate::signed_token::MAC_LEN;
9768
9869 const KEY: [u8; 32] = [7; 32];
9970 const OTHER_KEY: [u8; 32] = [9; 32];
crates/forge-core/src/lib.rsmodified+27 -0
@@ -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+
127 pub mod advisories;
228 pub mod alerts;
329 pub mod audit;
@@ -28,6 +54,7 @@ pub mod releases;
2854 pub mod reviews;
2955 pub mod secret;
3056 pub mod server_settings;
57+pub mod signed_token;
3158 pub mod store;
3259 pub mod suggestions;
3360 pub mod time;
crates/forge-core/src/mail.rsmodified+29 -54
@@ -25,24 +25,11 @@ pub enum Security {
2525 Plain,
2626 }
2727
28-impl Security {
29- pub fn as_str(self) -> &'static str {
30- match self {
31- Security::StartTls => "starttls",
32- Security::Tls => "tls",
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-}
28+string_enum!(Security {
29+ StartTls = "starttls",
30+ Tls = "tls",
31+ Plain = "none",
32+});
4633
4734 #[derive(Debug, Clone, PartialEq, Eq)]
4835 pub struct MailSettings {
@@ -121,23 +108,17 @@ impl MailKind {
121108 MailKind::Test,
122109 MailKind::Other,
123110 ];
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- }
139111 }
140112
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+
141122 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
142123 pub enum MailState {
143124 Queued,
@@ -157,23 +138,17 @@ impl MailState {
157138 MailState::Failed,
158139 MailState::Discarded,
159140 ];
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- }
175141 }
176142
143+string_enum!(MailState {
144+ Queued = "queued",
145+ Retrying = "retrying",
146+ Sending = "sending",
147+ Sent = "sent",
148+ Failed = "failed",
149+ Discarded = "discarded",
150+});
151+
177152 #[derive(Clone, PartialEq, Eq)]
178153 pub struct OutgoingMail {
179154 pub to: String,
@@ -415,17 +390,17 @@ mod tests {
415390 #[test]
416391 fn enum_names_round_trip_and_unknown_names_are_refused() {
417392 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));
419394 }
420- assert_eq!(Security::parse("ssl"), None);
395+ assert!("ssl".parse::<Security>().is_err());
421396 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));
423398 }
424- assert_eq!(MailKind::parse("spam"), None);
399+ assert!("spam".parse::<MailKind>().is_err());
425400 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));
427402 }
428- assert_eq!(MailState::parse("gave up"), None);
403+ assert!("gave up".parse::<MailState>().is_err());
429404 }
430405
431406 #[test]
crates/forge-core/src/merge_queue.rsmodified+7 -31
@@ -1,4 +1,3 @@
1-use crate::error::{Error, Result};
21 use crate::pulls::MergeStyle;
32
43 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -10,36 +9,13 @@ pub enum QueueState {
109 Removed,
1110 }
1211
13-impl QueueState {
14- pub fn as_str(self) -> &'static str {
15- match self {
16- QueueState::Queued => "queued",
17- QueueState::Testing => "testing",
18- QueueState::Merging => "merging",
19- QueueState::Failed => "failed",
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-}
12+string_enum!(QueueState {
13+ Queued = "queued",
14+ Testing = "testing",
15+ Merging = "merging",
16+ Failed = "failed",
17+ Removed = "removed",
18+});
4319
4420 #[derive(Debug, Clone, PartialEq, Eq)]
4521 pub struct QueueEntry {
crates/forge-core/src/mirrors.rsmodified+4 -22
@@ -6,28 +6,10 @@ pub enum MirrorDirection {
66 Push,
77 }
88
9-impl MirrorDirection {
10- pub fn as_str(self) -> &'static str {
11- match self {
12- MirrorDirection::Pull => "pull",
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-}
9+string_enum!(MirrorDirection {
10+ Pull = "pull",
11+ Push = "push",
12+});
3113
3214 #[derive(Debug, Clone, PartialEq, Eq)]
3315 pub struct Mirror {
crates/forge-core/src/model.rsmodified+12 -49
@@ -147,55 +147,18 @@ impl std::fmt::Debug for Session {
147147 }
148148 }
149149
150-impl Visibility {
151- pub fn as_str(&self) -> &'static str {
152- match self {
153- Visibility::Public => "public",
154- Visibility::Private => "private",
155- }
156- }
157-}
158-
159-impl std::str::FromStr for Visibility {
160- type Err = crate::error::Error;
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-}
150+string_enum!(Visibility {
151+ Public = "public",
152+ Private = "private",
153+});
154+
155+string_enum!(Role {
156+ Read = "read",
157+ Triage = "triage",
158+ Write = "write",
159+ Maintain = "maintain",
160+ Admin = "admin",
161+});
199162
200163 #[cfg(test)]
201164 mod tests {
crates/forge-core/src/notifications.rsmodified+20 -61
@@ -8,24 +8,11 @@ pub enum WatchLevel {
88 Ignoring,
99 }
1010
11-impl WatchLevel {
12- pub fn as_str(self) -> &'static str {
13- match self {
14- WatchLevel::Watching => "watching",
15- WatchLevel::Participating => "participating",
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-}
11+string_enum!(WatchLevel {
12+ Watching = "watching",
13+ Participating = "participating",
14+ Ignoring = "ignoring",
15+});
2916
3017 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
3118 pub enum SubState {
@@ -33,22 +20,10 @@ pub enum SubState {
3320 Ignored,
3421 }
3522
36-impl SubState {
37- pub fn as_str(self) -> &'static str {
38- match self {
39- SubState::Subscribed => "subscribed",
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-}
23+string_enum!(SubState {
24+ Subscribed = "subscribed",
25+ Ignored = "ignored",
26+});
5227
5328 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
5429 pub enum Reason {
@@ -62,34 +37,18 @@ pub enum Reason {
6237 Watching,
6338 }
6439
65-impl Reason {
66- pub fn as_str(self) -> &'static str {
67- match self {
68- Reason::Mention => "mention",
69- Reason::Assign => "assign",
70- Reason::ReviewRequested => "review_requested",
71- Reason::Author => "author",
72- Reason::Comment => "comment",
73- Reason::StateChange => "state_change",
74- Reason::Subscribed => "subscribed",
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- }
40+string_enum!(Reason {
41+ Mention = "mention",
42+ Assign = "assign",
43+ ReviewRequested = "review_requested",
44+ Author = "author",
45+ Comment = "comment",
46+ StateChange = "state_change",
47+ Subscribed = "subscribed",
48+ Watching = "watching",
49+});
9250
51+impl Reason {
9352 pub fn rank(self) -> u8 {
9453 match self {
9554 Reason::Mention => 8,
crates/forge-core/src/oci.rsmodified+6 -15
@@ -1,10 +1,6 @@
1+use crate::signed_token;
12 use base64::prelude::{BASE64_URL_SAFE_NO_PAD, Engine as _};
2-use hmac::{Hmac, KeyInit, Mac};
33 use serde_json::Value;
4-use sha2::Sha256;
5-use subtle::ConstantTimeEq;
6-
7-type HmacSha256 = Hmac<Sha256>;
84
95 pub const MANIFEST_MEDIA_TYPES: [&str; 4] = [
106 "application/vnd.oci.image.manifest.v1+json",
@@ -134,17 +130,13 @@ fn descriptor_size(descriptor: &Value) -> u64 {
134130 descriptor.get("size").and_then(Value::as_u64).unwrap_or(0)
135131 }
136132
137-fn mac_for(key: &[u8; 32], payload: &[u8]) -> HmacSha256 {
138- let mut mac =
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
133+fn framing(payload: &[u8]) -> [&[u8]; 2] {
134+ [b"oci\0", payload]
143135 }
144136
145137 pub fn issue_token(key: &[u8; 32], subject: Option<&str>, expires_unix: i64) -> String {
146138 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()));
148140 format!(
149141 "{}.{}",
150142 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
156148 let (payload_b64, mac_b64) = token.split_once('.')?;
157149 let payload = BASE64_URL_SAFE_NO_PAD.decode(payload_b64).ok()?;
158150 let tag = BASE64_URL_SAFE_NO_PAD.decode(mac_b64).ok()?;
159- let expected = mac_for(key, &payload).finalize().into_bytes();
160- if !bool::from(expected.as_slice().ct_eq(&tag)) {
151+ if !signed_token::verify(key, &framing(&payload), &tag) {
161152 return None;
162153 }
163154 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
166157 return None;
167158 }
168159 let subject = parts.next()?;
169- let expires: i64 = parts.next()?.parse().ok()?;
160+ let expires = signed_token::parse_expiry(parts.next()?)?;
170161 if parts.next().is_some() || now_unix >= expires {
171162 return None;
172163 }
crates/forge-core/src/pulls.rsmodified+26 -51
@@ -1,4 +1,3 @@
1-use crate::error::{Error, Result};
21 use crate::issues::Issue;
32 use crate::model::Id;
43
@@ -11,32 +10,13 @@ pub enum Mergeable {
1110 UpToDate,
1211 }
1312
14-impl Mergeable {
15- pub fn as_str(&self) -> &'static str {
16- match self {
17- Mergeable::Unknown => "unknown",
18- Mergeable::Clean => "clean",
19- Mergeable::Conflict => "conflict",
20- Mergeable::Merged => "merged",
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-}
13+string_enum!(Mergeable {
14+ Unknown = "unknown",
15+ Clean = "clean",
16+ Conflict = "conflict",
17+ Merged = "merged",
18+ UpToDate = "up_to_date",
19+});
4020
4121 #[derive(Debug, Clone, PartialEq)]
4222 pub struct PullRequest {
@@ -56,6 +36,19 @@ pub struct PullRequest {
5636 pub auto_merge: Option<AutoMerge>,
5737 }
5838
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+
5952 #[derive(Debug, Clone, PartialEq, Eq)]
6053 pub struct AutoMerge {
6154 pub style: MergeStyle,
@@ -70,30 +63,12 @@ pub enum MergeStyle {
7063 Rebase,
7164 }
7265
73-impl MergeStyle {
74- pub fn as_str(&self) -> &'static str {
75- match self {
76- MergeStyle::Merge => "merge",
77- MergeStyle::Squash => "squash",
78- MergeStyle::FastForward => "ff",
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-}
66+string_enum!(MergeStyle {
67+ Merge = "merge",
68+ Squash = "squash",
69+ FastForward = "ff",
70+ Rebase = "rebase",
71+});
9772
9873 #[cfg(test)]
9974 mod tests {
crates/forge-core/src/raw_token.rsmodified+9 -24
@@ -1,51 +1,36 @@
1+use crate::signed_token;
12 use base64::prelude::{BASE64_URL_SAFE_NO_PAD, Engine as _};
2-use hmac::{Hmac, KeyInit, Mac};
3-use sha2::Sha256;
43
5-type HmacSha256 = Hmac<Sha256>;
6-
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
4+fn framing<'a>(repo_id: &'a str, expires: &'a str) -> [&'a [u8]; 4] {
5+ [b"raw-v1:", repo_id.as_bytes(), b":", expires.as_bytes()]
176 }
187
198 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();
21- format!("{expires_unix}.{}", BASE64_URL_SAFE_NO_PAD.encode(tag))
9+ let expires = expires_unix.to_string();
10+ let tag = signed_token::mac(key, &framing(repo_id, &expires));
11+ format!("{expires}.{}", BASE64_URL_SAFE_NO_PAD.encode(tag))
2212 }
2313
2414 pub fn verify_raw(key: &[u8; 32], token: &str, repo_id: &str, now_unix: i64) -> bool {
2515 let Some((expires_str, mac_str)) = token.split_once('.') else {
2616 return false;
2717 };
28- let Ok(expires) = expires_str.parse::<i64>() else {
18+ let Some(expires) = signed_token::parse_expiry(expires_str) else {
2919 return false;
3020 };
31- if expires.to_string() != expires_str {
32- return false;
33- }
3421 if now_unix >= expires {
3522 return false;
3623 }
3724 let Ok(tag) = BASE64_URL_SAFE_NO_PAD.decode(mac_str) else {
3825 return false;
3926 };
40- if tag.len() != MAC_LEN {
41- return false;
42- }
43- mac_for(key, repo_id, expires).verify_slice(&tag).is_ok()
27+ signed_token::verify(key, &framing(repo_id, expires_str), &tag)
4428 }
4529
4630 #[cfg(test)]
4731 mod tests {
4832 use super::*;
33+ use crate::signed_token::MAC_LEN;
4934
5035 const KEY: [u8; 32] = [7; 32];
5136 const OTHER_KEY: [u8; 32] = [9; 32];
crates/forge-core/src/reactions.rsmodified+17 -27
@@ -24,19 +24,6 @@ impl Reaction {
2424 Reaction::Eyes,
2525 ];
2626
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-
4027 pub fn emoji(self) -> &'static str {
4128 match self {
4229 Reaction::PlusOne => "\u{1f44d}",
@@ -49,12 +36,19 @@ impl Reaction {
4936 Reaction::Eyes => "\u{1f440}",
5037 }
5138 }
52-
53- pub fn parse(name: &str) -> Option<Reaction> {
54- Reaction::ALL.into_iter().find(|r| r.name() == name)
55- }
5639 }
5740
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+
5852 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
5953 pub enum ReactionTarget {
6054 Issue,
@@ -63,16 +57,12 @@ pub enum ReactionTarget {
6357 DiscussionComment,
6458 }
6559
66-impl ReactionTarget {
67- pub fn as_str(self) -> &'static str {
68- match self {
69- ReactionTarget::Issue => "issue",
70- ReactionTarget::Comment => "comment",
71- ReactionTarget::Discussion => "discussion",
72- ReactionTarget::DiscussionComment => "discussion_comment",
73- }
74- }
75-}
60+string_enum!(ReactionTarget {
61+ Issue = "issue",
62+ Comment = "comment",
63+ Discussion = "discussion",
64+ DiscussionComment = "discussion_comment",
65+});
7666
7767 #[derive(Debug, Clone, PartialEq, Eq)]
7868 pub struct ReactionSummary {
crates/forge-core/src/reviews.rsmodified+11 -47
@@ -1,4 +1,3 @@
1-use crate::error::{Error, Result};
21 use crate::model::Id;
32
43 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -10,32 +9,13 @@ pub enum ReviewState {
109 Dismissed,
1110 }
1211
13-impl ReviewState {
14- pub fn as_str(&self) -> &'static str {
15- match self {
16- ReviewState::Pending => "pending",
17- ReviewState::Commented => "commented",
18- ReviewState::Approved => "approved",
19- ReviewState::ChangesRequested => "changes_requested",
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-}
12+string_enum!(ReviewState {
13+ Pending = "pending",
14+ Commented = "commented",
15+ Approved = "approved",
16+ ChangesRequested = "changes_requested",
17+ Dismissed = "dismissed",
18+});
3919
4020 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
4121 pub enum Side {
@@ -43,26 +23,10 @@ pub enum Side {
4323 New,
4424 }
4525
46-impl Side {
47- pub fn as_str(&self) -> &'static str {
48- match self {
49- Side::Old => "old",
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-}
26+string_enum!(Side {
27+ Old = "old",
28+ New = "new",
29+});
6630
6731 #[derive(Debug, Clone, PartialEq)]
6832 pub struct Review {
crates/forge-core/src/secret.rsmodified+1 -2
@@ -97,8 +97,7 @@ pub fn open(key: &[u8; 32], sealed: &str) -> Result<Vec<u8>> {
9797 return Err(Error::Crypto("sealed value is too short".into()));
9898 }
9999 let (nonce, ciphertext) = blob.split_at(NONCE_LEN);
100- let nonce = <[u8; NONCE_LEN]>::try_from(nonce)
101- .map_err(|_| Error::Crypto("sealed value has a bad nonce".into()))?;
100+ let nonce: [u8; NONCE_LEN] = nonce.try_into().expect("split_at yields NONCE_LEN bytes");
102101 let cipher = XChaCha20Poly1305::new(key.into());
103102 cipher
104103 .decrypt(&XNonce::from(nonce), ciphertext)
crates/forge-core/src/server_settings.rsmodified+324 -310
@@ -5,7 +5,9 @@ use std::sync::{Arc, RwLock};
55 use ipnet::IpNet;
66
77 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+};
911 use crate::error::{Error, Result};
1012
1113 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -34,23 +36,17 @@ impl Group {
3436 Group::Integrations,
3537 Group::Alerts,
3638 ];
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- }
5239 }
5340
41+string_enum!(Group {
42+ General = "general",
43+ Limits = "limits",
44+ Storage = "storage",
45+ Backups = "backups",
46+ Integrations = "integrations",
47+ Alerts = "alerts",
48+});
49+
5450 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
5551 pub enum Ty {
5652 Bool,
@@ -71,6 +67,9 @@ pub struct Field {
7167 pub ty: Ty,
7268 pub label: &'static str,
7369 pub help: &'static str,
70+ get: fn(&Config) -> String,
71+ set: fn(&mut Config, &str),
72+ check: fn(&str) -> Option<String>,
7473 }
7574
7675 impl Field {
@@ -79,6 +78,34 @@ impl Field {
7978 }
8079 }
8180
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)]
82109 const fn f(
83110 key: &'static str,
84111 group: Group,
@@ -86,6 +113,8 @@ const fn f(
86113 ty: Ty,
87114 label: &'static str,
88115 help: &'static str,
116+ get: fn(&Config) -> String,
117+ set: fn(&mut Config, &str),
89118 ) -> Field {
90119 Field {
91120 key,
@@ -94,18 +123,33 @@ const fn f(
94123 ty,
95124 label,
96125 help,
126+ get,
127+ set,
128+ check: no_check,
97129 }
98130 }
99131
100132 use Group::{Alerts, Backups, General, Integrations, Limits, Storage};
101133 use Kind::{Live as L, ReadOnly as R, Restart as X};
102134
103-const REGISTRATION: &[&str] = &["closed", "invite", "open"];
104-const BANNER_LEVEL: &[&str] = &["info", "warning"];
105-const ORG_CREATION: &[&str] = &["all", "admin"];
106-const MAIL_TRANSPORT: &[&str] = &["smtp", "log"];
107-const BACKEND: &[&str] = &["fs", "s3", "r2"];
108-const JURISDICTION: &[&str] = &["", "eu", "fedramp"];
135+const REGISTRATION: &[&str] = &[
136+ Registration::Closed.as_str(),
137+ Registration::Invite.as_str(),
138+ Registration::Open.as_str(),
139+];
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+];
109153 const MB: Ty = Ty::Uint(1, 1_048_576);
110154 const PORT: Ty = Ty::Uint(1, 65_535);
111155
@@ -117,6 +161,8 @@ pub static FIELDS: &[Field] = &[
117161 Ty::Choice(REGISTRATION),
118162 "Registration",
119163 "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(),
120166 ),
121167 f(
122168 "orgs.creation",
@@ -125,15 +171,22 @@ pub static FIELDS: &[Field] = &[
125171 Ty::Choice(ORG_CREATION),
126172 "Organization creation",
127173 "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(),
128176 ),
129- f(
130- "banner.message",
131- General,
132- L,
133- Ty::Text,
134- "Announcement banner",
135- "One line shown under the header on every page. Empty hides it.",
136- ),
177+ Field {
178+ check: message_check,
179+ ..f(
180+ "banner.message",
181+ General,
182+ L,
183+ Ty::Text,
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+ },
137190 f(
138191 "banner.level",
139192 General,
@@ -141,23 +194,50 @@ pub static FIELDS: &[Field] = &[
141194 Ty::Choice(BANNER_LEVEL),
142195 "Banner level",
143196 "Info or warning.",
197+ |c| c.banner.level.as_str().into(),
198+ |c, v| c.banner.level = v.parse().unwrap_or_default(),
144199 ),
145- f(
146- "banner.expires",
147- General,
148- L,
149- Ty::Text,
150- "Banner expires (UTC)",
151- "As YYYY-MM-DD HH:MM. Empty keeps the banner until it is cleared.",
152- ),
153- f(
154- "trusted_proxies",
155- General,
156- L,
157- Ty::List,
158- "Trusted proxies",
159- "Addresses or CIDR networks whose X-Forwarded-For header is trusted. Comma separated.",
160- ),
200+ Field {
201+ check: expires_check,
202+ ..f(
203+ "banner.expires",
204+ General,
205+ L,
206+ Ty::Text,
207+ "Banner expires (UTC)",
208+ "As YYYY-MM-DD HH:MM. Empty keeps the banner until it is cleared.",
209+ |c| c.banner.expires.clone(),
210+ |c, v| c.banner.expires = v.to_owned(),
211+ )
212+ },
213+ Field {
214+ check: proxies_check,
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+ },
161241 f(
162242 "base_url",
163243 General,
@@ -165,6 +245,8 @@ pub static FIELDS: &[Field] = &[
165245 Ty::Text,
166246 "Base URL",
167247 "Public URL used in links and clone URLs.",
248+ |c| c.base_url.clone(),
249+ |c, v| c.base_url = v.to_owned(),
168250 ),
169251 f(
170252 "user_content_base_url",
@@ -173,6 +255,8 @@ pub static FIELDS: &[Field] = &[
173255 Ty::Text,
174256 "User content URL",
175257 "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(),
176260 ),
177261 f(
178262 "ssh_public_host",
@@ -181,6 +265,8 @@ pub static FIELDS: &[Field] = &[
181265 Ty::Text,
182266 "SSH host shown",
183267 "Host in SSH clone URLs.",
268+ |c| c.ssh_public_host.clone(),
269+ |c, v| c.ssh_public_host = v.to_owned(),
184270 ),
185271 f(
186272 "ssh_public_port",
@@ -189,6 +275,8 @@ pub static FIELDS: &[Field] = &[
189275 PORT,
190276 "SSH port shown",
191277 "Port in SSH clone URLs.",
278+ |c| c.ssh_public_port.to_string(),
279+ |c, v| c.ssh_public_port = n(v) as u16,
192280 ),
193281 f(
194282 "listen",
@@ -197,6 +285,8 @@ pub static FIELDS: &[Field] = &[
197285 Ty::Addr,
198286 "HTTP listen address",
199287 "Set in the config file.",
288+ |c| c.listen.to_string(),
289+ |_, _| {},
200290 ),
201291 f(
202292 "user_content_listen",
@@ -205,6 +295,8 @@ pub static FIELDS: &[Field] = &[
205295 Ty::Addr,
206296 "User content listen address",
207297 "Set in the config file.",
298+ |c| c.user_content_listen.to_string(),
299+ |_, _| {},
208300 ),
209301 f(
210302 "ssh_listen",
@@ -213,6 +305,8 @@ pub static FIELDS: &[Field] = &[
213305 Ty::Addr,
214306 "SSH listen address",
215307 "Set in the config file.",
308+ |c| c.ssh_listen.to_string(),
309+ |_, _| {},
216310 ),
217311 f(
218312 "database",
@@ -221,6 +315,8 @@ pub static FIELDS: &[Field] = &[
221315 Ty::Path,
222316 "Database file",
223317 "Set in the config file.",
318+ |c| c.database.to_string_lossy().into_owned(),
319+ |_, _| {},
224320 ),
225321 f(
226322 "data_dir",
@@ -229,6 +325,8 @@ pub static FIELDS: &[Field] = &[
229325 Ty::Path,
230326 "Data directory",
231327 "Set in the config file.",
328+ |c| c.data_dir.to_string_lossy().into_owned(),
329+ |_, _| {},
232330 ),
233331 f(
234332 "ci.enabled",
@@ -237,6 +335,8 @@ pub static FIELDS: &[Field] = &[
237335 Ty::Bool,
238336 "CI enabled",
239337 "When off, pushes and pull requests create no runs.",
338+ |c| c.ci.enabled.to_string(),
339+ |c, v| c.ci.enabled = b(v),
240340 ),
241341 f(
242342 "ci.max_log_mb",
@@ -245,6 +345,8 @@ pub static FIELDS: &[Field] = &[
245345 MB,
246346 "Largest job log (MiB)",
247347 "A longer log is truncated.",
348+ |c| c.ci.max_log_mb.to_string(),
349+ |c, v| c.ci.max_log_mb = n(v),
248350 ),
249351 f(
250352 "ci.max_artifact_mb",
@@ -253,6 +355,8 @@ pub static FIELDS: &[Field] = &[
253355 MB,
254356 "Largest artifact (MiB)",
255357 "",
358+ |c| c.ci.max_artifact_mb.to_string(),
359+ |c, v| c.ci.max_artifact_mb = n(v),
256360 ),
257361 f(
258362 "ci.max_artifacts_per_job",
@@ -261,6 +365,8 @@ pub static FIELDS: &[Field] = &[
261365 Ty::Uint(1, 100_000),
262366 "Artifacts per job",
263367 "",
368+ |c| c.ci.max_artifacts_per_job.to_string(),
369+ |c, v| c.ci.max_artifacts_per_job = n(v) as u32,
264370 ),
265371 f(
266372 "ci.max_job_artifacts_mb",
@@ -269,6 +375,8 @@ pub static FIELDS: &[Field] = &[
269375 MB,
270376 "Largest total of one job's artifacts (MiB)",
271377 "",
378+ |c| c.ci.max_job_artifacts_mb.to_string(),
379+ |c, v| c.ci.max_job_artifacts_mb = n(v),
272380 ),
273381 f(
274382 "ci.log_retention_days",
@@ -277,6 +385,8 @@ pub static FIELDS: &[Field] = &[
277385 Ty::Uint(1, 36_500),
278386 "Log retention (days)",
279387 "",
388+ |c| c.ci.log_retention_days.to_string(),
389+ |c, v| c.ci.log_retention_days = n(v),
280390 ),
281391 f(
282392 "ci.artifact_retention_days",
@@ -285,6 +395,8 @@ pub static FIELDS: &[Field] = &[
285395 Ty::Uint(1, 36_500),
286396 "Artifact retention (days)",
287397 "",
398+ |c| c.ci.artifact_retention_days.to_string(),
399+ |c, v| c.ci.artifact_retention_days = n(v),
288400 ),
289401 f(
290402 "ci.artifact_keep_runs",
@@ -293,6 +405,8 @@ pub static FIELDS: &[Field] = &[
293405 Ty::Uint(0, 100_000),
294406 "Artifact runs kept per repo",
295407 "0 keeps all.",
408+ |c| c.ci.artifact_keep_runs.to_string(),
409+ |c, v| c.ci.artifact_keep_runs = n(v) as u32,
296410 ),
297411 f(
298412 "ci.artifact_max_total_mb",
@@ -301,6 +415,8 @@ pub static FIELDS: &[Field] = &[
301415 Ty::Uint(0, 100_000_000),
302416 "Artifact disk limit (MiB)",
303417 "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),
304420 ),
305421 f(
306422 "ci.registration_token_hours",
@@ -309,6 +425,8 @@ pub static FIELDS: &[Field] = &[
309425 Ty::Uint(1, 8_760),
310426 "Runner token lifetime (hours)",
311427 "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,
312430 ),
313431 f(
314432 "lfs.max_object_mb",
@@ -317,6 +435,8 @@ pub static FIELDS: &[Field] = &[
317435 MB,
318436 "Largest LFS object (MiB)",
319437 "",
438+ |c| c.lfs.max_object_mb.to_string(),
439+ |c, v| c.lfs.max_object_mb = n(v),
320440 ),
321441 f(
322442 "releases.max_asset_mb",
@@ -325,6 +445,8 @@ pub static FIELDS: &[Field] = &[
325445 MB,
326446 "Largest release asset (MiB)",
327447 "",
448+ |c| c.releases.max_asset_mb.to_string(),
449+ |c, v| c.releases.max_asset_mb = n(v),
328450 ),
329451 f(
330452 "storage.backend",
@@ -333,6 +455,8 @@ pub static FIELDS: &[Field] = &[
333455 Ty::Choice(BACKEND),
334456 "Backend",
335457 "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(),
336460 ),
337461 f(
338462 "storage.r2.account_id",
@@ -341,8 +465,19 @@ pub static FIELDS: &[Field] = &[
341465 Ty::Text,
342466 "R2 account id",
343467 "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(),
344480 ),
345- f("storage.r2.bucket", Storage, X, Ty::Text, "R2 bucket", ""),
346481 f(
347482 "storage.r2.jurisdiction",
348483 Storage,
@@ -350,6 +485,8 @@ pub static FIELDS: &[Field] = &[
350485 Ty::Choice(JURISDICTION),
351486 "R2 jurisdiction",
352487 "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(),
353490 ),
354491 f(
355492 "storage.r2.prefix",
@@ -358,6 +495,8 @@ pub static FIELDS: &[Field] = &[
358495 Ty::Text,
359496 "R2 key prefix",
360497 "",
498+ |c| c.storage.r2.prefix.clone(),
499+ |c, v| c.storage.r2.prefix = v.to_owned(),
361500 ),
362501 f(
363502 "storage.r2.access_key_id",
@@ -366,6 +505,8 @@ pub static FIELDS: &[Field] = &[
366505 Ty::Text,
367506 "R2 access key id",
368507 "",
508+ |c| c.storage.r2.access_key_id.clone(),
509+ |c, v| c.storage.r2.access_key_id = v.to_owned(),
369510 ),
370511 f(
371512 "storage.r2.secret_access_key_file",
@@ -374,9 +515,35 @@ pub static FIELDS: &[Field] = &[
374515 Ty::Path,
375516 "R2 secret key file",
376517 "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(),
377546 ),
378- f("storage.s3.bucket", Storage, X, Ty::Text, "S3 bucket", ""),
379- f("storage.s3.region", Storage, X, Ty::Text, "S3 region", ""),
380547 f(
381548 "storage.s3.endpoint",
382549 Storage,
@@ -384,6 +551,8 @@ pub static FIELDS: &[Field] = &[
384551 Ty::Text,
385552 "S3 endpoint",
386553 "Leave empty for AWS.",
554+ |c| c.storage.s3.endpoint.clone(),
555+ |c, v| c.storage.s3.endpoint = v.to_owned(),
387556 ),
388557 f(
389558 "storage.s3.prefix",
@@ -392,6 +561,8 @@ pub static FIELDS: &[Field] = &[
392561 Ty::Text,
393562 "S3 key prefix",
394563 "",
564+ |c| c.storage.s3.prefix.clone(),
565+ |c, v| c.storage.s3.prefix = v.to_owned(),
395566 ),
396567 f(
397568 "storage.s3.access_key_id",
@@ -400,6 +571,8 @@ pub static FIELDS: &[Field] = &[
400571 Ty::Text,
401572 "S3 access key id",
402573 "",
574+ |c| c.storage.s3.access_key_id.clone(),
575+ |c, v| c.storage.s3.access_key_id = v.to_owned(),
403576 ),
404577 f(
405578 "storage.s3.secret_access_key_file",
@@ -408,6 +581,14 @@ pub static FIELDS: &[Field] = &[
408581 Ty::Path,
409582 "S3 secret key file",
410583 "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(),
411592 ),
412593 f(
413594 "storage.s3.allow_http",
@@ -416,6 +597,8 @@ pub static FIELDS: &[Field] = &[
416597 Ty::Bool,
417598 "S3 allow http",
418599 "",
600+ |c| c.storage.s3.allow_http.to_string(),
601+ |c, v| c.storage.s3.allow_http = b(v),
419602 ),
420603 f(
421604 "storage.s3.virtual_hosted_style",
@@ -424,6 +607,8 @@ pub static FIELDS: &[Field] = &[
424607 Ty::Bool,
425608 "S3 virtual hosted style",
426609 "",
610+ |c| c.storage.s3.virtual_hosted_style.to_string(),
611+ |c, v| c.storage.s3.virtual_hosted_style = b(v),
427612 ),
428613 f(
429614 "backup.dir",
@@ -432,6 +617,8 @@ pub static FIELDS: &[Field] = &[
432617 Ty::Path,
433618 "Backup directory",
434619 "Empty turns scheduled backups off.",
620+ |c| c.backup.dir.to_string_lossy().into_owned(),
621+ |c, v| c.backup.dir = v.into(),
435622 ),
436623 f(
437624 "backup.interval_hours",
@@ -440,6 +627,8 @@ pub static FIELDS: &[Field] = &[
440627 Ty::Uint(1, 8_760),
441628 "Backup interval (hours)",
442629 "",
630+ |c| c.backup.interval_hours.to_string(),
631+ |c, v| c.backup.interval_hours = n(v),
443632 ),
444633 f(
445634 "backup.keep",
@@ -448,6 +637,8 @@ pub static FIELDS: &[Field] = &[
448637 Ty::Uint(1, 10_000),
449638 "Backup sets kept",
450639 "",
640+ |c| c.backup.keep.to_string(),
641+ |c, v| c.backup.keep = n(v) as usize,
451642 ),
452643 f(
453644 "backup.fsck_interval_days",
@@ -456,6 +647,8 @@ pub static FIELDS: &[Field] = &[
456647 Ty::Uint(1, 3_650),
457648 "fsck interval (days)",
458649 "",
650+ |c| c.backup.fsck_interval_days.to_string(),
651+ |c, v| c.backup.fsck_interval_days = n(v),
459652 ),
460653 f(
461654 "backup.healthcheck_url",
@@ -464,6 +657,8 @@ pub static FIELDS: &[Field] = &[
464657 Ty::Secret,
465658 "Backup healthcheck URL",
466659 "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(),
467662 ),
468663 f(
469664 "replication.target",
@@ -472,6 +667,8 @@ pub static FIELDS: &[Field] = &[
472667 Ty::Text,
473668 "Replication target",
474669 "Empty turns standby replication off.",
670+ |c| c.replication.target.clone(),
671+ |c, v| c.replication.target = v.to_owned(),
475672 ),
476673 f(
477674 "replication.ssh_port",
@@ -480,6 +677,8 @@ pub static FIELDS: &[Field] = &[
480677 PORT,
481678 "Replication SSH port",
482679 "",
680+ |c| c.replication.ssh_port.to_string(),
681+ |c, v| c.replication.ssh_port = n(v) as u16,
483682 ),
484683 f(
485684 "replication.identity_file",
@@ -488,6 +687,8 @@ pub static FIELDS: &[Field] = &[
488687 Ty::Path,
489688 "Replication identity file",
490689 "",
690+ |c| c.replication.identity_file.to_string_lossy().into_owned(),
691+ |c, v| c.replication.identity_file = v.into(),
491692 ),
492693 f(
493694 "replication.known_hosts_file",
@@ -496,6 +697,13 @@ pub static FIELDS: &[Field] = &[
496697 Ty::Path,
497698 "Replication known hosts file",
498699 "",
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(),
499707 ),
500708 f(
501709 "replication.db_snapshot_minutes",
@@ -504,6 +712,8 @@ pub static FIELDS: &[Field] = &[
504712 Ty::Uint(1, 525_600),
505713 "Database snapshot (minutes)",
506714 "",
715+ |c| c.replication.db_snapshot_minutes.to_string(),
716+ |c, v| c.replication.db_snapshot_minutes = n(v),
507717 ),
508718 f(
509719 "replication.reconcile_minutes",
@@ -512,6 +722,8 @@ pub static FIELDS: &[Field] = &[
512722 Ty::Uint(1, 525_600),
513723 "Reconcile (minutes)",
514724 "",
725+ |c| c.replication.reconcile_minutes.to_string(),
726+ |c, v| c.replication.reconcile_minutes = n(v),
515727 ),
516728 f(
517729 "replication.healthcheck_url",
@@ -520,6 +732,8 @@ pub static FIELDS: &[Field] = &[
520732 Ty::Secret,
521733 "Replication healthcheck URL",
522734 "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(),
523737 ),
524738 f(
525739 "webhooks.allow_http",
@@ -528,6 +742,8 @@ pub static FIELDS: &[Field] = &[
528742 Ty::Bool,
529743 "Allow http webhooks",
530744 "Permit http:// hook URLs besides https://.",
745+ |c| c.webhooks.allow_http.to_string(),
746+ |c, v| c.webhooks.allow_http = b(v),
531747 ),
532748 f(
533749 "webhooks.allowed_hosts",
@@ -536,6 +752,8 @@ pub static FIELDS: &[Field] = &[
536752 Ty::List,
537753 "Webhook allowed hosts",
538754 "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),
539757 ),
540758 f(
541759 "mail.transport",
@@ -544,6 +762,8 @@ pub static FIELDS: &[Field] = &[
544762 Ty::Choice(MAIL_TRANSPORT),
545763 "Mail transport",
546764 "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(),
547767 ),
548768 f(
549769 "advisories.enabled",
@@ -552,15 +772,22 @@ pub static FIELDS: &[Field] = &[
552772 Ty::Bool,
553773 "Security advisories",
554774 "Download OSV dumps and scan lockfiles.",
775+ |c| c.advisories.enabled.to_string(),
776+ |c, v| c.advisories.enabled = b(v),
555777 ),
556- f(
557- "advisories.ecosystems",
558- Integrations,
559- X,
560- Ty::List,
561- "Advisory ecosystems",
562- "Any of crates.io, npm, Go. Comma separated.",
563- ),
778+ Field {
779+ check: ecosystems_check,
780+ ..f(
781+ "advisories.ecosystems",
782+ Integrations,
783+ X,
784+ Ty::List,
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+ },
564791 f(
565792 "advisories.refresh_hours",
566793 Integrations,
@@ -568,6 +795,8 @@ pub static FIELDS: &[Field] = &[
568795 Ty::Uint(1, 8_760),
569796 "Advisory refresh (hours)",
570797 "",
798+ |c| c.advisories.refresh_hours.to_string(),
799+ |c, v| c.advisories.refresh_hours = n(v),
571800 ),
572801 f(
573802 "self_update.enabled",
@@ -576,6 +805,8 @@ pub static FIELDS: &[Field] = &[
576805 Ty::Bool,
577806 "Self-update",
578807 "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),
579810 ),
580811 f(
581812 "self_update.repo",
@@ -584,6 +815,8 @@ pub static FIELDS: &[Field] = &[
584815 Ty::Text,
585816 "Self-update repo",
586817 "As owner/name.",
818+ |c| c.self_update.repo.clone(),
819+ |c, v| c.self_update.repo = v.to_owned(),
587820 ),
588821 f(
589822 "self_update.branch",
@@ -592,6 +825,8 @@ pub static FIELDS: &[Field] = &[
592825 Ty::Text,
593826 "Self-update branch",
594827 "",
828+ |c| c.self_update.branch.clone(),
829+ |c, v| c.self_update.branch = v.to_owned(),
595830 ),
596831 f(
597832 "self_update.job",
@@ -600,6 +835,8 @@ pub static FIELDS: &[Field] = &[
600835 Ty::Text,
601836 "Self-update job",
602837 "",
838+ |c| c.self_update.job.clone(),
839+ |c, v| c.self_update.job = v.to_owned(),
603840 ),
604841 f(
605842 "self_update.artifact",
@@ -608,6 +845,8 @@ pub static FIELDS: &[Field] = &[
608845 Ty::Text,
609846 "Self-update artifact",
610847 "{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(),
611850 ),
612851 f(
613852 "alerts.enabled",
@@ -616,6 +855,8 @@ pub static FIELDS: &[Field] = &[
616855 Ty::Bool,
617856 "Admin alerts",
618857 "Master switch. Off raises and sends nothing.",
858+ |c| c.alerts.enabled.to_string(),
859+ |c, v| c.alerts.enabled = b(v),
619860 ),
620861 f(
621862 "alerts.email",
@@ -624,6 +865,8 @@ pub static FIELDS: &[Field] = &[
624865 Ty::Bool,
625866 "Email alerts",
626867 "Also email the admins who have a verified address.",
868+ |c| c.alerts.email.to_string(),
869+ |c, v| c.alerts.email = b(v),
627870 ),
628871 f(
629872 "alerts.runner_offline_minutes",
@@ -632,6 +875,8 @@ pub static FIELDS: &[Field] = &[
632875 Ty::Uint(1, 1_440),
633876 "Runner offline after (minutes)",
634877 "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),
635880 ),
636881 f(
637882 "alerts.disk_free_percent",
@@ -640,6 +885,8 @@ pub static FIELDS: &[Field] = &[
640885 Ty::Uint(1, 90),
641886 "Low disk space (percent free)",
642887 "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),
643890 ),
644891 f(
645892 "alerts.disk_free_gib",
@@ -648,6 +895,8 @@ pub static FIELDS: &[Field] = &[
648895 Ty::Uint(0, 100_000),
649896 "Low disk space (GiB free)",
650897 "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),
651900 ),
652901 f(
653902 "alerts.on_runner_offline",
@@ -656,6 +905,8 @@ pub static FIELDS: &[Field] = &[
656905 Ty::Bool,
657906 "Runner offline alerts",
658907 "",
908+ |c| c.alerts.on_runner_offline.to_string(),
909+ |c, v| c.alerts.on_runner_offline = b(v),
659910 ),
660911 f(
661912 "alerts.on_backup",
@@ -664,6 +915,8 @@ pub static FIELDS: &[Field] = &[
664915 Ty::Bool,
665916 "Backup alerts",
666917 "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),
667920 ),
668921 f(
669922 "alerts.on_disk",
@@ -672,6 +925,8 @@ pub static FIELDS: &[Field] = &[
672925 Ty::Bool,
673926 "Disk space alerts",
674927 "",
928+ |c| c.alerts.on_disk.to_string(),
929+ |c, v| c.alerts.on_disk = b(v),
675930 ),
676931 f(
677932 "alerts.on_ci_killed",
@@ -680,6 +935,8 @@ pub static FIELDS: &[Field] = &[
680935 Ty::Bool,
681936 "Killed CI job alerts",
682937 "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),
683940 ),
684941 f(
685942 "alerts.on_self_update",
@@ -688,6 +945,8 @@ pub static FIELDS: &[Field] = &[
688945 Ty::Bool,
689946 "Self-update alerts",
690947 "Deployed, failed, and server restarted.",
948+ |c| c.alerts.on_self_update.to_string(),
949+ |c, v| c.alerts.on_self_update = b(v),
691950 ),
692951 f(
693952 "alerts.on_replication",
@@ -696,6 +955,8 @@ pub static FIELDS: &[Field] = &[
696955 Ty::Bool,
697956 "Replication alerts",
698957 "Standby failing or lagging.",
958+ |c| c.alerts.on_replication.to_string(),
959+ |c, v| c.alerts.on_replication = b(v),
699960 ),
700961 ];
701962
@@ -753,14 +1014,8 @@ pub fn normalize(field: &Field, raw: &str) -> Result<String> {
7531014 "must be one line of at most 1024 characters",
7541015 ));
7551016 }
756- if field.key == "banner.expires"
757- && !raw.is_empty()
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"));
1017+ if let Some(why) = (field.check)(raw) {
1018+ return Err(invalid(field, &why));
7641019 }
7651020 Ok(raw.to_owned())
7661021 }
@@ -772,19 +1027,8 @@ pub fn normalize(field: &Field, raw: &str) -> Result<String> {
7721027 {
7731028 return Err(invalid(field, "has an entry that is too long"));
7741029 }
775- if field.key == "trusted_proxies" {
776- for item in &items {
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- }
1030+ if let Some(why) = (field.check)(raw) {
1031+ return Err(invalid(field, &why));
7881032 }
7891033 Ok(items.join(", "))
7901034 }
@@ -799,121 +1043,8 @@ fn n(v: &str) -> u64 {
7991043 v.parse().unwrap_or_default()
8001044 }
8011045
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-
8171046 pub fn get(cfg: &Config, key: &str) -> String {
818- let path = |p: &std::path::Path| p.to_string_lossy().into_owned();
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- }
1047+ field(key).map_or_else(String::new, |f| (f.get)(cfg))
9171048 }
9181049
9191050 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<()> {
9221053 return Err(invalid(field, "is read-only"));
9231054 }
9241055 let v = normalize(field, raw)?;
925- let v = v.as_str();
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- }
1056+ (field.set)(cfg, &v);
10431057 Ok(())
10441058 }
10451059
crates/forge-core/src/signed_token.rsadded+25 -0
@@ -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+}
crates/forge-core/src/store/admin_alerts.rsmodified+24 -17
@@ -2,13 +2,14 @@ use turso::{Row, Value};
22
33 use super::finish;
44 use super::{Store, col_int, col_text, db_err, fetch_all, fetch_opt, new_id, text};
5+use crate::alerts::AlertTopic;
56 use crate::error::Result;
67 use crate::time::now_stamp;
78
89 #[derive(Debug, Clone, PartialEq, Eq)]
910 pub struct AdminAlert {
1011 pub key: String,
11- pub kind: String,
12+ pub kind: AlertTopic,
1213 pub subject: String,
1314 pub detail: String,
1415 pub raised_at: String,
@@ -18,7 +19,7 @@ pub struct AdminAlert {
1819 pub struct AdminNotice {
1920 pub id: String,
2021 pub alert_key: String,
21- pub kind: String,
22+ pub kind: AlertTopic,
2223 pub subject: String,
2324 pub detail: String,
2425 pub resolved: bool,
@@ -31,7 +32,7 @@ const NOTICE_COLS: &str = "id, alert_key, kind, subject, detail, resolved, unrea
3132 fn map_alert(row: &Row) -> Result<AdminAlert> {
3233 Ok(AdminAlert {
3334 key: col_text(row, 0)?,
34- kind: col_text(row, 1)?,
35+ kind: super::issues::parse_db(&col_text(row, 1)?)?,
3536 subject: col_text(row, 2)?,
3637 detail: col_text(row, 3)?,
3738 raised_at: col_text(row, 4)?,
@@ -42,7 +43,7 @@ fn map_notice(row: &Row) -> Result<AdminNotice> {
4243 Ok(AdminNotice {
4344 id: col_text(row, 0)?,
4445 alert_key: col_text(row, 1)?,
45- kind: col_text(row, 2)?,
46+ kind: super::issues::parse_db(&col_text(row, 2)?)?,
4647 subject: col_text(row, 3)?,
4748 detail: col_text(row, 4)?,
4849 resolved: col_int(row, 5)? != 0,
@@ -55,7 +56,7 @@ impl Store {
5556 pub async fn raise_alert(
5657 &self,
5758 key: &str,
58- kind: &str,
59+ kind: AlertTopic,
5960 subject: &str,
6061 detail: &str,
6162 ) -> Result<bool> {
@@ -90,7 +91,7 @@ impl Store {
9091 updated_at = excluded.updated_at",
9192 vec![
9293 text(key),
93- text(kind),
94+ text(kind.as_str()),
9495 text(subject),
9596 text(detail),
9697 text(&now),
@@ -137,7 +138,7 @@ impl Store {
137138 pub async fn record_alert_event(
138139 &self,
139140 key: &str,
140- kind: &str,
141+ kind: AlertTopic,
141142 subject: &str,
142143 detail: &str,
143144 ) -> Result<bool> {
@@ -149,7 +150,7 @@ impl Store {
149150 raised_at, resolved_at, updated_at) VALUES (?1, ?2, ?3, ?4, 'event', ?5, NULL, ?5)",
150151 vec![
151152 text(key),
152- text(kind),
153+ text(kind.as_str()),
153154 text(subject),
154155 text(detail),
155156 text(&now),
@@ -172,12 +173,12 @@ impl Store {
172173 .await
173174 }
174175
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>> {
176177 let conn = self.read_conn().await;
177178 fetch_all(
178179 &conn,
179180 "SELECT key FROM admin_alerts WHERE state = 'active' AND kind = ?1",
180- (kind.to_owned(),),
181+ (kind.as_str().to_owned(),),
181182 |row| col_text(row, 0),
182183 )
183184 .await
@@ -187,7 +188,7 @@ impl Store {
187188 &self,
188189 user_id: &str,
189190 alert_key: &str,
190- kind: &str,
191+ kind: AlertTopic,
191192 subject: &str,
192193 detail: &str,
193194 resolved: bool,
@@ -200,7 +201,7 @@ impl Store {
200201 text(&new_id()),
201202 text(user_id),
202203 text(alert_key),
203- text(kind),
204+ text(kind.as_str()),
204205 text(subject),
205206 text(detail),
206207 Value::Integer(i64::from(resolved)),
@@ -289,6 +290,7 @@ impl Store {
289290
290291 #[cfg(test)]
291292 mod tests {
293+ use crate::alerts::AlertTopic;
292294 use crate::store::Store;
293295
294296 async fn store() -> (Store, tempfile::TempDir) {
@@ -300,13 +302,18 @@ mod tests {
300302 async fn an_alert_is_raised_once_until_it_resolves(store: &Store) {
301303 assert!(
302304 store
303- .raise_alert("runner_offline:r1", "runner_offline", "ci-1", "")
305+ .raise_alert("runner_offline:r1", AlertTopic::RunnerOffline, "ci-1", "")
304306 .await
305307 .unwrap()
306308 );
307309 assert!(
308310 !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+ )
310317 .await
311318 .unwrap(),
312319 "still active: not raised again"
@@ -329,7 +336,7 @@ mod tests {
329336
330337 assert!(
331338 store
332- .raise_alert("runner_offline:r1", "runner_offline", "ci-1", "")
339+ .raise_alert("runner_offline:r1", AlertTopic::RunnerOffline, "ci-1", "")
333340 .await
334341 .unwrap(),
335342 "a new failure after the resolution is raised again"
@@ -339,13 +346,13 @@ mod tests {
339346 async fn events_fire_once_and_are_never_active(store: &Store) {
340347 assert!(
341348 store
342- .record_alert_event("ci_killed:run1", "ci_killed", "ci-1", "")
349+ .record_alert_event("ci_killed:run1", AlertTopic::CiKilled, "ci-1", "")
343350 .await
344351 .unwrap()
345352 );
346353 assert!(
347354 !store
348- .record_alert_event("ci_killed:run1", "ci_killed", "ci-1", "")
355+ .record_alert_event("ci_killed:run1", AlertTopic::CiKilled, "ci-1", "")
349356 .await
350357 .unwrap()
351358 );
crates/forge-core/src/store/advisories.rsmodified+8 -20
@@ -3,6 +3,7 @@ use std::collections::{BTreeSet, HashMap};
33 use tokio::sync::mpsc;
44 use turso::{Row, Value};
55
6+use super::issues::parse_db;
67 use super::{Store, col_int, col_text, db_err, fetch_all, fetch_opt, finish};
78 use crate::advisories::{Advisory, Dependency, Range, affects};
89 use crate::error::{Error, Result};
@@ -15,24 +16,11 @@ pub enum AlertState {
1516 Fixed,
1617 }
1718
18-impl AlertState {
19- pub fn as_str(self) -> &'static str {
20- match self {
21- AlertState::Open => "open",
22- AlertState::Dismissed => "dismissed",
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-}
19+string_enum!(AlertState {
20+ Open = "open",
21+ Dismissed = "dismissed",
22+ Fixed = "fixed",
23+});
3624
3725 #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
3826 pub struct AlertKey {
@@ -100,7 +88,7 @@ fn key_of(row: &Row, offset: usize) -> Result<AlertKey> {
10088 fn map_alert(row: &Row) -> Result<Alert> {
10189 Ok(Alert {
10290 key: key_of(row, 0)?,
103- state: AlertState::parse(&col_text(row, 4)?)?,
91+ state: parse_db(&col_text(row, 4)?)?,
10492 summary: col_text(row, 5)?,
10593 severity: col_text(row, 6)?,
10694 created_at: col_text(row, 7)?,
@@ -250,7 +238,7 @@ impl Store {
250238 "SELECT advisory_id, ecosystem, package, version, state FROM repo_alerts \
251239 WHERE repo_id = ?1",
252240 (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)?)?)),
254242 )
255243 .await?
256244 .into_iter()
crates/forge-core/src/store/audit.rsmodified+4 -4
@@ -1,8 +1,9 @@
11 use turso::{Row, Value};
22
3+use super::issues::parse_db;
34 use super::{Store, col_opt_text, col_text, db_err, fetch_all};
4-use crate::audit::{AuditAction, AuditCursor, AuditEntry, AuditFilter};
5-use crate::error::{Error, Result};
5+use crate::audit::{AuditCursor, AuditEntry, AuditFilter};
6+use crate::error::Result;
67
78 const AUDIT_COLS: &str = "id, at, actor_id, actor_name, action, target_kind, target_id, \
89 target_name, ip, data";
@@ -15,8 +16,7 @@ fn map_audit(row: &Row) -> Result<AuditEntry> {
1516 at: col_text(row, 1)?,
1617 actor_id: col_opt_text(row, 2)?,
1718 actor_name: col_text(row, 3)?,
18- action: AuditAction::parse(&action)
19- .ok_or_else(|| Error::Database(format!("unknown audit action {action:?}")))?,
19+ action: parse_db(&action)?,
2020 target_kind: col_text(row, 5)?,
2121 target_id: col_text(row, 6)?,
2222 target_name: col_text(row, 7)?,
crates/forge-core/src/store/backup_runs.rsmodified+12 -40
@@ -1,5 +1,6 @@
11 use turso::{Row, Value};
22
3+use super::issues::parse_db;
34 use super::{Store, col_opt_int, col_opt_text, col_text, db_err, fetch_all, new_id};
45 use crate::error::{Error, Result};
56 use crate::time::now_stamp;
@@ -13,22 +14,10 @@ pub enum RunKind {
1314 Fsck,
1415 }
1516
16-impl RunKind {
17- pub fn as_str(self) -> &'static str {
18- match self {
19- RunKind::Backup => "backup",
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-}
17+string_enum!(RunKind {
18+ Backup = "backup",
19+ Fsck = "fsck",
20+});
3221
3322 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
3423 pub enum RunTrigger {
@@ -37,24 +26,11 @@ pub enum RunTrigger {
3726 Cli,
3827 }
3928
40-impl RunTrigger {
41- pub fn as_str(self) -> &'static str {
42- match self {
43- RunTrigger::Schedule => "schedule",
44- RunTrigger::Manual => "manual",
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-}
29+string_enum!(RunTrigger {
30+ Schedule = "schedule",
31+ Manual = "manual",
32+ Cli = "cli",
33+});
5834
5935 #[derive(Debug, Clone, PartialEq, Eq)]
6036 pub struct BackupRun {
@@ -70,17 +46,13 @@ pub struct BackupRun {
7046 }
7147
7248 fn map_run(row: &Row) -> Result<BackupRun> {
73- let kind = col_text(row, 1)?;
74- let trigger = col_text(row, 8)?;
7549 let bytes = col_opt_int(row, 6)?
7650 .map(|n| u64::try_from(n).map_err(|_| Error::Database("negative run size".into())))
7751 .transpose()?;
7852 Ok(BackupRun {
7953 id: col_text(row, 0)?,
80- kind: RunKind::parse(&kind)
81- .ok_or_else(|| Error::Database(format!("unknown run kind {kind:?}")))?,
82- trigger: RunTrigger::parse(&trigger)
83- .ok_or_else(|| Error::Database(format!("unknown run trigger {trigger:?}")))?,
54+ kind: parse_db(&col_text(row, 1)?)?,
55+ trigger: parse_db(&col_text(row, 8)?)?,
8456 started_at: col_text(row, 2)?,
8557 finished_at: col_opt_text(row, 3)?,
8658 ok: col_opt_int(row, 4)?.map(|n| n != 0),
crates/forge-core/src/store/ci.rsmodified+45 -18
@@ -3,6 +3,7 @@ use std::time::Duration;
33
44 use turso::{Connection, Row, Value};
55
6+use super::issues::parse_db;
67 use super::{
78 Store, col_blob, col_bool, col_int, col_opt_int, col_opt_text, col_text, db_err, fetch_all,
89 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> {
102103 commit_oid: col_text(row, 5)?,
103104 pull_number: col_opt_int(row, 6)?,
104105 actor_id: col_text(row, 7)?,
105- state: col_text(row, 8)?.parse::<RunState>()?,
106+ state: parse_db(&col_text(row, 8)?)?,
106107 config_error: col_opt_text(row, 9)?,
107108 created_at: col_text(row, 10)?,
108109 finished_at: col_opt_text(row, 11)?,
@@ -115,7 +116,7 @@ fn map_job(row: &Row) -> Result<CiJob> {
115116 run_id: col_text(row, 1)?,
116117 name: col_text(row, 2)?,
117118 spec_json: col_text(row, 3)?,
118- state: col_text(row, 4)?.parse::<JobState>()?,
119+ state: parse_db(&col_text(row, 4)?)?,
119120 runner_id: col_opt_text(row, 5)?,
120121 exit_code: col_opt_int(row, 6)?,
121122 message: col_opt_text(row, 7)?,
@@ -333,7 +334,7 @@ async fn recompute_run(conn: &Connection, run_id: &str, now: &str) -> Result<()>
333334 conn,
334335 "SELECT state FROM ci_jobs WHERE run_id = ?1",
335336 (run_id.to_string(),),
336- |row| col_text(row, 0)?.parse::<JobState>(),
337+ |row| parse_db(&col_text(row, 0)?),
337338 )
338339 .await?;
339340 let active =
@@ -498,8 +499,8 @@ impl Store {
498499 ));
499500 }
500501 tx.execute(
501- "INSERT INTO ci_runners (id, name, labels, secret_hash, created_at, disabled) \
502- VALUES (?1, ?2, ?3, ?4, ?5, 0)",
502+ "INSERT INTO ci_runners (id, name, labels, registered_labels, secret_hash, created_at, disabled) \
503+ VALUES (?1, ?2, ?3, ?3, ?4, ?5, 0)",
503504 vec![
504505 text(&id),
505506 text(name),
@@ -683,25 +684,21 @@ impl Store {
683684 .map_err(|e| Error::Database(e.to_string()))?,
684685 )
685686 };
686- let labels = if key == "labels" {
687+ if key == "labels" {
687688 let chosen = runner
688689 .config_overrides
689690 .get("labels")
690- .or_else(|| runner.reported_config.get("labels"));
691- chosen.and_then(|v| serde_json::from_value::<Vec<String>>(v.clone()).ok())
692- } else {
693- None
694- };
695- if let Some(labels) = labels {
691+ .or_else(|| runner.reported_config.get("labels"))
692+ .and_then(|v| serde_json::from_value::<Vec<String>>(v.clone()).ok())
693+ .map(|labels| serde_json::to_string(&labels))
694+ .transpose()
695+ .map_err(|e| Error::Database(e.to_string()))?;
696696 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",
698698 (
699699 id.to_string(),
700700 overrides,
701- text(
702- &serde_json::to_string(&labels)
703- .map_err(|e| Error::Database(e.to_string()))?,
704- ),
701+ chosen.map_or(Value::Null, |json| text(&json)),
705702 ),
706703 )
707704 .await
@@ -1777,10 +1774,41 @@ impl Store {
17771774 name: &str,
17781775 size: i64,
17791776 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,
17801790 ) -> Result<CiArtifact> {
17811791 if size < 0 {
17821792 return Err(Error::Invalid("an artifact size cannot be negative".into()));
17831793 }
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+ }
17841812 let artifact = CiArtifact {
17851813 id: new_id(),
17861814 job_id: job_id.to_string(),
@@ -1789,7 +1817,6 @@ impl Store {
17891817 sha256: sha256.to_string(),
17901818 created_at: now_stamp(),
17911819 };
1792- let conn = self.inner.conn.lock().await;
17931820 conn.execute(
17941821 "INSERT INTO ci_artifacts (id, job_id, name, size, sha256, created_at) \
17951822 VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
crates/forge-core/src/store/commit_status.rsmodified+8 -26
@@ -2,6 +2,7 @@ use std::collections::HashMap;
22
33 use turso::{Row, Value};
44
5+use super::issues::parse_db;
56 use super::{Store, col_opt_text, col_text, db_err, fetch_all, fetch_opt, missing_row, new_id};
67 use crate::error::{Error, Result};
78 use crate::time::now_stamp;
@@ -22,26 +23,12 @@ pub enum StatusState {
2223 Error,
2324 }
2425
25-impl StatusState {
26- pub fn as_str(self) -> &'static str {
27- match self {
28- StatusState::Pending => "pending",
29- StatusState::Success => "success",
30- StatusState::Failure => "failure",
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-}
26+string_enum!(StatusState {
27+ Pending = "pending",
28+ Success = "success",
29+ Failure = "failure",
30+ Error = "error",
31+});
4532
4633 #[derive(Debug, Clone, PartialEq, Eq)]
4734 pub struct CommitStatus {
@@ -272,13 +259,8 @@ impl Store {
272259 }
273260 }
274261
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-
280262 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)?)?;
282264 Ok(CommitStatus {
283265 id: col_text(row, 0)?,
284266 repo_id: col_text(row, 1)?,
crates/forge-core/src/store/contributions.rsmodified+12 -11
@@ -189,6 +189,7 @@ impl Store {
189189 #[cfg(test)]
190190 mod tests {
191191 use crate::model::Visibility;
192+ use crate::pulls::NewPull;
192193
193194 use super::*;
194195
@@ -332,17 +333,17 @@ mod tests {
332333 .await
333334 .unwrap();
334335 let pull = store
335- .create_pull(
336- &demo.id,
337- &tahinli.id,
338- "change",
339- "",
340- "main",
341- &demo.id,
342- "topic",
343- OID,
344- OID,
345- )
336+ .create_pull(&NewPull {
337+ repo_id: &demo.id,
338+ author_id: &tahinli.id,
339+ title: "change",
340+ body: "",
341+ base_branch: "main",
342+ head_repo_id: &demo.id,
343+ head_branch: "topic",
344+ head_oid: OID,
345+ base_oid: OID,
346+ })
346347 .await
347348 .unwrap();
348349 set_created_at(&store, "issues", &pull.issue.id, day2).await;
crates/forge-core/src/store/discussions.rsmodified+5 -5
@@ -2,12 +2,13 @@ use turso::transaction::Transaction;
22 use turso::{Connection, Row, Value};
33
44 use super::finish;
5+use super::issues::parse_db;
56 use super::{
67 Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, insert_err, new_id,
78 };
89 use crate::discussions::{
910 Discussion, DiscussionCategory, DiscussionComment, DiscussionFilter, DiscussionListItem,
10- DiscussionNotification, DiscussionReason, validate_comment, validate_discussion,
11+ DiscussionNotification, validate_comment, validate_discussion,
1112 };
1213 use crate::error::{Error, Result};
1314 use crate::time::now_stamp;
@@ -23,8 +24,7 @@ fn map_discussion(row: &Row) -> Result<Discussion> {
2324 id: col_text(row, 0)?,
2425 repo_id: col_text(row, 1)?,
2526 number: col_int(row, 2)?,
26- category: DiscussionCategory::parse(&category)
27- .ok_or_else(|| Error::Database(format!("stored category {category:?}")))?,
27+ category: parse_db(&category)?,
2828 title: col_text(row, 4)?,
2929 body: col_text(row, 5)?,
3030 author_id: col_text(row, 6)?,
@@ -52,8 +52,7 @@ fn map_discussion_note(row: &Row) -> Result<DiscussionNotification> {
5252 repo_name: col_text(row, 3)?,
5353 number: col_int(row, 4)?,
5454 title: col_text(row, 5)?,
55- reason: DiscussionReason::parse(&reason)
56- .ok_or_else(|| Error::Database(format!("unknown discussion reason {reason:?}")))?,
55+ reason: parse_db(&reason)?,
5756 last_actor_name: col_opt_text(row, 7)?,
5857 unread: col_int(row, 8)? != 0,
5958 updated_at: col_text(row, 9)?,
@@ -689,6 +688,7 @@ async fn upsert_discussion_notification(
689688 #[cfg(test)]
690689 mod tests {
691690 use super::*;
691+ use crate::discussions::DiscussionReason;
692692 use crate::model::{User, Visibility};
693693
694694 struct Fixture {
crates/forge-core/src/store/edit_history_read.rsmodified+5 -9
@@ -10,15 +10,11 @@ pub enum EditTarget {
1010 ReviewComment,
1111 }
1212
13-impl EditTarget {
14- pub fn as_str(self) -> &'static str {
15- match self {
16- Self::Issue => "issue",
17- Self::Comment => "comment",
18- Self::ReviewComment => "review_comment",
19- }
20- }
21-}
13+string_enum!(EditTarget {
14+ Issue = "issue",
15+ Comment = "comment",
16+ ReviewComment = "review_comment",
17+});
2218
2319 #[derive(Debug, Clone, PartialEq)]
2420 pub struct EditVersion {
crates/forge-core/src/store/exports.rsmodified+8 -18
@@ -13,23 +13,11 @@ pub enum ExportState {
1313 Failed,
1414 }
1515
16-impl ExportState {
17- pub fn as_str(self) -> &'static str {
18- match self {
19- ExportState::Building => "building",
20- ExportState::Ready => "ready",
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-}
16+string_enum!(ExportState {
17+ Building = "building",
18+ Ready = "ready",
19+ Failed = "failed",
20+});
3321
3422 #[derive(Debug, Clone, PartialEq)]
3523 pub struct DataExport {
@@ -49,7 +37,9 @@ fn map_export(row: &Row) -> Result<DataExport> {
4937 Ok(DataExport {
5038 id: col_text(row, 0)?,
5139 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),
5343 size: col_int(row, 3)?,
5444 error: col_opt_text(row, 4)?,
5545 created_at: col_text(row, 5)?,
crates/forge-core/src/store/imports.rsmodified+10 -21
@@ -1,7 +1,8 @@
11 use turso::{Row, Value};
22
3+use super::issues::parse_db;
34 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;
56 use crate::time::now_stamp;
67
78 pub const MAX_EVENTS: i64 = 500;
@@ -14,29 +15,17 @@ pub enum ImportState {
1415 Failed,
1516 }
1617
17-impl ImportState {
18- pub fn as_str(self) -> &'static str {
19- match self {
20- ImportState::Queued => "queued",
21- ImportState::Running => "running",
22- ImportState::Done => "done",
23- ImportState::Failed => "failed",
24- }
25- }
18+string_enum!(ImportState {
19+ Queued = "queued",
20+ Running = "running",
21+ Done = "done",
22+ Failed = "failed",
23+});
2624
25+impl ImportState {
2726 pub fn is_finished(self) -> bool {
2827 matches!(self, ImportState::Done | ImportState::Failed)
2928 }
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- }
4029 }
4130
4231 #[derive(Debug, Clone, PartialEq)]
@@ -83,7 +72,7 @@ fn map_job(row: &Row) -> Result<ImportJob> {
8372 source: col_text(row, 3)?,
8473 source_ref: col_text(row, 4)?,
8574 options: col_text(row, 5)?,
86- state: ImportState::parse(&col_text(row, 6)?)?,
75+ state: parse_db(&col_text(row, 6)?)?,
8776 stage: col_text(row, 7)?,
8877 done: col_int(row, 8)?,
8978 total: col_int(row, 9)?,
crates/forge-core/src/store/issues.rsmodified+121 -72
@@ -163,6 +163,97 @@ pub(super) async fn insert_event(
163163 Ok(())
164164 }
165165
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+
166257 pub(super) async fn load_issue(conn: &Connection, issue_id: &str) -> Result<Issue> {
167258 fetch_opt(
168259 conn,
@@ -503,43 +594,38 @@ impl Store {
503594 reason: Option<StateReason>,
504595 data: Json,
505596 ) -> Result<bool> {
506- let mut data = event_data(data)?;
597+ let data = event_data(data)?;
507598 let conn = self.inner.conn.lock().await;
508599 let tx = conn.unchecked_transaction().await.map_err(db_err)?;
509- let outcome: Result<bool> = async {
510- let current = load_issue(&tx, issue_id).await?;
511- if current.state == state {
512- return Ok(false);
513- }
514- let now = now_stamp();
515- let (reason_value, closed_at, kind) = match state {
516- IssueState::Open => (None, None, "reopened"),
517- IssueState::Closed => {
518- if let Some(r) = reason {
519- data.insert("reason".into(), Json::from(r.as_str()));
520- }
521- (
522- reason.map(|r| r.as_str().to_string()),
523- Some(now.clone()),
524- "closed",
525- )
600+ let outcome = apply_issue_state(&tx, issue_id, actor_id, state, reason, data).await;
601+ finish(tx, outcome).await
602+ }
603+
604+ pub async fn comment_and_set_state(
605+ &self,
606+ issue_id: &str,
607+ author_id: &str,
608+ body: Option<&str>,
609+ change: Option<(IssueState, Option<StateReason>)>,
610+ ) -> Result<(Option<Comment>, bool)> {
611+ if let Some(body) = body {
612+ check_body(body)?;
613+ }
614+ let conn = self.inner.conn.lock().await;
615+ let tx = conn.unchecked_transaction().await.map_err(db_err)?;
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?
526625 }
626+ None => false,
527627 };
528- tx.execute(
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)
628+ Ok((comment, changed))
543629 }
544630 .await;
545631 finish(tx, outcome).await
@@ -597,47 +683,10 @@ impl Store {
597683 author_id: &str,
598684 body: &str,
599685 ) -> Result<Comment> {
600- validate_body(body)?;
601- if body.trim().is_empty() {
602- return Err(Error::Invalid("comment is empty".into()));
603- }
686+ check_body(body)?;
604687 let conn = self.inner.conn.lock().await;
605688 let tx = conn.unchecked_transaction().await.map_err(db_err)?;
606- let outcome: Result<Comment> = async {
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;
689+ let outcome = insert_comment(&tx, issue_id, author_id, body).await;
641690 finish(tx, outcome).await
642691 }
643692
crates/forge-core/src/store/labels.rsmodified+2 -2
@@ -4,7 +4,7 @@ use jiff::civil::Date;
44 use serde_json::json;
55 use turso::{Connection, Row};
66
7-use super::issues::insert_event;
7+use super::issues::{insert_event, parse_db};
88 use super::{
99 Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, finish, insert_err,
1010 new_id,
@@ -630,7 +630,7 @@ fn map_milestone(row: &Row) -> Result<Milestone> {
630630 title: col_text(row, 2)?,
631631 description: col_text(row, 3)?,
632632 due_on: col_opt_text(row, 4)?,
633- state: col_text(row, 5)?.parse()?,
633+ state: parse_db(&col_text(row, 5)?)?,
634634 created_at: col_text(row, 6)?,
635635 closed_at: col_opt_text(row, 7)?,
636636 open_issues: col_int(row, 8)?,
crates/forge-core/src/store/mail.rsmodified+8 -6
@@ -7,7 +7,7 @@ use super::{
77 use crate::error::{Error, Result};
88 use crate::mail::{
99 MailKind, MailPassword, MailSettings, MailSettingsUpdate, MailState, MailStatus, OutboxEntry,
10- OutgoingMail, Security, validate_settings,
10+ OutgoingMail, validate_settings,
1111 };
1212 use crate::secret;
1313
@@ -42,8 +42,9 @@ fn map_settings(row: &Row) -> Result<MailSettings> {
4242 Ok(MailSettings {
4343 host: col_text(row, 0)?,
4444 port: u16::try_from(port).map_err(|_| Error::Database("bad SMTP port".into()))?,
45- security: Security::parse(&security)
46- .ok_or_else(|| Error::Database(format!("unknown mail security {security}")))?,
45+ security: security
46+ .parse()
47+ .map_err(|_| Error::Database(format!("unknown mail security {security}")))?,
4748 username: col_text(row, 3)?,
4849 from_addr: col_text(row, 4)?,
4950 from_name: col_text(row, 5)?,
@@ -70,8 +71,9 @@ fn map_outbox(row: &Row) -> Result<OutboxEntry> {
7071 last_error: col_opt_text(row, 9)?,
7172 message_id: col_opt_text(row, 10)?,
7273 in_reply_to: col_opt_text(row, 11)?,
73- kind: MailKind::parse(&kind)
74- .ok_or_else(|| Error::Database(format!("unknown mail kind {kind}")))?,
74+ kind: kind
75+ .parse()
76+ .map_err(|_| Error::Database(format!("unknown mail kind {kind}")))?,
7577 user_id: col_opt_text(row, 13)?,
7678 lease_until: col_opt_text(row, 14)?,
7779 discarded_at: col_opt_text(row, 15)?,
@@ -389,7 +391,7 @@ mod tests {
389391 use std::time::Duration;
390392
391393 use super::*;
392- use crate::mail::MailState;
394+ use crate::mail::{MailState, Security};
393395 use crate::time::{now_stamp, stamp_after};
394396
395397 const KEY: [u8; 32] = [7u8; 32];
crates/forge-core/src/store/merge_queue.rsmodified+13 -1
@@ -1,5 +1,6 @@
11 use turso::Value;
22
3+use super::issues::parse_db;
34 use super::{Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, finish, new_id};
45 use crate::error::{Error, Result};
56 use crate::merge_queue::{QueueEntry, QueueState};
@@ -129,6 +130,17 @@ impl Store {
129130 Ok(out)
130131 }
131132
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+
132144 pub async fn queue_testing_on(&self, repo_id: &str, oid: &str) -> Result<Vec<QueueEntry>> {
133145 let conn = self.read_conn().await;
134146 fetch_all(
@@ -224,7 +236,7 @@ fn map_entry(row: &turso::Row) -> Result<QueueEntry> {
224236 merge_style: col_text(row, 5)?
225237 .parse::<MergeStyle>()
226238 .map_err(|e| Error::Database(e.to_string()))?,
227- state: col_text(row, 6)?.parse::<QueueState>()?,
239+ state: parse_db(&col_text(row, 6)?)?,
228240 seq: col_int(row, 7)?,
229241 enqueued_by: col_text(row, 8)?,
230242 enqueued_at: col_text(row, 9)?,
crates/forge-core/src/store/migrate.rsmodified+59 -0
@@ -1,8 +1,13 @@
1+use std::collections::HashSet;
2+
13 use turso::Connection;
24
35 use crate::error::{Error, Result};
6+use crate::names::normalize_name;
47 use crate::time::now_stamp;
58
9+const MILESTONE_TITLE_REPAIR: i64 = 76;
10+
611 pub const MIGRATIONS: &[(u32, &str)] = &[
712 (1, include_str!("../../migrations/0001_init.sql")),
813 (2, include_str!("../../migrations/0002_profile.sql")),
@@ -126,6 +131,14 @@ pub const MIGRATIONS: &[(u32, &str)] = &[
126131 74,
127132 include_str!("../../migrations/0074_failed_runs_dismissed.sql"),
128133 ),
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+ ),
129142 ];
130143
131144 pub fn latest_schema_version() -> u32 {
@@ -151,6 +164,9 @@ pub async fn migrate(conn: &Connection) -> Result<()> {
151164 }
152165 let tx = conn.unchecked_transaction().await.map_err(migration_err)?;
153166 tx.execute_batch(sql).await.map_err(migration_err)?;
167+ if version == MILESTONE_TITLE_REPAIR {
168+ repair_swapped_milestone_titles(&tx).await?;
169+ }
154170 tx.execute(
155171 "INSERT INTO schema_migrations (version, applied_at) VALUES (?1, ?2)",
156172 (version, now_stamp()),
@@ -163,6 +179,49 @@ pub async fn migrate(conn: &Connection) -> Result<()> {
163179 Ok(())
164180 }
165181
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+
166225 async fn applied_versions(conn: &Connection) -> Result<Vec<i64>> {
167226 let mut rows = conn
168227 .query("SELECT version FROM schema_migrations ORDER BY version", ())
crates/forge-core/src/store/mirrors.rsmodified+20 -6
@@ -1,5 +1,6 @@
11 use turso::{Row, Value};
22
3+use super::issues::parse_db;
34 use super::{
45 Store, col_bool, col_int, col_opt_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt,
56 finish, insert_err, missing_row, new_id, opt_text,
@@ -22,7 +23,7 @@ fn map_mirror(row: &Row) -> Result<Mirror> {
2223 Ok(Mirror {
2324 id: col_text(row, 0)?,
2425 repo_id: col_text(row, 1)?,
25- direction: col_text(row, 2)?.parse::<MirrorDirection>()?,
26+ direction: parse_db(&col_text(row, 2)?)?,
2627 url: col_text(row, 3)?,
2728 username: col_text(row, 4)?,
2829 has_secret: col_bool(row, 5)?,
@@ -239,12 +240,12 @@ impl Store {
239240 .await
240241 }
241242
242- pub async fn next_mirror_due(&self) -> Result<Option<String>> {
243+ pub async fn next_mirror_due(&self, now: &str) -> Result<Option<String>> {
243244 let conn = self.read_conn().await;
244245 fetch_opt(
245246 &conn,
246- "SELECT MIN(next_sync_at) FROM repo_mirrors WHERE enabled = 1",
247- (),
247+ "SELECT MIN(next_sync_at) FROM repo_mirrors WHERE enabled = 1 AND next_sync_at > ?1",
248+ (now.to_string(),),
248249 |row| col_opt_text(row, 0),
249250 )
250251 .await
@@ -557,7 +558,7 @@ mod tests {
557558 #[tokio::test]
558559 async fn due_mirrors_are_earliest_first_and_skip_disabled() {
559560 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);
561562 let late = store
562563 .create_mirror(&push(&repo, "https://late.example/r.git"))
563564 .await
@@ -602,10 +603,23 @@ mod tests {
602603 .await
603604 .unwrap();
604605 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(),
606611 Some("2020-01-01T00:00:00.000000000Z"),
607612 "a disabled mirror is ignored"
608613 );
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+ );
609623
610624 let now = now_stamp();
611625 let due: Vec<String> = store
crates/forge-core/src/store/mod.rsmodified+5 -41
@@ -623,7 +623,7 @@ impl Store {
623623 name.to_string(),
624624 normalize_name(name),
625625 description.to_string(),
626- visibility_str(visibility),
626+ visibility.as_str(),
627627 default_branch.to_string(),
628628 now_stamp(),
629629 fork_of.map(str::to_string),
@@ -701,7 +701,7 @@ impl Store {
701701 .await
702702 .map_err(db_err)?;
703703 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)?)?)),
705705 None => Ok(None),
706706 }
707707 }
@@ -725,7 +725,7 @@ impl Store {
725725 let conn = self.inner.conn.lock().await;
726726 conn.execute(
727727 "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()),
729729 )
730730 .await
731731 .map_err(db_err)?;
@@ -1160,7 +1160,7 @@ fn map_repo(row: &Row) -> Result<Repo> {
11601160 owner_name: col_text(row, 2)?,
11611161 name: col_text(row, 3)?,
11621162 description: col_text(row, 4)?,
1163- visibility: parse_visibility(&col_text(row, 5)?)?,
1163+ visibility: issues::parse_db(&col_text(row, 5)?)?,
11641164 default_branch: col_text(row, 6)?,
11651165 archived: col_bool(row, 7)?,
11661166 created_at: col_text(row, 8)?,
@@ -1168,42 +1168,6 @@ fn map_repo(row: &Row) -> Result<Repo> {
11681168 })
11691169 }
11701170
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-
12071171 impl Store {
12081172 pub async fn delete_repo(&self, repo_id: &str) -> Result<()> {
12091173 let conn = self.inner.conn.lock().await;
@@ -2205,7 +2169,7 @@ impl Store {
22052169 WHERE collaborators.repo_id = ?1 ORDER BY users.username_folded"
22062170 ),
22072171 (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)?)?)),
22092173 )
22102174 .await
22112175 }
crates/forge-core/src/store/notifications.rsmodified+8 -4
@@ -1,6 +1,7 @@
11 use turso::transaction::Transaction;
22 use turso::{Row, Value};
33
4+use super::issues::parse_db;
45 use super::repo_listing::VIEWER_ACCESS;
56 use super::{
67 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
3132 LEFT JOIN users a ON a.id = n.last_actor_id";
3233
3334 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:?}")))
3537 }
3638
3739 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:?}")))
3942 }
4043
4144 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:?}")))
4347 }
4448
4549 fn map_notification(row: &Row) -> Result<Notification> {
@@ -53,7 +57,7 @@ fn map_notification(row: &Row) -> Result<Notification> {
5357 number: col_int(row, 5)?,
5458 is_pull: kind == "pull",
5559 title: col_text(row, 7)?,
56- issue_state: col_text(row, 8)?.parse()?,
60+ issue_state: parse_db(&col_text(row, 8)?)?,
5761 reason: reason_from(&col_text(row, 9)?)?,
5862 last_activity: col_text(row, 10)?,
5963 last_actor_name: match row.get_value(11).map_err(db_err)? {
crates/forge-core/src/store/orgs.rsmodified+21 -43
@@ -1,9 +1,10 @@
11 use turso::{Connection, IntoParams};
22
33 use super::finish;
4+use super::issues::parse_db;
45 use super::{
56 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,
78 };
89 use crate::authz::max_role;
910 use crate::error::{Error, Result};
@@ -20,22 +21,10 @@ pub enum OrgMemberRole {
2021 Member,
2122 }
2223
23-impl OrgMemberRole {
24- pub fn as_str(self) -> &'static str {
25- match self {
26- OrgMemberRole::Owner => "owner",
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-}
24+string_enum!(OrgMemberRole {
25+ Owner = "owner",
26+ Member = "member",
27+});
3928
4029 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
4130 pub enum DefaultRepoRole {
@@ -44,24 +33,13 @@ pub enum DefaultRepoRole {
4433 Write,
4534 }
4635
47-impl DefaultRepoRole {
48- pub fn as_str(self) -> &'static str {
49- match self {
50- DefaultRepoRole::None => "none",
51- DefaultRepoRole::Read => "read",
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- }
36+string_enum!(DefaultRepoRole {
37+ None = "none",
38+ Read = "read",
39+ Write = "write",
40+});
6441
42+impl DefaultRepoRole {
6543 fn role(self) -> Option<Role> {
6644 match self {
6745 DefaultRepoRole::None => None,
@@ -96,7 +74,7 @@ fn map_team(row: &turso::Row) -> Result<Team> {
9674 org_id: col_text(row, 1)?,
9775 name: col_text(row, 2)?,
9876 description: col_text(row, 3)?,
99- role: parse_role(&col_text(row, 4)?)?,
77+ role: parse_db(&col_text(row, 4)?)?,
10078 all_repos: col_int(row, 5)? != 0,
10179 created_at: col_text(row, 6)?,
10280 })
@@ -141,7 +119,7 @@ async fn member_role(
141119 conn,
142120 "SELECT role FROM org_members WHERE org_id = ?1 AND user_id = ?2 LIMIT 1",
143121 (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)),
145123 )
146124 .await
147125 }
@@ -219,7 +197,7 @@ impl Store {
219197 (org_id.to_string(),),
220198 |row| {
221199 Ok(OrgSettings {
222- default_repo_role: DefaultRepoRole::parse(&col_text(row, 0)?)?,
200+ default_repo_role: parse_db(&col_text(row, 0)?)?,
223201 members_can_create_repos: col_int(row, 1)? != 0,
224202 })
225203 },
@@ -256,7 +234,7 @@ impl Store {
256234 ORDER BY (org_role = 'owner') DESC, username_folded"
257235 ),
258236 (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)?)?)),
260238 )
261239 .await
262240 }
@@ -371,7 +349,7 @@ impl Store {
371349 (SELECT org_id FROM org_members WHERE user_id = ?1) ORDER BY username_folded"
372350 ),
373351 (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)?)?)),
375353 )
376354 .await
377355 }
@@ -460,7 +438,7 @@ impl Store {
460438 display.clone(),
461439 folded,
462440 description.to_string(),
463- role_str(role).to_string(),
441+ role.as_str().to_string(),
464442 i64::from(all_repos),
465443 created_at.clone(),
466444 ),
@@ -497,7 +475,7 @@ impl Store {
497475 display,
498476 folded,
499477 description.to_string(),
500- role_str(role).to_string(),
478+ role.as_str().to_string(),
501479 i64::from(all_repos),
502480 ),
503481 )
@@ -657,7 +635,7 @@ impl Store {
657635 &conn,
658636 "SELECT default_repo_role FROM org_settings WHERE org_id = ?1 LIMIT 1",
659637 (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)),
661639 )
662640 .await?
663641 .ok_or(Error::NotFound)?
@@ -668,7 +646,7 @@ impl Store {
668646 WHERE t.org_id = ?1 AND tm.user_id = ?2 AND (t.all_repos = 1 OR EXISTS \
669647 (SELECT 1 FROM team_repos tr WHERE tr.team_id = t.id AND tr.repo_id = ?3))",
670648 (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)?),
672650 )
673651 .await?;
674652 Ok(team_roles
crates/forge-core/src/store/pulls.rsmodified+55 -45
@@ -9,7 +9,7 @@ use super::{
99 use crate::error::{Error, Result};
1010 use crate::issues::{IssueFilter, IssueListItem, IssueState, validate_body, validate_title};
1111 use crate::model::{Id, Repo};
12-use crate::pulls::{AutoMerge, MergeStyle, Mergeable, PullRequest};
12+use crate::pulls::{AutoMerge, MergeStyle, Mergeable, NewPull, PullRequest};
1313 use crate::time::now_stamp;
1414
1515 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) -
9090 }
9191
9292 impl Store {
93- #[allow(clippy::too_many_arguments)]
94- pub async fn create_pull(
95- &self,
96- repo_id: &str,
97- author_id: &str,
98- title: &str,
99- body: &str,
100- base_branch: &str,
101- head_repo_id: &str,
102- head_branch: &str,
103- head_oid: &str,
104- base_oid: &str,
105- ) -> Result<PullRequest> {
93+ pub async fn create_pull(&self, new: &NewPull<'_>) -> Result<PullRequest> {
94+ let NewPull {
95+ repo_id,
96+ author_id,
97+ title,
98+ body,
99+ base_branch,
100+ head_repo_id,
101+ head_branch,
102+ head_oid,
103+ base_oid,
104+ } = *new;
106105 let title = validate_title(title)?;
107106 validate_body(body)?;
108107 let conn = self.inner.conn.lock().await;
@@ -167,6 +166,17 @@ impl Store {
167166 finish(tx, outcome).await
168167 }
169168
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+
170180 pub async fn pull_by_number(&self, repo_id: &str, number: i64) -> Result<Option<PullRequest>> {
171181 let conn = self.read_conn().await;
172182 fetch_opt(
@@ -608,17 +618,17 @@ mod tests {
608618 title: &str,
609619 ) -> PullRequest {
610620 fx.store
611- .create_pull(
612- &repo.id,
613- &fx.tahinli.id,
621+ .create_pull(&NewPull {
622+ repo_id: &repo.id,
623+ author_id: &fx.tahinli.id,
614624 title,
615- "",
616- "main",
617- head_repo,
625+ body: "",
626+ base_branch: "main",
627+ head_repo_id: head_repo,
618628 head_branch,
619- &"a".repeat(40),
620- &"b".repeat(40),
621- )
629+ head_oid: &"a".repeat(40),
630+ base_oid: &"b".repeat(40),
631+ })
622632 .await
623633 .unwrap()
624634 }
@@ -898,17 +908,17 @@ mod tests {
898908 let first = open_pull(&fx, &repo, &repo.id, "feature", "first").await;
899909 let second = fx
900910 .store
901- .create_pull(
902- &repo.id,
903- &fx.bob.id,
904- "second",
905- "",
906- "main",
907- &repo.id,
908- "feature",
909- &"c".repeat(40),
910- &"b".repeat(40),
911- )
911+ .create_pull(&NewPull {
912+ repo_id: &repo.id,
913+ author_id: &fx.bob.id,
914+ title: "second",
915+ body: "",
916+ base_branch: "main",
917+ head_repo_id: &repo.id,
918+ head_branch: "feature",
919+ head_oid: &"c".repeat(40),
920+ base_oid: &"b".repeat(40),
921+ })
912922 .await;
913923 match second {
914924 Err(Error::Conflict(msg)) => assert!(
@@ -1314,17 +1324,17 @@ mod tests {
13141324 let incoming = open_pull(&fx, &source, &fork.id, "topic", "incoming").await;
13151325 let outgoing = fx
13161326 .store
1317- .create_pull(
1318- &fork.id,
1319- &fx.bob.id,
1320- "outgoing",
1321- "",
1322- "main",
1323- &source.id,
1324- "main",
1325- &"a".repeat(40),
1326- &"b".repeat(40),
1327- )
1327+ .create_pull(&NewPull {
1328+ repo_id: &fork.id,
1329+ author_id: &fx.bob.id,
1330+ title: "outgoing",
1331+ body: "",
1332+ base_branch: "main",
1333+ head_repo_id: &source.id,
1334+ head_branch: "main",
1335+ head_oid: &"a".repeat(40),
1336+ base_oid: &"b".repeat(40),
1337+ })
13281338 .await
13291339 .unwrap();
13301340
crates/forge-core/src/store/reactions.rsmodified+3 -3
@@ -42,7 +42,7 @@ impl Store {
4242 kind.as_str().to_string(),
4343 target_id.to_string(),
4444 user_id.to_string(),
45- reaction.name().to_string(),
45+ reaction.as_str().to_string(),
4646 ),
4747 )
4848 .await
@@ -57,7 +57,7 @@ impl Store {
5757 kind.as_str().to_string(),
5858 target_id.to_string(),
5959 user_id.to_string(),
60- reaction.name().to_string(),
60+ reaction.as_str().to_string(),
6161 now_stamp(),
6262 ),
6363 )
@@ -106,7 +106,7 @@ impl Store {
106106 )
107107 .await?;
108108 for (target, emoji, user_id, username) in rows {
109- let Some(reaction) = Reaction::parse(&emoji) else {
109+ let Ok(reaction) = emoji.parse::<Reaction>() else {
110110 continue;
111111 };
112112 grouped
crates/forge-core/src/store/replication.rsmodified+76 -1
@@ -2,7 +2,7 @@ use turso::{Row, Value};
22
33 use super::{Store, col_opt_text, col_text, db_err, fetch_all, fetch_opt};
44 use crate::error::Result;
5-use crate::time::now_stamp;
5+use crate::time::{now_stamp, stamp_to_unix};
66
77 pub const DB_SUBJECT: &str = "db";
88
@@ -17,6 +17,36 @@ pub struct ReplicationStatus {
1717 pub refs_sha256: Option<String>,
1818 }
1919
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+
2050 fn map_status(row: &Row) -> Result<ReplicationStatus> {
2151 Ok(ReplicationStatus {
2252 subject: col_text(row, 0)?,
@@ -190,4 +220,49 @@ mod tests {
190220 assert_eq!(healed.last_error, None, "success clears the error");
191221 assert_eq!(healed.refs_sha256.as_deref(), Some("abc"), "refs hash kept");
192222 }
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+ }
193268 }
crates/forge-core/src/store/reviews.rsmodified+13 -12
@@ -36,7 +36,7 @@ fn map_review(row: &Row) -> Result<Review> {
3636 created_at: col_text(row, 8)?,
3737 submitted_at: col_opt_text(row, 9)?,
3838 dismissed_from: col_opt_text(row, 10)?
39- .map(|state| state.parse::<ReviewState>())
39+ .map(|state| parse_db(&state))
4040 .transpose()?,
4141 })
4242 }
@@ -803,6 +803,7 @@ impl Store {
803803 mod tests {
804804 use super::*;
805805 use crate::model::{User, Visibility};
806+ use crate::pulls::NewPull;
806807
807808 fn oid(c: char) -> String {
808809 c.to_string().repeat(40)
@@ -847,17 +848,17 @@ mod tests {
847848 let head = format!("feature-{topic}");
848849 let pull = fx
849850 .store
850- .create_pull(
851- &fx.repo_id,
852- &fx.tahinli.id,
853- "change",
854- "",
855- "main",
856- &fx.repo_id,
857- &head,
858- &oid('a'),
859- &oid('b'),
860- )
851+ .create_pull(&NewPull {
852+ repo_id: &fx.repo_id,
853+ author_id: &fx.tahinli.id,
854+ title: "change",
855+ body: "",
856+ base_branch: "main",
857+ head_repo_id: &fx.repo_id,
858+ head_branch: &head,
859+ head_oid: &oid('a'),
860+ base_oid: &oid('b'),
861+ })
861862 .await
862863 .unwrap();
863864 pull.issue.id.clone()
crates/forge-core/src/store/shell_activity.rsmodified+3 -2
@@ -2,6 +2,7 @@ use std::time::Duration;
22
33 use turso::{Row, Value};
44
5+use super::issues::parse_db;
56 use super::needs::{failing_runs_params, failing_runs_sql};
67 use super::notifications::{readable_params, readable_repo};
78 use super::{Store, col_int, col_opt_text, col_text, fetch_all};
@@ -72,7 +73,7 @@ fn map_actor_run(row: &Row) -> Result<ActorRun> {
7273 repo: col_text(row, 1)?,
7374 number: col_int(row, 2)?,
7475 git_ref: col_text(row, 3)?,
75- state: col_text(row, 4)?.parse::<RunState>()?,
76+ state: parse_db(&col_text(row, 4)?)?,
7677 created_at: col_text(row, 5)?,
7778 finished_at: col_opt_text(row, 6)?,
7879 jobs_total: count_from(col_int(row, 7)?)?,
@@ -126,7 +127,7 @@ impl Store {
126127 let conn = self.read_conn().await;
127128 fetch_all(&conn, &sql, params, |row| {
128129 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(|_| {
130131 Error::Database(format!("unknown notification reason {reason_text:?}"))
131132 })?;
132133 Ok(WaitingItem {
crates/forge-core/src/store/signatures.rsmodified+14 -51
@@ -1,8 +1,8 @@
11 use std::collections::HashMap;
2-use std::str::FromStr;
32
43 use turso::Value;
54
5+use super::issues::parse_db;
66 use super::{
77 SSH_KEY_COLS, Store, col_opt_text, col_text, db_err, fetch_all, fetch_opt, insert_err,
88 map_ssh_key, new_id,
@@ -46,53 +46,18 @@ pub enum SigKind {
4646 Gpg,
4747 }
4848
49-impl SigStatus {
50- pub fn as_str(self) -> &'static str {
51- match self {
52- SigStatus::Verified => "verified",
53- SigStatus::Unverified => "unverified",
54- SigStatus::Unsigned => "unsigned",
55- SigStatus::UnknownKey => "unknown_key",
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-}
49+string_enum!(SigStatus {
50+ Verified = "verified",
51+ Unverified = "unverified",
52+ Unsigned = "unsigned",
53+ UnknownKey = "unknown_key",
54+ Bad = "bad",
55+});
7556
76-impl SigKind {
77- pub fn as_str(self) -> &'static str {
78- match self {
79- SigKind::Ssh => "ssh",
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-}
57+string_enum!(SigKind {
58+ Ssh = "ssh",
59+ Gpg = "gpg",
60+});
9661
9762 fn map_gpg_key(row: &turso::Row) -> Result<GpgKey> {
9863 let emails_json = col_text(row, 4)?;
@@ -110,10 +75,8 @@ fn map_gpg_key(row: &turso::Row) -> Result<GpgKey> {
11075
11176 fn map_cached(row: &turso::Row) -> Result<(String, CachedSig)> {
11277 let oid = col_text(row, 0)?;
113- let status = col_text(row, 1)?.parse::<SigStatus>()?;
114- let kind = col_opt_text(row, 2)?
115- .map(|k| k.parse::<SigKind>())
116- .transpose()?;
78+ let status = parse_db(&col_text(row, 1)?)?;
79+ let kind = col_opt_text(row, 2)?.map(|k| parse_db(&k)).transpose()?;
11780 Ok((
11881 oid,
11982 CachedSig {
crates/forge-core/src/store/snippets.rsmodified+11 -37
@@ -1,6 +1,7 @@
11 use serde::{Deserialize, Serialize};
22 use turso::Connection;
33
4+use super::issues::parse_db;
45 use super::{Store, col_int, col_text, db_err, fetch_all, fetch_opt, finish, new_id};
56 use crate::error::{Error, Result};
67 use crate::time::now_stamp;
@@ -25,23 +26,14 @@ impl SnippetVisibility {
2526 SnippetVisibility::Unlisted,
2627 SnippetVisibility::Private,
2728 ];
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- }
4329 }
4430
31+string_enum!(SnippetVisibility {
32+ Public = "public",
33+ Unlisted = "unlisted",
34+ Private = "private",
35+});
36+
4537 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
4638 pub struct SnippetFile {
4739 pub name: String,
@@ -174,8 +166,7 @@ fn map_snippet(row: &turso::Row) -> Result<Snippet> {
174166 owner_name: col_text(row, 2)?,
175167 title: col_text(row, 3)?,
176168 description: col_text(row, 4)?,
177- visibility: SnippetVisibility::parse(&visibility)
178- .ok_or_else(|| Error::Database(format!("unknown snippet visibility {visibility}")))?,
169+ visibility: parse_db(&visibility)?,
179170 created_at: col_text(row, 6)?,
180171 updated_at: col_text(row, 7)?,
181172 files: Vec::new(),
@@ -188,8 +179,7 @@ fn summary_row(row: &turso::Row) -> Result<SnippetSummary> {
188179 id: col_text(row, 0)?,
189180 owner_name: col_text(row, 1)?,
190181 title: col_text(row, 2)?,
191- visibility: SnippetVisibility::parse(&visibility)
192- .ok_or_else(|| Error::Database(format!("unknown snippet visibility {visibility}")))?,
182+ visibility: parse_db(&visibility)?,
193183 updated_at: col_text(row, 4)?,
194184 file_count: u64::try_from(col_int(row, 5)?).unwrap_or(0),
195185 })
@@ -487,25 +477,9 @@ mod tests {
487477 #[test]
488478 fn visibility_names_round_trip() {
489479 for v in SnippetVisibility::ALL {
490- assert_eq!(
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- );
480+ assert_eq!(v.as_str().parse::<SnippetVisibility>().ok(), Some(v));
507481 }
508- assert_eq!(SnippetVisibility::parse("secret"), None);
482+ assert!("secret".parse::<SnippetVisibility>().is_err());
509483 }
510484
511485 #[tokio::test]
crates/forge-core/src/store/webhooks.rsmodified+6 -13
@@ -2,6 +2,7 @@ use std::time::Duration;
22
33 use turso::{Connection, Row, Value};
44
5+use super::issues::parse_db;
56 use super::{
67 Store, col_blob, col_bool, col_int, col_opt_int, col_opt_text, col_text, db_err, fetch_all,
78 fetch_opt, finish, new_id, opt_int_value, opt_text,
@@ -26,10 +27,8 @@ fn map_webhook(row: &Row) -> Result<Webhook> {
2627 .map_err(|e| Error::Database(format!("bad webhook events JSON: {e}")))?;
2728 let events = names
2829 .iter()
29- .map(|name| {
30- WebhookEvent::parse(name)
31- .ok_or_else(|| Error::Database(format!("unknown webhook event {name:?}")))
32- })
30+ .map(String::as_str)
31+ .map(parse_db)
3332 .collect::<Result<Vec<_>>>()?;
3433 Ok(Webhook {
3534 id: col_text(row, 0)?,
@@ -49,13 +48,11 @@ fn map_delivery(row: &Row) -> Result<Delivery> {
4948 id: col_text(row, 0)?,
5049 hook_id: col_text(row, 1)?,
5150 guid: col_text(row, 2)?,
52- event: WebhookEvent::parse(&event)
53- .ok_or_else(|| Error::Database(format!("unknown webhook event {event:?}")))?,
51+ event: parse_db(&event)?,
5452 action: col_text(row, 4)?,
5553 request_headers: col_text(row, 5)?,
5654 request_body: col_text(row, 6)?,
57- state: DeliveryState::parse(&state)
58- .ok_or_else(|| Error::Database(format!("unknown delivery state {state:?}")))?,
55+ state: parse_db(&state)?,
5956 attempt: u32::try_from(col_int(row, 8)?)
6057 .map_err(|_| Error::Database("negative delivery attempt count".into()))?,
6158 next_attempt_at: col_opt_text(row, 9)?,
@@ -297,11 +294,7 @@ impl Store {
297294 let conn = self.read_conn().await;
298295 fetch_all(&conn, &sql, (repo_id.to_string(),), |row| {
299296 let last = match col_opt_text(row, 7)? {
300- Some(s) => Some((
301- DeliveryState::parse(&s)
302- .ok_or_else(|| Error::Database(format!("unknown delivery state {s:?}")))?,
303- col_text(row, 8)?,
304- )),
297+ Some(s) => Some((parse_db(&s)?, col_text(row, 8)?)),
305298 None => None,
306299 };
307300 Ok((map_webhook(row)?, last))
crates/forge-core/src/time.rsmodified+36 -6
@@ -1,5 +1,6 @@
11 use std::time::Duration;
22
3+use jiff::{Timestamp, tz::TimeZone};
34 use time::{
45 OffsetDateTime, SignedDuration,
56 format_description::{FormatItem, well_known::Rfc3339},
@@ -17,14 +18,10 @@ pub fn now_stamp() -> String {
1718 format_stamp(OffsetDateTime::now_utc())
1819 }
1920
20-pub fn unix_now() -> u64 {
21+pub fn now_unix() -> i64 {
2122 std::time::SystemTime::now()
2223 .duration_since(std::time::UNIX_EPOCH)
23- .map_or(0, |d| d.as_secs())
24-}
25-
26-pub fn now_unix() -> i64 {
27- i64::try_from(unix_now()).unwrap_or(0)
24+ .map_or(0, |d| i64::try_from(d.as_secs()).unwrap_or(0))
2825 }
2926
3027 pub fn stamp_after(after: Duration) -> String {
@@ -49,6 +46,39 @@ pub fn stamp_to_unix(stamp: &str) -> Option<i64> {
4946 .map(OffsetDateTime::unix_timestamp)
5047 }
5148
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+
5282 const MIN_SLEEP: Duration = Duration::from_secs(1);
5383
5484 pub fn sleep_until(next_due: Option<&str>, now: OffsetDateTime, backstop: Duration) -> Duration {
crates/forge-core/src/totp.rsmodified+2 -2
@@ -34,8 +34,8 @@ pub fn hotp(secret: &[u8], counter: u64) -> u32 {
3434 binary % 10u32.pow(DIGITS as u32)
3535 }
3636
37-pub fn step_for(unix_secs: u64) -> u64 {
38- unix_secs / STEP_SECS
37+pub fn step_for(unix_secs: i64) -> u64 {
38+ unix_secs.unsigned_abs() / STEP_SECS
3939 }
4040
4141 pub fn code_at(secret: &[u8], step: u64) -> String {
crates/forge-core/src/webhooks.rsmodified+18 -38
@@ -23,26 +23,20 @@ impl WebhookEvent {
2323 WebhookEvent::Ping,
2424 WebhookEvent::Release,
2525 ];
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- }
4426 }
4527
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+
4640 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
4741 pub enum DeliveryState {
4842 Pending,
@@ -51,26 +45,12 @@ pub enum DeliveryState {
5145 GaveUp,
5246 }
5347
54-impl DeliveryState {
55- pub fn as_str(self) -> &'static str {
56- match self {
57- DeliveryState::Pending => "pending",
58- DeliveryState::Ok => "ok",
59- DeliveryState::Failed => "failed",
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-}
48+string_enum!(DeliveryState {
49+ Pending = "pending",
50+ Ok = "ok",
51+ Failed = "failed",
52+ GaveUp = "gave_up",
53+});
7454
7555 #[derive(Debug, Clone, PartialEq, Eq)]
7656 pub struct Webhook {
crates/forge-e2e/tests/e2e/account_mail_e2e.rsmodified+3 -3
@@ -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};
22 use std::fs;
33 use std::path::{Path, PathBuf};
44 use std::time::Duration;
@@ -120,7 +120,7 @@ async fn forgot(http: &Http, email: &str) -> Resp {
120120 async fn reset_link_sets_a_new_password_once() {
121121 let root = tempfile::tempdir().expect("temp dir");
122122 let dir = root.path().to_path_buf();
123- let ports = pick_ports();
123+ let (_, ports) = provision(&dir, LOG_TRANSPORT, &[]);
124124 seed(&dir).await;
125125 let (_server, ports) = launch_with(&dir, ports, LOG_TRANSPORT).await;
126126 let http = Http::new(ports.http);
@@ -168,7 +168,7 @@ async fn reset_link_sets_a_new_password_once() {
168168 async fn an_unverified_address_gets_no_reset_mail_and_the_same_answer() {
169169 let root = tempfile::tempdir().expect("temp dir");
170170 let dir = root.path().to_path_buf();
171- let ports = pick_ports();
171+ let (_, ports) = provision(&dir, LOG_TRANSPORT, &[]);
172172 seed(&dir).await;
173173 let (_server, ports) = launch_with(&dir, ports, LOG_TRANSPORT).await;
174174 let http = Http::new(ports.http);
crates/forge-e2e/tests/e2e/advisories_e2e.rsmodified+15 -86
@@ -1,15 +1,12 @@
11 use crate::common::{
2- Http, Resp, Server, input_value, launch_with, login, pick_ports, run_admin, tool_on_path,
3- write_config_with,
2+ BOB_CMD, Http, PW, Resp, Server, TAHINLI_CMD, boot_forge, commit_file, create_token, csrf_for,
3+ git_text, login, temp_dir, tool_on_path,
44 };
55 use std::fs;
66 use std::io::{Cursor, Write};
7-use std::path::{Path, PathBuf};
8-use std::process::{Command, Output};
7+use std::path::PathBuf;
98 use std::time::{Duration, Instant};
109
11-const TAHINLI_PW: &str = "tahinli-password-123";
12-const BOB_PW: &str = "bob-password-123";
1310 const ADVISORIES_TOML: &str = "\n[advisories]\nenabled = true\necosystems = [\"crates.io\"]\n";
1411 const SCAN_TIMEOUT: Duration = Duration::from_secs(30);
1512
@@ -27,36 +24,6 @@ const OSV_RECORD: &str = r#"{
2724 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";
2825 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";
2926
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-
6027 fn dump_zip() -> Vec<u8> {
6128 let mut buf = Cursor::new(Vec::new());
6229 {
@@ -82,20 +49,13 @@ async fn boot() -> Booted {
8249 if !tool_on_path("git") {
8350 panic!("`git` was not found on PATH");
8451 }
85- let root = tempfile::Builder::new()
86- .prefix("adv2e")
87- .tempdir_in("/tmp")
88- .expect("temp dir");
52+ let root = temp_dir("adv2e");
8953 let dir = root.path().to_path_buf();
9054 let dump_dir = dir.join("advisories").join("crates.io");
9155 fs::create_dir_all(&dump_dir).expect("dump dir");
9256 fs::write(dump_dir.join("all.zip"), dump_zip()).expect("write dump");
9357
94- let ports = pick_ports();
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;
58+ let (server, ports) = boot_forge(&dir, ADVISORIES_TOML, &[TAHINLI_CMD, BOB_CMD]).await;
9959 Booted {
10060 _server: server,
10161 _root: root,
@@ -105,37 +65,8 @@ async fn boot() -> Booted {
10565 }
10666 }
10767
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-
13568 async fn new_repo(http: &Http, session: &str, name: &str) {
136- let page = http.get_cookie("/new", session).await;
137- assert_eq!(page.status, 200, "GET /new");
138- let csrf = input_value(&page.body, "csrf");
69+ let csrf = csrf_for(http, "/new", session).await;
13970 let res = http
14071 .post_form(
14172 "/new",
@@ -173,9 +104,7 @@ async fn wait_for_text(http: &Http, session: &str, text: &str) -> String {
173104 }
174105
175106 async fn post_alert_action(http: &Http, session: &str, action: &str) -> Resp {
176- let page = security_page(http, session).await;
177- assert_eq!(page.status, 200, "GET security page");
178- let csrf = input_value(&page.body, "csrf");
107+ let csrf = csrf_for(http, "/tahinli/app/security", session).await;
179108 http.post_form(
180109 &format!("/tahinli/app/security/{action}"),
181110 &[
@@ -193,8 +122,8 @@ async fn post_alert_action(http: &Http, session: &str, action: &str) -> Resp {
193122 #[tokio::test]
194123 async fn advisory_alert_opens_on_push_and_follows_dismiss_reopen_and_fix() {
195124 let b = boot().await;
196- let tahinli = login(&b.http, "tahinli", TAHINLI_PW).await;
197- let token = create_token(&b.http, &tahinli).await;
125+ let tahinli = login(&b.http, "tahinli", PW).await;
126+ let token = create_token(&b.http, &tahinli, "advisory-token").await;
198127 new_repo(&b.http, &tahinli, "app").await;
199128
200129 let work = b.dir.join("app-work");
@@ -202,12 +131,12 @@ async fn advisory_alert_opens_on_push_and_follows_dismiss_reopen_and_fix() {
202131 "http://tahinli:{token}@127.0.0.1:{}/tahinli/app.git",
203132 b.port
204133 );
205- git(
134+ git_text(
206135 &b.dir,
207136 &["clone", "-q", &remote, work.to_str().expect("utf-8 path")],
208137 );
209- commit_lock(&work, LOCK_OLD, "lock demo 1.0.0");
210- git(&work, &["push", "-q", "origin", "HEAD:refs/heads/main"]);
138+ commit_file(&work, "Cargo.lock", LOCK_OLD, "lock demo 1.0.0");
139+ git_text(&work, &["push", "-q", "origin", "HEAD:refs/heads/main"]);
211140
212141 let page = wait_for_text(&b.http, &tahinli, "RUSTSEC-TEST-0001").await;
213142 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() {
222151 assert_eq!(reopened.status, 303, "reopen: {}", reopened.body);
223152 wait_for_text(&b.http, &tahinli, ">Open</span>").await;
224153
225- let bob = login(&b.http, "bob", BOB_PW).await;
154+ let bob = login(&b.http, "bob", PW).await;
226155 let refused = security_page(&b.http, &bob).await;
227156 assert_eq!(refused.status, 404, "a reader without Write gets 404");
228157
229- commit_lock(&work, LOCK_FIXED, "lock demo 2.0.0");
230- git(&work, &["push", "-q", "origin", "HEAD:refs/heads/main"]);
158+ commit_file(&work, "Cargo.lock", LOCK_FIXED, "lock demo 2.0.0");
159+ git_text(&work, &["push", "-q", "origin", "HEAD:refs/heads/main"]);
231160 wait_for_text(&b.http, &tahinli, ">Fixed</span>").await;
232161 }
crates/forge-e2e/tests/e2e/branch_protection_e2e.rsmodified+8 -116
@@ -1,19 +1,12 @@
11 use crate::common::{
2- Http, Ports, Server, describe, input_value, launch, login, pick_ports, relaunch, run_admin,
3- tool_on_path, write_config,
2+ Http, PW, Ports, Server, TAHINLI_CMD, boot_forge, commit_file, create_repo, create_token,
3+ describe, git, login, ok, path_str, relaunch, temp_dir, tool_on_path,
44 };
5-use std::fs;
65 use std::path::{Path, PathBuf};
7-use std::process::{Command, Output};
6+use std::process::Output;
87
98 use forge_core::Store;
109
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-
1710 fn rejected(out: &Output, what: &str) -> String {
1811 assert!(
1912 !out.status.success(),
@@ -23,51 +16,6 @@ fn rejected(out: &Output, what: &str) -> String {
2316 describe(out)
2417 }
2518
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-
7119 fn remote_sha(repo: &Path, reference: &str) -> String {
7220 let out = git(repo, &["ls-remote", "origin", reference]);
7321 ok(&out, "ls-remote");
@@ -78,55 +26,6 @@ fn remote_sha(repo: &Path, reference: &str) -> String {
7826 .to_owned()
7927 }
8028
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-
13029 struct Ctx {
13130 dir: PathBuf,
13231 config: PathBuf,
@@ -171,26 +70,19 @@ async fn branch_protection_end_to_end() {
17170 return;
17271 }
17372
174- let root = tempfile::Builder::new()
175- .prefix("fbp")
176- .tempdir_in("/tmp")
177- .expect("temp dir");
73+ let root = temp_dir("fbp");
17874 let dir = root.path().to_path_buf();
179- let ports = pick_ports();
180- let config = write_config(&dir, ports);
181- run_admin(&config, "tahinli", &["--admin"], TAHINLI_PW);
182-
183- let (server, ports) = launch(&dir, ports).await;
75+ let (server, ports) = boot_forge(&dir, "", &[TAHINLI_CMD]).await;
18476 let ctx = Ctx {
18577 log: dir.join("serve.log"),
18678 http: Http::new(ports.http),
18779 ports,
188- config,
80+ config: dir.join("forge.toml"),
18981 dir,
19082 };
191- let tahinli = login(&ctx.http, "tahinli", TAHINLI_PW).await;
83+ let tahinli = login(&ctx.http, "tahinli", PW).await;
19284 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;
19486
19587 drop(server);
19688 let repo_id = {
crates/forge-e2e/tests/e2e/browse_e2e.rsmodified+38 -89
@@ -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+};
25 use std::fs;
36 use std::path::Path;
4-use std::process::{Command, Output};
57 use std::time::Duration;
68
79 use reqwest::header::{
@@ -9,7 +11,6 @@ use reqwest::header::{
911 LOCATION, SET_COOKIE, X_CONTENT_TYPE_OPTIONS,
1012 };
1113
12-const TAHINLI_PW: &str = "tahinli-password-123";
1314 const PNG: &[u8] = b"\x89PNG\r\n\x1a\n\x00\x00\x00\x00IEND\xaeB`\x82";
1415
1516 struct Resp {
@@ -70,6 +71,10 @@ impl Http {
7071 .await
7172 }
7273
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+
7378 async fn send(&self, req: reqwest::RequestBuilder, cookie: Option<&str>) -> Resp {
7479 let req = match cookie {
7580 Some(cookie) => req.header(COOKIE, cookie),
@@ -95,22 +100,6 @@ fn cookie_named(resp: &Resp, suffix: &str) -> Option<String> {
95100 })
96101 }
97102
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-
114103 fn assert_latest_bar(body: &str, what: &str, subject: &str, oid: &str, count: &str) {
115104 assert_eq!(
116105 element_texts(body, ".head-sub").len(),
@@ -132,35 +121,6 @@ fn assert_latest_bar(body: &str, what: &str, subject: &str, oid: &str, count: &s
132121 );
133122 }
134123
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-
164124 fn write_fixtures(work: &Path) {
165125 fs::create_dir_all(work.join("src")).expect("create src");
166126 fs::write(
@@ -190,12 +150,6 @@ fn commit_all(repo: &Path, message: &str) {
190150 );
191151 }
192152
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-
199153 fn push_fixtures(dir: &Path, url: &str, work: &Path) -> String {
200154 ok(&git(dir, &["clone", url, path_str(work)]), "https clone");
201155 write_fixtures(work);
@@ -297,13 +251,14 @@ async fn browse_end_to_end() {
297251 return;
298252 }
299253
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;
301256 let dir = root.path().to_path_buf();
302257 let http = Http::new(ports.http);
303258 let raw = Http::new(ports.content);
304259 let raw_base = raw.base.clone();
305260
306- let tahinli = login(&http, "tahinli", TAHINLI_PW).await;
261+ let tahinli = login(&http, "tahinli", PW).await;
307262 let token = create_token(&http, &tahinli, "browse-token").await;
308263 create_repo(&http, &tahinli, "pub", "public").await;
309264 create_repo(&http, &tahinli, "priv", "private").await;
@@ -556,19 +511,6 @@ async fn browse_end_to_end() {
556511 assert_no_cookie(&login_page, "raw /login");
557512 }
558513
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-
572514 async fn next_chunk(res: &mut reqwest::Response) -> Option<String> {
573515 let chunk = tokio::time::timeout(Duration::from_secs(2), res.chunk())
574516 .await
@@ -584,11 +526,12 @@ async fn code_view_stream_follows_pushes() {
584526 return;
585527 }
586528
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;
588531 let dir = root.path().to_path_buf();
589532 let http = Http::new(ports.http);
590533
591- let tahinli = login(&http, "tahinli", TAHINLI_PW).await;
534+ let tahinli = login(&http, "tahinli", PW).await;
592535 let token = create_token(&http, &tahinli, "live-token").await;
593536 create_repo(&http, &tahinli, "pub", "public").await;
594537 create_repo(&http, &tahinli, "priv", "private").await;
@@ -627,7 +570,7 @@ async fn code_view_stream_follows_pushes() {
627570 "a commit page does not follow a branch"
628571 );
629572
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;
631574 assert_eq!(stream.status().as_u16(), 200);
632575 assert_eq!(
633576 stream.headers().get(CONTENT_TYPE).unwrap(),
@@ -675,13 +618,13 @@ async fn code_view_stream_follows_pushes() {
675618 assert!(deleted.contains("event: changed"), "{deleted}");
676619
677620 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;
679622 assert_eq!(
680623 anonymous.status().as_u16(),
681624 404,
682625 "private stream without a session"
683626 );
684- let member = open_stream(&http, private, Some(tahinli.as_str())).await;
627+ let member = http.stream(private, Some(tahinli.as_str())).await;
685628 assert_eq!(
686629 member.status().as_u16(),
687630 200,
@@ -708,10 +651,11 @@ async fn issue_streams_follow_writes() {
708651 return;
709652 }
710653
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;
712656 let http = Http::new(ports.http);
713657
714- let tahinli = login(&http, "tahinli", TAHINLI_PW).await;
658+ let tahinli = login(&http, "tahinli", PW).await;
715659 create_repo(&http, &tahinli, "pub", "public").await;
716660 create_repo(&http, &tahinli, "priv", "private").await;
717661
@@ -722,7 +666,7 @@ async fn issue_streams_follow_writes() {
722666 .contains(r#"data-live="/tahinli/pub/issues/live""#),
723667 "the list follows the repo"
724668 );
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;
726670 assert_eq!(list.status().as_u16(), 200);
727671
728672 let new_page = http.get("/tahinli/pub/issues/new", Some(&tahinli)).await;
@@ -736,7 +680,7 @@ async fn issue_streams_follow_writes() {
736680 .await;
737681 assert_changed(&mut list, "creating an issue").await;
738682
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;
740684 assert_eq!(issue.status().as_u16(), 200);
741685 let view = http.get("/tahinli/pub/issues/1", Some(&tahinli)).await;
742686 assert!(
@@ -808,19 +752,21 @@ async fn issue_streams_follow_writes() {
808752 assert_changed(&mut issue, what).await;
809753 }
810754
811- let anonymous = open_stream(&http, "/tahinli/priv/issues/live", None).await;
755+ let anonymous = http.stream("/tahinli/priv/issues/live", None).await;
812756 assert_eq!(
813757 anonymous.status().as_u16(),
814758 404,
815759 "private list without a session"
816760 );
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;
818762 assert_eq!(
819763 anonymous_issue.status().as_u16(),
820764 404,
821765 "private issue without a session"
822766 );
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;
824770 assert_eq!(member.status().as_u16(), 200, "private list for its owner");
825771 }
826772
@@ -831,11 +777,12 @@ async fn browsing_pages_stream_their_changes() {
831777 return;
832778 }
833779
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;
835782 let dir = root.path().to_path_buf();
836783 let http = Http::new(ports.http);
837784
838- let tahinli = login(&http, "tahinli", TAHINLI_PW).await;
785+ let tahinli = login(&http, "tahinli", PW).await;
839786 let token = create_token(&http, &tahinli, "live-pages-token").await;
840787 create_repo(&http, &tahinli, "pub", "public").await;
841788 let pub_url = format!(
@@ -848,13 +795,15 @@ async fn browsing_pages_stream_their_changes() {
848795 "/notifications/events",
849796 "/notifications/events?all=1&user=tahinli",
850797 ] {
851- let anonymous = open_stream(&http, path, None).await;
798+ let anonymous = http.stream(path, None).await;
852799 assert_eq!(anonymous.status().as_u16(), 401, "anonymous {path}");
853800 }
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;
855804 assert_eq!(inbox.status().as_u16(), 200, "inbox stream for its owner");
856805
857- let mut header = open_stream(&http, "/tahinli/pub/events", None).await;
806+ let mut header = http.stream("/tahinli/pub/events", None).await;
858807 assert_eq!(header.status().as_u16(), 200);
859808 let page = http.get("/tahinli/pub", Some(&tahinli)).await;
860809 let csrf = input_value(&page.body(), "csrf");
@@ -877,7 +826,7 @@ async fn browsing_pages_stream_their_changes() {
877826 ok(&git(&work, &["push", "-q", "origin", "main"]), "push main");
878827 assert_ne!(pushed, head_sha(&work), "the second push moved main");
879828
880- let mut explore = open_stream(&http, "/explore/events", None).await;
829+ let mut explore = http.stream("/explore/events", None).await;
881830 assert_eq!(explore.status().as_u16(), 200);
882831 create_repo(&http, &tahinli, "lib", "public").await;
883832 let listed = next_chunk(&mut explore)
@@ -885,13 +834,13 @@ async fn browsing_pages_stream_their_changes() {
885834 .expect("event for a new public repo");
886835 assert!(listed.contains("event: changed"), "{listed}");
887836
888- let mut profile = open_stream(&http, "/users/tahinli/events", None).await;
837+ let mut profile = http.stream("/users/tahinli/events", None).await;
889838 assert_eq!(profile.status().as_u16(), 200);
890839 create_repo(&http, &tahinli, "tools", "public").await;
891840 let changed = next_chunk(&mut profile)
892841 .await
893842 .expect("event for a new repo of the profile");
894843 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;
896845 assert_eq!(missing.status().as_u16(), 404, "profile of an unknown user");
897846 }
crates/forge-e2e/tests/e2e/ci_e2e.rsmodified+33 -168
@@ -1,5 +1,6 @@
11 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,
34 };
45 use forge_ci::proto::{JobAssignment, Outcome, RegisterRequest};
56 use forge_runner::client::ForgeClient;
@@ -14,9 +15,9 @@ use std::sync::Arc;
1415 use std::time::{Duration, Instant};
1516 use tokio_util::sync::CancellationToken;
1617
17-const TAHINLI_PW: &str = "tahinli-password-123";
18-const BOB_PW: &str = "bob-password-4567";
1918 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);
2021 const REPO_PATH: &str = "/tahinli/r";
2122 const SECRET_VALUE: &str = "supersecretvalue";
2223 const LABELS: &[&str] = &["linux"];
@@ -75,127 +76,12 @@ run = "echo never"
7576 needs = ["broken"]
7677 "#;
7778
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-
14879 fn remote(port: u16, user: &str, token: &str, owner: &str, repo: &str) -> String {
14980 format!("http://{user}:{token}@127.0.0.1:{port}/{owner}/{repo}.git")
15081 }
15182
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-
19783 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;
19985 let res = http
20086 .post_form(
20187 &format!("{REPO_PATH}/settings/secrets"),
@@ -220,17 +106,9 @@ fn server_log(b: &Booted) -> String {
220106 }
221107
222108 async fn boot() -> Booted {
223- let root = tempfile::Builder::new()
224- .prefix("ci2e")
225- .tempdir_in("/tmp")
226- .expect("temp dir");
109+ let root = temp_dir("ci2e");
227110 let dir = root.path().to_path_buf();
228- let ports = pick_ports();
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;
111+ let (server, ports) = boot_forge(&dir, FAST_CLAIMS, &[TAHINLI_CMD, BOB_CMD]).await;
234112 Booted {
235113 _server: server,
236114 _root: root,
@@ -268,9 +146,7 @@ impl Worker {
268146 }
269147
270148 async fn register_runner(b: &Booted, admin_session: &str, name: &str) -> Worker {
271- let page = b.http.get("/admin/runners", Some(admin_session)).await;
272- assert_eq!(page.status, 200, "GET /admin/runners");
273- let csrf = input_value(&page.body, "csrf");
149+ let csrf = csrf_for(&b.http, "/admin/runners", admin_session).await;
274150 let res = b
275151 .http
276152 .post_form(
@@ -381,24 +257,17 @@ fn job_id_of(status: &Status) -> String {
381257 }
382258
383259 fn push_ci_config(work: &Path, contents: &str) -> String {
384- let sha = commit(
385- work,
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"]);
260+ let sha = commit(work, ".forge/ci.toml", contents, "add ci", TAHINLI);
261+ git_text(work, &["push", "-q", "origin", "HEAD:refs/heads/main"]);
393262 sha
394263 }
395264
396265 #[tokio::test]
397266 async fn push_run_masks_secrets_keeps_artifacts_and_skips_dependants() {
398267 let b = boot().await;
399- let tahinli = login(&b.http, "tahinli", TAHINLI_PW).await;
268+ let tahinli = login(&b.http, "tahinli", PW).await;
400269 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;
402271 set_secret(&b.http, &tahinli, "MY_SECRET", SECRET_VALUE).await;
403272 let worker = register_runner(&b, &tahinli, "runner-a").await;
404273
@@ -485,9 +354,9 @@ async fn push_run_masks_secrets_keeps_artifacts_and_skips_dependants() {
485354 #[tokio::test]
486355 async fn run_page_lists_a_jobs_steps_and_a_step_opens_its_part_of_the_log() {
487356 let b = boot().await;
488- let tahinli = login(&b.http, "tahinli", TAHINLI_PW).await;
357+ let tahinli = login(&b.http, "tahinli", PW).await;
489358 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;
491360 let worker = register_runner(&b, &tahinli, "runner-a").await;
492361
493362 let work = clone(
@@ -538,9 +407,9 @@ async fn run_page_lists_a_jobs_steps_and_a_step_opens_its_part_of_the_log() {
538407 #[tokio::test]
539408 async fn fork_pull_waits_for_approval_and_runs_without_secrets() {
540409 let b = boot().await;
541- let tahinli = login(&b.http, "tahinli", TAHINLI_PW).await;
410+ let tahinli = login(&b.http, "tahinli", PW).await;
542411 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;
544413 set_secret(&b.http, &tahinli, "MY_SECRET", SECRET_VALUE).await;
545414 let worker = register_runner(&b, &tahinli, "runner-a").await;
546415
@@ -552,9 +421,9 @@ async fn fork_pull_waits_for_approval_and_runs_without_secrets() {
552421 wait_statuses(&b.http, &token, &base_sha, &["ci/build"]).await;
553422 worker.drain().await;
554423
555- let bob = login(&b.http, "bob", BOB_PW).await;
424+ let bob = login(&b.http, "bob", PW).await;
556425 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;
558427 let fork = b
559428 .http
560429 .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() {
565434 &remote(b.port, "bob", &bob_token, "bob", "r"),
566435 &b.dir.join("bob-work"),
567436 );
568- git(&bob_work, &["checkout", "-q", "-b", "bob-feature"]);
437+ git_text(&bob_work, &["checkout", "-q", "-b", "bob-feature"]);
569438 let head = commit(
570439 &bob_work,
571440 ".forge/ci.toml",
572441 CI_TOML_FORK,
573442 "print the secret",
574- "bob",
575- BOB_EMAIL,
443+ BOB,
576444 );
577- git(
445+ git_text(
578446 &bob_work,
579447 &["push", "-q", "origin", "HEAD:refs/heads/bob-feature"],
580448 );
@@ -587,7 +455,7 @@ async fn fork_pull_waits_for_approval_and_runs_without_secrets() {
587455 )
588456 .await;
589457 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;
591459 let open = b
592460 .http
593461 .post_form(
@@ -623,7 +491,10 @@ async fn fork_pull_waits_for_approval_and_runs_without_secrets() {
623491 .http
624492 .post_form(
625493 &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+ )],
627498 Some(&tahinli),
628499 )
629500 .await;
@@ -652,9 +523,9 @@ async fn fork_pull_waits_for_approval_and_runs_without_secrets() {
652523 #[tokio::test]
653524 async fn live_log_streams_until_the_job_finishes() {
654525 let b = boot().await;
655- let tahinli = login(&b.http, "tahinli", TAHINLI_PW).await;
526+ let tahinli = login(&b.http, "tahinli", PW).await;
656527 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;
658529 let worker = register_runner(&b, &tahinli, "runner-a").await;
659530
660531 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=$
717588 #[tokio::test]
718589 async fn ci_job_token_clones_the_repos_wiki_read_only() {
719590 let b = boot().await;
720- let tahinli = login(&b.http, "tahinli", TAHINLI_PW).await;
591+ let tahinli = login(&b.http, "tahinli", PW).await;
721592 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;
723594 let worker = register_runner(&b, &tahinli, "runner-a").await;
724595
725- let csrf = input_value(
726- &b.http
727- .get(&format!("{REPO_PATH}/wiki/-/new"), Some(&tahinli))
728- .await
729- .body,
730- "csrf",
731- );
596+ let csrf = csrf_for(&b.http, &format!("{REPO_PATH}/wiki/-/new"), &tahinli).await;
732597 let saved = b
733598 .http
734599 .post_form(
@@ -770,8 +635,8 @@ run = "echo started; sleep 5; echo done"
770635 assert!(home.contains("Welcome from the wiki"), "{home}");
771636
772637 fs::write(job_wiki.join("Home.md"), "# changed by a job\n").expect("write");
773- git(&job_wiki, &["add", "Home.md"]);
774- git_env(
638+ git_text(&job_wiki, &["add", "Home.md"]);
639+ git_text_env(
775640 &job_wiki,
776641 &[
777642 "-c",
crates/forge-e2e/tests/e2e/common/http.rsmodified+28 -14
@@ -96,20 +96,7 @@ impl Http {
9696 }
9797
9898 pub async fn stream(&self, path: &str, cookie: Option<&str>) -> reqwest::Response {
99- let mut req = self.client.get(format!("{}{path}", self.base));
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
99+ open_stream(&self.client, &format!("{}{path}", self.base), cookie).await
113100 }
114101
115102 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 {
162149 assert_eq!(res.status, 303, "login as {username}: {}", res.body);
163150 cookie_named(&res, "forge_session").expect("session cookie after login")
164151 }
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+}
crates/forge-e2e/tests/e2e/common/mod.rsmodified+162 -33
@@ -5,11 +5,9 @@ use std::process::{Child, Command, ExitStatus, Output, Stdio};
55 use std::sync::OnceLock;
66 use std::time::{Duration, Instant};
77
8-use tempfile::TempDir;
9-
108 mod http;
119
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};
1311
1412 pub fn bin() -> &'static str {
1513 static BIN: OnceLock<String> = OnceLock::new();
@@ -78,6 +76,62 @@ pub fn input_value(body: &str, name: &str) -> String {
7876 .to_owned()
7977 }
8078
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+
81135 pub fn temp_dir(prefix: &str) -> tempfile::TempDir {
82136 tempfile::Builder::new()
83137 .prefix(prefix)
@@ -85,6 +139,11 @@ pub fn temp_dir(prefix: &str) -> tempfile::TempDir {
85139 .expect("temp dir")
86140 }
87141
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+
88147 pub fn free_port() -> u16 {
89148 std::net::TcpListener::bind("127.0.0.1:0")
90149 .expect("bind free port")
@@ -117,10 +176,6 @@ pub fn tool_on_path(name: &str) -> bool {
117176 .is_ok()
118177 }
119178
120-pub fn write_config(dir: &Path, ports: Ports) -> PathBuf {
121- write_config_with(dir, ports, "")
122-}
123-
124179 pub fn write_config_with(dir: &Path, ports: Ports, extra: &str) -> PathBuf {
125180 let d = dir.display();
126181 let Ports {
@@ -148,7 +203,19 @@ pub fn write_config_with(dir: &Path, ports: Ports, extra: &str) -> PathBuf {
148203
149204 pub const FAST_CLAIMS: &str = "[ci]\nclaim_wait_ms = 50\n";
150205
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 {
152219 let mut cmd = Command::new("git");
153220 cmd.current_dir(cwd)
154221 .args(["-c", "credential.helper="])
@@ -160,6 +227,78 @@ pub fn git(cwd: &Path, args: &[&str], env: &[(&str, &str)]) -> Output {
160227 cmd.output().expect("run git")
161228 }
162229
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+
163302 pub async fn create_token(http: &Http, session: &str, name: &str) -> String {
164303 let page = http.get_cookie("/settings/keys", session).await;
165304 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
211350
212351 pub const PW: &str = "tahinli-password-123";
213352
214-pub fn admin(config: &Path, args: &[&str]) {
353+pub fn admin(config: &Path, args: &[&str]) -> Output {
215354 let out = Command::new(bin())
216355 .arg("--config")
217356 .arg(config)
@@ -225,6 +364,7 @@ pub fn admin(config: &Path, args: &[&str]) {
225364 "admin {args:?} failed:\n{}",
226365 describe(&out)
227366 );
367+ out
228368 }
229369
230370 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) {
257397 assert!(text.contains("event: changed"), "{what}: {text}");
258398 }
259399
260-pub fn run_admin(config: &Path, username: &str, extra: &[&str], password: &str) {
261- let out = Command::new(bin())
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-}
400+pub const TAHINLI_CMD: &[&str] = &["create-user", "tahinli", "--admin"];
401+pub const BOB_CMD: &[&str] = &["create-user", "bob"];
275402
276-pub async fn boot_admin(prefix: &str, password: &str) -> (TempDir, Server, Ports) {
277- let root = tempfile::Builder::new()
278- .prefix(prefix)
279- .tempdir_in("/tmp")
280- .expect("temp dir");
403+pub fn provision(dir: &Path, extra: &str, admin_cmds: &[&[&str]]) -> (PathBuf, Ports) {
281404 let ports = pick_ports();
282- let config = write_config(root.path(), ports);
283- run_admin(&config, "tahinli", &["--admin"], password);
284- let (server, ports) = launch(root.path(), ports).await;
285- (root, server, ports)
405+ let config = write_config_with(dir, ports, extra);
406+ for args in admin_cmds {
407+ admin(&config, args);
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
286415 }
287416
288417 pub async fn launch(dir: &Path, ports: Ports) -> (Server, Ports) {
crates/forge-e2e/tests/e2e/community_i18n_e2e.rsmodified+2 -24
@@ -1,35 +1,13 @@
1-use std::process::Command;
21 use std::time::Duration;
32
4-use crate::common::{bin, describe, launch, pick_ports, write_config};
3+use crate::common::boot_forge;
54 use reqwest::header::ACCEPT_LANGUAGE;
65
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-
256 #[tokio::test]
267 async fn snippets_page_follows_the_browser_language() {
278 let root = tempfile::tempdir().expect("temp dir");
289 let dir = root.path().to_path_buf();
29- let ports = pick_ports();
30- let config = write_config(&dir, ports);
31- admin(&config, &["create-user", "tahinli"]);
32- let (_server, ports) = launch(&dir, ports).await;
10+ let (_server, ports) = boot_forge(&dir, "", &[&["create-user", "tahinli"]]).await;
3311
3412 let client = reqwest::Client::builder()
3513 .timeout(Duration::from_secs(60))
crates/forge-e2e/tests/e2e/discussions_e2e.rsmodified+11 -59
@@ -1,34 +1,7 @@
11 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,
33 };
44
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-
325 fn anchored_id(location: Option<&str>) -> String {
336 location
347 .and_then(|l| l.rsplit_once("#comment-"))
@@ -45,17 +18,11 @@ async fn discussions_create_reply_answer_lock_and_toggle() {
4518
4619 let root = tempfile::tempdir().expect("temp dir");
4720 let dir = root.path().to_path_buf();
48- let ports = pick_ports();
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;
21+ let (_server, ports) = boot_forge(&dir, "", &[TAHINLI_CMD, BOB_CMD]).await;
5522 let http = Http::new(ports.http);
56- let tahinli = login(&http, "tahinli", TAHINLI_PW).await;
57- let bob = login(&http, "bob", BOB_PW).await;
58- create_repo(&http, &tahinli, "pub").await;
23+ let tahinli = login(&http, "tahinli", PW).await;
24+ let bob = login(&http, "bob", PW).await;
25+ create_repo(&http, &tahinli, "pub", "public").await;
5926
6027 let repo_page = http.get("/tahinli/pub", Some(tahinli.as_str())).await;
6128 assert_eq!(repo_page.status, 200);
@@ -71,11 +38,7 @@ async fn discussions_create_reply_answer_lock_and_toggle() {
7138 "list while off"
7239 );
7340
74- let settings = http
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");
41+ let csrf = csrf_for(&http, "/tahinli/pub/settings", &tahinli).await;
7942 let res = http
8043 .post_form(
8144 "/tahinli/pub/settings/discussions",
@@ -90,11 +53,7 @@ async fn discussions_create_reply_answer_lock_and_toggle() {
9053 "the Discussions tab is missing after turning it on"
9154 );
9255
93- let form = http
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");
56+ let csrf = csrf_for(&http, "/tahinli/pub/discussions/new", &tahinli).await;
9857 let res = http
9958 .post_form(
10059 "/tahinli/pub/discussions/new",
@@ -114,9 +73,7 @@ async fn discussions_create_reply_answer_lock_and_toggle() {
11473 );
11574 let discussion = "/tahinli/pub/discussions/1";
11675
117- let page = http.get(discussion, Some(bob.as_str())).await;
118- assert_eq!(page.status, 200, "GET discussion as bob");
119- let csrf_bob = input_value(&page.body, "csrf");
76+ let csrf_bob = csrf_for(&http, discussion, &bob).await;
12077 let res = http
12178 .post_form(
12279 &format!("{discussion}/comments"),
@@ -159,8 +116,7 @@ async fn discussions_create_reply_answer_lock_and_toggle() {
159116 res.body
160117 );
161118
162- let page = http.get(discussion, Some(tahinli.as_str())).await;
163- let csrf_tahinli = input_value(&page.body, "csrf");
119+ let csrf_tahinli = csrf_for(&http, discussion, &tahinli).await;
164120 let res = http
165121 .post_form(
166122 &format!("{discussion}/answer"),
@@ -179,8 +135,7 @@ async fn discussions_create_reply_answer_lock_and_toggle() {
179135 "the answered badge is missing after marking an answer"
180136 );
181137
182- let page = http.get(discussion, Some(tahinli.as_str())).await;
183- let csrf_tahinli = input_value(&page.body, "csrf");
138+ let csrf_tahinli = csrf_for(&http, discussion, &tahinli).await;
184139 let res = http
185140 .post_form(
186141 &format!("{discussion}/lock"),
@@ -206,10 +161,7 @@ async fn discussions_create_reply_answer_lock_and_toggle() {
206161 .await;
207162 assert_eq!(res.status, 403, "bob locks a discussion");
208163
209- let settings = http
210- .get("/tahinli/pub/settings", Some(tahinli.as_str()))
211- .await;
212- let csrf = input_value(&settings.body, "csrf");
164+ let csrf = csrf_for(&http, "/tahinli/pub/settings", &tahinli).await;
213165 let res = http
214166 .post_form(
215167 "/tahinli/pub/settings/discussions",
crates/forge-e2e/tests/e2e/git_e2e.rsmodified+32 -100
@@ -1,6 +1,6 @@
11 use crate::common::{
2- Http, create_repo, create_token, describe, git, input_value, launch, login, pick_ports,
3- run_admin, tool_on_path, write_config,
2+ BOB_CMD, Http, PW, TAHINLI_CMD, boot_forge, commit_file, create_repo, create_token, csrf_for,
3+ describe, git, git_env, head_sha, login, ok, path_str, set_identity, tool_on_path,
44 };
55 use std::fs;
66 use std::path::{Path, PathBuf};
@@ -8,13 +8,6 @@ use std::process::{Command, Output};
88
99 use reqwest::header::WWW_AUTHENTICATE;
1010
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-
1811 fn rejected(out: &Output, what: &str) -> String {
1912 assert!(
2013 !out.status.success(),
@@ -24,10 +17,6 @@ fn rejected(out: &Output, what: &str) -> String {
2417 describe(out)
2518 }
2619
27-fn path_str(path: &Path) -> &str {
28- path.to_str().expect("utf-8 path")
29-}
30-
3120 fn ssh_opts(key: &Path, ssh_port: u16) -> Vec<String> {
3221 [
3322 "-i",
@@ -63,37 +52,6 @@ fn gen_key(path: &Path) {
6352 ok(&out, "ssh-keygen");
6453 }
6554
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-
9755 fn find_file(dir: &Path, name: &str) -> bool {
9856 std::fs::read_dir(dir).is_ok_and(|entries| {
9957 entries.flatten().any(|entry| {
@@ -107,9 +65,7 @@ fn read(path: PathBuf) -> String {
10765 }
10866
10967 async fn add_key(http: &Http, session: &str, public_key: &str) {
110- let page = http.get_cookie("/settings/keys", session).await;
111- assert_eq!(page.status, 200, "GET /settings/keys");
112- let csrf = input_value(&page.body, "csrf");
68+ let csrf = csrf_for(http, "/settings/keys", session).await;
11369 let res = http
11470 .post_form(
11571 "/settings/keys",
@@ -135,22 +91,13 @@ async fn git_end_to_end() {
13591 }
13692 }
13793
138- let root = tempfile::Builder::new()
139- .prefix("fe2e")
140- .tempdir_in("/tmp")
141- .expect("temp dir");
94+ let root = crate::common::temp_dir("fe2e");
14295 let dir = root.path().to_path_buf();
143- let ports = pick_ports();
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;
96+ let (_server, ports) = boot_forge(&dir, "", &[TAHINLI_CMD, BOB_CMD]).await;
15097 let http = Http::new(ports.http);
15198 let (http_port, ssh_port) = (ports.http, ports.ssh);
15299
153- let tahinli = login(&http, "tahinli", TAHINLI_PW).await;
100+ let tahinli = login(&http, "tahinli", PW).await;
154101 let tahinli_token = create_token(&http, &tahinli, "e2e-token").await;
155102
156103 let key = dir.join("id");
@@ -164,19 +111,19 @@ async fn git_end_to_end() {
164111 let pub_url = format!("http://tahinli:{tahinli_token}@127.0.0.1:{http_port}/tahinli/pub.git");
165112 let pub_work = dir.join("pub-work");
166113 ok(
167- &git(&dir, &["clone", &pub_url, path_str(&pub_work)], &[]),
114+ &git(&dir, &["clone", &pub_url, path_str(&pub_work)]),
168115 "https clone of empty public repo",
169116 );
170117 commit_file(&pub_work, "hello.txt", "hello over https\n", "https commit");
171118 ok(
172- &git(&pub_work, &["push", "origin", "HEAD:main"], &[]),
119+ &git(&pub_work, &["push", "origin", "HEAD:main"]),
173120 "https push",
174121 );
175122 let pushed_main = head_sha(&pub_work);
176123
177124 let pub_verify = dir.join("pub-verify");
178125 ok(
179- &git(&dir, &["clone", &pub_url, path_str(&pub_verify)], &[]),
126+ &git(&dir, &["clone", &pub_url, path_str(&pub_verify)]),
180127 "https fresh clone",
181128 );
182129 assert_eq!(read(pub_verify.join("hello.txt")), "hello over https\n");
@@ -184,7 +131,7 @@ async fn git_end_to_end() {
184131 let anon_url = format!("http://127.0.0.1:{http_port}/tahinli/pub.git");
185132 let pub_anon = dir.join("pub-anon");
186133 ok(
187- &git(&dir, &["clone", &anon_url, path_str(&pub_anon)], &[]),
134+ &git(&dir, &["clone", &anon_url, path_str(&pub_anon)]),
188135 "anonymous clone of public repo",
189136 );
190137 assert_eq!(read(pub_anon.join("hello.txt")), "hello over https\n");
@@ -193,7 +140,6 @@ async fn git_end_to_end() {
193140 &git(
194141 &dir,
195142 &["clone", "--depth", "1", &anon_url, path_str(&pub_shallow)],
196- &[],
197143 ),
198144 "anonymous shallow clone",
199145 );
@@ -203,7 +149,7 @@ async fn git_end_to_end() {
203149 let priv_ssh_url = format!("ssh://git@127.0.0.1:{ssh_port}/tahinli/priv.git");
204150 let priv_work = dir.join("priv-work");
205151 ok(
206- &git(
152+ &git_env(
207153 &dir,
208154 &["clone", &priv_ssh_url, path_str(&priv_work)],
209155 &ssh_env,
@@ -212,12 +158,12 @@ async fn git_end_to_end() {
212158 );
213159 commit_file(&priv_work, "secret.txt", "over ssh\n", "ssh commit");
214160 ok(
215- &git(&priv_work, &["push", "origin", "HEAD:main"], &ssh_env),
161+ &git_env(&priv_work, &["push", "origin", "HEAD:main"], &ssh_env),
216162 "ssh push",
217163 );
218164 let priv_verify = dir.join("priv-verify");
219165 ok(
220- &git(
166+ &git_env(
221167 &dir,
222168 &["clone", &priv_ssh_url, path_str(&priv_verify)],
223169 &ssh_env,
@@ -228,7 +174,7 @@ async fn git_end_to_end() {
228174
229175 let priv_https_anon = format!("http://127.0.0.1:{http_port}/tahinli/priv.git");
230176 rejected(
231- &git(&dir, &["clone", &priv_https_anon, "anon-priv"], &[]),
177+ &git(&dir, &["clone", &priv_https_anon, "anon-priv"]),
232178 "anonymous clone of private repo",
233179 );
234180 let refs_path = "/tahinli/priv.git/info/refs?service=git-upload-pack";
@@ -239,7 +185,7 @@ async fn git_end_to_end() {
239185 "401 must carry WWW-Authenticate"
240186 );
241187
242- let bob = login(&http, "bob", BOB_PW).await;
188+ let bob = login(&http, "bob", PW).await;
243189 let bob_page = http.get_cookie("/tahinli/priv", &bob).await;
244190 assert_eq!(bob_page.status, 404, "bob's web view of tahinli/priv");
245191 let bob_token = create_token(&http, &bob, "bob-token").await;
@@ -253,11 +199,11 @@ async fn git_end_to_end() {
253199 let wrong_url =
254200 format!("http://tahinli:forge_notarealtoken@127.0.0.1:{http_port}/tahinli/priv.git");
255201 rejected(
256- &git(&dir, &["clone", &wrong_url, "wrong-token-clone"], &[]),
202+ &git(&dir, &["clone", &wrong_url, "wrong-token-clone"]),
257203 "clone with wrong token",
258204 );
259205
260- let delete = git(&pub_verify, &["push", "origin", "--delete", "main"], &[]);
206+ let delete = git(&pub_verify, &["push", "origin", "--delete", "main"]);
261207 let text = rejected(&delete, "deleting main");
262208 assert!(
263209 text.contains("deleting protected branch 'main' is not allowed"),
@@ -277,18 +223,17 @@ async fn git_end_to_end() {
277223 "-m",
278224 "rewritten",
279225 ],
280- &[],
281226 ),
282227 "amend commit",
283228 );
284- let force = git(&pub_verify, &["push", "-f", "origin", "HEAD:main"], &[]);
229+ let force = git(&pub_verify, &["push", "-f", "origin", "HEAD:main"]);
285230 let text = rejected(&force, "force-push to main");
286231 assert!(
287232 text.contains("force-push to protected branch 'main' is not allowed"),
288233 "force-push message: {text}"
289234 );
290235
291- let ls = git(&dir, &["ls-remote", &pub_url, "refs/heads/main"], &[]);
236+ let ls = git(&dir, &["ls-remote", &pub_url, "refs/heads/main"]);
292237 ok(&ls, "ls-remote main");
293238 let remote_main = String::from_utf8_lossy(&ls.stdout);
294239 assert!(
@@ -297,11 +242,7 @@ async fn git_end_to_end() {
297242 );
298243
299244 ok(
300- &git(
301- &pub_verify,
302- &["push", "origin", "HEAD:refs/heads/scratch"],
303- &[],
304- ),
245+ &git(&pub_verify, &["push", "origin", "HEAD:refs/heads/scratch"]),
305246 "push scratch",
306247 );
307248 let overwritten = head_sha(&pub_verify);
@@ -323,12 +264,11 @@ async fn git_end_to_end() {
323264 "-m",
324265 "rewritten again",
325266 ],
326- &[],
327267 ),
328268 "amend again",
329269 );
330270 ok(
331- &git(&pub_verify, &["push", "-f", "origin", "HEAD:scratch"], &[]),
271+ &git(&pub_verify, &["push", "-f", "origin", "HEAD:scratch"]),
332272 "force-push scratch",
333273 );
334274 assert_eq!(
@@ -346,7 +286,7 @@ async fn git_end_to_end() {
346286 let rogue_cmd = ssh_command(&rogue, ssh_port);
347287 let rogue_env = [("GIT_SSH_COMMAND", rogue_cmd.as_str())];
348288 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),
350290 "clone with unregistered key",
351291 );
352292 assert!(
@@ -390,22 +330,14 @@ async fn suspended_user_token_is_refused_over_http_git() {
390330 eprintln!("SKIP git_e2e: `git` was not found on PATH");
391331 return;
392332 }
393- let root = tempfile::Builder::new()
394- .prefix("fe2s")
395- .tempdir_in("/tmp")
396- .expect("temp dir");
333+ let root = crate::common::temp_dir("fe2s");
397334 let dir = root.path().to_path_buf();
398- let ports = pick_ports();
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;
335+ let (_server, ports) = boot_forge(&dir, "", &[TAHINLI_CMD, BOB_CMD]).await;
403336 let http = Http::new(ports.http);
404337
405- let bob = login(&http, "bob", BOB_PW).await;
338+ let bob = login(&http, "bob", PW).await;
406339 let bob_token = create_token(&http, &bob, "suspend-token").await;
407- let page = http.get_cookie("/new", &bob).await;
408- let csrf = input_value(&page.body, "csrf");
340+ let csrf = csrf_for(&http, "/new", &bob).await;
409341 let created = http
410342 .post_form(
411343 "/new",
@@ -426,16 +358,16 @@ async fn suspended_user_token_is_refused_over_http_git() {
426358 );
427359 let work = dir.join("work");
428360 ok(
429- &git(&dir, &["clone", &url, path_str(&work)], &[]),
361+ &git(&dir, &["clone", &url, path_str(&work)]),
430362 "clone before suspension",
431363 );
432364 commit_file(&work, "a.txt", "one\n", "first");
433365 ok(
434- &git(&work, &["push", "origin", "HEAD:main"], &[]),
366+ &git(&work, &["push", "origin", "HEAD:main"]),
435367 "push before suspension",
436368 );
437369
438- let tahinli = login(&http, "tahinli", TAHINLI_PW).await;
370+ let tahinli = login(&http, "tahinli", PW).await;
439371 let list = http.get_cookie("/admin/users", &tahinli).await;
440372 assert_eq!(list.status, 200, "GET /admin/users");
441373 let doc = scraper::Html::parse_document(&list.body);
@@ -453,7 +385,7 @@ async fn suspended_user_token_is_refused_over_http_git() {
453385 .to_owned();
454386 let detail = http.get_cookie(&bob_href, &tahinli).await;
455387 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;
457389 let res = http
458390 .post_form(
459391 &format!("{bob_href}/suspend"),
@@ -465,12 +397,12 @@ async fn suspended_user_token_is_refused_over_http_git() {
465397
466398 commit_file(&work, "b.txt", "two\n", "second");
467399 rejected(
468- &git(&work, &["push", "origin", "HEAD:main"], &[]),
400+ &git(&work, &["push", "origin", "HEAD:main"]),
469401 "push with a suspended user's token",
470402 );
471403 let again = dir.join("again");
472404 rejected(
473- &git(&dir, &["clone", &url, path_str(&again)], &[]),
405+ &git(&dir, &["clone", &url, path_str(&again)]),
474406 "clone with a suspended user's token",
475407 );
476408 }
crates/forge-e2e/tests/e2e/i18n_e2e.rsmodified+2 -27
@@ -1,29 +1,6 @@
1-use std::path::Path;
2-use std::process::Command;
3-
4-use crate::common::{
5- Http, Server, bin, describe, input_value, launch, login, pick_ports, write_config,
6-};
1+use crate::common::{Http, PW, Server, input_value, launch, login, provision};
72 use forge_core::Store;
83
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-
274 struct Env {
285 _root: tempfile::TempDir,
296 _server: Server,
@@ -37,9 +14,7 @@ where
3714 {
3815 let root = tempfile::tempdir().expect("temp dir");
3916 let dir = root.path().to_path_buf();
40- let ports = pick_ports();
41- let config = write_config(&dir, ports);
42- admin(&config, &["create-user", "tahinli"]);
17+ let (_, ports) = provision(&dir, "", &[&["create-user", "tahinli"]]);
4318 let store = Store::open(&dir.join("forge.db"))
4419 .await
4520 .expect("open store");
crates/forge-e2e/tests/e2e/issue_close_e2e.rsmodified+30 -135
@@ -1,109 +1,12 @@
11 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,
34 };
4-use std::fs;
55 use std::future::Future;
6-use std::path::Path;
7-use std::process::{Command, Output};
86 use std::time::{Duration, Instant};
97
108 use forge_core::Store;
119
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-
10710 async fn eventually<F, Fut>(what: &str, mut check: F)
10811 where
10912 F: FnMut() -> Fut,
@@ -127,15 +30,6 @@ async fn issue_page(http: &Http, session: &str, number: u32) -> String {
12730 res.body
12831 }
12932
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-
13933 #[tokio::test]
14034 async fn pushes_close_and_reference_issues() {
14135 if !tool_on_path("git") {
@@ -143,24 +37,16 @@ async fn pushes_close_and_reference_issues() {
14337 return;
14438 }
14539
146- let root = tempfile::Builder::new()
147- .prefix("ice2e")
148- .tempdir_in("/tmp")
149- .expect("temp dir");
40+ let root = crate::common::temp_dir("ice2e");
15041 let dir = root.path().to_path_buf();
151- let ports = pick_ports();
152- let config = write_config(&dir, ports);
42+ let config = dir.join("forge.toml");
15343 let log_path = dir.join("serve.log");
154-
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;
44+ let (mut server, ports) = boot_forge(&dir, "", &[TAHINLI_CMD, BOB_CMD]).await;
15945 let http_port = ports.http;
16046 let http = Http::new(http_port);
161- let tahinli = login(&http, "tahinli", TAHINLI_PW).await;
47+ let tahinli = login(&http, "tahinli", PW).await;
16248 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;
16450
16551 drop(server);
16652 {
@@ -185,34 +71,39 @@ async fn pushes_close_and_reference_issues() {
18571 }
18672 }
18773 server = relaunch(&config, &log_path, ports).await;
188- let tahinli = login(&http, "tahinli", TAHINLI_PW).await;
74+ let tahinli = login(&http, "tahinli", PW).await;
18975
19076 let url = format!("http://tahinli:{token}@127.0.0.1:{http_port}/tahinli/pub.git");
19177 let work = dir.join("work");
192- git(
78+ git_text(
19379 &dir,
19480 &["clone", "-q", &url, work.to_str().expect("utf-8 path")],
19581 );
196- let base = commit_file(&work, "base.txt", "base commit");
197- git(&work, &["push", "-q", "origin", "HEAD:refs/heads/main"]);
82+ let base = commit_file(&work, "base.txt", "base commit", "base commit");
83+ git_text(&work, &["push", "-q", "origin", "HEAD:refs/heads/main"]);
19884
199- git(&work, &["checkout", "-q", "-b", "topic"]);
200- let topic_oid = commit_file(&work, "topic.txt", "fixes #3 on a topic branch");
201- git(&work, &["push", "-q", "origin", "HEAD:refs/heads/topic"]);
85+ git_text(&work, &["checkout", "-q", "-b", "topic"]);
86+ let topic_oid = commit_file(
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"]);
20293
203- git(&work, &["checkout", "-q", "-B", "mainline", &base]);
204- let main_oid = commit_file(&work, "main.txt", "Fixes #1, refs #2");
205- git(
94+ git_text(&work, &["checkout", "-q", "-B", "mainline", &base]);
95+ let main_oid = commit_file(&work, "main.txt", "Fixes #1, refs #2", "Fixes #1, refs #2");
96+ git_text(
20697 &work,
20798 &["push", "-q", "origin", "HEAD:refs/heads/dup-of-main"],
20899 );
209- git(&work, &["push", "-q", "origin", "HEAD:refs/heads/main"]);
100+ git_text(&work, &["push", "-q", "origin", "HEAD:refs/heads/main"]);
210101
211102 let commit_link = format!("/commit/{main_oid}");
212103 let link_ref = commit_link.as_str();
213104 let (http_ref, tahinli_ref) = (&http, tahinli.as_str());
214105 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"
216107 })
217108 .await;
218109 let page1 = issue_page(&http, &tahinli, 1).await;
@@ -227,7 +118,11 @@ async fn pushes_close_and_reference_issues() {
227118 })
228119 .await;
229120 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+ );
231126
232127 tokio::time::sleep(Duration::from_secs(2)).await;
233128 let page2 = issue_page(&http, &tahinli, 2).await;
@@ -238,7 +133,7 @@ async fn pushes_close_and_reference_issues() {
238133 );
239134 let page3 = issue_page(&http, &tahinli, 3).await;
240135 assert_eq!(
241- state_badge(&page3),
136+ text_or_empty(&page3, ".issue-badge"),
242137 "Open",
243138 "#3 must not be closed from topic"
244139 );
crates/forge-e2e/tests/e2e/lfs_e2e.rsmodified+16 -94
@@ -1,33 +1,11 @@
11 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,
33 };
44 use std::fs;
5-use std::path::Path;
6-use std::process::{Command, Output};
5+use std::process::Command;
76
8-const TAHINLI_PW: &str = "tahinli-password-123";
97 const FILE_SIZE: usize = 100 * 1024;
108
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-
319 fn git_lfs_installed() -> bool {
3210 Command::new("git")
3311 .args(["lfs", "version"])
@@ -41,55 +19,6 @@ fn payload() -> Vec<u8> {
4119 .collect()
4220 }
4321
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-
9322 #[tokio::test]
9423 async fn lfs_end_to_end() {
9524 if !git_lfs_installed() {
@@ -97,19 +26,12 @@ async fn lfs_end_to_end() {
9726 return;
9827 }
9928
100- let root = tempfile::Builder::new()
101- .prefix("flfs")
102- .tempdir_in("/tmp")
103- .expect("temp dir");
29+ let root = crate::common::temp_dir("flfs");
10430 let dir = root.path().to_path_buf();
105- let ports = pick_ports();
106- let config = write_config(&dir, ports);
107- run_admin(&config, "tahinli", &["--admin"], TAHINLI_PW);
108-
109- let (_server, ports) = launch(&dir, ports).await;
31+ let (_server, ports) = boot_forge(&dir, "", &[TAHINLI_CMD]).await;
11032 let http = Http::new(ports.http);
11133
112- let session = login(&http, "tahinli", TAHINLI_PW).await;
34+ let session = login(&http, "tahinli", PW).await;
11335 let token = create_token(&http, &session, "lfs-e2e").await;
11436 create_repo(&http, &session, "lfs", "public").await;
11537
@@ -125,15 +47,15 @@ async fn lfs_end_to_end() {
12547
12648 let work = dir.join("work");
12749 ok(
128- &git(&dir, &["clone", &url, path_str(&work)], &iso),
50+ &git_env(&dir, &["clone", &url, path_str(&work)], &iso),
12951 "clone of empty repo",
13052 );
13153 ok(
132- &git(&work, &["config", "user.name", "tahinli"], &iso),
54+ &git_env(&work, &["config", "user.name", "tahinli"], &iso),
13355 "user.name",
13456 );
13557 ok(
136- &git(
58+ &git_env(
13759 &work,
13860 &["config", "user.email", "tahinli@example.com"],
13961 &iso,
@@ -141,21 +63,21 @@ async fn lfs_end_to_end() {
14163 "user.email",
14264 );
14365 ok(
144- &git(&work, &["lfs", "install", "--local"], &iso),
66+ &git_env(&work, &["lfs", "install", "--local"], &iso),
14567 "git lfs install",
14668 );
14769 ok(
148- &git(&work, &["lfs", "track", "*.bin"], &iso),
70+ &git_env(&work, &["lfs", "track", "*.bin"], &iso),
14971 "git lfs track",
15072 );
15173 let content = payload();
15274 fs::write(work.join("data.bin"), &content).expect("write data.bin");
15375 ok(
154- &git(&work, &["add", ".gitattributes", "data.bin"], &iso),
76+ &git_env(&work, &["add", ".gitattributes", "data.bin"], &iso),
15577 "git add",
15678 );
15779 ok(
158- &git(
80+ &git_env(
15981 &work,
16082 &[
16183 "-c",
@@ -170,21 +92,21 @@ async fn lfs_end_to_end() {
17092 "git commit",
17193 );
17294 ok(
173- &git(&work, &["push", "origin", "HEAD:main"], &iso),
95+ &git_env(&work, &["push", "origin", "HEAD:main"], &iso),
17496 "git push",
17597 );
17698
17799 let verify = dir.join("verify");
178100 let smudge = [iso[0], iso[1], ("GIT_LFS_SKIP_SMUDGE", "0")];
179101 ok(
180- &git(&dir, &["clone", &url, path_str(&verify)], &smudge),
102+ &git_env(&dir, &["clone", &url, path_str(&verify)], &smudge),
181103 "clone for verification",
182104 );
183105 ok(
184- &git(&verify, &["lfs", "install", "--local"], &iso),
106+ &git_env(&verify, &["lfs", "install", "--local"], &iso),
185107 "git lfs install in verify clone",
186108 );
187- ok(&git(&verify, &["lfs", "pull"], &smudge), "git lfs pull");
109+ ok(&git_env(&verify, &["lfs", "pull"], &smudge), "git lfs pull");
188110 let fetched = fs::read(verify.join("data.bin")).expect("read fetched data.bin");
189111 assert!(
190112 fetched == content,
crates/forge-e2e/tests/e2e/merge_queue_e2e.rsmodified+23 -166
@@ -1,6 +1,6 @@
11 use crate::common::{
2- FAST_CLAIMS, Http, Server, input_value, launch_with, login, pick_ports, run_admin,
3- tool_on_path, 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, login, temp_dir, tool_on_path,
44 };
55 use forge_ci::proto::{JobAssignment, RegisterRequest};
66 use forge_runner::client::ForgeClient;
@@ -10,134 +10,17 @@ use forge_runner::runner::{RunOptions, Runner};
1010 use std::collections::BTreeMap;
1111 use std::fs;
1212 use std::path::{Path, PathBuf};
13-use std::process::Command;
1413 use std::sync::Arc;
1514 use tokio_util::sync::CancellationToken;
1615
17-const TAHINLI_PW: &str = "tahinli-password-123";
18-const BOB_PW: &str = "bob-password-4567";
16+const TAHINLI: (&str, &str) = ("tahinli", "tahinli@example.test");
1917 const REPO_PATH: &str = "/tahinli/r";
2018 const LABELS: &[&str] = &["linux"];
2119
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-
9220 fn remote(port: u16, user: &str, token: &str, owner: &str, repo: &str) -> String {
9321 format!("http://{user}:{token}@127.0.0.1:{port}/{owner}/{repo}.git")
9422 }
9523
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-
14124 struct Booted {
14225 _server: Server,
14326 _root: tempfile::TempDir,
@@ -152,17 +35,9 @@ fn server_log(b: &Booted) -> String {
15235 }
15336
15437 async fn boot() -> Booted {
155- let root = tempfile::Builder::new()
156- .prefix("ci2e")
157- .tempdir_in("/tmp")
158- .expect("temp dir");
38+ let root = temp_dir("ci2e");
15939 let dir = root.path().to_path_buf();
160- let ports = pick_ports();
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;
40+ let (server, ports) = boot_forge(&dir, FAST_CLAIMS, &[TAHINLI_CMD, BOB_CMD]).await;
16641 Booted {
16742 _server: server,
16843 _root: root,
@@ -200,9 +75,7 @@ impl Worker {
20075 }
20176
20277 async fn register_runner(b: &Booted, admin_session: &str, name: &str) -> Worker {
203- let page = b.http.get("/admin/runners", Some(admin_session)).await;
204- assert_eq!(page.status, 200, "GET /admin/runners");
205- let csrf = input_value(&page.body, "csrf");
78+ let csrf = csrf_for(&b.http, "/admin/runners", admin_session).await;
20679 let res = b
20780 .http
20881 .post_form(
@@ -287,7 +160,7 @@ run = "if [ -f a.txt ] && [ -f b.txt ]; then echo both files present; exit 1; fi
287160 "#;
288161
289162 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;
291164 let res = http
292165 .post_form(
293166 &format!("{REPO_PATH}/settings/branches"),
@@ -309,22 +182,14 @@ async fn require_merge_queue(http: &Http, session: &str) {
309182 }
310183
311184 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"]);
313186 let start = "origin/main";
314- git(work, &["checkout", "-q", "-B", branch, start]);
315- let author = "tahinli@example.test";
316- commit(
317- work,
318- file,
319- "change\n",
320- &format!("add {file}"),
321- "tahinli",
322- author,
323- );
187+ git_text(work, &["checkout", "-q", "-B", branch, start]);
188+ commit(work, file, "change\n", &format!("add {file}"), TAHINLI);
324189 let target = format!("HEAD:refs/heads/{branch}");
325- git(work, &["push", "-q", "-f", "origin", &target]);
190+ git_text(work, &["push", "-q", "-f", "origin", &target]);
326191
327- let csrf = csrf_from(http, &format!("{REPO_PATH}/pulls"), session).await;
192+ let csrf = csrf_for(http, &format!("{REPO_PATH}/pulls"), session).await;
328193 let res = http
329194 .post_form(
330195 &format!("{REPO_PATH}/pulls"),
@@ -348,7 +213,7 @@ async fn open_pull(http: &Http, session: &str, work: &Path, branch: &str, file:
348213 }
349214
350215 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;
352217 let res = http
353218 .post_form(
354219 &format!("{REPO_PATH}/pulls/{number}/merge-queue"),
@@ -368,7 +233,7 @@ async fn pull_page(http: &Http, session: &str, number: i64) -> String {
368233 }
369234
370235 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;
372237 require_merge_queue(&b.http, tahinli).await;
373238 let worker = register_runner(b, tahinli, "runner-a").await;
374239 let work = clone(
@@ -380,10 +245,9 @@ async fn setup_queue_repo(b: &Booted, tahinli: &str, token: &str) -> (Worker, Pa
380245 ".forge/ci.toml",
381246 CI_TOML_QUEUE,
382247 "add queue ci",
383- "tahinli",
384- "tahinli@example.test",
248+ TAHINLI,
385249 );
386- git(&work, &["push", "-q", "origin", "HEAD:refs/heads/main"]);
250+ git_text(&work, &["push", "-q", "origin", "HEAD:refs/heads/main"]);
387251 (worker, work)
388252 }
389253
@@ -394,7 +258,7 @@ async fn merge_queue_lands_the_first_pull_and_kicks_out_the_conflicting_second()
394258 return;
395259 }
396260 let b = boot().await;
397- let tahinli = login(&b.http, "tahinli", TAHINLI_PW).await;
261+ let tahinli = login(&b.http, "tahinli", PW).await;
398262 let token = create_token(&b.http, &tahinli, "mq-token").await;
399263 let (worker, work) = setup_queue_repo(&b, &tahinli, &token).await;
400264
@@ -414,9 +278,9 @@ async fn merge_queue_lands_the_first_pull_and_kicks_out_the_conflicting_second()
414278 let ran = worker.drain().await;
415279 assert_eq!(ran, 2, "one candidate run each: {}", server_log(&b));
416280
417- git(&work, &["fetch", "-q", "origin"]);
418- let main_tip = git(&work, &["rev-parse", "origin/main"]);
419- let files = git(&work, &["ls-tree", "--name-only", "origin/main"]);
281+ git_text(&work, &["fetch", "-q", "origin"]);
282+ let main_tip = git_text(&work, &["rev-parse", "origin/main"]);
283+ let files = git_text(&work, &["ls-tree", "--name-only", "origin/main"]);
420284 assert!(files.contains("a.txt"), "first pull landed: {files}");
421285 assert!(
422286 !files.contains("b.txt"),
@@ -464,7 +328,7 @@ async fn pushing_to_a_queued_pull_removes_it_from_the_queue() {
464328 return;
465329 }
466330 let b = boot().await;
467- let tahinli = login(&b.http, "tahinli", TAHINLI_PW).await;
331+ let tahinli = login(&b.http, "tahinli", PW).await;
468332 let token = create_token(&b.http, &tahinli, "mq-token").await;
469333 let (_worker, work) = setup_queue_repo(&b, &tahinli, &token).await;
470334
@@ -473,15 +337,8 @@ async fn pushing_to_a_queued_pull_removes_it_from_the_queue() {
473337 let queued = pull_page(&b.http, &tahinli, number).await;
474338 assert!(queued.contains("Position 1 in the merge queue"), "queued");
475339
476- commit(
477- &work,
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"]);
340+ commit(&work, "c.txt", "changed again\n", "more", TAHINLI);
341+ git_text(&work, &["push", "-q", "origin", "HEAD:refs/heads/three"]);
485342
486343 let after = pull_page(&b.http, &tahinli, number).await;
487344 assert!(
crates/forge-e2e/tests/e2e/mirrors_e2e.rsmodified+26 -99
@@ -1,14 +1,13 @@
11 use crate::common::{
2- Http, Server, input_value, launch_with, login, pick_ports, run_admin, tool_on_path,
3- write_config_with,
2+ self, Http, PW, Server, TAHINLI_CMD, boot_forge, clone, create_token, csrf_for, git_env,
3+ git_text_env, login, temp_dir, tool_on_path,
44 };
55 use std::collections::BTreeSet;
66 use std::fs;
77 use std::path::{Path, PathBuf};
8-use std::process::{Command, Output};
8+use std::process::Output;
99 use std::time::{Duration, Instant};
1010
11-const TAHINLI_PW: &str = "tahinli-password-123";
1211 const WEBHOOK_TOML: &str = "\n[webhooks]\nallow_http = true\nallowed_hosts = [\"127.0.0.1\"]\n\n[mirrors]\npush_debounce_secs = 0\n";
1312 const SYNC_TIMEOUT: Duration = Duration::from_secs(30);
1413 const PUSH_TIMEOUT: Duration = Duration::from_secs(90);
@@ -23,65 +22,33 @@ fn form_actions(body: &str, suffix: &str) -> Vec<String> {
2322 .collect()
2423 }
2524
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-
3525 fn git_output(cwd: &Path, args: &[&str], env: &[(&str, &str)]) -> Output {
36- let mut cmd = Command::new("git");
37- cmd.current_dir(cwd)
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()
26+ let all: Vec<(&str, &str)> = GIT_HERMETIC_ENV.iter().chain(env).copied().collect();
27+ git_env(cwd, args, &all)
5528 }
5629
5730 fn git(cwd: &Path, args: &[&str]) -> String {
58- git_env(cwd, args, &[])
31+ git_text_env(cwd, args, GIT_HERMETIC_ENV)
5932 }
6033
6134 fn commit(repo: &Path, file: &str, contents: &str, message: &str) -> String {
62- fs::write(repo.join(file), contents).expect("write file");
63- git(repo, &["add", file]);
64- git_env(
35+ common::commit(
6536 repo,
66- &["-c", "commit.gpgsign=false", "commit", "-q", "-m", message],
67- &[
68- ("GIT_AUTHOR_NAME", "tahinli"),
69- ("GIT_AUTHOR_EMAIL", "tahinli@example.test"),
70- ("GIT_COMMITTER_NAME", "tahinli"),
71- ("GIT_COMMITTER_EMAIL", "tahinli@example.test"),
72- ],
73- );
74- git(repo, &["rev-parse", "HEAD"])
37+ file,
38+ contents,
39+ message,
40+ ("tahinli", "tahinli@example.test"),
41+ )
7542 }
7643
77-fn clone(url: &str, into: &Path) -> PathBuf {
78- let parent = into.parent().expect("clone target has a parent");
79- git(
80- parent,
81- &["clone", "-q", url, into.to_str().expect("utf-8 path")],
82- );
83- into.to_path_buf()
84-}
44+const GIT_HERMETIC_ENV: &[(&str, &str)] = &[
45+ ("GIT_AUTHOR_NAME", "tahinli"),
46+ ("GIT_AUTHOR_EMAIL", "tahinli@example.com"),
47+ ("GIT_COMMITTER_NAME", "tahinli"),
48+ ("GIT_COMMITTER_EMAIL", "tahinli@example.com"),
49+ ("GIT_CONFIG_GLOBAL", "/dev/null"),
50+ ("GIT_CONFIG_NOSYSTEM", "1"),
51+];
8552
8653 fn remote(port: u16, token: &str, owner: &str, repo: &str) -> String {
8754 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) {
12794 }
12895 }
12996
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-
15997 async fn new_repo(http: &Http, session: &str, name: &str, mirror: Option<(&str, &str, &str)>) {
160- let page = http.get_cookie("/new", session).await;
161- assert_eq!(page.status, 200, "GET /new");
162- let csrf = input_value(&page.body, "csrf");
98+ let csrf = csrf_for(http, "/new", session).await;
16399 let mut form = vec![
164100 ("csrf", csrf.as_str()),
165101 ("name", name),
@@ -185,9 +121,7 @@ async fn new_repo(http: &Http, session: &str, name: &str, mirror: Option<(&str,
185121
186122 async fn add_push_mirror(http: &Http, session: &str, repo: &str, url: &str, secret: &str) {
187123 let path = format!("/tahinli/{repo}/settings/mirrors");
188- let page = http.get_cookie(&path, session).await;
189- assert_eq!(page.status, 200, "GET {path}");
190- let csrf = input_value(&page.body, "csrf");
124+ let csrf = csrf_for(http, &path, session).await;
191125 let res = http
192126 .post_form(
193127 &path,
@@ -212,7 +146,7 @@ async fn sync_now(http: &Http, session: &str, repo: &str) {
212146 .into_iter()
213147 .next()
214148 .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;
216150 let res = http
217151 .post_form(&action, &[("csrf", &csrf)], Some(session))
218152 .await;
@@ -231,16 +165,9 @@ async fn boot() -> Booted {
231165 if !tool_on_path("git") {
232166 panic!("`git` was not found on PATH");
233167 }
234- let root = tempfile::Builder::new()
235- .prefix("mr2e")
236- .tempdir_in("/tmp")
237- .expect("temp dir");
168+ let root = temp_dir("mr2e");
238169 let dir = root.path().to_path_buf();
239- let ports = pick_ports();
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;
170+ let (server, ports) = boot_forge(&dir, WEBHOOK_TOML, &[TAHINLI_CMD]).await;
244171 Booted {
245172 _server: server,
246173 _root: root,
@@ -257,7 +184,7 @@ fn server_log(b: &Booted) -> String {
257184 #[tokio::test]
258185 async fn pull_and_push_mirrors_sync_over_smart_http() {
259186 let b = boot().await;
260- let session = login(&b.http, "tahinli", TAHINLI_PW).await;
187+ let session = login(&b.http, "tahinli", PW).await;
261188 let token = create_token(&b.http, &session, "mirror-token").await;
262189 let port = b.http_port;
263190
crates/forge-e2e/tests/e2e/oci_e2e.rsmodified+7 -27
@@ -1,5 +1,4 @@
1-use crate::common::{Server, bin, describe, launch, pick_ports, tool_on_path, write_config};
2-use std::path::Path;
1+use crate::common::{Server, describe, launch, provision, tool_on_path};
32 use std::process::Command;
43 use std::time::Duration;
54
@@ -8,7 +7,6 @@ use forge_core::token::{generate_token, hash_token};
87 use forge_core::{Store, User};
98 use sha2::{Digest, Sha256};
109
11-const PW: &str = "tahinli-password-123";
1210 const MANIFEST_TYPE: &str = "application/vnd.oci.image.manifest.v1+json";
1311
1412 struct Resp {
@@ -107,22 +105,6 @@ impl Http {
107105 }
108106 }
109107
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-
126108 struct Env {
127109 _root: tempfile::TempDir,
128110 _server: Server,
@@ -135,15 +117,13 @@ where
135117 F: FnOnce(Store) -> Fut,
136118 Fut: std::future::Future<Output = ()>,
137119 {
138- let root = tempfile::Builder::new()
139- .prefix("foci")
140- .tempdir_in("/tmp")
141- .expect("temp dir");
120+ let root = crate::common::temp_dir("foci");
142121 let dir = root.path().to_path_buf();
143- let ports = pick_ports();
144- let config = write_config(&dir, ports);
145- admin(&config, &["create-user", "tahinli"]);
146- admin(&config, &["create-user", "bob"]);
122+ let (_, ports) = provision(
123+ &dir,
124+ "",
125+ &[&["create-user", "tahinli"], &["create-user", "bob"]],
126+ );
147127 let store = Store::open(&dir.join("forge.db"))
148128 .await
149129 .expect("open store");
crates/forge-e2e/tests/e2e/orgs_core_e2e.rsmodified+6 -27
@@ -1,9 +1,5 @@
1-use crate::common::{
2- Http, Resp, Server, bin, cookie_named, describe, input_value, launch, pick_ports, write_config,
3-};
1+use crate::common::{Http, PW, Resp, Server, cookie_named, input_value, launch, provision};
42 use std::future::Future;
5-use std::path::Path;
6-use std::process::Command;
73 use std::time::Duration;
84
95 use forge_core::token::hash_token;
@@ -12,26 +8,9 @@ use forge_core::{Store, Visibility};
128 static SERIAL: std::sync::LazyLock<tokio::sync::Mutex<()>> =
139 std::sync::LazyLock::new(|| tokio::sync::Mutex::new(()));
1410
15-const PW: &str = "tahinli-password-123";
1611 const ORG_TOKEN: &str = "forge_org_token_for_tests_0123456789";
1712 const ORG_SESSION: &str = "org-session-token-for-tests-0123456789";
1813
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-
3514 async fn try_login(http: &Http, username: &str) -> Resp {
3615 let page = http.get("/login", None).await;
3716 assert_eq!(page.status, 200, "GET /login");
@@ -63,11 +42,11 @@ where
6342 {
6443 let root = tempfile::tempdir().expect("temp dir");
6544 let dir = root.path().to_path_buf();
66- let ports = pick_ports();
67- let config = write_config(&dir, ports);
68- for user in ["dana", "tahinli"] {
69- admin(&config, &["create-user", user]);
70- }
45+ let (_, ports) = provision(
46+ &dir,
47+ "",
48+ &[&["create-user", "dana"], &["create-user", "tahinli"]],
49+ );
7150 let store = Store::open(&dir.join("forge.db"))
7251 .await
7352 .expect("open store");
crates/forge-e2e/tests/e2e/orgs_live_e2e.rsmodified+24 -78
@@ -1,9 +1,7 @@
11 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,
34 };
4-use std::path::Path;
5-use std::process::{Command, Output};
6-use std::time::Duration;
75
86 use forge_core::store::orgs::{DefaultRepoRole, OrgMemberRole, OrgSettings};
97 use forge_core::{Role, Store, Visibility};
@@ -11,8 +9,6 @@ use forge_core::{Role, Store, Visibility};
119 static SERIAL: std::sync::LazyLock<tokio::sync::Mutex<()>> =
1210 std::sync::LazyLock::new(|| tokio::sync::Mutex::new(()));
1311
14-const PW: &str = "tahinli-password-123";
15-
1612 fn live_url(body: &str) -> Option<String> {
1713 let doc = scraper::Html::parse_document(body);
1814 let selector = scraper::Selector::parse("[data-live]").expect("selector");
@@ -22,51 +18,6 @@ fn live_url(body: &str) -> Option<String> {
2218 .map(str::to_owned)
2319 }
2420
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-
7021 #[tokio::test]
7122 async fn org_pages_follow_writes_live_and_refuse_outsiders() {
7223 let _guard = SERIAL.lock().await;
@@ -74,15 +25,18 @@ async fn org_pages_follow_writes_live_and_refuse_outsiders() {
7425 eprintln!("SKIP orgs_live_e2e: `git` was not found on PATH");
7526 return;
7627 }
77- let root = short_temp_dir();
28+ let root = temp_dir("orgl");
7829 let dir = root.path().to_path_buf();
79- let ports = pick_ports();
80- let config = write_config(&dir, ports);
81-
82- admin(&config, &["create-user", "tahinli", "--admin"]);
83- for name in ["bob", "carol", "dana"] {
84- admin(&config, &["create-user", name]);
85- }
30+ let (_, ports) = provision(
31+ &dir,
32+ "",
33+ &[
34+ &["create-user", "tahinli", "--admin"],
35+ &["create-user", "bob"],
36+ &["create-user", "carol"],
37+ &["create-user", "dana"],
38+ ],
39+ );
8640
8741 {
8842 let store = Store::open(&dir.join("forge.db"))
@@ -106,7 +60,7 @@ async fn org_pages_follow_writes_live_and_refuse_outsiders() {
10660 let tahinli = login(&http, "tahinli", PW).await;
10761 let bob = login(&http, "bob", PW).await;
10862 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;
11064
11165 let members = http.get("/org/acme/members", Some(&tahinli)).await;
11266 assert_eq!(members.status, 200, "GET members");
@@ -224,17 +178,6 @@ async fn org_pages_follow_writes_live_and_refuse_outsiders() {
224178 next_changed(&mut bob_members, "adding dana").await;
225179 }
226180
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-
238181 #[tokio::test]
239182 async fn private_linked_repo_is_hidden_from_a_viewer_who_cannot_read_it() {
240183 let _guard = SERIAL.lock().await;
@@ -242,13 +185,16 @@ async fn private_linked_repo_is_hidden_from_a_viewer_who_cannot_read_it() {
242185 eprintln!("SKIP orgs_live_e2e: `git` was not found on PATH");
243186 return;
244187 }
245- let root = short_temp_dir();
188+ let root = temp_dir("orgl");
246189 let dir = root.path().to_path_buf();
247- let ports = pick_ports();
248- let config = write_config(&dir, ports);
249-
250- admin(&config, &["create-user", "tahinli", "--admin"]);
251- admin(&config, &["create-user", "bob"]);
190+ let (_, ports) = provision(
191+ &dir,
192+ "",
193+ &[
194+ &["create-user", "tahinli", "--admin"],
195+ &["create-user", "bob"],
196+ ],
197+ );
252198
253199 let team_id = {
254200 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() {
295241 let http = Http::new(ports.http);
296242 let tahinli = login(&http, "tahinli", PW).await;
297243 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;
299245 let team_page = format!("/org/acme/teams/{team_id}");
300246
301247 let owner_view = http.get(&team_page, Some(&tahinli)).await;
crates/forge-e2e/tests/e2e/orgs_ui_e2e.rsmodified+65 -163
@@ -1,10 +1,7 @@
11 use crate::common::{
2- Http, Resp, bin, describe, input_value, launch, launch_with, login, pick_ports, temp_dir,
3- tool_on_path, write_config,
2+ Http, PW, Resp, attr_of, attr_values, boot_forge, commit_file, create_token, csrf_for,
3+ describe, git, init_bare, launch, login, provision, temp_dir, tool_on_path,
44 };
5-use std::fs;
6-use std::path::Path;
7-use std::process::{Command, Output};
85
96 use forge_core::store::orgs::{DefaultRepoRole, OrgMemberRole, OrgSettings};
107 use forge_core::{Role, Store, Visibility};
@@ -13,60 +10,6 @@ use reqwest::header::LOCATION;
1310 static SERIAL: std::sync::LazyLock<tokio::sync::Mutex<()>> =
1411 std::sync::LazyLock::new(|| tokio::sync::Mutex::new(()));
1512
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-
7013 fn notice_location(redirect: &Resp) -> String {
7114 redirect.header(LOCATION).expect("notice redirect")
7215 }
@@ -80,13 +23,17 @@ async fn org_members_teams_and_access_end_to_end() {
8023 }
8124 let root = temp_dir("forg");
8225 let dir = root.path().to_path_buf();
83- let ports = pick_ports();
84- let config = write_config(&dir, ports);
85-
86- admin(&config, &["create-user", "root", "--admin"]);
87- for name in ["tahinli", "bob", "carol", "dana"] {
88- admin(&config, &["create-user", name]);
89- }
26+ let (_, ports) = provision(
27+ &dir,
28+ "",
29+ &[
30+ &["create-user", "root", "--admin"],
31+ &["create-user", "tahinli"],
32+ &["create-user", "bob"],
33+ &["create-user", "carol"],
34+ &["create-user", "dana"],
35+ ],
36+ );
9037
9138 let (tahinli_id, team_id) = {
9239 let store = Store::open(&dir.join("forge.db"))
@@ -154,7 +101,7 @@ async fn org_members_teams_and_access_end_to_end() {
154101 "members get no add form"
155102 );
156103
157- let bob_csrf = csrf_for(&http, &bob).await;
104+ let bob_csrf = csrf_for(&http, "/settings/keys", &bob).await;
158105 let res = http
159106 .post_form(
160107 "/org/acme/members/add",
@@ -168,7 +115,7 @@ async fn org_members_teams_and_access_end_to_end() {
168115 .await;
169116 assert_eq!(res.status, 403, "member add is refused: {}", res.body);
170117
171- let tahinli_csrf = csrf_for(&http, &tahinli).await;
118+ let tahinli_csrf = csrf_for(&http, "/settings/keys", &tahinli).await;
172119 let res = http
173120 .post_form(
174121 "/org/acme/members/add",
@@ -264,11 +211,15 @@ async fn org_members_teams_and_access_end_to_end() {
264211
265212 let tahinli_new = http.get("/new", Some(&tahinli)).await;
266213 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()),
268216 "owner choice lists acme"
269217 );
270218 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+ );
272223 let res = http
273224 .post_form(
274225 "/new",
@@ -299,13 +250,16 @@ async fn org_settings_delete_and_audit_end_to_end() {
299250 }
300251 let root = temp_dir("forg");
301252 let dir = root.path().to_path_buf();
302- let ports = pick_ports();
303- let config = write_config(&dir, ports);
304-
305- admin(&config, &["create-user", "root", "--admin"]);
306- for name in ["tahinli", "bob", "dana"] {
307- admin(&config, &["create-user", name]);
308- }
253+ let (_, ports) = provision(
254+ &dir,
255+ "",
256+ &[
257+ &["create-user", "root", "--admin"],
258+ &["create-user", "tahinli"],
259+ &["create-user", "bob"],
260+ &["create-user", "dana"],
261+ ],
262+ );
309263 {
310264 let store = Store::open(&dir.join("forge.db"))
311265 .await
@@ -347,7 +301,7 @@ async fn org_settings_delete_and_audit_end_to_end() {
347301 "outsider"
348302 );
349303
350- let csrf = csrf_for(&http, &tahinli).await;
304+ let csrf = csrf_for(&http, "/settings/keys", &tahinli).await;
351305 let res = http
352306 .post_form(
353307 settings,
@@ -371,7 +325,12 @@ async fn org_settings_delete_and_audit_end_to_end() {
371325 "display name on the profile"
372326 );
373327 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(),
375334 Some("write"),
376335 "default role saved"
377336 );
@@ -449,12 +408,15 @@ async fn org_creation_can_be_limited_to_admins() {
449408 let _guard = SERIAL.lock().await;
450409 let root = temp_dir("forg");
451410 let dir = root.path().to_path_buf();
452- let ports = pick_ports();
453- let config = write_config(&dir, ports);
454- admin(&config, &["create-user", "root", "--admin"]);
455- admin(&config, &["create-user", "tahinli"]);
456-
457- let (_server, ports) = launch_with(&dir, ports, "[orgs]\ncreation = \"admin\"\n").await;
411+ let (_server, ports) = boot_forge(
412+ &dir,
413+ "[orgs]\ncreation = \"admin\"\n",
414+ &[
415+ &["create-user", "root", "--admin"],
416+ &["create-user", "tahinli"],
417+ ],
418+ )
419+ .await;
458420 let http = Http::new(ports.http);
459421 let tahinli = login(&http, "tahinli", PW).await;
460422 let root_session = login(&http, "root", PW).await;
@@ -480,7 +442,7 @@ async fn org_creation_can_be_limited_to_admins() {
480442 403,
481443 "a person may not create orgs under the admin policy"
482444 );
483- let csrf = csrf_for(&http, &tahinli).await;
445+ let csrf = csrf_for(&http, "/settings/keys", &tahinli).await;
484446 let res = http
485447 .post_form(
486448 "/org/new",
@@ -495,7 +457,7 @@ async fn org_creation_can_be_limited_to_admins() {
495457 200,
496458 "an admin may create orgs"
497459 );
498- let root_csrf = csrf_for(&http, &root_session).await;
460+ let root_csrf = csrf_for(&http, "/settings/keys", &root_session).await;
499461 let res = http
500462 .post_form(
501463 "/org/new",
@@ -518,70 +480,6 @@ async fn org_creation_can_be_limited_to_admins() {
518480 assert!(profile.body.contains("Organization"), "marked as an org");
519481 }
520482
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-
585483 #[tokio::test]
586484 async fn org_member_pushes_over_https_through_a_write_team() {
587485 let _guard = SERIAL.lock().await;
@@ -591,13 +489,16 @@ async fn org_member_pushes_over_https_through_a_write_team() {
591489 }
592490 let root = temp_dir("forg");
593491 let dir = root.path().to_path_buf();
594- let ports = pick_ports();
595- let config = write_config(&dir, ports);
596-
597- admin(&config, &["create-user", "root", "--admin"]);
598- for name in ["tahinli", "bob", "dana"] {
599- admin(&config, &["create-user", name]);
600- }
492+ let (_, ports) = provision(
493+ &dir,
494+ "",
495+ &[
496+ &["create-user", "root", "--admin"],
497+ &["create-user", "tahinli"],
498+ &["create-user", "bob"],
499+ &["create-user", "dana"],
500+ ],
501+ );
601502 {
602503 let store = Store::open(&dir.join("forge.db"))
603504 .await
@@ -631,7 +532,7 @@ async fn org_member_pushes_over_https_through_a_write_team() {
631532 let bob = login(&http, "bob", PW).await;
632533 let dana = login(&http, "dana", PW).await;
633534
634- let csrf = csrf_for(&http, &tahinli).await;
535+ let csrf = csrf_for(&http, "/settings/keys", &tahinli).await;
635536 let res = http
636537 .post_form(
637538 "/new",
@@ -665,7 +566,8 @@ async fn org_member_pushes_over_https_through_a_write_team() {
665566 let team_url = location.split('?').next().expect("team path").to_owned();
666567 let team = http.get(&team_url, Some(&tahinli)).await;
667568 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");
669571 let res = http
670572 .post_form(
671573 &format!("{team_url}/repos/add"),
@@ -683,8 +585,8 @@ async fn org_member_pushes_over_https_through_a_write_team() {
683585 .await;
684586 assert_eq!(res.status, 303, "bob joins writers");
685587
686- let bob_token = create_token(&http, &bob).await;
687- let dana_token = create_token(&http, &dana).await;
588+ let bob_token = create_token(&http, &bob, "e2e").await;
589+ let dana_token = create_token(&http, &dana, "e2e").await;
688590 let bob_url = format!(
689591 "http://bob:{bob_token}@127.0.0.1:{}/acme/pushme.git",
690592 ports.http
@@ -701,7 +603,7 @@ async fn org_member_pushes_over_https_through_a_write_team() {
701603 let work_str = work.to_str().expect("utf8 path");
702604 let clone = git(&dir, &["clone", &bob_url, work_str]);
703605 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");
705607 let push = git(&work, &["push", "origin", "HEAD:main"]);
706608 assert!(push.status.success(), "bob pushes: {}", describe(&push));
707609 }
crates/forge-e2e/tests/e2e/packages_e2e.rsmodified+7 -27
@@ -1,4 +1,4 @@
1-use crate::common::{Server, bin, describe, launch, pick_ports, write_config};
1+use crate::common::{Server, launch, provision};
22 use std::io::Write;
33 use std::path::Path;
44 use std::process::Command;
@@ -9,8 +9,6 @@ use forge_core::token::{generate_token, hash_token};
99 use forge_core::{Store, User};
1010 use sha2::{Digest, Sha256};
1111
12-const PW: &str = "tahinli-password-123";
13-
1412 const DEMO_INDEX: &str = "/api/packages/tahinli/cargo/de/mo/demo-crate";
1513 const PUBLISH: &str = "/api/packages/tahinli/cargo/api/v1/crates/new";
1614
@@ -81,22 +79,6 @@ impl Http {
8179 }
8280 }
8381
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-
10082 struct Env {
10183 _root: tempfile::TempDir,
10284 _server: Server,
@@ -108,15 +90,13 @@ where
10890 F: FnOnce(Store) -> Fut,
10991 Fut: std::future::Future<Output = ()>,
11092 {
111- let root = tempfile::Builder::new()
112- .prefix("fpk")
113- .tempdir_in("/tmp")
114- .expect("temp dir");
93+ let root = crate::common::temp_dir("fpk");
11594 let dir = root.path().to_path_buf();
116- let ports = pick_ports();
117- let config = write_config(&dir, ports);
118- admin(&config, &["create-user", "tahinli"]);
119- admin(&config, &["create-user", "bob"]);
95+ let (_, ports) = provision(
96+ &dir,
97+ "",
98+ &[&["create-user", "tahinli"], &["create-user", "bob"]],
99+ );
120100 let store = Store::open(&dir.join("forge.db"))
121101 .await
122102 .expect("open store");
crates/forge-e2e/tests/e2e/pulls_e2e.rsmodified+56 -178
@@ -1,85 +1,25 @@
11 use crate::common::{
2- Http, Resp, Server, create_token, input_value, launch, login, pick_ports, run_admin,
3- tool_on_path, write_config,
2+ BOB_CMD, Http, PW, Resp, Server, TAHINLI_CMD, assert_quiet, boot_forge, clone, commit,
3+ create_repo, create_token, csrf_for, git_text, login, next_changed, temp_dir, text_or_empty,
4+ tool_on_path,
45 };
56 use std::fs;
67 use std::path::{Path, PathBuf};
7-use std::process::{Command, Output};
88 use std::time::{Duration, Instant};
99
10-use reqwest::header::{AUTHORIZATION, CONTENT_TYPE, COOKIE};
10+use reqwest::header::{AUTHORIZATION, CONTENT_TYPE};
1111
12-const TAHINLI_PW: &str = "tahinli-password-123";
13-const BOB_PW: &str = "bob-password-4567";
1412 const BOB_EMAIL: &str = "bob@users.noreply.127.0.0.1";
1513 const REPO_PATH: &str = "/tahinli/r";
1614 const TAHINLI: (&str, &str) = ("tahinli", "tahinli@example.test");
1715 const BOB: (&str, &str) = ("bob", BOB_EMAIL);
1816
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-
7717 fn remote(port: u16, user: &str, token: &str, owner: &str, repo: &str) -> String {
7818 format!("http://{user}:{token}@127.0.0.1:{port}/{owner}/{repo}.git")
7919 }
8020
8121 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}")]);
8323 out.split_whitespace()
8424 .next()
8525 .unwrap_or_else(|| panic!("branch {branch} missing on remote"))
@@ -87,40 +27,10 @@ fn remote_sha(dir: &Path, url: &str, branch: &str) -> String {
8727 }
8828
8929 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]);
9131 line.split_whitespace().count() - 1
9232 }
9333
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-
12434 struct Booted {
12535 _server: Server,
12636 _root: tempfile::TempDir,
@@ -137,17 +47,9 @@ async fn boot() -> Booted {
13747 if !tool_on_path("git") {
13848 panic!("`git` was not found on PATH");
13949 }
140- let root = tempfile::Builder::new()
141- .prefix("pr2e")
142- .tempdir_in("/tmp")
143- .expect("temp dir");
50+ let root = temp_dir("pr2e");
14451 let dir = root.path().to_path_buf();
145- let ports = pick_ports();
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;
52+ let (server, ports) = boot_forge(&dir, "", &[TAHINLI_CMD, BOB_CMD]).await;
15153 Booted {
15254 _server: server,
15355 _root: root,
@@ -158,15 +60,15 @@ async fn boot() -> Booted {
15860 }
15961
16062 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;
16264 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;
16466 let work = clone(
16567 &remote(b.http_port, "tahinli", &token, "tahinli", "r"),
16668 &b.dir.join("tahinli-work"),
16769 );
16870 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"]);
17072 (tahinli, token, work)
17173 }
17274
@@ -175,7 +77,7 @@ async fn open_pull(http: &Http, session: &str, base: &str, head: &str, title: &s
17577 .get_cookie(&format!("{REPO_PATH}/compare/{base}...{head}"), session)
17678 .await;
17779 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;
17981 let res = http
18082 .post_form(
18183 &format!("{REPO_PATH}/pulls"),
@@ -199,11 +101,7 @@ async fn open_pull(http: &Http, session: &str, base: &str, head: &str, title: &s
199101 }
200102
201103 async fn open_issue(http: &Http, session: &str, title: &str) -> u32 {
202- let page = http
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");
104+ let csrf = csrf_for(http, &format!("{REPO_PATH}/issues/new"), session).await;
207105 let res = http
208106 .post_form(
209107 &format!("{REPO_PATH}/issues/new"),
@@ -243,7 +141,7 @@ async fn wait_page(
243141 }
244142
245143 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;
247145 http.post_form(
248146 &format!("{REPO_PATH}/pulls/{number}/merge"),
249147 &[("csrf", &csrf), ("style", style), ("message", "")],
@@ -260,9 +158,9 @@ async fn same_repo_pull_merges_and_closes_issue() {
260158 let issue = open_issue(&b.http, &tahinli, "add x").await;
261159 assert_eq!(issue, 1);
262160
263- git(&work, &["checkout", "-q", "-b", "feature"]);
161+ git_text(&work, &["checkout", "-q", "-b", "feature"]);
264162 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"]);
266164
267165 let compare = b
268166 .http
@@ -295,7 +193,7 @@ async fn same_repo_pull_merges_and_closes_issue() {
295193 "main tip is a merge commit with two parents"
296194 );
297195 assert!(
298- git(&check, &["log", "--format=%s", "-n", "5"]).contains("Add x"),
196+ git_text(&check, &["log", "--format=%s", "-n", "5"]).contains("Add x"),
299197 "feature commit reachable from main"
300198 );
301199
@@ -303,14 +201,17 @@ async fn same_repo_pull_merges_and_closes_issue() {
303201 .http
304202 .get_cookie(&format!("{REPO_PATH}/pulls/2"), &tahinli)
305203 .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+ );
307208
308209 wait_page(
309210 &b.http,
310211 &tahinli,
311212 &format!("{REPO_PATH}/issues/1"),
312213 "issue closed",
313- |body| state_badge(body) == "Closed",
214+ |body| text_or_empty(body, ".head-sub > .badge, .head-sub > .issue-badge") == "Closed",
314215 )
315216 .await;
316217 }
@@ -320,13 +221,13 @@ async fn push_to_head_branch_updates_open_pull() {
320221 let b = boot().await;
321222 let (tahinli, _token, work) = tahinli_repo_with_main(&b).await;
322223
323- git(&work, &["checkout", "-q", "-b", "feature2"]);
224+ git_text(&work, &["checkout", "-q", "-b", "feature2"]);
324225 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"]);
326227 let number = open_pull(&b.http, &tahinli, "main", "feature2", "Feature two").await;
327228
328229 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"]);
330231
331232 let path = format!("{REPO_PATH}/pulls/{number}");
332233 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() {
351252 assert!(commits.body.contains(&second[..7]), "new commit sha shown");
352253 }
353254
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-
386255 #[tokio::test]
387256 async fn pull_pages_follow_writes_live() {
388257 let b = boot().await;
389258 let (tahinli, token, work) = tahinli_repo_with_main(&b).await;
390259
391- git(&work, &["checkout", "-q", "-b", "live"]);
260+ git_text(&work, &["checkout", "-q", "-b", "live"]);
392261 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"]);
394263 let number = open_pull(&b.http, &tahinli, "main", "live", "Live pull").await;
395264 let pull = format!("{REPO_PATH}/pulls/{number}");
396265 let list = format!("{REPO_PATH}/pulls");
@@ -409,13 +278,19 @@ async fn pull_pages_follow_writes_live() {
409278 "pull list follows its stream"
410279 );
411280
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;
413285 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;
415290 assert_eq!(list_events.status().as_u16(), 200, "list stream");
416291 assert_quiet(&mut pull_events, "connecting to the pull stream").await;
417292
418- let csrf = csrf_token(&b.http, &tahinli).await;
293+ let csrf = csrf_for(&b.http, "/settings/keys", &tahinli).await;
419294 let res = b
420295 .http
421296 .post_form(
@@ -432,7 +307,7 @@ async fn pull_pages_follow_writes_live() {
432307 next_changed(&mut pull_events, "a comment").await;
433308 next_changed(&mut list_events, "a comment").await;
434309
435- let csrf = csrf_token(&b.http, &tahinli).await;
310+ let csrf = csrf_for(&b.http, "/settings/keys", &tahinli).await;
436311 let res = b
437312 .http
438313 .post_form(
@@ -450,7 +325,7 @@ async fn pull_pages_follow_writes_live() {
450325 next_changed(&mut pull_events, "a review").await;
451326
452327 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"]);
454329 next_changed(&mut pull_events, "a push to the head").await;
455330 next_changed(&mut list_events, "a push to the head").await;
456331
@@ -475,7 +350,7 @@ async fn pull_pages_follow_writes_live() {
475350 next_changed(&mut pull_events, "the merge").await;
476351 next_changed(&mut list_events, "the merge").await;
477352
478- let csrf = csrf_token(&b.http, &tahinli).await;
353+ let csrf = csrf_for(&b.http, "/settings/keys", &tahinli).await;
479354 let res = b
480355 .http
481356 .post_form(
@@ -491,11 +366,14 @@ async fn pull_pages_follow_writes_live() {
491366 )
492367 .await;
493368 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;
495370 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;
497372 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;
499377 assert_eq!(member.status().as_u16(), 200, "private list, owner");
500378 }
501379
@@ -504,10 +382,10 @@ async fn fork_pull_squash_merge_credits_contributor() {
504382 let b = boot().await;
505383 let (tahinli, tahinli_token, _work) = tahinli_repo_with_main(&b).await;
506384
507- let bob = login(&b.http, "bob", BOB_PW).await;
385+ let bob = login(&b.http, "bob", PW).await;
508386 let bob_token = create_token(&b.http, &bob, "bob-token").await;
509387
510- let csrf = csrf_token(&b.http, &bob).await;
388+ let csrf = csrf_for(&b.http, "/settings/keys", &bob).await;
511389 let fork = b
512390 .http
513391 .post_form(&format!("{REPO_PATH}/fork"), &[("csrf", &csrf)], Some(&bob))
@@ -517,9 +395,9 @@ async fn fork_pull_squash_merge_credits_contributor() {
517395
518396 let bob_url = remote(b.http_port, "bob", &bob_token, "bob", "r");
519397 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"]);
521399 let bob_head = commit(&bob_work, "bob.txt", "bob\n", "Bob change", BOB);
522- git(
400+ git_text(
523401 &bob_work,
524402 &["push", "-q", "origin", "HEAD:refs/heads/bob-feature"],
525403 );
@@ -536,12 +414,12 @@ async fn fork_pull_squash_merge_credits_contributor() {
536414 let check = clone(&tahinli_url, &b.dir.join("check"));
537415 assert_eq!(parent_count(&check, "HEAD"), 1, "squash makes one parent");
538416 assert_ne!(
539- git(&check, &["rev-parse", "HEAD"]),
417+ git_text(&check, &["rev-parse", "HEAD"]),
540418 bob_head,
541419 "main has a new squash commit, not bob's commit"
542420 );
543- assert_eq!(git(&check, &["log", "-1", "--format=%an"]), "bob");
544- assert_eq!(git(&check, &["log", "-1", "--format=%ae"]), BOB_EMAIL);
421+ assert_eq!(git_text(&check, &["log", "-1", "--format=%an"]), "bob");
422+ assert_eq!(git_text(&check, &["log", "-1", "--format=%ae"]), BOB_EMAIL);
545423 }
546424
547425 #[tokio::test]
@@ -549,14 +427,14 @@ async fn conflicting_pull_cannot_merge() {
549427 let b = boot().await;
550428 let (tahinli, token, work) = tahinli_repo_with_main(&b).await;
551429
552- git(&work, &["checkout", "-q", "-b", "conflict"]);
430+ git_text(&work, &["checkout", "-q", "-b", "conflict"]);
553431 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"]);
555433 let number = open_pull(&b.http, &tahinli, "main", "conflict", "Conflicting").await;
556434
557- git(&work, &["checkout", "-q", "main"]);
435+ git_text(&work, &["checkout", "-q", "main"]);
558436 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"]);
560438
561439 let path = format!("{REPO_PATH}/pulls/{number}");
562440 let page = wait_page(&b.http, &tahinli, &path, "conflict detection", |body| {
crates/forge-e2e/tests/e2e/repo_collaborators_e2e.rsmodified+16 -54
@@ -1,50 +1,10 @@
11 use crate::common::{
2- Http, bin, describe, input_value, launch, login, pick_ports, tool_on_path, with_cookie,
3- write_config,
2+ Http, PW, csrf_for, init_bare, launch, login, provision, tool_on_path, with_cookie,
43 };
5-use std::fs;
6-use std::path::Path;
7-use std::process::{Command, Output};
84
95 use forge_core::{Role, Store, Visibility};
106 use reqwest::header::LOCATION;
117
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-
488 async fn shown_role(http: &Http, session: &str, username: &str) -> Option<String> {
499 let page = http
5010 .get("/olivia/priv/settings/collaborators", Some(session))
@@ -68,19 +28,21 @@ async fn repo_collaborators_end_to_end() {
6828 return;
6929 }
7030
71- let root = tempfile::Builder::new()
72- .prefix("frc")
73- .tempdir_in("/tmp")
74- .expect("temp dir");
31+ let root = crate::common::temp_dir("frc");
7532 let dir = root.path().to_path_buf();
7633
77- let ports = pick_ports();
78- let config = write_config(&dir, ports);
79-
80- admin(&config, &["create-user", "root", "--admin"]);
81- for name in ["olivia", "bob", "carol", "dana", "wendy"] {
82- admin(&config, &["create-user", name]);
83- }
34+ let (_, ports) = provision(
35+ &dir,
36+ "",
37+ &[
38+ &["create-user", "root", "--admin"],
39+ &["create-user", "olivia"],
40+ &["create-user", "bob"],
41+ &["create-user", "carol"],
42+ &["create-user", "dana"],
43+ &["create-user", "wendy"],
44+ ],
45+ );
8446
8547 let (bob_id, carol_id, dana_id) = {
8648 let store = Store::open(&dir.join("forge.db"))
@@ -142,7 +104,7 @@ async fn repo_collaborators_end_to_end() {
142104 let owner_page = http.get(page, Some(&olivia)).await;
143105 assert_eq!(owner_page.status, 200, "owner page");
144106
145- let csrf = csrf_for(&http, &olivia).await;
107+ let csrf = csrf_for(&http, "/settings/keys", &olivia).await;
146108 let res = http
147109 .post_form(
148110 add,
@@ -273,7 +235,7 @@ async fn repo_collaborators_end_to_end() {
273235 "CSRF failure added bob"
274236 );
275237
276- let carol_csrf = csrf_for(&http, &carol).await;
238+ let carol_csrf = csrf_for(&http, "/settings/keys", &carol).await;
277239 assert_eq!(http.get(page, Some(&carol)).await.status, 200, "carol page");
278240 let res = http
279241 .post_form(
crates/forge-e2e/tests/e2e/repo_rename_e2e.rsmodified+22 -130
@@ -1,74 +1,13 @@
11 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,
34 };
4-use std::fs;
5-use std::path::Path;
6-use std::process::{Command, Output};
75
86 use forge_core::{Role, Store, Visibility};
97 use reqwest::header::LOCATION;
108
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-
689 async fn create_repo_web(http: &Http, session: &str, name: &str) -> Resp {
69- let page = http.get("/new", Some(session)).await;
70- assert_eq!(page.status, 200, "GET /new");
71- let csrf = input_value(&page.body, "csrf");
10+ let csrf = csrf_for(http, "/new", session).await;
7211 http.post_form(
7312 "/new",
7413 &[
@@ -83,54 +22,6 @@ async fn create_repo_web(http: &Http, session: &str, name: &str) -> Resp {
8322 .await
8423 }
8524
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-
13425 #[tokio::test]
13526 async fn repo_rename_end_to_end() {
13627 if !tool_on_path("git") {
@@ -138,18 +29,19 @@ async fn repo_rename_end_to_end() {
13829 return;
13930 }
14031
141- let root = tempfile::Builder::new()
142- .prefix("frn")
143- .tempdir_in("/tmp")
144- .expect("temp dir");
32+ let root = crate::common::temp_dir("frn");
14533 let dir = root.path().to_path_buf();
146- let ports = pick_ports();
147- let config = write_config(&dir, ports);
148-
149- admin(&config, &["create-user", "tahinli", "--admin"]);
150- for name in ["bob", "carol", "dave", "eve"] {
151- admin(&config, &["create-user", name]);
152- }
34+ let (_, ports) = provision(
35+ &dir,
36+ "",
37+ &[
38+ &["create-user", "tahinli", "--admin"],
39+ &["create-user", "bob"],
40+ &["create-user", "carol"],
41+ &["create-user", "dave"],
42+ &["create-user", "eve"],
43+ ],
44+ );
15345 {
15446 let store = Store::open(&dir.join("forge.db"))
15547 .await
@@ -213,7 +105,7 @@ async fn repo_rename_end_to_end() {
213105 let tree = http.get("/bob/pub/tree/main/src", None).await;
214106 assert_eq!(tree.status, 200, "tree before rename");
215107
216- let csrf = csrf_for(&http, &bob).await;
108+ let csrf = csrf_for(&http, "/settings/keys", &bob).await;
217109 let renamed = http
218110 .post_form(
219111 "/bob/pub/settings/rename",
@@ -287,7 +179,7 @@ async fn repo_rename_end_to_end() {
287179 );
288180 assert!(new_clone.join("src/lib.rs").exists());
289181
290- let csrf = csrf_for(&http, &bob).await;
182+ let csrf = csrf_for(&http, "/settings/keys", &bob).await;
291183 let taken = http
292184 .post_form(
293185 "/bob/newpub/settings/rename",
@@ -312,7 +204,7 @@ async fn repo_rename_end_to_end() {
312204 "name unchanged after rejected renames"
313205 );
314206
315- let carol_csrf = csrf_for(&http, &carol).await;
207+ let carol_csrf = csrf_for(&http, "/settings/keys", &carol).await;
316208 let carol_rename = http
317209 .post_form(
318210 "/bob/newpub/settings/rename",
@@ -323,7 +215,7 @@ async fn repo_rename_end_to_end() {
323215 assert_eq!(carol_rename.status, 403, "write collaborator rename");
324216 assert_eq!(http.get("/bob/newpub", None).await.status, 200);
325217
326- let dave_csrf = csrf_for(&http, &dave).await;
218+ let dave_csrf = csrf_for(&http, "/settings/keys", &dave).await;
327219 let dave_transfer = http
328220 .post_form(
329221 "/bob/newpub/settings/transfer",
@@ -338,7 +230,7 @@ async fn repo_rename_end_to_end() {
338230 assert_eq!(dave_transfer.status, 403, "admin collaborator transfer");
339231 assert_eq!(http.get("/bob/newpub", None).await.status, 200);
340232
341- let csrf = csrf_for(&http, &bob).await;
233+ let csrf = csrf_for(&http, "/settings/keys", &bob).await;
342234 let transfer_wrong = http
343235 .post_form(
344236 "/bob/newpub/settings/transfer",
@@ -379,7 +271,7 @@ async fn repo_rename_end_to_end() {
379271 assert!(offered.body.contains("Pending transfer to carol"));
380272 let inbox = http.get("/notifications", Some(&carol)).await;
381273 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;
383275 let accepted = http
384276 .post_form(
385277 &accept_action,
@@ -431,7 +323,7 @@ async fn repo_rename_end_to_end() {
431323 "the other old name still redirects"
432324 );
433325
434- let csrf = csrf_for(&http, &bob).await;
326+ let csrf = csrf_for(&http, "/settings/keys", &bob).await;
435327 let secret_rename = http
436328 .post_form(
437329 "/bob/secret/settings/rename",
crates/forge-e2e/tests/e2e/repo_settings_e2e.rsmodified+53 -96
@@ -1,50 +1,14 @@
11 use crate::common::{
2- Http, bin, cookie_named, describe, input_value, launch, login, pick_ports, tool_on_path,
3- with_cookie, write_config,
2+ Http, PW, admin, attr_of, cookie_named, csrf_for, describe, init_bare, input_value, launch,
3+ login, provision, tool_on_path, with_cookie,
44 };
55 use std::fs;
66 use std::path::{Path, PathBuf};
7-use std::process::{Command, Output};
7+use std::process::Command;
88
99 use forge_core::{Role, Store, Visibility};
1010 use reqwest::header::LOCATION;
1111
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-
4812 fn trash_entries(data_dir: &Path, repo_id: &str) -> Vec<PathBuf> {
4913 let prefix = format!("{}-", repo_id.to_ascii_lowercase());
5014 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() {
6731 return;
6832 }
6933
70- let root = tempfile::Builder::new()
71- .prefix("frs")
72- .tempdir_in("/tmp")
73- .expect("temp dir");
34+ let root = crate::common::temp_dir("frs");
7435 let dir = root.path().to_path_buf();
7536
76- let ports = pick_ports();
77- let config = write_config(&dir, ports);
78-
79- admin(&config, &["create-user", "tahinli", "--admin"]);
80- admin(&config, &["create-user", "bob"]);
81- admin(&config, &["create-user", "carol"]);
37+ let (config, ports) = provision(
38+ &dir,
39+ "",
40+ &[
41+ &["create-user", "tahinli", "--admin"],
42+ &["create-user", "bob"],
43+ &["create-user", "carol"],
44+ ],
45+ );
8246
8347 let (public_id, private_id) = {
8448 let store = Store::open(&dir.join("forge.db"))
@@ -125,7 +89,7 @@ async fn repo_settings_end_to_end() {
12589 !carol_page.body.contains("/bob/priv/settings/delete\""),
12690 "admin collaborator must not see the delete form"
12791 );
128- let carol_csrf = csrf_for(&http, &carol).await;
92+ let carol_csrf = csrf_for(&http, "/settings/keys", &carol).await;
12993 let carol_delete = http
13094 .post_form(
13195 "/bob/priv/settings/delete",
@@ -156,7 +120,7 @@ async fn repo_settings_end_to_end() {
156120 "Settings tab shows to an Admin collaborator"
157121 );
158122
159- let owner_csrf = csrf_for(&http, &bob).await;
123+ let owner_csrf = csrf_for(&http, "/settings/keys", &bob).await;
160124 let wrong = http
161125 .post_form(
162126 "/bob/pub/settings/delete",
@@ -235,7 +199,7 @@ async fn repo_settings_end_to_end() {
235199
236200 let admin_page = http.get("/bob/priv/settings", Some(&tahinli)).await;
237201 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;
239203 let admin_delete = http
240204 .post_form(
241205 "/bob/priv/settings/delete",
@@ -282,14 +246,9 @@ async fn repo_settings_deletes_rows_when_repo_dir_is_missing() {
282246 return;
283247 }
284248
285- let root = tempfile::Builder::new()
286- .prefix("frm")
287- .tempdir_in("/tmp")
288- .expect("temp dir");
249+ let root = crate::common::temp_dir("frm");
289250 let dir = root.path().to_path_buf();
290- let ports = pick_ports();
291- let config = write_config(&dir, ports);
292- admin(&config, &["create-user", "bob"]);
251+ let (_, ports) = provision(&dir, "", &[&["create-user", "bob"]]);
293252
294253 let (repo_id, bare_dir) = {
295254 let store = Store::open(&dir.join("forge.db"))
@@ -309,7 +268,7 @@ async fn repo_settings_deletes_rows_when_repo_dir_is_missing() {
309268 let (server, ports) = launch(&dir, ports).await;
310269 let http = Http::new(ports.http);
311270 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;
313272 let deleted = http
314273 .post_form(
315274 "/bob/gone/settings/delete",
@@ -380,18 +339,18 @@ async fn branch_protection_end_to_end() {
380339 return;
381340 }
382341
383- let root = tempfile::Builder::new()
384- .prefix("frb")
385- .tempdir_in("/tmp")
386- .expect("temp dir");
342+ let root = crate::common::temp_dir("frb");
387343 let dir = root.path().to_path_buf();
388- let ports = pick_ports();
389- let config = write_config(&dir, ports);
390-
391- admin(&config, &["create-user", "tahinli", "--admin"]);
392- admin(&config, &["create-user", "bob"]);
393- admin(&config, &["create-user", "carol"]);
394- admin(&config, &["create-user", "dan"]);
344+ let (_, ports) = provision(
345+ &dir,
346+ "",
347+ &[
348+ &["create-user", "tahinli", "--admin"],
349+ &["create-user", "bob"],
350+ &["create-user", "carol"],
351+ &["create-user", "dan"],
352+ ],
353+ );
395354
396355 {
397356 let store = Store::open(&dir.join("forge.db"))
@@ -446,7 +405,7 @@ async fn branch_protection_end_to_end() {
446405 "main",
447406 "pattern is prefilled with the default branch"
448407 );
449- let owner_csrf = csrf_for(&http, &bob).await;
408+ let owner_csrf = csrf_for(&http, "/settings/keys", &bob).await;
450409
451410 let added = http
452411 .post_form(
@@ -602,7 +561,7 @@ async fn branch_protection_end_to_end() {
602561 .get("/bob/app/settings?section=branches", Some(&dan))
603562 .await;
604563 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;
606565 let dan_save = http
607566 .post_form(
608567 "/bob/app/settings/branches",
@@ -638,7 +597,7 @@ async fn branch_protection_end_to_end() {
638597 .contains("href=\"/bob/app/settings\""),
639598 "Settings tab shows for an Admin collaborator"
640599 );
641- let carol_csrf = csrf_for(&http, &carol).await;
600+ let carol_csrf = csrf_for(&http, "/settings/keys", &carol).await;
642601 let carol_save = http
643602 .post_form(
644603 "/bob/app/settings/branches",
@@ -746,13 +705,11 @@ fn git_head(data_dir: &Path, repo_id: &str) -> String {
746705 }
747706
748707 fn selected_branch(body: &str) -> Option<String> {
749- let doc = scraper::Html::parse_document(body);
750- let selector =
751- scraper::Selector::parse("select[name=\"default_branch\"] option[selected]").expect("sel");
752- doc.select(&selector)
753- .next()
754- .and_then(|el| el.value().attr("value"))
755- .map(str::to_owned)
708+ attr_of(
709+ body,
710+ "select[name=\"default_branch\"] option[selected]",
711+ "value",
712+ )
756713 }
757714
758715 #[tokio::test]
@@ -762,17 +719,17 @@ async fn general_settings_end_to_end() {
762719 return;
763720 }
764721
765- let root = tempfile::Builder::new()
766- .prefix("fgen")
767- .tempdir_in("/tmp")
768- .expect("temp dir");
722+ let root = crate::common::temp_dir("fgen");
769723 let dir = root.path().to_path_buf();
770- let ports = pick_ports();
771- let config = write_config(&dir, ports);
772-
773- admin(&config, &["create-user", "tahinli", "--admin"]);
774- admin(&config, &["create-user", "bob"]);
775- admin(&config, &["create-user", "carol"]);
724+ let (_, ports) = provision(
725+ &dir,
726+ "",
727+ &[
728+ &["create-user", "tahinli", "--admin"],
729+ &["create-user", "bob"],
730+ &["create-user", "carol"],
731+ ],
732+ );
776733
777734 let gen_id = {
778735 let store = Store::open(&dir.join("forge.db"))
@@ -823,7 +780,7 @@ async fn general_settings_end_to_end() {
823780 .contains("href=\"/bob/gen/settings?section=danger\"")
824781 );
825782
826- let csrf = csrf_for(&http, &bob).await;
783+ let csrf = csrf_for(&http, "/settings/keys", &bob).await;
827784 let saved = http
828785 .post_form(
829786 "/bob/gen/settings/general",
@@ -907,7 +864,7 @@ async fn general_settings_end_to_end() {
907864 .await;
908865 assert!(long_page.body.contains("at most 350 characters"));
909866
910- let vis_csrf = csrf_for(&http, &bob).await;
867+ let vis_csrf = csrf_for(&http, "/settings/keys", &bob).await;
911868 let no_ack = http
912869 .post_form(
913870 "/bob/gen/settings/visibility",
@@ -961,7 +918,7 @@ async fn general_settings_end_to_end() {
961918 "anonymous on public"
962919 );
963920
964- let arch_csrf = csrf_for(&http, &bob).await;
921+ let arch_csrf = csrf_for(&http, "/settings/keys", &bob).await;
965922 let archive = http
966923 .post_form(
967924 "/bob/gen/settings/archive",
@@ -996,7 +953,7 @@ async fn general_settings_end_to_end() {
996953
997954 let carol_page = http.get("/bob/gen/settings", Some(&carol)).await;
998955 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;
1000957 let carol_general = http
1001958 .post_form(
1002959 "/bob/gen/settings/general",
@@ -1055,7 +1012,7 @@ async fn general_settings_end_to_end() {
10551012 "empty repo notice"
10561013 );
10571014 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;
10591016 let empty_save = http
10601017 .post_form(
10611018 "/bob/empty/settings/general",
crates/forge-e2e/tests/e2e/repo_transfer_e2e.rsmodified+16 -58
@@ -1,49 +1,13 @@
11 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,
33 };
4-use std::fs;
5-use std::process::Command;
64
75 use forge_core::store::orgs::OrgMemberRole;
86 use forge_core::{Store, Visibility};
97 use reqwest::header::LOCATION;
108
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-
459 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;
4711 http.post_form(
4812 &format!("/{owner}/{repo}/settings/transfer"),
4913 &[
@@ -59,7 +23,7 @@ async fn offer(http: &Http, session: &str, owner: &str, repo: &str, to: &str) ->
5923 async fn act_from(http: &Http, session: &str, page: &str, suffix: &str) -> Resp {
6024 let body = http.get(page, Some(session)).await.body;
6125 let action = form_action(&body, suffix);
62- let csrf = csrf_for(http, session).await;
26+ let csrf = csrf_for(http, "/settings/keys", session).await;
6327 http.post_form(&action, &[("csrf", &csrf)], Some(session))
6428 .await
6529 }
@@ -71,18 +35,19 @@ async fn repo_transfer_offers_declines_cancels_and_org_targets() {
7135 return;
7236 }
7337
74- let root = tempfile::Builder::new()
75- .prefix("frt")
76- .tempdir_in("/tmp")
77- .expect("temp dir");
38+ let root = crate::common::temp_dir("frt");
7839 let dir = root.path().to_path_buf();
79- let ports = pick_ports();
80- let config = write_config(&dir, ports);
81-
82- admin(&config, &["create-user", "tahinli", "--admin"]);
83- for name in ["bob", "carol", "dave", "eve"] {
84- admin(&config, &["create-user", name]);
85- }
40+ let (_, ports) = provision(
41+ &dir,
42+ "",
43+ &[
44+ &["create-user", "tahinli", "--admin"],
45+ &["create-user", "bob"],
46+ &["create-user", "carol"],
47+ &["create-user", "dave"],
48+ &["create-user", "eve"],
49+ ],
50+ );
8651 {
8752 let store = Store::open(&dir.join("forge.db"))
8853 .await
@@ -108,14 +73,7 @@ async fn repo_transfer_offers_declines_cancels_and_org_targets() {
10873 .await
10974 .expect("eve member");
11075 for repo in [&priv_repo, &pub_repo] {
111- let path = forge_git::repo::repo_path(&dir, &repo.id).expect("repo path");
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));
76+ init_bare(&dir, &repo.id);
11977 }
12078 }
12179
crates/forge-e2e/tests/e2e/section_nav_e2e.rsmodified+2 -25
@@ -1,24 +1,4 @@
1-use crate::common::{Http, Server, bin, describe, launch, login, pick_ports, write_config};
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-}
1+use crate::common::{Http, PW, Server, boot_forge, login};
222
233 struct Env {
244 _root: tempfile::TempDir,
@@ -29,10 +9,7 @@ struct Env {
299 async fn start() -> Env {
3010 let root = tempfile::tempdir().expect("temp dir");
3111 let dir = root.path().to_path_buf();
32- let ports = pick_ports();
33- let config = write_config(&dir, ports);
34- admin(&config, &["create-user", "tahinli", "--admin"]);
35- let (server, ports) = launch(&dir, ports).await;
12+ let (server, ports) = boot_forge(&dir, "", &[&["create-user", "tahinli", "--admin"]]).await;
3613 let http = Http::new(ports.http);
3714 Env {
3815 _root: root,
crates/forge-e2e/tests/e2e/snippets_e2e.rsmodified+15 -51
@@ -1,13 +1,8 @@
1-use crate::common::{
2- Http, Server, bin, describe, input_value, launch, login, next_changed, pick_ports, write_config,
3-};
4-use std::path::{Path, PathBuf};
5-use std::process::Command;
1+use crate::common::{Http, PW, Server, boot_forge, csrf_for, login, next_changed};
2+use std::path::PathBuf;
63
74 use reqwest::header::{CONTENT_TYPE, LOCATION};
85
9-const PW: &str = "tahinli-password-123";
10-
116 fn path_of(url: &str) -> String {
127 let rest = url.split_once("//").map_or(url, |(_, r)| r);
138 match rest.find('/') {
@@ -26,22 +21,6 @@ fn link_href(body: &str, text: &str) -> String {
2621 .to_owned()
2722 }
2823
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-
4524 struct Env {
4625 _root: tempfile::TempDir,
4726 _server: Server,
@@ -52,11 +31,12 @@ struct Env {
5231 async fn start() -> Env {
5332 let root = tempfile::tempdir().expect("temp dir");
5433 let dir: PathBuf = root.path().to_path_buf();
55- let ports = pick_ports();
56- let config = write_config(&dir, ports);
57- admin(&config, &["create-user", "tahinli"]);
58- admin(&config, &["create-user", "bob"]);
59- let (server, ports) = launch(&dir, ports).await;
34+ let (server, ports) = boot_forge(
35+ &dir,
36+ "",
37+ &[&["create-user", "tahinli"], &["create-user", "bob"]],
38+ )
39+ .await;
6040 Env {
6141 _root: root,
6242 _server: server,
@@ -72,9 +52,7 @@ async fn create(
7252 visibility: &str,
7353 files: &[(&str, &str)],
7454 ) -> String {
75- let page = http.get("/snippets/new", Some(cookie)).await;
76- assert_eq!(page.status, 200, "GET /snippets/new");
77- let csrf = input_value(&page.body, "csrf");
55+ let csrf = csrf_for(http, "/snippets/new", cookie).await;
7856 let mut form: Vec<(String, String)> = vec![
7957 ("csrf".into(), csrf),
8058 ("title".into(), title.into()),
@@ -133,7 +111,7 @@ async fn snippet_streams_follow_writes() {
133111 assert_eq!(item_events.status().as_u16(), 200, "snippet stream");
134112
135113 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;
137115 let saved = env
138116 .app
139117 .post_form(
@@ -163,13 +141,7 @@ async fn snippet_streams_follow_writes() {
163141 .await;
164142 next_changed(&mut list_events, "a create").await;
165143
166- let csrf = input_value(
167- &env.app
168- .get(&format!("/snippets/{other}"), Some(&tahinli))
169- .await
170- .body,
171- "csrf",
172- );
144+ let csrf = csrf_for(&env.app, &format!("/snippets/{other}"), &tahinli).await;
173145 let deleted = env
174146 .app
175147 .post_form(
@@ -233,9 +205,7 @@ async fn create_edit_and_revisions() {
233205 assert!(view.body.contains("hello"), "file contents are shown");
234206
235207 let edit_path = format!("/snippets/{id}/edit");
236- let page = env.app.get(&edit_path, Some(&tahinli)).await;
237- assert_eq!(page.status, 200, "GET edit");
238- let csrf = input_value(&page.body, "csrf");
208+ let csrf = csrf_for(&env.app, &edit_path, &tahinli).await;
239209 let saved = env
240210 .app
241211 .post_form(
@@ -317,8 +287,7 @@ async fn private_snippet_is_hidden_from_others() {
317287 .get(&format!("/snippets/{id}/edit"), Some(&bob))
318288 .await;
319289 assert_eq!(page.status, 404, "bob cannot open the editor");
320- let bob_page = env.app.get("/snippets/new", Some(&bob)).await;
321- let bob_csrf = input_value(&bob_page.body, "csrf");
290+ let bob_csrf = csrf_for(&env.app, "/snippets/new", &bob).await;
322291 let res = env
323292 .app
324293 .post_form(
@@ -414,11 +383,7 @@ async fn unlisted_is_by_link_only_and_delete_removes_it() {
414383 200
415384 );
416385
417- let page = env
418- .app
419- .get(&format!("/snippets/{id}"), Some(&tahinli))
420- .await;
421- let csrf = input_value(&page.body, "csrf");
386+ let csrf = csrf_for(&env.app, &format!("/snippets/{id}"), &tahinli).await;
422387 let res = env
423388 .app
424389 .post_form(
@@ -438,8 +403,7 @@ async fn unlisted_is_by_link_only_and_delete_removes_it() {
438403 async fn bad_input_redisplays_the_form_with_an_error() {
439404 let env = start().await;
440405 let tahinli = login(&env.app, "tahinli", PW).await;
441- let page = env.app.get("/snippets/new", Some(&tahinli)).await;
442- let csrf = input_value(&page.body, "csrf");
406+ let csrf = csrf_for(&env.app, "/snippets/new", &tahinli).await;
443407 let res = env
444408 .app
445409 .post_form(
crates/forge-e2e/tests/e2e/stars_e2e.rsmodified+9 -13
@@ -1,6 +1,5 @@
11 use crate::common::{
2- Http, PW, Resp, Server, admin, describe, init_bare, input_value, launch, login, pick_ports,
3- tool_on_path, write_config,
2+ Http, PW, Resp, Server, csrf_for, describe, init_bare, launch, login, provision, tool_on_path,
43 };
54 use std::path::{Path, PathBuf};
65 use std::process::{Command, Stdio};
@@ -19,15 +18,13 @@ where
1918 F: FnOnce(PathBuf, Store) -> Fut,
2019 Fut: std::future::Future<Output = ()>,
2120 {
22- let root = tempfile::Builder::new()
23- .prefix("fst")
24- .tempdir_in("/tmp")
25- .expect("temp dir");
21+ let root = crate::common::temp_dir("fst");
2622 let dir = root.path().to_path_buf();
27- let ports = pick_ports();
28- let config = write_config(&dir, ports);
29- admin(&config, &["create-user", "tahinli"]);
30- admin(&config, &["create-user", "bob"]);
23+ let (_, ports) = provision(
24+ &dir,
25+ "",
26+ &[&["create-user", "tahinli"], &["create-user", "bob"]],
27+ );
3128 let store = Store::open(&dir.join("forge.db"))
3229 .await
3330 .expect("open store");
@@ -139,7 +136,7 @@ async fn star_round_trip_shows_the_count() {
139136 "star button with zero: {}",
140137 page.body
141138 );
142- let csrf = input_value(&page.body, "csrf");
139+ let csrf = csrf_for(&env.http, "/tahinli/pub", &bob).await;
143140
144141 let res = post_star(&env.http, "/tahinli/pub/star", &csrf, Some(&bob), None).await;
145142 assert_eq!(res.status, 303, "star: {}", res.body);
@@ -231,8 +228,7 @@ async fn explore_lists_public_repos_and_searches_literally() {
231228 assert_eq!(repo_names(&page.body), vec!["tahinli/pct%x".to_owned()]);
232229
233230 let bob = login(&env.http, "bob", PW).await;
234- let page = env.http.get("/tahinli/pub", Some(&bob)).await;
235- let csrf = input_value(&page.body, "csrf");
231+ let csrf = csrf_for(&env.http, "/tahinli/pub", &bob).await;
236232 let res = post_star(&env.http, "/tahinli/pub/star", &csrf, Some(&bob), None).await;
237233 assert_eq!(res.status, 303);
238234 let by_name = repo_names(&env.http.get("/explore?sort=name", None).await.body);
crates/forge-e2e/tests/e2e/ui_prefs_e2e.rsmodified+26 -62
@@ -1,19 +1,11 @@
1-use crate::common::{
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;
1+use crate::common::{Http, PW, Server, attr_of, boot_forge, cookie_named, csrf_for, login};
62
7-const PW: &str = "tahinli-password-123";
8-
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)
3+fn html_attr(body: &str, name: &str) -> Option<String> {
4+ attr_of(body, "html", name)
125 }
136
14-fn html_attr(body: &str, name: &str) -> Option<String> {
15- let doc = scraper::Html::parse_document(body);
16- doc.root_element().attr(name).map(str::to_owned)
7+fn html_theme(body: &str) -> Option<String> {
8+ html_attr(body, "data-theme")
179 }
1810
1911 fn html_colours(body: &str) -> [Option<String>; 4] {
@@ -35,26 +27,21 @@ fn checked_colours(body: &str) -> [Option<String>; 4] {
3527 }
3628
3729 fn checked_radio(body: &str, name: &str) -> Option<String> {
38- let doc = scraper::Html::parse_document(body);
39- let selector =
40- scraper::Selector::parse(&format!("input[type=\"radio\"][name=\"{name}\"][checked]"))
41- .expect("selector");
42- doc.select(&selector)
43- .next()
44- .and_then(|el| el.value().attr("value"))
45- .map(str::to_owned)
30+ attr_of(
31+ body,
32+ &format!("input[type=\"radio\"][name=\"{name}\"][checked]"),
33+ "value",
34+ )
4635 }
4736
4837 fn selected_option(body: &str, select: &str) -> Option<String> {
49- let doc = scraper::Html::parse_document(body);
50- let selector = scraper::Selector::parse(&format!(
51- "select[name=\"{select}\"] option[selected], input[name=\"{select}\"][checked], button[name=\"{select}\"][aria-pressed=\"true\"]"
52- ))
53- .expect("selector");
54- doc.select(&selector)
55- .next()
56- .and_then(|el| el.value().attr("value"))
57- .map(str::to_owned)
38+ attr_of(
39+ body,
40+ &format!(
41+ "select[name=\"{select}\"] option[selected], input[name=\"{select}\"][checked], button[name=\"{select}\"][aria-pressed=\"true\"]"
42+ ),
43+ "value",
44+ )
5845 }
5946
6047 fn theme_button(body: &str) -> (String, String) {
@@ -81,22 +68,6 @@ fn theme_button(body: &str) -> (String, String) {
8168 (value, label)
8269 }
8370
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-
10071 struct Env {
10172 _root: tempfile::TempDir,
10273 _server: Server,
@@ -106,10 +77,7 @@ struct Env {
10677 async fn start() -> Env {
10778 let root = tempfile::tempdir().expect("temp dir");
10879 let dir = root.path().to_path_buf();
109- let ports = pick_ports();
110- let config = write_config(&dir, ports);
111- admin(&config, &["create-user", "tahinli"]);
112- let (server, ports) = launch(&dir, ports).await;
80+ let (server, ports) = boot_forge(&dir, "", &[&["create-user", "tahinli"]]).await;
11381 let http = Http::new(ports.http);
11482 Env {
11583 _root: root,
@@ -134,7 +102,7 @@ async fn appearance_setting_persists_and_renders_the_html_attribute() {
134102 Some("light"),
135103 "the default is light, which renders data-theme=light"
136104 );
137- let csrf = input_value(&page.body, "csrf");
105+ let csrf = csrf_for(&env.http, "/settings/appearance", &session).await;
138106
139107 let saved = env
140108 .http
@@ -205,7 +173,7 @@ async fn light_and_dark_colours_save_independently_and_render_on_html() {
205173 let defaults = ["sage", "sage", "ink", "ink"].map(str::to_owned);
206174 assert_eq!(checked_colours(&page.body), defaults.clone().map(Some));
207175 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;
209177
210178 let saved = env
211179 .http
@@ -325,8 +293,7 @@ async fn a_save_without_colour_fields_keeps_the_stored_colours() {
325293 let env = start().await;
326294 let session = login(&env.http, "tahinli", PW).await;
327295
328- let page = env.http.get("/settings/appearance", Some(&session)).await;
329- let csrf = input_value(&page.body, "csrf");
296+ let csrf = csrf_for(&env.http, "/settings/appearance", &session).await;
330297 let saved = env
331298 .http
332299 .post_form(
@@ -392,8 +359,7 @@ async fn appearance_save_without_a_valid_csrf_token_is_403() {
392359 async fn unoffered_theme_or_language_is_rejected_and_nothing_is_saved() {
393360 let env = start().await;
394361 let session = login(&env.http, "tahinli", PW).await;
395- let page = env.http.get("/settings/appearance", Some(&session)).await;
396- let csrf = input_value(&page.body, "csrf");
362+ let csrf = csrf_for(&env.http, "/settings/appearance", &session).await;
397363 for form in [
398364 [
399365 ("csrf", csrf.as_str()),
@@ -493,8 +459,7 @@ async fn appearance_page_needs_a_session() {
493459 async fn signed_in_toggle_saves_the_preference_and_returns_to_back() {
494460 let env = start().await;
495461 let session = login(&env.http, "tahinli", PW).await;
496- let page = env.http.get("/settings/appearance", Some(&session)).await;
497- let csrf = input_value(&page.body, "csrf");
462+ let csrf = csrf_for(&env.http, "/settings/appearance", &session).await;
498463 let saved = env
499464 .http
500465 .post_form(
@@ -548,8 +513,7 @@ async fn signed_in_toggle_saves_the_preference_and_returns_to_back() {
548513 async fn theme_toggle_with_an_unsafe_back_returns_to_the_root() {
549514 let env = start().await;
550515 let session = login(&env.http, "tahinli", PW).await;
551- let page = env.http.get("/settings/appearance", Some(&session)).await;
552- let csrf = input_value(&page.body, "csrf");
516+ let csrf = csrf_for(&env.http, "/settings/appearance", &session).await;
553517 for back in ["//evil.com", "https://evil.com", "/\\evil"] {
554518 let res = env
555519 .http
@@ -610,7 +574,7 @@ async fn theme_button_cycles_light_dark_auto_light_for_signed_in_users() {
610574 let back = "/settings/appearance";
611575
612576 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;
614578 assert_eq!(html_theme(&page.body).as_deref(), Some("light"));
615579
616580 let step = env
@@ -691,7 +655,7 @@ async fn appearance_sidebar_side_saves_and_renders_on_html() {
691655 html_attr(&page.body, "data-sidebar").as_deref(),
692656 Some("left")
693657 );
694- let csrf = input_value(&page.body, "csrf");
658+ let csrf = csrf_for(&env.http, "/settings/appearance", &session).await;
695659
696660 let saved = env
697661 .http
crates/forge-e2e/tests/e2e/user_delete_e2e.rsmodified+15 -35
@@ -1,33 +1,13 @@
11 use crate::common::{
2- Http, Resp, Server, bin, cookie_named, describe, input_value, launch, login, pick_ports,
3- write_config,
2+ Http, PW, Resp, Server, cookie_named, csrf_for, input_value, launch, login, provision,
43 };
54 use std::fs;
65 use std::future::Future;
7-use std::path::{Path, PathBuf};
8-use std::process::Command;
6+use std::path::PathBuf;
97
108 use forge_core::{Store, Visibility};
119 use reqwest::header::LOCATION;
1210
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-
3111 async fn try_login(http: &Http, username: &str) -> Resp {
3212 let page = http.get("/login", None).await;
3313 assert_eq!(page.status, 200, "GET /login");
@@ -60,11 +40,15 @@ where
6040 {
6141 let root = tempfile::tempdir().expect("temp dir");
6242 let dir = root.path().to_path_buf();
63- let ports = pick_ports();
64- let config = write_config(&dir, ports);
65- for user in ["dana", "tahinli", "bob"] {
66- admin(&config, &["create-user", user]);
67- }
43+ let (_, ports) = provision(
44+ &dir,
45+ "",
46+ &[
47+ &["create-user", "dana"],
48+ &["create-user", "tahinli"],
49+ &["create-user", "bob"],
50+ ],
51+ );
6852 let store = Store::open(&dir.join("forge.db"))
6953 .await
7054 .expect("open store");
@@ -117,7 +101,7 @@ async fn admin_delete_moves_content_to_ghost_and_pages_still_render() {
117101 let page = http.get(&path, Some(&dana)).await;
118102 assert_eq!(page.status, 200, "{}", page.body);
119103 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;
121105
122106 let wrong = http
123107 .post_form(
@@ -162,9 +146,7 @@ async fn self_delete_refuses_wrong_password_and_owned_repos() {
162146 let http = &env.http;
163147
164148 let tahinli = login(http, "tahinli", PW).await;
165- let security = http.get("/settings/security", Some(&tahinli)).await;
166- assert_eq!(security.status, 200);
167- let csrf = input_value(&security.body, "csrf");
149+ let csrf = csrf_for(http, "/settings/security", &tahinli).await;
168150 let wrong = http
169151 .post_form(
170152 "/settings/security/delete",
@@ -188,8 +170,7 @@ async fn self_delete_refuses_wrong_password_and_owned_repos() {
188170 );
189171
190172 let bob = login(http, "bob", PW).await;
191- let security = http.get("/settings/security", Some(&bob)).await;
192- let csrf = input_value(&security.body, "csrf");
173+ let csrf = csrf_for(http, "/settings/security", &bob).await;
193174 let refused = http
194175 .post_form(
195176 "/settings/security/delete",
@@ -221,8 +202,7 @@ async fn self_delete_with_correct_password_signs_out_and_removes_login() {
221202 let env = start(seed_issue_by_tahinli).await;
222203 let http = &env.http;
223204 let tahinli = login(http, "tahinli", PW).await;
224- let security = http.get("/settings/security", Some(&tahinli)).await;
225- let csrf = input_value(&security.body, "csrf");
205+ let csrf = csrf_for(http, "/settings/security", &tahinli).await;
226206 let done = http
227207 .post_form(
228208 "/settings/security/delete",
crates/forge-e2e/tests/e2e/wiki_e2e.rsmodified+38 -168
@@ -1,108 +1,11 @@
11 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,
34 };
45 use std::fs;
5-use std::path::Path;
6-use std::process::{Command, Output};
7-use std::time::Duration;
86
97 use forge_core::{Role, Store, Visibility};
10-use reqwest::header::{COOKIE, 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-}
8+use reqwest::header::LOCATION;
1069
10710 async fn get_ok(http: &Http, path: &str, session: Option<&str>) -> Resp {
10811 let res = http.get(path, session).await;
@@ -112,18 +15,18 @@ async fn get_ok(http: &Http, path: &str, session: Option<&str>) -> Resp {
11215
11316 #[tokio::test]
11417 async fn wiki_end_to_end() {
115- let root = tempfile::Builder::new()
116- .prefix("fwk")
117- .tempdir_in("/tmp")
118- .expect("temp dir");
18+ let root = crate::common::temp_dir("fwk");
11919 let dir = root.path().to_path_buf();
120- let ports = pick_ports();
121- let config = write_config(&dir, ports);
122-
123- admin(&config, &["create-user", "tahinli", "--admin"]);
124- for name in ["bob", "carol", "dave"] {
125- admin(&config, &["create-user", name]);
126- }
20+ let (_, ports) = provision(
21+ &dir,
22+ "",
23+ &[
24+ &["create-user", "tahinli", "--admin"],
25+ &["create-user", "bob"],
26+ &["create-user", "carol"],
27+ &["create-user", "dave"],
28+ ],
29+ );
12730 {
12831 let store = Store::open(&dir.join("forge.db"))
12932 .await
@@ -154,10 +57,7 @@ async fn wiki_end_to_end() {
15457 let empty = get_ok(&http, "/bob/proj/wiki", Some(&bob)).await;
15558 assert!(empty.body.contains("no pages yet"), "{}", empty.body);
15659
157- let csrf = input_value(
158- &http.get("/bob/proj/wiki/-/new", Some(&bob)).await.body,
159- "csrf",
160- );
60+ let csrf = csrf_for(&http, "/bob/proj/wiki/-/new", &bob).await;
16161 let saved = http
16262 .post_form(
16363 "/bob/proj/wiki/-/new",
@@ -224,13 +124,7 @@ async fn wiki_end_to_end() {
224124 assert!(audit.body.contains("carol"), "the pusher is named");
225125 assert!(audit.body.contains("bob/proj"), "the repo is named");
226126
227- let stale_csrf = input_value(
228- &http
229- .get("/bob/proj/wiki/Home/edit", Some(&carol))
230- .await
231- .body,
232- "csrf",
233- );
127+ let stale_csrf = csrf_for(&http, "/bob/proj/wiki/Home/edit", &carol).await;
234128 let stale = http
235129 .post_form(
236130 "/bob/proj/wiki/Home/edit",
@@ -284,7 +178,7 @@ async fn wiki_end_to_end() {
284178 let off = http
285179 .post_form(
286180 "/bob/proj/settings/wiki",
287- &[("csrf", &input_value(&settings.body, "csrf"))],
181+ &[("csrf", &csrf_for(&http, "/bob/proj/settings", &bob).await)],
288182 Some(&bob),
289183 )
290184 .await;
@@ -301,46 +195,19 @@ async fn wiki_end_to_end() {
301195 drop(server);
302196 }
303197
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-
330198 #[tokio::test]
331199 async fn wiki_streams_follow_saves_and_pushes() {
332- let root = tempfile::Builder::new()
333- .prefix("fwl")
334- .tempdir_in("/tmp")
335- .expect("temp dir");
200+ let root = crate::common::temp_dir("fwl");
336201 let dir = root.path().to_path_buf();
337- let ports = pick_ports();
338- let config = write_config(&dir, ports);
339-
340- admin(&config, &["create-user", "tahinli", "--admin"]);
341- for name in ["bob", "dave"] {
342- admin(&config, &["create-user", name]);
343- }
202+ let (_, ports) = provision(
203+ &dir,
204+ "",
205+ &[
206+ &["create-user", "tahinli", "--admin"],
207+ &["create-user", "bob"],
208+ &["create-user", "dave"],
209+ ],
210+ );
344211 {
345212 let store = Store::open(&dir.join("forge.db"))
346213 .await
@@ -371,11 +238,9 @@ async fn wiki_streams_follow_saves_and_pushes() {
371238 "page list follows the wiki stream"
372239 );
373240
374- let mut wiki_events = open_wiki_stream(&http, "/bob/proj/wiki/-/events", Some(&bob)).await;
375- let csrf = input_value(
376- &http.get("/bob/proj/wiki/-/new", Some(&bob)).await.body,
377- "csrf",
378- );
241+ let mut wiki_events = http.stream("/bob/proj/wiki/-/events", Some(&bob)).await;
242+ assert_eq!(wiki_events.status().as_u16(), 200, "stream wiki events");
243+ let csrf = csrf_for(&http, "/bob/proj/wiki/-/new", &bob).await;
379244 let created = http
380245 .post_form(
381246 "/bob/proj/wiki/-/new",
@@ -390,7 +255,7 @@ async fn wiki_streams_follow_saves_and_pushes() {
390255 )
391256 .await;
392257 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;
394259
395260 let home = get_ok(&http, "/bob/proj/wiki/Home", Some(&bob)).await;
396261 assert!(
@@ -398,7 +263,12 @@ async fn wiki_streams_follow_saves_and_pushes() {
398263 .contains(r#"data-live="/bob/proj/wiki/Home/events""#),
399264 "wiki page follows its stream"
400265 );
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+ );
402272 let token = create_token(&http, &bob, "wiki-live").await;
403273 let work = dir.join("wiki-live-work");
404274 let url = format!(
@@ -414,7 +284,7 @@ async fn wiki_streams_follow_saves_and_pushes() {
414284 &git(&work, &["push", "-q", "origin", "HEAD:main"]),
415285 "push to wiki",
416286 );
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;
418288
419289 for path in ["/bob/vault/wiki/-/events", "/bob/vault/wiki/Home/events"] {
420290 let res = http.get(path, Some(&dave)).await;
crates/forge-git/src/history.rsmodified+4 -1
@@ -320,9 +320,10 @@ pub async fn new_commits(
320320 repo: &Path,
321321 old: Option<&str>,
322322 new: &str,
323+ skip: usize,
323324 max: usize,
324325 ) -> 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
326327 }
327328
328329 pub async fn new_commits_with(
@@ -331,6 +332,7 @@ pub async fn new_commits_with(
331332 src: ObjectSource<'_>,
332333 old: Option<&str>,
333334 new: &str,
335+ skip: usize,
334336 max: usize,
335337 ) -> Result<Vec<CommitInfo>> {
336338 validate_oid(new)?;
@@ -350,6 +352,7 @@ pub async fn new_commits_with(
350352 .arg("-z")
351353 .arg("--no-color")
352354 .arg(COMMIT_FORMAT)
355+ .user_opt("--skip", &skip.to_string())?
353356 .user_opt("--max-count", &max.to_string())?
354357 .objects(src)?
355358 .user_revs(&revs)?;
crates/forge-git/src/pulls.rsmodified+1 -1
@@ -451,7 +451,7 @@ pub async fn range_log_with(
451451 ) -> Result<Vec<CommitInfo>> {
452452 validate_oid(base_oid)?;
453453 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
455455 }
456456
457457 #[derive(Debug, Clone, PartialEq, Eq)]
crates/forge-git/src/repo.rsmodified+3 -3
@@ -1,6 +1,6 @@
11 use std::path::{Path, PathBuf};
22
3-use forge_core::time::unix_now;
3+use forge_core::time::now_unix;
44
55 use crate::command::{GitCommand, GitEnv};
66 use crate::error::{Error, Result};
@@ -36,7 +36,7 @@ pub struct TrashEntry {
3636
3737 pub async fn move_to_trash(data_dir: &Path, repo_id: &str) -> Result<PathBuf> {
3838 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());
4040 trash_dir(data_dir, &src, &name).await
4141 }
4242
@@ -45,7 +45,7 @@ pub async fn move_wiki_to_trash(data_dir: &Path, repo_id: &str) -> Result<Option
4545 if !tokio::fs::try_exists(&src).await? {
4646 return Ok(None);
4747 }
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());
4949 trash_dir(data_dir, &src, &name).await.map(Some)
5050 }
5151
crates/forge-runner/Cargo.tomlmodified+1 -0
@@ -13,6 +13,7 @@ test-host-executor = []
1313 [dependencies]
1414 clap = { workspace = true, features = ["string"] }
1515 forge-ci.workspace = true
16+rand = { workspace = true }
1617 reqwest = { workspace = true, features = ["json"] }
1718 serde = { workspace = true }
1819 sha2 = { workspace = true }
crates/forge-runner/src/check.rsmodified+13 -8
@@ -7,9 +7,9 @@ use tokio::io::AsyncWriteExt;
77 use tokio::process::Command;
88
99 use crate::config::{Limits, UsernsMode};
10-use crate::sandbox::SandboxRequest;
1110 use crate::sandbox::helper::job_cgroup_base;
1211 use crate::sandbox::idmap::IdMap;
12+use crate::sandbox::{SandboxRequest, new_token, strip_line};
1313
1414 const PROBE_SCRIPT: &str = "grep '^Seccomp:' /proc/self/status; true";
1515 const PROBE_SUBUID_SCRIPT: &str = "grep '^Seccomp:' /proc/self/status; \
@@ -128,6 +128,7 @@ struct Probe {
128128 status: ExitStatus,
129129 stdout: String,
130130 stderr: String,
131+ token: String,
131132 }
132133
133134 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,
147148 } else {
148149 PROBE_SCRIPT
149150 };
151+ let token = new_token();
150152 let request = SandboxRequest {
153+ token: token.clone(),
151154 job_id: "forge-check".to_owned(),
152155 rootfs,
153156 job_dir: root.join("job"),
@@ -182,13 +185,14 @@ async fn run_probe(helper: &Path, work_dir: &Path, map: &IdMap) -> Result<Probe,
182185 status: output.status,
183186 stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
184187 stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
188+ token,
185189 })
186190 }
187191
188-fn sandbox_lines(stderr: &str) -> Vec<&str> {
192+fn sandbox_lines<'a>(stderr: &'a str, token: &str) -> Vec<&'a str> {
189193 stderr
190194 .lines()
191- .filter_map(|line| line.strip_prefix("forge-sandbox: "))
195+ .filter_map(|line| strip_line(line, token))
192196 .collect()
193197 }
194198
@@ -265,7 +269,7 @@ fn report(probe: Result<&Probe, &str>, controllers: Result<&[String], &str>) ->
265269 }
266270 };
267271
268- let setup_errors = sandbox_lines(&probe.stderr);
272+ let setup_errors = sandbox_lines(&probe.stderr, &probe.token);
269273 let userns_error = setup_errors
270274 .iter()
271275 .find(|l| l.contains("user namespaces unavailable"));
@@ -367,7 +371,7 @@ fn ownership_line(probe: &Probe) -> Line {
367371 let reason = probe
368372 .stderr
369373 .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())
371375 .unwrap_or("no output");
372376 Line::fail(
373377 NAME,
@@ -431,6 +435,7 @@ mod tests {
431435 status: ExitStatus::from_raw(0),
432436 stdout: stdout.to_owned(),
433437 stderr: stderr.to_owned(),
438+ token: "t".to_owned(),
434439 }
435440 }
436441
@@ -447,7 +452,7 @@ mod tests {
447452
448453 #[test]
449454 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");
451456 let lines = report(Ok(&p), Ok(&all()));
452457 let userns = lines
453458 .iter()
@@ -466,8 +471,8 @@ mod tests {
466471 fn overlay_and_limit_warnings_are_failures() {
467472 let p = probe(
468473 "Seccomp:\t2\n",
469- "forge-sandbox: warning: overlay mount failed (EPERM), copying the rootfs instead\n\
470- forge-sandbox: warning: resource limits unavailable: cgroup\n",
474+ "forge-sandbox[t]: warning: overlay mount failed (EPERM), copying the rootfs instead\n\
475+ forge-sandbox[t]: warning: resource limits unavailable: cgroup\n",
471476 );
472477 let lines = report(Ok(&p), Ok(&all()));
473478 let overlay = lines
crates/forge-runner/src/cli.rsmodified+1 -1
@@ -139,7 +139,7 @@ fn hidden_dispatch(args: &[OsString]) -> i32 {
139139 Some(b"__sandbox-map") => crate::sandbox::idmap::map_helper_main(&args[1..]),
140140 Some(b"__sandbox-unpack") => crate::oci::unpack_helper_main(),
141141 _ => {
142- eprintln!("forge-sandbox: unknown helper command");
142+ crate::sandbox::report("unknown helper command");
143143 125
144144 }
145145 }
crates/forge-runner/src/executor.rsmodified+19 -16
@@ -23,11 +23,9 @@ use crate::oci::{ImageError, ImageStore, PreparedImage, RegistryAuth};
2323 use crate::oom::{OomEvents, OomSink};
2424 use crate::sandbox::helper::EXIT_SETUP_FAILED;
2525 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};
2727 use crate::workspace::validate_job_id;
2828
29-const SANDBOX_PREFIX: &[u8] = b"forge-sandbox: ";
30-
3129 const READER_GRACE: Duration = Duration::from_secs(10);
3230 const STOP_GRACE: Duration = Duration::from_secs(30);
3331
@@ -318,20 +316,20 @@ struct Supervised {
318316 async fn tap_sandbox_errors(
319317 mut lines: mpsc::Receiver<Vec<u8>>,
320318 logs: mpsc::Sender<Vec<u8>>,
319+ token: String,
321320 ) -> (Option<String>, Option<OomEvents>) {
322321 let mut found = None;
323322 let mut oom = None;
324323 while let Some(chunk) = lines.recv().await {
325- if chunk.starts_with(SANDBOX_PREFIX)
326- && let Some(events) = OomEvents::from_line(&String::from_utf8_lossy(&chunk))
327- {
328- oom = Some(events);
329- continue;
330- }
331- let is_error = chunk.starts_with(SANDBOX_PREFIX)
332- && !chunk[SANDBOX_PREFIX.len()..].starts_with(b"warning:");
333- if is_error {
334- found = Some(String::from_utf8_lossy(&chunk).trim_end().to_owned());
324+ let text = String::from_utf8_lossy(&chunk).into_owned();
325+ if let Some(message) = strip_line(&text, &token) {
326+ if let Some(events) = OomEvents::from_line(message) {
327+ oom = Some(events);
328+ continue;
329+ }
330+ if !message.starts_with("warning:") {
331+ found = Some(message.trim_end().to_owned());
332+ }
335333 }
336334 if logs.send(chunk).await.is_err() {
337335 break;
@@ -346,6 +344,7 @@ async fn supervise(
346344 cancel: CancellationToken,
347345 stopper: Stopper,
348346 cleanup: Option<JobCleanup>,
347+ token: String,
349348 ) -> Supervised {
350349 let mut readers: Vec<JoinHandle<()>> = Vec::new();
351350 if let Some(out) = child.stdout.take() {
@@ -355,7 +354,7 @@ async fn supervise(
355354 if let Some(err) = child.stderr.take() {
356355 let (tx, rx) = mpsc::channel(64);
357356 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)));
359358 }
360359 drop(logs);
361360
@@ -453,6 +452,7 @@ impl Executor for PodmanExecutor {
453452 container: inv.container,
454453 },
455454 None,
455+ new_token(),
456456 )
457457 .await,
458458 )
@@ -495,6 +495,7 @@ impl Executor for HostExecutor {
495495 req.cancel,
496496 Stopper::ProcessGroup { pid },
497497 None,
498+ new_token(),
498499 )
499500 .await,
500501 )
@@ -631,7 +632,9 @@ impl<I: ImageSource> BuiltinExecutor<I> {
631632 } else {
632633 None
633634 };
635+ let token = new_token();
634636 let request = SandboxRequest {
637+ token: token.clone(),
635638 job_id: job.job_id.clone(),
636639 rootfs: image.rootfs,
637640 job_dir,
@@ -704,6 +707,7 @@ impl<I: ImageSource> BuiltinExecutor<I> {
704707 idmap: self.idmap.clone(),
705708 helper: self.helper.clone(),
706709 }),
710+ token,
707711 )
708712 .await;
709713 if let Some(watcher) = watcher {
@@ -734,8 +738,7 @@ impl<I: ImageSource> BuiltinExecutor<I> {
734738 message: None,
735739 },
736740 Some(EXIT_SETUP_FAILED) if sandbox_error.is_some() => {
737- let line = sandbox_error.unwrap_or_default();
738- let reason = line.strip_prefix("forge-sandbox: ").unwrap_or(&line);
741+ let reason = sandbox_error.unwrap_or_default();
739742 ExecResult {
740743 outcome: Outcome::Error,
741744 exit_code: Some(EXIT_SETUP_FAILED),
crates/forge-runner/src/main.rsmodified+1 -5
@@ -1,11 +1,7 @@
11 use std::process::ExitCode;
22
33 fn main() -> ExitCode {
4- forge_ci::build::set_identity(
5- env!("FORGE_GIT_SHA"),
6- env!("FORGE_GIT_DATE"),
7- matches!(env!("FORGE_GIT_DIRTY").as_bytes(), b"1"),
8- );
4+ forge_ci::build::set_identity(env!("FORGE_GIT_SHA"), env!("FORGE_GIT_DATE"));
95 if forge_runner::cli::is_sandbox_invocation() {
106 std::process::exit(forge_runner::cli::hidden_main());
117 }
crates/forge-runner/src/oci/helper.rsmodified+1 -1
@@ -46,7 +46,7 @@ pub fn unpack_helper_main() -> i32 {
4646 match run_helper() {
4747 Ok(()) => 0,
4848 Err(message) => {
49- eprintln!("forge-sandbox: {message}");
49+ crate::sandbox::report(message);
5050 125
5151 }
5252 }
crates/forge-runner/src/oci/store.rsmodified+29 -10
@@ -154,14 +154,11 @@ impl ImageStore {
154154 let now = SystemTime::now();
155155 let mut stats = GcStats::default();
156156 let mut live_layers: HashSet<String> = HashSet::new();
157+ let mut live_rootfs: HashSet<PathBuf> = HashSet::new();
157158
158- for dir in ["rootfs", "blobs/sha256", "meta", "tags"] {
159+ for dir in ["blobs/sha256", "meta", "tags"] {
159160 for path in entries(&self.root.join(dir))? {
160- let is_temp = path
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)) {
161+ if is_stale_temp(&path, now) {
165162 self.remove_entry(&path)?;
166163 stats.temp_removed += 1;
167164 }
@@ -180,8 +177,20 @@ impl ImageStore {
180177 remove_file_if_exists(&meta_file)?;
181178 remove_file_if_exists(&self.stamp_path(&hex))?;
182179 stats.images_removed += 1;
183- } else if let Ok(meta) = serde_json::from_slice::<ImageMeta>(&fs::read(&meta_file)?) {
184- live_layers.extend(meta.layers);
180+ } else {
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+ );
185194 }
186195 }
187196
@@ -250,6 +259,16 @@ fn entries(dir: &Path) -> io::Result<Vec<PathBuf>> {
250259 }
251260 }
252261
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+
253272 fn file_stem(path: &Path) -> Option<String> {
254273 path.file_stem()
255274 .and_then(|name| name.to_str())
@@ -433,9 +452,9 @@ mod tests {
433452 set_age(&stale_meta_tmp, two_hours);
434453
435454 let stats = store.gc(7).expect("gc");
436- assert_eq!(stats.temp_removed, 3);
455+ assert_eq!(stats.temp_removed, 2);
437456 assert_eq!(stats.blobs_removed, 0);
438- assert!(!stale_dir.exists());
457+ assert!(stale_dir.is_dir());
439458 assert!(fresh_dir.is_dir());
440459 assert!(!stale_blob_tmp.exists());
441460 assert!(fresh_blob_tmp.is_file());
crates/forge-runner/src/oom.rsmodified+5 -13
@@ -1,8 +1,6 @@
11 use std::sync::Arc;
22 use std::sync::atomic::{AtomicU32, Ordering};
33
4-pub const LINE_PREFIX: &str = "forge-sandbox: oom-events ";
5-
64 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
75 pub struct OomEvents {
86 pub oom: u64,
@@ -36,11 +34,11 @@ impl OomEvents {
3634 }
3735
3836 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)
4038 }
4139
4240 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 ")?;
4442 let mut events = Self::default();
4543 for pair in rest.split_whitespace() {
4644 let (key, value) = pair.split_once('=')?;
@@ -118,16 +116,10 @@ mod tests {
118116 oom: 1,
119117 oom_kill: 2,
120118 };
121- assert_eq!(
122- events.to_line(),
123- "forge-sandbox: oom-events oom=1 oom_kill=2"
124- );
119+ assert_eq!(events.to_line(), "oom-events oom=1 oom_kill=2");
125120 assert_eq!(OomEvents::from_line(&events.to_line()), Some(events));
126- assert_eq!(OomEvents::from_line("forge-sandbox: setup failed"), None);
127- assert_eq!(
128- OomEvents::from_line("forge-sandbox: oom-events oom=x"),
129- None
130- );
121+ assert_eq!(OomEvents::from_line("setup failed"), None);
122+ assert_eq!(OomEvents::from_line("oom-events oom=x"), None);
131123 }
132124
133125 #[test]
crates/forge-runner/src/runner.rsmodified+4 -1
@@ -473,7 +473,10 @@ impl Runner {
473473 };
474474 }
475475
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+ {
477480 result.message = Some("cancelled because an admin restarted the runner".to_owned());
478481 }
479482
crates/forge-runner/src/sandbox/helper.rsmodified+5 -4
@@ -25,7 +25,7 @@ use super::idmap::enter_mapped_userns;
2525 use super::net;
2626 use super::seccomp::build_filter;
2727 use super::spec::{HOSTNAME, build_spec};
28-use super::{SandboxError, SandboxRequest};
28+use super::{SandboxError, SandboxRequest, bind_token, report};
2929 use crate::workspace::validate_job_id;
3030
3131 pub const EXIT_SETUP_FAILED: i32 = 125;
@@ -41,7 +41,7 @@ pub fn helper_main() -> i32 {
4141 match run() {
4242 Ok(code) => code,
4343 Err(e) => {
44- eprintln!("forge-sandbox: {e}");
44+ report(e);
4545 EXIT_SETUP_FAILED
4646 }
4747 }
@@ -77,6 +77,7 @@ impl Layout {
7777 fn run() -> Result<i32, SandboxError> {
7878 let req: SandboxRequest = serde_json::from_reader(io::stdin().lock())
7979 .map_err(|e| SandboxError::Invalid(format!("cannot read request: {e}")))?;
80+ bind_token(&req.token);
8081 validate_request(&req)?;
8182 let signals = install_signal_handlers()?;
8283
@@ -523,7 +524,7 @@ fn report_oom(cgroup: Option<&Path>) {
523524 };
524525 let events = crate::oom::OomEvents::parse_memory_events(&text);
525526 if events.any() {
526- eprintln!("{}", events.to_line());
527+ report(events.to_line());
527528 }
528529 }
529530
@@ -541,5 +542,5 @@ fn cleanup(layout: &Layout) {
541542 }
542543
543544 fn warn(message: impl std::fmt::Display) {
544- eprintln!("forge-sandbox: warning: {message}");
545+ report(format!("warning: {message}"));
545546 }
crates/forge-runner/src/sandbox/idmap.rsmodified+2 -2
@@ -332,7 +332,7 @@ pub fn map_helper_main(args: &[OsString]) -> i32 {
332332 match map_helper(args) {
333333 Ok(()) => 0,
334334 Err(message) => {
335- eprintln!("forge-sandbox: {message}");
335+ super::report(message);
336336 125
337337 }
338338 }
@@ -391,7 +391,7 @@ pub fn rm_helper_main(args: &[OsString]) -> i32 {
391391 match rm_helper(args) {
392392 Ok(()) => 0,
393393 Err(message) => {
394- eprintln!("forge-sandbox: {message}");
394+ super::report(message);
395395 125
396396 }
397397 }
crates/forge-runner/src/sandbox/mod.rsmodified+24 -0
@@ -5,7 +5,9 @@ pub mod net;
55 pub mod seccomp;
66 pub mod spec;
77
8+use std::fmt::Display;
89 use std::path::PathBuf;
10+use std::sync::OnceLock;
911
1012 use serde::{Deserialize, Serialize};
1113
@@ -15,8 +17,30 @@ use idmap::IdMap;
1517 pub use helper::{BOX_NAME, helper_main, job_cgroup_base, job_cgroup_path};
1618 pub use spec::build_spec;
1719
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+
1841 #[derive(Serialize, Deserialize)]
1942 pub struct SandboxRequest {
43+ pub token: String,
2044 pub job_id: String,
2145 pub rootfs: PathBuf,
2246 pub job_dir: PathBuf,
crates/forge-runner/src/sandbox/net.rsmodified+1 -1
@@ -148,7 +148,7 @@ pub fn net_helper_main(args: &[OsString]) -> i32 {
148148 match net_helper(args) {
149149 Ok(()) => 0,
150150 Err(message) => {
151- eprintln!("forge-sandbox: {message}");
151+ super::report(message);
152152 125
153153 }
154154 }
crates/forge-runner/src/sandbox/spec.rsmodified+1 -0
@@ -390,6 +390,7 @@ mod tests {
390390
391391 fn request(network: bool) -> SandboxRequest {
392392 SandboxRequest {
393+ token: String::new(),
393394 job_id: "job_01".to_owned(),
394395 rootfs: PathBuf::from("/var/lib/forge/rootfs"),
395396 job_dir: PathBuf::from("/var/lib/forge/jobs/job_01"),
crates/forge-runner/tests/integration/sandbox.rsmodified+3 -2
@@ -8,8 +8,8 @@ use std::os::unix::fs::MetadataExt;
88
99 use forge_runner::check;
1010 use forge_runner::config::Limits;
11-use forge_runner::sandbox::SandboxRequest;
1211 use forge_runner::sandbox::idmap::{IdMap, UsernsMode};
12+use forge_runner::sandbox::{SandboxRequest, new_token};
1313
1414 use crate::common::can_run;
1515
@@ -25,6 +25,7 @@ fn request(dir: &Path, rootfs: &Path, run: &str, network: bool) -> SandboxReques
2525 let workspace = dir.join("workspace");
2626 fs::create_dir_all(&workspace).expect("create workspace");
2727 SandboxRequest {
28+ token: new_token(),
2829 job_id: "job_01".to_owned(),
2930 rootfs: rootfs.to_owned(),
3031 job_dir: dir.join("jobs/job_01"),
@@ -260,7 +261,7 @@ fn setup_failure_exits_125_with_a_reason() {
260261 let out = run_helper(&req);
261262 assert_eq!(out.status.code(), Some(125));
262263 assert!(
263- stderr_of(&out).contains("forge-sandbox: "),
264+ stderr_of(&out).contains("forge-sandbox["),
264265 "stderr: {}",
265266 stderr_of(&out)
266267 );
crates/forge-ssh/src/parse.rsmodified+18 -3
@@ -21,14 +21,29 @@ pub struct RepoPath {
2121 pub name: String,
2222 }
2323
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> {
2540 let (service, rest) = split_service(cmd)?;
2641 let raw = unquote_argument(rest)?;
2742 let path = normalize_path(raw)?;
2843 Ok((service, path))
2944 }
3045
31-pub(crate) const LFS_AUTHENTICATE_PREFIX: &str = "git-lfs-authenticate ";
46+const LFS_AUTHENTICATE_PREFIX: &str = "git-lfs-authenticate ";
3247
3348 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
3449 pub enum LfsOperation {
@@ -36,7 +51,7 @@ pub enum LfsOperation {
3651 Upload,
3752 }
3853
39-pub(crate) fn parse_lfs_authenticate(cmd: &str) -> Result<(RepoPath, LfsOperation), ParseError> {
54+fn parse_lfs_authenticate(cmd: &str) -> Result<(RepoPath, LfsOperation), ParseError> {
4055 let rest = cmd
4156 .strip_prefix(LFS_AUTHENTICATE_PREFIX)
4257 .ok_or(ParseError::UnsupportedCommand)?;
crates/forge-ssh/src/server.rsmodified+22 -18
@@ -26,7 +26,7 @@ use tokio::sync::{Notify, Semaphore, mpsc};
2626
2727 use crate::backend::GitBackend;
2828 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};
3030
3131 const PUMP_CHUNK: usize = 32 * 1024;
3232 const STDIN_QUEUE: usize = 8;
@@ -179,13 +179,20 @@ fn load_or_create_host_key(path: &Path) -> Result<PrivateKey> {
179179 if let Some(parent) = path.parent() {
180180 std::fs::create_dir_all(parent)?;
181181 }
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()
183185 .write(true)
184186 .create_new(true)
185187 .mode(0o600)
186- .open(path)?;
187- file.write_all(pem.as_bytes())?;
188- file.sync_all()?;
188+ .open(&tmp)
189+ .and_then(|mut file| {
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?;
189196 std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))?;
190197 tracing::info!(path = %path.display(), "generated ssh host key");
191198 Ok(key)
@@ -216,15 +223,12 @@ impl<B: GitBackend> Client<B> {
216223 session: &mut Session,
217224 channel: ChannelId,
218225 user_id: &str,
219- command: &str,
226+ path: &RepoPath,
227+ operation: LfsOperation,
220228 ) -> 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- };
225229 let reply = match self
226230 .backend
227- .lfs_authenticate(user_id, &path, operation)
231+ .lfs_authenticate(user_id, path, operation)
228232 .await
229233 {
230234 Ok(reply) => reply,
@@ -317,13 +321,13 @@ impl<B: GitBackend> Handler for Client<B> {
317321 Ok(command) => command,
318322 Err(_) => return reject_exec(session, channel, "invalid command"),
319323 };
320- if command.starts_with(LFS_AUTHENTICATE_PREFIX) {
321- return self
322- .exec_lfs_authenticate(session, channel, &user_id, command)
323- .await;
324- }
325- let (service, path) = match parse_exec(command) {
326- Ok(parsed) => parsed,
324+ let (service, path) = match parse_command(command) {
325+ Ok(ExecCommand::Git(service, path)) => (service, path),
326+ Ok(ExecCommand::LfsAuthenticate(path, operation)) => {
327+ return self
328+ .exec_lfs_authenticate(session, channel, &user_id, &path, operation)
329+ .await;
330+ }
327331 Err(e) => return reject_exec(session, channel, &e.to_string()),
328332 };
329333
crates/forge-web-account/src/lib.rsmodified+1 -1
@@ -8,6 +8,6 @@ pub(crate) use forge_web_app::{
88 web_push, webhooks,
99 };
1010 #[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};
1212
1313 pub mod pages;
crates/forge-web-account/src/pages/account_tools_tests.rsmodified+4 -4
@@ -1,5 +1,5 @@
11 use forge_core::Store;
2-use forge_core::config::BannerConfig;
2+use forge_core::config::{BannerConfig, BannerLevel};
33 use topcoat::router::request::Request;
44 use topcoat::router::{Body, Router, to_bytes};
55
@@ -271,7 +271,7 @@ async fn banner_shows_on_pages_and_a_dismissal_hides_it() {
271271 let dir = tempfile::tempdir().unwrap();
272272 let banner = BannerConfig {
273273 message: "Maintenance tonight".into(),
274- level: "warning".into(),
274+ level: BannerLevel::Warning,
275275 expires: String::new(),
276276 };
277277 let fx = fixture(dir.path(), Some(banner)).await;
@@ -281,7 +281,7 @@ async fn banner_shows_on_pages_and_a_dismissal_hides_it() {
281281 assert!(body.contains("site-banner warning"), "{body}");
282282 assert!(body.contains("Maintenance tonight"));
283283 }
284- let hash = crate::views::banner_hash("Maintenance tonight", "warning");
284+ let hash = crate::views::banner_hash("Maintenance tonight", BannerLevel::Warning);
285285 let req = Request::builder()
286286 .method("GET")
287287 .uri("/explore")
@@ -315,7 +315,7 @@ async fn expired_banner_is_not_shown() {
315315 let dir = tempfile::tempdir().unwrap();
316316 let banner = BannerConfig {
317317 message: "Old news".into(),
318- level: "info".into(),
318+ level: BannerLevel::Info,
319319 expires: "2020-01-01 00:00".into(),
320320 };
321321 let fx = fixture(dir.path(), Some(banner)).await;
crates/forge-web-account/src/pages/admin_backups.rsmodified+1 -1
@@ -29,7 +29,7 @@ use crate::views::{alert, enc, human_size, rel_time, shell, stamp_unix};
2929 const RUN_LIMIT: u32 = 20;
3030
3131 #[query_params(error = bad_request)]
32-pub(crate) struct NoticeQuery {
32+struct NoticeQuery {
3333 notice: Option<String>,
3434 }
3535
crates/forge-web-account/src/pages/admin_health.rsmodified+21 -37
@@ -4,7 +4,9 @@ use std::time::Duration;
44
55 use forge_core::mail::MailState;
66 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+};
810 use forge_core::time::stamp_to_unix;
911 use tokio::process::Command;
1012 use topcoat::Result;
@@ -21,6 +23,7 @@ use crate::i18n::{self, Lang};
2123 use crate::live::{Topic, stream_changes};
2224 use crate::pages::admin_users::admin_only;
2325 use crate::state::AppState;
26+use crate::views::paging::{paginate, requested_page};
2427 use crate::views::parts::{SubPart, head};
2528 use crate::views::repo_list::{PageLink, pager, pager_links};
2629 use crate::views::{human_size, now_unix, rel_time, shell};
@@ -342,15 +345,13 @@ async fn gather(state: &AppState, lang: Lang) -> Result<Health> {
342345 match state.store.replication_status(DB_SUBJECT).await? {
343346 Some(status) => {
344347 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);
346- let lagging = ok_unix.is_none_or(|t| (now - t).max(0) as u64 > window);
347- let errored = status.last_error.is_some();
348- let (value, dot) = if errored {
349- (at(lang, A::Error), Dot::Bad)
350- } else if lagging {
351- (at(lang, A::Lagging), Dot::Bad)
352- } else {
353- (at(lang, A::Ok), Dot::Ok)
348+ let window = window_secs(live.replication.db_snapshot_minutes);
349+ let (value, dot) = match replication_health(Some(&status), now, window) {
350+ ReplicationHealth::Error => (at(lang, A::Error), Dot::Bad),
351+ ReplicationHealth::Lagging | ReplicationHealth::Never => {
352+ (at(lang, A::Lagging), Dot::Bad)
353+ }
354+ ReplicationHealth::Ok => (at(lang, A::Ok), Dot::Ok),
354355 };
355356 Service {
356357 label: at(lang, A::Replication),
@@ -382,15 +383,7 @@ async fn gather(state: &AppState, lang: Lang) -> Result<Health> {
382383 || at(lang, A::Unavailable).to_owned(),
383384 |secs| duration_short_in(lang, secs),
384385 );
385- let build = format!(
386- "{}{}",
387- forge_ci::build::commit(),
388- if forge_ci::build::dirty() {
389- "-dirty"
390- } else {
391- ""
392- }
393- );
386+ let build = forge_ci::build::commit();
394387 let meta = meta_line(
395388 lang,
396389 &uptime,
@@ -424,8 +417,8 @@ async fn alert_rows(state: &AppState, lang: Lang) -> Result<Vec<AlertRow>> {
424417 .await?
425418 .into_iter()
426419 .map(|alert| AlertRow {
427- title: alert_text::title(lang, &alert.kind, &alert.subject, false),
428- body: alert_text::body(lang, &alert.kind, &alert.subject, &alert.detail, false),
420+ title: alert_text::title(lang, alert.kind, &alert.subject, false),
421+ body: alert_text::body(lang, alert.kind, &alert.subject, &alert.detail, false),
429422 stamp: alert.raised_at.clone(),
430423 })
431424 .collect())
@@ -549,26 +542,17 @@ async fn health_page(cx: &Cx) -> Result<impl View> {
549542 let health = gather(state, lang).await?;
550543 let all = alert_rows(state, lang).await?;
551544 let total = all.len();
552- let pages = total.div_ceil(ALERTS_PER_PAGE).max(1);
553- let page = query
554- .page
555- .as_deref()
556- .and_then(|p| p.parse::<usize>().ok())
557- .unwrap_or(1)
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- });
545+ let (alerts, page, pages) = paginate(
546+ all,
547+ requested_page(query.page.as_deref()),
548+ ALERTS_PER_PAGE as u64,
549+ );
550+ let nav = pager_links(page, pages, |n| format!("/admin/health?page={n}"));
567551 let title = at(lang, A::Health);
568552 Ok(view! {
569553 shell(title: title, viewer: Some(&viewer),
570554 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))
572556 })
573557 }
574558
crates/forge-web-account/src/pages/admin_live_tests.rsmodified+7 -22
@@ -1,11 +1,9 @@
11 use std::fmt::Debug;
2-use std::time::Duration;
32
4-use bytes::Bytes;
53 use forge_core::AuditAction;
64 use forge_core::store::backup_runs::RunKind;
75 use forge_core::store::replication::DB_SUBJECT;
8-use futures_util::{Stream, StreamExt};
6+use futures_util::Stream;
97 use serde_json::Value;
108 use topcoat::router::request::Request;
119 use topcoat::router::{Body, Router};
@@ -14,6 +12,7 @@ use crate::audit::{self, Actor, Target};
1412 use crate::auth::SESSION_COOKIE;
1513 use crate::live::{Topic, admin};
1614 use crate::state::AppState;
15+use crate::test_support::fixture::{next_event as next_event_or_end, next_frame};
1716 use crate::test_support::{app_router, create_session, test_state};
1817
1918 const ADMIN_TOKEN: &str = "admin-live-admin-session";
@@ -76,28 +75,14 @@ async fn open(app: &Router, uri: &str, token: Option<&str>) -> topcoat::router::
7675 .await
7776 }
7877
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-
9078 async fn next_event<S, E>(frames: &mut S) -> Vec<u8>
9179 where
92- S: Stream<Item = Result<Bytes, E>> + Unpin,
80+ S: Stream<Item = Result<bytes::Bytes, E>> + Unpin,
9381 E: Debug,
9482 {
95- loop {
96- let bytes = next_frame(frames).await.expect("an event before the end");
97- if !bytes.starts_with(b"retry: ") {
98- return bytes;
99- }
100- }
83+ next_event_or_end(frames)
84+ .await
85+ .expect("an event before the end")
10186 }
10287
10388 fn changed(data: &str) -> Vec<u8> {
@@ -253,7 +238,7 @@ async fn backups_replication_health_and_server_send_for_their_changes() {
253238
254239 crate::alerts::raise(
255240 &fx.state,
256- crate::alerts::AlertTopic::RunnerOffline,
241+ forge_core::alerts::AlertTopic::RunnerOffline,
257242 "runner-offline:tahinli-ci",
258243 "tahinli-ci",
259244 "silent for an hour",
crates/forge-web-account/src/pages/admin_mail.rsmodified+14 -5
@@ -32,7 +32,7 @@ use crate::views::{enc, rel_time, shell};
3232 const LIST_LIMIT: u32 = 100;
3333
3434 #[query_params(error = bad_request)]
35-pub(crate) struct NoticeQuery {
35+struct NoticeQuery {
3636 notice: Option<String>,
3737 tab: Option<String>,
3838 state: Option<String>,
@@ -317,7 +317,10 @@ async fn mail_page(cx: &Cx) -> Result<impl View> {
317317 } else {
318318 Tab::Settings
319319 };
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());
321324 let data = page_data(state, lang, tab, filter).await?;
322325 let csrf = viewer.1.csrf_token.clone();
323326 let title = g::t(lang, K::Mail);
@@ -401,8 +404,11 @@ async fn save_settings(
401404 .trim()
402405 .parse()
403406 .map_err(|_| Error::Invalid(g::t(lang, K::ErrPortRange).to_owned()))?;
404- let security = Security::parse(form.security.trim())
405- .ok_or_else(|| Error::Invalid(g::t(lang, K::ErrChooseSecurity).to_owned()))?;
407+ let security = form
408+ .security
409+ .trim()
410+ .parse::<Security>()
411+ .map_err(|_| Error::Invalid(g::t(lang, K::ErrChooseSecurity).to_owned()))?;
406412 let password = (!form.password.is_empty()).then_some(form.password.as_str());
407413 let update = MailSettingsUpdate {
408414 host: form.host.trim(),
@@ -555,7 +561,10 @@ async fn queue_action(cx: &Cx, form: QueueForm, action: QueueAction) -> Result<R
555561 if done {
556562 live::bump();
557563 }
558- let filter = MailState::parse(&form.state)
564+ let filter = form
565+ .state
566+ .parse::<MailState>()
567+ .ok()
559568 .map_or_else(String::new, |s| format!("&state={}", s.as_str()));
560569 let location = format!(
561570 "/admin/mail?tab=queue{filter}&notice={}",
crates/forge-web-account/src/pages/admin_replication.rsmodified+63 -108
@@ -1,9 +1,10 @@
11 use std::collections::HashMap;
2-use std::time::Duration;
32
43 use forge_core::server_settings::Group;
5-use forge_core::store::replication::{DB_SUBJECT, ReplicationStatus};
6-use forge_core::time::stamp_ago;
4+use forge_core::store::replication::{
5+ DB_SUBJECT, ReplicationHealth, ReplicationStatus, replication_health, window_secs,
6+};
7+use forge_core::time::now_unix;
78 use forge_core::{AuditAction, Error};
89 use serde::Deserialize;
910 use topcoat::Result;
@@ -29,12 +30,13 @@ use crate::pages::admin_users::admin_only;
2930 use crate::pages::issues_list::list_href;
3031 use crate::state::AppState;
3132 use crate::views::find::{Finder, finder_field};
33+use crate::views::paging::{paginate, requested_page};
3234 use crate::views::parts::{head, post_act};
3335 use crate::views::repo_list::{PageLink, pager, pager_links};
3436 use crate::views::{alert, enc, rel_time_or_never, shell};
3537
3638 #[query_params(error = bad_request)]
37-pub(crate) struct NoticeQuery {
39+struct NoticeQuery {
3840 notice: Option<String>,
3941 q: Option<String>,
4042 exact: Option<String>,
@@ -45,80 +47,63 @@ pub(crate) struct NoticeQuery {
4547
4648 const REPO_ROWS: usize = 10;
4749
48-const HEALTH_MENU: [Health; 4] = [Health::Error, Health::Lagging, Health::Never, Health::Ok];
49-
50-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
51-enum Health {
52- Ok,
53- Lagging,
54- Error,
55- Never,
56-}
57-
58-impl Health {
59- fn dot(self) -> &'static str {
60- match self {
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- }
50+const HEALTH_MENU: [ReplicationHealth; 4] = [
51+ ReplicationHealth::Error,
52+ ReplicationHealth::Lagging,
53+ ReplicationHealth::Never,
54+ ReplicationHealth::Ok,
55+];
56+
57+fn health_dot(health: ReplicationHealth) -> &'static str {
58+ match health {
59+ ReplicationHealth::Ok => "health-dot ok",
60+ ReplicationHealth::Lagging => "health-dot warn",
61+ ReplicationHealth::Error => "health-dot bad",
62+ ReplicationHealth::Never => "health-dot",
7463 }
64+}
7565
76- fn key(self) -> &'static str {
77- match self {
78- Health::Ok => "ok",
79- Health::Lagging => "lagging",
80- Health::Error => "error",
81- Health::Never => "never",
82- }
66+fn health_tone(health: ReplicationHealth) -> &'static str {
67+ match health {
68+ ReplicationHealth::Ok | ReplicationHealth::Never => "",
69+ ReplicationHealth::Lagging => "warn",
70+ ReplicationHealth::Error => "bad",
8371 }
72+}
8473
85- fn from_key(key: &str) -> Option<Health> {
86- HEALTH_MENU.into_iter().find(|h| h.key() == key)
74+fn health_slug(health: ReplicationHealth) -> &'static str {
75+ match health {
76+ ReplicationHealth::Ok => "ok",
77+ ReplicationHealth::Lagging => "lagging",
78+ ReplicationHealth::Error => "error",
79+ ReplicationHealth::Never => "never",
8780 }
81+}
8882
89- fn label(self, lang: Lang) -> &'static str {
90- match self {
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- }
83+fn health_from_slug(slug: &str) -> Option<ReplicationHealth> {
84+ HEALTH_MENU.into_iter().find(|h| health_slug(*h) == slug)
9785 }
9886
99-fn health(status: Option<&ReplicationStatus>, cutoff: &str) -> Health {
100- match status {
101- None => Health::Never,
102- Some(s) if s.last_error.is_some() => Health::Error,
103- Some(s) => match s.last_ok_at.as_deref() {
104- None => Health::Never,
105- Some(ok) if ok >= cutoff => Health::Ok,
106- Some(_) => Health::Lagging,
107- },
87+fn health_text(health: ReplicationHealth, lang: Lang) -> &'static str {
88+ match health {
89+ ReplicationHealth::Ok => g::t(lang, K::HealthOk),
90+ ReplicationHealth::Lagging => g::t(lang, K::HealthLagging),
91+ ReplicationHealth::Error => g::t(lang, K::HealthError),
92+ ReplicationHealth::Never => g::t(lang, K::HealthNever),
10893 }
10994 }
11095
11196 struct RepoRow {
11297 name: String,
113- kind: Health,
98+ kind: ReplicationHealth,
11499 last_ok: Option<String>,
115100 error: String,
116101 }
117102
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 {
119104 RepoRow {
120105 name,
121- kind: health(status, cutoff),
106+ kind: replication_health(status, now, window),
122107 last_ok: status.and_then(|s| s.last_ok_at.clone()),
123108 error: status
124109 .and_then(|s| s.last_error.clone())
@@ -138,8 +123,9 @@ struct PageData {
138123
139124 async fn page_data(state: &AppState, lang: Lang) -> forge_core::Result<PageData> {
140125 let config = &state.config.replication;
141- let db_cutoff = stamp_ago(Duration::from_secs(config.db_snapshot_minutes * 60 * 2));
142- let repo_cutoff = stamp_ago(Duration::from_secs(config.reconcile_minutes * 60 * 2));
126+ let now = now_unix();
127+ let db_window = window_secs(config.db_snapshot_minutes);
128+ let repo_window = window_secs(config.reconcile_minutes);
143129
144130 let statuses: HashMap<String, ReplicationStatus> = state
145131 .store
@@ -158,20 +144,20 @@ async fn page_data(state: &AppState, lang: Lang) -> forge_core::Result<PageData>
158144 Some(repo) => format!("{}/{}", repo.owner_name, repo.name),
159145 None => id.clone(),
160146 };
161- repos.push(repo_row(name, status, &repo_cutoff));
147+ repos.push(repo_row(name, status, now, repo_window));
162148 }
163149 for status in statuses.values() {
164150 if status.subject != DB_SUBJECT && !ids.contains(&status.subject) {
165151 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));
167153 }
168154 }
169155
170- let db_health = health(db, &db_cutoff);
156+ let db_health = replication_health(db, now, db_window);
171157 Ok(PageData {
172158 enabled: config.enabled(),
173- db_dot: db_health.dot(),
174- db_health: db_health.label(lang),
159+ db_dot: health_dot(db_health),
160+ db_health: health_text(db_health, lang),
175161 db_last_ok: db.and_then(|s| s.last_ok_at.clone()),
176162 db_last_attempt: db.and_then(|s| s.last_attempt_at.clone()),
177163 db_error: db.and_then(|s| s.last_error.clone()).unwrap_or_default(),
@@ -259,7 +245,7 @@ async fn replication_view(
259245 <select name="health" data-autosubmit="true">
260246 <option value="" selected=(health.is_none())>(all_label)</option>
261247 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>
263249 }
264250 </select>
265251 </label>
@@ -270,7 +256,7 @@ async fn replication_view(
270256 for row in rows.into_iter() {
271257 <div class="line" data-kb-row="">
272258 <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>
274260 </div>
275261 if !row.error.is_empty() {
276262 alert(message: row.error.as_str())
@@ -292,7 +278,7 @@ async fn page_fingerprint(state: &AppState) -> Result<String> {
292278 .map(|row| {
293279 (
294280 &row.name,
295- row.kind.label(Lang::En),
281+ health_text(row.kind, Lang::En),
296282 &row.last_ok,
297283 &row.error,
298284 )
@@ -323,7 +309,7 @@ async fn replication_events(cx: &Cx) -> Result<Response> {
323309 struct RepoList {
324310 has_repos: bool,
325311 finder: Finder,
326- health: Option<Health>,
312+ health: Option<ReplicationHealth>,
327313 rows: Vec<RepoRow>,
328314 page: u64,
329315 pages: u64,
@@ -336,26 +322,19 @@ fn repo_list(repos: Vec<RepoRow>, query: &NoticeQuery) -> RepoList {
336322 query.exact.as_deref(),
337323 query.case.as_deref(),
338324 );
339- let health = query.health.as_deref().and_then(Health::from_key);
325+ let health = query.health.as_deref().and_then(health_from_slug);
340326 let has_repos = !repos.is_empty();
341327 let matching: Vec<RepoRow> = repos
342328 .into_iter()
343329 .filter(|row| health.is_none_or(|h| row.kind == h))
344330 .filter(|row| finder.matches_any(&[row.name.as_str(), row.error.as_str()]))
345331 .collect();
346- let pages = (matching.len() as u64).div_ceil(REPO_ROWS as u64).max(1);
347- let page = query
348- .page
349- .as_deref()
350- .and_then(|p| p.parse::<u64>().ok())
351- .unwrap_or(1)
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);
332+ let (rows, page, pages) = paginate(
333+ matching,
334+ requested_page(query.page.as_deref()),
335+ REPO_ROWS as u64,
336+ );
337+ let health_key = health.map_or("", health_slug);
359338 let nav = pager_links(page, pages, |n| {
360339 let number = n.to_string();
361340 let mut params = finder.params();
@@ -678,28 +657,4 @@ mod tests {
678657 .any(|e| e.action == AuditAction::ReplicationReconcileStarted)
679658 );
680659 }
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- }
705660 }
crates/forge-web-account/src/pages/assets.rsmodified+4 -4
@@ -66,10 +66,10 @@ async fn custom_css_route(cx: &Cx) -> Result<(StatusCode, HeaderMap, String)> {
6666 if let Some(query) = uri(cx).query() {
6767 for (key, value) in form_urlencoded::parse(query.as_bytes()) {
6868 let (slot, default_vivid) = match key.as_ref() {
69- "al" => (0, 50),
70- "ad" => (1, 50),
71- "bl" => (2, 30),
72- "bd" => (3, 30),
69+ "al" => (0, accent::ACCENT_VIVID),
70+ "ad" => (1, accent::ACCENT_VIVID),
71+ "bl" => (2, accent::BASE_VIVID),
72+ "bd" => (3, accent::BASE_VIVID),
7373 _ => continue,
7474 };
7575 if let Some((hue, vivid)) = accent::custom_of(&value, default_vivid) {
crates/forge-web-account/src/pages/audit_log.rsmodified+18 -26
@@ -15,6 +15,7 @@ use crate::pages::issues_list::list_href;
1515 use crate::pages::settings_security::security_rail_for;
1616 use crate::state::AppState;
1717 use crate::views::find::{Finder, finder_field};
18+use crate::views::paging::{paginate, requested_page};
1819 use crate::views::parts::{RailItem, head, rail};
1920 use crate::views::repo_list::{PageLink, pager, pager_links};
2021 use crate::views::{rel_time, shell};
@@ -302,23 +303,6 @@ fn fold_groups(entries: &[AuditEntry], lang: Lang, finder: &Finder) -> Vec<Group
302303 groups
303304 }
304305
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-
322306 fn nav_for(
323307 page: u64,
324308 pages: u64,
@@ -615,9 +599,9 @@ async fn admin_audit_page(cx: &Cx) -> Result<impl View> {
615599 span.apply(&mut filter, &viewer.0.timezone);
616600 let mut notice: Option<String> = None;
617601 if !action.is_empty() {
618- match AuditAction::parse(&action) {
619- Some(known) => filter.action = Some(known),
620- None => notice = Some(g::no_action_named(lang, &action)),
602+ match action.parse::<AuditAction>() {
603+ Ok(known) => filter.action = Some(known),
604+ Err(_) => notice = Some(g::no_action_named(lang, &action)),
621605 }
622606 }
623607 if !actor.is_empty() {
@@ -633,7 +617,11 @@ async fn admin_audit_page(cx: &Cx) -> Result<impl View> {
633617 };
634618 let groups = fold_groups(&entries, lang, &finder);
635619 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+ );
637625 let mut params = keep_params(&finder, &action, &actor);
638626 params.extend(span.params());
639627 let nav = nav_for(page, pages, "/admin/audit", &params);
@@ -650,9 +638,9 @@ async fn admin_audit_page(cx: &Cx) -> Result<impl View> {
650638 async fn first_page_fingerprint(store: &Store, action: &str, actor: &str) -> Result<String> {
651639 let mut filter = AuditFilter::default();
652640 if !action.is_empty() {
653- match AuditAction::parse(action) {
654- Some(known) => filter.action = Some(known),
655- None => return Ok(String::new()),
641+ match action.parse::<AuditAction>() {
642+ Ok(known) => filter.action = Some(known),
643+ Err(_) => return Ok(String::new()),
656644 }
657645 }
658646 if !actor.is_empty() {
@@ -698,13 +686,17 @@ async fn own_log_page(cx: &Cx) -> Result<impl View> {
698686 ..Default::default()
699687 };
700688 span.apply(&mut filter, &viewer.0.timezone);
701- if let Some(known) = AuditAction::parse(&action) {
689+ if let Ok(known) = action.parse::<AuditAction>() {
702690 filter.action = Some(known);
703691 }
704692 let entries = store.list_audit_page(&filter, 0, SEARCH_CAP).await?;
705693 let groups = fold_groups(&entries, lang, &finder);
706694 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+ );
708700 let mut params = keep_params(&finder, &action, "");
709701 params.extend(span.params());
710702 let nav = nav_for(page, pages, "/settings/security/log", &params);
crates/forge-web-account/src/pages/banner.rsmodified+7 -7
@@ -47,31 +47,31 @@ async fn dismiss(cx: &Cx, Form(form): Form<DismissForm>) -> Result<SeeOther> {
4747 #[cfg(test)]
4848 mod tests {
4949 use crate::views::view_for;
50- use forge_core::config::BannerConfig;
50+ use forge_core::config::{BannerConfig, BannerLevel};
5151
52- fn config(message: &str, level: &str, expires: &str) -> BannerConfig {
52+ fn config(message: &str, level: BannerLevel, expires: &str) -> BannerConfig {
5353 BannerConfig {
5454 message: message.into(),
55- level: level.into(),
55+ level,
5656 expires: expires.into(),
5757 }
5858 }
5959
6060 #[test]
6161 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());
6363 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");
6565 assert!(view_for(&cfg, expiry - 1, None).is_some());
6666 assert!(view_for(&cfg, expiry, None).is_none());
6767 }
6868
6969 #[test]
7070 fn a_dismissed_hash_hides_only_that_message() {
71- let cfg = config("maintenance tonight", "info", "");
71+ let cfg = config("maintenance tonight", BannerLevel::Info, "");
7272 let shown = view_for(&cfg, 0, None).unwrap();
7373 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, "");
7575 assert!(view_for(&changed, 0, Some(&shown.hash)).is_some());
7676 }
7777
crates/forge-web-account/src/pages/explore.rsmodified+17 -41
@@ -13,9 +13,10 @@ use crate::live::{Topic, stream_changes};
1313 use crate::pages::issues_list::list_href;
1414 use crate::state::AppState;
1515 use crate::views::find::{Finder, finder_field};
16+use crate::views::paging::{paginate, requested_page};
1617 use crate::views::parts::head;
1718 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,
1920 };
2021 use crate::views::{now_unix, shell};
2122
@@ -56,7 +57,7 @@ async fn org_listing(
5657 state: &AppState,
5758 finder: &Finder,
5859 page: u64,
59-) -> Result<(Vec<User>, u64, u64)> {
60+) -> Result<(Vec<User>, u64, u64, u64)> {
6061 let mut all: Vec<User> = state
6162 .store
6263 .list_orgs()
@@ -71,13 +72,8 @@ async fn org_listing(
7172 .collect();
7273 all.sort_by_key(|org| org.username.to_lowercase());
7374 let total = all.len() as u64;
74- let page = page.clamp(1, total.div_ceil(PER_PAGE).max(1));
75- let shown = all
76- .into_iter()
77- .skip(((page - 1) * PER_PAGE) as usize)
78- .take(PER_PAGE as usize)
79- .collect();
80- Ok((shown, total, page))
75+ let (shown, page, pages) = paginate(all, page, PER_PAGE);
76+ Ok((shown, total, pages, page))
8177 }
8278
8379 fn explore_href(finder: &Finder, sort: &str, page: u64) -> String {
@@ -88,28 +84,14 @@ fn explore_href(finder: &Finder, sort: &str, page: u64) -> String {
8884 list_href("/explore", &params)
8985 }
9086
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-
9987 fn listing_args(query: &ExploreQuery) -> (Finder, &'static str, u64) {
10088 let finder = Finder::new(
10189 query.q.as_deref(),
10290 query.exact.as_deref(),
10391 query.case.as_deref(),
10492 );
105- let sort = sort_key(query.sort.as_deref());
106- let page = query
107- .page
108- .as_deref()
109- .and_then(|p| p.parse::<u64>().ok())
110- .unwrap_or(1)
111- .max(1);
112- (finder, sort, page)
93+ let sort = pick_sort(query.sort.as_deref(), &SORTS);
94+ (finder, sort, requested_page(query.page.as_deref()))
11395 }
11496
11597 async fn listing(
@@ -117,7 +99,7 @@ async fn listing(
11799 finder: &Finder,
118100 sort: &'static str,
119101 page: u64,
120-) -> Result<(Vec<(Repo, u64, String)>, u64, u64)> {
102+) -> Result<(Vec<(Repo, u64, String)>, u64, u64, u64)> {
121103 let sort_kind = match sort {
122104 "stars" => RepoSort::MostStars,
123105 "name" => RepoSort::Name,
@@ -135,13 +117,8 @@ async fn listing(
135117 })
136118 .collect();
137119 let total = matching.len() as u64;
138- let page = page.clamp(1, total.div_ceil(PER_PAGE).max(1));
139- let shown = matching
140- .into_iter()
141- .skip(((page - 1) * PER_PAGE) as usize)
142- .take(PER_PAGE as usize)
143- .collect();
144- Ok((shown, total, page))
120+ let (shown, page, pages) = paginate(matching, page, PER_PAGE);
121+ Ok((shown, total, pages, page))
145122 }
146123
147124 #[page("/explore")]
@@ -152,12 +129,12 @@ async fn explore_page(cx: &Cx) -> Result<impl View> {
152129 let lang = i18n::lang(cx, viewer.as_ref().map(|(u, _)| u));
153130 let state = context::<AppState>(cx);
154131 let on_orgs = orgs_tab(query);
155- let (listed, org_page, total, page) = if on_orgs {
156- let (orgs, total, page) = org_listing(state, &finder, page).await?;
157- (Vec::new(), orgs, total, page)
132+ let (listed, org_page, total, pages, page) = if on_orgs {
133+ let (orgs, total, pages, page) = org_listing(state, &finder, page).await?;
134+ (Vec::new(), orgs, total, pages, page)
158135 } else {
159- let (repos, total, page) = listing(state, &finder, sort, page).await?;
160- (repos, Vec::new(), total, page)
136+ let (repos, total, pages, page) = listing(state, &finder, sort, page).await?;
137+ (repos, Vec::new(), total, pages, page)
161138 };
162139 let (_, repos_all) = state
163140 .store
@@ -182,7 +159,6 @@ async fn explore_page(cx: &Cx) -> Result<impl View> {
182159 let avatar = crate::views::avatar_url(&org.username, hash.as_deref());
183160 orgs.push((org.username, avatar));
184161 }
185- let pages = total.div_ceil(PER_PAGE).max(1);
186162 let sort_links: Vec<SortLink> = SORTS
187163 .iter()
188164 .map(|(key, label)| SortLink {
@@ -242,12 +218,12 @@ async fn explore_fingerprint(
242218 on_orgs: bool,
243219 ) -> Result<String> {
244220 if on_orgs {
245- let (orgs, total, _) = org_listing(state, finder, page).await?;
221+ let (orgs, total, _, _) = org_listing(state, finder, page).await?;
246222 let mut lines = vec![total.to_string()];
247223 lines.extend(orgs.into_iter().map(|org| format!("org {}", org.username)));
248224 return Ok(lines.join("\n"));
249225 }
250- let (listed, total, _) = listing(state, finder, sort, page).await?;
226+ let (listed, total, _, _) = listing(state, finder, sort, page).await?;
251227 let mut lines = vec![total.to_string()];
252228 for (repo, stars, activity) in listed {
253229 lines.push(format!(
crates/forge-web-account/src/pages/import.rsmodified+3 -12
@@ -27,6 +27,7 @@ use crate::live::{changed_event, events_response};
2727 use crate::pages::new_repo::{owner_choices, repo_owner};
2828 use crate::pages::repo_ctx::still_readable;
2929 use crate::state::AppState;
30+use crate::views::paging::{paginate, requested_page};
3031 use crate::views::parts::{SubPart, head};
3132 use crate::views::repo_list::{PageLink, pager, pager_links};
3233 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> {
10671068 let state = context::<AppState>(cx);
10681069 let query = query_params::<JobsQuery>(cx)?;
10691070 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 page = query
1072- .page
1073- .as_deref()
1074- .and_then(|p| p.parse::<u64>().ok())
1075- .unwrap_or(1)
1076- .clamp(1, pages);
1071+ let (shown, page, pages) = paginate(all, requested_page(query.page.as_deref()), HISTORY_ROWS);
10771072 let user = state.store.user_by_id(&viewer.0.id).await?;
10781073 let mut rows = Vec::new();
1079- for job in all
1080- .into_iter()
1081- .skip(((page - 1) * HISTORY_ROWS) as usize)
1082- .take(HISTORY_ROWS as usize)
1083- {
1074+ for job in shown {
10841075 let repo = job_repo(state, user.as_ref(), &job).await?;
10851076 rows.push((job, repo));
10861077 }
crates/forge-web-account/src/pages/login.rsmodified+2 -12
@@ -14,7 +14,7 @@ use topcoat::view::{View, component, view};
1414
1515 use crate::audit::{self, Actor, Target};
1616 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,
1818 hash_password_async, login, logout, pending_login, pre_csrf_token, safe_next,
1919 set_pending_login, two_factor_enabled, verify_password_async, verify_second_factor,
2020 };
@@ -52,12 +52,6 @@ struct LoginForm {
5252 precsrf: String,
5353 }
5454
55-#[derive(Deserialize)]
56-struct CsrfForm {
57- #[serde(default)]
58- csrf: String,
59-}
60-
6155 #[derive(Deserialize)]
6256 struct TwoFactorForm {
6357 #[serde(default)]
@@ -725,11 +719,7 @@ mod tests {
725719 }
726720
727721 fn live_code(shared: &[u8], ahead: u64) -> String {
728- let now = std::time::SystemTime::now()
729- .duration_since(std::time::UNIX_EPOCH)
730- .unwrap()
731- .as_secs();
732- totp::code_at(shared, totp::step_for(now) + ahead)
722+ totp::code_at(shared, totp::step_for(forge_core::time::now_unix()) + ahead)
733723 }
734724
735725 fn both(pending: &str, precsrf_cookie: &str) -> String {
crates/forge-web-account/src/pages/needs_you.rsmodified+4 -13
@@ -1,7 +1,6 @@
11 use forge_core::User;
22 use forge_core::authz::{Action, authorize};
33 use forge_core::store::needs::Verdict;
4-use serde::Deserialize;
54 use topcoat::Result;
65 use topcoat::context::{Cx, context};
76 use topcoat::router::content::Form;
@@ -10,13 +9,14 @@ use topcoat::router::response::Response;
109 use topcoat::router::{Body, StatusCode, page, query_params, route};
1110 use topcoat::view::{View, component, view};
1211
13-use crate::auth::{current_user, require_csrf, require_user};
12+use crate::auth::{CsrfForm, current_user, require_csrf, require_user};
1413 use crate::i18n::authoring::{self as ga};
1514 use crate::i18n::needs::{self as ni, K};
1615 use crate::i18n::{self, Lang};
1716 use crate::live::{Topic, stream_wakes};
1817 use crate::pages::ci_runs::run_href;
1918 use crate::state::AppState;
19+use crate::views::paging::{page_count, requested_page};
2020 use crate::views::parts::{head, post_act};
2121 use crate::views::repo_list::{PageLink, pager, pager_links};
2222 use crate::views::{rel_time, repo_href, shell};
@@ -308,11 +308,8 @@ async fn load_full(
308308 requested: Option<&str>,
309309 ) -> Result<NeedSection> {
310310 let total = section.total(state, &user.id).await?;
311- let pages = total.div_ceil(PER_PAGE).max(1);
312- let page = requested
313- .and_then(|p| p.parse::<u64>().ok())
314- .unwrap_or(1)
315- .clamp(1, pages);
311+ let pages = page_count(total, PER_PAGE);
312+ let page = requested_page(requested).clamp(1, pages);
316313 let offset = (page - 1) * PER_PAGE;
317314 let rows = section
318315 .rows(state, user, lang, PER_PAGE as i64, offset as i64)
@@ -438,12 +435,6 @@ async fn needs_you(cx: &Cx) -> Result<impl View> {
438435 })
439436 }
440437
441-#[derive(Deserialize)]
442-struct CsrfForm {
443- #[serde(default)]
444- csrf: String,
445-}
446-
447438 #[route(POST "/needs-you/runs/dismiss")]
448439 async fn dismiss_failed_runs(cx: &Cx, Form(form): Form<CsrfForm>) -> Result<SeeOther> {
449440 let (user, _) = require_csrf(cx, &form.csrf).await?;
crates/forge-web-account/src/pages/org_ctx.rsmodified+3 -11
@@ -4,7 +4,6 @@ use forge_core::{Role, Session, User};
44 use topcoat::Result;
55 use topcoat::context::{Cx, context};
66 use topcoat::router::error::{forbidden, not_found};
7-use topcoat::router::request::uri;
87 use topcoat::view::{View, component, view};
98
109 use crate::auth::{check_csrf, require_user};
@@ -12,7 +11,7 @@ use crate::i18n::Lang;
1211 use crate::i18n::orgs::{self as g, K};
1312 use crate::pages::packages;
1413 use crate::state::AppState;
15-use crate::views::{alert, profile_items};
14+use crate::views::{notice_line, profile_items, query_value};
1615
1716 const NOTICE_PARAM: &str = "notice";
1817
@@ -139,10 +138,7 @@ pub fn notice_href(back: &str, word: &'static str) -> String {
139138 }
140139
141140 pub fn take_notice(cx: &Cx, lang: Lang) -> Option<(&'static str, bool)> {
142- let query = uri(cx).query()?;
143- let value = query
144- .split('&')
145- .find_map(|pair| pair.strip_prefix(NOTICE_PARAM)?.strip_prefix('='))?;
141+ let value = query_value(cx, NOTICE_PARAM)?;
146142 NOTICES
147143 .iter()
148144 .find(|(word, _, _)| *word == value)
@@ -208,11 +204,7 @@ pub async fn org_tabs(
208204 pub async fn org_notice(cx: &Cx, notice: Option<(&'static str, bool)>) -> Result<impl View> {
209205 Ok(view! {
210206 if let Some((text, is_error)) = notice {
211- if is_error {
212- alert(message: text)
213- } else {
214- <p class="state" role="status">(text)</p>
215- }
207+ notice_line(text: text, is_error: is_error)
216208 }
217209 })
218210 }
crates/forge-web-account/src/pages/org_members.rsmodified+2 -2
@@ -160,7 +160,7 @@ async fn org_members_add(cx: &Cx, Form(form): Form<AddForm>) -> Result<SeeOther>
160160 let state = context::<AppState>(cx);
161161 let back = ctx.href("/members");
162162
163- let Some(role) = OrgMemberRole::parse(form.role.trim()).ok() else {
163+ let Some(role) = form.role.trim().parse::<OrgMemberRole>().ok() else {
164164 return Ok(see_other(notice_href(&back, "invalid_role")));
165165 };
166166 let username = form.username.trim();
@@ -210,7 +210,7 @@ async fn org_members_role(cx: &Cx, Form(form): Form<RoleForm>) -> Result<SeeOthe
210210 let state = context::<AppState>(cx);
211211 let back = ctx.href("/members");
212212
213- let Some(role) = OrgMemberRole::parse(form.role.trim()).ok() else {
213+ let Some(role) = form.role.trim().parse::<OrgMemberRole>().ok() else {
214214 return Ok(see_other(notice_href(&back, "invalid_role")));
215215 };
216216 let user_id = form.user_id.trim();
crates/forge-web-account/src/pages/org_settings.rsmodified+3 -8
@@ -10,6 +10,7 @@ use topcoat::router::{page, path_param, route};
1010 use topcoat::view::{View, component, view};
1111
1212 use crate::audit::{self, Actor, Target};
13+use crate::auth::CsrfForm;
1314 use crate::i18n::orgs::{self as g, K};
1415 use crate::i18n::{self, Key, Lang, t};
1516 use crate::live::Topic;
@@ -38,12 +39,6 @@ struct SettingsForm {
3839 members_can_create: String,
3940 }
4041
41-#[derive(Deserialize)]
42-struct CsrfForm {
43- #[serde(default)]
44- csrf: String,
45-}
46-
4742 #[derive(Deserialize)]
4843 struct DeleteForm {
4944 #[serde(default)]
@@ -144,7 +139,7 @@ async fn settings_body(
144139 </div>
145140 <div class="acts asks">
146141 <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>
148143 </div>
149144 </form>
150145 </details>
@@ -196,7 +191,7 @@ async fn org_settings_save(cx: &Cx, Form(form): Form<SettingsForm>) -> Result<Se
196191 if description.chars().count() > MAX_DESCRIPTION_CHARS {
197192 return Ok(see_other(notice_href(&back, "description_length")));
198193 }
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 {
200195 return Ok(see_other(notice_href(&back, "invalid_role")));
201196 };
202197 let members_can_create_repos = !form.members_can_create.is_empty();
crates/forge-web-account/src/pages/org_teams.rsmodified+1 -6
@@ -9,6 +9,7 @@ use topcoat::router::{page, path_param, route};
99 use topcoat::view::{View, component, view};
1010
1111 use crate::audit::{self, Actor, Target};
12+use crate::auth::CsrfForm;
1213 use crate::i18n::orgs::{self as g, K};
1314 use crate::i18n::{self, Lang};
1415 use crate::pages::org_ctx::{
@@ -24,12 +25,6 @@ path_param!(team);
2425
2526 const MAX_TEAM_DESCRIPTION_CHARS: usize = 350;
2627
27-#[derive(Deserialize)]
28-struct CsrfForm {
29- #[serde(default)]
30- csrf: String,
31-}
32-
3328 #[derive(Deserialize)]
3429 struct TeamForm {
3530 #[serde(default)]
crates/forge-web-account/src/pages/passkeys.rsmodified+16 -10
@@ -26,7 +26,7 @@ use webauthn_rs_proto::ResidentKeyRequirement;
2626 use crate::api;
2727 use crate::audit::{self, Actor, Target};
2828 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,
3030 };
3131 use crate::client_ip::client_ip;
3232 use crate::i18n::{self, Key, Lang, s, t};
@@ -178,12 +178,6 @@ struct FinishForm {
178178 credential: String,
179179 }
180180
181-#[derive(Deserialize)]
182-struct CsrfForm {
183- #[serde(default)]
184- csrf: String,
185-}
186-
187181 #[derive(Deserialize)]
188182 struct RenameForm {
189183 #[serde(default)]
@@ -593,6 +587,13 @@ pub async fn build_panel(state: &AppState, user_id: &str) -> forge_core::Result<
593587 })
594588 }
595589
590+struct PasskeyEntry {
591+ item: PasskeyItem,
592+ rename_action: String,
593+ delete_action: String,
594+ field: String,
595+}
596+
596597 #[component]
597598 pub async fn passkeys_panel(
598599 cx: &Cx,
@@ -605,13 +606,18 @@ pub async fn passkeys_panel(
605606 let count_text = format!("{} {}", items.len(), s(lang, "passkeys", "geçiş anahtarı"));
606607 let usable = problem.is_none();
607608 let problem_text = problem.map(|why| why.message(lang));
608- let rows: Vec<(PasskeyItem, String, String, String)> = items
609+ let rows: Vec<PasskeyEntry> = items
609610 .into_iter()
610611 .map(|item| {
611612 let rename_action = format!("/settings/security/passkeys/{}/rename", item.id);
612613 let delete_action = format!("/settings/security/passkeys/{}/delete", item.id);
613614 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+ }
615621 })
616622 .collect();
617623 Ok(view! {
@@ -625,7 +631,7 @@ pub async fn passkeys_panel(
625631 if let Some(text) = problem_text {
626632 <p class="hint topic-warn">(text)</p>
627633 }
628- for (item, rename_action, delete_action, field) in rows.into_iter() {
634+ for PasskeyEntry { item, rename_action, delete_action, field } in rows {
629635 <details class="row-open">
630636 <summary class="line">
631637 <span class="name">(item.name.as_str())</span>
crates/forge-web-account/src/pages/profile.rsmodified+7 -29
@@ -29,9 +29,10 @@ use crate::render::markdown::render_markdown;
2929 use crate::state::AppState;
3030 use crate::views::find::{Finder, finder_field};
3131 use crate::views::heatmap::{Calendar, DayDetail, contribution_calendar};
32+use crate::views::paging::{page_count, paginate, requested_page};
3233 use crate::views::parts::{SubPart, head};
3334 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,
3536 };
3637 use crate::views::{
3738 NavItem, avatar_url, enc, now_unix, profile_items, repo_href, shell, user_href,
@@ -68,14 +69,6 @@ const SORTS: [(&str, K); 3] = [
6869 ("stars", K::SortMostStars),
6970 ];
7071
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-
7972 #[derive(Clone, Copy, PartialEq, Eq)]
8073 pub enum Tab {
8174 Overview,
@@ -145,8 +138,8 @@ async fn profile_page(cx: &Cx) -> Result<impl View> {
145138 query.exact.as_deref(),
146139 query.case.as_deref(),
147140 );
148- let page = page_number(query.page.as_deref());
149- let sort = sort_key(query.sort.as_deref());
141+ let page = requested_page(query.page.as_deref());
142+ let sort = pick_sort(query.sort.as_deref(), &SORTS);
150143
151144 let owned = RepoScope::OwnedBy(&user.id);
152145 let starred = RepoScope::StarredBy(&user.id);
@@ -233,8 +226,7 @@ async fn profile_page(cx: &Cx) -> Result<impl View> {
233226 .collect()
234227 };
235228 let snippet_total = snippets.len() as u64;
236- let snippet_pages = snippet_total.div_ceil(PER_PAGE).max(1);
237- let snippet_page = page.min(snippet_pages);
229+ let (snippets, snippet_page, snippet_pages) = paginate(snippets, page, PER_PAGE);
238230 let snippet_pager = pager_links(snippet_page, snippet_pages, |n| {
239231 profile_href(
240232 &user.username,
@@ -244,11 +236,6 @@ async fn profile_page(cx: &Cx) -> Result<impl View> {
244236 n,
245237 )
246238 });
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();
252239
253240 let (orgs, org_create_allowed) = match actor {
254241 Some(viewer_user) if tab == Tab::Organizations => {
@@ -310,12 +297,7 @@ async fn profile_page(cx: &Cx) -> Result<impl View> {
310297 })
311298 .collect();
312299 let total = matching.len() as u64;
313- let page = page.min(total.div_ceil(PER_PAGE).max(1));
314- let shown = matching
315- .into_iter()
316- .skip(((page - 1) * PER_PAGE) as usize)
317- .take(PER_PAGE as usize)
318- .collect();
300+ let (shown, _, _) = paginate(matching, page, PER_PAGE);
319301 (shown, total)
320302 };
321303 let tz = actor.map_or("UTC", |u| u.timezone.as_str());
@@ -330,7 +312,7 @@ async fn profile_page(cx: &Cx) -> Result<impl View> {
330312 } else {
331313 g::repo_count(lang, total)
332314 };
333- let pages = total.div_ceil(PER_PAGE).max(1);
315+ let pages = page_count(total, PER_PAGE);
334316 let page = page.min(pages);
335317 Listing {
336318 rows: listed
@@ -517,10 +499,6 @@ struct Listing {
517499 empty: &'static str,
518500 }
519501
520-fn page_number(raw: Option<&str>) -> u64 {
521- raw.and_then(|p| p.parse::<u64>().ok()).unwrap_or(1).max(1)
522-}
523-
524502 fn profile_href(name: &str, tab: &str, finder: &Finder, sort: &str, page: u64) -> String {
525503 let mut href = format!("/{}?tab={tab}", enc(name));
526504 if !finder.is_empty() {
crates/forge-web-account/src/pages/profile_pins.rsmodified+4 -30
@@ -128,9 +128,9 @@ async fn org_pins_save(cx: &Cx, RawForm(raw): RawForm) -> Result<SeeOther> {
128128
129129 #[cfg(test)]
130130 mod tests {
131+ use crate::test_support::fixture::{Reply, send_form};
131132 use forge_core::{Store, Visibility};
132- use topcoat::router::request::Request;
133- use topcoat::router::{Body, Router, to_bytes};
133+ use topcoat::router::Router;
134134
135135 use crate::auth::SESSION_COOKIE;
136136
@@ -142,12 +142,6 @@ mod tests {
142142 _dir: tempfile::TempDir,
143143 }
144144
145- struct Reply {
146- status: u16,
147- location: Option<String>,
148- body: String,
149- }
150-
151145 async fn site() -> Site {
152146 let dir = tempfile::tempdir().expect("tempdir");
153147 let state = crate::test_support::test_state(dir.path()).await;
@@ -172,30 +166,10 @@ mod tests {
172166 cookie: Option<&str>,
173167 fields: &[(&str, &str)],
174168 ) -> Reply {
175- let mut builder = Request::builder().method(method).uri(uri);
176- if let Some(cookie) = cookie {
177- builder = builder.header("cookie", cookie);
178- }
179- let body = form_urlencoded::Serializer::new(String::new())
169+ let form = form_urlencoded::Serializer::new(String::new())
180170 .extend_pairs(fields)
181171 .finish();
182- builder = builder.header("content-type", "application/x-www-form-urlencoded");
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- }
172+ send_form(&site.router, method, uri, cookie, Some(form)).await
199173 }
200174
201175 struct Seed {
crates/forge-web-account/src/pages/settings_appearance.rsmodified+4 -4
@@ -12,7 +12,10 @@ use topcoat::router::error::{SeeOther, see_other};
1212 use topcoat::router::{page, route};
1313 use topcoat::view::{View, component, view};
1414
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+};
1619 use crate::audit::{self, Actor, Target};
1720 use crate::auth::{require_csrf, require_user};
1821 use crate::custom_colour;
@@ -72,9 +75,6 @@ struct Stripe {
7275 hex: String,
7376 }
7477
75-const ACCENT_VIVID: u8 = 50;
76-const BASE_VIVID: u8 = 30;
77-
7878 fn row_lightness(base: bool, dark: bool) -> f64 {
7979 match (base, dark) {
8080 (false, true) => 0.75,
crates/forge-web-account/src/pages/settings_export.rsmodified+1 -8
@@ -9,7 +9,6 @@ use http::header::{
99 };
1010 use http_body::Frame;
1111 use http_body_util::StreamBody;
12-use serde::Deserialize;
1312 use tokio_util::io::ReaderStream;
1413 use topcoat::Result;
1514 use topcoat::context::{Cx, context};
@@ -19,7 +18,7 @@ use topcoat::router::response::Response;
1918 use topcoat::router::{Body, HeaderMap, StatusCode, page, path_param, query_params, route};
2019 use topcoat::view::{View, component, view};
2120
22-use crate::auth::{require_csrf, require_user, two_factor_enabled};
21+use crate::auth::{CsrfForm, require_csrf, require_user, two_factor_enabled};
2322 use crate::exporter;
2423 use crate::i18n::migrate::{self as g, K};
2524 use crate::i18n::{self, Key, Lang};
@@ -30,12 +29,6 @@ use crate::views::{alert, csrf_field, human_size, rel_time, shell};
3029
3130 path_param!(export_id);
3231
33-#[derive(Deserialize)]
34-struct CsrfForm {
35- #[serde(default)]
36- csrf: String,
37-}
38-
3932 #[query_params(error = bad_request)]
4033 struct SeenQuery {
4134 v: Option<String>,
crates/forge-web-account/src/pages/settings_gpg_tests.rsmodified+3 -39
@@ -1,8 +1,8 @@
11 use forge_core::Store;
2-use topcoat::router::request::Request;
3-use topcoat::router::{Body, Router, to_bytes};
2+use topcoat::router::Router;
43
54 use crate::auth::SESSION_COOKIE;
5+use crate::test_support::fixture::{Reply, send};
66
77 const CSRF: &str = "gpg-test-csrf";
88 const TOKEN: &str = "gpg-test-token";
@@ -15,12 +15,6 @@ struct Site {
1515 _dir: tempfile::TempDir,
1616 }
1717
18-struct Reply {
19- status: u16,
20- location: Option<String>,
21- body: String,
22-}
23-
2418 async fn site() -> (Site, bool) {
2519 let dir = tempfile::tempdir().expect("tempdir");
2620 let state = crate::test_support::test_state(dir.path()).await;
@@ -49,37 +43,7 @@ async fn call(
4943 cookie: Option<&str>,
5044 fields: Option<&[(&str, &str)]>,
5145 ) -> Reply {
52- let mut builder = Request::builder().method(method).uri(uri);
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- }
46+ send(&site.router, method, uri, cookie, fields).await
8347 }
8448
8549 #[tokio::test]
crates/forge-web-account/src/pages/settings_profile.rsmodified+1 -7
@@ -16,7 +16,7 @@ use topcoat::router::{BodyLimit, page, query_params, route};
1616 use topcoat::view::{View, component, view};
1717
1818 use crate::audit::{self, Actor, Target};
19-use crate::auth::{require_csrf, require_user};
19+use crate::auth::{CsrfForm, require_csrf, require_user};
2020 use crate::i18n::{self, Key, Lang, about_too_long, display_name_too_long, t};
2121 use crate::live::Topic;
2222 use crate::state::AppState;
@@ -46,12 +46,6 @@ struct ProfileForm {
4646 timezone: String,
4747 }
4848
49-#[derive(Deserialize)]
50-struct CsrfForm {
51- #[serde(default)]
52- csrf: String,
53-}
54-
5549 struct Draft {
5650 display_name: String,
5751 username: String,
crates/forge-web-account/src/pages/settings_security.rsmodified+14 -91
@@ -15,7 +15,7 @@ use topcoat::view::{View, component, view};
1515
1616 use crate::audit::{self, Actor, Target};
1717 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,
1919 verify_password_async, verify_second_factor,
2020 };
2121 use crate::i18n::packages::{self as pk, K as PK};
@@ -41,12 +41,6 @@ struct SecurityQuery {
4141 part: Option<String>,
4242 }
4343
44-#[derive(Deserialize)]
45-struct CsrfForm {
46- #[serde(default)]
47- csrf: String,
48-}
49-
5044 #[derive(Deserialize)]
5145 struct PasswordForm {
5246 #[serde(default)]
@@ -846,7 +840,7 @@ async fn two_factor_confirm(cx: &Cx, Form(form): Form<EnrollForm>) -> Result<imp
846840 match totp::verify(
847841 &shared,
848842 form.code.trim(),
849- totp::step_for(forge_core::time::unix_now()),
843+ totp::step_for(forge_core::time::now_unix()),
850844 totp_state.last_step,
851845 ) {
852846 Some(step) => {
@@ -1002,25 +996,20 @@ async fn two_factor_recovery(cx: &Cx, Form(form): Form<CodeForm>) -> Result<impl
1002996
1003997 #[cfg(test)]
1004998 mod tests {
1005- use std::sync::Arc;
1006-
1007999 use forge_core::time::stamp_after;
10081000 use forge_core::token::hash_token;
1009- use forge_core::{Config, Registration, Store, User, secret, totp};
1010- use forge_git::GitEnv;
1011- use topcoat::cookie::CookieLayer;
1001+ use forge_core::{User, secret, totp};
10121002 use topcoat::router::request::Request;
1013- use topcoat::router::{Body, Router, RouterBuilderDiscoverExt, to_bytes};
1003+ use topcoat::router::{Body, Router, to_bytes};
10141004
10151005 use crate::auth::{SESSION_COOKIE, hash_password_async};
10161006 use crate::state::AppState;
1017- use crate::throttle::{LOGIN_USER_LIMIT, Throttle, user_key};
1007+ use crate::throttle::{LOGIN_USER_LIMIT, user_key};
10181008
10191009 const TOKEN: &str = "security-test-session";
10201010 const OTHER_TOKEN: &str = "security-test-other-session";
10211011 const CSRF: &str = "security-test-csrf";
10221012 const PASSWORD: &str = "current password 1";
1023- const KEY: [u8; 32] = [7u8; 32];
10241013
10251014 struct Fixture {
10261015 router: Router,
@@ -1031,81 +1020,15 @@ mod tests {
10311020
10321021 async fn fixture() -> Fixture {
10331022 let dir = tempfile::tempdir().unwrap();
1034- let path = dir.path().to_path_buf();
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- };
1023+ let state = crate::test_support::test_state(dir.path()).await;
10941024 let hash = hash_password_async(PASSWORD.into()).await.unwrap();
1095- let user = store
1025+ let user = state
1026+ .store
10961027 .create_user("tahinli", None, &hash, false)
10971028 .await
10981029 .unwrap();
1099- let expiry = stamp_after(std::time::Duration::from_secs(3600));
1100- store
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();
1030+ crate::test_support::create_session(&state.store, &user.id, TOKEN, CSRF).await;
1031+ let router = crate::test_support::app_router(state.clone());
11091032 Fixture {
11101033 router,
11111034 state,
@@ -1146,12 +1069,12 @@ mod tests {
11461069 }
11471070
11481071 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()))
11501073 }
11511074
11521075 async fn enable_totp_directly(fx: &Fixture) -> Vec<u8> {
11531076 let shared = totp::new_secret();
1154- let sealed = secret::seal(&KEY, &shared).unwrap();
1077+ let sealed = secret::seal(&fx.state.key, &shared).unwrap();
11551078 fx.state
11561079 .store
11571080 .set_totp_secret(&fx.user.id, &sealed)
@@ -1466,7 +1389,7 @@ mod tests {
14661389 .unwrap();
14671390 assert!(!pending.enabled);
14681391 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();
14701393
14711394 let page = send(&fx.router, "GET", "/settings/security", true, "").await;
14721395 assert!(
@@ -1591,7 +1514,7 @@ mod tests {
15911514 .enabled
15921515 );
15931516
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);
15951518 let disable = format!("csrf={CSRF}&current_password={PASSWORD}&code={next}");
15961519 let reply = send(
15971520 &fx.router,
crates/forge-web-account/src/pages/settings_sessions.rsmodified+1 -7
@@ -7,7 +7,7 @@ use topcoat::router::error::{SeeOther, see_other};
77 use topcoat::router::route;
88
99 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};
1111 use crate::i18n::{Key, Lang, t};
1212 use crate::state::AppState;
1313 use crate::web_push::agent_label_in;
@@ -20,12 +20,6 @@ struct RevokeForm {
2020 id: String,
2121 }
2222
23-#[derive(Deserialize)]
24-struct CsrfForm {
25- #[serde(default)]
26- csrf: String,
27-}
28-
2923 pub(crate) fn session_label(lang: Lang, session: &Session) -> String {
3024 session.user_agent.as_deref().map_or_else(
3125 || t(lang, Key::UnknownBrowser).to_owned(),
crates/forge-web-account/src/pages/snippets.rsmodified+6 -6
@@ -586,9 +586,9 @@ async fn snippet_create(cx: &Cx, Form(form): Form<HashMap<String, String>>) -> R
586586 if step.is_none() {
587587 let store = &context::<AppState>(cx).store;
588588 let files = draft.saved_files();
589- let saved = match SnippetVisibility::parse(&draft.visibility) {
590- None => Err(g::t(lang, K::ChooseVisibility).to_owned()),
591- Some(visibility) => match store
589+ let saved = match draft.visibility.parse::<SnippetVisibility>() {
590+ Err(_) => Err(g::t(lang, K::ChooseVisibility).to_owned()),
591+ Ok(visibility) => match store
592592 .create_snippet(
593593 &user.id,
594594 &draft.title,
@@ -675,9 +675,9 @@ async fn snippet_update(cx: &Cx, Form(form): Form<HashMap<String, String>>) -> R
675675 if step.is_none() {
676676 let store = &context::<AppState>(cx).store;
677677 let files = draft.saved_files();
678- let saved = match SnippetVisibility::parse(&draft.visibility) {
679- None => Err(g::t(lang, K::ChooseVisibility).to_owned()),
680- Some(visibility) => match store
678+ let saved = match draft.visibility.parse::<SnippetVisibility>() {
679+ Err(_) => Err(g::t(lang, K::ChooseVisibility).to_owned()),
680+ Ok(visibility) => match store
681681 .update_snippet(
682682 &user.id,
683683 &snippet_id,
crates/forge-web-app/src/alerts.rsmodified+117 -118
@@ -1,11 +1,15 @@
11 use std::sync::OnceLock;
22 use std::sync::atomic::{AtomicBool, Ordering};
33
4-use forge_core::alerts::{self, AlertKind};
4+use forge_core::alerts::{self, AlertKind, AlertTopic};
55 use forge_core::mail::{MailKind, OutgoingMail};
66 use forge_core::store::backup_runs::RunKind;
7+use forge_core::store::replication::{
8+ DB_SUBJECT, ReplicationHealth, replication_health, window_secs,
9+};
710 use forge_core::time::stamp_to_unix;
811
12+use crate::backup::scheduler::BackupSetError;
913 use crate::i18n::{self, alerts as text};
1014 use crate::mail;
1115 use crate::notify_hub::publish_unread;
@@ -19,77 +23,11 @@ fn started() -> i64 {
1923 *STARTED.get_or_init(now_unix)
2024 }
2125
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-
8426 pub async fn raise(state: &AppState, topic: AlertTopic, key: &str, subject: &str, detail: &str) {
8527 if !state.live().alerts.kind_enabled(topic.kind()) {
8628 return;
8729 }
88- match state
89- .store
90- .raise_alert(key, topic.as_str(), subject, detail)
91- .await
92- {
30+ match state.store.raise_alert(key, topic, subject, detail).await {
9331 Ok(true) => {
9432 if topic == AlertTopic::RunnerOffline {
9533 OFFLINE_ACTIVE.store(true, Ordering::Relaxed);
@@ -105,12 +43,8 @@ pub async fn resolve(state: &AppState, key: &str) {
10543 match state.store.resolve_alert(key).await {
10644 Ok(Some(alert)) => {
10745 crate::live::admin().bump(&crate::live::Topic::AdminHealth);
108- let Some(topic) = AlertTopic::parse(&alert.kind) else {
109- tracing::error!(key, kind = %alert.kind, "alerts: resolved an unknown topic");
110- return;
111- };
112- if state.live().alerts.kind_enabled(topic.kind()) {
113- deliver(state, key, topic, &alert.subject, &alert.detail, true).await;
46+ if state.live().alerts.kind_enabled(alert.kind.kind()) {
47+ deliver(state, key, alert.kind, &alert.subject, &alert.detail, true).await;
11448 }
11549 }
11650 Ok(None) => {}
@@ -124,7 +58,7 @@ pub async fn event(state: &AppState, topic: AlertTopic, key: &str, subject: &str
12458 }
12559 match state
12660 .store
127- .record_alert_event(key, topic.as_str(), subject, detail)
61+ .record_alert_event(key, topic, subject, detail)
12862 .await
12963 {
13064 Ok(true) => deliver(state, key, topic, subject, detail, false).await,
@@ -155,7 +89,7 @@ async fn deliver(
15589 for admin in admins.into_iter().filter(|u| !u.is_org()) {
15690 if let Err(e) = state
15791 .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)
15993 .await
16094 {
16195 tracing::error!(error = %e, key, "alerts: writing an inbox row failed");
@@ -185,10 +119,10 @@ async fn deliver(
185119 }
186120 }
187121 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);
189123 let body = text::mail_body(
190124 lang,
191- &text::body(lang, topic.as_str(), subject, detail, resolved),
125+ &text::body(lang, topic, subject, detail, resolved),
192126 &format!("{base}/admin/health"),
193127 &format!("{base}/admin/server?tab=alerts"),
194128 );
@@ -217,7 +151,11 @@ pub async fn runner_seen(state: &AppState, runner_id: &str) {
217151 return;
218152 }
219153 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+ {
221159 Ok(keys) if keys.is_empty() => OFFLINE_ACTIVE.store(false, Ordering::Relaxed),
222160 Ok(_) => {}
223161 Err(e) => tracing::error!(error = %e, "alerts: reading the active alerts failed"),
@@ -255,28 +193,36 @@ pub async fn job_ended(
255193 .await;
256194 }
257195
258-pub async fn backup_finished(state: &AppState, outcome: Result<(), &str>) {
196+pub async fn backup_finished(state: &AppState, outcome: Result<(), &BackupSetError>) {
259197 match outcome {
260198 Ok(()) => {
261- resolve(state, "backup_failed").await;
262- resolve(state, "backup_verify_failed").await;
263- resolve(state, "backup_overdue").await;
199+ resolve(state, AlertTopic::BackupFailed.as_str()).await;
200+ resolve(state, AlertTopic::BackupVerifyFailed.as_str()).await;
201+ resolve(state, AlertTopic::BackupOverdue.as_str()).await;
264202 }
265- Err(error) => {
266- let topic = if error.contains("failed verification") {
267- AlertTopic::BackupVerifyFailed
268- } else {
269- AlertTopic::BackupFailed
203+ Err(failure) => {
204+ let (topic, error) = match failure {
205+ BackupSetError::Failed(error) => (AlertTopic::BackupFailed, error),
206+ BackupSetError::Verify(error) => (AlertTopic::BackupVerifyFailed, error),
270207 };
271- raise(state, topic, topic.as_str(), "", error).await;
208+ raise(state, topic, topic.as_str(), "", &error.to_string()).await;
272209 }
273210 }
274211 }
275212
276213 pub async fn fsck_finished(state: &AppState, outcome: Result<(), &str>) {
277214 match outcome {
278- Ok(()) => resolve(state, "fsck_failed").await,
279- Err(error) => raise(state, AlertTopic::FsckFailed, "fsck_failed", "", error).await,
215+ Ok(()) => resolve(state, AlertTopic::FsckFailed.as_str()).await,
216+ Err(error) => {
217+ raise(
218+ state,
219+ AlertTopic::FsckFailed,
220+ AlertTopic::FsckFailed.as_str(),
221+ "",
222+ error,
223+ )
224+ .await
225+ }
280226 }
281227 }
282228
@@ -284,7 +230,7 @@ pub async fn self_update_deployed(state: &AppState, version: &str) {
284230 raise(
285231 state,
286232 AlertTopic::SelfUpdateRestart,
287- "self_update_restart",
233+ AlertTopic::SelfUpdateRestart.as_str(),
288234 version,
289235 "",
290236 )
@@ -304,11 +250,18 @@ pub async fn self_update_failed(state: &AppState, run_id: &str, error: &str) {
304250
305251 pub async fn on_boot(state: &AppState) {
306252 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+ {
308258 Ok(keys) => OFFLINE_ACTIVE.store(!keys.is_empty(), Ordering::Relaxed),
309259 Err(e) => tracing::error!(error = %e, "alerts: reading the active alerts failed"),
310260 }
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
312265 && state.live().alerts.kind_enabled(AlertKind::SelfUpdate)
313266 {
314267 {
@@ -317,7 +270,7 @@ pub async fn on_boot(state: &AppState) {
317270 .unwrap_or(alert.subject.clone());
318271 deliver(
319272 state,
320- "self_update_restart",
273+ AlertTopic::SelfUpdateRestart.as_str(),
321274 AlertTopic::SelfUpdateRestart,
322275 &version,
323276 "",
@@ -359,7 +312,11 @@ pub async fn check_runners(state: &AppState, now: i64) {
359312 let since = seen.map_or_else(String::new, |t| forge_core::tz::format_in_tz(t, "UTC"));
360313 raise(state, AlertTopic::RunnerOffline, &key, &runner.name, &since).await;
361314 }
362- match state.store.active_alert_keys("runner_offline").await {
315+ match state
316+ .store
317+ .active_alert_keys(AlertTopic::RunnerOffline)
318+ .await
319+ {
363320 Ok(active) => {
364321 for key in active.into_iter().filter(|k| !offline.contains(k)) {
365322 resolve(state, &key).await;
@@ -392,7 +349,7 @@ async fn check_disk(state: &AppState) {
392349 let live = state.live();
393350 let cfg = &live.alerts;
394351 if !cfg.kind_enabled(AlertKind::Disk) {
395- resolve(state, "disk_low").await;
352+ resolve(state, AlertTopic::DiskLow.as_str()).await;
396353 return;
397354 }
398355 let dir = live.data_dir.clone();
@@ -416,20 +373,20 @@ async fn check_disk(state: &AppState) {
416373 raise(
417374 state,
418375 AlertTopic::DiskLow,
419- "disk_low",
376+ AlertTopic::DiskLow.as_str(),
420377 &dir.to_string_lossy(),
421378 &detail,
422379 )
423380 .await;
424381 } else {
425- resolve(state, "disk_low").await;
382+ resolve(state, AlertTopic::DiskLow.as_str()).await;
426383 }
427384 }
428385
429386 async fn check_backup_overdue(state: &AppState, now: i64) {
430387 let live = state.live();
431388 if !live.backup.enabled() || !live.alerts.kind_enabled(AlertKind::Backup) {
432- resolve(state, "backup_overdue").await;
389+ resolve(state, AlertTopic::BackupOverdue.as_str()).await;
433390 return;
434391 }
435392 let last_ok = match state.store.last_ok(RunKind::Backup).await {
@@ -448,20 +405,20 @@ async fn check_backup_overdue(state: &AppState, now: i64) {
448405 raise(
449406 state,
450407 AlertTopic::BackupOverdue,
451- "backup_overdue",
408+ AlertTopic::BackupOverdue.as_str(),
452409 "",
453410 &detail,
454411 )
455412 .await;
456413 } else {
457- resolve(state, "backup_overdue").await;
414+ resolve(state, AlertTopic::BackupOverdue.as_str()).await;
458415 }
459416 }
460417
461418 async fn check_replication(state: &AppState, now: i64) {
462419 let live = state.live();
463420 if !live.replication.enabled() || !live.alerts.kind_enabled(AlertKind::Replication) {
464- resolve(state, "replication").await;
421+ resolve(state, AlertTopic::Replication.as_str()).await;
465422 return;
466423 }
467424 let rows = match state.store.list_replication_status().await {
@@ -471,25 +428,32 @@ async fn check_replication(state: &AppState, now: i64) {
471428 return;
472429 }
473430 };
474- let window =
475- i64::try_from(live.replication.db_snapshot_minutes.saturating_mul(120)).unwrap_or(i64::MAX);
431+ let window = window_secs(live.replication.db_snapshot_minutes);
476432 let mut problem: Option<String> = None;
477433 for row in &rows {
478434 if let Some(error) = &row.last_error {
479435 problem = Some(format!("{}: {error}.", row.subject));
480436 break;
481437 }
482- if row.subject == forge_core::store::replication::DB_SUBJECT {
483- let ok = row.last_ok_at.as_deref().and_then(stamp_to_unix);
484- if ok.is_none_or(|t| now.saturating_sub(t) > window) {
438+ if row.subject == DB_SUBJECT {
439+ if replication_health(Some(row), now, window) != ReplicationHealth::Ok {
485440 problem = Some("The database snapshot has not reached the standby in time.".into());
486441 break;
487442 }
488443 }
489444 }
490445 match problem {
491- Some(detail) => raise(state, AlertTopic::Replication, "replication", "", &detail).await,
492- None => resolve(state, "replication").await,
446+ Some(detail) => {
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,
493457 }
494458 }
495459
@@ -547,8 +511,22 @@ mod tests {
547511 let tahinli = admin(&state, "tahinli", true).await;
548512 let second = admin(&state, "tahinli2", false).await;
549513
550- raise(&state, AlertTopic::DiskLow, "disk_low", "/data", "4% free").await;
551- raise(&state, AlertTopic::DiskLow, "disk_low", "/data", "3% free").await;
514+ raise(
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;
552530 assert_eq!(inbox(&state, &tahinli).await.len(), 1, "deduplicated");
553531 assert_eq!(inbox(&state, &second).await.len(), 1);
554532 assert_eq!(state.store.active_alerts().await.unwrap().len(), 1);
@@ -558,8 +536,8 @@ mod tests {
558536 "only the verified admin is mailed"
559537 );
560538
561- resolve(&state, "disk_low").await;
562- resolve(&state, "disk_low").await;
539+ resolve(&state, AlertTopic::DiskLow.as_str()).await;
540+ resolve(&state, AlertTopic::DiskLow.as_str()).await;
563541 let rows = inbox(&state, &tahinli).await;
564542 assert_eq!(rows.len(), 2, "raised and resolved, once each");
565543 assert!(rows.iter().any(|r| r.resolved));
@@ -567,7 +545,14 @@ mod tests {
567545 assert_eq!(queued_mail(&state).await, 2);
568546 assert_eq!(state.store.unread_count(&tahinli).await.unwrap(), 2);
569547
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;
571556 assert_eq!(
572557 inbox(&state, &tahinli).await.len(),
573558 3,
@@ -583,13 +568,27 @@ mod tests {
583568 let mut config = (*state.config).clone();
584569 config.alerts.on_disk = false;
585570 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;
587579 assert!(inbox(&state, &tahinli).await.is_empty());
588580
589581 config.alerts.on_disk = true;
590582 config.alerts.email = false;
591583 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;
593592 assert_eq!(inbox(&state, &tahinli).await.len(), 1);
594593 assert_eq!(queued_mail(&state).await, 0);
595594
@@ -598,7 +597,7 @@ mod tests {
598597 raise(
599598 &state,
600599 AlertTopic::BackupFailed,
601- "backup_failed",
600+ AlertTopic::BackupFailed.as_str(),
602601 "",
603602 "boom",
604603 )
crates/forge-web-app/src/api/gitea.rsmodified+2 -8
@@ -19,6 +19,7 @@ use topcoat::router::{StatusCode, path_param, route};
1919 use crate::api::{self, Refusal};
2020 use crate::client_ip::client_ip;
2121 use crate::state::AppState;
22+use crate::views::query_value;
2223
2324 path_param!(owner);
2425 path_param!(repo);
@@ -63,13 +64,6 @@ pub fn user_json(base: &str, id: &str, name: &str) -> Value {
6364 })
6465 }
6566
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-
7367 fn effective_headers(cx: &Cx) -> HeaderMap {
7468 let mut map = headers(cx).clone();
7569 if !map.contains_key(AUTHORIZATION)
@@ -582,7 +576,7 @@ async fn reactions_json(
582576 };
583577 out.push(json!({
584578 "user": user_json(&ctx.base, &user.id, username),
585- "reaction": summary.reaction.name(),
579+ "reaction": summary.reaction.as_str(),
586580 "created_at": created_at,
587581 }));
588582 }
crates/forge-web-app/src/api/statuses.rsmodified+1 -1
@@ -40,7 +40,7 @@ async fn report_status(cx: &Cx, body: Body) -> topcoat::Result<Response> {
4040 Ok(report) => report,
4141 Err(res) => return Ok(*res),
4242 };
43- let Some(status_state) = StatusState::parse(&report.state) else {
43+ let Ok(status_state) = report.state.parse::<StatusState>() else {
4444 return Ok(api::error(
4545 StatusCode::UNPROCESSABLE_ENTITY,
4646 "state must be one of pending, success, failure, error",
crates/forge-web-app/src/auth.rsmodified+13 -6
@@ -2,9 +2,10 @@ use std::sync::{Arc, OnceLock};
22 use std::time::Duration;
33
44 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};
66 use forge_core::token::{constant_time_eq, hash_token, random_b64url};
77 use forge_core::{Session, Store, User, secret, totp};
8+use serde::Deserialize;
89 use tokio::sync::Semaphore;
910 use topcoat::Result;
1011 use topcoat::context::{Cx, context};
@@ -169,6 +170,12 @@ pub async fn require_user(cx: &Cx) -> Result<(User, Session)> {
169170 }
170171 }
171172
173+#[derive(Deserialize)]
174+pub struct CsrfForm {
175+ #[serde(default)]
176+ pub csrf: String,
177+}
178+
172179 pub async fn require_csrf(cx: &Cx, submitted: &str) -> Result<(User, Session)> {
173180 let (user, session) = require_user(cx).await?;
174181 if check_csrf(&session, submitted) {
@@ -189,7 +196,7 @@ pub fn set_pending_login(
189196 user_id: &str,
190197 next: &str,
191198 ) -> 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());
193200 let sealed = secret::seal(key, format!("{expires}|{user_id}|{next}").as_bytes())?;
194201 let max_age = time::Duration::seconds(i64::try_from(PENDING_2FA_TTL.as_secs()).unwrap_or(0));
195202 session_jar(cx).add(
@@ -209,10 +216,10 @@ pub fn pending_login(cx: &Cx, key: &[u8; 32]) -> Option<PendingLogin> {
209216 let plain = secret::open(key, cookie.value()).ok()?;
210217 let text = String::from_utf8(plain).ok()?;
211218 let mut parts = text.splitn(3, '|');
212- let expires: u64 = parts.next()?.parse().ok()?;
219+ let expires: i64 = parts.next()?.parse().ok()?;
213220 let user_id = parts.next()?;
214221 let next = parts.next()?;
215- if unix_now() >= expires {
222+ if now_unix() >= expires {
216223 return None;
217224 }
218225 Some(PendingLogin {
@@ -258,7 +265,7 @@ pub async fn verify_second_factor(
258265 let shared = secret::open(key, sealed)?;
259266 let is_totp = input.len() == totp::DIGITS && input.bytes().all(|b| b.is_ascii_digit());
260267 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) {
262269 Some(step) => store.accept_totp_step(user_id, step).await,
263270 None => Ok(false),
264271 };
@@ -386,7 +393,7 @@ mod tests {
386393 let org = store.create_org("acme", &tahinli.id).await.unwrap();
387394 let shared = forge_core::totp::new_secret();
388395 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()));
390397 let recovery = forge_core::totp::recovery_code_hash("aaaa-bbbb");
391398 for id in [&org.id, &tahinli.id] {
392399 store.set_totp_secret(id, &sealed).await.unwrap();
crates/forge-web-app/src/backup/scheduler.rsmodified+28 -10
@@ -213,11 +213,9 @@ pub async fn backup_job(
213213 healthcheck::start(url).await;
214214 }
215215
216- let outcome = backup_set(state, &opts).await;
217- match &outcome {
218- Ok(_) => crate::alerts::backup_finished(state, Ok(())).await,
219- Err(e) => crate::alerts::backup_finished(state, Err(&e.to_string())).await,
220- }
216+ let set = backup_set(state, &opts).await;
217+ crate::alerts::backup_finished(state, set.as_ref().map(|_| ())).await;
218+ let outcome = set.map_err(BackupSetError::into_error);
221219 match &outcome {
222220 Ok(summary) => {
223221 let path = summary.path.to_string_lossy().into_owned();
@@ -246,19 +244,39 @@ pub async fn backup_job(
246244 outcome
247245 }
248246
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> {
250264 let source = BackupSource {
251265 store: state.store.clone(),
252266 git: (*state.git).clone(),
253267 base_url: state.config.base_url.clone(),
254268 };
255- let summary = create_backup(&source, opts).await?;
256- let report = verify_backup(&summary.path, &source.git).await?;
269+ let summary = create_backup(&source, opts)
270+ .await
271+ .map_err(BackupSetError::Failed)?;
272+ let report = verify_backup(&summary.path, &source.git)
273+ .await
274+ .map_err(BackupSetError::Failed)?;
257275 if !report.is_ok() {
258- return Err(Error::Invalid(format!(
276+ return Err(BackupSetError::Verify(Error::Invalid(format!(
259277 "the new backup set failed verification: {}",
260278 report.problems.join("; ")
261- )));
279+ ))));
262280 }
263281 Ok(summary)
264282 }
crates/forge-web-app/src/ci/api.rsmodified+15 -6
@@ -22,9 +22,10 @@ use topcoat::router::{Body, HeaderMap, StatusCode, path_param, route};
2222
2323 use crate::api::{self, Refusal};
2424 use crate::ci::{artifact_key, log_path};
25+use crate::i18n::Lang;
2526 use crate::self_update;
2627 use crate::state::AppState;
27-use crate::views::{bytes_text, https_clone_url};
28+use crate::views::{https_clone_url, human_size};
2829
2930 path_param!(job_id);
3031 path_param!(artifact_name);
@@ -437,8 +438,8 @@ fn idle_text(skips: &QueueSkips, free: Option<u64>) -> Option<String> {
437438 parts.push(format!(
438439 "{} waiting for memory: smallest needs {}, {} free",
439440 skips.too_big,
440- bytes_text(need),
441- bytes_text(free)
441+ human_size(Lang::En, need),
442+ human_size(Lang::En, free)
442443 ));
443444 }
444445 if let (Some(need), Some(free)) = (skips.starved_need, free) {
@@ -447,8 +448,8 @@ fn idle_text(skips: &QueueSkips, free: Option<u64>) -> Option<String> {
447448 starts until running jobs finish and it fits",
448449 skips.held_behind,
449450 forge_core::ci::STARVE_AFTER_SECS / 60,
450- bytes_text(need),
451- bytes_text(free)
451+ human_size(Lang::En, need),
452+ human_size(Lang::En, free)
452453 ));
453454 }
454455 Some(parts.join("; "))
@@ -969,6 +970,7 @@ async fn upload(state: &AppState, job: &CiJob, name: &str, body: Body) -> Result
969970 .max_artifact_mb
970971 .saturating_mul(MIB)
971972 .min(left);
973+ let job_bytes = state.live().ci.max_job_artifacts_mb.saturating_mul(MIB);
972974 let temp_key = format!("ci/tmp/{}", ulid::Ulid::generate());
973975 let mut writer = state
974976 .blobs
@@ -996,7 +998,14 @@ async fn upload(state: &AppState, job: &CiJob, name: &str, body: Body) -> Result
996998
997999 let artifact = match state
9981000 .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+ )
10001009 .await
10011010 {
10021011 Ok(artifact) => artifact,
crates/forge-web-app/src/ci/api_tests.rsmodified+10 -14
@@ -1003,21 +1003,17 @@ async fn job_token_reads_over_smart_http_but_never_pushes() {
10031003 .await
10041004 .unwrap()
10051005 .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- };
10201006 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();
10211017 fx.store
10221018 .create_run(
10231019 &NewRun {
crates/forge-web-app/src/ci/schedule.rsmodified+11 -12
@@ -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};
22 use forge_core::authz::{Action, authorize};
33 use forge_core::ci::{CiRun, NewJob, NewRun};
44 use forge_core::store::commit_status::StatusState;
@@ -12,7 +12,6 @@ use crate::internal::is_zero_oid;
1212 use crate::state::AppState;
1313
1414 pub const CONFIG_PATH: &str = ".forge/ci.toml";
15-const MAX_CONFIG_BYTES: usize = 64 * 1024;
1615 const MAX_WARNING_LINES: usize = 20;
1716 const MIB: u64 = 1024 * 1024;
1817
@@ -430,7 +429,7 @@ fn plan_jobs(cfg: &CiConfig) -> forge_core::Result<Vec<PlannedJob>> {
430429 Ok(jobs)
431430 }
432431
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> {
434433 match load(state, repo_id, commit).await {
435434 Loaded::Valid(config) => Some(config),
436435 Loaded::Missing | Loaded::Invalid(_) => None,
@@ -548,7 +547,7 @@ pub(super) mod tests {
548547 use forge_core::ci::{CiJob, CiRunner, JobState, RunState};
549548 use forge_core::store::commit_status::{CommitStatus, StatusState};
550549 use forge_core::time::stamp_after;
551- use forge_core::{User, Visibility};
550+ use forge_core::{NewPull, User, Visibility};
552551 use forge_git::repo::{init_bare, repo_path};
553552 use tempfile::TempDir;
554553
@@ -920,17 +919,17 @@ run = "make"
920919 let pr = fx
921920 .state
922921 .store
923- .create_pull(
924- &fx.repo.id,
922+ .create_pull(&NewPull {
923+ repo_id: &fx.repo.id,
925924 author_id,
926- "Change",
927- "",
928- "main",
925+ title: "Change",
926+ body: "",
927+ base_branch: "main",
929928 head_repo_id,
930- branch,
929+ head_branch: branch,
931930 head_oid,
932- head_oid,
933- )
931+ base_oid: head_oid,
932+ })
934933 .await
935934 .expect("create pull");
936935 on_pull_event(&fx.state, &fx.repo, &pr, author_id).await;
crates/forge-web-app/src/lfs/gc.rsmodified+2 -1
@@ -4,7 +4,7 @@ use std::time::{Duration, SystemTime};
44 use forge_core::Store;
55 use serde::{Deserialize, Serialize};
66
7-use super::{is_sha256_hex, lfs_root, tmp_dir};
7+use super::{is_sha256_hex, lfs_root, lock, tmp_dir};
88
99 pub const GC_MIN_AGE: Duration = Duration::from_secs(24 * 60 * 60);
1010
@@ -46,6 +46,7 @@ pub async fn gc(
4646 .await
4747 .map_err(|e| forge_core::Error::Io(std::io::Error::other(e)))??;
4848 for candidate in objects {
49+ let _lock = lock().await;
4950 summary.checked += 1;
5051 if !is_older_than(candidate.modified, now, min_age) {
5152 continue;
crates/forge-web-app/src/lfs/mod.rsmodified+7 -0
@@ -6,9 +6,16 @@ mod routes;
66 use std::path::{Path, PathBuf};
77
88 use forge_core::Result;
9+use tokio::sync::{Mutex, MutexGuard};
910
1011 use crate::state::AppState;
1112
13+static LOCK: Mutex<()> = Mutex::const_new(());
14+
15+pub async fn lock() -> MutexGuard<'static, ()> {
16+ LOCK.lock().await
17+}
18+
1219 pub fn is_sha256_hex(oid: &str) -> bool {
1320 oid.len() == 64
1421 && oid
crates/forge-web-app/src/lfs/routes.rsmodified+20 -12
@@ -1,5 +1,5 @@
11 use std::net::IpAddr;
2-use std::path::Path;
2+use std::path::{Path, PathBuf};
33 use std::sync::atomic::{AtomicU64, Ordering};
44
55 use forge_core::Action;
@@ -19,7 +19,7 @@ use topcoat::router::request::headers;
1919 use topcoat::router::response::Response;
2020 use topcoat::router::{Body, HeaderMap, StatusCode, path_param, route, to_bytes};
2121
22-use super::{is_sha256_hex, object_path, tmp_dir};
22+use super::{is_sha256_hex, lock, object_path, tmp_dir};
2323 use crate::access::{AccessError, find_repo, resolve_repo_for};
2424 use crate::client_ip::client_ip;
2525 use crate::git_http::{access_error, authenticate};
@@ -247,10 +247,14 @@ async fn put_object(cx: &Cx, body: Body) -> topcoat::Result<Response> {
247247 ));
248248 }
249249
250- let size = match receive_object(&state.config.data_dir, body, oid, max).await {
251- Ok(size) => size,
250+ let (temp, size) = match receive_object(&state.config.data_dir, body, oid, max).await {
251+ Ok(received) => received,
252252 Err(response) => return Ok(*response),
253253 };
254+ let _lock = lock().await;
255+ if let Err(response) = place_object(&state.config.data_dir, &temp, oid).await {
256+ return Ok(*response);
257+ }
254258 if let Err(e) = state.store.insert_lfs_object(&repo.id, oid, size).await {
255259 return Ok(server_error(e));
256260 }
@@ -354,7 +358,7 @@ async fn receive_object(
354358 body: Body,
355359 oid: &str,
356360 max: u64,
357-) -> Result<u64, Box<Response>> {
361+) -> Result<(PathBuf, u64), Box<Response>> {
358362 let dir = tmp_dir(data_dir);
359363 tokio::fs::create_dir_all(&dir)
360364 .await
@@ -373,18 +377,22 @@ async fn receive_object(
373377 let _ = tokio::fs::remove_file(&temp).await;
374378 return Err(unprocessable("the content does not match the oid"));
375379 }
380+ Ok((temp, size))
381+}
376382
383+async fn place_object(data_dir: &Path, temp: &Path, oid: &str) -> Result<(), Box<Response>> {
377384 let target = object_path(data_dir, oid);
378- if let Some(parent) = target.parent() {
379- tokio::fs::create_dir_all(parent)
380- .await
381- .map_err(|e| Box::new(server_error(e)))?;
385+ if let Some(parent) = target.parent()
386+ && let Err(e) = tokio::fs::create_dir_all(parent).await
387+ {
388+ let _ = tokio::fs::remove_file(temp).await;
389+ return Err(Box::new(server_error(e)));
382390 }
383- if let Err(e) = tokio::fs::rename(&temp, &target).await {
384- let _ = tokio::fs::remove_file(&temp).await;
391+ if let Err(e) = tokio::fs::rename(temp, &target).await {
392+ let _ = tokio::fs::remove_file(temp).await;
385393 return Err(Box::new(server_error(e)));
386394 }
387- Ok(size)
395+ Ok(())
388396 }
389397
390398 async fn write_and_hash(temp: &Path, body: Body, max: u64) -> Result<(u64, String), Box<Response>> {
crates/forge-web-app/src/lib.rsmodified+0 -1
@@ -55,6 +55,5 @@ pub mod build_info {
5555 pub const BUILD_SHA: &str = env!("FORGE_BUILD_SHA");
5656 pub const GIT_SHA: &str = env!("FORGE_GIT_SHA");
5757 pub const GIT_DATE: &str = env!("FORGE_GIT_DATE");
58- pub const GIT_DIRTY: bool = matches!(env!("FORGE_GIT_DIRTY").as_bytes(), b"1");
5958 pub const MAIN_CSS: &str = include_str!(concat!(env!("OUT_DIR"), "/main.css"));
6059 }
crates/forge-web-app/src/merge_queue.rsmodified+69 -4
@@ -1,12 +1,16 @@
1+use std::time::Duration;
2+
3+use forge_ci::config::DEFAULT_TIMEOUT_MINUTES;
14 use forge_core::merge_queue::{QueueEntry, QueueState, test_ref_name};
25 use forge_core::protection::effective;
36 use forge_core::store::commit_status::StatusState;
7+use forge_core::time::stamp_ago;
48 use forge_core::{Action, IssueState, MergeStyle, Mergeable, PullRequest, Repo, User, authorize};
59 use forge_git::browse::default_branch_commit;
610 use forge_git::pulls::{set_ref, update_ref_cas};
711 use forge_git::repo::repo_path;
812
9-use crate::ci::schedule::merge_queue_run;
13+use crate::ci::schedule::{config_at, merge_queue_run};
1014 use crate::merge::{
1115 ERR_CONFLICT, ERR_DRAFT, ERR_HEAD_MISSING, ERR_NEEDS_CHECKS, ERR_NOT_UP_TO_DATE,
1216 ERR_QUEUE_ALREADY, finish_merge, merge_commit, merge_gate,
@@ -225,9 +229,52 @@ async fn start(
225229 pr.issue.number,
226230 )
227231 .await?;
232+ schedule_timeout(state, repo, &entry.id, &entry.branch, &tested);
228233 Ok(true)
229234 }
230235
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+
231278 pub async fn evaluate(state: &AppState, repo: &Repo, entry_id: &str) -> forge_core::Result<bool> {
232279 let Some(entry) = state.store.queue_entry(entry_id).await? else {
233280 return Ok(true);
@@ -271,7 +318,7 @@ pub async fn evaluate(state: &AppState, repo: &Repo, entry_id: &str) -> forge_co
271318 let rule = effective(&rules, &repo.default_branch, &entry.branch);
272319 if !rule.required_checks.is_empty() {
273320 let statuses = state.store.statuses_for(&repo.id, &tested).await?;
274- let mut waiting = false;
321+ let mut missing: Option<&String> = None;
275322 for context in &rule.required_checks {
276323 match statuses
277324 .iter()
@@ -285,16 +332,34 @@ pub async fn evaluate(state: &AppState, repo: &Repo, entry_id: &str) -> forge_co
285332 fail(state, repo, &entry, &pr, "checks_failed", &text).await?;
286333 return Ok(true);
287334 }
288- _ => waiting = true,
335+ _ => {
336+ missing.get_or_insert(context);
337+ }
289338 }
290339 }
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+ }
292349 return Ok(false);
293350 }
294351 }
295352 land(state, repo, &entry, &pr).await
296353 }
297354
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+
298363 async fn land(
299364 state: &AppState,
300365 repo: &Repo,
crates/forge-web-app/src/mirrors/worker.rsmodified+5 -2
@@ -23,15 +23,17 @@ async fn run(state: AppState) {
2323 let mut running_mirrors: HashSet<String> = HashSet::new();
2424 let mut running_repos: HashSet<String> = HashSet::new();
2525 loop {
26+ let now = now_stamp();
2627 claim(
2728 &state,
2829 &policy,
30+ &now,
2931 &done_tx,
3032 &mut running_mirrors,
3133 &mut running_repos,
3234 )
3335 .await;
34- let nap = match state.store.next_mirror_due().await {
36+ let nap = match state.store.next_mirror_due(&now).await {
3537 Ok(next) => sleep_until(next.as_deref(), OffsetDateTime::now_utc(), BACKSTOP),
3638 Err(e) => {
3739 tracing::error!(error = %e, "mirrors: could not read the next due time");
@@ -52,11 +54,12 @@ async fn run(state: AppState) {
5254 async fn claim(
5355 state: &AppState,
5456 policy: &WebhookPolicy,
57+ now: &str,
5558 done_tx: &mpsc::UnboundedSender<(String, String)>,
5659 running_mirrors: &mut HashSet<String>,
5760 running_repos: &mut HashSet<String>,
5861 ) {
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 {
6063 Ok(due) => due,
6164 Err(e) => {
6265 tracing::error!(error = %e, "mirrors: could not list due mirrors");
crates/forge-web-app/src/oci/auth.rsmodified+2 -2
@@ -1,7 +1,7 @@
11 use forge_core::User;
22 use forge_core::oci as rules;
33 use forge_core::packages::{KIND_OCI, Package};
4-use forge_core::time::unix_now;
4+use forge_core::time::now_unix;
55 use http::header::{AUTHORIZATION, HeaderValue, WWW_AUTHENTICATE};
66 use topcoat::context::{Cx, context};
77 use topcoat::router::StatusCode;
@@ -37,7 +37,7 @@ pub async fn caller(cx: &Cx) -> Result<Caller, Refusal> {
3737 if let Some(bearer) = value.strip_prefix("Bearer ").map(str::trim)
3838 && !bearer.starts_with("forge_")
3939 {
40- let now = unix_now() as i64;
40+ let now = now_unix();
4141 return match rules::verify_token(&state.key, bearer, now) {
4242 Some(Some(user_id)) => match state.store.user_by_id(&user_id).await {
4343 Ok(Some(user)) if !user.is_org() => Ok(Caller { user: Some(user) }),
crates/forge-web-app/src/oci/gc.rsmodified+22 -1
@@ -1,4 +1,4 @@
1-use std::time::Duration;
1+use std::time::{Duration, SystemTime};
22
33 use tokio::sync::{Mutex, MutexGuard};
44
@@ -13,6 +13,27 @@ pub async fn lock() -> MutexGuard<'static, ()> {
1313 LOCK.lock().await
1414 }
1515
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+
1637 pub async fn sweep(state: &AppState, package_id: &str) -> forge_core::Result<usize> {
1738 let _guard = lock().await;
1839 let linked_before = forge_core::time::stamp_ago(GRACE);
crates/forge-web-app/src/post_update.rsmodified+27 -20
@@ -13,9 +13,7 @@ use crate::pulls_sync;
1313 use crate::state::AppState;
1414 use crate::webhooks::emit::{Sender, emit_item_action, emit_ref_update, lookup_sender};
1515
16-const MAX_PUSH_COMMITS: usize = 500;
17-const MAX_NEW_BRANCH_COMMITS: usize = 50;
18-const MAX_COAUTHOR_COMMITS: usize = 200;
16+const COMMIT_PAGE: usize = 100;
1917
2018 pub async fn after_ref_update(
2119 state: &AppState,
@@ -94,19 +92,32 @@ async fn pushed_commits(
9492 repo_dir: &Path,
9593 old: &str,
9694 new: &str,
97- max_update: usize,
9895 ) -> Option<Vec<CommitInfo>> {
9996 let old = (!is_zero_oid(old)).then_some(old);
100- let max = if old.is_some() {
101- max_update
102- } else {
103- MAX_NEW_BRANCH_COMMITS
104- };
105- match history::new_commits(&state.git, repo_dir, old, new, max).await {
106- Ok(commits) => Some(commits),
107- Err(e) => {
108- tracing::error!(error = %e, repo_id = %repo.id, "pushed commits: listing failed");
109- None
97+ let mut commits: Vec<CommitInfo> = Vec::new();
98+ loop {
99+ let page = match history::new_commits(
100+ &state.git,
101+ repo_dir,
102+ old,
103+ new,
104+ commits.len(),
105+ COMMIT_PAGE,
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);
110121 }
111122 }
112123 }
@@ -120,9 +131,7 @@ async fn close_from_pushed_commits(
120131 old: String,
121132 new: String,
122133 ) {
123- let Some(commits) =
124- pushed_commits(&state, &repo, &repo_dir, &old, &new, MAX_PUSH_COMMITS).await
125- else {
134+ let Some(commits) = pushed_commits(&state, &repo, &repo_dir, &old, &new).await else {
126135 return;
127136 };
128137 let actor = (!actor_id.is_empty()).then_some(actor_id.as_str());
@@ -142,9 +151,7 @@ async fn credit_coauthors(
142151 old: String,
143152 new: String,
144153 ) {
145- let Some(commits) =
146- pushed_commits(&state, &repo, &repo_dir, &old, &new, MAX_COAUTHOR_COMMITS).await
147- else {
154+ let Some(commits) = pushed_commits(&state, &repo, &repo_dir, &old, &new).await else {
148155 return;
149156 };
150157 let actor = (!actor_id.is_empty()).then_some(actor_id.as_str());
crates/forge-web-app/src/prune.rsmodified+3 -0
@@ -45,6 +45,9 @@ async fn sweep(state: &AppState) {
4545 Err(e) => tracing::error!(error = %e, repo_id = %id, "prune failed"),
4646 }
4747 }
48+ if let Err(e) = crate::oci::gc::sweep_orphans(state).await {
49+ tracing::error!(error = %e, "prune: oci orphan sweep failed");
50+ }
4851 }
4952
5053 async fn blank_unreachable_messages(state: &AppState, repo_id: &str, dir: &Path) {
crates/forge-web-app/src/pulls_sync.rsmodified+78 -78
@@ -312,7 +312,7 @@ pub async fn refresh_mergeability(
312312 mod tests {
313313 use std::path::{Path, PathBuf};
314314
315- use forge_core::{IssueState, Visibility};
315+ use forge_core::{IssueState, NewPull, Visibility};
316316 use forge_git::repo::{init_bare, repo_path};
317317 use tempfile::TempDir;
318318
@@ -440,17 +440,17 @@ mod tests {
440440 let pr = fx
441441 .state
442442 .store
443- .create_pull(
444- &fx.repo.id,
445- &fx.owner_id,
446- "Feature",
447- "",
448- "main",
449- &fx.repo.id,
450- "feature",
451- &f1,
452- &base,
453- )
443+ .create_pull(&NewPull {
444+ repo_id: &fx.repo.id,
445+ author_id: &fx.owner_id,
446+ title: "Feature",
447+ body: "",
448+ base_branch: "main",
449+ head_repo_id: &fx.repo.id,
450+ head_branch: "feature",
451+ head_oid: &f1,
452+ base_oid: &base,
453+ })
454454 .await
455455 .expect("create pull");
456456 let number = pr.issue.number;
@@ -492,17 +492,17 @@ mod tests {
492492 let pr = fx
493493 .state
494494 .store
495- .create_pull(
496- &fx.repo.id,
497- &fx.owner_id,
498- "Feature",
499- "",
500- "main",
501- &fx.repo.id,
502- "feature",
503- &f1,
504- &base,
505- )
495+ .create_pull(&NewPull {
496+ repo_id: &fx.repo.id,
497+ author_id: &fx.owner_id,
498+ title: "Feature",
499+ body: "",
500+ base_branch: "main",
501+ head_repo_id: &fx.repo.id,
502+ head_branch: "feature",
503+ head_oid: &f1,
504+ base_oid: &base,
505+ })
506506 .await
507507 .expect("create pull");
508508 let zero = "0".repeat(40);
@@ -540,17 +540,17 @@ mod tests {
540540 let pr = fx
541541 .state
542542 .store
543- .create_pull(
544- &fx.repo.id,
545- &fx.owner_id,
546- "Feature",
547- "",
548- "main",
549- &fx.repo.id,
550- "feature",
551- &f1,
552- &base,
553- )
543+ .create_pull(&NewPull {
544+ repo_id: &fx.repo.id,
545+ author_id: &fx.owner_id,
546+ title: "Feature",
547+ body: "",
548+ base_branch: "main",
549+ head_repo_id: &fx.repo.id,
550+ head_branch: "feature",
551+ head_oid: &f1,
552+ base_oid: &base,
553+ })
554554 .await
555555 .expect("create pull");
556556 assert_eq!(pr.mergeable, Mergeable::Unknown);
@@ -580,17 +580,17 @@ mod tests {
580580 let pr = fx
581581 .state
582582 .store
583- .create_pull(
584- &fx.repo.id,
585- &fx.owner_id,
586- "Feature",
587- "",
588- "main",
589- &fx.repo.id,
590- "feature",
591- &f1,
592- &base,
593- )
583+ .create_pull(&NewPull {
584+ repo_id: &fx.repo.id,
585+ author_id: &fx.owner_id,
586+ title: "Feature",
587+ body: "",
588+ base_branch: "main",
589+ head_repo_id: &fx.repo.id,
590+ head_branch: "feature",
591+ head_oid: &f1,
592+ base_oid: &base,
593+ })
594594 .await
595595 .expect("create pull");
596596 let store = &fx.state.store;
@@ -651,17 +651,17 @@ mod tests {
651651 let pr = fx
652652 .state
653653 .store
654- .create_pull(
655- &fx.repo.id,
656- &fx.owner_id,
657- "Feature",
658- "",
659- "main",
660- &fx.repo.id,
661- "feature",
662- &f1,
663- &base,
664- )
654+ .create_pull(&NewPull {
655+ repo_id: &fx.repo.id,
656+ author_id: &fx.owner_id,
657+ title: "Feature",
658+ body: "",
659+ base_branch: "main",
660+ head_repo_id: &fx.repo.id,
661+ head_branch: "feature",
662+ head_oid: &f1,
663+ base_oid: &base,
664+ })
665665 .await
666666 .expect("create pull");
667667
@@ -716,17 +716,17 @@ mod tests {
716716 let pr = fx
717717 .state
718718 .store
719- .create_pull(
720- &fx.repo.id,
721- &fx.owner_id,
722- "Feature",
723- "",
724- "main",
725- &fx.repo.id,
726- "feature",
727- &f1,
728- &base,
729- )
719+ .create_pull(&NewPull {
720+ repo_id: &fx.repo.id,
721+ author_id: &fx.owner_id,
722+ title: "Feature",
723+ body: "",
724+ base_branch: "main",
725+ head_repo_id: &fx.repo.id,
726+ head_branch: "feature",
727+ head_oid: &f1,
728+ base_oid: &base,
729+ })
730730 .await
731731 .expect("create pull");
732732 let store = &fx.state.store;
@@ -782,17 +782,17 @@ mod tests {
782782 let pr = fx
783783 .state
784784 .store
785- .create_pull(
786- &fx.repo.id,
787- &fx.owner_id,
788- "Feature",
789- "",
790- "main",
791- &fx.repo.id,
792- "feature",
793- &f1,
794- &base,
795- )
785+ .create_pull(&NewPull {
786+ repo_id: &fx.repo.id,
787+ author_id: &fx.owner_id,
788+ title: "Feature",
789+ body: "",
790+ base_branch: "main",
791+ head_repo_id: &fx.repo.id,
792+ head_branch: "feature",
793+ head_oid: &f1,
794+ base_oid: &base,
795+ })
796796 .await
797797 .expect("create pull");
798798 fx.state
crates/forge-web-app/src/test_support/fixture.rsmodified+83 -0
@@ -1,5 +1,10 @@
1+use std::fmt::Debug;
12 use std::path::{Path, PathBuf};
23 use std::process::Command;
4+use std::time::Duration;
5+
6+use bytes::Bytes;
7+use futures_util::{Stream, StreamExt};
38
49 use forge_core::{Store, Visibility};
510
@@ -149,3 +154,81 @@ pub async fn get(router: &Router, uri: &str) -> (u16, http::HeaderMap, Vec<u8>)
149154 .to_vec();
150155 (status, headers, body)
151156 }
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+}
crates/forge-web-app/src/views/diff.rsmodified+1 -1
@@ -779,7 +779,7 @@ async fn inline_comment_form(cx: &Cx, form: InlineForm, lang: Lang) -> Result<im
779779 if let Some(text) = suggest_line {
780780 <button type="button" class="act" data-suggest=(text.as_str())>(suggest_label)</button>
781781 }
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>
783783 </div>
784784 </form>
785785 })
crates/forge-web-app/src/views/mod.rsmodified+24 -42
@@ -3,6 +3,7 @@ pub mod commit_status;
33 pub mod diff;
44 pub mod find;
55 pub mod heatmap;
6+pub mod paging;
67 pub mod parts;
78 pub mod repo_list;
89 pub mod review_thread;
@@ -12,7 +13,7 @@ use std::collections::HashMap;
1213 use std::sync::OnceLock;
1314
1415 use forge_core::ci::RunState;
15-use forge_core::config::BannerConfig;
16+use forge_core::config::{BannerConfig, BannerLevel};
1617 use forge_core::store::shell_activity::{ActorRun, ActorRuns, InboxKinds};
1718 use forge_core::store::user_prefs::SOUND;
1819 use forge_core::token::hash_token;
@@ -1122,31 +1123,27 @@ pub fn repo_href(owner: &str, repo: &str, section: &str, rest: &str) -> String {
11221123 href
11231124 }
11241125
1125-pub use forge_core::time::now_unix;
1126+pub use forge_core::time::{civil_from_days, days_from_civil, iso_time, now_unix};
11261127
1127-pub fn iso_time(unix: i64) -> String {
1128- let days = unix.div_euclid(86_400);
1129- let secs = unix.rem_euclid(86_400);
1130- let (y, m, d) = civil_from_days(days);
1131- format!(
1132- "{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}Z",
1133- secs / 3600,
1134- secs % 3600 / 60,
1135- secs % 60
1136- )
1128+pub fn query_value(cx: &Cx, key: &str) -> Option<String> {
1129+ let query = uri(cx).query()?;
1130+ form_urlencoded::parse(query.as_bytes())
1131+ .find(|(name, _)| name == key)
1132+ .map(|(_, value)| value.into_owned())
11371133 }
11381134
1139-fn civil_from_days(days: i64) -> (i64, i64, i64) {
1140- let z = days + 719_468;
1141- let era = z.div_euclid(146_097);
1142- let doe = z.rem_euclid(146_097);
1143- let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
1144- let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
1145- let mp = (5 * doy + 2) / 153;
1146- let d = doy - (153 * mp + 2) / 5 + 1;
1147- let m = if mp < 10 { mp + 3 } else { mp - 9 };
1148- let y = yoe + era * 400 + i64::from(m <= 2);
1149- (y, m, d)
1135+pub fn take_notice_cookie<K: Copy>(
1136+ cx: &Cx,
1137+ cookie: &str,
1138+ notices: &[(&str, K, bool)],
1139+) -> Option<(K, bool)> {
1140+ let jar = cookies(cx);
1141+ let value = jar.get(cookie)?.value().to_owned();
1142+ jar.remove(topcoat::cookie::Cookie::build((cookie.to_owned(), "")).path("/"));
1143+ notices
1144+ .iter()
1145+ .find(|(word, _, _)| *word == value)
1146+ .map(|(_, key, is_error)| (*key, *is_error))
11501147 }
11511148
11521149 pub fn relative_time(lang: Lang, unix: i64, now: i64) -> String {
@@ -1512,16 +1509,6 @@ pub fn stamp_unix(stamp: &str) -> i64 {
15121509 days_from_civil(y, mo, d) * 86_400 + h * 3_600 + mi * 60 + s
15131510 }
15141511
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-
15251512 pub fn highlight_css_text() -> &'static str {
15261513 highlight_css()
15271514 }
@@ -1584,8 +1571,8 @@ pub struct BannerView {
15841571 pub expires: Option<i64>,
15851572 }
15861573
1587-pub fn banner_hash(message: &str, level: &str) -> String {
1588- hash_token(&format!("{level}\n{message}"))[..16].to_owned()
1574+pub fn banner_hash(message: &str, level: BannerLevel) -> String {
1575+ hash_token(&format!("{}\n{message}", level.as_str()))[..16].to_owned()
15891576 }
15901577
15911578 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
15931580 return None;
15941581 }
15951582 let message = config.message.trim().to_owned();
1596- let hash = banner_hash(&message, &config.level);
1583+ let hash = banner_hash(&message, config.level);
15971584 if dismissed == Some(hash.as_str()) {
15981585 return None;
15991586 }
16001587 Some(BannerView {
16011588 message,
1602- warning: config.level == "warning",
1589+ warning: config.level == BannerLevel::Warning,
16031590 hash,
16041591 expires: config.expires_unix(),
16051592 })
@@ -1640,11 +1627,6 @@ pub fn sound_attr(prefs: Option<&HashMap<String, String>>) -> Option<&'static st
16401627 (stored == "on").then_some("on")
16411628 }
16421629
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-
16481630 pub fn https_clone_url(config: &Config, owner: &str, name: &str) -> String {
16491631 format!(
16501632 "{}/{owner}/{name}.git",
crates/forge-web-app/src/views/paging.rsadded+18 -0
@@ -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+}
crates/forge-web-app/src/views/repo_list.rsmodified+7 -0
@@ -13,6 +13,13 @@ pub fn private_fact(lang: Lang, visibility: Visibility) -> Option<String> {
1313 .then(|| format!("{} \u{b7} ", i18n::visibility_label(lang, visibility)))
1414 }
1515
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+
1623 pub struct RepoRow {
1724 href: String,
1825 title: String,
crates/forge-web-app/src/views/timeline.rsmodified+2 -2
@@ -5,7 +5,7 @@ use topcoat::view::{View, component, view};
55
66 use super::{repo_href, short_oid};
77 use crate::i18n::Lang;
8-use crate::i18n::timeline::{self as tl, K};
8+use crate::i18n::timeline as tl;
99
1010 pub const MIN_BAR_PERCENT: u32 = 6;
1111
@@ -52,7 +52,7 @@ pub async fn history_strip(
5252 let max = bars.iter().map(|bar| bar.lines).max().unwrap_or(0);
5353 let newest = bars.len().saturating_sub(1);
5454 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);
5656 let items: Vec<BarView> = bars
5757 .into_iter()
5858 .enumerate()
crates/forge-web-app/src/webhooks/emit.rsmodified+13 -5
@@ -439,7 +439,7 @@ async fn new_commits(
439439 } else {
440440 MAX_NEW_REF_COMMITS
441441 };
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 {
443443 Ok(commits) => commits,
444444 Err(e) => {
445445 tracing::error!(error = %e, repo_id = %repo.id, "webhooks: listing push commits failed");
@@ -459,7 +459,7 @@ async fn new_commits(
459459 mod tests {
460460 use super::*;
461461 use crate::test_support::{KEY, test_state};
462- use forge_core::Visibility;
462+ use forge_core::{NewPull, Visibility};
463463
464464 async fn fixture(dir: &std::path::Path) -> (AppState, Repo, [String; 3]) {
465465 let state = test_state(dir).await;
@@ -671,9 +671,17 @@ mod tests {
671671 let zeros = "1".repeat(40);
672672 let pr = state
673673 .store
674- .create_pull(
675- &repo.id, &owner.id, "Title", "", "main", &repo.id, "feat", &zeros, &zeros,
676- )
674+ .create_pull(&NewPull {
675+ repo_id: &repo.id,
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+ })
677685 .await
678686 .expect("pr");
679687 let hook = hook_for(
crates/forge-web-base/src/accent.rsmodified+8 -5
@@ -1,6 +1,9 @@
11 use crate::accent_palette::{BASE_DEFAULT, BASES, Base, DEFAULT, PALETTES, Palette};
22 use crate::custom_colour;
33
4+pub const ACCENT_VIVID: u8 = 50;
5+pub const BASE_VIVID: u8 = 30;
6+
47 pub fn resolve(stored: &str) -> &'static Palette {
58 PALETTES
69 .iter()
@@ -56,7 +59,7 @@ pub fn custom_id(hue: u16, vivid: u8) -> String {
5659 }
5760
5861 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)
6063 }
6164
6265 fn canonical_number(digits: &str, max: u16) -> Option<u16> {
@@ -161,8 +164,8 @@ mod tests {
161164 let hues = (0..360u16).map(|hue| {
162165 (
163166 format!("hue-{hue}"),
164- accent_tokens(hue, 50, false),
165- accent_tokens(hue, 50, true),
167+ accent_tokens(hue, ACCENT_VIVID, false),
168+ accent_tokens(hue, ACCENT_VIVID, true),
166169 )
167170 });
168171 presets.chain(hues).collect()
@@ -175,8 +178,8 @@ mod tests {
175178 let hues = (0..360u16).map(|hue| {
176179 (
177180 format!("hue-{hue}"),
178- base_tokens(hue, 30, false),
179- base_tokens(hue, 30, true),
181+ base_tokens(hue, BASE_VIVID, false),
182+ base_tokens(hue, BASE_VIVID, true),
180183 )
181184 });
182185 presets.chain(hues).collect()
crates/forge-web-base/src/blobs.rsmodified+14 -1
@@ -1,5 +1,6 @@
11 use std::path::Path;
22 use std::sync::Arc;
3+use std::time::SystemTime;
34
45 use bytes::Bytes;
56 use forge_core::config::{R2Config, S3Config, StorageBackend, StorageConfig};
@@ -160,6 +161,17 @@ impl BlobStore {
160161 .map_err(storage_err)
161162 }
162163
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+
163175 pub async fn delete(&self, key: &str) -> Result<()> {
164176 match self.store.delete(&ObjectPath::from(key)).await {
165177 Ok(()) | Err(object_store::Error::NotFound { .. }) => Ok(()),
@@ -206,6 +218,7 @@ impl BlobWriter {
206218
207219 #[cfg(test)]
208220 mod tests {
221+ use forge_core::config::R2Jurisdiction;
209222 use object_store::memory::InMemory;
210223
211224 use super::*;
@@ -271,7 +284,7 @@ mod tests {
271284 let r2 = R2Config {
272285 account_id: "0123abcd".into(),
273286 bucket: "forge".into(),
274- jurisdiction: "eu".into(),
287+ jurisdiction: R2Jurisdiction::Eu,
275288 prefix: "/forge/".into(),
276289 access_key_id: "AKIA".into(),
277290 secret_access_key_file: secret,
crates/forge-web-base/src/custom_colour.rsmodified+7 -6
@@ -69,7 +69,7 @@ const NEUTRAL_CHROMA: f64 = 0.012;
6969 const GAMUT_EPS: f64 = 1e-6;
7070
7171 fn accent_factor(vivid: u8) -> f64 {
72- if vivid == 50 {
72+ if vivid == crate::accent::ACCENT_VIVID {
7373 return 1.0;
7474 }
7575 (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 {
104104 }
105105
106106 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);
108108 let mut tokens = base_tokens_at(hue, factor, dark);
109109 for _ in 0..10 {
110110 if base_is_readable(&tokens) {
@@ -357,14 +357,14 @@ mod tests {
357357 fn every_hue_gives_hex_colours_with_the_right_token_names_and_keyed_rules() {
358358 for hue in 0..360 {
359359 for dark in [false, true] {
360- let accent = accent_tokens(hue, 50, dark);
360+ let accent = accent_tokens(hue, crate::accent::ACCENT_VIVID, dark);
361361 let names: Vec<&str> = accent.decls().iter().map(|(n, _)| *n).collect();
362362 let expected: Vec<&str> = TOKEN_VARS.iter().map(|t| t.name).collect();
363363 assert_eq!(names, expected);
364364 for (name, value) in accent.decls() {
365365 assert!(is_hex_colour(value), "{hue} {dark} {name}: {value}");
366366 }
367- let base = base_tokens(hue, 30, dark);
367+ let base = base_tokens(hue, crate::accent::BASE_VIVID, dark);
368368 let names: Vec<&str> = base.decls().iter().map(|(n, _)| *n).collect();
369369 let expected: Vec<&str> = BASE_TOKEN_VARS.iter().map(|t| t.name).collect();
370370 assert_eq!(names, expected);
@@ -403,8 +403,9 @@ mod tests {
403403
404404 #[test]
405405 fn legacy_and_explicit_default_vividness_give_the_same_accent() {
406- let legacy = crate::accent::custom_of("hue-215", 50).unwrap();
407- let explicit = crate::accent::custom_of("hue-215-v50", 50).unwrap();
406+ let legacy = crate::accent::custom_of("hue-215", crate::accent::ACCENT_VIVID).unwrap();
407+ let explicit =
408+ crate::accent::custom_of("hue-215-v50", crate::accent::ACCENT_VIVID).unwrap();
408409 assert_eq!(legacy, explicit);
409410 for dark in [false, true] {
410411 let a = accent_tokens(legacy.0, legacy.1, dark);
crates/forge-web-base/src/i18n/accounts.rsmodified+50 -153
@@ -1,158 +1,55 @@
11 use super::Lang;
22
3-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
4-pub enum A {
5- Active,
6- Suspended,
7- LastLogin,
8- Repositories,
9- TwoFactor,
10- On,
11- Off,
12- Administrator,
13- Suspend,
14- Unsuspend,
15- SuspendReason,
16- GrantAdmin,
17- RevokeAdmin,
18- AdminHelp,
19- GenerateLink,
20- ResetLinkReady,
21- OkSuspended,
22- OkUnsuspended,
23- OkAdminOn,
24- OkAdminOff,
25- Ok2faDisabled,
26- ErrSelf,
27- ErrNoEmail,
28- AccountSuspended,
29- Dismiss,
30- Health,
31- BackupDirectory,
32- DatabaseFile,
33- Free,
34- CiQueue,
35- QueuedJobs,
36- RunnersOnline,
37- MailQueue,
38- Pending,
39- Failed,
40- LastBackup,
41- Replication,
42- NotConfigured,
43- Unavailable,
44- Never,
45- Ok,
46- Error,
47- Lagging,
48- Storage,
49- Services,
50- Fine,
51- DiskUsed,
52- Joined,
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- }
3+strings! {
4+ A;
5+ Active => "Active", "Etkin";
6+ Suspended => "Suspended", "Askıda";
7+ LastLogin => "Last sign-in", "Son giriş";
8+ Repositories => "Repositories", "Depolar";
9+ TwoFactor => "Two-factor", "İki adımlı doğrulama";
10+ On => "On", "Açık";
11+ Off => "Off", "Kapalı";
12+ Administrator => "Administrator", "Yönetici";
13+ Suspend => "Suspend", "Askıya al";
14+ Unsuspend => "Lift suspension", "Askıyı kaldır";
15+ SuspendReason => "Reason shown on the login page", "Giriş sayfasında gösterilen neden";
16+ GrantAdmin => "Make administrator", "Yönetici yap";
17+ RevokeAdmin => "Remove administrator", "Yöneticiliği kaldır";
18+ AdminHelp => "The last administrator cannot be demoted.", "Son yönetici yetkisiz bırakılamaz.";
19+ GenerateLink => "Generate reset link", "Sıfırlama bağlantısı üret";
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 => "Account suspended.", "Hesap askıya alındı.";
22+ OkUnsuspended => "Suspension lifted.", "Askı kaldırıldı.";
23+ OkAdminOn => "Administrator rights granted.", "Yönetici yetkisi verildi.";
24+ OkAdminOff => "Administrator rights removed.", "Yönetici yetkisi kaldırıldı.";
25+ Ok2faDisabled => "Two-factor disabled.", "İki adımlı doğrulama kapatıldı.";
26+ ErrSelf => "You cannot do this to your own account.", "Bunu kendi hesabınıza yapamazsınız.";
27+ ErrNoEmail => "Nothing to do.", "Yapılacak bir şey yok.";
28+ AccountSuspended => "This account is suspended.", "Bu hesap askıya alındı.";
29+ Dismiss => "Dismiss", "Kapat";
30+ Health => "Health", "Sağlık";
31+ BackupDirectory => "Backup directory", "Yedek dizini";
32+ DatabaseFile => "Database file", "Veritabanı dosyası";
33+ Free => "free of", "boş, toplam";
34+ CiQueue => "CI queue", "CI kuyruğu";
35+ QueuedJobs => "queued", "bekleyen";
36+ RunnersOnline => "runners online", "çalıştırıcı çevrim içi";
37+ MailQueue => "Mail queue", "Posta kuyruğu";
38+ Pending => "pending", "bekleyen";
39+ Failed => "failed", "başarısız";
40+ LastBackup => "Last backup", "Son yedek";
41+ Replication => "Replication", "Çoğaltma";
42+ NotConfigured => "Not configured", "Ayarlanmamış";
43+ Unavailable => "Unavailable", "Alınamadı";
44+ Never => "Never", "Hiç";
45+ Ok => "OK", "Tamam";
46+ Error => "Error", "Hata";
47+ Lagging => "Lagging", "Geride";
48+ Storage => "Storage", "Depolama";
49+ Services => "Services", "Hizmetler";
50+ Fine => "Everything looks fine", "Her şey yolunda";
51+ DiskUsed => "used", "kullanıldı";
52+ Joined => "Joined", "Katılım";
15653 }
15754
15855 pub fn suspended_message(lang: Lang, reason: &str) -> String {
crates/forge-web-base/src/i18n/admin.rsmodified+129 -540
@@ -3,415 +3,135 @@ use forge_core::store::backup_runs::{RunKind, RunTrigger};
33
44 use super::Lang;
55
6-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
7-pub enum K {
8- ActionLabel,
9- AddARunner,
10- AdminArea,
11- Administrator,
12- AllActions,
13- Anonymous,
14- AuditLog,
15- BackToRunners,
16- BackToUsers,
17- Backups,
18- CiRunners,
19- CopyTokenNow,
20- CreateRegistrationToken,
21- CreateUser,
22- Database,
23- DatabaseErrorPrefix,
24- DeleteAccountRest,
25- DeletesAccount,
26- DeleteOrgTitle,
27- DeleteUser,
28- Directory,
29- Disable,
30- Disabled,
31- Enable,
32- ErrAccountCannotBeDeleted,
33- ErrBackupsNotConfigured,
34- ErrChooseSecurity,
35- ErrInvalidUsername,
36- ErrNoAddressForTest,
37- ErrPasswordTooLong,
38- ErrPortRange,
39- ErrReplicationNotConfigured,
40- ErrTestNeedsMailOn,
41- ErrTypeUsernameExactly,
42- Filter,
43- FromAddress,
44- FromName,
45- Fsck,
46- Healthcheck,
47- HealthError,
48- HealthLagging,
49- HealthNever,
50- HealthOk,
51- Invites,
52- LastDbAttempt,
53- LastDbSnapshotShipped,
54- LastSeen,
55- LastSuccess,
56- ServerSettings,
57- SrvSaved,
58- SrvNothingChanged,
59- SrvResetDone,
60- SrvResetToFile,
61- SrvRestartNeeded,
62- SrvKindLive,
63- SrvKindRestart,
64- SrvKindReadOnly,
65- SrvSecretSet,
66- SrvSecretNotSet,
67- SrvFileValue,
68- SrvEmpty,
69- Mail,
70- MailHost,
71- MailTabSettings,
72- MailTabQueue,
73- MailFilterAll,
74- MailRetryNow,
75- MailDiscard,
76- MailRetried,
77- MailNotFailed,
78- MailDiscarded,
79- MailSentAt,
80- MailNothingMatches,
81- MailQueueEmpty,
82- MailPort,
83- MailSettingsSaved,
84- MovedToGhost,
85- NoEntries,
86- NoReposYet,
87- NoRunnersYet,
88- NoRunnerWithId,
89- NoRunsYet,
90- Older,
91- RecentRuns,
92- ReconcileNow,
93- ReconcileStarted,
94- RegisterARunner,
95- RegistrationToken,
96- RemovedWithAccount,
97- Replication,
98- ReplicationOff,
99- Repos,
100- Retention,
101- Role,
102- RoleAdmin,
103- RoleOrganization,
104- RoleUser,
105- RunBackupNow,
106- RunFsckNow,
107- RunnerDeletedNotice,
108- RunnerDisabledNotice,
109- RunnerEnabledNotice,
110- Runners,
111- ScheduledBackupsOff,
112- SecurityLogTitle,
113- SecurityNone,
114- SendMailCheckbox,
115- SendTestMailToMe,
116- Settings,
117- SmtpServer,
118- Standby,
119- StatusFailed,
120- StatusInProgress,
121- StatusOk,
122- TableLastError,
123- TableQueued,
124- TableTries,
125- TestQueued,
126- Token,
127- TokenCreateFailed,
128- TransferOrDeleteFirst,
129- UnknownHost,
130- Users,
131- OpenOrgSettings,
132- OrgNotAUser,
133- OrgReposFirst,
134- ViewOrg,
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- }
6+strings! {
7+ K;
8+ ActionLabel => "Action", "İşlem";
9+ AddARunner => "Add a runner", "Çalıştırıcı ekle";
10+ AdminArea => "Admin", "Yönetim";
11+ Administrator => "Administrator", "Yönetici";
12+ AllActions => "All actions", "Tüm işlemler";
13+ Anonymous => "anonymous", "anonim";
14+ AuditLog => "Audit log", "Denetim günlüğü";
15+ BackToRunners => "Back to runners", "Çalıştırıcılara dön";
16+ BackToUsers => "Back to users", "Kullanıcılara dön";
17+ Backups => "Backups", "Yedeklemeler";
18+ CiRunners => "CI runners", "CI çalıştırıcıları";
19+ CopyTokenNow => "Shown once.", "Bir kez gösterilir.";
20+ CreateRegistrationToken => "Create registration token", "Kayıt belirteci oluştur";
21+ CreateUser => "Create user", "Kullanıcı oluştur";
22+ Database => "Database", "Veritabanı";
23+ DatabaseErrorPrefix => "Database: ", "Veritabanı: ";
24+ DeleteAccountRest => ". This cannot be undone.", " hesabını siler. Bu işlem geri alınamaz.";
25+ DeletesAccount => "This deletes the account ", "Bu işlem ";
26+ DeleteOrgTitle => "Delete organization", "Kuruluşu sil";
27+ DeleteUser => "Delete user", "Kullanıcıyı sil";
28+ Directory => "Directory", "Dizin";
29+ Disable => "Disable", "Devre dışı bırak";
30+ Disabled => "disabled", "devre dışı";
31+ Enable => "Enable", "Etkinleştir";
32+ OpenOrgSettings => "Open organization settings", "Kuruluş ayarlarını aç";
33+ OrgNotAUser => " is an organization.", " bir kuruluştur.";
34+ OrgReposFirst => "Repositories it still owns:", "Hâlâ sahip olduğu depolar:";
35+ ErrAccountCannotBeDeleted => "this account cannot be deleted", "bu hesap silinemez";
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+ ErrChooseSecurity => "choose a security option", "bir güvenlik seçeneği seçin";
38+ ErrInvalidUsername => "invalid username", "geçersiz kullanıcı adı";
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+ ErrPasswordTooLong => "password is too long", "parola çok uzun";
41+ ErrPortRange => "the port must be a number from 1 to 65535", "bağlantı noktası 1 ile 65535 arasında bir sayı olmalı";
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+ ErrTestNeedsMailOn => "turn mail on and save the settings before sending a test", "test göndermeden önce e-postayı açın ve ayarları kaydedin";
44+ ErrTypeUsernameExactly => "Type the username exactly to confirm.", "Onaylamak için kullanıcı adını tam olarak yazın.";
45+ Filter => "Filter", "Filtrele";
46+ FromAddress => "From address", "Gönderen adresi";
47+ FromName => "From name", "Gönderen adı";
48+ Fsck => "Fsck", "Fsck";
49+ Healthcheck => "Healthcheck", "Sağlık denetimi";
50+ HealthError => "error", "hata";
51+ HealthLagging => "lagging", "gecikmeli";
52+ HealthNever => "never replicated", "hiç çoğaltılmadı";
53+ HealthOk => "ok", "tamam";
54+ Invites => "Invites", "Davetler";
55+ LastDbAttempt => "Last database attempt", "Son veritabanı denemesi";
56+ LastDbSnapshotShipped => "Last database snapshot shipped", "Son gönderilen veritabanı anlık görüntüsü";
57+ LastSeen => "Last seen", "Son görülme";
58+ LastSuccess => "Last success", "Son başarı";
59+ ServerSettings => "Server", "Sunucu";
60+ SrvSaved => "Server settings saved.", "Sunucu ayarları kaydedildi.";
61+ SrvNothingChanged => "Nothing changed.", "Değişiklik yok.";
62+ SrvResetDone => "Back to the file value.", "Dosya değerine dönüldü.";
63+ SrvResetToFile => "Reset to file value", "Dosya değerine sıfırla";
64+ SrvRestartNeeded => "restart needed", "yeniden başlatma gerekli";
65+ SrvKindLive => "live", "canlı";
66+ SrvKindRestart => "restart", "yeniden başlatma";
67+ SrvKindReadOnly => "read-only", "salt okunur";
68+ SrvSecretSet => "set", "ayarlı";
69+ SrvSecretNotSet => "not set", "ayarlı değil";
70+ SrvFileValue => "File value", "Dosya değeri";
71+ SrvEmpty => "(empty)", "(boş)";
72+ Mail => "Mail", "E-posta";
73+ MailTabSettings => "Settings", "Ayarlar";
74+ MailTabQueue => "Queue", "Kuyruk";
75+ MailFilterAll => "All", "Tümü";
76+ MailRetryNow => "Retry now", "Şimdi yeniden dene";
77+ MailDiscard => "Discard", "Vazgeç";
78+ MailRetried => "The message is queued for another try.", "Mesaj yeniden denenmek üzere kuyruğa alındı.";
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+ MailDiscarded => "The message was discarded.", "Mesajdan vazgeçildi.";
81+ MailSentAt => "Sent", "Gönderildi";
82+ MailNothingMatches => "No message is in this state.", "Bu durumda ileti yok.";
83+ MailQueueEmpty => "Nothing waiting to be sent.", "Gönderilmeyi bekleyen ileti yok.";
84+ MailHost => "Host", "Sunucu";
85+ MailPort => "Port", "Bağlantı noktası";
86+ MailSettingsSaved => "Mail settings saved.", "E-posta ayarları kaydedildi.";
87+ MovedToGhost => "Moved to the ghost user:", "Hayalet kullanıcıya taşınanlar:";
88+ NoEntries => "No entries.", "Kayıt yok.";
89+ NoReposYet => "No repos yet.", "Henüz depo yok.";
90+ NoRunnersYet => "No runners registered yet.", "Henüz kayıtlı çalıştırıcı yok.";
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+ NoRunsYet => "No runs yet.", "Henüz çalıştırma yok.";
93+ RecentRuns => "Recent runs", "Son çalıştırmalar";
94+ ReconcileNow => "Reconcile now", "Şimdi uzlaştır";
95+ ReconcileStarted => "Reconcile started.", "Uzlaştırma başlatıldı.";
96+ RegisterARunner => "Register a runner", "Bir çalıştırıcı kaydet";
97+ RegistrationToken => "Registration token", "Kayıt belirteci";
98+ RemovedWithAccount => "Removed with the account:", "Hesapla birlikte silinenler:";
99+ Replication => "Replication", "Çoğaltma";
100+ ReplicationOff => "Replication is off.", "Çoğaltma kapalı.";
101+ Repos => "Repos", "Depolar";
102+ Retention => "Retention", "Saklama";
103+ Role => "Role", "Rol";
104+ RoleAdmin => "admin", "yönetici";
105+ RoleOrganization => "organization", "kuruluş";
106+ RoleUser => "user", "kullanıcı";
107+ RunBackupNow => "Run backup now", "Şimdi yedekle";
108+ RunFsckNow => "Run fsck now", "Şimdi fsck çalıştır";
109+ RunnerDeletedNotice => "Runner deleted.", "Çalıştırıcı silindi.";
110+ RunnerDisabledNotice => "Runner disabled. It will not take new jobs.", "Çalıştırıcı devre dışı bırakıldı. Yeni iş almayacak.";
111+ RunnerEnabledNotice => "Runner enabled.", "Çalıştırıcı etkinleştirildi.";
112+ Runners => "Runners", "Çalıştırıcılar";
113+ ScheduledBackupsOff => "Scheduled backups are off.", "Zamanlanmış yedeklemeler kapalı.";
114+ SecurityLogTitle => "Security log", "Güvenlik günlüğü";
115+ SecurityNone => "None (plain text)", "Yok (düz metin)";
116+ SendMailCheckbox => "Send mail", "E-posta gönder";
117+ SendTestMailToMe => "Send test mail to me", "Bana test e-postası gönder";
118+ Settings => "Settings", "Ayarlar";
119+ SmtpServer => "SMTP server", "SMTP sunucusu";
120+ Standby => "Standby", "Bekleme kopyası";
121+ StatusFailed => "failed", "başarısız";
122+ StatusInProgress => "in progress", "sürüyor";
123+ StatusOk => "ok", "tamam";
124+ TableLastError => "Last error", "Son hata";
125+ TableQueued => "Queued", "Kuyruğa alındı";
126+ TableTries => "Tries", "Deneme";
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+ Token => "Token", "Belirteç";
129+ TokenCreateFailed => "The registration token could not be created. Nothing was changed.", "Kayıt belirteci oluşturulamadı. Hiçbir şey değiştirilmedi.";
130+ TransferOrDeleteFirst => "Transfer or delete these repositories first:", "Önce bu depoları devredin veya silin:";
131+ UnknownHost => "unknown", "bilinmiyor";
132+ Users => "Users", "Kullanıcılar";
133+ ViewOrg => "View organization", "Kuruluşu görüntüle";
134+ WhatHappens => "What happens", "Ne olacak";
415135 }
416136
417137 pub fn type_to_confirm(lang: Lang, name: &str) -> String {
@@ -530,137 +250,6 @@ pub fn no_user_named(lang: Lang, actor: &str) -> String {
530250 mod tests {
531251 use super::*;
532252
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-
664253 #[test]
665254 fn every_variant_has_text_in_both_languages() {
666255 for key in ALL {
crates/forge-web-base/src/i18n/alerts.rsmodified+122 -92
@@ -1,127 +1,170 @@
11 use super::Lang;
2+use forge_core::alerts::AlertTopic;
23
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 {
45 match (lang, topic, resolved) {
5- (Lang::En, "runner_offline", false) => format!("Runner {subject} is offline"),
6- (Lang::En, "runner_offline", true) => format!("Runner {subject} is back online"),
7- (Lang::Tr, "runner_offline", false) => format!("{subject} runner'ı çevrim dışı"),
8- (Lang::Tr, "runner_offline", true) => format!("{subject} runner'ı yeniden çevrim içi"),
9-
10- (Lang::En, "backup_failed", false) => "A backup failed".to_owned(),
11- (Lang::En, "backup_failed", true) => "Backups work again".to_owned(),
12- (Lang::Tr, "backup_failed", false) => "Bir yedekleme başarısız oldu".to_owned(),
13- (Lang::Tr, "backup_failed", true) => "Yedeklemeler yeniden çalışıyor".to_owned(),
14-
15- (Lang::En, "backup_verify_failed", false) => "Backup verification failed".to_owned(),
16- (Lang::En, "backup_verify_failed", true) => "Backup verification passes again".to_owned(),
17- (Lang::Tr, "backup_verify_failed", false) => "Yedek doğrulaması başarısız oldu".to_owned(),
18- (Lang::Tr, "backup_verify_failed", true) => "Yedek doğrulaması yeniden başarılı".to_owned(),
19-
20- (Lang::En, "backup_overdue", false) => "No recent backup".to_owned(),
21- (Lang::En, "backup_overdue", true) => "A backup finished, none overdue".to_owned(),
22- (Lang::Tr, "backup_overdue", false) => "Yakın zamanda yedek alınmadı".to_owned(),
23- (Lang::Tr, "backup_overdue", true) => "Bir yedek tamamlandı, gecikme yok".to_owned(),
24-
25- (Lang::En, "fsck_failed", false) => "The integrity check found problems".to_owned(),
26- (Lang::En, "fsck_failed", true) => "The integrity check passes again".to_owned(),
27- (Lang::Tr, "fsck_failed", false) => "Bütünlük denetimi sorun buldu".to_owned(),
28- (Lang::Tr, "fsck_failed", true) => "Bütünlük denetimi yeniden başarılı".to_owned(),
29-
30- (Lang::En, "disk_low", false) => "Disk space is low".to_owned(),
31- (Lang::En, "disk_low", true) => "Disk space is back to normal".to_owned(),
32- (Lang::Tr, "disk_low", false) => "Disk alanı azaldı".to_owned(),
33- (Lang::Tr, "disk_low", true) => "Disk alanı normale döndü".to_owned(),
34-
35- (Lang::En, "ci_killed", _) => format!("A CI job was killed on runner {subject}"),
36- (Lang::Tr, "ci_killed", _) => format!("{subject} runner'ında bir CI işi öldürüldü"),
37-
38- (Lang::En, "self_update_restart", false) => "Self-update deployed, restarting".to_owned(),
39- (Lang::En, "self_update_restart", true) => "Server restarted after self-update".to_owned(),
40- (Lang::Tr, "self_update_restart", false) => {
6+ (Lang::En, AlertTopic::RunnerOffline, false) => format!("Runner {subject} is offline"),
7+ (Lang::En, AlertTopic::RunnerOffline, true) => format!("Runner {subject} is back online"),
8+ (Lang::Tr, AlertTopic::RunnerOffline, false) => format!("{subject} runner'ı çevrim dışı"),
9+ (Lang::Tr, AlertTopic::RunnerOffline, true) => {
10+ format!("{subject} runner'ı yeniden çevrim içi")
11+ }
12+
13+ (Lang::En, AlertTopic::BackupFailed, false) => "A backup failed".to_owned(),
14+ (Lang::En, AlertTopic::BackupFailed, true) => "Backups work again".to_owned(),
15+ (Lang::Tr, AlertTopic::BackupFailed, false) => "Bir yedekleme başarısız oldu".to_owned(),
16+ (Lang::Tr, AlertTopic::BackupFailed, true) => "Yedeklemeler yeniden çalışıyor".to_owned(),
17+
18+ (Lang::En, AlertTopic::BackupVerifyFailed, false) => {
19+ "Backup verification failed".to_owned()
20+ }
21+ (Lang::En, AlertTopic::BackupVerifyFailed, true) => {
22+ "Backup verification passes again".to_owned()
23+ }
24+ (Lang::Tr, AlertTopic::BackupVerifyFailed, false) => {
25+ "Yedek doğrulaması başarısız oldu".to_owned()
26+ }
27+ (Lang::Tr, AlertTopic::BackupVerifyFailed, true) => {
28+ "Yedek doğrulaması yeniden başarılı".to_owned()
29+ }
30+
31+ (Lang::En, AlertTopic::BackupOverdue, false) => "No recent backup".to_owned(),
32+ (Lang::En, AlertTopic::BackupOverdue, true) => "A backup finished, none overdue".to_owned(),
33+ (Lang::Tr, AlertTopic::BackupOverdue, false) => "Yakın zamanda yedek alınmadı".to_owned(),
34+ (Lang::Tr, AlertTopic::BackupOverdue, true) => {
35+ "Bir yedek tamamlandı, gecikme yok".to_owned()
36+ }
37+
38+ (Lang::En, AlertTopic::FsckFailed, false) => {
39+ "The integrity check found problems".to_owned()
40+ }
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) => {
4162 "Kendini güncelleme dağıtıldı, yeniden başlıyor".to_owned()
4263 }
43- (Lang::Tr, "self_update_restart", true) => {
64+ (Lang::Tr, AlertTopic::SelfUpdateRestart, true) => {
4465 "Sunucu kendini güncelledikten sonra yeniden başladı".to_owned()
4566 }
4667
47- (Lang::En, "self_update_failed", _) => "Self-update failed".to_owned(),
48- (Lang::Tr, "self_update_failed", _) => "Kendini güncelleme başarısız oldu".to_owned(),
49-
50- (Lang::En, "replication", false) => "Standby replication has a problem".to_owned(),
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(),
68+ (Lang::En, AlertTopic::SelfUpdateFailed, _) => "Self-update failed".to_owned(),
69+ (Lang::Tr, AlertTopic::SelfUpdateFailed, _) => {
70+ "Kendini güncelleme başarısız oldu".to_owned()
71+ }
5472
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+ }
5685 }
5786 }
5887
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 {
6089 match (lang, topic, resolved) {
61- (Lang::En, "runner_offline", false) => format!(
90+ (Lang::En, AlertTopic::RunnerOffline, false) => format!(
6291 "No heartbeat since {detail}. Queued jobs wait for another runner until it returns."
6392 ),
64- (Lang::Tr, "runner_offline", false) => format!(
93+ (Lang::Tr, AlertTopic::RunnerOffline, false) => format!(
6594 "{detail} tarihinden beri sinyal yok. Sıradaki işler, geri dönene kadar başka bir runner bekler."
6695 ),
67- (Lang::En, "runner_offline", true) => format!("Runner {subject} checked in again."),
68- (Lang::Tr, "runner_offline", true) => format!("{subject} runner'ı yeniden bağlandı."),
96+ (Lang::En, AlertTopic::RunnerOffline, true) => {
97+ format!("Runner {subject} checked in again.")
98+ }
99+ (Lang::Tr, AlertTopic::RunnerOffline, true) => {
100+ format!("{subject} runner'ı yeniden bağlandı.")
101+ }
69102
70- (Lang::En, "backup_failed", true) => "The latest backup succeeded.".to_owned(),
71- (Lang::Tr, "backup_failed", true) => "Son yedekleme başarılı oldu.".to_owned(),
72- (Lang::En, "backup_verify_failed", true) => {
103+ (Lang::En, AlertTopic::BackupFailed, true) => "The latest backup succeeded.".to_owned(),
104+ (Lang::Tr, AlertTopic::BackupFailed, true) => "Son yedekleme başarılı oldu.".to_owned(),
105+ (Lang::En, AlertTopic::BackupVerifyFailed, true) => {
73106 "The latest backup set was verified.".to_owned()
74107 }
75- (Lang::Tr, "backup_verify_failed", true) => "Son yedek seti doğrulandı.".to_owned(),
76- (Lang::En, "fsck_failed", true) => "The latest integrity check was clean.".to_owned(),
77- (Lang::Tr, "fsck_failed", true) => "Son bütünlük denetimi temiz çıktı.".to_owned(),
108+ (Lang::Tr, AlertTopic::BackupVerifyFailed, true) => "Son yedek seti doğrulandı.".to_owned(),
109+ (Lang::En, AlertTopic::FsckFailed, true) => {
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(),
78113
79- (Lang::En, "backup_overdue", false) => format!(
114+ (Lang::En, AlertTopic::BackupOverdue, false) => format!(
80115 "No backup has succeeded within twice the schedule interval. Last good backup: {detail}."
81116 ),
82- (Lang::Tr, "backup_overdue", false) => format!(
117+ (Lang::Tr, AlertTopic::BackupOverdue, false) => format!(
83118 "Zamanlama aralığının iki katı içinde başarılı yedek yok. Son iyi yedek: {detail}."
84119 ),
85- (Lang::En, "backup_overdue", true) => "The backup schedule is back on track.".to_owned(),
86- (Lang::Tr, "backup_overdue", true) => "Yedekleme takvimi yeniden yolunda.".to_owned(),
120+ (Lang::En, AlertTopic::BackupOverdue, true) => {
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+ }
87126
88- (Lang::En, "disk_low", false) => format!("{subject}: {detail}."),
89- (Lang::Tr, "disk_low", false) => format!("{subject}: {detail}."),
90- (Lang::En, "disk_low", true) => format!("{subject} has enough free space again."),
91- (Lang::Tr, "disk_low", true) => format!("{subject} yeniden yeterli boş alana sahip."),
127+ (Lang::En, AlertTopic::DiskLow, false) => format!("{subject}: {detail}."),
128+ (Lang::Tr, AlertTopic::DiskLow, false) => format!("{subject}: {detail}."),
129+ (Lang::En, AlertTopic::DiskLow, true) => {
130+ format!("{subject} has enough free space again.")
131+ }
132+ (Lang::Tr, AlertTopic::DiskLow, true) => {
133+ format!("{subject} yeniden yeterli boş alana sahip.")
134+ }
92135
93- (Lang::En, "ci_killed", _) => format!(
136+ (Lang::En, AlertTopic::CiKilled, _) => format!(
94137 "{detail} ended with a kill signal, probably the out-of-memory killer. \
95138 Consider lowering the concurrency of runner {subject}."
96139 ),
97- (Lang::Tr, "ci_killed", _) => format!(
140+ (Lang::Tr, AlertTopic::CiKilled, _) => format!(
98141 "{detail} bir öldürme sinyaliyle sona erdi, büyük olasılıkla bellek yetersizliği. \
99142 {subject} runner'ının eşzamanlılığını düşürmeyi düşünün."
100143 ),
101144
102- (Lang::En, "self_update_restart", false) => {
145+ (Lang::En, AlertTopic::SelfUpdateRestart, false) => {
103146 format!("Version {subject} is installed. The server is restarting to run it.")
104147 }
105- (Lang::Tr, "self_update_restart", false) => {
148+ (Lang::Tr, AlertTopic::SelfUpdateRestart, false) => {
106149 format!("{subject} sürümü kuruldu. Sunucu onu çalıştırmak için yeniden başlıyor.")
107150 }
108- (Lang::En, "self_update_restart", true) => {
151+ (Lang::En, AlertTopic::SelfUpdateRestart, true) => {
109152 format!("The server is running version {subject}.")
110153 }
111- (Lang::Tr, "self_update_restart", true) => {
154+ (Lang::Tr, AlertTopic::SelfUpdateRestart, true) => {
112155 format!("Sunucu {subject} sürümünü çalıştırıyor.")
113156 }
114157
115- (_, "self_update_failed", _) => detail.to_owned(),
158+ (_, AlertTopic::SelfUpdateFailed, _) => detail.to_owned(),
116159
117- (Lang::En, "replication", false) => {
160+ (Lang::En, AlertTopic::Replication, false) => {
118161 format!("{detail} The standby may be behind until this is fixed.")
119162 }
120- (Lang::Tr, "replication", false) => {
163+ (Lang::Tr, AlertTopic::Replication, false) => {
121164 format!("{detail} Bu düzelene kadar yedek sunucu geride kalabilir.")
122165 }
123- (Lang::En, "replication", true) => "The standby is up to date.".to_owned(),
124- (Lang::Tr, "replication", true) => "Yedek sunucu güncel.".to_owned(),
166+ (Lang::En, AlertTopic::Replication, true) => "The standby is up to date.".to_owned(),
167+ (Lang::Tr, AlertTopic::Replication, true) => "Yedek sunucu güncel.".to_owned(),
125168
126169 _ => detail.to_owned(),
127170 }
@@ -170,28 +213,15 @@ pub fn mail_body(lang: Lang, body: &str, health_url: &str, settings_url: &str) -
170213 mod tests {
171214 use super::*;
172215
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-
186216 #[test]
187217 fn every_topic_is_worded_in_both_languages_without_em_dashes() {
188218 for lang in [Lang::En, Lang::Tr] {
189- for topic in TOPICS {
219+ for topic in AlertTopic::ALL {
190220 for resolved in [false, true] {
191221 let t = title(lang, topic, "tahinli-ci", resolved);
192222 let b = body(lang, topic, "tahinli-ci", "detail", resolved);
193- assert_ne!(t, *topic, "{topic} has a title");
194- assert!(!b.is_empty(), "{topic} has a body");
223+ assert_ne!(t, topic.as_str(), "{topic:?} has a title");
224+ assert!(!b.is_empty(), "{topic:?} has a body");
195225 assert!(!t.contains('\u{2014}') && !b.contains('\u{2014}'));
196226 }
197227 }
crates/forge-web-base/src/i18n/authoring.rsmodified+12 -39
@@ -1,44 +1,17 @@
11 use super::Lang;
22
3-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
4-pub enum K {
5- Reviewers,
6- RequestReview,
7- ReviewerName,
8- WithdrawRequest,
9- ReviewRequests,
10- NoReviewRequests,
11- ReviewerUnknown,
12- ReviewerNoAccess,
13- ReviewerIsAuthor,
14- ReviewerAlready,
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- }
3+strings! {
4+ K;
5+ Reviewers => "Reviewers", "İnceleyenler";
6+ RequestReview => "Request review", "İnceleme iste";
7+ ReviewerName => "Username", "Kullanıcı adı";
8+ WithdrawRequest => "Withdraw request", "İsteği geri çek";
9+ ReviewRequests => "Review requests", "İnceleme istekleri";
10+ NoReviewRequests => "Nobody is waiting for your review.", "İncelemenizi bekleyen yok.";
11+ ReviewerUnknown => "No such user.", "Böyle bir kullanıcı yok.";
12+ ReviewerNoAccess => "That user cannot read this repository.", "Bu kullanıcı bu depoyu okuyamaz.";
13+ ReviewerIsAuthor => "The author cannot review their own pull request.", "Yazar kendi değişiklik isteğini inceleyemez.";
14+ ReviewerAlready => "A review is already requested from that user.", "Bu kullanıcıdan zaten inceleme istendi.";
4215 }
4316
4417 pub fn tasks_progress(lang: Lang, done: usize, total: usize) -> String {
crates/forge-web-base/src/i18n/browse.rsmodified+1 -18
@@ -1,24 +1,7 @@
11 use super::Lang;
22
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-
213 strings! {
4+ K;
225 DiffView => "Diff view", "Fark görünümü";
236 Unified => "Unified", "Birleşik";
247 Split => "Split", "Bölünmüş";
crates/forge-web-base/src/i18n/code.rsmodified+108 -463
@@ -2,349 +2,114 @@ use forge_core::store::commit_status::StatusState;
22
33 use super::Lang;
44
5-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
6-pub enum K {
7- SearchWord,
8- SearchFailed,
9- SearchCodePlaceholder,
10- SearchButton,
11- RefField,
12- PathField,
13- MatchCase,
14- RegexOption,
15- SearchFilesAt,
16- NoMatches,
17- ShowingFirst,
18- ShowingFirstEnd,
19- CloneTitle,
20- CopyCloneUrl,
21- CloneCopied,
22- CloneCopyFailed,
23- BranchesTitle,
24- FilterRefs,
25- ViewAllBranches,
26- ViewAllTags,
27- EmptyRepoPush,
28- OverHttps,
29- OverSsh,
30- DownloadZip,
31- DownloadTarGz,
32- RecentPushes,
33- HadRecentPushes,
34- CompareAndPr,
35- BranchLabel,
36- KindDir,
37- KindFile,
38- KindExec,
39- KindLink,
40- KindSubmodule,
41- Rendered,
42- SourceToggle,
43- HistoryLink,
44- RawLink,
45- DownloadLink,
46- SymlinkPrefix,
47- SubmodulePrefix,
48- SubmoduleSuffix,
49- TruncatedPrefix,
50- ViewFullRaw,
51- LivePathGone,
52- StatusAdded,
53- StatusDeleted,
54- StatusModified,
55- StatusRenamed,
56- StatusCopied,
57- StatusTypeChanged,
58- NoFileChanges,
59- BinaryFileChanged,
60- DiffTooLargePrefix,
61- ViewFile,
62- DiffTooLarge,
63- CommentOnLine,
64- AddReviewComment,
65- StartReview,
66- CommentLabel,
67- AddSingleComment,
68- CancelLink,
69- ThisCommit,
70- ShowFullMessage,
71- CommitStatusPrefix,
72- StateSuccess,
73- StateFailure,
74- StateError,
75- StatePending,
76- NoChecksReported,
77- AllChecksPassed,
78- ChecksPending,
79- SomeChecksFailed,
80- ShowChecks,
81- DetailsLink,
82- AuthorLabel,
83- CommitterLabel,
84- CoAuthorAnd,
85- CoAuthorsLabel,
86- RootCommit,
87- CommitChangesLabel,
88- ParentLabel,
89- BrowseFiles,
90- SigVerified,
91- SigUnverified,
92- CommitsOn,
93- FilteredTo,
94- ClearFilter,
95- NoCommits,
96- BrowseFilesShort,
97- NewerLink,
98- OlderLink,
99- NothingHere,
100- DefaultBadge,
101- TagsTitle,
102- ForkedFrom,
103- MirrorOf,
104- NotSyncedYet,
105- ForkButton,
106- StarsAria,
107- ArchivedNotice,
108- RepositoryNav,
109- TabIssues,
110- TabPulls,
111- TabCommits,
112- TabReleases,
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- }
5+strings! {
6+ K;
7+ SearchWord => "search", "arama";
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 => "Search code", "Kodda ara";
10+ SearchButton => "Search", "Ara";
11+ RefField => "Ref ", "Referans ";
12+ PathField => "Path ", "Yol ";
13+ MatchCase => " Match case", " Büyük/küçük harfe duyarlı";
14+ RegexOption => " Regex", " Düzenli ifade";
15+ SearchFilesAt => "Search the files at ", "Dosyaları şurada ara: ";
16+ NoMatches => "No matches.", "Eşleşme yok.";
17+ ShowingFirst => " (showing the first ", " (ilk ";
18+ ShowingFirstEnd => ")", " gösteriliyor)";
19+ CloneTitle => "Clone", "Klonla";
20+ CopyCloneUrl => "Copy clone URL", "Klon adresini kopyala";
21+ CloneCopied => "Copied", "Kopyalandı";
22+ CloneCopyFailed => "Copy failed", "Kopyalanamadı";
23+ BranchesTitle => "Branches", "Dallar";
24+ FilterRefs => "Filter branches and tags", "Dal ve etiketleri süz";
25+ ViewAllBranches => "View all branches", "Tüm dalları gör";
26+ ViewAllTags => "View all tags", "Tüm etiketleri gör";
27+ EmptyRepoPush => "This repository is empty.", "Bu depo boş.";
28+ OverHttps => "Over HTTPS", "HTTPS üzerinden";
29+ OverSsh => "Over SSH", "SSH üzerinden";
30+ DownloadZip => "Download ZIP", "ZIP olarak indir";
31+ DownloadTarGz => "Download tar.gz", "tar.gz olarak indir";
32+ RecentPushes => "Recent pushes", "Son gönderimler";
33+ HadRecentPushes => " had recent pushes ", " dalına son zamanlarda gönderim yapıldı ";
34+ CompareAndPr => "Compare & pull request", "Karşılaştır ve çekme isteği aç";
35+ BranchLabel => "Branch", "Dal";
36+ KindDir => "dir", "dizin";
37+ KindFile => "file", "dosya";
38+ KindExec => "exec", "çalıştırılabilir";
39+ KindLink => "link", "bağlantı";
40+ KindSubmodule => "submodule", "alt modül";
41+ Rendered => "Rendered", "Önizleme";
42+ SourceToggle => "Source", "Kaynak";
43+ HistoryLink => "History", "Geçmiş";
44+ RawLink => "Raw", "Ham";
45+ DownloadLink => "Download", "İndir";
46+ SymlinkPrefix => "Symbolic link → ", "Sembolik bağlantı → ";
47+ SubmodulePrefix => "Submodule at commit ", "Alt modül, şu commit'te: ";
48+ SubmoduleSuffix => ". Its contents are not in this repository.", ". İçeriği bu depoda yok.";
49+ TruncatedPrefix => "Showing the first 1 MiB of this file. ", "Bu dosyanın ilk 1 MiB'ı gösteriliyor. ";
50+ ViewFullRaw => "View raw", "Ham görüntüle";
51+ LivePathGone => "This path no longer exists in this ref.", "Bu yol bu referansta artık yok.";
52+ StatusAdded => "added", "eklendi";
53+ StatusDeleted => "deleted", "silindi";
54+ StatusModified => "modified", "değiştirildi";
55+ StatusRenamed => "renamed", "yeniden adlandırıldı";
56+ StatusCopied => "copied", "kopyalandı";
57+ StatusTypeChanged => "type changed", "tür değiştirildi";
58+ NoFileChanges => "No file changes.", "Dosya değişikliği yok.";
59+ BinaryFileChanged => "Binary file changed", "İkili dosya değiştirildi";
60+ DiffTooLargePrefix => "Diff too large; ", "Fark çok büyük; ";
61+ ViewFile => "view file", "dosyayı görüntüle";
62+ DiffTooLarge => "Diff too large.", "Fark çok büyük.";
63+ CommentOnLine => "Comment on this line", "Bu satıra yorum yap";
64+ AddReviewComment => "Add review comment", "İnceleme yorumu ekle";
65+ StartReview => "Start a review", "İnceleme başlat";
66+ CommentLabel => "Comment", "Yorum";
67+ AddSingleComment => "Add single comment", "Tek yorum ekle";
68+ ThisCommit => "this commit", "bu commit";
69+ ShowFullMessage => "Show full message", "Tam mesajı göster";
70+ CommitStatusPrefix => "Commit status: ", "Commit durumu: ";
71+ StateSuccess => "success", "başarılı";
72+ StateFailure => "failure", "başarısız";
73+ StateError => "error", "hata";
74+ StatePending => "pending", "bekliyor";
75+ NoChecksReported => "No checks reported", "Hiç kontrol bildirilmedi";
76+ AllChecksPassed => "All checks have passed", "Tüm kontroller geçti";
77+ ChecksPending => "Checks pending", "Kontroller bekliyor";
78+ SomeChecksFailed => "Some checks failed", "Bazı kontroller başarısız oldu";
79+ ShowChecks => "Show checks", "Kontrolleri göster";
80+ DetailsLink => "Details", "Ayrıntılar";
81+ AuthorLabel => "Author ", "Yazar ";
82+ CommitterLabel => "Committer ", "Commit eden ";
83+ CoAuthorAnd => " and ", " ve ";
84+ CoAuthorsLabel => "Co-authors", "Ortak yazarlar";
85+ RootCommit => "Root commit (no parents)", "Kök commit (üst commit yok)";
86+ CommitChangesLabel => "Changes in this commit", "Bu commit'teki değişiklikler";
87+ ParentLabel => "Parent: ", "Üst commit: ";
88+ BrowseFiles => "Browse files at this commit", "Bu commit'teki dosyalara göz at";
89+ SigVerified => "Verified", "Doğrulandı";
90+ SigUnverified => "Unverified", "Doğrulanmadı";
91+ CommitsOn => "Commits on ", "Referanstaki commit'ler: ";
92+ FilteredTo => "Filtered to ", "Şuna göre filtrelendi: ";
93+ ClearFilter => "Clear filter", "Filtreyi temizle";
94+ NoCommits => "No commits yet.", "Henüz commit yok.";
95+ NothingHere => "Nothing here yet.", "Henüz burada bir şey yok.";
96+ DefaultBadge => "default", "varsayılan";
97+ TagsTitle => "Tags", "Etiketler";
98+ ForkedFrom => "forked from ", "Şu depodan çatallandı: ";
99+ MirrorOf => "Mirror of ", "Yansı kaynağı: ";
100+ NotSyncedYet => "not synced yet", "henüz eşitlenmedi";
101+ ForkButton => "Fork", "Çatalla";
102+ StarsAria => "Stars", "Yıldızlar";
103+ ArchivedNotice => "This repository is archived. It is read-only.", "Bu depo arşivlendi. Salt okunurdur.";
104+ RepositoryNav => "Repository", "Depo";
105+ TabIssues => "Issues", "Sorunlar";
106+ TabPulls => "Pull requests", "Çekme istekleri";
107+ TabCommits => "Commits", "Commitler";
108+ TabReleases => "Releases", "Sürümler";
109+ TabCi => "CI", "CI";
110+ TabDiscussions => "Discussions", "Tartışmalar";
111+ TabWiki => "Wiki", "Wiki";
112+ TabSettings => "Settings", "Ayarlar";
348113 }
349114
350115 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) {
489254 mod tests {
490255 use super::*;
491256
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-
605257 #[test]
606258 fn every_key_has_text_in_both_languages() {
607259 for key in ALL {
@@ -610,13 +262,6 @@ mod tests {
610262 }
611263 }
612264
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-
620265 #[test]
621266 fn turkish_differs_from_english_for_several_keys() {
622267 let differing = ALL
crates/forge-web-base/src/i18n/community.rsmodified+86 -370
@@ -2,287 +2,92 @@ use forge_core::discussions::DiscussionCategory;
22
33 use super::Lang;
44
5-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
6-pub enum K {
7- AllCategories,
8- CategoriesNav,
9- NewDiscussion,
10- NoDiscussionsYet,
11- Discussions,
12- Newer,
13- Older,
14- Category,
15- Title,
16- Description,
17- StartDiscussion,
18- Cancel,
19- Save,
20- Delete,
21- Edit,
22- EditComment,
23- CouldNotSave,
24- CommentDeleted,
25- Answer,
26- MarkAsAnswer,
27- UnmarkAnswer,
28- Reply,
29- DeleteDiscussion,
30- Conversation,
31- LockConversation,
32- UnlockConversation,
33- Answered,
34- Locked,
35- NoDescription,
36- LockedNotice,
37- AddComment,
38- CommentButton,
39- LogInLink,
40- ToCommentSuffix,
41- ArchivedDiscussions,
42- CategoryGeneral,
43- CategoryIdeas,
44- CategoryQa,
45- CategoryAnnouncements,
46- Wiki,
47- Home,
48- AllPages,
49- NewPage,
50- History,
51- PageNav,
52- WikiNoPages,
53- CreateFirstPage,
54- NoPagesYet,
55- BackToPage,
56- NoChangesYet,
57- PageName,
58- ContentMarkdown,
59- Summary,
60- SavePage,
61- PageNameRules,
62- PageExists,
63- WikiConflict,
64- WikiPages,
65- Snippets,
66- NewSnippet,
67- NoSnippets,
68- Visibility,
69- VisibilityPublic,
70- VisibilityUnlisted,
71- VisibilityPrivate,
72- PublicOption,
73- UnlistedOption,
74- PrivateOption,
75- FileLabel,
76- FileNamePlaceholder,
77- FileName,
78- FileContents,
79- Untitled,
80- Files,
81- SnippetTitlePlaceholder,
82- DescriptionOptional,
83- AddFile,
84- RemoveFile,
85- SaveSnippet,
86- EditSnippet,
87- Raw,
88- Revisions,
89- BackToSnippet,
90- NoRevisions,
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- }
5+strings! {
6+ K;
7+ AllCategories => "All", "Tümü";
8+ CategoriesNav => "Discussion categories", "Tartışma kategorileri";
9+ NewDiscussion => "New discussion", "Yeni tartışma";
10+ NoDiscussionsYet => "No discussions here yet.", "Henüz tartışma yok.";
11+ Discussions => "Discussions", "Tartışmalar";
12+ Category => "Category", "Kategori";
13+ Title => "Title", "Başlık";
14+ Description => "Description", "Açıklama";
15+ StartDiscussion => "Start discussion", "Tartışma başlat";
16+ Save => "Save", "Kaydet";
17+ Delete => "Delete", "Sil";
18+ Edit => "Edit", "Düzenle";
19+ EditComment => "Edit comment", "Yorumu düzenle";
20+ CouldNotSave => "Could not save", "Kaydedilemedi";
21+ CommentDeleted => "Comment deleted", "Yorum silindi";
22+ Answer => "Answer", "Cevap";
23+ MarkAsAnswer => "Mark as answer", "Cevap olarak işaretle";
24+ UnmarkAnswer => "Unmark answer", "Cevap işaretini kaldır";
25+ Reply => "Reply", "Yanıtla";
26+ DeleteDiscussion => "Delete discussion", "Tartışmayı sil";
27+ Conversation => "Conversation", "Konuşma";
28+ LockConversation => "Lock conversation", "Konuşmayı kilitle";
29+ UnlockConversation => "Unlock conversation", "Konuşmanın kilidini aç";
30+ Answered => "Answered", "Cevaplandı";
31+ Locked => "Locked", "Kilitli";
32+ NoDescription => "_No description provided._", "_Açıklama eklenmedi._";
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+ AddComment => "Add a comment", "Yorum ekle";
35+ CommentButton => "Comment", "Yorum yap";
36+ ToCommentSuffix => " to comment.", ".";
37+ ArchivedDiscussions => "This repository is archived, so its discussions are read-only.", "Bu depo arşivlendiği için tartışmalar salt okunur.";
38+ CategoryGeneral => "General", "Genel";
39+ CategoryIdeas => "Ideas", "Fikirler";
40+ CategoryQa => "Q&A", "Soru-cevap";
41+ CategoryAnnouncements => "Announcements", "Duyurular";
42+
43+ Wiki => "Wiki", "Wiki";
44+ Home => "Home", "Ana sayfa";
45+ AllPages => "All pages", "Tüm sayfalar";
46+ NewPage => "New page", "Yeni sayfa";
47+ History => "History", "Geçmiş";
48+ PageNav => "Page", "Sayfa";
49+ WikiNoPages => "This wiki has no pages yet.", "Bu wiki'de henüz sayfa yok.";
50+ CreateFirstPage => "Create the first page", "İlk sayfayı oluştur";
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+ BackToPage => "Back to page", "Sayfaya dön";
53+ NoChangesYet => "No changes yet.", "Henüz değişiklik yok.";
54+ PageName => "Page name", "Sayfa adı";
55+ ContentMarkdown => "Content (Markdown)", "İçerik (Markdown)";
56+ Summary => "Summary", "Özet";
57+ SavePage => "Save page", "Sayfayı kaydet";
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+ PageExists => "A page with that name already exists. Edit it instead.", "Bu adla bir sayfa zaten var. Bunun yerine onu düzenleyin.";
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+ WikiPages => "Wiki pages", "Wiki sayfaları";
62+
63+ Snippets => "Snippets", "Parçacıklar";
64+ NewSnippet => "New snippet", "Yeni parçacık";
65+ NoSnippets => "No snippets to show.", "Gösterilecek parçacık yok.";
66+ Visibility => "Visibility", "Görünürlük";
67+ VisibilityPublic => "Public", "Herkese açık";
68+ VisibilityUnlisted => "Unlisted", "Listelenmez";
69+ VisibilityPrivate => "Private", "Özel";
70+ PublicOption => "Public: listed on /snippets", "Herkese açık: /snippets üzerinde listelenir";
71+ UnlistedOption => "Unlisted: anyone with the link", "Listelenmez: bağlantıya sahip herkes";
72+ PrivateOption => "Private: only you", "Özel: yalnızca siz";
73+ FileLabel => "File ", "Dosya ";
74+ FileNamePlaceholder => "file name, for example notes.md", "dosya adı, örneğin notes.md";
75+ FileName => "File name", "Dosya adı";
76+ FileContents => "File contents", "Dosya içeriği";
77+ Untitled => "untitled", "adsız";
78+ Files => "Files", "Dosyalar";
79+ SnippetTitlePlaceholder => "Snippet title", "Parçacık başlığı";
80+ DescriptionOptional => "Description (optional)", "Açıklama (isteğe bağlı)";
81+ AddFile => "Add file", "Dosya ekle";
82+ RemoveFile => "Remove file", "Dosyayı kaldır";
83+ SaveSnippet => "Save snippet", "Parçacığı kaydet";
84+ EditSnippet => "Edit snippet", "Parçacığı düzenle";
85+ Raw => "Raw", "Ham";
86+ Revisions => "Revisions", "Revizyonlar";
87+ BackToSnippet => "Back to the snippet", "Parçacığa dön";
88+ NoRevisions => "No revisions.", "Revizyon yok.";
89+ RevisionLabel => "Revision ", "Revizyon ";
90+ ChooseVisibility => "Choose a visibility.", "Bir görünürlük seçin.";
28691 }
28792
28893 pub fn category_label(lang: Lang, category: DiscussionCategory) -> &'static str {
@@ -361,95 +166,6 @@ pub fn revisions_of(lang: Lang, title: &str) -> String {
361166 mod tests {
362167 use super::*;
363168
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-
453169 #[test]
454170 fn every_key_has_both_languages() {
455171 for key in ALL {
crates/forge-web-base/src/i18n/integrations.rsmodified+86 -378
@@ -1,383 +1,91 @@
11 use super::Lang;
22
3-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
4-pub enum K {
5- ActiveField,
6- AddPullMirror,
7- AddPushMirror,
8- AddWebhook,
9- ArchivedNotice,
10- BackToWebhooks,
11- ClearSecret,
12- CreateWebhook,
13- CurrentUrl,
14- Cancel,
15- DeleteConfirm,
16- DeleteMirror,
17- DeleteWebhook,
18- DirectionPull,
19- DirectionPush,
20- EnabledField,
21- ErrIntervalMax,
22- ErrIntervalNotWhole,
23- ErrNoEvent,
24- ErrUrlMissing,
25- ErrUrlRequired,
26- ErrorLabel,
27- EvCreate,
28- EvDelete,
29- EvIssueComment,
30- EvIssues,
31- EvPullRequest,
32- EvPullRequestReview,
33- EvPush,
34- EvRelease,
35- Events,
36- HookArchivedNotice,
37- HookNoticeConfirm,
38- HookNoticeCreated,
39- HookNoticeDeleted,
40- HookNoticeRedelivered,
41- HookNoticeSaved,
42- HookNoticeTested,
43- IntervalField,
44- LastSync,
45- ManualOnly,
46- Mirrors,
47- NoDeliveries,
48- NoMirrors,
49- NoWebhooks,
50- NoneYet,
51- NoResponse,
52- NoticeCreated,
53- NoticeDeleted,
54- NoticePullCreated,
55- NoticePullNotEmpty,
56- NoticeSaved,
57- NoticeSynced,
58- PayloadUrl,
59- PullMirror,
60- PushMirror,
61- RecentDeliveries,
62- Redeliver,
63- RemoteUrl,
64- RepositoryUrl,
65- RequestBody,
66- RequestHeaders,
67- Response,
68- ResponseBody,
69- ResponseHeaders,
70- SaveMirror,
71- SaveWebhook,
72- Secret,
73- SecretHintSet,
74- SecretHintUnset,
75- SecretOptional,
76- SendTestPing,
77- StateFailed,
78- StateGaveUp,
79- StatePending,
80- Status,
81- StatusFailed,
82- StatusLower,
83- StatusNotRun,
84- StatusOk,
85- SyncHeading,
86- SyncNow,
87- Test,
88- UsernameOptional,
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- }
3+strings! {
4+ K;
5+ ActiveField => "Active: deliver events to this URL", "Etkin: olaylar bu URL'ye teslim edilir";
6+ AddPullMirror => "Add pull mirror", "Çekme yansısı ekle";
7+ AddPushMirror => "Add push mirror", "Gönderme yansısı ekle";
8+ AddWebhook => "Add webhook", "Web kancası ekle";
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 => "Back to webhooks", "Web kancalarına dön";
11+ ClearSecret => "Clear the stored password or token", "Kayıtlı parola veya belirteci temizle";
12+ CreateWebhook => "Create webhook", "Web kancası oluştur";
13+ CurrentUrl => "Current URL:", "Mevcut URL:";
14+ DeleteConfirm => "Delete it? This cannot be undone.", "Silinsin mi? Bu işlem geri alınamaz.";
15+ DeleteMirror => "Delete mirror", "Yansıyı sil";
16+ DeleteWebhook => "Delete webhook", "Web kancasını sil";
17+ DirectionPull => "Pull", "Çekme";
18+ DirectionPush => "Push", "Gönderme";
19+ EnabledField => "Enabled: sync on the interval and after pushes", "Etkin: aralıkla ve göndermelerden sonra eşitlenir";
20+ ErrIntervalMax => "The sync interval can be at most one year.", "Eşitleme aralığı en fazla bir yıl olabilir.";
21+ ErrIntervalNotWhole => "The sync interval must be a whole number of minutes.", "Eşitleme aralığı dakika cinsinden tam sayı olmalıdır.";
22+ ErrNoEvent => "Choose at least one event.", "En az bir olay seçin.";
23+ ErrUrlMissing => "Enter the URL the events are sent to.", "Olayların gönderileceği URL'yi girin.";
24+ ErrUrlRequired => "Enter the URL of the repository to mirror.", "Yansılanacak deponun URL'sini girin.";
25+ ErrorLabel => "Error", "Hata";
26+ EvCreate => "Branch and tag creation", "Dal ve etiket oluşturma";
27+ EvDelete => "Branch and tag deletion", "Dal ve etiket silme";
28+ EvIssueComment => "Comments on issues and pull requests", "Sorun ve çekme isteklerindeki yorumlar";
29+ EvIssues => "Issues: opened, closed, reopened, edited, labels, assignees", "Sorunlar: açıldı, kapatıldı, yeniden açıldı, düzenlendi, etiketler, atananlar";
30+ EvPullRequest => "Pull requests: opened, closed, reopened, merged, updated", "Çekme istekleri: açıldı, kapatıldı, yeniden açıldı, birleştirildi, güncellendi";
31+ EvPullRequestReview => "Pull request reviews", "Çekme isteği incelemeleri";
32+ EvPush => "Pushes to a branch or tag", "Bir dala veya etikete gönderimler";
33+ EvRelease => "Releases: published, updated, deleted", "Sürümler: yayımlandı, güncellendi, silindi";
34+ Events => "Events", "Olaylar";
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+ HookNoticeConfirm => "The delete was not confirmed. Nothing was deleted.", "Silme onaylanmadı. Hiçbir şey silinmedi.";
37+ HookNoticeCreated => "Webhook created. A ping was queued.", "Web kancası oluşturuldu. Bir ping sıraya alındı.";
38+ HookNoticeDeleted => "Webhook deleted.", "Web kancası silindi.";
39+ HookNoticeRedelivered => "The delivery was queued again.", "Teslimat yeniden sıraya alındı.";
40+ HookNoticeSaved => "Webhook saved.", "Web kancası kaydedildi.";
41+ HookNoticeTested => "A test ping was queued.", "Bir test pingi sıraya alındı.";
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+ LastSync => "Last sync:", "Son eşitleme:";
44+ ManualOnly => "manual only", "yalnızca elle";
45+ Mirrors => "Mirrors", "Yansılar";
46+ NoDeliveries => "No deliveries yet.", "Henüz teslimat yok.";
47+ NoMirrors => "No mirrors yet.", "Henüz yansı yok.";
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+ NoneYet => "none yet", "henüz yok";
50+ NoResponse => "no response", "yanıt yok";
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+ NoticeDeleted => "Mirror deleted.", "Yansı silindi.";
53+ NoticePullCreated => "Pull mirror created. The first sync is queued.", "Çekme yansısı oluşturuldu. İlk eşitleme sıraya alındı.";
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+ NoticeSaved => "Mirror saved.", "Yansı kaydedildi.";
56+ NoticeSynced => "A sync was queued.", "Bir eşitleme sıraya alındı.";
57+ PayloadUrl => "Payload URL", "Yük URL'si";
58+ PullMirror => "Pull mirror", "Çekme yansısı";
59+ PushMirror => "Push mirror", "Gönderme yansısı";
60+ RecentDeliveries => "Recent deliveries", "Son teslimatlar";
61+ Redeliver => "Redeliver", "Yeniden teslim et";
62+ RemoteUrl => "Remote URL", "Uzak URL";
63+ RepositoryUrl => "Repository URL", "Depo URL'si";
64+ RequestBody => "Request body", "İstek gövdesi";
65+ RequestHeaders => "Request headers", "İstek üst bilgileri";
66+ Response => "Response", "Yanıt";
67+ ResponseBody => "Response body", "Yanıt gövdesi";
68+ ResponseHeaders => "Response headers", "Yanıt üst bilgileri";
69+ SaveMirror => "Save mirror", "Yansıyı kaydet";
70+ SaveWebhook => "Save webhook", "Web kancasını kaydet";
71+ Secret => "Secret", "Gizli anahtar";
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+ SecretHintUnset => "No secret is set. Type one to add it.", "Gizli anahtar ayarlı değil. Eklemek için bir tane yazın.";
74+ SecretOptional => "Password or token (optional)", "Parola veya belirteç (isteğe bağlı)";
75+ SendTestPing => "Send test ping", "Test pingi gönder";
76+ StateFailed => "failed, will retry", "başarısız, yeniden denenecek";
77+ StateGaveUp => "gave up", "vazgeçildi";
78+ StatePending => "pending", "beklemede";
79+ Status => "Status", "Durum";
80+ StatusFailed => "failed", "başarısız";
81+ StatusLower => "status", "durum";
82+ StatusNotRun => "not run yet", "henüz çalışmadı";
83+ StatusOk => "ok", "tamam";
84+ SyncHeading => "Sync", "Eşitleme";
85+ SyncNow => "Sync now", "Şimdi eşitle";
86+ Test => "Test", "Test";
87+ UsernameOptional => "Username (optional)", "Kullanıcı adı (isteğe bağlı)";
88+ Webhooks => "Webhooks", "Web kancaları";
38189 }
38290
38391 pub fn interval_too_short(lang: Lang, min: u32) -> String {
crates/forge-web-base/src/i18n/issues.rsmodified+139 -571

Diff too large; view file

@@ -1,150 +1,143 @@
11 use super::Lang;
22
3-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
4-pub enum K {
5- CouldNotSave,
6- GoBack,
7- Issues,
8- Labels,
9- Milestones,
10- Pinned,
11- Comment,
12- Edit,
13- Delete,
14- Title,
15- Description,
16- Cancel,
17- Name,
18- Color,
19- Reason,
20- Open,
21- Closed,
22- Search,
23- Sort,
24- Unknown,
25- System,
26- Edited,
27- EditedBy,
28- Raw,
29-
30- IssuePages,
31- PinIssue,
32- UnpinIssue,
33- PinnedTopNote,
34- PinnedIssues,
35-
36- LockOffTopic,
37- LockTooHeated,
38- LockResolved,
39- LockSpam,
40- OptOffTopic,
41- OptTooHeated,
42- OptResolved,
43- OptSpam,
44- ConversationLocked,
45- ArchivedIssuesReadOnly,
46- LogIn,
47- LogInLink,
48- ToComment,
49-
50- ClosedCompleted,
51- ClosedNotPlanned,
52- ClosedThis,
53- ReopenedThis,
54- ReferencedThis,
55- LockedConversation,
56- UnlockedConversation,
57- PinnedThisIssue,
58- UnpinnedThisIssue,
59- MergedCommit,
60- PushedNewCommits,
61- DeletedHeadBranch,
62- InCommit,
63- ReviewDismissedPrefix,
64-
65- StateClosedNotPlanned,
66- SaveChanges,
67- EditComment,
68- SaveComment,
69-
70- ApprovedChanges,
71- RequestedChanges,
72- Reviewed,
73- ApprovedDismissed,
74- RequestedDismissed,
75- ReviewedDismissed,
76- DismissedPrefix,
77- AddReaction,
78- NoDescription,
79-
80- NoRepoLabels,
81- SaveLabels,
82- NoneYet,
83- Assignees,
84- SaveAssignees,
85- AssignToMe,
86- MilestoneBox,
87- NoneOption,
88- SaveMilestone,
89- ConversationBox,
90- Locked,
91- UnlockConversation,
92- NoReason,
93- LockConversation,
94- LockedToCollaborators,
95-
96- AddComment,
97- CloseCompleted,
98- CloseNotPlanned,
99- CommentEmpty,
100- Add,
101- Close,
102- Reopen,
103-
104- LabelsArchived,
105- NoLabelsYet,
106- AddDefaultLabels,
107- SaveLabel,
108- NewLabel,
109- CreateLabel,
110- OpenLabelCount,
111-
112- MilestonesArchived,
113- Overdue,
114- MilestoneState,
115- NoClosedMilestones,
116- NoOpenMilestones,
117- NewMilestone,
118- DueDate,
119- CreateMilestone,
120- EditMilestone,
121- BackToMilestones,
122- StateLabel,
123- ClosedMilestoneCount,
124- OpenMilestoneCount,
125-
126- OpenIssue,
127- ClosedIssue,
128- SortNewest,
129- SortOldest,
130- SortUpdated,
131- NewIssue,
132- NoIssuesMatch,
133- NoIssuesYet,
134- SearchTitles,
135- FiltersApplied,
136- ClearFilters,
137- ChooseTemplate,
138- BlankIssue,
139- SubmitNewIssue,
140- Newer,
141- Older,
142-
143- HistIssueDescription,
144- HistPullDescription,
145- HistComment,
146- HistReviewComment,
147- NoEarlierVersions,
3+strings! {
4+ K;
5+ CouldNotSave => "Could not save", "Kaydedilemedi";
6+ GoBack => "Go back", "Geri dön";
7+ Issues => "Issues", "Sorunlar";
8+ Labels => "Labels", "Etiketler";
9+ Milestones => "Milestones", "Kilometre taşları";
10+ Pinned => "Pinned", "Sabitlenmiş";
11+ Comment => "Comment", "Yorum";
12+ Edit => "Edit", "Düzenle";
13+ Delete => "Delete", "Sil";
14+ Title => "Title", "Başlık";
15+ Description => "Description", "Açıklama";
16+ Name => "Name", "Ad";
17+ Color => "Color", "Renk";
18+ Reason => "Reason", "Neden";
19+ Open => "Open", "Açık";
20+ Closed => "Closed", "Kapalı";
21+ Search => "Search", "Ara";
22+ Sort => "Sort", "Sırala";
23+ Unknown => "unknown", "bilinmeyen";
24+ System => "system", "sistem";
25+ Edited => "edited", "düzenlendi";
26+ EditedBy => " edited ", " ";
27+ Raw => "Raw", "Ham";
28+
29+ IssuePages => "Issue pages", "Sorun sayfaları";
30+ PinIssue => "Pin issue", "Sorunu sabitle";
31+ UnpinIssue => "Unpin issue", "Sabitlemeyi kaldır";
32+ PinnedTopNote => "Pinned to the top of the issue list.", "Sorun listesinin en üstünde sabitlendi.";
33+ PinnedIssues => "Pinned issues", "Sabitlenmiş sorunlar";
34+
35+ LockOffTopic => "off-topic", "konu dışı";
36+ LockTooHeated => "too heated", "tartışma kızıştı";
37+ LockResolved => "resolved", "çözüldü";
38+ LockSpam => "spam", "spam";
39+ OptOffTopic => "Off-topic", "Konu dışı";
40+ OptTooHeated => "Too heated", "Tartışma kızıştı";
41+ OptResolved => "Resolved", "Çözüldü";
42+ OptSpam => "Spam", "Spam";
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+ ArchivedIssuesReadOnly => "This repository is archived, so its issues are read-only.", "Bu depo arşivlenmiş, bu yüzden sorunları salt okunurdur.";
45+ LogIn => "Log in", "Giriş yap";
46+ ToComment => " to comment.", ".";
47+
48+ ClosedCompleted => "closed this as completed", "bunu tamamlandı olarak kapattı";
49+ ClosedNotPlanned => "closed this as not planned", "bunu planlanmadı olarak kapattı";
50+ ClosedThis => "closed this", "bunu kapattı";
51+ ReopenedThis => "reopened this", "bunu yeniden açtı";
52+ ReferencedThis => "referenced this", "buna atıfta bulundu";
53+ LockedConversation => "locked this conversation", "bu tartışmayı kilitledi";
54+ UnlockedConversation => "unlocked this conversation", "bu tartışmanın kilidini açtı";
55+ PinnedThisIssue => "pinned this issue", "bu sorunu sabitledi";
56+ UnpinnedThisIssue => "unpinned this issue", "bu sorunun sabitlemesini kaldırdı";
57+ MergedCommit => "merged commit", "commit'i birleştirdi";
58+ PushedNewCommits => "pushed new commits", "yeni commit'ler gönderdi";
59+ DeletedHeadBranch => "deleted the head branch", "kaynak dalını sildi";
60+ InCommit => " in", "commit'inde";
61+ ReviewDismissedPrefix => "dismissed a review: ", "bir incelemeyi iptal etti: ";
62+
63+ StateClosedNotPlanned => "Closed as not planned", "Planlanmadı olarak kapalı";
64+ SaveChanges => "Save changes", "Değişiklikleri kaydet";
65+ EditComment => "Edit comment", "Yorumu düzenle";
66+
67+ ApprovedChanges => "approved these changes", "bu değişiklikleri onayladı";
68+ RequestedChanges => "requested changes", "değişiklik istedi";
69+ Reviewed => "reviewed", "inceledi";
70+ ApprovedDismissed => "approved these changes (dismissed)", "bu değişiklikleri onayladı (iptal edildi)";
71+ RequestedDismissed => "requested changes (dismissed)", "değişiklik istedi (iptal edildi)";
72+ ReviewedDismissed => "reviewed (dismissed)", "inceledi (iptal edildi)";
73+ DismissedPrefix => "dismissed: ", "iptal edildi: ";
74+ AddReaction => "React", "Tepki ver";
75+ NoDescription => "_No description provided._", "_Açıklama girilmedi._";
76+
77+ NoRepoLabels => "This repository has no labels yet.", "Bu depoda henüz etiket yok.";
78+ SaveLabels => "Save labels", "Etiketleri kaydet";
79+ NoneYet => "None yet.", "Henüz yok.";
80+ Assignees => "Assignees", "Atananlar";
81+ SaveAssignees => "Save assignees", "Atananları kaydet";
82+ AssignToMe => "Assign to me", "Bana ata";
83+ MilestoneBox => "Milestone", "Kilometre taşı";
84+ NoneOption => "None", "Yok";
85+ SaveMilestone => "Save milestone", "Kilometre taşını kaydet";
86+ ConversationBox => "Conversation", "Tartışma";
87+ Locked => "Locked", "Kilitli";
88+ UnlockConversation => "Unlock conversation", "Tartışmanın kilidini aç";
89+ NoReason => "No reason", "Neden yok";
90+ LockConversation => "Lock conversation", "Tartışmayı kilitle";
91+ LockedToCollaborators => "Locked to collaborators", "Katkıda bulunanlarla sınırlı";
92+
93+ AddComment => "Add a comment", "Yorum ekle";
94+ CloseCompleted => "Close as completed", "Tamamlandı olarak kapat";
95+ CloseNotPlanned => "Close as not planned", "Planlanmadı olarak kapat";
96+ CommentEmpty => "Comment cannot be empty.", "Yorum boş olamaz.";
97+ Add => "Add", "Ekle";
98+ Close => "Close", "Kapat";
99+ Reopen => "Reopen", "Yeniden aç";
100+
101+ LabelsArchived => "This repository is archived. Labels are read-only.", "Bu depo arşivlenmiş. Etiketler salt okunur.";
102+ NoLabelsYet => "No labels yet.", "Henüz etiket yok.";
103+ AddDefaultLabels => "Add default labels", "Varsayılan etiketleri ekle";
104+ SaveLabel => "Save label", "Etiketi kaydet";
105+ NewLabel => "New label", "Yeni etiket";
106+ CreateLabel => "Create label", "Etiketi oluştur";
107+ OpenLabelCount => "open", "açık";
108+
109+ MilestonesArchived => "This repository is archived. Milestones are read-only.", "Bu depo arşivlenmiş. Kilometre taşları salt okunur.";
110+ Overdue => "overdue", "gecikmiş";
111+ MilestoneState => "Milestone state", "Kilometre taşı durumu";
112+ NoClosedMilestones => "No closed milestones.", "Kapalı kilometre taşı yok.";
113+ NoOpenMilestones => "No open milestones.", "Açık kilometre taşı yok.";
114+ NewMilestone => "New milestone", "Yeni kilometre taşı";
115+ DueDate => "Due date", "Bitiş tarihi";
116+ CreateMilestone => "Create milestone", "Kilometre taşı oluştur";
117+ EditMilestone => "Edit milestone", "Kilometre taşını düzenle";
118+ BackToMilestones => "Back to milestones", "Kilometre taşlarına dön";
119+ StateLabel => "State", "Durum";
120+ ClosedMilestoneCount => "closed", "kapalı";
121+ OpenMilestoneCount => "open", "açık";
122+
123+ OpenIssue => "Open issue", "Açık sorun";
124+ ClosedIssue => "Closed issue", "Kapalı sorun";
125+ SortNewest => "Newest", "En yeni";
126+ SortOldest => "Oldest", "En eski";
127+ NewIssue => "New issue", "Yeni sorun";
128+ NoIssuesMatch => "No issues match these filters.", "Bu filtrelerle eşleşen sorun yok.";
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+ FiltersApplied => "Filters applied · ", "Filtreler uygulandı · ";
131+ ClearFilters => "Clear filters", "Filtreleri temizle";
132+ ChooseTemplate => "Choose a template to start from.", "Başlamak için bir şablon seçin.";
133+ BlankIssue => "Open a blank issue", "Boş bir sorun aç";
134+ SubmitNewIssue => "Submit new issue", "Yeni sorunu gönder";
135+
136+ HistIssueDescription => "issue description", "sorun açıklaması";
137+ HistPullDescription => "pull request description", "çekme isteği açıklaması";
138+ HistComment => "comment", "yorum";
139+ HistReviewComment => "review comment", "inceleme yorumu";
140+ NoEarlierVersions => "No earlier versions.", "Önceki sürüm yok.";
148141 }
149142
150143 pub fn edited_after(lang: Lang) -> &'static str {
@@ -154,296 +147,6 @@ pub fn edited_after(lang: Lang) -> &'static str {
154147 }
155148 }
156149
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-
447150 pub fn comment_count(lang: Lang, n: i64) -> String {
448151 match lang {
449152 Lang::En => format!("{n} comment{}", if n == 1 { "" } else { "s" }),
@@ -793,142 +496,7 @@ pub fn commit_event_sides(
793496
794497 #[cfg(test)]
795498 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,
crates/forge-web-base/src/i18n/link.rsmodified+10 -32

Diff too large; view file

crates/forge-web-base/src/i18n/merge_queue.rsmodified+34 -141

Diff too large; view file

crates/forge-web-base/src/i18n/migrate.rsmodified+75 -268

Diff too large; view file

crates/forge-web-base/src/i18n/misc.rsmodified+118 -497

Diff too large; view file

crates/forge-web-base/src/i18n/mod.rsmodified+217 -754

Diff too large; view file

crates/forge-web-base/src/i18n/needs.rsmodified+18 -77

Diff too large; view file

crates/forge-web-base/src/i18n/orgs.rsmodified+107 -435

Diff too large; view file

crates/forge-web-base/src/i18n/packages.rsmodified+30 -96

Diff too large; view file

crates/forge-web-base/src/i18n/pulls.rsmodified+60 -291

Diff too large; view file

crates/forge-web-base/src/i18n/pulls_review.rsmodified+78 -333

Diff too large; view file

crates/forge-web-base/src/i18n/push.rsmodified+21 -73

Diff too large; view file

crates/forge-web-base/src/i18n/releases_ci.rsmodified+111 -515

Diff too large; view file

crates/forge-web-base/src/i18n/repo_admin.rsmodified+107 -460

Diff too large; view file

crates/forge-web-base/src/i18n/timeline.rsmodified+3 -15

Diff too large; view file

crates/forge-web-pages/src/pages/admin_runners.rsmodified+33 -58

Diff too large; view file

crates/forge-web-pages/src/pages/admin_users.rsmodified+3 -13

Diff too large; view file

crates/forge-web-pages/src/pages/ci_job.rsmodified+7 -12

Diff too large; view file

crates/forge-web-pages/src/pages/ci_runs.rsmodified+39 -103

Diff too large; view file

crates/forge-web-pages/src/pages/discussion_settings.rsmodified+1 -1

Diff too large; view file

crates/forge-web-pages/src/pages/issue_meta.rsmodified+2 -2

Diff too large; view file

crates/forge-web-pages/src/pages/issue_parts.rsmodified+38 -52

Diff too large; view file

crates/forge-web-pages/src/pages/issues_list.rsmodified+13 -17

Diff too large; view file

crates/forge-web-pages/src/pages/mod.rsmodified+26 -0

Diff too large; view file

crates/forge-web-pages/src/pages/notifications.rsmodified+4 -10

Diff too large; view file

crates/forge-web-pages/src/pages/pull_live.rsmodified+2 -4

Diff too large; view file

crates/forge-web-pages/src/pages/pull_reviews.rsmodified+21 -39

Diff too large; view file

crates/forge-web-pages/src/pages/refs.rsmodified+2 -2

Diff too large; view file

crates/forge-web-pages/src/pages/releases.rsmodified+59 -138

Diff too large; view file

crates/forge-web-pages/src/pages/releases_live.rsmodified+2 -3

Diff too large; view file

crates/forge-web-pages/src/pages/repo.rsmodified+2 -2

Diff too large; view file

crates/forge-web-pages/src/pages/repo_ctx.rsmodified+39 -7

Diff too large; view file

crates/forge-web-pages/src/pages/repo_mirrors.rsmodified+22 -71

Diff too large; view file

crates/forge-web-pages/src/pages/repo_rename.rsmodified+1 -1

Diff too large; view file

crates/forge-web-pages/src/pages/repo_security.rsmodified+10 -16

Diff too large; view file

crates/forge-web-pages/src/pages/repo_settings.rsmodified+35 -8

Diff too large; view file

crates/forge-web-pages/src/pages/tree.rsmodified+2 -2

Diff too large; view file

crates/forge-web-pages/src/pages/wiki.rsmodified+6 -6

Diff too large; view file

crates/forge-web-repo/src/pages/authoring_tests.rsmodified+23 -23

Diff too large; view file

crates/forge-web-repo/src/pages/blame.rsmodified+1 -1

Diff too large; view file

crates/forge-web-repo/src/pages/blob.rsmodified+1 -1

Diff too large; view file

crates/forge-web-repo/src/pages/branches.rsmodified+6 -18

Diff too large; view file

crates/forge-web-repo/src/pages/ci_tests.rsmodified+1 -31

Diff too large; view file

crates/forge-web-repo/src/pages/code_search.rsmodified+1 -1

Diff too large; view file

crates/forge-web-repo/src/pages/commit.rsmodified+1 -1

Diff too large; view file

crates/forge-web-repo/src/pages/commits.rsmodified+5 -5

Diff too large; view file

crates/forge-web-repo/src/pages/compare.rsmodified+40 -23

Diff too large; view file

crates/forge-web-repo/src/pages/discussion_actions.rsmodified+1 -1

Diff too large; view file

crates/forge-web-repo/src/pages/discussion_live_tests.rsmodified+5 -17

Diff too large; view file

crates/forge-web-repo/src/pages/discussion_view.rsmodified+2 -2

Diff too large; view file

crates/forge-web-repo/src/pages/discussions.rsmodified+12 -11

Diff too large; view file

crates/forge-web-repo/src/pages/fork.rsmodified+3 -35

Diff too large; view file

crates/forge-web-repo/src/pages/issue_meta_tests.rsmodified+4 -35

Diff too large; view file

crates/forge-web-repo/src/pages/issue_pin_tests.rsmodified+35 -67

Diff too large; view file

crates/forge-web-repo/src/pages/issue_view.rsmodified+10 -37

Diff too large; view file

crates/forge-web-repo/src/pages/labels_page.rsmodified+6 -23

Diff too large; view file

crates/forge-web-repo/src/pages/merge_queue.rsmodified+4 -11

Diff too large; view file

crates/forge-web-repo/src/pages/milestones_page.rsmodified+8 -24

Diff too large; view file

crates/forge-web-repo/src/pages/pull_branch.rsmodified+32 -66

Diff too large; view file

crates/forge-web-repo/src/pages/pull_files.rsmodified+22 -42

Diff too large; view file

crates/forge-web-repo/src/pages/pull_flow.rsmodified+6 -14

Diff too large; view file

crates/forge-web-repo/src/pages/pull_view.rsmodified+50 -58

Diff too large; view file

crates/forge-web-repo/src/pages/pulls_list.rsmodified+63 -56

Diff too large; view file

crates/forge-web-repo/src/pages/pulls_merge.rsmodified+18 -48

Diff too large; view file

crates/forge-web-repo/src/pages/push.rsmodified+1 -7

Diff too large; view file

crates/forge-web-repo/src/pages/reactions.rsmodified+1 -1

Diff too large; view file

crates/forge-web-repo/src/pages/reactions_tests.rsmodified+3 -27

Diff too large; view file

crates/forge-web-repo/src/pages/repo_collaborators.rsmodified+2 -12

Diff too large; view file

crates/forge-web-repo/src/pages/repo_scrub.rsmodified+1 -1

Diff too large; view file

crates/forge-web-repo/src/pages/repo_secrets.rsmodified+13 -56

Diff too large; view file

crates/forge-web-repo/src/pages/repo_webhooks.rsmodified+26 -79

Diff too large; view file

crates/forge-web-repo/src/pages/review_requests.rsmodified+11 -19

Diff too large; view file

crates/forge-web/src/admin_cli.rsmodified+10 -9

Diff too large; view file

crates/forge-web/src/boot.rsmodified+48 -45

Diff too large; view file

crates/forge-web/src/compression_route_tests.rsmodified+2 -2

Diff too large; view file

crates/forge-web/src/forgejo_tests.rsmodified+8 -7

Diff too large; view file

crates/forge-web/src/gitea_route_tests.rsmodified+14 -14

Diff too large; view file

crates/forge-web/src/importer_route_tests.rsmodified+8 -6

Diff too large; view file

crates/forge-web/src/main.rsmodified+1 -9

Diff too large; view file

crates/forge-web/src/page_route_tests/edit_history.rsmodified+16 -15

Diff too large; view file

crates/forge-web/src/page_route_tests/notifications.rsmodified+8 -38

Diff too large; view file

crates/forge-web/src/page_route_tests/pull_reviews.rsmodified+23 -8

Diff too large; view file

crates/forge-web/src/page_route_tests/repo.rsmodified+17 -17

Diff too large; view file

crates/forge-web/src/shell_route_tests.rsmodified+11 -11

Diff too large; view file

crates/forge-web/src/templates_route_tests.rsmodified+2 -2

Diff too large; view file

docs/merge-queue.mdmodified+1 -1

Diff too large; view file