pipe-rename 1.6.3

Rename your files using your favorite text editor
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
use ansi_term::Colour;
use clap::Parser;

use anyhow::{anyhow, Context};
use dialoguer::Select;
use serde::{Deserialize, Serialize};
use std::env;
use std::fmt::{Display, Formatter};
use std::fs;
use std::io::{self, Read, Seek, SeekFrom, Write};
use std::path::{Path, PathBuf};
use std::process::Command;

use thiserror::Error;

mod text_diff;
use text_diff::{calculate_text_diff, TextDiff};

#[derive(Parser, Debug)]
#[clap(
    version = env!("CARGO_PKG_VERSION"),
    author = "Marcus B. <me@mbuffett.com>",
    about = "https://github.com/marcusbuffett/pipe-rename",
    long_about = "Takes a list of files and renames/moves them by piping them through an external editor"
)]
struct Opts {
    #[clap(name = "FILES")]
    files: Vec<String>,
    /// Optionally set a custom rename command, like 'git mv'
    #[clap(short = 'c', long, value_name = "COMMAND")]
    rename_command: Option<String>,
    /// Optionally set an editor, overriding EDITOR environment variable and default
    #[clap(short = 'e', long)]
    editor: Option<String>,
    /// Prettify diffs
    #[clap(short, long)]
    pretty_diff: bool,
    /// Answer all prompts with yes
    #[clap(short = 'y', long = "yes")]
    assume_yes: bool,
    /// Overwrite existing files
    #[clap(short, long)]
    force: bool,
    /// Undo the previous renaming operation
    #[clap(short, long)]
    undo: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct Rename {
    original: PathBuf,
    new: PathBuf,
}

impl Rename {
    fn new(original: &str, new: &str) -> Self {
        // Expand ~ if applicable.
        let mut new = new.to_string();
        if let Ok(home) = env::var("HOME") {
            if new.starts_with("~/") {
                new = new.replacen('~', &home, 1);
            }
        }

        Rename {
            original: original.into(),
            new: new.into(),
        }
    }

    fn pretty_diff(&self) -> impl Display {
        struct PrettyDiff(Rename);
        impl Display for PrettyDiff {
            fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
                let diff_changes = calculate_text_diff(
                    &self.0.original.display().to_string(),
                    &self.0.new.display().to_string(),
                );

                // print old
                write!(f, "{}", Colour::Red.paint("- "))?;
                for change in &diff_changes {
                    match change {
                        TextDiff::Removed(old) => {
                            write!(f, "{}", Colour::Red.paint(old))?;
                        }
                        TextDiff::Unchanged(same) => {
                            write!(f, "{}", same)?;
                        }
                        _ => (),
                    }
                }
                writeln!(f)?;

                // print new
                write!(f, "{}", Colour::Green.paint("+ "))?;
                for change in &diff_changes {
                    match change {
                        TextDiff::New(new) => {
                            write!(f, "{}", Colour::Green.paint(new))?;
                        }
                        TextDiff::Unchanged(same) => {
                            write!(f, "{}", same)?;
                        }
                        _ => (),
                    }
                }

                Ok(())
            }
        }
        PrettyDiff(self.clone())
    }

    fn plain_diff(&self) -> impl Display {
        struct PlainDiff(Rename);
        impl Display for PlainDiff {
            fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
                write!(
                    f,
                    "{} -> {}",
                    self.0.original.display(),
                    self.0.new.display()
                )
            }
        }
        PlainDiff(self.clone())
    }
}
impl Display for Rename {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        self.plain_diff().fmt(f)
    }
}

#[derive(Error, Debug, Clone)]
pub enum RenamerError {
    #[error("No replacements found")]
    NoReplacementsFound,
    #[error("Unequal number of files")]
    UnequalLines,
}

fn find_renames(
    old_lines: &Vec<String>,
    new_lines: &Vec<String>,
) -> Result<Vec<Rename>, RenamerError> {
    if old_lines.len() != new_lines.len() {
        return Err(RenamerError::UnequalLines);
    }
    let renames: Vec<_> = old_lines
        .iter()
        .zip(new_lines)
        .filter_map(|(original, new)| {
            if original == new {
                None
            } else {
                Some(Rename::new(original, new))
            }
        })
        .collect();

    if renames.is_empty() {
        return Err(RenamerError::NoReplacementsFound);
    }

    Ok(renames)
}

