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

rokucommunity / brighterscript / #13061

23 Sep 2024 02:51PM UTC coverage: 88.769% (+0.8%) from 87.933%
#13061

push

web-flow
Merge 373852d93 into 56dcaaa63

6620 of 7920 branches covered (83.59%)

Branch coverage included in aggregate %.

1025 of 1156 new or added lines in 28 files covered. (88.67%)

24 existing lines in 5 files now uncovered.

9456 of 10190 relevant lines covered (92.8%)

1711.78 hits per line

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

72.32
/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 type { Logger } from './logging';
12
import { LogLevel, createLogger } from './logging';
1✔
13
import PluginInterface from './PluginInterface';
1✔
14
import * as diagnosticUtils from './diagnosticUtils';
1✔
15
import * as fsExtra from 'fs-extra';
1✔
16
import * as requireRelative from 'require-relative';
1✔
17
import { Throttler } from './Throttler';
1✔
18
import { URI } from 'vscode-uri';
1✔
19

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

25
    public constructor(
26
        options?: {
27
            logger?: Logger;
28
        }
29
    ) {
30
        this.logger = options?.logger ?? createLogger();
95✔
31
        this.plugins = new PluginInterface([], { logger: this.logger });
95✔
32

33
        //add the default file resolver (used to load source file contents).
34
        this.addFileResolver((filePath) => {
95✔
35
            return fsExtra.readFile(filePath).then((value) => {
41✔
36
                return value.toString();
41✔
37
            });
38
        });
39
    }
40
    /**
41
     * Determines whether the console should be cleared after a run (true for cli, false for languageserver)
42
     */
43
    public allowConsoleClearing = true;
95✔
44

45
    public options: FinalizedBsConfig = util.normalizeConfig({});
95✔
46
    private isRunning = false;
95✔
47
    private watcher: Watcher | undefined;
48
    public program: Program | undefined;
49
    public logger: Logger;
50
    public plugins: PluginInterface;
51
    private fileResolvers = [] as FileResolver[];
95✔
52

53
    /**
54
     * Add file resolvers that will be able to provide file contents before loading from the file system
55
     * @param fileResolvers a list of file resolvers
56
     */
57
    public addFileResolver(...fileResolvers: FileResolver[]) {
58
        this.fileResolvers.push(...fileResolvers);
95✔
59
    }
60

61
    /**
62
     * Get the contents of the specified file as a string.
63
     * This walks backwards through the file resolvers until we get a value.
64
     * This allow the language server to provide file contents directly from memory.
65
     */
66
    public async getFileContents(srcPath: string) {
67
        srcPath = s`${srcPath}`;
41✔
68
        let reversedResolvers = [...this.fileResolvers].reverse();
41✔
69
        for (let fileResolver of reversedResolvers) {
41✔
70
            let result = await fileResolver(srcPath);
46✔
71
            if (typeof result === 'string') {
46✔
72
                return result;
41✔
73
            }
74
        }
75
        throw new Error(`Could not load file "${srcPath}"`);
×
76
    }
77

78
    /**
79
     * A list of diagnostics that are always added to the `getDiagnostics()` call.
80
     */
81
    private staticDiagnostics = [] as BsDiagnostic[];
95✔
82

83
    public addDiagnostic(srcPath: string, diagnostic: Partial<BsDiagnostic>) {
84
        if (!this.program) {
1!
85
            throw new Error('Cannot call `ProgramBuilder.addDiagnostic` before `ProgramBuilder.run()`');
×
86
        }
87
        let file: BscFile | undefined = this.program.getFile(srcPath);
1✔
88
        if (!file) {
1!
89
            file = {
1✔
90
                pkgPath: path.basename(srcPath),
91
                pathAbsolute: srcPath, //keep this for backwards-compatibility. TODO remove in v1
92
                srcPath: srcPath,
93
                getDiagnostics: () => {
94
                    return [<any>diagnostic];
×
95
                }
96
            } as BscFile;
97
        }
98
        diagnostic.file = file;
1✔
99
        this.staticDiagnostics.push(<any>diagnostic);
1✔
100
    }
101

102
    public getDiagnostics() {
103
        return [
188✔
104
            ...this.staticDiagnostics,
105
            ...(this.program?.getDiagnostics() ?? [])
1,128!
106
        ];
107
    }
108

109
    public async run(options: BsConfig & { skipInitialValidation?: boolean }) {
110
        this.logger.logLevel = options.logLevel;
80✔
111

112
        if (this.isRunning) {
80!
113
            throw new Error('Server is already running');
×
114
        }
115
        this.isRunning = true;
80✔
116
        try {
80✔
117
            this.options = util.normalizeAndResolveConfig(options);
80✔
118
            if (this.options?.logLevel !== undefined) {
78!
119
                this.logger.logLevel = this.options?.logLevel;
78!
120
            }
121

122
            if (this.options.noProject) {
78!
123
                this.logger.log(`'no-project' flag is set so bsconfig.json loading is disabled'`);
×
124
            } else if (this.options.project) {
78✔
125
                this.logger.log(`Using config file: "${this.options.project}"`);
29✔
126
            } else {
127
                this.logger.log(`No bsconfig.json file found, using default options`);
49✔
128
            }
129
            this.loadRequires();
78✔
130
            this.loadPlugins();
78✔
131
        } catch (e: any) {
132
            //For now, just use a default options object so we have a functioning program
133
            this.options = util.normalizeConfig({
2✔
134
                showDiagnosticsInConsole: options?.showDiagnosticsInConsole
6!
135
            });
136

137
            if (e?.file && e.message && e.code) {
2!
138
                let err = e as BsDiagnostic;
2✔
139
                this.staticDiagnostics.push(err);
2✔
140
            } else {
141
                //if this is not a diagnostic, something else is wrong...
142
                throw e;
×
143
            }
144

145
            this.printDiagnostics();
2✔
146
        }
147
        this.logger.logLevel = this.options.logLevel;
80✔
148

149
        this.createProgram();
80✔
150

151
        //parse every file in the entire project
152
        await this.loadAllFilesAST();
80✔
153

154
        if (this.options.watch) {
80!
155
            this.logger.log('Starting compilation in watch mode...');
×
NEW
156
            await this.runOnce({
×
157
                skipValidation: options.skipInitialValidation
158
            });
UNCOV
159
            this.enableWatchMode();
×
160
        } else {
161
            await this.runOnce({
80✔
162
                skipValidation: options.skipInitialValidation
163
            });
164
        }
165
    }
166

167
    protected createProgram() {
168
        this.program = new Program(this.options, this.logger, this.plugins);
81✔
169

170
        this.plugins.emit('afterProgramCreate', this.program);
81✔
171

172
        return this.program;
81✔
173
    }
174

175
    protected loadPlugins() {
176
        const cwd = this.options.cwd ?? process.cwd();
78!
177
        const plugins = util.loadPlugins(
78✔
178
            cwd,
179
            this.options.plugins ?? [],
234!
180
            (pathOrModule, err) => this.logger.error(`Error when loading plugin '${pathOrModule}':`, err)
×
181
        );
182
        this.logger.log(`Loading ${this.options.plugins?.length ?? 0} plugins for cwd "${cwd}"`, this.options.plugins);
78!
183
        for (let plugin of plugins) {
78✔
184
            this.plugins.add(plugin);
1✔
185
        }
186

187
        this.plugins.emit('beforeProgramCreate', this);
78✔
188
    }
189

190
    /**
191
     * `require()` every options.require path
192
     */
193
    protected loadRequires() {
194
        for (const dep of this.options.require ?? []) {
78✔
195
            requireRelative(dep, this.options.cwd);
2✔
196
        }
197
    }
198

199
    private clearConsole() {
200
        if (this.allowConsoleClearing) {
78!
201
            util.clearConsole();
78✔
202
        }
203
    }
204

205
    /**
206
     * A handle for the watch mode interval that keeps the process alive.
207
     * We need this so we can clear it if the builder is disposed
208
     */
209
    private watchInterval: NodeJS.Timer | undefined;
210

