From 264395ddeb185d1c92d8bc18577f8b2f2d59ccbc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Tue, 20 Oct 2026 08:37:20 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat:=20CI=20run=20UX,=20partial=20?= =?UTF-8?q?re-runs,=20run=20artifacts=20zip,=20ANSI=20log=20viewer,=20supe?= =?UTF-8?q?rseded=20runs,=20config=20warnings?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/forge-ci/src/config.rs | 14 + .../migrations/0050_run_warnings.sql | 4 + crates/forge-core/src/store/ci.rs | 294 +++++++++++++-- crates/forge-core/src/store/migrate.rs | 1 + crates/forge-web/Cargo.toml | 2 +- crates/forge-web/assets/nav.js | 339 +++++++++++++++++- crates/forge-web/src/ci/schedule.rs | 90 ++++- crates/forge-web/src/i18n/releases_ci.rs | 70 ++++ crates/forge-web/src/pages/ci_job.rs | 102 +++++- crates/forge-web/src/pages/ci_runs.rs | 299 ++++++++++++++- crates/forge-web/src/pages/ci_tests.rs | 245 +++++++++++++ docs/ci.md | 43 ++- style/main.scss | 269 ++++++++++++++ 13 files changed, 1724 insertions(+), 48 deletions(-) create mode 100644 crates/forge-core/migrations/0050_run_warnings.sql diff --git a/crates/forge-ci/src/config.rs b/crates/forge-ci/src/config.rs index 1c636cf..d03956d 100644 --- a/crates/forge-ci/src/config.rs +++ b/crates/forge-ci/src/config.rs @@ -145,6 +145,9 @@ pub struct Triggers { pub pull_request: bool, /// Defaults to `true`. pub manual: bool, + /// Defaults to `false`. When set, a push to a branch cancels the queued and running runs of + /// older commits on that branch. + pub cancel_superseded: bool, } impl Default for Triggers { @@ -154,6 +157,7 @@ impl Default for Triggers { tags: Vec::new(), pull_request: false, manual: true, + cancel_superseded: false, } } } @@ -700,6 +704,16 @@ artifacts = ["target/release/forge"] assert!(cfg.on.push.is_empty()); } + #[test] + fn cancel_superseded_is_opt_in() { + let cfg = parse_config(&job_toml("")).unwrap(); + assert!(!cfg.on.cancel_superseded); + let cfg = + parse_config(&format!("[on]\ncancel_superseded = true\n{}", job_toml(""))).unwrap(); + assert!(cfg.on.cancel_superseded); + assert!(cfg.warnings.is_empty(), "{:?}", cfg.warnings); + } + #[test] fn manual_can_be_disabled() { let cfg = parse_config(&format!("[on]\nmanual = false\n{}", job_toml(""))).unwrap(); diff --git a/crates/forge-core/migrations/0050_run_warnings.sql b/crates/forge-core/migrations/0050_run_warnings.sql new file mode 100644 index 0000000..456343f --- /dev/null +++ b/crates/forge-core/migrations/0050_run_warnings.sql @@ -0,0 +1,4 @@ +-- Config warnings of a run (ignored ci.toml keys), one per line, shown as a banner on the run page. +-- NULL when the run had none. Applied by store/migrate.rs. + +ALTER TABLE ci_runs ADD COLUMN config_warnings TEXT; diff --git a/crates/forge-core/src/store/ci.rs b/crates/forge-core/src/store/ci.rs index 92fefdc..1d93d48 100644 --- a/crates/forge-core/src/store/ci.rs +++ b/crates/forge-core/src/store/ci.rs @@ -142,6 +142,17 @@ fn map_artifact(row: &Row) -> Result { }) } +/// `spec` with its `needs` array replaced. Malformed input is returned as it is. +fn spec_with_needs(spec: &str, needs: &[String]) -> String { + match serde_json::from_str::(spec) { + Ok(mut value) if value.is_object() => { + value["needs"] = serde_json::Value::from(needs.to_vec()); + value.to_string() + } + _ => spec.to_owned(), + } +} + /// The `needs` array of a JobSpec. Missing or malformed input gives no needs. fn spec_needs(spec: &str) -> Vec { serde_json::from_str::(spec) @@ -1021,20 +1032,91 @@ impl Store { /// A new run, with the next number, for the same commit, ref, trigger and job specs. The /// new run is queued at once, without approval. pub async fn rerun(&self, run_id: &str, actor_id: &str) -> Result { - let (run, jobs) = { - let conn = self.read_conn().await; - let run = load_run(&conn, run_id).await?.ok_or(Error::NotFound)?; - let jobs = jobs_of_run(&conn, run_id).await?; - (run, jobs) - }; + let (run, jobs) = self.run_and_jobs(run_id).await?; + let names: Vec = jobs.iter().map(|j| j.name.clone()).collect(); + self.rerun_subset(&run, &jobs, &names, actor_id).await + } + + /// A new run with only the failed, errored and cancelled jobs of a finished run, and every + /// job that depends on them (directly or not). Specs are the originals; a need on a job that + /// is not in the new run is dropped, since that job succeeded in the original run. + /// `Conflict` when the run is not finished or has no such job. + pub async fn rerun_failed(&self, run_id: &str, actor_id: &str) -> Result { + let (run, jobs) = self.run_and_jobs(run_id).await?; + if !run.state.is_terminal() { + return Err(Error::Conflict("the run has not finished".into())); + } + let seeds: Vec = jobs + .iter() + .filter(|j| { + matches!( + j.state, + JobState::Failure | JobState::Error | JobState::Cancelled + ) + }) + .map(|j| j.name.clone()) + .collect(); + if seeds.is_empty() { + return Err(Error::Conflict("the run has no failed jobs".into())); + } + self.rerun_subset(&run, &jobs, &seeds, actor_id).await + } + + /// A new run with one finished job of `run_id` and the jobs that depend on it. `NotFound` when + /// the job is not in the run, `Conflict` when it has not finished. + pub async fn rerun_job(&self, run_id: &str, job_id: &str, actor_id: &str) -> Result { + let (run, jobs) = self.run_and_jobs(run_id).await?; + let job = jobs + .iter() + .find(|j| j.id == job_id) + .ok_or(Error::NotFound)?; + if !job.state.is_terminal() { + return Err(Error::Conflict("the job has not finished".into())); + } + self.rerun_subset(&run, &jobs, std::slice::from_ref(&job.name), actor_id) + .await + } + + async fn run_and_jobs(&self, run_id: &str) -> Result<(CiRun, Vec)> { + let conn = self.read_conn().await; + let run = load_run(&conn, run_id).await?.ok_or(Error::NotFound)?; + let jobs = jobs_of_run(&conn, run_id).await?; + Ok((run, jobs)) + } + + /// Creates a run of `seeds` and their dependants out of `jobs`, and copies the warnings. + async fn rerun_subset( + &self, + run: &CiRun, + jobs: &[CiJob], + seeds: &[String], + actor_id: &str, + ) -> Result { + let mut chosen: Vec<&str> = seeds.iter().map(String::as_str).collect(); + loop { + let before = chosen.len(); + for job in jobs { + if !chosen.contains(&job.name.as_str()) + && spec_needs(&job.spec_json) + .iter() + .any(|need| chosen.contains(&need.as_str())) + { + chosen.push(job.name.as_str()); + } + } + if chosen.len() == before { + break; + } + } let owned: Vec<(String, String, Vec)> = jobs .iter() + .filter(|j| chosen.contains(&j.name.as_str())) .map(|j| { - ( - j.name.clone(), - j.spec_json.clone(), - spec_needs(&j.spec_json), - ) + let needs: Vec = spec_needs(&j.spec_json) + .into_iter() + .filter(|need| chosen.contains(&need.as_str())) + .collect(); + (j.name.clone(), spec_with_needs(&j.spec_json, &needs), needs) }) .collect(); let new_jobs: Vec> = owned @@ -1045,16 +1127,77 @@ impl Store { needs, }) .collect(); - self.create_run( - &run.repo_id, - &run.trigger, - &run.git_ref, - &run.commit_oid, - run.pull_number, - actor_id, - false, - &new_jobs, - run.config_error.as_deref(), + let created = self + .create_run( + &run.repo_id, + &run.trigger, + &run.git_ref, + &run.commit_oid, + run.pull_number, + actor_id, + false, + &new_jobs, + run.config_error.as_deref(), + ) + .await?; + let warnings = self.run_warnings(&run.id).await?; + if !warnings.is_empty() { + self.set_run_warnings(&created.id, &warnings).await?; + } + Ok(created) + } + + /// Stores the config warnings of a run, replacing any earlier ones. + pub async fn set_run_warnings(&self, run_id: &str, warnings: &[String]) -> Result<()> { + let joined = (!warnings.is_empty()).then(|| warnings.join("\n")); + let conn = self.inner.conn.lock().await; + conn.execute( + "UPDATE ci_runs SET config_warnings = ?2 WHERE id = ?1", + vec![text(run_id), opt_text(joined.as_deref())], + ) + .await + .map_err(db_err)?; + Ok(()) + } + + /// The config warnings stored for a run, in order. + pub async fn run_warnings(&self, run_id: &str) -> Result> { + let conn = self.read_conn().await; + let joined = fetch_opt( + &conn, + "SELECT config_warnings FROM ci_runs WHERE id = ?1", + (run_id.to_string(),), + |row| col_opt_text(row, 0), + ) + .await? + .flatten(); + Ok(joined + .map(|text| text.lines().map(str::to_owned).collect()) + .unwrap_or_default()) + } + + /// Runs on `git_ref` of the repo that are still queued or running, were started by a push, and + /// are for a commit other than `commit_oid`. The runs a newer push supersedes. + pub async fn superseded_candidates( + &self, + repo_id: &str, + git_ref: &str, + commit_oid: &str, + ) -> Result> { + let conn = self.read_conn().await; + fetch_all( + &conn, + &format!( + "SELECT {RUN_COLS} FROM ci_runs WHERE repo_id = ?1 AND git_ref = ?2 \ + AND trigger = 'push' AND commit_oid <> ?3 \ + AND state IN ('queued', 'running') ORDER BY number" + ), + ( + repo_id.to_string(), + git_ref.to_string(), + commit_oid.to_string(), + ), + map_run, ) .await } @@ -2273,6 +2416,115 @@ mod tests { )); } + #[tokio::test] + async fn partial_reruns_take_failed_jobs_and_their_dependants() { + let fx = fixture().await; + let jobs = [ + job("a", &[], &[]), + job("b", &["a"], &[]), + job("c", &["b"], &[]), + job("d", &[], &[]), + ]; + let first = create(&fx.store, &fx.repo.id, &fx.tahinli.id, &jobs, false).await; + assert!(matches!( + fx.store.rerun_failed(&first.id, &fx.tahinli.id).await, + Err(Error::Conflict(_)) + )); + let a = job_named(&fx.store, &first.id, "a").await; + fx.store + .finish_job(&a.id, JobState::Success, Some(0), None) + .await + .unwrap(); + let b = job_named(&fx.store, &first.id, "b").await; + fx.store + .finish_job(&b.id, JobState::Failure, Some(1), None) + .await + .unwrap(); + // Fail fast cancels the queued `d` and skips `c`. + let done = fx.store.run_by_id(&first.id).await.unwrap().unwrap(); + assert_eq!(done.state, RunState::Failure); + assert_eq!( + job_named(&fx.store, &first.id, "d").await.state, + JobState::Cancelled + ); + + let again = fx + .store + .rerun_failed(&first.id, &fx.tahinli.id) + .await + .unwrap(); + let names: Vec = fx + .store + .jobs_for_run(&again.id) + .await + .unwrap() + .into_iter() + .map(|j| j.name) + .collect(); + assert_eq!(names, ["b", "c", "d"]); + let b2 = job_named(&fx.store, &again.id, "b").await; + assert_eq!(b2.state, JobState::Queued, "its need succeeded before"); + assert!(spec_needs(&b2.spec_json).is_empty()); + let c2 = job_named(&fx.store, &again.id, "c").await; + assert_eq!(c2.state, JobState::Blocked); + assert_eq!(spec_needs(&c2.spec_json), ["b"]); + + // One finished job brings its dependants; a live one is refused. + let single = fx + .store + .rerun_job(&first.id, &a.id, &fx.tahinli.id) + .await + .unwrap(); + assert_eq!(fx.store.jobs_for_run(&single.id).await.unwrap().len(), 3); + assert!(matches!( + fx.store.rerun_job(&again.id, &b2.id, &fx.tahinli.id).await, + Err(Error::Conflict(_)) + )); + assert!(matches!( + fx.store.rerun_job(&again.id, &a.id, &fx.tahinli.id).await, + Err(Error::NotFound) + )); + } + + #[tokio::test] + async fn warnings_are_stored_and_carried_into_reruns() { + let fx = fixture().await; + let jobs = [job("a", &[], &[])]; + let run = create(&fx.store, &fx.repo.id, &fx.tahinli.id, &jobs, false).await; + assert!(fx.store.run_warnings(&run.id).await.unwrap().is_empty()); + let warnings = vec!["unknown key `on.schedule`".to_owned(), "second".to_owned()]; + fx.store.set_run_warnings(&run.id, &warnings).await.unwrap(); + assert_eq!(fx.store.run_warnings(&run.id).await.unwrap(), warnings); + let again = fx.store.rerun(&run.id, &fx.tahinli.id).await.unwrap(); + assert_eq!(fx.store.run_warnings(&again.id).await.unwrap(), warnings); + } + + #[tokio::test] + async fn superseded_candidates_are_older_live_push_runs_on_the_ref() { + let fx = fixture().await; + let jobs = [job("a", &[], &[])]; + let first = create(&fx.store, &fx.repo.id, &fx.tahinli.id, &jobs, false).await; + let found = fx + .store + .superseded_candidates(&fx.repo.id, "refs/heads/main", "def456") + .await + .unwrap(); + assert_eq!(found.len(), 1); + assert_eq!(found[0].id, first.id); + let same = fx + .store + .superseded_candidates(&fx.repo.id, "refs/heads/main", "abc123") + .await + .unwrap(); + assert!(same.is_empty()); + let elsewhere = fx + .store + .superseded_candidates(&fx.repo.id, "refs/heads/other", "def456") + .await + .unwrap(); + assert!(elsewhere.is_empty()); + } + #[tokio::test] async fn reap_lost_jobs_errors_stale_running_jobs() { let fx = fixture().await; diff --git a/crates/forge-core/src/store/migrate.rs b/crates/forge-core/src/store/migrate.rs index 7f1a8ff..d4816c9 100644 --- a/crates/forge-core/src/store/migrate.rs +++ b/crates/forge-core/src/store/migrate.rs @@ -71,6 +71,7 @@ pub const MIGRATIONS: &[(u32, &str)] = &[ 46, include_str!("../../migrations/0046_server_settings.sql"), ), + (50, include_str!("../../migrations/0050_run_warnings.sql")), ]; /// The highest migration version this binary knows about. diff --git a/crates/forge-web/Cargo.toml b/crates/forge-web/Cargo.toml index 13936fa..ee00f65 100644 --- a/crates/forge-web/Cargo.toml +++ b/crates/forge-web/Cargo.toml @@ -52,6 +52,7 @@ multer.workspace = true ulid.workspace = true forge-runner = { workspace = true } lettre.workspace = true +zip = { workspace = true } [build-dependencies] grass.workspace = true @@ -63,4 +64,3 @@ tempfile.workspace = true forge-runner = { workspace = true, features = ["test-host-executor"] } image = { workspace = true } scraper = { workspace = true } -zip = { workspace = true } diff --git a/crates/forge-web/assets/nav.js b/crates/forge-web/assets/nav.js index 5ea564f..cb51695 100644 --- a/crates/forge-web/assets/nav.js +++ b/crates/forge-web/assets/nav.js @@ -150,6 +150,7 @@ if (dd) { openDropdowns(dd); } if (kept) { restoreFields(kept); } if (dd) { focusDropdown(dd); } + syncLog(); followTail(); restoreJobs(jobs); syncUnread(); @@ -160,7 +161,7 @@ // The log tail is a terminal: it opens at its end. A reader who scrolls up keeps their place. function followTail() { var pre = document.querySelector('[data-live-log]'); - if (pre) { pre.scrollTop = pre.scrollHeight; } + if (pre && !pre.querySelector('.ll-sel')) { pre.scrollTop = pre.scrollHeight; } } // The run page's job rows each have a last-line preview and a tail that opens under the row @@ -576,6 +577,338 @@ syncUnread(); + // The CI log (a job page's [data-live-log]). The server sends the raw text; this turns it into + // numbered lines (#L12 anchors) with ANSI colours as spans, `::group::name` / `::endgroup::` + // sections as
, and a search box with highlight and next/previous. Streamed bytes go + // through the same feed. All text is set with textContent, never as HTML. + var logQuery = ''; // the search text survives a live swap of the page + var LOG_MAX_MARKS = 2000; + + function ansiState() { return { fg: null, bg: null, b: false, d: false, i: false, u: false, v: false }; } + + function ansiCopy(s) { return { fg: s.fg, bg: s.bg, b: s.b, d: s.d, i: s.i, u: s.u, v: s.v }; } + + // The rgb of an xterm 256-colour index above the 16 named ones, as a CSS colour. + function ansi256(n) { + if (n < 16) { return n; } + if (n >= 232) { var g = 8 + (n - 232) * 10; return 'rgb(' + g + ',' + g + ',' + g + ')'; } + n -= 16; + var lv = [0, 95, 135, 175, 215, 255]; + return 'rgb(' + lv[Math.floor(n / 36) % 6] + ',' + lv[Math.floor(n / 6) % 6] + ',' + lv[n % 6] + ')'; + } + + // Applies the numbers of one SGR sequence (ESC [ ... m) to `s`. + function ansiApply(s, codes) { + if (!codes.length) { codes = [0]; } + for (var k = 0; k < codes.length; k++) { + var c = codes[k]; + if (c === 0) { var z = ansiState(); s.fg = z.fg; s.bg = z.bg; s.b = s.d = s.i = s.u = s.v = false; } + else if (c === 1) { s.b = true; } + else if (c === 2) { s.d = true; } + else if (c === 3) { s.i = true; } + else if (c === 4) { s.u = true; } + else if (c === 7) { s.v = true; } + else if (c === 22) { s.b = false; s.d = false; } + else if (c === 23) { s.i = false; } + else if (c === 24) { s.u = false; } + else if (c === 27) { s.v = false; } + else if (c >= 30 && c <= 37) { s.fg = c - 30; } + else if (c >= 90 && c <= 97) { s.fg = c - 90 + 8; } + else if (c >= 40 && c <= 47) { s.bg = c - 40; } + else if (c >= 100 && c <= 107) { s.bg = c - 100 + 8; } + else if (c === 39) { s.fg = null; } + else if (c === 49) { s.bg = null; } + else if (c === 38 || c === 48) { + var val = null; + if (codes[k + 1] === 5 && k + 2 < codes.length) { val = ansi256(codes[k + 2]); k += 2; } + else if (codes[k + 1] === 2 && k + 4 < codes.length) { + val = 'rgb(' + codes[k + 2] + ',' + codes[k + 3] + ',' + codes[k + 4] + ')'; k += 4; + } else { break; } + if (c === 38) { s.fg = val; } else { s.bg = val; } + } + } + } + + // The span for a run of text in state `s`: a class per named colour (so the theme tokens apply + // in light and dark), an inline colour only for the 256 and rgb ones. + function ansiSpan(s, text) { + var plain = s.fg === null && s.bg === null && !s.b && !s.d && !s.i && !s.u && !s.v; + if (plain) { return document.createTextNode(text); } + var el = document.createElement('span'); + var cls = []; + if (typeof s.fg === 'number') { cls.push('a-fg-' + s.fg); } else if (s.fg) { el.style.color = s.fg; } + if (typeof s.bg === 'number') { cls.push('a-bg-' + s.bg); } else if (s.bg) { el.style.backgroundColor = s.bg; } + if (s.b) { cls.push('a-b'); } + if (s.d) { cls.push('a-d'); } + if (s.i) { cls.push('a-i'); } + if (s.u) { cls.push('a-u'); } + if (s.v) { cls.push('a-v'); } + el.className = cls.join(' '); + el.textContent = text; + return el; + } + + // Renders `raw` (one line) from state `start` into `into`. Returns the state at the line's end. + // A carriage return overwrites the line, so only what follows the last one shows. + function ansiLine(into, raw, start) { + var parts = raw.split('\r'); + var shown = parts[0]; + for (var p = 1; p < parts.length; p++) { if (parts[p] !== '') { shown = parts[p]; } } + var s = ansiCopy(start); + var re = /\u001b\[([0-9;:]*)([@-~])|\u001b/g; + var last = 0, m; + into.textContent = ''; + while ((m = re.exec(shown))) { + if (m.index > last) { into.appendChild(ansiSpan(s, shown.slice(last, m.index))); } + last = re.lastIndex; + if (m[2] === 'm') { + ansiApply(s, m[1] === '' ? [] : m[1].split(/[;:]/).map(function (n) { return parseInt(n, 10) || 0; })); + } + } + if (last < shown.length) { into.appendChild(ansiSpan(s, shown.slice(last))); } + return s; + } + + function logLineEl(n) { + var row = document.createElement('div'); + row.className = 'll'; + row.id = 'L' + n; + var num = document.createElement('a'); + num.className = 'ln'; + num.href = '#L' + n; + num.setAttribute('data-n', n); + num.setAttribute('aria-label', 'L' + n); + var text = document.createElement('span'); + text.className = 'lt'; + row.appendChild(num); + row.appendChild(text); + return row; + } + + // Takes the text the server put in `pre` and starts the log state on it. + function logInit(pre) { + var raw = pre.textContent; + var first = parseInt(pre.getAttribute('data-first') || '1', 10) || 1; + pre.textContent = ''; + pre._ci = { next: first, cur: null, st: ansiState(), stack: [pre], groups: 0, hit: -1 }; + logFeed(pre, raw); + pre.setAttribute('data-ci', '1'); + } + + function logTop(ci) { return ci.stack[ci.stack.length - 1]; } + + // Adds text to the log: completes the open line, then makes a line for each newline. + function logFeed(pre, text) { + var ci = pre._ci; + var pieces = text.split('\n'); + for (var i = 0; i < pieces.length; i++) { + var ends = i < pieces.length - 1; + if (pieces[i] !== '' || ci.cur || ends) { + if (!ci.cur) { + var el = logLineEl(ci.next); + logTop(ci).appendChild(el); + ci.cur = { el: el, raw: '', start: ansiCopy(ci.st) }; + } + ci.cur.raw += pieces[i]; + ansiLine(ci.cur.el.lastChild, ci.cur.raw, ci.cur.start); + } + if (ends) { logDone(pre); } + } + } + + // The open line is complete: carry its colours on, and turn group markers into sections. + function logDone(pre) { + var ci = pre._ci; + var cur = ci.cur; + ci.cur = null; + var n = ci.next++; + ci.st = ansiLine(cur.el.lastChild, cur.raw, cur.start); + var plain = cur.el.lastChild.textContent; + var g = /^::group::(.*)$/.exec(plain); + if (g) { + var det = document.createElement('details'); + det.className = 'lg'; + det.open = true; + var sum = document.createElement('summary'); + sum.className = 'll lgs'; + sum.id = 'L' + n; + var num = cur.el.firstChild; + var title = document.createElement('span'); + title.className = 'lt'; + title.textContent = g[1].trim() || 'group'; + sum.appendChild(num); + sum.appendChild(title); + det.appendChild(sum); + cur.el.replaceWith(det); + ci.stack.push(det); + ci.groups++; + var fold = document.querySelector('[data-log-fold-box]'); + if (fold) { fold.hidden = false; } + } else if (/^::endgroup::\s*$/.test(plain)) { + cur.el.remove(); + if (ci.stack.length > 1) { ci.stack.pop(); } + } + } + + function logOpenAround(el) { + for (var p = el.parentNode; p && p.nodeType === 1; p = p.parentNode) { + if (p.tagName === 'DETAILS') { p.open = true; } + } + } + + // Marks the line of a #L123 fragment and brings it into view. + function logSelect(id, scroll) { + var pre = document.querySelector('[data-live-log]'); + if (!pre) { return false; } + var prev = pre.querySelector('.ll-sel'); + if (prev) { prev.classList.remove('ll-sel'); } + var el = id ? document.getElementById(id) : null; + if (!el || !pre.contains(el)) { return false; } + logOpenAround(el); + el.classList.add('ll-sel'); + if (scroll) { el.scrollIntoView({ block: 'center' }); } + return true; + } + + function logClear(pre) { + Array.prototype.forEach.call(pre.querySelectorAll('mark.lm'), function (mark) { + var parent = mark.parentNode; + parent.replaceChild(document.createTextNode(mark.textContent), mark); + parent.normalize(); + }); + pre._ci.hit = -1; + } + + function logCount(text, none) { + var out = document.querySelector('[data-log-count]'); + if (!out) { return; } + out.textContent = text; + out.classList.toggle('ci-none', !!none); + } + + // Highlights every match of `q` (case-insensitive) in the log and selects the one at `keep`. + function logFind(pre, q, keep) { + logClear(pre); + logCount('', false); + if (!q) { return; } + var needle = q.toLowerCase(); + var total = 0; + var texts = pre.querySelectorAll('.lt'); + for (var t = 0; t < texts.length && total < LOG_MAX_MARKS; t++) { + var walker = document.createTreeWalker(texts[t], NodeFilter.SHOW_TEXT); + var nodes = []; + while (walker.nextNode()) { nodes.push(walker.currentNode); } + for (var k = 0; k < nodes.length && total < LOG_MAX_MARKS; k++) { + var node = nodes[k]; + var lower = node.data.toLowerCase(); + var at = [], from = 0, idx; + while ((idx = lower.indexOf(needle, from)) >= 0 && total + at.length < LOG_MAX_MARKS) { + at.push(idx); + from = idx + needle.length; + } + for (var m = at.length - 1; m >= 0; m--) { + var mid = node.splitText(at[m]); + mid.splitText(needle.length); + var mark = document.createElement('mark'); + mark.className = 'lm'; + mid.parentNode.replaceChild(mark, mid); + mark.appendChild(mid); + } + total += at.length; + } + } + var marks = pre.querySelectorAll('mark.lm'); + if (!marks.length) { + var none = document.querySelector('[data-log-count]'); + logCount(none ? none.getAttribute('data-none') || '' : '', true); + return; + } + logGo(pre, keep >= 0 && keep < marks.length ? keep : 0, false); + } + + // Makes match `i` the current one (wrapping) and scrolls to it. + function logGo(pre, i, scroll) { + var marks = pre.querySelectorAll('mark.lm'); + if (!marks.length) { return; } + i = (i + marks.length) % marks.length; + var was = pre.querySelector('mark.lm-cur'); + if (was) { was.classList.remove('lm-cur'); } + var mark = marks[i]; + mark.classList.add('lm-cur'); + pre._ci.hit = i; + logOpenAround(mark); + if (scroll !== false) { mark.scrollIntoView({ block: 'center', inline: 'nearest' }); } + logCount((i + 1) + ' / ' + marks.length + (marks.length >= LOG_MAX_MARKS ? '+' : ''), false); + } + + var logFindFrame = 0; + function logRefind(pre) { + if (!logQuery || logFindFrame) { return; } + logFindFrame = requestAnimationFrame(function () { + logFindFrame = 0; + if (pre._ci) { logFind(pre, logQuery, pre._ci.hit); } + }); + } + + function syncLog() { + var pre = document.querySelector('[data-live-log]'); + if (!pre || pre.getAttribute('data-ci')) { return; } + logInit(pre); + var input = document.querySelector('[data-log-q]'); + if (input && logQuery) { input.value = logQuery; logFind(pre, logQuery, -1); } + if (location.hash && /^#L\d+$/.test(location.hash)) { logSelect(location.hash.slice(1), true); } + } + + document.addEventListener('input', function (e) { + var input = e.target; + if (!input || !input.hasAttribute || !input.hasAttribute('data-log-q')) { return; } + var pre = document.querySelector('[data-live-log]'); + if (!pre || !pre._ci) { return; } + logQuery = input.value; + logFind(pre, logQuery, -1); + }); + + document.addEventListener('keydown', function (e) { + var input = e.target; + if (!input || !input.hasAttribute || !input.hasAttribute('data-log-q')) { return; } + var pre = document.querySelector('[data-live-log]'); + if (!pre || !pre._ci) { return; } + if (e.key === 'Enter') { + e.preventDefault(); + logGo(pre, pre._ci.hit + (e.shiftKey ? -1 : 1), true); + } else if (e.key === 'Escape') { + input.value = ''; + logQuery = ''; + logFind(pre, '', -1); + } + }); + + document.addEventListener('click', function (e) { + var el = e.target && e.target.closest ? e.target.closest('[data-log-prev],[data-log-next],[data-log-fold],a.ln') : null; + if (!el) { return; } + var pre = document.querySelector('[data-live-log]'); + if (!pre || !pre._ci) { return; } + if (el.classList.contains('ln')) { + e.preventDefault(); + e.stopPropagation(); + var id = el.getAttribute('href').slice(1); + history.replaceState(history.state, '', '#' + id); + logSelect(id, false); + return; + } + e.preventDefault(); + if (el.hasAttribute('data-log-prev')) { logGo(pre, pre._ci.hit - 1, true); } + else if (el.hasAttribute('data-log-next')) { logGo(pre, pre._ci.hit + 1, true); } + else { + var open = el.getAttribute('data-log-fold') === 'open'; + Array.prototype.forEach.call(pre.querySelectorAll('details.lg'), function (d) { d.open = open; }); + } + }, true); + + window.addEventListener('hashchange', function () { + if (/^#L\d+$/.test(location.hash)) { logSelect(location.hash.slice(1), true); } + }); + // Live pages. A run or job page that is not finished marks its wrapper with data-live, the URL of // its event stream. One EventSource follows it. A `changed` event re-fetches the page and swaps it in // with no history entry and the scroll kept. A job page also has a log tail (data-live-log) whose @@ -624,7 +957,8 @@ var pre = document.querySelector('[data-live-log]'); if (!pre || !text) { return; } var atEnd = pre.scrollTop + pre.clientHeight >= pre.scrollHeight - 24; - pre.appendChild(document.createTextNode(text)); + if (pre._ci) { logFeed(pre, text); logRefind(pre); } + else { pre.appendChild(document.createTextNode(text)); } if (atEnd) { pre.scrollTop = pre.scrollHeight; } } @@ -721,6 +1055,7 @@ }); } + syncLog(); followTail(); syncLive(); syncTick(); diff --git a/crates/forge-web/src/ci/schedule.rs b/crates/forge-web/src/ci/schedule.rs index c9d5cfc..685a382 100644 --- a/crates/forge-web/src/ci/schedule.rs +++ b/crates/forge-web/src/ci/schedule.rs @@ -47,6 +47,8 @@ enum Plan { jobs: Vec, config_error: Option, warnings: Vec, + /// `[on] cancel_superseded`: a push cancels the older live runs on its branch. + cancel_superseded: bool, }, } @@ -87,9 +89,10 @@ pub async fn on_ref_update( jobs, config_error, warnings, + cancel_superseded, } = plan_for(loaded, &event)? { - create( + let run = create( state, Request { repo, @@ -105,6 +108,9 @@ pub async fn on_ref_update( &warnings, ) .await?; + if cancel_superseded && trigger == "push" { + cancel_superseded_runs(state, &run).await?; + } } forge_core::Result::Ok(()) } @@ -137,6 +143,7 @@ async fn pull_run( jobs, config_error, warnings, + .. } = plan_for(loaded, &Event::PullRequest)? else { return Ok(()); @@ -190,6 +197,7 @@ pub async fn manual_run( jobs, config_error, warnings, + .. } => { create( state, @@ -249,6 +257,7 @@ async fn create( ) .await?; state.ci_live.bump_repo(&run.repo_id); + state.store.set_run_warnings(&run.id, warnings).await?; note_warnings(state, &run, warnings).await?; if let Some(message) = config_error { let url = format!( @@ -275,6 +284,23 @@ async fn create( Ok(run) } +/// Cancels the queued and running push runs on the branch of `run` that are for older commits. +/// Queued jobs are cancelled at once; running jobs stop at their next heartbeat. +async fn cancel_superseded_runs(state: &AppState, run: &CiRun) -> forge_core::Result<()> { + let older = state + .store + .superseded_candidates(&run.repo_id, &run.git_ref, &run.commit_oid) + .await?; + for old in older.into_iter().filter(|old| old.number < run.number) { + let before = state.store.jobs_for_run(&old.id).await?; + state.store.request_cancel(&old.id).await?; + if let Err(e) = crate::pages::ci_runs::after_change(state, &old.id, &before).await { + tracing::error!(error = %e, run_id = %old.id, "ci: syncing a superseded run failed"); + } + } + Ok(()) +} + /// 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. @@ -342,6 +368,7 @@ fn plan_for(loaded: Loaded, event: &Event<'_>) -> forge_core::Result { jobs: Vec::new(), config_error: Some(message), warnings: Vec::new(), + cancel_superseded: false, }), Loaded::Valid(cfg) => { if !cfg.triggered_by(event) { @@ -351,6 +378,7 @@ fn plan_for(loaded: Loaded, event: &Event<'_>) -> forge_core::Result { jobs: plan_jobs(&cfg)?, config_error: None, warnings: cfg.warnings.clone(), + cancel_superseded: cfg.on.cancel_superseded, }) } } @@ -1026,4 +1054,64 @@ run = "make" assert_eq!(logs, 1); assert!(!path.exists(), "log file is deleted"); } + + const CONFIG_SUPERSEDE: &str = r#" +[on] +push = ["main"] +cancel_superseded = true + +[jobs.build] +image = "alpine:3" +run = "make" +"#; + + #[tokio::test] + async fn a_newer_push_cancels_older_live_runs_when_asked() { + let fx = fixture().await; + push(&fx, &[(CONFIG_PATH, CONFIG_SUPERSEDE)], "refs/heads/main").await; + push(&fx, &[("a.txt", "a")], "refs/heads/main").await; + let store = &fx.state.store; + let first = store.run_by_number(&fx.repo.id, 1).await.unwrap().unwrap(); + let second = store.run_by_number(&fx.repo.id, 2).await.unwrap().unwrap(); + assert_eq!( + first.state, + RunState::Cancelled, + "the older run is cancelled" + ); + assert_eq!(second.state, RunState::Queued, "the newest run keeps going"); + let jobs = store.jobs_for_run(&first.id).await.unwrap(); + assert_eq!(state_of(&jobs, "build"), Some(JobState::Cancelled)); + } + + #[tokio::test] + async fn older_runs_are_kept_without_the_key() { + let fx = fixture().await; + push(&fx, &[(CONFIG_PATH, CONFIG_ONE_JOB)], "refs/heads/main").await; + push(&fx, &[("a.txt", "a")], "refs/heads/main").await; + let first = fx + .state + .store + .run_by_number(&fx.repo.id, 1) + .await + .unwrap() + .unwrap(); + assert_eq!(first.state, RunState::Queued); + } + + #[tokio::test] + async fn ignored_config_keys_are_stored_as_run_warnings() { + let fx = fixture().await; + let config = "[on]\npush = [\"main\"]\nschedule = true\n\n[jobs.build]\nimage = \"alpine:3\"\nrun = \"make\"\n"; + push(&fx, &[(CONFIG_PATH, config)], "refs/heads/main").await; + let run = fx + .state + .store + .run_by_number(&fx.repo.id, 1) + .await + .unwrap() + .unwrap(); + let warnings = fx.state.store.run_warnings(&run.id).await.unwrap(); + assert_eq!(warnings.len(), 1); + assert!(warnings[0].contains("`on.schedule`"), "{warnings:?}"); + } } diff --git a/crates/forge-web/src/i18n/releases_ci.rs b/crates/forge-web/src/i18n/releases_ci.rs index 8b7c21d..cfc92fa 100644 --- a/crates/forge-web/src/i18n/releases_ci.rs +++ b/crates/forge-web/src/i18n/releases_ci.rs @@ -27,6 +27,21 @@ pub enum K { ApproveAndRun, Cancel, Rerun, + RerunFailed, + RerunJob, + DownloadAll, + Download, + ConfigWarnings, + ConfigWarningsHint, + CiNoticeNoFailed, + CiNoticeNotDone, + CiNoticeTooBig, + LogSearch, + LogPrev, + LogNext, + LogNoMatches, + LogCollapseAll, + LogExpandAll, Runs, NoRunsYet, NoRunsHint, @@ -166,6 +181,46 @@ pub fn t(lang: Lang, key: K) -> &'static str { (ApproveAndRun, Tr) => "Onayla ve çalıştır", (Cancel, En) => "Cancel", (Cancel, Tr) => "İptal et", + (RerunFailed, En) => "Re-run failed jobs", + (RerunFailed, Tr) => "Başarısız işleri yeniden çalıştır", + (RerunJob, En) => "Re-run this job", + (RerunJob, Tr) => "Bu işi yeniden çalıştır", + (DownloadAll, En) => "Download all (.zip)", + (DownloadAll, Tr) => "Hepsini indir (.zip)", + (Download, En) => "Download", + (Download, Tr) => "İndir", + (ConfigWarnings, En) => "Config warnings", + (ConfigWarnings, Tr) => "Yapılandırma uyarıları", + (ConfigWarningsHint, En) => { + "These keys of .forge/ci.toml were ignored, so they have no effect on this run." + } + (ConfigWarningsHint, Tr) => { + "Bu .forge/ci.toml anahtarları yok sayıldı, bu çalıştırmayı etkilemiyor." + } + (CiNoticeNoFailed, En) => "This run has no failed or cancelled jobs to run again.", + (CiNoticeNoFailed, Tr) => { + "Bu çalıştırmada yeniden çalıştırılacak başarısız ya da iptal edilmiş iş yok." + } + (CiNoticeNotDone, En) => "That run or job has not finished yet. Nothing was changed.", + (CiNoticeNotDone, Tr) => "Bu çalıştırma ya da iş henüz bitmedi. Hiçbir şey değiştirilmedi.", + (CiNoticeTooBig, En) => { + "The artifacts are too large to download as one file. Download them one by one." + } + (CiNoticeTooBig, Tr) => { + "Yapıtlar tek dosya olarak indirilemeyecek kadar büyük. Tek tek indirin." + } + (LogSearch, En) => "Search the log", + (LogSearch, Tr) => "Günlükte ara", + (LogPrev, En) => "Previous match", + (LogPrev, Tr) => "Önceki eşleşme", + (LogNext, En) => "Next match", + (LogNext, Tr) => "Sonraki eşleşme", + (LogNoMatches, En) => "No matches", + (LogNoMatches, Tr) => "Eşleşme yok", + (LogCollapseAll, En) => "Collapse groups", + (LogCollapseAll, Tr) => "Grupları daralt", + (LogExpandAll, En) => "Expand groups", + (LogExpandAll, Tr) => "Grupları genişlet", (Rerun, En) => "Re-run", (Rerun, Tr) => "Yeniden çalıştır", (Runs, En) => "Runs", @@ -492,6 +547,21 @@ mod tests { K::ApproveAndRun, K::Cancel, K::Rerun, + K::RerunFailed, + K::RerunJob, + K::DownloadAll, + K::Download, + K::ConfigWarnings, + K::ConfigWarningsHint, + K::CiNoticeNoFailed, + K::CiNoticeNotDone, + K::CiNoticeTooBig, + K::LogSearch, + K::LogPrev, + K::LogNext, + K::LogNoMatches, + K::LogCollapseAll, + K::LogExpandAll, K::Runs, K::NoRunsYet, K::NoRunsHint, diff --git a/crates/forge-web/src/pages/ci_job.rs b/crates/forge-web/src/pages/ci_job.rs index 5ca6558..c2f5bde 100644 --- a/crates/forge-web/src/pages/ci_job.rs +++ b/crates/forge-web/src/pages/ci_job.rs @@ -34,7 +34,7 @@ use crate::i18n::{ releases_ci::{self as g, K}, }; use crate::pages::ci_runs::{ - changed_event, events_response, job_href, job_status, run_href, state_text, + can_write, changed_event, events_response, job_href, job_status, run_href, state_text, }; use crate::pages::repo::repo_head; use crate::pages::repo_ctx::{RepoCtx, RepoHead, load_repo}; @@ -78,12 +78,50 @@ fn whole_utf8_len(buf: &[u8]) -> usize { } } -/// The last `TAIL_BYTES` of a log, from a line boundary, whether anything was cut, and the byte -/// offset just past the text shown. A log that does not exist yet is empty. -async fn log_tail(path: &Path) -> Result<(String, bool, u64)> { +/// What the job page shows of a log: the text, whether the start was cut, the byte offset just +/// past the text, and the number of its first line in the whole log. +struct Tail { + text: String, + truncated: bool, + offset: u64, + first_line: u64, +} + +/// The number of newlines in the first `end` bytes of the file, so a cut log keeps true line numbers. +async fn newlines_before(path: &Path, end: u64) -> Result { + let mut file = tokio::fs::File::open(path) + .await + .map_err(forge_core::Error::Io)?; + let mut left = end; + let mut count = 0u64; + let mut buf = vec![0u8; CHUNK_BYTES]; + while left > 0 { + let want = usize::try_from(left).map_or(CHUNK_BYTES, |n| n.min(CHUNK_BYTES)); + let n = file + .read(&mut buf[..want]) + .await + .map_err(forge_core::Error::Io)?; + if n == 0 { + break; + } + count += buf[..n].iter().filter(|byte| **byte == b'\n').count() as u64; + left -= n as u64; + } + Ok(count) +} + +/// The last `TAIL_BYTES` of a log, from a line boundary. A log that does not exist yet is empty. +async fn log_tail(path: &Path) -> Result { let mut file = match tokio::fs::File::open(path).await { Ok(file) => file, - Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok((String::new(), false, 0)), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => { + return Ok(Tail { + text: String::new(), + truncated: false, + offset: 0, + first_line: 1, + }); + } Err(e) => return Err(forge_core::Error::Io(e).into()), }; let len = file.metadata().await.map_err(forge_core::Error::Io)?.len(); @@ -107,11 +145,17 @@ async fn log_tail(path: &Path) -> Result<(String, bool, u64)> { } buf.truncate(whole_utf8_len(&buf)); let offset = start + buf.len() as u64; - Ok(( - String::from_utf8_lossy(&buf).into_owned(), + let first_line = if start > 0 { + newlines_before(path, start).await? + 1 + } else { + 1 + }; + Ok(Tail { + text: String::from_utf8_lossy(&buf).into_owned(), truncated, offset, - )) + first_line, + }) } /// Follows a log: yields what the file holds, then sends new bytes each time the job changes (its @@ -213,6 +257,8 @@ struct JobView { run_href: String, run_number: i64, log_href: String, + /// The POST target that runs the job again and the CSRF token, for a writer once it finished. + rerun: Option<(String, String)>, } /// One artifact row: its link and its size. @@ -231,6 +277,7 @@ async fn job_body( job: JobView, log: String, log_offset: String, + first_line: String, truncated: bool, artifacts: Vec, live: Option, @@ -259,6 +306,14 @@ async fn job_body( if !job.message.is_empty() {

(job.message.as_str())

} + if let Some((action, csrf)) = job.rerun.as_ref() { +
+
+ + +
+
+ }

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

