Skip to content

Commit

Permalink
exclude coreDirname
Browse files Browse the repository at this point in the history
  • Loading branch information
metelkin committed Jan 14, 2025
1 parent 75b1ceb commit 7c298fe
Show file tree
Hide file tree
Showing 21 changed files with 72 additions and 206 deletions.
37 changes: 30 additions & 7 deletions bin/heta-build.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ const { Command } = require('commander');
const program = new Command();
const fs = require('fs-extra');
const path = require('path');
const { Builder, StdoutTransport } = require('../src');
const { Builder, StdoutTransport, Transport } = require('../src');
const YAML = require('js-yaml'); // https://www.npmjs.com/package/js-yaml
const { bugs } = require('../package');
const colors = require('colors');
Expand All @@ -32,7 +32,6 @@ program
.option('--log-level <debug|info|warn|error|crit>', 'Set log level to display.')
// options
.option('--units-check', 'Check all Records for unit consistency.')
.option('-L, --log-mode <never|error|always>', 'When to create log file.')
.option('--debug', 'If set the raw module output will be stored in "meta".')
.option('--dist-dir <filepath>', 'Set export directory path, where to store exported files.')
.option('--meta-dir <filepath>', 'Set meta directory path.')
Expand All @@ -42,6 +41,8 @@ program
.option('-e, --export <formats>', 'export formats: "JSON,XLSX" or "{format:JSON},{format:XLSX,omitRows:3}"')
// checking newer version of heta-compiler
.option('--skip-updates', 'Skip checking newer version of heta-compiler.')
.option('-L, --log-mode <never|error|always>', 'When to create log file.', 'error')
.option('--log-path <filepath>', 'Set log file path.', 'build.log')
.parse(process.argv);

