<commit_before>/* jshint esversion:6, node: true */

'use strict';

const express = require('express');
const bodyParser = require('body-parser');
const request = require('request');
const app = express();

app.set('port', (process.env.PORT || 5000));

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({extended: false}));

// parse application/json
app.use(bodyParser.json());

// index
app.get('/', function (req, res) {
	res.send('hello world i am a secret bot');
});

// for facebook verification
app.get('/webhook/', function (req, res) {
	if (req.query['hub.verify_token'] === 'my_voice_is_my_password_verify_me') {
		res.send(req.query['hub.challenge']);
	} else {
		res.send('Error, wrong token');
	}
});

// to post data
app.post('/webhook/', function (req, res) {
	var results;

	let messaging_events = req.body.entry[0].messaging;
	for (let i = 0; i < messaging_events.length; i++) {
		let event = req.body.entry[0].messaging[i];
		let sender = event.sender.id;

		if (event.message && event.message.text) {
			let text = event.message.text;
			if (text === 'Generic') {
				sendGenericMessage(sender);
				continue;
			}

			else if (text == 'cookies'){
				var headers = {
				    'Authorization': 'bearer fd887ce5-7b15-4c1e-93a0-dc91ce883ec6'
				};

				var options = {
				    url: 'https://www.loblaws.ca/ecommerce/v2/loblaw/products/search?q=apple&page=0&pageSize=10&sort=recommended&filters=category:LSL001006000000',
				    headers: headers
				};
				function callback(error, response, body) {
				    if (!error && response.statusCode == 200) {
				        //console.log(body);
				        var resp = JSON.parse(body);
				        results = resp["searchResults"];
				        console.log(results[0]);
				        console.log(results.products[0].productName);

				        sendProductMessage(sender, results);
				    }
				}

				request(options, callback);

			}
			sendTextMessage(sender, "echo: " + text.substring(0, 200));
		}
		if (event.postback) {
			let text = JSON.stringify(event.postback);
			sendTextMessage(sender, "Postback received: "+text.substring(0, 200), token);
			continue;
		}
	}
	res.sendStatus(200);
});

// recommended to inject access tokens as environmental variables, e.g.
const token = process.env.PAGE_ACCESS_TOKEN;
//const token = "<PAGE_ACCESS_TOKEN>"

function sendTextMessage(sender, text) {
	let messageData = { text:text };

	request({
		url: 'https://graph.facebook.com/v2.6/me/messages',
		qs: {access_token:token},
		method: 'POST',
		json: {
			recipient: {id:sender},
			message: messageData,
		}
	}, function(error, response, body) {
		if (error) {
			console.log('Error sending messages: ', error);
		} else if (response.body.error) {
			console.log('Error: ', response.body.error);
		}
	});
}

function sendGenericMessage(sender) {
	let messageData = {
		"attachment": {
			"type": "template",
			"payload": {
				"template_type": "generic",
				"elements": [{
					"title": "First card",
					"subtitle": "Element #1 of an hscroll",
					"image_url": "http://messengerdemo.parseapp.com/img/rift.png",
					"buttons": [{
						"type": "web_url",
						"url": "https://www.messenger.com",
						"title": "web url"
					}, {
						"type": "postback",
						"title": "Postback",
						"payload": "Payload for first element in a generic bubble",
					}],
				}, {
					"title": "Second card",
					"subtitle": "Element #2 of an hscroll",
					"image_url": "http://messengerdemo.parseapp.com/img/gearvr.png",
					"buttons": [{
						"type": "postback",
						"title": "Postback",
						"payload": "Payload for second element in a generic bubble",
					}],
				}]
			}
		}
	};

	request({
		url: 'https://graph.facebook.com/v2.6/me/messages',
		qs: {access_token:token},
		method: 'POST',
		json: {
			recipient: {id:sender},
			message: messageData,
		}
	}, function(error, response, body) {
		if (error) {
			console.log('Error sending messages: ', error);
		} else if (response.body.error) {
			console.log('Error: ', response.body.error);
		}
	});
}

function sendProductMessage(sender, results) {
	let messageData = {
		"attachment": {
			"type": "template",
			"payload": {
				"template_type": "generic",
				/*"elements": [{
					"title": results.products[0].productName,
					"subtitle": results.products[0].description,
					"image_url": results.products[0].primaryImage,
					"buttons": [{
						"type": "web_url",
						"url": "https://www.messenger.com",
						"title": "web url"
					}, {
						"type": "postback",
						"title": "Postback",
						"payload": "Payload for first element in a generic bubble",
					}],
				}, {
					"title": "Second card",
					"subtitle": "Element #2 of an hscroll",
					"image_url": "http://messengerdemo.parseapp.com/img/gearvr.png",
					"buttons": [{
						"type": "postback",
						"title": "Postback",
						"payload": "Payload for second element in a generic bubble",
					}],
				}] */
				"elements": loadElements(results),
			}
		}
	};

	request({
		url: 'https://graph.facebook.com/v2.6/me/messages',
		qs: {access_token:token},
		method: 'POST',
		json: {
			recipient: {id:sender},
			message: messageData,
		}
	}, function(error, response, body) {
		if (error) {
			console.log('Error sending messages: ', error);
		} else if (response.body.error) {
			console.log('Error: ', response.body.error);
		}
	});
}

function loadElements(products){
	var elements;

	for (let i = 0; i < products.length; i++){
		var element = {
			"title": results.products[i].productName,
			"subtitle": results.products[i].description,
			"image_url": results.products[i].primaryImage,
		}

		elements.push(element);
	}

	return elements;
}

// spin spin sugar
app.listen(app.get('port'), function() {
	console.log('running on port', app.get('port'));
});
<commit_msg>heroku<commit_after>/* jshint esversion:6, node: true */

'use strict';

const express = require('express');
const bodyParser = require('body-parser');
const request = require('request');
const app = express();

app.set('port', (process.env.PORT || 5000));

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({extended: false}));

// parse application/json
app.use(bodyParser.json());

// index
app.get('/', function (req, res) {
	res.send('hello world i am a secret bot');
});

// for facebook verification
app.get('/webhook/', function (req, res) {
	if (req.query['hub.verify_token'] === 'my_voice_is_my_password_verify_me') {
		res.send(req.query['hub.challenge']);
	} else {
		res.send('Error, wrong token');
	}
});

// to post data
app.post('/webhook/', function (req, res) {
	var results;

	let messaging_events = req.body.entry[0].messaging;
	for (let i = 0; i < messaging_events.length; i++) {
		let event = req.body.entry[0].messaging[i];
		let sender = event.sender.id;

		if (event.message && event.message.text) {
			let text = event.message.text;
			if (text === 'Generic') {
				sendGenericMessage(sender);
				continue;
			}

			else if (text == 'cookies'){
				var headers = {
				    'Authorization': 'bearer fd887ce5-7b15-4c1e-93a0-dc91ce883ec6'
				};

				var options = {
				    url: 'https://www.loblaws.ca/ecommerce/v2/loblaw/products/search?q=apple&page=0&pageSize=10&sort=recommended&filters=category:LSL001006000000',
				    headers: headers
				};
				function callback(error, response, body) {
				    if (!error && response.statusCode == 200) {
				        //console.log(body);
				        var resp = JSON.parse(body);
				        results = resp["searchResults"];
				        console.log(results[0]);
				        console.log(results.products[0].productName);

				        sendProductMessage(sender, results);
				    }
				}

				request(options, callback);

			}
			sendTextMessage(sender, "echo: " + text.substring(0, 200));
		}
		if (event.postback) {
			let text = JSON.stringify(event.postback);
			sendTextMessage(sender, "Postback received: "+text.substring(0, 200), token);
			continue;
		}
	}
	res.sendStatus(200);
});

// recommended to inject access tokens as environmental variables, e.g.
const token = process.env.PAGE_ACCESS_TOKEN;
//const token = "<PAGE_ACCESS_TOKEN>"

function sendTextMessage(sender, text) {
	let messageData = { text:text };

	request({
		url: 'https://graph.facebook.com/v2.6/me/messages',
		qs: {access_token:token},
		method: 'POST',
		json: {
			recipient: {id:sender},
			message: messageData,
		}
	}, function(error, response, body) {
		if (error) {
			console.log('Error sending messages: ', error);
		} else if (response.body.error) {
			console.log('Error: ', response.body.error);
		}
	});
}

function sendGenericMessage(sender) {
	let messageData = {
		"attachment": {
			"type": "template",
			"payload": {
				"template_type": "generic",
				"elements": [{
					"title": "First card",
					"subtitle": "Element #1 of an hscroll",
					"image_url": "http://messengerdemo.parseapp.com/img/rift.png",
					"buttons": [{
						"type": "web_url",
						"url": "https://www.messenger.com",
						"title": "web url"
					}, {
						"type": "postback",
						"title": "Postback",
						"payload": "Payload for first element in a generic bubble",
					}],
				}, {
					"title": "Second card",
					"subtitle": "Element #2 of an hscroll",
					"image_url": "http://messengerdemo.parseapp.com/img/gearvr.png",
					"buttons": [{
						"type": "postback",
						"title": "Postback",
						"payload": "Payload for second element in a generic bubble",
					}],
				}]
			}
		}
	};

	request({
		url: 'https://graph.facebook.com/v2.6/me/messages',
		qs: {access_token:token},
		method: 'POST',
		json: {
			recipient: {id:sender},
			message: messageData,
		}
	}, function(error, response, body) {
		if (error) {
			console.log('Error sending messages: ', error);
		} else if (response.body.error) {
			console.log('Error: ', response.body.error);
		}
	});
}

function sendProductMessage(sender, results) {
	let messageData = {
		"attachment": {
			"type": "template",
			"payload": {
				"template_type": "generic",
				"elements": loadElements(results)
				/*"elements": [{
					"title": results.products[0].productName,
					"subtitle": results.products[0].description,
					"image_url": results.products[0].primaryImage,
					"buttons": [{
						"type": "web_url",
						"url": "https://www.messenger.com",
						"title": "web url"
					}, {
						"type": "postback",
						"title": "Postback",
						"payload": "Payload for first element in a generic bubble",
					}],
				}, {
					"title": "Second card",
					"subtitle": "Element #2 of an hscroll",
					"image_url": "http://messengerdemo.parseapp.com/img/gearvr.png",
					"buttons": [{
						"type": "postback",
						"title": "Postback",
						"payload": "Payload for second element in a generic bubble",
					}],
				}] */
			}
		}
	};

	request({
		url: 'https://graph.facebook.com/v2.6/me/messages',
		qs: {access_token:token},
		method: 'POST',
		json: {
			recipient: {id:sender},
			message: messageData,
		}
	}, function(error, response, body) {
		if (error) {
			console.log('Error sending messages: ', error);
		} else if (response.body.error) {
			console.log('Error: ', response.body.error);
		}
	});
}

function loadElements(products){
	var elements = [];

	for (let i = 0; i < products.length; i++){
		var element = {
			"title": results.products[i].productName,
			"subtitle": results.products[i].description,
			"image_url": results.products[i].primaryImage,
		}

		elements.push(element);
	}

	return elements;
}

// spin spin sugar
app.listen(app.get('port'), function() {
	console.log('running on port', app.get('port'));
});
<|endoftext|>


<commit_before>/*!
 * Lansa
 *
 * Eric Mann <eric@eamann.com>
 *
 * MIT License.
 */

'use strict';

/**
 * Module dependencies
 */
var os = require( 'os' ),
	Package = require( '../package.json' ),
	Program = require( 'commander' ),
	chalk = require( 'chalk' ),
	Parser = require( './parser' );

// Queue up our CLI options
Program
	.version( Package.version )
	.usage( '<project>:<environment> [options]' )
	.option( '-d, --desc <desc>', 'Description of deployment' )
	.option( '-c, --changelog <changelog>', 'Description of changes included' )
	.option( '-r, --rev <revision>', 'Deployed revision' )
	.option( '-u, --user <user>', 'Deploying user' )
	.option( '--dispatcher <dispatcher>', 'Dispatcher to use for notifications' )
	.option( '--logfile <log file>', 'Destination log (for log dispatcher only)' )
	.parse( process.argv );

// If nothing, print help and exit
if ( process.argv.length <= 2 ) {
	Program.help();
	process.exit( 0 );
}

// Parse the passed arguments for validity
var parsed = new Parser( Program );

// Add a newline for readability
if ( parsed.error ) {
	process.stderr.write( os.EOL );
}

// Handle any error codes
if ( parsed.error & 1 && 'log' !== Program.dispatcher ) {
	process.stderr.write( chalk.red( 'Either the application name or ID must be specified!' ) + os.EOL );
}
if ( parsed.error & 2 ) {
	process.stderr.write( chalk.red( 'A deployment description is required!' ) + os.EOL );
}
if ( parsed.error & 4 ) {
	process.stderr.write( chalk.red( 'A revision ID or hash is required!' ) + os.EOL );
}
if ( parsed.error & 8 ) {
	process.stderr.write( chalk.red( 'A user is required!' ) + os.EOL );
}
if ( parsed.error & 16 ) {
	process.stderr.write( chalk.red( 'You must configure a `' + chalk.yellow( '.lansarc' ) + '` file in the project root.' ) + os.EOL );
}
if ( parsed.error & 32 ) {
	process.stderr.write( chalk.red( 'Please specify an environment as configured in the `' + chalk.yellow( '.lansarc' ) + '` file.' ) + os.EOL );
}

// If we had an error code at all, die
if ( parsed.error ) {
	process.stderr.write( os.EOL );
	process.exit( 1 );
}

// No error, so get our dispatcher
var Dispatcher;
Program.dispatcher = Program.dispatcher || 'newrelic';
switch ( Program.dispatcher.toLowerCase() ) {
	case 'log':
		Dispatcher = require( './dispatcher.log.js' );
		break;
	case 'newrelic':
	default:
		Dispatcher = require( './dispatcher.newrelic.js' );
}

var dispatcher = new Dispatcher();

// Log our notification
dispatcher.notify( parsed ).then( function( message ) {
	process.stdout.write( os.EOL + chalk.green( message ) + os.EOL );
} );<commit_msg>Ensure we don't prematurely exit when logging to text files.<commit_after>/*!
 * Lansa
 *
 * Eric Mann <eric@eamann.com>
 *
 * MIT License.
 */

'use strict';

/**
 * Module dependencies
 */
var os = require( 'os' ),
	Package = require( '../package.json' ),
	Program = require( 'commander' ),
	chalk = require( 'chalk' ),
	Parser = require( './parser' );

// Queue up our CLI options
Program
	.version( Package.version )
	.usage( '<project>:<environment> [options]' )
	.option( '-d, --desc <desc>', 'Description of deployment' )
	.option( '-c, --changelog <changelog>', 'Description of changes included' )
	.option( '-r, --rev <revision>', 'Deployed revision' )
	.option( '-u, --user <user>', 'Deploying user' )
	.option( '--dispatcher <dispatcher>', 'Dispatcher to use for notifications' )
	.option( '--logfile <log file>', 'Destination log (for log dispatcher only)' )
	.parse( process.argv );

// If nothing, print help and exit
if ( process.argv.length <= 2 ) {
	Program.help();
	process.exit( 0 );
}

// Parse the passed arguments for validity
var parsed = new Parser( Program ),
	exit_error = false;

// Add a newline for readability
if ( parsed.error ) {
	process.stderr.write( os.EOL );
}

// Handle any error codes
if ( parsed.error & 1 && 'log' !== Program.dispatcher ) {
	exit_error = true;
	process.stderr.write( chalk.red( 'Either the application name or ID must be specified!' ) + os.EOL );
}
if ( parsed.error & 2 ) {
	exit_error = true;
	process.stderr.write( chalk.red( 'A deployment description is required!' ) + os.EOL );
}
if ( parsed.error & 4 ) {
	exit_error = true;
	process.stderr.write( chalk.red( 'A revision ID or hash is required!' ) + os.EOL );
}
if ( parsed.error & 8 ) {
	exit_error = true;
	process.stderr.write( chalk.red( 'A user is required!' ) + os.EOL );
}
if ( parsed.error & 16 ) {
	exit_error = true;
	process.stderr.write( chalk.red( 'You must configure a `' + chalk.yellow( '.lansarc' ) + '` file in the project root.' ) + os.EOL );
}
if ( parsed.error & 32 ) {
	exit_error = true;
	process.stderr.write( chalk.red( 'Please specify an environment as configured in the `' + chalk.yellow( '.lansarc' ) + '` file.' ) + os.EOL );
}

// If we had an error code at all, die
if ( exit_error ) {
	process.stderr.write( os.EOL );
	process.exit( 1 );
}

// No error, so get our dispatcher
var Dispatcher;
Program.dispatcher = Program.dispatcher || 'newrelic';
switch ( Program.dispatcher.toLowerCase() ) {
	case 'log':
		Dispatcher = require( './dispatcher.log.js' );
		break;
	case 'newrelic':
	default:
		Dispatcher = require( './dispatcher.newrelic.js' );
}

var dispatcher = new Dispatcher();

// Log our notification
dispatcher.notify( parsed ).then( function( message ) {
	process.stdout.write( os.EOL + chalk.green( message ) + os.EOL );
} );<|endoftext|>


<commit_before>/**
 * This module handles the loading of the jamrc files used to configure the
 * behaviour of the command-line tool.
 *
 * @module
 */

var utils = require('./utils'),
    async = require('async'),
    _ = require('underscore')._,
    path = require('path'),
    env = require('./env');

/**
 * Default paths to lookup when constructing values for jamrc.
 * Paths are checked in order, with later paths overriding the values obtained
 * from earlier ones.
 */

exports.PATHS = [
    //'/etc/jamrc',
    //'/usr/local/etc/jamrc',
    env.home + '/.jamrc'
];

/**
 * The defaults jamrc settings
 */

exports.DEFAULTS = {
    repositories: [ "http://packages.jamjs.org" ]
};

/**
 * Loads jamrc settings from PATHS, and merges them along with the DEFAULT
 * values, returning the result.
 *
 * @param {Function} callback
 */

exports.load = function (callback) {
    async.map(exports.PATHS, exports.loadFile, function (err, results) {
        if (err) {
            return callback(err);
        }
        var defaults = _.clone(exports.DEFAULTS);
        var settings = results.reduce(function (merged, r) {
            return exports.merge(merged, r);
        }, defaults);
        callback(null, settings);
    });
};

/**
 * Deep merge for JSON objects, overwrites conflicting properties
 *
 * @param {Object} a
 * @param {Object} b
 * @returns {Object}
 */

exports.merge = function (a, b) {
    if (!b) {
        return a;
    }
    for (var k in b) {
        if (Array.isArray(b[k])) {
            a[k] = b[k];
        }
        else if (typeof b[k] === 'object') {
            if (typeof a[k] === 'object') {
                exports.merge(a[k], b[k]);
            }
            else if (b.hasOwnProperty(k)) {
                a[k] = b[k];
            }
        }
        else if (b.hasOwnProperty(k)) {
            a[k] = b[k]
        }
    }
    return a;
};

/**
 * Checks a jamrc file exists and loads it if available. If the file does not
 * exist the function will respond with an empty object.
 *
 * @param {String} p - the path of the jamrc file to load
 * @param {Function} callback
 */

exports.loadFile = function (p, callback) {
    path.exists(p, function (exists) {
        if (exists) {
            try {
                var mod = require(path.resolve(p));
            }
            catch (e) {
                return callback(e);
            }
            callback(null, mod);
        }
        else {
            callback(null, {});
        }
    });
};

/**
 * Extend currently loaded settings with another .jamrc file. Used by commands
 * specific to a project directory that would like to load project-specific
 * settings.
 */

exports.extend = function (settings, path, callback) {
    exports.loadFile(path, function (err, s) {
        if (err) {
            return callback(err);
        }
        exports.merge(settings, s);
        callback(null, settings);
    });
};
<commit_msg>update repository url<commit_after>/**
 * This module handles the loading of the jamrc files used to configure the
 * behaviour of the command-line tool.
 *
 * @module
 */

var utils = require('./utils'),
    async = require('async'),
    _ = require('underscore')._,
    path = require('path'),
    env = require('./env');

/**
 * Default paths to lookup when constructing values for jamrc.
 * Paths are checked in order, with later paths overriding the values obtained
 * from earlier ones.
 */

exports.PATHS = [
    //'/etc/jamrc',
    //'/usr/local/etc/jamrc',
    env.home + '/.jamrc'
];

/**
 * The defaults jamrc settings
 */

exports.DEFAULTS = {
    repositories: [ "http://groundcomputing.co.uk/code/jam/repository" ]
};

/**
 * Loads jamrc settings from PATHS, and merges them along with the DEFAULT
 * values, returning the result.
 *
 * @param {Function} callback
 */

exports.load = function (callback) {
    async.map(exports.PATHS, exports.loadFile, function (err, results) {
        if (err) {
            return callback(err);
        }
        var defaults = _.clone(exports.DEFAULTS);
        var settings = results.reduce(function (merged, r) {
            return exports.merge(merged, r);
        }, defaults);
        callback(null, settings);
    });
};

/**
 * Deep merge for JSON objects, overwrites conflicting properties
 *
 * @param {Object} a
 * @param {Object} b
 * @returns {Object}
 */

exports.merge = function (a, b) {
    if (!b) {
        return a;
    }
    for (var k in b) {
        if (Array.isArray(b[k])) {
            a[k] = b[k];
        }
        else if (typeof b[k] === 'object') {
            if (typeof a[k] === 'object') {
                exports.merge(a[k], b[k]);
            }
            else if (b.hasOwnProperty(k)) {
                a[k] = b[k];
            }
        }
        else if (b.hasOwnProperty(k)) {
            a[k] = b[k]
        }
    }
    return a;
};

/**
 * Checks a jamrc file exists and loads it if available. If the file does not
 * exist the function will respond with an empty object.
 *
 * @param {String} p - the path of the jamrc file to load
 * @param {Function} callback
 */

exports.loadFile = function (p, callback) {
    path.exists(p, function (exists) {
        if (exists) {
            try {
                var mod = require(path.resolve(p));
            }
            catch (e) {
                return callback(e);
            }
            callback(null, mod);
        }
        else {
            callback(null, {});
        }
    });
};

/**
 * Extend currently loaded settings with another .jamrc file. Used by commands
 * specific to a project directory that would like to load project-specific
 * settings.
 */

exports.extend = function (settings, path, callback) {
    exports.loadFile(path, function (err, s) {
        if (err) {
            return callback(err);
        }
        exports.merge(settings, s);
        callback(null, settings);
    });
};
<|endoftext|>


<commit_before>/*
 * jitsu.js: Top-level include for the jitsu module.
 *
 * (C) 2010, Nodejitsu Inc.
 *
 */

var path = require('path'),
    colors = require('colors'),
    flatiron = require('flatiron');

var jitsu = module.exports = flatiron.app;

//
// Setup `jitsu` to use `pkginfo` to expose version
//
require('pkginfo')(module, 'name', 'version');

//
// Configure jitsu to use `flatiron.plugins.cli`
//
jitsu.use(flatiron.plugins.cli, {
  usage: require('./jitsu/usage'),
  source: path.join(__dirname, 'jitsu', 'commands'),
  argv: {
    version: {
      alias: 'v',
      description: 'print jitsu version and exit',
      string: true
    },
    localconf: {
      description: 'search for .jitsuconf file in ./ and then parent directories',
      string: true
    },
    jitsuconf: {
      alias: 'j',
      description: 'specify file to load configuration from',
      string: true
    },
    noanalyze: {
      description: 'skip require-analyzer: do not attempt to dynamicially detect dependencies',
      boolean: true
    },
    colors: {
      description: '--no-colors will disable output coloring',
      boolean: true
    }
  }
});

//
// Setup config, command aliases and prompt settings
//
require('./jitsu/config');
require('./jitsu/alias');
jitsu.prompt.properties = require('./jitsu/properties');
jitsu.prompt.override   = jitsu.argv;

//
// Setup other jitsu settings.
//
jitsu.skipAuth = false;
jitsu.started  = false;
jitsu.common   = require('./jitsu/common');
jitsu.package  = require('./jitsu/package');
jitsu.logFile  = new (require('./jitsu/common/logfile').LogFile)(path.join(process.env.HOME, '.jitsulog'));

//
// Hoist `jitsu.api` from `nodejitsu-api` module.
//
jitsu.api               = {};
jitsu.api.Client        = require('nodejitsu-api').Client;
jitsu.api.Apps          = require('nodejitsu-api').Apps;
jitsu.api.Databases     = require('nodejitsu-api').Databases;
jitsu.api.Logs          = require('nodejitsu-api').Logs;
jitsu.api.Snapshots     = require('nodejitsu-api').Snapshots;
jitsu.api.Users         = require('nodejitsu-api').Users;

//
// ### function welcome ()
// Print welcome message.
//
jitsu.welcome = function () {
  jitsu.log.info('Welcome to ' + 'Nodejitsu'.grey);
  jitsu.log.info('It worked if it ends with ' + 'Nodejitsu'.grey + ' ok'.green.bold);
};

//
// ### function start (command, callback)
// #### @command {string} Command to execute once started
// #### @callback {function} Continuation to pass control to when complete.
// Starts the jitsu CLI and runs the specified command.
//
jitsu.start = function (callback) {
  //
  // Check for --no-colors/--colors option, without hitting the config file
  // yet
  //
  (typeof jitsu.argv.colors == 'undefined' || jitsu.argv.colors) || (colors.mode = "none");

  jitsu.common.checkVersion(function (err) {
    if (err) {
      return callback();
    }

    jitsu.init(function (err) {
      if (err) {
        jitsu.welcome();
        callback(err);
        return jitsu.showError.apply(null, [command[0]].concat(arguments));
      }

      //
      // --no-colors option turns off output coloring, and so does setting
      // colors: false in ~/.jitsuconf (see
      // https://github.com/nodejitsu/jitsu/issues/101 )
      //
      jitsu.config.get('colors') || (colors.mode = "none");
      jitsu.welcome();

      var username = jitsu.config.get('username');
      if (!username && jitsu.config.get('requiresAuth').indexOf(jitsu.argv._[0]) !== -1) {
        return jitsu.setupUser(function (err) {
          if (err) {
            callback(err);
            return jitsu.showError.apply(jitsu, [command[0]].concat(arguments));
          }

          var username = jitsu.config.get('username');
          jitsu.log.info('Successfully configured user ' + username.magenta);
          return jitsu.exec(jitsu.argv._, callback);
        });
      }

      return jitsu.exec(jitsu.argv._, callback);
    });
  });
};

//
// ### function exec (command, callback)
// #### @command {string} Command to execute
// #### @callback {function} Continuation to pass control to when complete.
// Runs the specified command in the jitsu CLI.
//
jitsu.exec = function (command, callback) {
  function execCommand (err) {
    if (err) {
      return callback(err);
    }

    //
    // Remark: This is a temporary fix for aliasing init=>install,
    // was having a few issues with the alias command on the install resource
    //
    if (command[0] === 'init') {
      command[0] = 'install';
    }

    // Alias db to databases
    if (command[0] === 'db') {
      command[0] = 'databases';
    }

    // Allow `jitsu logs` as a shortcut for `jitsu logs app`
    if (command[0] === 'logs' && command.length === 1) {
      command[1] = 'app';
    }

    jitsu.log.info('Executing command ' + command.join(' ').magenta);
    jitsu.router.dispatch('on', command.join(' '), jitsu.log, function (err, shallow) {
      if (err) {
        callback(err);
        return jitsu.showError(command.join(' '), err, shallow);
      }

      //
      // TODO (indexzero): Something here
      //
      callback();
    });
  }

  return !jitsu.started ? jitsu.setup(execCommand) : execCommand();
};

//
// ### function setup (callback)
// #### @callback {function} Continuation to pass control to when complete.
// Sets up the instances of the Resource clients for jitsu.
// there is no io here, yet this function is ASYNC.
//
jitsu.setup = function (callback) {
  if (jitsu.started === true) {
    return callback();
  }

  jitsu.users = new jitsu.api.Users(jitsu.config);
  jitsu.apps = new jitsu.api.Apps(jitsu.config);
  jitsu.snapshots = new jitsu.api.Snapshots(jitsu.config);
  jitsu.databases = new jitsu.api.Databases(jitsu.config);
  jitsu.logs = new jitsu.api.Logs(jitsu.config);
  jitsu.started = true;

  callback();
};

//
// ### function auth (callback)
// #### @callback {function} Continuation to pass control to when complete.
// Attempts to authenicate the user identified in `jitsu.config.get('username'|'password')`
//
jitsu.auth = function (callback) {
  if (jitsu.skipAuth) {
    return callback();
  }

  var username = jitsu.config.get('username');
  jitsu.log.silly('Attempting to authenticate as ' + username.magenta);
  jitsu.users.auth(function (err, success) {
    if (err || !success) {
      jitsu.log.error('Unable to Authenticate as ' + username.magenta);
      jitsu.log.error(err.message);
      return callback(err);
    }

    jitsu.skipAuth = true;
    jitsu.log.info('Authenticated as ' + username.magenta);
    return callback();
  })
}

//
// ### function setupUser (callback)
// #### @callback {function} Continuation to pass control to when complete.
// Prompts the user for their username / password combo, then sets up the jitsu CLI,
// and saves the resulting configuration to disk.
//
jitsu.setupUser = function (callback) {
  jitsu.log.warn('You will need to login to continue');
  jitsu.log.info('To login, you will need an activated nodejitsu account');
  jitsu.log.help('You can create an account using the ' + 'jitsu signup'.magenta + ' command');
  jitsu.setupUserNoWarn(callback);
};

//
// ### function setupUserNoWarn (callback)
// #### @callback {function} Continuation to pass control to when complete.
// Prompts the user for their username / password combo, then sets up the jitsu CLI,
// and saves the resulting configuration to disk without a warning
//
jitsu.setupUserNoWarn = function (callback) {
  //
  // Attempt to get the password three times.
  //
  var tries = 0;

  function offerReset (username) {
    jitsu.prompt.get(['reset'], function (err, res) {
      if (err) {
        return callback(err);
      }
      if (/^y[es]+/i.test(res['request password reset'])) {
        return jitsu.commands.run(['users', 'forgot', username], callback);
      }

      callback(new Error('Invalid username / password.'));
    });
  }

  (function setupAuth () {
    jitsu.prompt.get(['username', 'password'], function (err, result) {
      if (err) {
        return callback(err);
      }

      jitsu.config.set('username', result.username);
      jitsu.config.set('password', result.password);
      jitsu.setup(function () {
        jitsu.auth(function (err) {
          //
          // Increment the auth attempts
          //
          tries += 1;

          if (err) {
            if (tries >= 3) {
              jitsu.log.error('Three failed login attempts');
              jitsu.log.info('Would you like to reset your password?');
              return offerReset(result.username);
            }
            return setupAuth();
          }

          jitsu.config.save(function (err) {
            return err ? callback(err) : callback();
          });
        });
      });
    });
  })();
};

