Skip to content

Instantly share code, notes, and snippets.

@zkat
Last active December 16, 2017 02:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zkat/45777e68b7c6ef7e9fd7109ed547451c to your computer and use it in GitHub Desktop.
Save zkat/45777e68b7c6ef7e9fd7109ed547451c to your computer and use it in GitHub Desktop.
find the cached version that's closest to a given spec
'use strict'
const BB = require('bluebird')
const cacache = require('cacache')
const npa = require('npm-package-arg')
const pickManifest = require('npm-pick-manifest')
const ssri = require('ssri')
module.exports = cachedVersions
async function cachedVersions (cache, spec, opts) {
spec = npa(spec)
opts = opts || {}
const registry = opts.registry || 'https://registry.npmjs.org'
if (!spec.registry) {
throw new Error('Only registry specs are supported')
}
let res
try {
res = await cacache.get(cache, `make-fetch-happen:request-cache:${
registry
}/${
spec.escapedName
}`)
} catch (err) {
if (err.code === 'ENOENT') { return null }
throw err
}
const packument = JSON.parse(res.data.toString('utf8'))
const versions = Object.keys(packument.versions)
let bestMatch
try {
bestMatch = pickManifest(packument, spec.rawSpec)
} catch (e) {
if (e.code === 'ETARGET') {
bestMatch = packument.versions[versions[versions.length - 1]]
} else {
throw e
}
}
const bestMatchIdx = versions.indexOf(bestMatch.version)
for (
let i = 0;
// If we haven't gone past the beginning
(bestMatchIdx - i) > 0 ||
// Or we haven't gone past the end
(bestMatchIdx + i) < versions.length;
i++
) {
const back = packument.versions[versions[bestMatchIdx - i]]
const forth = packument.versions[versions[bestMatchIdx + i]]
const promises = []
if (back) {
promises.push(
cacache.get.hasContent(cache, back.dist.integrity),
cacache.get.hasContent(cache, ssri.fromHex(back.dist.shasum), 'sha1')
)
}
if (forth) {
promises.push(
cacache.get.hasContent(cache, forth.dist.integrity),
cacache.get.hasContent(cache, ssri.fromHex(forth.dist.shasum), 'sha1')
)
}
if (!promises.length) { continue }
try {
const existing = await BB.some(promises, 1)
return existing[0] && existing[0].sri.toString()
} catch (e) {
if (e instanceof BB.AggregateError) { continue }
throw e
}
}
}
{
"name": "nearest-cached-hash",
"version": "0.0.0",
"dependencies": {
"ssri": "^5.0.0",
"npm-pick-manifest": "^2.1.0",
"npm-package-arg": "^6.0.0",
"cacache": "^10.0.1"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment