<commit_before>var CloudCommander, CloudFunc, CodeMirror;
/* object contains editors CodeMirror
 * and later will be Ace
 */
 (function(){
    "use strict";
    var cloudcmd                    = CloudCommander,
        Util                        = CloudCommander.Util,
        KeyBinding                  = CloudCommander.KeyBinding,
        CodeMirrorEditor            = {},
        CodeMirrorLoaded            = false,
        FM,
        CodeMirrorElement;

    cloudcmd.Editor                 = {
        get : (function(){
            return this.CodeMirror;
        })
    };

    var createEditorDiv = function(pIsReadOnly){
        if(!FM)
            FM = Util.getById('fm');

        CodeMirrorElement = Util.anyload({
            name        : 'div',
            id          : 'CodeMirrorEditor',
            className   : 'panel',
            parent      : FM
        });
    };

    cloudcmd.Editor.dir             = 'lib/client/editor/';
    CodeMirrorEditor.dir            = cloudcmd.Editor.dir + 'codemirror/';

    /* indicator says CodeMirror still loads */
    CodeMirrorEditor.loading        = false;

    /* function loads CodeMirror js and css files */
    CodeMirrorEditor.load           = (function(pCurrentFile, pIsReadOnly){
        /* function loads css files of CodeMirror */
        var loadAll = function() {
            Util.cssLoad([
                { src : CodeMirrorEditor.dir + 'codemirror.css'},
                { src : CodeMirrorEditor.dir + 'theme/night.css'}
            ]);

            Util.cssSet({id:'editor',
                inner : '.CodeMirror{'                                      +
                            'font-family :\'Droid Sans Mono\';'             +
                            'font-size   :15px;'                            +
                            'padding     :20px 0 0 0;'                      +
                        '}'                                                 +
                        '.CodeMirror-scroll{'                               +
                            'height      : ' + (cloudcmd.HEIGHT-40) + 'px'  +
                        '}'
            });

            Util.jsload(CodeMirrorEditor.dir +
                'mode/javascript.js', function(){
                        CodeMirrorLoaded = true;
                        CodeMirrorEditor.show(pIsReadOnly);
                    });
        };

        /* load CodeMirror main module */
        Util.jsload(CodeMirrorEditor.dir + 'codemirror.js', loadAll);
    });

     /* function shows CodeMirror editor */
    CodeMirrorEditor.show           = (function(pIsReadOnly){
        /* if CodeMirrorEditor is not loaded - loading him */
        if(!CodeMirrorLoaded)
            return this.load(pIsReadOnly);

        /* if CodeMirror function show already
         * called do not call it again
         * if f4 key pressed couple times
         */
        if(this.loading)
            return;

        /* when folder view
         * is no need to edit
         * data
         */
        var lReadOnly = pIsReadOnly || false;

        var lThis = this;

        var initCodeMirror_f = function(pValue){
            createEditorDiv();
            CodeMirrorEditor.CodeMirror = new CodeMirror(CodeMirrorElement,{
                mode        : 'javascript',
                value       : pValue,
                theme       : 'night',
                lineNumbers : true,
                //переносим длинные строки
                lineWrapping: false,
                autofocus   : true,
                extraKeys: {
                  //Сохранение
                  "Esc": lThis.hide
                },
                readOnly    : lReadOnly
            });
        };

        /* getting link */
        var lCurrentFile = Util.getCurrentFile(),
            lA = Util.getCurrentLink(lCurrentFile);
            lA = lA.href;

        /* убираем адрес хоста*/
        lA = '/' + lA.replace(document.location.href,'');

        /* checking is this link is to directory */
        var lSize = Util.getByClass('size', lCurrentFile);
        if(lSize){
            lSize = lSize[0].textContent;

            /* if directory - load json
             * not html data
             */
            if (lSize === '<dir>'){
                if (lA.indexOf(CloudFunc.NOJS) ===
                    CloudFunc.FS.length) {
                        lA = lA.replace(CloudFunc.NOJS, '');
                        lReadOnly = true;
                }
            }
        }

        this.loading = true;
        setTimeout(function(){
            lThis.loading = false;},
            400);

        /* reading data from current file */
        Util.ajax({
            url:lA,
             error: (function(jqXHR, textStatus, errorThrown){
                 lThis.loading             = false;

                 return Util.Images.showError(jqXHR);
             }),

             success:function(data, textStatus, jqXHR){
                /* if we got json - show it */
                if(typeof data === 'object')
                    data = JSON.stringify(data, null, 4);

                initCodeMirror_f(data);

                /* removing keyBinding if set */
                KeyBinding.unSet();

                Util.hidePanel();
                Util.Images.hideLoad();

                lThis.loading               = false;
            }
        });
    });

    /* function hides CodeMirror editor */
    CodeMirrorEditor.hide           = (function() {
        var lElem = CodeMirrorElement;
        KeyBinding.set();

        if(lElem && FM)
            FM.removeChild(lElem);

        Util.showPanel();
    });

    cloudcmd.Editor.Keys            = (function(pCurrentFile, pIsReadOnly){
        var lThis = this.CodeMirror;
        /* loading js and css of CodeMirror */
        lThis.show(pCurrentFile, pIsReadOnly);

        var key_event = function(pEvent){

            /* если клавиши можно обрабатывать */
            if( KeyBinding.get() ){
                /* if f4 or f3 pressed */
                var lF3 = cloudcmd.KEY.F3;
                var lF4 = cloudcmd.KEY.F4;
                //var lShow = lThis.show.bind(lThis);
                var lShow = Util.bind(lThis.show, lThis);

                if(!pEvent.shiftKey){
                    if(pEvent.keyCode === lF4)
                        lShow();
                    else if(pEvent.keyCode === lF3){
                        lShow(true);
                    }
                }
            }
        };

        /* добавляем обработчик клавишь */
        if (document.addEventListener)
            document.addEventListener('keydown', key_event,false);

        else{
            var lFunc;
            if(typeof document.onkeydown === 'function')
                lFunc = document.onkeydown;

            document.onkeydown = function(){
                if(lFunc)
                    lFunc();

                key_event();
            };
        }
    });

    cloudcmd.Editor.CodeMirror      = CodeMirrorEditor;
})();<commit_msg>added ability to work with codemirror v3<commit_after>var CloudCommander, CloudFunc, CodeMirror;
/* object contains editors CodeMirror
 * and later will be Ace
 */
 (function(){
    "use strict";
    var cloudcmd                    = CloudCommander,
        Util                        = CloudCommander.Util,
        KeyBinding                  = CloudCommander.KeyBinding,
        CodeMirrorEditor            = {},
        CodeMirrorLoaded            = false,
        FM,
        CodeMirrorElement;

    cloudcmd.Editor                 = {
        get : (function(){
            return this.CodeMirror;
        })
    };

    var createEditorDiv = function(pIsReadOnly){
        if(!FM)
            FM = Util.getById('fm');

        CodeMirrorElement = Util.anyload({
            name        : 'div',
            id          : 'CodeMirrorEditor',
            className   : 'panel',
            parent      : FM
        });
    };

    cloudcmd.Editor.dir             = 'lib/client/editor/';
    CodeMirrorEditor.dir            = cloudcmd.Editor.dir + 'codemirror/';

    /* indicator says CodeMirror still loads */
    CodeMirrorEditor.loading        = false;

    /* function loads CodeMirror js and css files */
    CodeMirrorEditor.load           = (function(pCurrentFile, pIsReadOnly){
        /* function loads css files of CodeMirror */
        var loadAll = function() {
            Util.cssLoad([
                { src : CodeMirrorEditor.dir + 'codemirror.css'},
                { src : CodeMirrorEditor.dir + 'theme/night.css'}
            ]);

            Util.cssSet({id:'editor',
                inner : '.CodeMirror{'                                      +
                            'font-family :\'Droid Sans Mono\';'             +
                            'font-size   :15px;'                            +
                            'padding     :20px 0 0 0;'                    +
                            /* codemirror v3 */
                            //'height      : ' + cloudcmd.HEIGHT + 'px'       +
                        '}'                                                 +
                        '.CodeMirror-scroll{'                               +
                            'height      : ' + (cloudcmd.HEIGHT-40) + 'px'  +
                        '}'                                                 //+
                        /* codemirror v3 */
                        //'#CodeMirrorEditor{'                                +
                        //    'padding        :20px 20px 20px 20px;'          +
                        //    '}'
            });

            Util.jsload(CodeMirrorEditor.dir +
                'mode/javascript.js', function(){
                        CodeMirrorLoaded = true;
                        CodeMirrorEditor.show(pIsReadOnly);
                    });
        };

        /* load CodeMirror main module */
        Util.jsload(CodeMirrorEditor.dir + 'codemirror.js', loadAll);
    });

     /* function shows CodeMirror editor */
    CodeMirrorEditor.show           = (function(pIsReadOnly){
        /* if CodeMirrorEditor is not loaded - loading him */
        if(!CodeMirrorLoaded)
            return this.load(pIsReadOnly);

        /* if CodeMirror function show already
         * called do not call it again
         * if f4 key pressed couple times
         */
        if(this.loading)
            return;

        /* when folder view
         * is no need to edit
         * data
         */
        var lReadOnly = pIsReadOnly || false;

        var lThis = this;

        var initCodeMirror_f = function(pValue){
            createEditorDiv();
            CodeMirrorEditor.CodeMirror = new CodeMirror(CodeMirrorElement,{
                mode        : 'javascript',
                value       : pValue,
                theme       : 'night',
                lineNumbers : true,
                //переносим длинные строки
                lineWrapping: false,
                autofocus   : true,
                extraKeys: {
                  //Сохранение
                  "Esc": lThis.hide
                },
                readOnly    : lReadOnly
            });
        };

        /* getting link */
        var lCurrentFile = Util.getCurrentFile(),
            lA = Util.getCurrentLink(lCurrentFile);
            lA = lA.href;

        /* убираем адрес хоста*/
        lA = '/' + lA.replace(document.location.href,'');

        /* checking is this link is to directory */
        var lSize = Util.getByClass('size', lCurrentFile);
        if(lSize){
            lSize = lSize[0].textContent;

            /* if directory - load json
             * not html data
             */
            if (lSize === '<dir>'){
                if (lA.indexOf(CloudFunc.NOJS) ===
                    CloudFunc.FS.length) {
                        lA = lA.replace(CloudFunc.NOJS, '');
                        lReadOnly = true;
                }
            }
        }

        this.loading = true;
        setTimeout(function(){
            lThis.loading = false;},
            400);

        /* reading data from current file */
        Util.ajax({
            url:lA,
             error: (function(jqXHR, textStatus, errorThrown){
                 lThis.loading             = false;

                 return Util.Images.showError(jqXHR);
             }),

             success:function(data, textStatus, jqXHR){
                /* if we got json - show it */
                if(typeof data === 'object')
                    data = JSON.stringify(data, null, 4);

                initCodeMirror_f(data);

                /* removing keyBinding if set */
                KeyBinding.unSet();

                Util.hidePanel();
                Util.Images.hideLoad();

                lThis.loading               = false;
            }
        });
    });

    /* function hides CodeMirror editor */
    CodeMirrorEditor.hide           = (function() {
        var lElem = CodeMirrorElement;
        KeyBinding.set();

        if(lElem && FM)
            FM.removeChild(lElem);

        Util.showPanel();
    });

    cloudcmd.Editor.Keys            = (function(pCurrentFile, pIsReadOnly){
        var lThis = this.CodeMirror;
        /* loading js and css of CodeMirror */
        lThis.show(pCurrentFile, pIsReadOnly);

        var key_event = function(pEvent){

            /* если клавиши можно обрабатывать */
            if( KeyBinding.get() ){
                /* if f4 or f3 pressed */
                var lF3 = cloudcmd.KEY.F3;
                var lF4 = cloudcmd.KEY.F4;
                //var lShow = lThis.show.bind(lThis);
                var lShow = Util.bind(lThis.show, lThis);

                if(!pEvent.shiftKey){
                    if(pEvent.keyCode === lF4)
                        lShow();
                    else if(pEvent.keyCode === lF3){
                        lShow(true);
                    }
                }
            }
        };

        /* добавляем обработчик клавишь */
        if (document.addEventListener)
            document.addEventListener('keydown', key_event,false);

        else{
            var lFunc;
            if(typeof document.onkeydown === 'function')
                lFunc = document.onkeydown;

            document.onkeydown = function(){
                if(lFunc)
                    lFunc();

                key_event();
            };
        }
    });

    cloudcmd.Editor.CodeMirror      = CodeMirrorEditor;
})();<|endoftext|>


