<commit_before>/// <reference path="../../dist/preview release/babylon.d.ts"/>

var Test = (function () {
    function Test(canvasId) {
        var _this = this;
        var canvas = document.getElementById(canvasId);
        this.engine = new BABYLON.Engine(canvas, true);
        BABYLONDEVTOOLS.Loader.debugShortcut(this.engine);
        this.scene = null;
        window.addEventListener("resize", function () {
            _this.engine.resize();
        });
        this._run();
    }
    Test.prototype._run = function () {
        var _this = this;
        this._initScene();
        this.scene.debugLayer.show({
            popup: false,
            parentElement: document.getElementById('inspector'),
            newColors: {
                backgroundColor: '#eee',
                backgroundColorLighter: '#fff',
                backgroundColorLighter2: '#fff',
                backgroundColorLighter3: '#fff',
                color: '#333'
            }
        });
        this.scene.executeWhenReady(function () {
            _this.engine.runRenderLoop(function () {
                _this.scene.render();
            });
        });
    };
    Test.prototype._initScene = function () {
        var scene = new BABYLON.Scene(this.engine);
        var canvas = scene.getEngine().getRenderingCanvas();
        var light = new BABYLON.HemisphericLight("hemi", new BABYLON.Vector3(0, 1, 0), scene);

        var camera = new BABYLON.ArcRotateCamera("Camera", Math.PI / 2, 1.0, 110, new BABYLON.Vector3(0, -20, 0), scene);
        camera.attachControl(canvas, true);

        var camera1 = new BABYLON.ArcRotateCamera("Camera1", 1.58, 1.2, 110, BABYLON.Vector3.Zero(), scene);
        var camera2 = new BABYLON.ArcRotateCamera("Camera2", Math.PI / 3, .8, 40, BABYLON.Vector3.Zero(), scene);
        var camera3 = new BABYLON.ArcRotateCamera("Camera3", -Math.PI / 5, 1.0, 70, BABYLON.Vector3.Zero(), scene);
        var camera4 = new BABYLON.ArcRotateCamera("Camera4", -Math.PI / 6, 1.3, 110, BABYLON.Vector3.Zero(), scene);

        camera1.layerMask = 2;
        camera2.layerMask = 2;
        camera3.layerMask = 2;
        camera4.layerMask = 2;
        /*
            camera1.parent = camera;
            camera2.parent = camera;
            camera3.parent = camera;
            camera4.parent = camera;
        */

        //Sounds
        var jump = new BABYLON.Sound("Jump", "test/jump.wav", scene);
        var explosion = new BABYLON.Sound("Explosion", "test/explosion.wav", scene);
        jump.setVolume(0.1);
        window.addEventListener("keydown", function (evt) {
            if (evt.keyCode === 32) {
                jump.play();
            }
        });

        // Skybox
        var skybox = BABYLON.Mesh.CreateBox("skyBox", 500.0, scene);
        var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", scene);
        skyboxMaterial.backFaceCulling = false;
        skyboxMaterial.reflectionTexture = new BABYLON.CubeTexture("/playground/textures/TropicalSunnyDay", scene);
        skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
        skyboxMaterial.diffuseColor = new BABYLON.Color3(0, 0, 0);
        skyboxMaterial.specularColor = new BABYLON.Color3(0, 0, 0);
        skyboxMaterial.disableLighting = true;
        skybox.material = skyboxMaterial;

        var sphere1 = BABYLON.Mesh.CreateSphere("Sphere1", 10.0, 9.0, scene);
        var sphere2 = BABYLON.Mesh.CreateSphere("Sphere2", 2.0, 9.0, scene);//Only two segments
        var sphere3 = BABYLON.Mesh.CreateSphere("Sphere3", 10.0, 9.0, scene);
        var sphere4 = BABYLON.Mesh.CreateSphere("Sphere4", 10.0, 9.0, scene);
        var sphere5 = BABYLON.Mesh.CreateSphere("Sphere5", 10.0, 9.0, scene);
        var sphere6 = BABYLON.Mesh.CreateSphere("Sphere6", 10.0, 9.0, scene);

        sphere1.position.x = 40;
        sphere2.position.x = 25;
        sphere3.position.x = 10;
        sphere4.position.x = -5;
        sphere5.position.x = -20;
        sphere6.position.x = -35;

        var rt1 = new BABYLON.RenderTargetTexture("depth", 1024, scene, true, true);
        scene.customRenderTargets.push(rt1);
        rt1.activeCamera = camera1;
        rt1.renderList = scene.meshes;

        var rt2 = new BABYLON.RenderTargetTexture("depth", 1024, scene, true, true);
        scene.customRenderTargets.push(rt2);
        rt2.activeCamera = camera2;
        rt2.renderList = scene.meshes;

        var rt3 = new BABYLON.RenderTargetTexture("depth", 1024, scene, true, true);
        scene.customRenderTargets.push(rt3);
        rt3.activeCamera = camera3;
        rt3.renderList = scene.meshes;

        var rt4 = new BABYLON.RenderTargetTexture("depth", 1024, scene, true, true);
        scene.customRenderTargets.push(rt4);
        rt4.activeCamera = camera4;
        rt4.renderList = scene.meshes;

        var mon1 = BABYLON.Mesh.CreatePlane("plane", 5, scene);
        mon1.position = new BABYLON.Vector3(-8.8, -7.8, 25)
        // mon1.showBoundingBox = true;
        var mon1mat = new BABYLON.StandardMaterial("texturePlane", scene);
        mon1mat.diffuseTexture = rt1;
        mon1.material = mon1mat;
        mon1.parent = camera;
        mon1.layerMask = 1;

        var mon2 = BABYLON.Mesh.CreatePlane("plane", 5, scene);
        mon2.position = new BABYLON.Vector3(-2.9, -7.8, 25)
        // mon2.showBoundingBox = true;
        var mon2mat = new BABYLON.StandardMaterial("texturePlane", scene);
        mon2mat.diffuseTexture = rt2;
        mon2.material = mon2mat;
        mon2.parent = camera;
        mon2.layerMask = 1;

        var mon3 = BABYLON.Mesh.CreatePlane("plane", 5, scene);
        mon3.position = new BABYLON.Vector3(2.9, -7.8, 25)
        // mon3.showBoundingBox = true;
        var mon3mat = new BABYLON.StandardMaterial("texturePlane", scene);
        mon3mat.diffuseTexture = rt3;
        mon3.material = mon3mat;
        mon3.parent = camera;
        mon3.layerMask = 1;

        var mon4 = BABYLON.Mesh.CreatePlane("plane", 5, scene);
        mon4.position = new BABYLON.Vector3(8.8, -7.8, 25)
        // mon4.showBoundingBox = true;
        var mon4mat = new BABYLON.StandardMaterial("texturePlane", scene);
        mon4mat.diffuseTexture = rt4;
        mon4.material = mon4mat;
        mon4.parent = camera;
        mon4.layerMask = 1;

        var butback = BABYLON.MeshBuilder.CreatePlane("plane", { width: 25, height: 6 }, scene);
        butback.position = new BABYLON.Vector3(0, -8.2, 26)
        // butback.showBoundingBox = true;
        var butbackmat = new BABYLON.StandardMaterial("texturePlane", scene);
        butbackmat.diffuseColor = BABYLON.Color3.Black();
        butback.material = butbackmat;
        butback.parent = camera;
        butback.layerMask = 1;

        var plane = BABYLON.Mesh.CreatePlane("plane", 120, scene);
        plane.position.y = -5;
        plane.rotation.x = Math.PI / 2;

        var materialSphere1 = new BABYLON.StandardMaterial("texture1", scene);
        materialSphere1.wireframe = true;

        //Creation of a red material with alpha
        var materialSphere2 = new BABYLON.StandardMaterial("texture2", scene);
        materialSphere2.diffuseColor = new BABYLON.Color3(1, 0, 0); //Red
        materialSphere2.alpha = 0.3;

        //Creation of a material with an image texture
        var materialSphere3 = new BABYLON.StandardMaterial("texture3", scene);
        materialSphere3.diffuseTexture = new BABYLON.Texture("/playground/textures/amiga.jpg", scene);

        //Creation of a material with translated texture
        var materialSphere4 = new BABYLON.StandardMaterial("texture4", scene);
        materialSphere4.diffuseTexture = new BABYLON.Texture("/playground/textures/floor.png", scene);
        materialSphere4.diffuseTexture.vOffset = 0.1;//Vertical offset of 10%
        materialSphere4.diffuseTexture.uOffset = 0.4;//Horizontal offset of 40%

        //Creation of a material with an alpha texture
        var materialSphere5 = new BABYLON.StandardMaterial("texture5", scene);
        materialSphere5.diffuseTexture = new BABYLON.Texture("/playground/textures/rock.png", scene);
        materialSphere5.diffuseTexture.hasAlpha = true;//Has an alpha

        //Creation of a material and show all the faces
        var materialSphere6 = new BABYLON.StandardMaterial("texture6", scene);
        materialSphere6.diffuseTexture = new BABYLON.Texture("/playground/textures/grass.png", scene);
        materialSphere6.diffuseTexture.hasAlpha = true;//Have an alpha
        materialSphere6.backFaceCulling = false;//Show all the faces of the element

        //Creation of a repeated textured material
        var materialPlane = new BABYLON.StandardMaterial("texturePlane", scene);
        materialPlane.diffuseTexture = new BABYLON.Texture("/playground/textures/mixMap.png", scene);
        materialPlane.diffuseTexture.uScale = 5.0;
        materialPlane.diffuseTexture.vScale = 5.0;
        materialPlane.backFaceCulling = false;

        //Apply the materials to meshes
        sphere1.material = materialSphere1;
        sphere2.material = materialSphere2;

        sphere3.material = materialSphere3;
        sphere4.material = materialSphere4;

        sphere5.material = materialSphere5;
        sphere6.material = materialSphere6;

        plane.material = materialPlane;

        new BABYLON.Mesh('mesh_without_geometry', scene);

        var d = 50;
        var cubes = new Array();
        for (var i = 0; i < 360; i += 20) {
            var r = BABYLON.Tools.ToRadians(i);
            var b = BABYLON.Mesh.CreateBox("Box #" + i / 20, 5, scene, false);
            b.position.x = Math.cos(r) * d;
            b.position.z = Math.sin(r) * d;
            cubes.push(b);
        }

        scene.getMeshByName("Box #6").scaling.x = 2;

        //Other meshes, to contrôl mesh hierarchy
        var box1 = BABYLON.MeshBuilder.CreateBox("box1", {size: 1}, scene);

        var box2 = BABYLON.MeshBuilder.CreateBox("box2", {size: 1}, scene);
        box2.position.x = 1.5;
        box2.parent = box1;

        var box3 = BABYLON.MeshBuilder.CreateBox("box3", {size: 1}, scene);
        box3.position.x = 1.5;
        box3.parent = box2;

        var box4 = BABYLON.MeshBuilder.CreateBox("box4", {size: 1}, scene);
        box4.position.x = 1.5;
        box4.parent = box3;

        window.addEventListener("keydown", function (evt) {
            sphere1.dispose();
            var sphere7 = BABYLON.Mesh.CreateSphere("Sphere7", 10.0, 9.0, scene);
            sphere7.position.x = 40;
        });

        var sphere_1 = BABYLON.Mesh.CreateSphere("_sphere_1", 16, 2, scene);

        var assets_mesh = new BABYLON.AbstractMesh("assets_mesh", scene);
        var sphere_2 = BABYLON.Mesh.CreateSphere("_sphere_2", 3, 2, scene);
        var sphere_3 = BABYLON.Mesh.CreateSphere("_sphere_3", 2, 2, scene);
        var scene_mesh = new BABYLON.AbstractMesh;
        scene_mesh.name="scene_mesh";

        sphere_1.parent = assets_mesh;
        sphere_2.parent = assets_mesh;
        sphere_3.parent = assets_mesh;

        for (var i=0; i<10 ; i++){
            var inst = sphere_1.createInstance("C_" + i + "clone");
            inst.isVisible = true;
            inst.setEnabled = true;
            inst.parent = scene_mesh;
            inst.position.x = i*2;
            inst.refreshBoundingInfo();
            inst.computeWorldMatrix();
        }

        // to test reflection prob texture handling
        var probe = new BABYLON.ReflectionProbe("probe", 512, scene);
        probe.renderList.push(sphere1);

        // gui
        var advancedTexture = BABYLON.GUI.AdvancedDynamicTexture.CreateFullscreenUI("UI");

        var picker = new BABYLON.GUI.ColorPicker();
        picker.height = "150px";
        picker.width = "150px";
        picker.horizontalAlignment = BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_CENTER;

        var checkbox = new BABYLON.GUI.Checkbox();
        checkbox.width = "20px";
        checkbox.height = "20px";

        var slider = new BABYLON.GUI.Slider();
        slider.minimum = 0;
        slider.maximum = 2 * Math.PI;
        slider.value = 0;
        slider.height = "20px";
        slider.width = "200px";

        var line = new BABYLON.GUI.Line();
        line.x1 = 10;
        line.y1 = 10;
        line.x2 = 1000;
        line.y2 = 500;

        var panel = new BABYLON.GUI.StackPanel();

        var button = BABYLON.GUI.Button.CreateSimpleButton("but", "Click Me");
        button.width = 0.2;
        button.height = "40px";
        button.color = "white";
        button.background = "green";
        panel.addControl(button);

        var button2 = BABYLON.GUI.Button.CreateSimpleButton("but2", "Click Me also!");
        button2.width = 0.2;
        button2.height = "40px";
        button2.color = "white";
        button2.background = "green";
        panel.addControl(button2);

        var ellipse1 = new BABYLON.GUI.Ellipse();
        ellipse1.width = "100px"
        ellipse1.height = "100px";
        ellipse1.color = "Orange";
        ellipse1.thickness = 4;
        ellipse1.background = "green";

        advancedTexture.addControl(ellipse1);
        advancedTexture.addControl(panel);
        advancedTexture.addControl(picker);
        advancedTexture.addControl(checkbox);
        advancedTexture.addControl(slider);
        advancedTexture.addControl(line);
        advancedTexture.addControl(checkbox);

        this.scene = scene;
    };
    return Test;
}());<commit_msg>Test for inspector simplified<commit_after>/// <reference path="../../dist/preview release/babylon.d.ts"/>

