use std::fs::{read_to_string, OpenOptions};
use std::io::{BufWriter, ErrorKind, Write};
use std::path::{Path, PathBuf};
use anyhow::{anyhow, Result};
use regex::Regex;
use crate::command::Command;
use crate::ops::io::walk;
use crate::ops::path::{path_has_extension, path_is_hidden};
use crate::Recurse;
const BACKUP_FILEPATH_EXTENSION: &str = "bu";
pub(crate) struct ReplaceCommand {}
impl Command for ReplaceCommand {
fn execute(subcmd: Recurse, mut writer: impl Write) -> Result<()> {
println!("Sub-command 'replace' is not implemented yet. Follow issue https://github.com/chrissimpkins/recurse/issues/6 for progress.");
Ok(())
}
}
fn get_backup_filepath(inpath: &Path) -> PathBuf {
match inpath.extension() {
Some(pre_ext) => {
let post_ext = pre_ext.to_string_lossy() + "." + BACKUP_FILEPATH_EXTENSION;
return inpath.with_extension(post_ext.to_string());
}
None => {
return inpath.with_extension(BACKUP_FILEPATH_EXTENSION);
}
}
}
fn has_backup_extension(inpath: &Path) -> bool {
match inpath.extension() {
Some(ext) => return ext.to_string_lossy() == BACKUP_FILEPATH_EXTENSION,
None => return false,
}
}
fn is_root_filepath(inpath: &Path) -> bool {
let invalid_list = ["/", r"\"];
let inpath_needle = inpath.to_string_lossy();
invalid_list.contains(&inpath_needle.as_ref())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_get_secondary_filepath_with_txt_extension() {
let testpath = PathBuf::from("test/path/bogus.txt");
assert_eq!(
get_backup_filepath(&testpath),
PathBuf::from("test/path/bogus.txt.bu")
);
}
#[test]
fn test_get_secondary_filepath_with_2_extension() {
let testpath = PathBuf::from("test/path/bogus.2");
assert_eq!(
get_backup_filepath(&testpath),
PathBuf::from("test/path/bogus.2.bu")
);
}
#[test]
fn test_get_secondary_filepath_without_extension() {
let testpath = PathBuf::from("test/path/bogus");
assert_eq!(
get_backup_filepath(&testpath),
PathBuf::from("test/path/bogus.bu")
);
}
#[test]
fn test_has_secondary_extension_with_secondary_extension() {
let testpath = PathBuf::from("test/path/bogus.txt.bu");
assert!(has_backup_extension(&testpath));
}
#[test]
fn test_has_secondary_extension_with_secondary_extension_alt1() {
let testpath = PathBuf::from("test/path/bogus.bu");
assert!(has_backup_extension(&testpath));
}
#[test]
fn test_has_secondary_extension_without_secondary_extension() {
let testpath = PathBuf::from("test/path/bogus.txt");
assert_eq!(has_backup_extension(&testpath), false);
}
#[test]
fn test_is_root_filepath_with_unix_root() {
let testpath = PathBuf::from("/");
assert!(is_root_filepath(&testpath));
}
#[test]
fn test_is_root_filepath_with_win_root() {
let testpath = PathBuf::from(r"\");
assert!(is_root_filepath(&testpath));
}
#[test]
fn test_is_root_filepath_without_root_fp() {
let testpath = PathBuf::from("test/path/bogus");
assert_eq!(is_root_filepath(&testpath), false);
}
}