Files
radicle-native-ci/src/runlog.rs
T
2024-03-31 14:51:56 +03:00

224 lines
6.5 KiB
Rust

use std::path::{Path, PathBuf};
use html_page::{Document, Element, Tag};
use radicle_ci_broker::msg::{Oid, RepoId};
use crate::runspec::RunSpecError;
#[derive(Debug, Default)]
pub struct RunLog {
filename: PathBuf,
title: Option<String>,
rid: Option<RepoId>,
commit: Option<Oid>,
commands: Vec<Command>,
timeout: bool,
runspec_error: Option<String>,
}
impl RunLog {
pub fn new(filename: &Path) -> Self {
Self {
filename: filename.into(),
..Default::default()
}
}
pub fn title(&mut self, title: &str) {
self.title = Some(title.into());
}
pub fn rid(&mut self, rid: RepoId) {
self.rid = Some(rid);
}
pub fn commit(&mut self, commit: Oid) {
self.commit = Some(commit);
}
pub fn all_commands_succeeded(&self) -> bool {
self.commands.iter().all(|c| c.exit == 0) && !self.timeout && self.runspec_error.is_none()
}
pub fn runspec(&mut self, e: &RunSpecError) {
self.runspec_error = Some(format!("{}", e));
}
pub fn runcmd(&mut self, argv: &[&str], cwd: &Path, exit: i32, stdout: &[u8], stderr: &[u8]) {
self.commands.push(Command {
argv: argv.iter().map(|a| a.to_string()).collect(),
cwd: cwd.into(),
exit,
stdout: stdout.to_vec(),
stderr: stderr.to_vec(),
});
}
pub fn command_timed_out(&mut self) {
self.timeout = true;
}
pub fn write(&self) -> Result<(), RunLogError> {
let title = self.title.as_ref().ok_or(RunLogError::Missing("title"))?;
let rid = self.rid.as_ref().ok_or(RunLogError::Missing("rid"))?;
let commit = self.commit.as_ref().ok_or(RunLogError::Missing("commit"))?;
let mut doc = Document::default();
doc.push_to_head(&Element::new(Tag::Title).with_text(title));
doc.push_to_body(&Element::new(Tag::H1).with_text(title));
let mut ul = Element::new(Tag::Ul);
ul.push_child(
&Element::new(Tag::Li)
.with_text("Repository id: ")
.with_child(Element::new(Tag::Code).with_text(&rid.to_string())),
);
ul.push_child(
&Element::new(Tag::Li)
.with_text("Commit: ")
.with_child(Element::new(Tag::Code).with_text(&commit.to_string())),
);
ul.push_child(
&Element::new(Tag::Li)
.with_text("Result: ")
.with_child(Element::new(Tag::B).with_text(self.result())),
);
doc.push_to_body(&ul);
if let Some(e) = &self.runspec_error {
let error = Element::new(Tag::P)
.with_text("Failed to load .radicle/native.yaml: ")
.with_child(Element::new(Tag::Code).with_text(e));
doc.push_to_body(&error);
}
if self.timeout {
let timeout = Element::new(Tag::P).with_text("Last command timed out");
doc.push_to_body(&timeout);
}
let mut toc = ToC::default();
let mut body = Element::new(Tag::Div);
for cmd in self.commands.iter() {
cmd.format(&mut body, &mut toc);
}
doc.push_to_body(&toc.as_html());
doc.push_to_body(&body);
let html = format!("{}", doc);
std::fs::write(&self.filename, html.as_bytes())
.map_err(|e| RunLogError::Write(self.filename.clone(), e))?;
Ok(())
}
fn result(&self) -> &'static str {
if self.all_commands_succeeded() {
"SUCCESS"
} else {
"FAILURE"
}
}
}
#[derive(Debug)]
struct Command {
argv: Vec<String>,
cwd: PathBuf,
exit: i32,
stdout: Vec<u8>,
stderr: Vec<u8>,
}
impl Command {
fn command(&self) -> String {
self.argv.as_slice().join(" ")
}
fn format(&self, body: &mut Element, toc: &mut ToC) {
body.push_child(
&toc.push(
Element::new(Tag::Span)
.with_text("Run: ")
.with_child(Element::new(Tag::Code).with_text(&self.command())),
),
);
body.push_child(&Element::new(Tag::P).with_text("Command arguments:"));
let mut ul = Element::new(Tag::Ul);
for arg in self.argv.iter() {
ul.push_child(
&Element::new(Tag::Li)
.with_child(Element::new(Tag::Code).with_text(&format!("{:?}", arg))),
);
}
body.push_child(&ul);
body.push_child(
&Element::new(Tag::P)
.with_text("In directory: ")
.with_child(Element::new(Tag::Code).with_text(&format!("{}", self.cwd.display()))),
);
body.push_child(&Element::new(Tag::P).with_text(&format!("Exit code: {}", self.exit)));
self.output(body, "Stdout:", &self.stdout);
self.output(body, "Stderr:", &self.stderr);
}
fn output(&self, body: &mut Element, stream: &str, data: &[u8]) {
if !data.is_empty() {
body.push_child(&Element::new(Tag::P).with_text(stream));
body.push_child(
&Element::new(Tag::Blockquote)
.with_child(Element::new(Tag::Pre).with_text(&String::from_utf8_lossy(data))),
);
}
}
}
#[derive(Debug, Default)]
struct ToC {
counter: usize,
headings: Vec<(String, Element)>,
}
impl ToC {
fn push(&mut self, content: Element) -> Element {
self.counter += 1;
let anchor = format!("h{}", self.counter);
self.headings.push((anchor.clone(), content.clone()));
Element::new(Tag::H2)
.with_attribute("id", &format!("h{}", self.counter))
.with_child(content)
}
fn as_html(&self) -> Element {
let mut toc =
Element::new(Tag::Div).with_child(Element::new(Tag::H2).with_text("Table of contents"));
let mut list = Element::new(Tag::Ul);
for (anchor, content) in self.headings.iter() {
let entry = Element::new(Tag::Li).with_child(
Element::new(Tag::A)
.with_attribute("href", &format!("#{anchor}"))
.with_child(content.clone()),
);
list.push_child(&entry);
}
toc.push_child(&list);
toc
}
}
#[derive(Debug, thiserror::Error)]
pub enum RunLogError {
#[error("programming error: missing field for run log {0}")]
Missing(&'static str),
#[error("failed to write HTML run log to {0}")]
Write(PathBuf, #[source] std::io::Error),
}