var Test = (function () {
    function Test(canvasId) {
        var _this = this;
        var canvas = document.getElementById(canvasId);
        this.engine = new BABYLON.Engine(canvas, true);
        BABYLONDEVTOOLS.Loader.debugShortcut(this.engine);
        this.scene = null;
        window.addEventListener("resize", function () {
            _this.engine.resize();
        });
        this._run();
    }
    Test.prototype._run = function () {
        var _this = this;
        this._initScene();
        this.scene.debugLayer.show({
            popup: false,
            parentElement: document.getElementById('inspector'),
            newColors: {
                backgroundColor: '#eee',
                backgroundColorLighter: '#fff',
                backgroundColorLighter2: '#fff',
                backgroundColorLighter3: '#fff',
                color: '#333'
            }
        });
        this.scene.executeWhenReady(function () {
            _this.engine.runRenderLoop(function () {
                _this.scene.render();
            });
        });
    };
    Test.prototype._initScene = function () {
        var scene = new BABYLON.Scene(this.engine);
        var canvas = scene.getEngine().getRenderingCanvas();

        var sceneRoot = new BABYLON.AbstractMesh("SceneRoot");
        // Our built-in 'ground' shape. Params: name, width, depth, subdivs, scene
        var ground = BABYLON.Mesh.CreateGround("node_damagedHelmet_-6514", 6, 6, 2, scene);
        ground.parent = sceneRoot;

        let num = 5;
        let angStep = 6.283185307 / num;
        let rad = 2;
        let p = ground;
        for (let i = 0; i < num; i++) {
            // Our built-in 'sphere' shape. Params: name, subdivs, size, scene
            let sphere = BABYLON.Mesh.CreateSphere(`sphere${i}`, 16, 2, scene);

            // Move the sphere upward 1/2 its height
            sphere.position.y = 0.2;
            sphere.position.x = Math.sin(i * angStep) * rad;
            sphere.position.z = Math.cos(i * angStep) * rad;
            sphere.parent = p;
            p = sphere;
        }

        scene.createDefaultCameraOrLight(true);
        scene.activeCamera.attachControl(canvas);

        this.scene = scene;
    };
    return Test;
}());<|endoftext|>


<commit_before>/* @flow */

import React from 'react'
import { View, Text, StyleSheet, Platform } from 'react-native'
import NavBarBackButton from './NavBarBackButton'

export function leftButtonRouteMapperGenerator (BackComponent, styles, tintColor, topNavigator) {
  return {
    LeftButton: (route, navigator, index, navState) => {
      if (route.leftElement) {
        const leftElement = React.cloneElement(route.leftElement, {
          navigator: navigator,
          topNavigator: topNavigator,
        })
        return (
          <View style={defaultStyles.elementContainer}>
            {leftElement}
          </View>
        )
      } else if (index > 0) {
        const previousRoute = navState.routeStack[index - 1]
        return (
          <View style={{flex: 1, flexDirection: 'row', alignItems: 'center'}}>
            <BackComponent
              onPress={() => navigator.pop()}
              style={[{flex: 1}, styles]}
              tintColor={tintColor}
              showBackTitle={true}>
              {previousRoute.title}
            </BackComponent>
          </View>
        )
      }
      return null
    }
  }
}

export function rightButtonRouteMapperGenerator (RightComponent, topNavigator) {
  return {
    RightButton: (route, navigator, index, navState) => {
      if (route.rightElement) {
        const rightElement = React.cloneElement(route.rightElement, {
          navigator: navigator,
          topNavigator: topNavigator,
        })
        return (
          <View style={defaultStyles.elementContainer}>
            {rightElement}
          </View>
        )
      } else if (RightComponent) {
        return <RightComponent navigator={navigator} topNavigator={topNavigator} />
      }
      return null
    }
  }
}

export function titleRouteMapperGenerator (TitleComponent, styles, topNavigator) {
  return {
    Title: (route, navigator, index, navState) => {
      const Component = TitleComponent || Text
      return (
        <Component style={styles} numberOfLines={1}>
          {route.title}
        </Component>
      )
    }
  }
}

export class CenteredText extends React.Component {
  render () {
    return (
      <View style={{flex: 1, flexDirection: 'row', alignItems: 'center'}}>
        <Text style={this.props.style}>
          {this.props.children}
        </Text>
      </View>
    )
  }
}

const defaultStyles = StyleSheet.create({
  back: {
    flex: 1,
    color: (Platform.OS === 'ios') ? '#0076ff' : '#607D8B',
  },
  navFont: {
    fontSize: 17,
  },
  navText: {
    flex: 1,
  },
  elementContainer: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
  },
})

export function defaultRouteMapper () {
  return {
    ...leftButtonRouteMapperGenerator(NavBarBackButton, [defaultStyles.navFont, defaultStyles.back], (Platform.OS === 'ios') ? '#0076ff' : '#607D8B'),
    ...rightButtonRouteMapperGenerator(),
    ...titleRouteMapperGenerator(CenteredText, [defaultStyles.navFont, defaultStyles.navText])
  }
}
<commit_msg>Solved issue with title alignment (#14)<commit_after>/* @flow */

import React from 'react'
import { View, Text, StyleSheet, Platform } from 'react-native'
import NavBarBackButton from './NavBarBackButton'

export function leftButtonRouteMapperGenerator (BackComponent, styles, tintColor, topNavigator) {
  return {
    LeftButton: (route, navigator, index, navState) => {
      if (route.leftElement) {
        const leftElement = React.cloneElement(route.leftElement, {
          navigator: navigator,
          topNavigator: topNavigator,
        })
        return (
          <View style={defaultStyles.elementContainer}>
            {leftElement}
          </View>
        )
      } else if (index > 0) {
        const previousRoute = navState.routeStack[index - 1]
        return (
          <View style={{flex: 1, flexDirection: 'row', alignItems: 'center'}}>
            <BackComponent
              onPress={() => navigator.pop()}
              style={[{flex: 1}, styles]}
              tintColor={tintColor}
              showBackTitle={true}>
              {previousRoute.title}
            </BackComponent>
          </View>
        )
      }
      return null
    }
  }
}

export function rightButtonRouteMapperGenerator (RightComponent, topNavigator) {
  return {
    RightButton: (route, navigator, index, navState) => {
      if (route.rightElement) {
        const rightElement = React.cloneElement(route.rightElement, {
          navigator: navigator,
          topNavigator: topNavigator,
        })
        return (
          <View style={defaultStyles.elementContainer}>
            {rightElement}
          </View>
        )
      } else if (RightComponent) {
        return <RightComponent navigator={navigator} topNavigator={topNavigator} />
      }
      return null
    }
  }
}

export function titleRouteMapperGenerator (TitleComponent, styles, topNavigator) {
  return {
    Title: (route, navigator, index, navState) => {
      const Component = TitleComponent || Text
      return (
        <Component style={styles} numberOfLines={1}>
          {route.title}
        </Component>
      )
    }
  }
}

export class CenteredText extends React.Component {
  render () {
    return (
      <View style={titleStyles.container}>
        <Text style={[titleStyles.title, this.props.style]}>
          {this.props.children}
        </Text>
      </View>
    )
  }
}

const titleStyles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
  },
  title: {
    textAlign: (Platform.OS === 'ios') ? 'center' : 'left',
  }
})

const defaultStyles = StyleSheet.create({
  back: {
    flex: 1,
    color: (Platform.OS === 'ios') ? '#0076ff' : '#607D8B',
  },
  navFont: {
    fontSize: 17,
  },
  navText: {
    flex: 1,
  },
  elementContainer: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
  },
})

export function defaultRouteMapper () {
  return {
    ...leftButtonRouteMapperGenerator(NavBarBackButton, [defaultStyles.navFont, defaultStyles.back], (Platform.OS === 'ios') ? '#0076ff' : '#607D8B'),
    ...rightButtonRouteMapperGenerator(),
    ...titleRouteMapperGenerator(CenteredText, [defaultStyles.navFont, defaultStyles.navText])
  }
}
<|endoftext|>


<commit_before>let async = require('async');
//require("../utils/debug_util.js")(__filename, async);
let utils = require('../utils/utils.js');

let RunCode = require('../core/runCode.js');

let CodeGenerator = require('./code_generator.js');

class Deploy {
  constructor(options) {
    this.blockchain = options.blockchain;
    this.web3 = this.blockchain.web3;
    this.contractsManager = options.contractsManager;
    this.logger = options.logger;
    this.events = options.events;
    this.plugins = options.plugins;
    this.gasLimit = options.gasLimit;
  }

