<commit_before>'use strict';

var _ = require('underscore');

var dialects = {
	base: require('./dialects/base'),
	mssql: require('./dialects/mssql'),
	postgresql: require('./dialects/postgresql'),
	sqlite: require('./dialects/sqlite')
};

var Builder = module.exports = function(params) {
	params = params || {};

	this.setDialect(params.dialect || 'base');

	this.reset();
};

// Builder methods
Builder.prototype.reset = function() {
	this._placeholderId = 0;
	this._query = '';
	this._values = {};
};

Builder.prototype.getPlaceholder = function() {
	return 'p' + (this._placeholderId++);
};

Builder.prototype.wrapPlaceholder = function(name) {
	return this.dialect.config.placeholderPreffix + name +
		this.dialect.config.placeholderSuffix;
};

Builder.prototype.wrapIdentifier = function(name) {
	return this.dialect.config.identifierPreffix + name +
		this.dialect.config.identifierSuffix;
};

Builder.prototype.pushValue = function(value) {
	var valueType = typeof value;

	if (valueType === 'undefined') {
		return 'null';
	} else if (value === null || valueType === 'number' ||
			valueType === 'boolean') {
		return String(value);
	} else if (valueType === 'string') {
		var placeholder = this.getPlaceholder();
		this._values[placeholder] = value;
		return this.wrapPlaceholder(placeholder);
	} else {
		throw new Error('Wrong value type "' + valueType + '".');
	}
};

Builder.prototype.buildBlock = function(block, params) {
	var blockFn = this.dialect.blocks.get(block);

	if (!blockFn) {
		throw new Error('Unknown block "' + block + '".');
	}

	return blockFn(params);
};

Builder.prototype.buildCondition = function(params) {
	var self = this;
	var result = '';

	var condition = params.condition;
	var logicalOperator = params.logicalOperator ||
		this.dialect.config.defaultLogicalOperator;

	if (_.isObject(condition) && !_.isEmpty(condition)) {
		// if condition is array: [{a: 1}, {b: 2}]
		if (_.isArray(condition)) {
			result = _(condition).map(function(item) {
				return self.buildCondition({
					condition: item,
					operator: params.operator
				});
			});

		// if condition is object
		} else {
			result = _(condition).map(function(value, field) {
				// if field name is operator
				if (field[0] === '$') {
					// if field name is logical operator: {$logicalOperator: {a: 1}}
					if (!self.dialect.logicalOperators.has(field)) {
						throw new Error('Unknown logical operator "' + field + '".');
					}

					return self.buildCondition({
						condition: value,
						logicalOperator: field,
						operator: params.operator
					});

				// if condition item is object: {a: {$operator: 4}}
				} else if (_.isObject(value)) {
					var logicalOperatorFn = self.dialect.logicalOperators
						.get(self.dialect.config.defaultLogicalOperator);

					return logicalOperatorFn(_(value).map(function(operatorValue, operator) {
						var operatorFn = self.dialect.conditions.get(operator);
						if (!operatorFn) {
							throw new Error('Unknown operator "' + operator + '".');
						}
						return operatorFn(field, operator, operatorValue);
					}));

				// if condition item type is simple: {a: 1, b: 2}
				} else {
					var operatorFn = self.dialect.conditions.get(params.operator);
					if (!operatorFn) {
						throw new Error('Unknown operator "' + params.operator + '".');
					}
					return operatorFn(field, params.operator, value);
				}
			});
		}

		result = this.dialect.logicalOperators
			.get(logicalOperator)(_(result).compact());
	}

	return result;
};

Builder.prototype.buildTemplate = function(templateName, params) {
	var self = this;

	var template = this.dialect.templates.get(templateName);
	if (!template) {
		throw new Error('Unknown template "' + templateName + '".');
	}

	return _(template).chain().map(function(block) {
		var blockMatch = block.match(/^\{(\w+)\}$/i);

		if (blockMatch) {
			// if template block match block pattern - process it
			block = blockMatch[1];

			if (typeof params[block] !== 'undefined') {
				return self.buildBlock(block, params);
			}

			// if no data in params for block - return null
			return null;
		} else {
			// if template block is simple string - return it
			return block;
		}
	}).compact().value().join(' ');
};

Builder.prototype.build = function(params) {
	params = this.dialect.prepare(params);

	this.reset();

	this._query = this.buildTemplate(params.type, params) + ';';

	return {
		query: this._query,
		values: this._values
	};
};

Builder.prototype.getQuery = function() {
	return this._query;
};

Builder.prototype.getValues = function() {
	return this._values;
};

Builder.prototype.getWrappedValues = function() {
	var self = this;
	var values = {};
	_(this._values).each(function(value, name) {
		values[self.wrapPlaceholder(name)] = value;
	});
	return values;
};

Builder.prototype.setDialect = function(name) {
	if (!dialects[name]) {
		throw new Error('Unknown dialect "' + name + '".');
	}

	this.dialect = new (dialects[name])(this);
};
<commit_msg>move builder get methods to result object<commit_after>'use strict';

var _ = require('underscore');

var dialects = {
	base: require('./dialects/base'),
	mssql: require('./dialects/mssql'),
	postgresql: require('./dialects/postgresql'),
	sqlite: require('./dialects/sqlite')
};

var Builder = module.exports = function(params) {
	params = params || {};

	this.setDialect(params.dialect || 'base');

	this.reset();
};

// Builder methods
Builder.prototype.reset = function() {
	this._placeholderId = 0;
	this._query = '';
	this._values = {};
};

Builder.prototype.getPlaceholder = function() {
	return 'p' + (this._placeholderId++);
};

Builder.prototype.wrapPlaceholder = function(name) {
	return this.dialect.config.placeholderPreffix + name +
		this.dialect.config.placeholderSuffix;
};

Builder.prototype.wrapIdentifier = function(name) {
	return this.dialect.config.identifierPreffix + name +
		this.dialect.config.identifierSuffix;
};

Builder.prototype.pushValue = function(value) {
	var valueType = typeof value;

	if (valueType === 'undefined') {
		return 'null';
	} else if (value === null || valueType === 'number' ||
			valueType === 'boolean') {
		return String(value);
	} else if (valueType === 'string') {
		var placeholder = this.getPlaceholder();
		this._values[placeholder] = value;
		return this.wrapPlaceholder(placeholder);
	} else {
		throw new Error('Wrong value type "' + valueType + '".');
	}
};

Builder.prototype.buildBlock = function(block, params) {
	var blockFn = this.dialect.blocks.get(block);

	if (!blockFn) {
		throw new Error('Unknown block "' + block + '".');
	}

	return blockFn(params);
};

Builder.prototype.buildCondition = function(params) {
	var self = this;
	var result = '';

	var condition = params.condition;
	var logicalOperator = params.logicalOperator ||
		this.dialect.config.defaultLogicalOperator;

	if (_.isObject(condition) && !_.isEmpty(condition)) {
		// if condition is array: [{a: 1}, {b: 2}]
		if (_.isArray(condition)) {
			result = _(condition).map(function(item) {
				return self.buildCondition({
					condition: item,
					operator: params.operator
				});
			});

		// if condition is object
		} else {
			result = _(condition).map(function(value, field) {
				// if field name is operator
				if (field[0] === '$') {
					// if field name is logical operator: {$logicalOperator: {a: 1}}
					if (!self.dialect.logicalOperators.has(field)) {
						throw new Error('Unknown logical operator "' + field + '".');
					}

					return self.buildCondition({
						condition: value,
						logicalOperator: field,
						operator: params.operator
					});

				// if condition item is object: {a: {$operator: 4}}
				} else if (_.isObject(value)) {
					var logicalOperatorFn = self.dialect.logicalOperators
						.get(self.dialect.config.defaultLogicalOperator);

					return logicalOperatorFn(_(value).map(function(operatorValue, operator) {
						var operatorFn = self.dialect.conditions.get(operator);
						if (!operatorFn) {
							throw new Error('Unknown operator "' + operator + '".');
						}
						return operatorFn(field, operator, operatorValue);
					}));

				// if condition item type is simple: {a: 1, b: 2}
				} else {
					var operatorFn = self.dialect.conditions.get(params.operator);
					if (!operatorFn) {
						throw new Error('Unknown operator "' + params.operator + '".');
					}
					return operatorFn(field, params.operator, value);
				}
			});
		}

		result = this.dialect.logicalOperators
			.get(logicalOperator)(_(result).compact());
	}

	return result;
};

Builder.prototype.buildTemplate = function(templateName, params) {
	var self = this;

	var template = this.dialect.templates.get(templateName);
	if (!template) {
		throw new Error('Unknown template "' + templateName + '".');
	}

	return _(template).chain().map(function(block) {
		var blockMatch = block.match(/^\{(\w+)\}$/i);

		if (blockMatch) {
			// if template block match block pattern - process it
			block = blockMatch[1];

			if (typeof params[block] !== 'undefined') {
				return self.buildBlock(block, params);
			}

			// if no data in params for block - return null
			return null;
		} else {
			// if template block is simple string - return it
			return block;
		}
	}).compact().value().join(' ');
};

Builder.prototype.build = function(params) {
	var builder = this;

	params = this.dialect.prepare(params);

	this.reset();

	this._query = this.buildTemplate(params.type, params) + ';';

	return {
		query: this._query,
		values: this._values,
		getWrappedValues: function() {
			var values = {};
			_(this.values).each(function(value, name) {
				values[builder.wrapPlaceholder(name)] = value;
			});
			return values;
		},
		toArray: function() {
			return _(this.values).values();
		}
	};
};

Builder.prototype.setDialect = function(name) {
	if (!dialects[name]) {
		throw new Error('Unknown dialect "' + name + '".');
	}

	this.dialect = new (dialects[name])(this);
};
<|endoftext|>


<commit_before>const fs = require('fs-promise');
const log4js = require('log4js');
const path = require('path');
const spawn = require('./spawn');

module.exports = {
    build: (push) => {
        const gitUrl = push.repository.git_url;
        const name = push.repository.full_name;
        const userDir = path.join('/tmp/nekobuilder', name.split('/')[0]);
        const workDir = path.join('/tmp/nekobuilder', name);
        const gitDir = path.join(workDir, '.git');
        const type = push.ref.split('/')[1];
        const tag = push.ref.split('/')[2];
        const build = log4js.getLogger('[BUILD]');

        fs.exists('/tmp/nekobuilder')
            .then((exists) => exists || fs.mkdir('/tmp/nekobuilder'))
            .then(() => fs.exists(userDir))
            .then((exists) => exists || fs.mkdir(userDir))
            .then(() => fs.exists(gitDir))
            .then((exists) => exists || spawn('git', ['clone', gitUrl, workDir]))
            .then(() => spawn('git', ['fetch'], {cwd: workDir}))
            .then(() => spawn('git', ['checkout', '--force', tag], {cwd: workDir}))
            .then(() => type === 'heads' && spawn('git', ['pull', '--rebase'], {cwd: workDir}))
            .then(() => spawn('git', ['submodule', 'update', '--init', '--recursive', '--force'], {cwd: workDir}))
            .then(() => spawn('docker', ['build', `--tag=${name}:${tag}`, workDir]))
            .then(() => tag === 'master' && spawn('docker', ['tag', '-f', `${name}:${tag}`, `${name}:latest`]))
            .then(() => build.info('OK'))
            .catch((error) => build.error(error))
            ;
    },
};<commit_msg>Serialize build tasks<commit_after>const fs = require('fs-promise');
const log4js = require('log4js');
const path = require('path');
const spawn = require('./spawn');

