Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix bug that prevented --format pretty and --format short from working #1177

Merged
merged 32 commits into from
Mar 6, 2021
Merged
Show file tree
Hide file tree
Changes from 13 commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
1f8351a
behavior test for format --pretty
sriniv27 Feb 3, 2021
d44a6e8
add pretty exporter
sriniv27 Feb 3, 2021
2251cd3
include vscode debugging config
sriniv27 Feb 3, 2021
3d69131
config file for pretty formatting
sriniv27 Feb 3, 2021
bfb975b
update gitignore
sriniv27 Feb 3, 2021
1739cee
basic colorize unittest
sriniv27 Feb 4, 2021
15efc56
implement behave test steps for format --pretty
sriniv27 Feb 4, 2021
ce930a2
make color handling more robust
sriniv27 Feb 4, 2021
c9404d0
rework core run() so config_upgrade can be tested
sriniv27 Feb 4, 2021
be8c48d
formatting for pretty exporter
sriniv27 Feb 4, 2021
ca45c76
base .vscode/launch.json and ignore further user modifications from SCM
sriniv27 Feb 4, 2021
b8daeec
fix linting errors
sriniv27 Feb 4, 2021
ddb62b7
make format
sriniv27 Feb 4, 2021
457375d
Revert "make format"
sriniv27 Feb 6, 2021
166ca60
Revert "make color handling more robust"
sriniv27 Feb 6, 2021
cc9a2f1
Revert "config file for pretty formatting"
sriniv27 Feb 6, 2021
afc48bb
delete prettyexporter
sriniv27 Feb 6, 2021
06f5ef3
Revert "Revert "config file for pretty formatting""
sriniv27 Feb 7, 2021
1bd5931
delete remaining unneded code
sriniv27 Feb 7, 2021
6e3574c
define dummy exporter type pretty
sriniv27 Feb 7, 2021
2642cde
first cut at wrapper method to export journals
sriniv27 Feb 7, 2021
ddebb67
match indentation to rest of file
sriniv27 Feb 7, 2021
ac0233a
behave test and dummy short exporter
sriniv27 Feb 7, 2021
694ba3b
unittest export_journal
sriniv27 Feb 7, 2021
9d60911
update unittest
sriniv27 Feb 7, 2021
e0f7736
make format
sriniv27 Feb 7, 2021
9b2633a
fix bad mock import
sriniv27 Feb 7, 2021
edc8cd9
address formatting
sriniv27 Feb 14, 2021
0a6e5f9
Address code review
sriniv27 Feb 27, 2021
b1adedb
Update jrnl/jrnl.py with suggestion
sriniv27 Mar 3, 2021
77ac858
update tests and imports for removal of _export_journal
sriniv27 Mar 3, 2021
8256414
Update core.py
sriniv27 Mar 3, 2021
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -54,3 +54,8 @@ exp/
_extras/
*.sublime-*
site/

.coverage
sriniv27 marked this conversation as resolved.
Show resolved Hide resolved
.vscode/settings.json
coverage.xml
.vscode/launch.json
31 changes: 31 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
{
sriniv27 marked this conversation as resolved.
Show resolved Hide resolved
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "behave",
"type": "python",
"request": "launch",
"program": "behave", // adjust as needed for virtualenv
"args": [
"features/upgrade.feature",
"--stop",
"-n",
"without colors to colors"
],
"justMyCode": true,
"console": "integratedTerminal"
},
{
"name": "Jrnl",
"type": "python",
"request": "launch",
"program": "jrnl", //adjust as needed for virtualenv
"args": [],
"justMyCode": false,
"console": "integratedTerminal"
}
],
}
19 changes: 19 additions & 0 deletions features/data/configs/pretty.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
default_hour: 9
sriniv27 marked this conversation as resolved.
Show resolved Hide resolved
default_minute: 0
editor: "vim"
encrypt: false
highlight: true
journals:
default: features/journals/simple.journal
linewrap: 80
tagsymbols: "@"
template: false
timeformat: "%Y-%m-%d %H:%M"
indent_character: "|"
colors:
body: green
title: blue
date: red
tags: magenta