<commit_before>var util = require('util'),
    Marshal = require('./marshal'),
    Column = require('./column'),
    Row = require('./row'),
    ttype = require('./cassandra/1.0/cassandra_types');

/**
 * NO-Operation for deault callbacks
 * @private
 * @memberOf ColumnFamily
 */
var NOOP = function(){};

/**
 * Default read consistency level
 * @private
 * @constant
 * @memberOf ColumnFamily
 */
var DEFAULT_READ_CONSISTENCY = ttype.ConsistencyLevel.QUORUM;

/**
 * Default write consistency level
 * @private
 * @constant
 * @memberOf ColumnFamily
 */
var DEFAULT_WRITE_CONSISTENCY = ttype.ConsistencyLevel.QUORUM;

/**
 * Gets an array of columns from an object
 * @param {Object} columns
 * @private
 * @memberOf ColumnFamily
 * @returns {Array} and array of columns
 */
function getColumns(columns){
  var keys = Object.keys(columns), len = keys.length, i = 0, key, value, arr = [],
      ts = new Date();
  for(; i < len; i += 1){
    key = keys[i];
    value = columns[key];

    if(value === null || value === undefined){
      value = '';
    }

    arr.push(new Column(key, value, ts));
  }
  return arr;
}

/**
 * Representation of a Column Family
 *
 * @param {Object} definition The Column Family definition
 * @constructor
 */
var ColumnFamily = function(keyspace, definition){
//  ttype.CfDef.call(this, definition);
  this.isSuper = this.column_type === 'Super';
  this.keyspace = keyspace;
  this.connection = keyspace.connection;
  this.definition = definition;
  this.name = definition.name;
  this.columnMarshaller = new Marshal(definition.comparator_type);
  this.valueMarshaller = new Marshal(definition.default_validation_class);
  this.keyMarshaller = new Marshal(definition.key_validation_class);

  this.columns = {};

  if(definition.column_metadata && Array.isArray(definition.column_metadata)){
    var i = 0, len = definition.column_metadata.length, col;
    for(; i < len; i += 1){
      col = definition.column_metadata[i];
      this.columns[col.name] = new Marshal(col.validation_class);
    }
  }
};

/**
 * Performs a set command to the cluster
 *
 * @param {String} key The key for the row
 * @param {Object} columns The value for the columns as represented by JSON or an array of Column objects
 * @param {Object} options The options for the insert
 * @param {Function} callback The callback to call once complete
 */
ColumnFamily.prototype.insert = function(key, columns, options, callback){
  if (typeof options === 'function'){
    callback = options;
    options = {};
  }

  if(!Array.isArray(columns)){
    columns = getColumns(columns);
  }

  var len = columns.length, i = 0, valueMarshaller, col,
      mutations = [], batch = {},
      consistency = options.consistency || DEFAULT_WRITE_CONSISTENCY;

  for(; i < len; i += 1){
    col = columns[i];
    valueMarshaller = this.columns[col.name] || this.valueMarshaller;

    mutations.push(new ttype.Mutation({
      column_or_supercolumn: new ttype.ColumnOrSuperColumn({
        column: col.toThrift(this.columnMarshaller, valueMarshaller)
      })
    }));
  }

  var marshalledKey = this.keyMarshaller.serialize(key).toString('binary');

  batch[marshalledKey] = {};
  batch[marshalledKey][this.definition.name] = mutations;

  this.connection.execute('batch_mutate', batch, consistency, callback);
};

/**
 * Get a column in a row by its key
 * @param {String} key The key to get
 * @param {Object} options Options for the get, can have start, end, max, consistencyLevel
 *

 *
start: the from part of the column name

 *
end: the to part of the column name

 *
max: the max amount of columns to return

 *
columns: an {Array} of column names to get

 *
consistencyLevel: the read consistency level

 *

 * @param {Function} callback The callback to invoke once the response has been received
 */
ColumnFamily.prototype.get = function(key, options, callback){
  if (typeof options === 'function'){
    callback = options;
    options = {};
  }

  callback = callback || NOOP;

  var consistency = options.consistencyLevel || DEFAULT_READ_CONSISTENCY,
      self = this, predicate, parent;

  parent = new ttype.ColumnParent({
    column_family: this.name
  });

  predicate = new ttype.SlicePredicate({
    columns: options.columns,
    slice_range: new ttype.SliceRange({
      start:options.start,
      finish:options.end,
      reversed:options.reversed,
      count:options.max
    })
  });

  function onComplete(err, val){
    if(err){
      callback(err);
      return;
    }

    callback(null, Row.fromThrift(key, val, self));
  }

  var marshalledKey = this.keyMarshaller.serialize(key).toString('binary');

  this.connection.execute('get_slice', marshalledKey, parent, predicate, consistency, onComplete);
};

module.exports = ColumnFamily;<commit_msg>predicates can name have both slices and column names<commit_after>var util = require('util'),
    Marshal = require('./marshal'),
    Column = require('./column'),
    Row = require('./row'),
    ttype = require('./cassandra/1.0/cassandra_types');

/**
 * NO-Operation for deault callbacks
 * @private
 * @memberOf ColumnFamily
 */
var NOOP = function(){};

/**
 * Default read consistency level
 * @private
 * @constant
 * @memberOf ColumnFamily
 */
var DEFAULT_READ_CONSISTENCY = ttype.ConsistencyLevel.QUORUM;

/**
 * Default write consistency level
 * @private
 * @constant
 * @memberOf ColumnFamily
 */
var DEFAULT_WRITE_CONSISTENCY = ttype.ConsistencyLevel.QUORUM;

/**
 * Gets an array of columns from an object
 * @param {Object} columns
 * @private
 * @memberOf ColumnFamily
 * @returns {Array} and array of columns
 */
function getColumns(columns){
  var keys = Object.keys(columns), len = keys.length, i = 0, key, value, arr = [],
      ts = new Date();
  for(; i < len; i += 1){
    key = keys[i];
    value = columns[key];

    if(value === null || value === undefined){
      value = '';
    }

    arr.push(new Column(key, value, ts));
  }
  return arr;
}

/**
 * Representation of a Column Family
 *
 * @param {Object} definition The Column Family definition
 * @constructor
 */
var ColumnFamily = function(keyspace, definition){
//  ttype.CfDef.call(this, definition);
  this.isSuper = this.column_type === 'Super';
  this.keyspace = keyspace;
  this.connection = keyspace.connection;
  this.definition = definition;
  this.name = definition.name;
  this.columnMarshaller = new Marshal(definition.comparator_type);
  this.valueMarshaller = new Marshal(definition.default_validation_class);
  this.keyMarshaller = new Marshal(definition.key_validation_class);

  this.columns = {};

  if(definition.column_metadata && Array.isArray(definition.column_metadata)){
    var i = 0, len = definition.column_metadata.length, col;
    for(; i < len; i += 1){
      col = definition.column_metadata[i];
      this.columns[col.name] = new Marshal(col.validation_class);
    }
  }
};

/**
 * Performs a set command to the cluster
 *
 * @param {String} key The key for the row
 * @param {Object} columns The value for the columns as represented by JSON or an array of Column objects
 * @param {Object} options The options for the insert
 * @param {Function} callback The callback to call once complete
 */
ColumnFamily.prototype.insert = function(key, columns, options, callback){
  if (typeof options === 'function'){
    callback = options;
    options = {};
  }

  if(!Array.isArray(columns)){
    columns = getColumns(columns);
  }

  var len = columns.length, i = 0, valueMarshaller, col,
      mutations = [], batch = {},
      consistency = options.consistency || DEFAULT_WRITE_CONSISTENCY;

  for(; i < len; i += 1){
    col = columns[i];
    valueMarshaller = this.columns[col.name] || this.valueMarshaller;

    mutations.push(new ttype.Mutation({
      column_or_supercolumn: new ttype.ColumnOrSuperColumn({
        column: col.toThrift(this.columnMarshaller, valueMarshaller)
      })
    }));
  }

  var marshalledKey = this.keyMarshaller.serialize(key).toString('binary');

  batch[marshalledKey] = {};
  batch[marshalledKey][this.definition.name] = mutations;

  this.connection.execute('batch_mutate', batch, consistency, callback);
};

/**
 * Get a column in a row by its key
 * @param {String} key The key to get
 * @param {Object} options Options for the get, can have start, end, max, consistencyLevel
 *

 *
start: the from part of the column name

 *
end: the to part of the column name

 *
max: the max amount of columns to return

 *
columns: an {Array} of column names to get

 *
consistencyLevel: the read consistency level

 *

 * @param {Function} callback The callback to invoke once the response has been received
 */
ColumnFamily.prototype.get = function(key, options, callback){
  if (typeof options === 'function'){
    callback = options;
    options = {};
  }

  callback = callback || NOOP;

  var consistency = options.consistencyLevel || DEFAULT_READ_CONSISTENCY,
      self = this, predicate, parent;

  parent = new ttype.ColumnParent({
    column_family: this.name
  });

  predicate = new ttype.SlicePredicate();

  if(Array.isArray(options.columns)){
    predicate.column_names = options.columns;
  } else {
    predicate.slice_range = new ttype.SliceRange({
      start:options.start,
      finish:options.end,
      reversed:options.reversed,
      count:options.max
    });
  }

  function onComplete(err, val){
    if(err){
      callback(err);
      return;
    }

    callback(null, Row.fromThrift(key, val, self));
  }

  var marshalledKey = this.keyMarshaller.serialize(key).toString('binary');

  this.connection.execute('get_slice', marshalledKey, parent, predicate, consistency, onComplete);
};

module.exports = ColumnFamily;<|endoftext|>


<commit_before>/*
 * info.js: Titanium CLI info command
 *
 * Copyright (c) 2012, Appcelerator, Inc.  All Rights Reserved.
 * See the LICENSE file for more information.
 */

var appc = require('node-appc'),
	env = appc.environ,
	mix = appc.util.mix,
	async = require('async');

exports.config = function (logger, config, cli) {
	return {
		desc: __('display development environment information'),
		noAuth: true,
		skipBanner: true,
		options: {
			output: {
				abbr: 'o',
				default: 'report',
				desc: __('output format'),
				values: ['report', 'json']
			}
		}
	};
};

