Skip to content

Instantly share code, notes, and snippets.

@yershalom
Created December 17, 2017 13:19
Show Gist options
  • Save yershalom/a7c08f9441d1aadb13777bce4c7cdc3b to your computer and use it in GitHub Desktop.
Save yershalom/a7c08f9441d1aadb13777bce4c7cdc3b to your computer and use it in GitHub Desktop.
Easy way to calculate commits count from the github api
import requests
base_url = 'https://api.github.com'
def get_all_commits_count(owner, repo, sha):
first_commit = get_first_commit(owner, repo)
compare_url = '{}/repos/{}/{}/compare/{}...{}'.format(base_url, owner, repo, first_commit, sha)
commit_req = requests.get(compare_url)
commit_count = commit_req.json()['total_commits'] + 1
print(commit_count)
return commit_count
def get_first_commit(owner, repo):
url = '{}/repos/{}/{}/commits'.format(base_url, owner, repo)
req = requests.get(url)
json_data = req.json()
if req.headers.get('Link'):
page_url = req.headers.get('Link').split(',')[1].split(';')[0].split('<')[1].split('>')[0]
req_last_commit = requests.get(page_url)
first_commit = req_last_commit.json()
first_commit_hash = first_commit[-1]['sha']
else:
first_commit_hash = json_data[-1]['sha']
return first_commit_hash
def main():
owner = 'getredash'
repo = 'redash'
# Took the last commit, Can do it automatically also but keeping it open
sha = '5ba15ef35074a88daa5032ec4bec34d3a22a607e'
get_all_commits_count(owner, repo, sha)
if __name__ == '__main__':
main()
@0penBrain
Copy link

Maybe you can be interested in this very simple solution

@kingspp
Copy link

kingspp commented May 1, 2020

Pure JS

const base_url = 'https://api.github.com';

    function httpGet(theUrl, return_headers) {
        var xmlHttp = new XMLHttpRequest();
        xmlHttp.open("GET", theUrl, false); // false for synchronous request
        xmlHttp.send(null);
        if (return_headers) {
            return xmlHttp
        }
        return xmlHttp.responseText;
    }

    function get_all_commits_count(owner, repo, sha) {
        let first_commit = get_first_commit(owner, repo);
        let compare_url = base_url + '/repos/' + owner + '/' + repo + '/compare/' + first_commit + '...' + sha;
        let commit_req = httpGet(compare_url);
        let commit_count = JSON.parse(commit_req)['total_commits'] + 1;
        console.log('Commit Count: ', commit_count);
        return commit_count
    }
    
    function get_first_commit(owner, repo) {
        let url = base_url + '/repos/' + owner + '/' + repo + '/commits';
        let req = httpGet(url, true);
        let first_commit_hash = '';
        if (req.getResponseHeader('Link')) {
            let page_url = req.getResponseHeader('Link').split(',')[1].split(';')[0].split('<')[1].split('>')[0];
            let req_last_commit = httpGet(page_url);
            let first_commit = JSON.parse(req_last_commit);
            first_commit_hash = first_commit[first_commit.length - 1]['sha']
        } else {
            let first_commit = JSON.parse(req.responseText);
            first_commit_hash = first_commit[first_commit.length - 1]['sha'];
        }
        return first_commit_hash;
    }
    
    let owner = 'getredash';
    let repo = 'redash';
    let sha = 'master';
    get_all_commits_count(owner, repo, sha);

@Braian-92
Copy link

Braian-92 commented Dec 4, 2021

PHP

<?php
$listaCommits = buscarTodosLosCommits($usuario, $repositorio, $rama);

function buscarTodosLosCommits($usuario, $repositorio, $rama){
	$ultimoSha = buscarUltimoCommit($usuario, $repositorio);
	$curl = curl_init();
	curl_setopt_array($curl, [
		CURLOPT_RETURNTRANSFER => 1,
		CURLOPT_URL => 'https://api.github.com/repos/'.$usuario.'/'.$repositorio.'/compare/'.$ultimoSha.'...'.$rama,
		CURLOPT_HTTPHEADER => [
			"Accept: application/vnd.github.v3+json",
			"Content-Type: text/plain"
		],
		CURLOPT_USERAGENT  => 'Github API in Curl'
	]);
	$response = curl_exec($curl);
	return json_decode(json_encode( json_decode($response) ), true);
}

function buscarUltimoCommit($usuario, $repositorio){
	$curl = curl_init();
	curl_setopt_array($curl, [
		CURLOPT_RETURNTRANSFER => 1,
		CURLOPT_URL => 'https://api.github.com/repos/'.$usuario.'/'.$repositorio.'/commits',
		CURLOPT_HTTPHEADER => [
			"Accept: application/vnd.github.v3+json",
			"Content-Type: text/plain"
		],
		CURLOPT_USERAGENT  => 'Github API in Curl'
	]);
	$response = curl_exec($curl);
	$respuesta = json_decode(json_encode( json_decode($response) ), true);
	return $respuesta[count($respuesta) - 1]['sha'];
}

@shashi1iitk
Copy link

Good! But, can be done with just 1 request. Check here: https://stackoverflow.com/a/70610670/10266115

@0penBrain
Copy link

@shashi1iitk Humm that's what is in my Gist in my comment above (2 years ago) and that most probably inspire your answer on SO. I may be mistaken, but quoting the source there would be fair.

@arye321
Copy link

arye321 commented Aug 9, 2023

need api key tho

import requests

owner = "yt-dlp"
name = "yt-dlp"
access_token = "YOUR_ACCESS_TOKEN"

query = f'''
{{
  repository(owner: "{owner}", name: "{name}") {{
    defaultBranchRef {{
      target {{
        ... on Commit {{
          history(first: 0) {{
            totalCount
          }}
        }}
      }}
    }}
  }}
}}
'''

headers = {'Authorization': f'Bearer {access_token}'}
url = 'https://api.github.com/graphql'

response = requests.post(url, json={'query': query}, headers=headers)
data = response.json()

commits_count = data['data']['repository']['defaultBranchRef']['target']['history']['totalCount']
print(f"Number of commits: {commits_count}")

@eonist
Copy link

eonist commented Sep 22, 2023

here is one if you want total commits for a user the last 24h across all repos on GitHub.

#!/bin/bash

# Prompt the user to enter their GitHub username
read -p "Enter your GitHub username: " username

# Get the total commit count for the user
commit_count=$(curl -s "https://api.github.com/users/$username/events" | grep -c "PushEvent")

# Print the total commit count
echo "Total commit count for $username: $commit_count"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment