-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcodeview.ts
680 lines (635 loc) · 17.7 KB
/
codeview.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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
import {
blue,
bold,
Command,
green,
red,
relative,
resolve,
serve as serveStd,
Server,
Spinner,
Toggle,
wait,
Webview,
yellow,
} from "./deps.ts";
import { loadingTemplate } from "./loader.ts";
const codeview = new Command<void>()
.version("0.2.1")
.name("codeview")
.description("Deno Coverage Webview Reporter.")
.arguments<[testFiles?: string, watchFiles?: string]>(
"[test-files] [watch-files]",
)
// Codeview options
.option<{ watch?: boolean }>(
"-w, --watch",
"Enable watch mode.",
)
.option<{ excludeWatch?: Array<string> }>(
"-W, --exclude-watch <files:string[]>",
"Exclude files from watch.",
{ value: (files: Array<string>) => files.map((file) => resolve(file)) },
)
.option<{ tmp: string }>(
"--tmp",
"Tmp directory for generated coverage files.",
{
default: resolve(".coverage"),
value: (tmp) => resolve(tmp),
},
)
.option<{ keep?: boolean }>(
"-k, --keep",
"Keep tmp directory on exit.",
)
.option<{ host: string }>(
"-H, --host, --hostname <hostname>",
"The hostname for the web-server.",
{ default: "0.0.0.0" },
)
.option<{ port: number }>(
"-p, --port <port:number>",
"The port for the web-server.",
{ default: 1717 },
)
.option<{ spinner: boolean }>(
"--no-spinner",
"Disable spinner and log output directly to stdout.",
)
.option<{ debounce: number }>(
"-d, --debounce <debounce:number>",
"Delays the file change event in watch mode.",
{ default: 200 },
)
.option<{ maximize?: boolean }>(
"-M, --maximize",
"Start web-view with a maximized window.",
)
// Deno options
.option<{ allowAll?: boolean }>(
"-A, --allow-all",
"Allow all permissions",
)
.option<{ allowEnv?: boolean }>(
"-A, --allow-env",
"Allow environment access",
)
.option<{ allowHrtime?: boolean }>(
"--allow-hrtime",
"Allow high resolution time measurement",
)
.option<{ allowNet?: boolean | string }>(
"--allow-net [domains:string]",
"Allow network access",
)
.option<{ allowNone?: boolean }>(
"--allow-none",
"Don't return error code if no test files are found",
)
.option<{ allowPlugin?: boolean }>(
"--allow-plugin",
"Allow loading plugins.",
)
.option<{ allowRead?: boolean | string }>(
"--allow-read [files:string]",
"Allow file system read access.",
)
.option<{ allowRun?: boolean }>(
"--allow-run",
"Allow running subprocesses.",
)
.option<{ allowWrite?: boolean | string }>(
"--allow-write [files:string]",
"Allow file system write access.",
)
.option<{ cachedOnly?: boolean }>(
"--cached-only",
"Require that remote dependencies are already cached.",
)
.option<{ cert?: string }>(
"--cert <file:string>",
"Load certificate authority from PEM encoded file.",
)
.option<{ config?: string }>(
"-c, --config <file:string>",
"Load tsconfig.json configuration file.",
)
.option<{ failFast?: boolean }>(
"--fail-fast",
"Stop on first error.",
)
.option<{ filter?: string }>(
"--filter <filter:string>",
"Run tests with this string or pattern in the test name.",
)
.option<{ importMap?: string }>(
"--import-map <file:string>",
"Load import map file",
)
.option<{ location?: string }>(
"--location <href:string>",
"Value of 'globalThis.location' used by some web APIs.",
)
.option<{ lock?: string }>(
"--lock <file>",
"Check the specified lock file.",
)
.option<{ logLevel?: "debug" | "info" }>(
"-L, --log-level <log-level:string>",
"Set log level [possible values: debug, info]",
)
.option<{ check?: boolean }>(
"--no-check",
"Skip type checking modules.",
)
.option<{ remote?: boolean }>(
"--no-remote",
"Do not resolve remote modules.",
)
.option<{ quiet?: boolean }>(
"-q, --quiet",
"Suppress diagnostic output.",
)
.option<{ reload?: boolean | string }>(
"-r, --reload [cache-blocklist:string]",
"Reload source code cache (recompile TypeScript).",
)
.option<{ seed?: number }>(
"--seed <number:number>",
"Seed Math.random().",
)
.option<{ unstable?: boolean }>(
"--unstable",
"Enable unstable features and APIs.",
)
.option<{ v8Flags?: string }>(
"--v8-flags <v8-flags:string>",
"Set V8 command line options (for help: --v8-flags=--help).",
)
.option<{ exclude?: string }>(
"--exclude <regex:string>",
"Exclude source files from the report [default: test\.(js|mjs|ts|jsx|tsx)$]",
)
.option<{ ignore?: string }>(
"--ignore <ignore:string>",
"Ignore coverage files.",
)
.option<{ include?: string }>(
"--include <regex:string>",
"Include source files in the report [default: ^file:]",
)
.action(async (
options,
testFiles = ".",
watchFiles: string = testFiles,
): Promise<void> => {
if (options.logLevel === "debug") {
options.spinner = false;
}
let infoMessage = "Initializing codeview....";
const waitingMessage = "Waiting for file system changes...";
const url = `http://${options.host}:${options.port}`;
const spinner: Spinner | null = options.spinner
? wait(infoMessage).start()
: null;
const sig = Deno.signals.interrupt();
const processes: Set<Deno.Process | Deno.File> = new Set();
let webview: Webview | null = null;
let server: Server | null = null;
let cleanConfirmed = false;
let hasExitCalled = false;
await clean(options.tmp, true).catch((error) => exit(error, false));
const loadingMessageInterval = setInterval(
() => {
webview?.eval(`window.updateLoadingMessage("${infoMessage}")`);
},
100,
);
Promise.any([
sig,
serve(),
runWebview(),
options.watch ? watch() : new Promise(() => {}),
]).then(() => exit()).catch(exit);
welcome();
await generate()
.then(() => {
clearInterval(loadingMessageInterval);
let message = "Successfully generated coverage report!";
if (options.watch) {
message += " " + waitingMessage;
}
logInfo(message);
webview?.eval(`window.location.href = "${url}"`);
})
.catch((error) => {
if (!options.watch) {
exit(error);
return;
}
logError(error);
logInfo(`Failed to generated coverage report! ${waitingMessage}`);
});
async function exit(error?: Error, doClean = true): Promise<void> {
if (hasExitCalled) {
return;
}
hasExitCalled = true;
debug("exit called");
if (error) {
logError(error);
}
if (doClean && cleanConfirmed && !options.keep) {
await clean(options.tmp, false).catch((error) => exit(error, false));
}
closeAllProcesses();
clearInterval(loadingMessageInterval);
sig.dispose();
spinner?.stop();
webview?.exit();
server?.close();
Deno.exit(0);
}
async function watch() {
if (!options.watch) {
return;
}
const watcher: AsyncIterableIterator<Deno.FsEvent> = Deno.watchFs(
watchFiles,
{
recursive: true,
},
);
const update = debounce(async (changedFile?: string) => {
changedFile && log(
"%s %s %s",
blue(`[Info]`),
bold(relative(Deno.cwd(), changedFile)),
blue("changed. Restarting..."),
);
await generate();
webview?.eval("window.location.reload()");
logInfo(waitingMessage);
}, options.debounce);
for await (const event of watcher) {
if (
!event.paths.some((path) =>
path.startsWith(options.tmp) ||
options.excludeWatch?.some((exclude) => path.startsWith(exclude))
) && event.paths[0][event.paths[0].length - 1] !== "~"
) {
try {
await update(event.paths[0]);
} catch (error) {
logError(error);
}
}
}
}
const MEDIA_TYPES: Record<string, string> = {
".css": "text/css",
".gif": "image/gif",
".gz": "application/gzip",
".htm": "text/html",
".html": "text/html",
".jpe": "image/jpeg",
".jpeg": "image/jpeg",
".jpg": "image/jpeg",
".js": "application/javascript",
".json": "application/json",
".jsx": "text/jsx",
".map": "application/json",
".md": "text/markdown",
".mjs": "application/javascript",
".png": "image/png",
".svg": "image/svg+xml",
".ts": "text/typescript",
".tsx": "text/tsx",
".txt": "text/plain",
".wasm": "application/wasm",
};
function getContentType(path: string): string | undefined {
const parts = path.split(".");
parts.shift();
const ext = parts[parts.length - 1];
return ext && MEDIA_TYPES[ext];
}
async function serve(): Promise<void> {
if (server) {
return;
}
debug("Starting server at: %s:%s", options.host, options.port);
server = serveStd({
hostname: options.host,
port: options.port,
});
for await (const req of server) {
const fileName = req.url[req.url.length - 1] === "/"
? req.url + "index.html"
: req.url;
const path = `${options.tmp}/html${fileName}`;
try {
const [file, fileInfo] = await Promise.all([
Deno.open(path),
Deno.stat(path),
]);
const headers = new Headers();
headers.set("content-length", fileInfo.size.toString());
const contentType = getContentType(path);
if (contentType) {
headers.set("content-type", contentType);
}
req.done.then(() => file.close());
debug("%s %s %s", blue("GET"), green("200"), path);
req.respond({
status: 200,
body: file,
headers,
});
} catch (error) {
if (error instanceof Deno.errors.NotFound) {
debug("%s %s %s", blue("GET"), red("404"), path);
req.respond({ status: 404, body: "Not Found" });
} else {
debug("%s %s %s", blue("GET"), red("500"), path);
logError(error);
req.respond({ status: 500, body: "Internal Server Error" });
}
}
}
}
function runWebview(): Promise<void> {
webview = new Webview({
url: `data:text/html,${
encodeURIComponent(
loadingTemplate.replace("{{subtitle}}", infoMessage),
)
}`,
frameless: false,
resizable: true,
debug: options.logLevel === "debug",
title: "Coverage Report",
});
const promise = webview.run();
setTimeout(() => webview?.setMaximized(!!options.maximize), 200);
return promise;
}
async function generate() {
closeAllProcesses();
try {
// remove old coverage data or old data will be shown after re-build
await clean(`${options.tmp}/cov`, false);
await test();
await coverage();
await html();
} finally {
closeAllProcesses();
}
}
function closeAllProcesses() {
processes.forEach((process) => {
try {
process.close();
} catch (_) {
// ignore error
}
try {
if (process instanceof Deno.Process) {
process.kill(Deno.Signal.SIGKILL);
}
} catch (_) {
// ignore error
}
});
processes.clear();
}
function welcome() {
log();
log(
blue(" Web server is running at: %s 🚀"),
green(url),
);
log(
blue(" Watch mode: %s ⌚"),
options.watch ? green("enabled") : red("disabled"),
);
log();
}
async function clean(path: string, confirm: boolean): Promise<void> {
if (
!await Deno.lstat(path).then(() => true).catch(() => false)
) {
cleanConfirmed = true;
return;
}
if (confirm) {
log(
"%s tmp directory %s already exists!",
yellow(`[Warning]`),
bold(path),
);
log(
"%s Existing files in this directory will be deleted!",
yellow(`[Warning]`),
);
spinner?.stop();
const abort = !await Toggle.prompt({
message: "Continue and delete existing tmp directory?",
default: false,
indent: "",
});
if (abort) {
Deno.exit(0);
}
cleanConfirmed = true;
}
if (cleanConfirmed) {
logInfo("Deleting tmp directory...");
await run({
cmd: ["rm", "-rf", path],
});
} else {
debug("Prevent deleting tmp directory!");
}
}
async function test() {
logInfo("Running tests...");
const testOptions: Array<keyof typeof options> = [
"allowAll",
"allowEnv",
"allowHrtime",
"allowNet",
"allowNone",
"allowPlugin",
"allowRead",
"allowRun",
"allowWrite",
"cachedOnly",
"cert",
"config",
"failFast",
"filter",
"importMap",
"location",
"lock",
"logLevel",
"quiet",
"reload",
"v8Flags",
];
const negatableOptions: Array<keyof typeof options> = [
"check",
"remote",
];
await run({
cmd: [
"deno",
"test",
`--coverage=${options.tmp}/cov`,
"--unstable",
...testOptions
.filter((name: keyof typeof options) =>
typeof options[name] !== "undefined"
)
.map((name: keyof typeof options) =>
options[name] === true
? `--${paramCase(name)}`
: `--${paramCase(name)}=${String(options[name])}`
),
...negatableOptions
.filter((name: keyof typeof options) => options[name] === false)
.map((name: keyof typeof options) => `--no-${name}`),
...(testFiles ? [testFiles] : []),
],
});
}
async function coverage() {
logInfo("Generating lcov coverage report...");
await run({
cmd: [
"deno",
"coverage",
"--unstable",
`${options.tmp}/cov`,
"--lcov",
...(options.quiet ? ["--quiet"] : []),
...(options.logLevel ? [`--log-level=${options.logLevel}`] : []),
...(options.exclude ? [`--exclude=${options.exclude}`] : []),
...(options.include ? [`--include=${options.include}`] : []),
],
process: async (process) => {
if (process.stdout) {
debug("Reading cov.lcov...");
const lcov: Deno.File = await Deno.open(
`${options.tmp}/cov.lcov`,
{
create: true,
write: true,
},
);
processes.add(lcov);
await Deno.copy(process.stdout, lcov);
}
},
});
}
async function html() {
logInfo("Generating html report...");
await run({
cmd: [
"genhtml",
"-o",
`${options.tmp}/html`,
`${options.tmp}/cov.lcov`,
],
});
}
type RunOptions = Deno.RunOptions & {
process?: (process: Deno.Process) => Promise<void>;
};
async function run(opts: RunOptions) {
debug(blue("$ %s"), opts.cmd.join(" "));
const process = Deno.run({
stdout: !opts.process && options.logLevel === "debug"
? "inherit"
: "piped",
stderr: options.logLevel ? "inherit" : "piped",
...opts,
});
processes.add(process);
await opts.process?.(process);
const [status, stdOutput] = await Promise.all([
process.status(),
(!opts.process && options.logLevel === "debug"
? Promise.resolve()
: process.output()) as Promise<Uint8Array | void>,
]);
if (!status.success) {
debug(yellow("Failed: %s"), opts.cmd.join(" "), status);
if (status.signal) {
// don't throw an error on signal!
return;
}
let output = stdOutput ? new TextDecoder().decode(stdOutput) : "";
if (!options.logLevel) {
output += "\n\n" + new TextDecoder().decode(
await process.stderrOutput(),
);
}
throw new Error(output || "Command failed.");
}
debug(green("Done: %s"), opts.cmd.join(" "));
}
function logInfo(message: string) {
infoMessage = message;
if (spinner && options.spinner) {
spinner.text = message;
} else {
log(message);
}
webview?.eval(`window.updateLoadingMessage("${message}")`);
}
function log(...args: Array<unknown>) {
spinner?.stop();
console.log(...args);
spinner?.start();
}
function debug(...args: Array<unknown>) {
if (options.logLevel) {
log(...args);
}
}
function logError(...args: Array<unknown>) {
spinner?.stop();
console.error(...args);
spinner?.start();
}
// deno-lint-ignore no-explicit-any
function debounce<T extends (...args: Array<any>) => void | Promise<void>>(
func: T,
wait: number,
): T {
let timeout: number | null;
return ((...args: Array<unknown>) => {
if (timeout !== null) {
clearTimeout(timeout);
}
timeout = setTimeout(() => {
timeout = null;
func(...args);
}, wait);
// deno-lint-ignore no-explicit-any
}) as any;
}
});
if (import.meta.main) {
await codeview.parse();
}
function paramCase(str: string): string {
return str.replace(
/([a-z][A-Z])/g,
(g) => g[0] + "-" + g[1].toLowerCase(),
);
}