Skip to content

Commit

Permalink
feat: add support for relative dates on --date argument
Browse files Browse the repository at this point in the history
  • Loading branch information
Brainface1 committed Apr 18, 2020
1 parent 52cfaf4 commit b9454be
Show file tree
Hide file tree
Showing 10 changed files with 116 additions and 71 deletions.
4 changes: 4 additions & 0 deletions .scripts/tests-e2e.sh 100644 → 100755
Expand Up @@ -81,6 +81,10 @@ assertSuccess "kosmorro -h"
assertSuccess "kosmorro -d 2020-01-27"
assertFailure "kosmorro -d yolo-yo-lo"
assertFailure "kosmorro -d 2020-13-32"
assertSuccess "kosmorro --date='+3y 5m3d'"
assertSuccess "kosmorro --date='-1y3d'"
assertFailure "kosmorro --date='+3d4m"
assertFailure "kosmorro -date='3y'"
assertSuccess "kosmorro --latitude=50.5876 --longitude=3.0624"
assertSuccess "kosmorro --latitude=50.5876 --longitude=3.0624 -d 2020-01-27"
assertSuccess "kosmorro --latitude=50.5876 --longitude=3.0624 -d 2020-01-27 --timezone=1"
Expand Down
1 change: 1 addition & 0 deletions Pipfile
Expand Up @@ -16,6 +16,7 @@ tabulate = "*"
numpy = ">=1.17.0,<2.0.0"
termcolor = "*"
latex = "*"
python-dateutil = "*"

[requires]
python_version = "3"
82 changes: 45 additions & 37 deletions Pipfile.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Empty file modified kosmorro 100644 → 100755
Empty file.
31 changes: 31 additions & 0 deletions kosmorrolib/core.py
Expand Up @@ -21,10 +21,15 @@
from shutil import rmtree
from pathlib import Path

from datetime import date
from dateutil.relativedelta import relativedelta

from skyfield.api import Loader
from skyfield.timelib import Time
from skyfield.nutationlib import iau2000b

from kosmorrolib.i18n import _

CACHE_FOLDER = str(Path.home()) + '/.kosmorro-cache'

class Environment:
Expand Down Expand Up @@ -86,3 +91,29 @@ def flatten_list(the_list: list):
new_list.append(item)

return new_list


def get_date(date_arg: str) -> date:
if re.match(r'^\d{4}-\d{2}-\d{2}$', date_arg):
try:
return date.fromisoformat(date_arg)
except ValueError as error:
raise ValueError(_('The date {date} is not valid: {error}').format(date=date_arg, error=error.args[0]))
elif re.match(r'^([+-])(([0-9]+)y)?[ ]?(([0-9]+)m)?[ ]?(([0-9]+)d)?$', date_arg):
def get_offset(date_arg: str, signifier: str):
if re.search(r'([0-9]+)' + signifier, date_arg):
return abs(int(re.search(r'[+-]?([0-9]+)' + signifier, date_arg).group(0)[:-1]))
return 0

days = get_offset(date_arg, 'd')
months = get_offset(date_arg, 'm')
years = get_offset(date_arg, 'y')


if date_arg[0] == '+':
return date.today() + relativedelta(days=days, months=months, years=years)
return date.today() - relativedelta(days=days, months=months, years=years)

else:
error_msg = _('The date {date} does not match the required YYYY-MM-DD format or the offset format.')
raise ValueError(error_msg.format(date=date_arg))
48 changes: 25 additions & 23 deletions kosmorrolib/locales/messages.pot
Expand Up @@ -8,7 +8,7 @@ msgid ""
msgstr ""
"Project-Id-Version: kosmorro 0.7.0\n"
"Report-Msgid-Bugs-To: EMAIL@ADDRESS\n"
"POT-Creation-Date: 2020-04-05 10:47+0200\n"
"POT-Creation-Date: 2020-04-16 17:57+0200\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"
Expand All @@ -17,6 +17,16 @@ msgstr ""
"Content-Transfer-Encoding: 8bit\n"
"Generated-By: Babel 2.8.0\n"

#: kosmorrolib/core.py:101
msgid "The date {date} is not valid: {error}"
msgstr ""

#: kosmorrolib/core.py:118
msgid ""
"The date {date} does not match the required YYYY-MM-DD format or the "
"offset format."
msgstr ""

#: kosmorrolib/data.py:32
msgid "New Moon"
msgstr ""
Expand Down Expand Up @@ -211,80 +221,72 @@ msgstr ""
msgid "Selected output format needs an output file (--output)."
msgstr ""

#: kosmorrolib/main.py:104
msgid "The date {date} does not match the required YYYY-MM-DD format."
msgstr ""

#: kosmorrolib/main.py:109
msgid "The date {date} is not valid: {error}"
msgstr ""

#: kosmorrolib/main.py:123
#: kosmorrolib/main.py:115
msgid "Running on Python {python_version}"
msgstr ""

#: kosmorrolib/main.py:129
#: kosmorrolib/main.py:121
msgid "Do you really want to clear Kosmorro's cache? [yN] "
msgstr ""

#: kosmorrolib/main.py:136
#: kosmorrolib/main.py:128
msgid "Answer did not match expected options, cache not cleared."
msgstr ""