5 changes: 5 additions & 0 deletions features/format.feature
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
Feature: Custom formats
Scenario: Pretty Printing aka the Default
Given We use the config "pretty.yaml"
When we run "jrnl --format pretty -3"
Then we should get no error
And the output should be pretty printed

Scenario Outline: JSON format
Given we use the config "<config>.yaml"
Expand Down
8 changes: 8 additions & 0 deletions features/steps/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
import toml
import yaml


import jrnl.time
from jrnl import Journal
from jrnl import __version__
Expand Down Expand Up @@ -394,6 +395,12 @@ def all_input_was_used(context):
def run(context, command, text=""):
text = text or context.text or ""

if "config_path" in context and context.config_path is not None:
with open(context.config_path) as f:
context.jrnl_config = yaml.load(f, Loader=yaml.FullLoader)
else:
context.jrnl_config = None

if "cache_dir" in context and context.cache_dir is not None:
cache_dir = os.path.join("features", "cache", context.cache_dir)
command = command.format(cache_dir=cache_dir)
Expand Down Expand Up @@ -423,6 +430,7 @@ def _mock_editor(command):
patch("sys.stdin.read", side_effect=lambda: text), \
patch("jrnl.time.parse", side_effect=_mock_time_parse(context)), \
patch("jrnl.config.get_config_path", side_effect=lambda: context.config_path), \
patch("jrnl.install.load_or_install_jrnl",wraps=jrnl.install.load_or_install_jrnl), \
sriniv27 marked this conversation as resolved.
Show resolved Hide resolved
patch("jrnl.install.get_config_path", side_effect=lambda: context.config_path) \
:
context.editor = mock_editor
Expand Down
42 changes: 41 additions & 1 deletion features/steps/export_steps.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,55 @@
# Copyright (C) 2012-2021 jrnl contributors
# License: https://www.gnu.org/licenses/gpl-3.0.html


import json
import os
import shutil
import random
import string
from xml.etree import ElementTree

from colorama import Fore, Style
from behave import given
from behave import then
import colorama


def style_text(to_bold: bool, text_color: Fore, text_to_print: str):
"""Generate colorized and styled text for expected output. Its purpose is the same as Entry.colorize

:param to_bold: Flag whether the text should be bolded
:type to_bold: bool
:param text_color: Valid colorama.Fore color for the text
:type text_color: colorama.Fore
:param text_to_print: Message contents
:type text_to_print: str
:return: Styled and colored output
:rtype: str
"""
if to_bold:
text_style = Style.BRIGHT
else:
text_style = Style.NORMAL
text_color = getattr(colorama.Fore, text_color.upper(), None)
return text_style + text_color + text_to_print + Style.RESET_ALL


@then("the output should be pretty printed")
def check_export_pretty(context):
out = context.stdout_capture.getvalue()
lines = out.splitlines()

# As per the configuration,
expected_colorized_title = (
style_text(
True, context.jrnl_config["colors"]["date"].upper(), "2013-06-09 15:39"
sriniv27 marked this conversation as resolved.
Show resolved Hide resolved
)
+ " "
+ style_text(
True, context.jrnl_config["colors"]["title"].upper(), "My first entry."
)
)
assert lines[0] == expected_colorized_title


@then("the output should be parsable as json")
Expand Down
32 changes: 25 additions & 7 deletions jrnl/Entry.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,9 +99,25 @@ def pprint(self, short=False):
else:
indent = ""

if "colors" in self.journal.config and "date" in self.journal.config["colors"]:
date_color = self.journal.config["colors"]["date"]
else:
date_color = None
title_color = (
self.journal.config["colors"]["title"]
if "colors" in self.journal.config
and "title" in self.journal.config["colors"]
else None
)
body_color = (
self.journal.config["colors"]["body"]
if "colors" in self.journal.config
and "title" in self.journal.config["colors"]
else None
)
date_str = colorize(
self.date.strftime(self.journal.config["timeformat"]),
self.journal.config["colors"]["date"],
date_color,
bold=True,
)

Expand All @@ -113,13 +129,13 @@ def pprint(self, short=False):
+ highlight_tags_with_background_color(
self,
self.title,
self.journal.config["colors"]["title"],
title_color,
is_title=True,
),
self.journal.config["linewrap"],
)
body = highlight_tags_with_background_color(
self, self.body.rstrip(" \n"), self.journal.config["colors"]["body"]
self, self.body.rstrip(" \n"), body_color
)
body_text = [
colorize(
Expand All @@ -130,7 +146,7 @@ def pprint(self, short=False):
subsequent_indent=indent,
drop_whitespace=True,
),
self.journal.config["colors"]["body"],
body_color,
)
or indent
for line in body.rstrip(" \n").splitlines()
Expand All @@ -142,27 +158,29 @@ def pprint(self, short=False):
# properly. textwrap doesn't have this issue, however, it doesn't wrap
# the strings properly as it counts ANSI escapes as literal characters.
# TL;DR: I'm sorry.

body = "\n".join(
[
colorize(indent, self.journal.config["colors"]["body"]) + line
colorize(indent, body_color) + line
if not ansiwrap.strip_color(line).startswith(indent)
else line
for line in body_text
]
)
else:

title = (
date_str
+ " "
+ highlight_tags_with_background_color(
self,
self.title.rstrip("\n"),
self.journal.config["colors"]["title"],
title_color,
is_title=True,
)
)
body = highlight_tags_with_background_color(
self, self.body.rstrip("\n "), self.journal.config["colors"]["body"]
self, self.body.rstrip("\n "), body_color
)

# Suppress bodies that are just blanks and new lines.
Expand Down
10 changes: 8 additions & 2 deletions jrnl/color.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import re
from string import punctuation
from string import whitespace
from typing import Union

import colorama

Expand All @@ -15,11 +16,16 @@
RESET_COLOR = colorama.Fore.RESET


def colorize(string, color, bold=False):
def colorize(string, color: Union[str, None], bold=False):
"""Returns the string colored with colorama.Fore.color. If the color set by
the user is "NONE" or the color doesn't exist in the colorama.Fore attributes,
it returns the string without any modification."""
color_escape = getattr(colorama.Fore, color.upper(), None)

if color is not None:
color_escape = getattr(colorama.Fore, color.upper(), None)
else:
color_escape = None

if not color_escape:
return string
elif not bold:
Expand Down
3 changes: 2 additions & 1 deletion jrnl/plugins/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
from .tag_exporter import TagExporter
from .dates_exporter import DatesExporter
from .template_exporter import __all__ as template_exporters
from .text_exporter import TextExporter
from .text_exporter import PrettyExporter, TextExporter
from .xml_exporter import XMLExporter
from .yaml_exporter import YAMLExporter

Expand All @@ -20,6 +20,7 @@
TagExporter,
DatesExporter,
TextExporter,
PrettyExporter,
XMLExporter,
YAMLExporter,
FancyExporter,
Expand Down
10 changes: 10 additions & 0 deletions jrnl/plugins/text_exporter.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@
# Copyright (C) 2012-2021 jrnl contributors
# License: https://www.gnu.org/licenses/gpl-3.0.html

from jrnl.Entry import Entry
import os
import re
from typing import Any, Union
import unicodedata

from jrnl.color import ERROR_COLOR
Expand Down Expand Up @@ -77,3 +79,11 @@ def export(cls, journal, output=None):
return cls.write_file(journal, output)
else:
return cls.export_journal(journal)


class PrettyExporter(TextExporter):
names = ["pretty"]

@classmethod
def export_entry(cls, entry: Entry) -> Union[str, Any]:
return entry.pprint()
23 changes: 23 additions & 0 deletions tests/test_color.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import pytest

from jrnl.color import colorize
from colorama import Fore, Style


@pytest.fixture()
def data_fixture():
string = "Zwei peanuts walked into a bar"
sriniv27 marked this conversation as resolved.
Show resolved Hide resolved
yield string


def test_colorize(data_fixture):
sriniv27 marked this conversation as resolved.
Show resolved Hide resolved
string = data_fixture
colorized_string = colorize(string, "BLUE", True)

assert colorized_string == Style.BRIGHT + Fore.BLUE + string + Style.RESET_ALL


def test_colorize_none(data_fixture):
string = data_fixture
colorized_string = colorize(string, None, False)
assert colorized_string == string