Skip to content

Commit

Permalink
Merge pull request #59 from assarbad/editor-command-line-switch
Browse files Browse the repository at this point in the history
Implemented editor override, general cleanup
  • Loading branch information
mtimkovich authored Nov 6, 2022
2 parents 325d115 + 1451a5b commit 085d804
Show file tree
Hide file tree
Showing 5 changed files with 48 additions and 23 deletions.
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "pipe-rename"
version = "1.5.0"
version = "1.6.1"
authors = ["Marcus Buffett <[email protected]>"]
description = "Rename your files using your favorite text editor"
homepage = "https://github.com/marcusbuffett/pipe-rename"
Expand Down
27 changes: 21 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,13 +47,28 @@ USAGE:
ARGS:
<FILES>...
OPTIONS:
-c, --rename-command <RENAME_COMMAND> Optionally set a custom rename command, like 'git mv'
-f, --force Overwrite existing files
-h, --help Print help information
-p, --pretty-diff Prettify diffs
-V, --version Print version information
-y, --yes Answer all prompts with yes
-c, --rename-command <COMMAND>
Optionally set a custom rename command, like 'git mv'
-e, --editor <EDITOR>
Optionally set an editor, overriding EDITOR environment variable and default
-f, --force
Overwrite existing files
-h, --help
Print help information
-p, --pretty-diff
Prettify diffs
-V, --version
Print version information
-y, --yes
Answer all prompts with yes
```

## Contributors ✨
Expand Down
38 changes: 24 additions & 14 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,6 @@ use std::fs;
use std::io::{self, Read, Seek, SeekFrom, Write};
use std::path::Path;
use std::process::Command;
use tempfile;
use wild;

use thiserror::Error;

Expand All @@ -30,8 +28,11 @@ struct Opts {
#[clap(name = "FILES")]
files: Vec<String>,
/// Optionally set a custom rename command, like 'git mv'
#[clap(short = 'c', long)]
#[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,
Expand All @@ -55,7 +56,7 @@ impl Rename {
let mut new = new.to_string();
if let Ok(home) = env::var("HOME") {
if new.starts_with("~/") {
new = new.replacen("~", &home, 1);
new = new.replacen('~', &home, 1);
}
}

Expand Down Expand Up @@ -138,7 +139,7 @@ fn find_renames(
return Err(RenamerError::UnequalLines);
}
let renames: Vec<_> = old_lines
.into_iter()
.iter()
.zip(new_lines)
.filter_map(|(original, new)| {
if original == new {
Expand Down Expand Up @@ -195,18 +196,21 @@ fn expand_dir(path: &str) -> anyhow::Result<Vec<String>, io::Error> {
.collect())
}

fn open_editor(input_files: &Vec<String>) -> anyhow::Result<Vec<String>> {
let mut tmpfile = tempfile::NamedTempFile::new().context("Could not create temp file")?;
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_string = env::var("EDITOR").unwrap_or("vim".to_string());
let editor_parsed = shell_words::split(&editor_string)
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()
.context("Failed to execute editor process")?;
.with_context(|| format!("Failed to execute editor command: '{}'", shell_words::join(editor_parsed)))?;

let output = child.wait_with_output()?;
if !output.status.success() {
Expand All @@ -219,7 +223,7 @@ fn open_editor(input_files: &Vec<String>) -> anyhow::Result<Vec<String>> {
.collect())
}

fn check_for_existing_files(replacements: &Vec<Rename>, force: bool) -> anyhow::Result<()> {
fn check_for_existing_files(replacements: &[Rename], force: bool) -> anyhow::Result<()> {
// Skip check if forcing renames.
if force {
return Ok(());
Expand All @@ -241,7 +245,7 @@ fn check_for_existing_files(replacements: &Vec<Rename>, force: bool) -> anyhow::
Ok(())
}

fn check_input_files(input_files: &Vec<String>) -> anyhow::Result<()> {
fn check_input_files(input_files: &[String]) -> anyhow::Result<()> {
let nonexisting_files: Vec<_> = input_files
.iter()
.filter(|input_file| !Path::new(input_file).exists())
Expand Down Expand Up @@ -310,7 +314,7 @@ fn prompt(selections: &[MenuItem], yes: bool) -> anyhow::Result<&MenuItem> {
let selection = Select::new()
.with_prompt("Execute these renames?")
.default(0)
.items(&selections)
.items(selections)
.interact()?;

Ok(&selections[selection])
Expand Down Expand Up @@ -344,10 +348,16 @@ fn main() -> anyhow::Result<()> {

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)?;
let new_files = open_editor(&buffer, &editor)?;
let replacements = find_renames(&input_files, &new_files)?;
println!();

Expand Down
2 changes: 1 addition & 1 deletion src/text_diff.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#[derive(Debug, PartialEq)]
#[derive(Debug, PartialEq, Eq)]
pub enum TextDiff {
Removed(String),
Unchanged(String),
Expand Down

0 comments on commit 085d804

Please sign in to comment.