-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathhelpers.ts
More file actions
367 lines (307 loc) · 10.8 KB
/
helpers.ts
File metadata and controls
367 lines (307 loc) · 10.8 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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
import * as cp from "node:child_process";
import * as path from "node:path";
import * as core from "@actions/core";
import * as httpClient from "@actions/http-client";
import * as tc from "@actions/tool-cache";
import { SemVer } from "semver";
import { parse } from "shell-quote";
import which from "which";
import { version as actionVersion } from "../package.json";
import { parseNpmRegistryResponse, parsePylanceBuildMetadata } from "./schema";
export function getActionVersion() {
return actionVersion;
}
export interface NodeInfo {
version: string;
execPath: string;
}
export function getNodeInfo(process: NodeInfo): NodeInfo {
return {
version: process.version,
execPath: process.execPath,
};
}
export interface Args {
workingDirectory: string;
annotate: ReadonlySet<"error" | "warning">;
pyrightVersion: SemVer;
command: string;
args: readonly string[];
}
// https://github.com/microsoft/pyright/blob/c8a16aa148afea403d985a80bd87998b06135c93/packages/pyright-internal/src/pyright.ts#LL188C35-L188C84
// But also with --verifytypes, which supports JSON but this action doesn't do anything with it.
const flagsWithoutCommentingSupport = new Set([
"--verifytypes",
"--stats",
"--verbose",
"--createstub",
"--dependencies",
]);
// TODO: allow non-dashed forms to be passed as inputs. A long time ago, I
// went with dashed names as pyright was not fully consistent, and dashes were
// consistent with other GitHub actions. However, pyright has now gone the
// other way and settled on no dashes in flag names. So, it's probably clearer
// if this action supports the names without dashes.
export async function getArgs(execPath: string): Promise<Args> {
const pyrightInfo = await getPyrightInfo();
let pyrightPath: string | undefined;
let command: string;
switch (pyrightInfo.kind) {
case "npm":
pyrightPath = await downloadPyright(pyrightInfo);
command = execPath;
break;
case "path":
command = pyrightInfo.command;
break;
}
const pyrightVersion = new SemVer(pyrightInfo.version);
// https://github.com/microsoft/pyright/commit/ba18f421d1b57c433156cbc6934e0893abc130db
const useDashedFlags = pyrightVersion.compare("1.1.309") === -1;
const args = [];
if (pyrightPath) {
args.push(path.join(pyrightPath, "package", "index.js"));
}
// pyright-action options
const workingDirectory = core.getInput("working-directory");
// pyright flags
const createStub = core.getInput("create-stub");
if (createStub) {
args.push("--createstub", createStub);
}
const dependencies = core.getInput("dependencies");
if (dependencies) {
args.push("--dependencies", dependencies);
}
const ignoreExternal = core.getInput("ignore-external");
if (ignoreExternal) {
args.push("--ignoreexternal");
}
const level = core.getInput("level");
if (level) {
args.push("--level", level);
}
const project = core.getInput("project");
if (project) {
args.push("--project", project);
}
const pythonPlatform = core.getInput("python-platform");
if (pythonPlatform) {
args.push("--pythonplatform", pythonPlatform);
}
const pythonPath = core.getInput("python-path");
if (pythonPath) {
args.push("--pythonpath", pythonPath);
}
const pythonVersion = core.getInput("python-version");
if (pythonVersion) {
args.push("--pythonversion", pythonVersion);
}
const skipUnannotated = getBooleanInput("skip-unannotated", false);
if (skipUnannotated) {
args.push("--skipunannotated");
}
const stats = getBooleanInput("stats", false);
if (stats) {
args.push("--stats");
}
const typeshedPath = core.getInput("typeshed-path");
if (typeshedPath) {
args.push(useDashedFlags ? "--typeshed-path" : "--typeshedpath", typeshedPath);
}
const venvPath = core.getInput("venv-path");
if (venvPath) {
args.push(useDashedFlags ? "--venv-path" : "--venvpath", venvPath);
}
const verbose = getBooleanInput("verbose", false);
if (verbose) {
args.push("--lib");
}
const verifyTypes = core.getInput("verify-types");
if (verifyTypes) {
args.push("--verifytypes", verifyTypes);
}
const warnings = getBooleanInput("warnings", false);
if (warnings) {
args.push("--warnings");
}
// Deprecated flags
const lib = getBooleanInput("lib", false);
if (lib) {
args.push("--lib");
}
const extraArgs = core.getInput("extra-args");
if (extraArgs) {
for (const arg of parse(extraArgs)) {
if (typeof arg !== "string") {
// eslint-disable-next-line unicorn/prefer-type-error
throw new Error(`malformed extra-args: ${extraArgs}`);
}
args.push(arg);
}
}
let annotateInput = core.getInput("annotate").trim() || "all";
if (isAnnotateNone(annotateInput)) {
annotateInput = "";
} else if (isAnnotateAll(annotateInput)) {
annotateInput = "errors, warnings";
}
const split = annotateInput ? annotateInput.split(",") : [];
const annotate = new Set<"error" | "warning">();
for (let value of split) {
value = value.trim();
switch (value) {
case "errors":
annotate.add("error");
break;
case "warnings":
annotate.add("warning");
break;
default:
if (isAnnotateAll(value) || isAnnotateNone(value)) {
throw new Error(`invalid value ${JSON.stringify(value)} in comma-separated annotate`);
}
throw new Error(`invalid value ${JSON.stringify(value)} for annotate`);
}
}
const noComments = getBooleanInput("no-comments", false)
|| args.some((arg) => flagsWithoutCommentingSupport.has(arg));
if (noComments) {
annotate.clear();
}
return {
workingDirectory,
annotate,
pyrightVersion: pyrightInfo.version,
command,
args,
};
}
function isAnnotateNone(name: string): boolean {
return name === "none" || name.toUpperCase() === "FALSE";
}
function isAnnotateAll(name: string): boolean {
return name === "all" || name.toUpperCase() === "TRUE";
}
function getBooleanInput(name: string, defaultValue: boolean): boolean {
const input = core.getInput(name);
if (!input) {
return defaultValue;
}
return input.toUpperCase() === "TRUE";
}
const pyrightToolName = "pyright";
async function downloadPyright(info: PyrightInfoFromNpm): Promise<string> {
const version = info.version.format();
// Note: this only works because the pyright package doesn't have any
// dependencies. If this ever changes, we'll have to actually install it.
// eslint-disable-next-line unicorn/no-array-callback-reference, unicorn/no-array-method-this-argument
const found = tc.find(pyrightToolName, version);
if (found) {
return found;
}
const tarballPath = await tc.downloadTool(info.tarball);
const extractedPath = await tc.extractTar(tarballPath);
return await tc.cacheDir(extractedPath, pyrightToolName, version);
}
type PyrightInfo = PyrightInfoFromNpm | PyrightInfoFromPath;
interface PyrightInfoFromNpm {
kind: "npm";
version: SemVer;
tarball: string;
}
interface PyrightInfoFromPath {
kind: "path";
version: SemVer;
command: string;
}
function formatSemVerOrString(v: SemVer | string) {
if (typeof v === "string") {
return v;
}
return v.format();
}
function parsePyrightVersionFromStdout(stdout: string): SemVer {
const prefix = "pyright ";
for (let line of stdout.trim().split(/\r?\n/)) {
line = line.trimEnd();
if (line.startsWith(prefix)) {
try {
return new SemVer(line.slice(prefix.length));
} catch {
// Continue
}
}
}
throw new Error(`Failed to parse pyright version from ${JSON.stringify(stdout)}`);
}
async function getPyrightInfo(): Promise<PyrightInfo> {
const version = await getPyrightVersion();
if (version === "PATH") {
const command = which.sync("pyright");
let version!: SemVer;
for (let i = 0; i < 2; i++) {
try {
const versionOut = cp.execFileSync(command, ["--version"], { encoding: "utf8" });
version = parsePyrightVersionFromStdout(versionOut);
break;
} catch (e) {
if (i === 1) {
throw e;
}
}
}
return {
kind: "path",
version,
command: command,
};
}
const client = new httpClient.HttpClient();
const versionString = formatSemVerOrString(version);
const url = `https://registry.npmjs.org/pyright/${versionString}`;
const resp = await client.get(url);
const body = await resp.readBody();
if (resp.message.statusCode !== httpClient.HttpCodes.OK) {
throw new Error(`Failed to download metadata for pyright ${versionString} from ${url} -- ${body}`);
}
const parsed = parseNpmRegistryResponse(JSON.parse(body));
return {
kind: "npm",
version: new SemVer(parsed.version),
tarball: parsed.dist.tarball,
};
}
async function getPyrightVersion(): Promise<SemVer | "PATH" | "latest"> {
const versionSpec = core.getInput("version");
if (versionSpec) {
if (versionSpec.toUpperCase() === "PATH") {
return "PATH";
}
if (versionSpec === "latest") {
return "latest";
}
return new SemVer(versionSpec);
}
const pylanceVersion = core.getInput("pylance-version");
if (pylanceVersion) {
if (pylanceVersion !== "latest-release" && pylanceVersion !== "latest-prerelease") {
new SemVer(pylanceVersion); // validate version string
}
return await getPylancePyrightVersion(pylanceVersion);
}
return "latest";
}
async function getPylancePyrightVersion(pylanceVersion: string): Promise<SemVer> {
const client = new httpClient.HttpClient();
const url = `https://raw.githubusercontent.com/microsoft/pylance-release/main/releases/${pylanceVersion}.json`;
const resp = await client.get(url);
const body = await resp.readBody();
if (resp.message.statusCode !== httpClient.HttpCodes.OK) {
throw new Error(`Failed to download release metadata for Pylance ${pylanceVersion} from ${url} -- ${body}`);
}
const buildMetadata = parsePylanceBuildMetadata(JSON.parse(body));
const pyrightVersion = buildMetadata.pyrightVersion;
core.info(`Pylance ${pylanceVersion} uses pyright ${pyrightVersion}`);
return new SemVer(pyrightVersion);
}