1 | import { Spec } from '@hayspec/spec';
|
2 | import * as glob from 'fast-glob';
|
3 |
|
4 |
|
5 |
|
6 |
|
7 | export interface RunnerResult {
|
8 | file: string;
|
9 | spec: Spec;
|
10 | }
|
11 |
|
12 |
|
13 |
|
14 |
|
15 | export interface RunnerOptions {
|
16 | cwd?: string;
|
17 | deep?: number;
|
18 | dot?: boolean;
|
19 | }
|
20 |
|
21 | |
22 |
|
23 |
|
24 | export class Runner {
|
25 | protected options: RunnerOptions;
|
26 | protected onlyEnabled: boolean = false;
|
27 | public results: RunnerResult[] = [];
|
28 |
|
29 | |
30 |
|
31 |
|
32 | public constructor(options?: RunnerOptions) {
|
33 | this.options = {
|
34 | cwd: process.cwd(),
|
35 | deep: Infinity,
|
36 | dot: false,
|
37 | ...options,
|
38 | };
|
39 | }
|
40 |
|
41 | |
42 |
|
43 |
|
44 | public async require(...patterns: string[]) {
|
45 | const options = {
|
46 | absolute: true,
|
47 | ...this.options,
|
48 | };
|
49 | const files = await glob(patterns, options) as string[];
|
50 |
|
51 | files.forEach((file) => {
|
52 | const spec = this.loadSpec(file);
|
53 |
|
54 | if (!spec) {
|
55 | return;
|
56 | }
|
57 | else if (spec.spec.hasOnly() && !this.onlyEnabled) {
|
58 | this.onlyEnabled = true;
|
59 | this.results = [];
|
60 | }
|
61 |
|
62 | if (this.onlyEnabled && spec.spec.hasOnly()) {
|
63 | this.results.push(spec);
|
64 | }
|
65 | else if (!this.onlyEnabled) {
|
66 | this.results.push(spec);
|
67 | }
|
68 |
|
69 | });
|
70 | }
|
71 |
|
72 | |
73 |
|
74 |
|
75 | public clear () {
|
76 | this.results = [];
|
77 | return this;
|
78 | }
|
79 |
|
80 | |
81 |
|
82 |
|
83 |
|
84 |
|
85 | protected loadSpec(file: string) {
|
86 | const spec = require(file);
|
87 |
|
88 | if (spec instanceof Spec) {
|
89 | return { file, spec };
|
90 | } else if (spec.default instanceof Spec) {
|
91 | return { file, spec: spec.default };
|
92 | }
|
93 | else {
|
94 | return null;
|
95 | }
|
96 | }
|
97 |
|
98 | }
|