  determineArguments(suppliedArgs, contract) {
    let realArgs = [], l, arg, contractName, referedContract;

    let args = suppliedArgs;

    if (!Array.isArray(args)) {
      args = [];
      let abi = contract.abiDefinition.find((abi) => abi.type === 'constructor');

      for (let input of abi.inputs) {
        let inputValue = suppliedArgs[input.name];
        if (!inputValue) {
          this.logger.error(__("{{inputName}} has not been defined for {{className}} constructor", {inputName: input.name, className: contract.className}));
        }
        args.push(inputValue || "");
      }
    }

    for (l = 0; l < args.length; l++) {
      arg = args[l];
      if (arg[0] === "$") {
        contractName = arg.substr(1);
        referedContract = this.contractsManager.getContract(contractName);
        realArgs.push(referedContract.deployedAddress);
      } else if (Array.isArray(arg)) {
        let subRealArgs = [];
        for (let sub_arg of arg) {
          if (sub_arg[0] === "$") {
            contractName = sub_arg.substr(1);
            referedContract = this.contractsManager.getContract(contractName);
            subRealArgs.push(referedContract.deployedAddress);
          } else {
            subRealArgs.push(sub_arg);
          }
        }
        realArgs.push(subRealArgs);
      } else {
        realArgs.push(arg);
      }
    }

    return realArgs;
  }

  checkAndDeployContract(contract, params, callback) {
    let self = this;
    contract.error = false;

    if (contract.deploy === false) {
      self.events.emit("deploy:contract:undeployed", contract);
      return callback();
    }

    contract.realArgs = self.determineArguments(params || contract.args, contract);

    if (contract.address !== undefined) {
      try {
        utils.toChecksumAddress(contract.address);
      } catch(e) {
        self.logger.error(__("error deploying %s", contract.className));
        self.logger.error(e.message);
        contract.error = e.message;
        self.events.emit("deploy:contract:error", contract);
        return callback(e.message);
      }
      contract.deployedAddress = contract.address;
      self.logger.info(contract.className.bold.cyan + __(" already deployed at ").green + contract.address.bold.cyan);
      self.events.emit("deploy:contract:deployed", contract);
      return callback();
    }

    // TODO: this should be a plugin API instead, if not existing, it should by default deploy the contract
    self.events.request("deploy:contract:shouldDeploy", contract, function(trackedContract) {
      if (!trackedContract) {
        return self.contractToDeploy(contract, params, callback);
      }

      self.blockchain.getCode(trackedContract.address, function(_getCodeErr, codeInChain) {
        if (codeInChain !== "0x") {
          self.contractAlreadyDeployed(contract, trackedContract, callback);
        } else {
          self.contractToDeploy(contract, params, callback);
        }
      });
    });
  }

  contractAlreadyDeployed(contract, trackedContract, callback) {
    const self = this;
    self.logger.info(contract.className.bold.cyan + __(" already deployed at ").green + trackedContract.address.bold.cyan);
    contract.deployedAddress = trackedContract.address;
    self.events.emit("deploy:contract:deployed", contract);

    // always run contractCode so other functionality like 'afterDeploy' can also work
    let codeGenerator = new CodeGenerator({contractsManager: self.contractsManager});
    let contractCode = codeGenerator.generateContractCode(contract, self.gasLimit);
    RunCode.doEval(contractCode, {web3: self.web3});

    return callback();
  }

  contractToDeploy(contract, params, callback) {
    const self = this;
    contract.realArgs = self.determineArguments(params || contract.args, contract);

    this.deployContract(contract, contract.realArgs, function (err, address) {
      if (err) {
        self.events.emit("deploy:contract:error", contract);
        return callback(new Error(err));
      }
      contract.address = address;
      self.events.emit("deploy:contract:deployed", contract);

      // always run contractCode so other functionality like 'afterDeploy' can also work
      let codeGenerator = new CodeGenerator({contractsManager: self.contractsManager});
      let contractCode = codeGenerator.generateContractCode(contract, self.gasLimit);
      RunCode.doEval(contractCode, {web3: self.web3});

      let onDeployPlugins = self.plugins.getPluginsProperty('onDeployActions', 'onDeployActions');

      async.eachLimit(onDeployPlugins, 1, function(plugin, nextEach) {
        plugin.call(plugin, contract, nextEach);
      }, () => {
        callback();
      });
    });
  }

  deployContract(contract, params, callback) {
    let self = this;
    let accounts = [];
    let contractParams = (params || contract.args).slice();
    let contractCode = contract.code;
    let deploymentAccount = self.blockchain.defaultAccount();
    let deployObject;

    async.waterfall([
      // TODO: can potentially go to a beforeDeploy plugin
      function getAccounts(next) {
        self.blockchain.getAccounts(function (err, _accounts) {
          if (err) {
            return next(new Error(err));
          }
          accounts = _accounts;

          // applying deployer account configuration, if any
          if (typeof contract.fromIndex == 'number') {
            deploymentAccount = accounts[contract.fromIndex];
            if (deploymentAccount === undefined) {
              return next(__("error deploying") + " " + contract.className + ": " + __("no account found at index") + " " + contract.fromIndex + __(" check the config"));
            }
          }
          if (typeof contract.from == 'string' && typeof contract.fromIndex != 'undefined') {
            self.logger.warn(__('Both "from" and "fromIndex" are defined for contract') + ' "' + contract.className + '". ' + __('Using "from" as deployer account.'));
          }
          if (typeof contract.from == 'string') {
            deploymentAccount = contract.from;
          }

          deploymentAccount = deploymentAccount || accounts[0];
          next();
        });
      },
      function doLinking(next) {
        self.events.request('contracts:list', (contracts) => {
          for (let contractObj of contracts) {
            let filename = contractObj.filename;
            let deployedAddress = contractObj.deployedAddress;
            if (deployedAddress) {
              deployedAddress = deployedAddress.substr(2);
            }
            let linkReference = '__' + filename + ":" + contractObj.className;
            if (contractCode.indexOf(linkReference) < 0) {
              continue;
            }
            if (linkReference.length > 40) {
              return next(new Error(__("{{linkReference}} is too long, try reducing the path of the contract ({{filename}}) and/or its name {{contractName}}", {linkReference: linkReference, filename: filename, contractName: contractObj.className})));
            }
            let toReplace = linkReference + "_".repeat(40 - linkReference.length);
            if (deployedAddress === undefined) {
              let libraryName = contractObj.className;
              return next(new Error(__("{{contractName}} needs {{libraryName}} but an address was not found, did you deploy it or configured an address?", {contractName: contract.className, libraryName: libraryName})));
            }
            contractCode = contractCode.replace(new RegExp(toReplace, "g"), deployedAddress);
          }
          // saving code changes back to contract object
          contract.code = contractCode;
          next();
        });
      },
      function applyBeforeDeploy(next) {
        let beforeDeployPlugins = self.plugins.getPluginsFor('beforeDeploy');

        //self.logger.info("applying beforeDeploy plugins...", beforeDeployPlugins.length);
        async.eachSeries(beforeDeployPlugins, (plugin, eachPluginCb) => {
          self.logger.info(__("running beforeDeploy plugin %s .", plugin.name));

          // calling each beforeDeploy handler declared by the plugin
          async.eachSeries(plugin.beforeDeploy, (beforeDeployFn, eachCb) => {
            function beforeDeployCb(resObj){
              contract.code = resObj.contractCode;
              eachCb();
            }
            beforeDeployFn({
              embarkDeploy:       self,
              pluginConfig:       plugin.pluginConfig,
              deploymentAccount:  deploymentAccount,
              contract:           contract,
              callback: beforeDeployCb
            }, beforeDeployCb);
          }, () => {
            //self.logger.info('All beforeDeploy handlers of the plugin has processed.');
            eachPluginCb();
          });
        }, () => {
          //self.logger.info('All beforeDeploy plugins has been processed.');
          contractCode = contract.code;
          next();
        });
      },
      function createDeployObject(next) {
        let contractObject = self.blockchain.ContractObject({abi: contract.abiDefinition});

        try {
          const dataCode = contractCode.startsWith('0x') ? contractCode : "0x" + contractCode;
          deployObject = self.blockchain.deployContractObject(contractObject, {arguments: contractParams, data: dataCode});
        } catch(e) {
          if (e.message.indexOf('Invalid number of parameters for "undefined"') >= 0) {
            return next(new Error(__("attempted to deploy %s without specifying parameters", contract.className)));
          } else {
            return next(new Error(e));
          }
        }
        next();
      },
      function estimateCorrectGas(next) {
        if (contract.gas === 'auto') {
          return deployObject.estimateGas().then((gasValue) => {
            contract.gas = gasValue;
            next();
          }).catch(next);
        }
        next();
      },
      function deployTheContract(next) {
        self.logger.info(__("deploying") + " " + contract.className.bold.cyan + " " + __("with").green + " " + contract.gas + " " + __("gas").green);

        self.blockchain.deployContractFromObject(deployObject, {
          from: deploymentAccount,
          gas: contract.gas,
          gasPrice: contract.gasPrice
        }, function(error, receipt) {
          if (error) {
            return next(new Error("error deploying =" + contract.className + "= due to error: " + error.message));
          }
          self.logger.info(contract.className.bold.cyan + " " + __("deployed at").green + " " + receipt.contractAddress.bold.cyan);
          contract.deployedAddress = receipt.contractAddress;
          contract.transactionHash = receipt.transactionHash;
          return next(null, receipt.contractAddress);
        });
      }
    ], callback);
  }

  deployAll(done) {
    let self = this;
    this.logger.info(__("deploying contracts"));
    this.events.emit("deploy:beforeAll");

    self.events.request('contracts:list', (contracts) => {
      async.eachOfSeries(contracts,
        function (contract, key, callback) {
          self.logger.trace(arguments);
          self.checkAndDeployContract(contract, null, callback);
        },
        function (err, _results) {
          if (err) {
            self.logger.error(__("error deploying contracts"));
            self.logger.error(err.message);
            self.logger.debug(err.stack);
          }
          if (contracts.length === 0) {
            self.logger.info(__("no contracts found"));
            return done();
          }
          self.logger.info(__("finished deploying contracts"));
          self.logger.trace(arguments);
          done(err);
        }
      );
    });

  }
}

module.exports = Deploy;
<commit_msg>refactor to waterfall, in preparation to making determine arguments async<commit_after>let async = require('async');
//require("../utils/debug_util.js")(__filename, async);
let utils = require('../utils/utils.js');

let RunCode = require('../core/runCode.js');

let CodeGenerator = require('./code_generator.js');

class Deploy {
  constructor(options) {
    this.blockchain = options.blockchain;
    this.web3 = this.blockchain.web3;
    this.contractsManager = options.contractsManager;
    this.logger = options.logger;
    this.events = options.events;
    this.plugins = options.plugins;
    this.gasLimit = options.gasLimit;
  }

  determineArguments(suppliedArgs, contract) {
    let realArgs = [], l, arg, contractName, referedContract;

    let args = suppliedArgs;

    if (!Array.isArray(args)) {
      args = [];
      let abi = contract.abiDefinition.find((abi) => abi.type === 'constructor');

      for (let input of abi.inputs) {
        let inputValue = suppliedArgs[input.name];
        if (!inputValue) {
          this.logger.error(__("{{inputName}} has not been defined for {{className}} constructor", {inputName: input.name, className: contract.className}));
        }
        args.push(inputValue || "");
      }
    }

    for (l = 0; l < args.length; l++) {
      arg = args[l];
      if (arg[0] === "$") {
        contractName = arg.substr(1);
        referedContract = this.contractsManager.getContract(contractName);
        realArgs.push(referedContract.deployedAddress);
      } else if (Array.isArray(arg)) {
        let subRealArgs = [];
        for (let sub_arg of arg) {
          if (sub_arg[0] === "$") {
            contractName = sub_arg.substr(1);
            referedContract = this.contractsManager.getContract(contractName);
            subRealArgs.push(referedContract.deployedAddress);
          } else {
            subRealArgs.push(sub_arg);
          }
        }
        realArgs.push(subRealArgs);
      } else {
        realArgs.push(arg);
      }
    }

    return realArgs;
  }