fn get_input(files: Vec<String>) -> anyhow::Result<Vec<String>> {
    if !files.is_empty() {
        return Ok(files);
    }

    let input = {
        let mut buffer = String::new();
        io::stdin().read_to_string(&mut buffer)?;
        buffer
    };
    if input.is_empty() {
        return Err(anyhow!("No input files on stdin or as args. Aborting."));
    }
    return Ok(input.lines().map(|f| f.to_string()).collect());
}

fn get_input_files(files: Vec<String>) -> anyhow::Result<Vec<String>> {
    let mut input_files = get_input(files)?;
    // This is a special case where we want to expand `.` and `..`.
    let dots = &[".", ".."];
    if input_files.len() == 1 && dots.contains(&input_files[0].as_str()) {
        input_files = expand_dir(&input_files[0])?;
    }
    if input_files.is_empty() {
        return Err(anyhow!("No input files on stdin or as args. Aborting."));
    }

    Ok(input_files)
}

fn expand_dir(path: &str) -> anyhow::Result<Vec<String>, io::Error> {
    Ok(fs::read_dir(path)?
        .filter_map(|e| {
            e.ok()
                .and_then(|e| e.path().into_os_string().into_string().ok())
        })
        .collect())
}

fn open_editor(input_files: &[String], editor_string: &str) -> anyhow::Result<Vec<String>> {
    let mut tmpfile = tempfile::Builder::new()
        .prefix("renamer-")
        .suffix(".txt")
        .tempfile()
        .context("Could not create temp file")?;
    write!(tmpfile, "{}", input_files.join("\n"))?;
    let editor_parsed = shell_words::split(editor_string)
        .expect("failed to parse command line flags in EDITOR command");
    tmpfile.seek(SeekFrom::Start(0))?;
    let child = Command::new(&editor_parsed[0])
        .args(&editor_parsed[1..])
        .arg(tmpfile.path())
        .spawn()
        .with_context(|| {
            format!(
                "Failed to execute editor command: '{}'",
                shell_words::join(editor_parsed)
            )
        })?;

    let output = child.wait_with_output()?;
    if !output.status.success() {
        return Err(anyhow!("Editor terminated unexpectedly. Aborting."));
    }

    Ok(fs::read_to_string(&tmpfile)?
        .lines()
        .map(|f| f.to_string())
        .collect())
}

fn check_for_existing_files(replacements: &[Rename], force: bool) -> anyhow::Result<()> {
    // Skip check if forcing renames.
    if force {
        return Ok(());
    }

    let replacements_over_existing_files: Vec<_> = replacements
        .iter()
        .filter(|replacement| Path::new(&replacement.new).exists())
        .collect();
    if !replacements_over_existing_files.is_empty() {
        println!("The following replacements overwrite existing files:");
        for replacement in &replacements_over_existing_files {
            println!("{}", Colour::Red.paint(replacement.to_string()));
        }
        println!();
        return Err(anyhow!("Refusing to overwrite existing files. Aborting."));
    }

    Ok(())
}

fn check_input_files(input_files: &[String]) -> anyhow::Result<()> {
    let nonexisting_files: Vec<_> = input_files
        .iter()
        .filter(|input_file| !Path::new(input_file).exists())
        .collect();

    if !nonexisting_files.is_empty() {
        println!("The following input files do not exist:");
        for file in nonexisting_files {
            println!("{}", Colour::Red.paint(file));
        }
        println!();
        return Err(anyhow!("Nonexisting input files. Aborting."));
    }

    Ok(())
}

fn print_replacements(replacements: &Vec<Rename>, pretty: bool) {
    println!(
        "{}",
        Colour::Yellow.paint("The following replacements were found:")
    );
    println!();

    if pretty {
        let diff_output = replacements
            .iter()
            .map(|repl| repl.pretty_diff().to_string())
            .collect::<Vec<String>>()
            .join("\n\n"); // leave a blank line between pretty file diffs
        println!("{}", diff_output);
    } else {
        for replacement in replacements {
            println!("{}", Colour::Green.paint(replacement.to_string()));
        }
    }
    println!();
}

fn execute_renames(
    replacements: &Vec<Rename>,
    rename_command: Option<String>,
) -> anyhow::Result<()> {
    for replacement in replacements {
        if let Some(ref cmd) = rename_command {
            subprocess::Exec::cmd(cmd)
                .arg(&replacement.original)
                .arg(&replacement.new)
                .join()?;
        } else {
            match fs::rename(&replacement.original, &replacement.new) {
                Ok(()) => (),
                // If renaming fails, try creating parent directories and try again.
                Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
                    let dir = &replacement.new.parent();
                    if let Some(dir) = dir {
                        fs::create_dir_all(&dir)?;
                    }

                    fs::rename(&replacement.original, &replacement.new)?;
                }
                Err(e) => return Err(e.into()),
            };
        }
    }

    Ok(())
}