211
    public enableWatchMode() {
212
        this.watcher = new Watcher(this.options);
×
213
        if (this.watchInterval) {
×
214
            clearInterval(this.watchInterval);
×
215
        }
216
        //keep the process alive indefinitely by setting an interval that runs once every 12 days
217
        this.watchInterval = setInterval(() => { }, 1073741824);
×
218

219
        //clear the console
220
        this.clearConsole();
×
221

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

224
        //add each set of files to the file watcher
225
        for (let fileObject of fileObjects) {
×
226
            let src = typeof fileObject === 'string' ? fileObject : fileObject.src;
×
227
            this.watcher.watch(src);
×
228
        }
229

230
        this.logger.log('Watching for file changes...');
×
231

232
        let debouncedRunOnce = debounce(async () => {
×
233
            this.logger.log('File change detected. Starting incremental compilation...');
×
234
            await this.runOnce();
×
235
            this.logger.log(`Watching for file changes.`);
×
236
        }, 50);
237

238
        //on any file watcher event
239
        this.watcher.on('all', async (event: string, thePath: string) => { //eslint-disable-line @typescript-eslint/no-misused-promises
×
240
            if (!this.program) {
×
241
                throw new Error('Internal invariant exception: somehow file watcher ran before `ProgramBuilder.run()`');
×
242
            }
243
            thePath = s`${path.resolve(this.rootDir, thePath)}`;
×
244
            if (event === 'add' || event === 'change') {
×
245
                const fileObj = {
×
246
                    src: thePath,
247
                    dest: rokuDeploy.getDestPath(
248
                        thePath,
249
                        this.program.options.files,
250
                        //some shells will toTowerCase the drive letter, so do it to rootDir for consistency
251
                        util.driveLetterToLower(this.rootDir)
252
                    )
253
                };
254
                this.program.setFile(
×
255
                    fileObj,
256
                    await this.getFileContents(fileObj.src)
257
                );
258
            } else if (event === 'unlink') {
×
259
                this.program.removeFile(thePath);
×
260
            }
261
            //wait for change events to settle, and then execute `run`
262
            await debouncedRunOnce();
×
263
        });
264
    }
265

266
    /**
267
     * The rootDir for this program.
268
     */
269
    public get rootDir() {
UNCOV
270
        if (!this.program) {
×
271
            throw new Error('Cannot access `ProgramBuilder.rootDir` until after `ProgramBuilder.run()`');
×
272
        }
UNCOV
273
        return this.program.options.rootDir;
×
274
    }
275

276
    /**
277
     * A method that is used to cancel a previous run task.
278
     * Does nothing if previous run has completed or was already canceled
279
     */
280
    private cancelLastRun = () => {
95✔
281
        return Promise.resolve();
78✔
282
    };
283

284
    /**
285
     * Run the entire process exactly one time.
286
     */
287
    private runOnce(options?: { skipValidation?: boolean }) {
288
        //clear the console
289
        this.clearConsole();
78✔
290
        let cancellationToken = { isCanceled: false };
78✔
291
        //wait for the previous run to complete
292
        let runPromise = this.cancelLastRun().then(() => {
78✔
293
            //start the new run
294
            return this._runOnce({
78✔
295
                cancellationToken: cancellationToken,
296
                skipValidation: options?.skipValidation
234!
297
            });
298
        }) as any;
299

300
        //a function used to cancel this run
301
        this.cancelLastRun = () => {
78✔
302
            cancellationToken.isCanceled = true;
×
303
            return runPromise;
×
304
        };
305
        return runPromise;
78✔
306
    }
307

308
    private printDiagnostics(diagnostics?: BsDiagnostic[]) {
309
        if (this.options?.showDiagnosticsInConsole === false) {
86!
310
            return;
74✔
311
        }
312
        if (!diagnostics) {
12✔
313
            diagnostics = this.getDiagnostics();
6✔
314
        }
315

316
        //group the diagnostics by file
317
        let diagnosticsByFile = {} as Record<string, BsDiagnostic[]>;
12✔
318
        for (let diagnostic of diagnostics) {
12✔
319
            if (!diagnosticsByFile[diagnostic.file.srcPath]) {
7✔
320
                diagnosticsByFile[diagnostic.file.srcPath] = [];
6✔
321
            }
322
            diagnosticsByFile[diagnostic.file.srcPath].push(diagnostic);
7✔
323
        }
324

325
        //get printing options
326
        const options = diagnosticUtils.getPrintDiagnosticOptions(this.options);
12✔
327
        const { cwd, emitFullPaths } = options;
12✔
328

329
        let srcPaths = Object.keys(diagnosticsByFile).sort();
12✔
330
        for (let srcPath of srcPaths) {
12✔
331
            let diagnosticsForFile = diagnosticsByFile[srcPath];
6✔
332
            //sort the diagnostics in line and column order
333
            let sortedDiagnostics = diagnosticsForFile.sort((a, b) => {
6✔
334
                return (
1✔
335
                    (a.range?.start.line ?? -1) - (b.range?.start.line ?? -1) ||
14!
336
                    (a.range?.start.character ?? -1) - (b.range?.start.character ?? -1)
12!
337
                );
338
            });
339

340
            let filePath = srcPath;
6✔
341
            if (!emitFullPaths) {
6!
342
                filePath = path.relative(cwd, filePath);
6✔
343
            }
344
            //load the file text
345
            const file = this.program?.getFile(srcPath);
6!
346
            //get the file's in-memory contents if available
347
            const lines = file?.fileContents?.split(/\r?\n/g) ?? [];
6✔
348

349
            for (let diagnostic of sortedDiagnostics) {
6✔
350
                //default the severity to error if undefined
351
                let severity = typeof diagnostic.severity === 'number' ? diagnostic.severity : DiagnosticSeverity.Error;
7✔
352
                let relatedInformation = (diagnostic.relatedInformation ?? []).map(x => {
7!
353
                    let relatedInfoFilePath = URI.parse(x.location.uri).fsPath;
×
354
                    if (!emitFullPaths) {
×
355
                        relatedInfoFilePath = path.relative(cwd, relatedInfoFilePath);
×
356
                    }
357
                    return {
×
358
                        filePath: relatedInfoFilePath,
359
                        range: x.location.range,
360
                        message: x.message
361
                    };
362
                });
363
                //format output
364
                diagnosticUtils.printDiagnostic(options, severity, filePath, lines, diagnostic, relatedInformation);
7✔
365
            }
366
        }
367
    }
