-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtaskopen
executable file
·252 lines (198 loc) · 6.8 KB
/
taskopen
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
#!/usr/bin/env python3
"""
better replacement for the few functions of 'taskopen' that we use
- taskopen: find urls in annotations, offers selection menu, spawns $BROWSER
- tasknote: displays the .rst file attached to task, or runs $EDITOR
"""
__url__ = 'https://github.com/smemsh/.task'
__author__ = 'Scott Mcdermott <scott@smemsh.net>'
__license__ = 'GPL-2.0'
import argparse
from sys import exit, hexversion
if hexversion < 0x030900f0: exit("minpython: %s" % hexversion)
from sys import argv, stdin, stdout, stderr
from tty import setraw
from json import loads, JSONDecodeError
from string import digits, ascii_letters as letters
from signal import SIGTSTP
from shutil import which
from termios import tcgetattr, tcsetattr, TCSADRAIN
from textwrap import fill
from traceback import print_exc
from subprocess import check_output, CalledProcessError
from urllib.parse import urlparse
from os.path import basename
from os import (
getpid, kill,
spawnl, P_WAIT,
getenv, unsetenv,
EX_OK as EXIT_SUCCESS,
EX_SOFTWARE as EXIT_FAILURE,
)
# the urls are embedded in annotations. following characters are
# stripped from each end of a note's words before testing whether a url
#
STRIPCHARS='().?,;!'
###
def err(*args, **kwargs):
print(*args, file=stderr, **kwargs)
def bomb(*args, **kwargs):
err(*args, **kwargs)
exit(EXIT_FAILURE)
def exe(cmd):
cmdargs = cmd.split()
cmd = cmdargs[0]
cmdargs[0] = which(cmd) or cmd
if not cmd: bomb(f"cannot find command {cmdargs[0]}")
return check_output(cmdargs).decode()
def spawn(evar, default, arg):
app = getenv(evar, default)
cmd = which(app)
spawnl(P_WAIT, cmd, basename(app), arg)
###
def process_args():
global args
def addopt(p, flagchar, longopt, help=None, /, **kwargs):
options = list(("-%s --%s" % (flagchar, longopt)).split())
p.add_argument(*options, help=help, **kwargs)
def addarg(p, vname, vdesc, help=None, /, **kwargs):
p.add_argument(vname, metavar=vdesc, help=help, **kwargs)
def addflag(*args, **kwargs):
addopt(*args, action='store_true', **kwargs)
p = argparse.ArgumentParser(
prog = invname,
description = __doc__.strip(),
allow_abbrev = False,
formatter_class = argparse.RawTextHelpFormatter,
)
addarg(p, 'task', 'taskid',
'unique lookup string for "taskuuid" command',
nargs='?')
if invname == 'tasknote':
addflag(p, 'e', 'edit', 'open the tasknote in $EDITOR')
args, left = p.parse_known_args(args)
if len(left):
bomb("supply just one arg, should lookup to a unique task")
if not args.task:
args.task = exe("tasknow").split()[0]
return args.task
def get_task(task):
try:
uuids = exe(f"taskuuid {task}").split()
if len(uuids) != 1:
bomb("error getting a single uuid")
uuid = uuids[0]
task = exe(f"task {uuid} export")
task = loads(task)
if not len(task):
bomb("no matching task")
except CalledProcessError: bomb("task lookup failed")
except (JSONDecodeError, ValueError): bomb("bad json decode")
return task[0]
def tasknote(task):
global args
uuid = task['uuid']
notefile = f"{getenv('HOME')}/.task/notes/{uuid}.rst" # todo: rcfile
if args.edit:
spawn('EDITOR', 'vi', notefile)
# todo: if exists and didn't before, add uda
else:
try: f = open(notefile)
except FileNotFoundError: bomb(f"note {notefile} dne")
except PermissionError: bomb(f"note {notefile} not readable")
stdout.write(''.join(f.readlines()))
def taskopen(task):
global pid
charmap = digits + letters
idxmap = {charmap[i]: i for i in range(len(charmap))}
def getchar():
fd = stdin.fileno()
tattrs = tcgetattr(fd)
setraw(fd)
c = stdin.buffer.raw.read(1).decode(stdin.encoding)
tcsetattr(fd, TCSADRAIN, tattrs)
return c
anns = [a['description'] for a in task.get('annotations', [])]
nanns = len(anns)
links = []
matchn = 0
for i in range(nanns):
ann = anns[i]
words = ann.split()
matched = False
for j in range(len(words)):
url = urlparse(words[j].strip(STRIPCHARS))
if url.scheme.startswith('http'):
url = url.geturl()
words[j] = f"({charmap[matchn]}) {url} <--"
links.append(url)
matchn += 1
matched = True
if matched:
fillargs = {
'subsequent_indent': 4 * "\x20",
'fix_sentence_endings': True,
'break_long_words': False,
'break_on_hyphens': False,
'width': 78,
}
print(fill("\x20".join(words), **fillargs))
if matchn:
if matchn == 1: matchrange = charmap[0]
else: matchrange = f"{charmap[0]}-{charmap[matchn-1]}"
while True:
print(f"\nselect url ({matchrange})? ", end='')
stdout.flush()
c = getchar(); print(c)
if c == '\x03': bomb("interrupted") # ETX, ^c
elif c == '\x04': return # EOT, ^d
elif c == '\x0a': idx = 0; break # LF, ^j
elif c == '\x0d': idx = 0; break # CR, enter
elif c == '\x1a': kill(pid, SIGTSTP); continue # SUB, ^z
elif c in charmap:
idx = idxmap[c]
if idx < matchn:
break
else:
print(f"got char {hex(ord(c))}, try again")
url = links[idx]
print(f"opening {url} ...")
spawn('BROWSER', 'open', url)
else:
if nanns: print("no urls")
else: print("no annotations")
###
def main():
if debug == 1: breakpoint()
task = process_args()
task = get_task(task)
try: subprogram = globals()[invname]
except (KeyError, TypeError):
bomb(f"unimplemented command '{invname}'")
return subprogram(task)
###
if __name__ == "__main__":
invname = basename(argv[0])
args = argv[1:]
pid = getpid()
from bdb import BdbQuit
if debug := int(getenv('DEBUG') or 0):
import pdb
from pprint import pp
err('debug: enabled')
unsetenv('DEBUG') # otherwise forked children hang
try: main()
except BdbQuit: bomb("debug: stop")
except SystemExit: raise
except KeyboardInterrupt: bomb("interrupted")
except:
print_exc(file=stderr)
if debug: pdb.post_mortem()
else: bomb("aborting...")
finally: # cpython bug 55589
try: stdout.flush()
finally:
try: stdout.close()
finally:
try: stderr.flush()
finally: stderr.close()