Skip to content

Commit

Permalink
feat(nr): select script
Browse files Browse the repository at this point in the history
  • Loading branch information
antfu committed Dec 26, 2020
1 parent 55457f1 commit 3d9b6bd
Show file tree
Hide file tree
Showing 4 changed files with 55 additions and 9 deletions.
14 changes: 6 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,14 +65,6 @@ ni -g iroiro

### `nr` - run

```bash
nr

# npm run start
# yarn run start
# pnpm run start
```

```bash
nr dev --port=3000

Expand All @@ -81,6 +73,12 @@ nr dev --port=3000
# pnpm run dev -- --port=3000
```

```bash
nr

# interactively select the script to run
```

### `nci` - clean install

```bash
Expand Down
18 changes: 18 additions & 0 deletions src/fs.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { resolve } from 'path'
import fs from 'fs'

export function getPackageJSON(): any {
const path = resolve(process.cwd(), 'package.json')

if (fs.existsSync(path)) {
try {
const raw = fs.readFileSync(path, 'utf-8')
const data = JSON.parse(raw)
return data
}
catch (e) {
console.warn('Failed to parse package.json')
process.exit(0)
}
}
}
27 changes: 27 additions & 0 deletions src/nr.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,33 @@
import inquirer from 'inquirer'
import { parseNr } from './commands'
import { getPackageJSON } from './fs'
import { run } from './runner'

run(async(agent, args) => {
if (args.length === 0) {
const scripts = getPackageJSON().scripts || {}

const names = Object.keys(scripts)

if (!names.length)
return

try {
const { fn } = await inquirer.prompt({
name: 'fn',
message: 'script to run',
pageSize: 20,
type: 'list',
choices: names,
})
if (!fn)
return
args.push(fn)
}
catch (e) {
console.error(e)
process.exit(1)
}
}
return parseNr(agent, args)
})
5 changes: 4 additions & 1 deletion src/runner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { remove } from './utils'
const args = process.argv.slice(2).filter(Boolean)
const DEBUG_SIGN = '?'

export type Runner = (agent: Agent, args: string[], hasLock?: boolean) => Promise<string>
export type Runner = (agent: Agent, args: string[], hasLock?: boolean) => Promise<string | undefined>

export async function run(fn: Runner, options: DetectOptions = {}) {
const debug = args.includes(DEBUG_SIGN)
Expand All @@ -25,6 +25,9 @@ export async function run(fn: Runner, options: DetectOptions = {}) {
command = await fn(agent || await getDefaultAgent(), args, Boolean(agent))
}

if (!command)
return

if (debug)
console.log(command)
else
Expand Down

0 comments on commit 3d9b6bd

Please sign in to comment.