<commit_before>'use strict';

exports = module.exports = createREPL;

function createREPL(gulp){
  if(gulp.repl && gulp.repl !== true){ return; }

  var readline = require('readline');

  var repl = gulp.repl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
    completer: function completion(line){
      return completer(gulp, line);
    }
  });

  repl.on('line', function(line){
    line = line.trim();
    if(!line){ return repl.prompt(); }

    var notFound = [];
    line = line.split(/[ ]+/).filter(function(task){
      var found = gulp.tasks.get(task) || {};
      if(typeof found.fn === 'function'){ return true; }
      notFound.push(task);
    });

    if(notFound.length){
      var plural = notFound.length > 1;
      console.log(' Warning: `%s` task%s %s undefined',
        notFound.join(', '),
        plural && 's' || '',
        plural && 'are' || 'is'
      );

      if(!line.length){ return repl.prompt(); }
    }

    gulp.stack.apply(gulp, line)();
  });

  repl.on('SIGINT', function(){
    repl.output.write('\n');
    console.log(new Date());
    process.exit(0);
  });
}

function completer(gulp, line){
  var match = line.match(/([ ]+|^)\S+$/);
  var completion = Object.keys(gulp.tasks.store);

  if(match){
    line = line.slice(match.index, line.length).trim();
  }

  var hits = completion.filter(function(elem){
    return !elem.indexOf(line);
  });

  return [hits.length ? hits : completion, line];
}
<commit_msg>reword: for undefined tasks<commit_after>'use strict';

exports = module.exports = createREPL;

function createREPL(gulp){
  if(gulp.repl && gulp.repl !== true){ return; }

  var readline = require('readline');

  var repl = gulp.repl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
    completer: function completion(line){
      return completer(gulp, line);
    }
  });

  repl.on('line', function(line){
    line = line.trim();
    if(!line){ return repl.prompt(); }

    var notFound = [];
    line = line.split(/[ ]+/).filter(function(task){
      var found = gulp.tasks.get(task) || {};
      if(typeof found.fn === 'function'){ return true; }
      notFound.push(task);
    });

    if(notFound.length){
      var plural = notFound.length > 1;
      console.log(' `%s` task%s %s is not defined yet',
        notFound.join(', '),
        plural && 's' || '',
        plural && 'are' || 'is'
      );

      if(!line.length){ return repl.prompt(); }
    }

    gulp.stack.apply(gulp, line)();
  });

  repl.on('SIGINT', function(){
    repl.output.write('\n');
    console.log(new Date());
    process.exit(0);
  });
}

function completer(gulp, line){
  var match = line.match(/([ ]+|^)\S+$/);
  var completion = Object.keys(gulp.tasks.store);

  if(match){
    line = line.slice(match.index, line.length).trim();
  }

  var hits = completion.filter(function(elem){
    return !elem.indexOf(line);
  });

  return [hits.length ? hits : completion, line];
}
<|endoftext|>


<commit_before>/**
 * Extend module's NODE_PATH
 * HACK: temporary solution
 */

require('node-path')(module);

/**
 * Module dependencies.
 */

var mongoose = require('mongoose');
var Law = mongoose.model('Law');
var commentApi = require('./comment');
var delegationApi = require('./delegation');
var tagApi = require('./tag');
var utils = require('lib/utils');
var pluck = utils.pluck;
var log = require('debug')('democracyos:db-api:law');

/**
 * Get all laws
 *
 * @param {Object} find query object
 * @param {Function} fn callback function
 *   - 'err' error found on query or `null`
 *   - 'laws' list items found or `undefined`
 * @return {Module} `law` module
 * @api public
 */

exports.all = function all(find, fn) {
  log('Looking for all laws.')

  if (1 === arguments.length) {
    fn = find;
    find = {};
  }

  Law
  .find(find)
  .select('id lawId mediaTitle tag participants votes createdAt updatedAt closingAt publishedAt deletedAt status open closed')
  .populate('tag', 'id hash name color image')
  .exec(function (err, laws) {
    if (err) {
      log('Found error %j', err);
      return fn(err);
    };

    log('Delivering laws %j', pluck(laws, 'id'));
    fn(null, laws);
  });

  return this;
};

/**
 * Creates law
 *
 * @param {Object} data to create law
 * @param {Function} fn callback function
 *   - 'err' error found on query or `null`
 *   - 'law' item created or `undefined`
 * @return {Module} `law` module
 * @api public
 */

exports.create = function create(data, fn) {
  log('Creating new law %j', data);

  // wrong using tag api within proposal's
  log('Looking for tag %s in database.', data.tag);
  tagApi.create(data.tag, function (err, tag) {
    if (err) {
      log('Found error from tag creation %j', err);
      return fn(err);
    };

    data.tag = tag;

    var law = new Law(data);

    law.save(onsave);

    function onsave(err) {
      if (!err) return log('Saved law %s', law.id), fn(null, law);

      if (11000 == err.code) {
        log('Attempt of duplication');
        exports.searchOne(law.lawId, fn);
      } else {
        log('Found error %s', err);
        fn(err);
      }

    }

  });

  return this;
};

/**
 * Update law by `id` and `data`
 *
 * @param {ObjectId|String} data to create law
 * @param {Function} fn callback function
 *   - 'err' error found on query or `null`
 *   - 'law' item created or `undefined`
 * @return {Module} `law` module
 * @api public
 */

exports.update = function update(id, data, fn) {
  log('Updating law %s with %j', id, data);

  // look for tag for nesting reference
  log('Looking for tag %s in database.', data.tag);
  tagApi.searchOne(data.tag, function (err, tag) {
    if (err) return log('Found error %s', err.message), fn(err);

    // now set `data.tag` to `tag`'s document _id
    data.tag = tag;

    // get law
    exports.get(id, onget);

    function onget(err, law) {
      if (err) {
        log('Found error %s', err.message);
        return fn(err);
      };

      var clauses = data.clauses || [];
      delete data.clauses;

      clauses.forEach(function(clause) {
        var c = law.clauses.id(clause.id);
        // c.update(clause);
        c.set(clause);
      });

      // update and save law document with data
      law.set(data);
      law.save(onupdate);
    }

    function onupdate(err, law) {
      if (!err) return log('Saved law %s', law.id), fn(null, law);
      return log('Found error %s', err), fn(err);
    }

  });

  return this;
};

/**
 * Search single law from lawId
 *
 * @param {String} lawId string to search by `lawId`
 * @param {Function} fn callback function
 *   - 'err' error found while process or `null`
 *   - 'law' single law object found or `undefined`
 * @return {Module} `law` module
 * @api public
 */

exports.searchOne = function searchByLawId(lawId, fn) {
  var query = { lawId: lawId };

  log('Searching for single law matching %j', query);
  Law
  .findOne(query)
  .populate('tag')
  .populate('participants')
  .exec(function (err, law) {
    if (err) {
      log('Found error %s', err);
      return fn(err);
    }

    log('Delivering law %s', law.id);
    fn(null, law);
  })

  return this;
};

/**
 * Get Law form `id` string or `ObjectId`
 *
 * @param {String|ObjectId} id Law's `id`
 * @param {Function} fn callback function
 *   - 'err' error found while process or `null`
 *   - 'law' found item or `undefined`
 * @api public
 */

exports.get = function get(id, fn) {
  log('Looking for law %s', id);

  Law
  .findById(id)
  .populate('tag')
  .exec(function (err, law) {
    if (err) {
      log('Found error %s', err);
      return fn(err);
    };

    log('Delivering law %s', law.id);
    fn(null, law);
  });
};

/**
 * Vote law
 *
 * @param {String} id Law `id`
 * @param {String} citizen author of the vote
 * @param {String} value `positive` or `negative` or `neutral`
 * @param {Function} fn callback function
 *   - 'err' error found while process or `null`
 *   - 'proposal' single object created or `undefined`
 * @api public
 */

exports.vote = function vote(id, citizen, value, fn) {
  log('Proceding to vote %s at law %s by citizen %s', value, id, citizen.id || citizen);

  Law.findById(id, function (err, law) {
    if (err) {
      log('Found error %s', err);
      return fn(err);
    };

    law.vote(citizen.id, value, function(err) {
      if (err) {
        log('Found error %s', err);
        return fn(err);
      };

      log('Voted %s at law %s by citizen %s', value, id, citizen.id || citizen);
      fn(null, law);
    });
  });
};

/*
 * Recount law votes and process delegations
 *
 * @param {String} id Law `id`
 * @param {Function} fn callback function
 *   - 'err' error found while process or `null`
 *   - 'proposal' single object created or `undefined`
 * @api public
 */

exports.recount = function vote(id, fn) {
  log('Proceding to recount %s', id);

  Law.findById(id, function (err, law) {
    if (err) {
      log('Found error %s', err);
      return fn(err);
    };

    if ('recount' === law.status) {
      log('Called recount but recount has already started.');
      return fn(new Error('Recount already started.'));
    };

    if ('closed' === law.status) {
      log('Called recount but law vote cast is closed.');
      return fn(new Error('Vote cast closed for law.'));
    };

    // Mark law for recount
    law.recount(function(err) {
      if (err) {
        log('Found error %s', err);
        return fn(err);
      };

      // WRONG
      delegationApi.trees(pluck(law.votes, 'author'), function(trees) {
        var nodes = trees.map(function(t) { return t.nodes() })

        nodes.forEach(function(n) {
          // node value
          var author = n.truster;
          // node parent
          var trustee = n.trustee;
          // node's branch top node
          var caster = n.caster;

          law.proxyVote(author, trustee, caster);
        });

        law.save(function(err) {
          if (err) {
            log('Found err %s', err);
            return fn(err);
          };

          fn(null, law);
        });
      });
    });
  });
};

/**
 * Direct comment to law
 *
 * @param {String} id Proposal's `id`
 * @param {Object} comment to attach
 * @param {Function} fn callback function
 *   - 'err' error found while process or `null`
 *   - 'law' single object created or `undefined`
 * @api public
 */

exports.comment = function comment(comment, fn) {
  log('Creating comment %j for law %s', comment.text, comment.reference);
  commentApi.create(comment, function (err, commentDoc) {
    if (err) {
      log('Found error %j', err);
      return fn(err);
    };

    log('Delivering comment %j', commentDoc);
    fn(null, commentDoc);
  });
};

/**
 * Get comments for law
 *
 * @param {String} id Law's `id`
 * @param {Function} fn callback function
 *   - 'err' error found while process or `null`
 *   - 'law' single object created or `undefined`
 * @api public
 */

exports.comments = function comments(id, fn) {
  log('Get comments for law %s', id);
  commentApi.getFor({
    context: 'law',
    reference: id
  }, function (err, comments) {
    if (err) {
      log('Found error %j', err);
      return fn(err);
    };

    log('Delivering comments %j', pluck(comments, 'id'));
    fn(null, comments);
  });
};<commit_msg>[db-api:law] - Update queries to only display undeleted laws<commit_after>/**
 * Extend module's NODE_PATH
 * HACK: temporary solution
 */

require('node-path')(module);

/**
 * Module dependencies.
 */

var mongoose = require('mongoose');
var Law = mongoose.model('Law');
var commentApi = require('./comment');
var delegationApi = require('./delegation');
var tagApi = require('./tag');
var utils = require('lib/utils');
var pluck = utils.pluck;
var log = require('debug')('democracyos:db-api:law');

/**
 * Get all laws
 *
 * @param {Function} fn callback function
 *   - 'err' error found on query or `null`
 *   - 'laws' list items found or `undefined`
 * @return {Module} `law` module
 * @api public
 */

exports.all = function all(fn) {
  log('Looking for all laws.')

  Law
  .find({ deletedAt: null })
  .select('id lawId mediaTitle tag participants votes createdAt updatedAt closingAt publishedAt deletedAt status open closed')
  .populate('tag', 'id hash name color image')
  .exec(function (err, laws) {
    if (err) {
      log('Found error %j', err);
      return fn(err);
    };

    log('Delivering laws %j', pluck(laws, 'id'));
    fn(null, laws);
  });

  return this;
};

/**
 * Creates law
 *
 * @param {Object} data to create law
 * @param {Function} fn callback function
 *   - 'err' error found on query or `null`
 *   - 'law' item created or `undefined`
 * @return {Module} `law` module
 * @api public
 */

exports.create = function create(data, fn) {
  log('Creating new law %j', data);

  // wrong using tag api within proposal's
  log('Looking for tag %s in database.', data.tag);
  tagApi.create(data.tag, function (err, tag) {
    if (err) {
      log('Found error from tag creation %j', err);
      return fn(err);
    };

    data.tag = tag;

    var law = new Law(data);

    law.save(onsave);

    function onsave(err) {
      if (!err) return log('Saved law %s', law.id), fn(null, law);

      if (11000 == err.code) {
        log('Attempt of duplication');
        exports.searchOne(law.lawId, fn);
      } else {
        log('Found error %s', err);
        fn(err);
      }

    }

  });

  return this;
};

/**
 * Update law by `id` and `data`
 *
 * @param {ObjectId|String} data to create law
 * @param {Function} fn callback function
 *   - 'err' error found on query or `null`
 *   - 'law' item created or `undefined`
 * @return {Module} `law` module
 * @api public
 */

exports.update = function update(id, data, fn) {
  log('Updating law %s with %j', id, data);

  // look for tag for nesting reference
  log('Looking for tag %s in database.', data.tag);
  tagApi.searchOne(data.tag, function (err, tag) {
    if (err) return log('Found error %s', err.message), fn(err);

    // now set `data.tag` to `tag`'s document _id
    data.tag = tag;

    // get law
    exports.get(id, onget);

    function onget(err, law) {
      if (err) {
        log('Found error %s', err.message);
        return fn(err);
      };

      var clauses = data.clauses || [];
      delete data.clauses;

      clauses.forEach(function(clause) {
        var c = law.clauses.id(clause.id);
        // c.update(clause);
        c.set(clause);
      });

      // update and save law document with data
      law.set(data);
      law.save(onupdate);
    }

    function onupdate(err, law) {
      if (!err) return log('Saved law %s', law.id), fn(null, law);
      return log('Found error %s', err), fn(err);
    }

  });

  return this;
};

/**
 * Search single law from lawId
 *
 * @param {String} lawId string to search by `lawId`
 * @param {Function} fn callback function
 *   - 'err' error found while process or `null`
 *   - 'law' single law object found or `undefined`
 * @return {Module} `law` module
 * @api public
 */

exports.searchOne = function searchByLawId(lawId, fn) {
  var query = { lawId: lawId, deletedAt: null };

  log('Searching for single law matching %j', query);
  Law
  .findOne(query)
  .populate('tag')
  .populate('participants')
  .exec(function (err, law) {
    if (err) {
      log('Found error %s', err);
      return fn(err);
    }

    log('Delivering law %s', law.id);
    fn(null, law);
  })

  return this;
};

/**
 * Get Law form `id` string or `ObjectId`
 *
 * @param {String|ObjectId} id Law's `id`
 * @param {Function} fn callback function
 *   - 'err' error found while process or `null`
 *   - 'law' found item or `undefined`
 * @api public
 */

exports.get = function get(id, fn) {
  var query = { _id: id, deletedAt: null };

  log('Looking for law %s', id);
  Law
  .findOne(query)
  .populate('tag')
  .exec(function (err, law) {
    if (err) {
      log('Found error %s', err);
      return fn(err);
    };

    log('Delivering law %s', law.id);
    fn(null, law);
  });
};

/**
 * Vote law
 *
 * @param {String} id Law `id`
 * @param {String} citizen author of the vote
 * @param {String} value `positive` or `negative` or `neutral`
 * @param {Function} fn callback function
 *   - 'err' error found while process or `null`
 *   - 'proposal' single object created or `undefined`
 * @api public
 */

exports.vote = function vote(id, citizen, value, fn) {
  var query = { _id: id, deletedAt: null };

  log('Proceding to vote %s at law %s by citizen %s', value, id, citizen.id || citizen);
  Law
  .findOne(query)
  .exec(function (err, law) {
    if (err) {
      log('Found error %s', err);
      return fn(err);
    };

    law.vote(citizen.id, value, function(err) {
      if (err) {
        log('Found error %s', err);
        return fn(err);
      };

      log('Voted %s at law %s by citizen %s', value, id, citizen.id || citizen);
      fn(null, law);
    });
  });
};

/*
 * Recount law votes and process delegations
 *
 * @param {String} id Law `id`
 * @param {Function} fn callback function
 *   - 'err' error found while process or `null`
 *   - 'proposal' single object created or `undefined`
 * @api public
 */

exports.recount = function vote(id, fn) {
  var query = { _id: id, deletedAt: null };
  log('Proceding to recount %s', id);

  Law
  .findOne(query)
  .exec(function (err, law) {
    if (err) {
      log('Found error %s', err);
      return fn(err);
    };

    if ('recount' === law.status) {
      log('Called recount but recount has already started.');
      return fn(new Error('Recount already started.'));
    };

    if ('closed' === law.status) {
      log('Called recount but law vote cast is closed.');
      return fn(new Error('Vote cast closed for law.'));
    };

    // Mark law for recount
    law.recount(function(err) {
      if (err) {
        log('Found error %s', err);
        return fn(err);
      };

      // WRONG
      delegationApi.trees(pluck(law.votes, 'author'), function(trees) {
        var nodes = trees.map(function(t) { return t.nodes() })

        nodes.forEach(function(n) {
          // node value
          var author = n.truster;
          // node parent
          var trustee = n.trustee;
          // node's branch top node
          var caster = n.caster;

          law.proxyVote(author, trustee, caster);
        });

        law.save(function(err) {
          if (err) {
            log('Found err %s', err);
            return fn(err);
          };

          fn(null, law);
        });
      });
    });
  });
};

/**
 * Direct comment to law
 *
 * @param {String} id Proposal's `id`
 * @param {Object} comment to attach
 * @param {Function} fn callback function
 *   - 'err' error found while process or `null`
 *   - 'law' single object created or `undefined`
 * @api public
 */

exports.comment = function comment(comment, fn) {
  log('Creating comment %j for law %s', comment.text, comment.reference);
  commentApi.create(comment, function (err, commentDoc) {
    if (err) {
      log('Found error %j', err);
      return fn(err);
    };

    log('Delivering comment %j', commentDoc);
    fn(null, commentDoc);
  });
};

/**
 * Get comments for law
 *
 * @param {String} id Law's `id`
 * @param {Function} fn callback function
 *   - 'err' error found while process or `null`
 *   - 'law' single object created or `undefined`
 * @api public
 */

exports.comments = function comments(id, fn) {
  log('Get comments for law %s', id);
  commentApi.getFor({
    context: 'law',
    reference: id
  }, function (err, comments) {
    if (err) {
      log('Found error %j', err);
      return fn(err);
    };

    log('Delivering comments %j', pluck(comments, 'id'));
    fn(null, comments);
  });
};<|endoftext|>


<commit_before>var WebSocket = require('ws'),
    _ = require('underscore'),
    util = require('util'),
    events = require('events');

DDPClient = function(opts) {
  var self = this;

  // default arguments
  self.host = opts.host || 'localhost';
  self.port = opts.port || 3000;
  self.path = opts.path || 'websocket';
  self.use_ssl = opts.use_ssl || self.port === 443;

  // very very simple collections (name -> [{id -> document}])
  self.collections = {};

  // internal stuff to track callbacks
  self._next_id = 0;
  self._callbacks = {};
}

/**
 * Inherits from EventEmitter
 */
util.inherits(DDPClient, events.EventEmitter);

DDPClient.prototype._prepareHandlers = function() {
  var self = this;

  self.socket.on('open', function() {
    // just go ahead and open the connection on connect
    self._send({msg: 'connect'});
  });

  self.socket.on('error', function(error) {
    self.emit('error', error);
  });

  self.socket.on('close', function(code, message) {
    self.emit('close', code, message);
  });

  self.socket.on('message', function(data, flags) {
    self.emit('message', data, flags);

    self._message(data, flags);
  });
}

DDPClient.prototype.onMessage = function (callback) {
  this._msg_filters.push(callback);
};

///////////////////////////////////////////////////////////////////////////
// RAW, low level functions
DDPClient.prototype._send = function(data) {

  this.socket.send(JSON.stringify(data));
}

// handle a message from the server
DDPClient.prototype._message = function(data, flags) {
  var self = this;
  var data = JSON.parse(data);

  // TODO: 'error'
  // TODO -- method acks <- not sure exactly what the point is here

  if (!data.msg) {
    return;

  } else if (data.msg === 'connected') {
    self.emit('connected');

  // method result
  } else if (data.msg === 'result') {
    var cb = self._callbacks[data.id];

    if (cb) {
      cb(data.error, data.result);
      delete self._callbacks[data.id]
    }

  // missing subscription
  } else if (data.msg === 'nosub') {
    var cb = self._callbacks[data.id];

    if (cb) {
      cb(data.error);
      delete self._callbacks[data.id]
    }

  } else if (data.msg === 'data') {

    if (data.collection) {
      self._updateCollection(data);

    // subscription complete
    } else if (data.subs) {

      _.each(data.subs, function(id) {
        var cb = self._callbacks[id];
        if (cb) {
          cb();
          delete self._callbacks[id]
        }
      });
    }

  }
}

DDPClient.prototype._nextId = function() {

  return (this._next_id += 1).toString();
}

DDPClient.prototype._updateCollection = function(data) {
  var self = this;

  var name = data.collection, id = data.id;

  if (!self.collections[name])
    self.collections[name] = {};
  if (!self.collections[name][id])
    self.collections[name][id] = {}

  if (data.set) {
    _.each(data.set, function(value, key) {
      self.collections[name][id][key] = value;
    });
  }
  if (data.unset) {
    _.each(data.unset, function(value) {
      delete self.collections[name][id][value];
    });
  }

  // clean up
  if (_.isEmpty(self.collections[name][id]))
    delete self.collections[name][id];
}

//////////////////////////////////////////////////////////////////////////
// USER functions -- use these to control the client

/* open the connection to the server
 *
 *  connected(): Called when the 'connected' message is received
 *               Deprecated - use on('connected', cb) instead
 */
DDPClient.prototype.connect = function(connected) {
  var self = this;

  if (connected)
    self.addListener("connected", connected);

  // websocket
  var protocol = self.use_ssl ? 'wss://' : 'ws://';
  self.socket = new WebSocket(protocol + self.host + ':' + self.port + '/' + self.path);
  self._prepareHandlers();
}

DDPClient.prototype.close = function() {
  var self = this;

  self.socket.close();
}

// call a method on the server,
//
// callback = function(err, result)
DDPClient.prototype.call = function(name, params, callback) {
  var self = this;
  var id = self._nextId()

  if (callback)
    self._callbacks[id] = callback;

  self._send({msg: 'method', id: id, method: name, params: params});
}

// open a subscription on the server, callback should handle on ready and nosub
DDPClient.prototype.subscribe = function(name, params, callback) {
  var self = this;
  var id = self._nextId()

  if (callback)
    self._callbacks[id] = callback;

  self._send({msg: 'sub', id: id, name: name, params: params});
}

module.exports = DDPClient;
<commit_msg>Removing : replaced by on('message')<commit_after>var WebSocket = require('ws'),
    _ = require('underscore'),
    util = require('util'),
    events = require('events');

DDPClient = function(opts) {
  var self = this;

  // default arguments
  self.host = opts.host || 'localhost';
  self.port = opts.port || 3000;
  self.path = opts.path || 'websocket';
  self.use_ssl = opts.use_ssl || self.port === 443;

  // very very simple collections (name -> [{id -> document}])
  self.collections = {};

  // internal stuff to track callbacks
  self._next_id = 0;
  self._callbacks = {};
}

/**
 * Inherits from EventEmitter
 */
util.inherits(DDPClient, events.EventEmitter);

DDPClient.prototype._prepareHandlers = function() {
  var self = this;

  self.socket.on('open', function() {
    // just go ahead and open the connection on connect
    self._send({msg: 'connect'});
  });

  self.socket.on('error', function(error) {
    self.emit('error', error);
  });

  self.socket.on('close', function(code, message) {
    self.emit('close', code, message);
  });

  self.socket.on('message', function(data, flags) {
    self.emit('message', data, flags);

    self._message(data, flags);
  });
}

///////////////////////////////////////////////////////////////////////////
// RAW, low level functions
DDPClient.prototype._send = function(data) {

  this.socket.send(JSON.stringify(data));
}

// handle a message from the server
DDPClient.prototype._message = function(data, flags) {
  var self = this;
  var data = JSON.parse(data);

  // TODO: 'error'
  // TODO -- method acks <- not sure exactly what the point is here

  if (!data.msg) {
    return;

  } else if (data.msg === 'connected') {
    self.emit('connected');

  // method result
  } else if (data.msg === 'result') {
    var cb = self._callbacks[data.id];

    if (cb) {
      cb(data.error, data.result);
      delete self._callbacks[data.id]
    }

  // missing subscription
  } else if (data.msg === 'nosub') {
    var cb = self._callbacks[data.id];

    if (cb) {
      cb(data.error);
      delete self._callbacks[data.id]
    }

  } else if (data.msg === 'data') {

    if (data.collection) {
      self._updateCollection(data);

    // subscription complete
    } else if (data.subs) {

      _.each(data.subs, function(id) {
        var cb = self._callbacks[id];
        if (cb) {
          cb();
          delete self._callbacks[id]
        }
      });
    }

  }
}

DDPClient.prototype._nextId = function() {

  return (this._next_id += 1).toString();
}

DDPClient.prototype._updateCollection = function(data) {
  var self = this;

  var name = data.collection, id = data.id;

  if (!self.collections[name])
    self.collections[name] = {};
  if (!self.collections[name][id])
    self.collections[name][id] = {}

  if (data.set) {
    _.each(data.set, function(value, key) {
      self.collections[name][id][key] = value;
    });
  }
  if (data.unset) {
    _.each(data.unset, function(value) {
      delete self.collections[name][id][value];
    });
  }

  // clean up
  if (_.isEmpty(self.collections[name][id]))
    delete self.collections[name][id];
}

//////////////////////////////////////////////////////////////////////////
// USER functions -- use these to control the client

/* open the connection to the server
 *
 *  connected(): Called when the 'connected' message is received
 *               Deprecated - use on('connected', cb) instead
 */
DDPClient.prototype.connect = function(connected) {
  var self = this;

  if (connected)
    self.addListener("connected", connected);

  // websocket
  var protocol = self.use_ssl ? 'wss://' : 'ws://';
  self.socket = new WebSocket(protocol + self.host + ':' + self.port + '/' + self.path);
  self._prepareHandlers();
}

DDPClient.prototype.close = function() {
  var self = this;

  self.socket.close();
}

// call a method on the server,
//
// callback = function(err, result)
DDPClient.prototype.call = function(name, params, callback) {
  var self = this;
  var id = self._nextId()

  if (callback)
    self._callbacks[id] = callback;

  self._send({msg: 'method', id: id, method: name, params: params});
}

// open a subscription on the server, callback should handle on ready and nosub
DDPClient.prototype.subscribe = function(name, params, callback) {
  var self = this;
  var id = self._nextId()

  if (callback)
    self._callbacks[id] = callback;

  self._send({msg: 'sub', id: id, name: name, params: params});
}

module.exports = DDPClient;
<|endoftext|>


<commit_before>module.exports = function deployment(request) {
    return {
        list: function list(cb) {
            request("/api/deployments/", function(err, response, body) {
                if (err) return cb(err);
                cb(null, JSON.parse(body), response);
            });
        },
        get: function get(id, cb) {
            request("/api/deployments/" + id, function(err, response, body) {
                if (err) return cb(err);
                cb(null, JSON.parse(body), response);
            });
        },
        del: function del(id, cb) {
            request.del("/api/deployments/" + id, function(err, response, body) {
                if (err) return cb(err);
                cb(null, body, response);
            });
        },
        log: function log(id, cb) {
            request("/api/deployments/" + id + "/log", function(err, response, body) {
                if (err) return cb(err);
                cb(null, JSON.parse(body), response);
            });
        },
        logDetails: function logDetails(id, entryId, cb) {
            request("/api/deployments/" + id + "/log/" + entryId, function(err, response, body) {
                if (err) return cb(err);
                cb(null, JSON.parse(body), response);
            });
        },
        deploy: function deploy(repoUrl, cb) {
            request.post({
                uri: "/deploy/",
                json: {
                    format: "basic",
                    url: repoUrl
                }
            }, function(err, response, body) {
                if (err) return cb(err);
                cb(null, body, response);
            });
        },
        redeploy: function redeploy(id, payload, cb) {
            if (typeof payload === "function") {
                cb = payload;
                payload = undefined;
            }

            request.put({
              uri: "/api/deployments/" + id,
              json: payload || {}
              }, function (err, response, body) {
                if(!cb){
                  return;
                }
                if (err) return cb(err);
                cb(null, body, response);
            });
        }
    };
};
<commit_msg>Fix jslint errors in lib/deployment.js<commit_after>"use strict";

module.exports = function deployment(request) {
    return {
        list: function list(cb) {
            request("/api/deployments/", function deploymentListCallback(err, response, body) {
                if (err) {
                    return cb(err);
                }

                cb(null, JSON.parse(body), response);
            });
        },
        get: function get(id, cb) {
            request("/api/deployments/" + id, function deploymentGetCallback(err, response, body) {
                if (err) {
                    return cb(err);
                }

                cb(null, JSON.parse(body), response);
            });
        },
        del: function del(id, cb) {
            request.del("/api/deployments/" + id, function deploymentDelCallback(err, response, body) {
                if (err) {
                    return cb(err);
                }

                cb(null, body, response);
            });
        },
        log: function log(id, cb) {
            request("/api/deployments/" + id + "/log", function deploymentLogCallback(err, response, body) {
                if (err) {
                    return cb(err);
                }

                cb(null, JSON.parse(body), response);
            });
        },
        logDetails: function logDetails(id, entryId, cb) {
            request("/api/deployments/" + id + "/log/" + entryId, function deploymentLogDetailsCallback(err, response, body) {
                if (err) {
                    return cb(err);
                }

                cb(null, JSON.parse(body), response);
            });
        },
        deploy: function deploy(repoUrl, cb) {
            request.post({
                uri: "/deploy/",
                json: {
                    format: "basic",
                    url: repoUrl
                }
            }, function deploymentDeployCallback(err, response, body) {
                if (err) {
                    return cb(err);
                }

                cb(null, body, response);
            });
        },
        redeploy: function redeploy(id, payload, cb) {
            if (typeof payload === "function") {
                cb = payload;
                payload = undefined;
            }

            request.put({
                uri: "/api/deployments/" + id,
                json: payload || {}
            }, function deploymentRedeployCallback(err, response, body) {
                if (!cb) {
                    return;
                }

                if (err) {
                    return cb(err);
                }

                cb(null, body, response);
            });
        }
    };
};
<|endoftext|>


<commit_before>var exec = require('child_process').exec;

module.exports = function(dir, config, callback) {

var env = process.env;
env['REGI_HOST'] = config.host
env['REGI_USER'] = config.user
env['REGI_PASSWD'] = config.pass

	var options = {cwd: dir, env: env};
	console.log("regi.exe create workspace")
	exec("regi.exe create workspace", options, function(err, stdout, stderr) {
	console.log(err, stdout, stderr)
		console.log("regi track")
		exec("regi.exe track " + config.root, options, function(err, stdout, stderr) {
	console.log(err, stdout, stderr)
			console.log("regi commit")
			exec("regi.exe commit", options, function(err, stdout, stderr) {
	console.log(err, stdout, stderr)
				console.log("regi activate")
				exec("regi.exe activate", options, function(err, stdout, stderr) {
	console.log(err, stdout, stderr)
					callback(null, "deployed to " + config.host);
				});
			});
		});
	});
};
<commit_msg>Update deployment.js<commit_after>var exec = require('child_process').exec;

module.exports = function(dir, config, callback) {

var env = process.env;
env['REGI_HOST'] = config.host
env['REGI_USER'] = config.user
env['REGI_PASSWD'] = config.pass

	var options = {cwd: dir, env: env};
	console.log("regi.exe create workspace")
	exec("regi.exe create workspace --force", options, function(err, stdout, stderr) {
	console.log(err, stdout, stderr)
		console.log("regi track")
		exec("regi.exe track " + config.root, options, function(err, stdout, stderr) {
	console.log(err, stdout, stderr)
			console.log("regi commit")
			exec("regi.exe commit", options, function(err, stdout, stderr) {
	console.log(err, stdout, stderr)
				console.log("regi activate")
				exec("regi.exe activate", options, function(err, stdout, stderr) {
	console.log(err, stdout, stderr)
					callback(null, "deployed to " + config.host);
				});
			});
		});
	});
};
<|endoftext|>


<commit_before>var fs    = require('fs');
var path  = require('path');
var mkdirp = require('mkdirp');
var request = require('request');
var pkg = require('../package');
var pathEx = require('path-extra');

// First, look for the download link.
/*jshint maxlen:false */
var dir, filePath, isWin;
var dataPath = pathEx.datadir(pkg.name);
var regexp = /https:\/\/yt-dl\.org\/downloads\/(\d{4}\.\d\d\.\d\d(\.\d)?)\/youtube-dl/;
var url = 'https://rg3.github.io/youtube-dl/download.html';

function download(link, callback) {

  'use strict';
  var downloadFile = request.get(link);
  var status = null;

  downloadFile.on('response', function response(res) {
    if (res.statusCode !== 200) {
      status = new Error('Response Error: ' + res.statusCode);
      return;
    }
    downloadFile.pipe(fs.createWriteStream(filePath, {mode: 457}));
  });

  downloadFile.on('error', function error(err) { callback(err); });

  downloadFile.on('end', function end() { callback(status); });

}

function createBase(binDir) {
  'use strict';
  isWin = (process.platform === 'win32' || process.env.NODE_PLATFORM === 'windows') ? true : false;
  dir = (binDir) ? binDir : path.join(__dirname, '..', 'bin');
  mkdirp.sync(dir, {mode: 484});
  mkdirp.sync(dataPath, {mode: 484});
  filePath = path.join(dir, 'youtube-dl' + ((isWin) ? '.exe' : ''));
}

function savePath() {
  'use strict';
  fs.writeFileSync(path.join(dataPath, 'bin'), filePath, 'utf8');
}

function downloader(binDir, callback) {

  'use strict';
  if (typeof binDir === 'function') {
    callback = binDir;
    binDir = null;
  }

  createBase(binDir);

  var ytdlBinary = fs.readFileSync(pathEx.datadir(pkg.name) + '/bin').toString();

  var exists = fs.existsSync(ytdlBinary);

  request.get(url, function get(err, res, body) {

    if (err || res.statusCode !== 200) { return callback(err || new Error('Response Error: ' + res.statusCode)); }

    var m = regexp.exec(body);

    if (!m) { return callback(new Error('Could not find download link in ' + url)); }

    // Check if there is a new version available.
    var newVersion = m[1];
    var verpath  = path.join(dir, 'version');
    var oldVersion = fs.existsSync(verpath) && fs.readFileSync(verpath, 'utf8');

    if (newVersion === oldVersion && exists) { return callback(null, 'Already up to date ' + newVersion); }

    var link = m[0];
    if (isWin) { link += '.exe'; }

    download(link, function error(err) {
      if (err) { return callback(err); }
      fs.writeFileSync(verpath, newVersion);
      savePath();
      callback(null, 'Downloaded youtube-dl ' + newVersion);
    });

  });

}

module.exports = downloader;
<commit_msg>update path<commit_after>var fs    = require('fs');
var path  = require('path');
var mkdirp = require('mkdirp');
var request = require('request');
var pkg = require('../package');
var pathEx = require('path-extra');

// First, look for the download link.
/*jshint maxlen:false */
var dir, filePath, isWin;
var dataPath = pathEx.datadir(pkg.name);
var regexp = /https:\/\/yt-dl\.org\/downloads\/(\d{4}\.\d\d\.\d\d(\.\d)?)\/youtube-dl/;
var url = 'https://rg3.github.io/youtube-dl/download.html';

function download(link, callback) {

  'use strict';
  var downloadFile = request.get(link);
  var status = null;

  downloadFile.on('response', function response(res) {
    if (res.statusCode !== 200) {
      status = new Error('Response Error: ' + res.statusCode);
      return;
    }
    downloadFile.pipe(fs.createWriteStream(filePath, {mode: 457}));
  });

  downloadFile.on('error', function error(err) { callback(err); });

  downloadFile.on('end', function end() { callback(status); });

}

function createBase(binDir) {
  'use strict';
  isWin = (process.platform === 'win32' || process.env.NODE_PLATFORM === 'windows') ? true : false;
  dir = (binDir) ? binDir : path.join(__dirname, '..', 'bin');
  mkdirp.sync(dir, {mode: 484});
  mkdirp.sync(dataPath, {mode: 484});
  filePath = path.join(dir, 'youtube-dl' + ((isWin) ? '.exe' : ''));
}

function savePath() {
  'use strict';
  fs.writeFileSync(path.join(dataPath, 'bin'), filePath, 'utf8');
}

function downloader(binDir, callback) {

  'use strict';
  if (typeof binDir === 'function') {
    callback = binDir;
    binDir = null;
  }

  createBase(binDir);

  var ytdlBinary = fs.readFileSync(dataPath + '/bin').toString();

  var exists = fs.existsSync(ytdlBinary);

  request.get(url, function get(err, res, body) {

    if (err || res.statusCode !== 200) { return callback(err || new Error('Response Error: ' + res.statusCode)); }

    var m = regexp.exec(body);

    if (!m) { return callback(new Error('Could not find download link in ' + url)); }

    // Check if there is a new version available.
    var newVersion = m[1];
    var verpath  = path.join(dir, 'version');
    var oldVersion = fs.existsSync(verpath) && fs.readFileSync(verpath, 'utf8');

    if (newVersion === oldVersion && exists) { return callback(null, 'Already up to date ' + newVersion); }

    var link = m[0];
    if (isWin) { link += '.exe'; }

    download(link, function error(err) {
      if (err) { return callback(err); }
      fs.writeFileSync(verpath, newVersion);
      savePath();
      callback(null, 'Downloaded youtube-dl ' + newVersion);
    });

  });

}

module.exports = downloader;
<|endoftext|>


<commit_before>/*
 EnvJasmine: Jasmine test runner for EnvJS.

 EnvJasmine allows you to run headless JavaScript tests.

 Based on info from:
 http://agile.dzone.com/news/javascript-bdd-jasmine-without
 http://www.mozilla.org/rhino/
 http://www.envjs.com/
 http://pivotal.github.com/jasmine/
 https://github.com/velesin/jasmine-jquery
*/

importPackage(java.lang);
importPackage(java.io);
importPackage(org.mozilla.javascript);

// Create the EnvJasmine namespace
if (!this.EnvJasmine) {
    this.EnvJasmine = {};
}

EnvJasmine.cx = Context.getCurrentContext();
EnvJasmine.cx.setOptimizationLevel(-1);
EnvJasmine.topLevelScope = this;

EnvJasmine.about = function () {
    print("usage: envjasmine.js [options] [spec_file...]");
    print("");
    print("options:");
    print("     --configFile=<File>         Set a config file to run before specs are executed");
    print("     --disableColor              Disable console colors (colors are not available in Windows)");
    print("     --environment=<WIN|UNIX>    Set the environment to UNIX or Windows");
    print("     --help                      This list");
    print("     --incrementalOutput         Disable the ./F output and print results for each spec file");
    print("     --rootDir=<Dir>             Set the EnvJasmine root directory (REQUIRED)");
    print("     --suppressConsoleMsgs       Suppress window.console messages");
    print("     --testDir=<Dir>             Set the directory with the specs/ directory (REQUIRED)");
    print("     --customSpecsDir=<Dir>     Sets the name of the specs directory, default is 'specs'");
};

EnvJasmine.normalizePath = function(path) {
    var endsInSlash = (path.slice(-1) == "/");

    if (path.slice(0, 1) == ".") {
        path = EnvJasmine.projectRoot + "/" + path;
    }

    return File(path).getCanonicalPath() + (endsInSlash ? "/" : "");
};

EnvJasmine.loadFactory = function(scope) {
    return function (path) {
        var fileIn,
            normalizedPath = EnvJasmine.normalizePath(path);

        try {
            fileIn = new FileReader(normalizedPath);
            EnvJasmine.cx.evaluateReader(scope, fileIn, normalizedPath, 0, null);
        } catch (e) {
            print('Could not read file: ' + normalizedPath );
        } finally {
            fileIn.close();
        }
    };
};
EnvJasmine.loadGlobal = EnvJasmine.loadFactory(EnvJasmine.topLevelScope);

EnvJasmine.setRootDir = function (rootDir) {
    // These are standard directories in the EnvJasmine project.
    EnvJasmine.rootDir = EnvJasmine.normalizePath(rootDir);
    EnvJasmine.libDir = EnvJasmine.normalizePath(EnvJasmine.rootDir + "/lib/");
    EnvJasmine.includeDir = EnvJasmine.normalizePath(EnvJasmine.rootDir + "/include/");

    // This is the standard spec suffix
    EnvJasmine.specSuffix = new RegExp(/.spec.js$/);

    // Load the default dirs and files, these can be overridden with command line options
    EnvJasmine.configFile = EnvJasmine.normalizePath(EnvJasmine.includeDir + "dependencies.js");
};

EnvJasmine.setTestDir = function (testDir, override) {
    if (typeof EnvJasmine.testDir === "undefined" || !EnvJasmine.testDir || override) {
        EnvJasmine.testDir = EnvJasmine.normalizePath(testDir);
        EnvJasmine.mocksDir = EnvJasmine.normalizePath(EnvJasmine.testDir + "/mocks/");
        EnvJasmine.specsDir = EnvJasmine.normalizePath(EnvJasmine.testDir + "/specs/");
    }
};

