<commit_before>var Env = require('./config/env.js');

var mongoose = require('mongoose');
mongoose.connect(Env.MONGO_CONNECTION_STRING);
var Order = require('./models/order.js');

var winston = require('winston');
winston.add(winston.transports.File, { filename: 'listener.log' });

var ReadWriteLock = require('rwlock');
var lock = new ReadWriteLock();

var CoinbaseExchange = require('coinbase-exchange');
var authedClient = new CoinbaseExchange.AuthenticatedClient(Env.ACCESS_KEY, Env.SECRET_KEY, Env.PASSPHRASE_KEY, Env.REST_URL);
var websocket = new CoinbaseExchange.WebsocketClient('BTC-USD', Env.SOCKET_URL);

websocket.on('close', function(data){

  winston.log('info', "Closing?");
  winston.log('info', JSON.stringify(data));

  process.exit(-1);

});

winston.log('info', "Listening for messages...");

websocket.on('message', function(data) {

  if(data.type == 'done' && data.reason == 'filled'){

    lock.writeLock(function (writeRelease) {

      Order.findOne({ id : data.order_id }, function(err, foundOrder){

        // Verify that we found a video with that ID
        if(err){
           winston.log('info', "Failed to find order " + data.order_id + " with error " + err);
           writeRelease();
           return;
        }

        // If we are not tracking this order then just bail
        if(!foundOrder){
          writeRelease();
          return;
        }

        winston.log('info', "------------------------------------------------------------");
        winston.log('info', data);

        var closedOrder = foundOrder;
        winston.log('info', "Closed Order: " + JSON.stringify(closedOrder));

        if(closedOrder.side == 'buy' ){

          // Create a sell order at old price + $1
          winston.log('info', "Closed buy order found.  Creating new sell order at price + 1");

          var orderToCreate = {
            size : closedOrder.size,
            price : (Number(closedOrder.price) + ( 1 * Env.GAP_AMOUNT)).toFixed(2) ,
            side : "sell",
            product_id : "BTC-USD"
          };

          winston.log("info", JSON.stringify(orderToCreate));

          authedClient.sell(orderToCreate, function(error, response, data){

            if (error || response.statusCode != 200) {
              winston.log('error', "Error creating new sell order: " + error);
              winston.log('error', "Response: " + JSON.stringify(response));
              winston.log('info', "Trying again in 1 second...");

              setTimeout(function() {
                authedClient.sell(orderToCreate, function(error, response, data){
                  if (error || response.statusCode != 200) {
                    winston.log('error', "Failed again... bailing");
                    writeRelease;
                    return;
                  }

                  // Add the new sell order to the existing order list
                  orderToCreate.id = data.id;
                  winston.log('info', "Created Order: " + JSON.stringify(orderToCreate));

                  Order(orderToCreate).save(function(error){

                    if(error){
                      winston.log('error', "Failed to create order" + orderToCreate.id + " with errro " + error);
                      writeRelease();
                      return;
                    }

                    closedOrder.remove(function(error){
                      if(error){
                        winston.log('error', "Failed to remove order" + closedOrder.id + " with errro " + error);
                        writeRelease();
                        return;
                      }
                    });

                  });

                });
              }, 1000);

            }

            // Add the new sell order to the existing order list
            orderToCreate.id = data.id;
            winston.log('info', "Created Order: " + JSON.stringify(orderToCreate));

            Order(orderToCreate).save(function(error){

              if(error){
                winston.log('error', "Failed to create order" + orderToCreate.id + " with errro " + error);
                writeRelease();
                return;
              }

              closedOrder.remove(function(error){
                if(error){
                  winston.log('error', "Failed to remove order" + closedOrder.id + " with errro " + error);
                  writeRelease();
                  return;
                }
              });

            });

          });

        } else {

          // Create a buy order at old price - $1
          winston.log('info', "Closed sell order found.  Creating new buy order at price - 1");

          var orderToCreate = {
            size : closedOrder.size,
            price : (Number(closedOrder.price) - ( 1 * Env.GAP_AMOUNT)).toFixed(2) ,
            side : "buy",
            product_id : "BTC-USD"
          };

          winston.log("info", JSON.stringify(orderToCreate));

          authedClient.buy(orderToCreate, function(error, response, data){

            if (error || response.statusCode != 200) {
              winston.log('error', "Error creating new buy order: " + error);
              winston.log('error', "Response: " + JSON.stringify(response));
              winston.log('info', "Trying again in 1 second...");

              setTimeout(function() {
                authedClient.buy(orderToCreate, function(error, response, data){
                  if (error || response.statusCode != 200) {
                    winston.log('error', "Failed again... bailing");
                    writeRelease;
                    return;
                  }

                  // Add the new sell order to the existing order list
                  orderToCreate.id = data.id;
                  winston.log('info', "Created Order: " + JSON.stringify(orderToCreate));

                  Order(orderToCreate).save(function(error){

                    if(error){
                      winston.log('error', "Failed to create order" + orderToCreate.id + " with errro " + error);
                      writeRelease();
                      return;
                    }

                    closedOrder.remove(function(error){
                      if(error){
                        winston.log('error', "Failed to remove order" + closedOrder.id + " with errro " + error);
                        writeRelease();
                        return;
                      }
                    });

                  });

                });
              }, 1000);
            }

            // Add the new sell order to the existing order list
            orderToCreate.id = data.id;
            winston.log('info', "Created Order: " + JSON.stringify(orderToCreate));

            Order(orderToCreate).save(function(error){

              if(error){
                winston.log('error', "Failed to create order" + orderToCreate.id + " with errro " + error);
                writeRelease();
                return;
              }

              closedOrder.remove(function(error){
                if(error){
                  winston.log('error', "Failed to remove order" + closedOrder.id + " with errro " + error);
                  writeRelease();
                  return;
                }
              });

            });

          });

        }

      });

    });

  }

});
<commit_msg>added lock release back in<commit_after>var Env = require('./config/env.js');

var mongoose = require('mongoose');
mongoose.connect(Env.MONGO_CONNECTION_STRING);
var Order = require('./models/order.js');

var winston = require('winston');
winston.add(winston.transports.File, { filename: 'listener.log' });

var ReadWriteLock = require('rwlock');
var lock = new ReadWriteLock();

var CoinbaseExchange = require('coinbase-exchange');
var authedClient = new CoinbaseExchange.AuthenticatedClient(Env.ACCESS_KEY, Env.SECRET_KEY, Env.PASSPHRASE_KEY, Env.REST_URL);
var websocket = new CoinbaseExchange.WebsocketClient('BTC-USD', Env.SOCKET_URL);

websocket.on('close', function(data){

  winston.log('info', "Closing?");
  winston.log('info', JSON.stringify(data));

  process.exit(-1);

});

winston.log('info', "Listening for messages...");

websocket.on('message', function(data) {

  if(data.type == 'done' && data.reason == 'filled'){

    lock.writeLock(function (writeRelease) {

      Order.findOne({ id : data.order_id }, function(err, foundOrder){

        // Verify that we found a video with that ID
        if(err){
           winston.log('info', "Failed to find order " + data.order_id + " with error " + err);
           writeRelease();
           return;
        }

        // If we are not tracking this order then just bail
        if(!foundOrder){
          writeRelease();
          return;
        }

        winston.log('info', "------------------------------------------------------------");
        winston.log('info', data);

        var closedOrder = foundOrder;
        winston.log('info', "Closed Order: " + JSON.stringify(closedOrder));

        if(closedOrder.side == 'buy' ){

          // Create a sell order at old price + $1
          winston.log('info', "Closed buy order found.  Creating new sell order at price + 1");

          var orderToCreate = {
            size : closedOrder.size,
            price : (Number(closedOrder.price) + ( 1 * Env.GAP_AMOUNT)).toFixed(2) ,
            side : "sell",
            product_id : "BTC-USD"
          };

          winston.log("info", JSON.stringify(orderToCreate));

          authedClient.sell(orderToCreate, function(error, response, data){

            if (error || response.statusCode != 200) {
              winston.log('error', "Error creating new sell order: " + error);
              winston.log('error', "Response: " + JSON.stringify(response));
              winston.log('info', "Trying again in 1 second...");

              setTimeout(function() {
                authedClient.sell(orderToCreate, function(error, response, data){
                  if (error || response.statusCode != 200) {
                    winston.log('error', "Failed again... bailing");
                    writeRelease;
                    return;
                  }

                  // Add the new sell order to the existing order list
                  orderToCreate.id = data.id;
                  winston.log('info', "Created Order: " + JSON.stringify(orderToCreate));

                  Order(orderToCreate).save(function(error){

                    if(error){
                      winston.log('error', "Failed to create order" + orderToCreate.id + " with errro " + error);
                      writeRelease();
                      return;
                    }

                    closedOrder.remove(function(error){
                      if(error){
                        winston.log('error', "Failed to remove order" + closedOrder.id + " with errro " + error);
                        writeRelease();
                        return;
                      }
                    });

                  });

                });
              }, 1000);

            }

            // Add the new sell order to the existing order list
            orderToCreate.id = data.id;
            winston.log('info', "Created Order: " + JSON.stringify(orderToCreate));

            Order(orderToCreate).save(function(error){

              if(error){
                winston.log('error', "Failed to create order" + orderToCreate.id + " with errro " + error);
                writeRelease();
                return;
              }

              closedOrder.remove(function(error){
                if(error){
                  winston.log('error', "Failed to remove order" + closedOrder.id + " with errro " + error);
                  writeRelease();
                  return;
                }
              });

            });

          });

        } else {

          // Create a buy order at old price - $1
          winston.log('info', "Closed sell order found.  Creating new buy order at price - 1");

          var orderToCreate = {
            size : closedOrder.size,
            price : (Number(closedOrder.price) - ( 1 * Env.GAP_AMOUNT)).toFixed(2) ,
            side : "buy",
            product_id : "BTC-USD"
          };

          winston.log("info", JSON.stringify(orderToCreate));

          authedClient.buy(orderToCreate, function(error, response, data){

            if (error || response.statusCode != 200) {
              winston.log('error', "Error creating new buy order: " + error);
              winston.log('error', "Response: " + JSON.stringify(response));
              winston.log('info', "Trying again in 1 second...");

              setTimeout(function() {
                authedClient.buy(orderToCreate, function(error, response, data){
                  if (error || response.statusCode != 200) {
                    winston.log('error', "Failed again... bailing");
                    writeRelease;
                    return;
                  }

                  // Add the new sell order to the existing order list
                  orderToCreate.id = data.id;
                  winston.log('info', "Created Order: " + JSON.stringify(orderToCreate));

                  Order(orderToCreate).save(function(error){

                    if(error){
                      winston.log('error', "Failed to create order" + orderToCreate.id + " with errro " + error);
                      writeRelease();
                      return;
                    }

                    closedOrder.remove(function(error){
                      if(error){
                        winston.log('error', "Failed to remove order" + closedOrder.id + " with errro " + error);
                        writeRelease();
                        return;
                      }
                    });

                  });

                });
              }, 1000);
            }

            // Add the new sell order to the existing order list
            orderToCreate.id = data.id;
            winston.log('info', "Created Order: " + JSON.stringify(orderToCreate));

            Order(orderToCreate).save(function(error){

              if(error){
                winston.log('error', "Failed to create order" + orderToCreate.id + " with errro " + error);
                writeRelease();
                return;
              }

              closedOrder.remove(function(error){
                if(error){
                  winston.log('error', "Failed to remove order" + closedOrder.id + " with errro " + error);
                  writeRelease();
                  return;
                }
              });

            });

          });

        }

      });

      writeRelease();

    });

  }

});
<|endoftext|>


<commit_before>'use strict';

const every = require('lodash/every');
const requiredMethods = [
    'start',
    'stop',
    'isRunning'
];
const enableMethods = [
    'isEnabled',
    'enable',
    'disable'
];

class ProcessManager {
    /**
     * Constructs the process manager. Process Managers get access to the UI and System instances
     *
     * @param {UI} ui UI instance
     * @param {System} system System
     * @param {Instance} instance Ghost instance
     */
    constructor(ui, system, instance) {
        this.ui = ui;
        this.system = system;
        this.instance = instance;
    }

    /**
     * Method called to start the Ghost process
     *
     * @param {String} cwd Current working directory of Ghost instance
     * @param {String} environment Environment to start Ghost in
     * @return Promise<void>|null
     */
    async start() {}
    async stop() {}

    async restart(cwd, env) {
        await this.stop(cwd, env);
        await this.start(cwd, env);
    }

    /* istanbul ignore next */
    success() {
        // Base implementation - noop
    }

    error(error) {
        // Base implementation - re-throw the error in case the
        // extension has no error method defined
        throw error;
    }

    async isRunning() {
        return false;
    }

    /**
     * General implementation of figuring out if the Ghost blog has started successfully.
     *
     * @returns {Promise<any>}
     */
    async ensureStarted(options) {
        const portPolling = require('./utils/port-polling');
        const semver = require('semver');

        options = Object.assign({
            stopOnError: true,
            port: this.instance.config.get('server.port'),
            host: this.instance.config.get('server.host', 'localhost'),
            useNetServer: semver.major(this.instance.version) === 2
        }, options || {});

        try {
            await portPolling(options);
        } catch (error) {
            if (options.stopOnError) {
                try {
                    await this.stop();
                } catch (e) {
                    // ignore stop error
                }
            }

            throw error;
        }
    }

    /**
     * This function checks if this process manager can be used on this system
     *
     * @return {Boolean} whether or not the process manager can be used
     */
    static willRun() {
        // Base implementation - return true
        return true;
    }
}

function isValid(SubClass) {
    if (!(SubClass.prototype instanceof ProcessManager)) {
        return false;
    }

    const missing = requiredMethods.filter(method => !Object.prototype.hasOwnProperty.call(SubClass, method));

    if (!missing.length) {
        return true;
    }

    return missing;
}

function supportsEnableBehavior(processInstance) {
    return every(enableMethods, method => processInstance[method]);
}

module.exports = ProcessManager;
module.exports.isValid = isValid;
module.exports.supportsEnableBehavior = supportsEnableBehavior;
<commit_msg>fix test issue<commit_after>'use strict';

const every = require('lodash/every');
const requiredMethods = [
    'start',
    'stop',
    'isRunning'
];
const enableMethods = [
    'isEnabled',
    'enable',
    'disable'
];

class ProcessManager {
    /**
     * Constructs the process manager. Process Managers get access to the UI and System instances
     *
     * @param {UI} ui UI instance
     * @param {System} system System
     * @param {Instance} instance Ghost instance
     */
    constructor(ui, system, instance) {
        this.ui = ui;
        this.system = system;
        this.instance = instance;
    }

    /**
     * Method called to start the Ghost process
     *
     * @param {String} cwd Current working directory of Ghost instance
     * @param {String} environment Environment to start Ghost in
     * @return Promise<void>|null
     */
    async start() {}
    async stop() {}

    async restart(cwd, env) {
        await this.stop(cwd, env);
        await this.start(cwd, env);
    }

    /* istanbul ignore next */
    success() {
        // Base implementation - noop
    }

    error(error) {
        // Base implementation - re-throw the error in case the
        // extension has no error method defined
        throw error;
    }

    async isRunning() {
        return false;
    }

    /**
     * General implementation of figuring out if the Ghost blog has started successfully.
     *
     * @returns {Promise<any>}
     */
    async ensureStarted(options) {
        const portPolling = require('./utils/port-polling');
        const semver = require('semver');

        options = Object.assign({
            stopOnError: true,
            port: this.instance.config.get('server.port'),
            host: this.instance.config.get('server.host', 'localhost'),
            useNetServer: semver.major(this.instance.version) === 2
        }, options || {});

        try {
            await portPolling(options);
        } catch (error) {
            if (options.stopOnError) {
                try {
                    await this.stop();
                } catch (e) {
                    // ignore stop error
                }
            }

            throw error;
        }
    }

    /**
     * This function checks if this process manager can be used on this system
     *
     * @return {Boolean} whether or not the process manager can be used
     */
    static willRun() {
        // Base implementation - return true
        return true;
    }
}

function isValid(SubClass) {
    if (!(SubClass.prototype instanceof ProcessManager)) {
        return false;
    }

    const missing = requiredMethods.filter(method => !Object.prototype.hasOwnProperty.call(SubClass.prototype, method));

    if (!missing.length) {
        return true;
    }

    return missing;
}

function supportsEnableBehavior(processInstance) {
    return every(enableMethods, method => processInstance[method]);
}

module.exports = ProcessManager;
module.exports.isValid = isValid;
module.exports.supportsEnableBehavior = supportsEnableBehavior;
<|endoftext|>


<commit_before>import fs from 'fs';
import path from 'path';
import loaderUtils from 'loader-utils';

const cache = {};

export default class {
    constructor(filename, config) {
        this.sourcePath = path.resolve(filename);
        this.config = config;
        this.sourceLayerIndex = this.getSourceLayerIndex();
        this.remainingLayers = config.layers.slice(0, this.sourceLayerIndex + 1);
    }

    getSourceLayerIndex() {
        for (let i = 0; i < this.config.layers.length; i++) {
            if (this.sourcePath.indexOf(this.config.layers[i]) === 0) {
                return i;
            }
        }

        return this.config.layers.length - 1;
    }

    parseRequiredString(requiredString) {
        const [ rawComponent, rawOpts ] = requiredString.split('?');
        const component = rawComponent.substr(this.config.prefix.length);
        const opts = {};
        let mods = {};

        if (rawOpts) {
            const parsedOpts = loaderUtils.parseQuery('?' + rawOpts);

            Object.keys(parsedOpts).forEach(optName => {
                const optVal = parsedOpts[optName];

                // mods
                if (optName.charAt(0) === '_') {
                    mods = {
                        ...mods,
                        [optName]: optVal
                    };
                // rest
                } else {
                    opts[optName] = optVal;
                }
            });
        }

        return {
            component,
            mods,
            opts
        };
    }

    collectPaths(required) {
        const out = [];

        this.remainingLayers.forEach(layer => {
            const pathToCheck = path.join(layer, required);

            // self-require guard
            if (pathToCheck === this.sourcePath) {
                return;
            }

            // main
            if (this.config.files.main) {
                out.push({
                    type: 'main',
                    path: path.join(pathToCheck, this.config.files.main)
                });
            }

            // styles
            if (this.required.opts.styles !== false && this.config.files.styles) {
                out.push({
                    type: 'styles',
                    path: path.join(pathToCheck, this.config.files.styles)
                });
            }

            // propTypes
            if (this.required.opts.propTypes !== false && this.config.files.propTypes) {
                out.push({
                    type: 'propTypes',
                    path: path.join(pathToCheck, this.config.files.propTypes)
                });
            }
        });

        return out;
    }

    filterPaths(pathsObj) {
        return pathsObj.filter(pathObj => fs.existsSync(pathObj.path));
    }

    process(requiredString) {
        const uniqueKey = this.sourceLayerIndex + requiredString;

        if (uniqueKey in cache) {
            return cache[uniqueKey];
        }

        this.required = this.parseRequiredString(requiredString);

        const pathsToCheck = [];

        // collect paths to check
        pathsToCheck.push(...this.collectPaths(this.required.component));

        // also collect main component paths if modifier was required
        if (this.required.mods) {
            Object.keys(this.required.mods).forEach(modName => {
                const modVal = this.required.mods[modName];
                const pathToCheck = path.join(this.required.component, modName, modVal);

                pathsToCheck.push(...this.collectPaths(pathToCheck));
            });
        }

        const out = {
            method: this.required.opts.raw ? 'yummifyRaw' : 'yummify',
            items: this.filterPaths(pathsToCheck)
        };

        // cache it
        cache[uniqueKey] = out;

        return out;
    }
}
<commit_msg>:heavy_plus_sign: support boolean modifiers<commit_after>import fs from 'fs';
import path from 'path';
import loaderUtils from 'loader-utils';

const cache = {};

export default class {
    constructor(filename, config) {
        this.sourcePath = path.resolve(filename);
        this.config = config;
        this.sourceLayerIndex = this.getSourceLayerIndex();
        this.remainingLayers = config.layers.slice(0, this.sourceLayerIndex + 1);
    }

    getSourceLayerIndex() {
        for (let i = 0; i < this.config.layers.length; i++) {
            if (this.sourcePath.indexOf(this.config.layers[i]) === 0) {
                return i;
            }
        }

        return this.config.layers.length - 1;
    }

    parseRequiredString(requiredString) {
        const [ rawComponent, rawOpts ] = requiredString.split('?');
        const component = rawComponent.substr(this.config.prefix.length);
        const opts = {};
        let mods = {};

        if (rawOpts) {
            const parsedOpts = loaderUtils.parseQuery('?' + rawOpts);

            Object.keys(parsedOpts).forEach(optName => {
                const optVal = parsedOpts[optName];

                // mods
                if (optName.charAt(0) === '_') {
                    mods = {
                        ...mods,
                        [optName]: optVal
                    };
                // rest
                } else {
                    opts[optName] = optVal;
                }
            });
        }

        return {
            component,
            mods,
            opts
        };
    }

    collectPaths(required) {
        const out = [];

        this.remainingLayers.forEach(layer => {
            const pathToCheck = path.join(layer, required);

            // self-require guard
            if (pathToCheck === this.sourcePath) {
                return;
            }

            // main
            if (this.config.files.main) {
                out.push({
                    type: 'main',
                    path: path.join(pathToCheck, this.config.files.main)
                });
            }

            // styles
            if (this.required.opts.styles !== false && this.config.files.styles) {
                out.push({
                    type: 'styles',
                    path: path.join(pathToCheck, this.config.files.styles)
                });
            }

            // propTypes
            if (this.required.opts.propTypes !== false && this.config.files.propTypes) {
                out.push({
                    type: 'propTypes',
                    path: path.join(pathToCheck, this.config.files.propTypes)
                });
            }
        });

        return out;
    }

    filterPaths(pathsObj) {
        return pathsObj.filter(pathObj => fs.existsSync(pathObj.path));
    }

    process(requiredString) {
        const uniqueKey = this.sourceLayerIndex + requiredString;

        if (uniqueKey in cache) {
            return cache[uniqueKey];
        }

        this.required = this.parseRequiredString(requiredString);

        const pathsToCheck = [];

        // collect paths to check
        pathsToCheck.push(...this.collectPaths(this.required.component));

        // also collect main component paths if modifier was required
        if (this.required.mods) {
            Object.keys(this.required.mods).forEach(modName => {
                const modVal = this.required.mods[modName];
                let pathToCheck;

                if (modVal === true) {
                    pathToCheck = path.join(this.required.component, modName);
                } else {
                    pathToCheck = path.join(this.required.component, modName, modVal);
                }

                pathsToCheck.push(...this.collectPaths(pathToCheck));
            });
        }

        const out = {
            method: this.required.opts.raw ? 'yummifyRaw' : 'yummify',
            items: this.filterPaths(pathsToCheck)
        };

        // cache it
        cache[uniqueKey] = out;

        return out;
    }
}
<|endoftext|>


<commit_before>/**
 * node-compress-commons
 *
 * Copyright (c) 2014 Chris Talkington, contributors.
 * Licensed under the MIT license.
 * https://github.com/ctalkington/node-compress-commons/blob/master/LICENSE-MIT
 */
var inherits = require('util').inherits;
var crc32 = require('buffer-crc32');
var CRC32Stream = require('crc32-stream');
var DeflateCRC32Stream = CRC32Stream.DeflateCRC32Stream;

var ArchiveOutputStream = require('../archive-output-stream');
var ZipArchiveEntry = require('./zip-archive-entry');
var GeneralPurposeBit = require('./general-purpose-bit');

var constants = require('./constants');
var util = require('../../util');
var zipUtil = require('./util');

var ZipArchiveOutputStream = module.exports = function(options) {
  if (!(this instanceof ZipArchiveOutputStream)) {
    return new ZipArchiveOutputStream(options);
  }

  options = this.options = this._defaults(options);

  ArchiveOutputStream.call(this, options);

  this._entry = null;
  this._entries = [];
  this._archive = {
    centralLength: 0,
    centralOffset: 0,
    comment: '',
    finish: false,
    finished: false,
    processing: false
  };
};

inherits(ZipArchiveOutputStream, ArchiveOutputStream);

ZipArchiveOutputStream.prototype._afterAppend = function(ae) {
  this._entries.push(ae);

  if (ae.getGeneralPurposeBit().usesDataDescriptor()) {
    this._writeDataDescriptor(ae);
  }

  this._archive.processing = false;
  this._entry = null;

  if (this._archive.finish && !this._archive.finished) {
    this._finish();
  }
};

ZipArchiveOutputStream.prototype._appendBuffer = function(ae, source, callback) {
  if (source.length === 0) {
    ae.setMethod(constants.METHOD_STORED);
  }

  var method = ae.getMethod();

  if (method === constants.METHOD_STORED) {
    ae.setSize(source.length);
    ae.setCompressedSize(source.length);
    ae.setCrc(crc32.unsigned(source));
  }

  this._writeLocalFileHeader(ae);

  if (method === constants.METHOD_STORED) {
    this.write(source);
    this._afterAppend(ae);
    callback(null, ae);
    return;
  } else if (method === constants.METHOD_DEFLATED) {
    this._smartStream(ae, callback).end(source);
    return;
  } else {
    callback(new Error('compression method ' + method + ' not implemented'));
    return;
  }
};

ZipArchiveOutputStream.prototype._appendStream = function(ae, source, callback) {
  ae.getGeneralPurposeBit().useDataDescriptor(true);

  this._writeLocalFileHeader(ae);

  var smart = this._smartStream(ae, callback);
  source.pipe(smart);
};

ZipArchiveOutputStream.prototype._defaults = function(o) {
  if (typeof o !== 'object') {
    o = {};
  }

  if (typeof o.zlib !== 'object') {
    o.zlib = {};
  }

  if (typeof o.zlib.level !== 'number') {
    o.zlib.level = constants.ZLIB_BEST_SPEED;
  }

  return o;
};

ZipArchiveOutputStream.prototype._finish = function() {
  this._archive.centralOffset = this.offset;

  this._entries.forEach(function(ae) {
    this._writeCentralFileHeader(ae);
  }.bind(this));

  this._archive.centralLength = this.offset - this._archive.centralOffset;

  if (this.isZip64()) {
    this._writeCentralDirectoryZip64();
  }

  this._writeCentralDirectoryEnd();

  this._archive.processing = false;
  this._archive.finish = true;
  this._archive.finished = true;
  this.end();
};

ZipArchiveOutputStream.prototype._normalizeEntry = function(ae) {
  if (ae.getMethod() === -1) {
    ae.setMethod(constants.METHOD_DEFLATED);
  }

  if (ae.getMethod() === constants.METHOD_DEFLATED) {
    ae.getGeneralPurposeBit().useDataDescriptor(true);
    ae.setVersionNeededToExtract(constants.MIN_VERSION_DATA_DESCRIPTOR);
  }

  if (ae.getTime() === -1) {
    ae.setTime(new Date());
  }

  ae._offsets = {
    file: 0,
    data: 0,
    contents: 0,
  };
};

ZipArchiveOutputStream.prototype._smartStream = function(ae, callback) {
  var deflate = ae.getMethod() === constants.METHOD_DEFLATED;
  var process = deflate ? new DeflateCRC32Stream(this.options.zlib) : new CRC32Stream();

  function handleStuff(err) {
    ae.setCrc(process.digest());
    ae.setSize(process.size());
    ae.setCompressedSize(process.size(true));
    this._afterAppend(ae);
    callback(null, ae);
  }

  process.once('error', callback);
  process.once('end', handleStuff.bind(this));

  process.pipe(this, { end: false });

  return process;
};

ZipArchiveOutputStream.prototype._writeCentralDirectoryEnd = function() {
  var records = this._entries.length;
  var size = this._archive.centralLength;
  var offset = this._archive.centralOffset;

  if (this.isZip64()) {
    records = constants.ZIP64_MAGIC_SHORT;
    size = constants.ZIP64_MAGIC;
    offset = constants.ZIP64_MAGIC;
  }

  // signature
  this.write(zipUtil.getLongBytes(constants.SIG_EOCD));

  // disk numbers
  this.write(constants.SHORT_ZERO);
  this.write(constants.SHORT_ZERO);

  // number of entries
  this.write(zipUtil.getShortBytes(records));
  this.write(zipUtil.getShortBytes(records));

  // length and location of CD
  this.write(zipUtil.getLongBytes(size));
  this.write(zipUtil.getLongBytes(offset));

  // archive comment
  var comment = this.getComment();
  var commentLength = Buffer.byteLength(comment);
  this.write(zipUtil.getShortBytes(commentLength));
  this.write(comment);
};

ZipArchiveOutputStream.prototype._writeCentralDirectoryZip64 = function() {
  // signature
  this.write(constants.SIG_ZIP64_EOCD);

  // size of the ZIP64 EOCD record
  this.write(zipUtil.getEightBytes((constants.SHORT * 2) + (constants.LONG * 2) + (8 * 4)));

  // version made by
  this.write(zipUtil.getShortBytes((ae.getPlatform() << 8) | constants.VERSION_MADEBY));

  // version needed to extract
  this.write(zipUtil.getShortBytes(ae.getVersionNeededToExtract()));

  // disk numbers
  this.write(constants.LONG_ZERO);
  this.write(constants.LONG_ZERO);

  // number of entries
  this.write(zipUtil.getEightBytes(this._entries.length));
  this.write(zipUtil.getEightBytes(this._entries.length));

  // length and location of CD
  this.write(zipUtil.getEightBytes(this._archive.centralLength));
  this.write(zipUtil.getEightBytes(this._archive.centralOffset));

  // extensible data sector
  // not implemented at this time

  // end of central directory locator
  this.write(costants.SIG_ZIP64_EOCD_LOC);

  // disk number holding the ZIP64 EOCD record
  this.write(constants.LONG_ZERO);

  // relative offset of the ZIP64 EOCD record
  this.write(zipUtil.getEightBytes(this._archive.centralOffset + this._archive.centralLength));

  // total number of disks
  this.write(this.getLongBytes(1));
};

ZipArchiveOutputStream.prototype._writeCentralFileHeader = function(ae) {
  var gpb = ae.getGeneralPurposeBit();
  var method = ae.getMethod();
  var offsets = ae._offsets;

  var extraBuf;
  var size = ae.getSize();
  var compressedSize = ae.getCompressedSize();

  if (ae.isZip64() || offsets.file > constants.ZIP64_MAGIC) {
    size = constants.ZIP64_MAGIC;
    compressedSize = constants.ZIP64_MAGIC;

    ae.setVersionNeededToExtract(constants.MIN_VERSION_ZIP64);

    extraBuf = new Buffer(28);
    extraBuf.write(zipUtil.getShortBytes(constants.ZIP64_EXTRA_ID));
    extraBuf.write(zipUtil.getShortBytes(24));
    extraBuf.write(zipUtil.getEightBytes(ae.getSize()));
    extraBuf.write(zipUtil.getEightBytes(ae.getCompressedSize()));
    extraBuf.write(zipUtil.getEightBytes(offsets.file));
    ae.setExtra(extraBuf);
  }

  // signature
  this.write(zipUtil.getLongBytes(constants.SIG_CFH));

  // version made by
  this.write(zipUtil.getShortBytes((ae.getPlatform() << 8) | constants.VERSION_MADEBY));

  // version to extract and general bit flag
  this.write(zipUtil.getShortBytes(ae.getVersionNeededToExtract()));
  this.write(gpb.encode());

  // compression method
  this.write(zipUtil.getShortBytes(method));

  // datetime
  this.write(zipUtil.getLongBytes(ae.getTimeDos()));

  // crc32 checksum
  this.write(zipUtil.getLongBytes(ae.getCrc()));

  // sizes
  this.write(zipUtil.getLongBytes(compressedSize));
  this.write(zipUtil.getLongBytes(size));

  var name = ae.getName();
  var comment = ae.getComment();
  var extra = ae.getCentralDirectoryExtra();

  if (gpb.usesUTF8ForNames()) {
    name = new Buffer(name);
    comment = new Buffer(comment);
  }

  // name length
  this.write(zipUtil.getShortBytes(name.length));

  // extra length
  this.write(zipUtil.getShortBytes(extra.length));

  // comments length
  this.write(zipUtil.getShortBytes(comment.length));

  // disk number start
  this.write(constants.SHORT_ZERO);

  // internal attributes
  this.write(zipUtil.getShortBytes(ae.getInternalAttributes()));

  // external attributes
  this.write(zipUtil.getLongBytes(ae.getExternalAttributes()));

  // relative offset of LFH
  if (offsets.file > constants.ZIP64_MAGIC) {
    this.write(zipUtil.getLongBytes(constants.ZIP64_MAGIC));
  } else {
    this.write(zipUtil.getLongBytes(offsets.file));
  }

  // name
  this.write(name);

  // extra
  this.write(extra);

  // comment
  this.write(comment);
};

ZipArchiveOutputStream.prototype._writeDataDescriptor = function(ae) {
  // signature
  this.write(zipUtil.getLongBytes(constants.SIG_DD));

  // crc32 checksum
  this.write(zipUtil.getLongBytes(ae.getCrc()));

  // sizes
  if (ae.isZip64()) {
    this.write(zipUtil.getEightBytes(ae.getCompressedSize()));
    this.write(zipUtil.getEightBytes(ae.getSize()));
  } else {
    this.write(zipUtil.getLongBytes(ae.getCompressedSize()));
    this.write(zipUtil.getLongBytes(ae.getSize()));
  }
};

ZipArchiveOutputStream.prototype._writeLocalFileHeader = function(ae) {
  var gpb = ae.getGeneralPurposeBit();
  var method = ae.getMethod();
  var name = ae.getName();
  var extra = ae.getLocalFileDataExtra();

  if (ae.isZip64()) {
    gpb.useDataDescriptor(true);
  }

  if (gpb.usesUTF8ForNames()) {
    name = new Buffer(name);
  }

  ae._offsets.file = this.offset;

  // signature
  this.write(zipUtil.getLongBytes(constants.SIG_LFH));

  // version to extract and general bit flag
  this.write(zipUtil.getShortBytes(ae.getVersionNeededToExtract()));
  this.write(gpb.encode());

  // compression method
  this.write(zipUtil.getShortBytes(method));

  // datetime
  this.write(zipUtil.getLongBytes(ae.getTimeDos()));

  ae._offsets.data = this.offset;

  // crc32 checksum and sizes
  if (gpb.usesDataDescriptor()) {
    this.write(constants.LONG_ZERO);
    this.write(constants.LONG_ZERO);
    this.write(constants.LONG_ZERO);
  } else {
    this.write(zipUtil.getLongBytes(ae.getCrc()));
    this.write(zipUtil.getLongBytes(ae.getCompressedSize()));
    this.write(zipUtil.getLongBytes(ae.getSize()));
  }

  // name length
  this.write(zipUtil.getShortBytes(name.length));

  // extra length
  this.write(zipUtil.getShortBytes(extra.length));

  // name
  this.write(name);

  // extra
  this.write(extra);

  ae._offsets.contents = this.offset;
};

ZipArchiveOutputStream.prototype.getComment = function(comment) {
  return this._archive.comment !== null ? this._archive.comment : '';
};

ZipArchiveOutputStream.prototype.isZip64 = function() {
  return this._entries.length > constants.ZIP64_MAGIC_SHORT || this._archive.centralLength > constants.ZIP64_MAGIC || this._archive.centralOffset > constants.ZIP64_MAGIC;
};

ZipArchiveOutputStream.prototype.setComment = function(comment) {
  this._archive.comment = comment;
};<commit_msg>zip: few CS touch ups.<commit_after>/**
 * node-compress-commons
 *
 * Copyright (c) 2014 Chris Talkington, contributors.
 * Licensed under the MIT license.
 * https://github.com/ctalkington/node-compress-commons/blob/master/LICENSE-MIT
 */
var inherits = require('util').inherits;
var crc32 = require('buffer-crc32');
var CRC32Stream = require('crc32-stream');
var DeflateCRC32Stream = CRC32Stream.DeflateCRC32Stream;

var ArchiveOutputStream = require('../archive-output-stream');
var ZipArchiveEntry = require('./zip-archive-entry');
var GeneralPurposeBit = require('./general-purpose-bit');

var constants = require('./constants');
var util = require('../../util');
var zipUtil = require('./util');

var ZipArchiveOutputStream = module.exports = function(options) {
  if (!(this instanceof ZipArchiveOutputStream)) {
    return new ZipArchiveOutputStream(options);
  }

  options = this.options = this._defaults(options);

  ArchiveOutputStream.call(this, options);

  this._entry = null;
  this._entries = [];
  this._archive = {
    centralLength: 0,
    centralOffset: 0,
    comment: '',
    finish: false,
    finished: false,
    processing: false
  };
};

inherits(ZipArchiveOutputStream, ArchiveOutputStream);

ZipArchiveOutputStream.prototype._afterAppend = function(ae) {
  this._entries.push(ae);

  if (ae.getGeneralPurposeBit().usesDataDescriptor()) {
    this._writeDataDescriptor(ae);
  }

  this._archive.processing = false;
  this._entry = null;

  if (this._archive.finish && !this._archive.finished) {
    this._finish();
  }
};

ZipArchiveOutputStream.prototype._appendBuffer = function(ae, source, callback) {
  if (source.length === 0) {
    ae.setMethod(constants.METHOD_STORED);
  }

  var method = ae.getMethod();

  if (method === constants.METHOD_STORED) {
    ae.setSize(source.length);
    ae.setCompressedSize(source.length);
    ae.setCrc(crc32.unsigned(source));
  }

  this._writeLocalFileHeader(ae);

  if (method === constants.METHOD_STORED) {
    this.write(source);
    this._afterAppend(ae);
    callback(null, ae);
    return;
  } else if (method === constants.METHOD_DEFLATED) {
    this._smartStream(ae, callback).end(source);
    return;
  } else {
    callback(new Error('compression method ' + method + ' not implemented'));
    return;
  }
};

ZipArchiveOutputStream.prototype._appendStream = function(ae, source, callback) {
  ae.getGeneralPurposeBit().useDataDescriptor(true);

  this._writeLocalFileHeader(ae);

  var smart = this._smartStream(ae, callback);
  source.pipe(smart);
};

ZipArchiveOutputStream.prototype._defaults = function(o) {
  if (typeof o !== 'object') {
    o = {};
  }

  if (typeof o.zlib !== 'object') {
    o.zlib = {};
  }

  if (typeof o.zlib.level !== 'number') {
    o.zlib.level = constants.ZLIB_BEST_SPEED;
  }

  return o;
};

ZipArchiveOutputStream.prototype._finish = function() {
  this._archive.centralOffset = this.offset;

  this._entries.forEach(function(ae) {
    this._writeCentralFileHeader(ae);
  }.bind(this));

  this._archive.centralLength = this.offset - this._archive.centralOffset;

  if (this.isZip64()) {
    this._writeCentralDirectoryZip64();
  }

  this._writeCentralDirectoryEnd();

  this._archive.processing = false;
  this._archive.finish = true;
  this._archive.finished = true;
  this.end();
};

ZipArchiveOutputStream.prototype._normalizeEntry = function(ae) {
  if (ae.getMethod() === -1) {
    ae.setMethod(constants.METHOD_DEFLATED);
  }

  if (ae.getMethod() === constants.METHOD_DEFLATED) {
    ae.getGeneralPurposeBit().useDataDescriptor(true);
    ae.setVersionNeededToExtract(constants.MIN_VERSION_DATA_DESCRIPTOR);
  }

  if (ae.getTime() === -1) {
    ae.setTime(new Date());
  }

  ae._offsets = {
    file: 0,
    data: 0,
    contents: 0,
  };
};

ZipArchiveOutputStream.prototype._smartStream = function(ae, callback) {
  var deflate = ae.getMethod() === constants.METHOD_DEFLATED;
  var process = deflate ? new DeflateCRC32Stream(this.options.zlib) : new CRC32Stream();

  function handleStuff(err) {
    ae.setCrc(process.digest());
    ae.setSize(process.size());
    ae.setCompressedSize(process.size(true));
    this._afterAppend(ae);
    callback(null, ae);
  }

  process.once('error', callback);
  process.once('end', handleStuff.bind(this));

  process.pipe(this, { end: false });

  return process;
};

ZipArchiveOutputStream.prototype._writeCentralDirectoryEnd = function() {
  var records = this._entries.length;
  var size = this._archive.centralLength;
  var offset = this._archive.centralOffset;

  if (this.isZip64()) {
    records = constants.ZIP64_MAGIC_SHORT;
    size = constants.ZIP64_MAGIC;
    offset = constants.ZIP64_MAGIC;
  }

  // signature
  this.write(zipUtil.getLongBytes(constants.SIG_EOCD));

  // disk numbers
  this.write(constants.SHORT_ZERO);
  this.write(constants.SHORT_ZERO);

  // number of entries
  this.write(zipUtil.getShortBytes(records));
  this.write(zipUtil.getShortBytes(records));

  // length and location of CD
  this.write(zipUtil.getLongBytes(size));
  this.write(zipUtil.getLongBytes(offset));

  // archive comment
  var comment = this.getComment();
  var commentLength = Buffer.byteLength(comment);
  this.write(zipUtil.getShortBytes(commentLength));
  this.write(comment);
};

ZipArchiveOutputStream.prototype._writeCentralDirectoryZip64 = function() {
  // signature
  this.write(constants.SIG_ZIP64_EOCD);

  // size of the ZIP64 EOCD record
  this.write(zipUtil.getEightBytes((constants.SHORT * 2) + (constants.LONG * 2) + (8 * 4)));

  // version made by
  this.write(zipUtil.getShortBytes((ae.getPlatform() << 8) | constants.VERSION_MADEBY));

  // version needed to extract
  this.write(zipUtil.getShortBytes(ae.getVersionNeededToExtract()));

  // disk numbers
  this.write(constants.LONG_ZERO);
  this.write(constants.LONG_ZERO);

  // number of entries
  this.write(zipUtil.getEightBytes(this._entries.length));
  this.write(zipUtil.getEightBytes(this._entries.length));

  // length and location of CD
  this.write(zipUtil.getEightBytes(this._archive.centralLength));
  this.write(zipUtil.getEightBytes(this._archive.centralOffset));

  // extensible data sector
  // not implemented at this time

  // end of central directory locator
  this.write(costants.SIG_ZIP64_EOCD_LOC);

  // disk number holding the ZIP64 EOCD record
  this.write(constants.LONG_ZERO);

  // relative offset of the ZIP64 EOCD record
  this.write(zipUtil.getEightBytes(this._archive.centralOffset + this._archive.centralLength));

  // total number of disks
  this.write(this.getLongBytes(1));
};

ZipArchiveOutputStream.prototype._writeCentralFileHeader = function(ae) {
  var gpb = ae.getGeneralPurposeBit();
  var method = ae.getMethod();
  var offsets = ae._offsets;

  var size = ae.getSize();
  var compressedSize = ae.getCompressedSize();

  if (ae.isZip64() || offsets.file > constants.ZIP64_MAGIC) {
    size = constants.ZIP64_MAGIC;
    compressedSize = constants.ZIP64_MAGIC;

    ae.setVersionNeededToExtract(constants.MIN_VERSION_ZIP64);

    var extraBuf = new Buffer(28);
    extraBuf.write(zipUtil.getShortBytes(constants.ZIP64_EXTRA_ID));
    extraBuf.write(zipUtil.getShortBytes(24));
    extraBuf.write(zipUtil.getEightBytes(ae.getSize()));
    extraBuf.write(zipUtil.getEightBytes(ae.getCompressedSize()));
    extraBuf.write(zipUtil.getEightBytes(offsets.file));
    ae.setExtra(extraBuf);
  }

  // signature
  this.write(zipUtil.getLongBytes(constants.SIG_CFH));

  // version made by
  this.write(zipUtil.getShortBytes((ae.getPlatform() << 8) | constants.VERSION_MADEBY));

  // version to extract and general bit flag
  this.write(zipUtil.getShortBytes(ae.getVersionNeededToExtract()));
  this.write(gpb.encode());

  // compression method
  this.write(zipUtil.getShortBytes(method));

  // datetime
  this.write(zipUtil.getLongBytes(ae.getTimeDos()));

  // crc32 checksum
  this.write(zipUtil.getLongBytes(ae.getCrc()));

  // sizes
  this.write(zipUtil.getLongBytes(compressedSize));
  this.write(zipUtil.getLongBytes(size));

  var name = ae.getName();
  var comment = ae.getComment();
  var extra = ae.getCentralDirectoryExtra();

  if (gpb.usesUTF8ForNames()) {
    name = new Buffer(name);
    comment = new Buffer(comment);
  }

  // name length
  this.write(zipUtil.getShortBytes(name.length));

  // extra length
  this.write(zipUtil.getShortBytes(extra.length));

  // comments length
  this.write(zipUtil.getShortBytes(comment.length));

  // disk number start
  this.write(constants.SHORT_ZERO);

  // internal attributes
  this.write(zipUtil.getShortBytes(ae.getInternalAttributes()));

  // external attributes
  this.write(zipUtil.getLongBytes(ae.getExternalAttributes()));

  // relative offset of LFH
  if (offsets.file > constants.ZIP64_MAGIC) {
    this.write(zipUtil.getLongBytes(constants.ZIP64_MAGIC));
  } else {
    this.write(zipUtil.getLongBytes(offsets.file));
  }

  // name
  this.write(name);

  // extra
  this.write(extra);

  // comment
  this.write(comment);
};

