fsvalidator 0.3.0

A file structure validator
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
//! # Validation
//!
//! Contains the logic for validating filesystem paths against the model.
//!
//! This module implements the core validation functionality, checking whether real filesystem
//! paths match the expected structure defined in the model.

use crate::model::{DirNode, FileNode, Node, NodeName};
use anyhow::{Result, anyhow};
use regex::Regex;
use std::fs;
use std::path::{Path, PathBuf};
use std::fmt;
use std::error::Error;

/// Error category for classifying validation errors.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ErrorCategory {
    /// Missing file or directory that was required
    Missing,
    /// Path exists but is the wrong type (e.g., file instead of directory)
    WrongType,
    /// Name doesn't match expected literal or pattern
    NameMismatch,
    /// Unexpected entry in directory with allow_defined_only=true
    Unexpected,
    /// Invalid regex pattern
    InvalidPattern,
    /// Error accessing filesystem
    IoError,
    /// Other/miscellaneous errors
    Other,
}

/// Represents a validation error encountered during filesystem validation.
#[derive(Debug)]
pub struct ValidationError {
    /// Path where the validation error occurred
    pub path: PathBuf,
    /// Description of the validation error
    pub message: String,
    /// Category of the validation error
    pub category: ErrorCategory,
    /// Nested validation errors (for directory validation)
    pub children: Vec<ValidationError>,
}

impl ValidationError {
    /// Creates a new ValidationError with the given path, message, and category.
    pub fn new(
        path: impl AsRef<Path>,
        message: impl Into<String>,
        category: ErrorCategory
    ) -> Self {
        ValidationError {
            path: path.as_ref().to_path_buf(),
            message: message.into(),
            category,
            children: Vec::new(),
        }
    }

    /// Creates a new ValidationError with the given path, message, category, and child errors.
    pub fn with_children(
        path: impl AsRef<Path>, 
        message: impl Into<String>,
        category: ErrorCategory,
        children: Vec<ValidationError>
    ) -> Self {
        ValidationError {
            path: path.as_ref().to_path_buf(),
            message: message.into(),
            category,
            children,
        }
    }

    /// Adds a child validation error to this error.
    pub fn add_child(&mut self, error: ValidationError) {
        self.children.push(error);
    }
}

impl fmt::Display for ValidationError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        writeln!(f, "At {}: {}", self.path.display(), self.message)?;
        for child in &self.children {
            write!(f, "  ")?;
            write!(f, "{}", child)?;
        }
        Ok(())
    }
}

impl Error for ValidationError {}

/// Result type for validation operations that may return multiple validation errors.
pub type ValidationResult = Result<(), ValidationError>;

impl Node {
    /// Validates a filesystem path against this node, collecting all validation errors.
    ///
    /// This method checks whether the given path matches the requirements specified by this node.
    /// For file nodes, it verifies the file exists (if required) and matches the name/pattern.
    /// For directory nodes, it checks the directory exists (if required), matches the name/pattern,
    /// and contains the expected children.
    ///
    /// # Arguments
    ///
    /// * `path` - The direct filesystem path to the item (file or directory) to validate
    ///
    /// # Returns
    ///
    /// * `Ok(())` - If the path matches the requirements
    /// * `Err(ValidationError)` - If the path doesn't match, with all validation errors found
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use fsvalidator::model::{DirNode, FileNode, NodeName};
    ///
    /// // Create a validation model
    /// let file_node = FileNode::new(NodeName::Literal("README.md".to_string()), true);
    ///
    /// // Validate a path
    /// let result = file_node.validate("./project/README.md");
    /// assert!(result.is_ok());
    /// ```
    pub fn validate(&self, path: impl AsRef<Path>) -> ValidationResult {
        let path = path.as_ref();
        match self {
            Node::File(file_rc) => {
                let file = file_rc.borrow();
                validate_file(&file, path)
            }

            Node::Dir(dir_rc) => {
                let dir = dir_rc.borrow();
                validate_dir(&dir, path)
            }
        }
    }
}