const tasks = [];
let working = false;
const runBuilder = () => {
    if (!working) {
        working = true;

        while (tasks.length > 0) {
            const push = tasks.pop();

            const gitUrl = push.repository.git_url;
            const name = push.repository.full_name;
            const userDir = path.join('/tmp/nekobuilder', name.split('/')[0]);
            const workDir = path.join('/tmp/nekobuilder', name);
            const gitDir = path.join(workDir, '.git');
            const type = push.ref.split('/')[1];
            const tag = push.ref.split('/')[2];
            const build = log4js.getLogger('[BUILD]');

            fs.exists('/tmp/nekobuilder')
                .then((exists) => exists || fs.mkdir('/tmp/nekobuilder'))
                .then(() => fs.exists(userDir))
                .then((exists) => exists || fs.mkdir(userDir))
                .then(() => fs.exists(gitDir))
                .then((exists) => exists || spawn('git', ['clone', gitUrl, workDir]))
                .then(() => spawn('git', ['fetch'], {cwd: workDir}))
                .then(() => spawn('git', ['checkout', '--force', tag], {cwd: workDir}))
                .then(() => type === 'heads' && spawn('git', ['pull', '--rebase'], {cwd: workDir}))
                .then(() => spawn('git', ['submodule', 'update', '--init', '--recursive', '--force'], {cwd: workDir}))
                .then(() => spawn('docker', ['build', `--tag=${name}:${tag}`, workDir]))
                .then(() => tag === 'master' && spawn('docker', ['tag', '-f', `${name}:${tag}`, `${name}:latest`]))
                .then(() => build.info('OK'))
                .catch((error) => build.error(error))
                ;
        }

        working = false;
    }
};

module.exports = {
    build: (push) => {
        tasks.push(push);
        setTimeout(runBuilder);
    },
};<|endoftext|>


<commit_before>var fs = require('fs')
var path = require('path')
var domain = require('domain')
var mktemp = require('mktemp')
var mkdirp = require('mkdirp')
var rimraf = require('rimraf')
var synchronized = require('synchronized')

exports.Builder = Builder
function Builder (options) {
  var self = this

  this.reader = options.reader
  this.transformer = options.transformer

  var tmpBaseDir = options.tmpDir || '.'
  mkdirp.sync(tmpBaseDir)
  this.tmpDir = mktemp.createDirSync(path.join(tmpBaseDir, 'broccoli-XXXXXX.tmp'))
  process.on('exit', function () {
    self.cleanupTmpDir()
  })

  this.cacheDir = path.join(this.tmpDir, 'cache.tmp')
  fs.mkdirSync(this.cacheDir)

  this.buildScheduled = false
}

// outputDir is optional
Builder.prototype.build = function (outputDir, callback) {
  var self = this

  if (this.buildScheduled) return
  this.buildScheduled = true

  synchronized(this, function (done) {
    self.buildScheduled = false

    var startTime = Date.now()

    self.buildError = null

    self.cleanupBuildProducts() // remove last build's directories
    if (outputDir == null) {
      self.outputTmpDir = mktemp.createDirSync(path.join(self.tmpDir, 'output-XXXXXX.tmp'))
      outputDir = self.outputTmpDir
    }
    self.buildTmpDir = mktemp.createDirSync(path.join(self.tmpDir, 'build-XXXXXX.tmp'))

    var readerDest = mktemp.createDirSync(path.join(self.buildTmpDir, 'reader-XXXXXX.tmp'))
    var d = domain.create()
    d.on('error', function (err) {
      // The domain documentation says that continuing to run is bad practice
      // and that we leak resources. On the other hand, we generally don't
      // want our server to go down, ever. We should investigate.
      finish(err)
    })
    d.run(function () {
      // Without setImmediate, while a synchronous exception inside this
      // function would still be caught, any code after builder.build() would
      // not run.
      setImmediate(function () {
        self.reader._setup({
          tmpDir: self.buildTmpDir,
          cacheDir: self.cacheDir
        })
        self.reader.read(readerDest, function (err) {
          if (err) {
            finish(err)
            return
          }
          self.transformer._setup({
            tmpDir: self.buildTmpDir,
            cacheDir: self.cacheDir
          })
          self.transformer.transform(readerDest, outputDir, function (err) {
            finish(err)
          })
        })
      })
    })

    function finish (err) {
      if (err) self.buildError = err
      console.log('Built ' + (err ? 'with error ' : '') + '(' + (Date.now() - startTime) + ' ms)')
      done()
      if (callback != null) callback()
    }
  })
}

Builder.prototype.cleanupTmpDir = function (exitCode) {
  if (this.tmpDir != null) {
    rimraf.sync(this.tmpDir)
  }
}

Builder.prototype.cleanupBuildProducts = function () {
  var fields = ['buildTmpDir', 'outputTmpDir']
  for (var i = 0; i < fields.length; i++) {
    if (this[fields[i]] != null) {
      rimraf.sync(this[fields[i]])
      this[fields[i]] = null
    }
  }
}
<commit_msg>Use chained methods for Builder as well<commit_after>var fs = require('fs')
var path = require('path')
var domain = require('domain')
var mktemp = require('mktemp')
var mkdirp = require('mkdirp')
var rimraf = require('rimraf')
var synchronized = require('synchronized')

exports.Builder = Builder
function Builder (options) {
  var self = this

  var tmpBaseDir = options.tmpDir || '.'
  mkdirp.sync(tmpBaseDir)
  this.tmpDir = mktemp.createDirSync(path.join(tmpBaseDir, 'broccoli-XXXXXX.tmp'))
  process.on('exit', function () {
    self.cleanupTmpDir()
  })

  this.cacheDir = path.join(this.tmpDir, 'cache.tmp')
  fs.mkdirSync(this.cacheDir)

  this.buildScheduled = false
}

Builder.prototype.setReader = function (reader) {
  this.reader = reader
  return this
}

Builder.prototype.addTransformer = function (transformer) {
  if (this.transformer != null) throw new Error('multiple transformers not yet supported')
  this.transformer = transformer
  return this
}

// outputDir is optional
Builder.prototype.build = function (outputDir, callback) {
  var self = this

  if (this.buildScheduled) return
  this.buildScheduled = true

  synchronized(this, function (done) {
    self.buildScheduled = false

    var startTime = Date.now()

    self.buildError = null

    self.cleanupBuildProducts() // remove last build's directories
    if (outputDir == null) {
      self.outputTmpDir = mktemp.createDirSync(path.join(self.tmpDir, 'output-XXXXXX.tmp'))
      outputDir = self.outputTmpDir
    }
    self.buildTmpDir = mktemp.createDirSync(path.join(self.tmpDir, 'build-XXXXXX.tmp'))

    var readerDest = mktemp.createDirSync(path.join(self.buildTmpDir, 'reader-XXXXXX.tmp'))
    var d = domain.create()
    d.on('error', function (err) {
      // The domain documentation says that continuing to run is bad practice
      // and that we leak resources. On the other hand, we generally don't
      // want our server to go down, ever. We should investigate.
      finish(err)
    })
    d.run(function () {
      // Without setImmediate, while a synchronous exception inside this
      // function would still be caught, any code after builder.build() would
      // not run.
      setImmediate(function () {
        self.reader._setup({
          tmpDir: self.buildTmpDir,
          cacheDir: self.cacheDir
        })
        self.reader.read(readerDest, function (err) {
          if (err) {
            finish(err)
            return
          }
          self.transformer._setup({
            tmpDir: self.buildTmpDir,
            cacheDir: self.cacheDir
          })
          self.transformer.transform(readerDest, outputDir, function (err) {
            finish(err)
          })
        })
      })
    })

    function finish (err) {
      if (err) self.buildError = err
      console.log('Built ' + (err ? 'with error ' : '') + '(' + (Date.now() - startTime) + ' ms)')
      done()
      if (callback != null) callback()
    }
  })
}

Builder.prototype.cleanupTmpDir = function (exitCode) {
  if (this.tmpDir != null) {
    rimraf.sync(this.tmpDir)
  }
}

Builder.prototype.cleanupBuildProducts = function () {
  var fields = ['buildTmpDir', 'outputTmpDir']
  for (var i = 0; i < fields.length; i++) {
    if (this[fields[i]] != null) {
      rimraf.sync(this[fields[i]])
      this[fields[i]] = null
    }
  }
}
<|endoftext|>


<commit_before>var extend = require( 'extend' );
var dispatchy = require( 'dispatchy' );
var flatCache = require( 'flat-cache' );
var fileEntryCache = require( 'file-entry-cache' );
var expand = require( 'glob-expand' );

module.exports = {
  create: function ( id ) {

    return extend( dispatchy.create(), {
      id: id,
      bundle: function ( target, options ) {
        var me = this;
        var opts = {
          useCache: true,
          transforms: {
            babelify: {
              global: false,
              disabled: false
            },
            shimixify: {
              global: false,
              disabled: false,
              config: {
                addDefaultShims: true,
                shims: {}
              }
            }
          }
        };

        opts = extend( true, opts, options );

        var transforms = opts.transforms || { };
        var consoleFilter = transforms.consoleFilter || { };

        if ( consoleFilter ) {
          var cOptions = consoleFilter.config || { };
          consoleFilter.disabled = !cOptions.keep;
        }

        var shimixify = transforms.shimixify || { };
        var shimixifyConfig = shimixify.config || { };

        if ( shimixifyConfig && shimixifyConfig.addDefaultShims ) {
          shimixify.config = extend( true, {
            shims: {
              window: 'global.window',
              screen: 'global.screen',
              document: 'global.document',
              Worker: 'global.Worker',
              Promise: 'global.Promise'
            }
          }, shimixifyConfig );
        }

        var cache;
        var depsCacheFile;

        var useCache = opts.useCache || opts.watch;

        if ( useCache ) {

          cache = flatCache.load( id );
          //console.log('cache', cache);
          depsCacheFile = fileEntryCache.create( 'deps-cx-' + id );
        } else {
          flatCache.clearCacheById( id );
        }

        var watchify = require( 'watchify' );
        var browserify = require( 'browserify' );

        var done = function ( receivedTarget, time, text ) {

          me.fire( 'bundler:done', {
            result: text,
            target: receivedTarget,
            startTime: time
          } );

          return text;
        };

        var configTransform = function ( b, transform, trConfig ) {
          trConfig = trConfig || { };
          if ( trConfig.disabled ) {
            return;
          }

          if ( trConfig.config ) {
            transform = transform.configure( trConfig.config );
          }

          b.transform( { global: trConfig.global }, transform );

        };

        var commonTransforms = function ( b ) {
          configTransform( b, require( './simplessy' ), transforms.lessify );
          configTransform( b, require( './dotify' ), transforms.dotify );

          configTransform( b, require( './babelify' ), transforms.babelify );
          configTransform( b, require( 'shimixify' ), shimixify );

          configTransform( b, require( 'console-filter' ), consoleFilter );
          configTransform( b, require( 'require-arr' ), transforms.requireArr );
        };

        function bundle() {
          var wArgs = {
            cache: {},
            packageCache: {}
          };

          if ( useCache ) {
            wArgs = cache.getKey( 'watchifyArgs' ) || wArgs;

            if ( !wArgs ) {

              wArgs = {
                cache: {},
                packageCache: {}
              };

              cache.setKey( 'watchifyArgs', wArgs );
            }

            var changedFiles = depsCacheFile.getUpdatedFiles( expand.apply( null, Object.keys( wArgs.cache ) ) );
            if ( changedFiles.length > 0 ) {
              me.fire( 'bundler:files:updated', { files: changedFiles } );
            }
            changedFiles.forEach( function ( file ) {
              delete wArgs.cache[ file ];
            } );
          }

          var watchifyArgs = wArgs;

          var b = browserify( watchifyArgs );

          if ( target.src ) {
            b.add( target.src );
          }

          commonTransforms( b );

          opts.preBundleCB && opts.preBundleCB( b );

          var w = (opts.watch || opts.useCache) ? watchify( b ) : b;

          var doBundle = function ( _changedFiles ) {
            _changedFiles = _changedFiles || [ ];
            if ( _changedFiles.length > 0 ) {
              me.fire( 'bundler:files:updated', { files: _changedFiles } );
            }

            var time = Date.now();

            w.bundle( function ( err, buff ) {

              if ( err ) {
                me.fire( 'error', err );
                return;
              }

              opts.postBundle && opts.postBundle();

              if ( useCache ) {
                setTimeout( function () {
                  cache.setKey( 'watchifyArgs', watchifyArgs );
                  cache.save();
                  depsCacheFile.getUpdatedFiles( expand.apply( null, Object.keys( watchifyArgs.cache ) ) );
                  depsCacheFile.reconcile();
                }, 0 );
              }

              var outp = buff.toString();
              done( target, time, outp );

            } );
          };

          opts.watch && w.on( 'update', doBundle );

          doBundle();

        }

        bundle();
      }
    } );
  }
};
<commit_msg>FIX: wrong trasnform name for simplessy<commit_after>var extend = require( 'extend' );
var dispatchy = require( 'dispatchy' );
var flatCache = require( 'flat-cache' );
var fileEntryCache = require( 'file-entry-cache' );
var expand = require( 'glob-expand' );

module.exports = {
  create: function ( id ) {

    return extend( dispatchy.create(), {
      id: id,
      bundle: function ( target, options ) {
        var me = this;
        var opts = {
          useCache: true,
          transforms: {
            babelify: {
              global: false,
              disabled: false
            },
            shimixify: {
              global: false,
              disabled: false,
              config: {
                addDefaultShims: true,
                shims: {}
              }
            }
          }
        };

        opts = extend( true, opts, options );

        var transforms = opts.transforms || { };
        var consoleFilter = transforms.consoleFilter || { };

        if ( consoleFilter ) {
          var cOptions = consoleFilter.config || { };
          consoleFilter.disabled = !cOptions.keep;
        }

        var shimixify = transforms.shimixify || { };
        var shimixifyConfig = shimixify.config || { };

        if ( shimixifyConfig && shimixifyConfig.addDefaultShims ) {
          shimixify.config = extend( true, {
            shims: {
              window: 'global.window',
              screen: 'global.screen',
              document: 'global.document',
              Worker: 'global.Worker',
              Promise: 'global.Promise'
            }
          }, shimixifyConfig );
        }

        var cache;
        var depsCacheFile;

        var useCache = opts.useCache || opts.watch;

        if ( useCache ) {

          cache = flatCache.load( id );
          //console.log('cache', cache);
          depsCacheFile = fileEntryCache.create( 'deps-cx-' + id );
        } else {
          flatCache.clearCacheById( id );
        }

        var watchify = require( 'watchify' );
        var browserify = require( 'browserify' );

        var done = function ( receivedTarget, time, text ) {

          me.fire( 'bundler:done', {
            result: text,
            target: receivedTarget,
            startTime: time
          } );

          return text;
        };

        var configTransform = function ( b, transform, trConfig ) {
          trConfig = trConfig || { };
          if ( trConfig.disabled ) {
            return;
          }

          if ( trConfig.config ) {
            transform = transform.configure( trConfig.config );
          }

          b.transform( { global: trConfig.global }, transform );

        };

        var commonTransforms = function ( b ) {
          configTransform( b, require( './simplessy' ), transforms.simplessy );
          configTransform( b, require( './dotify' ), transforms.dotify );

          configTransform( b, require( './babelify' ), transforms.babelify );
          configTransform( b, require( 'shimixify' ), shimixify );

          configTransform( b, require( 'console-filter' ), consoleFilter );
          configTransform( b, require( 'require-arr' ), transforms.requireArr );
        };

        function bundle() {
          var wArgs = {
            cache: {},
            packageCache: {}
          };

          if ( useCache ) {
            wArgs = cache.getKey( 'watchifyArgs' ) || wArgs;

            if ( !wArgs ) {

              wArgs = {
                cache: {},
                packageCache: {}
              };

              cache.setKey( 'watchifyArgs', wArgs );
            }

            var changedFiles = depsCacheFile.getUpdatedFiles( expand.apply( null, Object.keys( wArgs.cache ) ) );
            if ( changedFiles.length > 0 ) {
              me.fire( 'bundler:files:updated', { files: changedFiles } );
            }
            changedFiles.forEach( function ( file ) {
              delete wArgs.cache[ file ];
            } );
          }

          var watchifyArgs = wArgs;

          var b = browserify( watchifyArgs );

          if ( target.src ) {
            b.add( target.src );
          }

          commonTransforms( b );

          opts.preBundleCB && opts.preBundleCB( b );

          var w = (opts.watch || opts.useCache) ? watchify( b ) : b;

          var doBundle = function ( _changedFiles ) {
            _changedFiles = _changedFiles || [ ];
            if ( _changedFiles.length > 0 ) {
              me.fire( 'bundler:files:updated', { files: _changedFiles } );
            }

            var time = Date.now();

            w.bundle( function ( err, buff ) {

              if ( err ) {
                me.fire( 'error', err );
                return;
              }

              opts.postBundle && opts.postBundle();

              if ( useCache ) {
                setTimeout( function () {
                  cache.setKey( 'watchifyArgs', watchifyArgs );
                  cache.save();
                  depsCacheFile.getUpdatedFiles( expand.apply( null, Object.keys( watchifyArgs.cache ) ) );
                  depsCacheFile.reconcile();
                }, 0 );
              }

              var outp = buff.toString();
              done( target, time, outp );

            } );
          };

          opts.watch && w.on( 'update', doBundle );

          doBundle();

        }

        bundle();
      }
    } );
  }
};
<|endoftext|>


<commit_before>var EventEmitter = require('events').EventEmitter;
var jsonRpc = require('json-rpc');
var array = require('./array');
var HEARTBEAT_INTERVAL_DELAY = 3 * 1000;

module.exports = function(socket, rooms) {
  var emitter = new EventEmitter();
  var rpc = jsonRpc();
  var joinedRooms = [];
  var heartbeatCount = 0;
  var heartbeatInterval = null;

  var errorListener = function(err) {
    emitter.emit('error', err);
  };

  var closeListener = function(code, message) {
    stopHealthCheck();
    socket.removeAllListeners();
    emitter.emit('close', code, message);
  };

  var pongListener = function(data, flags) {
    resetHealthCheck();
  };

  var outboundMessageHandler = function(json) {
    if (socket.readyState !== socket.OPEN) {
      throw new Error('Socket not ready to send');
    }

    socket.send(json);
    resetHealthCheck();
  };

  var startHealthCheck = function() {
    heartbeatCount = 0;

    heartbeatInterval = setInterval(function() {
      if (heartbeatCount > 4) {
        socket.close();
        return;
      }

      heartbeatCount += 1;
      socket.ping();
    }, HEARTBEAT_INTERVAL_DELAY);
  };

  var stopHealthCheck = function() {
    clearInterval(heartbeatInterval);
    heartbeatInterval = null;
  };

  var resetHealthCheck = function() {
    if(!heartbeatInterval) {
      return;
    }

    stopHealthCheck();
    startHealthCheck();
  };

  var inRoom = function(roomId) {
    return array.contains(joinedRooms, roomId);
  };

  rpc.on('message', outboundMessageHandler);
  socket.on('message', rpc.inboundMessageHandler);
  socket.on('error', errorListener);
  socket.on('close', closeListener);
  socket.on('pong', pongListener);

  return {
    on: function(event, var_args) {
      // Special events
      if (array.contains(['message', 'error', 'close', 'pong'], event)) {
        emitter.on.apply(emitter, arguments);
        return;
      }

      rpc.on.apply(rpc, arguments);
    },

    to: function(roomId) {

    },

    join: function(roomId) {
      if (inRoom(roomId)) {
        return;
      }

      joinedRooms.push(roomId);
      rooms.add(roomId, this);
    },

    leave: function(roomId) {
      if (inRoom(roomId)) {
        return;
      }

      array.remove(joinedRooms, roomId);
      rooms.remove(roomId, this);
    },

    leaveAll: function() {
      joinedRooms.forEach(function(roomId) {
        this.leave(roomId);
      }.bind(this));
    },

    close: socket.close.bind(socket)
  };
};<commit_msg>Expose inRoom function.<commit_after>var EventEmitter = require('events').EventEmitter;
var jsonRpc = require('json-rpc');
var array = require('./array');
var HEARTBEAT_INTERVAL_DELAY = 3 * 1000;

