Add functionality for creating new journals from cmd

This commit is contained in:
Maruan Al-Shedivat 2015-08-20 01:34:14 +03:00
parent d0f86d398f
commit e36c152a0a
2 changed files with 56 additions and 21 deletions

View file

@ -27,6 +27,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="*")
@ -150,14 +151,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("According to your jrnl_config, you already have a journal with name `{0}`. Please choose another name for your new journal.".format(journal_name))
sys.exit(1)
# create a config entry for the new journal
journal_file_path = os.path.join(os.path.expanduser('.'),
install.DEFAULT_JOURNAL_NAME)
config = install.create(journal_name, journal_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.") elif os.path.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

@ -91,8 +91,7 @@ def load_or_install_jrnl():
log.debug('Configuration file not found, installing jrnl...') log.debug('Configuration file not found, installing jrnl...')
return install() return install()
def create(journal_name, default_journal_file_path=None, config=None):
def install():
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]
@ -102,12 +101,26 @@ 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_journal_file_path is None:
default_journal_file_path = JOURNAL_FILE_PATH
# Where to create the journal?
path_query = 'Path to your journal file (leave blank for {}): '.format(default_journal_file_path)
journal_path = util.py23_input(path_query).strip() or \
default_journal_file_path
journal_path = os.path.expanduser(os.path.expandvars(journal_path))
config['journals'][journal_name] = {'journal': journal_path}
# if the provided filename already taken, ask what to do
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:
@ -116,18 +129,19 @@ 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]['password'] = password
config['journals'][journal_name]['encrypt'] = 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
save_config(config) save_config(config)
if password:
config['password'] = password
return config return config
def install():
return create('default')