<commit_before>/* Il prefisso "component_" negli attributi del modello serve ad evitare collisioni
   (sia l'app che il panel usano Backbone) */

define(["backbone", "underscore", "models/AppComponent", "backboneAgentClient"],
function(Backbone, _, AppComponent, backboneAgentClient) {

    var AppView = AppComponent.extend({

        category: "View",

        // attributi supportati dal modello
        defaults: {
            "component_index": null, // int
            "component_name": null, // string
            "component_modelIndex": null, // int
            "component_collectionIndex": null, // int
            "component_status": "Created" // can be "Created", "Rendered" or "Removed"
        },

        // Change the component status by analyzing its "Operation" actions.
        handleAction: function(action) {
            if (action.get("type") == "Operation") {
                var operationName = action.get("name");
                if (operationName == "render") {
                    this.set("component_status", "Rendered");
                } else if (operationName == "remove") {
                    this.set("component_status", "Removed");
                }
            }
        },

        // Estrae gli attributi dalle info recuperate dall'agent.
        fetchLogic: function(onComplete) {
            backboneAgentClient.execFunction(function(componentIndex, componentStatus) {
                var appViewInfo = this.getAppComponentInfoByIndex("View", componentIndex);
                var componentModelInfo = this.getAppComponentInfo(appViewInfo.component.model);
                var componentCollectionInfo = this.getAppComponentInfo(appViewInfo.component.collection);

                var appViewComponent = appViewInfo.component;
                var appViewSelector = "";
                if (appViewComponent.el) {
                    if (appViewComponent.el.id && appViewComponent.el.id !== "") {
                        appViewSelector = "#"+appViewComponent.el.id;
                    }
                    if (appViewComponent.el.className && appViewComponent.el.className !== "") {
                        appViewSelector += "."+appViewComponent.el.className.replace(/ /g, '.');
                    }
                }
                var componentName = appViewComponent.constructor.name || null;
                var componentNameDetails = appViewSelector || null;
                if (componentName && componentNameDetails) {
                    componentName += " - " + componentNameDetails;
                } else {
                    componentName = componentName || componentNameDetails;
                }

                var appViewAttributes = {
                    "component_index": appViewInfo.index,
                    "component_name": componentName,
                    "component_modelIndex": componentModelInfo? componentModelInfo.index : null,
                    "component_collectionIndex": componentCollectionInfo? componentCollectionInfo.index : null,
                    "component_status": componentStatus
                };
                return appViewAttributes;
            }, [this.get("component_index"), this.get("component_status")], onComplete);
        },

        // stampa l'elemento html della vista sulla console
        printElement: function() {
            backboneAgentClient.execFunction(function(componentIndex) {
                var appViewInfo = this.getAppComponentInfoByIndex("View", componentIndex);
                var appViewEl = appViewInfo.component.el;
                console.log(appViewEl);
            }, [this.get("component_index")], _.bind(function(result) { // on executed
                // do nothing
            }, this));
        }
    });
    return AppView;
});
<commit_msg>Safer detection of app view selector<commit_after>/* Il prefisso "component_" negli attributi del modello serve ad evitare collisioni
   (sia l'app che il panel usano Backbone) */

define(["backbone", "underscore", "models/AppComponent", "backboneAgentClient"],
function(Backbone, _, AppComponent, backboneAgentClient) {

    var AppView = AppComponent.extend({

        category: "View",

        // attributi supportati dal modello
        defaults: {
            "component_index": null, // int
            "component_name": null, // string
            "component_modelIndex": null, // int
            "component_collectionIndex": null, // int
            "component_status": "Created" // can be "Created", "Rendered" or "Removed"
        },

        // Change the component status by analyzing its "Operation" actions.
        handleAction: function(action) {
            if (action.get("type") == "Operation") {
                var operationName = action.get("name");
                if (operationName == "render") {
                    this.set("component_status", "Rendered");
                } else if (operationName == "remove") {
                    this.set("component_status", "Removed");
                }
            }
        },

        // Estrae gli attributi dalle info recuperate dall'agent.
        fetchLogic: function(onComplete) {
            backboneAgentClient.execFunction(function(componentIndex, componentStatus) {
                var appViewInfo = this.getAppComponentInfoByIndex("View", componentIndex);
                var componentModelInfo = this.getAppComponentInfo(appViewInfo.component.model);
                var componentCollectionInfo = this.getAppComponentInfo(appViewInfo.component.collection);

                var appViewComponent = appViewInfo.component;
                var appViewSelector = "";
                if (appViewComponent.el) {
                    if (typeof appViewComponent.el.id == 'string' && appViewComponent.el.id !== "") {
                        appViewSelector = "#"+appViewComponent.el.id;
                    }
                    if (typeof appViewComponent.el.className == 'string' && appViewComponent.el.className !== "") {
                        appViewSelector += "."+appViewComponent.el.className.replace(/ /g, '.');
                    }
                }
                var componentName = appViewComponent.constructor.name || null;
                var componentNameDetails = appViewSelector || null;
                if (componentName && componentNameDetails) {
                    componentName += " - " + componentNameDetails;
                } else {
                    componentName = componentName || componentNameDetails;
                }

                var appViewAttributes = {
                    "component_index": appViewInfo.index,
                    "component_name": componentName,
                    "component_modelIndex": componentModelInfo? componentModelInfo.index : null,
                    "component_collectionIndex": componentCollectionInfo? componentCollectionInfo.index : null,
                    "component_status": componentStatus
                };
                return appViewAttributes;
            }, [this.get("component_index"), this.get("component_status")], onComplete);
        },

        // stampa l'elemento html della vista sulla console
        printElement: function() {
            backboneAgentClient.execFunction(function(componentIndex) {
                var appViewInfo = this.getAppComponentInfoByIndex("View", componentIndex);
                var appViewEl = appViewInfo.component.el;
                console.log(appViewEl);
            }, [this.get("component_index")], _.bind(function(result) { // on executed
                // do nothing
            }, this));
        }
    });
    return AppView;
});
<|endoftext|>


<commit_before>var async = require('async')
var Job = require('../tools/job')
var tools = require('../tools')
var flatten = require('etcd-flatten')
var endpoints = require('./endpoints')
var env = require('../tools/env')
var logger = require('../tools/logger')

module.exports = function(config, etcd){

	function findJob(job, done){
		var self = this;
		etcd.get(tools.jobKey('proc', job), {
			recursive:true
		}, function(err, data){
			if(err){
				return done(err)
			}
			if(data){
				var nodes = (data.node.nodes || []).map(function(n){
					return JSON.parse(n.value)
				})
				data = nodes[0]
			}
			done(err, data)
		})
	}

	function getScaleJobs(job){
		var jobs = []

		var scale = job.scale || 1

		while(scale>0){
			scale--
			var scaleJob = JSON.parse(JSON.stringify(job))
			var jobObject = Job(scaleJob)
			jobObject.ensureValues()
			jobs.push(scaleJob)
		}

		return jobs
	}

	function writeScaleJobs(job, done){
		var scaleJobs = getScaleJobs(job)

		async.forEachSeries(scaleJobs, function(runJob, nextJob){
			writeJob(runJob, nextJob)
		}, function(err){
			done(err, scaleJobs)
		})
	}

	function writeJob(job, done){
		var self = this;
		var jobObject = Job(job)
		jobObject.ensureValues()

		var key = tools.jobKey('proc', job)
		logger('[schedule write] ' + job.id + ' ' + key + ' [json] ' + JSON.stringify(job))

		etcd.set(key, JSON.stringify(job), done)
	}

	function ensureJob(job, done){
		var self = this;
		findJob(job, function(err, existingjob){
			if(err){
				return done(err)
			}
			if(existingjob){
				return done(null, existingjob)
			}
			writeJob(job, done)
		})
	}

	// this is once we have allocated
	// by writing to /deploy the slave will kick in and run the job
	function runJob(job, server, done){

		var jobObject = Job(job)
		jobObject.ensureValues()

		logger('[schedule run] ' + job.id + ' [json] ' + JSON.stringify({
			job:job,
			server:server.name
		}))

		async.series([
			function(next){
				etcd.set('/run' + jobObject.key(), server.name, next)
			},

			function(next){
				etcd.set('/deploy/' + server.name + jobObject.key(), '', next)
			}
		], done)

	}

	function writeEndpoint(job, opts, done){

		logger('[schedule endpoint] ' + job.id)// + ' [json] ' + JSON.stringify(opts))

		endpoints.writeEndpoint(etcd, job, opts, done)

	}

	function writeDockerEndpoint(settings, done){

		logger('[schedule docker endpoint]')//' [json] ' + JSON.stringify(settings))

		endpoints.writeDockerEndpoint(etcd, settings, done)

	}

	function getJobServer(job, done){
		var jobObject = Job(job)

		etcd.get('/run' + jobObject.key(), function(err, result){
			if(err) return done(err)
			if(!result) return done()
			done(null, result.node.value)
		})
	}

	function getJobState(job, done){
		var self = this
		var jobObject = Job(job)

		getJobServer(job, function(err, server){
			if(err) return done(err)

			async.parallel({
				server:function(next){
					etcd.get('/deploy/' + server + jobObject.key(), next)
				},
				ports:function(next){
					etcd.get('/ports' + jobObject.key(), {
						recursive:true
					}, function(err, results){
						if(err) return next(err)
						if(!results) return next()
						var ports = flatten(results.node)
						next(null, ports)
					})
				}
			}, function(err, data){
				if(err) return done(err)
				var state = {
					job:job,
					hostname:server,
					server:data.server,
					ports:data.ports
				}
				done(null, state)
			})

		})
	}

	function loadJobByPath(path, done){
		etcd.get('/proc/' + path, function(err, result){
			if(err || !result){
				return done(err || 'no result found')
			}
			done(null, JSON.parse(result.node.value))
		})
	}

	function loadJob(job, done){
		if(typeof(job)=='string'){
			job = job.replace(/-/g, '/')
			loadJobByPath(job, done)
			return
		}
		var jobObject = Job(job)
		etcd.get('/proc/' + jobObject.key(), function(err, result){
			if(err || !result){
				return done(err || 'no result found')
			}
			done(null, JSON.parse(result.node.value))
		})
	}

	function removeJob(opts, done){

		var self = this;
		opts = opts || {}

		var job = opts.job
		var jobObject = Job(job)

		logger('[remove job] ' + jobObject.key() + ' [json] ' + JSON.stringify(opts))

		getJobServer(job, function(err, hostname){
			if(err) return done(err)

			if(!hostname){
				logger.error('no hostname loaded for job destroy: ' + job.id)
				console.log('-------------------------------------------');
				console.log('error no hostname')
				process.exit(1)
			}

			var keys = [
				'/run' + jobObject.key(),
				'/ports' + jobObject.key(),
				//'/log' + jobObject.key(),
				'/container' + jobObject.key()
			]

			if(hostname){
				keys.push('/deploy/' + hostname + jobObject.key())
			}

			if(opts.removeServer){
				keys.push('/fixed' + jobObject.key())
			}

			if(opts.removeProc){
				keys.push('/proc' + jobObject.key())
			}

			async.parallel({
				ports:function(next){
					etcd.get('/ports' + jobObject.key(), function(err, portData){
						if(err) return next(err)
						if(!portData) return next()
						var ports = tools.flattenResult(portData.node)
						next(err, ports)
					})
				},
				jobInfo:function(next){
					etcd.get('/proc' + jobObject.key(), function(err, data){
						if(err){
							return next(err)
						}
						if(!data){
							return next('no data')
						}
						if(data.dir){
							return next('data is a directory')
						}
						var job = data.node.value
						next(null, job)
					})
				}
			}, function(err, data){

				Object.keys(data.ports || {}).forEach(function(key){
					// add the port key for deletion
					if(key.indexOf(jobObject.key())>=0){
						keys.push(key)
					}
				})

				async.forEach(keys, function(key, nextKey){
					console.log('[remove key] ' + key)
					etcd.del(key, {
						recursive:true
					}, nextKey)
				}, function(){
					if(err) return done(err)
					if(opts.failed){
						etcd.set('/failed' + jobObject.key(), job, done)
					}
					else{
						done()
					}

				})
			})
		})
	}

	function getPIDS(job, done){

		var key = '/proc/' + job.stack + '/' + job.tag + '/' + job.name

		etcd.get('/proc/' + job.stack + '/' + job.tag + '/' + job.name, {
			recursive:true
		}, function(err, results){

			if(err) return done(err)
			results = flatten(results.node)

			var pids = Object.keys(results || {}).map(function(key){
				var parts = key.split('/')
				return parts.pop()
			})

			done(null, pids)
		})
	}

	return {
		ensureJob:ensureJob,
		findJob:findJob,
		writeJob:writeJob,
		writeScaleJobs:writeScaleJobs,
		getScaleJobs:getScaleJobs,
		runJob:runJob,
		writeEndpoint:writeEndpoint,
		writeDockerEndpoint:writeDockerEndpoint,
		getJobServer:getJobServer,
		getJobState:getJobState,
		loadJobByPath:loadJobByPath,
		loadJob:loadJob,
		removeJob:removeJob,
		getPIDS:getPIDS
	}
}
<commit_msg>remove ports with ip from keyspace<commit_after>var async = require('async')
var Job = require('../tools/job')
var tools = require('../tools')
var flatten = require('etcd-flatten')
var endpoints = require('./endpoints')
var env = require('../tools/env')
var logger = require('../tools/logger')

module.exports = function(config, etcd){

	function findJob(job, done){
		var self = this;
		etcd.get(tools.jobKey('proc', job), {
			recursive:true
		}, function(err, data){
			if(err){
				return done(err)
			}
			if(data){
				var nodes = (data.node.nodes || []).map(function(n){
					return JSON.parse(n.value)
				})
				data = nodes[0]
			}
			done(err, data)
		})
	}

	function getScaleJobs(job){
		var jobs = []

		var scale = job.scale || 1

		while(scale>0){
			scale--
			var scaleJob = JSON.parse(JSON.stringify(job))
			var jobObject = Job(scaleJob)
			jobObject.ensureValues()
			jobs.push(scaleJob)
		}

		return jobs
	}

	function writeScaleJobs(job, done){
		var scaleJobs = getScaleJobs(job)

		async.forEachSeries(scaleJobs, function(runJob, nextJob){
			writeJob(runJob, nextJob)
		}, function(err){
			done(err, scaleJobs)
		})
	}

	function writeJob(job, done){
		var self = this;
		var jobObject = Job(job)
		jobObject.ensureValues()

		var key = tools.jobKey('proc', job)
		logger('[schedule write] ' + job.id + ' ' + key + ' [json] ' + JSON.stringify(job))

		etcd.set(key, JSON.stringify(job), done)
	}

	function ensureJob(job, done){
		var self = this;
		findJob(job, function(err, existingjob){
			if(err){
				return done(err)
			}
			if(existingjob){
				return done(null, existingjob)
			}
			writeJob(job, done)
		})
	}

	// this is once we have allocated
	// by writing to /deploy the slave will kick in and run the job
	function runJob(job, server, done){

		var jobObject = Job(job)
		jobObject.ensureValues()

		logger('[schedule run] ' + job.id + ' [json] ' + JSON.stringify({
			job:job,
			server:server.name
		}))

		async.series([
			function(next){
				etcd.set('/run' + jobObject.key(), server.name, next)
			},

			function(next){
				etcd.set('/deploy/' + server.name + jobObject.key(), '', next)
			}
		], done)

	}

	function writeEndpoint(job, opts, done){

		logger('[schedule endpoint] ' + job.id)// + ' [json] ' + JSON.stringify(opts))

		endpoints.writeEndpoint(etcd, job, opts, done)

	}

	function writeDockerEndpoint(settings, done){

		logger('[schedule docker endpoint]')//' [json] ' + JSON.stringify(settings))

		endpoints.writeDockerEndpoint(etcd, settings, done)

	}

	function getJobServer(job, done){
		var jobObject = Job(job)

		etcd.get('/run' + jobObject.key(), function(err, result){
			if(err) return done(err)
			if(!result) return done()
			done(null, result.node.value)
		})
	}

	function getJobState(job, done){
		var self = this
		var jobObject = Job(job)

		getJobServer(job, function(err, server){
			if(err) return done(err)

			async.parallel({
				server:function(next){
					etcd.get('/deploy/' + server + jobObject.key(), next)
				},
				ports:function(next){
					etcd.get('/ports' + jobObject.key(), {
						recursive:true
					}, function(err, results){
						if(err) return next(err)
						if(!results) return next()
						var ports = flatten(results.node)
						next(null, ports)
					})
				}
			}, function(err, data){
				if(err) return done(err)
				var state = {
					job:job,
					hostname:server,
					server:data.server,
					ports:data.ports
				}
				done(null, state)
			})

		})
	}

	function loadJobByPath(path, done){
		etcd.get('/proc/' + path, function(err, result){
			if(err || !result){
				return done(err || 'no result found')
			}
			done(null, JSON.parse(result.node.value))
		})
	}

	function loadJob(job, done){
		if(typeof(job)=='string'){
			job = job.replace(/-/g, '/')
			loadJobByPath(job, done)
			return
		}
		var jobObject = Job(job)
		etcd.get('/proc/' + jobObject.key(), function(err, result){
			if(err || !result){
				return done(err || 'no result found')
			}
			done(null, JSON.parse(result.node.value))
		})
	}

	function removeJob(opts, done){

		var self = this;
		opts = opts || {}

		var job = opts.job
		var jobObject = Job(job)

		logger('[remove job] ' + jobObject.key() + ' [json] ' + JSON.stringify(opts))

		getJobServer(job, function(err, hostname){
			if(err) return done(err)

			if(!hostname){
				logger.error('no hostname loaded for job destroy: ' + job.id)
				console.log('-------------------------------------------');
				console.log('error no hostname')
				process.exit(1)
			}

			var keys = [
				'/run' + jobObject.key(),
				'/ports' + jobObject.key(),
				//'/log' + jobObject.key(),
				'/container' + jobObject.key()
			]

			if(hostname){
				keys.push('/deploy/' + hostname + jobObject.key())
			}

			if(opts.removeServer){
				keys.push('/fixed' + jobObject.key())
			}

			if(opts.removeProc){
				keys.push('/proc' + jobObject.key())
			}

			async.parallel({
				ports:function(next){
					etcd.get('/ports' + jobObject.key(), function(err, portData){
						if(err) return next(err)
						if(!portData) return next()
						var ports = tools.flattenResult(portData.node)
						next(err, ports)
					})
				},
				jobInfo:function(next){
					etcd.get('/proc' + jobObject.key(), function(err, data){
						if(err){
							return next(err)
						}
						if(!data){
							return next('no data')
						}
						if(data.dir){
							return next('data is a directory')
						}
						var job = data.node.value
						next(null, job)
					})
				}
			}, function(err, data){

				Object.keys(data.ports || {}).forEach(function(key){
					// add the port key for deletion
					if(key.indexOf(jobObject.key())>=0){
						var portParts = key.split('/')
						portParts.pop()
						key = portParts.join('/')
						keys.push(key)
					}
				})

				async.forEach(keys, function(key, nextKey){
					console.log('[remove key] ' + key)
					etcd.del(key, {
						recursive:true
					}, nextKey)
				}, function(){
					if(err) return done(err)
					if(opts.failed){
						etcd.set('/failed' + jobObject.key(), job, done)
					}
					else{
						done()
					}

				})
			})
		})
	}

	function getPIDS(job, done){

		var key = '/proc/' + job.stack + '/' + job.tag + '/' + job.name

		etcd.get('/proc/' + job.stack + '/' + job.tag + '/' + job.name, {
			recursive:true
		}, function(err, results){

			if(err) return done(err)
			results = flatten(results.node)

			var pids = Object.keys(results || {}).map(function(key){
				var parts = key.split('/')
				return parts.pop()
			})

			done(null, pids)
		})
	}

	return {
		ensureJob:ensureJob,
		findJob:findJob,
		writeJob:writeJob,
		writeScaleJobs:writeScaleJobs,
		getScaleJobs:getScaleJobs,
		runJob:runJob,
		writeEndpoint:writeEndpoint,
		writeDockerEndpoint:writeDockerEndpoint,
		getJobServer:getJobServer,
		getJobState:getJobState,
		loadJobByPath:loadJobByPath,
		loadJob:loadJob,
		removeJob:removeJob,
		getPIDS:getPIDS
	}
}
<|endoftext|>


<commit_before>import postcss from 'postcss';
import matchHelper from 'posthtml-match-helper';
import { extendStyle, sortCssNodesBySpecificity, getCssFromStyleTags } from './helpers';

export default css => {
    return function inlineCss(tree) {
        if (!css || !Object.keys(css).length) {
            css = getCssFromStyleTags(tree);
        }

        var postcssObj = css.then ? css : postcss().process(css);
        return postcssObj
            .then(result => sortCssNodesBySpecificity(result.root.nodes))
            .then(cssNodes => {
                cssNodes.forEach(cssNode => {
                    tree.match(matchHelper(cssNode.selector), htmlNode => {
                        return extendStyle(htmlNode, cssNode);
                    });
                });
            });
    };
};
<commit_msg>fix(inlineCss): fix condition for node 0.12<commit_after>import postcss from 'postcss';
import matchHelper from 'posthtml-match-helper';
import { extendStyle, sortCssNodesBySpecificity, getCssFromStyleTags } from './helpers';

export default css => {
    return function inlineCss(tree) {
        if (!css || (typeof css !== 'string' && !Object.keys(css).length)) {
            css = getCssFromStyleTags(tree);
        }

        var postcssObj = css.then ? css : postcss().process(css);
        return postcssObj
            .then(result => sortCssNodesBySpecificity(result.root.nodes))
            .then(cssNodes => {
                cssNodes.forEach(cssNode => {
                    tree.match(matchHelper(cssNode.selector), htmlNode => {
                        return extendStyle(htmlNode, cssNode);
                    });
                });
            });
    };
};
<|endoftext|>


<commit_before>var fs = require('fs'),
    path = require('path'),
    shelljs = require('shelljs'),
    os = require('os'),
    argv = require('optimist').argv,
    IonicProject = require('./project'),
    Task = require('./task').Task,
    IonicStats = require('./stats').IonicStats,
    semver = require('semver');

var requirements = {
  node: '>=0.10.33',
  cordova: '>=4.2.0'
}

var IonicTask = function() {};

IonicTask.prototype = new Task();

// http://en.wikipedia.org/wiki/Darwin_%28operating_system%29#Release_history
IonicTask.prototype.getMacInfo = function() {
  //Need to get:
  //Look up for what version (Yosemite, Mavericks, Mountain Lion)
  //What version of Xcode
  var macVersion = 'Yosemite';
  switch(os.release()) {
    case '14.0.0':
      macVersion = 'Yosemite';
      break;
    case '13.0.0':
    case '13.1.0':
    case '13.2.0':
    case '13.3.0':
    case '13.4.0':
      macVersion = 'Mavericks';
      break;
    case '12.0.0':
    case '12.5.0':
      macVersion = 'Mountain Lion';
      break;
    case '11.4.2':
      macVersion = 'Lion';
      break;
    case '10.8':
      macVersion = 'Snow Leopard';
      break;
  }

  return 'Mac OS X ' + macVersion;
  // console.log('Mac OS X', macVersion);
}

IonicTask.prototype.getCordovaInfo = function(info) {
  var command = 'cordova -v';
  var result = shelljs.exec(command, { silent: true });
  if(result.code != 0) {
    info.cordova = 'Not installed';
    return;
  }

  info.cordova = result.output.replace('\n', '');
}

IonicTask.prototype.getXcodeInfo = function() {
  var result = shelljs.exec('/usr/bin/xcodebuild -version', { silent: true });
  if(result.code != 0) {
    return 'Not installed';
  }
  var version = result.output.replace(/\n/g, ' ')
  return version;
}

IonicTask.prototype.getIosSimInfo = function() {
  var result = shelljs.exec('ios-sim --version', { silent: true });
  if(result.code != 0) {
    return 'Not installed';
  }
  var version = result.output.replace(/\n/g, ' ')
  return version;
}

IonicTask.prototype.getIosDeployInfo = function() {
  var result = shelljs.exec('ios-deploy --version', { silent: true });
  if(result.code != 0) {
    return 'Not installed';
  }
  var version = result.output.replace(/\n/g, ' ')
  return version;
}

IonicTask.prototype.getIonicVersions = function(info) {
  var ionicCliVersion = require('../../package.json').version;

  info.ionic_cli = ionicCliVersion;

  try {
    var ionicVersionFile = require(path.resolve('www/lib/ionic/version.json'));
    var ionicVersion = ionicVersionFile.version;

    info.ionic = ionicVersion;
  } catch (ex) {}

}

// Windows XP  5.1.2600
// Windows Server 2003 5.2.3790
// Windows Vista
// Windows Server 2008 6.0.6000
// Windows Vista, SP2  6.0.6002
// Windows 7
// Windows Server 2008 R2  6.1.7600
// Windows 7 SP1
// Windows Server 2008 R2 SP1  6.1.7601
// Windows 8
// Windows Server 2012 6.2.9200
// Windows 8.1
// Windows Server 2012 R2  6.3.9600
// Windows 10 Technical Preview  6.4.9841

IonicTask.prototype.getWindowsEnvironmentInfo = function() {
  // Windows version reference
  // http://en.wikipedia.org/wiki/Ver_%28command%29
  var version = os.release();
  var windowsVersion = null;
  switch(version) {
    case '5.1.2600':
      windowsVersion = 'Windows XP';
      break;
    case '6.0.6000':
      windowsVersion = 'Windows Vista';
      break;
    case '6.0.6002':
      windowsVersion = 'Windows Vista SP2';
      break;
    case '6.1.7600':
      windowsVersion = 'Windows 7';
      break;
    case '6.1.7601':
      windowsVersion = 'Windows 7 SP1';
      break;
    case '6.2.9200':
      windowsVersion = 'Windows 8';
      break;
    case '6.3.9600':
      windowsVersion = 'Windows 8.1';
      break;
  }

  return windowsVersion;
}

IonicTask.prototype.getLinuxEnvironmentInfo = function() {
  var result = shelljs.exec('lsb_release -id', { silent: true });
  return result.output.replace(/\n/g, ' ')
}

//http://stackoverflow.com/questions/6551006/get-my-os-from-the-node-js-shell
IonicTask.prototype.getOsEnvironment = function(info) {
  var self = this;

  switch(os.type()) {
    case 'Darwin':
      info.os = self.getMacInfo();
      info.xcode = self.getXcodeInfo();
      info.ios_sim = self.getIosSimInfo();
      info.ios_deploy = self.getIosDeployInfo();
      break;
    case 'Windows_NT':
      info.os = self.getWindowsEnvironmentInfo();
      break;
    case 'Linux':
      info.os = self.getLinuxEnvironmentInfo();
      break;
  }
}

IonicTask.prototype.getNodeVersion = function(info) {
  var command = 'node -v';
  var result = shelljs.exec(command, { silent: true } );
  info.node = result.output.replace('\n','');
}

IonicTask.prototype.gatherInfo = function() {
  var self = this;
  var info = {};
  //For macs we want:
  //Mac version, xcode version (if installed)

  //For windows
  //Windows version

  //For all
  // Android SDK info
  // Cordova CLI info
  // Ionic CLI version
  // Ionic version

  // var info = {
  //   cordova: 'CLI v3.5.0',
  //   os: 'Mac OSX Yosemite',
  //   xcode: 'Xcode 6.1.1',
  //   ionic: '1.0.0-beta.13',
  //   ionic_cli: '1.3.0'
  // };

  self.getIonicVersions(info);

  self.getNodeVersion(info);

  self.getOsEnvironment(info);

  self.getCordovaInfo(info);

  // self.printJavaInformation();
  return info;
}

IonicTask.prototype.printInfo = function(info) {
  console.log('\nYour system information:\n');
  console.log('OS:', info.os);
  console.log('Node Version:', info.node);
  console.log('Cordova CLI:', info.cordova);
  if (info.ionic) {
    console.log('Ionic Version:', info.ionic);
  }
  console.log('Ionic CLI Version:', info.ionic_cli);
  if(info.xcode) {
    console.log('Xcode version:', info.xcode);
  }

  if(info.ios_sim) {
    console.log('ios-sim version:', info.ios_sim);
  }
  if(info.ios_deploy) {
    console.log('ios-deploy version:', info.ios_deploy);
  }

  console.log('\n');
}

IonicTask.prototype.checkRuntime = function checkRuntime() {
  var info = this.gatherInfo();
  var validRuntime = true;

  if(!semver.satisfies(info.node, requirements.node)) {
    var updateMessage = ['Please update your Node runtime to version >=', requirements.node].join(' ');
    console.log(updateMessage.red.bold);
    validRuntime = false;
  }

  if(!semver.satisfies(info.cordova, requirements.cordova)) {
    var updateMessage = ['Please update your Cordova CLI to version >=', requirements.cordova, '`npm install -g cordova`'].join(' ')
    console.log(updateMessage.red.bold);
    validRuntime = false;
  }

  return validRuntime;
}

IonicTask.prototype.run = function(ionic) {

  var info = this.gatherInfo();
  this.ionic = ionic;
  this.printInfo(info);

  this.checkRuntime();

  IonicStats.t();
}

exports.IonicTask = IonicTask;
<commit_msg>Adding in try/catch - invalid semver version scaning with '-dev' in them will break semver. Recovering gracefully<commit_after>var fs = require('fs'),
    path = require('path'),
    shelljs = require('shelljs'),
    os = require('os'),
    argv = require('optimist').argv,
    IonicProject = require('./project'),
    Task = require('./task').Task,
    IonicStats = require('./stats').IonicStats,
    semver = require('semver');

var requirements = {
  node: '>=0.10.33',
  cordova: '>=4.2.0'
}

var IonicTask = function() {};

IonicTask.prototype = new Task();

// http://en.wikipedia.org/wiki/Darwin_%28operating_system%29#Release_history
IonicTask.prototype.getMacInfo = function() {
  //Need to get:
  //Look up for what version (Yosemite, Mavericks, Mountain Lion)
  //What version of Xcode
  var macVersion = 'Yosemite';
  switch(os.release()) {
    case '14.0.0':
      macVersion = 'Yosemite';
      break;
    case '13.0.0':
    case '13.1.0':
    case '13.2.0':
    case '13.3.0':
    case '13.4.0':
      macVersion = 'Mavericks';
      break;
    case '12.0.0':
    case '12.5.0':
      macVersion = 'Mountain Lion';
      break;
    case '11.4.2':
      macVersion = 'Lion';
      break;
    case '10.8':
      macVersion = 'Snow Leopard';
      break;
  }

  return 'Mac OS X ' + macVersion;
  // console.log('Mac OS X', macVersion);
}

IonicTask.prototype.getCordovaInfo = function(info) {
  var command = 'cordova -v';
  var result = shelljs.exec(command, { silent: true });
  if(result.code != 0) {
    info.cordova = 'Not installed';
    return;
  }

  info.cordova = result.output.replace('\n', '');
}

IonicTask.prototype.getXcodeInfo = function() {
  var result = shelljs.exec('/usr/bin/xcodebuild -version', { silent: true });
  if(result.code != 0) {
    return 'Not installed';
  }
  var version = result.output.replace(/\n/g, ' ')
  return version;
}

IonicTask.prototype.getIosSimInfo = function() {
  var result = shelljs.exec('ios-sim --version', { silent: true });
  if(result.code != 0) {
    return 'Not installed';
  }
  var version = result.output.replace(/\n/g, ' ')
  return version;
}

IonicTask.prototype.getIosDeployInfo = function() {
  var result = shelljs.exec('ios-deploy --version', { silent: true });
  if(result.code != 0) {
    return 'Not installed';
  }
  var version = result.output.replace(/\n/g, ' ')
  return version;
}

IonicTask.prototype.getIonicVersions = function(info) {
  var ionicCliVersion = require('../../package.json').version;

  info.ionic_cli = ionicCliVersion;

  try {
    var ionicVersionFile = require(path.resolve('www/lib/ionic/version.json'));
    var ionicVersion = ionicVersionFile.version;

    info.ionic = ionicVersion;
  } catch (ex) {}

}

// Windows XP  5.1.2600
// Windows Server 2003 5.2.3790
// Windows Vista
// Windows Server 2008 6.0.6000
// Windows Vista, SP2  6.0.6002
// Windows 7
// Windows Server 2008 R2  6.1.7600
// Windows 7 SP1
// Windows Server 2008 R2 SP1  6.1.7601
// Windows 8
// Windows Server 2012 6.2.9200
// Windows 8.1
// Windows Server 2012 R2  6.3.9600
// Windows 10 Technical Preview  6.4.9841

IonicTask.prototype.getWindowsEnvironmentInfo = function() {
  // Windows version reference
  // http://en.wikipedia.org/wiki/Ver_%28command%29
  var version = os.release();
  var windowsVersion = null;
  switch(version) {
    case '5.1.2600':
      windowsVersion = 'Windows XP';
      break;
    case '6.0.6000':
      windowsVersion = 'Windows Vista';
      break;
    case '6.0.6002':
      windowsVersion = 'Windows Vista SP2';
      break;
    case '6.1.7600':
      windowsVersion = 'Windows 7';
      break;
    case '6.1.7601':
      windowsVersion = 'Windows 7 SP1';
      break;
    case '6.2.9200':
      windowsVersion = 'Windows 8';
      break;
    case '6.3.9600':
      windowsVersion = 'Windows 8.1';
      break;
  }

  return windowsVersion;
}

IonicTask.prototype.getLinuxEnvironmentInfo = function() {
  var result = shelljs.exec('lsb_release -id', { silent: true });
  return result.output.replace(/\n/g, ' ')
}

//http://stackoverflow.com/questions/6551006/get-my-os-from-the-node-js-shell
IonicTask.prototype.getOsEnvironment = function(info) {
  var self = this;

  switch(os.type()) {
    case 'Darwin':
      info.os = self.getMacInfo();
      info.xcode = self.getXcodeInfo();
      info.ios_sim = self.getIosSimInfo();
      info.ios_deploy = self.getIosDeployInfo();
      break;
    case 'Windows_NT':
      info.os = self.getWindowsEnvironmentInfo();
      break;
    case 'Linux':
      info.os = self.getLinuxEnvironmentInfo();
      break;
  }
}

IonicTask.prototype.getNodeVersion = function(info) {
  var command = 'node -v';
  var result = shelljs.exec(command, { silent: true } );
  info.node = result.output.replace('\n','');
}

IonicTask.prototype.gatherInfo = function() {
  var self = this;
  var info = {};
  //For macs we want:
  //Mac version, xcode version (if installed)

  //For windows
  //Windows version

  //For all
  // Android SDK info
  // Cordova CLI info
  // Ionic CLI version
  // Ionic version

  // var info = {
  //   cordova: 'CLI v3.5.0',
  //   os: 'Mac OSX Yosemite',
  //   xcode: 'Xcode 6.1.1',
  //   ionic: '1.0.0-beta.13',
  //   ionic_cli: '1.3.0'
  // };

  self.getIonicVersions(info);

  self.getNodeVersion(info);

  self.getOsEnvironment(info);

  self.getCordovaInfo(info);

  // self.printJavaInformation();
  return info;
}

IonicTask.prototype.printInfo = function(info) {
  console.log('\nYour system information:\n');
  console.log('OS:', info.os);
  console.log('Node Version:', info.node);
  console.log('Cordova CLI:', info.cordova);
  if (info.ionic) {
    console.log('Ionic Version:', info.ionic);
  }
  console.log('Ionic CLI Version:', info.ionic_cli);
  if(info.xcode) {
    console.log('Xcode version:', info.xcode);
  }

  if(info.ios_sim) {
    console.log('ios-sim version:', info.ios_sim);
  }
  if(info.ios_deploy) {
    console.log('ios-deploy version:', info.ios_deploy);
  }

  console.log('\n');
}

IonicTask.prototype.checkRuntime = function checkRuntime() {
  var info = this.gatherInfo();
  var validRuntime = true;

  try {

    if(!semver.satisfies(info.node, requirements.node)) {
      var updateMessage = ['Please update your Node runtime to version >=', requirements.node].join(' ');
      console.log(updateMessage.red.bold);
      validRuntime = false;
    }

    if(!semver.satisfies(info.cordova, requirements.cordova)) {
      var updateMessage = ['Please update your Cordova CLI to version >=', requirements.cordova, '`npm install -g cordova`'].join(' ')
      console.log(updateMessage.red.bold);
      validRuntime = false;
    }
  } catch(ex) {
    console.log('There was an error checking your runtime environment: ', ex)
  }

  return validRuntime;
}

IonicTask.prototype.run = function(ionic) {

  var info = this.gatherInfo();
  this.ionic = ionic;
  this.printInfo(info);

  this.checkRuntime();

  IonicStats.t();
}

exports.IonicTask = IonicTask;
<|endoftext|>


<commit_before>var irc = require('irc'),
    _ = require('underscore');

var IRCActor = function(actorConfig, globalConfig){
    return {
        id: actorConfig.id,
        onStage: false,
        setup: function(clb){
            console.log(new Date().toString(), 'actor::setup', actorConfig.nickName);
            this.client = new irc.Client(globalConfig.irc.server, actorConfig.nickName, {
                userName: actorConfig.id,
                realName: actorConfig.name,
                port: 6667,
                debug: false,
                showErrors: false,
                autoRejoin: true,
                autoConnect: true,
                secure: false
            });
            this.client.addListener('connect', clb);
        },
        enter: function(clb) {
            console.log(new Date().toString(), "actor::enter", actorConfig.id, globalConfig.irc.channel);
            var that = this;
            if (this.onStage) {
                clb();
            } else {
                console.log(new Date().toString(), 'irc::join', actorConfig.id, globalConfig.irc.channel);
                this.client.join(globalConfig.irc.channel, function(){
                    that.onStage = true;
                    clb();
                });
            }
        },
        speak: function(statement, clb) {
            console.log(new Date().toString(), "actor::speak", actorConfig.id);
            var that = this;
            if (!this.onStage){
                this.enter(function(){
                    that.speak(statement, clb);
                });
            }
            console.log(new Date().toString(), "irc::say", actorConfig.id, globalConfig.irc.channel, statement.line);
            this.client.say(globalConfig.irc.channel, statement.line);
            var timeout = statement.line.split(' ').length * 600 + 1000;
            setTimeout(clb, timeout);
        },
        exit: function(clb){
            console.log(new Date().toString(), 'actor::exit', actorConfig.id);
            var that = this;
            if (!this.onStage) {
                clb();
            } else {
                console.log(new Date().toString(), 'irc::part', globalConfig.irc.channel);
                this.client.part(globalConfig.irc.channel, function() {
                    that.onStage = false;
                    clb();
                });
            }
        }
    };
};

exports.getTheater = function(){
    return {
        setup: function(config, clb){
            console.log(new Date().toString(), 'theater::setup');
            var that = this;
            this.actors = {};
            this.config = config;
            this.director =  new irc.Client(config.irc.server, config.prefix + "director", {
                userName: 'nodeshakespearebot',
                realName: 'Director',
                port: 6667,
                debug: false,
                showErrors: false,
                autoRejoin: true,
                autoConnect: true,
                secure: false
            });
            this.director.addListener('connect', function() {
                that.director.join(that.config.irc.channel, function() {
                    var cb = _.after(config.actors.length, clb);
                    config.actors.forEach(function(actor) {
                        that.actors[actor.id] = IRCActor(actor, config);
                        that.actors[actor.id].setup(cb);
                    });
                });
            });
        },
        run: function(skript) {
            console.log(new Date().toString(), 'theater::run');
            var current = 0, that = this, lastActor;
            that.director.addListener("message" + this.config.irc.channel, function(from, message){
                console.log(new Date().toString(), 'director got:', message, 'from:', from);
            });
            // should be called executeAndNextAndNextAndNext..
            var executeNext = function() {
                console.log(new Date().toString(), 'theater::run::executeNext', current);
                if (!_.isUndefined(skript[current])) {
                    that.execute(skript[current], function() {
                        current += 1;
                        executeNext();
                    });
                } else {
                    that.tearDown();
                }
            };
            executeNext();
        },
        execute: function(statement, clb) {
            console.log(new Date().toString(), 'theater::execute', statement);
            if (_.isFunction(this[statement.action])) {
                this[statement.action](statement, clb);
            }
        },
        defaultPauseDuration: 2000,
        announcement: function(data, clb){
            this.director.say(this.config.irc.channel, data.content);
            setTimeout(clb, defaultPauseDuration);
        },
        pause: function(data, clb) {
            setTimeout(clb, data.duration || defaultPauseDuration)
        },
        forActorsDo: function(actorsIds, action, clb) {
            var that = this,
                cb = _.after(actorsIds.length, clb);
            actorsIds.forEach(function(id) {
                that.actors[id][action](cb);
            });
        },
        enter: function(data, clb) {
            this.forActorsDo(data.actors, "enter", clb);
        },
        speak: function(data, clb) {
            this.actors[data.actor].speak(data, clb);
        },
        exit: function(data, clb) {
            this.forActorsDo(data.actors, "exit", clb);
        },
        tearDown: function() {
            console.log(new Date().toString(), 'theater::teardown');
            _(this.actors).chain()
                .values()
                .filter(function(actor) { return actor.onStage; })
                .each(function(actor) { actor.exit(function(){}); })
        }
    };
};
<commit_msg>catch socket not writable, todo: fix it<commit_after>var irc = require('irc'),
    _ = require('underscore');

var IRCActor = function(actorConfig, globalConfig){
    return {
        id: actorConfig.id,
        onStage: false,
        setup: function(clb){
            console.log(new Date().toString(), 'actor::setup', actorConfig.nickName);
            this.client = new irc.Client(globalConfig.irc.server, actorConfig.nickName, {
                userName: actorConfig.id,
                realName: actorConfig.name,
                port: 6667,
                debug: false,
                showErrors: false,
                autoRejoin: true,
                autoConnect: true,
                secure: false
            });
            this.client.addListener('connect', clb);
        },
        enter: function(clb) {
            console.log(new Date().toString(), "actor::enter", actorConfig.id, globalConfig.irc.channel);
            var that = this;
            if (this.onStage) {
                clb();
            } else {
                console.log(new Date().toString(), 'irc::join', actorConfig.id, globalConfig.irc.channel);
                this.client.join(globalConfig.irc.channel, function(){
                    that.onStage = true;
                    clb();
                });
            }
        },
        speak: function(statement, clb) {
            console.log(new Date().toString(), "actor::speak", actorConfig.id);
            var that = this;
            if (!this.onStage){
                this.enter(function(){
                    that.speak(statement, clb);
                });
            }
            console.log(new Date().toString(), "irc::say", actorConfig.id, globalConfig.irc.channel, statement.line);
            try{
                this.client.say(globalConfig.irc.channel, statement.line);
            } catch(err){
                // Catch Socket not writable
                // FIXME
            }
            var timeout = statement.line.split(' ').length * 600 + 1000;
            setTimeout(clb, timeout);
        },
        exit: function(clb){
            console.log(new Date().toString(), 'actor::exit', actorConfig.id);
            var that = this;
            if (!this.onStage) {
                clb();
            } else {
                console.log(new Date().toString(), 'irc::part', globalConfig.irc.channel);
                this.client.part(globalConfig.irc.channel, function() {
                    that.onStage = false;
                    clb();
                });
            }
        }
    };
};

exports.getTheater = function(){
    return {
        setup: function(config, clb){
            console.log(new Date().toString(), 'theater::setup');
            var that = this;
            this.actors = {};
            this.config = config;
            this.director =  new irc.Client(config.irc.server, config.prefix + "director", {
                userName: 'nodeshakespearebot',
                realName: 'Director',
                port: 6667,
                debug: false,
                showErrors: false,
                autoRejoin: true,
                autoConnect: true,
                secure: false
            });
            this.director.addListener('connect', function() {
                that.director.join(that.config.irc.channel, function() {
                    var cb = _.after(config.actors.length, clb);
                    config.actors.forEach(function(actor) {
                        that.actors[actor.id] = IRCActor(actor, config);
                        that.actors[actor.id].setup(cb);
                    });
                });
            });
        },
        run: function(skript) {
            console.log(new Date().toString(), 'theater::run');
            var current = 0, that = this, lastActor;
            that.director.addListener("message" + this.config.irc.channel, function(from, message){
                console.log(new Date().toString(), 'director got:', message, 'from:', from);
            });
            // should be called executeAndNextAndNextAndNext..
            var executeNext = function() {
                console.log(new Date().toString(), 'theater::run::executeNext', current);
                if (!_.isUndefined(skript[current])) {
                    that.execute(skript[current], function() {
                        current += 1;
                        executeNext();
                    });
                } else {
                    that.tearDown();
                }
            };
            executeNext();
        },
        execute: function(statement, clb) {
            console.log(new Date().toString(), 'theater::execute', statement);
            if (_.isFunction(this[statement.action])) {
                this[statement.action](statement, clb);
            }
        },
        defaultPauseDuration: 2000,
        announcement: function(data, clb){
            this.director.say(this.config.irc.channel, data.content);
            setTimeout(clb, defaultPauseDuration);
        },
        pause: function(data, clb) {
            setTimeout(clb, data.duration || defaultPauseDuration)
        },
        forActorsDo: function(actorsIds, action, clb) {
            var that = this,
                cb = _.after(actorsIds.length, clb);
            actorsIds.forEach(function(id) {
                that.actors[id][action](cb);
            });
        },
        enter: function(data, clb) {
            this.forActorsDo(data.actors, "enter", clb);
        },
        speak: function(data, clb) {
            this.actors[data.actor].speak(data, clb);
        },
        exit: function(data, clb) {
            this.forActorsDo(data.actors, "exit", clb);
        },
        tearDown: function() {
            console.log(new Date().toString(), 'theater::teardown');
            _(this.actors).chain()
                .values()
                .filter(function(actor) { return actor.onStage; })
                .each(function(actor) { actor.exit(function(){}); })
        }
    };
};
<|endoftext|>


<commit_before>// Load in dependencies
var extend = require('obj-extend');

// Define a set of constants
exports.DECLARED_YES = true;
exports.DECLARED_UNKNOWN = 'unknown';
exports.DECLARED_NO = false;

// Define a set of defaults
var defaults = {
  // Summary
  declared: exports.DECLARED_NO, // false

  // Scope level
  topLevel: false,
  'with': false,

  // VariableDeclaration
  'var': false,
  'let': false,
  'const': false,

  // Function
  'function': false,

  // Try/catch
  'catch': false
};

// Define a helper to collect info from the `VariableDeclarator` node
function collectDeclaratorInfo(declarator) {
  // Find the declaration
  // https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Parser_API#Declarations
  var declaration = declarator.parent;
  return collectGenericInfo(declaration, {
    'var': declarator.kind === 'var',
    // TODO: Properly handle block scoping with `let` for `toplevel`
    'let': declarator.kind === 'let',
    // TODO: Is `const` block or lexical scoping?
    'const': declarator.kind === 'const'
  });
}

// Define a helper to calculate node info
function collectGenericInfo(_node, deductions) {
  // Resolve the scope for our node
  var scope = 'lexical';
  var node = _node;
  if (node.type === 'VariableDeclaration' && node.kind === 'let') {
    scope = 'block';
  }

  // Resolve the scope container
  node = _node;
  var scopeContainer;
  while (node) {
    // If the scoping is `lexical`
    if (scope === 'lexical') {
      // If we are at a function or the Program, stop traversing
      // TODO: Verify we handle both flavors of function (declaration and inline)
      if (node.type === 'Program') {
        scopeContainer = node;
        break;
      }
    }

    // TODO: What do we do in a block scope -_-;;
      // TODO: I know we stop at blocks... but what about functions?
      // TODO: If block adds onto lexical, then we might want to always perform lexical
        // TODO: but with an if clause that checks for block operators

    // Move to the parent
    node = node.parent;
  }

  // TODO: `with` should be collected in other traversal steps and passed through
  return extend({}, defaults, {
    topLevel: scopeContainer.type === 'Program'
  }, deductions);
}

// Define our scope collector
function ecmaVariableScope(_node) {
  // If the node is not an identifier, complain and leave
  // TODO: Are `labels` considered identifiers?
  var node = _node;
  var retObj = {

  };
  if (node.type !== 'Identifier') {
    throw new Error('`ecmaVariableScope` expected an "Identifier" but received "' + node.type + '"');
  }

  // Gather the name
  var varName = node.name;

  // If the current item is a variable declaration, exit early
  if (node.parent && node.parent.type === 'VariableDeclarator') {
    return collectDeclaratorInfo(node.parent);
  }

  // Traverse this scope to the previous node
  node = _node;
  while (node) {
    // Move to the previous node
    node = node.prev;
  }
  // console.log(require('util').inspect(node, {depth: 1}));

  // Tra

}

// Export our scope collector
module.exports = ecmaVariableScope;<commit_msg>Working through nodes and detecting scopes<commit_after>// Load in dependencies
var extend = require('obj-extend');

// Define a set of constants
exports.DECLARED_YES = true;
exports.DECLARED_UNKNOWN = 'unknown';
exports.DECLARED_NO = false;

// Define a set of defaults
var defaults = {
  // Summary
  declared: exports.DECLARED_NO, // false

  // Scope level
  topLevel: false,
  'with': false,

  // VariableDeclaration
  'var': false,
  'let': false,
  'const': false,

  // Function
  'function': false,

  // Try/catch
  'catch': false
};

// Define a helper to collect info from the `VariableDeclarator` node
function collectDeclaratorInfo(declarator) {
  // Find the declaration
  // https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Parser_API#Declarations
  var declaration = declarator.parent;
  return collectGenericInfo(declaration, {
    'var': declarator.kind === 'var',
    // TODO: Properly handle block scoping with `let` for `toplevel`
    'let': declarator.kind === 'let',
    // TODO: Is `const` block or lexical scoping?
    'const': declarator.kind === 'const'
  });
}

// Define a helper to calculate node info
function collectGenericInfo(_node, deductions) {
  // Resolve the scope for our node
  var scope = 'lexical';
  var node = _node;
  if (node.type === 'VariableDeclaration' && node.kind === 'let') {
    scope = 'block';
  }

  // Resolve the scope container
  node = _node;
  var scopeContainer;
  while (node) {
    // If we are at a function or the Program, stop traversing
    // TODO: Verify we handle both flavors of function (declaration and inline)
    if (node.type === 'Program') {
      scopeContainer = node;
      break;
    }

    // If we are checking against `block` scoping
    // TODO: Find a JSON block that matches what we expect
    // TODO: If we cannot find it, make one and publish it
    /*{
      program: 'Program',
      lexical: [
        'FunctionExpression'
      ],
      block: [
        'IfStatement'
      ]
    }*/
    if (scope === 'block') {
      // TODO: Detect block scopes
    }

    // Move to the parent
    node = node.parent;
  }

  // TODO: `with` should be collected in other traversal steps and passed through
  return extend({}, defaults, {
    topLevel: scopeContainer.type === 'Program'
  }, deductions);
}

// Define our scope collector
function ecmaVariableScope(_node) {
  // If the node is not an identifier, complain and leave
  // TODO: Are `labels` considered identifiers?
  var node = _node;
  var retObj = {

  };
  if (node.type !== 'Identifier') {
    throw new Error('`ecmaVariableScope` expected an "Identifier" but received "' + node.type + '"');
  }

  // Gather the name
  var varName = node.name;

  // If the current item is a variable declaration, exit early
  if (node.parent && node.parent.type === 'VariableDeclarator') {
    return collectDeclaratorInfo(node.parent);
  }

  // Traverse this scope to the previous node
  node = _node;
  while (node) {
    // Move to the previous node
    node = node.prev;
  }
  // console.log(require('util').inspect(node, {depth: 1}));

  // Tra

}

// Export our scope collector
module.exports = ecmaVariableScope;<|endoftext|>


<commit_before>var moment = require('moment');
var Jobs = require('../models/jobs_model');

exports.checkJobs = function() {
  var jobStream = Jobs.find().stream();
  jobStream.on('data', function(job) {
    addToQueue(job);
    console.log(moment(job.jobDate));
  });
};
function addToQueue(job) {
  var jobDate = moment(job.jobDate).utc().format();
  var later = moment().add(1, 'days').utc().format();
  // if the job date is within the next 24 hrs, add to Queue
  if (moment(jobDate).isBefore(moment(later))) {
    console.log('Sending to Queue: ' + jobDate);
  }
}

function sendToTwilio(date) {
  var jobDate = moment(date).utc().format();
  var later = moment().add(5, 'minutes'.utc().format());
  // if the job date is within the next 5 minutes, send to Twilio
  if (moment(jobDate).isBefore(moment(later))) {
    console.log('Sending to Twilio: ' + jobDate);
  }
}
<commit_msg>jobManager wip<commit_after>var moment = require('moment');
var Jobs = require('../models/jobs_model');

exports.checkJobs = function() {
  var jobStream = Jobs.find().stream();
  jobStream.on('data', function(job) {
    addToQueue(job);
    console.log(moment(job.jobDate).utc().format());
  });
};
function addToQueue(job) {
  var jobDate = moment(job.jobDate).utc().format();
  var later = moment().add(1, 'days').utc().format();
  // if the job date is within the next 24 hrs, add to Queue
  if (moment(jobDate).isBefore(moment(later))) {
    console.log('Sending to Queue: ' + jobDate);
  }
}

function sendToTwilio(date) {
  var jobDate = moment(date).utc().format();
  var later = moment().add(5, 'minutes'.utc().format());
  // if the job date is within the next 5 minutes, send to Twilio
  if (moment(jobDate).isBefore(moment(later))) {
    console.log('Sending to Twilio: ' + jobDate);
  }
}
<|endoftext|>


<commit_before>ZBase.registerView((function() {
  var widget_list = null;
  var edit_view = null;

  // REMOVEME
  var goToURL = function(path) {
    var kPathPrefix = "/a/reports/";
    var report_id = path.substr(kPathPrefix.length);
    loadReport(report_id);
  }
  // REMOVEME END

  var loadReport = function(report_id) {
    if (widget_list) {
      widget_list.destroy();
      widget_list = null;
    }

    $.showLoader();
    $.httpGet("/api/v1/documents/" + report_id, function(r) {
      if (r.status == 200) {
        var doc = JSON.parse(r.response);
        if (doc.content.length == 0) {
          doc.content = null;
        } else {
          doc.content = JSON.parse(doc.content);
        }

        // load required widgets
        var required_widgets = findRequiredWidgets(doc);
        ReportWidgetFactory.loadWidgets(required_widgets, function() {
          render(doc);
          $.hideLoader();
        });
      } else {
        $.fatalError();
      }
    });
  };

  var destroy = function() {
    //if (docsync) {
    //  docsync.close();
    //}

    if (widget_list) {
      widget_list.destroy();
    }

    if (edit_view) {
      edit_view.destroy();
    }
  };

  var render = function(doc) {
    var readonly = !doc.is_writable;
    var page = $.getTemplate(
        "views/report",
        "zbase_report_main_tpl");

    $.handleLinks(page);
    $.replaceViewport(page);

    setReportName(doc.name);

    var description = "";
    if (doc.content != null && doc.content.hasOwnProperty("description")) {
      description = doc.content.description;
    }
    setReportDescription(description);

    var widgets = [];
    if (doc.content != null && doc.content.hasOwnProperty("widgets")) {
      widgets = doc.content.widgets;
    }
    widget_list = WidgetList(widgets);
    widget_list.onWidgetEdit(function(widget_id) {
      showWidgetEditor(widget_id);
    });

    // handle display mode
    $(".zbase_report_pane z-dropdown.mode").addEventListener("change", function() {
      widget_list.setEditable(this.getValue() == "editing");
    }, false);

    if (readonly) {
      $(".readonly_hint").classList.remove("hidden");
    } else {
      initNameEditing();
      initDescriptionEditing();
      initShareDocModal(doc.uuid);
      initWidgetAdding();
    }

    showReportView();

    //// setup docsync
    //docsync = DocSync(
    //    getDocument,
    //    "/api/v1/documents/" + doc_id,
    //    $(".zbase_report_infobar"));
  };

  var showReportView = function(doc) {
    //showLoader?
    if (edit_view) {
      edit_view.destroy();
    }
    var viewport = $(".zbase_report_viewport");
    viewport.innerHTML = "";

    if (widget_list) {
      widget_list.render(viewport);
      widget_list.setEditable(true);
    } else {
      $.fatalError();
    }
  };

  var showWidgetEditor = function(widget_id) {
    if (!widget_list) {
      $.fatalError();
      return;
    }

    var conf = widget_list.getWidgetConfig(widget_id);
    edit_view = ReportWidgetFactory.getWidgetEditor(conf);

    edit_view.onSave(function(config) {
      widget_list.updateWidgetConfig(widget_id, config);
      showReportView();
    });

    edit_view.onCancel(function() {
      showReportView();
    });

    showEditView();
  };

  var showEditView = function() {
    var viewport = $(".zbase_report_viewport");
    viewport.innerHTML = "";
    edit_view.render(viewport);
  };

  var findRequiredWidgets = function(doc) {
    var widgets = [];

    if (doc.content != null && doc.content.hasOwnProperty("widgets")) {
      for (var i = 0; i < doc.content.widgets.length; i++) {
        if (widgets.indexOf(doc.content.widgets[i].type) == -1) {
          widgets.push(doc.content.widgets[i].type);
        }
      }
    }

    return widgets;
  };

  //var setEditable = function(is_editable) {
  //  widget_list.setEditable(is_editable);

  //  if (is_editable) {
  //    $(".writable_report_actions").classList.remove("hidden");
  //    $(".zbase_report_pane .report_name").classList.add("editable");
  //    $(".zbase_report_pane .report_description").classList.add("editable");
  //  } else {
  //    $(".writable_report_actions").classList.add("hidden");
  //    $(".zbase_report_pane .report_name").classList.remove("editable");
  //    $(".zbase_report_pane .report_description").classList.remove("editable");
  //  }
  //};

  var initShareDocModal = function(doc_id) {
    var modal = ShareDocModal(
        $(".zbase_report_pane"),
        doc_id,
        "http://zbase.io/a/report/" + doc_id);

    $.onClick($(".zbase_report_pane .link.share"), function() {
      modal.show();
    });
  };

  var initNameEditing = function() {
    var modal = $(".zbase_report_pane z-modal.rename_report");
    var name_input = $("input.report_name", modal);

    $.onClick($(".zbase_report_pane .report_name.editable"), function() {
      modal.show();
      name_input.focus();
    });

    $.onClick($("button.submit", modal), function() {
      setReportName($.escapeHTML(name_input.value));
      docsync.saveDocument();
      modal.close();
    });
  };

  var initDescriptionEditing = function() {
    var modal = $(".zbase_report_pane z-modal.edit_description");
    var textarea = $("textarea.report_description", modal);

    var showModal = function() {
      modal.show();
      textarea.focus();
    };

    $.onClick($(".zbase_report_pane .report_description.editable"), showModal);
    $.onClick($(".zbase_report_pane .link.add_description"), showModal);

    $.onClick($("button.submit", modal), function() {
      setReportDescription($.escapeHTML(textarea.value));
      docsync.saveDocument();
      modal.close();
    });
  };

  var initWidgetAdding = function() {
    var modal = $(".zbase_report_pane z-modal.add_widget");
    $.onClick($(".zbase_report_pane .link.add_widget"), function() {
      //FIXME get available report widgets and render selection
      modal.show();
    });

    $.onClick($("button.submit", modal), function() {
      var widget_type = $(".widget_selection[data-selected", modal)
          .getAttribute("data-widget");

      modal.close();
      $.showLoader();
      ReportWidgetFactory.loadWidgets([widget_type], function() {
        //post
        if (!widget_list) {
          $.fatalError();
          return;
        }
        widget_list.addNewWidget(widget_type);
        save();
        showReportView();
        $.hideLoader();
      });
    });
  };

  //var initContentEditing = function(page) {
  //  var edit_pane = $(".zbase_report_pane .edit_content_pane");
  //  var report_ui = $(".zbase_report_pane .report_ui");

  //  var closeEditPane = function() {
  //    updateReportContent();
  //    edit_pane.classList.add("hidden");
  //    report_ui.classList.remove("hidden");
  //    $(".error_note", edit_pane).classList.add("hidden");
  //  };

  //  $.onClick($(".zbase_report_pane .link.edit"), function() {
  //    report_ui.classList.add("hidden");
  //    edit_pane.classList.remove("hidden");
  //  });

  //  $.onClick($(".submit", edit_pane), function() {
  //    try {
  //      var content = JSON.parse(
  //          $.escapeHTML($("z-codeeditor", edit_pane).getValue()));
  //      description = content.description;
  //      widget_list.setJSON(content.widgets);
  //      docsync.saveDocument();
  //      closeEditPane();
  //    } catch (e) {
  //      $(".error_note", edit_pane).classList.remove("hidden");
  //    }
  //  });
  //  $.onClick($(".close", edit_pane), closeEditPane);
  //};

  var setReportName = function(name) {
    var escaped_name = $.escapeHTML(name);
    $("zbase-breadcrumbs-section.report_name").innerHTML = escaped_name;
    $(".zbase_report_pane .report_name").innerHTML = escaped_name;
    $(".zbase_report_pane z-modal input.report_name").value = escaped_name;
  };

  var setReportDescription = function(description) {
    var escaped_description = $.escapeHTML(description);

    //FIXME
    var readonly = false;
    if (!readonly && escaped_description.length == 0) {
      // display edit link
      $(".zbase_report_pane .sidebar_content .link.add_description")
        .classList.remove("hidden");
    } else {
      $(".zbase_report_pane .sidebar_content .link.add_description")
        .classList.add("hidden");
    }

    $(".zbase_report_pane .report_description").innerHTML = escaped_description;
    $(".zbase_report_pane z-modal textarea.report_description").innerHTML =
      escaped_description;
  };

  //var setReportContent = function() {
  //  var content = {
  //    description: description,
  //    widgets: widget_list.getJSON()
  //  };

  //  $(".zbase_report_pane .edit_content_pane z-codeeditor").setValue(
  //      JSON.stringify(content));
  //};

  //var updateReportContent = function() {
  //  setReportContent();
  //  setReportDescription();
  //};

  //FIXME save via doc_sync?
  var save = function() {
    //FIXME
    var kPathPrefix = "/a/reports/";
    var report_id = window.location.pathname.substr(kPathPrefix.length);
    var save_url = "/api/v1/documents/" + report_id;
    var postbody = $.buildQueryString(getDocument());

    $.httpPost(save_url, postbody, function(r) {
      if (r.status != 201) {
        $.fatalError("Saving Document Failed");
      }
    });
  };

  var getDocument = function() {
    var widgets = [];
    if (widget_list) {
      widgets = widget_list.getJSON();
    }

    return {
      content: JSON.stringify({
          description: $(".zbase_report_pane .report_description").innerText,
          widgets: widgets}),
      name: $(".zbase_report_pane input.report_name").value
    };
  };

  return {
    name: "report",
    loadView: function(params) { goToURL(params.path); },
    unloadView: destroy,
    handleNavigationChange: goToURL
  };

})());
<commit_msg>showRawJSONEditor and handle json update<commit_after>ZBase.registerView((function() {
  var widget_list = null;
  var edit_view = null;

  // REMOVEME
  var goToURL = function(path) {
    var kPathPrefix = "/a/reports/";
    var report_id = path.substr(kPathPrefix.length);
    loadReport(report_id);
  }
  // REMOVEME END

  var loadReport = function(report_id) {
    if (widget_list) {
      widget_list.destroy();
      widget_list = null;
    }

    $.showLoader();
    $.httpGet("/api/v1/documents/" + report_id, function(r) {
      if (r.status == 200) {
        var doc = JSON.parse(r.response);
        if (doc.content.length == 0) {
          doc.content = null;
        } else {
          doc.content = JSON.parse(doc.content);
        }

        // load required widgets
        var required_widgets = findRequiredWidgets(doc);
        ReportWidgetFactory.loadWidgets(required_widgets, function() {
          render(doc);
          $.hideLoader();
        });
      } else {
        $.fatalError();
      }
    });
  };

  var destroy = function() {
    //if (docsync) {
    //  docsync.close();
    //}

    if (widget_list) {
      widget_list.destroy();
    }

    if (edit_view) {
      edit_view.destroy();
    }
  };

  var render = function(doc) {
    var readonly = !doc.is_writable;
    var page = $.getTemplate(
        "views/report",
        "zbase_report_main_tpl");

    $.handleLinks(page);
    $.replaceViewport(page);

    setReportName(doc.name);

    var description = "";
    if (doc.content != null && doc.content.hasOwnProperty("description")) {
      description = doc.content.description;
    }
    setReportDescription(description);

    var widgets = [];
    if (doc.content != null && doc.content.hasOwnProperty("widgets")) {
      widgets = doc.content.widgets;
    }
    widget_list = WidgetList(widgets);
    widget_list.onWidgetEdit(function(widget_id) {
      showWidgetEditor(widget_id);
    });

    // handle display mode
    $(".zbase_report_pane z-dropdown.mode").addEventListener("change", function() {
      widget_list.setEditable(this.getValue() == "editing");
    }, false);

    if (readonly) {
      $(".readonly_hint").classList.remove("hidden");
    } else {
      initNameEditing();
      initDescriptionEditing();
      initShareDocModal(doc.uuid);
      initWidgetAdding();
      $.onClick($(".zbase_report_pane .link.edit_source"), showRawJSONEditor);
    }

    showReportView();

    //// setup docsync
    //docsync = DocSync(
    //    getDocument,
    //    "/api/v1/documents/" + doc_id,
    //    $(".zbase_report_infobar"));
  };

  var showReportView = function(doc) {
    //showLoader?
    if (edit_view) {
      edit_view.destroy();
    }
    var viewport = $(".zbase_report_viewport");
    viewport.innerHTML = "";

    if (widget_list) {
      widget_list.render(viewport);
      widget_list.setEditable(true);
    } else {
      $.fatalError();
    }
  };

  var showWidgetEditor = function(widget_id) {
    if (!widget_list) {
      $.fatalError();
      return;
    }

    var conf = widget_list.getWidgetConfig(widget_id);
    var editor = ReportWidgetFactory.getWidgetEditor(conf);

    editor.onSave(function(config) {
      widget_list.updateWidgetConfig(widget_id, config);
      showReportView();
    });

    editor.onCancel(function() {
      showReportView();
    });

    showEditView(editor);
  };

  var showRawJSONEditor = function() {
    var editor = ReportJSONEditor(getContentJSON());
    showEditView(editor);

    editor.onSave(function(json) {
      if (!widget_list) {
        $.fatalError();
        return;
      }
      var content = JSON.parse(json);
      widget_list.setJSON(content.widgets);
      setReportDescription(content.description);
      showReportView();
      save();
    });

    editor.onCancel(showReportView);
  };

  var showEditView = function(editor) {
    edit_view = editor;
    var viewport = $(".zbase_report_viewport");
    viewport.innerHTML = "";
    edit_view.render(viewport);
  };

  //var setEditable = function(is_editable) {
  //  widget_list.setEditable(is_editable);

  //  if (is_editable) {
  //    $(".writable_report_actions").classList.remove("hidden");
  //    $(".zbase_report_pane .report_name").classList.add("editable");
  //    $(".zbase_report_pane .report_description").classList.add("editable");
  //  } else {
  //    $(".writable_report_actions").classList.add("hidden");
  //    $(".zbase_report_pane .report_name").classList.remove("editable");
  //    $(".zbase_report_pane .report_description").classList.remove("editable");
  //  }
  //};

  var initShareDocModal = function(doc_id) {
    var modal = ShareDocModal(
        $(".zbase_report_pane"),
        doc_id,
        "http://zbase.io/a/report/" + doc_id);

    $.onClick($(".zbase_report_pane .link.share"), function() {
      modal.show();
    });
  };

  var initNameEditing = function() {
    var modal = $(".zbase_report_pane z-modal.rename_report");
    var name_input = $("input.report_name", modal);

    $.onClick($(".zbase_report_pane .report_name.editable"), function() {
      modal.show();
      name_input.focus();
    });

    $.onClick($("button.submit", modal), function() {
      setReportName($.escapeHTML(name_input.value));
      docsync.saveDocument();
      modal.close();
    });
  };

  var initDescriptionEditing = function() {
    var modal = $(".zbase_report_pane z-modal.edit_description");
    var textarea = $("textarea.report_description", modal);

    var showModal = function() {
      modal.show();
      textarea.focus();
    };

    $.onClick($(".zbase_report_pane .report_description.editable"), showModal);
    $.onClick($(".zbase_report_pane .link.add_description"), showModal);

    $.onClick($("button.submit", modal), function() {
      setReportDescription($.escapeHTML(textarea.value));
      docsync.saveDocument();
      modal.close();
    });
  };

  var initWidgetAdding = function() {
    var modal = $(".zbase_report_pane z-modal.add_widget");
    $.onClick($(".zbase_report_pane .link.add_widget"), function() {
      //FIXME get available report widgets and render selection
      modal.show();
    });

    $.onClick($("button.submit", modal), function() {
      var widget_type = $(".widget_selection[data-selected", modal)
          .getAttribute("data-widget");

      modal.close();
      $.showLoader();
      ReportWidgetFactory.loadWidgets([widget_type], function() {
        //post
        if (!widget_list) {
          $.fatalError();
          return;
        }
        widget_list.addNewWidget(widget_type);
        save();
        showReportView();
        $.hideLoader();
      });
    });
  };

  //var initContentEditing = function(page) {
  //  var edit_pane = $(".zbase_report_pane .edit_content_pane");
  //  var report_ui = $(".zbase_report_pane .report_ui");

  //  var closeEditPane = function() {
  //    updateReportContent();
  //    edit_pane.classList.add("hidden");
  //    report_ui.classList.remove("hidden");
  //    $(".error_note", edit_pane).classList.add("hidden");
  //  };

  //  $.onClick($(".zbase_report_pane .link.edit"), function() {
  //    report_ui.classList.add("hidden");
  //    edit_pane.classList.remove("hidden");
  //  });

  //  $.onClick($(".submit", edit_pane), function() {
  //    try {
  //      var content = JSON.parse(
  //          $.escapeHTML($("z-codeeditor", edit_pane).getValue()));
  //      description = content.description;
  //      widget_list.setJSON(content.widgets);
  //      docsync.saveDocument();
  //      closeEditPane();
  //    } catch (e) {
  //      $(".error_note", edit_pane).classList.remove("hidden");
  //    }
  //  });
  //  $.onClick($(".close", edit_pane), closeEditPane);
  //};

  var setReportName = function(name) {
    var escaped_name = $.escapeHTML(name);
    $("zbase-breadcrumbs-section.report_name").innerHTML = escaped_name;
    $(".zbase_report_pane .report_name").innerHTML = escaped_name;
    $(".zbase_report_pane z-modal input.report_name").value = escaped_name;
  };

  var setReportDescription = function(description) {
    var escaped_description = $.escapeHTML(description);

    //FIXME
    var readonly = false;
    if (!readonly && escaped_description.length == 0) {
      // display edit link
      $(".zbase_report_pane .sidebar_content .link.add_description")
        .classList.remove("hidden");
    } else {
      $(".zbase_report_pane .sidebar_content .link.add_description")
        .classList.add("hidden");
    }

    $(".zbase_report_pane .report_description").innerHTML = escaped_description;
    $(".zbase_report_pane z-modal textarea.report_description").innerHTML =
      escaped_description;
  };

  //var setReportContent = function() {
  //  var content = {
  //    description: description,
  //    widgets: widget_list.getJSON()
  //  };

  //  $(".zbase_report_pane .edit_content_pane z-codeeditor").setValue(
  //      JSON.stringify(content));
  //};

  //var updateReportContent = function() {
  //  setReportContent();
  //  setReportDescription();
  //};

  //FIXME save via doc_sync?
  var save = function() {
    //FIXME
    var kPathPrefix = "/a/reports/";
    var report_id = window.location.pathname.substr(kPathPrefix.length);
    var save_url = "/api/v1/documents/" + report_id;
    var postbody = $.buildQueryString(getDocument());

    $.httpPost(save_url, postbody, function(r) {
      if (r.status != 201) {
        $.fatalError("Saving Document Failed");
      }
    });
  };

  var getContentJSON = function() {
    var widgets = [];
    if (widget_list) {
      widgets = widget_list.getJSON();
    }

    return JSON.stringify({
        description: $(".zbase_report_pane .report_description").innerText,
        widgets: widgets});
  };

  var getDocument = function() {
    return {
      content: getContentJSON(),
      name: $(".zbase_report_pane input.report_name").value
    };
  };

  var findRequiredWidgets = function(doc) {
    var widgets = [];

    if (doc.content != null && doc.content.hasOwnProperty("widgets")) {
      for (var i = 0; i < doc.content.widgets.length; i++) {
        if (widgets.indexOf(doc.content.widgets[i].type) == -1) {
          widgets.push(doc.content.widgets[i].type);
        }
      }
    }

    return widgets;
  };

  return {
    name: "report",
    loadView: function(params) { goToURL(params.path); },
    unloadView: destroy,
    handleNavigationChange: goToURL
  };

})());
<|endoftext|>


