From a40ed02b7066fcf78f32477c534cebb077c817f2 Mon Sep 17 00:00:00 2001 From: Brian Olore Date: Fri, 31 Aug 2018 20:35:19 -0400 Subject: [PATCH] version-checker: use cacache to only check for new versions once per 24 hours --- lib/utils/version-checker.js | 66 ++++++++++++++++++++++++------------ 1 file changed, 44 insertions(+), 22 deletions(-) diff --git a/lib/utils/version-checker.js b/lib/utils/version-checker.js index 39392fbf8e8a6..9ae7a0e0875b0 100644 --- a/lib/utils/version-checker.js +++ b/lib/utils/version-checker.js @@ -1,14 +1,16 @@ const boxen = require('boxen') +const cacache = require('cacache') const log = require('npmlog') +const nopt = require('nopt') +const path = require('path') const pacote = require('pacote') const semver = require('semver') -var npmconf = require('../config/core.js') -var configDefs = npmconf.defs + +const npm = require('../npm.js') +const npmconf = require('../config/core.js') +const configDefs = npmconf.defs const shorthands = configDefs.shorthands const types = configDefs.types -const nopt = require('nopt') -let npm = require('../npm.js') - const pacoteOpts = require('../config/pacote') const unsupported = require('./unsupported.js') @@ -25,23 +27,43 @@ exports.doCheck = function () { npm.load(conf, function (err) { if (err) return - if ( - npm.config.get('update-notifier') && - !isGlobalNpmUpdate && - !unsupported.checkVersion(process.version).unsupported && - !isCI - ) { - pacote.manifest('npm@latest', pacoteOpts()) - .then((latest) => { - const oldVersion = require('../../package.json').version - let diffType = semver.diff(oldVersion, latest.version) - if (diffType) { - console.log(generateMessage(oldVersion, latest.version, diffType, npm)) - } else { - log.silly('version-check', 'we are running the latest version of npm') - } - }) - } + + isBeyondCheckInterval().then((shouldCheck) => { + if (shouldCheck) { + if ( + npm.config.get('update-notifier') && + !isGlobalNpmUpdate && + !unsupported.checkVersion(process.version).unsupported && + !isCI + ) { + pacote.manifest('npm@latest', pacoteOpts()) + .then((latest) => { + const oldVersion = require('../../package.json').version + let diffType = semver.diff(oldVersion, latest.version) + if (diffType) { + console.log(generateMessage(oldVersion, latest.version, diffType, npm)) + } else { + log.silly('version-checker', 'we are running the latest version of npm') + } + }) + } + } + }) + }) +} + +function isBeyondCheckInterval () { + const cache = path.join(npm.config.get('cache'), '_cacache') + const ONE_DAY = 24 * 60 * 60 * 1000 + + return cacache.get(cache, 'update-notifier:last-check').then(cacheObj => { + const time = Number(cacheObj.data.toString('utf8')) + return (time + ONE_DAY) < Date.now() + }).catch((notFound) => { + const time = Number(Date.now()).toString() + return cacache.put(cache, 'update-notifier:last-check', time).then(() => { + return true + }) }) }