<commit_before>import _ from 'lodash/fp';

import {
  UPDATE_PROFILE_FIELDS,
  PROFILE_LOADING_FINISHED,
  FETCHING_LATEST_MHV_TERMS,
  FETCHING_LATEST_MHV_TERMS_SUCCESS,
  FETCHING_LATEST_MHV_TERMS_FAILURE,
  ACCEPTING_LATEST_MHV_TERMS,
  ACCEPTING_LATEST_MHV_TERMS_SUCCESS,
  ACCEPTING_LATEST_MHV_TERMS_FAILURE,
} from '../actions';
import { UPDATE_LOGGEDIN_STATUS, FETCH_LOGIN_URLS_FAILED } from '../../login/actions';

// TODO(crew): Romove before this goes to production.
const initialState = {
  userFullName: {
    first: null,
    middle: null,
    last: null,
    suffix: null,
  },
  email: null,
  dob: null,
  gender: null,
  accountType: null,
  terms: {
    loading: false,
    terms: {},
  },
  savedForms: [],
  prefillsAvailable: [],
  loading: true
};

function profileInformation(state = initialState, action) {
  switch (action.type) {
    case UPDATE_PROFILE_FIELDS: {
      return _.assign(state, action.newState);
    }
    case PROFILE_LOADING_FINISHED: {
      return _.set('loading', false, state);
    }
    case FETCH_LOGIN_URLS_FAILED: {
      return _.set('loading', false, state);
    }
    case UPDATE_LOGGEDIN_STATUS: {
      return _.set('loading', false, state);
    }
    case FETCHING_LATEST_MHV_TERMS: {
      return {
        ...state,
        terms: {
          ...state.terms,
          content: {},
          loading: true,
        }
      };
    }
    case FETCHING_LATEST_MHV_TERMS_SUCCESS: {
      return {
        ...state,
        terms: {
          ...state.terms,
          ...action.terms,
          loading: false,
        }
      };
    }
    case FETCHING_LATEST_MHV_TERMS_FAILURE: {
      return {
        ...state,
        terms: {
          loading: false,
        }
      };
    }
    case ACCEPTING_LATEST_MHV_TERMS: {
      return state;
    }
    case ACCEPTING_LATEST_MHV_TERMS_SUCCESS: {
      return {
        ...state,
        terms: {
          loading: false,
        }
      };
    }
    case ACCEPTING_LATEST_MHV_TERMS_FAILURE: {
      return {
        ...state,
        terms: {
          ...state.terms,
          loading: false,
        }
      };
    }
    default:
      return state;
  }
}

export default profileInformation;
<commit_msg>Refactored user-profile reducer.<commit_after>import { assign, set } from 'lodash/fp';

import {
  UPDATE_PROFILE_FIELDS,
  PROFILE_LOADING_FINISHED,
  FETCHING_LATEST_MHV_TERMS,
  FETCHING_LATEST_MHV_TERMS_SUCCESS,
  FETCHING_LATEST_MHV_TERMS_FAILURE,
  ACCEPTING_LATEST_MHV_TERMS,
  ACCEPTING_LATEST_MHV_TERMS_SUCCESS,
  ACCEPTING_LATEST_MHV_TERMS_FAILURE,
} from '../actions';
import { UPDATE_LOGGEDIN_STATUS, FETCH_LOGIN_URLS_FAILED } from '../../login/actions';

const initialState = {
  userFullName: {
    first: null,
    middle: null,
    last: null,
    suffix: null,
  },
  email: null,
  dob: null,
  gender: null,
  accountType: null,
  terms: {
    loading: false
  },
  savedForms: [],
  prefillsAvailable: [],
  loading: true
};

function profileInformation(state = initialState, action) {
  switch (action.type) {
    case UPDATE_PROFILE_FIELDS:
      return assign(state, action.newState);

    case PROFILE_LOADING_FINISHED:
    case FETCH_LOGIN_URLS_FAILED:
    case UPDATE_LOGGEDIN_STATUS:
      return set('loading', false, state);

    case FETCHING_LATEST_MHV_TERMS:
      return set('terms.loading', true, state);

    case FETCHING_LATEST_MHV_TERMS_SUCCESS: {
      return set('terms', {
        ...initialState.terms,
        ...action.terms,
        loading: false,
      }, state);
    }

    case FETCHING_LATEST_MHV_TERMS_FAILURE: {
      return set('terms', {
        ...initialState.terms,
        loading: false,
      }, state);
    }

    case ACCEPTING_LATEST_MHV_TERMS: {
      return set('terms.loading', true, state);
    }

    case ACCEPTING_LATEST_MHV_TERMS_SUCCESS:
    case ACCEPTING_LATEST_MHV_TERMS_FAILURE: {
      return set('terms.loading', false, state);
    }

    default:
      return state;
  }
}

export default profileInformation;
<|endoftext|>


<commit_before>const json = JSON.parse(require("fs").readFileSync("./package.json", "utf8"));
delete json.devDependencies;
let deps = json.dependencies;
json.dependencies = {};
json.prodDependencies.forEach(e => {
  json.dependencies[e] = deps[e];
})
delete json.prodDependencies;
delete json.main;
delete json.scripts;
json.bin = "./index.js";
require("fs").writeFileSync("./dist/package.json", JSON.stringify(json, null, 2), "utf8");
<commit_msg>Add comments to build-package-json<commit_after>const json = JSON.parse(require("fs").readFileSync("./package.json", "utf8"));
// delete dev deps
delete json.devDependencies;
// carry over dependencies required for the production build
let deps = json.dependencies;
json.dependencies = {};
json.prodDependencies.forEach(e => {
  json.dependencies[e] = deps[e];
})
// remove keys not used in production
delete json.prodDependencies;
delete json.main;
delete json.scripts;
//set the webpack output as the bin file
json.bin = "./index.js";
//save to the output directory
require("fs").writeFileSync("./dist/package.json", JSON.stringify(json, null, 2), "utf8");
<|endoftext|>


<commit_before>'use strict';
var _fs = require('fs');
var _path = require('path');

var async = require('async');
var webpack = require('webpack');

var utils = require('./utils');
var webpackConfig = require('../config/build');

var cwd = process.cwd();

module.exports = function(o, cb) {
  if(o.task === 'copy_assets') {
    utils.copyIfExists.apply(null, o.params.concat([cb]));
  }
  else if(o.task === 'write_main') {
    writeMain(o.params, cb);
  }
  else if(o.task === 'copy_extra_assets') {
    utils.copyExtraAssets.apply(null, o.params.concat([cb]));
  }
  else if(o.task === 'write') {
    write(o.params, cb);
  }
  else if(o.task === 'write_pages') {
    writePages(o.params, cb);
  }
  else {
    cb();
  }
};

function writeMain(params, cb) {
  var assetsDir = params.assetsDir;
  var mainPath = params.mainPath;

  _fs.exists(mainPath, function(exists) {
    if(!exists) {
      return cb();
    }

    _fs.readFile(mainPath, function(err, data) {
      if(err) {
        return cb(err);
      }

      _fs.writeFile(_path.join(assetsDir, 'main.css'), data, cb);
    });
  });
}

function writePages(params, cb) {
  var cwd = process.cwd();

  try {
    var config = require(_path.join(cwd, 'antwar.config.js'));
  }
  catch(err) {
    return cb(err);
  }

  webpackConfig(config).then(function(c) {
    webpack(c, function(err) {
      if(err) {
        return cb(err);
      }

      var renderPage = require(_path.join(cwd, './.antwar/build/bundleStaticPage.js'));

      async.each(params.pages, function(page, cb) {
        // XXX: why page can be null?
        if(page) {
          renderPage(page.page, function(err, html) {
            if(err) {
              return cb(err);
            }

            write({
              path: page.path,
              data: html
            }, cb);
          });
        }
        else {
          cb();
        }
      }, cb);
    });
  }).catch(cb);
}

function write(params, cb) {
  _fs.writeFile(params.path, params.data, cb);
}
<commit_msg>Add build logging<commit_after>'use strict';
var _fs = require('fs');
var _path = require('path');

var async = require('async');
var webpack = require('webpack');

var utils = require('./utils');
var webpackConfig = require('../config/build');

var cwd = process.cwd();

module.exports = function(o, cb) {
  if(o.task === 'copy_assets') {
    utils.copyIfExists.apply(null, o.params.concat([cb]));
  }
  else if(o.task === 'write_main') {
    writeMain(o.params, cb);
  }
  else if(o.task === 'copy_extra_assets') {
    utils.copyExtraAssets.apply(null, o.params.concat([cb]));
  }
  else if(o.task === 'write') {
    write(o.params, cb);
  }
  else if(o.task === 'write_pages') {
    writePages(o.params, cb);
  }
  else {
    cb();
  }
};

function writeMain(params, cb) {
  var assetsDir = params.assetsDir;
  var mainPath = params.mainPath;

  _fs.exists(mainPath, function(exists) {
    if(!exists) {
      return cb();
    }

    _fs.readFile(mainPath, function(err, data) {
      if(err) {
        return cb(err);
      }

      _fs.writeFile(_path.join(assetsDir, 'main.css'), data, cb);
    });
  });
}

function writePages(params, cb) {
  var cwd = process.cwd();

  try {
    var config = require(_path.join(cwd, 'antwar.config.js'));
  }
  catch(err) {
    return cb(err);
  }

  webpackConfig(config).then(function(c) {
    webpack(c, function(err) {
      if(err) {
        return cb(err);
      }

      var renderPage = require(_path.join(cwd, './.antwar/build/bundleStaticPage.js'));

      async.each(params.pages, function(page, cb) {
        // XXX: why page can be null?
        if(page) {
          // TODO: use user defined logger instead
          console.log('Starting to write page', page.page);

          renderPage(page.page, function(err, html) {
            if(err) {
              return cb(err);
            }

            write({
              path: page.path,
              data: html
            }, function(err) {
              if(err) {
                return cb(err);
              }

              // TODO: use user defined logger instead
              console.log('Finished writing page', page.page);

              cb();
            });
          });
        }
        else {
          cb();
        }
      }, cb);
    });
  }).catch(cb);
}

function write(params, cb) {
  _fs.writeFile(params.path, params.data, cb);
}
<|endoftext|>


