<commit_before>'use babel';

/* @flow */

import globToRegex from 'glob-to-regexp';
import { Emitter, CompositeDisposable } from 'atom';
import { convertWindowsPathToUnixPath } from './helpers';
/* flow-include
import type { TextEditor, Disposable } from 'atom'
import EditorTester from './editor-tester';
import type { Tester } from './types'
*/

export default class TesterRegistry {
    /* ::
    emitter: Emitter;
    testers: Set<Tester>;
    locks: Set<EditorTester>;
    testOnChange: boolean;
    subscriptions: CompositeDisposable;
    */

  constructor() {
    this.emitter = new Emitter();
    this.testers = new Set();
    this.locks = new Set();
    this.subscriptions = new CompositeDisposable();

    this.subscriptions.add(atom.config.observe('tester.testOnChange', (testOnChange) => {
      this.testOnChange = testOnChange;
    }));
  }

  hasTester(tester /* : Tester*/) /* : boolean*/ {
    return this.testers.has(tester);
  }

  addTester(tester /* : Tester*/) {
    this.testers.add(tester);
  }

  deleteTester(tester /* : Tester*/) {
    this.testers.delete(tester);
  }

  onShouldTriggerTester(callback /* : Function*/) /* : Disposable*/ {
    return this.emitter.on('should-trigger-tester', callback);
  }
  onDidUpdateMessages(callback /* : Function*/) /* : Disposable*/ {
    return this.emitter.on('did-update-messages', callback);
  }
  onDidBeginTesting(callback /* : Function*/) /* : Disposable*/ {
    return this.emitter.on('did-begin-testing', callback);
  }
  onDidFinishTesting(callback /* : Function*/) /* : Disposable*/ {
    return this.emitter.on('did-finish-testing', callback);
  }
  dispose() {
    this.testers.clear();
    this.subscriptions.dispose();
  }
  async test(editorTester/* : EditorTester*/)/* : Promise<boolean> */ {
    const editor = editorTester.editor;
    if (!editor.getPath() || this.locks.has(editorTester) ||
      (editor.isModified() && !this.testOnChange)) {
      return Promise.resolve(true);
    }

    this.emitter.emit('did-begin-testing', { editorTester });
    this.locks.add(editorTester);

    const promises = [];
    this.testers.forEach((tester) => {
      let shouldTriggerTester = false;
      try {
        shouldTriggerTester = tester.scopes.some(scope =>
          globToRegex(scope).test(convertWindowsPathToUnixPath(editor.getPath())));
      } catch (error) {
        atom.notifications.addError(`Tester error: ${error.toString()}`);
      }
      if (!shouldTriggerTester) {
        return;
      }
      promises.push(new Promise((resolve) => {
        // $FlowIgnore: Type too complex
        resolve(tester.test(editor));
      })
      .then(({ messages, output }) => {
        if (messages) {
          this.emitter.emit('did-update-messages', { tester, editor, messages, output });
        }
      })
      .catch((error) => {
        atom.notifications.addError(`Tester error: ${error.toString()}`);
        return false;
      }));
    });
    await Promise.all(promises)
      .then(() => {
        this.locks.delete(editorTester);
        this.emitter.emit('did-finish-testing', { editorTester });
      })
      .catch((error) => {
        atom.notifications.addError(`Tester error: ${error.toString()}`);
        return false;
      });
    return true;
  }

  async stop(editorTester/* : EditorTester*/)/* : Promise<boolean> */ {
    const promises = [];
    this.testers.forEach((tester) => {
      promises.push(new Promise((resolve) => {
        // $FlowIgnore: Type too complex
        resolve(tester.stop(editorTester));
      }));
    });
    await Promise.all(promises)
      .then(() => {
        this.locks.delete(editorTester);
        this.emitter.emit('did-finish-testing', { editorTester });
      })
      .catch((error) => {
        atom.notifications.addError(`Tester error: ${error.toString()}`);
        return false;
      });
    return true;
  }
}
<commit_msg>not send begin/finish events for non scope editors<commit_after>'use babel';

/* @flow */

import globToRegex from 'glob-to-regexp';
import { Emitter, CompositeDisposable } from 'atom';
import { convertWindowsPathToUnixPath } from './helpers';
/* flow-include
import type { TextEditor, Disposable } from 'atom'
import EditorTester from './editor-tester';
import type { Tester } from './types'
*/

export default class TesterRegistry {
    /* ::
    emitter: Emitter;
    testers: Set<Tester>;
    locks: Set<EditorTester>;
    testOnChange: boolean;
    subscriptions: CompositeDisposable;
    */

  constructor() {
    this.emitter = new Emitter();
    this.testers = new Set();
    this.locks = new Set();
    this.subscriptions = new CompositeDisposable();

    this.subscriptions.add(atom.config.observe('tester.testOnChange', (testOnChange) => {
      this.testOnChange = testOnChange;
    }));
  }

  hasTester(tester /* : Tester*/) /* : boolean*/ {
    return this.testers.has(tester);
  }

  addTester(tester /* : Tester*/) {
    this.testers.add(tester);
  }

  deleteTester(tester /* : Tester*/) {
    this.testers.delete(tester);
  }

  onShouldTriggerTester(callback /* : Function*/) /* : Disposable*/ {
    return this.emitter.on('should-trigger-tester', callback);
  }
  onDidUpdateMessages(callback /* : Function*/) /* : Disposable*/ {
    return this.emitter.on('did-update-messages', callback);
  }
  onDidBeginTesting(callback /* : Function*/) /* : Disposable*/ {
    return this.emitter.on('did-begin-testing', callback);
  }
  onDidFinishTesting(callback /* : Function*/) /* : Disposable*/ {
    return this.emitter.on('did-finish-testing', callback);
  }
  dispose() {
    this.testers.clear();
    this.subscriptions.dispose();
  }
  async test(editorTester/* : EditorTester*/)/* : Promise<boolean> */ {
    const editor = editorTester.editor;
    if (!editor.getPath() || this.locks.has(editorTester) ||
      (editor.isModified() && !this.testOnChange)) {
      return Promise.resolve(true);
    }

    this.locks.add(editorTester);
    const promises = [];
    this.testers.forEach((tester) => {
      let shouldTriggerTester = false;
      try {
        shouldTriggerTester = tester.scopes.some(scope =>
          globToRegex(scope).test(convertWindowsPathToUnixPath(editor.getPath())));
      } catch (error) {
        atom.notifications.addError(`Tester error: ${error.toString()}`);
      }
      if (!shouldTriggerTester) {
        return;
      }
      this.emitter.emit('did-begin-testing', { editorTester });
      promises.push(new Promise((resolve) => {
        // $FlowIgnore: Type too complex
        resolve(tester.test(editor));
      })
      .then(({ messages, output }) => {
        if (messages) {
          this.emitter.emit('did-update-messages', { tester, editor, messages, output });
        }
      })
      .catch((error) => {
        atom.notifications.addError(`Tester error: ${error.toString()}`);
        return false;
      }));
    });
    await Promise.all(promises)
      .then(() => {
        this.locks.delete(editorTester);
        if (promises.length > 0) {
          this.emitter.emit('did-finish-testing', { editorTester });
        }
      })
      .catch((error) => {
        atom.notifications.addError(`Tester error: ${error.toString()}`);
        return false;
      });
    return true;
  }

  async stop(editorTester/* : EditorTester*/)/* : Promise<boolean> */ {
    const promises = [];
    this.testers.forEach((tester) => {
      promises.push(new Promise((resolve) => {
        // $FlowIgnore: Type too complex
        resolve(tester.stop(editorTester));
      }));
    });
    await Promise.all(promises)
      .then(() => {
        this.locks.delete(editorTester);
        this.emitter.emit('did-finish-testing', { editorTester });
      })
      .catch((error) => {
        atom.notifications.addError(`Tester error: ${error.toString()}`);
        return false;
      });
    return true;
  }
}
<|endoftext|>


<commit_before>module.exports = function tokenizePattern(pattern) {
  if (typeof pattern !== 'string') {
    let valueString = pattern;
    try {
      valueString = JSON.stringify(pattern);
    } catch (e) {}
    throw new Error(
      'i18nTools.tokenizePattern: Value must be a string: ' + valueString
    );
  }
  const tokens = [], fragments = pattern.split(/(\{\d+\})/);
  for (let i = 0; i < fragments.length; i += 1) {
    const fragment = fragments[i];
    if (fragment.length > 0) {
      const matchPlaceHolder = fragment.match(/^\{(\d+)\}$/);
      if (matchPlaceHolder) {
        tokens.push({
          type: 'placeHolder',
          value: parseInt(matchPlaceHolder[1], 10)
        });
      } else {
        tokens.push({
          type: 'text',
          value: fragment
        });
      }
    }
  }
  return tokens;
};
<commit_msg>lebab -t for-of --replace bin --replace lib<commit_after>module.exports = function tokenizePattern(pattern) {
  if (typeof pattern !== 'string') {
    let valueString = pattern;
    try {
      valueString = JSON.stringify(pattern);
    } catch (e) {}
    throw new Error(
      'i18nTools.tokenizePattern: Value must be a string: ' + valueString
    );
  }
  const tokens = [], fragments = pattern.split(/(\{\d+\})/);

  for (const fragment of fragments) {
    if (fragment.length > 0) {
      const matchPlaceHolder = fragment.match(/^\{(\d+)\}$/);
      if (matchPlaceHolder) {
        tokens.push({
          type: 'placeHolder',
          value: parseInt(matchPlaceHolder[1], 10)
        });
      } else {
        tokens.push({
          type: 'text',
          value: fragment
        });
      }
    }
  }

  return tokens;
};
<|endoftext|>


<commit_before>'use strict';

var lxHelpers = require('lx-helpers'),
    TransportError = require('../errors').TransportError,
    fs = require('fs');

module.exports = function (baboon) {
    if (!baboon || !baboon.config) {
        throw new TransportError(400, '', 'Parameter baboon is required!');
    }

    var pub = {},
        PATH_API = 'api/',
        CONTROLLER_FILES = '/**/controllers/*.js',
        STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;

    var useRightSystem = baboon.config.useRightSystem || false;

    /**
     * Returns the function parameters as strings in an array
     *
     * @param func
     * @returns {Array|{index: number, input: string}|Array}
     */
    function getParamNames(func) {
        var fnStr = func.toString().replace(STRIP_COMMENTS, '');
        return fnStr.slice(fnStr.indexOf('(') + 1, fnStr.indexOf(')')).match(/([^\s,]+)/g) || [];
    }

    /**
     * Return the controller path for the route
     *
     * @param fullPathToControllerFile
     * @param separator
     * @param controllerDirectory
     * @returns {*}
     */
    function getControllerPath(fullPathToControllerFile, separator, controllerDirectory) {
        var modulePath = '';
        var splittedFile = fullPathToControllerFile.split(separator);

        // get controller name and remove '.js' from file name
        var controllerName = splittedFile.pop().slice(0, -3);

        // remove controllerName
        splittedFile.pop();

        var moduleName = splittedFile.pop();
        var i = splittedFile.length - 1;

        if (controllerDirectory) {
            if (splittedFile.indexOf(controllerDirectory) === -1) {
                return null;
            }

            while (splittedFile[i] !== controllerDirectory) {
                modulePath = splittedFile[i] + '/' + modulePath;
                i--;
            }
        }

        return modulePath + moduleName + '/' + controllerName;
    }

    /**
     * Indexes all controller files and their actions into the controllers list
     * @returns {{}}
     */
    function initAppControllers() {
        var grunt = require('grunt');

        // modules
        var patternControllers = baboon.config.path.modules + CONTROLLER_FILES,
            controllers = grunt.file.expand(patternControllers),
            result = {};

        lxHelpers.forEach(controllers, function (controllerFile) {
            // get controller path, e.g. app/blog/blog
            var controllerPath = getControllerPath(controllerFile, '/', 'modules');

            if (controllerPath) {
                // init controller and store in result
                result[PATH_API + controllerPath] = require(controllerFile)(baboon);
            }
        });

        // lib
        patternControllers = baboon.config.path.lib_controller + '.js';
        controllers = grunt.file.expand(patternControllers);

        lxHelpers.forEach(controllers, function (controllerFile) {
            // get controller path, e.g. app/blog/blog
            var controllerPath = getControllerPath(controllerFile, '/', null);

            if (controllerPath) {
                // init controller and store in result
                result[PATH_API + controllerPath] = require(controllerFile)(baboon);
            }
        });

        return result;
    }

    var controllers = initAppControllers();

    /**
     *
     * @param route
     * @returns {{action: *, controllerName: *, controllerFullPath: string}}
     */
    function parseRoute(route) {
        var parts = route.split('/');

        return {
            action: parts.pop(),
            controllerName: parts[parts.length - 1],
            controllerFullPath: parts.join('/')
        };
    }

    /**
     * Returns controllers with their actions
     *
     * @returns {*}
     */
    pub.getControllers = function () {
        return controllers;
    };

    /**
     * Adds a controller or controller file to the controllers list
     *
     * @param controller
     * @param controllerPath
     * @param args
     */
    pub.addController = function (controller, controllerPath, args) {
        controllerPath = PATH_API + controllerPath;

        if (controllerPath[controllerPath.length - 1] === '/') {
            controllerPath = controllerPath.slice(0, -1);
        }

        if (!lxHelpers.isObject(controller)) {
            if (fs.existsSync(controller)) {
                // init controller
                controller = require(controller)(args);
            } else {
                return;
            }
        }

        // init
        controllers[controllerPath] = {};

        lxHelpers.forEach(controller, function (action, functionName) {
            var params = getParamNames(action);

            // check signature of params of function
            if (params.length === 3 && params[0] === 'data' && params[1] === 'request' && params[2] === 'callback') {
                // store in list
                controllers[controllerPath][functionName] = action;
            }
        });

        // remove when no action available
        if (Object.keys(controllers[controllerPath]).length === 0) {
            delete controllers[controllerPath];
        }
    };

    /**
     * Processes the rest request and calls the controller/action
     * @param req
     * @param res
     */
    pub.processRequest = function (req, res) {
        // remove trailing slash
        var route = req.originalUrl.substring(1);
        var parsedRoute = parseRoute(route);

        if (!useRightSystem) {
//        if ((!useRightSystem) || ( useRightSystem && userHasAccessTo(route))) {
            var data = req.body;

            var request = {
                getSession: function (callback) {
                    if (callback) {
                        callback(null, req.session);
                    }
                },
                setSession: function (session, callback) {
                    if (callback) {
                        callback(null, true);
                    }
                }
            };

            if (controllers[parsedRoute.controllerFullPath] && controllers[parsedRoute.controllerFullPath][parsedRoute.action]) {
                controllers[parsedRoute.controllerFullPath][parsedRoute.action](data, request, function (error, result) {
                    if (error) {
                        res.json(401, error);
                    } else {
                        res.json(200, result);
                    }
                });
            } else {
                res.json(403, 'Wrong url');
            }
        } else {
            res.json(403, 'Access denied.');
        }
    };

    /**
     * Registers the events on the socket
     *
     * @param socket
     */
    pub.registerSocketEvents = function (socket) {
        // iterate over each controller in the acl module
        lxHelpers.forEach(controllers, function (actions, controllerName) {

            // iterate over each action in the controller
            lxHelpers.forEach(actions, function (action, actionName) {
                var eventName = controllerName + '/' + actionName;

                if (!useRightSystem) {
//                if ((!useRightSystem) || ( useRightSystem && userHasAccessTo(eventName))) {
                    // register socket event
                    socket.on(eventName, function (data, callback) {
                        controllers[controllerName][actionName](data, {}, function (error, result) {
                            callback(error, result);
                        });
                    });
                }
            });
        });
    };

    return pub;
};<commit_msg>chore(transport): tests angepasst<commit_after>'use strict';

var lxHelpers = require('lx-helpers'),
    TransportError = require('../errors').TransportError,
    fs = require('fs');

module.exports = function (baboon) {
    if (!baboon || !baboon.config) {
        throw new TransportError(400, '', 'Parameter baboon is required!');
    }

    var pub = {},
        PATH_API = 'api/',
        CONTROLLER_FILES = '/**/controllers/*.js',
        STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;

    var useRightSystem = baboon.config.useRightSystem || false;

    /**
     * Returns the function parameters as strings in an array
     *
     * @param func
     * @returns {Array|{index: number, input: string}|Array}
     */
    function getParamNames(func) {
        var fnStr = func.toString().replace(STRIP_COMMENTS, '');
        return fnStr.slice(fnStr.indexOf('(') + 1, fnStr.indexOf(')')).match(/([^\s,]+)/g) || [];
    }

    /**
     * Return the controller path for the route
     *
     * @param fullPathToControllerFile
     * @param separator
     * @param controllerDirectory
     * @returns {*}
     */
    function getControllerPath(fullPathToControllerFile, separator, controllerDirectory) {
        var modulePath = '';
        var splittedFile = fullPathToControllerFile.split(separator);

        // get controller name and remove '.js' from file name
        var controllerName = splittedFile.pop().slice(0, -3);

        // remove controllerName
        splittedFile.pop();

        var moduleName = splittedFile.pop();
        var i = splittedFile.length - 1;

        if (controllerDirectory) {
            if (splittedFile.indexOf(controllerDirectory) === -1) {
                return null;
            }

            while (splittedFile[i] !== controllerDirectory) {
                modulePath = splittedFile[i] + '/' + modulePath;
                i--;
            }
        }

        return modulePath + moduleName + '/' + controllerName;
    }

    /**
     * Indexes all controller files and their actions into the controllers list
     * @returns {{}}
     */
    function initAppControllers() {
        var grunt = require('grunt');

        // modules
        var patternControllers = baboon.config.path.modules + CONTROLLER_FILES,
            controllers = grunt.file.expand(patternControllers),
            result = {};

        lxHelpers.forEach(controllers, function (controllerFile) {
            // get controller path, e.g. app/blog/blog
            var controllerPath = getControllerPath(controllerFile, '/', 'modules');

            if (controllerPath) {
                // init controller and store in result
                result[PATH_API + controllerPath] = require(controllerFile)(baboon);
            }
        });

        // lib
        patternControllers = baboon.config.path.lib_controller + '*.js';
        controllers = grunt.file.expand(patternControllers);

        lxHelpers.forEach(controllers, function (controllerFile) {
            // get controller path, e.g. app/blog/blog
            var controllerPath = getControllerPath(controllerFile, '/', null);

            if (controllerPath) {
                // init controller and store in result
                result[PATH_API + controllerPath] = require(controllerFile)(baboon);
            }
        });

        return result;
    }

    var controllers = initAppControllers();

    /**
     *
     * @param route
     * @returns {{action: *, controllerName: *, controllerFullPath: string}}
     */
    function parseRoute(route) {
        var parts = route.split('/');

        return {
            action: parts.pop(),
            controllerName: parts[parts.length - 1],
            controllerFullPath: parts.join('/')
        };
    }

    /**
     * Returns controllers with their actions
     *
     * @returns {*}
     */
    pub.getControllers = function () {
        return controllers;
    };

    /**
     * Adds a controller or controller file to the controllers list
     *
     * @param controller
     * @param controllerPath
     * @param args
     */
    pub.addController = function (controller, controllerPath, args) {
        controllerPath = PATH_API + controllerPath;

        if (controllerPath[controllerPath.length - 1] === '/') {
            controllerPath = controllerPath.slice(0, -1);
        }

        if (!lxHelpers.isObject(controller)) {
            if (fs.existsSync(controller)) {
                // init controller
                controller = require(controller)(args);
            } else {
                return;
            }
        }

        // init
        controllers[controllerPath] = {};

        lxHelpers.forEach(controller, function (action, functionName) {
            var params = getParamNames(action);

            // check signature of params of function
            if (params.length === 3 && params[0] === 'data' && params[1] === 'request' && params[2] === 'callback') {
                // store in list
                controllers[controllerPath][functionName] = action;
            }
        });

        // remove when no action available
        if (Object.keys(controllers[controllerPath]).length === 0) {
            delete controllers[controllerPath];
        }
    };

    /**
     * Processes the rest request and calls the controller/action
     * @param req
     * @param res
     */
    pub.processRequest = function (req, res) {
        // remove trailing slash
        var route = req.originalUrl.substring(1);
        var parsedRoute = parseRoute(route);

        if (!useRightSystem) {
//        if ((!useRightSystem) || ( useRightSystem && userHasAccessTo(route))) {
            var data = req.body;

            var request = {
                getSession: function (callback) {
                    if (callback) {
                        callback(null, req.session);
                    }
                },
                setSession: function (session, callback) {
                    if (callback) {
                        callback(null, true);
                    }
                }
            };

            if (controllers[parsedRoute.controllerFullPath] && controllers[parsedRoute.controllerFullPath][parsedRoute.action]) {
                controllers[parsedRoute.controllerFullPath][parsedRoute.action](data, request, function (error, result) {
                    if (error) {
                        res.json(401, error);
                    } else {
                        res.json(200, result);
                    }
                });
            } else {
                res.json(403, 'Wrong url');
            }
        } else {
            res.json(403, 'Access denied.');
        }
    };

    /**
     * Registers the events on the socket
     *
     * @param socket
     */
    pub.registerSocketEvents = function (socket) {
        // iterate over each controller in the acl module
        lxHelpers.forEach(controllers, function (actions, controllerName) {

            // iterate over each action in the controller
            lxHelpers.forEach(actions, function (action, actionName) {
                var eventName = controllerName + '/' + actionName;

                if (!useRightSystem) {
//                if ((!useRightSystem) || ( useRightSystem && userHasAccessTo(eventName))) {
                    // register socket event
                    socket.on(eventName, function (data, callback) {
                        controllers[controllerName][actionName](data, {}, function (error, result) {
                            callback(error, result);
                        });
                    });
                }
            });
        });
    };

    return pub;
};<|endoftext|>


<commit_before>'use strict'

const deepMap = require('../../utils/collection/deepMap')

function factory (type, config, load, typed) {
  /**
   * Test whether a value is positive: larger than zero.
   * The function supports types `number`, `BigNumber`, `Fraction`, and `Unit`.
   *
   * The function is evaluated element-wise in case of Array or Matrix input.
   *
   * Syntax:
   *
   *     math.isPositive(x)
   *
   * Examples:
   *
   *    math.isPositive(3)                     // returns true
   *    math.isPositive(-2)                    // returns false
   *    math.isPositive(0)                     // returns false
   *    math.isPositive(-0)                    // returns false
   *    math.isPositive(0.5)                   // returns true
   *    math.isPositive(math.bignumber(2))     // returns true
   *    math.isPositive(math.fraction(-2, 5))  // returns false
   *    math.isPositive(math.fraction(1,3))    // returns false
   *    math.isPositive('2')                   // returns true
   *    math.isPositive([2, 0, -3]')           // returns [true, false, false]
   *
   * See also:
   *
   *    isNumeric, isZero, isNegative, isInteger
   *
   * @param {number | BigNumber | Fraction | Unit | Array | Matrix} x  Value to be tested
   * @return {boolean}  Returns true when `x` is larger than zero.
   *                    Throws an error in case of an unknown data type.
   */
  const isPositive = typed('isPositive', {
    'number': function (x) {
      return x > 0
    },

    'BigNumber': function (x) {
      return !x.isNeg() && !x.isZero() && !x.isNaN()
    },

    'Fraction': function (x) {
      return x.s > 0 && x.n > 0
    },

    'Unit': function (x) {
      return isPositive(x.value)
    },

    'Array | Matrix': function (x) {
      return deepMap(x, isPositive)
    }
  })

  return isPositive
}

exports.name = 'isPositive'
exports.factory = factory
<commit_msg>Fixed a typo in an example<commit_after>'use strict'

const deepMap = require('../../utils/collection/deepMap')

function factory (type, config, load, typed) {
  /**
   * Test whether a value is positive: larger than zero.
   * The function supports types `number`, `BigNumber`, `Fraction`, and `Unit`.
   *
   * The function is evaluated element-wise in case of Array or Matrix input.
   *
   * Syntax:
   *
   *     math.isPositive(x)
   *
   * Examples:
   *
   *    math.isPositive(3)                     // returns true
   *    math.isPositive(-2)                    // returns false
   *    math.isPositive(0)                     // returns false
   *    math.isPositive(-0)                    // returns false
   *    math.isPositive(0.5)                   // returns true
   *    math.isPositive(math.bignumber(2))     // returns true
   *    math.isPositive(math.fraction(-2, 5))  // returns false
   *    math.isPositive(math.fraction(1,3))    // returns false
   *    math.isPositive('2')                   // returns true
   *    math.isPositive([2, 0, -3])           // returns [true, false, false]
   *
   * See also:
   *
   *    isNumeric, isZero, isNegative, isInteger
   *
   * @param {number | BigNumber | Fraction | Unit | Array | Matrix} x  Value to be tested
   * @return {boolean}  Returns true when `x` is larger than zero.
   *                    Throws an error in case of an unknown data type.
   */
  const isPositive = typed('isPositive', {
    'number': function (x) {
      return x > 0
    },

    'BigNumber': function (x) {
      return !x.isNeg() && !x.isZero() && !x.isNaN()
    },

    'Fraction': function (x) {
      return x.s > 0 && x.n > 0
    },

    'Unit': function (x) {
      return isPositive(x.value)
    },

    'Array | Matrix': function (x) {
      return deepMap(x, isPositive)
    }
  })

  return isPositive
}

exports.name = 'isPositive'
exports.factory = factory
<|endoftext|>


<commit_before>var _ = require('lodash');
var util = require('util');

var TypeConstructor = module.exports = {};

var typeStaticMethods = {
    hasProperty: function(propertyName) {
        return this.propertyNames.indexOf(propertyName) >= 0;
    },
    hasMethod: function(methodName) {
        return this.methodNames.indexOf(methodName) >= 0;
    },
    addChild: function(name) {
        this.children[name] = true;
    },
    eachChild: function(scope, deep, cb) {
        _.forOwn(this.children, function(exists, name) {
            var child = scope.getTypeOrNull(name);
            if (child) {
                cb(child);
                if (deep) {
                    child.eachChild(scope, deep, cb);
                }
            }
        });
    }
};

TypeConstructor.build = function(typeName, def) {
    var newType = this.buildTypeConstructor(def);
    var parent = newType.parent = def.parentType;

    var hasParent = !!def.parentType;
    if (hasParent) {
        util.inherits(newType, parent);
        delete newType.super_;
        parent.addChild(typeName);

        newType.propertyAssertions = def.propertyAssertions;
        newType.propertyNames = Object.keys(def.propertyAssertions).concat(parent.propertyNames);
        newType.methodNames = Object.keys(def.methods).concat(parent.methodNames);
    } else {
        newType.propertyAssertions = def.propertyAssertions;
        newType.propertyNames = Object.keys(def.propertyAssertions);
        newType.methodNames = Object.keys(def.methods);
    }

    newType.def = def;
    newType.children = {};
    newType.props = def.props;

    _.forOwn(typeStaticMethods, function(method, name) {
        newType[name] = method;
    });

    newType.prototype.validate = this.buildTypeValidation(def);
    newType.prototype.typeName = newType.typeName = typeName;

    _.forOwn(def.methods, function(fn, name) {
        newType.prototype[name] = fn;
    });

    return newType;

};

TypeConstructor.buildTypeConstructor = function(def) {
    return function(scope, props, schema) {
        if (def.parentType) {
            def.parentType.call(this, scope, props);
        }
        if (def.onCreate.length) {
            _.each(def.onCreate, function(fn) {
                fn.call(this, scope, props, schema);
            }, this);
        }
        if (def.methodCalls.length) {
            var callstack = {};
            _.each(def.methodCalls, function(proxy) {
                callstack[proxy.id] = this[proxy.name].apply(this, proxy.filteredArgs(callstack));
            }, this);
        }
        if (schema) {
            schema.call(this);
        }
    };
};

TypeConstructor.buildTypeValidation = function(def) {
    return function(value, path, dataWrapper) {
        if (def.typeAssertion && !def.typeAssertion.call(this, value)) {
            return this.scope.error(path, "Type assertion failed for type " + this.typeName);
        }

        if (def.parentType) {
            def.parentType.prototype.validate.call(this, value, path, dataWrapper);
        }

        _.forOwn(def.propertyAssertions, function(assertion, name) {
            if (assertion && this.props.hasOwnProperty(name) && !assertion.call(this, this.props[name], value, path, dataWrapper)) {
                this.scope.error(path, "Param assertion " + name + " failed for type " + this.typeName + "; value: " + JSON.stringify(value));
            }
        }, this);

        if (def.onValidate.length) {
            _.each(def.onValidate, function(fn) {
                fn.call(this, value, path, dataWrapper);
            }, this);
        }
    };
};
<commit_msg>Keep ._super instead of .parent for types<commit_after>var _ = require('lodash');
var util = require('util');

var TypeConstructor = module.exports = {};

var typeStaticMethods = {
    hasProperty: function(propertyName) {
        return this.propertyNames.indexOf(propertyName) >= 0;
    },
    hasMethod: function(methodName) {
        return this.methodNames.indexOf(methodName) >= 0;
    },
    addChild: function(name) {
        this.children[name] = true;
    },
    eachChild: function(scope, deep, cb) {
        _.forOwn(this.children, function(exists, name) {
            var child = scope.getTypeOrNull(name);
            if (child) {
                cb(child);
                if (deep) {
                    child.eachChild(scope, deep, cb);
                }
            }
        });
    }
};

TypeConstructor.build = function(typeName, def) {
    var newType = this.buildTypeConstructor(def);
    var parent = def.parentType;

    var hasParent = !!def.parentType;
    if (hasParent) {
        util.inherits(newType, parent);
        parent.addChild(typeName);

        newType.propertyAssertions = def.propertyAssertions;
        newType.propertyNames = Object.keys(def.propertyAssertions).concat(parent.propertyNames);
        newType.methodNames = Object.keys(def.methods).concat(parent.methodNames);
    } else {
        newType.propertyAssertions = def.propertyAssertions;
        newType.propertyNames = Object.keys(def.propertyAssertions);
        newType.methodNames = Object.keys(def.methods);
    }

    newType.def = def;
    newType.children = {};
    newType.props = def.props;

    _.forOwn(typeStaticMethods, function(method, name) {
        newType[name] = method;
    });

    newType.prototype.validate = this.buildTypeValidation(def);
    newType.prototype.typeName = newType.typeName = typeName;

    _.forOwn(def.methods, function(fn, name) {
        newType.prototype[name] = fn;
    });

    return newType;

};

TypeConstructor.buildTypeConstructor = function(def) {
    return function(scope, props, schema) {
        if (def.parentType) {
            def.parentType.call(this, scope, props);
        }
        if (def.onCreate.length) {
            _.each(def.onCreate, function(fn) {
                fn.call(this, scope, props, schema);
            }, this);
        }
        if (def.methodCalls.length) {
            var callstack = {};
            _.each(def.methodCalls, function(proxy) {
                callstack[proxy.id] = this[proxy.name].apply(this, proxy.filteredArgs(callstack));
            }, this);
        }
        if (schema) {
            schema.call(this);
        }
    };
};