// Process command line options

(function(argumentList) {
    var arg, nameValue, spec = "", specLoc;

    EnvJasmine.specs = [];
    EnvJasmine.passedCount = 0;
    EnvJasmine.failedCount = 0;
    EnvJasmine.totalCount = 0;

    for (var i = 0; i < argumentList.length; i++) {
        arg = argumentList[i];

        if (arg.slice(0, 2) == "--") {
            nameValue = arg.slice(2).split('=');

            switch(nameValue[0]) {
                case "testDir":
                    EnvJasmine.setTestDir(nameValue[1], true);
                    break;
                case "rootDir":
                    EnvJasmine.setRootDir(nameValue[1]);
                    EnvJasmine.setTestDir(nameValue[1]); // Set the root as the default testDir.
                    break;
                case "environment":
                    EnvJasmine.environment = nameValue[1];
                    break;
                case "configFile":
                    EnvJasmine.configFile = EnvJasmine.normalizePath(nameValue[1]);
                    break;
                case "disableColor":
                    EnvJasmine.disableColorOverride = true;
                    break;
                case "incrementalOutput":
                    EnvJasmine.incrementalOutput = true;
                    break;
                case "suppressConsoleMsgs":
                    EnvJasmine.suppressConsoleMsgs = true;
                    break;
                case "customSpecsDir":
                    EnvJasmine.customSpecsDir = nameValue[1];
                    break;
                case "help":
                    EnvJasmine.about();
                    System.exit(0);
                default:
                    print("Unknown option: " + arg);
                    break;
            }
        } else {
            if (arg.slice(-3) !== ".js") {
                spec += arg + " ";
            } else {
                spec += arg;
                if (arg[0] === "/" || (arg[1] === ":" && arg[2] === "\\")) {
                    specLoc = spec;
                } else {
                    specLoc = EnvJasmine.testDir + "/" + spec
                }
                print(specLoc);
                EnvJasmine.specs.push(EnvJasmine.normalizePath(specLoc));
                spec = "";
            }
        }
    }
}(arguments));

if (typeof EnvJasmine.customSpecsDir !== "undefined") {
    EnvJasmine.specsDir = EnvJasmine.normalizePath(EnvJasmine.testDir + EnvJasmine.customSpecsDir);
}

if (typeof EnvJasmine.rootDir == "undefined" || typeof EnvJasmine.environment == "undefined") {
    EnvJasmine.about();
    System.exit(1);
}

EnvJasmine.SEPARATOR = (function (env) {
    if (env == "UNIX") {
        return "/";
    } else if  (env == "WIN") {
        return "\\";
    } else {
        EnvJasmine.about();
        System.exit(1);
    }
}(EnvJasmine.environment));

EnvJasmine.disableColor = (function (env) {
    return EnvJasmine.disableColorOverride || (env == "WIN");
}(EnvJasmine.environment));

(function() {
    if (EnvJasmine.disableColor) {
        EnvJasmine.green = function(msg) { return msg; };
        EnvJasmine.red = function(msg) { return msg; };
        EnvJasmine.plain = function(msg) { return msg; };
    } else {
        var green = "\033[32m",
            red = "\033[31m",
            end = "\033[0m";

        EnvJasmine.green = function(msg) { return green + msg + end; };
        EnvJasmine.red = function(msg) { return red + msg + end; };
        EnvJasmine.plain = function(msg) { return msg; };
    }
}());
EnvJasmine.results = [];

EnvJasmine.loadConfig = function () {
    EnvJasmine.loadGlobal(EnvJasmine.configFile);
};

(function() {
    var i, fileIn, len;

    EnvJasmine.loadConfig();

    if (typeof EnvJasmine.reporterClass === "undefined") {
    	// Use the standard reporter
    	EnvJasmine.reporterClass = RhinoReporter;
    }

    jasmine.getEnv().addReporter(new EnvJasmine.reporterClass());

    if (EnvJasmine.suppressConsoleMsgs === true) {
        // suppress console messages
        window.console = $.extend({}, window.console, {
            info: jasmine.createSpy(),
            log: jasmine.createSpy(),
            debug: jasmine.createSpy(),
            warning: jasmine.createSpy(),
            error: jasmine.createSpy()
        });
    }

    EnvJasmine.loadGlobal(EnvJasmine.libDir + "spanDir/spanDir.js");
    if (EnvJasmine.specs.length == 0) {
        spanDir(EnvJasmine.specsDir, function(spec) {
            if (EnvJasmine.specSuffix.test(spec)) {
                EnvJasmine.specs.push(spec);
            }
        });
    }

    for (i = 0, len = EnvJasmine.specs.length >>> 0; i < len; i += 1) {
        try {
            EnvJasmine.currentScope = {};
            EnvJasmine.load = EnvJasmine.loadFactory(EnvJasmine.currentScope);
            EnvJasmine.specFile = EnvJasmine.specs[i];
            fileIn = new FileReader(EnvJasmine.specFile);
            EnvJasmine.cx.evaluateReader(EnvJasmine.currentScope, fileIn, EnvJasmine.specs[i], 0, null);
            EnvJasmine.cx.evaluateString(EnvJasmine.currentScope, 'window.location.assign(["file://", EnvJasmine.libDir, "envjasmine.html"].join(EnvJasmine.SEPARATOR));', 'Executing '+EnvJasmine.specs[i], 0, null);
        }
        catch (e) {
            print("Problem opening " + EnvJasmine.specFile + ": " + e);
        }
        finally {
            if(fileIn) {
                fileIn.close();
            }
        }
    }

    if (EnvJasmine.results.length > 0) {
        print("\n");
        print(EnvJasmine.red(EnvJasmine.results.join("\n\n")));
    }

    print();
    print(EnvJasmine[EnvJasmine.passedCount ? 'green' : 'plain']("Passed: " + EnvJasmine.passedCount));
    print(EnvJasmine[EnvJasmine.failedCount ? 'red' : 'plain']("Failed: " + EnvJasmine.failedCount));
    print(EnvJasmine.plain("Total : " + EnvJasmine.totalCount));

    if (EnvJasmine.failedCount > 0) {
        System.exit(1);
    }
}());
<commit_msg>'projectRoot' is now 'rootDir'<commit_after>/*
 EnvJasmine: Jasmine test runner for EnvJS.

 EnvJasmine allows you to run headless JavaScript tests.

 Based on info from:
 http://agile.dzone.com/news/javascript-bdd-jasmine-without
 http://www.mozilla.org/rhino/
 http://www.envjs.com/
 http://pivotal.github.com/jasmine/
 https://github.com/velesin/jasmine-jquery
*/

importPackage(java.lang);
importPackage(java.io);
importPackage(org.mozilla.javascript);

// Create the EnvJasmine namespace
if (!this.EnvJasmine) {
    this.EnvJasmine = {};
}

EnvJasmine.cx = Context.getCurrentContext();
EnvJasmine.cx.setOptimizationLevel(-1);
EnvJasmine.topLevelScope = this;

EnvJasmine.about = function () {
    print("usage: envjasmine.js [options] [spec_file...]");
    print("");
    print("options:");
    print("     --configFile=<File>         Set a config file to run before specs are executed");
    print("     --disableColor              Disable console colors (colors are not available in Windows)");
    print("     --environment=<WIN|UNIX>    Set the environment to UNIX or Windows");
    print("     --help                      This list");
    print("     --incrementalOutput         Disable the ./F output and print results for each spec file");
    print("     --rootDir=<Dir>             Set the EnvJasmine root directory (REQUIRED)");
    print("     --suppressConsoleMsgs       Suppress window.console messages");
    print("     --testDir=<Dir>             Set the directory with the specs/ directory (REQUIRED)");
    print("     --customSpecsDir=<Dir>     Sets the name of the specs directory, default is 'specs'");
};

EnvJasmine.normalizePath = function(path) {
    var endsInSlash = (path.slice(-1) == "/");

    if (path.slice(0, 1) == ".") {
        path = EnvJasmine.rootDir + "/" + path;
    }

    return File(path).getCanonicalPath() + (endsInSlash ? "/" : "");
};

EnvJasmine.loadFactory = function(scope) {
    return function (path) {
        var fileIn,
            normalizedPath = EnvJasmine.normalizePath(path);

        try {
            fileIn = new FileReader(normalizedPath);
            EnvJasmine.cx.evaluateReader(scope, fileIn, normalizedPath, 0, null);
        } catch (e) {
            print('Could not read file: ' + normalizedPath );
        } finally {
            fileIn.close();
        }
    };
};
EnvJasmine.loadGlobal = EnvJasmine.loadFactory(EnvJasmine.topLevelScope);

EnvJasmine.setRootDir = function (rootDir) {
    // These are standard directories in the EnvJasmine project.
    EnvJasmine.rootDir = EnvJasmine.normalizePath(rootDir);
    EnvJasmine.libDir = EnvJasmine.normalizePath(EnvJasmine.rootDir + "/lib/");
    EnvJasmine.includeDir = EnvJasmine.normalizePath(EnvJasmine.rootDir + "/include/");

    // This is the standard spec suffix
    EnvJasmine.specSuffix = new RegExp(/.spec.js$/);

    // Load the default dirs and files, these can be overridden with command line options
    EnvJasmine.configFile = EnvJasmine.normalizePath(EnvJasmine.includeDir + "dependencies.js");
};

EnvJasmine.setTestDir = function (testDir, override) {
    if (typeof EnvJasmine.testDir === "undefined" || !EnvJasmine.testDir || override) {
        EnvJasmine.testDir = EnvJasmine.normalizePath(testDir);
        EnvJasmine.mocksDir = EnvJasmine.normalizePath(EnvJasmine.testDir + "/mocks/");
        EnvJasmine.specsDir = EnvJasmine.normalizePath(EnvJasmine.testDir + "/specs/");
    }
};

// Process command line options