<commit_before>#!/usr/bin/env node
;(function() {
  'use strict';

  /** Load Node modules */
  var exec = require('child_process').exec,
      fs = require('fs'),
      https = require('https'),
      path = require('path'),
      tar = require('../vendor/tar/tar.js'),
      zlib = require('zlib');

  /** The path of the directory that is the base of the repository */
  var basePath = fs.realpathSync(path.join(__dirname, '..'));

  /** The path of the `vendor` directory */
  var vendorPath = path.join(basePath, 'vendor');

  /** The Git object ID of `closure-compiler.tar.gz` */
  var closureId = 'a2787b470c577cee2404d186c562dd9835f779f5';

  /** The Git object ID of `uglifyjs.tar.gz` */
  var uglifyId = '7ecae09d413eb48dd5785fe877f24e60ac3bbcef';

  /** The media type for raw blob data */
  var mediaType = 'application/vnd.github.v3.raw';

  /** Reassign `existsSync` for older versions of Node */
  fs.existsSync || (fs.existsSync = path.existsSync);

  /** Used to reference parts of the blob href */
  var location = (function() {
    var host = 'api.github.com',
        origin = 'https://api.github.com',
        pathname = '/repos/bestiejs/lodash/git/blobs';

    return {
      'host': host,
      'href': host + origin + pathname,
      'origin': origin,
      'pathname': pathname
    };
  }());

  /*--------------------------------------------------------------------------*/

  /**
   * Fetches a required `.tar.gz` dependency with the given Git object ID from
   * the Lo-Dash repo on GitHub. The object ID may be obtained by running
   * `git hash-object path/to/dependency.tar.gz`.
   *
   * @private
   * @param {Object} options The options object.
   *  id - The Git object ID of the `.tar.gz` file.
   *  onComplete - The function, invoked with one argument (exception),
   *   called once the extraction has finished.
   *  path - The path of the extraction directory.
   *  title - The dependency's title used in status updates logged to the console.
   */
  function getDependency(options) {
    options || (options = {});

    var id = options.id,
        onComplete = options.onComplete,
        path = options.path,
        title = options.title;

    function callback(exception) {
      if (exception) {
        console.error([
          'There was a problem installing ' + title + '. To manually install, run:',
          '',
          "curl -H 'Accept: " + mediaType + "' " + location.href + '/' + id + " | tar xvz -C '" + path + "'"
        ].join('\n'));
      }
      onComplete(exception);
    }

    console.log('Downloading ' + title + '...');

    https.get({
      'host': location.host,
      'path': location.pathname + '/' + id,
      'headers': {
        // By default, all GitHub blob API endpoints return a JSON document
        // containing Base64-encoded blob data. Overriding the `Accept` header
        // with the GitHub raw media type returns the blob data directly.
        // See http://developer.github.com/v3/media/.
        'Accept': mediaType
      }
    }, function(response) {
      var decompressor = zlib.createUnzip(),
          parser = new tar.Extract({ 'path': path });

      decompressor.on('error', callback)
      parser.on('end', callback).on('error', callback);
      response.pipe(decompressor).pipe(parser);
    })
    .on('error', callback);
  }

  /*--------------------------------------------------------------------------*/

  exec('npm -g root', function(exception, stdout) {
    if (!exception) {
      try {
        var root = stdout.trim(),
            isGlobal = fs.existsSync(root) && path.resolve(basePath, '..') == fs.realpathSync(root);
      } catch(e) {
        exception = e;
      }
    }
    if (exception) {
      console.error([
        'Oops! There was a problem detecting the install mode. If you’re installing the',
        'Lo-Dash command-line executable (via `npm install -g lodash`), you’ll need to',
        'manually install UglifyJS and the Closure Compiler by running:',
        '',
        "curl -H 'Accept: " + mediaType + "' " + location.href + '/' + closureId + " | tar xvz -C '" + vendorPath + "'",
        "curl -H 'Accept: " + mediaType + "' " + location.href + '/' + uglifyId  + " | tar xvz -C '" + vendorPath + "'",
        '',
        'Please submit an issue on the GitHub issue tracker: ' + process.env.npm_package_bugs_url
      ].join('\n'));

      console.error(exception);
    }
    if (!isGlobal) {
      return;
    }
    // download the Closure Compiler
    getDependency({
      'title': 'the Closure Compiler',
      'id': closureId,
      'path': vendorPath,
      'onComplete': function() {
        // download UglifyJS
        getDependency({
          'title': 'UglifyJS',
          'id': uglifyId,
          'path': vendorPath,
          'onComplete': function() {
            process.exit();
          }
        });
      }
    });
  });
}());
<commit_msg>Use `child_process.execFile` instead of `child_process.exec` in `post-install.js`.<commit_after>#!/usr/bin/env node
;(function() {
  'use strict';

  /** Load Node modules */
  var execFile = require('child_process').execFile,
      fs = require('fs'),
      https = require('https'),
      path = require('path'),
      tar = require('../vendor/tar/tar.js'),
      zlib = require('zlib');

  /** The path of the directory that is the base of the repository */
  var basePath = fs.realpathSync(path.join(__dirname, '..'));

  /** The path of the `vendor` directory */
  var vendorPath = path.join(basePath, 'vendor');

  /** The Git object ID of `closure-compiler.tar.gz` */
  var closureId = 'a2787b470c577cee2404d186c562dd9835f779f5';

  /** The Git object ID of `uglifyjs.tar.gz` */
  var uglifyId = '505f1be36ef60fd25a992a522f116d5179ab317f';

  /** The media type for raw blob data */
  var mediaType = 'application/vnd.github.v3.raw';

  /** Used to reference parts of the blob href */
  var location = (function() {
    var host = 'api.github.com',
        origin = 'https://api.github.com',
        pathname = '/repos/bestiejs/lodash/git/blobs';

    return {
      'host': host,
      'href': host + origin + pathname,
      'origin': origin,
      'pathname': pathname
    };
  }());

  /** The message to display when the install mode is undetectable */
  var oopsMessage = [
    'Oops! There was a problem detecting the install mode. If you’re installing the',
    'Lo-Dash command-line executable (via `npm install -g lodash`), you’ll need to',
    'manually install UglifyJS and the Closure Compiler by running:',
    '',
    "curl -H 'Accept: " + mediaType + "' " + location.href + '/' + closureId + " | tar xvz -C '" + vendorPath + "'",
    "curl -H 'Accept: " + mediaType + "' " + location.href + '/' + uglifyId  + " | tar xvz -C '" + vendorPath + "'",
    '',
    'Please submit an issue on the GitHub issue tracker: ' + process.env.npm_package_bugs_url
  ].join('\n');

  /** Reassign `existsSync` for older versions of Node */
  fs.existsSync || (fs.existsSync = path.existsSync);

  /*--------------------------------------------------------------------------*/

  /**
   * Fetches a required `.tar.gz` dependency with the given Git object ID from
   * the Lo-Dash repo on GitHub. The object ID may be obtained by running
   * `git hash-object path/to/dependency.tar.gz`.
   *
   * @private
   * @param {Object} options The options object.
   *  id - The Git object ID of the `.tar.gz` file.
   *  onComplete - The function, invoked with one argument (exception),
   *   called once the extraction has finished.
   *  path - The path of the extraction directory.
   *  title - The dependency's title used in status updates logged to the console.
   */
  function getDependency(options) {
    options || (options = {});

    var id = options.id,
        onComplete = options.onComplete,
        path = options.path,
        title = options.title;

    function callback(exception) {
      if (exception) {
        console.error([
          'There was a problem installing ' + title + '. To manually install, run:',
          '',
          "curl -H 'Accept: " + mediaType + "' " + location.href + '/' + id + " | tar xvz -C '" + path + "'"
        ].join('\n'));
      }
      onComplete(exception);
    }

    console.log('Downloading ' + title + '...');

    https.get({
      'host': location.host,
      'path': location.pathname + '/' + id,
      'headers': {
        // By default, all GitHub blob API endpoints return a JSON document
        // containing Base64-encoded blob data. Overriding the `Accept` header
        // with the GitHub raw media type returns the blob data directly.
        // See http://developer.github.com/v3/media/.
        'Accept': mediaType
      }
    }, function(response) {
      var decompressor = zlib.createUnzip(),
          parser = new tar.Extract({ 'path': path });

      decompressor.on('error', callback)
      parser.on('end', callback).on('error', callback);
      response.pipe(decompressor).pipe(parser);
    })
    .on('error', callback);
  }

  /**
   * The `child_process.execFile` callback.
   *
   * @private
   * @param {Object|Undefined} exception The error object.
   * @param {String} stdout The stdout buffer.
   */
  function onExecFile(exception, stdout) {
    if (!exception) {
      try {
        var root = stdout.trim(),
            isGlobal = fs.existsSync(root) && path.resolve(basePath, '..') == fs.realpathSync(root);
      } catch(e) {
        exception = e;
      }
    }
    if (exception) {
      console.error(oopsMessage);
      console.error(exception);
    }
    if (!isGlobal) {
      return;
    }
    // download the Closure Compiler
    getDependency({
      'title': 'the Closure Compiler',
      'id': closureId,
      'path': vendorPath,
      'onComplete': function() {
        // download UglifyJS
        getDependency({
          'title': 'UglifyJS',
          'id': uglifyId,
          'path': vendorPath,
          'onComplete': function() {
            process.exit();
          }
        });
      }
    });
  }

  /*--------------------------------------------------------------------------*/

  try {
    execFile('npm', [ '-g', 'root' ], onExecFile);
  } catch(e) {
    console.error(oopsMessage);
    console.error(e);
  }
}());
<|endoftext|>


<commit_before>var T = require("./timbre.debug.js");
var assert = require("chai").assert;

var EventEmitter = timbre.modules.EventEmitter;

describe("EventEmitter", function() {
    it("new", function() {
        var e = new EventEmitter();
        assert.instanceOf(e, EventEmitter);
    });
    it("new with context", function() {
        var e = new EventEmitter(this);
        assert.equal(e.context, this);
    });
    it(".on is an alias of .addListener", function() {
        var e = new EventEmitter();
        assert.equal(e.addListener, e.on);
    });
    it("addListener", function() {
        var e = new EventEmitter();
        var emitted = 0;
        e.on("hello", function() {
            emitted++;
        });
        e.emit("hello");
        e.emit("hello");
        e.emit("hello");
        e.emit("hello");
        assert.equal(emitted, 4);
    });
    it("once", function() {
        var e = new EventEmitter();
        var emitted = 0;
        e.once("hello", function() {
            emitted++;
        });
        e.emit("hello");
        e.emit("hello");
        e.emit("hello");
        e.emit("hello");
        assert.equal(emitted, 1);
    });
    it("removeListener", function() {
        var e = new EventEmitter();
        var emitted = 0;
        var f1 = function() {
            assert(false, "on->foo(1) should not be emitted");
        };
        var f2 = function() {
            assert(false, "on->foo(2) should not be emitted");
        };
        var f3 = function() {
            emitted++;
        };
        e.on("foo", f1);
        e.on("foo", f2);
        e.on("foo", f3);
        e.removeListener("foo", f1);
        e.removeListener("foo", f2);
        assert.equal(e.listeners("foo").length, 1);
        e.emit("foo");
        assert.equal(emitted, 1);
    });
    it("once removeListener", function() {
        var e = new EventEmitter();
        var emitted = 0;
        var f1 = function() {
            assert(false, "once->foo(1) should not be emitted");
        };
        var f2 = function() {
            assert(false, "once->foo(2) should not be emitted");
        };
        var f3 = function() {
            emitted++;
        };
        e.once("foo", f1);
        e.once("foo", f2);
        e.once("foo", f3);
        e.removeListener("foo", f1);
        e.removeListener("foo", f2);
        assert.equal(e.listeners("foo").length, 1);
        e.emit("foo");
        e.emit("foo");
        assert.equal(emitted, 1);
    });
    it("removeAllListeners", function() {
        var e = new EventEmitter();
        var f1 = function() {
            assert(false, "on->foo(1) should not be emitted");
        };
        var f2 = function() {
            assert(false, "on->foo(2) should not be emitted");
        };
        var f3 = function() {
            assert(false, "on->foo(3) should not be emitted");
        };
        e.on("foo", f1);
        e.on("foo", f2);
        e.once("foo", f3);
        e.removeAllListeners("foo");
        assert.equal(e.listeners("foo").length, 0);
        e.emit("foo");
        assert(true);
    });
    it("listeners", function() {
        var e = new EventEmitter();
        var f1 = function() {
            assert(false, "on->foo(1) should not be emitted");
        };
        var f2 = function() {
            assert(false, "on->foo(2) should not be emitted");
        };
        var f3 = function() {
            assert(false, "on->foo(3) should not be emitted");
        };
        e.on("foo", f1);
        e.on("foo", f2);
        e.on("foo", f3);
        var list = e.listeners("foo");
        assert.deepEqual(list, [f1, f2, f3]);
    });
    it("emit with args", function() {
        var e = new EventEmitter();
        var emitted = 0;
        e.on("hello", function(a, b) {
            assert.equal(a, "world");
            assert.equal(b, "!!");
            emitted++;
        });
        e.emit("hello", "world", "!!");
        e.emit("hello", "world", "!!");
        assert.equal(emitted, 2);
    });
    it("emit with context", function() {
        var context = {};
        var e = new EventEmitter(context);
        var emitted = 0;
        e.on("hello", function() {
            assert.equal(this, context)
            emitted++;
        });
        e.emit("hello");
        assert.equal(emitted, 1);
    });
    it("once emit with args", function() {
        var e = new EventEmitter();
        var emitted = 0;
        e.once("hello", function(a, b) {
            assert.equal(a, "world");
            assert.equal(b, "!!");
            emitted++;
        });
        e.emit("hello", "world", "!!");
        e.emit("hello", "world", "!!");
        assert.equal(emitted, 1);
    });
    it("once emit with context", function() {
        var context = {};
        var e = new EventEmitter(context);
        var emitted = 0;
        e.once("hello", function() {
            assert.equal(this, context)
            emitted++;
        });
        e.emit("hello");
        e.emit("hello");
        assert.equal(emitted, 1);
    });
    describe("T-Object", function() {
        it("addListener", function() {
            var emitted = 0;
            var t = T(10).on("bang", function() {
                emitted++;
            });
            var e = new EventEmitter();
            e.on("hello", t);
            e.emit("hello");
            e.emit("hello");
            e.emit("hello");
            e.emit("hello");
            assert.equal(emitted, 4);
        });
        it("once", function() {
            var emitted = 0;
            var t = T(10).on("bang", function() {
                emitted++;
            });
            var e = new EventEmitter();
            e.once("hello", t);
            e.emit("hello");
            e.emit("hello");
            e.emit("hello");
            e.emit("hello");
            assert.equal(emitted, 1);
        });
        it("removeListener", function() {
            var emitted = 0;
            var t1 = T(10).on("bang", function() {
                assert(false, "on->foo(1) should not be emitted");
            });
            var t2 = T(10).on("bang", function() {
                assert(false, "on->foo(2) should not be emitted");
            });
            var t3 = T(10).on("bang", function() {
                emitted++;
            });
            var e = new EventEmitter();
            e.on("foo", t1);
            e.on("foo", t2);
            e.on("foo", t3);
            e.removeListener("foo", t1);
            e.removeListener("foo", t2);
            assert.equal(e.listeners("foo").length, 1);
            e.emit("foo");
            e.emit("foo");
            assert.equal(emitted, 2);
        });
        it("once removeListener", function() {
            var emitted = 0;
            var t1 = T(10).on("bang", function() {
                assert(false, "on->foo(1) should not be emitted");
            });
            var t2 = T(10).on("bang", function() {
                assert(false, "on->foo(2) should not be emitted");
            });
            var t3 = T(10).on("bang", function() {
                emitted++;
            });
            var e = new EventEmitter();
            e.once("foo", t1);
            e.once("foo", t2);
            e.once("foo", t3);
            e.removeListener("foo", t1);
            e.removeListener("foo", t2);
            assert.equal(e.listeners("foo").length, 1);
            e.emit("foo");
            e.emit("foo");
            assert.equal(emitted, 1);
        });
        it("removeAllListeners", function() {
            var t1 = T(10).on("bang", function() {
                assert(false, "on->foo(1) should not be emitted");
            });
            var t2 = T(10).on("bang", function() {
                assert(false, "on->foo(2) should not be emitted");
            });
            var t3 = T(10).on("bang", function() {
                assert(false, "on->foo(3) should not be emitted");
            });
            var e = new EventEmitter();
            e.on("foo", t1);
            e.on("foo", t2);
            e.once("foo", t3);
            e.removeAllListeners("foo");
            assert.equal(e.listeners("foo").length, 0);
            e.emit("foo");
            assert(true);
        });
        it("listeners", function() {
            var e = new EventEmitter();
            var t1 = T(10).on("bang", function() {
                assert(false, "on->foo(1) should not be emitted");
            });
            var t2 = T(10).on("bang", function() {
                assert(false, "on->foo(2) should not be emitted");
            });
            var t3 = T(10).on("bang", function() {
                assert(false, "on->foo(3) should not be emitted");
            });
            e.on("foo", t1);
            e.on("foo", t2);
            e.on("foo", t3);
            var list = e.listeners("foo");
            assert.deepEqual(list, [t1, t2, t3]);
        });
        it("emit with args", function() {
            var emitted = 0;
            var t = T(10).on("bang", function(a) {
                emitted++;
                assert.equal(a, 100);
            });
            var e = new EventEmitter();
            e.on("hello", t);
            e.emit("hello", 100);
            assert.equal(emitted, 1);
        });
        it("emit with context", function() {
            var context = {};
            var emitted = 0;
            var t = T(10).on("bang", function() {
                assert.notEqual(this, context);
                assert.equal(this, t)
                emitted++;
            });
            var e = new EventEmitter(context);
            e.on("hello", t);
            e.emit("hello");
            assert.equal(emitted, 1);
        });
        it("once emit with args", function() {
            var emitted = 0;
            var t = T(10).on("bang", function(a) {
                emitted++;
                assert.equal(a, 100);
            });
            var e = new EventEmitter();
            e.once("hello", t);
            e.emit("hello", 100);
            e.emit("hello", 200);
            assert.equal(emitted, 1);
        });
        it("once emit with context", function() {
            var context = {};
            var emitted = 0;
            var t = T(10).on("bang", function() {
                assert.notEqual(this, context);
                assert.equal(this, t)
                emitted++;
            });
            var e = new EventEmitter(context);
            e.once("hello", t);
            e.emit("hello");
            e.emit("hello");
            assert.equal(emitted, 1);
        });
    });
});
<commit_msg>update test<commit_after>var T = require("./timbre.debug.js");
var assert = require("chai").assert;

var EventEmitter = timbre.modules.EventEmitter;

describe("EventEmitter", function() {
    it("new", function() {
        var e = new EventEmitter();
        assert.instanceOf(e, EventEmitter);
    });
    it("new with context", function() {
        var e = new EventEmitter(this);
        assert.equal(e.context, this);
    });
    it("on", function() {
        var e = new EventEmitter();
        var emitted = 0;
        e.on("hello", function() {
            emitted++;
        });
        e.emit("hello");
        e.emit("hello");
        e.emit("hello");
        e.emit("hello");
        assert.equal(emitted, 4);
    });
    it("once", function() {
        var e = new EventEmitter();
        var emitted = 0;
        e.once("hello", function() {
            emitted++;
        });
        e.emit("hello");
        e.emit("hello");
        e.emit("hello");
        e.emit("hello");
        assert.equal(emitted, 1);
    });
    it("off", function() {
        var e = new EventEmitter();
        var emitted = 0;
        var f1 = function() {
            assert(false, "on->foo(1) should not be emitted");
        };
        var f2 = function() {
            assert(false, "on->foo(2) should not be emitted");
        };
        var f3 = function() {
            emitted++;
        };
        e.on("foo", f1);
        e.on("foo", f2);
        e.on("foo", f3);
        e.off("foo", f1);
        e.off("foo", f2);
        assert.equal(e.listeners("foo").length, 1);
        e.emit("foo");
        assert.equal(emitted, 1);
    });
    it("once removeListener", function() {
        var e = new EventEmitter();
        var emitted = 0;
        var f1 = function() {
            assert(false, "once->foo(1) should not be emitted");
        };
        var f2 = function() {
            assert(false, "once->foo(2) should not be emitted");
        };
        var f3 = function() {
            emitted++;
        };
        e.once("foo", f1);
        e.once("foo", f2);
        e.once("foo", f3);
        e.off("foo", f1);
        e.off("foo", f2);
        assert.equal(e.listeners("foo").length, 1);
        e.emit("foo");
        e.emit("foo");
        assert.equal(emitted, 1);
    });
    it("removeAllListeners", function() {
        var e = new EventEmitter();
        var f1 = function() {
            assert(false, "on->foo(1) should not be emitted");
        };
        var f2 = function() {
            assert(false, "on->foo(2) should not be emitted");
        };
        var f3 = function() {
            assert(false, "on->foo(3) should not be emitted");
        };
        e.on("foo", f1);
        e.on("foo", f2);
        e.once("foo", f3);
        e.removeAllListeners("foo");
        assert.equal(e.listeners("foo").length, 0);
        e.emit("foo");
        assert(true);
    });
    it("listeners", function() {
        var e = new EventEmitter();
        var f1 = function() {
            assert(false, "on->foo(1) should not be emitted");
        };
        var f2 = function() {
            assert(false, "on->foo(2) should not be emitted");
        };
        var f3 = function() {
            assert(false, "on->foo(3) should not be emitted");
        };
        e.on("foo", f1);
        e.on("foo", f2);
        e.on("foo", f3);
        var list = e.listeners("foo");
        assert.deepEqual(list, [f1, f2, f3]);
    });
    it("emit with args", function() {
        var e = new EventEmitter();
        var emitted = 0;
        e.on("hello", function(a, b) {
            assert.equal(a, "world");
            assert.equal(b, "!!");
            emitted++;
        });
        e.emit("hello", "world", "!!");
        e.emit("hello", "world", "!!");
        assert.equal(emitted, 2);
    });
    it("emit with context", function() {
        var context = {};
        var e = new EventEmitter(context);
        var emitted = 0;
        e.on("hello", function() {
            assert.equal(this, context)
            emitted++;
        });
        e.emit("hello");
        assert.equal(emitted, 1);
    });
    it("once emit with args", function() {
        var e = new EventEmitter();
        var emitted = 0;
        e.once("hello", function(a, b) {
            assert.equal(a, "world");
            assert.equal(b, "!!");
            emitted++;
        });
        e.emit("hello", "world", "!!");
        e.emit("hello", "world", "!!");
        assert.equal(emitted, 1);
    });
    it("once emit with context", function() {
        var context = {};
        var e = new EventEmitter(context);
        var emitted = 0;
        e.once("hello", function() {
            assert.equal(this, context)
            emitted++;
        });
        e.emit("hello");
        e.emit("hello");
        assert.equal(emitted, 1);
    });
    describe("T-Object", function() {
        it("addListener", function() {
            var emitted = 0;
            var t = T(10).on("bang", function() {
                emitted++;
            });
            var e = new EventEmitter();
            e.on("hello", t);
            e.emit("hello");
            e.emit("hello");
            e.emit("hello");
            e.emit("hello");
            assert.equal(emitted, 4);
        });
        it("once", function() {
            var emitted = 0;
            var t = T(10).on("bang", function() {
                emitted++;
            });
            var e = new EventEmitter();
            e.once("hello", t);
            e.emit("hello");
            e.emit("hello");
            e.emit("hello");
            e.emit("hello");
            assert.equal(emitted, 1);
        });
        it("removeListener", function() {
            var emitted = 0;
            var t1 = T(10).on("bang", function() {
                assert(false, "on->foo(1) should not be emitted");
            });
            var t2 = T(10).on("bang", function() {
                assert(false, "on->foo(2) should not be emitted");
            });
            var t3 = T(10).on("bang", function() {
                emitted++;
            });
            var e = new EventEmitter();
            e.on("foo", t1);
            e.on("foo", t2);
            e.on("foo", t3);
            e.off("foo", t1);
            e.off("foo", t2);
            assert.equal(e.listeners("foo").length, 1);
            e.emit("foo");
            e.emit("foo");
            assert.equal(emitted, 2);
        });
        it("once removeListener", function() {
            var emitted = 0;
            var t1 = T(10).on("bang", function() {
                assert(false, "on->foo(1) should not be emitted");
            });
            var t2 = T(10).on("bang", function() {
                assert(false, "on->foo(2) should not be emitted");
            });
            var t3 = T(10).on("bang", function() {
                emitted++;
            });
            var e = new EventEmitter();
            e.once("foo", t1);
            e.once("foo", t2);
            e.once("foo", t3);
            e.off("foo", t1);
            e.off("foo", t2);
            assert.equal(e.listeners("foo").length, 1);
            e.emit("foo");
            e.emit("foo");
            assert.equal(emitted, 1);
        });
        it("removeAllListeners", function() {
            var t1 = T(10).on("bang", function() {
                assert(false, "on->foo(1) should not be emitted");
            });
            var t2 = T(10).on("bang", function() {
                assert(false, "on->foo(2) should not be emitted");
            });
            var t3 = T(10).on("bang", function() {
                assert(false, "on->foo(3) should not be emitted");
            });
            var e = new EventEmitter();
            e.on("foo", t1);
            e.on("foo", t2);
            e.once("foo", t3);
            e.removeAllListeners("foo");
            assert.equal(e.listeners("foo").length, 0);
            e.emit("foo");
            assert(true);
        });
        it("listeners", function() {
            var e = new EventEmitter();
            var t1 = T(10).on("bang", function() {
                assert(false, "on->foo(1) should not be emitted");
            });
            var t2 = T(10).on("bang", function() {
                assert(false, "on->foo(2) should not be emitted");
            });
            var t3 = T(10).on("bang", function() {
                assert(false, "on->foo(3) should not be emitted");
            });
            e.on("foo", t1);
            e.on("foo", t2);
            e.on("foo", t3);
            var list = e.listeners("foo");
            assert.deepEqual(list, [t1, t2, t3]);
        });
        it("emit with args", function() {
            var emitted = 0;
            var t = T(10).on("bang", function(a) {
                emitted++;
                assert.equal(a, 100);
            });
            var e = new EventEmitter();
            e.on("hello", t);
            e.emit("hello", 100);
            assert.equal(emitted, 1);
        });
        it("emit with context", function() {
            var context = {};
            var emitted = 0;
            var t = T(10).on("bang", function() {
                assert.notEqual(this, context);
                assert.equal(this, t)
                emitted++;
            });
            var e = new EventEmitter(context);
            e.on("hello", t);
            e.emit("hello");
            assert.equal(emitted, 1);
        });
        it("once emit with args", function() {
            var emitted = 0;
            var t = T(10).on("bang", function(a) {
                emitted++;
                assert.equal(a, 100);
            });
            var e = new EventEmitter();
            e.once("hello", t);
            e.emit("hello", 100);
            e.emit("hello", 200);
            assert.equal(emitted, 1);
        });
        it("once emit with context", function() {
            var context = {};
            var emitted = 0;
            var t = T(10).on("bang", function() {
                assert.notEqual(this, context);
                assert.equal(this, t)
                emitted++;
            });
            var e = new EventEmitter(context);
            e.once("hello", t);
            e.emit("hello");
            e.emit("hello");
            assert.equal(emitted, 1);
        });
    });
});
<|endoftext|>


<commit_before>var like_button = document.getElementsByClassName('recsGamepad__button--like');

var counter = 0;
var random = 0;
var liked_profiles = 0;

(function next() {
    if (counter++ >= 300) return;
    setTimeout(function() {
	try {
        like_button[0].click();
	} catch(TypeError) {}
        next();
	console.log("Liked "+liked_profiles+" profiles")
	liked_profiles = liked_profiles + 1
    }, 200);
})();<commit_msg>Liking until likes is run out<commit_after>var like_button = document.getElementsByClassName('recsGamepad__button--like');
var nolikesmodal = document.getElementsByClassName('modalManager');

var counter = 0;
var random = 0;
var liked_profiles = 0;

(function next() {
    if(nolikesmodal) console.log("Out of likes"); return;
    //if (counter++ >= 300) return;
    setTimeout(function() {
	try {
        like_button[0].click();
	} catch(TypeError) {}
        next();
	console.log("Liked "+liked_profiles+" profiles")
	liked_profiles = liked_profiles + 1
    }, 200);
})();<|endoftext|>


<commit_before>/* eslint-env mocha */

var chai
if (typeof chai === 'undefined') {
  chai = require('chai')
  var chaiGenerator = require('..')
  chai.use(chaiGenerator)
}

var DEFAULT_RETURN = 'retoin'
var DEFAULT_YIELD = 'yeild'

function * createCounter () {
  var i = 0
  while (1) {
    yield i++
  }
}

function * createReturnOnly () {
  return DEFAULT_RETURN
}

function * createNtimes (n) {
  for (var i = 0; i < n; i++) {
    yield DEFAULT_YIELD
  }
  return DEFAULT_RETURN
}

function * createEcho (echo) {
  while (1) {
    echo = yield echo
  }
}

describe('expect()', function () {
  describe('.to.yield()', function () {
    it('works with { value: "val", done: false }', function () {
      var next = { value: 'val', done: false }
      chai.expect(next).to.yield()
    })
  })

  describe('.to.yield(value)', function () {
    it('works with { value: undefined, done: false }', function () {
      var next = { value: undefined, done: false }
      chai.expect(next).to.yield(undefined)
    })

    it('works with counting generator', function () {
      var generator = createCounter()
      chai.expect(generator).to.yield(0)
      chai.expect(generator).to.yield(1)
      chai.expect(generator).to.yield(2)
      chai.expect(generator).to.yield(3)
      chai.expect(generator).to.yield(4)
      chai.expect(generator).to.yield(5)
    })

    it('works with ntimes generator', function () {
      var generator = createNtimes(3)
      chai.expect(generator).to.yield(DEFAULT_YIELD)
      chai.expect(generator).to.yield(DEFAULT_YIELD)
      chai.expect(generator).to.yield(DEFAULT_YIELD)
    })
  })

  describe('.to.yield().equals(value)', function () {
    it('works with { value: "val", done: false }', function () {
      var next = { value: 'val', done: false }
      chai.expect(next).to.yield().equals('val')
    })
  })

  describe('.to.deep.yield(value)', function () {
    it('works with { value: "val", done: false }', function () {
      var next = { value: 'val', done: false }
      chai.expect(next).to.deep.yield('val')
    })

    it('works with { value: ["deep", "equals"], done: false }', function () {
      var next = { value: ['deep', 'equals'], done: false }
      chai.expect(next).to.deep.yield(['deep', 'equals'])
    })
  })

  describe('.not.to.yield(value)', function () {
    it('works with { value: "val", done: false }', function () {
      var next = { value: 'val', done: false }
      chai.expect(next).not.to.yield('foo')
    })

    it('works when yielding the wrong value', function () {
      var generator = createCounter()
      chai.expect(generator).not.to.yield(4)
      chai.expect(generator).not.to.yield(-1)
    })

    it('works when returning', function () {
      var generator = createReturnOnly()
      chai.expect(generator).not.to.yield(DEFAULT_RETURN)
    })

    it('works when deep yielding', function () {
      var next = { value: ['deep', 'equals'], done: false }
      chai.expect(next).not.to.yield(['deep', 'equals'])
    })
  })

  describe('.to.return()', function () {
    it('works with { value: "val", done: true }', function () {
      var next = { value: 'val', done: true }
      chai.expect(next).to.return()
    })
  })

  describe('.to.return(value)', function () {
    it('works with { value: "val", done: true }', function () {
      var next = { value: 'val', done: true }
      chai.expect(next).to.return('val')
    })

    it('works with return only generator', function () {
      var generator = createReturnOnly()
      chai.expect(generator).to.return(DEFAULT_RETURN)
    })

    it('works with ntimes generator', function () {
      var generator = createNtimes(4)
      generator.next()
      generator.next()
      generator.next()
      generator.next()
      chai.expect(generator).to.return(DEFAULT_RETURN)
    })
  })

  describe('.to.return().equals(value)', function () {
    it('works with { value: "val", done: true }', function () {
      var next = { value: 'val', done: true }
      chai.expect(next).to.return().equals('val')
    })
  })

  describe('.not.to.return(value)', function () {
    it('works with { value: "val", done: true }', function () {
      var next = { value: 'val', done: true }
      chai.expect(next).not.to.return('foo')
    })

    it('works when return the wrong value', function () {
      var generator = createReturnOnly()
      chai.expect(generator).not.to.return('fail')
    })

    it('works when yielding', function () {
      var generator = createCounter()
      chai.expect(generator).not.to.return(0)
      chai.expect(generator).not.to.return(1)
    })
  })

  describe('.next(parameter)', function () {
    describe('.to.yield(value)', function () {
      it('works with echo generator', function () {
        var generator = createEcho(1)
        chai.expect(generator.next()).to.yield(1)
        chai.expect(generator.next(4)).to.yield(4)
        chai.expect(generator.next('foo')).to.yield('foo')
        chai.expect(generator).to.yield(undefined)
      })
    })
  })
})
<commit_msg>Promote ".and.equal" chain syntax<commit_after>/* eslint-env mocha */

var chai
if (typeof chai === 'undefined') {
  chai = require('chai')
  var chaiGenerator = require('..')
  chai.use(chaiGenerator)
}

var DEFAULT_RETURN = 'retoin'
var DEFAULT_YIELD = 'yeild'

function * createCounter () {
  var i = 0
  while (1) {
    yield i++
  }
}

function * createReturnOnly () {
  return DEFAULT_RETURN
}

function * createNtimes (n) {
  for (var i = 0; i < n; i++) {
    yield DEFAULT_YIELD
  }
  return DEFAULT_RETURN
}

function * createEcho (echo) {
  while (1) {
    echo = yield echo
  }
}

describe('expect()', function () {
  describe('.to.yield()', function () {
    it('works with { value: "val", done: false }', function () {
      var next = { value: 'val', done: false }
      chai.expect(next).to.yield()
    })
  })

  describe('.to.yield(value)', function () {
    it('works with { value: undefined, done: false }', function () {
      var next = { value: undefined, done: false }
      chai.expect(next).to.yield(undefined)
    })

    it('works with counting generator', function () {
      var generator = createCounter()
      chai.expect(generator).to.yield(0)
      chai.expect(generator).to.yield(1)
      chai.expect(generator).to.yield(2)
      chai.expect(generator).to.yield(3)
      chai.expect(generator).to.yield(4)
      chai.expect(generator).to.yield(5)
    })

    it('works with ntimes generator', function () {
      var generator = createNtimes(3)
      chai.expect(generator).to.yield(DEFAULT_YIELD)
      chai.expect(generator).to.yield(DEFAULT_YIELD)
      chai.expect(generator).to.yield(DEFAULT_YIELD)
    })
  })

  describe('.to.yield().and.equal(value)', function () {
    it('works with { value: "val", done: false }', function () {
      var next = { value: 'val', done: false }
      chai.expect(next).to.yield().and.equal('val')
    })
  })

  describe('.to.deep.yield(value)', function () {
    it('works with { value: "val", done: false }', function () {
      var next = { value: 'val', done: false }
      chai.expect(next).to.deep.yield('val')
    })

    it('works with { value: ["deep", "equals"], done: false }', function () {
      var next = { value: ['deep', 'equals'], done: false }
      chai.expect(next).to.deep.yield(['deep', 'equals'])
    })
  })

  describe('.not.to.yield(value)', function () {
    it('works with { value: "val", done: false }', function () {
      var next = { value: 'val', done: false }
      chai.expect(next).not.to.yield('foo')
    })

    it('works when yielding the wrong value', function () {
      var generator = createCounter()
      chai.expect(generator).not.to.yield(4)
      chai.expect(generator).not.to.yield(-1)
    })

    it('works when returning', function () {
      var generator = createReturnOnly()
      chai.expect(generator).not.to.yield(DEFAULT_RETURN)
    })

    it('works when deep yielding', function () {
      var next = { value: ['deep', 'equals'], done: false }
      chai.expect(next).not.to.yield(['deep', 'equals'])
    })
  })

  describe('.to.return()', function () {
    it('works with { value: "val", done: true }', function () {
      var next = { value: 'val', done: true }
      chai.expect(next).to.return()
    })
  })

  describe('.to.return(value)', function () {
    it('works with { value: "val", done: true }', function () {
      var next = { value: 'val', done: true }
      chai.expect(next).to.return('val')
    })

    it('works with return only generator', function () {
      var generator = createReturnOnly()
      chai.expect(generator).to.return(DEFAULT_RETURN)
    })

    it('works with ntimes generator', function () {
      var generator = createNtimes(4)
      generator.next()
      generator.next()
      generator.next()
      generator.next()
      chai.expect(generator).to.return(DEFAULT_RETURN)
    })
  })

  describe('.to.return().and.equal(value)', function () {
    it('works with { value: "val", done: true }', function () {
      var next = { value: 'val', done: true }
      chai.expect(next).to.return().and.equal('val')
    })
  })

  describe('.not.to.return(value)', function () {
    it('works with { value: "val", done: true }', function () {
      var next = { value: 'val', done: true }
      chai.expect(next).not.to.return('foo')
    })

    it('works when return the wrong value', function () {
      var generator = createReturnOnly()
      chai.expect(generator).not.to.return('fail')
    })

    it('works when yielding', function () {
      var generator = createCounter()
      chai.expect(generator).not.to.return(0)
      chai.expect(generator).not.to.return(1)
    })
  })

  describe('.next(parameter)', function () {
    describe('.to.yield(value)', function () {
      it('works with echo generator', function () {
        var generator = createEcho(1)
        chai.expect(generator.next()).to.yield(1)
        chai.expect(generator.next(4)).to.yield(4)
        chai.expect(generator.next('foo')).to.yield('foo')
        chai.expect(generator).to.yield(undefined)
      })
    })
  })
})
<|endoftext|>


