diff --git a/CHANGELOG.md b/CHANGELOG.md index 75691ca..9d758f9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,14 +10,17 @@ and I do try to adhere to [Semantic Versioning](https://semver.org/spec/v2.0.0.h * `add todo` and `add event` take `--set-alarm`, either a duration like `10m`, which puts it that long before the DUE of a task (or before its DTSTART if it has none) or before the start of an event (`+10m` is after, as in iCalendar), or a timestamp. A number without a unit, like `15`, is minutes, as in most calendar software. The alarm displays the summary. * 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. ### Changed +* The plan that `check-for-panic --interactive-fix-timeline` (and `interactive manage-tasks`) opens in the editor now has a start and a duration per task, like `2026-11-24 10:00 +1h30m`, instead of a start and an end, so editing the start moves the task and keeps its length. All times are in one timezone, named at the top of the file, as are the times printed by `--print-timeline` and the list of tasks that will need to be procrastinated; they used to be in whatever timezone each event was stored in. Existing events are `#` comment lines, and a `#` in a task summary is no longer cut off. * The `plann interactive` subcommands now have the same defaults as when `interactive manage-tasks` runs them, except `dismiss-panic --hours-per-day`, which `manage-tasks` runs with 24 and then 14. `check-due` looks 24 hours ahead (was 16) and goes through at most 16 tasks (was unlimited); `split-huge-tasks` and `split-high-pri-tasks` look 60 days and 640 tasks ahead (was 30 days and 32 tasks). * A bare hour (one or two digits, 0-23) in a date or time argument, like `--set-dtstart=14`, means 14:00 today in the implicit timezone. It was taken as the 14th of the month, giving an all-day task. `--set-alarm` is the exception: there a number without a unit is minutes. ### Fixed +* 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 ... 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/TASK_MANAGEMENT.md b/TASK_MANAGEMENT.md index c340a21..425861e 100644 --- a/TASK_MANAGEMENT.md +++ b/TASK_MANAGEMENT.md @@ -395,3 +395,16 @@ The panic planning will try to figure out if it's still possible to perform all TODO: write more about the panic planning algorithm. +#### Pinning tasks to the calendar + +`plann select --todo check-for-panic --include-all-events --interactive-fix-timeline` (also run by `interactive manage-tasks`, for the next five days) opens the suggested timeline in an editor, one line per task: + +``` +# All times are in Europe/Oslo (CET = UTC+01:00). +... +2b5c0e1e-... 2026-11-24 10:00 +1h30m Write the report +# 2026-11-24 12:00 +1h Lunch +``` + +The columns are UID, start, duration and summary. There is no end time, so changing the start moves the task and keeps its length; change the duration to make it shorter or longer. Delete a line to leave a task off the calendar. Lines starting with `#` are existing events, shown for reference. All times are in one timezone, the one named at the top of the file (the `--implicit-timezone`, or else the local one). Each remaining line becomes a tentative event, a child of the task. A line that can't be parsed reopens the editor with the error at the top; delete all the task lines to get out without pinning anything. Afterwards you may plan again: the tasks just pinned are left out of the new suggestion. + diff --git a/plann/cli.py b/plann/cli.py index ffd22f7..62cb85b 100755 --- a/plann/cli.py +++ b/plann/cli.py @@ -511,7 +511,7 @@ def complete(ctx, **kwargs): @click.option('--include-all-events/--no-extra-events', help='Include all events (and selected tasks)') @click.option('--print-timeline/--no-print-timeline', help='Print a possible timeline') @click.option('--fix-timeline/--no-fix-timeline', help='Make events from the tasks and pin them to the calendar') -@click.option('--interactive-fix-timeline/--no-interactive-fix-timeline', help='Make a suggested editable time table') +@click.option('--interactive-fix-timeline/--no-interactive-fix-timeline', help='Edit the suggested timeline (start and duration per task) and pin the tasks to the calendar') @click.pass_context def check_for_panic(ctx, **kwargs): """Check if we need to panic diff --git a/plann/commands.py b/plann/commands.py index af3a951..125f169 100644 --- a/plann/commands.py +++ b/plann/commands.py @@ -10,6 +10,7 @@ import click import icalendar from caldav.lib.error import ETagMismatchError, NotFoundError, PutError, ScheduleTagMismatchError +from dateutil import tz as dateutil_tz from icalendar_searcher import Searcher from plann.interactive import ( @@ -22,7 +23,6 @@ _mass_interactive_edit, _mass_reprioritize, _pdb_edit, - _strip_line, interactive_split_task, ) from plann.lib import ( @@ -45,7 +45,7 @@ childlike, parentlike, ) -from plann.panic_planning import timeline_suggestion +from plann.panic_planning import format_pin_plan, parse_pin_plan, timeline_suggestion from plann.template import Template from plann.timespec import DURATION_RE, _ensure_ts, _now, parse_add_dur, parse_dt, parse_timespec, tz @@ -362,6 +362,39 @@ def _edit(ctx, cancel=None, interactive_ical=False, interactive_relations=False, ## OPTIMIZE TODO: only save objects that actually have been edited obj.save() +def _display_timezone(): + return tz.implicit_timezone or dateutil_tz.tzlocal() + +def _timeline_entries(possible_timeline, timeline_start): + """(uid, begin, end, summary) for the future items of the timeline, + uid is None for things that are already events""" + ret = [] + for (foo, next) in zip(possible_timeline, possible_timeline[1:]): + if 'begin' in foo and 'obj' in foo and not isinstance(foo['obj'], str): + if _ensure_ts(foo['begin'])>timeline_start: + obj = foo['obj'] + uid = str(obj.icalendar_component['UID']) if isinstance(obj, caldav.Todo) else None + ret.append((uid, foo['begin'], next['begin'], _summary(obj))) + return ret + +def _interactive_fix_timeline(ctx, possible_timeline, timeline_start): + """Lets the user edit the suggested plan and pins the tasks in it to + the calendar. Returns the number of events added.""" + tzinfo = _display_timezone() + text = format_pin_plan(_timeline_entries(possible_timeline, timeline_start), tzinfo) + while True: + text = _editor(text) + try: + plan = parse_pin_plan(text, tzinfo) + break + except ValueError as e: + text = "\n".join([f"# ERROR: {e}"] + [x for x in text.split("\n") if not x.startswith("# ERROR: ")]) + for (uid, begin, end, summary) in plan: + event = _add_event(ctx, summary=summary, timespec=(begin, end), set_status='TENTATIVE', first_calendar=True, set_parent=[uid]) + ## so a new plan won't suggest the task again + ctx.obj['objs'].append(event) + return len(plan) + def _check_for_panic(ctx, hours_per_day, output=True, print_timeline=True, fix_timeline=False, interactive_fix_timeline=False, timeline_start=None, timeline_end=None, include_all_events=False): if not timeline_start: timeline_start = _now() @@ -384,10 +417,11 @@ def summary(obj): return _summary(obj) if (print_timeline): + tzinfo = _display_timezone() click.echo("Calculated timeline suggestion:") for foo in possible_timeline: if 'begin' in foo: - click.echo(f"{foo['begin']:%FT%H:%M %Z} {summary(foo.get('obj'))}") + click.echo(f"{foo['begin'].astimezone(tzinfo):%FT%H:%M %Z} {summary(foo.get('obj'))}") if output: click.echo() @@ -395,43 +429,18 @@ def summary(obj): for foo in possible_timeline: if 'begin' in foo and 'obj' in foo and not isinstance(foo['obj'], str): if _ensure_ts(foo['begin'])timeline_start: - obj = foo['obj'] - if isinstance(obj, caldav.Todo): - comp = obj.icalendar_component - if fix_timeline: - ## TODO: copy other attributes? - _add_event(ctx, summary=_summary(obj), timespec=(foo['begin'], next['begin']), set_status='TENTATIVE', first_calendar=True, set_parent=[comp['UID']]) - elif interactive_fix_timeline: - output.append(f"{comp['UID']:37} {foo['begin']} - {next['begin']}: {_summary(obj)}") - elif interactive_fix_timeline: - output.append(f"{' '*37} {foo['begin']} - {next['begin']}: {_summary(obj)}") + due = _ensure_ts(foo['obj'].get_due()).astimezone(_display_timezone()) + click.echo(f"{due:%FT%H%M %Z} {foo['obj'].icalendar_component.get('PRIORITY', 0)} {_summary(foo['obj'])}") + + if fix_timeline: + for (uid, begin, end, summary) in _timeline_entries(possible_timeline, timeline_start): + if uid: + ## TODO: copy other attributes? + _add_event(ctx, summary=summary, timespec=(begin, end), set_status='TENTATIVE', first_calendar=True, set_parent=[uid]) if interactive_fix_timeline: - pinned_re = re.compile("^(.+?) +(.+?) - (.+?): (.+)$") - fixed_timeline = _editor("""\ -# Lines not starting with UID are already events and cannot be changed as for now -# Delete things you don't want on the calendar -# You may also change the suggested times and even the summary -# There are no collision control if you change the suggested times -""" + "\n".join(output)) - for line in fixed_timeline.split('\n'): - if line.startswith(' '*16): - continue - line = _strip_line(line) - if not line: - continue - parsed = pinned_re.match(line) - assert parsed ## TODO: print a friendly error message and probably even continue execution - (uid, begin, end, summary) = parsed.groups() - _add_event(ctx, summary=summary, timespec=f"{begin} {end}", set_status='TENTATIVE', first_calendar=True, set_parent=[uid]) + while (_interactive_fix_timeline(ctx, possible_timeline, timeline_start) and + click.confirm("Plan again, with the events just added?", default=False)): + possible_timeline = timeline_suggestion(ctx, hours_per_day=hours_per_day, timeline_end=timeline_end) return possible_timeline diff --git a/plann/panic_planning.py b/plann/panic_planning.py index f7bec8f..50e42b0 100644 --- a/plann/panic_planning.py +++ b/plann/panic_planning.py @@ -1,8 +1,10 @@ -from datetime import datetime, timedelta +import re +from datetime import datetime, timedelta, timezone from sortedcontainers import SortedKeyList from plann.lib import _component_type, _ensure_ts, _now +from plann.timespec import parse_add_dur class TimeLine(SortedKeyList): @@ -148,3 +150,86 @@ def timeline_suggestion(ctx, hours_per_day=4, timeline_end=None): timeline.pad_slack(begin, -slackbalance) slackbalance=timedelta(0) return timeline + + +## The editable plan used by check-for-panic --interactive-fix-timeline. +## One line per task: UID START DURATION SUMMARY. The end is deliberately +## not written out, so moving the start keeps the length of the block. + +PIN_PLAN_TS_FORMAT = '%Y-%m-%d %H:%M' +_pin_plan_re = re.compile(r'^(\S+)\s+(\d{4}-\d{2}-\d{2} \d{1,2}:\d{2})\s+(\+?[0-9.smhdwy]+)\s+(\S.*?)\s*$') + +def format_duration(duration): + """timedelta to the duration syntax parse_add_dur reads, like +1h30m""" + secs = int(duration.total_seconds()) + ret = '' + for unit, size in (('d', 86400), ('h', 3600), ('m', 60), ('s', 1)): + if secs >= size: + ret += f"{secs // size}{unit}" + secs %= size + return '+' + (ret or '0m') + +def _utc_offset(ts): + off = ts.strftime('%z') + return f"UTC{off[:3]}:{off[3:]}" + +def format_pin_plan(entries, tzinfo): + """entries are (uid, begin, end, summary) tuples, uid None for + existing events. All timestamps are shown in tzinfo.""" + zone = getattr(tzinfo, 'key', None) or 'local time' + offsets = [] + for (uid, begin, end, summary) in entries: + ts = begin.astimezone(tzinfo) + label = f"{ts:%Z} = {_utc_offset(ts)}" + if label not in offsets: + offsets.append(label) + if len(offsets) > 1: + offset_note = f" ({', '.join(offsets)}; the offset changes within this plan)" + elif offsets: + offset_note = f" ({offsets[0]})" + else: + offset_note = '' + lines = [ + f"# All times are in {zone}{offset_note}.", + "#", + "# Each line is: UID START DURATION SUMMARY", + "# There is no end time: the end is START + DURATION. Change START to move", + "# a task, it keeps its length. Change DURATION (like +45m, +2h, +1h30m)", + "# to make it shorter or longer. The summary may be edited too.", + "# Delete a line to leave that task off the calendar. Delete all the task", + "# lines to pin nothing - also the way out after an error.", + "# Lines starting with '#' are existing events, they can't be changed here.", + "# There is no collision check.", + "", + ] + width = max([len(x[0]) for x in entries if x[0]] + [36]) + for (uid, begin, end, summary) in entries: + prefix = uid.ljust(width) if uid else '#'.ljust(width) + ## real elapsed time, as parse_pin_plan adds it back + duration = end.astimezone(timezone.utc) - begin.astimezone(timezone.utc) + summary = re.sub(r'\s*[\r\n]+\s*', ' ', str(summary)).strip() + lines.append(f"{prefix} {begin.astimezone(tzinfo):{PIN_PLAN_TS_FORMAT}} {format_duration(duration):7} {summary}") + return "\n".join(lines) + "\n" + +def parse_pin_plan(text, tzinfo): + """Inverse of format_pin_plan. Returns a list of (uid, begin, end, + summary), raises ValueError naming the line on syntax errors.""" + ret = [] + for (lineno, line) in enumerate(text.split('\n'), start=1): + line = line.strip() + if not line or line.startswith('#'): + continue + parsed = _pin_plan_re.match(line) + if not parsed: + raise ValueError(f"line {lineno}: expected UID YYYY-MM-DD HH:MM DURATION SUMMARY, got: {line}") + (uid, begin, duration, summary) = parsed.groups() + try: + begin = datetime.strptime(begin, PIN_PLAN_TS_FORMAT).replace(tzinfo=tzinfo) + duration = parse_add_dur(None, duration) + except ValueError as e: + raise ValueError(f"line {lineno}: {e}: {line}") from e + if not duration or duration <= timedelta(0): + raise ValueError(f"line {lineno}: the duration must be positive: {line}") + end = (begin.astimezone(timezone.utc) + duration).astimezone(tzinfo) + ret.append((uid, begin, end, summary)) + return ret diff --git a/pyproject.toml b/pyproject.toml index 3caaa52..deff065 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -102,6 +102,9 @@ known-first-party = ["plann"] testpaths = ["tests"] python_files = ["test_*.py"] filterwarnings = ["error"] +# No async tests here; a pytest-asyncio installed system-wide would +# otherwise fail the run with a deprecation warning made fatal above. +addopts = "-p no:asyncio" [tool.coverage.run] source = ["plann"] diff --git a/tests/test_functional.py b/tests/test_functional.py index 291e27b..03a7494 100644 --- a/tests/test_functional.py +++ b/tests/test_functional.py @@ -329,10 +329,29 @@ def dag(obj, reltype, observed=None): ## Testing interactive fix timeline, and checking that past events are ignored in the ## panic planning. ## We were busy with other things at the scheduled time. Let's try to reschedule ... - with patch('plann.commands._editor', new=passthrough) as _editor: + ## A parse error reopens the editor with the error on top; then + ## we accept the plan and ask for a new one, which should have + ## nothing left to pin, so no third round is offered. + editor_texts = [] + def editor(text): + editor_texts.append(text) + if len(editor_texts) == 1: + return text + "\nthis line is garbage\n" + return text.replace("this line is garbage", "") + def editor_(text): + assert len(editor_texts) < 5 + return editor(text) + with patch("plann.commands._editor", new=editor_), \ + patch('plann.commands.click.confirm', return_value=True) as _confirm: with patch('plann.panic_planning._now', new=lambda: datetime_(2010,12,9,23,33,33)) as _now: _select(ctx, todo=True) _check_for_panic(ctx, timeline_start='2010-10-10', timeline_end=datetime_(year=2011, month=11, day=11, hour=11, minute=11), hours_per_day=24, print_timeline=False, interactive_fix_timeline=True, include_all_events=True) + assert len(editor_texts) == 3 + assert editor_texts[1].startswith('# ERROR: line ') + assert 'garbage' in editor_texts[1] + assert _confirm.call_count == 1 + ## the second plan has the newly pinned tasks as existing events only + assert not [x for x in editor_texts[2].split('\n') if x and not x.startswith('#')] _select(ctx, event=True) assert len(ctx.obj['objs'])==4 diff --git a/tests/test_panic.py b/tests/test_panic.py index 1697d8f..0316799 100644 --- a/tests/test_panic.py +++ b/tests/test_panic.py @@ -109,3 +109,103 @@ def test_timeline_suggestion(): timeline = panic_planning.timeline_suggestion(ctx, hours_per_day=23) #['x' for x in assert + +## The editable plan of interactive_fix_timeline: one line per task, +## UID START DURATION SUMMARY. The end is START+DURATION, so moving the +## start keeps the length. + +def test_pin_plan_format(): + from zoneinfo import ZoneInfo + oslo = ZoneInfo('Europe/Oslo') + utc = ZoneInfo('UTC') + entries = [ + ## an existing event, stored in UTC + (None, datetime(2026, 11, 24, 8, 0, tzinfo=utc), datetime(2026, 11, 24, 9, 0, tzinfo=utc), 'Standup'), + ('uid-1', datetime(2026, 11, 24, 10, 0, tzinfo=oslo), datetime(2026, 11, 24, 11, 30, tzinfo=oslo), 'Write #1 report'), + ] + text = panic_planning.format_pin_plan(entries, oslo) + ## time zone named in the header + assert 'Europe/Oslo' in text + assert 'UTC+01:00' in text + ## all timestamps converted to the display zone, the end is not written out + assert '2026-11-24 09:00 +1h' in text + assert '2026-11-24 10:00 +1h30m' in text + assert '11:30' not in text + ## the existing event is a comment, the task is not + lines = text.split('\n') + assert [x for x in lines if 'Standup' in x][0].startswith('#') + assert [x for x in lines if 'Write' in x][0].startswith('uid-1 ') + + ## Unchanged text parses back to the same plan, converted to the + ## display zone - and a '#' in a summary is not a comment + parsed = panic_planning.parse_pin_plan(text, oslo) + assert parsed == [('uid-1', entries[1][1], entries[1][2], 'Write #1 report')] + + ## Moving the start moves the end + moved = text.replace('2026-11-24 10:00 +1h30m', '2026-11-24 13:15 +1h30m') + ((uid, begin, end, summary),) = panic_planning.parse_pin_plan(moved, oslo) + assert begin == datetime(2026, 11, 24, 13, 15, tzinfo=oslo) + assert end == datetime(2026, 11, 24, 14, 45, tzinfo=oslo) + + ## Changing the duration resizes; no plus sign is fine too + resized = text.replace('+1h30m', '45m') + ((uid, begin, end, summary),) = panic_planning.parse_pin_plan(resized, oslo) + assert end - begin == timedelta(minutes=45) + +def test_pin_plan_dst_switch(): + from zoneinfo import ZoneInfo + oslo = ZoneInfo('Europe/Oslo') + entries = [ + ('a', datetime(2026, 10, 24, 10, 0, tzinfo=oslo), datetime(2026, 10, 24, 11, 0, tzinfo=oslo), 'before'), + ('b', datetime(2026, 10, 26, 10, 0, tzinfo=oslo), datetime(2026, 10, 26, 11, 0, tzinfo=oslo), 'after'), + ] + text = panic_planning.format_pin_plan(entries, oslo) + assert 'UTC+02:00' in text + assert 'UTC+01:00' in text + assert panic_planning.parse_pin_plan(text, oslo) == entries + +def test_pin_plan_entry_spanning_dst_switch(): + """The duration is real elapsed time, so an unedited plan gives + back the same start and end, whatever zone the entry came in""" + from zoneinfo import ZoneInfo + oslo = ZoneInfo('Europe/Oslo') + utc = ZoneInfo('UTC') + ## three hours across the night the clocks go back + stored_utc = ('a', datetime(2026, 10, 24, 23, 30, tzinfo=utc), datetime(2026, 10, 25, 2, 30, tzinfo=utc), 'utc') + ## 00:30 to 03:30 Oslo wall clock is four hours + stored_oslo = ('b', datetime(2026, 10, 25, 0, 30, tzinfo=oslo), datetime(2026, 10, 25, 3, 30, tzinfo=oslo), 'oslo') + for (entry, shown) in ((stored_utc, '+3h '), (stored_oslo, '+4h ')): + text = panic_planning.format_pin_plan([entry], oslo) + assert shown in text + ((uid, begin, end, summary),) = panic_planning.parse_pin_plan(text, oslo) + assert (begin, end) == (entry[1], entry[2]) + +def test_pin_plan_multiline_summary(): + """A summary taken from a multi-line DESCRIPTION stays on its line""" + from zoneinfo import ZoneInfo + oslo = ZoneInfo('Europe/Oslo') + entries = [ + (None, datetime(2026, 11, 24, 8, 0, tzinfo=oslo), datetime(2026, 11, 24, 9, 0, tzinfo=oslo), 'Standup\nwith the team'), + ('uid-1', datetime(2026, 11, 24, 10, 0, tzinfo=oslo), datetime(2026, 11, 24, 11, 0, tzinfo=oslo), 'Buy milk\r\nand bread\n'), + ] + text = panic_planning.format_pin_plan(entries, oslo) + assert panic_planning.parse_pin_plan(text, oslo) == [ + ('uid-1', entries[1][1], entries[1][2], 'Buy milk and bread')] + +def test_pin_plan_says_how_to_cancel(): + from zoneinfo import ZoneInfo + text = panic_planning.format_pin_plan([], ZoneInfo('Europe/Oslo')) + assert 'Delete all the task\n# lines to pin nothing' in text + +def test_pin_plan_parse_errors(): + from zoneinfo import ZoneInfo + + import pytest + oslo = ZoneInfo('Europe/Oslo') + for bad in ('uid-1 2026-11-24 10:00 - 11:30 summary', + 'uid-1 tomorrow +1h summary', + 'uid-1 2026-11-24 10:00 +0m summary', + 'uid-1 2026-11-24 10:00 +1h'): + with pytest.raises(ValueError, match='line 2'): + panic_planning.parse_pin_plan('# comment\n' + bad, oslo) + assert panic_planning.parse_pin_plan('\n# only comments\n \n', oslo) == []