-
Notifications
You must be signed in to change notification settings - Fork 2
/
extension.ts
245 lines (215 loc) · 6.63 KB
/
extension.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
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
234
235
236
237
238
239
240
241
242
243
244
245
import { spawnSync } from "child_process";
import * as crypto from "crypto";
import * as jp from "jsonpath";
import * as path from "path";
import * as vscode from "vscode";
import { requireOperation } from "./requireOperation";
const serializers = {
json: (val: string | object) => {
return JSON.stringify(val);
},
plain: (val: string | object) => {
if (Array.isArray(val)) {
return val.join(" ");
}
return `${val}`;
},
};
type ReadOperationOptions = {
var: string;
quickPickOptions?: vscode.QuickPickOptions;
};
type WriteOperationOptions = {
var?: string;
command: string;
args: string[];
unwrap?: string;
serializer?: keyof typeof serializers;
quickPickOptions?: vscode.QuickPickOptions;
};
const cache: Map<string, string> = new Map<string, string>();
function isWriteOperationOptions(opts: any): asserts opts is WriteOperationOptions {
if (typeof opts !== "object") {
throw new Error("Expected args to an object");
}
if (opts === null) {
throw new Error("Expected args to be an object");
}
if (!Array.isArray(opts.args)) {
throw new Error("Expected args to be string[]");
}
if (opts.serializer && !(opts.serializer in serializers)) {
throw new Error("Expected serializer is not implemented");
}
if (!(opts.args as string[]).every((arg: unknown) => typeof arg === "string")) {
throw new Error("Expected args to be string[]");
}
if ("var" in opts) {
if (typeof opts.var !== "string") {
throw new Error("Expected args.var to be string[]");
}
if (opts.var.trim() === "") {
throw new Error("Expected args.var to be a non-empty string");
}
}
}
function isReadOperationOptions(opts: any): asserts opts is ReadOperationOptions {
if (typeof opts !== "object") {
throw new Error("Expected args to be an object");
}
if (opts === null) {
throw new Error("Expected args to be not null");
}
if (typeof opts.var !== "string") {
throw new Error("Expected args.var to be a string");
}
if (opts.var.trim() === "") {
throw new Error("Expected args.var to be a non-empty string");
}
}
function resolveVariables(str: string, vars: Record<string, string | undefined>) {
return path.normalize(
str.replace(/(\${([^}]+)})/g, (_, match, name) => {
return vars[name] ?? match;
})
);
}
function sha256(str: string) {
return crypto.createHash("sha256").update(str, "utf8").digest("hex");
}
function truncate(str: string, n: number = 24) {
return str.slice(0, n);
}
function getSubstitutedVariables(
opts: ReadOperationOptions | WriteOperationOptions
): Record<string, string | undefined> {
const currentWorkspace = vscode.workspace.workspaceFolders?.[0];
if (!currentWorkspace) {
throw new Error(`Failed to retrieve current workspace`);
}
return {
configId: truncate(sha256(JSON.stringify(opts)), 8),
workspaceId: truncate(sha256(currentWorkspace.uri.path), 8),
workspaceFolder: currentWorkspace.uri.path,
workspaceName: currentWorkspace.name,
};
}
async function writeOperation(opts: WriteOperationOptions) {
const variables = getSubstitutedVariables(opts);
const resolvedArgs = opts.args.map((arg) => resolveVariables(arg, variables));
const child = spawnSync(opts.command, resolvedArgs, {
encoding: "utf-8",
shell: true,
cwd: variables.workspaceFolder,
});
const lines = child.stdout.split("\n");
for (let i = lines.length - 1; i >= 0; i--) {
try {
const line = lines[i];
if (!line) {
continue;
}
const items: vscode.QuickPickItem[] = JSON.parse(line);
const selection = await vscode.window.showQuickPick<vscode.QuickPickItem>(items, opts.quickPickOptions);
if (typeof selection === "undefined") {
// reset cache after cancellation
cache.clear();
// skip when no selection was made
return;
}
let value: string | undefined;
const serialize = serializers[opts.serializer ?? "json"];
if (typeof selection === "string") {
value = serialize(selection);
}
if (typeof selection === "object") {
if (selection === null) {
value = serialize(selection);
} else {
if (opts.quickPickOptions?.canPickMany) {
const unwrapped = jp.query(selection, opts.unwrap ?? "*");
value = serialize(unwrapped);
} else {
const unwrapped = jp.value(selection, opts.unwrap ?? "$");
value = serialize(unwrapped);
}
}
}
if (typeof value === "undefined") {
// reset cache after cancellation
cache.clear();
// skip when no selection was made
return;
}
if (opts.var) {
const variables = getSubstitutedVariables(opts);
const key = resolveVariables(opts.var, variables);
cache.set(key, value);
}
return value;
} catch (err) {
if (i === 0) {
throw err;
}
}
}
}
export function activate(context: vscode.ExtensionContext) {
context.subscriptions.push(
vscode.commands.registerCommand("dynamic-inputs.write", async (opts: unknown) => {
try {
isWriteOperationOptions(opts);
return await writeOperation(opts);
} catch (err) {
if (err instanceof Error) {
await vscode.window.showErrorMessage(err.name, {
modal: true,
detail: err.message,
});
return;
}
throw err;
}
})
);
context.subscriptions.push(
vscode.tasks.onDidStartTask(() => {
return cache.clear();
})
);
context.subscriptions.push(
vscode.debug.onDidStartDebugSession(() => {
return cache.clear();
})
);
context.subscriptions.push(
vscode.commands.registerCommand("dynamic-inputs.read", async (opts: unknown) => {
try {
isReadOperationOptions(opts);
const variables = getSubstitutedVariables(opts);
const key = resolveVariables(opts.var, variables);
if (cache.has(key)) {
return cache.get(key);
}
isWriteOperationOptions(opts);
return await writeOperation(opts);
} catch (err) {
if (err instanceof Error) {
await vscode.window.showErrorMessage(err.name, {
modal: true,
detail: err.message,
});
return;
}
throw err;
}
})
);
context.subscriptions.push(
vscode.commands.registerCommand("dynamic-inputs.require", (scriptPath: string) => {
vscode.window.showWarningMessage("Deprecation: replace dynamic-inputs.require with dynamic-inputs.write");
return requireOperation(scriptPath);
})
);
}
export function deactivate() {}