dynamic-cli 0.2.0

A framework for building configurable CLI and REPL applications from YAML/JSON configuration files
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
//! File validation functions
//!
//! This module provides functions to validate file paths according to
//! [`ValidationRule::MustExist`] and [`ValidationRule::Extensions`].
//!
//! # Functions
//!
//! - [`validate_file_exists`] - Check if a file or directory exists
//! - [`validate_file_extension`] - Check if a file has an allowed extension
//!
//! # Example
//!
//! ```no_run
//! use dynamic_cli::validator::file_validator::{validate_file_exists, validate_file_extension};
//! use std::path::Path;
//!
//! let path = Path::new("config.yaml");
//!
//! // Validate file exists
//! validate_file_exists(path, "config_file")?;
//!
//! // Validate file extension
//! let allowed = vec!["yaml".to_string(), "yml".to_string()];
//! validate_file_extension(path, "config_file", &allowed)?;
//! # Ok::<(), dynamic_cli::error::DynamicCliError>(())
//! ```

use crate::error::{Result, ValidationError};
use std::path::Path;

/// Validate that a file or directory exists
///
/// This function checks if the given path exists on the file system.
/// It works for both files and directories.
///
/// # Arguments
///
/// * `path` - Path to validate
/// * `arg_name` - Name of the argument (for error messages)
///
/// # Returns
///
/// - `Ok(())` if the path exists
/// - `Err(ValidationError::FileNotFound)` if the path doesn't exist
///
/// # Example
///
/// ```no_run
/// use dynamic_cli::validator::file_validator::validate_file_exists;
/// use std::path::Path;
///
/// let path = Path::new("input.txt");
/// validate_file_exists(path, "input_file")?;
/// # Ok::<(), dynamic_cli::error::DynamicCliError>(())
/// ```
///
/// # Error Messages
///
/// If the file doesn't exist, the error message includes:
/// - The argument name
/// - The full path that was checked
///
/// Example: `File not found for argument 'input_file': "/path/to/input.txt"`
pub fn validate_file_exists(path: &Path, arg_name: &str) -> Result<()> {
    // Check if the path exists on the file system
    // This works for both files and directories
    if !path.exists() {
        return Err(ValidationError::FileNotFound {
            path: path.to_path_buf(),
            arg_name: arg_name.to_string(),
            suggestion: Some("Check that the file exists and the path is correct.".to_string()),
        }
        .into());
    }

    Ok(())
}