//
// ### function showError (command, err, shallow, skip)
// #### @command {string} Command which has errored.
// #### @err {Error} Error received for the command.
// #### @shallow {boolean} Value indicating if a deep stack should be displayed
// #### @skip {boolean} Value indicating if this error should be forcibly suppressed.
// Displays the `err` to the user for the `command` supplied.
//
jitsu.showError = function (command, err, shallow, skip) {
  var username,
      stack;

  if (err.statusCode === '403') {
    username = jitsu.config.get('username');
    if (username) {
      jitsu.log.error('Unable to authenticate as: ' + username.magenta);
    }

    jitsu.log.error('403 ' + err.result.error);
  }
  else if (!skip) {
    jitsu.log.error('Error running command ' + command.magenta);

    if (!jitsu.config.get('nolog')) {
      jitsu.logFile.log(err);
    }

    if (err.message) {
      jitsu.log.error(err.message);
    }

    if (err.result) {
      if (err.result.error) {
        jitsu.log.error(err.result.error);
      }

      if (err.result.result && err.result.result.error) {
        if (err.result.result.error.stderr || err.result.result.error.stdout) {
          jitsu.log.error('');
          jitsu.log.error('There was an error while attempting to start your application.');
          jitsu.log.error(err.result.result.error.message);
          if (err.result.result.error.blame) {
            jitsu.log.error(err.result.result.error.blame.message);
            jitsu.log.error('');
            jitsu.log.error('This type of error is usually a ' + err.result.result.error.blame.type + ' error.');
          }

          jitsu.log.error('Error output from your application:');
          jitsu.log.error('');
          if (err.result.result.error.stdout) {
            err.result.result.error.stdout.split('\n').forEach(function (line) {
              jitsu.log.error(line);
            });
          }

          if (err.result.result.error.stderr) {
            err.result.result.error.stderr.split('\n').forEach(function (line) {
              jitsu.log.error(line);
            });
          }
        }
        else if (err.result.result.error.stack && jitsu.config.get('debug')) {
          jitsu.log.error('There was an error while attempting to deploy your application.');
          jitsu.log.error('');
          jitsu.log.error(err.result.result.error.message);

          if (err.result.result.error.blame) {
            jitsu.log.error(err.result.result.error.blame.message);
            jitsu.log.error('');
            jitsu.log.error('This type of error is usually a ' + err.result.result.error.blame.type + ' error.');
          }

          jitsu.log.error('Error output from Haibu:');
          jitsu.log.error('');
          stack = err.result.result.error.result || err.result.result.error.stack;
          stack.split('\n').forEach(function (line) {
            jitsu.log.error(line);
          });
        }
      }
      else if (err.result.stack) {
        jitsu.log.warn('Error returned from Nodejitsu');
        err.result.stack.split('\n').forEach(function (line) {
          jitsu.log.error(line);
        });
      }
    }
    else {
      if (err.stack && !shallow) {
        err.stack.split('\n').forEach(function (trace) {
          jitsu.log.error(trace);
        });
      }
    }
  }

  jitsu.log.info('Nodejitsu '.grey + 'not ok'.red.bold);
};
<commit_msg>[api] Default `jitsu.argv.colors` to `true`<commit_after>/*
 * jitsu.js: Top-level include for the jitsu module.
 *
 * (C) 2010, Nodejitsu Inc.
 *
 */

var path = require('path'),
    colors = require('colors'),
    flatiron = require('flatiron');

var jitsu = module.exports = flatiron.app;

//
// Setup `jitsu` to use `pkginfo` to expose version
//
require('pkginfo')(module, 'name', 'version');

//
// Configure jitsu to use `flatiron.plugins.cli`
//
jitsu.use(flatiron.plugins.cli, {
  usage: require('./jitsu/usage'),
  source: path.join(__dirname, 'jitsu', 'commands'),
  argv: {
    version: {
      alias: 'v',
      description: 'print jitsu version and exit',
      string: true
    },
    localconf: {
      description: 'search for .jitsuconf file in ./ and then parent directories',
      string: true
    },
    jitsuconf: {
      alias: 'j',
      description: 'specify file to load configuration from',
      string: true
    },
    noanalyze: {
      description: 'skip require-analyzer: do not attempt to dynamicially detect dependencies',
      boolean: true
    },
    colors: {
      description: '--no-colors will disable output coloring',
      default: true,
      boolean: true
    }
  }
});

//
// Setup config, command aliases and prompt settings
//
require('./jitsu/config');
require('./jitsu/alias');
jitsu.prompt.properties = require('./jitsu/properties');
jitsu.prompt.override   = jitsu.argv;

//
// Setup other jitsu settings.
//
jitsu.skipAuth = false;
jitsu.started  = false;
jitsu.common   = require('./jitsu/common');
jitsu.package  = require('./jitsu/package');
jitsu.logFile  = new (require('./jitsu/common/logfile').LogFile)(path.join(process.env.HOME, '.jitsulog'));

//
// Hoist `jitsu.api` from `nodejitsu-api` module.
//
jitsu.api               = {};
jitsu.api.Client        = require('nodejitsu-api').Client;
jitsu.api.Apps          = require('nodejitsu-api').Apps;
jitsu.api.Databases     = require('nodejitsu-api').Databases;
jitsu.api.Logs          = require('nodejitsu-api').Logs;
jitsu.api.Snapshots     = require('nodejitsu-api').Snapshots;
jitsu.api.Users         = require('nodejitsu-api').Users;

//
// ### function welcome ()
// Print welcome message.
//
jitsu.welcome = function () {
  jitsu.log.info('Welcome to ' + 'Nodejitsu'.grey);
  jitsu.log.info('It worked if it ends with ' + 'Nodejitsu'.grey + ' ok'.green.bold);
};

//
// ### function start (command, callback)
// #### @command {string} Command to execute once started
// #### @callback {function} Continuation to pass control to when complete.
// Starts the jitsu CLI and runs the specified command.
//
jitsu.start = function (callback) {
  //
  // Check for --no-colors/--colors option, without hitting the config file
  // yet
  //
  (typeof jitsu.argv.colors == 'undefined' || jitsu.argv.colors) || (colors.mode = "none");

  jitsu.common.checkVersion(function (err) {
    if (err) {
      return callback();
    }

    jitsu.init(function (err) {
      if (err) {
        jitsu.welcome();
        callback(err);
        return jitsu.showError.apply(null, [command[0]].concat(arguments));
      }

      //
      // --no-colors option turns off output coloring, and so does setting
      // colors: false in ~/.jitsuconf (see
      // https://github.com/nodejitsu/jitsu/issues/101 )
      //
      jitsu.config.get('colors') || (colors.mode = "none");
      jitsu.welcome();

      var username = jitsu.config.get('username');
      if (!username && jitsu.config.get('requiresAuth').indexOf(jitsu.argv._[0]) !== -1) {
        return jitsu.setupUser(function (err) {
          if (err) {
            callback(err);
            return jitsu.showError.apply(jitsu, [command[0]].concat(arguments));
          }

          var username = jitsu.config.get('username');
          jitsu.log.info('Successfully configured user ' + username.magenta);
          return jitsu.exec(jitsu.argv._, callback);
        });
      }

      return jitsu.exec(jitsu.argv._, callback);
    });
  });
};

//
// ### function exec (command, callback)
// #### @command {string} Command to execute
// #### @callback {function} Continuation to pass control to when complete.
// Runs the specified command in the jitsu CLI.
//
jitsu.exec = function (command, callback) {
  function execCommand (err) {
    if (err) {
      return callback(err);
    }

    //
    // Remark: This is a temporary fix for aliasing init=>install,
    // was having a few issues with the alias command on the install resource
    //
    if (command[0] === 'init') {
      command[0] = 'install';
    }

    // Alias db to databases
    if (command[0] === 'db') {
      command[0] = 'databases';
    }

    // Allow `jitsu logs` as a shortcut for `jitsu logs app`
    if (command[0] === 'logs' && command.length === 1) {
      command[1] = 'app';
    }

    jitsu.log.info('Executing command ' + command.join(' ').magenta);
    jitsu.router.dispatch('on', command.join(' '), jitsu.log, function (err, shallow) {
      if (err) {
        callback(err);
        return jitsu.showError(command.join(' '), err, shallow);
      }

      //
      // TODO (indexzero): Something here
      //
      callback();
    });
  }

  return !jitsu.started ? jitsu.setup(execCommand) : execCommand();
};

//
// ### function setup (callback)
// #### @callback {function} Continuation to pass control to when complete.
// Sets up the instances of the Resource clients for jitsu.
// there is no io here, yet this function is ASYNC.
//
jitsu.setup = function (callback) {
  if (jitsu.started === true) {
    return callback();
  }

  jitsu.users = new jitsu.api.Users(jitsu.config);
  jitsu.apps = new jitsu.api.Apps(jitsu.config);
  jitsu.snapshots = new jitsu.api.Snapshots(jitsu.config);
  jitsu.databases = new jitsu.api.Databases(jitsu.config);
  jitsu.logs = new jitsu.api.Logs(jitsu.config);
  jitsu.started = true;

  callback();
};

//
// ### function auth (callback)
// #### @callback {function} Continuation to pass control to when complete.
// Attempts to authenicate the user identified in `jitsu.config.get('username'|'password')`
//
jitsu.auth = function (callback) {
  if (jitsu.skipAuth) {
    return callback();
  }

  var username = jitsu.config.get('username');
  jitsu.log.silly('Attempting to authenticate as ' + username.magenta);
  jitsu.users.auth(function (err, success) {
    if (err || !success) {
      jitsu.log.error('Unable to Authenticate as ' + username.magenta);
      jitsu.log.error(err.message);
      return callback(err);
    }

    jitsu.skipAuth = true;
    jitsu.log.info('Authenticated as ' + username.magenta);
    return callback();
  })
}

//
// ### function setupUser (callback)
// #### @callback {function} Continuation to pass control to when complete.
// Prompts the user for their username / password combo, then sets up the jitsu CLI,
// and saves the resulting configuration to disk.
//
jitsu.setupUser = function (callback) {
  jitsu.log.warn('You will need to login to continue');
  jitsu.log.info('To login, you will need an activated nodejitsu account');
  jitsu.log.help('You can create an account using the ' + 'jitsu signup'.magenta + ' command');
  jitsu.setupUserNoWarn(callback);
};

//
// ### function setupUserNoWarn (callback)
// #### @callback {function} Continuation to pass control to when complete.
// Prompts the user for their username / password combo, then sets up the jitsu CLI,
// and saves the resulting configuration to disk without a warning
//
jitsu.setupUserNoWarn = function (callback) {
  //
  // Attempt to get the password three times.
  //
  var tries = 0;

  function offerReset (username) {
    jitsu.prompt.get(['reset'], function (err, res) {
      if (err) {
        return callback(err);
      }
      if (/^y[es]+/i.test(res['request password reset'])) {
        return jitsu.commands.run(['users', 'forgot', username], callback);
      }

      callback(new Error('Invalid username / password.'));
    });
  }

  (function setupAuth () {
    jitsu.prompt.get(['username', 'password'], function (err, result) {
      if (err) {
        return callback(err);
      }

      jitsu.config.set('username', result.username);
      jitsu.config.set('password', result.password);
      jitsu.setup(function () {
        jitsu.auth(function (err) {
          //
          // Increment the auth attempts
          //
          tries += 1;

          if (err) {
            if (tries >= 3) {
              jitsu.log.error('Three failed login attempts');
              jitsu.log.info('Would you like to reset your password?');
              return offerReset(result.username);
            }
            return setupAuth();
          }

          jitsu.config.save(function (err) {
            return err ? callback(err) : callback();
          });
        });
      });
    });
  })();
};

//
// ### function showError (command, err, shallow, skip)
// #### @command {string} Command which has errored.
// #### @err {Error} Error received for the command.
// #### @shallow {boolean} Value indicating if a deep stack should be displayed
// #### @skip {boolean} Value indicating if this error should be forcibly suppressed.
// Displays the `err` to the user for the `command` supplied.
//
jitsu.showError = function (command, err, shallow, skip) {
  var username,
      stack;

  if (err.statusCode === '403') {
    username = jitsu.config.get('username');
    if (username) {
      jitsu.log.error('Unable to authenticate as: ' + username.magenta);
    }

    jitsu.log.error('403 ' + err.result.error);
  }
  else if (!skip) {
    jitsu.log.error('Error running command ' + command.magenta);

    if (!jitsu.config.get('nolog')) {
      jitsu.logFile.log(err);
    }

    if (err.message) {
      jitsu.log.error(err.message);
    }

    if (err.result) {
      if (err.result.error) {
        jitsu.log.error(err.result.error);
      }

      if (err.result.result && err.result.result.error) {
        if (err.result.result.error.stderr || err.result.result.error.stdout) {
          jitsu.log.error('');
          jitsu.log.error('There was an error while attempting to start your application.');
          jitsu.log.error(err.result.result.error.message);
          if (err.result.result.error.blame) {
            jitsu.log.error(err.result.result.error.blame.message);
            jitsu.log.error('');
            jitsu.log.error('This type of error is usually a ' + err.result.result.error.blame.type + ' error.');
          }

          jitsu.log.error('Error output from your application:');
          jitsu.log.error('');
          if (err.result.result.error.stdout) {
            err.result.result.error.stdout.split('\n').forEach(function (line) {
              jitsu.log.error(line);
            });
          }

          if (err.result.result.error.stderr) {
            err.result.result.error.stderr.split('\n').forEach(function (line) {
              jitsu.log.error(line);
            });
          }
        }
        else if (err.result.result.error.stack && jitsu.config.get('debug')) {
          jitsu.log.error('There was an error while attempting to deploy your application.');
          jitsu.log.error('');
          jitsu.log.error(err.result.result.error.message);

          if (err.result.result.error.blame) {
            jitsu.log.error(err.result.result.error.blame.message);
            jitsu.log.error('');
            jitsu.log.error('This type of error is usually a ' + err.result.result.error.blame.type + ' error.');
          }

          jitsu.log.error('Error output from Haibu:');
          jitsu.log.error('');
          stack = err.result.result.error.result || err.result.result.error.stack;
          stack.split('\n').forEach(function (line) {
            jitsu.log.error(line);
          });
        }
      }
      else if (err.result.stack) {
        jitsu.log.warn('Error returned from Nodejitsu');
        err.result.stack.split('\n').forEach(function (line) {
          jitsu.log.error(line);
        });
      }
    }
    else {
      if (err.stack && !shallow) {
        err.stack.split('\n').forEach(function (trace) {
          jitsu.log.error(trace);
        });
      }
    }
  }

  jitsu.log.info('Nodejitsu '.grey + 'not ok'.red.bold);
};
<|endoftext|>


<commit_before>var EventEmitter = require('events').EventEmitter
  , async = require('async')
  , readFile = require('./util').readFile
  , joinData = require('./util').joinData
  , extname = require('path').extname
  ;

function JscatEvent(options) {
  this.events = {};
  if (options) {
    var self = this;
    Object.keys(options).forEach(function (key) {
      self.on(key, options[key]);
    });
  }
  return this;
}

JscatEvent.prototype.on = function (key, callback) {
  if (!this.events[key]) this.events[key] = [];
  this.events[key].push(callback);
  return this;
};

JscatEvent.prototype.namespace = function (val) {
  this._namespace = ':' + val;
  return this;
};

JscatEvent.prototype.outPath = function (val) {
  this._outPath = val;
  return this;
};

// @param {String} key - read|each|join
// @param {String} path
// @return {Array}
JscatEvent.prototype.getEvents = function (key, path) {
  var ext = extname(path)
    , ns = this._namespace;

  return [].concat( // 1. key.extension:namespace
            ((ns && this.events[key + ext + ns]) || [])
          ).concat( // 2. key.extension
            (this.events[key + ext] || [])
          ).concat( // 3. key:namespace
            ((ns && this.events[key + ns]) || [])
          ).concat(  // 4. key
            (this.events[key] || [])
          );
};

JscatEvent.prototype.fireRead = function (filePath, next) {
  var events = this.getEvents('read', filePath)
    , length = events.length;

  // first events
  if (!length) {
    readFile(filePath, next);
    return this;
  }

  async.reduce(events, filePath, function (buffer, fn, callback) {
    fn.call(null, filePath, function (err, content) {
      if (err) return callback(err);
      // if content has been returned, throw error and interapt reduce
      if (content) return callback('hit', content);
      // if no content, call next event callback
      callback(null, filePath);
    });
  }, function (err, result) {
    if (err && err !== 'hit') return next(err);
    if (result) return next(null, result);
    // if result is null, fallback by default read
    readFile(filePath, next);
  });
  return this;
};

// data = {path: '', content: ''};
// @param data {Object}
// @param next {Function}
JscatEvent.prototype.fireEach = function (data, next) {
  var path = data.path
    , events = this.getEvents('each', path);
  if (!events.length) return next(null, data);
  // apply event by step
  async.reduce(events, data.content, function (buffer, fn, callback) {
    // make sure path is immutable through reducing
    fn.call(null, { path: path, content: buffer }, function (err, content, stop) {
      if (err) return callback(err);
      // if stop is true, pass error and stop reduce
      if (stop) return callback('stop', content);
      callback(null, content);
    });
  }, function (err, result) {
    if (err && err !== 'stop') return next(err);
    next(null, {
      path: path
    , content: result
    });
  });

  return this;
};

JscatEvent.prototype.fireJoin = function (dataArray, next) {
  var events = this.getEvents('join', (this._outPath || ''));
  if (events.length) {
    events[0].call(null, dataArray, next);
  } else {
    joinData(dataArray, next);
  }

  return this;
};

module.exports = JscatEvent;<commit_msg>fix namespace parse bug<commit_after>var EventEmitter = require('events').EventEmitter
  , async = require('async')
  , readFile = require('./util').readFile
  , joinData = require('./util').joinData
  , extname = require('path').extname
  ;

function JscatEvent(options) {
  this.events = {};
  if (options) {
    var self = this;
    Object.keys(options).forEach(function (key) {
      self.on(key, options[key]);
    });
  }
  return this;
}

JscatEvent.prototype.on = function (key, callback) {
  if (!this.events[key]) this.events[key] = [];
  this.events[key].push(callback);
  return this;
};

JscatEvent.prototype.namespace = function (val) {
  this._namespace = ':' + val;
  return this;
};

JscatEvent.prototype.outPath = function (val) {
  this._outPath = val;
  return this;
};

// @param {String} key - read|each|join
// @param {String} path
// @return {Array}
JscatEvent.prototype.getEvents = function (key, path) {
  var ext = extname(path)
    , ns = this._namespace;

  return [].concat( // 1. key.extension:namespace
            ((ns && this.events[key + ext + ns]) || [])
          ).concat( // 2. key.extension
            (this.events[key + ext] || [])
          ).concat( // 3. key:namespace
            ((ns && this.events[key + ns]) || [])
          ).concat(  // 4. key
            (this.events[key] || [])
          );
};

JscatEvent.prototype.fireRead = function (filePath, next) {
  var events = this.getEvents('read', filePath)
    , length = events.length;

  // first events
  if (!length) {
    readFile(filePath, next);
    return this;
  }

  async.reduce(events, filePath, function (buffer, fn, callback) {
    fn.call(null, filePath, function (err, content) {
      if (err) return callback(err);
      // if content has been returned, throw error and interapt reduce
      if (content) return callback('hit', content);
      // if no content, call next event callback
      callback(null, filePath);
    });
  }, function (err, result) {
    if (err && err !== 'hit') return next(err);
    // if result is null, fallback by default read
    if (!result) return readFile(filePath, next);

    next(null, {
      path: filePath
    , content: result
    });
  });
  return this;
};

// data = {path: '', content: ''};
// @param data {Object}
// @param next {Function}
JscatEvent.prototype.fireEach = function (data, next) {
  var path = data.path
    , events = this.getEvents('each', path);
  if (!events.length) return next(null, data);
  // apply event by step
  async.reduce(events, data.content, function (buffer, fn, callback) {
    // make sure path is immutable through reducing
    fn.call(null, { path: path, content: buffer }, function (err, content, stop) {
      if (err) return callback(err);
      // if stop is true, pass error and stop reduce
      if (stop) return callback('stop', content);
      callback(null, content);
    });
  }, function (err, result) {
    if (err && err !== 'stop') return next(err);
    next(null, {
      path: path
    , content: result
    });
  });

  return this;
};

JscatEvent.prototype.fireJoin = function (dataArray, next) {
  var events = this.getEvents('join', (this._outPath || ''));
  if (events.length) {
    events[0].call(null, dataArray, next);
  } else {
    joinData(dataArray, next);
  }

  return this;
};

module.exports = JscatEvent;<|endoftext|>


<commit_before>/*The MIT License (MIT)

 Copyright (c) 2015 Jens Malmborg

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in all
 copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 SOFTWARE.*/

var Utils = require('/utils.js').Utils;
var Entity = require('/entity.js').Entity;
var Color = require('/color.js').Color;

function Light(position) {
    Entity.call(this);
    if (position) {
        this.transform.position = position;
    }
    this.color = Color.white();
    this.attenuation = 0.1;
    this.ambientCoefficient = 0.1;
}

Utils.extend(Light, Entity);

function DirectionalLight(position) {
    Light.call(this, position);
}

Utils.extend(DirectionalLight, Light);

function PointLight(position) {
    Light.call(this, position);
}

Utils.extend(PointLight, Light);

function SpotLight(position) {
    Light.call(this, position);
    this.coneAngle = 15.1;
    this.coneDirection = new Vector3(0,0,-1);
    this.attenuation = 0.1;
    this.ambientCoefficient = 0.1;
}

Utils.extend(SpotLight, Light);

module.exports.PointLight = PointLight;
module.exports.DirectionalLight = DirectionalLight;
module.exports.SpotLight = SpotLight;<commit_msg>Minor change just to get Model lighting to work.<commit_after>/*The MIT License (MIT)

 Copyright (c) 2016 Jens Malmborg

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in all
 copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 SOFTWARE.*/

var Utils = require('/utils.js').Utils;
var Entity = require('/entity.js').Entity;
var Color = require('/color.js').Color;

function Light(position) {
    Entity.call(this);
    if (position) {
        this.transform.position = position;
    }
    this.color = Color.white();
    this.attenuation = 0.1;
    this.ambientCoefficient = 0.1;
}

Utils.extend(Light, Entity);

function DirectionalLight(position) {
    Light.call(this, position);
    this.position = position;
}

Utils.extend(DirectionalLight, Light);

function PointLight(position) {
    Light.call(this, position);
}

Utils.extend(PointLight, Light);

function SpotLight(position) {
    Light.call(this, position);
    this.coneAngle = 15.1;
    this.coneDirection = new Vector3(0,0,-1);
    this.attenuation = 0.1;
    this.ambientCoefficient = 0.1;
}

Utils.extend(SpotLight, Light);

module.exports.PointLight = PointLight;
module.exports.DirectionalLight = DirectionalLight;
module.exports.SpotLight = SpotLight;<|endoftext|>


<commit_before>var Log = require('./logger'),
  logger = new Log(global.logLevel),
  exec = require('child_process').exec,
  fs = require('fs'),
  http = require('http'),
  windows = ((process.platform.match(/win32/) || process.platform.match(/win64/)) !== null),
  localBinary = __dirname + (windows ? '/BrowserStackTunnel.jar' : '/BrowserStackLocal'),
  utils = require('./utils'),
  config = require('./config');

var Tunnel = function Tunnel(key, port, uniqueIdentifier, callback, err) {
  var that = {};

  function tunnelLauncher() {
    var tunnelCommand = (windows ? 'java -jar ' : '') + localBinary + ' ';
    if (config.debug) tunnelCommand += ' -v ';
    tunnelCommand += key + ' ';
    tunnelCommand += 'localhost' + ',';
    tunnelCommand += port.toString() + ',';
    tunnelCommand += '0';
    tunnelCommand += (typeof uniqueIdentifier === 'undefined') ? ' -force -onlyAutomate' : ' -tunnelIdentifier ' + uniqueIdentifier;
    tunnelCommand += checkAndAddProxy();

    if (typeof callback !== 'function') {
      callback = function(){};
    }

    logger.debug("[%s] Launching tunnel", new Date());
    var subProcess = exec(tunnelCommand, function(error, stdout, stderr) {
      logger.debug(stderr);
      logger.debug(error);
      if (stdout.indexOf('Error') >= 0 || error) {
        logger.debug("[%s] Tunnel launching failed", new Date());
        logger.debug(stdout);
        process.kill(process.pid, 'SIGINT');
      }
    });

    var data = '';
    var running = false;
    var runMatcher = "You can now access your local server(s)";

    setTimeout(function() {
      if (!running) {
        utils.alertBrowserStack("Tunnel launch timeout", 'Stdout:\n' + data);
      }
    }, 30 * 1000);

    subProcess.stdout.on('data', function(_data) {
      if (running) {
        return;
      }

      data += _data;

      if (data.indexOf(runMatcher) >= 0) {
        running = true;
        logger.debug("[%s] Tunnel launched", new Date());
        callback();
      }
    });

    that.process = subProcess;
  }

  function checkAndAddProxy() {
    var proxy = config.proxy;
    if(typeof proxy == 'undefined') {
      return "";
    }
    var proxyCommand = "";
    proxyCommand += " -proxyHost " + proxy.host;
    proxyCommand += " -proxyPort " + proxy.port;
    if(typeof proxy.username !== 'undefined'){
      proxyCommand += " -proxyUser " + proxy.username;
      proxyCommand += " -proxyPass " + proxy.password;
    }
    return proxyCommand;
  }

  fs.exists(localBinary, function(exists) {
    if (exists) {
      tunnelLauncher();
      return;
    }
    logger.debug('Downloading BrowserStack Local to `%s`', localBinary);

    var file = fs.createWriteStream(localBinary);
    var request = http.get(
    (windows ? "http://www.browserstack.com/BrowserStackTunnel.jar" : ("http://s3.amazonaws.com/browserStack/browserstack-local/BrowserStackLocal-" + process.platform + "-" + process.arch)),
    function(response) {
      response.pipe(file);

      response.on('end', function() {
        fs.chmodSync(localBinary, 0700);
        setTimeout(function() {
          tunnelLauncher();
        }, 100);
      }).on('error', function(e) {
        logger.info("Got error while downloading binary: " + e.message);
        process.kill(process.pid, 'SIGINT');
      });
    });
  });

  return that;
};

exports.Tunnel = Tunnel;
<commit_msg>for some reason, local fails intermittently. this fixes it.<commit_after>var Log = require('./logger'),
  logger = new Log(global.logLevel),
  exec = require('child_process').exec,
  fs = require('fs'),
  http = require('http'),
  windows = ((process.platform.match(/win32/) || process.platform.match(/win64/)) !== null),
  localBinary = __dirname + (windows ? '/BrowserStackTunnel.jar' : '/BrowserStackLocal'),
  utils = require('./utils'),
  config = require('./config');

var Tunnel = function Tunnel(key, port, uniqueIdentifier, callback, err) {
  var that = {};

  function tunnelLauncher() {
    var tunnelCommand = (windows ? 'java -jar ' : '') + localBinary + ' ';
    if (config.debug) tunnelCommand += ' -v ';
    tunnelCommand += key + ' ';
    tunnelCommand += 'localhost' + ',';
    tunnelCommand += port.toString() + ',';
    tunnelCommand += '0';
    tunnelCommand += (typeof uniqueIdentifier === 'undefined') ? ' -force -onlyAutomate' : ' -tunnelIdentifier ' + uniqueIdentifier;
    tunnelCommand += checkAndAddProxy();

    if (typeof callback !== 'function') {
      callback = function(){};
    }

    logger.debug("[%s] Launching tunnel", new Date());
    var subProcess = exec(tunnelCommand, function(error, stdout, stderr) {
      logger.debug(stderr);
      logger.debug(error);
      if (stdout.indexOf('Error') >= 0 || error) {
        logger.debug("[%s] Tunnel launching failed", new Date());
        logger.debug(stdout);
        process.kill(process.pid, 'SIGINT');
      }
    });

    var data = '';
    var running = false;
    var runMatcher = "You can now access your local server(s)";

    setTimeout(function() {
      if (!running) {
        utils.alertBrowserStack("Tunnel launch timeout", 'Stdout:\n' + data);
      }
    }, 30 * 1000);

    subProcess.stdout.on('data', function(_data) {
      if (running) {
        return;
      }

      data += _data;

      if (data.indexOf(runMatcher) >= 0) {
        running = true;
        logger.debug("[%s] Tunnel launched", new Date());
        setTimeout(function(){
          callback();
        }, 2000);
      }
    });

    that.process = subProcess;
  }

  function checkAndAddProxy() {
    var proxy = config.proxy;
    if(typeof proxy == 'undefined') {
      return "";
    }
    var proxyCommand = "";
    proxyCommand += " -proxyHost " + proxy.host;
    proxyCommand += " -proxyPort " + proxy.port;
    if(typeof proxy.username !== 'undefined'){
      proxyCommand += " -proxyUser " + proxy.username;
      proxyCommand += " -proxyPass " + proxy.password;
    }
    return proxyCommand;
  }

  fs.exists(localBinary, function(exists) {
    if (exists) {
      tunnelLauncher();
      return;
    }
    logger.debug('Downloading BrowserStack Local to `%s`', localBinary);

    var file = fs.createWriteStream(localBinary);
    var request = http.get(
    (windows ? "http://www.browserstack.com/BrowserStackTunnel.jar" : ("http://s3.amazonaws.com/browserStack/browserstack-local/BrowserStackLocal-" + process.platform + "-" + process.arch)),
    function(response) {
      response.pipe(file);

      response.on('end', function() {
        fs.chmodSync(localBinary, 0700);
        setTimeout(function() {
          tunnelLauncher();
        }, 100);
      }).on('error', function(e) {
        logger.info("Got error while downloading binary: " + e.message);
        process.kill(process.pid, 'SIGINT');
      });
    });
  });

  return that;
};

exports.Tunnel = Tunnel;
<|endoftext|>


<commit_before>var util = require("../lib/util.js");
var data = require("../lib/data.js");
var async = require('async');

/**
 * For our dashboard we've grouped up certain types of contribution activity in 'buckets'
 * @param  {str} str
 * @return {str or array}
 */
exports.applyBucketGroupings = function applyBucketGroupings(str) {
  if (str === 'content') {
    return ['content', 'translation'];
  }
  if (str === 'community') {
    return ['community', 'partners', '1to1relation'];
  }
  return str;
};

/**
 * Process data submitted through the standard form at /log-em
 */
exports.processForm = function processForm(body, user_email, callback) {
  var teamname = body.teamname;
  var databucket = body.databucket;
  var description = body.description;
  var date = body.date;
  var evidence = body.evidence;
  var contributors = body.contributors;
  // split on comma, semicolon, extra white spaces and new lines
  contributors = contributors.split(/\s*[,;]\s*|\s{2,}|[\r\n]+/);
  // trim all of these
  for (var i = contributors.length - 1; i >= 0; i--) {
    contributors[i] = contributors[i].trim();
  }
  contributors = util.cleanArray(contributors);

  async.each(contributors, function (contributor, callback) {
    var entry = {
      logged_by: user_email,
      contributor_id: contributor,
      contribution_date: new Date(date),
      moz_team: teamname,
      data_bucket: databucket,
      description: description,
      evidence: evidence
    };
    data.saveItem(entry, function savedItem(err, res) {
      if (err) {
        console.error(err);
      }
      callback(null);
    });
  }, function savedAllItems(err) {
    if (err) {
      console.error(err);
    }
    callback(null);
  });

};

/**
 * Process data submitted through the bulk form at /log-many
 */
exports.processMany = function processMany(body, user_email, callback) {
  var teamname = body.teamname;
  var databucket = body.databucket;
  var evidence = body.evidence;
  var contributors = body.contributors;

  // remove straight quote marks
  contributors = util.removeQuotes(contributors);

  // split each row to process them individually
  var rows = contributors.split(/[\n\r]/g);
  var validToSave = [];
  var hasErrors = [];

  for (var i = rows.length - 1; i >= 0; i--) {
    var row = rows[i].split(',');

    if (!row[0]) {
      // empty lines or array items introduced by the split
      continue;
    }

    // there should only be three values per line
    if (row.length !== 3) {
      hasErrors.push(row);
      continue;
    }

    // trim the strings
    row = util.trimArrayValues(row);

    // the first value should be an email address
    if (row[0].indexOf("@") === -1) {
      hasErrors.push(row);
      continue;
    }

    // the second value shoud be a date
    var d = util.parseAndCheckDate(row[1]);
    if (!d) {
      hasErrors.push(row);
      continue;
    }

    // Format this exactly as needed
    row[1] = util.dateToISOtring(d);

    // this is valid
    validToSave.push({
      contributor_id: row[0],
      contribution_date: row[1],
      description: row[2]
    });
  }

  async.eachSeries(validToSave, function (contribution, callback) {
    var entry = {
      logged_by: user_email,
      contributor_id: contribution.contributor_id,
      contribution_date: new Date(contribution.contribution_date),
      moz_team: teamname,
      data_bucket: databucket,
      description: contribution.description,
      evidence: evidence
    };
    data.saveItem(entry, function savedItem(err, res) {
      if (err) {
        console.log(entry);
        console.error(err);
        return;
      }
      callback(null);
    });
  }, function savedAllItems(err) {
    if (err) {
      console.error(err);
    }
    callback(null, validToSave, hasErrors);
  });

};
<commit_msg>improve saving speed to limit timeouts<commit_after>var util = require("../lib/util.js");
var data = require("../lib/data.js");
var async = require('async');

