<commit_before>#!/usr/bin/env node
var utils = require('../utils')
  , argv = require('optimist').boolean(['billable', 'b'])
                              .default('date', utils.today())
                              .default('hours', 8)
                              .default('description', '')
                              .argv
  , futures = require('futures')
  , config = require('../config')
  , intervals = require('../intervals')
;

/**
 * Add time for each dates specified
 */
function addTime(options, client) {
    return function(next, project) {
        var dates = options.dates;
        delete options.dates;
        var join = futures.join();
        join.add(dates.map(function(date) {
            var promise = futures.future();
            // we must clone to prevent options.date override
            var opts = utils.clone(options);
            opts.date = date;
            var message = ('Save '+ opts.time + ' ' +
                           (opts.billable ? 'billable' : 'non billable') +
                           ' hours for '+ opts.date);
            intervals.addTime(project, opts, client, function (err, res) {
                var msg = 'OK';
                if (err) { msg = 'ERROR'; console.error(err); }
                else if (res.status != 201) { msg = 'ERROR'; console.error('Unexpected status '+ res.status +' for addTime method'); };
                console.log(message + ' ' + msg);
                promise.deliver();
            });
            return promise;
        }));
        join.when(function() {
            next(project);
        });
    };
}

function askForToken(callback) {
    config.read(function(err, value) {
        if (err) {
            if (err.code == 'ENOENT') {
                process.stdout.write('Please enter your token (go to https://xx.timetask.com/account/api/ and generate a new one): ');
                utils.readInput(function(input) {
                    config.write({token: input}, function(err) {
                        if (err) throw err;
                        console.log('token saved in '+ config.path);
                        callback({token: input});
                    });
                });
            } else {
                throw err;
            }
        } else {
            callback(value);
        }
    });
}

/**
 * Ask user to save the project
 */
function askForSave(conf) {
    return function(next, project) {
        process.stdout.write('Do you yant to save this project combinaison: (y/N)');
        utils.readInput(function(input) {
            if (input == 'y') {
                process.stdout.write('Name of this combinaison: ');
                utils.readInput(function(input) {
                    conf.projects ? '': conf.projects = [];
                    project.name = input;
                    conf.projects.push(project);
                    config.write(conf, function(err) {
                        if (err) throw err;
                        console.log('ok. You can add time to this combinaison with intervals --project '+ input);
                        next();
                    })
                });
            } else {
                next();
            }
        });
    }
}

/**
 * Extract options from argv
 */
function optionsFrom(argv) {
    var date     = argv.date,
        dates    = utils.parseDate(date),
        options  = { time: argv.hours,
                     dates: dates,
                     billable: argv.billable || argv.b,
                     description: argv.description };
    return options;
}

function loadProject(conf, argv) {
    return function(next) {
        for (var i in conf.projects) {
            if (conf.projects[i].name == argv.project) {
                var project = conf.projects[i];
                delete project.name;
                next(project);
            }
        }
        console.error('The project '+ argv.project +" doesn't exist.");
    }
}
/**
 * Add time is the default action
 */
if (argv._.length == 0) {
    argv._.push('add-time');
}
var cmd = argv._[0];

if (argv.version || cmd == 'version' || argv.v) {
    return require('../version')();
} else if (argv.help || cmd == 'help') {
    return require('../help')();
} else if (cmd == 'list-projects') {
    askForToken(function(conf) {
        if (Array.isArray(conf.projects) && conf.projects.length) {
            conf.projects.forEach(function(project) {
                console.log(project.name, ":");
                console.log(config.toYaml(project.human, '  '));
            });
        } else {
            console.log('No projects found. Register a new one with intervals add-time.');
        }
    });
} else if (cmd == 'add-time') {
    askForToken(function(conf) {
        var options  = optionsFrom(argv),
            sequence = null;

        console.log('Add '+ options.time + ' ' +
                    (options.billable ? 'billable' : 'non billable') +
                    ' hours for '+ options.dates.join(' and '));
        var client = intervals.createClient(conf.token);
        var sequence = futures.sequence();
        if (argv.project) {
            sequence.then(loadProject(conf, argv))
                    .then(addTime(options, client));
        } else {
            sequence.then(intervals.askForProject(client))
                    .then(addTime(options, client))
                    .then(askForSave(conf));
        }
    });
} else if (cmd == 'ls') {
    askForToken(function(conf) {
        require('../list')(conf, argv);
    });
} else if (cmd == 'start-timer' || cmd == 'get-timer'
           || cmd == 'delete-timer' || cmd == 'list-timers') {
    askForToken(function(conf) {
        require('../timer')(conf, argv);
    });
} else if (cmd == 'completion') {
    askForToken(function(conf) {
        require('../completion')(conf);
    });
} else {
    return require('../help')();
}
<commit_msg>Quit the loop after found the good project.<commit_after>#!/usr/bin/env node
var utils = require('../utils')
  , argv = require('optimist').boolean(['billable', 'b'])
                              .default('date', utils.today())
                              .default('hours', 8)
                              .default('description', '')
                              .argv
  , futures = require('futures')
  , config = require('../config')
  , intervals = require('../intervals')
;

/**
 * Add time for each dates specified
 */
function addTime(options, client) {
    return function(next, project) {
        var dates = options.dates;
        delete options.dates;
        var join = futures.join();
        join.add(dates.map(function(date) {
            var promise = futures.future();
            // we must clone to prevent options.date override
            var opts = utils.clone(options);
            opts.date = date;
            var message = ('Save '+ opts.time + ' ' +
                           (opts.billable ? 'billable' : 'non billable') +
                           ' hours for '+ opts.date);
            intervals.addTime(project, opts, client, function (err, res) {
                var msg = 'OK';
                if (err) { msg = 'ERROR'; console.error(err); }
                else if (res.status != 201) { msg = 'ERROR'; console.error('Unexpected status '+ res.status +' for addTime method'); };
                console.log(message + ' ' + msg);
                promise.deliver();
            });
            return promise;
        }));
        join.when(function() {
            next(project);
        });
    };
}

function askForToken(callback) {
    config.read(function(err, value) {
        if (err) {
            if (err.code == 'ENOENT') {
                process.stdout.write('Please enter your token (go to https://xx.timetask.com/account/api/ and generate a new one): ');
                utils.readInput(function(input) {
                    config.write({token: input}, function(err) {
                        if (err) throw err;
                        console.log('token saved in '+ config.path);
                        callback({token: input});
                    });
                });
            } else {
                throw err;
            }
        } else {
            callback(value);
        }
    });
}

/**
 * Ask user to save the project
 */
function askForSave(conf) {
    return function(next, project) {
        process.stdout.write('Do you yant to save this project combinaison: (y/N)');
        utils.readInput(function(input) {
            if (input == 'y') {
                process.stdout.write('Name of this combinaison: ');
                utils.readInput(function(input) {
                    conf.projects ? '': conf.projects = [];
                    project.name = input;
                    conf.projects.push(project);
                    config.write(conf, function(err) {
                        if (err) throw err;
                        console.log('ok. You can add time to this combinaison with intervals --project '+ input);
                        next();
                    })
                });
            } else {
                next();
            }
        });
    }
}

/**
 * Extract options from argv
 */
function optionsFrom(argv) {
    var date     = argv.date,
        dates    = utils.parseDate(date),
        options  = { time: argv.hours,
                     dates: dates,
                     billable: argv.billable || argv.b,
                     description: argv.description };
    return options;
}

function loadProject(conf, argv) {
    return function(next) {
        for (var i in conf.projects) {
            if (conf.projects[i].name == argv.project) {
                var project = conf.projects[i];
                delete project.name;
                return next(project);
            }
        }
        console.error('The project '+ argv.project +" doesn't exist.");
    }
}
/**
 * Add time is the default action
 */
if (argv._.length == 0) {
    argv._.push('add-time');
}
var cmd = argv._[0];

if (argv.version || cmd == 'version' || argv.v) {
    return require('../version')();
} else if (argv.help || cmd == 'help') {
    return require('../help')();
} else if (cmd == 'list-projects') {
    askForToken(function(conf) {
        if (Array.isArray(conf.projects) && conf.projects.length) {
            conf.projects.forEach(function(project) {
                console.log(project.name, ":");
                console.log(config.toYaml(project.human, '  '));
            });
        } else {
            console.log('No projects found. Register a new one with intervals add-time.');
        }
    });
} else if (cmd == 'add-time') {
    askForToken(function(conf) {
        var options  = optionsFrom(argv),
            sequence = null;

        console.log('Add '+ options.time + ' ' +
                    (options.billable ? 'billable' : 'non billable') +
                    ' hours for '+ options.dates.join(' and '));
        var client = intervals.createClient(conf.token);
        var sequence = futures.sequence();
        if (argv.project) {
            sequence.then(loadProject(conf, argv))
                    .then(addTime(options, client));
        } else {
            sequence.then(intervals.askForProject(client))
                    .then(addTime(options, client))
                    .then(askForSave(conf));
        }
    });
} else if (cmd == 'ls') {
    askForToken(function(conf) {
        require('../list')(conf, argv);
    });
} else if (cmd == 'start-timer' || cmd == 'get-timer'
           || cmd == 'delete-timer' || cmd == 'list-timers') {
    askForToken(function(conf) {
        require('../timer')(conf, argv);
    });
} else if (cmd == 'completion') {
    askForToken(function(conf) {
        require('../completion')(conf);
    });
} else {
    return require('../help')();
}
<|endoftext|>


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

'use strict';

const fs = require('fs');
const imageWrite = require('../lib/write');
const image = process.argv[2];
const device = process.argv[3];

if (!image || !device) {
  console.error('Usage: <image> <device>');
  process.exit(1);
}

const imageStream = fs.createReadStream(image);

console.log('Writing', image, 'to', device);

imageWrite.write(device, imageStream, {
  check: true,
  size: fs.statSync(image).size
})
  .on('progress', (state) => {
    console.log(state);
  })
  .on('error', (error) => {
    console.error(error);
  })
  .on('done', () => {
    console.log('Finished writing to device');
  });
