1use std::path::Path;
7
8use crate::config::Config;
9use crate::context::AppContext;
10use crate::error::AftError;
11use crate::format;
12use crate::parser::{detect_language, grammar_for, FileParser};
13
14pub fn line_col_to_byte(source: &str, line: u32, col: u32) -> usize {
21 let mut byte = 0;
22 for (i, l) in source.lines().enumerate() {
23 if i == line as usize {
24 return byte + (col as usize).min(l.len());
25 }
26 byte += l.len() + 1; }
28 source.len()
30}
31
32pub fn replace_byte_range(source: &str, start: usize, end: usize, replacement: &str) -> String {
36 let mut result = String::with_capacity(source.len() - (end - start) + replacement.len());
37 result.push_str(&source[..start]);
38 result.push_str(replacement);
39 result.push_str(&source[end..]);
40 result
41}
42
43pub fn validate_syntax(path: &Path) -> Result<Option<bool>, AftError> {
48 let mut parser = FileParser::new();
49 match parser.parse(path) {
50 Ok((tree, _lang)) => Ok(Some(!tree.root_node().has_error())),
51 Err(AftError::InvalidRequest { .. }) => {
52 Ok(None)
54 }
55 Err(e) => Err(e),
56 }
57}
58
59pub fn validate_syntax_str(content: &str, path: &Path) -> Option<bool> {
65 let lang = detect_language(path)?;
66 let grammar = grammar_for(lang);
67 let mut parser = tree_sitter::Parser::new();
68 if parser.set_language(&grammar).is_err() {
69 return None;
70 }
71 let tree = parser.parse(content.as_bytes(), None)?;
72 Some(!tree.root_node().has_error())
73}
74
75pub struct DryRunResult {
77 pub diff: String,
79 pub syntax_valid: Option<bool>,
81}
82
83pub fn dry_run_diff(original: &str, proposed: &str, path: &Path) -> DryRunResult {
88 let display_path = path.display().to_string();
89 let text_diff = similar::TextDiff::from_lines(original, proposed);
90 let diff = text_diff
91 .unified_diff()
92 .context_radius(3)
93 .header(
94 &format!("a/{}", display_path),
95 &format!("b/{}", display_path),
96 )
97 .to_string();
98 let syntax_valid = validate_syntax_str(proposed, path);
99 DryRunResult { diff, syntax_valid }
100}
101
102pub fn is_dry_run(params: &serde_json::Value) -> bool {
106 params
107 .get("dry_run")
108 .and_then(|v| v.as_bool())
109 .unwrap_or(false)
110}
111
112pub fn auto_backup(
119 ctx: &AppContext,
120 path: &Path,
121 description: &str,
122) -> Result<Option<String>, AftError> {
123 if !path.exists() {
124 return Ok(None);
125 }
126 let backup_id = {
127 let mut store = ctx.backup().borrow_mut();
128 store.snapshot(path, description)?
129 }; Ok(Some(backup_id))
131}
132
133pub struct WriteResult {
138 pub syntax_valid: Option<bool>,
140 pub formatted: bool,
142 pub format_skipped_reason: Option<String>,
144 pub validate_requested: bool,
146 pub validation_errors: Vec<format::ValidationError>,
148 pub validate_skipped_reason: Option<String>,
150 pub lsp_diagnostics: Vec<crate::lsp::diagnostics::StoredDiagnostic>,
153}
154
155impl WriteResult {
156 pub fn append_lsp_diagnostics_to(&self, result: &mut serde_json::Value) {
159 if !self.lsp_diagnostics.is_empty() {
160 result["lsp_diagnostics"] = serde_json::json!(self
161 .lsp_diagnostics
162 .iter()
163 .map(|d| {
164 serde_json::json!({
165 "file": d.file.display().to_string(),
166 "line": d.line,
167 "column": d.column,
168 "end_line": d.end_line,
169 "end_column": d.end_column,
170 "severity": d.severity.as_str(),
171 "message": d.message,
172 "code": d.code,
173 "source": d.source,
174 })
175 })
176 .collect::<Vec<_>>());
177 }
178 }
179}
180
181pub fn write_format_validate(
193 path: &Path,
194 content: &str,
195 config: &Config,
196 params: &serde_json::Value,
197) -> Result<WriteResult, AftError> {
198 std::fs::write(path, content).map_err(|e| AftError::InvalidRequest {
200 message: format!("failed to write file: {}", e),
201 })?;
202
203 let (formatted, format_skipped_reason) = format::auto_format(path, config);
205
206 let syntax_valid = match validate_syntax(path) {
208 Ok(sv) => sv,
209 Err(_) => None,
210 };
211
212 let validate_requested = params.get("validate").and_then(|v| v.as_str()) == Some("full");
214 let (validation_errors, validate_skipped_reason) = if validate_requested {
215 format::validate_full(path, config)
216 } else {
217 (Vec::new(), None)
218 };
219
220 Ok(WriteResult {
221 syntax_valid,
222 formatted,
223 format_skipped_reason,
224 validate_requested,
225 validation_errors,
226 validate_skipped_reason,
227 lsp_diagnostics: Vec::new(),
228 })
229}
230
231#[cfg(test)]
232mod tests {
233 use super::*;
234
235 #[test]
238 fn line_col_to_byte_empty_string() {
239 assert_eq!(line_col_to_byte("", 0, 0), 0);
240 }
241
242 #[test]
243 fn line_col_to_byte_single_line() {
244 let source = "hello";
245 assert_eq!(line_col_to_byte(source, 0, 0), 0);
246 assert_eq!(line_col_to_byte(source, 0, 3), 3);
247 assert_eq!(line_col_to_byte(source, 0, 5), 5); }
249
250 #[test]
251 fn line_col_to_byte_multi_line() {
252 let source = "abc\ndef\nghi\n";
253 assert_eq!(line_col_to_byte(source, 0, 0), 0);
255 assert_eq!(line_col_to_byte(source, 0, 2), 2);
256 assert_eq!(line_col_to_byte(source, 1, 0), 4);
258 assert_eq!(line_col_to_byte(source, 1, 3), 7);
259 assert_eq!(line_col_to_byte(source, 2, 0), 8);
261 assert_eq!(line_col_to_byte(source, 2, 2), 10);
262 }
263
264 #[test]
265 fn line_col_to_byte_last_line_no_trailing_newline() {
266 let source = "abc\ndef";
267 assert_eq!(line_col_to_byte(source, 1, 0), 4);
269 assert_eq!(line_col_to_byte(source, 1, 3), 7); }
271
272 #[test]
273 fn line_col_to_byte_multi_byte_utf8() {
274 let source = "café\nbar";
276 assert_eq!(line_col_to_byte(source, 0, 0), 0);
278 assert_eq!(line_col_to_byte(source, 0, 5), 5); assert_eq!(line_col_to_byte(source, 1, 0), 6);
281 assert_eq!(line_col_to_byte(source, 1, 2), 8);
282 }
283
284 #[test]
285 fn line_col_to_byte_beyond_end() {
286 let source = "abc";
287 assert_eq!(line_col_to_byte(source, 5, 0), source.len());
289 }
290
291 #[test]
292 fn line_col_to_byte_col_clamped_to_line_length() {
293 let source = "ab\ncd";
294 assert_eq!(line_col_to_byte(source, 0, 10), 2);
296 }
297
298 #[test]
301 fn replace_byte_range_basic() {
302 let source = "hello world";
303 let result = replace_byte_range(source, 6, 11, "rust");
304 assert_eq!(result, "hello rust");
305 }
306
307 #[test]
308 fn replace_byte_range_delete() {
309 let source = "hello world";
310 let result = replace_byte_range(source, 5, 11, "");
311 assert_eq!(result, "hello");
312 }
313
314 #[test]
315 fn replace_byte_range_insert_at_same_position() {
316 let source = "helloworld";
317 let result = replace_byte_range(source, 5, 5, " ");
318 assert_eq!(result, "hello world");
319 }
320
321 #[test]
322 fn replace_byte_range_replace_entire_string() {
323 let source = "old content";
324 let result = replace_byte_range(source, 0, source.len(), "new content");
325 assert_eq!(result, "new content");
326 }
327}