Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: Argument parsing (>= node 16) #283

Open
wants to merge 10 commits into
base: main
Choose a base branch
from
48 changes: 26 additions & 22 deletions cli.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#!/usr/bin/env node
import { globbySync } from 'globby'
import fs from 'node:fs'
import { parseArgs } from 'node:util'
aarondill marked this conversation as resolved.
Show resolved Hide resolved
import sortPackageJson from './index.js'
import Reporter from './reporter.js'

Expand All @@ -27,6 +28,25 @@ If file/glob is omitted, './package.json' file will be processed.
)
}

function parseCliArguments() {
try {
return parseArgs({
aarondill marked this conversation as resolved.
Show resolved Hide resolved
options: {
check: { type: 'boolean', short: 'c' },
quiet: { type: 'boolean', short: 'q' },
version: { type: 'boolean', short: 'v' },
help: { type: 'boolean', short: 'h' },
},
allowPositionals: true,
strict: true,
})
} catch (err) {
const { message } = err
console.error(message)
process.exit(2)
aarondill marked this conversation as resolved.
Show resolved Hide resolved
}
}

function sortPackageJsonFile(file, reporter, isCheck) {
const original = fs.readFileSync(file, 'utf8')
const sorted = sortPackageJson(original)
Expand Down Expand Up @@ -58,35 +78,19 @@ function sortPackageJsonFiles(patterns, options) {
}

function run() {
const cliArguments = process.argv.slice(2)
const cliArguments = parseCliArguments()

if (
cliArguments.some((argument) => argument === '--help' || argument === '-h')
) {
if (cliArguments.values.help) {
return showHelpInformation()
}

if (
cliArguments.some(
(argument) => argument === '--version' || argument === '-v',
)
) {
if (cliArguments.values.version) {
return showVersion()
}

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)
}
}
const patterns = cliArguments.positionals
const isCheck = !!cliArguments.values.check
const shouldBeQuiet = !!cliArguments.values.quiet
aarondill marked this conversation as resolved.
Show resolved Hide resolved

if (!patterns.length) {
aarondill marked this conversation as resolved.
Show resolved Hide resolved
patterns[0] = 'package.json'
Expand Down