• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

rokucommunity / brighterscript / #13286

21 Nov 2024 03:03PM UTC coverage: 88.232% (-0.9%) from 89.088%
#13286

push

TwitchBronBron
0.68.0

6754 of 8102 branches covered (83.36%)

Branch coverage included in aggregate %.

8983 of 9734 relevant lines covered (92.28%)

1868.45 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

71.02
/src/ProgramBuilder.ts
1
import * as debounce from 'debounce-promise';
1✔
2
import * as path from 'path';
1✔
3
import { rokuDeploy } from 'roku-deploy';
1✔
4
import type { LogLevel as RokuDeployLogLevel } from 'roku-deploy/dist/Logger';
5
import type { BsConfig, FinalizedBsConfig } from './BsConfig';
6
import type { BscFile, BsDiagnostic, FileObj, FileResolver } from './interfaces';
7
import { Program } from './Program';
1✔
8
import { standardizePath as s, util } from './util';
1✔
9
import { Watcher } from './Watcher';
1✔
10
import { DiagnosticSeverity } from 'vscode-languageserver';
1✔
11
import { LogLevel, createLogger } from './logging';
1✔
12
import PluginInterface from './PluginInterface';
1✔
13
import * as diagnosticUtils from './diagnosticUtils';
1✔
14
import * as fsExtra from 'fs-extra';
1✔
15
import * as requireRelative from 'require-relative';
1✔
16
import { Throttler } from './Throttler';
1✔
17
import { URI } from 'vscode-uri';
1✔
18

19
/**
20
 * A runner class that handles
21
 */
