All files doctor.js

98.32% Statements 176/179
100% Branches 81/81
94.74% Functions 18/19
98.3% Lines 173/176

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 2833x   3x 3x 3x 3x 3x 3x 3x 3x   3x 3x 14x 14x 14x 14x 11x   3x 1x   2x   14x       3x 3x 14x 14x 14x 14x 14x 13x   1x   14x       3x 3x 3x   14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 43x 14x   43x 1x   14x 14x 13x   1x   14x       3x 3x 3x 3x 3x 3x 2x   3x 1x   3x 2x   3x   3x 3x 3x 3x 3x 65x 26x   65x   65x   65x 65x 65x 65x 65x 77x 77x   1x 1x     77x   77x 1x   76x 1x 1x     76x 1x   75x 75x   3x 3x 3x 3x     72x 66x           66x 12x       65x 65x 5x     60x       3x 3x 14x 14x 14x 14x 1x 1x     14x       3x 3x 14x 14x 14x 14x 14x 14x 3x 1x   3x 1x   3x 1x   3x   14x     14x   14x       3x 3x 14x 1x   13x     14x   3x 14x     14x   14x                                         14x 149x 149x 149x   12x   149x     14x   14x 39x 14x 14x   138x 138x 138x 138x     11x 11x 1x 1x   11x 11x   14x 14x 906x     14x 13x 13x 8x   14x 8x     3x  
const npm = require('./npm.js')
 
const chalk = require('chalk')
const ansiTrim = require('./utils/ansi-trim.js')
const table = require('text-table')
const output = require('./utils/output.js')
const completion = require('./utils/completion/none.js')
const usageUtil = require('./utils/usage.js')
const usage = usageUtil('doctor', 'npm doctor')
const { resolve } = require('path')
 
const ping = require('./utils/ping.js')
const checkPing = async () => {
  const tracker = npm.log.newItem('checkPing', 1)
  tracker.info('checkPing', 'Pinging registry')
  try {
    await ping(npm.flatOptions)
    return ''
  } catch (er) {
    if (/^E\d{3}$/.test(er.code || ''))
      throw er.code.substr(1) + ' ' + er.message
    else
      throw er.message
  } finally {
    tracker.finish()
  }
}
 
const pacote = require('pacote')
const getLatestNpmVersion = async () => {
  const tracker = npm.log.newItem('getLatestNpmVersion', 1)
  tracker.info('getLatestNpmVersion', 'Getting npm package information')
  try {
    const latest = (await pacote.manifest('npm@latest', npm.flatOptions)).version
    if (semver.gte(npm.version, latest))
      return `current: v${npm.version}, latest: v${latest}`
    else
      throw `Use npm v${latest}`
  } finally {
    tracker.finish()
  }
}
 
const semver = require('semver')
const fetch = require('make-fetch-happen')
const getLatestNodejsVersion = async () => {
  // XXX get the latest in the current major as well
  const current = process.version
  const currentRange = `^${current}`
  const url = 'https://nodejs.org/dist/index.json'
  const tracker = npm.log.newItem('getLatestNodejsVersion', 1)
  tracker.info('getLatestNodejsVersion', 'Getting Node.js release information')
  try {
    const res = await fetch(url, { method: 'GET', ...npm.flatOptions })
    const data = await res.json()
    let maxCurrent = '0.0.0'
    let maxLTS = '0.0.0'
    for (const { lts, version } of data) {
      if (lts && semver.gt(version, maxLTS))
        maxLTS = version
 
      if (semver.satisfies(version, currentRange) && semver.gt(version, maxCurrent))
        maxCurrent = version
    }
    const recommended = semver.gt(maxCurrent, maxLTS) ? maxCurrent : maxLTS
    if (semver.gte(process.version, recommended))
      return `current: ${current}, recommended: ${recommended}`
    else
      throw `Use node ${recommended} (current: ${current})`
  } finally {
    tracker.finish()
  }
}
 
const { promisify } = require('util')
const fs = require('fs')
const { R_OK, W_OK, X_OK } = fs.constants
const maskLabel = mask => {
  const label = []
  if (mask & R_OK)
    label.push('readable')
 
  if (mask & W_OK)
    label.push('writable')
 
  if (mask & X_OK)
    label.push('executable')
 
  return label.join(', ')
}
const lstat = promisify(fs.lstat)
const readdir = promisify(fs.readdir)
const access = promisify(fs.access)
const isWindows = require('./utils/is-windows.js')
const checkFilesPermission = async (root, shouldOwn, mask = null) => {
  if (mask === null)
    mask = shouldOwn ? R_OK | W_OK : R_OK
 
  let ok = true
 
  const tracker = npm.log.newItem(root, 1)
 
  try {
    const uid = process.getuid()
    const gid = process.getgid()
    const files = new Set([root])
    for (const f of files) {
      tracker.silly('checkFilesPermission', f.substr(root.length + 1))
      const st = await lstat(f)
        .catch(er => {
          ok = false
          tracker.warn('checkFilesPermission', 'error getting info for ' + f)
        })
 
      tracker.completeWork(1)
 
      if (!st)
        continue
 
      if (shouldOwn && (uid !== st.uid || gid !== st.gid)) {
        tracker.warn('checkFilesPermission', 'should be owner of ' + f)
        ok = false
      }
 
      if (!st.isDirectory() && !st.isFile())
        continue
 
      try {
        await access(f, mask)
      } catch (er) {
        ok = false
        const msg = `Missing permissions on ${f} (expect: ${maskLabel(mask)})`
        tracker.error('checkFilesPermission', msg)
        continue
      }
 
      if (st.isDirectory()) {
        const entries = await readdir(f)
          .catch(er => {
            ok = false
            tracker.warn('checkFilesPermission', 'error reading directory ' + f)
            return []
          })
        for (const entry of entries)
          files.add(resolve(f, entry))
      }
    }
  } finally {
    tracker.finish()
    if (!ok) {
      throw `Check the permissions of files in ${root}` +
        (shouldOwn ? ' (should be owned by current user)' : '')
    } else
      return ''
  }
}
 
const which = require('which')
const getGitPath = async () => {
  const tracker = npm.log.newItem('getGitPath', 1)
  tracker.info('getGitPath', 'Finding git in your PATH')
  try {
    return await which('git').catch(er => {
      tracker.warn(er)
      throw "Install git and ensure it's in your PATH."
    })
  } finally {
    tracker.finish()
  }
}
 
const cacache = require('cacache')
const verifyCachedFiles = async () => {
  const tracker = npm.log.newItem('verifyCachedFiles', 1)
  tracker.info('verifyCachedFiles', 'Verifying the npm cache')
  try {
    const stats = await cacache.verify(npm.flatOptions.cache)
    const { badContentCount, reclaimedCount, missingContent, reclaimedSize } = stats
    if (badContentCount || reclaimedCount || missingContent) {
      if (badContentCount)
        tracker.warn('verifyCachedFiles', `Corrupted content removed: ${badContentCount}`)
 
      if (reclaimedCount)
        tracker.warn('verifyCachedFiles', `Content garbage-collected: ${reclaimedCount} (${reclaimedSize} bytes)`)
 
      if (missingContent)
        tracker.warn('verifyCachedFiles', `Missing content: ${missingContent}`)
 
      tracker.warn('verifyCachedFiles', 'Cache issues have been fixed')
    }
    tracker.info('verifyCachedFiles', `Verification complete. Stats: ${
      JSON.stringify(stats, null, 2)
    }`)
    return `verified ${stats.verifiedContent} tarballs`
  } finally {
    tracker.finish()
  }
}
 
const { defaults: { registry: defaultRegistry } } = require('./utils/config.js')
const checkNpmRegistry = async () => {
  if (npm.flatOptions.registry !== defaultRegistry)
    throw `Try \`npm config set registry=${defaultRegistry}\``
  else
    return `using default registry (${defaultRegistry})`
}
 
const cmd = (args, cb) => doctor(args).then(() => cb()).catch(cb)
 
const doctor = async args => {
  npm.log.info('Running checkup')
 
  // each message is [title, ok, message]
  const messages = []
 
  const actions = [
    ['npm ping', checkPing, []],
    ['npm -v', getLatestNpmVersion, []],
    ['node -v', getLatestNodejsVersion, []],
    ['npm config get registry', checkNpmRegistry, []],
    ['which git', getGitPath, []],
    ...(isWindows ? [] : [
      ['Perms check on cached files', checkFilesPermission, [npm.cache, true, R_OK]],
      ['Perms check on local node_modules', checkFilesPermission, [npm.localDir, true]],
      ['Perms check on global node_modules', checkFilesPermission, [npm.globalDir, false]],
      ['Perms check on local bin folder', checkFilesPermission, [npm.localBin, false, R_OK | W_OK | X_OK]],
      ['Perms check on global bin folder', checkFilesPermission, [npm.globalBin, false, X_OK]],
    ]),
    ['Verify cache contents', verifyCachedFiles, [npm.flatOptions.cache]],
    // TODO:
    // - ensure arborist.loadActual() runs without errors and no invalid edges
    // - ensure package-lock.json matches loadActual()
    // - verify loadActual without hidden lock file matches hidden lockfile
    // - verify all local packages have bins linked
  ]
 
  for (const [msg, fn, args] of actions) {
    const line = [msg]
    try {
      line.push(true, await fn(...args))
    } catch (er) {
      line.push(false, er)
    }
    messages.push(line)
  }
 
  const silent = npm.log.levels[npm.log.level] > npm.log.levels.error
 
  const outHead = ['Check', 'Value', 'Recommendation/Notes']
    .map(!npm.color ? h => h : h => chalk.underline(h))
  let allOk = true
  const outBody = messages.map(!npm.color
    ? item => {
      allOk = allOk && item[1]
      item[1] = item[1] ? 'ok' : 'not ok'
      item[2] = String(item[2])
      return item
    }
    : item => {
      allOk = allOk && item[1]
      if (!item[1]) {
        item[0] = chalk.red(item[0])
        item[2] = chalk.magenta(String(item[2]))
      }
      item[1] = item[1] ? chalk.green('ok') : chalk.red('not ok')
      return item
    })
  const outTable = [outHead, ...outBody]
  const tableOpts = {
    stringLength: s => ansiTrim(s).length,
  }
 
  if (!silent) {
    output(table(outTable, tableOpts))
    if (!allOk)
      console.error('')
  }
  if (!allOk)
    throw 'Some problems found. See above for recommendations.'
}
 
module.exports = Object.assign(cmd, { completion, usage })