exports.run = function (logger, config, cli) {
	// important: we must duplicate every bit of info as to not accidentally
	// break the contract of the JSON formatted output.
	async.parallel([
		function (next) {
			env.getOSInfo(function (info) {
				next(null, {
					os: {
						name: info.os,
						version: info.osver,
						architecture: info.osarch,
						numcpus: info.oscpu,
						memory: info.memory
					},
					node: {
						version: info.node
					},
					npm: {
						version: info.npm
					}
				});
			});
		},

		function (next) {
			appc.ios.detect(function (info) {
				var result = { xcode: {} };
				Object.keys(info.xcode).forEach(function (ver) {
					if (ver != '__selected__') {
						result.xcode[ver] = {
							path: info.xcode[ver].path,
							xcodebuild: info.xcode[ver].xcodebuild,
							selected: info.xcode[ver].selected,
							version: info.xcode[ver].version,
							build: info.xcode[ver].build,
							sdks: [].concat(info.xcode[ver].sdks),
							sims: [].concat(info.xcode[ver].sims)
						};
					}
				});
				result.iosCerts = {
					dev: info.certs.dev,
					devNames: [].concat(info.certs.devNames),
					dist: info.certs.dist,
					distNames: [].concat(info.certs.distNames),
					wwdr: info.certs.wwdr
				};

				var pp = result.iOSProvisioningProfiles = {};
				Object.keys(info.provisioningProfiles).forEach(function (type) {
					pp[type] || (pp[type] = []);
					info.provisioningProfiles[type].forEach(function (profile) {
						pp[type].push(mix({}, profile));
					});
				});

				next(null, result);
			});
		},

		function (next) {
			appc.android.detect(function (info) {
				var result = {};

				next(null, { android: result });
			});
		},

		function (next) {
			var sdks = {};
			Object.keys(env.sdks).forEach(function (ver) {
				var n = env.sdks[ver];
				sdks[ver] = {
					path: n.path,
					platforms: Object.keys(n.platforms),
					githash: n.manifest ? n.manifest.githash : null,
					timestamp: n.manifest ? n.manifest.timestamp : null
				};
			});
			next(null, { titanium: sdks });
		}
	], function (err, results) {
		var data = mix.apply(null, results);

		if (cli.argv.output == 'json') {
			logger.log(JSON.stringify(data, null, '\t'));
		} else {
			var sections = {
				'Operating System': [
					['Name', data.os.name],
					['Version', data.os.version],
					['Architecture', data.os.architecture],
					['# CPUs', data.os.numcpus],
					['Memory', (data.os.memory / 1024 / 1024 / 1024).toFixed(1) + 'GB']
				],
				'node.js': [
					['node.js Version', data.node.version],
					['npm Version', data.npm.version]
				]
			};

			if (process.platform == 'darwin') {
				var xcode = sections['Xcode'] = {};
				Object.keys(data.xcode).forEach(function (ver) {
					var x = data.xcode[ver];
					xcode[x.version + ' (build ' + x.build + ')'] = [
						['Install Location', x.path],
						['Selected', x.selected],
						['iOS SDKs', x.sdks.length ? x.sdks.join(', ') : 'none'],
						['iOS Simulators', x.sims.length ? x.sims.join(', ') : 'none']
					];
				});

				sections['iOS Certificates'] = [
					['Development', data.iosCerts.dev ? data.iosCerts.devNames.join(', ') : 'not found'],
					['Distribution', data.iosCerts.dist ? data.iosCerts.distNames.join(', ') : 'not found'],
					['Apple WWDR', data.iosCerts.wwdr ? 'installed' : 'not found']
				];

				var pp = sections['Development iOS Provisioning Profiles'] = {};
				if (data.iOSProvisioningProfiles.development.length) {
					data.iOSProvisioningProfiles.development.forEach(function (profile) {
						pp[profile.name] = [
							['UUID', profile.uuid],
							['App Prefix', profile.appPrefix],
							['App Id', profile.appId]
						];
					});
				} else {
					pp['None'] = [];
				}

				pp = sections['Distribution iOS Provisioning Profiles'] = {};
				if (data.iOSProvisioningProfiles.distribution.length) {
					data.iOSProvisioningProfiles.distribution.forEach(function (profile) {
						pp[profile.name] = [
							['UUID', profile.uuid],
							['App Prefix', profile.appPrefix],
							['App Id', profile.appId]
						];
					});
				} else {
					pp['None'] = [];
				}

				pp = sections['Adhoc iOS Provisioning Profiles'] = {};
				if (data.iOSProvisioningProfiles.adhoc.length) {
					data.iOSProvisioningProfiles.adhoc.forEach(function (profile) {
						pp[profile.name] = [
							['UUID', profile.uuid],
							['App Prefix', profile.appPrefix],
							['App Id', profile.appId]
						];
					});
				} else {
					pp['None'] = [];
				}
			}

			var titanium = sections['Titanium SDKs'] = {};
			Object.keys(data.titanium).forEach(function (ver) {
				var x = data.titanium[ver];
				titanium[ver] = [
					['Install Location', x.path],
					['Platforms', Object.keys(x.platforms).join(', ')],
					['git Hash', x.githash || 'unknown'],
					['git Timestamp', x.timestamp || 'unknown']
				];
			});

			// find the max length of the left column
			var maxlen = 0;
			Object.keys(sections).forEach(function (section) {
				var s = sections[section];
				if (Array.isArray(s)) {
					s.forEach(function (i) {
						if (i[0].length > maxlen) {
							maxlen = i[0].length;
						}
					});
				} else {
					Object.keys(s).forEach(function (i) {
						if (i.length > maxlen) {
							maxlen = i.length;
						}
						s[i].forEach(function (j) {
							if (j[0].length > maxlen) {
								maxlen = j[0].length;
							}
						});
					});
				}
			});

			logger.banner();

			// print the sections and data
			Object.keys(sections).forEach(function (section) {
				var s = sections[section];
				logger.log(section.bold);

				if (Array.isArray(s)) {
					s.forEach(function (i) {
						logger.log('  %s = %s', appc.string.rpad(i[0], maxlen), ('' + i[1]).cyan);
					});
				} else {
					Object.keys(s).forEach(function (i) {
						logger.log((''+i).grey);
						s[i].forEach(function (j) {
							logger.log('  %s = %s', appc.string.rpad(j[0], maxlen), ('' + j[1]).cyan);
						});
					});
				}

				logger.log();
			});
		}
	});
};
<commit_msg>Added keychains to the info command.<commit_after>/*
 * info.js: Titanium CLI info command
 *
 * Copyright (c) 2012, Appcelerator, Inc.  All Rights Reserved.
 * See the LICENSE file for more information.
 */

var appc = require('node-appc'),
	env = appc.environ,
	mix = appc.util.mix,
	async = require('async'),
	path = require('path');

exports.config = function (logger, config, cli) {
	return {
		desc: __('display development environment information'),
		noAuth: true,
		skipBanner: true,
		options: {
			output: {
				abbr: 'o',
				default: 'report',
				desc: __('output format'),
				values: ['report', 'json']
			}
		}
	};
};

exports.run = function (logger, config, cli) {
	// important: we must duplicate every bit of info as to not accidentally
	// break the contract of the JSON formatted output.
	async.parallel([
		function (next) {
			env.getOSInfo(function (info) {
				next(null, {
					os: {
						name: info.os,
						version: info.osver,
						architecture: info.osarch,
						numcpus: info.oscpu,
						memory: info.memory
					},
					node: {
						version: info.node
					},
					npm: {
						version: info.npm
					}
				});
			});
		},

		function (next) {
			appc.ios.detect(function (info) {
				var result = { xcode: {} };
				Object.keys(info.xcode).forEach(function (ver) {
					if (ver != '__selected__') {
						result.xcode[ver] = {
							path: info.xcode[ver].path,
							xcodebuild: info.xcode[ver].xcodebuild,
							selected: info.xcode[ver].selected,
							version: info.xcode[ver].version,
							build: info.xcode[ver].build,
							sdks: [].concat(info.xcode[ver].sdks),
							sims: [].concat(info.xcode[ver].sims)
						};
					}
				});
				result.iosCerts = {
					dev: info.certs.dev,
					devNames: [].concat(info.certs.devNames),
					dist: info.certs.dist,
					distNames: [].concat(info.certs.distNames),
					wwdr: info.certs.wwdr
				};

				var pp = result.iOSProvisioningProfiles = {};
				Object.keys(info.provisioningProfiles).forEach(function (type) {
					pp[type] || (pp[type] = []);
					info.provisioningProfiles[type].forEach(function (profile) {
						pp[type].push(mix({}, profile));
					});
				});

				result.iOSKeychains = ['System Default'].concat(info.keychains);

				next(null, result);
			});
		},

		function (next) {
			appc.android.detect(function (info) {
				var result = {};

				next(null, { android: result });
			});
		},

		function (next) {
			var sdks = {};
			Object.keys(env.sdks).forEach(function (ver) {
				var n = env.sdks[ver];
				sdks[ver] = {
					path: n.path,
					platforms: Object.keys(n.platforms),
					githash: n.manifest ? n.manifest.githash : null,
					timestamp: n.manifest ? n.manifest.timestamp : null
				};
			});
			next(null, { titanium: sdks });
		}
	], function (err, results) {
		var data = mix.apply(null, results);

		if (cli.argv.output == 'json') {
			logger.log(JSON.stringify(data, null, '\t'));
		} else {
			var sections = {
				'Operating System': [
					['Name', data.os.name],
					['Version', data.os.version],
					['Architecture', data.os.architecture],
					['# CPUs', data.os.numcpus],
					['Memory', (data.os.memory / 1024 / 1024 / 1024).toFixed(1) + 'GB']
				],
				'node.js': [
					['node.js Version', data.node.version],
					['npm Version', data.npm.version]
				]
			};

			if (process.platform == 'darwin') {
				var xcode = sections['Xcode'] = {};
				Object.keys(data.xcode).forEach(function (ver) {
					var x = data.xcode[ver];
					xcode[x.version + ' (build ' + x.build + ')'] = [
						['Install Location', x.path],
						['Selected', x.selected],
						['iOS SDKs', x.sdks.length ? x.sdks.join(', ') : 'none'],
						['iOS Simulators', x.sims.length ? x.sims.join(', ') : 'none']
					];
				});

				sections['iOS Certificates'] = [
					['Development', data.iosCerts.dev ? data.iosCerts.devNames.join(', ') : 'not found'],
					['Distribution', data.iosCerts.dist ? data.iosCerts.distNames.join(', ') : 'not found'],
					['Apple WWDR', data.iosCerts.wwdr ? 'installed' : 'not found']
				];

				var pp = sections['Development iOS Provisioning Profiles'] = {};
				if (data.iOSProvisioningProfiles.development.length) {
					data.iOSProvisioningProfiles.development.forEach(function (profile) {
						pp[profile.name] = [
							['UUID', profile.uuid],
							['App Prefix', profile.appPrefix],
							['App Id', profile.appId]
						];
					});
				} else {
					pp['None'] = [];
				}

				pp = sections['Distribution iOS Provisioning Profiles'] = {};
				if (data.iOSProvisioningProfiles.distribution.length) {
					data.iOSProvisioningProfiles.distribution.forEach(function (profile) {
						pp[profile.name] = [
							['UUID', profile.uuid],
							['App Prefix', profile.appPrefix],
							['App Id', profile.appId]
						];
					});
				} else {
					pp['None'] = [];
				}

				pp = sections['Adhoc iOS Provisioning Profiles'] = {};
				if (data.iOSProvisioningProfiles.adhoc.length) {
					data.iOSProvisioningProfiles.adhoc.forEach(function (profile) {
						pp[profile.name] = [
							['UUID', profile.uuid],
							['App Prefix', profile.appPrefix],
							['App Id', profile.appId]
						];
					});
				} else {
					pp['None'] = [];
				}

				sections['iOS Keychains'] = data.iOSKeychains.map(function (keychain) {
					return [path.basename(keychain), keychain];
				});
			}

			var titanium = sections['Titanium SDKs'] = {};
			Object.keys(data.titanium).forEach(function (ver) {
				var x = data.titanium[ver];
				titanium[ver] = [
					['Install Location', x.path],
					['Platforms', x.platforms.join(', ')],
					['git Hash', x.githash || 'unknown'],
					['git Timestamp', x.timestamp || 'unknown']
				];
			});

			// find the max length of the left column
			var maxlen = 0;
			Object.keys(sections).forEach(function (section) {
				var s = sections[section];
				if (Array.isArray(s)) {
					s.forEach(function (i) {
						if (i[0].length > maxlen) {
							maxlen = i[0].length;
						}
					});
				} else {
					Object.keys(s).forEach(function (i) {
						if (i.length > maxlen) {
							maxlen = i.length;
						}
						s[i].forEach(function (j) {
							if (j[0].length > maxlen) {
								maxlen = j[0].length;
							}
						});
					});
				}
			});

			logger.banner();

			// print the sections and data
			Object.keys(sections).forEach(function (section) {
				var s = sections[section];
				logger.log(section.bold);

				if (Array.isArray(s)) {
					s.forEach(function (i) {
						logger.log('  %s = %s', appc.string.rpad(i[0], maxlen), ('' + i[1]).cyan);
					});
				} else {
					Object.keys(s).forEach(function (i) {
						logger.log((''+i).grey);
						s[i].forEach(function (j) {
							logger.log('  %s = %s', appc.string.rpad(j[0], maxlen), ('' + j[1]).cyan);
						});
					});
				}

				logger.log();
			});
		}
	});
};
<|endoftext|>


<commit_before>var mout = require('mout');
var fs = require('graceful-fs');
var path = require('path');
var Q = require('q');
var Logger = require('bower-logger');
var endpointParser = require('bower-endpoint-parser');
var Project = require('../core/Project');
var defaultConfig = require('../config');
var GitHubResolver = require('../core/resolvers/GitHubResolver');
var GitFsResolver = require('../core/resolvers/GitFsResolver');
var cli = require('../util/cli');
var cmd = require('../util/cmd');
var createError = require('../util/createError');

function init(config) {
    var project;
    var logger = new Logger();

    config = mout.object.deepFillIn(config || {}, defaultConfig);

    // This command requires interactive to be enabled
    if (!config.interactive) {
        process.nextTick(function () {
            logger.emit('error', createError('Register requires interactive', 'ENOINT'));
        });
        return logger;
    }

    project = new Project(config, logger);

    // Start with existing JSON details
    readJson(project, logger)
    // Fill in defaults
    .then(setDefaults.bind(null, config))
    // Now prompt user to make changes
    .then(promptUser.bind(null, logger))
    // Set ignore based on the response
    .spread(setIgnore)
    // Set dependencies based on the response
    .spread(setDependencies.bind(null, project))
    // All done!
    .spread(saveJson.bind(null, project, logger))
    .then(function (json) {
        logger.emit('end', json);
    })
    .fail(function (error) {
        logger.emit('error', error);
    });

    return logger;
}

function readJson(project, logger) {
    return project.hasJson()
    .then(function (json) {
        if (json) {
            logger.warn('existing', 'The existing ' + path.basename(json) + ' file will be used and filled in');
        }

        return project.getJson();
    });
}

function saveJson(project, logger, json) {
    // Cleanup empty props (null values, empty strings, objects and arrays)
    mout.object.forOwn(json, function (value, key) {
        if (value == null || mout.lang.isEmpty(value)) {
            delete json[key];
        }
    });

    logger.info('json', 'Generated json', { json: json });

    // Confirm the json with the user
    return Q.nfcall(logger.prompt.bind(logger), {
        type: 'confirm',
        message: 'Looks good?',
        default: true
    })
    .then(function (good) {
        if (!good) {
            return null;
        }

        // Save json (true forces file creation)
        return project.saveJson(true);
    });
}

function setDefaults(config, json) {
    var name;
    var promise = Q.resolve();

    // Name
    if (!json.name) {
        json.name = path.basename(config.cwd);
    }

    // Version
    if (!json.version) {
        // Assume latest semver tag if it's a git repo
        promise = promise.then(function () {
            return GitFsResolver.versions(config.cwd)
            .then(function (versions) {
                json.version = versions[0] || '0.0.0';
            }, function () {
                json.version = '0.0.0';
            });
        });
    }

    // Main
    if (!json.main) {
        // Remove '.js' from the end of the package name if it is there
        name = path.basename(json.name, '.js');

        if (fs.existsSync(path.join(config.cwd, 'index.js'))) {
            json.main = 'index.js';
        } else if (fs.existsSync(path.join(config.cwd, name + '.js'))) {
            json.main = name + '.js';
        }
    }

    // Homepage
    if (!json.homepage) {
        // Set as GitHub homepage if it's a GitHub repository
        promise = promise.then(function () {
            return cmd('git', ['config', '--get', 'remote.origin.url'])
            .spread(function (stdout) {
                var pair;

                stdout = stdout.trim();
                if (!stdout) {
                    return;
                }

                pair = GitHubResolver.getOrgRepoPair(stdout);
                if (pair) {
                    json.homepage = 'https://github.com/' + pair.org + '/' + pair.repo;
                }
            })
            .fail(function () { });
        });
    }

    if (!json.authors) {
        promise = promise.then(function () {
            // Get the user name configured in git
            return cmd('git', ['config', '--get', '--global', 'user.name'])
            .spread(function (stdout) {
                var gitEmail;
                var gitName = stdout.trim();

                // Abort if no name specified
                if (!gitName) {
                    return;
                }

                // Get the user email configured in git
                return cmd('git', ['config', '--get', '--global', 'user.email'])
                .spread(function (stdout) {
                    gitEmail = stdout.trim();
                }, function () {})
                .then(function () {
                    json.authors = gitName;
                    json.authors += gitEmail ? ' <' + gitEmail + '>' : '';
                });
            }, function () {});
        });
    }

    return promise.then(function () {
        return json;
    });
}

function promptUser(logger, json) {
    var questions = [
        {
            'name': 'name',
            'message': 'name',
            'default': json.name,
            'type': 'input'
        },
        {
            'name': 'version',
            'message': 'version',
            'default': json.version,
            'type': 'input'
        },
        {
            'name': 'description',
            'message': 'description',
            'default': json.description,
            'type': 'input'
        },
        {
            'name': 'main',
            'message': 'main file',
            'default': json.main,
            'type': 'input'
        },
        {
            'name': 'keywords',
            'message': 'keywords',
            'default': json.keywords ? json.keywords.toString() : null,
            'type': 'input'
        },
        {
            'name': 'authors',
            'message': 'authors',
            'default': json.authors ? json.authors.toString() : null,
            'type': 'input'
        },
        {
            'name': 'license',
            'message': 'license',
            'default': json.license || 'MIT',
            'type': 'input'
        },
        {
            'name': 'homepage',
            'message': 'homepage',
            'default': json.homepage,
            'type': 'input'
        },
        {
            'name': 'dependencies',
            'message': 'set currently installed components as dependencies?',
            'default': !mout.object.size(json.dependencies) && !mout.object.size(json.devDependencies),
            'type': 'confirm'
        },
        {
            'name': 'ignore',
            'message': 'add commonly ignored files to ignore list?',
            'default': true,
            'type': 'confirm'
        },
        {
            'name': 'private',
            'message': 'would you like to mark this package as private which prevents it from being accidentally published to the registry?',
            'default': !!json.private,
            'type': 'confirm'
        }
    ];

    return Q.nfcall(logger.prompt.bind(logger), questions)
    .then(function (answers) {
        json.name = answers.name;
        json.version = answers.version;
        json.description = answers.description;
        json.main = answers.main;
        json.keywords = toArray(answers.keywords);
        json.authors = toArray(answers.authors, ',');
        json.license = answers.license;
        json.homepage = answers.homepage;
        json.private = answers.private || null;

        return [json, answers];
    });
}

function toArray(value, splitter) {
    var arr = value.split(splitter || /[\s,]/);

    // Trim values
    arr = arr.map(function (item) {
        return item.trim();
    });

    // Filter empty values
    arr = arr.filter(function (item) {
        return !!item;
    });

    return arr.length ? arr : null;
}

function setIgnore(json, answers) {
    if (answers.ignore) {
        json.ignore = mout.array.combine(json.ignore || [], [
            '**/.*',
            'node_modules',
            'bower_components',
            'test',
            'tests'
        ]);
    }

    return [json, answers];
}

function setDependencies(project, json, answers) {
    if (answers.dependencies) {
        return project.getTree()
        .spread(function (tree, flattened, extraneous) {
            if (extraneous.length) {
                json.dependencies = {};

                // Add extraneous as dependencies
                extraneous.forEach(function (extra) {
                    var jsonEndpoint;

                    // Skip linked packages
                    if (extra.linked) {
                        return;
                    }

                    jsonEndpoint = endpointParser.decomposed2json(extra.endpoint);
                    mout.object.mixIn(json.dependencies, jsonEndpoint);
                });
            }

            return [json, answers];
        });
    }

    return [json, answers];
}

// -------------------

init.line = function () {
    return init();
};

init.options = function (argv) {
    return cli.readOptions(argv);
};

init.completion = function () {
    // TODO:
};

module.exports = init;
<commit_msg>Improve non-interactive shell error message.<commit_after>var mout = require('mout');
var fs = require('graceful-fs');
var path = require('path');
var Q = require('q');
var Logger = require('bower-logger');
var endpointParser = require('bower-endpoint-parser');
var Project = require('../core/Project');
var defaultConfig = require('../config');
var GitHubResolver = require('../core/resolvers/GitHubResolver');
var GitFsResolver = require('../core/resolvers/GitFsResolver');
var cli = require('../util/cli');
var cmd = require('../util/cmd');
var createError = require('../util/createError');

function init(config) {
    var project;
    var logger = new Logger();

    config = mout.object.deepFillIn(config || {}, defaultConfig);

    // This command requires interactive to be enabled
    if (!config.interactive) {
        process.nextTick(function () {
            logger.emit('error', createError('Register requires an interactive shell', 'ENOINT', {
                details: 'Note that you can manually force an interactive shell with --config.interactive'
            }));
        });
        return logger;
    }

    project = new Project(config, logger);

    // Start with existing JSON details
    readJson(project, logger)
    // Fill in defaults
    .then(setDefaults.bind(null, config))
    // Now prompt user to make changes
    .then(promptUser.bind(null, logger))
    // Set ignore based on the response
    .spread(setIgnore)
    // Set dependencies based on the response
    .spread(setDependencies.bind(null, project))
    // All done!
    .spread(saveJson.bind(null, project, logger))
    .then(function (json) {
        logger.emit('end', json);
    })
    .fail(function (error) {
        logger.emit('error', error);
    });

    return logger;
}

