Skip to content

Commit

Permalink
refactor: make CLI async
Browse files Browse the repository at this point in the history
  • Loading branch information
fisker committed Jan 30, 2023
1 parent 1488785 commit 0a956ee
Showing 1 changed file with 34 additions and 30 deletions.
64 changes: 34 additions & 30 deletions cli.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
#!/usr/bin/env node
import { globbySync } from 'globby'
import fs from 'node:fs'
import { globbyStream } from 'globby'
import fs from 'node:fs/promises'
import sortPackageJson from './index.js'

function showVersion() {
async function showVersion() {
const { name, version } = JSON.parse(
fs.readFileSync(new URL('package.json', import.meta.url)),
await fs.readFile(new URL('package.json', import.meta.url)),
)

console.log(`${name} ${version}`)
Expand All @@ -26,49 +26,53 @@ If file/glob is omitted, './package.json' file will be processed.
)
}

function sortPackageJsonFiles(patterns, { isCheck, shouldBeQuit }) {
const files = globbySync(patterns)
async function sortPackageJsonFiles(patterns, { isCheck, shouldBeQuit }) {
const printToStdout = shouldBeQuit ? () => {} : console.log

if (files.length === 0) {
console.error('No matching files.')
process.exitCode = 2
return
}

let notSortedFiles = 0
for (const file of files) {
const packageJson = fs.readFileSync(file, 'utf8')
let matchedFiles = 0
for await (const file of globbyStream(patterns)) {
matchedFiles++

const packageJson = await fs.readFile(file, 'utf8')
const sorted = sortPackageJson(packageJson)

if (sorted !== packageJson) {
if (isCheck) {
notSortedFiles++
printToStdout(file)
process.exitCode = 1
} else {
fs.writeFileSync(file, sorted)
if (sorted === packageJson) {
continue
}

notSortedFiles++

printToStdout(`${file} is sorted!`)
}
if (isCheck) {
printToStdout(file)
process.exitCode = 1
} else {
await fs.writeFile(file, sorted)
printToStdout(`${file} is sorted!`)
}
}

if (matchedFiles === 0) {
console.error('No matching files.')
process.exitCode = 2
return
}

if (isCheck) {
// Print a empty line
printToStdout()

if (notSortedFiles) {
printToStdout(
notSortedFiles === 1
? `${notSortedFiles} of ${files.length} matched file is not sorted.`
: `${notSortedFiles} of ${files.length} matched files are not sorted.`,
? `${notSortedFiles} of ${matchedFiles} matched file is not sorted.`
: `${notSortedFiles} of ${matchedFiles} matched files are not sorted.`,
)
} else {
printToStdout(
files.length === 1
? `${files.length} matched file is sorted.`
: `${files.length} matched files are sorted.`,
matchedFiles === 1
? `${matchedFiles} matched file is sorted.`
: `${matchedFiles} matched files are sorted.`,
)
}
}
Expand Down Expand Up @@ -109,7 +113,7 @@ function run() {
patterns[0] = 'package.json'
}

sortPackageJsonFiles(patterns, { isCheck, shouldBeQuit })
return sortPackageJsonFiles(patterns, { isCheck, shouldBeQuit })
}

run()
await run()

0 comments on commit 0a956ee

Please sign in to comment.