From 54270fdf05ec8712c4006ed2bcd5d5969b2bd09c Mon Sep 17 00:00:00 2001 From: aarondill Date: Wed, 1 Feb 2023 11:43:15 -0600 Subject: [PATCH] feat: use util.parseArgs --- cli.js | 48 ++++++++++++++++++++++++++---------------------- 1 file changed, 26 insertions(+), 22 deletions(-) diff --git a/cli.js b/cli.js index e1cb7bd9..340244c4 100755 --- a/cli.js +++ b/cli.js @@ -1,6 +1,7 @@ #!/usr/bin/env node import { globbySync } from 'globby' import fs from 'node:fs' +import { parseArgs } from 'node:util' import sortPackageJson from './index.js' import Reporter from './reporter.js' @@ -27,6 +28,25 @@ If file/glob is omitted, './package.json' file will be processed. ) } +function parseCliArguments() { + try { + return parseArgs({ + 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) + } +} + function sortPackageJsonFile(file, reporter, isCheck) { const original = fs.readFileSync(file, 'utf8') const sorted = sortPackageJson(original) @@ -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 if (!patterns.length) { patterns[0] = 'package.json'