Skip to content

Instantly share code, notes, and snippets.

@gentlegiantJGC
Created September 11, 2022 11:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gentlegiantJGC/6f4d90249010a9e5d6b8f779c9f29660 to your computer and use it in GitHub Desktop.
Save gentlegiantJGC/6f4d90249010a9e5d6b8f779c9f29660 to your computer and use it in GitHub Desktop.
Get the total download count for all assets in all releases for a repository.
from urllib.request import urlopen, Request
import json
# The Github API has a rate limit. This can be increased with the use of an access token.
# An access token is required if there are many releases.
# You can create one here: https://github.com/settings/tokens/new
# The access token does not need any permissions unless you are using this on a private repository in which case it needs the repo permission.
TOKEN = "" # Put your token here. Do not share it online.
OWNER = "Amulet-Team"
REPO = "Amulet-Map-Editor"
def get_json(url: str):
headers = {"Authorization": f"token {TOKEN}"} if TOKEN else {}
request = Request(url, headers=headers)
with urlopen(request) as response:
return json.load(response)
def get_release_downloads(assets_url: str):
"""Get the download count for all asserts in a single release."""
assets = get_json(assets_url)
assert isinstance(assets, list)
return sum(asset["download_count"] for asset in assets)
def get_downloads(owner: str, repo: str) -> dict[str, int]:
"""Get a dictionary mapping version number to download count for all versions."""
versions = {}
page = 1
while True:
releases = get_json(
f"https://api.github.com/repos/{owner}/{repo}/releases?page={page}"
)
page += 1
if not isinstance(releases, list) or not releases:
break
for release in releases:
print(release["tag_name"])
versions[release["tag_name"]] = get_release_downloads(release["assets_url"])
return versions
def get_download_count(owner: str, repo: str):
return sum(get_downloads(owner, repo).values())
def main():
print(get_download_count(OWNER, REPO))
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment