util.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. 'use strict'
  2. const log = require('npmlog')
  3. const execFile = require('child_process').execFile
  4. const path = require('path')
  5. function logWithPrefix (log, prefix) {
  6. function setPrefix (logFunction) {
  7. return (...args) => logFunction.apply(null, [ prefix, ...args ]) // eslint-disable-line
  8. }
  9. return {
  10. silly: setPrefix(log.silly),
  11. verbose: setPrefix(log.verbose),
  12. info: setPrefix(log.info),
  13. warn: setPrefix(log.warn),
  14. error: setPrefix(log.error)
  15. }
  16. }
  17. function regGetValue (key, value, addOpts, cb) {
  18. const outReValue = value.replace(/\W/g, '.')
  19. const outRe = new RegExp(`^\\s+${outReValue}\\s+REG_\\w+\\s+(\\S.*)$`, 'im')
  20. const reg = path.join(process.env.SystemRoot, 'System32', 'reg.exe')
  21. const regArgs = ['query', key, '/v', value].concat(addOpts)
  22. log.silly('reg', 'running', reg, regArgs)
  23. const child = execFile(reg, regArgs, { encoding: 'utf8' },
  24. function (err, stdout, stderr) {
  25. log.silly('reg', 'reg.exe stdout = %j', stdout)
  26. if (err || stderr.trim() !== '') {
  27. log.silly('reg', 'reg.exe err = %j', err && (err.stack || err))
  28. log.silly('reg', 'reg.exe stderr = %j', stderr)
  29. return cb(err, stderr)
  30. }
  31. const result = outRe.exec(stdout)
  32. if (!result) {
  33. log.silly('reg', 'error parsing stdout')
  34. return cb(new Error('Could not parse output of reg.exe'))
  35. }
  36. log.silly('reg', 'found: %j', result[1])
  37. cb(null, result[1])
  38. })
  39. child.stdin.end()
  40. }
  41. function regSearchKeys (keys, value, addOpts, cb) {
  42. var i = 0
  43. const search = () => {
  44. log.silly('reg-search', 'looking for %j in %j', value, keys[i])
  45. regGetValue(keys[i], value, addOpts, (err, res) => {
  46. ++i
  47. if (err && i < keys.length) { return search() }
  48. cb(err, res)
  49. })
  50. }
  51. search()
  52. }
  53. module.exports = {
  54. logWithPrefix: logWithPrefix,
  55. regGetValue: regGetValue,
  56. regSearchKeys: regSearchKeys
  57. }