<commit_before>'use strict';

var S = require('string');
var os = require('os');
var exec = require('child_process').exec;
var p4options = require('./p4options');
var ztagRegex = /^\.\.\.\s+(\w+)\s+(.+)/;

// build a list of options/arguments for the p4 command
function optionBuilder(options) {
  options = options || {};

  var results = {stdin: [], args: [], files: []};
  Object.keys(options).map(function (option) {
    var p4option = p4options[option];
    if (!p4option) return;
    if (p4option.category !== 'unary') {
      if ((options[option] || {}).constructor !== p4option.type) return;
    }
    if (p4option.category === 'stdin') {
      results.stdin.push(p4option.cmd + options[option]);
      if (results.args.indexOf('-i') < 0) results.args.push('-i');
    } else if (p4option.cmd) {
      results.args.push(p4option.cmd);
      if (p4option.category === 'mixed') results.args.push(options[option]);
    } else {
      results.files = results.files.concat(options[option]);
    }
  });
  return results;
}

// filter passed-in options to get a hash of child process options
// (i.e., not p4 command arguments)
function execOptionBuilder(options) {
  var validKeys = {
    cwd:        true,
    env:        true,
    encoding:   true,
    shell:      true,
    timeout:    true,
    maxBuffer:  true,
    killSignal: true,
    uid:        true,
    gid:        true
  };

  options = options || {};

  return Object.keys(options).reduce(function(result, key) {
    if(validKeys[key]) {
      result[key] = options[key];
    }
    return result;
  }, options);
}

function execP4(p4cmd, options, callback) {
  if (typeof options === 'function') {
    callback = options;
    options = undefined;
  }

  var ob = optionBuilder(options);
  var childProcessOptions = execOptionBuilder(options);
  var cmd = ['p4', p4cmd, ob.args.join(' '), ob.files.join(' ')];
  var child = exec(cmd.join(' '), childProcessOptions, function (err, stdout, stderr) {
    if (err) return callback(err);
    if (stderr) return callback(new Error(stderr));
    return callback(null, stdout);
  });
  if (ob.stdin.length > 0) {
    ob.stdin.forEach(function (line) {
      child.stdin.write(line + '\n');
    });
    child.stdin.emit('end');
  }
}

// process group of lines of output from a p4 command executed with -ztag
function processZtagOutput(output) {
  return output.split('\n').reduce(function(memo, line) {
    var match, key, value;
      match = ztagRegex.exec(line);
      if(match) {
        key = match[1];
        value = match[2];
        memo[key] = value;
      }
      return memo;
  }, {});
}

function NodeP4() {}

NodeP4.prototype.changelist = {
  create: function (options, callback) {
    if (typeof options === 'function') {
      callback = options;
      options = undefined;
    }
    var newOptions = {
      _change: 'new',
      description: options.description || '<saved by node-perforce>'
    };
    execP4('change', newOptions, function (err, stdout) {
      if (err) return callback(err);
      var matched = stdout.match(/([0-9]+)/g);
      if (matched.length > 0) return callback(null, parseInt(matched[0], 10));
      else return callback(new Error('Unknown error'));
    });
  },
  edit: function (options, callback) {
    callback = callback || function(){};
    if (!options || !options.changelist) return callback(new Error('Missing parameter/argument'));
    if (!options.description) return callback();
    var newOptions = {
      _change: options.changelist.toString(),
      description: options.description
    };
    execP4('change', newOptions, function (err) {
      if (err) return callback(err);
      return callback();
    });
  },
  delete: function (options, callback) {
    callback = callback || function(){};
    if (!options || !options.changelist) return callback(new Error('Missing parameter/argument'));
    execP4('change', {_delete: options.changelist}, function (err) {
      if (err) return callback(err);
      return callback();
    });
  },
  view: function (options, callback) {
    if (!options || !options.changelist) return callback(new Error('Missing parameter/argument'));
    execP4('change', {_output: options.changelist}, function (err, stdout) {
      if (err) return callback(err);

      // preprocessing file status
      stdout = stdout.replace(/(\t)+#(.)*/g, function (match) {
        return '@@@' + match.substring(3);
      });

      var result = {};
      var lines = stdout.replace(/#(.)*\n/g, '').split(os.EOL + os.EOL);
      lines.forEach(function (line) {
        var key = S(line.split(':')[0].toLowerCase()).trim().camelize().s;
        if (key) {
          result[key] = S(line).between(':').trim().s;
        }
      });

      if (result.files) {
        result.files = result.files.split('\n').map(function (file) {
          var file = file.replace(/\t*/g, '').split('@@@');
          return {file: file[0], action: file[1]};
        });
      } else {
        result.files = [];
      }
      return callback(null, result);
    });
  },
  submit: function (options, callback) {
    if (!options || !options.changelist) return callback(new Error('Missing parameter/argument'));
    execP4('submit', options, function (err, stdout) {
      if (err) return callback(err);
    });
  }
};

NodeP4.prototype.info = function (options, callback) {
  if(typeof options === 'function') {
    callback = options;
    options = undefined;
  }
  execP4('info', options, function (err, stdout) {
    if (err) return callback(err);

    var result = {};
    S(stdout).lines().forEach(function (line) {
      if (!line) return;
      var key = S((line.split(':')[0]).toLowerCase()).camelize().s;
      result[key] = S(line).between(':').trim().s;

    });
    callback(null, result);
  });
};

// return an array of file info objects for each file opened in the workspace
NodeP4.prototype.opened = function (options, callback) {
  if(typeof options === 'function') {
    callback = options;
    options = undefined;
  }
  execP4('-ztag opened', options, function (err, stdout) {
    var result;
    if (err) return callback(err);

    // process each file
    result = stdout.trim().split('\n\n').reduce(function(memo, fileinfo) {
      // process each line of file info, transforming into a hash
      memo.push(processZtagOutput(fileinfo));
      return memo;
    }, []);

    callback(null, result);
  });
};

NodeP4.prototype.fstat = function (options, callback) {
  if(typeof options === 'function') {
    callback = options;
    options = undefined;
  }
  execP4('fstat', options, function (err, stdout) {
    var result;
    if (err) return callback(err);

    // process file info
    result = processZtagOutput(stdout);

    callback(null, result);
  });
}

var commonCommands = ['add', 'delete', 'edit', 'revert', 'sync',
                      'diff', 'reconcile', 'changes', 'reopen', 'resolved',
                      'shelve', 'unshelve', 'client', 'resolve', 'submit'];
commonCommands.forEach(function (command) {
  NodeP4.prototype[command] = function (options, callback) {
    execP4(command, options, callback);
  };
});

module.exports = new NodeP4();
<commit_msg>Add valid keys to a new object instead of to itself<commit_after>'use strict';

var S = require('string');
var os = require('os');
var exec = require('child_process').exec;
var p4options = require('./p4options');
var ztagRegex = /^\.\.\.\s+(\w+)\s+(.+)/;

// build a list of options/arguments for the p4 command
function optionBuilder(options) {
  options = options || {};

  var results = {stdin: [], args: [], files: []};
  Object.keys(options).map(function (option) {
    var p4option = p4options[option];
    if (!p4option) return;
    if (p4option.category !== 'unary') {
      if ((options[option] || {}).constructor !== p4option.type) return;
    }
    if (p4option.category === 'stdin') {
      results.stdin.push(p4option.cmd + options[option]);
      if (results.args.indexOf('-i') < 0) results.args.push('-i');
    } else if (p4option.cmd) {
      results.args.push(p4option.cmd);
      if (p4option.category === 'mixed') results.args.push(options[option]);
    } else {
      results.files = results.files.concat(options[option]);
    }
  });
  return results;
}

// filter passed-in options to get a hash of child process options
// (i.e., not p4 command arguments)
function execOptionBuilder(options) {
  var validKeys = {
    cwd:        true,
    env:        true,
    encoding:   true,
    shell:      true,
    timeout:    true,
    maxBuffer:  true,
    killSignal: true,
    uid:        true,
    gid:        true
  };

  options = options || {};

  return Object.keys(options).reduce(function(result, key) {
    if(validKeys[key]) {
      result[key] = options[key];
    }
    return result;
  }, {});
}

function execP4(p4cmd, options, callback) {
  if (typeof options === 'function') {
    callback = options;
    options = undefined;
  }

  var ob = optionBuilder(options);
  var childProcessOptions = execOptionBuilder(options);
  var cmd = ['p4', p4cmd, ob.args.join(' '), ob.files.join(' ')];
  var child = exec(cmd.join(' '), childProcessOptions, function (err, stdout, stderr) {
    if (err) return callback(err);
    if (stderr) return callback(new Error(stderr));
    return callback(null, stdout);
  });
  if (ob.stdin.length > 0) {
    ob.stdin.forEach(function (line) {
      child.stdin.write(line + '\n');
    });
    child.stdin.emit('end');
  }
}

// process group of lines of output from a p4 command executed with -ztag
function processZtagOutput(output) {
  return output.split('\n').reduce(function(memo, line) {
    var match, key, value;
      match = ztagRegex.exec(line);
      if(match) {
        key = match[1];
        value = match[2];
        memo[key] = value;
      }
      return memo;
  }, {});
}

function NodeP4() {}

NodeP4.prototype.changelist = {
  create: function (options, callback) {
    if (typeof options === 'function') {
      callback = options;
      options = undefined;
    }
    var newOptions = {
      _change: 'new',
      description: options.description || '<saved by node-perforce>'
    };
    execP4('change', newOptions, function (err, stdout) {
      if (err) return callback(err);
      var matched = stdout.match(/([0-9]+)/g);
      if (matched.length > 0) return callback(null, parseInt(matched[0], 10));
      else return callback(new Error('Unknown error'));
    });
  },
  edit: function (options, callback) {
    callback = callback || function(){};
    if (!options || !options.changelist) return callback(new Error('Missing parameter/argument'));
    if (!options.description) return callback();
    var newOptions = {
      _change: options.changelist.toString(),
      description: options.description
    };
    execP4('change', newOptions, function (err) {
      if (err) return callback(err);
      return callback();
    });
  },
  delete: function (options, callback) {
    callback = callback || function(){};
    if (!options || !options.changelist) return callback(new Error('Missing parameter/argument'));
    execP4('change', {_delete: options.changelist}, function (err) {
      if (err) return callback(err);
      return callback();
    });
  },
  view: function (options, callback) {
    if (!options || !options.changelist) return callback(new Error('Missing parameter/argument'));
    execP4('change', {_output: options.changelist}, function (err, stdout) {
      if (err) return callback(err);

      // preprocessing file status
      stdout = stdout.replace(/(\t)+#(.)*/g, function (match) {
        return '@@@' + match.substring(3);
      });

      var result = {};
      var lines = stdout.replace(/#(.)*\n/g, '').split(os.EOL + os.EOL);
      lines.forEach(function (line) {
        var key = S(line.split(':')[0].toLowerCase()).trim().camelize().s;
        if (key) {
          result[key] = S(line).between(':').trim().s;
        }
      });

      if (result.files) {
        result.files = result.files.split('\n').map(function (file) {
          var file = file.replace(/\t*/g, '').split('@@@');
          return {file: file[0], action: file[1]};
        });
      } else {
        result.files = [];
      }
      return callback(null, result);
    });
  },
  submit: function (options, callback) {
    if (!options || !options.changelist) return callback(new Error('Missing parameter/argument'));
    execP4('submit', options, function (err, stdout) {
      if (err) return callback(err);
    });
  }
};

NodeP4.prototype.info = function (options, callback) {
  if(typeof options === 'function') {
    callback = options;
    options = undefined;
  }
  execP4('info', options, function (err, stdout) {
    if (err) return callback(err);

    var result = {};
    S(stdout).lines().forEach(function (line) {
      if (!line) return;
      var key = S((line.split(':')[0]).toLowerCase()).camelize().s;
      result[key] = S(line).between(':').trim().s;

    });
    callback(null, result);
  });
};

// return an array of file info objects for each file opened in the workspace
NodeP4.prototype.opened = function (options, callback) {
  if(typeof options === 'function') {
    callback = options;
    options = undefined;
  }
  execP4('-ztag opened', options, function (err, stdout) {
    var result;
    if (err) return callback(err);

    // process each file
    result = stdout.trim().split('\n\n').reduce(function(memo, fileinfo) {
      // process each line of file info, transforming into a hash
      memo.push(processZtagOutput(fileinfo));
      return memo;
    }, []);

    callback(null, result);
  });
};

NodeP4.prototype.fstat = function (options, callback) {
  if(typeof options === 'function') {
    callback = options;
    options = undefined;
  }
  execP4('fstat', options, function (err, stdout) {
    var result;
    if (err) return callback(err);

    // process file info
    result = processZtagOutput(stdout);

    callback(null, result);
  });
}

var commonCommands = ['add', 'delete', 'edit', 'revert', 'sync',
                      'diff', 'reconcile', 'changes', 'reopen', 'resolved',
                      'shelve', 'unshelve', 'client', 'resolve', 'submit'];
commonCommands.forEach(function (command) {
  NodeP4.prototype[command] = function (options, callback) {
    execP4(command, options, callback);
  };
});

module.exports = new NodeP4();
<|endoftext|>


<commit_before>var url = require('url')
var httpProxy = require('http-proxy')

var log = require('../logger').create('proxy')
var _ = require('../helper')._

var parseProxyConfig = function (proxies, config) {
  var endsWithSlash = function (str) {
    return str.substr(-1) === '/'
  }

  if (!proxies) {
    return []
  }

  return _.sortBy(_.map(proxies, function (proxyConfiguration, proxyPath) {
    if (typeof proxyConfiguration === 'string') {
      proxyConfiguration = {target: proxyConfiguration}
    }
    var proxyUrl = proxyConfiguration.target
    var proxyDetails = url.parse(proxyUrl)
    var pathname = proxyDetails.pathname

    // normalize the proxies config
    // should we move this to lib/config.js ?
    if (endsWithSlash(proxyPath) && !endsWithSlash(proxyUrl)) {
      log.warn('proxy "%s" normalized to "%s"', proxyUrl, proxyUrl + '/')
      proxyUrl += '/'
      pathname += '/'
    }

    if (!endsWithSlash(proxyPath) && endsWithSlash(proxyUrl)) {
      log.warn('proxy "%s" normalized to "%s"', proxyPath, proxyPath + '/')
      proxyPath += '/'
    }

    if (pathname === '/' && !endsWithSlash(proxyUrl)) {
      pathname = ''
    }

    var hostname = proxyDetails.hostname || config.hostname
    var protocol = proxyDetails.protocol || config.protocol
    var port = proxyDetails.port || config.port ||
      (proxyDetails.protocol === 'https:' ? '443' : '80')
    var https = proxyDetails.protocol === 'https:'

    var proxy = httpProxy.createProxyServer({
      target: {
        host: hostname,
        port: port,
        https: https,
        protocol: protocol
      },
      xfwd: true,
      secure: config.proxyValidateSSL
    })

    proxy.on('error', function proxyError (err, req, res) {
      if (err.code === 'ECONNRESET' && req.socket.destroyed) {
        log.debug('failed to proxy %s (browser hung up the socket)', req.url)
      } else {
        log.warn('failed to proxy %s (%s)', req.url, err.message)
      }

      res.destroy()
    })

    return {
      path: proxyPath,
      baseUrl: pathname,
      host: hostname,
      port: port,
      https: https,
      proxy: proxy
    }
  }), 'path').reverse()
}

/**
 * Returns a handler which understands the proxies and its redirects, along with the proxy to use
 * @param proxies An array of proxy record objects
 * @param urlRoot The URL root that karma is mounted on
 * @return {Function} handler function
 */
var createProxyHandler = function (proxies, urlRoot) {
  if (!proxies.length) {
    var nullProxy = function createNullProxy (request, response, next) {
      return next()
    }
    nullProxy.upgrade = function upgradeNullProxy () {}
    return nullProxy
  }

  var middleware = function createProxy (request, response, next) {
    var proxyRecord = _.find(proxies, function (p) {
      return request.url.indexOf(p.path) === 0
    })

    if (!proxyRecord) {
      return next()
    }

    log.debug('proxying request - %s to %s:%s', request.url, proxyRecord.host, proxyRecord.port)
    request.url = request.url.replace(proxyRecord.path, proxyRecord.baseUrl)
    proxyRecord.proxy.web(request, response)
  }

  middleware.upgrade = function upgradeProxy (request, socket, head) {
    // special-case karma's route to avoid upgrading it
    if (request.url.indexOf(urlRoot) === 0) {
      log.debug('NOT upgrading proxyWebSocketRequest %s', request.url)
      return
    }

    var proxyRecord = _.find(proxies, function (p) {
      return request.url.indexOf(p.path) === 0
    })

    if (!proxyRecord) {
      return
    }

    log.debug('upgrade proxyWebSocketRequest %s to %s:%s',
      request.url, proxyRecord.host, proxyRecord.port)
    request.url = request.url.replace(proxyRecord.path, proxyRecord.baseUrl)
    proxyRecord.proxy.ws(request, socket, head)
  }

  return middleware
}

exports.create = function (/* config */config, /* config.proxies */proxies) {
  return createProxyHandler(parseProxyConfig(proxies, config), config.urlRoot)
}
<commit_msg>feat(proxy): Allow to configure changeOrigin option of http-proxy<commit_after>var url = require('url')
var httpProxy = require('http-proxy')

var log = require('../logger').create('proxy')
var _ = require('../helper')._

var parseProxyConfig = function (proxies, config) {
  var endsWithSlash = function (str) {
    return str.substr(-1) === '/'
  }

  if (!proxies) {
    return []
  }

  return _.sortBy(_.map(proxies, function (proxyConfiguration, proxyPath) {
    if (typeof proxyConfiguration === 'string') {
      proxyConfiguration = {target: proxyConfiguration}
    }
    var proxyUrl = proxyConfiguration.target
    var proxyDetails = url.parse(proxyUrl)
    var pathname = proxyDetails.pathname

    // normalize the proxies config
    // should we move this to lib/config.js ?
    if (endsWithSlash(proxyPath) && !endsWithSlash(proxyUrl)) {
      log.warn('proxy "%s" normalized to "%s"', proxyUrl, proxyUrl + '/')
      proxyUrl += '/'
      pathname += '/'
    }

    if (!endsWithSlash(proxyPath) && endsWithSlash(proxyUrl)) {
      log.warn('proxy "%s" normalized to "%s"', proxyPath, proxyPath + '/')
      proxyPath += '/'
    }

    if (pathname === '/' && !endsWithSlash(proxyUrl)) {
      pathname = ''
    }

    var hostname = proxyDetails.hostname || config.hostname
    var protocol = proxyDetails.protocol || config.protocol
    var port = proxyDetails.port || config.port ||
      (proxyDetails.protocol === 'https:' ? '443' : '80')
    var https = proxyDetails.protocol === 'https:'

    var changeOrigin = 'changeOrigin' in proxyConfiguration ? proxyConfiguration.changeOrigin : false
    var proxy = httpProxy.createProxyServer({
      target: {
        host: hostname,
        port: port,
        https: https,
        protocol: protocol
      },
      xfwd: true,
      changeOrigin: changeOrigin,
      secure: config.proxyValidateSSL
    })

    proxy.on('error', function proxyError (err, req, res) {
      if (err.code === 'ECONNRESET' && req.socket.destroyed) {
        log.debug('failed to proxy %s (browser hung up the socket)', req.url)
      } else {
        log.warn('failed to proxy %s (%s)', req.url, err.message)
      }

      res.destroy()
    })

    return {
      path: proxyPath,
      baseUrl: pathname,
      host: hostname,
      port: port,
      https: https,
      proxy: proxy
    }
  }), 'path').reverse()
}

/**
 * Returns a handler which understands the proxies and its redirects, along with the proxy to use
 * @param proxies An array of proxy record objects
 * @param urlRoot The URL root that karma is mounted on
 * @return {Function} handler function
 */
var createProxyHandler = function (proxies, urlRoot) {
  if (!proxies.length) {
    var nullProxy = function createNullProxy (request, response, next) {
      return next()
    }
    nullProxy.upgrade = function upgradeNullProxy () {}
    return nullProxy
  }

  var middleware = function createProxy (request, response, next) {
    var proxyRecord = _.find(proxies, function (p) {
      return request.url.indexOf(p.path) === 0
    })

    if (!proxyRecord) {
      return next()
    }

    log.debug('proxying request - %s to %s:%s', request.url, proxyRecord.host, proxyRecord.port)
    request.url = request.url.replace(proxyRecord.path, proxyRecord.baseUrl)
    proxyRecord.proxy.web(request, response)
  }

  middleware.upgrade = function upgradeProxy (request, socket, head) {
    // special-case karma's route to avoid upgrading it
    if (request.url.indexOf(urlRoot) === 0) {
      log.debug('NOT upgrading proxyWebSocketRequest %s', request.url)
      return
    }

    var proxyRecord = _.find(proxies, function (p) {
      return request.url.indexOf(p.path) === 0
    })

    if (!proxyRecord) {
      return
    }

    log.debug('upgrade proxyWebSocketRequest %s to %s:%s',
      request.url, proxyRecord.host, proxyRecord.port)
    request.url = request.url.replace(proxyRecord.path, proxyRecord.baseUrl)
    proxyRecord.proxy.ws(request, socket, head)
  }

  return middleware
}

exports.create = function (/* config */config, /* config.proxies */proxies) {
  return createProxyHandler(parseProxyConfig(proxies, config), config.urlRoot)
}
<|endoftext|>


<commit_before>
var kue = require('kue');
var twitter = require('ntwitter');
var EventEmitter = require('events').EventEmitter;

var utils = require('./lib/utils');

/*
 *
 * TwitterProcessing
 *
 */
var TwitterProcessing = function(options) {

	//Call eventemitter constructor
	EventEmitter.call(this);

	//Options
	this.options = utils.merge({
		'debug' : false,
		'processor' : null,
		'redis' : {
			'host' : '127.0.0.1',
			'port' : 6379
		},
		'twitter' : {
			'consumer_key' : 'Twitter',
			'consumer_secret' : 'API',
			'access_token_key' : 'keys',
			'access_token_secret' : 'go here'
		},
		'filter' : {
			'track' : ['twitter']
		},
		'pauseTimeout' : 5000,
		'queueName' : 'twitter_processing_'
	},options);

	//Server
	this.twitter = this.createTwitter();

	//Twitter Stream
	this.currentStream = null;

	//Queue
	//this.redis = this.createRedis();
	this.jobs = this.createQueue();
	this.jobsCount = 0;

	//Processor
	this.processor = this.options.processor || null;

	//State
	this.isProcessing = false;
	this.isStarted = false;

	//Initialize
	this.init();

};

//Extend EventEmitter
TwitterProcessing.prototype = Object.create(EventEmitter.prototype);

/*
 *
 * Create methods
 *
 */
//Create queue
TwitterProcessing.prototype.createQueue = function() {
	var self = this;
	kue.redis.createClient = function() {
		var redis = require('redis');
		var client = redis.createClient(self.options.redis.port, self.options.redis.host);
		if(self.options.redis.password) {
	    	client.auth(self.options.redis.password);
		}
		return client;
	};
	var jobs = kue.createQueue();
	return jobs;
}

//Create Redis
TwitterProcessing.prototype.createRedis = function() {
	var redis = require('redis');
	var client = redis.createClient(this.options.redis.port, this.options.redis.host);
	if(this.options.redis.password) {
    	client.auth(this.options.redis.password);
	}
    return client;
}

//Create Twitter
TwitterProcessing.prototype.createTwitter = function() {
	var twit = new twitter(this.options.twitter);
	return twit;
};

/*
 *
 * Init methods
 *
 */
TwitterProcessing.prototype.init = function() {

	var self = this;

	//Init kue
	this.jobs.on('job complete', function(id){
		if(self.options.debug) {
			console.log('Kue: Job completed', id);
		}
		self.jobsCount--;
		kue.Job.get(id, function(err, job){
			if (err || !job) return;

			self.emit('tweet',job.data);

			job.remove(function(err){
				if(self.options.debug) {
					console.log('Kue: Removing job', err, job.data.text);
				}
				if(self.jobsCount == 0) {
					self.isProcessing = false;
					if(self.options.debug) {
						console.log('Kue: Queue completed');
					}
				}
				if (err) throw err;
			});
		});
	});

};

TwitterProcessing.prototype._startStream = function() {

	if(!this._retriesCount) {
		this._retriesCount = 1;
	}

	var self = this;

	this.twitter.stream('statuses/filter', this.options.filter, function(stream) {

		if(self.options.debug) {
			console.log('Twitter stream started');
		}

		self.currentStream = stream;

		//On new tweet
		stream.on('data', function (tweet) {

			//Filter tweet text to remove symbols
			tweet.textFiltered = utils.filterTweetText(tweet.text);

			//console.log('Tweet: '+tweet.textFiltered);

			//Create the job
			self.jobs.create(self.options.queueName, tweet).save();
			self.jobsCount++;

			//Start the queue if it is paused
			if(!self.isProcessing) {
				self.jobs.process(self.options.queueName,function() {
					self.process.apply(self,arguments);
				});
				self.isProcessing = true;
			}

		});

		//On stream error
		stream.on('error', function (response) {
			if(self.options.debug) {
				console.log('Twitter error',arguments);
			}
			try {
				self._retriesCount = self._retriesCount * 2;
				stream.destroy();
			} catch(e){}
		});

		//On stream end
		stream.on('end', function (response) {
			try {
				self._retriesCount = 1;
				stream.destroy();
			} catch(e){}
		});

		//On stream destroy, reconnect
		stream.on('destroy', function (response) {

			//Reconnect if the destroy was not intented
			if(self.isStarted) {
				if(self.options.debug) {
					console.log('Twitter stream reconnect in '+self._retriesCount+' second(s)');
				}
				setTimeout(function() {
					self._startStream();
				},self._retriesCount * 1000);
			}
		});

	});

};

//Start
TwitterProcessing.prototype.start = function() {

	if(this.options.debug) {
		console.log('TwitterProcessing start');
	}

	this.isStarted = true;

	this._startStream();

};

//Stop the streamer
TwitterProcessing.prototype.stop = function() {

	if(this.options.debug) {
		console.log('TwitterProcessing stop');
	}

	this.isStarted = false;

	if(this.currentStream) {
		this.currentStream.end();
	}

};

//Process tweet
TwitterProcessing.prototype.process = function(job,done) {

	if(!this.processor) done();

	this.processor.process(job,function() {
		job.save(done);
	});

	return;

};

/*
 *
 * Factory
 *
 */
function factory(options) {

	var twittertts = new TwitterProcessing(options);

	return twittertts;

}

module.exports = exports = factory;<commit_msg>Processor accept a function instead of an object with a process method<commit_after>
var kue = require('kue');
var twitter = require('ntwitter');
var EventEmitter = require('events').EventEmitter;

var utils = require('./lib/utils');

/*
 *
 * TwitterProcessing
 *
 */
var TwitterProcessing = function(options) {

	//Call eventemitter constructor
	EventEmitter.call(this);

	//Options
	this.options = utils.merge({
		'debug' : false,
		'processor' : function(job,done){
			done();
		},
		'redis' : {
			'host' : '127.0.0.1',
			'port' : 6379
		},
		'twitter' : {
			'consumer_key' : 'Twitter',
			'consumer_secret' : 'API',
			'access_token_key' : 'keys',
			'access_token_secret' : 'go here'
		},
		'filter' : {
			'track' : ['twitter']
		},
		'pauseTimeout' : 5000,
		'queueName' : 'twitter_processing_'
	},options);

	//Server
	this.twitter = this.createTwitter();

	//Twitter Stream
	this.currentStream = null;

	//Queue
	//this.redis = this.createRedis();
	this.jobs = this.createQueue();
	this.jobsCount = 0;

	//Processor
	this.processor = this.options.processor || null;

	//State
	this.isProcessing = false;
	this.isStarted = false;

	//Initialize
	this.init();

};

//Extend EventEmitter
TwitterProcessing.prototype = Object.create(EventEmitter.prototype);

/*
 *
 * Create methods
 *
 */
//Create queue
TwitterProcessing.prototype.createQueue = function() {
	var self = this;
	kue.redis.createClient = function() {
		var redis = require('redis');
		var client = redis.createClient(self.options.redis.port, self.options.redis.host);
		if(self.options.redis.password) {
	    	client.auth(self.options.redis.password);
		}
		return client;
	};
	var jobs = kue.createQueue();
	return jobs;
}

//Create Redis
TwitterProcessing.prototype.createRedis = function() {
	var redis = require('redis');
	var client = redis.createClient(this.options.redis.port, this.options.redis.host);
	if(this.options.redis.password) {
    	client.auth(this.options.redis.password);
	}
    return client;
}

//Create Twitter
TwitterProcessing.prototype.createTwitter = function() {
	var twit = new twitter(this.options.twitter);
	return twit;
};

/*
 *
 * Init methods
 *
 */
TwitterProcessing.prototype.init = function() {

	var self = this;

	//Init kue
	this.jobs.on('job complete', function(id){
		if(self.options.debug) {
			console.log('Kue: Job completed', id);
		}
		self.jobsCount--;
		kue.Job.get(id, function(err, job){
			if (err || !job) return;

			self.emit('tweet',job.data);

			job.remove(function(err){
				if(self.options.debug) {
					console.log('Kue: Removing job', err, job.data.text);
				}
				if(self.jobsCount == 0) {
					self.isProcessing = false;
					if(self.options.debug) {
						console.log('Kue: Queue completed');
					}
				}
				if (err) throw err;
			});
		});
	});

};

TwitterProcessing.prototype._startStream = function() {

	if(!this._retriesCount) {
		this._retriesCount = 1;
	}

	var self = this;

	this.twitter.stream('statuses/filter', this.options.filter, function(stream) {

		if(self.options.debug) {
			console.log('Twitter stream started');
		}

		self.currentStream = stream;

		//On new tweet
		stream.on('data', function (tweet) {

			//Filter tweet text to remove symbols
			tweet.textFiltered = utils.filterTweetText(tweet.text);

			//console.log('Tweet: '+tweet.textFiltered);

			//Create the job
			self.jobs.create(self.options.queueName, tweet).save();
			self.jobsCount++;

			//Start the queue if it is paused
			if(!self.isProcessing) {
				self.jobs.process(self.options.queueName,function() {
					self.process.apply(self,arguments);
				});
				self.isProcessing = true;
			}

		});

		//On stream error
		stream.on('error', function (response) {
			if(self.options.debug) {
				console.log('Twitter error',arguments);
			}
			try {
				self._retriesCount = self._retriesCount * 2;
				stream.destroy();
			} catch(e){}
		});

		//On stream end
		stream.on('end', function (response) {
			try {
				self._retriesCount = 1;
				stream.destroy();
			} catch(e){}
		});

		//On stream destroy, reconnect
		stream.on('destroy', function (response) {

			//Reconnect if the destroy was not intented
			if(self.isStarted) {
				if(self.options.debug) {
					console.log('Twitter stream reconnect in '+self._retriesCount+' second(s)');
				}
				setTimeout(function() {
					self._startStream();
				},self._retriesCount * 1000);
			}
		});

	});

};

//Start
TwitterProcessing.prototype.start = function() {

	if(this.options.debug) {
		console.log('TwitterProcessing start');
	}

	this.isStarted = true;

	this._startStream();

};

//Stop the streamer
TwitterProcessing.prototype.stop = function() {

	if(this.options.debug) {
		console.log('TwitterProcessing stop');
	}

	this.isStarted = false;

	if(this.currentStream) {
		this.currentStream.end();
	}

};

//Process tweet
TwitterProcessing.prototype.process = function(job,done) {

	if(!this.processor) done();

	if(this.processor) {
		this.processor(job,function() {
			job.save(done);
		});
	}

	return;

};

/*
 *
 * Factory
 *
 */
function factory(options) {

	var twittertts = new TwitterProcessing(options);

	return twittertts;

}

module.exports = exports = factory;<|endoftext|>


<commit_before>'use strict';

const _ = require('underscore');
const pProps = require('p-props');
const pMap = require('p-map');
const pEachSeries = require('p-each-series');
const Migrator = require('./migrator');

function MigrationManager() {
	this.migrator = new Migrator();

	// TODO: allow to pass params
	this._initLogger({});
}

MigrationManager.prototype._initLogger = function _initLogger(params) {
	const logger = _({}).extend(console);

	logger.debug = params.trace ? logger.log : _.noop;

	if (params.silent) {
		logger.log = _.noop;
	}

	this.logger = logger;
};

MigrationManager.prototype.configure = function configure(params) {
	// FIXME: call init logger once
	this._initLogger(params);

	return this.migrator.configure(params);
};

MigrationManager.prototype.connect = function connect() {
	return this.migrator.connect();
};

MigrationManager.prototype.disconnect = function disconnect() {
	return this.migrator.disconnect();
};

MigrationManager.prototype._filterMigrationNames =
	function _filterMigrationNames(params) {
		return Promise.resolve()
			.then(() => {
				return this.migrator.filterMigrationNames({
					by: params.by,
					names: params.names,
					tag: params.tag
				});
			})
			.then((filterResult) => {
				return filterResult && filterResult.names;
			});
	};

MigrationManager.prototype._fallbackCommaSeparatedNames =
	function _fallbackCommaSeparatedNames(names) {
		const length = names.length;

		if (length === 1) {
			names = names[0].split(',');

			if (names.length > length) {
				this.logger.info(
					'DEPRECATION WARNING: target migrations separated by comma will ' +
					'not be supported in future versions (use space instead)'
				);
			}
		}

		return names;
	};

MigrationManager.prototype.getMigrationNames =
	function getMigrationNames(params) {
		return Promise.resolve()
			.then(() => {
				if (params.migrations && params.status) {
					throw new Error(
						'`status` option cannot be used when particular ' +
						'migrations are specified'
					);
				}

				if (params.migrations && params.migrations.length) {
					const migrations = this._fallbackCommaSeparatedNames(
						params.migrations
					);

					return this.migrator.normalizeNames(migrations);
				} else {
					const status = params.status || 'new';

					return this.migrator.getMigrationNames(status);
				}
			})
			.then((names) => {
				if (params.tag) {
					return this._filterMigrationNames({
						by: 'tag',
						tag: params.tag,
						names
					});
				} else {
					return names;
				}
			});
	};

MigrationManager.prototype._validateMigrationNames =
	function _validateMigrationNames(names) {
		return Promise.resolve()
			.then(() => {
				return pProps({
					checkMigrationsExistsResult: (
						this.migrator.checkMigrationsExists(names)
					),
					names
				});
			})
			.then((result) => result.names);
	};

MigrationManager.prototype._migrate = function _migrate(migration) {
	return Promise.resolve()
		.then(() => {
			this.logger.log(`Migrate "${migration.name}"`);

			return this.migrator.migrate(migration);
		})
		.then(() => {
			this.logger.log('Migration done');
		});
};

MigrationManager.prototype.migrate = function migrate(params) {
	return Promise.resolve()
		.then(() => {
			const getParams = {
				migrations: params.migrations,
				status: params.status,
				tag: params.tag
			};

			return this.getMigrationNames(getParams);
		})
		.then((names) => this._validateMigrationNames(names))
		.then((names) => {
			const promisesObject = {
				separated: this.migrator.separateNames(names)
			};

			if (params.force) {
				delete promisesObject.separated;
				promisesObject.names = names;
			}

			return pProps(promisesObject);
		})
		.then((result) => {
			if (result.separated) {
				_(result.separated.executedNames).each((name) => {
					this.logger.log(`Skip "${name}" because it's already executed`);
				});

				return result.separated.newNames;
			} else {
				return result.names;
			}
		})
		.then((names) => {
			if (_(names).isEmpty()) {
				this.logger.info('Nothing to migrate');

				return null;
			}

			this.logger.log(`Target migrations:\n\t${names.join('\n\t')}`);

			// TODO: move concurrency to vars
			return pMap(names, (name) => {
				return this.migrator.loadMigration(name);
			}, {concurrency: 10});
		})
		.then((migrations) => {
			if (migrations) {
				return pEachSeries(migrations, (migration) => {
					migration.force = params.force;

					return this._migrate(migration);
				});
			}
		});
};

MigrationManager.prototype.getParams = function getParams() {
	return Promise.resolve(this.migrator.params);
};

MigrationManager.prototype.isMigrationsDirExist =
	function isMigrationsDirExist() {
		return this.migrator.isDirExists();
	};

module.exports = MigrationManager;
<commit_msg>use underscore to pick and check empty<commit_after>'use strict';

const _ = require('underscore');
const pProps = require('p-props');
const pMap = require('p-map');
const pEachSeries = require('p-each-series');
const Migrator = require('./migrator');

function MigrationManager() {
	this.migrator = new Migrator();

	// TODO: allow to pass params
	this._initLogger({});
}

MigrationManager.prototype._initLogger = function _initLogger(params) {
	const logger = _({}).extend(console);

	logger.debug = params.trace ? logger.log : _.noop;

	if (params.silent) {
		logger.log = _.noop;
	}

	this.logger = logger;
};

MigrationManager.prototype.configure = function configure(params) {
	// FIXME: call init logger once
	this._initLogger(params);

	return this.migrator.configure(params);
};

MigrationManager.prototype.connect = function connect() {
	return this.migrator.connect();
};

MigrationManager.prototype.disconnect = function disconnect() {
	return this.migrator.disconnect();
};

MigrationManager.prototype._filterMigrationNames =
	function _filterMigrationNames(params) {
		return Promise.resolve()
			.then(() => {
				return this.migrator.filterMigrationNames({
					by: params.by,
					names: params.names,
					tag: params.tag
				});
			})
			.then((filterResult) => {
				return filterResult && filterResult.names;
			});
	};

MigrationManager.prototype._fallbackCommaSeparatedNames =
	function _fallbackCommaSeparatedNames(names) {
		const length = names.length;

		if (length === 1) {
			names = names[0].split(',');

			if (names.length > length) {
				this.logger.info(
					'DEPRECATION WARNING: target migrations separated by comma will ' +
					'not be supported in future versions (use space instead)'
				);
			}
		}

		return names;
	};

MigrationManager.prototype.getMigrationNames =
	function getMigrationNames(params) {
		return Promise.resolve()
			.then(() => {
				if (params.migrations && params.status) {
					throw new Error(
						'`status` option cannot be used when particular ' +
						'migrations are specified'
					);
				}

				if (_(params.migrations).isEmpty()) {
					const status = params.status || 'new';

					return this.migrator.getMigrationNames(status);
				} else {
					const migrations = this._fallbackCommaSeparatedNames(
						params.migrations
					);

					return this.migrator.normalizeNames(migrations);
				}
			})
			.then((names) => {
				if (params.tag) {
					return this._filterMigrationNames({
						by: 'tag',
						tag: params.tag,
						names
					});
				} else {
					return names;
				}
			});
	};

MigrationManager.prototype._validateMigrationNames =
	function _validateMigrationNames(names) {
		return Promise.resolve()
			.then(() => {
				return pProps({
					checkMigrationsExistsResult: (
						this.migrator.checkMigrationsExists(names)
					),
					names
				});
			})
			.then((result) => result.names);
	};

MigrationManager.prototype._migrate = function _migrate(migration) {
	return Promise.resolve()
		.then(() => {
			this.logger.log(`Migrate "${migration.name}"`);

			return this.migrator.migrate(migration);
		})
		.then(() => {
			this.logger.log('Migration done');
		});
};

MigrationManager.prototype.migrate = function migrate(params) {
	return Promise.resolve()
		.then(() => {
			return this.getMigrationNames(
				_(params).pick('migrations', 'status', 'tag')
			);
		})
		.then((names) => this._validateMigrationNames(names))
		.then((names) => {
			const promisesObject = {
				separated: this.migrator.separateNames(names)
			};

			if (params.force) {
				delete promisesObject.separated;
				promisesObject.names = names;
			}

			return pProps(promisesObject);
		})
		.then((result) => {
			if (result.separated) {
				_(result.separated.executedNames).each((name) => {
					this.logger.log(`Skip "${name}" because it's already executed`);
				});

				return result.separated.newNames;
			} else {
				return result.names;
			}
		})
		.then((names) => {
			if (_(names).isEmpty()) {
				this.logger.info('Nothing to migrate');

				return null;
			}

			this.logger.log(`Target migrations:\n\t${names.join('\n\t')}`);

			// TODO: move concurrency to vars
			return pMap(names, (name) => {
				return this.migrator.loadMigration(name);
			}, {concurrency: 10});
		})
		.then((migrations) => {
			if (migrations) {
				return pEachSeries(migrations, (migration) => {
					migration.force = params.force;

					return this._migrate(migration);
				});
			}
		});
};

MigrationManager.prototype.getParams = function getParams() {
	return Promise.resolve(this.migrator.params);
};

MigrationManager.prototype.isMigrationsDirExist =
	function isMigrationsDirExist() {
		return this.migrator.isDirExists();
	};

module.exports = MigrationManager;
<|endoftext|>


<commit_before>import setup from './lib/setup'
import verify from './lib/verify'
import pickStrategies from './lib/pickStrategies'
import rimraf from 'rimraf'
import Promise from 'bluebird'

const rm = Promise.promisify(rimraf)

function* run() {
  const sandboxPath = yield setup()
  const verifyResult = yield verify(sandboxPath)
  if (verifyResult === false) {
    yield rm(sandboxPath)
    return '`npm install` works fine'
  }

  const strategies = pickStrategies(verifyResult)
  for (let strategy of strategies) {
    yield strategy(sandboxPath)
  }

  const reVerifyResult = yield verify(sandboxPath)
  if (reVerifyResult === false) {
    yield rm(sandboxPath)
    return '`npm install` is now working'
  }

  yield rm(sandboxPath)
  return 'Unable to fix `npm install` issues'
}

run = Promise.coroutine(run)

run()
  .then((msg) => console.log(msg))
  .catch((e) => console.warn(e))

// let sandboxPath = null
// setup()
//   .then(path => {
//     sandboxPath = path
//     return verify(sandboxPath)
//   })
//   .then(err => {
//     if (err === false) {
//       throw '`npm install` works fine. Chill bro'
//     }
//     return pickStrategies(err)
//   })
//   .then(strategies => Promise.all(strategies.map(strategy => strategy(sandboxPath))))
//   .then(() => verify(sandboxPath))
//   .then(err => {
//     if (err === false) {
//       console.log('yay fixed')
//     } else {
//       console.log('no dice')
//     }
//   })
//   .finally(() => {
//     rimraf(sandboxPath, {}, () => {})
//   })

<commit_msg>Add some comments and remove dead code<commit_after>import setup from './lib/setup'
import verify from './lib/verify'
import pickStrategies from './lib/pickStrategies'
import rimraf from 'rimraf'
import Promise from 'bluebird'

const rm = Promise.promisify(rimraf)

function* run() {
  // Setup our test environment - this involves copying from the source
  // into a temporary directory so we aren't affecting actual versions
  const sandboxPath = yield setup()

  // Verify there is actually an issue with `npm install`
  const verifyResult = yield verify(sandboxPath)
  if (verifyResult === false) {
    yield rm(sandboxPath)
    return '`npm install` works fine'
  }

  // Based on the error message from `npm install`, pick a list
  // of strategies to fix the error and then execute each strategy
  const strategies = pickStrategies(verifyResult)
  for (let strategy of strategies) {
    yield strategy(sandboxPath)
  }

  // Check again if `npm install` works
  const reVerifyResult = yield verify(sandboxPath)
  if (reVerifyResult === false) {
    yield rm(sandboxPath)
    return '`npm install` is now working'
  }

  yield rm(sandboxPath)
  return 'Unable to fix `npm install` issues'
}