function readJson(project, logger) {
    return project.hasJson()
    .then(function (json) {
        if (json) {
            logger.warn('existing', 'The existing ' + path.basename(json) + ' file will be used and filled in');
        }

        return project.getJson();
    });
}

function saveJson(project, logger, json) {
    // Cleanup empty props (null values, empty strings, objects and arrays)
    mout.object.forOwn(json, function (value, key) {
        if (value == null || mout.lang.isEmpty(value)) {
            delete json[key];
        }
    });

    logger.info('json', 'Generated json', { json: json });

    // Confirm the json with the user
    return Q.nfcall(logger.prompt.bind(logger), {
        type: 'confirm',
        message: 'Looks good?',
        default: true
    })
    .then(function (good) {
        if (!good) {
            return null;
        }

        // Save json (true forces file creation)
        return project.saveJson(true);
    });
}

function setDefaults(config, json) {
    var name;
    var promise = Q.resolve();

    // Name
    if (!json.name) {
        json.name = path.basename(config.cwd);
    }

    // Version
    if (!json.version) {
        // Assume latest semver tag if it's a git repo
        promise = promise.then(function () {
            return GitFsResolver.versions(config.cwd)
            .then(function (versions) {
                json.version = versions[0] || '0.0.0';
            }, function () {
                json.version = '0.0.0';
            });
        });
    }

    // Main
    if (!json.main) {
        // Remove '.js' from the end of the package name if it is there
        name = path.basename(json.name, '.js');

        if (fs.existsSync(path.join(config.cwd, 'index.js'))) {
            json.main = 'index.js';
        } else if (fs.existsSync(path.join(config.cwd, name + '.js'))) {
            json.main = name + '.js';
        }
    }

    // Homepage
    if (!json.homepage) {
        // Set as GitHub homepage if it's a GitHub repository
        promise = promise.then(function () {
            return cmd('git', ['config', '--get', 'remote.origin.url'])
            .spread(function (stdout) {
                var pair;

                stdout = stdout.trim();
                if (!stdout) {
                    return;
                }

                pair = GitHubResolver.getOrgRepoPair(stdout);
                if (pair) {
                    json.homepage = 'https://github.com/' + pair.org + '/' + pair.repo;
                }
            })
            .fail(function () { });
        });
    }

    if (!json.authors) {
        promise = promise.then(function () {
            // Get the user name configured in git
            return cmd('git', ['config', '--get', '--global', 'user.name'])
            .spread(function (stdout) {
                var gitEmail;
                var gitName = stdout.trim();

                // Abort if no name specified
                if (!gitName) {
                    return;
                }

                // Get the user email configured in git
                return cmd('git', ['config', '--get', '--global', 'user.email'])
                .spread(function (stdout) {
                    gitEmail = stdout.trim();
                }, function () {})
                .then(function () {
                    json.authors = gitName;
                    json.authors += gitEmail ? ' <' + gitEmail + '>' : '';
                });
            }, function () {});
        });
    }

    return promise.then(function () {
        return json;
    });
}

function promptUser(logger, json) {
    var questions = [
        {
            'name': 'name',
            'message': 'name',
            'default': json.name,
            'type': 'input'
        },
        {
            'name': 'version',
            'message': 'version',
            'default': json.version,
            'type': 'input'
        },
        {
            'name': 'description',
            'message': 'description',
            'default': json.description,
            'type': 'input'
        },
        {
            'name': 'main',
            'message': 'main file',
            'default': json.main,
            'type': 'input'
        },
        {
            'name': 'keywords',
            'message': 'keywords',
            'default': json.keywords ? json.keywords.toString() : null,
            'type': 'input'
        },
        {
            'name': 'authors',
            'message': 'authors',
            'default': json.authors ? json.authors.toString() : null,
            'type': 'input'
        },
        {
            'name': 'license',
            'message': 'license',
            'default': json.license || 'MIT',
            'type': 'input'
        },
        {
            'name': 'homepage',
            'message': 'homepage',
            'default': json.homepage,
            'type': 'input'
        },
        {
            'name': 'dependencies',
            'message': 'set currently installed components as dependencies?',
            'default': !mout.object.size(json.dependencies) && !mout.object.size(json.devDependencies),
            'type': 'confirm'
        },
        {
            'name': 'ignore',
            'message': 'add commonly ignored files to ignore list?',
            'default': true,
            'type': 'confirm'
        },
        {
            'name': 'private',
            'message': 'would you like to mark this package as private which prevents it from being accidentally published to the registry?',
            'default': !!json.private,
            'type': 'confirm'
        }
    ];

    return Q.nfcall(logger.prompt.bind(logger), questions)
    .then(function (answers) {
        json.name = answers.name;
        json.version = answers.version;
        json.description = answers.description;
        json.main = answers.main;
        json.keywords = toArray(answers.keywords);
        json.authors = toArray(answers.authors, ',');
        json.license = answers.license;
        json.homepage = answers.homepage;
        json.private = answers.private || null;

        return [json, answers];
    });
}

function toArray(value, splitter) {
    var arr = value.split(splitter || /[\s,]/);

    // Trim values
    arr = arr.map(function (item) {
        return item.trim();
    });

    // Filter empty values
    arr = arr.filter(function (item) {
        return !!item;
    });

    return arr.length ? arr : null;
}

function setIgnore(json, answers) {
    if (answers.ignore) {
        json.ignore = mout.array.combine(json.ignore || [], [
            '**/.*',
            'node_modules',
            'bower_components',
            'test',
            'tests'
        ]);
    }

    return [json, answers];
}

function setDependencies(project, json, answers) {
    if (answers.dependencies) {
        return project.getTree()
        .spread(function (tree, flattened, extraneous) {
            if (extraneous.length) {
                json.dependencies = {};

                // Add extraneous as dependencies
                extraneous.forEach(function (extra) {
                    var jsonEndpoint;

                    // Skip linked packages
                    if (extra.linked) {
                        return;
                    }

                    jsonEndpoint = endpointParser.decomposed2json(extra.endpoint);
                    mout.object.mixIn(json.dependencies, jsonEndpoint);
                });
            }

            return [json, answers];
        });
    }

    return [json, answers];
}

// -------------------

init.line = function () {
    return init();
};

init.options = function (argv) {
    return cli.readOptions(argv);
};

init.completion = function () {
    // TODO:
};

module.exports = init;
<|endoftext|>


<commit_before>var kanso = require('../kanso'),
    couchdb = require('../couchdb'),
    logger = require('../logger'),
    argParse = require('../args').parse,
    utils = require('../utils'),
    settings = require('../settings'),
    urlParse = require('url').parse,
    urlFormat = require('url').format;

exports.summary = 'Upload a project to a CouchDB instance';
exports.usage = '' +
'kanso push [OPTIONS] DB [PATH]\n' +
'\n' +
'Parameters:\n' +
'  DB     The CouchDB instance to upload the app to\n' +
'  PATH   The project path to load the app from\n' +
'\n' +
'Options:\n' +
'  --minify               Compress CommonJS modules using UglifyJS\n' +
'  --minify-attachments   Compress .js attachments\n' +
'  --baseURL PATH         Force the baseURL to a specific value.\n' +
'                         (allows vhosts on CouchDB < v1.1.x)';

exports.run = function (args) {
    var a = argParse(args, {
        'minify': {match: '--minify'},
        'minify_attachments': {match: '--minify-attachments'},
        'baseURL': {match: '--baseURL', value: true}
    });
    if (!a.positional[0]) {
        return logger.error('No CouchDB URL specified');
    }
    var dir = a.positional[1] || '.';
    settings.load(dir, function (err, settings) {
        if (err) {
            return logger.error(err);
        }
        settings.minify = a.options.minify;
        settings.minify_attachments = a.options.minify_attachments;
        if (a.options.baseURL !== undefined) {
            settings.baseURL = a.options.baseURL || '';
        }
        var url = a.positional[0].replace(/\/$/, '');
        exports.loadApp(dir, settings, url, function (err, appurl) {
            if (err) {
                return logger.error(err);
            }
            logger.end(
                appurl + '/_design/' +
                settings.name + '/_rewrite/'
            );
        });
    });
};

exports.loadApp = function (dir, settings, url, callback) {
    kanso.load(dir, settings, function (err, doc) {
        if (err) {
            if (callback) {
                return callback(err);
            }
            else {
                return logger.error(err);
            }
        }
        exports.push(dir, settings, doc, url, callback);
    });
};

exports.authError = function (err, dir, settings, doc, url, callback) {
    logger.error(err);
    if (err.response && err.response.statusCode === 401) {
        utils.getAuth(url, function (err, url) {
            if (err) {
                if (calback) {
                    return callback(err);
                }
                else {
                    return logger.error(err);
                }
            }
            exports.push(dir, settings, doc, url, callback);
        });
    }
};

exports.push = function (dir, settings, doc, url, callback) {
    var parsed = urlParse(url);
    // if only a username has been specified, ask for password
    if (parsed.auth && parsed.auth.split(':').length === 1) {
        utils.getPassword(function (err, password) {
            delete parsed.host;
            parsed.auth += ':' + password;
            url = urlFormat(parsed);
            exports.push(dir, settings, doc, url, callback);
        });
        return;
    }
    var db = couchdb(url);
    db.ensureDB(function (err) {
        if (err) {
            return exports.authError(err, dir, settings, doc, url, callback);
        }
        var id = '_design/' + settings.name;
        logger.info('Uploading...');
        db.save(id, doc, {force: true}, function (err) {
            if (err) {
                return exports.authError(err, dir, settings, doc, url, callback);
            }
            var appurl = urlParse(url);
            delete appurl.auth;
            delete appurl.host;
            appurl = urlFormat(appurl);
            if (callback) {
                callback(null, appurl, url);
            }
            else {
                logger.end(
                    appurl + '/_design/' +
                    settings.name + '/_rewrite/'
                );
            }
        });
    });
};
<commit_msg>#119 allow kanso cmdline tool to assume 127.0.0.1:5984 for couch instance.<commit_after>var kanso = require('../kanso'),
    couchdb = require('../couchdb'),
    logger = require('../logger'),
    argParse = require('../args').parse,
    utils = require('../utils'),
    settings = require('../settings'),
    urlParse = require('url').parse,
    urlFormat = require('url').format;

exports.summary = 'Upload a project to a CouchDB instance';
exports.usage = '' +
'kanso push [OPTIONS] DB [PATH]\n' +
'\n' +
'Parameters:\n' +
'  DB     The CouchDB instance to upload the app to\n' +
'  PATH   The project path to load the app from\n' +
'\n' +
'Options:\n' +
'  --minify               Compress CommonJS modules using UglifyJS\n' +
'  --minify-attachments   Compress .js attachments\n' +
'  --baseURL PATH         Force the baseURL to a specific value.\n' +
'                         (allows vhosts on CouchDB < v1.1.x)';

