<commit_before>const fs = require('fs');
const del = require('del');
const childProcess = require('child_process');

function Builder() {
    var me = this;
    me.rootFolder = fs.realpathSync(__dirname + '/..');
    me.buildPath = me.rootFolder + '/build';
    me.blendPath = me.rootFolder + '/blend';
    me.blendSourcePath = me.blendPath + '/src';
    me.testPath = me.rootFolder + '/tests'
}

Builder.prototype.checkSanity = function(callback) {
    var me = this;
    childProcess.exec('compass -v', { cwd: me.rootFolder }, function(error, stdout, stderr) {
        if (!error) {
            callback.apply(me, [null]);
        } else {
            callback.apply(me, ['No Compass installation found!']);
        }
    });
}

Builder.prototype.cleanBuild = function(callback) {
    var me = this;
    try {
        console.log('-- Cleaning the build (' + me.buildPath + ')');
        if (fs.existsSync(me.buildPath)) {
            del.sync(me.buildPath);
        }
        fs.mkdir(me.buildPath);
        callback.apply(me, [null]);
    } catch (e) {
        callback.apply(me, [e]);
    }
}

Builder.prototype.buildStyles = function(callback) {
    var me = this;
    console.log('-- Building Themes and Styles');
    childProcess.exec('compass compile', { cwd: me.blendPath }, function(error, stdout, stderr) {
        if (!error) {
            callback.apply(me, [null]);
        } else {
            callback.apply(me, [stdout.toString()]);
        }
    });
}

Builder.prototype.buildBlend = function(callback) {
    var me = this;
    console.log('-- Building Blend');
    childProcess.exec('tsc', { cwd: me.blendPath }, function(error, stdout, stderr) {
        if (!error) {
            callback.apply(me, [null]);
        } else {
            callback.apply(me, [stdout.toString()]);
        }
    });
}

Builder.prototype.run = function() {
    var me = this;
    me.checkSanity(function(error) {
        if (!error) {
            me.cleanBuild(function(error) {
                if (!error) {
                    me.buildStyles(function(error) {
                        if (!error) {
                            me.buildBlend(function(error) {
                                if (!error) {
                                    console.log('-- Done :)')
                                } else {
                                    console.error(error);
                                }
                            });
                        } else {
                            console.error(error);
                        }
                    });
                } else {
                    console.error(error);
                }
            });
        } else {
            console.error(error);
        }
    });
}

var builder = new Builder();
builder.run();

/*
Builder.prototype.checkSanity = function() {

    var me = this;

    var checkCompass = function(version) {
        if (childProcess.execSync('compass -v').toString().indexOf('Compass') !== -1) {
            return true;
        } else {
            throw Error('No Compass installation found!');
        }
    }

    try {
        if (checkCompass(me.minCompassVersion)) {
            return true;
        }
    } catch (e) {
        console.log('ERROR: ' + e);
        return false;
    }
}

Builder.prototype.cleanBuild = function() {
    var me = this;
    try {
        console.log('-- Cleaning the build (' + me.buildPath + ')');
        if (fs.existsSync(me.buildPath)) {
            del.sync(me.buildPath);
        }
        fs.mkdir(me.buildPath);
        return true;
    } catch (e) {
        console.log('ERROR: ' + e);
        return false;
    }
}

Builder.prototype.buildStyles = function() {
    var me = this,
        result;
    console.log('-- Building the themes');
    try {
        spawn = childProcess.spawnSync('compass', ['compile'], {
            cwd: me.blendPath,
            stdio: ['pipe', 'pipe', process.stderr]
        });
        spawn.stderr.setEncoding('utf8');
        console.log(spawn);
        return true;
    } catch (e) {
        console.log('ERROR: ' + e);
        return false;
    }
}

Builder.prototype.buildBlend = function() {
    var me = this;
    console.log('-- Building Blend');
    try {
        return true;
    } catch (e) {
        console.log('ERROR: ' + e);
    }
}

Builder.prototype.buildTests = function() {
    var me = this;
    console.log('-- Building Tests');
    try {
        return true;
    } catch (e) {
        console.log('ERROR: ' + e);
    }
}

Builder.prototype.run = function() {
    var me = this;
    console.log("MaterialBlend Framework Builder 1.0\n");
    if (me.checkSanity()) {
        if (me.cleanBuild()) {
            if (me.buildStyles()) {
                if (me.buildBlend()) {
                    if (me.buildTests()) {
                        console.log('\nDone.')
                    }
                }
            }
        }
    }
}

var builder = new Builder();
builder.run();
*/<commit_msg>Cleanup<commit_after>const fs = require('fs');
const del = require('del');
const childProcess = require('child_process');

function Builder() {
    var me = this;
    me.rootFolder = fs.realpathSync(__dirname + '/..');
    me.buildPath = me.rootFolder + '/build';
    me.blendPath = me.rootFolder + '/blend';
    me.blendSourcePath = me.blendPath + '/src';
    me.testPath = me.rootFolder + '/tests'
}

Builder.prototype.checkSanity = function(callback) {
    var me = this;
    childProcess.exec('compass -v', { cwd: me.rootFolder }, function(error, stdout, stderr) {
        if (!error) {
            callback.apply(me, [null]);
        } else {
            callback.apply(me, ['No Compass installation found!']);
        }
    });
}

Builder.prototype.cleanBuild = function(callback) {
    var me = this;
    try {
        console.log('-- Cleaning the build (' + me.buildPath + ')');
        if (fs.existsSync(me.buildPath)) {
            del.sync(me.buildPath);
        }
        fs.mkdir(me.buildPath);
        callback.apply(me, [null]);
    } catch (e) {
        callback.apply(me, [e]);
    }
}

Builder.prototype.buildStyles = function(callback) {
    var me = this;
    console.log('-- Building Themes and Styles');
    childProcess.exec('compass compile', { cwd: me.blendPath }, function(error, stdout, stderr) {
        if (!error) {
            callback.apply(me, [null]);
        } else {
            callback.apply(me, [stdout.toString()]);
        }
    });
}

Builder.prototype.buildBlend = function(callback) {
    var me = this;
    console.log('-- Building Blend');
    childProcess.exec('tsc', { cwd: me.blendPath }, function(error, stdout, stderr) {
        if (!error) {
            callback.apply(me, [null]);
        } else {
            callback.apply(me, [stdout.toString()]);
        }
    });
}

Builder.prototype.run = function() {
    var me = this;
    me.checkSanity(function(error) {
        if (!error) {
            me.cleanBuild(function(error) {
                if (!error) {
                    me.buildStyles(function(error) {
                        if (!error) {
                            me.buildBlend(function(error) {
                                if (!error) {
                                    console.log('-- Done :)')
                                } else {
                                    console.error(error);
                                }
                            });
                        } else {
                            console.error(error);
                        }
                    });
                } else {
                    console.error(error);
                }
            });
        } else {
            console.error(error);
        }
    });
}

var builder = new Builder();
builder.run();<|endoftext|>


<commit_before>// Imports
const firebase = require('firebase');
const appconfig = require('./appconfig.js');
const { JSDOM } = require('jsdom');
const { window } = new JSDOM('<!doctype html>');
global.document = window.document;
global.window = window;

// Initialize Firebase
firebase.initializeApp(appconfig.firebaseConfig);

// Other files
require('./location.js');
require('./chat.js');
require('./script.js');
require('./welcome.js');

// Redirect from index.html to welcome page if not signed in.
function redirectToWelcomeOrChat() {
    const welcomePageUrl = '/static/welcome.html';
    const signupPageUrl = '/static/signup.html';
    const chatPageUrl = '/static/chat.html';
    if(!firebase.auth().currentUser && !(window.location.href.endsWith(welcomePageUrl)||window.location.href.endsWith(signupPageUrl))) {
        window.location.replace(welcomePageUrl);
    } else {
        window.location.replace(chatPageUrl);
    }
}

window.redirectToWelcomeOrChat = redirectToWelcomeOrChat<commit_msg>fix redirection when no page is given<commit_after>// Imports
const firebase = require('firebase');
const appconfig = require('./appconfig.js');
const { JSDOM } = require('jsdom');
window = (new JSDOM('')).window;
global.window = window;
global.document = window.document;

// Initialize Firebase
firebase.initializeApp(appconfig.firebaseConfig);

// Other files
require('./location.js');
require('./chat.js');
require('./script.js');
require('./welcome.js');

// Redirect from index.html to welcome page if not signed in.
function redirectToWelcomeOrChat() {
    const welcomePageUrl = '/static/welcome.html';
    const signupPageUrl = '/static/signup.html';
    const chatPageUrl = '/static/chat.html';

    firebase.auth().onAuthStateChanged(function(user) {
        if (user) {
            // User is already signed in.
            window.location.replace(chatPageUrl);
        } else {
            // No user is signed in.
            if (!(window.location.href.endsWith(welcomePageUrl)||window.location.href.endsWith(signupPageUrl))){
                window.location.replace(welcomePageUrl);
            }
        }
    });
}

window.redirectToWelcomeOrChat = redirectToWelcomeOrChat;<|endoftext|>


<commit_before>/**********************************************************************************

Copyright (C) 2012 by Mozilla Foundation

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

**********************************************************************************/

