gitrings 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- gitrings/__init__.py +0 -0
- gitrings/cli.py +57 -0
- gitrings/github.py +145 -0
- gitrings/gitlab.py +30 -0
- gitrings/rings.py +67 -0
- gitrings/story.html +1338 -0
- gitrings/story.py +85 -0
- gitrings/svg.py +147 -0
- gitrings-0.1.0.dist-info/METADATA +84 -0
- gitrings-0.1.0.dist-info/RECORD +13 -0
- gitrings-0.1.0.dist-info/WHEEL +4 -0
- gitrings-0.1.0.dist-info/entry_points.txt +2 -0
- gitrings-0.1.0.dist-info/licenses/LICENSE +21 -0
gitrings/__init__.py
ADDED
|
File without changes
|
gitrings/cli.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
import os
|
|
3
|
+
import subprocess
|
|
4
|
+
from datetime import date
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
from gitrings import gitlab, story, svg
|
|
8
|
+
from gitrings.github import checkup, fetch
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def main() -> None:
|
|
12
|
+
parser = argparse.ArgumentParser(
|
|
13
|
+
prog="gitrings", description="Draw your GitHub years as tree rings."
|
|
14
|
+
)
|
|
15
|
+
parser.add_argument("login", nargs="?")
|
|
16
|
+
parser.add_argument("--theme", choices=sorted(svg.THEMES), default="light")
|
|
17
|
+
parser.add_argument("--out", type=Path, default=Path("gitrings.svg"))
|
|
18
|
+
parser.add_argument("--story", type=Path, help="also write the animated year story")
|
|
19
|
+
parser.add_argument("--vs", metavar="LOGIN", help="also draw your rings next to LOGIN's")
|
|
20
|
+
parser.add_argument("--forest", nargs="+", metavar="LOGIN", help="also draw your team's forest")
|
|
21
|
+
parser.add_argument("--gitlab", metavar="USER", help="also count USER's GitLab events")
|
|
22
|
+
parser.add_argument("--doctor", action="store_true", help="check token, SSO and git email")
|
|
23
|
+
args = parser.parse_args()
|
|
24
|
+
if not (args.login or args.doctor):
|
|
25
|
+
parser.error("the following arguments are required: login")
|
|
26
|
+
token = (
|
|
27
|
+
os.environ.get("GITHUB_TOKEN")
|
|
28
|
+
or subprocess.run(
|
|
29
|
+
["gh", "auth", "token"], capture_output=True, text=True, check=True
|
|
30
|
+
).stdout.strip()
|
|
31
|
+
)
|
|
32
|
+
if args.doctor:
|
|
33
|
+
git = subprocess.run(["git", "config", "user.email"], capture_output=True, text=True)
|
|
34
|
+
findings = checkup(token, git.stdout.strip())
|
|
35
|
+
for ok, finding in findings:
|
|
36
|
+
print("ok " if ok else "fix", finding)
|
|
37
|
+
raise SystemExit(0 if all(ok for ok, _ in findings) else 1)
|
|
38
|
+
profile, rings = fetch(args.login, token, date.today())
|
|
39
|
+
if args.gitlab:
|
|
40
|
+
lab = os.environ.get("GITLAB_URL", "https://gitlab.com")
|
|
41
|
+
rings = gitlab.add(rings, args.gitlab, os.environ.get("GITLAB_TOKEN", ""), lab)
|
|
42
|
+
args.out.write_text(svg.render(args.login, rings, args.theme))
|
|
43
|
+
print(f"{args.out}: {len(rings)} rings")
|
|
44
|
+
if args.story:
|
|
45
|
+
args.story.write_text(story.render(profile, rings))
|
|
46
|
+
print(f"{args.story}: {rings[-1].year} story")
|
|
47
|
+
if args.vs:
|
|
48
|
+
_, other = fetch(args.vs, token, date.today())
|
|
49
|
+
pair = args.out.with_stem(f"{args.out.stem}-vs-{args.vs}")
|
|
50
|
+
pair.write_text(svg.forest([(args.login, rings), (args.vs, other)], args.theme))
|
|
51
|
+
print(f"{pair}: {args.login} vs {args.vs}")
|
|
52
|
+
if args.forest:
|
|
53
|
+
trees = [(args.login, rings)]
|
|
54
|
+
trees += [(login, fetch(login, token, date.today())[1]) for login in args.forest]
|
|
55
|
+
grove = args.out.with_stem(f"{args.out.stem}-forest")
|
|
56
|
+
grove.write_text(svg.forest(trees, args.theme))
|
|
57
|
+
print(f"{grove}: {len(trees)} trees")
|
gitrings/github.py
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import urllib.error
|
|
3
|
+
import urllib.request
|
|
4
|
+
from datetime import date
|
|
5
|
+
from email.message import Message
|
|
6
|
+
from itertools import batched
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from gitrings.rings import Profile, Ring
|
|
10
|
+
|
|
11
|
+
API = "https://api.github.com/graphql"
|
|
12
|
+
REST = "https://api.github.com"
|
|
13
|
+
PROFILE = """
|
|
14
|
+
query($login: String!, $from: DateTime!, $to: DateTime!) {
|
|
15
|
+
user(login: $login) {
|
|
16
|
+
createdAt name avatarUrl
|
|
17
|
+
contributionsCollection(from: $from, to: $to) {
|
|
18
|
+
totalCommitContributions totalPullRequestContributions
|
|
19
|
+
totalPullRequestReviewContributions totalIssueContributions
|
|
20
|
+
totalRepositoryContributions restrictedContributionsCount
|
|
21
|
+
commitContributionsByRepository(maxRepositories: 100) {
|
|
22
|
+
contributions { totalCount }
|
|
23
|
+
repository { isPrivate primaryLanguage { name color } }
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
"""
|
|
29
|
+
CALENDAR = """
|
|
30
|
+
y{end.year}: contributionsCollection(from: "{end.year}-01-01T00:00:00Z", to: "{end}T23:59:59Z") {{
|
|
31
|
+
contributionCalendar {{ weeks {{ contributionDays {{ date contributionCount }} }} }}
|
|
32
|
+
}}
|
|
33
|
+
"""
|
|
34
|
+
KINDS = {
|
|
35
|
+
"commits": "totalCommitContributions",
|
|
36
|
+
"pullRequests": "totalPullRequestContributions",
|
|
37
|
+
"reviews": "totalPullRequestReviewContributions",
|
|
38
|
+
"issues": "totalIssueContributions",
|
|
39
|
+
"repositories": "totalRepositoryContributions",
|
|
40
|
+
"restricted": "restrictedContributionsCount",
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _query(token: str, query: str, variables: dict[str, str]) -> Any:
|
|
45
|
+
request = urllib.request.Request(
|
|
46
|
+
API,
|
|
47
|
+
data=json.dumps({"query": query, "variables": variables}).encode(),
|
|
48
|
+
headers={"Authorization": f"bearer {token}", "User-Agent": "gitrings"},
|
|
49
|
+
)
|
|
50
|
+
with urllib.request.urlopen(request) as response:
|
|
51
|
+
body = json.load(response)
|
|
52
|
+
if "errors" in body:
|
|
53
|
+
raise RuntimeError(body["errors"])
|
|
54
|
+
return body["data"]
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _window(login: str, year: int, end: date) -> dict[str, str]:
|
|
58
|
+
return {"login": login, "from": f"{year}-01-01T00:00:00Z", "to": f"{end}T23:59:59Z"}
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def fetch(login: str, token: str, today: date) -> tuple[Profile, list[Ring]]:
|
|
62
|
+
user = _query(token, PROFILE, _window(login, today.year, today))["user"]
|
|
63
|
+
collection = user["contributionsCollection"]
|
|
64
|
+
languages: dict[str, tuple[str, int]] = {}
|
|
65
|
+
private = 0
|
|
66
|
+
for entry in collection["commitContributionsByRepository"]:
|
|
67
|
+
count = entry["contributions"]["totalCount"]
|
|
68
|
+
private += count if entry["repository"]["isPrivate"] else 0
|
|
69
|
+
language = entry["repository"]["primaryLanguage"]
|
|
70
|
+
if language:
|
|
71
|
+
color, total = languages.get(language["name"], (language["color"] or "#888888", 0))
|
|
72
|
+
languages[language["name"]] = (color, total + count)
|
|
73
|
+
profile = Profile(
|
|
74
|
+
login=login,
|
|
75
|
+
name=user["name"] or login,
|
|
76
|
+
avatar=user["avatarUrl"],
|
|
77
|
+
kinds={kind: collection[field] for kind, field in KINDS.items()},
|
|
78
|
+
languages=sorted(
|
|
79
|
+
((name, color, total) for name, (color, total) in languages.items()),
|
|
80
|
+
key=lambda language: -language[2],
|
|
81
|
+
),
|
|
82
|
+
private_commits=private,
|
|
83
|
+
)
|
|
84
|
+
ends = [
|
|
85
|
+
min(today, date(year, 12, 31)) for year in range(int(user["createdAt"][:4]), today.year + 1)
|
|
86
|
+
]
|
|
87
|
+
calendars: dict[str, Any] = {}
|
|
88
|
+
for chunk in batched(ends, 3):
|
|
89
|
+
fields = "".join(CALENDAR.format(end=end) for end in chunk)
|
|
90
|
+
query = f"query($login: String!) {{ user(login: $login) {{ {fields} }} }}"
|
|
91
|
+
calendars |= _query(token, query, {"login": login})["user"]
|
|
92
|
+
rings = []
|
|
93
|
+
for end in ends:
|
|
94
|
+
weeks = calendars[f"y{end.year}"]["contributionCalendar"]["weeks"]
|
|
95
|
+
days = tuple(
|
|
96
|
+
day["contributionCount"]
|
|
97
|
+
for week in weeks
|
|
98
|
+
for day in week["contributionDays"]
|
|
99
|
+
if day["date"].startswith(str(end.year)) and day["date"] <= end.isoformat()
|
|
100
|
+
)
|
|
101
|
+
rings.append(Ring(end.year, days))
|
|
102
|
+
return profile, rings
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _get(token: str, path: str) -> tuple[Any, Message]:
|
|
106
|
+
request = urllib.request.Request(
|
|
107
|
+
REST + path, headers={"Authorization": f"bearer {token}", "User-Agent": "gitrings"}
|
|
108
|
+
)
|
|
109
|
+
with urllib.request.urlopen(request) as response:
|
|
110
|
+
return json.load(response), response.headers
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def checkup(token: str, git_email: str) -> list[tuple[bool, str]]:
|
|
114
|
+
"""What keeps work out of the rings: token scopes, SSO authorisation, the git commit email."""
|
|
115
|
+
listed = _get(token, "/user")[1].get("X-OAuth-Scopes")
|
|
116
|
+
scopes = {scope.strip() for scope in (listed or "").split(",")}
|
|
117
|
+
scopes |= {"read:user"} if "user" in scopes else set()
|
|
118
|
+
missing = " and ".join(sorted({"repo", "read:user"} - scopes))
|
|
119
|
+
if listed is None:
|
|
120
|
+
findings = [(False, "fine-grained and app tokens hide their scopes: use a classic token")]
|
|
121
|
+
elif missing:
|
|
122
|
+
findings = [(False, f"token lacks {missing}: private work counts only as a total")]
|
|
123
|
+
else:
|
|
124
|
+
findings = [(True, "token has repo and read:user")]
|
|
125
|
+
sso = _get(token, "/user/repos?per_page=1")[1].get("X-GitHub-SSO", "")
|
|
126
|
+
if orgs := sso.partition("organizations=")[2]:
|
|
127
|
+
blocked = f"{len(orgs.split(','))} organisation(s)"
|
|
128
|
+
findings.append(
|
|
129
|
+
(False, f"SSO keeps out {blocked}: authorise at https://github.com/settings/tokens")
|
|
130
|
+
)
|
|
131
|
+
else:
|
|
132
|
+
findings.append((True, "no organisation is waiting for SSO authorisation"))
|
|
133
|
+
try:
|
|
134
|
+
emails = _get(token, "/user/emails")[0]
|
|
135
|
+
except urllib.error.HTTPError:
|
|
136
|
+
findings.append((False, "the token needs user:email to check your git email"))
|
|
137
|
+
return findings
|
|
138
|
+
if git_email.lower() in {entry["email"].lower() for entry in emails if entry["verified"]}:
|
|
139
|
+
findings.append((True, f"git commits as {git_email}, a verified email of yours"))
|
|
140
|
+
else:
|
|
141
|
+
unknown = git_email or "(no user.email)"
|
|
142
|
+
findings.append(
|
|
143
|
+
(False, f"commits as {unknown} go uncounted: https://github.com/settings/emails")
|
|
144
|
+
)
|
|
145
|
+
return findings
|
gitrings/gitlab.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import urllib.request
|
|
3
|
+
from collections import Counter
|
|
4
|
+
from datetime import date, timedelta
|
|
5
|
+
|
|
6
|
+
from gitrings.rings import Ring
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def add(rings: list[Ring], user: str, token: str, base: str) -> list[Ring]:
|
|
10
|
+
"""Adds a GitLab user's events per day, counted as GitLab's calendar does; it keeps 3 years."""
|
|
11
|
+
counts: Counter[str] = Counter()
|
|
12
|
+
page = "1"
|
|
13
|
+
while page:
|
|
14
|
+
request = urllib.request.Request(
|
|
15
|
+
f"{base}/api/v4/users/{user}/events?per_page=100&page={page}",
|
|
16
|
+
headers={"User-Agent": "gitrings"} | ({"PRIVATE-TOKEN": token} if token else {}),
|
|
17
|
+
)
|
|
18
|
+
with urllib.request.urlopen(request) as response:
|
|
19
|
+
counts.update(event["created_at"][:10] for event in json.load(response))
|
|
20
|
+
page = response.headers.get("X-Next-Page", "")
|
|
21
|
+
return [
|
|
22
|
+
Ring(
|
|
23
|
+
ring.year,
|
|
24
|
+
tuple(
|
|
25
|
+
count + counts[(date(ring.year, 1, 1) + timedelta(day)).isoformat()]
|
|
26
|
+
for day, count in enumerate(ring.days)
|
|
27
|
+
),
|
|
28
|
+
)
|
|
29
|
+
for ring in rings
|
|
30
|
+
]
|
gitrings/rings.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
from calendar import isleap
|
|
2
|
+
from dataclasses import dataclass
|
|
3
|
+
from math import sqrt
|
|
4
|
+
|
|
5
|
+
SWAY = 0.4
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
@dataclass(frozen=True)
|
|
9
|
+
class Ring:
|
|
10
|
+
year: int
|
|
11
|
+
days: tuple[int, ...]
|
|
12
|
+
|
|
13
|
+
@property
|
|
14
|
+
def total(self) -> int:
|
|
15
|
+
return sum(self.days)
|
|
16
|
+
|
|
17
|
+
@property
|
|
18
|
+
def length(self) -> int:
|
|
19
|
+
return 366 if isleap(self.year) else 365
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass(frozen=True)
|
|
23
|
+
class Profile:
|
|
24
|
+
login: str
|
|
25
|
+
name: str
|
|
26
|
+
avatar: str
|
|
27
|
+
kinds: dict[str, int]
|
|
28
|
+
languages: list[tuple[str, str, int]]
|
|
29
|
+
private_commits: int
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def widths(rings: list[Ring], span: float, min_width: float) -> list[float]:
|
|
33
|
+
weights = [sqrt(ring.total) for ring in rings]
|
|
34
|
+
spare = span - min_width * len(rings)
|
|
35
|
+
scale = spare / sum(weights) if sum(weights) else 0.0
|
|
36
|
+
return [min_width + weight * scale for weight in weights]
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _smooth(values: list[float], window: int) -> list[float]:
|
|
40
|
+
half = window // 2
|
|
41
|
+
size = len(values)
|
|
42
|
+
return [
|
|
43
|
+
sum(values[(i + k) % size] for k in range(-half, half + 1)) / (2 * half + 1)
|
|
44
|
+
for i in range(size)
|
|
45
|
+
]
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def growth(ring: Ring, samples: int) -> list[float]:
|
|
49
|
+
"""Thickness factor per angle, mean 1: busy weeks bulge, quiet weeks and days ahead thin."""
|
|
50
|
+
days = [j * ring.length // samples for j in range(samples)]
|
|
51
|
+
counts = [float(ring.days[day]) if day < len(ring.days) else 0.0 for day in days]
|
|
52
|
+
activity = _smooth(_smooth(counts, 21), 21)
|
|
53
|
+
top = max(activity) or 1.0
|
|
54
|
+
mean = sum(activity) / samples / top
|
|
55
|
+
return [1 + SWAY * (value / top - mean) for value in activity]
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def boundaries(
|
|
59
|
+
rings: list[Ring], pith: float, span: float, min_width: float, samples: int
|
|
60
|
+
) -> list[list[float]]:
|
|
61
|
+
radius = [pith] * samples
|
|
62
|
+
outer = []
|
|
63
|
+
for ring, width in zip(rings, widths(rings, span, min_width), strict=True):
|
|
64
|
+
radius = [r + width * g for r, g in zip(radius, growth(ring, samples), strict=True)]
|
|
65
|
+
outer.append(radius)
|
|
66
|
+
scale = min(1.0, (pith + span) / max(outer[-1]))
|
|
67
|
+
return [[r * scale for r in edge] for edge in outer]
|