<commit_before>var append = require('append');
var Cache = require('persistence-cache').Cache;

exports.stores = {};
exports.caches = {};

/**
 * Connects to memory db.
 *
 * This is only needed for similarity to other db layers.
 *
 * @param options
 *            [optional]
 * @param callback
 *            (err, db)
 */
exports.connect = function(options, callback) {
  if (typeof options == 'function') {
    callback = options;
    options = {};
  }

  callback(null, new Memory(options));
};

var Memory = exports.Memory = function Memory(options) {
  var counter = 0;
  options = options || {};
  this.uri = options.uri;

  this.increment = function() {
    return ++counter;
  };

  if (typeof this.uri == 'string') {
    // Application-wide store
    if (!exports.stores[this.uri]) {
      this.store = exports.stores[this.uri] = {};
      this.cache = exports.caches[this.uri] = new Cache();
    } else {
      // Use store that was created before
      this.store = exports.stores[this.uri];
      this.cache = exports.caches[this.uri];
    }
  } else {
    // Connection-wise store
    this.store = {};
    this.cache = new Cache();
  }
};

Memory.prototype.protocol = 'memory';

Memory.prototype.load = function(data) {
  if (data instanceof Array) {
    var tmp = {};
    data.forEach(function(e) {
      tmp[e.id] = JSON.stringify(e);
    });
    data = tmp;
  }

  this.store = data;

  // Update cache
  if (this.uri) {
    exports.stores[this.uri] = JSON.parse(JSON.stringify(this.store));
  }

  return this;
};

Memory.prototype.request = function(fn) {
  var self = this;

  process.nextTick(function() {
    fn.call(self);
  });
};

Memory.prototype.save = function(key, val, callback) {
  var args = Array.prototype.slice.call(arguments);
  var callback = args.pop(), val = args.pop();
  if (!args.length || !key) {
    key = this.increment();
    val.id = key;
  }

  // Forces key to be a string
  key += '';
  val.id += '';

  this.request(function() {
    this.store[key] = JSON.stringify(val);
    callback(null, val);
  });
};

Memory.prototype.put = function() {
  this.save.apply(this, arguments);
};

Memory.prototype.update = function(key, obj, callback) {
  var jsObj = JSON.parse(this.store[key] || "{}");
  this.put(key, append(jsObj, obj), callback);
};

Memory.prototype.get = function(key, callback) {
  this.request(function() {
    key = key.toString();
    return (key in this.store) ? callback(null, JSON.parse(this.store[key]
        || "null")) : callback({
      status : 404
    });
  });
};

Memory.prototype.destroy = function(key, callback) {
  this.request(function() {
    delete this.store[key];
    return callback(null, {
      status : 204
    });
  });
};

Memory.prototype.find = function(conditions, callback) {
  this.filter(function(obj) {
    return Object.keys(conditions).every(function(k) {
      return conditions[k] === obj[k];
    });
  }, callback);
};