ZipArchiveOutputStream.prototype._writeDataDescriptor = function(ae) {
  // signature
  this.write(zipUtil.getLongBytes(constants.SIG_DD));

  // crc32 checksum
  this.write(zipUtil.getLongBytes(ae.getCrc()));

  // sizes
  if (ae.isZip64()) {
    this.write(zipUtil.getEightBytes(ae.getCompressedSize()));
    this.write(zipUtil.getEightBytes(ae.getSize()));
  } else {
    this.write(zipUtil.getLongBytes(ae.getCompressedSize()));
    this.write(zipUtil.getLongBytes(ae.getSize()));
  }
};

ZipArchiveOutputStream.prototype._writeLocalFileHeader = function(ae) {
  var gpb = ae.getGeneralPurposeBit();
  var method = ae.getMethod();
  var name = ae.getName();
  var extra = ae.getLocalFileDataExtra();

  if (ae.isZip64()) {
    gpb.useDataDescriptor(true);
  }

  if (gpb.usesUTF8ForNames()) {
    name = new Buffer(name);
  }

  ae._offsets.file = this.offset;

  // signature
  this.write(zipUtil.getLongBytes(constants.SIG_LFH));

  // version to extract and general bit flag
  this.write(zipUtil.getShortBytes(ae.getVersionNeededToExtract()));
  this.write(gpb.encode());

  // compression method
  this.write(zipUtil.getShortBytes(method));

  // datetime
  this.write(zipUtil.getLongBytes(ae.getTimeDos()));

  ae._offsets.data = this.offset;

  // crc32 checksum and sizes
  if (gpb.usesDataDescriptor()) {
    this.write(constants.LONG_ZERO);
    this.write(constants.LONG_ZERO);
    this.write(constants.LONG_ZERO);
  } else {
    this.write(zipUtil.getLongBytes(ae.getCrc()));
    this.write(zipUtil.getLongBytes(ae.getCompressedSize()));
    this.write(zipUtil.getLongBytes(ae.getSize()));
  }

  // name length
  this.write(zipUtil.getShortBytes(name.length));

  // extra length
  this.write(zipUtil.getShortBytes(extra.length));

  // name
  this.write(name);

  // extra
  this.write(extra);

  ae._offsets.contents = this.offset;
};

ZipArchiveOutputStream.prototype.getComment = function(comment) {
  return this._archive.comment !== null ? this._archive.comment : '';
};

ZipArchiveOutputStream.prototype.isZip64 = function() {
  return this._entries.length > constants.ZIP64_MAGIC_SHORT || this._archive.centralLength > constants.ZIP64_MAGIC || this._archive.centralOffset > constants.ZIP64_MAGIC;
};

ZipArchiveOutputStream.prototype.setComment = function(comment) {
  this._archive.comment = comment;
};<|endoftext|>


<commit_before>var fs = require("fs");
var os = require("os");
var path = require("path");
var child_process = require("child_process");

module.exports = {

	getDefaultTemplate: function() {
		return path.join(__dirname, "../boilerplates/default");
	},

	createStructure: function(dir_path, template_path) {
		var self = this;

		// if template path is undefined, use the default bare template
		template_path = template_path || self.getDefaultTemplate();

		var createSiteDirectory = function(site_dir_path, callback) {
			fs.stat(site_dir_path, function(err, stat) {
				if (err || !stat.isDirectory()) {
					return fs.mkdir(site_dir_path, callback);
				} else {
					return callback(null, site_dir_path);
				}
			});
		};

		var createSiteStructure = function(destination_path, source_path) {
			var copy_command;

			if (os.platform() === "win32") {
				copy_command = "ROBOCOPY " + source_path + " " + destination_path + " *.* /E";
			} else {
				copy_command = "cp -r " + source_path + "/* " + destination_path;
			}

			child_process.exec(copy_command, function(err, stdout, stderr) {
				if(err) {
					throw err;
				}

				console.log("Created a new site in " + destination_path);
				console.log("To get started, run: cd " + destination_path + "; punch s");
			});
		};

		if (dir_path && dir_path !== ".") {
			createSiteDirectory(dir_path, function(err) {
				if (err) {
					console.log("Failed to create the site in " + dir_path);
					return false;
				}
				return createSiteStructure(dir_path, template_path);
			});
		} else {
			createSiteStructure(process.cwd(), template_path);
		}
	}

};
<commit_msg>Robocopy has special return codes, it can return positive codes even when there was no error<commit_after>var fs = require("fs");
var os = require("os");
var path = require("path");
var child_process = require("child_process");

module.exports = {

	getDefaultTemplate: function() {
		return path.join(__dirname, "../boilerplates/default");
	},

	createStructure: function(dir_path, template_path) {
		var self = this;

		// if template path is undefined, use the default bare template
		template_path = template_path || self.getDefaultTemplate();

		var createSiteDirectory = function(site_dir_path, callback) {
			fs.stat(site_dir_path, function(err, stat) {
				if (err || !stat.isDirectory()) {
					return fs.mkdir(site_dir_path, callback);
				} else {
					return callback(null, site_dir_path);
				}
			});
		};

		var createSiteStructure = function(destination_path, source_path) {
			var copy_command;

			if (os.platform() === "win32") {
				copy_command = "ROBOCOPY " + source_path + " " + destination_path + " *.* /E";
			} else {
				copy_command = "cp -r " + source_path + "/* " + destination_path;
			}

			child_process.exec(copy_command, function(err, stdout, stderr) {
				if (err && os.platform() === "win32" && err.code <= 3) {
				} else if(err) {
					throw err;
				}

				console.log("Created a new site in " + destination_path);
				console.log("To get started, run: cd " + destination_path + "; punch s");
			});
		};

		if (dir_path && dir_path !== ".") {
			createSiteDirectory(dir_path, function(err) {
				if (err) {
					console.log("Failed to create the site in " + dir_path);
					return false;
				}
				return createSiteStructure(dir_path, template_path);
			});
		} else {
			createSiteStructure(process.cwd(), template_path);
		}
	}

};
<|endoftext|>


<commit_before>$(() => {
  // Hide the PDF Formatting section if 'pdf' is not the desired format
  $('select#format').on('change', (e) => {
    if ($(e.currentTarget).val() === 'pdf') {
      $('#pdf-formatting').show();
    } else {
      $('#pdf-formatting').hide();
    }
  });
});
<commit_msg>fixed linter issue with CRLF<commit_after>$(() => {
  // Hide the PDF Formatting section if 'pdf' is not the desired format
  $('select#format').on('change', (e) => {
    if ($(e.currentTarget).val() === 'pdf') {
      $('#pdf-formatting').show();
    } else {
      $('#pdf-formatting').hide();
    }
  });
});
<|endoftext|>


<commit_before>/*:tabSize=2:indentSize=2:noTabs=true:mode=javascript:*/

var _ = require('underscore'),
    async = require('async'),
    exec = require('child_process').exec,
    findit = require('findit'),
    fs = require('fs'),
    mime = require('mime'),
    path = require('path');

var getOwnerOfFile = function (file, stat, callback) {
  switch (process.platform) {
    case 'win32':
      tmpl = 'powershell -Command "(get-acl <%=filename%>).owner"';
      break;
    default:
      tmpl = 'stat -c "%U" "<%=filename%>"';
  }
  cmd = _.template(tmpl, {filename: file});
  var child = exec(cmd, function (error, stdout, stderr) {
     callback(null, stdout.trim());
  });
  child.stdin.end();
};

var groupDatasets = function(dataset) {
    extRegex = new RegExp(path.extname(_.first(dataset.files).href)
                          +"$");
    withoutExt = _.first(dataset.files).href.replace(extRegex,'');
    return dataset.author.name+" - "+withoutExt
};

var combineGroupedDatasets = function(datasets) {
    // Handle singular case quickly
    if (datasets.length == 1)
      return _.first(datasets);
    return {
      'author': _.first(datasets).author,
      'files': _.pluck(datasets,'files'),
      'updated': _.max(datasets, function(d) {
        return d.updated.getTime();
      }).updated
    };
};

var buildDatasetObject = function(details) {
  relativeName = path.relative(this.directory, details['file']).trim();
  return {
    'author': {
      'name': details['owner'],
    },
    'files': [{
      'href': relativeName,
      'length': details['stat'].size,
      'title': path.basename(relativeName),
      'type': mime.lookup(relativeName)
    }],
    'updated': details['stat'].mtime
  }
};

var scan = function(directory, callback) {
  var finder = findit.find(directory);

  var results = {};
  var filesBeingProcessed = {};
  finder.on('file', function(file, stat) {
      filesBeingProcessed[file] = true;
      getOwnerOfFile(file, stat, function(owner) {
          results[file] = {
            'file': file,
            'owner': owner,
            'stat': stat
          };
          delete filesBeingProcessed[file];
      });
  });

  finder.on('end', function() {
    var processFiles = function(results) {
      retval = _.chain(_.values(results))
        .sortBy(function(details) {
            // Sort by time
            return details['stat'].mtime.getTime();
        })
        .reverse() // Reverse sort
        .map(_.bind(buildDatasetObject, {'directory': directory}))
        .groupBy(groupDatasets)
        .map(combineGroupedDatasets)
        .value();
      callback(null, retval);
    };
    // Can't process until all the files are in
    var waitForFiles = function() {
      if (_.values(filesBeingProcessed).length == 0)
        processFiles(results);
      else
        process.nextTick(waitForFiles);
    };
    // Wait before processing
    waitForFiles();
  });
};

exports.scan = scan;
<commit_msg>Added uid caching.<commit_after>/*:tabSize=2:indentSize=2:noTabs=true:mode=javascript:*/

var _ = require('underscore'),
    async = require('async'),
    exec = require('child_process').exec,
    findit = require('findit'),
    fs = require('fs'),
    mime = require('mime'),
    path = require('path');

var uidLookup = {};

/* On Windows, UID is always 0, so to be safe we never cache it anywhere. */
var isUidCacheable = function(uid) { return uid > 0; };

var getOwnerOfFile = function (file, stat, callback) {
  // Get cached result if one is available
  if (uidLookup[stat.uid]) {
    callback(null, uidLookup[stat.uid]);
    return;
  }
  // Get command to run
  switch (process.platform) {
    case 'win32':
      tmpl = 'powershell -Command "(get-acl <%=filename%>).owner"';
      break;
    default:
      tmpl = 'stat -c "%U" "<%=filename%>"';
  }
  cmd = _.template(tmpl, {filename: file});
  // Run the command
  var child = exec(cmd, function (error, stdout, stderr) {
     username = stdout.trim();
     // If we can cache this result, do so
     if (isUidCacheable(stat.uid))
       uidLookup[stat.uid] = username;
     // Return the result
     callback(null, username);
  });
  // STDIN needs to be closed, or we'll wait forever
  child.stdin.end();
};

var groupDatasets = function(dataset) {
    extRegex = new RegExp(path.extname(_.first(dataset.files).href)+"$");
    withoutExt = _.first(dataset.files).href.replace(extRegex,'');
    return dataset.author.name+" - "+withoutExt
};

