use anyhow::{Context, Result};
use clap::Parser;
use clap_version_flag::colorful_version;
use std::fs;
use std::path::{Path, PathBuf};
#[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 {
#[arg(short = 'p', long = "parents")]
parents: bool,
#[arg(short = 'v', long = "verbose")]
verbose: bool,
#[arg(short = 'm', long = "mode", default_value = "755")]
mode: String,
#[arg(required = true, num_args = 1..)]
patterns: Vec<String>,
}
#[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 },
}
#[derive(Debug, Clone)]
enum PathSegment {
Literal(String),
Expansion(Vec<String>),
}
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 {
current.push(' ');
current.push_str(&arg);
for ch in arg.chars() {
match ch {
'{' => brace_depth += 1,
'}' => brace_depth -= 1,
_ => {}
}
}
if brace_depth == 0 {
result.push(current.clone());
current.clear();
}
} else {
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 {
current = arg;
} else if brace_depth < 0 {
result.push(arg);
} else {
result.push(arg);
}
}
}
if !current.is_empty() {
result.push(current);
}
result
}
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(),
})
}
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] {
'{' => {
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(),
});
}
let content: String = chars[i + 1..j].iter().collect();
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(),
});
}
_ => {
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));
}
if i < len && chars[i] == '}' {
return Err(MkdirError::InvalidPattern {
pattern: pattern.to_string(),
reason: "Unmatched closing brace".to_string(),
});
}
}
}
}
Ok(segments)
}
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)
}
fn normalize_path(path: &str) -> String {
path.replace('/', "\\")
}
fn has_brace_expansion(path: &str) -> bool {
path.contains('{') && path.contains('}')
}
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 {
if verbose {
println!("mkdir-rs: directory '{}' already exists", path.display());
}
Ok(())
} else {
Err(MkdirError::CreationFailed {
path: path.display().to_string(),
source: e,
}.into())
}
}
}
}
fn process_patterns(args: &Args) -> Result<()> {
let mut created_count = 0;
let mut error_count = 0;
let joined_patterns = rejoin_brace_args(args.patterns.clone());
for pattern in &joined_patterns {
let has_braces = has_brace_expansion(pattern);
let expanded = match parse_brace_pattern(pattern) {
Ok(paths) => paths,
Err(e) => {
eprintln!("Error: {}", e);
error_count += 1;
continue;
}
};
let use_create_all = has_braces || args.parents;
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();
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}"]);
let args3 = vec!["simple_dir".to_string()];
let result3 = rejoin_brace_args(args3);
assert_eq!(result3, vec!["simple_dir"]);
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}"]);
}
}