From 74724b21850c92f30d8533ff30cd0434e6301e6e Mon Sep 17 00:00:00 2001 From: Eshan Date: Sat, 6 Jun 2020 15:46:06 -0400 Subject: [PATCH] Create directory if it doesn't exist (#963) * create dir if it doesn't exist * switch order of print and creation * makedirs instead of mkdir and stderr printing * add test * black reformatting --- features/core.feature | 6 ++++++ jrnl/EncryptedJournal.py | 5 ++++- jrnl/Journal.py | 5 ++++- 3 files changed, 14 insertions(+), 2 deletions(-) diff --git a/features/core.feature b/features/core.feature index 3008cfce..ab61eb87 100644 --- a/features/core.feature +++ b/features/core.feature @@ -113,3 +113,9 @@ Feature: Basic reading and writing to a journal 2013-06-10 15:40 Life is good. """ And we should get no error + + Scenario: Journal directory does not exist + Given we use the config "missing_directory.yaml" + When we run "jrnl Life is good" + and we run "jrnl -n 1" + Then the output should contain "Life is good" diff --git a/jrnl/EncryptedJournal.py b/jrnl/EncryptedJournal.py index 2a6df460..ec4ceee8 100644 --- a/jrnl/EncryptedJournal.py +++ b/jrnl/EncryptedJournal.py @@ -40,8 +40,11 @@ class EncryptedJournal(Journal): """Opens the journal file defined in the config and parses it into a list of Entries. Entries have the form (date, title, body).""" filename = filename or self.config["journal"] - + dirname = os.path.dirname(filename) if not os.path.exists(filename): + if not os.path.isdir(dirname): + os.makedirs(dirname) + print(f"[Directory {dirname} created]", file=sys.stderr) self.create_file(filename) self.password = util.create_password(self.name) print( diff --git a/jrnl/Journal.py b/jrnl/Journal.py index 23fa80a0..72b3b9cd 100644 --- a/jrnl/Journal.py +++ b/jrnl/Journal.py @@ -74,8 +74,11 @@ class Journal: """Opens the journal file defined in the config and parses it into a list of Entries. Entries have the form (date, title, body).""" filename = filename or self.config["journal"] - + dirname = os.path.dirname(filename) if not os.path.exists(filename): + if not os.path.isdir(dirname): + os.makedirs(dirname) + print(f"[Directory {dirname} created]", file=sys.stderr) self.create_file(filename) print(f"[Journal '{self.name}' created at {filename}]", file=sys.stderr)