var combineGroupedDatasets = function(datasets) {
    // Handle singular case quickly
    if (datasets.length == 1)
      return _.first(datasets);
    return {
      'author': _.first(datasets).author,
      'files': _.pluck(datasets,'files'),
      'updated': _.max(datasets, function(d) {
        return d.updated.getTime();
      }).updated
    };
};

var buildDatasetObject = function(details) {
  relativeName = path.relative(this.directory, details['file']).trim();
  return {
    'author': {
      'name': details['owner'],
    },
    'files': [{
      'href': relativeName,
      'length': details['stat'].size,
      'title': path.basename(relativeName),
      'type': mime.lookup(relativeName)
    }],
    'updated': details['stat'].mtime
  }
};

var scan = function(directory, callback) {
  var finder = findit.find(directory);

  var results = {};
  var filesBeingProcessed = {};
  finder.on('file', function(file, stat) {
      filesBeingProcessed[file] = true;
      getOwnerOfFile(file, stat, function(owner) {
          results[file] = {
            'file': file,
            'owner': owner,
            'stat': stat
          };
          delete filesBeingProcessed[file];
      });
  });

  finder.on('end', function() {
    var processFiles = function(results) {
      retval = _.chain(_.values(results))
        .sortBy(function(details) {
            // Sort by time
            return details['stat'].mtime.getTime();
        })
        .reverse() // Reverse sort
        .map(_.bind(buildDatasetObject, {'directory': directory}))
        .groupBy(groupDatasets)
        .map(combineGroupedDatasets)
        .value();
      callback(null, retval);
    };
    // Can't process until all the files are in
    var waitForFiles = function() {
      if (_.values(filesBeingProcessed).length == 0)
        processFiles(results);
      else
        process.nextTick(waitForFiles);
    };
    // Wait before processing
    waitForFiles();
  });
};

exports.scan = scan;
<|endoftext|>


<commit_before>function Konsole() {
  var _this = this;

  var _container = document.createElement('div'),
    _title = document.createElement('span'),
    _toggle = document.createElement('span'),
    _resize = document.createElement('span'),
    _clear = document.createElement('span'),
    _log = document.createElement('pre');

  var _minimized = false;

  var _resizeData = {
    height: window.innerHeight / 3,
    ratio: 1/3,
    dragY: 0,
    dragDelta: 0,
    resizing: false
  };

  _resizeData.dragStart = function (clientY) {
    _resizeData.dragY = clientY;
    _resizeData.dragDelta = 0;
    _resizeData.resizing = true;
  };
  _resizeData.dragMove = function (clientY) {
    var maxHeight = window.innerHeight * 0.85,
      minHeight = window.innerHeight * 0.05;

    _resizeData.dragDelta = _resizeData.dragY - clientY;
    _resizeData.height += _resizeData.dragDelta;

    if (_resizeData.height > maxHeight || _resizeData.height < minHeight) {
      _resizeData.height = Math.min(_resizeData.height, maxHeight);
      _resizeData.height = Math.max(_resizeData.height, minHeight);
      _log.style.height = _resizeData.height + 'px';

      _container.style.borderColor = 'red';
      setTimeout(function () {
        _container.style.borderColor = 'gray';
      }, 300);

      _resizeData.dragEnd();

      return;
    }

    _log.style.height = _resizeData.height + 'px';
    _resizeData.dragY = clientY;
  };
  _resizeData.dragEnd = function () {
    _resizeData.ratio = _resizeData.height / window.innerHeight;
    _resizeData.dragY = 0;
    _resizeData.dragDelta = 0;
    _resizeData.resizing = false;
  };

  _container.setAttribute('class', 'konsole-container');
  _container.style.width = '97%';

  _title.setAttribute('class', 'konsole-control konsole-title');
  _title.innerHTML = 'Konsole';
  _title.addEventListener('click', function (ev) {
    if (_log.scrollTop == 0) {
      // if at the top of the log, scroll to the bottom
      _log.scrollTop = _log.scrollHeight;
    } else {
      // when anywhere in the log, scroll to the top
      _log.scrollTop = 0;
    }
  });

  _toggle.setAttribute('class', 'konsole-control konsole-toggle');
  _toggle.innerHTML = 'Minimize';
  _toggle.addEventListener('click', function (ev) {
    if (_log.style.display === 'none') {
      _this.show();
    } else {
      _this.minimize();
    }
  });

  _resize.setAttribute('class', 'konsole-control konsole-resize');
  _resize.innerHTML = 'Resize';
  _resize.addEventListener('touchstart', function (ev) {
    _resizeData.dragStart(ev.touches[0].clientY);

    ev.preventDefault();
    ev.stopPropagation();
  });
  _resize.addEventListener('mousedown', function (ev) {
    _resizeData.dragStart(ev.clientY);

    ev.preventDefault();
    ev.stopPropagation();
  });
  document.body.addEventListener('touchmove', function (ev) {
    if (!_resizeData.resizing) {
      return;
    }

    _resizeData.dragMove(ev.touches[0].clientY);

    ev.preventDefault();
    ev.stopPropagation();
  });
  document.body.addEventListener('mousemove', function (ev) {
    if (!_resizeData.resizing) {
      return;
    }

    _resizeData.dragMove(ev.clientY);

    ev.preventDefault();
    ev.stopPropagation();
  });
  document.body.addEventListener('touchend', function (ev) {
    if (!_resizeData.resizing) {
      return;
    }

    _resizeData.dragEnd();
  });
  document.body.addEventListener('mouseup', function (ev) {
    if (!_resizeData.resizing) {
      return;
    }

    _resizeData.dragEnd();
  });
  window.addEventListener('resize', function () {
    _resizeData.height = window.innerHeight * _resizeData.ratio;
    _log.style.height = _resizeData.height + 'px';
  });

  _clear.setAttribute('class', 'konsole-control konsole-clear');
  _clear.innerHTML = 'Clear';
  _clear.addEventListener('click', function (ev) {
    _this.clear();
  });

  _log.setAttribute('class', 'konsole-log');
  _log.style.height = _resizeData.height + 'px';

  _container.appendChild(_title);
  _container.appendChild(_toggle);
  _container.appendChild(_resize);
  _container.appendChild(_clear);
  _container.appendChild(_log);

  document.body.appendChild(_container);

  _this.dom = function () {
    return {
      container: _container,
      title: _title,
      toggle: _toggle,
      resize: _resize,
      clear: _clear,
      log: _log
    };
  }

  _this.minimized = function () {
    return _minimized;
  }

  _this.show = function () {
    _container.style.width = '97%';
    _toggle.innerHTML = 'Minimize';
    _resize.style.display = '';
    _clear.style.display = '';
    _log.style.display = '';

    _minimized = false;

    return _this;
  };

  _this.minimize = function () {
    _container.style.width = 'inherit';
    _toggle.innerHTML = 'Show';
    _resize.style.display = 'none';
    _clear.style.display = 'none';
    _log.style.display = 'none';

    _minimized = true;

    return _this;
  };

  _this.clear = function () {
    _log.textContent = '';

    return _this;
  };

  _this.log = function (obj, comment) {
    if (comment) {
      _log.textContent += '// ' + comment + '\n';
    }
    _log.textContent += obj + '\n---\n';

    // scroll to the bottom of the log
    _log.scrollTop = _log.scrollHeight;

    return _this;
  };

  // start minimized
  _this.minimize();
}

Konsole.pretty = function (obj) {
  var objs = [], keys = [];

  return JSON.stringify(obj, function (k, v) {
    var seen;

    if (v instanceof Object) {
      if ( (seen = objs.indexOf(v)) == -1 ) {
        objs.push(v);
        keys.push(k || 'ROOT');

        return v;
      }

      return v + ' (ref to ' + keys[seen] + ')';
    }

    return v;
  }, 2);
}

Konsole.noop = function () {
  Konsole.defInst = {};
  kpp = kp = function () {};
}

document.addEventListener('DOMContentLoaded', function () {
  if (!Konsole.defInst) {
    Konsole.defInst = new Konsole();
  }
});

function kp(obj, comment) {
  if (document.readyState === 'loading') {
    // defer kp calls made before DOM ready
    document.addEventListener('DOMContentLoaded', function () {
      kp(obj, comment);
    });

    return;
  }

  if (!Konsole.defInst) {
    Konsole.defInst = new Konsole();
  }

  if (Konsole.defInst.minimized()) {
    Konsole.defInst.show();
  }

  Konsole.defInst.log(obj, comment);
}

function kpp(obj, comment) {
  kp(Konsole.pretty(obj), comment);
}