TypeConstructor.buildTypeValidation = function(def) {
    return function(value, path, dataWrapper) {
        if (def.typeAssertion && !def.typeAssertion.call(this, value)) {
            return this.scope.error(path, "Type assertion failed for type " + this.typeName);
        }

        if (def.parentType) {
            def.parentType.prototype.validate.call(this, value, path, dataWrapper);
        }

        _.forOwn(def.propertyAssertions, function(assertion, name) {
            if (assertion && this.props.hasOwnProperty(name) && !assertion.call(this, this.props[name], value, path, dataWrapper)) {
                this.scope.error(path, "Param assertion " + name + " failed for type " + this.typeName + "; value: " + JSON.stringify(value));
            }
        }, this);

        if (def.onValidate.length) {
            _.each(def.onValidate, function(fn) {
                fn.call(this, value, path, dataWrapper);
            }, this);
        }
    };
};
<|endoftext|>


<commit_before>'use strict';
var util = require('util');
var path = require('path');
var Configstore = require('configstore');
var request = require('request');
var colors = require('colors');

function UpdateNotifier(options) {
	options = options || {};

	if (!options.packageName && !options.packageVersion) {
		this.packageFile = require(path.resolve(path.dirname(module.parent.filename), options.packagePath || 'package'));
	}

	this.packageName = options.packageName || this.packageFile.name;
	this.packageVersion = options.packageVersion || this.packageFile.version;
	this.updateCheckInterval = options.updateCheckInterval || 1000 * 60 * 60 * 24; // 1 day
	this.registryUrl = options.registryUrl || 'http://registry.npmjs.org/%s';
	this.config = new Configstore('update-notifier-' + this.packageName, {
		optOut: false
	});
}

UpdateNotifier.prototype.check = function() {
	if (this.config.get('optOut')) {
		return;
	}

	// Only check for updates on a set interval
	if (new Date() - this.config.get('lastUpdateCheck') < this.updateCheckInterval) {
		return;
	}

	this.config.set('lastUpdateCheck', +new Date());
	this.update = this.config.get('update');
	this.config.del('update');

	this.checkNpm(function(update) {
		if (update.type && update.type !== 'latest') {
			this.config.set('update', update);
		}
	}.bind(this));
};

UpdateNotifier.prototype.checkNpm = function(cb) {
	var url = util.format(this.registryUrl, this.packageName);

	request({url: url, json: true}, function(error, response, body) {
		var currentVersion, latestVersion;

		if (body.error) {
			error = 'Package not found';
		}

		currentVersion = this.packageVersion;
		latestVersion = Object.keys(body.time).reverse()[0];

		cb({
			latest: latestVersion,
			current: currentVersion,
			type: this.updateType(currentVersion, latestVersion),
			date: body.time[latestVersion],
			name: this.packageName,
			error: error
		});
	}.bind(this));
};

UpdateNotifier.prototype.notify = function(customMessage) {
	var message =
		'-----------------------------------------'.blue.bold +
		'\nUpdate available: ' + this.update.latest.green.bold +
		(' (current: ' + this.update.current + ')').grey +
		'\nRun ' + ('npm update -g ' + this.packageName).magenta +
		' to update\n' +
		'-----------------------------------------'.blue;
	if (customMessage) {
		process.on('exit', function() {
			console.log(typeof customMessage === 'string' ? customMessage : message);
		});
	} else {
		console.log(message);
	}
};

UpdateNotifier.prototype.updateType = function(currentVersion, latestVersion) {
	if (currentVersion  === latestVersion) {
		return 'latest';
	}

	currentVersion = currentVersion.split('.');
	latestVersion = latestVersion.split('.');

	if (latestVersion[0] > currentVersion[0]) {
		return 'major';
	} else if (latestVersion[1] > currentVersion[1]) {
		return 'minor';
	} else if (latestVersion[2] > currentVersion[2]) {
		return 'patch';
	}
};

module.exports = function(options) {
	var updateNotifier = new UpdateNotifier(options);
	updateNotifier.check();
	return updateNotifier;
};
<commit_msg>Fix issue when passing packageName but not packageVersion and vice-versa<commit_after>'use strict';
var util = require('util');
var path = require('path');
var Configstore = require('configstore');
var request = require('request');
var colors = require('colors');

function UpdateNotifier(options) {
	options = options || {};

	if (!options.packageName || !options.packageVersion) {
		this.packageFile = require(path.resolve(path.dirname(module.parent.filename), options.packagePath || 'package'));
	}

	this.packageName = options.packageName || this.packageFile.name;
	this.packageVersion = options.packageVersion || this.packageFile.version;
	this.updateCheckInterval = options.updateCheckInterval || 1000 * 60 * 60 * 24; // 1 day
	this.registryUrl = options.registryUrl || 'http://registry.npmjs.org/%s';
	this.config = new Configstore('update-notifier-' + this.packageName, {
		optOut: false
	});
}

UpdateNotifier.prototype.check = function() {
	if (this.config.get('optOut')) {
		return;
	}

	// Only check for updates on a set interval
	if (new Date() - this.config.get('lastUpdateCheck') < this.updateCheckInterval) {
		return;
	}

	this.config.set('lastUpdateCheck', +new Date());
	this.update = this.config.get('update');
	this.config.del('update');

	this.checkNpm(function(update) {
		if (update.type && update.type !== 'latest') {
			this.config.set('update', update);
		}
	}.bind(this));
};

UpdateNotifier.prototype.checkNpm = function(cb) {
	var url = util.format(this.registryUrl, this.packageName);

	request({url: url, json: true}, function(error, response, body) {
		var currentVersion, latestVersion;

		if (body.error) {
			error = 'Package not found';
		}

		currentVersion = this.packageVersion;
		latestVersion = Object.keys(body.time).reverse()[0];

		cb({
			latest: latestVersion,
			current: currentVersion,
			type: this.updateType(currentVersion, latestVersion),
			date: body.time[latestVersion],
			name: this.packageName,
			error: error
		});
	}.bind(this));
};

UpdateNotifier.prototype.notify = function(customMessage) {
	var message =
		'-----------------------------------------'.blue.bold +
		'\nUpdate available: ' + this.update.latest.green.bold +
		(' (current: ' + this.update.current + ')').grey +
		'\nRun ' + ('npm update -g ' + this.packageName).magenta +
		' to update\n' +
		'-----------------------------------------'.blue;
	if (customMessage) {
		process.on('exit', function() {
			console.log(typeof customMessage === 'string' ? customMessage : message);
		});
	} else {
		console.log(message);
	}
};

UpdateNotifier.prototype.updateType = function(currentVersion, latestVersion) {
	if (currentVersion  === latestVersion) {
		return 'latest';
	}

	currentVersion = currentVersion.split('.');
	latestVersion = latestVersion.split('.');

	if (latestVersion[0] > currentVersion[0]) {
		return 'major';
	} else if (latestVersion[1] > currentVersion[1]) {
		return 'minor';
	} else if (latestVersion[2] > currentVersion[2]) {
		return 'patch';
	}
};

module.exports = function(options) {
	var updateNotifier = new UpdateNotifier(options);
	updateNotifier.check();
	return updateNotifier;
};
<|endoftext|>


<commit_before>/*jslint forin:true sub:true anon:true, sloppy:true, stupid:true nomen:true, node:true continue:true*/

/*
 * Copyright (c) 2012, Yahoo! Inc.  All rights reserved.
 * Copyrights licensed under the New BSD License.
 * See the accompanying LICENSE file for terms.
 */

var fs = require("fs");
var glob = require("glob");
var path = require('path');
var url = require('url');
var async = require('async');
var Properties = require("../util/properties");
var log4js = require("log4js");
var LibManager = require('../util/libmanager');
var FileUtil = require("../util/fileutil");
var ErrorManager = require("../util/errormanager");
var PhantomJsSetup = require("./phantomJsSetup.js");
var Servermanager = require("../../arrow_server/arrowservermanager.js");

function ArrowSetup(config, argv) {
    var __dirname = global.appRoot;
    this.config = config;
    this.argv = argv;
}

ArrowSetup.prototype.setup = function (callback) {
    var self = this;

    async.series(
        [
            function(cb) {
                self.setuplog4js(function() {
                    return cb(null, 'setuplog4js');
                });
            },

            function(cb) {
                self.setupReportDir(function() {
                    return cb(null, 'setupReportDir');
                });
            },

            function(cb) {
                self.setupDefaultDriverName(function() {
                    return cb(null, 'setupDefaultDriverName');
                });
            },

            function(cb) {
                self.setupTestEngine(function() {
                    return cb(null, 'setupTestEngine');
                });
            },

            function(cb) {
                self.setupDefaultLib(function() {
                    return cb(null, 'setupDefaultLib');
                });
            },

            function(cb) {
                self.setupHeadlessParam(function() {
                    return cb(null, 'setupHeadlessParam');
                });
            },

            function(cb) {
                self.setupCapabilities(function() {
                    return cb(null, 'setupCapabilities');
                });
            },

            function(cb) {
                self.setupMisc(function() {
                    return cb(null, 'setupMisc');
                });
            },

            function(cb) {
                self.setupReplaceParam(function() {
                    return cb(null, 'setupReplaceParam');
                });
            },

            function(cb) {
                self.setupDefaultParam(function() {
                    return cb(null, 'setupDefaultParam');
                });
            },

            function(cb) {
                self.startPhantomJs(function() {
                    return cb(null, 'startPhantomJs');
                });
            },

            function(cb) {
                self.startArrowServer(function() {
                    return cb(null, 'startArrowServer');
                });
            },

            function(cb) {
                self.errorCheck(function() {
                    return cb(null, 'errorCheck');
                });
            },

            function(cb) {
                self.setupUseSSL(function() {
                    return cb(null, 'errorCheck');
                });
            }

        ],
        function(err, results) {
            callback();
        }
    );

};

ArrowSetup.prototype.setupUseSSL = function (cb) {
    var self = this;
    self.logger.trace('setupUseSSL starts');
    if (this.argv.useSSL){
        this.config.useSSL = this.argv.useSSL;
    }
    self.logger.trace('setupUseSSL ends');
    if (cb) {
        cb();
    }
};

ArrowSetup.prototype.setupReplaceParam = function (cb) {

    var self = this;
    self.logger.trace('setupReplaceParam starts');
    if (this.argv.replaceParamJSON) {
        this.config.replaceParamJSON = this.argv.replaceParamJSON;
    }
    self.logger.trace('setupReplaceParam ends');
    if (cb) {
        cb();
    }

};

ArrowSetup.prototype.setupDefaultParam = function (cb) {

    var self = this;
    self.logger.trace('setupDefaultParam starts');
    if (this.argv.defaultParamJSON) {
        this.config.defaultParamJSON = this.argv.defaultParamJSON;
    }
    self.logger.trace('setupDefaultParam ends');
    if (cb) {
        cb();
    }

};

ArrowSetup.prototype.errorCheck = function (cb) {

    var self = this, em = ErrorManager.getInstance(),
        environment = function() {
            if (self.argv.argv.cooked) {
                // em.errorLog("self.argv.argv.cooked {0}",  JSON.stringify(self.argv.argv.cooked));
                var cooked = JSON.stringify(self.argv.argv.cooked), proc = self.mock || process;
                cooked.replace(/"--context","([\w\W]*?)"/, function (match, context) {
                    // em.errorLog("match is {0}, context is {1}", match, context);
                    context.replace(/environment:([\w\W]*)/, function (match, env) {
                        // em.errorLog("match is {0}, env is {1}", match, env);
                        if (self.dimensions[0].environment[env] === undefined) {
                            em.errorLog(1000, env, self.dimensionsFile);
                            proc.exit(1);
                        } else {
                            self.environment = env;
                        }
                    });
                });
            }
        },
        dimensions = function() {
            // To Do : should check dimensions file with Json schema
            // em.errorLog("config {0} argv {1}", JSON.stringify(self.config), JSON.stringify(self.argv));
            var dimensions = self.argv.dimensions || self.config.dimensions || "", dimJson, i = 0, proc = self.mock || process,
                errorMessage, argv = self.argv.argv || {}, remain = JSON.stringify(argv.remain) || "",
                dimensionsExist = function () {
                    return remain.match(/"[\w\W]*\.json"/) && dimensions.length > 0;
                };

            if (dimensionsExist()) {
                try {
                    self.dimensionsFile = dimensions;
                    dimJson = JSON.parse(fs.readFileSync(dimensions, "utf-8"));
                } catch (e) {
                    errorMessage = e.message;
                }
                if (dimJson && dimJson.length > 0 && dimJson[i].dimensions) {
                    self.dimensions = dimJson[i].dimensions;
                    // em.errorLog("dimensions {0}", JSON.stringify(self.dimensions));
                } else {
                    em.errorLog(1001, dimensions, errorMessage || JSON.stringify(dimJson));
                    proc.exit(1);
                }
                environment();
            }
        },
        invalidArgument = function() {
            var argv = self.argv, arg, value, isNotValid = false, proc = self.mock || process,
                mandatory = { "seleniumHost" : true };
            for (arg in argv) {
                if (mandatory[arg] === undefined || !mandatory[arg]) {
                    continue;
                }
                value = argv[arg];
                if (value === null || value === "null") {
                    em.errorLog(1006, arg, "null");
                    isNotValid = true;
                } else if (value === '') {
                    em.errorLog(1006, arg, "empty string");
                    isNotValid = true;
                } else if (value === undefined) {
                    em.errorLog(1006, arg, "undefined");
                    isNotValid = true;
                }
            }
            if (isNotValid) {
                proc.exit(1);
            }
            dimensions();
        };

    em.logger = self.mock || em.logger;
    invalidArgument();
    self.logger.trace('errorCheck ends..' + cb);
    if (cb) {
        cb();
    }

};

ArrowSetup.prototype.setupReportDir = function (cb) {

    var self = this,
        artifactsUrl,
        arrowTargetDir = 'arrow-target',
        arrowReportDir = 'arrow-report',
        fileUtil = new FileUtil(),
        targetFolderRelPath, // relative path till target directory
        targetFolderPath, // path till target directory
        reportFolderPath,
        reportFolder = "";

    self.logger.trace('setupReportDir starts');
    global.reportFolder = "";

    if (this.argv.artifactsUrl) {
        artifactsUrl = this.argv.artifactsUrl;
    }

    // To generate the reports, if either report is true or reportFolder is passed
    if (this.argv.reportFolder) {
        reportFolder = this.argv.reportFolder;
    }
    targetFolderRelPath = path.join(reportFolder,arrowTargetDir); // Relative path to target directory
    targetFolderPath =  path.resolve(global.workingDirectory, targetFolderRelPath); // Absolute path to target directory

    // Cleanup report folder if keepTestReport set to false or undefined
    if (this.argv.keepTestReport === undefined || false === this.argv.keepTestReport) {
        fileUtil.removeDirectory(targetFolderPath);
    }

    if (this.argv.report || this.argv.reportFolder) {
        // Get path till arrow-report directory
        reportFolderPath = path.resolve(targetFolderPath, arrowReportDir);
        // Create arrow-report directory
        fileUtil.createDirectory(reportFolderPath);

        this.argv.reportFolder = targetFolderPath;
        global.reportFolder = this.argv.reportFolder || "";

    }

    if (artifactsUrl) {
        artifactsUrl = path.join(artifactsUrl , targetFolderRelPath);
        global.artifactsUrl = artifactsUrl;
    }

    self.logger.trace('setupReportDir ends');

    if (cb) {
        cb();
    }

};

ArrowSetup.prototype.setupMisc = function (cb) {

    var self = this;
    self.logger.trace('setupMisc starts');
    if (this.argv.coverage !== undefined) {
        this.config.coverage = this.argv.coverage;
    }

    if (this.argv.report === undefined && this.config.report) {
        this.argv.report = this.config.report;
    }

    if (this.argv.dimensions) {
        this.argv.dimensions = path.resolve(global.workingDirectory, this.argv.dimensions);
        this.config.dimensions = this.argv.dimensions;
    }
    self.logger.trace('setupMisc ends');
    if (cb) {
        cb();
    }

};

ArrowSetup.prototype.setuplog4js = function (cb) {

    var logLevel;
    logLevel = this.config["logLevel"];
    log4js.setGlobalLogLevel(logLevel);
    log4js.restoreConsole();
    this.logger = log4js.getLogger("ArrowSetup");
    this.logger.trace('setuplog4js ends');
    if (cb) {
        cb();
    }

};

ArrowSetup.prototype.setupDefaultDriverName = function (cb) {

    var self = this;
    self.logger.trace('setupDefaultDriverName starts');
    // turn on reuseSession, if browser is being reused
    // adding support for "reuse-" too, just in case if a null version is passed with browser.
    if ("reuse" === this.argv.browser || "reuse-" === this.argv.browser) {
        this.argv.reuseSession = true;

        if (!this.argv.driver) {
            this.argv.driver = "selenium";
        }
        delete this.argv.browser;
    }

    // setup the selenium host using the auto hookup if possible
    this.setupSeleniumHost(function() {
        self.logger.trace('setupDefaultDriverName ends');
        if (cb) {
            cb();
        }

    });

};

ArrowSetup.prototype.setupSeleniumHost = function (cb) {

    var self = this;
    self.logger.trace('In setupSeleniumHost starts');
    var wdHubHost,
        wdStatusFile = "/tmp/arrow_sel_server.status";

    // setup the selenium host using the auto hookup if possible
    wdHubHost = this.config["seleniumHost"];
    if (0 === wdHubHost.length) {
        // check if we have a hooked up server
        try {
            fs.statSync(wdStatusFile).isFile();
            wdHubHost = fs.readFileSync(wdStatusFile, "utf-8");
        } catch (ex) {
        }

        // final default
        if (wdHubHost.length === 0) {
            wdHubHost = "http://localhost:4444/wd/hub";
        }
        this.config["seleniumHost"] = wdHubHost;
        self.logger.trace('setupSeleniumHost ends');
        if (cb) {
            cb();
        }

    } else {
        self.logger.trace('setupSeleniumHost ends');
        if (cb) {
            cb();
        }

    }

};

ArrowSetup.prototype.setupDefaultLib = function (cb) {

    var self = this;
    self.logger.trace('setupDefaultLib starts');
    this.argv.lib = new LibManager().getAllCommonLib(this.config, this.config.lib);
    this.logger.debug("Commandline + Common Libs for Test :" + this.config.lib);
    self.logger.trace('setupDefaultLib ends');
    if (cb) {
        cb();
    }

};

ArrowSetup.prototype.setupHeadlessParam = function (cb) {

    var self = this,
        hd,
        results,
        ext;

    self.logger.trace('setupHeadlessParam starts');

    if (!this.argv.argv.remain[0]) {
        self.logger.trace('setupHeadlessParam ends');
        if (cb) {
            cb();
        }

    }

    hd = this.argv.argv.remain[0];

    results = glob.sync(hd);
    this.logger.info("Glob result: " + results);

    if (0 === results.length) {
        this.logger.error("ERROR : No Test or Descriptor Found, while looking for : " + hd);
        process.exit(1);
    }

    ext = path.extname(results[0]);
    // check the first file to determine the type
    if (".json" === ext) {
        this.config.arrDescriptor = results;
    } else if ((".js" === ext) || (".html" === ext)) {
        if (results.length > 1) {
            this.argv.tests = results;
        } else {
            this.argv.test = results[0];
        }
    } else {
        this.logger.fatal("Unknown test file type " + results[0]);
        process.exit(0);
    }
    self.logger.trace('setupHeadlessParam ends');
    if (cb) {
        cb();
    }

};

ArrowSetup.prototype.setupCapabilities = function (cb) {

    var self = this;
    self.logger.trace('setupCapabilities starts');
    if (this.argv.capabilities) {
        this.config.capabilities = this.argv.capabilities;
    }
    self.logger.trace('setupCapabilities ends');
    if (cb) {
        cb();
    }

};

ArrowSetup.prototype.setupTestEngine = function (cb) {

    var self = this;
    self.logger.trace('setupTestEngine starts');
    this.config.engine = "yui";
    if (this.argv.engine) {
        this.config.engine = this.argv.engine;
    }
    if (this.argv.engineConfig) {
        try {
            this.config.engineConfig = this.argv.engineConfig;
            if (fs.statSync(this.argv.engineConfig).isFile()) {
                //get absolute path before chdir
                this.config.engineConfig = path.resolve("", this.argv.engineConfig);
            }
            self.logger.trace('setupTestEngine ends');
            if (cb) {
                cb();
            }

        } catch (e) {
            self.logger.trace('setupTestEngine ends');
            if (cb) {
                cb();
            }

        }
    } else {
        self.logger.trace('setupTestEngine ends');
        if (cb) {
            cb();
        }

    }

};

ArrowSetup.prototype.startArrowServer = function(cb) {

    var self = this;
    self.logger.trace('startArrowServer starts');
    if (this.config.startArrowServer) {
        Servermanager.startArrowServer(function(arrowServerStarted) {
            if (arrowServerStarted === false) {
                self.logger.info('Failed to start Arrow Server. Exiting !!!');
                process.exit(1);
            }
            self.logger.trace('startArrowServer ends');
            if (cb) {
                cb();
            }

        });
    } else {
        self.logger.trace('startArrowServer ends');
        if (cb) {
            cb();
        }

    }

};

ArrowSetup.prototype.startPhantomJs = function(cb) {

    var self = this;
    self.logger.trace('startPhantomJs starts');

    if (this.config.startPhantomJs) {

        PhantomJsSetup.startPhantomJs(self.config.ignoreSslErrorsPhantomJs, function(phantomHost) {
            self.logger.trace('startPhantomJs ends..' + phantomHost);

            if (!phantomHost) {
                self.logger.info('Could not start phantomjs. Exiting.');
                process.exit(1);
            }

            self.config["phantomHost"] = phantomHost;
            if (cb) {
                cb();
            }
        });
    } else if (cb) {
        self.logger.trace('startPhantomJs ends');
        cb();
    }

};

module.exports = ArrowSetup;<commit_msg>Using url.resolve to resolve artifacts url<commit_after>/*jslint forin:true sub:true anon:true, sloppy:true, stupid:true nomen:true, node:true continue:true*/

/*
 * Copyright (c) 2012, Yahoo! Inc.  All rights reserved.
 * Copyrights licensed under the New BSD License.
 * See the accompanying LICENSE file for terms.
 */

var fs = require("fs");
var glob = require("glob");
var path = require('path');
var url = require('url');
var async = require('async');
var Properties = require("../util/properties");
var log4js = require("log4js");
var LibManager = require('../util/libmanager');
var FileUtil = require("../util/fileutil");
var ErrorManager = require("../util/errormanager");
var PhantomJsSetup = require("./phantomJsSetup.js");
var Servermanager = require("../../arrow_server/arrowservermanager.js");

function ArrowSetup(config, argv) {
    var __dirname = global.appRoot;
    this.config = config;
    this.argv = argv;
}

ArrowSetup.prototype.setup = function (callback) {
    var self = this;

    async.series(
        [
            function(cb) {
                self.setuplog4js(function() {
                    return cb(null, 'setuplog4js');
                });
            },

            function(cb) {
                self.setupReportDir(function() {
                    return cb(null, 'setupReportDir');
                });
            },

            function(cb) {
                self.setupDefaultDriverName(function() {
                    return cb(null, 'setupDefaultDriverName');
                });
            },

            function(cb) {
                self.setupTestEngine(function() {
                    return cb(null, 'setupTestEngine');
                });
            },

            function(cb) {
                self.setupDefaultLib(function() {
                    return cb(null, 'setupDefaultLib');
                });
            },

            function(cb) {
                self.setupHeadlessParam(function() {
                    return cb(null, 'setupHeadlessParam');
                });
            },

            function(cb) {
                self.setupCapabilities(function() {
                    return cb(null, 'setupCapabilities');
                });
            },

            function(cb) {
                self.setupMisc(function() {
                    return cb(null, 'setupMisc');
                });
            },

            function(cb) {
                self.setupReplaceParam(function() {
                    return cb(null, 'setupReplaceParam');
                });
            },

            function(cb) {
                self.setupDefaultParam(function() {
                    return cb(null, 'setupDefaultParam');
                });
            },

            function(cb) {
                self.startPhantomJs(function() {
                    return cb(null, 'startPhantomJs');
                });
            },

            function(cb) {
                self.startArrowServer(function() {
                    return cb(null, 'startArrowServer');
                });
            },

            function(cb) {
                self.errorCheck(function() {
                    return cb(null, 'errorCheck');
                });
            },

            function(cb) {
                self.setupUseSSL(function() {
                    return cb(null, 'errorCheck');
                });
            }

        ],
        function(err, results) {
            callback();
        }
    );

};

ArrowSetup.prototype.setupUseSSL = function (cb) {
    var self = this;
    self.logger.trace('setupUseSSL starts');
    if (this.argv.useSSL){
        this.config.useSSL = this.argv.useSSL;
    }
    self.logger.trace('setupUseSSL ends');
    if (cb) {
        cb();
    }
};

ArrowSetup.prototype.setupReplaceParam = function (cb) {

    var self = this;
    self.logger.trace('setupReplaceParam starts');
    if (this.argv.replaceParamJSON) {
        this.config.replaceParamJSON = this.argv.replaceParamJSON;
    }
    self.logger.trace('setupReplaceParam ends');
    if (cb) {
        cb();
    }

};

ArrowSetup.prototype.setupDefaultParam = function (cb) {

    var self = this;
    self.logger.trace('setupDefaultParam starts');
    if (this.argv.defaultParamJSON) {
        this.config.defaultParamJSON = this.argv.defaultParamJSON;
    }
    self.logger.trace('setupDefaultParam ends');
    if (cb) {
        cb();
    }

};

ArrowSetup.prototype.errorCheck = function (cb) {

    var self = this, em = ErrorManager.getInstance(),
        environment = function() {
            if (self.argv.argv.cooked) {
                // em.errorLog("self.argv.argv.cooked {0}",  JSON.stringify(self.argv.argv.cooked));
                var cooked = JSON.stringify(self.argv.argv.cooked), proc = self.mock || process;
                cooked.replace(/"--context","([\w\W]*?)"/, function (match, context) {
                    // em.errorLog("match is {0}, context is {1}", match, context);
                    context.replace(/environment:([\w\W]*)/, function (match, env) {
                        // em.errorLog("match is {0}, env is {1}", match, env);
                        if (self.dimensions[0].environment[env] === undefined) {
                            em.errorLog(1000, env, self.dimensionsFile);
                            proc.exit(1);
                        } else {
                            self.environment = env;
                        }
                    });
                });
            }
        },
        dimensions = function() {
            // To Do : should check dimensions file with Json schema
            // em.errorLog("config {0} argv {1}", JSON.stringify(self.config), JSON.stringify(self.argv));
            var dimensions = self.argv.dimensions || self.config.dimensions || "", dimJson, i = 0, proc = self.mock || process,
                errorMessage, argv = self.argv.argv || {}, remain = JSON.stringify(argv.remain) || "",
                dimensionsExist = function () {
                    return remain.match(/"[\w\W]*\.json"/) && dimensions.length > 0;
                };

            if (dimensionsExist()) {
                try {
                    self.dimensionsFile = dimensions;
                    dimJson = JSON.parse(fs.readFileSync(dimensions, "utf-8"));
                } catch (e) {
                    errorMessage = e.message;
                }
                if (dimJson && dimJson.length > 0 && dimJson[i].dimensions) {
                    self.dimensions = dimJson[i].dimensions;
                    // em.errorLog("dimensions {0}", JSON.stringify(self.dimensions));
                } else {
                    em.errorLog(1001, dimensions, errorMessage || JSON.stringify(dimJson));
                    proc.exit(1);
                }
                environment();
            }
        },
        invalidArgument = function() {
            var argv = self.argv, arg, value, isNotValid = false, proc = self.mock || process,
                mandatory = { "seleniumHost" : true };
            for (arg in argv) {
                if (mandatory[arg] === undefined || !mandatory[arg]) {
                    continue;
                }
                value = argv[arg];
                if (value === null || value === "null") {
                    em.errorLog(1006, arg, "null");
                    isNotValid = true;
                } else if (value === '') {
                    em.errorLog(1006, arg, "empty string");
                    isNotValid = true;
                } else if (value === undefined) {
                    em.errorLog(1006, arg, "undefined");
                    isNotValid = true;
                }
            }
            if (isNotValid) {
                proc.exit(1);
            }
            dimensions();
        };

    em.logger = self.mock || em.logger;
    invalidArgument();
    self.logger.trace('errorCheck ends..' + cb);
    if (cb) {
        cb();
    }

};

ArrowSetup.prototype.setupReportDir = function (cb) {

    var self = this,
        artifactsUrl,
        arrowTargetDir = 'arrow-target',
        arrowReportDir = 'arrow-report',
        fileUtil = new FileUtil(),
        targetFolderRelPath, // relative path till target directory
        targetFolderPath, // path till target directory
        reportFolderPath,
        reportFolder = "";

    self.logger.trace('setupReportDir starts');
    global.reportFolder = "";

    if (this.argv.artifactsUrl) {
        artifactsUrl = this.argv.artifactsUrl;
    }

    // To generate the reports, if either report is true or reportFolder is passed
    if (this.argv.reportFolder) {
        reportFolder = this.argv.reportFolder;
    }
    targetFolderRelPath = path.join(reportFolder,arrowTargetDir); // Relative path to target directory
    targetFolderPath =  path.resolve(global.workingDirectory, targetFolderRelPath); // Absolute path to target directory

    // Cleanup report folder if keepTestReport set to false or undefined
    if (this.argv.keepTestReport === undefined || false === this.argv.keepTestReport) {
        fileUtil.removeDirectory(targetFolderPath);
    }

    if (this.argv.report || this.argv.reportFolder) {
        // Get path till arrow-report directory
        reportFolderPath = path.resolve(targetFolderPath, arrowReportDir);
        // Create arrow-report directory
        fileUtil.createDirectory(reportFolderPath);

        this.argv.reportFolder = targetFolderPath;
        global.reportFolder = this.argv.reportFolder || "";

    }
    if (artifactsUrl) {
        artifactsUrl = url.resolve(artifactsUrl , targetFolderRelPath);
        global.artifactsUrl = artifactsUrl;
    }
    self.logger.trace('setupReportDir ends');

    if (cb) {
        cb();
    }

};

ArrowSetup.prototype.setupMisc = function (cb) {

    var self = this;
    self.logger.trace('setupMisc starts');
    if (this.argv.coverage !== undefined) {
        this.config.coverage = this.argv.coverage;
    }

    if (this.argv.report === undefined && this.config.report) {
        this.argv.report = this.config.report;
    }

    if (this.argv.dimensions) {
        this.argv.dimensions = path.resolve(global.workingDirectory, this.argv.dimensions);
        this.config.dimensions = this.argv.dimensions;
    }
    self.logger.trace('setupMisc ends');
    if (cb) {
        cb();
    }

};

ArrowSetup.prototype.setuplog4js = function (cb) {

    var logLevel;
    logLevel = this.config["logLevel"];
    log4js.setGlobalLogLevel(logLevel);
    log4js.restoreConsole();
    this.logger = log4js.getLogger("ArrowSetup");
    this.logger.trace('setuplog4js ends');
    if (cb) {
        cb();
    }

};

