-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommitose.py
More file actions
executable file
·1115 lines (917 loc) · 36.2 KB
/
commitose.py
File metadata and controls
executable file
·1115 lines (917 loc) · 36.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
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
from __future__ import annotations
import argparse
import math
import os
import random
import secrets
import subprocess
import sys
from dataclasses import dataclass, field
from datetime import date, timedelta
from enum import Enum
from pathlib import Path
from types import UnionType
from typing import Any, Optional, get_args, get_origin, get_type_hints
import tomllib
TODAY = date.today()
Week = tuple[float, float, float, float, float, float, float]
@dataclass
class Commit:
date: date
message: str
@dataclass
class Break:
"""A time period with scaled commit activity."""
start_date: date
end_date: date
factor: float = 0.0
class MarkovChain:
Vector = tuple[float, float, float, float]
Matrix = tuple[Vector, Vector, Vector, Vector]
class State(Enum):
OFF = 0
QUIET = 1
NORMAL = 2
BUSY = 3
transition_matrix: Matrix
rng: random.Random
current_state: State
def __init__(self, transition_matrix: Matrix, seed: int | None = None):
self.transition_matrix = transition_matrix
self.rng = random.Random(seed)
self.current_state = MarkovChain.State.OFF
def next(self) -> MarkovChain.State:
probabilities = self.transition_matrix[self.current_state.value]
self.current_state = self.rng.choices(
list(MarkovChain.State), weights=probabilities
)[0]
return self.current_state
@dataclass
class Sampler:
seed: int | None = None
rng: random.Random = field(init=False)
def __post_init__(self):
self.rng = random.Random(self.seed)
def zinb(self, mean: float, dispersion: float, zero_inflation: float) -> int:
# Zero inflation
if self.rng.random() < zero_inflation:
return 0
# Negative binomial via gamma-Poisson mixture
# See: https://en.wikipedia.org/wiki/Negative_binomial_distribution
if mean > 0:
lam = self.rng.gammavariate(dispersion, mean / dispersion)
return self.poisson(lam)
return 0
def poisson(self, lam: float) -> int:
if lam <= 0:
return 0
# Knuth algorithm
# See: https://en.wikipedia.org/wiki/Poisson_distribution#Random_variate_generation
L = math.exp(-lam)
k = 0
p = 1.0
while p > L:
k += 1
p *= self.rng.random()
return k - 1
@dataclass
class Simulator:
start_date: date
end_date: date
# Weights for each weekday. Allows commit activity to be scaled by a factor
# depending on the day of the week.
weekday_weights: Week
breaks: list[Break]
# Mean number of commits per state
commit_means: MarkovChain.Vector
# Dispersion parameter for commit count distribution
commit_dispersion: float
# Zero inflation per state
commit_zero_inflation: MarkovChain.Vector
transition_matrix: MarkovChain.Matrix
seed: int | None = None
sampler: Sampler = field(init=False)
markov_chain: MarkovChain = field(init=False)
def __post_init__(self):
self.sampler = Sampler(self.seed)
self.markov_chain = MarkovChain(self.transition_matrix, self.seed)
def simulate(self) -> list[Commit]:
commits: list[Commit] = []
current_date = self.start_date
while current_date <= self.end_date:
commit_count = self.sample_daily_commits(current_date)
for _ in range(commit_count):
commits.append(
Commit(date=current_date, message=self.generate_commit_msg())
)
current_date += timedelta(days=1)
return commits
def sample_daily_commits(self, date: date) -> int:
state = self.markov_chain.next()
if state == MarkovChain.State.OFF:
return 0
weekday_weight = self.weekday_weights[date.weekday()]
break_factor = self.get_break_factor(date)
commit_mean = self.commit_means[state.value] * weekday_weight * break_factor
commit_zero_inflation = self.commit_zero_inflation[state.value]
commit_count = self.sampler.zinb(
commit_mean, self.commit_dispersion, commit_zero_inflation
)
return commit_count
def get_break_factor(self, date: date) -> float:
"""Return activity scaling factor for a given date."""
for b in self.breaks:
if b.start_date <= date <= b.end_date:
return b.factor
return 1.0
def generate_commit_msg(self) -> str:
"""Generate a random commit message."""
return secrets.token_hex(8)
@dataclass
class GitClient:
user_name: str
user_email: str
repo_path: Path
branch: str
class WouldOverwriteRepoError(Exception):
pass
def exec_git(
self, cmd: list[str], env: dict[str, str] | None = None, check: bool = False
):
"""Execute a git command in the repository."""
subprocess.run(
["git", *cmd],
cwd=self.repo_path,
env=env,
check=check,
capture_output=True,
)
def commit_all(self, commits: list[Commit]) -> None:
"""Commit all commits in the list."""
for i, commit in enumerate(commits, 1):
self.commit(commit)
if i == len(commits):
print(f"\033[KCommitted {i}/{len(commits)} commits!")
elif i % 10 == 0:
print(f"\033[KCommitted {i}/{len(commits)} commits...", end="\r")
def commit(self, commit: Commit) -> None:
env = os.environ.copy()
date_str = commit.date.strftime("%Y-%m-%dT%H:%M:%S%z")
env.update(
{
"GIT_AUTHOR_NAME": self.user_name,
"GIT_AUTHOR_EMAIL": self.user_email,
"GIT_AUTHOR_DATE": date_str,
"GIT_COMMITTER_NAME": self.user_name,
"GIT_COMMITTER_EMAIL": self.user_email,
"GIT_COMMITTER_DATE": date_str,
}
)
self.exec_git(["commit", "--allow-empty", "-m", commit.message], env)
def wipe_repo(self) -> None:
self.exec_git(["checkout", "--orphan", "temp-branch"])
self.exec_git(["rm", "-rf", "."], check=False)
# If user has switched branch, the new branch may not yet exist
self.exec_git(["branch", "-D", self.branch], check=False)
self.exec_git(["branch", "-m", self.branch])
@staticmethod
def check_repo_path(repo_path: Path) -> None:
repo_path.mkdir(parents=True, exist_ok=True)
# Ensure that directory is empty, or only contains .git
for entry in repo_path.iterdir():
if not (entry.name == ".git" and entry.is_dir()):
raise ValueError(
f"Directory '{repo_path}' is not empty (found '{entry.name}')"
)
if (repo_path / ".git").exists():
# Verify it's a valid git repository
try:
subprocess.run(
["git", "rev-parse", "--git-dir"],
cwd=repo_path,
check=True,
capture_output=True,
)
except subprocess.CalledProcessError:
raise ValueError(
f"Directory {repo_path} contains invalid .git directory"
)
raise GitClient.WouldOverwriteRepoError()
else:
# Create new repo
subprocess.run(
["git", "init"],
cwd=repo_path,
check=True,
capture_output=True,
)
@staticmethod
def get_git_config(key: str) -> str | None:
"""Get a value from git config."""
try:
result = subprocess.run(
["git", "config", "--get", key],
capture_output=True,
text=True,
check=True,
)
return result.stdout.strip()
except subprocess.CalledProcessError:
return None
@dataclass
class Config:
start_date: date = TODAY - timedelta(days=365)
end_date: date = TODAY
breaks: list[Break] = field(default_factory=list)
weekday_weights: Week = (1, 1, 1, 1, 1, 1, 1)
commit_means: MarkovChain.Vector = (0, 1, 3, 7)
commit_dispersion: float = 1
commit_zero_inflation: MarkovChain.Vector = (1, 0.3, 0.1, 0.05)
transition_matrix: MarkovChain.Matrix = (
(0.65, 0.25, 0.10, 0.00), # off
(0.15, 0.60, 0.20, 0.05), # quiet
(0.05, 0.15, 0.65, 0.15), # normal
(0.00, 0.05, 0.35, 0.60), # busy
)
seed: int | None = None
repo_path: Path = Path("commits_repo")
user_name: str | None = None
user_email: str | None = None
branch: str = "main"
dry_run: bool = False
def load_toml(self, path: str) -> None:
"""Load configuration from TOML file."""
with open(path, "rb") as f:
raw_data = tomllib.load(f)
coerced_data = Config.coerce_config(raw_data)
for field_name in coerced_data:
setattr(self, field_name, coerced_data[field_name])
self._validate()
def load_args(self, args: dict[str, Any]):
"""Load configuration from parsed CLI arguments."""
coerced_data = Config.coerce_config(args)
for field_name in coerced_data:
setattr(self, field_name, coerced_data[field_name])
self._validate()
@staticmethod
def coerce_config(raw_data: dict[str, Any]) -> dict[str, Any]:
coerced_data = {}
field_types = get_type_hints(Config)
for field_name in raw_data:
if field_name not in field_types:
continue
value = raw_data[field_name]
if value is None:
# Value not passed
continue
expected_type = field_types[field_name]
coerced_data[field_name] = Config.coerce_field(
field_name, value, expected_type
)
return coerced_data
@staticmethod
def coerce_field(field_name: str, value: Any, expected_type: Any) -> Any:
origin = get_origin(expected_type)
args = get_args(expected_type)
# Date
if expected_type is date:
# If passed as date (from TOML conversion), no need to coerce
if isinstance(value, date):
return value
# If passed as string, should be ISO format
if isinstance(value, str):
try:
return date.fromisoformat(value)
except ValueError:
raise ValueError(
f"Invalid {field_name} '{value}', expected ISO format (YYYY-MM-DD)"
)
raise TypeError(
f"Expected date or ISO string for {field_name}, got {type(value).__name__}"
)
# Break
if expected_type is Break:
return Config.coerce_break(value)
# Path
if expected_type is Path:
# Should be passed as string or Path
if isinstance(value, str):
return Path(value)
if isinstance(value, Path):
return value
raise TypeError(
f"Expected path for {field_name}, got {type(value).__name__}"
)
# String
if expected_type is str:
# Should be passed as string
if isinstance(value, str):
return value
raise TypeError(
f"Expected string for {field_name}, got {type(value).__name__}"
)
# Int
if expected_type is int:
# Should be passed as int
if isinstance(value, int):
return value
raise TypeError(
f"Expected int for {field_name}, got {type(value).__name__}"
)
# Float
if expected_type is float:
# Should be passed as float
if isinstance(value, float):
return value
# But we can also accept ints
if isinstance(value, int):
return float(value)
raise TypeError(
f"Expected float for {field_name}, got {type(value).__name__}"
)
# Boolean
if expected_type is bool:
# Should be passed as bool
if isinstance(value, bool):
return value
raise TypeError(
f"Expected bool for {field_name}, got {type(value).__name__}"
)
# Union
if origin is UnionType:
# Union types for this class consist of None and one other type
# If the config option has been passed, we expect the other type
some_type = next(arg for arg in args if arg is not type(None))
return Config.coerce_field(field_name, value, some_type)
# List
if origin is list:
# Should be passed as list
if isinstance(value, list):
return [Config.coerce_field(field_name, v, args[0]) for v in value]
raise TypeError(
f"Expected list for {field_name}, got {type(value).__name__}"
)
# Tuple
if origin is tuple:
# Should be passed as list
if isinstance(value, list):
if len(value) != len(args):
raise ValueError(
f"Expected tuple of length {len(args)} for {field_name}, got {len(value)}"
)
return tuple(
Config.coerce_field(field_name, v, args[i])
for i, v in enumerate(value)
)
raise TypeError(
f"Expected list (to convert to tuple), got {type(value).__name__}"
)
# TODO: Also support dict input
@staticmethod
def coerce_break(value: Any) -> Break:
"""Parse break from string format START:END[:FACTOR]."""
BREAK_FORMAT = "START_DATE:END_DATE[:FLOAT]"
if isinstance(value, str):
try:
start_date, end_date, *rest = value.split(":")
except ValueError:
raise ValueError(
f"Invalid break '{value}', expected format: {BREAK_FORMAT}"
)
if len(rest) == 0:
factor = None
elif len(rest) == 1:
try:
factor = float(rest[0])
except ValueError:
raise ValueError(
f"Invalid break factor '{rest[0]}', expected a float"
)
else:
raise ValueError(f"Invalid break '{value}', expected {BREAK_FORMAT}")
try:
start_date = date.fromisoformat(start_date)
except ValueError:
raise ValueError(
f"Invalid break start date '{start_date}', expected ISO format (YYYY-MM-DD)"
)
try:
end_date = date.fromisoformat(end_date)
except ValueError:
raise ValueError(
f"Invalid break end date '{end_date}', expected ISO format (YYYY-MM-DD)"
)
if factor is not None:
return Break(start_date, end_date, factor)
else:
return Break(start_date, end_date)
if isinstance(value, dict):
start_date = value.get("start_date")
end_date = value.get("end_date")
factor = value.get("factor")
if start_date is None:
raise ValueError("Break dict must contain 'start_date'")
if end_date is None:
raise ValueError("Break dict must contain 'end_date'")
# Convert dates if they're strings
if isinstance(start_date, str):
try:
start_date = date.fromisoformat(start_date)
except ValueError:
raise ValueError(
f"Invalid break start date '{start_date}', expected ISO format (YYYY-MM-DD)"
)
if isinstance(end_date, str):
try:
end_date = date.fromisoformat(end_date)
except ValueError:
raise ValueError(
f"Invalid break end date '{end_date}', expected ISO format (YYYY-MM-DD)"
)
if factor is None:
return Break(start_date, end_date)
else:
return Break(start_date, end_date, factor)
raise TypeError(f"Expected break string or dict, got {type(value).__name__}")
def _validate(self) -> None:
if self.start_date > self.end_date:
raise ValueError(
f"Simulation start date ({self.start_date}) must be before end date ({self.end_date})"
)
for weight in self.weekday_weights:
if weight < 0:
raise ValueError(
f"All weekday weights must be non-negative (got {self.weekday_weights})"
)
for mean in self.commit_means:
if mean < 0:
raise ValueError(
f"All commit means must be non-negative (got {self.commit_means})"
)
if self.commit_dispersion <= 0:
raise ValueError(
f"Commit dispersion must be positive (got {self.commit_dispersion})"
)
for zero_inflation in self.commit_zero_inflation:
if not 0 <= zero_inflation <= 1:
raise ValueError(
f"Zero inflation probabilities must be between 0 and 1 (got {self.commit_zero_inflation})"
)
for i, row in enumerate(self.transition_matrix):
if not math.isclose(sum(row), 1.0, rel_tol=1e-9):
raise ValueError(
f"Transition matrix rows must sum to 1.0 (got {sum(row):.6f} in row {i})"
)
self._validate_breaks()
def _validate_breaks(self) -> None:
"""Ensure breaks are valid and don't overlap."""
# Validate
for b in self.breaks:
if b.start_date > b.end_date:
raise ValueError(
f"Break start date must be before end date (got {b.start_date} to {b.end_date})"
)
if b.factor < 0:
raise ValueError(f"Break factor must be non-negative (got {b.factor})")
# Check for overlaps
sorted_breaks = sorted(self.breaks, key=lambda b: b.start_date)
for i in range(len(sorted_breaks) - 1):
current_break = sorted_breaks[i]
next_break = sorted_breaks[i + 1]
if current_break.end_date >= next_break.start_date:
raise ValueError(
f"Breaks must not overlap: {current_break.start_date} to "
f"{current_break.end_date} overlaps with {next_break.start_date} to "
f"{next_break.end_date}"
)
class Visualizer:
"""Renders commit schedule as GitHub-style contribution graph."""
# Colour scheme (GitHub-style green)
COLOUR_SCHEME = [
(239, 242, 245),
(172, 238, 187),
(74, 194, 107),
(45, 164, 78),
(17, 99, 41),
]
BLOCK = "█"
def __init__(self, schedule: list[Commit], start_date: date, end_date: date):
self.schedule = schedule
self.start_date = start_date
self.end_date = end_date
self.commit_map = self._build_commit_map()
self.colour_cutoffs = self._calculate_colour_cutoffs()
def _build_commit_map(self) -> dict[date, int]:
"""Create mapping of date to commit count."""
commit_map = {}
# Initialize all dates with zero (including days with no commits)
current = self.start_date
while current <= self.end_date:
commit_map[current] = 0
current += timedelta(days=1)
# Count commits per day
for commit in self.schedule:
commit_map[commit.date] += 1
return commit_map
def render(self) -> str:
"""Render the contribution graph adaptively."""
try:
terminal_width = os.get_terminal_size().columns
except OSError:
terminal_width = 80
total_days = (self.end_date - self.start_date).days + 1
total_weeks = (total_days + 6) // 7
horizontal_width = 8 + total_weeks * 2
lines = []
if horizontal_width <= terminal_width:
lines += self._render_horizontal()
elif terminal_width >= 70:
lines += self._render_quarterly()
else:
lines += self._render_vertical()
lines += self._render_statistics()
return "\n".join(lines)
def _render_horizontal(self) -> list[str]:
"""Render full horizontal GitHub-style graph."""
lines = [self._bold("Commit Graph Preview\n")]
weeks = self._build_weeks(self.start_date, self.end_date)
# Month labels
lines.append(self._muted(self._build_month_labels(weeks)))
# Day rows
day_labels = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
for day_idx in range(7):
line = self._muted(day_labels[day_idx]) + " "
for week in weeks:
count = week[day_idx]
line += " " if count is None else self._coloured_block(count) * 2
lines.append(line)
lines.append("")
lines.append(self._render_legend())
return lines
def _render_quarterly(self) -> list[str]:
"""Render in quarterly sections."""
lines = [
self._bold("Commit Graph Preview") + " " + self._muted("(quarterly view)\n")
]
current_date = self.start_date
while current_date <= self.end_date:
year = current_date.year
quarter = (current_date.month - 1) // 3 + 1
quarter_end = self._get_quarter_end(year, quarter)
quarter_end = min(quarter_end, self.end_date)
lines.append(
self._bold(f"Q{quarter} {year}")
+ self._muted(
f" {current_date.strftime('%b %d')} - {quarter_end.strftime('%b %d, %Y')}"
)
)
weeks = self._build_weeks(current_date, quarter_end)
day_labels = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
for day_idx in range(7):
line = self._muted(day_labels[day_idx]) + " "
for week in weeks:
count = week[day_idx]
line += " " if count is None else self._coloured_block(count) * 2
lines.append(line)
lines.append("")
current_date = quarter_end + timedelta(days=1)
return lines
def _render_vertical(self) -> list[str]:
"""Render in vertical/transposed layout."""
lines = [
self._bold("Commit Graph Preview") + " " + self._muted("(vertical view)\n")
]
lines.append(self._bold("Date") + " " + self._muted("M T W T F S S"))
weeks = self._build_weeks(self.start_date, self.end_date)
current_date = self.start_date
# Find first Monday
days_to_monday = (7 - current_date.weekday()) % 7 # 0 is Monday
current_date -= timedelta(days=days_to_monday)
for week in weeks:
date_str = self._muted(current_date.strftime("%b %d"))
line = f"{date_str} "
for day_idx in range(7):
count = week[day_idx]
line += " " if count is None else self._coloured_block(count) * 2
lines.append(line)
current_date += timedelta(days=7)
lines.append("")
return lines
def _render_statistics(self) -> list[str]:
"""Render commit statistics."""
active_days = sum(1 for count in self.commit_map.values() if count > 0)
avg_commits = len(self.schedule) / max(active_days, 1)
return [
self._bold("Statistics"),
f" Total commits: {len(self.schedule)}",
f" Days with commits: {active_days}",
f" Average per active day: {avg_commits:.1f}",
f" Max commits in a day: {max(self.commit_map.values())}",
"",
]
def _render_legend(self) -> str:
"""Render colour gradient legend."""
legend = "Less "
for colour in self.COLOUR_SCHEME:
legend += (
f"\033[38;2;{colour[0]};{colour[1]};{colour[2]}m{self.BLOCK}\033[0m"
) * 2
legend += " More\n"
return legend
def _build_weeks(self, start: date, end: date) -> list[list[Optional[int]]]:
"""Build week data structure for date range."""
current = start
while current.weekday() != 0:
current -= timedelta(days=1)
weeks = []
week: list[Optional[int]] = [None] * current.weekday()
while current <= end:
if current >= start:
week.append(self.commit_map.get(current, 0))
else:
week.append(None)
if len(week) == 7:
weeks.append(week)
week = []
current += timedelta(days=1)
if week:
week.extend([None] * (7 - len(week)))
weeks.append(week)
return weeks
def _build_month_labels(self, weeks: list[list[Optional[int]]]) -> str:
"""Build month label row for horizontal view."""
# Main idea: Build up a list of months associated with the week they
# start in
months = [(self.start_date.strftime("%b"), 0)]
current_week = 0
for d in sorted(self.commit_map.keys()):
month_abbr = d.strftime("%b")
if month_abbr != months[-1][0]:
# Encountered a new month
if current_week - months[-1][1] < 2:
# Previous month would be cut off, so blank it
months[-1] = ("", months[-1][1])
months.append((month_abbr, current_week))
if d.weekday() == 6:
# New week is beginning, so update column
current_week += 1
labels = " " * 4
for i in range(len(months) - 1):
labels += months[i][0]
# Add spacing until next month's first week
week_delta = months[i + 1][1] - months[i][1]
spacing = week_delta * 2 - len(months[i][0])
labels += " " * spacing
labels += months[-1][0]
return labels
def _get_quarter_end(self, year: int, quarter: int) -> date:
"""Get last day of quarter."""
end_month = quarter * 3
if end_month == 12:
return date(year, 12, 31)
return date(year, end_month + 1, 1) - timedelta(days=1)
def _calculate_colour_cutoffs(self) -> list[float]:
"""Calculate colour cutoffs based on quartiles after removing outliers."""
# Get all non-zero commit counts
counts = [c for c in self.commit_map.values() if c > 0]
if len(counts) == 0:
# No commits, all will be gray
return [0, 0, 0]
max_val = max(counts)
fallback_cutoffs = [max_val * 0.25, max_val * 0.5, max_val * 0.75]
if len(counts) < 4:
# Too few data points for meaningful quartiles, use simple division
return fallback_cutoffs
# Remove outliers using IQR method
filtered_counts = self._remove_outliers(counts)
if len(filtered_counts) < 4:
# After outlier removal, too few points remain
return fallback_cutoffs
# Calculate quartiles on filtered data
q1, q2, q3 = self._calculate_quartiles(filtered_counts)
return [q1, q2, q3]
def _remove_outliers(self, values: list[int]) -> list[int]:
"""Remove outliers using IQR (Interquartile Range) method.
Outliers are values outside the range [Q1 - 1.5*IQR, Q3 + 1.5*IQR].
"""
if len(values) < 4:
return values.copy()
sorted_values = sorted(values)
n = len(sorted_values)
# Calculate Q1 and Q3
q1_idx = n // 4
q3_idx = (3 * n) // 4
q1 = sorted_values[q1_idx]
q3 = sorted_values[q3_idx]
iqr = q3 - q1
# Define outlier bounds
lower_bound = q1 - 1.5 * iqr
upper_bound = q3 + 1.5 * iqr
# Filter out outliers
filtered = [v for v in values if lower_bound <= v <= upper_bound]
return filtered if filtered else values.copy()
def _calculate_quartiles(self, values: list[int]) -> tuple[float, float, float]:
"""Calculate Q1, Q2 (median), and Q3 from sorted values.
Uses the next distinct value after each quartile index to ensure
proper distribution when there are duplicate values.
"""
if not values:
return (0.0, 0.0, 0.0)
sorted_values = sorted(values)
n = len(sorted_values)
# If all values are the same, use the value itself as all cutoffs
if sorted_values[0] == sorted_values[-1]:
return (
float(sorted_values[0]),
float(sorted_values[0]),
float(sorted_values[0]),
)
# Find the next distinct value after each quartile index
def get_cutoff(idx: int) -> float:
"""Get the smallest value greater than the value at idx."""
val = sorted_values[idx]
for i in range(idx + 1, n):
if sorted_values[i] > val:
return float(sorted_values[i])
# No greater value found
return float(val)
# Calculate quartile indices
q1_idx = n // 4
q2_idx = n // 2
q3_idx = (3 * n) // 4
q1 = get_cutoff(q1_idx)
q2 = get_cutoff(q2_idx)
q3 = get_cutoff(q3_idx)
return (q1, q2, q3)
def _coloured_block(self, count: int) -> str:
"""Get coloured block for commit count.
Colour mapping:
- 0 commits: gray (colour 0)
- 0 < count < Q1: lightest green (colour 1)
- Q1 <= count < Q2: medium-light green (colour 2)
- Q2 <= count < Q3: medium-dark green (colour 3)
- count >= Q3: darkest green (colour 4)
"""
if count == 0:
colour_idx = 0
elif count < self.colour_cutoffs[0]:
colour_idx = 1
elif count < self.colour_cutoffs[1]:
colour_idx = 2
elif count < self.colour_cutoffs[2]:
colour_idx = 3
else:
colour_idx = 4
r, g, b = self.COLOUR_SCHEME[colour_idx]
return f"\033[38;2;{r};{g};{b}m{self.BLOCK}\033[0m"
def _bold(self, text: str) -> str:
return f"\033[1m{text}\033[0m"
def _muted(self, text: str) -> str:
return f"\033[90m{text}\033[0m"
def main() -> None:
config = Config()
parser = argparse.ArgumentParser(
description="Commitose: Markov chain-based commit history simulator"
)
# Date arguments
parser.add_argument(
"--start-date",
help="simulation start date (format: YYYY-MM-DD, default: 365 days ago)",
)
parser.add_argument(
"--end-date",
help="simulation end date (format: YYYY-MM-DD, default: today)",
)
# Git arguments
parser.add_argument(
"--repo-path",
type=Path,
help=f"path to Git repository (default: {config.repo_path})",
)
parser.add_argument("--user-name", help="Git author name")
parser.add_argument("--user-email", help="Git author email")
parser.add_argument("--branch", help=f"Git branch name (default: {config.branch})")
# Generation arguments
parser.add_argument("--seed", type=int, help="random seed for reproducibility")
parser.add_argument(
"--break",
nargs="*",
action="extend",
dest="breaks",
help="scale average commits over a period by a factor (START-DATE:END-DATE[:FACTOR], factor default: 0)",
)
# Configuration file
parser.add_argument("--config", type=Path, help="load configuration from TOML")
# Runtime options
parser.add_argument(
"--dry-run",
action="store_true",
help="Generate schedule without making commits",
default=None,
)
args = parser.parse_args()
try:
if args.config:
config.load_toml(args.config)
# CLI arguments overwrite config file