run = Promise.coroutine(run)

run()
  .then((msg) => console.log(msg))
  .catch((e) => console.warn(e))

<|endoftext|>


<commit_before>/* globals navigator*/

'use strict';

function info(){
  var ua = navigator.userAgent;
  var tem;
  var os;

  var match = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];

  if (ua.indexOf('Win') !== -1) {
    os = 'Windows';
  }
  if (ua.indexOf('Mac') !== -1) {
    os = 'MacOS';
  }
  if (ua.indexOf('X11') !== -1) {
    os = 'UNIX';
  }
  if (ua.indexOf('Linux' )!== -1) {
    os = 'Linux';
  }

  if (/trident/i.test(match[1])) {
    tem = /\brv[ :]+(\d+)/g.exec(ua) || [];
    return {
      name: 'IE ',
      version: (tem[1]||''),
      os: os
    };
  }
  if (match[1] === 'Chrome') {
    tem = ua.match(/\bOPR\/(\d+)/);
    if (tem !== null) {
      return {
        name: 'Opera',
        version: tem[1],
        os: os
      };
    }
  }
  match = match[2]? [match[1], match[2]]: [navigator.appName, navigator.appVersion, '-?'];
  if ((tem = ua.match(/version\/(\d+)/i)) !== null) {
    match.splice(1, 1, tem[1]);
  }
  return {
    name: match[0],
    version: match[1],
    os: os
  };
}

module.exports = info;
<commit_msg>Removed space added to browser name when IE<commit_after>/* globals navigator*/

'use strict';

function info(){
  var ua = navigator.userAgent;
  var tem;
  var os;

  var match = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];

  if (ua.indexOf('Win') !== -1) {
    os = 'Windows';
  }
  if (ua.indexOf('Mac') !== -1) {
    os = 'MacOS';
  }
  if (ua.indexOf('X11') !== -1) {
    os = 'UNIX';
  }
  if (ua.indexOf('Linux' )!== -1) {
    os = 'Linux';
  }

  if (/trident/i.test(match[1])) {
    tem = /\brv[ :]+(\d+)/g.exec(ua) || [];
    return {
      name: 'IE',
      version: (tem[1]||''),
      os: os
    };
  }
  if (match[1] === 'Chrome') {
    tem = ua.match(/\bOPR\/(\d+)/);
    if (tem !== null) {
      return {
        name: 'Opera',
        version: tem[1],
        os: os
      };
    }
  }
  match = match[2]? [match[1], match[2]]: [navigator.appName, navigator.appVersion, '-?'];
  if ((tem = ua.match(/version\/(\d+)/i)) !== null) {
    match.splice(1, 1, tem[1]);
  }
  return {
    name: match[0],
    version: match[1],
    os: os
  };
}

module.exports = info;
<|endoftext|>


<commit_before>var fs     = require('fs');
var xml2js = require('xml2js');
var ig     = require('imagemagick');
var colors = require('colors');
var _      = require('underscore');
var Q      = require('q');

/**
 * Check which platforms are added to the project and return their icon names and sized
 *
 * @param  {String} projectName
 * @return {Promise} resolves with an array of platforms
 */
var getPlatforms = function (projectName) {
    var deferred = Q.defer();
    var platforms = [];
    platforms.push({
        name : 'ios',
        // TODO: use async fs.exists
        isAdded : fs.existsSync('platforms/ios'),
        iconsPath : 'platforms/ios/' + projectName + '/Resources/icons/',
        icons : [
            { name : 'icon-40.png',       size : 40  },
            { name : 'icon-40@2x.png',    size : 80  },
            { name : 'icon-50.png',       size : 50  },
            { name : 'icon-50@2x.png',    size : 100 },
            { name : 'icon-60.png',       size : 60  },
            { name : 'icon-60@2x.png',    size : 120 },
            { name : 'icon-60@3x.png',    size : 180 },
            { name : 'icon-72.png',       size : 72  },
            { name : 'icon-72@2x.png',    size : 144 },
            { name : 'icon-76.png',       size : 76  },
            { name : 'icon-76@2x.png',    size : 152 },
            { name : 'icon-small.png',    size : 29  },
            { name : 'icon-small@2x.png', size : 58  },
            { name : 'icon.png',          size : 57  },
            { name : 'icon@2x.png',       size : 114 },
        ]
    });
    platforms.push({
        name : 'android',
        iconsPath : 'platforms/android/res/',
        isAdded : fs.existsSync('platforms/android'),
        icons : [
            { name : 'drawable/icon.png',       size : 96 },
            { name : 'drawable-hdpi/icon.png',  size : 72 },
            { name : 'drawable-ldpi/icon.png',  size : 36 },
            { name : 'drawable-mdpi/icon.png',  size : 48 },
            { name : 'drawable-xhdpi/icon.png', size : 96 },
            { name : 'drawable-xxhdpi/icon.png', size : 144 },
        ]
    });
    // TODO: add all platforms
    deferred.resolve(platforms);
    return deferred.promise;
};

/**
 * @var {Object} settings - names of the confix file and of the icon image
 * TODO: add option to get these values as CLI params
 */
var settings = {};
settings.CONFIG_FILE = 'config.xml';
settings.ICON_FILE   = 'icon.png';

/**
 * @var {Object} console utils
 */
var display = {};
display.success = function (str) {
    str = '✓  '.green + str;
    console.log('  ' + str);
};
display.error = function (str) {
    str = '✗  '.red + str;
    console.log('  ' + str);
};
display.header = function (str) {
    console.log('');
    console.log(' ' + str.cyan.underline);
    console.log('');
};

/**
 * read the config file and get the project name
 *
 * @return {Promise} resolves to a string - the project's name
 */
var getProjectName = function () {
    var deferred = Q.defer();
    var parser = new xml2js.Parser();
    data = fs.readFile(settings.CONFIG_FILE, function (err, data) {
        if (err) {
            deferred.reject(err);
        }
        parser.parseString(data, function (err, result) {
            if (err) {
                deferred.reject(err);
            }
            var projectName = result.widget.name[0];
            deferred.resolve(projectName);
        });
    });
    return deferred.promise;
};

/**
 * Resizes and creates a new icon in the platform's folder.
 *
 * @param  {Object} platform
 * @param  {Object} icon
 * @return {Promise}
 */
var generateIcon = function (platform, icon) {
    var deferred = Q.defer();
    ig.resize({
        srcPath: settings.ICON_FILE,
        dstPath: platform.iconsPath + icon.name,
        quality: 1,
        format: 'png',
        width: icon.size,
        height: icon.size,
    } , function(err, stdout, stderr){
        if (err) {
            deferred.reject(err);
        } else {
            deferred.resolve();
            display.success(icon.name + ' created');
        }
    });
    return deferred.promise;
};

/**
 * Generates icons based on the platform object
 *
 * @param  {Object} platform
 * @return {Promise}
 */
var generateIconsForPlatform = function (platform) {
    var deferred = Q.defer();
    display.header('Generating Icons for ' + platform.name);
    var all = [];
    var icons = platform.icons;
    icons.forEach(function (icon) {
        all.push(generateIcon(platform, icon));
    });
    Q.all(all).then(function () {
        deferred.resolve();
    }).catch(function (err) {
        console.log(err);
    });
    return deferred.promise;
};

/**
 * Goes over all the platforms and triggers icon generation
 *
 * @param  {Array} platforms
 * @return {Promise}
 */
var generateIcons = function (platforms) {
    var deferred = Q.defer();
    var sequence = Q();
    var all = [];
    _(platforms).where({ isAdded : true }).forEach(function (platform) {
        sequence = sequence.then(function () {
            return generateIconsForPlatform(platform);
        });
        all.push(sequence);
    });
    Q.all(all).then(function () {
        deferred.resolve();
    });
    return deferred.promise;
};

/**
 * Checks if at least one platform was added to the project
 *
 * @return {Promise} resolves if at least one platform was found, rejects otherwise
 */
var atLeastOnePlatformFound = function () {
    var deferred = Q.defer();
    getPlatforms().then(function (platforms) {
        var activePlatforms = _(platforms).where({ isAdded : true });
        if (activePlatforms.length > 0) {
            display.success('platforms found: ' + _(activePlatforms).pluck('name').join(', '));
            deferred.resolve();
        } else {
            display.error('No cordova platforms found. Make sure you are in the root folder of your Cordova project and add platforms with \'cordova platform add\'');
            deferred.reject();
        }
    });
    return deferred.promise;
};

/**
 * Checks if a valid icon file exists
 *
 * @return {Promise} resolves if exists, rejects otherwise
 */
var validIconExists = function () {
    var deferred = Q.defer();
    fs.exists(settings.ICON_FILE, function (exists) {
        if (exists) {
            display.success(settings.ICON_FILE + ' exists');
            deferred.resolve();
        } else {
            display.error(settings.ICON_FILE + ' does not exist in the root folder');
            deferred.reject();
        }
    });
    return deferred.promise;
};

/**
 * Checks if a config.xml file exists
 *
 * @return {Promise} resolves if exists, rejects otherwise
 */
var configFileExists = function () {
    var deferred = Q.defer();
    fs.exists(settings.CONFIG_FILE, function (exists) {
        if (exists) {
            display.success(settings.CONFIG_FILE + ' exists');
            deferred.resolve();
        } else {
            display.error('cordova\'s ' + settings.CONFIG_FILE + ' does not exist in the root folder');
            deferred.reject();
        }
    });
    return deferred.promise;
};

display.header('Checking Project & Icon');

atLeastOnePlatformFound()
    .then(validIconExists)
    .then(configFileExists)
    .then(getProjectName)
    .then(getPlatforms)
    .then(generateIcons)
    .catch(function (err) {
        if (err) {
            console.log(err);
        }
    }).then(function () {
        console.log('');
    });
<commit_msg>splash image expansion<commit_after>var fs     = require('fs');
var xml2js = require('xml2js');
var ig     = require('imagemagick');
var colors = require('colors');
var _      = require('underscore');
var Q      = require('q');

/**
 * Check which platforms are added to the project and return their icon names and sized
 *
 * @param  {String} projectName
 * @return {Promise} resolves with an array of platforms
 */
var getPlatforms = function (projectName) {
    var deferred = Q.defer();
    var platforms = [];
    platforms.push({
        name : 'ios',
        // TODO: use async fs.exists
        isAdded : fs.existsSync('platforms/ios'),
        iconsPath : 'platforms/ios/' + projectName + '/Resources/icons/',
        icons : [
            { name : 'icon-40.png',       size : 40  },
            { name : 'icon-40@2x.png',    size : 80  },
            { name : 'icon-50.png',       size : 50  },
            { name : 'icon-50@2x.png',    size : 100 },
            { name : 'icon-60.png',       size : 60  },
            { name : 'icon-60@2x.png',    size : 120 },
            { name : 'icon-60@3x.png',    size : 180 },
            { name : 'icon-72.png',       size : 72  },
            { name : 'icon-72@2x.png',    size : 144 },
            { name : 'icon-76.png',       size : 76  },
            { name : 'icon-76@2x.png',    size : 152 },
            { name : 'icon-small.png',    size : 29  },
            { name : 'icon-small@2x.png', size : 58  },
            { name : 'icon.png',          size : 57  },
            { name : 'icon@2x.png',       size : 114 },
        ]
    });
    platforms.push({
        name : 'android',
        iconsPath : 'platforms/android/res/',
        isAdded : fs.existsSync('platforms/android'),
        icons : [
            { name : 'drawable/icon.png',       size : 96 },
            { name : 'drawable-hdpi/icon.png',  size : 72 },
            { name : 'drawable-ldpi/icon.png',  size : 36 },
            { name : 'drawable-mdpi/icon.png',  size : 48 },
            { name : 'drawable-xhdpi/icon.png', size : 96 },
            { name : 'drawable-xxhdpi/icon.png', size : 144 },
        ]
    });
    // TODO: add all platforms
    deferred.resolve(platforms);
    return deferred.promise;
};

/**
 * @var {Object} settings - names of the confix file and of the icon image
 * TODO: add option to get these values as CLI params
 */
var settings = {};
settings.CONFIG_FILE = 'config.xml';
settings.ICON_FILE   = 'res/icon.png';
settings.SPLASH_FILE_PORTRAIT = 'res/splash_p.png';
settings.SPLASH_FILE_LANDSCAPE = 'res/splash_l.png';

/**
 * @var {Object} console utils
 */
var display = {};
display.success = function (str) {
    str = '✓  '.green + str;
    console.log('  ' + str);
};
display.error = function (str) {
    str = '✗  '.red + str;
    console.log('  ' + str);
};
display.header = function (str) {
    console.log('');
    console.log(' ' + str.cyan.underline);
    console.log('');
};

/**
 * read the config file and get the project name
 *
 * @return {Promise} resolves to a string - the project's name
 */
var getProjectName = function () {
    var deferred = Q.defer();
    var parser = new xml2js.Parser();
    data = fs.readFile(settings.CONFIG_FILE, function (err, data) {
        if (err) {
            deferred.reject(err);
        }
        parser.parseString(data, function (err, result) {
            if (err) {
                deferred.reject(err);
            }
            var projectName = result.widget.name[0];
            deferred.resolve(projectName);
        });
    });
    return deferred.promise;
};

/**
 * Resizes and creates a new icon in the platform's folder.
 *
 * @param  {Object} platform
 * @param  {Object} icon
 * @return {Promise}
 */
var generateIcon = function (platform, image) {
    var deferred = Q.defer();
    var imageProp = {
        dstPath: platform.iconsPath + image.name,
        quality: 1,
        format: 'png',
        width: image.width,
        height: image.height,
    };

    if(platform.type == 'Icons'){
        imageProp.srcPath = settings.ICON_FILE;
    } else {
        if(image.width > image.height){
            imageProp.srcPath = settings.SPLASH_FILE_LANDSCAPE;
        } else {
            imageProp.srcPath = settings.SPLASH_FILE_PORTRAIT;
        }
    }

    ig.resize(imageProp, function(err, stdout, stderr){
        if (err) {
            deferred.reject(err);
        } else {
            deferred.resolve();
            display.success(image.name + ' created');
        }
    });

    return deferred.promise;
};

/**
 * Generates icons based on the platform object
 *
 * @param  {Object} platform
 * @return {Promise}
 */
var generateIconsForPlatform = function (platform) {
    var deferred = Q.defer();
    display.header('Generating ' + platform.type + ' for ' + platform.name);
    var all = [];

    if (platform.icons) {
        platform.icons.forEach(function (icon) {
            all.push(generateIcon(platform, icon));
        });
    } else {
        platform.splashes.forEach(function (splash) {
            all.push(generateIcon(platform, splash));
        });
    }

    Q.all(all).then(function () {
        deferred.resolve();
    }).catch(function (err) {
        console.log(err);
    });
    return deferred.promise;
};

/**
 * Goes over all the platforms and triggers icon generation
 *
 * @param  {Array} platforms
 * @return {Promise}
 */
var generateIcons = function (platforms) {
    var deferred = Q.defer();
    var sequence = Q();
    var all = [];
    _(platforms).where({ isAdded : true }).forEach(function (platform) {
        sequence = sequence.then(function () {
            return generateIconsForPlatform(platform);
        });
        all.push(sequence);
    });
    Q.all(all).then(function () {
        deferred.resolve();
    });
    return deferred.promise;
};

/**
 * Checks if at least one platform was added to the project
 *
 * @return {Promise} resolves if at least one platform was found, rejects otherwise
 */
var atLeastOnePlatformFound = function () {
    var deferred = Q.defer();
    getPlatformsFromConfig().then(function (platforms) {
        var activePlatforms = _(platforms).where({ isAdded : true });
        if (activePlatforms.length > 0) {
            display.success('platforms found: ' + _(activePlatforms).pluck('name').join(', '));
            deferred.resolve();
        } else {
            display.error('No cordova platforms found. Make sure you are in the root folder of your Cordova project and add platforms with \'cordova platform add\'');
            deferred.reject();
        }
    });
    return deferred.promise;
};

/**
 * Checks if a valid images files exist
 *
 * @return {Promise} resolves if exists, rejects otherwise
 */
var validImagesExist = function () {
    var deferred = Q.defer();
    var all = []

    all.push(checkImage(settings.ICON_FILE));
    all.push(checkImage(settings.SPLASH_FILE_PORTRAIT));
    all.push(checkImage(settings.SPLASH_FILE_LANDSCAPE));

    Q.all(all).then(function () {
        deferred.resolve();
    });

    return deferred.promise;
};

/**
 * Checks if a valid image file exists
 *
 * @return {Promise} resolves if exists, rejects otherwise
 */
var checkImage = function (file) {
    var deferred = Q.defer();
    fs.exists(file, function (exists) {
        if (exists) {
            display.success(file + ' exists');
            deferred.resolve();
        } else {
            display.error(file + ' does not exist in the root folder');
            deferred.reject();
        }
    });
    return deferred.promise;
};

/**
 * Checks if a config.xml file exists
 *
 * @return {Promise} resolves if exists, rejects otherwise
 */
var configFileExists = function () {
    var deferred = Q.defer();
    fs.exists(settings.CONFIG_FILE, function (exists) {
        if (exists) {
            display.success(settings.CONFIG_FILE + ' exists');
            deferred.resolve();
        } else {
            display.error('cordova\'s ' + settings.CONFIG_FILE + ' does not exist in the root folder');
            deferred.reject();
        }
    });
    return deferred.promise;
};

/**
 * Check which platforms are added to the project (via confix.xml) and return their icon names and size
 *
 * @param  {String} projectName
 * @return {Promise} resolves with an array of platforms
 */
var getPlatformsFromConfig = function (projectName) {
    var deferred = Q.defer();
    var parser = new xml2js.Parser();
    var platforms = [];
    var folderCount = 0;
    var all = [];

    fs.readFile(settings.CONFIG_FILE, 'utf8', function(err, data){
        parser.parseString(data, function (err, result) {
            result.widget.platform.forEach(function(node){
                getIcons(node, platforms, function(platforms_result){
                    getSplash(node, platforms, function(platforms_result){
                        folderCount++;

                        if(folderCount == result.widget.platform.length){
                            deferred.resolve(platforms_result);
                        }
                    });
                });
            });
        });
    });

    return deferred.promise;
};

/**
 * extract the icon information from the node structure
 *
 * @param  {Object} node
 * @param  {Array} platforms
 * @param  {String} cb
 * @return {Function} function with platforms array
 */
var getIcons = function (node, platforms, cb) {
    var platform = {};

    fs.mkdir('res/' + node.$.name, function(err){

        platform.name = node.$.name;
        platform.iconsPath = '';
        platform.isAdded = fs.existsSync('platforms/' + node.$.name),
        platform.icons = [];
        platform.type = 'Icons';

        if(node.icon){
            node.icon.forEach(function(icon){
                platform.icons.push({ name: icon.$.src, width: icon.$.width, height: icon.$.height });
            });
        }

        platforms.push(platform);

        return cb(platforms);
    });
};

/**
 * extract the splash information from the node structure
 *
 * @param  {Object} node
 * @param  {Array} platforms
 * @param  {String} cb
 * @return {Function} function with platforms array
 */
var getSplash = function (node, platforms, cb) {
    var platform = {};

    fs.mkdir('res/screen', function(err){
        fs.mkdir('res/screen/' + node.$.name, function(err){

            platform.name = node.$.name;
            platform.iconsPath = '';
            platform.isAdded = fs.existsSync('platforms/' + node.$.name),
            platform.splashes = [];
            platform.type = 'Splashes';

            if(node.splash){
                node.splash.forEach(function(splash){
                    platform.splashes.push({ name: splash.$.src, width: splash.$.width, height: splash.$.height });
                });
            }

            platforms.push(platform);

            return cb(platforms);
        });
    });
};

display.header('Checking Project & Icon');

atLeastOnePlatformFound()
    .then(validImagesExist)
    .then(configFileExists)
    .then(getProjectName)
    // .then(getPlatforms)
    .then(getPlatformsFromConfig)
    .then(generateIcons)
    .catch(function (err) {
        if (err) {
            console.log(err);
        }
    }).then(function () {
        console.log('');
    });
<|endoftext|>