22
export class ProgramBuilder {
1✔
23

24
    public constructor() {
25
        //add the default file resolver (used to load source file contents).
26
        this.addFileResolver((filePath) => {
59✔
27
            return fsExtra.readFile(filePath).then((value) => {
23✔
28
                return value.toString();
23✔
29
            });
30
        });
31
    }
32
    /**
33
     * Determines whether the console should be cleared after a run (true for cli, false for languageserver)
34
     */
35
    public allowConsoleClearing = true;
59✔
36

37
    public options: FinalizedBsConfig = util.normalizeConfig({});
59✔
38
    private isRunning = false;
59✔
39
    private watcher: Watcher | undefined;
40
    public program: Program | undefined;
41
    public logger = createLogger();
59✔
42
    public plugins: PluginInterface = new PluginInterface([], { logger: this.logger });
59✔
43
    private fileResolvers = [] as FileResolver[];
59✔
44

45
    public addFileResolver(fileResolver: FileResolver) {
46
        this.fileResolvers.push(fileResolver);
94✔
47
    }
48

49
    /**
50
     * Get the contents of the specified file as a string.
51
     * This walks backwards through the file resolvers until we get a value.
52
     * This allow the language server to provide file contents directly from memory.
53
     */
54
    public async getFileContents(srcPath: string) {
55
        srcPath = s`${srcPath}`;
23✔
56
        let reversedResolvers = [...this.fileResolvers].reverse();
23✔
57
        for (let fileResolver of reversedResolvers) {
23✔
58
            let result = await fileResolver(srcPath);
43✔
59
            if (typeof result === 'string') {
43✔
60
                return result;
23✔
61
            }
62
        }
63
        throw new Error(`Could not load file "${srcPath}"`);
×
64
    }
65

66
    /**
67
     * A list of diagnostics that are always added to the `getDiagnostics()` call.
68
     */
69
    private staticDiagnostics = [] as BsDiagnostic[];
59✔
70

71
    public addDiagnostic(srcPath: string, diagnostic: Partial<BsDiagnostic>) {
72
        if (!this.program) {
×
73
            throw new Error('Cannot call `ProgramBuilder.addDiagnostic` before `ProgramBuilder.run()`');
×
74
        }
75
        let file: BscFile | undefined = this.program.getFile(srcPath);
×
76
        if (!file) {
×
77
            file = {
×
78
                pkgPath: this.program.getPkgPath(srcPath),
79
                pathAbsolute: srcPath, //keep this for backwards-compatibility. TODO remove in v1
80
                srcPath: srcPath,
81
                getDiagnostics: () => {
82
                    return [<any>diagnostic];
×
83
                }
84
            } as BscFile;
85
        }
86
        diagnostic.file = file;
×
87
        this.staticDiagnostics.push(<any>diagnostic);
×
88
    }
89

90
    public getDiagnostics() {
91
        return [
105✔
92
            ...this.staticDiagnostics,
93
            ...(this.program?.getDiagnostics() ?? [])
630!
94
        ];
95
    }
96

97
    public async run(options: BsConfig) {
98
        if (options?.logLevel) {
44✔
99
            this.logger.logLevel = options.logLevel;
2✔
100
        }
101

102
        if (this.isRunning) {
44!
103
            throw new Error('Server is already running');
×
104
        }
105
        this.isRunning = true;
44✔
106
        try {
44✔
107
            this.options = util.normalizeAndResolveConfig(options);
44✔
108
            if (this.options.noProject) {
43!
109
                this.logger.log(`'no-project' flag is set so bsconfig.json loading is disabled'`);
×
110
            } else if (this.options.project) {
43✔
111
                this.logger.log(`Using config file: "${this.options.project}"`);
9✔
112
            } else {
113
                this.logger.log(`No bsconfig.json file found, using default options`);
34✔
114
            }
115
            this.loadRequires();
43✔
116
            this.loadPlugins();
43✔
117
        } catch (e: any) {
118
            if (e?.file && e.message && e.code) {
1!
119
                let err = e as BsDiagnostic;
1✔
120
                this.staticDiagnostics.push(err);
1✔
121
            } else {
122
                //if this is not a diagnostic, something else is wrong...
123
                throw e;
×
124
            }
125
            this.printDiagnostics();
1✔
126

127
            //we added diagnostics, so hopefully that draws attention to the underlying issues.
128
            //For now, just use a default options object so we have a functioning program
129
            this.options = util.normalizeConfig({});
1✔
130
        }
131
        this.logger.logLevel = this.options.logLevel;
44✔
132

133
        this.createProgram();
44✔
134

135
        //parse every file in the entire project
136
        await this.loadAllFilesAST();
44✔
137

138
        if (this.options.watch) {
44!
139
            this.logger.log('Starting compilation in watch mode...');
×
140
            await this.runOnce();
×
141
            this.enableWatchMode();
×
142
        } else {
143
            await this.runOnce();
44✔
144
        }
145
    }
146

147
    protected createProgram() {
148
        this.program = new Program(this.options, this.logger, this.plugins);
45✔
149

150
        this.plugins.emit('afterProgramCreate', this.program);
45✔
151

152
        return this.program;
45✔
153
    }
154

155
    protected loadPlugins() {
156
        const cwd = this.options.cwd ?? process.cwd();
43!
157
        const plugins = util.loadPlugins(
43✔
158
            cwd,
159
            this.options.plugins ?? [],
129!
160
            (pathOrModule, err) => this.logger.error(`Error when loading plugin '${pathOrModule}':`, err)
×
161
        );
162
        this.logger.log(`Loading ${this.options.plugins?.length ?? 0} plugins for cwd "${cwd}"`);
43!
163
        for (let plugin of plugins) {
43✔
164
            this.plugins.add(plugin);
×
165
        }
166

167
        this.plugins.emit('beforeProgramCreate', this);
43✔
168
    }
169

170
    /**
171
     * `require()` every options.require path
172
     */
173
    protected loadRequires() {
174
        for (const dep of this.options.require ?? []) {
43✔
175
            requireRelative(dep, this.options.cwd);
2✔
176
        }
177
    }
178

179
    private clearConsole() {
180
        if (this.allowConsoleClearing) {
41✔
181
            util.clearConsole();
6✔
182
        }
183
    }
184

185
    /**
186
     * A handle for the watch mode interval that keeps the process alive.
187
     * We need this so we can clear it if the builder is disposed
188
     */
189
    private watchInterval: NodeJS.Timer | undefined;
190

191
    public enableWatchMode() {
192
        this.watcher = new Watcher(this.options);
×
193
        if (this.watchInterval) {
×
194
            clearInterval(this.watchInterval);
×
195
        }
196
        //keep the process alive indefinitely by setting an interval that runs once every 12 days
197
        this.watchInterval = setInterval(() => { }, 1073741824);
×
198

199
        //clear the console
200
        this.clearConsole();
×
201

202
        let fileObjects = rokuDeploy.normalizeFilesArray(this.options.files ? this.options.files : []);
×
203

204
        //add each set of files to the file watcher
205
        for (let fileObject of fileObjects) {
×
206
            let src = typeof fileObject === 'string' ? fileObject : fileObject.src;
×
207
            this.watcher.watch(src);
×
208
        }
209

210
        this.logger.log('Watching for file changes...');
×
211

212
        let debouncedRunOnce = debounce(async () => {
×
213
            this.logger.log('File change detected. Starting incremental compilation...');
×
214
            await this.runOnce();
×
215
            this.logger.log(`Watching for file changes.`);
×
216
        }, 50);
217

218
        //on any file watcher event
219
        this.watcher.on('all', async (event: string, thePath: string) => { //eslint-disable-line @typescript-eslint/no-misused-promises
×
220
            if (!this.program) {
×
221
                throw new Error('Internal invariant exception: somehow file watcher ran before `ProgramBuilder.run()`');
×
222
            }
223
            thePath = s`${path.resolve(this.rootDir, thePath)}`;
×
224
            if (event === 'add' || event === 'change') {
×
225
                const fileObj = {
×
226
                    src: thePath,
227
                    dest: rokuDeploy.getDestPath(
228
                        thePath,
229
                        this.program.options.files,
230
                        //some shells will toTowerCase the drive letter, so do it to rootDir for consistency
231
                        util.driveLetterToLower(this.rootDir)
232
                    )
233
                };
234
                this.program.setFile(
×
235
                    fileObj,
236
                    await this.getFileContents(fileObj.src)
237
                );
238
            } else if (event === 'unlink') {
×
239
                this.program.removeFile(thePath);
×
240
            }
241
            //wait for change events to settle, and then execute `run`
242
            await debouncedRunOnce();
×
243
        });
244
    }
245

246
    /**
247
     * The rootDir for this program.
248
     */
249
    public get rootDir() {
250
        if (!this.program) {
8!
251
            throw new Error('Cannot access `ProgramBuilder.rootDir` until after `ProgramBuilder.run()`');
×
252
        }
253
        return this.program.options.rootDir;
8✔
254
    }
255

256
    /**
257
     * A method that is used to cancel a previous run task.
258
     * Does nothing if previous run has completed or was already canceled
259
     */
260
    private cancelLastRun = () => {
59✔
261
        return Promise.resolve();
41✔
262
    };
263

264
    /**
265
     * Run the entire process exactly one time.
266
     */
267
    private runOnce() {
268
        //clear the console
269
        this.clearConsole();
41✔
270
        let cancellationToken = { isCanceled: false };
41✔
271
        //wait for the previous run to complete
272
        let runPromise = this.cancelLastRun().then(() => {
41✔
273
            //start the new run
274
            return this._runOnce(cancellationToken);
41✔
275
        }) as any;
276

277
        //a function used to cancel this run
278
        this.cancelLastRun = () => {
41✔
279
            cancellationToken.isCanceled = true;
×
280
            return runPromise;
×
281
        };
282
        return runPromise;
41✔
283
    }
284

285
    private printDiagnostics(diagnostics?: BsDiagnostic[]) {
286
        if (this.options?.showDiagnosticsInConsole === false) {
48!
287
            return;
34✔
288
        }
289
        if (!diagnostics) {
14✔
290
            diagnostics = this.getDiagnostics();
6✔
291
        }
292

293
        //group the diagnostics by file
294
        let diagnosticsByFile = {} as Record<string, BsDiagnostic[]>;
14✔
295
        for (let diagnostic of diagnostics) {
14✔
296
            if (!diagnosticsByFile[diagnostic.file.srcPath]) {
7✔
297
                diagnosticsByFile[diagnostic.file.srcPath] = [];
6✔
298
            }
299
            diagnosticsByFile[diagnostic.file.srcPath].push(diagnostic);
7✔
300
        }
301

302
        //get printing options
303
        const options = diagnosticUtils.getPrintDiagnosticOptions(this.options);
14✔
304
        const { cwd, emitFullPaths } = options;
14✔
305

306
        let srcPaths = Object.keys(diagnosticsByFile).sort();
14✔
307
        for (let srcPath of srcPaths) {
14✔
308
            let diagnosticsForFile = diagnosticsByFile[srcPath];
6✔
309
            //sort the diagnostics in line and column order
310
            let sortedDiagnostics = diagnosticsForFile.sort((a, b) => {
6✔
311
                return (
1✔
312
                    (a.range?.start.line ?? -1) - (b.range?.start.line ?? -1) ||
14!
313
                    (a.range?.start.character ?? -1) - (b.range?.start.character ?? -1)
12!
314
                );
315
            });
316

317
            let filePath = srcPath;
6✔
318
            if (!emitFullPaths) {
6!
319
                filePath = path.relative(cwd, filePath);
6✔
320
            }
321
            //load the file text
322
            const file = this.program?.getFile(srcPath);
6!
323
            //get the file's in-memory contents if available
324
            const lines = file?.fileContents?.split(/\r?\n/g) ?? [];
6✔
325

326
            for (let diagnostic of sortedDiagnostics) {
6✔
327
                //default the severity to error if undefined
328
                let severity = typeof diagnostic.severity === 'number' ? diagnostic.severity : DiagnosticSeverity.Error;
7✔
329
                let relatedInformation = (diagnostic.relatedInformation ?? []).map(x => {
7!
330
                    let relatedInfoFilePath = URI.parse(x.location.uri).fsPath;
×
331
                    if (!emitFullPaths) {
×
332
                        relatedInfoFilePath = path.relative(cwd, relatedInfoFilePath);
×
333
                    }
334
                    return {
×
335
                        filePath: relatedInfoFilePath,
336
                        range: x.location.range,
337
                        message: x.message
338
                    };
339
                });
340
                //format output
341
                diagnosticUtils.printDiagnostic(options, severity, filePath, lines, diagnostic, relatedInformation);
7✔
342
            }
343
        }
344
    }
345

346
    /**
347
     * Run the process once, allowing cancelability.
348
     * NOTE: This should only be called by `runOnce`.
349
     */
350
    private async _runOnce(cancellationToken: { isCanceled: any }) {
351
        let wereDiagnosticsPrinted = false;
41✔
352
        try {
41✔
353
            //maybe cancel?
354
            if (cancellationToken.isCanceled === true) {
41!
355
                return -1;
×
356
            }
357
            //validate program
358
            this.validateProject();
41✔
359

360
            //maybe cancel?
361
            if (cancellationToken.isCanceled === true) {
41!
362
                return -1;
×
363
            }
364

365
            const diagnostics = this.getDiagnostics();
41✔
366
            this.printDiagnostics(diagnostics);
41✔
367
            wereDiagnosticsPrinted = true;
41✔
368
            let errorCount = diagnostics.filter(x => x.severity === DiagnosticSeverity.Error).length;
41✔
369

370
            if (errorCount > 0) {
41✔
371
                this.logger.log(`Found ${errorCount} ${errorCount === 1 ? 'error' : 'errors'}`);
1!
372
                return errorCount;
1✔
373
            }
374

375
            //create the deployment package (and transpile as well)
376
            await this.createPackageIfEnabled();
40✔
377

378
            //maybe cancel?
379
            if (cancellationToken.isCanceled === true) {
40!
380
                return -1;
×
381
            }
382

383
            //deploy the package
384
            await this.deployPackageIfEnabled();
40✔
385

386
            return 0;
40✔
387
        } catch (e) {
388
            if (wereDiagnosticsPrinted === false) {
×
389
                this.printDiagnostics();
×
390
            }
391
            throw e;
×
392
        }
393
    }
394

395
    private async createPackageIfEnabled() {
396
        if (this.options.copyToStaging || this.options.createPackage || this.options.deploy) {
40✔
397

398
            //transpile the project
399
            await this.transpile();
4✔
400

401
            //create the zip file if configured to do so
402
            if (this.options.createPackage !== false || this.options.deploy) {
4✔
403
                await this.logger.time(LogLevel.log, [`Creating package at ${this.options.outFile}`], async () => {
2✔
404
                    await rokuDeploy.zipPackage({
2✔
405
                        ...this.options,
406
                        logLevel: this.options.logLevel as unknown as RokuDeployLogLevel,
407
                        outDir: util.getOutDir(this.options),
408
                        outFile: path.basename(this.options.outFile)
409
                    });
410
                });
411
            }
412
        }
413
    }
414

415
    private transpileThrottler = new Throttler(0);
59✔
416
    /**
417
     * Transpiles the entire program into the staging folder
418
     */
419
    public async transpile() {
420
        await this.transpileThrottler.run(async () => {
4✔
421
            let options = util.cwdWork(this.options.cwd, () => {
4✔
422
                return rokuDeploy.getOptions({
4✔
423
                    ...this.options,
424
                    logLevel: this.options.logLevel as unknown as RokuDeployLogLevel,
425
                    outDir: util.getOutDir(this.options),
426
                    outFile: path.basename(this.options.outFile)
427

428
                    //rokuDeploy's return type says all its fields can be nullable, but it sets values for all of them.
429
                }) as any as Required<ReturnType<typeof rokuDeploy.getOptions>>;
430
            });
431

432
            //get every file referenced by the files array
433
            let fileMap = await rokuDeploy.getFilePaths(options.files, options.rootDir);
4✔
434

435
            //remove files currently loaded in the program, we will transpile those instead (even if just for source maps)
436
            let filteredFileMap = [] as FileObj[];
4✔
437

438
            for (let fileEntry of fileMap) {
4✔
439
                if (this.program!.hasFile(fileEntry.src) === false) {
4✔
440
                    filteredFileMap.push(fileEntry);
2✔
441
                }
442
            }
443

444
            this.plugins.emit('beforePrepublish', this, filteredFileMap);
4✔
445

446
            await this.logger.time(LogLevel.log, ['Copying to staging directory'], async () => {
4✔
447
                //prepublish all non-program-loaded files to staging
448
                await rokuDeploy.prepublishToStaging({
4✔
449
                    ...options,
450
                    files: filteredFileMap
451
                });
452
            });
453

454
            this.plugins.emit('afterPrepublish', this, filteredFileMap);
4✔
455
            this.plugins.emit('beforePublish', this, fileMap);
4✔
456

457
            await this.logger.time(LogLevel.log, ['Transpiling'], async () => {
4✔
458
                //transpile any brighterscript files
459
                await this.program!.transpile(fileMap, options.stagingDir);
4✔
460
            });
461

462
            this.plugins.emit('afterPublish', this, fileMap);
4✔
463
        });
464
    }
465

466
    private async deployPackageIfEnabled() {
467
        //deploy the project if configured to do so
468
        if (this.options.deploy) {
40!
469
            await this.logger.time(LogLevel.log, ['Deploying package to', this.options.host], async () => {
×
470
                await rokuDeploy.publish({
×
471
                    ...this.options,
472
                    logLevel: this.options.logLevel as unknown as RokuDeployLogLevel,
473
                    outDir: util.getOutDir(this.options),
474
                    outFile: path.basename(this.options.outFile)
475
                });
476
            });
477
        }
478
    }
479

480
    /**
481
     * Parse and load the AST for every file in the project
482
     */
483
    private async loadAllFilesAST() {
484
        await this.logger.time(LogLevel.log, ['Parsing files'], async () => {
46✔
485
            let files = await this.logger.time(LogLevel.debug, ['getFilePaths'], async () => {
46✔
486
                return util.getFilePaths(this.options);
46✔
487
            });
488
            this.logger.trace('ProgramBuilder.loadAllFilesAST() files:', files);
46✔
489

490
            const typedefFiles = [] as FileObj[];
46✔
491
            const sourceFiles = [] as FileObj[];
46✔
492
            let manifestFile: FileObj | null = null;
46✔
493

494
            for (const file of files) {
46✔
495
                // source files (.brs, .bs, .xml)
496
                if (/(?<!\.d)\.(bs|brs|xml)$/i.test(file.dest)) {
30✔
497
                    sourceFiles.push(file);
23✔
498

499
                    // typedef files (.d.bs)
500
                } else if (/\.d\.bs$/i.test(file.dest)) {
7✔
501
                    typedefFiles.push(file);
2✔
502

503
                    // manifest file
504
                } else if (/^manifest$/i.test(file.dest)) {
5!
505
                    manifestFile = file;
5✔
506
                }
507
            }
508

509
            if (manifestFile) {
46✔
510
                this.program!.loadManifest(manifestFile, false);
5✔
511
            }
512

513
            const loadFile = async (fileObj) => {
46✔
514
                try {
25✔
515
                    this.program!.setFile(fileObj, await this.getFileContents(fileObj.src));
25✔
516
                } catch (e) {
517
                    this.logger.log(e); // log the error, but don't fail this process because the file might be fixable later
×
518
                }
519
            };
520
            await Promise.all(typedefFiles.map(loadFile)); // preload every type definition file, which eliminates duplicate file loading
46✔
521
            await Promise.all(sourceFiles.map(loadFile)); // parse source files
46✔
522
        });
523
    }
524

525
    /**
526
     * Remove all files from the program that are in the specified folder path
527
     * @param srcPath the path to the
528
     */
529
    public removeFilesInFolder(srcPath: string) {
530
        for (let filePath in this.program.files) {
×
531
            //if the file path starts with the parent path and the file path does not exactly match the folder path
532
            if (filePath.startsWith(srcPath) && filePath !== srcPath) {
×
533
                this.program.removeFile(filePath);
×
534
            }
535
        }
536
    }
537

538
    /**
539
     * Scan every file and resolve all variable references.
540
     * If no errors were encountered, return true. Otherwise return false.
541
     */
542
    private validateProject() {
543
        this.program.validate();
41✔
544
    }
545

546
    public dispose() {
547
        if (this.watcher) {
21!
548
            this.watcher.dispose();
×
549
        }
550
        if (this.program) {
21!
551
            this.program.dispose?.();
21!
552
        }
553
        if (this.watchInterval) {
21!
554
            clearInterval(this.watchInterval);
×
555
        }
556
    }
557
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc