Skip to content

Commit

Permalink
Format pretty jrnl-org#1172 (#9)
Browse files Browse the repository at this point in the history
* Add brew and gitter badges to README

* Update changelog [ci skip]

* Make journal selection behavior more consistent when there's a colon with no date (jrnl-org#1164)

* Bump pytest from 6.2.1 to 6.2.2 (jrnl-org#1167)

Bumps [pytest](https://github.com/pytest-dev/pytest) from 6.2.1 to 6.2.2.
- [Release notes](https://github.com/pytest-dev/pytest/releases)
- [Changelog](https://github.com/pytest-dev/pytest/blob/master/CHANGELOG.rst)
- [Commits](pytest-dev/pytest@6.2.1...6.2.2)

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* Bump keyring from 21.8.0 to 22.0.1 (jrnl-org#1168)

Bumps [keyring](https://github.com/jaraco/keyring) from 21.8.0 to 22.0.1.
- [Release notes](https://github.com/jaraco/keyring/releases)
- [Changelog](https://github.com/jaraco/keyring/blob/main/CHANGES.rst)
- [Commits](jaraco/keyring@v21.8.0...v22.0.1)

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* Update changelog [ci skip]

* behavior test for format --pretty

* add pretty exporter

* include vscode debugging config

* config file for pretty formatting

* update gitignore

* basic colorize unittest

* implement behave test steps for format --pretty

* make color handling more robust

* rework core run() so config_upgrade can be tested

* formatting for pretty exporter

* base .vscode/launch.json and ignore further user modifications from SCM

* fix linting errors

* make format

* Update pyproject.toml

* update lockfile and make format

Co-authored-by: Micah Jerome Ellison <micah.jerome.ellison@gmail.com>
Co-authored-by: Jrnl Bot <jrnl.bot@gmail.com>
Co-authored-by: Jonathan Wren <jonathan@nowandwren.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
  • Loading branch information
5 people authored Feb 4, 2021
1 parent 2be0d37 commit e2fb4df
Show file tree
Hide file tree
Showing 14 changed files with 183 additions and 135 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -61,3 +61,4 @@ coverage.xml
.coverage
.vscode/tasks.json
todo.txt

31 changes: 31 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
{
// 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
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
7 changes: 7 additions & 0 deletions features/steps/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -396,6 +396,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 @@ -425,6 +431,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), \
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"
)
+ " "
+ 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
2 changes: 1 addition & 1 deletion jrnl/args.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ def deserialize_config_args(input: list) -> dict:
cfg_value = True
elif cfg_value.lower() == "false":
cfg_value = False

runtime_modifications[cfg_key] = cfg_value

return runtime_modifications
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()
Loading

0 comments on commit e2fb4df

Please sign in to comment.