mirror of
https://github.com/jrnl-org/jrnl.git
synced 2025-05-12 01:18:31 +02:00
Merge pull request #305 from pcarranza/debug-flag
Added basic logging feature to understand how is configuration loaded
This commit is contained in:
commit
d216dcdbd2
2 changed files with 28 additions and 0 deletions
18
jrnl/cli.py
18
jrnl/cli.py
|
@ -17,16 +17,19 @@ import jrnl
|
||||||
import os
|
import os
|
||||||
import argparse
|
import argparse
|
||||||
import sys
|
import sys
|
||||||
|
import logging
|
||||||
|
|
||||||
xdg_config = os.environ.get('XDG_CONFIG_HOME')
|
xdg_config = os.environ.get('XDG_CONFIG_HOME')
|
||||||
CONFIG_PATH = os.path.join(xdg_config, "jrnl") if xdg_config else os.path.expanduser('~/.jrnl_config')
|
CONFIG_PATH = os.path.join(xdg_config, "jrnl") if xdg_config else os.path.expanduser('~/.jrnl_config')
|
||||||
PYCRYPTO = install.module_exists("Crypto")
|
PYCRYPTO = install.module_exists("Crypto")
|
||||||
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
def parse_args(args=None):
|
def parse_args(args=None):
|
||||||
parser = argparse.ArgumentParser()
|
parser = argparse.ArgumentParser()
|
||||||
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')
|
||||||
|
|
||||||
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="*")
|
||||||
|
@ -90,6 +93,7 @@ def decrypt(journal, filename=None):
|
||||||
def touch_journal(filename):
|
def touch_journal(filename):
|
||||||
"""If filename does not exist, touch the file"""
|
"""If filename does not exist, touch the file"""
|
||||||
if not os.path.exists(filename):
|
if not os.path.exists(filename):
|
||||||
|
log.debug('Creating journal file %s', filename)
|
||||||
util.prompt("[Journal created at {0}]".format(filename))
|
util.prompt("[Journal created at {0}]".format(filename))
|
||||||
open(filename, 'a').close()
|
open(filename, 'a').close()
|
||||||
|
|
||||||
|
@ -114,8 +118,15 @@ def update_config(config, new_config, scope, force_local=False):
|
||||||
config.update(new_config)
|
config.update(new_config)
|
||||||
|
|
||||||
|
|
||||||
|
def configure_logger(debug=False):
|
||||||
|
logging.basicConfig(level=logging.DEBUG if debug else logging.INFO,
|
||||||
|
format='%(levelname)-8s %(name)-12s %(message)s')
|
||||||
|
logging.getLogger('parsedatetime').setLevel(logging.INFO) # disable parsedatetime debug logging
|
||||||
|
|
||||||
|
|
||||||
def run(manual_args=None):
|
def run(manual_args=None):
|
||||||
args = parse_args(manual_args)
|
args = parse_args(manual_args)
|
||||||
|
configure_logger(args.debug)
|
||||||
args.text = [p.decode('utf-8') if util.PY2 and not isinstance(p, unicode) else p for p in args.text]
|
args.text = [p.decode('utf-8') if util.PY2 and not isinstance(p, unicode) else p for p in args.text]
|
||||||
if args.version:
|
if args.version:
|
||||||
version_str = "{0} version {1}".format(jrnl.__title__, jrnl.__version__)
|
version_str = "{0} version {1}".format(jrnl.__title__, jrnl.__version__)
|
||||||
|
@ -123,8 +134,10 @@ def run(manual_args=None):
|
||||||
sys.exit(0)
|
sys.exit(0)
|
||||||
|
|
||||||
if not os.path.exists(CONFIG_PATH):
|
if not os.path.exists(CONFIG_PATH):
|
||||||
|
log.debug('Configuration file not found, installing jrnl...')
|
||||||
config = install.install_jrnl(CONFIG_PATH)
|
config = install.install_jrnl(CONFIG_PATH)
|
||||||
else:
|
else:
|
||||||
|
log.debug('Reading configuration from file %s', CONFIG_PATH)
|
||||||
config = util.load_and_fix_json(CONFIG_PATH)
|
config = util.load_and_fix_json(CONFIG_PATH)
|
||||||
install.upgrade_config(config, config_path=CONFIG_PATH)
|
install.upgrade_config(config, config_path=CONFIG_PATH)
|
||||||
|
|
||||||
|
@ -132,6 +145,7 @@ def run(manual_args=None):
|
||||||
print(util.py2encode(list_journals(config)))
|
print(util.py2encode(list_journals(config)))
|
||||||
sys.exit(0)
|
sys.exit(0)
|
||||||
|
|
||||||
|
log.debug('Using configuration "%s"', config)
|
||||||
original_config = config.copy()
|
original_config = config.copy()
|
||||||
# check if the configuration is supported by available modules
|
# check if the configuration is supported by available modules
|
||||||
if config['encrypt'] and not PYCRYPTO:
|
if config['encrypt'] and not PYCRYPTO:
|
||||||
|
@ -151,8 +165,10 @@ def run(manual_args=None):
|
||||||
except:
|
except:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
log.debug('Using journal "%s"', journal_name)
|
||||||
journal_conf = config['journals'].get(journal_name)
|
journal_conf = config['journals'].get(journal_name)
|
||||||
if type(journal_conf) is dict: # We can override the default config on a by-journal basis
|
if type(journal_conf) is dict: # We can override the default config on a by-journal basis
|
||||||
|
log.debug('Updating configuration with specific jourlnal overrides %s', journal_conf)
|
||||||
config.update(journal_conf)
|
config.update(journal_conf)
|
||||||
else: # But also just give them a string to point to the journal file
|
else: # But also just give them a string to point to the journal file
|
||||||
config['journal'] = journal_conf
|
config['journal'] = journal_conf
|
||||||
|
@ -163,6 +179,7 @@ def run(manual_args=None):
|
||||||
|
|
||||||
config['journal'] = os.path.expanduser(os.path.expandvars(config['journal']))
|
config['journal'] = os.path.expanduser(os.path.expandvars(config['journal']))
|
||||||
touch_journal(config['journal'])
|
touch_journal(config['journal'])
|
||||||
|
log.debug('Using journal path %(journal)s', config)
|
||||||
mode_compose, mode_export = guess_mode(args, config)
|
mode_compose, mode_export = guess_mode(args, config)
|
||||||
|
|
||||||
# open journal file or folder
|
# open journal file or folder
|
||||||
|
@ -204,6 +221,7 @@ def run(manual_args=None):
|
||||||
raw = " ".join(args.text).strip()
|
raw = " ".join(args.text).strip()
|
||||||
if util.PY2 and type(raw) is not unicode:
|
if util.PY2 and type(raw) is not unicode:
|
||||||
raw = raw.decode(sys.getfilesystemencoding())
|
raw = raw.decode(sys.getfilesystemencoding())
|
||||||
|
log.debug('Appending raw line "%s" to journal "%s"', raw, journal_name)
|
||||||
journal.new_entry(raw)
|
journal.new_entry(raw)
|
||||||
util.prompt("[Entry added to {0} journal]".format(journal_name))
|
util.prompt("[Entry added to {0} journal]".format(journal_name))
|
||||||
journal.write()
|
journal.write()
|
||||||
|
|
10
jrnl/util.py
10
jrnl/util.py
|
@ -13,6 +13,7 @@ import tempfile
|
||||||
import subprocess
|
import subprocess
|
||||||
import codecs
|
import codecs
|
||||||
import unicodedata
|
import unicodedata
|
||||||
|
import logging
|
||||||
|
|
||||||
PY3 = sys.version_info[0] == 3
|
PY3 = sys.version_info[0] == 3
|
||||||
PY2 = sys.version_info[0] == 2
|
PY2 = sys.version_info[0] == 2
|
||||||
|
@ -22,6 +23,8 @@ STDOUT = sys.stdout
|
||||||
TEST = False
|
TEST = False
|
||||||
__cached_tz = None
|
__cached_tz = None
|
||||||
|
|
||||||
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
def getpass(prompt="Password: "):
|
def getpass(prompt="Password: "):
|
||||||
if not TEST:
|
if not TEST:
|
||||||
|
@ -96,21 +99,28 @@ def load_and_fix_json(json_path):
|
||||||
"""
|
"""
|
||||||
with open(json_path) as f:
|
with open(json_path) as f:
|
||||||
json_str = f.read()
|
json_str = f.read()
|
||||||
|
log.debug('Configuration file %s read correctly', json_path)
|
||||||
config = None
|
config = None
|
||||||
try:
|
try:
|
||||||
return json.loads(json_str)
|
return json.loads(json_str)
|
||||||
except ValueError as e:
|
except ValueError as e:
|
||||||
|
log.debug('Could not parse configuration %s: %s', json_str, e,
|
||||||
|
exc_info=True)
|
||||||
# Attempt to fix extra ,
|
# Attempt to fix extra ,
|
||||||
json_str = re.sub(r",[ \n]*}", "}", json_str)
|
json_str = re.sub(r",[ \n]*}", "}", json_str)
|
||||||
# Attempt to fix missing ,
|
# Attempt to fix missing ,
|
||||||
json_str = re.sub(r"([^{,]) *\n *(\")", r"\1,\n \2", json_str)
|
json_str = re.sub(r"([^{,]) *\n *(\")", r"\1,\n \2", json_str)
|
||||||
try:
|
try:
|
||||||
|
log.debug('Attempting to reload automatically fixed configuration file %s',
|
||||||
|
json_str)
|
||||||
config = json.loads(json_str)
|
config = json.loads(json_str)
|
||||||
with open(json_path, 'w') as f:
|
with open(json_path, 'w') as f:
|
||||||
json.dump(config, f, indent=2)
|
json.dump(config, f, indent=2)
|
||||||
|
log.debug('Fixed configuration saved in file %s', json_path)
|
||||||
prompt("[Some errors in your jrnl config have been fixed for you.]")
|
prompt("[Some errors in your jrnl config have been fixed for you.]")
|
||||||
return config
|
return config
|
||||||
except ValueError as e:
|
except ValueError as e:
|
||||||
|
log.debug('Could not load fixed configuration: %s', e, exc_info=True)
|
||||||
prompt("[There seems to be something wrong with your jrnl config at {0}: {1}]".format(json_path, e.message))
|
prompt("[There seems to be something wrong with your jrnl config at {0}: {1}]".format(json_path, e.message))
|
||||||
prompt("[Entry was NOT added to your journal]")
|
prompt("[Entry was NOT added to your journal]")
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
|
|
Loading…
Add table
Reference in a new issue