diff --git a/.forge/ci.toml b/.forge/ci.toml index 12ddc82..065b698 100644 --- a/.forge/ci.toml +++ b/.forge/ci.toml @@ -7,7 +7,6 @@ push = ["main"] pull_request = true manual = true -tags = ["v*"] [jobs.test] image = "docker.io/library/rust:1" @@ -35,6 +34,3 @@ mkdir -p dist && cp target/dist/forge dist/forge artifacts = ["dist/forge", "forge-*-linux", "SHA256SUMS"] cache = ["target"] timeout_minutes = 120 - -[release] -assets = ["build:forge-*-linux", "build:SHA256SUMS"] diff --git a/Cargo.lock b/Cargo.lock index 57636d8..df20c45 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1852,6 +1852,7 @@ dependencies = [ "base64 0.23.1", "globset", "serde", + "serde_ignored", "serde_json", "thiserror 2.0.21", "toml", @@ -6206,6 +6207,16 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "serde_ignored" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "115dffd5f3853e06e746965a20dcbae6ee747ae30b543d91b0e089668bb07798" +dependencies = [ + "serde", + "serde_core", +] + [[package]] name = "serde_json" version = "1.0.154" diff --git a/crates/forge-ci/Cargo.toml b/crates/forge-ci/Cargo.toml index 463ccdd..9f40e4c 100644 --- a/crates/forge-ci/Cargo.toml +++ b/crates/forge-ci/Cargo.toml @@ -10,6 +10,7 @@ publish = false base64 = { workspace = true } globset = { workspace = true } serde = { workspace = true } +serde_ignored = "0.1.14" serde_json = { workspace = true } thiserror = { workspace = true } toml = { workspace = true } diff --git a/crates/forge-ci/src/config.rs b/crates/forge-ci/src/config.rs index 1eb52d8..f991e49 100644 --- a/crates/forge-ci/src/config.rs +++ b/crates/forge-ci/src/config.rs @@ -40,7 +40,6 @@ pub const MAX_RELEASE_TITLE_CHARS: usize = 200; /// A parsed and validated workflow. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] pub struct CiConfig { /// Optional display name, e.g. `"build"`. The CI badge uses it as its label. #[serde(default)] @@ -54,11 +53,16 @@ pub struct CiConfig { /// The `[release]` table. Optional; when set, a tag run that fully succeeds publishes a release. #[serde(default)] pub release: Option, + /// Keys this forge does not know, as dotted paths, e.g. `release` or `jobs.build.foo`. They are + /// ignored, not rejected, so a newer `ci.toml` still runs on an older forge. Filled by + /// [`parse_config`]; never read from the file. + #[serde(skip)] + pub warnings: Vec, } /// The `[release]` table. Requires `on.tags`. See docs/ci.md, Releases. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields, default)] +#[serde(default)] pub struct ReleaseSpec { /// `":"` entries. The glob matches the job's flattened artifact names. pub assets: Vec, @@ -132,7 +136,7 @@ pub enum ReleaseNotes { /// The `[on]` table. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields, default)] +#[serde(default)] pub struct Triggers { /// Branch globs, e.g. `"main"`, `"release/*"`. pub push: Vec, @@ -156,7 +160,6 @@ impl Default for Triggers { /// One `[jobs.]` table. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] pub struct JobSpec { pub image: String, pub run: String, @@ -207,8 +210,18 @@ pub fn parse_config(text: &str) -> Result { max: MAX_CONFIG_BYTES, }); } - let config: CiConfig = toml::from_str(text).map_err(|e| ConfigError::Toml(e.to_string()))?; + let de = toml::Deserializer::parse(text).map_err(|e| ConfigError::Toml(e.to_string()))?; + let mut warnings = Vec::new(); + let mut config: CiConfig = serde_ignored::deserialize(de, |path| { + // serde_ignored marks `Option` wrappers with `?`; they are not part of the key path. + let path = path.to_string().replace("?.", ""); + warnings.push(format!( + "unknown key `{path}` ignored \u{2014} this forge may be older than your ci.toml" + )); + }) + .map_err(|e| ConfigError::Toml(e.to_string()))?; config.validate()?; + config.warnings = warnings; Ok(config) } @@ -694,16 +707,41 @@ artifacts = ["target/release/forge"] } #[test] - fn unknown_keys_are_rejected() { + fn unknown_keys_are_ignored_with_a_warning() { + let cfg = parse_config(&format!("[on]\nschedule = true\n{}", job_toml(""))).unwrap(); + assert_eq!(cfg.warnings.len(), 1); + assert!(cfg.warnings[0].starts_with("unknown key `on.schedule` ignored")); + assert!(cfg.on.manual, "known keys still apply"); + + let cfg = parse_config(&job_toml("bogus = 1")).unwrap(); + assert_eq!(cfg.warnings.len(), 1); + assert!(cfg.warnings[0].contains("`jobs.build.bogus`"), "{:?}", cfg.warnings); + assert_eq!(cfg.jobs.len(), 1); + + let cfg = parse_config(&format!("{}\n[other]\nx = 1\n", job_toml(""))).unwrap(); + assert_eq!(cfg.warnings.len(), 1); + assert!(cfg.warnings[0].contains("`other`"), "{:?}", cfg.warnings); + } + + #[test] + fn known_file_has_no_warnings() { + assert!(parse_config(EXAMPLE).unwrap().warnings.is_empty()); + } + + #[test] + fn known_keys_are_still_validated() { assert!(matches!( - err_of(&format!("[on]\nschedule = true\n{}", job_toml(""))), + err_of(&format!("[on]\npush = 3\n{}", job_toml(""))), ConfigError::Toml(_) )); assert!(matches!( - err_of(&job_toml("bogus = 1")), + err_of(&job_toml("timeout_minutes = \"soon\"\nbogus = 1")), ConfigError::Toml(_) )); - assert!(matches!(err_of("[other]\nx = 1\n"), ConfigError::Toml(_))); + assert!(matches!( + err_of(&job_toml("timeout_minutes = 0")), + ConfigError::InvalidTimeout { .. } + )); } #[test] @@ -1153,11 +1191,11 @@ artifacts = ["target/release/forge"] } #[test] - fn release_unknown_keys_are_rejected() { - assert!(matches!( - err_of(&release_toml("bogus = 1")), - ConfigError::Toml(_) - )); + fn release_unknown_keys_are_ignored_with_a_warning() { + let cfg = parse_config(&release_toml("bogus = 1")).unwrap(); + assert_eq!(cfg.warnings.len(), 1); + assert!(cfg.warnings[0].contains("`release.bogus`"), "{:?}", cfg.warnings); + assert!(cfg.release.is_some()); } #[test] diff --git a/crates/forge-core/migrations/0043_sidebar_side.sql b/crates/forge-core/migrations/0043_sidebar_side.sql new file mode 100644 index 0000000..e49030b --- /dev/null +++ b/crates/forge-core/migrations/0043_sidebar_side.sql @@ -0,0 +1,5 @@ +-- Which side the main shell sidebar sits on: 'left' or 'right'. The store checks the value (see +-- store/ui_prefs.rs), and the web layer renders it on as data-sidebar. Applied by +-- store/migrate.rs. + +ALTER TABLE users ADD COLUMN sidebar_side TEXT NOT NULL DEFAULT 'left'; diff --git a/crates/forge-core/src/authz.rs b/crates/forge-core/src/authz.rs index 6a7fb92..4d86b64 100644 --- a/crates/forge-core/src/authz.rs +++ b/crates/forge-core/src/authz.rs @@ -132,6 +132,7 @@ mod tests { accent_dark: crate::store::ui_prefs::DEFAULT_ACCENT.into(), base_light: crate::store::ui_prefs::DEFAULT_BASE.into(), base_dark: crate::store::ui_prefs::DEFAULT_BASE.into(), + sidebar_side: crate::store::ui_prefs::DEFAULT_SIDEBAR.into(), kind: AccountKind::User, email_notifications: true, } diff --git a/crates/forge-core/src/model.rs b/crates/forge-core/src/model.rs index 74c5ca4..3b8d70e 100644 --- a/crates/forge-core/src/model.rs +++ b/crates/forge-core/src/model.rs @@ -56,6 +56,8 @@ pub struct User { pub base_light: String, /// Base set for the dark theme. "fern" is the default. pub base_dark: String, + /// Which side the main shell sidebar sits on: "left" (the default) or "right". + pub sidebar_side: String, /// `User` for a person, `Org` for an organization. pub kind: AccountKind, /// Whether notifications are also sent by email (needs a verified email and instance mail). @@ -140,6 +142,7 @@ impl std::fmt::Debug for User { .field("accent_dark", &self.accent_dark) .field("base_light", &self.base_light) .field("base_dark", &self.base_dark) + .field("sidebar_side", &self.sidebar_side) .field("kind", &self.kind) .finish() } @@ -232,6 +235,7 @@ mod tests { accent_dark: crate::store::ui_prefs::DEFAULT_ACCENT.into(), base_light: crate::store::ui_prefs::DEFAULT_BASE.into(), base_dark: crate::store::ui_prefs::DEFAULT_BASE.into(), + sidebar_side: crate::store::ui_prefs::DEFAULT_SIDEBAR.into(), kind: AccountKind::User, email_notifications: true, }; diff --git a/crates/forge-core/src/store/account_tokens.rs b/crates/forge-core/src/store/account_tokens.rs index 6fc734b..33f2900 100644 --- a/crates/forge-core/src/store/account_tokens.rs +++ b/crates/forge-core/src/store/account_tokens.rs @@ -100,7 +100,7 @@ impl Store { &conn, "SELECT id, username, email, password_hash, is_admin, created_at, about, timezone, \ (SELECT hash FROM avatars WHERE avatars.user_id = users.id) AS avatar_hash, \ - theme, language, kind, email_notifications, display_name, accent, accent_dark, base_light, base_dark FROM users WHERE LOWER(email) = LOWER(?1) \ + theme, language, kind, email_notifications, display_name, accent, accent_dark, base_light, base_dark, sidebar_side FROM users WHERE LOWER(email) = LOWER(?1) \ AND email_verified_at IS NOT NULL AND kind = 'user' LIMIT 1", (email.to_owned(),), map_user, @@ -307,6 +307,7 @@ impl Store { accent_dark: crate::store::ui_prefs::DEFAULT_ACCENT.into(), base_light: crate::store::ui_prefs::DEFAULT_BASE.into(), base_dark: crate::store::ui_prefs::DEFAULT_BASE.into(), + sidebar_side: crate::store::ui_prefs::DEFAULT_SIDEBAR.into(), kind: AccountKind::User, email_notifications: true, }; diff --git a/crates/forge-core/src/store/migrate.rs b/crates/forge-core/src/store/migrate.rs index 7c5c09f..da3adb1 100644 --- a/crates/forge-core/src/store/migrate.rs +++ b/crates/forge-core/src/store/migrate.rs @@ -61,6 +61,7 @@ pub const MIGRATIONS: &[(u32, &str)] = &[ (40, include_str!("../../migrations/0040_mail_queue.sql")), (41, include_str!("../../migrations/0041_accent.sql")), (42, include_str!("../../migrations/0042_colours.sql")), + (43, include_str!("../../migrations/0043_sidebar_side.sql")), ]; /// The highest migration version this binary knows about. diff --git a/crates/forge-core/src/store/mod.rs b/crates/forge-core/src/store/mod.rs index e3f9ed2..dd27a29 100644 --- a/crates/forge-core/src/store/mod.rs +++ b/crates/forge-core/src/store/mod.rs @@ -110,7 +110,7 @@ struct Inner { const USER_COLS: &str = "id, username, email, password_hash, is_admin, created_at, about, timezone, \ (SELECT hash FROM avatars WHERE avatars.user_id = users.id) AS avatar_hash, \ - theme, language, kind, email_notifications, display_name, accent, accent_dark, base_light, base_dark"; + theme, language, kind, email_notifications, display_name, accent, accent_dark, base_light, base_dark, sidebar_side"; const SESSION_COLS: &str = "id, user_id, csrf_token, created_at, expires_at, last_seen, user_agent"; const SSH_KEY_COLS: &str = "id, user_id, title, algorithm, key_blob, fingerprint, created_at, last_used_at"; @@ -204,6 +204,7 @@ impl Store { accent_dark: crate::store::ui_prefs::DEFAULT_ACCENT.into(), base_light: crate::store::ui_prefs::DEFAULT_BASE.into(), base_dark: crate::store::ui_prefs::DEFAULT_BASE.into(), + sidebar_side: crate::store::ui_prefs::DEFAULT_SIDEBAR.into(), kind: AccountKind::User, email_notifications: true, }; @@ -251,6 +252,7 @@ impl Store { accent_dark: crate::store::ui_prefs::DEFAULT_ACCENT.into(), base_light: crate::store::ui_prefs::DEFAULT_BASE.into(), base_dark: crate::store::ui_prefs::DEFAULT_BASE.into(), + sidebar_side: crate::store::ui_prefs::DEFAULT_SIDEBAR.into(), kind: AccountKind::User, email_notifications: true, }; @@ -1048,6 +1050,7 @@ fn map_user(row: &Row) -> Result { accent_dark: col_text(row, 15)?, base_light: col_text(row, 16)?, base_dark: col_text(row, 17)?, + sidebar_side: col_text(row, 18)?, }) } @@ -2178,7 +2181,7 @@ impl Store { WHERE collaborators.repo_id = ?1 ORDER BY users.username_folded" ), (repo_id.to_string(),), - |row| Ok((map_user(row)?, parse_role(&col_text(row, 18)?)?)), + |row| Ok((map_user(row)?, parse_role(&col_text(row, 19)?)?)), ) .await } diff --git a/crates/forge-core/src/store/orgs.rs b/crates/forge-core/src/store/orgs.rs index 2541eac..c013825 100644 --- a/crates/forge-core/src/store/orgs.rs +++ b/crates/forge-core/src/store/orgs.rs @@ -277,7 +277,7 @@ impl Store { ORDER BY (org_role = 'owner') DESC, username_folded" ), (org_id.to_string(),), - |row| Ok((map_user(row)?, OrgMemberRole::parse(&col_text(row, 18)?)?)), + |row| Ok((map_user(row)?, OrgMemberRole::parse(&col_text(row, 19)?)?)), ) .await } @@ -397,7 +397,7 @@ impl Store { (SELECT org_id FROM org_members WHERE user_id = ?1) ORDER BY username_folded" ), (user_id.to_string(),), - |row| Ok((map_user(row)?, OrgMemberRole::parse(&col_text(row, 18)?)?)), + |row| Ok((map_user(row)?, OrgMemberRole::parse(&col_text(row, 19)?)?)), ) .await } diff --git a/crates/forge-core/src/store/ui_prefs.rs b/crates/forge-core/src/store/ui_prefs.rs index 41bc938..1571496 100644 --- a/crates/forge-core/src/store/ui_prefs.rs +++ b/crates/forge-core/src/store/ui_prefs.rs @@ -1,8 +1,8 @@ -//! Per-user UI preferences: the colour theme, the language and the colour choices. The colours -//! are an accent and a base (neutral background, surface and text) for each of the light and the -//! dark theme. All are stored as text in `users` (migrations 0030, 0041 and 0042). The web layer -//! decides which values it offers; the store only checks that a value is well formed, so a new -//! language, accent or base needs no store change. +//! Per-user UI preferences: the colour theme, the language, the colour choices and the side of the +//! shell sidebar. The colours are an accent and a base (neutral background, surface and text) for +//! each of the light and the dark theme. All are stored as text in `users` (migrations 0030, 0041, +//! 0042 and 0043). The web layer decides which values it offers; the store only checks that a +//! value is well formed, so a new language, accent or base needs no store change. use super::{Store, db_err}; use crate::error::{Error, Result}; @@ -21,6 +21,12 @@ pub const DEFAULT_ACCENT: &str = "sage"; /// forge-web's `accent_palette.rs`, which a test there checks. pub const DEFAULT_BASE: &str = "fern"; +/// The sidebar sides, in the order the settings page lists them. +pub const SIDEBAR_SIDES: &[&str] = &["left", "right"]; + +/// The side a new user's sidebar sits on. It is the side the shell has always used. +pub const DEFAULT_SIDEBAR: &str = "left"; + /// Longest accepted language code, in bytes. const MAX_LANGUAGE_LEN: usize = 16; @@ -52,6 +58,11 @@ pub fn valid_accent(id: &str) -> bool { .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-') } +/// True for `left` or `right`, the two sides the sidebar can sit on. +pub fn valid_sidebar(side: &str) -> bool { + SIDEBAR_SIDES.contains(&side) +} + impl Store { /// Sets the user's theme and language. Anything malformed is rejected and nothing is written. pub async fn set_ui_prefs(&self, user_id: &str, theme: &str, language: &str) -> Result<()> { @@ -136,6 +147,26 @@ impl Store { Ok(()) } + /// Sets the side the shell sidebar sits on. Anything but `left` or `right` is rejected and + /// nothing is written. + pub async fn set_sidebar_side(&self, user_id: &str, side: &str) -> Result<()> { + if !valid_sidebar(side) { + return Err(Error::Invalid(format!("sidebar {side:?}"))); + } + let conn = self.inner.conn.lock().await; + let n = conn + .execute( + "UPDATE users SET sidebar_side = ?2 WHERE id = ?1", + (user_id.to_string(), side.to_string()), + ) + .await + .map_err(db_err)?; + if n == 0 { + return Err(Error::NotFound); + } + Ok(()) + } + /// Turns the email copy of notifications on or off for one user (migration 0035). pub async fn set_email_notifications(&self, user_id: &str, on: bool) -> Result<()> { let conn = self.inner.conn.lock().await; @@ -310,4 +341,51 @@ mod tests { ("dark", "tr") ); } + + #[tokio::test] + async fn sidebar_side_persists_and_bad_values_change_nothing() { + let dir = tempfile::tempdir().unwrap(); + let store = Store::open(&dir.path().join("forge.db")).await.unwrap(); + let user = store + .create_user("tahinli", None, "hash", false) + .await + .unwrap(); + assert_eq!(user.sidebar_side, DEFAULT_SIDEBAR); + + store.set_sidebar_side(&user.id, "right").await.unwrap(); + assert_eq!( + store + .user_by_id(&user.id) + .await + .unwrap() + .unwrap() + .sidebar_side, + "right" + ); + + for bad in ["", "Right", "top", "../x", "left "] { + assert!( + store.set_sidebar_side(&user.id, bad).await.is_err(), + "{bad}" + ); + } + assert_eq!( + store + .user_by_id(&user.id) + .await + .unwrap() + .unwrap() + .sidebar_side, + "right" + ); + } + + #[test] + fn sidebar_sides() { + assert!(valid_sidebar("left")); + assert!(valid_sidebar("right")); + for bad in ["", "center", "Left", "right-2"] { + assert!(!valid_sidebar(bad), "{bad}"); + } + } } diff --git a/crates/forge-core/src/store/user_delete.rs b/crates/forge-core/src/store/user_delete.rs index cb88640..9b22413 100644 --- a/crates/forge-core/src/store/user_delete.rs +++ b/crates/forge-core/src/store/user_delete.rs @@ -170,6 +170,7 @@ impl Store { accent_dark: crate::store::ui_prefs::DEFAULT_ACCENT.into(), base_light: crate::store::ui_prefs::DEFAULT_BASE.into(), base_dark: crate::store::ui_prefs::DEFAULT_BASE.into(), + sidebar_side: crate::store::ui_prefs::DEFAULT_SIDEBAR.into(), kind: AccountKind::User, email_notifications: true, }; diff --git a/crates/forge-web/assets/nav.js b/crates/forge-web/assets/nav.js index be0fb05..13330aa 100644 --- a/crates/forge-web/assets/nav.js +++ b/crates/forge-web/assets/nav.js @@ -130,7 +130,7 @@ function adopt(doc, keepFields, dd) { document.title = doc.title; - ['lang', 'data-theme', 'data-accent-light', 'data-accent-dark', 'data-base-light', 'data-base-dark', 'data-ui'].forEach(function (name) { + ['lang', 'data-theme', 'data-accent-light', 'data-accent-dark', 'data-base-light', 'data-base-dark', 'data-sidebar', 'data-ui'].forEach(function (name) { if (doc.documentElement.hasAttribute(name)) { root.setAttribute(name, doc.documentElement.getAttribute(name)); } else { root.removeAttribute(name); } }); @@ -424,7 +424,7 @@ // Appearance page: a colour or theme choice shows on at once, before the form's request returns. // The attributes match what the shell renders: theme `auto` has no data-theme, `dark` is dark, else light. - var PREVIEW_ATTR = { accent_light: 'data-accent-light', accent_dark: 'data-accent-dark', base_light: 'data-base-light', base_dark: 'data-base-dark' }; + var PREVIEW_ATTR = { accent_light: 'data-accent-light', accent_dark: 'data-accent-dark', base_light: 'data-base-light', base_dark: 'data-base-dark', sidebar_side: 'data-sidebar' }; document.addEventListener('change', function (e) { var el = e.target; diff --git a/crates/forge-web/src/api/releases.rs b/crates/forge-web/src/api/releases.rs index e98b30b..7c9b034 100644 --- a/crates/forge-web/src/api/releases.rs +++ b/crates/forge-web/src/api/releases.rs @@ -415,9 +415,17 @@ mod tests { let out = std::process::Command::new("git") .current_dir(dir) .args(args) + .env("GIT_AUTHOR_NAME", "test") + .env("GIT_AUTHOR_EMAIL", "test@example.com") + .env("GIT_COMMITTER_NAME", "test") + .env("GIT_COMMITTER_EMAIL", "test@example.com") .output() .expect("git runs"); - assert!(out.status.success(), "git {args:?} failed"); + assert!( + out.status.success(), + "git {args:?} failed: {}", + String::from_utf8_lossy(&out.stderr) + ); String::from_utf8_lossy(&out.stdout).trim().to_owned() } diff --git a/crates/forge-web/src/ci/schedule.rs b/crates/forge-web/src/ci/schedule.rs index 9a174da..e6aaa0b 100644 --- a/crates/forge-web/src/ci/schedule.rs +++ b/crates/forge-web/src/ci/schedule.rs @@ -10,8 +10,10 @@ use forge_core::ci::{CiRun, NewJob}; use forge_core::store::commit_status::StatusState; use forge_core::{PullRequest, Repo}; use forge_git::browse::{read_blob, resolve_commit}; +use tokio::io::AsyncWriteExt; -use super::{publish, sync_run_statuses}; +use super::api::fit_to_cap; +use super::{log_path, publish, sync_run_statuses}; use crate::internal::is_zero_oid; use crate::state::AppState; @@ -19,6 +21,9 @@ use crate::state::AppState; pub const CONFIG_PATH: &str = ".forge/ci.toml"; /// Largest workflow file read, in bytes. const MAX_CONFIG_BYTES: usize = 64 * 1024; +/// Most config warnings written to each job log. The rest are only in the tracing output. +const MAX_WARNING_LINES: usize = 20; +const MIB: u64 = 1024 * 1024; /// A job ready to store: name, `JobSpec` as JSON, and its needs. type PlannedJob = (String, String, Vec); @@ -36,10 +41,12 @@ enum Plan { Missing, /// The file is valid but this event does not trigger it. NotTriggered, - /// Create a run with these jobs, or an Error run when `config_error` is set. + /// Create a run with these jobs, or an Error run when `config_error` is set. `warnings` are the + /// config's ignored keys, written to the start of every job log. Run { jobs: Vec, config_error: Option, + warnings: Vec, }, } @@ -76,7 +83,12 @@ pub async fn on_ref_update( }; let result = async { let loaded = load(state, &repo.id, new_oid).await; - if let Plan::Run { jobs, config_error } = plan_for(loaded, &event)? { + if let Plan::Run { + jobs, + config_error, + warnings, + } = plan_for(loaded, &event)? + { create( state, Request { @@ -90,6 +102,7 @@ pub async fn on_ref_update( }, jobs, config_error.as_deref(), + &warnings, ) .await?; } @@ -120,7 +133,12 @@ async fn pull_run( actor_id: &str, ) -> forge_core::Result<()> { let loaded = load(state, &repo.id, &pull.head_oid).await; - let Plan::Run { jobs, config_error } = plan_for(loaded, &Event::PullRequest)? else { + let Plan::Run { + jobs, + config_error, + warnings, + } = plan_for(loaded, &Event::PullRequest)? + else { return Ok(()); }; let needs_approval = needs_approval(state, repo, pull).await?; @@ -138,6 +156,7 @@ async fn pull_run( }, jobs, config_error.as_deref(), + &warnings, ) .await?; Ok(()) @@ -167,7 +186,11 @@ pub async fn manual_run( }; let loaded = load(state, &repo.id, &commit).await; match plan_for(loaded, &Event::Manual)? { - Plan::Run { jobs, config_error } => { + Plan::Run { + jobs, + config_error, + warnings, + } => { create( state, Request { @@ -181,6 +204,7 @@ pub async fn manual_run( }, jobs, config_error.as_deref(), + &warnings, ) .await } @@ -200,6 +224,7 @@ async fn create( req: Request<'_>, jobs: Vec, config_error: Option<&str>, + warnings: &[String], ) -> forge_core::Result { let new_jobs: Vec> = jobs .iter() @@ -224,6 +249,7 @@ async fn create( ) .await?; state.ci_live.bump_repo(&run.repo_id); + note_warnings(state, &run, warnings).await?; if let Some(message) = config_error { let url = format!( "{}/{}/{}/ci/runs/{}", @@ -249,6 +275,65 @@ async fn create( Ok(run) } +/// Writes the config warnings as `[forge] warning: ...` lines at the start of every job's log, and +/// logs them. Runs before the runners are woken, so the lines come first. A failed write is logged +/// and does not fail the run. +async fn note_warnings( + state: &AppState, + run: &CiRun, + warnings: &[String], +) -> forge_core::Result<()> { + if warnings.is_empty() { + return Ok(()); + } + let mut text = String::new(); + for warning in warnings { + tracing::warn!(run_id = %run.id, repo_id = %run.repo_id, "ci: {warning}"); + } + for warning in warnings.iter().take(MAX_WARNING_LINES) { + text.push_str(&format!("[forge] warning: {warning}\n")); + } + let cap = state.config.ci.max_log_mb.saturating_mul(MIB); + for job in state.store.jobs_for_run(&run.id).await? { + let path = log_path(&state.config.data_dir, &job.id); + let current = match tokio::fs::metadata(&path).await { + Ok(meta) => meta.len(), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => 0, + Err(e) => { + tracing::error!(error = %e, job_id = %job.id, "ci: reading the job log failed"); + continue; + } + }; + let bytes = fit_to_cap(current, cap, text.as_bytes()); + if bytes.is_empty() { + continue; + } + let written: std::io::Result<()> = async { + if let Some(parent) = path.parent() { + tokio::fs::create_dir_all(parent).await?; + } + let mut file = tokio::fs::OpenOptions::new() + .create(true) + .append(true) + .open(&path) + .await?; + file.write_all(&bytes).await?; + file.flush().await + } + .await; + if let Err(e) = written { + tracing::error!(error = %e, job_id = %job.id, "ci: writing the job log failed"); + continue; + } + if let Err(e) = state.store.add_log_bytes(&job.id, bytes.len() as i64).await { + tracing::error!(error = %e, job_id = %job.id, "ci: counting the job log bytes failed"); + continue; + } + state.ci_live.bump_job(&job.id); + } + Ok(()) +} + /// Decides what a request does, given the loaded config and the event. fn plan_for(loaded: Loaded, event: &Event<'_>) -> forge_core::Result { match loaded { @@ -256,6 +341,7 @@ fn plan_for(loaded: Loaded, event: &Event<'_>) -> forge_core::Result { Loaded::Invalid(message) => Ok(Plan::Run { jobs: Vec::new(), config_error: Some(message), + warnings: Vec::new(), }), Loaded::Valid(cfg) => { if !cfg.triggered_by(event) { @@ -264,6 +350,7 @@ fn plan_for(loaded: Loaded, event: &Event<'_>) -> forge_core::Result { Ok(Plan::Run { jobs: plan_jobs(&cfg)?, config_error: None, + warnings: cfg.warnings.clone(), }) } } @@ -612,6 +699,35 @@ run = "make" assert_eq!(test.state, StatusState::Pending); } + #[tokio::test] + async fn unknown_config_keys_still_run_and_warn_in_each_job_log() { + let fx = fixture().await; + let text = format!("{CONFIG_ONE_JOB}\n[future]\nx = 1\n"); + push(&fx, &[(CONFIG_PATH, text.as_str())], "refs/heads/main").await; + + let run = fx + .state + .store + .run_by_number(&fx.repo.id, 1) + .await + .expect("query") + .expect("run exists"); + assert!(run.config_error.is_none(), "unknown keys are not an error"); + let jobs = fx.state.store.jobs_for_run(&run.id).await.expect("jobs"); + assert_eq!(state_of(&jobs, "build"), Some(JobState::Queued)); + + for job in &jobs { + let log = std::fs::read_to_string(log_path(&fx.state.config.data_dir, &job.id)) + .expect("job log"); + assert!( + log.starts_with( + "[forge] warning: unknown key `future` ignored \u{2014} this forge may be older than your ci.toml\n" + ), + "log was {log:?}" + ); + } + } + #[tokio::test] async fn no_file_means_no_run() { let fx = fixture().await; diff --git a/crates/forge-web/src/i18n/admin.rs b/crates/forge-web/src/i18n/admin.rs index 684075e..25d2cf6 100644 --- a/crates/forge-web/src/i18n/admin.rs +++ b/crates/forge-web/src/i18n/admin.rs @@ -11,6 +11,7 @@ pub enum K { ActionLabel, ActorUsername, AddARunner, + AdminArea, Administrator, AllActions, Anonymous, @@ -168,6 +169,8 @@ pub fn t(lang: Lang, key: K) -> &'static str { (ActorUsername, Tr) => "Yapan kullanıcı adı", (AddARunner, En) => "Add a runner", (AddARunner, Tr) => "Çalıştırıcı ekle", + (AdminArea, En) => "Admin", + (AdminArea, Tr) => "Yönetim", (Administrator, En) => "Administrator", (Administrator, Tr) => "Yönetici", (AllActions, En) => "All actions", @@ -722,6 +725,7 @@ mod tests { K::ActionLabel, K::ActorUsername, K::AddARunner, + K::AdminArea, K::Administrator, K::AllActions, K::Anonymous, diff --git a/crates/forge-web/src/i18n/misc.rs b/crates/forge-web/src/i18n/misc.rs index 4ce0e24..05f2d13 100644 --- a/crates/forge-web/src/i18n/misc.rs +++ b/crates/forge-web/src/i18n/misc.rs @@ -31,6 +31,11 @@ pub enum K { DarkColours, BackgroundLabel, ChooseBase, + // Appearance: which side the shell sidebar sits on. + SidebarLabel, + SidebarLeft, + SidebarRight, + ChooseSidebar, // Notifications: row kinds. KindOpenIssue, KindClosedIssue, @@ -173,6 +178,10 @@ const ALL: &[K] = &[ K::DarkColours, K::BackgroundLabel, K::ChooseBase, + K::SidebarLabel, + K::SidebarLeft, + K::SidebarRight, + K::ChooseSidebar, K::KindOpenIssue, K::KindClosedIssue, K::KindOpenPull, @@ -327,6 +336,14 @@ pub fn t(lang: Lang, key: K) -> &'static str { (BackgroundLabel, Tr) => "Arka plan", (ChooseBase, En) => "Choose a background from the list.", (ChooseBase, Tr) => "Listeden bir arka plan seçin.", + (SidebarLabel, En) => "Sidebar position", + (SidebarLabel, Tr) => "Kenar çubuğu konumu", + (SidebarLeft, En) => "Left", + (SidebarLeft, Tr) => "Sol", + (SidebarRight, En) => "Right", + (SidebarRight, Tr) => "Sağ", + (ChooseSidebar, En) => "Choose a sidebar position from the list.", + (ChooseSidebar, Tr) => "Listeden bir kenar çubuğu konumu seçin.", (KindOpenIssue, En) => "Open issue", (KindOpenIssue, Tr) => "Açık sorun", (KindClosedIssue, En) => "Closed issue", diff --git a/crates/forge-web/src/i18n/mod.rs b/crates/forge-web/src/i18n/mod.rs index 0ae075e..e1b5faf 100644 --- a/crates/forge-web/src/i18n/mod.rs +++ b/crates/forge-web/src/i18n/mod.rs @@ -124,9 +124,7 @@ pub enum Key { AccessTokens, Sessions, Security, - AdminUsers, - AdminAuditLog, - AdminRunners, + BackToSite, LogOut, LogIn, SiteMenu, @@ -355,9 +353,7 @@ pub const ALL: &[Key] = &[ Key::AccessTokens, Key::Sessions, Key::Security, - Key::AdminUsers, - Key::AdminAuditLog, - Key::AdminRunners, + Key::BackToSite, Key::LogOut, Key::LogIn, Key::SiteMenu, @@ -574,12 +570,8 @@ pub fn t(lang: Lang, key: Key) -> &'static str { (Sessions, Tr) => "Oturumlar", (Security, En) => "Security", (Security, Tr) => "Güvenlik", - (AdminUsers, En) => "Admin: users", - (AdminUsers, Tr) => "Yönetici: kullanıcılar", - (AdminAuditLog, En) => "Admin: audit log", - (AdminAuditLog, Tr) => "Yönetici: denetim günlüğü", - (AdminRunners, En) => "Admin: runners", - (AdminRunners, Tr) => "Yönetici: çalıştırıcılar", + (BackToSite, En) => "Back to forge", + (BackToSite, Tr) => "Forge'a dön", (LogOut, En) => "Log out", (LogOut, Tr) => "Çıkış yap", (SiteMenu, En) => "Menu", diff --git a/crates/forge-web/src/pages/admin_runners.rs b/crates/forge-web/src/pages/admin_runners.rs index cd7a91c..b3b6d90 100644 --- a/crates/forge-web/src/pages/admin_runners.rs +++ b/crates/forge-web/src/pages/admin_runners.rs @@ -100,13 +100,6 @@ fn register_command(base_url: &str, token: &str) -> String { ) } -#[component] -async fn runners_nav(lang: Lang) -> Result { - Ok(view! { -

(g::t(lang, K::Users)) " · " (g::t(lang, K::AuditLog)) " · " (g::t(lang, K::Backups)) " · " (g::t(lang, K::Replication)) " · " (g::t(lang, K::Mail)) " · " (g::t(lang, K::Runners))

- }) -} - #[component] async fn runners_view( lang: Lang, @@ -118,7 +111,6 @@ async fn runners_view( Ok(view! {