Memory.prototype.filter = function(filter, callback) {
  this.request(function() {
    var result = [], store = this.store;

    Object.keys(this.store).forEach(function(k) {
      var obj = JSON.parse(store[k]);
      if (filter(obj)) {
        obj.id = obj.id.split('/').slice(1).join('/');
        result.push(obj);
      }
    });

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

Memory.prototype.sync = function(factory, callback) {
  process.nextTick(function() {
    callback();
  });
};
<commit_msg>Comments<commit_after>var append = require('append');
var Cache = require('persistence-cache').Cache;

exports.stores = {};
exports.caches = {};

/**
 * Connects to memory db.
 *
 * This is only needed for similarity to other db layers.
 *
 * @param options
 *            [optional]
 * @param callback
 *            (err, db)
 */
exports.connect = function(options, callback) {
  if (typeof options == 'function') {
    callback = options;
    options = {};
  }

  callback(null, new Memory(options));
};

/**
 * Constructor
 */
var Memory = exports.Memory = function Memory(options) {
  var counter = 0;
  options = options || {};
  this.uri = options.uri;

  this.increment = function() {
    return ++counter;
  };

  if (typeof this.uri == 'string') { // Application-wide store
    if (!exports.stores[this.uri]) {
      this.store = exports.stores[this.uri] = {};
      this.cache = exports.caches[this.uri] = new Cache();
    } else {
      // Use store that was created before
      this.store = exports.stores[this.uri];
      this.cache = exports.caches[this.uri];
    }
  } else { // Connection-wide store
    this.store = {};
    this.cache = new Cache();
  }
};

Memory.prototype.protocol = 'memory';

/**
 * Loads some data into this store.
 */
Memory.prototype.load = function(data) {
  if (data instanceof Array) {
    var tmp = {};
    data.forEach(function(e) {
      tmp[e.id] = JSON.stringify(e);
    });
    data = tmp;
  }

  this.store = data;

  // Update cache
  if (this.uri) {
    exports.stores[this.uri] = JSON.parse(JSON.stringify(this.store));
  }

  return this;
};

/**
 * Request a function.
 */
Memory.prototype.request = function(fn) {
  var self = this;

  process.nextTick(function() {
    fn.call(self);
  });
};

/**
 * Save the record at the given key.
 *
 * @see Memory.prototype.put
 */
Memory.prototype.save = function(key, val, callback) {
  var args = Array.prototype.slice.call(arguments);
  var callback = args.pop(), val = args.pop();
  if (!args.length || !key) {
    key = this.increment();
    val.id = key;
  }

  // Forces key to be a string
  key += '';
  val.id += '';

  this.request(function() {
    this.store[key] = JSON.stringify(val);
    callback(null, val);
  });
};

/**
 * Save the record at the given key.
 *
 * @see Memory.prototype.save
 */
Memory.prototype.put = function() {
  this.save.apply(this, arguments);
};

/**
 * Updates a record.
 *
 * TODO Should behave like a save, but a file must.
 */
Memory.prototype.update = function(key, obj, callback) {
  var current = JSON.parse(this.store[key] || "{}");
  this.put(key, append(current, obj), callback);
};

/**
 *
 */
Memory.prototype.get = function(key, callback) {
  this.request(function() {
    key = key.toString();
    return (key in this.store) ? callback(null, JSON.parse(this.store[key]
        || "null")) : callback({
      status : 404
    });
  });
};

Memory.prototype.destroy = function(key, callback) {
  this.request(function() {
    delete this.store[key];
    return callback(null, {
      status : 204
    });
  });
};

Memory.prototype.find = function(conditions, callback) {
  this.filter(function(obj) {
    return Object.keys(conditions).every(function(k) {
      return conditions[k] === obj[k];
    });
  }, callback);
};

Memory.prototype.filter = function(filter, callback) {
  this.request(function() {
    var result = [], store = this.store;

    Object.keys(this.store).forEach(function(k) {
      var obj = JSON.parse(store[k]);
      if (filter(obj)) {
        obj.id = obj.id.split('/').slice(1).join('/');
        result.push(obj);
      }
    });

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

Memory.prototype.sync = function(factory, callback) {
  process.nextTick(function() {
    callback();
  });
};
<|endoftext|>


<commit_before>var DB_FIELDS = ['dialect', 'host', 'port', 'database', 'username', 'password', 'storage'];

var Sequelize = require('sequelize'),
    util = require('../util');

/* Load Database Configuration */
var db = util.getEnvConfig(DB_FIELDS, { prefix: 'DB_' });

// use sqlite by defaults if no dialect is specified
db.dialect = db.dialect || 'sqlite';
switch (db.dialect) {
case 'sqlite':
    db.storage = db.storage || 'app.db';
    break;
case 'mysql':
    if (!util.hasFields(db, ['host', 'port', 'database', 'username', 'password']))
        throw new Error("Missing or incomplete MySQL database configuration.");
    break;
}

/* Connect to Database Server */
var ORM; ORM = function(name, fields, init) {
    var config = {};
    Object.keys(fields)
        .filter(function (f) { return f.match(/^\$/) })
        .forEach(function (f) {
            config[f.replace(/^\$/, '')] = fields[f];
            delete fields[f];
        });
    var model = ORM.models[name] = ORM.sequelize.define(name, fields, config);
    init = init || function(){};
    model.init = function () {
        init.call(model, ORM.models);
    }.bind(model);
    model.fields = Object.keys(fields)
                         .filter(function (f) { return !f.match(/^\$/) });
    return model;
};
function make_types(typedefs) {
    var types = {};
    Object.keys(typedefs).forEach(function (t) {
        var type = typedefs[t].type;
        types[t] = util.autoconfig(typedefs[t])({ toString: type.toString.bind(type) });
        util.defProp(types[t], 'type', { get: function () { return this.toString() } });
    });
    return util.extend(Sequelize, types);
}
ORM.config = db;
ORM.sequelize = new Sequelize(db.database, db.username, db.password,
                                { host: db.host, port: db.port, dialect: db.dialect,
                                  storage: db.storage });
ORM.models    = {};
ORM.types     = make_types({
    String: { type: Sequelize.STRING  },
    Text:   {
        type:       Sequelize.TEXT,
        allowNull:  false,
        defaultValue: ''
    },
    Int:    { type: Sequelize.INTEGER },
    Float:  { type: Sequelize.FLOAT   },
    Date:   {
        type:       Sequelize.DATE,
        allowNull:  true,
        defaultValue: null
    },
    URL:    {
        type:       Sequelize.STRING,
        validate:   { isUrl: true },
        allowNull:  true,
        defaultValue: null
    },
    Email:  {
        type:       Sequelize.STRING,
        validate:   { isEmail: true }
    }
});
require('../models')(ORM);
module.exports = ORM;
<commit_msg>Fix bug 922747 - Add support for Heroku CLEARDB_DATABASE_URL<commit_after>var Habitat = require('habitat'),
    config = new Habitat();

var Sequelize = require('sequelize'),
    util = require('../util');

/* Connect to Database Server */
var ORM = function(name, fields, init) {
    var config = {};
    Object.keys(fields)
        .filter(function (f) { return f.match(/^\$/) })
        .forEach(function (f) {
            config[f.replace(/^\$/, '')] = fields[f];
            delete fields[f];
        });
    var model = ORM.models[name] = ORM.sequelize.define(name, fields, config);
    init = init || function(){};
    model.init = function () {
        init.call(model, ORM.models);
    }.bind(model);
    model.fields = Object.keys(fields)
                         .filter(function (f) { return !f.match(/^\$/) });
    return model;
};
function make_types(typedefs) {
    var types = {};
    Object.keys(typedefs).forEach(function (t) {
        var type = typedefs[t].type;
        types[t] = util.autoconfig(typedefs[t])({ toString: type.toString.bind(type) });
        util.defProp(types[t], 'type', { get: function () { return this.toString() } });
    });
    return util.extend(Sequelize, types);
}

if (config.get('CLEARDB_DATABASE_URL')) {
  ORM.sequelize = new Sequelize(config.get('CLEARDB_DATABASE_URL'));
} else {
  var db = config.get('DB');
  ORM.sequelize = new Sequelize(db.database, db.username, db.password,
                                  { host: db.host, port: db.port, dialect: db.dialect,
                                    storage: db.storage });
}

ORM.models    = {};
ORM.types     = make_types({
    String: { type: Sequelize.STRING  },
    Text:   {
        type:       Sequelize.TEXT,
        allowNull:  false,
        defaultValue: ''
    },
    Int:    { type: Sequelize.INTEGER },
    Float:  { type: Sequelize.FLOAT   },
    Date:   {
        type:       Sequelize.DATE,
        allowNull:  true,
        defaultValue: null
    },
    URL:    {
        type:       Sequelize.STRING,
        validate:   { isUrl: true },
        allowNull:  true,
        defaultValue: null
    },
    Email:  {
        type:       Sequelize.STRING,
        validate:   { isEmail: true }
    }
});
require('../models')(ORM);
module.exports = ORM;
<|endoftext|>


<commit_before>var gulp = require('gulp'),
    gutil = require('gulp-util'),
    react = require('gulp-react'),
    jshint = require('gulp-jshint'),
    fs = require('fs'),
    buffer = require('vinyl-buffer'),
    source = require('vinyl-source-stream'),
    aliasify = require('aliasify'),
    browserify = require('browserify'),
    uglify = require('gulp-uglify'),
    nodemon = require('nodemon'),
    browserSync = require('browser-sync'),
    serverStarted = false,

// If you use vim and watch tasks be triggered 2 times when saving
// You can :set nowritebackup in vim to prevent this
// Reference: https://github.com/joyent/node/issues/3172
configs = {
    test_tmp_dir: 'test_tmp/',
    static_dir: 'static/',
    mainjs: require(process.cwd() + '/package.json').main,
    appjs: process.cwd() + '/fluxexapp.js',
    nodemon_restart_delay: 200,
    nodemon_delay: 2000,
    gulp_watch: {debounceDelay: 500},
    watchify: {debug: true, delay: 500},
    jshint_jsx: {quotmark: false},
    aliasify: {
        aliases: {
            request: 'browser-request'
        }
    }
},

build_files = {
    js: ['actions/*.js', 'stores/*.js'],
    jsx: ['components/*.jsx']
},

restart_nodemon = function () {
    setTimeout(function () {
        nodemon.emit('restart');
    }, configs.nodemon_restart_delay);
},

// Never use node-jsx or other transform in your code!
initIstanbulHookHack = function () {
    var React = require('react-tools'),
        Module = require('module');

    Module._extensions['.js'] = function (module, filename) {
        var src = fs.readFileSync(filename, {encoding: 'utf8'}),
            React = require('react-tools');

        if (filename.match(/\.jsx/)) {
            try {
                src = React.transform(src);
            } catch (e) {
                throw new Error('Error when transform ' + filename + ': ' + e.toString());
            }
        }
        module._compile(src, filename);
    };
},

bundleAll = function (b, noSave) {
    var B = b.bundle()
    .on('error', function (E) {
        gutil.log('[browserify ERROR]', gutil.colors.red(E));
    });

    if (!noSave) {
        B.pipe(source('main.js'))
        .pipe(gulp.dest(configs.static_dir + 'js/'))
        .on('end', restart_nodemon);
    }

    return B;
},

buildApp = function (watch, fullpath, nosave, disc) {
    var b = browserify(configs.appjs, {
        cache: {},
        packageCache: {},
        require: (disc ? process.cwd() : '.') + '/components/Html.jsx',
        standalone: 'Fluxex',
        fullPaths: fullpath ? true: false,
        debug: watch
    });

    b.transform('reactify');
    b.transform(aliasify.configure(configs.aliasify), {global: true});

    if (watch) {
        b = require('watchify')(b, configs.watchify);
        b.on('update', function (F) {
            gutil.log('[browserify] ' + F[0] + ' updated');
            bundleAll(b);
        });
    }

    return bundleAll(b, nosave);
};

gulp.task('build_app', function () {
    return buildApp(false, false, true)
        .pipe(source('main.js'))
        .pipe(buffer())
        .pipe(uglify())
        .pipe(gulp.dest(configs.static_dir + 'js/'));
});

gulp.task('disc_app', function () {
    return buildApp(false, true, true, true)
        .pipe(require('disc')())
        .pipe(fs.createWriteStream(configs.static_dir + 'disc.html'));
});

gulp.task('watch_app', function () {
    return buildApp(true, true);
});

gulp.task('watch_flux_js', ['lint_flux_js'], function () {
    gulp.watch(build_files.js, configs.gulp_watch, ['lint_flux_js']);
});

gulp.task('lint_flux_js', function () {
    return gulp.src(build_files.js)
    .pipe(jshint())
    .pipe(jshint.reporter('jshint-stylish'));
});

gulp.task('watch_jsx', ['lint_jsx'], function () {
    gulp.watch(build_files.jsx, configs.gulp_watch, ['lint_jsx']);
});

gulp.task('lint_jsx', function () {
    return gulp.src(build_files.jsx)
    .pipe(react({
        sourceMap: true
    }))
    .on('error', function (E) {
        gutil.log('[jsx ERROR]', gutil.colors.red(E.fileName));
        gutil.log('[jsx ERROR]', gutil.colors.red(E.message));
    })
    .pipe(jshint(configs.jshint_jsx))
    .pipe(jshint.reporter('jshint-stylish'));
});

gulp.task('watch_server', ['lint_server'], function () {
    gulp.watch(configs.mainjs, configs.gulp_watch, ['lint_server'])
    .on('change', function () {
        nodemon.emit('restart');
    });
});

gulp.task('lint_server', function () {
    return gulp.src(configs.mainjs)
    .pipe(jshint())
    .pipe(jshint.reporter('jshint-stylish'))
});

gulp.task('nodemon_server', ['watch_flux_js', 'watch_jsx', 'watch_app', 'watch_server'], function () {
    nodemon({
        ignore: '*',
        script: configs.mainjs,
        ext: 'do_not_watch'
    })
    .on('log', function (log) {
        gutil.log(log.colour);
    })
    .on('start', function () {
        if (serverStarted) {
            setTimeout(browserSync.reload, configs.nodemon_delay);
        } else {
            browserSync.init(null, {
                proxy: 'http://localhost:3000',
                files: [configs.static_dir + 'css/*.css'],
                port: 3001,
                online: false,
                open: false
            });

            serverStarted = true;
        }
    });
});

gulp.task('test_app', function (cb) {
    var istanbul = initIstanbulHookHack() || require('gulp-istanbul'),
        hook = require('istanbul').hook,
        mocha = require('gulp-mocha');

    gulp.src(build_files.jsx.concat(build_files.js))
    .pipe(react({keepExt: true}))
    .pipe(istanbul({includeUntested: true}))
    .pipe(istanbul.hookRequire())
    .on('finish', function () {
        return gulp.src(['test/**/*.js', 'test/components/*.js*'])
//        .pipe(react())
//        .pipe(react({keepExt: true}))
        .pipe(mocha())
        .pipe(istanbul.writeReports())
        .on('end', cb);
    });
});

gulp.task('develop', ['nodemon_server']);
gulp.task('lint_all', ['lint_server', 'lint_flux_js', 'lint_jsx']);
gulp.task('buildall', ['lint_all', 'build_app']);
gulp.task('default',['buildall']);
<commit_msg>enable jsx coverage with istanbul. Now hack into module loader and need to patch gulp-react (refer to: https://github.com/sindresorhus/gulp-react/pull/29 )<commit_after>var gulp = require('gulp'),
    gutil = require('gulp-util'),
    react = require('gulp-react'),
    jshint = require('gulp-jshint'),
    fs = require('fs'),
    buffer = require('vinyl-buffer'),
    source = require('vinyl-source-stream'),
    aliasify = require('aliasify'),
    browserify = require('browserify'),
    uglify = require('gulp-uglify'),
    nodemon = require('nodemon'),
    browserSync = require('browser-sync'),
    serverStarted = false,

// If you use vim and watch tasks be triggered 2 times when saving
// You can :set nowritebackup in vim to prevent this
// Reference: https://github.com/joyent/node/issues/3172
configs = {
    test_tmp_dir: 'test_tmp/',
    static_dir: 'static/',
    mainjs: require(process.cwd() + '/package.json').main,
    appjs: process.cwd() + '/fluxexapp.js',
    nodemon_restart_delay: 200,
    nodemon_delay: 2000,
    gulp_watch: {debounceDelay: 500},
    watchify: {debug: true, delay: 500},
    jshint_jsx: {quotmark: false},
    aliasify: {
        aliases: {
            request: 'browser-request'
        }
    }
},

build_files = {
    js: ['actions/*.js', 'stores/*.js'],
    jsx: ['components/*.jsx']
},

restart_nodemon = function () {
    setTimeout(function () {
        nodemon.emit('restart');
    }, configs.nodemon_restart_delay);
},

// Never use node-jsx or other transform in your code!
initIstanbulHookHack = function () {
    var React = require('react-tools'),
        Module = require('module');

    Module._extensions['.js'] = function (module, filename) {
        var src = fs.readFileSync(filename, {encoding: 'utf8'}),
            React = require('react-tools');

        if (filename.match(/\.jsx/)) {
            try {
                src = React.transform(src);
            } catch (e) {
                throw new Error('Error when transform ' + filename + ': ' + e.toString());
            }
        }
        module._compile(src, filename);
    };
},

bundleAll = function (b, noSave) {
    var B = b.bundle()
    .on('error', function (E) {
        gutil.log('[browserify ERROR]', gutil.colors.red(E));
    });

    if (!noSave) {
        B.pipe(source('main.js'))
        .pipe(gulp.dest(configs.static_dir + 'js/'))
        .on('end', restart_nodemon);
    }

    return B;
},

buildApp = function (watch, fullpath, nosave, disc) {
    var b = browserify(configs.appjs, {
        cache: {},
        packageCache: {},
        require: (disc ? process.cwd() : '.') + '/components/Html.jsx',
        standalone: 'Fluxex',
        fullPaths: fullpath ? true: false,
        debug: watch
    });

    b.transform('reactify');
    b.transform(aliasify.configure(configs.aliasify), {global: true});

    if (watch) {
        b = require('watchify')(b, configs.watchify);
        b.on('update', function (F) {
            gutil.log('[browserify] ' + F[0] + ' updated');
            bundleAll(b);
        });
    }

    return bundleAll(b, nosave);
};

gulp.task('build_app', function () {
    return buildApp(false, false, true)
        .pipe(source('main.js'))
        .pipe(buffer())
        .pipe(uglify())
        .pipe(gulp.dest(configs.static_dir + 'js/'));
});

gulp.task('disc_app', function () {
    return buildApp(false, true, true, true)
        .pipe(require('disc')())
        .pipe(fs.createWriteStream(configs.static_dir + 'disc.html'));
});

gulp.task('watch_app', function () {
    return buildApp(true, true);
});

gulp.task('watch_flux_js', ['lint_flux_js'], function () {
    gulp.watch(build_files.js, configs.gulp_watch, ['lint_flux_js']);
});

gulp.task('lint_flux_js', function () {
    return gulp.src(build_files.js)
    .pipe(jshint())
    .pipe(jshint.reporter('jshint-stylish'));
});

gulp.task('watch_jsx', ['lint_jsx'], function () {
    gulp.watch(build_files.jsx, configs.gulp_watch, ['lint_jsx']);
});

gulp.task('lint_jsx', function () {
    return gulp.src(build_files.jsx)
    .pipe(react({
        sourceMap: true
    }))
    .on('error', function (E) {
        gutil.log('[jsx ERROR]', gutil.colors.red(E.fileName));
        gutil.log('[jsx ERROR]', gutil.colors.red(E.message));
    })
    .pipe(jshint(configs.jshint_jsx))
    .pipe(jshint.reporter('jshint-stylish'));
});

gulp.task('watch_server', ['lint_server'], function () {
    gulp.watch(configs.mainjs, configs.gulp_watch, ['lint_server'])
    .on('change', function () {
        nodemon.emit('restart');
    });
});

gulp.task('lint_server', function () {
    return gulp.src(configs.mainjs)
    .pipe(jshint())
    .pipe(jshint.reporter('jshint-stylish'))
});

gulp.task('nodemon_server', ['watch_flux_js', 'watch_jsx', 'watch_app', 'watch_server'], function () {
    nodemon({
        ignore: '*',
        script: configs.mainjs,
        ext: 'do_not_watch'
    })
    .on('log', function (log) {
        gutil.log(log.colour);
    })
    .on('start', function () {
        if (serverStarted) {
            setTimeout(browserSync.reload, configs.nodemon_delay);
        } else {
            browserSync.init(null, {
                proxy: 'http://localhost:3000',
                files: [configs.static_dir + 'css/*.css'],
                port: 3001,
                online: false,
                open: false
            });

            serverStarted = true;
        }
    });
});

gulp.task('test_app', function (cb) {
    var istanbul = initIstanbulHookHack() || require('gulp-istanbul'),
        hook = require('istanbul').hook,
        mocha = require('gulp-mocha');

    gulp.src(build_files.jsx.concat(build_files.js))
    .pipe(react({keepExt: true}))
    .pipe(istanbul({includeUntested: true}))
    .pipe(istanbul.hookRequire())
    .on('finish', function () {
        return gulp.src(['test/**/*.js', 'test/components/*.js*'])
        .pipe(mocha())
        .pipe(istanbul.writeReports({
            reporters: [ 'lcov', 'json', 'text', 'text-summary' ]
        }))
        .on('end', cb);
    });
});

gulp.task('develop', ['nodemon_server']);
gulp.task('lint_all', ['lint_server', 'lint_flux_js', 'lint_jsx']);
gulp.task('buildall', ['lint_all', 'build_app']);
gulp.task('default',['buildall']);
<|endoftext|>


<commit_before>// this is meant as a hack for development
// TODO: reproduce here the filter application of Camshaft

var filters = {
    category: require('./camshaft/category'),
    range: require('./camshaft/range')
};

function createFilter(filterDefinition) {
    var filterType = filterDefinition.type.toLowerCase();
    if (!filters.hasOwnProperty(filterType)) {
        throw new Error('Unknown filter type: ' + filterType);
    }
    return new filters[filterType](filterDefinition.column, filterDefinition.params);
}

function CamshaftFilters(filters) {
    this.filters = filters;
}

CamshaftFilters.prototype.sql = function(rawSql) {
  var filters = this.filters || {};
  var applyFilters = {};

  return Object.keys(filters)
      .filter(function(filterName) {
          return applyFilters.hasOwnProperty(filterName) ? applyFilters[filterName] : true;
      })
      .map(function(filterName) {
          var filterDefinition = filters[filterName];
          return createFilter(filterDefinition);
      })
      .reduce(function(sql, filter) {
          return filter.sql(sql);
      }, rawSql);
};

module.exports = CamshaftFilters;
<commit_msg>Remove comment<commit_after>var filters = {
    category: require('./camshaft/category'),
    range: require('./camshaft/range')
};

function createFilter(filterDefinition) {
    var filterType = filterDefinition.type.toLowerCase();
    if (!filters.hasOwnProperty(filterType)) {
        throw new Error('Unknown filter type: ' + filterType);
    }
    return new filters[filterType](filterDefinition.column, filterDefinition.params);
}

function CamshaftFilters(filters) {
    this.filters = filters;
}

CamshaftFilters.prototype.sql = function(rawSql) {
  var filters = this.filters || {};
  var applyFilters = {};

  return Object.keys(filters)
      .filter(function(filterName) {
          return applyFilters.hasOwnProperty(filterName) ? applyFilters[filterName] : true;
      })
      .map(function(filterName) {
          var filterDefinition = filters[filterName];
          return createFilter(filterDefinition);
      })
      .reduce(function(sql, filter) {
          return filter.sql(sql);
      }, rawSql);
};

module.exports = CamshaftFilters;
<|endoftext|>


<commit_before>var playurl="http://localhost:3000/";
var room="";
var playerName="";
var status;
var active=false;
var inqueue=true;
var gamestarted=false;
var drawbuffer=false;
var callback="?callback=?";

function Card(color,value) {

	this.color = color;
	this.value = value;
	switch(parseInt(color))
	{
		case 0:this.colortext="Red";break;
		case 1:this.colortext="Green";break;
		case 2:this.colortext="Blue";break;
		case 3:this.colortext="Yellow";break;
		case 4:this.colortext="Wild";break;
		default:this.colortext="Error";
	}
	switch(parseInt(value))
	{
		case 10:this.valuetext="";break;
		case 11:this.valuetext="+2";break;
		case 12:this.valuetext="";break;
		case 13:this.valuetext="";break;
		case 14:this.valuetext="";break;
		default:this.valuetext=value;
	}
}

Card.prototype.html = function() {
	return 	'
' +
			'
' +
			'
' +
			this.valuetext +
			'
' +
			'
' +
			'
';
}

function QueryStatus()
{

}

function QueryLobby()
{

}

$(document).ready(function() {

	$("#gamejoin").click(function(){

		active=false;
		$("#loadmsg").html("A carregar o jogo.");
		$("#lobby").hide();
		$("#loading").show();

		room="/"+$("#roomslt").val()+"/";
		room="";
		playerName=$("#name").val();
		console.log(playerName+" "+room);

		$.post(playurl+room+"lobby",{name:playerName},function(data){

				active=true;
				console.log("sucesso lobby");
				$("#loading").hide();
				if (data=="null")//json de jogo cheiro
				{
					$('#lobbyerrormsg').text("Jogo cheio. Por favor tente outro jogo.");
					$('#lobbyerrormsg').show();
				}else{
					//TODO joinar o jogo
					$("#game").show();
					console.log(data.q);
					if (data.q==false)
					{
						inqueue=false;
						QueryStatus();
					}
					else
					{
						inqueue=true;
						QueryStatus();
					}
				}
		},'json').fail(
		function(jqxhr, textStatus, error ) {
			var err = textStatus + ', ' + error;
			console.log( "lobbyRequest Failed: " + err);
			active=true;
			$("#loading").hide();
			$('#lobbyerrormsg').text("Erro a entrar no jogo. Por favor tente outra vez.");
			$('#lobbyerrormsg').show();
			$('#lobby').show();
		})/*.always(function(){
			alert("x3");
		})*/;
	});

	/*$("#gameauto").click(function(){
		if (active==true){

			$("#loadmsg").text("A carregar o jogo.");
			$("#lobby").hide();
			$("#loading").show();
			active=false;
			$.post(playurl+room,{//args
			},function(data){
					//console.log(data);
					active=false;
					if (data=="null")//json de jogo cheio
					{
						$('#lobbyerrormsg').text("Jogo cheio. Por favor tente outro jogo.");
						$('#lobbyerrormsg').show();
					}else{
						//TODO joinar o jogo
					}
			}).fail(
			function(){
				$('#lobbyerrormsg').text("Erro a entrar no jogo. Por favor tente outra vez.");
				$('#lobbyerrormsg').show();
				active=true
			});
		}
	});*/

	$("#drawcard").click(function(){
		if (active==true){

		/*
		$.post(playurl,{//args
		},function(data){
				//console.log(data);
				if (data=="null")//json de jogo cheio
				{

				}else{
					//TODO  sacar as cartas
				}
		}).fail(
		function(){

		});*/
		}
		console.log("pick a card "+active);

	});

	$(document).on('click','.card',function(event){
		if (active==true){

		}
		console.log($(this).data("color")+" "+$(this).data("value")+" "+active);
	});

	$("#readycheck").click(function(){
		if (active==true){

		/*
		$.post(playurl,{//args

		},function(data){
				//console.log(data);
				if (data=="null")//json de jogo cheio

				{

				}else{
					//TODO  sacar as cartas

				}
		}).fail(
		function(){

		});*/
		}
		console.log("readycheck "+active);

	});

	$("#skipturn").click(function(){
		if (active==true){

		/*
		$.post(playurl,{//args

		},function(data){
				//console.log(data);
				if (data=="null")//json de jogo cheio

				{

				}else{
					//TODO  sacar as cartas

				}
		}).fail(
		function(){

		});*/
		}
		console.log("skipturn"+active);

	});

	$("#acceptdraw").click(function(){
		if (active==true){

		/*
		$.post(playurl,{//args

		},function(data){
				//console.log(data);
				if (data=="null")//json de jogo cheio

				{

				}else{
					//TODO  sacar as cartas

				}
		}).fail(
		function(){

		});*/
		}
		console.log("acceptdraw "+active);

	});

	$("#exitbtn").click(function(){
		if (active==true){

		/*
		$.post(playurl,{//args

		},function(data){
				//console.log(data);
				if (data=="null")//json de jogo cheio

				{

				}else{
					//TODO  sacar as cartas

				}
		}).fail(
		function(){

		});*/
		}
		console.log("exitbtn "+active);

	});

	active=true; //ativar os campos

	/*teste*/
	/*$("#lobby").hide();
	$("#game").show();
	var c1=new Card("0","11");
	var c2=new Card("1","13");
	var c3=new Card("2","10");
	var c4=new Card("3","12");
	var c5=new Card("4","14");

	$("#cardsdiv").append(c1.html());
	$("#cardsdiv").append(c2.html());
	$("#cardsdiv").append(c3.html());
	$("#cardsdiv").append(c4.html());
	$("#cardsdiv").append(c5.html());
	$("#cardsdiv").append(c1.html());
	$("#cardsdiv").append(c2.html());
	$("#cardsdiv").append(c3.html());
	$("#cardsdiv").append(c4.html());
	$("#cardsdiv").append(c5.html());
	$("#cardsdiv").append(c1.html());
	$("#cardsdiv").append(c2.html());
	$("#cardsdiv").append(c3.html());
	$("#cardsdiv").append(c4.html());
	$("#cardsdiv").append(c5.html());*/
});

<commit_msg>coisas<commit_after>var playurl="http://localhost:3000/";
var room="";
var playerName="";
var status;
var active=false;
var inqueue=true;
var gamestarted=false;
var drawbuffer=false;
var callback="?callback=?";

function Card(color,value) {

	this.color = color;
	this.value = value;
	switch(parseInt(color))
	{
		case 0:this.colortext="Red";break;
		case 1:this.colortext="Green";break;
		case 2:this.colortext="Blue";break;
		case 3:this.colortext="Yellow";break;
		case 4:this.colortext="Wild";break;
		default:this.colortext="Error";
	}
	switch(parseInt(value))
	{
		case 10:this.valuetext="";break;
		case 11:this.valuetext="+2";break;
		case 12:this.valuetext="";break;
		case 13:this.valuetext="";break;
		case 14:this.valuetext="";break;
		default:this.valuetext=value;
	}
}

Card.prototype.html = function() {
	return 	'
' +
			'
' +
			'
' +
			this.valuetext +
			'
' +
			'
' +
			'
';
}

function QueryStatus()
{

}

function QueryLobby()
{

}

$(document).ready(function() {

	$("#gamejoin").click(function(){

		active=false;
		$("#loadmsg").html("A carregar o jogo.");
		$("#lobby").hide();
		$("#loading").show();

		room="/"+$("#roomslt").val()+"/";
		room="";
		playerName=$("#name").val();
		console.log(playerName+" "+room);

		$.post(playurl+room+"lobby",{name:playerName},function(data){

				active=true;
				console.log("sucesso lobby");
				$("#loading").hide();
				if (data=="null")//json de jogo cheiro
				{
					$('#lobbyerrormsg').text("Jogo cheio. Por favor tente outro jogo.");
					$('#lobbyerrormsg').show();
				}else{
					//TODO joinar o jogo
					$("#game").show();
					console.log(data.q);
					if (data.q==false)
					{
						inqueue=false;
						QueryStatus();
					}
					else
					{
						inqueue=true;
						QueryStatus();
					}
				}
		},'json').fail(
		function(jqxhr, textStatus, error ) {
			var err = textStatus + ', ' + error;
			console.log( "lobbyRequest Failed: " + err);
			active=true;
			$("#loading").hide();
			$('#lobbyerrormsg').text("Erro a entrar no jogo. Por favor tente outra vez.");
			$('#lobbyerrormsg').show();
			$('#lobby').show();
		})/*.always(function(){
			alert("x3");
		})*/;
	});

	/*$("#gameauto").click(function(){
		if (active==true){

			$("#loadmsg").text("A carregar o jogo.");
			$("#lobby").hide();
			$("#loading").show();
			active=false;
			$.post(playurl+room,{//args
			},function(data){
					//console.log(data);
					active=false;
					if (data=="null")//json de jogo cheio
					{
						$('#lobbyerrormsg').text("Jogo cheio. Por favor tente outro jogo.");
						$('#lobbyerrormsg').show();
					}else{
						//TODO joinar o jogo
					}
			}).fail(
			function(){
				$('#lobbyerrormsg').text("Erro a entrar no jogo. Por favor tente outra vez.");
				$('#lobbyerrormsg').show();
				active=true
			});
		}
	});*/

	$("#drawcard").click(function(){
		if (active==true){

		/*
		$.post(playurl,{//args
		},function(data){
				//console.log(data);
				if (data=="null")//json de jogo cheio
				{

				}else{
					//TODO  sacar as cartas
				}
		}).fail(
		function(){

		});*/
		}
		console.log("pick a card "+active);

	});

	$(document).on('click','.card',function(event){
		if (active==true){

		}
		console.log($(this).data("color")+" "+$(this).data("value")+" "+active);
	});

	$("#readycheck").click(function(){
		if (active==true){

		/*
		$.post(playurl,{//args

		},function(data){
				//console.log(data);
				if (data=="null")//json de jogo cheio

				{

				}else{
					//TODO  sacar as cartas

				}
		}).fail(
		function(){

		});*/
		}
		console.log("readycheck "+active);

	});

	$("#skipturn").click(function(){
		if (active==true){

		/*
		$.post(playurl,{//args

		},function(data){
				//console.log(data);
				if (data=="null")//json de jogo cheio

				{

				}else{
					//TODO  sacar as cartas

				}
		}).fail(
		function(){

		});*/
		}
		console.log("skipturn"+active);

	});

	$("#acceptdraw").click(function(){
		if (active==true){

		/*
		$.post(playurl,{//args

		},function(data){
				//console.log(data);
				if (data=="null")//json de jogo cheio

				{

				}else{
					//TODO  sacar as cartas

				}
		}).fail(
		function(){

		});*/
		}
		console.log("acceptdraw "+active);

	});

	$("#exitbtn").click(function(){
		if (active==true){

		$.ajax({type:'DELETE',url:playurl+"lobby",done:function(data){
				active=true;
				console.log("sucesso sair");
				$("#game").hide();
				$("#statusmsg").hide();
				$("#lobby").show();
				}});
		}
		console.log("exitbtn "+active);

	});

	active=true; //ativar os campos

	/*teste*/
	/*$("#lobby").hide();
	$("#game").show();
	var c1=new Card("0","11");
	var c2=new Card("1","13");
	var c3=new Card("2","10");
	var c4=new Card("3","12");
	var c5=new Card("4","14");

	$("#cardsdiv").append(c1.html());
	$("#cardsdiv").append(c2.html());
	$("#cardsdiv").append(c3.html());
	$("#cardsdiv").append(c4.html());
	$("#cardsdiv").append(c5.html());
	$("#cardsdiv").append(c1.html());
	$("#cardsdiv").append(c2.html());
	$("#cardsdiv").append(c3.html());
	$("#cardsdiv").append(c4.html());
	$("#cardsdiv").append(c5.html());
	$("#cardsdiv").append(c1.html());
	$("#cardsdiv").append(c2.html());
	$("#cardsdiv").append(c3.html());
	$("#cardsdiv").append(c4.html());
	$("#cardsdiv").append(c5.html());*/
});

<|endoftext|>


<commit_before>
/*!
 * Express - Server
 * Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>
 * MIT Licensed
 */

/**
 * Module dependencies.
 */

var url = require('url'),
    view = require('./view'),
    connect = require('connect'),
    utils = require('connect/utils'),
    queryString = require('querystring'),
    router = require('connect/middleware/router');

/**
 * Initialize a new `Server` with optional `middleware`.
 *
 * @param {Array} middleware
 * @api public
 */

var Server = exports = module.exports = function Server(middleware){
    var self = this;
    this.config = {};
    this.settings = {};
    this.redirects = {};
    this.viewHelpers = {};
    this.dynamicViewHelpers = {};
    this.errorHandlers = [];
    connect.Server.call(this, middleware || []);

    // Default "home" to /
    this.set('home', '/');

    // DEPRECATED: remove in 1.0
    if (process.env.EXPRESS_ENV) {
      process.env.NODE_ENV = process.env.EXPRESS_ENV;
      console.warn('\x1b[33mWarning\x1b[0m: EXPRESS_ENV is deprecated, use NODE_ENV.');
    }

    // Set "env" to NODE_ENV
    this.set('env', process.env.NODE_ENV);

    // Expose objects to each other
    this.use(function(req, res, next){
        req.query = {};
        res.headers = {};
        req.app = res.app = self;
        req.res = res;
        res.req = req;
        req.next = next;
        // Assign req.params.get
        if (req.url.indexOf('?') > 0) {
            var query = url.parse(req.url).query;
            req.query = queryString.parse(query);
        }
        next();
    });

    // Use router, expose as app.get(), etc
    var fn = router(function(app){ self.routes = app; });
    this.__defineGetter__('router', function(){
        this.__usedRouter = true;
        return fn;
    });
};

/**
 * Inherit from `connect.Server`.
 */

Server.prototype.__proto__ = connect.Server.prototype;

/**
 * Proxy in order to register error handlers.
 */

Server.prototype.listen = function(){
    this.registerErrorHandlers();
    connect.Server.prototype.listen.apply(this, arguments);
};

/**
 * Proxy in order to register error handlers.
 */

Server.prototype.listenFD = function(){
    this.registerErrorHandlers();
    connect.Server.prototype.listenFD.apply(this, arguments);
};

/**
 * Register error handlers. This is automatically
 * called from within `Server#listen()` and `Server#listenFD()`.
 *
 * @return {Server} for chaining
 * @api public
 */

Server.prototype.registerErrorHandlers = function(){
    this.errorHandlers.forEach(function(fn){
        this.use(function(err, req, res, next){
            fn.apply(this, arguments);
        });
    }, this);
    return this;
};

/**
 * Proxy `connect.Server#use()` to apply settings to
 * mounted applications.
 *
 * @param {String|Function|Server} route
 * @param {Function|Server} middleware
 * @return {Server} for chaining
 * @api public
 */

Server.prototype.use = function(route, middleware){
    if (typeof route !== 'string') {
        middleware = route, route = '/';
    }

    connect.Server.prototype.use.call(this, route, middleware);

    // Mounted an app
    if (middleware instanceof Server) {
        // Home is /:route/:home
        var app = middleware,
            home = app.set('home');
        if (home === '/') home = '';
        app.set('home', (app.route || '') + home);
        app.parent = this;
        // Mounted hook
        if (app.__mounted) app.__mounted.call(app, this);
    }

    return this;
};

/**
 * Assign a callback `fn` which is called
 * when this `Server` is passed to `Server#use()`.
 *
 * Examples:
 *
 *    var app = express.createServer(),
 *        blog = express.createServer();
 *
 *    blog.mounted(function(parent){
 *        // parent is app
 *        // "this" is blog
 *    });
 *
 *    app.use(blog);
 *
 * @param {Function} fn
 * @return {Server} for chaining
 * @api public
 */

Server.prototype.mounted = function(fn){
    this.__mounted = fn;
    return this;
};

/**
 * See: view.register.
 *
 * @return {Server} for chaining
 * @api public
 */

Server.prototype.register = function(){
    view.register.apply(this, arguments);
    return this;
};

/**
 * Register the given view helpers `obj`. This method
 * can be called several times to apply additional helpers.
 *
 * @param {Object} obj
 * @return {Server} for chaining
 * @api public
 */

Server.prototype.helpers = function(obj){
    utils.merge(this.viewHelpers, obj);
    return this;
};

/**
 * Register the given dynamic view helpers `obj`. This method
 * can be called several times to apply additional helpers.
 *
 * @param {Object} obj
 * @return {Server} for chaining
 * @api public
 */

Server.prototype.dynamicHelpers = function(obj){
    utils.merge(this.dynamicViewHelpers, obj);
    return this;
};

/**
 * Assign a custom exception handler callback `fn`.
 * These handlers are always _last_ in the middleware stack.
 *
 * @param {Function} fn
 * @return {Server} for chaining
 * @api public
 */

Server.prototype.error = function(fn){
    this.errorHandlers.push(fn);
    return this;
};

/**
 * Assign `setting` to `val`, or return `setting`'s value.
 * Mounted servers inherit their parent server's settings.
 *
 * @param {String} setting
 * @param {String} val
 * @return {Server|Mixed} for chaining, or the setting value
 * @api public
 */

Server.prototype.set = function(setting, val){
    if (val === undefined) {
        if (this.settings.hasOwnProperty(setting)) {
            return this.settings[setting];
        } else if (this.parent) {
            return this.parent.set(setting);
        }
    } else {
        this.settings[setting] = val;
        return this;
    }
};

/**
 * Enable `setting`.
 *
 * @param {String} setting
 * @return {Server} for chaining
 * @api public
 */

Server.prototype.enable = function(setting){
    return this.set(setting, true);
};

/**
 * Disable `setting`.
 *
 * @param {String} setting
 * @return {Server} for chaining
 * @api public
 */

Server.prototype.disable = function(setting){
    return this.set(setting, false);
};

/**
 * Redirect `key` to `url`.
 *
 * @param {String} key
 * @param {String} url
 * @return {Server} for chaining
 * @api public
 */

Server.prototype.redirect = function(key, url){
    this.redirects[key] = url;
    return this;
};

/**
 * Configure callback for the given `env`.
 *
 * @param {String} env
 * @param {Function} fn
 * @return {Server} for chaining
 * @api public
 */

Server.prototype.configure = function(env, fn){
    if (typeof env === 'function') {
        fn = env, env = 'all';
    }
    if (env === 'all' || this.set('env') === env) {
        fn.call(this);
    }
    return this;
};

// Generate routing methods

(function(method){
    Server.prototype[method] = function(path, fn){
        var self = this;

        // Ensure router is mounted
        if (!this.__usedRouter) {
            this.use(this.router);
        }

        // Route specific middleware support
        if (arguments.length > 2) {
            var args = Array.prototype.slice.call(arguments, 1);
            fn = args.pop();
            (function stack(middleware){
                middleware.forEach(function(fn){
                    if (Array.isArray(fn)) {
                        stack(fn);
                    } else {
                        self[method](path, fn);
                    }
                });
            })(args);
        }

        // Generate the route
        this.routes[method](path, fn);
        return this;
    };
    return arguments.callee;
})('get')('post')('put')('del');
<commit_msg>Added support for swappable querystring parsers<commit_after>
/*!
 * Express - Server
 * Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>
 * MIT Licensed
 */

/**
 * Module dependencies.
 */

var url = require('url'),
    view = require('./view'),
    connect = require('connect'),
    utils = require('connect/utils'),
    queryString = require('querystring'),
    router = require('connect/middleware/router');

/**
 * Initialize a new `Server` with optional `middleware`.
 *
 * @param {Array} middleware
 * @api public
 */

var Server = exports = module.exports = function Server(middleware){
    var self = this;
    this.config = {};
    this.settings = {};
    this.redirects = {};
    this.viewHelpers = {};
    this.dynamicViewHelpers = {};
    this.errorHandlers = [];
    connect.Server.call(this, middleware || []);

    // Default "home" to /
    this.set('home', '/');

    // DEPRECATED: remove in 1.0
    if (process.env.EXPRESS_ENV) {
      process.env.NODE_ENV = process.env.EXPRESS_ENV;
      console.warn('\x1b[33mWarning\x1b[0m: EXPRESS_ENV is deprecated, use NODE_ENV.');
    }

    // Set "env" to NODE_ENV
    this.set('env', process.env.NODE_ENV);

    // Expose objects to each other
    this.use(function(req, res, next){
        req.query = {};
        res.headers = {};
        req.app = res.app = self;
        req.res = res;
        res.req = req;
        req.next = next;
        // Assign req.params.get
        if (req.url.indexOf('?') > 0) {
            var query = url.parse(req.url).query;
            req.query = exports.parseQueryString(query);
        }
        next();
    });

    // Use router, expose as app.get(), etc
    var fn = router(function(app){ self.routes = app; });
    this.__defineGetter__('router', function(){
        this.__usedRouter = true;
        return fn;
    });
};

/**
 * Inherit from `connect.Server`.
 */

Server.prototype.__proto__ = connect.Server.prototype;

/**
 * Support swappable querystring parsers.
 */

exports.parseQueryString = queryString.parse;

/**
 * Proxy in order to register error handlers.
 */

Server.prototype.listen = function(){
    this.registerErrorHandlers();
    connect.Server.prototype.listen.apply(this, arguments);
};

/**
 * Proxy in order to register error handlers.
 */

Server.prototype.listenFD = function(){
    this.registerErrorHandlers();
    connect.Server.prototype.listenFD.apply(this, arguments);
};

/**
 * Register error handlers. This is automatically
 * called from within `Server#listen()` and `Server#listenFD()`.
 *
 * @return {Server} for chaining
 * @api public
 */

Server.prototype.registerErrorHandlers = function(){
    this.errorHandlers.forEach(function(fn){
        this.use(function(err, req, res, next){
            fn.apply(this, arguments);
        });
    }, this);
    return this;
};

/**
 * Proxy `connect.Server#use()` to apply settings to
 * mounted applications.
 *
 * @param {String|Function|Server} route
 * @param {Function|Server} middleware
 * @return {Server} for chaining
 * @api public
 */

Server.prototype.use = function(route, middleware){
    if (typeof route !== 'string') {
        middleware = route, route = '/';
    }

    connect.Server.prototype.use.call(this, route, middleware);

    // Mounted an app
    if (middleware instanceof Server) {
        // Home is /:route/:home
        var app = middleware,
            home = app.set('home');
        if (home === '/') home = '';
        app.set('home', (app.route || '') + home);
        app.parent = this;
        // Mounted hook
        if (app.__mounted) app.__mounted.call(app, this);
    }

    return this;
};

/**
 * Assign a callback `fn` which is called
 * when this `Server` is passed to `Server#use()`.
 *
 * Examples:
 *
 *    var app = express.createServer(),
 *        blog = express.createServer();
 *
 *    blog.mounted(function(parent){
 *        // parent is app
 *        // "this" is blog
 *    });
 *
 *    app.use(blog);
 *
 * @param {Function} fn
 * @return {Server} for chaining
 * @api public
 */

Server.prototype.mounted = function(fn){
    this.__mounted = fn;
    return this;
};

/**
 * See: view.register.
 *
 * @return {Server} for chaining
 * @api public
 */

Server.prototype.register = function(){
    view.register.apply(this, arguments);
    return this;
};

/**
 * Register the given view helpers `obj`. This method
 * can be called several times to apply additional helpers.
 *
 * @param {Object} obj
 * @return {Server} for chaining
 * @api public
 */

Server.prototype.helpers = function(obj){
    utils.merge(this.viewHelpers, obj);
    return this;
};

/**
 * Register the given dynamic view helpers `obj`. This method
 * can be called several times to apply additional helpers.
 *
 * @param {Object} obj
 * @return {Server} for chaining
 * @api public
 */

Server.prototype.dynamicHelpers = function(obj){
    utils.merge(this.dynamicViewHelpers, obj);
    return this;
};

/**
 * Assign a custom exception handler callback `fn`.
 * These handlers are always _last_ in the middleware stack.
 *
 * @param {Function} fn
 * @return {Server} for chaining
 * @api public
 */

Server.prototype.error = function(fn){
    this.errorHandlers.push(fn);
    return this;
};

/**
 * Assign `setting` to `val`, or return `setting`'s value.
 * Mounted servers inherit their parent server's settings.
 *
 * @param {String} setting
 * @param {String} val
 * @return {Server|Mixed} for chaining, or the setting value
 * @api public
 */

Server.prototype.set = function(setting, val){
    if (val === undefined) {
        if (this.settings.hasOwnProperty(setting)) {
            return this.settings[setting];
        } else if (this.parent) {
            return this.parent.set(setting);
        }
    } else {
        this.settings[setting] = val;
        return this;
    }
};

/**
 * Enable `setting`.
 *
 * @param {String} setting
 * @return {Server} for chaining
 * @api public
 */

Server.prototype.enable = function(setting){
    return this.set(setting, true);
};

/**
 * Disable `setting`.
 *
 * @param {String} setting
 * @return {Server} for chaining
 * @api public
 */

Server.prototype.disable = function(setting){
    return this.set(setting, false);
};

/**
 * Redirect `key` to `url`.
 *
 * @param {String} key
 * @param {String} url
 * @return {Server} for chaining
 * @api public
 */

Server.prototype.redirect = function(key, url){
    this.redirects[key] = url;
    return this;
};

/**
 * Configure callback for the given `env`.
 *
 * @param {String} env
 * @param {Function} fn
 * @return {Server} for chaining
 * @api public
 */

Server.prototype.configure = function(env, fn){
    if (typeof env === 'function') {
        fn = env, env = 'all';
    }
    if (env === 'all' || this.set('env') === env) {
        fn.call(this);
    }
    return this;
};

// Generate routing methods

(function(method){
    Server.prototype[method] = function(path, fn){
        var self = this;

        // Ensure router is mounted
        if (!this.__usedRouter) {
            this.use(this.router);
        }

        // Route specific middleware support
        if (arguments.length > 2) {
            var args = Array.prototype.slice.call(arguments, 1);
            fn = args.pop();
            (function stack(middleware){
                middleware.forEach(function(fn){
                    if (Array.isArray(fn)) {
                        stack(fn);
                    } else {
                        self[method](path, fn);
                    }
                });
            })(args);
        }

        // Generate the route
        this.routes[method](path, fn);
        return this;
    };
    return arguments.callee;
})('get')('post')('put')('del');
<|endoftext|>


<commit_before>
// Ensure the global scope objects are created if they don't already exist.
if (!window.rhubarb){
    window.rhubarb = {};
}

if (!window.rhubarb.validation){
    window.rhubarb.validation = {};
}

if (!window.rhubarb.validation.common){
    window.rhubarb.validation.common = {};
}

if (!window.rhubarb.validation.sources){
    window.rhubarb.validation.sources = {};
}

if (!window.rhubarb.validation.triggers){
    window.rhubarb.validation.triggers = {};
}

if (!window.validation){
    // Provide a quick global alias to validation if that is possible
    window.validation = window.rhubarb.validation;
}

window.rhubarb.validation.states = {
    "notTested": 0,
    'valid': 1,
    'checking': 2,
    'invalid': 3
};

window.rhubarb.validation.validator = function(){

    this._checks = [];
    this._triggers = [];
    this._source = false;
    this._targetElement = false;
    this._isRequired = false;
    this._hasValue = false;
    this._messageFormatter = function(errors){
        return "
" + errors + "
";
    };

    this.requiredMessage = "A value is required here.";
    this.state = window.rhubarb.validation.states.nottested;
    this.errorMessages = [];

    var self = this;

    this.require = function(message){
        self._isRequired = true;

        if (message){
            self.requiredMessage = message;
        }

        return self;
    };

    this.check = function(callback){
        self._checks.push(callback);

        return self;
    };

    this.setMessageFormatter = function(formatterCallback){
        self._messageFormatter = formatterCallback;
    };

    this.addTrigger = function(broker){

        // Try and upscale any strings passed to an HTML element
        try {
            broker = this.makeHtmlElement(broker);
        } catch (error) {
            throw new Error("A string '" + broker + "' passed to addTrigger was not a valid HTML Element ID.");
        }

        if (broker instanceof HTMLElement){
            broker = window.rhubarb.validation.triggers.onHtmlElementValueChanged(broker);
        }

        self._triggers.push(broker);

        broker.trigger = function(value){
            self.validate();
        };

        return self;
    };

    this.setSource = function(source){
        try {
            self._source = this.makeHtmlElementValueCallback(source);
        } catch (error){
            if (error.message == "string" ){
                throw new Error("A string '" + source + "' passed to setSource was not a valid HTML Element ID." );
            } else {
                throw new Error("An element passed to setSource was not a valid HTML input element." );
            }
        }

        return self;
    };

    this.makeHtmlElement = function(nameOrElement){
        if (typeof nameOrElement == "string"){
            nameOrElement = document.getElementById(nameOrElement);

            if (!nameOrElement){
                throw new Error(nameOrElement + " is not an HTML element" );
            }
        }

        return nameOrElement;
    };

    this.makeHtmlElementValueCallback = function(elementOrCallback){

        try {
            elementOrCallback = this.makeHtmlElement(elementOrCallback);
        } catch(error){
            throw new Error("string");
        }

        if (elementOrCallback instanceof HTMLElement){
            if ( typeof elementOrCallback.value == undefined ) {
                throw new Error("element");
            }

            var element = elementOrCallback;
            elementOrCallback = function () {
                return element.value;
            };
        }

        return elementOrCallback;
    };

    this.setTargetElement = function(targetElement){

        // Try and upscale any strings passed to an HTML element
        try {
            targetElement = this.makeHtmlElement(targetElement);
        } catch (error) {
            throw new Error("A string '" + targetElement + "' passed to setTargetElement was not a valid HTML Element ID.");
        }

        self._targetElement = targetElement;

        return self;
    };

    this.validate = function(successCallback, failureCallback){

        var value = (self._source) ? self._source() : false;

        if (value == "0"){
            value = false;
        }

        self._hasValue = !!value;

        // Update our status to checking (this might be used for slow validations)
        self.state = window.rhubarb.validation.states.checking;
        self.updateClasses();

        // Reset our error messages in case this is a second attempt
        self.errorMessages = [];

        var validationCompleted = function() {

            for (var i = 0; i < self._checks.length; i++) {
                var check = self._checks[i];
                if (!check.checked){
                    // Not all the checks are complete - a later callback will come back here
                    // when that happens. For now we can't update the status yet.
                    return;
                }
            }

            if (self._isRequired && !self._hasValue){
                self.errorMessages.push(self.requiredMessage);
            }

            if (self.errorMessages.length > 0){
                self.state = window.rhubarb.validation.states.invalid;
                self.updateClasses();

                if (failureCallback){
                    failureCallback(self.errorMessages);
                }
            } else {
                self.state = window.rhubarb.validation.states.valid;
                self.updateClasses();

                if (successCallback){
                    successCallback();
                }
            }
        };

        if ( self._checks.length > 0 ) {
            // Do the checks only if we have checks to do
            for (var i = 0; i < self._checks.length; i++) {
                var check = self._checks[i];
                check.checked = false;

                check(
                    value,
                    function () {
                        // On success
                        this.checked = true;
                        validationCompleted();
                    }.bind(check),
                    function (error) {
                        // The validation failed - an Error exception should have been thrown.
                        this.checked = true;
                        if (Array.isArray(error)) {
                            for (var m = 0; m < error.length; m++) {
                                self.errorMessages.push(error[m]);
                            }
                        } else {
                            self.errorMessages.push(error);
                        }
                        validationCompleted();
                    }.bind(check)
                );
            }
        } else {
            // Otherwise just evaluation completion (essentially allowing for required status only)
            validationCompleted();
        }

        return self.state == window.rhubarb.validation.states.valid;
    };

    this.updateClasses = function(){
        if (!self._targetElement){
            // If we don't have a target element we can't update any CSS classes.
            return;
        }

        self._targetElement.classList.remove("is-valid", "is-checking", "is-invalid", "is-not-tested", "is-required", "is-missing");

        switch(self.state){
            case window.rhubarb.validation.states.valid:
                self._targetElement.classList.add("is-valid");
                break;
            case window.rhubarb.validation.states.checking:
                self._targetElement.classList.add("is-checking");
                break;
            case window.rhubarb.validation.states.invalid:
                self._targetElement.classList.add("is-invalid");
                break;
            case window.rhubarb.validation.states.notTested:
                self._targetElement.classList.add("is-not-tested");
                break;
        }

        if (self._isRequired){
            self._targetElement.classList.add("is-required");

            if (!self._hasValue){
                self._targetElement.classList.add("is-missing");
            }
        }

        // Try and find an error container and update the message with our error messages.
        var errorMessage = self._targetElement.querySelector(".js-validation-message");

        if (errorMessage){
            if( self.errorMessages.length > 0){
                errorMessage.innerHTML = self._messageFormatter(self.errorMessages);
            } else {
                errorMessage.innerHTML = "";
            }
        }
    }
};

window.rhubarb.validation.sources.fromHtmlElement = function(htmlElement){
    return function(){
        return htmlElement.value;
    };
};

window.rhubarb.validation.triggers.onHtmlElementValueChanged = function(htmlElement){
    var broker = {};
    broker.trigger = function(){};

    htmlElement.addEventListener('change', function(){
        broker.trigger();
    });

    return broker;
};

// Define our standard validation routines. You can of course create your own. The validation framework requires
// a callback for each validation routine. Our pattern here is to define a function that **returns a callback**.
// This allows our outer function to define arguments that are then presented to the programmer in any good IDE.
window.rhubarb.validation.common.lengthGreaterThan = function(greaterThan, orEqual){
  return function (value, successCallback, failedCallback){
      var compareTo = (orEqual) ? greaterThan - 1 : greaterThan;
      if (value.length > greaterThan){
          failedCallback("The length must less than " + (orEqual ? " (or equal to) " : "" ) + greaterThan);
          return;
      }

      successCallback();
  };
};

window.rhubarb.validation.common.isEmailAddress = function(){
    return function(value, successCallback, failedCallback){
        if (value.indexOf("@") == -1){
            failedCallback("Email addresses must contain a '@' character");
            return;
        }

        successCallback();
    }
};

window.rhubarb.validation.common.matches = function(matchSourceCallback){
  return function(value, successCallback, failedCallback){
      var compareTo = matchSourceCallback();

      if (compareTo != value){
          failedCallback("The values must match");
          return;
      }

      successCallback();
  };
};

window.rhubarb.validation.common.allValid = function(validations) {
    return function (value, successCallback, failedCallback) {
        var errors = [];
        var validationsToCheck = validations;

        var checkAll = function() {

            for (var i = 0; i < validationsToCheck.length; i++) {
                var validationToCheck = validationsToCheck[i];

                if (validationToCheck.state != window.rhubarb.validation.states.checking) {
                    validationToCheck.validate(function(){
                    }.bind(validationToCheck), function(errorMessages){
                        for( var m = 0; m <errorMessages.length; m++){
                            errors.push(errorMessages[m]);
                        }
                    }.bind(validationToCheck));
                }
            }

            for (var j = 0; i < validationsToCheck.length; i++) {
                var validationToCheckOn = validationsToCheck[i];
                if (validationToCheckOn.state == window.rhubarb.validation.states.checking){
                    setTimeout(checkAll, 200);
                    return;
                }
            }

            if (errors.length > 1) {
                failedCallback(errors);
                return;
            }

            if (errors.length > 0) {
                failedCallback(errors);
                return;
            }

            successCallback();
        };

        checkAll();
    };
};<commit_msg>Added fuller email validation<commit_after>
// Ensure the global scope objects are created if they don't already exist.
if (!window.rhubarb){
    window.rhubarb = {};
}

if (!window.rhubarb.validation){
    window.rhubarb.validation = {};
}

if (!window.rhubarb.validation.common){
    window.rhubarb.validation.common = {};
}

if (!window.rhubarb.validation.sources){
    window.rhubarb.validation.sources = {};
}

if (!window.rhubarb.validation.triggers){
    window.rhubarb.validation.triggers = {};
}

if (!window.validation){
    // Provide a quick global alias to validation if that is possible
    window.validation = window.rhubarb.validation;
}

window.rhubarb.validation.states = {
    "notTested": 0,
    'valid': 1,
    'checking': 2,
    'invalid': 3
};

window.rhubarb.validation.validator = function(){

    this._checks = [];
    this._triggers = [];
    this._source = false;
    this._targetElement = false;
    this._isRequired = false;
    this._hasValue = false;
    this._messageFormatter = function(errors){
        return "
" + errors + "
";
    };

    this.requiredMessage = "A value is required here.";
    this.state = window.rhubarb.validation.states.nottested;
    this.errorMessages = [];

    var self = this;

    this.require = function(message){
        self._isRequired = true;

        if (message){
            self.requiredMessage = message;
        }

        return self;
    };

    this.check = function(callback){
        self._checks.push(callback);

        return self;
    };

    this.setMessageFormatter = function(formatterCallback){
        self._messageFormatter = formatterCallback;
    };

    this.addTrigger = function(broker){

        // Try and upscale any strings passed to an HTML element
        try {
            broker = this.makeHtmlElement(broker);
        } catch (error) {
            throw new Error("A string '" + broker + "' passed to addTrigger was not a valid HTML Element ID.");
        }

        if (broker instanceof HTMLElement){
            broker = window.rhubarb.validation.triggers.onHtmlElementValueChanged(broker);
        }

        self._triggers.push(broker);

        broker.trigger = function(value){
            self.validate();
        };

        return self;
    };

    this.setSource = function(source){
        try {
            self._source = this.makeHtmlElementValueCallback(source);
        } catch (error){
            if (error.message == "string" ){
                throw new Error("A string '" + source + "' passed to setSource was not a valid HTML Element ID." );
            } else {
                throw new Error("An element passed to setSource was not a valid HTML input element." );
            }
        }

        return self;
    };

    this.makeHtmlElement = function(nameOrElement){
        if (typeof nameOrElement == "string"){
            nameOrElement = document.getElementById(nameOrElement);

            if (!nameOrElement){
                throw new Error(nameOrElement + " is not an HTML element" );
            }
        }

        return nameOrElement;
    };

    this.makeHtmlElementValueCallback = function(elementOrCallback){

        try {
            elementOrCallback = this.makeHtmlElement(elementOrCallback);
        } catch(error){
            throw new Error("string");
        }

        if (elementOrCallback instanceof HTMLElement){
            if ( typeof elementOrCallback.value == undefined ) {
                throw new Error("element");
            }

            var element = elementOrCallback;
            elementOrCallback = function () {
                return element.value;
            };
        }

        return elementOrCallback;
    };

    this.setTargetElement = function(targetElement){

        // Try and upscale any strings passed to an HTML element
        try {
            targetElement = this.makeHtmlElement(targetElement);
        } catch (error) {
            throw new Error("A string '" + targetElement + "' passed to setTargetElement was not a valid HTML Element ID.");
        }

        self._targetElement = targetElement;

        return self;
    };

    this.validate = function(successCallback, failureCallback){

        var value = (self._source) ? self._source() : false;

        if (value == "0"){
            value = false;
        }

        self._hasValue = !!value;

        // Update our status to checking (this might be used for slow validations)
        self.state = window.rhubarb.validation.states.checking;
        self.updateClasses();

        // Reset our error messages in case this is a second attempt
        self.errorMessages = [];

        var validationCompleted = function() {

            for (var i = 0; i < self._checks.length; i++) {
                var check = self._checks[i];
                if (!check.checked){
                    // Not all the checks are complete - a later callback will come back here
                    // when that happens. For now we can't update the status yet.
                    return;
                }
            }

            if (self._isRequired && !self._hasValue){
                self.errorMessages.push(self.requiredMessage);
            }

            if (self.errorMessages.length > 0){
                self.state = window.rhubarb.validation.states.invalid;
                self.updateClasses();

                if (failureCallback){
                    failureCallback(self.errorMessages);
                }
            } else {
                self.state = window.rhubarb.validation.states.valid;
                self.updateClasses();

                if (successCallback){
                    successCallback();
                }
            }
        };

        if ( self._checks.length > 0 ) {
            // Do the checks only if we have checks to do
            for (var i = 0; i < self._checks.length; i++) {
                var check = self._checks[i];
                check.checked = false;

                check(
                    value,
                    function () {
                        // On success
                        this.checked = true;
                        validationCompleted();
                    }.bind(check),
                    function (error) {
                        // The validation failed - an Error exception should have been thrown.
                        this.checked = true;
                        if (Array.isArray(error)) {
                            for (var m = 0; m < error.length; m++) {
                                self.errorMessages.push(error[m]);
                            }
                        } else {
                            self.errorMessages.push(error);
                        }
                        validationCompleted();
                    }.bind(check)
                );
            }
        } else {
            // Otherwise just evaluation completion (essentially allowing for required status only)
            validationCompleted();
        }

        return self.state == window.rhubarb.validation.states.valid;
    };

    this.updateClasses = function(){
        if (!self._targetElement){
            // If we don't have a target element we can't update any CSS classes.
            return;
        }

        self._targetElement.classList.remove("is-valid", "is-checking", "is-invalid", "is-not-tested", "is-required", "is-missing");

        switch(self.state){
            case window.rhubarb.validation.states.valid:
                self._targetElement.classList.add("is-valid");
                break;
            case window.rhubarb.validation.states.checking:
                self._targetElement.classList.add("is-checking");
                break;
            case window.rhubarb.validation.states.invalid:
                self._targetElement.classList.add("is-invalid");
                break;
            case window.rhubarb.validation.states.notTested:
                self._targetElement.classList.add("is-not-tested");
                break;
        }

        if (self._isRequired){
            self._targetElement.classList.add("is-required");

            if (!self._hasValue){
                self._targetElement.classList.add("is-missing");
            }
        }

        // Try and find an error container and update the message with our error messages.
        var errorMessage = self._targetElement.querySelector(".js-validation-message");

        if (errorMessage){
            if( self.errorMessages.length > 0){
                errorMessage.innerHTML = self._messageFormatter(self.errorMessages);
            } else {
                errorMessage.innerHTML = "";
            }
        }
    }
};

window.rhubarb.validation.sources.fromHtmlElement = function(htmlElement){
    return function(){
        return htmlElement.value;
    };
};

window.rhubarb.validation.triggers.onHtmlElementValueChanged = function(htmlElement){
    var broker = {};
    broker.trigger = function(){};

    htmlElement.addEventListener('change', function(){
        broker.trigger();
    });

    return broker;
};

// Define our standard validation routines. You can of course create your own. The validation framework requires
// a callback for each validation routine. Our pattern here is to define a function that **returns a callback**.
// This allows our outer function to define arguments that are then presented to the programmer in any good IDE.
window.rhubarb.validation.common.lengthGreaterThan = function(greaterThan, orEqual){
  return function (value, successCallback, failedCallback){
      var compareTo = (orEqual) ? greaterThan - 1 : greaterThan;
      if (value.length > greaterThan){
          failedCallback("The length must less than " + (orEqual ? " (or equal to) " : "" ) + greaterThan);
          return;
      }

      successCallback();
  };
};

window.rhubarb.validation.common.isEmailAddress = function(){
    return function(value, successCallback, failedCallback){
        if (value.indexOf("@") == -1){
            failedCallback("Email addresses must contain a '@' character");
            return;
        }

        var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        if (!re.test(value)){
            failedCallback(value + " does not look like an email address");
            return;
        }

        successCallback();
    }
};

window.rhubarb.validation.common.matches = function(matchSourceCallback){
  return function(value, successCallback, failedCallback){
      var compareTo = matchSourceCallback();

      if (compareTo != value){
          failedCallback("The values must match");
          return;
      }

      successCallback();
  };
};

window.rhubarb.validation.common.allValid = function(validations) {
    return function (value, successCallback, failedCallback) {
        var errors = [];
        var validationsToCheck = validations;

        var checkAll = function() {

            for (var i = 0; i < validationsToCheck.length; i++) {
                var validationToCheck = validationsToCheck[i];

                if (validationToCheck.state != window.rhubarb.validation.states.checking) {
                    validationToCheck.validate(function(){
                    }.bind(validationToCheck), function(errorMessages){
                        for( var m = 0; m <errorMessages.length; m++){
                            errors.push(errorMessages[m]);
                        }
                    }.bind(validationToCheck));
                }
            }

            for (var j = 0; i < validationsToCheck.length; i++) {
                var validationToCheckOn = validationsToCheck[i];
                if (validationToCheckOn.state == window.rhubarb.validation.states.checking){
                    setTimeout(checkAll, 200);
                    return;
                }
            }

            if (errors.length > 1) {
                failedCallback(errors);
                return;
            }

            if (errors.length > 0) {
                failedCallback(errors);
                return;
            }

            successCallback();
        };

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


<commit_before>/*
 * Licensed to Cloudkick, Inc ('Cloudkick') under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * Cloudkick licenses this file to You 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.
 */

var sys = require('sys');
var fs = require('fs');

var sprintf = require('extern/sprintf').sprintf;

var dotfiles = require('util/client_dotfiles');
var terminal = require('util/terminal');

exports.config = {
  short_description: 'Print a list of saved remotes',
  long_description: 'Print a list of saved remotes.',
  required_arguments: [],
  optional_arguments: []
};

exports.handle_command = function(args) {
  dotfiles.get_remotes(function(err, remotes) {
    var remote, is_default;

    if (err) {
      sys.puts('Failed to read remotes file');
      return;
    }

    if (Object.keys(remotes).length === 0) {
      sys.puts('No remotes exist yet. You can add one by calling "remotes add" command');
      return;
    }

    sys.puts('Available remotes:\n');
    for (var remote_name in remotes) {
      if (remotes.hasOwnProperty(remote_name)) {
        remote = remotes[remote_name];

        is_default = (remote.is_default === true) ? '(default)' : '';
        sys.puts(sprintf('Name: %s %s', remote_name, is_default));
        sys.puts(sprintf('URL: %s', remote.url));
        sys.puts(sprintf('Certificate fingerprint: %s\n', remote.fingerprint ? remote.fingerprint : '[none]'));
      }
    }
  });
};
<commit_msg>modify 'remotes list' to separate project/global<commit_after>/*
 * Licensed to Cloudkick, Inc ('Cloudkick') under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * Cloudkick licenses this file to You 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.
 */

var sys = require('sys');
var fs = require('fs');

var sprintf = require('extern/sprintf').sprintf;
var async = require('extern/async');

var dotfiles = require('util/client_dotfiles');
var terminal = require('util/terminal');

exports.config = {
  short_description: 'Print a list of saved remotes',
  long_description: 'Print a list of saved remotes.',
  required_arguments: [],
  optional_arguments: []
};

function print_remote_list(head, remotes) {
  var name, remote, default_str, i;
  var names = Object.keys(remotes);
  names = names.sort();

  sys.puts(head);
  for (i = 0; i < names.length; i++) {
    name = names[i];
    if (remotes.hasOwnProperty(name)) {
      remote = remotes[name];
      if (remote.is_default) {
        default_str = '';
      }
      else {
        default_str = ' ';
      }

      sys.puts(sprintf('  %s%s', name, (remote.is_default ? ' (default)' : '')));
      sys.puts(sprintf('    %s', remote.url));
      if (remote.fingerprint) {
        sys.puts(sprintf('    %s', remote.fingerprint));
      }
    }
  }
}

var PROJECT_HEADER = 'Project Remotes (override globals):';
var GLOBAL_HEADER = 'Global Remotes:';

exports.handle_command = function(args) {
  var had_remotes = false;

  async.series([
    function(callback) {
      dotfiles.get_local_remotes(function(err, remotes) {
        if (!err && Object.keys(remotes).length > 0) {
          had_remotes = true;
          print_remote_list(PROJECT_HEADER, remotes);
        }
        callback(err);
      });
    },

    function(callback) {
      dotfiles.get_global_remotes(function(err, remotes) {
        if (!err && Object.keys(remotes).length > 0) {
          if (had_remotes) {
            sys.puts('');
          }
          had_remotes = true;
          print_remote_list(GLOBAL_HEADER, remotes);
        }
        callback(err);
      });
    }
  ],
  function(err) {
    if (err) {
      sys.puts('Error: ' + err.message);
    }
    else if (!had_remotes) {
      sys.puts('No remotes exist yet. You can add one by calling "remotes add" command');
    }
  });
};
<|endoftext|>


<commit_before>import eslint from 'eslint';
import globby from 'globby';
import Logger from './logger';

export default function lint() {

  const engine = new eslint.CLIEngine({
    useEslintrc: true
  });

  return new Promise((resolve, reject) => {

    globby(['**/**.js', '!node_modules/**', '!bower_components/**', '!dist/**']).then( paths => {
    // globby(['*.js']).then( paths => {

      var report = engine.executeOnFiles(paths.slice(2));
      var formatter = engine.getFormatter();

      if (report.errorCount || report.warningCount) {
        Logger.failed(`eslint`);
        Logger.simple(`${formatter(report.results)}`);
        reject();
      }else {
        Logger.ok(`eslint`);
        resolve();
      }

    });

  });

}
<commit_msg>ignore bower_components, node_modules and /dist<commit_after>import eslint from 'eslint';
import globby from 'globby';
import Logger from './logger';

export default function lint() {

  const engine = new eslint.CLIEngine({
    useEslintrc: true
  });

  return new Promise((resolve, reject) => {

    globby(['**/**.js', '!node_modules/**', '!bower_components/**', '!dist/**', '!build/**']).then( paths => {

      var report = engine.executeOnFiles(paths.slice(2));
      var formatter = engine.getFormatter();

      if (report.errorCount || report.warningCount) {
        Logger.failed(`eslint`);
        Logger.simple(`${formatter(report.results)}`);
        reject();
      }else {
        Logger.ok(`eslint`);
        resolve();
      }

    });

  });

}
<|endoftext|>


<commit_before>/* jshint strict:false */

var http = require('http');
var url = require('url');
var qs = require('querystring');
var Parameter = require('./parameter');

var defaultConfig = {
  segments: [],
  port: 8000
};

function Metron(config){
  this.config = config || {};
  this.set(config);
}

Metron.prototype.get = function(key){
  return this.config[key];
}

Metron.prototype.set = function(obj){
  for(var key in defaultConfig){
    this.config[key] =
      [obj[key], this.config[key], defaultConfig[key]].filter(function(v){
        return v !== undefined
      })[0];
  }

  return this.config;
}

Metron.prototype.start = function(){
  var server  = http.createServer(this.processRequest.bind(this));
  this.server = server;

  server.listen(this.get('port'));
}

Metron.prototype.stop = function(){
  this.server.close();
}

Metron.prototype.processRequest = function(req, res){
  var params = { };
  var parsedUrl = url.parse(req.url, true);

  if(req.method === 'GET'){
    try{
      req.params = JSON.parse(parsedUrl.query.data);
      this.processParameters(req, res);
    }catch(e){
      return this.endRequest(req, res, 400);
    }
  }else{
    var body = [];

    req.on('data', function (data) {
      body.push(data.toString());
    });

    req.on('end', function () {
      body = body.join('');

      if(req.headers['Content-Type'].toLowerCase().indexOf('json') > -1){
        try{
          params = JSON.parse(body);
        }catch(e){
          return this.endRequest(req, res, 400);
        }
      }else{
        req.params = qs.parse(body);
        this.processParameters(req, res);
      }
    });
  }
}

Metron.prototype.endRequest = function(req, res, statusCode){
  res.writeHead(statusCode || 204);
  res.end();
};

Metron.prototype.processParameters = function(req, res){
  var params = req.params;

  for(var segmentName in params){
    var segmentConfig = this.config.segments[segmentName];
    var segment = params[segmentName];

    if(!segmentConfig)
      return this.endRequest(req, res, 422);

    for(var statName in segment){
      var statConfig = segmentConfig.stats[statName];
      var statValue = segment[statName];
      statValue = new Parameter(statValue, statConfig).value();

      if(statValue !== undefined){
        var config = { };
        var store = statConfig.dataStore ||
                    segmentConfig.dataStore ||
                    console.log;

        for(var key in segmentConfig){
          if(key == 'stats') continue;
          config[key] = statConfig[key];
        }

        for(key in statConfig){
          config[key] = statConfig[key];
        }

        if(typeof store === 'function'){
          store(statName, statValue, config, req);
        }else if(typeof store === 'object'){
          store.forEach(function(s){
            s(statName, statValue, config, req);
          });
        }
      }
    }
  }

  this.endRequest(req, res);
}

Metron.dataAdapters = {
  Statsd: require('./data/statsd'),
  Log: require('./data/log')
}

module.exports = Metron;
<commit_msg>Allow middleware<commit_after>/* jshint strict:false */

var http = require('http');
var url = require('url');
var qs = require('querystring');
var Parameter = require('./parameter');

var defaultConfig = {
  segments: [],
  port: 8000
};

function Metron(config, middleware){
  this.config = config || {};
  this.middleware = middleware || [];
  this.set(config);
}

Metron.prototype.get = function(key){
  return this.config[key];
}

Metron.prototype.set = function(obj){
  for(var key in defaultConfig){
    this.config[key] =
      [obj[key], this.config[key], defaultConfig[key]].filter(function(v){
        return v !== undefined
      })[0];
  }

  return this.config;
}

Metron.prototype.start = function(){
  var server  = http.createServer(this.processRequest.bind(this));
  this.server = server;

  server.listen(this.get('port'));
}

Metron.prototype.stop = function(){
  this.server.close();
}

Metron.prototype.processRequest = function(req, res){
  var params = { };
  var parsedUrl = url.parse(req.url, true);

  if(req.method === 'GET'){
    try{
      req.params = JSON.parse(parsedUrl.query.data);
      this.processParameters(req, res);
    }catch(e){
      return this.endRequest(req, res, 400);
    }
  }else{
    var body = [];

    req.on('data', function (data) {
      body.push(data.toString());
    });

    req.on('end', function () {
      body = body.join('');

      if(req.headers['Content-Type'].toLowerCase().indexOf('json') > -1){
        try{
          params = JSON.parse(body);
        }catch(e){
          return this.endRequest(req, res, 400);
        }
      }else{
        req.params = qs.parse(body);
        this.processParameters(req, res);
      }
    });
  }
}

Metron.prototype.endRequest = function(req, res, statusCode){
  res.writeHead(statusCode || 204);
  res.end();
};

Metron.prototype.processParameters = function(req, res){
  var params = req.params;

  for(var i = 0; i < this.middleware.length; i++){
    this.middleware[i](req, res);
  }

  for(var segmentName in params){
    var segmentConfig = this.config.segments[segmentName];
    var segment = params[segmentName];

    if(!segmentConfig)
      return this.endRequest(req, res, 422);

    for(var statName in segment){
      var statConfig = segmentConfig.stats[statName];
      var statValue = segment[statName];
      statValue = new Parameter(statValue, statConfig).value();

      if(statValue !== undefined){
        var config = { };
        var store = statConfig.dataStore ||
                    segmentConfig.dataStore ||
                    console.log;

        for(var key in segmentConfig){
          if(key == 'stats') continue;
          config[key] = statConfig[key];
        }

        for(key in statConfig){
          config[key] = statConfig[key];
        }

        if(typeof store === 'function'){
          store(statName, statValue, config, req);
        }else if(typeof store === 'object'){
          store.forEach(function(s){
            s(statName, statValue, config, req);
          });
        }
      }
    }
  }

  this.endRequest(req, res);
}

Metron.dataAdapters = {
  Statsd: require('./data/statsd'),
  Log: require('./data/log')
}

module.exports = Metron;
<|endoftext|>


<commit_before>/*
  plug.js
  Version: 1.0.0 2015-06-06
  http://hvlmnns.github.io/plug.js/
  The MIT License (MIT)
  Copyright (c) 2015 hvlmnns
*/

// dependencies !!

;(function ($) { 'use strict';
  $.pluglib = {}; // register library
  $.plug = function(name,functions) {
    var name,functions;
    // main plug function
    $.plug.js = function() {
      if(name) $.plug.js.proto();
    }
    $.plug.js.noop = function() {};

    // create prototype for the plugin
    $.plug.js.proto = function() {
      $.plug.js.fn(); // make function
      $.plug[name].prototype = {
        constructor: name,
        name: name,
        init: $.plug.js.noop()
      }
      $.extend(true,$.plug[name].prototype,functions)
      $.plug[name].defaults = $.plug[name].prototype.defaults;
      $.plug.js.register();
    }

    // create base function
    $.plug.js.fn = function() {
      $.plug[name] = function(el, opts, callback) {
        this.proto      = $.plug[name].prototype
        this.el        = el;
        this.$el       = $(el);
        var inlinedata = $.plug.js.inlinedata(this.defaults,this.$el);
        this.opts      = $.extend(true,{}, this.defaults, opts, inlinedata);
      };
    }

    // register plugin in jquery library
    $.plug.js.register = function () {
      var subs = $.plug.js.getsubs(name);
      $.plug.js.registersubs(subs);
      $.fn[name] = function(opts, callback, fallback) {
        if ('string' == typeof opts) {
          this.each(function() {
            $(this)[name+'__'+opts](this,callback,fallback);
          });
          return this
        } else {
          this.each(function() {
            new $.plug[name](this, opts, callback).init();
            return $.plug.js.callback([opts,callback],this);
          });
          return this
        }
      };
      $.pluglib[name] = $.plug[name].prototype;
    }

    // register plugin methods in jquery library
    $.plug.js.getsubs = function (name,all) {
      var temp = $.plug[name].prototype;
      var subs = {};
      for(var fn in temp){
        if (all) {
          subs[fn] = temp[fn];
        }else {
          if ('function' == typeof temp[fn]) {
            subs[fn] = temp[fn];
          }
        }
      }
      return subs;
    }

    $.plug.js.registersubs = function(subs) {
      for (var fn in subs) {
        $.fn[name+'__'+fn] =  function (el,opts, callback) {
          new $.plug[name](el, opts, callback)[fn]();
          return $.plug.js.callback([opts,callback],el);
        }
      }
    }

    // returning inline data attributs as object
    $.plug.js.inlinedata = function(defaults,obj) {
      var data = {};
      for(var option in defaults){
        data[option] = obj.data(name.toLowerCase()+'-'+option)
      }
      return data;
    }

    $.plug.js.callback = function(callback,el) {
      for(var n in callback) {
        if ('function' == typeof callback[n]) {
          (function(el) {
            this[name+'__callback'] = callback[n];
            this[name+'__callback']();
            delete this[name+'__callback'];
          }).call(el);
        }
      }
    }

    // copy plugin
    $.plug.copy = function (name,copy) {
      var subs = $.plug.js.getsubs(name,true);
      $.plug(copy,subs);
      $.plug[copy].prototype.name        = copy;
      $.plug[copy].prototype.constructor = copy;
    }

    // replace funtion
    $.plug.replace = function (name,method,replace) {
      if ('function' == typeof $.plug[name].prototype[method]) {
        return $.plug[name].prototype[method] = replace;
      }
      throw new Error('\n$.plug.js:  Plugin ('+name+') has no ('+method+') function.')
    }

    $.plug.append = function (name,method,append) {
      $.plug.js.modify('append',name,method,append)
    }

    $.plug.prepend = function (name,method,prepend) {
      $.plug.js.modify('prepend',name,method,prepend)
    }

    $.plug.js.modify = function (type,name,method,fn) {
      if ('function' == typeof $.plug[name].prototype[method]) {
        var original = $.plug[name].prototype[method]
        if (type == 'append') {
          $.plug[name].prototype[method] = function () {
            original.call(this)
            fn.call(this)
          }
        } else if (type == 'prepend') {
          $.plug[name].prototype[method] = function () {
            fn.call(this)
            original.call(this)
          }
        }
        return;
      }
      throw new Error('\n$.plug.js - '+type+':  Plugin ('+name+') has no ('+method+') function.')
    }
    // execute plug
    $.plug.js();

  };

})(jQuery);<commit_msg>version change<commit_after>/*
  plug.js
  Version: 1.0.1 2015-06-06
  http://hvlmnns.github.io/plug.js/
  The MIT License (MIT)
  Copyright (c) 2015 hvlmnns
*/

// dependencies !!

;(function ($) { 'use strict';
  $.pluglib = {}; // register library
  $.plug = function(name,functions) {
    var name,functions;
    // main plug function
    $.plug.js = function() {
      if(name) $.plug.js.proto();
    }
    $.plug.js.noop = function() {};

    // create prototype for the plugin
    $.plug.js.proto = function() {
      $.plug.js.fn(); // make function
      $.plug[name].prototype = {
        constructor: name,
        name: name,
        init: $.plug.js.noop()
      }
      $.extend(true,$.plug[name].prototype,functions)
      $.plug[name].defaults = $.plug[name].prototype.defaults;
      $.plug.js.register();
    }

    // create base function
    $.plug.js.fn = function() {
      $.plug[name] = function(el, opts, callback) {
        this.proto      = $.plug[name].prototype
        this.el        = el;
        this.$el       = $(el);
        var inlinedata = $.plug.js.inlinedata(this.defaults,this.$el);
        this.opts      = $.extend(true,{}, this.defaults, opts, inlinedata);
      };
    }

    // register plugin in jquery library
    $.plug.js.register = function () {
      var subs = $.plug.js.getsubs(name);
      $.plug.js.registersubs(subs);
      $.fn[name] = function(opts, callback, fallback) {
        if ('string' == typeof opts) {
          this.each(function() {
            $(this)[name+'__'+opts](this,callback,fallback);
          });
          return this
        } else {
          this.each(function() {
            new $.plug[name](this, opts, callback).init();
            return $.plug.js.callback([opts,callback],this);
          });
          return this
        }
      };
      $.pluglib[name] = $.plug[name].prototype;
    }

    // register plugin methods in jquery library
    $.plug.js.getsubs = function (name,all) {
      var temp = $.plug[name].prototype;
      var subs = {};
      for(var fn in temp){
        if (all) {
          subs[fn] = temp[fn];
        }else {
          if ('function' == typeof temp[fn]) {
            subs[fn] = temp[fn];
          }
        }
      }
      return subs;
    }

    $.plug.js.registersubs = function(subs) {
      for (var fn in subs) {
        $.fn[name+'__'+fn] =  function (el,opts, callback) {
          new $.plug[name](el, opts, callback)[fn]();
          return $.plug.js.callback([opts,callback],el);
        }
      }
    }

    // returning inline data attributs as object
    $.plug.js.inlinedata = function(defaults,obj) {
      var data = {};
      for(var option in defaults){
        data[option] = obj.data(name.toLowerCase()+'-'+option)
      }
      return data;
    }

    $.plug.js.callback = function(callback,el) {
      for(var n in callback) {
        if ('function' == typeof callback[n]) {
          (function(el) {
            this[name+'__callback'] = callback[n];
            this[name+'__callback']();
            delete this[name+'__callback'];
          }).call(el);
        }
      }
    }

    // copy plugin
    $.plug.copy = function (name,copy) {
      var subs = $.plug.js.getsubs(name,true);
      $.plug(copy,subs);
      $.plug[copy].prototype.name        = copy;
      $.plug[copy].prototype.constructor = copy;
    }

    // replace funtion
    $.plug.replace = function (name,method,replace) {
      if ('function' == typeof $.plug[name].prototype[method]) {
        return $.plug[name].prototype[method] = replace;
      }
      throw new Error('\n$.plug.js:  Plugin ('+name+') has no ('+method+') function.')
    }

    $.plug.append = function (name,method,append) {
      $.plug.js.modify('append',name,method,append)
    }

    $.plug.prepend = function (name,method,prepend) {
      $.plug.js.modify('prepend',name,method,prepend)
    }

    $.plug.js.modify = function (type,name,method,fn) {
      if ('function' == typeof $.plug[name].prototype[method]) {
        var original = $.plug[name].prototype[method]
        if (type == 'append') {
          $.plug[name].prototype[method] = function () {
            original.call(this)
            fn.call(this)
          }
        } else if (type == 'prepend') {
          $.plug[name].prototype[method] = function () {
            fn.call(this)
            original.call(this)
          }
        }
        return;
      }
      throw new Error('\n$.plug.js - '+type+':  Plugin ('+name+') has no ('+method+') function.')
    }
    // execute plug
    $.plug.js();

  };

})(jQuery);<|endoftext|>