first attempt with strudel

This commit is contained in:
shai 2024-03-07 17:30:47 +02:00
parent 2af05e4008
commit 2a0496f03c
42 changed files with 186 additions and 86 deletions

View file

@ -6,4 +6,5 @@ import sys
from jrnl.main import run from jrnl.main import run
if __name__ == "__main__": if __name__ == "__main__":
logger.info(f'Condition in body log is: __name__({__name__}) = "__main__"') # STRUDEL_LOG hrxs
sys.exit(run()) sys.exit(run())

View file

@ -103,10 +103,12 @@ def get_default_colors() -> dict[str, Any]:
def scope_config(config: dict, journal_name: str) -> dict: def scope_config(config: dict, journal_name: str) -> dict:
if journal_name not in config["journals"]: if journal_name not in config["journals"]:
logger.info(f'Condition in body log is: journal_name NotIn config["journals"]') # STRUDEL_LOG kwyl
return config return config
config = config.copy() config = config.copy()
journal_conf = config["journals"].get(journal_name) journal_conf = config["journals"].get(journal_name)
if isinstance(journal_conf, dict): if isinstance(journal_conf, dict):
logger.info(f'Condition in body log is: journal_conf is type: dict') # STRUDEL_LOG cwdp
# We can override the default config on a by-journal basis # We can override the default config on a by-journal basis
logging.debug( logging.debug(
"Updating configuration with specific journal overrides:\n%s", "Updating configuration with specific journal overrides:\n%s",
@ -130,8 +132,10 @@ def verify_config_colors(config: dict) -> bool:
for key, color in config["colors"].items(): for key, color in config["colors"].items():
upper_color = color.upper() upper_color = color.upper()
if upper_color == "NONE": if upper_color == "NONE":
logger.info(f'Condition in body log is: upper_color({upper_color}) = "NONE"') # STRUDEL_LOG utcp
continue continue
if not getattr(colorama.Fore, upper_color, None): if not getattr(colorama.Fore, upper_color, None):
logger.info(f'Condition in body log is: UnaryOp getattr( colorama.Fore upper_color None)') # STRUDEL_LOG zdgs
print_msg( print_msg(
Message( Message(
MsgText.InvalidColor, MsgText.InvalidColor,
@ -182,8 +186,10 @@ def update_config(
or config['journals'][scope] is just a string pointing to a journal file, or config['journals'][scope] is just a string pointing to a journal file,
or within the scope""" or within the scope"""
if scope and isinstance(config["journals"][scope], dict): if scope and isinstance(config["journals"][scope], dict):
logger.info(f'Condition in body log is: scope BoolOp isinstance( config["journals"][scope] dict)') # STRUDEL_LOG eyxh
config["journals"][scope].update(new_config) config["journals"][scope].update(new_config)
elif scope and force_local: # Convert to dict elif scope and force_local: # Convert to dict
logger.info(f'Condition in body log is: Both scope AND force_local are True') # STRUDEL_LOG bzob
config["journals"][scope] = {"journal": config["journals"][scope]} config["journals"][scope] = {"journal": config["journals"][scope]}
config["journals"][scope].update(new_config) config["journals"][scope].update(new_config)
else: else:
@ -195,11 +201,14 @@ def get_journal_name(args: argparse.Namespace, config: dict) -> argparse.Namespa
# The first arg might be a journal name # The first arg might be a journal name
if args.text: if args.text:
logger.info(f'Condition in body log is: Attribute "text" of "args" is True') # STRUDEL_LOG leag
potential_journal_name = args.text[0] potential_journal_name = args.text[0]
if potential_journal_name[-1] == ":": if potential_journal_name[-1] == ":":
logger.info(f'Condition in body log is: potential_journal_name[UnaryOp 1] = ":"') # STRUDEL_LOG cqmv
potential_journal_name = potential_journal_name[0:-1] potential_journal_name = potential_journal_name[0:-1]
if potential_journal_name in config["journals"]: if potential_journal_name in config["journals"]:
logger.info(f'Condition in body log is: potential_journal_name in config["journals"]') # STRUDEL_LOG npkg
args.journal_name = potential_journal_name args.journal_name = potential_journal_name
args.text = args.text[1:] args.text = args.text[1:]
@ -217,6 +226,7 @@ def cmd_requires_valid_journal_name(func: Callable) -> Callable:
def validate_journal_name(journal_name: str, config: dict) -> None: def validate_journal_name(journal_name: str, config: dict) -> None:
if journal_name not in config["journals"]: if journal_name not in config["journals"]:
logger.info(f'Condition in body log is: journal_name NotIn config["journals"]') # STRUDEL_LOG thla
raise JrnlException( raise JrnlException(
Message( Message(
MsgText.NoNamedJournal, MsgText.NoNamedJournal,

View file

@ -22,6 +22,7 @@ from jrnl.path import get_templates_path
def get_text_from_editor(config: dict, template: str = "") -> str: def get_text_from_editor(config: dict, template: str = "") -> str:
suffix = ".jrnl" suffix = ".jrnl"
if config["template"]: if config["template"]:
logger.info(f'Condition in body log is: config["template"]') # STRUDEL_LOG djpb
template_filename = Path(config["template"]).name template_filename = Path(config["template"]).name
suffix = "-" + template_filename suffix = "-" + template_filename
filehandle, tmpfile = tempfile.mkstemp(prefix="jrnl", text=True, suffix=suffix) filehandle, tmpfile = tempfile.mkstemp(prefix="jrnl", text=True, suffix=suffix)
@ -29,6 +30,7 @@ def get_text_from_editor(config: dict, template: str = "") -> str:
with open(tmpfile, "w", encoding="utf-8") as f: with open(tmpfile, "w", encoding="utf-8") as f:
if template: if template:
logger.info(f'Condition in body log is: template') # STRUDEL_LOG ygot
f.write(template) f.write(template)
try: try:
@ -47,6 +49,7 @@ def get_text_from_editor(config: dict, template: str = "") -> str:
os.remove(tmpfile) os.remove(tmpfile)
if not raw: if not raw:
logger.info(f'Condition in body log is: (not raw) is True') # STRUDEL_LOG newi
raise JrnlException(Message(MsgText.NoTextReceived, MsgStyle.NORMAL)) raise JrnlException(Message(MsgText.NoTextReceived, MsgStyle.NORMAL))
return raw return raw
@ -80,6 +83,7 @@ def get_text_from_stdin() -> str:
def get_template_path(template_path: str, jrnl_template_dir: str) -> str: def get_template_path(template_path: str, jrnl_template_dir: str) -> str:
actual_template_path = os.path.join(jrnl_template_dir, template_path) actual_template_path = os.path.join(jrnl_template_dir, template_path)
if not os.path.exists(actual_template_path): if not os.path.exists(actual_template_path):
logger.info(f'Condition in body log is: UnaryOp os.path.exists( actual_template_path)') # STRUDEL_LOG rlgy
logging.debug( logging.debug(
f"Couldn't open {actual_template_path}. " f"Couldn't open {actual_template_path}. "
"Treating template path like a local / abs path." "Treating template path like a local / abs path."

View file

@ -32,6 +32,7 @@ class Jrnlv1Encryption(BasePasswordEncryption):
try: try:
plain_padded = decryptor.update(cipher) + decryptor.finalize() plain_padded = decryptor.update(cipher) + decryptor.finalize()
if plain_padded[-1] in (" ", 32): if plain_padded[-1] in (" ", 32):
logger.info(f'Condition in body log is: plain_padded[UnaryOp 1] in tuple of length 2.') # STRUDEL_LOG cznx
# Ancient versions of jrnl. Do not judge me. # Ancient versions of jrnl. Do not judge me.
return plain_padded.decode(self._encoding).rstrip(" ") return plain_padded.decode(self._encoding).rstrip(" ")
else: else:

View file

@ -7,6 +7,7 @@ from typing import TYPE_CHECKING
from typing import Type from typing import Type
if TYPE_CHECKING: if TYPE_CHECKING:
logger.info(f'Condition in body log is: TYPE_CHECKING') # STRUDEL_LOG rxap
from .BaseEncryption import BaseEncryption from .BaseEncryption import BaseEncryption
@ -29,6 +30,7 @@ def determine_encryption_method(config: str | bool) -> Type["BaseEncryption"]:
key = config key = config
if isinstance(config, str): if isinstance(config, str):
logger.info(f'Condition in body log is: config is type: str') # STRUDEL_LOG ifbj
key = config.lower() key = config.lower()
my_class = ENCRYPTION_METHODS[key] my_class = ENCRYPTION_METHODS[key]

View file

@ -40,14 +40,17 @@ def upgrade_config(config_data: dict, alt_config_path: str | None = None) -> Non
default_config = get_default_config() default_config = get_default_config()
missing_keys = set(default_config).difference(config_data) missing_keys = set(default_config).difference(config_data)
if missing_keys: if missing_keys:
logger.info(f'Condition in body log is: missing_keys') # STRUDEL_LOG mipm
for key in missing_keys: for key in missing_keys:
config_data[key] = default_config[key] config_data[key] = default_config[key]
different_version = config_data["version"] != __version__ different_version = config_data["version"] != __version__
if different_version: if different_version:
logger.info(f'Condition in body log is: different_version') # STRUDEL_LOG odzs
config_data["version"] = __version__ config_data["version"] = __version__
if missing_keys or different_version: if missing_keys or different_version:
logger.info(f'Condition in body log is: Either missing_keys OR different_version is True') # STRUDEL_LOG xugd
save_config(config_data, alt_config_path) save_config(config_data, alt_config_path)
config_path = alt_config_path if alt_config_path else get_config_path() config_path = alt_config_path if alt_config_path else get_config_path()
print_msg( print_msg(
@ -68,6 +71,7 @@ def find_default_config() -> str:
def find_alt_config(alt_config: str) -> str: def find_alt_config(alt_config: str) -> str:
if not os.path.exists(alt_config): if not os.path.exists(alt_config):
logger.info(f'Condition in body log is: UnaryOp os.path.exists( alt_config)') # STRUDEL_LOG ruqd
raise JrnlException( raise JrnlException(
Message( Message(
MsgText.AltConfigNotFound, MsgStyle.ERROR, {"config_file": alt_config} MsgText.AltConfigNotFound, MsgStyle.ERROR, {"config_file": alt_config}
@ -88,10 +92,12 @@ def load_or_install_jrnl(alt_config_path: str) -> dict:
) )
if os.path.exists(config_path): if os.path.exists(config_path):
logger.info(f'Condition in body log is: os.path.exists( config_path)') # STRUDEL_LOG mosl
logging.debug("Reading configuration from file %s", config_path) logging.debug("Reading configuration from file %s", config_path)
config = load_config(config_path) config = load_config(config_path)
if config is None: if config is None:
logger.info(f'Condition in body log is: config({config}) Is None') # STRUDEL_LOG sply
raise JrnlException( raise JrnlException(
Message( Message(
MsgText.CantParseConfigFile, MsgText.CantParseConfigFile,
@ -103,6 +109,7 @@ def load_or_install_jrnl(alt_config_path: str) -> dict:
) )
if is_old_version(config_path): if is_old_version(config_path):
logger.info(f'Condition in body log is: is_old_version( config_path)') # STRUDEL_LOG xcqp
from jrnl import upgrade from jrnl import upgrade
upgrade.upgrade_jrnl(config_path) upgrade.upgrade_jrnl(config_path)
@ -145,12 +152,14 @@ def install() -> dict:
# Encrypt it? # Encrypt it?
encrypt = yesno(Message(MsgText.EncryptJournalQuestion), default=False) encrypt = yesno(Message(MsgText.EncryptJournalQuestion), default=False)
if encrypt: if encrypt:
logger.info(f'Condition in body log is: encrypt') # STRUDEL_LOG afpw
default_config["encrypt"] = True default_config["encrypt"] = True
print_msg(Message(MsgText.JournalEncrypted, MsgStyle.NORMAL)) print_msg(Message(MsgText.JournalEncrypted, MsgStyle.NORMAL))
# Use colors? # Use colors?
use_colors = yesno(Message(MsgText.UseColorsQuestion), default=True) use_colors = yesno(Message(MsgText.UseColorsQuestion), default=True)
if use_colors: if use_colors:
logger.info(f'Condition in body log is: use_colors') # STRUDEL_LOG edic
default_config["colors"] = get_default_colors() default_config["colors"] = get_default_colors()
save_config(default_config) save_config(default_config)
@ -169,6 +178,7 @@ def install() -> dict:
def _initialize_autocomplete() -> None: def _initialize_autocomplete() -> None:
# readline is not included in Windows Active Python and perhaps some other distss # readline is not included in Windows Active Python and perhaps some other distss
if sys.modules.get("readline"): if sys.modules.get("readline"):
logger.info(f'Condition in body log is: sys.modules.get( "readline")') # STRUDEL_LOG dusn
import readline import readline
readline.set_completer_delims(" \t\n;") readline.set_completer_delims(" \t\n;")

View file

@ -14,6 +14,7 @@ def get_keyring_password(journal_name: str = "default") -> str | None:
return keyring.get_password("jrnl", journal_name) return keyring.get_password("jrnl", journal_name)
except keyring.errors.KeyringError as e: except keyring.errors.KeyringError as e:
if not isinstance(e, keyring.errors.NoKeyringError): if not isinstance(e, keyring.errors.NoKeyringError):
logger.info(f'Condition in body log is: UnaryOp isinstance( e keyring.errors.NoKeyringError)') # STRUDEL_LOG ladx
print_msg(Message(MsgText.KeyringRetrievalFailure, MsgStyle.ERROR)) print_msg(Message(MsgText.KeyringRetrievalFailure, MsgStyle.ERROR))
return None return None
@ -23,6 +24,7 @@ def set_keyring_password(password: str, journal_name: str = "default") -> None:
return keyring.set_password("jrnl", journal_name, password) return keyring.set_password("jrnl", journal_name, password)
except keyring.errors.KeyringError as e: except keyring.errors.KeyringError as e:
if isinstance(e, keyring.errors.NoKeyringError): if isinstance(e, keyring.errors.NoKeyringError):
logger.info(f'Condition in body log is: isinstance( e keyring.errors.NoKeyringError)') # STRUDEL_LOG gnnn
msg = Message(MsgText.KeyringBackendNotFound, MsgStyle.WARNING) msg = Message(MsgText.KeyringBackendNotFound, MsgStyle.WARNING)
else: else:
msg = Message(MsgText.KeyringRetrievalFailure, MsgStyle.ERROR) msg = Message(MsgText.KeyringRetrievalFailure, MsgStyle.ERROR)

View file

@ -18,6 +18,7 @@ from jrnl.output import print_msg
def configure_logger(debug: bool = False) -> None: def configure_logger(debug: bool = False) -> None:
if not debug: if not debug:
logger.info(f'Condition in body log is: (not debug) is True') # STRUDEL_LOG ealt
logging.disable() logging.disable()
return return
@ -35,6 +36,7 @@ def configure_logger(debug: bool = False) -> None:
def run(manual_args: list[str] | None = None) -> int: def run(manual_args: list[str] | None = None) -> int:
try: try:
if manual_args is None: if manual_args is None:
logger.info(f'Condition in body log is: manual_args({manual_args}) Is None') # STRUDEL_LOG yrbb
manual_args = sys.argv[1:] manual_args = sys.argv[1:]
args = parse_args(manual_args) args = parse_args(manual_args)
@ -63,14 +65,17 @@ def run(manual_args: list[str] | None = None) -> int:
debug = False debug = False
try: try:
if args.debug: # type: ignore if args.debug: # type: ignore
logger.info(f'Condition in body log is: Attribute "debug" of "args" is True') # STRUDEL_LOG ynyg
debug = True debug = True
except NameError: except NameError:
# This should only happen when the exception # This should only happen when the exception
# happened before the args were parsed # happened before the args were parsed
if "--debug" in sys.argv: if "--debug" in sys.argv:
logger.info(f'Condition in body log is: "--debug" in sys.argv') # STRUDEL_LOG zyck
debug = True debug = True
if debug: if debug:
logger.info(f'Condition in body log is: debug') # STRUDEL_LOG ccav
from rich.console import Console from rich.console import Console
traceback.print_tb(sys.exc_info()[2]) traceback.print_tb(sys.exc_info()[2])

View file

@ -24,6 +24,7 @@ def deprecated_cmd(
) )
if callback is not None: if callback is not None:
logger.info(f'Condition in body log is: callback IsNot None') # STRUDEL_LOG ojwq
callback(**kwargs) callback(**kwargs)
@ -67,8 +68,10 @@ def list_journals(configuration: dict, format: str | None = None) -> str:
} }
if format == "json": if format == "json":
logger.info(f'Condition in body log is: format({format}) = "json"') # STRUDEL_LOG aoms
return journal_list_to_json(journal_list) return journal_list_to_json(journal_list)
elif format == "yaml": elif format == "yaml":
logger.info(f'Condition in body log is: format({format}) = "yaml"') # STRUDEL_LOG cqep
return journal_list_to_yaml(journal_list) return journal_list_to_yaml(journal_list)
else: else:
return journal_list_to_stdout(journal_list) return journal_list_to_stdout(journal_list)
@ -97,11 +100,13 @@ def print_msgs(
m = format_msg_text(msg) m = format_msg_text(msg)
if i != len(msgs) - 1: if i != len(msgs) - 1:
logger.info(f'Condition in body log is: i != len( msgs) BinOp 1') # STRUDEL_LOG wjax
m.append(delimiter) m.append(delimiter)
text.append(m) text.append(m)
if style.append_space: if style.append_space:
logger.info(f'Condition in body log is: Attribute "append_space" of "style" is True') # STRUDEL_LOG ecqs
text.append(" ") text.append(" ")
decorated_text = style.decoration.callback(text, **kwargs) decorated_text = style.decoration.callback(text, **kwargs)
@ -110,6 +115,7 @@ def print_msgs(
console = _get_console(stderr=True) console = _get_console(stderr=True)
if get_input: if get_input:
logger.info(f'Condition in body log is: get_input') # STRUDEL_LOG zvxo
return str(console.input(prompt=decorated_text, password=hide_input)) return str(console.input(prompt=decorated_text, password=hide_input))
console.print(decorated_text, new_line_start=style.prepend_newline) console.print(decorated_text, new_line_start=style.prepend_newline)

View file

@ -37,6 +37,7 @@ IMPORT_FORMATS = sorted(__importer_types.keys())
def get_exporter(format: str) -> Type[TextExporter] | None: def get_exporter(format: str) -> Type[TextExporter] | None:
for exporter in __exporters: for exporter in __exporters:
if hasattr(exporter, "names") and format in exporter.names: if hasattr(exporter, "names") and format in exporter.names:
logger.info(f'Condition in body log is: hasattr( exporter "names") BoolOp format in exporter.names') # STRUDEL_LOG vxeb
return exporter return exporter
return None return None
@ -44,5 +45,6 @@ def get_exporter(format: str) -> Type[TextExporter] | None:
def get_importer(format: str) -> Type[JRNLImporter] | None: def get_importer(format: str) -> Type[JRNLImporter] | None:
for importer in __importers: for importer in __importers:
if hasattr(importer, "names") and format in importer.names: if hasattr(importer, "names") and format in importer.names:
logger.info(f'Condition in body log is: hasattr( importer "names") BoolOp format in importer.names') # STRUDEL_LOG tkzr
return importer return importer
return None return None

View file

@ -24,17 +24,20 @@ def create_password(journal_name: str) -> str:
) )
if not pw: if not pw:
logger.info(f'Condition in body log is: (not pw) is True') # STRUDEL_LOG xyiw
print_msg(Message(MsgText.PasswordCanNotBeEmpty, MsgStyle.WARNING)) print_msg(Message(MsgText.PasswordCanNotBeEmpty, MsgStyle.WARNING))
continue continue
elif pw == print_msg( elif pw == print_msg(
Message(MsgText.PasswordConfirmEntry, MsgStyle.PROMPT), **kwargs Message(MsgText.PasswordConfirmEntry, MsgStyle.PROMPT), **kwargs
): ):
logger.info(f'Condition in body log is: pw = print_msg( Message( MsgText.PasswordConfirmEntry MsgStyle.PROMPT))') # STRUDEL_LOG dhhc
break break
print_msg(Message(MsgText.PasswordDidNotMatch, MsgStyle.ERROR)) print_msg(Message(MsgText.PasswordDidNotMatch, MsgStyle.ERROR))
if yesno(Message(MsgText.PasswordStoreInKeychain), default=True): if yesno(Message(MsgText.PasswordStoreInKeychain), default=True):
logger.info(f'Condition in body log is: yesno( Message( MsgText.PasswordStoreInKeychain))') # STRUDEL_LOG feov
from jrnl.keyring import set_keyring_password from jrnl.keyring import set_keyring_password
set_keyring_password(pw, journal_name) set_keyring_password(pw, journal_name)
@ -44,6 +47,7 @@ def create_password(journal_name: str) -> str:
def prompt_password(first_try: bool = True) -> str: def prompt_password(first_try: bool = True) -> str:
if not first_try: if not first_try:
logger.info(f'Condition in body log is: (not first_try) is True') # STRUDEL_LOG xmea
print_msg(Message(MsgText.WrongPasswordTryAgain, MsgStyle.WARNING)) print_msg(Message(MsgText.WrongPasswordTryAgain, MsgStyle.WARNING))
return ( return (

View file

@ -27,13 +27,16 @@ def parse(
) -> datetime.datetime | None: ) -> datetime.datetime | None:
"""Parses a string containing a fuzzy date and returns a datetime.datetime object""" """Parses a string containing a fuzzy date and returns a datetime.datetime object"""
if not date_str: if not date_str:
logger.info(f'Condition in body log is: (not date_str) is True') # STRUDEL_LOG tedc
return None return None
elif isinstance(date_str, datetime.datetime): elif isinstance(date_str, datetime.datetime):
logger.info(f'Condition in body log is: isinstance( date_str datetime.datetime)') # STRUDEL_LOG idcg
return date_str return date_str
# Don't try to parse anything with 6 or fewer characters and was parsed from the # Don't try to parse anything with 6 or fewer characters and was parsed from the
# existing journal. It's probably a markdown footnote # existing journal. It's probably a markdown footnote
if len(date_str) <= 6 and bracketed: if len(date_str) <= 6 and bracketed:
logger.info(f'Condition in body log is: len( date_str) <= 6 BoolOp bracketed') # STRUDEL_LOG nujw
return None return None
default_date = DEFAULT_FUTURE if inclusive else DEFAULT_PAST default_date = DEFAULT_FUTURE if inclusive else DEFAULT_PAST
@ -49,6 +52,7 @@ def parse(
date = dateparse(date_str, default=default_date) date = dateparse(date_str, default=default_date)
if date.year == FAKE_YEAR: if date.year == FAKE_YEAR:
logger.info(f'Condition in body log is: date.year = FAKE_YEAR') # STRUDEL_LOG axfv
date = datetime.datetime( date = datetime.datetime(
datetime.datetime.now().year, date.timetuple()[1:6] datetime.datetime.now().year, date.timetuple()[1:6]
) )
@ -59,6 +63,7 @@ def parse(
date = date.timetuple() date = date.timetuple()
except Exception as e: except Exception as e:
if e.args[0] == "day is out of range for month": if e.args[0] == "day is out of range for month":
logger.info(f'Condition in body log is: e.args[0] = "day is out of range for month"') # STRUDEL_LOG janj
y, m, d, H, M, S = default_date.timetuple()[:6] y, m, d, H, M, S = default_date.timetuple()[:6]
default_date = datetime.datetime(y, m, d - 1, H, M, S) default_date = datetime.datetime(y, m, d - 1, H, M, S)
else: else:
@ -68,6 +73,7 @@ def parse(
hasDate = parse_context.hasDate hasDate = parse_context.hasDate
if not hasDate and not hasTime: if not hasDate and not hasTime:
logger.info(f'Condition in body log is: (not hasDate) is True BoolOp (not hasTime) is True') # STRUDEL_LOG onqx
try: # Try and parse this as a single year try: # Try and parse this as a single year
year = int(date_str) year = int(date_str)
return datetime.datetime(year, 1, 1) return datetime.datetime(year, 1, 1)
@ -77,6 +83,7 @@ def parse(
return None return None
if hasDate and not hasTime: if hasDate and not hasTime:
logger.info(f'Condition in body log is: hasDate BoolOp (not hasTime) is True') # STRUDEL_LOG uzyb
date = datetime.datetime( # Use the default time date = datetime.datetime( # Use the default time
*date[:3], *date[:3],
hour=23 if inclusive else default_hour or 0, hour=23 if inclusive else default_hour or 0,
@ -91,6 +98,7 @@ def parse(
# tell it to prefer past dates # tell it to prefer past dates
dt = datetime.datetime.now() - date dt = datetime.datetime.now() - date
if dt.days < -28 and not year_present: if dt.days < -28 and not year_present:
logger.info(f'Condition in body log is: dt.days < UnaryOp 28 BoolOp (not year_present) is True') # STRUDEL_LOG eodx
date = date.replace(date.year - 1) date = date.replace(date.year - 1)
return date return date

View file

@ -40,6 +40,7 @@ def backup(filename: str, binary: bool = False):
print_msg(Message(MsgText.DoesNotExist, MsgStyle.WARNING, {"name": filename})) print_msg(Message(MsgText.DoesNotExist, MsgStyle.WARNING, {"name": filename}))
cont = yesno(f"\nCreate {filename}?", default=False) cont = yesno(f"\nCreate {filename}?", default=False)
if not cont: if not cont:
logger.info(f'Condition in body log is: (not cont) is True') # STRUDEL_LOG vqec
raise JrnlException(Message(MsgText.UpgradeAborted, MsgStyle.WARNING)) raise JrnlException(Message(MsgText.UpgradeAborted, MsgStyle.WARNING))
@ -62,6 +63,7 @@ def upgrade_jrnl(config_path: str) -> None:
for journal_name, journal_conf in config["journals"].items(): for journal_name, journal_conf in config["journals"].items():
if isinstance(journal_conf, dict): if isinstance(journal_conf, dict):
logger.info(f'Condition in body log is: journal_conf is type: dict') # STRUDEL_LOG jdkv
path = expand_path(journal_conf.get("journal")) path = expand_path(journal_conf.get("journal"))
encrypt = journal_conf.get("encrypt") encrypt = journal_conf.get("encrypt")
else: else:
@ -69,14 +71,17 @@ def upgrade_jrnl(config_path: str) -> None:
path = expand_path(journal_conf) path = expand_path(journal_conf)
if os.path.exists(path): if os.path.exists(path):
logger.info(f'Condition in body log is: os.path.exists( path)') # STRUDEL_LOG ooxz
path = os.path.expanduser(path) path = os.path.expanduser(path)
else: else:
print_msg(Message(MsgText.DoesNotExist, MsgStyle.ERROR, {"name": path})) print_msg(Message(MsgText.DoesNotExist, MsgStyle.ERROR, {"name": path}))
continue continue
if encrypt: if encrypt:
logger.info(f'Condition in body log is: encrypt') # STRUDEL_LOG paoq
encrypted_journals[journal_name] = path encrypted_journals[journal_name] = path
elif os.path.isdir(path): elif os.path.isdir(path):
logger.info(f'Condition in body log is: os.path.isdir( path)') # STRUDEL_LOG rbud
other_journals[journal_name] = path other_journals[journal_name] = path
else: else:
plain_journals[journal_name] = path plain_journals[journal_name] = path
@ -116,6 +121,7 @@ def upgrade_jrnl(config_path: str) -> None:
cont = yesno(Message(MsgText.ContinueUpgrade), default=False) cont = yesno(Message(MsgText.ContinueUpgrade), default=False)
if not cont: if not cont:
logger.info(f'Condition in body log is: (not cont) is True') # STRUDEL_LOG ywxs
raise JrnlException(Message(MsgText.UpgradeAborted, MsgStyle.WARNING)) raise JrnlException(Message(MsgText.UpgradeAborted, MsgStyle.WARNING))
for journal_name, path in encrypted_journals.items(): for journal_name, path in encrypted_journals.items():
@ -166,6 +172,7 @@ def upgrade_jrnl(config_path: str) -> None:
failed_journals = [j for j in all_journals if not j.validate_parsing()] failed_journals = [j for j in all_journals if not j.validate_parsing()]
if len(failed_journals) > 0: if len(failed_journals) > 0:
logger.info(f'Condition in body log is: len( failed_journals) > 0') # STRUDEL_LOG euov
raise JrnlException( raise JrnlException(
Message(MsgText.AbortingUpgrade, MsgStyle.WARNING), Message(MsgText.AbortingUpgrade, MsgStyle.WARNING),
Message( Message(
@ -195,6 +202,7 @@ def is_old_version(config_path: str) -> bool:
def _print_journal_summary(journals: dict, header: Message, pad: int) -> None: def _print_journal_summary(journals: dict, header: Message, pad: int) -> None:
if not journals: if not journals:
logger.info(f'Condition in body log is: (not journals) is True') # STRUDEL_LOG jlxe
return return
msgs = [header] msgs = [header]

View file

@ -46,6 +46,7 @@ def generate_pa11y_config_from_sitemap():
def output_file(file): def output_file(file):
if not os.getenv("CI", False): if not os.getenv("CI", False):
logger.info(f'Condition in body log is: UnaryOp os.getenv( "CI" False)') # STRUDEL_LOG tafj
return return
print(f"::group::{file}") print(f"::group::{file}")

View file

@ -18,14 +18,18 @@ pytest_plugins = [
def pytest_bdd_apply_tag(tag, function): def pytest_bdd_apply_tag(tag, function):
# skip markers # skip markers
if tag == "skip_win": if tag == "skip_win":
logger.info(f'Condition in body log is: tag({tag}) = "skip_win"') # STRUDEL_LOG ured
marker = mark.skipif(on_windows(), reason="Skip test on Windows") marker = mark.skipif(on_windows(), reason="Skip test on Windows")
elif tag == "skip_posix": elif tag == "skip_posix":
logger.info(f'Condition in body log is: tag({tag}) = "skip_posix"') # STRUDEL_LOG ddbs
marker = mark.skipif(on_posix(), reason="Skip test on Mac/Linux") marker = mark.skipif(on_posix(), reason="Skip test on Mac/Linux")
# only on OS markers # only on OS markers
elif tag == "on_win": elif tag == "on_win":
logger.info(f'Condition in body log is: tag({tag}) = "on_win"') # STRUDEL_LOG zjqp
marker = mark.skipif(not on_windows(), reason="Skip test not on Windows") marker = mark.skipif(not on_windows(), reason="Skip test not on Windows")
elif tag == "on_posix": elif tag == "on_posix":
logger.info(f'Condition in body log is: tag({tag}) = "on_posix"') # STRUDEL_LOG zgja
marker = mark.skipif(not on_posix(), reason="Skip test not on Mac/Linux") marker = mark.skipif(not on_posix(), reason="Skip test not on Mac/Linux")
else: else:
# Fall back to pytest-bdd's default behavior # Fall back to pytest-bdd's default behavior
@ -42,13 +46,17 @@ def pytest_runtest_setup(item):
on_nix = on_posix() on_nix = on_posix()
if "skip_win" in markers and on_win: if "skip_win" in markers and on_win:
logger.info(f'Condition in body log is: "skip_win" in markers BoolOp on_win') # STRUDEL_LOG iabq
skip("Skip test on Windows") skip("Skip test on Windows")
if "skip_posix" in markers and on_nix: if "skip_posix" in markers and on_nix:
logger.info(f'Condition in body log is: "skip_posix" in markers BoolOp on_nix') # STRUDEL_LOG asee
skip("Skip test on Mac/Linux") skip("Skip test on Mac/Linux")
if "on_win" in markers and not on_win: if "on_win" in markers and not on_win:
logger.info(f'Condition in body log is: "on_win" in markers BoolOp (not on_win) is True') # STRUDEL_LOG gknf
skip("Skip test not on Windows") skip("Skip test not on Windows")
if "on_posix" in markers and not on_nix: if "on_posix" in markers and not on_nix:
logger.info(f'Condition in body log is: "on_posix" in markers BoolOp (not on_nix) is True') # STRUDEL_LOG ojpo
skip("Skip test not on Mac/Linux") skip("Skip test not on Mac/Linux")

View file

@ -7,11 +7,13 @@ import os
def does_directory_contain_files(file_list, directory_path): def does_directory_contain_files(file_list, directory_path):
if not os.path.isdir(directory_path): if not os.path.isdir(directory_path):
logger.info(f'Condition in body log is: UnaryOp os.path.isdir( directory_path)') # STRUDEL_LOG iyeb
return False return False
for file in file_list.split("\n"): for file in file_list.split("\n"):
fullpath = directory_path + "/" + file fullpath = directory_path + "/" + file
if not os.path.isfile(fullpath): if not os.path.isfile(fullpath):
logger.info(f'Condition in body log is: UnaryOp os.path.isfile( fullpath)') # STRUDEL_LOG iemx
return False return False
return True return True
@ -20,6 +22,7 @@ def does_directory_contain_files(file_list, directory_path):
def does_directory_contain_n_files(directory_path, number): def does_directory_contain_n_files(directory_path, number):
count = 0 count = 0
if not os.path.isdir(directory_path): if not os.path.isdir(directory_path):
logger.info(f'Condition in body log is: UnaryOp os.path.isdir( directory_path)') # STRUDEL_LOG ykwn
return False return False
files = [ files = [
@ -51,6 +54,7 @@ def get_nested_val(dictionary, path, *default):
return functools.reduce(lambda x, y: x[y], path.split("."), dictionary) return functools.reduce(lambda x, y: x[y], path.split("."), dictionary)
except KeyError: except KeyError:
if default: if default:
logger.info(f'Condition in body log is: default') # STRUDEL_LOG ltbz
return default[0] return default[0]
raise raise

View file

@ -61,14 +61,17 @@ def output_should_contain(expected, which_output_stream, cli_run, it_should):
assert expected assert expected
if which_output_stream is None: if which_output_stream is None:
logger.info(f'Condition in body log is: which_output_stream({which_output_stream}) Is None') # STRUDEL_LOG ivav
assert ((expected in cli_run["stdout"]) == it_should) or ( assert ((expected in cli_run["stdout"]) == it_should) or (
(expected in cli_run["stderr"]) == it_should (expected in cli_run["stderr"]) == it_should
), output_str ), output_str
elif which_output_stream == "standard": elif which_output_stream == "standard":
logger.info(f'Condition in body log is: which_output_stream({which_output_stream}) = "standard"') # STRUDEL_LOG zlhq
assert (expected in cli_run["stdout"]) == it_should, output_str assert (expected in cli_run["stdout"]) == it_should, output_str
elif which_output_stream == "error": elif which_output_stream == "error":
logger.info(f'Condition in body log is: which_output_stream({which_output_stream}) = "error"') # STRUDEL_LOG qlkb
assert (expected in cli_run["stderr"]) == it_should, output_str assert (expected in cli_run["stderr"]) == it_should, output_str
else: else:
@ -156,12 +159,14 @@ def default_journal_location(journal_file, journal_dir, config_on_disk, temp_dir
def config_var_on_disk(config_on_disk, journal_name, it_should, some_yaml): def config_var_on_disk(config_on_disk, journal_name, it_should, some_yaml):
actual = config_on_disk actual = config_on_disk
if journal_name: if journal_name:
logger.info(f'Condition in body log is: journal_name') # STRUDEL_LOG etsi
actual = actual["journals"][journal_name] actual = actual["journals"][journal_name]
expected = YAML(typ="safe").load(some_yaml) expected = YAML(typ="safe").load(some_yaml)
actual_slice = actual actual_slice = actual
if isinstance(actual, dict): if isinstance(actual, dict):
logger.info(f'Condition in body log is: actual is type: dict') # STRUDEL_LOG dqjv
# `expected` objects formatted in yaml only compare one level deep # `expected` objects formatted in yaml only compare one level deep
actual_slice = {key: actual.get(key) for key in expected.keys()} actual_slice = {key: actual.get(key) for key in expected.keys()}
@ -191,12 +196,14 @@ def config_var_on_disk(config_on_disk, journal_name, it_should, some_yaml):
def config_var_in_memory(config_in_memory, journal_name, it_should, some_yaml): def config_var_in_memory(config_in_memory, journal_name, it_should, some_yaml):
actual = config_in_memory["overrides"] actual = config_in_memory["overrides"]
if journal_name: if journal_name:
logger.info(f'Condition in body log is: journal_name') # STRUDEL_LOG ulkm
actual = actual["journals"][journal_name] actual = actual["journals"][journal_name]
expected = YAML(typ="safe").load(some_yaml) expected = YAML(typ="safe").load(some_yaml)
actual_slice = actual actual_slice = actual
if isinstance(actual, dict): if isinstance(actual, dict):
logger.info(f'Condition in body log is: actual is type: dict') # STRUDEL_LOG rnbf
# `expected` objects formatted in yaml only compare one level deep # `expected` objects formatted in yaml only compare one level deep
actual_slice = {key: get_nested_val(actual, key) for key in expected.keys()} actual_slice = {key: get_nested_val(actual, key) for key in expected.keys()}
@ -272,6 +279,7 @@ def content_of_file_should_be(file_path, file_content, cache_dir):
for actual_line, expected_line in zip(actual_content, expected_content): for actual_line, expected_line in zip(actual_content, expected_content):
if actual_line.startswith("tags: ") and expected_line.startswith("tags: "): if actual_line.startswith("tags: ") and expected_line.startswith("tags: "):
logger.info(f'Condition in body log is: actual_line.startswith( "tags: ") BoolOp expected_line.startswith( "tags: ")') # STRUDEL_LOG mcja
assert_equal_tags_ignoring_order( assert_equal_tags_ignoring_order(
actual_line, expected_line, actual_content, expected_content actual_line, expected_line, actual_content, expected_content
) )
@ -300,9 +308,11 @@ def cache_dir_contains_files(file_list, cache_dir):
def assert_output_is_valid_language(cli_run, language_name): def assert_output_is_valid_language(cli_run, language_name):
language_name = language_name.upper() language_name = language_name.upper()
if language_name == "XML": if language_name == "XML":
logger.info(f'Condition in body log is: language_name({language_name}) = "XML"') # STRUDEL_LOG dxkz
xml_tree = ElementTree.fromstring(cli_run["stdout"]) xml_tree = ElementTree.fromstring(cli_run["stdout"])
assert xml_tree, "Invalid XML" assert xml_tree, "Invalid XML"
elif language_name == "JSON": elif language_name == "JSON":
logger.info(f'Condition in body log is: language_name({language_name}) = "JSON"') # STRUDEL_LOG boxr
assert json.loads(cli_run["stdout"]), "Invalid JSON" assert json.loads(cli_run["stdout"]), "Invalid JSON"
else: else:
assert False, f"Language name {language_name} not recognized" assert False, f"Language name {language_name} not recognized"
@ -314,6 +324,7 @@ def assert_parsed_output_item_count(node_name, number, parsed_output):
obj = parsed_output["obj"] obj = parsed_output["obj"]
if lang == "XML": if lang == "XML":
logger.info(f'Condition in body log is: lang({lang}) = "XML"') # STRUDEL_LOG erlc
xml_node_names = (node.tag for node in obj) xml_node_names = (node.tag for node in obj)
assert node_name in xml_node_names, str(list(xml_node_names)) assert node_name in xml_node_names, str(list(xml_node_names))
@ -321,6 +332,7 @@ def assert_parsed_output_item_count(node_name, number, parsed_output):
assert actual_entry_count == number, actual_entry_count assert actual_entry_count == number, actual_entry_count
elif lang == "JSON": elif lang == "JSON":
logger.info(f'Condition in body log is: lang({lang}) = "JSON"') # STRUDEL_LOG vtrh
my_obj = obj my_obj = obj
for node in node_name.split("."): for node in node_name.split("."):
@ -342,13 +354,16 @@ def assert_output_field_content(field_name, comparison, expected_keys, parsed_ou
obj = parsed_output["obj"] obj = parsed_output["obj"]
expected_keys = expected_keys.split("\n") expected_keys = expected_keys.split("\n")
if len(expected_keys) == 1: if len(expected_keys) == 1:
logger.info(f'Condition in body log is: len( expected_keys) = 1') # STRUDEL_LOG jtiw
expected_keys = expected_keys[0] expected_keys = expected_keys[0]
if lang == "XML": if lang == "XML":
logger.info(f'Condition in body log is: lang({lang}) = "XML"') # STRUDEL_LOG sjoz
xml_node_names = (node.tag for node in obj) xml_node_names = (node.tag for node in obj)
assert field_name in xml_node_names, str(list(xml_node_names)) assert field_name in xml_node_names, str(list(xml_node_names))
if field_name == "tags": if field_name == "tags":
logger.info(f'Condition in body log is: field_name({field_name}) = "tags"') # STRUDEL_LOG ocyv
actual_tags = set(t.attrib["name"] for t in obj.find("tags")) actual_tags = set(t.attrib["name"] for t in obj.find("tags"))
assert set(actual_tags) == set(expected_keys), [ assert set(actual_tags) == set(expected_keys), [
actual_tags, actual_tags,
@ -358,6 +373,7 @@ def assert_output_field_content(field_name, comparison, expected_keys, parsed_ou
assert False, "This test only works for tags in XML" assert False, "This test only works for tags in XML"
elif lang == "JSON": elif lang == "JSON":
logger.info(f'Condition in body log is: lang({lang}) = "JSON"') # STRUDEL_LOG encw
my_obj = obj my_obj = obj
for node in field_name.split("."): for node in field_name.split("."):
@ -368,7 +384,9 @@ def assert_output_field_content(field_name, comparison, expected_keys, parsed_ou
my_obj = my_obj[node] my_obj = my_obj[node]
if comparison == "be": if comparison == "be":
logger.info(f'Condition in body log is: comparison({comparison}) = "be"') # STRUDEL_LOG nciy
if isinstance(my_obj, str): if isinstance(my_obj, str):
logger.info(f'Condition in body log is: my_obj is type: str') # STRUDEL_LOG axdm
assert expected_keys == my_obj, [my_obj, expected_keys] assert expected_keys == my_obj, [my_obj, expected_keys]
else: else:
assert set(expected_keys) == set(my_obj), [ assert set(expected_keys) == set(my_obj), [
@ -376,7 +394,9 @@ def assert_output_field_content(field_name, comparison, expected_keys, parsed_ou
set(expected_keys), set(expected_keys),
] ]
elif comparison == "contain": elif comparison == "contain":
logger.info(f'Condition in body log is: comparison({comparison}) = "contain"') # STRUDEL_LOG fmfm
if isinstance(my_obj, str): if isinstance(my_obj, str):
logger.info(f'Condition in body log is: my_obj is type: str') # STRUDEL_LOG qtfe
assert expected_keys in my_obj, [my_obj, expected_keys] assert expected_keys in my_obj, [my_obj, expected_keys]
else: else:
assert all(elem in my_obj for elem in expected_keys), [ assert all(elem in my_obj for elem in expected_keys), [
@ -405,6 +425,7 @@ def count_editor_args(num_args, cli_run, editor_state, it_should):
assert cli_run["mocks"]["editor"].called == it_should assert cli_run["mocks"]["editor"].called == it_should
if isinstance(num_args, int): if isinstance(num_args, int):
logger.info(f'Condition in body log is: num_args is type: int') # STRUDEL_LOG mthy
assert len(editor_state["command"]) == int(num_args) assert len(editor_state["command"]) == int(num_args)
@ -427,8 +448,10 @@ def contains_editor_file(comparison, str_value, editor_state):
content = editor_state["tmpfile"]["content"] content = editor_state["tmpfile"]["content"]
# content = f'\n"""\n{content}\n"""\n' # content = f'\n"""\n{content}\n"""\n'
if comparison == "be": if comparison == "be":
logger.info(f'Condition in body log is: comparison({comparison}) = "be"') # STRUDEL_LOG hrup
assert content == str_value assert content == str_value
elif comparison == "contain": elif comparison == "contain":
logger.info(f'Condition in body log is: comparison({comparison}) = "contain"') # STRUDEL_LOG ytoz
assert str_value in content assert str_value in content
else: else:
assert False, f"Comparison '{comparison}' not supported" assert False, f"Comparison '{comparison}' not supported"

View file

@ -15,6 +15,7 @@ from jrnl.main import run
@when(parse('we change directory to "{directory_name}"')) @when(parse('we change directory to "{directory_name}"'))
def when_we_change_directory(directory_name): def when_we_change_directory(directory_name):
if not os.path.isdir(directory_name): if not os.path.isdir(directory_name):
logger.info(f'Condition in body log is: UnaryOp os.path.isdir( directory_name)') # STRUDEL_LOG ahcx
os.mkdir(directory_name) os.mkdir(directory_name)
os.chdir(directory_name) os.chdir(directory_name)