use std::path::{Path, PathBuf};
use super::error::{CliError, CliResult};
use super::io_utils::{read_file, read_stdin};
use super::{CheckArgs, DiagnosticFormat};
use crate::parser;
#[derive(Debug, Clone)]
pub struct Diagnostic {
pub file: PathBuf,
pub line: usize,
pub column: usize,
pub message: String,
}
impl Diagnostic {
pub fn format_text(&self) -> String {
format!("{}:{}:{}: error: {}", self.file.display(), self.line, self.column, self.message)
}
pub fn format_github(&self) -> String {
let encoded_message =
self.message.replace('%', "%25").replace('\r', "%0D").replace('\n', "%0A");
format!(
"::error file={},line={},col={}::{}",
self.file.display(),
self.line,
self.column,
encoded_message
)
}
pub fn format_json(&self) -> String {
serde_json::json!({
"file": self.file.to_string_lossy(),
"line": self.line,
"column": self.column,
"message": self.message,
"severity": "error"
})
.to_string()
}
}
pub struct CheckResult {
pub file: PathBuf,
pub diagnostics: Vec<Diagnostic>,
}
impl CheckResult {
pub fn is_valid(&self) -> bool {
self.diagnostics.is_empty()
}
}
pub fn execute(args: &CheckArgs) -> CliResult<()> {
let results = check_files(args)?;
let all_diagnostics: Vec<&Diagnostic> = results.iter().flat_map(|r| &r.diagnostics).collect();
if !all_diagnostics.is_empty() {
report_diagnostics(&all_diagnostics, args.format);
return Err(CliError::Validation(format!("{} error(s) found", all_diagnostics.len())));
}
Ok(())
}
fn check_files(args: &CheckArgs) -> CliResult<Vec<CheckResult>> {
if args.input.is_empty() || (args.input.len() == 1 && args.input[0].as_os_str() == "-") {
let content = read_stdin()?;
let diagnostics = check_content(&content, Path::new("<stdin>"));
return Ok(vec![CheckResult { file: PathBuf::from("<stdin>"), diagnostics }]);
}
let mut results = Vec::with_capacity(args.input.len());
for path in &args.input {
results.push(check_single_file(path)?);
}
Ok(results)
}
fn check_single_file(path: &Path) -> CliResult<CheckResult> {
let content = read_file(path)?;
let diagnostics = check_content(&content, path);
Ok(CheckResult { file: path.to_path_buf(), diagnostics })
}
fn check_content(content: &str, file: &Path) -> Vec<Diagnostic> {
let (_, errors) = parser::parse_with_errors(content);
errors
.iter()
.map(|e| Diagnostic {
file: file.to_path_buf(),
line: (e.span.start.line as usize) + 1,
column: (e.span.start.column as usize) + 1,
message: e.kind.to_string(),
})
.collect()
}
fn report_diagnostics(diagnostics: &[&Diagnostic], format: DiagnosticFormat) {
match format {
DiagnosticFormat::Json => {
let json_array: Vec<serde_json::Value> = diagnostics
.iter()
.map(|diag| {
serde_json::json!({
"file": diag.file.to_string_lossy(),
"line": diag.line,
"column": diag.column,
"message": diag.message,
"severity": "error"
})
})
.collect();
eprintln!("{}", serde_json::to_string_pretty(&json_array).unwrap_or_default());
}
_ => {
for diag in diagnostics {
let output = match format {
DiagnosticFormat::Text => diag.format_text(),
DiagnosticFormat::Github => diag.format_github(),
DiagnosticFormat::Json => unreachable!(),
};
eprintln!("{output}");
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_check_valid_content() {
let content = "key: value\n";
let diagnostics = check_content(content, Path::new("test.toon"));
assert!(diagnostics.is_empty());
}
#[test]
fn test_check_invalid_content() {
let content = "key: [unclosed";
let diagnostics = check_content(content, Path::new("test.toon"));
assert!(!diagnostics.is_empty());
}
#[test]
fn test_diagnostic_format_text() {
let diag = Diagnostic {
file: PathBuf::from("test.toon"),
line: 5,
column: 10,
message: "test error".to_string(),
};
let text = diag.format_text();
assert!(text.contains("test.toon"));
assert!(text.contains('5'));
assert!(text.contains("10"));
assert!(text.contains("test error"));
}
#[test]
fn test_diagnostic_format_github() {
let diag = Diagnostic {
file: PathBuf::from("test.toon"),
line: 5,
column: 10,
message: "test error".to_string(),
};
let github = diag.format_github();
assert!(github.starts_with("::error"));
assert!(github.contains("file=test.toon"));
assert!(github.contains("line=5"));
assert!(github.contains("col=10"));
}
#[test]
fn test_diagnostic_format_github_encodes_special_chars() {
let diag = Diagnostic {
file: PathBuf::from("test.toon"),
line: 1,
column: 1,
message: "100% complete\nwith newline\rand carriage return".to_string(),
};
let github = diag.format_github();
assert!(github.contains("100%25 complete"));
assert!(github.contains("%0Awith newline"));
assert!(github.contains("%0Dand carriage return"));
assert!(!github.contains('\n'));
assert!(!github.contains('\r'));
}
#[test]
fn test_diagnostic_format_json() {
let diag = Diagnostic {
file: PathBuf::from("test.toon"),
line: 5,
column: 10,
message: "test error".to_string(),
};
let json = diag.format_json();
assert!(json.contains("\"file\""));
assert!(json.contains("\"line\":5"));
assert!(json.contains("\"column\":10"));
}
}