gitlytics 0.4.4__tar.gz → 0.4.6__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.4.4 → gitlytics-0.4.6}/PKG-INFO +2 -1
- {gitlytics-0.4.4 → gitlytics-0.4.6}/pyproject.toml +2 -1
- {gitlytics-0.4.4 → gitlytics-0.4.6}/src/gitlytics/__init__.py +7 -3
- {gitlytics-0.4.4 → gitlytics-0.4.6}/src/gitlytics/api.py +40 -9
- {gitlytics-0.4.4 → gitlytics-0.4.6}/src/gitlytics/automation.py +54 -34
- {gitlytics-0.4.4 → gitlytics-0.4.6}/src/gitlytics/core.py +12 -2
- {gitlytics-0.4.4 → gitlytics-0.4.6}/src/gitlytics/process.py +24 -5
- gitlytics-0.4.6/src/gitlytics/static/assets/CardModal-C59MkcBx.js +1 -0
- gitlytics-0.4.4/src/gitlytics/static/assets/ExportModal-BBjEZhmF.js → gitlytics-0.4.6/src/gitlytics/static/assets/ExportModal-TgUqez0T.js +1 -1
- gitlytics-0.4.4/src/gitlytics/static/assets/exports-BD7YfSBX.js → gitlytics-0.4.6/src/gitlytics/static/assets/exports-CBIW6Z6w.js +3 -3
- gitlytics-0.4.4/src/gitlytics/static/assets/index-qzHj2txI.js → gitlytics-0.4.6/src/gitlytics/static/assets/index-Bi9mu2Wz.js +42 -42
- gitlytics-0.4.4/src/gitlytics/static/assets/index.es-BvMAPrqL.js → gitlytics-0.4.6/src/gitlytics/static/assets/index.es-BpixEfNZ.js +1 -1
- gitlytics-0.4.4/src/gitlytics/static/assets/jspdf.es.min-BXFa7K9_.js → gitlytics-0.4.6/src/gitlytics/static/assets/jspdf.es.min-WsKal4G6.js +3 -3
- {gitlytics-0.4.4 → gitlytics-0.4.6}/src/gitlytics/static/index.html +1 -1
- {gitlytics-0.4.4 → gitlytics-0.4.6}/src/gitlytics.egg-info/PKG-INFO +2 -1
- {gitlytics-0.4.4 → gitlytics-0.4.6}/src/gitlytics.egg-info/SOURCES.txt +6 -6
- {gitlytics-0.4.4 → gitlytics-0.4.6}/src/gitlytics.egg-info/requires.txt +1 -0
- {gitlytics-0.4.4 → gitlytics-0.4.6}/tests/test_api.py +17 -0
- {gitlytics-0.4.4 → gitlytics-0.4.6}/tests/test_process.py +16 -0
- gitlytics-0.4.4/src/gitlytics/static/assets/CardModal-CDZ8n_vy.js +0 -1
- {gitlytics-0.4.4 → gitlytics-0.4.6}/LICENSE +0 -0
- {gitlytics-0.4.4 → gitlytics-0.4.6}/README.md +0 -0
- {gitlytics-0.4.4 → gitlytics-0.4.6}/setup.cfg +0 -0
- {gitlytics-0.4.4 → gitlytics-0.4.6}/src/gitlytics/__main__.py +0 -0
- {gitlytics-0.4.4 → gitlytics-0.4.6}/src/gitlytics/cli.py +0 -0
- {gitlytics-0.4.4 → gitlytics-0.4.6}/src/gitlytics/static/_headers +0 -0
- {gitlytics-0.4.4 → gitlytics-0.4.6}/src/gitlytics/static/_redirects +0 -0
- {gitlytics-0.4.4 → gitlytics-0.4.6}/src/gitlytics/static/android-chrome-192x192.png +0 -0
- {gitlytics-0.4.4 → gitlytics-0.4.6}/src/gitlytics/static/android-chrome-512x512.png +0 -0
- {gitlytics-0.4.4 → gitlytics-0.4.6}/src/gitlytics/static/apple-touch-icon.png +0 -0
- {gitlytics-0.4.4 → gitlytics-0.4.6}/src/gitlytics/static/assets/html2canvas-pro.esm-9xys3ejh.js +0 -0
- {gitlytics-0.4.4 → gitlytics-0.4.6}/src/gitlytics/static/assets/html2canvas.esm-DXEQVQnt.js +0 -0
- {gitlytics-0.4.4 → gitlytics-0.4.6}/src/gitlytics/static/assets/index-BRI0yQ1K.css +0 -0
- {gitlytics-0.4.4 → gitlytics-0.4.6}/src/gitlytics/static/assets/purify.es-CC4Brkr_.js +0 -0
- {gitlytics-0.4.4 → gitlytics-0.4.6}/src/gitlytics/static/favicon-16x16.png +0 -0
- {gitlytics-0.4.4 → gitlytics-0.4.6}/src/gitlytics/static/favicon-32x32.png +0 -0
- {gitlytics-0.4.4 → gitlytics-0.4.6}/src/gitlytics/static/favicon-48x48.png +0 -0
- {gitlytics-0.4.4 → gitlytics-0.4.6}/src/gitlytics/static/favicon.ico +0 -0
- {gitlytics-0.4.4 → gitlytics-0.4.6}/src/gitlytics/static/gitlytics-logo.png +0 -0
- {gitlytics-0.4.4 → gitlytics-0.4.6}/src/gitlytics/static/google-search-icon-48x48.png +0 -0
- {gitlytics-0.4.4 → gitlytics-0.4.6}/src/gitlytics/static/google-search-icon.png +0 -0
- {gitlytics-0.4.4 → gitlytics-0.4.6}/src/gitlytics/static/robots.txt +0 -0
- {gitlytics-0.4.4 → gitlytics-0.4.6}/src/gitlytics/static/sitemap.xml +0 -0
- {gitlytics-0.4.4 → gitlytics-0.4.6}/src/gitlytics.egg-info/dependency_links.txt +0 -0
- {gitlytics-0.4.4 → gitlytics-0.4.6}/src/gitlytics.egg-info/entry_points.txt +0 -0
- {gitlytics-0.4.4 → gitlytics-0.4.6}/src/gitlytics.egg-info/top_level.txt +0 -0
- {gitlytics-0.4.4 → gitlytics-0.4.6}/tests/test_automation.py +0 -0
- {gitlytics-0.4.4 → gitlytics-0.4.6}/tests/test_cli.py +0 -0
- {gitlytics-0.4.4 → gitlytics-0.4.6}/tests/test_core.py +0 -0
- {gitlytics-0.4.4 → gitlytics-0.4.6}/tests/test_star_history.py +0 -0
- {gitlytics-0.4.4 → gitlytics-0.4.6}/tests/test_username.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: gitlytics
|
|
3
|
-
Version: 0.4.
|
|
3
|
+
Version: 0.4.6
|
|
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,6 +17,7 @@ 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: numpy>=1.26.0
|
|
20
21
|
Requires-Dist: croniter>=2.0.0
|
|
21
22
|
Provides-Extra: dashboard
|
|
22
23
|
Requires-Dist: fastapi>=0.111.0; extra == "dashboard"
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "gitlytics"
|
|
7
|
-
version = "0.4.
|
|
7
|
+
version = "0.4.6"
|
|
8
8
|
description = "Monitor and automate your GitHub repository traffic analytics."
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.9"
|
|
@@ -19,6 +19,7 @@ authors = [
|
|
|
19
19
|
dependencies = [
|
|
20
20
|
"requests>=2.32.0",
|
|
21
21
|
"pandas>=2.2.0",
|
|
22
|
+
"numpy>=1.26.0",
|
|
22
23
|
"croniter>=2.0.0"
|
|
23
24
|
]
|
|
24
25
|
keywords = [
|
|
@@ -9,7 +9,7 @@ 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.4.
|
|
12
|
+
__version__ = "0.4.6"
|
|
13
13
|
|
|
14
14
|
__all__ = [
|
|
15
15
|
"fetch_traffic",
|
|
@@ -110,15 +110,19 @@ def fetch_traffic(token: str, repo_name=None, print_table: bool = False, return_
|
|
|
110
110
|
# --- dataframe mode: just return the raw DataFrame, optionally save it ---
|
|
111
111
|
if return_format == "dataframe":
|
|
112
112
|
if save_file:
|
|
113
|
+
# When persisting to disk, strip private repos by default (security firewall).
|
|
114
|
+
export_df = df
|
|
115
|
+
if "is_private" in df.columns:
|
|
116
|
+
export_df = df[~df["is_private"]]
|
|
113
117
|
if save_file.endswith(".json"):
|
|
114
118
|
# Save as a chart-ready JSON file (always public-only when exported to disk)
|
|
115
|
-
payload = build_json_payload(
|
|
119
|
+
payload = build_json_payload(export_df, return_format="timeseries", export_public_only=True)
|
|
116
120
|
_write_json_safely(save_file, payload)
|
|
117
121
|
else:
|
|
118
122
|
# Save as a standard CSV file
|
|
119
123
|
p = Path(save_file)
|
|
120
124
|
p.parent.mkdir(parents=True, exist_ok=True)
|
|
121
|
-
|
|
125
|
+
export_df.to_csv(p, index=False)
|
|
122
126
|
return df
|
|
123
127
|
|
|
124
128
|
# Reject anything that isn't a known format before doing more work
|
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
gitlytics/api.py
|
|
3
3
|
Powers the FastAPI backend — serves traffic data and the React dashboard to the browser.
|
|
4
4
|
"""
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
5
7
|
import hashlib
|
|
6
8
|
import logging
|
|
7
9
|
import os
|
|
@@ -288,10 +290,17 @@ def get_star_history_endpoint(
|
|
|
288
290
|
response: Response,
|
|
289
291
|
authorization: str | None = Header(default=None),
|
|
290
292
|
):
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
293
|
+
# If an Authorization header is present but malformed (wrong scheme, empty
|
|
294
|
+
# token, etc.), error out rather than silently falling back to the server's
|
|
295
|
+
# own GITLYTICS_TOKEN — anyone who can reach this endpoint must not be able
|
|
296
|
+
# to burn the operator's PAT quota with a spoofed header.
|
|
297
|
+
if authorization:
|
|
298
|
+
parts = authorization.strip().split(None, 1)
|
|
299
|
+
if len(parts) != 2 or parts[0].lower() != "bearer" or not parts[1].strip():
|
|
300
|
+
raise HTTPException(status_code=401, detail="Malformed Authorization header.")
|
|
301
|
+
token = parts[1].strip()
|
|
302
|
+
else:
|
|
303
|
+
token = os.environ.get("GITLYTICS_TOKEN")
|
|
295
304
|
try:
|
|
296
305
|
points = fetch_star_history(owner, repo, token)
|
|
297
306
|
except GitHubRateLimitError as exc:
|
|
@@ -343,7 +352,30 @@ def upload_csv(
|
|
|
343
352
|
)
|
|
344
353
|
out.write(chunk)
|
|
345
354
|
file.file.seek(0)
|
|
346
|
-
|
|
355
|
+
upload_stream = file.file
|
|
356
|
+
else:
|
|
357
|
+
# No data_dir configured — the common case for `gitlytics dashboard`
|
|
358
|
+
# without persistence. The 25 MB cap MUST still be enforced here,
|
|
359
|
+
# otherwise an unbounded upload is fully buffered into memory before
|
|
360
|
+
# pd.read_csv runs (DoS / OOM). Read into a bounded BytesIO so the
|
|
361
|
+
# size check happens before any parsing.
|
|
362
|
+
import io
|
|
363
|
+
buf = io.BytesIO()
|
|
364
|
+
total = 0
|
|
365
|
+
while True:
|
|
366
|
+
chunk = file.file.read(1024 * 1024)
|
|
367
|
+
if not chunk:
|
|
368
|
+
break
|
|
369
|
+
total += len(chunk)
|
|
370
|
+
if total > _MAX_UPLOAD_BYTES:
|
|
371
|
+
raise HTTPException(
|
|
372
|
+
status_code=413,
|
|
373
|
+
detail=f"CSV too large. Maximum size is {_MAX_UPLOAD_BYTES // (1024 * 1024)} MB.",
|
|
374
|
+
)
|
|
375
|
+
buf.write(chunk)
|
|
376
|
+
buf.seek(0)
|
|
377
|
+
upload_stream = buf
|
|
378
|
+
df = process_uploaded_csv(upload_stream)
|
|
347
379
|
df = df.replace([float('inf'), float('-inf')], None).where(pd.notnull(df), None)
|
|
348
380
|
payload = build_react_payload(df, deep_stats=None)
|
|
349
381
|
return payload
|
|
@@ -356,6 +388,9 @@ def upload_csv(
|
|
|
356
388
|
|
|
357
389
|
# Static file serving
|
|
358
390
|
frontend_dir = Path(__file__).parent / "static"
|
|
391
|
+
assets_dir = frontend_dir / "assets"
|
|
392
|
+
if assets_dir.exists():
|
|
393
|
+
app.mount("/assets", StaticFiles(directory=assets_dir), name="assets")
|
|
359
394
|
|
|
360
395
|
|
|
361
396
|
@app.get("/")
|
|
@@ -395,7 +430,3 @@ def serve_spa_fallback(full_path: str):
|
|
|
395
430
|
|
|
396
431
|
return JSONResponse(status_code=404, content={"error": "Not found."})
|
|
397
432
|
|
|
398
|
-
|
|
399
|
-
assets_dir = frontend_dir / "assets"
|
|
400
|
-
if assets_dir.exists():
|
|
401
|
-
app.mount("/assets", StaticFiles(directory=assets_dir), name="assets")
|
|
@@ -20,21 +20,21 @@ from gitlytics.process import build_json_payload, build_react_payload
|
|
|
20
20
|
logger = logging.getLogger(__name__)
|
|
21
21
|
|
|
22
22
|
|
|
23
|
-
def get_csv_path(data_dir: str, mode: str) -> str:
|
|
24
|
-
#
|
|
23
|
+
def get_csv_path(data_dir: str, mode: str, ref_date: datetime = None) -> str:
|
|
24
|
+
# Use ref_date (actual data month) instead of today to avoid cross-month file naming bugs.
|
|
25
25
|
data_dir_path = Path(data_dir).resolve()
|
|
26
26
|
data_dir_path.mkdir(parents=True, exist_ok=True)
|
|
27
27
|
|
|
28
|
-
|
|
28
|
+
d = ref_date or datetime.now(timezone.utc)
|
|
29
29
|
if mode == "yearly":
|
|
30
|
-
filename = f"traffic_{
|
|
30
|
+
filename = f"traffic_{d.year}.csv"
|
|
31
31
|
else:
|
|
32
|
-
|
|
33
|
-
filename = f"traffic_{today.strftime('%Y-%m')}.csv"
|
|
32
|
+
filename = f"traffic_{d.strftime('%Y-%m')}.csv"
|
|
34
33
|
|
|
35
34
|
return str(data_dir_path / filename)
|
|
36
35
|
|
|
37
36
|
|
|
37
|
+
|
|
38
38
|
def export_json_database(data_dir: str, export_path: str, export_public_only: bool = True):
|
|
39
39
|
# Read every CSV in the data folder and merge them into one big JSON file for the dashboard
|
|
40
40
|
data_dir_path = Path(data_dir).resolve()
|
|
@@ -105,36 +105,20 @@ def _merge_schema(existing_fields: list, new_fields: list) -> list:
|
|
|
105
105
|
return original_for_norm
|
|
106
106
|
|
|
107
107
|
|
|
108
|
-
def
|
|
109
|
-
#
|
|
110
|
-
df = fetch_traffic_data(token, repo_names, metrics)
|
|
111
|
-
|
|
112
|
-
# Always regenerate the export if requested, even when fresh data is empty,
|
|
113
|
-
# so the export file never becomes silently stale.
|
|
114
|
-
if export_json:
|
|
115
|
-
export_json_database(data_dir, export_json, export_public_only)
|
|
116
|
-
|
|
117
|
-
if df.empty:
|
|
118
|
-
logger.info("No traffic data found to sync.")
|
|
119
|
-
return
|
|
120
|
-
|
|
121
|
-
# Figure out which CSV file to write to based on today's date
|
|
122
|
-
csv_path = get_csv_path(data_dir, output_mode)
|
|
108
|
+
def _write_df_to_csv(df: pd.DataFrame, csv_path: str) -> int:
|
|
109
|
+
# Merge incoming df rows into the target CSV file, returns count of new records added.
|
|
123
110
|
file_exists = os.path.exists(csv_path)
|
|
124
|
-
|
|
125
111
|
existing_fields = None
|
|
126
112
|
existing_data = {}
|
|
127
113
|
|
|
128
114
|
if file_exists:
|
|
129
|
-
|
|
130
|
-
with open(csv_path, "r", encoding="utf-8-sig", newline="") as f:
|
|
115
|
+
with open(csv_path, "r", encoding="utf-8", newline="") as f:
|
|
131
116
|
reader = csv.reader(f)
|
|
132
117
|
try:
|
|
133
118
|
existing_fields = next(reader)
|
|
134
119
|
except StopIteration:
|
|
135
120
|
pass
|
|
136
121
|
|
|
137
|
-
# Load all existing rows in one pass — avoid iterrows() on large files.
|
|
138
122
|
try:
|
|
139
123
|
existing_df = pd.read_csv(csv_path)
|
|
140
124
|
for record in existing_df.to_dict("records"):
|
|
@@ -143,14 +127,12 @@ def run_sync_cycle(token: str, repo_names=None, data_dir="./data", output_mode="
|
|
|
143
127
|
except Exception as exc:
|
|
144
128
|
logger.warning(f"Could not read existing CSV '{csv_path}': {exc}. Starting fresh.")
|
|
145
129
|
|
|
146
|
-
# Merge old and new column schemas so we never lose new fields
|
|
147
130
|
new_fields = list(df.columns)
|
|
148
131
|
if existing_fields:
|
|
149
132
|
existing_fields = _merge_schema(existing_fields, new_fields)
|
|
150
133
|
else:
|
|
151
134
|
existing_fields = new_fields
|
|
152
135
|
|
|
153
|
-
# Merge fresh data into existing rows — preserves columns not present in this sync run
|
|
154
136
|
new_records_added = 0
|
|
155
137
|
for record in df.to_dict("records"):
|
|
156
138
|
key = (str(record.get("repository", "")), str(record.get("date", "")))
|
|
@@ -160,26 +142,20 @@ def run_sync_cycle(token: str, repo_names=None, data_dir="./data", output_mode="
|
|
|
160
142
|
else:
|
|
161
143
|
existing_data[key].update(record)
|
|
162
144
|
|
|
163
|
-
# Sort all rows by date and repo name before writing back to disk
|
|
164
145
|
final_rows = []
|
|
165
146
|
for v in existing_data.values():
|
|
166
|
-
# Fill any missing schema columns with empty strings for old rows
|
|
167
147
|
clean_row = {}
|
|
168
148
|
for k in existing_fields:
|
|
169
149
|
nk = _normalize_field(k)
|
|
170
150
|
if nk in v:
|
|
171
151
|
clean_row[k] = v[nk]
|
|
172
152
|
else:
|
|
173
|
-
# Try to match by normalized name to old-style keys in the dict.
|
|
174
153
|
match = next((orig for orig in v.keys() if _normalize_field(orig) == nk), None)
|
|
175
154
|
clean_row[k] = v[match] if match is not None else ""
|
|
176
155
|
final_rows.append(clean_row)
|
|
177
156
|
|
|
178
157
|
final_rows.sort(key=lambda x: (str(x.get("date", "")), str(x.get("repository", ""))))
|
|
179
158
|
|
|
180
|
-
# Atomic write: dump to a sibling .tmp file then os.replace() it into
|
|
181
|
-
# place. A crash mid-write leaves the original CSV intact, so a single
|
|
182
|
-
# interrupted sync never corrupts the user's whole traffic history.
|
|
183
159
|
tmp_path = csv_path + ".tmp"
|
|
184
160
|
with open(tmp_path, "w", newline="", encoding="utf-8") as f:
|
|
185
161
|
writer = csv.DictWriter(f, fieldnames=existing_fields, extrasaction='ignore')
|
|
@@ -187,7 +163,51 @@ def run_sync_cycle(token: str, repo_names=None, data_dir="./data", output_mode="
|
|
|
187
163
|
writer.writerows(final_rows)
|
|
188
164
|
os.replace(tmp_path, csv_path)
|
|
189
165
|
|
|
190
|
-
|
|
166
|
+
return new_records_added
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def run_sync_cycle(token: str, repo_names=None, data_dir="./data", output_mode="monthly", export_json=None, export_public_only=True, metrics: list = None):
|
|
170
|
+
df = fetch_traffic_data(token, repo_names, metrics)
|
|
171
|
+
|
|
172
|
+
if export_json:
|
|
173
|
+
export_json_database(data_dir, export_json, export_public_only)
|
|
174
|
+
|
|
175
|
+
if df.empty:
|
|
176
|
+
logger.info("No traffic data found to sync.")
|
|
177
|
+
return
|
|
178
|
+
|
|
179
|
+
total_new = 0
|
|
180
|
+
|
|
181
|
+
if output_mode == "monthly" and "date" in df.columns:
|
|
182
|
+
# Group rows by their actual data month so June data never lands in a July file.
|
|
183
|
+
df["_month"] = pd.to_datetime(df["date"], errors="coerce").dt.strftime("%Y-%m")
|
|
184
|
+
# Warn about rows with unparseable dates — groupby(dropna=True) drops NaN keys
|
|
185
|
+
# silently, which can cause data loss without any logging.
|
|
186
|
+
bad_mask = df["_month"].isna()
|
|
187
|
+
bad_count = bad_mask.sum()
|
|
188
|
+
if bad_count:
|
|
189
|
+
logger.warning(
|
|
190
|
+
"Dropping %d row(s) with unparseable date values (set to NaT). "
|
|
191
|
+
"Check your data for malformed dates.", bad_count
|
|
192
|
+
)
|
|
193
|
+
df = df[~bad_mask]
|
|
194
|
+
for month_key, group in df.groupby("_month"):
|
|
195
|
+
group = group.drop(columns=["_month"])
|
|
196
|
+
try:
|
|
197
|
+
ref_dt = datetime.strptime(month_key, "%Y-%m").replace(tzinfo=timezone.utc)
|
|
198
|
+
except ValueError:
|
|
199
|
+
ref_dt = datetime.now(timezone.utc)
|
|
200
|
+
csv_path = get_csv_path(data_dir, output_mode, ref_dt)
|
|
201
|
+
added = _write_df_to_csv(group, csv_path)
|
|
202
|
+
total_new += added
|
|
203
|
+
logger.info(f"Wrote {added} new records for {month_key} → {csv_path}")
|
|
204
|
+
else:
|
|
205
|
+
# Yearly mode or no date column — fall back to a single file keyed by run date.
|
|
206
|
+
csv_path = get_csv_path(data_dir, output_mode)
|
|
207
|
+
total_new = _write_df_to_csv(df, csv_path)
|
|
208
|
+
logger.info(f"Successfully processed traffic data. Added {total_new} new daily records to {csv_path}")
|
|
209
|
+
|
|
210
|
+
logger.info(f"Sync complete. Total new records: {total_new}")
|
|
191
211
|
|
|
192
212
|
|
|
193
213
|
def _interruptible_sleep(total_seconds: float) -> None:
|
|
@@ -6,6 +6,8 @@
|
|
|
6
6
|
gitlytics/core.py
|
|
7
7
|
Handles fetching traffic and deep metadata from the GitHub API.
|
|
8
8
|
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
9
11
|
import json
|
|
10
12
|
import logging
|
|
11
13
|
import re
|
|
@@ -184,13 +186,13 @@ def _fetch_public_repos_by_stars(username: str, per_page: int) -> list:
|
|
|
184
186
|
|
|
185
187
|
|
|
186
188
|
def get_public_repos(username: str, max_repos: int = 50) -> list:
|
|
187
|
-
username = validate_github_username(username)
|
|
188
189
|
"""
|
|
189
190
|
Fetches up to max_repos best public repos for a username using two calls:
|
|
190
191
|
1. Most recently updated (catches active projects)
|
|
191
192
|
2. Most starred via Search API (catches famous older projects)
|
|
192
193
|
The two lists are merged, deduplicated, sorted by stars, and capped at max_repos.
|
|
193
194
|
"""
|
|
195
|
+
username = validate_github_username(username)
|
|
194
196
|
# Don't request more than the caller actually wants.
|
|
195
197
|
per_page = min(50, max_repos) if max_repos > 0 else 50
|
|
196
198
|
recent = _fetch_public_repos_by_updated(username, per_page=per_page)
|
|
@@ -679,10 +681,18 @@ def fetch_traffic_data(token: str, repo_names=None, metrics: list = None) -> pd.
|
|
|
679
681
|
# to get_all_repos (which would fetch every accessible repo).
|
|
680
682
|
if len(repo_names) == 0:
|
|
681
683
|
return pd.DataFrame()
|
|
682
|
-
repos = [
|
|
684
|
+
repos = []
|
|
685
|
+
for name in repo_names:
|
|
686
|
+
try:
|
|
687
|
+
repos.append(get_single_repo(token, name))
|
|
688
|
+
except ValueError as exc:
|
|
689
|
+
logger.warning("Skipping unknown repo '%s': %s", name, exc)
|
|
683
690
|
else:
|
|
684
691
|
repos = get_all_repos(token)
|
|
685
692
|
|
|
693
|
+
if not repos:
|
|
694
|
+
return pd.DataFrame()
|
|
695
|
+
|
|
686
696
|
all_rows = []
|
|
687
697
|
for repo in repos:
|
|
688
698
|
traffic = get_repo_traffic(token, repo["full_name"], metrics)
|
|
@@ -135,6 +135,18 @@ def build_json_payload(df: pd.DataFrame, return_format: str = "timeseries", expo
|
|
|
135
135
|
}
|
|
136
136
|
|
|
137
137
|
|
|
138
|
+
_LEGACY_COLUMN_MAP = {
|
|
139
|
+
"repository": "repository",
|
|
140
|
+
"repo_name": "repository",
|
|
141
|
+
"total views": "views",
|
|
142
|
+
"unique visitors": "unique_visitors",
|
|
143
|
+
"total clones": "clones",
|
|
144
|
+
"unique cloners": "unique_cloners",
|
|
145
|
+
"stars": "stars",
|
|
146
|
+
"forks": "forks",
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
|
|
138
150
|
def process_uploaded_csv(uploaded_file) -> pd.DataFrame:
|
|
139
151
|
"""Reads a user-uploaded CSV and normalises column names to match our tidy schema."""
|
|
140
152
|
raw_df = pd.read_csv(uploaded_file)
|
|
@@ -146,12 +158,19 @@ def process_uploaded_csv(uploaded_file) -> pd.DataFrame:
|
|
|
146
158
|
rename_lower = {c: c.lower() for c in raw_df.columns}
|
|
147
159
|
raw_df = raw_df.rename(columns=rename_lower)
|
|
148
160
|
|
|
161
|
+
# Map legacy display names (e.g. "Total Views", "Unique Visitors") to the
|
|
162
|
+
# canonical schema columns that build_react_payload / build_json_payload expect.
|
|
163
|
+
# Without this, multi-word legacy headers like "total views" stay as-is after
|
|
164
|
+
# lower-casing and downstream code silently returns 0 for those metrics.
|
|
165
|
+
legacy_rename = {}
|
|
166
|
+
for legacy, canonical in _LEGACY_COLUMN_MAP.items():
|
|
167
|
+
if legacy in raw_df.columns and canonical not in raw_df.columns:
|
|
168
|
+
legacy_rename[legacy] = canonical
|
|
169
|
+
if legacy_rename:
|
|
170
|
+
raw_df = raw_df.rename(columns=legacy_rename)
|
|
171
|
+
|
|
149
172
|
if "repository" not in raw_df.columns:
|
|
150
|
-
|
|
151
|
-
if "repo_name" in raw_df.columns:
|
|
152
|
-
raw_df = raw_df.rename(columns={"repo_name": "repository"})
|
|
153
|
-
else:
|
|
154
|
-
raise ValueError("Invalid CSV format: missing 'repository' column")
|
|
173
|
+
raise ValueError("Invalid CSV format: missing 'repository' column")
|
|
155
174
|
|
|
156
175
|
if "date" not in raw_df.columns:
|
|
157
176
|
raise ValueError("Invalid CSV format: missing required 'date' column")
|
|
@@ -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 I,U as G}from"./index-Bi9mu2Wz.js";import{b as T}from"./exports-CBIW6Z6w.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((s,r)=>s+(Number(r.stars)||0),0),x=t.reduce((s,r)=>s+(Number(r.forks)||0),0),z=t.length,b=new Map;for(const s of t){const r=k(s);b.set(r,(b.get(r)||0)+1)}const F=[...b.entries()].sort((s,r)=>r[1]-s[1]).slice(0,3).map(([s])=>s),P=[...t].sort((s,r)=>(Number(r.stars)||0)-(Number(s.stars)||0))[0],N=[...b.values()].reduce((s,r)=>s+r,0),M=[...b.entries()].sort((s,r)=>r[1]-s[1]).slice(0,3).map(([s,r])=>({name:s,percentage:N>0?Math.round(r/N*100):0}));return{totalStars:l,totalForks:x,repoCount:z,topLangs:F,popular:P,langShares:M}},[t]);async function S(){n(!0);try{await T(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(B,{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("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 B({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(I,{className:"h-4 w-4"}),label:"Repos",value:f,colorClass:"text-chart-3"}),t.followers&&e.jsx(h,{icon:e.jsx(G,{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};
|
|
@@ -1 +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-
|
|
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-Bi9mu2Wz.js";import{r as G,a as I}from"./exports-CBIW6Z6w.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};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/jspdf.es.min-
|
|
2
|
-
import{t as S,e as _,c as W,_ as D}from"./index-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/jspdf.es.min-WsKal4G6.js","assets/index-Bi9mu2Wz.js","assets/index-BRI0yQ1K.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{t as S,e as _,c as W,_ as D}from"./index-Bi9mu2Wz.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
3
|
.recharts-wrapper, .recharts-surface { overflow: visible !important; }
|
|
4
4
|
.recharts-responsive-container { overflow: visible !important; }
|
|
5
5
|
.recharts-cartesian-axis-tick text { font-size: 11px; }
|
|
@@ -11,4 +11,4 @@ import{t as S,e as _,c as W,_ as D}from"./index-qzHj2txI.js";function R(t,o){typ
|
|
|
11
11
|
transition-duration: 0s !important;
|
|
12
12
|
transition-delay: 0s !important;
|
|
13
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-
|
|
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-WsKal4G6.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};
|