Skip to content

Commit

Permalink
updates to use bsc alpha api
Browse files Browse the repository at this point in the history
  • Loading branch information
georgejecook committed Dec 1, 2023
1 parent e199c5f commit 536782e
Show file tree
Hide file tree
Showing 20 changed files with 778 additions and 2,317 deletions.
3 changes: 2 additions & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -156,5 +156,6 @@
"project_id": 0,
"team_id": 0,
"project_name": ""
}
},
"cSpell.words": ["cdbl", "Lcov", "RBSFM", "ROIBOS", "rooibosskipfields"]
}
6 changes: 3 additions & 3 deletions bsc-plugin/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "rooibos-roku",
"version": "5.8.0",
"version": "6.0.0-wip",
"description": "simple, flexible, fun brightscript test framework for roku scenegraph apps - roku brighterscript plugin",
"repository": {
"type": "git",
Expand Down Expand Up @@ -28,7 +28,7 @@
"@typescript-eslint/eslint-plugin": "^5.27.0",
"@typescript-eslint/parser": "^5.27.0",
"cz-conventional-changelog": "^3.3.0",
"brighterscript": "^0.61.3",
"brighterscript": "^0.66.0-alpha.9",
"chai": "^4.2.0",
"chai-subset": "^1.6.0",
"coveralls": "^3.0.0",
Expand Down Expand Up @@ -117,4 +117,4 @@
"path": "./node_modules/cz-conventional-changelog"
}
}
}
}
12 changes: 6 additions & 6 deletions bsc-plugin/src/lib/rooibos/CodeCoverageProcessor.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { RooibosPlugin } from '../../plugin';

let tmpPath = s`${process.cwd()}/tmp`;
let _rootDir = s`${tmpPath}/rootDir`;
let _stagingFolderPath = s`${tmpPath}/staging`;
let _stagingDir = s`${tmpPath}/staging`;