(function(argumentList) {
    var arg, nameValue, spec = "", specLoc;

    EnvJasmine.specs = [];
    EnvJasmine.passedCount = 0;
    EnvJasmine.failedCount = 0;
    EnvJasmine.totalCount = 0;

    for (var i = 0; i < argumentList.length; i++) {
        arg = argumentList[i];

        if (arg.slice(0, 2) == "--") {
            nameValue = arg.slice(2).split('=');

            switch(nameValue[0]) {
                case "testDir":
                    EnvJasmine.setTestDir(nameValue[1], true);
                    break;
                case "rootDir":
                    EnvJasmine.setRootDir(nameValue[1]);
                    EnvJasmine.setTestDir(nameValue[1]); // Set the root as the default testDir.
                    break;
                case "environment":
                    EnvJasmine.environment = nameValue[1];
                    break;
                case "configFile":
                    EnvJasmine.configFile = EnvJasmine.normalizePath(nameValue[1]);
                    break;
                case "disableColor":
                    EnvJasmine.disableColorOverride = true;
                    break;
                case "incrementalOutput":
                    EnvJasmine.incrementalOutput = true;
                    break;
                case "suppressConsoleMsgs":
                    EnvJasmine.suppressConsoleMsgs = true;
                    break;
                case "customSpecsDir":
                    EnvJasmine.customSpecsDir = nameValue[1];
                    break;
                case "help":
                    EnvJasmine.about();
                    System.exit(0);
                default:
                    print("Unknown option: " + arg);
                    break;
            }
        } else {
            if (arg.slice(-3) !== ".js") {
                spec += arg + " ";
            } else {
                spec += arg;
                if (arg[0] === "/" || (arg[1] === ":" && arg[2] === "\\")) {
                    specLoc = spec;
                } else {
                    specLoc = EnvJasmine.testDir + "/" + spec
                }
                print(specLoc);
                EnvJasmine.specs.push(EnvJasmine.normalizePath(specLoc));
                spec = "";
            }
        }
    }
}(arguments));

if (typeof EnvJasmine.customSpecsDir !== "undefined") {
    EnvJasmine.specsDir = EnvJasmine.normalizePath(EnvJasmine.testDir + EnvJasmine.customSpecsDir);
}

if (typeof EnvJasmine.rootDir == "undefined" || typeof EnvJasmine.environment == "undefined") {
    EnvJasmine.about();
    System.exit(1);
}

EnvJasmine.SEPARATOR = (function (env) {
    if (env == "UNIX") {
        return "/";
    } else if  (env == "WIN") {
        return "\\";
    } else {
        EnvJasmine.about();
        System.exit(1);
    }
}(EnvJasmine.environment));

EnvJasmine.disableColor = (function (env) {
    return EnvJasmine.disableColorOverride || (env == "WIN");
}(EnvJasmine.environment));

(function() {
    if (EnvJasmine.disableColor) {
        EnvJasmine.green = function(msg) { return msg; };
        EnvJasmine.red = function(msg) { return msg; };
        EnvJasmine.plain = function(msg) { return msg; };
    } else {
        var green = "\033[32m",
            red = "\033[31m",
            end = "\033[0m";

        EnvJasmine.green = function(msg) { return green + msg + end; };
        EnvJasmine.red = function(msg) { return red + msg + end; };
        EnvJasmine.plain = function(msg) { return msg; };
    }
}());
EnvJasmine.results = [];

EnvJasmine.loadConfig = function () {
    EnvJasmine.loadGlobal(EnvJasmine.configFile);
};

(function() {
    var i, fileIn, len;

    EnvJasmine.loadConfig();

    if (typeof EnvJasmine.reporterClass === "undefined") {
    	// Use the standard reporter
    	EnvJasmine.reporterClass = RhinoReporter;
    }

    jasmine.getEnv().addReporter(new EnvJasmine.reporterClass());

    if (EnvJasmine.suppressConsoleMsgs === true) {
        // suppress console messages
        window.console = $.extend({}, window.console, {
            info: jasmine.createSpy(),
            log: jasmine.createSpy(),
            debug: jasmine.createSpy(),
            warning: jasmine.createSpy(),
            error: jasmine.createSpy()
        });
    }

    EnvJasmine.loadGlobal(EnvJasmine.libDir + "spanDir/spanDir.js");
    if (EnvJasmine.specs.length == 0) {
        spanDir(EnvJasmine.specsDir, function(spec) {
            if (EnvJasmine.specSuffix.test(spec)) {
                EnvJasmine.specs.push(spec);
            }
        });
    }

    for (i = 0, len = EnvJasmine.specs.length >>> 0; i < len; i += 1) {
        try {
            EnvJasmine.currentScope = {};
            EnvJasmine.load = EnvJasmine.loadFactory(EnvJasmine.currentScope);
            EnvJasmine.specFile = EnvJasmine.specs[i];
            fileIn = new FileReader(EnvJasmine.specFile);
            EnvJasmine.cx.evaluateReader(EnvJasmine.currentScope, fileIn, EnvJasmine.specs[i], 0, null);
            EnvJasmine.cx.evaluateString(EnvJasmine.currentScope, 'window.location.assign(["file://", EnvJasmine.libDir, "envjasmine.html"].join(EnvJasmine.SEPARATOR));', 'Executing '+EnvJasmine.specs[i], 0, null);
        }
        catch (e) {
            print("Problem opening " + EnvJasmine.specFile + ": " + e);
        }
        finally {
            if(fileIn) {
                fileIn.close();
            }
        }
    }

    if (EnvJasmine.results.length > 0) {
        print("\n");
        print(EnvJasmine.red(EnvJasmine.results.join("\n\n")));
    }

    print();
    print(EnvJasmine[EnvJasmine.passedCount ? 'green' : 'plain']("Passed: " + EnvJasmine.passedCount));
    print(EnvJasmine[EnvJasmine.failedCount ? 'red' : 'plain']("Failed: " + EnvJasmine.failedCount));
    print(EnvJasmine.plain("Total : " + EnvJasmine.totalCount));

    if (EnvJasmine.failedCount > 0) {
        System.exit(1);
    }
}());
<|endoftext|>


<commit_before>
var util   = require("util"),
    path   = require("path"),
    Super  = require("./super");

function Unzip() {

};

module.exports = Unzip;

util.inherits(Unzip, Super);

Unzip.prototype.fileExtracted = false;

Unzip.prototype.fileName = null;

Unzip.prototype.options = {
    maxBuffer: 1024*1024
};

Unzip.prototype.exec = function()
{
    return this.doExec("unzip " + this.fileName + " -d " + this.output);
};

Unzip.prototype.onExecCallback = function(error, stdout, stderr)
{
    this.fileExtracted = (error === null);

    this.emit("exec");
};<commit_msg>Increased buffer size for unzip action and added error message<commit_after>
var util   = require("util"),
    path   = require("path"),
    evento = require("evento"),
    Super  = require("./super");

function Unzip() {

};

module.exports = Unzip;

util.inherits(Unzip, Super);

Unzip.prototype.fileExtracted = false;

Unzip.prototype.fileName = null;

Unzip.prototype.options = {
    maxBuffer: 1024*1024*1024
};

Unzip.prototype.exec = function()
{
    return this.doExec("unzip " + this.fileName + " -d " + this.output);
};

Unzip.prototype.onExecCallback = function(error, stdout, stderr)
{
    if (error !== null) {
        evento.trigger("INFORMER_ERROR", "unzip: " + error)
    }

    this.fileExtracted = (error === null);

    this.emit("exec");
};<|endoftext|>


<commit_before>/*
 * extsprintf.js: extended POSIX-style sprintf
 */

var mod_assert = require('assert');
var mod_util = require('util');

/*
 * Public interface
 */
exports.sprintf = jsSprintf;

/*
 * Stripped down version of s[n]printf(3c).  We make a best effort to throw an
 * exception when given a format string we don't understand, rather than
 * ignoring it, so that we won't break existing programs if/when we go implement
 * the rest of this.
 *
 * This implementation currently supports specifying
 *	- field alignment ('-' flag),
 * 	- zero-pad ('0' flag)
 *	- always show numeric sign ('+' flag),
 *	- field width
 *	- conversions for strings, decimal integers, and floats (numbers).
 *	- argument size specifiers.  These are all accepted but ignored, since
 *	  Javascript has no notion of the physical size of an argument.
 *
 * Everything else is currently unsupported, most notably precision, unsigned
 * numbers, non-decimal numbers, and characters.
 */
