Skip to content

Instantly share code, notes, and snippets.

@AstraLuma
Created December 17, 2024 02:13
Show Gist options
  • Select an option

  • Save AstraLuma/d8de1337d4e62b01597f625e13052190 to your computer and use it in GitHub Desktop.

Select an option

Save AstraLuma/d8de1337d4e62b01597f625e13052190 to your computer and use it in GitHub Desktop.
GitHub Stats
#!/usr/bin/env python3
"""
Uses GitHub's contributions APIs to summarize your activity on GitHub.
Leaves a stats.json with the stats of each block of time.
Must have the GitHub CLI installed and authenticated.
"""
import datetime
import json
import subprocess
def gh_gql(query, **variables):
varopts = []
for k,v in variables.items():
varopts += ['-f', f'{k}={v}']
proc = subprocess.run(
['gh', 'api', 'graphql', '--paginate','-f', f'query={query}', *varopts],
stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, text=True, check=True,
)
return json.loads(proc.stdout)['data']
CONTRIBUTIONS_QUERY = """
query($start:DateTime!, $end:DateTime!) {
viewer {
contributionsCollection(
from: $start
to: $end
) {
endedAt
startedAt
hasActivityInThePast
totalCommitContributions
totalIssueContributions
totalPullRequestContributions
totalRepositoriesWithContributedCommits
totalRepositoriesWithContributedIssues
totalRepositoriesWithContributedPullRequests
commitContributionsByRepository(maxRepositories:100) {
repository {
nameWithOwner
}
}
issueContributionsByRepository(maxRepositories:100) {
repository {
nameWithOwner
}
}
pullRequestContributionsByRepository(maxRepositories:100) {
repository {
nameWithOwner
}
}
}
}
}
"""
INCREMENT = datetime.timedelta(days=30)
keep_going = True
end_time = datetime.datetime.now(datetime.timezone.utc)
blocks = []
while keep_going:
start_time = end_time - INCREMENT
print(start_time, end=' ', flush=True)
res = gh_gql(
CONTRIBUTIONS_QUERY,
start=start_time.isoformat(timespec='seconds').replace('+00:00', 'Z'),
end=end_time.isoformat(timespec='seconds').replace('+00:00', 'Z'),
)
cc = res['viewer']['contributionsCollection']
blocks.append(cc)
print(cc['totalCommitContributions'], cc['totalIssueContributions'], cc['totalPullRequestContributions'])
assert cc['totalRepositoriesWithContributedCommits'] <= 100
assert cc['totalRepositoriesWithContributedIssues'] <= 100
assert cc['totalRepositoriesWithContributedPullRequests'] <= 100
keep_going = cc['hasActivityInThePast']
end_time = start_time
with open('stats.json', 'wt') as f:
json.dump(blocks, f)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment