From dfc385628ca1995e65f63f65d5353e469c617d9f Mon Sep 17 00:00:00 2001 From: Freddie Ridell Date: Mon, 23 Feb 2026 19:18:03 +0000 Subject: [PATCH] Refactor Render trait: separate format methods, return strings --- crates/pollard-cli/src/io.rs | 81 ++++---- crates/pollard-cli/src/mutate/apply.rs | 39 ++-- crates/pollard-cli/src/mutate/describe.rs | 66 +++--- crates/pollard-cli/src/mutate/generate.rs | 62 +++--- crates/pollard-cli/src/mutate/view.rs | 79 +++++--- .../src/steps/apply_mutant_to_workspace.rs | 38 ++-- crates/pollard-cli/src/steps/cleanup.rs | 34 ++-- .../src/steps/create_workspaces.rs | 39 ++-- .../pollard-cli/src/steps/derive_mutants.rs | 34 ++-- crates/pollard-cli/src/steps/find_files.rs | 38 ++-- crates/pollard-cli/src/steps/mod.rs | 44 ++-- .../pollard-cli/src/steps/reset_workspace.rs | 34 ++-- crates/pollard-core/src/io.rs | 38 +++- crates/pollard-core/src/lib.rs | 188 ++++++++++-------- 14 files changed, 413 insertions(+), 401 deletions(-) diff --git a/crates/pollard-cli/src/io.rs b/crates/pollard-cli/src/io.rs index 22af5931..69a775f4 100644 --- a/crates/pollard-cli/src/io.rs +++ b/crates/pollard-cli/src/io.rs @@ -64,47 +64,37 @@ impl Action { impl Render for Action { - fn render(&self, style: &Style, no_color: bool, _depth: u8) { - let no_color = no_color || matches!(style, Style::Plain); - match style { - Style::Json => { - println!( - "{}", - serde_json::to_string(self).expect("failed to serialize") - ); + fn render_json(&self) -> String { + serde_json::to_string(self).expect("failed to serialize") + } + + fn render_pretty(&self, _depth: u8) -> String { + match self { + Action::WriteFile { path, .. } => { + format!("write {}\n", color("\x1b[36m", &path.display().to_string())) + } + Action::CreateJjWorkspace { name, path } => { + format!( + "jj workspace add {} at {}\n", + color("\x1b[33m", name), + color("\x1b[36m", &path.display().to_string()), + ) + } + Action::ForgetJjWorkspace { name } => { + format!("jj workspace forget {}\n", color("\x1b[33m", name)) + } + Action::RemoveDir { path } => { + format!("rm -r {}\n", color("\x1b[36m", &path.display().to_string())) + } + Action::RemoveFile { path } => { + format!("rm {}\n", color("\x1b[36m", &path.display().to_string())) } - Style::Plain | Style::Pretty | Style::Markdown => match self { - Action::WriteFile { path, .. } => { - println!( - "write {}", - color("\x1b[36m", &path.display().to_string(), no_color) - ); - } - Action::CreateJjWorkspace { name, path } => { - println!( - "jj workspace add {} at {}", - color("\x1b[33m", name, no_color), - color("\x1b[36m", &path.display().to_string(), no_color), - ); - } - Action::ForgetJjWorkspace { name } => { - println!("jj workspace forget {}", color("\x1b[33m", name, no_color)); - } - Action::RemoveDir { path } => { - println!( - "rm -r {}", - color("\x1b[36m", &path.display().to_string(), no_color) - ); - } - Action::RemoveFile { path } => { - println!( - "rm {}", - color("\x1b[36m", &path.display().to_string(), no_color) - ); - } - }, } } + + fn render_markdown(&self, depth: u8) -> String { + self.render_pretty(depth) + } } impl Report for Action { @@ -133,11 +123,16 @@ impl SessionReport { } impl Render for SessionReport { - fn render(&self, style: &Style, _no_color: bool, _depth: u8) { - match style { - Style::Json => println!("{}", self.json), - _ => println!("{}", self.debug), - } + fn render_json(&self) -> String { + self.json.clone() + } + + fn render_pretty(&self, _depth: u8) -> String { + format!("{}\n", self.debug) + } + + fn render_markdown(&self, _depth: u8) -> String { + format!("```\n{}\n```\n", self.debug) } } diff --git a/crates/pollard-cli/src/mutate/apply.rs b/crates/pollard-cli/src/mutate/apply.rs index 9571df58..dd77959e 100644 --- a/crates/pollard-cli/src/mutate/apply.rs +++ b/crates/pollard-cli/src/mutate/apply.rs @@ -1,12 +1,10 @@ -use crate::io::{Action, Render, Report, Style, hashed_path}; +use crate::io::{Action, Render, Report, color, hashed_path}; use crate::mutate::find_mutated; use pollard_core::config::LanguageId; use pollard_core::{Hash, SourceFile}; use serde::Serialize; use std::path::{Path, PathBuf}; -use crate::io::color; - pub fn run( language: &LanguageId, input: &Path, @@ -37,27 +35,20 @@ pub struct ApplyReport { } impl Render for ApplyReport { - fn render(&self, style: &Style, no_color: bool, _depth: u8) { - let no_color = no_color || matches!(style, Style::Plain); - match style { - Style::Json => { - println!( - "{}", - serde_json::to_string(self).expect("failed to serialize") - ); - } - Style::Plain | Style::Pretty | Style::Markdown => { - println!( - "Will apply mutation {} to {}", - color("\x1b[33m", &self.mutated_hash.to_string(), no_color), - color( - "\x1b[36m", - &self.source_path.display().to_string(), - no_color - ), - ); - } - } + fn render_json(&self) -> String { + serde_json::to_string(self).expect("failed to serialize") + } + + fn render_pretty(&self, _depth: u8) -> String { + format!( + "Will apply mutation {} to {}\n", + color("\x1b[33m", &self.mutated_hash.to_string()), + color("\x1b[36m", &self.source_path.display().to_string()), + ) + } + + fn render_markdown(&self, depth: u8) -> String { + self.render_pretty(depth) } } diff --git a/crates/pollard-cli/src/mutate/describe.rs b/crates/pollard-cli/src/mutate/describe.rs index e86197eb..3911343d 100644 --- a/crates/pollard-cli/src/mutate/describe.rs +++ b/crates/pollard-cli/src/mutate/describe.rs @@ -1,12 +1,10 @@ -use crate::io::{Action, Render, Report, Style, hashed_path}; +use crate::io::{Action, Render, Report, color, hashed_path}; use crate::mutate::find_description; use pollard_core::config::LanguageId; use pollard_core::{Hash, MutationKind, SourceFile}; use serde::Serialize; use std::path::{Path, PathBuf}; -use crate::io::color; - pub fn run(language: &LanguageId, input: &Path, hash: &Hash) -> (Vec, DescribeReport) { let file = SourceFile::read(input).expect("failed to read input file"); let desc = find_description(language, &file, hash); @@ -54,42 +52,38 @@ impl DescribeReport { } impl Render for DescribeReport { - fn render(&self, style: &Style, no_color: bool, depth: u8) { + fn render_json(&self) -> String { + serde_json::to_string(self).expect("failed to serialize") + } + + fn render_pretty(&self, depth: u8) -> String { let path = self.path.display(); let loc = self.location(); + format!( + "{} at {}\n{}\n{}\n", + color("\x1b[1m", &self.kind.render_pretty(depth + 1)), + color("\x1b[36m", &format!("{path}:{loc}")), + color("\x1b[31m", &self.original), + color("\x1b[32m", &self.replacement), + ) + } - match style { - Style::Json => { - println!( - "{}", - serde_json::to_string(self).expect("failed to serialize") - ); - } - Style::Markdown => { - let heading = "#".repeat((depth + 1).min(6) as usize); - println!("{heading} Mutation\n"); - print!("**Kind:** "); - self.kind.render(style, no_color, depth + 1); - println!("\n"); - println!("**File:** `{path}`\n"); - println!("**Location:** {loc}\n"); - let tag = self.code_tag; - println!("**Original:**\n```{tag}\n{}\n```\n", self.original); - println!("**Replacement:**\n```{tag}\n{}\n```", self.replacement); - } - Style::Plain | Style::Pretty => { - let no_color = no_color || matches!(style, Style::Plain); - print!("{}", if no_color { "" } else { "\x1b[1m" }); - self.kind.render(style, no_color, depth + 1); - println!( - "{} at {}", - if no_color { "" } else { "\x1b[0m" }, - color("\x1b[36m", &format!("{path}:{loc}"), no_color), - ); - println!("{}", color("\x1b[31m", &self.original, no_color)); - println!("{}", color("\x1b[32m", &self.replacement, no_color)); - } - } + fn render_markdown(&self, depth: u8) -> String { + let path = self.path.display(); + let loc = self.location(); + let heading = "#".repeat((depth + 1).min(6) as usize); + let tag = self.code_tag; + format!( + "{heading} Mutation\n\n\ + **Kind:** {}\n\n\ + **File:** `{path}`\n\n\ + **Location:** {loc}\n\n\ + **Original:**\n```{tag}\n{}\n```\n\n\ + **Replacement:**\n```{tag}\n{}\n```\n", + self.kind.render_markdown(depth + 1), + self.original, + self.replacement, + ) } } diff --git a/crates/pollard-cli/src/mutate/generate.rs b/crates/pollard-cli/src/mutate/generate.rs index 94549eec..6f3ffad3 100644 --- a/crates/pollard-cli/src/mutate/generate.rs +++ b/crates/pollard-cli/src/mutate/generate.rs @@ -1,4 +1,4 @@ -use crate::io::{Action, Render, Report, Style, hashed_path}; +use crate::io::{Action, Render, Report, color, hashed_path}; use crate::steps::expand_glob; use pollard_core::config::LanguageId; use pollard_core::languages::javascript::JavaScript; @@ -63,40 +63,34 @@ pub struct GenerateReport { pub replacement: String, } -use crate::io::color; - impl Render for GenerateReport { - fn render(&self, style: &Style, no_color: bool, _depth: u8) { - let no_color = no_color || matches!(style, Style::Plain); - match style { - Style::Json => { - println!( - "{}", - serde_json::to_string(self).expect("failed to serialize") - ); - } - Style::Plain | Style::Pretty | Style::Markdown => { - println!( - "{} {} {} {}\n{}\n{}\n", - color("\x1b[33m", &self.mutated_hash.to_string(), no_color), - self.source_path.display(), - color("\x1b[1m", &format!("{:?}", self.kind), no_color), - color( - "\x1b[36m", - &format!( - "{}:{}-{}:{}", - self.start_line + 1, - self.start_char + 1, - self.end_line + 1, - self.end_char + 1, - ), - no_color, - ), - color("\x1b[31m", &self.original, no_color), - color("\x1b[32m", &self.replacement, no_color), - ); - } - } + fn render_json(&self) -> String { + serde_json::to_string(self).expect("failed to serialize") + } + + fn render_pretty(&self, _depth: u8) -> String { + format!( + "{} {} {} {}\n{}\n{}\n\n", + color("\x1b[33m", &self.mutated_hash.to_string()), + self.source_path.display(), + color("\x1b[1m", &format!("{:?}", self.kind)), + color( + "\x1b[36m", + &format!( + "{}:{}-{}:{}", + self.start_line + 1, + self.start_char + 1, + self.end_line + 1, + self.end_char + 1, + ), + ), + color("\x1b[31m", &self.original), + color("\x1b[32m", &self.replacement), + ) + } + + fn render_markdown(&self, depth: u8) -> String { + self.render_pretty(depth) } } diff --git a/crates/pollard-cli/src/mutate/view.rs b/crates/pollard-cli/src/mutate/view.rs index 25dff6eb..36133efa 100644 --- a/crates/pollard-cli/src/mutate/view.rs +++ b/crates/pollard-cli/src/mutate/view.rs @@ -1,11 +1,11 @@ -use crate::io::{Action, DiffStyle, Render, Report, Style, hashed_path}; -use std::path::PathBuf; +use crate::io::{Action, DiffStyle, Render, Report, hashed_path}; use crate::mutate::find_mutated; use pollard_core::config::LanguageId; +use pollard_core::io::color; use pollard_core::{Hash, SourceFile}; use similar::{ChangeTag, TextDiff}; use std::fmt::Write; -use std::path::Path; +use std::path::{Path, PathBuf}; pub fn run( language: &LanguageId, @@ -34,14 +34,25 @@ pub struct ViewReport { } impl Render for ViewReport { - fn render(&self, _style: &Style, no_color: bool, _depth: u8) { + fn render_json(&self) -> String { + serde_json::to_string(&serde_json::json!({ + "path": self.path, + "old": self.old, + "new": self.new, + })) + .expect("failed to serialize") + } + + fn render_pretty(&self, _depth: u8) -> String { match self.diff_style { - DiffStyle::Unified => render_unified(&self.old, &self.new, &self.path, no_color), - DiffStyle::SideBySide => { - render_side_by_side(&self.old, &self.new, &self.path, no_color) - } + DiffStyle::Unified => format_unified(&self.old, &self.new, &self.path), + DiffStyle::SideBySide => format_side_by_side(&self.old, &self.new, &self.path), } } + + fn render_markdown(&self, depth: u8) -> String { + self.render_pretty(depth) + } } impl Report for ViewReport { @@ -53,60 +64,66 @@ impl Report for ViewReport { let content = format!("{}:{}:{}", self.path, self.old, self.new); hashed_path(&self.get_dir(session), &content, "diff") } - } -use crate::io::color; - -fn render_unified(old: &str, new: &str, path: &str, no_color: bool) { +fn format_unified(old: &str, new: &str, path: &str) -> String { let diff = TextDiff::from_lines(old, new); - println!("{}", color("\x1b[1m", &format!("--- {path}"), no_color)); - println!( - "{}", - color("\x1b[1m", &format!("+++ {path} (mutated)"), no_color) - ); + let mut out = String::new(); + out.push_str(&color("\x1b[1m", &format!("--- {path}"))); + out.push('\n'); + out.push_str(&color("\x1b[1m", &format!("+++ {path} (mutated)"))); + out.push('\n'); for hunk in diff.unified_diff().context_radius(3).iter_hunks() { let mut buf = String::new(); write!(&mut buf, "{hunk}").unwrap(); for line in buf.lines() { if line.starts_with("@@") { - println!("{}", color("\x1b[36m", line, no_color)); + out.push_str(&color("\x1b[36m", line)); } else if line.starts_with('-') { - println!("{}", color("\x1b[31m", line, no_color)); + out.push_str(&color("\x1b[31m", line)); } else if line.starts_with('+') { - println!("{}", color("\x1b[32m", line, no_color)); + out.push_str(&color("\x1b[32m", line)); } else { - println!(" {line}"); + out.push(' '); + out.push_str(line); } + out.push('\n'); } } + out } -fn render_side_by_side(old: &str, new: &str, path: &str, no_color: bool) { +fn format_side_by_side(old: &str, new: &str, path: &str) -> String { let diff = TextDiff::from_lines(old, new); let width = terminal_width() / 2 - 3; + let mut out = String::new(); - println!( - "{} │ {}", - color("\x1b[1m", &pad(path, width), no_color), - color("\x1b[1m", &format!("{path} (mutated)"), no_color), - ); - println!("{}─┼─{}", "─".repeat(width), "─".repeat(width)); + out.push_str(&format!( + "{} │ {}\n", + color("\x1b[1m", &pad(path, width)), + color("\x1b[1m", &format!("{path} (mutated)")), + )); + out.push_str(&format!("{}─┼─{}\n", "─".repeat(width), "─".repeat(width))); for change in diff.iter_all_changes() { let text = change.value().trim_end_matches('\n'); match change.tag() { ChangeTag::Equal => { - println!("{} │ {}", pad(text, width), text); + out.push_str(&format!("{} │ {}\n", pad(text, width), text)); } ChangeTag::Delete => { - println!("{} │", color("\x1b[31m", &pad(text, width), no_color)); + out.push_str(&format!("{} │\n", color("\x1b[31m", &pad(text, width)))); } ChangeTag::Insert => { - println!("{} │ {}", pad("", width), color("\x1b[32m", text, no_color)); + out.push_str(&format!( + "{} │ {}\n", + pad("", width), + color("\x1b[32m", text) + )); } } } + out } fn pad(s: &str, width: usize) -> String { diff --git a/crates/pollard-cli/src/steps/apply_mutant_to_workspace.rs b/crates/pollard-cli/src/steps/apply_mutant_to_workspace.rs index 970742fa..394f3b6f 100644 --- a/crates/pollard-cli/src/steps/apply_mutant_to_workspace.rs +++ b/crates/pollard-cli/src/steps/apply_mutant_to_workspace.rs @@ -1,6 +1,5 @@ -use crate::io::{Action, Render, Report, Style, hashed_path}; +use crate::io::{Action, Render, Report, color, hashed_path}; use pollard_session::Session; -use crate::io::color; use crate::steps::{find_workspace, read_plan, read_workspace_manifest}; use pollard_core::Hash; use serde::Serialize; @@ -68,27 +67,20 @@ pub struct ApplyMutantToWorkspaceReport { } impl Render for ApplyMutantToWorkspaceReport { - fn render(&self, style: &Style, no_color: bool, _depth: u8) { - let no_color = no_color || matches!(style, Style::Plain); - match style { - Style::Json => { - println!( - "{}", - serde_json::to_string(self).expect("failed to serialize") - ); - } - Style::Plain | Style::Pretty | Style::Markdown => { - println!( - "Will apply mutation {} to {}", - color("\x1b[33m", &self.mutated_hash.to_string(), no_color), - color( - "\x1b[36m", - &self.source_path.display().to_string(), - no_color - ), - ); - } - } + fn render_json(&self) -> String { + serde_json::to_string(self).expect("failed to serialize") + } + + fn render_pretty(&self, _depth: u8) -> String { + format!( + "Will apply mutation {} to {}\n", + color("\x1b[33m", &self.mutated_hash.to_string()), + color("\x1b[36m", &self.source_path.display().to_string()), + ) + } + + fn render_markdown(&self, depth: u8) -> String { + self.render_pretty(depth) } } diff --git a/crates/pollard-cli/src/steps/cleanup.rs b/crates/pollard-cli/src/steps/cleanup.rs index 97b99b2b..9d7a42b8 100644 --- a/crates/pollard-cli/src/steps/cleanup.rs +++ b/crates/pollard-cli/src/steps/cleanup.rs @@ -1,6 +1,5 @@ -use crate::io::{Action, Render, Report, Style, hashed_path}; +use crate::io::{Action, Render, Report, color, hashed_path}; use pollard_session::Session; -use crate::io::color; use crate::steps::expand_glob; use serde::Serialize; use std::path::PathBuf; @@ -53,23 +52,20 @@ pub struct CleanupReport { } impl Render for CleanupReport { - fn render(&self, style: &Style, no_color: bool, _depth: u8) { - let no_color = no_color || matches!(style, Style::Plain); - match style { - Style::Json => { - println!( - "{}", - serde_json::to_string(self).expect("failed to serialize") - ); - } - Style::Plain | Style::Pretty | Style::Markdown => { - println!( - "Will clean up {} workspaces from {} manifests", - color("\x1b[33m", &self.workspace_count.to_string(), no_color), - color("\x1b[36m", &self.manifest_count.to_string(), no_color), - ); - } - } + fn render_json(&self) -> String { + serde_json::to_string(self).expect("failed to serialize") + } + + fn render_pretty(&self, _depth: u8) -> String { + format!( + "Will clean up {} workspaces from {} manifests\n", + color("\x1b[33m", &self.workspace_count.to_string()), + color("\x1b[36m", &self.manifest_count.to_string()), + ) + } + + fn render_markdown(&self, depth: u8) -> String { + self.render_pretty(depth) } } diff --git a/crates/pollard-cli/src/steps/create_workspaces.rs b/crates/pollard-cli/src/steps/create_workspaces.rs index 8b945dd3..f4c3f255 100644 --- a/crates/pollard-cli/src/steps/create_workspaces.rs +++ b/crates/pollard-cli/src/steps/create_workspaces.rs @@ -1,6 +1,5 @@ -use crate::io::{Action, Render, Report, Style, hashed_path}; +use crate::io::{Action, Render, Report, color, hashed_path}; use pollard_session::Session; -use crate::io::color; use crate::steps::content_id; use pollard_core::config::Vcs; use serde::Serialize; @@ -65,26 +64,24 @@ pub struct CreateWorkspacesReport { } impl Render for CreateWorkspacesReport { - fn render(&self, style: &Style, no_color: bool, _depth: u8) { - let no_color = no_color || matches!(style, Style::Plain); - match style { - Style::Json => { - println!( - "{}", - serde_json::to_string(self).expect("failed to serialize") - ); - } - Style::Plain | Style::Pretty | Style::Markdown => { - println!( - "Will create {} workspaces, manifest: {}", - color("\x1b[33m", &self.workspaces.len().to_string(), no_color), - color("\x1b[36m", &self.manifest.display().to_string(), no_color), - ); - for ws in &self.workspaces { - println!(" {}", color("\x1b[33m", ws, no_color)); - } - } + fn render_json(&self) -> String { + serde_json::to_string(self).expect("failed to serialize") + } + + fn render_pretty(&self, _depth: u8) -> String { + let mut out = format!( + "Will create {} workspaces, manifest: {}\n", + color("\x1b[33m", &self.workspaces.len().to_string()), + color("\x1b[36m", &self.manifest.display().to_string()), + ); + for ws in &self.workspaces { + out.push_str(&format!(" {}\n", color("\x1b[33m", ws))); } + out + } + + fn render_markdown(&self, depth: u8) -> String { + self.render_pretty(depth) } } diff --git a/crates/pollard-cli/src/steps/derive_mutants.rs b/crates/pollard-cli/src/steps/derive_mutants.rs index 0227c6ae..c0e5ccf7 100644 --- a/crates/pollard-cli/src/steps/derive_mutants.rs +++ b/crates/pollard-cli/src/steps/derive_mutants.rs @@ -1,6 +1,5 @@ -use crate::io::{Action, Render, Report, Style, hashed_path}; +use crate::io::{Action, Render, Report, color, hashed_path}; use pollard_session::Session; -use crate::io::color; use crate::steps::content_id; use pollard_core::config::LanguageId; use pollard_core::languages::javascript::JavaScript; @@ -79,23 +78,20 @@ pub struct DeriveMutantsReport { } impl Render for DeriveMutantsReport { - fn render(&self, style: &Style, no_color: bool, _depth: u8) { - let no_color = no_color || matches!(style, Style::Plain); - match style { - Style::Json => { - println!( - "{}", - serde_json::to_string(self).expect("failed to serialize") - ); - } - Style::Plain | Style::Pretty | Style::Markdown => { - println!( - "Derived {} mutations, will write to {}", - color("\x1b[33m", &self.count.to_string(), no_color), - color("\x1b[36m", &self.path.display().to_string(), no_color), - ); - } - } + fn render_json(&self) -> String { + serde_json::to_string(self).expect("failed to serialize") + } + + fn render_pretty(&self, _depth: u8) -> String { + format!( + "Derived {} mutations, will write to {}\n", + color("\x1b[33m", &self.count.to_string()), + color("\x1b[36m", &self.path.display().to_string()), + ) + } + + fn render_markdown(&self, depth: u8) -> String { + self.render_pretty(depth) } } diff --git a/crates/pollard-cli/src/steps/find_files.rs b/crates/pollard-cli/src/steps/find_files.rs index 0142bdda..787f7a21 100644 --- a/crates/pollard-cli/src/steps/find_files.rs +++ b/crates/pollard-cli/src/steps/find_files.rs @@ -1,4 +1,4 @@ -use crate::io::{Action, Render, Report, Style, hashed_path}; +use crate::io::{Action, Render, Report, color, hashed_path}; use pollard_session::Session; use crate::steps::expand_glob; use serde::Serialize; @@ -22,26 +22,24 @@ pub struct FindFilesReport { } impl Render for FindFilesReport { - fn render(&self, style: &Style, no_color: bool, _depth: u8) { - let no_color = no_color || matches!(style, Style::Plain); - match style { - Style::Json => { - println!( - "{}", - serde_json::to_string(self).expect("failed to serialize") - ); - } - Style::Plain | Style::Pretty | Style::Markdown => { - println!( - "{} files match {}", - crate::io::color("\x1b[33m", &self.files.len().to_string(), no_color), - crate::io::color("\x1b[36m", &self.pattern, no_color), - ); - for f in &self.files { - println!(" {}", f.display()); - } - } + fn render_json(&self) -> String { + serde_json::to_string(self).expect("failed to serialize") + } + + fn render_pretty(&self, _depth: u8) -> String { + let mut out = format!( + "{} files match {}\n", + color("\x1b[33m", &self.files.len().to_string()), + color("\x1b[36m", &self.pattern), + ); + for f in &self.files { + out.push_str(&format!(" {}\n", f.display())); } + out + } + + fn render_markdown(&self, depth: u8) -> String { + self.render_pretty(depth) } } diff --git a/crates/pollard-cli/src/steps/mod.rs b/crates/pollard-cli/src/steps/mod.rs index e93a6183..03cbd7af 100644 --- a/crates/pollard-cli/src/steps/mod.rs +++ b/crates/pollard-cli/src/steps/mod.rs @@ -7,7 +7,7 @@ pub mod reset_workspace; pub mod setup_workspace; pub mod test_workspace; -use crate::io::{Render, Report, Style, hashed_path}; +use crate::io::{Render, Report, hashed_path}; use pollard_session::Session; use pollard_core::plan::{Plan, WorkspaceManifest}; use serde::Serialize; @@ -135,29 +135,27 @@ pub struct CommandReport { } impl Render for CommandReport { - fn render(&self, style: &Style, no_color: bool, _depth: u8) { - let no_color = no_color || matches!(style, Style::Plain); - match style { - Style::Json => { - println!( - "{}", - serde_json::to_string(self).expect("failed to serialize") - ); - } - Style::Plain | Style::Pretty | Style::Markdown => { - let (status, output) = match &self.result { - Ok(stdout) => (color("\x1b[32m", "OK", no_color), stdout), - Err(stderr) => (color("\x1b[31m", "FAIL", no_color), stderr), - }; - println!( - "{} {} in {} [{}]", - status, self.step, self.workspace, self.command - ); - if !output.is_empty() { - print!("{output}"); - } - } + fn render_json(&self) -> String { + serde_json::to_string(self).expect("failed to serialize") + } + + fn render_pretty(&self, _depth: u8) -> String { + let (status, output) = match &self.result { + Ok(stdout) => (color("\x1b[32m", "OK"), stdout.as_str()), + Err(stderr) => (color("\x1b[31m", "FAIL"), stderr.as_str()), + }; + let mut out = format!( + "{} {} in {} [{}]\n", + status, self.step, self.workspace, self.command + ); + if !output.is_empty() { + out.push_str(output); } + out + } + + fn render_markdown(&self, depth: u8) -> String { + self.render_pretty(depth) } } diff --git a/crates/pollard-cli/src/steps/reset_workspace.rs b/crates/pollard-cli/src/steps/reset_workspace.rs index dd7e9fe9..a192b017 100644 --- a/crates/pollard-cli/src/steps/reset_workspace.rs +++ b/crates/pollard-cli/src/steps/reset_workspace.rs @@ -1,6 +1,5 @@ -use crate::io::{Action, Render, Report, Style, hashed_path}; +use crate::io::{Action, Render, Report, color, hashed_path}; use pollard_session::Session; -use crate::io::color; use crate::steps::{find_workspace, read_workspace_manifest}; use pollard_core::config::Vcs; use serde::Serialize; @@ -52,23 +51,20 @@ pub struct ResetWorkspaceReport { } impl Render for ResetWorkspaceReport { - fn render(&self, style: &Style, no_color: bool, _depth: u8) { - let no_color = no_color || matches!(style, Style::Plain); - match style { - Style::Json => { - println!( - "{}", - serde_json::to_string(self).expect("failed to serialize") - ); - } - Style::Plain | Style::Pretty | Style::Markdown => { - println!( - "Will reset {} to {}", - color("\x1b[33m", &self.workspace, no_color), - color("\x1b[36m", &self.rev, no_color), - ); - } - } + fn render_json(&self) -> String { + serde_json::to_string(self).expect("failed to serialize") + } + + fn render_pretty(&self, _depth: u8) -> String { + format!( + "Will reset {} to {}\n", + color("\x1b[33m", &self.workspace), + color("\x1b[36m", &self.rev), + ) + } + + fn render_markdown(&self, depth: u8) -> String { + self.render_pretty(depth) } } diff --git a/crates/pollard-core/src/io.rs b/crates/pollard-core/src/io.rs index 58dc254e..cc0d20e9 100644 --- a/crates/pollard-core/src/io.rs +++ b/crates/pollard-core/src/io.rs @@ -19,15 +19,41 @@ pub enum DiffStyle { } pub trait Render { - fn render(&self, style: &Style, no_color: bool, depth: u8); + fn render_json(&self) -> String; + fn render_pretty(&self, depth: u8) -> String; + fn render_markdown(&self, depth: u8) -> String; + + fn render(&self, style: &Style, no_color: bool, depth: u8) { + let output = match style { + Style::Json => self.render_json(), + Style::Markdown => self.render_markdown(depth), + Style::Pretty if no_color => strip_ansi(&self.render_pretty(depth)), + Style::Pretty => self.render_pretty(depth), + Style::Plain => strip_ansi(&self.render_pretty(depth)), + }; + print!("{output}"); + } +} + +pub fn color(code: &str, text: &str) -> String { + format!("{code}{text}\x1b[0m") } -pub fn color(code: &str, text: &str, no_color: bool) -> String { - if no_color { - text.to_string() - } else { - format!("{code}{text}\x1b[0m") +pub fn strip_ansi(s: &str) -> String { + let mut result = String::with_capacity(s.len()); + let mut chars = s.chars(); + while let Some(c) = chars.next() { + if c == '\x1b' { + for c in chars.by_ref() { + if c == 'm' { + break; + } + } + } else { + result.push(c); + } } + result } pub fn hashed_path(dir: &PathBuf, content: &str, label: &str) -> PathBuf { diff --git a/crates/pollard-core/src/lib.rs b/crates/pollard-core/src/lib.rs index e1f4f0d2..df7ae43f 100644 --- a/crates/pollard-core/src/lib.rs +++ b/crates/pollard-core/src/lib.rs @@ -292,54 +292,61 @@ pub struct MutationSubstitution<'a, 'b, L: Language> { pub replacement: String, } -impl io::Render for BinaryOpKind { - fn render(&self, style: &io::Style, _no_color: bool, _depth: u8) { - match style { - io::Style::Json => { - println!( - "{}", - serde_json::to_string(self).expect("failed to serialize") - ); - } - _ => { - let label = match self { - BinaryOpKind::Add => "+", - BinaryOpKind::Sub => "-", - BinaryOpKind::Mul => "*", - BinaryOpKind::Div => "/", - BinaryOpKind::And => "&&", - BinaryOpKind::Or => "||", - BinaryOpKind::StrictEq => "===", - BinaryOpKind::StrictNeq => "!==", - BinaryOpKind::Eq => "==", - BinaryOpKind::Neq => "!=", - BinaryOpKind::Lt => "<", - BinaryOpKind::Lte => "<=", - BinaryOpKind::Gt => ">", - BinaryOpKind::Gte => ">=", - }; - print!("{label}"); - } +impl BinaryOpKind { + pub fn label(&self) -> &'static str { + match self { + BinaryOpKind::Add => "+", + BinaryOpKind::Sub => "-", + BinaryOpKind::Mul => "*", + BinaryOpKind::Div => "/", + BinaryOpKind::And => "&&", + BinaryOpKind::Or => "||", + BinaryOpKind::StrictEq => "===", + BinaryOpKind::StrictNeq => "!==", + BinaryOpKind::Eq => "==", + BinaryOpKind::Neq => "!=", + BinaryOpKind::Lt => "<", + BinaryOpKind::Lte => "<=", + BinaryOpKind::Gt => ">", + BinaryOpKind::Gte => ">=", } } } +impl io::Render for BinaryOpKind { + fn render_json(&self) -> String { + serde_json::to_string(self).expect("failed to serialize") + } + + fn render_pretty(&self, _depth: u8) -> String { + self.label().to_string() + } + + fn render_markdown(&self, _depth: u8) -> String { + self.label().to_string() + } +} + impl io::Render for MutationKind { - fn render(&self, style: &io::Style, no_color: bool, depth: u8) { - match style { - io::Style::Json => { - println!( - "{}", - serde_json::to_string(self).expect("failed to serialize") - ); + fn render_json(&self) -> String { + serde_json::to_string(self).expect("failed to serialize") + } + + fn render_pretty(&self, depth: u8) -> String { + match self { + MutationKind::StatementBlock => "empty statement block".to_string(), + MutationKind::BinaryOp(op) => { + format!("binary operator {}", op.render_pretty(depth)) + } + } + } + + fn render_markdown(&self, depth: u8) -> String { + match self { + MutationKind::StatementBlock => "empty statement block".to_string(), + MutationKind::BinaryOp(op) => { + format!("binary operator {}", op.render_markdown(depth)) } - _ => match self { - MutationKind::StatementBlock => print!("empty statement block"), - MutationKind::BinaryOp(op) => { - print!("binary operator "); - op.render(style, no_color, depth); - } - }, } } } @@ -348,10 +355,31 @@ impl io::Render for MutationSubstitution<'_, '_, L> where L::Kind: Clone + Into, { - fn render(&self, style: &io::Style, no_color: bool, depth: u8) { + fn render_json(&self) -> String { + let point = self.point; + let original = &point.file.content()[point.span.start.byte..point.span.end.byte]; + let kind: MutationKind = point.kind.clone().into(); + let path = point.file.path().display().to_string(); + let loc = format!( + "{}:{}-{}:{}", + point.span.start.line + 1, + point.span.start.char + 1, + point.span.end.line + 1, + point.span.end.char + 1, + ); + serde_json::to_string(&serde_json::json!({ + "path": path, + "location": loc, + "kind": kind, + "original": original, + "replacement": self.replacement, + })) + .expect("failed to serialize") + } + + fn render_pretty(&self, depth: u8) -> String { let point = self.point; - let original = - &point.file.content()[point.span.start.byte..point.span.end.byte]; + let original = &point.file.content()[point.span.start.byte..point.span.end.byte]; let kind: MutationKind = point.kind.clone().into(); let path = point.file.path().display(); let loc = format!( @@ -361,45 +389,39 @@ where point.span.end.line + 1, point.span.end.char + 1, ); + format!( + "{} at {}\n{}\n{}\n", + io::color("\x1b[1m", &kind.render_pretty(depth + 1)), + io::color("\x1b[36m", &format!("{path}:{loc}")), + io::color("\x1b[31m", original), + io::color("\x1b[32m", &self.replacement), + ) + } - match style { - io::Style::Json => { - println!( - "{}", - serde_json::to_string(&serde_json::json!({ - "path": path.to_string(), - "location": loc, - "kind": kind, - "original": original, - "replacement": self.replacement, - })) - .expect("failed to serialize") - ); - } - io::Style::Markdown => { - let heading = "#".repeat((depth + 1).min(6) as usize); - println!("{heading} Mutation\n"); - print!("**Kind:** "); - kind.render(style, no_color, depth + 1); - println!("\n"); - println!("**File:** `{path}`\n"); - println!("**Location:** {loc}\n"); - let tag = L::code_tag(); - println!("**Original:**\n```{tag}\n{original}\n```\n"); - println!( - "**Replacement:**\n```{tag}\n{}\n```", - self.replacement - ); - } - io::Style::Plain | io::Style::Pretty => { - let no_color = no_color || matches!(style, io::Style::Plain); - print!("{}", io::color("\x1b[1m", "", no_color)); - kind.render(style, no_color, depth + 1); - println!(" at {}", io::color("\x1b[36m", &format!("{path}:{loc}"), no_color)); - println!("{}", io::color("\x1b[31m", original, no_color)); - println!("{}", io::color("\x1b[32m", &self.replacement, no_color)); - } - } + fn render_markdown(&self, depth: u8) -> String { + let point = self.point; + let original = &point.file.content()[point.span.start.byte..point.span.end.byte]; + let kind: MutationKind = point.kind.clone().into(); + let path = point.file.path().display(); + let loc = format!( + "{}:{}-{}:{}", + point.span.start.line + 1, + point.span.start.char + 1, + point.span.end.line + 1, + point.span.end.char + 1, + ); + let heading = "#".repeat((depth + 1).min(6) as usize); + let tag = L::code_tag(); + format!( + "{heading} Mutation\n\n\ + **Kind:** {}\n\n\ + **File:** `{path}`\n\n\ + **Location:** {loc}\n\n\ + **Original:**\n```{tag}\n{original}\n```\n\n\ + **Replacement:**\n```{tag}\n{}\n```\n", + kind.render_markdown(depth + 1), + self.replacement, + ) } } -- knotmirror 0.0.1