window.addEventListener('error', function () {
  kpp(arguments, arguments[0].message);
});
<commit_msg>Add visual cues on writing to/clearing Konsole<commit_after>function Konsole() {
  var _this = this;

  var _container = document.createElement('div'),
    _title = document.createElement('span'),
    _toggle = document.createElement('span'),
    _resize = document.createElement('span'),
    _clear = document.createElement('span'),
    _log = document.createElement('pre');

  var _minimized = false;

  var _resizeData = {
    height: window.innerHeight / 3,
    ratio: 1/3,
    dragY: 0,
    dragDelta: 0,
    resizing: false
  };

  _resizeData.dragStart = function (clientY) {
    _resizeData.dragY = clientY;
    _resizeData.dragDelta = 0;
    _resizeData.resizing = true;
  };
  _resizeData.dragMove = function (clientY) {
    var maxHeight = window.innerHeight * 0.85,
      minHeight = window.innerHeight * 0.05;

    _resizeData.dragDelta = _resizeData.dragY - clientY;
    _resizeData.height += _resizeData.dragDelta;

    if (_resizeData.height > maxHeight || _resizeData.height < minHeight) {
      _resizeData.height = Math.min(_resizeData.height, maxHeight);
      _resizeData.height = Math.max(_resizeData.height, minHeight);
      _log.style.height = _resizeData.height + 'px';

      _container.style.borderColor = 'red';
      setTimeout(function () {
        _container.style.borderColor = 'gray';
      }, 300);

      _resizeData.dragEnd();

      return;
    }

    _log.style.height = _resizeData.height + 'px';
    _resizeData.dragY = clientY;
  };
  _resizeData.dragEnd = function () {
    _resizeData.ratio = _resizeData.height / window.innerHeight;
    _resizeData.dragY = 0;
    _resizeData.dragDelta = 0;
    _resizeData.resizing = false;
  };

  _container.setAttribute('class', 'konsole-container');
  _container.style.width = '97%';

  _title.setAttribute('class', 'konsole-control konsole-title');
  _title.innerHTML = 'Konsole';
  _title.addEventListener('click', function (ev) {
    if (_log.scrollTop == 0) {
      // if at the top of the log, scroll to the bottom
      _log.scrollTop = _log.scrollHeight;
    } else {
      // when anywhere in the log, scroll to the top
      _log.scrollTop = 0;
    }
  });

  _toggle.setAttribute('class', 'konsole-control konsole-toggle');
  _toggle.innerHTML = 'Minimize';
  _toggle.addEventListener('click', function (ev) {
    if (_log.style.display === 'none') {
      _this.show();
    } else {
      _this.minimize();
    }
  });

  _resize.setAttribute('class', 'konsole-control konsole-resize');
  _resize.innerHTML = 'Resize';
  _resize.addEventListener('touchstart', function (ev) {
    _resizeData.dragStart(ev.touches[0].clientY);

    ev.preventDefault();
    ev.stopPropagation();
  });
  _resize.addEventListener('mousedown', function (ev) {
    _resizeData.dragStart(ev.clientY);

    ev.preventDefault();
    ev.stopPropagation();
  });
  document.body.addEventListener('touchmove', function (ev) {
    if (!_resizeData.resizing) {
      return;
    }

    _resizeData.dragMove(ev.touches[0].clientY);

    ev.preventDefault();
    ev.stopPropagation();
  });
  document.body.addEventListener('mousemove', function (ev) {
    if (!_resizeData.resizing) {
      return;
    }

    _resizeData.dragMove(ev.clientY);

    ev.preventDefault();
    ev.stopPropagation();
  });
  document.body.addEventListener('touchend', function (ev) {
    if (!_resizeData.resizing) {
      return;
    }

    _resizeData.dragEnd();
  });
  document.body.addEventListener('mouseup', function (ev) {
    if (!_resizeData.resizing) {
      return;
    }

    _resizeData.dragEnd();
  });
  window.addEventListener('resize', function () {
    _resizeData.height = window.innerHeight * _resizeData.ratio;
    _log.style.height = _resizeData.height + 'px';
  });

  _clear.setAttribute('class', 'konsole-control konsole-clear');
  _clear.innerHTML = 'Clear';
  _clear.addEventListener('click', function (ev) {
    _this.clear();
  });

  _log.setAttribute('class', 'konsole-log');
  _log.style.height = _resizeData.height + 'px';

  _container.appendChild(_title);
  _container.appendChild(_toggle);
  _container.appendChild(_resize);
  _container.appendChild(_clear);
  _container.appendChild(_log);

  document.body.appendChild(_container);

  _this.dom = function () {
    return {
      container: _container,
      title: _title,
      toggle: _toggle,
      resize: _resize,
      clear: _clear,
      log: _log
    };
  }

  _this.minimized = function () {
    return _minimized;
  }

  _this.show = function () {
    _container.style.width = '97%';
    _toggle.innerHTML = 'Minimize';
    _resize.style.display = '';
    _clear.style.display = '';
    _log.style.display = '';

    _minimized = false;

    return _this;
  };

  _this.minimize = function () {
    _container.style.width = 'inherit';
    _toggle.innerHTML = 'Show';
    _resize.style.display = 'none';
    _clear.style.display = 'none';
    _log.style.display = 'none';

    _minimized = true;

    return _this;
  };

  _this.clear = function () {
    _log.textContent = '';

    _container.style.boxShadow = '0 0 1em blue';
    setTimeout(function () {
      _container.style.boxShadow = '0 0 1em gray';
    }, 300);

    return _this;
  };

  _this.log = function (obj, comment, err) {
    if (comment) {
      _log.textContent += '// ' + comment + '\n';
    }
    _log.textContent += obj + '\n---\n';

    // scroll to the bottom of the log
    _log.scrollTop = _log.scrollHeight;

    if (err) {
      _container.style.boxShadow = '0 0 1em red';
      setTimeout(function () {
        _container.style.boxShadow = '0 0 1em gray';
        setTimeout(function () {
          _container.style.boxShadow = '0 0 1em red';
          setTimeout(function () {
            _container.style.boxShadow = '0 0 1em gray';
          }, 300);
        }, 200);
      }, 300);
    } else {
      _container.style.boxShadow = '0 0 1em green';
      setTimeout(function () {
        _container.style.boxShadow = '0 0 1em gray';
      }, 400);
    }

    return _this;
  };

  // start minimized
  _this.minimize();
}

Konsole.pretty = function (obj) {
  var objs = [], keys = [];

  return JSON.stringify(obj, function (k, v) {
    var seen;

    if (v instanceof Object) {
      if ( (seen = objs.indexOf(v)) == -1 ) {
        objs.push(v);
        keys.push(k || 'ROOT');

        return v;
      }

      return v + ' (ref to ' + keys[seen] + ')';
    }

    return v;
  }, 2);
}

Konsole.noop = function () {
  Konsole.defInst = {};
  kpp = kp = function () {};
}

document.addEventListener('DOMContentLoaded', function () {
  if (!Konsole.defInst) {
    Konsole.defInst = new Konsole();
  }
});

function kp(obj, comment, err) {
  if (document.readyState === 'loading') {
    // defer kp calls made before DOM ready
    document.addEventListener('DOMContentLoaded', function () {
      kp(obj, comment, err);
    });

    return;
  }

  if (!Konsole.defInst) {
    Konsole.defInst = new Konsole();
  }

  if (Konsole.defInst.minimized()) {
    Konsole.defInst.show();
  }

  Konsole.defInst.log(obj, comment, err);
}

function kpp(obj, comment, err) {
  kp(Konsole.pretty(obj), comment, err);
}

window.addEventListener('error', function () {
  kpp(arguments, arguments[0].message, true);
});
<|endoftext|>


<commit_before>var cp = require('child_process')
var Q = require('q')

/**
 * Promise-Based functions from child_process
 */
module.exports = {
  /**
   * Execute a child-process and return a promise
   * @param cmd
   * @param args
   * @param options
   * @returns {*}
     */
  execFile: function (cmd, args, options) {
    var defer = Q.defer()
    cp.execFile(cmd, args, options, (err, stdout, stderr) => {
      if (err) {
        return defer.reject(err)
      }
      return defer.resolve({
        stdout: stdout,
        stderr: stderr,
        /**
         * Appends first stdout, then stderr to the `output`-string and returns the result
         * @param {string} output the previous output
         */
        appendTo: function (output) {
          var myOutput = `${stdout.trim()}\n${stderr.trim()}`
          return `${output}\n${myOutput.trim()}`.trim()
        }
      })
    })
    return defer.promise
  },

  spawn: function (cmd, args, options) {
    var defer = Q.defer()
    var child = cp.spawn(cmd, args, options)
    child.on('exit', function (code) {
      if (code === 0) {
        defer.resolve()
      } else {
        defer.reject()
      }
    })
    return defer.promise
  }
}
<commit_msg>Update jsdoc for q-child-process file<commit_after>var cp = require('child_process')
var Q = require('q')

/**
 * Promise-Based functions from child_process
 */
module.exports = {
  /**
   * Execute a child-process and return a promise for the output
   * @param cmd
   * @param args
   * @param options
   * @returns {{ stdout: string, stderr: string}} the output of the process on stdout and stderr
     */
  execFile: function (cmd, args, options) {
    var defer = Q.defer()
    cp.execFile(cmd, args, options, (err, stdout, stderr) => {
      if (err) {
        return defer.reject(err)
      }
      return defer.resolve({
        stdout: stdout,
        stderr: stderr,
        /**
         * Appends first stdout, then stderr to the `output`-string and returns the result
         * @param {string} output the previous output
         */
        appendTo: function (output) {
          var myOutput = `${stdout.trim()}\n${stderr.trim()}`
          return `${output}\n${myOutput.trim()}`.trim()
        }
      })
    })
    return defer.promise
  },

  spawn: function (cmd, args, options) {
    var defer = Q.defer()
    var child = cp.spawn(cmd, args, options)
    child.on('exit', function (code) {
      if (code === 0) {
        defer.resolve()
      } else {
        defer.reject()
      }
    })
    return defer.promise
  }
}
<|endoftext|>


<commit_before>/*
 * @class Radar
 * @aka L.Radar
 * @inherits Path
 *
 * A class for drawing 'radar' overlays on a map. Extends `Patth`.
 *
 * Shares the same approximation weaknesses as L.Circle and may become inaccurate near the poles
 *
 * @example
 *
 * ```js
 * L.radar([50.5, 30.5], {radarDescriptor: L.Radar.radarDescriptor(100, 200, 0, 4)}).addTo(map);
 * ```
 */
L.Radar = L.Path.extend({

	options: {
		fill: true,

		// Default values for the radar object
		radarDescriptor: {
			_minorRadius: 0,
			_majorRadius: 0,
			_startAngle: 0,
			_endAngle: 0
		}
	},

	// @method initialize(latlng: LatLng, options: Object)
	// Performs basic setup for the radar object
	initialize: function (latlng, options) {
		L.setOptions(this, options);
		this._latlng = L.latLng(latlng);
		if (options.radarDescriptor.type === "RadarDescriptor") {
			this._radarDescriptor = options.radarDescriptor;
		} else {
			this._radarDescriptor = this.options.radarDescriptor;
		}
	},

	// @method setLatLng(latlng: LatLng): this
	// Sets the position of a circle marker to a new location.
	setLatLng: function (latlng) {
		this._latlng = L.latLng(latlng);
		this.redraw();
	},

	// @method getLatLng(): LatLng
	// Returns the current geographical position of the circle marker
	getLatLng: function () {
		return this._latlng;
	},

	// @method setStyle(options: Object): this
	// Sets the style of the radar object based on the given parameters.  Returns this.
	setStyle: function (options) {
		var radarDescriptor = options && options.radarDescriptor || this._radarDescriptor;
		L.Path.prototype.setStyle.call(this, options);
		this.setRadarDescriptor(radarDescriptor);
		return this;
	},

	// @method _project()
	// Projects the radar object onto the map based on the latlng coordinates
	_project: function () {

		// Pretty much all of this logic for projection is ripped from L.circle, as a radar
		// object is essentially two concentric circles
		var lng = this._latlng.lng,
		    lat = this._latlng.lat,
		    map = this._map,
			radarDescriptor = this._radarDescriptor,
			crs = map.options.crs;

		if (crs.distance === L.CRS.Earth.distance) {
			var d = Math.PI / 180,
			    latR = (radarDescriptor._mRadius / L.CRS.Earth.R) / d,
			    top = map.project([lat + latR, lng]),
			    bottom = map.project([lat - latR, lng]),
			    p = top.add(bottom).divideBy(2),
			    lat2 = map.unproject(p).lat,
			    lngR = Math.acos((Math.cos(latR * d) - Math.sin(lat * d) * Math.sin(lat2 * d)) /
			            (Math.cos(lat * d) * Math.cos(lat2 * d))) / d;

			if (isNaN(lngR) || lngR === 0) {
				lngR = latR / Math.cos(Math.PI / 180 * lat);
			}

			this._point = p.subtract(map.getPixelOrigin());
			radarDescriptor._majorRadius = isNaN(lngR) ? 0 : Math.max(Math.round(p.x - map.project([lat2, lng - lngR]).x), 1);

			latR = (radarDescriptor._nRadius / L.CRS.Earth.R) / d;
			top = map.project([lat + latR, lng]);
			bottom = map.project([lat - latR, lng]);
			p = top.add(bottom).divideBy(2);
			lat2 = map.unproject(p).lat;
			lngR = Math.acos((Math.cos(latR * d) - Math.sin(lat * d) * Math.sin(lat2 * d)) /
			            (Math.cos(lat * d) * Math.cos(lat2 * d))) / d;

			if (isNaN(lngR) || lngR === 0) {
				lngR = latR / Math.cos(Math.PI / 180 * lat);
			}

			radarDescriptor._minorRadius = isNaN(lngR) ? 0 : Math.max(Math.round(p.x - map.project([lat2, lng - lngR]).x), 1);

		} else {
			var latlng2 = crs.unproject(crs.project(this._latlng).subtract([radarDescriptor._mRadius, 0]));

			this._point = map.latLngToLayerPoint(this._latlng);
			radarDescriptor._majorRadius = this._point.x - map.latLngToLayerPoint(latlng2).x;
		}
		this._point = this._map.latLngToLayerPoint(this._latlng);
		this._updateBounds();
	},

	// @method _updateBounds()
	// Updates the bounding box of the radar.  Uses a square based on the major radius
	_updateBounds: function () {
		var r = this._radarDescriptor._majorRadius,
			w = this._clickTolerance(),
			p = [r + w, r + w];
		this._pxBounds = new L.Bounds(this._point.subtract(p), this._point.subtract(p));
	},

	// @method setRadarDescriptor(radarDescriptor: RadarDescriptor)
	// Sets the descriptor for the radar object
	setRadarDescriptor: function (radarDescriptor) {
		this._radarDescriptor = radarDescriptor;
	},

	// @method getBounds(): LatLngBounds
	// Returns the `LatLngBounds` of the path.
	getBounds: function () {
		return this._bounds;
	},

	// @method _update()
	// Updates the radar object
	_update: function () {
		if (this._map) {
			this._updatePath();
		}
	},

	// @method _updatePath()
	// Updates the path of the radar object in the renderer
	_updatePath: function () {
		this._renderer._setPath(this, this._radarDescriptor.getPath(this._point));
	}
});

