<commit_before>
var AWS         = require('aws-sdk')
  , _           = require('lodash')
  , nameRegexp  = /\/?nfd[-:]([^-]+)-(.+)$/

function fetchLoadBalancers(config, namespaces, cb) {

  var elb           = new AWS.ELB()

    , instancesMap  = _.chain(namespaces)
                       .values()
                       .map(function(namespace) {
                         return _.values(namespace.topology.containers)
                       })
                       .flatten()
                       .filter(function(container) {
                         // this is an EC2 instance
                         return container.specific.instanceId
                       })
                       .reduce(function(acc, container) {
                         acc[container.specific.instanceId] = container
                         return acc
                       }, {})
                       .value()

  elb.describeLoadBalancers({}, function(err, data) {
    if (err) { return cb(err) }

    data.LoadBalancerDescriptions.forEach(function(elb) {

      var match = elb.LoadBalancerName.match(nameRegexp)

        , id
        , namespace

        , topologyContainers
        , containerDefinitions

      if (!match) {
        return
      }

      id = match[2]
      namespace = match[1]

      if (!namespaces[namespace]) {
        // TODO handle this condition better
        return cb(new Error('ELB with no instance'))
      }

      topologyContainers    = namespaces[namespace].topology.containers
      containerDefinitions  = namespaces[namespace].containerDefinitions

      topologyContainers[id] = {
          id: id
        , contains: []
        , specific: {
          }
      }

      elb.Instances.forEach(function(instance) {
        instance = instancesMap[instance.InstanceId]

        topologyContainers[id].contains.push(instance.id)

        instance.containedBy = id
      })

    })

    cb()
  })
}

module.exports = fetchLoadBalancers
<commit_msg>Added container definition for ELBs.<commit_after>
var AWS         = require('aws-sdk')
  , _           = require('lodash')
  , nameRegexp  = /\/?nfd[-:]([^-]+)-(.+)$/
  , uuid        = require('uuid')

function fetchLoadBalancers(config, namespaces, cb) {

  var elb           = new AWS.ELB()

    , instancesMap  = _.chain(namespaces)
                       .values()
                       .map(function(namespace) {
                         return _.values(namespace.topology.containers)
                       })
                       .flatten()
                       .filter(function(container) {
                         // this is an EC2 instance
                         return container.specific.instanceId
                       })
                       .reduce(function(acc, container) {
                         acc[container.specific.instanceId] = container
                         return acc
                       }, {})
                       .value()

  elb.describeLoadBalancers({}, function(err, data) {
    if (err) { return cb(err) }

    data.LoadBalancerDescriptions.forEach(function(elb) {

      var match = elb.LoadBalancerName.match(nameRegexp)

        , id
        , namespace

        , topologyContainers
        , containerDefinitions
        , def

      if (!match) {
        return
      }

      id = match[2]
      namespace = match[1]

      if (!namespaces[namespace]) {
        // TODO handle this condition better
        return cb(new Error('ELB with no instance'))
      }

      topologyContainers    = namespaces[namespace].topology.containers
      containerDefinitions  = namespaces[namespace].containerDefinitions

      def = {
          id: uuid.v1()
        , type: 'aws-elb'
      }

      containerDefinitions.push(def)

      topologyContainers[id] = {
          id: id
        , containerDefinitionId: def.id
        , contains: []
        , specific: {
          }
      }

      elb.Instances.forEach(function(instance) {
        instance = instancesMap[instance.InstanceId]

        topologyContainers[id].contains.push(instance.id)

        instance.containedBy = id
      })

    })

    cb()
  })
}

module.exports = fetchLoadBalancers
<|endoftext|>


<commit_before>'use strict';

/**
 *  lib
 **/

/*global nodeca*/

// 3rd-party
var Puncher = require('puncher');

////////////////////////////////////////////////////////////////////////////////

var tzOffset = (new Date).getTimezoneOffset();

////////////////////////////////////////////////////////////////////////////////

/**
 *  lib.env(options) -> Object
 *  - options (Object): Environment options.
 *
 *  Create new request environment object.
 *
 *
 *  ##### Options
 *
 *  - **http**: HTTP origin object that contains `req` and `res`.
 *  - **rpc**: API3 (Ajax) origin that contains `req` and `res`.
 *  - **skip**: Array of middlewares to skip
 *  - **session**: Session object
 *  - **method**: Name of the server method, e.g. `'forums.posts.show'`
 *  - **layout**: Layout name as String
 **/
module.exports = function env(options) {
  var req     = (options.http || options.rpc).req;
  var method  = String(options.method || '');
  var ns      = method.split('.').shift();

  var ctx = {
    extras:  {
      puncher: new Puncher()
    },
    helpers: {
      asset_path: function asset_path(path) {
        var asset = nodeca.runtime.assets.manifest.assets[path];
        return !asset ? "#" : nodeca.runtime.router.linkTo('assets', { path: asset });
      }
    },
    origin: {
      http: options.http,
      rpc: options.rpc
    },
    skip: (options.skip || []).slice(),
    session: options.session || null,
    request: {
      // FIXME: should be deprecated in flavour of env.origin
      origin:     !!options.rpc ? 'RPC' : 'HTTP',
      method:     method,
      ip:         req.connection.remoteAddress,
      user_agent: req.headers['user-agent'],
      namespace:  ns
    },
    data: {},
    runtime: {
      // FIXME: must be set from cookies
      theme: 'desktop'
    },
    settings: {
      params: {},
      fetch: function fetchSettings(keys, callback) {
        nodeca.settings.get(keys, this.params, {}, callback);
      }
    },
    response: {
      data: {
        head: {
          title: null, // should be filled with default value
          apiPath: method,
          // List of assets for yepnope,
          // Each element is an object with properties:
          //
          //    type:   css|js
          //    link:   asset_url
          //
          // example: assets.push({type: 'js', link: '//example.com/foo.js'});
          assets: []
        },
        menus: {},
        widgets: {}
      },
      headers: {},
      // Layouts are supporting "nesting" via `dots:
      //
      //    default.blogs
      //
      // In the example above, `default.blogs` will be rendered first and the
      // result will be provided for rendering to `default`.
      layout: options.layout || ('admin' === ns) ? method : ('default.' + method),
      // Default view template name == server method name
      // One might override this, to render different view
      //
      view: method
    }
  };

  //
  // env-dependent helper needs to be bounded to env
  //

  ctx.helpers.t = function (phrase, params) {
    var locale = this.runtime.locale || nodeca.config.locales['default'];
    return nodeca.runtime.i18n.t(locale, phrase, params);
  }.bind(ctx);

  ctx.helpers.t.exists = function (phrase) {
    var locale = this.runtime.locale || nodeca.config.locales['default'];
    return nodeca.runtime.i18n.hasPhrase(locale, phrase);
  }.bind(ctx);

  ctx.helpers.date = function (value, format) {
    var locale = this.runtime.locale || nodeca.config.locales['default'];
    return nodeca.shared.date(value, format, locale, tzOffset);
  }.bind(ctx);

  return ctx;
};
<commit_msg>Improve layout auto-guessing<commit_after>'use strict';

/**
 *  lib
 **/

/*global nodeca*/

// 3rd-party
var Puncher = require('puncher');

////////////////////////////////////////////////////////////////////////////////

var tzOffset = (new Date).getTimezoneOffset();

////////////////////////////////////////////////////////////////////////////////

/**
 *  lib.env(options) -> Object
 *  - options (Object): Environment options.
 *
 *  Create new request environment object.
 *
 *
 *  ##### Options
 *
 *  - **http**: HTTP origin object that contains `req` and `res`.
 *  - **rpc**: API3 (Ajax) origin that contains `req` and `res`.
 *  - **skip**: Array of middlewares to skip
 *  - **session**: Session object
 *  - **method**: Name of the server method, e.g. `'forums.posts.show'`
 *  - **layout**: Layout name as String
 **/
module.exports = function env(options) {
  var req     = (options.http || options.rpc).req;
  var method  = String(options.method || '');
  var ns      = method.split('.').shift();
  var layout  = options.layout;

  if (!layout) {
    // get auto-guessed layout based on requested apiPath:
    //
    //    forum.threads.show        -> default.forum.threads
    //    blogs.index               -> default.blogs
    //    admin.dashboard           -> admin
    //    admin.users.show          -> admin.users
    //
    layout  = (('admin' === ns) ? '' : 'default.') +
              method.split('.').slice(0, -1).join('.');
  }

  var ctx = {
    extras:  {
      puncher: new Puncher()
    },
    helpers: {
      asset_path: function asset_path(path) {
        var asset = nodeca.runtime.assets.manifest.assets[path];
        return !asset ? "#" : nodeca.runtime.router.linkTo('assets', { path: asset });
      }
    },
    origin: {
      http: options.http,
      rpc: options.rpc
    },
    skip: (options.skip || []).slice(),
    session: options.session || null,
    request: {
      // FIXME: should be deprecated in flavour of env.origin
      origin:     !!options.rpc ? 'RPC' : 'HTTP',
      method:     method,
      ip:         req.connection.remoteAddress,
      user_agent: req.headers['user-agent'],
      namespace:  ns
    },
    data: {},
    runtime: {
      // FIXME: must be set from cookies
      theme: 'desktop'
    },
    settings: {
      params: {},
      fetch: function fetchSettings(keys, callback) {
        nodeca.settings.get(keys, this.params, {}, callback);
      }
    },
    response: {
      data: {
        head: {
          title: null, // should be filled with default value
          apiPath: method,
          // List of assets for yepnope,
          // Each element is an object with properties:
          //
          //    type:   css|js
          //    link:   asset_url
          //
          // example: assets.push({type: 'js', link: '//example.com/foo.js'});
          assets: []
        },
        menus: {},
        widgets: {}
      },
      headers: {},
      // Layouts are supporting "nesting" via `dots:
      //
      //    default.blogs
      //
      // In the example above, `default.blogs` will be rendered first and the
      // result will be provided for rendering to `default`.
      layout: layout,
      // Default view template name == server method name
      // One might override this, to render different view
      //
      view: method
    }
  };

  //
  // env-dependent helper needs to be bounded to env
  //

  ctx.helpers.t = function (phrase, params) {
    var locale = this.runtime.locale || nodeca.config.locales['default'];
    return nodeca.runtime.i18n.t(locale, phrase, params);
  }.bind(ctx);

  ctx.helpers.t.exists = function (phrase) {
    var locale = this.runtime.locale || nodeca.config.locales['default'];
    return nodeca.runtime.i18n.hasPhrase(locale, phrase);
  }.bind(ctx);

  ctx.helpers.date = function (value, format) {
    var locale = this.runtime.locale || nodeca.config.locales['default'];
    return nodeca.shared.date(value, format, locale, tzOffset);
  }.bind(ctx);

  return ctx;
};
<|endoftext|>


<commit_before>function Thing(){
    this.config = {};
}

Thing.prototype.copy = function(){
    var anotherThing = new Thing();
    anotherThing.config = this.config;
    return anotherThing;
};

//Thing.prototype.set = function( key ){
//    object[ key ] = true;
//};

Thing.prototype.on = function( key ){
    var transientThing = this.copy();

    transientThing.currentKey = key;
    if( transientThing.config[ key ] === undefined ){
        transientThing.config[ key ] = {};
    }
    return transientThing;
};

