From d0adf49fee98acc2dc6b842d1e969a7652d2fefb Mon Sep 17 00:00:00 2001 From: Coin de Gamma Date: Tue, 17 Sep 2024 17:40:27 +0000 Subject: [PATCH] basic editing --- src/editor.rs | 11 ++++++++--- src/main.rs | 20 ++++++++++++++++++-- src/storage.rs | 7 ++++++- 3 files changed, 32 insertions(+), 6 deletions(-) diff --git a/src/editor.rs b/src/editor.rs index 3d3acf3..c1a8e3c 100644 --- a/src/editor.rs +++ b/src/editor.rs @@ -7,10 +7,14 @@ use std::io::{self, Write}; const DEFAULT_EDITOR: &str = "nano"; - -pub fn open_to_edit() -> io::Result { +// Use with content "" (empty string) for adding new item +pub fn open_to_edit(content: &String) -> io::Result { // Create a temporary file - let temp_file = NamedTempFile::new()?; + let mut temp_file = NamedTempFile::new()?; + + // Write content + write!(temp_file, "{}", content)?; + // Get the user's preferred editor from the $EDITOR environment variable // Default is 'nano' let editor = env::var("EDITOR").unwrap_or_else(|_| DEFAULT_EDITOR.to_string()); @@ -47,3 +51,4 @@ pub fn open_to_show(content: &String) -> io::Result<()> { .status()?; Ok(()) } + diff --git a/src/main.rs b/src/main.rs index 83e8fb9..e75a7cd 100644 --- a/src/main.rs +++ b/src/main.rs @@ -128,8 +128,9 @@ fn add(id: &String) -> io::Result<()> { PROMPT::NO => return Ok(()), } } - - let content = editor::open_to_edit()?; + + // set empty string because there is no content yet + let content = editor::open_to_edit(&String::from(""))?; st.add(Item::from(id.clone(), content)); st.dump()?; @@ -138,6 +139,21 @@ fn add(id: &String) -> io::Result<()> { fn edit(id: &String) -> io::Result<()> { // TODO: implement + let passphrase = login()?; + let mut st = Storage::from_db(passphrase)?; + if !st.contains(id) { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + format!("Can`t find id: {}", id) + )); + } + + let mut item = (*st.get(id)).clone(); + let new_content = editor::open_to_edit(&item.content)?; + item.content = new_content; + st.update(item); + st.dump()?; + Ok(()) } diff --git a/src/storage.rs b/src/storage.rs index fbba804..2327b59 100644 --- a/src/storage.rs +++ b/src/storage.rs @@ -18,7 +18,7 @@ static STORAGE_PATH: Lazy = Lazy::new(|| { }); static PASSWORD_TEST_SALT: &str = "MyPasswordStorage1234567890"; - +#[derive(Clone)] pub struct Item { pub id: String, pub content: String @@ -200,6 +200,11 @@ impl Storage { self.items.insert(item); } + pub fn update(&mut self, item: Item) { + self.items.remove(&item); + self.items.insert(item); + } + pub fn dump(&self) -> io::Result<()> { let mut file = fs::OpenOptions::new() .write(true)