Completed
Push — master ( 3f76fd...7863ed )
by Thomas
30s
created

Updater.js ➔ getLatestVersion   A

Complexity

Conditions 1
Paths 3

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
nc 3
nop 1
dl 0
loc 8
rs 9.4285
c 1
b 0
f 0

1 Function

Rating   Name   Duplication   Size   Complexity  
A Updater.js ➔ ... ➔ util.end 0 6 4
1
'use strict'
2
3
const fs = require('fs')
4
const cli = require('pixl-cli')
5
const path = require('path')
6
const util = require('../util')
7
const chalk = require('chalk')
8
const semver = require('semver')
9
const manifest = require('../../package.json')
10
11
var versionCheckFile = path.join(util.getPluginsDirectory(), '.version_check_cache')
12
13
function needsCheck () {
14
  try {
15
    var lastChecked = parseInt(fs.readFileSync(versionCheckFile, 'utf8'), 10) || 0
16
    if (lastChecked > (new Date()).getTime() - 43200000) {
17
      return false
18
    }
19
  } catch (e) {
20
    // Do nothing
21
  }
22
23
  return true
24
}
25
26
function setNeedsCheck (force) {
27
  if (!fs.existsSync(util.getPluginsDirectory())) {
28
    fs.mkdirSync(util.getPluginsDirectory())
29
  }
30
  fs.writeFileSync(versionCheckFile, force ? '-2' : (new Date()).getTime().toString(), 'utf8')
31
}
32
33
function getLatestVersion (cb) {
34
  util.request('cli/version').timeout(2000).end(function (response) {
35
    if (response.body && typeof response.body === 'object' && 'data' in response.body) {
36
      cb(response.body.data)
37
    }
38
    cb(null)
39
  })
40
}
41
42
module.exports = function (cb) {
43
  if (!needsCheck()) {
44
    cb()
45
    return
46
  }
47
48
  var didCallback = false
49
  var stopSpinner = util.output.wait('Checking for updates')
50
  getLatestVersion(function (version) {
51
    if (version) {
52
      if (semver.gt(version, manifest.version)) {
53
        var type = semver.diff(version, manifest.version)
54
        var color = type === 'patch' ? 'yellow' : 'red'
55
        cli.print('\n' +
56
          cli.box(cli.center(chalk[color](chalk.bold('Update available: v' + version)) + '\n' +
57
            chalk.white('npm i -g includable@latest'), 33), {
58
              styles: [color],
59
              indent: 2
60
            }) + '\n'
61
        )
62
63
        setNeedsCheck(true)
64
      } else {
65
        setNeedsCheck(false)
66
      }
67
    }
68
    if (!didCallback) {
69
      didCallback = true
70
      stopSpinner()
71
      cb()
72
    }
73
  })
74
}
75