Skip to content

Instantly share code, notes, and snippets.

@medeirosinacio
Last active August 5, 2021 19:29
Show Gist options
  • Save medeirosinacio/0f018f4712a92651461f9e6c17b7a0d9 to your computer and use it in GitHub Desktop.
Save medeirosinacio/0f018f4712a92651461f9e6c17b7a0d9 to your computer and use it in GitHub Desktop.
Easy way to calculate all commits count from one user
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;
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;
}
function get_all_commits_count_from_all_repos(owner) {
let url = base_url + '/users/' + owner + '/repos';
let repos = httpGet(url);
let count = 0;
if(isInvalidJsonString(repos)){
return 0;
}
repos = JSON.parse(repos);
for (let repo of repos) {
count = count + get_all_commits_count(owner, repo.name, repo.default_branch);
}
return count;
}
function isInvalidJsonString(tester) {
if (/^\s*$|undefined/.test(tester) || !(/number|object|array|string|boolean/.test(typeof tester))) {
return true;
}
return false;
}
get_all_commits_count_from_all_repos('medeirosinacio');
@medeirosinacio
Copy link
Author

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