-
Notifications
You must be signed in to change notification settings - Fork 0
/
tallytime
executable file
·480 lines (431 loc) · 16 KB
/
tallytime
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
#!/usr/bin/env python3
import os
import os.path
import sys
import time
import re
from optparse import OptionParser
from configparser import ConfigParser
from pathlib import Path
version = "%prog Version 1.0"
usage = "usage: %prog [options] time log message"
description = (
"A stupidly simple time tracker. Supports concurrent marked "
"segments using leading punctuation on a word ('started @work "
"on %task'), comments with a stand-alone leading punctuation in "
"the comment-line ('% comment only seen in raw segment')."
)
epilog = (
"The time log message can be a single argument or can be multiple "
"arguments. There is no support for an on-going task. You start one "
"task, then start a new task. The time associated with marks is "
"tracked by summing each of the log entries with the same mark. You "
"can have multiple marks in the same log entry, and this is the only "
"supported way to track multiple concurrent tasks."
)
mark_re = re.compile(r"(?:^|(?<=\s))(?:[^\w\s]|_)[\w](?:[^\s]*[\w])?(?:$|(?=\s))")
comment_re = re.compile(r"^\W+ ")
all_segments = ("raw", "comment", "mark", "last", "rawraw", "secs")
default_segments = "raw,mark,last"
default_home = "~/.tallytime"
default_log_filename = "time.log"
default_report_filename = "report.txt"
default_config_filename = "config.ini"
default_verbose = 1
parser = OptionParser(usage=usage, version=version,
description=description, epilog=epilog)
parser.add_option("-v", "--verbose",
action="count", default=0,
help="display output [default]")
parser.add_option("-q", "--quiet",
action="count", default=0,
help="be less verbose")
parser.add_option("--draft", action="store_true", default=False,
help="dump a draft of the report to stdout")
parser.add_option("--tally", default=False, action="store_true",
help="Instead of logging a time entry, generate the report.")
parser.add_option("--last", default=False, action="store_true",
help="Print the last-entered log and current time elapsed.")
parser.add_option("--home", metavar="DIR",
help="Set the default configuration directory. " +
"[default: {}".format(default_home))
parser.add_option("-s", "--segments",
default=[], action="append",
help="one or more output segments: raw, comment, mark, "
"secs, last, all, none, (and any can be preceded "
"with 'no' to disable) "
+ "[default: %s]" % default_segments)
parser.add_option("--undo", action="store_true", default=False,
help="Undo the previous tally.")
parser.add_option("--fake", metavar="TIMESPEC",
help="Produce timelog output for {YYYY-{MM-{DD'T'}}}HH{:MM{:SS}}")
parser.add_option("--write-config", action="store_true", default=False,
help="Write the current configuration to the configuration "
"file.")
def verbose(s, nonl=False):
global _verbose
if _verbose > 0:
if nonl:
print (s,end="")
else:
print (s)
def debug(i, s, nonl=False):
global _verbose
if _verbose > i:
if nonl:
print (s,end="")
else:
print (s)
def print_last_line(time_log, timen = None):
blocksize = 65536
last_line = None
if timen is None:
timen = time.time()
try:
approx_size = 0
if time_log.exists():
approx_size = time_log.stat().st_size
if approx_size == 0:
last_line = None
elif approx_size <= blocksize:
log_tmp = time_log.read_text().splitlines()
last_line = log_tmp[-1]
else:
start = approx_size - blocksize
with time_log.open("rt") as infile:
infile.seek(start)
last_line = infile.read(blocksize).splitlines()[-1]
except IOError:
timen = float("%.0f" % timen)
last_line = "%.0f - - - -" % timen
if last_line is not None:
if len(last_line) > 0 and last_line[-1] in '\r\n':
last_line = last_line[:-1]
if len(last_line) > 0 and last_line[-1] in '\r\n':
last_line = last_line[:-1]
subs = last_line.split(" ", 4)
secs = float(subs[0])
phours = secs / 60.0 / 60.0
chours = timen / 60.0 / 60.0
hours = chours - phours
last_line = "[%s] %s / %.4f min" % (" ".join(subs[1:3]),
subs[-1], hours * 60.0)
s = "Last entry: %s" % (last_line,)
print (s)
return
class TimeReport(object):
def __init__(self):
pass
def __str__(self):
pass
def store_all_raw(self, duration, line, comment=False):
self.store_raw(line)
self.store_punch(duration, line, comment=comment)
def store_raw(self, line):
pass
def store_punch(self, duration, line, comment=False):
pass
def store_message(self, line):
pass
def store_mark(self, mark, duration=0.0):
pass
def store_last(self, message):
pass
def log_time(time_log, args, segments, opts):
last_mode = segments.get("last")
last_line = None
timen = time.time()
times = time.localtime(timen)
if opts.fake:
fakeit = opts.fake.replace("-","").replace(":","")
fakeit = list(fakeit.replace("T", " ").split())
if len(fakeit) == 1 or (len(fakeit) == 2 and not fakeit):
fakeit.insert(0, time.strftime("%Y%m%d", times))
elif len(fakeit[0]) == 2:
fakeit[0] = time.strftime("%Y%m", times) + fakeit[0]
elif len(fakeit[0]) == 4:
fakeit[0] = time.strftime("%Y", times) + fakeit[0]
if len(fakeit[1]) < 6:
fakeit[1] = fakeit[1] + ("0" * (6 - len(fakeit[1])))
times = time.strptime(" ".join(fakeit), "%Y%m%d %H%M%S")
timen = time.mktime(times)
s = "%.0f %s - %s" % (timen, time.strftime("%Y-%m-%d %H:%M:%S", times), " ".join(args));
verbose(s)
if last_mode:
print_last_line(time_log, timen = timen)
with time_log.open("at") as outf:
outf.write(s + "\n")
return 0
def hours_str(label, d):
s = "%s Sections:\n" % (label, )
keylist = list(d.keys())
keylist.sort()
for k in keylist:
s = s + " %s: %.4f hours / %.4f min\n" % (k, d[k], d[k] * 60.0)
return s
def tally_time(timelog_lines, timereport, timetally, marktally, segments,
had_args):
hours_total = 0
starthours = None
raw_mode = None
last_mode = segments.get("last", False)
secs_mode = segments.get("secs", False)
if segments.get("rawraw", False):
raw_mode = "rawraw"
elif segments.get("raw", False):
raw_mode = "raw"
global mark_re
global comment_re
last_line = None
last_whole_line = None
for line in timelog_lines:
if len(line) > 0 and line[-1] in '\r\n':
line = line[:-1]
if len(line) > 0 and line[-1] in '\r\n':
line = line[:-1]
if len(line) == 0:
continue
subs = line.split(" ", 4)
if comment_re.match(subs[-1]):
if raw_mode == "rawraw":
s = " ".join(subs)
else:
s = " [%s %s] %s" % (subs[1], subs[2], subs[-1])
if raw_mode is not None:
if timereport is not None:
timereport.write(s + "\n")
verbose(s)
else:
debug(2, s)
continue
secs = float(subs[0])
phours = secs / 60.0 / 60.0
if starthours == None:
s = "Starting time: %s" % " ".join(subs[1:3])
if timereport is not None:
timereport.write(s + "\n")
verbose(s)
hours = 0.0
else:
hours = phours - starthours
hours_total += hours
if raw_mode == "rawraw":
s = " ".join(subs)
elif not secs_mode:
s = "%.4f min [%s %s] %s" % (hours * 60.0, subs[1],
subs[2], subs[-1])
else:
s = "%.4f min (%s) [%s %s] %s" % (hours * 60.0, subs[0], subs[1],
subs[2], subs[-1])
if last_whole_line is not None:
lastcomment = last_whole_line[-1]
for mark in mark_re.findall(lastcomment):
marktally[mark] = marktally.get(mark, 0) + hours
timetally[lastcomment] = timetally.get(lastcomment, 0) + hours
last_line = "[%s] %s / %.4f min" % (" ".join(last_whole_line[1:3]),
lastcomment, hours * 60.0)
last_whole_line = subs
if raw_mode in ("raw", "rawraw"):
if timereport is not None:
timereport.write(s + "\n")
verbose(s)
else:
debug(2, s)
starthours = phours
if not had_args:
s = "Last entry: %s" % (last_line,)
if last_mode:
if timereport is not None:
timereport.write(s + "\n")
verbose(s)
else:
debug(2, s)
return hours_total
def segments_to_unicode(segments):
ret = []
for s in segments:
if segments.get(s):
ret.append(s)
return ",".join(ret)
def parse_segments(segments, segs):
if segs is None:
return segments
if isinstance(segs, str):
segs = (segs, )
for sEarly in segs:
for s in sEarly.split(","):
s = s.strip()
if s == "all" or s == "nonone":
for sLate in all_segments:
segments[sLate] = True
elif s == "none" or s == "noall":
for sLate in all_segments:
segments[sLate] = False
elif s.startswith("no"):
s = s[2:]
if s[0] == '-': s = s[1:]
segments[s] = False
else:
segments[s] = True
for s in segments:
if s not in all_segments:
if s is not None and s != "":
print ("Error: unknown segment %s" % s)
return 1
for s in all_segments:
if s not in segments:
segments[s] = False
return segments
def join_config_options(config, options):
global default_segments
global all_segments
global default_log_filename
global default_report_filename
global default_verbose
global _verbose
ret = {}
segments = {}
parse_segments(segments, default_segments)
if config.has_section("tallytime"):
for option in config.options("tallytime"):
if option == "segments":
parse_segments(segments, config.get("tallytime", option))
else:
ret[option] = config.get("tallytime", option)
if options.tally:
if config.has_section("report"):
for option in config.options("report"):
if option == "segments":
parse_segments(segments, config.get("report", option))
else:
ret[option] = config.get("report", option)
elif options.draft:
if config.has_section("draft"):
for option in config.options("draft"):
if option == "segments":
parse_segments(segments, config.get("draft", option))
else:
ret[option] = config.get("draft", option)
else:
if config.has_section("log"):
for option in config.options("log"):
if option == "segments":
parse_segments(segments, config.get("log", option))
else:
ret[option] = config.get("log", option)
parse_segments(segments, options.segments)
ret["segments"] = segments
ret["log_filename"] = ret.get("log_filename", default_log_filename)
ret["report_filename"] = ret.get("report_filename", default_report_filename)
if "verbose" in ret:
ret["verbose"] = int(ret.get("verbose"))
else:
ret["verbose"] = default_verbose
if options.verbose:
ret["verbose"] = ret["verbose"] + options.verbose - options.quiet
_verbose = ret["verbose"]
return ret
def write_config(config, real_config, config_name, options):
section = "log"
if options.tally:
section="report"
elif options.draft:
section="draft"
if not config.has_section(section):
config.add_section(section)
for key in real_config:
if key == "segments":
config.set(section, key, segments_to_unicode(real_config.get(key)))
else:
config.set(section, key, str(real_config.get(key)))
if not config.has_section("tallytime"):
config.add_section("tallytime")
with config_name.open("wt") as outf:
config.write(outf)
def main(argv):
global _verbose
options, args = parser.parse_args(argv)
config_home = os.environ.get("TALLYTIME_HOME", options.home)
if config_home == None or config_conf == "":
config_home = default_home
config_home = Path(config_home).expanduser()
config_name = config_home / default_config_filename
config = ConfigParser()
config.read(str(config_name))
real_config = join_config_options(config, options)
segments = real_config.get("segments")
if options.write_config:
config_name.parent.mkdir(parents=True, exist_ok=True)
write_config(config, real_config, config_name, options)
time_log = config_home / real_config.get("log_filename")
undo_log = time_log.with_suffix(".undo")
ret = 0
if len(args) > 0:
time_log.parent.mkdir(parents=True, exist_ok=True)
ret = log_time(time_log, args, segments, options)
if not time_log.exists():
try:
with time_log.open("at") as tfile:
pass
except IOError:
print ("Error: Failed to open", time_log)
sys.exit(1)
if options.draft:
if _verbose == 0:
_verbose = 1
verbose("- - - DRAFT MODE - - - - DRAFT MODE - - -")
elif options.last:
return print_last_line(time_log)
elif options.undo:
if time_log.exists():
time_log.write_text(undo_log.read_text())
return 0
print ("Error: Can't automatically undo if new times have been added.")
return 1
elif not options.tally:
return ret
report_log = config_home / real_config.get("report_filename")
timereport = None
if not options.draft:
report_log.parent.mkdir(parents=True, exist_ok=True)
try:
timereport = report_log.open("r+t")
timereport.seek(0, os.SEEK_END)
timereport.write("----\n\n")
except IOError:
timereport = report_log.open("at")
timelog_text = time_log.read_text()
undo_log.write_text(timelog_text)
timelog_lines = timelog_text.splitlines()
if options.draft and not args:
timelog_lines.append("%.0f - - - -\n" % time.time())
timetally = {}
marktally = {}
hours_total = tally_time(timelog_lines, timereport, timetally, marktally,
segments, len(args) > 0)
if segments.get("raw") or segments.get("rawraw"):
s = "Time total: %.4f hours (%.4f min)" % (hours_total, hours_total * 60.0) + "\n"
verbose(s, nonl=True)
if timereport is not None:
timereport.write(s)
if segments.get("comment"):
s = hours_str("\nComment", timetally)
verbose(s, nonl=True)
if timereport is not None:
timereport.write(s)
if segments.get("mark"):
if marktally:
s = hours_str("\nMark", marktally)
else:
s = "\nNo marks found"
verbose(s, nonl=True)
if timereport is not None:
timereport.write(s)
if timereport is not None:
timereport.write("\n")
if options.tally:
if timereport is not None:
timereport.close()
time_log.unlink()
if __name__ == "__main__":
main(sys.argv[1:])