#: kosmorrolib/main.py:145
#: kosmorrolib/main.py:137
msgid ""
"Compute the ephemerides and the events for a given date, at a given "
"position on Earth."
msgstr ""

#: kosmorrolib/main.py:147
#: kosmorrolib/main.py:139
msgid ""
"By default, only the events will be computed for today ({date}).\n"
"To compute also the ephemerides, latitude and longitude arguments are "
"needed."
msgstr ""

#: kosmorrolib/main.py:152
#: kosmorrolib/main.py:144
msgid "Show the program version"
msgstr ""

#: kosmorrolib/main.py:154
#: kosmorrolib/main.py:146
msgid "Delete all the files Kosmorro stored in the cache."
msgstr ""

#: kosmorrolib/main.py:156
#: kosmorrolib/main.py:148
msgid "The format under which the information have to be output"
msgstr ""

#: kosmorrolib/main.py:158
#: kosmorrolib/main.py:150
msgid ""
"The observer's latitude on Earth. Can also be set in the "
"KOSMORRO_LATITUDE environment variable."
msgstr ""

#: kosmorrolib/main.py:161
#: kosmorrolib/main.py:153
msgid ""
"The observer's longitude on Earth. Can also be set in the "
"KOSMORRO_LONGITUDE environment variable."
msgstr ""

#: kosmorrolib/main.py:164
#: kosmorrolib/main.py:156
msgid ""
"The date for which the ephemerides must be computed (in the YYYY-MM-DD "
"format). Defaults to the current date ({default_date})"
msgstr ""

#: kosmorrolib/main.py:168
#: kosmorrolib/main.py:160
msgid ""
"The timezone to display the hours in (e.g. 2 for UTC+2 or -3 for UTC-3). "
"Can also be set in the KOSMORRO_TIMEZONE environment variable."
msgstr ""

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

#: kosmorrolib/main.py:173
#: kosmorrolib/main.py:165
msgid ""
"A file to export the output to. If not given, the standard output is "
"used. This argument is needed for PDF format."
Expand Down
10 changes: 1 addition & 9 deletions kosmorrolib/main.py
Expand Up @@ -42,7 +42,7 @@ def main():
return 0 if args.special_action() else 1

try:
compute_date = get_date(args.date)
compute_date = core.get_date(args.date)
except ValueError as error:
print(colored(error.args[0], color='red', attrs=['bold']))
return -1
Expand Down Expand Up @@ -99,14 +99,6 @@ def main():
return 0


def get_date(yyyymmdd: str) -> date:
if not re.match(r'^\d{4}-\d{2}-\d{2}$', yyyymmdd):
raise ValueError(_('The date {date} does not match the required YYYY-MM-DD format.').format(date=yyyymmdd))

try:
return date.fromisoformat(yyyymmdd)
except ValueError as error:
raise ValueError(_('The date {date} is not valid: {error}').format(date=yyyymmdd, error=error.args[0]))


def get_dumpers() -> {str: dumper.Dumper}:
Expand Down
2 changes: 1 addition & 1 deletion manpage/kosmorro.1.md
Expand Up @@ -23,7 +23,7 @@
the observer's longitude on Earth

`--date=`_DATE_, `-d` _DATE_
The date for which the ephemerides must be computed (in the YYYY-MM-DD format); defaults to the current date
The date for which the ephemerides must be computed, either in the YYYY-MM-DD format or as an interval in the "[+-]YyMmDd" format (with Y, M, and D numbers); defaults to the current date

`--timezone=`_TIMEZONE_, `-t` _TIMEZONE_
the timezone to display the hours in; e.g. 2 for UTC+2 or -3 for UTC-3
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Expand Up @@ -41,7 +41,7 @@
data_files=[
('man/man1', ['manpage/kosmorro.1'])
],
install_requires=['skyfield>=1.17.0,<2.0.0', 'tabulate', 'numpy>=1.17.0,<2.0.0', 'termcolor'],
install_requires=['skyfield>=1.17.0,<2.0.0', 'tabulate', 'numpy>=1.17.0,<2.0.0', 'termcolor', 'python-dateutil'],
classifiers=[
'Development Status :: 3 - Alpha',
'Operating System :: POSIX :: Linux',
Expand Down
7 changes: 7 additions & 0 deletions test/core.py
Expand Up @@ -3,6 +3,9 @@
import os
import kosmorrolib.core as core

from datetime import date
from dateutil.relativedelta import relativedelta


class CoreTestCase(unittest.TestCase):
def test_flatten_list(self):
Expand All @@ -27,6 +30,10 @@ def test_get_env(self):

self.assertEqual("{'great_variable': 'value', 'another_variable': 'another value'}", str(env))

def test_date_arg_parsing(self):
self.assertEqual(core.get_date("+1y 2m3d"), date.today() + relativedelta(years=1, months=2, days=3))
self.assertEqual(core.get_date("-1y2d"), date.today() - relativedelta(years=1, days=2))
self.assertEqual(core.get_date("1111-11-13"), date(1111, 11, 13))

if __name__ == '__main__':
unittest.main()

0 comments on commit b9454be

Please sign in to comment.