Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

More extensions #12

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 69 additions & 15 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use colored::Colorize;
use regex::Regex;
use std::fmt::{Display, Formatter, Result};
use std::fs::rename;
use std::io::ErrorKind;
use std::path::{Path, PathBuf};
Expand All @@ -19,39 +20,52 @@ impl RenameIntent {
}
}

impl Display for RenameIntent {
fn fmt(&self, f: &mut Formatter) -> Result {
if self.is_changed() {
write!(
f,
"{0} → {1}",
self.path.to_string_lossy().red(),
self.new_name.to_string_lossy().green()
)
} else {
write!(f, "{0} =", self.path.to_string_lossy(),)
}
}
}

pub enum RenameCommand {
SetExtension(String),
Remove(String),
Prefix(String),
FixExtension,
Normalize,
Replace(String, String, bool),
ChangeCase,
}

pub struct Config {
pub command: RenameCommand,
pub dry: bool,
pub files: Vec<PathBuf>,
pub auto_confirm: bool,
pub show_unchanged: bool,
}

fn confirm_intents(intents: &Vec<RenameIntent>) -> bool {
println!("The following files will be renamed:");
print_intents(intents);
print_intents(intents, false);
println!("Do you want to continue? [y/N] ");
let mut input = String::new();
std::io::stdin().read_line(&mut input).unwrap();
input.trim().to_lowercase() == "y"
}

fn print_intents(intents: &Vec<RenameIntent>) {
fn print_intents(intents: &Vec<RenameIntent>, show_unchanged: bool) {
for intent in intents {
if intent.is_changed() {
println!(
"- {0} → {1}",
intent.path.to_string_lossy().red(),
intent.new_name.to_string_lossy().green()
);
if intent.is_changed() || show_unchanged {
println!("{}", intent);
}
}
}
Expand Down Expand Up @@ -119,13 +133,28 @@ fn suggest_renames(files: &[PathBuf], command: &RenameCommand) -> Vec<RenameInte
new_name: PathBuf::from(new_name),
}
}
RenameCommand::ChangeCase => {
let path_str = path.to_string_lossy().to_string();
let new_name = path_str.to_lowercase();
RenameIntent {
path: path.clone(),
new_name: PathBuf::from(new_name),
}
}
})
.collect()
}

fn infer_mimetype(path: &Path) -> Option<String> {
fn infer_mimetype(path: &Path, mime_type: bool) -> Option<String> {
let mut cmd = process::Command::new("file");
let output = cmd.arg(path).arg("--brief").arg("--mime-type").output();
let cmd_with_args = cmd.arg(path).arg("--brief");
let cmd_with_args = if mime_type {
cmd_with_args.arg("--mime-type")
} else {
cmd_with_args
};

let output = cmd_with_args.output();
match output {
Ok(output) => {
let output_str = String::from_utf8(output.stdout).unwrap();
Expand All @@ -146,21 +175,36 @@ fn infer_mimetype(path: &Path) -> Option<String> {
}

fn find_extensions_from_content(path: &Path) -> Vec<String> {
match infer_mimetype(path) {
let mime_type_based = match infer_mimetype(path, true) {
None => vec![],
Some(mime_type) => {
let mime_type_str = mime_type.as_str();
dbg!(&mime_type);
match mime_type_str {
"application/pdf" => vec![String::from("pdf")],
"image/jpeg" => vec![String::from("jpeg"), String::from("jpg")],
"image/png" => vec![String::from("png")],
"text/csv" => vec![String::from("csv")],
"text/html" => vec![String::from("html"), String::from("htm")],
"text/x-script.python" => vec![String::from("py"), String::from("pyw")],
_other => vec![],
}
}
}
};

let mut description_based = match infer_mimetype(path, false) {
None => vec![],
Some(description) => {
let description_str = description.as_str();
match description_str {
"Apache Parquet" => vec![String::from("parquet"), String::from("pq")],
_other => vec![],
}
}
};

let mut extensions = mime_type_based.clone();
extensions.append(&mut description_based);
extensions
}

fn has_correct_extension(path: &Path, possible_extensions: &[String]) -> bool {
Expand Down Expand Up @@ -201,10 +245,16 @@ fn try_rename(path: &Path, new_name: &Path) -> bool {
}
}

fn process_command(command: &RenameCommand, files: &[PathBuf], dry: bool, auto_confirm: bool) {
fn process_command(
command: &RenameCommand,
files: &[PathBuf],
dry: bool,
auto_confirm: bool,
show_unchanged: bool,
) {
let intents = suggest_renames(files, command);
if dry {
print_intents(&intents);
print_intents(&intents, show_unchanged);
} else {
let confirmed = auto_confirm || {
let changed_count = intents.iter().filter(|i| i.is_changed()).count();
Expand All @@ -218,6 +268,9 @@ fn process_command(command: &RenameCommand, files: &[PathBuf], dry: bool, auto_c
let renamed = try_rename(&intent.path, &intent.new_name);
renamed_count += renamed as i32;
}
if show_unchanged {
println!("{}", intent)
}
}
println!("{renamed_count} files renamed.");
}
Expand All @@ -230,5 +283,6 @@ pub fn run(config: &Config) {
&config.files,
config.dry,
config.auto_confirm,
config.show_unchanged,
);
}
20 changes: 16 additions & 4 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,12 @@ fn parse_config(matches: &ArgMatches) -> Config {
Some(args) => args.cloned().collect(),
None => vec![],
};
let dry = matches.get_flag("dry");
let confirm = matches.get_flag("yes");
Config {
command,
dry,
dry: matches.get_flag("dry"),
files,
auto_confirm: confirm,
auto_confirm: matches.get_flag("yes"),
show_unchanged: matches.get_flag("unchanged"),
}
}

Expand All @@ -39,6 +38,7 @@ fn extract_command(args_matches: &ArgMatches) -> Option<RenameCommand> {
matches.get_one::<String>("replacement").unwrap().clone(),
matches.get_flag("regex"),
)),
Some(("change-case", _)) => Some(RenameCommand::ChangeCase),
_ => None,
}
}
Expand All @@ -58,6 +58,13 @@ fn create_cli_command() -> Command {
.global(true)
.action(clap::ArgAction::SetTrue),
)
.arg(
arg!(
-u --unchanged ... "Show unchanged files"
)
.global(true)
.action(clap::ArgAction::SetTrue),
)
.arg(
arg!(
-y --yes ... "Automatically confirm all actions"
Expand Down Expand Up @@ -136,6 +143,11 @@ fn create_cli_command() -> Command {
)
.arg(path_arg.clone()),
)
.subcommand(
Command::new("change-case")
.about("Change case of all files.")
.arg(path_arg.clone()),
)
}

fn main() {
Expand Down
Loading