function jsSprintf(fmt)
{
	var regex = [
	    '([^%]*)',				/* normal text */
	    '%',				/* start of format */
	    '([\'\\-+ #0]*?)',			/* flags (optional) */
	    '([1-9]\\d*)?',			/* width (optional) */
	    '(\\.([1-9]\\d*))?',		/* precision (optional) */
	    '[lhjztL]*?',			/* length mods (ignored) */
	    '([diouxXfFeEgGaAcCsSp%jr])'	/* conversion */
	].join('');

	var re = new RegExp(regex);
	var args = Array.prototype.slice.call(arguments, 1);
	var flags, width, precision, conversion;
	var left, pad, sign, arg, match;
	var ret = '';
	var argn = 1;

	mod_assert.equal('string', typeof (fmt));

	while ((match = re.exec(fmt)) !== null) {
		ret += match[1];
		fmt = fmt.substring(match[0].length);

		flags = match[2] || '';
		width = match[3] || 0;
		precision = match[4] || '';
		conversion = match[6];
		left = false;
		sign = false;
		pad = ' ';

		if (conversion == '%') {
			ret += '%';
			continue;
		}

		if (args.length === 0)
			throw (new Error('too few args to sprintf'));

		arg = args.shift();
		argn++;

		if (flags.match(/[\' #]/))
			throw (new Error(
			    'unsupported flags: ' + flags));

		if (precision.length > 0)
			throw (new Error(
			    'non-zero precision not supported'));

		if (flags.match(/-/))
			left = true;

		if (flags.match(/0/))
			pad = '0';

		if (flags.match(/\+/))
			sign = true;

		switch (conversion) {
		case 's':
			if (arg === undefined || arg === null)
				throw (new Error('argument ' + argn +
				    ': attempted to print undefined or null ' +
				    'as a string'));
			ret += doPad(pad, width, left, arg.toString());
			break;

		case 'd':
			arg = Math.floor(arg);
			/*jsl:fallthru*/
		case 'f':
			sign = sign && arg > 0 ? '+' : '';
			ret += sign + doPad(pad, width, left,
			    arg.toString());
			break;

		case 'j': /* non-standard */
			if (width === 0)
				width = 10;
			ret += mod_util.inspect(arg, false, width);
			break;

		case 'r': /* non-standard */
			ret += dumpException(arg);
			break;

		default:
			throw (new Error('unsupported conversion: ' +
			    conversion));
		}
	}

	ret += fmt;
	return (ret);
}

function doPad(chr, width, left, str)
{
	var ret = str;

	while (ret.length < width) {
		if (left)
			ret += chr;
		else
			ret = chr + ret;
	}

	return (ret);
}

/*
 * This function dumps long stack traces for exceptions having a cause() method.
 * See node-verror for an example.
 */
function dumpException(ex)
{
	var ret;

	if (!(ex instanceof Error))
		throw (new Error(jsSprintf('invalid type for %%r: %j', ex)));

	/* Note that V8 prepends "ex.stack" with ex.toString(). */
	ret = 'EXCEPTION: ' + ex.constructor.name + ': ' + ex.stack;

	if (ex.cause && typeof (ex.cause) === 'function')
		ret += '\nCaused by: ' + dumpException(ex.cause());

	return (ret);
}
<commit_msg>fix ex.cause walk that ends in a 'ex.cause() === undefined'<commit_after>/*
 * extsprintf.js: extended POSIX-style sprintf
 */

var mod_assert = require('assert');
var mod_util = require('util');

/*
 * Public interface
 */
exports.sprintf = jsSprintf;

/*
 * Stripped down version of s[n]printf(3c).  We make a best effort to throw an
 * exception when given a format string we don't understand, rather than
 * ignoring it, so that we won't break existing programs if/when we go implement
 * the rest of this.
 *
 * This implementation currently supports specifying
 *	- field alignment ('-' flag),
 * 	- zero-pad ('0' flag)
 *	- always show numeric sign ('+' flag),
 *	- field width
 *	- conversions for strings, decimal integers, and floats (numbers).
 *	- argument size specifiers.  These are all accepted but ignored, since
 *	  Javascript has no notion of the physical size of an argument.
 *
 * Everything else is currently unsupported, most notably precision, unsigned
 * numbers, non-decimal numbers, and characters.
 */
function jsSprintf(fmt)
{
	var regex = [
	    '([^%]*)',				/* normal text */
	    '%',				/* start of format */
	    '([\'\\-+ #0]*?)',			/* flags (optional) */
	    '([1-9]\\d*)?',			/* width (optional) */
	    '(\\.([1-9]\\d*))?',		/* precision (optional) */
	    '[lhjztL]*?',			/* length mods (ignored) */
	    '([diouxXfFeEgGaAcCsSp%jr])'	/* conversion */
	].join('');

	var re = new RegExp(regex);
	var args = Array.prototype.slice.call(arguments, 1);
	var flags, width, precision, conversion;
	var left, pad, sign, arg, match;
	var ret = '';
	var argn = 1;

	mod_assert.equal('string', typeof (fmt));

	while ((match = re.exec(fmt)) !== null) {
		ret += match[1];
		fmt = fmt.substring(match[0].length);

		flags = match[2] || '';
		width = match[3] || 0;
		precision = match[4] || '';
		conversion = match[6];
		left = false;
		sign = false;
		pad = ' ';

		if (conversion == '%') {
			ret += '%';
			continue;
		}

		if (args.length === 0)
			throw (new Error('too few args to sprintf'));

		arg = args.shift();
		argn++;

		if (flags.match(/[\' #]/))
			throw (new Error(
			    'unsupported flags: ' + flags));

		if (precision.length > 0)
			throw (new Error(
			    'non-zero precision not supported'));

		if (flags.match(/-/))
			left = true;

		if (flags.match(/0/))
			pad = '0';

		if (flags.match(/\+/))
			sign = true;

		switch (conversion) {
		case 's':
			if (arg === undefined || arg === null)
				throw (new Error('argument ' + argn +
				    ': attempted to print undefined or null ' +
				    'as a string'));
			ret += doPad(pad, width, left, arg.toString());
			break;

		case 'd':
			arg = Math.floor(arg);
			/*jsl:fallthru*/
		case 'f':
			sign = sign && arg > 0 ? '+' : '';
			ret += sign + doPad(pad, width, left,
			    arg.toString());
			break;

		case 'j': /* non-standard */
			if (width === 0)
				width = 10;
			ret += mod_util.inspect(arg, false, width);
			break;

		case 'r': /* non-standard */
			ret += dumpException(arg);
			break;

		default:
			throw (new Error('unsupported conversion: ' +
			    conversion));
		}
	}

	ret += fmt;
	return (ret);
}

function doPad(chr, width, left, str)
{
	var ret = str;

	while (ret.length < width) {
		if (left)
			ret += chr;
		else
			ret = chr + ret;
	}

	return (ret);
}

/*
 * This function dumps long stack traces for exceptions having a cause() method.
 * See node-verror for an example.
 */
function dumpException(ex)
{
	var ret;

	if (!(ex instanceof Error))
		throw (new Error(jsSprintf('invalid type for %%r: %j', ex)));

	/* Note that V8 prepends "ex.stack" with ex.toString(). */
	ret = 'EXCEPTION: ' + ex.constructor.name + ': ' + ex.stack;

	if (ex.cause && typeof (ex.cause) === 'function') {
		var cex = ex.cause();
		if (cex) {
			ret += '\nCaused by: ' + dumpException(cex);
		}
	}

	return (ret);
}
<|endoftext|>


<commit_before>/*jshint laxcomma: true, smarttabs: true, node: true, unused: true*/
'use strict';
/**
 * resource field definitions
 * @module tastypie/fields/api
 * @author Eric Satterwhite
 * @since 0.0.1
 * @requires events
 * @requires path
 * @requires util
 * @requires mout/lang/isFunction
 * @requires mout/lang/isString
 * @requires mout/lang/kindOf
 * @requires mout/date/strftime
 * @requires mout/object/get
 * @requires tastypie/lib/class
 * @requires tastypie/lib/class/options
 * @requires tastypie/lib/class/parent
 */

var events         = require( 'events' )
  , util           = require( 'util' )
  , boom           = require( 'boom' )
  , get            = require( 'mout/object/get' )
  , isFunction     = require( 'mout/lang/isFunction' )
  , Class          = require( '../class' )
  , Options        = require( '../class/options' )
  , Parent         = require( '../class/parent' )
  , STRING         = 'string'
  , FUNCTION       = 'function'
  , ApiField
  ;

/**
 * Base field providing generic functionality around value serialization / deserialization
 * @constructor
 * @alias module:tastypie/fields/api
 * @param {Object} options
 * @param {Boolean} [options.readonly=false] Vales will be omitted during the hydration cycle
 * @param {Boolean} [options.nullable=false] true of the field should allow for a null vlaue
 * @param {?String|Function} [options.attribute=null] A name path or function to be used to extract values during dehydration
 * @param {String} [options.name=null] The name of the field. This is automatically set when added to a resource
 * @param {String} [options.help=A general no-op field] Help text to include in the schema defintion for this field
 * @param {!Mixed} [options.default=null] A default value for the field to fill in if none is provided
 * @mixes module:tastypie/lib/class/options
 * @mixes module:tastypie/lib/class/parent
 * @example var x = new tastypie/fields.ApiField();
 */
ApiField = new Class({
	inherits: events.EventEmitter
    , mixin:[ Parent, Options ]
    , options:{
		'readonly'  : false
	  , 'nullable'  : false
	  , 'attribute' : null
	  , 'default'   : null
	  , 'blank'     : false
	  , 'name'      : null
	  , 'exclude'   : false
	  , help:'A general no op field'
	}

	, constructor: function( options ){
		this.setOptions( options );
	}

	/**
	 * used to determine serialization type
	 * @private
	 * @method module:tastypie/fields/api#type
	 * @return {String} internal data type
	 **/
	, type: function( ){
		return 'string';
	}

	/**
	 * returns a sample of the format expected and returned by a field
	 * @method module:tastypie/fields/api#format
	 * @return {String|undefined} The format expected for a particular field type
	 **/
	,format: function(){

	}

	/**
	 * Converts data value into the serialization specific type.
	 * @method module:tastypie/fields/api#convert
	 * @param {Mixed} val value to convert
	 * @returns {Mixed} value
	 **/
	, convert: function convert( val ){
		return val;
	}

	/**
	 * Converts a serialized value in to a javascript object value
	 * @method module:tastypie/fields/api#hydrate
	 * @param {Bundle} bundle
	 **/
	, hydrate: function hydrate( bundle, cb ){
		var name = this.options.name
		  , attr = this.options.attribute
		  , obj  = bundle.object
		  ;

		// if readonly, don't care!
		if( this.options.readonly ){
			return cb && cb( null );
		}

		// if there is a value in data, return it.
		if( bundle.data.hasOwnProperty( name ) ){
			return cb && cb( null, bundle.data[ name ] );
		}

		// if bundle data doesn't have a matching property.
		// look for one.
		// NOTE: we can't use hasOwnProperty here because we care inherited properties
		if( attr && attr in obj ){
			return cb && cb( null, obj[ attr ] );
		} else if ( name && name in obj ){
			return cb && cb( null, obj[ name ] );
		}else if( this.options.hasOwnProperty( 'default' ) ){
			return cb && cb( null, isFunction( this.default ) ? this.default( bundle.data ) : this.default );
		} else if( this.options.nullable ){
			return cb && cb( null, null );
		} else {
			this.emit('error', boom.create(400, util.format( "Field %s has no data, default value and is not nullable ", this.options.name) ));
		}
	}

	/**
	 * Converts a javascript object / value into something sutable for seriaation. ex. Date formatting
	 * @method module:tastypie/fields/api#dehydrate
	 * @param {Object} object Object to dehydrate before serialization
	 * @param {Sting|Function} attribute a name path or function to use to retrieve a value from the object
	 * @return {Mixed} value object value converted to its internal type
	 **/
	, dehydrate: function dehydrate( obj, cb ){
		var current, attribute;
		attribute = this.options.attribute;

		if( typeof attribute === STRING ){
			current = get( obj, attribute );
			if( current == null ){
				if( this.options.hasOwnProperty( 'default' ) ){
					current = this.options.default;
				} else if( this.options.nullable ){
					current = null;
				}
			}
			current = typeof current === FUNCTION ? current( obj ) : current;
		} else if( typeof attribute === FUNCTION ){
			current = attribute();
		}
		return setImmediate(cb, null, this.convert( current ))
	}

	/**
	 * Injects dynamic properties onto field instance for later use
	 * @protected
	 * @method module:tastypie/fields/api#augment
	 * @param {Resource} resource the resource instance this field is attached to
	 * @param {String} name The property name this field is associated to
	 **/
	, augment: function augment( cls, name ){
		this.name = this.name || name;
		this.resource = this.resource || cls;
		return this;
	}
});

Object.defineProperties(ApiField.prototype,{
	default:{
		enumerable:false
		,writeable:false
		,get: function( ){
			return this.options.default;
		}
	}
});

module.exports = ApiField;
<commit_msg>documentation on the field option `exclude`<commit_after>/*jshint laxcomma: true, smarttabs: true, node: true, unused: true*/
'use strict';
/**
 * resource field definitions
 * @module tastypie/fields/api
 * @author Eric Satterwhite
 * @since 0.0.1
 * @requires events
 * @requires path
 * @requires util
 * @requires mout/lang/isFunction
 * @requires mout/lang/isString
 * @requires mout/lang/kindOf
 * @requires mout/date/strftime
 * @requires mout/object/get
 * @requires tastypie/lib/class
 * @requires tastypie/lib/class/options
 * @requires tastypie/lib/class/parent
 */

var events         = require( 'events' )
  , util           = require( 'util' )
  , boom           = require( 'boom' )
  , get            = require( 'mout/object/get' )
  , isFunction     = require( 'mout/lang/isFunction' )
  , Class          = require( '../class' )
  , Options        = require( '../class/options' )
  , Parent         = require( '../class/parent' )
  , STRING         = 'string'
  , FUNCTION       = 'function'
  , ApiField
  ;

/**
 * Base field providing generic functionality around value serialization / deserialization
 * @constructor
 * @alias module:tastypie/fields/api
 * @param {Object} options
 * @param {Boolean} [options.readonly=false] Vales will be omitted during the hydration cycle
 * @param {Boolean} [options.nullable=false] true of the field should allow for a null vlaue
 * @param {?String|Function} [options.attribute=null] A name path or function to be used to extract values during dehydration
 * @param {String} [options.name=null] The name of the field. This is automatically set when added to a resource
 * @param {String} [options.help=A general no-op field] Help text to include in the schema defintion for this field
 * @param {!Mixed} [options.default=null] A default value for the field to fill in if none is provided
 * @param {Boolean} [options.exclude=false] If true the field values will be excluded from dehydration & response payloads
 * @mixes module:tastypie/lib/class/options
 * @mixes module:tastypie/lib/class/parent
 * @example var x = new tastypie/fields.ApiField();
 */
ApiField = new Class({
	inherits: events.EventEmitter
    , mixin:[ Parent, Options ]
    , options:{
		'readonly'  : false
	  , 'nullable'  : false
	  , 'attribute' : null
	  , 'default'   : null
	  , 'blank'     : false
	  , 'name'      : null
	  , 'exclude'   : false
	  , help:'A general no op field'
	}

	, constructor: function( options ){
		this.setOptions( options );
	}

	/**
	 * used to determine serialization type
	 * @private
	 * @method module:tastypie/fields/api#type
	 * @return {String} internal data type
	 **/
	, type: function( ){
		return 'string';
	}

	/**
	 * returns a sample of the format expected and returned by a field
	 * @method module:tastypie/fields/api#format
	 * @return {String|undefined} The format expected for a particular field type
	 **/
	,format: function(){

	}

	/**
	 * Converts data value into the serialization specific type.
	 * @method module:tastypie/fields/api#convert
	 * @param {Mixed} val value to convert
	 * @returns {Mixed} value
	 **/
	, convert: function convert( val ){
		return val;
	}

	/**
	 * Converts a serialized value in to a javascript object value
	 * @method module:tastypie/fields/api#hydrate
	 * @param {Bundle} bundle
	 **/
	, hydrate: function hydrate( bundle, cb ){
		var name = this.options.name
		  , attr = this.options.attribute
		  , obj  = bundle.object
		  ;

		// if readonly, don't care!
		if( this.options.readonly ){
			return cb && cb( null );
		}

		// if there is a value in data, return it.
		if( bundle.data.hasOwnProperty( name ) ){
			return cb && cb( null, bundle.data[ name ] );
		}

		// if bundle data doesn't have a matching property.
		// look for one.
		// NOTE: we can't use hasOwnProperty here because we care inherited properties
		if( attr && attr in obj ){
			return cb && cb( null, obj[ attr ] );
		} else if ( name && name in obj ){
			return cb && cb( null, obj[ name ] );
		}else if( this.options.hasOwnProperty( 'default' ) ){
			return cb && cb( null, isFunction( this.default ) ? this.default( bundle.data ) : this.default );
		} else if( this.options.nullable ){
			return cb && cb( null, null );
		} else {
			this.emit('error', boom.create(400, util.format( "Field %s has no data, default value and is not nullable ", this.options.name) ));
		}
	}

	/**
	 * Converts a javascript object / value into something sutable for seriaation. ex. Date formatting
	 * @method module:tastypie/fields/api#dehydrate
	 * @param {Object} object Object to dehydrate before serialization
	 * @param {Sting|Function} attribute a name path or function to use to retrieve a value from the object
	 * @return {Mixed} value object value converted to its internal type
	 **/
	, dehydrate: function dehydrate( obj, cb ){
		var current, attribute;
		attribute = this.options.attribute;

		if( typeof attribute === STRING ){
			current = get( obj, attribute );
			if( current == null ){
				if( this.options.hasOwnProperty( 'default' ) ){
					current = this.options.default;
				} else if( this.options.nullable ){
					current = null;
				}
			}
			current = typeof current === FUNCTION ? current( obj ) : current;
		} else if( typeof attribute === FUNCTION ){
			current = attribute();
		}
		return setImmediate(cb, null, this.convert( current ))
	}

	/**
	 * Injects dynamic properties onto field instance for later use
	 * @protected
	 * @method module:tastypie/fields/api#augment
	 * @param {Resource} resource the resource instance this field is attached to
	 * @param {String} name The property name this field is associated to
	 **/
	, augment: function augment( cls, name ){
		this.name = this.name || name;
		this.resource = this.resource || cls;
		return this;
	}
});

Object.defineProperties(ApiField.prototype,{
	default:{
		enumerable:false
		,writeable:false
		,get: function( ){
			return this.options.default;
		}
	}
});

module.exports = ApiField;
<|endoftext|>


<commit_before>// Client script to find all the styles of a page and compute the position of the matching elements

(function(window){
  var document = window.document;

  //reinsert any cross domain restricted sheets
  var reinsert = []
  var sheets = document.styleSheets;
  for (var i=0; i < sheets.length; i++) {
    if(sheets[i].cssRules == null){
      reinsert.push(sheets[i]);
    }
  };
  for (var i=0; i < reinsert.length; i++) {
    var sheet = reinsert[i];

    var callback = function(){
      try {
        var newsheet = document.createElement('style');
            newsheet.setAttribute('type','text/css');
            newsheet.innerHTML = this.responseText;

        // insert before so that any relative images that will now fail
        // will be overridden
        sheet.ownerNode.parentNode.insertBefore(newsheet, sheet.ownerNode);
      } catch(e) {
        // alert(e); // "Error: SYNTAX_ERR: DOM Exception 12"
      }
    };

    var oXHR = new XMLHttpRequest();
    oXHR.onreadystatechange = function() {
      if (oXHR.readyState === 4) { callback.apply(oXHR); }
    };

    console.log(window._wtcss_prox + sheet.href);

    oXHR.open("GET", window._wtcss_prox + sheet.href, false);// synchronously
    oXHR.send(null);

  };

  // where we will put all the styles
  window._wtcss_styles = [];

  (function process(sheets,aggregated){

    for (var i=0; i < sheets.length; i++) {
      if(sheets[i].cssRules == null){
        // TODO - re-insert unavailable (cross domain) styles
        continue;
      }

      var rules = sheets[i].cssRules;

      for(var j = 0; j < rules.length; j++){
        var rule = rules[j];

        if(rule.selectorText){
          var rr = [rule.cssText];
          try {
            var elements = document.querySelectorAll(rule.selectorText);
            for(var k = 0; k < elements.length; k++){
             var offset = offsets(elements[k]);
             rr.push(offset);
            }
            aggregated.push(rr);
          } catch(e) {}
        }

        // recursively add @import styles
        if(rule.styleSheet){
          process([rule.styleSheet], aggregated);
        }
      }
    }

  })(document.styleSheets,window._wtcss_styles);

  // the full offsets of a given element
  // returns [top, left]
  function offsets(elem){
    if(!elem) return [0,0];
    var vals = offsets(elem.offsetParent);
    return [vals[0] + elem.offsetTop, vals[1] + elem.offsetLeft];
  };

})(window)<commit_msg>only use cors proxy when available, and limit @include depth<commit_after>// Client script to find all the styles of a page and compute the position of the matching elements
//
// results are stored in window._wtcss_styles

(function(window){
  var document = window.document;

  //reinsert any cross domain restricted sheets
  //if we have a proxy that we can request them through.
  if(window._wtcss_prox){

    var reinsert = []
    var sheets = document.styleSheets;
    for (var i=0; i < sheets.length; i++) {
      if(sheets[i].cssRules == null){
        reinsert.push(sheets[i]);
      }
    };
    for (var i=0; i < reinsert.length; i++) {
      var sheet = reinsert[i];

      var callback = function(){
        try {
          var newsheet = document.createElement('style');
              newsheet.setAttribute('type','text/css');
              newsheet.innerHTML = this.responseText;

          // insert before so that any relative images that will now fail
          // will be overridden
          sheet.ownerNode.parentNode.insertBefore(newsheet, sheet.ownerNode);
        } catch(e) {
          // alert(e); // "Error: SYNTAX_ERR: DOM Exception 12"
        }
      };

      var oXHR = new XMLHttpRequest();
      oXHR.onreadystatechange = function() {
        if (oXHR.readyState === 4) { callback.apply(oXHR); }
      };

      console.log(window._wtcss_prox + sheet.href);

      oXHR.open("GET", window._wtcss_prox + sheet.href, false);// synchronously
      oXHR.send(null);

    };

  }

  // where we will put all the styles
  window._wtcss_styles = [];

  (function process(sheets,aggregated,depth){
    if(depth > 3) return;

    for (var i=0; i < sheets.length; i++) {
      if(sheets[i].cssRules == null){
        // TODO - re-insert unavailable (cross domain) styles
        continue;
      }

      var rules = sheets[i].cssRules;

      for(var j = 0; j < rules.length; j++){
        var rule = rules[j];

        if(rule.selectorText){
          var rr = [rule.cssText];
          try {
            var elements = document.querySelectorAll(rule.selectorText);
            for(var k = 0; k < elements.length; k++){
             var offset = offsets(elements[k]);
             rr.push(offset);
            }
            aggregated.push(rr);
          } catch(e) {}
        }

        // recursively add @import styles
        if(rule.styleSheet){
          process([rule.styleSheet], aggregated, depth);
        }
      }
    }

  })(document.styleSheets,window._wtcss_styles,0);

  // the full offsets of a given element
  // returns [top, left]
  function offsets(elem){
    if(!elem) return [0,0];
    var vals = offsets(elem.offsetParent);
    return [vals[0] + elem.offsetTop, vals[1] + elem.offsetLeft];
  };

})(window)<|endoftext|>