forked from siddharthkp/nps-i
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
107 lines (85 loc) · 2.67 KB
/
index.js
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
#!/usr/bin/env node
const inquirer = require('inquirer')
const autocomplete = require('inquirer-autocomplete-prompt')
const fuzzy = require('fuzzy')
const pad = require('right-pad')
const path = require('path')
const exec = require('./exec')
const config = path.join(process.cwd(), './package-scripts.js')
const packageScripts = require(config).scripts
let flatScripts = []
const flattenScripts = (scripts, prefix) => {
const keys = Object.keys(scripts)
keys.forEach(key => {
// format = name: command
let script
let description
let name
if (prefix) name = prefix + '.' + key
else name = key
// format = name: command
if (typeof scripts[key] === 'string') {
script = scripts[key]
description = ''
}
if (typeof scripts[key] === 'object') {
const shape = scripts[key]
// format = name: { default: command }
if (typeof shape.default === 'string') {
script = shape.default
description = shape.description
delete shape.default
delete shape.description
}
// format = name: { script: command }
if (typeof shape.script === 'string') {
script = shape.script
description = shape.description
delete shape.script
delete shape.description
}
// recursively call for other shapes inside this object
// format = parent: { child: { script: command } }
flattenScripts(shape, name)
}
if (script) flatScripts.push({ name, script, description })
})
}
/* Flatten scripts */
flattenScripts(packageScripts)
/* Find longest key */
let longestKey = ''
flatScripts.forEach(element => {
if (element.name.length > longestKey.length) longestKey = element.name
})
/* Width of key column */
const width = longestKey.length + 5
/* Add pretty string to each element */
flatScripts = flatScripts.map(element => {
element.prettyString = `${pad(element.name, width)} ${element.description}`
return element
})
const fuzzyOptions = {
extract: element => element.prettyString
}
const filterScripts = (_, input) => {
input = input || ''
return new Promise(resolve => {
const results = fuzzy.filter(input, flatScripts, fuzzyOptions)
const prettyResults = results.map(result => {
return result.original.prettyString
})
resolve(prettyResults)
})
}
const autocompleteOptions = {
type: 'autocomplete',
name: 'string',
message: 'Which script would you like to run?\n\n',
source: filterScripts
}
inquirer.registerPrompt('autocomplete', autocomplete)
inquirer.prompt(autocompleteOptions).then(result => {
const element = flatScripts.find(element => element.prettyString === result.string)
exec(`nps ${element.name}`)
})