How to remove a Github Environment - github

My question is about cleaning up the "Environments" tab on a Github repository.
I previously deployed via Heroku, using automatic deployment from two separate Github branches (one for staging, one for production).
This created a tab "Environments" on the repository, in which both Heroku environments were shown - exactly as intended.
Once I started to dive into Heroku pipelines, I have now configured the app to be promoted to production from staging, so the production environment no longer auto-deploys from a branch.
The Environments tab on my Github repo has no way to remove the environment that I no longer use. I can't seem to find any place on Github or Heroku to make Github "forget" this deployment environment.
I hope my question is clear enough; if I can elaborate on anything, please let me know.

I made a little webpage/script too, to automate the process (I don't have Python installed, and I didn't see that someone else had already made a script), and this is online and putting your info will do the process automatically.
Stackblitz - Github Deployments deleter
Edit 18/07/2020: I copied the script from Stackblitz to a local snippet code in here too, just in case Stackblitz disappears:
// RECOMMENDED: Disconnect HEROKU from Github before doing this (though not strictly necessary, I think).
//See https://stackoverflow.com/a/61272173/6569950 for more info.
// PARAMETERS
const TOKEN = ""; // MUST BE `repo_deployments` authorized
const REPO = "your-repo"; // e.g. "monorepo"
const USER_OR_ORG = "your-name"; // e.g. "your-name"
// GLOBAL VARS
const URL = `https://api.github.com/repos/${USER_OR_ORG}/${REPO}/deployments`;
const AUTH_HEADER = `token ${TOKEN}`;
// UTILITY FUNCTIONS
const getAllDeployments = () =>
fetch(`${URL}`, {
headers: {
authorization: AUTH_HEADER
}
}).then(val => val.json());
const makeDeploymentInactive = id =>
fetch(`${URL}/${id}/statuses`, {
method: "POST",
body: JSON.stringify({
state: "inactive"
}),
headers: {
"Content-Type": "application/json",
Accept: "application/vnd.github.ant-man-preview+json",
authorization: AUTH_HEADER
}
}).then(() => id);
const deleteDeployment = id =>
fetch(`${URL}/${id}`, {
method: "DELETE",
headers: {
authorization: AUTH_HEADER
}
}).then(() => id);
// MAIN
getAllDeployments()
.catch(console.error)
.then(res => {
console.log(`${res.length} deployments found`);
return res;
})
.then(val => val.map(({
id
}) => id))
.then(ids => Promise.all(ids.map(id => makeDeploymentInactive(id))))
.then(res => {
console.log(`${res.length} deployments marked as "inactive"`);
return res;
})
.then(ids => Promise.all(ids.map(id => deleteDeployment(id))))
.then(res => {
console.log(`${res.length} deployments deleted`);
return res;
})
.then(finalResult => {
const appDiv = document.getElementById("app");
appDiv.innerHTML = `
<h1>CLEANUP RESULT</h1>
<br>
Removed Deployments: ${finalResult.length}
<br>
<br>Ids:<br>
${JSON.stringify(finalResult)}
<br><br><br><br><br><br>
<p>(Open up the console)</p>
`;
});
h1,
h2 {
font-family: Lato;
}
<div id="app">
<h1>Github Deployment's Cleaner</h1>
<p> You need to put the parameters in!</p>
</div>

There doesn't seem to be UI for it, but you can do it using the GitHub API.
You should probably disconnect GitHub and Heroku before doing this.
First, go to your GitHub account settings, then developer settings, then personal access tokens. Create a new token that has repo_deployments allowed. After it's generated, save the hexadecimal token, you'll need it for the upcoming API requests.
For these examples I'll assume that your username is $aaaa and your repo name is $bbbb and your access token is $tttt. Replace these with your actual username and repo name and access token. Or just use shell variables to store the actual values which will let you paste the code blocks directly.
First, list all the deployments on your repo:
curl https://api.github.com/repos/$aaaa/$bbbb/deployments
Each deployment has an id integer. Note it, and replace $iiii in the upcoming code blocks with that ID. Or create another shell variable for it.
Now you have to create an "inactive" status for that deployment:
curl https://api.github.com/repos/$aaaa/$bbbb/deployments/$iiii/statuses -X POST -d '{"state":"inactive"}' -H 'accept: application/vnd.github.ant-man-preview+json' -H "authorization: token $tttt"
And now you can delete the deployment forever:
curl https://api.github.com/repos/$aaaa/$bbbb/deployments/$iiii -X DELETE -H "authorization: token $tttt"
If you have multiple deployments, send the first request to see all the deployments that remain, and then you can delete those too if you want.
After you delete all the deployments, the environments button on the GitHub repo will disappear.
Information sourced from the GitHub deployments documentation and the GitHub oauth documentation. This worked for me.

This will not answer the OP question, I thought it would at first, but it didn't behave as I had expected. Therefore, I'm adding this answer as a community wiki.
GitHub seems to have two notions of "Environments", the one the OP means are "public environments", but GitHub also seems to have some kind of "private environments".
I'm adding my experience as an answer below because it is really confusing.
You can access "private environments" through "Settings > Environments". (E.g: https://github.com/UnlyEd/next-right-now/settings/environments)
You can then delete each environment. It'll prompt a confirm dialog. Upon confirm, the environment will be destroyed.
I deleted the "staging" and "production" environments.
But the public environments still continue to exist, alongside all their deployments. (and this is not what the OP wants)
Public environments still contains "staging" and "production".

I've made an interactive python script which can delete specific environments by name (which was my issue) or all of your deployments. Check it out and let me know if it works for you: https://github.com/VishalRamesh50/Github-Environment-Cleaner.
This will also actually delete all of your deployments even if you have more than 30 unlike the other scripts here because it goes through the paginated response data from Github's API and doesn't just use the first page.

Based on Cadence's answer, I built the following bash script. Just set the appropriate parameters and let it run.
The token requires repo_deployment OAuth scope.
env=asd
token=asd
repo=asd
user=asd
for id in $(curl -u $user:$token https://api.github.com/repos/$user/$repo/deployments\?environment\=$env | jq ".[].id"); do
curl -X POST -u $user:$token -d '{"state":"inactive"}' -H 'accept: application/vnd.github.ant-man-preview+json' https://api.github.com/repos/$user/$repo/deployments/$id/statuses
curl -X DELETE -u $user:$token https://api.github.com/repos/$user/$repo/deployments/$id
done

I Expect Your already got the answer for your question This answer is for those who wan't to Remove The Environments Tab from There GitHib Repo
As I Understand
If You Want to Remove the Environments Tab Shown on The Right Side of The Screen
If You Want to Remove Specific Environments
Remove Environments Tab
To Remove Entire Tab
On Your Repo Page Click on Settings Button
Uncheck the Mark on Environments
It Will Remove The Environments Tab from the Right Side
Remove Specific Environments
For Removing Specific Environment
Click on SettingsClick On EnvironmentsHere You Can Remove a Specific Environment
Reply from GitHub for Removing of Environments from Private Repo
Hi Deekshith,
Thanks for writing in!
As it turns out, the Environments feature is an enterprise-only feature for private repositories, however, they still get created as a side effect of Deployments in private repositories.
https://docs.github.com/en/actions/deployment/targeting-different-environments/using-environments-for-deployment
This means that though you'd be able to create Deployments in a private repository, you won't be able to manage (e.g delete, add rules e.t.c) the deployment Environments. I'm afraid this is currently the expected behaviour. Our engineers are still discussing how best to help users who'd want to delete environments in non-enterprise private repositories, such as in your case. We’ll be sure to update you as soon as there’s any news to share.
Sorry that we could not be of more help with this -- please let us know if you have any questions at all!
Regards,
Peter
GitHub Support

I've built an online tool to help out removing deployments
I ran into the same problem and found #spersico's code very handy, but needed a bit more tooling/feedback. I iterated on #spersico code to add a bit of frontend.
Same as #spersico's version, all calls are made client side (and are visible in your console/network logs).
Project is opensource on Github and has a hosted version on Netlify which can be used instantly:
https://github-deployment-cleaner.netlify.app/

Unfortunately, it seems that the 'Deployments' dashboard is currently in beta, which means that they may not have a feature yet.
Read here.

I've just used this Python script: 5 minutes and I removed my unwanted environment:
https://github.com/VishalRamesh50/Github-Environment-Cleaner
There is a discussion in GitHub Community: https://github.community/t/how-to-remove-the-environment-tab/10584/10?u=aerendir
Please, vote up the feature.

Using GitHub CLI:
org=':org:'
repo=':repo:'
env=':env:'
gh api "repos/${org}/${repo}/deployments?environment=${env}" \
| jq -r ".[].id" \
| xargs -n 1 -I % sh -c "
gh api -X POST -F state=inactive repos/${org}/${repo}/deployments/%/statuses
gh api -X DELETE repos/${org}/${repo}/deployments/%
"

I don't know if this was posted already but I definitely didn't want do delete my 40+ deployments manually so I created following script, feel free to use it too :)
#!/bin/bash
REPO=<your GH name>/<your project name>
TOKEN=<your personal access token>
# https://starkandwayne.com/blog/bash-for-loop-over-json-array-using-jq/
for deployment in $(curl https://api.github.com/repos/$REPO/deployments | jq -r '.[] | #base64'); do
DEPLOYMENT_ID=$(echo "$deployment" | base64 --decode | jq -r '.id')
echo "$DEPLOYMENT_ID"
curl "https://api.github.com/repos/$REPO/deployments/$DEPLOYMENT_ID/statuses" \
-X POST \
-d '{"state":"inactive"}' \
-H 'accept: application/vnd.github.ant-man-preview+json' \
-H "authorization: token $TOKEN"
done
for deployment in $(curl https://api.github.com/repos/$REPO/deployments | jq -r '.[] | #base64'); do
DEPLOYMENT_ID=$(echo "$deployment" | base64 --decode | jq -r '.id')
curl "https://api.github.com/repos/$REPO/deployments/$DEPLOYMENT_ID" \
-X DELETE \
-H "authorization: token $TOKEN"
done

You can remove the environment from a repository if its public. But in case of private repositories, either you have to make it public or use the github API. Both works, but here is my approach for deleting the environments.
I created an npm package (here) for the same. Just get the github access token, with repo_deployments scope enabled.
Now run npx delete-github-environment and select the environment that you want to delete. If everything went right, your environment will be deleted.
PS: Here's my github repo - (github), feel free to contribute to the code.

To remove a Github Environment go to Settings -> Environments -> and click the trashcan icon next to the Environment you want to delete (see picture below).
More can be read about it from the Github official documentation:
Deleting an Environment

Related

How to pass API parameters to GCP cloud build triggers

I have a large set of GCP Cloud Build Triggers that I invoke via a Cloud scheduler, all running fine.
Now I want to invoke these triggers by an external API call and pass them dynamic parameters that vary in values and number of parameters.
I was able to start a trigger by running an API request but any JSON parameters in the API request that I sent were ignored.
Google talks about substitution parameters at https://cloud.google.com/cloud-build/docs/configuring-builds/substitute-variable-values. I define these variables in the cloudbuild.yaml file, however they were not propagated into my shell script from the API request.
I don't any errors with authentication or authorization, so security may not be an issue.
Is my idea supported at all or do I need to resort to another solution such as running a GKE cluster with containers that would expose its API (a very heavy-boxing solution).
We do something similar -- we migrated from Jenkins to GCB but for some people we still need a nicer "UI" to start builds / pass variables.
I got scripts from here and modified them to our own needs: https://medium.com/#nieldw/put-your-build-triggers-into-source-control-with-the-cloud-build-api-ed0c18d6fcac
Here is their REST API: https://cloud.google.com/cloud-build/docs/api/reference/rest/v1/projects.triggers/run
For the script below, keep in mind you need the trigger-id of what you want to run. (you can also get this by parsing the output of another REST API.)
TRIGGER_ID=1
# we need to specify ATLEAST the branch name or commit id (check after)
BRANCH_OR_SHA=$2
# check if branch_name or commit_sha
if [[ $BRANCH_OR_SHA =~ [0-9a-f]{5,40} ]]; then
# is COMMIT_HASH
COMMIT_SHA=$BRANCH_OR_SHA
BRANCH_OR_SHA="\"commitSha\": \"$COMMIT_SHA\""
else
# is BRANCH_NAME
BRANCH_OR_SHA="\"branchName\": \"$BRANCH_OR_SHA\""
fi
# This is the request we send to google so it knows what to build
# Here we're overriding some variables that we have already set in the default 'cloudbuild.yaml' file of the repo
cat <<EOF > request.json
{
"projectId": "$PROJECT_ID",
$BRANCH_OR_SHA,
"substitutions": {
"_MY_VAR_1": "my_value",
"_MY_VAR_2": "my_value_2"
}
}
EOF
# our curl post, we send 'request.json' with info, add our Token, and set the trigger_id
curl -X POST -T request.json -H "Authorization: Bearer $(gcloud config config-helper \
--format='value(credential.access_token)')" \
https://cloudbuild.googleapis.com/v1/projects/"$PROJECT_ID"/triggers/"$TRIGGER_ID":run

How do I remove a GitHub status check?

I have a GitHub status check generated by TeamCity, and I'm trying to delete it (not just disable it).
I've tried (line breaks added for readability):
curl -u <myusername>:<mytoken>
-X DELETE
https://:github_instance/api/v3/repos/:user/:repo/statuses/:hash
I got the url from:
curl -u <myusername>:<mytoken>
https://:github_instance/api/v3/repos/:user/:repo/statuses/:branch_name
Am I missing something?
Like #VonC I couldn't find a deletion option. However, you can disable any existing checks so that they no longer run on your PRs.
Settings
Branches
Branch protection rules
Edit (next to your desired branch, e.g. 'master')
Rule settings
Require status checks to pass before merging
Require branches to be up to date before merging
< Uncheck any statuses you want to disable! >
I see the GitHub API V3 Repository Statuses (for github.com or for a private GitHub enterprise instance) includes:
Create a status
List statuses for a specific ref
Get the combined status for a specific ref
There is no deletion as far as I can see.

Diff between arbitrary commits in BitBucket

I am running bitbucket server v4.14. I want to be able to get diff of any two commits for a repo. I saw this posted at https://bitbucket.org/site/master/issues/4779/ability-to-diff-between-any-two-commits
However the same does not work, probably cause the version I am running is older. The compare page directly takes me to diff across branches. I do not want any UI element, just a URL is fine.
Thanks
This feature is not available to Bitbucket 4.14.
You can get this data using the REST API. Try to execute the following command:
curl -s --user USER:PASS --request GET https://BITBUCKET-SERVER/rest/api/1.0/projects/PROJECT/repos/REPOSITORY/commits?since=SINCE-COMMIT\&until=UNTIL-COMMIT | jq --raw-output '.values[] | .displayId+ " " + .author.name'
AFAIK there is only rest api endpoint. There is a since parameter that you can pass. See the docs for more details.

How does one find out one's own Repo ID?

While I definitely am not the owner of this private repo, I have been using it as part of a group for a school project, and the teacher is simply asking for the Repo's ID when sending him emails concerning anything. I'm sorry if this is blatantly obvious to a lot of people, but for the life of me I could not find any clear notes on this via github or google. I am not using a GUI for my git, strictly through a linux shell.
How do I find out the ID of the current Repo?
If, like me, you were after the GitHub repository ID (as in - the number identifying the repo - not its name), then I found an easy way to do this via the metadata element on the main page of the repository on GitHub:
View the page source (Right Click > View Page Source in Chrome or Firefox for example)
Search the page source and look for octolytics-dimension-repository_id. You should find something that looks like:
<meta content="123456789" name="octolytics-dimension-repository_id" />
In this example, the ID of the repository is 123456789.
Here's a quick query you can run in console:
$("meta[name=octolytics-dimension-repository_id]").getAttribute('content')
Nine years later, using the graphql API, there is an awesome
explorer
Login
Paste the following query
Replace repo_name, owner_name with real values
click play
query {
repository (name: *repo_name*, owner: *owner_name*) {
id
}
}
That is all.
When you say "repo ID", do you mean the URL of the repo on GitHub?
If that's what you're looking for, use git remote.
plankton:~/scraps $ git remote -v
origin git#github.com:petdance/scraps.git (fetch)
origin git#github.com:petdance/scraps.git (push)
If you have multiple remote repos feeding into your local repository, all of them will be listed there.
Your repository on GitHub does have a unique ID and it can be obtained using the following simple bash script:
#!/bin/bash
OWNER='your github username or organization name'
REPO_NAME='your repository name'
echo $(gh api -H "Accept: application/vnd.github+json" repos/$OWNER/$REPO_NAME) | jq .id
Note: you will need to install both jq and github cli to get this to work.
jq can be installed as written in this link: https://stackoverflow.com/a/64605901/4441211
github cli can be installed according to this link: https://cli.github.com/
I guess he was talking about name/reponame combination (which uniquely identifies repo on github), e.g. if you using the following string in your git remote
git://github.com/sublimescala/sublime-ensime.git
The id will be sublimescala/sublime-ensime

Github: Can I see the number of downloads for a repo?

In Github, is there a way I can see the number of downloads for a repo?
Update 2019:
Ustin's answer points to:
API /repos/:owner/:repo/traffic/clones, to get the total number of clones and breakdown per day or week, but: only for the last 14 days.
API /repos/:owner/:repo/releases/:release_id for getting downloads number of your assets (files attached to the release), field download_count mentioned below, but, as commented, only for the most recent 30 releases..
Update 2017
You still can use the GitHub API to get the download count for your releases (which is not exactly what was asked)
See "Get a single release", the download_count field.
There is no longer a traffic screen mentioning the number of repo clones.
Instead, you have to rely on third-party services like:
GitItBack (at www.netguru.co/gititback), but even that does not include the number of clones.
githubstats0, mentioned below by Aveek Saha.
www.somsubhra.com/github-release-stats (web archive), mentioned below.
For instance, here is the number for the latest git for Windows release
Update August 2014
GitHub also proposes the number of clones for repo in its Traffic Graph:
See "Clone Graphs"
Update October 2013
As mentioned below by andyberry88, and as I detailed last July, GitHub now proposes releases (see its API), which has a download_count field.
Michele Milidoni, in his (upvoted) answer, does use that field in his python script.
(very small extract)
c.setopt(c.URL, 'https://api.github.com/repos/' + full_name + '/releases')
for p in myobj:
if "assets" in p:
for asset in p['assets']:
print (asset['name'] + ": " + str(asset['download_count']) +
" downloads")
Original answer (December 2010)
I am not sure you can see that information (if it is recorded at all), because I don't see it in the GitHub Repository API:
$ curl http://github.com/api/v2/yaml/repos/show/schacon/grit
---
repository:
:name: grit
:owner: schacon
:source: mojombo/grit # The original repo at top of the pyramid
:parent: defunkt/grit # This repo's direct parent
:description: Grit is a Ruby library for extracting information from a
git repository in an object oriented manner - this fork tries to
intergrate as much pure-ruby functionality as possible
:forks: 4
:watchers: 67
:private: false
:url: http://github.com/schacon/grit
:fork: true
:homepage: http://grit.rubyforge.org/
:has_wiki: true
:has_issues: false
:has_downloads: true
You can only see if it has downloads or not.
Adam Jagosz reports in the comments:
I got it to work with
curl -H "Accept: application/vnd.github.v3+json" https://api.github.com/repos/:user/:repo/releases
A couple of things that I had wrong:
I needed an actual Github release (not just git tag, even though Github does display those under releases, ugh).
And the release needs an asset file other than the zipped source that is added automatically in order to get the download count.
I have written a small web application in javascript for showing count of the number of downloads of all the assets in the available releases of any project on Github. You can try out the application over here: http://somsubhra.github.io/github-release-stats/
VISITOR count should be available under your dashboard > Traffic (or stats or insights):
GitHub has deprecated the download support and now supports 'Releases' - https://github.com/blog/1547-release-your-software. To create a release either use the GitHub UI or create an annotated tag (http:// git-scm.com/book/ch2-6.html) and add release notes to it in GitHub. You can then upload binaries, or 'assets', to each release.
Once you have some releases, the GitHub API supports getting information about them, and their assets.
curl -i \
https://api.github.com/repos/:owner/:repo/releases \
-H "Accept: application/vnd.github.manifold-preview+json"
Look for the 'download_count' entry. Theres more info at http://developer.github.com/v3/repos/releases/. This part of the API is still in the preview period ATM so it may change.
Update Nov 2013:
GitHub's releases API is now out of the preview period so the 'Accept' header is no longer needed - http://developer.github.com/changes/2013-11-04-releases-api-is-official/
It won't do any harm to continue to add the 'Accept' header though.
I had made a web app that shows GitHub release statistics in a clean format:
https://hanadigital.github.io/grev/
As mentioned, GitHub API returns downloads count of binary file releases. I developed a little script to easly get downloads count by command line.
Formerly, there was two methods of download code in Github: clone or download as zip a .git repo, or upload a file (for example, a binary) for later download.
When download a repo (clone or download as zip), Github doesn't count the number of downloads for technical limitations. Clone a repository is a read-only operation. There is no authentication required. This operation can be done via many protocols, including HTTPS, the same protocol that the web page uses to show the repo in the browser. It's very difficult to count it.
See: http://git-scm.com/book/en/Git-on-the-Server-The-Protocols
Recently, Github deprecate the download functionality. This was because they understand that Github is focused in building software, and not in distribute binaries.
See: https://github.com/blog/1302-goodbye-uploads
To check the number of times a release file/package was downloaded you can go to https://githubstats0.firebaseapp.com
It gives you a total download count and a break up of of total downloads per release tag.
Very late, but here is the answer you want:
https://api.github.com/repos/ [git username] / [git project] /releases
Next, find the id of the project you are looking for in the data. It should be near the top, next to the urls. Then, navigate to
https://api.github.com/repos/ [git username] / [git project] /releases/ [id] / assets
The field named download_count is your answer.
EDIT: Capitals matter in your username and project name
The Github API does not provide the needed information anymore. Take a look at the releases page, mentioned in Stan Towianski's answer. As we discussed in the comments to that answer, the Github API only reports the downloads of 1 of the three files he offers per release.
I have checked the solutions, provided in some other answers to this questions. Vonc's answer presents the essential part of Michele Milidoni's solution. I installed his gdc script with the following result
# ./gdc stant
mdcsvimporter.mxt: 37 downloads
mdcsvimporter.mxt: 80 downloads
How-to-use-mdcsvimporter-beta-16.zip: 12 downloads
As you can clearly see, gdc does not report the download count of the tar.gz and zip files.
If you want to check without installing anything, try the web page where Somsubhra has installed the solution, mentioned in his answer. Fill in 'stant' as Github username and 'mdcsvimporter2015' as Repository name and you will see things like:
Download Info:
mdcsvimporter.mxt(0.20MB) - Downloaded 37 times.
Last updated on 2015-03-26
Alas, once again only a report without the downloads of the tar.gz and zip files. I have carefully examined the information that Github's API returns, but it is not provided anywhere. The download_count that the API does return is far from complete nowadays.
I ended up writing a scraper script to find my clone count:
#!/bin/sh
#
# This script requires:
# apt-get install html-xml-utils
# apt-get install jq
#
USERNAME=dougluce
PASSWORD="PASSWORD GOES HERE, BE CAREFUL!"
REPO="dougluce/node-autovivify"
TOKEN=`curl https://github.com/login -s -c /tmp/cookies.txt | \
hxnormalize | \
hxselect 'input[name=authenticity_token]' 2>/dev/null | \
perl -lne 'print $1 if /value=\"(\S+)\"/'`
curl -X POST https://github.com/session \
-s -b /tmp/cookies.txt -c /tmp/cookies2.txt \
--data-urlencode commit="Sign in" \
--data-urlencode authenticity_token="$TOKEN" \
--data-urlencode login="$USERNAME" \
--data-urlencode password="$PASSWORD" > /dev/null
curl "https://github.com/$REPO/graphs/clone-activity-data" \
-s -b /tmp/cookies2.txt \
-H "x-requested-with: XMLHttpRequest" | jq '.summary'
This'll grab the data from the same endpoint that Github's clone graph uses and spit out the totals from it. The data also includes per-day counts, replace .summary with just . to see those pretty-printed.
To try to make this more clear:
for this github project: stant/mdcsvimporter2015
https://github.com/stant/mdcsvimporter2015
with releases at
https://github.com/stant/mdcsvimporter2015/releases
go to http or https: (note added "api." and "/repos")
https://api.github.com/repos/stant/mdcsvimporter2015/releases
you will get this json output and you can search for "download_count":
"download_count": 2,
"created_at": "2015-02-24T18:20:06Z",
"updated_at": "2015-02-24T18:20:07Z",
"browser_download_url": "https://github.com/stant/mdcsvimporter2015/releases/download/v18/mdcsvimporter-beta-18.zip"
or on command line do:
wget --no-check-certificate https://api.github.com/repos/stant/mdcsvimporter2015/releases
Based on VonC and Michele Milidoni answers I've created this bookmarklet which displays downloads statistics of github hosted released binaries.
Note: Because of issues with browsers related to Content Security Policy implementation, bookmarklets can temporarily violate some CSP directives and basically may not function properly when running on github while CSP is enabled.
Though its highly discouraged, you can disable CSP in Firefox as a
temporary workaround. Open up about:config and set security.csp.enable
to false.
I have created three solutions to fetch the download count and other statistics for GitHub releases. Each of these implementations are able to accumulate the GitHub API pagination results, which means that calculating the total number of downloads won't be an issue.
Web Application
https://qwertycube.com/github-release-stats/
Available as a PWA
Supports the GitHub API pagination
Node.js Implementation
https://github.com/kefir500/github-release-stats
Available via NPM
Written in TypeScript, compiled to JavaScript
Can be used as a command-line tool
Can be used as a Node.js module
Can be used in a browser environment
Supports the GitHub API pagination
Python Implementation
https://github.com/kefir500/ghstats
Available via PyPI
Can be used as a command-line tool
Can be used as a Python module
Supports the GitHub API pagination
New implementation:
Port into GitHub composite action to reuse workflow code base.
https://github.com/andry81-devops/github-accum-stats
With additional features:
Can count traffic clones or/and views.
Can use GitHub composite action to reuse workflow code base: https://docs.github.com/en/actions/creating-actions/creating-a-composite-action
GitHub workflow file example:
.github/workflows/accum-gh-clone-stats.yml
Previous implementation (marked as obsolete):
This implementation based on GitHub Actions + statistic accumulation into separate repository: https://github.com/andry81-devops/github-clone-count-badge
based on: https://github.com/MShawon/github-clone-count-badge
With some advantages:
Repository to track and repository to store traffic statistic are different, and you may directly point the statistic as commits list: https://github.com/{{REPO_OWNER}}/{{REPO}}--gh-stats/commits/master/traffic/clones
Workflow is used accum-traffic-clones.sh bash script to accumulate traffic clones
The script accumulates statistic both into a single file and into a set of files grouped by year and allocated per day: traffic/clones/by_year/YYYY/YYYY-MM-DD.json
GitHub workflow file example:
.github/workflows/myrepo-gh-clone-stats.yml
As already stated, you can get information about your Releases via the API.
For those using WordPress, I developed this plugin: GitHub Release Downloads. It allows you to get the download count, links and more information for releases of GitHub repositories.
To address the original question, the shortcode [grd_count user="User" repo="MyRepo"] will return the number of downloads for a repository. This number corresponds to the sum of all download count values of all releases for one GitHub repository.
Example:
Answer from 2019:
For number of clones you can use https://developer.github.com/v3/repos/traffic/#clones (but be aware that it returns count only for last 14 days)
For get downloads number of your assets (files attached to the release), you can use https://developer.github.com/v3/repos/releases/#get-a-single-release (exactly "download_count" property of the items of assets list in response)
There's a nice Chrome extension that does exactly what you want:
GitHub Release Downloads
11 years later...
Here's a small python3 snippet to retrieve the download count of the last 100 release assets:
import requests
owner = "twbs"
repo = "bootstrap"
h = {"Accept": "application/vnd.github.v3+json"}
u = f"https://api.github.com/repos/{owner}/{repo}/releases?per_page=100"
r = requests.get(u, headers=h).json()
r.reverse() # older tags first
for rel in r:
if rel['assets']:
tag = rel['tag_name']
dls = rel['assets'][0]['download_count']
pub = rel['published_at']
print(f"Pub: {pub} | Tag: {tag} | Dls: {dls} ")
Pub: 2013-07-18T00:03:17Z | Tag: v1.2.0 | Dls: 1193
Pub: 2013-08-19T21:20:59Z | Tag: v3.0.0 | Dls: 387786
Pub: 2013-10-30T17:07:16Z | Tag: v3.0.1 | Dls: 102278
Pub: 2013-11-06T21:58:55Z | Tag: v3.0.2 | Dls: 381136
...
Pub: 2020-12-07T16:24:37Z | Tag: v5.0.0-beta1 | Dls: 93943
Demo
Here is a python solution using the pip install PyGithub package
from github import Github
g = Github("youroauth key") #create token from settings page
for repo in g.get_user().get_repos():
if repo.name == "yourreponame":
releases = repo.get_releases()
for i in releases:
if i.tag_name == "yourtagname":
for j in i.get_assets():
print("{} date: {} download count: {}".format(j.name, j.updated_at, j._download_count.value))