-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworklog_cli.py
More file actions
935 lines (734 loc) · 30.2 KB
/
worklog_cli.py
File metadata and controls
935 lines (734 loc) · 30.2 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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
#!/usr/bin/env python3
"""
Work Log Automation CLI
Automates daily work logging with beautiful Rich UI and traffic light colors
"""
import argparse
import json
import os
import subprocess
import sys
from datetime import datetime, timedelta
from pathlib import Path
from typing import List, Dict, Optional, Tuple
try:
from rich.console import Console
from rich.panel import Panel
from rich.table import Table
from rich.prompt import Prompt, Confirm
from rich.markdown import Markdown
from rich import box
from rich.text import Text
except ImportError:
print("❌ Missing required package: rich")
print("Install with: pip install rich")
sys.exit(1)
console = Console()
# ============================================================================
# FEATURE FLAGS - Configure your automation preferences
# ============================================================================
FEATURE_FLAGS = {
"auto_create_daily": True, # Auto-create daily log file
"git_integration": True, # Git commit integration with git-standup
"auto_tag_validation": True, # Validate tags when logging work
"weekly_summary": True, # Generate weekly summaries
"time_tracking": True, # Track start/end times
"epic_grouping": True, # Group tasks by Epic
"ascii_art": True, # Show ASCII art headers
}
# ============================================================================
# CONFIGURATION
# ============================================================================
CONFIG = {
"log_directory": os.path.expanduser("~/work-logs"),
"date_format": "%d-%m-%Y",
"time_format": "%H:%M",
"current_sprint": "Sprint-XX",
"valid_tags": ["@feature", "@bugfix", "@review", "@docs", "@support", "@meeting"],
"status_icons": {
"done": "✅",
"in_progress": "🔄",
"started": "📝",
"blocked": "🚫"
}
}
# ============================================================================
# ASCII ART
# ============================================================================
ASCII_LOGO = """
╦ ╦╔═╗╦═╗╦╔═ ╦ ╔═╗╔═╗
║║║║ ║╠╦╝╠╩╗ ║ ║ ║║ ╦
╚╩╝╚═╝╩╚═╩ ╩ ╩═╝╚═╝╚═╝
"""
# ============================================================================
# UTILITY FUNCTIONS
# ============================================================================
def ensure_log_directory():
"""Create log directory if it doesn't exist"""
log_dir = Path(CONFIG["log_directory"])
log_dir.mkdir(parents=True, exist_ok=True)
return log_dir
def get_daily_log_path(date: Optional[datetime] = None) -> Path:
"""Get path to daily log file"""
if date is None:
date = datetime.now()
log_dir = ensure_log_directory()
filename = f"{date.strftime(CONFIG['date_format'])}.md"
return log_dir / filename
def get_current_sprint() -> str:
"""Get current sprint from config file or prompt user"""
config_file = Path(CONFIG["log_directory"]) / ".worklog_config.json"
if config_file.exists():
with open(config_file, 'r') as f:
data = json.load(f)
return data.get("current_sprint", CONFIG["current_sprint"])
return CONFIG["current_sprint"]
def save_sprint_config(sprint_name: str):
"""Save current sprint to config file"""
config_file = Path(CONFIG["log_directory"]) / ".worklog_config.json"
data = {"current_sprint": sprint_name}
with open(config_file, 'w') as f:
json.dump(data, f, indent=2)
def validate_tag(tag: str) -> bool:
"""Validate if tag is in approved list"""
return tag in CONFIG["valid_tags"]
def parse_log_entry(line: str) -> Optional[Dict]:
"""Parse a work log entry line"""
# Parse markdown table row: | Time | Task ID | Description | Status |
if not line.strip().startswith("|"):
return None
parts = [p.strip() for p in line.split("|")[1:-1]] # Remove empty first/last
if len(parts) >= 4 and parts[0] and parts[0] != "Time":
return {
"time": parts[0],
"task_id": parts[1],
"description": parts[2],
"status": parts[3]
}
return None
def get_git_commits_today(start_time_str: Optional[str] = None) -> List[Dict]:
"""Get today's git commits from current repository"""
try:
# Determine start time - use work_start if provided, otherwise midnight
if start_time_str:
try:
start_time = datetime.strptime(start_time_str, CONFIG["time_format"])
today = datetime.now().date()
today_start = datetime.combine(today, start_time.time())
except:
# Fallback to midnight if parsing fails
today_start = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
else:
# Default to midnight
today_start = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
since_date = today_start.strftime("%Y-%m-%d %H:%M:%S")
# Git log command to get commits since start time
# Format: hash|timestamp|commit message
cmd = [
"git", "log",
f"--since={since_date}",
"--pretty=format:%h|%ai|%s",
"--no-merges"
]
result = subprocess.run(
cmd,
capture_output=True,
text=True,
cwd=os.getcwd()
)
if result.returncode != 0:
# Not a git repo or git not installed
return []
commits = []
for line in result.stdout.strip().split('\n'):
if not line:
continue
parts = line.split('|', 2)
if len(parts) == 3:
commit_hash, timestamp, message = parts
# Parse timestamp and format time
try:
dt = datetime.fromisoformat(timestamp.split('+')[0].strip())
time_str = dt.strftime(CONFIG["time_format"])
except:
time_str = "N/A"
commits.append({
"hash": commit_hash,
"time": time_str,
"message": message,
"timestamp": timestamp
})
return commits
except FileNotFoundError:
# Git not installed
return []
except Exception as e:
console.print(f"[yellow]⚠️ Error getting git commits: {str(e)}[/yellow]")
return []
def add_git_commits_to_log(log_path: Path, commits: List[Dict]):
"""Add git commits section to the log file"""
if not commits:
return
with open(log_path, 'r') as f:
content = f.read()
# Check if Git Commits section already exists
if "## Git Commits" in content:
# Replace existing section
lines = content.split('\n')
new_lines = []
skip_until_next_section = False
for line in lines:
if "## Git Commits" in line:
skip_until_next_section = True
new_lines.append(line)
new_lines.append("")
new_lines.append("| Time | Hash | Commit Message |")
new_lines.append("|------|------|----------------|")
for commit in commits:
new_lines.append(f"| {commit['time']} | `{commit['hash']}` | {commit['message']} |")
new_lines.append("")
continue
if skip_until_next_section:
if line.startswith("##") or line.startswith("---"):
skip_until_next_section = False
new_lines.append(line)
continue
new_lines.append(line)
content = '\n'.join(new_lines)
else:
# Add new Git Commits section before Blockers
git_section = "\n## Git Commits\n\n"
git_section += "| Time | Hash | Commit Message |\n"
git_section += "|------|------|----------------|\n"
for commit in commits:
git_section += f"| {commit['time']} | `{commit['hash']}` | {commit['message']} |\n"
git_section += "\n---\n"
# Insert before Blockers section
if "## Blockers" in content:
content = content.replace("## Blockers", git_section + "\n## Blockers")
else:
# Insert before the last --- separator
parts = content.rsplit("\n---\n", 1)
if len(parts) == 2:
content = parts[0] + "\n---\n" + git_section + "\n" + parts[1]
else:
content += "\n" + git_section
with open(log_path, 'w') as f:
f.write(content)
# ============================================================================
# TEMPLATE GENERATION
# ============================================================================
def generate_daily_template(date: datetime, sprint: str) -> str:
"""Generate daily log template"""
yesterday = (date - timedelta(days=1)).strftime(CONFIG["date_format"])
tomorrow = (date + timedelta(days=1)).strftime(CONFIG["date_format"])
date_str = date.strftime(CONFIG["date_format"])
weekday = date.strftime("%A, %d %B %Y")
template = f"""---
date: {date_str}
sprint: {sprint}
work_start:
work_end:
total_hours:
---
# {weekday}
<< [[{yesterday}|Yesterday]] | [[{tomorrow}|Tomorrow]] >>
## Today's Focus (Top 3)
1.
2.
3.
---
## Work Log
### [EPIC] Project Name / Feature Area
| Time | Task ID | Description | Status |
|------|---------|-------------|--------|
| | | | |
---
## Git Commits
| Time | Hash | Commit Message |
|------|------|----------------|
| | | *Commits will be added automatically when you run 'worklog end'* |
---
## Blockers
-
---
## Notes & Learnings
-
---
## Tomorrow's Priority
- [ ]
- [ ]
- [ ]
---
## Tags
#work-log #{sprint.lower().replace(' ', '-')}
"""
return template
# ============================================================================
# CORE COMMANDS
# ============================================================================
def cmd_start():
"""Start work day - create daily log and set start time"""
if FEATURE_FLAGS["ascii_art"]:
console.print(ASCII_LOGO, style="bold cyan")
console.print(Panel.fit(
"🚀 [bold green]Starting Work Day[/bold green]",
border_style="green",
box=box.DOUBLE
))
date = datetime.now()
log_path = get_daily_log_path(date)
# Check if log already exists
if log_path.exists():
console.print(f"\n[yellow]⚠️ Log already exists:[/yellow] {log_path}")
if not Confirm.ask("Do you want to open it?", default=True):
return
# Read and display current log
with open(log_path, 'r') as f:
content = f.read()
console.print(f"\n[green]✅ Opening today's log[/green]")
console.print(f"[dim]{log_path}[/dim]\n")
return
# Create new daily log
if FEATURE_FLAGS["auto_create_daily"]:
sprint = get_current_sprint()
# Allow sprint update
console.print(f"\n[cyan]Current Sprint:[/cyan] {sprint}")
if Confirm.ask("Update sprint name?", default=False):
sprint = Prompt.ask("Enter sprint name", default=sprint)
save_sprint_config(sprint)
template = generate_daily_template(date, sprint)
with open(log_path, 'w') as f:
f.write(template)
# Set start time
if FEATURE_FLAGS["time_tracking"]:
start_time = datetime.now().strftime(CONFIG["time_format"])
update_start_time(log_path, start_time)
console.print(Panel(
f"[green]✅ Created daily log[/green]\n\n"
f"📁 Location: [cyan]{log_path}[/cyan]\n"
f"🕐 Start Time: [green]{start_time}[/green]\n"
f"🏃 Sprint: [yellow]{sprint}[/yellow]",
title="[bold green]Work Day Started[/bold green]",
border_style="green",
box=box.ROUNDED
))
else:
console.print("[yellow]⚠️ Feature 'auto_create_daily' is disabled[/yellow]")
def update_start_time(log_path: Path, start_time: str):
"""Update work_start time in log file"""
with open(log_path, 'r') as f:
content = f.read()
# Replace empty work_start with actual time
content = content.replace("work_start: \n", f"work_start: {start_time}\n")
with open(log_path, 'w') as f:
f.write(content)
def update_end_time(log_path: Path, end_time: str, total_hours: str):
"""Update work_end and total_hours in log file"""
with open(log_path, 'r') as f:
content = f.read()
content = content.replace("work_end: \n", f"work_end: {end_time}\n")
content = content.replace("total_hours: \n", f"total_hours: {total_hours}\n")
with open(log_path, 'w') as f:
f.write(content)
def cmd_log():
"""Log a work item interactively"""
console.print(Panel.fit(
"📝 [bold yellow]Log Work Item[/bold yellow]",
border_style="yellow",
box=box.DOUBLE
))
log_path = get_daily_log_path()
if not log_path.exists():
console.print("[red]❌ No daily log found. Run 'worklog start' first.[/red]")
return
# Collect work item details
console.print("\n[cyan]Enter work item details:[/cyan]\n")
time_range = Prompt.ask("⏰ Time range", default=datetime.now().strftime(CONFIG["time_format"]))
task_id = Prompt.ask("🎫 Task ID", default="")
# Tag selection
console.print("\n[cyan]Available tags:[/cyan]")
for i, tag in enumerate(CONFIG["valid_tags"], 1):
console.print(f" {i}. {tag}")
tag_input = Prompt.ask("\n🏷️ Tag (number or name)", default="1")
if tag_input.isdigit() and 1 <= int(tag_input) <= len(CONFIG["valid_tags"]):
tag = CONFIG["valid_tags"][int(tag_input) - 1]
elif tag_input in CONFIG["valid_tags"]:
tag = tag_input
elif tag_input.startswith("@") and FEATURE_FLAGS["auto_tag_validation"]:
console.print(f"[yellow]⚠️ Tag '{tag_input}' not recognized. Using as-is.[/yellow]")
tag = tag_input
else:
tag = CONFIG["valid_tags"][0]
description = Prompt.ask(f"📋 Description (starts with {tag})")
# Ensure tag is in description
if not description.startswith("@"):
description = f"{tag} {description}"
# Status selection
console.print("\n[cyan]Status:[/cyan]")
statuses = list(CONFIG["status_icons"].items())
for i, (status, icon) in enumerate(statuses, 1):
console.print(f" {i}. {icon} {status.replace('_', ' ').title()}")
status_input = Prompt.ask("\n📊 Status (number)", default="1")
status_key = statuses[int(status_input) - 1][0] if status_input.isdigit() else "done"
status = CONFIG["status_icons"][status_key] + " " + status_key.replace("_", " ").title()
# Epic selection
epic = Prompt.ask("\n🎯 Epic/Project name", default="General")
# Format the entry
entry = f"| {time_range} | {task_id} | {description} | {status} |"
# Add to log file
add_entry_to_log(log_path, epic, entry)
# Display confirmation
table = Table(title="Work Item Logged", box=box.ROUNDED, border_style="green")
table.add_column("Time", style="cyan")
table.add_column("Task ID", style="magenta")
table.add_column("Description", style="white")
table.add_column("Status", style="green")
table.add_row(time_range, task_id, description, status)
console.print("\n")
console.print(table)
console.print(f"\n[green]✅ Added to Epic:[/green] [yellow]{epic}[/yellow]\n")
def add_entry_to_log(log_path: Path, epic: str, entry: str):
"""Add work entry to the appropriate Epic section"""
with open(log_path, 'r') as f:
lines = f.readlines()
epic_header = f"### [EPIC] {epic}"
epic_found = False
insert_line = None
# Find the Epic section or create it
for i, line in enumerate(lines):
if epic_header in line:
epic_found = True
# Find the table and insert after the header row
for j in range(i, min(i + 10, len(lines))):
if lines[j].strip().startswith("|---"):
insert_line = j + 1
break
break
if not epic_found:
# Add new Epic section after "## Work Log"
for i, line in enumerate(lines):
if "## Work Log" in line:
insert_line = i + 2
lines.insert(insert_line, f"\n{epic_header}\n")
lines.insert(insert_line + 1, "| Time | Task ID | Description | Status |\n")
lines.insert(insert_line + 2, "|------|---------|-------------|--------|\n")
insert_line = insert_line + 3
break
if insert_line:
lines.insert(insert_line, entry + "\n")
with open(log_path, 'w') as f:
f.writelines(lines)
def cmd_end():
"""End work day - set end time and calculate total hours"""
console.print(Panel.fit(
"🏁 [bold red]Ending Work Day[/bold red]",
border_style="red",
box=box.DOUBLE
))
log_path = get_daily_log_path()
if not log_path.exists():
console.print("[red]❌ No daily log found for today.[/red]")
return
# Read current log
with open(log_path, 'r') as f:
content = f.read()
# Extract start time
start_time_str = None
for line in content.split('\n'):
if line.startswith('work_start:'):
start_time_str = line.split(':', 1)[1].strip()
break
if not start_time_str:
console.print("[yellow]⚠️ No start time found. Please add manually.[/yellow]")
return
# Set end time
end_time = datetime.now().strftime(CONFIG["time_format"])
# Calculate total hours
try:
start = datetime.strptime(start_time_str, CONFIG["time_format"])
end = datetime.strptime(end_time, CONFIG["time_format"])
delta = end - start
hours = delta.total_seconds() / 3600
total_hours = f"{hours:.2f}h"
except:
total_hours = "N/A"
update_end_time(log_path, end_time, total_hours)
# Git Integration - Pull today's commits
if FEATURE_FLAGS["git_integration"]:
console.print("\n[cyan]🔍 Checking for git commits...[/cyan]")
commits = get_git_commits_today(start_time_str)
if commits:
add_git_commits_to_log(log_path, commits)
# Display commits table
console.print("")
commit_table = Table(
title=f"Git Commits Found ({len(commits)})",
box=box.ROUNDED,
border_style="cyan"
)
commit_table.add_column("Time", style="cyan", no_wrap=True)
commit_table.add_column("Hash", style="magenta", no_wrap=True)
commit_table.add_column("Message", style="white")
for commit in commits:
commit_table.add_row(
commit['time'],
commit['hash'],
commit['message'][:60] + "..." if len(commit['message']) > 60 else commit['message']
)
console.print(commit_table)
console.print(f"\n[green]✅ Added {len(commits)} commit(s) to work log[/green]\n")
else:
console.print("[yellow]⚠️ No git commits found for today[/yellow]")
console.print("[dim]Make sure you're in a git repository with commits from today[/dim]\n")
# Display summary
console.print(Panel(
f"[green]✅ Work day completed[/green]\n\n"
f"🕐 Start: [cyan]{start_time_str}[/cyan]\n"
f"🕐 End: [cyan]{end_time}[/cyan]\n"
f"⏱️ Total: [yellow]{total_hours}[/yellow]",
title="[bold red]Day Summary[/bold red]",
border_style="red",
box=box.ROUNDED
))
# Ask about tomorrow's priorities
if Confirm.ask("\nSet tomorrow's priorities now?", default=True):
console.print("\n[cyan]Enter 3 priorities for tomorrow:[/cyan]\n")
priorities = []
for i in range(1, 4):
priority = Prompt.ask(f"Priority {i}", default="")
if priority:
priorities.append(priority)
if priorities:
add_tomorrow_priorities(log_path, priorities)
console.print("[green]✅ Priorities saved[/green]\n")
def add_tomorrow_priorities(log_path: Path, priorities: List[str]):
"""Add tomorrow's priorities to log"""
with open(log_path, 'r') as f:
content = f.read()
# Replace the Tomorrow's Priority section
priority_section = "## Tomorrow's Priority\n"
for priority in priorities:
priority_section += f"- [ ] {priority}\n"
# Find and replace the section
lines = content.split('\n')
in_section = False
new_lines = []
for line in lines:
if "## Tomorrow's Priority" in line:
in_section = True
new_lines.append(priority_section.strip())
continue
if in_section and line.startswith("##"):
in_section = False
if not in_section or not line.startswith("- [ ]"):
new_lines.append(line)
with open(log_path, 'w') as f:
f.write('\n'.join(new_lines))
def cmd_status():
"""Show current work day status"""
console.print(Panel.fit(
"📊 [bold cyan]Work Day Status[/bold cyan]",
border_style="cyan",
box=box.DOUBLE
))
log_path = get_daily_log_path()
if not log_path.exists():
console.print("\n[yellow]⚠️ No log file for today.[/yellow]")
console.print("[dim]Run 'worklog start' to begin.[/dim]\n")
return
# Parse log file
with open(log_path, 'r') as f:
content = f.read()
# Extract metadata
metadata = {}
work_items = []
for line in content.split('\n'):
if line.startswith('date:'):
metadata['date'] = line.split(':', 1)[1].strip()
elif line.startswith('sprint:'):
metadata['sprint'] = line.split(':', 1)[1].strip()
elif line.startswith('work_start:'):
metadata['start'] = line.split(':', 1)[1].strip()
elif line.startswith('work_end:'):
metadata['end'] = line.split(':', 1)[1].strip()
elif line.startswith('total_hours:'):
metadata['hours'] = line.split(':', 1)[1].strip()
# Parse work items
entry = parse_log_entry(line)
if entry:
work_items.append(entry)
# Display status
status_text = f"📅 Date: [cyan]{metadata.get('date', 'N/A')}[/cyan]\n"
status_text += f"🏃 Sprint: [yellow]{metadata.get('sprint', 'N/A')}[/yellow]\n"
status_text += f"🕐 Start: [green]{metadata.get('start', 'Not started')}[/green]\n"
status_text += f"🕐 End: [{'green' if metadata.get('end') else 'red'}]{metadata.get('end', 'In progress')}[/]\n"
status_text += f"⏱️ Hours: [yellow]{metadata.get('hours', 'N/A')}[/yellow]"
console.print(Panel(status_text, title="[bold]Today's Overview[/bold]", border_style="cyan", box=box.ROUNDED))
# Display work items
if work_items:
console.print("\n")
table = Table(title="Today's Work Items", box=box.ROUNDED, border_style="cyan")
table.add_column("Time", style="cyan", no_wrap=True)
table.add_column("Task", style="magenta")
table.add_column("Description", style="white")
table.add_column("Status", style="green")
for item in work_items:
table.add_row(
item['time'],
item['task_id'],
item['description'][:50] + "..." if len(item['description']) > 50 else item['description'],
item['status']
)
console.print(table)
console.print(f"\n[dim]Total items logged: {len(work_items)}[/dim]\n")
else:
console.print("\n[yellow]⚠️ No work items logged yet.[/yellow]\n")
def cmd_summary(days: int = 7):
"""Generate weekly summary report"""
if not FEATURE_FLAGS["weekly_summary"]:
console.print("[yellow]⚠️ Feature 'weekly_summary' is disabled[/yellow]")
return
console.print(Panel.fit(
f"📈 [bold magenta]Generating {days}-Day Summary[/bold magenta]",
border_style="magenta",
box=box.DOUBLE
))
# Collect logs from past N days
all_items = []
start_date = datetime.now() - timedelta(days=days-1)
for i in range(days):
date = start_date + timedelta(days=i)
log_path = get_daily_log_path(date)
if log_path.exists():
with open(log_path, 'r') as f:
content = f.read()
for line in content.split('\n'):
entry = parse_log_entry(line)
if entry:
entry['date'] = date.strftime(CONFIG["date_format"])
all_items.append(entry)
if not all_items:
console.print(f"\n[yellow]⚠️ No work items found in the past {days} days.[/yellow]\n")
return
# Group by tag
tag_groups = {}
for item in all_items:
# Extract tag from description
desc = item['description']
tag = "Other"
for valid_tag in CONFIG["valid_tags"]:
if valid_tag in desc:
tag = valid_tag
break
if tag not in tag_groups:
tag_groups[tag] = []
tag_groups[tag].append(item)
# Display summary
console.print(f"\n[bold cyan]Summary for {days} days ({start_date.strftime('%d-%m-%Y')} to {datetime.now().strftime('%d-%m-%Y')})[/bold cyan]\n")
for tag, items in sorted(tag_groups.items()):
# Color based on tag
if tag == "@feature":
color = "green"
elif tag == "@bugfix":
color = "red"
elif tag == "@review":
color = "yellow"
elif tag == "@meeting":
color = "blue"
else:
color = "white"
console.print(Panel(
f"[{color}]{len(items)} items[/{color}]",
title=f"[bold {color}]{tag}[/bold {color}]",
border_style=color,
expand=False
))
console.print(f"\n[dim]Total work items: {len(all_items)}[/dim]\n")
# Ask to export
if Confirm.ask("Export detailed summary to file?", default=True):
export_summary(all_items, tag_groups, days)
def export_summary(items: List[Dict], tag_groups: Dict, days: int):
"""Export summary to markdown file"""
log_dir = Path(CONFIG["log_directory"])
summary_file = log_dir / f"weekly-summary-{datetime.now().strftime('%d-%m-%Y')}.md"
content = f"# Weekly Summary Report\n\n"
content += f"**Period:** {(datetime.now() - timedelta(days=days-1)).strftime('%d-%m-%Y')} to {datetime.now().strftime('%d-%m-%Y')}\n"
content += f"**Total Items:** {len(items)}\n\n"
content += "---\n\n"
for tag, tag_items in sorted(tag_groups.items()):
content += f"## {tag} ({len(tag_items)} items)\n\n"
for item in tag_items:
content += f"- [{item['date']}] {item['task_id']} - {item['description']}\n"
content += "\n"
with open(summary_file, 'w') as f:
f.write(content)
console.print(f"[green]✅ Summary exported to:[/green] [cyan]{summary_file}[/cyan]\n")
def cmd_config():
"""Show and edit configuration"""
console.print(Panel.fit(
"⚙️ [bold cyan]Configuration[/bold cyan]",
border_style="cyan",
box=box.DOUBLE
))
# Display current config
console.print("\n[bold]Feature Flags:[/bold]\n")
for key, value in FEATURE_FLAGS.items():
status = "[green]✅ Enabled[/green]" if value else "[red]❌ Disabled[/red]"
console.print(f" {key}: {status}")
console.print("\n[bold]Settings:[/bold]\n")
console.print(f" Log Directory: [cyan]{CONFIG['log_directory']}[/cyan]")
console.print(f" Current Sprint: [yellow]{get_current_sprint()}[/yellow]")
console.print(f" Date Format: [cyan]{CONFIG['date_format']}[/cyan]")
console.print()
# ============================================================================
# MAIN CLI
# ============================================================================
def main():
parser = argparse.ArgumentParser(
description="Work Log Automation CLI - Beautiful logging for developers",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Commands:
start Start your work day (creates daily log)
log Log a work item interactively
end End your work day (calculates hours)
status Show current day status
summary Generate weekly summary report
config Show configuration
Examples:
worklog start
worklog log
worklog end
worklog summary --days 14
worklog config
"""
)
parser.add_argument('command',
choices=['start', 'log', 'end', 'status', 'summary', 'config'],
help='Command to execute')
parser.add_argument('--days', type=int, default=7,
help='Number of days for summary (default: 7)')
args = parser.parse_args()
# Execute command
try:
if args.command == 'start':
cmd_start()
elif args.command == 'log':
cmd_log()
elif args.command == 'end':
cmd_end()
elif args.command == 'status':
cmd_status()
elif args.command == 'summary':
cmd_summary(args.days)
elif args.command == 'config':
cmd_config()
except KeyboardInterrupt:
console.print("\n\n[yellow]⚠️ Cancelled by user[/yellow]")
sys.exit(0)
except Exception as e:
console.print(f"\n[red]❌ Error:[/red] {str(e)}")
sys.exit(1)
if __name__ == "__main__":
main()