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
//! # Model
//!
//! Defines the core data structures used for filesystem validation.
//!
//! This module contains the primary types used to represent filesystem validation models
//! including files, directories, and naming patterns.
//!
//! The module provides two ways to create validation models:
//! 
//! 1. Using the constructors directly: `FileNode::new()` and `DirNode::new()`
//! 2. Using the fluent builder API: `ModelBuilder::new_dir()` or `ModelBuilder::new_file()`

use std::{cell::RefCell, rc::Rc};

use regex::Regex;

/// Represents a name for a file or directory, which can be either a literal string or a regex pattern.
#[derive(Debug, PartialEq, Clone)]
pub enum NodeName {
    /// A literal, exact name that must match exactly
    Literal(String),
    /// A regex pattern that the name must match
    Pattern(String),
}

/// Represents a node in the filesystem validation tree, which can be either a file or directory.
#[derive(Debug, Clone)]
pub enum Node {
    /// A directory node, which can contain child nodes
    Dir(Rc<RefCell<DirNode>>),
    /// A file node (leaf node)
    File(Rc<RefCell<FileNode>>),
}

/// Represents a directory in the filesystem validation model.
#[derive(Debug, Clone)]
pub struct DirNode {
    /// The name of the directory (literal or pattern)
    pub name: NodeName,
    /// Child nodes contained within this directory
    pub children: Vec<Node>,
    /// Whether this directory is required to exist
    pub required: bool,
    /// Whether only specified children are allowed (restricts unexpected files/dirs)
    pub allow_defined_only: bool,
    /// Exclude files/dirs from dir children with patterns
    /// The excluded list extends global excluded
    pub excluded: Vec<Regex>,
}

/// Represents a file in the filesystem validation model.
#[derive(Debug, Clone)]
pub struct FileNode {
    /// The name of the file (literal or pattern)
    pub name: NodeName,
    /// Whether this file is required to exist
    pub required: bool,
}

/// A builder to construct filesystem validation models with a fluent API.
///
/// `ModelBuilder` provides an easy way to build complex filesystem validation structures
/// using method chaining. It supports nesting directory structures and returning up the
/// hierarchy.
///
/// # Examples
///
/// ```
/// use fsvalidator::model::{ModelBuilder, NodeName};
///
/// // Create a project structure
/// let project = ModelBuilder::new_dir("project")
///     .required(true)
///     .allow_defined_only(true)
///     .add_file("README.md", true)
///     .add_dir("src", true)
///         .add_file_pattern(".*\\.rs", true)
///         .up()
///     .add_dir("tests", false)
///         .add_file_pattern("test_.*\\.rs", false)
///         .build();
/// ```
pub struct ModelBuilder {
    /// Current node being built
    current: Node,
    /// Stack of parent builders
    parent_stack: Vec<ModelBuilder>,
}

impl ModelBuilder {
    /// Creates a new builder for a directory with the given literal name.
    ///
    /// # Arguments
    ///
    /// * `name` - The literal name of the directory
    ///
    /// # Returns
    ///
    /// A new builder for a directory node
    pub fn new_dir(name: impl Into<String>) -> Self {
        Self {
            current: DirNode::new(
                NodeName::Literal(name.into()),
                vec![],
                false,
                false,
                vec![],
            ),
            parent_stack: vec![],
        }
    }

    /// Creates a new builder for a directory with the given regex pattern.
    ///
    /// # Arguments
    ///
    /// * `pattern` - The regex pattern for the directory name
    ///
    /// # Returns
    ///
    /// A new builder for a directory node
    pub fn new_dir_pattern(pattern: impl Into<String>) -> Self {
        Self {
            current: DirNode::new(
                NodeName::Pattern(pattern.into()),
                vec![],
                false,
                false,
                vec![],
            ),
            parent_stack: vec![],
        }
    }

