gitlytics 0.3.1__tar.gz → 0.4.0__tar.gz
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.
- {gitlytics-0.3.1 → gitlytics-0.4.0}/PKG-INFO +37 -5
- {gitlytics-0.3.1 → gitlytics-0.4.0}/README.md +35 -3
- {gitlytics-0.3.1 → gitlytics-0.4.0}/pyproject.toml +5 -3
- {gitlytics-0.3.1 → gitlytics-0.4.0}/src/gitlytics/__init__.py +18 -4
- {gitlytics-0.3.1 → gitlytics-0.4.0}/src/gitlytics/api.py +34 -1
- {gitlytics-0.3.1 → gitlytics-0.4.0}/src/gitlytics/cli.py +29 -0
- {gitlytics-0.3.1 → gitlytics-0.4.0}/src/gitlytics/core.py +164 -0
- gitlytics-0.4.0/src/gitlytics/static/assets/CardModal-DmHoAnrK.js +1 -0
- gitlytics-0.4.0/src/gitlytics/static/assets/ExportModal-BF_sosAP.js +1 -0
- gitlytics-0.4.0/src/gitlytics/static/assets/exports-CrU6Ta4Q.js +14 -0
- gitlytics-0.4.0/src/gitlytics/static/assets/index-D5qdeNvu.css +1 -0
- gitlytics-0.4.0/src/gitlytics/static/assets/index-hb6NMx5Y.js +119 -0
- gitlytics-0.3.1/src/gitlytics/static/assets/index.es-D93aAsH7.js → gitlytics-0.4.0/src/gitlytics/static/assets/index.es-ComYkcii.js +1 -1
- gitlytics-0.3.1/src/gitlytics/static/assets/jspdf.es.min-BZAHn0Ub.js → gitlytics-0.4.0/src/gitlytics/static/assets/jspdf.es.min-vktmDsgQ.js +3 -3
- {gitlytics-0.3.1 → gitlytics-0.4.0}/src/gitlytics/static/index.html +3 -2
- {gitlytics-0.3.1 → gitlytics-0.4.0}/src/gitlytics.egg-info/PKG-INFO +37 -5
- {gitlytics-0.3.1 → gitlytics-0.4.0}/src/gitlytics.egg-info/SOURCES.txt +8 -4
- gitlytics-0.4.0/tests/test_star_history.py +154 -0
- gitlytics-0.3.1/src/gitlytics/static/assets/index-CbK1npG-.js +0 -127
- gitlytics-0.3.1/src/gitlytics/static/assets/index-ClrHOmX2.css +0 -1
- {gitlytics-0.3.1 → gitlytics-0.4.0}/LICENSE +0 -0
- {gitlytics-0.3.1 → gitlytics-0.4.0}/setup.cfg +0 -0
- {gitlytics-0.3.1 → gitlytics-0.4.0}/src/gitlytics/__main__.py +0 -0
- {gitlytics-0.3.1 → gitlytics-0.4.0}/src/gitlytics/automation.py +0 -0
- {gitlytics-0.3.1 → gitlytics-0.4.0}/src/gitlytics/process.py +0 -0
- {gitlytics-0.3.1 → gitlytics-0.4.0}/src/gitlytics/static/android-chrome-192x192.png +0 -0
- {gitlytics-0.3.1 → gitlytics-0.4.0}/src/gitlytics/static/android-chrome-512x512.png +0 -0
- {gitlytics-0.3.1 → gitlytics-0.4.0}/src/gitlytics/static/apple-touch-icon.png +0 -0
- {gitlytics-0.3.1 → gitlytics-0.4.0}/src/gitlytics/static/assets/html2canvas-pro.esm-9xys3ejh.js +0 -0
- {gitlytics-0.3.1 → gitlytics-0.4.0}/src/gitlytics/static/assets/html2canvas.esm-DXEQVQnt.js +0 -0
- {gitlytics-0.3.1 → gitlytics-0.4.0}/src/gitlytics/static/assets/purify.es-CC4Brkr_.js +0 -0
- {gitlytics-0.3.1 → gitlytics-0.4.0}/src/gitlytics/static/favicon-16x16.png +0 -0
- {gitlytics-0.3.1 → gitlytics-0.4.0}/src/gitlytics/static/favicon-32x32.png +0 -0
- {gitlytics-0.3.1 → gitlytics-0.4.0}/src/gitlytics/static/favicon-48x48.png +0 -0
- {gitlytics-0.3.1 → gitlytics-0.4.0}/src/gitlytics/static/favicon.ico +0 -0
- {gitlytics-0.3.1 → gitlytics-0.4.0}/src/gitlytics/static/gitlytics-logo.png +0 -0
- {gitlytics-0.3.1 → gitlytics-0.4.0}/src/gitlytics/static/google-search-icon-48x48.png +0 -0
- {gitlytics-0.3.1 → gitlytics-0.4.0}/src/gitlytics/static/google-search-icon.png +0 -0
- {gitlytics-0.3.1 → gitlytics-0.4.0}/src/gitlytics/static/robots.txt +0 -0
- {gitlytics-0.3.1 → gitlytics-0.4.0}/src/gitlytics/static/sitemap.xml +0 -0
- {gitlytics-0.3.1 → gitlytics-0.4.0}/src/gitlytics.egg-info/dependency_links.txt +0 -0
- {gitlytics-0.3.1 → gitlytics-0.4.0}/src/gitlytics.egg-info/entry_points.txt +0 -0
- {gitlytics-0.3.1 → gitlytics-0.4.0}/src/gitlytics.egg-info/requires.txt +1 -1
- {gitlytics-0.3.1 → gitlytics-0.4.0}/src/gitlytics.egg-info/top_level.txt +0 -0
- {gitlytics-0.3.1 → gitlytics-0.4.0}/tests/test_api.py +0 -0
- {gitlytics-0.3.1 → gitlytics-0.4.0}/tests/test_automation.py +0 -0
- {gitlytics-0.3.1 → gitlytics-0.4.0}/tests/test_cli.py +0 -0
- {gitlytics-0.3.1 → gitlytics-0.4.0}/tests/test_core.py +0 -0
- {gitlytics-0.3.1 → gitlytics-0.4.0}/tests/test_process.py +0 -0
- {gitlytics-0.3.1 → gitlytics-0.4.0}/tests/test_username.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: gitlytics
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.4.0
|
|
4
4
|
Summary: Monitor and automate your GitHub repository traffic analytics.
|
|
5
5
|
Author-email: Ameya Chopade <ameyaccod171@gmail.com>
|
|
6
6
|
License: Apache-2.0
|
|
@@ -17,7 +17,6 @@ Description-Content-Type: text/markdown
|
|
|
17
17
|
License-File: LICENSE
|
|
18
18
|
Requires-Dist: requests>=2.32.0
|
|
19
19
|
Requires-Dist: pandas>=2.2.0
|
|
20
|
-
Requires-Dist: python-dotenv>=1.0.1
|
|
21
20
|
Requires-Dist: croniter>=2.0.0
|
|
22
21
|
Provides-Extra: dashboard
|
|
23
22
|
Requires-Dist: fastapi>=0.111.0; extra == "dashboard"
|
|
@@ -28,6 +27,7 @@ Requires-Dist: pytest>=8.0.0; extra == "dev"
|
|
|
28
27
|
Requires-Dist: pytest-cov>=5.0.0; extra == "dev"
|
|
29
28
|
Requires-Dist: httpx>=0.27.0; extra == "dev"
|
|
30
29
|
Requires-Dist: anyio[trio]>=4.0.0; extra == "dev"
|
|
30
|
+
Requires-Dist: python-dotenv>=1.0.1; extra == "dev"
|
|
31
31
|
Dynamic: license-file
|
|
32
32
|
|
|
33
33
|
<div align="center">
|
|
@@ -78,14 +78,16 @@ Dynamic: license-file
|
|
|
78
78
|
- [🚨 The 14-Day Catch (And How We Fix It)](#-the-14-day-catch-and-how-we-fix-it)
|
|
79
79
|
- [🛠️ Installation](#installation)
|
|
80
80
|
- [🔑 Generating a GitHub Personal Access Token](#generating-a-github-personal-access-token)
|
|
81
|
-
- [⌨️ The
|
|
81
|
+
- [⌨️ The 4 Core CLI Commands](#the-4-core-cli-commands)
|
|
82
82
|
- [1️⃣ `gitlytics fetch` (Live Terminal Data)](#1-gitlytics-fetch-live-terminal-data)
|
|
83
83
|
- [2️⃣ `gitlytics sync` (Background Database Cron)](#2-gitlytics-sync-background-database-cron)
|
|
84
84
|
- [3️⃣ `gitlytics dashboard` (React Web UI)](#3-gitlytics-dashboard-react-web-ui)
|
|
85
|
+
- [4️⃣ `gitlytics stars` (Stargazer History)](#4-gitlytics-stars-stargazer-history)
|
|
85
86
|
- [🐍 Native Python API](#native-python-api)
|
|
86
87
|
- [1️⃣ `gitlytics.fetch_traffic()`](#1-gitlyticsfetch_traffic)
|
|
87
88
|
- [2️⃣ `gitlytics.sync()`](#2-gitlyticssync)
|
|
88
89
|
- [3️⃣ `gitlytics.serve_dashboard()`](#3-gitlyticsserve_dashboard)
|
|
90
|
+
- [4️⃣ `gitlytics.fetch_star_history()`](#4-gitlyticsfetch_star_history)
|
|
89
91
|
- [📊 CSV Output Columns](#csv-output-columns)
|
|
90
92
|
- [🌟 Show Your Support](#show-your-support)
|
|
91
93
|
- [📄 License](#license)
|
|
@@ -134,9 +136,9 @@ To use the tools, you'll need a GitHub token.
|
|
|
134
136
|
|
|
135
137
|
---
|
|
136
138
|
|
|
137
|
-
## ⌨️ The
|
|
139
|
+
## ⌨️ The 4 Core CLI Commands
|
|
138
140
|
|
|
139
|
-
Gitlytics is powered by
|
|
141
|
+
Gitlytics is powered by 4 massive command-line tools. You can run them anywhere in your terminal.
|
|
140
142
|
|
|
141
143
|
### 1️⃣ `gitlytics fetch` (Live Terminal Data)
|
|
142
144
|
Fetch your live 14-day traffic and print a beautiful ASCII table directly in your console.
|
|
@@ -170,6 +172,13 @@ gitlytics dashboard
|
|
|
170
172
|
> gitlytics dashboard --token "ghp_xxx" --data-dir "./data"
|
|
171
173
|
> ```
|
|
172
174
|
|
|
175
|
+
### 4️⃣ `gitlytics stars` (Stargazer History)
|
|
176
|
+
Fetch the historical cumulative stargazer growth trajectory for a repository.
|
|
177
|
+
```bash
|
|
178
|
+
# Fetch and print star history table
|
|
179
|
+
gitlytics stars owner/repo --token ghp_your_token
|
|
180
|
+
```
|
|
181
|
+
|
|
173
182
|
---
|
|
174
183
|
|
|
175
184
|
## 🐍 Native Python API
|
|
@@ -279,6 +288,29 @@ gitlytics.serve_dashboard(
|
|
|
279
288
|
|
|
280
289
|
---
|
|
281
290
|
|
|
291
|
+
### 4️⃣ `gitlytics.fetch_star_history()`
|
|
292
|
+
Fetches a list of cumulative star counts per date for a given repository.
|
|
293
|
+
|
|
294
|
+
```python
|
|
295
|
+
import gitlytics
|
|
296
|
+
|
|
297
|
+
# Fetch stargazer history timeline
|
|
298
|
+
points = gitlytics.fetch_star_history(
|
|
299
|
+
owner="ameyac11",
|
|
300
|
+
repo="gitlytics",
|
|
301
|
+
token="ghp_your_token" # Optional for public repos, recommended to avoid rate limits
|
|
302
|
+
)
|
|
303
|
+
```
|
|
304
|
+
|
|
305
|
+
#### ⚙️ Parameters:
|
|
306
|
+
| Parameter | Type | Default | Description |
|
|
307
|
+
|---|---|---|---|
|
|
308
|
+
| `owner` | `str` | *Required* | Owner of the repository. |
|
|
309
|
+
| `repo` | `str` | *Required* | Repository name. |
|
|
310
|
+
| `token` | `str` | `None` | Optional GitHub Personal Access Token. |
|
|
311
|
+
|
|
312
|
+
---
|
|
313
|
+
|
|
282
314
|
|
|
283
315
|
## 📊 CSV Output Columns
|
|
284
316
|
|
|
@@ -46,14 +46,16 @@
|
|
|
46
46
|
- [🚨 The 14-Day Catch (And How We Fix It)](#-the-14-day-catch-and-how-we-fix-it)
|
|
47
47
|
- [🛠️ Installation](#installation)
|
|
48
48
|
- [🔑 Generating a GitHub Personal Access Token](#generating-a-github-personal-access-token)
|
|
49
|
-
- [⌨️ The
|
|
49
|
+
- [⌨️ The 4 Core CLI Commands](#the-4-core-cli-commands)
|
|
50
50
|
- [1️⃣ `gitlytics fetch` (Live Terminal Data)](#1-gitlytics-fetch-live-terminal-data)
|
|
51
51
|
- [2️⃣ `gitlytics sync` (Background Database Cron)](#2-gitlytics-sync-background-database-cron)
|
|
52
52
|
- [3️⃣ `gitlytics dashboard` (React Web UI)](#3-gitlytics-dashboard-react-web-ui)
|
|
53
|
+
- [4️⃣ `gitlytics stars` (Stargazer History)](#4-gitlytics-stars-stargazer-history)
|
|
53
54
|
- [🐍 Native Python API](#native-python-api)
|
|
54
55
|
- [1️⃣ `gitlytics.fetch_traffic()`](#1-gitlyticsfetch_traffic)
|
|
55
56
|
- [2️⃣ `gitlytics.sync()`](#2-gitlyticssync)
|
|
56
57
|
- [3️⃣ `gitlytics.serve_dashboard()`](#3-gitlyticsserve_dashboard)
|
|
58
|
+
- [4️⃣ `gitlytics.fetch_star_history()`](#4-gitlyticsfetch_star_history)
|
|
57
59
|
- [📊 CSV Output Columns](#csv-output-columns)
|
|
58
60
|
- [🌟 Show Your Support](#show-your-support)
|
|
59
61
|
- [📄 License](#license)
|
|
@@ -102,9 +104,9 @@ To use the tools, you'll need a GitHub token.
|
|
|
102
104
|
|
|
103
105
|
---
|
|
104
106
|
|
|
105
|
-
## ⌨️ The
|
|
107
|
+
## ⌨️ The 4 Core CLI Commands
|
|
106
108
|
|
|
107
|
-
Gitlytics is powered by
|
|
109
|
+
Gitlytics is powered by 4 massive command-line tools. You can run them anywhere in your terminal.
|
|
108
110
|
|
|
109
111
|
### 1️⃣ `gitlytics fetch` (Live Terminal Data)
|
|
110
112
|
Fetch your live 14-day traffic and print a beautiful ASCII table directly in your console.
|
|
@@ -138,6 +140,13 @@ gitlytics dashboard
|
|
|
138
140
|
> gitlytics dashboard --token "ghp_xxx" --data-dir "./data"
|
|
139
141
|
> ```
|
|
140
142
|
|
|
143
|
+
### 4️⃣ `gitlytics stars` (Stargazer History)
|
|
144
|
+
Fetch the historical cumulative stargazer growth trajectory for a repository.
|
|
145
|
+
```bash
|
|
146
|
+
# Fetch and print star history table
|
|
147
|
+
gitlytics stars owner/repo --token ghp_your_token
|
|
148
|
+
```
|
|
149
|
+
|
|
141
150
|
---
|
|
142
151
|
|
|
143
152
|
## 🐍 Native Python API
|
|
@@ -247,6 +256,29 @@ gitlytics.serve_dashboard(
|
|
|
247
256
|
|
|
248
257
|
---
|
|
249
258
|
|
|
259
|
+
### 4️⃣ `gitlytics.fetch_star_history()`
|
|
260
|
+
Fetches a list of cumulative star counts per date for a given repository.
|
|
261
|
+
|
|
262
|
+
```python
|
|
263
|
+
import gitlytics
|
|
264
|
+
|
|
265
|
+
# Fetch stargazer history timeline
|
|
266
|
+
points = gitlytics.fetch_star_history(
|
|
267
|
+
owner="ameyac11",
|
|
268
|
+
repo="gitlytics",
|
|
269
|
+
token="ghp_your_token" # Optional for public repos, recommended to avoid rate limits
|
|
270
|
+
)
|
|
271
|
+
```
|
|
272
|
+
|
|
273
|
+
#### ⚙️ Parameters:
|
|
274
|
+
| Parameter | Type | Default | Description |
|
|
275
|
+
|---|---|---|---|
|
|
276
|
+
| `owner` | `str` | *Required* | Owner of the repository. |
|
|
277
|
+
| `repo` | `str` | *Required* | Repository name. |
|
|
278
|
+
| `token` | `str` | `None` | Optional GitHub Personal Access Token. |
|
|
279
|
+
|
|
280
|
+
---
|
|
281
|
+
|
|
250
282
|
|
|
251
283
|
## 📊 CSV Output Columns
|
|
252
284
|
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "gitlytics"
|
|
7
|
-
version = "0.
|
|
7
|
+
version = "0.4.0"
|
|
8
8
|
description = "Monitor and automate your GitHub repository traffic analytics."
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.9"
|
|
@@ -14,10 +14,11 @@ authors = [
|
|
|
14
14
|
]
|
|
15
15
|
# Fix #20: Add version lower-bounds to prevent silent breakage on old environments.
|
|
16
16
|
# These match the constraints already documented in requirements.txt.
|
|
17
|
+
# python-dotenv was removed from runtime deps — the library never reads .env;
|
|
18
|
+
# only tests use it, so it lives in the [dev] extra below.
|
|
17
19
|
dependencies = [
|
|
18
20
|
"requests>=2.32.0",
|
|
19
21
|
"pandas>=2.2.0",
|
|
20
|
-
"python-dotenv>=1.0.1",
|
|
21
22
|
"croniter>=2.0.0"
|
|
22
23
|
]
|
|
23
24
|
keywords = [
|
|
@@ -51,7 +52,8 @@ dev = [
|
|
|
51
52
|
"pytest>=8.0.0",
|
|
52
53
|
"pytest-cov>=5.0.0",
|
|
53
54
|
"httpx>=0.27.0", # required by FastAPI TestClient (used in test_api.py)
|
|
54
|
-
"anyio[trio]>=4.0.0"
|
|
55
|
+
"anyio[trio]>=4.0.0", # async test support
|
|
56
|
+
"python-dotenv>=1.0.1" # only tests load .env — runtime package doesn't
|
|
55
57
|
]
|
|
56
58
|
|
|
57
59
|
|
|
@@ -9,12 +9,26 @@ from pathlib import Path
|
|
|
9
9
|
|
|
10
10
|
# Single source of truth for the package version.
|
|
11
11
|
# Mirrors the version in pyproject.toml — keep them in sync.
|
|
12
|
-
__version__ = "0.
|
|
13
|
-
|
|
14
|
-
__all__ = [
|
|
12
|
+
__version__ = "0.4.0"
|
|
13
|
+
|
|
14
|
+
__all__ = [
|
|
15
|
+
"fetch_traffic",
|
|
16
|
+
"fetch_star_history",
|
|
17
|
+
"sync",
|
|
18
|
+
"serve_dashboard",
|
|
19
|
+
"__version__",
|
|
20
|
+
"GitHubRateLimitError",
|
|
21
|
+
"StarHistoryFetchError",
|
|
22
|
+
]
|
|
15
23
|
|
|
16
24
|
# Import the internal building blocks — users never call these directly
|
|
17
|
-
from .core import
|
|
25
|
+
from .core import (
|
|
26
|
+
fetch_traffic_data,
|
|
27
|
+
fetch_star_history,
|
|
28
|
+
print_repo_table,
|
|
29
|
+
GitHubRateLimitError,
|
|
30
|
+
StarHistoryFetchError,
|
|
31
|
+
)
|
|
18
32
|
from .automation import run_sync
|
|
19
33
|
from .process import build_json_payload
|
|
20
34
|
|
|
@@ -11,7 +11,7 @@ import uuid
|
|
|
11
11
|
from pathlib import Path
|
|
12
12
|
|
|
13
13
|
import pandas as pd
|
|
14
|
-
from fastapi import FastAPI, HTTPException, Body, File, UploadFile
|
|
14
|
+
from fastapi import FastAPI, HTTPException, Body, File, Header, Response, UploadFile
|
|
15
15
|
from fastapi.responses import FileResponse, JSONResponse
|
|
16
16
|
from fastapi.middleware.cors import CORSMiddleware
|
|
17
17
|
from fastapi.staticfiles import StaticFiles
|
|
@@ -23,6 +23,9 @@ from gitlytics.core import (
|
|
|
23
23
|
get_public_repos,
|
|
24
24
|
fetch_traffic_data,
|
|
25
25
|
fetch_deep_stats_for_top,
|
|
26
|
+
fetch_star_history,
|
|
27
|
+
GitHubRateLimitError,
|
|
28
|
+
StarHistoryFetchError,
|
|
26
29
|
)
|
|
27
30
|
from gitlytics.process import process_uploaded_csv, build_react_payload
|
|
28
31
|
|
|
@@ -208,6 +211,36 @@ def get_traffic(token: str = Body("", embed=True)):
|
|
|
208
211
|
return payload
|
|
209
212
|
|
|
210
213
|
|
|
214
|
+
# Star history endpoint — sampled star timeline for the SPA chart.
|
|
215
|
+
# Accepts the token via Authorization: Bearer header (PAT) so the chart
|
|
216
|
+
# can hit its own backend without exposing the token to the cloud.
|
|
217
|
+
# Falls back to GITLYTICS_TOKEN env so the local widget still works
|
|
218
|
+
# for users who stored their PAT in env instead of the LoginView.
|
|
219
|
+
@app.get("/api/star-history")
|
|
220
|
+
def get_star_history_endpoint(
|
|
221
|
+
owner: str,
|
|
222
|
+
repo: str,
|
|
223
|
+
response: Response,
|
|
224
|
+
authorization: str | None = Header(default=None),
|
|
225
|
+
):
|
|
226
|
+
bearer = ""
|
|
227
|
+
if authorization and authorization.lower().startswith("bearer "):
|
|
228
|
+
bearer = authorization.split(" ", 1)[1].strip()
|
|
229
|
+
token = bearer or os.environ.get("GITLYTICS_TOKEN")
|
|
230
|
+
try:
|
|
231
|
+
points = fetch_star_history(owner, repo, token)
|
|
232
|
+
except GitHubRateLimitError as exc:
|
|
233
|
+
# Surface rate-limit hits as 429 so the SPA shows the chart's rate-limit UI.
|
|
234
|
+
raise HTTPException(status_code=429, detail=str(exc))
|
|
235
|
+
except StarHistoryFetchError as exc:
|
|
236
|
+
# Validation / metadata / network failures are caller errors — 400 makes more
|
|
237
|
+
# sense than 429 here so the SPA can distinguish "GitHub is throttling us"
|
|
238
|
+
# from "your request was malformed".
|
|
239
|
+
raise HTTPException(status_code=400, detail=str(exc))
|
|
240
|
+
response.headers["Cache-Control"] = "public, max-age=86400"
|
|
241
|
+
return {"owner": owner, "repo": repo, "points": points}
|
|
242
|
+
|
|
243
|
+
|
|
211
244
|
@app.post("/api/upload-csv")
|
|
212
245
|
def upload_csv(file: UploadFile = File(...)):
|
|
213
246
|
try:
|
|
@@ -9,6 +9,7 @@ import os
|
|
|
9
9
|
|
|
10
10
|
# Import the three public functions that power every subcommand
|
|
11
11
|
from gitlytics import fetch_traffic, sync, serve_dashboard
|
|
12
|
+
from gitlytics.core import fetch_star_history
|
|
12
13
|
|
|
13
14
|
|
|
14
15
|
def parse_repo_names(repo_arg: str):
|
|
@@ -76,6 +77,11 @@ def main():
|
|
|
76
77
|
dash_parser.add_argument("-t", "--token", help="GitHub token for headless TV display.")
|
|
77
78
|
dash_parser.add_argument("--data-dir", help="Inject historical CSV database.")
|
|
78
79
|
|
|
80
|
+
# ── STARS subcommand ───────────────────────────────────────────────────────
|
|
81
|
+
stars_parser = subparsers.add_parser("stars", help="Fetch sampled star history for a repo.")
|
|
82
|
+
stars_parser.add_argument("repo", help="Repository in 'owner/repo' form (e.g. ameyac11/gitlytics).")
|
|
83
|
+
stars_parser.add_argument("-t", "--token", help="GitHub Personal Access Token.")
|
|
84
|
+
|
|
79
85
|
args = parser.parse_args()
|
|
80
86
|
|
|
81
87
|
# Print help and exit cleanly (code 0) if the user didn't give a subcommand.
|
|
@@ -153,6 +159,29 @@ def main():
|
|
|
153
159
|
data_dir=args.data_dir
|
|
154
160
|
)
|
|
155
161
|
|
|
162
|
+
elif args.command == "stars":
|
|
163
|
+
owner, _, repo = args.repo.partition("/")
|
|
164
|
+
if not owner or not repo:
|
|
165
|
+
print("❌ Error: repo must be in 'owner/repo' form.")
|
|
166
|
+
sys.exit(2)
|
|
167
|
+
try:
|
|
168
|
+
points = fetch_star_history(owner, repo, token)
|
|
169
|
+
except ValueError as exc:
|
|
170
|
+
# Bad input — non-zero exit so scripts can branch on it.
|
|
171
|
+
print(f"❌ Error: {exc}")
|
|
172
|
+
sys.exit(2)
|
|
173
|
+
except Exception as exc:
|
|
174
|
+
# Anything else (rate limit, network, etc.) — exit 1 so CI knows it failed.
|
|
175
|
+
print(f"❌ Error: {exc}")
|
|
176
|
+
sys.exit(1)
|
|
177
|
+
# Tabulate date + total stars.
|
|
178
|
+
print(f"{'DATE':<12} {'TOTAL STARS':>12}")
|
|
179
|
+
print("-" * 24)
|
|
180
|
+
for p in points:
|
|
181
|
+
print(f"{p['date']:<12} {p['total']:>12,}")
|
|
182
|
+
print("-" * 24)
|
|
183
|
+
print(f"{len(points)} sampled point(s)")
|
|
184
|
+
|
|
156
185
|
|
|
157
186
|
if __name__ == "__main__":
|
|
158
187
|
main()
|
|
@@ -29,6 +29,14 @@ _MAX_COMMIT_PAGES = 50 # hard cap when counting /commits (50 * 100 = 5000)
|
|
|
29
29
|
_PER_PAGE = 100 # request size for paginated endpoints
|
|
30
30
|
|
|
31
31
|
|
|
32
|
+
class GitHubRateLimitError(Exception):
|
|
33
|
+
"""Raised when GitHub responds with 403/429 (rate limit or abuse guard)."""
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class StarHistoryFetchError(Exception):
|
|
37
|
+
"""Raised for non-rate-limit star-history failures (network, parse, validation)."""
|
|
38
|
+
|
|
39
|
+
|
|
32
40
|
def make_headers(token: str) -> dict:
|
|
33
41
|
# Auth headers for authenticated API calls
|
|
34
42
|
return {
|
|
@@ -371,6 +379,162 @@ def get_single_repo(token: str, full_name: str) -> dict:
|
|
|
371
379
|
return data
|
|
372
380
|
|
|
373
381
|
|
|
382
|
+
def _star_headers(token: str | None) -> dict:
|
|
383
|
+
# Headers for the stargazers endpoint — needs the star+json media type
|
|
384
|
+
# so each item carries `starred_at`. Token is optional for public reads.
|
|
385
|
+
# Merge order matters: star+json must land AFTER the base headers so it
|
|
386
|
+
# overrides the default Accept (otherwise GitHub returns bare user objects).
|
|
387
|
+
h = {
|
|
388
|
+
**_GITHUB_BASE_HEADERS,
|
|
389
|
+
"Accept": "application/vnd.github.star+json",
|
|
390
|
+
}
|
|
391
|
+
if token:
|
|
392
|
+
h["Authorization"] = f"Bearer {token}"
|
|
393
|
+
return h
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
def fetch_star_history(owner: str, repo: str, token: str | None = None) -> list[dict]:
|
|
397
|
+
# Returns list of {date, total} cumulative points. No on-disk cache — the
|
|
398
|
+
# library always reads live from GitHub; the browser (IndexedDB via
|
|
399
|
+
# TanStack) and the Vercel CDN cache handle persistence upstream.
|
|
400
|
+
if not owner or not repo or "/" in repo:
|
|
401
|
+
raise ValueError("fetch_star_history requires owner and repo (no '/' in repo).")
|
|
402
|
+
|
|
403
|
+
now = datetime.now(timezone.utc)
|
|
404
|
+
today_str = now.strftime("%Y-%m-%d")
|
|
405
|
+
|
|
406
|
+
# Live fetch — pull total star count from the repo metadata endpoint.
|
|
407
|
+
meta, status = _safe_get(f"{BASE}/repos/{owner}/{repo}", _star_headers(token))
|
|
408
|
+
if status in (403, 429):
|
|
409
|
+
# GitHub's rate-limit guard returns 403 with a 'rate limit' message in body.
|
|
410
|
+
raise GitHubRateLimitError("GitHub rate limit reached, try again later")
|
|
411
|
+
if status != 200 or not isinstance(meta, dict):
|
|
412
|
+
raise StarHistoryFetchError(f"Failed to fetch repo metadata (HTTP {status})")
|
|
413
|
+
total_stars = int(meta.get("stargazers_count", 0) or 0)
|
|
414
|
+
if total_stars <= 0:
|
|
415
|
+
return [{"date": today_str, "total": 0}]
|
|
416
|
+
|
|
417
|
+
headers = _star_headers(token)
|
|
418
|
+
per_page = _PER_PAGE
|
|
419
|
+
points: list[dict] = []
|
|
420
|
+
# Choose strategy based on repo size so small repos get a real
|
|
421
|
+
# datewise timeline (every individual star) while large repos use
|
|
422
|
+
# sampling to stay under rate limits.
|
|
423
|
+
SMALL_THRESHOLD = 200
|
|
424
|
+
if total_stars <= SMALL_THRESHOLD:
|
|
425
|
+
# Walk every page at smaller page size for finer granularity.
|
|
426
|
+
small_per_page = 30
|
|
427
|
+
positions = list(range(1, total_stars + 1))
|
|
428
|
+
# Use the small page size for these requests.
|
|
429
|
+
per_page = small_per_page
|
|
430
|
+
small_by_page: dict[int, list[int]] = {}
|
|
431
|
+
for pos in positions:
|
|
432
|
+
p = (pos - 1) // small_per_page + 1
|
|
433
|
+
small_by_page.setdefault(p, []).append(pos)
|
|
434
|
+
for p, poses in small_by_page.items():
|
|
435
|
+
try:
|
|
436
|
+
r = requests.get(
|
|
437
|
+
f"{BASE}/repos/{owner}/{repo}/stargazers",
|
|
438
|
+
headers=headers,
|
|
439
|
+
params={"page": p, "per_page": small_per_page},
|
|
440
|
+
timeout=10,
|
|
441
|
+
)
|
|
442
|
+
except Exception as exc:
|
|
443
|
+
logger.warning(f"Stargazers fetch failed for {owner}/{repo} page {p}: {exc}")
|
|
444
|
+
continue
|
|
445
|
+
if r.status_code in (403, 429):
|
|
446
|
+
raise GitHubRateLimitError("GitHub rate limit reached, try again later")
|
|
447
|
+
if r.status_code != 200:
|
|
448
|
+
logger.warning(f"Stargazers page {p} returned HTTP {r.status_code}")
|
|
449
|
+
continue
|
|
450
|
+
items = r.json()
|
|
451
|
+
if not isinstance(items, list):
|
|
452
|
+
continue
|
|
453
|
+
for pos in poses:
|
|
454
|
+
offset = (pos - 1) % small_per_page
|
|
455
|
+
if offset >= len(items):
|
|
456
|
+
continue
|
|
457
|
+
item = items[offset]
|
|
458
|
+
if not isinstance(item, dict):
|
|
459
|
+
continue
|
|
460
|
+
starred_at = item.get("starred_at")
|
|
461
|
+
if not starred_at:
|
|
462
|
+
continue
|
|
463
|
+
points.append({"date": str(starred_at)[:10], "total": pos})
|
|
464
|
+
else:
|
|
465
|
+
# Pick 10 evenly-spaced individual stars. GitHub only keeps the last
|
|
466
|
+
# ~420 pages of stargazers even for huge repos so we cap the page
|
|
467
|
+
# range to avoid 422s on the upper bound.
|
|
468
|
+
max_pages = 422
|
|
469
|
+
max_position = min(total_stars, max_pages * per_page)
|
|
470
|
+
sample_count = 10
|
|
471
|
+
if max_position == 1:
|
|
472
|
+
sampled = [1]
|
|
473
|
+
else:
|
|
474
|
+
step = (max_position - 1) / (sample_count - 1)
|
|
475
|
+
sampled = sorted({max(1, min(max_position, round(1 + i * step))) for i in range(sample_count)})
|
|
476
|
+
# Group positions by page so each page is requested at most once.
|
|
477
|
+
by_page: dict[int, list[int]] = {}
|
|
478
|
+
for pos in sampled:
|
|
479
|
+
p = (pos - 1) // per_page + 1
|
|
480
|
+
by_page.setdefault(p, []).append(pos)
|
|
481
|
+
for p, poses in by_page.items():
|
|
482
|
+
try:
|
|
483
|
+
r = requests.get(
|
|
484
|
+
f"{BASE}/repos/{owner}/{repo}/stargazers",
|
|
485
|
+
headers=headers,
|
|
486
|
+
params={"page": p, "per_page": per_page},
|
|
487
|
+
timeout=10,
|
|
488
|
+
)
|
|
489
|
+
except Exception as exc:
|
|
490
|
+
logger.warning(f"Stargazers fetch failed for {owner}/{repo} page {p}: {exc}")
|
|
491
|
+
continue
|
|
492
|
+
if r.status_code in (403, 429):
|
|
493
|
+
raise GitHubRateLimitError("GitHub rate limit reached, try again later")
|
|
494
|
+
if r.status_code != 200:
|
|
495
|
+
logger.warning(f"Stargazers page {p} returned HTTP {r.status_code}")
|
|
496
|
+
continue
|
|
497
|
+
items = r.json()
|
|
498
|
+
if not isinstance(items, list):
|
|
499
|
+
continue
|
|
500
|
+
for pos in poses:
|
|
501
|
+
offset = (pos - 1) % per_page
|
|
502
|
+
if offset >= len(items):
|
|
503
|
+
continue
|
|
504
|
+
item = items[offset]
|
|
505
|
+
if not isinstance(item, dict):
|
|
506
|
+
continue
|
|
507
|
+
starred_at = item.get("starred_at")
|
|
508
|
+
if not starred_at:
|
|
509
|
+
continue
|
|
510
|
+
points.append({"date": str(starred_at)[:10], "total": pos})
|
|
511
|
+
|
|
512
|
+
# Build a per-day cumulative timeline. Each entry means "by end of <date>,
|
|
513
|
+
# this repo had <total> stars". Today always equals the live stargazers
|
|
514
|
+
# count so the chart's right edge is the current count.
|
|
515
|
+
per_day_max: dict[str, int] = {}
|
|
516
|
+
for p in points:
|
|
517
|
+
d = p["date"]
|
|
518
|
+
per_day_max[d] = max(per_day_max.get(d, 0), int(p["total"]))
|
|
519
|
+
if not per_day_max or max(per_day_max.values()) < total_stars:
|
|
520
|
+
per_day_max[today_str] = total_stars
|
|
521
|
+
|
|
522
|
+
# Convert raw "max position on this day" into a running cumulative count.
|
|
523
|
+
# Stars are monotone — total can never decrease across dates.
|
|
524
|
+
sorted_dates = sorted(per_day_max.keys())
|
|
525
|
+
cumulative = 0
|
|
526
|
+
points: list[dict] = []
|
|
527
|
+
for d in sorted_dates:
|
|
528
|
+
cumulative = max(cumulative, per_day_max[d])
|
|
529
|
+
points.append({"date": d, "total": cumulative})
|
|
530
|
+
if points and points[-1]["date"] != today_str:
|
|
531
|
+
points.append({"date": today_str, "total": max(cumulative, total_stars)})
|
|
532
|
+
if points and points[-1]["total"] < total_stars:
|
|
533
|
+
points[-1] = {"date": today_str, "total": total_stars}
|
|
534
|
+
|
|
535
|
+
return points
|
|
536
|
+
|
|
537
|
+
|
|
374
538
|
def get_repo_traffic(token: str, full_name: str, metrics: list = None) -> dict:
|
|
375
539
|
# Fetch only the traffic endpoints requested in metrics
|
|
376
540
|
h = make_headers(token)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{r as j,b as k,a as D,j as e,X as E,I as $,W as v,S as w,G as y,P as G,U as I}from"./index-hb6NMx5Y.js";import{b as O}from"./exports-CrU6Ta4Q.js";function U({profile:a,repos:t,onClose:c}){const[i,f]=j.useState({profile:!0,stats:!0,languages:!0,popular:!0,followers:!1}),[m,n]=j.useState(!1),{totalStars:u,totalForks:o,repoCount:g,topLangs:d,popular:p,langShares:C}=j.useMemo(()=>{const l=t.reduce((r,s)=>r+(Number(s.stars)||0),0),x=t.reduce((r,s)=>r+(Number(s.forks)||0),0),z=t.length,b=new Map;for(const r of t){const s=k(r);b.set(s,(b.get(s)||0)+1)}const F=[...b.entries()].sort((r,s)=>s[1]-r[1]).slice(0,3).map(([r])=>r),P=[...t].sort((r,s)=>(Number(s.stars)||0)-(Number(r.stars)||0))[0],N=[...b.values()].reduce((r,s)=>r+s,0),M=[...b.entries()].sort((r,s)=>s[1]-r[1]).slice(0,3).map(([r,s])=>({name:r,percentage:N>0?Math.round(s/N*100):0}));return{totalStars:l,totalForks:x,repoCount:z,topLangs:F,popular:P,langShares:M}},[t]);async function S(){n(!0);try{await O(a.username),c()}catch{}finally{n(!1)}}const L=l=>f(x=>({...x,[l]:!x[l]}));return D.createPortal(e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-background/95 p-4 backdrop-blur-md",onClick:()=>!m&&c(),children:e.jsxs("div",{className:"glass animate-slide-up w-full max-w-4xl overflow-hidden rounded-xl border border-border",onClick:l=>l.stopPropagation(),children:[e.jsxs("div",{className:"flex items-center justify-between border-b border-border p-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold",children:"Create Developer Card"}),e.jsx("p",{className:"mt-0.5 text-xs text-muted-foreground",children:"Shareable image for X and LinkedIn"})]}),e.jsx("button",{onClick:()=>!m&&c(),"aria-label":"Close",className:"rounded-lg p-1 text-muted-foreground transition-colors hover:bg-foreground/5 hover:text-foreground",children:e.jsx(E,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"grid gap-5 p-5 md:grid-cols-[1fr_240px]",children:[e.jsx("div",{className:"flex items-center justify-center rounded-lg border border-border/60 bg-background/30 p-4",children:e.jsx(T,{profile:a,opts:i,totalStars:u,totalForks:o,repoCount:g,topLangs:d,popular:p,langShares:C})}),e.jsxs("div",{className:"space-y-2 text-sm",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Include"}),[["profile","Profile info"],["stats","Stats"],["languages","Top languages"],["popular","Most popular repo"],["followers","Followers / following"]].map(([l,x])=>e.jsxs("label",{className:"flex cursor-pointer items-center gap-2.5 rounded-lg border border-border/60 bg-background/30 px-3 py-2 transition-colors hover:bg-foreground/5",children:[e.jsx("input",{type:"checkbox",checked:i[l],onChange:()=>L(l),className:"h-4 w-4 cursor-pointer accent-primary"}),x]},l)),e.jsxs("label",{className:"flex items-center gap-2.5 rounded-lg border border-border/60 bg-background/30 px-3 py-2 opacity-70",children:[e.jsx("input",{type:"checkbox",checked:!0,readOnly:!0,className:"h-4 w-4 accent-primary"}),"Gitlytics branding"]}),e.jsxs("button",{onClick:S,disabled:m,className:"mt-3 flex w-full items-center justify-center gap-1.5 rounded-lg bg-primary px-4 py-2.5 text-sm font-semibold text-primary-foreground transition-transform hover:scale-[1.01] disabled:opacity-50",children:[e.jsx($,{className:"h-4 w-4"}),m?"Generating…":"Download Card"]})]})]})]})}),document.body)}function T({profile:a,opts:t,totalStars:c,totalForks:i,repoCount:f,topLangs:m,popular:n,langShares:u}){return e.jsxs("div",{id:"developer-card",className:"relative w-[480px] rounded-2xl border border-border/80 p-6 shadow-2xl bg-[#141312] overflow-hidden",children:[e.jsx("div",{className:"absolute -right-20 -top-20 h-40 w-40 rounded-full bg-primary/10 pointer-events-none"}),e.jsx("div",{className:"absolute -left-20 -bottom-20 h-40 w-40 rounded-full bg-chart-2/10 pointer-events-none"}),e.jsxs("div",{className:"relative z-10 mb-5 flex items-center gap-2",children:[e.jsx("img",{src:"/gitlytics-logo.png",alt:"",className:"h-5 w-5 object-contain"}),e.jsx(v,{className:"text-xs font-bold tracking-wider uppercase opacity-90"})]}),t.profile&&e.jsxs("div",{className:"relative z-10 mb-5 flex items-center gap-4",children:[e.jsx("img",{src:a.avatar_url,alt:"",crossOrigin:"anonymous",onError:o=>{o.currentTarget.src="/gitlytics-logo.png"},className:"h-16 w-16 rounded-full border-2 border-primary/50 p-0.5 bg-surface/40 object-cover shadow-lg shadow-primary/5"}),e.jsxs("div",{className:"leading-tight",children:[e.jsx("p",{className:"text-lg font-bold tracking-tight text-foreground",children:a.name||a.username}),e.jsxs("p",{className:"text-xs font-semibold text-primary",children:["@",a.username]}),(a.bio||a.location)&&e.jsx("p",{className:"mt-1 text-xs text-muted-foreground line-clamp-2 max-w-[340px]",children:[a.bio,a.location].filter(Boolean).join(" · ")})]})]}),t.stats&&e.jsxs("div",{className:`relative z-10 mb-5 grid gap-2.5 text-xs ${t.followers?"grid-cols-4":"grid-cols-3"}`,children:[e.jsx(h,{icon:e.jsx(w,{className:"h-4 w-4"}),label:"Stars",value:c,colorClass:"text-chart-2"}),e.jsx(h,{icon:e.jsx(y,{className:"h-4 w-4"}),label:"Forks",value:i,colorClass:"text-chart-4"}),e.jsx(h,{icon:e.jsx(G,{className:"h-4 w-4"}),label:"Repos",value:f,colorClass:"text-chart-3"}),t.followers&&e.jsx(h,{icon:e.jsx(I,{className:"h-4 w-4"}),label:"Followers",value:a.followers??0,colorClass:"text-primary"})]}),t.languages&&u.length>0&&e.jsxs("div",{className:"relative z-10 mb-5",children:[e.jsx("p",{className:"mb-2 text-[10px] uppercase tracking-wider text-muted-foreground/80 font-bold",children:"Top Languages"}),e.jsx("div",{className:"mb-3 h-2 w-full rounded-full bg-foreground/5 overflow-hidden flex",children:u.map((o,g)=>{const d=["bg-primary","bg-chart-2","bg-chart-3","bg-chart-4"],p=d[g%d.length];return e.jsx("div",{style:{width:`${o.percentage}%`},className:`${p} h-full`},o.name)})}),e.jsx("div",{className:"flex flex-wrap gap-x-4 gap-y-1.5",children:u.map((o,g)=>{const d=["bg-primary","bg-chart-2","bg-chart-3","bg-chart-4"],p=d[g%d.length];return e.jsxs("div",{className:"flex items-center gap-1.5 text-xs",children:[e.jsx("span",{className:`h-2 w-2 rounded-full ${p}`}),e.jsx("span",{className:"font-semibold text-foreground",children:o.name}),e.jsxs("span",{className:"text-muted-foreground font-medium",children:[o.percentage,"%"]})]},o.name)})})]}),t.popular&&n&&e.jsxs("div",{className:"relative z-10 mb-5 rounded-xl border border-border/50 bg-foreground/[0.01] p-3.5 hover:bg-foreground/[0.02] transition-colors group",children:[e.jsx("p",{className:"mb-1.5 text-[10px] uppercase tracking-wider text-muted-foreground/80 font-bold",children:"Most Popular Project"}),e.jsx("p",{className:"truncate text-sm font-bold text-foreground group-hover:text-primary transition-colors",children:n.repository}),e.jsxs("div",{className:"mt-2 flex items-center gap-3 text-xs text-muted-foreground font-semibold",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(w,{className:"h-3.5 w-3.5 text-chart-2 fill-chart-2/10"})," ",n.stars]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(y,{className:"h-3.5 w-3.5 text-chart-4"})," ",n.forks]}),e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-primary"}),e.jsx("span",{children:k(n)})]})]}),e.jsxs("p",{className:"relative z-10 mt-1 text-center text-[10px] tracking-wide text-muted-foreground/80",children:[e.jsx(v,{className:"font-bold inline"})," · gitlytics.dev"]})]})}function h({icon:a,label:t,value:c,colorClass:i="text-primary"}){return e.jsxs("div",{className:"flex flex-col rounded-xl border border-border/50 bg-foreground/[0.02] p-2.5 transition-all hover:bg-foreground/[0.04] relative overflow-hidden group",children:[e.jsxs("div",{className:"flex items-center justify-between text-muted-foreground",children:[e.jsx("span",{className:"text-[9px] font-bold uppercase tracking-wider text-muted-foreground/75",children:t}),e.jsx("span",{className:`transition-transform group-hover:scale-110 ${i}`,children:a})]}),e.jsx("span",{className:"text-base font-bold tracking-tight tabular-nums text-foreground mt-1.5",children:(Number(c)||0).toLocaleString()})]})}export{U as CardModal};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{r as l,a as S,j as t,X as P,C as T,I as A,F as D}from"./index-hb6NMx5Y.js";import{r as G,a as I}from"./exports-CrU6Ta4Q.js";const j=[{id:"section-hero",label:"Lifetime Stats Hero Card",default:!0},{id:"section-issues-prs",label:"Issues and PRs Summary Card",default:!0},{id:"section-stat-cards",label:"6 Stat Cards",default:!0},{id:"section-top10-charts",label:"Top 10 Charts",default:!0},{id:"section-star-history",label:"Star History Chart",default:!0},{id:"section-referrer-aggregation",label:"Global Referrer Aggregation",default:!1},{id:"section-heatmap",label:"Traffic Patterns Heatmap",default:!1},{id:"section-languages",label:"Language Distribution",default:!1},{id:"section-commits",label:"Commit Activity",default:!1},{id:"section-most-cloned",label:"Most Cloned Repositories Table",default:!1},{id:"section-all-repos",label:"All Repositories Table",default:!0}];function O({onClose:u,mode:a="png",allRepos:o,defaultRepos:m,runWithRepos:y,profile:p}){const[d,x]=l.useState(!1),n=l.useMemo(()=>typeof document>"u"?j:j.filter(e=>document.getElementById(e.id)!==null),[]),[f,g]=l.useState(Object.fromEntries(n.map(e=>[e.id,e.default])));l.useEffect(()=>{g(Object.fromEntries(n.map(e=>[e.id,e.default])))},[n]);const N=m.length>0&&m.length<o.length?m:o,[s,h]=l.useState(N),w=e=>g(r=>({...r,[e]:!r[e]})),v=a==="pdf"?!0:Object.values(f).some(Boolean),i=s.length===o.length,b=l.useMemo(()=>i?"All repos":s.length===1?s[0]:`${s.length} repos`,[s,i]);function C(e){h(r=>r.includes(e)?r.filter(c=>c!==e):[...r,e])}function k(){h(i?[]:o)}async function E(){if(s.length!==0){x(!0);try{await y(i?[]:s,async()=>{if(a==="png"){const r=n.filter(c=>f[c.id]).map(c=>c.id);if(r.length===0)return;await G(r,b,p)}else await I(b,p)}),u()}catch{}finally{x(!1)}}}return S.createPortal(t.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-background/95 p-4 backdrop-blur-md",onClick:()=>!d&&u(),children:t.jsxs("div",{className:"glass animate-slide-up flex max-h-[90vh] w-full max-w-lg flex-col overflow-hidden rounded-xl border border-border",onClick:e=>e.stopPropagation(),children:[t.jsxs("div",{className:"flex shrink-0 items-center justify-between border-b border-border p-4",children:[t.jsxs("div",{children:[t.jsx("h3",{className:"text-sm font-semibold",children:a==="png"?"Export PNG":"Export PDF"}),t.jsx("p",{className:"mt-0.5 text-xs text-muted-foreground",children:a==="png"?"Choose repositories and sections to include":"Choose repositories to include in the full report"})]}),t.jsx("button",{onClick:()=>!d&&u(),"aria-label":"Close",className:"rounded-lg p-1 text-muted-foreground transition-colors hover:bg-foreground/5 hover:text-foreground",children:t.jsx(P,{className:"h-4 w-4"})})]}),t.jsxs("div",{className:"flex-1 space-y-4 overflow-y-auto p-5",children:[t.jsxs("div",{children:[t.jsxs("div",{className:"mb-1.5 flex items-center justify-between",children:[t.jsxs("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:["Repositories (",s.length,"/",o.length,")"]}),t.jsx("button",{onClick:k,className:"text-xs font-medium text-primary hover:underline",children:i?"Clear all":"Select all"})]}),t.jsx("div",{className:"max-h-40 space-y-1 overflow-auto rounded-lg border border-border/60 bg-background/30 p-2",children:o.map(e=>{const r=s.includes(e);return t.jsxs("button",{onClick:()=>C(e),className:"flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-xs hover:bg-foreground/5",children:[t.jsx("span",{className:`flex h-4 w-4 shrink-0 items-center justify-center rounded border ${r?"border-primary bg-primary text-primary-foreground":"border-input"}`,children:r&&t.jsx(T,{className:"h-3 w-3"})}),t.jsx("span",{className:"truncate",children:e})]},e)})})]}),a==="png"&&t.jsxs("div",{className:"space-y-1.5",children:[t.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Sections"}),n.length===0&&t.jsx("p",{className:"text-xs text-muted-foreground",children:"No exportable sections in the current view."}),n.map(e=>t.jsxs("label",{className:"flex cursor-pointer items-center gap-2.5 rounded-lg border border-border/60 bg-background/30 px-3 py-2 text-sm transition-colors hover:bg-foreground/5",children:[t.jsx("input",{type:"checkbox",checked:f[e.id],onChange:()=>w(e.id),className:"h-4 w-4 cursor-pointer accent-primary"}),e.label]},e.id))]}),t.jsxs("button",{onClick:E,disabled:d||!v||s.length===0,className:"flex w-full items-center justify-center gap-1.5 rounded-lg bg-primary px-4 py-2.5 text-sm font-semibold text-primary-foreground transition-transform hover:scale-[1.01] disabled:opacity-50",children:[a==="png"?t.jsx(A,{className:"h-4 w-4"}):t.jsx(D,{className:"h-4 w-4"}),d?"Generating…":a==="png"?"Export PNG":"Export PDF"]})]})]})}),document.body)}export{O as ExportModal};
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/jspdf.es.min-vktmDsgQ.js","assets/index-hb6NMx5Y.js","assets/index-D5qdeNvu.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{t as S,e as _,c as W,_ as D}from"./index-hb6NMx5Y.js";function R(t,o){typeof window>"u"||(window.isGitlyticsExporting=o,window.dispatchEvent(new CustomEvent("gitlytics-export-busy",{detail:{kind:t,busy:o}})))}function w(t){typeof window>"u"||window.dispatchEvent(new CustomEvent("gitlytics-export-step",{detail:{message:t}}))}async function F(){try{const t=new Image;return t.crossOrigin="anonymous",t.src="/gitlytics-logo.png",await new Promise((o,r)=>{t.onload=()=>o(),t.onerror=()=>r(new Error("logo"))}),t}catch{return null}}async function L(t){try{const o=new Image;return o.crossOrigin="anonymous",o.src=t,await new Promise((r,l)=>{o.onload=()=>r(),o.onerror=()=>l(new Error("avatar"))}),o}catch{return null}}async function G(t,o,r,l,e){const y=l.avatar_url?await L(l.avatar_url):null;t.save();const h=16*e,d=96*e,n=64*e,c=16*e,u=h,f=r+h,P=o-h*2;t.fillStyle="rgba(15, 15, 20, 0.65)",t.beginPath(),typeof t.roundRect=="function"?t.roundRect(u,f,P,d,12*e):t.rect(u,f,P,d),t.fill(),t.strokeStyle="rgba(255, 255, 255, 0.08)",t.lineWidth=1*e,t.stroke();let m=u+h*1.5;if(y){const i=u+h*1.5,a=f+(d-n)/2,g=12*e;t.save(),t.beginPath(),typeof t.roundRect=="function"?t.roundRect(i,a,n,n,g):t.arc(i+n/2,a+n/2,n/2,0,Math.PI*2),t.clip(),t.drawImage(y,i,a,n,n),t.restore(),t.strokeStyle="#d97757",t.lineWidth=1.5*e,t.beginPath(),typeof t.roundRect=="function"?t.roundRect(i,a,n,n,g):t.arc(i+n/2,a+n/2,n/2,0,Math.PI*2),t.stroke(),m=i+n+c}t.textAlign="left";const b=f+d/2-2*e;t.font=`bold ${22*e}px ui-sans-serif, system-ui, -apple-system, sans-serif`,t.fillStyle="#ffffff",t.textBaseline="bottom",t.fillText(l.name,m,b),t.font=`${14*e}px ui-sans-serif, system-ui, -apple-system, sans-serif`,t.fillStyle="rgba(255, 255, 255, 0.6)",t.textBaseline="top";const E=`@${l.username}`;if(t.fillText(E,m,b+2*e),l.location){const i=l.location;t.font=`${13*e}px ui-sans-serif, system-ui, -apple-system, sans-serif`,t.fillStyle="rgba(255, 255, 255, 0.4)";const a=t.measureText(E).width;t.textBaseline="top",t.fillText(`• ${i}`,m+a+10*e,b+2*e)}const v=await F();if(v){const i=32*e,a=u+P-h*1.5-i,g=f+(d-i)/2;t.drawImage(v,a,g,i,i),t.font=`bold ${16*e}px ui-sans-serif, system-ui, -apple-system, sans-serif`,t.fillStyle="#d97757",t.textBaseline="middle",t.textAlign="right",t.fillText("Gitlytics",a-8*e,f+d/2)}t.restore()}function O(){const t=new Date,o=r=>String(r).padStart(2,"0");return`${t.getFullYear()}-${o(t.getMonth()+1)}-${o(t.getDate())} ${o(t.getHours())}:${o(t.getMinutes())}`}async function A(t,o,r){const l=await F(),e=Math.max(.9,Math.min(o,r)/1600),y=Math.round(20*e),h=Math.round(18*e),d=Math.round(36*e),n=Math.round(18*e),c=Math.round(11*e);t.save(),t.globalAlpha=.9,t.font=`bold ${n}px ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto`;const u="Git",f="lytics",P=t.measureText(u).width,m=t.measureText(f).width,b=P+m,E="gitlytics.dev";t.font=`${c}px ui-sans-serif, system-ui, -apple-system`;const v=t.measureText(E).width,i=O(),a=t.measureText(i).width,g=Math.round(10*e),M=Math.round(8*e),s=Math.max(b,v,a)+(l?d+M:0)+g*2,p=Math.round(62*e),C=o-s-y,I=r-p-h;t.fillStyle="rgba(15,15,20,0.72)",t.beginPath(),typeof t.roundRect=="function"?t.roundRect(C,I,s,p,Math.round(8*e)):t.rect(C,I,s,p),t.fill(),t.strokeStyle="rgba(217,119,87,0.45)",t.lineWidth=Math.max(1,Math.round(e)),t.stroke();let T=C+g;const k=I+g+Math.round(n*.85);l&&(t.drawImage(l,T,I+(p-d)/2,d,d),T+=d+M),t.font=`bold ${n}px ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto`,t.fillStyle="#d97757",t.fillText(u,T,k),t.fillStyle="#ffffff",t.fillText(f,T+P,k),t.font=`${c}px ui-sans-serif, system-ui, -apple-system`,t.fillStyle="rgba(255,255,255,0.85)",t.fillText(E,T,k+Math.round(c*1.4)),t.fillStyle="rgba(255,255,255,0.65)",t.fillText(i,T,k+Math.round(c*2.6)),t.restore()}function H(){return typeof window>"u"?"#000":getComputedStyle(document.body).backgroundColor||"#000"}async function $(){return(await D(async()=>{const{default:t}=await import("./html2canvas-pro.esm-9xys3ejh.js");return{default:t}},[])).default}function B(){const t=document.createElement("style");return t.setAttribute("data-gitlytics-export","1"),t.textContent=`
|
|
3
|
+
.recharts-wrapper, .recharts-surface { overflow: visible !important; }
|
|
4
|
+
.recharts-responsive-container { overflow: visible !important; }
|
|
5
|
+
.recharts-cartesian-axis-tick text { font-size: 11px; }
|
|
6
|
+
[id^="section-"], #dashboard-root .glass { overflow: visible !important; }
|
|
7
|
+
#dashboard-root * {
|
|
8
|
+
animation-delay: 0s !important;
|
|
9
|
+
animation-duration: 0s !important;
|
|
10
|
+
animation-iteration-count: 1 !important;
|
|
11
|
+
transition-duration: 0s !important;
|
|
12
|
+
transition-delay: 0s !important;
|
|
13
|
+
}
|
|
14
|
+
`,document.head.appendChild(t),()=>t.remove()}async function Y(t,o="All repos",r){if(t.length===0)return;R("png",!0);const l=S.loading("Generating PNG…");window.dispatchEvent(new CustomEvent("gitlytics-export-expand"));const e=B();try{w("Preparing sections…");const y=await $(),h=H(),d={scale:2,useCORS:!0,allowTaint:!0,backgroundColor:h};w("Rendering charts…"),await new Promise(a=>setTimeout(a,1500)),w("Capturing dashboard…");const n=[];for(const a of t){const g=document.getElementById(a);if(!g)continue;g.scrollIntoView({block:"center",behavior:"instant"}),await new Promise(s=>setTimeout(s,250));const M=g.getBoundingClientRect();n.push(await y(g,{...d,width:Math.ceil(M.width),height:Math.ceil(g.scrollHeight),windowWidth:document.documentElement.clientWidth}))}if(n.length===0)throw new Error("No sections found");const c=32,u=Math.max(...n.map(a=>a.width)),f=r?256:0,P=n.reduce((a,g)=>a+g.height,0)+c*(n.length-1)+c*2+(r?f+c:0),m=document.createElement("canvas");m.width=u+c*2,m.height=P;const b=m.getContext("2d");b.fillStyle=h,b.fillRect(0,0,m.width,m.height);let E=c;r&&(w("Adding profile header…"),await G(b,m.width,E,r,2),E+=f+c);for(const a of n)b.drawImage(a,c,E),E+=a.height+c;w("Adding watermark…"),await A(b,m.width,m.height),w("Generating file…");const v=_("png"),i=document.createElement("a");i.href=m.toDataURL("image/png"),i.download=v,i.click(),W({action:"Export PNG",repos:o,filename:v}),S.success("PNG ready — downloading",{id:l,duration:3e3})}catch(y){throw S.error("Failed to generate PNG",{id:l}),y}finally{e(),window.dispatchEvent(new CustomEvent("gitlytics-export-restore")),R("png",!1)}}async function N(t="All repos",o){R("pdf",!0);const r=S.loading("Generating full report… this may take a few seconds");window.dispatchEvent(new CustomEvent("gitlytics-export-expand"));const l=B();try{w("Preparing full report…"),w("Expanding all sections…"),await new Promise(s=>setTimeout(s,900)),w("Rendering all charts…"),await new Promise(s=>setTimeout(s,2e3));const e=await $(),{jsPDF:y}=await D(async()=>{const{jsPDF:s}=await import("./jspdf.es.min-vktmDsgQ.js").then(p=>p.j);return{jsPDF:s}},__vite__mapDeps([0,1,2])),h=H(),d=document.getElementById("dashboard-root")||document.body,n=1.5;w("Capturing dashboard…");const c=await e(d,{scale:n,useCORS:!0,allowTaint:!0,backgroundColor:h,windowHeight:document.documentElement.scrollHeight,height:d.scrollHeight});let u=c;if(o){w("Adding profile header…");const s=128*n,p=document.createElement("canvas");p.width=c.width,p.height=c.height+s;const C=p.getContext("2d");C.fillStyle=h,C.fillRect(0,0,p.width,p.height),await G(C,p.width,0,o,n),C.drawImage(c,0,s),u=p}const f=new y("l","mm","a4"),P=f.internal.pageSize.getWidth(),m=f.internal.pageSize.getHeight(),b=u.width/P,E=Math.floor(m*b),v=document.createElement("canvas");v.width=u.width,v.height=E;const i=v.getContext("2d");w("Adding watermark…"),w("Building PDF…");let a=0,g=0;for(;a<u.height;){const s=Math.min(E,u.height-a);v.height=s,i.fillStyle=h,i.fillRect(0,0,v.width,s),i.drawImage(u,0,a,u.width,s,0,0,u.width,s),await A(i,v.width,s);const p=v.toDataURL("image/jpeg",.82),C=s/b;g>0&&f.addPage(),f.addImage(p,"JPEG",0,0,P,C,void 0,"FAST"),a+=s,g+=1}const M=_("pdf");f.save(M),W({action:"Export PDF",repos:t,filename:M}),S.success("PDF ready — downloading",{id:r,duration:3e3})}catch(e){throw S.error("Failed to generate PDF",{id:r}),e}finally{l(),window.dispatchEvent(new CustomEvent("gitlytics-export-restore")),R("pdf",!1)}}async function U(t){R("card",!0);const o=S.loading("Generating card…");try{w("Preparing card…"),w("Rendering…"),await new Promise(n=>setTimeout(n,1e3));const r=await $(),l=document.getElementById("developer-card");if(!l)throw new Error("Card not found");const e=H(),y=await r(l,{scale:2,useCORS:!0,allowTaint:!0,backgroundColor:null});w("Adding branding…"),await A(y.getContext("2d"),y.width,y.height),w("Downloading…");const h=_("card",t),d=document.createElement("a");d.href=y.toDataURL("image/png"),d.download=h,d.click(),W({action:"Create Card",repos:`@${t}`,filename:h}),S.success("Card ready — downloading",{id:o,duration:3e3})}catch(r){throw S.error("Failed to generate card",{id:o}),r}finally{R("card",!1)}}export{N as a,U as b,Y as r};
|