piston/api/src/runtime.js

72 lines
2.3 KiB
JavaScript
Raw Normal View History

2021-02-20 23:39:03 +01:00
const logger = require('logplease').create('runtime');
const semver = require('semver');
const config = require('./config');
const globals = require('./globals');
const fss = require('fs');
const path = require('path');
2021-02-20 15:13:56 +01:00
2021-02-20 23:39:03 +01:00
const runtimes = [];
2021-02-20 15:13:56 +01:00
class Runtime {
#env_vars
#compiled
constructor(package_dir){
2021-03-06 07:17:56 +01:00
const {language, version, author, build_platform, aliases} = JSON.parse(
2021-02-20 23:39:03 +01:00
fss.read_file_sync(path.join(package_dir, 'pkg-info.json'))
);
2021-02-20 15:13:56 +01:00
2021-02-20 23:39:03 +01:00
this.pkgdir = package_dir;
this.language = language;
this.version = semver.parse(version);
this.author = author;
2021-03-06 07:17:56 +01:00
this.aliases = aliases;
2021-02-20 15:13:56 +01:00
if(build_platform != globals.platform){
2021-02-20 23:39:03 +01:00
logger.warn(`Package ${language}-${version} was built for platform ${build_platform}, but our platform is ${globals.platform}`);
2021-02-20 15:13:56 +01:00
}
2021-02-20 23:39:03 +01:00
logger.debug(`Package ${language}-${version} was loaded`);
runtimes.push(this);
2021-02-20 15:13:56 +01:00
}
get env_file_path(){
2021-03-06 07:17:56 +01:00
return path.join(this.pkgdir, 'environment');
2021-02-20 15:13:56 +01:00
}
get compiled(){
2021-02-20 23:39:03 +01:00
if(this.#compiled === undefined) this.#compiled = fss.exists_sync(path.join(this.pkgdir, 'compile'));
return this.#compiled;
2021-02-20 15:13:56 +01:00
}
get env_vars(){
if(!this.#env_vars){
2021-02-20 23:39:03 +01:00
const env_file = path.join(this.pkgdir, '.env');
const env_content = fss.read_file_sync(env_file).toString();
this.#env_vars = {};
2021-02-20 15:13:56 +01:00
env_content
2021-02-21 00:57:20 +01:00
.trim()
2021-02-20 23:39:03 +01:00
.split('\n')
.map(line => line.split('=',2))
2021-02-20 15:13:56 +01:00
.forEach(([key,val]) => {
2021-02-21 00:57:20 +01:00
this.#env_vars[key.trim()] = val.trim();
2021-02-20 23:39:03 +01:00
});
2021-02-20 15:13:56 +01:00
}
2021-02-20 23:39:03 +01:00
return this.#env_vars;
2021-02-20 15:13:56 +01:00
}
toString(){
2021-02-20 23:39:03 +01:00
return `${this.language}-${this.version.raw}`;
2021-02-20 15:13:56 +01:00
}
}
2021-02-20 23:39:03 +01:00
module.exports = runtimes;
module.exports.Runtime = Runtime;
2021-02-20 15:13:56 +01:00
module.exports.get_runtimes_matching_language_version = function(lang, ver){
2021-03-06 07:17:56 +01:00
return runtimes.filter(rt => (rt.language == lang || rt.aliases.includes(lang)) && semver.satisfies(rt.version, ver));
2021-02-20 23:39:03 +01:00
};
2021-02-20 15:13:56 +01:00
module.exports.get_latest_runtime_matching_language_version = function(lang, ver){
return module.exports.get_runtimes_matching_language_version(lang, ver)
2021-02-20 23:39:03 +01:00
.sort((a,b) => semver.rcompare(a.version, b.version))[0];
};
2021-02-20 15:13:56 +01:00