Skip to content
Permalink
Browse files

feat: add colors in the text return

Colors can be disabled with the new `--no-colors` argument.
  • Loading branch information
Deuchnord committed Jan 18, 2020
1 parent 058254e commit 38fc06657fb7452e35e81e61fb2b8990bf341f72
Showing with 110 additions and 83 deletions.
  1. +1 −0 Pipfile
  2. +44 −37 Pipfile.lock
  3. +41 −28 kosmorrolib/dumper.py
  4. +16 −12 kosmorrolib/locales/messages.pot
  5. +3 −1 kosmorrolib/main.py
  6. +5 −5 test/dumper.py
@@ -13,6 +13,7 @@ babel = "*"
skyfield = ">=1.13.0,<2.0.0"
tabulate = "*"
numpy = ">=1.17.0,<2.0.0"
termcolor = "*"

[requires]
python_version = "3"

Some generated files are not rendered by default. Learn more.

@@ -22,6 +22,7 @@
from tabulate import tabulate
from skyfield.timelib import Time
from numpy import int64
from termcolor import colored
from .data import Object, AsterEphemerides, MoonPhase, Event
from .i18n import _

@@ -31,10 +32,12 @@


class Dumper(ABC):
def __init__(self, ephemeris: dict, events: [Event], date: datetime.date = datetime.date.today()):
def __init__(self, ephemeris: dict, events: [Event], date: datetime.date = datetime.date.today(),
with_colors: bool = True):
self.ephemeris = ephemeris
self.events = events
self.date = date
self.with_colors = with_colors

@abstractmethod
def to_string(self):
@@ -80,35 +83,45 @@ def _json_default(obj):

class TextDumper(Dumper):
def to_string(self):
text = self.date.strftime(FULL_DATE_FORMAT)
# Always capitalize the first character
text = ''.join([text[0].upper(), text[1:]])
text = [self.style(self.get_date(), 'h1')]

if len(self.ephemeris['details']) > 0:
text = '\n\n'.join([text,
self.get_asters(self.ephemeris['details'])
])
text.append(self.get_asters(self.ephemeris['details']))

text = '\n\n'.join([text,
self.get_moon(self.ephemeris['moon_phase'])
])
text.append(self.get_moon(self.ephemeris['moon_phase']))

if len(self.events) > 0:
text = '\n\n'.join([text,
_('Expected events:'),
self.get_events(self.events)
])
text.append('\n'.join([self.style(_('Expected events:'), 'h2'),
self.get_events(self.events)]))

text = '\n\n'.join([text, _('Note: All the hours are given in UTC.')])
text.append(self.style(_('Note: All the hours are given in UTC.'), 'em'))

return text
return '\n\n'.join(text)

@staticmethod
def get_asters(asters: [Object]) -> str:
def style(self, text: str, tag: str) -> str:
if not self.with_colors:
return text

styles = {
'h1': lambda t: colored(t, 'yellow', attrs=['bold']),
'h2': lambda t: colored(t, 'magenta', attrs=['bold']),
'th': lambda t: colored(t, 'white', attrs=['bold']),
'strong': lambda t: colored(t, attrs=['bold']),
'em': lambda t: colored(t, attrs=['dark'])
}

return styles[tag](text)

def get_date(self) -> str:
date = self.date.strftime(FULL_DATE_FORMAT)

return ''.join([date[0].upper(), date[1:]])

def get_asters(self, asters: [Object]) -> str:
data = []

for aster in asters:
name = aster.name
name = self.style(aster.name, 'th')

if aster.ephemerides.rise_time is not None:
planet_rise = aster.ephemerides.rise_time.utc_strftime(TIME_FORMAT)
@@ -127,23 +140,23 @@ def get_asters(asters: [Object]) -> str:

data.append([name, planet_rise, planet_culmination, planet_set])