exports.run = function (args) {
    var a = argParse(args, {
        'minify': {match: '--minify'},
        'minify_attachments': {match: '--minify-attachments'},
        'baseURL': {match: '--baseURL', value: true}
    });
    if (!a.positional[0]) {
        return logger.error('No CouchDB URL specified');
    }
    var dir = a.positional[1] || '.';
    settings.load(dir, function (err, settings) {
        if (err) {
            return logger.error(err);
        }
        settings.minify = a.options.minify;
        settings.minify_attachments = a.options.minify_attachments;
        if (a.options.baseURL !== undefined) {
            settings.baseURL = a.options.baseURL || '';
        }
        var url = a.positional[0].replace(/\/$/, '');
        url = url.search(/^http/) != -1 ? url : 'http://127.0.0.1:5984/' + url;
        exports.loadApp(dir, settings, url, function (err, appurl) {
            if (err) {
                return logger.error(err);
            }
            logger.end(
                appurl + '/_design/' +
                settings.name + '/_rewrite/'
            );
        });
    });
};

exports.loadApp = function (dir, settings, url, callback) {
    kanso.load(dir, settings, function (err, doc) {
        if (err) {
            if (callback) {
                return callback(err);
            }
            else {
                return logger.error(err);
            }
        }
        exports.push(dir, settings, doc, url, callback);
    });
};

exports.authError = function (err, dir, settings, doc, url, callback) {
    logger.error(err);
    if (err.response && err.response.statusCode === 401) {
        utils.getAuth(url, function (err, url) {
            if (err) {
                if (calback) {
                    return callback(err);
                }
                else {
                    return logger.error(err);
                }
            }
            exports.push(dir, settings, doc, url, callback);
        });
    }
};

exports.push = function (dir, settings, doc, url, callback) {
    var parsed = urlParse(url);
    // if only a username has been specified, ask for password
    if (parsed.auth && parsed.auth.split(':').length === 1) {
        utils.getPassword(function (err, password) {
            delete parsed.host;
            parsed.auth += ':' + password;
            url = urlFormat(parsed);
            exports.push(dir, settings, doc, url, callback);
        });
        return;
    }
    var db = couchdb(url);
    db.ensureDB(function (err) {
        if (err) {
            return exports.authError(err, dir, settings, doc, url, callback);
        }
        var id = '_design/' + settings.name;
        logger.info('Uploading...');
        db.save(id, doc, {force: true}, function (err) {
            if (err) {
                return exports.authError(err, dir, settings, doc, url, callback);
            }
            var appurl = urlParse(url);
            delete appurl.auth;
            delete appurl.host;
            appurl = urlFormat(appurl);
            if (callback) {
                callback(null, appurl, url);
            }
            else {
                logger.end(
                    appurl + '/_design/' +
                    settings.name + '/_rewrite/'
                );
            }
        });
    });
};
<|endoftext|>


<commit_before>// Dependencies
var Which = require("which")
  , Exec = require("child_process").exec
  , OArgv = require("oargv")
  , Path = require("path")
  ;

/**
 * CheckCobc
 * Checks if `cobc` exists as executable.
 *
 * @name CheckCobc
 * @function
 * @param {Function} callback The callback function.
 */
var _cobcExists = false;
function CheckCobc(callback) {
    if (_cobcExists) {
        return process.nextTick(function () {
            callback(_cobcExists);
        });
    }
    Which("cobc", function (err) {
        _cobcExists = !err;
        callback(_cobcExists);
    });
}

/**
 * Compile
 * Compiles the cobol file.
 *
 * @name Compile
 * @function
 * @param {String} input The path to the cobol file.
 * @param {Object} options An object containing the following fields:
 * @param {Function} callback The callback function.
 */
function Compile(input, options, callback) {
    CheckCobc(function (exists) {
        if (!exists) {
            return callback(new Error("Couldn't find the cobc executable in the PATH. Make sure you installed Open Cobol."));
        }

        var args = {
            x: true
          , _: input
        };
        if (options.free) {
            args.free = options.free;
        }
	if(options.l) {
	    args.l = options.l;
	}

        Exec(OArgv(args, "cobc"), {
            cwd: options.cwd
        }, function (err, stdout, stderr) {
            if (stderr || err) {
                return callback(stderr || err);
            }
            var output = Path.join(options.cwd, Path.basename(input).slice(0, -4));
            callback(null, output);
        })
    });
}

module.exports = Compile;
<commit_msg>Fixed indentation<commit_after>// Dependencies
var Which = require("which")
  , Exec = require("child_process").exec
  , OArgv = require("oargv")
  , Path = require("path")
  ;

/**
 * CheckCobc
 * Checks if `cobc` exists as executable.
 *
 * @name CheckCobc
 * @function
 * @param {Function} callback The callback function.
 */
var _cobcExists = false;
function CheckCobc(callback) {
    if (_cobcExists) {
        return process.nextTick(function () {
            callback(_cobcExists);
        });
    }
    Which("cobc", function (err) {
        _cobcExists = !err;
        callback(_cobcExists);
    });
}

/**
 * Compile
 * Compiles the cobol file.
 *
 * @name Compile
 * @function
 * @param {String} input The path to the cobol file.
 * @param {Object} options An object containing the following fields:
 * @param {Function} callback The callback function.
 */
function Compile(input, options, callback) {
    CheckCobc(function (exists) {
        if (!exists) {
            return callback(new Error("Couldn't find the cobc executable in the PATH. Make sure you installed Open Cobol."));
        }

        var args = {
            x: true
          , _: input
        };
        if (options.free) {
            args.free = options.free;
        }

	if(options.l) {
	    args.l = options.l;
	}

        Exec(OArgv(args, "cobc"), {
            cwd: options.cwd
        }, function (err, stdout, stderr) {
            if (stderr || err) {
                return callback(stderr || err);
            }
            var output = Path.join(options.cwd, Path.basename(input).slice(0, -4));
            callback(null, output);
        })
    });
}

module.exports = Compile;
<|endoftext|>


<commit_before>const fs = require('fs');
require('util.promisify/shim')(); // NOTE: shim for native node 8.0 uril.promisify
const util = require('util');
const readFile = util.promisify(fs.readFile);
const writeFile = util.promisify(fs.writeFile);
const YAWN = require('yawn-yaml/cjs');
const path = require('path');
const log = require('../logger').config;
const chokidar = require('chokidar');
const glob = require('glob');
const yamlOrJson = require('js-yaml');
const eventBus = require('../eventBus');
const schemas = require('../schemas');

class Config {
  constructor () {
    this.gatewayConfig = null;
    this.systemConfig = null;
    this.gatewayConfigPath = null;
    this.systemConfigPath = null;

    this.models = {};

    this.watchers = {
      system: null,
      gateway: null
    };

    this.gatewayValidator = schemas.register('config', 'gateway.config', require('./gateway.config.json'));
    this.systemValidator = schemas.register('config', 'system.config', require('./system.config.json'));
  }

  loadSystemConfig () {
    let systemConfig;
    let systemConfigPath = this.systemConfigPath || path.join(process.env.EG_CONFIG_DIR, 'system.config.yml');

    try {
      systemConfig = yamlOrJson.load(fs.readFileSync(systemConfigPath));
    } catch (err) {
      try {
        systemConfigPath = path.join(process.env.EG_CONFIG_DIR, 'system.config.json');

        systemConfig = yamlOrJson.load(fs.readFileSync(systemConfigPath));
      } catch (err) {
        log.error(`failed to (re)load system config: ${err}`);
        throw (err);
      }
    }

    const { isValid, error } = this.systemValidator(systemConfig);

    if (!isValid) {
      throw new Error(error);
    }

    this.systemConfig = systemConfig;
    this.systemConfigPath = systemConfigPath;
    log.debug('systemConfigPath: ', systemConfigPath);
  }

  loadGatewayConfig () {
    let gatewayConfigPath = this.gatewayConfigPath || path.join(process.env.EG_CONFIG_DIR, 'gateway.config.yml');
    let gatewayConfig;

    try {
      gatewayConfig = yamlOrJson.load(fs.readFileSync(gatewayConfigPath));
    } catch (err) {
      log.warn(err);
      try {
        gatewayConfigPath = path.join(process.env.EG_CONFIG_DIR, 'gateway.config.json');

        gatewayConfig = yamlOrJson.load(fs.readFileSync(gatewayConfigPath));
      } catch (err) {
        log.error(`failed to (re)load gateway config: ${err}`);
        throw (err);
      }
    }

    const { isValid, error } = this.gatewayValidator(gatewayConfig);

    if (!isValid) {
      throw new Error(error);
    }

    this.gatewayConfig = gatewayConfig;
    this.gatewayConfigPath = gatewayConfigPath;
    log.debug('gatewayConfigPath: ', gatewayConfigPath);
  }

  loadModels () {
    glob.sync(path.resolve(process.env.EG_CONFIG_DIR, 'models', '*.json')).forEach(module => {
      const name = path.basename(module, '.json');
      this.models[name] = require(module);
      schemas.register('model', name, this.models[name]);
      log.info(`Registered schema for ${name} model.`);
    });
  }

  watch () {
    const watchEvents = ['add', 'change'];

    const watchOptions = {
      awaitWriteFinish: true,
      ignoreInitial: true
    };

    const systemWatcher = chokidar.watch(this.systemConfigPath, watchOptions);
    const gatewayWatcher = chokidar.watch(this.gatewayConfigPath, watchOptions);

    watchEvents.forEach(watchEvent => {
      systemWatcher.on(watchEvent, name => {
        log.info(`${watchEvent} event on ${name} file. Reloading system config ` +
          `file from ${this.systemConfigPath}`);
        this.loadSystemConfig();
        eventBus.emit('hot-reload', { type: 'system', config: this });
      });

      gatewayWatcher.on(watchEvent, name => {
        log.info(`${watchEvent} event on ${name} file. Reloading gateway config ` +
          `file from ${this.gatewayConfigPath}`);
        this.loadGatewayConfig();
        eventBus.emit('hot-reload', { type: 'gateway', config: this });
      });
    });

    this.watchers.system = systemWatcher;
    this.watchers.gateway = gatewayWatcher;

    systemWatcher.on('ready', () => {
      systemWatcher.isReady = true;
    });

    gatewayWatcher.on('ready', () => {
      gatewayWatcher.isReady = true;
    });
  }

  updateGatewayConfig (modifier) {
    return this._updateConfigFile(this.gatewayConfigPath, modifier);
  }
  updateSystemConfig (modifier) {
    return this._updateConfigFile(this.systemConfigPath, modifier);
  }

  // this function can preserve comments and formatting.
  // due to fragile nature of YAWN it may not work properly in that mode.
  // safe way is to use it in rewrite file mode
  _updateConfigFile (path, modifier) {
    return readFile(path, 'utf8').then(data => {
      let text;
      const isJSON = path.toLowerCase().endsWith('.json');
      if (this.systemConfig && this.systemConfig.preserveStructureOnUpdates && !isJSON) {
        const yawn = new YAWN(data);
        yawn.json = modifier(yawn.json);
        text = yawn.yaml;
      } else { // js-yaml can handle JSON as well as YAML if no need for structure\comments save
        const json = yamlOrJson.load(data);
        const result = modifier(json);
        text = yamlOrJson.dump(result);
      }
      return writeFile(path, text);
    });
  }
}

module.exports = Config;
<commit_msg>Do not crash if loading fails<commit_after>const fs = require('fs');
require('util.promisify/shim')(); // NOTE: shim for native node 8.0 uril.promisify
const util = require('util');
const readFile = util.promisify(fs.readFile);
const writeFile = util.promisify(fs.writeFile);
const YAWN = require('yawn-yaml/cjs');
const path = require('path');
const log = require('../logger').config;
const chokidar = require('chokidar');
const glob = require('glob');
const yamlOrJson = require('js-yaml');
const eventBus = require('../eventBus');
const schemas = require('../schemas');

class Config {
  constructor () {
    this.gatewayConfig = null;
    this.systemConfig = null;
    this.gatewayConfigPath = null;
    this.systemConfigPath = null;

    this.models = {};

    this.watchers = {
      system: null,
      gateway: null
    };

    this.gatewayValidator = schemas.register('config', 'gateway.config', require('./gateway.config.json'));
    this.systemValidator = schemas.register('config', 'system.config', require('./system.config.json'));
  }

  loadSystemConfig () {
    let systemConfig;
    let systemConfigPath = this.systemConfigPath || path.join(process.env.EG_CONFIG_DIR, 'system.config.yml');

    try {
      systemConfig = yamlOrJson.load(fs.readFileSync(systemConfigPath));
    } catch (err) {
      try {
        systemConfigPath = path.join(process.env.EG_CONFIG_DIR, 'system.config.json');

        systemConfig = yamlOrJson.load(fs.readFileSync(systemConfigPath));
      } catch (err) {
        log.error(`failed to (re)load system config: ${err}`);
        throw (err);
      }
    }

    const { isValid, error } = this.systemValidator(systemConfig);

    if (!isValid) {
      throw new Error(error);
    }

    this.systemConfig = systemConfig;
    this.systemConfigPath = systemConfigPath;
    log.debug('systemConfigPath: ', systemConfigPath);
  }

  loadGatewayConfig () {
    let gatewayConfigPath = this.gatewayConfigPath || path.join(process.env.EG_CONFIG_DIR, 'gateway.config.yml');
    let gatewayConfig;

    try {
      gatewayConfig = yamlOrJson.load(fs.readFileSync(gatewayConfigPath));
    } catch (err) {
      log.warn(err);
      try {
        gatewayConfigPath = path.join(process.env.EG_CONFIG_DIR, 'gateway.config.json');

        gatewayConfig = yamlOrJson.load(fs.readFileSync(gatewayConfigPath));
      } catch (err) {
        log.error(`failed to (re)load gateway config: ${err}`);
        throw (err);
      }
    }

    const { isValid, error } = this.gatewayValidator(gatewayConfig);

    if (!isValid) {
      throw new Error(error);
    }

    this.gatewayConfig = gatewayConfig;
    this.gatewayConfigPath = gatewayConfigPath;
    log.debug('gatewayConfigPath: ', gatewayConfigPath);
  }

  loadModels () {
    glob.sync(path.resolve(process.env.EG_CONFIG_DIR, 'models', '*.json')).forEach(module => {
      const name = path.basename(module, '.json');
      this.models[name] = require(module);
      schemas.register('model', name, this.models[name]);
      log.info(`Registered schema for ${name} model.`);
    });
  }

  watch () {
    const watchEvents = ['add', 'change'];

    const watchOptions = {
      awaitWriteFinish: true,
      ignoreInitial: true
    };

    const systemWatcher = chokidar.watch(this.systemConfigPath, watchOptions);
    const gatewayWatcher = chokidar.watch(this.gatewayConfigPath, watchOptions);

    watchEvents.forEach(watchEvent => {
      systemWatcher.on(watchEvent, name => {
        log.info(`${watchEvent} event on ${name} file. Reloading system config ` +
          `file from ${this.systemConfigPath}`);
        try { this.loadSystemConfig(); } catch (e) { }
        eventBus.emit('hot-reload', { type: 'system', config: this });
      });

      gatewayWatcher.on(watchEvent, name => {
        log.info(`${watchEvent} event on ${name} file. Reloading gateway config ` +
          `file from ${this.gatewayConfigPath}`);
        try { this.loadGatewayConfig(); } catch (e) { }
        eventBus.emit('hot-reload', { type: 'gateway', config: this });
      });
    });

    this.watchers.system = systemWatcher;
    this.watchers.gateway = gatewayWatcher;

    systemWatcher.on('ready', () => {
      systemWatcher.isReady = true;
    });

    gatewayWatcher.on('ready', () => {
      gatewayWatcher.isReady = true;
    });
  }

  updateGatewayConfig (modifier) {
    return this._updateConfigFile(this.gatewayConfigPath, modifier);
  }
  updateSystemConfig (modifier) {
    return this._updateConfigFile(this.systemConfigPath, modifier);
  }

  // this function can preserve comments and formatting.
  // due to fragile nature of YAWN it may not work properly in that mode.
  // safe way is to use it in rewrite file mode
  _updateConfigFile (path, modifier) {
    return readFile(path, 'utf8').then(data => {
      let text;
      const isJSON = path.toLowerCase().endsWith('.json');
      if (this.systemConfig && this.systemConfig.preserveStructureOnUpdates && !isJSON) {
        const yawn = new YAWN(data);
        yawn.json = modifier(yawn.json);
        text = yawn.yaml;
      } else { // js-yaml can handle JSON as well as YAML if no need for structure\comments save
        const json = yamlOrJson.load(data);
        const result = modifier(json);
        text = yamlOrJson.dump(result);
      }
      return writeFile(path, text);
    });
  }
}

module.exports = Config;
<|endoftext|>


<commit_before>/*
 * Copyright 2014-2015 Fabian Tollenaar <fabian@starting-point.nl>
 *
 * 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.
*/

module.exports = function(app) {

  "use strict";

  var path          = require('path')
    , express       = require("express")
    , EventEmitter  = require("events").EventEmitter
    , debug         = require('debug')('signalk-server:config:config')
    , cors          = require('cors')
    , config        = app.config = {}
    , env           = app.env = process.env
  ;

  config.getExternalHostname = getExternalHostname.bind(config, config);
  config.getExternalPort = getExternalPort.bind(config, config);

  app.event = new EventEmitter();
  app.use(cors());

  try {
    var pkg = require('../../package.json');

    config.name     = pkg.name;
    config.author   = pkg.author;
    config.version  = pkg.version;
  } catch(err) {
    console.error('error parsing package.json', err);

    config.settings = {};
    config.name     = "";
    config.author   = "";
    config.vesion   = -1;
  }

  config.appPath    = path.normalize(__dirname + '/../../');
  config.port       = env.PORT || 3000;

  if(app.overrides.port && typeof app.overrides.port === 'number') {
    debug('Port number was set using .start(), overriding all other options');
    config.port = app.overrides.port;
  }

  debug("Config - appPath: " + config.appPath);
  debug("Config - port: " + config.port);

  require('./development')(app);
  require('./production')(app);
  require('./cli')(app);
};

function getExternalHostname(config) {
  if(config.settings.proxy_host) {
    return config.settings.proxy_host;
  } else if(config.hostname) {
    return config.hostname;
  }
  try {
    return require('os').hostname();
  } catch(ex) {
    return "hostname_not_available";
  }
}

function getExternalPort(config) {
  console.log(config);
  if(config.settings.proxy_port) {
    return config.settings.proxy_port;
  } else if(config.port) {
    return config.port;
  }
  return '';
}
<commit_msg>Remove console.log<commit_after>/*
 * Copyright 2014-2015 Fabian Tollenaar <fabian@starting-point.nl>
 *
 * 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.
*/

module.exports = function(app) {

  "use strict";

  var path          = require('path')
    , express       = require("express")
    , EventEmitter  = require("events").EventEmitter
    , debug         = require('debug')('signalk-server:config:config')
    , cors          = require('cors')
    , config        = app.config = {}
    , env           = app.env = process.env
  ;

  config.getExternalHostname = getExternalHostname.bind(config, config);
  config.getExternalPort = getExternalPort.bind(config, config);

  app.event = new EventEmitter();
  app.use(cors());

  try {
    var pkg = require('../../package.json');

    config.name     = pkg.name;
    config.author   = pkg.author;
    config.version  = pkg.version;
  } catch(err) {
    console.error('error parsing package.json', err);

    config.settings = {};
    config.name     = "";
    config.author   = "";
    config.vesion   = -1;
  }

  config.appPath    = path.normalize(__dirname + '/../../');
  config.port       = env.PORT || 3000;

  if(app.overrides.port && typeof app.overrides.port === 'number') {
    debug('Port number was set using .start(), overriding all other options');
    config.port = app.overrides.port;
  }

  debug("Config - appPath: " + config.appPath);
  debug("Config - port: " + config.port);

  require('./development')(app);
  require('./production')(app);
  require('./cli')(app);
};

function getExternalHostname(config) {
  if(config.settings.proxy_host) {
    return config.settings.proxy_host;
  } else if(config.hostname) {
    return config.hostname;
  }
  try {
    return require('os').hostname();
  } catch(ex) {
    return "hostname_not_available";
  }
}

function getExternalPort(config) {
  if(config.settings.proxy_port) {
    return config.settings.proxy_port;
  } else if(config.port) {
    return config.port;
  }
  return '';
}
<|endoftext|>


<commit_before>var ressources = require('./ressources.json');

module.exports = {

  /**
  * Here your can configure your routes, this is a simple JSOM format
  * Each route is identify by its path like /books/:id
  * Then this object can specify a method for the route --> Default GET
  * There must have an action on each route
  * You can specify a controller where you action is define --> in api/controllers directory
  * You can specify middleware to use
  * You can specify if this route must be authenticate
  * You can specify if you want that this route send socket.
  * You can specify necessary parameters
  * You can specify what the user should have to be able to call the route ex : administrator
  **/

  default: {
    method: 'GET',
    auth  : false
  },

  ressources: ressources,

  // REST API ---------------------------------------------------------------------
  // BASE ROUTE =======================
  '/': {
    action: function(req, res) {
      var json = {
        message: 'Welcome on our Api'
      };
      res.json(json);
    },
    auth: false
  },

  // REQUEST AUTHENTCATION ROUTE =======================
  '/login': {
    method    : 'POST',
    uses      : 'authController@login',
    middleware: ['generateAuth'],
    parameters: ['username', 'password'],
    auth      : false
  },

  '/me' : {
    uses: 'userController@me'
  },

  // // USER ======================
  // Sign Up
  '/users/signup': {
    method    : 'POST',
    uses      : 'userController@signup',
    parameters: ['username', 'password'],
    auth      : false
  },

  '/users/:id': {
    uses: 'userController@get'
  },

  // // TODOS =======================
  // DONE

  '/todos': {
    method: 'EGT',
    uses  : 'todoController@test',
    auth: false
  },

  '/todos/:id/done': {
    method: 'PUT',
    uses  : 'todoController@done',
    socket: true
  },

  // UNDO
  '/todos/:id/undo': {
    method: 'PUT',
    uses  : 'todoController@undo',
    socket: true
  }

};
<commit_msg>delete test route<commit_after>var ressources = require('./ressources.json');