<commit_before>/* global require, __dirname */
module.exports = function() {
	'use strict';

	var path = require( 'path' ),
		project = null;

	project = {
		paths: {
			config:    'config/',
			assets:    'assets/',
			languages: 'languages/',
			release:   'release/',
			tmp:       'tmp/',
			jsSrc:     'js/src/',
			cssSrc:    'css/src/',
			fontSrc:   'font/src/',
			imagesSrc: 'images/src/',
			bower:     'bower/',
			grunt:     'config/grunt/',
			tasks:     'config/grunt/tasks/',
			global: {
				config: path.join( __dirname, 'config/' ),
				grunt:  path.join( __dirname, 'config/grunt/' ),
				tasks:  path.join( __dirname, 'config/grunt/tasks/' )
			}
		},
		taskMap: {
			addtextdomain: 'grunt-wp-i18n',
			makepot:       'grunt-wp-i18n',
			usebanner:     'grunt-banner',
			wpcss:         'grunt-wp-css'
		}
	};

	project.files = {
		js:     project.paths.jsSrc   + '**/*.js',
		scss:   project.paths.cssSrc  + '**/*.scss',
		config: project.paths.config  + '**/*.js',
		php: [
			'*.php',
			'**/*.php',
			'!.git/**',
			'!.sass-cache/**',
			'!assets/**',
			'!css/**',
			'!release/**',
			'!fonts/**',
			'!images/**',
			'!js/**',
			'!languages/**',
			'!bower_components/**',
			'!node_modules/**',
			'!tmp/**'
		]
	};

	return project;
};
<commit_msg>Prevent js build recursion during the watch command<commit_after>/* global require, __dirname */
module.exports = function() {
	'use strict';

	var path = require( 'path' ),
		project = null;

	project = {
		paths: {
			config:    'config/',
			assets:    'assets/',
			languages: 'languages/',
			release:   'release/',
			tmp:       'tmp/',
			jsSrc:     'js/src/',
			cssSrc:    'css/src/',
			fontSrc:   'font/src/',
			imagesSrc: 'images/src/',
			bower:     'bower/',
			grunt:     'config/grunt/',
			tasks:     'config/grunt/tasks/',
			global: {
				config: path.join( __dirname, 'config/' ),
				grunt:  path.join( __dirname, 'config/grunt/' ),
				tasks:  path.join( __dirname, 'config/grunt/tasks/' )
			}
		},
		taskMap: {
			addtextdomain: 'grunt-wp-i18n',
			makepot:       'grunt-wp-i18n',
			usebanner:     'grunt-banner',
			wpcss:         'grunt-wp-css'
		}
	};

	project.files = {
		js: [
			project.paths.jsSrc + '**/*.js',
			'!' + project.paths.jsSrc + '**/*.min.js',
			'!' + project.paths.jsSrc + 'vendor/'
		],
		scss:   project.paths.cssSrc  + '**/*.scss',
		config: project.paths.config  + '**/*.js',
		php: [
			'*.php',
			'**/*.php',
			'!.git/**',
			'!.sass-cache/**',
			'!assets/**',
			'!css/**',
			'!release/**',
			'!fonts/**',
			'!images/**',
			'!js/**',
			'!languages/**',
			'!bower_components/**',
			'!node_modules/**',
			'!tmp/**'
		]
	};

	return project;
};
<|endoftext|>


<commit_before>'use strict';

const path = require('path')
    , fs = require('fs')
    , env = process.env
    , cp = require('child_process')

const HOST_NON_EXISTENT = /host does not exist/i
    , ALREADY_RUNNING = /already running/i

class Machine {
  static options(opts) {
    if (typeof opts === 'string') return { name: opts }
    else return opts || {}
  }

  static command(args, done) {
    cp.execFile('docker-machine', [].concat(args), {
      cwd: env.DOCKER_TOOLBOX_INSTALL_PATH || '.',
      encoding: 'utf8'
    }, done)
  }

  constructor(opts) {
    opts = Machine.options(opts)
    this.name = opts.name || env.DOCKER_MACHINE_NAME || 'default'
  }

  static status(name, done) {
    Machine.command(['status', name], (err, stdout) => {
      if (err) done(err)
      else done(null, stdout.trim().toLowerCase())
    })
  }

  static isRunning(name, done) {
    Machine.status(name, (err, status) => {
      done(err, status === 'running')
    })
  }

  static start(name, done) {
    Machine.command(['start', name], (err) => {
      if (HOST_NON_EXISTENT.test(err)) {
        done(new Error(`Docker host "${name}" does not exist`))
      } else if (ALREADY_RUNNING.test(err)) {
        done()
      } else {
        done(err)
      }
    })
  }

  static env(name, opts, done) {
    if (typeof opts === 'function') done = opts, opts = {}

    const args = ['env']

    if (opts.json) args.push('--shell', 'bash')
    else if (opts.shell) args.push('--shell', opts.shell)

    args.push(name)

    Machine.command(args, function (err, stdout) {
      if (err) return done(err)
      if (!opts.json) return done(null, stdout.trim())

      const res = {}

      stdout.split(/\n+/).forEach(line => {
        const m = /^export (.+)="([^"]+)/i.exec(line)
        if (m) res[m[1]] = m[2]
      })

      done(null, res)
    })
  }

  static ssh(name, cmd, done) {
    if (Array.isArray(cmd)) cmd = cmd.join(' ')
    Machine.command(['ssh', name, cmd], done)
  }
}

;['status', 'isRunning', 'start', 'env', 'ssh'].forEach(method => {
  Machine.prototype[method] = function () {
    const args = Array.from(arguments)
    args.unshift(this.name)
    Machine[method].apply(null, args)
  }
})

module.exports = Machine
<commit_msg>feat: add inspect method<commit_after>'use strict';

const path = require('path')
    , fs = require('fs')
    , env = process.env
    , cp = require('child_process')

const HOST_NON_EXISTENT = /host does not exist/i
    , ALREADY_RUNNING = /already running/i

class Machine {
  constructor(opts) {
    opts = Machine.options(opts)
    this.name = opts.name || env.DOCKER_MACHINE_NAME || 'default'
  }

  static options(opts) {
    if (typeof opts === 'string') return { name: opts }
    else return opts || {}
  }

  static command(args, done) {
    cp.execFile('docker-machine', [].concat(args), {
      cwd: env.DOCKER_TOOLBOX_INSTALL_PATH || '.',
      encoding: 'utf8'
    }, done)
  }

  static status(name, done) {
    Machine.command(['status', name], (err, stdout) => {
      if (err) done(err)
      else done(null, stdout.trim().toLowerCase())
    })
  }

  static isRunning(name, done) {
    Machine.status(name, (err, status) => {
      done(err, status === 'running')
    })
  }

  static start(name, done) {
    Machine.command(['start', name], (err) => {
      if (HOST_NON_EXISTENT.test(err)) {
        done(new Error(`Docker host "${name}" does not exist`))
      } else if (ALREADY_RUNNING.test(err)) {
        done()
      } else {
        done(err)
      }
    })
  }

  static env(name, opts, done) {
    if (typeof opts === 'function') done = opts, opts = {}

    const args = ['env']

    if (opts.json) args.push('--shell', 'bash')
    else if (opts.shell) args.push('--shell', opts.shell)

    args.push(name)

    Machine.command(args, function (err, stdout) {
      if (err) return done(err)
      if (!opts.json) return done(null, stdout.trim())

      const res = {}

      stdout.split(/\n+/).forEach(line => {
        const m = /^export (.+)="([^"]+)/i.exec(line)
        if (m) res[m[1]] = m[2]
      })

      done(null, res)
    })
  }

  static ssh(name, cmd, done) {
    if (Array.isArray(cmd)) cmd = cmd.join(' ')
    Machine.command(['ssh', name, cmd], done)
  }

  static inspect(name, done) {
    Machine.command(['inspect', name], (err, stdout) => {
      if (err) return done(err)

      try {
        var data = JSON.parse(stdout.trim())
      } catch (err) {
        return done(err)
      }

      done(null, data)
    })
  }

}

;['status', 'isRunning', 'start', 'env', 'ssh', 'inspect'].forEach(method => {
  Machine.prototype[method] = function () {
    const args = Array.from(arguments)
    args.unshift(this.name)
    Machine[method].apply(null, args)
  }
})

module.exports = Machine
<|endoftext|>


<commit_before>var /**
     * @private
     * @const
     * @type {Object}
     */
    db = require('./db.json'),
    /**
     * @private
     * @const
     * @type {String}
     * @default
     */
    SEP = '/',
    /**
     * @private
     * @cons
     * @type {String}
     * @default
     */
    E = '',
    /**
     * @private
     * @constant
     * @type {String}
     * @default
     */
    TEXT = 'text',
    /**
     * @private
     * @constant
     * @type {String}
     * @default
     */
    RAW = 'raw',
    /**
     * @private
     * @constant
     * @type {String}
     * @default
     */
    UNKNOWN = 'unknown',
    /**
     * @private
     * @constant
     * @type {String}
     * @default
     */
    PLAIN = 'plain',

    /**
     * All the content type base types that mostly mean what they are meant to do!
     *
     * @private
     * @constant
     * @type {RegExp}
     * @default
     */
    AUDIO_VIDEO_IMAGE_TEXT = /(audio|video|image|text)/,
    /**
     * A blanket check for commonly used keywords that are associated with text content type
     *
     * @private
     * @constant
     * @type {RegExp}
     * @default
     */
    JSON_XML_SCRIPT_SIBLINGS = /(jsonp|json|xml|html|yaml|vml|webml|script)/,
    /**
     * Same check as the sure-shot bases, except that these must be sub-types
     *
     * @private
     * @constant
     * @type {RegExp}
     * @default
     */
    AUDIO_VIDEO_IMAGE_TEXT_SUBTYPE = /\/[^\/]*(audio|video|image|text)/,
    /**
     * The content type bases that are not well defined or ambiguous to classify
     *
     * @private
     * @constant
     * @type {RegExp}
     * @default
     */
    APPLICATION_MESSAGE_MULTIPART = /(application|message|multipart)/;

/**
 * Simple module to lookup the base format of HTTP response bodies from the content-type header
 * @module mime-format
 */

module.exports = {
    /**
     * Attempts to guess the format by analysing mime type and not a db lookup
     * @private
     * @param {String} mime - contentType header value
     * @returns {Object}
     */
    guess: function (mime) {

        var info = {
                type: UNKNOWN,
                format: RAW,
                guessed: true
            },
            match,
            base;

        // extract the mime base
        base = (base = mime.split(SEP)) && base[0] || E;

        // bail out on the mime types that are sure-shot ones with no ambiguity
        match = base.match(AUDIO_VIDEO_IMAGE_TEXT);
        if (match && match[1]) {
            info.type = info.format = match[1];

            // we do special kane matching to extract the format in case the match was text
            // this ensures that we get same formats like we will do in kane match later down the line
            if (info.type === TEXT) {
                match = mime.match(JSON_XML_SCRIPT_SIBLINGS);
                info.format = match && match[1] || PLAIN;
            }
            return info;
        }

        // we do a kane match on entire mime (not just base) to find texts
        match = mime.match(JSON_XML_SCRIPT_SIBLINGS);
        if (match && match[1]) {
            info.type = TEXT;
            info.format = match[1];
            return info;
        }

        // now we match the subtype having names from the sure shot bases
        match = mime.match(AUDIO_VIDEO_IMAGE_TEXT_SUBTYPE);
        if (match && match[1]) {
            info.type = info.format = match[1];
            return info;
        }

        // now that most text and sure-shot types and sub-types are out of our way, we detect standard bases
        // and rest are unknown
        match = base.match(APPLICATION_MESSAGE_MULTIPART);
        if (match && match[1]) {
            info.type = match[1];
            info.format = RAW;
            return info;
        }

        // at this point nothing has matched nothing. it is worth keeping a note of it
        info.orphan = true;
        return info;
    },

    /**
     * Finds the mime-format of the provided Content-Type
     * @param {String} mime - Content-Type for which you want to find the mime format. e.g application/xml.
     * @returns {Object}
     * @example
Basic usage

     * mimeFormat.lookup('application/xml');
     *
     * // Output
     * // {
     * //   "type": "text",
     * //   "format": "xml"
     * // }
     *
     * @example
Content-Type with charset

     * mimeFormat.lookup('application/xml; charset=gBk');
     *
     * // Output
     * // {
     * //   "type": "text",
     * //   "format": "xml",
     * //   "charset": "gBk"
     * // }
     *
     * @example
Unknown Content-Type

     * mimeFormat.lookup('random/abc');
     *
     * // Output
     * // {
     * //   "type": "unknown",
     * //   "format": "raw",
     * //   "guessed": true,
     * //   "orphan": true
     * // }
     *
     */
    lookup: function mimeFormatLookup (mime) {
        var charset = require('charset')(mime);

        // sanitise the mime argument
        mime = String(mime).toLowerCase().replace(/\s/g, E).replace(/^([^;]+).*$/g, '$1');
        var result = db[mime] || module.exports.guess(mime);

        // add the charset info to the mime.
        result && charset && (result.charset = charset);
        result && (result.source = mime); // store the sanitised mime
        return result;
    }
};
<commit_msg>replaced constant with const<commit_after>var /**
     * @private
     * @const
     * @type {Object}
     */
    db = require('./db.json'),
    /**
     * @private
     * @const
     * @type {String}
     * @default
     */
    SEP = '/',
    /**
     * @private
     * @const
     * @type {String}
     * @default
     */
    E = '',
    /**
     * @private
     * @const
     * @type {String}
     * @default
     */
    TEXT = 'text',
    /**
     * @private
     * @const
     * @type {String}
     * @default
     */
    RAW = 'raw',
    /**
     * @private
     * @const
     * @type {String}
     * @default
     */
    UNKNOWN = 'unknown',
    /**
     * @private
     * @const
     * @type {String}
     * @default
     */
    PLAIN = 'plain',

    /**
     * All the content type base types that mostly mean what they are meant to do!
     *
     * @private
     * @const
     * @type {RegExp}
     * @default
     */
    AUDIO_VIDEO_IMAGE_TEXT = /(audio|video|image|text)/,
    /**
     * A blanket check for commonly used keywords that are associated with text content type
     *
     * @private
     * @const
     * @type {RegExp}
     * @default
     */
    JSON_XML_SCRIPT_SIBLINGS = /(jsonp|json|xml|html|yaml|vml|webml|script)/,
    /**
     * Same check as the sure-shot bases, except that these must be sub-types
     *
     * @private
     * @const
     * @type {RegExp}
     * @default
     */
    AUDIO_VIDEO_IMAGE_TEXT_SUBTYPE = /\/[^\/]*(audio|video|image|text)/,
    /**
     * The content type bases that are not well defined or ambiguous to classify
     *
     * @private
     * @const
     * @type {RegExp}
     * @default
     */
    APPLICATION_MESSAGE_MULTIPART = /(application|message|multipart)/;

