Add support to create new journal from cmd

This commit is contained in:
mzfr 2019-07-09 10:37:10 +05:30
parent bb15e68fc7
commit 036df08a9e
2 changed files with 54 additions and 15 deletions

View file

@ -15,6 +15,7 @@ from . import install
from . import plugins from . import plugins
from .util import ERROR_COLOR, RESET_COLOR, UserAbort from .util import ERROR_COLOR, RESET_COLOR, UserAbort
import jrnl import jrnl
from os.path import abspath, join, exists
import argparse import argparse
import sys import sys
import logging import logging
@ -28,6 +29,7 @@ def parse_args(args=None):
parser.add_argument('-v', '--version', dest='version', action="store_true", help="prints version information and exits") parser.add_argument('-v', '--version', dest='version', action="store_true", help="prints version information and exits")
parser.add_argument('-ls', dest='ls', action="store_true", help="displays accessible journals") parser.add_argument('-ls', dest='ls', action="store_true", help="displays accessible journals")
parser.add_argument('-d', '--debug', dest='debug', action='store_true', help='execute in debug mode') parser.add_argument('-d', '--debug', dest='debug', action='store_true', help='execute in debug mode')
parser.add_argument('-create', help='create a new journal', metavar='NAME')
composing = parser.add_argument_group('Composing', 'To write an entry simply write it on the command line, e.g. "jrnl yesterday at 1pm: Went to the gym."') composing = parser.add_argument_group('Composing', 'To write an entry simply write it on the command line, e.g. "jrnl yesterday at 1pm: Went to the gym."')
composing.add_argument('text', metavar='', nargs="*") composing.add_argument('text', metavar='', nargs="*")
@ -157,14 +159,34 @@ def run(manual_args=None):
log.debug('Using configuration "%s"', config) log.debug('Using configuration "%s"', config)
original_config = config.copy() original_config = config.copy()
if args.create:
journal_name = args.create
# if the journal with the same name already exists
if journal_name in config['journals']:
util.prompt("Journal with `{0}` name already exists.".format(journal_name))
sys.exit(1)
# create a config entry for the new journal
default_file_path = join(abspath('.'),install.DEFAULT_JOURNAL_NAME)
config = install.create(journal_name, default_file_path, config)
sys.exit(0)
# If the first textual argument points to a journal file, # If the first textual argument points to a journal file,
# use this! # use this!
journal_name = args.text[0] if (args.text and args.text[0] in config['journals']) else 'default' if args.text and args.text[0] in config['journals']:
journal_name = args.text[0]
if journal_name is not 'default':
args.text = args.text[1:] args.text = args.text[1:]
elif "default" not in config['journals']: # If the current folder contains .jrnl file, read the journal name from it
util.prompt("No default journal configured.") util.prompt("No default journal configured.")
elif exists('.jrnl'):
with open('.jrnl', 'r') as fp:
journal_name = fp.read().strip()
else:
journal_name = 'default'
if journal_name not in config['journals']:
util.prompt("No '{}' journal configured.".format(journal_name))
util.prompt(list_journals(config)) util.prompt(list_journals(config))
sys.exit(1) sys.exit(1)

View file

@ -6,6 +6,7 @@ import readline
import glob import glob
import getpass import getpass
import os import os
import sys
import xdg.BaseDirectory import xdg.BaseDirectory
from . import util from . import util
from . import upgrade from . import upgrade
@ -109,7 +110,7 @@ def load_or_install_jrnl():
return config return config
def install(): def create(journal_name, default_file_path=None, config=None):
def autocomplete(text, state): def autocomplete(text, state):
expansions = glob.glob(os.path.expanduser(os.path.expandvars(text)) + '*') expansions = glob.glob(os.path.expanduser(os.path.expandvars(text)) + '*')
expansions = [e + "/" if os.path.isdir(e) else e for e in expansions] expansions = [e + "/" if os.path.isdir(e) else e for e in expansions]
@ -119,12 +120,25 @@ def install():
readline.parse_and_bind("tab: complete") readline.parse_and_bind("tab: complete")
readline.set_completer(autocomplete) readline.set_completer(autocomplete)
# Where to create the journal? # Take the default config if none is provided
path_query = 'Path to your journal file (leave blank for {}): '.format(JOURNAL_FILE_PATH) if config is None:
journal_path = util.py23_input(path_query).strip() or JOURNAL_FILE_PATH config = default_config
default_config['journals']['default'] = os.path.expanduser(os.path.expandvars(journal_path))
path = os.path.split(default_config['journals']['default'])[0] # If the folder doesn't exist, create it # Set up the default journal file path
if default_file_path is None:
default_file_path = JOURNAL_FILE_PATH
# Where to create the journal?
path_query = 'Path to your journal file (leave blank for {}): '.format(default_file_path)
journal_path = util.py23_input(path_query).strip() or default_file_path
journal_path = os.path.expanduser(os.path.expandvars(journal_path))
config['journals'][journal_name] = {'journal': journal_path}
if os.path.exists(journal_path) and not util.yesno("File {} already exists. Do you still want to use it?".format(journal_path), default=False):
sys.exit(1)
path = os.path.split(config['journals'][journal_name]['journal'])[0] # If the folder doesn't exist, create it
try: try:
os.makedirs(path) os.makedirs(path)
except OSError: except OSError:
@ -133,18 +147,21 @@ def install():
# Encrypt it? # Encrypt it?
password = getpass.getpass("Enter password for journal (leave blank for no encryption): ") password = getpass.getpass("Enter password for journal (leave blank for no encryption): ")
if password: if password:
default_config['encrypt'] = True config['journals'][journal_name] = True
if util.yesno("Do you want to store the password in your keychain?", default=True): if util.yesno("Do you want to store the password in your keychain?", default=True):
util.set_keychain("default", password) util.set_keychain(journal_name, password)
else: else:
util.set_keychain("default", None) util.set_keychain(journal_name, None)
EncryptedJournal._create(default_config['journals']['default'], password) EncryptedJournal._create(journal_path, password)
print("Journal will be encrypted.") print("Journal will be encrypted.")
else: else:
PlainJournal._create(default_config['journals']['default']) PlainJournal._create(journal_path)
config = default_config config = default_config
save_config(config) save_config(config)
if password: if password:
config['password'] = password config['password'] = password
return config return config
def install():
return create('default')