  checkAndDeployContract(contract, params, callback) {
    let self = this;
    contract.error = false;

    if (contract.deploy === false) {
      self.events.emit("deploy:contract:undeployed", contract);
      return callback();
    }

    async.waterfall([
      function determineArguments(next) {
        contract.realArgs = self.determineArguments(params || contract.args, contract);
        next();
      },
      function deployIt(next) {
        if (contract.address !== undefined) {
          try {
            utils.toChecksumAddress(contract.address);
          } catch(e) {
            self.logger.error(__("error deploying %s", contract.className));
            self.logger.error(e.message);
            contract.error = e.message;
            self.events.emit("deploy:contract:error", contract);
            return next(e.message);
          }
          contract.deployedAddress = contract.address;
          self.logger.info(contract.className.bold.cyan + __(" already deployed at ").green + contract.address.bold.cyan);
          self.events.emit("deploy:contract:deployed", contract);
          return next();
        }

        // TODO: this should be a plugin API instead, if not existing, it should by default deploy the contract
        self.events.request("deploy:contract:shouldDeploy", contract, function(trackedContract) {
          if (!trackedContract) {
            return self.contractToDeploy(contract, params, next);
          }

          self.blockchain.getCode(trackedContract.address, function(_getCodeErr, codeInChain) {
            if (codeInChain !== "0x") {
              self.contractAlreadyDeployed(contract, trackedContract, next);
            } else {
              self.contractToDeploy(contract, params, next);
            }
          });
        });
      }
    ], callback);
  }

  contractAlreadyDeployed(contract, trackedContract, callback) {
    const self = this;
    self.logger.info(contract.className.bold.cyan + __(" already deployed at ").green + trackedContract.address.bold.cyan);
    contract.deployedAddress = trackedContract.address;
    self.events.emit("deploy:contract:deployed", contract);

    // always run contractCode so other functionality like 'afterDeploy' can also work
    let codeGenerator = new CodeGenerator({contractsManager: self.contractsManager});
    let contractCode = codeGenerator.generateContractCode(contract, self.gasLimit);
    RunCode.doEval(contractCode, {web3: self.web3});

    return callback();
  }

  contractToDeploy(contract, params, callback) {
    const self = this;
    contract.realArgs = self.determineArguments(params || contract.args, contract);

    this.deployContract(contract, contract.realArgs, function (err, address) {
      if (err) {
        self.events.emit("deploy:contract:error", contract);
        return callback(new Error(err));
      }
      contract.address = address;
      self.events.emit("deploy:contract:deployed", contract);

      // always run contractCode so other functionality like 'afterDeploy' can also work
      let codeGenerator = new CodeGenerator({contractsManager: self.contractsManager});
      let contractCode = codeGenerator.generateContractCode(contract, self.gasLimit);
      RunCode.doEval(contractCode, {web3: self.web3});

      let onDeployPlugins = self.plugins.getPluginsProperty('onDeployActions', 'onDeployActions');

      async.eachLimit(onDeployPlugins, 1, function(plugin, nextEach) {
        plugin.call(plugin, contract, nextEach);
      }, () => {
        callback();
      });
    });
  }

  deployContract(contract, params, callback) {
    let self = this;
    let accounts = [];
    let contractParams = (params || contract.args).slice();
    let contractCode = contract.code;
    let deploymentAccount = self.blockchain.defaultAccount();
    let deployObject;

    async.waterfall([
      // TODO: can potentially go to a beforeDeploy plugin
      function getAccounts(next) {
        self.blockchain.getAccounts(function (err, _accounts) {
          if (err) {
            return next(new Error(err));
          }
          accounts = _accounts;

          // applying deployer account configuration, if any
          if (typeof contract.fromIndex == 'number') {
            deploymentAccount = accounts[contract.fromIndex];
            if (deploymentAccount === undefined) {
              return next(__("error deploying") + " " + contract.className + ": " + __("no account found at index") + " " + contract.fromIndex + __(" check the config"));
            }
          }
          if (typeof contract.from == 'string' && typeof contract.fromIndex != 'undefined') {
            self.logger.warn(__('Both "from" and "fromIndex" are defined for contract') + ' "' + contract.className + '". ' + __('Using "from" as deployer account.'));
          }
          if (typeof contract.from == 'string') {
            deploymentAccount = contract.from;
          }

          deploymentAccount = deploymentAccount || accounts[0];
          next();
        });
      },
      function doLinking(next) {
        self.events.request('contracts:list', (contracts) => {
          for (let contractObj of contracts) {
            let filename = contractObj.filename;
            let deployedAddress = contractObj.deployedAddress;
            if (deployedAddress) {
              deployedAddress = deployedAddress.substr(2);
            }
            let linkReference = '__' + filename + ":" + contractObj.className;
            if (contractCode.indexOf(linkReference) < 0) {
              continue;
            }
            if (linkReference.length > 40) {
              return next(new Error(__("{{linkReference}} is too long, try reducing the path of the contract ({{filename}}) and/or its name {{contractName}}", {linkReference: linkReference, filename: filename, contractName: contractObj.className})));
            }
            let toReplace = linkReference + "_".repeat(40 - linkReference.length);
            if (deployedAddress === undefined) {
              let libraryName = contractObj.className;
              return next(new Error(__("{{contractName}} needs {{libraryName}} but an address was not found, did you deploy it or configured an address?", {contractName: contract.className, libraryName: libraryName})));
            }
            contractCode = contractCode.replace(new RegExp(toReplace, "g"), deployedAddress);
          }
          // saving code changes back to contract object
          contract.code = contractCode;
          next();
        });
      },
      function applyBeforeDeploy(next) {
        let beforeDeployPlugins = self.plugins.getPluginsFor('beforeDeploy');

        //self.logger.info("applying beforeDeploy plugins...", beforeDeployPlugins.length);
        async.eachSeries(beforeDeployPlugins, (plugin, eachPluginCb) => {
          self.logger.info(__("running beforeDeploy plugin %s .", plugin.name));

          // calling each beforeDeploy handler declared by the plugin
          async.eachSeries(plugin.beforeDeploy, (beforeDeployFn, eachCb) => {
            function beforeDeployCb(resObj){
              contract.code = resObj.contractCode;
              eachCb();
            }
            beforeDeployFn({
              embarkDeploy:       self,
              pluginConfig:       plugin.pluginConfig,
              deploymentAccount:  deploymentAccount,
              contract:           contract,
              callback: beforeDeployCb
            }, beforeDeployCb);
          }, () => {
            //self.logger.info('All beforeDeploy handlers of the plugin has processed.');
            eachPluginCb();
          });
        }, () => {
          //self.logger.info('All beforeDeploy plugins has been processed.');
          contractCode = contract.code;
          next();
        });
      },
      function createDeployObject(next) {
        let contractObject = self.blockchain.ContractObject({abi: contract.abiDefinition});

        try {
          const dataCode = contractCode.startsWith('0x') ? contractCode : "0x" + contractCode;
          deployObject = self.blockchain.deployContractObject(contractObject, {arguments: contractParams, data: dataCode});
        } catch(e) {
          if (e.message.indexOf('Invalid number of parameters for "undefined"') >= 0) {
            return next(new Error(__("attempted to deploy %s without specifying parameters", contract.className)));
          } else {
            return next(new Error(e));
          }
        }
        next();
      },
      function estimateCorrectGas(next) {
        if (contract.gas === 'auto') {
          return deployObject.estimateGas().then((gasValue) => {
            contract.gas = gasValue;
            next();
          }).catch(next);
        }
        next();
      },
      function deployTheContract(next) {
        self.logger.info(__("deploying") + " " + contract.className.bold.cyan + " " + __("with").green + " " + contract.gas + " " + __("gas").green);

        self.blockchain.deployContractFromObject(deployObject, {
          from: deploymentAccount,
          gas: contract.gas,
          gasPrice: contract.gasPrice
        }, function(error, receipt) {
          if (error) {
            return next(new Error("error deploying =" + contract.className + "= due to error: " + error.message));
          }
          self.logger.info(contract.className.bold.cyan + " " + __("deployed at").green + " " + receipt.contractAddress.bold.cyan);
          contract.deployedAddress = receipt.contractAddress;
          contract.transactionHash = receipt.transactionHash;
          return next(null, receipt.contractAddress);
        });
      }
    ], callback);
  }

  deployAll(done) {
    let self = this;
    this.logger.info(__("deploying contracts"));
    this.events.emit("deploy:beforeAll");

    self.events.request('contracts:list', (contracts) => {
      async.eachOfSeries(contracts,
        function (contract, key, callback) {
          self.logger.trace(arguments);
          self.checkAndDeployContract(contract, null, callback);
        },
        function (err, _results) {
          if (err) {
            self.logger.error(__("error deploying contracts"));
            self.logger.error(err.message);
            self.logger.debug(err.stack);
          }
          if (contracts.length === 0) {
            self.logger.info(__("no contracts found"));
            return done();
          }
          self.logger.info(__("finished deploying contracts"));
          self.logger.trace(arguments);
          done(err);
        }
      );
    });

  }
}

module.exports = Deploy;
<|endoftext|>


<commit_before>/* global process, require */

var path = require('path');
var fs = require('fs');
var through = require('through2');
var handlebars = require('handlebars');

handlebars.registerHelper('inc', function (value) {
    return parseInt(value, 10) + 1;
});

var reporter = {
    /**
     * Returns reporter's output path or default file name relative to CWD
     * @param {string} outputPath
     * @returns {string}
     */
    getOutputPath: function (outputPath) {
        return path.relative(process.cwd(), outputPath || 'jscs-html-report.html');
    },

    /**
     * Returns relative path from output path to reporter
     * @param {string} outputPath
     * @returns {string}
     */
    getRelativePath: function (outputPath) {
        return path.relative(path.dirname(outputPath), __dirname);
    },

    /**
     * Returns transformed array of errors
     * @param {Array} errors
     * @param {boolean} isOutputPathSet
     * @returns {Array}
     */
    processErrors: function (errors, isOutputPathSet) {
        return errors.getErrorList().map(function (error) {
            return {
                message: error.message,
                line: error.line,
                column: error.column,
                reason: errors.explainError(error),
                fileName: path.relative(isOutputPathSet ? __dirname : process.cwd(), errors.getFilename()),
            };
        });
    },

    /**
     * Compiles handlebars template
     * @param {Object} context
     * @returns {string}
     */
    compileTemplate: function (context) {
        var template = fs.readFileSync(path.join(__dirname, 'template.hbs'), 'utf-8');

        return handlebars.compile(template)(context);
    },

    /**
     * Saves report to an output path
     * @param {Object} data
     * @param {string} outputPath
     * @param {boolean} [isGrunt]
     */
    saveReport: function (data, outputPath, isGrunt) {
        var html = this.compileTemplate(data);

        if (isGrunt) {
            process.stdout.write(html);

            return;
        }

        fs.writeFileSync(outputPath, html);

        console.log('*** JSCS report saved to %s\n', outputPath);
    }
};

/**
 * JSCS Gulp reporter
 * @param {Object} [options]
 * @returns {*}
 */
function jscsGulpReporter(options) {
    var options = options || {};
    var outputPath = reporter.getOutputPath(options.reporterOutput);
    var relativeReporterPath = reporter.getRelativePath(outputPath);
    var failedFiles = null;
    var errorsCollection;

    return through.obj(function (file, enc, callback) {
        if (file.jscs && !file.jscs.success) {
            (failedFiles = failedFiles || []).push(file.path);

            errorsCollection = (errorsCollection || []).concat(reporter.processErrors(file.jscs.errors, Boolean(options.reporterOutput)));
        }

        callback(null, file);
    }, function (callback) {
        if (failedFiles) {
            reporter.saveReport({errorsCollection: errorsCollection, relativeReporterPath: relativeReporterPath}, outputPath);
        }

        callback();
    });
}