/**
 * Simple module to lookup the base format of HTTP response bodies from the content-type header
 * @module mime-format
 */

module.exports = {
    /**
     * Attempts to guess the format by analysing mime type and not a db lookup
     * @private
     * @param {String} mime - contentType header value
     * @returns {Object}
     */
    guess: function (mime) {

        var info = {
                type: UNKNOWN,
                format: RAW,
                guessed: true
            },
            match,
            base;

        // extract the mime base
        base = (base = mime.split(SEP)) && base[0] || E;

        // bail out on the mime types that are sure-shot ones with no ambiguity
        match = base.match(AUDIO_VIDEO_IMAGE_TEXT);
        if (match && match[1]) {
            info.type = info.format = match[1];

            // we do special kane matching to extract the format in case the match was text
            // this ensures that we get same formats like we will do in kane match later down the line
            if (info.type === TEXT) {
                match = mime.match(JSON_XML_SCRIPT_SIBLINGS);
                info.format = match && match[1] || PLAIN;
            }
            return info;
        }

        // we do a kane match on entire mime (not just base) to find texts
        match = mime.match(JSON_XML_SCRIPT_SIBLINGS);
        if (match && match[1]) {
            info.type = TEXT;
            info.format = match[1];
            return info;
        }

        // now we match the subtype having names from the sure shot bases
        match = mime.match(AUDIO_VIDEO_IMAGE_TEXT_SUBTYPE);
        if (match && match[1]) {
            info.type = info.format = match[1];
            return info;
        }

        // now that most text and sure-shot types and sub-types are out of our way, we detect standard bases
        // and rest are unknown
        match = base.match(APPLICATION_MESSAGE_MULTIPART);
        if (match && match[1]) {
            info.type = match[1];
            info.format = RAW;
            return info;
        }

        // at this point nothing has matched nothing. it is worth keeping a note of it
        info.orphan = true;
        return info;
    },

    /**
     * Finds the mime-format of the provided Content-Type
     * @param {String} mime - Content-Type for which you want to find the mime format. e.g application/xml.
     * @returns {Object}
     * @example
Basic usage

     * mimeFormat.lookup('application/xml');
     *
     * // Output
     * // {
     * //   "type": "text",
     * //   "format": "xml"
     * // }
     *
     * @example
Content-Type with charset

     * mimeFormat.lookup('application/xml; charset=gBk');
     *
     * // Output
     * // {
     * //   "type": "text",
     * //   "format": "xml",
     * //   "charset": "gBk"
     * // }
     *
     * @example
Unknown Content-Type

     * mimeFormat.lookup('random/abc');
     *
     * // Output
     * // {
     * //   "type": "unknown",
     * //   "format": "raw",
     * //   "guessed": true,
     * //   "orphan": true
     * // }
     *
     */
    lookup: function mimeFormatLookup (mime) {
        var charset = require('charset')(mime);

        // sanitise the mime argument
        mime = String(mime).toLowerCase().replace(/\s/g, E).replace(/^([^;]+).*$/g, '$1');
        var result = db[mime] || module.exports.guess(mime);

        // add the charset info to the mime.
        result && charset && (result.charset = charset);
        result && (result.source = mime); // store the sanitised mime
        return result;
    }
};
<|endoftext|>


<commit_before>module.exports = function(nunjucks, opts) {
    opts = opts || { start: 'applyFilter', end: 'endApplyFilter' };

    return function FilterExtension(_env) {
        this.tags = [name || opts.start];

        this.parse = function(parser, nodes, lexer) {
            // get the tag token
            var tok = parser.nextToken();

            // parse the args and move after the block end. passing true
            // as the second arg is required if there are no parentheses
            var args = parser.parseSignature(null, true);
            parser.advanceAfterBlockEnd(tok.value);

            // parse the body and possibly the error block, which is optional
            var body = parser.parseUntilBlocks(opts.end);

            parser.advanceAfterBlockEnd();

            return new nodes.CallExtension(this, 'run', args, [body]);
        };

        this.run = function(context, filter) {
            var ret, args, body;
            args = Array.prototype.slice.call(arguments);
            body = args[args.length - 1];
            args = args.slice(2,-1);

            ret = new nunjucks.runtime.SafeString(body());
            if (!_env.filters[filter]) throw "Filter '"+filter+"' doesn't exists";

            args.unshift(ret.val);
            ret.val = _env.filters[filter].apply(null, args);
            return ret;
        };
    };
};
<commit_msg>I need some sleep and some unit tests<commit_after>module.exports = function(nunjucks, opts) {
    opts = opts || { start: 'applyFilter', end: 'endApplyFilter' };

    return function FilterExtension(_env) {
        this.tags = [opts.start];

        this.parse = function(parser, nodes, lexer) {
            // get the tag token
            var tok = parser.nextToken();

            // parse the args and move after the block end. passing true
            // as the second arg is required if there are no parentheses
            var args = parser.parseSignature(null, true);
            parser.advanceAfterBlockEnd(tok.value);

            // parse the body and possibly the error block, which is optional
            var body = parser.parseUntilBlocks(opts.end);

            parser.advanceAfterBlockEnd();

            return new nodes.CallExtension(this, 'run', args, [body]);
        };

        this.run = function(context, filter) {
            var ret, args, body;
            args = Array.prototype.slice.call(arguments);
            body = args[args.length - 1];
            args = args.slice(2,-1);

            ret = new nunjucks.runtime.SafeString(body());
            if (!_env.filters[filter]) throw "Filter '"+filter+"' doesn't exists";

            args.unshift(ret.val);
            ret.val = _env.filters[filter].apply(null, args);
            return ret;
        };
    };
};
<|endoftext|>


<commit_before>var execFile, waveform_bin;

execFile = require('child_process').execFile;
waveform_bin = path.resolve(__dirname, "bin", "waveform");

module.exports = function(audiofile, pngfile, options, callback) {
  var cmdline, value, opt;

  cmdline = [audiofile, pngfile];
  for (opt in options) {
    if (options.hasOwnProperty(opt)) {
      value = options[opt];
      cmdline.push('--' + opt);
      cmdline.push(value);
    }
  }

  execFile(waveform_bin, cmdline, function(err, stdout, stderr) {
    if (err) {
      callback(err);
    } else if (stderr.length) {
      callback(stderr);
    } else {
      callback(null);
    }
  });
};
<commit_msg>fix bug: forgot to require path<commit_after>var execFile, waveform_bin, path;

path = require('path');

execFile = require('child_process').execFile;
waveform_bin = path.resolve(__dirname, "bin", "waveform");

module.exports = function(audiofile, pngfile, options, callback) {
  var cmdline, value, opt;

  cmdline = [audiofile, pngfile];
  for (opt in options) {
    if (options.hasOwnProperty(opt)) {
      value = options[opt];
      cmdline.push('--' + opt);
      cmdline.push(value);
    }
  }

  execFile(waveform_bin, cmdline, function(err, stdout, stderr) {
    if (err) {
      callback(err);
    } else if (stderr.length) {
      callback(stderr);
    } else {
      callback(null);
    }
  });
};
<|endoftext|>


<commit_before>/**
 * connect-cache-control
 *
 * Connect middleware to prevent the browser
 * from caching the response.
 *
 * Copyright (c) Eric Elliott 2013
 *
 * MIT License
 *
 * Written for the book,
 * "Programming JavaScript Applications"
 * (O'Reilly)
 */

'use strict';

var cacheControl = function cacheControl(req, res,
    next) {

  // Support old browsers
  res.setHeader('Expires', 0);

  // Support recent browsers
  res.setHeader('Cache-Control', 'no-store, ' +
    'no-cache, must-revalidate, max-age=0');

  // This isn't a standard response header,
  // but many browsers respect it.
  res.setHeader('Pragma', 'no-cache');

  next();
};

module.exports = cacheControl;
<commit_msg>Set response header to a valid date in the past.<commit_after>/**
 * connect-cache-control
 *
 * Connect middleware to prevent the browser
 * from caching the response.
 *
 * Copyright (c) Eric Elliott 2013
 *
 * MIT License
 *
 * Written for the book,
 * "Programming JavaScript Applications"
 * (O'Reilly)
 */

'use strict';

var cacheControl = function cacheControl(req, res,
    next) {

  // Support old browsers
  res.setHeader('Expires', 'Fri, 01 Jan 1990 00:00:00 GMT');

  // Support recent browsers
  res.setHeader('Cache-Control', 'no-store, ' +
    'no-cache, must-revalidate, max-age=0');

  // This isn't a standard response header,
  // but many browsers respect it.
  res.setHeader('Pragma', 'no-cache');

  next();
};

module.exports = cacheControl;

<|endoftext|>