<commit_before>'use strict';
/**
 * StyleSheets represents the StyleSheets found in the source code.
 * @constructor
 */
function StyleSheets() {
  this.styleSheets = {};
}

/**
 * Add adds a StyleSheet to our StyleSheets collections.
 *
 * @param {string} styleSheetName - The name of the StyleSheet.
 * @param {object} properties - The collection of rules in the styleSheet.
 */
StyleSheets.prototype.add = function (styleSheetName, properties) {
  this.styleSheets[styleSheetName] = properties;
};

/**
 * MarkAsUsed marks a rule as used in our source code by removing it from the
 * specified StyleSheet rules.
 *
 * @param {string} fullyQualifiedName - The fully qualified name of the rule.
 * for example 'styles.text'
 */
StyleSheets.prototype.markAsUsed = function (fullyQualifiedName) {
  const nameSplit = fullyQualifiedName.split('.');
  const styleSheetName = nameSplit[0];
  const styleSheetProperty = nameSplit[1];

  if (this.styleSheets[styleSheetName]) {
    this.styleSheets[styleSheetName] = this
        .styleSheets[styleSheetName]
        .filter((property) => property.key.name !== styleSheetProperty);
  }
};

/**
 * GetUnusedReferences returns all collected StyleSheets and their
 * unmarked rules.
 */
StyleSheets.prototype.getUnusedReferences = function () {
  return this.styleSheets;
};

/**
 * AddColorLiterals adds an array of expressions that contain color literals
 * to the ColorLiterals collection
 * @param {array} expressions - an array of expressions containing color literals
 */
StyleSheets.prototype.addColorLiterals = function (expressions) {
  if (!this.colorLiterals) {
    this.colorLiterals = [];
  }
  this.colorLiterals = this.colorLiterals.concat(expressions);
};

/**
 * GetColorLiterals returns an array of collected color literals expressions
 * @returns {Array}
 */
StyleSheets.prototype.getColorLiterals = function () {
  return this.colorLiterals;
};

/**
 * AddObjectexpressions adds an array of expressions to the ObjectExpressions collection
 * @param {Array} expressions - an array of expressions containing ObjectExpressions in
 * inline styles
 */
StyleSheets.prototype.addObjectExpressions = function (expressions) {
  if (!this.objectExpressions) {
    this.objectExpressions = [];
  }
  this.objectExpressions = this.objectExpressions.concat(expressions);
};

/**
 * GetObjectExpressions returns an array of collected object expressiosn used in inline styles
 * @returns {Array}
 */
StyleSheets.prototype.getObjectExpressions = function () {
  return this.objectExpressions;
};

let currentContent;
const getSourceCode = node => currentContent
  .getSourceCode(node)
  .getText(node);

const astHelpers = {
  containsStyleSheetObject: function (node) {
    return Boolean(
      node &&
      node.init &&
      node.init.callee &&
      node.init.callee.object &&
      node.init.callee.object.name === 'StyleSheet'
    );
  },

  containsCreateCall: function (node) {
    return Boolean(
      node &&
      node.init &&
      node.init.callee &&
      node.init.callee.property &&
      node.init.callee.property.name === 'create'
    );
  },

  isStyleSheetDeclaration: function (node) {
    return Boolean(
      astHelpers.containsStyleSheetObject(node) &&
      astHelpers.containsCreateCall(node)
    );
  },

  getStyleSheetName: function (node) {
    if (
      node &&
      node.id
    ) {
      return node.id.name;
    }
  },

  getStyleDeclarations: function (node) {
    if (
      node &&
      node.init &&
      node.init.arguments &&
      node.init.arguments[0] &&
      node.init.arguments[0].properties
    ) {
      return node
        .init
        .arguments[0]
        .properties;
    }

    return [];
  },

  isStyleAttribute: function (node) {
    return Boolean(
      node.type === 'JSXAttribute' &&
      node.name &&
      node.name.name &&
      node.name.name.toLowerCase().includes('style')
    );
  },

  collectStyleReferences: function (node) {
    if (astHelpers.hasArrayOfStyleReferences(node)) {
      const styleReferenceContainers = node
        .expression
        .elements;

      return astHelpers.collectStyleReferencesFromContainers(
        styleReferenceContainers
      );
    }

    return astHelpers.getStyleReferenceFromNode(node.expression);
  },

  collectStyleObjectExpressions: function (node, context) {
    currentContent = context;
    if (astHelpers.hasArrayOfStyleReferences(node)) {
      const styleReferenceContainers = node
          .expression
          .elements;

      return astHelpers.collectStyleObjectExpressionFromContainers(
          styleReferenceContainers
      );
    }

    return astHelpers.getStyleObjectExpressionFromNode(node.expression);
  },

  collectColorLiterals: function (node, context) {
    currentContent = context;
    if (astHelpers.hasArrayOfStyleReferences(node)) {
      const styleReferenceContainers = node
          .expression
          .elements;

      return astHelpers.collectColorLiteralsFromContainers(
          styleReferenceContainers
      );
    }

    if (node.type === 'ObjectExpression') {
      return astHelpers.getColorLiteralsFromNode(node);
    }

    return astHelpers.getColorLiteralsFromNode(node.expression);
  },

  collectStyleReferencesFromContainers: function (nodes) {
    let styleReferences = [];
    nodes.forEach(node => {
      styleReferences = styleReferences.concat(astHelpers.getStyleReferenceFromNode(node));
    });
    return styleReferences;
  },

  collectStyleObjectExpressionFromContainers: function (nodes) {
    let objectExpressions = [];
    nodes.forEach(node => {
      objectExpressions = objectExpressions
          .concat(astHelpers.getStyleObjectExpressionFromNode(node));
    });

    return objectExpressions;
  },

  collectColorLiteralsFromContainers: function (nodes) {
    let colorLiterals = [];
    nodes.forEach(node => {
      colorLiterals = colorLiterals
          .concat(astHelpers.getColorLiteralsFromNode(node));
    });

    return colorLiterals;
  },

  getStyleReferenceFromNode: function (node) {
    let styleReference;
    let leftStyleReferences;
    let rightStyleReferences;

    if (!node) {
      return [];
    }

    switch (node.type) {
      case 'MemberExpression':
        styleReference = astHelpers.getStyleReferenceFromExpression(node);
        return [styleReference];
      case 'LogicalExpression':
        leftStyleReferences = astHelpers.getStyleReferenceFromNode(node.left);
        rightStyleReferences = astHelpers.getStyleReferenceFromNode(node.right);
        return [].concat(leftStyleReferences).concat(rightStyleReferences);
      case 'ConditionalExpression':
        leftStyleReferences = astHelpers.getStyleReferenceFromNode(node.consequent);
        rightStyleReferences = astHelpers.getStyleReferenceFromNode(node.alternate);
        return [].concat(leftStyleReferences).concat(rightStyleReferences);
      default:
        return [];
    }
  },

  getStyleObjectExpressionFromNode: function (node) {
    let leftStyleObjectExpression;
    let rightStyleObjectExpression;

    if (!node) {
      return [];
    }

    if (node.type === 'ObjectExpression') {
      return [astHelpers.getStyleObjectFromExpression(node)];
    }

    switch (node.type) {
      case 'LogicalExpression':
        leftStyleObjectExpression = astHelpers.getStyleObjectExpressionFromNode(node.left);
        rightStyleObjectExpression = astHelpers.getStyleObjectExpressionFromNode(node.right);
        return [].concat(leftStyleObjectExpression).concat(rightStyleObjectExpression);
      case 'ConditionalExpression':
        leftStyleObjectExpression = astHelpers.getStyleObjectExpressionFromNode(node.consequent);
        rightStyleObjectExpression = astHelpers.getStyleObjectExpressionFromNode(node.alternate);
        return [].concat(leftStyleObjectExpression).concat(rightStyleObjectExpression);
      default:
        return [];
    }
  },

  getColorLiteralsFromNode: function (node) {
    let leftColorLiterals;
    let rightColorLiterals;

    if (!node) {
      return [];
    }

    if (node.type === 'ObjectExpression') {
      return [astHelpers.getColorLiteralsFromExpression(node)];
    }

    switch (node.type) {
      case 'LogicalExpression':
        leftColorLiterals = astHelpers.getColorLiteralsFromNode(node.left);
        rightColorLiterals = astHelpers.getColorLiteralsFromNode(node.right);
        return [].concat(leftColorLiterals).concat(rightColorLiterals);
      case 'ConditionalExpression':
        leftColorLiterals = astHelpers.getColorLiteralsFromNode(node.consequent);
        rightColorLiterals = astHelpers.getColorLiteralsFromNode(node.alternate);
        return [].concat(leftColorLiterals).concat(rightColorLiterals);
      default:
        return [];
    }
  },

  hasArrayOfStyleReferences: function (node) {
    return Boolean(
      node.type === 'JSXExpressionContainer' &&
      node.expression &&
      node.expression.type === 'ArrayExpression'
    );
  },

  getStyleReferenceFromExpression: function (node) {
    const result = [];
    const name = astHelpers.getObjectName(node);
    if (name) {
      result.push(name);
    }

    const property = astHelpers.getPropertyName(node);
    if (property) {
      result.push(property);
    }

    return result.join('.');
  },

  getStyleObjectFromExpression: function (node) {
    const obj = {};
    let invalid = false;
    if (node.properties && node.properties.length) {
      node.properties.forEach(p => {
        if (p.value.type === 'Literal') {
          invalid = true;
          obj[p.key.name] = p.value.value;
        } else if (p.value.type === 'ConditionalExpression') {
          const innerNode = p.value;
          if (innerNode.consequent.type === 'Literal' || innerNode.alternate.type === 'Literal') {
            invalid = true;
            obj[p.key.name] = getSourceCode(innerNode);
          }
        } else if (p.value.type === 'UnaryExpression' && p.value.operator === '-') {
          invalid = true;
          obj[p.key.name] = -1 * p.value.argument.value;
        } else if (p.value.type === 'UnaryExpression' && p.value.operator === '+') {
          invalid = true;
          obj[p.key.name] = p.value.argument.value;
        }
      });
    }
    return invalid ? { expression: obj, node: node } : undefined;
  },

  getColorLiteralsFromExpression: function (node) {
    const obj = {};
    let invalid = false;
    if (node.properties && node.properties.length) {
      node.properties.forEach(p => {
        if (p.key.name.toLowerCase().indexOf('color') !== -1) {
          if (p.value.type === 'Literal') {
            invalid = true;
            obj[p.key.name] = p.value.value;
          } else if (p.value.type === 'ConditionalExpression') {
            const innerNode = p.value;
            if (innerNode.consequent.type === 'Literal' || innerNode.alternate.type === 'Literal') {
              invalid = true;
              obj[p.key.name] = getSourceCode(innerNode);
            }
          }
        }
      });
    }
    return invalid ? { expression: obj, node: node } : undefined;
  },

  getObjectName: function (node) {
    if (
      node &&
      node.object &&
      node.object.name
    ) {
      return node.object.name;
    }
  },

  getPropertyName: function (node) {
    if (
      node &&
      node.property &&
      node.property.name
    ) {
      return node.property.name;
    }
  },
};

module.exports.astHelpers = astHelpers;
module.exports.StyleSheets = StyleSheets;
<commit_msg>Fix #41<commit_after>'use strict';
/**
 * StyleSheets represents the StyleSheets found in the source code.
 * @constructor
 */
function StyleSheets() {
  this.styleSheets = {};
}

/**
 * Add adds a StyleSheet to our StyleSheets collections.
 *
 * @param {string} styleSheetName - The name of the StyleSheet.
 * @param {object} properties - The collection of rules in the styleSheet.
 */
StyleSheets.prototype.add = function (styleSheetName, properties) {
  this.styleSheets[styleSheetName] = properties;
};

/**
 * MarkAsUsed marks a rule as used in our source code by removing it from the
 * specified StyleSheet rules.
 *
 * @param {string} fullyQualifiedName - The fully qualified name of the rule.
 * for example 'styles.text'
 */
StyleSheets.prototype.markAsUsed = function (fullyQualifiedName) {
  const nameSplit = fullyQualifiedName.split('.');
  const styleSheetName = nameSplit[0];
  const styleSheetProperty = nameSplit[1];

  if (this.styleSheets[styleSheetName]) {
    this.styleSheets[styleSheetName] = this
        .styleSheets[styleSheetName]
        .filter((property) => property.key.name !== styleSheetProperty);
  }
};

/**
 * GetUnusedReferences returns all collected StyleSheets and their
 * unmarked rules.
 */
StyleSheets.prototype.getUnusedReferences = function () {
  return this.styleSheets;
};

/**
 * AddColorLiterals adds an array of expressions that contain color literals
 * to the ColorLiterals collection
 * @param {array} expressions - an array of expressions containing color literals
 */
StyleSheets.prototype.addColorLiterals = function (expressions) {
  if (!this.colorLiterals) {
    this.colorLiterals = [];
  }
  this.colorLiterals = this.colorLiterals.concat(expressions);
};

/**
 * GetColorLiterals returns an array of collected color literals expressions
 * @returns {Array}
 */
StyleSheets.prototype.getColorLiterals = function () {
  return this.colorLiterals;
};

/**
 * AddObjectexpressions adds an array of expressions to the ObjectExpressions collection
 * @param {Array} expressions - an array of expressions containing ObjectExpressions in
 * inline styles
 */
StyleSheets.prototype.addObjectExpressions = function (expressions) {
  if (!this.objectExpressions) {
    this.objectExpressions = [];
  }
  this.objectExpressions = this.objectExpressions.concat(expressions);
};

/**
 * GetObjectExpressions returns an array of collected object expressiosn used in inline styles
 * @returns {Array}
 */
StyleSheets.prototype.getObjectExpressions = function () {
  return this.objectExpressions;
};

let currentContent;
const getSourceCode = node => currentContent
  .getSourceCode(node)
  .getText(node);

const astHelpers = {
  containsStyleSheetObject: function (node) {
    return Boolean(
      node &&
      node.init &&
      node.init.callee &&
      node.init.callee.object &&
      node.init.callee.object.name === 'StyleSheet'
    );
  },

  containsCreateCall: function (node) {
    return Boolean(
      node &&
      node.init &&
      node.init.callee &&
      node.init.callee.property &&
      node.init.callee.property.name === 'create'
    );
  },

  isStyleSheetDeclaration: function (node) {
    return Boolean(
      astHelpers.containsStyleSheetObject(node) &&
      astHelpers.containsCreateCall(node)
    );
  },

  getStyleSheetName: function (node) {
    if (
      node &&
      node.id
    ) {
      return node.id.name;
    }
  },

  getStyleDeclarations: function (node) {
    if (
      node &&
      node.init &&
      node.init.arguments &&
      node.init.arguments[0] &&
      node.init.arguments[0].properties
    ) {
      return node
        .init
        .arguments[0]
        .properties;
    }

    return [];
  },

  isStyleAttribute: function (node) {
    return Boolean(
      node.type === 'JSXAttribute' &&
      node.name &&
      node.name.name &&
      node.name.name.toLowerCase().includes('style')
    );
  },

  collectStyleReferences: function (node) {
    if (astHelpers.hasArrayOfStyleReferences(node)) {
      const styleReferenceContainers = node
        .expression
        .elements;

      return astHelpers.collectStyleReferencesFromContainers(
        styleReferenceContainers
      );
    }

    return astHelpers.getStyleReferenceFromNode(node.expression);
  },

  collectStyleObjectExpressions: function (node, context) {
    currentContent = context;
    if (astHelpers.hasArrayOfStyleReferences(node)) {
      const styleReferenceContainers = node
          .expression
          .elements;

      return astHelpers.collectStyleObjectExpressionFromContainers(
          styleReferenceContainers
      );
    }

    return astHelpers.getStyleObjectExpressionFromNode(node.expression);
  },

  collectColorLiterals: function (node, context) {
    currentContent = context;
    if (astHelpers.hasArrayOfStyleReferences(node)) {
      const styleReferenceContainers = node
          .expression
          .elements;

      return astHelpers.collectColorLiteralsFromContainers(
          styleReferenceContainers
      );
    }

    if (node.type === 'ObjectExpression') {
      return astHelpers.getColorLiteralsFromNode(node);
    }

    return astHelpers.getColorLiteralsFromNode(node.expression);
  },

  collectStyleReferencesFromContainers: function (nodes) {
    let styleReferences = [];
    nodes.forEach(node => {
      styleReferences = styleReferences.concat(astHelpers.getStyleReferenceFromNode(node));
    });
    return styleReferences;
  },

  collectStyleObjectExpressionFromContainers: function (nodes) {
    let objectExpressions = [];
    nodes.forEach(node => {
      objectExpressions = objectExpressions
          .concat(astHelpers.getStyleObjectExpressionFromNode(node));
    });

    return objectExpressions;
  },

  collectColorLiteralsFromContainers: function (nodes) {
    let colorLiterals = [];
    nodes.forEach(node => {
      colorLiterals = colorLiterals
          .concat(astHelpers.getColorLiteralsFromNode(node));
    });

    return colorLiterals;
  },

  getStyleReferenceFromNode: function (node) {
    let styleReference;
    let leftStyleReferences;
    let rightStyleReferences;

    if (!node) {
      return [];
    }

    switch (node.type) {
      case 'MemberExpression':
        styleReference = astHelpers.getStyleReferenceFromExpression(node);
        return [styleReference];
      case 'LogicalExpression':
        leftStyleReferences = astHelpers.getStyleReferenceFromNode(node.left);
        rightStyleReferences = astHelpers.getStyleReferenceFromNode(node.right);
        return [].concat(leftStyleReferences).concat(rightStyleReferences);
      case 'ConditionalExpression':
        leftStyleReferences = astHelpers.getStyleReferenceFromNode(node.consequent);
        rightStyleReferences = astHelpers.getStyleReferenceFromNode(node.alternate);
        return [].concat(leftStyleReferences).concat(rightStyleReferences);
      default:
        return [];
    }
  },

  getStyleObjectExpressionFromNode: function (node) {
    let leftStyleObjectExpression;
    let rightStyleObjectExpression;

    if (!node) {
      return [];
    }

    if (node.type === 'ObjectExpression') {
      return [astHelpers.getStyleObjectFromExpression(node)];
    }

    switch (node.type) {
      case 'LogicalExpression':
        leftStyleObjectExpression = astHelpers.getStyleObjectExpressionFromNode(node.left);
        rightStyleObjectExpression = astHelpers.getStyleObjectExpressionFromNode(node.right);
        return [].concat(leftStyleObjectExpression).concat(rightStyleObjectExpression);
      case 'ConditionalExpression':
        leftStyleObjectExpression = astHelpers.getStyleObjectExpressionFromNode(node.consequent);
        rightStyleObjectExpression = astHelpers.getStyleObjectExpressionFromNode(node.alternate);
        return [].concat(leftStyleObjectExpression).concat(rightStyleObjectExpression);
      default:
        return [];
    }
  },

  getColorLiteralsFromNode: function (node) {
    let leftColorLiterals;
    let rightColorLiterals;

    if (!node) {
      return [];
    }

    if (node.type === 'ObjectExpression') {
      return [astHelpers.getColorLiteralsFromExpression(node)];
    }

    switch (node.type) {
      case 'LogicalExpression':
        leftColorLiterals = astHelpers.getColorLiteralsFromNode(node.left);
        rightColorLiterals = astHelpers.getColorLiteralsFromNode(node.right);
        return [].concat(leftColorLiterals).concat(rightColorLiterals);
      case 'ConditionalExpression':
        leftColorLiterals = astHelpers.getColorLiteralsFromNode(node.consequent);
        rightColorLiterals = astHelpers.getColorLiteralsFromNode(node.alternate);
        return [].concat(leftColorLiterals).concat(rightColorLiterals);
      default:
        return [];
    }
  },

  hasArrayOfStyleReferences: function (node) {
    return Boolean(
      node.type === 'JSXExpressionContainer' &&
      node.expression &&
      node.expression.type === 'ArrayExpression'
    );
  },

  getStyleReferenceFromExpression: function (node) {
    const result = [];
    const name = astHelpers.getObjectName(node);
    if (name) {
      result.push(name);
    }

    const property = astHelpers.getPropertyName(node);
    if (property) {
      result.push(property);
    }

    return result.join('.');
  },

  getStyleObjectFromExpression: function (node) {
    const obj = {};
    let invalid = false;
    if (node.properties && node.properties.length) {
      node.properties.forEach(p => {
        if (p.value.type === 'Literal') {
          invalid = true;
          obj[p.key.name] = p.value.value;
        } else if (p.value.type === 'ConditionalExpression') {
          const innerNode = p.value;
          if (innerNode.consequent.type === 'Literal' || innerNode.alternate.type === 'Literal') {
            invalid = true;
            obj[p.key.name] = getSourceCode(innerNode);
          }
        } else if (p.value.type === 'UnaryExpression' && p.value.operator === '-') {
          invalid = true;
          obj[p.key.name] = -1 * p.value.argument.value;
        } else if (p.value.type === 'UnaryExpression' && p.value.operator === '+') {
          invalid = true;
          obj[p.key.name] = p.value.argument.value;
        }
      });
    }
    return invalid ? { expression: obj, node: node } : undefined;
  },

  getColorLiteralsFromExpression: function (node) {
    const obj = {};
    let invalid = false;
    if (node.properties && node.properties.length) {
      node.properties.forEach(p => {
        if (p.key.name && p.key.name.toLowerCase().indexOf('color') !== -1) {
          if (p.value.type === 'Literal') {
            invalid = true;
            obj[p.key.name] = p.value.value;
          } else if (p.value.type === 'ConditionalExpression') {
            const innerNode = p.value;
            if (innerNode.consequent.type === 'Literal' || innerNode.alternate.type === 'Literal') {
              invalid = true;
              obj[p.key.name] = getSourceCode(innerNode);
            }
          }
        }
      });
    }
    return invalid ? { expression: obj, node: node } : undefined;
  },

  getObjectName: function (node) {
    if (
      node &&
      node.object &&
      node.object.name
    ) {
      return node.object.name;
    }
  },

  getPropertyName: function (node) {
    if (
      node &&
      node.property &&
      node.property.name
    ) {
      return node.property.name;
    }
  },
};

module.exports.astHelpers = astHelpers;
module.exports.StyleSheets = StyleSheets;
<|endoftext|>


<commit_before>
exports = module.exports = lifecycle
exports.cmd = cmd

var log = require("npmlog")
  , exec = require("./exec.js")
  , npm = require("../npm.js")
  , path = require("path")
  , fs = require("graceful-fs")
  , chain = require("slide").chain
  , constants = require("constants")
  , Stream = require("stream").Stream
  , PATH = "PATH"

// windows calls it's path "Path" usually, but this is not guaranteed.
if (process.platform === "win32") {
  PATH = "Path"
  Object.keys(process.env).forEach(function (e) {
    if (e.match(/^PATH$/i)) {
      PATH = e
    }
  })
}

function lifecycle (pkg, stage, wd, unsafe, failOk, cb) {
  if (typeof cb !== "function") cb = failOk, failOk = false
  if (typeof cb !== "function") cb = unsafe, unsafe = false
  if (typeof cb !== "function") cb = wd, wd = null

  while (pkg && pkg._data) pkg = pkg._data
  if (!pkg) return cb(new Error("Invalid package data"))

  log.info(stage, pkg._id)
  if (!pkg.scripts) pkg.scripts = {}

  validWd(wd || path.resolve(npm.dir, pkg.name), function (er, wd) {
    if (er) return cb(er)

    unsafe = unsafe || npm.config.get("unsafe-perm")

    if ((wd.indexOf(npm.dir) !== 0 || path.basename(wd) !== pkg.name)
        && !unsafe && pkg.scripts[stage]) {
      log.warn( "cannot run in wd", "%s %s (wd=%s)"
              , pkg._id, pkg.scripts[stage], wd)
      return cb()
    }

    // set the env variables, then run scripts as a child process.
    var env = makeEnv(pkg)
    env.npm_lifecycle_event = stage

    // "nobody" typically doesn't have permission to write to /tmp
    // even if it's never used, sh freaks out.
    if (!npm.config.get("unsafe-perm")) env.TMPDIR = wd

    lifecycle_(pkg, stage, wd, env, unsafe, failOk, cb)
  })
}

function checkForLink (pkg, cb) {
  var f = path.join(npm.dir, pkg.name)
  fs.lstat(f, function (er, s) {
    cb(null, !(er || !s.isSymbolicLink()))
  })
}

function lifecycle_ (pkg, stage, wd, env, unsafe, failOk, cb) {
  var pathArr = []
    , p = wd.split("node_modules")
    , acc = path.resolve(p.shift())
  p.forEach(function (pp) {
    pathArr.unshift(path.join(acc, "node_modules", ".bin"))
    acc = path.join(acc, "node_modules", pp)
  })
  pathArr.unshift(path.join(acc, "node_modules", ".bin"))

  // we also unshift the bundled node-gyp-bin folder so that
  // the bundled one will be used for installing things.
  pathArr.unshift(path.join(__dirname, "..", "..", "bin", "node-gyp-bin"))

  if (env[PATH]) pathArr.push(env[PATH])
  env[PATH] = pathArr.join(process.platform === "win32" ? ";" : ":")

  var packageLifecycle = pkg.scripts && pkg.scripts.hasOwnProperty(stage)

  if (packageLifecycle) {
    // define this here so it's available to all scripts.
    env.npm_lifecycle_script = pkg.scripts[stage]
    // if the command is "node-gyp <args>", then call ours instead.
    try {
      var ourGyp = require.resolve("node-gyp/bin/node-gyp.js")
    } catch (er) {
      return cb(new Error("No gyp installed with npm"))
    }
    var gyp = path.execPath + " " + JSON.stringify(ourGyp)
    pkg.scripts[stage] = pkg.scripts[stage].replace(/^node-gyp( |$)/, gyp)
  }

  if (failOk) {
    cb = (function (cb_) { return function (er) {
      if (er) log.warn("continuing anyway", er.message)
      cb_()
    }})(cb)
  }

  if (npm.config.get("force")) {
    cb = (function (cb_) { return function (er) {
      if (er) log.info("forced, continuing", er)
      cb_()
    }})(cb)
  }

  chain
    ( [ packageLifecycle && [runPackageLifecycle, pkg, env, wd, unsafe]
      , [runHookLifecycle, pkg, env, wd, unsafe] ]
    , cb )
}

function validWd (d, cb) {
  fs.stat(d, function (er, st) {
    if (er || !st.isDirectory()) {
      var p = path.dirname(d)
      if (p === d) {
        return cb(new Error("Could not find suitable wd"))
      }
      return validWd(p, cb)
    }
    return cb(null, d)
  })
}

function runPackageLifecycle (pkg, env, wd, unsafe, cb) {
  // run package lifecycle scripts in the package root, or the nearest parent.
  var stage = env.npm_lifecycle_event
    , user = unsafe ? null : npm.config.get("user")
    , group = unsafe ? null : npm.config.get("group")
    , cmd = env.npm_lifecycle_script
    , sh = "sh"
    , shFlag = "-c"

  if (process.platform === "win32") {
    sh = "cmd"
    shFlag = "/c"
  }

  log.verbose("unsafe-perm in lifecycle", unsafe)

  var note = "\n> " + pkg._id + " " + stage + " " + wd
           + "\n> " + cmd + "\n"

  console.log(note)
  exec( sh, [shFlag, cmd], env, true, wd
      , user, group
      , function (er, code, stdout, stderr) {
    if (er && !npm.ROLLBACK) {
      log.info(pkg._id, "Failed to exec "+stage+" script")
      er.message = pkg._id + " "
                 + stage + ": `" + env.npm_lifecycle_script+"`\n"
                 + er.message
      if (er.code !== "EPERM") {
        er.code = "ELIFECYCLE"
      }
      er.pkgid = pkg._id
      er.stage = stage
      er.script = env.npm_lifecycle_script
      er.pkgname = pkg.name
      return cb(er)
    } else if (er) {
      log.error(pkg._id+"."+stage, er)
      log.error(pkg._id+"."+stage, "continuing anyway")
      return cb()
    }
    cb(er)
  })
}

function runHookLifecycle (pkg, env, wd, unsafe, cb) {
  // check for a hook script, run if present.
  var stage = env.npm_lifecycle_event
    , hook = path.join(npm.dir, ".hooks", stage)
    , user = unsafe ? null : npm.config.get("user")
    , group = unsafe ? null : npm.config.get("group")
    , cmd = hook

  fs.stat(hook, function (er) {
    if (er) return cb()

    exec( "sh", ["-c", cmd], env, true, wd
        , user, group
        , function (er) {
      if (er) {
        er.message += "\nFailed to exec "+stage+" hook script"
        log.info(pkg._id, er)
      }
      if (npm.ROLLBACK) return cb()
      cb(er)
    })
  })
}

function makeEnv (data, prefix, env) {
  prefix = prefix || "npm_package_"
  if (!env) {
    env = {}
    for (var i in process.env) if (!i.match(/^npm_/)) {
      env[i] = process.env[i]
    }

    // npat asks for tap output
    if (npm.config.get("npat")) env.TAP = 1

    // express and others respect the NODE_ENV value.
    if (npm.config.get("production")) env.NODE_ENV = "production"

  } else if (!data.hasOwnProperty("_lifecycleEnv")) {
    Object.defineProperty(data, "_lifecycleEnv",
      { value : env
      , enumerable : false
      })
  }

  for (var i in data) if (i.charAt(0) !== "_") {
    var envKey = (prefix+i).replace(/[^a-zA-Z0-9_]/g, '_')
    if (data[i] && typeof(data[i]) === "object") {
      try {
        // quick and dirty detection for cyclical structures
        JSON.stringify(data[i])
        makeEnv(data[i], envKey+"_", env)
      } catch (ex) {
        // usually these are package objects.
        // just get the path and basic details.
        var d = data[i]
        makeEnv( { name: d.name, version: d.version, path:d.path }
               , envKey+"_", env)
      }
    } else {
      env[envKey] = String(data[i])
      env[envKey] = -1 !== env[envKey].indexOf("\n")
                  ? JSON.stringify(env[envKey])
                  : env[envKey]
    }

  }

  if (prefix !== "npm_package_") return env

  prefix = "npm_config_"
  var pkgConfig = {}
    , ini = require("./ini.js")
    , keys = ini.keys
    , pkgVerConfig = {}
    , namePref = data.name + ":"
    , verPref = data.name + "@" + data.version + ":"

  keys.forEach(function (i) {
    if (i.charAt(0) === "_" && i.indexOf("_"+namePref) !== 0) {
      return
    }
    var value = ini.get(i)
    if (value instanceof Stream) return
    if (!value) value = ""
    else if (typeof value !== "string") value = JSON.stringify(value)

    value = -1 !== value.indexOf("\n")
          ? JSON.stringify(value)
          : value
    i = i.replace(/^_+/, "")
    if (i.indexOf(namePref) === 0) {
      var k = i.substr(namePref.length).replace(/[^a-zA-Z0-9_]/g, "_")
      pkgConfig[ k ] = value
    } else if (i.indexOf(verPref) === 0) {
      var k = i.substr(verPref.length).replace(/[^a-zA-Z0-9_]/g, "_")
      pkgVerConfig[ k ] = value
    }
    var envKey = (prefix+i).replace(/[^a-zA-Z0-9_]/g, "_")
    env[envKey] = value
  })

  prefix = "npm_package_config_"
  ;[pkgConfig, pkgVerConfig].forEach(function (conf) {
    for (var i in conf) {
      var envKey = (prefix+i)
      env[envKey] = conf[i]
    }
  })

  return env
}

function cmd (stage) {
  function CMD (args, cb) {
    if (args.length) {
      chain(args.map(function (p) {
        return [npm.commands, "run-script", [p, stage]]
      }), cb)
    } else npm.commands["run-script"]([stage], cb)
  }
  CMD.usage = "npm "+stage+" <name>"
  var installedShallow = require("./completion/installed-shallow.js")
  CMD.completion = function (opts, cb) {
    installedShallow(opts, function (d) {
      return d.scripts && d.scripts[stage]
    }, cb)
  }
  return CMD
}
<commit_msg>removed superfluous and erroneous node-gyp command replacement<commit_after>
exports = module.exports = lifecycle
exports.cmd = cmd

var log = require("npmlog")
  , exec = require("./exec.js")
  , npm = require("../npm.js")
  , path = require("path")
  , fs = require("graceful-fs")
  , chain = require("slide").chain
  , constants = require("constants")
  , Stream = require("stream").Stream
  , PATH = "PATH"

// windows calls it's path "Path" usually, but this is not guaranteed.
if (process.platform === "win32") {
  PATH = "Path"
  Object.keys(process.env).forEach(function (e) {
    if (e.match(/^PATH$/i)) {
      PATH = e
    }
  })
}

function lifecycle (pkg, stage, wd, unsafe, failOk, cb) {
  if (typeof cb !== "function") cb = failOk, failOk = false
  if (typeof cb !== "function") cb = unsafe, unsafe = false
  if (typeof cb !== "function") cb = wd, wd = null

  while (pkg && pkg._data) pkg = pkg._data
  if (!pkg) return cb(new Error("Invalid package data"))

  log.info(stage, pkg._id)
  if (!pkg.scripts) pkg.scripts = {}

  validWd(wd || path.resolve(npm.dir, pkg.name), function (er, wd) {
    if (er) return cb(er)

    unsafe = unsafe || npm.config.get("unsafe-perm")

    if ((wd.indexOf(npm.dir) !== 0 || path.basename(wd) !== pkg.name)
        && !unsafe && pkg.scripts[stage]) {
      log.warn( "cannot run in wd", "%s %s (wd=%s)"
              , pkg._id, pkg.scripts[stage], wd)
      return cb()
    }

    // set the env variables, then run scripts as a child process.
    var env = makeEnv(pkg)
    env.npm_lifecycle_event = stage

    // "nobody" typically doesn't have permission to write to /tmp
    // even if it's never used, sh freaks out.
    if (!npm.config.get("unsafe-perm")) env.TMPDIR = wd

    lifecycle_(pkg, stage, wd, env, unsafe, failOk, cb)
  })
}

function checkForLink (pkg, cb) {
  var f = path.join(npm.dir, pkg.name)
  fs.lstat(f, function (er, s) {
    cb(null, !(er || !s.isSymbolicLink()))
  })
}

function lifecycle_ (pkg, stage, wd, env, unsafe, failOk, cb) {
  var pathArr = []
    , p = wd.split("node_modules")
    , acc = path.resolve(p.shift())
  p.forEach(function (pp) {
    pathArr.unshift(path.join(acc, "node_modules", ".bin"))
    acc = path.join(acc, "node_modules", pp)
  })
  pathArr.unshift(path.join(acc, "node_modules", ".bin"))

  // we also unshift the bundled node-gyp-bin folder so that
  // the bundled one will be used for installing things.
  pathArr.unshift(path.join(__dirname, "..", "..", "bin", "node-gyp-bin"))

  if (env[PATH]) pathArr.push(env[PATH])
  env[PATH] = pathArr.join(process.platform === "win32" ? ";" : ":")

  var packageLifecycle = pkg.scripts && pkg.scripts.hasOwnProperty(stage)

  if (packageLifecycle) {
    // define this here so it's available to all scripts.
    env.npm_lifecycle_script = pkg.scripts[stage]
  }

  if (failOk) {
    cb = (function (cb_) { return function (er) {
      if (er) log.warn("continuing anyway", er.message)
      cb_()
    }})(cb)
  }

  if (npm.config.get("force")) {
    cb = (function (cb_) { return function (er) {
      if (er) log.info("forced, continuing", er)
      cb_()
    }})(cb)
  }

  chain
    ( [ packageLifecycle && [runPackageLifecycle, pkg, env, wd, unsafe]
      , [runHookLifecycle, pkg, env, wd, unsafe] ]
    , cb )
}

function validWd (d, cb) {
  fs.stat(d, function (er, st) {
    if (er || !st.isDirectory()) {
      var p = path.dirname(d)
      if (p === d) {
        return cb(new Error("Could not find suitable wd"))
      }
      return validWd(p, cb)
    }
    return cb(null, d)
  })
}

function runPackageLifecycle (pkg, env, wd, unsafe, cb) {
  // run package lifecycle scripts in the package root, or the nearest parent.
  var stage = env.npm_lifecycle_event
    , user = unsafe ? null : npm.config.get("user")
    , group = unsafe ? null : npm.config.get("group")
    , cmd = env.npm_lifecycle_script
    , sh = "sh"
    , shFlag = "-c"

  if (process.platform === "win32") {
    sh = "cmd"
    shFlag = "/c"
  }

  log.verbose("unsafe-perm in lifecycle", unsafe)

  var note = "\n> " + pkg._id + " " + stage + " " + wd
           + "\n> " + cmd + "\n"

  console.log(note)
  exec( sh, [shFlag, cmd], env, true, wd
      , user, group
      , function (er, code, stdout, stderr) {
    if (er && !npm.ROLLBACK) {
      log.info(pkg._id, "Failed to exec "+stage+" script")
      er.message = pkg._id + " "
                 + stage + ": `" + env.npm_lifecycle_script+"`\n"
                 + er.message
      if (er.code !== "EPERM") {
        er.code = "ELIFECYCLE"
      }
      er.pkgid = pkg._id
      er.stage = stage
      er.script = env.npm_lifecycle_script
      er.pkgname = pkg.name
      return cb(er)
    } else if (er) {
      log.error(pkg._id+"."+stage, er)
      log.error(pkg._id+"."+stage, "continuing anyway")
      return cb()
    }
    cb(er)
  })
}

function runHookLifecycle (pkg, env, wd, unsafe, cb) {
  // check for a hook script, run if present.
  var stage = env.npm_lifecycle_event
    , hook = path.join(npm.dir, ".hooks", stage)
    , user = unsafe ? null : npm.config.get("user")
    , group = unsafe ? null : npm.config.get("group")
    , cmd = hook

  fs.stat(hook, function (er) {
    if (er) return cb()

    exec( "sh", ["-c", cmd], env, true, wd
        , user, group
        , function (er) {
      if (er) {
        er.message += "\nFailed to exec "+stage+" hook script"
        log.info(pkg._id, er)
      }
      if (npm.ROLLBACK) return cb()
      cb(er)
    })
  })
}

function makeEnv (data, prefix, env) {
  prefix = prefix || "npm_package_"
  if (!env) {
    env = {}
    for (var i in process.env) if (!i.match(/^npm_/)) {
      env[i] = process.env[i]
    }

    // npat asks for tap output
    if (npm.config.get("npat")) env.TAP = 1

    // express and others respect the NODE_ENV value.
    if (npm.config.get("production")) env.NODE_ENV = "production"

  } else if (!data.hasOwnProperty("_lifecycleEnv")) {
    Object.defineProperty(data, "_lifecycleEnv",
      { value : env
      , enumerable : false
      })
  }

  for (var i in data) if (i.charAt(0) !== "_") {
    var envKey = (prefix+i).replace(/[^a-zA-Z0-9_]/g, '_')
    if (data[i] && typeof(data[i]) === "object") {
      try {
        // quick and dirty detection for cyclical structures
        JSON.stringify(data[i])
        makeEnv(data[i], envKey+"_", env)
      } catch (ex) {
        // usually these are package objects.
        // just get the path and basic details.
        var d = data[i]
        makeEnv( { name: d.name, version: d.version, path:d.path }
               , envKey+"_", env)
      }
    } else {
      env[envKey] = String(data[i])
      env[envKey] = -1 !== env[envKey].indexOf("\n")
                  ? JSON.stringify(env[envKey])
                  : env[envKey]
    }

  }

  if (prefix !== "npm_package_") return env

  prefix = "npm_config_"
  var pkgConfig = {}
    , ini = require("./ini.js")
    , keys = ini.keys
    , pkgVerConfig = {}
    , namePref = data.name + ":"
    , verPref = data.name + "@" + data.version + ":"

  keys.forEach(function (i) {
    if (i.charAt(0) === "_" && i.indexOf("_"+namePref) !== 0) {
      return
    }
    var value = ini.get(i)
    if (value instanceof Stream) return
    if (!value) value = ""
    else if (typeof value !== "string") value = JSON.stringify(value)

    value = -1 !== value.indexOf("\n")
          ? JSON.stringify(value)
          : value
    i = i.replace(/^_+/, "")
    if (i.indexOf(namePref) === 0) {
      var k = i.substr(namePref.length).replace(/[^a-zA-Z0-9_]/g, "_")
      pkgConfig[ k ] = value
    } else if (i.indexOf(verPref) === 0) {
      var k = i.substr(verPref.length).replace(/[^a-zA-Z0-9_]/g, "_")
      pkgVerConfig[ k ] = value
    }
    var envKey = (prefix+i).replace(/[^a-zA-Z0-9_]/g, "_")
    env[envKey] = value
  })

  prefix = "npm_package_config_"
  ;[pkgConfig, pkgVerConfig].forEach(function (conf) {
    for (var i in conf) {
      var envKey = (prefix+i)
      env[envKey] = conf[i]
    }
  })

  return env
}

function cmd (stage) {
  function CMD (args, cb) {
    if (args.length) {
      chain(args.map(function (p) {
        return [npm.commands, "run-script", [p, stage]]
      }), cb)
    } else npm.commands["run-script"]([stage], cb)
  }
  CMD.usage = "npm "+stage+" <name>"
  var installedShallow = require("./completion/installed-shallow.js")
  CMD.completion = function (opts, cb) {
    installedShallow(opts, function (d) {
      return d.scripts && d.scripts[stage]
    }, cb)
  }
  return CMD
}
<|endoftext|>


<commit_before>//  Clear selection range of current selected term view
//  Fix event when terminal text is selected and keyboard action is invoked
exports.clear = function (terminal) {
  terminal.document_.getSelection().removeAllRanges();
};

// Use selection extend upon dblclick
exports.extend = function (terminal) {
  const sel = terminal.document_.getSelection();

  // Test if focusNode exist and nodeName is #text
  if (sel.focusNode && sel.focusNode.nodeName === '#text') {
    terminal.screen_.expandSelection(sel);
  }
};