<commit_before>var recurse = require('../');
var test = require('tap').test;
var fs = require('fs');
var mkdirp = require('mkdirp');
var rimraf = require('rimraf');

function createFixtures(prefix) {
  mkdirp.sync(prefix + '-filter/sub');
  mkdirp.sync(prefix + '-filter/sub2');
  fs.openSync(prefix + '-filter/1.txt', 'w');
  fs.openSync(prefix + '-filter/2.tar.gz', 'w');
  fs.openSync(prefix + '-filter/sub/3.txt', 'w');
  fs.openSync(prefix + '-filter/sub2/4.jpg', 'w');
}

test('relname filter', function (t) {
  createFixtures('relname');

  t.plan(2);

  var flat = recurse('relname-filter', function(relname, stat) {
    return !stat.isDirectory() && relname.match(/\.txt$/)
  });
  flat.on('data', function(data) {
    t.ok(data.match(/\d\.txt/));
  });
  flat.on('end', function() {
    rimraf.sync('relname-filter');
  });
});

test('stat filter', function (t) {
  createFixtures('stat');

  t.plan(2);

  var flat = recurse('stat-filter', function(relname, stat) {
    return !stat.isDirectory() && relname.match(/\.txt$/)
  });
  flat.on('data', function(data) {
    t.ok(data.match(/\d\.txt/));
  });
  flat.on('end', function() {
    rimraf.sync('stat-filter');
  });
});
<commit_msg>Cleanup filter tests.<commit_after>var recurse = require('../');
var test = require('tap').test;
var fs = require('fs');
var mkdirp = require('mkdirp');
var rimraf = require('rimraf');

function createFixtures(d) {
  mkdirp.sync(d + '/sub');
  mkdirp.sync(d + '/sub2');
  fs.openSync(d + '/1.txt', 'w');
  fs.openSync(d + '/2.tar.gz', 'w');
  fs.openSync(d + '/sub/3.txt', 'w');
  fs.openSync(d + '/sub2/4.jpg', 'w');
}

test('filter txts', function (t) {
  var d = 'filter-txts';
  createFixtures(d);

  t.plan(3);

  var writes = 0;

  var flat = recurse(d, function(relname, stat) {
    return !stat.isDirectory() && relname.match(/\.txt$/);
  });
  flat.on('data', function(data) {
    t.ok(data.match(/\d\.txt/));
    writes++;
  });
  flat.on('end', function() {
    t.equal(writes, 2);
    rimraf.sync(d);
  });
});

test('filter dirs', function (t) {
  var d = 'filter-dirs';
  createFixtures(d);

  t.plan(3);

  var writes = 0;

  var flat = recurse(d, function(relname, stat) {
    return stat.isDirectory();
  });
  flat.on('data', function(data) {
    t.ok(data.match(new RegExp('^' + d + '/sub\\d?$')));
    writes++;
  });
  flat.on('end', function() {
    t.equal(writes, 2);
    rimraf.sync(d);
  });
});
<|endoftext|>


<commit_before>/*
 * to-asciidoc - an HTML to Asciidoc converter
 *
 * Copyright 2015, asciidocfx
 * Licenced under the MIT licence
 *
 */

if (typeof he !== 'object' && typeof require === 'function') {
    var he = require('he');
}

var nbspRegex = new RegExp(String.fromCharCode(160), "g");

var toAsciidoc = function (string) {

    string= string.replace(nbspRegex, " ");

    var all = document.createElement("div");
    all.innerHTML = string;

    // fix for apple converted space
    var spans = all.querySelectorAll("span.Apple-converted-space");
    for (var i = 0; i < spans.length; i++) {
        var parentNode = spans[i].parentNode || "";
        if (parentNode)
            parentNode.replaceChild(document.createTextNode(" "), spans[i]);
    }

    // table converter
    var tables = all.querySelectorAll("table");
    for (var i = 0; i < tables.length; i++) {
        var tablePrefix = "\n\n|====\n";
        var tableSuffix = "|====\n";
        var tableText = "";
        tableText += tablePrefix;
        var table = tables[i];
        var trs = table.querySelectorAll("tr");

        for (var j = 0; j < trs.length; j++) {
            var tr = trs[j];
            var columns = tr.querySelectorAll("td");
            if (columns.length == 0)
                columns = tr.querySelectorAll("th");
            var row = [].slice.call(columns).map(function (e) {
                return "|" + e.textContent || e.innerText || "";
            }).join(" ");
            tableText += row + "\n";
        }

        tableText += tableSuffix;

        if (table.parentNode)
            table.parentNode.replaceChild(document.createTextNode(tableText), table);
    }

    // fix pre > code block
    var codes = all.querySelectorAll("pre > code");
    for (var i = 0; i < codes.length; i++) {
        var code = codes[i];
        var innerCode = strip(code.innerHTML);
        var pre = code.parentNode;
        if (pre.parentNode)
            pre.parentNode.replaceChild(document.createTextNode("\n\n[source,java]\n----\n" + innerCode + "\n----\n\n"), pre);

    }

    // remove anchor surrounding an img
    var images = all.querySelectorAll("img");
    for (var i = 0; i < images.length; i++) {
        var parentNode = images[i].parentNode || "";
        if (parentNode.parentNode)
            if (parentNode.constructor == HTMLAnchorElement)
                parentNode.parentNode.replaceChild(images[i], parentNode);
    }
    string = all.innerHTML;

    var ELEMENTS = [
        {
            patterns: 'p',
            replacement: function (str, attrs, innerHTML) {
                return innerHTML ? '\n\n' + innerHTML + '\n' : '';
            }
        },
        {
            patterns: 'br',
            type: 'void',
            replacement: '  \n'
        },
        {
            patterns: 'h([1-6])',
            replacement: function (str, hLevel, attrs, innerHTML) {
                var hPrefix = '';
                for (var i = 0; i < hLevel; i++) {
                    hPrefix += '=';
                }
                return '\n\n' + hPrefix + ' ' + innerHTML + '\n';
            }
        },
        {
            patterns: 'hr',
            type: 'void',
            replacement: "\n\n'''\n"
        },
        {
            patterns: 'a',
            replacement: function (str, attrs, innerHTML) {
                var href = attrs.match(attrRegExp('href')),
                    title = attrs.match(attrRegExp('title'));

                return href ? href[1] + '[' + innerHTML + ']' : '';
                //return href ? '[' + innerHTML + ']' + '(' + href[1] + (title && title[1] ? ' "' + title[1] + '"' : '') + ')' : str;
            }
        },
        {
            patterns: ['b', 'strong'],
            replacement: function (str, attrs, innerHTML) {
                if(calloutRegExp(innerHTML.trim()))
                    return '*' + innerHTML + '*';
                if(calloutRegExp(cleanUp(innerHTML)))
                    return innerHTML.replace("(","<").replace(")",">");
                return '';
            }
        },
        {
            patterns: ['i', 'em'],
            replacement: function (str, attrs, innerHTML) {
                return innerHTML ? '__' + innerHTML + '__' : '';
            }
        },
        {
            patterns: 'sub',
            replacement: function (str, attrs, innerHTML) {
                return innerHTML ? '~' + innerHTML + '~' : '';
            }
        },
        {
            patterns: 'sup',
            replacement: function (str, attrs, innerHTML) {
                return innerHTML ? '^' + innerHTML + '^' : '';
            }
        },
        {
            patterns: 'u',
            replacement: function (str, attrs, innerHTML) {
                return innerHTML ? '[underline]#' + str + '#' : '';
            }
        },
        {
            patterns: 'del',
            replacement: function (str, attrs, innerHTML) {
                return innerHTML ? '[line-through]#' + str + '#' : '';
            }
        },
        {
            patterns: 'code',
            replacement: function (str, attrs, innerHTML) {
                return innerHTML ? '``' + he.decode(innerHTML) + '``' : '';
            }
        },
        {
            patterns: 'pre',
            replacement: function (str, attrs, innerHTML) {
                return innerHTML ? '\n\n----\n' + he.decode(innerHTML) + '\n----\n' : '';
            }
        },
        {
            patterns: 'img',
            type: 'void',
            replacement: function (str, attrs, innerHTML) {
                var src = attrs.match(attrRegExp('src')),
                    alt = attrs.match(attrRegExp('alt')),
                    title = attrs.match(attrRegExp('title'));
                return src ? '\nimage::' + src[1] + '[' + alt[1] + ']\n' : '';
                //return src ? '![' + (alt && alt[1] ? alt[1] : '') + ']' + '(' + src[1] + (title && title[1] ? ' "' + title[1] + '"' : '') + ')' : '';
            }
        }
    ];

    for (var i = 0, len = ELEMENTS.length; i < len; i++) {
        if (typeof ELEMENTS[i].patterns === 'string') {
            string = replaceEls(string, {
                tag: ELEMENTS[i].patterns,
                replacement: ELEMENTS[i].replacement,
                type: ELEMENTS[i].type
            });
        }
        else {
            for (var j = 0, pLen = ELEMENTS[i].patterns.length; j < pLen; j++) {
                string = replaceEls(string, {
                    tag: ELEMENTS[i].patterns[j],
                    replacement: ELEMENTS[i].replacement,
                    type: ELEMENTS[i].type
                });
            }
        }
    }

    function replaceEls(html, elProperties) {
        var pattern = elProperties.type === 'void' ? '<' + elProperties.tag + '\\b([^>]*)\\/?>' : '<' + elProperties.tag + '\\b([^>]*)>([\\s\\S]*?)<\\/' + elProperties.tag + '>',
            regex = new RegExp(pattern, 'gi'),
            asciidoc = '';
        if (typeof elProperties.replacement === 'string') {
            asciidoc = html.replace(regex, elProperties.replacement);
        }
        else {
            asciidoc = html.replace(regex, function (str, p1, p2, p3) {
                return elProperties.replacement.call(this, str, p1, p2, p3);
            });
        }
        return asciidoc;
    }

    function calloutRegExp(context){
        return context.match(/^\(\d+\)$/);
    }

    function attrRegExp(attr) {
        return new RegExp(attr + '\\s*=\\s*["\']?([^"\']*)["\']?', 'i');
    }

    // Pre code blocks

    string = string.replace(/
]*>`([\s\S]*?)`<\/pre>/gi, function (str, innerHTML) {
        var text = he.decode(innerHTML);
        text = text.replace(/^\t+/g, '  '); // convert tabs to spaces (you know it makes sense)
        text = text.replace(/\n/g, '\n    ');
        return '\n\n    ' + text + '\n';
    });

    // Lists

    // Escape numbers that could trigger an ol
    // If there are more than three spaces before the code, it would be in a pre tag
    // Make sure we are escaping the period not matching any character
    string = string.replace(/^(\s{0,3}\d+)\. /g, '$1\\. ');

    // Converts lists that have no child lists (of same type) first, then works its way up
    var noChildrenRegex = /<(ul|ol)\b[^>]*>(?:(?!<ul|<ol)[\s\S])*?<\/\1>/gi;
    while (string.match(noChildrenRegex)) {
        string = string.replace(noChildrenRegex, function (str) {
            return replaceLists(str);
        });
    }

    function replaceLists(html) {

        html = html.replace(/<(ul|ol)\b[^>]*>([\s\S]*?)<\/\1>/gi, function (str, listType, innerHTML) {
            var lis = innerHTML.split('
');
            lis.splice(lis.length - 1, 1);

            for (i = 0, len = lis.length; i < len; i++) {
                if (lis[i]) {
                    var prefix = (listType === 'ol') ? (i + 1) + ".  " : "*   ";
                    lis[i] = lis[i].replace(/\s*
]*>([\s\S]*)/i, function (str, innerHTML) {

                        innerHTML = innerHTML.replace(/^\s+/, '');
                        innerHTML = innerHTML.replace(/\n\n/g, '\n\n    ');
                        // indent nested lists
                        innerHTML = innerHTML.replace(/\n([ ]*)+(\*|\d+\.) /g, '\n$1    $2 ');
                        return prefix + innerHTML;
                    });
                }
                lis[i] = lis[i].replace(/(.) +$/m, '$1');
            }
            return lis.join('\n');
        });

        return '\n\n' + html.replace(/[ \t]+\n|\s+$/g, '');
    }

    // Blockquotes
    var deepest = /
]*>((?:(?!<blockquote)[\s\S])*?)<\/blockquote>/gi;
    while (string.match(deepest)) {
        string = string.replace(deepest, function (str) {
            return replaceBlockquotes(str);
        });
    }

    function replaceBlockquotes(html) {
        html = html.replace(/
]*>([\s\S]*?)<\/blockquote>/gi, function (str, inner) {
            inner = inner.replace(/^\s+|\s+$/g, '');
            inner = cleanUp(inner);
            inner = inner.replace(/^/gm, '> ');
            inner = inner.replace(/^(>([ \t]{2,}>)+)/gm, '> >');
            return inner;
        });
        return html;
    }

    function strip(html) {
        var tmp = document.createElement("div");
        tmp.innerHTML = html;
        return tmp.textContent || tmp.innerText || "";
    }

    function cleanUp(string) {
        string = strip(string);
        string = string.replace(/^[\t\r\n]+|[\t\r\n]+$/g, ''); // trim leading/trailing whitespace
        string = string.replace(/\n\s+\n/g, '\n\n');
        string = string.replace(/\n{3,}/g, '\n\n'); // limit consecutive linebreaks to 2
        return string;
    }

    return cleanUp(string);
};

if (typeof exports === 'object') {
    exports.toAsciidoc = toAsciidoc;
}<commit_msg>- Update strong<commit_after>/*
 * to-asciidoc - an HTML to Asciidoc converter
 *
 * Copyright 2015, asciidocfx
 * Licenced under the MIT licence
 *
 */

if (typeof he !== 'object' && typeof require === 'function') {
    var he = require('he');
}

var nbspRegex = new RegExp(String.fromCharCode(160), "g");

var toAsciidoc = function (string) {

    string = string.replace(nbspRegex, " ");

    var all = document.createElement("div");
    all.innerHTML = string;

    // fix for apple converted space
    var spans = all.querySelectorAll("span.Apple-converted-space");
    for (var i = 0; i < spans.length; i++) {
        var parentNode = spans[i].parentNode || "";
        if (parentNode)
            parentNode.replaceChild(document.createTextNode(" "), spans[i]);
    }

    // table converter
    var tables = all.querySelectorAll("table");
    for (var i = 0; i < tables.length; i++) {
        var tablePrefix = "\n\n|====\n";
        var tableSuffix = "|====\n";
        var tableText = "";
        tableText += tablePrefix;
        var table = tables[i];
        var trs = table.querySelectorAll("tr");

        for (var j = 0; j < trs.length; j++) {
            var tr = trs[j];
            var columns = tr.querySelectorAll("td");
            if (columns.length == 0)
                columns = tr.querySelectorAll("th");
            var row = [].slice.call(columns).map(function (e) {
                return "|" + e.textContent || e.innerText || "";
            }).join(" ");
            tableText += row + "\n";
        }

        tableText += tableSuffix;

        if (table.parentNode)
            table.parentNode.replaceChild(document.createTextNode(tableText), table);
    }

    // fix pre > code block
    var codes = all.querySelectorAll("pre > code");
    for (var i = 0; i < codes.length; i++) {
        var code = codes[i];
        var innerCode = strip(code.innerHTML);
        var pre = code.parentNode;
        if (pre.parentNode)
            pre.parentNode.replaceChild(document.createTextNode("\n\n[source,java]\n----\n" + innerCode + "\n----\n\n"), pre);

    }

    // remove anchor surrounding an img
    var images = all.querySelectorAll("img");
    for (var i = 0; i < images.length; i++) {
        var parentNode = images[i].parentNode || "";
        if (parentNode.parentNode)
            if (parentNode.constructor == HTMLAnchorElement)
                parentNode.parentNode.replaceChild(images[i], parentNode);
    }
    string = all.innerHTML;

    var ELEMENTS = [
        {
            patterns: 'p',
            replacement: function (str, attrs, innerHTML) {
                return innerHTML ? '\n\n' + innerHTML + '\n' : '';
            }
        },
        {
            patterns: 'br',
            type: 'void',
            replacement: '  \n'
        },
        {
            patterns: 'h([1-6])',
            replacement: function (str, hLevel, attrs, innerHTML) {
                var hPrefix = '';
                for (var i = 0; i < hLevel; i++) {
                    hPrefix += '=';
                }
                return '\n\n' + hPrefix + ' ' + innerHTML + '\n';
            }
        },
        {
            patterns: 'hr',
            type: 'void',
            replacement: "\n\n'''\n"
        },
        {
            patterns: 'a',
            replacement: function (str, attrs, innerHTML) {
                var href = attrs.match(attrRegExp('href')),
                    title = attrs.match(attrRegExp('title'));

                return href ? href[1] + '[' + innerHTML + ']' : '';
                //return href ? '[' + innerHTML + ']' + '(' + href[1] + (title && title[1] ? ' "' + title[1] + '"' : '') + ')' : str;
            }
        },
        {
            patterns: ['b', 'strong'],
            replacement: function (str, attrs, innerHTML) {
                return '**' + innerHTML + '**';
            }
        },
        {
            patterns: ['i', 'em'],
            replacement: function (str, attrs, innerHTML) {
                return innerHTML ? '__' + innerHTML + '__' : '';
            }
        },
        {
            patterns: 'sub',
            replacement: function (str, attrs, innerHTML) {
                return innerHTML ? '~' + innerHTML + '~' : '';
            }
        },
        {
            patterns: 'sup',
            replacement: function (str, attrs, innerHTML) {
                return innerHTML ? '^' + innerHTML + '^' : '';
            }
        },
        {
            patterns: 'u',
            replacement: function (str, attrs, innerHTML) {
                return innerHTML ? '[underline]#' + str + '#' : '';
            }
        },
        {
            patterns: 'del',
            replacement: function (str, attrs, innerHTML) {
                return innerHTML ? '[line-through]#' + str + '#' : '';
            }
        },
        {
            patterns: 'code',
            replacement: function (str, attrs, innerHTML) {
                return innerHTML ? '``' + he.decode(innerHTML) + '``' : '';
            }
        },
        {
            patterns: 'pre',
            replacement: function (str, attrs, innerHTML) {
                return innerHTML ? '\n\n----\n' + he.decode(innerHTML) + '\n----\n' : '';
            }
        },
        {
            patterns: 'img',
            type: 'void',
            replacement: function (str, attrs, innerHTML) {
                var src = attrs.match(attrRegExp('src')),
                    alt = attrs.match(attrRegExp('alt')),
                    title = attrs.match(attrRegExp('title'));
                return src ? '\nimage::' + src[1] + '[' + alt[1] + ']\n' : '';
                //return src ? '![' + (alt && alt[1] ? alt[1] : '') + ']' + '(' + src[1] + (title && title[1] ? ' "' + title[1] + '"' : '') + ')' : '';
            }
        }
    ];

    for (var i = 0, len = ELEMENTS.length; i < len; i++) {
        if (typeof ELEMENTS[i].patterns === 'string') {
            string = replaceEls(string, {
                tag: ELEMENTS[i].patterns,
                replacement: ELEMENTS[i].replacement,
                type: ELEMENTS[i].type
            });
        }
        else {
            for (var j = 0, pLen = ELEMENTS[i].patterns.length; j < pLen; j++) {
                string = replaceEls(string, {
                    tag: ELEMENTS[i].patterns[j],
                    replacement: ELEMENTS[i].replacement,
                    type: ELEMENTS[i].type
                });
            }
        }
    }

    function replaceEls(html, elProperties) {
        var pattern = elProperties.type === 'void' ? '<' + elProperties.tag + '\\b([^>]*)\\/?>' : '<' + elProperties.tag + '\\b([^>]*)>([\\s\\S]*?)<\\/' + elProperties.tag + '>',
            regex = new RegExp(pattern, 'gi'),
            asciidoc = '';
        if (typeof elProperties.replacement === 'string') {
            asciidoc = html.replace(regex, elProperties.replacement);
        }
        else {
            asciidoc = html.replace(regex, function (str, p1, p2, p3) {
                return elProperties.replacement.call(this, str, p1, p2, p3);
            });
        }
        return asciidoc;
    }

    function calloutRegExp(context) {
        return context.match(/^\(\d+\)$/);
    }

    function attrRegExp(attr) {
        return new RegExp(attr + '\\s*=\\s*["\']?([^"\']*)["\']?', 'i');
    }

    // Pre code blocks

    string = string.replace(/
]*>`([\s\S]*?)`<\/pre>/gi, function (str, innerHTML) {
        var text = he.decode(innerHTML);
        text = text.replace(/^\t+/g, '  '); // convert tabs to spaces (you know it makes sense)
        text = text.replace(/\n/g, '\n    ');
        return '\n\n    ' + text + '\n';
    });

    // Lists

    // Escape numbers that could trigger an ol
    // If there are more than three spaces before the code, it would be in a pre tag
    // Make sure we are escaping the period not matching any character
    string = string.replace(/^(\s{0,3}\d+)\. /g, '$1\\. ');

    // Converts lists that have no child lists (of same type) first, then works its way up
    var noChildrenRegex = /<(ul|ol)\b[^>]*>(?:(?!<ul|<ol)[\s\S])*?<\/\1>/gi;
    while (string.match(noChildrenRegex)) {
        string = string.replace(noChildrenRegex, function (str) {
            return replaceLists(str);
        });
    }

    function replaceLists(html) {

        html = html.replace(/<(ul|ol)\b[^>]*>([\s\S]*?)<\/\1>/gi, function (str, listType, innerHTML) {
            var lis = innerHTML.split('
');
            lis.splice(lis.length - 1, 1);

            for (i = 0, len = lis.length; i < len; i++) {
                if (lis[i]) {
                    var prefix = (listType === 'ol') ? (i + 1) + ".  " : "*   ";
                    lis[i] = lis[i].replace(/\s*
]*>([\s\S]*)/i, function (str, innerHTML) {

                        innerHTML = innerHTML.replace(/^\s+/, '');
                        innerHTML = innerHTML.replace(/\n\n/g, '\n\n    ');
                        // indent nested lists
                        innerHTML = innerHTML.replace(/\n([ ]*)+(\*|\d+\.) /g, '\n$1    $2 ');
                        return prefix + innerHTML;
                    });
                }
                lis[i] = lis[i].replace(/(.) +$/m, '$1');
            }
            return lis.join('\n');
        });

        return '\n\n' + html.replace(/[ \t]+\n|\s+$/g, '');
    }

    // Blockquotes
    var deepest = /
]*>((?:(?!<blockquote)[\s\S])*?)<\/blockquote>/gi;
    while (string.match(deepest)) {
        string = string.replace(deepest, function (str) {
            return replaceBlockquotes(str);
        });
    }

    function replaceBlockquotes(html) {
        html = html.replace(/
]*>([\s\S]*?)<\/blockquote>/gi, function (str, inner) {
            inner = inner.replace(/^\s+|\s+$/g, '');
            inner = cleanUp(inner);
            inner = inner.replace(/^/gm, '> ');
            inner = inner.replace(/^(>([ \t]{2,}>)+)/gm, '> >');
            return inner;
        });
        return html;
    }

    function strip(html) {
        var tmp = document.createElement("div");
        tmp.innerHTML = html;
        return tmp.textContent || tmp.innerText || "";
    }

    function cleanUp(string) {
        string = strip(string);
        string = string.replace(/^[\t\r\n]+|[\t\r\n]+$/g, ''); // trim leading/trailing whitespace
        string = string.replace(/\n\s+\n/g, '\n\n');
        string = string.replace(/\n{3,}/g, '\n\n'); // limit consecutive linebreaks to 2
        return string;
    }

    return cleanUp(string);
};

