diff --git a/CHANGELOG.md b/CHANGELOG.md index 41a35f4..91991d4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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. diff --git a/USER_GUIDE.md b/USER_GUIDE.md index 0266d27..f6973b8 100644 --- a/USER_GUIDE.md +++ b/USER_GUIDE.md @@ -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: ``` diff --git a/plann/commands.py b/plann/commands.py index c9d5d1c..e383291 100644 --- a/plann/commands.py +++ b/plann/commands.py @@ -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- (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: diff --git a/plann/interactive.py b/plann/interactive.py index 6bbbe49..8c7d694 100644 --- a/plann/interactive.py +++ b/plann/interactive.py @@ -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('=') diff --git a/plann/lib.py b/plann/lib.py index acb5bb5..cf0a719 100644 --- a/plann/lib.py +++ b/plann/lib.py @@ -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): """ @@ -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- 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) @@ -649,11 +662,43 @@ 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- 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. @@ -661,24 +706,23 @@ def _set_something(obj, arg, value): """ 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 diff --git a/tests/test_interactive.py b/tests/test_interactive.py index 3b0771c..68e8cc7 100644 --- a/tests/test_interactive.py +++ b/tests/test_interactive.py @@ -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'] diff --git a/tests/test_lib.py b/tests/test_lib.py index c646036..c203944 100644 --- a/tests/test_lib.py +++ b/tests/test_lib.py @@ -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-, 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-="" 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=