/**
 * JSCS reporter
 * @param {Array} files
 */
function jscsReporter(files) {
    // For grunt-jscs we need `this.options`, for node-jscs - `this`
    var options = this.options || this;
    var isGrunt = Boolean(this.options);
    var outputPath = reporter.getOutputPath(options.reporterOutput);
    var relativeReporterPath = reporter.getRelativePath(outputPath);

    function generateReport() {
        var errorsCollection = [];

        files.forEach(function (errors) {
            if (!errors.isEmpty()) {
                errorsCollection = errorsCollection.concat(reporter.processErrors(errors, Boolean(options.reporterOutput)));
            }
        });

        reporter.saveReport({errorsCollection: errorsCollection, relativeReporterPath: relativeReporterPath}, outputPath, isGrunt);
    }

    generateReport();
}

module.exports = jscsReporter;

// Expose path to reporter so it can be configured in grunt-jscs task
module.exports.path = __dirname;

module.exports.gulpReporter = jscsGulpReporter;
<commit_msg>correct relative file path; exit process if `reporterOutput` is not specified in Grunt task<commit_after>/* global process, require */

var path = require('path');
var fs = require('fs');
var through = require('through2');
var handlebars = require('handlebars');

handlebars.registerHelper('inc', function (value) {
    return parseInt(value, 10) + 1;
});

var reporter = {
    /**
     * Returns reporter's output path or default file name relative to CWD
     * @param {string} outputPath
     * @returns {string}
     */
    getOutputPath: function (outputPath) {
        return path.relative(process.cwd(), outputPath || 'jscs-html-report.html');
    },

    /**
     * Returns relative path from output path to reporter
     * @param {string} outputPath
     * @returns {string}
     */
    getRelativePath: function (outputPath) {
        return path.relative(path.dirname(outputPath), __dirname);
    },

    /**
     * Returns transformed array of errors
     * @param {Array} errors
     * @param {string} outputDir
     * @returns {Array}
     */
    processErrors: function (errors, outputDir) {
        return errors.getErrorList().map(function (error) {
            return {
                message: error.message,
                line: error.line,
                column: error.column,
                reason: errors.explainError(error),
                fileName: path.relative(outputDir, errors.getFilename())
            };
        });
    },

    /**
     * Compiles handlebars template
     * @param {Object} context
     * @returns {string}
     */
    compileTemplate: function (context) {
        var template = fs.readFileSync(path.join(__dirname, 'template.hbs'), 'utf-8');

        return handlebars.compile(template)(context);
    },

    /**
     * Saves report to an output path
     * @param {Object} data
     * @param {string} outputPath
     * @param {boolean} [isGrunt]
     */
    saveReport: function (data, outputPath, isGrunt) {
        var html = this.compileTemplate(data);

        if (isGrunt) {
            process.stdout.write(html);

            return;
        }

        fs.writeFileSync(outputPath, html);

        console.log('*** JSCS report saved to %s\n', outputPath);
    }
};

/**
 * JSCS Gulp reporter
 * @param {Object} [options]
 * @returns {*}
 */
function jscsGulpReporter(options) {
    var options = options || {};
    var outputPath = reporter.getOutputPath(options.reporterOutput);
    var relativeReporterPath = reporter.getRelativePath(outputPath);
    var failedFiles = null;
    var errorsCollection;

    return through.obj(function (file, enc, callback) {
        if (file.jscs && !file.jscs.success) {
            (failedFiles = failedFiles || []).push(file.path);

            errorsCollection = (errorsCollection || []).concat(reporter.processErrors(file.jscs.errors, path.dirname(outputPath)));
        }

        callback(null, file);
    }, function (callback) {
        if (failedFiles) {
            reporter.saveReport({errorsCollection: errorsCollection, relativeReporterPath: relativeReporterPath}, outputPath);
        }

        callback();
    });
}

/**
 * JSCS reporter
 * @param {Array} files
 */
function jscsReporter(files) {
    // For grunt-jscs we need `this.options`, for node-jscs - `this`
    var options = this.options || this;
    var isGrunt = Boolean(this.options);
    var outputPath = reporter.getOutputPath(options.reporterOutput);
    var relativeReporterPath = reporter.getRelativePath(outputPath);

    if (isGrunt && !options.reporterOutput) {
        console.error(new Error('JSCS HTML reporter `reporterOutput` path not specified in grunt task!\n'));

        process.exit(1);
    }

    function generateReport() {
        var errorsCollection = [];

        files.forEach(function (errors) {
            if (!errors.isEmpty()) {
                errorsCollection = errorsCollection.concat(reporter.processErrors(errors, path.dirname(outputPath)));
            }
        });

        reporter.saveReport({errorsCollection: errorsCollection, relativeReporterPath: relativeReporterPath}, outputPath, isGrunt);
    }

    generateReport();
}

module.exports = jscsReporter;

// Expose path to reporter so it can be configured in grunt-jscs task
module.exports.path = __dirname;

module.exports.gulpReporter = jscsGulpReporter;
<|endoftext|>


<commit_before>'use strict';

const assert = require('assert');
const pathUtil = require('path');
const fs = require('mz/fs');
const yieldCache = require('yield-cache');

const is = require('is-type-of');
const RouteInfo = require('plover-util/lib/route-info');

const invoker = require('../util/invoker');
const RenderHelper = require('./render-helper');
const HelperContainer = require('./helper-container');

const logger = require('plover-logger')('plover:core/view-render');

class ViewRender {

  /**
   * 用于执行视图渲染
   * 一个ViewRender对应于一次请求
   *
   * @param {PloverApplication} app - Plover应用对象
   * @param {Navigator} navigator   - Navigator对象
   */
  constructor(app, navigator) {
    this.app = app;
    this.navigator = navigator;

    this.moduleResolver = app.moduleResolver;
    this.development = app.settings.development;

    this.engines = app.engines;
    this.helpers = app.helpers;
    this.filters = navigator.filters;

    // 前端资源配置
    this.assetsSettings = app.settings.assets || {};
  }

  /**
   * 渲染模块
   *
   * @param {RenderData}    rd      - 渲染上下文对象
   * @param {ActionContext} ctx     - 控制器执行上下文
   * @param {Boolean}       incept  - 是否执行过滤器，即beforeRender & afterRender
   *                                  渲染control时不执行过滤器
   * @return {RenderResult}         - 渲染结果
   */
  * render(rd, ctx, incept) {
    logger.debug('render: %s', rd.view);

    this.development && vertify(rd);

    const view = resolveView(this, rd, rd.view);
    if (!view) {
      logger.error('view not found: %s', rd.view);
      return RenderHelper.notFound(rd.view, this.development);
    }

    logger.debug('view resolved: %o', view);

    // 依赖，Promise对象数组
    rd.depends = [];
    // 前端资源
    rd.assets = rd.assets || {};
    // 帮助方法
    rd.helpers = new HelperContainer(rd, this, this.navigator, this.app);

    if (ctx) {
      // 控制器中可以通过$取得渲染帮助方法
      ctx.$ = rd.helpers;
    }

    return yield* render(this, rd, view, ctx, incept);
  }

  /**
   * 异步渲染
   *
   * @param {Object}  rd    - 当前模块RunData
   * @param {Promise} defer - 异步渲染Promise对象
   * @param {String}  url   - 可选，仅用于调试，用于not found时输出信息
   * @return {String}       - 结果占位符
   */
  renderAsync(rd, defer, url) {
    return RenderHelper.renderAsync(rd, defer, url, this.development);
  }
}

module.exports = ViewRender;

/*
 * 验证RunData完整性，因为参数比较多可能搞错
 */
function vertify(rd) {
  const fields = ['info', 'route', 'view', 'data', 'ctx'];
  for (const name of fields) {
    assert(rd[name], 'rd.' + name + ' not specified');
  }
}

/*
 * 具体的渲染流程
 */
function* render(self, rd, view, ctx, incept) { // eslint-disable-line
  // beforeRender
  if (incept) {
    const ret = yield* beforeRender(self, rd, ctx);
    if (ret === false) {
      return ctx.body !== undefined && ctx.body !== null ?
          { content: ctx.body } : null;
    }
  }

  // 渲染内容
  let content = yield* renderContent(self, rd, view);

  // afterRender
  if (incept) {
    ctx.content = content;
    yield* afterRender(self, rd, ctx);
    content = ctx.content;
  }

  // 内部调用需要处理assets
  rd.route.navigate && tryTransformAssets(rd);

  return { content: content, assets: rd.assets };
}

ViewRender.TEMPLATE_TIMEOUT = 3000;

/**
 * 渲染内容
 */
const renderCache = yieldCache();
function* renderContent(self, rd, view) {
  const context = createViewContext(self.app, rd);
  const path = pathUtil.join(view.root, view.template);

  // 开发状态3秒缓存失效
  self.development && setTimeout(function() {
    renderCache.remove(path);
  }, ViewRender.TEMPLATE_TIMEOUT);

  // 渲染器
  const fn = yield* renderCache(path, function() {
    return getRender(self, path);
  });

  logger.debug('render template: %s', path);

  // 调用渲染器
  let content = fn(context);

  // 添加View对应的前端资源
  attachAssets(self, rd, view);

  // 渲染子View
  content = yield* RenderHelper.renderChildren(rd, content);

  logger.debug('render template success: %s', path);

  return content;
}

/*
 * 解析View
 */
function resolveView(self, rd, url) {
  const viewRoute = RouteInfo.parse(rd.route, url);

  // 本模块view，直接从info取得
  if (rd.route.module === viewRoute.module) {
    return regularView(rd.info, rd.info.views[viewRoute.action]);
  }

  // 其他模块view
  const info = self.moduleResolver.resolve(viewRoute.module);
  return info && regularView(info, info.views[viewRoute.action]);
}

/*
 * 规范化View对象
 */
function regularView(info, view) {
  if (!view) {
    return null;
  }
  // 本来应该产生一个新的对象的
  // 但是它调用很频繁，所以就直接设置属性了
  view.root = info.path;
  return view;
}

/*
 * 请求和编译模板
 *
 * @param {String} path
 * @return {Promise}
 */
function getRender(self, path) {
  logger.debug('get render: %s', path);

  const ext = pathUtil.extname(path).substr(1); // remove prefix .
  const engine = self.engines[ext];
  if (!engine) {
    const e = new Error('render engine not exists: ' + ext);
    return Promise.reject(e);
  }

  return fs.readFile(path, 'utf-8').then(tpl => {
    const opts = { development: self.development, path: path };
    const fn = engine.compile(tpl, opts);
    logger.debug('comple template success: %s', path);
    return fn;
  });
}

/*
 * 创建模板上下文
 */
function createViewContext(app, rd) {
  // 直接重用helper container对象减少对象的构造
  const ctx = rd.helpers;

  ctx.$ = rd.helpers;
  ctx.self = rd.data;
  ctx.json = JSON.stringify;

  ctx.query = rd.route.query;
  ctx.route = rd.route;
  ctx.settings = app.settings;

  Object.assign(ctx, rd.data);
  return ctx;
}

/*
 * 执行beforeRender过滤器
 */
function* beforeRender(self, rd, ctx) {
  const ret = yield* invoker.filter(self.filters, 'beforeRender', ctx);
  if (ret === false) {
    return false;
  }

  const fn = rd.module.beforeRender;
  if (fn) {
    return is.generatorFunction(fn) ?
        yield* fn.call(ctx) : fn.call(ctx);
  }

  return null;
}

/*
 * 执行afterRender过滤器
 */