module.exports = function(socket, rooms) {
  var emitter = new EventEmitter();
  var rpc = jsonRpc();
  var joinedRooms = [];
  var heartbeatCount = 0;
  var heartbeatInterval = null;

  var errorListener = function(err) {
    emitter.emit('error', err);
  };

  var closeListener = function(code, message) {
    stopHealthCheck();
    socket.removeAllListeners();
    emitter.emit('close', code, message);
  };

  var pongListener = function(data, flags) {
    resetHealthCheck();
  };

  var outboundMessageHandler = function(json) {
    if (socket.readyState !== socket.OPEN) {
      throw new Error('Socket not ready to send');
    }

    socket.send(json);
    resetHealthCheck();
  };

  var startHealthCheck = function() {
    heartbeatCount = 0;

    heartbeatInterval = setInterval(function() {
      if (heartbeatCount > 4) {
        socket.close();
        return;
      }

      heartbeatCount += 1;
      socket.ping();
    }, HEARTBEAT_INTERVAL_DELAY);
  };

  var stopHealthCheck = function() {
    clearInterval(heartbeatInterval);
    heartbeatInterval = null;
  };

  var resetHealthCheck = function() {
    if(!heartbeatInterval) {
      return;
    }

    stopHealthCheck();
    startHealthCheck();
  };

  var inRoom = function(roomId) {
    return array.contains(joinedRooms, roomId);
  };

  rpc.on('message', outboundMessageHandler);
  socket.on('message', rpc.inboundMessageHandler);
  socket.on('error', errorListener);
  socket.on('close', closeListener);
  socket.on('pong', pongListener);

  return {
    on: function(event, var_args) {
      // Special events
      if (array.contains(['message', 'error', 'close', 'pong'], event)) {
        emitter.on.apply(emitter, arguments);
        return;
      }

      rpc.on.apply(rpc, arguments);
    },

    to: function(roomId) {

    },

    join: function(roomId) {
      if (inRoom(roomId)) {
        return;
      }

      joinedRooms.push(roomId);
      rooms.add(roomId, this);
    },

    leave: function(roomId) {
      if (inRoom(roomId)) {
        return;
      }

      array.remove(joinedRooms, roomId);
      rooms.remove(roomId, this);
    },

    leaveAll: function() {
      joinedRooms.forEach(function(roomId) {
        this.leave(roomId);
      }.bind(this));
    },

    close: socket.close.bind(socket),

    inRoom: inRoom
  };
};<|endoftext|>


<commit_before>function getDistanceBetweenPoints(latitudeA, longitudeA, latitudeB, longitudeB) {
	// generally used geo measurement function
    var R = 6378.137; // Radius of earth in KM
    var dLat = (latitudeB - latitudeA) * Math.PI / 180;
    var dLon = (longitudeB - longitudeA) * Math.PI / 180;
    var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(latitudeA * Math.PI / 180) * Math.cos(latitudeB * Math.PI / 180) * Math.sin(dLon/2) * Math.sin(dLon/2);
    var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
    var d = R * c;

    return d * 1000; // meters
}

function formatGeoJson() {
	return {
		"type": "FeatureCollection",
		"features": Array.prototype.slice.call(arguments)
	}
}

function formatOneFeature(result) {
	return {
		"type": "Feature",
		"geometry": {
			"type": "Point",
			"coordinates": [result.longitude, result.latitude]
		},
		"properties": {
			"name": result.zhName,
			"summary": result.summmary
		}
	};
}

var results = [];

module.exports = function(latitude, longitude) {
	return new Promise(function(resolve) {
		if(!results.length) {
			var model = new AV.Query('Place');
			model.addAscending('order');
			model.find({
				success : function(records) {
					results = records;
					resolve();
				}
			});
		} else {
			resolve();
		}
	}).then(function() {
		var formatter = formatGeoJson;
		for(var i = 0, currentResult; i < results.length; i += 1) {
			currentResult = results[i]._serverData;
			if(Math.abs(getDistanceBetweenPoints(latitude, longitude, currentResult.latitude, currentResult.longitude)) < 1000) {
				formatter = formatGeoJson.bind(null, currentResult);
			}
		}

		return formatter();
	});
};<commit_msg>default values for closeTo<commit_after>function getDistanceBetweenPoints(latitudeA, longitudeA, latitudeB, longitudeB) {
	// generally used geo measurement function
    var R = 6378.137; // Radius of earth in KM
    var dLat = (latitudeB - latitudeA) * Math.PI / 180;
    var dLon = (longitudeB - longitudeA) * Math.PI / 180;
    var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(latitudeA * Math.PI / 180) * Math.cos(latitudeB * Math.PI / 180) * Math.sin(dLon/2) * Math.sin(dLon/2);
    var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
    var d = R * c;

    return d * 1000; // meters
}

function formatGeoJson() {
	return arguments.length ? {
		"type": "FeatureCollection",
		"features": Array.prototype.slice.call(arguments)
	} : false;
}

function formatOneFeature(result) {
	return {
		"type": "Feature",
		"geometry": {
			"type": "Point",
			"coordinates": [result.longitude, result.latitude]
		},
		"properties": {
			"name": result.zhName,
			"summary": result.summmary
		}
	};
}

var results = [];

module.exports = function(latitude, longitude) {
	return new Promise(function(resolve) {
		if(!results.length) {
			var model = new AV.Query('Place');
			model.addAscending('order');
			model.find({
				success : function(records) {
					results = records;
					resolve();
				}
			});
		} else {
			resolve();
		}
	}).then(function() {
		var formatter = formatGeoJson;
		for(var i = 0, currentResult; i < results.length; i += 1) {
			currentResult = results[i]._serverData;
			if(Math.abs(getDistanceBetweenPoints(latitude, longitude, currentResult.latitude, currentResult.longitude)) < 1000) {
				formatter = formatGeoJson.bind(null, currentResult);
			}
		}

		return formatter();
	});
};<|endoftext|>


<commit_before>"use strict";
var cluster = require('cluster');
var os = require('os');
var TimedChecker = require('./tools/timed_checker');

var Cluster = function (opt_app) {
	this.app = opt_app;
	this.settings = null;

	this.isDisabled = null;
	this.numberOfWorkers = null;
	this.logger = null;

	this.workersInfo = {};

	this.lazyChecker = null;
	this.zombieChecker = null;
};

Cluster.prototype.unitIsInitRequired = true;

Cluster.prototype.unitInit = function (units) {
	if (this.app == null) {
		this.app = units.require('core.app');
	}

	this.settings = units.require('core.settings').core.cluster;
	this.logger = units.require('core.logging').getLogger('cluster');

	this.isDisabled = this.settings.disable;
	this.numberOfWorkers = (this.settings.numberOfWorkers != null ? this.settings.numberOfWorkers : os.cpus().length);
};

Cluster.prototype.createLazyChecker = function () {
	var self = this;
	return new TimedChecker(function () {
		self.checkLazy(this.items);
	}, this.settings.checks.lazy.interval);
};

Cluster.prototype.createZombieChecker = function () {
	var self = this;
	return new TimedChecker(function () {
		self.checkZombie(this.items);
	}, this.settings.checks.zombie.interval);
};

Cluster.prototype.start = function () {
	if (cluster.isMaster) {
		this.startMaster();
	}
	else {
		this.app.startWorker();
	}
};

Cluster.prototype.startMaster = function () {
	this.setupMaster();
	this.createCheckers();
	this.initListeners();
	this.forkWorkers();
};

Cluster.prototype.setupMaster = function () {
	var settings = null;
	for (var k in this.settings.master) {
		var v = this.settings.master[k];
		if (v != null) {
			settings = settings || {};
			settings[k] = v;
		}
	}
	cluster.setupMaster(settings);
};

Cluster.prototype.createCheckers = function () {
	this.lazyChecker = this.createLazyChecker();
	this.zombieChecker = this.createZombieChecker();
};

Cluster.prototype.initListeners = function () {
	var self = this;
	cluster.on('fork', function(worker) {
		self.onWorkerFork(worker);
	});
	cluster.on('online', function(worker) {
		self.onWorkerOnline(worker);
	});
	cluster.on('listening', function(worker, address) {
		self.onWorkerListening(worker, address);
	});
	cluster.on('disconnect', function(worker) {
		self.onWorkerDisconnect(worker);
	});
	cluster.on('exit', function(worker, code, signal) {
		self.onWorkerExit(worker, code, signal);
	});
};

Cluster.prototype.forkWorkers = function () {
	for (var i = 0; i < this.numberOfWorkers; i++) {
		cluster.fork();
	}
	this.logger.info([this.numberOfWorkers, ' workers forked'].join(''));
};

Cluster.prototype.handleWorkerStateChange = function (worker, state, opt_data, opt_msg, opt_logLevel) {
	this.updateWorkerInfo(worker, state, opt_data);
	this.reportWorkerStateChange(worker, state, opt_data, opt_msg, opt_logLevel);
};

Cluster.prototype.updateWorkerInfo = function (worker, state, opt_data) {
	var info;
	if (state == 'fork') {
		this.workersInfo[worker.id] = info = {
			stateHistory: {}
		};
	}
	else {
		info = this.workersInfo[worker.id];
	}

	info.state = state;
	var historyItem = {
		date: new Date()
	};
	if (opt_data != null) {
		historyItem.data = opt_data;
	}
	info.stateHistory[state] = historyItem;
};

Cluster.prototype.reportWorkerStateChange = function (worker, state, opt_data, opt_msg, opt_logLevel) {
	var logLevel = opt_logLevel || 'debug';
	var parts = ['Worker ', worker.id, ' ', state];
	if (opt_msg) {
		parts.push(', ', opt_msg);
	}
	this.logger.log(logLevel, parts.join(''));
};

Cluster.prototype.onWorkerFork = function (worker) {
	this.lazyChecker.add(worker.id);
	this.handleWorkerStateChange(worker, 'fork');
};

Cluster.prototype.onWorkerOnline = function (worker) {
	this.handleWorkerStateChange(worker, 'online');
};

Cluster.prototype.onWorkerListening = function (worker, address) {
	this.lazyChecker.remove(worker.id);
	this.handleWorkerStateChange(worker, 'listening', address, this.getWorkerListeningMsg(worker, address));
};

Cluster.prototype.getWorkerListeningMsg = function (worker, address) {
	return [
		address.address, ':', address.port
	].join('');
};

Cluster.prototype.onWorkerDisconnect = function (worker) {
	var info = this.workersInfo[worker.id];
	// WARN workaround, sometimes getting exit before disconnect
	if (info && !info.stateHistory.exit) {
		this.zombieChecker.add(worker.id);
		this.handleWorkerStateChange(worker, 'disconnect');
	}
};

Cluster.prototype.onWorkerExit = function (worker, code, signal) {
	this.zombieChecker.remove(worker.id);
	cluster.fork();
	var logLevel = (worker.suicide ? null : 'critical');
	this.handleWorkerStateChange(worker, 'exit', {
		code: code,
		signal: signal,
		isSuicide: worker.suicide
	}, this.getWorkerExitMsg(worker, code, signal), logLevel);
	delete this.workersInfo[worker.id];
};

Cluster.prototype.getWorkerExitMsg = function (worker, code, signal) {
	var parts = ['code = ', code];
	if (worker.suicide) {
		parts.push(', suicide');
	}
	else if (signal != null) {
		parts.push(', signal = ', signal);
	}
	return parts.join('');
};

Cluster.prototype.checkLazy = function (items) {
	for (var k in items) {
		var info = this.workersInfo[k];
		if (info != null && info.stateHistory.listening == null && (Date.now() - info.stateHistory.fork.date) > this.settings.checks.lazy.maxTime) {
			this.reportLazy(k);
			this.lazyChecker.remove(k); // report once
		}
	}
};

Cluster.prototype.reportLazy = function (workerId) {
	this.logger.critical(['Lazy worker detected, worker id = ', workerId].join(''));
};

Cluster.prototype.checkZombie = function (items) {
	for (var k in items) {
		var info = this.workersInfo[k];
		if (info != null && info.stateHistory.exit == null && (Date.now() - info.stateHistory.disconnect.date) > this.settings.checks.zombie.maxTime) {
			this.reportZombie(k);
			this.zombieChecker.remove(k); // report once
		}
	}
};

Cluster.prototype.reportZombie = function (workerId) {
	this.logger.critical(['Zombie worker detected, worker id = ', workerId].join(''));
};

module.exports = Cluster;
<commit_msg>added numberOfWorkers check<commit_after>"use strict";
var cluster = require('cluster');
var os = require('os');
var TimedChecker = require('./tools/timed_checker');

var Cluster = function (opt_app) {
	this.app = opt_app;
	this.settings = null;

	this.isDisabled = null;
	this.numberOfWorkers = null;
	this.logger = null;

	this.workersInfo = {};

	this.lazyChecker = null;
	this.zombieChecker = null;
};

Cluster.prototype.unitIsInitRequired = true;

Cluster.prototype.unitInit = function (units) {
	if (this.app == null) {
		this.app = units.require('core.app');
	}

	this.settings = units.require('core.settings').core.cluster;
	this.logger = units.require('core.logging').getLogger('cluster');

	this.isDisabled = this.settings.disable;
	this.numberOfWorkers = (this.settings.numberOfWorkers != null ? this.settings.numberOfWorkers : os.cpus().length);
};

Cluster.prototype.createLazyChecker = function () {
	var self = this;
	return new TimedChecker(function () {
		self.checkLazy(this.items);
	}, this.settings.checks.lazy.interval);
};

Cluster.prototype.createZombieChecker = function () {
	var self = this;
	return new TimedChecker(function () {
		self.checkZombie(this.items);
	}, this.settings.checks.zombie.interval);
};

Cluster.prototype.start = function () {
	if (cluster.isMaster) {
		this.startMaster();
	}
	else {
		this.app.startWorker();
	}
};

Cluster.prototype.startMaster = function () {
	this.setupMaster();
	this.createCheckers();
	this.initListeners();
	this.forkWorkers();
};

Cluster.prototype.setupMaster = function () {
	var settings = null;
	for (var k in this.settings.master) {
		var v = this.settings.master[k];
		if (v != null) {
			settings = settings || {};
			settings[k] = v;
		}
	}
	cluster.setupMaster(settings);
};

Cluster.prototype.createCheckers = function () {
	this.lazyChecker = this.createLazyChecker();
	this.zombieChecker = this.createZombieChecker();
};

Cluster.prototype.initListeners = function () {
	var self = this;
	cluster.on('fork', function(worker) {
		self.onWorkerFork(worker);
	});
	cluster.on('online', function(worker) {
		self.onWorkerOnline(worker);
	});
	cluster.on('listening', function(worker, address) {
		self.onWorkerListening(worker, address);
	});
	cluster.on('disconnect', function(worker) {
		self.onWorkerDisconnect(worker);
	});
	cluster.on('exit', function(worker, code, signal) {
		self.onWorkerExit(worker, code, signal);
	});
};

Cluster.prototype.forkWorkers = function () {
	for (var i = 0; i < this.numberOfWorkers; i++) {
		cluster.fork();
	}
	if (this.numberOfWorkers < 1) {
		this.logger.critical(['No workers forked, numberOfWorkers = ', this.numberOfWorkers].join(''));
	}
	else {
		this.logger.info([this.numberOfWorkers, ' workers forked'].join(''));
	}
};

Cluster.prototype.handleWorkerStateChange = function (worker, state, opt_data, opt_msg, opt_logLevel) {
	this.updateWorkerInfo(worker, state, opt_data);
	this.reportWorkerStateChange(worker, state, opt_data, opt_msg, opt_logLevel);
};

Cluster.prototype.updateWorkerInfo = function (worker, state, opt_data) {
	var info;
	if (state == 'fork') {
		this.workersInfo[worker.id] = info = {
			stateHistory: {}
		};
	}
	else {
		info = this.workersInfo[worker.id];
	}

	info.state = state;
	var historyItem = {
		date: new Date()
	};
	if (opt_data != null) {
		historyItem.data = opt_data;
	}
	info.stateHistory[state] = historyItem;
};

Cluster.prototype.reportWorkerStateChange = function (worker, state, opt_data, opt_msg, opt_logLevel) {
	var logLevel = opt_logLevel || 'debug';
	var parts = ['Worker ', worker.id, ' ', state];
	if (opt_msg) {
		parts.push(', ', opt_msg);
	}
	this.logger.log(logLevel, parts.join(''));
};

Cluster.prototype.onWorkerFork = function (worker) {
	this.lazyChecker.add(worker.id);
	this.handleWorkerStateChange(worker, 'fork');
};

Cluster.prototype.onWorkerOnline = function (worker) {
	this.handleWorkerStateChange(worker, 'online');
};

Cluster.prototype.onWorkerListening = function (worker, address) {
	this.lazyChecker.remove(worker.id);
	this.handleWorkerStateChange(worker, 'listening', address, this.getWorkerListeningMsg(worker, address));
};

Cluster.prototype.getWorkerListeningMsg = function (worker, address) {
	return [
		address.address, ':', address.port
	].join('');
};

Cluster.prototype.onWorkerDisconnect = function (worker) {
	var info = this.workersInfo[worker.id];
	// WARN workaround, sometimes getting exit before disconnect
	if (info && !info.stateHistory.exit) {
		this.zombieChecker.add(worker.id);
		this.handleWorkerStateChange(worker, 'disconnect');
	}
};

Cluster.prototype.onWorkerExit = function (worker, code, signal) {
	this.zombieChecker.remove(worker.id);
	cluster.fork();
	var logLevel = (worker.suicide ? null : 'critical');
	this.handleWorkerStateChange(worker, 'exit', {
		code: code,
		signal: signal,
		isSuicide: worker.suicide
	}, this.getWorkerExitMsg(worker, code, signal), logLevel);
	delete this.workersInfo[worker.id];
};

Cluster.prototype.getWorkerExitMsg = function (worker, code, signal) {
	var parts = ['code = ', code];
	if (worker.suicide) {
		parts.push(', suicide');
	}
	else if (signal != null) {
		parts.push(', signal = ', signal);
	}
	return parts.join('');
};

Cluster.prototype.checkLazy = function (items) {
	for (var k in items) {
		var info = this.workersInfo[k];
		if (info != null && info.stateHistory.listening == null && (Date.now() - info.stateHistory.fork.date) > this.settings.checks.lazy.maxTime) {
			this.reportLazy(k);
			this.lazyChecker.remove(k); // report once
		}
	}
};

Cluster.prototype.reportLazy = function (workerId) {
	this.logger.critical(['Lazy worker detected, worker id = ', workerId].join(''));
};

Cluster.prototype.checkZombie = function (items) {
	for (var k in items) {
		var info = this.workersInfo[k];
		if (info != null && info.stateHistory.exit == null && (Date.now() - info.stateHistory.disconnect.date) > this.settings.checks.zombie.maxTime) {
			this.reportZombie(k);
			this.zombieChecker.remove(k); // report once
		}
	}
};

Cluster.prototype.reportZombie = function (workerId) {
	this.logger.critical(['Zombie worker detected, worker id = ', workerId].join(''));
};

module.exports = Cluster;
<|endoftext|>


<commit_before>'use strict';
exports.info = {
  name: 'mc',
  desc: 'Posts stats and online user list of a Nodecraft MC server',
  usage: 'mc',
};

const nodecraft = require('nodecraft-api');
const config = require('../../config');
const utils = require('../utilities');
const logger = require('winston');

// Set Nodecraft API credentials
const nodecraftAPI = nodecraft(config.nodecraft.username, config.nodecraft.api_key);

exports.run = (discord, msg) => {
  // Get server stats
  nodecraftAPI.services.stats(config.nodecraft.server_id, (err, results) => {
    if (err) {
      msg.channel.sendMessage('There was an error getting data for the subscriber server.');
    } else {
      logger.debug(JSON.stringify(results));
      const status = utils.capitalize(results.stats.status);
      let str = `\`\`\`Minecraft Subscriber Server Statistics\`\`\`Status: **${status}**`;
      const uptime = results.stats.time;
      const players = results.stats.players;
      if (status === 'Online') {
        str += ` - Uptime: **${uptime}** - Players Online: **${players.length}**`;
        const names = players
          .map(x => {
            return { name: x.username, modified: x.username.toLowerCase() };
          }).sort((a, b) => {
            if (a.modified < b.modified) {
              return -1;
            } else if (a.modified > b.modified) {
              return 1;
            } else {
              return 0;
            }
          });
        str += '\n\n';
        names.forEach(n => {
          str += n.name.replace(/_/gm, '\\_');
          if (names.indexOf(n) < names.length - 1) {
            str += ' | ';
          }
        });
      }
      msg.channel.sendMessage(str);
    }
  });
};
<commit_msg>Handle not giving Nodecraft credentials for MC command<commit_after>'use strict';
exports.info = {
  name: 'mc',
  desc: 'Posts stats and online user list of a Nodecraft MC server',
  usage: 'mc',
  aliases: [],
};

const nodecraft = require('nodecraft-api');
const config = require('../../config');
const utils = require('../utilities');
const logger = require('winston');

let nodecraftAPI;
// Set Nodecraft API credentials
if (config.nodecraft.username !== '' && config.nodecraft.api_key !== '') {
  nodecraftAPI = nodecraft(config.nodecraft.username, config.nodecraft.api_key);
}

exports.run = (client, msg) => {
  // Exit if we never connected to the nodecraft API
  if (!nodecraftAPI) {
    return;
  }
  // Get server stats
  nodecraftAPI.services.stats(config.nodecraft.server_id, (err, results) => {
    if (err) {
      msg.channel.sendMessage('There was an error getting data for the subscriber server.');
      return;
    }
    logger.debug(JSON.stringify(results));
    const status = utils.capitalize(results.stats.status);
    let str = `\`\`\`Minecraft Subscriber Server Statistics\`\`\`Status: **${status}**`;
    const uptime = results.stats.time;
    const players = results.stats.players;
    if (status === 'Online') {
      str += ` - Uptime: **${uptime}** - Players Online: **${players.length}**`;
      const names = players
        .map(x => {
          return { name: x.username, modified: x.username.toLowerCase() };
        }).sort((a, b) => {
          if (a.modified < b.modified) {
            return -1;
          } else if (a.modified > b.modified) {
            return 1;
          } else {
            return 0;
          }
        });
      str += '\n\n';
      names.forEach(n => {
        str += n.name.replace(/_/gm, '\\_');
        if (names.indexOf(n) < names.length - 1) {
          str += ' | ';
        }
      });
    }
    msg.channel.sendMessage(str);
  });
};
<|endoftext|>