return tabulate(data, headers=[_('Object'), _('Rise time'), _('Culmination time'), _('Set time')],
return tabulate(data, headers=[self.style(_('Object'), 'th'),
self.style(_('Rise time'), 'th'),
self.style(_('Culmination time'), 'th'),
self.style(_('Set time'), 'th')],
tablefmt='simple', stralign='center', colalign=('left',))

@staticmethod
def get_events(events: [Event]) -> str:
def get_events(self, events: [Event]) -> str:
data = []

for event in events:
data.append([event.start_time.utc_strftime(TIME_FORMAT), event.get_description()])
data.append([self.style(event.start_time.utc_strftime(TIME_FORMAT), 'th'),
event.get_description()])

return tabulate(data, tablefmt='plain', stralign='left')

@staticmethod
def get_moon(moon_phase: MoonPhase) -> str:
current_moon_phase = _('Moon phase: {current_moon_phase}').format(
current_moon_phase=moon_phase.get_phase()
)
def get_moon(self, moon_phase: MoonPhase) -> str:
current_moon_phase = ' '.join([self.style(_('Moon phase:'), 'strong'), moon_phase.get_phase()])
new_moon_phase = _('{next_moon_phase} on {next_moon_phase_date} at {next_moon_phase_time}').format(
next_moon_phase=moon_phase.get_next_phase(),
next_moon_phase_date=moon_phase.next_phase_date.utc_strftime(FULL_DATE_FORMAT),
@@ -8,7 +8,7 @@ msgid ""
msgstr ""
"Project-Id-Version: kosmorro 0.4.0\n"
"Report-Msgid-Bugs-To: EMAIL@ADDRESS\n"
"POT-Creation-Date: 2020-01-02 14:05+0100\n"
"POT-Creation-Date: 2020-01-19 10:39+0100\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
@@ -99,43 +99,43 @@ msgstr ""
msgid "%s and %s are in conjunction"
msgstr ""

#: kosmorrolib/dumper.py:28
#: kosmorrolib/dumper.py:29
msgid "{day_of_week} {month} {day_number}, {year}"
msgstr ""

#: kosmorrolib/dumper.py:30
#: kosmorrolib/dumper.py:31
msgid "{hours}:{minutes}"
msgstr ""

#: kosmorrolib/dumper.py:98
#: kosmorrolib/dumper.py:94
msgid "Expected events:"
msgstr ""

#: kosmorrolib/dumper.py:102
#: kosmorrolib/dumper.py:97
msgid "Note: All the hours are given in UTC."
msgstr ""

#: kosmorrolib/dumper.py:130
#: kosmorrolib/dumper.py:143
msgid "Object"
msgstr ""

#: kosmorrolib/dumper.py:130
#: kosmorrolib/dumper.py:144
msgid "Rise time"
msgstr ""

#: kosmorrolib/dumper.py:130
#: kosmorrolib/dumper.py:145
msgid "Culmination time"
msgstr ""

#: kosmorrolib/dumper.py:130
#: kosmorrolib/dumper.py:146
msgid "Set time"
msgstr ""

#: kosmorrolib/dumper.py:144
msgid "Moon phase: {current_moon_phase}"
#: kosmorrolib/dumper.py:159
msgid "Moon phase:"
msgstr ""

#: kosmorrolib/dumper.py:147
#: kosmorrolib/dumper.py:160
msgid "{next_moon_phase} on {next_moon_phase_date} at {next_moon_phase_time}"
msgstr ""

@@ -203,3 +203,7 @@ msgid ""
"{default_year} (the current year)."
msgstr ""

#: kosmorrolib/main.py:125
msgid "Disable the colors in the console."
msgstr ""

@@ -57,7 +57,7 @@ def main():

events_list = events.search_events(compute_date)

dump = output_formats[args.format](ephemerides, events_list, compute_date)
dump = output_formats[args.format](ephemerides, events_list, compute_date, args.colors)
print(dump.to_string())

return 0
@@ -121,5 +121,7 @@ def get_args(output_formats: [str]):
parser.add_argument('--year', '-y', type=int, default=today.year,
help=_('The year you want to compute the ephemerides for.'
' Defaults to {default_year} (the current year).').format(default_year=today.year))
parser.add_argument('--no-colors', dest='colors', action='store_false',
help=_('Disable the colors in the console.'))

return parser.parse_args()
@@ -52,7 +52,7 @@ def test_text_dumper_without_events(self):
'Moon phase: Full Moon\n'
'Last Quarter on Monday October 21, 2019 at 00:00\n\n'
'Note: All the hours are given in UTC.',
TextDumper(ephemerides, [], date=date(2019, 10, 14)).to_string())
TextDumper(ephemerides, [], date=date(2019, 10, 14), with_colors=False).to_string())

def test_text_dumper_with_events(self):
ephemerides = self._get_data()
@@ -62,26 +62,26 @@ def test_text_dumper_with_events(self):
'Mars - - -\n\n'
'Moon phase: Full Moon\n'
'Last Quarter on Monday October 21, 2019 at 00:00\n\n'
'Expected events:\n\n'
'Expected events:\n'
'05:12 Mars is in opposition\n\n'
'Note: All the hours are given in UTC.',
TextDumper(ephemerides, [Event('OPPOSITION',
[Planet('Mars', 'MARS')],
get_timescale().utc(2018, 7, 27, 5, 12))
], date=date(2019, 10, 14)).to_string())
], date=date(2019, 10, 14), with_colors=False).to_string())

def test_text_dumper_without_ephemerides_and_with_events(self):
ephemerides = self._get_data(False)
self.assertEqual('Monday October 14, 2019\n\n'
'Moon phase: Full Moon\n'
'Last Quarter on Monday October 21, 2019 at 00:00\n\n'
'Expected events:\n\n'
'Expected events:\n'
'05:12 Mars is in opposition\n\n'
'Note: All the hours are given in UTC.',
TextDumper(ephemerides, [Event('OPPOSITION',
[Planet('Mars', 'MARS')],
get_timescale().utc(2018, 7, 27, 5, 12))
], date=date(2019, 10, 14)).to_string())
], date=date(2019, 10, 14), with_colors=False).to_string())

@staticmethod
def _get_data(has_ephemerides: bool = True):

0 comments on commit 38fc066

Please sign in to comment.
You can’t perform that action at this time.