1#![allow(unused_assignments)]
7
8use std::path::{Path, PathBuf};
9
10use miette::{Diagnostic, SourceSpan};
11use owo_colors::OwoColorize;
12use thiserror::Error;
13
14#[derive(Error, Debug, Diagnostic)]
16pub enum TaleError {
17 #[error("File operation failed")]
19 #[diagnostic()]
20 File(#[from] Box<FileError>),
21
22 #[error("JSON format error")]
24 #[diagnostic()]
25 Json(#[from] Box<JsonError>),
26
27 #[error("Configuration error")]
29 #[diagnostic()]
30 Config(#[from] Box<ConfigError>),
31
32 #[error("I/O operation failed")]
34 #[diagnostic()]
35 Io(#[from] Box<IoError>),
36
37 #[error("Memory management error: {0}")]
39 #[diagnostic(code(tale::memory::error))]
40 MemoryError(String),
41
42 #[error(transparent)]
44 #[diagnostic()]
45 GlobPattern(#[from] glob::PatternError),
46
47 #[error("Internal error: failed to set up async channels for lines")]
48 LineReceiver,
49
50 #[error("Internal error: failed to set up async channels")]
51 BatchSender,
52
53 #[error("Internal error: trouble sending batched lines on async channels")]
54 BatchedLineSender,
55 #[error("Internal error: trouble sending batched vectors of lines on async channels")]
56 BatchedLineVecSender,
57
58 #[error(transparent)]
59 #[diagnostic()]
60 NotifyError(#[from] notify::Error),
61}
62
63#[derive(Error, Debug, Diagnostic)]
65pub enum FileError {
66 #[error("File not found: {}", path.display().yellow().bold())]
68 #[diagnostic(code(tale::file::not_found))]
69 NotFound { path: PathBuf, similar_files: Vec<String> },
70
71 #[error("Permission denied: {}", path.display().yellow().bold())]
73 #[diagnostic(code(tale::file::permission_denied))]
74 PermissionDenied { path: PathBuf, suggestion: String },
75
76 #[error("Not a regular file: {} is a {}", path.display().yellow().bold(), actual_type.bold())]
78 #[diagnostic(code(tale::file::not_a_file))]
79 NotAFile { path: PathBuf, actual_type: String },
80}
81
82#[derive(Error, Debug, Diagnostic)]
84pub enum JsonError {
85 #[error("Invalid JSON syntax")]
87 #[diagnostic(code(tale::json::invalid_syntax))]
88 InvalidSyntax {
89 #[source_code]
90 src: String,
91 #[label("invalid JSON here")]
92 span: SourceSpan,
93 details: String,
94 },
95
96 #[error("Missing required field: {}", field.blue())]
98 #[diagnostic(code(tale::json::missing_field))]
99 MissingField {
100 field: String,
101 #[source_code]
102 src: String,
103 #[label("in this JSON object")]
104 span: SourceSpan,
105 },
106}
107
108#[derive(Error, Debug, Diagnostic)]
110pub enum ConfigError {
111 #[error("Invalid argument combination")]
113 #[diagnostic(code(tale::config::invalid_args))]
114 InvalidArgs {
115 message: String,
116 conflicting_args: Vec<String>,
117 },
118
119 #[error("Invalid offset value: {}", value.blue())]
121 #[diagnostic(code(tale::config::invalid_offset))]
122 InvalidOffset { value: String, reason: String },
123}
124
125#[derive(Error, Debug, Diagnostic)]
127pub enum IoError {
128 #[error("I/O error: {}", operation.blue())]
130 #[diagnostic(code(tale::io::operation_failed))]
131 OperationFailed {
132 operation: String,
133 path: Option<PathBuf>,
134 #[source]
135 source: std::io::Error,
136 },
137}
138
139impl FileError {
141 pub fn not_found_with_suggestions(path: PathBuf, similar_files: Vec<PathBuf>) -> Self {
143 let similar_files = similar_files.into_iter().map(|p| p.display().to_string()).collect();
144 Self::NotFound { path, similar_files }
145 }
146
147 pub fn permission_denied_with_suggestion(path: PathBuf, suggestion: Option<String>) -> Self {
149 let suggestion = suggestion.unwrap_or_else(|| "Check file permissions".to_string());
150 Self::PermissionDenied { path, suggestion }
151 }
152
153 pub fn not_a_file_with_type(path: PathBuf) -> Self {
155 let actual_type = if path.is_dir() {
156 "directory".to_string()
157 } else if path.is_symlink() {
158 "symbolic link".to_string()
159 } else {
160 "special file".to_string()
161 };
162
163 Self::NotAFile { path, actual_type }
164 }
165}
166
167impl JsonError {
168 pub fn invalid_syntax_at(src: String, offset: usize, len: usize, details: String) -> Self {
170 Self::InvalidSyntax {
171 src,
172 span: SourceSpan::new(offset.into(), len),
173 details,
174 }
175 }
176}
177
178impl From<std::io::Error> for TaleError {
181 fn from(err: std::io::Error) -> Self {
182 TaleError::Io(Box::new(IoError::OperationFailed {
183 operation: "I/O operation".to_string(),
184 path: None,
185 source: err,
186 }))
187 }
188}
189
190impl From<serde_json::Error> for TaleError {
193 fn from(err: serde_json::Error) -> Self {
194 TaleError::Json(Box::new(JsonError::InvalidSyntax {
195 src: "JSON input".to_string(),
196 span: miette::SourceSpan::new(0.into(), 0usize),
197 details: err.to_string(),
198 }))
199 }
200}
201
202pub fn find_similar_files(target: &Path) -> Vec<PathBuf> {
204 let Some(parent) = target.parent() else {
205 return Vec::new();
206 };
207
208 let Some(target_name) = target.file_name().and_then(|n| n.to_str()) else {
209 return Vec::new();
210 };
211
212 let Ok(entries) = std::fs::read_dir(parent) else {
213 return Vec::new();
214 };
215
216 let mut similar = Vec::new();
217
218 for entry in entries.flatten() {
219 if let Some(name) = entry.file_name().to_str()
220 && name != target_name
221 && is_similar(target_name, name)
222 {
223 similar.push(entry.path());
224 }
225 }
226
227 similar.sort_by(|a, b| {
229 let a_name = a.file_name().unwrap_or_default().to_str().unwrap_or_default();
230 let b_name = b.file_name().unwrap_or_default().to_str().unwrap_or_default();
231 let a_dist = edit_distance(target_name, a_name);
232 let b_dist = edit_distance(target_name, b_name);
233 a_dist.cmp(&b_dist)
234 });
235
236 similar.truncate(3); similar
238}
239
240fn is_similar(target: &str, candidate: &str) -> bool {
242 let target = target.to_lowercase();
243 let candidate = candidate.to_lowercase();
244
245 let distance = edit_distance(&target, &candidate);
248 distance <= 3 && distance > 0
249}
250
251fn edit_distance(s1: &str, s2: &str) -> usize {
253 let len1 = s1.len();
254 let len2 = s2.len();
255 let mut matrix = vec![vec![0; len2 + 1]; len1 + 1];
256
257 for (i, row) in matrix.iter_mut().enumerate().take(len1 + 1) {
258 row[0] = i;
259 }
260 for (j, cell) in matrix[0].iter_mut().enumerate() {
261 *cell = j;
262 }
263
264 for i in 1..=len1 {
265 for j in 1..=len2 {
266 let cost = if s1.chars().nth(i - 1) == s2.chars().nth(j - 1) {
267 0
268 } else {
269 1
270 };
271 matrix[i][j] = std::cmp::min(
272 std::cmp::min(matrix[i - 1][j] + 1, matrix[i][j - 1] + 1),
273 matrix[i - 1][j - 1] + cost,
274 );
275 }
276 }
277
278 matrix[len1][len2]
279}
280
281#[cfg(test)]
282mod tests {
283 use std::path::PathBuf;
284
285 use super::*;
286
287 #[test]
288 fn edit_distance_calc_works() {
289 assert_eq!(edit_distance("hello", "hello"), 0);
290 assert_eq!(edit_distance("hello", "helo"), 1);
291 assert_eq!(edit_distance("hello", "help"), 2);
292 assert_eq!(edit_distance("file.txt", "file.log"), 3);
293 }
294
295 #[test]
296 fn can_find_similar_files() {
297 assert!(is_similar("file.txt", "file.log"));
298 assert!(is_similar("config.json", "config.jsn"));
299 assert!(!is_similar("file.txt", "completely_different.py"));
300 }
301
302 #[test]
303 fn good_error_on_enofile() {
304 let path = PathBuf::from("/nonexistent/file.txt");
305 let similar = vec![PathBuf::from("/nonexistent/file.log")];
306
307 let error = FileError::not_found_with_suggestions(path.clone(), similar);
308
309 match error {
310 FileError::NotFound {
311 path: error_path,
312 similar_files: suggestions,
313 } => {
314 assert_eq!(error_path, path);
315 assert!(!suggestions.is_empty());
316 assert_eq!(suggestions.len(), 1);
317 }
318 _ => panic!("Expected FileNotFound error variant, got different error type"),
319 }
320 }
321}