/**
 * For our dashboard we've grouped up certain types of contribution activity in 'buckets'
 * @param  {str} str
 * @return {str or array}
 */
exports.applyBucketGroupings = function applyBucketGroupings(str) {
  if (str === 'content') {
    return ['content', 'translation'];
  }
  if (str === 'community') {
    return ['community', 'partners', '1to1relation'];
  }
  return str;
};

/**
 * Process data submitted through the standard form at /log-em
 */
exports.processForm = function processForm(body, user_email, callback) {
  var teamname = body.teamname;
  var databucket = body.databucket;
  var description = body.description;
  var date = body.date;
  var evidence = body.evidence;
  var contributors = body.contributors;
  // split on comma, semicolon, extra white spaces and new lines
  contributors = contributors.split(/\s*[,;]\s*|\s{2,}|[\r\n]+/);
  // trim all of these
  for (var i = contributors.length - 1; i >= 0; i--) {
    contributors[i] = contributors[i].trim();
  }
  contributors = util.cleanArray(contributors);

  async.each(contributors, function (contributor, callback) {
    var entry = {
      logged_by: user_email,
      contributor_id: contributor,
      contribution_date: new Date(date),
      moz_team: teamname,
      data_bucket: databucket,
      description: description,
      evidence: evidence
    };
    data.saveItem(entry, function savedItem(err, res) {
      if (err) {
        console.error(err);
      }
      callback(null);
    });
  }, function savedAllItems(err) {
    if (err) {
      console.error(err);
    }
    callback(null);
  });

};

/**
 * Process data submitted through the bulk form at /log-many
 */
exports.processMany = function processMany(body, user_email, callback) {
  var teamname = body.teamname;
  var databucket = body.databucket;
  var evidence = body.evidence;
  var contributors = body.contributors;

  // remove straight quote marks
  contributors = util.removeQuotes(contributors);

  // split each row to process them individually
  var rows = contributors.split(/[\n\r]/g);
  var validToSave = [];
  var hasErrors = [];

  for (var i = rows.length - 1; i >= 0; i--) {
    var row = rows[i].split(',');

    if (!row[0]) {
      // empty lines or array items introduced by the split
      continue;
    }

    // there should only be three values per line
    if (row.length !== 3) {
      hasErrors.push(row);
      continue;
    }

    // trim the strings
    row = util.trimArrayValues(row);

    // the first value should be an email address
    if (row[0].indexOf("@") === -1) {
      hasErrors.push(row);
      continue;
    }

    // the second value shoud be a date
    var d = util.parseAndCheckDate(row[1]);
    if (!d) {
      hasErrors.push(row);
      continue;
    }

    // Format this exactly as needed
    row[1] = util.dateToISOtring(d);

    // this is valid
    validToSave.push({
      contributor_id: row[0],
      contribution_date: row[1],
      description: row[2]
    });
  }

  async.eachLimit(validToSave, 4, function (contribution, callback) {
    var entry = {
      logged_by: user_email,
      contributor_id: contribution.contributor_id,
      contribution_date: new Date(contribution.contribution_date),
      moz_team: teamname,
      data_bucket: databucket,
      description: contribution.description,
      evidence: evidence
    };
    data.saveItem(entry, function savedItem(err, res) {
      if (err) {
        console.log(entry);
        console.error(err);
        return;
      }
      callback(null);
    });
  }, function savedAllItems(err) {
    if (err) {
      console.error(err);
    }
    callback(null, validToSave, hasErrors);
  });

};
<|endoftext|>


<commit_before><commit_msg>Update lib<commit_after>'use strict';

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }

var React = require('react');

function LinesEllipsisLoose(props) {
  var Component = props.component,
      text = props.text,
      lineHeight = props.lineHeight,
      maxLine = props.maxLine,
      style = props.style,
      rest = _objectWithoutProperties(props, ['component', 'text', 'lineHeight', 'maxLine', 'style']);

  var lineHeightNumber = parseInt(lineHeight, 10);
  var unit = typeof lineHeight === 'string' && lineHeight.trim().endsWith('em') ? 'em' : 'px';
  var maxLineNumber = +maxLine || 1;
  return React.createElement(
    Component,
    _extends({}, rest, {
      style: _extends({}, style, {
        lineHeight: '' + lineHeightNumber + unit,
        maxHeight: '' + maxLineNumber * lineHeightNumber + unit,
        overflow: 'hidden',
        display: '-webkit-box',
        WebkitBoxOrient: 'vertical',
        WebkitLineClamp: maxLineNumber
      })
    }),
    text
  );
}

LinesEllipsisLoose.defaultProps = {
  component: 'div',
  maxLine: 1,
  style: {}
};

module.exports = LinesEllipsisLoose;

<|endoftext|>


<commit_before>"use babel";

import LoremIpsum from "./lorem-ipsum";
import { CompositeDisposable } from "atom";

export default {
  subscriptions: null,

  LoremIpsum: null,

  config: {
    defaultUnitType: {
      title: "Default type of items",
      type: "string",
      default: "Paragraph",
      enum: [
        "Paragraph",
        "Sentence",
        "Word",
        "Link",
        "Ordered List",
        "Unordered List"
      ],
      order: 1
    },
    defaultUnitCount: {
      title: "Default number of items",
      type: "integer",
      default: 1,
      minimum: 1,
      maximum: 20,
      order: 2
    },
    defaultUnitSize: {
      title: "Default length of items",
      type: "string",
      default: "Medium",
      enum: ["Any", "Short", "Medium", "Long", "Very Long"],
      order: 3
    },
    defaultIsWrapped: {
      title: "Is lorem text wrapped by default?",
      type: "boolean",
      default: true,
      order: 4
    },
    defaultWrapWidth: {
      title: "Wrap width if enabled",
      type: "integer",
      default: 80,
      minimum: 20,
      order: 5
    },
    defaultIsHTML: {
      title: "Is the lorem text wrapped in `<p>` tags?",
      type: "boolean",
      default: false,
      order: 6
    },
    defaultShowHelp: {
      title: "Should help be shown if no arguments are specified",
      type: "boolean",
      default: false,
      order: 7
    }
  },

  activate(state) {
    this.LoremIpsum = new LoremIpsum();

    // Events subscribed to in atom's system can be easily cleaned up with a CompositeDisposable
    this.subscriptions = new CompositeDisposable();

    // Register command that toggles this view
    this.subscriptions.add(
      atom.commands.add("atom-workspace", {
        "lorem:catch-command": () => this.handleLorem()
      })
    );
  },

  deactivate() {
    this.subscriptions.dispose();
  },

  serialize() {},

  getLoremCommand(editor) {
    const { row, column } = editor.getCursorBufferPosition(),
      line = editor.lineTextForBufferRow(row);

    let start = column, end = column, command = "";

    while (start > 0 && /\S/.test(line.charAt(start - 1))) {
      start--;
    }

    command = editor.getTextInBufferRange([[row, start], [row, end]]);

    if (command.match(/lorem/)) {
      command = command.substring(command.match(/lorem/).index);
    }

    return command.split("_")[0] === "lorem" ? command : "";
  },

  handleLorem() {
    const editor = atom.workspace.getActiveTextEditor();

    let command = this.getLoremCommand(editor),
      text = this.LoremIpsum.parseCommand(command),
      end = editor.getCursorBufferPosition(),
      start = [end.row, end.column - command.length];

    if (text === "") return;

    editor.transact(0, () => {
      let isComment = editor.isBufferRowCommented(end.row);

      editor.setSelectedBufferRange([start, end]);
      editor.insertText(text, { autoIndent: false, select: true });
      editor.autoIndentSelectedRows();

      if (isComment) {
        editor.languageMode.toggleLineCommentForBufferRow(end.row);
        editor.toggleLineCommentsInSelection();
      }
    });
  }
};
<commit_msg>Removed transaction groupingInterval<commit_after>"use babel";

import LoremIpsum from "./lorem-ipsum";
import { CompositeDisposable } from "atom";

export default {
  subscriptions: null,

  LoremIpsum: null,

  config: {
    defaultUnitType: {
      title: "Default type of items",
      type: "string",
      default: "Paragraph",
      enum: [
        "Paragraph",
        "Sentence",
        "Word",
        "Link",
        "Ordered List",
        "Unordered List"
      ],
      order: 1
    },
    defaultUnitCount: {
      title: "Default number of items",
      type: "integer",
      default: 1,
      minimum: 1,
      maximum: 20,
      order: 2
    },
    defaultUnitSize: {
      title: "Default length of items",
      type: "string",
      default: "Medium",
      enum: ["Any", "Short", "Medium", "Long", "Very Long"],
      order: 3
    },
    defaultIsWrapped: {
      title: "Is lorem text wrapped by default?",
      type: "boolean",
      default: true,
      order: 4
    },
    defaultWrapWidth: {
      title: "Wrap width if enabled",
      type: "integer",
      default: 80,
      minimum: 20,
      order: 5
    },
    defaultIsHTML: {
      title: "Is the lorem text wrapped in `<p>` tags?",
      type: "boolean",
      default: false,
      order: 6
    },
    defaultShowHelp: {
      title: "Should help be shown if no arguments are specified",
      type: "boolean",
      default: false,
      order: 7
    }
  },

  activate(state) {
    this.LoremIpsum = new LoremIpsum();

    // Events subscribed to in atom's system can be easily cleaned up with a CompositeDisposable
    this.subscriptions = new CompositeDisposable();

    // Register command that toggles this view
    this.subscriptions.add(
      atom.commands.add("atom-workspace", {
        "lorem:catch-command": () => this.handleLorem()
      })
    );
  },

  deactivate() {
    this.subscriptions.dispose();
  },

  serialize() {},

  getLoremCommand(editor) {
    const { row, column } = editor.getCursorBufferPosition(),
      line = editor.lineTextForBufferRow(row);

    let start = column, end = column, command = "";

    while (start > 0 && /\S/.test(line.charAt(start - 1))) {
      start--;
    }

    command = editor.getTextInBufferRange([[row, start], [row, end]]);

    if (command.match(/lorem/)) {
      command = command.substring(command.match(/lorem/).index);
    }

    return command.split("_")[0] === "lorem" ? command : "";
  },

  handleLorem() {
    const editor = atom.workspace.getActiveTextEditor();

    let command = this.getLoremCommand(editor),
      text = this.LoremIpsum.parseCommand(command),
      end = editor.getCursorBufferPosition(),
      start = [end.row, end.column - command.length];

    if (text === "") return;

    editor.transact(() => {
      let isComment = editor.isBufferRowCommented(end.row);

      editor.setSelectedBufferRange([start, end]);
      editor.insertText(text, { autoIndent: false, select: true });
      editor.autoIndentSelectedRows();

      if (isComment) {
        editor.languageMode.toggleLineCommentForBufferRow(end.row);
        editor.toggleLineCommentsInSelection();
      }
    });
  }
};
<|endoftext|>


