UNPKG

pp-parachute

Version:
91 lines (79 loc) 2.9 kB
var assert = require('../util/assert'); var Environment = require('./environment'); var Promise = require('bluebird'); var ParachuteBase = require('./parachute_base'); var inherits = require('util').inherits; var Application = function (name, rootPath) { assert.isString(name, 'Applications must have a name!'); ParachuteBase.call(this, name); this.absolutePath = findFilePath(); this.rootPath = rootPath || this.absolutePath; this.environments = {}; }; inherits(Application, ParachuteBase); Application.prototype.useEnvironment = function (env) { assert(env !== this, 'Application cannot use itself as an environment'); assert(env instanceof Environment, 'Application.useEnvironment(env) must be called with an instance of Parachute.Environment'); env.application = this; this.environments[env.name] = env; //traverse linked list of parent pointers and put self at the last slot var pointer = env; while(pointer.parent) { pointer = pointer.parent; } pointer.parent = this; return this; }; Application.prototype.getEnvironments = function() { var envNames = Object.keys(this.environments); return envNames.map(function(envName) { return this.environments[envName]; }, this); }; Application.prototype.getEnvironment = function(envName) { return this.environments[envName]; }; Application.prototype.build = function (environmentName) { if (environmentName instanceof Environment) { environmentName = environmentName.name; } var env = this.environments[environmentName]; if (!env) return Promise.reject('Environment ' + environmentName + ' is not registered'); return env.build(this); }; Application.prototype.watch = function (environmentName) { if (environmentName instanceof Environment) { environmentName = environmentName.name; } var env = this.environments[environmentName]; if (!env) { return Promise.reject('Environment ' + environmentName +' does not exist'); } return env.watch(this); }; Application.prototype.shutdown = function () { var environmentNames = Object.keys(this.environments); environmentNames.forEach(function(envName) { this.environments[envName].shutdown(); }, this); }; module.exports = Application; //gets the path to the file that the constructor was called in //by parsing a stack trace. function findFilePath() { try { throw new Error('give me a stack'); } catch (e) { var fileLines = e.stack.split('\n'); for(var i = 0; i < fileLines.length; i++ ) { if(fileLines[i].indexOf('at new') !== -1) { break; } } var fileLine = fileLines[i + 1]; var start = fileLine.indexOf('(') + 1; var end = fileLine.lastIndexOf('/'); return fileLine.substring(start, end); } }