function* afterRender(self, rd, ctx) {
  const fn = rd.module.afterRender;
  if (fn) {
    const ret = is.generatorFunction(fn) ?
        yield* fn.call(ctx) : fn.call(ctx);
    if (ret === false) {
      return false;
    }
  }

  return yield* invoker.filter(self.filters, 'afterRender', ctx, true);
}

/*
 * 将view相关的前端资源添加到上下文中
 * 使用的是assets helper
 * 可以通过设置`assets.disableAutowire=false`关闭，默认开启
 */
function attachAssets(self, rd, view) {
  const settings = self.assetsSettings;
  if (settings.disableAutowire) {
    return;
  }

  const route = rd.route;
  const type = route.type === 'layout' ? 'layout' : 'default';
  const bag = rd.assets[type] ||
      (rd.assets[type] = { css: [], js: [] });

  view.css && bag.css.push({
    route: RouteInfo.parse(route, view.css)
  });

  view.js && bag.js.push({
    route: RouteInfo.parse(route, view.js)
  });
}

function tryTransformAssets(rd) {
  const helper = rd.helpers.assets;
  if (helper && typeof helper.transform === 'function') {
    logger.debug('try transform assets');
    helper.transform(rd.assets);
  }
}

<commit_msg>refactor: rename param<commit_after>'use strict';

const assert = require('assert');
const pathUtil = require('path');
const fs = require('mz/fs');
const yieldCache = require('yield-cache');

const is = require('is-type-of');
const RouteInfo = require('plover-util/lib/route-info');

const invoker = require('../util/invoker');
const RenderHelper = require('./render-helper');
const HelperContainer = require('./helper-container');

const logger = require('plover-logger')('plover:core/view-render');

class ViewRender {

  /**
   * 用于执行视图渲染
   * 一个ViewRender对应于一次请求
   *
   * @param {PloverApplication} app - Plover应用对象
   * @param {Navigator} navigator   - Navigator对象
   */
  constructor(app, navigator) {
    this.app = app;
    this.navigator = navigator;

    this.moduleResolver = app.moduleResolver;
    this.development = app.settings.development;

    this.engines = app.engines;
    this.helpers = app.helpers;
    this.filters = navigator.filters;

    // 前端资源配置
    this.assetsSettings = app.settings.assets || {};
  }

  /**
   * 渲染模块
   *
   * @param {RenderData}    rd      - 渲染上下文对象
   * @param {ActionContext} ctx     - 控制器执行上下文
   * @param {Boolean}       incept  - 是否执行过滤器，即beforeRender & afterRender
   *                                  渲染control时不执行过滤器
   * @return {RenderResult}         - 渲染结果
   */
  * render(rd, ctx, incept) {
    logger.debug('render: %s', rd.view);

    this.development && vertify(rd);

    const view = resolveView(this, rd, rd.view);
    if (!view) {
      logger.error('view not found: %s', rd.view);
      return RenderHelper.notFound(rd.view, this.development);
    }

    logger.debug('view resolved: %o', view);

    // 依赖，Promise对象数组
    rd.depends = [];
    // 前端资源
    rd.assets = rd.assets || {};
    // 帮助方法
    rd.helpers = new HelperContainer(rd, this, this.navigator, this.app);

    if (ctx) {
      // 控制器中可以通过$取得渲染帮助方法
      ctx.$ = rd.helpers;
    }

    return yield* render(this, rd, view, ctx, incept);
  }

  /**
   * 异步渲染
   *
   * @param {Object}  rd    - 当前模块RunData
   * @param {Promise} defer - 异步渲染Promise对象
   * @param {String}  url   - 可选，仅用于调试，用于not found时输出信息
   * @return {String}       - 结果占位符
   */
  renderAsync(rd, defer, url) {
    return RenderHelper.renderAsync(rd, defer, url, this.development);
  }
}

module.exports = ViewRender;

/*
 * 验证RunData完整性，因为参数比较多可能搞错
 */
function vertify(rd) {
  const fields = ['info', 'route', 'view', 'data', 'ctx'];
  for (const name of fields) {
    assert(rd[name], 'rd.' + name + ' not specified');
  }
}

/*
 * 具体的渲染流程
 */
function* render(self, rd, view, ctx, incept) { // eslint-disable-line
  // beforeRender
  if (incept) {
    const ret = yield* beforeRender(self, rd, ctx);
    if (ret === false) {
      return ctx.body !== undefined && ctx.body !== null ?
          { content: ctx.body } : null;
    }
  }

  // 渲染内容
  let content = yield* renderContent(self, rd, view);

  // afterRender
  if (incept) {
    ctx.content = content;
    yield* afterRender(self, rd, ctx);
    content = ctx.content;
  }

  // 内部调用需要处理assets
  rd.route.navigate && tryTransformAssets(rd);

  return { content: content, assets: rd.assets };
}

ViewRender.TEMPLATE_TIMEOUT = 3000;

/**
 * 渲染内容
 */
const renderCache = yieldCache();
function* renderContent(self, rd, view) {
  const context = createViewContext(self.app, rd);
  const path = pathUtil.join(view.root, view.template);

  // 开发状态3秒缓存失效
  self.development && setTimeout(function() {
    renderCache.remove(path);
  }, ViewRender.TEMPLATE_TIMEOUT);

  // 渲染器
  const fn = yield* renderCache(path, function() {
    return getRender(self, path);
  });

  logger.debug('render template: %s', path);

  // 调用渲染器
  let content = fn(context);

  // 添加View对应的前端资源
  attachAssets(self, rd, view);

  // 渲染子View
  content = yield* RenderHelper.renderChildren(rd, content);

  logger.debug('render template success: %s', path);

  return content;
}

/*
 * 解析View
 */
function resolveView(self, rd, view) {
  const viewRoute = RouteInfo.parse(rd.route, view);

  // 本模块view，直接从info取得
  if (rd.route.module === viewRoute.module) {
    return regularView(rd.info, rd.info.views[viewRoute.action]);
  }

  // 其他模块view
  const info = self.moduleResolver.resolve(viewRoute.module);
  return info && regularView(info, info.views[viewRoute.action]);
}

/*
 * 规范化View对象
 */
function regularView(info, view) {
  if (!view) {
    return null;
  }
  // 本来应该产生一个新的对象的
  // 但是它调用很频繁，所以就直接设置属性了
  view.root = info.path;
  return view;
}

/*
 * 请求和编译模板
 *
 * @param {String} path
 * @return {Promise}
 */
function getRender(self, path) {
  logger.debug('get render: %s', path);

  const ext = pathUtil.extname(path).substr(1); // remove prefix .
  const engine = self.engines[ext];
  if (!engine) {
    const e = new Error('render engine not exists: ' + ext);
    return Promise.reject(e);
  }

  return fs.readFile(path, 'utf-8').then(tpl => {
    const opts = { development: self.development, path: path };
    const fn = engine.compile(tpl, opts);
    logger.debug('comple template success: %s', path);
    return fn;
  });
}

/*
 * 创建模板上下文
 */
function createViewContext(app, rd) {
  // 直接重用helper container对象减少对象的构造
  const ctx = rd.helpers;

  ctx.$ = rd.helpers;
  ctx.self = rd.data;
  ctx.json = JSON.stringify;

  ctx.query = rd.route.query;
  ctx.route = rd.route;
  ctx.settings = app.settings;

  Object.assign(ctx, rd.data);
  return ctx;
}

/*
 * 执行beforeRender过滤器
 */
function* beforeRender(self, rd, ctx) {
  const ret = yield* invoker.filter(self.filters, 'beforeRender', ctx);
  if (ret === false) {
    return false;
  }

  const fn = rd.module.beforeRender;
  if (fn) {
    return is.generatorFunction(fn) ?
        yield* fn.call(ctx) : fn.call(ctx);
  }

  return null;
}

/*
 * 执行afterRender过滤器
 */
function* afterRender(self, rd, ctx) {
  const fn = rd.module.afterRender;
  if (fn) {
    const ret = is.generatorFunction(fn) ?
        yield* fn.call(ctx) : fn.call(ctx);
    if (ret === false) {
      return false;
    }
  }

  return yield* invoker.filter(self.filters, 'afterRender', ctx, true);
}

/*
 * 将view相关的前端资源添加到上下文中
 * 使用的是assets helper
 * 可以通过设置`assets.disableAutowire=false`关闭，默认开启
 */
function attachAssets(self, rd, view) {
  const settings = self.assetsSettings;
  if (settings.disableAutowire) {
    return;
  }

  const route = rd.route;
  const type = route.type === 'layout' ? 'layout' : 'default';
  const bag = rd.assets[type] ||
      (rd.assets[type] = { css: [], js: [] });

  view.css && bag.css.push({
    route: RouteInfo.parse(route, view.css)
  });

  view.js && bag.js.push({
    route: RouteInfo.parse(route, view.js)
  });
}

function tryTransformAssets(rd) {
  const helper = rd.helpers.assets;
  if (helper && typeof helper.transform === 'function') {
    logger.debug('try transform assets');
    helper.transform(rd.assets);
  }
}

<|endoftext|>


<commit_before>/*
 * cushion-cli
 * https://github.com/stefanjudis/cushion-cli
 *
 * Copyright (c) 2012 stefan judis
 * Licensed under the MIT license.
 */

var databaseCommands = module.exports = {},
    databaseCallbacks = require('./databaseCallbacks'),
    cHelper = require('./helper/helper');

/**
 * [command description]
 * @param  {[type]} typedInput [description]
 * @param  {[type]} cli        [description]
 */
databaseCommands.command = function(input, cli) {
  var args = input.split(' '),
      command = args[0];

  databaseCommands['_' + command](args, cli);

};

/**
 * [commandExists description]
 * @param  {[type]} input [description]
 * @return {[type]}       [description]
 */
databaseCommands.commandExists = function(input) {
  var command = input.split(' ')[0],
      _return;

  if(this['_' + command] !== undefined) {
    _return = true;
  } else {
    _return = false;
  }

  return _return;
};

/**
 * [_connection description]
 * @param   {[type]} input [description]
 * @param   {[type]} cli   [description]
 * @private
 */
databaseCommands._connection = function(input, cli) {
  cli.db = undefined;
  console.log('Switched to connection level.');

  cli.runner = cli.handleConnectionCommands;
  cli.handleConnectionCommands();
};

/**
 * [_allDocuments description]
 * @param  {[type]} input [description]
 * @param  {[type]} cli   [description]
 * @private
 */
