From c88ef5bf4c78d8c06b81e35f2806d280bbcca479 Mon Sep 17 00:00:00 2001 From: Lars Wirzenius Date: Thu, 23 Sep 2021 09:42:32 +0300 Subject: fix: if a topic path contains missing directories, create them Sponsored-by: author --- jt.md | 8 ++++---- src/error.rs | 4 ++++ src/journal.rs | 11 +++++++++++ 3 files changed, 19 insertions(+), 4 deletions(-) diff --git a/jt.md b/jt.md index 7265724..0ffcc2d 100644 --- a/jt.md +++ b/jt.md @@ -312,15 +312,15 @@ when I try to run jt --editor=none --dirname=jrnl new --topic foo.bar "Abracadab then command fails then stderr contains "foo.bar" -when I run jt --editor=none --dirname=jrnl new-topic foo.bar "Things about Foobars" +when I run jt --editor=none --dirname=jrnl new-topic topics/foo.bar "Things about Foobars" then command is successful -then file jrnl/foo.bar.mdwn contains "Things about Foobars" +then file jrnl/topics/foo.bar.mdwn contains "Things about Foobars" then there are no uncommitted changes in jrnl -when I run jt --editor=none --dirname=jrnl new --topic foo.bar "Abracadabra" +when I run jt --editor=none --dirname=jrnl new --topic topics/foo.bar "Abracadabra" then command is successful and there is one draft in jrnl -and draft 0 in jrnl links to "foo.bar" +and draft 0 in jrnl links to "topics/foo.bar" ~~~ diff --git a/src/error.rs b/src/error.rs index 04ba777..c86ad13 100644 --- a/src/error.rs +++ b/src/error.rs @@ -22,6 +22,10 @@ pub enum JournalError { #[error("directory {0} is not a journal")] NotAJournal(String), + /// The specified directory for the journal does not exist. + #[error("journal directory does not exist: {0}")] + NoJournalDirectory(PathBuf), + /// Failed to create the directory for the journal. #[error("failed to create journal directory {0}")] CreateDirectory(PathBuf, #[source] std::io::Error), diff --git a/src/journal.rs b/src/journal.rs index a48a63d..270bb19 100644 --- a/src/journal.rs +++ b/src/journal.rs @@ -198,7 +198,18 @@ impl Journal { let mut context = Context::new(); context.insert("title", title); + let dirname = self.dirname(); + if !dirname.exists() { + return Err(JournalError::NoJournalDirectory(dirname.to_path_buf())); + } + let pathname = topic_path(self.dirname(), path); + let parent = pathname.parent().unwrap(); + if !parent.is_dir() { + std::fs::create_dir_all(&parent) + .map_err(|err| JournalError::CreateDirectory(parent.to_path_buf(), err))?; + } + let text = self.templates.new_topic(&context)?; std::fs::write(&pathname, text) .map_err(|err| JournalError::WriteTopic(pathname.to_path_buf(), err))?; -- cgit v1.2.1