1+ import os
2+ import requests
3+ from datetime import datetime
4+
5+ ### setup env variables
6+ GITHUB_PAT = os .getenv ("GHRS_GITHUB_API_TOKEN" )
7+ GITHUB_OWNER = os .getenv ("TRAFFIC_ACTION_OWNER" )
8+ GITHUB_REPO = os .getenv ("TRAFFIC_ACTION_REPO" )
9+
10+
11+ output_dir = "traffic/"
12+ os .makedirs (output_dir , exist_ok = True )
13+ current_date = datetime .today ().strftime ('%Y-%m-%d' )
14+
15+ # Define API endpoint URLs
16+ endpoints = [
17+ "/repos/{}/{}/traffic/clones" .format (GITHUB_OWNER , GITHUB_REPO ),
18+ "/repos/{}/{}/traffic/popular/paths" .format (GITHUB_OWNER , GITHUB_REPO ),
19+ "/repos/{}/{}/traffic/popular/referrers" .format (GITHUB_OWNER , GITHUB_REPO ),
20+ "/repos/{}/{}/traffic/views" .format (GITHUB_OWNER , GITHUB_REPO )
21+ ]
22+
23+ # Function to fetch data from GitHub API
24+ def fetch_data (endpoint ):
25+ url = "https://api.github.com" + endpoint
26+ headers = {
27+ "Accept" : "application/vnd.github.v3+json" ,
28+ "Authorization" : f"token { GITHUB_PAT } "
29+ }
30+ response = requests .get (url , headers = headers )
31+ return response .json ()
32+
33+
34+ # Loop through the endpoints and fetch traffic data
35+ for endpoint in endpoints :
36+ data = fetch_data (endpoint )
37+ print (data )
38+ with open (os .path .join (output_dir , current_date , endpoint .split ('/' )[- 1 ] + ".json" ), "w" ) as f :
39+ json .dump (data , f )
40+
41+
42+ # Write summary to a CSV file
43+ with open (os .path .join (output_dir , "summary.csv" ), "a" ) as summary_file :
44+ summary_file .write (
45+ "{},{},{},{},{}\n " .format (
46+ current_date ,
47+ json .loads (open (os .path .join (output_dir , current_date , "clones.json" )).read ())["count" ],
48+ json .loads (open (os .path .join (output_dir , current_date , "clones.json" )).read ())["uniques" ],
49+ json .loads (open (os .path .join (output_dir , current_date , "views.json" )).read ())["count" ],
50+ json .loads (open (os .path .join (output_dir , current_date , "views.json" )).read ())["uniques" ]
51+ )
52+ )
0 commit comments