Skip to content

Commit

Permalink
minor update in builder
Browse files Browse the repository at this point in the history
  • Loading branch information
metelkin committed Sep 9, 2024
1 parent 0581be0 commit 97ec2b9
Show file tree
Hide file tree
Showing 5 changed files with 40 additions and 51 deletions.
12 changes: 6 additions & 6 deletions bin/heta-build.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ const program = new Command();
const fs = require('fs');
const path = require('path');
const { Builder } = require('../src');
const { load } = require('js-yaml'); // https://www.npmjs.com/package/js-yaml
const YAML = require('js-yaml'); // https://www.npmjs.com/package/js-yaml
const semver = require('semver');
const { version, bugs } = require('../package');
const colors = require('colors');
Expand Down Expand Up @@ -70,7 +70,7 @@ async function main() {
process.stdout.write(`Running compilation with declaration file "${declarationFile}"...\n`);
let declarationText = fs.readFileSync(declarationFile);
try {
let declarationFromFile = load(declarationText);
let declarationFromFile = YAML.load(declarationText);
if (typeof declarationFromFile !== 'object'){
throw new Error('Not an object.');
}
Expand All @@ -82,17 +82,17 @@ async function main() {
}

// parse export
let export1 = opts.export?.replace(/:/g, ': ');
let exportYAML = '[' + opts.export?.replace(/:/g, ': ') + ']';
try {
var formats = load(`[${export1}]`).map((x) => {
var exportItems = YAML.load(exportYAML).map((x) => {
if (typeof x === 'string') {
return { format: x };
} else {
return x;
}
});
} catch (e) {
process.stdout.write(`Wrong format of export option: "${formats}"\n`);
process.stdout.write(`Wrong format of export option: "${exportYAML}"\n`);
process.exit(2); // BRAKE
}

Expand All @@ -104,7 +104,7 @@ async function main() {
opts.metaDir !== undefined && (declaration.options.metaDir = opts.metaDir);
opts.source !== undefined && (declaration.importModule.source = opts.source);
opts.type !== undefined && (declaration.importModule.type = opts.type);
opts.export !== undefined && (declaration.export = formats);
opts.export !== undefined && (declaration.export = exportItems);

// === wrong version throws, if no version stated than skip ===
let satisfiesVersion = declaration.builderVersion
Expand Down
31 changes: 15 additions & 16 deletions src/builder/declaration-schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"$schema": "http://json-schema.org/schema#",
"description" : "Describes platform.json file in Heta compiler.",
"type": "object",
"required": ["options", "importModule"],
"required": ["options", "importModule", "export"],
"additionalProperties": true,
"properties": {
"id": {"type": "string"},
Expand Down Expand Up @@ -47,6 +47,7 @@
},
"importModule": {
"type": "object",
"default": {"type": "heta", "source": "index.heta"},
"additionalProperties": true,
"properties": {
"type": {"type": "string", "enum": ["heta", "table", "xlsx", "json", "yaml", "sbml"], "default": "heta"},
Expand All @@ -55,22 +56,20 @@
"omitRows": { "type": "integer", "minimum": 0 }
}
},
"export": { "oneOf": [
{ "type": "null" },
{
"type": "array",
"items": {
"type": "object",
"required": ["format"],
"additionalProperties": true,
"properties": {
"id": { "type": "string" },
"format": { "type": "string" },
"filepath": { "type": "string" },
"spaceFilter": { "type": "string" }
}
"export": {
"type": "array",
"default": [],
"items": {
"type": "object",
"required": ["format"],
"additionalProperties": true,
"properties": {
"id": { "type": "string" },
"format": { "type": "string" },
"filepath": { "type": "string" },
"spaceFilter": { "type": "string" }
}
}
]}
}
}
}
34 changes: 18 additions & 16 deletions src/builder/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,63 +34,65 @@ const { StdoutTransport } = require('../logger');
* @property ... Other properties inherit from `declaration` object, see
* [CLI references]{@link https://hetalang.github.io/#/heta-compiler/cli-references?id=declaration-file-format}
* @property {object} _exportClasses map-like structure for storing all available constructors describing `_Export`s.
* @property {object[]} export Storage for `_Export` instances.
* @property {object} exportClasses the same as `_exportClasses` but bound to this builder.
* @property {object[]} exportArray Storage for `_Export` instances.
*/
class Builder {
constructor(declaration, coreDirname = '.'){
constructor(declaration = {}, coreDirname = '.') {

// create container
this.container = new Container();
this.container._builder = this; // back reference to parent builder
this.export = []; // storing Export objects
this.exportClasses = {}; // storing Export classes bound to builder (XXX: maybe it must be static)

// set transport and logger
this.logger = this.container.logger;
let minLogLevel = declaration?.options?.logLevel || 'info';
this.logger.addTransport(new StdoutTransport(minLogLevel));
let logger = this.logger = this.container.logger;
let minLogLevel = declaration?.options?.logLevel || 'info'; // use logLevel before declaration check
logger.addTransport(new StdoutTransport(minLogLevel));

// check based on schema
// XXX: move to heta-build.js ?
// check based on schema, use default values from schema
let validate = ajv.compile(declarationSchema);
let valid = validate(declaration);
if (!valid) {
// convert validation errors to heta errors
validate.errors.forEach((x) => {
this.logger.error(`${x.dataPath} ${x.message}`, {type: 'BuilderError'});
logger.error(`${x.dataPath} ${x.message}`, {type: 'BuilderError'});
});
throw new HetaLevelError('Wrong structure of platform file.');
}

// file paths
// assign from declaration
Object.assign(this, declaration);

// resolve file paths to absolute
this._coreDirname = path.resolve(coreDirname);
this._distDirname = path.resolve(coreDirname, declaration.options.distDir);
this._metaDirname = path.resolve(coreDirname, declaration.options.metaDir);
this._logPath = path.resolve(coreDirname, declaration.options.logPath);

this.logger.info(`Builder initialized in directory "${this._coreDirname}".`);
if (this.id) this.logger.info(`Platform id: "${this.id}"`);
logger.info(`Builder initialized in directory "${this._coreDirname}".`);
if (this.id) logger.info(`Platform id: "${this.id}"`);

// create "export" classes bound to this container
Builder._exportClasses && Object.entries(Builder._exportClasses).forEach(([key, _Class]) => {
Object.entries(Builder._exportClasses).forEach(([key, _Class]) => {
this.exportClasses[key] = class extends _Class {};
this.exportClasses[key].prototype._builder = this;
});

this.exportArray = [];
// create "export" instances
declaration.export && declaration.export.forEach((exportItem) => {
declaration.export.forEach((exportItem) => {
let ExportClass = this.exportClasses.hasOwnProperty(exportItem.format)
&& this.exportClasses[exportItem.format];
if (ExportClass) {
this.exportArray.push(new ExportClass(exportItem));
} else {
this.logger.error(`Export format "${exportItem.format}" is not supported.`, {type: 'BuilderError'});
logger.error(`Export format "${exportItem.format}" is not supported.`, {type: 'BuilderError'});
}
});
}

static _exportClasses = {}; // storing abstract Export classes
exportClasses = {}; // storing Export classes bound to builder

/**
* The method runs building of a platform declared with `Builder` object.
Expand Down
12 changes: 0 additions & 12 deletions test/builder/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,22 +12,10 @@ describe('Test Builder.', () => {
});

describe('Errors in declaration.', () => {
it('Empty declaration throws.', () => {
expect(() => {
let b = new Builder({options: {logLevel: 'panic'}});
}).to.throw();
//expect(b.container.hetaErrors()).to.be.lengthOf(1);
});
it('Wrong prop type.', () => {
expect(() => {
let b = new Builder({id: 'test', notes: 1.1, options: {logLevel: 'panic'}});
}).to.throw();
//expect(b.container.hetaErrors()).to.be.lengthOf(1);
});
it('Wrong version format.', () => {
expect(() => {
let b = new Builder({id: 'test', builderVersion: '0.100.0', options: {logLevel: 'panic'}});
}).to.throw();
//expect(b.container.hetaErrors()).to.be.lengthOf(1);
});
});
2 changes: 1 addition & 1 deletion test/export/export-check.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ const { Builder } = require('../../src');
const { expect } = require('chai');

describe('General argument checking', () => {
const b = new Builder({importModule: {}});
const b = new Builder();
const p = b.container;

it('Create JSON Export directly', () => {
Expand Down

0 comments on commit 97ec2b9

Please sign in to comment.