<commit_before>var _ = require('underscore'),
    path = require('path'),
    reporterOptions;

//create a namespace for these functions, so they do not conflict with other scripts
var phssr = phssr ? phssr : {};

var reportInfo = {};

phssr.makeScriptTag = function(){
    var scrpTag = "";
    scrpTag += "\n"
    return scrpTag;
};

phssr.makeHardCodedStyleTag = function(reporterOptions){
    var styleTag = "";

    //Can override all styles with a CSS file
    if(reporterOptions.cssOverrideFile){
         styleTag = '<link href="' + reporterOptions.cssOverrideFile + '" rel="stylesheet" type="text/css"/>';
    }

    return styleTag;
}

phssr.makeHTMLPage = function(tableHtml, reporterOptions){
    var styleTag = phssr.makeHardCodedStyleTag(reporterOptions);
    var scrpTag = phssr.makeScriptTag();

    var staticHTMLContentprefix = "<meta charset='utf-8'/>";

    //Add title if it was in config setup
    if (typeof (reporterOptions.docTitle) !== 'undefined' && _.isString(reporterOptions.docTitle) ){
        staticHTMLContentprefix += "<title>" + reporterOptions.docTitle + "</title>";
    } else {
        staticHTMLContentprefix += "<title></title>";
    }

    staticHTMLContentprefix +=  styleTag + scrpTag + " ";
    staticHTMLContentprefix +=  "
Test Result on " + baseUrl +"
" + buildSummaryReport();
    staticHTMLContentprefix +=  "
Detail Report
";
    staticHTMLContentprefix +=  "

Description	Passed	";
    staticHTMLContentprefix +=  "Browser	";
    staticHTMLContentprefix +=  "OS	Message	";
    staticHTMLContentprefix +=  "Screenshot
";

    var staticHTMLContentpostfix = "
";
    var htmlComplete = staticHTMLContentprefix + tableHtml + staticHTMLContentpostfix;

    return htmlComplete;
}

function generateHTML(data){
    var str = '
';
    str +=  '' + data.desc + '	';
    var bgColor = data.passed? 'green': 'red';
    str +=  '' + data.passed + '	';
    str +=  '' + data.browser.name+ ':' +data.browser.version + '	';
    str +=  '' + data.os + '	';
    var stackTraceInfo = data.passed? '': '
' + data.message;

    str +=  '' + 'Show details
' + data.message + '
	';

    if(!(reporterOptions.takeScreenShotsOnlyForFailedSpecs && data.passed)) {
        str +=  'View	';
    }
    else{
        str +=  '	';
    }

    str += '
';
    return str;

}

function findDeep(items, attrs) {

    function match(value) {
        for (var key in attrs) {
            if (attrs[key] !== value[key]) {
                return false;
            }
        }

        return true;
    }

    function traverse(value) {
        var result;

        _.forEach(value, function (val) {
            if (val && match(val)) {
                result = val;
                return false;
            }

            if (_.isObject(val) || _.isArray(val)) {
                result = traverse(val);
            }

            if (result) {
                return false;
            }
        });

        return result;
    }

    return traverse(items);

}

var formattedJson = [];
var currentFormattedDataIndex = 0;

function formatData(element, descArr) {
    if (currentFormattedDataIndex === descArr.length - 1) {
        var lastValueWithContent = {
            desc: descArr[currentFormattedDataIndex],
            level: currentFormattedDataIndex,
            description: element.description,
            passed: element.passed,
            os: element.os,
            browser: element.browser,
            message: element.message,
            trace: element.trace,
            screenShotFile: element.screenShotFile
        };
        var parentDataForFinalValue = findDeep(formattedJson, {
            desc: descArr[currentFormattedDataIndex - 1],
            level: currentFormattedDataIndex - 1
        });
        if (parentDataForFinalValue) {
            parentDataForFinalValue.children = parentDataForFinalValue.children || [];
            parentDataForFinalValue.children.push(lastValueWithContent);
        }

        currentFormattedDataIndex = 0;
    } else {
        var currentdata = {
            desc: descArr[currentFormattedDataIndex],
            level: currentFormattedDataIndex
        };
        var existingDataWithSameConf = findDeep(formattedJson, currentdata);
        if (!existingDataWithSameConf) {
            if (currentFormattedDataIndex === 0) {
                currentdata.depth = descArr.length;
                formattedJson.push(currentdata);
            } else {
                var parentData = findDeep(formattedJson, {
                    desc: descArr[currentFormattedDataIndex - 1],
                    level: currentFormattedDataIndex - 1
                });
                if (parentData) {
                    parentData.children = parentData.children || [];
                    parentData.children.push(currentdata);
                }

            }

        }

        currentFormattedDataIndex++;
        formatData(element, descArr);
    }

}

function processJson(jsonData, options){
    reporterOptions = options;
    //var jsonStr = "
";
    var jsonStr = "";
    formattedJson = [];
    currentFormattedDataIndex = 0;

    _.each(jsonData, function (value) {
        var descArr = value.description.split('|').reverse();
        if (descArr.length > 0) {
            formatData(value, descArr);
        }
    });

    function parseJSON(element) {
        if(element.children){
            var report = {};
            report.name = element.desc;
            report.passCount = 0;
            report.failCount = 0;
            report.total = element.children.length;

            element.children.forEach(function (e){
                if (e.passed) report.passCount++;
                else report.failCount++;

            });
            reportInfo[report.name] = report;

            jsonStr += '

'+element.desc+ '
';
            if (detailReport.hasOwnProperty(element.desc)){
                var obj = detailReport[element.desc][0];
                if (typeof obj === "undefined")
                    obj = detailReport[element.desc]["-1"];
                if (typeof obj === "undefined")
                    obj = detailReport[element.desc][1];

                for (var j = 0; j < obj.length; j++) {
                    if (obj[j].type === 'link') {
                        jsonStr += '' + obj[j].text + '
';
                    }
                    else {
                        jsonStr += obj[j].text + '
';
                    }
                }
            }
            jsonStr += '
';

            element.children.forEach(function (child, index, childArr) {
                if (child.children) {
                    parseJSON(child);
                }else{
                    var ss = generateHTML(child);
                    jsonStr += ss;
                    if(index === childArr.length-1){
                    }
                }
            });
            return jsonStr;
        }

    }

    var tableHtml = "";
    formattedJson.forEach(function (element) {

        jsonStr = "";
        tableHtml += parseJSON(element);
        tableHtml += new Array(element.depth-1).join();

    });

    tableHtml = tableHtml;
    var finalHtml = phssr.makeHTMLPage(tableHtml, reporterOptions);
    return finalHtml;
}

function msToTime(duration) {
    var milliseconds = parseInt( (duration % 1000) / 100 )
        , seconds = parseInt( (duration / 1000) % 60 )
        , minutes = parseInt( (duration / (1000 * 60) ) % 60 )
        , hours = parseInt( (duration / (1000 * 60 * 60) ) % 24);

    if (hours < 10) hours = "0" + hours;
    if (minutes < 10) minutes = "0" + minutes;
    if (seconds < 10) seconds = "0" + seconds;

    return hours + ":" + minutes + ":" + seconds + "." + milliseconds;
}

function JSON2File(obj, path, file) {
    "use strict";
    var fs = require('fs');
    var skip = false;

    try {
        fs.mkdirSync(path);
    } catch(e) {
        if ( e.code != 'EEXIST' ) {
            skip = true;
            console.log("can't create folder " + path);
        }
    }

    if (!skip)
        fs.writeFileSync(path + "/" + file, JSON.stringify(obj));
}

function buildSummaryReport() {
    var totalTest = 0, totalPass = 0, totalFail = 0, passPercent = 0, suiteCount = 0;
    var htmlCode = "
This report was generated on "+new Date()+"
";
    //add total test time if available
    if (typeof TotalTestTime !== "undefined") htmlCode += "
Total test time: " + msToTime(TotalTestTime) +"
";

    var jqcode = "\"javascript:(function(){$('tr:has(td:nth-child(2):contains(_STATUS_))').toggle()})()\"";
    var header = "
Summary Report
" +
        "
" +
        "
Test suite	Total cases	Pass	Fail
";
    header = header.replace("_PASS_", jqcode.replace("_STATUS_", "false")).replace("_FAIL_", jqcode.replace("_STATUS_", "true"));
    htmlCode += header;

    for (var key in reportInfo) {
        suiteCount++;
        var report = reportInfo[key];
        totalTest += report.total;
        totalPass += report.passCount;
        totalFail += report.failCount;
        passPercent = (report.passCount / report.total * 100);

        htmlCode += "
" +
            report.name + "	" + report.total + "	" +
            (passPercent == 100 ? "" : "") +
            report.passCount + " (" + passPercent.toFixed(2).toString() + "%)	" +
            (passPercent == 100 ? "" : "") +
            report.failCount + " (" + (100 - passPercent).toFixed(2).toString() + "%)
";
    }
    //Final total row
    passPercent = (totalPass / totalTest * 100);
    if (suiteCount > 1) {
        htmlCode += "
All suites	" +
            totalTest + "	" +
            totalPass + " (" + passPercent.toFixed(2).toString() + "%)	" +
            totalFail + " (" + (100 - passPercent).toFixed(2).toString() + "%)
";
    }
    htmlCode += "
";

    global.TotalFailCase = totalFail;
    global.TotalCase = totalTest;
    JSON2File(JSON.stringify({"url": baseUrl, "total": totalTest, "pass": totalPass, "startTime": StartTestTime}), reportPath, SummaryReportName);
    return htmlCode;
}

