summary refs log tree commit diff
path: root/dot_local/bin/executable_todojson.py
blob: 40db8f28c586181e4c6da9bb08bd6da6b1dd2959 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
#!/usr/bin/env python3

"""Convert some funky reminders JSON data to todo.txt."""

from __future__ import annotations

import datetime
import json
import sys
from dataclasses import dataclass


@dataclass(frozen=True)
class TodoEntry:
    index: int
    title: str | None
    notes: str | None
    completed: bool
    priority: int
    completion_date: datetime.datetime | None
    creation_date: datetime.datetime | None
    due_date: datetime.datetime | None
    url: str | None

    @staticmethod
    def from_str(string: str) -> TodoEntry:
        words = string.split()

        # Strip from left to find completion
        if words[0] == "x":
            completed = True
            del words[0]
        else:
            completed = False

        # Strip from left to find priority
        if len(words[0]) == 3 and words[0].startswith("(") and words[0].endswith(")"):
            if words[0] == "(A)":
                priority = 9
            elif words[0] == "(B)":
                priority = 5
            else:
                priority = 1
        else:
            priority = 0

        # Strip from left to find dates
        try:
            creation_date = datetime.date.fromisoformat(words[0])
        except ValueError:
            creation_date = None
            completion_date = None
        else:
            creation_date = datetime.datetime.combine(
                creation_date,
                datetime.time.min,
                datetime.timezone.utc,
            )
            del words[0]
            try:
                completion_date = datetime.date.fromisoformat(words[0])
            except ValueError:
                completion_date = None
            else:
                completion_date = datetime.datetime.combine(
                    completion_date,
                    datetime.time.min,
                    datetime.timezone.utc,
                )
                del words[0]

        # Strip from right to find meta
        meta = {}
        while words and ":" in words[-1][1:-1]:
            k, v = words.pop(-1).split(":", maxsplit=1)
            if k == "due":
                v = datetime.date.fromisoformat(v)
                v = datetime.datetime.combine(
                    v,
                    datetime.time.min,
                    datetime.timezone.utc,
                )
            if k == "index":
                v = int(v)
            if k in meta:
                raise ValueError(f"duplicate meta tag {k}")
            meta[k] = v

        # Strip from right to find context and project
        tags = []
        while words and (words[-1].startswith("+") or words[-1].startswith("@")):
            tags.append("#" + words.pop(-1)[1:])

        # Split the rest into title :: notes
        rest = " ".join(words)
        title, *rest = rest.split(" :: ", maxsplit=1)
        if rest:
            notes = rest[0]
        else:
            notes = None

        if "https" in meta:
            url = "https:" + meta.pop("https")
        elif "http" in meta:
            url = "http:" + meta.pop("http")
        else:
            url = None

        entry = TodoEntry(
            index=meta.pop("index", -1),
            title=title,
            notes=notes,
            completed=completed,
            priority=priority,
            creation_date=creation_date,
            completion_date=completion_date,
            due_date=meta.pop("due", None),
            url=url,
        )
        if meta:
            raise ValueError(f"Unconsumed meta: {meta}")
        return entry

    def __str__(self) -> str:
        bits = []

        # Completion
        if self.completed:
            bits.append("x")

        # Reduce priority to 9->high->A, 5->medium->B, 1->low->C
        if self.priority > 6:
            bits.append("(A)")
        elif self.priority > 3:
            bits.append("(B)")
        elif self.priority > 0:
            bits.append("(C)")

        # Creation date required so default if absent
        if self.creation_date is None:
            bits.append("1970-01-01")
        else:
            bits.append(roundd(self.creation_date).isoformat())

        if self.completion_date is not None:
            bits.append(roundd(self.completion_date).isoformat())

        # Extract tags from title or notes
        tags = ""
        if self.notes:
            notes, tags = extract_tags(self.notes)
            notes = notes.strip()
        else:
            notes = self.notes

        if self.title and not tags:
            title, tags = extract_tags(self.title)
            title = title.strip()
        elif self.title:
            title = self.title.strip()
        else:
            title = self.title

        if title and notes:
            bits.append(f"{title} :: {notes}")
        elif title:
            bits.append(title)
        elif notes:
            bits.append(notes)

        bits.append(tags)

        if self.due_date is not None:
            bits.append("due:" + roundd((self.due_date)).isoformat())

        bits.append("index:" + str(self.index))

        return " ".join(bits).replace("\n", " ")


def extract_tags(string: str) -> tuple[str, str]:
    words = string.split()
    tags = []
    while words and words[-1].startswith("#"):
        tags.append("@" + words.pop(-1)[1:])
    return " ".join(words), " ".join(sorted(tags, key=str.lower))


def roundd(dt: datetime.datetime) -> datetime.date:
    # Exist in more than one TZ, round to closest date
    dates = [
        datetime.datetime.combine(
            dt.date() + delta,
            datetime.time.min,
            datetime.timezone.utc,
        )
        for delta in [
            datetime.timedelta(days=-1),
            datetime.timedelta(days=0),
            datetime.timedelta(days=+1),
        ]
    ]
    min_date = datetime.date.min
    min_delta = datetime.timedelta(days=100)

    for date in dates:
        delta = abs(date - dt)
        if delta < min_delta:
            min_date = date.date()
            min_delta = delta

    return min_date


def _maybe_date(value: str | None) -> datetime.datetime | None:
    if value is not None:
        if value.endswith("Z"):
            value = value[:-1]
        dt = datetime.datetime.fromisoformat(value)
        if dt.tzinfo is None:
            dt = dt.replace(tzinfo=datetime.timezone.utc)
        return dt
    return None


def main():
    data = sys.stdin.read()
    try:
        json_data = json.loads(data)
    except ValueError:
        entries = [TodoEntry.from_str(line.strip()) for line in data.splitlines()]
    else:
        entries = [
            TodoEntry(
                index=n,
                title=row.pop("title", None),
                notes=row.pop("notes", None),
                completed=row.pop("completed"),
                priority=row.pop("priority"),
                completion_date=_maybe_date(row.pop("completionDate", None)),
                creation_date=_maybe_date(row.pop("creationDate", None)),
                due_date=_maybe_date(row.pop("dueDate", None)),
                url=row.pop("url", None),
            )
            for n, row in enumerate(json_data["reminders"])
        ]
        if any(x.keys() - {'uid'} for x in json_data["reminders"]):
            print(f"Left over data:\n{json_data['reminders']}")
    print("\n".join(map(str, entries)))


if __name__ == "__main__":
    main()