define( [], function(){

  function Vertical( controlElement ){
    var _element = document.createElement( "div" ),
        _handle = document.createElement( "div" ),
        _control = controlElement,
        _elementHeight,
        _controlHeight,
        _handleHeight,
        _mousePos = 0,
        _this = this;

    _element.className = "scroll-bar scroll-bar-v";
    _handle.className = "scroll-handle";

    _element.appendChild( _handle );

    function setup(){
      _elementHeight = _element.getBoundingClientRect().height;
      _controlHeight = _control.getBoundingClientRect().height;
      _handleHeight = Math.min( _elementHeight, _elementHeight - ( _control.scrollHeight - _controlHeight ) );
      _handle.style.height = _handleHeight + "px";
    } //setup

    function onMouseUp(){
      window.removeEventListener( "mouseup", onMouseUp, false );
      window.removeEventListener( "mousemove", onMouseMove, false );
      _handle.addEventListener( "mousedown", onMouseDown, false );
    } //onMouseUp

    function onMouseMove( e ){
      var diff = e.pageY - _mousePos;
      diff = Math.max( 0, Math.min( diff, _elementHeight - _handleHeight ) );
      _handle.style.top = diff + "px";
      var p = 0;
      if( _elementHeight - _handleHeight > 0 ){
        p = _handle.offsetTop / ( _elementHeight - _handleHeight );
      } //if
      _control.scrollTop = ( _control.scrollHeight - _elementHeight ) * p;
    } //onMouseMove

    function onMouseDown( e ){
      if( e.button === 0 ){
        var handleY = _handle.offsetTop;
        _mousePos = e.pageY - handleY;
        window.addEventListener( "mouseup", onMouseUp, false );
        window.addEventListener( "mousemove", onMouseMove, false );
        _handle.removeEventListener( "mousedown", onMouseDown, false );
      } //if
    } //onMouseDown

    this.update = function(){
      setup();
    }; //update

    _element.addEventListener( "click", function( e ) {
      // bail early if this event is coming from the handle
      if( e.srcElement === _handle || e.button > 0 ) {
        return;
      }

      var posY = e.pageY,
          handleRect = _handle.getBoundingClientRect(),
          elementRect = _element.getBoundingClientRect(),
          p;

      if( posY > handleRect.top ) {
        _handle.style.top = ( ( posY - elementRect.top ) - _handleHeight ) + "px";
      } else {
        _handle.style.top = posY - elementRect.top + "px";
      }

      p = _handle.offsetTop / ( _elementHeight - _handleHeight );
      _control.scrollTop = ( _control.scrollHeight - _elementHeight ) * p;
    }, false);

    window.addEventListener( "resize", setup, false );
    _handle.addEventListener( "mousedown", onMouseDown, false );

    setup();

    Object.defineProperties( this, {
      element: {
        enumerable: true,
        get: function(){
          return _element;
        }
      }
    });

  } //Vertical

  function Horizontal( controlElement ){
    var _element = document.createElement( "div" ),
        _handle = document.createElement( "div" ),
        _control = controlElement,
        _elementWidth,
        _controlWidth,
        _handleWidth,
        _mousePos = 0,
        _this = this;

    _element.className = "scroll-bar scroll-bar-h";
    _handle.className = "scroll-handle";

    _element.appendChild( _handle );

    function setup(){
      _elementWidth = _element.getBoundingClientRect().width;
      _controlWidth = _control.getBoundingClientRect().width;
      _handleWidth = Math.max( 20, Math.min( _elementWidth, _elementWidth - ( _control.scrollWidth - _controlWidth ) ) );
      _handle.style.width = _handleWidth + "px";
      var p = 0;
      if( _control.scrollWidth - _elementWidth > 0 ){
        p = _control.scrollLeft / ( _control.scrollWidth - _elementWidth );
      } //if
      _handle.style.left = p * ( _elementWidth - _handleWidth ) + "px";
    } //setup

    function onMouseUp(){
      window.removeEventListener( "mouseup", onMouseUp, false );
      window.removeEventListener( "mousemove", onMouseMove, false );
      _handle.addEventListener( "mousedown", onMouseDown, false );
    } //onMouseUp

    function onMouseMove( e ){
      var diff = e.pageX - _mousePos;
      diff = Math.max( 0, Math.min( diff, _elementWidth - _handleWidth ) );
      _handle.style.left = diff + "px";
      var p = _handle.offsetLeft / ( _elementWidth - _handleWidth );
      _control.scrollLeft = ( _control.scrollWidth - _elementWidth ) * p;
    } //onMouseMove

    function onMouseDown( e ){
      if( e.button === 0 ){
        var handleX = _handle.offsetLeft;
        _mousePos = e.pageX - handleX;
        window.addEventListener( "mouseup", onMouseUp, false );
        window.addEventListener( "mousemove", onMouseMove, false );
        _handle.removeEventListener( "mousedown", onMouseDown, false );
      } //if
    } //onMouseDown

    _element.addEventListener( "click", function( e ) {
      // bail early if this event is coming from the handle
      if( e.srcElement === _handle || e.button > 0 ) {
        return;
      }

      var posX = e.pageX,
          handleRect = _handle.getBoundingClientRect(),
          elementRect = _element.getBoundingClientRect(),
          p;

      if( posX > handleRect.right ) {
        _handle.style.left = ( ( posX - elementRect.left ) - _handleWidth ) + "px";
      } else {
        _handle.style.left = posX - elementRect.left + "px";
      }

      p = _handle.offsetLeft / ( _elementWidth - _handleWidth );
      _control.scrollLeft = ( _control.scrollWidth - _elementWidth ) * p;
    }, false);

    window.addEventListener( "resize", setup, false );
    _handle.addEventListener( "mousedown", onMouseDown, false );

    this.update = function(){
      setup();
    }; //update

    setup();

    Object.defineProperties( this, {
      element: {
        enumerable: true,
        get: function(){
          return _element;
        }
      }
    });

  } //Horizontal

  return {
    Vertical: Vertical,
    Horizontal: Horizontal
  };

}); //define

<commit_msg>Added mousewheel scrolling to timeline.<commit_after>/**********************************************************************************

Copyright (C) 2012 by Mozilla Foundation

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

**********************************************************************************/

define( [], function(){

  function Vertical( controlElement ){
    var _element = document.createElement( "div" ),
        _handle = document.createElement( "div" ),
        _control = controlElement,
        _elementHeight,
        _controlHeight,
        _handleHeight,
        _mousePos = 0,
        _this = this;

    _element.className = "scroll-bar scroll-bar-v";
    _handle.className = "scroll-handle";

    _element.appendChild( _handle );

    function setup(){
      _elementHeight = _element.getBoundingClientRect().height;
      _controlHeight = _control.getBoundingClientRect().height;
      _handleHeight = Math.min( _elementHeight, _elementHeight - ( _control.scrollHeight - _controlHeight ) );
      _handle.style.height = _handleHeight + "px";
      setHandlePosition();
    } //setup

    function onMouseUp(){
      window.removeEventListener( "mouseup", onMouseUp, false );
      window.removeEventListener( "mousemove", onMouseMove, false );
      _handle.addEventListener( "mousedown", onMouseDown, false );
    } //onMouseUp

    function onMouseMove( e ){
      var diff = e.pageY - _mousePos;
      diff = Math.max( 0, Math.min( diff, _elementHeight - _handleHeight ) );
      _handle.style.top = diff + "px";
      var p = 0;
      if( _elementHeight - _handleHeight > 0 ){
        p = _handle.offsetTop / ( _elementHeight - _handleHeight );
      } //if
      _control.scrollTop = ( _control.scrollHeight - _elementHeight ) * p;
    } //onMouseMove

    function onMouseDown( e ){
      if( e.button === 0 ){
        var handleY = _handle.offsetTop;
        _mousePos = e.pageY - handleY;
        window.addEventListener( "mouseup", onMouseUp, false );
        window.addEventListener( "mousemove", onMouseMove, false );
        _handle.removeEventListener( "mousedown", onMouseDown, false );
      } //if
    } //onMouseDown

    this.update = function(){
      setup();
    }; //update

    function setHandlePosition() {
      _handle.style.top = (_elementHeight - _handleHeight) *
        (_control.scrollTop / (_control.scrollHeight - _elementHeight)) + "px";
    }

    _control.addEventListener( "mousewheel", function(e) {
      if (e.wheelDeltaY) {
        _control.scrollTop -= e.wheelDeltaY;
        setHandlePosition();
        e.preventDefault();
      }
    }, false );

    // For Firefox
    _control.addEventListener( "DOMMouseScroll", function(e) {
      if (e.axis === e.VERTICAL_AXIS) {
        _control.scrollTop += e.detail;
        setHandlePosition();
        e.preventDefault();
      }
    }, false );

    _element.addEventListener( "click", function( e ) {
      // bail early if this event is coming from the handle
      if( e.srcElement === _handle || e.button > 0 ) {
        return;
      }

      var posY = e.pageY,
          handleRect = _handle.getBoundingClientRect(),
          elementRect = _element.getBoundingClientRect(),
          p;

      if( posY > handleRect.top ) {
        _handle.style.top = ( ( posY - elementRect.top ) - _handleHeight ) + "px";
      } else {
        _handle.style.top = posY - elementRect.top + "px";
      }

      p = _handle.offsetTop / ( _elementHeight - _handleHeight );
      _control.scrollTop = ( _control.scrollHeight - _elementHeight ) * p;
    }, false);

    window.addEventListener( "resize", setup, false );
    _handle.addEventListener( "mousedown", onMouseDown, false );

    setup();

    Object.defineProperties( this, {
      element: {
        enumerable: true,
        get: function(){
          return _element;
        }
      }
    });

  } //Vertical

  function Horizontal( controlElement ){
    var _element = document.createElement( "div" ),
        _handle = document.createElement( "div" ),
        _control = controlElement,
        _elementWidth,
        _controlWidth,
        _handleWidth,
        _mousePos = 0,
        _this = this;

    _element.className = "scroll-bar scroll-bar-h";
    _handle.className = "scroll-handle";

    _element.appendChild( _handle );

    function setup(){
      _elementWidth = _element.getBoundingClientRect().width;
      _controlWidth = _control.getBoundingClientRect().width;
      _handleWidth = Math.max( 20, Math.min( _elementWidth, _elementWidth - ( _control.scrollWidth - _controlWidth ) ) );
      _handle.style.width = _handleWidth + "px";
      setHandlePosition();
    } //setup

    function onMouseUp(){
      window.removeEventListener( "mouseup", onMouseUp, false );
      window.removeEventListener( "mousemove", onMouseMove, false );
      _handle.addEventListener( "mousedown", onMouseDown, false );
    } //onMouseUp

    function onMouseMove( e ){
      var diff = e.pageX - _mousePos;
      diff = Math.max( 0, Math.min( diff, _elementWidth - _handleWidth ) );
      _handle.style.left = diff + "px";
      var p = _handle.offsetLeft / ( _elementWidth - _handleWidth );
      _control.scrollLeft = ( _control.scrollWidth - _elementWidth ) * p;
    } //onMouseMove

    function onMouseDown( e ){
      if( e.button === 0 ){
        var handleX = _handle.offsetLeft;
        _mousePos = e.pageX - handleX;
        window.addEventListener( "mouseup", onMouseUp, false );
        window.addEventListener( "mousemove", onMouseMove, false );
        _handle.removeEventListener( "mousedown", onMouseDown, false );
      } //if
    } //onMouseDown

    function setHandlePosition() {
      return _handle.style.left = (_elementWidth - _handleWidth) *
        (_control.scrollLeft / (_control.scrollWidth - _elementWidth)) + "px";
    }

    _control.addEventListener( "mousewheel", function(e) {
      if (e.wheelDeltaX) {
        _control.scrollLeft -= e.wheelDeltaX;
        setHandlePosition();
        e.preventDefault();
      }
    }, false );

    // For Firefox
    _control.addEventListener( "DOMMouseScroll", function(e) {
      if (e.axis === e.HORIZONTAL_AXIS) {
        _control.scrollLeft += e.detail;
        setHandlePosition();
        e.preventDefault();
      }
    }, false );

    _element.addEventListener( "click", function( e ) {
      // bail early if this event is coming from the handle
      if( e.srcElement === _handle || e.button > 0 ) {
        return;
      }

      var posX = e.pageX,
          handleRect = _handle.getBoundingClientRect(),
          elementRect = _element.getBoundingClientRect(),
          p;

      if( posX > handleRect.right ) {
        _handle.style.left = ( ( posX - elementRect.left ) - _handleWidth ) + "px";
      } else {
        _handle.style.left = posX - elementRect.left + "px";
      }

      p = _handle.offsetLeft / ( _elementWidth - _handleWidth );
      _control.scrollLeft = ( _control.scrollWidth - _elementWidth ) * p;
    }, false);

    window.addEventListener( "resize", setup, false );
    _handle.addEventListener( "mousedown", onMouseDown, false );

    this.update = function(){
      setup();
    }; //update

    setup();

    Object.defineProperties( this, {
      element: {
        enumerable: true,
        get: function(){
          return _element;
        }
      }
    });

  } //Horizontal

  return {
    Vertical: Vertical,
    Horizontal: Horizontal
  };

}); //define

<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';

import InsertModalHeader from './InsertModalHeader';
import InsertModalFooter from './InsertModalFooter';
import InsertModalBody from './InsertModalBody';

export default class InsertModal extends Component {

  handleSave = () => {
    const bodyRefs = this.refs.body;
    if (bodyRefs.getFieldValue) {
      this.props.onSave(bodyRefs.getFieldValue());
    } else {
      console.error(`Custom InsertModalBody should implement getFieldValue function
        and should return an object presented as the new row that user input.`);
    }
  }