    /// Creates a new builder for a file with the given literal name.
    ///
    /// # Arguments
    ///
    /// * `name` - The literal name of the file
    ///
    /// # Returns
    ///
    /// A new builder for a file node
    pub fn new_file(name: impl Into<String>) -> Self {
        Self {
            current: FileNode::new(NodeName::Literal(name.into()), false),
            parent_stack: vec![],
        }
    }

    /// Creates a new builder for a file with the given regex pattern.
    ///
    /// # Arguments
    ///
    /// * `pattern` - The regex pattern for the file name
    ///
    /// # Returns
    ///
    /// A new builder for a file node
    pub fn new_file_pattern(pattern: impl Into<String>) -> Self {
        Self {
            current: FileNode::new(NodeName::Pattern(pattern.into()), false),
            parent_stack: vec![],
        }
    }

    /// Sets whether the current node is required to exist.
    ///
    /// # Arguments
    ///
    /// * `required` - Whether the node is required
    ///
    /// # Returns
    ///
    /// Self for method chaining
    pub fn required(self, required: bool) -> Self {
        match &self.current {
            Node::Dir(dir_rc) => {
                dir_rc.borrow_mut().required = required;
            }
            Node::File(file_rc) => {
                file_rc.borrow_mut().required = required;
            }
        };
        self
    }

    /// Sets whether the current directory should only allow defined children.
    ///
    /// # Arguments
    ///
    /// * `allow_defined_only` - Whether to only allow defined children
    ///
    /// # Returns
    ///
    /// Self for method chaining
    ///
    /// # Panics
    ///
    /// Panics if the current node is a file node.
    pub fn allow_defined_only(self, allow_defined_only: bool) -> Self {
        if let Node::Dir(dir_rc) = &self.current {
            dir_rc.borrow_mut().allow_defined_only = allow_defined_only;
        } else {
            panic!("Cannot set allow_defined_only on a file node");
        }
        self
    }

    /// Adds excluded regex patterns to the current directory.
    ///
    /// # Arguments
    ///
    /// * `patterns` - Regex patterns to exclude
    ///
    /// # Returns
    ///
    /// Self for method chaining
    ///
    /// # Panics
    ///
    /// Panics if the current node is a file node.
    pub fn exclude_patterns(self, patterns: Vec<impl Into<String>>) -> Self {
        if let Node::Dir(dir_rc) = &self.current {
            let mut dir = dir_rc.borrow_mut();
            for pattern in patterns {
                dir.excluded.push(Regex::new(&pattern.into()).unwrap());
            }
        } else {
            panic!("Cannot add excluded patterns to a file node");
        }
        self
    }

    /// Adds a child file with a literal name to the current directory.
    ///
    /// # Arguments
    ///
    /// * `name` - The literal name of the file
    /// * `required` - Whether the file is required
    ///
    /// # Returns
    ///
    /// Self for method chaining
    ///
    /// # Panics
    ///
    /// Panics if the current node is a file node.
    pub fn add_file(self, name: impl Into<String>, required: bool) -> Self {
        if let Node::Dir(dir_rc) = &self.current {
            let file_node = FileNode::new(NodeName::Literal(name.into()), required);
            dir_rc.borrow_mut().children.push(file_node);
        } else {
            panic!("Cannot add a child to a file node");
        }
        self
    }

    /// Adds a child file with a regex pattern to the current directory.
    ///
    /// # Arguments
    ///
    /// * `pattern` - The regex pattern for the file name
    /// * `required` - Whether the file is required
    ///
    /// # Returns
    ///
    /// Self for method chaining
    ///
    /// # Panics
    ///
    /// Panics if the current node is a file node.
    pub fn add_file_pattern(self, pattern: impl Into<String>, required: bool) -> Self {
        if let Node::Dir(dir_rc) = &self.current {
            let file_node = FileNode::new(NodeName::Pattern(pattern.into()), required);
            dir_rc.borrow_mut().children.push(file_node);
        } else {
            panic!("Cannot add a child to a file node");
        }
        self
    }