(g::t(lang, K::CiRunners))

- runners_nav(lang: lang)
if let Some((text, is_error)) = notice { if is_error { @@ -191,7 +183,6 @@ async fn token_view( Ok(view! {

(g::t(lang, K::RegistrationToken))

- runners_nav(lang: lang)

(g::t(lang, K::CopyTokenNow))

diff --git a/crates/forge-web/src/pages/admin_users.rs b/crates/forge-web/src/pages/admin_users.rs index cf9e0c7..2ebd26e 100644 --- a/crates/forge-web/src/pages/admin_users.rs +++ b/crates/forge-web/src/pages/admin_users.rs @@ -60,7 +60,6 @@ async fn users_view( Ok(view! {

(g::t(lang, K::Users))

-

(g::t(lang, K::AuditLog)) " · " (g::t(lang, K::Backups)) " · " (g::t(lang, K::Replication)) " · " (g::t(lang, K::Mail)) " · " (g::t(lang, K::Runners)) " · " (g::t(lang, K::Invites))

diff --git a/crates/forge-web/src/pages/settings_appearance.rs b/crates/forge-web/src/pages/settings_appearance.rs index 5a2323f..6fe4ed0 100644 --- a/crates/forge-web/src/pages/settings_appearance.rs +++ b/crates/forge-web/src/pages/settings_appearance.rs @@ -1,10 +1,11 @@ //! Page: appearance (`/settings/appearance`). The colour theme, the language, and for each of the -//! light and dark themes a background and an accent colour, all stored per user. Every change +//! light and dark themes a background and an accent colour, and the side of the shell sidebar, +//! all stored per user. Every change //! saves at once, so the form has no Save button. Anonymous visitors set the theme from the footer //! instead (see `pages/theme_cookie.rs`). Every POST checks the CSRF token first. use forge_core::AuditAction; -use forge_core::store::ui_prefs::THEMES; +use forge_core::store::ui_prefs::{SIDEBAR_SIDES, THEMES}; use forge_core::{Error as CoreError, Session, Store, User}; use serde::{Deserialize, Deserializer}; use topcoat::Result; @@ -30,6 +31,9 @@ pub const LANGUAGE_CODES: &[&str] = &["auto", "en", "tr"]; /// Theme codes, in display order. const THEME_CODES: &[&str] = &["auto", "light", "dark"]; +/// Sidebar sides, in display order. Must match `store::ui_prefs::SIDEBAR_SIDES`. +const SIDEBAR_CODES: &[&str] = &["left", "right"]; + /// Reads a field that is present as a string, even an empty one. The plain `Option` /// reading would turn an empty value into `None`, which is the same as a missing field. fn present_string<'de, D: Deserializer<'de>>( @@ -57,6 +61,8 @@ struct AppearanceForm { base_light: Option, #[serde(default, deserialize_with = "present_string")] base_dark: Option, + #[serde(default, deserialize_with = "present_string")] + sidebar_side: Option, } struct Choice { @@ -83,6 +89,15 @@ struct AppearancePage { language: Vec, light: ColourGroup, dark: ColourGroup, + sidebar: Vec, +} + +/// The label of a sidebar side. +fn sidebar_label(lang: Lang, code: &str) -> &'static str { + match code { + "right" => g::t(lang, K::SidebarRight), + _ => g::t(lang, K::SidebarLeft), + } } /// The label of a language code. The two native names stay as they are in every language. @@ -204,6 +219,7 @@ async fn appearance_body(page: AppearancePage) -> Result { language, light, dark, + sidebar, } = page; Ok(view! {
@@ -230,6 +246,17 @@ async fn appearance_body(page: AppearancePage) -> Result { } +
+ (g::t(lang, K::SidebarLabel)) +
+ for choice in sidebar.into_iter() { + + } +
+
colour_group_fields(group: light) @@ -271,6 +298,22 @@ fn base_choice(lang: Lang, posted: Option<&str>, stored: &str) -> forge_core::Re } } +/// The sidebar side a save stores. An absent field keeps the stored side. A present one must be +/// `left` or `right`, so an empty or unknown value is rejected. +fn sidebar_choice(lang: Lang, posted: Option<&str>, stored: &str) -> forge_core::Result { + match posted { + None => Ok(stored.to_owned()), + Some(side) if SIDEBAR_SIDES.contains(&side) => Ok(side.to_owned()), + Some(_) => Err(CoreError::Invalid(g::t(lang, K::ChooseSidebar).into())), + } +} + +/// The side a viewer's stored value stands for. Anything but `right` is `left`, the default, which +/// is also what the shell renders on `` (see `views/mod.rs`). +pub fn sidebar_stored(stored: &str) -> &'static str { + if stored == "right" { "right" } else { "left" } +} + /// Builds the page for a viewer. Each choice shows the stored value, or the default when the /// stored id is no longer offered, which is what the page renders on `` too. fn page_for(viewer: &(User, Session), lang: Lang) -> AppearancePage { @@ -294,6 +337,9 @@ fn page_for(viewer: &(User, Session), lang: Lang) -> AppearancePage { accent::resolve_base(&user.base_dark).id, accent::resolve(&user.accent_dark).id, ), + sidebar: choices(SIDEBAR_CODES, sidebar_stored(&user.sidebar_side), |code| { + sidebar_label(lang, code) + }), } } @@ -319,9 +365,11 @@ async fn appearance_save(cx: &Cx, Form(form): Form) -> Result) -> Result "right", + _ => "left", + }; // The stored preference, "auto" included, drives the button: its icon, its label and the // value it posts (the next preference in the cycle auto, light, dark). let theme_pref = crate::theme::preference(__cx, viewer.map(|(user, _)| user)); @@ -212,7 +225,7 @@ pub async fn shell( let unread_aside = unread_badge.clone(); Ok(view! { - + @@ -234,7 +247,11 @@ pub async fn shell( } @@ -285,17 +302,9 @@ pub async fn shell(