Thing.prototype.set = function( key ){
    var object;

    if( this.currentKey ){
        object = this.config[this.currentKey];
    }else{
        object = this.config;
    }

    object[ key ] = true;
};

var myThing = new Thing();
myThing.set( 'Hair' );
myThing.on('Cheese').set('Stink');
console.log( myThing );<commit_msg>experimenting with pattern<commit_after>function Thing(){
    this.config = {};
}

Thing.prototype.copy = function(){
    var anotherThing = new Thing();
    anotherThing.config = this.config;
    return anotherThing;
};

Thing.prototype.on = function( key ){
    var transientThing = this.copy();

    transientThing.currentKey = key;
    if( transientThing.config[ key ] === undefined ){
        transientThing.config[ key ] = {};
    }
    return transientThing;
};

Thing.prototype.set = function( key ){
    var object;

    if( this.currentKey ){
        object = this.config[this.currentKey];
    }else{
        object = this.config;
    }

    object[ key ] = true;
};

var myThing = new Thing();
myThing.set( 'Hair' );
myThing.on('Cheese').set('Stink');
myThing.set('Beard');

console.log( myThing );

var myOtherThing = new Thing();
myOtherThing.on( 'Toast ').set('Marmalade');
console.log( myOtherThing );
<|endoftext|>


<commit_before>'use strict'
module.exports = (target, path) => {
  if (typeof path === 'string') {
    path = path.split('.')
  }
  const len = path.length
  var i = 0
  while (i < len && (target = target[path[i++]]));
  return target
}
<commit_msg>no unnsecary type check<commit_after>'use strict'
module.exports = (target, path) => {
  const len = path.length
  var i = 0
  while (i < len && (target = target[path[i++]]));
  return target
}
<|endoftext|>


<commit_before>var fs = require('fs');
var marked = require('marked');

exports.transform = transform;
exports.transformers = transformers();

function transform(f, data, transformers, done) {
    var ctx = {sections: []};
    var tokens = marked.lexer(data).map(function(t) {
        if(t.type == 'text' || t.type == 'paragraph') {
            var text = t.text;

            for(var k in transformers) {
                var v = transformers[k];
                text = v.match(text, v.toHTML);
            }

            return {
                type: 'text',
                text: text
            };
        }
        if(t.type == 'heading') {
            var n = t.text;
            var i = n.toLowerCase();
            ctx.sections.push({name: n, id: i});

            return {
                type: 'heading',
                depth: t.depth,
                text: '<h' + t.depth + ' id="' + i + '">' + n + '</h' + t.depth + '>'
            };
        }
        return t;
    });
    tokens.links = [];

    ctx.data = marked.parser(tokens);

    done(f, ctx);
}

// http://phpjs.org/functions/ltrim:467
function ltrim(str, charlist) {
    charlist = !charlist ? ' \\s\u00A0' : (charlist + '').replace(/([\[\]\(\)\.\?\/\*\{\}\+\$\^\:])/g, '$1');
    var re = new RegExp('^[' + charlist + ']+', 'g');
    return (str + '').replace(re, '');
}

// http://phpjs.org/functions/rtrim:507
function rtrim(str, charlist) {
    charlist = !charlist ? ' \\s\u00A0' : (charlist + '').replace(/([\[\]\(\)\.\?\/\*\{\}\+\$\^\:])/g, '\\$1');
    var re = new RegExp('[' + charlist + ']+$', 'g');
    return (str + '').replace(re, '');
}

function trim(str, charlist) {
    return rtrim(ltrim(str, charlist), charlist);
}

function all(o) {
    for(var i = 0, len = o.length; i < len; i++) {
        if(!o[i]) return false;
    }

    return true;
}

function transformers() {
    return attachMissing({
        table: {
            match: function(text, output) {
                var parts = text.split('\n');
                if(parts.length < 2) return text;

                var header = trim(parts[0], '|');
                var align = trim(parts[1], '|');
                var lines = parts.slice(2);
                var headerParts = header.split('|');
                var headerLen = headerParts.length;
                var alignParts = align.split('|');
                var alignLen = alignParts.length;
                var ast = {};

                if(headerLen < 2) return text;
                if(headerLen != alignLen) return text;
                if(all(lines.map(function(v) {return v.indexOf('|') >= 0;})))

                var align = alignParts.map(function(p) {
                    if(p[0] == ':' && p[p.length - 1] == ':') return 'center';
                    if(p[p.length - 1] == ':') return 'right';
                    return 'left';
                });
                lines = lines.map(function(line) {
                    return rtrim(line, '|').split('|');
                });

                return output(headerParts, lines, align);
            },
            toHTML: function(header, lines, align) {
                var cols = header.length;
                var h = header? '

' + header.join('	') + '

': '';
                var c = '

' + lines.map(function(v) {
                    function empty(a) {var ret = []; for(var i = 0; i < a; i++) {ret.push('');}; return ret;}
                    if(v.length != cols) v = v.concat(empty(cols - v.length));
                    return '' + v.join('	') + '	';
                }).join('

') + '

';

                return '
' + h + c + '
';
            }
        },
        bracket_pipe_link: {
            pattern: /\[\[([^\|]+)\|([^\]]+)\]\]/g,
            toHTML: function(o) {
                var suffix = o.r.match('^http')? '': '.html';

                return '' + o.l + '';
            }
        },
        pipe_link: {
            pattern: /\[([^\|]+)\|([^\]]+)\]/g,
            toHTML: function(o) {
                return '' + o.l + '';
            }
        },
        bracket_link: {
            pattern: /\[\[([^\]]+)\]\]/g,
            toHTML: function(o) {
                return '' + o.l + '';
            }
        },
        regular_link_with_whitespace: {
            pattern: /\[([^\]]+)\]\s+\(([^\)]+)\)/g,
            toHTML: function(o) {
                return '' + o.l + '';
            }
        },
        paragraphs: {
            toHTML: function(o) {
                if(o.l) return '
' + o.l.split('\n').filter(id).join('

') + '
';
            }
        }
    });

    function attachMissing(o) {
        for(var k in o) {
            var v = o[k];

            attachMatch(v);
            attachToAST(v);
        }

        function attachMatch(v) {
            if(v.match) return;

            if(v.pattern) {
                v.match = function(text, output) {
                    if(!text) return;
                    output = output || function(o) {return o;};

                    return text.replace(v.pattern, function(orig, l, r) {
                        return output(v.toAST(l, r));
                    });
                };
            }
            else {
                v.match = function(text, output) {
                    return output(v.toAST(text));
                };
            }
        }

        function attachToAST(v) {
            if(!v.toAST) {
                v.toAST = function(l, r) {
                    return {'l': l, 'r': r};
                };
            }
        }

        return o;
    }
}

function id(a) {
    return a;
}

<commit_msg>Filter out empty table lines<commit_after>var fs = require('fs');
var marked = require('marked');

exports.transform = transform;
exports.transformers = transformers();

function transform(f, data, transformers, done) {
    var ctx = {sections: []};
    var tokens = marked.lexer(data).map(function(t) {
        if(t.type == 'text' || t.type == 'paragraph') {
            var text = t.text;

            for(var k in transformers) {
                var v = transformers[k];
                text = v.match(text, v.toHTML);
            }

            return {
                type: 'text',
                text: text
            };
        }
        if(t.type == 'heading') {
            var n = t.text;
            var i = n.toLowerCase();
            ctx.sections.push({name: n, id: i});

            return {
                type: 'heading',
                depth: t.depth,
                text: '<h' + t.depth + ' id="' + i + '">' + n + '</h' + t.depth + '>'
            };
        }
        return t;
    });
    tokens.links = [];

    ctx.data = marked.parser(tokens);

    done(f, ctx);
}

// http://phpjs.org/functions/ltrim:467
function ltrim(str, charlist) {
    charlist = !charlist ? ' \\s\u00A0' : (charlist + '').replace(/([\[\]\(\)\.\?\/\*\{\}\+\$\^\:])/g, '$1');
    var re = new RegExp('^[' + charlist + ']+', 'g');
    return (str + '').replace(re, '');
}

// http://phpjs.org/functions/rtrim:507
function rtrim(str, charlist) {
    charlist = !charlist ? ' \\s\u00A0' : (charlist + '').replace(/([\[\]\(\)\.\?\/\*\{\}\+\$\^\:])/g, '\\$1');
    var re = new RegExp('[' + charlist + ']+$', 'g');
    return (str + '').replace(re, '');
}

function trim(str, charlist) {
    return rtrim(ltrim(str, charlist), charlist);
}

function all(o) {
    for(var i = 0, len = o.length; i < len; i++) {
        if(!o[i]) return false;
    }

    return true;
}

function transformers() {
    return attachMissing({
        table: {
            match: function(text, output) {
                var parts = text.split('\n');
                if(parts.length < 2) return text;

                var header = trim(parts[0], '|');
                var align = trim(parts[1], '|');
                var lines = parts.slice(2);
                var headerParts = header.split('|');
                var headerLen = headerParts.length;
                var alignParts = align.split('|');
                var alignLen = alignParts.length;
                var ast = {};

                if(headerLen < 2) return text;
                if(headerLen != alignLen) return text;
                if(all(lines.map(function(v) {return v.indexOf('|') >= 0;})))

                var align = alignParts.map(function(p) {
                    if(p[0] == ':' && p[p.length - 1] == ':') return 'center';
                    if(p[p.length - 1] == ':') return 'right';
                    return 'left';
                });
                lines = lines.map(function(line) {
                    return rtrim(line, '|').split('|');
                }).filter(function(parts) {return parts.filter(id).length > 0;});

                return output(headerParts, lines, align);
            },
            toHTML: function(header, lines, align) {
                var cols = header.length;
                var h = header? '

' + header.join('	') + '

': '';
                var c = '

' + lines.map(function(v) {
                    function empty(a) {var ret = []; for(var i = 0; i < a; i++) {ret.push('');}; return ret;}
                    if(v.length != cols) v = v.concat(empty(cols - v.length));

                    return '' + v.join('	') + '	';
                }).join('

') + '

';

                return '
' + h + c + '
';
            }
        },
        bracket_pipe_link: {
            pattern: /\[\[([^\|]+)\|([^\]]+)\]\]/g,
            toHTML: function(o) {
                var suffix = o.r.match('^http')? '': '.html';

                return '' + o.l + '';
            }
        },
        pipe_link: {
            pattern: /\[([^\|]+)\|([^\]]+)\]/g,
            toHTML: function(o) {
                return '' + o.l + '';
            }
        },
        bracket_link: {
            pattern: /\[\[([^\]]+)\]\]/g,
            toHTML: function(o) {
                return '' + o.l + '';
            }
        },
        regular_link_with_whitespace: {
            pattern: /\[([^\]]+)\]\s+\(([^\)]+)\)/g,
            toHTML: function(o) {
                return '' + o.l + '';
            }
        },
        paragraphs: {
            toHTML: function(o) {
                if(o.l) return '
' + o.l.split('\n').filter(id).join('

') + '
';
            }
        }
    });

    function attachMissing(o) {
        for(var k in o) {
            var v = o[k];

            attachMatch(v);
            attachToAST(v);
        }

        function attachMatch(v) {
            if(v.match) return;

            if(v.pattern) {
                v.match = function(text, output) {
                    if(!text) return;
                    output = output || function(o) {return o;};

                    return text.replace(v.pattern, function(orig, l, r) {
                        return output(v.toAST(l, r));
                    });
                };
            }
            else {
                v.match = function(text, output) {
                    return output(v.toAST(text));
                };
            }
        }

        function attachToAST(v) {
            if(!v.toAST) {
                v.toAST = function(l, r) {
                    return {'l': l, 'r': r};
                };
            }
        }

        return o;
    }
}

function id(a) {
    return a;
}

<|endoftext|>


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

var fs = require('fs');
var path = require('path');
var optimist = require('optimist');

optimist = optimist.boolean(['activerecord', 'a', 'form', 'f']);
optimist = optimist.string(['parent', 'p', 'table', 't']);
var args = optimist.argv;

var supported_commands = fs.readdirSync(path.join(__dirname, 'generators'));

function valid_arguments(arguments) {
  if (arguments._.length >= 2) {
    for (var i = 0; i < supported_commands.length; i++) {
      if (arguments._[0] == supported_commands[i]) {
        return true;
      }
    }
  }
  return false;
}

if (valid_arguments(args)) {
  var generator = require('./generators/' + args._[0]);
} else {
  console.log(help);
}<commit_msg>cleaned up main script<commit_after>#!/usr/bin/env node

var fs = require('fs');
var path = require('path');
var optimist = require('optimist');

optimist = optimist.boolean(['activerecord', 'a', 'form', 'f', 'help']);
optimist = optimist.string(['parent', 'p', 'table', 't']);
var args = optimist.argv;

var supported_commands = fs.readdirSync(path.join(__dirname, 'generators'));
supported_commands = supported_commands.map(function(command) {
  return command.split(/\./)[0];
});

function valid_arguments(arguments) {
  if (arguments._.length >= 2) {
    for (var i = 0; i < supported_commands.length; i++) {
      if (arguments._[0] == supported_commands[i]) {
        return true;
      }
    }
  }
  return false;
}

if (valid_arguments(args)) {
  var generator = require('./generators/' + args._[0]);
  if (args.help) {
    generator.help();
  } else {
    generator.generate(args);
  }
} else {
  var message = '\n  Invalid Usage\n\n'
    + '  to view how to use a certain command, run the following:\n\n'
    + '      gii [command] --help\n\n'
    + '  where [command] can be one of the following:\n\n'
    + '      ' + supported_commands.join('\r\n      ');

  console.log(message);
}<|endoftext|>


<commit_before>/*

jQuery Browser Plugin
	* Version 2.3
	* 2008-09-17 19:27:05
	* URL: http://jquery.thewikies.com/browser
	* Description: jQuery Browser Plugin extends browser detection capabilities and can assign browser selectors to CSS classes.
	* Author: Nate Cavanaugh, Minhchau Dang, & Jonathan Neal
	* Copyright: Copyright (c) 2008 Jonathan Neal under dual MIT/GPL license.
	* JSLint: This javascript file passes JSLint verification.
*//*jslint
		bitwise: true,
		browser: true,
		eqeqeq: true,
		forin: true,
		nomen: true,
		plusplus: true,
		undef: true,
		white: true
*//*global
		jQuery
*/

(function ($) {
	// jal 20111230 This file is no longer used!!

	$.browserTest = function (a, z) {
		var u = 'unknown', x = 'X', m = function (r, h) {
			for (var i = 0; i < h.length; i = i + 1) {
				r = r.replace(h[i][0], h[i][1]);
			}

			return r;
		}, c = function (i, a, b, c) {
			var r = {
				name: m((a.exec(i) || [u, u])[1], b)
			};

			r[r.name] = true;

			r.version = (c.exec(i) || [x, x, x, x])[3];

			if (r.name.match(/safari/) && r.version > 400) {
				r.version = '2.0';
			}

			if (r.name === 'presto') {
				r.version = ($.browser.version > 9.27) ? 'futhark' : 'linear_b';
			}
			r.versionNumber = parseFloat(r.version, 10) || 0;
			r.versionX = (r.version !== x) ? (r.version + '').substr(0, 1) : x;
			r.className = r.name + r.versionX;
			return r;
		};

		a = (a.match(/Opera|Navigator|Minefield|KHTML|Chrome/) ? m(a, [
			[/(Firefox|MSIE|KHTML,\slike\sGecko|Konqueror)/, ''],
			['Chrome Safari', 'Chrome'],
			['KHTML', 'Konqueror'],
			['Minefield', 'Firefox'],
			['Navigator', 'Netscape']
		]) : a).toLowerCase();

		$.browser = $.extend((!z) ? $.browser : {}, c(a, /(camino|chrome|firefox|netscape|konqueror|lynx|msie|opera|safari)/, [], /(camino|chrome|firefox|netscape|netscape6|opera|version|konqueror|lynx|msie|safari)(\/|\s)([a-z0-9\.\+]*?)(\;|dev|rel|\s|$)/));

		$.layout = c(a, /(gecko|konqueror|msie|opera|webkit)/, [
			['konqueror', 'khtml'],
			['msie', 'trident'],
			['opera', 'presto']
		], /(applewebkit|rv|konqueror|msie)(\:|\/|\s)([a-z0-9\.]*?)(\;|\)|\s)/);

		$.os = {
			name: (/(win|mac|linux|sunos|solaris|iphone)/.exec(navigator.platform.toLowerCase()) || [u])[0].replace('sunos', 'solaris')
		};

		if (!z) {
			$('html').addClass([$.os.name, $.browser.name, $.browser.className, $.layout.name, $.layout.className].join(' '));
		}
	};

	$.browserTest(navigator.userAgent);
})(jQuery);<commit_msg>Remove unused file.<commit_after><|endoftext|>


<commit_before>/*
 * Copyright 2013, All Rights Reserved.
 *
 * Code licensed under the BSD License:
 * https://github.com/node-gh/gh/blob/master/LICENSE.md
 *
 * @author Eduardo Lundgren <eduardolundgren@gmail.com>
 */

var base = require('./base'),
    git = require('git-wrapper'),
    toArray;

toArray = Array.prototype.slice;

exports.git = new git();

exports.checkout = function(branch, opt_newBranch, opt_callback) {
    var args;

    args = [branch];

    if (opt_newBranch) {
        args.push('-B', opt_newBranch);
    }

    exports.exec('checkout', args, function(err, data) {
        opt_callback && opt_callback(err, data);
    });
};

exports.clone = function(url, folder, opt_callback) {
    exports.exec('clone', [url, folder], function(err, data) {
        opt_callback(err, data.trim());
    });
};

exports.countUserAdjacentCommits = function(opt_callback) {
    var skip = 0,
        counter = [0];

    exports.getConfig('user.name', function(err, myUser) {
        exports.countUserAdjacentCommits_(opt_callback, skip, myUser, counter);
    });
};

exports.countUserAdjacentCommits_ = function(opt_callback, skip, myUser, counter) {
    skip = skip || 0;

    exports.exec('log', ['-1', '--skip=' + skip, '--pretty="%an"'], function(err, user) {
        if (myUser === user.trim()) {
            skip++;
            counter[0]++;
            exports.countUserAdjacentCommits_(opt_callback, skip, myUser, counter);
            return;
        }

        opt_callback(err, counter[0]);
    });
};

exports.exec = function() {
    var args;

    args = toArray.call(arguments);

    if (typeof args[args.length - 1] !== 'function') {
        args.push(function() {});
    }

    exports.git.exec.apply(exports.git, args);
};

exports.findRoot = function(opt_callback) {
    exports.exec('rev-parse', ['--show-toplevel'], function(err, data) {
        opt_callback(err, data.trim());
    });
};

exports.getConfig = function(key, opt_callback) {
    exports.exec('config', ['--get', key], function(err, data) {
        opt_callback(err, data.trim());
    });
};

exports.getCurrentBranch = function(opt_callback) {
    exports.exec('symbolic-ref', ['HEAD'], function(err, data) {
        data = data.substring(data.lastIndexOf('/') + 1);
        opt_callback(err, data.trim());
    });
};

exports.getLastCommitMessage = function(opt_branch, opt_callback) {
    exports.exec('log', ['-1', '--first-parent', '--no-merges', '--pretty=%s', opt_branch || ''],
        function(err, data) {
            opt_callback(err, data.trim());
        });
};

exports.getLastCommitSHA = function(opt_callback) {
    exports.exec('rev-parse', ['HEAD'], function(err, data) {
        opt_callback(err, data.trim());
    });
};

exports.getRemoteUrl = function(remote, opt_callback) {
    exports.getConfig('remote.' + remote + '.url', opt_callback);
};

exports.getRepoFromRemoteURL = function(url) {
    var parsed = exports.parseRemoteUrl(url);

    return parsed && parsed[1];
};

exports.getUserFromRemoteUrl = function(url) {
    var parsed = exports.parseRemoteUrl(url);

    return parsed && parsed[0];
};

exports.getRepo = function(remote, opt_callback) {
    exports.getRemoteUrl(remote, function(err, data) {
        opt_callback(err, exports.getRepoFromRemoteURL(data));
    });
};

exports.getUser = function(remote, opt_callback) {
    exports.getRemoteUrl(remote, function(err, data) {
        opt_callback(err, exports.getUserFromRemoteUrl(data));
    });
};

exports.merge = function(branch, rebase, abort, opt_callback) {
    var type;

    type = rebase ? 'rebase' : 'merge';

    exports.exec(type, [branch], function(err, data) {
        if (err) {
            console.log(data);

            if (abort) {
                exports.exec(type, ['--abort'], function() {
                    base.logger.error('unable to ' + type);
                });
            }
            return;
        }
        opt_callback && opt_callback(err, data);
    });
};

exports.parseRemoteUrl = function(url) {
    var parsed = /[\/:]([\w-]+)\/(.*?)(?:\.git)?$/.exec(url);

    if (parsed) {
        parsed.shift();
    }

    return parsed;
};
<commit_msg>Improve git getCommitMessage helper<commit_after>/*
 * Copyright 2013, All Rights Reserved.
 *
 * Code licensed under the BSD License:
 * https://github.com/node-gh/gh/blob/master/LICENSE.md
 *
 * @author Eduardo Lundgren <eduardolundgren@gmail.com>
 */

var base = require('./base'),
    git = require('git-wrapper'),
    toArray;

toArray = Array.prototype.slice;

exports.git = new git();

exports.checkout = function(branch, opt_newBranch, opt_callback) {
    var args;

    args = [branch];

    if (opt_newBranch) {
        args.push('-B', opt_newBranch);
    }

    exports.exec('checkout', args, function(err, data) {
        opt_callback && opt_callback(err, data);
    });
};

exports.clone = function(url, folder, opt_callback) {
    exports.exec('clone', [url, folder], function(err, data) {
        opt_callback(err, data.trim());
    });
};

exports.countUserAdjacentCommits = function(opt_callback) {
    var skip = 0,
        counter = [0];

    exports.getConfig('user.name', function(err, myUser) {
        exports.countUserAdjacentCommits_(opt_callback, skip, myUser, counter);
    });
};

