Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ and I do try to adhere to [Semantic Versioning](https://semver.org/spec/v2.0.0.h
* A timestamp with an explicit UTC offset, like `plann select --event --start 2026-11-21T05:00+01:00`, crashed when expanding recurring events with `AttributeError: 'StaticTzInfo' object has no attribute 'normalize'`. https://github.com/niccokunzmann/python-recurring-ical-events/issues/311
* A line that could not be parsed in the plan of `check-for-panic --interactive-fix-timeline` (and `interactive manage-tasks`) crashed with an `AssertionError` and discarded the whole edit. The editor is now reopened with the error at the top.
* `plann select --sort-key DUE` (or any other date property, like `DTSTART`) crashed with `TypeError: '<' not supported between instances of 'vDDDTypes' and 'vDDDTypes'`, and a plain sort key missing on some of the items crashed too. Dates and timestamps now sort together (a date as midnight, a floating time in the implicit timezone), and items without the property come last, also with a reversed `-` sort key. A task with DTSTART and DURATION but no DUE now sorts on the DUE they give. https://github.com/pycalendar/plann/issues/65
* `edit --set-comment=hello` (and `--set-contact`, also on `add`) stored the Python representation of a tuple, `COMMENT:('hello'\,)`. Each value now gives one property, so the option can be repeated to get several. An empty value, like `edit --set-comment=` or `--set-location=`, removes the property instead of storing an empty one (or `(''\,)`), and adds nothing on `add` (the appending options and the ones for required properties excepted, see the user guide); it crashed for dates, durations, `--set-priority` and `--set-rrule`. https://github.com/pycalendar/plann/issues/66
* `plann select ... edit --set-dtend=...` on an event crashed with `TypeError: CalendarObjectResource.set_end() got an unexpected keyword argument 'check_dependent'`, so an event could not be given a new end time. It now moves the event, keeping its duration. `--set-dtend` on a task, `--set-due` on an event and either on a journal crashed too; they now give an error saying which one the item has.
* The `plann agenda --help` text now lists two runnable `plann select` commands giving the same events and tasks as `agenda`. In the task one, the `--sort-key '{PRIORITY:?0}'` template had no effect and `list --bottom-up` stood where `select --skip-parents` belongs, and the event one lacked the sort keys. It also pointed to a nonexistent USAGE.md instead of USER_GUIDE.md.
* `plann add -l LINE event` dropped the extra iCalendar lines; they are now added to the event, as they were to tasks and journals.
Expand Down
2 changes: 2 additions & 0 deletions USER_GUIDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,8 @@ Most of the options given after the subcommand are for populating object propert

On the command line, categories come in a singular and a plural form, and the difference matters: the plural form takes a comma-separated list, while the singular form takes one category, and a comma in it is kept as part of the name. `--set-categories=boat,keyboard` gives the two categories `boat` and `keyboard`; `--set-category=boat,keyboard` gives one category named `boat,keyboard`, which is hardly ever what one wants, so plann warns about it. Several categories can also be given by repeating the singular option: `--set-category=boat --set-category=keyboard`. A plural option given more than once is not split either, so give all the categories in one `--set-categories`. When editing, `--set-categories` replaces all categories, while `--add-category`/`--add-categories` (and the deprecated `--set-category`) append to them. Resources work the same way, except that the singular form exists only as `--add-resource`. When selecting, the meaning is different again: `--category` matches a substring of a category, `--categories` an exact category. The interactive editor and the `check` prompt always split on comma.

`--set-comment` and `--set-contact` can be repeated to give several COMMENT or CONTACT lines. When editing, a `--set-` option given an empty value, like `--set-comment=` or `--set-due=`, removes that property. The exceptions are the options that append, `--set-category`, `--set-parent` and `--set-child`, where an empty value does nothing, and the properties an item cannot be without: `--set-dtstamp=`, and `--set-dtstart=` on an event or on an item with a DURATION, give an error.

`--set-alarm` adds a reminder to a task or an event: a duration like `10m` or `1h` (a number without a unit, like `15`, is minutes, as in most calendar software) puts it that long before the DUE of a task (or its DTSTART, if it has no DUE) or before the start of an event (`+10m` is that long after, as in iCalendar), a timestamp puts it at that time:

```
Expand Down
3 changes: 3 additions & 0 deletions plann/commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -526,6 +526,9 @@ def _process_set_args(ctx, kwargs, keep_category=False):
continue
_warn_comma_literal('set', x[4:], kwargs[x])
ctx.obj['set_args'].update(_process_set_arg(x[4:], kwargs[x], keep_category=keep_category))
if not keep_category:
## creating: an empty --set-<attr> (which clears it on edit) adds nothing
ctx.obj['set_args'] = {k: v for k, v in ctx.obj['set_args'].items() if v not in ('', [])}
if 'summary' in kwargs:
ctx.obj['set_args']['summary'] = ctx.obj['set_args'].get('summary', '') + kwargs['summary']
if 'ical_fragment' in kwargs:
Expand Down
3 changes: 2 additions & 1 deletion plann/interactive.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,8 @@ def command_edit(obj, command, interactive=True, complete_cache=None, completed=
obj.icalendar_component['STATUS'] = 'CANCELLED'
elif command.lower().startswith('set rrule='):
## TODO: does this work from the cli? (...) edit --set-rrule=FREQ=YEARLY as well as add (...) --set-rrule=FREQ=YEARLY ? Write test code and check!
rrule = vRecur.from_ical(command[10:])
## an empty value clears it
rrule = vRecur.from_ical(command[10:]) if command[10:] else ''
_set_something(obj, 'RRULE', rrule)
elif command.startswith('set '):
command = command[4:].split('=')
Expand Down
62 changes: 53 additions & 9 deletions plann/lib.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,8 @@ def _set_comma_list(obj, canonical, tokens):
comp = _icalendar_component(obj)
if canonical in comp:
comp.pop(canonical)
comp.add(canonical, tokens)
if tokens:
comp.add(canonical, tokens)

def _split_vcal(ical):
"""
Expand Down Expand Up @@ -629,10 +630,22 @@ def _relationship_text(obj, reltype_wanted=None):
ret.append(reltype + "\n" + "\n".join(objs) + "\n")
return "\n".join(ret)

def _is_empty_value(value):
"""True for an empty --set-<attr> value: "", or a tuple/list (a repeatable
option) holding nothing but empty strings. Setting one clears the
property."""
if isinstance(value, str):
return value == ''
if isinstance(value, (tuple, list)):
return all(x == '' for x in value)
return False

## TODO - this needs to be better documented. What's the difference between _process_set_arg and _set_something? Do they overlap? Are they intended to be used together?
def _process_set_arg(arg, value, keep_category=False):
ret = {}
if arg in attr_time and arg != 'duration':
if _is_empty_value(value):
ret[arg] = ''
elif arg in attr_time and arg != 'duration':
ret[arg] = parse_dt(value, for_storage=True)
elif arg == 'duration':
ret[arg] = parse_add_dur(dt=None, dur=value)
Expand All @@ -649,36 +662,67 @@ def _process_set_arg(arg, value, keep_category=False):
## set_args straight to caldav's save_todo(categories=...) etc.
if not keep_category and not _comma_list_is_plural(arg):
arg = _comma_list_canonical(arg)
ret[arg] = value
ret[arg] = [x for x in value if x != '']
elif arg in ('child', 'parent'):
## always a list of UIDs (a bare string from the interactive editor)
if isinstance(value, str):
value = [value]
ret[arg] = [x for x in value if x != '']
elif isinstance(value, (tuple, list)):
## a repeatable option (--set-comment, --set-contact): one property per
## value - a tuple would be stored as its repr. A single value is
## passed bare, as icalendar would store a one-element list as a list
values = [x for x in value if x != '']
ret[arg] = values[0] if len(values) == 1 else values
else:
ret[arg] = value
return ret

def _check_end_attr(comp, arg):
"""Raise a UsageError unless ``arg`` (due or dtend) is how ``comp`` ends"""
right = {'VTODO': 'due', 'VEVENT': 'dtend'}.get(comp.name)
if arg != right:
hint = f", it ends with {right.upper()}" if right else ""
raise click.UsageError(f"a {comp.name} has no {arg.upper()}{hint}")

def _clear_something(obj, arg):
"""An empty --set-<attr> value: remove the property. The singular
comma-list forms and the relations append, so there is nothing to do;
a property the item cannot be without is an error."""
comp = obj.icalendar_component
if arg in ('child', 'parent') or (
_is_comma_list_attr(arg) and not _comma_list_is_plural(arg)):
return
if arg in ('due', 'dtend'):
_check_end_attr(comp, arg)
if arg == 'dtstamp' or (arg == 'dtstart' and (comp.name == 'VEVENT' or 'DURATION' in comp)):
raise click.UsageError(f"cannot remove {arg.upper()} from this {comp.name}")
comp.pop(_comma_list_canonical(arg) if _is_comma_list_attr(arg) else arg, None)

def _set_something(obj, arg, value):
"""
set_something is used when editing objects.
The arg and value is already processed through _process_set_arg
"""
arg = arg.lower()
comp = obj.icalendar_component
if arg in ('child', 'parent'):
if _is_empty_value(value):
_clear_something(obj, arg)
elif arg in ('child', 'parent'):
for val in value:
obj.set_relation(reltype=arg, other=val)
elif arg == 'duration':
obj.set_duration(value)
elif arg in ('due', 'dtend'):
## moves DTSTART too - _edit sets DTSTART after this
right = {'VTODO': 'due', 'VEVENT': 'dtend'}.get(comp.name)
if arg != right:
hint = f", it ends with {right.upper()}" if right else ""
raise click.UsageError(f"a {comp.name} has no {arg.upper()}{hint}")
_check_end_attr(comp, arg)
if arg == 'due':
obj.set_due(value, move_dtstart=True, check_dependent=True)
else: ## parent/child due checks are VTODO-only
obj.set_dtend(value, move_dtstart=True)
elif _is_comma_list_attr(arg):
## a list (already processed by _process_set_arg) or a raw comma string
tokens = _comma_list_tokens(arg, value)
tokens = [x for x in _comma_list_tokens(arg, value) if x != '']
canonical = _comma_list_canonical(arg)
if _comma_list_is_plural(arg):
_set_comma_list(obj, canonical, tokens) ## plural -> replace
Expand Down
11 changes: 11 additions & 0 deletions tests/test_interactive.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,3 +44,14 @@ def test_set_relations_blank_line_does_not_orphan_children():

for call in adjust.call_args_list:
assert call.args[0] is not None, "_adjust_relations called with parent=None"


def test_interactive_set_empty_rrule_clears():
"""'set rrule=' clears the RRULE, like every other 'set x='"""
from plann.interactive import command_edit
obj = Todo(data=todo.replace('END:VTODO', 'RRULE:FREQ=WEEKLY\nEND:VTODO'))
with patch.object(Todo, 'save'):
command_edit(obj, 'set rrule=', interactive=False)
assert 'RRULE' not in obj.icalendar_component
command_edit(obj, 'set rrule=FREQ=DAILY', interactive=False)
assert obj.icalendar_component['RRULE']['FREQ'] == ['DAILY']
110 changes: 110 additions & 0 deletions tests/test_lib.py
Original file line number Diff line number Diff line change
Expand Up @@ -988,3 +988,113 @@ def test_list_json_one_vtimezone_per_tzid():
_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']


def _edit_set(obj, arg, value):
"""--set-<arg>, the way the edit command applies it"""
for k, v in _process_set_arg(arg, value, keep_category=True).items():
_set_something(obj, k, v)


@pytest.mark.parametrize("arg", ['comment', 'contact'])
def test_set_repeatable_text_property(arg):
"""--set-comment and --set-contact are repeatable (click hands over a
tuple); the tuple was stored as its repr, COMMENT:('hello'\\,).
https://github.com/pycalendar/plann/issues/66"""
t = Todo()
t.data = todo.replace('END:VTODO', f'{arg.upper()}:old\nEND:VTODO')
_edit_set(t, arg, ('hello',))
assert str(t.icalendar_component[arg]) == 'hello'
_edit_set(t, arg, ('one', 'two, with a comma'))
assert [str(x) for x in t.icalendar_component[arg]] == ['one', 'two, with a comma']
assert "('" not in t.data


@pytest.mark.parametrize("arg, value", [
('comment', ('',)),
('contact', ('',)),
('location', ''),
('description', ''),
('priority', ''),
('rrule', ''),
('categories', ('',)),
('resources', ('',)),
('due', ''),
('dtstart', ''),
('duration', ''),
])
def test_set_empty_clears_property(arg, value):
"""--set-<attr>="" removes the property instead of storing an empty
value (or the repr of a tuple holding one).
https://github.com/pycalendar/plann/issues/66"""
t = Todo()
t.data = todo.replace('END:VTODO', 'COMMENT:a\nCOMMENT:b\nCONTACT:c\nLOCATION:d\n'
'RRULE:FREQ=WEEKLY\nCATEGORIES:e,f\nRESOURCES:g\nEND:VTODO')
if arg == 'duration':
t.data = t.data.replace('DUE:19970416T045959Z', 'DURATION:PT1H')
assert arg in t.icalendar_component
_edit_set(t, arg, value)
assert arg not in t.icalendar_component
assert 'SUMMARY:Fix a party' in t.data


def test_set_category_empty_appends_nothing():
"""The singular (appending) --set-category="" leaves CATEGORIES as it is"""
t = Todo()
t.data = todo.replace('END:VTODO', 'CATEGORIES:e,f\nEND:VTODO')
_edit_set(t, 'category', ('',))
assert _comma_list_set(t, 'CATEGORIES') == {'e', 'f'}


@pytest.mark.parametrize("comp_name, extra, arg", [
('VTODO', '', 'dtstamp'),
('VEVENT', '', 'dtstart'),
('VTODO', 'DURATION:PT1H\n', 'dtstart'),
])
def test_set_empty_refused_where_required(comp_name, extra, arg):
"""Clearing a property the item cannot be without is an error: DTSTAMP
always, DTSTART on an event or on an item with a DURATION"""
obj = (Event if comp_name == 'VEVENT' else Todo)()
data = todo.replace('VTODO', comp_name)
data = data.replace('DUE:19970416T045959Z\n', extra or ('DTEND:19970416T045959Z\n' if comp_name == 'VEVENT' else 'DUE:19970416T045959Z\n'))
obj.data = data
with pytest.raises(click.UsageError, match=arg.upper()):
_edit_set(obj, arg, '')
assert arg in obj.icalendar_component


@pytest.mark.parametrize("objclass, comp_name, arg", [
(Event, 'VEVENT', 'due'),
(Todo, 'VTODO', 'dtend'),
])
def test_set_empty_wrong_end(objclass, comp_name, arg):
"""--set-due= on an event is the same error as --set-due=<time>"""
obj = objclass()
obj.data = todo.replace('VTODO', comp_name).replace('DUE:', 'DTEND:' if comp_name == 'VEVENT' else 'DUE:')
with pytest.raises(click.UsageError, match=comp_name):
_edit_set(obj, arg, '')


def test_set_mixed_empty_and_value():
t = Todo()
t.data = todo
_edit_set(t, 'comment', ('a', ''))
assert str(t.icalendar_component['comment']) == 'a'


@pytest.mark.parametrize("value, expected", [
(('uid-1',), ['uid-1']),
(('uid-1', ''), ['uid-1']),
('uid-1', ['uid-1']), ## interactive "set parent=uid-1"
])
def test_process_set_relation(value, expected):
assert _process_set_arg('parent', value, keep_category=True) == {'parent': expected}


def test_set_empty_relation_is_noop():
t = Todo()
t.data = todo
with patch.object(Todo, 'set_relation') as set_relation:
_edit_set(t, 'parent', ('',))
_edit_set(t, 'child', '')
set_relation.assert_not_called()
24 changes: 24 additions & 0 deletions tests/test_plann_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -906,3 +906,27 @@ def test_list_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'


def test_add_set_repeatable_and_empty():
"""On add, --set-comment gives one COMMENT per value rather than a tuple
repr, and an empty --set-<attr> adds nothing.
https://github.com/pycalendar/plann/issues/66"""
from caldav.lib.vcal import create_ical
ctx = type('Ctx', (), {'obj': {}})()
_process_set_args(ctx, {'set_comment': ('a', 'b'), 'set_contact': ('',),
'set_location': '', 'set_priority': '',
'set_categories': ('',), 'summary': 'x'})
ical = create_ical(objtype='VTODO', **ctx.obj['set_args'])
assert 'COMMENT:a\nCOMMENT:b\n' in ical
for prop in ('CONTACT', 'LOCATION', 'PRIORITY', 'CATEGORIES'):
assert f'\n{prop}' not in ical
assert "('" not in ical


def test_add_set_empty_relation():
"""An empty --set-parent adds no relation on add"""
ctx = type('Ctx', (), {'obj': {}})()
_process_set_args(ctx, {'set_parent': ('',), 'set_child': ('c1',), 'summary': 'x'})
assert 'parent' not in ctx.obj['set_args']
assert ctx.obj['set_args']['child'] == ['c1']
Loading