smv 0.1.2

Smart Move - An enhanced mv command with transformation capabilities
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
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
use std::path::{Path, PathBuf};
use std::error::Error;
use std::env;
use std::io::{self, Write};
use std::process;

use colored::*;
use rustyline::{Editor, Result as RustylineResult, CompletionType, Config};
use rustyline::completion::{Completer, FilenameCompleter, Pair};
use rustyline::error::ReadlineError;
use rustyline::highlight::Highlighter;
use rustyline::hint::Hinter;
use rustyline::validate::Validator;
use rustyline::Helper;
use rustyline::history::DefaultHistory;
use glob::glob;

use crate::transformers::{TransformType, transform};
use crate::history::HistoryManager;

// Custom command completer
struct CommandCompleter {
    commands: Vec<String>,
    file_completer: FilenameCompleter,
}

impl CommandCompleter {
    fn new() -> Self {
        let commands = vec![
            "preview".to_string(),
            "apply".to_string(),
            "undo".to_string(),
            "cd".to_string(),
            "ls".to_string(),
            "rename".to_string(),
            "help".to_string(),
            "quit".to_string(),
            "exit".to_string(),
            "clean".to_string(),
            "snake".to_string(),
            "kebab".to_string(),
            "title".to_string(),
            "camel".to_string(),
            "pascal".to_string(),
            "lower".to_string(),
            "upper".to_string(),
        ];
        
        Self {
            commands,
            file_completer: FilenameCompleter::new(),
        }
    }
}

impl Completer for CommandCompleter {
    type Candidate = Pair;

    fn complete(
        &self,
        line: &str,
        pos: usize,
        ctx: &rustyline::Context<'_>,
    ) -> RustylineResult<(usize, Vec<Pair>)> {
        // Split line into words
        let words: Vec<&str> = line[..pos].split_whitespace().collect();
        
        // If we're on the first word, complete commands
        if words.len() <= 1 {
            let word = words.get(0).map_or("", |w| *w);
            let matches: Vec<Pair> = self.commands.iter()
                .filter(|cmd| cmd.starts_with(word))
                .map(|cmd| Pair {
                    display: cmd.clone(),
                    replacement: cmd.clone(),
                })
                .collect();
            
            return Ok((0, matches));
        }
        
        // Otherwise, complete filenames
        self.file_completer.complete(line, pos, ctx)
    }
}

// Helper functions for rustyline integration
impl Hinter for CommandCompleter {
    type Hint = String;
    fn hint(&self, _line: &str, _pos: usize, _ctx: &rustyline::Context<'_>) -> Option<String> {
        None
    }
}

impl Highlighter for CommandCompleter {}
impl Validator for CommandCompleter {}
impl Helper for CommandCompleter {}

/// Interactive REPL for SMV
pub struct InteractiveSession {
    editor: Editor<CommandCompleter, DefaultHistory>,
    history_manager: HistoryManager,
    current_dir: PathBuf,
}

impl InteractiveSession {
    pub fn new(max_history_size: usize, backup_dir: &Path) -> Result<Self, Box<dyn Error>> {
        // Create a rustyline editor with custom configuration
        let config = Config::builder()
            .completion_type(CompletionType::List)
            .build();
        let mut editor = Editor::with_config(config)?;
        
        // Set the helper for completion
        let helper = CommandCompleter::new();
        editor.set_helper(Some(helper));
        
        // Set the current directory
        let current_dir = env::current_dir()?;
        
        // Create history manager
        let history_manager = HistoryManager::new(max_history_size, backup_dir);
        
        Ok(Self {
            editor,
            history_manager,
            current_dir,
        })
    }
    
    /// Run the REPL session
    pub fn run(&mut self) -> Result<(), Box<dyn Error>> {
        self.display_welcome();
        
        loop {
            // Display prompt with current directory
            let prompt = format!("smv:{}> ", self.current_dir.display());
            
            // Read a line of input
            match self.editor.readline(&prompt) {
                Ok(line) => {
                    let line = line.trim();
                    if line.is_empty() {
                        continue;
                    }
                    
                    // Add to history
                    let _ = self.editor.add_history_entry(line);
                    
                    // Process the command
                    if let Err(e) = self.execute_command(line) {
                        eprintln!("{}: {}", "Error".red(), e);
                    }
                },
                Err(ReadlineError::Interrupted) => {
                    println!("CTRL-C");
                    break;
                },
                Err(ReadlineError::Eof) => {
                    println!("CTRL-D");
                    break;
                },
                Err(err) => {
                    eprintln!("Error: {}", err);
                    break;
                }
            }
        }
        
        Ok(())
    }
    
    /// Execute a REPL command
    fn execute_command(&mut self, command: &str) -> Result<(), Box<dyn Error>> {
        let parts: Vec<&str> = command.split_whitespace().collect();
        if parts.is_empty() {
            return Ok(());
        }
        
        match parts[0] {
            "preview" => self.cmd_preview(&parts[1..]),
            "apply" => self.cmd_apply(&parts[1..]),
            "undo" => self.cmd_undo(),
            "cd" => self.cmd_cd(&parts[1..]),
            "ls" => self.cmd_ls(&parts[1..]),
            "rename" => self.cmd_rename(&parts[1..]),
            "help" => self.cmd_help(),
            "quit" | "exit" => {
                println!("Goodbye!");
                process::exit(0);
            },
            _ => {
                // Check if the command is a transformation type
                if let Some(transform_type) = TransformType::from_str(parts[0]) {
                    if parts.len() > 1 {
                        // Use as transformation with file pattern
                        self.preview_transform(transform_type, &parts[1..])
                    } else {
                        eprintln!("Usage: {} <file_pattern>", transform_type.as_str());
                        Ok(())
                    }
                } else {
                    Err(format!("Unknown command: {}", parts[0]).into())
                }
            }
        }
    }
    
    /// Display welcome message
    fn display_welcome(&self) {
        println!("{}", "SMV - Smart Move".bold().green());
        println!("Type {} for available commands", "help".cyan());
    }
    
    /// Display help text
    fn cmd_help(&self) -> Result<(), Box<dyn Error>> {
        println!("{}:", "Commands".bold());
        println!("  {} <transform> <files>  - Show transformation without applying", "preview".cyan());
        println!("  {} <transform> <files>    - Apply transformation", "apply".cyan());
        println!("  {} <files> --options     - Interactive renaming wizard", "rename".cyan());
        println!("  {}                        - Revert last operation", "undo".cyan());
        println!("  {} <directory>              - Change directory", "cd".cyan());
        println!("  {} [pattern]                - List files", "ls".cyan());
        println!("  {}                        - Show this help", "help".cyan());
        println!("  {}                        - Exit program", "quit".cyan());
        println!();
        println!("{}:", "Transformations".bold());
        println!("  {} - Clean up spaces and special characters", "clean".yellow());
        println!("  {} - Convert to snake_case", "snake".yellow());
        println!("  {} - Convert to kebab-case", "kebab".yellow());
        println!("  {} - Convert to Title Case", "title".yellow());
        println!("  {} - Convert to camelCase", "camel".yellow());
        println!("  {} - Convert to PascalCase", "pascal".yellow());
        println!("  {} - Convert to lowercase", "lower".yellow());
        println!("  {} - Convert to UPPERCASE", "upper".yellow());
        
        Ok(())
    }
    
    /// Change current directory
    fn cmd_cd(&mut self, args: &[&str]) -> Result<(), Box<dyn Error>> {
        if args.is_empty() {
            // Default to home directory if no args
            let home = dirs::home_dir().ok_or("Could not determine home directory")?;
            self.current_dir = home;
        } else {
            let new_dir = Path::new(args[0]);
            let target_dir = if new_dir.is_absolute() {
                new_dir.to_path_buf()
            } else {
                self.current_dir.join(new_dir)
            };
            
            if target_dir.is_dir() {
                self.current_dir = target_dir;
            } else {
                return Err(format!("Directory not found: {}", args[0]).into());
            }
        }
        
        env::set_current_dir(&self.current_dir)?;
        Ok(())
    }
    
