-
-
Notifications
You must be signed in to change notification settings - Fork 195
/
nr.ts
95 lines (81 loc) · 2.41 KB
/
nr.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import type { Choice } from '@posva/prompts'
import prompts from '@posva/prompts'
import c from 'kleur'
import { Fzf } from 'fzf'
import { dump, load } from '../storage'
import { parseNr } from '../parse'
import { getPackageJSON } from '../fs'
import { runCli } from '../runner'
runCli(async (agent, args, ctx) => {
const storage = await load()
if (args[0] === '-') {
if (!storage.lastRunCommand) {
if (!ctx?.programmatic) {
console.error('No last command found')
process.exit(1)
}
throw new Error('No last command found')
}
args[0] = storage.lastRunCommand
}
if (args.length === 0 && !ctx?.programmatic) {
// support https://www.npmjs.com/package/npm-scripts-info conventions
const pkg = getPackageJSON(ctx)
const scripts = pkg.scripts || {}
const scriptsInfo = pkg['scripts-info'] || {}
const names = Object.entries(scripts) as [string, string][]
if (!names.length)
return
const raw = names
.filter(i => !i[0].startsWith('?'))
.map(([key, cmd]) => ({
key,
cmd,
description: scriptsInfo[key] || scripts[`?${key}`] || cmd,
}))
const terminalColumns = process.stdout?.columns || 80
function limitText(text: string, maxWidth: number) {
if (text.length <= maxWidth)
return text
return `${text.slice(0, maxWidth)}${c.dim('…')}`
}
const choices: Choice[] = raw
.map(({ key, description }) => ({
title: key,
value: key,
description: limitText(description, terminalColumns - 15),
}))
const fzf = new Fzf(raw, {
selector: item => `${item.key} ${item.description}`,
casing: 'case-insensitive',
})
if (storage.lastRunCommand) {
const last = choices.find(i => i.value === storage.lastRunCommand)
if (last)
choices.unshift(last)
}
try {
const { fn } = await prompts({
name: 'fn',
message: 'script to run',
type: 'autocomplete',
choices,
async suggest(input: string, choices: Choice[]) {
const results = fzf.find(input)
return results.map(r => choices.find(c => c.value === r.item.key))
},
})
if (!fn)
return
args.push(fn)
}
catch (e) {
process.exit(1)
}
}
if (storage.lastRunCommand !== args[0]) {
storage.lastRunCommand = args[0]
dump()
}
return parseNr(agent, args)
})