mkdir-rs 1.0.4

A robust, production-ready mkdir replacement with brace expansion for Windows
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
// File: src\main.rs
// Author: Hadi Cahyadi <cumulus13@gmail.com>
// Date: 2026-06-16
// Description: A robust mkdir replacement for Windows with brace expansion support
// License: MIT

use anyhow::{Context, Result};
use clap::Parser;
use clap_version_flag::colorful_version;
use std::fs;
use std::path::{Path, PathBuf};

/// A robust mkdir replacement for Windows with brace expansion support
#[derive(Parser, Debug)]
#[command(
    name = "mkdir-rs",
    version,
    about = "Create directories with brace expansion support",
    long_about = "Creates directories with full support for brace expansion patterns like Linux mkdir.\n\nExamples:\n  mkdir-rs dir1/{dir2,dir3,dir4}\n  mkdir-rs -p dir1/{dir2, dir3}\n  mkdir-rs {a,b}/{c,d}\n  mkdir-rs -v project/{src,docs,tests}"
)]
struct Args {
    /// Create parent directories as needed (no error if existing)
    #[arg(short = 'p', long = "parents")]
    parents: bool,

    /// Print a message for each created directory
    #[arg(short = 'v', long = "verbose")]
    verbose: bool,

    /// Set permission mode (ignored on Windows, provided for compatibility)
    #[arg(short = 'm', long = "mode", default_value = "755")]
    mode: String,

    /// Directory patterns to create (supports brace expansion)
    #[arg(required = true, num_args = 1..)]
    patterns: Vec<String>,
}

/// Error types for directory creation operations
#[derive(Debug, thiserror::Error)]
enum MkdirError {
    #[error("Failed to create directory '{path}': {source}")]
    CreationFailed {
        path: String,
        #[source]
        source: std::io::Error,
    },

    #[error("Invalid brace pattern '{pattern}': {reason}")]
    InvalidPattern { pattern: String, reason: String },

    #[error("Empty expansion in pattern '{pattern}'")]
    EmptyExpansion { pattern: String },
}

/// Represents a segment in a path pattern
#[derive(Debug, Clone)]
enum PathSegment {
    Literal(String),
    Expansion(Vec<String>),
}

/// Rejoin arguments that were split by shell due to spaces in brace expansion
fn rejoin_brace_args(args: Vec<String>) -> Vec<String> {
    if args.is_empty() {
        return args;
    }

    let mut result = Vec::new();
    let mut current = String::new();
    let mut brace_depth = 0i32;

    for arg in args {
        if brace_depth > 0 {
            // We're inside braces, append with space
            current.push(' ');
            current.push_str(&arg);
            
            // Count braces in this segment
            for ch in arg.chars() {
                match ch {
                    '{' => brace_depth += 1,
                    '}' => brace_depth -= 1,
                    _ => {}
                }
            }
            
            // If braces are now balanced, we have the complete pattern
            if brace_depth == 0 {
                result.push(current.clone());
                current.clear();
            }
        } else {
            // Check if this argument has unbalanced braces
            let mut open_count = 0i32;
            let mut close_count = 0i32;
            
            for ch in arg.chars() {
                match ch {
                    '{' => open_count += 1,
                    '}' => close_count += 1,
                    _ => {}
                }
            }
            
            brace_depth = open_count - close_count;
            
            if brace_depth > 0 {
                // Unbalanced opening braces, start collecting
                current = arg;
            } else if brace_depth < 0 {
                // Unbalanced closing braces (shouldn't happen at start)
                result.push(arg);
            } else {
                // Balanced braces or no braces
                result.push(arg);
            }
        }
    }

    // If we have remaining unclosed braces, push what we have
    if !current.is_empty() {
        result.push(current);
    }

    result
}

/// Parse a path pattern with brace expansion
fn parse_brace_pattern(pattern: &str) -> Result<Vec<String>, MkdirError> {
    let segments = tokenize_pattern(pattern)?;
    expand_segments(&segments)
        .ok_or_else( || MkdirError::EmptyExpansion {
            pattern: pattern.to_string(),
        })
}

/// Tokenize a pattern into literal and expansion segments
fn tokenize_pattern(pattern: &str) -> Result<Vec<PathSegment>, MkdirError> {
    let mut segments = Vec::new();
    let chars: Vec<char> = pattern.chars().collect();
    let len = chars.len();
    let mut i = 0;

    while i < len {
        match chars[i] {
            '{' => {
                // Find matching closing brace
                let mut brace_count = 1;
                let mut j = i + 1;
                let mut found = false;

                while j < len {
                    match chars[j] {
                        '{' => brace_count += 1,
                        '}' => {
                            brace_count -= 1;
                            if brace_count == 0 {
                                found = true;
                                break;
                            }
                        }
                        _ => {}
                    }
                    j += 1;
                }

                if !found {
                    return Err(MkdirError::InvalidPattern {
                        pattern: pattern.to_string(),
                        reason: "Unmatched opening brace".to_string(),
                    });
                }

                // Extract content between braces
                let content: String = chars[i + 1..j].iter().collect();

                // Split by comma, preserving whitespace
                let parts: Vec<String> = if content.contains(',') {
                    content.split(',')
                        .map(|s| s.to_string())
                        .collect()
                } else {
                    vec![content]
                };

                if parts.is_empty() || parts.iter().all(|s| s.is_empty()) {
                    return Err(MkdirError::InvalidPattern {
                        pattern: pattern.to_string(),
                        reason: "Empty brace expansion".to_string(),
                    });
                }

                segments.push(PathSegment::Expansion(parts));
                i = j + 1;
            }
            '}' => {
                return Err(MkdirError::InvalidPattern {
                    pattern: pattern.to_string(),
                    reason: "Unmatched closing brace".to_string(),
                });
            }
            _ => {
                // Collect literal characters until next brace or end
                let start = i;
                while i < len && chars[i] != '{' && chars[i] != '}' {
                    i += 1;
                }
                let literal: String = chars[start..i].iter().collect();
                if !literal.is_empty() {
                    segments.push(PathSegment::Literal(literal));
                }
                // Don't increment i here, as we're at a brace or end
                if i < len && chars[i] == '}' {
                    return Err(MkdirError::InvalidPattern {
                        pattern: pattern.to_string(),
                        reason: "Unmatched closing brace".to_string(),
                    });
                }
            }
        }
    }

    Ok(segments)
}

/// Expand tokenized segments into all possible path combinations
fn expand_segments(segments: &[PathSegment]) -> Option<Vec<String>> {
    if segments.is_empty() {
        return Some(vec![String::new()]);
    }

    let mut results: Vec<String> = vec![String::new()];

    for segment in segments {
        let mut new_results = Vec::new();

        match segment {
            PathSegment::Literal(s) => {
                for existing in &results {
                    new_results.push(format!("{}{}", existing, s));
                }
            }
            PathSegment::Expansion(options) => {
                if options.is_empty() {
                    return None;
                }
                for existing in &results {
                    for option in options {
                        new_results.push(format!("{}{}", existing, option));
                    }
                }
            }
        }

        results = new_results;
    }

    Some(results)
}

/// Normalize path separators for Windows
fn normalize_path(path: &str) -> String {
    path.replace('/', "\\")
}

/// Check if a path contains brace patterns
fn has_brace_expansion(path: &str) -> bool {
    path.contains('{') && path.contains('}')
}

/// Create a directory with proper error handling
/// For paths with brace expansion, always create parent directories automatically
fn create_directory(path: &Path, use_create_all: bool, verbose: bool) -> Result<()> {
    let result = if use_create_all {
        fs::create_dir_all(path)
    } else {
        fs::create_dir(path)
    };

    match result {
        Ok(()) => {
            if verbose {
                println!("mkdir-rs: created directory '{}'", path.display());
            }
            Ok(())
        }
        Err(e) => {
            if e.kind() == std::io::ErrorKind::AlreadyExists && use_create_all {
                // With create_dir_all, existing directories are not an error
                if verbose {
                    println!("mkdir-rs: directory '{}' already exists", path.display());
                }
                Ok(())
            } else {
                Err(MkdirError::CreationFailed {
                    path: path.display().to_string(),
                    source: e,
                }.into())
            }
        }
    }
}

/// Process patterns and create directories
fn process_patterns(args: &Args) -> Result<()> {
    let mut created_count = 0;
    let mut error_count = 0;

    // Rejoin arguments that were split by shell
    let joined_patterns = rejoin_brace_args(args.patterns.clone());

    for pattern in &joined_patterns {
        // Check if pattern contains brace expansion
        let has_braces = has_brace_expansion(pattern);
        
        // Parse and expand the pattern
        let expanded = match parse_brace_pattern(pattern) {
            Ok(paths) => paths,
            Err(e) => {
                eprintln!("Error: {}", e);
                error_count += 1;
                continue;
            }
        };

        // For brace expansion patterns, always create parent directories
        // For simple patterns, use the -p flag behavior
        let use_create_all = has_braces || args.parents;

        // Create each expanded path
        for path_str in &expanded {
            let normalized = normalize_path(path_str);
            let path = PathBuf::from(&normalized);

            match create_directory(&path, use_create_all, args.verbose) {
                Ok(()) => created_count += 1,
                Err(e) => {
                    eprintln!("Error: {}", e);
                    error_count += 1;
                }
            }
        }
    }

    if error_count > 0 {
        anyhow::bail!(
            "Failed to create {} director{} ({} created successfully)",
            error_count,
            if error_count == 1 { "y" } else { "ies" },
            created_count
        );
    }

    if args.verbose {
        println!(
            "mkdir-rs: created {} director{}",
            created_count,
            if created_count == 1 { "y" } else { "ies" }
        );
    }

    Ok(())
}

