-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathon-modify_timelog.py
More file actions
executable file
·260 lines (210 loc) · 8.86 KB
/
on-modify_timelog.py
File metadata and controls
executable file
·260 lines (210 loc) · 8.86 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
#!/usr/bin/env python3
import os as _os_timing, time as _time_module
if _os_timing.environ.get('TW_TIMING'):
import atexit as _atexit
_t0 = _time_module.perf_counter()
def _report_timing(_f=__file__):
elapsed = (_time_module.perf_counter() - _t0) * 1000
import os.path as _osp
print(f"[timing] {_osp.basename(_f)}: {elapsed:.1f}ms", file=__import__('sys').stderr)
_atexit.register(_report_timing)
"""
on-modify_timelog.py — Write hledger timeclock entries on task start/stop
When a task is started or stopped, writes a timeclock i/o pair to the
configured file, queryable with hledger or ledger for time reports.
If a manual 't in' session is open when a task stops, the hook pauses it
(closes at task-start, writes task entry, reopens at task-stop) to keep
the timeclock file valid and avoid overlapping sessions.
Config: ~/.task/config/timelog.rc
timelog.file = ~/.task/time/tw.timeclock
Backdate: add a plain-number annotation when starting/stopping to backdate:
task <id> start; task <id> annotate 15 → start recorded 15 minutes ago
task <id> stop; task <id> annotate 10 → stop recorded 10 minutes ago
Install: ~/.task/hooks/on-modify_timelog.py
Version: 1.1.0
"""
# ============================================================================
# DEBUG VERSION - Auto-generated by make-awesome.py
# ============================================================================
import os
import sys
from pathlib import Path
from datetime import datetime
import json
import re
import calendar
# Debug configuration (default 0, triggered by tw --debug=2)
DEBUG_MODE = 0
tw_debug_level = os.environ.get('TW_DEBUG', '0')
try:
tw_debug_level = int(tw_debug_level)
except ValueError:
tw_debug_level = 0
debug_active = DEBUG_MODE == 1 or tw_debug_level >= 2
def get_log_dir():
cwd = Path.cwd()
if (cwd / '.git').exists():
log_dir = cwd / 'logs' / 'debug'
else:
log_dir = Path.home() / '.task' / 'logs' / 'debug'
log_dir.mkdir(parents=True, exist_ok=True)
return log_dir
if debug_active:
DEBUG_LOG_DIR = get_log_dir()
DEBUG_SESSION_ID = datetime.now().strftime("%Y%m%d_%H%M%S")
try:
script_name = Path(__file__).stem
except:
script_name = Path(sys.argv[0]).stem if sys.argv else "script"
DEBUG_LOG_FILE = DEBUG_LOG_DIR / f"{script_name}_debug_{DEBUG_SESSION_ID}.log"
def debug_log(message, level=1):
if debug_active and tw_debug_level >= level:
timestamp = datetime.now().strftime("%H:%M:%S.%f")[:-3]
log_line = f"{timestamp} [DEBUG-{level}] {message}\n"
with open(DEBUG_LOG_FILE, "a") as f:
f.write(log_line)
print(f"\033[34m[DEBUG-{level}]\033[0m {message}", file=sys.stderr)
with open(DEBUG_LOG_FILE, "w") as f:
f.write("=" * 70 + "\n")
f.write(f"Debug Session - {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
f.write(f"Script: {script_name}\n")
f.write(f"TW_DEBUG Level: {tw_debug_level}\n")
f.write("=" * 70 + "\n\n")
debug_log(f"Debug logging initialized: {DEBUG_LOG_FILE}", 1)
else:
def debug_log(message, level=1):
pass
# ============================================================================
# Original Code
# ============================================================================
CONFIG_FILE = Path.home() / '.task' / 'config' / 'timelog.rc'
DEFAULT_FILE = Path.home() / '.task' / 'time' / 'tw.timeclock'
VERSION = '1.1.0'
def get_config(key: str, default: str = '') -> str:
"""Read timelog.<key> from timelog.rc."""
if not CONFIG_FILE.exists():
return default
with CONFIG_FILE.open() as f:
for line in f:
line = line.strip()
if not line or line.startswith('#') or '=' not in line:
continue
k, _, v = line.partition('=')
if k.strip() == f'timelog.{key}':
return v.strip()
return default
def tw_to_dt(s: str) -> datetime:
return datetime.strptime(s, '%Y%m%dT%H%M%SZ')
def dt_to_tw(d: datetime) -> str:
return d.strftime('%Y%m%dT%H%M%SZ')
def to_local(d: datetime) -> datetime:
"""Convert UTC datetime to local time."""
return datetime.fromtimestamp(calendar.timegm(d.timetuple()))
def tc_ts(d: datetime) -> str:
"""Format as hledger timeclock timestamp."""
return d.strftime('%Y/%m/%d %H:%M:%S')
def anno_count_grew(old: dict, new: dict) -> bool:
return len(new.get('annotations', [])) > len(old.get('annotations', []))
def pop_backdate(task: dict) -> tuple:
"""If the newest annotation is a plain integer, remove it and return (task, minutes).
Otherwise return (task, 0)."""
annos = task.get('annotations', [])
if not annos:
return task, 0
by_entry = sorted(annos, key=lambda a: a['entry'])
last = by_entry[-1]['description']
if not re.match(r'^\d+$', last):
return task, 0
task = dict(task)
task['annotations'] = by_entry[:-1]
if not task['annotations']:
del task['annotations']
return task, int(last)
def get_open_session(tc_path: Path):
"""Return (account_and_desc, started_dt) if there's an open 'i' entry, else None.
account_and_desc is everything after 'i DATE TIME ' on the last i-line."""
if not tc_path.exists():
return None
io_lines = []
with tc_path.open(encoding='utf-8') as f:
for line in f:
if line.startswith('i ') or line.startswith('o '):
io_lines.append(line.rstrip('\n'))
if not io_lines or not io_lines[-1].startswith('i '):
return None
# Format: "i YYYY/MM/DD HH:MM:SS account rest..."
parts = io_lines[-1].split(None, 3) # ['i', 'date', 'time', 'account rest...']
if len(parts) < 4:
return None
try:
started_dt = datetime.strptime(f'{parts[1]} {parts[2]}', '%Y/%m/%d %H:%M:%S')
except ValueError:
return None
return parts[3], started_dt
def main() -> None:
old = json.loads(sys.stdin.readline())
new = json.loads(sys.stdin.readline())
tc_str = get_config('file', str(DEFAULT_FILE))
tc_path = Path(tc_str.replace('~', str(Path.home())))
added = anno_count_grew(old, new)
# --- Task started ---
if 'start' in new and 'start' not in old:
if added:
new, minutes = pop_backdate(new)
if minutes:
start_dt = tw_to_dt(new['start']) - timedelta(minutes=minutes)
new['start'] = dt_to_tw(start_dt)
print(f'Timelog: started {minutes}m ago.')
# Don't let backdated start precede task entry date
if tw_to_dt(new['start']) < tw_to_dt(new['entry']):
new['entry'] = new['start']
# --- Task stopped ---
elif 'start' in old and 'start' not in new:
started = to_local(tw_to_dt(old['start']))
stopped = datetime.now()
if added:
new, minutes = pop_backdate(new)
if minutes:
stopped -= timedelta(minutes=minutes)
if stopped < started:
print(f'ERROR: -{minutes}m would precede start time', file=sys.stderr)
sys.exit(1)
print(f'Timelog: stopped {minutes}m ago.')
project = new.get('project', 'no:project').replace('.', ':')
desc = new.get('description', '')
tags = new.get('tags', [])
uuid = new['uuid']
tag_str = ', '.join(tags)
comment = f'; {tag_str} uuid:{uuid}' if tag_str else f'; uuid:{uuid}'
task_entry = (
f'i {tc_ts(started)} {project} {desc} {comment}\n'
f'o {tc_ts(stopped)}\n\n'
)
# If a manual 't in' session is open, pause it around the task entry
# to keep the timeclock file strictly alternating i/o.
open_sess = get_open_session(tc_path)
if open_sess:
open_acct_desc, open_started = open_sess
open_acct = open_acct_desc.split()[0]
if open_started <= started:
# Normal: pause the open session, write task, resume after
entry = (
f'o {tc_ts(started)} ; paused: {open_acct}\n\n'
+ task_entry
+ f'i {tc_ts(stopped)} {open_acct_desc}\n\n'
)
print(f'Timelog: paused {open_acct}; resumed after task.')
else:
# Open session started after task — can't insert cleanly; skip
print(f'Timelog: WARNING open {open_acct} session overlaps task start; '
'entry not written. Run "t" to fix.', file=sys.stderr)
print(json.dumps(new))
return
else:
entry = task_entry
tc_path.parent.mkdir(parents=True, exist_ok=True)
with tc_path.open('a', encoding='utf-8') as f:
f.write(entry)
print(json.dumps(new))
if __name__ == '__main__':
main()