-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathtodo
executable file
Β·462 lines (377 loc) Β· 16.5 KB
/
todo
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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
import os
import sys
import pickle
import re
from math import ceil
from enum import IntEnum
from pathlib import Path
from datetime import date
from datetime import datetime
from datetime import timedelta
from configparser import ConfigParser
from argparse import ArgumentParser
""" Define config and data file locations """
config_location = str(Path.home()) + '/.config/py-todo/'
datafile_location = str(Path.home()) + '/.local/share/py-todo/'
""" Define config and data file names """
config_name = 'config'
datafile_name = 'todo.dat'
""" Define colors """
index_color = '\x1b[34m{}\x1b[0m'
date_color = '\x1b[32m{}\x1b[0m'
due_color = '\x1b[31m{}\x1b[0m'
today_color = '\x1b[33m{}\x1b[0m'
""" Regex for removing terminal escape sequences from a string """
esc_seq_reg = re.compile(r'\x1b[^m]*m')
class Weekday(IntEnum):
""" Define Weekday constants """
MONDAY = 0
SATURDAY = 5
SUNDAY = 6
""" List of TodoItems, to be stored later in the datafile """
items = []
class TodoItem:
""" A class definition for each todo item, which is defined with todo -a, and stored in the datafile """
def __init__(self, title: str, exp_date: datetime):
self.title = title
self.exp_date = exp_date
@property
def days_left(self):
return 999 if self.exp_date is None else (self.exp_date.date() - date.today()).days
def exp_time(self):
return str(datetime.time(self.exp_date))
def __str__(self):
if self.exp_date is None:
return self.title
# Set the amount of days left as the timedelta from today to the expiration date, in days.
days_left = self.days_left
exp_time = ""
if config['PY-TODO'].getboolean('show_time', fallback=False) and self.exp_time() != '00:00:00':
# Get the exact Time of the item
exp_time = " " + self.exp_time()
if days_left == 0:
# Annotate as the current day
return self.title + " (Today" + exp_time + ")"
elif days_left == 1:
# Annotate as tomorrow
return self.title + " (Tomorrow" + exp_time + ")"
elif days_left == -1:
# Annotate as Yesterday
return self.title + " (Yesterday" + exp_time + ")"
elif days_left > 1:
output_str = self.title + " ("
# If in detail mode, annotate more explicitly (i.e. give the due weekday)
if config['PY-TODO'].getboolean('detail_mode', fallback=False):
# By default, the first weekday is 'Sun' (last_weekday = Weekday.SATURDAY),
# Users are allowed to override it with 'Mon' (last_weekday = Weekday.SUNDAY).
if 'week_start_day' in config and config['week_start_day'].lower() in ['sun', 'mon'] and config['week_start_day'].lower() == 'mon':
last_weekday = Weekday.SUNDAY
else:
last_weekday = Weekday.SATURDAY
# Calculate weeks_left to determine the event is in this or the next week.
# Suppose today is Thursday, and the week_start_day is Sunday.
# days_to_next_week = 5 (Sat) - 3 (Thu) = 2 (days)
#
# Consider an arbitrary event E,
# if E has 6 days left:
# (6 - 2) / 7 = 0 ... 4
# elif E has 2 days left:
# (2 - 2) / 7 = 0 ... 0
#
# Therefore, we have to apply ceiling function to weeks_left
# in order to distinguish between current week and next week.
days_to_next_week = last_weekday - datetime.today().weekday()
# There are 7 days in a week.
weeks_left = ceil((days_left - days_to_next_week) / 7)
# weeks_left == 0 iff this week;
# weeks_left == 1 iff next week.
if weeks_left == 0 or weeks_left == 1:
output_str += "{this_or_next} {weekday}; ".format(
this_or_next="This" if weeks_left == 0 else "Next",
weekday=self.exp_date.strftime("%A"))
return output_str + "{days_left} days left)".format(days_left=days_left)
elif days_left < -1:
# For dealing with Past-Due Stuffs
output_str = self.title + " ("
# Take absolute value
days_left = abs(days_left)
# Check for detail mode
if config['PY-TODO'].getboolean('detail_mode', fallback=False):
if 'week_start_day' in config and config['week_start_day'].lower() in ['sun', 'mon'] and config['week_start_day'].lower() == 'mon':
last_weekday = 1 # Sunday
else:
last_weekday = 2 # Saturday
days_to_prev_week = datetime.today().weekday() + last_weekday
weeks_left = ceil((days_left - days_to_prev_week) / 7)
if weeks_left == 0 or weeks_left == 1:
output_str += "{this_or_next}{weekday}; ".format(
this_or_next="Last " if weeks_left == 1 else "",
weekday=self.exp_date.strftime("%A"))
return output_str + "{days_left} days ago)".format(days_left=days_left)
else:
return self.title + " ERROR"
def __eq__(self, other):
""" Override default equality """
if isinstance(other, TodoItem):
return (self.title == other.title) and (self.exp_date == other.exp_date)
return False
def maybe_color_str(message, color_fstr, predicate=lambda: True):
"""Colors a string with color_fstr if the config has the color flag set to true
:param message: The message to possibly colorize
:param color_fstr: The color format string
:param predicate: A function deciding whether the message should be colored, alongside the config file
:return: A colored string if the config indicated color """
if config['PY-TODO'].getboolean('color', fallback=False):
stripped_message = esc_seq_reg.sub('', message)
return color_fstr.format(stripped_message) if predicate() else message
return message
def add_item(title: str, exp_date: datetime):
""" Adds a TodoItem to the items list """
items.append(TodoItem(title, exp_date))
def insert_todo_item(index, todo_item):
"""Inserts a TodoItem into the items list at a given index
:param index: The index to insert at
:param todo_item: The item to insert
"""
items.insert(index, todo_item)
def remove_item(indices: list):
""" Removes a TodoItem from the items list """
for index in sorted(indices, reverse=True):
del items[index]
def sort_items():
""" Sorts TodoItem by their remaining days """
items.sort(key=lambda i: i.days_left)
def list_items():
""" Iterate through each TodoItem in the items list and print it """
if len(items) == 0:
print("No items left on the reminder.")
return
print("You have {item_count} item{s} left on the reminder!".format(
item_count=len(items), s="s" if len(items) >= 2 else ""))
for index, item in enumerate(items):
item_str = str(item)
index = str(index)
maybe_colored_index = maybe_color_str(index + ") ", index_color)
if '(' not in item_str:
print(maybe_colored_index + item_str)
else:
# Slice of str from the last occurrence of "(" (inclusive)
date = item_str[item_str.rindex('('):]
# The date could possibly be either color, so no harm in calling maybe_color_str multiple times
date = maybe_color_str(
date, due_color, lambda: True if "DUE" in date else False)
date = maybe_color_str(
date, date_color, lambda: True if "DUE" not in date else False)
date = maybe_color_str(
date, today_color, lambda: True if "Today" in date else False)
date = maybe_color_str(
date, due_color, lambda: True if "Yesterday" in date else False)
# Support for Past-Due Stuffs
date = maybe_color_str(
date, due_color, lambda: True if "ago" in date else False)
print(maybe_colored_index + item.title + " " + date)
def parse_date_str(exp_date_str):
"""Parses a date string and returns a datetime object
:param exp_date_str: the date string to validate
:return: a valid datetime object
"""
try:
if exp_date_str == '':
return None
elif exp_date_str.endswith('d'):
day_count = int(exp_date_str.split('d')[0])
return datetime.today() + timedelta(days=day_count)
else:
return datetime(*map(int, exp_date_str.split('/')))
except:
print("An error occurred while parsing your date.")
sys.exit()
def take_input(title_pos, date_pos, default_title=None):
"""Takes a title and date from the user if not present in sys.argv
:param title_pos: the position of the title in sys.argv
:param date_pos: the position of the date in sys.argv
:param default_title: the default value for the title
:return: a tuple containing the title and date
"""
if default_title:
title = sys.argv[title_pos] if len(sys.argv) > title_pos else input(
"Title ({default_title}): ".format(default_title=default_title))
else:
title = sys.argv[title_pos] if len(
sys.argv) > title_pos else input("Title: ")
exp_date_str = sys.argv[date_pos] if len(sys.argv) > date_pos else input(
"Expiry date (YYYY/MM/DD or <days>d or YYYY/MM/DD/HH/MM/SS) (Optional): ")
return title if title else default_title, exp_date_str
def scrape_keywords(line):
"""Scrapes keywords from an orgfile
:param line: The line to scrape
:returns: A (possibly empty) list of keywords
"""
keywords = []
todos = line.replace('#+TODO: ', '')
for word in todos.split():
if word != '|':
keywords.append(word)
return keywords
def strip_line(line, word):
"""Strips a line of it's *'s and keywords
:param line: The line to strip
:param word: The keyword to strip from the line
:returns: A stripped line
"""
return line.strip('*').replace(word, '').strip()
def scrape_date(line):
"""Scrapes a date from a line known to contain a date
:param line: A line containgin a date
:returns: A datetime object
"""
date = line.split('<')[1]
match = re.search(r'\d{4}-\d{2}-\d{2}', date)
date = match.group(0)
date = datetime(*map(int, date.split('-')))
return date
def usage():
return "\nUsage: " + sys.argv[0] + " <argument>\n" \
"-a --add -- Add a new item.\n" \
"-a --add <title> <date or days> -- Add a new item with a title and expiry date provided.\n" \
"-e --edit <index> -- Edit an item.\n" \
"-e --edit <index> <title> <date or days> -- Edit an item with a title and expiry date provided.\n" \
"-m --move <index> <new index> -- Move an item from index to new index.\n" \
"-r --remove <indices...> -- Remove items by their indices.\n" \
"-s --sort -- Sort items by their remaining days.\n" \
"-l --list -- List all items.\n" \
"-org --orgfile <filename> -- Add org file TODOs.\n" \
"\n" \
"-h --help -- Display help message.\n" \
"-v --version -- Display version info.\n" \
"\n\n" \
"Configuration Options (See " + config_location + config_name + "):\n" \
"* color = true / false\n" \
"* detail_mode = true / false\n" \
def print_version():
print("py-todo 1.3.3\n"
"Copyright (C) 2018 Marco Wang\n"
"\n"
"This is free software, see the source for copying conditions. There is NO\n"
"warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE")
if __name__ == '__main__':
# mkdir -p on config_location and datafile_location.
Path(config_location).mkdir(parents=True, exist_ok=True)
Path(datafile_location).mkdir(parents=True, exist_ok=True)
# Try to load user configuration.
config = ConfigParser()
# Default configuration
config['PY-TODO'] = {
'color': False,
'detail_mode': False,
'week_start_day': 'Sun',
'show_time': False
}
if not os.path.isfile(os.path.join(config_location, config_name)):
# If a config file doesn't exist, write the default one
with open(os.path.join(config_location, config_name), 'w+') as configfile:
config.write(configfile)
else:
config.read(os.path.join(config_location, config_name))
# Try to unpickle todo list from the file.
try:
with open(datafile_location + datafile_name, 'rb') as f:
items = pickle.load(f)
except:
pass
# Command line argument parsing
if len(sys.argv) <= 1:
list_items()
elif sys.argv[1] in ['-l', '--list']:
list_items()
elif sys.argv[1] in ['-a', '--add']:
try:
title, exp_date_str = take_input(2, 3)
exp_date = parse_date_str(exp_date_str)
add_item(title, exp_date)
list_items()
except KeyboardInterrupt:
# If the input is canceled, print a newline for prettiness, list the items and exit
print()
list_items()
sys.exit(1)
elif sys.argv[1] in ['-r', '--remove']:
if len(sys.argv) >= 3:
try:
indices = list(map(int, sys.argv[2:]))
remove_item(indices)
list_items()
except:
print("Item does not exist.")
else:
print(usage())
elif sys.argv[1] in ['-e', '--edit']:
if len(sys.argv) >= 3:
try:
item = items[int(sys.argv[2])]
title, exp_date_str = take_input(
3, 4, default_title=item.title)
item.title = title
item.exp_date = parse_date_str(exp_date_str)
list_items()
except IndexError:
print("Item does not exist.")
sys.exit()
except KeyboardInterrupt:
# If the input is canceled, print a newline for prettiness, list the items and exit
# We don't need to re-add the old item here because if input is canceled, we never actually changed it
print()
list_items()
sys.exit()
else:
print(usage())
elif sys.argv[1] in ["-m", "--move"]:
if len(sys.argv) == 4:
try:
to_move = items[int(sys.argv[2])]
remove_item([int(sys.argv[2])])
insert_todo_item(int(sys.argv[3]), to_move)
except (IndexError, ValueError):
print("Item does not exist.")
sys.exit(1)
list_items()
else:
print(usage())
elif sys.argv[1] in ['-s', '--sort']:
sort_items()
list_items()
elif sys.argv[1] in ['-org', '--orgfile']:
keywords = []
filename = str(sys.argv[2])
# Open the orgfile
with open(filename, 'r') as f:
content = f.readlines()
for index, line in enumerate(content):
# Search for the header to obtain the keywords
if "#+TODO:" in line:
keywords.extend(scrape_keywords(line))
else:
if not keywords:
keywords.append('TODO')
for word in keywords:
# Search in each line and format if match
if word in line and line.startswith('*'):
title = strip_line(line, word)
try:
if ': <' in content[index + 1]:
add_item(title, scrape_date(
content[index + 1]))
else:
add_item(title, None)
except IndexError:
add_item(title, None)
list_items()
elif sys.argv[1] in ['-v', '--version']:
print_version()
else:
print(usage())
# Write all changes back to the file.
with open(datafile_location + datafile_name, 'wb') as f:
pickle.dump(items, f)