368

369
    /**
370
     * Run the process once, allowing it to be cancelled.
371
     * NOTE: This should only be called by `runOnce`.
372
     */
373
    private async _runOnce(options: { cancellationToken: { isCanceled: any }; skipValidation: boolean }) {
374
        let wereDiagnosticsPrinted = false;
78✔
375
        try {
78✔
376
            //maybe cancel?
377
            if (options.cancellationToken.isCanceled === true) {
78!
378
                return -1;
×
379
            }
380
            //validate program
381
            if (options.skipValidation !== true) {
78✔
382
                this.validateProject();
6✔
383
            }
384

385
            //maybe cancel?
386
            if (options.cancellationToken.isCanceled === true) {
78!
387
                return -1;
×
388
            }
389

390
            const diagnostics = this.getDiagnostics();
78✔
391
            this.printDiagnostics(diagnostics);
78✔
392
            wereDiagnosticsPrinted = true;
78✔
393
            let errorCount = diagnostics.filter(x => x.severity === DiagnosticSeverity.Error).length;
78✔
394

395
            if (errorCount > 0) {
78✔
396
                this.logger.log(`Found ${errorCount} ${errorCount === 1 ? 'error' : 'errors'}`);
2!
397
                return errorCount;
2✔
398
            }
399

400
            //create the deployment package (and transpile as well)
401
            await this.createPackageIfEnabled();
76✔
402

403
            //maybe cancel?
404
            if (options.cancellationToken.isCanceled === true) {
76!
405
                return -1;
×
406
            }
407

408
            //deploy the package
409
            await this.deployPackageIfEnabled();
76✔
410

411
            return 0;
76✔
412
        } catch (e) {
413
            if (wereDiagnosticsPrinted === false) {
×
414
                this.printDiagnostics();
×
415
            }
416
            throw e;
×
417
        }
418
    }
419

420
    private async createPackageIfEnabled() {
421
        if (this.options.copyToStaging || this.options.createPackage || this.options.deploy) {
76✔
422

423
            //transpile the project
424
            await this.transpile();
4✔
425

426
            //create the zip file if configured to do so
427
            if (this.options.createPackage !== false || this.options.deploy) {
4✔
428
                await this.logger.time(LogLevel.log, [`Creating package at ${this.options.outFile}`], async () => {
2✔
429
                    await rokuDeploy.zipPackage({
2✔
430
                        ...this.options,
431
                        logLevel: this.options.logLevel as unknown as RokuDeployLogLevel,
432
                        outDir: util.getOutDir(this.options),
433
                        outFile: path.basename(this.options.outFile)
434
                    });
435
                });
436
            }
437
        }
438
    }
439

440
    private transpileThrottler = new Throttler(0);
95✔
441
    /**
442
     * Transpiles the entire program into the staging folder
443
     */