  render() {
    let { headerComponent, footerComponent, bodyComponent } = this.props;
    const {
      columns,
      validateState,
      ignoreEditable,
      onModalClose
    } = this.props;
    const bodyAttr = { columns, validateState, ignoreEditable };

    bodyComponent = bodyComponent && bodyComponent(columns, validateState, ignoreEditable);

    headerComponent = headerComponent && headerComponent(onModalClose, this.handleSave);

    footerComponent = footerComponent && footerComponent(onModalClose, this.handleSave);

    if (bodyComponent) {
      bodyComponent = React.cloneElement(bodyComponent, { ref: 'body' });
    }

    if (headerComponent && headerComponent.type.name === InsertModalHeader.name) {
      headerComponent = React.cloneElement(headerComponent, {
        onModalClose, onSave: this.handleSave
      });
    } else if (headerComponent && headerComponent.type.name !== InsertModalHeader.name) {
      if (headerComponent.props.className.indexOf('modal-header') === -1) {
        headerComponent = (
{ headerComponent }
);
      }
    }

    if (footerComponent && footerComponent.type.name === InsertModalFooter.name) {
      footerComponent = React.cloneElement(footerComponent, {
        onModalClose, onSave: this.handleSave
      });
    } else if (footerComponent && footerComponent.type.name !== InsertModalFooter.name) {
      if (footerComponent.props.className.indexOf('modal-footer') === -1) {
        footerComponent = (
{ footerComponent }
);
      }
    }

    return (

        {
          headerComponent ||
          (<InsertModalHeader
            onModalClose={ onModalClose }/>)
        }
        {
          bodyComponent ||
          (<InsertModalBody ref='body' { ...bodyAttr }/>)
        }
        {
          footerComponent ||
          (<InsertModalFooter
            onModalClose={ onModalClose }
            onSave={ this.handleSave }/>)
        }

    );
  }
}
InsertModal.propTypes = {
  columns: PropTypes.array.isRequired,
  validateState: PropTypes.object.isRequired,
  ignoreEditable: PropTypes.bool,
  headerComponent: PropTypes.func,
  bodyComponent: PropTypes.func,
  footerComponent: PropTypes.func,
  onModalClose: PropTypes.func,
  onSave: PropTypes.func
};

InsertModal.defaultProps = {};
<commit_msg>fix className unassign bug<commit_after>import React, { Component, PropTypes } from 'react';

import InsertModalHeader from './InsertModalHeader';
import InsertModalFooter from './InsertModalFooter';
import InsertModalBody from './InsertModalBody';

export default class InsertModal extends Component {

  handleSave = () => {
    const bodyRefs = this.refs.body;
    if (bodyRefs.getFieldValue) {
      this.props.onSave(bodyRefs.getFieldValue());
    } else {
      console.error(`Custom InsertModalBody should implement getFieldValue function
        and should return an object presented as the new row that user input.`);
    }
  }

  render() {
    let { headerComponent, footerComponent, bodyComponent } = this.props;
    const {
      columns,
      validateState,
      ignoreEditable,
      onModalClose
    } = this.props;
    const bodyAttr = { columns, validateState, ignoreEditable };

    bodyComponent = bodyComponent && bodyComponent(columns, validateState, ignoreEditable);

    headerComponent = headerComponent && headerComponent(onModalClose, this.handleSave);

    footerComponent = footerComponent && footerComponent(onModalClose, this.handleSave);

    if (bodyComponent) {
      bodyComponent = React.cloneElement(bodyComponent, { ref: 'body' });
    }

    if (headerComponent && headerComponent.type.name === InsertModalHeader.name) {
      headerComponent = React.cloneElement(headerComponent, {
        onModalClose, onSave: this.handleSave
      });
    } else if (headerComponent && headerComponent.type.name !== InsertModalHeader.name) {
      const { className } = headerComponent.props;
      if (typeof className === 'undefined' || className.indexOf('modal-header') === -1) {
        headerComponent = (
{ headerComponent }
);
      }
    }

    if (footerComponent && footerComponent.type.name === InsertModalFooter.name) {
      footerComponent = React.cloneElement(footerComponent, {
        onModalClose, onSave: this.handleSave
      });
    } else if (footerComponent && footerComponent.type.name !== InsertModalFooter.name) {
      const { className } = footerComponent.props;
      if (typeof className === 'undefined' || className.indexOf('modal-footer') === -1) {
        footerComponent = (
{ footerComponent }
);
      }
    }

    return (

        {
          headerComponent ||
          (<InsertModalHeader
            onModalClose={ onModalClose }/>)
        }
        {
          bodyComponent ||
          (<InsertModalBody ref='body' { ...bodyAttr }/>)
        }
        {
          footerComponent ||
          (<InsertModalFooter
            onModalClose={ onModalClose }
            onSave={ this.handleSave }/>)
        }

    );
  }
}
InsertModal.propTypes = {
  columns: PropTypes.array.isRequired,
  validateState: PropTypes.object.isRequired,
  ignoreEditable: PropTypes.bool,
  headerComponent: PropTypes.func,
  bodyComponent: PropTypes.func,
  footerComponent: PropTypes.func,
  onModalClose: PropTypes.func,
  onSave: PropTypes.func
};

InsertModal.defaultProps = {};
<|endoftext|>


<commit_before>define([
    "require",
    "dojo/_base/declare",
    "dojo/_base/array",
    "./route",
    "dojo/Stateful"
], function(_require, declare, array, route, Stateful) {
    return declare("Base Package", [Stateful], {
        // summary:
        //      This is a base class for all Packages in manage
        //      area.

        // routes: [private] Array
        _routes: [],

        // routes: [protected] Array
        routeParams: [],

        constructor: function () {
            try {
                this._routes = this.routeParams = [];
            } catch (e) {
                 console.error(this.declaredClass+" "+arguments.callee.nom, arguments, e);
                 throw e;
            }
        },

        postscript: function () {
            try {
                this.inherited(arguments);
                var _self = this;

                array.forEach(this.get('routeParams'), function (routeParams){
                    var routeObject = _self.getRoute(routeParams);
                    _self.addRoute(routeObject);
                });
            } catch (e) {
                 console.error(this.declaredClass+" "+arguments.callee.nom, arguments, e);
                 throw e;
            }
        },

        getRoute: function (/*Object*/ routeParams) {
            // summary:
            //      Factory abstract method, created
            //      for provide abilities to overload
            //      in children.
            // returns:
            //      route object
            // tags:
            //      protected

            throw new TypeError("abstract");
        },

        register: function () {
            try {
                console.debug("All available routes in package >>>> ", this.get('routes'));
                array.forEach(this.get('routes'), _require('dojo/_base/lang').hitch(this, 'registerRoute'));
            } catch (e) {
                 console.error(this.declaredClass+" "+arguments.callee.nom, arguments, e);
                 throw e;
            }
        },

        addRoute: function (/*route*/ newRoute) {
            try {
                if (!newRoute.isInstanceOf(route)) {
                    throw new TypeError("newRoute has undefined or incompatible type");
                }
                this._routes.push(newRoute);
            } catch (e) {
                 console.error(this.declaredClass+" "+arguments.callee.nom, arguments, e);
                 throw e;
            }
        },

        registerRoute: function (/*route.route*/ newRoute) {
            // summary:
            //      Method for registering
            //      newRoute in the router and register handler
            //      for route match.
            // tags:
            //      protected

            // route: [route.route] Object
            try {
                throw new TypeError("abstract");
            } catch (e) {
                console.error(this.declaredClass+" "+arguments.callee.nom, arguments, e);
                throw e;
            }
        }
    });
});<commit_msg>Fix, mistake while rename _routes variable from protected to private<commit_after>define([
    "require",
    "dojo/_base/declare",
    "dojo/_base/array",
    "./route",
    "dojo/Stateful"
], function(_require, declare, array, route, Stateful) {
    return declare("Base Package", [Stateful], {
        // summary:
        //      This is a base class for all Packages in manage
        //      area.

        // _routes: [private] Array
        _routes: [],

        // routes: [protected] Array
        routeParams: [],

        constructor: function () {
            try {
                this._routes = this.routeParams = [];
            } catch (e) {
                 console.error(this.declaredClass+" "+arguments.callee.nom, arguments, e);
                 throw e;
            }
        },

        postscript: function () {
            try {
                this.inherited(arguments);
                var _self = this;

                array.forEach(this.get('routeParams'), function (routeParams){
                    var routeObject = _self.getRoute(routeParams);
                    _self.addRoute(routeObject);
                });
            } catch (e) {
                 console.error(this.declaredClass+" "+arguments.callee.nom, arguments, e);
                 throw e;
            }
        },

        getRoute: function (/*Object*/ routeParams) {
            // summary:
            //      Factory abstract method, created
            //      for provide abilities to overload
            //      in children.
            // returns:
            //      route object
            // tags:
            //      protected

            throw new TypeError("abstract");
        },

        register: function () {
            try {
                console.debug("All available routes in package >>>> ", this._routes);
                array.forEach(this._routes, _require('dojo/_base/lang').hitch(this, 'registerRoute'));
            } catch (e) {
                 console.error(this.declaredClass+" "+arguments.callee.nom, arguments, e);
                 throw e;
            }
        },

        addRoute: function (/*route*/ newRoute) {
            try {
                if (!newRoute.isInstanceOf(route)) {
                    throw new TypeError("newRoute has undefined or incompatible type");
                }
                this._routes.push(newRoute);
            } catch (e) {
                 console.error(this.declaredClass+" "+arguments.callee.nom, arguments, e);
                 throw e;
            }
        },

        registerRoute: function (/*route.route*/ newRoute) {
            // summary:
            //      Method for registering
            //      newRoute in the router and register handler
            //      for route match.
            // tags:
            //      protected

            // route: [route.route] Object
            try {
                throw new TypeError("abstract");
            } catch (e) {
                console.error(this.declaredClass+" "+arguments.callee.nom, arguments, e);
                throw e;
            }
        }
    });
});<|endoftext|>


<commit_before>var curEditor = undefined;
var editors = [];

function updateCurEditor(selected) {
    if (selected === undefined) {
        var $tabs = $('#edittabs').tabs();
        selected = $tabs.tabs('option', 'selected');
    }
    curEditor = editors[selected];
};

Editor = function(objid) {
    var small_objid = (objid.length < 8 ? objid : objid.slice(0, 7));

    var tabname = 'tab-' + objid;
    var tabeditor = 'tab-' + objid + '-editor';
    var tabresults = 'tab-' + objid + '-results';
    $('#edittabs').append('
' +
                          '

' +
                          '

' +
                          '
');
    var $tabs = $('#edittabs').tabs();
    var idx = $tabs.tabs('length');
    $tabs.tabs('add', '#' + tabname, small_objid);
    editors[idx] = this;
    $tabs.tabs('select', idx);
    updateCurEditor();

    this.object = objid;
    this.tabname = tabname;

    var theme = "ace/theme/dawn";
    var JavaScriptMode = require("ace/mode/javascript").Mode;

    this.editor = ace.edit(tabeditor);
    this.editor.setTheme(theme);
    this.editor.getSession().setMode(new JavaScriptMode());
    this.editor.renderer.setShowGutter(false);
    this.editor.$parent = this;

    this.results = ace.edit(tabresults);
    this.results.setTheme(theme);
    this.results.getSession().setMode(new JavaScriptMode());
    this.results.renderer.setShowGutter(false);
    this.results.setReadOnly(true);

    this.registerHotkeys();

    this.lastMessages = new Array();
    this.lastMessages.push('');
    this.last_msg_index = undefined;

    this.submitting = false;
};

Editor.prototype.appendMessage = function(msg) {
    this.lastMessages.pop(); // the ''
    this.lastMessages.push(msg);
    this.lastMessages.push('');
    this.last_msg_index = this.lastMessages.length-1;
};

Editor.prototype.displayCommand = function(msg)
{
    this.editor.getSession().setValue(msg);
};

Editor.prototype.addMessage = function(msg) {
    this.results.getSession().setValue( this.results.getSession().getValue() + msg + '\n' );
};

Editor.prototype.runCommand = function(msg) {
    if (this.submitting) return;

    var command = this.editor.getSession().getValue();
    if (command.length == 0 || command.trim().length == 0) return;

    // Clear with a timer because we're still getting the \n from the editor on Shift-Enter
    this.submitting = true;
    var self = this;
    setTimeout( function() { self.editor.getSession().setValue(''); self.submitting = false; }, 100);

    this.addMessage('>>> ' + command);
    this.appendMessage(command);

    var arg_map = [
        'ExecScript',
        this.object,
        command
    ];
    chrome.send("event", arg_map);
};

// We track key up and key down to make shift + enter trigger a send
Editor.prototype.registerHotkeys = function() {
    var canon = require("pilot/canon");
    canon.addCommand(
        {
            name: 'run',
            exec: function(env, args, request) { runCommand(); }
        }
    );
    canon.addCommand(
        {
            name: 'history-back',
            exec: function(env, args, request) { editorHistoryBack(); }
        }
    );
    canon.addCommand(
        {
            name: 'history-forward',
            exec: function(env, args, request) { editorHistoryForward(); }
        }
    );

    var HashHandler = require("ace/keyboard/hash_handler").HashHandler;
    var ue = require("pilot/useragent");

    var bindings = require("ace/keyboard/keybinding/default_" + (ue.isMac ? "mac" : "win")).bindings;
    delete bindings.reverse;
    bindings["run"] = "Shift-Return";
    bindings["history-back"] = "Shift-PageUp";
    bindings["history-forward"] = "Shift-PageDown";
    this.editor.setKeyboardHandler(new HashHandler(bindings));
};

Editor.prototype.updateEditorHistory = function() {
    if (this.last_msg_index != undefined)
        this.displayCommand( this.lastMessages[last_msg_index] );
};

Editor.prototype.editHistoryBack = function() {
    if (this.last_msg_index !== undefined && this.last_msg_index-1 >= 0)
        this.last_msg_index--;
    this.updateEditorHistory();
};

Editor.prototype.editHistoryForward = function() {
    if (this.last_msg_index !== undefined && this.last_msg_index+1 < this.lastMessages.length)
        this.last_msg_index++;
    this.updateEditorHistory();
};

function addObject(objid) {
	var gotIt = false;
	for (var i=0; i<editors.length; i++) {
		if (editors[i].object == objid) {
			gotIt = true;
			$('#edittabs').tabs('select', i);
			break;
		}
	}
	if (gotIt == false) {
		curEditor = new Editor(objid);
	}
	$( "#emerson-prompt-dialog" ).dialog( "open" );
}

function addMessage(objid, msg) {
    if (curEditor)
        curEditor.addMessage(msg);
}

function dialogClosed() {
	while (editors.length > 0) {
		closePrompt();
	}
}

function closePrompt() {
	var selectedIndex = $('#edittabs').tabs('option', 'selected');
	console.log("selected index = " + selectedIndex);
	delete editors[selectedIndex].results;
	delete editors[selectedIndex].editor;
	$("#" + editors[selectedIndex].tabname).remove();
	$('#edittabs').tabs('remove', selectedIndex);
	editors.splice(selectedIndex, 1);
	if (editors.length == 0) {
		$( "#emerson-prompt-dialog" ).dialog( "close" );
	} else {
		updateCurEditor();
	}
}

function runCommand() {
    if (curEditor)
        curEditor.runCommand();
}

function editHistoryBack() {
    if (curEditor)
        curEditor.editorHistoryBack();
};

function editHistoryForward() {
    if (curEditor)
        curEditor.editorHistoryForward();
};

$(document).ready(function() {
	$LAB
    .script("../ace/build/src/ace-uncompressed.js")
    .script("../ace/build/src/theme-dawn.js")
    .script("../ace/build/src/mode-javascript.js").wait();

	$('
').attr({id:'emerson-prompt-dialog', title:'Emerson Scripting'})
		.append($("
").attr({id:'edittabs'})
				.append($("
").attr({id:'edittab_titles'}).append(''))
		)
	.appendTo('body');

	/*

*/

	$('#edittabs').tabs({ select: function(event, ui) { updateCurEditor(ui.index); } });

	$( "#emerson-prompt-dialog" ).dialog({
		autoOpen: false,
		height: 'auto',
		width: 450,
		modal: false,
		buttons: {
			Run: runCommand,
			"Close Tab": closePrompt
		},
		close: dialogClosed
	});

	/*<button type="button" onclick="runCommand()">Run</button>
	<button type="button" onclick="closePrompt()">Close</button>*/

	var newcsslink = $("<link />").attr({rel:'stylesheet', type:'text/css', href:'../jquery_themes/redmond/jquery-ui-1.8.6.custom.css'})
	$("head").append(newcsslink);
	var newcsslink = $("<link />").attr({rel:'stylesheet', type:'text/css', href:'../scripting/prompt.css'})
	$("head").append(newcsslink);
});
<commit_msg>Make scripting dialog open before creating editors since ACE has trouble with hidden divs.<commit_after>var curEditor = undefined;
var editors = [];

function updateCurEditor(selected) {
    if (selected === undefined) {
        var $tabs = $('#edittabs').tabs();
        selected = $tabs.tabs('option', 'selected');
    }
    curEditor = editors[selected];
};

Editor = function(objid) {
    var small_objid = (objid.length < 8 ? objid : objid.slice(0, 7));

    var tabname = 'tab-' + objid;
    var tabeditor = 'tab-' + objid + '-editor';
    var tabresults = 'tab-' + objid + '-results';
    $('#edittabs').append('
' +
                          '

' +
                          '

' +
                          '
');
    var $tabs = $('#edittabs').tabs();
    var idx = $tabs.tabs('length');
    $tabs.tabs('add', '#' + tabname, small_objid);
    editors[idx] = this;
    $tabs.tabs('select', idx);
    updateCurEditor();

    this.object = objid;
    this.tabname = tabname;

    var theme = "ace/theme/dawn";
    var JavaScriptMode = require("ace/mode/javascript").Mode;

    this.editor = ace.edit(tabeditor);
    this.editor.setTheme(theme);
    this.editor.getSession().setMode(new JavaScriptMode());
    this.editor.renderer.setShowGutter(false);
    this.editor.$parent = this;

    this.results = ace.edit(tabresults);
    this.results.setTheme(theme);
    this.results.getSession().setMode(new JavaScriptMode());
    this.results.renderer.setShowGutter(false);
    this.results.setReadOnly(true);

    this.registerHotkeys();

    this.lastMessages = new Array();
    this.lastMessages.push('');
    this.last_msg_index = undefined;

    this.submitting = false;
};

Editor.prototype.appendMessage = function(msg) {
    this.lastMessages.pop(); // the ''
    this.lastMessages.push(msg);
    this.lastMessages.push('');
    this.last_msg_index = this.lastMessages.length-1;
};

Editor.prototype.displayCommand = function(msg)
{
    this.editor.getSession().setValue(msg);
};

Editor.prototype.addMessage = function(msg) {
    this.results.getSession().setValue( this.results.getSession().getValue() + msg + '\n' );
};

Editor.prototype.runCommand = function(msg) {
    if (this.submitting) return;

    var command = this.editor.getSession().getValue();
    if (command.length == 0 || command.trim().length == 0) return;

    // Clear with a timer because we're still getting the \n from the editor on Shift-Enter
    this.submitting = true;
    var self = this;
    setTimeout( function() { self.editor.getSession().setValue(''); self.submitting = false; }, 100);

    this.addMessage('>>> ' + command);
    this.appendMessage(command);

    var arg_map = [
        'ExecScript',
        this.object,
        command
    ];
    chrome.send("event", arg_map);
};

// We track key up and key down to make shift + enter trigger a send
Editor.prototype.registerHotkeys = function() {
    var canon = require("pilot/canon");
    canon.addCommand(
        {
            name: 'run',
            exec: function(env, args, request) { runCommand(); }
        }
    );
    canon.addCommand(
        {
            name: 'history-back',
            exec: function(env, args, request) { editorHistoryBack(); }
        }
    );
    canon.addCommand(
        {
            name: 'history-forward',
            exec: function(env, args, request) { editorHistoryForward(); }
        }
    );

    var HashHandler = require("ace/keyboard/hash_handler").HashHandler;
    var ue = require("pilot/useragent");

    var bindings = require("ace/keyboard/keybinding/default_" + (ue.isMac ? "mac" : "win")).bindings;
    delete bindings.reverse;
    bindings["run"] = "Shift-Return";
    bindings["history-back"] = "Shift-PageUp";
    bindings["history-forward"] = "Shift-PageDown";
    this.editor.setKeyboardHandler(new HashHandler(bindings));
};

Editor.prototype.updateEditorHistory = function() {
    if (this.last_msg_index != undefined)
        this.displayCommand( this.lastMessages[last_msg_index] );
};

Editor.prototype.editHistoryBack = function() {
    if (this.last_msg_index !== undefined && this.last_msg_index-1 >= 0)
        this.last_msg_index--;
    this.updateEditorHistory();
};

Editor.prototype.editHistoryForward = function() {
    if (this.last_msg_index !== undefined && this.last_msg_index+1 < this.lastMessages.length)
        this.last_msg_index++;
    this.updateEditorHistory();
};

function addObject(objid) {
	var gotIt = false;
	for (var i=0; i<editors.length; i++) {
		if (editors[i].object == objid) {
			gotIt = true;
			$('#edittabs').tabs('select', i);
			break;
		}
	}
	if (gotIt == false) {
	    $( "#emerson-prompt-dialog" ).dialog( "open" );
	    curEditor = new Editor(objid);
	}
}

function addMessage(objid, msg) {
    if (curEditor)
        curEditor.addMessage(msg);
}

function dialogClosed() {
	while (editors.length > 0) {
		closePrompt();
	}
}

function closePrompt() {
	var selectedIndex = $('#edittabs').tabs('option', 'selected');
	console.log("selected index = " + selectedIndex);
	delete editors[selectedIndex].results;
	delete editors[selectedIndex].editor;
	$("#" + editors[selectedIndex].tabname).remove();
	$('#edittabs').tabs('remove', selectedIndex);
	editors.splice(selectedIndex, 1);
	if (editors.length == 0) {
		$( "#emerson-prompt-dialog" ).dialog( "close" );
	} else {
		updateCurEditor();
	}
}

function runCommand() {
    if (curEditor)
        curEditor.runCommand();
}

function editHistoryBack() {
    if (curEditor)
        curEditor.editorHistoryBack();
};

function editHistoryForward() {
    if (curEditor)
        curEditor.editorHistoryForward();
};

$(document).ready(function() {
	$LAB
    .script("../ace/build/src/ace-uncompressed.js")
    .script("../ace/build/src/theme-dawn.js")
    .script("../ace/build/src/mode-javascript.js").wait();

	$('
').attr({id:'emerson-prompt-dialog', title:'Emerson Scripting'})
		.append($("
").attr({id:'edittabs'})
				.append($("
").attr({id:'edittab_titles'}).append(''))
		)
	.appendTo('body');

	/*

*/

	$('#edittabs').tabs({ select: function(event, ui) { updateCurEditor(ui.index); } });

	$( "#emerson-prompt-dialog" ).dialog({
		autoOpen: false,
		height: 'auto',
		width: 450,
		modal: false,
		buttons: {
			Run: runCommand,
			"Close Tab": closePrompt
		},
		close: dialogClosed
	});

	/*<button type="button" onclick="runCommand()">Run</button>
	<button type="button" onclick="closePrompt()">Close</button>*/

	var newcsslink = $("<link />").attr({rel:'stylesheet', type:'text/css', href:'../jquery_themes/redmond/jquery-ui-1.8.6.custom.css'})
	$("head").append(newcsslink);
	var newcsslink = $("<link />").attr({rel:'stylesheet', type:'text/css', href:'../scripting/prompt.css'})
	$("head").append(newcsslink);
});
<|endoftext|>


<commit_before>#!/usr/bin/env node
// This lets us remove files on all platforms. Notably, `rm` is missing on Windows.
const path = require("path");
const fs = require("fs");

const distPath = path.join(__dirname, "..", "dist");

fs.rmdirSync(distPath, { recursive: true });
<commit_msg>npm run clean: avoid deprecation error<commit_after>#!/usr/bin/env node
// This lets us remove files on all platforms. Notably, `rm` is missing on Windows.
const path = require("path");
const fs = require("fs");

const distPath = path.join(__dirname, "..", "dist");

fs.rmSync(distPath, { recursive: true, force: true });
<|endoftext|>


<commit_before>#!/usr/bin/env node

var pacificator = require('../src/pacificator.js'),
    program = require('commander'),
    pkg = require('../package.json');

program
  .version(pkg.version)
  .description(pkg.description)
  .option('-t, --tabIndent', "Choose the amount of tabs for indentation")
  .option('-s, --spaceIndent', "Choose the amount of spaces for indentation")
  .arguments('<input_file> [input_amount...]')
  .action(function (input_file, input_amount) {
    amount = input_amount;
    path = input_file;
  });

program.parse(process.argv);

if (program.tabIndent) {
    var output = pacificator.pacificateTab(path, amount);
  } else if (program.spaceIndent) {
    var output = pacificator.pacificateSpace(path, amount);
  } else {
    var output = pacificator.pacificate(path);
}

fs.writeFile(path, output);

console.log('Done! Your CSS was Pacificated successfully.');
<commit_msg>fix var declaration for stric mode<commit_after>#!/usr/bin/env node

var pacificator = require('../src/pacificator.js'),
    fs = require('fs');
    program = require('commander'),
    pkg = require('../package.json');

program
  .version(pkg.version)
  .description(pkg.description)
  .option('-t, --tabIndent', "Choose the amount of tabs for indentation")
  .option('-s, --spaceIndent', "Choose the amount of spaces for indentation")
  .arguments('<input_file> [input_amount...]')
  .action(function (input_file, input_amount) {
    amount = input_amount;
    path = input_file;
  });

program.parse(process.argv);

if (program.tabIndent) {
    var output = pacificator.pacificateTab(path, amount);
  } else if (program.spaceIndent) {
    var output = pacificator.pacificateSpace(path, amount);
  } else {
    var output = pacificator.pacificate(path);
}

fs.writeFile(path, output);

console.log('Done! Your CSS was Pacificated successfully.');
<|endoftext|>


<commit_before>#!/usr/bin/env node

global[' requestCallback'] = function me () {
    callback = me.onRequest();
    me.callbackRequested = true;
    return function (error, result) {
        me.callbackRequested = false;
        callback(error, result);
    };
};
global[' requestCallback'].callbackRequested = false;

var repl = require('repl'),
vm = require('vm'),
PURRL = require('../index'),
confFile = 'purrl.json',
specified = false,
minimist,
argv,
clients,
session;

try {
    minimist = require('minimist');
} catch (e) {
    // Optional dependency
}

function purrlEval (code, context, file, callback) {
    var err, result;

    function onRequest() {
        return callback;
    }
    global[' requestCallback'].onRequest = onRequest;

    try {
        result = vm.runInContext(code, context, file);
    } catch (e) {
        err = e;
    }
    if (err && process.domain) {
        process.domain.emit('error', err);
        process.domain.exit();
    }
    else {
        if (!global[' requestCallback'].callbackRequested) {
            callback(err, result);
        }
    }
}

if (minimist) {
    argv = minimist(process.argv.slice(2));
    if (Object.prototype.toString.call(argv.c) === '[object Array]') {
        argv.c = argv.c[0];
    }
    if (Object.prototype.toString.call(argv.conf) === '[object Array]') {
        argv.conf = argv.conf[0];
    }
    if (Object.prototype.toString.call(argv.c) === '[object String]') {
        confFile = argv.c;
        specified = true;
    }
    if (Object.prototype.toString.call(argv.conf) === '[object String]') {
        confFile = argv.conf;
        specified = true;
    }
}

clients = PURRL.createReplClients(confFile, specified);

session = repl.start({
    prompt : 'purrl> ',
    ignoreUndefined : true,
    eval : purrlEval
});

session.context.PURRL = function (config) { return new PURRL().config(PURRL.defaultReplConfig).config(config); };
session.context.PURRL.loadConfig = PURRL.loadConfig;
Object.keys(clients).forEach(function (client) {
    session.context[client] = clients[client];
});
<commit_msg>Fixed file permissions on bin/purrl.js<commit_after>#!/usr/bin/env node

global[' requestCallback'] = function me () {
    callback = me.onRequest();
    me.callbackRequested = true;
    return function (error, result) {
        me.callbackRequested = false;
        callback(error, result);
    };
};
global[' requestCallback'].callbackRequested = false;

var repl = require('repl'),
vm = require('vm'),
PURRL = require('../index'),
confFile = 'purrl.json',
specified = false,
minimist,
argv,
clients,
session;

try {
    minimist = require('minimist');
} catch (e) {
    // Optional dependency
}

function purrlEval (code, context, file, callback) {
    var err, result;

    function onRequest() {
        return callback;
    }
    global[' requestCallback'].onRequest = onRequest;

    try {
        result = vm.runInContext(code, context, file);
    } catch (e) {
        err = e;
    }
    if (err && process.domain) {
        process.domain.emit('error', err);
        process.domain.exit();
    }
    else {
        if (!global[' requestCallback'].callbackRequested) {
            callback(err, result);
        }
    }
}

if (minimist) {
    argv = minimist(process.argv.slice(2));
    if (Object.prototype.toString.call(argv.c) === '[object Array]') {
        argv.c = argv.c[0];
    }
    if (Object.prototype.toString.call(argv.conf) === '[object Array]') {
        argv.conf = argv.conf[0];
    }
    if (Object.prototype.toString.call(argv.c) === '[object String]') {
        confFile = argv.c;
        specified = true;
    }
    if (Object.prototype.toString.call(argv.conf) === '[object String]') {
        confFile = argv.conf;
        specified = true;
    }
}

clients = PURRL.createReplClients(confFile, specified);

session = repl.start({
    prompt : 'purrl> ',
    ignoreUndefined : true,
    eval : purrlEval
});

session.context.PURRL = function (config) { return new PURRL().config(PURRL.defaultReplConfig).config(config); };
session.context.PURRL.loadConfig = PURRL.loadConfig;
Object.keys(clients).forEach(function (client) {
    session.context[client] = clients[client];
});
<|endoftext|>


<commit_before>#! /usr/bin/env node
'use strict';

global.__REKIT_NO_WATCH = true;

const ArgumentParser = require('argparse').ArgumentParser;
const rekit = require('rekit-core');
const chalk = require('chalk');
const rekitPkgJson = require('../package.json');

const parser = new ArgumentParser({
  version: rekitPkgJson.version,
  addHelp: true,
  allowAbbrev: false,
  description: 'Rekit command line tools to manage a project.',
});

const subparsers = parser.addSubparsers({
  title: 'Sub commands',
  dest: 'commandName',
});

// Create project
const createCmd = subparsers.addParser('create', {
  addHelp: true,
  description: 'Create a new Rekit project.',
});

subparsers.addParser('list', {
  addHelp: true,
  description: 'List supported application types.',
});

createCmd.addArgument('name', {
  help: 'The project name',
});

createCmd.addArgument(['--source', '-s'], {
  help: 'Source template for creating the app. Could be a git repo or local folder.',
  dest: 'source',
});

createCmd.addArgument(['--type', '-t'], {
  help: 'Application type to create, default is rekit-react.',
  defaultValue: 'rekit-react',
});

// Install plugin command
const installPluginCmd = subparsers.addParser('install', {
  addHelp: true,
  description: 'Install a Rekit plugin.',
});

installPluginCmd.addArgument('name', {
  help: 'The plugin name',
});

// Uninstall plugin command
const uninstallPluginCmd = subparsers.addParser('uninstall', {
  addHelp: true,
  description: 'Uninstall a Rekit plugin.',
});

uninstallPluginCmd.addArgument('name', {
  help: 'The plugin name',
});

// Add sub-command
const addCmd = subparsers.addParser('add', {
  addHelp: true,
  description: 'Add an element to the project.',
});

addCmd.addArgument('type', {
  help: 'The type of the element to add.',
});

addCmd.addArgument('name', {
  help:
    "The element name to add, in format of <feature>/<name>, e.g.: 'rekit add component user/list-view'. <name> is unnecessary if add a feature.",
});

// TODO: move to rekit-react plugin
addCmd.addArgument(['--connect', '-c'], {
  help: 'Whether to connect to the Redux store. Only used for component.',
  action: 'storeTrue',
});

// TODO: move to rekit-react plugin
addCmd.addArgument(['--url-path', '-u'], {
  help: 'The url path added to react router config. Only used for page/component.',
  dest: 'urlPath',
});

// TODO: move to rekit-react plugin
addCmd.addArgument(['--async', '-a'], {
  help: 'Whether the action is async using redux-thunk.',
  action: 'storeTrue',
});

// Remove sub-command
const rmCmd = subparsers.addParser('remove', {
  aliases: ['rm'],
  addHelp: true,
  description: 'Remove an element from the project.',
});

rmCmd.addArgument('type', {
  help: 'The type of the element to remove.',
});

rmCmd.addArgument('name', {
  help:
    "The element name to remove, in format of <feature>/<name>, e.g.: 'rekit remove component user/list-view'. Name is unnecessary if remove a feature.",
});

// Move sub-command
const mvCmd = subparsers.addParser('move', {
  aliases: ['mv'],
  addHelp: true,
  description: 'Move or rename an element.',
});

mvCmd.addArgument('type', {
  help: 'The type of the element to move.',
});

mvCmd.addArgument('source', {
  help: 'The source element to move.',
});

mvCmd.addArgument('target', {
  help: 'The target element to reach.',
});

const args = parser.parseArgs();

// Convert aliases
const aliases = { rm: 'remove', mv: 'move' };
Object.keys(aliases).forEach(k => {
  if (args.commandName === k) {
    args.commandName = aliases[k];
  }
});

console.time('😃  Done');
switch (args.commandName) {
  case 'create':
    // Create a project
    rekit.core.create(args);
    break;
  case 'install':
    rekit.core.plugin.installPlugin(args.name);
    break;
  case 'list':
    rekit.core.create.getAppTypes().then(appTypes => {
      console.log(`Found ${appTypes.length} application types supported: `);
      appTypes.forEach((t, i) => {
        console.log(
          `${i + 1}. ${t.name}${chalk.gray('(' + t.id + ')')}: ${chalk.cyan(t.description)}`,
        );
      });
      console.timeEnd('😃  Done');
    });
    break;
  case 'uninstall':
    rekit.core.plugin.uninstallPlugin(args.name);
    break;
  default:
    rekit.core.handleCommand(args);
    rekit.core.vio.flush();
    console.timeEnd('😃  Done'); // create command doesn't need time end.
    break;
}
<commit_msg>Added clean and sass argument.<commit_after>#! /usr/bin/env node
'use strict';

global.__REKIT_NO_WATCH = true;

const ArgumentParser = require('argparse').ArgumentParser;
const rekit = require('rekit-core');
const chalk = require('chalk');
const rekitPkgJson = require('../package.json');

const parser = new ArgumentParser({
  version: rekitPkgJson.version,
  addHelp: true,
  allowAbbrev: false,
  description: 'Rekit command line tools to manage a project.',
});

const subparsers = parser.addSubparsers({
  title: 'Sub commands',
  dest: 'commandName',
});

// Create project
const createCmd = subparsers.addParser('create', {
  addHelp: true,
  description: 'Create a new Rekit project.',
});

subparsers.addParser('list', {
  addHelp: true,
  description: 'List supported application types.',
});

createCmd.addArgument('name', {
  help: 'The project name',
});

createCmd.addArgument(['--source', '-s'], {
  help: 'Source template for creating the app. Could be a git repo or local folder.',
  dest: 'source',
});

createCmd.addArgument(['--type', '-t'], {
  help: 'Application type to create, default is rekit-react.',
  defaultValue: 'rekit-react',
});

createCmd.addArgument(['--clean', '-c'], {
  help: 'No example code.',
  action: 'storeTrue',
});

createCmd.addArgument(['--sass'], {
  help: 'Use sass as css transpiler.',
  action: 'storeTrue',
});

// Install plugin command
const installPluginCmd = subparsers.addParser('install', {
  addHelp: true,
  description: 'Install a Rekit plugin.',
});

installPluginCmd.addArgument('name', {
  help: 'The plugin name',
});

// Uninstall plugin command
const uninstallPluginCmd = subparsers.addParser('uninstall', {
  addHelp: true,
  description: 'Uninstall a Rekit plugin.',
});

uninstallPluginCmd.addArgument('name', {
  help: 'The plugin name',
});

// Add sub-command
const addCmd = subparsers.addParser('add', {
  addHelp: true,
  description: 'Add an element to the project.',
});

addCmd.addArgument('type', {
  help: 'The type of the element to add.',
});

addCmd.addArgument('name', {
  help:
    "The element name to add, in format of <feature>/<name>, e.g.: 'rekit add component user/list-view'. <name> is unnecessary if add a feature.",
});

// TODO: move to rekit-react plugin
addCmd.addArgument(['--connect', '-c'], {
  help: 'Whether to connect to the Redux store. Only used for component.',
  action: 'storeTrue',
});

// TODO: move to rekit-react plugin
addCmd.addArgument(['--url-path', '-u'], {
  help: 'The url path added to react router config. Only used for page/component.',
  dest: 'urlPath',
});

// TODO: move to rekit-react plugin
addCmd.addArgument(['--async', '-a'], {
  help: 'Whether the action is async using redux-thunk.',
  action: 'storeTrue',
});

// Remove sub-command
const rmCmd = subparsers.addParser('remove', {
  aliases: ['rm'],
  addHelp: true,
  description: 'Remove an element from the project.',
});

rmCmd.addArgument('type', {
  help: 'The type of the element to remove.',
});

rmCmd.addArgument('name', {
  help:
    "The element name to remove, in format of <feature>/<name>, e.g.: 'rekit remove component user/list-view'. Name is unnecessary if remove a feature.",
});

// Move sub-command
const mvCmd = subparsers.addParser('move', {
  aliases: ['mv'],
  addHelp: true,
  description: 'Move or rename an element.',
});

mvCmd.addArgument('type', {
  help: 'The type of the element to move.',
});

mvCmd.addArgument('source', {
  help: 'The source element to move.',
});

mvCmd.addArgument('target', {
  help: 'The target element to reach.',
});

const args = parser.parseArgs();

// Convert aliases
const aliases = { rm: 'remove', mv: 'move' };
Object.keys(aliases).forEach(k => {
  if (args.commandName === k) {
    args.commandName = aliases[k];
  }
});

console.time('😃  Done');
switch (args.commandName) {
  case 'create':
    // Create a project
    rekit.core.create(args);
    break;
  case 'install':
    rekit.core.plugin.installPlugin(args.name);
    break;
  case 'list':
    rekit.core.create.getAppTypes().then(appTypes => {
      console.log(`Found ${appTypes.length} application types supported: `);
      appTypes.forEach((t, i) => {
        console.log(
          `${i + 1}. ${t.name}${chalk.gray('(' + t.id + ')')}: ${chalk.cyan(t.description)}`,
        );
      });
      console.timeEnd('😃  Done');
    });
    break;
  case 'uninstall':
    rekit.core.plugin.uninstallPlugin(args.name);
    break;
  default:
    rekit.core.handleCommand(args);
    rekit.core.vio.flush();
    console.timeEnd('😃  Done'); // create command doesn't need time end.
    break;
}
<|endoftext|>


<commit_before>#!/usr/bin/env node

/**
 * Module dependencies
 */
var _ = require('lodash')
	, program = require('./_commander')
	, package = require('../package.json');

program
	.version(package.version, '-v, --version');

//
// Normalize version argument, i.e.
//
// $ sails -v
// $ sails -V
// $ sails --version
// $ sails version
//

// make `-v` option case-insensitive
process.argv = _.map(process.argv,function(arg){
	return (arg === '-V') ? '-v' : arg;
});

// $ sails version (--version synonym)
program
	.command('version')
	.description('')
	.action( program.versionInformation );

program
	.option('--silent')
	.option('--verbose')
	.option('--silly');

// $ sails lift
program
	.command('lift')
	.option('--prod')
	.option('--port')
	.description('')
	.action( require('./sails-lift') );

// $ sails new <appname>
program
	.command('new <appname>')
	.option('--dry')
	.description('')
	.action( require('./sails-new') );

// $ sails generate <module>
program.command('generate')
	.description('')
	.option('--dry')
	.action(require('./sails-generate'));

// $ sails console
program
	.command('console')
	.description('')
	.action( require('./sails-console') );

// $ sails debug
program
	.command('debug')
	.description('')
	.action( require('./sails-debug') );

// $ sails configure
program
	.command('configure')
	.description('')
	.action( require('./sails-configure') );

//
// Normalize help argument, i.e.
//
// $ sails --help
// $ sails help
// $ sails
// $ sails <unrecognized_cmd>
//

// $ sails help (--help synonym)
program
	.command('help')
	.description('')
	.action( program.usageMinusWildcard );

// $ sails <unrecognized_cmd>
// Mask the '*' in `help`.
program
	.command('*')
	.action( program.usageMinusWildcard );

// $ sails
//
program.parse(process.argv);
var NO_COMMAND_SPECIFIED = program.args.length === 0;
if (NO_COMMAND_SPECIFIED) {
  program.usageMinusWildcard();
}

//
// CLIController contains handlers containing
// all of the logic that will then send a response
// to the user on the other side of the CLI
//

/**
 * Interpret, validate, and normalize command-line arguments.
 * Then take the appropriate action.
 */

/*
var program = {
	'--verbose': {},
	'--silly': {},
	'--silent': {},

	'lift': {
		'--env=<environment>': {},
		'--port': {},
	},

	'new <pathToNewApp>': {},

	'generate <module>': {
		'--dry': {},

		'model <resource>': {},
		'controller <resource>': {},
		'api <resource>': {},
	},

	'console': {},

	'run <cmd>': {},

	'help': {},

	'version': {}
};
// */

// var RESERVED = {
// 	usage: '_USAGE'
// };

// var REGEXP = {
// 	option: /^--/
// };

// function getUsage (program) {
// 	program[RESERVED.usage] = _.reduce(program, function (usage, v, k) {
// 		if (k.match(REGEXP.option)) {
// 			return usage + '\n'
// 		}
// 		return usage;
// 	});
// }

// module.exports = function interpretArguments ( argv, handlers ) {

// 	if ( !_.isObject(argv) ) return handlers.invalid();
// 	if ( !_.isArray(argv._) ) return handlers.invalid();
// 	if ( !argv._.length ) return handlers.usage();

// 	var first	= argv._[0] || '',
// 		second	= argv._[1] || '',
// 		third	= argv._[2] || '',
// 		fourth	= argv._[3] || '',
// 		fifth	= argv._[4] || '',
// 		all		= _.map(argv._, function (arg) {return arg + '';});

// 	var isLift		= _.contains(['lift', 'raise', 'start', 'server', 's', 'l'], first),
// 		isConsole	= _.contains(['console', 'c'], first),
// 		isGenerate	= _.contains(['generate'], first),
// 		isNew		= _.contains(['new'], first),
// 		isVersion	= _.contains(['version'], first),
// 		isWWW		= _.contains(['www', 'build'], first),
// 		isRun		= _.contains(['run','issue'], first);
// 		isConfigure	= _.contains(['configure'], first);

// 	// Interpret/validate arguments to `sails generate`
// 	if ( isGenerate ) {

// 		// Second argument is the type of module to generate
// 		var module = second;

// 		// Third argument is the id of the module we're creating
// 		var id = third;

// 		// If the module or id is invalid, or doesn't exist,
// 		// we have a usage error on our hands.
// 		if ( !module ) {
// 			return handlers.invalid(
// 				'What type of module would you like to generate?'
// 			);
// 		}

// 		// Whitelist
// 		var knownGenerators = [
// 			// Client
// 			'frontend',
// 			'gruntfile',

// 			// Core
// 			'backend',
// 			'controller',
// 			'model',
// 			'view',
// 			'api',
// 			'policy',

// 			// Plugins
// 			'generator',
// 			'adapter',
// 			'hook'
// 		];

// 		// Check for unknown generators
// 		// (this will be removed eventually)
// 		if ( !_.contains(knownGenerators, module) ) {
// 			return handlers.error(
// 				'Sorry, I don\'t have a "' + second + '" generator.  ' +
// 				'Did you mean: `sails generate api '+second+'`?'
// 			);
// 		}

// 		// Check for todo/not-yet-supported generators
// 		// switch ( module ) {
// 		// 	case 'view':
// 		// 	case 'policy':
// 		// 	case 'adapter':
// 		// 		return handlers.error(
// 		// 		'Sorry, `sails generate ' + second + '` ' +
// 		// 		'is currently out of commission.');
// 		// }

// 		// If no id argument exists, this is a usage error
// 		if ( !id ) {
// 			return handlers.invalid(
// 				'Please specify the name for the new ' + module + '.'
// 			);
// 		}
// 		if ( !id.match(/^[a-z]([a-z]|[0-9])*$/i) ) {
// 			return handlers.invalid(
// 				'Sorry, "' + id + '" is not a valid name for a ' + module + '.',
// 				'Only letters and numbers are allowed, and it must start with a letter.',
// 				'(Sails ' + module + 's are case-insensitive.)'
// 			);
// 		}

// 		// Allow cli user to specify `FooController` and really mean `foo`
// 		if (module === 'controller') {
// 			id = id.replace(/Controller$/, '');
// 		}

// 		// Figure out whether subsequent cmdline args are
// 		// supposed to be controller actions or model attributes.
// 		var arrayOfArgs = argv._.splice(3);
// 		var argsLookLikeAttributes = ( arrayOfArgs[0] && arrayOfArgs[0].match(/:/) );

// 		// If module === 'model', args ALWAYS "lookLikeAttributes"
// 		if ( module==='model' ) { argsLookLikeAttributes = true; }

// 		var actions = argsLookLikeAttributes ? [] : arrayOfArgs;
// 		var attributes = argsLookLikeAttributes ? arrayOfArgs : [];

// 		// Build options
// 		var options = _.extend({}, argv, {
// 			args: [id],
// 			id: id,
// 			module: second,
// 			actions:  actions,
// 			attributes: attributes
// 		});

// 		handlers.generate(options);
// 		return;
// 	}

// 	/**
// 	 * `sails new <APPNAME>`
// 	 *
// 	 * Asset auto-"linker" is enabled by default
// 	 */
// 	if ( isNew ) {

// 		var linkerExplicitlyDisabled = (argv['linker'] === false) || (argv['linker'] === 'false');

// 		handlers['new']({
// 			appName: second,
// 			assetLinker: {
// 				enabled: linkerExplicitlyDisabled ? false : true,
// 				src: argv['linker-src'] || 'assets/linker/**/*'
// 			},
// 			dry : argv.dry
// 		});
// 		return;
// 	}

// 	if ( isLift )		return handlers.lift();
// 	if ( isConsole )	return handlers.console();
// 	if ( isVersion )	return handlers.version();
// 	if ( isRun )		return handlers.run();
// 	if ( isWWW )		return handlers.www();
// 	if ( isConfigure )	return handlers.configure();

// 	// Unknown action
// 	return handlers.invalid( { first: first } );
// };

// Build Sails options & logger using ONLY command-line args
// (the only configuration we have available at this point)
// var config = cliutil.getCLIConfig(require('optimist').argv);

// // Mix-in options and logger into each command's context
// CLIController = mergeCtx.all(CLIController, {
// 	config: config
// });

// // Interpret arguments, route to appropriate handler
// require('./arguments')( require('optimist').argv, CLIController );

// {
// 	configure : require('./commands/configure'),
// 	new       : require('./commands/new'),
// 	generate  : require('./commands/generate'),
// 	version   : require('./commands/version'),
// 	lift      : require('./commands/lift'),
// 	console   : require('./commands/console'),
// 	www       : require('./commands/www'),
// 	error     : require('./report/error'),
// 	invalid   : require('./report/invalid'),
// 	usage     : require('./report/usage')
// }

// todo move these to their respective spots:

	// fs			= require('fs-extra'),
	// argv		= require('optimist').argv,
	// Err			= require('../errors'),
	// CaptainsLog	= require('captains-log'),
	// Sails		= require('../lib/app');
	// cliutil		= require('sails-util/cli');
	// // _.str		= require('underscore.string'),
	// REPL		= require('repl'),
	// Grunt__		= require('./www'),
	// path		= require('path');
	// // _.str		= require('underscore.string'),
	// generate	= require('sails-generate');

	// Monkey-patch commander's `unknownOption` to allow us
// to catch the `-V` argument
// program.Command.prototype.unknownOption = function (option) {
// 	console.log(option);
// };
<commit_msg>Removed commented-out stuff.<commit_after>#!/usr/bin/env node

/**
 * Module dependencies
 */
var _ = require('lodash')
	, program = require('./_commander')
	, package = require('../package.json');

program
	.version(package.version, '-v, --version');

//
// Normalize version argument, i.e.
//
// $ sails -v
// $ sails -V
// $ sails --version
// $ sails version
//

// make `-v` option case-insensitive
process.argv = _.map(process.argv,function(arg){
	return (arg === '-V') ? '-v' : arg;
});

// $ sails version (--version synonym)
program
	.command('version')
	.description('')
	.action( program.versionInformation );

program
	.option('--silent')
	.option('--verbose')
	.option('--silly');

// $ sails lift
program
	.command('lift')
	.option('--prod')
	.option('--port')
	.description('')
	.action( require('./sails-lift') );

// $ sails new <appname>
program
	.command('new <appname>')
	.option('--dry')
	.description('')
	.action( require('./sails-new') );

// $ sails generate <module>
program.command('generate')
	.description('')
	.option('--dry')
	.action(require('./sails-generate'));

// $ sails console
program
	.command('console')
	.description('')
	.action( require('./sails-console') );

// $ sails debug
program
	.command('debug')
	.description('')
	.action( require('./sails-debug') );

// $ sails configure
program
	.command('configure')
	.description('')
	.action( require('./sails-configure') );

//
// Normalize help argument, i.e.
//
// $ sails --help
// $ sails help
// $ sails
// $ sails <unrecognized_cmd>
//

// $ sails help (--help synonym)
program
	.command('help')
	.description('')
	.action( program.usageMinusWildcard );

// $ sails <unrecognized_cmd>
// Mask the '*' in `help`.
program
	.command('*')
	.action( program.usageMinusWildcard );

// $ sails
//
program.parse(process.argv);
var NO_COMMAND_SPECIFIED = program.args.length === 0;
if (NO_COMMAND_SPECIFIED) {
  program.usageMinusWildcard();
}

<|endoftext|>


<commit_before>#!/usr/bin/env node

// Native
const path = require('path')

// Packages
const asyncToGen = require('async-to-gen/register')
const updateNotifier = require('update-notifier')
const {red} = require('chalk')
const nodeVersion = require('node-version')
const isAsyncSupported = require('is-async-supported')

// Ours
const pkg = require('../package')

// Support for keywords "async" and "await"
if (!isAsyncSupported()) {
  const modulesDir = path.join(__dirname, '..', 'node_modules')

  asyncToGen({
    excludes: new RegExp(`.*${modulesDir}.*`),
    sourceMaps: false
  })
}

// Throw an error if node version is too low
if (nodeVersion.major < 6) {
  console.error(`${red('Error!')} Serve requires at least version 6 of Node. Please upgrade!`)
  process.exit(1)
}

// Let user know if there's an update
// This isn't important when deployed to Now
if (!process.env.NOW && pkg.dist) {
  updateNotifier({pkg}).notify()
}

// Load package core with async/await support
require('../lib')
<commit_msg>Use glob pattern for excluding files<commit_after>#!/usr/bin/env node

// Native
const path = require('path')

// Packages
const asyncToGen = require('async-to-gen/register')
const updateNotifier = require('update-notifier')
const {red} = require('chalk')
const nodeVersion = require('node-version')
const isAsyncSupported = require('is-async-supported')

// Ours
const pkg = require('../package')

// Support for keywords "async" and "await"
if (!isAsyncSupported()) {
  const modulesDir = path.join(__dirname, '..', 'node_modules')

  asyncToGen({
    exclude: `**/${modulesDir}/**`,
    sourceMaps: false
  })
}

// Throw an error if node version is too low
if (nodeVersion.major < 6) {
  console.error(`${red('Error!')} Serve requires at least version 6 of Node. Please upgrade!`)
  process.exit(1)
}

// Let user know if there's an update
// This isn't important when deployed to Now
if (!process.env.NOW && pkg.dist) {
  updateNotifier({pkg}).notify()
}

// Load package core with async/await support
require('../lib')
<|endoftext|>


<commit_before>#!/usr/bin/env node

// Must symlink the generator from xtc's modules up to the project's modules.
// Else Yeoman won't find it.

var path = require('path')
	,fs = require('fs')
	,util = require('util')
	,cwd = process.cwd()
	,src = path.join(cwd, '/node_modules/generator-xtc')
	,dest = path.join(resolve, '../generator-xtc')
;

if ('install' === process.env.npm_lifecycle_event) {

	try {
		fs.symlinkSync(src, dest, 'dir');
		console.log('symlink: generator-xtc into node_modules\n')
	} catch (e) {
		if ('EEXIST' === e.code) {
			console.info('symlink: generator-xtc already exists in node_modules\n');
		}
		else if ('EPERM' === e.code) {
			throw new Error(util.format('Permission error: creating symlink to generator-xtc\n%s --> %s\n', src, dest));
		}
		else {
			throw e;
		}
	}
}

// And of course we remove it again before xtc is uninstalled

else if ('uninstall' === process.env.npm_lifecycle_event) {

	try {
		fs.unlinkSync(dest, 'dir');
		console.log('symlink: removed generator-xtc from node_modules\n')
	} catch (e) {
		if ('ENOENT' !== e.code) {
			console.info('symlink: Unable to remove generator-xtc from node_modules\n');
		}
		throw e;
	}
}<commit_msg>un-derp<commit_after>#!/usr/bin/env node

// Must symlink the generator from xtc's modules up to the project's modules.
// Else Yeoman won't find it.

var path = require('path')
	,fs = require('fs')
	,util = require('util')
	,cwd = process.cwd()
	,src = path.join(cwd, '/node_modules/generator-xtc')
	,dest = path.resolve(cwd, '../generator-xtc')
;

if ('install' === process.env.npm_lifecycle_event) {

	try {
		fs.symlinkSync(src, dest, 'dir');
		console.log('symlink: generator-xtc into node_modules\n')
	} catch (e) {
		if ('EEXIST' === e.code) {
			console.info('symlink: generator-xtc already exists in node_modules\n');
		}
		else if ('EPERM' === e.code) {
			throw new Error(util.format('Permission error: creating symlink to generator-xtc\n%s --> %s\n', src, dest));
		}
		else {
			throw e;
		}
	}
}

// And of course we remove it again before xtc is uninstalled

else if ('uninstall' === process.env.npm_lifecycle_event) {

	try {
		fs.unlinkSync(dest, 'dir');
		console.log('symlink: removed generator-xtc from node_modules\n')
	} catch (e) {
		if ('ENOENT' !== e.code) {
			console.info('symlink: Unable to remove generator-xtc from node_modules\n');
		}
		throw e;
	}
}<|endoftext|>


<commit_before>var namespace = { window : {} };
utils.include('boxObject.js', namespace, 'Shift_JIS');

var sv;
var markupDocumentViewer;

function setUp()
{
	sv = {};
	sv.__proto__ = namespace.window['piro.sakura.ne.jp'].boxObject;

	yield Do(utils.loadURI('fixtures/box.html'));
	content.scrollTo(content.scrollMaxX+10, content.scrollMaxY+10);
}

function tearDown()
{
}

function test__getFrameOwnerFromFrame()
{
	assert.equals(gBrowser, sv._getFrameOwnerFromFrame(content));

	yield Do(utils.loadURI('fixtures/frame.html'));
	assert.equals(gBrowser, sv._getFrameOwnerFromFrame(content));
	assert.equals($('frame2'), sv._getFrameOwnerFromFrame($('frame2').contentWindow));
}

test_getBoxObjectFromBoxObjectFor.setUp = function()
{
	yield Do(utils.loadURI('fixtures/box.xul'));
}
function test_getBoxObjectFromBoxObjectFor()
{
	var button = $('button');
	var originalBox = button.boxObject;
	var box = {
			x       : originalBox.x,
			y       : originalBox.y,
			width   : originalBox.width,
			height  : originalBox.height,
			screenX : originalBox.screenX,
			screenY : originalBox.screenY
		};
	assert.equals(box, sv.getBoxObjectFromBoxObjectFor(button, false));
	assert.equals(box, sv.getBoxObjectFromBoxObjectFor(button));

	var rect = button.getBoundingClientRect();
	box.left   = Math.round(rect.left);
	box.top    = Math.round(rect.top);
	box.right  = Math.round(rect.right);
	box.bottom = Math.round(rect.bottom);
	assert.equals(box, sv.getBoxObjectFromBoxObjectFor(button, true));
}

function assertNearlyEqualBox(aExpected, aActual)
{
	assert.equals(aExpected.x, aActual.x);
	assert.equals(aExpected.y, aActual.y);
	assert.equals(aExpected.width, aActual.width);
	assert.equals(aExpected.height, aActual.height);
	if ('left' in aExpected) {
		assert.equals(aExpected.left, aActual.left);
		assert.equals(aExpected.right, aActual.right);
		assert.equals(aExpected.top, aActual.top);
		assert.equals(aExpected.bottom, aActual.bottom);
	}
	assert.inDelta(aExpected.screenY, aActual.screenY, 1);
	assert.inDelta(aExpected.screenX, aActual.screenX, 1);
}

function assertBoxObjectFromClientRect(aZoom)
{
	var root = content.document.documentElement;

	var containerBox = gBrowser.boxObject;
	var containerStyle = window.getComputedStyle(gBrowser, null);
	var baseX = containerBox.screenX + parseInt(containerStyle.getPropertyValue('border-left-width').replace('px', ''));
	var baseY = containerBox.screenY + parseInt(containerStyle.getPropertyValue('border-top-width').replace('px', ''));

	function assertBoxObject(aActualBox, aNode)
	{
		var box = {
				x       : aActualBox.x,
				y       : aActualBox.y,
				width   : aActualBox.width,
				height  : aActualBox.height,
				screenX : aActualBox.screenX,
				screenY : aActualBox.screenY
			};
		if (aZoom == 1) {
			assert.equal(box, sv.getBoxObjectFromClientRectFor(aNode, false));
			assert.equal(aActualBox, sv.getBoxObjectFromClientRectFor(aNode, true));
			assert.equal(box, sv.getBoxObjectFromClientRectFor(aNode));
		}
		else {
			assertNearlyEqualBox(box, sv.getBoxObjectFromClientRectFor(aNode, false));
			assertNearlyEqualBox(aActualBox, sv.getBoxObjectFromClientRectFor(aNode, true));
			assertNearlyEqualBox(box, sv.getBoxObjectFromClientRectFor(aNode));
		}
	}

	assertBoxObject(
		{
			x       : 2,
			y       : 2,
			width   : 100 + 2 + 2,
			height  : 100 + 2 + 2,
			screenX : baseX,
			screenY : baseY + (-content.scrollY * aZoom),
			left    : 0 - content.scrollX,
			top     : 0 - content.scrollY,
			right   : 100 + 2 + 2 - content.scrollX,
			bottom  : 100 + 2 + 2 - content.scrollY
		},
		$('positionedBoxStatic')
	);

	assertBoxObject(
		{
			x       : 100 + 3,
			y       : 100 + 2 + 2 + 30 + 3,
			width   : 100 + 3 + 3,
			height  : 100 + 3 + 3,
			screenX : baseX + (100 * aZoom),
			screenY : baseY + ((-content.scrollY + 100 + 2 + 2 + 30) * aZoom),
			left    : 100 - content.scrollX,
			top     : 100 + 2 + 2 - content.scrollY + 30,
			right   : 100 - content.scrollX + 100 + 3 + 3,
			bottom  : 100 + 2 + 2 - content.scrollY + 30 + 100 + 3 + 3
		},
		$('positionedBoxRelative')
	);

	assertBoxObject(
		{
			x       : root.offsetWidth - 100 - 4 - 4 - 10 + 4,
			y       : 10 + 4,
			width   : 100 + 4 + 4,
			height  : 100 + 4 + 4,
			screenX : baseX + ((root.offsetWidth - 100 - 4 - 4 - 10) * aZoom),
			screenY : baseY + ((-content.scrollY + 5 + 5) * aZoom),
			left    : root.offsetWidth - 100 - 4 - 4 - 10 - content.scrollX,
			top     : 10 - content.scrollY,
			right   : root.offsetWidth - 100 - 4 - 4 - 10 - content.scrollX + 100 + 4 + 4,
			bottom  : 10 - content.scrollY + 100 + 4 + 4
		},
		$('positionedBoxAbsolute')
	);

	assertBoxObject(
		{
			x       : 40 + 5,
			y       : 30 + 5,
			width   : 100 + 5 + 5,
			height  : 100 + 5 + 5,
			screenX : baseX + (40 * aZoom),
			screenY : baseY + (30 * aZoom),
			left    : 40,
			top     : 30,
			right   : 100 + 5 + 5 + 40,
			bottom  : 100 + 5 + 5 + 30
		},
		$('positionedBoxFixed')
	);

/*
	function assertCompareBoxObjects(aNode)
	{
		var actualBox = sv.getBoxObjectFromBoxObjectFor(aNode, true);
		var box = sv.getBoxObjectFromClientRectFor(aNode, true);
		assert.equals(actualBox, box);
	}

	assertCompareBoxObjects($('positionedBoxStatic'));
	assertCompareBoxObjects($('positionedBoxRelative'));
	assertCompareBoxObjects($('positionedBoxAbsolute'));
	assertCompareBoxObjects($('positionedBoxFixed'));
*/
}

function test_getBoxObjectFromClientRectFor()
{
	assertBoxObjectFromClientRect(1);
}

test_getBoxObjectFromSomethingFor_withZoom.setUp = function()
{
	utils.setPref('browser.zoom.full', true);
	markupDocumentViewer = content
		.QueryInterface(Ci.nsIInterfaceRequestor)
		.getInterface(Ci.nsIWebNavigation)
		.QueryInterface(Ci.nsIDocShell)
		.contentViewer
		.QueryInterface(Ci.nsIMarkupDocumentViewer);
	markupDocumentViewer.fullZoom = 2;
}
test_getBoxObjectFromSomethingFor_withZoom.tearDown = function()
{
	markupDocumentViewer.fullZoom = 1;
	markupDocumentViewer = null;
}
function test_getBoxObjectFromSomethingFor_withZoom()
{
	assertBoxObjectFromClientRect(2);
}
<commit_msg>テストコード修正<commit_after>var namespace = { window : {} };
utils.include('boxObject.js', namespace, 'Shift_JIS');

var sv;
var markupDocumentViewer;

function setUp()
{
	sv = {};
	sv.__proto__ = namespace.window['piro.sakura.ne.jp'].boxObject;

	yield Do(utils.loadURI('fixtures/box.html'));
	content.scrollTo(content.scrollMaxX+10, content.scrollMaxY+10);
}

function tearDown()
{
}

test_getBoxObjectFromBoxObjectFor.setUp = function()
{
	yield Do(utils.loadURI('fixtures/box.xul'));
}
function test_getBoxObjectFromBoxObjectFor()
{
	var button = $('button');
	var originalBox = button.boxObject;
	var box = {
			element : button,
			x       : originalBox.x,
			y       : originalBox.y,
			width   : originalBox.width,
			height  : originalBox.height,
			screenX : originalBox.screenX,
			screenY : originalBox.screenY
		};
	assert.equals(box, sv.getBoxObjectFromBoxObjectFor(button, false));
	assert.equals(box, sv.getBoxObjectFromBoxObjectFor(button));

	var rect = button.getBoundingClientRect();
	box.left   = Math.ceil(rect.left);
	box.top    = Math.ceil(rect.top);
	box.right  = Math.ceil(rect.right);
	box.bottom = Math.ceil(rect.bottom);
	assert.equals(box, sv.getBoxObjectFromBoxObjectFor(button, true));
}

function assertNearlyEqualBox(aExpected, aActual)
{
	assert.equals(aExpected.x, aActual.x);
	assert.equals(aExpected.y, aActual.y);
	assert.equals(aExpected.width, aActual.width);
	assert.equals(aExpected.height, aActual.height);
	if ('left' in aExpected) {
		assert.equals(aExpected.left, aActual.left);
		assert.equals(aExpected.right, aActual.right);
		assert.equals(aExpected.top, aActual.top);
		assert.equals(aExpected.bottom, aActual.bottom);
	}
	assert.inDelta(aExpected.screenY, aActual.screenY, 1);
	assert.inDelta(aExpected.screenX, aActual.screenX, 1);
}

function assertBoxObjectFromClientRect(aZoom)
{
	var root = content.document.documentElement;

	var containerBox = gBrowser.boxObject;
	var containerStyle = window.getComputedStyle(gBrowser, null);
	var baseX = containerBox.screenX + parseInt(containerStyle.getPropertyValue('border-left-width').replace('px', ''));
	var baseY = containerBox.screenY + parseInt(containerStyle.getPropertyValue('border-top-width').replace('px', ''));

	function assertBoxObject(aActualBox, aNode)
	{
		var box = {
				element : aNode,
				x       : aActualBox.x,
				y       : aActualBox.y,
				width   : aActualBox.width,
				height  : aActualBox.height,
				screenX : aActualBox.screenX,
				screenY : aActualBox.screenY
			};
		if (aZoom == 1) {
			assert.equal(box, sv.getBoxObjectFromClientRectFor(aNode, false));
			assert.equal(aActualBox, sv.getBoxObjectFromClientRectFor(aNode, true));
			assert.equal(box, sv.getBoxObjectFromClientRectFor(aNode));
		}
		else {
			assertNearlyEqualBox(box, sv.getBoxObjectFromClientRectFor(aNode, false));
			assertNearlyEqualBox(aActualBox, sv.getBoxObjectFromClientRectFor(aNode, true));
			assertNearlyEqualBox(box, sv.getBoxObjectFromClientRectFor(aNode));
		}
	}

	assertBoxObject(
		{
			element : $('positionedBoxStatic'),
			x       : 2,
			y       : 2,
			width   : 100 + 2 + 2,
			height  : 100 + 2 + 2,
			screenX : baseX,
			screenY : baseY + (-content.scrollY * aZoom),
			left    : 0 - content.scrollX,
			top     : 0 - content.scrollY,
			right   : 100 + 2 + 2 - content.scrollX,
			bottom  : 100 + 2 + 2 - content.scrollY
		},
		$('positionedBoxStatic')
	);

	assertBoxObject(
		{
			element : $('positionedBoxRelative'),
			x       : 100 + 3,
			y       : 100 + 2 + 2 + 30 + 3,
			width   : 100 + 3 + 3,
			height  : 100 + 3 + 3,
			screenX : baseX + (100 * aZoom),
			screenY : baseY + ((-content.scrollY + 100 + 2 + 2 + 30) * aZoom),
			left    : 100 - content.scrollX,
			top     : 100 + 2 + 2 - content.scrollY + 30,
			right   : 100 - content.scrollX + 100 + 3 + 3,
			bottom  : 100 + 2 + 2 - content.scrollY + 30 + 100 + 3 + 3
		},
		$('positionedBoxRelative')
	);

	assertBoxObject(
		{
			element : $('positionedBoxAbsolute'),
			x       : root.offsetWidth - 100 - 4 - 4 - 10 + 4,
			y       : 10 + 4,
			width   : 100 + 4 + 4,
			height  : 100 + 4 + 4,
			screenX : baseX + ((root.offsetWidth - 100 - 4 - 4 - 10) * aZoom),
			screenY : baseY + ((-content.scrollY + 5 + 5) * aZoom),
			left    : root.offsetWidth - 100 - 4 - 4 - 10 - content.scrollX,
			top     : 10 - content.scrollY,
			right   : root.offsetWidth - 100 - 4 - 4 - 10 - content.scrollX + 100 + 4 + 4,
			bottom  : 10 - content.scrollY + 100 + 4 + 4
		},
		$('positionedBoxAbsolute')
	);

	assertBoxObject(
		{
			element : $('positionedBoxFixed'),
			x       : 40 + 5,
			y       : 30 + 5,
			width   : 100 + 5 + 5,
			height  : 100 + 5 + 5,
			screenX : baseX + (40 * aZoom),
			screenY : baseY + (30 * aZoom),
			left    : 40,
			top     : 30,
			right   : 100 + 5 + 5 + 40,
			bottom  : 100 + 5 + 5 + 30
		},
		$('positionedBoxFixed')
	);

/*
	function assertCompareBoxObjects(aNode)
	{
		var actualBox = sv.getBoxObjectFromBoxObjectFor(aNode, true);
		var box = sv.getBoxObjectFromClientRectFor(aNode, true);
		assert.equals(actualBox, box);
	}

	assertCompareBoxObjects($('positionedBoxStatic'));
	assertCompareBoxObjects($('positionedBoxRelative'));
	assertCompareBoxObjects($('positionedBoxAbsolute'));
	assertCompareBoxObjects($('positionedBoxFixed'));
*/
}

function test_getBoxObjectFromClientRectFor()
{
	assertBoxObjectFromClientRect(1);
}

test_getBoxObjectFromSomethingFor_withZoom.setUp = function()
{
	utils.setPref('browser.zoom.full', true);
	markupDocumentViewer = content
		.QueryInterface(Ci.nsIInterfaceRequestor)
		.getInterface(Ci.nsIWebNavigation)
		.QueryInterface(Ci.nsIDocShell)
		.contentViewer
		.QueryInterface(Ci.nsIMarkupDocumentViewer);
	markupDocumentViewer.fullZoom = 2;
}
test_getBoxObjectFromSomethingFor_withZoom.tearDown = function()
{
	markupDocumentViewer.fullZoom = 1;
	markupDocumentViewer = null;
}
function test_getBoxObjectFromSomethingFor_withZoom()
{
	assertBoxObjectFromClientRect(2);
}
<|endoftext|>