-
Notifications
You must be signed in to change notification settings - Fork 88
/
cli.js
executable file
·108 lines (87 loc) · 2.42 KB
/
cli.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
108
#!/usr/bin/env node
import { globSync } from 'tinyglobby'
import fs from 'node:fs'
import getStdin from 'get-stdin'
import sortPackageJson from './index.js'
import Reporter from './reporter.js'
function showVersion() {
const { name, version } = JSON.parse(
fs.readFileSync(new URL('package.json', import.meta.url)),
)
console.log(`${name} ${version}`)
}
function showHelpInformation() {
console.log(
`Usage: sort-package-json [options] [file/glob ...]
Sort package.json files.
If file/glob is omitted, './package.json' file will be processed.
-c, --check Check if files are sorted
-q, --quiet Don't output success messages
-h, --help Display this help
-v, --version Display the package version
--stdin Read package.json from stdin
`,
)
}
function sortPackageJsonFile(file, reporter, isCheck) {
const original = fs.readFileSync(file, 'utf8')
const sorted = sortPackageJson(original)
if (sorted === original) {
return reporter.reportNotChanged(file)
}
if (!isCheck) {
fs.writeFileSync(file, sorted)
}
reporter.reportChanged(file)
}
function sortPackageJsonFiles(patterns, options) {
const files = globSync(patterns)
const reporter = new Reporter(files, options)
const { isCheck } = options
for (const file of files) {
try {
sortPackageJsonFile(file, reporter, isCheck)
} catch (error) {
reporter.reportFailed(file, error)
}
}
reporter.printSummary()
}
async function sortPackageJsonFromStdin() {
process.stdout.write(sortPackageJson(await getStdin()))
}
function run() {
const cliArguments = process.argv.slice(2)
if (
cliArguments.some((argument) => argument === '--help' || argument === '-h')
) {
return showHelpInformation()
}
if (
cliArguments.some(
(argument) => argument === '--version' || argument === '-v',
)
) {
return showVersion()
}
if (cliArguments.some((argument) => argument === '--stdin')) {
return sortPackageJsonFromStdin()
}
const patterns = []
let isCheck = false
let shouldBeQuiet = false
for (const argument of cliArguments) {
if (argument === '--check' || argument === '-c') {
isCheck = true
} else if (argument === '--quiet' || argument === '-q') {
shouldBeQuiet = true
} else {
patterns.push(argument)
}
}
if (!patterns.length) {
patterns[0] = 'package.json'
}
sortPackageJsonFiles(patterns, { isCheck, shouldBeQuiet })
}
run()