Skip to content

Instantly share code, notes, and snippets.

@jeremyzilar
Last active January 2, 2018 22:04
Show Gist options
  • Save jeremyzilar/93234f9749906a79ab3b25c4e2ef52c4 to your computer and use it in GitHub Desktop.
Save jeremyzilar/93234f9749906a79ab3b25c4e2ef52c4 to your computer and use it in GitHub Desktop.
Get Commit Data via GitHub API
// How we are getting the commit data for each page on digitalgov.gov and displaying the date/time each file was last updated.
// Full file is at: https://github.com/GSA/digitalgov.gov/blob/master/themes/digital.gov/static/js/external.js
// https://digital.gov/
jQuery(document).ready(function($) {
// Get the file path via HUGO in a data attr
// e.g. /about/about.md
var filepath = $('.last_commit').attr('data-filepath');
// Get the commit data via GitHub API
// https://api.github.com/repos/GSA/digitalgov.gov/commits?path=/content/about/about.md
function get_commit_data(filepath){
if (filepath !== undefined) {
var commit_file_path = 'https://api.github.com/repos/GSA/digitalgov.gov/commits?path=/content/'+filepath;
$.ajax({
url: commit_file_path,
dataType: 'json',
}).done(function(data) {
get_last_commit(data)
});
}
}
get_commit_data(filepath);
// Gets last commit from the commit data
function get_last_commit(data){
var commit_date = data[0]['commit']['committer']['date'];
$('.last_commit span').text(getFormattedDate(commit_date));
$('.last_commit').show();
}
// Gets last commit history URL
function get_commit_history_url(filepath) {
if (filepath !== undefined) {
var commit_history_url = 'https://github.com/GSA/digitalgov.gov/commits/master/content/' + filepath;
$('.last_commit span').wrap('<a href="'+commit_history_url+'"></a>');
}
}
get_commit_history_url(filepath);
// Formats the date of the last commit
function getFormattedDate(d) {
var date = new Date(d);
date.setUTCHours(date.getUTCHours() - 5);
var monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var year = date.getUTCFullYear();
var month = (date.getUTCMonth()).toString();
month = monthNames[month];
var day = date.getUTCDate().toString();
day = day.length > 1 ? day : '0' + day;
var hours = date.getUTCHours().toString();
var minutes = date.getUTCMinutes().toString();
minutes = minutes.length > 1 ? minutes : '0' + minutes;
var seconds = date.getUTCSeconds().toString();
var ampm = hours >= 12 ? 'pm' : 'am';
var date_string = month + ' ' + day + ', ' + year + ' at ' + hours + ':' + minutes + ampm + ' ET';
return date_string;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment