-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgit_activity_print.py
More file actions
159 lines (127 loc) · 5 KB
/
Copy pathgit_activity_print.py
File metadata and controls
159 lines (127 loc) · 5 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
#!/usr/bin/env python3
"""Print a live Git activity brief on the S01 thermal printer.
All content comes from the local repository at runtime: current branch, status,
recent commits, and changed-file counts. There are no curated topics or canned
data entries.
Examples:
python git_activity_print.py
python git_activity_print.py --commits 8
python git_activity_print.py --no-print
"""
from __future__ import annotations
import argparse
from collections import Counter
from dataclasses import dataclass
from datetime import datetime
from pathlib import Path
import subprocess
from print_common import ROOT, Card
@dataclass(frozen=True)
class Commit:
sha: str
date: str
subject: str
def git(args: list[str]) -> str:
result = subprocess.run(
["git", *args],
cwd=ROOT,
check=True,
text=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
return result.stdout.strip()
def safe_git(args: list[str], fallback: str = "") -> str:
try:
return git(args)
except subprocess.CalledProcessError:
return fallback
def branch_name() -> str:
return safe_git(["branch", "--show-current"], "(detached)")
def status_lines() -> list[str]:
out = safe_git(["status", "--short"])
return [line for line in out.splitlines() if line.strip()]
def recent_commits(count: int) -> list[Commit]:
fmt = "%h%x09%ad%x09%s"
out = safe_git(["log", f"-{count}", f"--pretty=format:{fmt}", "--date=short"])
commits: list[Commit] = []
for line in out.splitlines():
parts = line.split("\t", 2)
if len(parts) == 3:
commits.append(Commit(sha=parts[0], date=parts[1], subject=parts[2]))
return commits
def file_kind(path: str) -> str:
suffix = Path(path).suffix.lower()
if suffix in {".py", ".ps1", ".sh", ".js", ".ts", ".cs"}:
return "code"
if suffix in {".md", ".txt", ".rst"}:
return "docs"
if suffix in {".png", ".jpg", ".jpeg", ".gif", ".webp"}:
return "images"
if suffix in {".json", ".toml", ".yaml", ".yml", ".ini"}:
return "config"
return "other"
def summarize_status(lines: list[str]) -> tuple[Counter[str], Counter[str]]:
states: Counter[str] = Counter()
kinds: Counter[str] = Counter()
for line in lines:
state = line[:2].strip() or "?"
path = line[3:].strip()
if " -> " in path:
path = path.rsplit(" -> ", 1)[-1]
states[state] += 1
kinds[file_kind(path)] += 1
return states, kinds
def short_path(path: str, limit: int = 34) -> str:
if len(path) <= limit:
return path
return "..." + path[-(limit - 3):]
def main() -> int:
parser = argparse.ArgumentParser(description="Print a live Git activity brief on the S01 thermal printer.")
parser.add_argument("--commits", type=int, default=5, help="Number of recent commits to include.")
parser.add_argument("--files", type=int, default=8, help="Number of changed files to list.")
parser.add_argument("--out", type=Path, default=ROOT / "git_activity.png")
parser.add_argument("--darkness", type=int, choices=range(1, 6), default=3)
parser.add_argument("--bottom-feed", type=int, default=24)
parser.add_argument("--no-print", action="store_true")
args = parser.parse_args()
branch = branch_name()
lines = status_lines()
commits = recent_commits(max(1, args.commits))
states, kinds = summarize_status(lines)
print("Git activity brief")
print(f" branch: {branch}")
print(f" changed files: {len(lines)}")
for commit in commits[:3]:
print(f" {commit.sha} {commit.subject}")
card = Card()
card.title("GIT ACTIVITY")
card.kv("Branch", branch or "(none)", size=13)
card.kv("Changed files", str(len(lines)), size=13)
card.kv("Recent commits", str(len(commits)), size=13)
card.gap(2).divider()
card.line("WORKTREE", size=13, bold=True)
if lines:
kind_text = ", ".join(f"{name}:{count}" for name, count in sorted(kinds.items()))
state_text = ", ".join(f"{name}:{count}" for name, count in sorted(states.items()))
card.para(f"Types: {kind_text}", size=12)
card.para(f"States: {state_text}", size=12)
card.gap(2)
for line in lines[: max(1, args.files)]:
card.para(short_path(line), size=12)
if len(lines) > args.files:
card.para(f"... and {len(lines) - args.files} more", size=12)
else:
card.para("Working tree is clean.", size=13, bold=True, center=True)
card.gap(4).divider()
card.line("RECENT COMMITS", size=13, bold=True)
if commits:
for commit in commits:
card.para(f"{commit.sha} {commit.date}", size=12)
card.para(commit.subject, size=13, bold=True)
else:
card.para("No commits found.", size=13)
card.footer("local git", datetime.now().strftime("%Y-%m-%d %H:%M"))
return card.finish(args.out, args.bottom_feed, args.darkness, do_print=not args.no_print)
if __name__ == "__main__":
raise SystemExit(main())