ArrowSetup.prototype.setupDefaultDriverName = function (cb) {

    var self = this;
    self.logger.trace('setupDefaultDriverName starts');
    // turn on reuseSession, if browser is being reused
    // adding support for "reuse-" too, just in case if a null version is passed with browser.
    if ("reuse" === this.argv.browser || "reuse-" === this.argv.browser) {
        this.argv.reuseSession = true;

        if (!this.argv.driver) {
            this.argv.driver = "selenium";
        }
        delete this.argv.browser;
    }

    // setup the selenium host using the auto hookup if possible
    this.setupSeleniumHost(function() {
        self.logger.trace('setupDefaultDriverName ends');
        if (cb) {
            cb();
        }

    });

};

ArrowSetup.prototype.setupSeleniumHost = function (cb) {

    var self = this;
    self.logger.trace('In setupSeleniumHost starts');
    var wdHubHost,
        wdStatusFile = "/tmp/arrow_sel_server.status";

    // setup the selenium host using the auto hookup if possible
    wdHubHost = this.config["seleniumHost"];
    if (0 === wdHubHost.length) {
        // check if we have a hooked up server
        try {
            fs.statSync(wdStatusFile).isFile();
            wdHubHost = fs.readFileSync(wdStatusFile, "utf-8");
        } catch (ex) {
        }

        // final default
        if (wdHubHost.length === 0) {
            wdHubHost = "http://localhost:4444/wd/hub";
        }
        this.config["seleniumHost"] = wdHubHost;
        self.logger.trace('setupSeleniumHost ends');
        if (cb) {
            cb();
        }

    } else {
        self.logger.trace('setupSeleniumHost ends');
        if (cb) {
            cb();
        }

    }

};

ArrowSetup.prototype.setupDefaultLib = function (cb) {

    var self = this;
    self.logger.trace('setupDefaultLib starts');
    this.argv.lib = new LibManager().getAllCommonLib(this.config, this.config.lib);
    this.logger.debug("Commandline + Common Libs for Test :" + this.config.lib);
    self.logger.trace('setupDefaultLib ends');
    if (cb) {
        cb();
    }

};

ArrowSetup.prototype.setupHeadlessParam = function (cb) {

    var self = this,
        hd,
        results,
        ext;

    self.logger.trace('setupHeadlessParam starts');

    if (!this.argv.argv.remain[0]) {
        self.logger.trace('setupHeadlessParam ends');
        if (cb) {
            cb();
        }

    }

    hd = this.argv.argv.remain[0];

    results = glob.sync(hd);
    this.logger.info("Glob result: " + results);

    if (0 === results.length) {
        this.logger.error("ERROR : No Test or Descriptor Found, while looking for : " + hd);
        process.exit(1);
    }

    ext = path.extname(results[0]);
    // check the first file to determine the type
    if (".json" === ext) {
        this.config.arrDescriptor = results;
    } else if ((".js" === ext) || (".html" === ext)) {
        if (results.length > 1) {
            this.argv.tests = results;
        } else {
            this.argv.test = results[0];
        }
    } else {
        this.logger.fatal("Unknown test file type " + results[0]);
        process.exit(0);
    }
    self.logger.trace('setupHeadlessParam ends');
    if (cb) {
        cb();
    }

};

ArrowSetup.prototype.setupCapabilities = function (cb) {

    var self = this;
    self.logger.trace('setupCapabilities starts');
    if (this.argv.capabilities) {
        this.config.capabilities = this.argv.capabilities;
    }
    self.logger.trace('setupCapabilities ends');
    if (cb) {
        cb();
    }

};

ArrowSetup.prototype.setupTestEngine = function (cb) {

    var self = this;
    self.logger.trace('setupTestEngine starts');
    this.config.engine = "yui";
    if (this.argv.engine) {
        this.config.engine = this.argv.engine;
    }
    if (this.argv.engineConfig) {
        try {
            this.config.engineConfig = this.argv.engineConfig;
            if (fs.statSync(this.argv.engineConfig).isFile()) {
                //get absolute path before chdir
                this.config.engineConfig = path.resolve("", this.argv.engineConfig);
            }
            self.logger.trace('setupTestEngine ends');
            if (cb) {
                cb();
            }

        } catch (e) {
            self.logger.trace('setupTestEngine ends');
            if (cb) {
                cb();
            }

        }
    } else {
        self.logger.trace('setupTestEngine ends');
        if (cb) {
            cb();
        }

    }

};

ArrowSetup.prototype.startArrowServer = function(cb) {

    var self = this;
    self.logger.trace('startArrowServer starts');
    if (this.config.startArrowServer) {
        Servermanager.startArrowServer(function(arrowServerStarted) {
            if (arrowServerStarted === false) {
                self.logger.info('Failed to start Arrow Server. Exiting !!!');
                process.exit(1);
            }
            self.logger.trace('startArrowServer ends');
            if (cb) {
                cb();
            }

        });
    } else {
        self.logger.trace('startArrowServer ends');
        if (cb) {
            cb();
        }

    }

};

ArrowSetup.prototype.startPhantomJs = function(cb) {

    var self = this;
    self.logger.trace('startPhantomJs starts');

    if (this.config.startPhantomJs) {

        PhantomJsSetup.startPhantomJs(self.config.ignoreSslErrorsPhantomJs, function(phantomHost) {
            self.logger.trace('startPhantomJs ends..' + phantomHost);

            if (!phantomHost) {
                self.logger.info('Could not start phantomjs. Exiting.');
                process.exit(1);
            }

            self.config["phantomHost"] = phantomHost;
            if (cb) {
                cb();
            }
        });
    } else if (cb) {
        self.logger.trace('startPhantomJs ends');
        cb();
    }

};

module.exports = ArrowSetup;<|endoftext|>


<commit_before>export const promisify = (fn, NativeModule) => (...args) => {
  return new Promise((resolve, reject) => {
    const handler = (err, resp) => {
      setTimeout(() => {
        err ? reject(err) : resolve(resp);
      }, 0);
    }
    args.push(handler);
    (typeof fn === 'function' ? fn : NativeModule[fn])
      .call(NativeModule, ...args);
  });
};

export default promisify
<commit_msg>implemented new promisify util<commit_after>const handler = (resolve, reject, err, resp) => {
  setImmediate(() => {
    if (err) return reject(err);
    return resolve(resp);
  });
};

export default(fn, NativeModule) => (...args) => {
  return new Promise((resolve, reject) => {
    const _fn = typeof fn === 'function' ? fn : NativeModule[fn];
    if (!_fn || typeof _fn !== 'function') return reject(new Error('Missing function for promisify.'));
    return fn.apply(NativeModule, ...args, handler.bind(handler, resolve, reject));
  });
};
<|endoftext|>


<commit_before>
module.exports = readJson;

var fs = require("fs"),
  semver = require("./semver"),
  log = require("../utils").log;

function readJson (jsonFile, cb) {
  log(jsonFile, "readJson");
  fs.readFile(jsonFile, function (er, jsonString) {
    if (er) return cb(er, jsonString);
    var json;
    try {
      json = JSON.parse(jsonString);
    } catch (ex) {
      return cb(new Error(
        "Failed to parse json file: "+jsonFile+"\n"+ex.message+"\n"+jsonString));
    }
    json.name = json.name.replace(/([^\w-]|_)+/g, '-');
    // allow semvers, but also stuff like
    // 0.1.2beta-L24561-2010-02-25-13-41-32-903 for test/link packages.
    if (!(semver.valid(json.version))) {
      return cb(new Error("Invalid version: "+json.version));
    }
    var key = json.name+"-"+json.version;
    json._npmKey = key;
    cb(null, json);
  });
};
<commit_msg>Add an engine check when reading the json.<commit_after>
module.exports = readJson;

var fs = require("fs"),
  semver = require("./semver"),
  log = require("../utils").log;

function readJson (jsonFile, cb) {
  log(jsonFile, "readJson");
  fs.readFile(jsonFile, function (er, jsonString) {
    if (er) return cb(er, jsonString);
    var json;
    try {
      json = JSON.parse(jsonString);
    } catch (ex) {
      return cb(new Error(
        "Failed to parse json file: "+jsonFile+"\n"+ex.message+"\n"+jsonString));
    }
    json.name = json.name.replace(/([^\w-]|_)+/g, '-');
    // allow semvers, but also stuff like
    // 0.1.2beta-L24561-2010-02-25-13-41-32-903 for test/link packages.
    if (!(semver.valid(json.version))) {
      return cb(new Error("Invalid version: "+json.version));
    }

    var key = json.name+"-"+json.version;
    json._npmKey = key;
    testEngine(json, cb);
  });
};

function testEngine (json, cb) {
  if (!json.engines) return cb(null, json);

  var nodeVer = process.version,
    ok = false;
  if (Array.isArray(json.engines)) {
    // Packages/1.0 commonjs style, with an array.
    // hack it to just hang a "node" member with the version range,
    // then do the npm-style check below.
    for (var i = 0, l = json.engines.length; i < l; i ++) {
      var e = json.engines[i].trim();
      if (e.substr(0, 4) === "node") {
        json.engines.node = e.substr(4);
        break;
      }
    }
  }

  if (!json.engines.node) nodeNotSupported(cb);
  else if (!semver.satisfies(nodeVer, json.engines.node)) {
    nodeUnsatisfied(nodeVer, json.engines.node, cb);
  }
  else cb(null, json);
}

function nodeNotSupported (cb) { cb(new Error("node not supported")) }
function nodeUnsatisfied (nodeVer, e, cb) {
  cb(new Error("node version not compatible: \n"+
    "required: " +e+"\nactual: " +nodeVer));
}<|endoftext|>


<commit_before>'use strict';

function each(list) {
    var cursor = list.head;
    var result = '';

    if (cursor === null) {
        return result;
    }

    if (cursor === list.tail) {
        return translate(list.head.data);
    }

    while (cursor !== null) {
        result += translate(cursor.data);
        cursor = cursor.next;
    }

    return result;
}

function eachDelim(list, delimeter) {
    var cursor = list.head;
    var result = '';

    if (cursor === null) {
        return result;
    }

    if (cursor === list.tail) {
        return translate(list.head.data);
    }

    while (true) {
        result += translate(cursor.data);
        cursor = cursor.next;
        if (cursor === null) {
            break;
        }
        result += delimeter;
    }

    return result;
}

function translateAtRule(node) {
    var result = '@' + node.name;

    if (node.expression !== null) {
        result += ' ' + translate(node.expression);
    }

    if (node.block) {
        result += translate(node.block);
    } else {
        result += ';';
    }

    return result;
}

function translateSelector(list) {
    var cursor = list.head;
    var result = '';

    if (cursor === null) {
        return result;
    }

    if (cursor === list.tail) {
        return translate(list.head.data);
    }

    while (cursor !== null) {
        result += translate(cursor.data);
        cursor = cursor.next;
    }

    return result;
}

