-
Notifications
You must be signed in to change notification settings - Fork 0
/
viewcal
executable file
·365 lines (336 loc) · 13.5 KB
/
viewcal
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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
#!/usr/bin/env python3
# Copyright 2006-2024 Michael Cuffaro
#
# This file is part of mccal.
#
# mccal is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# mccal is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with mccal. If not, see <http://www.gnu.org/licenses/>.
import argparse
import re
import sys
from datetime import date, timedelta
from pathlib import Path
def get_events(
calendar_file, include_snoozes, include_remind_time, show_id,
year, month, day, delta
):
with open(calendar_file) as f:
events = []
for line in f:
line = line.rstrip('\n')
# Skip pending and already processed events:
if line.startswith("PROCESSED ") or line.startswith("PENDING "):
continue
# Skip snoozed events unless the include_snoozes flag is set:
snoozed = line.startswith('SNOOZE')
if not include_snoozes and snoozed:
continue
# Remove the initial portion of the line:
event_id = re.sub(r"^(SNOOZE )?ID:(\S+) (\S+).*$", r"\g<2>", line)
event = re.sub(r"^(SNOOZE )?ID:\S+ ", "", line)
# Remove date and time separators ("/" and ":"):
event = re.sub(
r"""
([0-9]{1,4})-
([0-9]{1,2})-
([0-9]{1,2})\s+
([0-9]{1,2}):
([0-9]{1,2})\s+
"
([0-9]{1,4})-
([0-9]{1,2})-
([0-9]{1,2})\s+
([0-9]{1,2}):
([0-9]{1,2})\s+
(.*?)
"
""",
r'\g<1> \g<2> \g<3> \g<4> \g<5> \g<6> \g<7> \g<8> \g<9> \g<10> \g<11>',
event,
flags=re.X
)
# Parse the reminder and event date and time fields:
event = event.split(' ', maxsplit=10)
for i in range(0, 10):
event[i] = int(event[i])
# Assign them appropriately:
remind_event_year = event[0]
remind_event_month = event[1]
remind_event_day = event[2]
remind_event_hour = event[3]
remind_event_minute = event[4]
event_year = remind_event_year if snoozed else event[5]
event_month = remind_event_month if snoozed else event[6]
event_day = remind_event_day if snoozed else event[7]
# Construct the dates for the range comparison:
event_date = date(year=event_year, month=event_month, day=event_day)
start = date(year=year, month=month or 1, day=day or 1)
end = start if delta is None else start + delta
# Determine whether the event matches the criteria represented by the input to the function:
if (start <= event_date) and (event_date <= end):
if snoozed or include_remind_time:
event[10] = (
event[10] +
f' ({"Snooze until" if snoozed else "Reminder at"}'
f' {remind_event_year:04}-{remind_event_month:02}-{remind_event_day:02}'
f' {remind_event_hour:02}:{remind_event_minute:02})'
)
if show_id:
event[10] = event[10] + f" (ID: {event_id})"
events.append(event)
return events
def sort_events(events):
# Sort the entries:
return sorted(events, key=lambda x: (x[5], x[6], x[7], x[8], x[9]))
def format_events(events, verbose):
# Add back the separators and quotes:
if not verbose:
pretty_events = [f'{x[5]:04}-{x[6]:02}-{x[7]:02} {x[8]:02}:{x[9]:02} {x[10]}' for x in events]
else:
raw_events = {}
for x in events:
key = (x[5], x[6], x[7])
if raw_events.get(key) is None:
raw_events[key] = []
raw_events[key].append(f"{x[8]:02}:{x[9]:02} {x[10]}")
pretty_events = []
raw_events = raw_events.items()
year = month = day = None
show_months = len(set([(k[0], k[1]) for (k, e) in raw_events])) > 1
for (key, events) in raw_events:
event_year, event_month, event_day = key[0], key[1], key[2]
if show_months and (event_year != year or event_month != month):
pretty_events.append("{}\n".format(
date(year=event_year, month=event_month, day=event_day).strftime("%B %Y")
))
day = None
if event_day != day:
pretty_events.append("{}".format(
date(year=event_year, month=event_month, day=event_day).strftime("%A, %B %d, %Y")
))
pretty_events.append("---")
pretty_events += events
pretty_events.append("---\n")
year, month, day = event_year, event_month, event_day
return pretty_events
def main(
calendar_file, modifier, time_period, include_snoozes, include_remind_time,
show_id, verbose
):
if m := re.fullmatch(r'(\d{1,4})(-(\d{1,2}))?(-(\d{1,2}))?', time_period):
year = int(m.groups()[0])
month = int(m.groups()[2]) if m.groups()[2] is not None else None
day = int(m.groups()[4]) if m.groups()[4] is not None else None
delta = None
if day is None and month is None:
new_years_day = date(year=year, month=1, day=1)
last_day_of_year = new_years_day.replace(year=new_years_day.year+1) - timedelta(days=1)
delta = last_day_of_year - new_years_day
elif day is None:
first_of_month = date(year=year, month=month, day=1)
end_of_month = first_of_month.replace(
month=first_of_month.month+1 if first_of_month.month != 12 else 1,
year=first_of_month.year+1 if first_of_month.month == 12 else first_of_month.year
) - timedelta(days=1)
delta = end_of_month - first_of_month
elif time_period == 'today':
today = date.today()
if modifier == "next":
# The "next today" is tomorrow ;-)
today = today + timedelta(days=1)
elif modifier == "last":
# The "last today" is yesterday ;-)
today = today - timedelta(days=1)
year, month, day = today.year, today.month, today.day
delta = None
elif time_period == 'tomorrow':
tomorrow = date.today() + timedelta(days=1)
if modifier == "next":
# The "next tomorrow" is two days from now ;-)
tomorrow = tomorrow + timedelta(days=1)
elif modifier == "last":
# The "last tomorrow" is today ;-)
tomorrow = tomorrow - timedelta(days=1)
year, month, day = tomorrow.year, tomorrow.month, tomorrow.day
delta = None
elif time_period == 'yesterday':
yesterday = date.today() + timedelta(days=-1)
if modifier == "next":
# The "next yesterday" is today ;-)
yesterday = yesterday + timedelta(days=1)
elif modifier == "last":
# The "last yesterday" was two days ago ;-)
yesterday = yesterday - timedelta(days=1)
year, month, day = yesterday.year, yesterday.month, yesterday.day
delta = None
elif time_period in ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday',
'sunday']:
today = date.today()
monday = today - timedelta(days=today.weekday())
if time_period == "monday":
start = monday
elif time_period == "tuesday":
start = monday + timedelta(days=1)
elif time_period == "wednesday":
start = monday + timedelta(days=2)
elif time_period == "thursday":
start = monday + timedelta(days=3)
elif time_period == "friday":
start = monday + timedelta(days=4)
elif time_period == "saturday":
start = monday + timedelta(days=5)
elif time_period == "sunday":
start = monday + timedelta(days=6)
else:
print(f"{time_period}? Sure, I'll work on it.")
sys.exit(1)
if modifier == "next":
start += timedelta(weeks=1)
elif modifier == "last":
start -= timedelta(weeks=1)
year, month, day = start.year, start.month, start.day
delta = None
elif time_period in ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august',
'september', 'october', 'november', 'december']:
if time_period == "january":
first_of_month = date.today().replace(month=1, day=1)
elif time_period == "february":
first_of_month = date.today().replace(month=2, day=1)
elif time_period == "march":
first_of_month = date.today().replace(month=3, day=1)
elif time_period == "april":
first_of_month = date.today().replace(month=4, day=1)
elif time_period == "may":
first_of_month = date.today().replace(month=5, day=1)
elif time_period == "june":
first_of_month = date.today().replace(month=6, day=1)
elif time_period == "july":
first_of_month = date.today().replace(month=7, day=1)
elif time_period == "august":
first_of_month = date.today().replace(month=8, day=1)
elif time_period == "september":
first_of_month = date.today().replace(month=9, day=1)
elif time_period == "october":
first_of_month = date.today().replace(month=10, day=1)
elif time_period == "november":
first_of_month = date.today().replace(month=11, day=1)
elif time_period == "december":
first_of_month = date.today().replace(month=12, day=1)
if modifier == "next":
first_of_month = first_of_month.replace(year=first_of_month.year+1)
elif modifier == "last":
first_of_month = first_of_month.replace(year=first_of_month.year-1)
year, month, day = first_of_month.year, first_of_month.month, first_of_month.day
end_of_month = first_of_month.replace(
month=first_of_month.month+1 if first_of_month.month != 12 else 1,
year=first_of_month.year+1 if first_of_month.month == 12 else first_of_month.year
) - timedelta(days=1)
delta = end_of_month - first_of_month
elif time_period == 'week':
today = date.today()
monday = today - timedelta(days=today.weekday())
if modifier == "next":
monday += timedelta(weeks=1)
elif modifier == "last":
monday -= timedelta(weeks=1)
year, month, day = monday.year, monday.month, monday.day
delta = timedelta(days=6)
elif time_period == 'month':
first_of_month = date.today().replace(day=1)
if modifier == "next":
first_of_month = first_of_month.replace(
month=first_of_month.month+1 if first_of_month.month != 12 else 1,
year=first_of_month.year+1 if first_of_month.month == 12 else first_of_month.year
)
elif modifier == "last":
first_of_month = first_of_month.replace(
month=first_of_month.month-1 if first_of_month.month != 1 else 12,
year=first_of_month.year-1 if first_of_month.month == 1 else first_of_month.year
)
year, month, day = first_of_month.year, first_of_month.month, first_of_month.day
end_of_month = first_of_month.replace(
month=first_of_month.month+1 if first_of_month.month != 12 else 1,
year=first_of_month.year+1 if first_of_month.month == 12 else first_of_month.year
) - timedelta(days=1)
delta = end_of_month - first_of_month
elif time_period == 'year':
new_years_day = date.today().replace(month=1, day=1)
if modifier == "next":
new_years_day = new_years_day.replace(year=new_years_day.year+1)
elif modifier == "last":
new_years_day = new_years_day.replace(year=new_years_day.year-1)
year, month, day = new_years_day.year, new_years_day.month, new_years_day.day
last_day_of_year = new_years_day.replace(year=new_years_day.year+1) - timedelta(days=1)
delta = last_day_of_year - new_years_day
else:
print(f"Illegal time period: {time_period}")
sys.exit(1)
events = get_events(calendar_file, include_snoozes, include_remind_time, show_id,
year, month, day, delta)
if events:
events = sort_events(events)
print('\n'.join(format_events(events, verbose)))
if __name__ == "__main__":
default_cal = f"{str(Path.home())}/.mycalendar.txt"
# If viewcal is run with no arguments, interpret this as if it were `viewcal today`:
if len(sys.argv) == 1:
main(default_cal, None, "today", False, False, False, False)
sys.exit(0)
# Otherwise parse the command line arguments:
parser = argparse.ArgumentParser(description="Simple reminder calendar -- viewcal")
parser.add_argument(
'--calendar', metavar='FILE',
help=f"use the given calendar file instead of '{default_cal}'"
)
parser.add_argument(
'-a', '--all',
help='also show snoozed events that will trigger reminders during the given PERIOD',
action="store_true"
)
parser.add_argument(
'-r', '--reminders',
help='show the date and time at which the reminder for a given event will be triggered',
action="store_true"
)
parser.add_argument(
'--show_id',
help="show the event ID of matching events",
action="store_true"
)
parser.add_argument(
'-v', '--verbose',
help='display the events in a somewhat more readable format',
action='store_true'
)
parser.add_argument(
'MODIFIER', choices=['this', 'next', 'last'], nargs='?',
help="(if left unspecified, defaults to 'this'); show the events for this PERIOD, the next \
PERIOD, or the last PERIOD, respectively."
)
parser.add_argument(
'PERIOD',
help="(if left unspecified, defaults to 'today'); can be one of: \
year, month, week, monday, tuesday, wednesday, thursday, friday, saturday, sunday, today, \
tomorrow, yesterday, january, february, march, april, may, june, july, august, september, \
october, november, december, yyyy-mm-dd, yyyy-mm, yyyy"
)
args = parser.parse_args()
main(
args.calendar or default_cal,
args.MODIFIER.lower() if args.MODIFIER else args.MODIFIER,
args.PERIOD.lower(),
args.all,
args.reminders,
args.show_id,
args.verbose
)