Created
July 5, 2018 05:38
-
-
Save nmanikiran/950bca59f1726fb405ec1277733f94ff to your computer and use it in GitHub Desktop.
Get the file size of a GitHub file without downloading it to the local
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function () { | |
"use strict"; | |
//Parse the current GitHub repo url. Examples: | |
// Repo root: /Sphinxxxx/vanilla-picker | |
// Subfolder: /Sphinxxxx/vanilla-picker/tree/master/src/css | |
// Subfolder at commit: /Sphinxxxx/vanilla-picker/tree/382231756aac75a49f046ccee1b04263196f9a22/src/css | |
// Subfolder at tag: /Sphinxxxx/vanilla-picker/tree/v2.2.0/src/css | |
// | |
//If applicable, the name of the commit/branch/tag is always the 4th element in the url path. | |
//Here, we put that in the "ref" variable: | |
const [/* Leading slash */, owner, repo, /* "tree" */, ref, ...path] = window.location.pathname.split('/'); | |
//Create the URL to query GitHub's API: https://developer.github.com/v3/repos/contents/#get-contents | |
//Example: | |
// https://api.github.com/repos/Sphinxxxx/vanilla-picker/contents/src/css?ref=382231756aac75a49f046ccee1b04263196f9a22 | |
const query = ['https://api.github.com/repos', owner, repo, 'contents'].concat(path || []), | |
url = query.join('/') + (ref ? '?ref=' + ref : ''); | |
console.log(url); | |
//https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch | |
fetch(url).then(r => r.json()) | |
.then(j => Array.isArray(j) ? j.forEach(handleFileInfo) : console.warn(j)); | |
function handleFileInfo(info) { | |
//console.log(info); | |
const link = document.querySelector('table.files a[title="' +info.name+ '"]'); | |
const ageCol = link.closest('tr').querySelector('td.age'); | |
const sizeCell = document.createElement('td'); | |
if(info.type === 'file') { | |
//http://stackoverflow.com/a/17663871/1869660 | |
//https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString#Parameters | |
sizeCell.textContent = (info.size/1024).toLocaleString('en-US', { minimumFractionDigits: 1, maximumFractionDigits: 1 }) + ' KB'; | |
sizeCell.style.textAlign = 'right'; | |
} | |
ageCol.parentNode.insertBefore(sizeCell, ageCol); | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment