<commit_before>"use strict";
var t0 = Date.now();

var express = require("express"),
    xhub = require('express-x-hub'),
    comment = require("./lib/comment");

if (process.env.NODE_ENV === "dev") {
    // Load local env variables
    require("./env");
}

function logArgs() {
    var args = arguments;
    process.nextTick(function() {
        console.log.apply(console, args);
    });
}

var app = express();
app.use(xhub({ algorithm: 'sha1', secret: process.env.GITHUB_SECRET }));

app.post('/github-hook', function (req, res, next) {
    if (process.env.NODE_ENV != 'production' || req.isXHubValid()) {
        res.send(new Date().toISOString());
        var payload = req.body;
        switch(payload.action) {
            case "opened":
            case "edited":
            case "reopened":
            case "synchronize":
                logArgs(`${ payload.pull_request.base.repo.full_name }#${ payload.number }: ${ payload.action }`);
                comment(payload).then(logArgs, logArgs);
                break;
            default:
                logArgs("Unknown request", JSON.stringify(payload, null, 4));
        }
    } else {
        logArgs("Unverified request", req);
    }
    next();
});

var port = process.env.PORT || 5000;
app.listen(port, function() {
    console.log("Express server listening on port %d in %s mode", port, app.settings.env);
    console.log("App started in", (Date.now() - t0) + "ms.");
});
<commit_msg>Minor changes.<commit_after>"use strict";
var t0 = Date.now();

var express = require("express"),
    xhub = require('express-x-hub'),
    comment = require("./lib/comment");

if (process.env.NODE_ENV === "dev") {
    // Load local env variables
    require("./env");
}

function logArgs() {
    var args = arguments;
    process.nextTick(function() {
        console.log.apply(console, args);
    });
}

var app = express();
app.use(xhub({ algorithm: 'sha1', secret: process.env.GITHUB_SECRET }));

app.post('/github-hook', function (req, res, next) {
    if (process.env.NODE_ENV != 'production' || req.isXHubValid()) {
        res.send(new Date().toISOString());
        var payload = req.body;
        if (payload.pull_request) {
            logArgs(`${ payload.pull_request.base.repo.full_name }#${ payload.number }: ${ payload.action }`);
            switch(payload.action) {
                case "opened":
                case "edited":
                case "reopened":
                case "synchronize":
                    comment(payload).then(logArgs, logArgs);
            }
        } else {
            logArgs("Unknown request", JSON.stringify(payload, null, 4));
        }
    } else {
        logArgs("Unverified request", req);
    }
    next();
});

var port = process.env.PORT || 5000;
app.listen(port, function() {
    console.log("Express server listening on port %d in %s mode", port, app.settings.env);
    console.log("App started in", (Date.now() - t0) + "ms.");
});
<|endoftext|>


<commit_before>var midpoint = require('turf-midpoint');
var point = require('turf-point');
var distance = require('turf-distance');

/**
 * Takes a bounding box and calculates the minimum square bounding box that would contain the input.
 *
 * @module turf/square
 * @param {Array<number>} bbox a bounding box
 * @return {Array<number>} a square surrounding `bbox`
 * @example
 * var bbox = [-20,-20,-15,0];
 * var squared = turf.square(bbox);
 * var features = turf.featurecollection([
 *   turf.bboxPolygon(bbox),
 *   turf.bboxPolygon(squared)]);
 *
 * //=features
 */
module.exports = function(bbox){
  var squareBbox = [0,0,0,0];
  var lowLeft = point(bbox[0], bbox[1]);
  var topLeft = point(bbox[0], bbox[3]);
  var topRight = point(bbox[2], bbox[3]);
  var lowRight = point(bbox[2], bbox[1]);

  var horizontalDistance = distance(lowLeft, lowRight, 'miles');
  var verticalDistance = distance(lowLeft, topLeft, 'miles');
  if(horizontalDistance >= verticalDistance){
    squareBbox[0] = bbox[0];
    squareBbox[2] = bbox[2];
    var verticalMidpoint = midpoint(lowLeft, topLeft);
    squareBbox[1] = verticalMidpoint.geometry.coordinates[1] - ((bbox[2] - bbox[0]) / 2);
    squareBbox[3] = verticalMidpoint.geometry.coordinates[1] + ((bbox[2] - bbox[0]) / 2);
    return squareBbox;
  }
  else {
    squareBbox[1] = bbox[1];
    squareBbox[3] = bbox[3];
    var horzontalMidpoint = midpoint(lowLeft, lowRight);
    squareBbox[0] = horzontalMidpoint.geometry.coordinates[0] - ((bbox[3] - bbox[1]) / 2);
    squareBbox[2] = horzontalMidpoint.geometry.coordinates[0] + ((bbox[3] - bbox[1]) / 2);
    return squareBbox;
  }
}

<commit_msg>Fix usage of point<commit_after>var midpoint = require('turf-midpoint');
var point = require('turf-point');
var distance = require('turf-distance');

/**
 * Takes a bounding box and calculates the minimum square bounding box that would contain the input.
 *
 * @module turf/square
 * @param {Array<number>} bbox a bounding box
 * @return {Array<number>} a square surrounding `bbox`
 * @example
 * var bbox = [-20,-20,-15,0];
 * var squared = turf.square(bbox);
 * var features = turf.featurecollection([
 *   turf.bboxPolygon(bbox),
 *   turf.bboxPolygon(squared)]);
 *
 * //=features
 */
module.exports = function(bbox){
  var squareBbox = [0,0,0,0];
  var lowLeft = point([bbox[0], bbox[1]]);
  var topLeft = point([bbox[0], bbox[3]]);
  var topRight = point([bbox[2], bbox[3]]);
  var lowRight = point([bbox[2], bbox[1]]);

  var horizontalDistance = distance(lowLeft, lowRight, 'miles');
  var verticalDistance = distance(lowLeft, topLeft, 'miles');
  if(horizontalDistance >= verticalDistance){
    squareBbox[0] = bbox[0];
    squareBbox[2] = bbox[2];
    var verticalMidpoint = midpoint(lowLeft, topLeft);
    squareBbox[1] = verticalMidpoint.geometry.coordinates[1] - ((bbox[2] - bbox[0]) / 2);
    squareBbox[3] = verticalMidpoint.geometry.coordinates[1] + ((bbox[2] - bbox[0]) / 2);
    return squareBbox;
  }
  else {
    squareBbox[1] = bbox[1];
    squareBbox[3] = bbox[3];
    var horzontalMidpoint = midpoint(lowLeft, lowRight);
    squareBbox[0] = horzontalMidpoint.geometry.coordinates[0] - ((bbox[3] - bbox[1]) / 2);
    squareBbox[2] = horzontalMidpoint.geometry.coordinates[0] + ((bbox[3] - bbox[1]) / 2);
    return squareBbox;
  }
}

<|endoftext|>


<commit_before>'use strict';

const _ = require('lodash'),
    BbPromise = require('bluebird'),
    dynamodbMigrations = require('dynamodb-migrations'),
    AWS = require('aws-sdk'),
    dynamodbLocal = require('dynamodb-localhost');

class ServerlessDynamodbLocal {
    constructor(serverless, options) {
        this.serverless = serverless;
        this.service = serverless.service;
        this.options = options;
        this.provider = 'aws';
        this.commands = {
            dynamodb: {
                commands: {
                    create: {
                        lifecycleEvents: ['createHandler'],
                        options: {
                            name: {
                                required: true,
                                shortcut: 'n',
                                usage: 'Create a migration template inside the directlry given in s-project.json with the given name.',
                            }
                        }
                    },
                    execute: {
                        lifecycleEvents: ['executeHandler'],
                        options: {
                            name: {
                                required: true,
                                shortcut: 'n',
                                usage: 'Execute a migration template with the given name'
                            },
                            region: {
                                shortcut: 'r',
                                usage: 'Region that dynamodb should be remotely executed'
                            },
                            stage: {
                                shortcut: 's',
                                usage: 'Stage that dynamodb should be remotely executed'
                            }
                        }
                    },
                    executeAll: {
                        lifecycleEvents: ['executeAllHandler'],
                        options: {
                            stage: {
                                shortcut: 's',
                                usage: 'Stage that dynamodb should be remotely executed'
                            }
                        }
                    },
                    start: {
                        lifecycleEvents: ['startHandler'],
                        options: {
                            port: {
                                shortcut: 'p',
                                usage: 'The port number that DynamoDB will use to communicate with your application. If you do not specify this option, the default port is 8000'
                            },
                            cors: {
                                shortcut: 'c',
                                usage: 'Enable CORS support (cross-origin resource sharing) for JavaScript. You must provide a comma-separated "allow" list of specific domains. The default setting for -cors is an asterisk (*), which allows public access.'
                            },
                            inMemory: {
                                shortcut: 'i',
                                usage: 'DynamoDB; will run in memory, instead of using a database file. When you stop DynamoDB;, none of the data will be saved. Note that you cannot specify both -dbPath and -inMemory at once.'
                            },
                            dbPath: {
                                shortcut: 'd',
                                usage: 'The directory where DynamoDB will write its database file. If you do not specify this option, the file will be written to the current directory. Note that you cannot specify both -dbPath and -inMemory at once. For the path, current working directory is <projectroot>/node_modules/serverless-dynamodb-local/dynamob. For example to create <projectroot>/node_modules/serverless-dynamodb-local/dynamob/<mypath> you should specify -d <mypath>/ or --dbPath <mypath>/ with a forwardslash at the end.'
                            },
                            sharedDb: {
                                shortcut: 'h',
                                usage: 'DynamoDB will use a single database file, instead of using separate files for each credential and region. If you specify -sharedDb, all DynamoDB clients will interact with the same set of tables regardless of their region and credential configuration.'
                            },
                            delayTransientStatuses: {
                                shortcut: 't',
                                usage: 'Causes DynamoDB to introduce delays for certain operations. DynamoDB can perform some tasks almost instantaneously, such as create/update/delete operations on tables and indexes; however, the actual DynamoDB service requires more time for these tasks. Setting this parameter helps DynamoDB simulate the behavior of the Amazon DynamoDB web service more closely. (Currently, this parameter introduces delays only for global secondary indexes that are in either CREATING or DELETING status.'
                            },
                            optimizeDbBeforeStartup: {
                                shortcut: 'o',
                                usage: 'Optimizes the underlying database tables before starting up DynamoDB on your computer. You must also specify -dbPath when you use this parameter.'
                            },
                            migration: {
                                shortcut: 'm',
                                usage: 'After starting dynamodb local, run dynamodb migrations'
                            }
                        }
                    },
                    remove: {
                        lifecycleEvents: ['removeHandler']
                    },
                    install: {
                        lifecycleEvents: ['installHandler'],
						options: {
                            localPath: {
                                shortcut: 'x',
                                usage: 'Local dynamodb install path'
                            }
                        }

                    }
                }
            }
        };

        this.hooks = {
            'dynamodb:create:createHandler': this.createHandler.bind(this),
            'dynamodb:execute:executeHandler': this.executeHandler.bind(this),
            'dynamodb:executeAll:executeAllHandler': this.executeAllHandler.bind(this),
            'dynamodb:remove:removeHandler': this.removeHandler.bind(this),
            'dynamodb:install:installHandler': this.installHandler.bind(this),
            'dynamodb:start:startHandler': this.startHandler.bind(this),
            'before:offline:start': this.startHandler.bind(this),
        };
    }
    createHandler() {
        let self = this,
            options = this.options;
        return new BbPromise(function(resolve, reject) {
            let dynamodb = self.dynamodbOptions(),
                tableOptions = self.tableOptions();
            dynamodbMigrations.init(dynamodb, tableOptions.path);
            dynamodbMigrations.create(options.name).then(resolve, reject);
        });
    }

	dynamodbOptions(region) {
			let self = this;
            let credentials, config = self.service.custom.dynamodb || {},
                port = config.start && config.start.port || 8000,
                dynamoOptions;
			if(region){
                AWS.config.update({
                    region: region
                });
			}else{
				dynamoOptions = {
			endpoint: 'http://localhost:' + port,
			region: 'localhost',
			accessKeyId: 'MOCK_ACCESS_KEY_ID',
			secretAccessKey: 'MOCK_SECRET_ACCESS_KEY'
                };
			}
			return {
                raw: new AWS.DynamoDB(dynamoOptions),
                doc: new AWS.DynamoDB.DocumentClient(dynamoOptions)
            };
        }

        tableOptions(table_prefix, table_suffix) {
			let self = this;
            let config = self.service.custom.dynamodb,
                migration = config && config.migration || {},
                rootPath = self.serverless.config.servicePath,
                path = rootPath + '/' + (migration.dir || 'dynamodb'),
                suffix = table_suffix || migration.table_suffix || '',
                prefix = table_prefix || migration.table_prefix || '';

            return {
                suffix: suffix,
                prefix: prefix,
                path: path
            };
        }

    executeHandler() {
        let self = this,
            options = this.options;
        return new BbPromise(function(resolve, reject) {
            let dynamodb = self.dynamodbOptions(options.stage, options.region),
                tableOptions = self.tableOptions();
            dynamodbMigrations.init(dynamodb, tableOptions.path);
            dynamodbMigrations.execute(options.name, tableOptions).then(resolve, reject);
        });
    }

    executeAllHandler(isOffline) {
        let self = this,
            region = isOffline ? null : self.service.provider.region,
            options = this.options;

        return new BbPromise(function(resolve, reject) {
            let dynamodb = self.dynamodbOptions(region),
                tableOptions = self.tableOptions(options.stage);
	        dynamodbMigrations.init(dynamodb, tableOptions.path);
            dynamodbMigrations.executeAll(tableOptions).then(resolve, reject);
        });
    }

    removeHandler() {
        return new BbPromise(function(resolve) {
            dynamodbLocal.remove(resolve);
        });
    }

    installHandler() {
        let self = this,
			options = this.options;
        return new BbPromise(function(resolve) {
	            dynamodbLocal.install(resolve, options.localPath);
        });
    }

    startHandler() {
        let self = this,
            options = this.options;
        return new BbPromise(function(resolve) {
            let config = self.service.custom.dynamodb,
                options = _.merge({
                        sharedDb: self.options.sharedDb || true
                    },
                    self.options,
                    config && config.start
                );
            if (options.migration) {
                dynamodbLocal.start(options);
                console.log(""); // seperator
                self.executeAllHandler(true);
                resolve();
            } else {
                dynamodbLocal.start(options);
                console.log("");
                resolve();
            }
        });
    }
}
module.exports = ServerlessDynamodbLocal;
<commit_msg>Forced Table Prefix Bug Fix<commit_after>'use strict';

const _ = require('lodash'),
    BbPromise = require('bluebird'),
    dynamodbMigrations = require('dynamodb-migrations'),
    AWS = require('aws-sdk'),
    dynamodbLocal = require('dynamodb-localhost');

class ServerlessDynamodbLocal {
    constructor(serverless, options) {
        this.serverless = serverless;
        this.service = serverless.service;
        this.options = options;
        this.provider = 'aws';
        this.commands = {
            dynamodb: {
                commands: {
                    create: {
                        lifecycleEvents: ['createHandler'],
                        options: {
                            name: {
                                required: true,
                                shortcut: 'n',
                                usage: 'Create a migration template inside the directlry given in s-project.json with the given name.',
                            }
                        }
                    },
                    execute: {
                        lifecycleEvents: ['executeHandler'],
                        options: {
                            name: {
                                required: true,
                                shortcut: 'n',
                                usage: 'Execute a migration template with the given name'
                            },
                            region: {
                                shortcut: 'r',
                                usage: 'Region that dynamodb should be remotely executed'
                            },
                            stage: {
                                shortcut: 's',
                                usage: 'Stage that dynamodb should be remotely executed'
                            }
                        }
                    },
                    executeAll: {
                        lifecycleEvents: ['executeAllHandler'],
                        options: {
                            stage: {
                                shortcut: 's',
                                usage: 'Stage that dynamodb should be remotely executed'
                            }
                        }
                    },
                    start: {
                        lifecycleEvents: ['startHandler'],
                        options: {
                            port: {
                                shortcut: 'p',
                                usage: 'The port number that DynamoDB will use to communicate with your application. If you do not specify this option, the default port is 8000'
                            },
                            cors: {
                                shortcut: 'c',
                                usage: 'Enable CORS support (cross-origin resource sharing) for JavaScript. You must provide a comma-separated "allow" list of specific domains. The default setting for -cors is an asterisk (*), which allows public access.'
                            },
                            inMemory: {
                                shortcut: 'i',
                                usage: 'DynamoDB; will run in memory, instead of using a database file. When you stop DynamoDB;, none of the data will be saved. Note that you cannot specify both -dbPath and -inMemory at once.'
                            },
                            dbPath: {
                                shortcut: 'd',
                                usage: 'The directory where DynamoDB will write its database file. If you do not specify this option, the file will be written to the current directory. Note that you cannot specify both -dbPath and -inMemory at once. For the path, current working directory is <projectroot>/node_modules/serverless-dynamodb-local/dynamob. For example to create <projectroot>/node_modules/serverless-dynamodb-local/dynamob/<mypath> you should specify -d <mypath>/ or --dbPath <mypath>/ with a forwardslash at the end.'
                            },
                            sharedDb: {
                                shortcut: 'h',
                                usage: 'DynamoDB will use a single database file, instead of using separate files for each credential and region. If you specify -sharedDb, all DynamoDB clients will interact with the same set of tables regardless of their region and credential configuration.'
                            },
                            delayTransientStatuses: {
                                shortcut: 't',
                                usage: 'Causes DynamoDB to introduce delays for certain operations. DynamoDB can perform some tasks almost instantaneously, such as create/update/delete operations on tables and indexes; however, the actual DynamoDB service requires more time for these tasks. Setting this parameter helps DynamoDB simulate the behavior of the Amazon DynamoDB web service more closely. (Currently, this parameter introduces delays only for global secondary indexes that are in either CREATING or DELETING status.'
                            },
                            optimizeDbBeforeStartup: {
                                shortcut: 'o',
                                usage: 'Optimizes the underlying database tables before starting up DynamoDB on your computer. You must also specify -dbPath when you use this parameter.'
                            },
                            migration: {
                                shortcut: 'm',
                                usage: 'After starting dynamodb local, run dynamodb migrations'
                            }
                        }
                    },
                    remove: {
                        lifecycleEvents: ['removeHandler']
                    },
                    install: {
                        lifecycleEvents: ['installHandler'],
						options: {
                            localPath: {
                                shortcut: 'x',
                                usage: 'Local dynamodb install path'
                            }
                        }

                    }
                }
            }
        };

        this.hooks = {
            'dynamodb:create:createHandler': this.createHandler.bind(this),
            'dynamodb:execute:executeHandler': this.executeHandler.bind(this),
            'dynamodb:executeAll:executeAllHandler': this.executeAllHandler.bind(this),
            'dynamodb:remove:removeHandler': this.removeHandler.bind(this),
            'dynamodb:install:installHandler': this.installHandler.bind(this),
            'dynamodb:start:startHandler': this.startHandler.bind(this),
            'before:offline:start': this.startHandler.bind(this),
        };
    }
    createHandler() {
        let self = this,
            options = this.options;
        return new BbPromise(function(resolve, reject) {
            let dynamodb = self.dynamodbOptions(),
                tableOptions = self.tableOptions();
            dynamodbMigrations.init(dynamodb, tableOptions.path);
            dynamodbMigrations.create(options.name).then(resolve, reject);
        });
    }

	dynamodbOptions(region) {
			let self = this;
            let credentials, config = self.service.custom.dynamodb || {},
                port = config.start && config.start.port || 8000,
                dynamoOptions;
			if(region){
                AWS.config.update({
                    region: region
                });
			}else{
				dynamoOptions = {
			endpoint: 'http://localhost:' + port,
			region: 'localhost',
			accessKeyId: 'MOCK_ACCESS_KEY_ID',
			secretAccessKey: 'MOCK_SECRET_ACCESS_KEY'
                };
			}
			return {
                raw: new AWS.DynamoDB(dynamoOptions),
                doc: new AWS.DynamoDB.DocumentClient(dynamoOptions)
            };
        }

        tableOptions(table_prefix, table_suffix) {
			let self = this;
            let config = self.service.custom.dynamodb,
                migration = config && config.migration || {},
                rootPath = self.serverless.config.servicePath,
                path = rootPath + '/' + (migration.dir || 'dynamodb'),
                suffix = table_suffix || migration.table_suffix || '',
                prefix = table_prefix || migration.table_prefix || '';

            return {
                suffix: suffix,
                prefix: prefix,
                path: path
            };
        }

    executeHandler() {
        let self = this,
            options = this.options;
        return new BbPromise(function(resolve, reject) {
            let dynamodb = self.dynamodbOptions(options.stage, options.region),
                tableOptions = self.tableOptions();
            dynamodbMigrations.init(dynamodb, tableOptions.path);
            dynamodbMigrations.execute(options.name, tableOptions).then(resolve, reject);
        });
    }

    executeAllHandler(isOffline) {
        let self = this,
            region = isOffline ? null : self.service.provider.region,
            options = this.options;

        return new BbPromise(function(resolve, reject) {
            let dynamodb = self.dynamodbOptions(region),
                tableOptions = self.tableOptions();
	        dynamodbMigrations.init(dynamodb, tableOptions.path);
            dynamodbMigrations.executeAll(tableOptions).then(resolve, reject);
        });
    }

    removeHandler() {
        return new BbPromise(function(resolve) {
            dynamodbLocal.remove(resolve);
        });
    }

    installHandler() {
        let self = this,
			options = this.options;
        return new BbPromise(function(resolve) {
	            dynamodbLocal.install(resolve, options.localPath);
        });
    }

    startHandler() {
        let self = this,
            options = this.options;
        return new BbPromise(function(resolve) {
            let config = self.service.custom.dynamodb,
                options = _.merge({
                        sharedDb: self.options.sharedDb || true
                    },
                    self.options,
                    config && config.start
                );
            if (options.migration) {
                dynamodbLocal.start(options);
                console.log(""); // seperator
                self.executeAllHandler(true);
                resolve();
            } else {
                dynamodbLocal.start(options);
                console.log("");
                resolve();
            }
        });
    }
}
module.exports = ServerlessDynamodbLocal;
<|endoftext|>


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

const Bluebird = require( 'bluebird' )
	, process = require( 'process' )
	, yargs = require( 'yargs' ).argv

	, console = require( './src/my-console.js' )
	, ProcedureError = require( './src/utils.js' ).ProcedureError
	, main = require( './src/main.js' )
	;

function activate() {
	return Bluebird.resolve( main() );
}

Bluebird
	.try( activate )
	.then( () => process.exit( 0 ) )
	.catch( ( err ) => {
		console.line( true );
		if ( err instanceof ProcedureError ) {
			console.error( err.message, err.command );
			if ( yargs.verbose && err.stacktrace ) {
				console.indent();
				console.error( err.stacktrace );
				console.outdent();
			}
		} else {
			console.error( 'An unexpected error has occured:' );
			if ( yargs.verbose && err.stack ) {
				console.error( err.stack );
			} else {
				console.error( err.message );
			}
		}
		console.error( 'Execution aborted.' );
		process.exit( 1 );
	} )
	;
<commit_msg>Error exceptions are now printed ignoring console lineLength<commit_after>#!/usr/bin/env node

const Bluebird = require( 'bluebird' )
	, process = require( 'process' )
	, yargs = require( 'yargs' ).argv

	, console = require( './src/my-console.js' )
	, ProcedureError = require( './src/utils.js' ).ProcedureError
	, main = require( './src/main.js' )
	;

function activate() {
	return Bluebird.resolve( main() );
}

Bluebird
	.try( activate )
	.then( () => process.exit( 0 ) )
	.catch( ( err ) => {
		console.lineLength = 9999;
		console.line( true );
		if ( err instanceof ProcedureError ) {
			console.error( err.message, err.command );
			if ( yargs.verbose && err.stacktrace ) {
				console.indent();
				console.error( err.stacktrace );
				console.outdent();
			}
		} else {
			console.error( 'An unexpected error has occured:' );
			if ( yargs.verbose && err.stack ) {
				console.error( err.stack );
			} else {
				console.error( err.message );
			}
		}
		console.error( 'Execution aborted.' );
		process.exit( 1 );
	} )
	;
<|endoftext|>


<commit_before>/* eslint-env node */
'use strict';
const fastbootTransform = require('fastboot-transform');

module.exports = {
  name: 'ember-fullcalendar',

  // isDevelopingAddon: function() {
  //   return true;
  // },

  options: {
    nodeAssets: {
      'fullcalendar': function() {
        return {
          import: {
            include: ['dist/fullcalendar.js', 'dist/fullcalendar.css'].concat(this.includeLocalesFiles),
            processTree(input) {
              return fastbootTransform(input);
            }
          }
        }
      },
      'fullcalendar-scheduler': {
        enabled: this.includeScheduler,
        import: {
          include: ['dist/scheduler.js', 'dist/scheduler.css'],
          processTree(input) {
            return fastbootTransform(input);
          }
        }
      }
    }
  },

  included(app, parentAddon) {
    var target = parentAddon || app;

    // allow addon to be nested - see: https://github.com/ember-cli/ember-cli/issues/3718
    if (target.app) {
      target = target.app;
    }

    var config = target.project.config(target.env) || {};

    // include locale files
    if (config.emberFullCalendar && config.emberFullCalendar.includeLocales) {
      if (Array.isArray(config.emberFullCalendar.includeLocales)) {
        this.includeLocalesFiles = config.emberFullCalendar.includeLocales.map(function(localeCode) {
          return 'dist/locale/' + localeCode + '.js';
        });
      } else if (config.emberFullCalendar.includeLocales === "all") {
        this.includeLocalesFiles = ['dist/locale-all.js'];
      } else {
        this.includeLocalesFiles = [];
      }
    } else {
      this.includeLocalesFiles = [];
    }

    // Add scheduler to executable unless configured not to.
    if (config.emberFullCalendar && config.emberFullCalendar.includeScheduler === true) {
      this.includeScheduler = true;
    } else {
      this.includeScheduler = false;
    }

    this._super.included.apply(this, arguments);
  }
};
<commit_msg>Add scheduler to function to fix enableScheduler config param<commit_after>/* eslint-env node */
'use strict';
const fastbootTransform = require('fastboot-transform');

module.exports = {
  name: 'ember-fullcalendar',

  // isDevelopingAddon: function() {
  //   return true;
  // },

  options: {
    nodeAssets: {
      'fullcalendar': function() {
        return {
          import: {
            include: ['dist/fullcalendar.js', 'dist/fullcalendar.css'].concat(this.includeLocalesFiles),
            processTree(input) {
              return fastbootTransform(input);
            }
          }
        };
      },
      'fullcalendar-scheduler': function() {
        return {
          enabled: this.includeScheduler,
          import: {
            include: ['dist/scheduler.js', 'dist/scheduler.css'],
            processTree(input) {
              return fastbootTransform(input);
            }
          }
        };
      }
    }
  },

  included(app, parentAddon) {
    var target = parentAddon || app;

    // allow addon to be nested - see: https://github.com/ember-cli/ember-cli/issues/3718
    if (target.app) {
      target = target.app;
    }

    var config = target.project.config(target.env) || {};

    // include locale files
    if (config.emberFullCalendar && config.emberFullCalendar.includeLocales) {
      if (Array.isArray(config.emberFullCalendar.includeLocales)) {
        this.includeLocalesFiles = config.emberFullCalendar.includeLocales.map(function(localeCode) {
          return 'dist/locale/' + localeCode + '.js';
        });
      } else if (config.emberFullCalendar.includeLocales === "all") {
        this.includeLocalesFiles = ['dist/locale-all.js'];
      } else {
        this.includeLocalesFiles = [];
      }
    } else {
      this.includeLocalesFiles = [];
    }

    // Add scheduler to executable unless configured not to.
    if (config.emberFullCalendar && config.emberFullCalendar.includeScheduler === true) {
      this.includeScheduler = true;
    } else {
      this.includeScheduler = false;
    }

    this._super.included.apply(this, arguments);
  }
};
<|endoftext|>


<commit_before>const express = require('express')
const app = express()
const port = 3000

var route_main = require('./routes/route-main')
var route_family = require('./routes/route-family')
var route_locations = require('./routes/route-locations')

app.configure(function(){
  app.use(express.bodyParser());
});

app.use((err, request, response, next) => {
    // log the error, for now just console.log
    console.log(err);
    response.status(500).send('Something broke!')
});

app.all('/', function (req, res, next) {
  next() // pass control to the next handler
})

app.use('/', route_main)
app.use('/family', route_family)
app.use('/locations', route_locations)

app.listen(port)<commit_msg>Adding POST call to update family member's location - fix 2<commit_after>const express = require('express')
const bodyParser = require('body-parser')
const app = express()
const port = 3000

var route_main = require('./routes/route-main')
var route_family = require('./routes/route-family')
var route_locations = require('./routes/route-locations')

app.use(bodyParser.json())

app.use((err, request, response, next) => {
    // log the error, for now just console.log
    console.log(err);
    response.status(500).send('Something broke!')
});

app.all('/', function (req, res, next) {
  next() // pass control to the next handler
})

app.use('/', route_main)
app.use('/family', route_family)
app.use('/locations', route_locations)

app.listen(port)<|endoftext|>


<commit_before>const http = require('http');
const https = require('https');
const fs = require('fs');
const net = require('net');
const url = require('url');
const log4js = require('log4js');

log4js.configure({
    appenders: [
        { type: 'console' },
        { type: 'file', filename: 'log/proxy.log' }
    ]
});

const logger = log4js.getLogger();

const proxy_ip = 'localhost';
const http_proxy_port = 8080;
const https_proxy_port = 8081;
const key_path = './douban.key';
const cert_path = './douban.crt';

/**
 * dump request
 */
function dump_request(req) {
    let dump = {
        url: req.url,
        host: req.headers.host || req.headers.hostname,
        headers: req.headers
    };
    logger.info(JSON.stringify(dump));
}

function connect_handler(c_req, c_sock) {
    let u = url.parse('http://' + c_req.url);
    let p_sock = net.connect(https_proxy_port, proxy_ip, () => {
        c_sock.write('HTTP/1.1 200 Connection Established\r\n\r\n');
        p_sock.pipe(c_sock);
    }).on('error', (e) => {
        c_sock.end();
    });
    c_sock.pipe(p_sock);
}

function transmit(req, res, request) {
    let u = url.parse(req.url);
    let options = {
        host : u.host || req.headers.host,
        hostname: u.hostname || req.headers.hostname,
        port: u.port || req.headers.port,
        path : u.path || req.headers.path,
        method : req.method,
        headers : req.headers
    };
    let c_req = request(options, function (c_res) {
        res.writeHead(c_res.statusCode, c_res.headers);
        c_res.pipe(res);
    }).on('error', (e) => {
        res.end();
    });
    req.pipe(c_req);
}

function https_proxy(req, res) {
    dump_request(req);
    transmit(req, res, https.request);
}

function http_proxy(req, res) {
    dump_request(req);
    transmit(req, res, http.request);
}

let options = {
    key: fs.readFileSync(key_path),
    cert: fs.readFileSync(cert_path)
};

http.createServer()
    .on('request', http_proxy)
    .on('connect', connect_handler)
    .listen(http_proxy_port, proxy_ip);

https.createServer(options)
     .on('request', https_proxy)
     .listen(https_proxy_port, proxy_ip);
<commit_msg>complete log format, including request header and response header<commit_after>const http = require('http');
const https = require('https');
const fs = require('fs');
const net = require('net');
const url = require('url');
const log4js = require('log4js');
const contentType = require('content-type');

log4js.configure({
    appenders: [
        { type: 'console' },
        { type: 'file', filename: 'log/proxy.log' }
    ]
});

const logger = log4js.getLogger();

const proxy_ip = '0.0.0.0';
const http_proxy_port = 8080;
const https_proxy_port = 8081;
const key_path = './douban.key';
const cert_path = './douban.crt';

/**
 * dump request and response
 */
function dump_communication(req, res) {
    let url_obj = url.parse(req.url);
    // request 的URL仅仅是header中的url，https下不包含protocol和host,但是在http下又是完整的。。
    url_obj.host = url_obj.host || req.headers.host;
    url_obj.protocol = url_obj.protocol || 'https';

    let dump = {
        "request": {
            url: url.format(url_obj),
            host: req.headers.host,
            headers: req.headers
        },
        "response": {
            statusCode: res.statusCode,
            headers: res.headers
        }
    };
    logger.info(JSON.stringify(dump));
}

function connect_handler(c_req, c_sock) {
    let p_sock = net.connect(https_proxy_port, proxy_ip, () => {
        c_sock.write('HTTP/1.1 200 Connection Established\r\n\r\n');
        p_sock.pipe(c_sock);
    }).on('error', (e) => {
        c_sock.end();
    });
    c_sock.pipe(p_sock);
}

function transmit(req, res, request) {
    let u = url.parse(req.url);
    let options = {
        url: url,
        host : u.host || req.headers.host,
        hostname: u.hostname || req.headers.hostname,
        port: u.port || req.headers.port,
        path : u.path || req.headers.path,
        method : req.method,
        headers : req.headers
    };
    let c_req = request(options, function (c_res) {
        res.writeHead(c_res.statusCode, c_res.headers);
        c_res.pipe(res);
        dump_communication(req, c_res);
    }).on('error', (e) => {
        res.end();
    });
    req.pipe(c_req);
}

function https_proxy(req, res) {
    console.log(req.httpVersion);
    transmit(req, res, https.request);
}

function http_proxy(req, res) {
    transmit(req, res, http.request);
}

let options = {
    key: fs.readFileSync(key_path),
    cert: fs.readFileSync(cert_path)
};

http.createServer()
    .on('request', http_proxy)
    .on('connect', connect_handler)
    .listen(http_proxy_port, proxy_ip);

https.createServer(options)
     .on('request', https_proxy)
     .listen(https_proxy_port, proxy_ip);

logger.info('http proxy start at: ' + proxy_ip + ':' + http_proxy_port);
<|endoftext|>


<commit_before>/*!
 * GitCDN
 * Copyright(c) 2012 Daniel D. Shaw <dshaw@dshaw.com> (http://dshaw.com)
 * MIT Licensed
 */

/**
 * Module dependencies.
 */

var path = require('path')
  , exec = require('child_process').exec
  , connect = require('connect')
  , pushover = require('pushover')

/**
 * Exports
 */

module.exports = GitCDN

/**
 * GitCDN
 */

function GitCDN (options) {
  if (!(this instanceof GitCDN)) return new GitCDN(options)
  options || (options = {})
  this.options = options

  this.repoDir = options.repoDir || __dirname + '/repos'
  this.fileDir = options.fileDir || __dirname + '/files'
  this.pushPort = options.pushPort || 7000
  this.hostPort = options.hostPort || 9000

  if (this.pushPort === this.hostPort) {
    throw new Error('Git push and server are set to the same port.')
  }

  this.pusher;
  this.server;

  this.initGit()
  this.initServer()
}

/**
 * Initialize Git Push Server
 */

GitCDN.prototype.initGit = function () {
  var self = this

  this.pusher = pushover(this.repoDir)

  this.pusher.on('push', function (repo) {
    console.log('received a push to ' + repo);
    exec('git clone ' + path.join(self.repoDir, repo + '.git'), { cwd: self.fileDir  }, function () {
      console.log(arguments);
//                if (name === 'end') {
//                    spawner('git',
//                        [ 'checkout', commit ],
//                        function (name) {
//                            if (name === 'end') {
//                                spawner(command[0], command.slice(1), emit);
//                            }
//                        },
//                        { cwd : dir }
//                    );
//                }
    })
  })

  this.pusher.listen(this.pushPort)

  this.pusher.on('listening', function () {
    console.log('listening on :%d', self.pushPort);
  })
}

/**
 * Initialize File Server
 */

GitCDN.prototype.initServer = function () {
  var self = this

  this.server = connect.createServer(connect.static(path.join(this.repoDir)))

  this.server.listen(this.hostPort)

  this.server.on('listening', function () {
    console.log('listening on :', self.server.address());
  })
}
<commit_msg>Cleaned up options. Added procstreams and mkdirp.<commit_after>/*!
 * GitCDN
 * Copyright(c) 2012 Daniel D. Shaw <dshaw@dshaw.com> (http://dshaw.com)
 * MIT Licensed
 */

/**
 * Module dependencies.
 */

var path = require('path')
  , exec = require('child_process').exec
  , util = require('util')
  , connect = require('connect')
  , mkdirp = require('mkdirp')
  , procstream = require('procstreams')
  , pushover = require('pushover')
  , EventEmitter = require('events').EventEmitter

/**
 * Exports
 */

module.exports = GitCDN

/**
 * GitCDN
 */

function GitCDN (options) {
  if (!(this instanceof GitCDN)) return new GitCDN(options)
  options || (options = {})
  this.options = options
  this.basedir = options.basedir || process.cwd()
  this.repodir = options.repodir || this.basedir + '/repos'
  this.filedir = options.filedir || this.basedir + '/files'
  this.pushport = options.pushport || 8000
  this.hostport = options.hostport || 9000

  if (this.pushport === this.hostport) {
    throw new Error('Git push and server are set to the same port.')
  }

  this.pusher = null;
  this.server = null;

  this.initGit()
  this.initServer()
}

util.inherits(GitCDN, EventEmitter)

/**
 * Initialize Git Push Server
 */

GitCDN.prototype.initGit = function () {
  var self = this

  mkdirp(this.filedir)
  this.pusher = pushover(this.repodir)

  this.pusher.on('push', function (repo) {
    self.emit('push', repo)
    console.log('received a push to ' + repo)
    path.exists(path.join(self.filedir, repo), function (exists) {
      if (!exists) {
        procstream('git clone http://localhost:' + self.pushPort + '/' + repo, { cwd: self.filedir  })
      } else {
        procstream('git pull', { cwd: self.filedir  })
      }
    })
  })

  this.pusher.on('listening', function () {
    console.log('listening on :', self.pushport);
  })

  this.pusher.listen(this.pushport)
}

/**
 * Initialize File Server
 */

GitCDN.prototype.initServer = function () {
  var self = this

  this.server = connect.createServer(connect.static(this.filedir))
  this.server.listen(this.hostport)

  this.server.on('listening', function () {
    console.log('listening on :', self.server.address())
    console.log('hosting files in:', self.filedir)
  })
}
<|endoftext|>


<commit_before>'use strict';

/**
 * Wordpress MVC gulp development file.
 * Enables predefined (standarized) tasks, such use minify or sass compilation.
 *
 * @link http://gulpjs.com/
 * @author Alejandro Mostajo <info@10quality.com>
 * @copyright 10 Quality
 * @license MIT
 * @version 1.1.1
 */

/**
 * Export module.
 * @since 1.0.0
 * @since 1.0.1 Changed execution order and added staging and gulp.
 * @since 1.0.2 Added fixes for theme check.
 * @since 1.0.3 Pretasks defined and better concat scope.
 * @since 1.0.4 Minification.
 * @since 1.0.5 Enable the option to set which directories to include on root.
 * @since 1.0.6 Added prebuild tasks to enable special customization before zip and build are made.
 * @since 1.0.7 Added prezip taks to enable special customization before zip is made.
 * @since 1.1.0 Node compatibility changes.
 * @since 1.2.0 Removes "bin" folders, adds wordpress.org updates via SVN.
 *
 * @param object gulp   Gulp project application.
 * @param array  config Configuration file.
 */
module.exports = function(gulp, config, wordpressOrg)
{
    // Dependencies.
    if (!gulp) gulp = require('gulp');
    var sass = require('gulp-sass');
    var concat = require('gulp-concat');
    var minify = require('gulp-minify');
    var cleanCSS = require('gulp-clean-css');
    var zip = require('gulp-zip');
    var del = require('del');
    // Prepare options
    if (!config) config = {};
    if (!config.name) config.name = 'app';
    if (!config.version) config.version = '1.0.0';
    if (!config.prestyles) config.prestyles = ['sass'];
    if (!config.prescripts) config.prescripts = [];
    if (!config.prebuild) config.prebuild = ['scripts', 'styles'];
    if (!config.prezip) config.prezip = ['build-prezip', 'jsmin', 'cssmin'];
    if (!config.rootdirs) config.rootdirs = '{app,assets,vendor}/**/*';

    // Set GULP tasks
    // SASS
    gulp.task('sass', function () {
        return gulp.src('./assets/raw/sass/*.scss')
            .pipe(sass().on('error', sass.logError))
            .pipe(gulp.dest('./assets/raw/css'));
    });
    // Styles
    gulp.task('styles', config.prestyles, function () {
        return gulp.src('./assets/raw/css/**/*.css')
            .pipe(concat('app.css'))
            .pipe(gulp.dest('./assets/css'));
    });
    // Scripts
    gulp.task('scripts', config.prescripts, function() {
        return gulp.src('./assets/raw/js/**/*.js')
            .pipe(concat('app.js'))
            .pipe(gulp.dest('./assets/js'));
    });
    // JS minify
    gulp.task('jsmin', ['scripts', 'build-prezip'], function() {
        return gulp.src('./assets/js/**/*.js')
            .pipe(minify({
                ext:{
                    min:'.js'
                }
            }))
            .pipe(gulp.dest('./builds/staging/'+config.name+'/assets/js'));
    });
    // CSS minify
    gulp.task('cssmin', ['styles', 'build-prezip'], function() {
        return gulp.src('./assets/css/**/*.css')
            .pipe(cleanCSS({compatibility: 'ie8'}))
            .pipe(gulp.dest('./builds/staging/'+config.name+'/assets/css'));
    });
    // Build files
    gulp.task('build-files', config.prebuild, function() {
        return gulp.src([
                config.rootdirs,
                './LICENSE',
                './*.{php,css,jpg,txt}'
            ])
            .pipe(gulp.dest('./builds/staging/'+config.name));
    });
    // Build clean pre zip
    gulp.task('build-prezip', ['build-files'], function() {
        return del([
            './builds/staging/'+config.name+'/assets/{raw,css,js,wordpress}/**/*',
            './builds/staging/'+config.name+'/vendor/10quality/{ayuco,wpmvc-commands}/**/*',
            './builds/staging/'+config.name+'/vendor/nikic/**/*',
            './builds/staging/'+config.name+'/vendor/bin/**/*',
            './builds/staging/'+config.name+'/vendor/10quality/{wp-file,wpmvc-logger,wpmvc-phpfastcache,wpmvc-core,wpmvc-mvc}/tests/**/*',
            './builds/staging/'+config.name+'/assets/{raw,css,js,wordpress}',
            './builds/staging/'+config.name+'/vendor/10quality/{ayuco,wpmvc-commands,nikic}',
            './builds/staging/'+config.name+'/vendor/nikic',
            './builds/staging/'+config.name+'/vendor/bin',
            './builds/staging/'+config.name+'/vendor/10quality/wp-file/{wp-file,wpmvc-logger,wpmvc-phpfastcache,wpmvc-core,wpmvc-mvc}/tests',
        ]);
    });
    // Build zip
    gulp.task('build-zip', config.prezip, function() {
        return gulp.src('./builds/staging/**/*')
            .pipe(zip(config.name+'-'+config.version+'.zip'))
            .pipe(gulp.dest('./builds'));
    });
    // Build clean
    gulp.task('build-clean', ['build-zip'], function() {
        return del([
            './builds/staging/**/*',
            './builds/staging',
        ]);
    });
    // Build trunk
    gulp.task('build-trunk', ['clean-trunk'], function() {
        return gulp.src('./builds/staging/'+config.name+'/**/*')
            .pipe(gulp.dest('svn/trunk'));
    });
    // Clean truck
    gulp.task('clean-trunk', config.prezip, function() {
        return del([
            './svn/trunk/**/*',
        ]);
    });
    // Build trunk
    gulp.task('build-assets', ['build-trunk'], function() {
        return gulp.src('./assets/wordpress/**/*')
            .pipe(gulp.dest('svn/assets'));
    });
    // Cleans SVN
    gulp.task('svn-clean', ['build-assets'], function() {
        return del([
            './builds/staging/**/*',
            './builds/staging',
        ]);
    });
    // --------------------
    // DEV
    gulp.task('default', [
        'styles',
        'scripts',
    ]);
    gulp.task('dev', [
        'styles',
        'scripts',
    ]);
    // BUILD
    gulp.task('build', [
        'styles',
        'scripts',
        'build-files',
        'jsmin',
        'cssmin',
        'build-prezip',
        'build-zip',
        'build-clean',
    ]);
    if (wordpressOrg
        && wordpressOrg.root
        && wordpressOrg.username
        && wordpressOrg.password
    ) {
        // Wordpress task
        gulp.task('wordpress', [
            'styles',
            'scripts',
            'build-files',
            'jsmin',
            'cssmin',
            'clean-trunk',
            'build-trunk',
            'build-assets',
            'svn-clean',
        ]);
    }
}<commit_msg>Add **WooCommerce** support.<commit_after>'use strict';

/**
 * Wordpress MVC gulp development file.
 * Enables predefined (standarized) tasks, such use minify or sass compilation.
 *
 * @link http://gulpjs.com/
 * @author Alejandro Mostajo <info@10quality.com>
 * @copyright 10 Quality
 * @license MIT
 * @version 1.1.1
 */

/**
 * Export module.
 * @since 1.0.0
 * @since 1.0.1 Changed execution order and added staging and gulp.
 * @since 1.0.2 Added fixes for theme check.
 * @since 1.0.3 Pretasks defined and better concat scope.
 * @since 1.0.4 Minification.
 * @since 1.0.5 Enable the option to set which directories to include on root.
 * @since 1.0.6 Added prebuild tasks to enable special customization before zip and build are made.
 * @since 1.0.7 Added prezip taks to enable special customization before zip is made.
 * @since 1.1.0 Node compatibility changes.
 * @since 1.2.0 Removes "bin" folders, adds woocommerce support, adds wordpress.org updates via SVN.
 *
 * @param object gulp   Gulp project application.
 * @param array  config Configuration file.
 */
module.exports = function(gulp, config, wordpressOrg)
{
    // Dependencies.
    if (!gulp) gulp = require('gulp');
    var sass = require('gulp-sass');
    var concat = require('gulp-concat');
    var minify = require('gulp-minify');
    var cleanCSS = require('gulp-clean-css');
    var zip = require('gulp-zip');
    var del = require('del');
    // Prepare options
    if (!config) config = {};
    if (!config.name) config.name = 'app';
    if (!config.version) config.version = '1.0.0';
    if (!config.prestyles) config.prestyles = ['sass'];
    if (!config.prescripts) config.prescripts = [];
    if (!config.prebuild) config.prebuild = ['scripts', 'styles'];
    if (!config.prezip) config.prezip = ['build-prezip', 'jsmin', 'cssmin'];
    if (!config.rootdirs) config.rootdirs = '{app,assets,vendor,woocommerce,templates}/**/*';

    // Set GULP tasks
    // SASS
    gulp.task('sass', function () {
        return gulp.src('./assets/raw/sass/*.scss')
            .pipe(sass().on('error', sass.logError))
            .pipe(gulp.dest('./assets/raw/css'));
    });
    // Styles
    gulp.task('styles', config.prestyles, function () {
        return gulp.src('./assets/raw/css/**/*.css')
            .pipe(concat('app.css'))
            .pipe(gulp.dest('./assets/css'));
    });
    // Scripts
    gulp.task('scripts', config.prescripts, function() {
        return gulp.src('./assets/raw/js/**/*.js')
            .pipe(concat('app.js'))
            .pipe(gulp.dest('./assets/js'));
    });
    // JS minify
    gulp.task('jsmin', ['scripts', 'build-prezip'], function() {
        return gulp.src('./assets/js/**/*.js')
            .pipe(minify({
                ext:{
                    min:'.js'
                }
            }))
            .pipe(gulp.dest('./builds/staging/'+config.name+'/assets/js'));
    });
    // CSS minify
    gulp.task('cssmin', ['styles', 'build-prezip'], function() {
        return gulp.src('./assets/css/**/*.css')
            .pipe(cleanCSS({compatibility: 'ie8'}))
            .pipe(gulp.dest('./builds/staging/'+config.name+'/assets/css'));
    });
    // Build files
    gulp.task('build-files', config.prebuild, function() {
        return gulp.src([
                config.rootdirs,
                './LICENSE',
                './*.{php,css,jpg,txt}'
            ])
            .pipe(gulp.dest('./builds/staging/'+config.name));
    });
    // Build clean pre zip
    gulp.task('build-prezip', ['build-files'], function() {
        return del([
            './builds/staging/'+config.name+'/assets/{raw,css,js,wordpress}/**/*',
            './builds/staging/'+config.name+'/vendor/10quality/{ayuco,wpmvc-commands}/**/*',
            './builds/staging/'+config.name+'/vendor/nikic/**/*',
            './builds/staging/'+config.name+'/vendor/bin/**/*',
            './builds/staging/'+config.name+'/vendor/10quality/{wp-file,wpmvc-logger,wpmvc-phpfastcache,wpmvc-core,wpmvc-mvc}/tests/**/*',
            './builds/staging/'+config.name+'/assets/{raw,css,js,wordpress}',
            './builds/staging/'+config.name+'/vendor/10quality/{ayuco,wpmvc-commands,nikic}',
            './builds/staging/'+config.name+'/vendor/nikic',
            './builds/staging/'+config.name+'/vendor/bin',
            './builds/staging/'+config.name+'/vendor/10quality/wp-file/{wp-file,wpmvc-logger,wpmvc-phpfastcache,wpmvc-core,wpmvc-mvc}/tests',
        ]);
    });
    // Build zip
    gulp.task('build-zip', config.prezip, function() {
        return gulp.src('./builds/staging/**/*')
            .pipe(zip(config.name+'-'+config.version+'.zip'))
            .pipe(gulp.dest('./builds'));
    });
    // Build clean
    gulp.task('build-clean', ['build-zip'], function() {
        return del([
            './builds/staging/**/*',
            './builds/staging',
        ]);
    });
    // Build trunk
    gulp.task('build-trunk', ['clean-trunk'], function() {
        return gulp.src('./builds/staging/'+config.name+'/**/*')
            .pipe(gulp.dest('svn/trunk'));
    });
    // Clean truck
    gulp.task('clean-trunk', config.prezip, function() {
        return del([
            './svn/trunk/**/*',
        ]);
    });
    // Build trunk
    gulp.task('build-assets', ['build-trunk'], function() {
        return gulp.src('./assets/wordpress/**/*')
            .pipe(gulp.dest('svn/assets'));
    });
    // Cleans SVN
    gulp.task('svn-clean', ['build-assets'], function() {
        return del([
            './builds/staging/**/*',
            './builds/staging',
        ]);
    });
    // --------------------
    // DEV
    gulp.task('default', [
        'styles',
        'scripts',
    ]);
    gulp.task('dev', [
        'styles',
        'scripts',
    ]);
    // BUILD
    gulp.task('build', [
        'styles',
        'scripts',
        'build-files',
        'jsmin',
        'cssmin',
        'build-prezip',
        'build-zip',
        'build-clean',
    ]);
    if (wordpressOrg
        && wordpressOrg.root
        && wordpressOrg.username
        && wordpressOrg.password
    ) {
        // Wordpress task
        gulp.task('wordpress', [
            'styles',
            'scripts',
            'build-files',
            'jsmin',
            'cssmin',
            'clean-trunk',
            'build-trunk',
            'build-assets',
            'svn-clean',
        ]);
    }
}<|endoftext|>


<commit_before>import { obj, arr } from "lively.lang";
import { getSystem, removeSystem, moduleEnv as _moduleEnv, moduleRecordFor as _moduleRecordFor, sourceOf as _sourceOf, printSystemConfig as _printSystemConfig } from "./src/system.js";

// System accessors
var GLOBAL = typeof window !== "undefined" ? window :
              (typeof global !== "undefined" ? global :
                (typeof self !== "undefined" ? self : this));

var defaultSystem = defaultSystem || getSystem("default");
function changeSystem(newSystem, makeGlobal) {
  defaultSystem = newSystem;
  if (makeGlobal) GLOBAL.System = newSystem;
}
function sourceOf(id) { return _sourceOf(defaultSystem, id); }
function moduleEnv(id) { return _moduleEnv(defaultSystem, id); }
function moduleRecordFor(id) { return _moduleRecordFor(defaultSystem, id); }
function printSystemConfig() { return _printSystemConfig(defaultSystem); }
export { defaultSystem as System, getSystem, removeSystem, printSystemConfig, changeSystem, sourceOf, moduleEnv, moduleRecordFor }

// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
// packages
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
import { registerPackage as _registerPackage, groupIntoPackages as _groupIntoPackages } from './src/packages.js'
function registerPackage(packageURL) { return _registerPackage(defaultSystem, packageURL); }
function groupIntoPackages(moduleNames, packageNames) { return _groupIntoPackages(defaultSystem, moduleNames, packageNames); }
export { registerPackage, groupIntoPackages }

// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
// changing modules
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
import { moduleSourceChange as _moduleSourceChange } from './src/change.js'
function moduleSourceChange(moduleName, newSource, options) { return _moduleSourceChange(defaultSystem, moduleName, newSource, options); }
export { moduleSourceChange };

// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
// dependencies
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
import {
  findDependentsOf as _findDependentsOf,
  findRequirementsOf as _findRequirementsOf,
  forgetModule as _forgetModule,
  reloadModule as _reloadModule,
  computeRequireMap
} from './src/dependencies.js'
import { importsAndExportsOf as _importsAndExportsOf } from './src/import-export.js';
function findDependentsOf(module) { return _findDependentsOf(defaultSystem, module); }
function findRequirementsOf(module) { return _findRequirementsOf(defaultSystem, module); }
function forgetModule(module, opts) { return _forgetModule(defaultSystem, module, opts); }
function reloadModule(module, opts) { return _reloadModule(defaultSystem, module, opts); }
function requireMap() { return computeRequireMap(defaultSystem); }
function importsAndExportsOf(System, moduleName, parent) { return _importsAndExportsOf(defaultSystem, moduleName, parent); }
export { findDependentsOf, findRequirementsOf, forgetModule, reloadModule, requireMap, importsAndExportsOf }

// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
// hooks
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
import { isInstalled as _isHookInstalled, install as _installHook, remove as _removeHook } from './src/hooks.js';
function isHookInstalled(methodName, hookOrName) { return _isHookInstalled(defaultSystem, methodName, hookOrName); }
function installHook(hookName, hook) { return _installHook(defaultSystem, hookName, hook); }
function removeHook(methodName, hookOrName) { return _removeHook(defaultSystem, methodName, hookOrName); }
export { isHookInstalled, installHook, removeHook }

// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
// instrumentation
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
import { wrapModuleLoad as _wrapModuleLoad, unwrapModuleLoad as _unwrapModuleLoad/*, getExceptions, setExceptions*/ } from "./src/instrumentation.js";
function wrapModuleLoad() { _wrapModuleLoad(defaultSystem); }
function unwrapModuleLoad() { _unwrapModuleLoad(defaultSystem); }

<commit_msg>runEval added to interface<commit_after>import { obj, arr } from "lively.lang";
import { getSystem, removeSystem, moduleEnv as _moduleEnv, moduleRecordFor as _moduleRecordFor, sourceOf as _sourceOf, printSystemConfig as _printSystemConfig } from "./src/system.js";

// System accessors
var GLOBAL = typeof window !== "undefined" ? window :
              (typeof global !== "undefined" ? global :
                (typeof self !== "undefined" ? self : this));

var defaultSystem = defaultSystem || getSystem("default");
function changeSystem(newSystem, makeGlobal) {
  defaultSystem = newSystem;
  if (makeGlobal) GLOBAL.System = newSystem;
}
function sourceOf(id) { return _sourceOf(defaultSystem, id); }
function moduleEnv(id) { return _moduleEnv(defaultSystem, id); }
function moduleRecordFor(id) { return _moduleRecordFor(defaultSystem, id); }
function printSystemConfig() { return _printSystemConfig(defaultSystem); }
export { defaultSystem as System, getSystem, removeSystem, printSystemConfig, changeSystem, sourceOf, moduleEnv, moduleRecordFor }

// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
// packages
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
import { registerPackage as _registerPackage, groupIntoPackages as _groupIntoPackages } from './src/packages.js'
function registerPackage(packageURL) { return _registerPackage(defaultSystem, packageURL); }
function groupIntoPackages(moduleNames, packageNames) { return _groupIntoPackages(defaultSystem, moduleNames, packageNames); }
export { registerPackage, groupIntoPackages }

// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
// changing modules
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
import { moduleSourceChange as _moduleSourceChange } from './src/change.js'
function moduleSourceChange(moduleName, newSource, options) { return _moduleSourceChange(defaultSystem, moduleName, newSource, options); }
export { moduleSourceChange };

// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
// dependencies
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
import {
  findDependentsOf as _findDependentsOf,
  findRequirementsOf as _findRequirementsOf,
  forgetModule as _forgetModule,
  reloadModule as _reloadModule,
  computeRequireMap
} from './src/dependencies.js'
import { importsAndExportsOf as _importsAndExportsOf } from './src/import-export.js';
function findDependentsOf(module) { return _findDependentsOf(defaultSystem, module); }
function findRequirementsOf(module) { return _findRequirementsOf(defaultSystem, module); }
function forgetModule(module, opts) { return _forgetModule(defaultSystem, module, opts); }
function reloadModule(module, opts) { return _reloadModule(defaultSystem, module, opts); }
function requireMap() { return computeRequireMap(defaultSystem); }
function importsAndExportsOf(System, moduleName, parent) { return _importsAndExportsOf(defaultSystem, moduleName, parent); }
export { findDependentsOf, findRequirementsOf, forgetModule, reloadModule, requireMap, importsAndExportsOf }

// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
// hooks
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
import { isInstalled as _isHookInstalled, install as _installHook, remove as _removeHook } from './src/hooks.js';
function isHookInstalled(methodName, hookOrName) { return _isHookInstalled(defaultSystem, methodName, hookOrName); }
function installHook(hookName, hook) { return _installHook(defaultSystem, hookName, hook); }
function removeHook(methodName, hookOrName) { return _removeHook(defaultSystem, methodName, hookOrName); }
export { isHookInstalled, installHook, removeHook }

// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
// instrumentation
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
import { wrapModuleLoad as _wrapModuleLoad, unwrapModuleLoad as _unwrapModuleLoad/*, getExceptions, setExceptions*/ } from "./src/instrumentation.js";
function wrapModuleLoad() { _wrapModuleLoad(defaultSystem); }
function unwrapModuleLoad() { _unwrapModuleLoad(defaultSystem); }

// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
// eval
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
import { runEval as _runEval } from './src/eval.js';
function runEval(code, options) { return _runEval(defaultSystem, code, options); }
export { runEval };

<|endoftext|>


<commit_before>//File to hold the gulp task being called in our gulpfile
module.exports = function(file, opt){
  if (!file) {
    throw new PluginError('gulp-speckjs', 'Missing file option for gulp-speckjs');
  }
  opt = opt || {};
};
<commit_msg>Added logic psuedocode<commit_after>//File to hold the gulp task being called in our gulpfile
var gutil = require('gulp-util');
var through = require('through2');
// var glob = require('glob');
var gutil = require('gulp-util');
var path = require('path');
var PluginError = gutil.PluginError;
var speck = require('speckjs');

//pass files and options into function
module.exports = function(options){
//Need to add some kind of options or default options logic
var defOption;
options = options || defOption;
var files = [];
var stream = through.obj(function (file, enc, cb) {
    if (file.isNull()) {
      cb(null, file);
      return;
    }
    if (file.isStream()) {
      cb(new gutil.PluginError('gulp-speckjs', 'Streaming not supported'));
      return;
    }
    //Grab each file
    //Run speckbuild on each file -- foreach?
    //Write string produced from that to a file with file name as origin file + w/e is in options
  });
return stream;
};
<|endoftext|>


<commit_before>var chownr = require('chownr')
var tar = require('tar-stream')
var pump = require('pump')
var mkdirp = require('mkdirp-classic')
var fs = require('fs')
var path = require('path')
var os = require('os')

var win32 = os.platform() === 'win32'

var noop = function () {}

var echo = function (name) {
  return name
}

var normalize = !win32 ? echo : function (name) {
  return name.replace(/\\/g, '/').replace(/[:?<>|]/g, '_')
}

var statAll = function (fs, stat, cwd, ignore, entries, sort) {
  var queue = entries || ['.']

  return function loop (callback) {
    if (!queue.length) return callback()
    var next = queue.shift()
    var nextAbs = path.join(cwd, next)

    stat(nextAbs, function (err, stat) {
      if (err) return callback(err)

      if (!stat.isDirectory()) return callback(null, next, stat)

      fs.readdir(nextAbs, function (err, files) {
        if (err) return callback(err)

        if (sort) files.sort()
        for (var i = 0; i < files.length; i++) {
          if (!ignore(path.join(cwd, next, files[i]))) queue.push(path.join(next, files[i]))
        }

        callback(null, next, stat)
      })
    })
  }
}

var strip = function (map, level) {
  return function (header) {
    header.name = header.name.split('/').slice(level).join('/')

    var linkname = header.linkname
    if (linkname && (header.type === 'link' || path.isAbsolute(linkname))) {
      header.linkname = linkname.split('/').slice(level).join('/')
    }

    return map(header)
  }
}

exports.pack = function (cwd, opts) {
  if (!cwd) cwd = '.'
  if (!opts) opts = {}

  var xfs = opts.fs || fs
  var ignore = opts.ignore || opts.filter || noop
  var map = opts.map || noop
  var mapStream = opts.mapStream || echo
  var statNext = statAll(xfs, opts.dereference ? xfs.stat : xfs.lstat, cwd, ignore, opts.entries, opts.sort)
  var strict = opts.strict !== false
  var umask = typeof opts.umask === 'number' ? ~opts.umask : ~processUmask()
  var dmode = typeof opts.dmode === 'number' ? opts.dmode : 0
  var fmode = typeof opts.fmode === 'number' ? opts.fmode : 0
  var pack = opts.pack || tar.pack()
  var finish = opts.finish || noop

  if (opts.strip) map = strip(map, opts.strip)

  if (opts.readable) {
    dmode |= parseInt(555, 8)
    fmode |= parseInt(444, 8)
  }
  if (opts.writable) {
    dmode |= parseInt(333, 8)
    fmode |= parseInt(222, 8)
  }

  var onsymlink = function (filename, header) {
    xfs.readlink(path.join(cwd, filename), function (err, linkname) {
      if (err) return pack.destroy(err)
      header.linkname = normalize(linkname)
      pack.entry(header, onnextentry)
    })
  }

  var onstat = function (err, filename, stat) {
    if (err) return pack.destroy(err)
    if (!filename) {
      if (opts.finalize !== false) pack.finalize()
      return finish(pack)
    }

    if (stat.isSocket()) return onnextentry() // tar does not support sockets...

    var header = {
      name: normalize(filename),
      mode: (stat.mode | (stat.isDirectory() ? dmode : fmode)) & umask,
      mtime: stat.mtime,
      size: stat.size,
      type: 'file',
      uid: stat.uid,
      gid: stat.gid
    }

    if (stat.isDirectory()) {
      header.size = 0
      header.type = 'directory'
      header = map(header) || header
      return pack.entry(header, onnextentry)
    }

    if (stat.isSymbolicLink()) {
      header.size = 0
      header.type = 'symlink'
      header = map(header) || header
      return onsymlink(filename, header)
    }

    // TODO: add fifo etc...

    header = map(header) || header

    if (!stat.isFile()) {
      if (strict) return pack.destroy(new Error('unsupported type for ' + filename))
      return onnextentry()
    }

    var entry = pack.entry(header, onnextentry)
    if (!entry) return

    var rs = mapStream(xfs.createReadStream(path.join(cwd, filename), { start: 0, end: header.size > 0 ? header.size - 1 : header.size }), header)

    rs.on('error', function (err) { // always forward errors on destroy
      entry.destroy(err)
    })

    pump(rs, entry)
  }

  var onnextentry = function (err) {
    if (err) return pack.destroy(err)
    statNext(onstat)
  }

  onnextentry()

  return pack
}

var head = function (list) {
  return list.length ? list[list.length - 1] : null
}

var processGetuid = function () {
  return process.getuid ? process.getuid() : -1
}

var processUmask = function () {
  return process.umask ? process.umask() : 0
}

exports.extract = function (cwd, opts) {
  if (!cwd) cwd = '.'
  if (!opts) opts = {}

  var xfs = opts.fs || fs
  var ignore = opts.ignore || opts.filter || noop
  var map = opts.map || noop
  var mapStream = opts.mapStream || echo
  var own = opts.chown !== false && !win32 && processGetuid() === 0
  var extract = opts.extract || tar.extract()
  var stack = []
  var now = new Date()
  var umask = typeof opts.umask === 'number' ? ~opts.umask : ~processUmask()
  var dmode = typeof opts.dmode === 'number' ? opts.dmode : 0
  var fmode = typeof opts.fmode === 'number' ? opts.fmode : 0
  var strict = opts.strict !== false

  if (opts.strip) map = strip(map, opts.strip)

  if (opts.readable) {
    dmode |= parseInt(555, 8)
    fmode |= parseInt(444, 8)
  }
  if (opts.writable) {
    dmode |= parseInt(333, 8)
    fmode |= parseInt(222, 8)
  }

  var utimesParent = function (name, cb) { // we just set the mtime on the parent dir again everytime we write an entry
    var top
    while ((top = head(stack)) && name.slice(0, top[0].length) !== top[0]) stack.pop()
    if (!top) return cb()
    xfs.utimes(top[0], now, top[1], cb)
  }

  var utimes = function (name, header, cb) {
    if (opts.utimes === false) return cb()

    if (header.type === 'directory') return xfs.utimes(name, now, header.mtime, cb)
    if (header.type === 'symlink') return utimesParent(name, cb) // TODO: how to set mtime on link?

    xfs.utimes(name, now, header.mtime, function (err) {
      if (err) return cb(err)
      utimesParent(name, cb)
    })
  }

  var chperm = function (name, header, cb) {
    var link = header.type === 'symlink'

    /* eslint-disable node/no-deprecated-api */
    var chmod = link ? xfs.lchmod : xfs.chmod
    var chown = link ? xfs.lchown : xfs.chown
    /* eslint-enable node/no-deprecated-api */

    if (!chmod) return cb()

    var mode = (header.mode | (header.type === 'directory' ? dmode : fmode)) & umask
    chmod(name, mode, function (err) {
      if (err) return cb(err)
      if (!own) return cb()
      if (!chown) return cb()
      chown(name, header.uid, header.gid, cb)
    })
  }

  extract.on('entry', function (header, stream, next) {
    header = map(header) || header
    header.name = normalize(header.name)
    var name = path.join(cwd, path.join('/', header.name))

    if (ignore(name, header)) {
      stream.resume()
      return next()
    }

    var stat = function (err) {
      if (err) return next(err)
      utimes(name, header, function (err) {
        if (err) return next(err)
        if (win32) return next()
        chperm(name, header, next)
      })
    }

    var onsymlink = function () {
      if (win32) return next() // skip symlinks on win for now before it can be tested
      xfs.unlink(name, function () {
        xfs.symlink(header.linkname, name, stat)
      })
    }

    var onlink = function () {
      if (win32) return next() // skip links on win for now before it can be tested
      xfs.unlink(name, function () {
        var srcpath = path.join(cwd, path.join('/', header.linkname))

        xfs.link(srcpath, name, function (err) {
          if (err && err.code === 'EPERM' && opts.hardlinkAsFilesFallback) {
            stream = xfs.createReadStream(srcpath)
            return onfile()
          }

          stat(err)
        })
      })
    }

    var onfile = function () {
      var ws = xfs.createWriteStream(name)
      var rs = mapStream(stream, header)

      ws.on('error', function (err) { // always forward errors on destroy
        rs.destroy(err)
      })

      pump(rs, ws, function (err) {
        if (err) return next(err)
        ws.on('close', stat)
      })
    }

    if (header.type === 'directory') {
      stack.push([name, header.mtime])
      return mkdirfix(name, {
        fs: xfs, own: own, uid: header.uid, gid: header.gid
      }, stat)
    }

    var dir = path.dirname(name)

    validate(xfs, dir, path.join(cwd, '.'), function (err, valid) {
      if (err) return next(err)
      if (!valid) return next(new Error(dir + ' is not a valid path'))

      mkdirfix(dir, {
        fs: xfs, own: own, uid: header.uid, gid: header.gid
      }, function (err) {
        if (err) return next(err)

        switch (header.type) {
          case 'file': return onfile()
          case 'link': return onlink()
          case 'symlink': return onsymlink()
        }

        if (strict) return next(new Error('unsupported type for ' + name + ' (' + header.type + ')'))

        stream.resume()
        next()
      })
    })
  })

  if (opts.finish) extract.on('finish', opts.finish)

  return extract
}

function validate (fs, name, root, cb) {
  if (name === root) return cb(null, true)
  fs.lstat(name, function (err, st) {
    if (err && err.code !== 'ENOENT') return cb(err)
    if (err || st.isDirectory()) return validate(fs, path.join(name, '..'), root, cb)
    cb(null, false)
  })
}

function mkdirfix (name, opts, cb) {
  mkdirp(name, { fs: opts.fs }, function (err, made) {
    if (!err && made && opts.own) {
      chownr(made, opts.uid, opts.gid, cb)
    } else {
      cb(err)
    }
  })
}
<commit_msg>add fix by @k13-engineering<commit_after>var chownr = require('chownr')
var tar = require('tar-stream')
var pump = require('pump')
var mkdirp = require('mkdirp-classic')
var fs = require('fs')
var path = require('path')
var os = require('os')

var win32 = os.platform() === 'win32'

var noop = function () {}

var echo = function (name) {
  return name
}

var normalize = !win32 ? echo : function (name) {
  return name.replace(/\\/g, '/').replace(/[:?<>|]/g, '_')
}

var statAll = function (fs, stat, cwd, ignore, entries, sort) {
  var queue = entries || ['.']

  return function loop (callback) {
    if (!queue.length) return callback()
    var next = queue.shift()
    var nextAbs = path.join(cwd, next)

    stat.call(fs, nextAbs, function (err, stat) {
      if (err) return callback(err)

      if (!stat.isDirectory()) return callback(null, next, stat)

      fs.readdir(nextAbs, function (err, files) {
        if (err) return callback(err)

        if (sort) files.sort()
        for (var i = 0; i < files.length; i++) {
          if (!ignore(path.join(cwd, next, files[i]))) queue.push(path.join(next, files[i]))
        }

        callback(null, next, stat)
      })
    })
  }
}

var strip = function (map, level) {
  return function (header) {
    header.name = header.name.split('/').slice(level).join('/')

    var linkname = header.linkname
    if (linkname && (header.type === 'link' || path.isAbsolute(linkname))) {
      header.linkname = linkname.split('/').slice(level).join('/')
    }

    return map(header)
  }
}

exports.pack = function (cwd, opts) {
  if (!cwd) cwd = '.'
  if (!opts) opts = {}

  var xfs = opts.fs || fs
  var ignore = opts.ignore || opts.filter || noop
  var map = opts.map || noop
  var mapStream = opts.mapStream || echo
  var statNext = statAll(xfs, opts.dereference ? xfs.stat : xfs.lstat, cwd, ignore, opts.entries, opts.sort)
  var strict = opts.strict !== false
  var umask = typeof opts.umask === 'number' ? ~opts.umask : ~processUmask()
  var dmode = typeof opts.dmode === 'number' ? opts.dmode : 0
  var fmode = typeof opts.fmode === 'number' ? opts.fmode : 0
  var pack = opts.pack || tar.pack()
  var finish = opts.finish || noop

  if (opts.strip) map = strip(map, opts.strip)

  if (opts.readable) {
    dmode |= parseInt(555, 8)
    fmode |= parseInt(444, 8)
  }
  if (opts.writable) {
    dmode |= parseInt(333, 8)
    fmode |= parseInt(222, 8)
  }

  var onsymlink = function (filename, header) {
    xfs.readlink(path.join(cwd, filename), function (err, linkname) {
      if (err) return pack.destroy(err)
      header.linkname = normalize(linkname)
      pack.entry(header, onnextentry)
    })
  }

  var onstat = function (err, filename, stat) {
    if (err) return pack.destroy(err)
    if (!filename) {
      if (opts.finalize !== false) pack.finalize()
      return finish(pack)
    }

    if (stat.isSocket()) return onnextentry() // tar does not support sockets...

    var header = {
      name: normalize(filename),
      mode: (stat.mode | (stat.isDirectory() ? dmode : fmode)) & umask,
      mtime: stat.mtime,
      size: stat.size,
      type: 'file',
      uid: stat.uid,
      gid: stat.gid
    }

    if (stat.isDirectory()) {
      header.size = 0
      header.type = 'directory'
      header = map(header) || header
      return pack.entry(header, onnextentry)
    }

    if (stat.isSymbolicLink()) {
      header.size = 0
      header.type = 'symlink'
      header = map(header) || header
      return onsymlink(filename, header)
    }

    // TODO: add fifo etc...

    header = map(header) || header

    if (!stat.isFile()) {
      if (strict) return pack.destroy(new Error('unsupported type for ' + filename))
      return onnextentry()
    }

    var entry = pack.entry(header, onnextentry)
    if (!entry) return

    var rs = mapStream(xfs.createReadStream(path.join(cwd, filename), { start: 0, end: header.size > 0 ? header.size - 1 : header.size }), header)

    rs.on('error', function (err) { // always forward errors on destroy
      entry.destroy(err)
    })

    pump(rs, entry)
  }

  var onnextentry = function (err) {
    if (err) return pack.destroy(err)
    statNext(onstat)
  }

  onnextentry()

  return pack
}

var head = function (list) {
  return list.length ? list[list.length - 1] : null
}

var processGetuid = function () {
  return process.getuid ? process.getuid() : -1
}

var processUmask = function () {
  return process.umask ? process.umask() : 0
}

exports.extract = function (cwd, opts) {
  if (!cwd) cwd = '.'
  if (!opts) opts = {}

  var xfs = opts.fs || fs
  var ignore = opts.ignore || opts.filter || noop
  var map = opts.map || noop
  var mapStream = opts.mapStream || echo
  var own = opts.chown !== false && !win32 && processGetuid() === 0
  var extract = opts.extract || tar.extract()
  var stack = []
  var now = new Date()
  var umask = typeof opts.umask === 'number' ? ~opts.umask : ~processUmask()
  var dmode = typeof opts.dmode === 'number' ? opts.dmode : 0
  var fmode = typeof opts.fmode === 'number' ? opts.fmode : 0
  var strict = opts.strict !== false

  if (opts.strip) map = strip(map, opts.strip)

  if (opts.readable) {
    dmode |= parseInt(555, 8)
    fmode |= parseInt(444, 8)
  }
  if (opts.writable) {
    dmode |= parseInt(333, 8)
    fmode |= parseInt(222, 8)
  }

  var utimesParent = function (name, cb) { // we just set the mtime on the parent dir again everytime we write an entry
    var top
    while ((top = head(stack)) && name.slice(0, top[0].length) !== top[0]) stack.pop()
    if (!top) return cb()
    xfs.utimes(top[0], now, top[1], cb)
  }

  var utimes = function (name, header, cb) {
    if (opts.utimes === false) return cb()

    if (header.type === 'directory') return xfs.utimes(name, now, header.mtime, cb)
    if (header.type === 'symlink') return utimesParent(name, cb) // TODO: how to set mtime on link?

    xfs.utimes(name, now, header.mtime, function (err) {
      if (err) return cb(err)
      utimesParent(name, cb)
    })
  }

  var chperm = function (name, header, cb) {
    var link = header.type === 'symlink'

    /* eslint-disable node/no-deprecated-api */
    var chmod = link ? xfs.lchmod : xfs.chmod
    var chown = link ? xfs.lchown : xfs.chown
    /* eslint-enable node/no-deprecated-api */

    if (!chmod) return cb()

    var mode = (header.mode | (header.type === 'directory' ? dmode : fmode)) & umask

    if (chown && own) chown.call(xfs, name, header.uid, header.gid, onchown)
    else onchown(null)

    function onchown (err) {
      if (err) return cb(err)
      if (!chmod) return cb()
      chmod.call(xfs, name, mode, cb)
    }
  }

  extract.on('entry', function (header, stream, next) {
    header = map(header) || header
    header.name = normalize(header.name)
    var name = path.join(cwd, path.join('/', header.name))

    if (ignore(name, header)) {
      stream.resume()
      return next()
    }

    var stat = function (err) {
      if (err) return next(err)
      utimes(name, header, function (err) {
        if (err) return next(err)
        if (win32) return next()
        chperm(name, header, next)
      })
    }

    var onsymlink = function () {
      if (win32) return next() // skip symlinks on win for now before it can be tested
      xfs.unlink(name, function () {
        xfs.symlink(header.linkname, name, stat)
      })
    }

    var onlink = function () {
      if (win32) return next() // skip links on win for now before it can be tested
      xfs.unlink(name, function () {
        var srcpath = path.join(cwd, path.join('/', header.linkname))

        xfs.link(srcpath, name, function (err) {
          if (err && err.code === 'EPERM' && opts.hardlinkAsFilesFallback) {
            stream = xfs.createReadStream(srcpath)
            return onfile()
          }

          stat(err)
        })
      })
    }

    var onfile = function () {
      var ws = xfs.createWriteStream(name)
      var rs = mapStream(stream, header)

      ws.on('error', function (err) { // always forward errors on destroy
        rs.destroy(err)
      })

      pump(rs, ws, function (err) {
        if (err) return next(err)
        ws.on('close', stat)
      })
    }

    if (header.type === 'directory') {
      stack.push([name, header.mtime])
      return mkdirfix(name, {
        fs: xfs, own: own, uid: header.uid, gid: header.gid
      }, stat)
    }

    var dir = path.dirname(name)

    validate(xfs, dir, path.join(cwd, '.'), function (err, valid) {
      if (err) return next(err)
      if (!valid) return next(new Error(dir + ' is not a valid path'))

      mkdirfix(dir, {
        fs: xfs, own: own, uid: header.uid, gid: header.gid
      }, function (err) {
        if (err) return next(err)

        switch (header.type) {
          case 'file': return onfile()
          case 'link': return onlink()
          case 'symlink': return onsymlink()
        }

        if (strict) return next(new Error('unsupported type for ' + name + ' (' + header.type + ')'))

        stream.resume()
        next()
      })
    })
  })

  if (opts.finish) extract.on('finish', opts.finish)

  return extract
}

