Skip to content

Commit

Permalink
use file handlers
Browse files Browse the repository at this point in the history
  • Loading branch information
metelkin committed Sep 10, 2024
1 parent 082a2a8 commit 2a35d07
Show file tree
Hide file tree
Showing 5 changed files with 27 additions and 24 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"description": "Programming platform for Quantitative Systems Pharmacology modeling in NodeJS",
"main": "src/index.js",
"scripts": {
"test:dev": "mocha test/cases/0 --config=./test/.mocharc.json",
"test:dev": "mocha test/cases/14 --config=./test/.mocharc.json",
"test": "mocha test --config=./test/.mocharc.json",
"jsdoc": "jsdoc -r -c .jsdoc.json --readme api-references.md -d docs/dev src",
"test:cov": "nyc --reporter=lcov npm run test",
Expand Down
25 changes: 16 additions & 9 deletions src/builder/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,12 @@ const { StdoutTransport } = require('../logger');
* @property {object[]} exportArray Storage for `_Export` instances.
*/
class Builder {
constructor(declaration = {}, coreDirname = '.') {

constructor(
declaration = {},
coreDirname = '.',
fileReadHandler = (fn) => fs.readFileSync(fn), // return text
fileWriteHandler = (fn, text) => fs.outputFileSync(fn, text) // return undefined
) {
// create container
this.container = new Container();
this.container._builder = this; // back reference to parent builder
Expand All @@ -49,6 +53,10 @@ class Builder {
let minLogLevel = declaration?.options?.logLevel || 'info'; // use logLevel before declaration check
logger.addTransport(new StdoutTransport(minLogLevel));

// file handlers
this.fileReadHandler = fileReadHandler;
this.fileWriteHandler = fileWriteHandler;

// check based on schema, use default values from schema
let validate = ajv.compile(declarationSchema);
let valid = validate(declaration);
Expand Down Expand Up @@ -115,12 +123,11 @@ class Builder {
* @method Builder#run
*
*/
run(){
run() {
this.logger.info(`Compilation of module "${this.importModule.source}" of type "${this.importModule.type}"...`);

// 1. Parsing
let fileHandler = (filename) => fs.readFileSync(filename);
let ms = new ModuleSystem(this.container.logger, fileHandler);
let ms = new ModuleSystem(this.logger, this.fileReadHandler);
let absFilename = path.join(this._coreDirname, this.importModule.source);
ms.addModuleDeep(absFilename, this.importModule.type, this.importModule);

Expand All @@ -130,7 +137,7 @@ class Builder {
let relPath = path.relative(this._coreDirname, name + '.json');
let absPath = path.join(this._metaDirname, relPath);
let str = JSON.stringify(ms.moduleCollection[name], null, 2);
fs.outputFileSync(absPath, str);
this.fileWriteHandler(absPath, str);
this.logger.info(`Meta file was saved to ${absPath}`);
});
}
Expand Down Expand Up @@ -187,7 +194,7 @@ class Builder {
.join('\n');
}

fs.outputFileSync(this._logPath, logs);
this.fileWriteHandler(this._logPath, logs);
this.logger.info(`All logs was saved to file: "${this._logPath}"`);
}
return;
Expand All @@ -206,15 +213,15 @@ class Builder {
}

function _makeAndSave(exportItem, pathPrefix) {
let { logger } = exportItem._builder;
let { logger, fileWriteHandler } = exportItem._builder;
let absPath = path.resolve(pathPrefix, exportItem.filepath);
let msg = `Exporting to "${absPath}" of format "${exportItem.format}"...`;
logger.info(msg);

exportItem.make().forEach((out) => {
let filePath = [absPath, out.pathSuffix].join('');
try {
fs.outputFileSync(filePath, out.content);
fileWriteHandler(filePath, out.content);
} catch (err) {
let msg =`Heta compiler cannot export to file: "${err.path}": ${err.message}`;
logger.error(msg, {type: 'ExportError'});
Expand Down
16 changes: 6 additions & 10 deletions src/container/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ class Container {
load(q, isCore = false){
// estimate action, default is upsert
let actionName = q.action || 'upsert';
if (typeof this[actionName] !== 'function') {
if (!this[actionName] || typeof this[actionName] !== 'function') {
this.logger.error(
`Action #${actionName} is unknown and will be skipped.`,
{type: 'QError', action: actionName}
Expand Down Expand Up @@ -147,11 +147,10 @@ class Container {
* @returns {number} Total number of components + `UnitDef` + `Functiondef` + `Scenario`.
*/
get length(){
return [...this.namespaceStorage]
.reduce((acc, x) => acc + x[1].size, 0)
+ this.unitDefStorage.size // global elements
+ this.functionDefStorage.size
+ this.scenarioStorage.size;
return [...this.namespaceStorage].reduce((acc, x) => acc + x[1].size, 0) // number of components in all namespaces
+ this.unitDefStorage.size // number of UnitDef
+ this.functionDefStorage.size // number of FunctionDef
+ this.scenarioStorage.size; // number of Scenario
}

/**
Expand All @@ -166,10 +165,7 @@ class Container {
// knit functionDef
this.functionDefStorage.forEach((fd) => fd.bind());
// knit components, only for concrete namespace
this.namespaceStorage.forEach((ns) => {
// knit only concrete namespace
if (!ns.isAbstract) ns.knit();
});
this.namespaceStorage.forEach((ns) => !ns.isAbstract && ns.knit());
// knit scenario
this.scenarioStorage.forEach((sc) => sc.bind());

Expand Down
6 changes: 3 additions & 3 deletions src/module-system/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,13 @@ class ModuleSystem {
* @property {Logger} logger Object to analyze log events.
* @property {_Module} _top Top-level module. Usually created from `index.heta` file.
*/
constructor(logger, fileHandler){
constructor(logger, fileReadHandler){
// stores modules in format
// { filepath : module, ...}
this.moduleCollection = {};
this.graph = new TopoSort();
this.logger = logger;
this.fileHandler = fileHandler;
this.fileReadHandler = fileReadHandler;
}

/**
Expand Down Expand Up @@ -137,7 +137,7 @@ class ModuleSystem {
}

try {
let fileContent = this.fileHandler(filename);
let fileContent = this.fileReadHandler(filename);
var parsed = loader(fileContent, options);
} catch (e) {
if (e.name === 'HetaLevelError') {
Expand Down
2 changes: 1 addition & 1 deletion test/cases/14.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/* global describe, it */

const { Builder } = require('../../src/builder');
const { Builder } = require('../../src');
const { expect, use } = require('chai');

const json_correct = require('../../cases/14-sbml-module/master/output.json');
Expand Down

0 comments on commit 2a35d07

Please sign in to comment.