@@ -266,7 +321,17 @@ async fn job_body( if truncated {

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

} -
(log.as_str())
+
+ + + + + +
+
(log.as_str())
if !artifacts.is_empty() {
@@ -292,7 +357,12 @@ async fn job_page(cx: &Cx) -> Result { let lang = i18n::lang(cx, ctx.viewer.as_ref().map(|(user, _)| user)); let state = app_context::(cx); let (job, run) = job_of(state, &ctx, &id).await?; - let (log, truncated, log_offset) = log_tail(&log_path(&state.config.data_dir, &job.id)).await?; + let Tail { + text: log, + truncated, + offset: log_offset, + first_line, + } = log_tail(&log_path(&state.config.data_dir, &job.id)).await?; let artifacts = state .store .list_artifacts(&job.id) @@ -337,12 +407,22 @@ async fn job_page(cx: &Cx) -> Result { run_href: run_href(&title, run.number), run_number: run.number, log_href: format!("{}/log.txt", job_href(&title, &job.id)), + rerun: if job.state.is_terminal() && can_write(&ctx) { + ctx.viewer.as_ref().map(|(_, session)| { + ( + format!("{}/rerun", job_href(&title, &job.id)), + session.csrf_token.clone(), + ) + }) + } else { + None + }, }; let head = ctx.head(state, "ci").await?; let page_title = format!("{title} \u{b7} CI \u{b7} {}", view.name); Ok(view! { shell(title: page_title.as_str(), viewer: ctx.viewer.as_ref(), - job_body(head: head, lang: lang, job: view, log: log, log_offset: log_offset.to_string(), + job_body(head: head, lang: lang, job: view, log: log, log_offset: log_offset.to_string(), first_line: first_line.to_string(), truncated: truncated, artifacts: artifacts, live: live)) }) } diff --git a/crates/forge-web/src/pages/ci_runs.rs b/crates/forge-web/src/pages/ci_runs.rs index e0eb3a3..cdfefc6 100644 --- a/crates/forge-web/src/pages/ci_runs.rs +++ b/crates/forge-web/src/pages/ci_runs.rs @@ -47,6 +47,7 @@ use crate::views::{alert, enc, human_size, now_unix, relative_time, shell, short path_param!(owner); path_param!(repo); path_param!(run_number); +path_param!(job_id); /// Runs per list page. const PER_PAGE: u32 = 25; @@ -54,7 +55,7 @@ const PER_PAGE: u32 = 25; const MAX_PAGE: u32 = 1000; /// Notice words (the only text a `?notice=` query can show), their text and whether they are errors. -const NOTICES: [(&str, K, bool); 8] = [ +const NOTICES: [(&str, K, bool); 11] = [ ("started", K::CiNoticeStarted, false), ("cancelled", K::CiNoticeCancelled, false), ("approved", K::CiNoticeApproved, false), @@ -63,6 +64,9 @@ const NOTICES: [(&str, K, bool); 8] = [ ("not-waiting", K::CiNoticeNotWaiting, true), ("no-branch", K::CiNoticeNoBranch, true), ("no-manual", K::CiNoticeNoManual, true), + ("no-failed", K::CiNoticeNoFailed, true), + ("not-done", K::CiNoticeNotDone, true), + ("too-big", K::CiNoticeTooBig, true), ]; #[derive(Deserialize)] @@ -85,7 +89,7 @@ fn viewer_user(ctx: &RepoCtx) -> Option<&User> { } /// Whether the viewer may change CI runs of this repo. Archived repos refuse. -fn can_write(ctx: &RepoCtx) -> bool { +pub(crate) fn can_write(ctx: &RepoCtx) -> bool { authorize( viewer_user(ctx), &ctx.repo, @@ -270,7 +274,7 @@ async fn run_of(state: &AppState, ctx: &RepoCtx, number: &str) -> Result /// Wakes the job queue and syncs the commit status of every job whose state changed since `before`. /// A job missing from `before` (a fresh run) counts as changed. -async fn after_change(state: &AppState, run_id: &str, before: &[CiJob]) -> Result<()> { +pub(crate) async fn after_change(state: &AppState, run_id: &str, before: &[CiJob]) -> Result<()> { state.ci_waker.notify_waiters(); let Some(run) = state.store.run_by_id(run_id).await? else { return Ok(()); @@ -339,7 +343,7 @@ struct JobLine { href: String, name: String, dot: String, - /// The image and the artifacts with their sizes, joined with a middle dot. + /// The short image name. detail: String, runner: String, duration: String, @@ -353,6 +357,16 @@ struct JobLine { tail: String, /// Whether the row starts with its tail open. expanded: bool, + /// The POST target that runs this job again. Set for a writer, once the job has finished. + rerun: Option, +} + +/// One artifact of the run: its download link, the job that made it, its name and size. +struct ArtifactLine { + href: String, + job: String, + name: String, + size: String, } /// The right column: the selected run, its timeline, its jobs and the log tail. @@ -374,6 +388,13 @@ struct RunDetail { action_base: String, can_approve: bool, can_cancel: bool, + /// A finished run with a failed, errored or cancelled job, for a writer. + can_rerun_failed: bool, + /// The config keys this forge ignored when it made the run. + warnings: Vec, + artifacts: Vec, + /// The zip of every artifact of the run. + zip_href: Option, writer_csrf: Option, gantt: Option, jobs: Vec, @@ -1399,15 +1420,21 @@ async fn run_detail( let jobs = timings_of(state, &run.id, runners, lang).await?; let gantt = (!jobs.is_empty()).then(|| gantt(&jobs, origin_of(run, now), run_end(run, now), now, lang)); + let writer = header.writer_csrf.is_some(); let mut lines = Vec::with_capacity(jobs.len()); + let mut artifacts = Vec::new(); for job in jobs.iter() { - let mut parts = Vec::new(); - if !job.image.is_empty() { - parts.push(job.image.clone()); - } for artifact in state.store.list_artifacts(&job.id).await? { - let size = human_size(lang, u64::try_from(artifact.size).unwrap_or(0)); - parts.push(format!("{} {size}", artifact.name)); + artifacts.push(ArtifactLine { + href: format!( + "{}/artifacts/{}", + job_href(title, &job.id), + enc(&artifact.name) + ), + job: job.name.clone(), + size: human_size(lang, u64::try_from(artifact.size).unwrap_or(0)), + name: artifact.name, + }); } let tail = log_last_lines(&log_path(&state.config.data_dir, &job.id)).await; let preview = match last_line(&tail) { @@ -1424,7 +1451,9 @@ async fn run_detail( href: job_href(title, &job.id), name: job.name.clone(), dot: format!("ci-dot ci-{}", job.state.as_str()), - detail: parts.join(" \u{b7} "), + detail: job.image.clone(), + rerun: (writer && job.state.is_terminal()) + .then(|| format!("{}/rerun", job_href(title, &job.id))), runner: job.runner.clone(), duration: job.duration.clone(), since: (job.finished.is_none() && job.state == JobState::Running) @@ -1432,6 +1461,17 @@ async fn run_detail( .flatten(), }); } + let can_rerun_failed = writer + && run_finished(&run.state) + && jobs.iter().any(|job| { + matches!( + job.state, + JobState::Failure | JobState::Error | JobState::Cancelled + ) + }); + let zip_href = + (!artifacts.is_empty()).then(|| format!("{}/artifacts.zip", run_href(title, run.number))); + let warnings = state.store.run_warnings(&run.id).await?; Ok(RunDetail { number: run.number, title: header.title, @@ -1455,6 +1495,10 @@ async fn run_detail( action_base: run_href(title, run.number), can_approve: header.writer_csrf.is_some() && run.state == RunState::WaitingApproval, can_cancel: header.writer_csrf.is_some() && !run_finished(&run.state), + can_rerun_failed, + warnings, + artifacts, + zip_href, writer_csrf: header.writer_csrf, gantt, jobs: lines, @@ -1585,6 +1629,9 @@ async fn runs_body( if run.can_cancel { action_button(action: format!("{}/cancel", run.action_base), csrf: csrf.clone(), label: g::t(lang, K::Cancel)) } + if run.can_rerun_failed { + action_button(action: format!("{}/rerun-failed", run.action_base), csrf: csrf.clone(), label: g::t(lang, K::RerunFailed)) + } action_button(action: format!("{}/rerun", run.action_base), csrf: csrf.clone(), label: g::t(lang, K::Rerun)) } @@ -1606,6 +1653,17 @@ async fn runs_body( if let Some(message) = run.config_error.as_ref() {
(message.as_str())
} + if !run.warnings.is_empty() { +
+

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

+

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

+
    + for warning in run.warnings.iter() { +
  • (warning.as_str())
  • + } +
+
+ } if let Some(g) = run.gantt.as_ref() {
@@ -1650,6 +1708,7 @@ async fn runs_body( } + if !run.artifacts.is_empty() { +
+

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

+ if let Some(href) = run.zip_href.as_ref() { + (g::t(lang, K::DownloadAll)) + } +
+
    + for artifact in run.artifacts.iter() { +
  • + (artifact.name.as_str()) + (artifact.job.as_str()) " \u{b7} " (artifact.size.as_str()) + (g::t(lang, K::Download)) +
  • + } +
+ } } else {

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

@@ -1971,10 +2054,204 @@ async fn run_rerun(cx: &Cx, Form(form): Form) -> Result { )) } +/// Starts a new run with only the failed, errored and cancelled jobs of a finished run, plus the +/// jobs that depend on them. The specs are the originals. +#[route(POST "/{owner}/{repo}/ci/runs/{run_number}/rerun-failed")] +async fn run_rerun_failed(cx: &Cx, Form(form): Form) -> Result { + let owner = path_param::(cx); + let name = path_param::(cx); + let number = path_param::(cx).to_owned(); + let ctx = load_repo(cx, owner, name).await?; + let (user, _) = require_csrf(cx, &form.csrf).await?; + require_write(&ctx)?; + let state = app_context::(cx); + let run = run_of(state, &ctx, &number).await?; + let href = run_href(&title_of(&ctx), run.number); + match state.store.rerun_failed(&run.id, &user.id).await { + Ok(new_run) => { + after_change(state, &new_run.id, &[]).await?; + Ok(notice_redirect( + &run_href(&title_of(&ctx), new_run.number), + "rerun", + )) + } + Err(forge_core::Error::Conflict(_)) => { + let word = if run_finished(&run.state) { + "no-failed" + } else { + "not-done" + }; + Ok(notice_redirect(&href, word)) + } + Err(e) => Err(e.into()), + } +} + +/// Starts a new run with one finished job and the jobs that depend on it. The specs are the +/// originals. +#[route(POST "/{owner}/{repo}/ci/jobs/{job_id}/rerun")] +async fn job_rerun(cx: &Cx, Form(form): Form) -> Result { + let owner = path_param::(cx); + let name = path_param::(cx); + let id = path_param::(cx).to_owned(); + let ctx = load_repo(cx, owner, name).await?; + let (user, _) = require_csrf(cx, &form.csrf).await?; + require_write(&ctx)?; + let state = app_context::(cx); + let Some(job) = state.store.job_by_id(&id).await? else { + return Err(not_found().into()); + }; + let Some(run) = state.store.run_by_id(&job.run_id).await? else { + return Err(not_found().into()); + }; + if run.repo_id != ctx.repo.id { + return Err(not_found().into()); + } + match state.store.rerun_job(&run.id, &job.id, &user.id).await { + Ok(new_run) => { + after_change(state, &new_run.id, &[]).await?; + Ok(notice_redirect( + &run_href(&title_of(&ctx), new_run.number), + "rerun", + )) + } + Err(forge_core::Error::Conflict(_)) => Ok(notice_redirect( + &run_href(&title_of(&ctx), run.number), + "not-done", + )), + Err(e) => Err(e.into()), + } +} + +/// Most bytes of artifacts the zip download builds in memory. +const MAX_ZIP_BYTES: i64 = 256 * 1024 * 1024; + +/// A zip of `files` (path in the zip, bytes), deflated. Paths use `/`. +fn build_zip(files: Vec<(String, Vec)>) -> std::io::Result> { + use std::io::{Cursor, Write}; + let mut zip = zip::ZipWriter::new(Cursor::new(Vec::new())); + let options = zip::write::SimpleFileOptions::default() + .compression_method(zip::CompressionMethod::Deflated); + for (path, bytes) in files { + zip.start_file(path, options) + .map_err(std::io::Error::other)?; + zip.write_all(&bytes)?; + } + Ok(zip.finish().map_err(std::io::Error::other)?.into_inner()) +} + +/// The path of an artifact inside the run's zip: `/`, with path separators in either +/// part made harmless. +fn zip_path(job: &str, artifact: &str) -> String { + let clean = |part: &str| part.replace(['/', '\\'], "_"); + format!("{}/{}", clean(job), clean(artifact)) +} + +/// Every artifact of a run as one zip, a folder per job. Readers of the repo may download it. +#[route(GET "/{owner}/{repo}/ci/runs/{run_number}/artifacts.zip")] +async fn run_artifacts_zip(cx: &Cx) -> Result { + use futures_util::TryStreamExt; + let owner = path_param::(cx); + let name = path_param::(cx); + let number = path_param::(cx).to_owned(); + let ctx = load_repo(cx, owner, name).await?; + let state = app_context::(cx); + let run = run_of(state, &ctx, &number).await?; + let href = run_href(&title_of(&ctx), run.number); + let mut entries = Vec::new(); + let mut total = 0i64; + for job in state.store.jobs_for_run(&run.id).await? { + for artifact in state.store.list_artifacts(&job.id).await? { + total = total.saturating_add(artifact.size); + entries.push((zip_path(&job.name, &artifact.name), artifact)); + } + } + if entries.is_empty() { + return Err(not_found().into()); + } + if total > MAX_ZIP_BYTES { + return notice_redirect(&href, "too-big").into_response(cx); + } + let mut files = Vec::with_capacity(entries.len()); + for (path, artifact) in entries { + let Some(read) = state + .blobs + .read(&crate::ci::artifact_key(&artifact.id)) + .await? + else { + tracing::error!(artifact_id = %artifact.id, "ci: artifact row without a blob"); + continue; + }; + let chunks: Vec = read + .stream + .try_collect() + .await + .map_err(forge_core::Error::Io)?; + files.push((path, chunks.concat())); + } + let zipped = tokio::task::spawn_blocking(move || build_zip(files)) + .await + .map_err(|e| forge_core::Error::Io(std::io::Error::other(e)))? + .map_err(forge_core::Error::Io)?; + let mut res = Response::new(topcoat::router::Body::from(zipped)); + let headers = res.headers_mut(); + headers.insert( + http::header::CONTENT_TYPE, + HeaderValue::from_static("application/zip"), + ); + let file = format!("{}-run-{}-artifacts.zip", ctx.repo.name, run.number); + if let Ok(value) = HeaderValue::from_str(&format!( + "attachment; filename=\"{}\"", + file.chars() + .map(|c| if c.is_ascii_graphic() && c != '"' && c != '\\' { + c + } else { + '_' + }) + .collect::() + )) { + headers.insert(http::header::CONTENT_DISPOSITION, value); + } + headers.insert( + http::header::HeaderName::from_static("x-content-type-options"), + HeaderValue::from_static("nosniff"), + ); + headers.insert( + http::header::HeaderName::from_static("cache-control"), + HeaderValue::from_static("private, no-cache"), + ); + Ok(res) +} + #[cfg(test)] mod tests { use super::*; + #[test] + fn zip_paths_keep_one_folder_per_job() { + assert_eq!(zip_path("build", "app.tar"), "build/app.tar"); + assert_eq!(zip_path("a/b", "..\\x"), "a_b/.._x"); + } + + #[test] + fn the_zip_holds_each_file_under_its_path() { + use std::io::{Cursor, Read}; + let bytes = build_zip(vec![ + ("build/a.txt".into(), b"hello".to_vec()), + ("test/b.txt".into(), b"world".to_vec()), + ]) + .unwrap(); + let mut archive = zip::ZipArchive::new(Cursor::new(bytes)).unwrap(); + assert_eq!(archive.len(), 2); + let mut text = String::new(); + archive + .by_name("test/b.txt") + .unwrap() + .read_to_string(&mut text) + .unwrap(); + assert_eq!(text, "world"); + } + /// A job timing with the given times, on runner `vps-1`. fn timing( name: &str, diff --git a/crates/forge-web/src/pages/ci_tests.rs b/crates/forge-web/src/pages/ci_tests.rs index 608d9c0..fdaeec1 100644 --- a/crates/forge-web/src/pages/ci_tests.rs +++ b/crates/forge-web/src/pages/ci_tests.rs @@ -1394,6 +1394,251 @@ async fn running_runs_carry_ticker_attributes_and_finished_ones_do_not() { ); } +#[tokio::test] +async fn rerun_failed_and_rerun_job_start_partial_runs() { + let dir = tempfile::tempdir().expect("tempdir"); + let fx = fixture(dir.path()).await; + let run = run_with(&fx, &["build", "lint"], false).await; + let run_url = format!("{RUN_BASE}/runs/{}", run.number); + let writer = cookie_for("bob-token"); + + // A live run offers neither control and refuses the request. + let page = get(&fx.app, &run_url, Some(&writer)).await.text(); + assert!(!page.contains("Re-run failed jobs")); + let early = post(&fx.app, &format!("{run_url}/rerun-failed"), &writer, &[]).await; + assert!( + early + .location() + .unwrap_or_default() + .ends_with("?notice=not-done") + ); + + let cancelled = post(&fx.app, &format!("{run_url}/cancel"), &writer, &[]).await; + assert_eq!(cancelled.status, 303); + let page = get(&fx.app, &run_url, Some(&writer)).await.text(); + assert!(page.contains("Re-run failed jobs"), "cancelled jobs count"); + let reader = get(&fx.app, &run_url, Some(&cookie_for("dave-token"))).await; + assert!(!reader.text().contains("Re-run failed jobs")); + let refused = post( + &fx.app, + &format!("{run_url}/rerun-failed"), + &cookie_for("dave-token"), + &[], + ) + .await; + assert_eq!(refused.status, 403); + + let again = post(&fx.app, &format!("{run_url}/rerun-failed"), &writer, &[]).await; + assert_eq!( + again.location().as_deref(), + Some("/tahinli/proj/ci/runs/2?notice=rerun") + ); + let second = fx + .store + .run_by_number(&fx.repo.id, 2) + .await + .unwrap() + .unwrap(); + assert_eq!(fx.store.jobs_for_run(&second.id).await.unwrap().len(), 2); + + // One job: it must have finished, and the request needs Write. + let job = job_of(&fx, &run).await; + let single = post( + &fx.app, + &format!("/tahinli/proj/ci/jobs/{}/rerun", job.id), + &writer, + &[], + ) + .await; + assert_eq!( + single.location().as_deref(), + Some("/tahinli/proj/ci/runs/3?notice=rerun") + ); + let third = fx + .store + .run_by_number(&fx.repo.id, 3) + .await + .unwrap() + .unwrap(); + assert_eq!(fx.store.jobs_for_run(&third.id).await.unwrap().len(), 1); + let live = job_of(&fx, &third).await; + let early = post( + &fx.app, + &format!("/tahinli/proj/ci/jobs/{}/rerun", live.id), + &writer, + &[], + ) + .await; + assert!( + early + .location() + .unwrap_or_default() + .ends_with("?notice=not-done") + ); + let refused = post( + &fx.app, + &format!("/tahinli/proj/ci/jobs/{}/rerun", job.id), + &cookie_for("dave-token"), + &[], + ) + .await; + assert_eq!(refused.status, 403); + let job_page = get( + &fx.app, + &format!("/tahinli/proj/ci/jobs/{}", job.id), + Some(&writer), + ) + .await + .text(); + assert!(job_page.contains("Re-run this job")); +} + +#[tokio::test] +async fn a_run_with_no_failed_jobs_has_nothing_to_rerun() { + let dir = tempfile::tempdir().expect("tempdir"); + let fx = fixture(dir.path()).await; + let run = run_with(&fx, &["build"], false).await; + finish_job(&fx).await; + let run_url = format!("{RUN_BASE}/runs/{}", run.number); + let writer = cookie_for("bob-token"); + let page = get(&fx.app, &run_url, Some(&writer)).await.text(); + assert!(!page.contains("Re-run failed jobs")); + let none = post(&fx.app, &format!("{run_url}/rerun-failed"), &writer, &[]).await; + assert!( + none.location() + .unwrap_or_default() + .ends_with("?notice=no-failed") + ); +} + +#[tokio::test] +async fn run_artifacts_list_and_zip() { + let dir = tempfile::tempdir().expect("tempdir"); + let fx = fixture(dir.path()).await; + let run = run_with(&fx, &["build", "test"], false).await; + let jobs = fx.store.jobs_for_run(&run.id).await.unwrap(); + for (job, name, payload) in [ + (&jobs[0], "report.txt", &b"alpha"[..]), + (&jobs[1], "out.bin", &b"beta"[..]), + ] { + let artifact = fx + .store + .add_artifact(&job.id, name, payload.len() as i64, SHA) + .await + .expect("artifact row"); + let mut writer = fx + .blobs + .begin(&artifact_key(&artifact.id), 1024) + .await + .expect("begin"); + writer.push(payload).await.expect("push"); + writer.finish().await.expect("finish"); + } + let reader = cookie_for("dave-token"); + let run_url = format!("{RUN_BASE}/runs/{}", run.number); + let page = get(&fx.app, &run_url, Some(&reader)).await.text(); + assert!(page.contains("Download all (.zip)")); + assert!(page.contains("artifacts.zip")); + assert!(page.contains("report.txt") && page.contains("out.bin")); + + let res = get(&fx.app, &format!("{run_url}/artifacts.zip"), Some(&reader)).await; + assert_eq!(res.status, 200); + assert_eq!( + res.headers + .get("content-type") + .and_then(|v| v.to_str().ok()), + Some("application/zip") + ); + let mut archive = zip::ZipArchive::new(std::io::Cursor::new(res.body.clone())).expect("zip"); + assert_eq!(archive.len(), 2); + let mut text = String::new(); + std::io::Read::read_to_string( + &mut archive.by_name("build/report.txt").expect("entry"), + &mut text, + ) + .expect("read"); + assert_eq!(text, "alpha"); + + let outsider = get( + &fx.app, + &format!("{run_url}/artifacts.zip"), + Some(&cookie_for("carol-token")), + ) + .await; + assert_eq!(outsider.status, 404, "a private repo stays private"); + let empty = run_with(&fx, &["lint"], false).await; + let none = get( + &fx.app, + &format!("{RUN_BASE}/runs/{}/artifacts.zip", empty.number), + Some(&reader), + ) + .await; + assert_eq!(none.status, 404); +} + +#[tokio::test] +async fn config_warnings_show_on_the_run_page() { + let dir = tempfile::tempdir().expect("tempdir"); + let fx = fixture(dir.path()).await; + let run = run_with(&fx, &["build"], false).await; + let run_url = format!("{RUN_BASE}/runs/{}", run.number); + let cookie = cookie_for("dave-token"); + assert!( + !get(&fx.app, &run_url, Some(&cookie)) + .await + .text() + .contains("ci-warnings") + ); + fx.store + .set_run_warnings( + &run.id, + &[ + "unknown key `on.schedule` ignored: this forge may be older than your ci.toml" + .to_owned(), + ], + ) + .await + .expect("warnings"); + let page = get(&fx.app, &run_url, Some(&cookie)).await.text(); + assert!(page.contains("ci-warnings")); + assert!(page.contains("on.schedule")); + assert!(page.contains("Config warnings")); +} + +#[tokio::test] +async fn job_page_log_carries_the_first_line_number_of_a_cut_log() { + let dir = tempfile::tempdir().expect("tempdir"); + let fx = fixture(dir.path()).await; + let run = run_with(&fx, &["build"], false).await; + let job = job_of(&fx, &run).await; + let path = log_path(&fx.data_dir, &job.id); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + let mut file = std::fs::File::create(&path).unwrap(); + // 11000 lines of 100 bytes cut the 512 KiB tail somewhere past line 5000. + for n in 0..11_000 { + writeln!(file, "{n:0>98}").unwrap(); + } + drop(file); + let page = get( + &fx.app, + &format!("/tahinli/proj/ci/jobs/{}", job.id), + Some(&cookie_for("dave-token")), + ) + .await + .text(); + let marker = "data-first=\""; + let at = page.find(marker).expect("data-first") + marker.len(); + let first: u64 = page[at..].split('"').next().unwrap().parse().unwrap(); + assert!(first > 5000, "first line {first}"); + let after = &page[at..]; + let text = &after[after.find('>').unwrap() + 1..]; + let expected = format!("{:0>98}", first - 1); + assert!( + text.starts_with(&expected), + "the tail starts at its own line number" + ); +} + /// The run page previews the last log line of every running job in its row, and a failed job's row /// starts expanded. #[tokio::test] diff --git a/docs/ci.md b/docs/ci.md index 5239a60..6396b2e 100644 --- a/docs/ci.md +++ b/docs/ci.md @@ -16,7 +16,9 @@ supported as an option (`executor = "podman"`). The file is limited to 64 KiB. Parsing is forward-compatible: an unknown key at any level (top level, `[on]`, `[jobs.]`, `[release]`) is ignored, not rejected, so a `ci.toml` that uses a newer feature still runs on an -older forge. The run's jobs get a `[forge] warning: unknown key ...` line at the start of their logs. Known keys +older forge. The run page shows the ignored keys in a warning banner, and the run's jobs get a +`[forge] warning: unknown key ...` line at the start of their logs. For example `on.schedule` is not supported +and shows up this way. Known keys keep full validation: their types, globs, limits and other checks still make the file an error. A file with a parse error still creates a run, in state `error`, with the message shown on the run page and a `ci/config` status set to `error`. @@ -35,6 +37,7 @@ page and a `ci/config` status set to `error`. | `tags` | array of string | `[]` | Tag globs. A push of a matching `refs/tags/*` starts a run. | | `pull_request` | bool | `false` | Start a run when a pull request is opened, updated or reopened. The config is read at the **head** commit. | | `manual` | bool | `true` | Writers can start a run on an existing branch from the CI tab. | +| `cancel_superseded` | bool | `false` | A push to a branch cancels the queued and running runs for older commits on that branch (see [Superseded runs](#superseded-runs)). | ### `[jobs.]` @@ -112,6 +115,44 @@ blocked jobs become `cancelled`, and jobs that are already running are told to s heartbeat, so the runner aborts them and they end `cancelled`. The run ends `failure`, so no release is published and no self-update happens. A long `build` does not keep compiling after `test` fails. +### Superseded runs + +With `[on] cancel_superseded = true`, a push to a branch cancels the runs that are still queued or running for +older commits of the **same branch** when its own run is created. Queued and blocked jobs become `cancelled` +at once and running jobs are told to stop through their heartbeat, as with the run's Cancel button. Only runs +that were started by a push are cancelled: manual, tag and pull request runs are left alone, and so are runs +that have already finished. The key is read from the new commit's `ci.toml`, and it is off by default. + +### Re-running + +A finished run has three re-run controls on its page (writers only): + +- **Re-run** creates a new run with every job of the original run. +- **Re-run failed jobs** creates a new run with only the jobs that ended `failure`, `error` or `cancelled`, plus every + job that depends on them, directly or not. Jobs that succeeded are not run again. A `needs` entry that points at a + job that is not in the new run is dropped, since that job already succeeded. +- **Re-run this job** (on the job page, and on each job row of the run page) creates a new run with that finished + job and the jobs that depend on it. + +A re-run always uses the **original specs**: the same commit, ref, trigger and job definitions as stored when the +original run was created. It does not read `ci.toml` again, so an edit to the file does not change a re-run. The +config warnings of the original run are carried over. To pick up a changed `ci.toml`, push a commit or start a +manual run. + +### Artifacts + +The run page lists the artifacts of all its jobs, each with a download link, and **Download all (.zip)** which +serves every artifact in one zip with a folder per job (`/`). Anyone who can read the repo can +download them. A run whose artifacts add up to more than 256 MiB offers the single downloads only. + +### Job logs + +The job page renders the log with ANSI colours (the sixteen named colours follow the theme, so they read in light +and dark), numbered lines with `#L123` anchors, and a search box (Enter and Shift+Enter move between matches). +A line that is exactly `::group::name` starts a collapsible section and `::endgroup::` ends it. The markers +themselves are not shown. Streaming keeps working while the job runs. The page shows the last 512 KiB; the +full log is at `log.txt`. + ### Releases A `[release]` table publishes a release from a tag run. It needs at least one glob in `[on] tags`. diff --git a/style/main.scss b/style/main.scss index b8ca900..358b5fd 100644 --- a/style/main.scss +++ b/style/main.scss @@ -3958,6 +3958,275 @@ span.reaction { padding-left: 20px; } +// A small button for the run page's row actions and the log toolbar. +.button.ci-mini, +button.ci-mini { + height: 28px; + padding: 0 10px; + font-size: 0.8125rem; +} + +// The config keys this forge ignored, above the timeline. +.ci-warnings { + margin: 8px 0 12px; + padding: 10px 12px; + border: 1px solid var(--warning); + border-radius: var(--radius-md); + background: color-mix(in srgb, var(--warning) 10%, transparent); + + p { + margin: 0; + } + + ul { + margin: 6px 0 0; + padding-left: 18px; + font-size: 0.8125rem; + overflow-wrap: anywhere; + } +} + +.ci-warnings-title { + font-weight: 600; + color: var(--warning); +} + +// The run's artifacts: a heading with "download all", then one row per file. +.ci-art-head { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: 8px 12px; + margin: 20px 0 8px; +} + +.ci-art-title { + margin: 0; + font-size: 0.75rem; + font-weight: 600; + letter-spacing: 0.06em; + text-transform: uppercase; + color: var(--muted); +} + +.ci-art-list { + margin: 0; + padding: 0; + list-style: none; + border-top: 1px solid var(--border); + + li { + display: grid; + grid-template-columns: minmax(0, 1fr) auto auto; + gap: 12px; + align-items: center; + padding: 8px 6px; + border-bottom: 1px solid var(--border); + font-size: 0.875rem; + } +} + +.ci-art-name { + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + font-family: var(--mono); + font-size: 0.8125rem; +} + +// A job row: the link takes the width, the re-run button sits at its right. +.ci-job-item { + display: flex; + align-items: center; + gap: 8px; + + .ci-job-line { + flex: 1; + min-width: 0; + } +} + +.ci-job-rerun { + flex: none; +} + +// The job log: search bar, then numbered lines. Colours come from the theme tokens, so they read in +// light and dark. A `.ll` is one line (`.ln` its number, `.lt` its text); a `details.lg` is a +// `::group::` section. +.ci-logbar { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px; + margin: 0 0 8px; +} + +.ci-logsearch { + flex: 1 1 180px; + max-width: 320px; + height: 28px; + min-width: 0; + padding: 0 10px; + font-size: 0.8125rem; +} + +.ci-logcount { + min-width: 5ch; + font-size: 0.8125rem; + font-family: var(--mono); + color: var(--muted); + + &.ci-none { + color: var(--danger); + } +} + +.ci-logfold { + display: inline-flex; + gap: 8px; + margin-left: auto; + + &[hidden] { + display: none; + } +} + +.ci-log { + font-family: var(--mono); + line-height: 1.5; + padding: 8px 0; + background: var(--code-bg); + border-radius: var(--radius-md); + + .ll { + display: flex; + padding-right: 12px; + + &:hover { + background: var(--surface-2); + } + + &:target, + &.ll-sel { + background: var(--row-target); + } + } + + .ln { + flex: none; + box-sizing: border-box; + width: 6ch; + padding-right: 12px; + text-align: right; + color: var(--muted); + text-decoration: none; + user-select: none; + + &::before { + content: attr(data-n); + } + + &:hover { + color: var(--text); + } + } + + .lt { + flex: 1; + min-width: 0; + white-space: pre-wrap; + word-break: break-word; + + &:empty::after { + content: "\200b"; + } + } + + details.lg > summary { + cursor: pointer; + font-weight: 600; + color: var(--text); + list-style: none; + + &::-webkit-details-marker { + display: none; + } + + .lt::before { + content: "\25BE\00a0"; + color: var(--muted); + } + } + + details.lg:not([open]) > summary .lt::before { + content: "\25B8\00a0"; + } + + mark.lm { + background: color-mix(in srgb, var(--warning) 35%, transparent); + color: inherit; + border-radius: 2px; + + &.lm-cur { + background: var(--warning); + color: var(--bg); + } + } + + // ANSI colours: the sixteen named ones map to the theme tokens. + .a-b { + font-weight: 700; + } + + .a-d { + opacity: 0.7; + } + + .a-i { + font-style: italic; + } + + .a-u { + text-decoration: underline; + } + + .a-v { + background: var(--text); + color: var(--code-bg); + } +} + +$ansi-colours: ( + 0: var(--muted), + 1: var(--danger), + 2: var(--ok), + 3: var(--warn), + 4: var(--accent), + 5: var(--important), + 6: var(--tip), + 7: var(--text-2), +); + +@each $n, $c in $ansi-colours { + .ci-log .a-fg-#{$n} { + color: $c; + } + + .ci-log .a-bg-#{$n} { + background: color-mix(in srgb, #{$c} 30%, transparent); + } + + .ci-log .a-fg-#{$n + 8} { + color: color-mix(in srgb, #{$c} 70%, var(--text)); + } + + .ci-log .a-bg-#{$n + 8} { + background: color-mix(in srgb, #{$c} 45%, transparent); + } +} + // Admin runners table: name and labels take the slack, the rest size to their content, and the // actions sit flush right. State reuses the `.ci-state` pill; a disabled runner is muted. .table.runners {