-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgithub_insights.py
More file actions
347 lines (314 loc) · 11.6 KB
/
Copy pathgithub_insights.py
File metadata and controls
347 lines (314 loc) · 11.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
import os
from datetime import datetime
import json
import shutil
from src.api import fetch_repo_views, fetch_repo_clones, fetch_repo_referrals
from src.data_processing import merge_data, save_data, preprocess_data
if __name__ == "__main__":
pat_token = os.getenv("INPUT_PAT-TOKEN")
repos = os.getenv("INPUT_REPOS").split(",")
if not pat_token or not repos:
raise ValueError("Both 'pat-token' and 'repos' must be provided.")
DOCS_DIR = "docs"
DATA_DIR = os.path.join(DOCS_DIR, "data")
DOCSIFY_INDEX_HTML_CONTENT = """<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>GitHub Repository Insights</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="description" content="Description">
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0">
<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/docsify/lib/themes/buble.css" />
</head>
<body>
<div id="app"></div>
<script>
window.$docsify = {
name: 'GitHub Repository Insights',
repo: 'emillg/github-repo-insights',
subMaxLevel: 3
};
</script>
<script src="//cdn.jsdelivr.net/npm/docsify/lib/docsify.min.js"></script>
<script src="//cdn.jsdelivr.net/npm/vega@6"></script>
<script src="//cdn.jsdelivr.net/npm/vega-lite@6"></script>
<script src="//cdn.jsdelivr.net/npm/vega-embed@7"></script>
<script src="//cdn.jsdelivr.net/gh/jerCarre/vega_docsify@v1.1/lib/docsivega.js"></script>
</body>
</html>
"""
if os.path.exists("insights/data/"):
images_dir = os.path.join("insights", "images")
if os.path.exists(images_dir):
print("Deleting insights/images directory ...")
shutil.rmtree(images_dir)
print("Renaming 'insights' directory to 'docs' ...")
os.rename("insights", "docs")
else:
os.makedirs(DATA_DIR, exist_ok=True)
current_date = datetime.now().strftime("%Y%m%d")
raw_data_dir = f"{DATA_DIR}/raw/{current_date}"
os.makedirs(raw_data_dir, exist_ok=True)
markdown_content = ""
repo_views_summary = {}
repo_clones_summary = {}
try:
for repo in repos:
repo_safe_name = repo.replace("/", "_")
# Fetch data from GitHub
print(f"Fetching data for {repo}...")
views_data = fetch_repo_views(repo, pat_token)
clones_data = fetch_repo_clones(repo, pat_token)
referrals_data = fetch_repo_referrals(repo, pat_token)
# Save raw data
print(f"Saving raw data for {repo}...")
raw_views_file = f"{raw_data_dir}/{repo_safe_name}_views.json"
raw_clones_file = f"{raw_data_dir}/{repo_safe_name}_clones.json"
raw_referrals_file = f"{raw_data_dir}/{repo_safe_name}_referrals.json"
save_data(views_data, raw_views_file)
save_data(clones_data, raw_clones_file)
save_data(referrals_data, raw_referrals_file)
# Process and merge data
print(f"Processing data for {repo}...")
views_data_cleaned = {"views": views_data["views"]}
clones_data_cleaned = {"clones": clones_data["clones"]}
views_file = f"{DATA_DIR}/{repo_safe_name}_views.json"
clones_file = f"{DATA_DIR}/{repo_safe_name}_clones.json"
referrals_file = f"{DATA_DIR}/{repo_safe_name}_referrals.json"
merged_views = merge_data(views_data_cleaned, views_file, "views")
merged_clones = merge_data(
clones_data_cleaned, clones_file, "clones")
save_data(merged_views, views_file)
save_data(merged_clones, clones_file)
save_data(referrals_data, referrals_file)
repo_views_summary[repo] = sum(item["count"]
for item in merged_views["views"])
repo_clones_summary[repo] = sum(item["count"]
for item in merged_clones["clones"])
# Preprocess data for plotting
total_views = preprocess_data(merged_views["views"])
unique_views = preprocess_data([
{"timestamp": item["timestamp"], "count": item["uniques"]}
for item in merged_views["views"]
])
total_clones = preprocess_data(merged_clones["clones"])
unique_clones = preprocess_data([
{"timestamp": item["timestamp"], "count": item["uniques"]}
for item in merged_clones["clones"]
])
# Generate charts
print(f"Generating charts for {repo}...")
repo_views_chart = """
```vega
{{
"$schema": "https://vega.github.io/schema/vega-lite/v6.json",
"width": 800,
"title": "Visitors for {repo}",
"data": {{
"values": [
{values_data}
]
}},
"mark": "line",
"encoding": {{
"x": {{
"field": "date",
"type": "temporal",
"title": "Date",
"scale": {{ "type": "utc" }},
"axis": {{
"format": "%Y-%m-%d",
"labelAngle": -45,
"labelOverlap": false,
"tickCount": {{"interval": "day", "step": 1}}
}}
}},
"y": {{"field": "value", "type": "quantitative", "title": "Views"}},
"color": {{
"field": "type",
"type": "nominal",
"legend": {{
"title": null
}}
}},
"tooltip": [
{{ "field": "date", "type": "temporal", "title": "Date" }},
{{ "field": "type", "type": "nominal", "title": "Metric" }},
{{ "field": "value", "type": "quantitative", "title": "Value" }}
]
}}
}}
```
""".format(
repo=repo,
values_data=",\n ".join(
json.dumps(
{"date": item["timestamp"][:10], "type": "Total Views", "value": item["count"]})
for item in merged_views["views"])
+ ",\n "
+ ",\n ".join(
json.dumps(
{"date": item["timestamp"][:10], "type": "Unique Views", "value": item["uniques"]})
for item in merged_views["views"]))
repo_clones_chart = """
```vega
{{
"$schema": "https://vega.github.io/schema/vega-lite/v6.json",
"width": 800,
"title": "Git Clones for {repo}",
"data": {{
"values": [
{values_data}
]
}},
"mark": "line",
"encoding": {{
"x": {{
"field": "date",
"type": "temporal",
"title": "Date",
"scale": {{ "type": "utc" }},
"axis": {{
"format": "%Y-%m-%d",
"labelAngle": -45,
"labelOverlap": false,
"tickCount": {{"interval": "day", "step": 1}}
}}
}},
"y": {{"field": "value", "type": "quantitative", "title": "Clones"}},
"color": {{
"field": "type",
"type": "nominal",
"legend": {{
"title": null
}}
}},
"tooltip": [
{{ "field": "date", "type": "temporal", "title": "Date" }},
{{ "field": "type", "type": "nominal", "title": "Metric" }},
{{ "field": "value", "type": "quantitative", "title": "Value" }}
]
}}
}}
```
""".format(
repo=repo,
values_data=",\n ".join(
json.dumps(
{"date": item["timestamp"][:10], "type": "Total Clones", "value": item["count"]})
for item in merged_clones["clones"]
)
+ ",\n "
+ ",\n ".join(
json.dumps({"date": item["timestamp"][:10],
"type": "Unique Clones", "value": item["uniques"]})
for item in merged_clones["clones"]
)
)
# Generate Markdown content
print(f"Generating Markdown for {repo}...")
repo_url = f"https://github.com/{repo}"
markdown_content += """### {repo}
[]({repo_url})
[]({repo_url}/stargazers)
[]({repo_url}/network/members)
[]({repo_url}/watchers)
{repo_views_chart}
{repo_clones_chart}
""".format(
repo=repo,
repo_url=repo_url,
repo_views_chart=repo_views_chart,
repo_clones_chart=repo_clones_chart
)
markdown_content += "| Referral Source | Views | Unique Visitors |\n"
markdown_content += "|-|-|-|\n"
for referral in referrals_data:
markdown_content += f"| {referral['referrer']} | {referral['count']} | {referral['uniques']} |\n"
markdown_content += "\n"
print("Generating top 10 repositories charts...")
sorted_views = sorted(repo_views_summary.items(),
key=lambda x: x[1], reverse=True)[:10]
sorted_clones = sorted(repo_clones_summary.items(),
key=lambda x: x[1], reverse=True)[:10]
print("Generating chart for top 10 repositories by views...")
view_values = [item[1] for item in sorted_views]
overview_views_chart = """
```vega
{{
"$schema": "https://vega.github.io/schema/vega-lite/v6.json",
"width": 800,
"height": 300,
"title": "Top 10 Repositories by Visitors",
"data": {{
"values": [
{values_data}
]
}},
"mark": {{
"type": "bar",
"color": "#ff7f0e"
}},
"encoding": {{
"y": {{"field": "repository", "type": "nominal", "title": "Repository", "sort": "-x"}},
"x": {{"field": "views", "type": "quantitative", "title": "Total Views"}}
}}
}}
```
""".format(
values_data=", ".join(
f'{{"repository": "{repo.split("/")[-1]}", "views": {views}}}'
for repo, views in sorted_views
)
)
clone_values = [item[1] for item in sorted_clones]
print("Generating chart for top 10 repositories by clones...")
overview_clones_chart = """
```vega
{{
"$schema": "https://vega.github.io/schema/vega-lite/v6.json",
"width": 800,
"height": 300,
"title": "Top 10 Repositories by Git Clones",
"data": {{
"values": [
{values_data}
]
}},
"mark": {{
"type": "bar",
"color": "#ff7f0e"
}},
"encoding": {{
"y": {{"field": "repository", "type": "nominal", "title": "Repository", "sort": "-x"}},
"x": {{"field": "clones", "type": "quantitative", "title": "Total Clones"}}
}}
}}
```
""".format(
values_data=", ".join(
f'{{"repository": "{repo.split("/")[-1]}", "clones": {clones}}}'
for repo, clones in sorted_clones
)
)
# Add the top 10 charts to the beginning of the Markdown content
overview_content = """# Insights
## Overview
{overview_views_chart}
{overview_clones_chart}
""".format(
overview_views_chart=overview_views_chart,
overview_clones_chart=overview_clones_chart
)
breakdown_content = "## Repository Breakdown\n\n"
# Combine overview and per-repo content
markdown_content = overview_content + breakdown_content + markdown_content
with open(f"{DOCS_DIR}/README.md", "w") as markdown_file:
markdown_file.write(markdown_content)
print("Generating index.html for Docsify...")
with open(f"{DOCS_DIR}/index.html", "w") as mkdocs_file:
mkdocs_file.write(DOCSIFY_INDEX_HTML_CONTENT)
print("Insights generated successfully!")
except Exception as e:
print(f"Error: {e}")