wsb 0.195.4199

Workspace - A tool suite for file operations, version management, and development workflow automation
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
use crate::prelude::*;
use clap::{Parser, ValueEnum};

#[derive(Parser, Debug, Clone)]
#[command(name = "refac")]
#[command(version = crate::get_version(), about = "A robust cross-platform tool for recursive string replacement in file/folder names and contents - part of the workspace tool suite")]
#[command(long_about = None)]
pub struct Args {
    /// Root directory to search in
    #[arg(value_name = "ROOT_DIR")]
    pub root_dir: PathBuf,

    /// Pattern to find and replace (required unless --patterns-file is used)
    #[arg(value_name = "PATTERN", required_unless_present = "patterns_file")]
    pub pattern: Option<String>,

    /// Replacement text (required unless --patterns-file is used)
    #[arg(value_name = "SUBSTITUTE", required_unless_present = "patterns_file")]
    pub substitute: Option<String>,

    /// File containing pattern/substitute pairs, one pair per line with shell-style quoting
    #[arg(long = "patterns-file", value_name = "FILE", conflicts_with_all = ["pattern", "substitute"])]
    pub patterns_file: Option<PathBuf>,

    /// Assume "yes" to confirmation prompts (non-interactive mode)
    #[arg(short = 'y', long = "assume-yes")]
    pub assume_yes: bool,

    /// Show detailed output
    #[arg(short = 'v', long = "verbose")]
    pub verbose: bool,

    /// Follow symbolic links
    #[arg(long = "follow-symlinks")]
    pub follow_symlinks: bool,

    /// Create backup files before modifying content
    #[arg(short = 'b', long = "backup")]
    pub backup: bool,

    /// Only process files (skip directories)
    #[arg(long = "files-only")]
    pub files_only: bool,

    /// Only process directories (skip files)
    #[arg(long = "dirs-only")]
    pub dirs_only: bool,

    /// Skip content replacement, only rename files/directories
    #[arg(long = "names-only")]
    pub names_only: bool,

    /// Skip file/directory renaming, only replace content
    #[arg(long = "content-only")]
    pub content_only: bool,

    /// Maximum depth to search (0 = unlimited)
    #[arg(long = "max-depth", default_value = "0")]
    pub max_depth: usize,

    /// Exclude files matching these patterns (glob patterns)
    #[arg(long = "exclude", value_name = "PATTERN")]
    pub exclude_patterns: Vec<String>,

    /// Include only files matching these patterns (glob patterns)
    #[arg(long = "include", value_name = "PATTERN")]
    pub include_patterns: Vec<String>,

    /// Output format
    #[arg(long = "format", default_value = "human")]
    pub format: OutputFormat,

    /// Number of threads to use for processing (0 = auto)
    #[arg(short = 'j', long = "threads", default_value = "0")]
    pub threads: usize,

    /// Progress display mode
    #[arg(long = "progress", default_value = "auto")]
    pub progress: ProgressMode,

    /// Ignore case when matching patterns
    #[arg(short = 'i', long = "ignore-case")]
    pub ignore_case: bool,

    /// Use regex patterns instead of literal strings
    #[arg(short = 'r', long = "regex")]
    pub use_regex: bool,

    /// Include hidden files and directories (starting with '.')
    #[arg(long = "include-hidden")]
    pub include_hidden: bool,

    /// Include binary file names in renaming operations (content will still be skipped)
    #[arg(long = "binary-names")]
    pub binary_names: bool,
}

#[derive(ValueEnum, Debug, Clone, PartialEq)]
pub enum OutputFormat {
    /// Human-readable output with colors
    Human,
    /// JSON output for scripting
    Json,
    /// Plain text output
    Plain,
}

#[derive(ValueEnum, Debug, Clone)]
pub enum ProgressMode {
    /// Auto-detect based on terminal capabilities
    Auto,
    /// Never show progress
    Never,
    /// Always show progress
    Always,
}

#[derive(Debug, Clone)]
pub enum Mode {
    /// Process both files and directories, both names and content
    Full,
    /// Only process files
    FilesOnly,
    /// Only process directories
    DirsOnly,
    /// Only rename files/directories (skip content)
    NamesOnly,
    /// Only replace content (skip renaming)
    ContentOnly,
}

impl Args {
    pub fn get_mode(&self) -> Mode {
        match (
            self.files_only,
            self.dirs_only,
            self.names_only,
            self.content_only,
        ) {
            (true, false, false, false) => Mode::FilesOnly,
            (false, true, false, false) => Mode::DirsOnly,
            (false, false, true, false) => Mode::NamesOnly,
            (false, false, false, true) => Mode::ContentOnly,
            _ => Mode::Full,
        }
    }