<commit_before>
var global = (function () { return this; })();

// Searches for the given property in `comp` or a parent,
// and returns it as is (without call it if it's a function).
var lookupComponentProp = function (comp, prop) {
  comp = findComponentWithProp(prop, comp);
  var result = (comp ? comp.data : null);
  if (typeof result === 'function')
    result = _.bind(result, comp);
  return result;
};

// Component that's a no-op when used as a block helper like
// `{{#foo}}...{{/foo}}`.
var noOpComponent = Component.extend({
  kind: 'NoOp',
  render: function (buf) {
    buf.write(this.content);
  }
});

// This map is searched first when you do something like `{{#if}}` in
// a template.
var builtInComponents = {
  'if': UI.If,
  'each': UI.Each,
  'unless': UI.Unless,
  'with': UI.With,
  // for past compat:
  'constant': noOpComponent,
  'isolate': noOpComponent
};

_extend(UI.Component, {
  // _dontCall is for internal use only.
  //
  // note: `get`/`lookup` will probably take multiple arguments
  // (forming a path)

  lookup: function (id) {
    var self = this;

    var result;

    var comp;
    if (! id) {
      // `id` is `""` or absent/undefined
      return lookupComponentProp(self, 'data');

    } else if ((comp = findComponentWithProp(id, self))) {
      // found a property or method of a component
      // (`self` or one of its ancestors)
      var result = comp[id];

    } else if (_.has(builtInComponents, id)) {
      return builtInComponents[id];
    // Code to search the global namespace for capitalized names
    // like component classes, `Template`, `StringUtils.foo`,
    // etc.
    //
    // } else if (/^[A-Z]/.test(id) && (id in global)) {
    //   // Only look for a global identifier if `id` is
    //   // capitalized.  This avoids having `{{name}}` mean
    //   // `window.name`.
    //   result = global[id];
    //   return function (/*arguments*/) {
    //     var data = getComponentData(self);
    //     if (typeof result === 'function')
    //       return result.apply(data, arguments);
    //     return result;
    //   };
    } else if (Handlebars._globalHelpers[id]) {
      // Backwards compatibility for helpers defined with
      // `Handlebars.registerHelper`. XXX what is the future pattern
      // for this? We should definitely not put it on the Handlebars
      // namespace.
      result = Handlebars._globalHelpers[id];
    } else {
      // Resolve id `foo` as `data.foo` (with a "soft dot").
      return function (/*arguments*/) {
        var data = getComponentData(self);
        if (! data)
          return data;
        var result = data[id];
        if (typeof result === 'function')
          return result.apply(data, arguments);
        return result;
      };
    }

    return function (/*arguments*/) {
      if (typeof result === 'function') {
        var data = getComponentData(self);
        return result.apply(data, arguments);
      }
      return result;
    };
  },
  get: function (id) {
    var result = this.lookup(id);
    return (typeof result === 'function' ? result() : result);
  },
  set: function (id, value) {
    var comp = findComponentWithProp(id, this);
    if (! comp || ! comp[id])
      throw new Error("Can't find field: " + id);
    if (typeof comp[id] !== 'function')
      throw new Error("Not a settable field: " + id);
    comp[id](value);
  }
});
<commit_msg>Fix spacebars-tests<commit_after>
var global = (function () { return this; })();

// Searches for the given property in `comp` or a parent,
// and returns it as is (without call it if it's a function).
var lookupComponentProp = function (comp, prop) {
  comp = findComponentWithProp(prop, comp);
  var result = (comp ? comp.data : null);
  if (typeof result === 'function')
    result = _.bind(result, comp);
  return result;
};

// Component that's a no-op when used as a block helper like
// `{{#foo}}...{{/foo}}`.
var noOpComponent = Component.extend({
  kind: 'NoOp',
  render: function (buf) {
    buf.write(this.content);
  }
});

// This map is searched first when you do something like `{{#if}}` in
// a template.
var builtInComponents = {
  'if': UI.If,
  'each': UI.Each,
  'unless': UI.Unless,
  'with': UI.With,
  // for past compat:
  'constant': noOpComponent,
  'isolate': noOpComponent
};

_extend(UI.Component, {
  // _dontCall is for internal use only.
  //
  // note: `get`/`lookup` will probably take multiple arguments
  // (forming a path)

  lookup: function (id) {
    var self = this;

    var result;

    var comp;
    if (! id) {
      // `id` is `""` or absent/undefined
      return lookupComponentProp(self, 'data');

    } else if ((comp = findComponentWithProp(id, self))) {
      // found a property or method of a component
      // (`self` or one of its ancestors)
      var result = comp[id];

    } else if (_.has(builtInComponents, id)) {
      return builtInComponents[id];
    // Code to search the global namespace for capitalized names
    // like component classes, `Template`, `StringUtils.foo`,
    // etc.
    //
    // } else if (/^[A-Z]/.test(id) && (id in global)) {
    //   // Only look for a global identifier if `id` is
    //   // capitalized.  This avoids having `{{name}}` mean
    //   // `window.name`.
    //   result = global[id];
    //   return function (/*arguments*/) {
    //     var data = getComponentData(self);
    //     if (typeof result === 'function')
    //       return result.apply(data, arguments);
    //     return result;
    //   };
    } else if (Handlebars._globalHelpers[id]) {
      // Backwards compatibility for helpers defined with
      // `Handlebars.registerHelper`. XXX what is the future pattern
      // for this? We should definitely not put it on the Handlebars
      // namespace.
      result = Handlebars._globalHelpers[id];
    } else {
      // Resolve id `foo` as `data.foo` (with a "soft dot").
      return function (/*arguments*/) {
        var data = getComponentData(self);
        if (! data)
          return data;
        var result = data[id];
        if (typeof result === 'function')
          return result.apply(data, arguments);
        return result;
      };
    }

    if (typeof result === 'function') {
      return function (/*arguments*/) {
        var data = getComponentData(self);
        return result.apply(data, arguments);
      };
    } else {
      return result;
    };
  },
  get: function (id) {
    var result = this.lookup(id);
    return (typeof result === 'function' ? result() : result);
  },
  set: function (id, value) {
    var comp = findComponentWithProp(id, this);
    if (! comp || ! comp[id])
      throw new Error("Can't find field: " + id);
    if (typeof comp[id] !== 'function')
      throw new Error("Not a settable field: " + id);
    comp[id](value);
  }
});
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright Google Inc. All Rights Reserved.
 *
 * Use of this source code is governed by an MIT-style license that can be
 * found in the LICENSE file at https://angular.io/license
 */

/**
 * @fileoverview Read a tsconfig.json file intended to produce production mode
 * JS output, modify it to produce esm5 output instead, and write the result
 * to disk.
 */
const fs = require('fs');
const path = require('path');

function main(args) {
  if (args.length < 3) {
    console.error('Usage: $0 input.tsconfig.json output.tsconfig.json newRoot binDir');
  }
  [input, output, newRoot, binDir] = args;

  const data = JSON.parse(fs.readFileSync(input, {encoding: 'utf-8'}));
  data['compilerOptions']['target'] = 'es5';
  data['bazelOptions']['es5Mode'] = true;
  data['compilerOptions']['outDir'] = path.join(data['compilerOptions']['outDir'], newRoot);
  if (data['angularCompilerOptions']) {
    // Don't enable tsickle's closure conversions
    data['angularCompilerOptions']['annotateForClosureCompiler'] = false;
    data['angularCompilerOptions']['expectedOut'] =
        data['angularCompilerOptions']['expectedOut'].map(
            f => f.replace(/\.closure\.js$/, '.js').replace(binDir, path.join(binDir, newRoot)));
  }
  fs.writeFileSync(output, JSON.stringify(data));
}

if (require.main === module) {
  process.exitCode = main(process.argv.slice(2));
}
<commit_msg>fix(bazel): ng_package not generating UMD bundles on windows (#27200)<commit_after>/**
 * @license
 * Copyright Google Inc. All Rights Reserved.
 *
 * Use of this source code is governed by an MIT-style license that can be
 * found in the LICENSE file at https://angular.io/license
 */

/**
 * @fileoverview Read a tsconfig.json file intended to produce production mode
 * JS output, modify it to produce esm5 output instead, and write the result
 * to disk.
 */
const fs = require('fs');
const path = require('path');

function main(args) {
  if (args.length < 3) {
    console.error('Usage: $0 input.tsconfig.json output.tsconfig.json newRoot binDir');
  }
  [input, output, newRoot, binDir] = args;

  const data = JSON.parse(fs.readFileSync(input, {encoding: 'utf-8'}));
  data['compilerOptions']['target'] = 'es5';
  data['bazelOptions']['es5Mode'] = true;
  data['compilerOptions']['outDir'] = path.posix.join(data['compilerOptions']['outDir'], newRoot);
  if (data['angularCompilerOptions']) {
    // Relative path to the execroot that refers to the directory for the ES5 output files.
    const newOutputBase = path.posix.join(binDir, newRoot);
    // Don't enable tsickle's closure conversions
    data['angularCompilerOptions']['annotateForClosureCompiler'] = false;
    // Note: It's important that the "expectedOut" is only modified in a way that still
    // keeps posix normalized paths. Otherwise this could cause unexpected behavior because
    // ngc-wrapped is expecting POSIX paths and the TypeScript Bazel rules by default only pass
    // POSIX paths as well.
    data['angularCompilerOptions']['expectedOut'] =
        data['angularCompilerOptions']['expectedOut'].map(
            f => f.replace(/\.closure\.js$/, '.js').replace(binDir, newOutputBase));
  }
  fs.writeFileSync(output, JSON.stringify(data));
}

if (require.main === module) {
  process.exitCode = main(process.argv.slice(2));
}
<|endoftext|>