fn main() -> Result<()> {
    let os_args: Vec<String> = std::env::args().collect();
    if os_args.len() == 2 && (os_args[1] == "-V" || os_args[1] == "--version") {
        let version = colorful_version!();
        version.print_and_exit();
    }

    let args = Args::parse();

    // Validate mode parameter (Windows compatibility warning)
    if args.mode != "755" && cfg!(windows) {
        eprintln!("Warning: Mode setting is ignored on Windows");
    }

    process_patterns(&args).with_context(|| "Failed to create directories")?;

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashSet;

    #[test]
    fn test_simple_brace_expansion() {
        let result = parse_brace_pattern("dir1/{dir2,dir3,dir4}").unwrap();
        let expected: HashSet<String> = ["dir1/dir2", "dir1/dir3", "dir1/dir4"]
            .iter()
            .map(|s| normalize_path(s))
            .collect();
        let actual: HashSet<String> = result.into_iter().collect();
        assert_eq!(actual, expected);
    }

    #[test]
    fn test_brace_expansion_with_spaces() {
        let result = parse_brace_pattern("dir1/{dir2, dir3, dir4}").unwrap();
        let expected: HashSet<String> = [
            "dir1/dir2",
            "dir1/ dir3",
            "dir1/ dir4",
        ]
        .iter()
        .map(|s| normalize_path(s))
        .collect();
        let actual: HashSet<String> = result.into_iter().collect();
        assert_eq!(actual, expected);
    }

    #[test]
    fn test_nested_brace_expansion() {
        let result = parse_brace_pattern("{a,b}/{c,d}").unwrap();
        let expected: HashSet<String> = ["a/c", "a/d", "b/c", "b/d"]
            .iter()
            .map(|s| normalize_path(s))
            .collect();
        let actual: HashSet<String> = result.into_iter().collect();
        assert_eq!(actual, expected);
    }

    #[test]
    fn test_single_directory() {
        let result = parse_brace_pattern("simple_dir").unwrap();
        assert_eq!(result.len(), 1);
        assert_eq!(normalize_path(&result[0]), normalize_path("simple_dir"));
    }

    #[test]
    fn test_multiple_expansions() {
        let result = parse_brace_pattern("project/{src/{main,test},docs}").unwrap();
        let expected: HashSet<String> = [
            "project/src/main",
            "project/src/test",
            "project/docs",
        ]
        .iter()
        .map(|s| normalize_path(s))
        .collect();
        let actual: HashSet<String> = result.into_iter().collect();
        assert_eq!(actual, expected);
    }

    #[test]
    fn test_empty_expansion_error() {
        let result = parse_brace_pattern("dir/{}");
        assert!(result.is_err());
    }

    #[test]
    fn test_unmatched_brace_error() {
        let result = parse_brace_pattern("dir/{a,b");
        assert!(result.is_err());
    }

    #[test]
    fn test_path_normalization() {
        assert_eq!(normalize_path("a/b/c"), "a\\b\\c");
        assert_eq!(normalize_path("a\\b\\c"), "a\\b\\c");
        assert_eq!(normalize_path("a/b\\c"), "a\\b\\c");
    }

    #[test]
    fn test_has_brace_expansion() {
        assert!(has_brace_expansion("dir/{a,b}"));
        assert!(!has_brace_expansion("simple_dir"));
        assert!(has_brace_expansion("{a,b}/{c,d}"));
    }

    #[test]
    fn test_rejoin_brace_args() {
        let args = vec![
            "TEST3\\{TEST4,".to_string(),
            "TEST5}".to_string(),
        ];
        let result = rejoin_brace_args(args);
        assert_eq!(result, vec!["TEST3\\{TEST4, TEST5}"]);

        let args2 = vec![
            "dir1/{dir2,".to_string(),
            "dir3,".to_string(),
            "dir4}".to_string(),
        ];
        let result2 = rejoin_brace_args(args2);
        assert_eq!(result2, vec!["dir1/{dir2, dir3, dir4}"]);

        // No braces
        let args3 = vec!["simple_dir".to_string()];
        let result3 = rejoin_brace_args(args3);
        assert_eq!(result3, vec!["simple_dir"]);

        // Multiple patterns with braces
        let args4 = vec![
            "{a,b}".to_string(),
            "dir1/{dir2,".to_string(),
            "dir3}".to_string(),
        ];
        let result4 = rejoin_brace_args(args4);
        assert_eq!(result4, vec!["{a,b}", "dir1/{dir2, dir3}"]);
    }
}