// @factory L.radar(latlng: LatLng, options: Object): L.Radar
// Instantiates a radar object given a geographical point, and an optional options object.
L.radar = function (latlng, options) {
	return new L.Radar(latlng, options);
};

// @factory L.Radar.radarDescriptor(minorRadius: Number, majorRadius: Number, startAngle: Number, endAngle: Number): RadarDescriptor
// Creates a new instance of a RadarDescriptor for defining a radar object
L.Radar.radarDescriptor = function (minorRadius, majorRadius, startAngle, endAngle) {
	function RadarDescriptor(minorRadius, majorRadius, startAngle, endAngle) {
		var self = this;
		self._minorRadius = minorRadius || 0;
		self._majorRadius = majorRadius || 0;
		self._mRadius = self._majorRadius;
		self._nRadius = self._minorRadius;
		self._startAngle = startAngle || 0;
		self._endAngle = endAngle || 0;
		self.type = "RadarDescriptor";

		// @method getPath(p: Point): String
		// Gets the SVG path of the radar object
		self.getPath = function(p) {
			var minorRadius = this._minorRadius;
			var majorRadius = this._majorRadius;
			var majorArc = (endAngle - startAngle) > Math.PI ? 1 : 0;
			var firstVertex = {
				x: minorRadius * Math.cos(this._startAngle) + p.x,
				y: minorRadius * Math.sin(this._startAngle) + p.y
			};

			var secondVertex = {
				x: majorRadius * Math.cos(this._startAngle) + p.x,
				y: majorRadius * Math.sin(this._startAngle) + p.y
			};

			var thirdVertex = {
				x: majorRadius * Math.cos(this._endAngle) + p.x,
				y: majorRadius * Math.sin(this._endAngle) + p.y
			};

			var fourthVertex = {
				x: minorRadius * Math.cos(this._endAngle) + p.x,
				y: minorRadius * Math.sin(this._endAngle) + p.y
			};

			return 'M ' + firstVertex.x + ' ' + firstVertex.y + ' ' +
				'L ' + secondVertex.x + ' ' + secondVertex.y + ' ' +
				'A ' + majorRadius + ' ' + majorRadius + ' 0 ' + majorArc + ' 1 ' +
				thirdVertex.x + ' ' + thirdVertex.y + ' ' +
				'L ' + fourthVertex.x + ' ' + fourthVertex.y + ' ' +
				'A ' + minorRadius + ' ' + minorRadius + ' 0 ' + majorArc + ' 0 ' +
				firstVertex.x + ' ' + firstVertex.y;
		}
	}

	return new RadarDescriptor(minorRadius, majorRadius, startAngle, endAngle);
}
<commit_msg>Tabbing<commit_after>/*
 * @class Radar
 * @aka L.Radar
 * @inherits Path
 *
 * A class for drawing 'radar' overlays on a map. Extends `Patth`.
 *
 * Shares the same approximation weaknesses as L.Circle and may become inaccurate near the poles
 *
 * @example
 *
 * ```js
 * L.radar([50.5, 30.5], {radarDescriptor: L.Radar.radarDescriptor(100, 200, 0, 4)}).addTo(map);
 * ```
 */
L.Radar = L.Path.extend({

    options: {
        fill: true,

        // Default values for the radar object
        radarDescriptor: {
            _minorRadius: 0,
            _majorRadius: 0,
            _startAngle: 0,
            _endAngle: 0
        }
    },

    // @method initialize(latlng: LatLng, options: Object)
    // Performs basic setup for the radar object
    initialize: function (latlng, options) {
        L.setOptions(this, options);
        this._latlng = L.latLng(latlng);
        if (options.radarDescriptor.type === "RadarDescriptor") {
            this._radarDescriptor = options.radarDescriptor;
        } else {
            this._radarDescriptor = this.options.radarDescriptor;
        }
    },

    // @method setLatLng(latlng: LatLng): this
    // Sets the position of a circle marker to a new location.
    setLatLng: function (latlng) {
        this._latlng = L.latLng(latlng);
        this.redraw();
    },

    // @method getLatLng(): LatLng
    // Returns the current geographical position of the circle marker
    getLatLng: function () {
        return this._latlng;
    },

    // @method setStyle(options: Object): this
    // Sets the style of the radar object based on the given parameters.  Returns this.
    setStyle: function (options) {
        var radarDescriptor = options && options.radarDescriptor || this._radarDescriptor;
        L.Path.prototype.setStyle.call(this, options);
        this.setRadarDescriptor(radarDescriptor);
        return this;
    },

    // @method _project()
    // Projects the radar object onto the map based on the latlng coordinates
    _project: function () {

        // Pretty much all of this logic for projection is ripped from L.circle, as a radar
        // object is essentially two concentric circles
        var lng = this._latlng.lng,
            lat = this._latlng.lat,
            map = this._map,
            radarDescriptor = this._radarDescriptor,
            crs = map.options.crs;

        if (crs.distance === L.CRS.Earth.distance) {
            var d = Math.PI / 180,
            latR = (radarDescriptor._mRadius / L.CRS.Earth.R) / d,
                top = map.project([lat + latR, lng]),
                bottom = map.project([lat - latR, lng]),
                p = top.add(bottom).divideBy(2),
                lat2 = map.unproject(p).lat,
                lngR = Math.acos((Math.cos(latR * d) - Math.sin(lat * d) * Math.sin(lat2 * d)) /
                        (Math.cos(lat * d) * Math.cos(lat2 * d))) / d;

            if (isNaN(lngR) || lngR === 0) {
                lngR = latR / Math.cos(Math.PI / 180 * lat);
            }

            this._point = p.subtract(map.getPixelOrigin());
            radarDescriptor._majorRadius = isNaN(lngR) ? 0 : Math.max(Math.round(p.x - map.project([lat2, lng - lngR]).x), 1);

            latR = (radarDescriptor._nRadius / L.CRS.Earth.R) / d;
            top = map.project([lat + latR, lng]);
            bottom = map.project([lat - latR, lng]);
            p = top.add(bottom).divideBy(2);
            lat2 = map.unproject(p).lat;
            lngR = Math.acos((Math.cos(latR * d) - Math.sin(lat * d) * Math.sin(lat2 * d)) /
                        (Math.cos(lat * d) * Math.cos(lat2 * d))) / d;

            if (isNaN(lngR) || lngR === 0) {
                lngR = latR / Math.cos(Math.PI / 180 * lat);
            }

            radarDescriptor._minorRadius = isNaN(lngR) ? 0 : Math.max(Math.round(p.x - map.project([lat2, lng - lngR]).x), 1);

        } else {
            var latlng2 = crs.unproject(crs.project(this._latlng).subtract([radarDescriptor._mRadius, 0]));

            this._point = map.latLngToLayerPoint(this._latlng);
            radarDescriptor._majorRadius = this._point.x - map.latLngToLayerPoint(latlng2).x;
        }
        this._point = this._map.latLngToLayerPoint(this._latlng);
        this._updateBounds();
    },

    // @method _updateBounds()
    // Updates the bounding box of the radar.  Uses a square based on the major radius
    _updateBounds: function () {
        var r = this._radarDescriptor._majorRadius,
            w = this._clickTolerance(),
            p = [r + w, r + w];
        this._pxBounds = new L.Bounds(this._point.subtract(p), this._point.subtract(p));
    },

    // @method setRadarDescriptor(radarDescriptor: RadarDescriptor)
    // Sets the descriptor for the radar object
    setRadarDescriptor: function (radarDescriptor) {
        this._radarDescriptor = radarDescriptor;
    },

    // @method getBounds(): LatLngBounds
    // Returns the `LatLngBounds` of the path.
    getBounds: function () {
        return this._bounds;
    },

    // @method _update()
    // Updates the radar object
    _update: function () {
        if (this._map) {
            this._updatePath();
        }
    },

    // @method _updatePath()
    // Updates the path of the radar object in the renderer
    _updatePath: function () {
        this._renderer._setPath(this, this._radarDescriptor.getPath(this._point));
    }
});

// @factory L.radar(latlng: LatLng, options: Object): L.Radar
// Instantiates a radar object given a geographical point, and an optional options object.
L.radar = function (latlng, options) {
    return new L.Radar(latlng, options);
};

// @factory L.Radar.radarDescriptor(minorRadius: Number, majorRadius: Number, startAngle: Number, endAngle: Number): RadarDescriptor
// Creates a new instance of a RadarDescriptor for defining a radar object
L.Radar.radarDescriptor = function (minorRadius, majorRadius, startAngle, endAngle) {
    function RadarDescriptor(minorRadius, majorRadius, startAngle, endAngle) {
        var self = this;
        self._minorRadius = minorRadius || 0;
        self._majorRadius = majorRadius || 0;
        self._mRadius = self._majorRadius;
        self._nRadius = self._minorRadius;
        self._startAngle = startAngle || 0;
        self._endAngle = endAngle || 0;
        self.type = "RadarDescriptor";

        // @method getPath(p: Point): String
        // Gets the SVG path of the radar object
        self.getPath = function(p) {
            var minorRadius = this._minorRadius;
            var majorRadius = this._majorRadius;
            var majorArc = (endAngle - startAngle) > Math.PI ? 1 : 0;
            var firstVertex = {
                x: minorRadius * Math.cos(this._startAngle) + p.x,
                y: minorRadius * Math.sin(this._startAngle) + p.y
            };

            var secondVertex = {
                x: majorRadius * Math.cos(this._startAngle) + p.x,
                y: majorRadius * Math.sin(this._startAngle) + p.y
            };

            var thirdVertex = {
                x: majorRadius * Math.cos(this._endAngle) + p.x,
                y: majorRadius * Math.sin(this._endAngle) + p.y
            };

            var fourthVertex = {
                x: minorRadius * Math.cos(this._endAngle) + p.x,
                y: minorRadius * Math.sin(this._endAngle) + p.y
            };

            return 'M ' + firstVertex.x + ' ' + firstVertex.y + ' ' +
                'L ' + secondVertex.x + ' ' + secondVertex.y + ' ' +
                'A ' + majorRadius + ' ' + majorRadius + ' 0 ' + majorArc + ' 1 ' +
                thirdVertex.x + ' ' + thirdVertex.y + ' ' +
                'L ' + fourthVertex.x + ' ' + fourthVertex.y + ' ' +
                'A ' + minorRadius + ' ' + minorRadius + ' 0 ' + majorArc + ' 0 ' +
                firstVertex.x + ' ' + firstVertex.y;
        }
    }

    return new RadarDescriptor(minorRadius, majorRadius, startAngle, endAngle);
}
<|endoftext|>