    /// List files in current or specified directory
    fn cmd_ls(&self, args: &[&str]) -> Result<(), Box<dyn Error>> {
        let pattern = if args.is_empty() { "*" } else { args[0] };
        let path_pattern = self.current_dir.join(pattern);
        let pattern_str = path_pattern.to_string_lossy();
        
        // Use glob pattern matching
        let mut entries = Vec::new();
        for entry in glob(&pattern_str)? {
            match entry {
                Ok(path) => {
                    let name = path.file_name()
                        .map(|n| n.to_string_lossy().to_string())
                        .unwrap_or_else(|| "".to_string());
                    
                    let formatted = if path.is_dir() {
                        name.blue().bold().to_string()
                    } else {
                        name
                    };
                    
                    entries.push(formatted);
                },
                Err(e) => eprintln!("{}: {}", "Error".red(), e),
            }
        }
        
        // Sort and print entries
        entries.sort();
        for chunk in entries.chunks(5) {
            for entry in chunk {
                print!("{:<20}", entry);
            }
            println!();
        }
        
        if entries.is_empty() {
            println!("No files found matching pattern: {}", pattern);
        }
        
        Ok(())
    }
    
    /// Preview transformation without applying
    fn cmd_preview(&self, args: &[&str]) -> Result<(), Box<dyn Error>> {
        if args.len() < 2 {
            return Err("Usage: preview <transform> <file_pattern>".into());
        }
        
        let transform_type = TransformType::from_str(args[0])
            .ok_or_else(|| format!("Unknown transformation: {}", args[0]))?;
            
        self.preview_transform(transform_type, &args[1..])
    }
    
    /// Apply transformation to files
    fn cmd_apply(&mut self, args: &[&str]) -> Result<(), Box<dyn Error>> {
        if args.len() < 2 {
            return Err("Usage: apply <transform> <file_pattern>".into());
        }
        
        let transform_type = TransformType::from_str(args[0])
            .ok_or_else(|| format!("Unknown transformation: {}", args[0]))?;
            
        self.apply_transform(transform_type, &args[1..])
    }
    
    /// Undo the last operation
    fn cmd_undo(&mut self) -> Result<(), Box<dyn Error>> {
        match self.history_manager.undo() {
            Ok(_) => {
                println!("Operation undone successfully.");
                Ok(())
            },
            Err(e) => Err(e)
        }
    }
    