module.exports = {
    processJson: processJson
};
<commit_msg>reverse previous commit<commit_after>var _ = require('underscore'),
    path = require('path'),
    reporterOptions;

//create a namespace for these functions, so they do not conflict with other scripts
var phssr = phssr ? phssr : {};

var reportInfo = {};

phssr.makeScriptTag = function(){
    var scrpTag = "";
    scrpTag += "\n"
    return scrpTag;
};

phssr.makeHardCodedStyleTag = function(reporterOptions){
    var styleTag = "";

    //Can override all styles with a CSS file
    if(reporterOptions.cssOverrideFile){
         styleTag = '<link href="' + reporterOptions.cssOverrideFile + '" rel="stylesheet" type="text/css"/>';
    }

    return styleTag;
}

phssr.makeHTMLPage = function(tableHtml, reporterOptions){
    var styleTag = phssr.makeHardCodedStyleTag(reporterOptions);
    var scrpTag = phssr.makeScriptTag();

    var staticHTMLContentprefix = "<meta charset='utf-8'/>";

    //Add title if it was in config setup
    if (typeof (reporterOptions.docTitle) !== 'undefined' && _.isString(reporterOptions.docTitle) ){
        staticHTMLContentprefix += "<title>" + reporterOptions.docTitle + "</title>";
    } else {
        staticHTMLContentprefix += "<title></title>";
    }

    staticHTMLContentprefix +=  styleTag + scrpTag + " ";
    staticHTMLContentprefix +=  "
Test Result on " + baseUrl +"
" + buildSummaryReport();
    staticHTMLContentprefix +=  "
Detail Report
";
    staticHTMLContentprefix +=  "

Description	Passed	";
    staticHTMLContentprefix +=  "Browser	";
    staticHTMLContentprefix +=  "OS	Message	";
    staticHTMLContentprefix +=  "Screenshot
";

    var staticHTMLContentpostfix = "
";
    var htmlComplete = staticHTMLContentprefix + tableHtml + staticHTMLContentpostfix;

    return htmlComplete;
}

function generateHTML(data){
    var str = '
';
    str +=  '' + data.desc + '	';
    var bgColor = data.passed? 'green': 'red';
    str +=  '' + data.passed + '	';
    str +=  '' + data.browser.name+ ':' +data.browser.version + '	';
    str +=  '' + data.os + '	';
    var stackTraceInfo = data.passed? '': '
' + data.message;

    str +=  '' + 'Show details
' + data.message + '
	';

    if(!(reporterOptions.takeScreenShotsOnlyForFailedSpecs && data.passed)) {
        str +=  'View	';
    }
    else{
        str +=  '	';
    }

    str += '
';
    return str;

}

function findDeep(items, attrs) {

    function match(value) {
        for (var key in attrs) {
            if (attrs[key] !== value[key]) {
                return false;
            }
        }

        return true;
    }

    function traverse(value) {
        var result;

        _.forEach(value, function (val) {
            if (val && match(val)) {
                result = val;
                return false;
            }

            if (_.isObject(val) || _.isArray(val)) {
                result = traverse(val);
            }

            if (result) {
                return false;
            }
        });

        return result;
    }

    return traverse(items);

}

var formattedJson = [];
var currentFormattedDataIndex = 0;

function formatData(element, descArr) {
    if (currentFormattedDataIndex === descArr.length - 1) {
        var lastValueWithContent = {
            desc: descArr[currentFormattedDataIndex],
            level: currentFormattedDataIndex,
            description: element.description,
            passed: element.passed,
            os: element.os,
            browser: element.browser,
            message: element.message,
            trace: element.trace,
            screenShotFile: element.screenShotFile
        };
        var parentDataForFinalValue = findDeep(formattedJson, {
            desc: descArr[currentFormattedDataIndex - 1],
            level: currentFormattedDataIndex - 1
        });
        if (parentDataForFinalValue) {
            parentDataForFinalValue.children = parentDataForFinalValue.children || [];
            parentDataForFinalValue.children.push(lastValueWithContent);
        }

        currentFormattedDataIndex = 0;
    } else {
        var currentdata = {
            desc: descArr[currentFormattedDataIndex],
            level: currentFormattedDataIndex
        };
        var existingDataWithSameConf = findDeep(formattedJson, currentdata);
        if (!existingDataWithSameConf) {
            if (currentFormattedDataIndex === 0) {
                currentdata.depth = descArr.length;
                formattedJson.push(currentdata);
            } else {
                var parentData = findDeep(formattedJson, {
                    desc: descArr[currentFormattedDataIndex - 1],
                    level: currentFormattedDataIndex - 1
                });
                if (parentData) {
                    parentData.children = parentData.children || [];
                    parentData.children.push(currentdata);
                }

            }

        }

        currentFormattedDataIndex++;
        formatData(element, descArr);
    }

}

function processJson(jsonData, options){
    reporterOptions = options;
    //var jsonStr = "
";
    var jsonStr = "";
    formattedJson = [];
    currentFormattedDataIndex = 0;

    _.each(jsonData, function (value) {
        var descArr = value.description.split('|').reverse();
        if (descArr.length > 0) {
            formatData(value, descArr);
        }
    });

    function parseJSON(element) {
        if(element.children){
            var report = {};
            report.name = element.desc;
            report.passCount = 0;
            report.failCount = 0;
            report.total = element.children.length;

            element.children.forEach(function (e){
                if (e.passed) report.passCount++;
                else report.failCount++;

            });
            reportInfo[report.name] = report;

            jsonStr += '

'+element.desc+ '
';
            if (detailReport.hasOwnProperty(element.desc)){
                var obj = detailReport[element.desc][0];
                if (typeof obj === "undefined")
                    obj = detailReport[element.desc]["-1"];
                if (typeof obj === "undefined")
                    obj = detailReport[element.desc][1];

                for (var j = 0; j < obj.length; j++) {
                    if (obj[j].type === 'link') {
                        jsonStr += '' + obj[j].text + '
';
                    }
                    else {
                        jsonStr += obj[j].text + '
';
                    }
                }
            }
            jsonStr += '
';

            element.children.forEach(function (child, index, childArr) {
                if (child.children) {
                    parseJSON(child);
                }else{
                    var ss = generateHTML(child);
                    jsonStr += ss;
                    if(index === childArr.length-1){
                    }
                }
            });
            return jsonStr;
        }

    }

    var tableHtml = "";
    formattedJson.forEach(function (element) {

        jsonStr = "";
        tableHtml += parseJSON(element);
        tableHtml += new Array(element.depth-1).join();

    });

    tableHtml = tableHtml;
    var finalHtml = phssr.makeHTMLPage(tableHtml, reporterOptions);
    return finalHtml;
}

function msToTime(duration) {
    var milliseconds = parseInt( (duration % 1000) / 100 )
        , seconds = parseInt( (duration / 1000) % 60 )
        , minutes = parseInt( (duration / (1000 * 60) ) % 60 )
        , hours = parseInt( (duration / (1000 * 60 * 60) ) % 24);

    if (hours < 10) hours = "0" + hours;
    if (minutes < 10) minutes = "0" + minutes;
    if (seconds < 10) seconds = "0" + seconds;

    return hours + ":" + minutes + ":" + seconds + "." + milliseconds;
}

function JSON2File(obj, path, file) {
    "use strict";
    var fs = require('fs');
    var skip = false;

    try {
        fs.mkdirSync(path);
    } catch(e) {
        if ( e.code != 'EEXIST' ) {
            skip = true;
            console.log("can't create folder " + path);
        }
    }

    if (!skip)
        fs.writeFileSync(path + "/" + file, JSON.stringify(obj));
}

function buildSummaryReport() {
    var totalTest = 0, totalPass = 0, totalFail = 0, passPercent = 0, suiteCount = 0;
    var htmlCode = "
This report was generated on "+new Date()+"
";
    //add total test time if available
    if (typeof TotalTestTime !== "undefined") htmlCode += "
Total test time: " + msToTime(TotalTestTime) +"
";

    var jqcode = "\"javascript:(function(){$('tr:has(td:nth-child(2):contains(_STATUS_))').toggle()})()\"";
    var header = "
Summary Report
" +
        "
" +
        "
Test suite	Total cases	Pass	Fail
";
    header = header.replace("_PASS_", jqcode.replace("_STATUS_", "false")).replace("_FAIL_", jqcode.replace("_STATUS_", "true"));
    htmlCode += header;

    for (var key in reportInfo) {
        suiteCount++;
        var report = reportInfo[key];
        totalTest += report.total;
        totalPass += report.passCount;
        totalFail += report.failCount;
        passPercent = (report.passCount / report.total * 100);

        htmlCode += "
" +
            report.name + "	" + report.total + "	" +
            (passPercent == 100 ? "" : "") +
            report.passCount + " (" + passPercent.toFixed(2).toString() + "%)	" +
            (passPercent == 100 ? "" : "") +
            report.failCount + " (" + (100 - passPercent).toFixed(2).toString() + "%)
";
    }
    //Final total row
    passPercent = (totalPass / totalTest * 100);
    if (suiteCount > 1) {
        htmlCode += "
All suites	" +
            totalTest + "	" +
            totalPass + " (" + passPercent.toFixed(2).toString() + "%)	" +
            totalFail + " (" + (100 - passPercent).toFixed(2).toString() + "%)
";
    }
    htmlCode += "
";

    global.TotalFailCase = totalFail;
    global.TotalCase = totalTest;
    JSON2File({"url": baseUrl, "total": totalTest, "pass": totalPass, "startTime": StartTestTime}, reportPath, SummaryReportName);
    return htmlCode;
}

module.exports = {
    processJson: processJson
};
<|endoftext|>


<commit_before>import React from 'react'
import {Redirect, Route} from 'react-router-dom'
import connect from '../utils/connect'

const defineMatch = (shouldRender, redirectTo) => {
  const DefinedMatch = ({
    component,
    ...rest
  }) => (
    <Route
      {...rest}
      render={props => (
        shouldRender(rest)
          ? renderComponent(component, props)
          : rest.redirect
          ? renderRedirect(redirectTo, props.location)
          : null
      )}
      />
  )

  return connect(DefinedMatch)
}

function renderRedirect (pathname, from) {
  return (
    <Redirect to={{pathname, state: {from}}} />
  )
}

function renderComponent (component, props) {
  const Component = connect(component)

  return (
    <Component {...props} />
  )
}

export default defineMatch
<commit_msg>refactor(router): clean up props<commit_after>import React from 'react'
import {Redirect, Route} from 'react-router-dom'
import connect from '../utils/connect'

const defineMatch = (shouldRender) => {
  const DefinedMatch = ({
    component,
    exact,
    path,
    ...rest
  }) => (
    <Route
      path={path}
      exact={exact}
      render={props => (
        shouldRender(rest)
          ? renderComponent(component, props)
          : rest.redirect
          ? renderRedirect(rest.redirect, props.location)
          : null
      )}
      />
  )

  return connect(DefinedMatch)
}

function renderRedirect (pathname, from) {
  return (
    <Redirect to={{pathname, state: {from}}} />
  )
}

function renderComponent (component, {history, location, match, ...props}) {
  const Component = connect(component)

  return (
    <Component {...props} />
  )
}

export default defineMatch
<|endoftext|>