|
| 1 | +use anyhow::{Context, Result}; |
| 2 | +use colored::Colorize; |
| 3 | +use serde::{Deserialize, Serialize}; |
| 4 | +use std::fs; |
| 5 | +use std::path::Path; |
| 6 | + |
| 7 | +use crate::utils::file_io::{read_file, write_file}; |
| 8 | + |
| 9 | +#[derive(Debug, Serialize, Deserialize)] |
| 10 | +struct ErrorLocation { |
| 11 | + row: usize, |
| 12 | + column: usize, |
| 13 | + byte_offset: usize, |
| 14 | + size: usize, |
| 15 | +} |
| 16 | + |
| 17 | +#[derive(Debug, Serialize, Deserialize)] |
| 18 | +struct ParseError { |
| 19 | + filename: String, |
| 20 | + title: String, |
| 21 | + message: String, |
| 22 | + location: ErrorLocation, |
| 23 | +} |
| 24 | + |
| 25 | +pub struct DivWhitespaceConverter {} |
| 26 | + |
| 27 | +impl DivWhitespaceConverter { |
| 28 | + pub fn new() -> Result<Self> { |
| 29 | + Ok(Self {}) |
| 30 | + } |
| 31 | + |
| 32 | + /// Parse a file and get error locations as JSON |
| 33 | + fn get_parse_errors(&self, file_path: &Path) -> Result<Vec<ParseError>> { |
| 34 | + let content = fs::read_to_string(file_path) |
| 35 | + .with_context(|| format!("Failed to read file: {}", file_path.display()))?; |
| 36 | + |
| 37 | + // Use the quarto-markdown-pandoc library to parse with JSON error formatter |
| 38 | + let mut sink = std::io::sink(); |
| 39 | + let filename = file_path.to_string_lossy(); |
| 40 | + |
| 41 | + let result = quarto_markdown_pandoc::readers::qmd::read( |
| 42 | + content.as_bytes(), |
| 43 | + false, // not loose mode |
| 44 | + &filename, |
| 45 | + &mut sink, |
| 46 | + Some( |
| 47 | + quarto_markdown_pandoc::readers::qmd_error_messages::produce_json_error_messages |
| 48 | + as fn( |
| 49 | + &[u8], |
| 50 | + &quarto_markdown_pandoc::utils::tree_sitter_log_observer::TreeSitterLogObserver, |
| 51 | + &str, |
| 52 | + ) -> Vec<String>, |
| 53 | + ), |
| 54 | + ); |
| 55 | + |
| 56 | + match result { |
| 57 | + Ok(_) => Ok(Vec::new()), // No errors |
| 58 | + Err(error_messages) => { |
| 59 | + // Parse the JSON error output |
| 60 | + // The error messages come as a single JSON array string |
| 61 | + if error_messages.is_empty() { |
| 62 | + return Ok(Vec::new()); |
| 63 | + } |
| 64 | + |
| 65 | + let json_str = error_messages.join(""); |
| 66 | + let errors: Vec<ParseError> = |
| 67 | + serde_json::from_str(&json_str).context("Failed to parse JSON error output")?; |
| 68 | + |
| 69 | + Ok(errors) |
| 70 | + } |
| 71 | + } |
| 72 | + } |
| 73 | + |
| 74 | + /// Find div fence errors that need whitespace fixes |
| 75 | + fn find_div_whitespace_errors(&self, content: &str, errors: &[ParseError]) -> Vec<usize> { |
| 76 | + let mut fix_positions = Vec::new(); |
| 77 | + let lines: Vec<&str> = content.lines().collect(); |
| 78 | + |
| 79 | + for error in errors { |
| 80 | + // Skip errors that are not about div fences |
| 81 | + // We're looking for "Missing Space After Div Fence" or errors on lines with ::: |
| 82 | + let is_div_error = error.title.contains("Div Fence") || error.title == "Parse error"; |
| 83 | + |
| 84 | + if !is_div_error { |
| 85 | + continue; |
| 86 | + } |
| 87 | + |
| 88 | + // The error might be on the line itself or the line before (for div fences) |
| 89 | + // Check both the current line and the previous line |
| 90 | + let lines_to_check = if error.location.row > 0 { |
| 91 | + vec![error.location.row - 1, error.location.row] |
| 92 | + } else { |
| 93 | + vec![error.location.row] |
| 94 | + }; |
| 95 | + |
| 96 | + for &line_idx in &lines_to_check { |
| 97 | + if line_idx >= lines.len() { |
| 98 | + continue; |
| 99 | + } |
| 100 | + |
| 101 | + let line = lines[line_idx]; |
| 102 | + |
| 103 | + // Check if this line starts with ::: followed immediately by { |
| 104 | + let trimmed = line.trim_start(); |
| 105 | + if let Some(after_colon) = trimmed.strip_prefix(":::") { |
| 106 | + if after_colon.starts_with('{') { |
| 107 | + // Calculate the position right after ::: |
| 108 | + // We need byte offset, not char offset |
| 109 | + let line_start = content |
| 110 | + .lines() |
| 111 | + .take(line_idx) |
| 112 | + .map(|l| l.len() + 1) // +1 for newline |
| 113 | + .sum::<usize>(); |
| 114 | + |
| 115 | + let indent_bytes = line.len() - trimmed.len(); |
| 116 | + let fix_pos = line_start + indent_bytes + 3; // +3 for ":::" |
| 117 | + |
| 118 | + fix_positions.push(fix_pos); |
| 119 | + break; // Found it, no need to check other lines for this error |
| 120 | + } |
| 121 | + } |
| 122 | + } |
| 123 | + } |
| 124 | + |
| 125 | + // Remove duplicates and sort |
| 126 | + fix_positions.sort_unstable(); |
| 127 | + fix_positions.dedup(); |
| 128 | + |
| 129 | + fix_positions |
| 130 | + } |
| 131 | + |
| 132 | + /// Apply fixes to content by inserting spaces at specified positions |
| 133 | + fn apply_fixes(&self, content: &str, fix_positions: &[usize]) -> String { |
| 134 | + let mut result = String::with_capacity(content.len() + fix_positions.len()); |
| 135 | + let mut last_pos = 0; |
| 136 | + |
| 137 | + for &pos in fix_positions { |
| 138 | + // Copy content up to this position |
| 139 | + result.push_str(&content[last_pos..pos]); |
| 140 | + // Insert a space |
| 141 | + result.push(' '); |
| 142 | + last_pos = pos; |
| 143 | + } |
| 144 | + |
| 145 | + // Copy remaining content |
| 146 | + result.push_str(&content[last_pos..]); |
| 147 | + |
| 148 | + result |
| 149 | + } |
| 150 | + |
| 151 | + /// Process a single file |
| 152 | + pub fn process_file( |
| 153 | + &self, |
| 154 | + file_path: &Path, |
| 155 | + in_place: bool, |
| 156 | + check: bool, |
| 157 | + verbose: bool, |
| 158 | + ) -> Result<()> { |
| 159 | + let content = read_file(file_path)?; |
| 160 | + |
| 161 | + // Get parse errors |
| 162 | + let errors = self.get_parse_errors(file_path)?; |
| 163 | + |
| 164 | + if errors.is_empty() { |
| 165 | + if verbose { |
| 166 | + println!(" No div whitespace issues found"); |
| 167 | + } |
| 168 | + return Ok(()); |
| 169 | + } |
| 170 | + |
| 171 | + // Find positions that need fixes |
| 172 | + let fix_positions = self.find_div_whitespace_errors(&content, &errors); |
| 173 | + |
| 174 | + if fix_positions.is_empty() { |
| 175 | + if verbose { |
| 176 | + println!(" No div whitespace issues found"); |
| 177 | + } |
| 178 | + return Ok(()); |
| 179 | + } |
| 180 | + |
| 181 | + if verbose || check { |
| 182 | + println!( |
| 183 | + " Found {} div fence(s) needing whitespace fixes", |
| 184 | + fix_positions.len().to_string().yellow() |
| 185 | + ); |
| 186 | + } |
| 187 | + |
| 188 | + if check { |
| 189 | + println!(" {} No changes written (--check mode)", "✓".green()); |
| 190 | + return Ok(()); |
| 191 | + } |
| 192 | + |
| 193 | + // Apply fixes |
| 194 | + let new_content = self.apply_fixes(&content, &fix_positions); |
| 195 | + |
| 196 | + if in_place { |
| 197 | + write_file(file_path, &new_content)?; |
| 198 | + println!( |
| 199 | + " {} Fixed {} div fence(s)", |
| 200 | + "✓".green(), |
| 201 | + fix_positions.len() |
| 202 | + ); |
| 203 | + } else { |
| 204 | + // Output to stdout |
| 205 | + print!("{}", new_content); |
| 206 | + } |
| 207 | + |
| 208 | + Ok(()) |
| 209 | + } |
| 210 | +} |
0 commit comments