UNPKG

2.73 kBJavaScriptView Raw
1#!/usr/bin/env node
2
3'use strict'
4require('coffee-script').register()
5const pkg = require('../package.json')
6require('update-notifier')({ pkg }).notify()
7
8const fs = require('fs')
9const os = require('os')
10const path = require('path')
11const createLogger = require('acho')
12const loggerSkinCLI = require('acho-skin-cli')
13
14const finepack = require('./../lib/Finepack')
15
16const isNil = value => value === undefined || value === null
17
18const isPrivate = filepath => {
19 try {
20 return JSON.parse(filepath).private
21 } catch (err) {
22 return false
23 }
24}
25
26const cli = require('meow')({
27 pkg,
28 help: [
29 'Usage',
30 ' $ finepack <fileJSON> [options]',
31 '\n options:',
32 '\t --no-validate\t\t disable validate mode.',
33 '\t --no-color\t\t disable colors in the output.',
34 "\t --sort-ignore-object-at don't sort object(s) at these comma separated key(s).",
35 "\t --sort-ignore-array-at don't sort array(s) at these comma separated key(s).",
36 '\t --version\t\t output the current version.',
37 '\n examples:',
38 '\t finepack package.json',
39 '\t finepack bower.json --no-validate'
40 ].join('\n'),
41 flags: {
42 validate: {
43 type: 'boolean',
44 default: true
45 }
46 }
47})
48
49const cliFlagCsvToArray = flagName =>
50 cli.flags[flagName]
51 .toString()
52 .split(',')
53 .filter(e => e)
54
55const filepath = path.resolve(cli.input[0] || 'package.json')
56const filename = path.basename(filepath)
57
58let options = {
59 filename,
60 validate: isNil(cli.flags.validate)
61 ? isPrivate(filepath)
62 : cli.flags.validate,
63 color: cli.flags.color
64}
65
66let sortOptions = {}
67
68if (cli.flags.sortIgnoreObjectAt) {
69 const ignoreObjectAtKeys = cliFlagCsvToArray('sortIgnoreObjectAt')
70
71 if (ignoreObjectAtKeys.length) {
72 sortOptions = Object.assign({}, sortOptions, { ignoreObjectAtKeys })
73 }
74}
75
76if (cli.flags.sortIgnoreArrayAt) {
77 const ignoreArrayAtKeys = cliFlagCsvToArray('sortIgnoreArrayAt')
78
79 if (ignoreArrayAtKeys.length) {
80 sortOptions = Object.assign({}, sortOptions, { ignoreArrayAtKeys })
81 }
82}
83
84options = Object.assign({}, options, { sortOptions })
85
86const stringify = data => {
87 return JSON.stringify(data, null, 2) + os.EOL
88}
89
90fs.readFile(filepath, { encoding: 'utf8' }, (err, filedata) => {
91 if (err) throw err
92
93 finepack(filedata, options, (error, output, messages) => {
94 const log = createLogger({
95 types: loggerSkinCLI,
96 keyword: 'symbol',
97 color: options.color,
98 messages: messages
99 })
100
101 if (error) {
102 log.print()
103 log.error(output)
104 return process.exit(1)
105 }
106
107 output = stringify(output)
108
109 fs.writeFile(filepath, output, { encoding: 'utf8' }, err => {
110 if (err) throw err
111 console.log()
112 log.print()
113 })
114 })
115})