module.exports = {

  /**
  * Here your can configure your routes, this is a simple JSOM format
  * Each route is identify by its path like /books/:id
  * Then this object can specify a method for the route --> Default GET
  * There must have an action on each route
  * You can specify a controller where you action is define --> in api/controllers directory
  * You can specify middleware to use
  * You can specify if this route must be authenticate
  * You can specify if you want that this route send socket.
  * You can specify necessary parameters
  * You can specify what the user should have to be able to call the route ex : administrator
  **/

  default: {
    method: 'GET',
    auth  : false
  },

  ressources: ressources,

  // REST API ---------------------------------------------------------------------
  // BASE ROUTE =======================
  '/': {
    action: function(req, res) {
      var json = {
        message: 'Welcome on our Api'
      };
      res.json(json);
    },
    auth: false
  },

  // REQUEST AUTHENTCATION ROUTE =======================
  '/login': {
    method    : 'POST',
    uses      : 'authController@login',
    middleware: ['generateAuth'],
    parameters: ['username', 'password'],
    auth      : false
  },

  '/me' : {
    uses: 'userController@me'
  },

  // // USER ======================
  // Sign Up
  '/users/signup': {
    method    : 'POST',
    uses      : 'userController@signup',
    parameters: ['username', 'password'],
    auth      : false
  },

  '/users/:id': {
    uses: 'userController@get'
  },

  // // TODOS =======================
  // DONE
  '/todos/:id/done': {
    method: 'PUT',
    uses  : 'todoController@done',
    socket: true
  },

  // UNDO
  '/todos/:id/undo': {
    method: 'PUT',
    uses  : 'todoController@undo',
    socket: true
  }

};
<|endoftext|>


<commit_before>'use strict';

var _ = require('lodash');
var path = require('path');

var constants = require('../definitions/constants.js');
var descriptor = require('./descriptor.js');

function newModuleEntry() {

  return {
    type: constants.MODULE_TYPE_SINGLETON,
    implements: [],
    inject: [],
    status: constants.FILE_STATUS_UNCHECKED,
    cache: {
      module: null,
      instantiationPromise: null,
      singletonInstance: null
    }
  };

}

function newInterfaceEntry(interfaceName) {

  return {
    interfaceName: interfaceName,
    interfaces: [],
    file: null,
    conflictingFiles: null
  };

}

function newRegistry(fireUp) {

  var registry = {

    basePathForFileRefs: process.cwd(),
    modules: {},
    interfaces: {}

  };

  registry.registerInterface = function (filePathRelativeToCwd, implementedInterface) {

    var interfaceChain = descriptor.parseInterfaceName(implementedInterface);
    var registryPointer = fireUp._internal.registry.interfaces;
    var currentInterface = "";

    for ( var p = 0; p < interfaceChain.length; p+=1 ) {

      if (p > 0) {
        currentInterface += ":";
      }
      currentInterface += interfaceChain[p];

      if (_.isPlainObject(registryPointer[interfaceChain[p]]) === false) {
        registryPointer[interfaceChain[p]] = newInterfaceEntry(currentInterface);
      }

      // Check for conflicts when arriving at last sub interface
      if (p === interfaceChain.length-1) {

        if (_.isNull(registryPointer[interfaceChain[p]].file) === false ||
            _.isNull(registryPointer[interfaceChain[p]].conflictingFiles) === false) {

          if (_.isNull(registryPointer[interfaceChain[p]].conflictingFiles)) {
            registryPointer[interfaceChain[p]].conflictingFiles = [];
          }
          if (_.isNull(registryPointer[interfaceChain[p]].file) === false) {
            registryPointer[interfaceChain[p]].conflictingFiles.push(registryPointer[interfaceChain[p]].file);
            registryPointer[interfaceChain[p]].file = null;
          }
          registryPointer[interfaceChain[p]].conflictingFiles.push(filePathRelativeToCwd);

          var err = new fireUp.errors.InterfaceRegistrationConflictError(currentInterface, registryPointer[interfaceChain[p]].conflictingFiles);
          fireUp.log.error({ err: err }, err.message);
          throw err;

        }

        registryPointer[interfaceChain[p]].file = filePathRelativeToCwd;
        fireUp.log.info({}, 'Registered module at \'%s\' as implementation for interface \'%s\'.', filePathRelativeToCwd, currentInterface);

      }

      registryPointer = registryPointer[interfaceChain[p]].interfaces;

    }

  };

  registry.findInterface = function (interfaceName) {

    var segments = descriptor.parseInterfaceName(interfaceName);
    var registryPointer = registry.interfaces;

    var lastImplementedInterface = "";

    for ( var i = 0; i < segments.length; i+=1 ) {

      if (_.isUndefined(registryPointer[segments[i]])) {
        fireUp.log.warn({}, "No implementation found for the interface '%s'.", interfaceName);
        if (lastImplementedInterface !== "") {
          fireUp.log.debug({}, "FYI there is an implementation for the more general interface '%s'.", lastImplementedInterface);
        }
        return;
      }

      if (i < segments.length-1) {

        if (_.isString(registryPointer[segments[i]].file)) {
          lastImplementedInterface = registryPointer[segments[i]].interfaceName;
        }
        registryPointer = registryPointer[segments[i]].interfaces;

      } else {

        if (_.isString(registryPointer[segments[i]].file)) {
          return registryPointer[segments[i]];
        } else if (_.isArray(registryPointer[segments[i]].conflictingFiles)) {
          fireUp.log.warn({
            interfaceName: registryPointer[segments[i]].interfaceName,
            conflictingFiles: registryPointer[segments[i]].conflictingFiles
          }, "No implementation available for the interface '%s' due to conflicting implementations for the same interface.", interfaceName);
          return;
        }

      }

    }

    // Get a more specific implementation if unambiguous
    var parentSegment;
    var currentSegment = segments[segments.length-1];
    var interfaces;
    while ((interfaces = _.keys(registryPointer[currentSegment].interfaces)).length === 1) {

      registryPointer = registryPointer[currentSegment].interfaces;
      parentSegment = currentSegment;
      currentSegment = interfaces[0];

      if (_.isString(registryPointer[currentSegment].file)) {
        return registryPointer[currentSegment];
      } else if (_.isArray(registryPointer[currentSegment].conflictingFiles)) {
        fireUp.log.warn({
          interfaceName: registryPointer[currentSegment].interfaceName,
          conflictingFiles: registryPointer[currentSegment].conflictingFiles
        }, "No implementation available for the interface '%s' due to conflicting implementations for the same interface.", interfaceName);
        return;
      }

    }

    fireUp.log.warn({}, "No exact or more specific, unambiguous implementation found for the interface '%s'.", interfaceName);
    fireUp.log.debug({
      interfaces: interfaces
    }, 'There are multiple implementations for more specific interfaces. However, the ambiguity prohibits loading a more specific implementation.');
    return;

  };

  return registry;

}

module.exports = {
  newModuleEntry: newModuleEntry,
  newInterfaceEntry: newInterfaceEntry,
  new: newRegistry
};
<commit_msg>Refactoring<commit_after>'use strict';

var _ = require('lodash');
var path = require('path');

var constants = require('../definitions/constants.js');
var descriptor = require('./descriptor.js');

function newModuleEntry() {

  return {
    type: constants.MODULE_TYPE_SINGLETON,
    implements: [],
    inject: [],
    status: constants.FILE_STATUS_UNCHECKED,
    cache: {
      module: null,
      instantiationPromise: null,
      singletonInstance: null
    }
  };

}

function newInterfaceEntry(interfaceName) {

  return {
    interfaceName: interfaceName,
    interfaces: [],
    file: null,
    conflictingFiles: null
  };

}

function newRegistry(fireUp) {

  var registry = {

    basePathForFileRefs: process.cwd(),
    modules: {},
    interfaces: {}

  };

  registry.registerInterface = function (filePathRelativeToCwd, implementedInterface) {

    var interfaceChain = descriptor.parseInterfaceName(implementedInterface);
    var registryPointer = fireUp._internal.registry.interfaces;
    var currentInterface = "";

    for ( var p = 0; p < interfaceChain.length; p+=1 ) {

      if (p > 0) {
        currentInterface += ":";
      }
      currentInterface += interfaceChain[p];

      if (_.isPlainObject(registryPointer[interfaceChain[p]]) === false) {
        registryPointer[interfaceChain[p]] = newInterfaceEntry(currentInterface);
      }

      // Check for conflicts when arriving at last sub interface
      if (p === interfaceChain.length-1) {

        if (_.isNull(registryPointer[interfaceChain[p]].file) === false ||
            _.isNull(registryPointer[interfaceChain[p]].conflictingFiles) === false) {

          if (_.isNull(registryPointer[interfaceChain[p]].conflictingFiles)) {
            registryPointer[interfaceChain[p]].conflictingFiles = [];
          }
          if (_.isNull(registryPointer[interfaceChain[p]].file) === false) {
            registryPointer[interfaceChain[p]].conflictingFiles.push(registryPointer[interfaceChain[p]].file);
            registryPointer[interfaceChain[p]].file = null;
          }
          registryPointer[interfaceChain[p]].conflictingFiles.push(filePathRelativeToCwd);

          var err = new fireUp.errors.InterfaceRegistrationConflictError(currentInterface, registryPointer[interfaceChain[p]].conflictingFiles);
          fireUp.log.error({ err: err }, err.message);
          throw err;

        }

        registryPointer[interfaceChain[p]].file = filePathRelativeToCwd;
        fireUp.log.info({}, 'Registered module at \'%s\' as implementation for interface \'%s\'.', filePathRelativeToCwd, currentInterface);

      }

      registryPointer = registryPointer[interfaceChain[p]].interfaces;

    }

  };

  registry.getInterface = function (interfaceName) {

    var segments = descriptor.parseInterfaceName(interfaceName);
    var registryPointer = registry.interfaces;

    var lastImplementedInterface = "";

    for ( var i = 0; i < segments.length; i+=1 ) {

      if (_.isUndefined(registryPointer[segments[i]])) {
        fireUp.log.warn({}, "No implementation found for the interface '%s'.", interfaceName);
        if (lastImplementedInterface !== "") {
          fireUp.log.debug({}, "FYI there is an implementation for the more general interface '%s'.", lastImplementedInterface);
        }
        return;
      }

      if (i < segments.length-1) {

        if (_.isString(registryPointer[segments[i]].file)) {
          lastImplementedInterface = registryPointer[segments[i]].interfaceName;
        }
        registryPointer = registryPointer[segments[i]].interfaces;

      }

    }

    return registryPointer[_.last(segments)];

  };

  registry.findInterface = function (interfaceName) {

    var registryPointer = this.getInterface(interfaceName);

    if (_.isUndefined(registryPointer)) {
      return;
    } else if (_.isString(registryPointer.file)) {
      return registryPointer;
    } else if (_.isArray(registryPointer.conflictingFiles)) {
      fireUp.log.warn({
        interfaceName: registryPointer.interfaceName,
        conflictingFiles: registryPointer.conflictingFiles
      }, "No implementation available for the interface '%s' due to conflicting implementations for the same interface.", interfaceName);
      return;
    }

    // Get a more specific implementation if unambiguous
    var interfaces;
    while ((interfaces = _.keys(registryPointer.interfaces)).length === 1) {

      registryPointer = registryPointer.interfaces[interfaces[0]];

      if (_.isString(registryPointer.file)) {
        return registryPointer;
      } else if (_.isArray(registryPointer.conflictingFiles)) {
        fireUp.log.warn({
          interfaceName: registryPointer.interfaceName,
          conflictingFiles: registryPointer.conflictingFiles
        }, "No implementation available for the interface '%s' due to conflicting implementations for the same interface.", interfaceName);
        return;
      }

    }

    fireUp.log.warn({}, "No exact or more specific, unambiguous implementation found for the interface '%s'.", interfaceName);
    fireUp.log.debug({
      interfaces: interfaces
    }, 'There are multiple implementations for more specific interfaces. However, the ambiguity prohibits loading a more specific implementation.');
    return;

  };

  return registry;

}

module.exports = {
  newModuleEntry: newModuleEntry,
  newInterfaceEntry: newInterfaceEntry,
  new: newRegistry
};
<|endoftext|>