-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtodo.py
executable file
·1954 lines (1712 loc) · 65.5 KB
/
todo.py
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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
""" todo.py
...A revamp of my quick and dirty todo list app.
-Christopher Welborn 07-21-2014
"""
import functools
import json
import os
import re
import shutil
import sys
from collections import namedtuple, UserDict, UserList
from contextlib import suppress
# Creates a friendlier message when third-party imports fail.
bad_import_msg = '\n'.join((
'Error: {err}',
'You may need to install {name} with pip: pip install {package}'
)).format
try:
from colr import (
__version__ as colr_version,
auto_disable as colr_auto_disable,
color,
Colr as C,
disabled as colr_disabled,
)
except ImportError as ex:
print(
bad_import_msg(err=ex, name='Colr', package='colr'),
file=sys.stderr,
)
sys.exit(1)
try:
from colr import docopt
except ImportError as ex:
print(
bad_import_msg(err=ex, name='Docopt', package='docopt'),
file=sys.stderr,
)
sys.exit(1)
try:
from printdebug import DebugColrPrinter
except ImportError as ex:
print(
bad_import_msg(err=ex, name='PrintDebug', package='printdebug'),
file=sys.stderr,
)
sys.exit(1)
debugprinter = DebugColrPrinter()
debugprinter.disable()
debug = debugprinter.debug
NAME = 'Todo'
VERSION = '2.6.1'
VERSIONSTR = '{} v. {}'.format(NAME, VERSION)
SCRIPT = os.path.split(os.path.abspath(sys.argv[0]))[1]
SCRIPTDIR = os.path.abspath(sys.path[0])
USAGESTR = """{versionstr}
Usage:
{script} -h | -v
{script} [-a | -b | -d | -r | -R | -s | -t | -u] KEY ITEM
[-f filename | -g] [-D]
{script} [-a | -b | -d | -r | -R | -s | -t | -u] ITEM
[-f filename | -g] [-D]
{script} [-c] | [-i] | ([-j] [KEY]) [-f filename | -g] [-D]
{script} -a [-i] KEY ITEM [-f filename | -g] [-D]
{script} -a [-i] ITEM [-f filename | -g] [-D]
{script} -e FILE KEY [-f filename | -g] [-D]
{script} -I KEY [ITEM] [-f filename | -g] [-D]
{script} -I (KEY | ITEM) [-f filename | -g] [-D]
{script} -i KEY [ITEM] [-f filename | -g] [-D]
{script} -i (KEY | ITEM) [-f filename | -g] [-D]
{script} -K KEY [-f filename | -g] [-D]
{script} -l [-i] [KEY] [-f filename | -g] [-D]
{script} (-k | -L | -P) [-i] [-f filename | -g] [-D]
{script} -m KEY ITEM <new_key> [-f filename | -g] [-D]
{script} -m ITEM <new_key> [-f filename | -g] [-D]
{script} -n [KEY] <new_keyname> [-f filename | -g] [-D]
{script} -p KEY ITEM <new_position> [-f filename | -g] [-D]
{script} -p ITEM <new_position> [-f filename | -g] [-D]
Options:
KEY : Key or label for the item.
Defaults to 'No Label'.
ITEM : Item to add, or query to use when finding
an item. When looking items up, the item
number may also be used.
<new_key> : New key for item when moving between keys.
<new_keyname> : New key name when renaming a key.
<new_position> : New position number for item when position
action is used.
Index must be (>= 0 and < list length).
You may also use 't[op]', or 'b[ottom]'.
-a,--add : Add an item to the list.
You may omit this option and just enter
the item (with optional key first),
unless you want to mark an item as
important while adding it.
-b,--bottom : Unprioritize item. (put on the bottom).
-c,--clear : Clear all items. Confirmation needed.
-d,--down : Bump item down one spot on the list.
-D,--debug : Debug mode, prints extra information.
Gives you a look into what's going on
behind the scenes.
-f FILE,--file FILE : Use this input file instead of todo.lst.
-g,--global : Use global todo.lst even when a local file
exists.
-h,--help : Show this help message.
-i,--important : Mark key/item as important (bold/red).
Only show important items when listing.
-I,--unimportant : Mark key/item as unimportant.
-j,--json : Show list, or a specific key in JSON format.
-k,--listkeys : List key names only.
-K,--removekey : Remove a key/label. (includes all items)
-l,--list : List items from a certain key.
Defaults to: (first key)
-L,--listall : List all items from all keys.
This is the default action when no
arguments are given.
-m,--movetokey : Move item to a new key, or another key.
-n,--renamekey : Give a key another name/label.
-p,--position : Move item to a new position in the same
key.
-P,--preview : Preview the list. Like --listall, except
some items are cut off.
-r,--remove : Remove an item from the list.
Accepts item number or regex to match.
Confirmation is needed.
-R,--REMOVE : Same as --remove, no confirmation though.
-s,--search : Search for items by index or regex/text.
-t,--top : Prioritize item (put on top of the list).
-u,--up : Bump item up one spot on the list.
-v,--version : Show version.
""".format(script=SCRIPT, versionstr=VERSIONSTR)
# Global flags/settings. ------------------------------------------
DEBUG = False
DEBUGARGS = False
DEFAULTFILE = os.path.join(SCRIPTDIR, 'todo.lst')
LOCALFILE = os.path.join(os.getcwd(), 'todo.lst')
# Global TodoList() to work with (..set in main())
todolist = None
# Main entry point ------------------------------------------------
def main(argd): # noqa
""" Main entry point, expects doctopt arg dict as argd """
global DEBUG, todolist, userkey, useritem
DEBUG = argd['--debug']
debugprinter.enable(DEBUG)
if DEBUGARGS:
DEBUG = True
debug('Arguments: ')
debug(json.dumps(argd, sort_keys=True, indent=4), align=True)
return 0
debug_header()
# Use provided file, then local, then the default.
if argd['--file']:
todofile = argd['--file']
elif (not argd['--global']) and os.path.exists(LOCALFILE):
todofile = LOCALFILE
else:
todofile = DEFAULTFILE
# Load todolist if available.
try:
todolist = TodoList(filename=todofile)
except TodoList.NoFileExists:
debug('No file exists at: {}'.format(todofile))
except TodoList.ParseError as exparse:
printstatus('The todo.lst couldn\'t be loaded!', error=exparse)
return 1
except Exception as ex:
printstatus('There was an error while loading the list:', error=ex)
return 1
if todolist is None:
todolist = TodoList()
todolist.filename = todofile
if not argd['--json']:
printheader(todolist)
# Build a map of cmdline-args to functions.
# Return the proper function to run, or None.
runaction = get_action(argd)
if runaction is None:
# Default actions when no args are present.
if argd['ITEM']:
# If the item is actually the name of a key, list that key.
trykey = todolist.get_key(argd['ITEM'])
if trykey:
return do_listkey(trykey)
# User is adding an item.
kwargs = {
'key': (argd['KEY'] or TodoKey.null),
'important': argd['--important'],
}
return do_add(argd['ITEM'], **kwargs)
# User is listing all items.
return do_listall()
# Run the action that was chosen based on cmdline-args.
try:
retvalue = runaction()
except Exception as ex:
printstatus('Error:', error=ex)
return 1
return retvalue
# Functions -------------------------------------------------------
def build_actions(argdict):
""" Builds a dict of command-line args mapped to their function,
arguments are prefilled.
"""
useritem = argdict['ITEM'] or None
rawkey = argdict['KEY']
userkey = rawkey or None
debug('Using key: {!r}'.format(userkey))
userimportant = argdict['--important']
actions = {
'--add': {
'function': do_add,
'args': [useritem],
'kwargs': {'key': userkey, 'important': userimportant},
},
'--bottom': {
'function': do_move_item,
'args': [useritem, 'bottom'],
'kwargs': {'key': userkey},
},
'--clear': {
'function': do_clear,
},
'--down': {
'function': do_move_item,
'args': [useritem, 'down'],
'kwargs': {'key': userkey},
},
'--important': {
'function': do_mark_important,
'args': [useritem],
'kwargs': {
'key': userkey,
'adding': argdict['--add'],
'important': True,
},
},
'--json': {
'function': do_json,
'kwargs': {'key': userkey}
},
'--list': {
'function': do_listkey,
'kwargs': {
'key': userkey,
'important_only': userimportant,
},
},
'--listall': {
'function': do_listall,
'kwargs': {
'important_only': userimportant,
},
},
'--listkeys': {
'function': do_listkeys,
'kwargs': {'important_only': userimportant},
},
'--movetokey': {
'function': do_move_tokey,
'args': [useritem],
'kwargs': {'key': userkey, 'newkey': argdict['<new_key>']},
},
'--position': {
'function': do_move_item,
'args': [useritem, argdict['<new_position>']],
'kwargs': {'key': userkey},
},
'--preview': {
'function': do_listall,
'kwargs': {
'preview': True,
'important_only': userimportant
},
},
'--remove': {
'function': do_remove,
'args': [useritem],
'kwargs': {'key': userkey, 'confirmation': True},
},
'--REMOVE': {
'function': do_remove,
'args': [useritem],
'kwargs': {'key': userkey, 'confirmation': False},
},
'--removekey': {
'function': do_removekey,
'kwargs': {'key': userkey},
},
'--renamekey': {
'function': do_renamekey,
'args': [argdict['<new_keyname>']],
'kwargs': {'key': userkey},
},
'--search': {
'function': do_search,
'args': [useritem],
'kwargs': {'key': rawkey},
},
'--top': {
'function': do_move_item,
'args': [useritem, 'top'],
'kwargs': {'key': userkey},
},
'--unimportant': {
'function': do_mark_important,
'args': [useritem],
'kwargs': {
'key': userkey,
'important': False,
},
},
'--up': {
'function': do_move_item,
'args': [useritem, 'up'],
'kwargs': {'key': userkey},
},
}
# Override do_mark_important with a listing function, this sucks.
for flag in ('--list', '--listall', '--listkeys', '--preview'):
if argdict['--important'] and argdict[flag]:
actions['--important'] = actions[flag]
return actions
def check_empty_key(key=None, silentsave=False):
""" Check to see if a key is empty, and offer to remove it if it is. """
todokey = todolist.get_key(key)
if todokey is None:
debug('Invalid empty key check for: {} (is {})'.format(
key,
todokey))
return False
if len(todokey) == 0:
debug('Key is empty: {}'.format(todokey.label))
warn = ('This key is empty now:', todokey.label)
msg = 'Would you like to remove the key?'
if confirm(msg, warn=warn):
debug('Removing empty key: {}'.format(todokey.label))
if do_removekey(todokey, silentsave=silentsave) == 0:
return True
return False
debug('Key was not empty.')
return False
def confirm(question, header=None, warn=None, forceanswer=False):
""" Confirm a yes/no question, returns True/False (yes/no).
Optional header and/or warning msg printed before the question.
"""
if header:
print('\n{}'.format(header))
if warn:
if isinstance(warn, str):
print('\n{}'.format(colorerr(warn)))
elif isinstance(warn, (list, tuple)):
print('\n{} {}'.format(colorerr(warn[0]), colorval(warn[1])))
if not question.endswith('?'):
question = '{}?'.format(question)
if not question.startswith('\n'):
question = '\n{}'.format(question)
question = '{} (y/N): '.format(question)
ans = input(question).lower()
while forceanswer and (not ans):
ans = input(question).lower()
return (ans[0] == 'y') if ans else False
def debug_header():
""" Print some debug info about this Todo version, if DEBUG is truthy. """
debug('Using:')
debug(
'colr : {}'.format(colr_version),
align=True
)
debug(
'python: {v.major}.{v.minor}.{v.micro}'.format(
v=sys.version_info
),
align=True
)
def do_add(text, key=None, important=False):
""" Add an item to the todo list. (Key is optional.) """
if not text:
printstatus('No item to add!', error=True)
return 1
debug('do_add(key={},important={},"{}")'.format(
key,
important,
text))
key, newitem = todolist.add_item(text, key=key, important=important)
# Todo lists are zero-based.
printstatus(
'Added item:',
key=key,
item=newitem,
index=len(key) - 1,
)
return do_save()
def do_clear():
""" Clear all items (after confirmation.) """
itemcnt = todolist.get_count()
confirmwarn = 'This will clear all {} items from the list.'.format(
itemcnt)
confirmmsg = 'Clear the entire todo list?'
if confirm(confirmmsg, warn=confirmwarn):
todolist.clear()
return do_save()
printstatus('User cancelled.', error=True)
return 1
def do_export(key=None, filename=None):
""" Export a key, or all keys to another JSON file.
This will try to safely merge with existing files.
Arguments:
key : TodoKey to export.
filename : Existing or new JSON file name. Content will be
printed to stdout if '-' is given.
"""
todokey = get_key(key or TodoKey.null)
if todokey is None:
return 1
if filename in (None, '-'):
print(todokey.to_json())
return 0
printstatus('Merging key into {}:'.format(filename), key=todokey)
return 0 if merge_json(todokey.to_json_obj(), filename) else 1
def do_json(key=None):
""" Print JSON format of TodoList. """
if key:
return do_export(key=key)
try:
jsondata = todolist.to_json()
except TodoList.ParseError:
printstatus('Unable to format JSON!', error=True)
return 1
print(jsondata)
return 1
def do_listall(preview=False, important_only=False):
""" List all items in all keys. """
retall = 0
names = todolist.keynames()
for keyname in names:
ret = do_listkey(
keyname,
preview=preview,
important_only=important_only
)
if ret == 1:
retall = 1
printstatus('Error listing key:', key=keyname, error=True)
if not names:
msg = color('No items saved yet.', fore='red')
print('\n{}\n'.format(msg))
return retall
def do_listkey(key=None, preview=False, important_only=False):
""" List all items within a key. """
todokey = get_key(key or TodoKey.null)
if todokey is None:
return 1
if not todokey:
print(' {}'.format(str(todokey)))
printstatus(
' (no items in this key)',
error=True,
nobreak=True
)
return 1
if important_only and (not todokey.important_items()):
return 0
if preview:
keystr = todokey.preview_str(
color=True,
important_only=important_only
)
else:
keystr = todokey.to_str(
color=True,
important_only=important_only
)
print(' {}'.format(keystr.replace('\n', '\n ')))
def do_listkeys(important_only=False):
""" List key names only. """
keynames = todolist.keynames()
# If color is disabled, then use a text marker.
usemarker = colr_disabled()
if not keynames:
printstatus('No keys to list.', error=True)
return 1
longestkeylen = len(max(keynames, key=len))
for keyname in keynames:
key = todolist[keyname]
if important_only and (not key.important):
continue
# Wrap the name in a Colr() to ljust without escape codes.
namefmt = C(
key.get_label(color=not usemarker, usetextmarker=usemarker)
).ljust(longestkeylen)
# Number of items.
lenfmt = C(
'{} items'.format(len(todolist[keyname])),
fore='blue',
).join('[', ']')
print('{} {}'.format(namefmt, lenfmt))
return 0
def do_mark_important(query, key=None, adding=False, important=True):
""" Mark an existing item as important. The 'adding' flag short-circuits
this function and does 'do_add' instead. It is because of the way
arguments are handled (the way functions are fired off.)
"""
debug('Marking important={}: {}, key={}'.format(
important,
query,
key,
))
todokey = todolist.get_key(key, default=None)
if todokey is None:
debug('Looking for item to mark important={}: {}'.format(
important,
key,
))
# User has passed only an item's text. We have to find the key.
items = todolist.find_item(key)
if not items:
printstatus('Cannot find that item: {}'.format(key), error=True)
return 1
# TODO: this is very inefficient.
errs = 0
for listresult in items:
if adding:
errs += do_add(
listresult.item.text,
key=listresult.key,
important=important
)
else:
errs += do_mark_important(
listresult.item.text,
key=listresult.key,
important=important
)
return errs
# We have a key, or both a key and an item.
if adding:
return do_add(query, key=key, important=important)
# We should have a useable key name after this, or else everything fails.
todokey = get_key(key or TodoKey.null)
if todokey is None:
return 1
importantstr = 'important' if important else 'unimportant'
msg = 'Marked as {}:'.format(importantstr)
if not query:
# No query, we are marking a key as important.
todokey.important = important
printstatus(msg, key=todokey)
else:
keyresult = todokey.find_item(query)
if not keyresult:
printstatus('Unable to find that item:', item=query, error=True)
return 1
keyresult.item.important = important
printstatus(
msg,
key=todokey,
index=keyresult.index,
item=keyresult.item
)
return do_save()
def do_move_item(query, newindex, key=None):
""" Move an item from one position to another inside it's key. """
if not newindex:
printstatus('Invalid new position given:', index=newindex, error=True)
return 1
key = key or TodoKey.null
todokey = get_key(key)
if todokey is None:
return 1
maxlength = todokey.get_count() - 1
# Position modifier shortcuts ('top', 'bottom', 'down', 'up')
# Holds a function that will convert the current index into the new one.
position_mod = {
't': lambda i: 0,
'b': lambda i: maxlength,
'u': lambda i: (i - 1) if (i > 0) else 0,
'd': lambda i: (i + 1) if (i < maxlength) else maxlength,
}
# Make sure the item exists, we may need its index anyway.
keyresult = todokey.find_item(query)
if not keyresult:
printstatus('Unable to find that item:', item=query)
return 1
if newindex.lower()[0] in position_mod:
# Modify the new index using shortcuts 'top', 'bottom', 'up', 'down'.
newindex = position_mod[newindex.lower()[0]](keyresult.index)
else:
# Set the index the user wants.
try:
newindex = int(newindex)
except (TypeError, ValueError):
printstatus('Invalid new position:', index=newindex)
indexstr = '{} -> {}'.format(keyresult.index, newindex)
errmsg = 'Unable to move item:'
try:
move = todolist.move_item(query, newindex, key=key)
except (TodoList.BadIndexError, TodoList.BadKeyError) as exindex:
printstatus(
errmsg,
index=indexstr,
item=keyresult.item,
error=exindex,
)
return 1
if not move:
printstatus(errmsg, key=key, index=indexstr, item=move.item)
return 1
# okay.
printstatus('Moved:', key=key, index=indexstr, item=move.item)
return do_save()
def do_move_tokey(query, newkey, key=None):
""" Move an item from one key to another, or to a new key. """
items = todolist.find_item(query, key=key)
if not items:
printstatus('Unable to find that item:', item=query)
return 1
errs = 0
for listresult in items:
try:
move = todolist.move_item_tokey(
listresult.index,
newkey,
key=listresult.key)
except TodoList.BadKeyError as ex:
printstatus(
'Unable to move item from {} to {}.'.format(
listresult.key.label,
newkey,
),
error=ex
)
return 1
keystr = '{} -> {}'.format(listresult.key.label, newkey)
if move:
printstatus('Move item:', key=keystr, item=move.item)
else:
printstatus('Unable to do move:', key=keystr, item=query)
errs += 1
if not check_empty_key(listresult.key, silentsave=True):
debug('Key still has items: {}'.format(listresult.key.label))
return do_save()
def do_remove(query, key=None, confirmation=True):
""" Remove an item (if no key is given, the default key is used.) """
items = todolist.find_item(query, key=key)
if not items:
printstatus('Could not find:', key=(key or '(any key)'), item=query)
if query in todolist.keynames():
printstatus('Did you mean to use --removekey?')
return 1
if confirmation:
itemlen = len(items)
warnmsg = '\n'.join((
'This will remove {cnt} item{plural}:',
' {items}')).format(
cnt=itemlen,
plural='' if itemlen == 1 else 's',
items='\n '.join(
'{}: {}'.format(key.label, item.preview_str())
for key, _, item in items
)
)
msg = 'Are you sure you want to remove {plural}?'.format(
plural='this item' if itemlen == 1 else 'these items'
)
if not confirm(msg, warn=warnmsg):
printstatus('User Cancelled', error=True)
return 1
for listresult in items:
removed = listresult.key.remove_item(listresult.index)
if removed is None:
printstatus('Could not find:', key=listresult.key, item=query)
return 1
printstatus(
'Removed:',
key=listresult.key,
item=removed,
index=listresult.index
)
# Offer to delete the key if it is empty.
if not check_empty_key(listresult.key, silentsave=True):
debug('Key still has items: {}'.format(listresult.key.label))
return do_save()
def do_removekey(key=None, confirmation=True, silentsave=False):
""" Remove a key and all of it's items. """
key = key if key is not None else TodoKey.null
todokey = get_key(key)
if todokey is None:
return 1
itemcnt = len(todokey)
if itemcnt > 1 and confirmation:
warnmsg = 'This will delete {} items!'.format(itemcnt)
msg = 'Are you sure you want to delete {}?'.format(colorkey(key))
if not confirm(msg, warn=warnmsg):
printstatus('User cancelled.', error=True)
return 1
if todolist.delete_key(todokey):
printstatus('Removed:', key=todokey)
else:
printstatus('Unable to remove key:', key=todokey)
return do_save(silent=silentsave)
def do_renamekey(newkeyname, key=None):
""" Rename a key. """
key = key if key is not None else TodoKey.null
# TODO: All of these checks need to be TodoList methods...
# TODO: write TODO comments in the TODO apps code.
# TODO: use the Todo app to write TODOS.
# Renaming to the same name? But why.
if key == newkeyname:
printstatus('Key already has that name:', key=key, error=True)
return 1
# Make sure old key exists.
existingkey = get_key(key)
if existingkey is None:
return 1
# If the new name exists, it would break things. Try 'merging' keys.
existingnewkey = todolist.get_key(newkeyname, None)
if existingnewkey is not None:
printstatus('New key name already taken:', key=newkeyname, error=True)
return 1
# Try renaming the key.
newkey = todolist.rename_key(newkeyname, key=key)
if newkey is None:
printstatus('Unable to rename key:', key=key)
return 1
keystr = '{} -> {}'.format(key, newkey.label)
printstatus('Renamed key:', key=keystr)
return do_save()
def do_save(silent=False):
""" Save all items to disk. """
itemcount = todolist.save_file()
if itemcount > 0:
if not silent:
printstatus('Items saved:', index=itemcount)
return 0
elif itemcount == 0:
if not silent:
printstatus('Items saved. (list is blank)')
return 0
# Error saving.
if not silent:
printstatus('Unable to save items!', error=True)
return 1
def do_search(query, key=None):
""" Search items within a key, or all items using index or regex pattern.
"""
if key is None:
results = todolist.search_items(query)
else:
todokey = get_key(key)
if todokey is None:
return 1
results = [(key, todokey.search_items(query))]
total = 0
for keyname, iteminfo in results:
print(colorkey('{}:'.format(keyname)))
for index, item in iteminfo:
indexstr = color(str(index), style='bright')
msg = ' {}: {}'.format(indexstr, item)
print(msg)
total += 1
resultmsg = 'result found.' if total == 1 else 'results found.'
printstatus('{} {}'.format(str(total), resultmsg))
return 0 if total else 1
def get_action(argdict):
""" Return a function to run based on user args. If no action can be found,
(no args present) then None is returned.
"""
actions = build_actions(argdict)
for argname in actions:
if argdict[argname]:
# Action arg is present, run the function and end.
info = actions[argname]
func = info['function']
args = info.get('args', [])
kwargs = info.get('kwargs', {})
if DEBUG:
fname = func.__name__
dbugmsg = (
'get_action(): '
'{} -> {}'
'({}, {})').format(
argname,
fname,
args,
kwarg_str(kwargs))
debug(dbugmsg)
# Return the function with the appropriate arguments/keyword-args.
return functools.partial(func, *args, **kwargs)
return None
def get_filenames(fore=None, back=None, style=None):
""" Return a list of acceptable todo.lst file paths.
Returns [DEFAULTFILE] or [DEFAULTFILE, LOCALFILE].
Arguments:
fore, back, style : Arguments for color().
If any of these arguments are given,
color() is called on each item before
returning the list.
"""
if DEFAULTFILE == LOCALFILE:
files = [DEFAULTFILE]
else:
files = sorted((DEFAULTFILE, LOCALFILE))
if any((fore, back, style)):
return [color(s, fore=fore, back=back, style=style) for s in files]
return files
def get_key(keyname=None):
""" Wrapper for todolist.get_key(). If an invalid keyname is passed,
an error message is printed and None is returned.
With a valid keyname, the actual TodoKey() is returned.
"""
# A TodoKey may have been passed to another command like do_listkey..
if isinstance(keyname, TodoKey):
debug('Already a key: {}'.format(keyname.label))
return keyname
if keyname is None:
keyname = TodoKey.null
key = todolist.get_key(keyname, default=None)
if key is None:
printstatus('No key named:', key=keyname, error=True)
return None
return key
def kwarg_str(d):
""" Just converts a dict into a keyword-arg-looking string.
kwarg_str({'this': True, 'thing': 25}) == 'this=True, thing=25'
For use in debug messages.
"""
if hasattr(d, 'items'):
return ', '.join('{}={}'.format(k, v) for k, v in d.items())
return ''
def merge_json(dictobj, filename):
""" Merge JSON data into an existing JSON file, or create a new file.
Arguments:
dictobj : A dict with string keys. These keys will be updated
in an existing JSON dict, or created for new files.
This dict should already be JSON serializable.
filename : New or existing JSON file name.
"""
# Try reading existing JSON data.
try:
with open(filename, 'r') as fread:
data = fread.read()
debug('Using existing data from: {}'.format(filename))
except FileNotFoundError:
debug('Creating a new JSON file: {}'.format(filename))
data = '{}'
# Create object from existing JSON, even if it's just an empty dict.
try:
jsondata = json.loads(data)
except ValueError as ex:
printstatus('Not a valid JSON file: {}'.format(filename), error=ex)
return False
# Merge new data with the old.
try:
jsondata.update(dictobj)
except (AttributeError, TypeError):
printstatus('\n'.join((
'Not a valid JSON dict: {filename}',
'Trying to merge: {newdata!r}',
' into: {olddata!r}')).format(
filename=filename,
newdata=dictobj,
olddata=jsondata))
return False
# Write the result to file.
try:
with open(filename, 'w') as f:
json.dump(jsondata, f, indent=4, sort_keys=True)
except EnvironmentError as exwrite:
printstatus(
'Failed to write JSON data: {}'.format(filename),
error=exwrite)
return False
except (ValueError, TypeError) as exjson:
printstatus(
'Failed to create JSON: {}'.format(filename),
error=exjson)
return False
return True