databaseCommands._allDocuments = function(input, cli) {
  var args = input.slice(1, input.length),
      argsLength = args.length,
      paramsObject = {},
      paramsValid = true;

  if (argsLength > 0) {
    // @zoddy wants to have an object instead an array - let's transform
    args.forEach(function(value) {
      console.log(value);
      // check for valid input
      if (value.match(/^.*[\=].*$/) !== null) {
        value = value.split('=');

        // set object and avoid "invalid UTF-8 JSON" errors
        paramsObject[value[0]] = value[1].replace(/'/g, '"');
      } else {
        paramsValid = false;
      }
    });

    // make call or show message for invalid params
    if (paramsValid) {
      cli.db['allDocuments'](paramsObject, databaseCallbacks['allDocuments']);
    } else {
      console.log('There was invalid parameter input');
      console.log('Look for help with:\n');
      console.log('    $ help allDocuments');

      cli.handleDatabaseCommands();
    }
  } else {
    cli.db['allDocuments'](databaseCallbacks['allDocuments']);
  }
};

/**
 * [_simpleCommand description]
 * @param   {[type]} command [description]
 * @param   {[type]} cli     [description]
 * @private
 */
databaseCommands._simpleCommand = function(input, cli) {
  var command = input[0];

  cli.db[command](databaseCallbacks[command]);
};

/**
 * [_help description]
 * @param   {[type]} input [description]
 * @param   {[type]} cli   [description]
 * @private
 */
databaseCommands._help = function(input, cli) {
  cHelper.getHelp(this, input, cli);
};

databaseCommands._exists =
databaseCommands._create =
databaseCommands._destroy =
databaseCommands._info = databaseCommands._simpleCommand;<commit_msg>refactoring of allDocs function and implementing view function at database level<commit_after>/*
 * cushion-cli
 * https://github.com/stefanjudis/cushion-cli
 *
 * Copyright (c) 2012 stefan judis
 * Licensed under the MIT license.
 */

var databaseCommands = module.exports = {},
    databaseCallbacks = require('./databaseCallbacks'),
    cHelper = require('./helper/helper');

/**
 * [command description]
 * @param  {[type]} typedInput [description]
 * @param  {[type]} cli        [description]
 */
databaseCommands.command = function(input, cli) {
  var args = input.split(' '),
      command = args[0];

  databaseCommands['_' + command](args, cli);

};

/**
 * [commandExists description]
 * @param  {[type]} input [description]
 * @return {[type]}       [description]
 */
databaseCommands.commandExists = function(input) {
  var command = input.split(' ')[0],
      _return;

  if(this['_' + command] !== undefined) {
    _return = true;
  } else {
    _return = false;
  }

  return _return;
};

/**
 * [_connection description]
 * @param   {[type]} input [description]
 * @param   {[type]} cli   [description]
 * @private
 */
databaseCommands._connection = function(input, cli) {
  cli.db = undefined;
  console.log('Switched to connection level.');

  cli.runner = cli.handleConnectionCommands;
  cli.handleConnectionCommands();
};

/**
 * [_allDocuments description]
 * @param  {[type]} input [description]
 * @param  {[type]} cli   [description]
 * @private
 */
databaseCommands._allDocuments = function(input, cli) {
  var args = input.slice(1, input.length),
      argsLength = args.length,
      paramsObject;

  if (argsLength > 0) {
    // @zoddy wants to have an object instead an array - let's transform
    paramsObject = this._createParamsObject(args);

    // make call or show message for invalid params
    if (paramsObject !== undefined) {
      cli.db['allDocuments'](paramsObject, databaseCallbacks['allDocuments']);
    } else {
      console.log('There was invalid parameter input');
      console.log('Look for help with:\n');
      console.log('    $ help allDocuments');

      cli.handleDatabaseCommands();
    }
  } else {
    cli.db['allDocuments'](databaseCallbacks['allDocuments']);
  }
};

/**
 * [_view description]
 * @param  {[type]} input [description]
 * @param  {[type]} cli   [description]
 * @private
 */
databaseCommands._view = function(input, cli) {
  var design = input[1],
      view = input[2],
      args = input.slice(1, 3),
      argsLength = args.length,
      params = input.slice(3, input.length),
      paramsObject;

  // check query params for view
  if (argsLength > 1) {
    paramsObject = this._createParamsObject(params);

    if (paramsObject !== undefined) {
      args.push(paramsObject, databaseCallbacks['view']);
      cli.db.view.apply(cli.db, args);
    } else {
      console.log('There was invalid parameter input');
      console.log('Look for help with:\n');
      console.log('    $ help view');

      cli.handleDatabaseCommands();
    }

  } else {
    console.log(
     'Please, use the \'view\' command with 2 or more arguments.\n' +
     'Look for help with:\n' +
     '    $ help view'
    );

    cli.handleDatabaseCommands();
  }
};

/**
 * [_createParamsObject description]
 * @param  {[type]} paramsArray [description]
 * @return {[type]}             [description]
 */
databaseCommands._createParamsObject = function(paramsArray) {
  paramsObject = {};

  paramsArray.forEach(function(value) {
    // check for valid input
    if (value.match(/^.*[\=].*$/) !== null) {
      value = value.split('=');

      // set object and avoid "invalid UTF-8 JSON" errors
      paramsObject[value[0]] = value[1].replace(/'/g, '"');
    } else {
      paramsObject = undefined;
      return;
    }
  });

  return paramsObject;
};

/**
 * [_simpleCommand description]
 * @param   {[type]} command [description]
 * @param   {[type]} cli     [description]
 * @private
 */
databaseCommands._simpleCommand = function(input, cli) {
  var command = input[0];

  cli.db[command](databaseCallbacks[command]);
};

/**
 * [_help description]
 * @param   {[type]} input [description]
 * @param   {[type]} cli   [description]
 * @private
 */
databaseCommands._help = function(input, cli) {
  cHelper.getHelp(this, input, cli);
};

databaseCommands._exists =
databaseCommands._create =
databaseCommands._destroy =
databaseCommands._info = databaseCommands._simpleCommand;<|endoftext|>


<commit_before>'use strict'

module.exports = {
  json: {
    pretty: false
  },
  logger: {
    enabled: true,
    format: 'common'
  },
  public: {
    gzip: true,
    maxage: 31536000
  }
}
<commit_msg>Update default maxage to use millis per koa-static<commit_after>'use strict'

module.exports = {
  json: {
    pretty: false
  },
  logger: {
    enabled: true,
    format: 'common'
  },
  public: {
    gzip: true,
    maxage: 31536000 * 1000
  }
}
<|endoftext|>


<commit_before>//TODO check try statement and its influence on the scope
var walk = require("acorn/dist/walk");
var path = require("path");

function formPathForScope(fileName, data) {
    return fileName + "_" + data.start + "_" + data.end;
}

function getFilePathName(fileName) {
    var index = fileName.indexOf("node_modules");
    if (index > -1) {
        var filePath = path.normalize(fileName);
        var pathRes = filePath.split("/");
        //console.error("File path name = ", pathRes.slice(2).join("/"));
        return pathRes.slice(2).join("/");
    } else {
        //console.error("File path name = ", fileName);
        return fileName;
    }
}

function resolveScopeCountPath(scope) {
    var scopeCountRes = scopeCountResolver[scope];
    if (scopeCountRes === undefined) {
        scopeCountResolver[scope] = 1;
        return scope;
    } else {
        scopeCountResolver[scope] = scopeCountRes + 1;
        return scope + "_" + scopeCountRes;
    }
}

var pathMap = [];

var resolvedFiles = [];

var currentScope;
var scopeCountResolver = [];

var pathVisitor = walk.make({
    //Processing of object.defineProperty
    CallExpression: function(node, scopeInfo, c) {
        var fileName = node.sourceFile.name;
        if (node.callee.type == 'MemberExpression' &&
            node.callee.object.name == 'Object' && node.callee.property.name == 'defineProperty') {
            var obj = node.arguments[0];
            var property = node.arguments[1];
            var newScope = scopeInfo.scope + "_obj_def_prop_";

            if (obj.type == 'Identifier') {
                newScope = newScope + "_" + obj.name;
            }

            if (property.type == 'Literal') {
                newScope = newScope + "_" + property.value
            }

            var key = formPathForScope(fileName, property);
            pathMap[key] = resolveScopeCountPath(newScope);
        };
        c(node.callee, scopeInfo);
        for (var i = 0; i < node.arguments.length; ++i) {
            c(node.arguments[i], scopeInfo);
        };

    },

    //handling of FunctionDeclaration and FunctionExpression
    Function: function(node, scopeInfo, c) {
        // if (scopeInfo.search != undefined && (node.start > scopeInfo.search.start || node.end < scopeInfo.search.end)) {
        //     return;
        // }
        var newScope = scopeInfo.scope + "_fn_";
        var fileName = node.sourceFile.name;
        if (node.id) {
            var key = formPathForScope(fileName, node.id);
            newScope = resolveScopeCountPath(newScope + node.id.name);
            pathMap[key] = newScope;
            c(node.id, {
                scope: newScope,
                search: scopeInfo.search
            });
        } else {
            newScope = resolveScopeCountPath(newScope);
        }

        for (var i = 0; i < node.params.length; ++i) {
            var key = formPathForScope(fileName, node.params[i]);
            var paramScope = resolveScopeCountPath(newScope + "_param_" + node.params[i].name);
            pathMap[key] = paramScope;
            c(node.params[i], {
                scope: paramScope,
                search: scopeInfo.search
            });
        }

        c(node.body, {
            scope: newScope,
            search: scopeInfo.search
        });
    },

    VariableDeclaration: function(node, scopeInfo, c) {
        // if (scopeInfo.search != undefined && (node.start > scopeInfo.search.start || node.end < scopeInfo.search.end)) {
        //     return;
        // }
        var fileName = node.sourceFile.name;
        for (var i = 0; i < node.declarations.length; ++i) {
            var decl = node.declarations[i];

            var key = formPathForScope(fileName, decl.id);
            var newScope = resolveScopeCountPath(scopeInfo.scope + "_var_" + decl.id.name);
            pathMap[key] = newScope;
            c(decl.id, {
                scope: newScope,
                search: scopeInfo.search
            });
            if (decl.init) c(decl.init, {
                scope: newScope,
                search: scopeInfo.search
            });
        }
    },

    // check what happens with this
    MemberExpression: function(node, scopeInfo, c) {
        // if (scopeInfo.search != undefined && (node.start > scopeInfo.search.start || node.end < scopeInfo.search.end)) {
        //     return;
        // }
        currentScope = scopeInfo.scope;
        var fileName = node.sourceFile.name;
        var newScope = scopeInfo.scope;
        if (node.object.type == 'Identifier') {
            newScope = resolveScopeCountPath(newScope + "_obj_" + node.object.name);
            var keyObj = formPathForScope(fileName, node.object);
            pathMap[keyObj] = newScope;
            c(node.object, {
                scope: newScope,
                search: scopeInfo.search
            });
        } else {
            c(node.object, {
                scope: newScope,
                search: scopeInfo.search
            });
            newScope = currentScope;
        }

        if (node.property.type == 'Identifier') {
            newScope = resolveScopeCountPath(newScope + "_prop_" + node.property.name);
            keyProp = formPathForScope(fileName, node.property);
            pathMap[keyProp] = newScope;
        }
        c(node.property, {
            scope: newScope,
            search: scopeInfo.search
        });

        currentScope = newScope;
    },

    ObjectExpression: function(node, scopeInfo, c) {
        // if (scopeInfo.search != undefined && (node.start > scopeInfo.search.start || node.end < scopeInfo.search.end)) {
        //     return;
        // }
        var fileName = node.sourceFile.name;
        var newScope = scopeInfo.scope + "_obj_";
        for (var i = 0; i < node.properties.length; ++i) {
            if (node.objType !== undefined && node.objType.name) {
                newScope = newScope + "_objType_" + node.objType.name;
            }

            if (node.properties[i].key.type == 'Identifier') {
                var key_key = formPathForScope(fileName, node.properties[i].key);
                newScope = resolveScopeCountPath(newScope + "_obj_key_" + node.properties[i].key.name);
                pathMap[key_key] = newScope;
            }
            c(node.properties[i].key, {
                scope: newScope,
                search: scopeInfo.search
            });

            if (node.properties[i].value.type == 'Identifier') {
                var key_val = formPathForScope(fileName, node.properties[i].value);
                newScope = resolveScopeCountPath(newScope + "_obj_val_" + node.properties[i].value.name);
                pathMap[key_val] = newScope;
            }
            c(node.properties[i].value, {
                scope: newScope,
                search: scopeInfo.search
            });
        }
    },

    Identifier: function(node, scopeInfo, c) {
        if (scopeInfo.search != undefined && node.start == scopeInfo.search.start && node.end == scopeInfo.search.end) {
            throw {
                found: scopeInfo.scope
            };
        }
    }
});

module.exports.initLocalFilesScopePaths = function(ternServer, localFiles) {
    resolvedFiles = localFiles;
    scopeCountResolver = [];
    ternServer.files.forEach(function(file) {
        if (localFiles.indexOf(file.name) > -1) {
            walk.recursive(file.ast, {
                scope: getFilePathName(file.name)
            }, null, pathVisitor);
        }
    });

    // console.error(pathMap);
}

module.exports.mapLinesPathToScopePath = function(ternServer, defInfo) {
    var key = formPathForScope(defInfo.file, {
        start: defInfo.start,
        end: defInfo.end
    });
    var mapRes = pathMap[key];
    //if value was found in the map or file is not external, so was fully indexed
    if (mapRes != undefined || resolvedFiles.indexOf(defInfo.file) > -1) {
        return mapRes;
    }

    var lookupRes;

    scopeCountResolver = [];
    ternServer.files.forEach(function(file) {
        if (file.name === defInfo.file) {
            try {
                walk.recursive(file.ast, {
                    scope: getFilePathName(file.name),
                    search: defInfo
                }, null, pathVisitor);
            } catch (e) {
                if (e.found) {
                    lookupRes = e.found;
                }
                //HERE not found
            }
        }

    });
    return lookupRes;
}
<commit_msg>Add import declaration handling<commit_after>//TODO check try statement and its influence on the scope
var walk = require("acorn/dist/walk");
var path = require("path");

function formPathForScope(fileName, data) {
    return fileName + "_" + data.start + "_" + data.end;
}

function getFilePathName(fileName) {
    var index = fileName.indexOf("node_modules");
    if (index > -1) {
        var filePath = path.normalize(fileName);
        var pathRes = filePath.split("/");
        //console.error("File path name = ", pathRes.slice(2).join("/"));
        return pathRes.slice(2).join("/");
    } else {
        //console.error("File path name = ", fileName);
        return fileName;
    }
}

function resolveScopeCountPath(scope) {
    var scopeCountRes = scopeCountResolver[scope];
    if (scopeCountRes === undefined) {
        scopeCountResolver[scope] = 1;
        return scope;
    } else {
        scopeCountResolver[scope] = scopeCountRes + 1;
        return scope + "_" + scopeCountRes;
    }
}

var pathMap = [];

var resolvedFiles = [];

var currentScope;
var scopeCountResolver = [];

var pathVisitor = walk.make({
    //Processing of object.defineProperty
    CallExpression: function(node, scopeInfo, c) {
        var fileName = node.sourceFile.name;
        if (node.callee.type == 'MemberExpression' &&
            node.callee.object.name == 'Object' && node.callee.property.name == 'defineProperty') {
            var obj = node.arguments[0];
            var property = node.arguments[1];
            var newScope = scopeInfo.scope + "_obj_def_prop_";

            if (obj.type == 'Identifier') {
                newScope = newScope + "_" + obj.name;
            }

            if (property.type == 'Literal') {
                newScope = newScope + "_" + property.value
            }

            var key = formPathForScope(fileName, property);
            pathMap[key] = resolveScopeCountPath(newScope);
        };
        c(node.callee, scopeInfo);
        for (var i = 0; i < node.arguments.length; ++i) {
            c(node.arguments[i], scopeInfo);
        };

    },

    ImportDeclaration: function(node, scopeInfo, c) {
        var fileName = node.sourceFile.name;
        var newScope = scopeInfo.scope + "_import_";
        for (var i = 0; i < node.specifiers.length; ++i) {
            if (node.specifiers[i].type == 'ImportDefaultSpecifier') {
                var id = node.specifiers[i].local;
                if (id.type == 'Identifier') {
                    var key = formPathForScope(fileName, id);
                    newScope = resolveScopeCountPath(newScope + id);
                    pathMap[key] = newScope;
                }
            }
            c(node.specifiers[i], {
                scope: newScope,
                search: scopeInfo.search
            });
        }
        c(node.source, {
            scope: newScope,
            search: scopeInfo.search
        });
    },

    //handling of FunctionDeclaration and FunctionExpression
    Function: function(node, scopeInfo, c) {
        // if (scopeInfo.search != undefined && (node.start > scopeInfo.search.start || node.end < scopeInfo.search.end)) {
        //     return;
        // }
        var newScope = scopeInfo.scope + "_fn_";
        var fileName = node.sourceFile.name;
        if (node.id) {
            var key = formPathForScope(fileName, node.id);
            newScope = resolveScopeCountPath(newScope + node.id.name);
            pathMap[key] = newScope;
            c(node.id, {
                scope: newScope,
                search: scopeInfo.search
            });
        } else {
            newScope = resolveScopeCountPath(newScope);
        }

        for (var i = 0; i < node.params.length; ++i) {
            var key = formPathForScope(fileName, node.params[i]);
            var paramScope = resolveScopeCountPath(newScope + "_param_" + node.params[i].name);
            pathMap[key] = paramScope;
            c(node.params[i], {
                scope: paramScope,
                search: scopeInfo.search
            });
        }

        c(node.body, {
            scope: newScope,
            search: scopeInfo.search
        });
    },

    VariableDeclaration: function(node, scopeInfo, c) {
        // if (scopeInfo.search != undefined && (node.start > scopeInfo.search.start || node.end < scopeInfo.search.end)) {
        //     return;
        // }
        var fileName = node.sourceFile.name;
        for (var i = 0; i < node.declarations.length; ++i) {
            var decl = node.declarations[i];

            var key = formPathForScope(fileName, decl.id);
            var newScope = resolveScopeCountPath(scopeInfo.scope + "_var_" + decl.id.name);
            pathMap[key] = newScope;
            c(decl.id, {
                scope: newScope,
                search: scopeInfo.search
            });
            if (decl.init) c(decl.init, {
                scope: newScope,
                search: scopeInfo.search
            });
        }
    },

    // check what happens with this
    MemberExpression: function(node, scopeInfo, c) {
        // if (scopeInfo.search != undefined && (node.start > scopeInfo.search.start || node.end < scopeInfo.search.end)) {
        //     return;
        // }
        currentScope = scopeInfo.scope;
        var fileName = node.sourceFile.name;
        var newScope = scopeInfo.scope;
        if (node.object.type == 'Identifier') {
            newScope = resolveScopeCountPath(newScope + "_obj_" + node.object.name);
            var keyObj = formPathForScope(fileName, node.object);
            pathMap[keyObj] = newScope;
            c(node.object, {
                scope: newScope,
                search: scopeInfo.search
            });
        } else {
            c(node.object, {
                scope: newScope,
                search: scopeInfo.search
            });
            newScope = currentScope;
        }

        if (node.property.type == 'Identifier') {
            newScope = resolveScopeCountPath(newScope + "_prop_" + node.property.name);
            keyProp = formPathForScope(fileName, node.property);
            pathMap[keyProp] = newScope;
        }
        c(node.property, {
            scope: newScope,
            search: scopeInfo.search
        });

        currentScope = newScope;
    },

    ObjectExpression: function(node, scopeInfo, c) {
        // if (scopeInfo.search != undefined && (node.start > scopeInfo.search.start || node.end < scopeInfo.search.end)) {
        //     return;
        // }
        var fileName = node.sourceFile.name;
        var newScope = scopeInfo.scope + "_obj_";
        for (var i = 0; i < node.properties.length; ++i) {
            if (node.objType !== undefined && node.objType.name) {
                newScope = newScope + "_objType_" + node.objType.name;
            }

            if (node.properties[i].key.type == 'Identifier') {
                var key_key = formPathForScope(fileName, node.properties[i].key);
                newScope = resolveScopeCountPath(newScope + "_obj_key_" + node.properties[i].key.name);
                pathMap[key_key] = newScope;
            }
            c(node.properties[i].key, {
                scope: newScope,
                search: scopeInfo.search
            });

            if (node.properties[i].value.type == 'Identifier') {
                var key_val = formPathForScope(fileName, node.properties[i].value);
                newScope = resolveScopeCountPath(newScope + "_obj_val_" + node.properties[i].value.name);
                pathMap[key_val] = newScope;
            }
            c(node.properties[i].value, {
                scope: newScope,
                search: scopeInfo.search
            });
        }
    },

    Identifier: function(node, scopeInfo, c) {
        if (scopeInfo.search != undefined && node.start == scopeInfo.search.start && node.end == scopeInfo.search.end) {
            throw {
                found: scopeInfo.scope
            };
        }
    }
});

module.exports.initLocalFilesScopePaths = function(ternServer, localFiles) {
    resolvedFiles = localFiles;
    scopeCountResolver = [];
    ternServer.files.forEach(function(file) {
        if (localFiles.indexOf(file.name) > -1) {
            walk.recursive(file.ast, {
                scope: getFilePathName(file.name)
            }, null, pathVisitor);
        }
    });

    // console.error(pathMap);
}

module.exports.mapLinesPathToScopePath = function(ternServer, defInfo) {
    var key = formPathForScope(defInfo.file, {
        start: defInfo.start,
        end: defInfo.end
    });
    var mapRes = pathMap[key];
    //if value was found in the map or file is not external, so was fully indexed
    if (mapRes != undefined || resolvedFiles.indexOf(defInfo.file) > -1) {
        return mapRes;
    }

    var lookupRes;

    scopeCountResolver = [];
    ternServer.files.forEach(function(file) {
        if (file.name === defInfo.file) {
            try {
                walk.recursive(file.ast, {
                    scope: getFilePathName(file.name),
                    search: defInfo
                }, null, pathVisitor);
            } catch (e) {
                if (e.found) {
                    lookupRes = e.found;
                }
                //HERE not found
            }
        }

    });
    return lookupRes;
}
<|endoftext|>


<commit_before>'use strict'

module.exports = (comment) => {
  let pos = 0
  let value = comment.text
  const match = value.match(/^\s*!?\s*rtl:/)
  let meta

  if (match) {
    meta = {
      source: comment,
      name: '',
      param: '',
      begin: true,
      end: true,
      blacklist: false,
      preserve: false
    }
    value = value.slice(match[0].length)
    pos = value.indexOf(':')

    if (pos > -1) {
      meta.name = value.slice(0, pos)
      // begin/end are always true, unless one of them actually exists.
      meta.begin = meta.name !== 'end'
      meta.end = meta.name !== 'begin'
      if (meta.name === 'begin' || meta.name === 'end') {
        value = value.slice(meta.name.length + 1)
        pos = value.indexOf(':')
        if (pos > -1) {
          meta.name = value.slice(0, pos)
          value = value.slice(pos)
          meta.param = value.slice(1)
        } else {
          meta.name = value
        }
      } else {
        meta.param = value.slice(pos + 1)
      }
    } else {
      meta.name = value
    }
  }

  return meta
}
<commit_msg>directive-parser.js: return early and minor refactoring<commit_after>'use strict'

module.exports = (comment) => {
  const match = comment.text.match(/^\s*!?\s*rtl:/)
  if (!match) return

  let value = comment.text.slice(match[0].length)
  let pos = value.indexOf(':')
  const meta = {
    source: comment,
    name: '',
    param: '',
    begin: true,
    end: true,
    blacklist: false,
    preserve: false
  }

  if (pos !== -1) {
    meta.name = value.slice(0, pos)
    // begin/end are always true, unless one of them actually exists.
    meta.begin = meta.name !== 'end'
    meta.end = meta.name !== 'begin'

    if (meta.name === 'begin' || meta.name === 'end') {
      value = value.slice(meta.name.length + 1)
      pos = value.indexOf(':')

      if (pos !== -1) {
        meta.name = value.slice(0, pos)
        meta.param = value.slice(pos + 1)
      } else {
        meta.name = value
      }
    } else {
      meta.param = value.slice(pos + 1)
    }
  } else {
    meta.name = value
  }

  return meta
}
<|endoftext|>