    /// Interactive rename wizard
    fn cmd_rename(&mut self, args: &[&str]) -> Result<(), Box<dyn Error>> {
        if args.is_empty() {
            return Err("Usage: rename <file_pattern> [options]".into());
        }
        
        // Collect files to rename
        let mut files = Vec::new();
        for pattern in args {
            let path_pattern = self.current_dir.join(pattern);
            let pattern_str = path_pattern.to_string_lossy();
            
            for entry in glob(&pattern_str)? {
                match entry {
                    Ok(path) => {
                        if path.is_file() {
                            files.push(path);
                        }
                    },
                    Err(e) => eprintln!("{}: {}", "Error".red(), e),
                }
            }
        }
        
        if files.is_empty() {
            println!("No files found matching pattern.");
            return Ok(());
        }
        
        // List files to be processed
        println!("\n{} files found:", files.len());
        for (i, file) in files.iter().enumerate() {
            let name = file.file_name().unwrap_or_default().to_string_lossy();
            println!("  {}. {}", i+1, name);
        }
        
        // Ask for transformation
        println!("\nSelect transformation:");
        println!("  1. Clean up spaces and special characters");
        println!("  2. Convert to snake_case");
        println!("  3. Convert to kebab-case");
        println!("  4. Convert to Title Case");
        println!("  5. Convert to camelCase");
        println!("  6. Convert to PascalCase");
        println!("  7. Convert to lowercase");
        println!("  8. Convert to UPPERCASE");
        
        print!("Enter selection [1-8]: ");
        io::stdout().flush()?;
        
        let mut input = String::new();
        io::stdin().read_line(&mut input)?;
        
        let transform_type = match input.trim().parse::<usize>() {
            Ok(1) => TransformType::Clean,
            Ok(2) => TransformType::Snake,
            Ok(3) => TransformType::Kebab,
            Ok(4) => TransformType::Title,
            Ok(5) => TransformType::Camel,
            Ok(6) => TransformType::Pascal,
            Ok(7) => TransformType::Lower,
            Ok(8) => TransformType::Upper,
            _ => {
                println!("Invalid selection. Using Clean transformation.");
                TransformType::Clean
            }
        };
        
        // Preview transformations
        let mut changes = Vec::new();
        println!("\nPreview of changes:");
        
        for path in &files {
            let filename = path.file_name()
                .ok_or("Invalid file name")?
                .to_string_lossy();
                
            // Apply the transformation
            let new_name = transform(&filename, transform_type);
            
            // Skip if no change
            if filename == new_name {
                println!("  \"{}\" → (no change needed)", filename);
                continue;
            }
            
            // Create the new path
            let parent = path.parent().unwrap_or(Path::new(""));
            let new_path = parent.join(&new_name);
            
            // Check for conflicts
            if new_path.exists() && path != &new_path {
                println!("  \"{}\"\"{}\" {}", 
                    filename, new_name, "CONFLICT - file exists".red());
                continue;
            }
            
            changes.push((path.clone(), new_path.clone()));
            println!("  \"{}\"\"{}\"", filename, new_name);
        }
        
        if changes.is_empty() {
            println!("\nNo changes needed or all changes would create conflicts.");
            return Ok(());
        }
        
        // Confirm with user
        print!("\nApply these changes? [y/N] ");
        io::stdout().flush()?;
        
        let mut input = String::new();
        io::stdin().read_line(&mut input)?;
        
        if !input.trim().eq_ignore_ascii_case("y") {
            println!("Operation cancelled.");
            return Ok(());
        }
        
        // Apply changes
        for (src, dst) in changes {
            // Record the operation for undo
            self.history_manager.record(src.clone(), dst.clone())?;
            
            // Perform the rename
            match std::fs::rename(&src, &dst) {
                Ok(_) => {
                    let src_name = src.file_name().unwrap_or_default().to_string_lossy();
                    let dst_name = dst.file_name().unwrap_or_default().to_string_lossy();
                    println!("Renamed: \"{}\"\"{}\"", src_name, dst_name);
                },
                Err(e) => {
                    eprintln!("{}: Failed to rename \"{}\" - {}", 
                        "Error".red(), src.display(), e);
                }
            }
        }
        
        println!("\nRenaming complete!");
        Ok(())
    }
    