exports.countUserAdjacentCommits_ = function(opt_callback, skip, myUser, counter) {
    skip = skip || 0;

    exports.exec('log', ['-1', '--skip=' + skip, '--pretty="%an"'], function(err, user) {
        if (myUser === user.trim()) {
            skip++;
            counter[0]++;
            exports.countUserAdjacentCommits_(opt_callback, skip, myUser, counter);
            return;
        }

        opt_callback(err, counter[0]);
    });
};

exports.exec = function() {
    var args;

    args = toArray.call(arguments);

    if (typeof args[args.length - 1] !== 'function') {
        args.push(function() {});
    }

    exports.git.exec.apply(exports.git, args);
};

exports.findRoot = function(opt_callback) {
    exports.exec('rev-parse', ['--show-toplevel'], function(err, data) {
        opt_callback(err, data.trim());
    });
};

exports.getCommitMessage = function(opt_branch, opt_number, opt_callback) {
    opt_number = opt_number || 1;

    exports.exec('log', ['-' + opt_number, '--first-parent', '--no-merges', '--pretty=%s', opt_branch || ''],
        function(err, data) {
            opt_callback(err, data.trim());
        });
};

exports.getConfig = function(key, opt_callback) {
    exports.exec('config', ['--get', key], function(err, data) {
        opt_callback(err, data.trim());
    });
};

exports.getCurrentBranch = function(opt_callback) {
    exports.exec('symbolic-ref', ['HEAD'], function(err, data) {
        data = data.substring(data.lastIndexOf('/') + 1);
        opt_callback(err, data.trim());
    });
};

exports.getLastCommitMessage = function(opt_branch, opt_callback) {
    exports.getCommitMessage(opt_branch, 1, opt_callback);
};

exports.getLastCommitSHA = function(opt_callback) {
    exports.exec('rev-parse', ['--short', 'HEAD'], function(err, data) {
        opt_callback(err, data.trim());
    });
};

exports.getRemoteUrl = function(remote, opt_callback) {
    exports.getConfig('remote.' + remote + '.url', opt_callback);
};

exports.getRepoFromRemoteURL = function(url) {
    var parsed = exports.parseRemoteUrl(url);

    return parsed && parsed[1];
};

exports.getUserFromRemoteUrl = function(url) {
    var parsed = exports.parseRemoteUrl(url);

    return parsed && parsed[0];
};

exports.getRepo = function(remote, opt_callback) {
    exports.getRemoteUrl(remote, function(err, data) {
        opt_callback(err, exports.getRepoFromRemoteURL(data));
    });
};

exports.getUser = function(remote, opt_callback) {
    exports.getRemoteUrl(remote, function(err, data) {
        opt_callback(err, exports.getUserFromRemoteUrl(data));
    });
};

exports.merge = function(branch, rebase, abort, opt_callback) {
    var type;

    type = rebase ? 'rebase' : 'merge';

    exports.exec(type, [branch], function(err, data) {
        if (err) {
            console.log(data);

            if (abort) {
                exports.exec(type, ['--abort'], function() {
                    base.logger.error('unable to ' + type);
                });
            }
            return;
        }
        opt_callback && opt_callback(err, data);
    });
};

exports.parseRemoteUrl = function(url) {
    var parsed = /[\/:]([\w-]+)\/(.*?)(?:\.git)?$/.exec(url);

    if (parsed) {
        parsed.shift();
    }

    return parsed;
};
<|endoftext|>


<commit_before>const { hasOwnProperty } = Object.prototype

/* istanbul ignore next */
const eol = typeof process !== 'undefined' &&
  process.platform === 'win32' ? '\r\n' : '\n'

const encode = (obj, opt) => {
  const children = []
  let out = ''

  if (typeof opt === 'string') {
    opt = {
      section: opt,
      whitespace: false,
    }
  } else {
    opt = opt || Object.create(null)
    opt.whitespace = opt.whitespace === true
  }

  const separator = opt.whitespace ? ' = ' : '='

  for (const k of Object.keys(obj)) {
    const val = obj[k]
    if (val && Array.isArray(val)) {
      for (const item of val) {
        out += safe(k + '[]') + separator + safe(item) + eol
      }
    } else if (val && typeof val === 'object') {
      children.push(k)
    } else {
      out += safe(k) + separator + safe(val) + eol
    }
  }

  if (opt.section && out.length) {
    out = '[' + safe(opt.section) + ']' + eol + out
  }

  for (const k of children) {
    const nk = dotSplit(k).join('\\.')
    const section = (opt.section ? opt.section + '.' : '') + nk
    const { whitespace } = opt
    const child = encode(obj[k], {
      section,
      whitespace,
    })
    if (out.length && child.length) {
      out += eol
    }

    out += child
  }

  return out
}

const dotSplit = str =>
  str.replace(/\1/g, '\u0002LITERAL\\1LITERAL\u0002')
    .replace(/\\\./g, '\u0001')
    .split(/\./)
    .map(part =>
      part.replace(/\1/g, '\\.')
        .replace(/\2LITERAL\\1LITERAL\2/g, '\u0001'))

const decode = str => {
  const out = Object.create(null)
  let p = out
  let section = null
  //          section     |key      = value
  const re = /^\[([^\]]*)\]$|^([^=]+)(=(.*))?$/i
  const lines = str.split(/[\r\n]+/g)

  for (const line of lines) {
    if (!line || line.match(/^\s*[;#]/)) {
      continue
    }
    const match = line.match(re)
    if (!match) {
      continue
    }
    if (match[1] !== undefined) {
      section = unsafe(match[1])
      if (section === '__proto__') {
        // not allowed
        // keep parsing the section, but don't attach it.
        p = Object.create(null)
        continue
      }
      p = out[section] = out[section] || Object.create(null)
      continue
    }
    const keyRaw = unsafe(match[2])
    const isArray = keyRaw.length > 2 && keyRaw.slice(-2) === '[]'
    const key = isArray ? keyRaw.slice(0, -2) : keyRaw
    if (key === '__proto__') {
      continue
    }
    const valueRaw = match[3] ? unsafe(match[4]) : true
    const value = valueRaw === 'true' ||
      valueRaw === 'false' ||
      valueRaw === 'null' ? JSON.parse(valueRaw)
      : valueRaw

    // Convert keys with '[]' suffix to an array
    if (isArray) {
      if (!hasOwnProperty.call(p, key)) {
        p[key] = []
      } else if (!Array.isArray(p[key])) {
        p[key] = [p[key]]
      }
    }

    // safeguard against resetting a previously defined
    // array by accidentally forgetting the brackets
    if (Array.isArray(p[key])) {
      p[key].push(value)
    } else {
      p[key] = value
    }
  }

  // {a:{y:1},"a.b":{x:2}} --> {a:{y:1,b:{x:2}}}
  // use a filter to return the keys that have to be deleted.
  const remove = []
  for (const k of Object.keys(out)) {
    if (!hasOwnProperty.call(out, k) ||
        typeof out[k] !== 'object' ||
        Array.isArray(out[k])) {
      continue
    }

    // see if the parent section is also an object.
    // if so, add it to that, and mark this one for deletion
    const parts = dotSplit(k)
    p = out
    const l = parts.pop()
    const nl = l.replace(/\\\./g, '.')
    for (const part of parts) {
      if (part === '__proto__') {
        continue
      }
      if (!hasOwnProperty.call(p, part) || typeof p[part] !== 'object') {
        p[part] = Object.create(null)
      }
      p = p[part]
    }
    if (p === out && nl === l) {
      continue
    }

    p[nl] = out[k]
    remove.push(k)
  }
  for (const del of remove) {
    delete out[del]
  }

  return out
}

const isQuoted = val => {
  return (val.startsWith('"') && val.endsWith('"')) ||
    (val.startsWith("'") && val.endsWith("'"))
}

const safe = val => {
  if (
    typeof val !== 'string' ||
    val.match(/[=\r\n]/) ||
    val.match(/^\[/) ||
    (val.length > 1 && isQuoted(val)) ||
    val !== val.trim()
  ) {
    return JSON.stringify(val)
  }
  return val.split(';').join('\\;').split('#').join('\\#')
}

const unsafe = (val, doUnesc) => {
  val = (val || '').trim()
  if (isQuoted(val)) {
    // remove the single quotes before calling JSON.parse
    if (val.charAt(0) === "'") {
      val = val.substr(1, val.length - 2)
    }

    try {
      val = JSON.parse(val)
    } catch (_) {}
  } else {
    // walk the val to find the first not-escaped ; character
    let esc = false
    let unesc = ''
    for (let i = 0, l = val.length; i < l; i++) {
      const c = val.charAt(i)
      if (esc) {
        if ('\\;#'.indexOf(c) !== -1) {
          unesc += c
        } else {
          unesc += '\\' + c
        }

        esc = false
      } else if (';#'.indexOf(c) !== -1) {
        break
      } else if (c === '\\') {
        esc = true
      } else {
        unesc += c
      }
    }
    if (esc) {
      unesc += '\\'
    }

    return unesc.trim()
  }
  return val
}

module.exports = {
  parse: decode,
  decode,
  stringify: encode,
  encode,
  safe,
  unsafe,
}
<commit_msg>fix: replace deprecated String.prototype.substr() (#155)<commit_after>const { hasOwnProperty } = Object.prototype

/* istanbul ignore next */
const eol = typeof process !== 'undefined' &&
  process.platform === 'win32' ? '\r\n' : '\n'

const encode = (obj, opt) => {
  const children = []
  let out = ''

  if (typeof opt === 'string') {
    opt = {
      section: opt,
      whitespace: false,
    }
  } else {
    opt = opt || Object.create(null)
    opt.whitespace = opt.whitespace === true
  }

  const separator = opt.whitespace ? ' = ' : '='

  for (const k of Object.keys(obj)) {
    const val = obj[k]
    if (val && Array.isArray(val)) {
      for (const item of val) {
        out += safe(k + '[]') + separator + safe(item) + eol
      }
    } else if (val && typeof val === 'object') {
      children.push(k)
    } else {
      out += safe(k) + separator + safe(val) + eol
    }
  }

  if (opt.section && out.length) {
    out = '[' + safe(opt.section) + ']' + eol + out
  }

  for (const k of children) {
    const nk = dotSplit(k).join('\\.')
    const section = (opt.section ? opt.section + '.' : '') + nk
    const { whitespace } = opt
    const child = encode(obj[k], {
      section,
      whitespace,
    })
    if (out.length && child.length) {
      out += eol
    }

    out += child
  }

  return out
}

const dotSplit = str =>
  str.replace(/\1/g, '\u0002LITERAL\\1LITERAL\u0002')
    .replace(/\\\./g, '\u0001')
    .split(/\./)
    .map(part =>
      part.replace(/\1/g, '\\.')
        .replace(/\2LITERAL\\1LITERAL\2/g, '\u0001'))

const decode = str => {
  const out = Object.create(null)
  let p = out
  let section = null
  //          section     |key      = value
  const re = /^\[([^\]]*)\]$|^([^=]+)(=(.*))?$/i
  const lines = str.split(/[\r\n]+/g)

  for (const line of lines) {
    if (!line || line.match(/^\s*[;#]/)) {
      continue
    }
    const match = line.match(re)
    if (!match) {
      continue
    }
    if (match[1] !== undefined) {
      section = unsafe(match[1])
      if (section === '__proto__') {
        // not allowed
        // keep parsing the section, but don't attach it.
        p = Object.create(null)
        continue
      }
      p = out[section] = out[section] || Object.create(null)
      continue
    }
    const keyRaw = unsafe(match[2])
    const isArray = keyRaw.length > 2 && keyRaw.slice(-2) === '[]'
    const key = isArray ? keyRaw.slice(0, -2) : keyRaw
    if (key === '__proto__') {
      continue
    }
    const valueRaw = match[3] ? unsafe(match[4]) : true
    const value = valueRaw === 'true' ||
      valueRaw === 'false' ||
      valueRaw === 'null' ? JSON.parse(valueRaw)
      : valueRaw

    // Convert keys with '[]' suffix to an array
    if (isArray) {
      if (!hasOwnProperty.call(p, key)) {
        p[key] = []
      } else if (!Array.isArray(p[key])) {
        p[key] = [p[key]]
      }
    }

    // safeguard against resetting a previously defined
    // array by accidentally forgetting the brackets
    if (Array.isArray(p[key])) {
      p[key].push(value)
    } else {
      p[key] = value
    }
  }

  // {a:{y:1},"a.b":{x:2}} --> {a:{y:1,b:{x:2}}}
  // use a filter to return the keys that have to be deleted.
  const remove = []
  for (const k of Object.keys(out)) {
    if (!hasOwnProperty.call(out, k) ||
        typeof out[k] !== 'object' ||
        Array.isArray(out[k])) {
      continue
    }

    // see if the parent section is also an object.
    // if so, add it to that, and mark this one for deletion
    const parts = dotSplit(k)
    p = out
    const l = parts.pop()
    const nl = l.replace(/\\\./g, '.')
    for (const part of parts) {
      if (part === '__proto__') {
        continue
      }
      if (!hasOwnProperty.call(p, part) || typeof p[part] !== 'object') {
        p[part] = Object.create(null)
      }
      p = p[part]
    }
    if (p === out && nl === l) {
      continue
    }

    p[nl] = out[k]
    remove.push(k)
  }
  for (const del of remove) {
    delete out[del]
  }

  return out
}

const isQuoted = val => {
  return (val.startsWith('"') && val.endsWith('"')) ||
    (val.startsWith("'") && val.endsWith("'"))
}

const safe = val => {
  if (
    typeof val !== 'string' ||
    val.match(/[=\r\n]/) ||
    val.match(/^\[/) ||
    (val.length > 1 && isQuoted(val)) ||
    val !== val.trim()
  ) {
    return JSON.stringify(val)
  }
  return val.split(';').join('\\;').split('#').join('\\#')
}

const unsafe = (val, doUnesc) => {
  val = (val || '').trim()
  if (isQuoted(val)) {
    // remove the single quotes before calling JSON.parse
    if (val.charAt(0) === "'") {
      val = val.slice(1, -1)
    }
    try {
      val = JSON.parse(val)
    } catch (_) {}
  } else {
    // walk the val to find the first not-escaped ; character
    let esc = false
    let unesc = ''
    for (let i = 0, l = val.length; i < l; i++) {
      const c = val.charAt(i)
      if (esc) {
        if ('\\;#'.indexOf(c) !== -1) {
          unesc += c
        } else {
          unesc += '\\' + c
        }

        esc = false
      } else if (';#'.indexOf(c) !== -1) {
        break
      } else if (c === '\\') {
        esc = true
      } else {
        unesc += c
      }
    }
    if (esc) {
      unesc += '\\'
    }

    return unesc.trim()
  }
  return val
}

module.exports = {
  parse: decode,
  decode,
  stringify: encode,
  encode,
  safe,
  unsafe,
}
<|endoftext|>


<commit_before>var Hook = require('hook.io').Hook,
    prompt = require('prompt'),
    ircModule = require('irc'),
    util = require('util');

var IRC = exports.IRC = function(options){
  for (var o in options) {
    this[o] = options[o];
  }
  Hook.call(this);
  var self = this;
  prompt.start();
  prompt.pause();
  self.on('ready', function(){

    self.ircClient = new ircModule.Client(
      self.server,
      self.nick,
      self.channels,
      self.showErrors,
      self.userName,
      self.realName
    );

    self.ircClient.on('motd', function (motd) {
      self.emit('o.ircConnect', 'Connected successfully!');
      console.log('hook.io-irc has successfully connected to IRC.');
      shell();
    });

    self.ircClient.on('invite', function (channel, from) {
      self.ircClient.join(channel, function () {
        self.ircClient.say(from, 'Thanks for the invite!');
      });
    });

    self.ircClient.on('error',function() {
      console.log(arguments);
      self.emit('o.IRCdError', arguments);
    });

    self.ircClient.on('join',function(channel, nick) {
      console.log(nick, ' has joined ', channel);
      self.emit('o.userJoined', channel, nick);
    });

    self.ircClient.on('part',function(channel, nick, reason) {
      console.log(nick, ' has left ', channel, ': ', reason);
      self.emit('o.userParted', channel, nick, reason);
    });

    self.ircClient.on('message',function(nick, to, text) {
      console.log(nick, ': ', to, ': ', text);
      self.emit('o.message', nick, to, text);
    });

    self.on('i.say.o.say', function (fullEvent, event, dest, msg) {
      self.ircClient.say(dest, msg);
      self.emit('o.msgSent', 'Message has been sent!');
    });

    self.on('i.command.o.command', function (fullEvent, event, command) {
      self.ircClient.send(command.join(' '));
      self.emit('o.commandSent');
    });

    self.on('i.join.o.join', function (fullEvent, event, channel) {
      self.ircClient.join(channel, function () {
        self.emit('o.Ijoined', channel);
      });
    });

    self.on('i.part.o.part', function (fullEvent, event, channel) {
      self.ircClient.part(channel, function () {
        self.emit('o.Iparted', channel);
      });
    });

    function shell() {
      var properties = {
            message: 'Hook.io-IRC>',
            name: 'command'
          },
          msg;
      prompt.resume();
      prompt.get(properties, function (err, results) {
        prompt.pause();
        if (err) { return console.log(err.stack); }
        var command = results.command.split(' ');
        switch (command[0]) {
          case 'say':
            command.shift();
            msg = command.slice(1).join(' ');
            self.ircClient.say(command[0], msg);
            self.emit('o.said', msg);
            shell();
            break;
          case 'join':
            command.shift();
            self.ircClient.join(command[0], function () {
              console.log('Joined: ', command[0]);
              self.emit('o.joined', command[0]);
            });
            shell();
            break;
          case 'part':
            command.shift();
            self.ircClient.part(command[0], function () {
              console.log('Left: ', command[0]);
              self.emit('o.parted', command[0]);
            });
            shell();
            break;
          case 'command':
            command.shift();
            self.ircClient.send(command.join(' '));
            self.emit('o.commandSent');
            shell();
            break;
          case 'exit':
            console.log('Goodbye!');
            self.ircClient.disconnect('http://github.com/AvianFlu/hook.io-irc');
            process.exit();
            break;
          default:
            console.log('Sorry, I do not understand.');
            shell();
            break;
        }
      });
    }
  });
};
util.inherits(IRC, Hook);

<commit_msg>[api] Added more events<commit_after>var Hook = require('hook.io').Hook,
    prompt = require('prompt'),
    ircModule = require('irc'),
    util = require('util');

var IRC = exports.IRC = function(options){
  for (var o in options) {
    this[o] = options[o];
  }
  Hook.call(this);
  var self = this;
  prompt.start();
  prompt.pause();
  self.on('ready', function(){

    self.ircClient = new ircModule.Client(
      self.server,
      self.nick,
      self.channels,
      self.showErrors,
      self.userName,
      self.realName
    );

    self.ircClient.on('motd', function (motd) {
      self.emit('o.ircConnect', 'Connected successfully!');
      console.log('hook.io-irc has successfully connected to IRC.');
      shell();
    });

    self.ircClient.on('invite', function (channel, from) {
      self.ircClient.join(channel, function () {
        self.ircClient.say(from, 'Thanks for the invite!');
      });
    });

    self.ircClient.on('error',function () {
      console.log(arguments);
      self.emit('o.IRCdError', arguments);
    });

    self.ircClient.on('join',function (channel, nick) {
      console.log(nick, ' has joined ', channel);
      self.emit('o.userJoined', channel, nick);
    });

    self.ircClient.on('part',function (channel, nick, reason) {
      console.log(nick, ' has left ', channel, ': ', reason);
      self.emit('o.userParted', channel, nick, reason);
    });

    self.ircClient.on('nick', function (oldNick, newNick, channels) {
      console.log(oldNick + ' is now known as ' + newNick);
      self.emit('o.nickChange', oldNick, newNick);
    });

    self.ircClient.on('quit', function (nick, reason, channels) {
      console.log(nick + ' has quit: ' + reason);
      self.emit('o.userQuit', nick, reason);
    });

    self.ircClient.on('message',function (nick, to, text) {
      console.log(nick, ': ', to, ': ', text);
      self.emit('o.message', nick, to, text);
    });

    self.on('i.say.o.say', function (fullEvent, event, dest, msg) {
      self.ircClient.say(dest, msg);
      self.emit('o.msgSent', 'Message has been sent!');
    });

    self.on('i.command.o.command', function (fullEvent, event, command) {
      self.ircClient.send(command.join(' '));
      self.emit('o.commandSent');
    });

    self.on('i.join.o.join', function (fullEvent, event, channel) {
      self.ircClient.join(channel, function () {
        self.emit('o.Ijoined', channel);
      });
    });

    self.on('i.part.o.part', function (fullEvent, event, channel) {
      self.ircClient.part(channel, function () {
        self.emit('o.Iparted', channel);
      });
    });

    function shell() {
      var properties = {
            message: 'Hook.io-IRC>',
            name: 'command'
          },
          msg;
      prompt.resume();
      prompt.get(properties, function (err, results) {
        prompt.pause();
        if (err) { return console.log(err.stack); }
        var command = results.command.split(' ');
        switch (command[0]) {
          case 'say':
            command.shift();
            msg = command.slice(1).join(' ');
            self.ircClient.say(command[0], msg);
            self.emit('o.said', msg);
            shell();
            break;
          case 'join':
            command.shift();
            self.ircClient.join(command[0], function () {
              console.log('Joined: ', command[0]);
              self.emit('o.Ijoined', command[0]);
            });
            shell();
            break;
          case 'part':
            command.shift();
            self.ircClient.part(command[0], function () {
              console.log('Left: ', command[0]);
              self.emit('o.Iparted', command[0]);
            });
            shell();
            break;
          case 'command':
            command.shift();
            self.ircClient.send(command[0], command.slice(1).join(' '));
            self.emit('o.commandSent');
            shell();
            break;
          case 'exit':
            console.log('Goodbye!');
            self.ircClient.disconnect('http://github.com/AvianFlu/hook.io-irc');
            process.exit();
            break;
          default:
            console.log('Sorry, I do not understand.');
            shell();
            break;
        }
      });
    }
  });
};
util.inherits(IRC, Hook);

<|endoftext|>


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

'use strict'

const as = require('bindings')('aerospike.node')
const Commands = require('./commands')

const DEFAULT_POLL_INTERVALL = 1000

/**
 * @class Job
 * @classdesc Potentially long-running background job.
 *
 * @see {@link Scan#background}
 * @see {@link Query#background}
 */
function Job (client, jobID, module) {
  this.client = client
  this.jobID = jobID
  this.module = module
}

Job.safeRandomJobID = function () {
  return Math.floor(Math.random() * Number.MAX_SAFE_INTEGER)
}

/**
 * Repeatedly execute the given status function until it either indicates that
 * the job has completed or returns an error.
 *
 * @returns {Promise}
 *
 * @private
 */
Job.pollUntilDone = function (statusFunction, pollInterval) {
  pollInterval = pollInterval || DEFAULT_POLL_INTERVALL

  return new Promise((resolve, reject) => {
    let timer = null
    let poll = function () {
      statusFunction()
        .then(done => {
          if (done) {
            if (timer) clearInterval(timer)
            resolve()
          } else if (!timer) {
            timer = setInterval(poll, pollInterval)
          }
        })
        .catch(error => {
          if (timer) clearInterval(timer)
          reject(error)
        })
    }
    poll()
  })
}

/**
 * @private
 */
Job.prototype.hasCompleted = function (info) {
  return (info.status === as.jobStatus.COMPLETED)
}

/**
 * Fetch job info once to check if the job has completed.
 *
 * @returns {Promise}
 *
 * @private
 */
Job.prototype.checkStatus = function () {
  return this.info().then(info => this.hasCompleted(info))
}

/**
 * @function Job#info
 *
 * @summary Check the progress of a background job running on the database.
 *
 * @param {number} [pollInterval=1000] - Interval in milliseconds to use when polling the cluster nodes.
 * @param {Client~InfoPolicy} [policy] - The Info Policy to use for this operation.
 * @param {Job~infoCallback} [callback] - The function to call with the job info response.
 *
 * @return {?Promise} If no callback function is passed, the function returns a
 * Promise that resolves to the job info.
 *
 * @example
 *
 * const Aerospike = require('aerospike')
 *
 * Aerospike.connect((error, client) => {
 *   if (error) throw error
 *
 *   var scan = client.scan('test', 'demo')
 *   scan.background('myUdfModule', 'myUdfFunction', (error, job) => {
 *     if (error) throw error
 *     var timer = setInterval(() => {
 *       job.info((error, info) => {
 *         if (error) throw error
 *         console.info('scan status: %d (%d%% complete, %d records scanned)', info.status, info.progressPct, info.recordsRead)
 *         if (info.status === Aerospike.jobStatus.COMPLETED) {
 *           console.info('scan completed!')
 *           clearInterval(timer)
 *           client.close()
 *         }
 *       })
 *     }, 1000)
 *   })
 * })
 */
Job.prototype.info = function (policy, callback) {
  if (typeof policy === 'function') {
    callback = policy
    policy = null
  }

  let cmd = new Commands.JobInfo(this.client, [this.jobID, this.module, policy], callback)
  return cmd.execute()
}

/**
 * @function Job#wait
 *
 * @summary Wait until the task has been completed.
 *
 * @param {number} [pollInterval=1000] - Interval in milliseconds to use when polling the cluster nodes.
 * @param {Job~doneCallback} [callback] - The function to call when the task has completed.
 *
 * @return {?Promise} If no callback function is passed, the function returns a
 * Promise that resolves once the job is completed.
 */
Job.prototype.wait = function (pollInterval, callback) {
  if (typeof pollInterval === 'function') {
    callback = pollInterval
    pollInterval = null
  }
  var checkStatus = this.checkStatus.bind(this)

  if (typeof callback === 'function') {
    Job.pollUntilDone(checkStatus, pollInterval)
      .then(result => callback(null, result))
      .catch(error => callback(error))
  } else {
    return Job.pollUntilDone(checkStatus, pollInterval)
  }
}

Job.prototype.waitUntilDone = Job.prototype.wait

/**
 * @callback Job~doneCallback
 *
 * @summary Callback function called when a job has completed.
 *
 * @param {?AerospikeError} error - The error code and message or null if the operation was successful.
 */

/**
 * @callback Job~infoCallback
 *
 * @summary The function called with the job info response.
 *
 * @param {?AerospikeError} error - The error code and message or null if the operation was successful.
 * @param {object} [info] - The job info.
 * @param {number} [info.status] - Status of the job. See {@link module:aerospike.jobStatus}.
 * @param {number} [info.progressPct] - Progress estimate for the job, as percentage.
 * @param {number} [info.recordsRead] - How many records have been processed.
 */

module.exports = Job
<commit_msg>[docs]: Remove docs for non-existent pollInterval param<commit_after>// *****************************************************************************
// Copyright 2013-2018 Aerospike, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License")
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// *****************************************************************************

'use strict'

const as = require('bindings')('aerospike.node')
const Commands = require('./commands')

const DEFAULT_POLL_INTERVALL = 1000

/**
 * @class Job
 * @classdesc Potentially long-running background job.
 *
 * @see {@link Scan#background}
 * @see {@link Query#background}
 */
function Job (client, jobID, module) {
  this.client = client
  this.jobID = jobID
  this.module = module
}

Job.safeRandomJobID = function () {
  return Math.floor(Math.random() * Number.MAX_SAFE_INTEGER)
}

/**
 * Repeatedly execute the given status function until it either indicates that
 * the job has completed or returns an error.
 *
 * @returns {Promise}
 *
 * @private
 */
Job.pollUntilDone = function (statusFunction, pollInterval) {
  pollInterval = pollInterval || DEFAULT_POLL_INTERVALL

  return new Promise((resolve, reject) => {
    let timer = null
    let poll = function () {
      statusFunction()
        .then(done => {
          if (done) {
            if (timer) clearInterval(timer)
            resolve()
          } else if (!timer) {
            timer = setInterval(poll, pollInterval)
          }
        })
        .catch(error => {
          if (timer) clearInterval(timer)
          reject(error)
        })
    }
    poll()
  })
}

/**
 * @private
 */
Job.prototype.hasCompleted = function (info) {
  return (info.status === as.jobStatus.COMPLETED)
}

/**
 * Fetch job info once to check if the job has completed.
 *
 * @returns {Promise}
 *
 * @private
 */
Job.prototype.checkStatus = function () {
  return this.info().then(info => this.hasCompleted(info))
}

/**
 * @function Job#info
 *
 * @summary Check the progress of a background job running on the database.
 *
 * @param {Client~InfoPolicy} [policy] - The Info Policy to use for this operation.
 * @param {Job~infoCallback} [callback] - The function to call with the job info response.
 *
 * @return {?Promise} If no callback function is passed, the function returns a
 * Promise that resolves to the job info.
 *
 * @example
 *
 * const Aerospike = require('aerospike')
 *
 * Aerospike.connect((error, client) => {
 *   if (error) throw error
 *
 *   var scan = client.scan('test', 'demo')
 *   scan.background('myUdfModule', 'myUdfFunction', (error, job) => {
 *     if (error) throw error
 *     var timer = setInterval(() => {
 *       job.info((error, info) => {
 *         if (error) throw error
 *         console.info('scan status: %d (%d%% complete, %d records scanned)', info.status, info.progressPct, info.recordsRead)
 *         if (info.status === Aerospike.jobStatus.COMPLETED) {
 *           console.info('scan completed!')
 *           clearInterval(timer)
 *           client.close()
 *         }
 *       })
 *     }, 1000)
 *   })
 * })
 */
Job.prototype.info = function (policy, callback) {
  if (typeof policy === 'function') {
    callback = policy
    policy = null
  }

  let cmd = new Commands.JobInfo(this.client, [this.jobID, this.module, policy], callback)
  return cmd.execute()
}

/**
 * @function Job#wait
 *
 * @summary Wait until the task has been completed.
 *
 * @param {number} [pollInterval=1000] - Interval in milliseconds to use when polling the cluster nodes.
 * @param {Job~doneCallback} [callback] - The function to call when the task has completed.
 *
 * @return {?Promise} If no callback function is passed, the function returns a
 * Promise that resolves once the job is completed.
 */
Job.prototype.wait = function (pollInterval, callback) {
  if (typeof pollInterval === 'function') {
    callback = pollInterval
    pollInterval = null
  }
  var checkStatus = this.checkStatus.bind(this)

  if (typeof callback === 'function') {
    Job.pollUntilDone(checkStatus, pollInterval)
      .then(result => callback(null, result))
      .catch(error => callback(error))
  } else {
    return Job.pollUntilDone(checkStatus, pollInterval)
  }
}

Job.prototype.waitUntilDone = Job.prototype.wait

/**
 * @callback Job~doneCallback
 *
 * @summary Callback function called when a job has completed.
 *
 * @param {?AerospikeError} error - The error code and message or null if the operation was successful.
 */

/**
 * @callback Job~infoCallback
 *
 * @summary The function called with the job info response.
 *
 * @param {?AerospikeError} error - The error code and message or null if the operation was successful.
 * @param {object} [info] - The job info.
 * @param {number} [info.status] - Status of the job. See {@link module:aerospike.jobStatus}.
 * @param {number} [info.progressPct] - Progress estimate for the job, as percentage.
 * @param {number} [info.recordsRead] - How many records have been processed.
 */

module.exports = Job
<|endoftext|>


<commit_before>var setup = require('./tessel/provision');

module.exports = function(opts) {
  return new Promise( function (resolve, reject) {
    setup.setupLocal(function(err, created) {
      if (!created) {
        reject(new Error('Key already exists. No new key created.'));
      }
      else {
        resolve();
      }
    });
  });
}
<commit_msg>name fix<commit_after>var provision = require('./tessel/provision');

module.exports = function(opts) {
  return new Promise( function (resolve, reject) {
    provision.setupLocal(function(err, created) {
      if (!created) {
        reject(new Error('Key already exists. No new key created.'));
      }
      else {
        resolve();
      }
    });
  });
}
<|endoftext|>


<commit_before>
'use strict';

const E2EBridge = require('e2e-bridge-lib');
const path = require('path');

const XUML_SERVICE_TYPE = 'xUML';
const NODE_SERVICE_TYPE = 'node';
const JAVA_SERVICE_TYPE = 'java';

const operations = Object.freeze({
    START: "start",
    STOP: "stop",
    KILL: "kill",
    REMOVE: "remove",
    DEPLOY: "deploy",
    PACK: "pack",
    SETTINGS: "settings",
    PREFERENCES: "preferences",
    MODELNOTES: "modelnotes",
    SERVICES: "services",
    STATUS: "status",
});
module.exports.operations = operations;

const deploymentOptions = Object.freeze({
    STARTUP: "startup",
    OVERWRITE: "overwrite",
    SETTINGS: "overwritePrefs",
    NPM_SCRIPTS: "runScripts",
    NPM_INSTALL: "npmInstall",
    INSTANCE_NAME: "instanceName"
});
module.exports.deploymentOptions = deploymentOptions;

const defaultDeploymentOptions = Object.freeze({
    startup: false,
    overwrite: false,
    overwritePrefs: false,
    npmInstall: false,
    runScripts: false,
    instanceName: undefined,
});
module.exports.defaultDeploymentOptions = defaultDeploymentOptions;

function helpText(message) {

    let help = '';

    if( message){
        help = message + '\n';
    }

    help +=
        'Usage:\n' +
        'services [[-n|--nodejs]|[-j|--java]] [settings]\n' +
        'start|stop|remove ${ServiceName} [[-n|--nodejs]|[-j|--java]] [settings]\n' +
        'kill ${ServiceName} [settings]\n' +
        'status ${ServiceName} [settings]\n' +
        'deploy [${path/to/repository}|${path/to/directory}] [settings] [-o option]...\n'+
        'pack [${path/to/directory}] [${path/to/repository}] [-g|--git] [-s|--shrinkwrap]\n'+
        'preferences ${ServiceName} [pref ${PreferenceName} ${PreferenceValue}]... [settings]\n' +
        'settings ${ServiceName} [set ${SettingsName} ${SettingValue}]... [settings]\n' +
        'modelnotes ${ServiceName} [${NotesFileName}] [settings]\n' +
        '--help\n\n' +
        'settings:\n' +
        '\t-h|--host <FQDN bridge host> The host, that runs the bridge. Defaults to localhost.\n' +
        '\t-p|--port <bridge port> The port of the bridge. Defaults to 8080.\n' +
        "\t-u|--user <bridge user> User that has the right to perform operation on bridge.\n" +
        "\t\tRequired. If not given, you'll be prompted for it.\n" +
        "\t-P|--password <password for bridge user> Password for the user.\n" +
        "\t\tRequired. If not given, you'll prompted for it, what is recommended as giving your password\n" +
        "\t\tin command line will expose it in your shell's history. Password is masked during prompt.\n\n" +
        'options:\n' +
        '\tstartup|overwrite|settings Multiple options can be separated by comma, like: "-o startup,overwrite"+\n' +
        '\t\tstartup: Launch service after deployment.\n' +
        '\t\toverwrite: Overwrite existing service if one already exists.\n' +
        '\t\toverwritePrefs: Overwrite settings and preferences too.\n' +
        "\t\tnpmInstall: Run 'npm install' (Applies to Node.js services only).\n" +
        "\t\trunScripts: Run 'npm install' (running scripts too) (Applies to Node.js services only).\n" +
        "\tinstanceName=<instance name>: Choose a different instance name  (applies to Node.js services only)\n\n" +
        'Other:\n' +
        '\t-n|--nodejs Assume that the service is a Node.js service. This is ignored for "deploy" and illegal for "kill".\n\n\n' +
        '\t-j|--java Assume that the service is a Java service. This is ignored for "deploy" and illegal for "kill".\n\n\n' +
        '\t-g|--git Use "git archive" for building the repository. This is ignored for all commands but "pack".\n\n\n' +
        '\t-s|--shrinkwrap Execute "npm shrinkwrap" before creating the repository. This is ignored for all commands but "pack".\n\n\n';

    return help;
}

module.exports.helpText = helpText;

function incorrectNbOfArgs(){
    return helpText('Incorrect number of arguments');
}

function unknownOp(op){
    return helpText('Unknown operation "' + op + '"');
}

module.exports.processOperation = function(positionalArguments) {

    let requiredProperties = {user: {required: true}, password: {required: true, hidden: true}};
    let error = undefined;
    const operation = ('' + positionalArguments[0]).toLowerCase();

    function checkNbOfArgs(chk) {
        return chk(positionalArguments.length) ? undefined : incorrectNbOfArgs();
    }

    switch (operation) {
        case operations.START:
        case operations.STOP:
        case operations.KILL:
        case operations.REMOVE:
        case operations.STATUS:
            error = checkNbOfArgs(n => n === 2);
            break;

        case operations.DEPLOY:
            error = checkNbOfArgs(n => n <= 2);
            break;
        case operations.PACK:
            error = checkNbOfArgs(n => n >= 2 && n <= 3);
            requiredProperties = {};
            break;
        case operations.SETTINGS:
        case operations.PREFERENCES:
            error = checkNbOfArgs(n => n >= 2 && (n - 2) % 3 === 0);
            break;
        case operations.MODELNOTES:
            error = checkNbOfArgs(n => n >= 2 && n <= 3);
            break;
        case operations.SERVICES:
            error = checkNbOfArgs(n => n === 1);
            break;
        default :
            error = unknownOp(positionalArguments[0]);
            requiredProperties = {};
            break;
    }

    return {error, operation, requiredProperties};
};

function getMode(options) {
    return options.nodejs ? NODE_SERVICE_TYPE : options.java ? JAVA_SERVICE_TYPE : XUML_SERVICE_TYPE;
}

/**
 * Do the actual work.
 * Take the options we have calculated and do something useful at last.
 * @param options   Set of known options. Calculated from command line and prompt.
 * @param callback  Let others know, that we're done here.
 * @returns {*} Null or whatever the callback returns.
 */
module.exports.perform = function(options, callback){
    const bridgeInstance = new E2EBridge(options.host, options.port, options.user, options.password);
    // noinspection FallThroughInSwitchStatementJS
    switch(options.operation){
        case operations.KILL:
            if(options.nodejs){
                return callback({ errorType: 'Logic error', error: 'Kill operation is not supported for Node.js services'});
            }
        case operations.START:
        case operations.STOP:
            bridgeInstance.setServiceStatus(options.operation, options.service, getMode(options), callback);
            return null;

        case operations.REMOVE:
            bridgeInstance.removeService(options.service, getMode(options), callback);
            return null;

        case operations.STATUS:
            bridgeInstance.getServiceStatus(options.service, getMode(options), callback);
            return null;

        case operations.DEPLOY:
            bridgeInstance.deployService(options.file, options.options, callback);
            return null;

        case operations.PACK:
            E2EBridge.pack(options.directory, options, callback);
            return null;

        case operations.PREFERENCES:
            if(options.preferences) {
                bridgeInstance.setServicePreferences(options.service, getMode(options), options.preferences, callback);
            } else {
                bridgeInstance.getServicePreferences(options.service, getMode(options), callback);
            }
            return null;
        case operations.SETTINGS:
            if(options.settings) {
                bridgeInstance.setServiceSettings(options.service, getMode(options), options.settings, callback);
            } else {
                bridgeInstance.getServiceSettings(options.service, getMode(options), callback);
            }
            return null;

        case operations.MODELNOTES:
            if(options.filename) {
                bridgeInstance.getXUMLModelNotes(options.service, options.filename, callback);
            } else {
                bridgeInstance.getXUMLModelNotesList(options.service, callback);
            }
            return null;

        case operations.SERVICES:
            if(options.nodejs) {
                bridgeInstance.listNodeServices(callback);
            } else if(options.java) {
                bridgeInstance.listJavaServices(callback);
            } else {
                bridgeInstance.listXUMLServices(callback);
            }
            return null;
    }
    // Should not happen
    return callback({
        errorType: 'BUG',
        error: '"perform" fed with incorrect operation. Please report the problem. Please attach your command line invocation.'
    });
};

module.exports.resolveInputOutput = function(operation, positionalArguments) {

    const settings = {};

    if (operation === operations.DEPLOY) {
        settings['file'] = path.resolve('' + (positionalArguments.shift() || '.'));
    } else if (operation === operations.PACK) {
        settings['directory'] = path.resolve('' + positionalArguments.shift());

        let out = positionalArguments.shift();
        settings['output'] = out
            ? path.resolve('' + out)
            : null;
    } else if(operation !== operations.SERVICES) {
        settings['service'] = '' + positionalArguments.shift();
        if(operation === operations.MODELNOTES) {
            const filename = positionalArguments.shift();
            if(filename) {
                settings['filename'] = '' + filename;
            }
        }
    }

    return settings;
};

module.exports.gatherPreferences = function(positionalArguments) {
    // scan for properties one may want to set
    if (positionalArguments.indexOf('pref') > -1 && positionalArguments.length >= 3) {
        const preferences = {};
        for (let i = 0; i < positionalArguments.length; i++) {
            if (positionalArguments[i] === 'pref') {
                let setName = positionalArguments[i + 1];
                let setValue = positionalArguments[i + 2];

                if (setValue === 'true') {
                    preferences[setName] = true;
                } else if (setValue === 'false') {
                    preferences[setName] = false;
                } else {
                    preferences[setName] = setValue;
                }
                i += 2;
            }
        }
        return preferences;
    }

    return undefined;
};

module.exports.gatherSettings = function(positionalArguments) {
    // scan for settings that should be changed
    if (positionalArguments.indexOf('set') > -1 && positionalArguments.length >= 3) {
        const settings = {};
        for (let i = 0; i < positionalArguments.length; i++) {
            if (positionalArguments[i] === 'set') {
                settings[positionalArguments[i + 1]] = positionalArguments[i + 2];
                i += 2;
            }
        }
        return settings;
    }
    return undefined;
};

module.exports.gatherDeploymentOptions = function(options) {

    const result = Object.assign({}, defaultDeploymentOptions);

    (options||[]).forEach(function (option) {
        const o = option.split('=');
        switch (o[0]) {
            case deploymentOptions.STARTUP :
                result.startup = true;
                break;
            case deploymentOptions.OVERWRITE:
                result.overwrite = true;
                break;
            case deploymentOptions.SETTINGS:
                result.overwritePrefs = true;
                break;
            case deploymentOptions.NPM_SCRIPTS:
                result.runScripts = true;
            //noinspection FallThroughInSwitchStatementJS
            case deploymentOptions.NPM_INSTALL:
                result.npmInstall = true;
                break;
            case deploymentOptions.INSTANCE_NAME:
                result.instanceName = o[1];
                break;
            default:
                return { error: helpText('Unknown option "' + option + '".') };
        }
    });

    return { options: result };
};

module.exports.gatherConnectionSettings = function(argv) {
    const settings = {};
    const port = parseInt(argv['p'] || argv['port'] || '8080');
    if (isNaN(port)) {
        return { error: helpText('Port has to be an integer number.') };
    }
    settings['port'] = port || 8080;
    settings['user'] = argv['u'] || argv['user'];
    settings['password'] = argv['P'] || argv['password'];

    settings['host'] = argv['h'] || argv['host'] || 'localhost';

    return { settings };
};

module.exports.isNodeJS = function(argv) {
    return (argv['n'] || argv['N'] || argv['nodejs']) && true;
};

module.exports.isJava = function(argv) {
    return (argv['j'] || argv['java']) && true;
};

module.exports.useGit = function(argv) {
    return (argv['g'] || argv['git']) && true;
};

module.exports.useShrinkwrap = function(argv) {
    return (argv['s'] || argv['shrinkwrap']) && true;
};<commit_msg>NOD-51: Add missing service type specification in help text<commit_after>
'use strict';

const E2EBridge = require('e2e-bridge-lib');
const path = require('path');

const XUML_SERVICE_TYPE = 'xUML';
const NODE_SERVICE_TYPE = 'node';
const JAVA_SERVICE_TYPE = 'java';

const operations = Object.freeze({
    START: "start",
    STOP: "stop",
    KILL: "kill",
    REMOVE: "remove",
    DEPLOY: "deploy",
    PACK: "pack",
    SETTINGS: "settings",
    PREFERENCES: "preferences",
    MODELNOTES: "modelnotes",
    SERVICES: "services",
    STATUS: "status",
});
module.exports.operations = operations;

const deploymentOptions = Object.freeze({
    STARTUP: "startup",
    OVERWRITE: "overwrite",
    SETTINGS: "overwritePrefs",
    NPM_SCRIPTS: "runScripts",
    NPM_INSTALL: "npmInstall",
    INSTANCE_NAME: "instanceName"
});
module.exports.deploymentOptions = deploymentOptions;

const defaultDeploymentOptions = Object.freeze({
    startup: false,
    overwrite: false,
    overwritePrefs: false,
    npmInstall: false,
    runScripts: false,
    instanceName: undefined,
});
module.exports.defaultDeploymentOptions = defaultDeploymentOptions;

function helpText(message) {

    let help = '';

    if( message){
        help = message + '\n';
    }

    help +=
        'Usage:\n' +
        'services [[-n|--nodejs]|[-j|--java]] [settings]\n' +
        'start|stop|remove ${ServiceName} [[-n|--nodejs]|[-j|--java]] [settings]\n' +
        'kill ${ServiceName} [settings]\n' +
        'status ${ServiceName} [[-n|--nodejs]|[-j|--java]] [settings]\n' +
        'deploy [${path/to/repository}|${path/to/directory}] [settings] [-o option]...\n'+
        'pack [${path/to/directory}] [${path/to/repository}] [-g|--git] [-s|--shrinkwrap]\n'+
        'preferences ${ServiceName} [[-n|--nodejs]|[-j|--java]] [pref ${PreferenceName} ${PreferenceValue}]... [settings]\n' +
        'settings ${ServiceName} [-n|--nodejs] [set ${SettingsName} ${SettingValue}]... [settings]\n' +
        'modelnotes ${ServiceName} [${NotesFileName}] [settings]\n' +
        '--help\n\n' +
        'settings:\n' +
        '\t-h|--host <FQDN bridge host> The host, that runs the bridge. Defaults to localhost.\n' +
        '\t-p|--port <bridge port> The port of the bridge. Defaults to 8080.\n' +
        "\t-u|--user <bridge user> User that has the right to perform operation on bridge.\n" +
        "\t\tRequired. If not given, you'll be prompted for it.\n" +
        "\t-P|--password <password for bridge user> Password for the user.\n" +
        "\t\tRequired. If not given, you'll prompted for it, what is recommended as giving your password\n" +
        "\t\tin command line will expose it in your shell's history. Password is masked during prompt.\n\n" +
        'options:\n' +
        '\tstartup|overwrite|settings Multiple options can be separated by comma, like: "-o startup,overwrite"+\n' +
        '\t\tstartup: Launch service after deployment.\n' +
        '\t\toverwrite: Overwrite existing service if one already exists.\n' +
        '\t\toverwritePrefs: Overwrite settings and preferences too.\n' +
        "\t\tnpmInstall: Run 'npm install' (Applies to Node.js services only).\n" +
        "\t\trunScripts: Run 'npm install' (running scripts too) (Applies to Node.js services only).\n" +
        "\tinstanceName=<instance name>: Choose a different instance name  (applies to Node.js services only)\n\n" +
        'Other:\n' +
        '\t-n|--nodejs Assume that the service is a Node.js service. This is ignored for "deploy" and illegal for "kill".\n\n\n' +
        '\t-j|--java Assume that the service is a Java service. This is ignored for "deploy" and illegal for "kill".\n\n\n' +
        '\t-g|--git Use "git archive" for building the repository. This is ignored for all commands but "pack".\n\n\n' +
        '\t-s|--shrinkwrap Execute "npm shrinkwrap" before creating the repository. This is ignored for all commands but "pack".\n\n\n';

    return help;
}

module.exports.helpText = helpText;

function incorrectNbOfArgs(){
    return helpText('Incorrect number of arguments');
}

function unknownOp(op){
    return helpText('Unknown operation "' + op + '"');
}

module.exports.processOperation = function(positionalArguments) {

    let requiredProperties = {user: {required: true}, password: {required: true, hidden: true}};
    let error = undefined;
    const operation = ('' + positionalArguments[0]).toLowerCase();

    function checkNbOfArgs(chk) {
        return chk(positionalArguments.length) ? undefined : incorrectNbOfArgs();
    }

    switch (operation) {
        case operations.START:
        case operations.STOP:
        case operations.KILL:
        case operations.REMOVE:
        case operations.STATUS:
            error = checkNbOfArgs(n => n === 2);
            break;

        case operations.DEPLOY:
            error = checkNbOfArgs(n => n <= 2);
            break;
        case operations.PACK:
            error = checkNbOfArgs(n => n >= 2 && n <= 3);
            requiredProperties = {};
            break;
        case operations.SETTINGS:
        case operations.PREFERENCES:
            error = checkNbOfArgs(n => n >= 2 && (n - 2) % 3 === 0);
            break;
        case operations.MODELNOTES:
            error = checkNbOfArgs(n => n >= 2 && n <= 3);
            break;
        case operations.SERVICES:
            error = checkNbOfArgs(n => n === 1);
            break;
        default :
            error = unknownOp(positionalArguments[0]);
            requiredProperties = {};
            break;
    }

    return {error, operation, requiredProperties};
};

function getMode(options) {
    return options.nodejs ? NODE_SERVICE_TYPE : options.java ? JAVA_SERVICE_TYPE : XUML_SERVICE_TYPE;
}

/**
 * Do the actual work.
 * Take the options we have calculated and do something useful at last.
 * @param options   Set of known options. Calculated from command line and prompt.
 * @param callback  Let others know, that we're done here.
 * @returns {*} Null or whatever the callback returns.
 */
module.exports.perform = function(options, callback){
    const bridgeInstance = new E2EBridge(options.host, options.port, options.user, options.password);
    // noinspection FallThroughInSwitchStatementJS
    switch(options.operation){
        case operations.KILL:
            if(options.nodejs){
                return callback({ errorType: 'Logic error', error: 'Kill operation is not supported for Node.js services'});
            }
        case operations.START:
        case operations.STOP:
            bridgeInstance.setServiceStatus(options.operation, options.service, getMode(options), callback);
            return null;

        case operations.REMOVE:
            bridgeInstance.removeService(options.service, getMode(options), callback);
            return null;

        case operations.STATUS:
            bridgeInstance.getServiceStatus(options.service, getMode(options), callback);
            return null;

        case operations.DEPLOY:
            bridgeInstance.deployService(options.file, options.options, callback);
            return null;

        case operations.PACK:
            E2EBridge.pack(options.directory, options, callback);
            return null;

        case operations.PREFERENCES:
            if(options.preferences) {
                bridgeInstance.setServicePreferences(options.service, getMode(options), options.preferences, callback);
            } else {
                bridgeInstance.getServicePreferences(options.service, getMode(options), callback);
            }
            return null;
        case operations.SETTINGS:
            if(options.settings) {
                bridgeInstance.setServiceSettings(options.service, getMode(options), options.settings, callback);
            } else {
                bridgeInstance.getServiceSettings(options.service, getMode(options), callback);
            }
            return null;

        case operations.MODELNOTES:
            if(options.filename) {
                bridgeInstance.getXUMLModelNotes(options.service, options.filename, callback);
            } else {
                bridgeInstance.getXUMLModelNotesList(options.service, callback);
            }
            return null;

        case operations.SERVICES:
            if(options.nodejs) {
                bridgeInstance.listNodeServices(callback);
            } else if(options.java) {
                bridgeInstance.listJavaServices(callback);
            } else {
                bridgeInstance.listXUMLServices(callback);
            }
            return null;
    }
    // Should not happen
    return callback({
        errorType: 'BUG',
        error: '"perform" fed with incorrect operation. Please report the problem. Please attach your command line invocation.'
    });
};

module.exports.resolveInputOutput = function(operation, positionalArguments) {

    const settings = {};

    if (operation === operations.DEPLOY) {
        settings['file'] = path.resolve('' + (positionalArguments.shift() || '.'));
    } else if (operation === operations.PACK) {
        settings['directory'] = path.resolve('' + positionalArguments.shift());

        let out = positionalArguments.shift();
        settings['output'] = out
            ? path.resolve('' + out)
            : null;
    } else if(operation !== operations.SERVICES) {
        settings['service'] = '' + positionalArguments.shift();
        if(operation === operations.MODELNOTES) {
            const filename = positionalArguments.shift();
            if(filename) {
                settings['filename'] = '' + filename;
            }
        }
    }

    return settings;
};

module.exports.gatherPreferences = function(positionalArguments) {
    // scan for properties one may want to set
    if (positionalArguments.indexOf('pref') > -1 && positionalArguments.length >= 3) {
        const preferences = {};
        for (let i = 0; i < positionalArguments.length; i++) {
            if (positionalArguments[i] === 'pref') {
                let setName = positionalArguments[i + 1];
                let setValue = positionalArguments[i + 2];

                if (setValue === 'true') {
                    preferences[setName] = true;
                } else if (setValue === 'false') {
                    preferences[setName] = false;
                } else {
                    preferences[setName] = setValue;
                }
                i += 2;
            }
        }
        return preferences;
    }

    return undefined;
};

module.exports.gatherSettings = function(positionalArguments) {
    // scan for settings that should be changed
    if (positionalArguments.indexOf('set') > -1 && positionalArguments.length >= 3) {
        const settings = {};
        for (let i = 0; i < positionalArguments.length; i++) {
            if (positionalArguments[i] === 'set') {
                settings[positionalArguments[i + 1]] = positionalArguments[i + 2];
                i += 2;
            }
        }
        return settings;
    }
    return undefined;
};

module.exports.gatherDeploymentOptions = function(options) {

    const result = Object.assign({}, defaultDeploymentOptions);

    (options||[]).forEach(function (option) {
        const o = option.split('=');
        switch (o[0]) {
            case deploymentOptions.STARTUP :
                result.startup = true;
                break;
            case deploymentOptions.OVERWRITE:
                result.overwrite = true;
                break;
            case deploymentOptions.SETTINGS:
                result.overwritePrefs = true;
                break;
            case deploymentOptions.NPM_SCRIPTS:
                result.runScripts = true;
            //noinspection FallThroughInSwitchStatementJS
            case deploymentOptions.NPM_INSTALL:
                result.npmInstall = true;
                break;
            case deploymentOptions.INSTANCE_NAME:
                result.instanceName = o[1];
                break;
            default:
                return { error: helpText('Unknown option "' + option + '".') };
        }
    });

    return { options: result };
};

module.exports.gatherConnectionSettings = function(argv) {
    const settings = {};
    const port = parseInt(argv['p'] || argv['port'] || '8080');
    if (isNaN(port)) {
        return { error: helpText('Port has to be an integer number.') };
    }
    settings['port'] = port || 8080;
    settings['user'] = argv['u'] || argv['user'];
    settings['password'] = argv['P'] || argv['password'];

    settings['host'] = argv['h'] || argv['host'] || 'localhost';

    return { settings };
};

module.exports.isNodeJS = function(argv) {
    return (argv['n'] || argv['N'] || argv['nodejs']) && true;
};

module.exports.isJava = function(argv) {
    return (argv['j'] || argv['java']) && true;
};

module.exports.useGit = function(argv) {
    return (argv['g'] || argv['git']) && true;
};

module.exports.useShrinkwrap = function(argv) {
    return (argv['s'] || argv['shrinkwrap']) && true;
};<|endoftext|>