Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 18 additions & 6 deletions src/app/cover_renderer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ use std::{

use crate::infrastructure::logging::Logger;

/// Choices for showing the cover letter.
///
/// You can show it as plain text or use tools like `bat` to add colors.
#[derive(Debug, Serialize, Deserialize, Clone, Copy, Default)]
pub enum CoverRenderer {
#[default]
Expand All @@ -17,6 +20,7 @@ pub enum CoverRenderer {
Bat,
}

/// Creates a renderer choice from a String.
impl From<String> for CoverRenderer {
fn from(value: String) -> Self {
match value.as_str() {
Expand All @@ -26,6 +30,7 @@ impl From<String> for CoverRenderer {
}
}

/// Creates a renderer choice from a string slice.
impl From<&str> for CoverRenderer {
fn from(value: &str) -> Self {
match value {
Expand All @@ -35,6 +40,7 @@ impl From<&str> for CoverRenderer {
}
}

/// Turns the choice back into a String.
impl Display for CoverRenderer {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Expand All @@ -44,6 +50,9 @@ impl Display for CoverRenderer {
}
}

/// Decides how to show the cover letter.
///
/// It looks at the settings and calls the right function to format the text.
pub fn render_cover(raw: &str, renderer: &CoverRenderer) -> color_eyre::Result<String> {
let text = match renderer {
CoverRenderer::Default => Ok(raw.to_string()),
Expand All @@ -53,17 +62,17 @@ pub fn render_cover(raw: &str, renderer: &CoverRenderer) -> color_eyre::Result<S
Ok(text)
}

/// Renders a .mbx cover using the `bat` command line tool.
/// Formats the cover letter using the `bat` command.
///
/// # Errors
///
/// If bat isn't installed or if the command fails, an error will be returned.
/// Fails if `bat` is not installed or has an error.
fn bat_cover_renderer(patch: &str) -> color_eyre::Result<String> {
let mut bat = Command::new("bat")
.arg("-pp")
.arg("-f")
.arg("-l")
.arg("mbx")
.arg("-pp") // Plain mode: no paging or extra decorations
.arg("-f") // Force: keep colors even if piping
.arg("-l") // Language: set the language type
.arg("mbx") // Mailbox format
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()
Expand All @@ -72,7 +81,10 @@ fn bat_cover_renderer(patch: &str) -> color_eyre::Result<String> {
e
})?;

// Sends the text to bat
bat.stdin.as_mut().unwrap().write_all(patch.as_bytes())?;

// Waits for bat to finish and gets the result
let output = bat.wait_with_output()?;
Ok(String::from_utf8(output.stdout)?)
}