    /// Adds a child directory to the current directory and returns a builder for the child.
    ///
    /// # Arguments
    ///
    /// * `name` - The literal name of the directory
    /// * `required` - Whether the directory is required
    ///
    /// # Returns
    ///
    /// A builder for the child directory
    ///
    /// # Panics
    ///
    /// Panics if the current node is a file node.
    pub fn add_dir(self, name: impl Into<String>, required: bool) -> Self {
        if let Node::Dir(dir_rc) = &self.current {
            let mut child_builder = Self::new_dir(name);
            child_builder = child_builder.required(required);
            
            let child_node = child_builder.current.clone();
            dir_rc.borrow_mut().children.push(child_node);
            
            // Push the current builder to the stack and return the child builder
            let mut new_builder = child_builder;
            new_builder.parent_stack.push(self);
            new_builder
        } else {
            panic!("Cannot add a child to a file node");
        }
    }

    /// Adds a child directory with a regex pattern to the current directory and returns a builder for the child.
    ///
    /// # Arguments
    ///
    /// * `pattern` - The regex pattern for the directory name
    /// * `required` - Whether the directory is required
    ///
    /// # Returns
    ///
    /// A builder for the child directory
    ///
    /// # Panics
    ///
    /// Panics if the current node is a file node.
    pub fn add_dir_pattern(self, pattern: impl Into<String>, required: bool) -> Self {
        if let Node::Dir(dir_rc) = &self.current {
            let mut child_builder = Self::new_dir_pattern(pattern);
            child_builder = child_builder.required(required);
            
            let child_node = child_builder.current.clone();
            dir_rc.borrow_mut().children.push(child_node);
            
            // Push the current builder to the stack and return the child builder
            let mut new_builder = child_builder;
            new_builder.parent_stack.push(self);
            new_builder
        } else {
            panic!("Cannot add a child to a file node");
        }
    }

    /// Moves up to the parent builder.
    ///
    /// # Returns
    ///
    /// The parent builder
    ///
    /// # Panics
    ///
    /// Panics if there is no parent (this is the root builder).
    pub fn up(mut self) -> Self {
        if !self.parent_stack.is_empty() {
            // Pop the parent builder from the stack and return it
            self.parent_stack.pop().expect("Parent stack is empty")
        } else {
            panic!("Cannot move up from the root builder");
        }
    }

    /// Completes the building process and returns the constructed node.
    ///
    /// # Returns
    ///
    /// The constructed `Node`
    pub fn build(self) -> Node {
        self.current
    }
}

// Implement Clone for ModelBuilder
impl Clone for ModelBuilder {
    fn clone(&self) -> Self {
        Self {
            current: self.current.clone(),
            parent_stack: self.parent_stack.clone(),
        }
    }
}

impl DirNode {
    /// Creates a new directory node with the specified properties.
    ///
    /// # Arguments
    ///
    /// * `name` - The name of the directory (literal or pattern)
    /// * `children` - List of child nodes contained in this directory
    /// * `required` - Whether this directory is required to exist
    /// * `allow_defined_only` - Whether only specified children are allowed
    /// * `excluded` - Regex patterns for files/dirs to exclude from validation
    ///
    /// # Returns
    ///
    /// A new `Node::Dir` containing the directory node
    #[allow(clippy::new_ret_no_self)]
    pub fn new(
        name: NodeName,
        children: Vec<Node>,
        required: bool,
        allow_defined_only: bool,
        excluded: Vec<Regex>,
    ) -> Node {
        Node::Dir(Rc::new(RefCell::new(Self {
            name,
            children,
            required,
            allow_defined_only,
            excluded,
        })))
    }
}

impl FileNode {
    /// Creates a new file node with the specified properties.
    ///
    /// # Arguments
    ///
    /// * `name` - The name of the file (literal or pattern)
    /// * `required` - Whether this file is required to exist
    ///
    /// # Returns
    ///
    /// A new `Node::File` containing the file node
    #[allow(clippy::new_ret_no_self)]
    pub fn new(name: NodeName, required: bool) -> Node {
        Node::File(Rc::new(RefCell::new(Self { name, required })))
    }
}