    pub fn validate(&self) -> Result<(), String> {
        // Check for conflicting mode options
        let mode_flags = [
            self.files_only,
            self.dirs_only,
            self.names_only,
            self.content_only,
        ];
        let active_modes = mode_flags.iter().filter(|&&x| x).count();

        if active_modes > 1 {
            return Err("Cannot specify more than one mode flag (--files-only, --dirs-only, --names-only, --content-only)".to_string());
        }

        // Validate root directory exists
        if !self.root_dir.exists() {
            return Err(format!(
                "Root directory does not exist: {}",
                self.root_dir.display()
            ));
        }

        if !self.root_dir.is_dir() {
            return Err(format!(
                "Root path is not a directory: {}",
                self.root_dir.display()
            ));
        }

        // Validate pattern source: either positional args or patterns file, not both, not neither
        match (&self.pattern, &self.substitute, &self.patterns_file) {
            (Some(p), Some(s), None) => {
                if p.is_empty() {
                    return Err("Pattern cannot be empty".to_string());
                }
                if s.is_empty() {
                    return Err("Substitute cannot be empty".to_string());
                }
                // Check for path-unsafe characters in substitute (only when processing names)
                if self.should_process_names() {
                    let invalid_chars = ['/', '\\', ':', '*', '?', '"', '<', '>', '|', '\0'];
                    if let Some(ch) = s.chars().find(|c| invalid_chars.contains(c)) {
                        return Err(format!(
                            "Substitute cannot contain path-unsafe characters ({}) when processing names. Use --content-only to replace in file contents only.",
                            ch
                        ));
                    }
                }
            }
            (None, None, Some(pf)) => {
                if !pf.exists() {
                    return Err(format!("Patterns file does not exist: {}", pf.display()));
                }
                if !pf.is_file() {
                    return Err(format!("Patterns file is not a file: {}", pf.display()));
                }
            }
            (Some(_), None, None) | (None, Some(_), None) => {
                return Err(
                    "Both PATTERN and SUBSTITUTE are required when not using --patterns-file"
                        .to_string(),
                );
            }
            (Some(_), _, Some(_)) | (_, Some(_), Some(_)) => {
                return Err(
                    "Cannot use positional PATTERN/SUBSTITUTE together with --patterns-file"
                        .to_string(),
                );
            }
            (None, None, None) => {
                return Err("Either provide PATTERN SUBSTITUTE or use --patterns-file".to_string());
            }
        }

        // Validate thread count
        if self.threads > 1000 {
            return Err("Thread count cannot exceed 1000".to_string());
        }

        // Validate max depth
        if self.max_depth > 1000 {
            return Err("Max depth cannot exceed 1000".to_string());
        }

        Ok(())
    }

    pub fn should_process_files(&self) -> bool {
        !self.dirs_only
    }

    pub fn should_process_dirs(&self) -> bool {
        !self.files_only
    }

    pub fn should_process_content(&self) -> bool {
        !self.names_only
    }

    pub fn should_process_names(&self) -> bool {
        !self.content_only
    }

