Skip to content

Instantly share code, notes, and snippets.

@Rudxain
Created June 19, 2025 07:58
Show Gist options
  • Save Rudxain/c87f4908d5f312612dec76bd8750316f to your computer and use it in GitHub Desktop.
Save Rudxain/c87f4908d5f312612dec76bd8750316f to your computer and use it in GitHub Desktop.
CLI that gets remote sizes of repositories; human-readable
#!/usr/bin/env node
//@ts-check
import assert from 'node:assert/strict'
import { argv } from 'node:process'
for (const arg of argv.slice(2)) {
// UX
const user_repo = (() => {
const a = arg.trim()
return a.slice(
+(a[0] == '/'),
//@ts-expect-error 2550
a.at(-1) == '/' ? -1 : undefined
)
})()
// regex is permissive, to be future-proof
if (!/^[^\x00-\x0a/\s]+\/[^\x00-\x0a/\s]+$/.test(user_repo)) {
console.error(`${user_repo} malformed`)
continue
}
const r = await fetch('https://api.github.com/repos/' + user_repo)
if (!r.ok) {
console.error(`${user_repo} ${r.status} ${r.statusText}`)
continue
}
// full `JSON.parse` is overkill (bad perf),
// but it's guaranteed to be reliable
const kilobytes = (await r.json()).size
assert(
// allow TS to narrow the `any`
typeof kilobytes == 'number' &&
// in theory, a number-literal can parse as `Infinity`!
// in practice, that'll never happen... right? πŸ‘€πŸ˜…
isFinite(kilobytes),
'API broken'
)
// 1024 is for kibibytes
const bytes = kilobytes * 1e3
assert(Number.isInteger(bytes))
// floor (`toUint32`) logarithm base 1000
const i = Math.log10(bytes) / 3 >>> 0
// https://en.wikipedia.org/wiki/Binary_prefix
// 1QB β‰… 2^99B,
// therefore the OOB index is practically impossible
console.log(`${user_repo} ${(bytes / 1e3 ** i).toFixed(1)} ${'KMGTPEZYRQ'[i - 1] || ''}B`)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment