-
Notifications
You must be signed in to change notification settings - Fork 3
/
things2md.py
703 lines (598 loc) · 27.5 KB
/
things2md.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
# Things3 Logbook -> Markdown conversion script.
# For use in Obsidian for Daily Notes.
# Execute from Obsidian with the shellcommands community plugin.
import argparse
from argparse import RawTextHelpFormatter
import errno
import json
import os
import re
import sys
import urllib.parse
from datetime import datetime
from dateutil.relativedelta import *
import things
THINGS2MD_CONFIG_FILE = './things2md.json'
# #############################################################################
# CLI ARGUMENTS
# #############################################################################
_required_args = ["date", "due", "project", "projects", "range", "tag", "today"]
_required_args_msg = f"At least one of these arguments is required: {', '.join(_required_args)}"
parser = argparse.ArgumentParser(description="Things3 database -> Markdown conversion script.", formatter_class=RawTextHelpFormatter,
epilog=f"{_required_args_msg}\n\nConfiguration options for {THINGS2MD_CONFIG_FILE} are documented in README.md")
parser.add_argument('--date', help='Date to get completed tasks for, in ISO format (e.g., 2023-10-07).', type=datetime.fromisoformat)
parser.add_argument('--debug', default=False, action='store_true', help='If set will show script debug information.')
parser.add_argument('--due', default=False, action='store_true', help='If set will show incomplete tasks with deadlines.')
parser.add_argument('--groupby', choices=['area', 'date','project'], help='How to group the tasks. Use in conjunction with --orderby')
parser.add_argument('--orderby', default='date', choices=['area', 'date','index','project'], help='How to order the tasks.')
parser.add_argument('--project', help='If provided, only tasks for this project are fetched.')
parser.add_argument('--projects', default=False, action='store_true', help='If set will show a list of projects only.')
parser.add_argument('--range', help='Relative date range to get completed tasks for (e.g., "today", "1 day ago", "1 week ago", "this week" which starts on Monday). Completed tasks are relative to midnight of the day requested.')
parser.add_argument('--tag', help='If provided, only uncompleted tasks with this tag are fetched.')
parser.add_argument('--template', default='default', help='Name of the template to use from the configuration.')
parser.add_argument('--today', default=False, action='store_true', help='If set will show incomplete tasks in Today.')
args = parser.parse_args()
# make sure at least one required argument is provided
if all(getattr(args, arg) is None or getattr(args, arg) is False for arg in _required_args):
sys.stderr.write(f"things2md: {_required_args_msg}\nUse --help to learn about available options.\n\n")
exit(errno.EINVAL) # Invalid argument error code
DEBUG = args.debug
ARG_DATE = args.date
ARG_DUE = args.due
ARG_GROUPBY = args.groupby
ARG_ORDERBY = args.orderby
ARG_PROJECT = args.project
ARG_PROJECTS = args.projects
ARG_PROJECT_UUID = None # set later if ARG_PROJECT is provided
ARG_RANGE = args.range
ARG_TAG = args.tag
ARG_TEMPLATE = args.template
ARG_TODAY = args.today
# #############################################################################
# LOAD CONFIGURATION
# #############################################################################
_config_file_path = os.path.join(os.path.dirname(__file__), THINGS2MD_CONFIG_FILE)
try:
with open(_config_file_path, "r") as config_file:
CONFIG = json.load(config_file)
except:
sys.stderr.write(f"things2md: Unable to open config file: {THINGS2MD_CONFIG_FILE}\n")
exit(1)
_config_error_msg = None
_required_params = ["filters", "formatting", "templates"]
if any(CONFIG.get(param) is None for param in _required_params):
_config_error_msg = f"{THINGS2MD_CONFIG_FILE}: All of these params are required: {', '.join(_required_params)}"
if _cfg_filters := CONFIG.get("filters"):
_required_params = ["remove_area_emojis", "remove_heading_emojis", "remove_project_emojis", "remove_task_emojis", "skip_tags"]
if any(_cfg_filters.get(param) is None for param in _required_params):
_config_error_msg = f"{THINGS2MD_CONFIG_FILE} (filters): All of these params are required: {', '.join(_required_params)}"
CFG_REMOVE_AREA_EMOJIS = _cfg_filters.get("remove_area_emojis")
CFG_REMOVE_HEADING_EMOJIS = _cfg_filters.get("remove_heading_emojis")
CFG_REMOVE_PROJECT_EMOJIS = _cfg_filters.get("remove_project_emojis")
CFG_REMOVE_TASK_EMOJIS = _cfg_filters.get("remove_task_emojis")
CFG_REMOVE_EMPTY_CHECKLIST_ITEMS = _cfg_filters.get("remove_empty_checklist_items") if _cfg_filters.get("remove_empty_checklist_items") else False
CFG_SKIP_TAGS = _cfg_filters.get("skip_tags")
if _cfg_formatting := CONFIG.get("formatting"):
_required_params = ["area_sep", "date_sep", "deadline_sep", "heading_sep", "project_sep", "status_symbols"]
if any(_cfg_formatting.get(param) is None for param in _required_params):
_config_error_msg = f"{THINGS2MD_CONFIG_FILE} (formatting): All of these params are required: {', '.join(_required_params)}"
CFG_AREA_SEPARATOR = _cfg_formatting.get("area_sep")
CFG_DATE_SEPARATOR = _cfg_formatting.get("date_sep")
CFG_DEADLINE_SEPARATOR = _cfg_formatting.get("deadline_sep")
CFG_HEADING_SEPARATOR = _cfg_formatting.get("heading_sep")
CFG_PROJECT_SEPARATOR = _cfg_formatting.get("project_sep")
CFG_STATUS_SYMBOLS = _cfg_formatting.get("status_symbols")
if _cfg_templates := CONFIG.get("templates"):
# get the requested template
CFG_TEMPLATE = None
for template in _cfg_templates:
if template.get("name") == ARG_TEMPLATE:
CFG_TEMPLATE = template
break
if not CFG_TEMPLATE:
_config_error_msg = f"Unable to find template: {ARG_TEMPLATE}\n"
else:
# validate the provided template's params are set
if CFG_TEMPLATE.get('type') == 'markdown_note':
_required_params = ["title", "body", "checklist_item"]
else:
_required_params = ["checklist_item", "groupby_date", "groupby_project", "project", "notes", "task"]
if any(CFG_TEMPLATE.get(param) is None for param in _required_params):
_config_error_msg = f"{THINGS2MD_CONFIG_FILE} ({ARG_TEMPLATE}): All of these params are required: {', '.join(_required_params)}"
# TODO: for ease-of-use, replace all template variables with lower-case?
if _config_error_msg:
sys.stderr.write(f"things2md: {_config_error_msg}")
exit(1)
# #############################################################################
# GLOBALS
# #############################################################################
EMOJI_PATTERN = re.compile("["
u"\U0001F600-\U0001F64F"
u"\U0001F300-\U0001F5FF"
u"\U0001F680-\U0001F6FF"
u"\U0001F700-\U0001F77F"
u"\U0001F780-\U0001F7FF"
u"\U0001F800-\U0001F8FF"
u"\U0001F900-\U0001F9FF"
u"\U0001FA00-\U0001FA6F"
u"\U0001FA70-\U0001FAFF"
u"\U00002702-\U000027B0"
u"\U000024C2-\U0001F251"
u"\U000023E9"
"]+", flags=re.UNICODE)
# default GCal event times to 9am-9:30am today
event_start_time = datetime.now().replace(hour=9, minute=0, second=0, microsecond=0)
event_finish_time = event_start_time + relativedelta(minutes=30)
event_start_rfc5545 = event_start_time.strftime('%Y%m%dT%H%M%S')
event_finish_rfc5545 = event_finish_time.strftime('%Y%m%dT%H%M%S')
GCAL_EVENT_DATES = f"{event_start_rfc5545}/{event_finish_rfc5545}"
QUERY_LIMIT = 100
TODAY = datetime.today().astimezone()
TODAY_DATE = TODAY.date()
TODAY_INT = int(TODAY_DATE.strftime('%Y%m%d'))
TODAY_TIMESTAMP = datetime(TODAY.year, TODAY.month, TODAY.day).timestamp()
# #############################################################################
# FUNCTIONS
# #############################################################################
def get_datetime_range(date_range):
'''
Returns dates for the given date range expressed in English, relative to today.
Supported: today, yesterday, X days ago, X weeks ago, X months ago, X years ago
"this week" is also supported, and starts on Monday
'''
splitted = date_range.split()
start_date = None
end_date = None
if date_range == "this week":
start_date = TODAY - relativedelta(days=TODAY.weekday())
end_date = start_date + relativedelta(days=6)
elif len(splitted) == 1 and splitted[0].lower() == 'today':
start_date = TODAY
elif len(splitted) == 1 and splitted[0].lower() == 'yesterday':
start_date = TODAY - relativedelta(days=1)
elif splitted[1].lower() in ['day', 'days', 'd']:
start_date = TODAY - relativedelta(days=int(splitted[0]))
elif splitted[1].lower() in ['wk', 'wks', 'week', 'weeks', 'w']:
start_date = TODAY - relativedelta(weeks=int(splitted[0]))
elif splitted[1].lower() in ['mon', 'mons', 'month', 'months', 'm']:
start_date = TODAY - relativedelta(months=int(splitted[0]))
elif splitted[1].lower() in ['yrs', 'yr', 'years', 'year', 'y']:
start_date = TODAY - relativedelta(years=int(splitted[0]))
else:
return None, None
start_date = start_date.replace(hour=0, minute=0, second=0, microsecond=0)
# set the end date to 11:59:59pm, to ensure we get all tasks
if end_date:
end_date = end_date.replace(hour=23, minute=59, second=59)
else:
end_date = TODAY.replace(hour=23, minute=59, second=59, microsecond=999999)
return start_date, end_date
def has_skip_tags(task):
'''
Returns True if any of the tags in the given task/project/area is in ENV_SKIP_TAGS.
'''
skip = False
if CFG_SKIP_TAGS:
if ('area' in task) and any(item in areas[task['area']].get('tags', []) for item in CFG_SKIP_TAGS):
skip = True
elif ('project' in task) and any(item in projects[task['project']].get('tags', []) for item in CFG_SKIP_TAGS):
skip = True
elif ('tags' in task) and any(item in task['tags'] for item in CFG_SKIP_TAGS):
skip = True
return skip
def indent_string(string_to_indent):
'''
Indents a multi-line string with tabs.
'''
lines = string_to_indent.split("\n")
indented_lines = ["\t" + line for line in lines]
indented_string = "\n".join(indented_lines)
return indented_string
def query_areas():
'''
Fetches areas.
'''
kwargs = dict()
if DEBUG: kwargs['print_sql'] = True; print("\nAREAS QUERY:")
try:
areas = things.areas(**kwargs)
except ValueError as ve:
sys.stderr.write(f"things2md: Things.py Error: {ve.args[0]}\n")
exit(1)
return areas
def query_projects(first_datetime):
'''
Fetches projects not finished, or finished within the range provided.
'''
kwargs = dict(status=None)
if DEBUG: kwargs['print_sql'] = True; print("\nPROJECT QUERY:")
try:
projects = things.projects(stop_date=False, **kwargs)
except ValueError as ve:
sys.stderr.write(f"things2md: Things.py Error: {ve.args[0]}\n")
exit(1)
if first_datetime is not None:
# FIXME: note that this drops the timezone, as Things works off UTC
# sounds like this needs to be fixed in Things.py:
# https://github.com/chrisgurney/things2md/pull/2#issuecomment-1967535472
# ...or not? (similar discussion here:) https://github.com/PyGithub/PyGithub/issues/512
stop_date = first_datetime.strftime("%Y-%m-%d")
projects += things.projects(stop_date=f'>{stop_date}', **kwargs)
#
# filter projects
#
for project in projects:
project['notes'] = filter_notes(project['notes'])
if CFG_REMOVE_AREA_EMOJIS and 'area_title' in project:
project['area_title'] = filter_area_title(project['area_title'])
if CFG_REMOVE_PROJECT_EMOJIS:
project['title'] = filter_project_title(project['title'])
#
# order projects based on arguments
#
if ARG_ORDERBY == "project":
projects.sort(key=lambda x: x.get("title","").casefold())
elif ARG_ORDERBY == "area":
projects.sort(key=lambda x: x.get("area_title","").casefold())
return projects
def query_tasks(first_datetime, last_datetime = None):
'''
Fetches tasks completed within the range provided.
'''
# things.py parameter documention here:
# https://thingsapi.github.io/things.py/things/api.html#tasks
kwargs = dict(include_items=True)
if ARG_PROJECT:
kwargs['project'] = ARG_PROJECT_UUID
if ARG_TAG:
kwargs['tag'] = ARG_TAG
if first_datetime is not None:
kwargs['status'] = None
# FIXME: note that this drops the timezone, as Things works off UTC
# sounds like this needs to be fixed in Things.py:
# https://github.com/chrisgurney/things2md/pull/2#issuecomment-1967535472
# ...or not? (similar discussion here:) https://github.com/PyGithub/PyGithub/issues/512
stop_date = first_datetime.strftime("%Y-%m-%d")
kwargs['stop_date'] = f'>{stop_date}'
elif ARG_DATE:
kwargs['status'] = None
kwargs['stop_date'] = f'{ARG_DATE.strftime("%Y-%m-%d")}'
elif ARG_DUE:
kwargs['deadline'] = True
kwargs['start_date'] = True
kwargs['status'] = 'incomplete' # default, but leaving here for clarity
elif ARG_TODAY:
kwargs['start_date'] = True
kwargs['start'] = 'Anytime'
kwargs['index'] = 'todayIndex'
else:
kwargs['status'] = 'incomplete' # default, but leaving here for clarity
if ARG_ORDERBY == "index":
kwargs['index'] = 'todayIndex'
if DEBUG: kwargs['print_sql'] = True; print("\nTASK QUERY:")
try:
tasks = things.tasks(**kwargs)
except ValueError as ve:
sys.stderr.write(f"things2md: Things.py Error: {ve.args[0]}\n")
exit(1)
# FIXME: get tasks for next day if last_datetime is provided as well
# get next day's tasks as well, so that we can account for GMT being past midnight local time
if ARG_DATE: # or last_datetime
# if ARG_DATE:
given_date_obj = ARG_DATE
# if last_datetime:
# given_date_obj = last_datetime
next_day_date_obj = given_date_obj + relativedelta(days=1)
next_day_date = next_day_date_obj.strftime("%Y-%m-%d")
kwargs['stop_date'] = f'{next_day_date}'
next_day_tasks = things.tasks(**kwargs)
tasks = tasks + next_day_tasks
#
# filter tasks
#
for task in tasks:
task['notes'] = filter_notes(task['notes'])
if CFG_REMOVE_TASK_EMOJIS: task['title'] = filter_task_title(task['title'])
if CFG_REMOVE_PROJECT_EMOJIS and 'project_title' in task:
task['project_title'] = filter_project_title(task['project_title'])
if CFG_REMOVE_HEADING_EMOJIS and 'heading_title' in task:
task['heading_title'] = filter_heading_title(task['heading_title'])
#
# order + group based on arguments
#
# return tasks based on the provided date
if ARG_DATE:
given_date_local = given_date_obj.astimezone()
given_date_local_eod = given_date_local.replace(hour=23, minute=59, second=59)
# FIXME: do when we have an end date set
for item in tasks[:]:
# FIXME: should this instead specify that this is UTC?
stop_date_local = datetime.strptime(item['stop_date'], "%Y-%m-%d %H:%M:%S").astimezone()
if stop_date_local > given_date_local and stop_date_local <= given_date_local_eod:
pass
else:
tasks.remove(item)
#
# sort based on arguments
#
if ARG_ORDERBY == "project":
tasks.sort(key=lambda x: x['stop_date'] if x['stop_date'] is not None else float('-inf'), reverse=True)
tasks.sort(key=lambda x: x.get("project_title","").casefold())
elif ARG_ORDERBY == 'index':
pass
elif ARG_DUE:
tasks.sort(key=lambda x: x['deadline'])
elif ARG_TODAY:
pass
elif ARG_TAG:
pass
else:
tasks.sort(key=lambda x: x['stop_date'] if x['stop_date'] is not None else float('-inf'), reverse=True)
return tasks[:QUERY_LIMIT]
def remove_emojis(input_string):
'''
Strips out emojis from the given string.
'''
cleaned_string = EMOJI_PATTERN.sub(r'', input_string)
cleaned_string = cleaned_string.strip()
return cleaned_string
def get_gcal_url(task_id, title):
'''
Generates URL for the given task that creates a GCal event, linking back to the task.
'''
url_base = "https://calendar.google.com/calendar/u/0/r/eventedit"
event_text = urllib.parse.quote_plus(title) # encode url
things_url = things.link(task_id)
event_details = f'<a href="{things_url}">{things_url}</a>'
event_details = urllib.parse.quote_plus(event_details) # encode url
url=f"{url_base}?text={event_text}&dates={GCAL_EVENT_DATES}&details={event_details}"
return url
def filter_area_title(area_title):
'''
Applies filters to the name of the area for output according to provided arguments.
'''
output = area_title
if CFG_REMOVE_AREA_EMOJIS:
output = remove_emojis(output)
return output
def filter_heading_title(heading_title):
'''
Applies filters to the name of the heading for output according to provided arguments.
'''
output = heading_title
if CFG_REMOVE_HEADING_EMOJIS:
output = remove_emojis(output)
return output
def filter_project_title(project_title):
'''
Applies filters to the name of the project for output according to provided arguments.
'''
output = project_title
if CFG_REMOVE_PROJECT_EMOJIS:
output = remove_emojis(output)
return output
def filter_task_title(task_title):
'''
Applies filters to the name of the task for output according to provided arguments.
'''
output = task_title
if CFG_REMOVE_TASK_EMOJIS:
output = remove_emojis(output)
return output
def filter_notes(notes):
'''
Filters notes by replacing non http links with markdown links.
'''
if notes:
non_http_pattern = r'\b((?!http)\w+://\S+)'
# Find all non-HTTP URI links in the text
non_http_links = re.findall(non_http_pattern, notes)
# Replace non-HTTP URI links with markdown format
for link in non_http_links:
# Extract the scheme from the URI
scheme = link.split("://")[0].capitalize()
markdown_link = f'[{scheme} Link]({link})'
notes = notes.replace(link, markdown_link)
return notes
# #############################################################################
# MAIN
# #############################################################################
if DEBUG: print("PARAMS:\n{}".format(args))
start_datetime = None
end_datetime = None
if ARG_RANGE is not None:
start_datetime, end_datetime = get_datetime_range(ARG_RANGE)
if start_datetime == None:
sys.stderr.write(f"things2md: Error: Invalid date range: {ARG_RANGE}")
exit(errno.EINVAL) # Invalid argument error code
if DEBUG: print(f"\nDATE RANGE:\n\"{ARG_RANGE}\" == {start_datetime} to {end_datetime}")
if DEBUG: print(f"\nTODAY: {TODAY}, TODAY_DATE: {TODAY_DATE}, TODAY_INT: {TODAY_INT}, TODAY_TIMESTAMP: {TODAY_TIMESTAMP}")
#
# Get Areas + Projects
#
# get area names
areas = dict()
area_results = query_areas()
for area in area_results:
areas[area['uuid']] = area
projects = {}
project_results = query_projects(start_datetime)
# format projects:
# store in associative array for easier reference later
if DEBUG: print(f"PROJECTS ({len(project_results)}):")
for project in project_results:
if DEBUG: print(dict(project))
projects[project['uuid']] = project
if ARG_PROJECT:
if ARG_PROJECT == project['title']:
ARG_PROJECT_UUID = project['uuid']
if ARG_PROJECT and ARG_PROJECT_UUID is None:
sys.stderr.write(f"things2md: Project not found: {ARG_PROJECT}")
exit(errno.EINVAL) # Invalid argument error code
#
# Get Tasks
#
task_results = {}
# don't need to get tasks if we're just getting the projects list
if not ARG_PROJECTS:
task_results = query_tasks(start_datetime, end_datetime)
else:
task_results = project_results
#
# Process All The Things
#
things_outputted = []
things_skipped = {}
header_area_previous = "PROJECTAREAPREVIOUS"
header_date_previous = ""
header_project_previous = "TASKPROJECTPREVIOUS"
if DEBUG: print(f"\nTASKS ({len(task_results)}):")
for task in task_results:
# skip this task if requested
if has_skip_tags(task):
things_skipped[task['uuid']] = dict(task)
if DEBUG: print(f"... SKIPPED (TAG): {dict(task)}")
continue
if DEBUG: print(dict(task))
#
# map Things data to template variables
#
vars = {}
notes_md = ""
task_md = ""
checklist_md = ""
project_md = ""
# these variables apply to both tasks and projects
vars['date'] = f"{datetime.fromisoformat(task['stop_date']).date()}" if task['stop_date'] is not None else ""
vars['date_sep'] = CFG_DATE_SEPARATOR if vars['date'] else ""
vars['deadline'] = task['deadline'] if task['deadline'] is not None else ""
vars['deadline_sep'] = CFG_DEADLINE_SEPARATOR if vars['deadline'] else ""
vars['gcal_url'] = get_gcal_url(task['uuid'], task['title'])
vars['notes'] = task['notes'] if task['notes'] else None
vars['url'] = things.link(task['uuid'])
vars['status'] = CFG_STATUS_SYMBOLS.get(task['status'], "")
# TODO: consider other tag list formats (e.g., for frontmatter lists)
vars['tags'] = "#" + " #".join(task['tags']) if 'tags' in task else ""
vars['title'] = task['title']
vars['uuid'] = task['uuid']
if task['type'] == "to-do":
vars['heading'] = task['heading_title'] if 'heading_title' in task else ""
vars['heading_sep'] = CFG_HEADING_SEPARATOR if vars['heading'] else ""
vars['project'] = projects[task['project']]['title'] if 'project' in task else ""
# if this task has a heading, we have to get the project name from the heading's task
if not vars['project'] and ('heading' in task) and (heading_task := things.tasks(uuid=task['heading'])):
vars['project'] = filter_project_title(heading_task['project_title'])
vars['project_sep'] = CFG_PROJECT_SEPARATOR if vars['project'] else ""
if not CFG_TEMPLATE.get('type'):
# attempt merge with template
try:
md_output = CFG_TEMPLATE.get("task").format(**vars)
except KeyError as e:
sys.stderr.write(f"things2md: Invalid task template variable: '{e.args[0]}'.")
exit(1)
# checklist
try:
if 'checklist' in task and task['checklist']:
for checklist_item in task.get('checklist'):
checklist_item_vars = {}
if CFG_REMOVE_EMPTY_CHECKLIST_ITEMS and not checklist_item['title']:
continue
checklist_item_vars['title'] = checklist_item['title']
checklist_item_vars['status'] = CFG_STATUS_SYMBOLS.get(checklist_item['status'], "")
if checklist_md: checklist_md += "\n"
if CFG_TEMPLATE.get("checklist_item"):
checklist_md += CFG_TEMPLATE.get("checklist_item").format(**checklist_item_vars)
vars['checklist'] = checklist_md
except KeyError as e:
sys.stderr.write(f"things2md: Invalid template variable: '{e.args[0]}'.")
exit(1)
elif task['type'] == "project":
# skip if project's area has SKIP_TAGS
if 'area' in task:
if has_skip_tags(task):
things_skipped[task['uuid']] = dict(task)
if DEBUG: print(f"... SKIPPED (AREA TAG): {dict(task)}")
continue
vars['area'] = task['area_title'] if 'area_title' in task else ""
vars['area_sep'] = CFG_AREA_SEPARATOR if vars['area'] else ""
vars['title'] = task['title']
# attempt merge with template
try:
md_output = CFG_TEMPLATE.get("project").format(**vars)
except KeyError as e:
sys.stderr.write(f"things2md: Invalid project template variable: '{e.args[0]}'.")
exit(1)
elif task['type'] == "heading":
# TODO: do something for --project output
pass
else:
# areas?
sys.stderr.write(f"things2md: DEBUG: UNHANDLED TYPE: {task['type']}")
#
# prepare groupby headers
#
if ARG_GROUPBY == "date" and CFG_TEMPLATE.get("groupby_date"):
if vars['date'] != header_date_previous:
try:
print(CFG_TEMPLATE.get("groupby_date").format(**vars))
except KeyError as e:
sys.stderr.write(f"things2md: Invalid groupby_date template variable: '{e.args[0]}'.")
exit(1)
header_date_previous = vars['date']
elif ARG_GROUPBY == "project" and CFG_TEMPLATE.get("groupby_project"):
if 'project' in vars and vars['project'] and vars['project'] != header_project_previous:
try:
print(CFG_TEMPLATE.get("groupby_project").format(**vars))
except KeyError as e:
sys.stderr.write(f"things2md: Invalid groupby_project template variable: '{e.args[0]}'.")
exit(1)
header_project_previous = vars['project']
elif ARG_GROUPBY == "area" and CFG_TEMPLATE.get("groupby_area"):
if 'area' in vars and vars['area'] != header_area_previous:
try:
print(CFG_TEMPLATE.get("groupby_area").format(**vars))
except KeyError as e:
sys.stderr.write(f"things2md: Invalid groupby_area template variable: '{e.args[0]}'.")
exit(1)
header_area_previous = vars['area']
#
# output
#
# TODO: move markdown_note type into global enum
if CFG_TEMPLATE.get('type') == 'markdown_note':
# markdown_note
try:
md_output = CFG_TEMPLATE.get("title").format(**vars)
md_output += CFG_TEMPLATE.get("body").format(**vars)
except KeyError as e:
sys.stderr.write(f"things2md: Invalid markdown_note body template variable: '{e.args[0]}'.")
exit(1)
print(md_output)
else:
# prepare task + project output
md_output = md_output.replace("[[]]", "") # remove empty wikilinks
md_output = md_output.strip() # remove spacing around output
md_output = re.sub(r'\s+', ' ', md_output) # reduce spaces within output
# prepare task/project notes output (assuming template is non-empty)
if vars['notes'] and CFG_TEMPLATE.get("notes"):
try:
notes_md = CFG_TEMPLATE.get("notes").format(**vars)
except KeyError as e:
sys.stderr.write(f"things2md: Invalid notes template variable: '{e.args[0]}'.")
exit(1)
print(md_output)
if notes_md: print(indent_string(notes_md))
if checklist_md: print(indent_string(checklist_md))
things_outputted.append(task)
#
# Summarize
#
if DEBUG:
print(f"\nTHINGS OUTPUT ({len(things_outputted)}):\n{things_outputted}")
print(f"\nSKIPPED TASKS ({len(things_skipped)}):\n{things_skipped}")
if len(things_skipped) > 0:
sys.stderr.write(f"things2md: Skipped {len(things_skipped)} tasks or projects with specified skip_tags\n")
if len(things_outputted) == 0:
sys.stderr.write(f"things2md: No results met the given criteria!\n")
exit(0)
if DEBUG: print("\nDONE!")