diff --git a/CHANGELOG.md b/CHANGELOG.md index efb4360..f5d13f1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ and I do try to adhere to [Semantic Versioning](https://semver.org/spec/v2.0.0.h ### Added +* `list --json` prints the selection as jCal (RFC 7265), the standard JSON representation of iCalendar. https://github.com/pycalendar/plann/issues/82 * `plann freebusy-sync`: keeps a copy of the busy time from one set of calendars in another calendar, holding only the time and a fixed summary. Copies are moved and deleted as the source changes, so it can run from a timer in both directions between a work and a private calendar. See the user guide. ### Deprecated @@ -18,10 +19,11 @@ and I do try to adhere to [Semantic Versioning](https://semver.org/spec/v2.0.0.h * Completing a task (`edit --complete`, `complete` in the interactive and multi-edit modes, `completed!` in `set-task-attribs`) now also completes its pending child tasks, recursively, and prints a warning for each. A child has to be done before the parent can be completed. * `completed!` in `set-task-attribs` moves a recurring task on to its next recurrence, like `edit --complete` does, instead of completing the whole series. * Shell tab completion scripts (bash, zsh, fish) now ship with the package. They work without shell configuration for system-wide installs (and for bash user/venv installs with bash-completion 2.12+); see the README for other setups. The `make install-completion` targets are gone. -* icalendar 6.2.0 or newer is required. +* icalendar 7.0.0 or newer is required. ### Fixed +* `list --ics` repeated the VTIMEZONE of every listed object, instead of giving each timezone once. * `interactive set-task-attribs` (also run by `interactive manage-tasks`): a task marked `completed!` at one prompt was asked about again at the next one, and answering `completed!` there crashed on the already-completed task. Regression in v1.2.0. * `list-categories` and timewarrior time tracking crashed on a task with more than one CATEGORIES line. https://github.com/pycalendar/plann/issues/71 * `{CATEGORIES}` in a `list --template` printed the internal `vCategory([...])` representation instead of a comma-separated list. diff --git a/USER_GUIDE.md b/USER_GUIDE.md index ad73e82..fb95fe5 100644 --- a/USER_GUIDE.md +++ b/USER_GUIDE.md @@ -109,7 +109,13 @@ Some calendar server implementations require `--todo` or `--event` to always be ### Listing objects -Events can either be output as ics, or through a template. +Events can either be output as ics (`list --ics`), as json (`list --json`), or through a template. + +The json output is jCal, the standard JSON representation of iCalendar (RFC 7265). It holds everything the ics output holds, and is easier for scripts (or AI agents) to work on than template output: + +``` +plann select --event --start=today --end=+7d list --json +``` The templating engine is built on top of the python `string.format()`. To learn the basics of `string.format()`, w3schools has some nice interactive thing on the web, https://www.w3schools.com/python/ref_string_format.asp diff --git a/plann/cli.py b/plann/cli.py index b5296d6..b931858 100755 --- a/plann/cli.py +++ b/plann/cli.py @@ -378,16 +378,19 @@ def list_categories(ctx): @select.command() @click.option('--ics/--no-ics', default=False, help="Output in ics format") +@click.option('--json/--no-json', 'json_', default=False, help="Output in jCal (RFC 7265) JSON format") @click.option('--template', default="{DTSTART:?{DUE:?(date missing)?}?%F %H:%M:%S %Z}: {SUMMARY:?{DESCRIPTION:?(no summary given)?}?}") @click.option('--separator', default="\n", help="String to separate the listed items with (defaults to a newline)") @click.option('--top-down/--flat-list', help="Check relations and list the relations in a hierarchical way") @click.option('--bottom-up/--flat-list', help="List parents (dependencies) in a hierarchical way (cannot be combined with top-down)") @click.pass_context -def list(ctx, ics, template, separator="\n", top_down=False, bottom_up=False): +def list(ctx, ics, json_, template, separator="\n", top_down=False, bottom_up=False): """ Print out a list of tasks/events/journals """ - return _list(ctx.obj['objs'], ics, template, top_down=top_down, bottom_up=bottom_up, separator=separator) + if ics and json_: + raise click.UsageError("--ics and --json cannot be combined") + return _list(ctx.obj['objs'], ics, as_json=json_, template=template, top_down=top_down, bottom_up=bottom_up, separator=separator) @select.command() diff --git a/plann/lib.py b/plann/lib.py index e78ca50..767a1a0 100644 --- a/plann/lib.py +++ b/plann/lib.py @@ -634,7 +634,7 @@ def _set_something(obj, arg, value): ## TODO: should be rewritten a bit, we should have a create_list method that does not call on click.echo directly ## let the caller decide if click is to be used or not. ## Use the yield method to avoid having to generate the full list prior to printing to screen -def _list(objs, ics=False, template="{DTSTART:?{DUE:?(date missing)?}?%F %H:%M:%S %Z}: {SUMMARY:?{DESCRIPTION:?(no summary given)?}?}", top_down=False, bottom_up=False, indent=0, echo=True, uids=None, filter=lambda obj: True, separator="\n", cache=None): +def _list(objs, ics=False, as_json=False, template="{DTSTART:?{DUE:?(date missing)?}?%F %H:%M:%S %Z}: {SUMMARY:?{DESCRIPTION:?(no summary given)?}?}", top_down=False, bottom_up=False, indent=0, echo=True, uids=None, filter=lambda obj: True, separator="\n", cache=None): """ Actual implementation of list @@ -647,14 +647,24 @@ def _list(objs, ics=False, template="{DTSTART:?{DUE:?(date missing)?}?%F %H:%M:% ## task is not re-fetched from the server for every edge it touches (E3) if cache is None and (top_down or bottom_up): cache = _RelativeCache() - if ics: + if ics or as_json: accepted = [obj for obj in objs if filter(obj)] - if not accepted: + ## a script parsing the json should get an empty calendar, not nothing + if not accepted and not as_json: return - icalendar = accepted[0].icalendar_instance - for obj in accepted[1:]: - icalendar.subcomponents.extend(obj.icalendar_instance.subcomponents) - click.echo(icalendar.to_ical()) + ## a fresh calendar, the objects' (cached) instances are not to be touched + cal = icalendar.Calendar() + cal.add('VERSION', '2.0') + cal.add('PRODID', '-//plann//list//EN') + tzids = set() + for obj in accepted: + for comp in obj.icalendar_instance.subcomponents: + if comp.name == 'VTIMEZONE': + if comp['TZID'] in tzids: + continue + tzids.add(comp['TZID']) + cal.add_component(comp) + click.echo(cal.to_json() if as_json else cal.to_ical()) return if isinstance(template, str): template=Template(template) diff --git a/pyproject.toml b/pyproject.toml index ea8effd..f5cd442 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -30,7 +30,7 @@ dependencies = [ "sortedcontainers", "dateparser>=1.2", "python-dateutil", - "icalendar>=6.2.0", + "icalendar>=7.0.0", "icalendar_searcher", ] @@ -63,6 +63,10 @@ build-backend = "hatchling.build" [tool.hatch.version] source = "vcs" +# Only v* tags are releases. The default describe takes the nearest +# tag containing a digit, so a date-stamped local tag (a pre-rewrite backup, +# say) could become the version and break the build. +raw-options = { scm = { git = { describe_command = "git describe --dirty --tags --long --abbrev=40 --match v[0-9]*" } } } [tool.hatch.build.hooks.vcs] version-file = "plann/_version.py" diff --git a/tests/test_lib.py b/tests/test_lib.py index e027777..db56a5c 100644 --- a/tests/test_lib.py +++ b/tests/test_lib.py @@ -657,3 +657,68 @@ def relships(obj, reltype_wanted=None, cache=None): assert odd.icalendar_component['STATUS'] == 'WAITING' assert child.icalendar_component['STATUS'] == 'NEEDS-ACTION' assert warnings == ["Not completing 'task odd': STATUS is WAITING"] + + +def test_list_json(): + """`list --json` dumps the selection as one jCal (RFC 7265) calendar, + like `--ics` does as iCalendar. + https://github.com/pycalendar/plann/issues/82""" + import json + + from plann.lib import _list + objs = [_todo_with_rels('a', []), _todo_with_rels('b', [])] + with patch('plann.lib.click.echo') as echo: + _list(objs, as_json=True) + jcal = json.loads(echo.call_args.args[0]) + assert jcal[0] == 'vcalendar' + uids = [prop[3] for comp in jcal[2] for prop in comp[1] if prop[0] == 'uid'] + assert uids == ['a', 'b'] + + +def test_list_json_empty(): + """An empty selection still gives valid json.""" + import json + + from plann.lib import _list + with patch('plann.lib.click.echo') as echo: + _list([], as_json=True) + jcal = json.loads(echo.call_args.args[0]) + assert jcal[0] == 'vcalendar' + assert {prop[0] for prop in jcal[1]} >= {'version', 'prodid'} + assert jcal[2] == [] + + +def _event_in_oslo(uid): + from caldav import Event + obj = Event() + obj.data = ( + "BEGIN:VCALENDAR\nVERSION:2.0\nPRODID:-//Example Corp.//CalDAV Client//EN\n" + "BEGIN:VTIMEZONE\nTZID:Europe/Oslo\n" + "BEGIN:STANDARD\nDTSTART:19701025T030000\nTZOFFSETFROM:+0200\nTZOFFSETTO:+0100\n" + "RRULE:FREQ=YEARLY;BYMONTH=10;BYDAY=-1SU\nEND:STANDARD\n" + "END:VTIMEZONE\n" + f"BEGIN:VEVENT\nUID:{uid}\nDTSTART;TZID=Europe/Oslo:20261021T100000\n" + f"SUMMARY:event {uid}\nEND:VEVENT\nEND:VCALENDAR" + ) + return obj + + +def test_list_ics_does_not_touch_the_objects(): + """Merging the selection into one calendar must not modify the + (cached) icalendar instance of the first object.""" + from plann.lib import _list + objs = [_event_in_oslo('a'), _event_in_oslo('b')] + for as_json in (False, True): + with patch('plann.lib.click.echo'): + _list(objs, ics=not as_json, as_json=as_json) + assert len(objs[0].icalendar_instance.subcomponents) == 2 + + +def test_list_json_one_vtimezone_per_tzid(): + import json + + from plann.lib import _list + with patch('plann.lib.click.echo') as echo: + _list([_event_in_oslo('a'), _event_in_oslo('b')], as_json=True) + names = [comp[0] for comp in json.loads(echo.call_args.args[0])[2]] + assert names == ['vtimezone', 'vevent', 'vevent'] diff --git a/tests/test_plann_cli.py b/tests/test_plann_cli.py index 981724b..1d1e497 100644 --- a/tests/test_plann_cli.py +++ b/tests/test_plann_cli.py @@ -569,3 +569,16 @@ def test_mass_interactive_edit_works_on_tasks_fetched_after_editing(): assert len(saved) == 1 assert saved[0] is not task assert saved[0].icalendar_component['PRIORITY'] == 3 + + +def test_list_json_and_ics_conflict(): + res = CliRunner().invoke(cli_mod.list, ['--ics', '--json'], obj={'objs': [_make_todo('a')]}) + assert res.exit_code != 0 + assert 'cannot be combined' in res.output + + +def test_list_json(): + import json + res = CliRunner().invoke(cli_mod.list, ['--json'], obj={'objs': [_make_todo('a')]}) + assert res.exit_code == 0, res.output + assert json.loads(res.output)[0] == 'vcalendar'