-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathwrite-worklog.py
More file actions
494 lines (408 loc) · 16.6 KB
/
write-worklog.py
File metadata and controls
494 lines (408 loc) · 16.6 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
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
#!/usr/bin/env python3
"""
업무일지 자동 생성기
- Claude Code Stop 훅 또는 수동으로 실행
- 지정 날짜의 git 활동 + 세션 노트를 수집해 Gemini로 요약 후 Obsidian에 저장
사용법:
python3 write-worklog.py [프로젝트_경로] [--force] [--date YYYY-MM-DD] [--backfill N]
필수 환경변수:
OBSIDIAN_VAULT_PATH — Obsidian 볼트 경로
선택 환경변수:
GEMINI_API_KEY — Google Gemini API 키 (없으면 기본 템플릿으로 생성)
"""
import os
import sys
import json
import subprocess
import datetime
import re
from pathlib import Path
from typing import Optional
# ── 설정 ──────────────────────────────────────────────────
def resolve_vault_root() -> Path:
override = os.environ.get("OBSIDIAN_VAULT_PATH", "").strip()
if override:
return Path(override).expanduser()
candidates = [
Path.home() / "Library" / "Mobile Documents" / "iCloud~md~obsidian" / "Documents" / "Obsidian Vault",
Path.home() / "Documents" / "Obsidian Vault",
]
for path in candidates:
if path.exists():
return path
return candidates[0]
VAULT_PATH = resolve_vault_root() / "업무일지"
SESSIONS_PATH = resolve_vault_root() / "sessions"
GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY", "")
# 모델 변경하려면 이 URL 수정 (gemini-2.5-flash → gemini-2.5-pro 등)
GEMINI_URL = "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent"
TODAY = datetime.date.today().isoformat()
# ── Git 컨텍스트 수집 ──────────────────────────────────────
def _run(cmd: list, cwd: Optional[str] = None) -> tuple:
result = subprocess.run(cmd, cwd=cwd, capture_output=True, text=True)
return result.returncode, (result.stdout or "").strip()
def _collect_repo_day(repo_dir: str, target_date: str, label: Optional[str] = None) -> dict:
next_day = (
datetime.datetime.strptime(target_date, "%Y-%m-%d").date()
+ datetime.timedelta(days=1)
).isoformat()
prefix = f"[{label}] " if label else ""
_, commit_out = _run(
[
"git", "log", "--oneline",
f"--since={target_date} 00:00",
f"--until={next_day} 00:00",
"--all",
],
cwd=repo_dir,
)
commits = [f"{prefix}{l.strip()}" for l in commit_out.splitlines() if l.strip()]
_, file_out = _run(
[
"git", "log", "--pretty=format:", "--name-only",
f"--since={target_date} 00:00",
f"--until={next_day} 00:00",
"--all",
],
cwd=repo_dir,
)
raw_files = [l.strip() for l in file_out.splitlines() if l.strip()]
seen = set()
deduped = []
for file in raw_files:
if file in seen:
continue
seen.add(file)
deduped.append(f"{label}/{file}" if label else file)
return {"commits": commits, "changed_files": deduped}
def _find_child_repos(base_dir: str, max_depth: int = 2, max_repos: int = 30) -> list[str]:
base = Path(base_dir).resolve()
repos = []
for git_dir in base.rglob(".git"):
if not git_dir.is_dir():
continue
repo = git_dir.parent
try:
depth = len(repo.relative_to(base).parts)
except ValueError:
continue
if depth > max_depth:
continue
repos.append(str(repo))
if len(repos) >= max_repos:
break
repos.sort()
return repos
def get_git_context(project_dir: str, target_date: str) -> dict:
ctx = {"commits": [], "changed_files": [], "project": Path(project_dir).name}
try:
code, root = _run(["git", "rev-parse", "--show-toplevel"], cwd=project_dir)
if code == 0 and root:
repo_ctx = _collect_repo_day(root, target_date)
ctx["commits"] = repo_ctx["commits"]
ctx["changed_files"] = repo_ctx["changed_files"]
ctx["project"] = Path(root).name
ctx["repo_scope"] = "single"
ctx["repo_count"] = 1
return ctx
repos = _find_child_repos(project_dir)
if not repos:
ctx["repo_scope"] = "none"
ctx["repo_count"] = 0
return ctx
commits = []
files = []
for repo in repos:
label = Path(repo).name
day = _collect_repo_day(repo, target_date, label=label)
commits.extend(day["commits"])
files.extend(day["changed_files"])
ctx["commits"] = commits[:120]
ctx["changed_files"] = files[:300]
ctx["repo_scope"] = "multi"
ctx["repo_count"] = len(repos)
except Exception:
pass
return ctx
def get_recent_files(project_dir: str, target_date: str) -> list:
"""최근 1시간 내 수정된 파일 목록 (당일만)"""
if target_date != TODAY:
return []
try:
result = subprocess.run(
["find", project_dir, "-mmin", "-60", "-type", "f",
"-not", "-path", "*/node_modules/*",
"-not", "-path", "*/.git/*",
"-not", "-path", "*/.*"],
capture_output=True, text=True
)
files = [Path(f).name for f in result.stdout.splitlines() if f.strip()]
return files[:10]
except Exception:
return []
def get_session_context(target_date: str) -> dict:
"""같은 날짜 세션 노트에서 사용자 요청 기록을 수집"""
out = {"session_files": [], "session_requests": []}
if not SESSIONS_PATH.exists():
return out
files = sorted(SESSIONS_PATH.glob(f"{target_date}-*.md"))
out["session_files"] = [f.name for f in files]
req_lines = []
for f in files:
try:
text = f.read_text(encoding="utf-8", errors="ignore")
except Exception:
continue
m = re.search(r"## 사용자 요청 기록\s*(.*?)\n## ", text, flags=re.DOTALL)
if not m:
m = re.search(r"## 사용자 요청 기록\s*(.*)$", text, flags=re.DOTALL)
if not m:
continue
section = m.group(1)
for line in section.splitlines():
s = line.strip()
if s.startswith("- [") or s.startswith("- "):
value = s[2:].strip()
if "세션 ID 기준 사용자 대화 기록을 찾지 못함" in value:
continue
req_lines.append(value)
# 중복 제거
deduped = []
seen = set()
for line in req_lines:
if line in seen:
continue
seen.add(line)
deduped.append(line)
out["session_requests"] = deduped[:40]
return out
# ── Gemini 요약 ────────────────────────────────────────────
def summarize_with_gemini(context: dict, target_date: str) -> dict:
if not GEMINI_API_KEY:
return _fallback_log(context)
prompt = f"""
당신은 개발자의 하루 업무를 Obsidian 업무일지로 정리해주는 어시스턴트입니다.
아래 정보를 바탕으로 업무일지를 작성해주세요.
## 프로젝트
{context.get('project', '알 수 없음')}
## 대상 날짜
{target_date}
## 해당 날짜 git 커밋
{chr(10).join(context.get('commits', [])) or '커밋 없음'}
## 해당 날짜 수정된 파일
{chr(10).join(context.get('changed_files', [])) or '변경 없음'}
## 최근 수정 파일
{chr(10).join(context.get('recent_files', [])) or '없음'}
## 같은 날짜 세션 기록 파일
{chr(10).join(context.get('session_files', [])) or '없음'}
## 같은 날짜 사용자 요청 기록
{chr(10).join(context.get('session_requests', [])) or '없음'}
---
다음 형식으로 작성하세요. 추측이 아닌 위 정보에서 파악 가능한 내용만 작성하세요.
확실하지 않은 내용은 "확인 필요" 또는 빈칸으로 두세요.
한 줄 요약: (한 문장)
시도한 것: (불릿 리스트, 3~5개)
된 것: (불릿 리스트)
안 된 것 또는 막힌 것: (불릿 리스트, 없으면 "없음")
다음 할 일: (불릿 리스트, 2~3개)
콘텐츠 씨앗: (블로그/강의 소재가 될 만한 인사이트 1~2개)
"""
try:
import urllib.request
payload = json.dumps({
"contents": [{"parts": [{"text": prompt}]}]
}).encode()
req = urllib.request.Request(
f"{GEMINI_URL}?key={GEMINI_API_KEY}",
data=payload,
headers={"Content-Type": "application/json"},
method="POST"
)
with urllib.request.urlopen(req, timeout=30) as resp:
data = json.loads(resp.read())
text = data["candidates"][0]["content"]["parts"][0]["text"]
result = _parse_gemini_response(text, context)
return _enrich_result_with_context(result, context, target_date)
except Exception as e:
print(f"[Gemini 오류] {e} — 기본 템플릿으로 생성")
return _fallback_log(context)
def _parse_gemini_response(text: str, context: dict) -> dict:
lines = text.strip().splitlines()
result = {
"summary": "", "tried": [], "done": [], "failed": [],
"next": [], "seeds": [], "project": context.get("project", "")
}
current = None
for line in lines:
line = line.strip()
if line.startswith("한 줄 요약:"):
result["summary"] = line.replace("한 줄 요약:", "").strip()
elif line.startswith("시도한 것:"):
current = "tried"
elif line.startswith("된 것:"):
current = "done"
elif line.startswith("안 된 것"):
current = "failed"
elif line.startswith("다음 할 일:"):
current = "next"
elif line.startswith("콘텐츠 씨앗:"):
current = "seeds"
elif line.startswith("-") and current:
result[current].append(line[1:].strip())
return result
def _enrich_result_with_context(result: dict, context: dict, target_date: str) -> dict:
session_files = context.get("session_files", [])
session_requests = context.get("session_requests", [])
if not session_requests and session_files:
summary = (result.get("summary") or "").strip()
if (not summary) or ("커밋이나 파일 변경은 없었습니다" in summary):
result["summary"] = f"{target_date}에 세션 노트 {len(session_files)}개를 기록했다."
if not result.get("tried") or all("작성 필요" in t for t in result.get("tried", [])):
result["tried"] = [f"세션 노트 {len(session_files)}개 검토/백필"]
if not result.get("done"):
result["done"] = [f"세션 노트 {len(session_files)}개 저장/집계"]
if (not result.get("next")) or any("작성 필요" in t for t in result.get("next", [])):
result["next"] = [
"핵심 세션 1~2개를 실행 단위 태스크로 분해",
"결과물을 커밋 또는 문서 링크로 남기기",
]
return result
if not session_requests:
return result
tried = result.get("tried", [])
if not tried or all("작성 필요" in t for t in tried):
result["tried"] = session_requests[:5]
if not result.get("done"):
result["done"] = [f"세션 노트 {len(session_files)}개 저장/집계"]
summary = (result.get("summary") or "").strip()
if (not summary) or ("커밋이나 파일 변경은 없었습니다" in summary):
result["summary"] = (
f"{target_date}에 세션 {len(session_files)}개를 진행했고 "
f"사용자 요청 {len(session_requests)}건이 기록됐다."
)
next_items = result.get("next", [])
if (not next_items) or any("작성 필요" in t for t in next_items):
result["next"] = [
"세션 요청을 프로젝트별 실행 태스크로 재정리",
"핵심 결과물을 커밋/문서로 명시",
]
return result
def _fallback_log(context: dict) -> dict:
"""Gemini 없을 때 기본 템플릿"""
commits = context.get("commits", [])
requests = context.get("session_requests", [])
tried = commits[:5] or requests[:5] or ["작성 필요"]
if commits or requests:
summary = "코드 변경/세션 요청 기록을 기반으로 작업 흔적을 정리한 하루"
else:
summary = "코드 변경 및 세션 기록이 거의 없어 요약 정보가 부족한 하루"
return {
"project": context.get("project", ""),
"summary": summary,
"tried": tried,
"done": requests[:3] if requests else [],
"failed": [],
"next": ["핵심 작업 1~2개를 명시적으로 태스크화"],
"seeds": []
}
# ── Obsidian 파일 작성 ─────────────────────────────────────
def write_to_obsidian(data: dict, target_date: str, force: bool = False) -> str:
VAULT_PATH.mkdir(parents=True, exist_ok=True)
filepath = VAULT_PATH / f"{target_date}.md"
if filepath.exists() and not force:
print(f"[스킵] 기존 일지가 있어 건너뜁니다(--force로 덮어쓰기 가능): {filepath}")
return str(filepath)
tried = "\n".join(f"- {t}" for t in data["tried"]) or "- 작성 필요"
done = "\n".join(f"- {t}" for t in data["done"]) or "- "
failed = "\n".join(f"- {t}" for t in data["failed"]) or "- 없음"
next_tasks = "\n".join(f"- [ ] {t}" for t in data["next"]) or "- [ ] 작성 필요"
seeds = "\n".join(f"- {t}" for t in data["seeds"]) or "- "
content = f"""---
date: {target_date}
project: {data.get('project', '')}
tags: [업무일지]
status: 완료
---
# {target_date} 업무일지
## 한 줄 요약
> {data.get('summary', '작성 필요')}
---
## 시도한 것
{tried}
## 된 것
{done}
## 안 된 것 / 막힌 것
{failed}
---
## 다음 할 일
{next_tasks}
---
## 콘텐츠 씨앗
> 블로그, 스레드, 강의 소재로 쓸 수 있는 인사이트
{seeds}
"""
filepath.write_text(content, encoding="utf-8")
print(f"[완료] 업무일지 저장: {filepath}")
return str(filepath)
# ── 메인 ──────────────────────────────────────────────────
def parse_arg_value(flag: str):
if flag in sys.argv:
idx = sys.argv.index(flag)
if idx + 1 < len(sys.argv):
return sys.argv[idx + 1]
return None
def valid_date_or_none(value: str):
try:
datetime.datetime.strptime(value, "%Y-%m-%d")
return value
except Exception:
return None
def run_for_date(project_dir: str, target_date: str, force: bool, hook_data: dict):
print(f"[업무일지] 프로젝트: {project_dir} / 날짜: {target_date}")
ctx = get_git_context(project_dir, target_date)
ctx["recent_files"] = get_recent_files(project_dir, target_date)
sess = get_session_context(target_date)
ctx["session_files"] = sess["session_files"]
ctx["session_requests"] = sess["session_requests"]
if hook_data.get("session_id"):
ctx["session_id"] = hook_data["session_id"]
data = summarize_with_gemini(ctx, target_date)
path = write_to_obsidian(data, target_date=target_date, force=force)
print(f"[업무일지] 완료 → {path}")
def main():
force = "--force" in sys.argv
args = [a for a in sys.argv[1:] if not a.startswith("--")]
date_arg = parse_arg_value("--date")
backfill_arg = parse_arg_value("--backfill")
project_dir = args[0] if args else os.getcwd()
# Claude Code Stop 훅에서 stdin으로 JSON이 들어올 수 있음
hook_data = {}
if not sys.stdin.isatty():
try:
hook_data = json.load(sys.stdin)
except Exception:
pass
if backfill_arg:
try:
days = int(backfill_arg)
except ValueError:
print("[오류] --backfill 값은 정수여야 합니다.")
sys.exit(1)
if days <= 0:
print("[오류] --backfill 값은 1 이상이어야 합니다.")
sys.exit(1)
today = datetime.date.today()
for i in range(days - 1, -1, -1):
d = (today - datetime.timedelta(days=i)).isoformat()
run_for_date(project_dir, d, force, hook_data)
return
if date_arg:
target_date = valid_date_or_none(date_arg)
if not target_date:
print("[오류] --date 형식은 YYYY-MM-DD 여야 합니다.")
sys.exit(1)
else:
target_date = TODAY
run_for_date(project_dir, target_date, force, hook_data)
if __name__ == "__main__":
main()