if (typeof exports === 'object') {
    exports.toAsciidoc = toAsciidoc;
}<|endoftext|>


<commit_before>var test      = require('tape');
var parseInts = require('../');

test.skip('#1 - require radix is an integer or undefined', function (t) {
  var nonInts = ['1', [1], {}];
  t.plan(nonInts.length);
  nonInts.forEach(function (radix) {
    t.throws(function () {
      parseInts('1', radix);
    });
  });
});
<commit_msg>Add failing test for negative integers.<commit_after>var test      = require('tape');
var parseInts = require('../');

var ints;

test.skip('#1 - require radix is an integer or undefined', function (t) {
  var nonInts = ['1', [1], {}];
  t.plan(nonInts.length);
  nonInts.forEach(function (radix) {
    t.throws(function () {
      parseInts('1', radix);
    });
  });
});

test('#3 supports negative integers', function (t) {
  t.plan(2);

  ints = parseInts('-3, -1');
  t.same(ints, [ -3, -1 ]);

  ints = parseInts('-3--1');
  t.same(ints, [ -3, -2, -1 ]);
});
<|endoftext|>


<commit_before>import test from 'ava'
import { spy } from 'sinon'
import pwc from './../dist/pretty-web-console'

test('pwc.level = "debug"|"log"|0', t => {
  t.plan(5)

  let logLevel = 'log'
  pwc().log(logLevel, logSpy, logLevel)
  t.true(logSpy.calledWith(`%c${logLevel}`))

  logLevel = 'debug'
  pwc().debug(logLevel, logSpy, logLevel)
  t.true(logSpy.calledWith(`%c${logLevel}`))

  logLevel = 'info'
  pwc().info(logLevel, logSpy, logLevel)
  t.true(logSpy.calledWith(`%c${logLevel}`))

  logLevel = 'warn'
  pwc().warn(logLevel, logSpy, logLevel)
  t.true(logSpy.calledWith(`%c${logLevel}`))

  logLevel = 'error'
  pwc().error(logLevel, logSpy, logLevel)
  t.true(logSpy.calledWith(`%c${logLevel}`))
})

test('pwc.level = "info"|1', t => {
  t.plan(5)
  pwc.level = 'info'

  let logLevel = 'log'
  pwc().log(logLevel, logSpy, logLevel)
  t.false(logSpy.calledWith(`%c${logLevel}`))

  logLevel = 'debug'
  pwc().debug(logLevel, logSpy, logLevel)
  t.false(logSpy.calledWith(`%c${logLevel}`))

  logLevel = 'info'
  pwc().info(logLevel, logSpy, logLevel)
  t.true(logSpy.calledWith(`%c${logLevel}`))

  logLevel = 'warn'
  pwc().warn(logLevel, logSpy, logLevel)
  t.true(logSpy.calledWith(`%c${logLevel}`))

  logLevel = 'error'
  pwc().error(logLevel, logSpy, logLevel)
  t.true(logSpy.calledWith(`%c${logLevel}`))
})

test('pwc.level = "warn"|2', t => {
  t.plan(5)
  pwc.level = 'warn'

  let logLevel = 'log'
  pwc().log(logLevel, logSpy, logLevel)
  t.false(logSpy.calledWith(`%c${logLevel}`))

  logLevel = 'debug'
  pwc().debug(logLevel, logSpy, logLevel)
  t.false(logSpy.calledWith(`%c${logLevel}`))

  logLevel = 'info'
  pwc().info(logLevel, logSpy, logLevel)
  t.false(logSpy.calledWith(`%c${logLevel}`))

  logLevel = 'warn'
  pwc().warn(logLevel, logSpy, logLevel)
  t.true(logSpy.calledWith(`%c${logLevel}`))

  logLevel = 'error'
  pwc().error(logLevel, logSpy, logLevel)
  t.true(logSpy.calledWith(`%c${logLevel}`))
})

test('pwc.level = "error"|3', t => {
  t.plan(5)
  pwc.level = 'error'

  let logLevel = 'log'
  pwc().log(logLevel, logSpy, logLevel)
  t.false(logSpy.calledWith(`%c${logLevel}`))

  logLevel = 'debug'
  pwc().debug(logLevel, logSpy, logLevel)
  t.false(logSpy.calledWith(`%c${logLevel}`))

  logLevel = 'info'
  pwc().info(logLevel, logSpy, logLevel)
  t.false(logSpy.calledWith(`%c${logLevel}`))

  logLevel = 'warn'
  pwc().warn(logLevel, logSpy, logLevel)
  t.false(logSpy.calledWith(`%c${logLevel}`))

  logLevel = 'error'
  pwc().error(logLevel, logSpy, logLevel)
  t.true(logSpy.calledWith(`%c${logLevel}`))
})

test('pwc.level = "none"|-1', t => {
  t.plan(5)
  pwc.level = 'none'

  let logLevel = 'log'
  pwc().log(logLevel, logSpy, logLevel)
  t.false(logSpy.calledWith(`%c${logLevel}`))

  logLevel = 'debug'
  pwc().debug(logLevel, logSpy, logLevel)
  t.false(logSpy.calledWith(`%c${logLevel}`))

  logLevel = 'info'
  pwc().info(logLevel, logSpy, logLevel)
  t.false(logSpy.calledWith(`%c${logLevel}`))

  logLevel = 'warn'
  pwc().warn(logLevel, logSpy, logLevel)
  t.false(logSpy.calledWith(`%c${logLevel}`))

  logLevel = 'error'
  pwc().error(logLevel, logSpy, logLevel)
  t.false(logSpy.calledWith(`%c${logLevel}`))
})

let logSpy
test.beforeEach('setup', () => {
  logSpy = spy()
  pwc.level = 0
})
<commit_msg>refactor: abstract body duplication of log-level tests<commit_after>import test from 'ava'
import { spy } from 'sinon'
import pwc from './../dist/pretty-web-console'

test('pwc.level = "debug"|"log"|0', t => {
  t.plan(5)
  testLevel(t, 'true', 'log', logSpy)
  testLevel(t, 'true', 'debug', logSpy)
  testLevel(t, 'true', 'info', logSpy)
  testLevel(t, 'true', 'warn', logSpy)
  testLevel(t, 'true', 'error', logSpy)
})

test('pwc.level = "info"|1', t => {
  t.plan(5)
  pwc.level = 'info'
  testLevel(t, 'false', 'log', logSpy)
  testLevel(t, 'false', 'debug', logSpy)
  testLevel(t, 'true', 'info', logSpy)
  testLevel(t, 'true', 'warn', logSpy)
  testLevel(t, 'true', 'error', logSpy)
})

test('pwc.level = "warn"|2', t => {
  t.plan(5)
  pwc.level = 'warn'
  testLevel(t, 'false', 'log', logSpy)
  testLevel(t, 'false', 'debug', logSpy)
  testLevel(t, 'false', 'info', logSpy)
  testLevel(t, 'true', 'warn', logSpy)
  testLevel(t, 'true', 'error', logSpy)
})

test('pwc.level = "error"|3', t => {
  t.plan(5)
  pwc.level = 'error'
  testLevel(t, 'false', 'log', logSpy)
  testLevel(t, 'false', 'debug', logSpy)
  testLevel(t, 'false', 'info', logSpy)
  testLevel(t, 'false', 'warn', logSpy)
  testLevel(t, 'true', 'error', logSpy)
})

test('pwc.level = "none"|-1', t => {
  t.plan(5)
  pwc.level = 'none'
  testLevel(t, 'false', 'log', logSpy)
  testLevel(t, 'false', 'debug', logSpy)
  testLevel(t, 'false', 'info', logSpy)
  testLevel(t, 'false', 'warn', logSpy)
  testLevel(t, 'false', 'error', logSpy)
})

let logSpy
test.beforeEach('setup', () => {
  logSpy = spy()
  pwc.level = 0
})

function testLevel (t, assertKey, logLevel, logSpy) {
  pwc()[logLevel](logLevel, logSpy, logLevel)
  t[assertKey](logSpy.calledWith(`%c${logLevel}`))
}
<|endoftext|>


<commit_before>
var express = require('express'),
  request = require('request'),
  should = require('should'),
  qs = require('qs')
var Grant = require('../').express(),
  oauth1 = require('../lib/oauth1')

