Browse Source

once_cell and contants

db-refactoring
Coin de Gamma 4 months ago
parent
commit
ef9f6f5f1b
  1. 1
      Cargo.toml
  2. 16
      src/main.rs

1
Cargo.toml

@ -7,3 +7,4 @@ edition = "2021"
[dependencies] [dependencies]
clap = { version = "4.5.16", features = ["derive"] } clap = { version = "4.5.16", features = ["derive"] }
once_cell = "1.19.0"

16
src/main.rs

@ -3,6 +3,8 @@ mod db;
use db::{DB, Item}; use db::{DB, Item};
use once_cell::sync::Lazy;
use clap::{Parser, Subcommand}; use clap::{Parser, Subcommand};
use std::fs; use std::fs;
@ -10,8 +12,10 @@ use std::io::{self, Write};
use std::path::Path; use std::path::Path;
const STORAGE_FOLDER: &str = "storage"; static STORAGE_FOLDER: &str = "storage";
const STORAGE_PATH: &str = "storage/db.mps"; // TODO: concat from STORAGE_FOLDER static STORAGE_PATH: Lazy<String> = Lazy::new(|| {
format!("{}/db.mps", STORAGE_FOLDER)
});
#[derive(Parser)] #[derive(Parser)]
@ -51,7 +55,7 @@ fn init() -> io::Result<()> {
fs::create_dir(STORAGE_FOLDER)?; fs::create_dir(STORAGE_FOLDER)?;
println!("Storage folder created"); println!("Storage folder created");
fs::File::create(STORAGE_PATH)?; fs::File::create(&*STORAGE_PATH)?;
println!("Storage db created."); println!("Storage db created.");
println!("Initialization complete."); println!("Initialization complete.");
println!(""); println!("");
@ -61,7 +65,7 @@ fn init() -> io::Result<()> {
} }
fn add(id: &String) -> io::Result<()> { fn add(id: &String) -> io::Result<()> {
let mut db = DB::new(STORAGE_PATH)?; let mut db = DB::new(&*STORAGE_PATH)?;
if db.contains(id) { if db.contains(id) {
// TODO: ask to edit existing in outer function which invoked this one // TODO: ask to edit existing in outer function which invoked this one
return Err(io::Error::new( return Err(io::Error::new(
@ -71,13 +75,13 @@ fn add(id: &String) -> io::Result<()> {
} }
db.items.insert(Item::from(id.clone())); db.items.insert(Item::from(id.clone()));
db.dump(STORAGE_PATH)?; db.dump(&*STORAGE_PATH)?;
Ok(()) Ok(())
} }
fn list() -> io:: Result<()> { fn list() -> io:: Result<()> {
let db = DB::new(STORAGE_PATH)?; let db = DB::new(&STORAGE_PATH)?;
let mut vec: Vec<_> = db.items.iter().collect(); let mut vec: Vec<_> = db.items.iter().collect();
vec.sort(); vec.sort();
for item in &vec { for item in &vec {

Loading…
Cancel
Save