<commit_msg>Fix non-working CLI example from `bin/cli.js` (#80)<commit_after>#!/usr/bin/env node

'use strict';

const drivelist = require('drivelist');
const _ = require('lodash');
const fs = require('fs');
const imageWrite = require('../lib/index');
const image = process.argv[2];
const device = process.argv[3];

const handleError = (error) => {
  console.error(error.message || error);
  process.exit(1);
};

if (!image || !device) {
  handleError('Usage: <image> <device>');
}

drivelist.list((error, drives) => {
  if (error) {
    return handleError(error);
  }

  const drive = _.find(drives, {
    device
  });

  if (!drive) {
    return handleError(`Unknown device: ${device}`);
  }

  console.log('Writing', image, 'to', device);

  imageWrite.write({
    fd: fs.openSync(drive.raw, 'rs+'),
    device: drive.raw,
    size: drive.size
  }, {
    stream: fs.createReadStream(image),
    size: fs.statSync(image).size
  }, {
    check: true
  })
    .on('error', handleError)
    .on('progress', (state) => {
      console.log(state);
    })
    .on('done', (results) => {
      console.log('Finished writing to device');
      console.log(JSON.stringify(results, null, 2));
    });
});
<|endoftext|>


<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, '<commit_msg>Work in Progress<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w<|endoftext|>


<commit_before>/**
    Copyright 2014-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.

    Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at

        http://aws.amazon.com/apache2.0/

    or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/

/**
 * This simple sample has no external dependencies or session management, and shows the most basic
 * example of how to create a Lambda function for handling Alexa Skill requests.
 *
 * Examples:
 * One-shot model:
 *  User: "Alexa, ask Space Geek for a space fact"
 *  Alexa: "Here's your space fact: ..."
 */

/**
 * App ID for the skill
 */
var APP_ID = undefined; //replace with "amzn1.echo-sdk-ams.app.[your-unique-value-here]";

var BASE_URL="http://api.railwayapi.com/";
var trains={
	[
	"name":"SOLAPUR MIRAJ SPECIAL",
	"id":"1413",
	"from":"SOLAPUR",
	"to":"MIRAJ"],
	[
	"name":"MIRAJ SOLAPUR SPECIAL",
	"id":"1414",
	"from":"MIRAJ",
	"to":"SOLAPUR"]
};
/**
 * Array containing API keys
 */
var API_KEYS = [
    "bfzhr4575",
    "puzgi7810",
    "xtjxm1892",
    "adieg3070",
    "bkxel1825",
    "bkjjv3426",
    "euhuq6862",
    "mdtzh6188"
];

/**
 * The AlexaSkill prototype and helper functions
 */
var AlexaSkill = require('./AlexaSkill');

/**
 * SpaceGeek is a child of AlexaSkill.
 * To read more about inheritance in JavaScript, see the link below.
 *
 * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript#Inheritance
 */
var Raily = function () {
    AlexaSkill.call(this, APP_ID);
};

// Extend AlexaSkill
Raily.prototype = Object.create(AlexaSkill.prototype);
Raily.prototype.constructor = SpaceGeek;

Raily.prototype.eventHandlers.onSessionStarted = function (sessionStartedRequest, session) {
    console.log("Raily onSessionStarted requestId: " + sessionStartedRequest.requestId
        + ", sessionId: " + session.sessionId);
    // any initialization logic goes here
};

Raily.prototype.eventHandlers.onLaunch = function (launchRequest, session, response) {
    console.log("Raily onLaunch requestId: " + launchRequest.requestId + ", sessionId: " + session.sessionId);
    handleNewFactRequest(response);
};

/**
 * Overridden to show that a subclass can override this function to teardown session state.
 */
Raily.prototype.eventHandlers.onSessionEnded = function (sessionEndedRequest, session) {
    console.log("Raily onSessionEnded requestId: " + sessionEndedRequest.requestId
        + ", sessionId: " + session.sessionId);
    // any cleanup logic goes here
};

Raily.prototype.intentHandlers = {
    "GetTrainDetailsIntent": function (intent, session, response) {
        handleNewTrainRequest(response);
    },

    "AMAZON.HelpIntent": function (intent, session, response) {
        response.ask("You can ask Indian Railways tell me the details of a train, or, you can say exit... What can I help you with?", "What can I help you with?");
    },

    "AMAZON.StopIntent": function (intent, session, response) {
        var speechOutput = "Goodbye";
        response.tell(speechOutput);
    },

    "AMAZON.CancelIntent": function (intent, session, response) {
        var speechOutput = "Goodbye";
        response.tell(speechOutput);
    }
};

/**
 * Gets a random new fact from the list and returns to the user.
 */
function handleNewTrainRequest(response) {
    // Get a random space fact from the space facts list
    var keyIndex = Math.floor(Math.random() * API_KEYS.length);
    var apiKey = API_KEYS[keyIndex];

    // Create speech output
    var speechOutput = "Here's your train details fact: " + "put details here";

    response.tellWithCard(speechOutput, "Raily- Indian Railways", speechOutput);
}

// Create the handler that responds to the Alexa Request.
exports.handler = function (event, context) {
    // Create an instance of the SpaceGeek skill.
    var raily = new Raily();
    Raily.execute(event, context);
};

<commit_msg>Delete index.js<commit_after><|endoftext|>


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

const chalk = require('chalk');
const minimist = require('minimist');
const redent = require('redent');
const trimNewlines = require('trim-newlines');

const qgen = require('../');

/**
 * Displays prewritten help message to stdout
 *
 * @return {undefined}
 */
const showHelp = () => {
	const helpText = `
		${chalk.bold('Usage')}
			$ qgen <template name> [dest] [arguments] [options]

		${chalk.bold('Options')}
		--directory=<dir>	Templates directory # Default: ./gqen-templates
		--config=<path>	Path to the JSON config file # Default: ./qgen.json

		${chalk.bold('Examples')}
			$ qgen post ${chalk.dim('# generates the post template in the current folder')}
			$ qgen post ./pages ${chalk.dim('# generates the post template inside ./pages')}
			$ qgen post ./pages --page-title "Hello World" ${chalk.dim('# generates the post template in inside ./pages with data field pageTitle="Hello World" to the template rendering engine')}
	`;

	const help = redent(trimNewlines(helpText).replace(/\t+\n*$/, ''), 2);

	console.log(help);
};

/**
 * Displays list of available templates to stdout
 *
 * @param  {Object} options - options for qgen
 * @return {undefined}
 */
const listTemplates = options => {
	const templates = qgen(options).templates();
	if (Array.isArray(templates) && templates.length > 0) {
		console.log(redent(`	${chalk.bold('Available Templates')}`, 2));
		templates.forEach(template => {
			console.log(redent(`${template}`, 4));
		});
	}
};

const argv = minimist(process.argv.slice(2));

// Display help and available templates help flag is set or no arguments passed
if (argv.help || argv._.length === 0) {
	showHelp();
	listTemplates(argv);
} else {
	try {
		qgen(argv).render(argv._[0], argv._[1]);
	} catch (err) {
		console.error(err.message);
		process.exit(1);
	}
}
<commit_msg>fix(cli): handles exceptions better<commit_after>#!/usr/bin/env node
'use strict';

const chalk = require('chalk');
const minimist = require('minimist');
const redent = require('redent');
const trimNewlines = require('trim-newlines');

const qgen = require('../');

/**
 * Displays prewritten help message to stdout
 *
 * @return {undefined}
 */
const showHelp = () => {
	const helpText = `
		${chalk.bold('Usage')}
			$ qgen <template name> [dest] [arguments] [options]

		${chalk.bold('Options')}
		--directory=<dir>	Templates directory # Default: ./gqen-templates
		--config=<path>	Path to the JSON config file # Default: ./qgen.json

		${chalk.bold('Examples')}
			$ qgen post ${chalk.dim('# generates the post template in the current folder')}
			$ qgen post ./pages ${chalk.dim('# generates the post template inside ./pages')}
			$ qgen post ./pages --page-title "Hello World" ${chalk.dim('# generates the post template in inside ./pages with data field pageTitle="Hello World" to the template rendering engine')}
	`;

	const help = redent(trimNewlines(helpText).replace(/\t+\n*$/, ''), 2);

	console.log(help);
};

/**
 * Displays list of available templates to stdout
 *
 * @param  {Object} options - options for qgen
 * @return {undefined}
 */
const listTemplates = options => {
	try {
		const templates = qgen(options).templates();
		if (Array.isArray(templates) && templates.length > 0) {
			console.log(redent(`	${chalk.bold('Available Templates')}`, 2));
			templates.forEach(template => {
				console.log(redent(`${template}`, 4));
			});
		}
	} catch (err) {
		console.error(err.message);
		process.exit(1);
	}
};

const argv = minimist(process.argv.slice(2));

// Display help and available templates help flag is set or no arguments passed
if (argv.help || argv._.length === 0) {
	showHelp();
	listTemplates(argv);
} else {
	try {
		qgen(argv).render(argv._[0], argv._[1]);
	} catch (err) {
		console.error(err.message);
		process.exit(1);
	}
}
<|endoftext|>


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

const commandLineArgs = require('command-line-args');
const commandLineCommands = require('command-line-commands');
const fs = require('fs-extra');
const os = require('os');
const package = require('../package.json');
const path = require('path');
const ChildProcess = require('child_process');

const validCommands = [ null, 'run' ];
const { command, argv } = commandLineCommands(validCommands);
const optionDefinitions = [
  { name: 'jsdebugger', type: Boolean },
  { name: 'path', type: String, defaultOption: true },
];
const options = commandLineArgs(optionDefinitions, { argv: argv });

const DIST_DIR = path.join(__dirname, '..', 'dist');

const EXECUTABLE_DIR = process.platform === 'darwin' ?
                       path.join(DIST_DIR, 'Runtime.app', 'Contents', 'MacOS') :
                       path.join(DIST_DIR, 'runtime');

const EXECUTABLE = process.platform === 'win32' ?
                   path.join(EXECUTABLE_DIR, 'firefox.exe') :
                   path.join(EXECUTABLE_DIR, 'firefox');

const applicationIni = path.join(__dirname, '..', 'application.ini');
const profileDir = fs.mkdtempSync(path.join(os.tmpdir(), `${package.name}-profile-`));
console.log(`profileDir: ${profileDir}`);

let executableArgs = [
  '--app', applicationIni,
  '--profile', profileDir,
  options.path,
];

// The Mac and Linux runtimes accept either -jsdebugger or --jsdebugger,
// but Windows needs the former, so we use it for all platforms.
options.jsdebugger && executableArgs.push('-jsdebugger');

process.env.MOZ_NO_REMOTE = 1;

const childProcess = ChildProcess.spawn(EXECUTABLE, executableArgs, {
  stdio: 'inherit',
});
childProcess.on('close', code => {
  fs.removeSync(profileDir);
  process.exit(code);
});
<commit_msg>don't log profile dir<commit_after>#!/usr/bin/env node

const commandLineArgs = require('command-line-args');
const commandLineCommands = require('command-line-commands');
const fs = require('fs-extra');
const os = require('os');
const package = require('../package.json');
const path = require('path');
const ChildProcess = require('child_process');

const validCommands = [ null, 'run' ];
const { command, argv } = commandLineCommands(validCommands);
const optionDefinitions = [
  { name: 'jsdebugger', type: Boolean },
  { name: 'path', type: String, defaultOption: true },
];
const options = commandLineArgs(optionDefinitions, { argv: argv });

const DIST_DIR = path.join(__dirname, '..', 'dist');

const EXECUTABLE_DIR = process.platform === 'darwin' ?
                       path.join(DIST_DIR, 'Runtime.app', 'Contents', 'MacOS') :
                       path.join(DIST_DIR, 'runtime');

const EXECUTABLE = process.platform === 'win32' ?
                   path.join(EXECUTABLE_DIR, 'firefox.exe') :
                   path.join(EXECUTABLE_DIR, 'firefox');

const applicationIni = path.join(__dirname, '..', 'application.ini');
const profileDir = fs.mkdtempSync(path.join(os.tmpdir(), `${package.name}-profile-`));

let executableArgs = [
  '--app', applicationIni,
  '--profile', profileDir,
  options.path,
];

// The Mac and Linux runtimes accept either -jsdebugger or --jsdebugger,
// but Windows needs the former, so we use it for all platforms.
options.jsdebugger && executableArgs.push('-jsdebugger');

process.env.MOZ_NO_REMOTE = 1;

const childProcess = ChildProcess.spawn(EXECUTABLE, executableArgs, {
  stdio: 'inherit',
});
childProcess.on('close', code => {
  fs.removeSync(profileDir);
  process.exit(code);
});
<|endoftext|>


<commit_before>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
//Added a comment that achieves no real goal.

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    console.info("Bytes: %s", length)
    try {
      child_process.execFileSync('/usr/bin/git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
    var args = ['commit', outFile, '-m', message]
    for (var counter = 0; counter < length; counter++)
    {
      var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
      var args = ['commit', outFile, '-m', message]
      fs.writeSync(outFD, data.slice(counter, counter+1), 0, 1)
      sleep(Math.random() * max_sleep)
      child_process.execFileSync('/usr/bin/git', args)
    }
  })
} else {
  console.info("Usage:")
  console.info("node commit.js infile outfile [time in seconds]")
}

