Browse Source

basic editor

db-refactoring
Coin de Gamma 3 months ago
parent
commit
069bc02f80
  1. 1
      Cargo.toml
  2. 14
      src/db.rs
  3. 29
      src/editor.rs
  4. 14
      src/main.rs

1
Cargo.toml

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

14
src/db.rs

@ -13,9 +13,12 @@ pub struct Item {
}
impl Item {
pub fn from(s: String) -> Item {
pub fn from(s: String, c: String) -> Item {
Item { id: s, content: c }
}
pub fn from_d(s: String) -> Item {
Item { id: s, content: String::from("") }
}
}
}
impl PartialEq for Item {
@ -65,7 +68,8 @@ impl DB {
for line in reader.lines() {
match line {
Ok(id) => {
items.insert(Item::from(id));
// TODO: check content
items.insert(Item::from_d(id));
},
Err(e) => {
eprintln!("Error reading line, {}", e);
@ -80,7 +84,8 @@ impl DB {
}
pub fn contains(&self, id: &String) -> bool {
let item = Item::from(id.clone());
// TODO: check with content
let item = Item::from_d(id.clone());
self.items.contains(&item)
}
@ -98,4 +103,3 @@ impl DB {
}
}

29
src/editor.rs

@ -0,0 +1,29 @@
use std::env;
use std::fs::read_to_string;
use std::process::Command;
use tempfile::NamedTempFile;
use std::io;
pub fn open_to_edit() -> io::Result<String> {
// Create a temporary file
let temp_file = NamedTempFile::new()?;
// Get the user's preferred editor from the $EDITOR environment variable
// Default is 'nano'
let editor = env::var("EDITOR").unwrap_or_else(|_| "nano".to_string());
// Get the path of the temp file
let file_path = temp_file.path().to_str().unwrap().to_string();
// Open the file in the external editor
Command::new(editor)
.arg(&file_path)
.status()
.expect("Failed to open editor");
// Read the file content after editing
let edited_content = read_to_string(&file_path)?;
// Print the edited content
Ok(edited_content)
}

14
src/main.rs

@ -1,4 +1,5 @@
mod db;
mod editor;
use db::{DB, Item};
@ -28,7 +29,7 @@ struct Cli {
#[derive(Subcommand)]
enum Commands {
/// Initialisation of storage and config, use this in first time of usage of mps
/// Initialization of storage and config, use this in first time of usage of mps
Init,
/// Adds new item with unique id to the db
@ -39,7 +40,7 @@ enum Commands {
/// Lists all ids stored in db
List
}
@ -73,8 +74,13 @@ fn add(id: &String) -> io::Result<()> {
format!("Dublicate item id: {}. Item id's must be unique.", id)
))
}
db.items.insert(Item::from(id.clone()));
// TODO: implement encryption
let content = editor::open_to_edit()?;
println!("Content");
println!("--------");
println!("{}", content);
db.items.insert(Item::from(id.clone(), content));
db.dump()?;
Ok(())

Loading…
Cancel
Save