1 | const path = require('path')
|
2 | const chalk = require('chalk')
|
3 | const padEnd = require('lodash.padend')
|
4 |
|
5 | module.exports = function list () {
|
6 | const packageDir = path.resolve(process.cwd(), process.argv[2] || '')
|
7 | const packageJson = path.resolve(packageDir, 'package.json')
|
8 | const pkg = loadJSON(packageJson)
|
9 |
|
10 | if (!pkg) {
|
11 | console.error(`\n No package.json found in ${chalk.yellow(packageDir)}\n`)
|
12 | process.exit(1)
|
13 | }
|
14 |
|
15 | if (!pkg.scripts) {
|
16 | console.info(`\n No ${chalk.bold('scripts')} property in package.json\n`)
|
17 | process.exit(0)
|
18 | }
|
19 |
|
20 | if (!Object.keys(pkg.scripts).length) {
|
21 | console.info(`\n Empty ${chalk.bold('scripts')} in package.json\n`)
|
22 | process.exit(0)
|
23 | }
|
24 |
|
25 | process.stdout.write(`\n npm scripts in ${chalk.yellow(packageJson)}:\n`)
|
26 | printScripts(Object.entries(pkg.scripts))
|
27 | }
|
28 |
|
29 | function loadJSON (jsonPath) {
|
30 | try {
|
31 | return require(jsonPath)
|
32 | } catch (e) {}
|
33 | }
|
34 |
|
35 | function printScripts (scripts) {
|
36 | const maxCommandLength = scripts.reduce((accu, curr) => {
|
37 | const len = curr[0].length
|
38 | return len > accu ? len : accu
|
39 | }, 0)
|
40 |
|
41 | scripts.forEach(script => {
|
42 | const name = chalk.blue.bold(padEnd(script[0], maxCommandLength))
|
43 | const command = script[1]
|
44 | process.stdout.write(`\n * ${name} ${command}`)
|
45 | })
|
46 |
|
47 | process.stdout.write('\n\n')
|
48 | }
|