use serde::{Deserialize, Serialize};
use crate::config::Config;
use crate::models::Finding;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum OutputFormat {
#[default]
Text,
Json,
Sarif,
Markdown,
Github,
}
impl std::str::FromStr for OutputFormat {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_lowercase().as_str() {
"text" => Ok(Self::Text),
"json" => Ok(Self::Json),
"sarif" => Ok(Self::Sarif),
"markdown" | "md" => Ok(Self::Markdown),
"github" | "gh" => Ok(Self::Github),
_ => Err(format!("Unknown output format: {}", s)),
}
}
}
impl std::fmt::Display for OutputFormat {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Text => write!(f, "text"),
Self::Json => write!(f, "json"),
Self::Sarif => write!(f, "sarif"),
Self::Markdown => write!(f, "markdown"),
Self::Github => write!(f, "github"),
}
}
}
pub fn format_findings(findings: &[Finding], format: OutputFormat) -> String {
let config = Config::default();
super::format(findings, format, &config)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_output_format_from_str() {
assert_eq!("text".parse::<OutputFormat>().unwrap(), OutputFormat::Text);
assert_eq!("json".parse::<OutputFormat>().unwrap(), OutputFormat::Json);
assert_eq!(
"sarif".parse::<OutputFormat>().unwrap(),
OutputFormat::Sarif
);
assert_eq!(
"markdown".parse::<OutputFormat>().unwrap(),
OutputFormat::Markdown
);
assert_eq!("md".parse::<OutputFormat>().unwrap(), OutputFormat::Markdown);
assert_eq!(
"github".parse::<OutputFormat>().unwrap(),
OutputFormat::Github
);
assert!("invalid".parse::<OutputFormat>().is_err());
}
#[test]
fn test_output_format_display() {
assert_eq!(OutputFormat::Text.to_string(), "text");
assert_eq!(OutputFormat::Json.to_string(), "json");
assert_eq!(OutputFormat::Sarif.to_string(), "sarif");
}
}