444
    public async transpile() {
445
        await this.transpileThrottler.run(async () => {
4✔
446
            let options = util.cwdWork(this.options.cwd, () => {
4✔
447
                return rokuDeploy.getOptions({
4✔
448
                    ...this.options,
449
                    logLevel: this.options.logLevel as unknown as RokuDeployLogLevel,
450
                    outDir: util.getOutDir(this.options),
451
                    outFile: path.basename(this.options.outFile)
452

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

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

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

463
            for (let fileEntry of fileMap) {
4✔
464
                if (this.program!.hasFile(fileEntry.src) === false) {
4✔
465
                    filteredFileMap.push(fileEntry);
2✔
466
                }
467
            }
468

469
            this.plugins.emit('beforePrepublish', this, filteredFileMap);
4✔
470

471
            await this.logger.time(LogLevel.log, ['Copying to staging directory'], async () => {
4✔
472
                //prepublish all non-program-loaded files to staging
473
                await rokuDeploy.prepublishToStaging({
4✔
474
                    ...options,
475
                    files: filteredFileMap
476
                });
477
            });
478

479
            this.plugins.emit('afterPrepublish', this, filteredFileMap);
4✔
480
            this.plugins.emit('beforePublish', this, fileMap);
4✔
481

482
            await this.logger.time(LogLevel.log, ['Transpiling'], async () => {
4✔
483
                //transpile any brighterscript files
484
                await this.program!.transpile(fileMap, options.stagingDir);
4✔
485
            });
486

487
            this.plugins.emit('afterPublish', this, fileMap);
4✔
488
        });
489
    }
490

491
    private async deployPackageIfEnabled() {
492
        //deploy the project if configured to do so
493
        if (this.options.deploy) {
76!
494
            await this.logger.time(LogLevel.log, ['Deploying package to', this.options.host], async () => {
×
495
                await rokuDeploy.publish({
×
496
                    ...this.options,
497
                    logLevel: this.options.logLevel as unknown as RokuDeployLogLevel,
498
                    outDir: util.getOutDir(this.options),
499
                    outFile: path.basename(this.options.outFile)
500
                });
501
            });
502
        }
503
    }
504

505
    /**
506
     * Parse and load the AST for every file in the project
507
     */
508
    private async loadAllFilesAST() {
509
        await this.logger.time(LogLevel.log, ['Parsing files'], async () => {
82✔
510
            let files = await this.logger.time(LogLevel.debug, ['getFilePaths'], async () => {
82✔
511
                return util.getFilePaths(this.options);
82✔
512
            });
513
            this.logger.trace('ProgramBuilder.loadAllFilesAST() files:', files);
82✔
514

515
            const typedefFiles = [] as FileObj[];
82✔
516
            const sourceFiles = [] as FileObj[];
82✔
517
            let manifestFile: FileObj | null = null;
82✔
518

519
            for (const file of files) {
82✔
520
                // source files (.brs, .bs, .xml)
521
                if (/(?<!\.d)\.(bs|brs|xml)$/i.test(file.dest)) {
55✔
522
                    sourceFiles.push(file);
45✔
523

524
                    // typedef files (.d.bs)
525
                } else if (/\.d\.bs$/i.test(file.dest)) {
10✔
526
                    typedefFiles.push(file);
2✔
527

528
                    // manifest file
529
                } else if (/^manifest$/i.test(file.dest)) {
8✔
530
                    manifestFile = file;
7✔
531
                }
532
            }
533

534
            if (manifestFile) {
82✔
535
                this.program!.loadManifest(manifestFile, false);
7✔
536
            }
537

538
            const loadFile = async (fileObj) => {
82✔
539
                try {
47✔
540
                    this.program!.setFile(fileObj, await this.getFileContents(fileObj.src));
47✔
541
                } catch (e) {
542
                    this.logger.log(e); // log the error, but don't fail this process because the file might be fixable later
×
543
                }
544
            };
545
            await Promise.all(typedefFiles.map(loadFile)); // preload every type definition file, which eliminates duplicate file loading
82✔
546
            await Promise.all(sourceFiles.map(loadFile)); // parse source files
82✔
547
        });
548
    }
549

550
    /**
551
     * Remove all files from the program that are in the specified folder path
552
     * @param srcPath the path to the folder to remove
553
     */
554
    public removeFilesInFolder(srcPath: string): boolean {
NEW
555
        let removedSomeFiles = false;
×
UNCOV
556
        for (let filePath in this.program.files) {
×
557
            //if the file path starts with the parent path and the file path does not exactly match the folder path
558
            if (filePath.startsWith(srcPath) && filePath !== srcPath) {
×
559
                this.program.removeFile(filePath);
×
NEW
560
                removedSomeFiles = true;
×
561
            }
562
        }
NEW
563
        return removedSomeFiles;
×
564
    }
565

566
    /**
567
     * Scan every file and resolve all variable references.
568
     * If no errors were encountered, return true. Otherwise return false.
569
     */
570
    private validateProject() {
571
        this.program.validate();
6✔
572
    }
573

574
    public dispose() {
575
        if (this.watcher) {
89!
576
            this.watcher.dispose();
×
577
        }
578
        if (this.program) {
89!
579
            this.program.dispose?.();
89!
580
        }
581
        if (this.watchInterval) {
89!
582
            clearInterval(this.watchInterval);
×
583
        }
584
    }
585
}
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