function translateBlock(list) {
    var cursor = list.head;
    var result = '';

    if (cursor === null) {
        return result;
    }

    if (cursor === list.tail) {
        return translate(list.head.data);
    }

    while (cursor !== null) {
        result += translate(cursor.data);
        if (cursor.next && cursor.data.type === 'Declaration') {
            result += ';';
        }
        cursor = cursor.next;
    }

    return result;
}

function translate(node) {
    switch (node.type) {
        case 'StyleSheet':
            return each(node.children);

        case 'Atrule':
            return translateAtRule(node);

        case 'Rule':
            return translate(node.selector) + translate(node.block);

        case 'SelectorList':
            return eachDelim(node.children, ',');

        case 'Selector':
            return translateSelector(node.children);

        case 'Block':
            return '{' + translateBlock(node.children) + '}';

        case 'DeclarationList':
            return translateBlock(node.children);

        case 'Declaration':
            return node.important
                ? node.property + ':' + translate(node.value) + '!important'
                : node.property + ':' + translate(node.value);

        case 'Value':
            return each(node.children);

        case 'Nth':
            var result = translate(node.nth);
            if (node.selector !== null) {
                result += ' of ' + translate(node.selector);
            }
            return result;

        case 'AttributeSelector':
            var result = translate(node.name);
            var flagsPrefix = ' ';

            if (node.operator !== null) {
                result += node.operator;

                if (node.value !== null) {
                    result += translate(node.value);

                    // space between string and flags is not required
                    if (node.value.type === 'String') {
                        flagsPrefix = '';
                    }
                }
            }

            if (node.flags !== null) {
                result += flagsPrefix + node.flags;
            }

            return '[' + result + ']';

        case 'Function':
            return node.name + '(' + each(node.children) + ')';

        case 'Parentheses':
            return '(' + each(node.children) + ')';

        case 'Brackets':
            return '[' + each(node.children) + ']';

        case 'AtruleExpression':
            return each(node.children);

        case 'MediaQueryList':
            return eachDelim(node.children, ',');

        case 'MediaQuery':
            return each(node.children);

        case 'MediaFeature':
            return node.value !== null
                ? '(' + node.name + ':' + translate(node.value) + ')'
                : '(' + node.name + ')';

        case 'Url':
            return 'url(' + translate(node.value) + ')';

        case 'Combinator':
            return node.name;

        case 'TypeSelector':
            return node.name;

        case 'Identifier':
            return node.name;

        case 'PseudoClassSelector':
            return node.children !== null
                ? ':' + node.name + '(' + each(node.children) + ')'
                : ':' + node.name;

        case 'PseudoElementSelector':
            return node.children !== null
                ? '::' + node.name + '(' + each(node.children) + ')'
                : '::' + node.name;

        case 'ClassSelector':
            return '.' + node.name;

        case 'IdSelector':
            return '#' + node.name;

        case 'UnicodeRange':
            return node.value;

        case 'HexColor':
            return '#' + node.value;

        case 'Dimension':
            return node.value + node.unit;

        case 'AnPlusB':
            var result = '';
            var a = node.a !== null && node.a !== undefined;
            var b = node.b !== null && node.b !== undefined;

            if (a) {
                result += node.a === '+1' || node.a === '1' ? 'n' :
                          node.a === '-1' ? '-n' :
                          node.a + 'n';
            }

            if (a && b) {
                if (String(node.b).charAt(0) !== '-' &&
                    String(node.b).charAt(0) !== '+') {
                    result += '+';
                }
            }

            if (b) {
                result += node.b;
            }

            return result;

        case 'Number':
            return node.value;

        case 'String':
            return node.value;

        case 'Operator':
            return node.value;

        case 'Ratio':
            return node.left + '/' + node.right;

        case 'Raw':
            return node.value;

        case 'Percentage':
            return node.value + '%';

        case 'WhiteSpace':
            return node.value;

        case 'Comment':
            return '/*' + node.value + '*/';

        default:
            throw new Error('Unknown node type: ' + node.type);
    }
}

module.exports = translate;
<commit_msg>drop redundant function<commit_after>'use strict';

function each(list) {
    var cursor = list.head;
    var result = '';

    if (cursor === null) {
        return result;
    }

    if (cursor === list.tail) {
        return translate(list.head.data);
    }

    while (cursor !== null) {
        result += translate(cursor.data);
        cursor = cursor.next;
    }

    return result;
}

function eachDelim(list, delimeter) {
    var cursor = list.head;
    var result = '';

    if (cursor === null) {
        return result;
    }

    if (cursor === list.tail) {
        return translate(list.head.data);
    }

    while (true) {
        result += translate(cursor.data);
        cursor = cursor.next;
        if (cursor === null) {
            break;
        }
        result += delimeter;
    }

    return result;
}

function translateAtRule(node) {
    var result = '@' + node.name;

    if (node.expression !== null) {
        result += ' ' + translate(node.expression);
    }

    if (node.block) {
        result += translate(node.block);
    } else {
        result += ';';
    }

    return result;
}

function translateBlock(list) {
    var cursor = list.head;
    var result = '';

    if (cursor === null) {
        return result;
    }

    if (cursor === list.tail) {
        return translate(list.head.data);
    }

    while (cursor !== null) {
        result += translate(cursor.data);
        if (cursor.next && cursor.data.type === 'Declaration') {
            result += ';';
        }
        cursor = cursor.next;
    }

    return result;
}

function translate(node) {
    switch (node.type) {
        case 'StyleSheet':
            return each(node.children);

        case 'Atrule':
            return translateAtRule(node);

        case 'Rule':
            return translate(node.selector) + translate(node.block);

        case 'SelectorList':
            return eachDelim(node.children, ',');

        case 'Selector':
            return each(node.children);

        case 'Block':
            return '{' + translateBlock(node.children) + '}';

        case 'DeclarationList':
            return translateBlock(node.children);

        case 'Declaration':
            return node.important
                ? node.property + ':' + translate(node.value) + '!important'
                : node.property + ':' + translate(node.value);

        case 'Value':
            return each(node.children);

        case 'Nth':
            var result = translate(node.nth);
            if (node.selector !== null) {
                result += ' of ' + translate(node.selector);
            }
            return result;

        case 'AttributeSelector':
            var result = translate(node.name);
            var flagsPrefix = ' ';

            if (node.operator !== null) {
                result += node.operator;

                if (node.value !== null) {
                    result += translate(node.value);

                    // space between string and flags is not required
                    if (node.value.type === 'String') {
                        flagsPrefix = '';
                    }
                }
            }

            if (node.flags !== null) {
                result += flagsPrefix + node.flags;
            }

            return '[' + result + ']';

        case 'Function':
            return node.name + '(' + each(node.children) + ')';

        case 'Parentheses':
            return '(' + each(node.children) + ')';

        case 'Brackets':
            return '[' + each(node.children) + ']';

        case 'AtruleExpression':
            return each(node.children);

        case 'MediaQueryList':
            return eachDelim(node.children, ',');

        case 'MediaQuery':
            return each(node.children);

        case 'MediaFeature':
            return node.value !== null
                ? '(' + node.name + ':' + translate(node.value) + ')'
                : '(' + node.name + ')';

        case 'Url':
            return 'url(' + translate(node.value) + ')';

        case 'Combinator':
            return node.name;

        case 'TypeSelector':
            return node.name;

        case 'Identifier':
            return node.name;

        case 'PseudoClassSelector':
            return node.children !== null
                ? ':' + node.name + '(' + each(node.children) + ')'
                : ':' + node.name;

        case 'PseudoElementSelector':
            return node.children !== null
                ? '::' + node.name + '(' + each(node.children) + ')'
                : '::' + node.name;

        case 'ClassSelector':
            return '.' + node.name;

        case 'IdSelector':
            return '#' + node.name;

        case 'UnicodeRange':
            return node.value;

        case 'HexColor':
            return '#' + node.value;

        case 'Dimension':
            return node.value + node.unit;

        case 'AnPlusB':
            var result = '';
            var a = node.a !== null && node.a !== undefined;
            var b = node.b !== null && node.b !== undefined;

            if (a) {
                result += node.a === '+1' || node.a === '1' ? 'n' :
                          node.a === '-1' ? '-n' :
                          node.a + 'n';
            }

            if (a && b) {
                if (String(node.b).charAt(0) !== '-' &&
                    String(node.b).charAt(0) !== '+') {
                    result += '+';
                }
            }

            if (b) {
                result += node.b;
            }

            return result;

        case 'Number':
            return node.value;

        case 'String':
            return node.value;

        case 'Operator':
            return node.value;

        case 'Ratio':
            return node.left + '/' + node.right;

        case 'Raw':
            return node.value;

        case 'Percentage':
            return node.value + '%';

        case 'WhiteSpace':
            return node.value;

        case 'Comment':
            return '/*' + node.value + '*/';

        default:
            throw new Error('Unknown node type: ' + node.type);
    }
}

module.exports = translate;
<|endoftext|>


<commit_before>/**
 * The typeCache module keeps all of the contentTypes in memory so that we can quickly access their
 * contents without going back to the database. Any time contentTypes are updated through core their
 * data gets updated in cache.
 */
module.exports = ( function() {
    'use strict';

    var contentTypes = {},
        db = require('../db'),
        config = require('../config'),
        _ = require('underscore'),
        cache = {};

    db.contentTypes.list({
        query: '',
        limit: config.db.defaultPageSize,
        skip: 0
    }).then(function(types){
        _.each( types, function( type ) {
            contentTypes[type._id.toString()] = type;
        });
    });

    cache.get = function(id) {
        return contentTypes[id];
    };

    cache.set = function(type){
        contentTypes[type._id.toString()] = type;
    };

    return cache;
} )();<commit_msg>Added list method to typeCache. It returns all of the types.<commit_after>/**
 * The typeCache module keeps all of the contentTypes in memory so that we can quickly access their
 * contents without going back to the database. Any time contentTypes are updated through core their
 * data gets updated in cache.
 */
module.exports = ( function() {
    'use strict';

    var contentTypes = {},
        db = require('../db'),
        config = require('../config'),
        _ = require('underscore'),
        cache = {};

    db.contentTypes.list({
        query: '',
        limit: config.db.defaultPageSize,
        skip: 0
    }).then(function(types){
        _.each( types, function( type ) {
            contentTypes[type._id.toString()] = type;
        });
    });

    cache.get = function(id) {
        return contentTypes[id];
    };

    cache.set = function(type){
        contentTypes[type._id.toString()] = type;
    };

    cache.list = function(){
        return contentTypes;
    };

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