function validate (fs, name, root, cb) {
  if (name === root) return cb(null, true)
  fs.lstat(name, function (err, st) {
    if (err && err.code !== 'ENOENT') return cb(err)
    if (err || st.isDirectory()) return validate(fs, path.join(name, '..'), root, cb)
    cb(null, false)
  })
}

function mkdirfix (name, opts, cb) {
  mkdirp(name, { fs: opts.fs }, function (err, made) {
    if (!err && made && opts.own) {
      chownr(made, opts.uid, opts.gid, cb)
    } else {
      cb(err)
    }
  })
}
<|endoftext|>


<commit_before>module.exports = FileArchive

var Transform = require("stream").Transform

if (!Transform) {
  Transform = require("readable-stream/transform")
}

var fs = require("fs")
var path_module = require("path")
var mkdir = require("mkdirp")
var util = require("util")
var zlib = require("zlib")
var xtend = require("xtend")

var DATE_OPTIONS = [
  {name: "year",     key: /%Y/, get: function(date) { return date.toISOString().substr(0,4)  }},
  {name: "month",    key: /%m/, get: function(date) { return date.toISOString().substr(5,2)  }},
  {name: "day",      key: /%d/, get: function(date) { return date.toISOString().substr(8,2)  }},
  {name: "iso_date", key: /%x/, get: function(date) { return date.toISOString().substr(0,10) }},
  {name: "hour",     key: /%h/, get: function(date) { return date.toISOString().substr(11,2) }},
  {name: "minute",   key: /%M/, get: function(date) { return date.toISOString().substr(14,2) }},
  {name: "second",   key: /%S/, get: function(date) { return date.toISOString().substr(17,2) }},
  {name: "iso_time", key: /%X/, get: function(date) { return date.toISOString().substr(11,8) }},
  {name: "iso",      key: /%I/, get: function(date) { return date.toISOString().substr(0,19) }},
]
var ROOT_PATH_RE = /^\//;//unix root
if ((/^win/.test(process.platform)) {//is windows
  ROOT_PATH_RE = /^[a-zA-Z]\:\\/;//win root
}

var DEFAULTS = {
  path: "out.log",
  compress: false,
}

// Date
// %Y 4-digit year
// %m month (01..12)
// %d day of month (01..31)
// %x iso8601 date portion (e.g. 2012-09-24)
// Time
// %h hour (00..23)
// %M minute (00..59)
// %S second (00..61)
// %X iso8601 time portion to the second (e.g.: 15:12:47)
// %I iso8601 date/time to the second (e.g. 2012-09-24T15:12:47)

// NOTE: date/time substitutions only work on "path" not "symlink" paths.

// symlink: "/path/too/link" // -> current log file
// compress: true // -> compress files once finished writing

function FileArchive(config) {
  if (!(this instanceof FileArchive)) return new FileArchive(config)
  Transform.call(this)
  this.cwd = process.cwd()

  var options = xtend(DEFAULTS, config)

  // TBD should check for bad filenames somewhere
  this.symlink = ""
  if (options.symlink) {
    this.symlink = options.symlink
    if (!ROOT_PATH_RE.exec(this.symlink)) {
      this.symlink = path_module.join(this.cwd, this.symlink)
    }
  }
  this.path_config = options.path
  this.compress = options.compress

  var self = this
  process.on("SIGHUP", function () {self.renew(true)})

  this.path_options = []
  this.path_options = DATE_OPTIONS.filter(function (option) {
    if (option.key.exec(self.path_config)) {
      return option
    }
  })

  this.path = this.current_name()
  this.refcount = 0

  this.renew(true)
}
util.inherits(FileArchive, Transform)

FileArchive.prototype._transform = function (chunk, encoding, cb) {
  this.renew()
  this.push(chunk)
  cb()
}

FileArchive.prototype._done = function () {
  this.refcount--
  if (this.refcount <= 0) {
    this.emit("done")
  }
}

FileArchive.prototype.renew = function (force) {
  var self = this
  var current_name = this.current_name()
  if (force || current_name !== this.path) {
    var old_path = this.path
    this.path = current_name
    var old_stream = this.stream
    mkpath(this.path)

    this.refcount++
    var newstream = fs.createWriteStream(this.path, {flags: "a", encoding: "utf8"})
    this.unpipe(this.stream)

    newstream.once("finish", this._done.bind(this))

    this.pipe(newstream)
    this.stream = newstream

    if (this.symlink) {
      mkpath(this.symlink)
      fs.unlink(this.symlink, function () {
        fs.symlink(self.path, self.symlink, function () {
          // TODO anything need to be done here?
        })
      })
    }
    if (old_stream && this.compress) {
      old_stream.on("close", function () {
        self.archive(old_path)
      })
    }
    if (old_stream && old_stream.writable) old_stream.destroySoon()
  }
}

function mkpath(path) {
  if (path.match(/\//)) {
    var path_array = path.split("/")
    // TBD use async?
    mkdir.sync(path_array.splice(0, path_array.length-1).join("/"))
  }
}

FileArchive.prototype.archive = function (path) {
  var self = this
  var inp = fs.createReadStream(path)
  var out = fs.createWriteStream(path + ".gz")
  inp.on("end", function () {
    fs.unlink(path)
    self._done()
  })
  inp.pipe(zlib.createGzip()).pipe(out)
}

FileArchive.prototype.current_name = function () {
  if (this.path && this.path_options.length == 0)
    return this.path

  var d = new Date()
  var path = this.path_config

  this.path_options.forEach(function (option) {
    path = path.replace(option.key, option.get(d))
  })

  // Moving this to initialization would gain some perf, but it would break
  // the ability to have the first part of the path be a date part to substitute
  if (!ROOT_PATH_RE.exec(path)) {
    path = path_module.join(this.cwd, path)
  }
  return path
}
<commit_msg>fix(typo)<commit_after>module.exports = FileArchive

var Transform = require("stream").Transform

if (!Transform) {
  Transform = require("readable-stream/transform")
}

var fs = require("fs")
var path_module = require("path")
var mkdir = require("mkdirp")
var util = require("util")
var zlib = require("zlib")
var xtend = require("xtend")

var DATE_OPTIONS = [
  {name: "year",     key: /%Y/, get: function(date) { return date.toISOString().substr(0,4)  }},
  {name: "month",    key: /%m/, get: function(date) { return date.toISOString().substr(5,2)  }},
  {name: "day",      key: /%d/, get: function(date) { return date.toISOString().substr(8,2)  }},
  {name: "iso_date", key: /%x/, get: function(date) { return date.toISOString().substr(0,10) }},
  {name: "hour",     key: /%h/, get: function(date) { return date.toISOString().substr(11,2) }},
  {name: "minute",   key: /%M/, get: function(date) { return date.toISOString().substr(14,2) }},
  {name: "second",   key: /%S/, get: function(date) { return date.toISOString().substr(17,2) }},
  {name: "iso_time", key: /%X/, get: function(date) { return date.toISOString().substr(11,8) }},
  {name: "iso",      key: /%I/, get: function(date) { return date.toISOString().substr(0,19) }},
]
var ROOT_PATH_RE = /^\//;//unix root
if (/^win/.test(process.platform)) {//is windows
  ROOT_PATH_RE = /^[a-zA-Z]\:\\/;//win root
}

var DEFAULTS = {
  path: "out.log",
  compress: false,
}

// Date
// %Y 4-digit year
// %m month (01..12)
// %d day of month (01..31)
// %x iso8601 date portion (e.g. 2012-09-24)
// Time
// %h hour (00..23)
// %M minute (00..59)
// %S second (00..61)
// %X iso8601 time portion to the second (e.g.: 15:12:47)
// %I iso8601 date/time to the second (e.g. 2012-09-24T15:12:47)

// NOTE: date/time substitutions only work on "path" not "symlink" paths.

// symlink: "/path/too/link" // -> current log file
// compress: true // -> compress files once finished writing

function FileArchive(config) {
  if (!(this instanceof FileArchive)) return new FileArchive(config)
  Transform.call(this)
  this.cwd = process.cwd()

  var options = xtend(DEFAULTS, config)

  // TBD should check for bad filenames somewhere
  this.symlink = ""
  if (options.symlink) {
    this.symlink = options.symlink
    if (!ROOT_PATH_RE.exec(this.symlink)) {
      this.symlink = path_module.join(this.cwd, this.symlink)
    }
  }
  this.path_config = options.path
  this.compress = options.compress

  var self = this
  process.on("SIGHUP", function () {self.renew(true)})

  this.path_options = []
  this.path_options = DATE_OPTIONS.filter(function (option) {
    if (option.key.exec(self.path_config)) {
      return option
    }
  })

  this.path = this.current_name()
  this.refcount = 0

  this.renew(true)
}
util.inherits(FileArchive, Transform)

FileArchive.prototype._transform = function (chunk, encoding, cb) {
  this.renew()
  this.push(chunk)
  cb()
}

FileArchive.prototype._done = function () {
  this.refcount--
  if (this.refcount <= 0) {
    this.emit("done")
  }
}

FileArchive.prototype.renew = function (force) {
  var self = this
  var current_name = this.current_name()
  if (force || current_name !== this.path) {
    var old_path = this.path
    this.path = current_name
    var old_stream = this.stream
    mkpath(this.path)

    this.refcount++
    var newstream = fs.createWriteStream(this.path, {flags: "a", encoding: "utf8"})
    this.unpipe(this.stream)

    newstream.once("finish", this._done.bind(this))

    this.pipe(newstream)
    this.stream = newstream

    if (this.symlink) {
      mkpath(this.symlink)
      fs.unlink(this.symlink, function () {
        fs.symlink(self.path, self.symlink, function () {
          // TODO anything need to be done here?
        })
      })
    }
    if (old_stream && this.compress) {
      old_stream.on("close", function () {
        self.archive(old_path)
      })
    }
    if (old_stream && old_stream.writable) old_stream.destroySoon()
  }
}

function mkpath(path) {
  if (path.match(/\//)) {
    var path_array = path.split("/")
    // TBD use async?
    mkdir.sync(path_array.splice(0, path_array.length-1).join("/"))
  }
}

FileArchive.prototype.archive = function (path) {
  var self = this
  var inp = fs.createReadStream(path)
  var out = fs.createWriteStream(path + ".gz")
  inp.on("end", function () {
    fs.unlink(path)
    self._done()
  })
  inp.pipe(zlib.createGzip()).pipe(out)
}

FileArchive.prototype.current_name = function () {
  if (this.path && this.path_options.length == 0)
    return this.path

  var d = new Date()
  var path = this.path_config

  this.path_options.forEach(function (option) {
    path = path.replace(option.key, option.get(d))
  })

  // Moving this to initialization would gain some perf, but it would break
  // the ability to have the first part of the path be a date part to substitute
  if (!ROOT_PATH_RE.exec(path)) {
    path = path_module.join(this.cwd, path)
  }
  return path
}
<|endoftext|>