use crate::paths::BACKUP_DIR_PATH;
use anyhow::Context;
use crossterm::style::Stylize;
use std::fs;
use std::io;
use std::io::Write;
use std::path::Path;
pub fn trim_newline(s: &mut String) {
if s.ends_with('\n') {
s.pop();
if s.ends_with('\r') {
s.pop();
}
}
}
pub fn file_is_empty(p: &Path) -> io::Result<bool> {
fs::metadata(p).map(|metadata| metadata.len() == 0)
}
pub fn get_now_str() -> String {
chrono::Local::now().format("%Y%m%d_%H%M%S%.9f").to_string()
}
pub fn skip<W: Write>(path: &Path, new_path: &Path, history_writer: &mut W) -> anyhow::Result<()> {
let recap_line = format!(
"(s) {} -> {}",
path.to_string_lossy(),
new_path.to_string_lossy()
);
println!("{}", recap_line.clone().dark_blue());
writeln!(history_writer, "{}", recap_line)
.with_context(|| "Failed to write to history file.")?;
Ok(())
}
pub fn backup<W: Write>(
path: &Path,
new_path: &Path,
history_writer: &mut W,
) -> anyhow::Result<()> {
let mut new_name;
let file_stem = new_path
.file_stem()
.with_context(|| "Expected new file to have a stem.")?;
new_name = format!("{}_backup_{}", file_stem.to_string_lossy(), get_now_str());
if let Some(extension) = new_path.extension() {
new_name.push('.');
new_name.push_str(&extension.to_string_lossy());
}
let mut backup_path = BACKUP_DIR_PATH.clone();
backup_path.push(new_name);
fs::rename(new_path, backup_path.clone()).with_context(|| {
format!(
"Failed to backup! Couldn't move {} to {}.",
new_path.display(),
backup_path.display()
)
})?;
fs::rename(path, new_path).with_context(|| "Failed to rename.")?;
let recap_line = format!(
"(b) {} -> {}",
path.to_string_lossy(),
new_path.to_string_lossy()
);
println!("{}", recap_line.clone().dark_green());
writeln!(history_writer, "{}", recap_line)
.with_context(|| "Failed to write to history file.")?;
Ok(())
}
pub fn overwrite<W: Write>(
path: &Path,
new_path: &Path,
history_writer: &mut W,
) -> anyhow::Result<()> {
fs::rename(path, new_path).with_context(|| "Failed to rename.")?;
let recap_line = format!(
"(o) {} -> {}",
path.to_string_lossy(),
new_path.to_string_lossy()
);
println!("{}", recap_line.clone().dark_yellow());
writeln!(history_writer, "{}", recap_line)
.with_context(|| "Failed to write to history file.")?;
Ok(())
}