    /// Preview transformation on files
    fn preview_transform(&self, transform_type: TransformType, patterns: &[&str]) -> Result<(), Box<dyn Error>> {
        let mut changes = Vec::new();
        
        // Process each file pattern
        for pattern in patterns {
            let path_pattern = self.current_dir.join(pattern);
            let pattern_str = path_pattern.to_string_lossy();
            
            for entry in glob(&pattern_str)? {
                match entry {
                    Ok(path) => {
                        // Skip directories
                        if path.is_dir() {
                            continue;
                        }
                        
                        // Get the file name
                        let filename = path.file_name()
                            .ok_or("Invalid file name")?
                            .to_string_lossy();
                            
                        // Apply the transformation
                        let new_name = transform(&filename, transform_type);
                        
                        // If the name hasn't changed, skip
                        if filename == new_name {
                            println!("{}{} (no change needed)", filename, new_name);
                            continue;
                        }
                        
                        // Create the new path
                        let parent = path.parent().unwrap_or(Path::new(""));
                        let new_path = parent.join(&new_name);
                        
                        // Check for conflicts
                        if new_path.exists() && path != new_path {
                            println!("{}: Cannot rename \"{}\" to \"{}\" - file already exists", 
                                "Conflict".red(), filename, new_name);
                            continue;
                        }
                        
                        changes.push((path.clone(), new_path.clone()));
                        println!("{} \"{}\"\"{}\"", "Preview:".blue(), filename, new_name);
                    },
                    Err(e) => eprintln!("{}: {}", "Error".red(), e),
                }
            }
        }
        
        if changes.is_empty() {
            println!("No files found or no changes needed.");
        } else {
            println!("\nFound {} file(s) to rename.", changes.len());
        }
        
        Ok(())
    }
    
    /// Apply transformation to files
    fn apply_transform(&mut self, transform_type: TransformType, patterns: &[&str]) -> Result<(), Box<dyn Error>> {
        let mut changes = Vec::new();
        
        // Process each file pattern
        for pattern in patterns {
            let path_pattern = self.current_dir.join(pattern);
            let pattern_str = path_pattern.to_string_lossy();
            
            for entry in glob(&pattern_str)? {
                match entry {
                    Ok(path) => {
                        // Skip directories
                        if path.is_dir() {
                            continue;
                        }
                        
                        // Get the file name
                        let filename = path.file_name()
                            .ok_or("Invalid file name")?
                            .to_string_lossy();
                            
                        // Apply the transformation
                        let new_name = transform(&filename, transform_type);
                        
                        // If the name hasn't changed, skip
                        if filename == new_name {
                            continue;
                        }
                        
                        // Create the new path
                        let parent = path.parent().unwrap_or(Path::new(""));
                        let new_path = parent.join(&new_name);
                        
                        // Check for conflicts
                        if new_path.exists() && path != new_path {
                            println!("{}: Cannot rename \"{}\" to \"{}\" - file already exists", 
                                "Conflict".red(), filename, new_name);
                            continue;
                        }
                        
                        changes.push((path.clone(), new_path.clone()));
                    },
                    Err(e) => eprintln!("{}: {}", "Error".red(), e),
                }
            }
        }
        
        if changes.is_empty() {
            println!("No files found or no changes needed.");
            return Ok(());
        }
        
        // Display changes
        println!("\nThe following {} file(s) will be renamed:", changes.len());
        for (src, dst) in &changes {
            let src_name = src.file_name().unwrap_or_default().to_string_lossy();
            let dst_name = dst.file_name().unwrap_or_default().to_string_lossy();
            println!("  \"{}\"\"{}\"", src_name, dst_name);
        }
        
        // Confirm with user
        print!("\nApply these changes? [y/N] ");
        io::stdout().flush()?;
        
        let mut input = String::new();
        io::stdin().read_line(&mut input)?;
        
        if !input.trim().eq_ignore_ascii_case("y") {
            println!("Operation cancelled.");
            return Ok(());
        }
        
        // Apply changes
        for (src, dst) in changes {
            // Record the operation for undo
            self.history_manager.record(src.clone(), dst.clone())?;
            
            // Perform the rename
            match std::fs::rename(&src, &dst) {
                Ok(_) => {
                    let src_name = src.file_name().unwrap_or_default().to_string_lossy();
                    let dst_name = dst.file_name().unwrap_or_default().to_string_lossy();
                    println!("Renamed: \"{}\"\"{}\"", src_name, dst_name);
                },
                Err(e) => {
                    eprintln!("{}: Failed to rename \"{}\" - {}", 
                        "Error".red(), src.display(), e);
                }
            }
        }
        
        println!("\nRenaming complete!");
        Ok(())
    }
}