function trimLeading(text: string) {
return text.split('\n').map((line) => line.trimStart()).join('\n');
Expand All @@ -21,15 +21,15 @@ describe('RooibosPlugin', () => {

function getContents(filename: string) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
return trimLeading(fsExtra.readFileSync(s`${_stagingFolderPath}/${filename}`).toString());
return trimLeading(fsExtra.readFileSync(s`${_stagingDir}/${filename}`).toString());
}

describe('CodeCoverageProcessor', () => {
beforeEach(() => {
plugin = new RooibosPlugin();
options = {
rootDir: _rootDir,
stagingFolderPath: _stagingFolderPath,
stagingDir: _stagingDir,
rooibos: {
isRecordingCodeCoverage: true,
coverageExcludedFiles: [
Expand All @@ -38,7 +38,7 @@ describe('RooibosPlugin', () => {
},
allowBrighterScriptInBrightScript: true
};
fsExtra.ensureDirSync(_stagingFolderPath);
fsExtra.ensureDirSync(_stagingDir);
fsExtra.ensureDirSync(_rootDir);
fsExtra.ensureDirSync(tmpPath);

Expand All @@ -51,11 +51,11 @@ describe('RooibosPlugin', () => {
builder.plugins = new PluginInterface([plugin], { logger: builder.logger });
program.plugins = new PluginInterface([plugin], { logger: builder.logger });
program.createSourceScope(); //ensure source scope is created
plugin.beforeProgramCreate(builder);
plugin.beforeProgramCreate({ builder: builder });

});
afterEach(() => {
plugin.afterProgramCreate(program);
plugin.afterProgramCreate({ program: program, builder: builder });
fsExtra.ensureDirSync(tmpPath);
fsExtra.emptyDirSync(tmpPath);
builder.dispose();
Expand Down
12 changes: 6 additions & 6 deletions bsc-plugin/src/lib/rooibos/CodeCoverageProcessor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,27 +63,27 @@ end function
private coverageMap: Map<number, number>;
private fileFactory: FileFactory;
private processedStatements: Set<Statement>;
private astEditor: Editor;
private editor: Editor;

public generateMetadata(isUsingCoverage: boolean, program: Program) {
if (isUsingCoverage) {
this.fileFactory.createCoverageComponent(program, this.expectedCoverageMap, this.filePathMap);
}
}

public addCodeCoverage(file: BrsFile, astEditor: Editor) {
public addCodeCoverage(file: BrsFile, editor: Editor) {
if (this.config.isRecordingCodeCoverage) {
this.transpileState = new BrsTranspileState(file);
this._processFile(file, astEditor);
this._processFile(file, editor);
}
}

public _processFile(file: BrsFile, astEditor: Editor) {
public _processFile(file: BrsFile, editor: Editor) {
this.fileId++;
this.coverageMap = new Map<number, number>();
this.executableLines = new Map<number, Statement>();
this.processedStatements = new Set<Statement>();
this.astEditor = astEditor;
this.editor = editor;

file.ast.walk(createVisitor({
ForStatement: (ds, parent, owner, key) => {
Expand Down Expand Up @@ -170,7 +170,7 @@ end function
const lineNumber = statement.range.start.line;
this.coverageMap.set(lineNumber, coverageType);
const parsed = Parser.parse(this.getFuncCallText(lineNumber, coverageType)).ast.statements[0] as ExpressionStatement;
this.astEditor.arraySplice(owner, key, 0, parsed);
this.editor.arraySplice(owner, key, 0, parsed);
// store the statement in a set to avoid handling again after inserting statement above
this.processedStatements.add(statement);
}
Expand Down
2 changes: 1 addition & 1 deletion bsc-plugin/src/lib/rooibos/FileFactory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ export class FileFactory {
public addFileToRootDir(program: Program, filePath: string, contents: string) {
try {
fse.outputFileSync(
path.join(program.options.stagingFolderPath ?? program.options.stagingDir ?? program.options.sourceRoot, filePath),
path.join(program.options.stagingDir ?? program.options.sourceRoot, filePath),
contents
);
} catch (error) {
Expand Down
12 changes: 6 additions & 6 deletions bsc-plugin/src/lib/rooibos/MockUtil.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,18 +40,18 @@ export class MockUtil {
private filePathMap: any;
private fileFactory: FileFactory;
private processedStatements: Set<brighterscript.FunctionStatement>;
private astEditor: Editor;
private editor: Editor;

enableGlobalMethodMocks(file: BrsFile, astEditor: Editor) {
enableGlobalMethodMocks(file: BrsFile, editor: Editor) {
if (this.config.isGlobalMethodMockingEnabled) {
this._processFile(file, astEditor);
this._processFile(file, editor);
}
}

_processFile(file: BrsFile, astEditor: Editor) {
_processFile(file: BrsFile, editor: Editor) {
this.fileId++;
this.processedStatements = new Set<brighterscript.FunctionStatement>();
this.astEditor = astEditor;
this.editor = editor;
// console.log('processing global methods on ', file.pkgPath);
for (let fs of file.parser.references.functionStatements) {
this.enableMockOnFunction(fs);
Expand Down Expand Up @@ -89,7 +89,7 @@ export class MockUtil {
const paramNames = functionStatement.func.parameters.map((param) => param.name.text).join(',');

const returnStatement = ((functionStatement.func.functionType?.kind === brighterscript.TokenKind.Sub && (functionStatement.func.returnTypeToken === undefined || functionStatement.func.returnTypeToken?.kind === brighterscript.TokenKind.Void)) || functionStatement.func.returnTypeToken?.kind === brighterscript.TokenKind.Void) ? 'return' : 'return result';
this.astEditor.addToArray(functionStatement.func.body.statements, 0, new RawCodeStatement(undent`
this.editor.addToArray(functionStatement.func.body.statements, 0, new RawCodeStatement(undent`
if RBS_SM_${this.fileId}_getMocksByFunctionName()["${methodName}"] <> invalid
result = RBS_SM_${this.fileId}_getMocksByFunctionName()["${methodName}"].callback(${paramNames})
${returnStatement}
Expand Down
28 changes: 14 additions & 14 deletions bsc-plugin/src/lib/rooibos/RooibosSession.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import * as path from 'path';
import type { BrsFile, BscFile, ClassStatement, FunctionStatement, NamespaceStatement, Program, ProgramBuilder, Scope, Statement } from 'brighterscript';
import { isBrsFile, ParseMode, util } from 'brighterscript';
import type { AstEditor } from 'brighterscript/dist/astUtils/AstEditor';
import type { Editor } from 'brighterscript/dist/astUtils/Editor';
import type { RooibosConfig } from './RooibosConfig';
import { SessionInfo } from './RooibosSessionInfo';
import { TestSuiteBuilder } from './TestSuiteBuilder';
Expand Down Expand Up @@ -52,7 +52,7 @@ export class RooibosSession {
this.sessionInfo = new SessionInfo(this.config);
}

prepareForTranspile(editor: AstEditor, program: Program, mockUtil: MockUtil) {
prepareForTranspile(editor: Editor, program: Program, mockUtil: MockUtil) {
this.addTestRunnerMetadata(editor);
this.addLaunchHookToExistingMain(editor);
if (this.config.isGlobalMethodMockingEnabled && this.config.isGlobalMethodMockingEfficientMode) {
Expand All @@ -76,7 +76,7 @@ export class RooibosSession {
return testSuites;
}

addLaunchHookToExistingMain(editor: AstEditor) {
addLaunchHookToExistingMain(editor: Editor) {
let mainFunction: FunctionStatement;
const files = this._builder.program.getScopeByName('source').getOwnFiles();
for (let file of files) {
Expand Down Expand Up @@ -105,19 +105,19 @@ export class RooibosSession {
}
}
if (!mainFunction) {
diagnosticWarnNoMainFound(files[0]);
if (!this._builder.options.stagingDir && !this._builder.options.stagingFolderPath) {
diagnosticWarnNoMainFound(files.find(isBrsFile));
if (!this._builder.options.stagingDir && !this._builder.options.stagingDir) {
console.error('this plugin requires that stagingDir or the deprecated stagingFolderPath bsconfig option is set');
diagnosticNoStagingDir(files[0]);
diagnosticNoStagingDir(files.find(isBrsFile));
} else {
const filePath = path.join(this._builder.options.stagingDir ?? this._builder.options.stagingFolderPath, 'source/rooibosMain.brs');
const filePath = path.join(this._builder.options.stagingDir ?? this._builder.options.stagingDir, 'source/rooibosMain.brs');
fsExtra.writeFileSync(filePath, `function main()\n Rooibos_init("${this.config?.testSceneName ?? 'RooibosScene'}")\nend function`);

}
}
}

addTestRunnerMetadata(editor: AstEditor) {
addTestRunnerMetadata(editor: Editor) {
let runtimeConfig = this._builder.program.getFile<BrsFile>('source/rooibos/RuntimeConfig.bs');
if (runtimeConfig) {
let classStatement = (runtimeConfig.ast.statements[0] as NamespaceStatement).body.statements[0] as ClassStatement;
Expand All @@ -129,7 +129,7 @@ export class RooibosSession {
}
}

updateRunTimeConfigFunction(classStatement: ClassStatement, editor: AstEditor) {
updateRunTimeConfigFunction(classStatement: ClassStatement, editor: Editor) {
let method = classStatement.methods.find((m) => m.name.text === 'getRuntimeConfig');
if (method) {
editor.addToArray(
Expand All @@ -153,7 +153,7 @@ export class RooibosSession {
}
}

updateVersionTextFunction(classStatement: ClassStatement, editor: AstEditor) {
updateVersionTextFunction(classStatement: ClassStatement, editor: Editor) {
let method = classStatement.methods.find((m) => m.name.text === 'getVersionText');
if (method) {
editor.addToArray(
Expand All @@ -164,7 +164,7 @@ export class RooibosSession {
}
}

updateClassLookupFunction(classStatement: ClassStatement, editor: AstEditor) {
updateClassLookupFunction(classStatement: ClassStatement, editor: Editor) {
let method = classStatement.methods.find((m) => m.name.text === 'getTestSuiteClassWithName');
if (method) {
editor.arrayPush(method.func.body.statements, new RawCodeStatement(undent`
Expand All @@ -177,7 +177,7 @@ export class RooibosSession {
}
}

updateGetAllTestSuitesNames(classStatement: ClassStatement, editor: AstEditor) {
updateGetAllTestSuitesNames(classStatement: ClassStatement, editor: Editor) {
let method = classStatement.methods.find((m) => m.name.text === 'getAllTestSuitesNames');
if (method) {
editor.arrayPush(method.func.body.statements, new RawCodeStatement([
Expand All @@ -195,6 +195,7 @@ export class RooibosSession {
}
}

//MOVE TO FILES API - serializeProgram, like in maestro plugin
createNodeFile(program: Program, suite: TestSuite) {
let p = path.join('components', 'rooibos', 'generated');

Expand All @@ -204,7 +205,6 @@ export class RooibosSession {
let bsFile = program.getFile(bsPath);
if (bsFile) {
(bsFile as BrsFile).parser.statements.push();
bsFile.needsTranspiled = true;
}
let brsFile = this.fileFactory.addFile(program, bsPath, undent`
import "pkg:/${suite.file.pkgPath}"
Expand Down Expand Up @@ -248,7 +248,7 @@ export class RooibosSession {
}


private createIgnoredTestsInfoFunction(cs: ClassStatement, editor: AstEditor) {
private createIgnoredTestsInfoFunction(cs: ClassStatement, editor: Editor) {
let method = cs.methods.find((m) => m.name.text === 'getIgnoredTestInfo');
if (method) {
editor.arrayPush(method.func.body.statements, new RawCodeStatement([
Expand Down
6 changes: 3 additions & 3 deletions bsc-plugin/src/lib/rooibos/TestGroup.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { AstEditor, CallExpression, DottedGetExpression, Expression } from 'brighterscript';
import type { Editor, CallExpression, DottedGetExpression, Expression } from 'brighterscript';
import { isCallExpression, isCallfuncExpression, isIndexedGetExpression, ArrayLiteralExpression, createInvalidLiteral, createStringLiteral, createToken, isDottedGetExpression, TokenKind, isLiteralExpression, isVariableExpression, isFunctionExpression } from 'brighterscript';
import * as brighterscript from 'brighterscript';
import { BrsTranspileState } from 'brighterscript/dist/parser/BrsTranspileState';
Expand Down Expand Up @@ -50,7 +50,7 @@ export class TestGroup extends TestBlock {
return [...this.testCases.values()];
}

public modifyAssertions(testCase: TestCase, noEarlyExit: boolean, editor: AstEditor, namespaceLookup: Map<string, NamespaceContainer>) {
public modifyAssertions(testCase: TestCase, noEarlyExit: boolean, editor: Editor, namespaceLookup: Map<string, NamespaceContainer>) {
//for each method
//if assertion
//wrap with if is not fail
Expand Down Expand Up @@ -95,7 +95,7 @@ export class TestGroup extends TestBlock {
}
}

private modifyModernRooibosExpectCallExpression(callExpression: CallExpression, editor: AstEditor, namespaceLookup: Map<string, NamespaceContainer>) {
private modifyModernRooibosExpectCallExpression(callExpression: CallExpression, editor: Editor, namespaceLookup: Map<string, NamespaceContainer>) {
let isNotCalled = false;
let isStubCall = false;
if (isDottedGetExpression(callExpression.callee)) {
Expand Down
4 changes: 2 additions & 2 deletions bsc-plugin/src/lib/rooibos/TestSuite.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { AstEditor, BrsFile, ClassStatement } from 'brighterscript';
import type { Editor, BrsFile, ClassStatement } from 'brighterscript';

import { diagnosticNodeTestIllegalNode, diagnosticNodeTestRequiresNode } from '../utils/Diagnostics';

Expand Down Expand Up @@ -100,7 +100,7 @@ export class TestSuite extends TestBlock {
this.isValid = true;
}

public addDataFunctions(editor: AstEditor) {
public addDataFunctions(editor: Editor) {
if (this.isIncluded) {
addOverriddenMethod(this.file, this.annotation.annotation, this.classStatement, 'getTestSuiteData', `return ${this.asText()}`, editor);
}
Expand Down
8 changes: 4 additions & 4 deletions bsc-plugin/src/lib/rooibos/Utils.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import type { BrsFile, ClassStatement, Expression, FunctionStatement, Statement, AnnotationExpression, AstEditor } from 'brighterscript';
import type { BrsFile, ClassStatement, Expression, FunctionStatement, Statement, AnnotationExpression, Editor } from 'brighterscript';
import * as brighterscript from 'brighterscript';
import { diagnosticCorruptTestProduced } from '../utils/Diagnostics';
import { SourceNode } from 'source-map';

export function overrideAstTranspile(editor: AstEditor, node: Expression | Statement, value: string) {
export function overrideAstTranspile(editor: Editor, node: Expression | Statement, value: string) {
editor.setProperty(node, 'transpile', function transpile(this: Expression | Statement, state) {
//indent every line with the current transpile indent level (except the first line, because that's pre-indented by bsc)
let source = value.replace(/\r?\n/g, (match, newline) => {
Expand All @@ -19,7 +19,7 @@ export function overrideAstTranspile(editor: AstEditor, node: Expression | State
});
}

export function addOverriddenMethod(file: BrsFile, annotation: AnnotationExpression, target: ClassStatement, name: string, source: string, editor: AstEditor): boolean {
export function addOverriddenMethod(file: BrsFile, annotation: AnnotationExpression, target: ClassStatement, name: string, source: string, editor: Editor): boolean {
let functionSource = `
function ${name}()
${source}
Expand All @@ -36,7 +36,7 @@ export function addOverriddenMethod(file: BrsFile, annotation: AnnotationExpress
let n = brighterscript.createIdentifier(name, target.range);
let method = new brighterscript.ClassMethodStatement(p, n, statement.func, o);
//bsc has a quirk where it auto-adds a `new` method if missing. That messes with our AST editing, so
//trigger that functionality BEFORE performing AstEditor operations. TODO remove this whenever bsc stops doing this.
//trigger that functionality BEFORE performing Editor operations. TODO remove this whenever bsc stops doing this.
// eslint-disable-next-line @typescript-eslint/dot-notation
target['ensureConstructorFunctionExists']?.();
editor.addToArray(target.body, target.body.length, method);
Expand Down
Loading

0 comments on commit 536782e

Please sign in to comment.