This repository was archived by the owner on Jul 17, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathlater
More file actions
executable file
·406 lines (352 loc) · 10 KB
/
Copy pathlater
File metadata and controls
executable file
·406 lines (352 loc) · 10 KB
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
#!/usr/bin/env python
import os
import sys
import getpass
import imp
from uuid import uuid4
from glob import iglob
from datetime import datetime
from tempfile import mkstemp
_SCRIPT_DIR = "/".join(sys.argv[0].split("/")[:-1])
_PLUGINS_DIR = _SCRIPT_DIR + "/plugins"
_CONFIG_FILE_NAME = "config"
_DATA_DIR = ".later"
_CONFIG={
"default_piority": 2,
"username": "ongspxm"
}
def error(msg):
print "Error:", msg
exit(2)
class Hooks(object):
def __getitem__(self, key):
return self.__dict__[key]
def __setitem__(self, key, value):
self.__dict__[key] = value
def get(self, key, default=None):
return self.__dict__.get(key, default)
_HOOKS=Hooks()
def hooked(fun):
"""Decorator: make function available via _HOOKS"""
_HOOKS[fun.__name__] = fun
def find_config():
"""Find config file starting from current directory upwards."""
current = os.path.abspath(os.path.curdir)
trash = None
while len(current) > 1:
data = os.path.join(current, _DATA_DIR)
config = os.path.join(data, _CONFIG_FILE_NAME)
if os.path.isdir(data) and os.path.isfile(config):
return config
current, trash = os.path.split(current)
return os.path.join(_SCRIPT_DIR, _CONFIG_FILE_NAME)
@hooked
def guess_username():
# try user login name
return getpass.getuser()
def load_plugins():
load_dir_plugins(_CONFIG.get("data_dir"))
load_dir_plugins(_PLUGINS_DIR)
def load_dir_plugins(parentDir):
if not parentDir: return
for path in iglob(os.path.join(parentDir, "*.py")):
name = os.path.basename(path)[:-3]
mod = imp.load_source("plugin:"+name, path)
mod.plugin_init(_HOOKS)
def load_config():
"""Load config from file"""
global _CONFIG
path = find_config()
if path and os.path.isfile(path):
for line in open(path):
i = line.find(": ")
if i<0: continue
_CONFIG[line[:i]] = line[i+2:-1]
_CONFIG["data_dir"] = os.path.dirname(path)
load_plugins()
if not _CONFIG.get("username", None):
_CONFIG["username"] = _HOOKS.guess_username()
def store_config(path):
"""Store config to file"""
fh = open(path, 'w')
for key,val in _CONFIG.items():
if key == "data_dir": continue
fh.write("%s: %s\n" % (key,val))
fh.close()
_PROPERTY_CHARS="abcdefghijklmnopqrstuvwxyz_"
def is_property_line(line):
for i,c in enumerate(line):
if not c in _PROPERTY_CHARS:
if i > 0 and c == ":":
return True
else:
return False
return False
def load_lfile(path):
fh = open(path)
props = dict()
line = fh.readline()
while is_property_line(line):
i = line.index(":")
props[line[:i]] = line[i+1:].strip()
line = fh.readline()
msg = ""
while line:
msg += line
line = fh.readline()
return msg.strip(), props
def store_lfile(path, msg, props):
fh = open(path, 'w')
for key,val in props.items():
if not val: continue
fh.write("%s: %s\n" % (key,val))
fh.write("\n")
fh.write(msg)
fh.write("\n")
fh.close()
def serialize_datetime(dt):
return dt.strftime("%Y-%m-%dT%H:%M:%S%z")
class Issue:
def __init__(self, guid=None, properties=dict(), message="Something is rotten ..."):
self.properties = dict(
status="reported",
#priority=_CONFIG["default_priority"],
responsible="nobody",
created=serialize_datetime(datetime.utcnow()),
reporter=_CONFIG['username'])
for k,v in properties.items():
self.properties[k] = v
self.msg = message
self.guid = guid or str(uuid4())
def shortString(self):
"""One line representation"""
i = self.msg.find("\n")
if i < 0:
i = None
string = self.msg[:i]
status = self.properties.get("status", "?")
return " %s %-50s %s"%(self.guid[:8], string, status)
def longString(self):
"""Multi line representation"""
string = "%s\n" % (self.guid)
for k,v in self.properties.items():
string += "%s: %s\n" % (k,v)
string += "\n" + self.msg
return string
# explicitly not @hooked, since backend specific
def be_gen_path(guid):
return os.path.join(_CONFIG.get("data_dir", ""), guid + ".issue")
@hooked
def be_all_guids():
for path in iglob(be_gen_path("*")):
yield os.path.basename(path)[:-6]
@hooked
def be_complete_guid(halfguid):
if len(halfguid) == 36:
return halfguid # already complete
found = None
for guid in _HOOKS.be_all_guids():
if guid.startswith(halfguid):
if found:
print "The guid part is ambiguous:"
print guid, "or"
print found, "?"
return
else:
found = guid
return found
@hooked
def be_store_issue(issue):
issue.properties["modified"] = serialize_datetime(datetime.utcnow())
store_lfile(be_gen_path(issue.guid), issue.msg, issue.properties)
@hooked
def be_load_issue(guid):
assert len(guid) == 36
path = be_gen_path(guid)
m, p = load_lfile(path)
return Issue(guid, p, m)
@hooked
def be_delete_issue(guid):
assert len(guid) == 36
path = be_gen_path(guid)
os.remove(path)
@hooked
def be_get_data_dir():
return _CONFIG.get("data_dir", "")
# explicitly not @hooked, since now plugins available at this point
def cmd_init(args):
"""Create a new data directory for issues in the current dir."""
try:
os.mkdir(_DATA_DIR)
except OSError, e:
error("Could not create data directory: " + str(e))
store_config(os.path.join(_DATA_DIR, _CONFIG_FILE_NAME))
@hooked
def cmd_add(args):
"""Quickly add a new issue by specifying only a message."""
issue = Issue()
issue.msg = args.pop(0)
_HOOKS.be_store_issue(issue)
print "issue stored as", issue.guid
def gen_matcher(args):
"""Generate an issue matcher from command line arguments"""
if not args:
def open_matcher(issue):
"""Default: only list non closed issues"""
return issue.properties["status"] != "closed"
return open_matcher
elif len(args) > 1:
parts = [gen_matcher([arg]) for arg in args]
def matcher_and(issue):
"""Every sub matcher must return True"""
for p in parts:
if not p(issue):
return False
return True
return matcher_and
else:
assert len(args) == 1
pattern = args[0]
if "!=" in pattern:
key, value = pattern.split("!=")
def except_matcher(issue):
return issue.properties.get(key, value) != value
return except_matcher
elif "=" in pattern:
key, value = pattern.split("=")
def matcher(issue):
return issue.properties.get(key, None) == value
return matcher
error("Can not parse pattern: " + " ".join(args))
@hooked
def cmd_list(args):
"""By default lists all issues, which are not closed.
Search terms can be given, then only issues where all search terms match the issue properties.
Examples:
- `list status=closed` shows all issues with status closed.
- `list reporter!=beza1e1 status=confirmed` shows all confirmed issues not reported by beza1e1.
- `list bugs` shows issues beginning with "bug:"
"""
issues = (_HOOKS.be_load_issue(guid) for guid in _HOOKS.be_all_guids())
# Filtering for bugs
if args.count('bugs'):
issues = (iss for iss in issues if iss.msg[:3]=="bug")
args.remove('bugs')
matcher = gen_matcher(args)
for issue in issues:
# if args specified search in properties,
# otherwise list all issues not closed.
if matcher(issue):
print issue.shortString()
@hooked
def cmd_edit(args):
"""Edit a specific issue.
If none specified a new issue is generated (like add does.)"""
try:
guid = _HOOKS.be_complete_guid(args[0])
if not guid:
return
except IndexError:
guid = None
editor = os.getenv("EDITOR")
if not editor:
error("no $EDITOR environment variable")
issue = _HOOKS.be_load_issue(guid)
fh, filename = mkstemp(".issue")
store_lfile(filename, issue.msg, issue.properties)
cmd = "%s %s" % (editor, filename)
os.system(cmd)
m,p = load_lfile(filename)
issue = Issue(issue.guid, p, m)
_HOOKS.be_store_issue(issue) # updates modified properties
if not guid: # generated a new issue
print "Issue stored as", issue.guid
@hooked
def cmd_show(args):
"""Show a specific issue."""
if not args:
error("need guid argument")
guid = _HOOKS.be_complete_guid(args[0])
if not guid:
return
issue = _HOOKS.be_load_issue(guid)
print issue.longString()
@hooked
def set_status(guid, status):
"""Change status of a specific issue"""
guid = _HOOKS.be_complete_guid(guid)
if not guid:
return
issue = _HOOKS.be_load_issue(guid)
issue.properties["status"] = status
_HOOKS.be_store_issue(issue)
@hooked
def cmd_close(args):
"""Set status of a specific issue to 'closed'"""
if not args:
error("need guid argument")
_HOOKS.set_status(args[0], "closed")
@hooked
def cmd_confirm(args):
"""Set status of a specific issue to 'confirmed'"""
if not args:
error("need guid argument")
_HOOKS.set_status(args[0], "confirmed")
@hooked
def cmd_assign(args):
"""Assign an issue to someone"""
if not args or len(args) < 2:
error("need guid and assignee")
guid = _HOOKS.be_complete_guid(args[0])
issue = _HOOKS.be_load_issue(guid)
issue.properties["responsible"] = " ".join(args[1:])
_HOOKS.be_store_issue(issue)
_USAGE = """\
A command-line issue tracker for a lazy developer.
Usage is "%s <cmd> ...", where <cmd> is one of
init create dir in current directory
add "msg" report new issue with title "msg"
edit <guid> edit issue with the given guid
close <guid> set status to closed
confirm <guid> set status to confirmed
assign <guid> <developer> set responsible to developer
list show all issues in short
show <guid> show issue <guid> completely
help <cmd> shows documentation for <cmd>
PLUGINS
=======
schedule calculates/show deadlines
htmlreport generate html report
delete <guid> delete issue <guid>
delete-closed delete all closed issues
list-subdirs show issue list of subdirs
revision manage revisions
""" % (sys.argv[0])
@hooked
def cmd_help(args=[]):
"""Provides general usage and help for every command."""
if len(args) == 0:
print _USAGE
return
fun = _HOOKS.get("cmd_" + args[0], None)
if not fun:
print "Can not help you with that. Typo?"
return
# print docstring as help for a specific command
print fun.__doc__
def main():
if len(sys.argv) <= 1:
print _USAGE
return
if sys.argv[1] == "init":
cmd_init(sys.argv[2:])
return
load_config()
# e.g. "add" leads to calling "cmd_add"
fun = _HOOKS.get("cmd_" + sys.argv[1], None)
if not fun:
return _HOOKS.cmd_help()
print
fun(sys.argv[2:])
if __name__ == "__main__":
main()