    pub fn get_thread_count(&self) -> usize {
        if self.threads == 0 {
            std::thread::available_parallelism()
                .map(|n| n.get())
                .unwrap_or(4)
        } else {
            self.threads
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::TempDir;

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

        let mut args = Args {
            root_dir: temp_dir.path().to_path_buf(),
            pattern: Some("old".to_string()),
            substitute: Some("new".to_string()),
            patterns_file: None,
            assume_yes: false,
            verbose: false,
            follow_symlinks: false,
            backup: false,
            files_only: false,
            dirs_only: false,
            names_only: false,
            content_only: false,
            max_depth: 0,
            exclude_patterns: vec![],
            include_patterns: vec![],
            format: OutputFormat::Human,
            threads: 0,
            progress: ProgressMode::Auto,
            ignore_case: false,
            use_regex: false,
            include_hidden: false,
            binary_names: false,
        };

        // Valid args should pass
        assert!(args.validate().is_ok());

        // Empty pattern should fail
        args.pattern = Some("".to_string());
        assert!(args.validate().is_err());
        args.pattern = Some("old".to_string());

        // Empty substitute should fail
        args.substitute = Some("".to_string());
        assert!(args.validate().is_err());
        args.substitute = Some("new".to_string());

        // Path-unsafe characters in substitute should fail when processing names
        let invalid_chars = vec![
            "new/path",
            "new\\path",
            "new:path",
            "new*path",
            "new?path",
            "new\"path",
            "new<path",
            "new>path",
            "new|path",
        ];
        for invalid in &invalid_chars {
            args.substitute = Some(invalid.to_string());
            assert!(args.validate().is_err(), "Should reject: {}", invalid);
        }
        args.substitute = Some("new".to_string());

        // Path-unsafe characters should be allowed with content-only mode
        args.content_only = true;
        for valid_in_content in &invalid_chars {
            args.substitute = Some(valid_in_content.to_string());
            assert!(
                args.validate().is_ok(),
                "Should allow in content-only mode: {}",
                valid_in_content
            );
        }
        args.substitute = Some("new".to_string());
        args.content_only = false;

        // Multiple mode flags should fail
        args.files_only = true;
        args.dirs_only = true;
        assert!(args.validate().is_err());
    }

    #[test]
    fn test_args_validation_patterns_file() {
        let temp_dir = TempDir::new().unwrap();
        let patterns_file = temp_dir.path().join("patterns.txt");
        std::fs::write(&patterns_file, "foo bar\n").unwrap();

        // Valid patterns file args
        let args = Args {
            root_dir: temp_dir.path().to_path_buf(),
            pattern: None,
            substitute: None,
            patterns_file: Some(patterns_file.clone()),
            assume_yes: false,
            verbose: false,
            follow_symlinks: false,
            backup: false,
            files_only: false,
            dirs_only: false,
            names_only: false,
            content_only: false,
            max_depth: 0,
            exclude_patterns: vec![],
            include_patterns: vec![],
            format: OutputFormat::Human,
            threads: 0,
            progress: ProgressMode::Auto,
            ignore_case: false,
            use_regex: false,
            include_hidden: false,
            binary_names: false,
        };
        assert!(args.validate().is_ok());

        // Both positional and file should fail
        let args_both = Args {
            pattern: Some("foo".to_string()),
            substitute: Some("bar".to_string()),
            patterns_file: Some(patterns_file.clone()),
            ..args.clone()
        };
        assert!(args_both.validate().is_err());

        // Neither positional nor file should fail
        let args_neither = Args {
            pattern: None,
            substitute: None,
            patterns_file: None,
            ..args.clone()
        };
        assert!(args_neither.validate().is_err());

        // Only pattern without substitute should fail
        let args_partial = Args {
            pattern: Some("foo".to_string()),
            substitute: None,
            patterns_file: None,
            ..args.clone()
        };
        assert!(args_partial.validate().is_err());

        // Nonexistent patterns file should fail
        let args_missing = Args {
            pattern: None,
            substitute: None,
            patterns_file: Some(PathBuf::from("/nonexistent/file.txt")),
            ..args.clone()
        };
        assert!(args_missing.validate().is_err());
    }

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

        let base_args = Args {
            root_dir: temp_dir.path().to_path_buf(),
            pattern: Some("old".to_string()),
            substitute: Some("new".to_string()),
            patterns_file: None,
            assume_yes: false,
            verbose: false,
            follow_symlinks: false,
            backup: false,
            files_only: false,
            dirs_only: false,
            names_only: false,
            content_only: false,
            max_depth: 0,
            exclude_patterns: vec![],
            include_patterns: vec![],
            format: OutputFormat::Human,
            threads: 0,
            progress: ProgressMode::Auto,
            ignore_case: false,
            use_regex: false,
            include_hidden: false,
            binary_names: false,
        };

        // Test default mode
        assert!(matches!(base_args.get_mode(), Mode::Full));

        // Test files only
        let mut args = base_args.clone();
        args.files_only = true;
        assert!(matches!(args.get_mode(), Mode::FilesOnly));

        // Test dirs only
        let mut args = base_args.clone();
        args.dirs_only = true;
        assert!(matches!(args.get_mode(), Mode::DirsOnly));

        // Test names only
        let mut args = base_args.clone();
        args.names_only = true;
        assert!(matches!(args.get_mode(), Mode::NamesOnly));

        // Test content only
        let mut args = base_args.clone();
        args.content_only = true;
        assert!(matches!(args.get_mode(), Mode::ContentOnly));
    }

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

        let mut args = Args {
            root_dir: temp_dir.path().to_path_buf(),
            pattern: Some("old".to_string()),
            substitute: Some("new".to_string()),
            patterns_file: None,
            assume_yes: false,
            verbose: false,
            follow_symlinks: false,
            backup: false,
            files_only: false,
            dirs_only: false,
            names_only: false,
            content_only: false,
            max_depth: 0,
            exclude_patterns: vec![],
            include_patterns: vec![],
            format: OutputFormat::Human,
            threads: 0,
            progress: ProgressMode::Auto,
            ignore_case: false,
            use_regex: false,
            include_hidden: false,
            binary_names: false,
        };

        // Default should process everything
        assert!(args.should_process_files());
        assert!(args.should_process_dirs());
        assert!(args.should_process_content());
        assert!(args.should_process_names());

        // Dirs only
        args.dirs_only = true;
        assert!(!args.should_process_files());
        assert!(args.should_process_dirs());
        args.dirs_only = false;

        // Names only
        args.content_only = true;
        assert!(args.should_process_content());
        assert!(!args.should_process_names());
    }
}