Files
shelf/src/main.rs
2026-08-21 15:07:30 +01:00

123 lines
3.7 KiB
Rust

use std::{env, path::Path, process};
use crate::structs::{Library, Shelf};
use crate::utils::save_library;
mod structs;
mod utils;
fn main() {
let mut args = env::args();
let _binary = args.next();
let mut library = match utils::deserialize_state_file() {
Ok(library) => library,
Err(e) => {
eprintln!("Error creating library: {}", e);
process::exit(1)
}
};
let mut current_shelf = utils::get_current_shelf(&mut library);
if let Some(arg) = args.next() {
match arg.as_str() {
"add" => add_files(&arg, &mut args, &mut current_shelf),
"rm" => remove_files(&mut args, &mut current_shelf),
"ls" => list_library(&mut library),
&_ => add_files(&arg, &mut args, &mut current_shelf),
}
} else {
// Should be replaced by help function
println!("no parameters")
}
let _ = save_library(library);
process::exit(0);
}
fn list_library(library: &mut Library) {
let current_shelf_index =
utils::get_shelf_index(&library.shelves, &library.current_shelf).unwrap_or(0);
let current_shelf = &library.shelves[current_shelf_index];
println!("Shelves: {}", library.shelves.len());
println!("Current Shelf: {}", &current_shelf.name);
println!("Content: ");
for path in &current_shelf.content {
println!(" - {}", path)
}
}
fn add_files(current_arg: &str, args: &mut env::Args, shelf: &mut Shelf) {
// Callable function thing
let mut add_file = |file: &str| {
let file_path = Path::new(&file);
let absolute_path = Path::canonicalize(&file_path).expect("Path cannot be Cannonicalized");
match utils::match_file_name(&file, shelf) {
Ok(_) => {
// Prevent existing files from being added to shelf
println!("File {} is already in current shelf", file);
process::exit(0)
}
Err(_) => {} // Continue with function
}
let _ = shelf
.content
.push(absolute_path.to_str().unwrap().to_string());
println!("Added file: {}", absolute_path.to_str().unwrap());
return;
};
// If add wasn't specified add the file
if current_arg != "add" {
add_file(&current_arg)
}
// For every remaining argument
for file in args {
add_file(&file)
}
return;
}
fn remove_files(args: &mut env::Args, shelf: &mut Shelf) {
if shelf.content.len() < 1 {
println!(
"Shelf \"{}\" is Empty. Are you using the right shelf?",
shelf.name
);
return;
}
if args.len() > 0 {
for file in args {
// If the argument is a number instead of a file name
let index: usize = match file.parse::<usize>() {
Ok(index) => {
println!("path is: {}", &shelf.content[*&index]);
index
}
Err(_) => match utils::match_file_name(&file, shelf) {
Ok(index) => {
println!("path is: {}", &shelf.content[*&index as usize]);
index
}
Err(e) => {
eprintln!("{e}");
process::exit(1)
}
},
};
let file_path = Path::new(&shelf.content[index]);
println!(
"Removed file {} from shelf {}",
file_path.canonicalize().unwrap().to_str().unwrap(),
shelf.name
);
shelf.content.remove(index);
}
} else {
// If there's no file specified, clear the whole thing
shelf.content.clear()
}
}