mediacentral-publish
Version:
A publish tool for publishing cloud-ux projects
410 lines (355 loc) • 16.8 kB
JavaScript
let optionsValidation = (() => {
var _ref = _asyncToGenerator(function* (options) {
logger.trace('Options passed to validation: ', (yield stripObjectFromOptions(options)));
if (!options.hasOwnProperty('project')) throw new Error("A project path not set!");
if (options.hasOwnProperty('build')) {
if (typeof options.build !== "boolean") {
throw new Error("Build needs to be bool!");
}
}
// --------------------- Docker proxy -----------------------------------
if (options.hasOwnProperty('https_proxy')) {
if (typeof options.https_proxy !== "string") {
throw new Error("Https_proxy needs to be string!");
}
if (options.https_proxy.length === 0) {
throw new Error("Https_proxy can not be empty string!");
}
}
// --------------------- Docker proxy END --------------------------------
if (options.hasOwnProperty('service')) {
if (typeof options.service !== "boolean") {
throw new Error("Service needs to be bool!");
}
}
if (typeof options.project !== 'string') throw new Error("A project path must be a string!");
if (!(yield fs.existsPromise(options.project))) throw new Error(`Path to a project (${options.project}) is invalid.`);
// ---------------------------------------Config ------------------------------------------
if (!options.hasOwnProperty('config')) {
throw new Error("A project config object not set!");
}
if (typeof options.config !== 'object') throw new Error("A config must be an object!");
if (!options.config.hasOwnProperty('version') || typeof options.config.version !== 'string') {
throw new Error("config.version must be string!");
}
if (!options.config.hasOwnProperty('organization') || typeof options.config.organization !== 'string') {
throw new Error("config.organization must be string!");
}
if (options.hasOwnProperty('build') && options.build === false) {
if (!(options.config.hasOwnProperty('privateKeyPath') && typeof options.config.privateKeyPath === 'string' && (yield fs.existsPromise(options.config.privateKeyPath)))) {
throw new Error("config.privateKeyPath must be valid path string!");
}
}
if (options.hasOwnProperty('buildImage')) {
if (typeof options.buildImage !== "boolean") {
throw new Error("buildImage needs to be bool!");
}
}
// appID and appSecret needs to be present for build / publish because without it app wont appear or publish correctly to marketplace
if (!options.config.hasOwnProperty('appID') || typeof options.config.appID !== 'string' || options.config.appID.length <= 10 || options.config.appID === 'your-app-id') {
throw new Error("config.appID must be not default string!");
}
// --------------------------------------END Config ---------------------------------------
if (!options.hasOwnProperty('name') || typeof options.name !== 'string') throw new Error("A project name not set!");
if (!options.name.match(/^([a-z0-9\-]{1,253})$/gm)) throw new Error("A project name should be up to maximum length of 253 characters and consist of lower case alphanumeric characters");
if (options.hasOwnProperty('didProgress') && typeof options.didProgress !== 'function') throw new Error("A didProgress must be a function!");
if (options.hasOwnProperty('password')) if (typeof options.password !== 'string') throw new Error("A password must be a string!");
if (options.password === undefined) options.password = '';
logger.info('----- Passed options are valid -----');
});
return function optionsValidation(_x) {
return _ref.apply(this, arguments);
};
})();
let getFeaturePack = (() => {
var _ref2 = _asyncToGenerator(function* (metadata, helm, docker, tag, output) {
logger.trace('starting getFeaturePack function');
return fp({
metadata,
helm,
docker,
tag,
output
});
});
return function getFeaturePack(_x2, _x3, _x4, _x5, _x6) {
return _ref2.apply(this, arguments);
};
})();
let doUpload = (() => {
var _ref3 = _asyncToGenerator(function* (manifest, pack, id) {
logger.trace('running doUpload function\nManifest:', manifest, '\nPackage', pack, '\nId', id);
return uploadProject({
manifest,
pack,
id
});
});
return function doUpload(_x7, _x8, _x9) {
return _ref3.apply(this, arguments);
};
})();
let doSign = (() => {
var _ref4 = _asyncToGenerator(function* (key, manifest, file, password, id) {
logger.trace('runnig doSign function');
return signManifest({
key,
manifest,
file,
password,
id
});
});
return function doSign(_x10, _x11, _x12, _x13, _x14) {
return _ref4.apply(this, arguments);
};
})();
let createWorkingDir = (() => {
var _ref5 = _asyncToGenerator(function* (projectDir) {
logger.trace('runnig createWorkingDir function with projectDir', projectDir);
do {
var name = path.join(projectDir, randomstring.generate());
} while (yield fs.existsPromise(name));
yield fs.mkdirPromise(name);
return normalize(path.resolve(name));
});
return function createWorkingDir(_x15) {
return _ref5.apply(this, arguments);
};
})();
let build = (() => {
var _ref6 = _asyncToGenerator(function* (config, doStep) {
logger.trace('running build Function with config: ', (yield stripObjectFromConfig(config)));
let docker, helm, metadata, featurePack;
// Option to build feature-pack for service.
if (config.service) {
docker = yield doStep('creating a docker save file', function () {
return buildDockerService(config.dir, config.projectDir, config.appName, config.version, config.organization, config.https_proxy);
});
helm = yield doStep('creating a helm chart file', function () {
return createChartService({
targetDir: config.dir,
projectName: config.appName,
version: config.version,
organization: config.organization,
chartDir: config.chartDir
});
});
} else {
docker = yield doStep('creating a docker save file', function () {
return buildDocker(config.dir, config.projectDir, config.appName, config.version, config.organization, config.https_proxy);
});
helm = yield doStep('creating a helm chart file', function () {
return createChart(config.dir, config.appName, config.version, config.organization);
});
}
metadata = yield doStep('creating a metadata file', function () {
return createMetadata(config.dir, config.appName, config.version, config.organization);
});
featurePack = yield doStep('creating a feature pack file', function () {
return getFeaturePack(metadata.file, helm.file, docker.file, config.tag, config.dir);
});
return {
docker: docker,
helm: helm,
metadata: metadata,
featurePack: featurePack
};
});
return function build(_x16, _x17) {
return _ref6.apply(this, arguments);
};
})();
let functionsFlow = (() => {
var _ref7 = _asyncToGenerator(function* (config, didProgress = function () {}) {
const doStep = function (totalSteps) {
return (() => {
var _ref8 = _asyncToGenerator(function* (name, step) {
// console.log(`${name}...`)
yield new Promise(function (r) {
return r(didProgress(null, name, totalSteps--));
});
return step().catch(function (err) {
return new Promise(function (r) {
return r(didProgress(err, name, 0));
}).then(function (data) {
throw new Error(`A error has occured during ${name}: ${err.message}`);
});
});
});
return function (_x19, _x20) {
return _ref8.apply(this, arguments);
};
})();
}(6);
let buildOut, docker, helm, metadata, featurePack, sign, upload, output;
try {
if (config.buildImage) {
buildOut = yield buildDockerImage(config, doStep);
docker = buildOut.docker;
output = 'Your docker image has been successfully builded.';
} else {
//TODO: Build feature-pack should be under /functions/buildFeaturePack refactor
buildOut = yield build(config, doStep);
docker = buildOut.docker;
helm = buildOut.helm;
metadata = buildOut.metadata;
featurePack = buildOut.featurePack;
if (config.build) {
const buildFile = path.join(config.projectDir, path.basename(featurePack.featurePackFile));
fs.copyFileSync(featurePack.featurePackFile, buildFile);
output = 'Your project has been successfully builded.';
} else {
// TODO: Publish should be separated function under functions/publish refactor
sign = yield doStep('signing a feature pack', function () {
return doSign(config.key, config.manifest, featurePack.featurePackFile, config.password, config.devID);
});
upload = yield doStep('uploading the project', function () {
return doUpload(config.manifest, featurePack.featurePackFile, config.appID);
});
output = 'Your project has been successfully published.';
}
}
doStep(output, _asyncToGenerator(function* () {}));
return {
config,
output,
docker,
helm,
metadata,
featurePack,
sign,
upload
};
} catch (e) {
e.docker = docker;
e.helm = helm;
e.metadata = metadata;
e.featurePack = featurePack;
e.sign = sign;
e.upload = upload;
e.config = config;
throw e;
}
});
return function functionsFlow(_x18) {
return _ref7.apply(this, arguments);
};
})();
let publish = (() => {
var _ref10 = _asyncToGenerator(function* (config, didProgress) {
config.dir = yield createWorkingDir(config.projectDir);
config.manifest = path.join(config.dir, 'manifest.json');
try {
return yield functionsFlow(config, didProgress);
} finally {
if (yield fs.existsPromise(config.dir)) {
fs.removePromise(config.dir).catch(function (err) {
if (err) logger.error(`Couldn't delete working dir ${err.path} (${err.code}).`);
});
}
}
});
return function publish(_x21, _x22) {
return _ref10.apply(this, arguments);
};
})();
let log4JsConfiguration = (() => {
var _ref11 = _asyncToGenerator(function* (projectPath) {
yield isProjectPathValid(projectPath);
let config = require('../config/log4jsConfig').config;
config.appenders.app.filename = path.join(projectPath, 'log', 'appLog.log');
config.appenders.errorFile.filename = path.join(projectPath, 'log', 'errorLog.log');
try {
fsEx.ensureFileSync(config.appenders.app.filename);
log4js.configure(config);
} catch (err) {
log4js.configure(require('../config/log4jsConfigOnlyLogs').config);
logger.debug('Failed to create log files', err);
}
logger.trace(`----- Starting publish process -----`);
logger.trace(`System information: `, os.type(), ` `, os.release(), ` `, os.platform(), ` Node Information: `, process.versions);
});
return function log4JsConfiguration(_x23) {
return _ref11.apply(this, arguments);
};
})();
let stripObjectFromOptions = (() => {
var _ref12 = _asyncToGenerator(function* (optionsObject) {
const OBJECT_SCHEMA = joi.object().keys({
project: joi.string().allow(""),
config: {
version: joi.string().allow(""),
organization: joi.string().allow(""),
privateKeyPath: joi.string().allow(""),
appID: joi.string().allow(""),
developerID: joi.string().allow("")
},
name: joi.string().allow(""),
build: joi.boolean().allow(""),
service: joi.boolean().allow(""),
didProgress: joi.func().allow("")
});
const options = {
stripUnknown: true
};
return OBJECT_SCHEMA.validate(optionsObject, options).value;
});
return function stripObjectFromOptions(_x24) {
return _ref12.apply(this, arguments);
};
})();
let stripObjectFromConfig = (() => {
var _ref13 = _asyncToGenerator(function* (configObject) {
const OBJECT_SCHEMA = joi.object().keys({
tag: joi.string().allow(""),
devID: joi.string().allow(""),
version: joi.string().allow(""),
organization: joi.string().allow(""),
key: joi.string().allow(""),
appID: joi.string().allow(""),
appName: joi.string().allow(""),
projectDir: joi.string().allow(""),
build: joi.boolean().allow(""),
service: joi.boolean().allow(""),
dir: joi.string().allow(""),
manifest: joi.string().allow("")
});
const options = {
stripUnknown: true
};
return OBJECT_SCHEMA.validate(configObject, options).value;
});
return function stripObjectFromConfig(_x25) {
return _ref13.apply(this, arguments);
};
})();
function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }
const fp = require('mediacentral-feature-pack'),
signManifest = require('mediacentral-sign'),
uploadProject = require('mediacentral-upload'),
fs = require('./fs'),
fsEx = require('fs-extra'),
randomstring = require('randomstring'),
path = require('path'),
buildDocker = require('./buildDocker'),
buildDockerImage = require('./functions/buildDockerImage/index');
buildDockerService = require('./buildDockerService'), createMetadata = require('./createMetadata'), createChart = require('./createChart'), createChartService = require('./createChartService'), normalize = require('normalize-path'), os = require('os'), log4js = require('log4js'), logger = require.main.require('log4js').getLogger(`mediacentral-publish ${__filename}`);
joi = require('joi');
function isProjectPathValid(projectPath) {
if (!fsEx.pathExistsSync(projectPath)) {
console.error(`Invalid project path`);
process.exit(-1);
}
}
module.exports = {
stripObjectFromConfig,
publish,
optionsValidation,
log4JsConfiguration,
createWorkingDir,
getFeaturePack,
doSign,
doUpload,
build
};