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

feat(cli): added --version and --help options #282

Merged
merged 12 commits into from
Jan 22, 2023
37 changes: 36 additions & 1 deletion cli.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,47 @@
#!/usr/bin/env node
import fs from 'node:fs'
import { globbySync } from 'globby'
import fs from 'node:fs'
import sortPackageJson from './index.js'

const isCheckFlag = (argument) => argument === '--check' || argument === '-c'
const isHelpFlag = (argument) => argument === '--help' || argument === '-h'
const isVersionFlag = (argument) =>
argument === '--version' || argument === '-V'

const cliArguments = process.argv.slice(2)
const isCheck = cliArguments.some(isCheckFlag)
const isHelp = cliArguments.some(isHelpFlag)
const isVersion = cliArguments.some(isVersionFlag)

if (isHelp) {
console.log(
`Usage: sort-package-json [OPTION...] [FILE...]
Sort npm package.json files. Default: ./package.json
Strings passed as files are parsed as globs.

-c, --check check if FILES are sorted
-q, --quiet don't output success messages
aarondill marked this conversation as resolved.
Show resolved Hide resolved
-h, --help display this help and exit
-V, --version display the version and exit
aarondill marked this conversation as resolved.
Show resolved Hide resolved
aarondill marked this conversation as resolved.
Show resolved Hide resolved
`,
)
process.exit(0)
}

if (isVersion) {
try {
const cliRealPath = fs.realpathSync(process.argv[1])
const cliParentDir = (await import('node:path')).dirname(cliRealPath)
const packageJsonBuffer = fs.readFileSync(`${cliParentDir}/package.json`)
aarondill marked this conversation as resolved.
Show resolved Hide resolved
const { version } = JSON.parse(packageJsonBuffer)

console.log(`sort-package-json ${version}`)
} catch {
// If anything goes wrong, fall back to 'unknown version'
aarondill marked this conversation as resolved.
Show resolved Hide resolved
console.log(`sort-package-json unknown version`)
}
process.exit(0)
}

const patterns = cliArguments.filter((argument) => !isCheckFlag(argument))

Expand Down