use topcoat::Result; use topcoat::context::Cx; use topcoat::view::{View, component, view}; use crate::ci::log_path; use crate::i18n::{ Lang, releases_ci::{self as g, K}, }; use crate::pages::ci_job::log_tail; use crate::pages::ci_runs::job_href; use crate::state::AppState; use forge_ci::steps::strip_ansi; const WINDOW: usize = 30; const PATTERNS: [&str; 7] = [ "error:", "error[E", "FAILED", "panicked at", "npm ERR!", "fatal:", "out of memory killer killed", ]; fn first_error(lines: &[String]) -> Option { lines .iter() .position(|line| PATTERNS.iter().any(|pattern| line.contains(pattern))) } #[derive(Clone)] pub struct FailFirst { job_name: String, job_href: String, message: String, has_log: bool, line_no: Option, error: Option, place: Option, } impl FailFirst { pub fn line_no(&self) -> Option { self.line_no } } fn place_in(lines: &[String]) -> Option { lines .iter() .flat_map(|line| line.split_whitespace()) .find_map(|word| { let word = word.trim_matches(|c: char| matches!(c, '(' | ')' | ',')); let mut parts = word.split(':'); let file = parts.next()?; let line = parts.next()?; (file.contains('.') && !file.contains("::") && !line.is_empty() && line.bytes().all(|b| b.is_ascii_digit())) .then(|| format!("{}:{line}", file.rsplit('/').next().unwrap_or(file))) }) } pub async fn read( state: &AppState, title: &str, job_id: &str, job_name: &str, message: &str, ) -> Result { let tail = log_tail(&log_path(&state.config.data_dir, job_id)).await?; let mut all: Vec = tail.text.lines().map(strip_ansi).collect(); while all.last().is_some_and(|line| line.trim().is_empty()) { all.pop(); } let hit = first_error(&all); let reason = hit.map(|index| { all[index..] .iter() .take(WINDOW) .find(|line| line.trim_start().starts_with("error")) .unwrap_or(&all[index]) .trim() .to_owned() }); let place = hit.and_then(|index| place_in(&all[index..(index + WINDOW).min(all.len())])); Ok(FailFirst { job_name: job_name.to_owned(), job_href: job_href(title, job_id), message: message.to_owned(), has_log: !all.is_empty(), line_no: hit.map(|index| tail.first_line + index as u64), error: reason, place, }) } #[component] pub async fn fail_first_block(cx: &Cx, lang: Lang, fail: FailFirst) -> Result { let line_href = fail.line_no.map(|no| format!("{}#L{no}", fail.job_href)); let why = if fail.message.is_empty() { fail.error.clone().unwrap_or_else(|| fail.job_name.clone()) } else { fail.message.clone() }; Ok(view! {
(why.as_str()) if let Some(place) = fail.place.as_ref() { (place.as_str()) } if let Some(href) = line_href.as_ref() { (g::t(lang, K::FailOpenLog)) } if !fail.has_log { (g::t(lang, K::FailNoLog)) } else if line_href.is_none() { (g::t(lang, K::FailNoError)) }
}) }