describe('oauth1', function () {
  function url (path) {
    var c = config.server
    return c.protocol + '://' + c.host + path
  }

  var grant, app, server
  var config = {server: {protocol:'http', host:'localhost:5000', callback:'/'}}

  describe('success', function () {
    before(function (done) {
      grant = new Grant(config)
      app = express().use(grant)

      grant.config.twitter.request_url = url('/request_url')
      grant.config.twitter.authorize_url = '/authorize_url'
      grant.config.twitter.access_url = url('/access_url')

      app.post('/request_url', function (req, res) {
        res.end(qs.stringify({some:'data'}))
      })
      app.post('/access_url', function (req, res) {
        res.end(JSON.stringify({some:'data'}))
      })
      server = app.listen(5000, done)
    })

    it('step1', function (done) {
      oauth1.step1(grant.config.twitter, function (err, data) {
        should.deepEqual(data, {some:'data'})
        done()
      })
    })

    it('step2', function () {
      var url = oauth1.step2(grant.config.twitter, {oauth_token:'token'})
      url.should.equal('/authorize_url?oauth_token=token')
    })

    it('step3', function (done) {
      oauth1.step3(grant.config.twitter, {}, {oauth_token:'token'}, function (err, url) {
        url.should.equal('/?raw%5Bsome%5D=data')
        done()
      })
    })

    after(function (done) {
      server.close(done)
    })
  })

  describe('error', function () {
    before(function (done) {
      grant = new Grant(config)
      app = express().use(grant)

      grant.config.twitter.request_url = url('/request_err')
      grant.config.twitter.authorize_url = '/authorize_url'
      grant.config.twitter.access_url = url('/access_url')

      app.post('/request_url', function (req, res) {
        res.status(500).end(JSON.stringify({error:'invalid'}))
      })

      server = app.listen(5000, done)
    })

    it('step1 - network error', function (done) {
      oauth1.step1(grant.config.twitter, function (err, body) {
        err.should.equal('error%5BCannot%20POST%20%2Frequest_err%0A%5D=')
        should.deepEqual(qs.parse(err), {error: {'Cannot POST /request_err\n': ''}})
        done()
      })
    })
    it('step1 - error response', function (done) {
      grant.config.twitter.request_url = url('/request_url')
      oauth1.step1(grant.config.twitter, function (err, body) {
        err.should.equal('error%5Berror%5D=invalid')
        should.deepEqual(qs.parse(err), {error: {error:'invalid'}})
        done()
      })
    })

    it('step2 - mising oauth_token - response error', function () {
      var url = oauth1.step2(grant.config.twitter, {error:'invalid'})
      url.should.equal('/?error%5Berror%5D=invalid')
    })
    it('step2 - mising oauth_token - empty response', function () {
      var url = oauth1.step2(grant.config.twitter, {})
      url.should.equal('/?error%5Berror%5D=Grant%3A%20request_url')
    })

    it('step3 - mising oauth_token - response error', function (done) {
      oauth1.step3(grant.config.twitter, {}, {error:'invalid'}, function (err, body) {
        err.should.equal('error%5Berror%5D=invalid')
        should.deepEqual(qs.parse(err), {error: {error:'invalid'}})
        done()
      })
    })
    it('step3 - mising oauth_token - empty response', function (done) {
      oauth1.step3(grant.config.twitter, {}, {}, function (err, body) {
        err.should.equal('error%5Berror%5D=Grant%3A%20authorize_url')
        should.deepEqual(qs.parse(err), {error: {error:'Grant: authorize_url'}})
        done()
      })
    })

    after(function (done) {
      server.close(done)
    })
  })
})
<commit_msg>Change wording<commit_after>
var express = require('express'),
  request = require('request'),
  should = require('should'),
  qs = require('qs')
var Grant = require('../').express(),
  oauth1 = require('../lib/oauth1')

describe('oauth1', function () {
  function url (path) {
    var c = config.server
    return c.protocol + '://' + c.host + path
  }

  var grant, app, server
  var config = {server: {protocol:'http', host:'localhost:5000', callback:'/'}}

  describe('success', function () {
    before(function (done) {
      grant = new Grant(config)
      app = express().use(grant)

      grant.config.twitter.request_url = url('/request_url')
      grant.config.twitter.authorize_url = '/authorize_url'
      grant.config.twitter.access_url = url('/access_url')

      app.post('/request_url', function (req, res) {
        res.end(qs.stringify({some:'data'}))
      })
      app.post('/access_url', function (req, res) {
        res.end(JSON.stringify({some:'data'}))
      })
      server = app.listen(5000, done)
    })

    it('step1', function (done) {
      oauth1.step1(grant.config.twitter, function (err, data) {
        should.deepEqual(data, {some:'data'})
        done()
      })
    })

    it('step2', function () {
      var url = oauth1.step2(grant.config.twitter, {oauth_token:'token'})
      url.should.equal('/authorize_url?oauth_token=token')
    })

    it('step3', function (done) {
      oauth1.step3(grant.config.twitter, {}, {oauth_token:'token'}, function (err, url) {
        url.should.equal('/?raw%5Bsome%5D=data')
        done()
      })
    })

    after(function (done) {
      server.close(done)
    })
  })

  describe('error', function () {
    before(function (done) {
      grant = new Grant(config)
      app = express().use(grant)

      grant.config.twitter.request_url = url('/request_err')
      grant.config.twitter.authorize_url = '/authorize_url'
      grant.config.twitter.access_url = url('/access_url')

      app.post('/request_url', function (req, res) {
        res.status(500).end(JSON.stringify({error:'invalid'}))
      })

      server = app.listen(5000, done)
    })

    it('step1 - network error', function (done) {
      oauth1.step1(grant.config.twitter, function (err, body) {
        err.should.equal('error%5BCannot%20POST%20%2Frequest_err%0A%5D=')
        should.deepEqual(qs.parse(err), {error: {'Cannot POST /request_err\n': ''}})
        done()
      })
    })
    it('step1 - error response', function (done) {
      grant.config.twitter.request_url = url('/request_url')
      oauth1.step1(grant.config.twitter, function (err, body) {
        err.should.equal('error%5Berror%5D=invalid')
        should.deepEqual(qs.parse(err), {error: {error:'invalid'}})
        done()
      })
    })

    it('step2 - mising oauth_token - error response', function () {
      var url = oauth1.step2(grant.config.twitter, {error:'invalid'})
      url.should.equal('/?error%5Berror%5D=invalid')
    })
    it('step2 - mising oauth_token - empty response', function () {
      var url = oauth1.step2(grant.config.twitter, {})
      url.should.equal('/?error%5Berror%5D=Grant%3A%20request_url')
    })

    it('step3 - mising oauth_token - response error', function (done) {
      oauth1.step3(grant.config.twitter, {}, {error:'invalid'}, function (err, body) {
        err.should.equal('error%5Berror%5D=invalid')
        should.deepEqual(qs.parse(err), {error: {error:'invalid'}})
        done()
      })
    })
    it('step3 - mising oauth_token - empty response', function (done) {
      oauth1.step3(grant.config.twitter, {}, {}, function (err, body) {
        err.should.equal('error%5Berror%5D=Grant%3A%20authorize_url')
        should.deepEqual(qs.parse(err), {error: {error:'Grant: authorize_url'}})
        done()
      })
    })

    after(function (done) {
      server.close(done)
    })
  })
})
<|endoftext|>


<commit_before>'use strict';

import assert from 'assert';
import Period from '../src/period';

describe('Period', () => {
  describe('#()', () => {
    let start, end;

    beforeEach(() => {
      start = new Date();
      end = new Date(+start);
      end.setDate(end.getDate() + 7);
    });

    it('should require parameters', () => {
      assert.throws(() => { new Period(); }, 'constructor should expect parameters');
    });

    it('should validate parameters', () => {
      assert.throws(() => { new Period('2013-12-01'); }, 'constructor should not allow invalid parameters');
    });

    it('should be iterable', () => {
      let period = new Period(start, 'P1D', 7);

      assert.deepEqual(period[0], start);
      assert.equal(period.length, 8);
    });

    it('should not include end date as last item', () => {
      let period = new Period(start, 'P1D', end),
        testEnd = new Date(+start);

      testEnd.setDate(testEnd.getDate() + 6);

      assert.deepEqual(period[period.length - 1], testEnd);
    });

    it('should handle not-matching start and end dates', () => {
      let thisEnd = new Date(+start);
      thisEnd.setDate(thisEnd.getDate() + 7);
      thisEnd.setHours(thisEnd.getHours() - 12);

      let period = new Period(start, 'P1D', thisEnd);

      assert.equal(period.length, 7, 'shortened end should affect length');

      thisEnd = new Date(+start);
      thisEnd.setDate(thisEnd.getDate() + 7);
      thisEnd.setHours(thisEnd.getHours() + 12);

      period = new Period(start, 'P1D', thisEnd);
      assert.equal(period.length, 8, 'stretched end should not affect length');
    });

    it('should parse a string in ISO format', () => {
      let period = new Period('R4/2012-07-01T00:00:00Z/P7D');

      assert.equal(5, period.length);
      assert.deepEqual(new Date('2012-07-01T00:00:00Z'), period[0]);
      assert.deepEqual(new Date('2012-07-29T00:00:00Z'), period[4]);
    });
  });

  describe('#toString()', () => {
    it('should return a string', () => {
      let start = new Date('2013-06-30T12:30:00Z'),
        period = new Period(start, 'P1D', 7),
        str = period.toString();

      assert.equal(typeof str, 'string');
      assert.equal(str, 'R7/2013-06-30T12:30:00Z/P1D');
    });
  });
});
<commit_msg>add tests for date-like objects and custom durations<commit_after>'use strict';

import assert from 'assert';
import Period from '../src/period';

describe('Period', () => {
  describe('#()', () => {
    let start, end;

    beforeEach(() => {
      start = new Date();
      end = new Date(+start);
      end.setDate(end.getDate() + 7);
    });

    it('should require parameters', () => {
      assert.throws(() => { new Period(); }, 'constructor should expect parameters');
    });

    it('should validate parameters', () => {
      assert.throws(() => { new Period('2013-12-01'); }, 'constructor should not allow invalid parameters');
    });

    it('should be iterable', () => {
      let period = new Period(start, 'P1D', 7);

      assert.deepEqual(period[0], start);
      assert.equal(period.length, 8);
    });

    it('should not include end date as last item', () => {
      let period = new Period(start, 'P1D', end),
        testEnd = new Date(+start);

      testEnd.setDate(testEnd.getDate() + 6);

      assert.deepEqual(period[period.length - 1], testEnd);
    });

    it('should handle not-matching start and end dates', () => {
      let thisEnd = new Date(+start);
      thisEnd.setDate(thisEnd.getDate() + 7);
      thisEnd.setHours(thisEnd.getHours() - 12);

      let period = new Period(start, 'P1D', thisEnd);

      assert.equal(period.length, 7, 'shortened end should affect length');

      thisEnd = new Date(+start);
      thisEnd.setDate(thisEnd.getDate() + 7);
      thisEnd.setHours(thisEnd.getHours() + 12);

      period = new Period(start, 'P1D', thisEnd);
      assert.equal(period.length, 8, 'stretched end should not affect length');
    });

    it('should parse a string in ISO format', () => {
      let period = new Period('R4/2012-07-01T00:00:00Z/P7D');

      assert.equal(5, period.length);
      assert.deepEqual(new Date('2012-07-01T00:00:00Z'), period[0]);
      assert.deepEqual(new Date('2012-07-29T00:00:00Z'), period[4]);
    });

    it('should handle date-like objects with a toDate method', () => {
      class CustomDate { // something like moment
        constructor(date) { this.date = date; }
        toDate() { return this.date; }
      }

      let dummy = new CustomDate(start),
        period = new Period(dummy, 'PT1H30M', 3);

      assert(period.length === 4);
      assert.deepEqual(period[0], start);
    });

    it('should handle duration objects with a toString method', () => {
      class CustomDuration { // something like moment.duration
        constructor(isoString) { this.isoString = isoString; }
        toString() { return this.isoString; }
      }

      let dummy = new CustomDuration('P1D'),
        period = new Period(start, dummy, 3);

      assert(period.length === 4);
      assert.deepEqual(period[0], start);
    });
  });

  describe('#toString()', () => {
    it('should return a string', () => {
      let start = new Date('2013-06-30T12:30:00Z'),
        period = new Period(start, 'P1D', 7),
        str = period.toString();

      assert.equal(typeof str, 'string');
      assert.equal(str, 'R7/2013-06-30T12:30:00Z/P1D');
    });
  });
});
<|endoftext|>