// Fix a bug in ScrollPort selectAll behavior
// Select all rows in the viewport
exports.all = function (terminal) {
  const scrollPort = terminal.scrollPort_;
  let firstRow;
  let lastRow;

  if (scrollPort.topFold_.nextSibling.rowIndex === 0) {
    firstRow = scrollPort.topFold_.nextSibling;
  } else {
    while (scrollPort.topFold_.previousSibling) {
      scrollPort.rowNodes_.removeChild(scrollPort.topFold_.previousSibling);
    }

    firstRow = scrollPort.fetchRowNode_(0);
    scrollPort.rowNodes_.insertBefore(firstRow, scrollPort.topFold_);
    scrollPort.syncRowNodesDimensions_();
  }

  const lastRowIndex = scrollPort.rowProvider_.getRowCount() - 1;

  if (scrollPort.bottomFold_.previousSibling.rowIndex === lastRowIndex) {
    lastRow = scrollPort.bottomFold_.previousSibling.rowIndex;
  } else {
    while (scrollPort.bottomFold_.nextSibling) {
      scrollPort.rowNodes_.removeChild(scrollPort.bottomFold_.nextSibling);
    }

    lastRow = scrollPort.fetchRowNode_(lastRowIndex);
    scrollPort.rowNodes_.appendChild(lastRow);
  }

  scrollPort.selection.sync();
};
<commit_msg>Fix selection extend when copyOnSelect is true (#975)<commit_after>//  Clear selection range of current selected term view
//  Fix event when terminal text is selected and keyboard action is invoked
exports.clear = function (terminal) {
  terminal.document_.getSelection().removeAllRanges();
};

// Use selection extend upon dblclick
exports.extend = function (terminal) {
  const sel = terminal.document_.getSelection();

  // Test if focusNode exist and nodeName is #text
  if (sel.focusNode && sel.focusNode.nodeName === '#text') {
    terminal.screen_.expandSelection(sel);
    if (terminal.copyOnSelect) {
      terminal.copyStringToClipboard();
    }
  }
};

// Fix a bug in ScrollPort selectAll behavior
// Select all rows in the viewport
exports.all = function (terminal) {
  const scrollPort = terminal.scrollPort_;
  let firstRow;
  let lastRow;

  if (scrollPort.topFold_.nextSibling.rowIndex === 0) {
    firstRow = scrollPort.topFold_.nextSibling;
  } else {
    while (scrollPort.topFold_.previousSibling) {
      scrollPort.rowNodes_.removeChild(scrollPort.topFold_.previousSibling);
    }

    firstRow = scrollPort.fetchRowNode_(0);
    scrollPort.rowNodes_.insertBefore(firstRow, scrollPort.topFold_);
    scrollPort.syncRowNodesDimensions_();
  }

  const lastRowIndex = scrollPort.rowProvider_.getRowCount() - 1;

  if (scrollPort.bottomFold_.previousSibling.rowIndex === lastRowIndex) {
    lastRow = scrollPort.bottomFold_.previousSibling.rowIndex;
  } else {
    while (scrollPort.bottomFold_.nextSibling) {
      scrollPort.rowNodes_.removeChild(scrollPort.bottomFold_.nextSibling);
    }

    lastRow = scrollPort.fetchRowNode_(lastRowIndex);
    scrollPort.rowNodes_.appendChild(lastRow);
  }

  scrollPort.selection.sync();
};
<|endoftext|>


<commit_before>'use babel';

import { $, ScrollView } from 'atom-space-pen-views';
import { getObject, resizeCursor, elapsedTime } from '../helpers';
import DirectoryView from './directory-view';

let hideLocalTreeError = false;

function hideLocalTree() {
  const treeView = getObject({
    obj: atom.packages.loadedPackages,
    keys: ['tree-view', 'mainModule', 'treeView'],
  });

  if (treeView && typeof treeView.detach === 'function') { // Fix for Issue 433 ( workaround to stop throwing error)
    try {
      treeView.detach();
    } catch (e) {
      if (hideLocalTreeError === false) {
        atom.notifications.addWarning('Remote FTP: See issue #433', {
          dismissable: false,
        });
        hideLocalTreeError = true;
      }
    }
  }
}

function showLocalTree() {
  const treeView = getObject({
    obj: atom.packages.loadedPackages,
    keys: ['tree-view', 'mainModule', 'treeView'],
  });
  if (treeView && typeof treeView.detach === 'function') treeView.attach();
}

class TreeView extends ScrollView {

  static content() {
    return this.div({
      class: 'remote-ftp-view ftptree-view-resizer tool-panel',
      'data-show-on-right-side': atom.config.get('tree-view.showOnRightSide'),
      'data-use-dock-integration': atom.config.get('Remote-FTP.tree.useDockIntegration'),
    }, () => {
      this.div({
        class: 'scroller',
        outlet: 'scroller',
      }, () => {
        this.ol({
          class: 'ftptree-view full-menu list-tree has-collapsable-children focusable-panel',
          tabindex: -1,
          outlet: 'list',
        });
      });
      this.div({
        class: 'resize-handle',
        outlet: 'horizontalResize',
        style: `cursor:${resizeCursor}`, // platform specific cursor
      });
      this.div({
        class: 'queue tool-panel panel-bottom',
        tabindex: -1,
        outlet: 'queue',
      }, () => {
        this.ul({
          class: 'progress tool-panel panel-top',
          tabindex: -1,
          outlet: 'progress',
        });
        this.ul({
          class: 'list',
          tabindex: -1,
          outlet: 'debug',
        });
        return this.div({
          class: 'resize-handle',
          outlet: 'verticalResize',
        });
      });
      this.div({
        class: 'offline',
        tabindex: -1,
        outlet: 'offline',
      });
    });
  }

  initialize(state) {
    super.initialize(state);

    const self = this;

    const html = `

Connect

Edit Configuration

Edit Ignore Configuration

Close Panel

`;

    self.offline.html(html);

    if (atom.project.remoteftp.isConnected()) {
      self.showOnline();
    } else {
      self.showOffline();
    }

    self.root = new DirectoryView(atom.project.remoteftp.root);
    self.root.expand();
    self.list.append(self.root);

    // self.attach();

    // Events
    atom.config.onDidChange('tree-view.showOnRightSide', () => {
      if (self.isVisible()) {
        setTimeout(() => {
          self.detach();
          self.attach();
        }, 1);
      }
    });

    atom.config.onDidChange('Remote-FTP.tree.hideLocalWhenDisplayed', (values) => {
      if (values.newValue) {
        if (self.isVisible()) {
          hideLocalTree();
        }
      } else if (self.isVisible()) {
        self.detach();
        showLocalTree();
        self.attach();
      } else {
        showLocalTree();
      }
    });

    atom.config.onDidChange('Remote-FTP.tree.useDockIntegration', () => {
      if (!atom.workspace.getRightDock === 'undefined') {
        atom.notifications.addWarning('Your editor is deprecated.
This option is available only >=1.17.0 version.');
        return;
      }

      if (self.isVisible()) {
        setTimeout(() => {
          this.detach();
          this.attach();
        }, 1);
      }
    });

    atom.project.remoteftp.on('debug', (msg) => {
      self.debug.prepend(`<li>${msg}</li>`);
      const children = self.debug.children();

      if (children.length > 20) {
        children.last().remove();
      }
    });

    atom.project.remoteftp.on('queue-changed', () => {
      self.progress.empty();

      const queues = [];
      if (atom.project.remoteftp.current) {
        queues.push(atom.project.remoteftp.current);
      }

      atom.project.remoteftp.queue.forEach((queueElem) => {
        queues.push(queueElem);
      });

      if (queues.length === 0) {
        self.progress.hide();
      } else {
        self.progress.show();

        queues.forEach((queue) => {
          const $li = $(`<li><progress class="inline-block" /><div class="name">${queue[0]}</div><div class="eta">-</div></li>`);
          const $progress = $li.children('progress');
          const $eta = $li.children('.eta');
          const progress = queue[2];

          self.progress.append($li);

          progress.on('progress', (percent) => {
            if (percent === -1) {
              $progress.removeAttr('max').removeAttr('value');
              $eta.text('-');
            } else {
              $progress.attr('max', 100).attr('value', parseInt(percent * 100, 10));
              const eta = progress.getEta();

              $eta.text(elapsedTime(eta));
            }
          });

          progress.once('done', () => {
            progress.removeAllListeners('progress');
          });
        });
      }
    });

    self.offline.on('click', '[role="connect"]', () => {
      atom.project.remoteftp.readConfig(() => {
        atom.project.remoteftp.connect();
      });
    });

    self.offline.on('click', '[role="configure"]', () => {
      atom.workspace.open(atom.project.remoteftp.getConfigPath());
    });

    self.offline.on('click', '[role="configure_ignored"]', () => {
      atom.workspace.open(atom.project.getDirectories()[0].resolve('.ftpignore'));
    });

    self.offline.on('click', '[role="toggle"]', () => {
      self.toggle();
    });

    self.horizontalResize.on('dblclick', (e) => { self.resizeToFitContent(e); });
    self.horizontalResize.on('mousedown', (e) => { self.resizeHorizontalStarted(e); });
    self.verticalResize.on('mousedown', (e) => { self.resizeVerticalStarted(e); });
    self.list.on('keydown', (e) => { self.remoteKeyboardNavigation(e); });

    atom.project.remoteftp.on('connected', () => {
      self.showOnline();
    });

    atom.project.remoteftp.on('disconnected', () => {
      self.showOffline();
    });

    self.getTitle = () => 'Remote-FTP';
  }

  attach() {
    const enableDock = atom.config.get('Remote-FTP.tree.useDockIntegration');
    const showOnRightSide = atom.config.get('tree-view.showOnRightSide');
    const hideLocalDisplay = atom.config.get('Remote-FTP.tree.hideLocalWhenDisplayed');

    if (showOnRightSide && enableDock) {
      // if show on right side && use new integration
      const activePane = atom.workspace.getRightDock().paneContainer.getActivePane();

      this.panel = activePane.addItem(this);
      activePane.activateItemforURI(this.getTitle());
    } else if (!showOnRightSide && enableDock) {
      // if not show on right side && use new integration
      const activePane = atom.workspace.getLeftDock().paneContainer.getActivePane();

      this.panel = activePane.addItem(this);
      activePane.activateItem(this.panel);
    } else if (showOnRightSide && !enableDock) {
      // if show on right side && not use new integration
      this.panel = atom.workspace.addRightPanel({ item: this });
    } else if (!showOnRightSide && !enableDock) {
      // if not show on right side && not use new integration
      this.panel = atom.workspace.addLeftPanel({ item: this });
    }

    if (hideLocalDisplay) {
      hideLocalTree();
    } else {
      showLocalTree();
    }
  }

  detach() {
    super.detach();

    if (this.panel) {
      if (typeof this.panel.destroy === 'function') {
        this.panel.destroy();
      } else if (typeof atom.workspace.paneForItem === 'function') {
        if (typeof atom.workspace.paneForItem(this.panel) !== 'undefined') {
          atom.workspace.paneForItem(this.panel).destroyItem(this.panel, true);
        }
      }

      this.panel = null;
    }
  }

  toggle() {
    if (typeof this.panel !== 'undefined' && this.panel !== null) {
      this.detach();
    } else {
      this.attach();
    }
  }

  showOffline() {
    this.list.hide();
    this.queue.hide();
    this.offline.css('display', 'flex');
  }

  showOnline() {
    this.list.show();
    this.queue.show();
    this.offline.hide();
  }

  resolve(path) {
    const view = $(`.remote-ftp-view [data-path="${path}"]`);

    return view.map(() => $(this).view() || null).get(0);
  }

  getSelected() {
    const views = $('.remote-ftp-view .selected');

    return views.map(() => $(this).view() || null).get();
  }

  resizeVerticalStarted(e) {
    e.preventDefault();

    const $doc = $(document);

    this.resizeHeightStart = this.queue.height();
    this.resizeMouseStart = e.pageY;

    $doc.on('mousemove', this.resizeVerticalView.bind(this));
    $doc.on('mouseup', this.resizeVerticalStopped);
  }

  resizeVerticalStopped() {
    delete this.resizeHeightStart;
    delete this.resizeMouseStart;

    const $doc = $(document);

    $doc.off('mousemove', this.resizeVerticalView);
    $doc.off('mouseup', this.resizeVerticalStopped);
  }

  resizeVerticalView(e) {
    if (e.which !== 1) { return this.resizeVerticalStopped(); }

    const delta = e.pageY - this.resizeMouseStart;
    const height = Math.max(26, this.resizeHeightStart - delta);

    this.queue.height(height);
    this.scroller.css('bottom', `${height}px`);

    return true;
  }

  resizeHorizontalStarted(e) {
    e.preventDefault();

    this.resizeWidthStart = this.width();
    this.resizeMouseStart = e.pageX;

    const $doc = $(document);

    $doc.on('mousemove', this.resizeHorizontalView.bind(this));
    $doc.on('mouseup', this.resizeHorizontalStopped);
  }

  resizeHorizontalStopped() {
    delete this.resizeWidthStart;
    delete this.resizeMouseStart;

    const $doc = $(document);

    $doc.off('mousemove', this.resizeHorizontalView);
    $doc.off('mouseup', this.resizeHorizontalStopped);
  }

  resizeHorizontalView(e) {
    if (e.which !== 1) { return this.resizeHorizontalStopped(); }

    const delta = e.pageX - this.resizeMouseStart;
    const width = Math.max(50, this.resizeWidthStart + delta);

    this.width(width);

    return true;
  }

  resizeToFitContent(e) {
    e.preventDefault();

    this.width(1);
    this.width(this.list.outerWidth());
  }

  remoteKeyboardNavigation(e) {
    const arrows = { left: 37, up: 38, right: 39, down: 40 };
    const keyCode = e.keyCode || e.which;

    switch (keyCode) {
      case arrows.up:
        this.remoteKeyboardNavigationUp();
        break;
      case arrows.down:
        this.remoteKeyboardNavigationDown();
        break;
      case arrows.left:
        this.remoteKeyboardNavigationLeft();
        break;
      case arrows.right:
        this.remoteKeyboardNavigationRight();
        break;
      default:
        return;
    }

    e.preventDefault();
    e.stopPropagation();

    this.remoteKeyboardNavigationMovePage();
  }

  remoteKeyboardNavigationUp() {
    const current = this.list.find('.selected');

    let next = current.prev('.entry:visible');

    if (next.length) {
      while (next.is('.expanded') && next.find('.entries .entry:visible').length) {
        next = next.find('.entries .entry:visible');
      }
    } else {
      next = current.closest('.entries').closest('.entry:visible');
    }

    if (next.length) {
      current.removeClass('selected');
      next.last().addClass('selected');
    }
  }

  remoteKeyboardNavigationDown() {
    const current = this.list.find('.selected');

    let next = current.find('.entries .entry:visible');
    let tmp = null;

    if (!next.length) {
      tmp = current;

      do {
        next = tmp.next('.entry:visible');

        if (!next.length) {
          tmp = tmp.closest('.entries').closest('.entry:visible');
        }
      } while (!next.length && !tmp.is('.project-root'));
    }
    if (next.length) {
      current.removeClass('selected');
      next.first().addClass('selected');
    }
  }

  remoteKeyboardNavigationLeft() {
    const current = this.list.find('.selected');

    let next = null;

    if (!current.is('.directory')) {
      next = current.closest('.directory');
      next.view().collapse();

      current.removeClass('selected');
      next.first().addClass('selected');
    } else {
      current.view().collapse();
    }
  }

  remoteKeyboardNavigationRight() {
    const current = this.list.find('.selected');

    if (current.is('.directory')) {
      const view = current.view();

      view.open();
      view.expand();
    }
  }

  remoteKeyboardNavigationMovePage() {
    const current = this.list.find('.selected');

    if (current.length) {
      const scrollerTop = this.scroller.scrollTop();
      const selectedTop = current.position().top;

      if (selectedTop < scrollerTop - 10) {
        this.scroller.pageUp();
      } else if (selectedTop > scrollerTop + (this.scroller.height() - 10)) {
        this.scroller.pageDown();
      }
    }
  }
}

export default TreeView;
<commit_msg>Fix FileTree + Self change to this<commit_after>'use babel';

import { $, ScrollView } from 'atom-space-pen-views';
import { getObject, resizeCursor, elapsedTime } from '../helpers';
import DirectoryView from './directory-view';

let hideLocalTreeError = false;

function hideLocalTree() {
  const treeView = getObject({
    obj: atom.packages.loadedPackages,
    keys: ['tree-view', 'mainModule', 'treeView'],
  });

  if (treeView && typeof treeView.detach === 'function') { // Fix for Issue 433 ( workaround to stop throwing error)
    try {
      treeView.detach();
    } catch (e) {
      if (hideLocalTreeError === false) {
        atom.notifications.addWarning('Remote FTP: See issue #433', {
          dismissable: false,
        });
        hideLocalTreeError = true;
      }
    }
  }
}

function showLocalTree() {
  const treeView = getObject({
    obj: atom.packages.loadedPackages,
    keys: ['tree-view', 'mainModule', 'treeView'],
  });
  if (treeView && typeof treeView.detach === 'function') treeView.attach();
}

class TreeView extends ScrollView {

  static content() {
    return this.div({
      class: 'remote-ftp-view ftptree-view-resizer tool-panel',
      'data-show-on-right-side': atom.config.get('tree-view.showOnRightSide'),
      'data-use-dock-integration': atom.config.get('Remote-FTP.tree.useDockIntegration'),
    }, () => {
      this.div({
        class: 'scroller',
        outlet: 'scroller',
      }, () => {
        this.ol({
          class: 'ftptree-view full-menu list-tree has-collapsable-children focusable-panel',
          tabindex: -1,
          outlet: 'list',
        });
      });
      this.div({
        class: 'resize-handle',
        outlet: 'horizontalResize',
        style: `cursor:${resizeCursor}`, // platform specific cursor
      });
      this.div({
        class: 'queue tool-panel panel-bottom',
        tabindex: -1,
        outlet: 'queue',
      }, () => {
        this.ul({
          class: 'progress tool-panel panel-top',
          tabindex: -1,
          outlet: 'progress',
        });
        this.ul({
          class: 'list',
          tabindex: -1,
          outlet: 'debug',
        });
        return this.div({
          class: 'resize-handle',
          outlet: 'verticalResize',
        });
      });
      this.div({
        class: 'offline',
        tabindex: -1,
        outlet: 'offline',
      });
    });
  }

  initialize(...args) {
    super.initialize(...args);

    const html = `

Connect

Edit Configuration

Edit Ignore Configuration

Close Panel

`;

    this.offline.html(html);

    if (atom.project.remoteftp.isConnected()) {
      this.showOnline();
    } else {
      this.showOffline();
    }

    this.root = new DirectoryView(atom.project.remoteftp.root);
    this.root.expand();
    this.list.append(this.root);

    // Events
    atom.config.onDidChange('tree-view.showOnRightSide', () => {
      if (this.isVisible()) {
        setTimeout(() => {
          this.detach();
          this.attach();
        }, 1);
      }
    });

    atom.config.onDidChange('Remote-FTP.tree.hideLocalWhenDisplayed', (values) => {
      if (values.newValue) {
        if (this.isVisible()) {
          hideLocalTree();
        }
      } else if (this.isVisible()) {
        this.detach();
        showLocalTree();
        this.attach();
      } else {
        showLocalTree();
      }
    });

    atom.config.onDidChange('Remote-FTP.tree.useDockIntegration', () => {
      if (!atom.workspace.getRightDock === 'undefined') {
        atom.notifications.addWarning('Your editor is deprecated.
This option is available only >=1.17.0 version.');
        return;
      }

      if (this.isVisible()) {
        setTimeout(() => {
          this.detach();
          this.attach();
        }, 1);
      }
    });

    atom.project.remoteftp.on('debug', (msg) => {
      this.debug.prepend(`<li>${msg}</li>`);
      const children = this.debug.children();

      if (children.length > 20) {
        children.last().remove();
      }
    });

    atom.project.remoteftp.on('queue-changed', () => {
      this.progress.empty();

      const queues = [];
      if (atom.project.remoteftp.current) {
        queues.push(atom.project.remoteftp.current);
      }

      atom.project.remoteftp.queue.forEach((queueElem) => {
        queues.push(queueElem);
      });

      if (queues.length === 0) {
        this.progress.hide();
      } else {
        this.progress.show();

        queues.forEach((queue) => {
          const $li = $(`<li><progress class="inline-block" /><div class="name">${queue[0]}</div><div class="eta">-</div></li>`);
          const $progress = $li.children('progress');
          const $eta = $li.children('.eta');
          const progress = queue[2];

          this.progress.append($li);

          progress.on('progress', (percent) => {
            if (percent === -1) {
              $progress.removeAttr('max').removeAttr('value');
              $eta.text('-');
            } else {
              $progress.attr('max', 100).attr('value', parseInt(percent * 100, 10));
              const eta = progress.getEta();

              $eta.text(elapsedTime(eta));
            }
          });

          progress.once('done', () => {
            progress.removeAllListeners('progress');
          });
        });
      }
    });

    this.offline.on('click', '[role="connect"]', () => {
      atom.project.remoteftp.readConfig(() => {
        atom.project.remoteftp.connect();
      });
    });

    this.offline.on('click', '[role="configure"]', () => {
      atom.workspace.open(atom.project.remoteftp.getConfigPath());
    });

    this.offline.on('click', '[role="configure_ignored"]', () => {
      atom.workspace.open(atom.project.getDirectories()[0].resolve('.ftpignore'));
    });

    this.offline.on('click', '[role="toggle"]', () => {
      this.toggle();
    });

    this.horizontalResize.on('dblclick', (e) => { this.resizeToFitContent(e); });
    this.horizontalResize.on('mousedown', (e) => { this.resizeHorizontalStarted(e); });
    this.verticalResize.on('mousedown', (e) => { this.resizeVerticalStarted(e); });
    this.list.on('keydown', (e) => { this.remoteKeyboardNavigation(e); });

    atom.project.remoteftp.on('connected', () => {
      this.showOnline();
    });

    atom.project.remoteftp.on('disconnected', () => {
      this.showOffline();
    });

    this.getTitle = () => 'Remote-FTP';
  }

  attach() {
    const enableDock = atom.config.get('Remote-FTP.tree.useDockIntegration');
    const showOnRightSide = atom.config.get('tree-view.showOnRightSide');
    const hideLocalDisplay = atom.config.get('Remote-FTP.tree.hideLocalWhenDisplayed');

    if (showOnRightSide && enableDock) {
      // if show on right side && use new integration
      const activePane = atom.workspace.getRightDock().paneContainer.getActivePane();

      this.panel = activePane.addItem(this);
      activePane.activateItemforURI(this.getTitle());
    } else if (!showOnRightSide && enableDock) {
      // if not show on right side && use new integration
      const activePane = atom.workspace.getLeftDock().paneContainer.getActivePane();

      this.panel = activePane.addItem(this);
      activePane.activateItem(this.panel);
    } else if (showOnRightSide && !enableDock) {
      // if show on right side && not use new integration
      this.panel = atom.workspace.addRightPanel({ item: this });
    } else if (!showOnRightSide && !enableDock) {
      // if not show on right side && not use new integration
      this.panel = atom.workspace.addLeftPanel({ item: this });
    }

    if (hideLocalDisplay) {
      hideLocalTree();
    } else {
      showLocalTree();
    }
  }

  detach(...args) {
    super.detach(...args);

    if (this.panel) {
      if (typeof this.panel.destroy === 'function') {
        this.panel.destroy();
      } else if (typeof atom.workspace.paneForItem === 'function') {
        if (typeof atom.workspace.paneForItem(this.panel) !== 'undefined') {
          atom.workspace.paneForItem(this.panel).destroyItem(this.panel, true);
        }
      }

      this.panel = null;
    }
  }

  toggle() {
    if (typeof this.panel !== 'undefined' && this.panel !== null) {
      this.detach();
    } else {
      this.attach();
    }
  }

  showOffline() {
    this.list.hide();
    this.queue.hide();
    this.offline.css('display', 'flex');
  }

  showOnline() {
    this.list.show();
    this.queue.show();
    this.offline.hide();
  }

  resolve(path) {
    const views = $(`.remote-ftp-view [data-path="${path}"]`);

    return views.map((err, item) => $(item).view() || null).get(0);
  }

  getSelected() {
    const views = $('.remote-ftp-view .selected');

    return views.map((err, item) => $(item).view() || null).get();
  }

  resizeVerticalStarted(e) {
    e.preventDefault();

    const $doc = $(document);

    this.resizeHeightStart = this.queue.height();
    this.resizeMouseStart = e.pageY;

    $doc.on('mousemove', this.resizeVerticalView.bind(this));
    $doc.on('mouseup', this.resizeVerticalStopped);
  }

  resizeVerticalStopped() {
    delete this.resizeHeightStart;
    delete this.resizeMouseStart;

    const $doc = $(document);

    $doc.off('mousemove', this.resizeVerticalView);
    $doc.off('mouseup', this.resizeVerticalStopped);
  }

  resizeVerticalView(e) {
    if (e.which !== 1) { return this.resizeVerticalStopped(); }

    const delta = e.pageY - this.resizeMouseStart;
    const height = Math.max(26, this.resizeHeightStart - delta);

    this.queue.height(height);
    this.scroller.css('bottom', `${height}px`);

    return true;
  }

  resizeHorizontalStarted(e) {
    e.preventDefault();

    this.resizeWidthStart = this.width();
    this.resizeMouseStart = e.pageX;

    const $doc = $(document);

    $doc.on('mousemove', this.resizeHorizontalView.bind(this));
    $doc.on('mouseup', this.resizeHorizontalStopped);
  }

  resizeHorizontalStopped() {
    delete this.resizeWidthStart;
    delete this.resizeMouseStart;

    const $doc = $(document);

    $doc.off('mousemove', this.resizeHorizontalView);
    $doc.off('mouseup', this.resizeHorizontalStopped);
  }

  resizeHorizontalView(e) {
    if (e.which !== 1) { return this.resizeHorizontalStopped(); }

    const delta = e.pageX - this.resizeMouseStart;
    const width = Math.max(50, this.resizeWidthStart + delta);

    this.width(width);

    return true;
  }

  resizeToFitContent(e) {
    e.preventDefault();

    this.width(1);
    this.width(this.list.outerWidth());
  }

  remoteKeyboardNavigation(e) {
    const arrows = { left: 37, up: 38, right: 39, down: 40 };
    const keyCode = e.keyCode || e.which;

    switch (keyCode) {
      case arrows.up:
        this.remoteKeyboardNavigationUp();
        break;
      case arrows.down:
        this.remoteKeyboardNavigationDown();
        break;
      case arrows.left:
        this.remoteKeyboardNavigationLeft();
        break;
      case arrows.right:
        this.remoteKeyboardNavigationRight();
        break;
      default:
        return;
    }

    e.preventDefault();
    e.stopPropagation();

    this.remoteKeyboardNavigationMovePage();
  }

  remoteKeyboardNavigationUp() {
    const current = this.list.find('.selected');

    let next = current.prev('.entry:visible');

    if (next.length) {
      while (next.is('.expanded') && next.find('.entries .entry:visible').length) {
        next = next.find('.entries .entry:visible');
      }
    } else {
      next = current.closest('.entries').closest('.entry:visible');
    }

    if (next.length) {
      current.removeClass('selected');
      next.last().addClass('selected');
    }
  }

  remoteKeyboardNavigationDown() {
    const current = this.list.find('.selected');

    let next = current.find('.entries .entry:visible');
    let tmp = null;

    if (!next.length) {
      tmp = current;

      do {
        next = tmp.next('.entry:visible');

        if (!next.length) {
          tmp = tmp.closest('.entries').closest('.entry:visible');
        }
      } while (!next.length && !tmp.is('.project-root'));
    }
    if (next.length) {
      current.removeClass('selected');
      next.first().addClass('selected');
    }
  }

  remoteKeyboardNavigationLeft() {
    const current = this.list.find('.selected');

    let next = null;

    if (!current.is('.directory')) {
      next = current.closest('.directory');
      next.view().collapse();

      current.removeClass('selected');
      next.first().addClass('selected');
    } else {
      current.view().collapse();
    }
  }

  remoteKeyboardNavigationRight() {
    const current = this.list.find('.selected');

    if (current.is('.directory')) {
      const view = current.view();

      view.open();
      view.expand();
    }
  }

  remoteKeyboardNavigationMovePage() {
    const current = this.list.find('.selected');

    if (current.length) {
      const scrollerTop = this.scroller.scrollTop();
      const selectedTop = current.position().top;

      if (selectedTop < scrollerTop - 10) {
        this.scroller.pageUp();
      } else if (selectedTop > scrollerTop + (this.scroller.height() - 10)) {
        this.scroller.pageDown();
      }
    }
  }
}

export default TreeView;
<|endoftext|>


<commit_before>const crypto = require('crypto');
const ecdsaOps = require('../ecdsaOps');
const utils = require('ethereumjs-util');
const BN = require('bn.js');

const GAS_COST = {
  1: 500,
  2: 50, //sha3
  3: 50 //RIPEMD160
};

/**
 * Runs extensions
 * @param  {Object} opts [description]
 * @return {Object|Boolean} - false when no extensions are executed.
 *                            Otherwise an object with the following
 *                            properties:
 *                            gasUsed that will be subtracted by runCode()
 *                            exception - VM status with 1=pass, 0=fail. pushed to stack by runCode()
 *                            returnValue that will be saved to memory by runCode()
 */
module.exports = function(opts) {
  var results = {};
  var gasCost;
  var to = new BN(opts.to);
  var data;
  var sha256;
  var ripemd160;
  var msgHash, v, r, s, publicKey;
  var hashStr;
  var buf;

  if (to.cmp(new BN(3)) === 1 || to.cmp(new BN(1)) === -1 ) {
    return false;
  }

  gasCost = new BN(GAS_COST[to]);
  if (opts.gas.cmp(gasCost) === -1) {
    results.gasUsed = opts.gas;
    results.exception = 0; // 0 means VM fail (in this case because of OOG)
    return results;
  }

  results.gasUsed = gasCost;

 if (to.cmp(new BN(1)) === 0) {
    buf = new Buffer(128);
    buf.fill(0);
    data = Buffer.concat([opts.data, buf]);

    msgHash = data.slice(0, 32);
    v = data.slice(32, 64);
    r = data.slice(64, 96);
    s = data.slice(96, 128);

    publicKey = ecdsaOps.ecrecover(msgHash, v, r, s);

    if (!publicKey) {
      results.exception = 1; // 1 since there is no VM error
      return results;
    }

    results.exception = 1;
    results.returnValue = utils.pad(utils.pubToAddress(publicKey), 32);
  } else if (to.cmp(new BN(2)) === 0 ) {
    sha256 = crypto.createHash('SHA256');
    data = opts.data;
    var dataGas = Math.ceil(data.length / 32) * 50;
    results.gasUsed += dataGas;

    if (opts.gas.cmp(new BN(gasCost + dataGas)) === -1) {
      results.gasUsed = opts.gas;
      results.exception = 0; // 0 means VM fail (in this case because of OOG)
      return results;
    }

    hashStr = sha256.update(data).digest('hex');

    results.exception = 1;
    results.returnValue = new Buffer(hashStr, 'hex');
  } else if (to.cmp(new BN(3)) === 0) {
    ripemd160 = crypto.createHash('RSA-RIPEMD160');
    data = opts.data;

    var dataGas2 = Math.ceil(opts.data.length / 32) * 50;
    // console.log('data: ' + data.toString('hex'));

    if (opts.gas.cmp(new BN(gasCost + dataGas2)) === -1) {
      results.gasUsed = opts.gas;
      results.exception = 0; // 0 means VM fail (in this case because of OOG)
      return results;
    }

    results.gasUsed += dataGas2;

    hashStr = utils.pad(ripemd160.update(data).digest('bin'), 32); // nb: bin

    results.exception = 1;
    results.returnValue = new Buffer(hashStr, 'hex');
  }

  return results;
};
<commit_msg>fixed precomiled tests<commit_after>const crypto = require('crypto');
const ecdsaOps = require('../ecdsaOps');
const utils = require('ethereumjs-util');
const BN = require('bn.js');

const GAS_COST = {
  1: 500,
  2: 50, //sha3
  3: 50 //RIPEMD160
};

/**
 * Runs extensions
 * @param  {Object} opts [description]
 * @return {Object|Boolean} - false when no extensions are executed.
 *                            Otherwise an object with the following
 *                            properties:
 *                            gasUsed that will be subtracted by runCode()
 *                            exception - VM status with 1=pass, 0=fail. pushed to stack by runCode()
 *                            returnValue that will be saved to memory by runCode()
 */
module.exports = function(opts) {
  var results = {};
  var gasCost;
  var to = new BN(opts.to);
  var data;
  var sha256;
  var ripemd160;
  var msgHash, v, r, s, publicKey;
  var hashStr;
  var buf;

  if (to.cmp(new BN(3)) === 1 || to.cmp(new BN(1)) === -1 ) {
    return false;
  }

  gasCost = GAS_COST[to];
  if (opts.gas.cmp(new BN(gasCost)) === -1) {
    results.gasUsed = opts.gas;
    results.exception = 0; // 0 means VM fail (in this case because of OOG)
    return results;
  }

  results.gasUsed = gasCost;

 if (to.cmp(new BN(1)) === 0) {
    buf = new Buffer(128);
    buf.fill(0);
    data = Buffer.concat([opts.data, buf]);

    msgHash = data.slice(0, 32);
    v = data.slice(32, 64);
    r = data.slice(64, 96);
    s = data.slice(96, 128);

    publicKey = ecdsaOps.ecrecover(msgHash, v, r, s);

    if (!publicKey) {
      results.exception = 1; // 1 since there is no VM error
      return results;
    }

    results.exception = 1;
    results.returnValue = utils.pad(utils.pubToAddress(publicKey), 32);
  } else if (to.cmp(new BN(2)) === 0 ) {
    sha256 = crypto.createHash('SHA256');
    data = opts.data;
    var dataGas = Math.ceil(data.length / 32) * 50;
    results.gasUsed += dataGas;

    if (opts.gas.cmp(new BN(gasCost + dataGas)) === -1) {
      results.gasUsed = opts.gas;
      results.exception = 0; // 0 means VM fail (in this case because of OOG)
      return results;
    }

    hashStr = sha256.update(data).digest('hex');

    results.exception = 1;
    results.returnValue = new Buffer(hashStr, 'hex');

  } else if (to.cmp(new BN(3)) === 0) {

    ripemd160 = crypto.createHash('RSA-RIPEMD160');
    data = opts.data;

    var dataGas2 = Math.ceil(opts.data.length / 32) * 50;
    // console.log('data: ' + data.toString('hex'));

    if (opts.gas.cmp(new BN(gasCost + dataGas2)) === -1) {
      results.gasUsed = opts.gas;
      results.exception = 0; // 0 means VM fail (in this case because of OOG)
      return results;
    }

    results.gasUsed += dataGas2;

    hashStr = utils.pad(ripemd160.update(data).digest('bin'), 32); // nb: bin

    results.exception = 1;
    results.returnValue = new Buffer(hashStr, 'hex');
  }

  return results;
};
<|endoftext|>


<commit_before>'use strict';

var net    = require('net'),
    utils  = require('radiodan-client').utils,
    logger = utils.logger(__filename);

function create(port, socket) {
  var deferred = utils.promise.defer(),
      retries  = 0,
      timeout  = 1000;

  socket = socket || new net.Socket();

  socket.setTimeout(2500);

  function addHandlers() {
    socket.on('connect', handleConnect);
    socket.on('error', handleError);
  }

  function handleConnect() {
    logger.debug('Connected to', port);
    deferred.resolve(port);
  }

  function handleError() {
    logger.warn('Cannot connect, attempt #' + ++retries);

    setTimeout(function () {
      socket.connect(port);
    }, timeout);
  }

  function connect() {
    logger.debug('Connecting to port', port);
    addHandlers();
    socket.connect(port);
    return deferred.promise;
  }

  return {
    _addHandlers: addHandlers,
    connect: connect
  };
}

module.exports = {
  create: create
};
<commit_msg>Increment `retries` variable in a way that pleases `jshint`.<commit_after>'use strict';

var net    = require('net'),
    utils  = require('radiodan-client').utils,
    logger = utils.logger(__filename);

function create(port, socket) {
  var deferred = utils.promise.defer(),
      retries  = 0,
      timeout  = 1000;

  socket = socket || new net.Socket();

  socket.setTimeout(2500);

  function addHandlers() {
    socket.on('connect', handleConnect);
    socket.on('error', handleError);
  }

  function handleConnect() {
    logger.debug('Connected to', port);
    deferred.resolve(port);
  }

  function handleError() {
    retries++;

    logger.warn('Cannot connect, attempt #' + retries);

    setTimeout(function () {
      socket.connect(port);
    }, timeout);
  }

  function connect() {
    logger.debug('Connecting to port', port);
    addHandlers();
    socket.connect(port);
    return deferred.promise;
  }

  return {
    _addHandlers: addHandlers,
    connect: connect
  };
}

module.exports = {
  create: create
};
<|endoftext|>


<commit_before>/**
* This file is part of $dom library (v0.9.2b)
* copyright 2009, 2010, 2011 Keith Clark
* Licensed under the MIT License.
* http://www.keithclark.co.uk/
*
* Copyright 2011, 2012 Julien Wajsberg
* Licensed under the MIT License
* http://github.com/julienw/dollardom
*/

(function(window) {
/*jshint boss: true, bitwise: true, curly: true, newcap: true, noarg: true, nonew: true, latedef: true, regexdash: true */

	var $dom = window.$dom;

    /* utilities functions */
    function _each(array, func) {
        for (var i = 0, l = array.length; i < l; i++) {
            func(array[i]);
        }
    }

    function _map(array, func) {
        var result = [],
            i = 0,
            l = array.length;
        for (; i < l; i++) {
            result.push(func(array[i]));
        }
        return result;
    }

    // this doesn't detect cycles (like array containting itself)
    function _flatten(array) {
		var i = 0,
			result = [],
			queue = [ array ],
			current, ii, ll, item;

		while (i < queue.length) {
			current = queue[i]; // current is always an array
			for (ii = 0, ll = current.length; ii < ll; ii++) {
				item = current[ii];
				if (isArray(item)) {
					queue.push(item);
				} else {
					result.push(item);
				}
			}
			i++;
		}
		return result;
	}

    function _isArray(arg) {
		return Object.prototype.toString.call(arg) === '[object Array]';
	}

    var each = Array.prototype.forEach ? function(array, func) { array.forEach(func); } : _each,
        map = Array.prototype.map ? function(array, func) { return array.map(func); } : _map,
        isArray = Array.isArray || _isArray;

	function DomObject(array) {
		this.a = array;
	}

	function select(sel, doc) {
		return new DomObject($dom.get(sel, doc));
	}

    function newElement(sel, doc) {
        return new DomObject([ $dom.create(sel, doc) ]);
    }

    function fromDom(a) {
		a = isArray(a) ? a : [ a ];
		return new DomObject(a);
	}

    var proto = DomObject.prototype = {
        addEvent: function(name, handler) {
            each(this.a, function(elt) {
                $dom.addEvent(elt, name, handler);
            });
            return this;
        },
        removeEvent: function(name, handler) {
            each(this.a, function(elt) {
                $dom.removeEvent(elt, name, handler);
            });
            return this;
        },
        descendants: function(sel) {
            return fromDom(
				_flatten(
					map(this.a, function(elt) {
						return $dom.descendants(elt, sel);
					})
				)
			);
        },
        ancestor: function(sel) {
            return fromDom(
				map(this.a, function(elt) {
					return $dom.ancestor(elt, sel);
				})
			);
        },
        next: function(sel) {
            return fromDom(
				map(this.a, function(elt) {
					return $dom.next(elt, sel);
				})
			);
        },
        previous: function(sel) {
            return fromDom(
				map(this.a, function(elt) {
					return $dom.previous(elt, sel);
				})
			);
        },
        first: function(sel) {
			return fromDom(
				map(this.a, function(elt) {
					return $dom.first(elt, sel);
				})
			);
		},
        last: function(sel) {
			return fromDom(
				map(this.a, function(elt) {
					return $dom.last(elt, sel);
				})
			);
		},
		empty: function() {
			each(this.a, $dom.empty);
            return this;
		},
        is: function(sel) {
            return this.a.length && $dom.is(this.a[0], sel);
        },
        hasClass: function(sel) {
            return this.a.length && $dom.hasClass(this.a[0], sel);
		},
        addClass: function(className) {
			each(this.a, function(elt) {
                $dom.addClass(elt, className);
            });
            return this;
		},
        removeClass: function(className) {
			each(this.a, function(elt) {
                $dom.removeClass(elt, className);
            });
            return this;
		},
        toggleClass: function(className, boolExpr) {
			each(this.a, function(elt) {
                $dom.toggleClass(elt, className, boolExpr);
            });
            return this;
		},
		style: function(prop, val) {
			each(this.a, function(elt) {
                $dom.style(elt, prop, val);
            });
            return this;
		},
		dom: function(n) {
			return (typeof n === "number") ? this.a[n] : this.a;
		},
		append: function(what) {
			if (what instanceof DomObject) {
				what = what.dom();
			}

			if (! isArray(what)) {
				what = [ what ];
			}
			each(this.a, function(node) {
				each(what, function(what) {
					node.appendChild(what);
				});
			});
			return this;
		},
		appendTo: function(node) {
			if (! (node instanceof DomObject)) {
				node = fromDom(node);
			}

			node.append(this);
			return this;
		},
		size: function() {
			return this.a.length;
		},
		each: function(func) {
			each(this.a, func);
			return this;
		},
		text: function(str) {
			return this.append($dom.text(str));
		}
    };

	if ($dom.transform) {
		proto.transform = proto.animate = function(props, duration, callback) {
			each(this.a, function(elt) {
				$dom.transform(elt, props, duration, callback);
				callback = null; // call callback only once
			});
			return this;
		};
	}

    $dom.Get = $dom.select = select;
    $dom.Create = $dom.element = element;
    $dom.From = $dom.from = fromDom;

})(this);
<commit_msg>minor change that should lower the size of the library<commit_after>/**
* This file is part of $dom library (v0.9.2b)
* copyright 2009, 2010, 2011 Keith Clark
* Licensed under the MIT License.
* http://www.keithclark.co.uk/
*
* Copyright 2011, 2012 Julien Wajsberg
* Licensed under the MIT License
* http://github.com/julienw/dollardom
*/

(function(window) {
/*jshint boss: true, bitwise: true, curly: true, newcap: true, noarg: true, nonew: true, latedef: true, regexdash: true */

	var $dom = window.$dom;

    /* utilities functions */
    function _each(array, func) {
        for (var i = 0, l = array.length; i < l; i++) {
            func(array[i]);
        }
    }

    function _map(array, func) {
        var result = [],
            i = 0,
            l = array.length;
        for (; i < l; i++) {
            result.push(func(array[i]));
        }
        return result;
    }

    // this doesn't detect cycles (like array containting itself)
    function _flatten(array) {
		var i = 0,
			result = [],
			queue = [ array ],
			current, ii, ll, item;

		while (i < queue.length) {
			current = queue[i]; // current is always an array
			for (ii = 0, ll = current.length; ii < ll; ii++) {
				item = current[ii];
				if (isArray(item)) {
					queue.push(item);
				} else {
					result.push(item);
				}
			}
			i++;
		}
		return result;
	}

    function _isArray(arg) {
		return Object.prototype.toString.call(arg) === '[object Array]';
	}

    var each = Array.prototype.forEach ? function(array, func) { array.forEach(func); } : _each,
        map = Array.prototype.map ? function(array, func) { return array.map(func); } : _map,
        isArray = Array.isArray || _isArray;

	function DomObject(array) {
		this.a = array;
	}

	function select(sel, doc) {
		return new DomObject($dom.get(sel, doc));
	}

    function newElement(sel, doc) {
        return new DomObject([ $dom.create(sel, doc) ]);
    }

    function fromDom(a) {
		a = isArray(a) ? a : [ a ];
		return new DomObject(a);
	}

    var proto = DomObject.prototype = {
        addEvent: function(name, handler) {
            each(this.a, function(elt) {
                $dom.addEvent(elt, name, handler);
            });
            return this;
        },
        removeEvent: function(name, handler) {
            each(this.a, function(elt) {
                $dom.removeEvent(elt, name, handler);
            });
            return this;
        },
        descendants: function(sel) {
            return fromDom(
				_flatten(
					map(this.a, function(elt) {
						return $dom.descendants(elt, sel);
					})
				)
			);
        },
        ancestor: function(sel) {
            return fromDom(
				map(this.a, function(elt) {
					return $dom.ancestor(elt, sel);
				})
			);
        },
        next: function(sel) {
            return fromDom(
				map(this.a, function(elt) {
					return $dom.next(elt, sel);
				})
			);
        },
        previous: function(sel) {
            return fromDom(
				map(this.a, function(elt) {
					return $dom.previous(elt, sel);
				})
			);
        },
        first: function(sel) {
			return fromDom(
				map(this.a, function(elt) {
					return $dom.first(elt, sel);
				})
			);
		},
        last: function(sel) {
			return fromDom(
				map(this.a, function(elt) {
					return $dom.last(elt, sel);
				})
			);
		},
		empty: function() {
			each(this.a, $dom.empty);
            return this;
		},
        is: function(sel) {
            return this.a.length && $dom.is(this.a[0], sel);
        },
        hasClass: function(sel) {
            return this.a.length && $dom.hasClass(this.a[0], sel);
		},
        addClass: function(className) {
			each(this.a, function(elt) {
                $dom.addClass(elt, className);
            });
            return this;
		},
        removeClass: function(className) {
			each(this.a, function(elt) {
                $dom.removeClass(elt, className);
            });
            return this;
		},
        toggleClass: function(className, boolExpr) {
			each(this.a, function(elt) {
                $dom.toggleClass(elt, className, boolExpr);
            });
            return this;
		},
		style: function(prop, val) {
			each(this.a, function(elt) {
                $dom.style(elt, prop, val);
            });
            return this;
		},
		dom: function(n) {
			return (typeof n === "number") ? this.a[n] : this.a;
		},
		append: function(what) {
			if (what instanceof DomObject) {
				what = what.a;
			}

			if (! isArray(what)) {
				what = [ what ];
			}
			each(this.a, function(node) {
				each(what, function(what) {
					node.appendChild(what);
				});
			});
			return this;
		},
		appendTo: function(node) {
			if (! (node instanceof DomObject)) {
				node = fromDom(node);
			}

			node.append(this);
			return this;
		},
		size: function() {
			return this.a.length;
		},
		each: function(func) {
			each(this.a, func);
			return this;
		},
		text: function(str) {
			return this.append($dom.text(str));
		}
    };

	if ($dom.transform) {
		proto.transform = proto.animate = function(props, duration, callback) {
			each(this.a, function(elt) {
				$dom.transform(elt, props, duration, callback);
				callback = null; // call callback only once
			});
			return this;
		};
	}

    $dom.Get = $dom.select = select;
    $dom.Create = $dom.element = element;
    $dom.From = $dom.from = fromDom;

})(this);
<|endoftext|>