<commit_before>/*
 * Optics / command.js
 * copyright (c) 2016 Susisu
 */

"use strict";

function endModule() {
    module.exports = Object.freeze({
        Argument,
        OptionalArgument,
        RequiredArgument,
        CommandBase,
        Command
    });
}

class Argument {
    constructor() {
    }
}

class OptionalArgument extends Argument {
    constructor(placeholder, defaultVal, reader) {
        super();
        this.placeholder = placeholder;
        this.defaultVal  = defaultVal;
        this.reader      = reader;
    }
}

class RequiredArgument extends Argument {
    constructor(placeholder, reader) {
        super();
        this.placeholder = placeholder;
        this.reader      = reader;
    }
}

class CommandBase {
    constructor() {
    }
}

class Command extends CommandBase {
    constructor(desc, opts, args, action) {
        super();
        this.desc   = desc;
        this.opts   = opts;
        this.args   = args;
        this.action = action;
    }
}

endModule();
<commit_msg>Add JSDoc comments for CommandBase and Command<commit_after>/*
 * Optics / command.js
 * copyright (c) 2016 Susisu
 */

/**
 * @module command
 */

"use strict";

function endModule() {
    module.exports = Object.freeze({
        Argument,
        OptionalArgument,
        RequiredArgument,
        CommandBase,
        Command
    });
}

class Argument {
    constructor() {
    }
}

class OptionalArgument extends Argument {
    constructor(placeholder, defaultVal, reader) {
        super();
        this.placeholder = placeholder;
        this.defaultVal  = defaultVal;
        this.reader      = reader;
    }
}

class RequiredArgument extends Argument {
    constructor(placeholder, reader) {
        super();
        this.placeholder = placeholder;
        this.reader      = reader;
    }
}

/**
 * The `CommandBase` class is the base class of commands.
 * @static
 */
class CommandBase {
    /**
     * Create an instance of `CommandBase`.
     */
    constructor() {
    }

    /**
     * Parse `argv` and run action associated with the command.
     * @param {module:output.Output} output Output target.
     * @param {string[]} argv Command-line arguments.
     * @throws {Error} Not implemented.
     */
    run(output, argv) {
        throw new Error("not implemented");
    }
}

/**
 * The `Command` class represents an ordinary command.
 * @extends module:command.CommandBase
 * @static
 */
class Command extends CommandBase {
    /**
     * Create an instance of `Command`.
     * @param {string} desc
     * @param {module:option.Option[]} opts
     * @param {module:command.Argument[]} args
     * @param {Function} action
     */
    constructor(desc, opts, args, action) {
        super();
        this.desc   = desc;
        this.opts   = opts;
        this.args   = args;
        this.action = action;
    }
}

endModule();
<|endoftext|>


<commit_before>"use strict";
var gh = require("simple-github")({
  owner: "heycam",
  repo: "webidl",
  token: process.env.GITHUB_TOKEN
});
var urlencode = require("urlencode");
var entities = require("entities");

var BASE_URL = "https://heycam.github.io/webidl/";
var COMMENT_INTRO = ``;

module.exports = (payload) => gh.request("GET /repos/:owner/:repo/pulls/:number/commits", { number: payload.number }).then(commits => {
    updateBody(payload, commits);
});

let shortSha = s => s.substr(0, 7);
let diff = (prev, next, anchor) => {
    prev = urlencode(prev.split("#")[0]);
    next = urlencode(next.split("#")[0]);
    return `https://services.w3.org/htmldiff?doc1=${ prev }&doc2=${ next }${ anchor || "" }`
};
let diffWithBase = (current, anchor) => diff(BASE_URL, current, anchor);
let rawgitLatest = (repo, branch, anchor) => `https://rawgit.com/${ repo }/${ branch }/index.html${ anchor || "" }`;
let rawgit = (repo, sha, anchor) => `https://cdn.rawgit.com/${ repo }/${ shortSha(sha) }/index.html${ anchor || "" }`;
let latest = (repo, branch, anchors) => {
    let anchor = anchors.length == 1 ? anchors[0] : null;
    let url = rawgitLatest(repo, branch, anchor);
    let diff = diffWithBase(url, anchor);
    return `[Preview](${ url }) ${ displayAnchors(url, anchors, 10) }| [Diff](${ diff }) ${ displayAnchors(diff, anchors, 10) }`;
}
let perCommit = (repo, current, prev, last, anchors) => {
    let anchor = anchors.length == 1 ? anchors[0] : null;
    let url = rawgit(repo, current.sha, anchor);
    let diffWBase = diffWithBase(url, anchor);
    let prevTxt = "";
    let txt = `<code title=${ JSON.stringify(msg(current)) }>${ shortSha(current.sha) }</code>`;
    if (prev) {
        let prevUrl = rawgit(repo, prev.sha, anchor);
        let prevDiff = diff(prevUrl, url, anchor);
        prevTxt = ` | [Diff w/ Previous](${ prevDiff })`
    }
    if (last) txt = `Latest (${ txt })`;
    return `${ txt }: [Preview](${ url }) ${ displayAnchors(url, anchors) }| [Diff w/ Head](${ diffWBase }) ${ displayAnchors(url, anchors) }${ prevTxt } _(${ current.commit.author.date.substr(0, 16).replace("T", " ") })_`;
}
let msg = (c, size) => {
    return entities.encodeHTML(shorten(c.commit.message, size));
}

let shorten = (txt, size) => {
    txt = txt.split("\n")[0];
    if (size < txt.length) {
        return txt.substr(0, size).trim() + "…";
    }
    return txt;
}

let previous = (repo, commits, anchors) => {
    if (commits.length == 1) return "";
    return "Per Commit Preview & Diffs" + commits.map((c, i) => {
        return perCommit(repo, c, commits[i-1], commits.length - 1 == i, anchors);
    }).join("\n") + "";
}

let getAnchors = (body) => {
    body = body.replace(/\r\n/g, "\n").split(COMMENT_BODY);
    if (body.length < 2) return [];
    return body[1].split(COMMENT_OUTRO)[0].trim().split(/,\s*/).filter(a => !(/^\s*$/).test(a)).map(a => "#" + a.trim().replace("#", ""));
}

let comment = (data, commits) => {
    var pr_branch   = data.head.ref;
    var pr_sha      = data.head.sha;
    var pr_repo     = data.head.repo.full_name;

    var base_branch = data.base.ref;
    var base_sha    = data.head.sha;
    var base_repo   = data.base.repo.full_name;
    var anchors = getAnchors(data.body);
    return `\n\n
${ COMMENT_INTRO }
${ COMMENT_BODY }
    ${ anchors.join(", ")}
${ COMMENT_OUTRO }

${ latest(pr_repo, pr_branch, anchors) }
${ previous(pr_repo, commits, anchors) }`
}

let body = (data, commits) => {
    let body = data.body.replace(/\r\n/g, "\n").trim();
    let newBod = body.split(COMMENT_INTRO)[0].trim() + comment(data, commits);
    return {
        needsUpdate: body != newBod.trim(),
        content: newBod,
        previous: body
    }
}

let displayAnchors = (url, anchors, size) => {
    if (!anchors || anchors.length < 2) return "";
    return anchors.map(a => `(<a href="${ url }${ a }" title="${ a }">${ size ? shorten(a, size) : "#" }</a>)`).join(" ") + " ";
}

let updateBody = (data, commits) => {
    let b = body(data, commits);
    b.updated = false;
    if (b.needsUpdate) {
        if (false) { //process.env.NODE_ENV == "production"
            return gh.request("PATCH /repos/:owner/:repo/pulls/:number", {
                number: data.number,
                body: {
                    body: b.content
                }
            }).then(_ => {
                b.updated = true;
                return b;
            }, err => {
                b.error = err
                return b;
            });
        } else {
            b.updated = "Not a live run!";
            console.log(b)
        }
    }
    return Promise.resolve(b);
}
<commit_msg>Move to prod.<commit_after>"use strict";
var gh = require("simple-github")({
  owner: "heycam",
  repo: "webidl",
  token: process.env.GITHUB_TOKEN
});
var urlencode = require("urlencode");
var entities = require("entities");

var BASE_URL = "https://heycam.github.io/webidl/";
var COMMENT_INTRO = ``;

module.exports = (payload) => gh.request("GET /repos/:owner/:repo/pulls/:number/commits", { number: payload.number }).then(commits => {
    updateBody(payload, commits);
});

let shortSha = s => s.substr(0, 7);
let diff = (prev, next, anchor) => {
    prev = urlencode(prev.split("#")[0]);
    next = urlencode(next.split("#")[0]);
    return `https://services.w3.org/htmldiff?doc1=${ prev }&doc2=${ next }${ anchor || "" }`
};
let diffWithBase = (current, anchor) => diff(BASE_URL, current, anchor);
let rawgitLatest = (repo, branch, anchor) => `https://rawgit.com/${ repo }/${ branch }/index.html${ anchor || "" }`;
let rawgit = (repo, sha, anchor) => `https://cdn.rawgit.com/${ repo }/${ shortSha(sha) }/index.html${ anchor || "" }`;
let latest = (repo, branch, anchors) => {
    let anchor = anchors.length == 1 ? anchors[0] : null;
    let url = rawgitLatest(repo, branch, anchor);
    let diff = diffWithBase(url, anchor);
    return `[Preview](${ url }) ${ displayAnchors(url, anchors, 10) }| [Diff](${ diff }) ${ displayAnchors(diff, anchors, 10) }`;
}
let perCommit = (repo, current, prev, last, anchors) => {
    let anchor = anchors.length == 1 ? anchors[0] : null;
    let url = rawgit(repo, current.sha, anchor);
    let diffWBase = diffWithBase(url, anchor);
    let prevTxt = "";
    let txt = `<code title=${ JSON.stringify(msg(current)) }>${ shortSha(current.sha) }</code>`;
    if (prev) {
        let prevUrl = rawgit(repo, prev.sha, anchor);
        let prevDiff = diff(prevUrl, url, anchor);
        prevTxt = ` | [Diff w/ Previous](${ prevDiff })`
    }
    if (last) txt = `Latest (${ txt })`;
    return `${ txt }: [Preview](${ url }) ${ displayAnchors(url, anchors) }| [Diff w/ Head](${ diffWBase }) ${ displayAnchors(url, anchors) }${ prevTxt } _(${ current.commit.author.date.substr(0, 16).replace("T", " ") })_`;
}
let msg = (c, size) => {
    return entities.encodeHTML(shorten(c.commit.message, size));
}

let shorten = (txt, size) => {
    txt = txt.split("\n")[0];
    if (size < txt.length) {
        return txt.substr(0, size).trim() + "…";
    }
    return txt;
}