async function main() {
Expand All @@ -56,6 +57,9 @@ async function main() {
}
process.stdout.write(`Running compilation in directory "${path.resolve(targetDir)}"...\n`); // global path

// set targetDir as working directory
process.chdir(targetDir);

// set minimal log level
let logLevel = cliOptions.logLevel || 'info';

Expand All @@ -67,7 +71,6 @@ async function main() {
let searches = ['', '.json', '.yml']
.map((ext) => (cliOptions.declaration || 'platform') + ext);
let extensionNumber = searches
.map((filename) => path.join(targetDir, filename)) // add targetDir
.map((x) => fs.existsSync(x) && fs.statSync(x).isFile() ) // check if it exist and is file
.indexOf(true);
// is declaration file found ?
Expand All @@ -79,7 +82,7 @@ async function main() {
} else {
let declarationFile = searches[extensionNumber];
process.stdout.write(`Reading declaration file "${declarationFile}"...\n`);
let declarationText = fs.readFileSync(path.join(targetDir, declarationFile));
let declarationText = fs.readFileSync(declarationFile);
try {
let declarationFromFile = YAML.load(declarationText);
if (typeof declarationFromFile !== 'object'){
Expand All @@ -103,7 +106,6 @@ async function main() {

// update declaration
cliOptions.unitsCheck !== undefined && (declaration.options.unitsCheck = cliOptions.unitsCheck);
cliOptions.logMode !== undefined && (declaration.options.logMode = cliOptions.logMode);
cliOptions.debug !== undefined && (declaration.options.debug = cliOptions.debug);
cliOptions.distDir !== undefined && (declaration.options.distDir = cliOptions.distDir);
cliOptions.metaDir !== undefined && (declaration.options.metaDir = cliOptions.metaDir);
Expand All @@ -114,15 +116,30 @@ async function main() {
// 3. run builder (set declaration defaults internally)
let builder = new Builder(
declaration,
targetDir,
fs.readFileSync,
fs.outputFileSync,
[new StdoutTransport(logLevel)]
[
new StdoutTransport(logLevel), // log to stdout
new FileTransport('debug', cliOptions.logPath) // log to file
]
).run();

return builder;
}

class FileTransport extends Transport {
constructor(level, filepath) {
super(level);
this.logStream = fs.createWriteStream(filepath, { flags: 'w' }); // or 'a' to append
}
analyzer(level, msg, opt, levelNum) {
if (levelNum >= this.showLevelNum) {
let line = `[${level}]\t${msg}`;
this.logStream.write(line + '\n');
}
}
}

function parseExportOption(value = '') {
let exportYAML = '[' + value.replace(/:/g, ': ') + ']';
var exportItems = YAML.load(exportYAML).map((x) => {
Expand All @@ -141,20 +158,26 @@ Promise.all([
main(),
!program.opts().skipUpdates && printVersionMessage()
]).then(([builder]) => {
const {logMode, logPath} = program.opts();
if (builder.container.hetaErrors().length > 0) {
process.stdout.write('Compilation ERROR! See logs.\n');
logMode !== 'never' && fs.removeSync(logPath);
process.exit(2);
} else {
process.stdout.write('Compilation OK!\n');
logMode !== 'always' && fs.removeSync(logPath);
process.exit(0);
}
}).catch((error) => {
const {logMode, logPath} = program.opts();
if (error.name === 'HetaLevelError') {
process.stdout.write('Error: ' + error.message + '\nSTOP!\n');
logMode !== 'never' && fs.removeSync(logPath);
process.exit(2);
} else {
process.stdout.write(contactMessage + '\n');
process.stdout.write(error.stack);
logMode !== 'never' && fs.removeSync(logPath);
process.exit(1); // unexpected error
}
});
1 change: 0 additions & 1 deletion bin/heta-init.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ const defaultPlatform = {
builderVersion: '^' + pkg.version,
options: {
debug: false,
logPath: 'output.log',
unitsCheck: false
},
//script: {
Expand Down
2 changes: 1 addition & 1 deletion build-win-installer/perUser.wxs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ perUser: does not require elevated privileges to install. Sets the package's Ins
<Control Id="InstallScopeDescription" Type="Text" X="25" Y="25" Width="320" Height="15" Text="Select the installation scope for this application:" />
<Control Id="ScopeType" Type="RadioButtonGroup" X="25" Y="65" Width="320" Height="40" Property="EVERYBODY">
<RadioButtonGroup Property="EVERYBODY">
<RadioButton Value="yes" X="0" Y="0" Width="300" Height="17" Text="All users (requires administrative rights)" />
<RadioButton Value="yes" X="0" Y="0" Width="300" Height="17" Text="All users (requires administrative permission)" />
<RadioButton Value="no" X="0" Y="20" Width="300" Height="17" Text="Just me" />
</RadioButtonGroup>
</Control>
Expand Down
1 change: 0 additions & 1 deletion cases/10-functions/platform.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
"license": "UNLICENSED",
"options": {
"debug": false,
"logPath": "output.log",
"unitsCheck": false
},
"importModule": {
Expand Down
3 changes: 1 addition & 2 deletions cases/12-to-sbml/platform.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,7 @@
"version": "v0.1.0",
"license": "UNLICENSED",
"options": {
"debug": false,
"logPath": "output.log"
"debug": false
},
"importModule": {
"type": "heta",
Expand Down
1 change: 0 additions & 1 deletion cases/16-d-switcher/platform.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
"license": "UNLICENSED",
"options": {
"debug": false,
"logPath": "output.log",
"unitsCheck": false
},
"importModule": {
Expand Down
3 changes: 1 addition & 2 deletions cases/17-multispace/platform.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@
"builderVersion": "*",
"id": "template",
"options": {
"debug": false,
"logPath": "output.log"
"debug": false
},
"importModule": {
"type": "heta",
Expand Down
1 change: 0 additions & 1 deletion cases/20-syntax/platform.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
"license": "UNLICENSED",
"options": {
"debug": false,
"logPath": "output.log",
"unitsCheck": false
},
"importModule": {
Expand Down
1 change: 0 additions & 1 deletion cases/30-sbml-annotation/platform.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
builderVersion: ^0.8.7,
options: {
debug: false,
logPath: output.log,
unitsCheck: false
},
importModule: {
Expand Down
1 change: 0 additions & 1 deletion cases/31-avogadro/platform.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
builderVersion: ^0.9.1,
options: {
debug: false,
logPath: output.log,
unitsCheck: false
},
importModule: {
Expand Down
7 changes: 2 additions & 5 deletions cli-references.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,8 @@ List of `heta build` options:
| --units-check | | | If set all records will be checked for units consistency. |
| --dist-dir | \<string\> | | Set export directory path, where to store exported files. Path can be absolute or relative to the project directory. |
| --meta-dir | \<string\> | | Set meta directory path. Path can be absolute or relative to the project directory.|
| --log-mode | string | error | The rule in which case the log file should be created. Possible values are: never/error/always. Path can be absolute or relative to the project directory. |
| --log-mode | string | error | The rule in which case the log file should be saved to file. Possible values are: never/error/always. Path can be absolute or relative to the project directory. |
| --log-path | string | build.log | Filepath where the log file should be saved. Path can be absolute or relative to the project directory. |
| -d, --declaration | string | platform | The filepath to declaration file (see below) without extension. The command will search the declaration file based on option trying a set of extensions: .json/.yml. |
| --log-level | string | error | The level of log information to display. Possible values are: error/warn/info/debug. |
| --skip-updates | | | Do not check available new version in npm. |
Expand Down Expand Up @@ -191,8 +192,6 @@ There are properties in declaration file which do not change compilation process
| importModule.source | string | --source | index.heta | Path to index heta module. Absolute and relative filepaths are applicable. Example: "src/table.xlsx" |
| importModule.type | string | --type | heta | Type of source file. This option set type of module which will be applied for parsing. Available values: heta/xlsx/json/yaml/sbml. |
| options | object | | {} | A set of compiler options. |
| options.logMode | string | --log-mode | error | The rule in which case the log file should be created. Possible values are: never/error/always. |
| options.logPath | string | | build.log | Filepath where the log file should be created. |
| options.logFormat | string | | `string` | The format of saving logs to file. The default value is `string` which corresponds the format similar to console. Full list of options is : `string`, `json`.|
| options.unitsCheck | boolean | --units-check | false | If `true` all Record will be checked for units consistency. |
| options.distDir | string | --dist-dir | dist | At default all export files are created inside **dist** directory. The option can set the another target for storing outputs. |
Expand All @@ -205,8 +204,6 @@ Using neither declaration file nor CLI options is equivalent to the following de
{
"builderVersion": "<current buider version>",
"options": {
"logMode": "error",
"logPath": "build.log",
"logFormat": "string",
"distDir": "dist",
"metaDir": "meta",
Expand Down
2 changes: 0 additions & 2 deletions src/builder/declaration-schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,6 @@
"errorMessage": "${0#} is unknown key in options"
},
"properties": {
"logMode": {"type": "string", "default": "error", "enum": ["never", "error", "always"]},
"logPath": {"type": "string", "default": "build.log"},
"logFormat": {"type": "string", "default": "string", "enum": ["string", "json"]},
"unitsCheck": {"type": "boolean", "default": false},
"distDir": {"type": "string", "default": "dist" },
Expand Down
33 changes: 10 additions & 23 deletions src/builder/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,17 +19,13 @@ const { version } = require('../../package');
* @param {Object} declaration - Object representing options for builder,
* see [CLI references]{@link https://hetalang.github.io/#/heta-compiler/cli-references}
* for more information about the structure.
* @param {string} coreDirname="." - Path of working directory of a Heta platform. Default: working directory of a shell.
*
* @property {Container} container This is the reference to the main platform storage.
* @property {Logger} logger Reference to logger object of platform. This object can also be called with `this.container.logger`
* @property {string} _coreDirname Absolute path of the core directory. Calculated from `coreDirname` parameter.
* @property {string} _distDirname Absolute path of the directory for exporting files.
* Calculated from `declaration.options.distDir` property.
* @property {string} _metaDirname Absolute path of the directory for storing meta files.
* Calculated from `declaration.options.metaDir`.
* @property {string} _logPath Absolute path of log file.
* Calculated from `declaration.options.logPath`.
* @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.
Expand All @@ -39,7 +35,6 @@ const { version } = require('../../package');
class Builder {
constructor(
declaration = {},
coreDirname = '.',
fileReadHandler = (fn) => { throw new Error('File read is not set for Builder'); }, // must return text
fileWriteHandler = (fn, text) => { throw new Error('File write is not set for Builder'); }, // must return undefined
transportArray = [] // Builder-level Transport
Expand Down Expand Up @@ -82,17 +77,9 @@ class Builder {
// assign from declaration
Object.assign(this, declaration);

// all relative or absolute depending on coreDirname
this._coreDirname = coreDirname; // relative to the shell or absolute
this._distDirname = path.isAbsolute(declaration.options.distDir)
? declaration.options.distDir // absolute path
: path.join(this._coreDirname, declaration.options.distDir); // relative to the shell
this._metaDirname = path.isAbsolute(declaration.options.metaDir)
? declaration.options.metaDir // absolute path
: path.join(this._coreDirname, declaration.options.metaDir); // relative to the shell
this._logPath = path.isAbsolute(declaration.options.logPath)
? declaration.options.logPath // absolute path
: path.join(this._coreDirname, declaration.options.logPath); // relative to the shell
// set directories
this._distDirname = declaration.options.distDir;
this._metaDirname = declaration.options.metaDir;

logger.info(`Heta compiler v${version} is initialized for the platform "${this.id}"`);

Expand Down Expand Up @@ -152,17 +139,15 @@ class Builder {
this.logger.error(`Import module source must be relative, got "${this.importModule.source}".`, {type: 'BuilderError'});
throw new HetaLevelError('Import module source must be relative.');
}
let sourcePath = path.join(this._coreDirname, this.importModule.source);
ms.addModuleDeep(sourcePath, this.importModule.type, this.importModule);
ms.addModuleDeep(this.importModule.source, this.importModule.type, this.importModule);

// 2. Modules integration
if (this.options.debug) {
Object.getOwnPropertyNames(ms.moduleCollection).forEach((name) => {
let relPath = path.relative(this._coreDirname, name + '.json');
let absPath = path.join(this._metaDirname, relPath);
Object.getOwnPropertyNames(ms.moduleCollection).forEach((sourcePath) => { // relative path, i.e. src/index.heta
let fullPath = path.join(this._metaDirname, sourcePath + '.json');
let str = JSON.stringify(ms.moduleCollection[name], null, 2);
this.fileWriteHandler(absPath, str);
this.logger.info(`Meta file was saved to ${absPath}`);
this.fileWriteHandler(fullPath, str);
this.logger.info(`Meta file was saved to ${fullPath}`);
});
}
let qArr = ms.integrate();
Expand Down Expand Up @@ -207,6 +192,7 @@ class Builder {
}

// 10. save logs if required
/*
let hetaErrors = this.container.hetaErrors();
let createLog = this.options.logMode === 'always'
|| (this.options.logMode === 'error' && hetaErrors.length > 0);
Expand All @@ -224,6 +210,7 @@ class Builder {
this.fileWriteHandler(this._logPath, logs);
this.logger.info(`All logs was saved to file: "${this._logPath}"`);
}
*/

return this;
}
Expand Down
4 changes: 3 additions & 1 deletion test/builder/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,10 @@ const fs = require('fs-extra');
describe('Test Builder.', () => {
let b;
it('Create Builder object and run.', () => {
b = new Builder(declaration, __dirname, fs.readFileSync, () => {});
process.chdir(__dirname);
b = new Builder(declaration, fs.readFileSync, () => {});
b.run();
process.chdir('../..');
});
});

Expand Down
4 changes: 3 additions & 1 deletion test/cases/0.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,11 +51,13 @@ describe('Testing "cases/0-hello-world"', () => {
{format: 'Mrgsolve', spaceFilter: '^mm$'},
{format: 'Julia', spaceFilter: '^mm$'}]
};
b = new Builder(declaration, 'cases/0-hello-world', fs.readFileSync, () => {});
process.chdir('cases/0-hello-world');
b = new Builder(declaration, fs.readFileSync, () => {});
});

it('Run include', () => {
b.run();
process.chdir('../..');
});

it('Run {format: SBML}, check and compare.', () => {
Expand Down
4 changes: 3 additions & 1 deletion test/cases/12.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,14 @@ describe('Testing "cases/12-to-sbml"', () => {
source: 'src/index.heta'
}
};
b = new Builder(declaration, 'cases/12-to-sbml', fs.readFileSync, () => {});
process.chdir('cases/12-to-sbml');
b = new Builder(declaration, fs.readFileSync, () => {});
//console.log(b);
});

it('Run include', () => {
b.run();
process.chdir('../..');
});

it('Run @SBMLExport, check and compare.', () => {
Expand Down
4 changes: 3 additions & 1 deletion test/cases/14.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ describe('Case #14: testing SBML module with units', () => {
let b;

it('Build platform', () => {
process.chdir('cases/14-sbml-module');
b = new Builder({
id: 'test',
builderVersion: '*',
Expand All @@ -22,8 +23,9 @@ describe('Case #14: testing SBML module with units', () => {
export: [
{format: 'JSON'}
]
}, 'cases/14-sbml-module', fs.readFileSync, () => {});
}, fs.readFileSync, () => {});
b.run();
process.chdir('../..');
expect(b.container.logger).to.have.property('hasErrors').false;
});

Expand Down
4 changes: 3 additions & 1 deletion test/cases/6.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,12 +27,14 @@ describe('Testing "cases/6-import"', () => {
{format: 'SBML', spaceFilter: 'model'},
]
};
b = new Builder(declaration, 'cases/6-import', fs.readFileSync, () => {});
process.chdir('cases/6-import');
b = new Builder(declaration, fs.readFileSync, () => {});
//console.log(b);
});

it('Run include', () => {
b.run();
process.chdir('../..');
exportArray = b.exportArray;
});

Expand Down
Loading

0 comments on commit 7c298fe

Please sign in to comment.