Coverage for /Users/les/Projects/crackerjack/crackerjack/services/smart_scheduling.py: 0%
74 statements
« prev ^ index » next coverage.py v7.10.6, created at 2025-09-03 15:39 -0700
« prev ^ index » next coverage.py v7.10.6, created at 2025-09-03 15:39 -0700
1import os
2import subprocess
3from datetime import datetime, timedelta
4from pathlib import Path
6from rich.console import Console
9class SmartSchedulingService:
10 def __init__(self, console: Console, project_path: Path) -> None:
11 self.console = console
12 self.project_path = project_path
13 self.cache_dir = Path.home() / ".cache" / "crackerjack"
14 self.cache_dir.mkdir(parents=True, exist_ok=True)
16 def should_scheduled_init(self) -> bool:
17 init_schedule = os.environ.get("CRACKERJACK_INIT_SCHEDULE", "weekly")
19 if init_schedule == "disabled":
20 return False
22 if init_schedule == "weekly":
23 return self._check_weekly_schedule()
24 if init_schedule == "commit-based":
25 return self._check_commit_based_schedule()
26 if init_schedule == "activity-based":
27 return self._check_activity_based_schedule()
29 return self._check_weekly_schedule()
31 def record_init_timestamp(self) -> None:
32 timestamp_file = self.cache_dir / f"{self.project_path.name}.init_timestamp"
33 try:
34 timestamp_file.write_text(datetime.now().isoformat())
35 except OSError as e:
36 self.console.print(
37 f"[yellow]⚠️ Could not record init timestamp: {e}[/ yellow]",
38 )
40 def _check_weekly_schedule(self) -> bool:
41 init_day = os.environ.get("CRACKERJACK_INIT_DAY", "monday")
42 today = datetime.now().strftime("% A").lower()
44 if today == init_day.lower():
45 last_init = self._get_last_init_timestamp()
46 if datetime.now() - last_init > timedelta(days=6):
47 self.console.print(
48 f"[blue]📅 Weekly initialization scheduled for {init_day}[/ blue]",
49 )
50 return True
52 return False
54 def _check_commit_based_schedule(self) -> bool:
55 commits_since_init = self._count_commits_since_init()
56 threshold = int(os.environ.get("CRACKERJACK_INIT_COMMITS", "50"))
58 if commits_since_init >= threshold:
59 self.console.print(
60 f"[blue]📊 {commits_since_init} commits since last init "
61 f"(threshold: {threshold})[/ blue]",
62 )
63 return True
65 return False
67 def _check_activity_based_schedule(self) -> bool:
68 if self._has_recent_activity() and self._days_since_init() >= 7:
69 self.console.print(
70 "[blue]⚡ Recent activity detected, initialization recommended[/ blue]",
71 )
72 return True
74 return False
76 def _get_last_init_timestamp(self) -> datetime:
77 timestamp_file = self.cache_dir / f"{self.project_path.name}.init_timestamp"
79 if timestamp_file.exists():
80 from contextlib import suppress
82 with suppress(OSError, ValueError):
83 timestamp_str = timestamp_file.read_text().strip()
84 return datetime.fromisoformat(timestamp_str)
86 return datetime.now() - timedelta(days=30)
88 def _count_commits_since_init(self) -> int:
89 since_date = self._get_last_init_timestamp().strftime("% Y - % m - % d")
91 try:
92 result = subprocess.run(
93 ["git", "log", f"--since ={since_date}", "--oneline"],
94 cwd=self.project_path,
95 capture_output=True,
96 text=True,
97 timeout=10,
98 check=False,
99 )
101 if result.returncode == 0:
102 return len([line for line in result.stdout.strip().split("\n") if line])
104 except (FileNotFoundError, subprocess.TimeoutExpired):
105 pass
107 return 0
109 def _has_recent_activity(self) -> bool:
110 try:
111 result = subprocess.run(
112 ["git", "log", "- 1", "--since=24.hours", "--oneline"],
113 cwd=self.project_path,
114 capture_output=True,
115 text=True,
116 timeout=10,
117 check=False,
118 )
120 return result.returncode == 0 and bool(result.stdout.strip())
122 except (FileNotFoundError, subprocess.TimeoutExpired):
123 return False
125 def _days_since_init(self) -> int:
126 last_init = self._get_last_init_timestamp()
127 return (datetime.now() - last_init).days