let previous = (repo, commits, anchors) => {
    if (commits.length == 1) return "";
    return "Per Commit Preview & Diffs" + commits.map((c, i) => {
        return perCommit(repo, c, commits[i-1], commits.length - 1 == i, anchors);
    }).join("\n") + "";
}

let getAnchors = (body) => {
    body = body.replace(/\r\n/g, "\n").split(COMMENT_BODY);
    if (body.length < 2) return [];
    return body[1].split(COMMENT_OUTRO)[0].trim().split(/,\s*/).filter(a => !(/^\s*$/).test(a)).map(a => "#" + a.trim().replace("#", ""));
}

let comment = (data, commits) => {
    var pr_branch   = data.head.ref;
    var pr_sha      = data.head.sha;
    var pr_repo     = data.head.repo.full_name;

    var base_branch = data.base.ref;
    var base_sha    = data.head.sha;
    var base_repo   = data.base.repo.full_name;
    var anchors = getAnchors(data.body);
    return `\n\n
${ COMMENT_INTRO }
${ COMMENT_BODY }
    ${ anchors.join(", ")}
${ COMMENT_OUTRO }

${ latest(pr_repo, pr_branch, anchors) }
${ previous(pr_repo, commits, anchors) }`
}

let body = (data, commits) => {
    let body = data.body.replace(/\r\n/g, "\n").trim();
    let newBod = body.split(COMMENT_INTRO)[0].trim() + comment(data, commits);
    return {
        needsUpdate: body != newBod.trim(),
        content: newBod,
        previous: body
    }
}

let displayAnchors = (url, anchors, size) => {
    if (!anchors || anchors.length < 2) return "";
    return anchors.map(a => `(<a href="${ url }${ a }" title="${ a }">${ size ? shorten(a, size) : "#" }</a>)`).join(" ") + " ";
}

let updateBody = (data, commits) => {
    let b = body(data, commits);
    b.updated = false;
    if (b.needsUpdate) {
        if (process.env.NODE_ENV == "production") {
            return gh.request("PATCH /repos/:owner/:repo/pulls/:number", {
                number: data.number,
                body: {
                    body: b.content
                }
            }).then(_ => {
                b.updated = true;
                return b;
            }, err => {
                b.error = err
                return b;
            });
        } else {
            b.updated = "Not a live run!";
            console.log(b)
        }
    }
    return Promise.resolve(b);
}
<|endoftext|>


<commit_before>const userHierarchy = ['primary_owner', 'owner', 'admin', 'restricted', 'ultra_restricted']

//Auxiliary functions for my bot!
module.exports = {

	createTable: (title, table) => {
		let formattedMessage = {
			attachments: [
				{
					fallback: JSON.stringify(table),
					'title': title,
					fields: []
				}
			]
		}
		let index;
		for (index = 0; index < table.length; index++) {
			formattedMessage.attachments[0].fields.push({
				'title': '',
				'value': table[index],
				'short': true
			})
		}
		return formattedMessage
	},

	createDropdown: (text, callback_id, name, texts, values) => {
		let index;
		let info = {
			'text': text,
			attachments: [{
				'text': '',
				'fallback': 'Sorry, failed.',
				'callback_id': callback_id,
				actions: [
				{
					'name': name,
					'text': 'Select from below...',
					'type': 'select',
					'options': []
				}]
			}]
		}
		for (index = 0; index < texts.value; index++) {
			info.attachments[0].actions[0].options.push({
				'text': texts[index],
				'value': values[index]
			})
		}
	}
}<commit_msg>work please<commit_after>const userHierarchy = ['primary_owner', 'owner', 'admin', 'restricted', 'ultra_restricted']

//Auxiliary functions for my bot!
module.exports = {

	createTable: (title, table) => {
		let formattedMessage = {
			attachments: [
				{
					fallback: JSON.stringify(table),
					'title': title,
					fields: []
				}
			]
		}
		let index;
		for (index = 0; index < table.length; index++) {
			formattedMessage.attachments[0].fields.push({
				'title': '',
				'value': table[index],
				'short': true
			})
		}
		return formattedMessage
	},

	createDropdown: (text, callback_id, name, texts, values) => {
		let index;
		let info = {
			'text': text,
			attachments: [{
				'text': '',
				'fallback': 'Sorry, failed.',
				'callback_id': callback_id,
				actions: [
				{
					'name': name,
					'text': 'Select from below...',
					'type': 'select',
					'options': []
				}]
			}]
		}
		for (index = 0; index < texts.value; index++) {
			info.attachments[0].actions[0].options.push({
				'text': texts[index],
				'value': values[index]
			})
		}
		return info
	}
}<|endoftext|>


<commit_before>var fs = require('fs-extra')
var path = require('path')
var c = require('chalk')
var safeEval = require('safe-eval')
var YAML = require('yamljs')
var scriptConverter =require(__dirname + '/scripts')
var util = require(__dirname + '/util')

module.exports = function (argv) {

  if (argv.all) {

    var dialectsDir = process.cwd() + '/dialects'
    var queriesDir = process.cwd() + '/queries'

    if (!fs.existsSync(dialectsDir)) {
      return console.log('\n Nothing to compile\n')
    }

    if (fs.existsSync(queriesDir)) {
      fs.removeSync(queriesDir)
    }

    var tribes = fs.readdirSync(dialectsDir)
    tribes.forEach(function (tribe) {
      var tribeDialectsDir = dialectsDir + '/' + tribe
      var localities = fs.readdirSync(tribeDialectsDir)
      localities.forEach(function (locality) {
        compile(tribe, locality)
      })
    })

  } else if (argv._.length === 2) {

    var temp = argv._[1].split('/')

    if (temp.length === 2) {
      var tribe = temp[0].toLowerCase()
      var locality = temp[1].toLowerCase()
      compile(tribe, locality)
    }
    else {
      errorMessage()
    }

  } else {
    errorMessage()
  }

}

function errorMessage() {
  console.log(c.red('\n Invalid format\n'))
  console.log(' Use the format ' + c.bold('tani compile <tribe/locality>'))
  console.log(' Ex: tani compile adi/geling\n')
}

function compile(tribe, locality) {

  var localityPath = tribe + '/' + locality
  var localityDialectsDir = process.cwd() + '/dialects/' + localityPath

  if (!fs.existsSync(localityDialectsDir)) {
    return console.log(c.bold('\n %s') + ' does not exist\n', localityPath)
  }

  setupConceptIndex()
  compileTribe(tribe, locality)
  compileLocality(localityPath)
  compileQueries(localityPath, localityDialectsDir)

}

function compileQueries(localityPath, localityDialectsDir) {

  var conceptDialectEntry = []

  // where query files will reside
  var localityQueriesDir = process.cwd() + '/queries/' + localityPath
  var localityQueriesDirIndex = process.cwd() + '/queries/' + localityPath + '/index.acf'

  // create the queries dir
  fs.mkdirpSync(localityQueriesDir, localityDialectsDir)

  // compile the concept queries from the dialect file
  var localityMetadataFile = localityDialectsDir + '/meta.yml'
  var localityMetadata = YAML.load(localityMetadataFile)
  var script = localityMetadata.script

  Object.keys(util.constructs).forEach(function (construct) {

    // check if corresponding dialects dir exists
    var dialectsConstructDir = localityDialectsDir + '/' + construct
    if (fs.existsSync(dialectsConstructDir)) {

      function compileEntries(dialectsConstructDir, subDir) {

        var files = fs.readdirSync(dialectsConstructDir)
        files.forEach(function (file) {

         if (util.ignore.indexOf(file) === -1) {

          var currentFilePath = dialectsConstructDir + '/' + file
          var stat = fs.statSync(currentFilePath);

          if (stat.isDirectory()) {
            return compileEntries(currentFilePath, file)
          }
          else {

            var dialectFilePath = localityDialectsDir + '/' + construct + '/' + (subDir ? subDir + '/' : '') + file
            var dialectEntry = util.getDialectEntry(fs.readFileSync(dialectFilePath).toString())
            // dialect files entry?
            if (dialectEntry.length) {

              conceptDialectEntry.push(construct)

              var file = path.basename(dialectFilePath)

              var constructsIndexFile = localityQueriesDir + '/' + construct + '/index.acf'
              if (!fs.existsSync(constructsIndexFile)) {
                fs.createFileSync(constructsIndexFile)
              }

              var globalID = file.replace('.txt', '').toUpperCase()
              var queryFilePath = localityQueriesDir + '/' + construct + '/entries/' + file.replace('txt', 'acf')
              fs.createFileSync(queryFilePath)

              registerConcept(globalID, dialectEntry)

              var parsed = parseDialectFile(dialectFilePath, globalID, construct, script, localityPath)
              if (parsed) {
                fs.writeFileSync(queryFilePath, parsed)
                var includeString = 'include entries/' + file.replace('txt', 'acf') + '\n'
                fs.appendFileSync(constructsIndexFile, includeString)
              }
            }

          }

         }

        })

      }

      compileEntries(dialectsConstructDir)

      if (conceptDialectEntry.indexOf(construct) > -1) {
        var localityQueriesDirIndex = process.cwd() + '/queries/' + localityPath + '/index.acf'
        fs.appendFileSync(localityQueriesDirIndex, 'include ' + construct + '/index.acf\n')
      }

    }

  })

}

function setupConceptIndex() {

  var conceptsIndexFile = process.cwd() + '/queries/concepts.acf'

  if (!fs.existsSync(conceptsIndexFile)) {
    fs.createFileSync(conceptsIndexFile)
  }

  // add to the queries index file
  var queriesIndexFile = process.cwd() + '/queries/index.acf'

  if (!fs.existsSync(queriesIndexFile)) {
    fs.createFileSync(queriesIndexFile)
  }
  fs.appendFileSync(queriesIndexFile, 'include concepts.acf\n')

}

function registerConcept(globalID, literal) {

  var conceptEntry = "global "+ globalID +" = { literal: '"+ literal +"' }\n"
      conceptEntry += "CREATE (n:Concept %"+ globalID +"%)\n"
      console.log(conceptEntry)
      console.log('------')
  var conceptsIndexFile = process.cwd() + '/queries/concepts.acf'
  fs.appendFileSync(conceptsIndexFile, conceptEntry)

}

function compileTribe(tribe, locality) {

  var tribeDirIndex = process.cwd() + '/queries/' + tribe + '/index.acf'

  // set up tribe file index for this tribe/locality
  if (!fs.existsSync(tribeDirIndex)) {
    fs.createFileSync(tribeDirIndex)
    fs.appendFileSync(tribeDirIndex, 'var tribe = ' + tribe.capitalize() + '\n\n')
    fs.appendFileSync(tribeDirIndex, 'include ' + locality + '/index.acf\n')
  }
  else {
    var tribeDirIndexContent = fs.readFileSync(tribeDirIndex).toString()
    var localityIncludeString = 'include ' + locality + '/index.acf\n'
    if (tribeDirIndexContent.indexOf(localityIncludeString) < 0) {
      fs.appendFileSync(tribeDirIndex, localityIncludeString)
    }
  }

  // add to the queries index file
  var queriesIndexFile = process.cwd() + '/queries/index.acf'
  fs.appendFileSync(queriesIndexFile, 'include ' + tribe + '/index.acf\n')
}

