Refactored path expansion calls into a new path.py file

This also fixed bugs with relative journal and template paths.
This commit is contained in:
apainintheneck 2022-05-04 16:41:47 -07:00
parent e6ed64ac7a
commit b6448cdf0c
7 changed files with 86 additions and 21 deletions

View file

@ -11,6 +11,7 @@ import sys
from . import Entry
from . import time
from .prompt import yesno
from .path import expand_path
class Tag:
@ -404,7 +405,7 @@ def open_journal(journal_name, config, legacy=False):
backwards compatibility with jrnl 1.x
"""
config = config.copy()
config["journal"] = os.path.expanduser(os.path.expandvars(config["journal"]))
config["journal"] = expand_path(config["journal"])
if os.path.isdir(config["journal"]):
if config["encrypt"]:

View file

@ -15,6 +15,7 @@ from jrnl.messages import MsgType
from .color import ERROR_COLOR
from .color import RESET_COLOR
from .output import list_journals
from .path import home_dir
# Constants
DEFAULT_CONFIG_NAME = "jrnl.yaml"
@ -83,9 +84,7 @@ def get_config_path():
),
)
return os.path.join(
config_directory_path or os.path.expanduser("~"), DEFAULT_CONFIG_NAME
)
return os.path.join(config_directory_path or home_dir(), DEFAULT_CONFIG_NAME)
def get_default_config():
@ -112,9 +111,7 @@ def get_default_config():
def get_default_journal_path():
journal_data_path = xdg.BaseDirectory.save_data_path(
XDG_RESOURCE
) or os.path.expanduser("~")
journal_data_path = xdg.BaseDirectory.save_data_path(XDG_RESOURCE) or home_dir()
return os.path.join(journal_data_path, DEFAULT_JOURNAL_NAME)

View file

@ -7,6 +7,9 @@ import logging
import os
import sys
from .path import home_dir
from .path import absolute_path
from .path import expand_path
from .config import DEFAULT_JOURNAL_KEY
from .config import get_config_path
from .config import get_default_config
@ -45,7 +48,7 @@ def find_default_config():
config_path = (
get_config_path()
if os.path.exists(get_config_path())
else os.path.join(os.path.expanduser("~"), ".jrnl_config")
else os.path.join(home_dir(), ".jrnl_config")
)
return config_path
@ -101,11 +104,9 @@ def install():
# Where to create the journal?
default_journal_path = get_default_journal_path()
path_query = f"Path to your journal file (leave blank for {default_journal_path}): "
journal_path = os.path.abspath(input(path_query).strip() or default_journal_path)
journal_path = absolute_path(input(path_query).strip() or default_journal_path)
default_config = get_default_config()
default_config["journals"][DEFAULT_JOURNAL_KEY] = os.path.expanduser(
os.path.expandvars(journal_path)
)
default_config["journals"][DEFAULT_JOURNAL_KEY] = journal_path
# If the folder doesn't exist, create it
path = os.path.split(default_config["journals"][DEFAULT_JOURNAL_KEY])[0]
@ -138,7 +139,7 @@ def _initialize_autocomplete():
def _autocomplete_path(text, state):
expansions = glob.glob(os.path.expanduser(os.path.expandvars(text)) + "*")
expansions = glob.glob(expand_path(text) + "*")
expansions = [e + "/" if os.path.isdir(e) else e for e in expansions]
expansions.append(None)
return expansions[state]

View file

@ -14,6 +14,7 @@ from .editor import get_text_from_editor
from .editor import get_text_from_stdin
from . import time
from .override import apply_overrides
from .path import expand_path
from jrnl.exception import JrnlException
from jrnl.messages import Message
@ -195,8 +196,10 @@ def _get_editor_template(config, **kwargs):
logging.debug("Write mode: no template configured")
return ""
template_path = expand_path(config["template"])
try:
template = open(config["template"]).read()
template = open(template_path).read()
logging.debug("Write mode: template loaded: %s", template)
except OSError:
logging.error("Write mode: template not loaded")
@ -204,7 +207,7 @@ def _get_editor_template(config, **kwargs):
Message(
MsgText.CantReadTemplate,
MsgType.ERROR,
{"template": config["template"]},
{"template": template_path},
)
)

13
jrnl/path.py Normal file
View file

@ -0,0 +1,13 @@
import os.path
def home_dir():
return os.path.expanduser("~")
def expand_path(path):
return os.path.expanduser(os.path.expandvars(path))
def absolute_path(path):
return os.path.abspath(expand_path(path))

View file

@ -11,6 +11,7 @@ from .config import is_config_json
from .config import load_config
from .config import scope_config
from .prompt import yesno
from .path import expand_path
from jrnl.output import print_msg
@ -22,7 +23,7 @@ from jrnl.messages import MsgType
def backup(filename, binary=False):
print(f" Created a backup at {filename}.backup", file=sys.stderr)
filename = os.path.expanduser(os.path.expandvars(filename))
filename = expand_path(filename)
try:
with open(filename, "rb" if binary else "r") as original:
@ -72,15 +73,13 @@ older versions of jrnl anymore.
for journal_name, journal_conf in config["journals"].items():
if isinstance(journal_conf, dict):
path = journal_conf.get("journal")
path = expand_path(journal_conf.get("journal"))
encrypt = journal_conf.get("encrypt")
else:
encrypt = config.get("encrypt")
path = journal_conf
path = expand_path(journal_conf)
if os.path.exists(os.path.expanduser(path)):
path = os.path.expanduser(path)
else:
if not os.path.exists(path):
print(f"\nError: {path} does not exist.")
continue

51
tests/unit/test_path.py Normal file
View file

@ -0,0 +1,51 @@
import pytest
from os import path
from jrnl.path import home_dir
from jrnl.path import expand_path
from jrnl.path import absolute_path
@pytest.fixture
def home_dir_str(monkeypatch):
username = "username"
monkeypatch.setenv("USERPROFILE", username) # for windows
monkeypatch.setenv("HOME", username) # for *nix
return username
@pytest.fixture
def expand_path_test_data(monkeypatch, home_dir_str):
monkeypatch.setenv("VAR", "var")
return [
["~", home_dir_str],
[path.join("~", "${VAR}", "$VAR"), path.join(home_dir_str, "var", "var")],
]
@pytest.fixture
def absolute_path_test_data(monkeypatch, expand_path_test_data):
cwd = "currentdir"
monkeypatch.setattr("jrnl.path.os.getcwd", lambda: cwd)
test_data = [
[".", cwd],
[path.join(".", "dir"), path.join(cwd, "dir")],
[".dot_file", path.join(cwd, ".dot_file")],
]
for inpath, outpath in expand_path_test_data:
test_data.append([inpath, path.join(cwd, outpath)])
return test_data
def test_home_dir(home_dir_str):
assert home_dir() == home_dir_str
def test_expand_path(expand_path_test_data):
for inpath, outpath in expand_path_test_data:
assert expand_path(inpath) == outpath
def test_absolute_path(absolute_path_test_data):
for inpath, outpath in absolute_path_test_data:
assert absolute_path(inpath) == outpath