UNPKG

2.97 kBPlain TextView Raw
1#!/usr/bin/env node
2
3const cmdline = require('commander');
4const fs = require('fs-extra');
5const path = require('path');
6const prettier = require('../src');
7const { version } = require('../package.json');
8const defaults = require('../src/defaultOptions');
9const glob = require('glob');
10
11cmdline
12 .version(version)
13 .arguments('[PATH...]')
14 .option('--write', 'Edit the files in-place. (Beware!)')
15 .option('--tab-width <int>', `Specify the number of spaces per indentation-level. Defaults to ${defaults.tabWidth}.`, (value) => parseInt(value, 10), defaults.tabWidth)
16 .option('--use-tabs', 'Indent lines with tabs instead of spaces.')
17 .option('--expand-users', 'Expand author and contributors into objects.')
18 .option('--key-order <items>', 'Sort order for keys in package.json', (val) => val.split(','), defaults.keyOrder)
19 .option('-l, --list-different', 'Print filenames of files that are different from prettier-package-json formatting.')
20 .parse(process.argv);
21
22const globs = cmdline.args.length > 0 ? cmdline.args : [path.join(process.cwd(), 'package.json')];
23
24const files = Promise.all(globs.map(globToPaths)).then((matches) => {
25 return matches.reduce((state, match) => [...state, ...match], []);
26});
27
28if (cmdline.listDifferent) {
29 files.then((paths) => {
30 return Promise.all(paths.map((filepath) => check(filepath, cmdline)));
31 }).then((details) => {
32 details.forEach(({ filepath, isDifferent, error }) => {
33 if (error) {
34 console.error(error);
35 } else if (isDifferent) {
36 console.log(filepath);
37 }
38 });
39 });
40} else {
41 files.then((paths) => {
42 return Promise.all(paths.map((filepath) => format(filepath, cmdline)));
43 }).then((details) => {
44 details.forEach(({ filepath, json, error }) => {
45 if (error) {
46 console.error(error);
47 } else {
48 if (cmdline.write) {
49 return fs.writeFile(filepath, json);
50 } else {
51 return console.log(json);
52 }
53 }
54 });
55 })
56}
57
58function globToPaths(arg) {
59 return new Promise((resolve, reject) => {
60 glob(arg, (err, files) => err ? reject(err) : resolve(files));
61 });
62}
63
64function format(filepath, options) {
65 return fs.pathExists(filepath).then((exists) => {
66 if (exists) {
67 return fs.readJson(filepath);
68 } else {
69 return Promise.reject(`${filepath} doesn't exist`);
70 }
71 }).then((json) => {
72 return prettier.format(json, options);
73 }).then((json) => {
74 return { filepath, json };
75 }).catch((error) => {
76 return { filepath, error };
77 });
78}
79
80function check(filepath, options) {
81 return fs.pathExists(filepath).then((exists) => {
82 if (exists) {
83 return fs.readJson(filepath);
84 } else {
85 return Promise.reject(`${filepath} doesn't exist`);
86 }
87 }).then((json) => {
88 return prettier.check(json, options);
89 }).then((isSame) => {
90 return { filepath, isDifferent: !isSame };
91 }).catch((error) => {
92 return { filepath, error };
93 });
94}