-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtype.ts
More file actions
62 lines (52 loc) · 1.53 KB
/
type.ts
File metadata and controls
62 lines (52 loc) · 1.53 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
/**
* @fileoverview TypeScript type coverage utilities.
*/
import process from 'node:process'
import { spawn } from '../spawn'
import type { GetTypeCoverageOptions, TypeCoverageResult } from './types'
/**
* Get TypeScript type coverage metrics.
*
* @throws {Error} When type-coverage command fails (if generateIfMissing is false).
*/
export async function getTypeCoverage(
options?: GetTypeCoverageOptions | undefined,
): Promise<TypeCoverageResult | null> {
const opts = {
__proto__: null,
cwd: process.cwd(),
generateIfMissing: false,
...options,
} as GetTypeCoverageOptions
const { cwd, generateIfMissing } = opts
if (!cwd) {
throw new Error('Working directory is required.')
}
try {
// Run type-coverage to get metrics.
const result = await spawn('type-coverage', ['--detail'], {
cwd,
stdio: ['ignore', 'pipe', 'pipe'],
})
// Parse output: "1234 / 5678 48.92%"
const outputText = result.stdout ? result.stdout.toString() : ''
const match = /(\d+) \/ (\d+) ([\d.]+)%/.exec(outputText)
if (!match || !match[1] || !match[2] || !match[3]) {
return null
}
return {
covered: Number.parseInt(match[1], 10),
percent: match[3],
total: Number.parseInt(match[2], 10),
}
} catch (e) {
if (generateIfMissing) {
throw new Error(
'Unable to generate type coverage. Ensure type-coverage is installed.',
{ cause: e },
)
}
// If not generating, return null when type-coverage isn't available.
return null
}
}