1 | const path = require('path')
|
2 | const packageJson = require('package-json')
|
3 | const semver = require('semver')
|
4 |
|
5 | async function getPkgVersion (name) {
|
6 | try {
|
7 | return await packageJson(name)
|
8 | } catch (e) {
|
9 | console.log(e)
|
10 | }
|
11 | }
|
12 |
|
13 | async function update () {
|
14 | const { version: currentVersion, name } = require(path.resolve(
|
15 | __dirname,
|
16 | '../package.json'
|
17 | ))
|
18 |
|
19 | const { version: latestVersion } = await getPkgVersion(name)
|
20 |
|
21 | let isNeedUpdate = semver.lt(currentVersion, latestVersion)
|
22 |
|
23 | return { name, currentVersion, latestVersion, isNeedUpdate }
|
24 | }
|
25 |
|
26 | function getWidthOfWindow () {
|
27 | if (typeof process === 'object' && process.stdout && process.stdout.columns) {
|
28 | return process.stdout.columns
|
29 | }
|
30 |
|
31 | return 80
|
32 | }
|
33 |
|
34 | async function print () {
|
35 | const { name, currentVersion, latestVersion, isNeedUpdate } = update()
|
36 |
|
37 | if (isNeedUpdate) {
|
38 | let text = [
|
39 | `Update avaliable ${currentVersion} -> ${latestVersion}`,
|
40 | `Run npm update ${name}@${latestVersion} to update`
|
41 | ]
|
42 | const maxWidth = getWidthOfWindow()
|
43 | const box = {
|
44 | topLeft: '╭',
|
45 | topRight: '╮',
|
46 | bottomRight: '╯',
|
47 | bottomLeft: '╰',
|
48 | vertical: '│',
|
49 | horizontal: '─'
|
50 | }
|
51 |
|
52 | const lines = []
|
53 | let line = box.topLeft + box.horizontal.repeat(maxWidth - 2) + box.topRight
|
54 | let lineOfCenter = ''
|
55 | let lineOfLast =
|
56 | box.bottomLeft + box.horizontal.repeat(maxWidth - 2) + box.bottomRight
|
57 |
|
58 | lines.push(line)
|
59 |
|
60 | function paddingWithCode (str, len = 0, code = ' ') {
|
61 | return code.repeat(len) + str + code.repeat(len)
|
62 | }
|
63 |
|
64 | text.forEach(v => {
|
65 | let width = Math.trunc((maxWidth - v.length - 2) / 2)
|
66 | let str = paddingWithCode(v, width)
|
67 | if (str.length % 2 == 1) {
|
68 | str += ' '
|
69 | }
|
70 | lineOfCenter = box.vertical + str + box.vertical
|
71 | lines.push(lineOfCenter)
|
72 | })
|
73 |
|
74 | lines.push(lineOfLast)
|
75 |
|
76 | console.log(lines.join('\n'))
|
77 | }
|
78 | }
|
79 |
|
80 | module.exports = print
|