/// Validates a filesystem path against a file node.
///
/// Checks if the file exists (when required) and matches the specified name or pattern.
///
/// # Arguments
///
/// * `file` - The file node to validate against
/// * `file_path` - The direct path to the file to validate
///
/// # Returns
///
/// * `Ok(())` - If validation succeeds
/// * `Err(ValidationError)` - If validation fails, containing all validation errors
fn validate_file(file: &FileNode, file_path: &Path) -> ValidationResult {
    // Check if the file exists and is actually a file
    if file_path.exists() {
        if !file_path.is_file() {
            return Err(ValidationError::new(
                file_path,
                format!("Path exists but is not a file"),
                ErrorCategory::WrongType,
            ));
        }

        // Get the file name to check against the pattern
        let file_name = match file_path.file_name() {
            Some(name) => name.to_string_lossy().to_string(),
            None => {
                return Err(ValidationError::new(
                    file_path,
                    format!("Invalid file path (no filename)"),
                    ErrorCategory::Other,
                ))
            }
        };

        match &file.name {
            NodeName::Literal(name) => {
                if &file_name != name {
                    return Err(ValidationError::new(
                        file_path,
                        format!(
                            "File name '{}' doesn't match expected name '{}'",
                            file_name, name
                        ),
                        ErrorCategory::NameMismatch,
                    ));
                }
                Ok(())
            }
            NodeName::Pattern(pattern) => {
                let re = match Regex::new(pattern) {
                    Ok(re) => re,
                    Err(e) => {
                        return Err(ValidationError::new(
                            file_path,
                            format!("Invalid regex pattern '{}': {}", pattern, e),
                            ErrorCategory::InvalidPattern,
                        ));
                    }
                };

                if re.is_match(&file_name) {
                    Ok(())
                } else {
                    Err(ValidationError::new(
                        file_path,
                        format!(
                            "File name '{}' doesn't match expected pattern '{}'",
                            file_name, pattern
                        ),
                        ErrorCategory::NameMismatch,
                    ))
                }
            }
        }
    } else if file.required {
        Err(ValidationError::new(
            file_path,
            format!("Missing required file"),
            ErrorCategory::Missing,
        ))
    } else {
        Ok(())
    }
}

/// Validates a filesystem path against a directory node.
///
/// Checks if the directory exists (when required), matches the specified name or pattern,
/// contains the expected children, and doesn't contain unexpected entries (when allow_defined_only is true).
///
/// # Arguments
///
/// * `dir` - The directory node to validate against
/// * `dir_path` - The direct path to the directory to validate
///
/// # Returns
///
/// * `Ok(())` - If validation succeeds
/// * `Err(ValidationError)` - If validation fails, containing all validation errors
fn validate_dir(dir: &DirNode, dir_path: &Path) -> ValidationResult {
    // Check if the directory exists and is actually a directory
    if !dir_path.exists() {
        return if dir.required {
            Err(ValidationError::new(
                dir_path,
                format!("Missing required directory"),
                ErrorCategory::Missing,
            ))
        } else {
            Ok(())
        };
    }

    if !dir_path.is_dir() {
        return Err(ValidationError::new(
            dir_path,
            format!("Path exists but is not a directory"),
            ErrorCategory::WrongType,
        ));
    }

    // Get the directory name to check against pattern/literal
    let dir_name = match dir_path.file_name() {
        Some(name) => name.to_string_lossy().to_string(),
        None => {
            return Err(ValidationError::new(
                dir_path,
                format!("Invalid directory path (no directory name)"),
                ErrorCategory::Other,
            ));
        }
    };

    let mut validation_errors = Vec::new();

    // Validate directory name against expected name/pattern
    match &dir.name {
        NodeName::Literal(name) => {
            if &dir_name != name {
                validation_errors.push(ValidationError::new(
                    dir_path,
                    format!(
                        "Directory name '{}' doesn't match expected name '{}'",
                        dir_name, name
                    ),
                    ErrorCategory::NameMismatch,
                ));
            }
        }
        NodeName::Pattern(pattern) => {
            let re = match Regex::new(pattern) {
                Ok(re) => re,
                Err(e) => {
                    return Err(ValidationError::new(
                        dir_path,
                        format!("Invalid regex pattern '{}': {}", pattern, e),
                        ErrorCategory::InvalidPattern,
                    ));
                }
            };

            if !re.is_match(&dir_name) {
                validation_errors.push(ValidationError::new(
                    dir_path,
                    format!(
                        "Directory name '{}' doesn't match expected pattern '{}'",
                        dir_name, pattern
                    ),
                    ErrorCategory::NameMismatch,
                ));
            }
        }
    }

    // Check for unexpected entries if allow_defined_only is true
    if dir.allow_defined_only {
        let expected_names: Vec<String> = dir
            .children
            .iter()
            .map(|node| match node {
                Node::File(f) => f.borrow().name_name_string(),
                Node::Dir(d) => d.borrow().name_name_string(),
            })
            .collect();

        let read_dir_result = match fs::read_dir(dir_path) {
            Ok(entries) => entries,
            Err(e) => {
                validation_errors.push(ValidationError::new(
                    dir_path,
                    format!("Failed to read directory: {}", e),
                    ErrorCategory::IoError,
                ));
                // Cannot continue checking entries
                if !validation_errors.is_empty() {
                    return Err(ValidationError::with_children(
                        dir_path,
                        format!("Directory validation failed with {} errors", validation_errors.len()),
                        ErrorCategory::Other,
                        validation_errors,
                    ));
                }
                return Ok(());
            }
        };

        for entry_result in read_dir_result {
            let entry = match entry_result {
                Ok(e) => e,
                Err(e) => {
                    validation_errors.push(ValidationError::new(
                        dir_path,
                        format!("Failed to read directory entry: {}", e),
                        ErrorCategory::IoError,
                    ));
                    continue;
                }
            };

            if dir
                .excluded
                .iter()
                .any(|re| re.is_match(entry.file_name().to_string_lossy().to_string().as_str()))
            {
                continue;
            }

            let name = entry.file_name().to_string_lossy().to_string();
            if !expected_names.iter().any(|p| pattern_match(p, &name)) {
                validation_errors.push(ValidationError::new(
                    entry.path(),
                    format!("Unexpected entry in directory"),
                    ErrorCategory::Unexpected,
                ));
            }
        }
    }

    // Validate children
    let mut child_errors = Vec::new();
    for child in &dir.children {
        // For child nodes, we need to find the actual path of the child
        match child {
            Node::File(f_rc) => {
                let f = f_rc.borrow();
                match &f.name {
                    NodeName::Literal(name) => {
                        let child_path = dir_path.join(name);
                        if let Err(err) = child.validate(&child_path) {
                            child_errors.push(err);
                        }
                    }
                    NodeName::Pattern(pattern) => {
                        let re = match Regex::new(pattern) {
                            Ok(re) => re,
                            Err(e) => {
                                validation_errors.push(ValidationError::new(
                                    dir_path,
                                    format!("Invalid regex pattern '{}': {}", pattern, e),
                                    ErrorCategory::InvalidPattern,
                                ));
                                continue;
                            }
                        };

                        let read_dir_result = match fs::read_dir(dir_path) {
                            Ok(entries) => entries,
                            Err(e) => {
                                validation_errors.push(ValidationError::new(
                                    dir_path,
                                    format!("Failed to read directory when matching pattern: {}", e),
                                    ErrorCategory::IoError,
                                ));
                                continue;
                            }
                        };

                        let mut matched_path = None;
                        for entry_result in read_dir_result {
                            let entry = match entry_result {
                                Ok(e) => e,
                                Err(e) => {
                                    validation_errors.push(ValidationError::new(
                                        dir_path,
                                        format!("Failed to read directory entry: {}", e),
                                        ErrorCategory::IoError,
                                    ));
                                    continue;
                                }
                            };

                            if dir.excluded.iter().any(|re| {
                                re.is_match(
                                    entry.file_name().to_string_lossy().to_string().as_str(),
                                )
                            }) {
                                continue;
                            }

                            if entry.path().is_file() {
                                let name = entry.file_name().to_string_lossy().to_string();
                                if re.is_match(&name) {
                                    matched_path = Some(entry.path());
                                    break;
                                }
                            }
                        }

                        match matched_path {
                            Some(path) => {
                                if let Err(err) = child.validate(&path) {
                                    child_errors.push(err);
                                }
                            }
                            None => {
                                if f.required {
                                    validation_errors.push(ValidationError::new(
                                        dir_path,
                                        format!(
                                            "Missing required file matching pattern: {}",
                                            pattern
                                        ),
                                        ErrorCategory::Missing,
                                    ));
                                }
                            }
                        }
                    }
                }
            }

            Node::Dir(d_rc) => {
                let d = d_rc.borrow();
                match &d.name {
                    NodeName::Literal(name) => {
                        let child_path = dir_path.join(name);
                        if let Err(err) = child.validate(&child_path) {
                            child_errors.push(err);
                        }
                    }
                    NodeName::Pattern(pattern) => {
                        let re = match Regex::new(pattern) {
                            Ok(re) => re,
                            Err(e) => {
                                validation_errors.push(ValidationError::new(
                                    dir_path,
                                    format!("Invalid regex pattern '{}': {}", pattern, e),
                                    ErrorCategory::InvalidPattern,
                                ));
                                continue;
                            }
                        };

                        let read_dir_result = match fs::read_dir(dir_path) {
                            Ok(entries) => entries,
                            Err(e) => {
                                validation_errors.push(ValidationError::new(
                                    dir_path,
                                    format!("Failed to read directory when matching pattern: {}", e),
                                    ErrorCategory::IoError,
                                ));
                                continue;
                            }
                        };

                        let mut matched_paths = vec![];
                        for entry_result in read_dir_result {
                            let entry = match entry_result {
                                Ok(e) => e,
                                Err(e) => {
                                    validation_errors.push(ValidationError::new(
                                        dir_path,
                                        format!("Failed to read directory entry: {}", e),
                                        ErrorCategory::IoError,
                                    ));
                                    continue;
                                }
                            };

                            if dir.excluded.iter().any(|re| {
                                re.is_match(
                                    entry.file_name().to_string_lossy().to_string().as_str(),
                                )
                            }) {
                                continue;
                            }
                            if entry.path().is_dir() {
                                let name = entry.file_name().to_string_lossy().to_string();
                                if re.is_match(&name) {
                                    matched_paths.push(entry.path());
                                }
                            }
                        }

                        if matched_paths.is_empty() {
                            if d.required {
                                validation_errors.push(ValidationError::new(
                                    dir_path,
                                    format!(
                                        "Missing required directory matching pattern: {}",
                                        pattern
                                    ),
                                    ErrorCategory::Missing,
                                ));
                            }
                        } else {
                            // Validate all matching directories
                            for matched_path in matched_paths {
                                if let Err(err) = child.validate(&matched_path) {
                                    child_errors.push(err);
                                }
                            }
                        }
                    }
                }
            }
        };
    }

    // Combine all validation errors
    validation_errors.extend(child_errors);

    if validation_errors.is_empty() {
        Ok(())
    } else {
        Err(ValidationError::with_children(
            dir_path,
            format!("Directory validation failed with {} errors", validation_errors.len()),
            ErrorCategory::Other,
            validation_errors,
        ))
    }
}

/// Checks if a name matches a pattern string.
///
/// If the pattern starts with "PATTERN(", it's treated as a regex pattern.
/// Otherwise, it's treated as a literal string that must match exactly.
///
/// # Arguments
///
/// * `pattern` - The pattern string (either a regex pattern or literal)
/// * `name` - The name to check against the pattern
///
/// # Returns
///
/// * `true` if the name matches the pattern
/// * `false` if the name doesn't match
fn pattern_match(pattern: &str, name: &str) -> bool {
    if pattern.starts_with("PATTERN(") && pattern.ends_with(")") {
        let inner = &pattern[8..pattern.len() - 1]; // Extract regex pattern
        match Regex::new(inner) {
            Ok(re) => re.is_match(name),
            Err(e) => {
                eprintln!("Error compiling regex pattern '{}': {}", inner, e);
                false
            }
        }
    } else {
        pattern == name
    }
}

/// Converts a `ValidationResult` to a standard `anyhow::Result`.
///
/// This helper function is useful for code that can't work with a ValidationResult directly.
pub fn to_anyhow_result(result: ValidationResult) -> Result<()> {
    match result {
        Ok(()) => Ok(()),
        Err(validation_err) => Err(anyhow!(validation_err.to_string())),
    }
}

/// A trait for converting a NodeName to a string representation.
///
/// This is used internally for comparing node names during validation.
trait NameString {
    /// Converts a node name to a string representation.
    fn name_name_string(&self) -> String;
}

impl NameString for DirNode {
    fn name_name_string(&self) -> String {
        match &self.name {
            NodeName::Literal(s) => s.clone(),
            NodeName::Pattern(p) => format!("PATTERN({})", p),
        }
    }
}

impl NameString for FileNode {
    fn name_name_string(&self) -> String {
        match &self.name {
            NodeName::Literal(s) => s.clone(),
            NodeName::Pattern(p) => format!("PATTERN({})", p),
        }
    }
}