Browse Source

db refactoring

db-refactoring
Coin de Gamma 4 months ago
parent
commit
dc5c5c5207
  1. 32
      src/db.rs
  2. 44
      src/main.rs

32
src/db.rs

@ -1,13 +1,37 @@
use std::collections::HashSet;
use std::fs;
use std::io::{self, BufRead};
pub struct DB {
pub items: HashSet::<String>
}
impl DB {
pub fn from() -> DB {
return DB::new();
pub fn new(path: &str) -> io::Result<DB> {
let file = fs::File::open(path)?;
let reader = io::BufReader::new(file);
let mut items = HashSet::<String>::new();
for line in reader.lines() {
match line {
Ok(content) => {
items.insert(content);
},
Err(e) => {
eprintln!("Error reading line , {}", e);
}
}
}
let result = DB {
items: items
};
Ok(result)
}
}
//pub fn dump(&self) {
// TODO: implement
//}
}

44
src/main.rs

@ -1,9 +1,12 @@
use clap::{Parser, Subcommand};
mod db;
use std::collections::HashSet;
use db::DB;
use clap::{Parser, Subcommand};
use std::fs;
use std::io::{self, Write, BufRead};
use std::io::{self, Write};
use std::path::Path;
@ -11,9 +14,6 @@ const STORAGE_FOLDER: &str = "storage";
const STORAGE_PATH: &str = "storage/db.mps"; // TODO: concat from STORAGE_FOLDER
type DB = HashSet<String>;
#[derive(Parser)]
#[command(name = "mps", version = "0.0.1", about = "MyPasswordStorage: Tool for storing your passwords locally with git synchronization")]
struct Cli {
@ -38,22 +38,6 @@ enum Commands {
}
fn read_db() -> io::Result<DB> {
let file = fs::File::open(STORAGE_PATH)?;
let reader = io::BufReader::new(file);
let mut db = DB::new();
for line in reader.lines() {
match line {
Ok(content) => {
db.insert(content);
},
Err(e) => {
eprintln!("Error reading line , {}", e);
}
}
}
Ok(db)
}
fn is_inited() -> bool {
let path = Path::new(STORAGE_FOLDER);
@ -68,15 +52,17 @@ fn init() -> io::Result<()> {
println!("Storage folder created");
fs::File::create(STORAGE_PATH)?;
println!("Storage db created");
println!("Initialization complete.");
println!("Now it's required to add folder `{}` under git manually. Don't worry it's going to be encrypted", STORAGE_FOLDER);
println!("Storage db created.");
println!("Initialization complete.");
println!("");
println!("Now it's required to add folder `{}` under git manually.", STORAGE_FOLDER);
println!("Don't worry it's going to be encrypted.");
Ok(())
}
fn add(id: &String) -> io::Result<()> {
let db = read_db()?;
if db.contains(id) {
let db = DB::new(STORAGE_PATH)?;
if db.items.contains(id) {
// TODO: ask to edit existing in outer function which invoked this one
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
@ -93,8 +79,8 @@ fn add(id: &String) -> io::Result<()> {
}
fn list() -> io:: Result<()> {
let db = read_db()?;
let mut vec: Vec<_> = db.iter().collect();
let db = DB::new(STORAGE_PATH)?;
let mut vec: Vec<_> = db.items.iter().collect();
vec.sort();
for item in &vec {
println!("{}", item);

Loading…
Cancel
Save