function compileLocality(localityPath) {

  var localityQueriesDirIndex = process.cwd() + '/queries/' + localityPath + '/index.acf'

  if (!fs.existsSync(localityQueriesDirIndex)) {
    fs.createFileSync(localityQueriesDirIndex)
  }

}

function parseDialectFile(dialectFilePath, globalID, construct, script, localityPath) {

  var content

  // compile creation
  var dialectFileContent = fs.readFileSync(dialectFilePath).toString()
  var root = dialectFileContent.split('Root:')[1].split('\n')[0].trim()

  // make entry only if the root is defined
  if (root) {

    var createTemplateFile = __dirname + '/templates/create.txt'
    var derivateTemplateFile = __dirname + '/templates/derivate.txt'
    var exampleTemplateFile = __dirname + '/templates/example.txt'

    content = fs.readFileSync(createTemplateFile).toString()

    content = content.replace('#ROOT#', scriptConverter.convert(root, script, 'tanilogy', localityPath))
    content = content.replace('#TYPE#', construct)
    content = content.replace('#GLOBALID#', globalID)
    content = content.replace('#CONSTRUCT#', construct)

    // derivate

    // example(s)

  }

  return content

}
<commit_msg>global concepts<commit_after>var fs = require('fs-extra')
var path = require('path')
var c = require('chalk')
var safeEval = require('safe-eval')
var YAML = require('yamljs')
var scriptConverter =require(__dirname + '/scripts')
var util = require(__dirname + '/util')

module.exports = function (argv) {

  if (argv.all) {

    var dialectsDir = process.cwd() + '/dialects'
    var queriesDir = process.cwd() + '/queries'

    if (!fs.existsSync(dialectsDir)) {
      return console.log('\n Nothing to compile\n')
    }

    if (fs.existsSync(queriesDir)) {
      fs.removeSync(queriesDir)
    }

    var tribes = fs.readdirSync(dialectsDir)
    tribes.forEach(function (tribe) {
      var tribeDialectsDir = dialectsDir + '/' + tribe
      var localities = fs.readdirSync(tribeDialectsDir)
      localities.forEach(function (locality) {
        compile(tribe, locality)
      })
    })

  } else if (argv._.length === 2) {

    var temp = argv._[1].split('/')

    if (temp.length === 2) {
      var tribe = temp[0].toLowerCase()
      var locality = temp[1].toLowerCase()
      compile(tribe, locality)
    }
    else {
      errorMessage()
    }

  } else {
    errorMessage()
  }

}

function errorMessage() {
  console.log(c.red('\n Invalid format\n'))
  console.log(' Use the format ' + c.bold('tani compile <tribe/locality>'))
  console.log(' Ex: tani compile adi/geling\n')
}

function compile(tribe, locality) {

  var localityPath = tribe + '/' + locality
  var localityDialectsDir = process.cwd() + '/dialects/' + localityPath

  if (!fs.existsSync(localityDialectsDir)) {
    return console.log(c.bold('\n %s') + ' does not exist\n', localityPath)
  }

  setupConceptIndex()
  compileTribe(tribe, locality)
  compileLocality(localityPath)
  compileQueries(localityPath, localityDialectsDir)

}

function compileQueries(localityPath, localityDialectsDir) {

  var conceptDialectEntry = []

  // where query files will reside
  var localityQueriesDir = process.cwd() + '/queries/' + localityPath
  var localityQueriesDirIndex = process.cwd() + '/queries/' + localityPath + '/index.acf'

  // create the queries dir
  fs.mkdirpSync(localityQueriesDir, localityDialectsDir)

  // compile the concept queries from the dialect file
  var localityMetadataFile = localityDialectsDir + '/meta.yml'
  var localityMetadata = YAML.load(localityMetadataFile)
  var script = localityMetadata.script

  Object.keys(util.constructs).forEach(function (construct) {

    // check if corresponding dialects dir exists
    var dialectsConstructDir = localityDialectsDir + '/' + construct
    if (fs.existsSync(dialectsConstructDir)) {

      function compileEntries(dialectsConstructDir, subDir) {

        var files = fs.readdirSync(dialectsConstructDir)
        files.forEach(function (file) {

         if (util.ignore.indexOf(file) === -1) {

          var currentFilePath = dialectsConstructDir + '/' + file
          var stat = fs.statSync(currentFilePath);

          if (stat.isDirectory()) {
            return compileEntries(currentFilePath, file)
          }
          else {

            var dialectFilePath = localityDialectsDir + '/' + construct + '/' + (subDir ? subDir + '/' : '') + file
            var dialectEntry = util.getDialectEntry(fs.readFileSync(dialectFilePath).toString())
            // dialect files entry?
            if (dialectEntry.length) {

              conceptDialectEntry.push(construct)

              var file = path.basename(dialectFilePath)

              var constructsIndexFile = localityQueriesDir + '/' + construct + '/index.acf'
              if (!fs.existsSync(constructsIndexFile)) {
                fs.createFileSync(constructsIndexFile)
              }

              var globalID = file.replace('.txt', '').toUpperCase()
              var queryFilePath = localityQueriesDir + '/' + construct + '/entries/' + file.replace('txt', 'acf')
              fs.createFileSync(queryFilePath)

              registerConcept(globalID, dialectEntry)

              var parsed = parseDialectFile(dialectFilePath, globalID, construct, script, localityPath)
              if (parsed) {
                fs.writeFileSync(queryFilePath, parsed)
                var includeString = 'include entries/' + file.replace('txt', 'acf') + '\n'
                fs.appendFileSync(constructsIndexFile, includeString)
              }
            }

          }

         }

        })

      }

      compileEntries(dialectsConstructDir)

      if (conceptDialectEntry.indexOf(construct) > -1) {
        var localityQueriesDirIndex = process.cwd() + '/queries/' + localityPath + '/index.acf'
        fs.appendFileSync(localityQueriesDirIndex, 'include ' + construct + '/index.acf\n')
      }

    }

  })

}

function setupConceptIndex() {

  var conceptsIndexFile = process.cwd() + '/queries/concepts.acf'

  if (!fs.existsSync(conceptsIndexFile)) {
    fs.createFileSync(conceptsIndexFile)
  }

  // add to the queries index file
  var queriesIndexFile = process.cwd() + '/queries/index.acf'

  if (!fs.existsSync(queriesIndexFile)) {
    fs.createFileSync(queriesIndexFile)
  }
  fs.appendFileSync(queriesIndexFile, 'include concepts.acf\n')

}

function registerConcept(globalID, literal) {

  var conceptEntry = "global "+ globalID +" = { literal: '"+ literal +"' }\n"
      conceptEntry += "CREATE (n:Concept %"+ globalID +"%)\n"
  var conceptsIndexFile = process.cwd() + '/queries/concepts.acf'
  fs.appendFileSync(conceptsIndexFile, conceptEntry)

}

function compileTribe(tribe, locality) {

  var tribeDirIndex = process.cwd() + '/queries/' + tribe + '/index.acf'

  // set up tribe file index for this tribe/locality
  if (!fs.existsSync(tribeDirIndex)) {
    fs.createFileSync(tribeDirIndex)
    fs.appendFileSync(tribeDirIndex, 'var tribe = ' + tribe.capitalize() + '\n\n')
    fs.appendFileSync(tribeDirIndex, 'include ' + locality + '/index.acf\n')
  }
  else {
    var tribeDirIndexContent = fs.readFileSync(tribeDirIndex).toString()
    var localityIncludeString = 'include ' + locality + '/index.acf\n'
    if (tribeDirIndexContent.indexOf(localityIncludeString) < 0) {
      fs.appendFileSync(tribeDirIndex, localityIncludeString)
    }
  }

  // add to the queries index file
  var queriesIndexFile = process.cwd() + '/queries/index.acf'
  fs.appendFileSync(queriesIndexFile, 'include ' + tribe + '/index.acf\n')
}

function compileLocality(localityPath) {

  var localityQueriesDirIndex = process.cwd() + '/queries/' + localityPath + '/index.acf'

  if (!fs.existsSync(localityQueriesDirIndex)) {
    fs.createFileSync(localityQueriesDirIndex)
  }

}

function parseDialectFile(dialectFilePath, globalID, construct, script, localityPath) {

  var content

  // compile creation
  var dialectFileContent = fs.readFileSync(dialectFilePath).toString()
  var root = dialectFileContent.split('Root:')[1].split('\n')[0].trim()

  // make entry only if the root is defined
  if (root) {

    var createTemplateFile = __dirname + '/templates/create.txt'
    var derivateTemplateFile = __dirname + '/templates/derivate.txt'
    var exampleTemplateFile = __dirname + '/templates/example.txt'

    content = fs.readFileSync(createTemplateFile).toString()

    content = content.replace('#ROOT#', scriptConverter.convert(root, script, 'tanilogy', localityPath))
    content = content.replace('#TYPE#', construct)
    content = content.replace('#GLOBALID#', globalID)
    content = content.replace('#CONSTRUCT#', construct)

    // derivate

    // example(s)

  }

  return content

}
<|endoftext|>


<commit_before>let plugin = require('..').plugin
let _ = require('underscore')

let ep = plugin.extensionPoints['http.endpoint']

exports.listRoutes = (println, tokens) => {
  let endpoints = ep.array

  println('Available end points')
  endpoints.forEach((endpoint) => {
    let method = endpoint.method || 'all'
    let line = '\t' + method + '\t' + endpoint.path
    if (endpoint.directory) {
      line += '/*'
    }
    if (endpoint.description) {
      line += '\t' + endpoint.description
    } else if (endpoint.directory) {
      line += 'static'
    }

    if (endpoint.directory) {
      line += ' - ' + endpoint.directory
    }

    println(line)
  })
  if (endpoints.length === 0) {
    println('\tNone')
  }
}<commit_msg>Change console to use cli-table format.<commit_after>let plugin = require('..').plugin
let _ = require('underscore')

let ep = plugin.extensionPoints['http.endpoint']

exports.listRoutes = (output, tokens) => {
  let endpoints = ep.array

  output.log('Available end points')
  let rows = endpoints.map((endpoint) => {

    let method = endpoint.method || 'all'
    let path = endpoint.path
    let desc = endpoint.description || ''
    if (endpoint.directory) {
      path += '/*'
    }

    if (endpoint.directory) {
      desc = 'static - ' + endpoint.directory
    }

    return [method, path, desc]
  })
  if (endpoints.length === 0) {
    output.log('\tNone')
  } else {
    output.table({}, rows)
  }
}<|endoftext|>