-
-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathpnpm-handler.ts
More file actions
233 lines (202 loc) · 6.82 KB
/
pnpm-handler.ts
File metadata and controls
233 lines (202 loc) · 6.82 KB
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
import { promisify } from 'node:util';
import child_process from 'node:child_process';
const exec = promisify(child_process.exec);
const { execSync } = child_process;
import type { PackageManagerCompletion } from '../package-manager-completion.js';
import { Command, Option } from '../../src/t.js';
interface LazyCommand extends Command {
_lazyCommand?: string;
_optionsLoaded?: boolean;
optionsRaw?: Map<string, Option>;
}
import {
packageJsonScriptCompletion,
packageJsonDependencyCompletion,
} from '../completions/completion-producers.js';
import {
stripAnsiEscapes,
measureIndent,
parseAliasList,
COMMAND_ROW_RE,
OPTION_ROW_RE,
OPTION_HEAD_RE,
type ParsedOption,
} from '../utils/text-utils.js';
// regex to detect options section in help text
const OPTIONS_SECTION_RE = /^\s*Options:/i;
// we parse the pnpm help text to extract commands and their descriptions!
export function parsePnpmHelp(helpText: string): Record<string, string> {
const helpLines = stripAnsiEscapes(helpText).split(/\r?\n/);
// we find the earliest description column across command rows.
let descColumnIndex = Number.POSITIVE_INFINITY;
for (const line of helpLines) {
const rowMatch = line.match(COMMAND_ROW_RE);
if (!rowMatch) continue;
const descColumnIndexOnThisLine = line.indexOf(rowMatch[2]);
if (
descColumnIndexOnThisLine >= 0 &&
descColumnIndexOnThisLine < descColumnIndex
) {
descColumnIndex = descColumnIndexOnThisLine;
}
}
if (!Number.isFinite(descColumnIndex)) return {};
// we fold rows, and join continuation lines aligned to descColumnIndex or deeper.
type PendingRow = { names: string[]; desc: string } | null;
let pendingRow: PendingRow = null;
const commandMap = new Map<string, string>();
const flushPendingRow = () => {
if (!pendingRow) return;
const desc = pendingRow.desc.trim();
for (const name of pendingRow.names) commandMap.set(name, desc);
pendingRow = null;
};
for (const line of helpLines) {
if (OPTIONS_SECTION_RE.test(line)) break; // we stop at options
// we match the command row
const rowMatch = line.match(COMMAND_ROW_RE);
if (rowMatch) {
flushPendingRow();
pendingRow = {
names: parseAliasList(rowMatch[1]),
desc: rowMatch[2].trim(),
};
continue;
}
// we join continuation lines aligned to descColumnIndex or deeper
if (pendingRow) {
const indentWidth = measureIndent(line);
if (indentWidth >= descColumnIndex && line.trim()) {
pendingRow.desc += ' ' + line.trim();
}
}
}
// we flush the pending row and return the command map
flushPendingRow();
return Object.fromEntries(commandMap);
}
// now we get the pnpm commands from the main help output
export async function getPnpmCommandsFromMainHelp(): Promise<
Record<string, string>
> {
try {
const { stdout } = await exec('pnpm --help', {
encoding: 'utf8',
timeout: 500,
maxBuffer: 4 * 1024 * 1024,
});
return parsePnpmHelp(stdout);
} catch {
return {};
}
}
// here we parse the pnpm options from the help text
export function parsePnpmOptions(
helpText: string,
{ flagsOnly = true }: { flagsOnly?: boolean } = {}
): ParsedOption[] {
// we strip the ANSI escapes from the help text
const helpLines = stripAnsiEscapes(helpText).split(/\r?\n/);
// we find the earliest description column among option rows we care about
let descColumnIndex = Number.POSITIVE_INFINITY;
for (const line of helpLines) {
const optionMatch = line.match(OPTION_ROW_RE);
if (!optionMatch) continue;
if (flagsOnly && optionMatch.groups?.val) continue; // skip value-taking options, we will add them manually with their value
const descColumnIndexOnThisLine = line.indexOf(optionMatch.groups!.desc);
if (
descColumnIndexOnThisLine >= 0 &&
descColumnIndexOnThisLine < descColumnIndex
) {
descColumnIndex = descColumnIndexOnThisLine;
}
}
if (!Number.isFinite(descColumnIndex)) return [];
// we fold the option rows and join the continuations
const optionsOut: ParsedOption[] = [];
let pendingOption: ParsedOption | null = null;
const flushPendingOption = () => {
if (!pendingOption) return;
pendingOption.desc = pendingOption.desc.trim();
optionsOut.push(pendingOption);
pendingOption = null;
};
// we match the option row
for (const line of helpLines) {
const optionMatch = line.match(OPTION_ROW_RE);
if (optionMatch) {
if (flagsOnly && optionMatch.groups?.val) continue;
flushPendingOption();
pendingOption = {
short: optionMatch.groups?.short || undefined,
long: optionMatch.groups!.long,
desc: optionMatch.groups!.desc.trim(),
};
continue;
}
// we join the continuations
if (pendingOption) {
const indentWidth = measureIndent(line);
const startsNewOption = OPTION_HEAD_RE.test(line);
if (indentWidth >= descColumnIndex && line.trim() && !startsNewOption) {
pendingOption.desc += ' ' + line.trim();
}
}
}
// we flush the pending option
flushPendingOption();
return optionsOut;
}
// we load the dynamic options synchronously when requested ( separated from the command loading )
export function loadDynamicOptionsSync(
cmd: LazyCommand,
command: string
): void {
try {
const stdout = execSync(`pnpm ${command} --help`, {
encoding: 'utf8',
timeout: 500,
});
const parsedOptions = parsePnpmOptions(stdout, { flagsOnly: true });
for (const { long, short, desc } of parsedOptions) {
const alreadyDefined = cmd.optionsRaw?.get?.(long);
if (!alreadyDefined) cmd.option(long, desc, short);
}
} catch (_err) {}
}
// we setup the lazy option loading for a command
function setupLazyOptionLoading(cmd: LazyCommand, command: string): void {
cmd._lazyCommand = command;
cmd._optionsLoaded = false;
const optionsStore = cmd.options;
cmd.optionsRaw = optionsStore;
Object.defineProperty(cmd, 'options', {
get() {
if (!this._optionsLoaded) {
this._optionsLoaded = true;
loadDynamicOptionsSync(this, this._lazyCommand); // block until filled
}
return optionsStore;
},
configurable: true,
});
}
export async function setupPnpmCompletions(
completion: PackageManagerCompletion
): Promise<void> {
try {
const commandsWithDescriptions = await getPnpmCommandsFromMainHelp();
for (const [command, description] of Object.entries(
commandsWithDescriptions
)) {
const cmd = completion.command(command, description);
if (['remove', 'rm', 'update', 'up'].includes(command)) {
cmd.argument('package', packageJsonDependencyCompletion);
}
if (command === 'run') {
cmd.argument('script', packageJsonScriptCompletion, true);
}
setupLazyOptionLoading(cmd, command);
}
} catch (_err) {}
}