<commit_before>/*
 © Copyright IBM Corp. 2017, 2018
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at
 http://www.apache.org/licenses/LICENSE-2.0
 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

'use strict';

const Handlebars = require('../lib/handlebars.js');
const Generator = require('yeoman-generator');
const Utils = require('../lib/utils');

module.exports = class extends Generator {
	constructor(args, opts) {
		super(args, opts);
		if (opts.cloudContext) {
			this.opts = opts.cloudContext
			this.opts.libertyVersion = opts.libertyVersion
		} else {
			this.opts = opts
		}
		if (typeof (opts.bluemix) === 'string') {
			this.bluemix = JSON.parse(opts.bluemix || '{}');
		} else if (typeof (opts.bluemix) === 'object') {
			this.bluemix = opts.bluemix;
		}

	}

	configuring() {
		this.manifestConfig = {};
		this.manifestConfig.env = {};
		this.toolchainConfig = {};
		this.pipelineConfig = {
			buildJobProps: {
				artifact_dir: "''"
			},
			triggersType: 'commit'
		};
		this.deployment = {
			type: 'CF',
			name: this.bluemix.name,
			language: this.bluemix.backendPlatform
		};

		this.name = undefined;
		if (this.bluemix.server) {
			this.name = this.bluemix.server.name;
			this.manifestConfig = Object.assign(this.manifestConfig, this.bluemix.server);
			this.deployment = Object.assign(this.deployment, this.bluemix.server.cloudDeploymentOptions);
			this.manifestConfig.instances = this.manifestConfig.instances || '1';
			this.deployment.type = this.bluemix.server.cloudDeploymentType || 'CF';
			this.deployment.chartName = Utils.sanitizeAlphaNumLowerCase(this.name || this.bluemix.name);
			this.deployment.scriptsDir = '.bluemix/scripts';
			this.deployment.hasMongo = this.opts.createType === 'mern' || this.opts.createType === 'mean';
			if (!this.deployment.kubeClusterNamespace) {
				this.deployment.kubeClusterNamespace = 'default';
			}
			if (!this.deployment.imageRegistryNamespace) {
				this.deployment.imageRegistryNamespace = 'my_registry_ns';
			}
		} else {
			this.name = this.bluemix.name;
			this.manifestConfig.name = this.bluemix.name;
			this.deployment.type = this.bluemix.cloudDeploymentType || 'CF';
		}

		this.toolchainConfig.repoType = this.opts.repoType || "clone";
		switch (this.bluemix.backendPlatform) {
			case 'NODE':
				this._configureNode();
				break;
			case 'SWIFT':
				this._configureSwift();
				break;
			case 'JAVA':
				this._configureLiberty();
				this._configureJavaCommon();
				break;
			case 'SPRING':
				this._configureJavaCommon();
				this._configureSpring();
				break;
			case 'PYTHON':
				this._configurePython();
				break;
			case 'DJANGO':
				this._configureDjango();
				break;
			case 'GO':
				this._configureGo();
				break;
			default:
				throw new Error(`Language ${this.bluemix.backendPlatform} was not one of the valid languages: NODE, SWIFT, JAVA, SPRING, DJANGO, PYTHON, or GO`);
		}
		if (this.manifestConfig && this.manifestConfig.ignorePaths) {
			this.cfIgnoreContent = this.cfIgnoreContent.concat(this.manifestConfig.ignorePaths);
		}

		this.pipelineConfig.postBuildScript = this.fs.read(this.templatePath('post_build.txt'));

		if (this.pipelineConfig.buildJobProps && this.pipelineConfig.buildJobProps.script) {
			this.pipelineConfig.buildJobProps.script += '\n\n' + this.pipelineConfig.postBuildScript;
		} else if (!this.pipelineConfig.buildJobProps.script) {
			Object.assign(this.pipelineConfig.buildJobProps, {
				build_type: 'shell',
				script: '|-\n' +
				'      #!/bin/bash\n' +
				this.pipelineConfig.postBuildScript
			});
		}
	}

	/***
	 * Get the highest memory size available
	 *
	 * @params manifestMemoryConfig {string} the memory allocaated h
	 */
	_getHighestMemorySize(manifestMemoryConfig, userDefinedMinMemory){
		if(!userDefinedMinMemory) {
			return manifestMemoryConfig;
		} else if (!manifestMemoryConfig && userDefinedMinMemory) {
			return userDefinedMinMemory;
		}

		const memMap = {
			k: 1,
			m: 2,
			g: 3
		};
		const manifestSize = manifestMemoryConfig.replace(/[^MmGgKk]/g, '');
		const userDefinedMinSize = userDefinedMinMemory.replace(/[^MmGgKk]/g, '');
		let highestAvailableSize;

		if(memMap[manifestSize.toLowerCase()] > memMap[userDefinedMinSize.toLowerCase()]){
			highestAvailableSize = manifestMemoryConfig;
		} else if (memMap[manifestSize.toLowerCase()] < memMap[userDefinedMinSize.toLowerCase()]){
			highestAvailableSize = userDefinedMinMemory;
		} else {
			const manifestValue = parseInt(manifestSize.replace(/[M,m,G,g,K,k]/g, ''));
			const definedValue = parseInt(userDefinedMinSize.replace(/[M,m,G,g,K,k]/g, ''));

			highestAvailableSize = manifestValue > definedValue ? manifestMemoryConfig : userDefinedMinMemory;
		}

		return highestAvailableSize;
	}

	_configureNode() {
		this.manifestConfig.buildpack = 'sdk-for-nodejs';
		this.manifestConfig.command = 'npm start';
		this.manifestConfig.memory = this._getHighestMemorySize(this.manifestConfig.memory, this.opts.nodeCFMinMemory);
		this.cfIgnoreContent = ['.git/', 'node_modules/', 'test/', 'vcap-local.js'];
	}

	_configureGo() {
		// Need a direct github link becasue 'go_buildpack' doesn't have dep support
		this.manifestConfig.buildpack = 'https://github.com/cloudfoundry/go-buildpack.git#v1.8.25';
		this.manifestConfig.command = undefined;
		this.manifestConfig.memory = this.manifestConfig.memory || '128M';
		this.manifestConfig.env.GOPACKAGENAME = this.bluemix.sanitizedName;
		this.cfIgnoreContent = ['.git/', 'vendor/'];
	}

	_configureSwift() {
		this.manifestConfig.buildpack = 'swift_buildpack';
		this.manifestConfig.command = this.bluemix.name ? ("\"'" + `${this.bluemix.name}` + "'\"") : undefined;
		this.manifestConfig.memory = this.manifestConfig.memory || '128M';
		this.pipelineConfig.swift = true;
		this.cfIgnoreContent = ['.build/*', '.build-ubuntu/*', 'Packages/*'];
	}

	_configureJavaCommon() {
		if (this.opts.appName) {
			this.manifestConfig.name = this.opts.appName;
			this.name = this.opts.appName;
		}
		if (this.opts.createType === 'bff/liberty') {
			this.manifestConfig.env.OPENAPI_SPEC = `/${this.name}/swagger/api`;
		}
		if (this.opts.createType === 'bff/spring') {
			this.manifestConfig.env.OPENAPI_SPEC = '/swagger/api';
		}

		if (this.opts.createType && this.opts.createType.startsWith('enable/')) {
			this.toolchainConfig.repoType = 'link';
		}
		let buildCommand = this.opts.buildType === 'gradle' ? '      gradle build' : '      mvn -N io.takari:maven:wrapper -Dmaven=3.5.0\n      ./mvnw install -DskipTests' ;
		this.pipelineConfig.javaBuildScriptContent = 'export JAVA_HOME=$JAVA8_HOME\n' + buildCommand;
		this.pipelineConfig.buildJobProps = {
			build_type: 'shell',
			script: '|\n' +
			'      #!/bin/bash\n' +
			'      ' + this.pipelineConfig.javaBuildScriptContent
		};
	}

	_configureLiberty() {
		let artifactId = this.opts.artifactId ? this.opts.artifactId : "java-liberty";
		let version = this.opts.version ? this.opts.version : "1.0-SNAPSHOT";

		this.cfIgnoreContent = ['/.classpath', '/.project', '/.settings', '/src/main/liberty/config/server.env', 'target/', 'build/'];
		this.manifestConfig.buildpack = 'liberty-for-java';
		this.manifestConfig.memory = this.manifestConfig.memory || '512M';
		let buildDir = (this.opts.buildType && this.opts.buildType === 'gradle') ? 'build' : 'target';
		let zipPath = `${buildDir}/` + artifactId + `-` + version + `.zip`;
		console.log ("**** zippath " + zipPath)
		this.manifestConfig.path = `./${zipPath}`;
		let excludes = [];
		if (this.opts.libertyVersion === 'beta') {
			this.manifestConfig.env.IBM_LIBERTY_BETA = 'true'
			this.manifestConfig.env.JBP_CONFIG_LIBERTY = '\"version: +\"'
		}
		if (this.bluemix.cloudant) {
			excludes.push('cloudantNoSQLDB=config');
		}
		if (this.bluemix.objectStorage) {
			excludes.push('Object-Storage=config');
		}
		if (excludes.length === 1) {
			this.manifestConfig.env.services_autoconfig_excludes = excludes[0];
		}
		if (excludes.length === 2) {
			this.manifestConfig.env.services_autoconfig_excludes = excludes[0] + ' ' + excludes[1];
		}
		this.pipelineConfig.pushCommand = 'cf push "${CF_APP}" -p ' + zipPath + ' --hostname "${CF_HOSTNAME}" -d "${CF_DOMAIN}"';
	}

	_configureSpring() {
		let artifactId = this.opts.artifactId ? this.opts.artifactId : "java-spring";
		let version = this.opts.version ? this.opts.version : "1.0-SNAPSHOT";

		this.cfIgnoreContent = ['/.classpath', '/.project', '/.settings', '/src/main/resources/application-local.properties', 'target/', 'build/'];
		this.manifestConfig.buildpack = 'java_buildpack';
		this.manifestConfig.memory = this._getHighestMemorySize(this.manifestConfig.memory, '1024M');
		let buildDir = (this.opts.buildType && this.opts.buildType === 'gradle') ? 'build/libs' : 'target';
		let jarPath = `${buildDir}/` + artifactId + `-` + version + `.jar`;
		console.log ("**** jarPath " + jarPath)
		this.manifestConfig.path = `./${jarPath}`;
		this.pipelineConfig.pushCommand = 'cf push "${CF_APP}" -p ' + jarPath + ' --hostname "${CF_HOSTNAME}" -d "${CF_DOMAIN}"';
	}

	_configurePython() {
		// buildpack is left blank; bluemix will auto detect
		this.manifestConfig.buildpack = 'python_buildpack';
		this.manifestConfig.command = this.opts.enable ?
			'echo No run command specified in manifest.yml' :
			'python manage.py start 0.0.0.0:$PORT';
		this.manifestConfig.memory = this.manifestConfig.memory || '128M';
		this.manifestConfig.env.FLASK_APP = 'server';
		this.manifestConfig.env.FLASK_DEBUG = 'false';
		this.cfIgnoreContent = ['.pyc', '.egg-info'];
	}

	_configureDjango() {
		// buildpack is left blank; bluemix will auto detect
		this.manifestConfig.buildpack = 'python_buildpack';
		this.manifestConfig.command = this.opts.enable ?
			'echo No run command specified in manifest.yml' :
			`gunicorn --env DJANGO_SETTINGS_MODULE=${this.bluemix.name}.settings.production ${this.bluemix.name}.wsgi -b 0.0.0.0:$PORT`;
		this.manifestConfig.memory = this.manifestConfig.memory || '128M';
		this.cfIgnoreContent = ['.pyc', '.egg-info'];
	}

	cleanUpPass() {
		if (this.manifestConfig && this.manifestConfig.env && Object.keys(this.manifestConfig.env).length < 1) {
			delete this.manifestConfig.env;
		}
		if (this.cfIgnoreContent) {
			this.cfIgnoreContent = this.cfIgnoreContent.join('\n');
		}
	}

	writing() {
		//skip writing files if platforms is specified via options and it doesn't include bluemix
		if (this.opts.platforms && !this.opts.platforms.includes('bluemix')) {
			return;
		}
		// write manifest.yml file
		this._writeHandlebarsFile('manifest_master.yml', 'manifest.yml', this.manifestConfig)

		// if cfIgnnoreContent exists, create/write .cfignore file
		if (this.cfIgnoreContent) {
			this.fs.write('.cfignore', this.cfIgnoreContent);
		}

		// create .bluemix directory for toolchain/devops related files
		this._writeHandlebarsFile('toolchain_master.yml', '.bluemix/toolchain.yml', {
			name: this.opts.toolchainName || this.name,
			org: this.opts.deploymentOrg || "{{organization}}",
			space: this.opts.deploymentSpace || "{{space}}",
			region: this.opts.deploymentRegion || "{{region}}",
			repoType: this.toolchainConfig.repoType,
			deployment: this.deployment
		});

		this._writeHandlebarsFile('deploy_master.json', '.bluemix/deploy.json', {
			deployment: this.deployment
		});

		this._writeHandlebarsFile('container_build.sh', '.bluemix/scripts/container_build.sh', {
			deployment: this.deployment
		});

		this._writeHandlebarsFile('kube_deploy.sh', '.bluemix/scripts/kube_deploy.sh', {
			deployment: this.deployment
		});

		if (Utils.sanitizeAlphaNumLowerCase(this.deployment.type) === "vsi") {
			this._writeHandlebarsFile('vsi_pipeline_master.yml', '.bluemix/pipeline.yml', {
				config: this.pipelineConfig,
				name: this.name,
				lowercaseName: Utils.sanitizeAlphaNumLowerCase(this.name),
				deployment: this.deployment
			});
		}
		else {
			this._writeHandlebarsFile('pipeline_master.yml', '.bluemix/pipeline.yml', {
				config: this.pipelineConfig,
				deployment: this.deployment,
				manifest: this.manifestConfig
			});
		}

	}

	_writeHandlebarsFile(templateFile, destinationFile, data) {
		let template = this.fs.read(this.templatePath(templateFile));
		let compiledTemplate = Handlebars.compile(template);
		let output = compiledTemplate(data);
		this.fs.write(this.destinationPath(destinationFile), output);
	}
};
<commit_msg>chore: remove log statements<commit_after>/*
 © Copyright IBM Corp. 2017, 2018
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at
 http://www.apache.org/licenses/LICENSE-2.0
 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

'use strict';

const Handlebars = require('../lib/handlebars.js');
const Generator = require('yeoman-generator');
const Utils = require('../lib/utils');

module.exports = class extends Generator {
	constructor(args, opts) {
		super(args, opts);
		if (opts.cloudContext) {
			this.opts = opts.cloudContext
			this.opts.libertyVersion = opts.libertyVersion
		} else {
			this.opts = opts
		}
		if (typeof (opts.bluemix) === 'string') {
			this.bluemix = JSON.parse(opts.bluemix || '{}');
		} else if (typeof (opts.bluemix) === 'object') {
			this.bluemix = opts.bluemix;
		}

	}

	configuring() {
		this.manifestConfig = {};
		this.manifestConfig.env = {};
		this.toolchainConfig = {};
		this.pipelineConfig = {
			buildJobProps: {
				artifact_dir: "''"
			},
			triggersType: 'commit'
		};
		this.deployment = {
			type: 'CF',
			name: this.bluemix.name,
			language: this.bluemix.backendPlatform
		};

		this.name = undefined;
		if (this.bluemix.server) {
			this.name = this.bluemix.server.name;
			this.manifestConfig = Object.assign(this.manifestConfig, this.bluemix.server);
			this.deployment = Object.assign(this.deployment, this.bluemix.server.cloudDeploymentOptions);
			this.manifestConfig.instances = this.manifestConfig.instances || '1';
			this.deployment.type = this.bluemix.server.cloudDeploymentType || 'CF';
			this.deployment.chartName = Utils.sanitizeAlphaNumLowerCase(this.name || this.bluemix.name);
			this.deployment.scriptsDir = '.bluemix/scripts';
			this.deployment.hasMongo = this.opts.createType === 'mern' || this.opts.createType === 'mean';
			if (!this.deployment.kubeClusterNamespace) {
				this.deployment.kubeClusterNamespace = 'default';
			}
			if (!this.deployment.imageRegistryNamespace) {
				this.deployment.imageRegistryNamespace = 'my_registry_ns';
			}
		} else {
			this.name = this.bluemix.name;
			this.manifestConfig.name = this.bluemix.name;
			this.deployment.type = this.bluemix.cloudDeploymentType || 'CF';
		}

		this.toolchainConfig.repoType = this.opts.repoType || "clone";
		switch (this.bluemix.backendPlatform) {
			case 'NODE':
				this._configureNode();
				break;
			case 'SWIFT':
				this._configureSwift();
				break;
			case 'JAVA':
				this._configureLiberty();
				this._configureJavaCommon();
				break;
			case 'SPRING':
				this._configureJavaCommon();
				this._configureSpring();
				break;
			case 'PYTHON':
				this._configurePython();
				break;
			case 'DJANGO':
				this._configureDjango();
				break;
			case 'GO':
				this._configureGo();
				break;
			default:
				throw new Error(`Language ${this.bluemix.backendPlatform} was not one of the valid languages: NODE, SWIFT, JAVA, SPRING, DJANGO, PYTHON, or GO`);
		}
		if (this.manifestConfig && this.manifestConfig.ignorePaths) {
			this.cfIgnoreContent = this.cfIgnoreContent.concat(this.manifestConfig.ignorePaths);
		}

		this.pipelineConfig.postBuildScript = this.fs.read(this.templatePath('post_build.txt'));

		if (this.pipelineConfig.buildJobProps && this.pipelineConfig.buildJobProps.script) {
			this.pipelineConfig.buildJobProps.script += '\n\n' + this.pipelineConfig.postBuildScript;
		} else if (!this.pipelineConfig.buildJobProps.script) {
			Object.assign(this.pipelineConfig.buildJobProps, {
				build_type: 'shell',
				script: '|-\n' +
				'      #!/bin/bash\n' +
				this.pipelineConfig.postBuildScript
			});
		}
	}

	/***
	 * Get the highest memory size available
	 *
	 * @params manifestMemoryConfig {string} the memory allocaated h
	 */
	_getHighestMemorySize(manifestMemoryConfig, userDefinedMinMemory){
		if(!userDefinedMinMemory) {
			return manifestMemoryConfig;
		} else if (!manifestMemoryConfig && userDefinedMinMemory) {
			return userDefinedMinMemory;
		}

		const memMap = {
			k: 1,
			m: 2,
			g: 3
		};
		const manifestSize = manifestMemoryConfig.replace(/[^MmGgKk]/g, '');
		const userDefinedMinSize = userDefinedMinMemory.replace(/[^MmGgKk]/g, '');
		let highestAvailableSize;

		if(memMap[manifestSize.toLowerCase()] > memMap[userDefinedMinSize.toLowerCase()]){
			highestAvailableSize = manifestMemoryConfig;
		} else if (memMap[manifestSize.toLowerCase()] < memMap[userDefinedMinSize.toLowerCase()]){
			highestAvailableSize = userDefinedMinMemory;
		} else {
			const manifestValue = parseInt(manifestSize.replace(/[M,m,G,g,K,k]/g, ''));
			const definedValue = parseInt(userDefinedMinSize.replace(/[M,m,G,g,K,k]/g, ''));

			highestAvailableSize = manifestValue > definedValue ? manifestMemoryConfig : userDefinedMinMemory;
		}

		return highestAvailableSize;
	}

	_configureNode() {
		this.manifestConfig.buildpack = 'sdk-for-nodejs';
		this.manifestConfig.command = 'npm start';
		this.manifestConfig.memory = this._getHighestMemorySize(this.manifestConfig.memory, this.opts.nodeCFMinMemory);
		this.cfIgnoreContent = ['.git/', 'node_modules/', 'test/', 'vcap-local.js'];
	}

	_configureGo() {
		// Need a direct github link becasue 'go_buildpack' doesn't have dep support
		this.manifestConfig.buildpack = 'https://github.com/cloudfoundry/go-buildpack.git#v1.8.25';
		this.manifestConfig.command = undefined;
		this.manifestConfig.memory = this.manifestConfig.memory || '128M';
		this.manifestConfig.env.GOPACKAGENAME = this.bluemix.sanitizedName;
		this.cfIgnoreContent = ['.git/', 'vendor/'];
	}

	_configureSwift() {
		this.manifestConfig.buildpack = 'swift_buildpack';
		this.manifestConfig.command = this.bluemix.name ? ("\"'" + `${this.bluemix.name}` + "'\"") : undefined;
		this.manifestConfig.memory = this.manifestConfig.memory || '128M';
		this.pipelineConfig.swift = true;
		this.cfIgnoreContent = ['.build/*', '.build-ubuntu/*', 'Packages/*'];
	}

	_configureJavaCommon() {
		if (this.opts.appName) {
			this.manifestConfig.name = this.opts.appName;
			this.name = this.opts.appName;
		}
		if (this.opts.createType === 'bff/liberty') {
			this.manifestConfig.env.OPENAPI_SPEC = `/${this.name}/swagger/api`;
		}
		if (this.opts.createType === 'bff/spring') {
			this.manifestConfig.env.OPENAPI_SPEC = '/swagger/api';
		}

		if (this.opts.createType && this.opts.createType.startsWith('enable/')) {
			this.toolchainConfig.repoType = 'link';
		}
		let buildCommand = this.opts.buildType === 'gradle' ? '      gradle build' : '      mvn -N io.takari:maven:wrapper -Dmaven=3.5.0\n      ./mvnw install -DskipTests' ;
		this.pipelineConfig.javaBuildScriptContent = 'export JAVA_HOME=$JAVA8_HOME\n' + buildCommand;
		this.pipelineConfig.buildJobProps = {
			build_type: 'shell',
			script: '|\n' +
			'      #!/bin/bash\n' +
			'      ' + this.pipelineConfig.javaBuildScriptContent
		};
	}

	_configureLiberty() {
		let artifactId = this.opts.artifactId ? this.opts.artifactId : "java-liberty";
		let version = this.opts.version ? this.opts.version : "1.0-SNAPSHOT";

		this.cfIgnoreContent = ['/.classpath', '/.project', '/.settings', '/src/main/liberty/config/server.env', 'target/', 'build/'];
		this.manifestConfig.buildpack = 'liberty-for-java';
		this.manifestConfig.memory = this.manifestConfig.memory || '512M';
		let buildDir = (this.opts.buildType && this.opts.buildType === 'gradle') ? 'build' : 'target';
		let zipPath = `${buildDir}/` + artifactId + `-` + version + `.zip`;
		this.manifestConfig.path = `./${zipPath}`;
		let excludes = [];
		if (this.opts.libertyVersion === 'beta') {
			this.manifestConfig.env.IBM_LIBERTY_BETA = 'true'
			this.manifestConfig.env.JBP_CONFIG_LIBERTY = '\"version: +\"'
		}
		if (this.bluemix.cloudant) {
			excludes.push('cloudantNoSQLDB=config');
		}
		if (this.bluemix.objectStorage) {
			excludes.push('Object-Storage=config');
		}
		if (excludes.length === 1) {
			this.manifestConfig.env.services_autoconfig_excludes = excludes[0];
		}
		if (excludes.length === 2) {
			this.manifestConfig.env.services_autoconfig_excludes = excludes[0] + ' ' + excludes[1];
		}
		this.pipelineConfig.pushCommand = 'cf push "${CF_APP}" -p ' + zipPath + ' --hostname "${CF_HOSTNAME}" -d "${CF_DOMAIN}"';
	}

	_configureSpring() {
		let artifactId = this.opts.artifactId ? this.opts.artifactId : "java-spring";
		let version = this.opts.version ? this.opts.version : "1.0-SNAPSHOT";

		this.cfIgnoreContent = ['/.classpath', '/.project', '/.settings', '/src/main/resources/application-local.properties', 'target/', 'build/'];
		this.manifestConfig.buildpack = 'java_buildpack';
		this.manifestConfig.memory = this._getHighestMemorySize(this.manifestConfig.memory, '1024M');
		let buildDir = (this.opts.buildType && this.opts.buildType === 'gradle') ? 'build/libs' : 'target';
		let jarPath = `${buildDir}/` + artifactId + `-` + version + `.jar`;
		this.manifestConfig.path = `./${jarPath}`;
		this.pipelineConfig.pushCommand = 'cf push "${CF_APP}" -p ' + jarPath + ' --hostname "${CF_HOSTNAME}" -d "${CF_DOMAIN}"';
	}

	_configurePython() {
		// buildpack is left blank; bluemix will auto detect
		this.manifestConfig.buildpack = 'python_buildpack';
		this.manifestConfig.command = this.opts.enable ?
			'echo No run command specified in manifest.yml' :
			'python manage.py start 0.0.0.0:$PORT';
		this.manifestConfig.memory = this.manifestConfig.memory || '128M';
		this.manifestConfig.env.FLASK_APP = 'server';
		this.manifestConfig.env.FLASK_DEBUG = 'false';
		this.cfIgnoreContent = ['.pyc', '.egg-info'];
	}

	_configureDjango() {
		// buildpack is left blank; bluemix will auto detect
		this.manifestConfig.buildpack = 'python_buildpack';
		this.manifestConfig.command = this.opts.enable ?
			'echo No run command specified in manifest.yml' :
			`gunicorn --env DJANGO_SETTINGS_MODULE=${this.bluemix.name}.settings.production ${this.bluemix.name}.wsgi -b 0.0.0.0:$PORT`;
		this.manifestConfig.memory = this.manifestConfig.memory || '128M';
		this.cfIgnoreContent = ['.pyc', '.egg-info'];
	}

	cleanUpPass() {
		if (this.manifestConfig && this.manifestConfig.env && Object.keys(this.manifestConfig.env).length < 1) {
			delete this.manifestConfig.env;
		}
		if (this.cfIgnoreContent) {
			this.cfIgnoreContent = this.cfIgnoreContent.join('\n');
		}
	}

	writing() {
		//skip writing files if platforms is specified via options and it doesn't include bluemix
		if (this.opts.platforms && !this.opts.platforms.includes('bluemix')) {
			return;
		}
		// write manifest.yml file
		this._writeHandlebarsFile('manifest_master.yml', 'manifest.yml', this.manifestConfig)

		// if cfIgnnoreContent exists, create/write .cfignore file
		if (this.cfIgnoreContent) {
			this.fs.write('.cfignore', this.cfIgnoreContent);
		}

		// create .bluemix directory for toolchain/devops related files
		this._writeHandlebarsFile('toolchain_master.yml', '.bluemix/toolchain.yml', {
			name: this.opts.toolchainName || this.name,
			org: this.opts.deploymentOrg || "{{organization}}",
			space: this.opts.deploymentSpace || "{{space}}",
			region: this.opts.deploymentRegion || "{{region}}",
			repoType: this.toolchainConfig.repoType,
			deployment: this.deployment
		});

		this._writeHandlebarsFile('deploy_master.json', '.bluemix/deploy.json', {
			deployment: this.deployment
		});

		this._writeHandlebarsFile('container_build.sh', '.bluemix/scripts/container_build.sh', {
			deployment: this.deployment
		});

		this._writeHandlebarsFile('kube_deploy.sh', '.bluemix/scripts/kube_deploy.sh', {
			deployment: this.deployment
		});

		if (Utils.sanitizeAlphaNumLowerCase(this.deployment.type) === "vsi") {
			this._writeHandlebarsFile('vsi_pipeline_master.yml', '.bluemix/pipeline.yml', {
				config: this.pipelineConfig,
				name: this.name,
				lowercaseName: Utils.sanitizeAlphaNumLowerCase(this.name),
				deployment: this.deployment
			});
		}
		else {
			this._writeHandlebarsFile('pipeline_master.yml', '.bluemix/pipeline.yml', {
				config: this.pipelineConfig,
				deployment: this.deployment,
				manifest: this.manifestConfig
			});
		}

	}

	_writeHandlebarsFile(templateFile, destinationFile, data) {
		let template = this.fs.read(this.templatePath(templateFile));
		let compiledTemplate = Handlebars.compile(template);
		let output = compiledTemplate(data);
		this.fs.write(this.destinationPath(destinationFile), output);
	}
};
<|endoftext|>