function sleep(seconds) {
  var endTime = new Date().getTime() + (seconds * 1000);
  while (new Date().getTime() <= endTime) {;}
}

process.on('exit', function () {
  var args = ['push']
  child_process.execFileSync('/usr/bin/git', args)
})

function randomIntFromInterval(min,max)
{
   return Math.floor(Mat<commit_msg>AAAAAAAAAAARGH!<commit_after>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
//Added a comment that achieves no real goal.

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    console.info("Bytes: %s", length)
    try {
      child_process.execFileSync('/usr/bin/git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
    var args = ['commit', outFile, '-m', message]
    for (var counter = 0; counter < length; counter++)
    {
      var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
      var args = ['commit', outFile, '-m', message]
      fs.writeSync(outFD, data.slice(counter, counter+1), 0, 1)
      sleep(Math.random() * max_sleep)
      child_process.execFileSync('/usr/bin/git', args)
    }
  })
} else {
  console.info("Usage:")
  console.info("node commit.js infile outfile [time in seconds]")
}

function sleep(seconds) {
  var endTime = new Date().getTime() + (seconds * 1000);
  while (new Date().getTime() <= endTime) {;}
}

process.on('exit', function () {
  var args = ['push']
  child_process.execFileSync('/usr/bin/git', args)
})

function randomIntFromInterval(min,max)
{
   return Math.floor(Math<|endoftext|>


<commit_before>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
//Added a comment that achieves no real goal.

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    console.info("Bytes: %s", length)
    try {
      child_process.execFileSync('/usr/bin/git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
    var args = ['commit', outFile, '-m', message]
    for (var counter = 0; counter < length; counter++)
    {
      var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
      va<commit_msg>Someone poisoned the waterhole!<commit_after>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
//Added a comment that achieves no real goal.

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    console.info("Bytes: %s", length)
    try {
      child_process.execFileSync('/usr/bin/git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
    var args = ['commit', outFile, '-m', message]
    for (var counter = 0; counter < length; counter++)
    {
      var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
      var<|endoftext|>


<commit_before>var log = require('./lib/logger');
var path = require('path');

function createTempOutputDir() {
	var temp = require('temp').track();
	var tempDir = temp.mkdirSync('docsplayer');

	process.on('SIGINT', function() {
		temp.cleanupSync();
		process.exit();
	});

	return tempDir;
}

function startDocs(src, opts) {

	opts = opts || {};

	var options = {
		port: opts.port || 8000,
		debug: opts.debug || false,
		ignored: opts.ignored || /([\/\\]\.|node_modules)/,
		src: src || path.join(process.cwd(), '**/*.md'),
		docsDestDir: opts.docsDestDir || createTempOutputDir(),
		theme: opts.theme || 'default',
		watch: opts.watch || false,
	};

	var docsServer = require('./lib/docs-server');
	var docsBuilder = require('./lib/docs-builder');
	var docsThemes = require('./lib/docs-themes');

	log.setDebug(options.debug || false);
	docsBuilder.build(options.src, options.docsDestDir, options, function() {

		var themePaths = docsThemes.readThemePaths(options.theme);
		if (!themePaths.length)
			return;

		log.info('Using docs theme:', log.colors.green(options.theme));

		docsServer.start({
			themePaths: themePaths,
			docsSrc: options.docsDestDir,
			port: options.port || 8000
		});
	});
}

function runCli() {
	var argv = require('yargs')
		.string('initTheme')
		.argv;

	log.setDebug(argv.debug || false);

	if (argv.initTheme) {
		return require('./lib/docs-themes').initTheme(argv.initTheme === true ? null : argv.initTheme);
	}

	if (argv.listThemes) {
		return require('./lib/docs-themes').listThemes();
	}

	startDocs(argv.src, argv);
}

module.exports = {
	start: startDocs,
	cli: runCli
};
<commit_msg>Multiple src attributes<commit_after>var log = require('./lib/logger');
var path = require('path');

function createTempOutputDir() {
	var temp = require('temp').track();
	var tempDir = temp.mkdirSync('docsplayer');

	process.on('SIGINT', function() {
		temp.cleanupSync();
		process.exit();
	});

	return tempDir;
}

function startDocs(src, opts) {

	opts = opts || {};
	src = typeof src === 'string' ? src.split(',') : src;

	var options = {
		port: opts.port || 8000,
		debug: opts.debug || false,
		ignored: opts.ignored || /([\/\\]\.|node_modules)/,
		src: src || path.join(process.cwd(), '**/*.md'),
		docsDestDir: opts.docsDestDir || createTempOutputDir(),
		theme: opts.theme || 'default',
		watch: opts.watch || false,
	};

	var docsServer = require('./lib/docs-server');
	var docsBuilder = require('./lib/docs-builder');
	var docsThemes = require('./lib/docs-themes');

	log.setDebug(options.debug || false);
	docsBuilder.build(options.src, options.docsDestDir, options, function() {

		var themePaths = docsThemes.readThemePaths(options.theme);
		if (!themePaths.length)
			return;

		log.info('Using docs theme:', log.colors.green(options.theme));

		docsServer.start({
			themePaths: themePaths,
			docsSrc: options.docsDestDir,
			port: options.port || 8000
		});
	});
}

function runCli() {
	var argv = require('yargs')
		.string('initTheme')
		.argv;

	log.setDebug(argv.debug || false);

	if (argv.initTheme) {
		return require('./lib/docs-themes').initTheme(argv.initTheme === true ? null : argv.initTheme);
	}

	if (argv.listThemes) {
		return require('./lib/docs-themes').listThemes();
	}

	startDocs(argv.src, argv);
}

module.exports = {
	start: startDocs,
	cli: runCli
};
<|endoftext|>


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

var util = require('util');
var path = require('path');
var assemble = require('..');
var commands = require('../lib/commands');
var plugins = require('../lib/plugins');
var utils = require('../lib/utils');
var errors = require('./errors');
var argv = utils.parseArgs(process.argv.slice(2));

function run(cb) {
  var cwd = process.cwd();
  var app;

  /**
   * Set the working directory
   */

  if (argv.cwd && cwd !== path.resolve(argv.cwd)) {
    process.chdir(argv.cwd);
    cwd = process.cwd();
  }

  /**
   * Log the working directory
   */

  console.log(utils.log.timestamp, 'using cwd ' + utils.formatDir(cwd));

  /**
   * Get the assemblefile.js to use
   */

  var assemblefile = path.resolve(cwd, argv.file || 'assemblefile.js');

  /**
   * Get the `assemble` instance to use
   */

  var defaults = require('../lib/generator');
  var configfile = utils.exists(assemblefile);
  if (configfile) {
    app = require(assemblefile);
  } else {
    app = defaults;
  }

  /**
   * If `app` is a function, it's an assemble "generator",
   * so we need to invoke it with an instance of assemble
   */

  if ((app && Object.keys(app).length === 0) || (typeof app === 'function' && app.initAssemble)) {
    var msg = util.format(errors['instance'], utils.homeRelative(assemblefile));
    cb(new Error(msg));
    return;
  } else if (typeof app === 'function') {
    var fn = app;
    app = assemble(argv);
    app.option(argv);
    app.use(fn);
  }

  assemble.initPlugins(app);

  /**
   * Listen for errors
   */

  app.on('error', handleError);
  app.on('build', function(event, build) {
    if (typeof event === 'string' && !build.isSilent) {
      app.log.time(event, build.key, app.log.magenta(build.time));
    }
  });
  app.on('task', function(event, task) {
    if (typeof event === 'string' && !task.isSilent) {
      app.log.time(event, task.key);
    }
  });

  /**
   * Support `--emit` for debugging
   *
   * Example:
   *   $ --emit data
   */

  if (argv.emit && typeof argv.emit === 'string') {
    app.on(argv.emit, app.log.bind(console));
  }

  /**
   * Process command line arguments
   */

  var tasks = argv._.length ? argv._ : ['default'];
  var args = app.argv(argv);
  args.tasks = tasks;

  app.set('cache.argv', args);
  app.option(args);

  /**
   * Show path to assemblefile
   */

  var fp = utils.homeRelative(assemblefile);
  app.log.path('using assemblefile ' + utils.colors.green('~/' + fp));

  /**
   * Registert `runtimes` plugin
   */

  app.use(plugins.runtimes());

  /**
   * Process command line arguments
   */

  cb(null, app);
}

/**
 * Run
 */

run(function(err, app) {
  if (err) handleError(err);
  commands(app);

  /**
   * Process command line arguments
   */

  app.cli.process(app.get('cache.argv'), function(err) {
    if (err) handleError(err);

    /**
     * Run tasks
     */

    var tasks = app.get('cache.argv.tasks');
    app.build(tasks, function(err) {
      if (err) handleError(err);
      app.log.success('finished');
    });
  });
});

/**
 * Handle CLI errors
 */

function handleError(err) {
  if (typeof err === 'string' && errors[err]) {
    console.error(errors[err]);
  } else {
    if (argv.verbose) {
      console.error(err.stack);
    } else {
      console.error(err.message);
    }
  }
  process.exit(1);
}
<commit_msg>revert cli change, only log assemblefile if it exists<commit_after>#!/usr/bin/env node

var util = require('util');
var path = require('path');
var assemble = require('..');
var commands = require('../lib/commands');
var plugins = require('../lib/plugins');
var utils = require('../lib/utils');
var errors = require('./errors');
var argv = utils.parseArgs(process.argv.slice(2));

function run(cb) {
  var cwd = process.cwd();
  var app;

  /**
   * Set the working directory
   */

  if (argv.cwd && cwd !== path.resolve(argv.cwd)) {
    process.ORIG_CWD = process.cwd();
    process.chdir(argv.cwd);
    cwd = process.cwd();
  }

  /**
   * Log the working directory
   */

  console.log(utils.log.timestamp, 'using cwd ' + utils.formatDir(cwd));

  /**
   * Get the assemblefile.js to use
   */

  var assemblefile = path.resolve(cwd, argv.file || 'assemblefile.js');

  /**
   * Get the `assemble` instance to use
   */

  var defaults = require('../lib/generator');
  var configfile = utils.exists(assemblefile);
  if (configfile) {
    app = require(assemblefile);
  } else {
    app = defaults;
  }

  /**
   * If `app` is a function, it's an assemble "generator",
   * so we need to invoke it with an instance of assemble
   */

  if (typeof app === 'function') {
    var fn = app;
    app = assemble(argv);
    app.option(argv);
    app.use(fn);
  } else if (Object.keys(app).length === 0) {
    var msg = util.format(errors['instance'], utils.homeRelative(assemblefile));
    cb(new Error(msg));
    return;
  }

  assemble.initPlugins(app);

  /**
   * Listen for errors
   */

  app.on('error', handleError);
  app.on('build', function(event, build) {
    if (typeof event === 'string' && !build.isSilent) {
      app.log.time(event, build.key, app.log.magenta(build.time));
    }
  });
  app.on('task', function(event, task) {
    if (typeof event === 'string' && !task.isSilent) {
      app.log.time(event, task.key);
    }
  });

  /**
   * Support `--emit` for debugging
   *
   * Example:
   *   $ --emit data
   */

  if (argv.emit && typeof argv.emit === 'string') {
    app.on(argv.emit, app.log.bind(console));
  }

  /**
   * Process command line arguments
   */

  var tasks = argv._.length ? argv._ : ['default'];
  var args = app.argv(argv);
  args.tasks = tasks;

  app.set('cache.argv', args);
  app.option(args);

  /**
   * Show path to assemblefile
   */

  if (configfile) {
    var fp = utils.homeRelative(assemblefile);
    app.log.path('using assemblefile ' + utils.colors.green('~/' + fp));
  }

  /**
   * Registert `runtimes` plugin
   */

  app.use(plugins.runtimes());

  /**
   * Process command line arguments
   */

  cb(null, app);
}

/**
 * Run
 */

run(function(err, app) {
  if (err) handleError(err);
  commands(app);

  /**
   * Process command line arguments
   */

  app.cli.process(app.get('cache.argv'), function(err) {
    if (err) handleError(err);

    /**
     * Run tasks
     */

    var tasks = app.get('cache.argv.tasks');
    app.build(tasks, function(err) {
      if (err) handleError(err);
      app.log.success('finished');
    });
  });
});

/**
 * Handle CLI errors
 */

function handleError(err) {
  if (typeof err === 'string' && errors[err]) {
    console.error(errors[err]);
  } else {
    if (argv.verbose) {
      console.error(err.stack);
    } else {
      console.error(err.message);
    }
  }
  process.exit(1);
}
<|endoftext|>


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

const fs = require("fs");
const path = require("path");
const { promisify } = require("util");

const mkdirp = require("mkdirp");

const mkdir = promisify(mkdirp);
const writeFile = promisify(fs.writeFile);
const readFile = promisify(fs.readFile);

const buildStats = require("../plugin/build-stats");
const TEMPLATE = require("../plugin/template-types");

const argv = require("yargs")
  .strict()
  .option("extra-style-path", {
    describe: "Extra override css file path",
    string: true
  })
  .option("filename", {
    describe: "Output file name",
    string: true,
    default: "./stats.html"
  })
  .option("title", {
    describe: "Output file title",
    string: true,
    default: "RollUp Visualizer"
  })
  .option("template", {
    describe: "Template type",
    string: true,
    choices: TEMPLATE,
    default: "treemap"
  })
  .help().argv;

const listOfFiles = argv._;

const run = async (title, template, extraStylePath, filename, files) => {
  if (files.length === 0) {
    throw new Error("Empty file list");
  }

  const fileContents = await Promise.all(
    files.map(async file => {
      const textContent = readFile(file, { encoding: "utf-8" });
      const jsonContent = JSON.parse(textContent);
      return [file, jsonContent];
    })
  );

  const tree = {
    name: "root",
    children: []
  };
  const nodes = Object.create(null);
  let links = [];

  for (const [, fileContent] of fileContents) {
    if (fileContent.tree.name === "root") {
      tree.children = tree.children.concat(fileContent.tree.children);
    } else {
      tree.children.push(fileContent.tree);
    }

    Object.assign(nodes, fileContent.nodes);

    links = links.concat(fileContent.links);
  }

  const data = { tree, links, nodes };

  const fileContent = await buildStats(
    title,
    data,
    template,
    extraStylePath,
    {}
  );

  await mkdir(path.dirname(filename));
  await writeFile(filename, fileContent);
};

run(
  argv.title,
  argv.template,
  argv.extraStylePath,
  argv.filename,
  listOfFiles
).catch(err => {
  console.error(err.message);
  process.exit(1);
});
<commit_msg>Add missing await<commit_after>#!/usr/bin/env node
"use strict";

const fs = require("fs");
const path = require("path");
const { promisify } = require("util");

const mkdirp = require("mkdirp");

const mkdir = promisify(mkdirp);
const writeFile = promisify(fs.writeFile);
const readFile = promisify(fs.readFile);

const buildStats = require("../plugin/build-stats");
const TEMPLATE = require("../plugin/template-types");

const argv = require("yargs")
  .strict()
  .option("extra-style-path", {
    describe: "Extra override css file path",
    string: true
  })
  .option("filename", {
    describe: "Output file name",
    string: true,
    default: "./stats.html"
  })
  .option("title", {
    describe: "Output file title",
    string: true,
    default: "RollUp Visualizer"
  })
  .option("template", {
    describe: "Template type",
    string: true,
    choices: TEMPLATE,
    default: "treemap"
  })
  .help().argv;

const listOfFiles = argv._;

const run = async (title, template, extraStylePath, filename, files) => {
  if (files.length === 0) {
    throw new Error("Empty file list");
  }

  const fileContents = await Promise.all(
    files.map(async file => {
      const textContent = await readFile(file, { encoding: "utf-8" });
      const jsonContent = JSON.parse(textContent);
      return [file, jsonContent];
    })
  );

  const tree = {
    name: "root",
    children: []
  };
  const nodes = Object.create(null);
  let links = [];

  for (const [, fileContent] of fileContents) {
    if (fileContent.tree.name === "root") {
      tree.children = tree.children.concat(fileContent.tree.children);
    } else {
      tree.children.push(fileContent.tree);
    }

    Object.assign(nodes, fileContent.nodes);

    links = links.concat(fileContent.links);
  }

  const data = { tree, links, nodes };

  const fileContent = await buildStats(
    title,
    data,
    template,
    extraStylePath,
    {}
  );

  await mkdir(path.dirname(filename));
  await writeFile(filename, fileContent);
};

run(
  argv.title,
  argv.template,
  argv.extraStylePath,
  argv.filename,
  listOfFiles
).catch(err => {
  console.error(err.message);
  process.exit(1);
});
<|endoftext|>


<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    <commit_msg>Not quite working<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    c<|endoftext|>


<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
<commit_msg>Not quite working<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
 <|endoftext|>


<commit_before>#!/usr/bin/env node
"use strict";
var usage = require("../");
var path = require("path");

process.argv.splice(0, 2);
var file = process.argv.shift();
var cliOptions = require(path.resolve(file));

console.log(usage(cliOptions, {
    viewWidth: process.stdout.columns
}));
<commit_msg>rewritten cli<commit_after>#!/usr/bin/env node
"use strict";
var usage = require("../");
var os = require("os");
var fs = require("fs");
var path = require("path");
var ansi = require("ansi-escape-sequences");

var tmpPath = path.join(os.tmpDir(), Date.now() + "-clu.js");

process.stdin
    .pipe(fs.createWriteStream(tmpPath))
    .on("close", getUsage);

function getUsage(){
    var cliOptions = require(tmpPath);
    fs.unlinkSync(tmpPath);
    console.log(usage(cliOptions));
}

function halt(msg){
    console.error(ansi.format(msg, "red"));
    process.exit(1);
}
<|endoftext|>


<commit_before>#!/usr/bin/env node
var argv = require('optimist').argv;
var fs = require('fs');
var path = require('path');
var mkdirp = require('mkdirp');
var dataDir = path.resolve(process.env.HOME || process.env.USERPROFILE, '.config/stream-adventure');
mkdirp.sync(dataDir);

var showMenu = require('./menu.js');
var verify = require('./verify.js');
var order = require('../data/order.json');

if (argv.h || argv.help || argv._[0] === 'help') {
    return fs.createReadStream(__dirname + '/usage.txt').pipe(process.stdout);
}

if (argv._[0] === 'list') {
    order.forEach(function (name) {
        console.log(name);
    });
    return;
}

if (argv._[0] === 'current') {
    var current = getData('current');
    console.log(current);
    return;
}

if (argv._[0] === 'select') {
    return onselect(argv._.slice(1).join(' '));
}

if (argv._[0] === 'verify' || argv._[0] === 'run') {
    var current = getData('current');
    if (!current) {
        console.error('ERROR: No active problem. '
            + 'Select a challenge from the menu.'
        );
        return process.exit(1);
    }
    var dir = dirFromName(current);
    var setup = require(dir + '/setup.js')({ run: argv._[0] === 'run' });
    setTimeout(function () {
        var a = argv._.slice(1)
            .concat(setup.aArgs || setup.args || [])
        ;
        var b = [ dir + '/solution.js' ]
            .concat(setup.bArgs || setup.args || [])
        ;
        var v = verify(a, b, {
            a: setup.a,
            b: setup.b,
            showStdout: setup.showStdout,
            long: setup.long,
            run: argv._[0] === 'run'
        });
        v.on('pass', onpass);
        v.on('fail', onfail);

        if (setup.stdin) {
            setup.stdin.pipe(v);
            setup.stdin.resume();
        }

        if (setup.a) setup.a.resume();
        if (setup.b) setup.b.resume();
    }, setup.wait || 1);

    function onpass () {
        console.log('# PASS');
        console.log('\nYour solution to ' + current + ' passed!');
        console.log(
            '\nHere\'s what the official solution'
            + ' is if you want to compare notes:\n'
        );
        var src = fs.readFileSync(path.join(dir, 'solution.js'), 'utf8');
        src.split('\n').forEach(function (line) {
            console.log('    ' + line);
        });

        updateData('completed', function (xs) {
            if (!xs) xs = [];
            var ix = xs.indexOf(current);
            return ix >= 0 ? xs : xs.concat(current);
        });

        var completed = getData('completed') || [];

        var remaining = order.length - completed.length;
        if (remaining === 0) {
            console.log("You've finished all the challenges! Hooray!\n");
        }
        else {
            console.log('You have ' + remaining + ' challenges left.');
            console.log('Type `stream-adventure` to show the menu.\n');
        }

        if (setup.close) setup.close();
    }

    function onfail () {
        if (setup.close) setup.close();

        console.log('# FAIL');
        console.log(
            "\nYour solution didn't match the expected output."
            + ' Try again!'
        );
    }
}
else {
  var opts = {
    completed: getData('completed') || []
  };

  if (argv.b || argv.bg){
    opts.bg = argv.b || argv.bg;
  }

  if (argv.f || argv.fg){
    opts.fg = argv.f || argv.fg;
  }

  var menu = showMenu(opts);

  menu.on('select', onselect);
  menu.on('exit', function () {
      console.log();
      process.exit(0);
  });
}

function onselect (name) {
    console.log('\n  ' + Array(70).join('#'));
    console.log(center('~~  ' + name + '  ~~'));
    console.log('  ' + Array(70).join('#') + '\n');

    var dir = dirFromName(name);
    var file = path.resolve(dir, 'problem.txt');
    updateData('current', function (c) { return name });
    var rs = fs.createReadStream(file);
    rs.on('close', function () {
        console.log(
            '\nTo verify your program, run: '
            + '`stream-adventure verify program.js`.\n'
        );
    });
    rs.pipe(process.stdout);
}

function updateData (name, fn) {
    var json = {};
    try { json = getData(name) }
    catch (e) {}
    var file = path.resolve(dataDir, name + '.json');
    fs.writeFileSync(file, JSON.stringify(fn(json)));
}

function getData (name) {
    var file = path.resolve(dataDir, name + '.json');
    try { return JSON.parse(fs.readFileSync(file, 'utf8')) }
    catch (e) {}
    return null;
}

function dirFromName (name) {
    return path.resolve(__dirname, '../problems/'
        + name.toLowerCase().replace(/\s/g, '_')
    );
}

function center (s) {
    var n = (67 - s.length) / 2;
    return '  ##' + Array(Math.floor(n)).join(' ')
        + s + Array(Math.ceil(n)).join(' ') + '##'
    ;
}
<commit_msg>Added some advice to failed verify output for debugging help.<commit_after>#!/usr/bin/env node
var argv = require('optimist').argv;
var fs = require('fs');
var path = require('path');
var mkdirp = require('mkdirp');
var dataDir = path.resolve(process.env.HOME || process.env.USERPROFILE, '.config/stream-adventure');
mkdirp.sync(dataDir);

var showMenu = require('./menu.js');
var verify = require('./verify.js');
var order = require('../data/order.json');

if (argv.h || argv.help || argv._[0] === 'help') {
    return fs.createReadStream(__dirname + '/usage.txt').pipe(process.stdout);
}

if (argv._[0] === 'list') {
    order.forEach(function (name) {
        console.log(name);
    });
    return;
}

if (argv._[0] === 'current') {
    var current = getData('current');
    console.log(current);
    return;
}

if (argv._[0] === 'select') {
    return onselect(argv._.slice(1).join(' '));
}

if (argv._[0] === 'verify' || argv._[0] === 'run') {
    var current = getData('current');
    if (!current) {
        console.error('ERROR: No active problem. '
            + 'Select a challenge from the menu.'
        );
        return process.exit(1);
    }
    var dir = dirFromName(current);
    var setup = require(dir + '/setup.js')({ run: argv._[0] === 'run' });
    setTimeout(function () {
        var a = argv._.slice(1)
            .concat(setup.aArgs || setup.args || [])
        ;
        var b = [ dir + '/solution.js' ]
            .concat(setup.bArgs || setup.args || [])
        ;
        var v = verify(a, b, {
            a: setup.a,
            b: setup.b,
            showStdout: setup.showStdout,
            long: setup.long,
            run: argv._[0] === 'run'
        });
        v.on('pass', onpass);
        v.on('fail', onfail);

        if (setup.stdin) {
            setup.stdin.pipe(v);
            setup.stdin.resume();
        }

        if (setup.a) setup.a.resume();
        if (setup.b) setup.b.resume();
    }, setup.wait || 1);

    function onpass () {
        console.log('# PASS');
        console.log('\nYour solution to ' + current + ' passed!');
        console.log(
            '\nHere\'s what the official solution'
            + ' is if you want to compare notes:\n'
        );
        var src = fs.readFileSync(path.join(dir, 'solution.js'), 'utf8');
        src.split('\n').forEach(function (line) {
            console.log('    ' + line);
        });

        updateData('completed', function (xs) {
            if (!xs) xs = [];
            var ix = xs.indexOf(current);
            return ix >= 0 ? xs : xs.concat(current);
        });

        var completed = getData('completed') || [];

        var remaining = order.length - completed.length;
        if (remaining === 0) {
            console.log("You've finished all the challenges! Hooray!\n");
        }
        else {
            console.log('You have ' + remaining + ' challenges left.');
            console.log('Type `stream-adventure` to show the menu.\n');
        }

        if (setup.close) setup.close();
    }

    function onfail () {
        if (setup.close) setup.close();

        console.log('# FAIL');
        console.log(
            "\nYour solution didn't match the expected output."
            + ' Try again, or run `stream-adventure run program.js` to see your solution\'s output.'
        );
    }
}
else {
  var opts = {
    completed: getData('completed') || []
  };

  if (argv.b || argv.bg){
    opts.bg = argv.b || argv.bg;
  }

  if (argv.f || argv.fg){
    opts.fg = argv.f || argv.fg;
  }

  var menu = showMenu(opts);

  menu.on('select', onselect);
  menu.on('exit', function () {
      console.log();
      process.exit(0);
  });
}

function onselect (name) {
    console.log('\n  ' + Array(70).join('#'));
    console.log(center('~~  ' + name + '  ~~'));
    console.log('  ' + Array(70).join('#') + '\n');

    var dir = dirFromName(name);
    var file = path.resolve(dir, 'problem.txt');
    updateData('current', function (c) { return name });
    var rs = fs.createReadStream(file);
    rs.on('close', function () {
        console.log(
            '\nTo verify your program, run: '
            + '`stream-adventure verify program.js`.\n'
        );
    });
    rs.pipe(process.stdout);
}

function updateData (name, fn) {
    var json = {};
    try { json = getData(name) }
    catch (e) {}
    var file = path.resolve(dataDir, name + '.json');
    fs.writeFileSync(file, JSON.stringify(fn(json)));
}

function getData (name) {
    var file = path.resolve(dataDir, name + '.json');
    try { return JSON.parse(fs.readFileSync(file, 'utf8')) }
    catch (e) {}
    return null;
}

function dirFromName (name) {
    return path.resolve(__dirname, '../problems/'
        + name.toLowerCase().replace(/\s/g, '_')
    );
}

function center (s) {
    var n = (67 - s.length) / 2;
    return '  ##' + Array(Math.floor(n)).join(' ')
        + s + Array(Math.ceil(n)).join(' ') + '##'
    ;
}
<|endoftext|>


<commit_before>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
//Added a comment that achieves no real goal.

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter<commit_msg>Fixing an important issue with the universe.<commit_after>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
//Added a comment that achieves no real goal.

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter <|endoftext|>


<commit_before>'use strict';

const Sequelize = require('sequelize');
const pluralize = Sequelize.Utils.pluralize;
const dasherize = require('dasherize');
const parser = require('body-parser');
const express = require('express');

const methods = {
	GET: 'GET',
	PUT: 'PUT',
	POST: 'POST',
	PATCH: 'PATCH',
	DELETE: 'DELETE'
};

const errors = {
	notFound: new Error(`record not found`),
	invalidModel: new TypeError(`'model' must be a valid Sequelize model`)
};

let handleRequestError = (req, res) => {
	return (e) => {
		switch (e.name) {
		case 'SequelizeForeignKeyConstraintError':
			return res.status(400).json({ errors: [{ message: 'foreign key constraint error' }]});
		case 'SequelizeValidationError':
		case 'SequelizeUniqueConstraintError':

			var results = [];
			e.errors.forEach((x) => {
				results.push({
					message: x.message,
					field: x.path
				});
			});

			return res.status(422).json({ errors: results });
		case 'SequelizeDatabaseError':
			return res.status(422).json({ errors: [{ message: e.message }] });
		}

		switch (e) {
		case errors.notFound:
			return res.status(404).json({ errors: [{ message: e.message }] });
		}

		return res.status(500).json({ errors: [{ message: e.message }] });
	};
};

let buildWhere = (method, req, options) => {
	let query = {
		where: {},
		include: options.relationships,
		limit: undefined,
		offset: undefined
	};

	if (req.params.id) {
		query.where.id = req.params.id;
	}

	if (method === methods.POST) {
		query.returning = true;
	}

	if (method === methods.DELETE) {
		query.limit = 1;
	}

	if (method === methods.GET) {
		if (req.query.limit) {
			query.limit = req.query.limit;
		} else if (options.limit) {
			query.limit = options.limit;
		}

		if (req.query.offset) {
			query.offset = req.query.offset;
		}

		if (req.query.filter) {
			Object.keys(req.query.filter).forEach((field) => {
				query.where[field] = req.query.filter[field];
			});
		}

		if (req.query.search) {
			Object.keys(req.query.search).forEach((field) => {
				if (options.useLike === true) {
					query.where[field] = {
						$like: `%${req.query.search[field]}%`
					};
				} else {
					query.where[field] = {
						$iLike: `%${req.query.search[field]}%`
					};
				}
			});
		}

		if (req.query.attributes) {
			try {
				req.query.attributes = req.query.attributes.split(',');
			} catch (e) {
				// Should we error here?
			}

			query.attributes = req.query.attributes;
		}
	}

	if (options.hooks && typeof options.hooks.beforeQuery === 'function') {
		options.hooks.beforeQuery(query, req);
	}

	return query;
};

let formatOutput = (results, model, options) => {
	let response = {};
	let plural = Array.isArray(results);

	if (options.disableNestedData === true) {
		return results;
	} else if (options.overrideOutputName) {
		if (plural) {
			response[pluralize(options.overrideOutputName)] = results;
		} else {
			response[options.overrideOutputName] = results;
		}
	} else {
		if (plural) {
			response[pluralize(model.name)] = results;
		} else {
			response[model.name] = results;
		}
	}
	return response;
};

let createController = (model, options) => {

	if (!(model instanceof Sequelize.Model)) {
		throw errors.invalidModel;
	}

	const router = express.Router();

	options = Object.assign({
		allowChangingPrimaryKey: false,
		includeRelationsInGetAll: false,
		disableBodyParser: false,
		overrideOutputName: null,
		limit: undefined,
		restrictedFields: [],
		relationships: [],
		handlers: {
			get: true,
			put: true,
			post: true,
			delete: true
		},
		middleware: {
			pre: [],
			post: []
		},
		useLike: true
	}, options);

	if (options.disableBodyParser !== true) {
		router.use(parser.json());
	}

	// Override for `$iLike` in Postgres
	try {
		if (model.sequelize.dialect.name === 'postgres') {
			options.useLike = false;
		}
	} catch (e) {
		// Nothing to do here
	}

	if (options.middleware && Array.isArray(options.middleware)) {
		options.middleware.forEach((middleware) => {
			router.use(middleware);
		});
	}

	if (options.handlers.get === true) {
		router.get('/', (req, res) => {

			let query = buildWhere(methods.GET, req, options);

			// By default we will not look up relations on the root endpoint as
			// this can become very slow with a lot of records
			if (options.includeRelationsInGetAll !== true) {
				delete query.include;
			}

			model.findAll(query).then((results) => {
				return res.status(200).json(formatOutput(results, model, options));
			}).catch((e) => {
				return res.status(500).json({ errors: [{ message: e.message }] });
			});
		});

		router.get('/:id', (req, res) => {
			model.findOne(buildWhere(methods.GET, req, options)).then((results) => {
				if (!results) {
					throw errors.notFound;
				}

				return res.status(200).json(formatOutput(results, model, options));
			}).catch(handleRequestError(req, res));
		});
	}

	if (options.handlers.post === true) {
		router.post('/', (req, res) => {

			let input = (options.disableNestedData === true ? req.body : req.body[model.name]);

			model.create(input, buildWhere(methods.POST, req, options)).then((results) => {

				if (options.hooks && typeof options.hooks.afterCreate === 'function') {
					options.hooks.afterCreate(model, results);
				}

				return res.status(200).json(formatOutput(results, model, options));
			}).catch(handleRequestError(req, res));
		});
	}

	if (options.handlers.put === true) {
		router.put('/:id', (req, res) => {

			// Prevent a consumer from changing the primary key of a given record
			if (options.allowChangingPrimaryKey !== true
				&& model.primaryKeyField
				&& typeof req.body[model.name][model.primaryKeyField] !== 'undefined') {

				if (req.params.id != req.body[model.name][model.primaryKeyField]) {
					return res.status(422).json({
						errors: [{
							message: 'cannot change record primary key',
							field: model.primaryKeyField
						}]
					});
				}
			}

			model.findOne(buildWhere(methods.PUT, req, options)).then((result) => {
				if (!result) {
					throw errors.notFound;
				}

				let input = (options.disableNestedData === true ? req.body : req.body[model.name]);

				Object.keys(input).forEach((field) => {
					result.set(field, input[field]);
				});

				if (options.hooks && typeof options.hooks.beforeUpdate === 'function') {
					options.hooks.beforeUpdate(model, result);
				}

				return result.save();
			}).then((results) => {

				if (options.hooks && typeof options.hooks.afterUpdate === 'function') {
					options.hooks.afterUpdate(model, results);
				}

				return res.status(200).json(formatOutput(results, model, options));
			}).catch(handleRequestError(req, res));
		});
	}

	if (options.handlers.delete === true) {
		router.delete('/:id', (req, res) => {
			model.destroy(buildWhere(methods.DELETE, req, options)).then((affected) => {
				if (affected !== 1) {
					throw errors.notFound;
				}

				return res.status(200).json({ status: 'ok' });
			}).catch(handleRequestError(req, res));
		});
	}

	return router;
};

let createRouter = (controllerOptions, routerOptions) => {

	if (!Array.isArray(controllerOptions)) {
		throw new TypeError(`'controllerOptions' must be an array`);
	}

	const router = express.Router();

	if (routerOptions) {
		// Append middleware to the start if we have any top-level included
		if (Array.isArray(routerOptions.middleware)) {
			router.use(routerOptions.middleware);
		}
	}

	// Iterate over provided option sets which should be exactly the same as
	// those that are provided for `createController`
	controllerOptions.forEach((controller) => {

		let model;
		let options = {
			handlers: {
				get: true,
				put: true,
				post: true,
				delete: true
			}
		};

		// If router options were provided we will run through them
		// and override any default controller options
		if (routerOptions) {
			Object.keys(routerOptions).forEach((option) => {
				if (option === 'middleware') {
					// Middleware should remain where they are rather than overwriting
					// any that may have been set on the specific controller
					return;
				} else if (option === 'handlers') {
					Object.assign(options[option], routerOptions[option]);
				} else {
					options[option] = routerOptions[option];
				}
			});
		}

		if (controller instanceof Sequelize.Model) {
			model = controller;
		} else if (controller.model instanceof Sequelize.Model) {
			model = controller.model;
			options = Object.assign(options, controller.options);
		} else {
			throw errors.invalidModel;
		}

		router.use(`/${dasherize(model.options.name.plural)}`, createController(model, options));
	});

	return router;
};

module.exports = {
	createController,
	createRouter
};
<commit_msg>main: small refactor<commit_after>'use strict';

const Sequelize = require('sequelize');
const pluralize = Sequelize.Utils.pluralize;
const dasherize = require('dasherize');
const parser = require('body-parser');
const express = require('express');

const methods = {
	GET: 'GET',
	PUT: 'PUT',
	POST: 'POST',
	PATCH: 'PATCH',
	DELETE: 'DELETE'
};

const errors = {
	notFound: new Error(`record not found`),
	invalidModel: new TypeError(`'model' must be a valid Sequelize model`)
};

let handleRequestError = (req, res) => {
	return (e) => {
		switch (e.name) {
		case 'SequelizeForeignKeyConstraintError':
			return res.status(400).json({ errors: [{ message: 'foreign key constraint error' }]});
		case 'SequelizeValidationError':
		case 'SequelizeUniqueConstraintError':

			var results = [];
			e.errors.forEach((x) => {
				results.push({
					message: x.message,
					field: x.path
				});
			});

			return res.status(422).json({ errors: results });
		case 'SequelizeDatabaseError':
			return res.status(422).json({ errors: [{ message: e.message }] });
		}

		switch (e) {
		case errors.notFound:
			return res.status(404).json({ errors: [{ message: e.message }] });
		}

		return res.status(500).json({ errors: [{ message: e.message }] });
	};
};

let buildWhere = (method, req, options) => {
	let query = {
		where: {},
		include: options.relationships,
		limit: undefined,
		offset: undefined
	};

	if (req.params.id) {
		query.where.id = req.params.id;
	}

	if (method === methods.POST) {
		query.returning = true;
	}

	if (method === methods.DELETE) {
		query.limit = 1;
	}

	if (method === methods.GET) {
		if (req.query.limit) {
			query.limit = req.query.limit;
		} else if (options.limit) {
			query.limit = options.limit;
		}

		if (req.query.offset) {
			query.offset = req.query.offset;
		}

		if (req.query.filter) {
			Object.keys(req.query.filter).forEach((field) => {
				query.where[field] = req.query.filter[field];
			});
		}

		if (req.query.search) {
			Object.keys(req.query.search).forEach((field) => {

				let like = `%${req.query.search[field]}%`;

				if (options.useLike === true) {
					query.where[field] = {
						$like: like
					};
				} else {
					query.where[field] = {
						$iLike: like
					};
				}
			});
		}

		if (req.query.attributes) {
			try {
				req.query.attributes = req.query.attributes.split(',');
			} catch (e) {
				// Should we error here?
			}

			query.attributes = req.query.attributes;
		}
	}

	if (options.hooks && typeof options.hooks.beforeQuery === 'function') {
		options.hooks.beforeQuery(query, req);
	}

	return query;
};

let formatOutput = (results, model, options) => {
	let response = {};
	let plural = Array.isArray(results);

	if (options.disableNestedData === true) {
		return results;
	}

	let outputName;

	if (options.overrideOutputName) {
		outputName = options.overrideOutputName;
	} else {
		outputName = model.name;
	}

	if (plural) {
		outputName = pluralize(outputName);
	}

	response[outputName] = results;

	return response;
};

let createController = (model, options) => {

	if (!(model instanceof Sequelize.Model)) {
		throw errors.invalidModel;
	}

	const router = express.Router();

	options = Object.assign({
		allowChangingPrimaryKey: false,
		includeRelationsInGetAll: false,
		disableBodyParser: false,
		overrideOutputName: null,
		limit: undefined,
		restrictedFields: [],
		relationships: [],
		handlers: {
			get: true,
			put: true,
			post: true,
			delete: true
		},
		middleware: {
			pre: [],
			post: []
		},
		useLike: true
	}, options);

	if (options.disableBodyParser !== true) {
		router.use(parser.json());
	}

	// Override for `$iLike` in Postgres
	try {
		if (model.sequelize.dialect.name === 'postgres') {
			options.useLike = false;
		}
	} catch (e) {
		// Nothing to do here
	}

	if (options.middleware && Array.isArray(options.middleware)) {
		options.middleware.forEach((middleware) => {
			router.use(middleware);
		});
	}

	if (options.handlers.get === true) {
		router.get('/', (req, res) => {

			let query = buildWhere(methods.GET, req, options);

			// By default we will not look up relations on the root endpoint as
			// this can become very slow with a lot of records
			if (options.includeRelationsInGetAll !== true) {
				delete query.include;
			}

			model.findAll(query).then((results) => {
				return res.status(200).json(formatOutput(results, model, options));
			}).catch((e) => {
				return res.status(500).json({ errors: [{ message: e.message }] });
			});
		});

		router.get('/:id', (req, res) => {
			model.findOne(buildWhere(methods.GET, req, options)).then((results) => {
				if (!results) {
					throw errors.notFound;
				}

				return res.status(200).json(formatOutput(results, model, options));
			}).catch(handleRequestError(req, res));
		});
	}

	if (options.handlers.post === true) {
		router.post('/', (req, res) => {

			let input = (options.disableNestedData === true ? req.body : req.body[model.name]);

			model.create(input, buildWhere(methods.POST, req, options)).then((results) => {

				if (options.hooks && typeof options.hooks.afterCreate === 'function') {
					options.hooks.afterCreate(model, results);
				}

				return res.status(200).json(formatOutput(results, model, options));
			}).catch(handleRequestError(req, res));
		});
	}

	if (options.handlers.put === true) {
		router.put('/:id', (req, res) => {

			// Prevent a consumer from changing the primary key of a given record
			if (options.allowChangingPrimaryKey !== true
				&& model.primaryKeyField
				&& typeof req.body[model.name][model.primaryKeyField] !== 'undefined') {

				if (req.params.id != req.body[model.name][model.primaryKeyField]) {
					return res.status(422).json({
						errors: [{
							message: 'cannot change record primary key',
							field: model.primaryKeyField
						}]
					});
				}
			}

			model.findOne(buildWhere(methods.PUT, req, options)).then((result) => {
				if (!result) {
					throw errors.notFound;
				}

				let input = (options.disableNestedData === true ? req.body : req.body[model.name]);

				Object.keys(input).forEach((field) => {
					result.set(field, input[field]);
				});

				if (options.hooks && typeof options.hooks.beforeUpdate === 'function') {
					options.hooks.beforeUpdate(model, result);
				}

				return result.save();
			}).then((results) => {

				if (options.hooks && typeof options.hooks.afterUpdate === 'function') {
					options.hooks.afterUpdate(model, results);
				}

				return res.status(200).json(formatOutput(results, model, options));
			}).catch(handleRequestError(req, res));
		});
	}

	if (options.handlers.delete === true) {
		router.delete('/:id', (req, res) => {
			model.destroy(buildWhere(methods.DELETE, req, options)).then((affected) => {
				if (affected !== 1) {
					throw errors.notFound;
				}

				return res.status(200).json({ status: 'ok' });
			}).catch(handleRequestError(req, res));
		});
	}

	return router;
};

let createRouter = (controllerOptions, routerOptions) => {

	if (!Array.isArray(controllerOptions)) {
		throw new TypeError(`'controllerOptions' must be an array`);
	}

	const router = express.Router();

	if (routerOptions) {
		// Append middleware to the start if we have any top-level included
		if (Array.isArray(routerOptions.middleware)) {
			router.use(routerOptions.middleware);
		}
	}

	// Iterate over provided option sets which should be exactly the same as
	// those that are provided for `createController`
	controllerOptions.forEach((controller) => {

		let model;
		let options = {
			handlers: {
				get: true,
				put: true,
				post: true,
				delete: true
			}
		};

		// If router options were provided we will run through them
		// and override any default controller options
		if (routerOptions) {
			Object.keys(routerOptions).forEach((option) => {
				if (option === 'middleware') {
					// Middleware should remain where they are rather than overwriting
					// any that may have been set on the specific controller
					return;
				} else if (option === 'handlers') {
					Object.assign(options[option], routerOptions[option]);
				} else {
					options[option] = routerOptions[option];
				}
			});
		}

		if (controller instanceof Sequelize.Model) {
			model = controller;
		} else if (controller.model instanceof Sequelize.Model) {
			model = controller.model;
			options = Object.assign(options, controller.options);
		} else {
			throw errors.invalidModel;
		}

		router.use(`/${dasherize(model.options.name.plural)}`, createController(model, options));
	});

	return router;
};

module.exports = {
	createController,
	createRouter
};
<|endoftext|>


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

'use strict';

/**
 * Register your service by using one of the following commands.
 *
 *     dds configure --accessKeyId :key --secretAccessKey :secret --region eu-west-1
 *     dds set mongo --host 10.9.128.3 --port 4444 --version 1.2
 *     dds set mongo@1.2 10.9.128.3:4444
 *
 * The default port is 80 and the default version is 1.0
 *
 * @author Sam Verschueren      <sam.verschueren@gmail.com>
 * @since  3 Jul. 2015
 */

// module dependencies
var AWS = require('aws-sdk'),
    fs = require('fs'),
    path = require('path'),
    os = require('os'),
    minimist = require('minimist'),
    pwuid = require('pwuid');

// Parse the arguments
var argv = minimist(process.argv.slice(2), {
    string: ['host', 'version', 'accessKeyId', 'secretAccessKey', 'region'],
    default: {
        port: 80,
        version: '1.0',
        region: 'us-west-1'
    }
});

// Run the task
runTask(argv._[0]);

function runTask(task) {
    if(task === undefined) {
        throw new Error('Please provide a task.');
    }

    if(task === 'configure') {
        var credentials = [],
            config = [];

        // Set the credentials
        credentials.push('[default]');
        credentials.push('aws_access_key_id=' + argv.accessKeyId);
        credentials.push('aws_secret_access_key=' + argv.secretAccessKey);

        // Set the config
        config.push('[default]');
        config.push('region=' + argv.region);
        config.push('output=json');

        fs.writeFileSync(path.join(pwuid().dir, '/.aws/credentials'), credentials.join(os.EOL));
        fs.writeFileSync(path.join(pwuid().dir, '/.aws/config'), config.join(os.EOL));
    }
    else {
        // TODO read region from ~/.aws/config file because they are not read upon initialization

        var dynamo = new AWS.DynamoDB();

        if(task === 'set') {
            var key = argv._[1],
                host = argv.host,
                port = argv.port,
                version = argv.version.split('.');

            console.log(key + '@' + version.join('.') + '=' + host + ':' + port);
        }
    }
};<commit_msg>Setting the correct profile in the credentials file<commit_after>#!/usr/bin/env node

'use strict';

/**
 * Register your service by using one of the following commands.
 *
 *     dds configure --accessKeyId :key --secretAccessKey :secret --region eu-west-1
 *     dds set mongo --host 10.9.128.3 --port 4444 --version 1.2
 *     dds set mongo@1.2 10.9.128.3:4444
 *
 * The default port is 80 and the default version is 1.0
 *
 * @author Sam Verschueren      <sam.verschueren@gmail.com>
 * @since  3 Jul. 2015
 */

// Set the AWS profile to load the correct config
process.env.AWS_PROFILE='dds';

// module dependencies
var AWS = require('aws-sdk'),
    fs = require('fs'),
    path = require('path'),
    os = require('os'),
    minimist = require('minimist'),
    pwuid = require('pwuid');

// Parse the arguments
var argv = minimist(process.argv.slice(2), {
    string: ['host', 'version', 'accessKeyId', 'secretAccessKey', 'region'],
    default: {
        port: 80,
        version: '1.0',
        region: 'us-west-1'
    }
});

// Run the task
runTask(argv._[0]);

function runTask(task) {
    if(task === undefined) {
        throw new Error('Please provide a task.');
    }

    if(task === 'configure') {
        var credentials = [],
            config = [];

        // Set the credentials
        credentials.push('[' + process.env.AWS_PROFILE + ']');
        credentials.push('aws_access_key_id=' + argv.accessKeyId);
        credentials.push('aws_secret_access_key=' + argv.secretAccessKey);

        // Set the config
        config.push('[' + process.env.AWS_PROFILE + ']');
        config.push('region=' + argv.region);
        config.push('output=json');

        fs.writeFileSync(path.join(pwuid().dir, '/.aws/credentials'), credentials.join(os.EOL));
        fs.writeFileSync(path.join(pwuid().dir, '/.aws/config'), config.join(os.EOL));
    }
    else {
        // TODO read region from ~/.aws/config file because they are not read upon initialization

        var dynamo = new AWS.DynamoDB();

        console.log(dynamo);

        if(task === 'set') {
            var key = argv._[1],
                host = argv.host,
                port = argv.port,
                version = argv.version.split('.');

            console.log(key + '@' + version.join('.') + '=' + host + ':' + port);
        }
    }
};<|endoftext|>


<commit_before>var request = require('request-promise'),
    cheerio = require('cheerio'),
    targets = require('./scrapeTargets.json');

var MAX_LENGTH = 256,
    DEFAULT_TAG = 'meta',
    DEFAULT_ATTR = 'content';

// Post-processing helper functions
var clean = function(string) {
  if (string.length <= MAX_LENGTH) return string;
  return string.substring(0, MAX_LENGTH - 3) + '...';
};

var nameFromUrl = function(url) {
  if (!url) return url;

  var wwwIndex = url.indexOf('www.');
  var name;

  if (url.indexOf('/') === -1 && wwwIndex === -1) return url;

  var wwwIndex = url.indexOf('www.');
  var name;

  if (wwwIndex !== -1) name = url.substring(wwwIndex + 4);
  else name = url.substring(url.indexOf('//') + 2);

  name = name.substring(0, name.indexOf('/'));

  return name;
};

var appendRef = function(full, partial) {
  var append;

  // Just appends http: or https:
  if (partial.substring(0, 2) === '//') {
    append = full.substring( 0, full.indexOf('//') );
    return append + partial;
  }

  // Appends everything up to the end of the domain
  append = full.substring( 0, full.indexOf('/', 7) );
  return append + partial;
};

// Scrapes a property based on an array of possible target tags
var scrapeProperty = function($, targets) {
  var tag, prop, val, attr, scrape;

  for (var i = 0; i < targets.length; i++) {
    var target = targets[i];

    tag = target.tag || DEFAULT_TAG;
    prop = target.prop ? '[' + target.prop + '=' : '';
    val = target.val ?  '"' + target.val + '"]' : '';
    attr = target.attr || DEFAULT_ATTR;

    if (target.text) scrape = clean( $(tag + prop + val).text() );
    else scrape = $(tag + prop + val).attr(attr);

    if (scrape) return scrape;
  }
};

module.exports = function (url) {
  return request(url)
  .then(function (html) {
    var $ = cheerio.load(html);
    var scrapes = {};

    // Attempt to scrape every property in scrapeTargets.json
    for (var key in targets) {
      scrapes[key] = scrapeProperty($, targets[key]);
    }

    // Perform some post-processing on particular properties
    scrapes.siteName = nameFromUrl(scrapes.siteName);
    scrapes.imageUrl = appendRef(url, scrapes.imageUrl);
    scrapes.siteIcon = appendRef(url, scrapes.siteIcon);

    return scrapes;
  });
};<commit_msg>(feat) Implement cleaner helper to prettify messy scraped text<commit_after>var request = require('request-promise'),
    cheerio = require('cheerio'),
    targets = require('./scrapeTargets.json');

// Settings which will control how some functins operate
var MAX_LENGTH = 256,
    DEFAULT_TAG = 'meta',
    DEFAULT_ATTR = 'content';

var PUNC = {
  '.': true,
  '!': true,
  '?': true,
  ',': true,
  ';': true,
  ':': true
};

// Post-processing helper functions
var clean = function(string) {
  if (!string) return string;

  var cleanWhitespace = function (char) {
    if (char.charCodeAt(0) < 32) return ' ';
    return char;
  };

  var addSpace = function (char, nextChar) {
    if (nextChar === undefined) return char;
    if (PUNC[char] && !PUNC[nextChar] && nextChar !== ' ') return char + ' ';
    return char;
  };

  var truncate = function (string) {
    if (string.length <= MAX_LENGTH) return string;
    return string.substring(0, MAX_LENGTH - 3) + '...';
  };

  var cleaned = '';

  for (var i = 0; i < string.length; i++) {
    var char = string[i];
    char = cleanWhitespace(char);
    char = addSpace(char, string[i+1]);
    cleaned += char;
  }

  return truncate(cleaned);
};

var nameFromUrl = function(url) {
  if (!url) return url;

  var wwwIndex = url.indexOf('www.');
  var name;

  if (url.indexOf('/') === -1 && wwwIndex === -1) return url;

  var wwwIndex = url.indexOf('www.');
  var name;

  if (wwwIndex !== -1) name = url.substring(wwwIndex + 4);
  else name = url.substring(url.indexOf('//') + 2);

  name = name.substring(0, name.indexOf('/'));

  return name;
};

var appendRef = function(full, partial) {
  if (!partial) return partial;

  var append;

  // Just appends http: or https:
  if (partial.substring(0, 2) === '//') {
    append = full.substring( 0, full.indexOf('//') );
    return append + partial;
  }

  // Appends everything up to the end of the domain
  append = full.substring( 0, full.indexOf('/', 7) );
  return append + partial;
};

// Scrapes a property based on an array of possible target tags
var scrapeProperty = function($, targets) {
  var tag, prop, val, attr, scrape;

  for (var i = 0; i < targets.length; i++) {
    var target = targets[i];

    tag = target.tag || DEFAULT_TAG;
    prop = target.prop ? '[' + target.prop + '=' : '';
    val = target.val ?  '"' + target.val + '"]' : '';
    attr = target.attr || DEFAULT_ATTR;

    if (target.text) scrape = clean( $(tag + prop + val).text() );
    else scrape = $(tag + prop + val).attr(attr);

    if (scrape) return scrape;
  }
};

module.exports = function (url) {
  return request(url)
  .then(function (html) {
    var $ = cheerio.load(html);
    var scrapes = {};

    // Attempt to scrape every property in scrapeTargets.json
    for (var key in targets) {
      scrapes[key] = scrapeProperty($, targets[key]);
    }

    // Perform some post-processing on particular properties
    scrapes.siteName = nameFromUrl(scrapes.siteName);
    scrapes.imageUrl = appendRef(url, scrapes.imageUrl);
    scrapes.siteIcon = appendRef(url, scrapes.siteIcon);

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


<commit_before>#!/usr/bin/env node
/*
 * Copyright (c) Maximilian Antoni <max@javascript.studio>
 *
 * @license MIT
 */
'use strict';

const editor = require('editor');
const changes = require('..');

const argv = require('minimist')(process.argv.slice(2), {
  alias: {
    file: 'f'
  }
});

let file = argv.file;

if (file) {
  changes.setFile(file);
} else {
  file = changes.getFile();
}

// Write the commit history to the changes file
const previous = changes.write();

// Let the user edit the changes
editor(file, (code) => {
  if (code === 0) {
    // Add the changes file to git
    changes.add(previous);
  } else {
    // Roll back
    changes.abort(previous);
  }
});
<commit_msg>Add help message<commit_after>#!/usr/bin/env node
/*
 * Copyright (c) Maximilian Antoni <max@javascript.studio>
 *
 * @license MIT
 */
'use strict';

const editor = require('editor');
const changes = require('..');

const argv = require('minimist')(process.argv.slice(2), {
  alias: {
    file: 'f',
    help: 'h'
  }
});
/* eslint-disable max-len */
const HELP_TEXT = `usage: changes [--file] [--help]

Options are ...
  -f, --file [FILENAME] Specify the name of the changelog file. Defaults to CHANGES.md.
  -h, --help            Display this help message.
`;
/* eslint-enable */

if (argv.h || argv.help) {
  console.log(HELP_TEXT);
  process.exit();
}

let file = argv.file;

if (file) {
  changes.setFile(file);
} else {
  file = changes.getFile();
}

// Write the commit history to the changes file
const previous = changes.write();

// Let the user edit the changes
editor(file, (code) => {
  if (code === 0) {
    // Add the changes file to git
    changes.add(previous);
  } else {
    // Roll back
    changes.abort(previous);
  }
});
<|endoftext|>