diff options
Diffstat (limited to 'mingling_ci/src')
| -rw-r--r-- | mingling_ci/src/bin/ci.rs | 46 | ||||
| -rw-r--r-- | mingling_ci/src/cmd.rs | 2 | ||||
| -rw-r--r-- | mingling_ci/src/cmd/cmd_report_collect.rs | 293 | ||||
| -rw-r--r-- | mingling_ci/src/cmd/cmd_show_manifests.rs | 71 | ||||
| -rw-r--r-- | mingling_ci/src/job.rs | 1 | ||||
| -rw-r--r-- | mingling_ci/src/job/cmd_build.rs | 4 | ||||
| -rw-r--r-- | mingling_ci/src/lib.rs | 22 | ||||
| -rw-r--r-- | mingling_ci/src/reporter.rs | 108 | ||||
| -rw-r--r-- | mingling_ci/src/res.rs | 5 | ||||
| -rw-r--r-- | mingling_ci/src/res/manifests.rs | 100 | ||||
| -rw-r--r-- | mingling_ci/src/res/print.rs | 174 |
11 files changed, 826 insertions, 0 deletions
diff --git a/mingling_ci/src/bin/ci.rs b/mingling_ci/src/bin/ci.rs new file mode 100644 index 0000000..a212921 --- /dev/null +++ b/mingling_ci/src/bin/ci.rs @@ -0,0 +1,46 @@ +use just_progress::{ + progress::{self}, + renderer::ProgressSimpleRenderer, +}; +use mingling::{ + hook::ProgramHook, + setup::{ + ConfirmSetup, DirectoryEnvironmentSetup, ExitCodeSetup, + picker::{ConfirmFlagSetup, HelpFlagSetup, QuietFlagSetup}, + }, +}; +use tokio::join; + +use mingling_ci_system::ThisProgram; +use mingling_ci_system::res::*; + +#[tokio::main] +async fn main() { + let center = progress::init(); + let renderer = ProgressSimpleRenderer::new().with_subprogress(true); + let bind = progress::bind(center, move |name, state| renderer.update(name, state)); + + let (_, exit_code) = join!(bind, mingling_ci_begin()); + std::process::exit(exit_code); +} + +async fn mingling_ci_begin() -> i32 { + let mut program = ThisProgram::new(); + + program.with_hook(ProgramHook::empty().on_finish(|_| progress::close())); + + // Plugins + program.with_setup(ExitCodeSetup::default()); + program.with_setup(DirectoryEnvironmentSetup::default()); + + program.with_setup(HelpFlagSetup::default()); + program.with_setup(ConfirmFlagSetup::default()); + program.with_setup(QuietFlagSetup::default()); + + program.with_setup(ConfirmSetup); + + // CI Plugins + program.with_setup(ManifestsSetup); + + program.exec().await +} diff --git a/mingling_ci/src/cmd.rs b/mingling_ci/src/cmd.rs new file mode 100644 index 0000000..45b077e --- /dev/null +++ b/mingling_ci/src/cmd.rs @@ -0,0 +1,2 @@ +pub(crate) mod cmd_report_collect; +pub(crate) mod cmd_show_manifests; diff --git a/mingling_ci/src/cmd/cmd_report_collect.rs b/mingling_ci/src/cmd/cmd_report_collect.rs new file mode 100644 index 0000000..da603c2 --- /dev/null +++ b/mingling_ci/src/cmd/cmd_report_collect.rs @@ -0,0 +1,293 @@ +use std::collections::{BTreeMap, HashMap}; +use std::path::PathBuf; + +use just_template::Template; +use mingling::{ + Grouped, RenderResult, Routable, + macros::{buffer, command, r_println, renderer}, +}; + +use crate::Next; +use crate::reporter::COLLECT_DIR; +use crate::res::{CargoError, Manifests, MessagePrinter, package_name}; + +const OUTPUT_PATH: &str = "./.temp/reports/result.md"; +const REPORT_TEMPLATE: &str = include_str!("../../tmpls/report.md"); +const TASK_SECTION_TEMPLATE: &str = include_str!("../../tmpls/task_section.md"); + +/// Maps a package to its per-OS pass/fail status. +type OsStatuses = BTreeMap<String, bool>; + +/// A row in a task section: package name and its per-OS statuses. +type TaskRow<'a> = (&'a String, &'a OsStatuses); + +/// Rows grouped by task name. +type RowsByTask<'a> = BTreeMap<&'a String, Vec<TaskRow<'a>>>; + +/// Git commit date and short hash for the report. +struct GitInfo { + date: String, + commit_hash: String, +} + +#[command(node = "report-collect")] +pub fn report_collect(manifests: &Manifests) -> Next { + let Ok(task_entries) = std::fs::read_dir(COLLECT_DIR) else { + return ErrorNoCollectDir.to_chain(); + }; + + // Parse `collect/{task}/{os}/{package}.{ok|err}` and group them by + // (task, package) -> os -> ok. + let mut statuses: BTreeMap<(String, String), OsStatuses> = BTreeMap::new(); + for task_entry in task_entries.flatten() { + if !task_entry.file_type().is_ok_and(|t| t.is_dir()) { + continue; + } + let task = task_entry.file_name().to_string_lossy().into_owned(); + + let Ok(os_entries) = std::fs::read_dir(task_entry.path()) else { + continue; + }; + for os_entry in os_entries.flatten() { + if !os_entry.file_type().is_ok_and(|t| t.is_dir()) { + continue; + } + let os = os_entry.file_name().to_string_lossy().into_owned(); + + let Ok(files) = std::fs::read_dir(os_entry.path()) else { + continue; + }; + for file in files.flatten() { + let file_name = file.file_name().to_string_lossy().into_owned(); + if let Some((package, ok)) = parse_log_name(&file_name) { + statuses + .entry((task.clone(), package)) + .or_default() + .insert(os.clone(), ok); + } + } + } + } + + // Group rows by task: task -> [(package, os_statuses)]. + let by_task: RowsByTask = statuses.iter().fold( + BTreeMap::new(), + |mut acc, ((task, package), os_statuses)| { + acc.entry(task).or_default().push((package, os_statuses)); + acc + }, + ); + + // Render one section per task (table rows + this task's failures). + let mut fail_count = 0; + let mut sections: Vec<HashMap<String, String>> = Vec::new(); + for (task, rows) in by_task { + let mut row_arms = Vec::new(); + let mut fail_arms = Vec::new(); + for (package, os_statuses) in rows { + row_arms.push(HashMap::from([ + ("package_name".to_string(), package.clone()), + ("package_dir".to_string(), package_dir(manifests, package)), + ( + "pass_win".to_string(), + pass_cell(os_statuses.get("Windows")), + ), + ( + "pass_linux".to_string(), + pass_cell(os_statuses.get("Linux")), + ), + ("pass_mac".to_string(), pass_cell(os_statuses.get("MacOS"))), + ])); + + for (os, ok) in os_statuses { + if !ok { + let path = format!("{COLLECT_DIR}/{task}/{os}/{package}.err"); + let stdout = strip_ansi(&std::fs::read_to_string(path).unwrap_or_default()); + fail_arms.push(HashMap::from([ + ("package_name".to_string(), package.clone()), + ("stdout".to_string(), stdout), + ])); + fail_count += 1; + } + } + } + + let mut section = Template::from(TASK_SECTION_TEMPLATE); + section.insert_param("task_name".to_string(), task.clone()); + *section.add_impl("rows".to_string()) = row_arms; + *section.add_impl("fails".to_string()) = fail_arms; + sections.push(HashMap::from([( + "section".to_string(), + section.expand().unwrap_or_default(), + )])); + } + + let git = git_info(); + let mut template = Template::from(REPORT_TEMPLATE); + template.insert_param("date".to_string(), git.date); + template.insert_param("commit_hash".to_string(), git.commit_hash); + *template.add_impl("task_sections".to_string()) = sections; + + let expanded = template.expand().unwrap_or_default(); + std::fs::create_dir_all(std::path::Path::new(OUTPUT_PATH).parent().unwrap()).ok(); + std::fs::write(OUTPUT_PATH, expanded).ok(); + + ResultCollectResults { + output: OUTPUT_PATH.into(), + fail_count, + } + .to_chain() +} + +/// Parses a `{package}.{ok|err}` file name into `(package, ok)`. +fn parse_log_name(file_name: &str) -> Option<(String, bool)> { + file_name + .strip_suffix(".ok") + .map(|n| (n.to_string(), true)) + .or_else(|| { + file_name + .strip_suffix(".err") + .map(|n| (n.to_string(), false)) + }) +} + +/// Strips ANSI escape sequences from `input`. +/// +/// Handles CSI (`ESC [ ...`), OSC (`ESC ] ...` terminated by BEL or `ESC \`) +/// and other single-character escapes, while preserving UTF-8 text. Literal +/// `^[` (caret-bracket, produced by some terminal captures) is normalized to +/// `ESC` first. +fn strip_ansi(input: &str) -> String { + // Normalize literal `^[` (0x5E 0x5B) to a real ESC byte. + let normalized = input.replace("^[", "\u{1b}"); + let mut out = String::with_capacity(normalized.len()); + let mut rest = normalized.as_str(); + while let Some(idx) = rest.find('\u{1b}') { + out.push_str(&rest[..idx]); + rest = &rest[idx..]; + rest = &rest[ansi_len(rest)..]; + } + out.push_str(rest); + out +} + +/// Byte length of the ANSI escape sequence starting at `s[0]` (`s[0]` is `ESC`). +fn ansi_len(s: &str) -> usize { + let b = s.as_bytes(); + match b.get(1) { + Some(b'[') => { + // CSI: `ESC [` params/intermediates (0x20-0x3F) then a final byte (0x40-0x7E). + let mut i = 2; + while i < b.len() { + let byte = b[i]; + i += 1; + if (0x40..=0x7E).contains(&byte) { + break; + } + if !(0x20..=0x3F).contains(&byte) { + break; + } + } + i + } + Some(b']') => { + // OSC: `ESC ]` ... terminated by BEL (0x07) or `ESC \`. + let mut i = 2; + while i < b.len() { + let byte = b[i]; + i += 1; + if byte == 0x07 { + break; + } + if byte == 0x1b { + if b.get(i) == Some(&b'\\') { + i += 1; + } + break; + } + } + i + } + Some(_) => 2.min(b.len()), + None => 1, + } +} + +/// Maps a package name to its manifest directory (e.g. `mingling` → +/// `./mingling`), or `—` when the manifest is unknown. +fn package_dir(manifests: &Manifests, package: &str) -> String { + manifests + .path + .iter() + .find(|path| package_name(path) == package) + .and_then(|path| path.parent()) + .map_or_else(|| "—".to_string(), |dir| dir.to_string_lossy().into_owned()) +} + +fn pass_cell(status: Option<&bool>) -> String { + match status { + Some(true) => "✅".to_string(), + Some(false) => "❌".to_string(), + None => "—".to_string(), + } +} + +/// Commit date (`YYYY-MM-DD`) and short commit hash; empty on failure. +fn git_info() -> GitInfo { + let run = |args: &[&str]| { + std::process::Command::new("git") + .args(args) + .output() + .ok() + .filter(|o| o.status.success()) + .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string()) + .unwrap_or_default() + }; + GitInfo { + date: run(&["log", "-1", "--format=%cs"]), + commit_hash: run(&["rev-parse", "--short", "HEAD"]), + } +} + +/// The generated report. +#[derive(Grouped)] +pub struct ResultCollectResults { + pub output: PathBuf, + pub fail_count: usize, +} + +#[derive(Grouped, Default)] +pub struct ErrorNoCollectDir; + +#[renderer(buffer)] +pub fn render_collect_results(r: ResultCollectResults) { + r_println!("Collected {} failing logs", r.fail_count); + r_println!("Report generated at {}", r.output.display()); +} + +#[renderer] +pub fn render_error_no_collect_dir(_: ErrorNoCollectDir, error: &CargoError) -> RenderResult { + let render_result = RenderResult::new(); + error.println(vec![format!("No collect directory: {COLLECT_DIR}")]); + render_result +} + +#[cfg(test)] +mod tests { + use super::strip_ansi; + + #[test] + fn strips_csi_and_osc_and_literal_caret() { + let input = + "\u{1b}[1m\u{1b}[92mok\u{1b}[0m \u{1b}]8;;https://x\u{1b}\\done\u{1b}]8;;\u{1b}\\\n"; + assert_eq!(strip_ansi(input), "ok done\n"); + + // Literal `^[` (caret-bracket) captured by some terminals. + assert_eq!(strip_ansi("^[[31mred^[[0m"), "red"); + } + + #[test] + fn preserves_utf8() { + assert_eq!(strip_ansi("你好\u{1b}[1m世界!\u{1b}[0m"), "你好世界!"); + } +} diff --git a/mingling_ci/src/cmd/cmd_show_manifests.rs b/mingling_ci/src/cmd/cmd_show_manifests.rs new file mode 100644 index 0000000..32e49c0 --- /dev/null +++ b/mingling_ci/src/cmd/cmd_show_manifests.rs @@ -0,0 +1,71 @@ +use std::path::PathBuf; + +use mingling::{ + Grouped, + macros::{buffer, command, r_println, renderer}, +}; + +use prettytable::{ + Cell, Row, Table, + format::{FormatBuilder, LinePosition, LineSeparator}, +}; + +use crate::res::{Manifests, package_name}; + +#[command(node = "show-manifests")] +pub fn show_manifests(manifests: &Manifests) -> ResultPrintManifests { + let mut entries: Vec<ManifestEntry> = manifests + .path + .iter() + .map(|path| ManifestEntry { + name: package_name(path), + path: path.clone(), + }) + .collect(); + entries.sort_by(|a, b| a.path.cmp(&b.path)); + ResultPrintManifests { entries } +} + +/// All manifests the CI will check, sorted by path. +#[derive(Grouped)] +pub struct ResultPrintManifests { + pub entries: Vec<ManifestEntry>, +} + +#[derive(Debug, Clone)] +pub struct ManifestEntry { + pub name: String, + pub path: PathBuf, +} + +#[renderer(buffer)] +pub fn render_print_manifests(r: ResultPrintManifests) { + let mut table = Table::new(); + + table.set_format( + FormatBuilder::new() + .column_separator('│') + .borders('│') + .separator(LinePosition::Top, LineSeparator::new('─', '┬', '┌', '┐')) + .separator(LinePosition::Title, LineSeparator::new('─', '┼', '├', '┤')) + .separator(LinePosition::Bottom, LineSeparator::new('─', '┴', '└', '┘')) + .padding(1, 1) + .build(), + ); + + table.set_titles(Row::new(vec![ + Cell::new("#"), + Cell::new("Package-Name"), + Cell::new("Package-Path"), + ])); + + for (index, entry) in r.entries.iter().enumerate() { + table.add_row(Row::new(vec![ + Cell::new(&(index + 1).to_string()), + Cell::new(&entry.name), + Cell::new(&entry.path.to_string_lossy()), + ])); + } + + r_println!("{table}"); +} diff --git a/mingling_ci/src/job.rs b/mingling_ci/src/job.rs new file mode 100644 index 0000000..6d86ac6 --- /dev/null +++ b/mingling_ci/src/job.rs @@ -0,0 +1 @@ +pub(crate) mod cmd_build; diff --git a/mingling_ci/src/job/cmd_build.rs b/mingling_ci/src/job/cmd_build.rs new file mode 100644 index 0000000..7f43102 --- /dev/null +++ b/mingling_ci/src/job/cmd_build.rs @@ -0,0 +1,4 @@ +use mingling::macros::command; + +#[command(node = "build")] +pub fn build() {} diff --git a/mingling_ci/src/lib.rs b/mingling_ci/src/lib.rs new file mode 100644 index 0000000..b625a81 --- /dev/null +++ b/mingling_ci/src/lib.rs @@ -0,0 +1,22 @@ +#![deny(clippy::pedantic)] +#![deny(clippy::nursery)] +#![allow(clippy::redundant_pub_crate)] +#![allow(clippy::missing_const_for_fn)] + +use mingling::macros::{gen_program, help}; + +pub(crate) mod cmd; +pub(crate) mod job; + +/// Mingling CI's Resources +pub mod res; + +/// Log exporter for CI reports +pub mod reporter; + +#[help] +pub fn render_fallback(_: EntryFallback) -> String { + include_str!("../help.txt").to_string() +} + +gen_program!(); diff --git a/mingling_ci/src/reporter.rs b/mingling_ci/src/reporter.rs new file mode 100644 index 0000000..00ce3e5 --- /dev/null +++ b/mingling_ci/src/reporter.rs @@ -0,0 +1,108 @@ +//! Minimal log exporter for CI reports. +//! +//! Writes per-package results into `collect/{task}/{platform}/{package}.{ok|err}` +//! so that the [`crate::cmd::collect_results`] command can assemble the final +//! report. The task name is set once per CI phase via [`set_task`]. + +use std::fs; +use std::path::Path; +use std::sync::Mutex; + +/// Root of the collected CI logs (relative to the repo root). +pub const COLLECT_DIR: &str = "./.temp/reports/collect"; + +/// The platform a package check ran on. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ReportPlatform { + Windows, + Linux, + MacOS, +} + +impl ReportPlatform { + /// Directory name used under the task folder. + const fn dir_name(self) -> &'static str { + match self { + Self::Windows => "Windows", + Self::Linux => "Linux", + Self::MacOS => "MacOS", + } + } +} + +/// The outcome of a package check. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ReportResult { + /// Check passed. + Ok, + /// Check failed, with the captured output. + Error(String), +} + +/// Current task name (e.g. `Build-All`); set via [`set_task`]. +static CURRENT_TASK: Mutex<Option<String>> = Mutex::new(None); + +/// Sets the task that subsequent [`export`] calls write under. +/// +/// # Panics +/// +/// Panics if the internal mutex is poisoned. +pub fn set_task(task: &str) { + *CURRENT_TASK.lock().unwrap() = Some(task.to_string()); +} + +/// Exports one package result to `collect/{task}/{platform}/{package}.{ok|err}`. +/// +/// Writes `{package}.ok` on success and `{package}.err` (with the output) on +/// failure. Errors are reported to stderr and otherwise ignored. +/// +/// # Panics +/// +/// Panics if the internal task mutex is poisoned. +pub fn export(package: &str, platform: ReportPlatform, result: ReportResult) { + let Some(task) = CURRENT_TASK.lock().unwrap().clone() else { + eprintln!("reporter: no current task; call reporter::set_task first"); + return; + }; + + let dir = Path::new(COLLECT_DIR).join(task).join(platform.dir_name()); + if let Err(e) = fs::create_dir_all(&dir) { + eprintln!("reporter: failed to create {}: {e}", dir.display()); + return; + } + + let (file_name, content) = match result { + ReportResult::Ok => (format!("{package}.ok"), String::new()), + ReportResult::Error(output) => (format!("{package}.err"), output), + }; + let path = dir.join(file_name); + if let Err(e) = fs::write(&path, content) { + eprintln!("reporter: failed to write {}: {e}", path.display()); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn export_writes_ok_and_err_files() { + set_task("reporter-test"); + let task_root = Path::new(COLLECT_DIR).join("reporter-test"); + let dir = task_root.join("Linux"); + fs::remove_dir_all(&task_root).ok(); + + export("pkg-a", ReportPlatform::Linux, ReportResult::Ok); + export( + "pkg-b", + ReportPlatform::Linux, + ReportResult::Error("boom".to_string()), + ); + + assert!(dir.join("pkg-a.ok").is_file()); + assert!(dir.join("pkg-b.err").is_file()); + assert_eq!(fs::read_to_string(dir.join("pkg-b.err")).unwrap(), "boom"); + + fs::remove_dir_all(&task_root).ok(); + } +} diff --git a/mingling_ci/src/res.rs b/mingling_ci/src/res.rs new file mode 100644 index 0000000..5b33a8f --- /dev/null +++ b/mingling_ci/src/res.rs @@ -0,0 +1,5 @@ +mod manifests; +pub use manifests::*; + +mod print; +pub use print::*; diff --git a/mingling_ci/src/res/manifests.rs b/mingling_ci/src/res/manifests.rs new file mode 100644 index 0000000..56829bb --- /dev/null +++ b/mingling_ci/src/res/manifests.rs @@ -0,0 +1,100 @@ +use std::path::{Path, PathBuf}; + +use mingling::{Program, macros::program_setup}; + +use crate::ThisProgram; + +/// Directories whose manifests are excluded from CI checks. +/// +/// Path is relative to the crate source file (`mingling_ci/src/res/`). +const IGNORED_DIRS_FILE: &str = include_str!("../../../.config/ci-ignored-dirs.txt"); + +/// All `Cargo.toml` manifests the CI will check. +#[derive(Default, Clone)] +pub struct Manifests { + pub path: Vec<PathBuf>, +} + +#[program_setup] +pub fn manifests_setup(p: &mut Program<ThisProgram>) { + p.with_resource(Manifests { + path: cargo_tomls(), + }); +} + +/// Recursively collects every `Cargo.toml` under the current directory, +/// skipping the legacy `.run` CI directory and any directory listed in +/// `.config/ci-ignored-dirs.txt`. +#[must_use] +fn cargo_tomls() -> Vec<PathBuf> { + let ignored = ignored_dirs(); + let mut cargo_tomls = Vec::new(); + let mut dirs = vec![PathBuf::from(".")]; + while let Some(dir) = dirs.pop() { + if is_ignored(&dir.to_string_lossy(), &ignored) { + continue; + } + if let Ok(entries) = std::fs::read_dir(&dir) { + for entry in entries.flatten() { + let path = entry.path(); + if path.is_dir() { + // Skip the legacy `.run` CI directory + if path.file_name().and_then(|n| n.to_str()) == Some(".run") { + continue; + } + dirs.push(path); + } else if path.file_name().and_then(|n| n.to_str()) == Some("Cargo.toml") { + cargo_tomls.push(path); + } + } + } + } + cargo_tomls +} + +/// Parses `.config/ci-ignored-dirs.txt` into directory prefixes: +/// non-empty lines that do not start with `#`, with the trailing `/` stripped +/// (e.g. `./.temp/` → `./.temp`). +fn ignored_dirs() -> Vec<String> { + IGNORED_DIRS_FILE + .lines() + .map(str::trim) + .filter(|line| !line.is_empty() && !line.starts_with('#')) + .map(|line| line.trim_end_matches('/').to_string()) + .collect() +} + +/// Whether `path` (a walk directory, e.g. `./.temp` or `./examples`) is inside +/// one of the ignored directories. +fn is_ignored(path: &str, ignored: &[String]) -> bool { + ignored.iter().any(|dir| { + path.strip_prefix(dir.as_str()) + .is_some_and(|rest| rest.is_empty() || rest.starts_with('/')) + }) +} + +/// Extracts the package name from a `Cargo.toml`. +/// +/// Falls back to the parent directory name (e.g. `mingling_core/Cargo.toml` → +/// `mingling_core`, workspace root → `(root)`), matching the legacy CI. +pub(crate) fn package_name(path: &Path) -> String { + let fallback = || { + path.parent() + .and_then(|p| p.file_name()) + .and_then(|n| n.to_str()) + .unwrap_or("(root)") + .to_string() + }; + + let Ok(content) = std::fs::read_to_string(path) else { + return fallback(); + }; + let Ok(toml_value) = content.parse::<toml::Table>() else { + return fallback(); + }; + toml_value + .get("package") + .and_then(|p| p.get("name")) + .and_then(|n| n.as_str()) + .map_or_else(fallback, str::to_string) +} diff --git a/mingling_ci/src/res/print.rs b/mingling_ci/src/res/print.rs new file mode 100644 index 0000000..9d844a6 --- /dev/null +++ b/mingling_ci/src/res/print.rs @@ -0,0 +1,174 @@ +use colored::Colorize; +use mingling::config::ErrorOutput; +use mingling::hook::ProgramHook; +use mingling::{Program, macros::program_setup}; +use mingling::{StringVec, this}; + +use crate::ThisProgram; + +#[program_setup] +pub fn print_setup(p: &mut Program<ThisProgram>) { + p.with_resource(CargoError::default()); + p.with_resource(CargoWarn::default()); + p.with_resource(CargoHelp::default()); + p.with_resource(CargoStatus::default()); + + p.with_hook(ProgramHook::empty().on_begin::<_, ()>(move |_| { + let p = this::<ThisProgram>(); + let silence_err = p.stdout_setting.error_output == ErrorOutput::Hide; + + p.modify_res(|r: &mut CargoError| r.silence = silence_err); + p.modify_res(|r: &mut CargoWarn| r.silence = silence_err); + p.modify_res(|r: &mut CargoHelp| r.silence = silence_err); + p.modify_res(|r: &mut CargoStatus| r.silence = silence_err); + })); +} + +#[derive(Default, Clone)] +pub struct CargoError { + silence: bool, +} + +impl MessagePrinter for CargoError { + fn format(&self, msg: impl Into<StringVec>) -> String { + format!("{}: {}", "error".bold().bright_red(), msg.into().join("")) + } + + fn std_mode(&self) -> StandardOutMode { + if self.silence { + StandardOutMode::Silence + } else { + StandardOutMode::Error + } + } +} + +#[derive(Default, Clone)] +pub struct CargoWarn { + silence: bool, +} + +impl MessagePrinter for CargoWarn { + fn format(&self, msg: impl Into<StringVec>) -> String { + format!("{}: {}", "warning".bright_yellow(), msg.into().join("")) + } + + fn std_mode(&self) -> StandardOutMode { + if self.silence { + StandardOutMode::Silence + } else { + StandardOutMode::Error + } + } +} + +#[derive(Default, Clone)] +pub struct CargoHelp { + silence: bool, +} + +impl MessagePrinter for CargoHelp { + fn format(&self, msg: impl Into<StringVec>) -> String { + format!("{}: {}", "help".bright_white(), msg.into().join("")) + } + + fn std_mode(&self) -> StandardOutMode { + if self.silence { + StandardOutMode::Silence + } else { + StandardOutMode::Error + } + } +} + +#[derive(Default, Clone)] +pub struct CargoStatus { + silence: bool, +} + +impl MessagePrinter for CargoStatus { + fn format(&self, msg: impl Into<StringVec>) -> String { + let parts: Vec<String> = msg.into().to_vec(); + let first = if parts.is_empty() { + String::new() + } else { + parts[0].trim().to_string() + }; + + let (prefix, content) = if first.is_empty() { + // Empty: fall back to Info with full message + ("Info".to_string(), parts.join(" ")) + } else if first.chars().count() == 1 { + // Single character: prefix is Info, entire message is content + ("Info".to_string(), parts.join(" ")) + } else if first.chars().count() <= 12 { + // Single part that is a status prefix (no message after it) + if parts.len() == 1 { + ("Info".to_string(), first) + } else { + // First part is a status prefix, remaining parts are the message + let content = parts[1..].join(" ").trim_start().to_string(); + (first, content) + } + } else { + // First part too long: all is message, fall back to Info + ("Info".to_string(), parts.join(" ")) + }; + + let padding = " ".repeat(12usize.saturating_sub(prefix.chars().count())); + + format!( + "{}{} {}", + padding, + prefix.bold().bright_green(), + content.trim() + ) + } + + fn std_mode(&self) -> StandardOutMode { + if self.silence { + StandardOutMode::Silence + } else { + StandardOutMode::Out + } + } +} + +pub trait MessagePrinter { + #[doc(hidden)] + fn println(&self, msg: impl Into<StringVec>) { + match self.std_mode() { + StandardOutMode::Out => println!("{}", self.format(msg)), + StandardOutMode::Error => eprintln!("{}", self.format(msg)), + StandardOutMode::Silence => {} + } + } + + #[doc(hidden)] + fn print(&self, msg: impl Into<StringVec>) { + match self.std_mode() { + StandardOutMode::Out => print!("{}", self.format(msg)), + StandardOutMode::Error => eprint!("{}", self.format(msg)), + StandardOutMode::Silence => {} + } + } + + /// Formats the message string before output. + fn format(&self, msg: impl Into<StringVec>) -> String; + + /// Returns the standard output mode (stdout or stderr). + fn std_mode(&self) -> StandardOutMode; +} + +/// Specifies where standard output messages should be directed. +/// +/// This enum determines whether messages are printed to stdout, stderr, or suppressed entirely. +#[repr(u8)] +pub enum StandardOutMode { + /// Print messages to standard output (stdout). + Out, + /// Print messages to standard error (stderr). + Error, + /// Suppress all output. + Silence, +} |