<commit_before>#!/usr/src/app/bin/node_gc

process.chdir('/code');

var CLIEngine = require("eslint").CLIEngine;
var docs = require("eslint").docs;
var fs = require("fs");
var glob = require("glob");
var options = { extensions: [".js"], ignore: true, reset: false, useEslintrc: true };
var cli = new CLIEngine(options);
var debug = false;
var checks = require("../lib/checks");

var stdout = console.log
console.log = console.error

// a wrapper for emitting perf timing
function runWithTiming(name, fn) {
  var start = new Date(),
      rv = fn(),
      duration = (new Date() - start) / 1000;
  console.error("eslint.timing." + name + ": " + duration + "s");
  return rv;
}

function buildIssueJson(message, path) {
  // ESLint doesn't emit a ruleId in the
  // case of a fatal error (such as an invalid
  // token)
  var checkName = message.ruleId;
  if(message.fatal) {
    checkName = "fatal";
  }

  var issue = {
    type: "issue",
    categories: checks.categories(checkName),
    check_name: checkName,
    description: message.message,
    content: {
      body: contentBody(checkName)
    },
    location: {
      path: path,
      positions: {
        begin: {
          line: message.line,
          column: message.column
        },
        end: {
          line: message.line,
          column: message.column
        }
      }
    },
    remediation_points: checks.remediationPoints(checkName, message)
  };
  return JSON.stringify(issue);
}

