lockman/src/add_command.rs
2024-08-31 16:28:01 +02:00

77 lines
2.8 KiB
Rust

use std::{path::PathBuf, process::exit, str::FromStr};
use crate::{
check_command::calculate_file_hash,
cli::AddArgs,
lockfile::{load_project_files, update_lock_file, update_project_file},
};
pub fn add_command(args: AddArgs) {
let path = PathBuf::from_str(&args.path).expect("Failed to parse file path");
let (project_files, lock_files) = load_project_files();
let (mut project_files, mut lock_files) = (project_files.files, lock_files.locks);
if !path.is_file() {
println!(
"The following path does not point to a file:\n\t{:?}",
args.path
);
exit(1);
}
let hash = calculate_file_hash(&path);
// Insert to lock file map
if let Some(old_hash) = lock_files.get(&args.path) {
if *old_hash == hash {
eprintln!(
"File {} already on record, hashes do match",
args.path.clone()
);
} else if args.allow_override {
println!(
"Replaced hash for file {}:\n\tOld: {old_hash}\n\tNew: {hash}",
args.path
);
let hc = hash.clone();
lock_files.insert(args.path.clone(), hc);
} else {
println!(
"File already on record {}:\n\tKnown: {old_hash}\n\tNew: {hash}",
args.path
);
eprintln!("Specify flag \"--override\" to allow replacement");
exit(1);
}
} else {
lock_files.insert(args.path.clone(), hash);
}
// Insert to project file map
if let Some(old_url) = project_files.get(&args.path) {
// Path is already present
if let Some(new_url) = args.url {
if &new_url != old_url && args.allow_override {
println!(
"Replaced URL for file {}:\n\tOld: {old_url}\n\tNew: {new_url}",
args.path
);
project_files.insert(args.path, new_url);
} else if &new_url != old_url {
println!("File already on record with a different URL {}:\n\tKnown: {old_url}\n\tNew: {new_url}", args.path);
eprintln!("Specify flag \"--override\" to allow replacement");
exit(1);
} else {
eprintln!("File is already on record with the same URL");
}
} else {
// File is already known with URL but none is specified
eprintln!("Although no URL has been specified, the URL already known for the specific path has been kept:\n\tKnown URL: {old_url}");
}
} else {
// Path is new to project
project_files.insert(args.path, args.url.unwrap_or_default()); // TODO: Consider what to do
}
update_lock_file(lock_files);
update_project_file(project_files);
}