thirdshift 0.34.0

Turn a GitHub issue into a ready-for-review pull request, unattended
//! Stateless Activity log formatting and file effects. The recording owner
//! decides starts, endings, shared skip history and warning suppression.

use std::fmt::{self, Display};
use std::fs::{self, File, OpenOptions};
use std::io::{Read, Seek, SeekFrom};
use std::path::Path;

use anyhow::{Context, Result};

use super::Pass;
use super::effects::Tail;

pub(super) const FILE: &str = "activity.log";
pub(super) const TIME_FORMAT: &str = "%Y-%m-%d %H:%M:%S";
pub(super) const TAIL: u64 = 64 * 1024;
const TIME_FORMAT_LENGTH: usize = "2026-10-03 10:41:01".len();

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum Kind {
    Run,
    SpecRun,
    ScoringRun,
    ReviewRun,
    FixRun,
    ReleaseRun,
    BaseCi,
    TriageRun,
    Experiment,
    Process,
    Pass(Pass),
    /// A warning about the User config.
    UserConfig,
}

impl Display for Kind {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Kind::Run => f.write_str("Run"),
            Kind::SpecRun => f.write_str("Spec run"),
            Kind::ScoringRun => f.write_str("Scoring run"),
            Kind::ReviewRun => f.write_str("Review run"),
            Kind::FixRun => f.write_str("Fix run"),
            Kind::ReleaseRun => f.write_str("Release run"),
            Kind::BaseCi => f.write_str("Base branch CI step"),
            Kind::TriageRun => f.write_str("Triage run"),
            Kind::Experiment => f.write_str("Experiment"),
            Kind::Process => f.write_str("Process"),
            Kind::Pass(pass) => pass.fmt(f),
            Kind::UserConfig => f.write_str("User config"),
        }
    }
}

pub(super) fn open(path: &Path) -> Result<File> {
    if let Some(dir) = path.parent() {
        fs::create_dir_all(dir).with_context(|| format!("could not create {}", dir.display()))?;
    }
    OpenOptions::new()
        .read(true)
        .append(true)
        .create(true)
        .open(path)
        .with_context(|| format!("could not open {}", path.display()))
}

/// Raw bytes at the end of the file. The owner discards a cut first line.
pub(super) fn tail(path: &Path, limit: u64) -> Result<Tail> {
    let mut file = open(path)?;
    let mut read = || -> std::io::Result<Tail> {
        let from = file.metadata()?.len().saturating_sub(limit);
        file.seek(SeekFrom::Start(from))?;
        let mut bytes = Vec::new();
        file.read_to_end(&mut bytes)?;
        Ok(Tail { from, bytes })
    };
    read().with_context(|| format!("could not read {}", path.display()))
}

/// The time and unstamped text of the last line of `kind` in the tail.
pub(super) fn last_of(tail: &str, kind: Kind) -> Option<(&str, &str)> {
    let kind = kind.to_string();
    lines(tail).rev().find(|(_, text)| {
        text.strip_prefix(&kind)
            .is_some_and(|rest| rest.starts_with(' ') || rest.starts_with(':'))
    })
}

/// The time and unstamped text of the last line about Process `name` in
/// the tail: a skip, or a start, Stop or end, so a run clears the last skip
/// reason. Compare the complete Process name: names can contain spaces and
/// colons.
pub(super) fn last_of_process<'a>(tail: &'a str, name: &str) -> Option<(&'a str, &'a str)> {
    let subject = format!("Process {name} ");
    lines(tail).rev().find(|(_, text)| {
        text.strip_prefix(&subject).is_some_and(|rest| {
            ["skipped: ", "started: ", "ended: ", "stopped "]
                .iter()
                .any(|word| rest.starts_with(word))
        })
    })
}

fn lines(tail: &str) -> impl DoubleEndedIterator<Item = (&str, &str)> {
    tail.lines().filter_map(|line| {
        Some((
            line.get(..TIME_FORMAT_LENGTH)?,
            line.get(TIME_FORMAT_LENGTH + 1..)?,
        ))
    })
}