function contentBody(check) {
  var content = docs.get(check) || "For more information visit ";
  return content + "Source: http://eslint.org/docs/rules/\n";
}

function isFileWithMatchingExtension(file, extensions) {
  var stats = fs.lstatSync(file);
  var extension = "." + file.split(".").pop();
  return (
    stats.isFile() &&
    !stats.isSymbolicLink()
    && extensions.indexOf(extension) >= 0
  );
}

function isFileIgnoredByLibrary(file) {
  var path = file.replace(/^\/code\//, "");
  var ignored = cli.isPathIgnored(path);
  if (ignored) {
    output = "File `" + path + "` ignored because of your .eslintignore file." + "\n";
    process.stderr.write(output);
  }
  return ignored;
}

function prunePathsWithinSymlinks(paths) {
  // Extracts symlinked paths and filters them out, including any child paths
  var symlinks = paths.filter(function(path) {
    return fs.lstatSync(path).isSymbolicLink();
  });

  return paths.filter(function(path) {
    var withinSymlink = false;
    symlinks.forEach(function(symlink) {
      if (path.indexOf(symlink) == 0) {
        withinSymlink = true;
      }
    });
    return !withinSymlink;
  });
}

function exclusionBasedFileListBuilder(excludePaths) {
  // Uses glob to traverse code directory and find files to analyze,
  // excluding files passed in with by CLI config, and including only
  // files in the list of desired extensions.
  //
  // Deprecated style of file expansion, supported for users of the old CLI.
  return function(extensions) {
    var analysisFiles = [];
    var allFiles = glob.sync("/code/**/**", {});

    prunePathsWithinSymlinks(allFiles).forEach(function(file, i, a){
      if(excludePaths.indexOf(file.split("/code/")[1]) < 0) {
        if(fs.lstatSync(file).isFile()) {
          if (!isFileIgnoredByLibrary(file) && isFileWithMatchingExtension(file, extensions)) {
            analysisFiles.push(file);
          }
        }
      }
    });

    return analysisFiles;
  };
}

function inclusionBasedFileListBuilder(includePaths) {
  // Uses glob to expand the files and directories in includePaths, filtering
  // down to match the list of desired extensions.
  return function(extensions) {
    var analysisFiles = [];

    includePaths.forEach(function(fileOrDirectory, i) {
      if ((/\/$/).test(fileOrDirectory)) {
        // if it ends in a slash, expand and push
        var filesInThisDirectory = glob.sync(
          "/code/" + fileOrDirectory + "/**/**"
        );
        prunePathsWithinSymlinks(filesInThisDirectory).forEach(function(file, j){
          if (!isFileIgnoredByLibrary(file) && isFileWithMatchingExtension(file, extensions)) {
            analysisFiles.push(file);
          }
        });
      } else {
        // if not, check for ending in *.js
        var fullPath = "/code/" + fileOrDirectory;
        if (!isFileIgnoredByLibrary(fullPath) && isFileWithMatchingExtension(fullPath, extensions)) {
          analysisFiles.push(fullPath);
        }
      }
    });

    return analysisFiles;
  };
}

var buildFileList;
runWithTiming("engineConfig", function () {
  if (fs.existsSync("/config.json")) {
    var engineConfig = JSON.parse(fs.readFileSync("/config.json"));

    if (engineConfig.include_paths) {
      buildFileList = inclusionBasedFileListBuilder(
        engineConfig.include_paths
      );
    } else if (engineConfig.exclude_paths) {
      var ignores = engineConfig.exclude_paths;
      buildFileList = exclusionBasedFileListBuilder(ignores);
    } else {
      // No includes or excludes, let's try with everything
      buildFileList = exclusionBasedFileListBuilder([]);
    }

    var userConfig = engineConfig.config || {};
    if (userConfig.config) {
      options.configFile = "/code/" + userConfig.config;
    }

    if (userConfig.extensions) {
      options.extensions = userConfig.extensions;
    }

    if (userConfig.debug) {
      debug = true;
    }
  }
});

var analysisFiles = runWithTiming("buildFileList", function() {
  return buildFileList(options.extensions);
});

function analyzeFiles() {
  var batchNum = 0,
      batchSize = 1,
      batchFiles,
      batchReport;

  while(analysisFiles.length > 0) {
    batchFiles = analysisFiles.splice(0, batchSize);

    if (debug) {
      process.stderr.write("Analyzing: " + batchFiles + "\n");
    }

    runWithTiming("analyze-batch-" + batchNum, function() {
       batchReport = cli.executeOnFiles(batchFiles);
    });
    runWithTiming("report-batch" + batchNum, function() {
      batchReport.results.forEach(function(result) {
        var path = result.filePath.replace(/^\/code\//, "");

        result.messages.forEach(function(message) {
          var issueJson = buildIssueJson(message, path);
          stdout(issueJson + "\u0000");
        });
      });
    });
    runWithTiming("gc-batch-" + batchNum, function() {
      batchFiles = null;
      batchReport = null;
      global.gc();
    });

    batchNum++;
  }
}

analyzeFiles();
<commit_msg>Do the console redirect earlier<commit_after>#!/usr/src/app/bin/node_gc

process.chdir('/code');

// Redirect `console.log` so that we are the only ones
// writing to STDOUT
var stdout = console.log;
console.log = console.error;

var CLIEngine = require("eslint").CLIEngine;
var docs = require("eslint").docs;
var fs = require("fs");
var glob = require("glob");
var options = { extensions: [".js"], ignore: true, reset: false, useEslintrc: true };
var cli = new CLIEngine(options);
var debug = false;
var checks = require("../lib/checks");

// a wrapper for emitting perf timing
function runWithTiming(name, fn) {
  var start = new Date(),
      rv = fn(),
      duration = (new Date() - start) / 1000;
  console.error("eslint.timing." + name + ": " + duration + "s");
  return rv;
}

function buildIssueJson(message, path) {
  // ESLint doesn't emit a ruleId in the
  // case of a fatal error (such as an invalid
  // token)
  var checkName = message.ruleId;
  if(message.fatal) {
    checkName = "fatal";
  }

  var issue = {
    type: "issue",
    categories: checks.categories(checkName),
    check_name: checkName,
    description: message.message,
    content: {
      body: contentBody(checkName)
    },
    location: {
      path: path,
      positions: {
        begin: {
          line: message.line,
          column: message.column
        },
        end: {
          line: message.line,
          column: message.column
        }
      }
    },
    remediation_points: checks.remediationPoints(checkName, message)
  };
  return JSON.stringify(issue);
}

function contentBody(check) {
  var content = docs.get(check) || "For more information visit ";
  return content + "Source: http://eslint.org/docs/rules/\n";
}

function isFileWithMatchingExtension(file, extensions) {
  var stats = fs.lstatSync(file);
  var extension = "." + file.split(".").pop();
  return (
    stats.isFile() &&
    !stats.isSymbolicLink()
    && extensions.indexOf(extension) >= 0
  );
}

function isFileIgnoredByLibrary(file) {
  var path = file.replace(/^\/code\//, "");
  var ignored = cli.isPathIgnored(path);
  if (ignored) {
    output = "File `" + path + "` ignored because of your .eslintignore file." + "\n";
    process.stderr.write(output);
  }
  return ignored;
}

function prunePathsWithinSymlinks(paths) {
  // Extracts symlinked paths and filters them out, including any child paths
  var symlinks = paths.filter(function(path) {
    return fs.lstatSync(path).isSymbolicLink();
  });

  return paths.filter(function(path) {
    var withinSymlink = false;
    symlinks.forEach(function(symlink) {
      if (path.indexOf(symlink) == 0) {
        withinSymlink = true;
      }
    });
    return !withinSymlink;
  });
}

function exclusionBasedFileListBuilder(excludePaths) {
  // Uses glob to traverse code directory and find files to analyze,
  // excluding files passed in with by CLI config, and including only
  // files in the list of desired extensions.
  //
  // Deprecated style of file expansion, supported for users of the old CLI.
  return function(extensions) {
    var analysisFiles = [];
    var allFiles = glob.sync("/code/**/**", {});

    prunePathsWithinSymlinks(allFiles).forEach(function(file, i, a){
      if(excludePaths.indexOf(file.split("/code/")[1]) < 0) {
        if(fs.lstatSync(file).isFile()) {
          if (!isFileIgnoredByLibrary(file) && isFileWithMatchingExtension(file, extensions)) {
            analysisFiles.push(file);
          }
        }
      }
    });

    return analysisFiles;
  };
}

function inclusionBasedFileListBuilder(includePaths) {
  // Uses glob to expand the files and directories in includePaths, filtering
  // down to match the list of desired extensions.
  return function(extensions) {
    var analysisFiles = [];

    includePaths.forEach(function(fileOrDirectory, i) {
      if ((/\/$/).test(fileOrDirectory)) {
        // if it ends in a slash, expand and push
        var filesInThisDirectory = glob.sync(
          "/code/" + fileOrDirectory + "/**/**"
        );
        prunePathsWithinSymlinks(filesInThisDirectory).forEach(function(file, j){
          if (!isFileIgnoredByLibrary(file) && isFileWithMatchingExtension(file, extensions)) {
            analysisFiles.push(file);
          }
        });
      } else {
        // if not, check for ending in *.js
        var fullPath = "/code/" + fileOrDirectory;
        if (!isFileIgnoredByLibrary(fullPath) && isFileWithMatchingExtension(fullPath, extensions)) {
          analysisFiles.push(fullPath);
        }
      }
    });

    return analysisFiles;
  };
}

var buildFileList;
runWithTiming("engineConfig", function () {
  if (fs.existsSync("/config.json")) {
    var engineConfig = JSON.parse(fs.readFileSync("/config.json"));

    if (engineConfig.include_paths) {
      buildFileList = inclusionBasedFileListBuilder(
        engineConfig.include_paths
      );
    } else if (engineConfig.exclude_paths) {
      var ignores = engineConfig.exclude_paths;
      buildFileList = exclusionBasedFileListBuilder(ignores);
    } else {
      // No includes or excludes, let's try with everything
      buildFileList = exclusionBasedFileListBuilder([]);
    }

    var userConfig = engineConfig.config || {};
    if (userConfig.config) {
      options.configFile = "/code/" + userConfig.config;
    }

    if (userConfig.extensions) {
      options.extensions = userConfig.extensions;
    }

    if (userConfig.debug) {
      debug = true;
    }
  }
});

var analysisFiles = runWithTiming("buildFileList", function() {
  return buildFileList(options.extensions);
});

function analyzeFiles() {
  var batchNum = 0,
      batchSize = 1,
      batchFiles,
      batchReport;

  while(analysisFiles.length > 0) {
    batchFiles = analysisFiles.splice(0, batchSize);

    if (debug) {
      process.stderr.write("Analyzing: " + batchFiles + "\n");
    }

    runWithTiming("analyze-batch-" + batchNum, function() {
       batchReport = cli.executeOnFiles(batchFiles);
    });
    runWithTiming("report-batch" + batchNum, function() {
      batchReport.results.forEach(function(result) {
        var path = result.filePath.replace(/^\/code\//, "");

        result.messages.forEach(function(message) {
          var issueJson = buildIssueJson(message, path);
          stdout(issueJson + "\u0000");
        });
      });
    });
    runWithTiming("gc-batch-" + batchNum, function() {
      batchFiles = null;
      batchReport = null;
      global.gc();
    });

    batchNum++;
  }
}

analyzeFiles();
<|endoftext|>


<commit_before>#!/usr/bin/env node

'use strict';

const args = require('yargs-parser')(process.argv.slice(2), {
    boolean: [
        'version',
        'help',
        'auto-restart',
    ],
    number: [
        'port',
    ],
    string: [
        'command',
        'path',
    ],
    alias: {
        'help': 'h',
        'version': 'v',
    },
    default: {
        'port': process.env.PORT | 1337,
        'auto-restart': true,
    }
});

const getMessage = (a) => a.message;

main(args);

function main() {
    if (args.help)
        return help();

    if (args.version)
        return version();

    if (args.path)
        return path();

    start({
        port: args.port,
        command: args.command,
        autoRestart: args.autoRestart,
    });
}

function path() {
    const join = require('path').join
    console.log(join(__dirname, '..'));
}

function start(options) {
    const squad = require('squad');

    let {
        port,
        command,
        autoRestart,
    } = options;

    check(port);

    const DIR = __dirname + '/../';

    const gritty  = require('../');
    const http = require('http');

    const express = require('express');
    const io = require('socket.io');

    const app = express();
    const server = http.createServer(app);

    const ip = process.env.IP ||  /* c9 */
              '0.0.0.0';

    app.use(gritty())
        .use(express.static(DIR));

    const socket = io.listen(server);

    gritty.listen(socket, {
        command,
        autoRestart,
    });

    server.listen(port, ip)
        .on('error', squad(exit, getMessage));

    console.log(`url: http://localhost:${port}`);
}

function help() {
    const bin = require('../help');
    const usage = 'Usage: gritty [options]';

    console.log(usage);
    console.log('Options:');

    Object.keys(bin).forEach((name) => {
        console.log('  %s %s', name, bin[name]);
    });
}

function version() {
    const pack = require('../package');
    console.log('v' + pack.version);
}

function check(port) {
    if (isNaN(port))
        exit('port should be a number 0..65535');
}

function exit(msg) {
    console.error(msg);
    process.exit(-1);
}

<commit_msg>fix(gritty) --path<commit_after>#!/usr/bin/env node

'use strict';

const args = require('yargs-parser')(process.argv.slice(2), {
    boolean: [
        'version',
        'help',
        'auto-restart',
        'path',
    ],
    number: [
        'port',
    ],
    string: [
        'command',
    ],
    alias: {
        'help': 'h',
        'version': 'v',
    },
    default: {
        'port': process.env.PORT | 1337,
        'auto-restart': true,
    }
});

const getMessage = (a) => a.message;

main(args);

function main() {
    if (args.help)
        return help();

    if (args.version)
        return version();

    if (args.path)
        return path();

    start({
        port: args.port,
        command: args.command,
        autoRestart: args.autoRestart,
    });
}

function path() {
    const join = require('path').join
    console.log(join(__dirname, '..'));
}

function start(options) {
    const squad = require('squad');

    let {
        port,
        command,
        autoRestart,
    } = options;

    check(port);

    const DIR = __dirname + '/../';

    const gritty  = require('../');
    const http = require('http');

    const express = require('express');
    const io = require('socket.io');

    const app = express();
    const server = http.createServer(app);

    const ip = process.env.IP ||  /* c9 */
              '0.0.0.0';

    app.use(gritty())
        .use(express.static(DIR));

    const socket = io.listen(server);

    gritty.listen(socket, {
        command,
        autoRestart,
    });

    server.listen(port, ip)
        .on('error', squad(exit, getMessage));

    console.log(`url: http://localhost:${port}`);
}

function help() {
    const bin = require('../help');
    const usage = 'Usage: gritty [options]';

    console.log(usage);
    console.log('Options:');

    Object.keys(bin).forEach((name) => {
        console.log('  %s %s', name, bin[name]);
    });
}

function version() {
    const pack = require('../package');
    console.log('v' + pack.version);
}

function check(port) {
    if (isNaN(port))
        exit('port should be a number 0..65535');
}

function exit(msg) {
    console.error(msg);
    process.exit(-1);
}

<|endoftext|>


<commit_before>var socket = require('socket.io-client');
var $ = require('jquery');

function calculateSizes($el) {
  return {
    width: $el.width(),
    height: $el.height(),
    aspect: $el.width() / $el.height()
  }
}

class Viewer {
  constructor($container) {
    this.$elements = {
      container: $container,
      viewer: $container.find('.event-viewer'),
      canvas: $container.find('.event-viewer-touch')
    }

    this.canvas = this.$elements.canvas[0];

    this.bounds = {
      viewer: calculateSizes(this.$elements.viewer)
    }

    this.pointers = [];

    this.resize();
    this._initSockets();
    this._initDrawing();

    $(window).on('resize', this.resize.bind(this));
  }

  resize() {
    this.bounds.container = calculateSizes(this.$elements.container);
    this.devicePixelRatio = window.devicePixelRatio || 1;

    var scaleThrough = 'width';

    // Container is wider than viewer, scale by height
    if (this.bounds.container.aspect > this.bounds.viewer.aspect) {
      scaleThrough = 'height';
    }

    var scale = this.bounds.container[scaleThrough] / this.bounds.viewer[scaleThrough];
    this.canvasScale = (window.devicePixelRatio || 1) * scale;
    this.canvas.width = this.bounds.viewer.width * this.canvasScale;
    this.canvas.height = this.bounds.viewer.height * this.canvasScale;
    this.$elements.viewer.css('transform', `scale(${scale})`);
  }

  _initSockets() {
    var id = null;
    var io = this.io = socket('/view');

    io.on('connect', function () {
      console.log('Connection Successful');
    });

    io.on('welcome', function (data) {
      if (id == null) {
        id = data.id;
        console.log(id);
      } else if (id != data.id) {
        location.reload(true);
      }
    });

    io.on('pointers', (data) => {

      this.pointers = data.map((p) => ({
        x: p[0],
        y: p[1],
        id: p[2],
        from: p[3],
        dead: false,
        opacity: 0,
        color: '#fff'
      }));

      // console.log(this.pointers);
    });
  }

  _initDrawing() {
    var draw = () => {
      var ctx = this.canvas.getContext('2d');

      ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);

      this.pointers.forEach((p) => {
        p.newx = p.x * this.canvas.width;
        p.newy = p.y * this.canvas.height;
      });

      this.pointers.forEach((p) => {
        ctx.fillStyle = p.color;
        ctx.beginPath();
        ctx.arc(p.newx, p.newy, 8 * this.canvasScale, 0, Math.PI * 2);
        ctx.fill();
      });

      requestAnimationFrame(draw);
    }

    requestAnimationFrame(draw);
  }
}

module.exports = function () {
  if ($('.event-viewer').length != 0) {
    var viewer = new Viewer($('.event-viewer-container'));
  }
};
<commit_msg>Add touch-connection rendering<commit_after>var socket = require('socket.io-client');
var $ = require('jquery');

const PHI = (1 + Math.sqrt(5)) / 2;

function calculateSizes($el) {
  return {
    width: $el.width(),
    height: $el.height(),
    aspect: $el.width() / $el.height()
  }
}

class Viewer {
  constructor($container) {
    this.$elements = {
      container: $container,
      viewer: $container.find('.event-viewer'),
      canvas: $container.find('.event-viewer-touch')
    }

    this.canvas = this.$elements.canvas[0];

    this.bounds = {
      viewer: calculateSizes(this.$elements.viewer)
    }

    this.pointers = [];

    this.resize();
    this._initSockets();
    this._initDrawing();

    $(window).on('resize', this.resize.bind(this));
  }

  resize() {
    this.bounds.container = calculateSizes(this.$elements.container);
    this.devicePixelRatio = window.devicePixelRatio || 1;

    var scaleThrough = 'width';

    // Container is wider than viewer, scale by height
    if (this.bounds.container.aspect > this.bounds.viewer.aspect) {
      scaleThrough = 'height';
    }

    var scale = this.bounds.container[scaleThrough] / this.bounds.viewer[scaleThrough];
    this.canvasScale = (window.devicePixelRatio || 1) * scale;
    this.canvas.width = this.bounds.viewer.width * this.canvasScale;
    this.canvas.height = this.bounds.viewer.height * this.canvasScale;
    this.$elements.viewer.css('transform', `scale(${scale})`);
  }

  _initSockets() {
    var id = null;
    var io = this.io = socket('/view');

    io.on('connect', function () {
      console.log('Connection Successful');
    });

    io.on('welcome', function (data) {
      if (id == null) {
        id = data.id;
        console.log(id);
      } else if (id != data.id) {
        location.reload(true);
      }
    });

    var encodeString = function (s) {
      var number = 0;
      for (var i = 0; i < s.length; i ++) {
        number += s.charCodeAt(i);
      }

      return number;
    }

    io.on('pointers', (data) => {
      this.pointers.forEach((p) => { p.dead = true; });

      // Iterate over pointers, only add new ones that don't exist
      // Otherwise just update existing ones
      data.forEach((dat) => {
        var from = dat[3];
        var hue = ((encodeString(from) % 100) + 280).toFixed(3);
        var newp = {
          x: dat[0],
          y: dat[1],
          id: dat[2],
          from: from,
          dead: false,
          opacity: 0,
          hue: hue,
          found: true
        };

        var found = this.pointers.some((p) => {
          if ((p.from == newp.from) && (p.id == newp.id)) {
            p.x = newp.x;
            p.y = newp.y;
            p.dead = false;

            return true;
          }

          return false;
        });

        if (!found) {
          this.pointers.push(newp);
        }
      });

      this.pointers = this.pointers.filter((p) => !((p.dead) && (p.opacity <= 0)));
    });
  }

  _initDrawing() {
    var draw = () => {
      var ctx = this.canvas.getContext('2d');

      ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);

      for (var i = 0; i < this.pointers.length; i ++) {
        var p = this.pointers[i];
        p.newx = p.x * this.canvas.width;
        p.newy = p.y * this.canvas.height;
        p.color = `hsla(${p.hue}, 100%, 50%, ${p.opacity})`;

        if (p.dead) {
          if (p.opacity > 0) {
            p.opacity -= 0.1;
          }
        } else {
          if (p.opacity < 1) {
            p.opacity += 0.1;
          }

        }
      }

      // Draw Lines
      var len = this.pointers.length;
      for (var i = 0; i < len; i ++) {
        var p1 = this.pointers[i];

        for (var n = i + 1; n < len; n ++) {
          var p2 = this.pointers[n];

          if (p1.from !== p2.from) {
            // Get squared distance adjusted for aspect ratio
            var dis = Math.pow((p1.newx - p2.newx) / this.canvas.height, 2) + Math.pow(p1.y - p2.y, 2);
            if (dis < 0.08) {
              var grad = ctx.createLinearGradient(p1.newx, p1.newy, p2.newx, p2.newy);

              grad.addColorStop(0, p1.color);
              grad.addColorStop(1, p2.color);

              ctx.strokeStyle = grad;
              ctx.lineWidth = (1 - dis / 0.08) * 2;

              ctx.beginPath();

              ctx.moveTo(p1.newx, p1.newy);
              ctx.lineTo(p2.newx, p2.newy);

              ctx.stroke();
            }
          }
        }

      }

      // Draw Touches
      this.pointers.forEach((p) => {
        ctx.fillStyle = p.color;
        ctx.beginPath();
        ctx.arc(p.newx, p.newy, 8 * this.canvasScale, 0, Math.PI * 2);
        ctx.fill();
      });

      requestAnimationFrame(draw);
    }

    requestAnimationFrame(draw);
  }
}

module.exports = function () {
  if ($('.event-viewer').length != 0) {
    var viewer = new Viewer($('.event-viewer-container'));
  }
};
<|endoftext|>


<commit_before>"use strict";

require('colors');
const moment = require('moment');

const fatal = function (message) {
    console.log(`FATAL [${moment().format('HH:mm:ss')}]: ${message}`.bgRed);

    process.exit();
};

const error = function (message) {
    console.log(`ERROR [${moment().format('HH:mm:ss')}]: ${message}`.red);
};

const warn = function (message) {
    console.log(`WARN [${moment().format('HH:mm:ss')}]: ${message}`.yellow);
};

const info = function (message) {
    console.log(`INFO [${moment().format('HH:mm:ss')}]: ${message}`.cyan);
};

const success = function (message) {
    console.log(`SUCCESS [${moment().format('HH:mm:ss')}]: ${message}`.green);
};

const failed = function (message) {
    console.log(`FAILED [${moment().format('HH:mm:ss')}]: ${message}`.red);
};

const log = function (message) {
    console.log(`LOG [${moment().format('HH:mm:ss')}]: ${message}`);
};

module.exports = {
    fatal: fatal,
    error: error,
    warn: warn,
    info: info,
    success: success,
    failed: failed,
    log: log,
};
<commit_msg>improve console tools<commit_after>"use strict";

require('colors');
const moment = require('moment');

const fatal = function () {
    let message = Object.values(arguments).join(', ');

    console.log(`FATAL [${moment().format('HH:mm:ss')}]: ${message}`.bgRed);

    process.exit();
};

const error = function () {
    let message = Object.values(arguments).join(', ');

    console.log(`ERROR [${moment().format('HH:mm:ss')}]: ${message}`.red);
};

const warn = function () {
    let message = Object.values(arguments).join(', ');

    console.log(`WARN [${moment().format('HH:mm:ss')}]: ${message}`.yellow);
};

const info = function () {
    let message = Object.values(arguments).join(', ');

    console.log(`INFO [${moment().format('HH:mm:ss')}]: ${message}`.cyan);
};

const success = function () {
    let message = Object.values(arguments).join(', ');

    console.log(`SUCCESS [${moment().format('HH:mm:ss')}]: ${message}`.green);
};

const failed = function () {
    let message = Object.values(arguments).join(', ');

    console.log(`FAILED [${moment().format('HH:mm:ss')}]: ${message}`.red);
};

const log = function () {
    let message = Object.values(arguments).join(', ');

    console.log(`LOG [${moment().format('HH:mm:ss')}]: ${message}`);
};

module.exports = {
    fatal: fatal,
    error: error,
    warn: warn,
    info: info,
    success: success,
    failed: failed,
    log: log,
};
<|endoftext|>


<commit_before>/**
 * Yii GridView widget.
 *
 * This is the JavaScript widget used by the yii\grid\GridView widget.
 *
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
(function ($) {
	$.fn.yiiGridView = function (method) {
		if (methods[method]) {
			return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
		} else if (typeof method === 'object' || !method) {
			return methods.init.apply(this, arguments);
		} else {
			$.error('Method ' + method + ' does not exist on jQuery.yiiGridView');
			return false;
		}
	};

	var defaults = {
		filterUrl: undefined,
		filterSelector: undefined
	};

	var methods = {
		init: function (options) {
			return this.each(function () {
				var $e = $(this);
				var settings = $.extend({}, defaults, options || {});
				$e.data('yiiGridView', {
					settings: settings
				});

				var enterPressed = false;
				$(settings.filterSelector).on('change.yiiGridView keydown.yiiGridView', function (event) {
					if (event.type === 'keydown') {
						if (event.keyCode !== 13) {
							return; // only react to enter key
						} else {
							enterPressed = true;
						}
					} else {
						// prevent processing for both keydown and change events
						if (enterPressed) {
							enterPressed = false;
							return;
						}
					}

					methods.applyFilter.apply($e);

					return false;
				});
			});
		},

		applyFilter: function () {
			var $grid = $(this);
			var settings = $grid.data('yiiGridView').settings;
			var data = $(settings.filterSelector).serialize();
			var url = settings.filterUrl;
			if (url.indexOf('?') >= 0) {
				url += '&' + data;
			} else {
				url += '?' + data;
			}

			$grid.find('form.gridview-filter-form').remove();
			var $form = $('<form action="' + url + '" method="get" class="gridview-filter-form" style="display:none" data-pjax></form>').appendTo($grid);
			$.each(yii.getQueryParams(url), function (name, value) {
				$form.append($('<input type="hidden" name="t" value="" />').attr('name', name).val(value));
			});
			$form.submit();
		},

		setSelectionColumn: function (options) {
			var $grid = $(this);
			var data = $grid.data('yiiGridView');
			data.selectionColumn = options.name;
			if (!options.multiple) {
				return;
			}
			$grid.on('click.yiiGridView', "input[name='" + options.checkAll + "']", function () {
				$grid.find("input[name='" + options.name + "']:enabled").prop('checked', this.checked);
			});
			$grid.on('click.yiiGridView', "input[name='" + options.name + "']:enabled", function () {
				var all = $grid.find("input[name='" + options.name + "']").length == $grid.find("input[name='" + options.name + "']:checked").length;
				$grid.find("input[name='" + options.checkAll + "']").prop('checked', all);
			});
		},

		getSelectedRows: function () {
			var $grid = $(this);
			var data = $grid.data('yiiGridView');
			var keys = [];
			if (data.selectionColumn) {
				$grid.find("input[name='" + data.selectionColumn + "']:checked").each(function () {
					keys.push($(this).parent().closest('tr').data('key'));
				});
			}
			return keys;
		},

		destroy: function () {
			return this.each(function () {
				$(window).unbind('.yiiGridView');
				$(this).removeData('yiiGridView');
			});
		},

		data: function() {
			return this.data('yiiGridView');
		}
	};
})(window.jQuery);

<commit_msg>removed duplicated query parameters.<commit_after>/**
 * Yii GridView widget.
 *
 * This is the JavaScript widget used by the yii\grid\GridView widget.
 *
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
(function ($) {
	$.fn.yiiGridView = function (method) {
		if (methods[method]) {
			return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
		} else if (typeof method === 'object' || !method) {
			return methods.init.apply(this, arguments);
		} else {
			$.error('Method ' + method + ' does not exist on jQuery.yiiGridView');
			return false;
		}
	};

	var defaults = {
		filterUrl: undefined,
		filterSelector: undefined
	};

	var methods = {
		init: function (options) {
			return this.each(function () {
				var $e = $(this);
				var settings = $.extend({}, defaults, options || {});
				$e.data('yiiGridView', {
					settings: settings
				});

				var enterPressed = false;
				$(settings.filterSelector).on('change.yiiGridView keydown.yiiGridView', function (event) {
					if (event.type === 'keydown') {
						if (event.keyCode !== 13) {
							return; // only react to enter key
						} else {
							enterPressed = true;
						}
					} else {
						// prevent processing for both keydown and change events
						if (enterPressed) {
							enterPressed = false;
							return;
						}
					}

					methods.applyFilter.apply($e);

					return false;
				});
			});
		},

		applyFilter: function () {
			var $grid = $(this);
			var settings = $grid.data('yiiGridView').settings;
			var data = {};
			$.each($(settings.filterSelector).serializeArray(), function () {
				data[this.name] = this.value;
			});

			$.each(yii.getQueryParams(settings.filterUrl), function (name, value) {
				if (data[name] === undefined) {
					data[name] = value;
				}
			});

			var pos = settings.filterUrl.indexOf('?');
			var url = pos < 0 ? settings.filterUrl : settings.filterUrl.substring(0, pos);

			$grid.find('form.gridview-filter-form').remove();
			var $form = $('<form action="' + url + '" method="get" class="gridview-filter-form" style="display:none" data-pjax></form>').appendTo($grid);
			$.each(data, function (name, value) {
				$form.append($('<input type="hidden" name="t" value="" />').attr('name', name).val(value));
			});
			$form.submit();
		},

		setSelectionColumn: function (options) {
			var $grid = $(this);
			var data = $grid.data('yiiGridView');
			data.selectionColumn = options.name;
			if (!options.multiple) {
				return;
			}
			$grid.on('click.yiiGridView', "input[name='" + options.checkAll + "']", function () {
				$grid.find("input[name='" + options.name + "']:enabled").prop('checked', this.checked);
			});
			$grid.on('click.yiiGridView', "input[name='" + options.name + "']:enabled", function () {
				var all = $grid.find("input[name='" + options.name + "']").length == $grid.find("input[name='" + options.name + "']:checked").length;
				$grid.find("input[name='" + options.checkAll + "']").prop('checked', all);
			});
		},

		getSelectedRows: function () {
			var $grid = $(this);
			var data = $grid.data('yiiGridView');
			var keys = [];
			if (data.selectionColumn) {
				$grid.find("input[name='" + data.selectionColumn + "']:checked").each(function () {
					keys.push($(this).parent().closest('tr').data('key'));
				});
			}
			return keys;
		},

		destroy: function () {
			return this.each(function () {
				$(window).unbind('.yiiGridView');
				$(this).removeData('yiiGridView');
			});
		},

		data: function() {
			return this.data('yiiGridView');
		}
	};
})(window.jQuery);

<|endoftext|>


<commit_before>#!/usr/bin/env node
'use strict'

process.title = 'netiam'

const resolve = require('resolve')
const exit = require('exit')

resolve('netiam-cli', {
  basedir: process.cwd()
}, (err, projectLocalCli) => {
  let cli

  if (err) {
    cli = require('../lib/cli')
  } else {
    cli = require(projectLocalCli)
  }

  cli({
    cliArgs: process.argv.slice(2),
    inputStream: process.stdin,
    outputStream: process.stdout
  })
    .then(result => {
      var exitCode = typeof result === 'object' ? result.exitCode : result
      exit(exitCode)
    })
    .catch(err => {
      console.error(err)
      console.error(err.stack)
    })

})
<commit_msg>refactor: use sync version to require cli<commit_after>#!/usr/bin/env node
'use strict'

process.title = 'netiam'

const resolve = require('resolve')
const exit = require('exit')

let cli
try {
  const projectLocalCli = resolve.sync('netiam-cli', {basedir: process.cwd()})
  cli = require(projectLocalCli)
} catch (err) {
  cli = require('../src/cli')
}

cli({
  cliArgs: process.argv.slice(2),
  inputStream: process.stdin,
  outputStream: process.stdout
})
  .then(result => {
    const exitCode = typeof result === 'object' ? result.exitCode : result
    exit(exitCode)
  })
  .catch(err => console.error(err))
<|endoftext|>


<commit_before>describe('Utilities page', () => {
  beforeEach(() => {
    cy.cleanupElasticsearch()
    cy.quickConnect()
    cy.visit('/utilities')
  })

  describe('creating data', () => {
    it('creates 10 indices', () => {
      cy.get('#utility_create_createIndices').click()
      cy.get('#utility_create_createIndices', { timeout: 10000 }).should('not.have.class', 'v-btn v-btn--loader') // wait for all requests
      cy.flushIndices().then(() => {
        cy.wait(250)
        cy.catIndices().then(response => {
          expect(response.body).not.to.be.empty
          expect(response.body).to.have.lengthOf(10)
        })
      })
    })

    it('creates twitter index and tweets', () => {
      cy.get('#utility_create_bulk').click()
      cy.get('#utility_create_bulk', { timeout: 1000 }).should('not.have.class', 'v-btn v-btn--loader')
      cy.flushIndices().then(() => {
        cy.catIndices().then(response => {
          expect(response.body).not.to.be.empty
          expect(response.body).to.have.lengthOf(1)
          expect(response.body[0]['docs.count']).to.equal('100')
        })
      })
    })
  })

  describe('deleting data', () => {
    it('deletes all indices', () => {
      cy.createIndex('some-index')
      cy.flushIndices().then(() => {
        cy.get('#utility_delete_indicesDelete').click()
        cy.get('#utility_delete_indicesDelete', { timeout: 1000 }).should('not.have.class', 'v-btn v-btn--loader')
        cy.catIndices().then(response => {
          expect(response.body).to.be.empty
          expect(response.body).to.have.lengthOf(0)
        })
      })
    })
  })
})
<commit_msg>fix utilities e2e spec<commit_after>describe('Utilities page', () => {
  beforeEach(() => {
    cy.cleanupElasticsearch()
    cy.quickConnect()
    cy.visit('/utilities')
  })

  describe('creating data', () => {
    it('creates 10 indices', () => {
      cy.get('#utility_create_createIndices').click()
      cy.get('#utility_create_createIndices', { timeout: 10000 }).should('not.have.class', 'v-btn v-btn--loader') // wait for all requests
      cy.wait(250)
      cy.flushIndices().then(() => {
        cy.wait(250)
        cy.catIndices().then(response => {
          expect(response.body).not.to.be.empty
          expect(response.body).to.have.lengthOf(10)
        })
      })
    })

    it('creates twitter index and tweets', () => {
      cy.get('#utility_create_bulk').click()
      cy.get('#utility_create_bulk', { timeout: 1000 }).should('not.have.class', 'v-btn v-btn--loader')
      cy.wait(250)
      cy.flushIndices().then(() => {
        cy.catIndices().then(response => {
          expect(response.body).not.to.be.empty
          expect(response.body).to.have.lengthOf(1)
          expect(response.body[0]['docs.count']).to.equal('100')
        })
      })
    })
  })

  describe('deleting data', () => {
    it('deletes all indices', () => {
      cy.createIndex('some-index')
      cy.flushIndices().then(() => {
        cy.get('#utility_delete_indicesDelete').click()
        cy.get('#utility_delete_indicesDelete', { timeout: 1000 }).should('not.have.class', 'v-btn v-btn--loader')
        cy.wait(250)
        cy.catIndices().then(response => {
          expect(response.body).to.be.empty
          expect(response.body).to.have.lengthOf(0)
        })
      })
    })
  })
})
<|endoftext|>


<commit_before>#!/usr/bin/env node

require('../lib/node-version-check'); // @note that this should not respect CLI --silent

const _ = require('lodash'),
    waterfall = require('async/waterfall'),
    { Command } = require('commander'),
    program = new Command(),
    version = require('../package.json').version,
    newman = require('../'),
    util = require('./util');

program
    .name('newman')
    .addHelpCommand(false)
    .version(version, '-v, --version');

// The `run` command allows you to specify a collection to be run with the provided options.
program
    .command('run <collection>')
    .description('URL or path to a Postman Collection')
    .usage('<collection> [options]')
    .option('-e, --environment <path>', 'Specify a URL or path to a Postman Environment')
    .option('-g, --globals <path>', 'Specify a URL or path to a file containing Postman Globals')
    .option('-r, --reporters [reporters]', 'Specify the reporters to use for this run', util.cast.csvParse, ['cli'])
    .option('-n, --iteration-count <n>', 'Define the number of iterations to run', util.cast.integer)
    .option('-d, --iteration-data <path>', 'Specify a data file to use for iterations (either JSON or CSV)')
    .option('--folder <path>',
        'Specify the folder to run from a collection. Can be specified multiple times to run multiple folders',
        util.cast.memoize, [])
    .option('--global-var <value>',
        'Allows the specification of global variables via the command line, in a key=value format',
        util.cast.memoizeKeyVal, [])
    .option('--env-var <value>',
        'Allows the specification of environment variables via the command line, in a key=value format',
        util.cast.memoizeKeyVal, [])
    .option('--export-environment <path>', 'Exports the final environment to a file after completing the run')
    .option('--export-globals <path>', 'Exports the final globals to a file after completing the run')
    .option('--export-collection <path>', 'Exports the executed collection to a file after completing the run')
    .option('--postman-api-key <apiKey>', 'API Key used to load the resources from the Postman API')
    .option('--bail [modifiers]',
        'Specify whether or not to gracefully stop a collection run on encountering an error' +
        ' and whether to end the run with an error based on the optional modifier', util.cast.csvParse)
    .option('--ignore-redirects', 'Prevents Newman from automatically following 3XX redirect responses')
    .option('-x , --suppress-exit-code', 'Specify whether or not to override the default exit code for the current run')
    .option('--silent', 'Prevents Newman from showing output to CLI')
    .option('--disable-unicode', 'Forces Unicode compliant symbols to be replaced by their plain text equivalents')
    .option('--color <value>', 'Enable/Disable colored output (auto|on|off)', util.cast.colorOptions, 'auto')
    .option('--delay-request [n]', 'Specify the extent of delay between requests (milliseconds)', util.cast.integer, 0)
    .option('--timeout [n]', 'Specify a timeout for collection run (milliseconds)', util.cast.integer, 0)
    .option('--timeout-request [n]', 'Specify a timeout for requests (milliseconds)', util.cast.integer, 0)
    .option('--timeout-script [n]', 'Specify a timeout for scripts (milliseconds)', util.cast.integer, 0)
    .option('--working-dir <path>', 'Specify the path to the working directory')
    .option('--no-insecure-file-read', 'Prevents reading the files situated outside of the working directory')
    .option('-k, --insecure', 'Disables SSL validations')
    .option('--ssl-client-cert-list <path>', 'Specify the path to a client certificates configurations (JSON)')
    .option('--ssl-client-cert <path>', 'Specify the path to a client certificate (PEM)')
    .option('--ssl-client-key <path>', 'Specify the path to a client certificate private key')
    .option('--ssl-client-passphrase <passphrase>', 'Specify the client certificate passphrase (for protected key)')
    .option('--ssl-extra-ca-certs <path>', 'Specify additionally trusted CA certificates (PEM)')
    .option('--cookie-jar <path>', 'Specify the path to a custom cookie jar (serialized tough-cookie JSON) ')
    .option('--export-cookie-jar <path>', 'Exports the cookie jar to a file after completing the run')
    .option('--verbose', 'Show detailed information of collection run and each request sent')
    .action((collection, command) => {
        let options = util.commanderToObject(command),

            // parse custom reporter options
            reporterOptions = util.parseNestedOptions(program._originalArgs, '--reporter-', options.reporters);

        // Inject additional properties into the options object
        options.collection = collection;
        options.reporterOptions = reporterOptions._generic;
        options.reporter = _.transform(_.omit(reporterOptions, '_generic'), (acc, value, key) => {
            acc[key] = _.assignIn(value, reporterOptions._generic); // overrides reporter options with _generic
        }, {});

        newman.run(options, function (err, summary) {
            const runError = err || summary.run.error || summary.run.failures.length;

            if (err) {
                console.error(`error: ${err.message || err}\n`);
                err.friendly && console.error(`  ${err.friendly}\n`);
            }
            runError && !_.get(options, 'suppressExitCode') && process.exit(1);
        });
    });

program.on('--help', function () {
    console.info('\nTo get available options for a command:');
    console.info('  newman <command> -h');
});

// Warn on invalid command and then exits.
program.on('command:*', (command) => {
    console.error(`error: invalid command \`${command}\`\n`);
    program.help();
});

/**
 * Starts the script execution.
 * callback is required when this is required as a module in tests.
 *
 * @param {String[]} argv - Argument vector.
 * @param {?Function} callback - The callback function invoked on the completion of execution.
 */
function run (argv, callback) {
    waterfall([
        (next) => {
            // cache original argv, required to parse nested options later.
            program._originalArgs = argv;
            // omit custom nested options, otherwise commander will throw unknown options error
            next(null, util.omitNestedOptions(argv, '--reporter-'));
        },
        (args, next) => {
            let error = null;

            try {
                program.parse(args);
            }
            catch (err) {
                error = err;
            }
            next(error);
        },
        (next) => {
            // throw error if no argument is provided.
            next(program.args.length ? null : new Error('no arguments provided'));
        }
    ], (error) => {
        // invoke callback if this is required as module, used in tests.
        if (callback) { return callback(error); }

        // in case of an error, log error message and print help message.
        if (error) {
            console.error(`error: ${error.message || error}\n`);
            program.help();
        }
    });
}

// This hack has been added from https://github.com/nodejs/node/issues/6456#issue-151760275
// @todo: remove when https://github.com/nodejs/node/issues/6456 has been fixed
(Number(process.version[1]) >= 6) && [process.stdout, process.stderr].forEach((s) => {
    s && s.isTTY && s._handle && s._handle.setBlocking && s._handle.setBlocking(true);
});

// Run this script if this is a direct stdin.
!module.parent && run(process.argv);

// Export to allow debugging and testing.
module.exports = run;
<commit_msg>Update CLI run command description<commit_after>#!/usr/bin/env node

require('../lib/node-version-check'); // @note that this should not respect CLI --silent

const _ = require('lodash'),
    waterfall = require('async/waterfall'),
    { Command } = require('commander'),
    program = new Command(),
    version = require('../package.json').version,
    newman = require('../'),
    util = require('./util');

program
    .name('newman')
    .addHelpCommand(false)
    .version(version, '-v, --version');

// The `run` command allows you to specify a collection to be run with the provided options.
program
    .command('run <collection>')
    .description('Initiate a Postman Collection run from a given URL or path')
    .usage('<collection> [options]')
    .option('-e, --environment <path>', 'Specify a URL or path to a Postman Environment')
    .option('-g, --globals <path>', 'Specify a URL or path to a file containing Postman Globals')
    .option('-r, --reporters [reporters]', 'Specify the reporters to use for this run', util.cast.csvParse, ['cli'])
    .option('-n, --iteration-count <n>', 'Define the number of iterations to run', util.cast.integer)
    .option('-d, --iteration-data <path>', 'Specify a data file to use for iterations (either JSON or CSV)')
    .option('--folder <path>',
        'Specify the folder to run from a collection. Can be specified multiple times to run multiple folders',
        util.cast.memoize, [])
    .option('--global-var <value>',
        'Allows the specification of global variables via the command line, in a key=value format',
        util.cast.memoizeKeyVal, [])
    .option('--env-var <value>',
        'Allows the specification of environment variables via the command line, in a key=value format',
        util.cast.memoizeKeyVal, [])
    .option('--export-environment <path>', 'Exports the final environment to a file after completing the run')
    .option('--export-globals <path>', 'Exports the final globals to a file after completing the run')
    .option('--export-collection <path>', 'Exports the executed collection to a file after completing the run')
    .option('--postman-api-key <apiKey>', 'API Key used to load the resources from the Postman API')
    .option('--bail [modifiers]',
        'Specify whether or not to gracefully stop a collection run on encountering an error' +
        ' and whether to end the run with an error based on the optional modifier', util.cast.csvParse)
    .option('--ignore-redirects', 'Prevents Newman from automatically following 3XX redirect responses')
    .option('-x , --suppress-exit-code', 'Specify whether or not to override the default exit code for the current run')
    .option('--silent', 'Prevents Newman from showing output to CLI')
    .option('--disable-unicode', 'Forces Unicode compliant symbols to be replaced by their plain text equivalents')
    .option('--color <value>', 'Enable/Disable colored output (auto|on|off)', util.cast.colorOptions, 'auto')
    .option('--delay-request [n]', 'Specify the extent of delay between requests (milliseconds)', util.cast.integer, 0)
    .option('--timeout [n]', 'Specify a timeout for collection run (milliseconds)', util.cast.integer, 0)
    .option('--timeout-request [n]', 'Specify a timeout for requests (milliseconds)', util.cast.integer, 0)
    .option('--timeout-script [n]', 'Specify a timeout for scripts (milliseconds)', util.cast.integer, 0)
    .option('--working-dir <path>', 'Specify the path to the working directory')
    .option('--no-insecure-file-read', 'Prevents reading the files situated outside of the working directory')
    .option('-k, --insecure', 'Disables SSL validations')
    .option('--ssl-client-cert-list <path>', 'Specify the path to a client certificates configurations (JSON)')
    .option('--ssl-client-cert <path>', 'Specify the path to a client certificate (PEM)')
    .option('--ssl-client-key <path>', 'Specify the path to a client certificate private key')
    .option('--ssl-client-passphrase <passphrase>', 'Specify the client certificate passphrase (for protected key)')
    .option('--ssl-extra-ca-certs <path>', 'Specify additionally trusted CA certificates (PEM)')
    .option('--cookie-jar <path>', 'Specify the path to a custom cookie jar (serialized tough-cookie JSON) ')
    .option('--export-cookie-jar <path>', 'Exports the cookie jar to a file after completing the run')
    .option('--verbose', 'Show detailed information of collection run and each request sent')
    .action((collection, command) => {
        let options = util.commanderToObject(command),

            // parse custom reporter options
            reporterOptions = util.parseNestedOptions(program._originalArgs, '--reporter-', options.reporters);

        // Inject additional properties into the options object
        options.collection = collection;
        options.reporterOptions = reporterOptions._generic;
        options.reporter = _.transform(_.omit(reporterOptions, '_generic'), (acc, value, key) => {
            acc[key] = _.assignIn(value, reporterOptions._generic); // overrides reporter options with _generic
        }, {});

        newman.run(options, function (err, summary) {
            const runError = err || summary.run.error || summary.run.failures.length;

            if (err) {
                console.error(`error: ${err.message || err}\n`);
                err.friendly && console.error(`  ${err.friendly}\n`);
            }
            runError && !_.get(options, 'suppressExitCode') && process.exit(1);
        });
    });

program.on('--help', function () {
    console.info('\nTo get available options for a command:');
    console.info('  newman <command> -h');
});

// Warn on invalid command and then exits.
program.on('command:*', (command) => {
    console.error(`error: invalid command \`${command}\`\n`);
    program.help();
});

/**
 * Starts the script execution.
 * callback is required when this is required as a module in tests.
 *
 * @param {String[]} argv - Argument vector.
 * @param {?Function} callback - The callback function invoked on the completion of execution.
 */
function run (argv, callback) {
    waterfall([
        (next) => {
            // cache original argv, required to parse nested options later.
            program._originalArgs = argv;
            // omit custom nested options, otherwise commander will throw unknown options error
            next(null, util.omitNestedOptions(argv, '--reporter-'));
        },
        (args, next) => {
            let error = null;

            try {
                program.parse(args);
            }
            catch (err) {
                error = err;
            }
            next(error);
        },
        (next) => {
            // throw error if no argument is provided.
            next(program.args.length ? null : new Error('no arguments provided'));
        }
    ], (error) => {
        // invoke callback if this is required as module, used in tests.
        if (callback) { return callback(error); }

        // in case of an error, log error message and print help message.
        if (error) {
            console.error(`error: ${error.message || error}\n`);
            program.help();
        }
    });
}

// This hack has been added from https://github.com/nodejs/node/issues/6456#issue-151760275
// @todo: remove when https://github.com/nodejs/node/issues/6456 has been fixed
(Number(process.version[1]) >= 6) && [process.stdout, process.stderr].forEach((s) => {
    s && s.isTTY && s._handle && s._handle.setBlocking && s._handle.setBlocking(true);
});

// Run this script if this is a direct stdin.
!module.parent && run(process.argv);

// Export to allow debugging and testing.
module.exports = run;
<|endoftext|>