fn prompt(selections: &[MenuItem], yes: bool) -> anyhow::Result<&MenuItem> {
    if yes {
        return Ok(&selections[0]);
    }

    let selection = Select::new()
        .with_prompt("Execute these renames?")
        .default(0)
        .items(selections)
        .interact()?;

    Ok(&selections[selection])
}

enum MenuItem {
    /// Perform the current replacements
    Yes,
    /// Abort and do nothing
    No,
    /// Open the editor with the current replacements for edit
    Edit,
    /// Open the editor with the original names for edit
    Reset,
}

impl Display for MenuItem {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            MenuItem::Yes => f.write_str("Yes"),
            MenuItem::No => f.write_str("No"),
            MenuItem::Edit => f.write_str("Edit"),
            MenuItem::Reset => f.write_str("Reset"),
        }
    }
}

fn make_absolute(path: PathBuf) -> anyhow::Result<PathBuf> {
    if path.is_relative() {
        Ok(std::env::current_dir()?.join(path))
    } else {
        Ok(path)
    }
}

fn write_undo_renames(backup_file: PathBuf, replacements: Vec<Rename>) -> anyhow::Result<()> {
    let undo_replacements = replacements
        .into_iter()
        .map(|r| {
            // make paths absolute to that undo does not depend on CWD
            let original = make_absolute(r.original)?;
            let new = make_absolute(r.new)?;

            Ok(Rename {
                // swap original and new to get undo replacements
                original: new,
                new: original,
            })
        })
        .collect::<anyhow::Result<Vec<_>>>()?;

    let file = fs::File::create(backup_file)?;
    serde_json::to_writer(file, &undo_replacements)?;
    Ok(())
}

fn load_undo_renames(backup_file: PathBuf) -> anyhow::Result<Vec<Rename>> {
    let file = fs::File::open(&backup_file);
    let file = match file {
        Ok(f) => f,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
            return Err(anyhow!("No undo information found."))
        }
        Err(e) => return Err(e.into()),
    };
    let undo_replacements: Vec<Rename> = serde_json::from_reader(file)?;
    for replacement in &undo_replacements {
        if !replacement.original.exists() {
            return Err(anyhow!(
                "Undo not possible. \"{}\" is missing.",
                replacement.original.display()
            ));
        }
    }
    fs::remove_file(backup_file)?;
    Ok(undo_replacements)
}

fn main() -> anyhow::Result<()> {
    let opts = Opts::parse_from(wild::args());
    let backup_file = std::env::temp_dir().join("pipe-renamer_undo.json");

    if opts.undo {
        let replacements = load_undo_renames(backup_file)?;
        execute_renames(&replacements, opts.rename_command)?;
        println!("Restored {} files.", replacements.len());
        return Ok(());
    }

    let input_files = get_input_files(opts.files)?;

    check_input_files(&input_files)?;

    let default_editor = if cfg!(windows) { "notepad.exe" } else { "vim" };
    let default_editor = default_editor.to_string();
    let editor = opts
        .editor
        .unwrap_or_else(|| env::var("EDITOR").unwrap_or(default_editor));
    let mut buffer = input_files.clone();

    loop {
        let new_files = open_editor(&buffer, &editor)?;
        let replacements = find_renames(&input_files, &new_files)?;
        println!();

        let check_existing = check_for_existing_files(&replacements, opts.force);

        let menu_options = match check_existing {
            Ok(()) => {
                print_replacements(&replacements, opts.pretty_diff);
                vec![MenuItem::Yes, MenuItem::No, MenuItem::Edit, MenuItem::Reset]
            }
            e @ Err(_) if opts.assume_yes => return e,
            Err(_) => vec![MenuItem::Edit, MenuItem::Yes, MenuItem::No, MenuItem::Reset],
        };

        match prompt(&menu_options, opts.assume_yes)? {
            MenuItem::Yes => {
                execute_renames(&replacements, opts.rename_command)?;
                write_undo_renames(backup_file, replacements)?;
                break;
            }
            MenuItem::No => {
                println!("Aborting");
                break;
            }
            MenuItem::Edit => buffer = new_files.clone(),
            MenuItem::Reset => buffer = input_files.clone(),
        }
    }

    Ok(())
}