Skip to content
Open
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
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ and I do try to adhere to [Semantic Versioning](https://semver.org/spec/v2.0.0.h
* A warning when the singular `--set-category`, `--add-category` or `--add-resource` is given a value with a comma in it, like `--set-category=boat,keyboard`, and when a plural option like `--set-categories` is given more than once with a comma in a value. Both give one category named `boat,keyboard`, while a single `--set-categories=boat,keyboard` gives two. The behaviour itself is unchanged (it is intended), but is now documented in the user guide.
* `plann interactive check-pinned` goes through the past week's events pinning tasks to the calendar (as made by the panic planning in `interactive manage-tasks`) and asks if each task was done. A done task is completed (with its subtasks), and its event is marked as confirmed; its other pins may be cancelled. If not done, the event is cancelled. It is also run first in `interactive manage-tasks`. https://github.com/pycalendar/plann/pull/89
* After the tasks in the plan of `check-for-panic --interactive-fix-timeline` (and `interactive manage-tasks`) are pinned, it offers to plan again, leaving out the tasks just pinned.
* `select --priority` selects by priority: one number, a range or a list, like `--priority 5`, `--priority 1-3` or `--priority 1,5-9`. 0 matches tasks with no priority set. The filtering is done client-side, and needs icalendar-searcher 1.4.0 or later.

### Changed

Expand All @@ -28,6 +29,7 @@ and I do try to adhere to [Semantic Versioning](https://semver.org/spec/v2.0.0.h
* `plann add -l LINE event` dropped the extra iCalendar lines; they are now added to the event, as they were to tasks and journals.
* A task with DTSTART as a date and DUE as a timestamp (or the other way around) made `interactive manage-tasks` and other selections crash with `KeyError: 'DTEND'`. The date is now made a timestamp at midnight, in the timezone of the other one if it has a named one, else in the local timezone; the time of day on the other one is kept (it used to be dropped), and the result is valid iCalendar.
* `interactive check-due` (also run by `interactive manage-tasks`) silently left out the due tasks beyond the first 16, usually the low-priority ones. It now says how many tasks are due when it cannot show them all.
* Postponing (`edit --postpone`, `interactive manage-tasks`) left DTSTART behind on a task where DTSTART equals DUE, or where one of them is a date and the other a timestamp, so the duration (used as a time estimate) grew with every postponement. DTSTART now moves along with DUE, keeping the duration. A date DTSTART is first made a timestamp, as in selections: next to a DUE in UTC it becomes local midnight, so the duration that is kept depends on the local timezone.
* `interactive manage-tasks`: a parent task postponed together with its child could be postponed once more in its own turn, and with caldav 3.6 this crashed with a "412 Precondition Failed" error. It is now skipped, with a note. A task changed on the server in the meantime is reloaded before it is postponed.
* `interactive manage-tasks` no longer stops with a traceback when the server refuses to store a task it postpones, e.g. with "423 Locked" from a Xandikos server busy with another write. The task is reported and the rest are still postponed.

Expand Down
2 changes: 1 addition & 1 deletion TASK_MANAGEMENT.md
Original file line number Diff line number Diff line change
Expand Up @@ -345,7 +345,7 @@ To interactively find and set the missing properties, it's possible to do `plann

### Listing tasks

The `select`-command can be used to list tasks. The `--todo`-flag will ensure that only pending tasks are listed. Say that it's a nice day for garden work, then `plann select --todo --category garden list` would probably be the right thing to do.
The `select`-command can be used to list tasks. The `--todo`-flag will ensure that only pending tasks are listed. Say that it's a nice day for garden work, then `plann select --todo --category garden list` would probably be the right thing to do. `--priority` selects by priority, like `plann select --todo --priority 1-3 list` for the most important tasks (`--priority 0` gives the tasks with no priority set).

There exists some other ways too. `plann agenda` will list out events and tasks with `DTSTART` in the near-term future. `plann interactive check-due` will go through overdue and near-due tasks and interactively ask the user what to do with them. Then there is also the "panic planning mode" available, for instance `plann interactive dismiss-panic` - it will list overdue tasks and tasks that you probably won't have time to do within the planned `DUE`. More on that below.

Expand Down
1 change: 1 addition & 0 deletions plann/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -361,6 +361,7 @@ def freebusy_sync(ctx, to_section, summary, tag, days, hours, weekdays_only, dry
@click.option('--offset', help='Skip the first objects', type=int)
@click.option('--freebusyhack', help='DEPRECATED, use the freebusy-sync command. Removes almost everything from the ical and replaces the summary with the provided string. Leaks the details of recurrence exceptions.')
@click.option('--pinned-tasks/--no-pinned-tasks', default=None, help='select all/no pinned tasks')
@click.option('--priority', help='select by priority: a number, a range or a list, like 5, 1-3 or 1,5-9. 1 is the highest priority, 9 the lowest, 0 undefined (also matches tasks without a priority)')
@click.pass_context
def select(*largs, **kwargs):
"""Search command, allows listing, editing, etc
Expand Down
74 changes: 36 additions & 38 deletions plann/commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
_comma_list_tokens,
_complete,
_component_type,
_fix_mismatched_date_types,
_is_comma_list_attr,
_list,
_process_set_arg,
Expand Down Expand Up @@ -132,7 +133,28 @@ def _sort_value(comp, skey):
value = comp.get(skey)
return getattr(value, 'dt', value)

def __select(ctx, extend_objects=False, all=None, uid=[], abort_on_missing_uid=None, warn_on_missing_uid=True, sort_key=[], skip_parents=None, skip_children=None, limit=None, offset=None, freebusyhack=None, pinned_tasks=None, **kwargs_):
def _parse_priority(spec):
"""The priorities in ``spec``: a comma-separated list of numbers or
ranges, like ``5``, ``1-3`` or ``1,5-9``."""
wanted = set()
for part in spec.split(','):
rx = re.fullmatch(r'\s*(\d)\s*(?:-\s*(\d)\s*)?', part)
if not rx:
raise click.BadParameter(f"expected priorities 0-9 like 5, 1-3 or 1,5-9, got {spec!r}", param_hint='--priority')
lo, hi = sorted((int(rx.group(1)), int(rx.group(rx.lastindex))))
wanted.update(range(lo, hi + 1))
return wanted

def _filter_priority(objs, wanted):
"""Keep the objects with a PRIORITY in ``wanted``. 0 is RFC 5545
"undefined priority" and also matches a missing PRIORITY. Done
client-side, as CalDAV searches have no integer comparison."""
searcher = Searcher()
searcher.add_property_filter('PRIORITY', wanted, operator='in')
return [obj for obj in objs
if searcher.check_component(obj) or (0 in wanted and 'PRIORITY' not in obj.icalendar_component)]

def __select(ctx, extend_objects=False, all=None, uid=[], abort_on_missing_uid=None, warn_on_missing_uid=True, sort_key=[], skip_parents=None, skip_children=None, limit=None, offset=None, freebusyhack=None, pinned_tasks=None, priority=None, **kwargs_):
"""
select/search/filter tasks/events, for listing/editing/deleting, etc
"""
Expand Down Expand Up @@ -185,6 +207,10 @@ def __select(ctx, extend_objects=False, all=None, uid=[], abort_on_missing_uid=N
if uid:
return

## parsed before searching, so a typo costs no server round-trip
if priority is not None:
priority = _parse_priority(priority)

if pinned_tasks:
kwargs['event'] = True
kwargs['todo'] = None
Expand All @@ -211,8 +237,14 @@ def __select(ctx, extend_objects=False, all=None, uid=[], abort_on_missing_uid=N

if 'start' in kwargs and 'end' in kwargs:
kwargs['expand'] = True
found = []
for c in ctx.obj['calendars']:
objs.extend(c.search(**kwargs))
found.extend(c.search(**kwargs))
## with --pinned-tasks the search finds the pinning events, and the
## priority filter waits for the tasks they pin, below
if priority is not None and pinned_tasks is None:
found = _filter_priority(found, priority)
objs.extend(found)

if skip_children or skip_parents:
i = 0
Expand Down Expand Up @@ -242,6 +274,8 @@ def __select(ctx, extend_objects=False, all=None, uid=[], abort_on_missing_uid=N
children = _relships_by_type(obj, 'CHILD').get('CHILD',[])
if not any(x.icalendar_component.get('STATUS', '')!='CANCELLED' for x in children if isinstance(x, caldav.Event)):
ret_objs.append(obj)
if priority is not None:
ret_objs = _filter_priority(ret_objs, priority)
ctx.obj['objs'] = ret_objs

## OPTIMIZE TODO: sorting the list multiple times rather than once is a bit of brute force, if there are several sort keys and long list of objects, we should sort once and consider all sort keys while sorting
Expand Down Expand Up @@ -274,42 +308,6 @@ def __select(ctx, extend_objects=False, all=None, uid=[], abort_on_missing_uid=N
if attr == 'SUMMARY':
comp[attr] = freebusyhack

def _fix_mismatched_date_types(comp):
"""If one of DTSTART and DTEND/DUE is a date and the other a timestamp,
turn the date into a timestamp at midnight, so they can be compared: in
the timezone of the timestamp if it has a named one (TZID), floating if
it is floating, and in the implicit timezone if it is in UTC (also a
TZID naming UTC). The time
of day on the timestamp is kept. Logs an error if DTSTART comes after
DTEND/DUE."""
endkey = 'DTEND' if 'DTEND' in comp else 'DUE'
dtstart = comp.get('DTSTART')
dtend = comp.get(endkey)
if not (dtstart and dtend):
return
start_is_ts = isinstance(dtstart.dt, datetime.datetime)
if start_is_ts != isinstance(dtend.dt, datetime.datetime):
logging.error(f"task with uuid {comp['uid']} has non-matching types on dtstart and dtend/due, setting both to timestamps")
date_key, d, other_key, other = (endkey, dtend, 'DTSTART', dtstart) if start_is_ts else ('DTSTART', dtstart, endkey, dtend)
d = d.dt
tz = other.dt.tzinfo
is_utc = tz is datetime.timezone.utc or str(tz) in ('UTC', 'Etc/UTC', 'Etc/Zulu', 'Zulu', 'Etc/UCT', 'UCT')
new_ts = datetime.datetime(d.year, d.month, d.day)
if tz and 'TZID' in other.params and not is_utc:
new_ts = new_ts.replace(tzinfo=tz)
## re-add the other one too, so icalendar writes its own name for
## the timezone (e.g. Europe/Berlin for "W. Europe Standard Time")
## in both properties
comp.pop(other_key)
comp.add(other_key, other.dt)
elif tz:
new_ts = _ensure_ts(d)
## replace the property rather than setting .dt, so VALUE=DATE goes away
comp.pop(date_key)
comp.add(date_key, new_ts)
if _ensure_ts(comp['DTSTART'].dt) > _ensure_ts(comp[endkey].dt):
logging.error(f"task with uuid {comp['uid']} has dtstart after dtend/due")

def _categories_in_use(objs):
categories = set()
for obj in objs:
Expand Down
46 changes: 46 additions & 0 deletions plann/lib.py
Original file line number Diff line number Diff line change
Expand Up @@ -299,6 +299,43 @@ def _summary(obj):
i = _icalendar_component(obj)
return i.get('summary') or i.get('description') or i.get('uid')

def _fix_mismatched_date_types(comp):
"""If one of DTSTART and DTEND/DUE is a date and the other a timestamp,
turn the date into a timestamp at midnight, so they can be compared: in
the timezone of the timestamp if it has a named one (TZID), floating if
it is floating, and in the implicit timezone if it is in UTC (also a
TZID naming UTC). The time
of day on the timestamp is kept. Logs an error if DTSTART comes after
DTEND/DUE."""
endkey = 'DTEND' if 'DTEND' in comp else 'DUE'
dtstart = comp.get('DTSTART')
dtend = comp.get(endkey)
if not (dtstart and dtend):
return
start_is_ts = isinstance(dtstart.dt, datetime.datetime)
if start_is_ts != isinstance(dtend.dt, datetime.datetime):
logging.error(f"task with uuid {comp['uid']} has non-matching types on dtstart and dtend/due, setting both to timestamps")
date_key, d, other_key, other = (endkey, dtend, 'DTSTART', dtstart) if start_is_ts else ('DTSTART', dtstart, endkey, dtend)
d = d.dt
tz = other.dt.tzinfo
is_utc = tz is datetime.timezone.utc or str(tz) in ('UTC', 'Etc/UTC', 'Etc/Zulu', 'Zulu', 'Etc/UCT', 'UCT')
new_ts = datetime.datetime(d.year, d.month, d.day)
if tz and 'TZID' in other.params and not is_utc:
new_ts = new_ts.replace(tzinfo=tz)
## re-add the other one too, so icalendar writes its own name for
## the timezone (e.g. Europe/Berlin for "W. Europe Standard Time")
## in both properties
comp.pop(other_key)
comp.add(other_key, other.dt)
elif tz:
new_ts = _ensure_ts(d)
## replace the property rather than setting .dt, so VALUE=DATE goes away
comp.pop(date_key)
comp.add(date_key, new_ts)
if _ensure_ts(comp['DTSTART'].dt) > _ensure_ts(comp[endkey].dt):
logging.error(f"task with uuid {comp['uid']} has dtstart after dtend/due")


childlike = {'CHILD', 'NEXT', 'FINISHTOSTART'}
parentlike = {'PARENT', 'FIRST', 'DEPENDS-ON', 'STARTTOFINISH'}

Expand Down Expand Up @@ -357,7 +394,16 @@ def _procrastinate(objs, delay, check_dependent="error", with_children=False, wi
## Let's force the due to be a timestamp
if not isinstance(new_due, datetime.datetime):
new_due = datetime.datetime(new_due.year, new_due.month, new_due.day)
comp = x.icalendar_component
_fix_mismatched_date_types(comp)
## caldav leaves DTSTART alone if the duration is zero; a negative
## one (DTSTART after DUE) is treated the same, so it is not saved
zero_duration = 'DTSTART' in comp and any(k in comp for k in ('DUE', 'DTEND', 'DURATION')) and x.get_duration() <= datetime.timedelta(0)
parent = x.set_due(new_due, move_dtstart=True, check_dependent=chk_parent)
if zero_duration and not parent:
comp.pop('DTSTART')
## set_due may have converted a naive new_due, DTSTART must match DUE
comp.add('DTSTART', comp['DUE'].dt)
if parent:
if check_dependent in ("error", "interactive"):
i = x.icalendar_component
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ dependencies = [
"dateparser>=1.2",
"python-dateutil",
"icalendar>=7.0.0",
"icalendar_searcher",
"icalendar_searcher>=1.4.0",
]

[project.urls]
Expand Down
Loading
Loading