From 6e60becfb6fd87b1101b97006910396132be7777 Mon Sep 17 00:00:00 2001 From: Lars Wirzenius Date: Sat, 3 Apr 2021 10:37:45 +0300 Subject: feat: launch editor for new draft --- src/error.rs | 8 ++++++++ src/journal.rs | 28 +++++++++++++++++++++------- 2 files changed, 29 insertions(+), 7 deletions(-) diff --git a/src/error.rs b/src/error.rs index 232eaec..05bb74d 100644 --- a/src/error.rs +++ b/src/error.rs @@ -45,4 +45,12 @@ pub enum JournalError { /// Failed to get metadata for specific file in drafts folder. #[error("failed to stat draft in {0}: {1}")] StatDraft(PathBuf, #[source] std::io::Error), + + /// Error spawning editor. + #[error("failed to start editor {0}: {1}")] + SpawnEditor(PathBuf, #[source] std::io::Error), + + /// Editor failed. + #[error("editor {0} failed: {1}")] + EditorFailed(PathBuf, String), } diff --git a/src/journal.rs b/src/journal.rs index 911f9a3..2adb48d 100644 --- a/src/journal.rs +++ b/src/journal.rs @@ -1,6 +1,5 @@ use crate::error::JournalError; use chrono::Local; -use log::debug; use std::path::{Path, PathBuf}; use std::process::Command; @@ -48,7 +47,7 @@ impl Journal { self.dirname().join("entries") } - pub fn new_draft(&self, title: &str, _editor: &str) -> anyhow::Result<()> { + pub fn new_draft(&self, title: &str, editor: &str) -> anyhow::Result<()> { let drafts = self.drafts(); if !drafts.exists() { std::fs::create_dir(&drafts)?; @@ -56,7 +55,8 @@ impl Journal { let pathname = self.pick_file_id(&drafts)?; let text = format!(r#"[[!meta title="{}"]]"#, title); - std::fs::write(pathname, format!("{}\n\n", text))?; + std::fs::write(&pathname, format!("{}\n\n", text))?; + self.edit(editor, &pathname)?; Ok(()) } @@ -84,11 +84,25 @@ impl Journal { } } + fn edit(&self, editor: &str, filename: &Path) -> Result<(), JournalError> { + match Command::new(editor).arg(filename).output() { + Err(err) => Err(JournalError::SpawnEditor(filename.to_path_buf(), err)), + Ok(output) => { + if output.status.success() { + Ok(()) + } else { + let stderr = String::from_utf8_lossy(&output.stderr); + Err(JournalError::EditorFailed( + filename.to_path_buf(), + stderr.into_owned(), + )) + } + } + } + } + pub fn edit_draft(&self, editor: &str, filename: &Path) -> anyhow::Result<()> { - debug!("edit_draft: editor={:?}", editor); - debug!("edit_draft: filename={:?}", filename); - Command::new(editor).arg(filename).status()?; - debug!("edit_draft: editor finished"); + self.edit(editor, filename)?; Ok(()) } -- cgit v1.2.1