/// Validate that a file has one of the expected extensions
///
/// This function checks if the file's extension matches one of the
/// allowed extensions. The comparison is **case-insensitive**.
///
/// # Arguments
///
/// * `path` - Path to the file
/// * `arg_name` - Name of the argument (for error messages)
/// * `expected` - List of allowed extensions (without the leading dot)
///
/// # Returns
///
/// - `Ok(())` if the file has an allowed extension
/// - `Err(ValidationError::InvalidExtension)` if the extension doesn't match
///
/// # Extension Format
///
/// Extensions should be specified **without** the leading dot:
/// - ✅ Correct: `["yaml", "yml"]`
/// - ❌ Incorrect: `[".yaml", ".yml"]`
///
/// # Case Sensitivity
///
/// The validation is **case-insensitive**:
/// - `"config.YAML"` matches `["yaml"]` ✅
/// - `"config.Yml"` matches `["yml"]` ✅
///
/// # Example
///
/// ```no_run
/// use dynamic_cli::validator::file_validator::validate_file_extension;
/// use std::path::Path;
///
/// let path = Path::new("config.yaml");
/// let allowed = vec!["yaml".to_string(), "yml".to_string()];
///
/// validate_file_extension(path, "config_file", &allowed)?;
/// # Ok::<(), dynamic_cli::error::DynamicCliError>(())
/// ```
///
/// # Error Messages
///
/// If the extension is invalid, the error includes:
/// - The argument name
/// - The file path
/// - The list of expected extensions
///
/// Example: `Invalid file extension for config_file: "config.txt". Expected: yaml, yml`
pub fn validate_file_extension(path: &Path, arg_name: &str, expected: &[String]) -> Result<()> {
    // Extract the file extension from the path
    let extension = path
        .extension()
        .and_then(|ext| ext.to_str())
        .map(|ext| ext.to_lowercase());

    // Check if we have an extension
    let ext = match extension {
        Some(e) => e,
        None => {
            // File has no extension
            return Err(ValidationError::InvalidExtension {
                arg_name: arg_name.to_string(),
                path: path.to_path_buf(),
                expected: expected.to_vec(),
            }
            .into());
        }
    };

    // Check if the extension is in the list of allowed extensions
    // Convert expected extensions to lowercase for case-insensitive comparison
    let is_valid = expected.iter().any(|allowed| allowed.to_lowercase() == ext);

    if !is_valid {
        return Err(ValidationError::InvalidExtension {
            arg_name: arg_name.to_string(),
            path: path.to_path_buf(),
            expected: expected.to_vec(),
        }
        .into());
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs::File;
    use std::io::Write;
    use tempfile::TempDir;

    /// Helper to create a temporary file with content
    fn create_temp_file(dir: &TempDir, name: &str, content: &str) -> std::path::PathBuf {
        let file_path = dir.path().join(name);
        let mut file = File::create(&file_path).unwrap();
        file.write_all(content.as_bytes()).unwrap();
        file_path
    }

    // ========================================================================
    // Tests for validate_file_exists
    // ========================================================================

    #[test]
    fn test_validate_file_exists_valid_file() {
        let temp_dir = TempDir::new().unwrap();
        let file_path = create_temp_file(&temp_dir, "test.txt", "content");

        let result = validate_file_exists(&file_path, "test_file");
        assert!(result.is_ok());
    }

    #[test]
    fn test_validate_file_exists_valid_directory() {
        let temp_dir = TempDir::new().unwrap();

        // The temp directory itself exists
        let result = validate_file_exists(temp_dir.path(), "test_dir");
        assert!(result.is_ok());
    }

    #[test]
    fn test_validate_file_exists_nonexistent() {
        let temp_dir = TempDir::new().unwrap();
        let nonexistent = temp_dir.path().join("does_not_exist.txt");

        let result = validate_file_exists(&nonexistent, "missing_file");

        assert!(result.is_err());
        match result.unwrap_err() {
            crate::error::DynamicCliError::Validation(ValidationError::FileNotFound {
                path,
                arg_name,
                ..
            }) => {
                assert_eq!(arg_name, "missing_file");
                assert_eq!(path, nonexistent);
            }
            other => panic!("Expected FileNotFound error, got {:?}", other),
        }
    }

    #[test]
    fn test_validate_file_exists_relative_path() {
        let temp_dir = TempDir::new().unwrap();
        let file_path = create_temp_file(&temp_dir, "relative.txt", "content");

        // Create a relative path by using only the filename
        let relative = std::path::Path::new(file_path.file_name().unwrap());

        // Change to the temp directory
        let original_dir = std::env::current_dir().unwrap();
        std::env::set_current_dir(temp_dir.path()).unwrap();

        let result = validate_file_exists(relative, "relative_file");
        assert!(result.is_ok());

        // Restore original directory
        std::env::set_current_dir(original_dir).unwrap();
    }

    // ========================================================================
    // Tests for validate_file_extension
    // ========================================================================

    #[test]
    fn test_validate_file_extension_valid_single() {
        let path = Path::new("config.yaml");
        let allowed = vec!["yaml".to_string()];

        let result = validate_file_extension(path, "config", &allowed);
        assert!(result.is_ok());
    }

    #[test]
    fn test_validate_file_extension_valid_multiple() {
        let path = Path::new("data.csv");
        let allowed = vec!["csv".to_string(), "tsv".to_string(), "txt".to_string()];

        let result = validate_file_extension(path, "data_file", &allowed);
        assert!(result.is_ok());
    }

    #[test]
    fn test_validate_file_extension_case_insensitive() {
        // File with uppercase extension
        let path1 = Path::new("config.YAML");
        let allowed = vec!["yaml".to_string()];

        assert!(validate_file_extension(path1, "config", &allowed).is_ok());

        // File with mixed case extension
        let path2 = Path::new("config.YaML");
        assert!(validate_file_extension(path2, "config", &allowed).is_ok());

        // Allowed extensions in uppercase
        let path3 = Path::new("config.yaml");
        let allowed_upper = vec!["YAML".to_string()];
        assert!(validate_file_extension(path3, "config", &allowed_upper).is_ok());
    }

    #[test]
    fn test_validate_file_extension_invalid() {
        let path = Path::new("document.txt");
        let allowed = vec!["yaml".to_string(), "yml".to_string()];

        let result = validate_file_extension(path, "doc", &allowed);

        assert!(result.is_err());
        match result.unwrap_err() {
            crate::error::DynamicCliError::Validation(ValidationError::InvalidExtension {
                arg_name,
                path: error_path,
                expected,
            }) => {
                assert_eq!(arg_name, "doc");
                assert_eq!(error_path, path);
                assert_eq!(expected, allowed);
            }
            other => panic!("Expected InvalidExtension error, got {:?}", other),
        }
    }

    #[test]
    fn test_validate_file_extension_no_extension() {
        let path = Path::new("makefile");
        let allowed = vec!["txt".to_string()];

        let result = validate_file_extension(path, "build_file", &allowed);

        assert!(result.is_err());
        match result.unwrap_err() {
            crate::error::DynamicCliError::Validation(ValidationError::InvalidExtension {
                ..
            }) => {
                // Expected
            }
            other => panic!("Expected InvalidExtension error, got {:?}", other),
        }
    }

    #[test]
    fn test_validate_file_extension_hidden_file_with_extension() {
        // Hidden files WITH extensions work normally
        // .hidden.txt has extension "txt"
        let path = Path::new(".hidden.txt");
        let allowed = vec!["txt".to_string()];

        let result = validate_file_extension(path, "hidden_file", &allowed);
        assert!(result.is_ok());
    }

    #[test]
    fn test_validate_file_extension_hidden_file_no_extension() {
        // Pure hidden files (like .gitignore) have NO extension
        // This should fail validation
        let path = Path::new(".gitignore");
        let allowed = vec!["txt".to_string()];

        let result = validate_file_extension(path, "git_file", &allowed);
        // .gitignore has no extension, so validation should fail
        assert!(result.is_err());
    }

    #[test]
    fn test_validate_file_extension_multiple_dots() {
        let path = Path::new("archive.tar.gz");
        let allowed = vec!["gz".to_string()];

        // Only the last extension is checked
        let result = validate_file_extension(path, "archive", &allowed);
        assert!(result.is_ok());
    }

    #[test]
    fn test_validate_file_extension_empty_allowed_list() {
        let path = Path::new("file.txt");
        let allowed: Vec<String> = vec![];

        let result = validate_file_extension(path, "file", &allowed);
        assert!(result.is_err());
    }

    #[test]
    fn test_validate_file_extension_with_leading_dot() {
        // Even though we specify extensions without dots,
        // the function should still work correctly
        let path = Path::new("config.yaml");

        // User mistakenly includes the dot - should still work
        // because we compare lowercase extensions
        let allowed = vec!["yaml".to_string()];

        let result = validate_file_extension(path, "config", &allowed);
        assert!(result.is_ok());
    }

    // ========================================================================
    // Integration tests
    // ========================================================================

    #[test]
    fn test_validate_both_file_and_extension() {
        let temp_dir = TempDir::new().unwrap();
        let file_path = create_temp_file(&temp_dir, "config.yaml", "key: value");

        // First validate existence
        let result1 = validate_file_exists(&file_path, "config_file");
        assert!(result1.is_ok());

        // Then validate extension
        let allowed = vec!["yaml".to_string(), "yml".to_string()];
        let result2 = validate_file_extension(&file_path, "config_file", &allowed);
        assert!(result2.is_ok());
    }

    #[test]
    fn test_validate_wrong_extension_existing_file() {
        let temp_dir = TempDir::new().unwrap();
        let file_path = create_temp_file(&temp_dir, "data.txt", "some data");

        // File exists
        assert!(validate_file_exists(&file_path, "data_file").is_ok());

        // But extension is wrong
        let allowed = vec!["csv".to_string()];
        let result = validate_file_extension(&file_path, "data_file", &allowed);
        assert!(result.is_err());
    }

    #[test]
    fn test_validate_extension_nonexistent_file() {
        // Extension validation doesn't check if file exists
        let path = Path::new("nonexistent.yaml");
        let allowed = vec!["yaml".to_string()];

        // Extension validation succeeds (only checks extension)
        let result = validate_file_extension(path, "config", &allowed);
        assert!(result.is_ok());

        // But existence validation fails
        let result2 = validate_file_exists(path, "config");
        assert!(result2.is_err());
    }
}