This repository has been archived by the owner on Feb 18, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 13
/
develop.ts
412 lines (381 loc) · 14 KB
/
develop.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
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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
import fs = require("fs");
import yargs = require("yargs");
import headerParser = require("@definitelytyped/header-parser");
import path = require("path");
import cp = require("child_process");
import {
dtsCritic,
dtToNpmName,
getNpmInfo,
parseExportErrorKind,
CriticError,
ExportErrorKind,
Mode,
checkSource,
findDtsName,
CheckOptions,
parseMode} from "./index";
const sourcesDir = "sources";
const downloadsPath = path.join(sourcesDir, "dts-critic-internal/downloads.json");
const isNpmPath = path.join(sourcesDir, "dts-critic-internal/npm.json");
function getPackageDownloads(dtName: string): number {
const npmName = dtToNpmName(dtName);
const url = `https://api.npmjs.org/downloads/point/last-month/${npmName}`;
const result = JSON.parse(
cp.execFileSync(
"curl",
["--silent", "-L", url],
{ encoding: "utf8" })) as { downloads?: number };
return result.downloads || 0;
}
interface DownloadsJson { [key: string]: number | undefined }
function getAllPackageDownloads(dtPath: string): DownloadsJson {
if (fs.existsSync(downloadsPath)) {
return JSON.parse(fs.readFileSync(downloadsPath, { encoding: "utf8" })) as DownloadsJson;
}
initDir(path.dirname(downloadsPath));
const downloads: DownloadsJson = {};
const dtTypesPath = getDtTypesPath(dtPath);
for (const item of fs.readdirSync(dtTypesPath)) {
const d = getPackageDownloads(item);
downloads[item] = d;
}
fs.writeFileSync(downloadsPath, JSON.stringify(downloads), { encoding: "utf8" });
return downloads;
}
function initDir(path: string): void {
if (!fs.existsSync(path)) {
fs.mkdirSync(path);
}
}
function getDtTypesPath(dtBasePath: string): string {
return path.join(dtBasePath, "types");
}
function compareDownloads(downloads: DownloadsJson, package1: string, package2: string): number {
const count1 = downloads[package1] || 0;
const count2 = downloads[package2] || 0;
return count1 - count2;
}
interface IsNpmJson { [key: string]: boolean | undefined }
function getAllIsNpm(dtPath: string): IsNpmJson {
if (fs.existsSync(isNpmPath)) {
return JSON.parse(fs.readFileSync(isNpmPath, { encoding: "utf8" })) as IsNpmJson;
}
initDir(path.dirname(isNpmPath));
const isNpm: IsNpmJson = {};
const dtTypesPath = getDtTypesPath(dtPath);
for (const item of fs.readdirSync(dtTypesPath)) {
isNpm[item] = getNpmInfo(item).isNpm;
}
fs.writeFileSync(isNpmPath, JSON.stringify(isNpm), { encoding: "utf8" });
return isNpm;
}
function getPopularNpmPackages(count: number, dtPath: string): string[] {
const dtPackages = getDtNpmPackages(dtPath);
const downloads = getAllPackageDownloads(dtPath);
dtPackages.sort((a, b) => compareDownloads(downloads, a, b));
return dtPackages.slice(dtPackages.length - count);
}
function getUnpopularNpmPackages(count: number, dtPath: string): string[] {
const dtPackages = getDtNpmPackages(dtPath);
const downloads = getAllPackageDownloads(dtPath);
dtPackages.sort((a, b) => compareDownloads(downloads, a, b));
return dtPackages.slice(0, count);
}
function getDtNpmPackages(dtPath: string): string[] {
const dtPackages = fs.readdirSync(getDtTypesPath(dtPath));
const isNpmJson = getAllIsNpm(dtPath);
return dtPackages.filter(pkg => isNpmPackage(pkg, /* header */ undefined, isNpmJson));
}
function getNonNpm(args: { dtPath: string }): void {
const nonNpm: string[] = [];
const dtTypesPath = getDtTypesPath(args.dtPath);
const isNpmJson = getAllIsNpm(args.dtPath);
for (const item of fs.readdirSync(dtTypesPath)) {
const entry = path.join(dtTypesPath, item);
const dts = fs.readFileSync(entry + "/index.d.ts", "utf8");
let header;
try {
header = headerParser.parseHeaderOrFail(dts);
}
catch (e) {
header = undefined;
}
if (!isNpmPackage(item, header, isNpmJson)) {
nonNpm.push(item);
}
}
console.log(`List of non-npm packages on DT:\n${nonNpm.map(name => `DT name: ${name}\n`).join("")}`);
}
interface CommonArgs {
dtPath: string,
mode: string,
enableError: string[] | undefined,
debug: boolean,
json: boolean,
}
function checkAll(args: CommonArgs): void {
const dtPackages = fs.readdirSync(getDtTypesPath(args.dtPath));
checkPackages({ packages: dtPackages, ...args });
}
function checkPopular(args: { count: number } & CommonArgs): void {
checkPackages({ packages: getPopularNpmPackages(args.count, args.dtPath), ...args });
}
function checkUnpopular(args: { count: number } & CommonArgs): void {
checkPackages({ packages: getUnpopularNpmPackages(args.count, args.dtPath), ...args });
}
function checkPackages(args: { packages: string[] } & CommonArgs): void {
const results = args.packages.map(pkg => doCheck({ package: pkg, ...args }));
printResults(results, args.json);
}
function checkPackage(args: { package: string } & CommonArgs): void {
printResults([doCheck(args)], args.json);
}
function doCheck(args: { package: string, dtPath: string, mode: string, enableError: string[] | undefined, debug: boolean }): Result {
const dtPackage = args.package;
const opts = getOptions(args.mode, args.enableError || []);
try {
const dtsPath = path.join(getDtTypesPath(args.dtPath), dtPackage, "index.d.ts");
const errors = dtsCritic(dtsPath, /* sourcePath */ undefined, opts, args.debug);
return { package: args.package, output: errors };
}
catch (e) {
return { package: args.package, output: e.toString() };
}
}
function getOptions(modeArg: string, enabledErrors: string[]): CheckOptions {
const mode = parseMode(modeArg);
if (!mode) {
throw new Error(`Could not find mode named '${modeArg}'.`);
}
switch (mode) {
case Mode.NameOnly:
return { mode };
case Mode.Code:
const errors = getEnabledErrors(enabledErrors);
return { mode, errors };
}
}
function getEnabledErrors(errorNames: string[]): Map<ExportErrorKind, boolean> {
const errors: ExportErrorKind[] = [];
for (const name of errorNames) {
const error = parseExportErrorKind(name);
if (error === undefined) {
throw new Error(`Could not find error named '${name}'.`);
}
errors.push(error);
}
return new Map(errors.map(err => [err, true]));
}
function checkFile(args: { jsFile: string, dtsFile: string, debug: boolean }): void {
console.log(`\tChecking JS file ${args.jsFile} and declaration file ${args.dtsFile}`);
try {
const errors = checkSource(findDtsName(args.dtsFile), args.dtsFile, args.jsFile, new Map(), args.debug);
console.log(formatErrors(errors));
}
catch (e) {
console.log(e);
}
}
interface Result {
package: string,
output: CriticError[] | string,
}
function printResults(results: Result[], json: boolean): void {
if (json) {
console.log(JSON.stringify(results));
return;
}
for (const result of results) {
console.log(`\tChecking package ${result.package} ...`);
if (typeof result.output === "string") {
console.log(`Exception:\n${result.output}`);
}
else {
console.log(formatErrors(result.output));
}
}
}
function formatErrors(errors: CriticError[]): string {
const lines: string[] = [];
for (const error of errors) {
lines.push("Error: " + error.message);
}
if (errors.length === 0) {
lines.push("No errors found! :)");
}
return lines.join("\n");
}
function isNpmPackage(name: string, header?: headerParser.Header, isNpmJson: IsNpmJson = {}): boolean {
if (header && header.nonNpm) return false;
const isNpm = isNpmJson[name];
if (isNpm !== undefined) {
return isNpm;
}
return getNpmInfo(name).isNpm;
}
function main() {
// eslint-disable-next-line no-unused-expressions
yargs
.usage("$0 <command>")
.command("check-all", "Check source and declaration of all DT packages that are on NPM.", {
dtPath: {
type: "string",
default: "../DefinitelyTyped",
describe: "Path of DT repository cloned locally.",
},
mode: {
type: "string",
required: true,
choices: [Mode.NameOnly, Mode.Code],
describe: "Mode that defines which group of checks will be made.",
},
enableError: {
type: "array",
string: true,
describe: "Enable checking for a specific export error."
},
debug: {
type: "boolean",
default: false,
describe: "Turn debug logging on.",
},
json: {
type: "boolean",
default: false,
describe: "Format output result as json."
},
}, checkAll)
.command("check-popular", "Check source and declaration of most popular DT packages that are on NPM.", {
count: {
alias: "c",
type: "number",
required: true,
describe: "Number of packages to be checked.",
},
dtPath: {
type: "string",
default: "../DefinitelyTyped",
describe: "Path of DT repository cloned locally.",
},
mode: {
type: "string",
required: true,
choices: [Mode.NameOnly, Mode.Code],
describe: "Mode that defines which group of checks will be made.",
},
enableError: {
type: "array",
string: true,
describe: "Enable checking for a specific export error."
},
debug: {
type: "boolean",
default: false,
describe: "Turn debug logging on.",
},
json: {
type: "boolean",
default: false,
describe: "Format output result as json."
},
}, checkPopular)
.command("check-unpopular", "Check source and declaration of least popular DT packages that are on NPM.", {
count: {
alias: "c",
type: "number",
required: true,
describe: "Number of packages to be checked.",
},
dtPath: {
type: "string",
default: "../DefinitelyTyped",
describe: "Path of DT repository cloned locally.",
},
mode: {
type: "string",
required: true,
choices: [Mode.NameOnly, Mode.Code],
describe: "Mode that defines which group of checks will be made.",
},
enableError: {
type: "array",
string: true,
describe: "Enable checking for a specific export error."
},
debug: {
type: "boolean",
default: false,
describe: "Turn debug logging on.",
},
json: {
type: "boolean",
default: false,
describe: "Format output result as json."
},
}, checkUnpopular)
.command("check-package", "Check source and declaration of a DT package.", {
package: {
alias: "p",
type: "string",
required: true,
describe: "DT name of a package."
},
dtPath: {
type: "string",
default: "../DefinitelyTyped",
describe: "Path of DT repository cloned locally.",
},
mode: {
type: "string",
required: true,
choices: [Mode.NameOnly, Mode.Code],
describe: "Mode that defines which group of checks will be made.",
},
enableError: {
type: "array",
string: true,
describe: "Enable checking for a specific export error."
},
debug: {
type: "boolean",
default: false,
describe: "Turn debug logging on.",
},
json: {
type: "boolean",
default: false,
describe: "Format output result as json."
},
}, checkPackage)
.command("check-file", "Check a JavaScript file and its matching declaration file.", {
jsFile: {
alias: "j",
type: "string",
required: true,
describe: "Path of JavaScript file.",
},
dtsFile: {
alias: "d",
type: "string",
required: true,
describe: "Path of declaration file.",
},
debug: {
type: "boolean",
default: false,
describe: "Turn debug logging on.",
},
}, checkFile)
.command("get-non-npm", "Get list of DT packages whose source package is not on NPM", {
dtPath: {
type: "string",
default: "../DefinitelyTyped",
describe: "Path of DT repository cloned locally.",
},
}, getNonNpm)
.demandCommand(1)
.help()
.argv;
}
main();