<commit_before>/* jshint node: true */
'use strict';

var StyleLinter = require('broccoli-stylelint');

module.exports = {
  name: 'ember-cli-stylelint',

  included: function(app) {
    //shared
    this.styleLintOptions = app.options.stylelint || {};
    this.styleLintOptions.console = console;

    //used in real app only
    if (!app.isTestingStyleLintAddon) {
      this._super.included(app);
    } else {
      //Testing only
      this.project = {
        generateTestFile: function(){}
      }
    }

    this.app = app;
  },

  lintTree: function(type, tree) {
    var project = this.project;

    if (type === 'app') {
      this.styleLintOptions.testGenerator =  function(relativePath, errors) {
        var passed = null;
        var name = relativePath+' should pass style lint';
        if (errors) {
          passed = false;
          var assertions = [name];
          for(var i = 0; i < errors.warnings.length; i++){
            var warning = errors.warnings[i];
            assertions.push(this.escapeErrorString('line: '+warning.line+', col: '+warning.column+' '+warning.text+'.'));
          }
          errors = assertions.join('\\n');
        } else {
          passed = true;
          errors = "";
        }

        return project.generateTestFile(' Style Lint ', [{
          name: name,
          passed: !!passed,
          errorMessage: errors
        }]);
      };
      return new StyleLinter(this.app.trees.app, this.styleLintOptions);
    } else {
      return tree;
    }
  }
};
<commit_msg>update broccoli<commit_after>/* jshint node: true */
'use strict';

var StyleLinter = require('broccoli-stylelint');

module.exports = {
  name: 'ember-cli-stylelint',

  included: function(app) {
    //shared
    this.styleLintOptions = app.options.stylelint || {};
    this.styleLintOptions.console = console;

    //used in real app only
    if (!app.isTestingStyleLintAddon) {
      this._super.included(app);
    } else {
      //Testing only
      this.project = {
        generateTestFile: function(){}
      }
    }

    this.app = app;
  },

  lintTree: function(type, tree) {
    var project = this.project;

    if (type === 'app') {
      this.styleLintOptions.testGenerator =  function(relativePath, errors) {
        var passed = null;
        var name = relativePath+' should pass style lint';
        if (errors) {
          passed = false;
          var assertions = [name];
          for(var i = 0; i < errors.warnings.length; i++){
            var warning = errors.warnings[i];
            assertions.push(this.escapeErrorString('line: '+warning.line+', col: '+warning.column+' '+warning.text+'.'));
          }
          errors = assertions.join('\\n');
        } else {
          passed = true;
          errors = "";
        }

        return project.generateTestFile(' Style Lint ', [{
          name: name,
          passed: !!passed,
          errorMessage: errors
        }]);
      };
      console.log(this.app.trees.app)
      return new StyleLinter(this.app.trees.app, this.styleLintOptions);
    } else {
      return tree;
    }
  }
};
<|endoftext|>


<commit_before>#!/usr/bin/env node
var fs = require('fs');
var path = require('path');
var mkdirp = require('mkdirp');
var minimist = require('minimist');
var level = require('level');
var strftime = require('strftime');

var argv = minimist(process.argv.slice(2));
var HOME = process.env.HOME || process.env.USERDIR;
var datadir = argv.d || path.join(HOME, '.timetrack');
mkdirp.sync(datadir);

var db = level(path.join(datadir, 'db'), { encoding: 'json' });

if (argv.h) usage(0)
else if (argv._[0] === 'start') {
    var d = argv.d ? new Date(argv.d) : new Date;
    var type = argv.type || argv.t || 'undefined';
    var pkey = strftime('time!%F %T', d);
    var tkey = 'time-type!' + type + strftime('!%F %T', d);
    db.batch([
        { key: pkey, value: { type: type } },
        { key: tkey, value: 0 }
    ], error);
    db.put(key, { type: argv.type || argv.t });
}
else if (argv._[0] === 'stop') {
    var d = argv.d ? new Date(argv.d) : new Date;
    var s = db.createReadStream({
        gt: 'time!', lt: 'time!~',
        limit: 1, reverse: true
    });
    s.once('data', function (row) {
        row.value.end = strftime('%F %T', d);
        db.put(row.key, row, error);
    });
}
else if (argv._[0] === 'status') {
    var s = db.createReadStream({
        gt: 'time!', lt: 'time!~',
        limit: 1, reverse: true
    });
    s.once('data', function (row) {
        var started = new Date(row.key.split('!')[1]);
        if (!row.value) {
            var elapsed = (new Date) - started;
            console.log('elapsed time: ' + fmt(elapsed));
        }
        else {
            console.log('stopped');
        }
    });
}
else if (argv._[0] === 'list') {
    var s = db.createReadStream({ gt: 'time!', lt: 'time!~' });
    s.on('error', error);
    s.on('data', function (row) {
        if (argv.raw) return console.log(JSON.stringify(row));

        var start = row.key.split('!')[1];
        var end = row.value.end;
        var elapsed = (end ? new Date(end) : new Date) - new Date(start);

        console.log(
            '%s  %s - %s  (%s)%s',
            new Date(start).valueOf(), start, end || 'NOW', fmt(elapsed),
            (row.value.type ? '  [' + row.value.type + ']' : '')
        );
    });
}
else if (argv._[0] === 'set') {
    db.put(argv._[1], JSON.parse(argv._[2]), error);
}
else if (argv._[0] === 'put') {
    db.put(argv._[1], JSON.parse(argv._[2]), error);
}
else if (argv._[0] === 'get') {
    db.get(argv._[1], function (err, row) {
        if (err) {
            console.error(String(err));
            process.exit(1);
        }
        else console.log(row);
    });
}
else if (argv._[0] === 'move') {
    db.get(argv._[1], function (err, row) {
        if (err) error(err);
        else db.batch([
            { type: 'del', key: argv._[1] },
            { type: 'put', key: argv._[2], value: row }
        ], error);
    });
}
else usage(1)

function usage (code) {
    var rs = fs.createReadStream(__dirname + '/usage.txt');
    rs.pipe(process.stdout);
    rs.on('close', function () {
        if (code) process.exit(code);
    });
}

function pad (s, len) {
    return Array(Math.max(0, len - String(s).length + 1)).join('0') + s;
}

function fmt (elapsed) {
    var n = elapsed / 1000;
    var hh = pad(Math.floor(n / 60 / 60), 2);
    var mm = pad(Math.floor(n / 60 % 60), 2);
    var ss = pad(Math.floor(n % 60), 2);
    return [ hh, mm, ss ].join(':');
}

function error (err) {
    if (!err) return;
    console.error(String(err));
    process.exit(1);
}
<commit_msg>easier to read output, removed duplicated date<commit_after>#!/usr/bin/env node
var fs = require('fs');
var path = require('path');
var mkdirp = require('mkdirp');
var minimist = require('minimist');
var level = require('level');
var strftime = require('strftime');

var argv = minimist(process.argv.slice(2));
var HOME = process.env.HOME || process.env.USERDIR;
var datadir = argv.d || path.join(HOME, '.timetrack');
mkdirp.sync(datadir);

var db = level(path.join(datadir, 'db'), { encoding: 'json' });

if (argv.h) usage(0)
else if (argv._[0] === 'start') {
    var d = argv.d ? new Date(argv.d) : new Date;
    var type = argv.type || argv.t || 'undefined';
    var pkey = strftime('time!%F %T', d);
    var tkey = 'time-type!' + type + strftime('!%F %T', d);
    db.batch([
        { key: pkey, value: { type: type } },
        { key: tkey, value: 0 }
    ], error);
    db.put(key, { type: argv.type || argv.t });
}
else if (argv._[0] === 'stop') {
    var d = argv.d ? new Date(argv.d) : new Date;
    var s = db.createReadStream({
        gt: 'time!', lt: 'time!~',
        limit: 1, reverse: true
    });
    s.once('data', function (row) {
        row.value.end = strftime('%F %T', d);
        db.put(row.key, row, error);
    });
}
else if (argv._[0] === 'status') {
    var s = db.createReadStream({
        gt: 'time!', lt: 'time!~',
        limit: 1, reverse: true
    });
    s.once('data', function (row) {
        var started = new Date(row.key.split('!')[1]);
        if (!row.value) {
            var elapsed = (new Date) - started;
            console.log('elapsed time: ' + fmt(elapsed));
        }
        else {
            console.log('stopped');
        }
    });
}
else if (argv._[0] === 'list') {
    var s = db.createReadStream({ gt: 'time!', lt: 'time!~' });
    s.on('error', error);
    s.on('data', function (row) {
        if (argv.raw) return console.log(JSON.stringify(row));

        var start = new Date(row.key.split('!')[1]);
        var end = row.value.end && new Date(row.value.end);
        var elapsed = (end ? end : new Date) - start;

        console.log(
            '%s  %s  [ %s - %s ]  (%s)%s',
            Math.floor(new Date(start).valueOf() / 1000),
            strftime('%F', start),
            strftime('%T', start),
            end ? strftime('%T', end) : 'NOW',
            fmt(elapsed),
            (row.value.type ? '  [' + row.value.type + ']' : '')
        );
    });
}
else if (argv._[0] === 'set') {
    db.put(argv._[1], JSON.parse(argv._[2]), error);
}
else if (argv._[0] === 'put') {
    db.put(argv._[1], JSON.parse(argv._[2]), error);
}
else if (argv._[0] === 'get') {
    db.get(argv._[1], function (err, row) {
        if (err) {
            console.error(String(err));
            process.exit(1);
        }
        else console.log(row);
    });
}
else if (argv._[0] === 'move') {
    db.get(argv._[1], function (err, row) {
        if (err) error(err);
        else db.batch([
            { type: 'del', key: argv._[1] },
            { type: 'put', key: argv._[2], value: row }
        ], error);
    });
}
else usage(1)

function usage (code) {
    var rs = fs.createReadStream(__dirname + '/usage.txt');
    rs.pipe(process.stdout);
    rs.on('close', function () {
        if (code) process.exit(code);
    });
}

function pad (s, len) {
    return Array(Math.max(0, len - String(s).length + 1)).join('0') + s;
}

function fmt (elapsed) {
    var n = elapsed / 1000;
    var hh = pad(Math.floor(n / 60 / 60), 2);
    var mm = pad(Math.floor(n / 60 % 60), 2);
    var ss = pad(Math.floor(n % 60), 2);
    return [ hh, mm, ss ].join(':');
}

function error (err) {
    if (!err) return;
    console.error(String(err));
    process.exit(1);
}
<|endoftext|>


<commit_before>const { gql } = require("apollo-server-express");
const ObjectId = require("mongodb").ObjectId;

const WorkExperienceType = "work";
const InterviewExperienceType = "interview";
const InternExperienceType = "intern";

const Type = gql`
    interface Experience {
        id: ID!
        type: ExperienceType!
        company: Company!
        job_title: JobTitle!
        region: String!
        experience_in_year: Int
        education: String
        salary: Salary
        title: String
        sections: [Section!]!
        created_at: Date!
        reply_count: Int!
        report_count: Int!
        like_count: Int!
        status: PublishStatus!
        archive: Archive!

        "使用者是否按贊 (null 代表未傳入驗證資訊)"
        liked: Boolean
    }

    type WorkExperience implements Experience {
        id: ID!
        type: ExperienceType!
        company: Company!
        job_title: JobTitle!
        region: String!
        experience_in_year: Int
        education: String
        salary: Salary
        title: String
        sections: [Section!]!
        created_at: Date!
        reply_count: Int!
        report_count: Int!
        like_count: Int!
        status: PublishStatus!
        archive: Archive!

        "使用者是否按贊 (null 代表未傳入驗證資訊)"
        liked: Boolean

        "work experience specific fields"
        data_time: YearMonth
        week_work_time: Int
        recommend_to_others: String
    }

    type WorkExperienceStatistics {
        count: Int!
        recommend_to_others: YesNoOrUnknownCount!
    }

    type InterviewExperience implements Experience {
        id: ID!
        type: ExperienceType!
        company: Company!
        job_title: JobTitle!
        region: String!
        experience_in_year: Int
        education: String
        salary: Salary
        title: String
        sections: [Section!]!
        created_at: Date!
        reply_count: Int!
        report_count: Int!
        like_count: Int!
        status: PublishStatus!
        archive: Archive!

        "使用者是否按贊 (null 代表未傳入驗證資訊)"
        liked: Boolean

        "interview experience specific fields"
        interview_time: YearMonth!
        interview_result: String!
        overall_rating: Int!
        interview_qas: [InterviewQuestion!]
        interview_sensitive_questions: [String!]
    }

    type InterviewExperienceStatistics {
        count: Int!
        overall_rating: Float!
    }

    enum ExperienceType {
        work
        interview
        intern
    }

    type Section {
        subtitle: String
        content: String
    }

    type InterviewQuestion {
        question: String
        answer: String
    }
`;

const Query = gql`
    extend type Query {
        "取得單篇經驗分享"
        experience(id: ID!): Experience
    }
`;

const Mutation = `
`;

const ExperienceLikedResolver = async (experience, args, { manager, user }) => {
    if (!user) {
        return null;
    }

    const like = await manager.ExperienceLikeModel.getLikeByExperienceAndUser(
        experience._id,
        user
    );

    if (like) {
        return true;
    }
    return false;
};

const resolvers = {
    Experience: {
        __resolveType(experience) {
            if (experience.type === WorkExperienceType) {
                return "WorkExperience";
            }
            if (experience.type === InterviewExperienceType) {
                return "InterviewExperience";
            }
            if (experience.type === InternExperienceType) {
                // TODO: Intern
                return null;
            }
            return null;
        },
    },
    WorkExperience: {
        id: experience => experience._id,
        job_title: experience => ({
            name: experience.job_title,
        }),
        liked: ExperienceLikedResolver,
    },
    InterviewExperience: {
        id: experience => experience._id,
        job_title: experience => ({
            name: experience.job_title,
        }),
        liked: ExperienceLikedResolver,
    },
    Query: {
        async experience(_, { id }, ctx) {
            const collection = ctx.db.collection("experiences");

            const result = await collection.findOne({
                _id: ObjectId(id),
                status: "published",
                "archive.is_archived": false,
            });

            if (!result) {
                return null;
            } else {
                return result;
            }
        },
    },
};

const types = [Type, Query, Mutation];

module.exports = {
    resolvers,
    types,
};
<commit_msg>Fix: query intern experiences (#589)<commit_after>const { gql } = require("apollo-server-express");
const ObjectId = require("mongodb").ObjectId;

const WorkExperienceType = "work";
const InterviewExperienceType = "interview";
const InternExperienceType = "intern";

const Type = gql`
    interface Experience {
        id: ID!
        type: ExperienceType!
        company: Company!
        job_title: JobTitle!
        region: String!
        experience_in_year: Int
        education: String
        salary: Salary
        title: String
        sections: [Section!]!
        created_at: Date!
        reply_count: Int!
        report_count: Int!
        like_count: Int!
        status: PublishStatus!
        archive: Archive!

        "使用者是否按贊 (null 代表未傳入驗證資訊)"
        liked: Boolean
    }

    type WorkExperience implements Experience {
        id: ID!
        type: ExperienceType!
        company: Company!
        job_title: JobTitle!
        region: String!
        experience_in_year: Int
        education: String
        salary: Salary
        title: String
        sections: [Section!]!
        created_at: Date!
        reply_count: Int!
        report_count: Int!
        like_count: Int!
        status: PublishStatus!
        archive: Archive!

        "使用者是否按贊 (null 代表未傳入驗證資訊)"
        liked: Boolean

        "work experience specific fields"
        data_time: YearMonth
        week_work_time: Int
        recommend_to_others: String
    }

    type WorkExperienceStatistics {
        count: Int!
        recommend_to_others: YesNoOrUnknownCount!
    }

    type InterviewExperience implements Experience {
        id: ID!
        type: ExperienceType!
        company: Company!
        job_title: JobTitle!
        region: String!
        experience_in_year: Int
        education: String
        salary: Salary
        title: String
        sections: [Section!]!
        created_at: Date!
        reply_count: Int!
        report_count: Int!
        like_count: Int!
        status: PublishStatus!
        archive: Archive!

        "使用者是否按贊 (null 代表未傳入驗證資訊)"
        liked: Boolean

        "interview experience specific fields"
        interview_time: YearMonth!
        interview_result: String!
        overall_rating: Int!
        interview_qas: [InterviewQuestion!]
        interview_sensitive_questions: [String!]
    }

    type InterviewExperienceStatistics {
        count: Int!
        overall_rating: Float!
    }

    type InternExperience implements Experience {
        id: ID!
        type: ExperienceType!
        company: Company!
        job_title: JobTitle!
        region: String!
        experience_in_year: Int
        education: String
        salary: Salary
        title: String
        sections: [Section!]!
        created_at: Date!
        reply_count: Int!
        report_count: Int!
        like_count: Int!
        status: PublishStatus!
        archive: Archive!

        "使用者是否按贊 (null 代表未傳入驗證資訊)"
        liked: Boolean

        "intern experience specific fields"
        starting_year: Int
        overall_rating: Float
    }

    enum ExperienceType {
        work
        interview
        intern
    }

    type Section {
        subtitle: String
        content: String
    }

    type InterviewQuestion {
        question: String
        answer: String
    }
`;

const Query = gql`
    extend type Query {
        "取得單篇經驗分享"
        experience(id: ID!): Experience
    }
`;

const Mutation = `
`;

const ExperienceLikedResolver = async (experience, args, { manager, user }) => {
    if (!user) {
        return null;
    }

    const like = await manager.ExperienceLikeModel.getLikeByExperienceAndUser(
        experience._id,
        user
    );

    if (like) {
        return true;
    }
    return false;
};

const resolvers = {
    Experience: {
        __resolveType(experience) {
            if (experience.type === WorkExperienceType) {
                return "WorkExperience";
            }
            if (experience.type === InterviewExperienceType) {
                return "InterviewExperience";
            }
            if (experience.type === InternExperienceType) {
                return "InternExperience";
            }
            return null;
        },
    },
    WorkExperience: {
        id: experience => experience._id,
        job_title: experience => ({
            name: experience.job_title,
        }),
        liked: ExperienceLikedResolver,
    },
    InterviewExperience: {
        id: experience => experience._id,
        job_title: experience => ({
            name: experience.job_title,
        }),
        liked: ExperienceLikedResolver,
    },
    InternExperience: {
        id: experience => experience._id,
        job_title: experience => ({
            name: experience.job_title,
        }),
        liked: ExperienceLikedResolver,
        region: experience => experience.region || "",
    },
    Query: {
        async experience(_, { id }, ctx) {
            const collection = ctx.db.collection("experiences");

            const result = await collection.findOne({
                _id: ObjectId(id),
                status: "published",
                "archive.is_archived": false,
            });

            if (!result) {
                return null;
            } else {
                return result;
            }
        },
    },
};

const types = [Type, Query, Mutation];

module.exports = {
    resolvers,
    types,
};
<|endoftext|>


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

/**
 * Copyright (c) 2016-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */

/* eslint-disable no-var */
/* eslint-disable flowtype/require-valid-file-annotation */

var semver = require('semver');
var ver = process.versions.node;
var possibles = [];
var found = false;

if (semver.satisfies(ver, '>=5.0.0')) {
  possibles.push('../updates/current/lib/cli/index.js');
  possibles.push('../lib/cli/index.js');
} else if (semver.satisfies(ver, '>=4.0.0')) {
  possibles.push('../updates/current/lib-legacy/cli/index.js');
  possibles.push('../lib-legacy/cli/index.js');
} else {
  throw new Error('Node version ' + ver + ' is not supported');
}

var i = 0;
for (; i < possibles.length; i++) {
  var possible = possibles[i];
  try {
    module.exports = require(possible);
    found = true;
    break;
  } catch (err) {
    if (err.code === 'MODULE_NOT_FOUND') {
      continue;
    } else {
      throw err;
    }
  }
}

if (!found) {
  throw new Error('Failed to load');
}
<commit_msg>Rethrow last module not found error when we fail to load bin/kpm - fixes #300<commit_after>#!/usr/bin/env node

/**
 * Copyright (c) 2016-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */

/* eslint-disable no-var */
/* eslint-disable flowtype/require-valid-file-annotation */

var semver = require('semver');
var ver = process.versions.node;
var possibles = [];
var found = false;
var _err;

if (semver.satisfies(ver, '>=5.0.0')) {
  possibles.push('../updates/current/lib/cli/index.js');
  possibles.push('../lib/cli/index.js');
} else if (semver.satisfies(ver, '>=4.0.0')) {
  possibles.push('../updates/current/lib-legacy/cli/index.js');
  possibles.push('../lib-legacy/cli/index.js');
} else {
  throw new Error('Node version ' + ver + ' is not supported');
}

var i = 0;
for (; i < possibles.length; i++) {
  var possible = possibles[i];
  try {
    module.exports = require(possible);
    found = true;
    break;
  } catch (err) {
    if (err.code === 'MODULE_NOT_FOUND') {
      _err = err;
      continue;
    } else {
      throw err;
    }
  }
}

if (!found) {
  throw _err || new Error('Failed to load');
}
<|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, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit_time = commit_count * max_sleep / 2
    var commit_time_hour = Math.floor(commit_time / 3600)
    var commit_time_rem = commit_time - (commit_time_hour * 3600)
    var commit_time_min = Math.floor(commit_time_rem / 60)
    var commit_time_sec = commit_time_rem - (commit_time_min * 60)
    console.info("Input file is %s Bytes, this will generate %s commits and take approximately %s hours %s minutes %s seconds", length, commit_count, commit_time_hour, commit_time_min, commit_time_sec)
    var t_offset = 0
    if (process.env.FAKETIME) {
      // 20% buffer, to reduce the<commit_msg>What do you mean you can't pack up the commit?<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')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit_time = commit_count * max_sleep / 2
    var commit_time_hour = Math.floor(commit_time / 3600)
    var commit_time_rem = commit_time - (commit_time_hour * 3600)
    var commit_time_min = Math.floor(commit_time_rem / 60)
    var commit_time_sec = commit_time_rem - (commit_time_min * 60)
    console.info("Input file is %s Bytes, this will generate %s commits and take approximately %s hours %s minutes %s seconds", length, commit_count, commit_time_hour, commit_time_min, commit_time_sec)
    var t_offset = 0
    if (process.env.FAKETIME) {
      // 20% buffer, to reduce the <|endoftext|>


<commit_before>module.exports = function (sails) {

	/**
	 * Module dependencies.
	 */

	var _			= require( 'lodash' ),
		utils		= require( './utils' )(sails),
		fs			= utils.fs,
		ejs			= require('ejs'),
		Session	= require('../lib/session')(sails);

	// Output in directory where cmdline tool was run
	var outputPath = '.';

	// If coffeescript is not installed, fail silently
	try {
		require('coffee-script');
		sails.log.verbose('Enabling CoffeeScript...');
	}
	catch (e) {
		sails.log.verbose('CoffeeScript not installed.');
	}

	/**
	 * Expose `sails new` functionality
	 */

	return function createNewApp(appName, templateLang, useLinker) {
		// Whether the project being made in an existing directory or not
		var existingDirectory;

		// If app is being created inside the current directory
		if (appName === '.') {

			// The app name is the current directory name
			appName = _.last(process.cwd().split('/'));

			// Set the current directory to the parent directory of the new app
			process.chdir('../');

			// This will be checked to determine if a new app directory needs to be made
			existingDirectory = true;
		}

		// Check if the appName is an absolute path, if so don't prepend './'
		if (appName.substr(0, 1) === '/') {
			outputPath = appName;
		} else {
			outputPath = outputPath + '/' + appName;
		}

		// If app is being created in new directory
		if (!existingDirectory) {

			// Check if there is a directory in the current directory with the new
			// app name, log and exit if there is
			utils.verifyDoesntExist(outputPath, 'A file or directory already exists at: ' + outputPath);

			// Create a directory with the specified app name
			utils.generateDir(outputPath);
		}

		sails.log.info('Generating Sails project (' + appName + ')...');

		// useLinker will determin the assets dir stucture for the new sails project
		if (useLinker) {
			utils.copyBoilerplate('linkerAssets', outputPath + '/assets');
		} else {
			utils.copyBoilerplate('assets', outputPath + '/assets');
		}

		// Add these boilerplate dirs regardless
		utils.copyBoilerplate('api', outputPath + '/api');
		utils.copyBoilerplate('config', outputPath + '/config', function () {

			// Generate session secret
			var boilerplatePath = __dirname + '/boilerplates/config/session.js';
			var newSessionConfig = ejs.render(fs.readFileSync(boilerplatePath, 'utf8'), {
				secret: Session.generateSecret()
			});
			fs.writeFileSync(outputPath + '/config/session.js', newSessionConfig, 'utf8');
		});

		// Different stuff for different view engines
		if (templateLang === 'handlebars') templateLang = 'hbs';

		utils.copyBoilerplate('views/' + templateLang, outputPath + '/views');

		var viewConfig = {
			viewEngine: templateLang
		};

		if (templateLang === 'jade' || templateLang === 'haml') {
			viewConfig.layout = false;
		}

		fs.createFileSync(outputPath + '/config/views.js');
		fs.writeFileSync(outputPath + '/config/views.js', 'module.exports = ' +
			JSON.stringify(viewConfig , null, '\t').split('"').join('\'') + ';');

		// Default app launcher file (for situations where sails lift isn't good enough)
		utils.generateFile('app.js', outputPath + '/app.js');

		// Create .gitignore
		utils.generateFile('gitignore', outputPath + '/.gitignore');

		// Generate package.json
		sails.log.debug('Generating package.json...');
		fs.writeFileSync(outputPath + '/package.json', JSON.stringify({
			name: appName,
			'private': true,
			version: '0.0.0',
			description: 'a Sails application',
			dependencies: {
				sails: sails.version,
				grunt: '0.4.1',
				optimist: '0.3.4' // TODO: remove this and handle it differently
			},
			scripts: {
				// Include this later when we have "sails test" ready.
				// test: './node_modules/mocha/bin/mocha -b',
				start: 'node app.js',
				debug: 'node debug app.js'
			},
			main: 'app.js',
			repository: '',
			author: '',
			license: ''
		}, null, 4));

		// Copy Gruntfile
		sails.log.debug('Generating README.md...');
		utils.generateFile('Gruntfile.js', outputPath + '/Gruntfile.js');

		// Generate README
		sails.log.debug('Generating README.md...');
		fs.writeFileSync(outputPath + '/README.md', '# ' + appName + '\n### a Sails application');

		// Copy dependencies (to avoid having to do a local npm install in new projects)
		utils.generateDir(outputPath + '/node_modules');
		utils.copySailsDependency('optimist', outputPath + '/node_modules');
		utils.copySailsDependency('grunt', outputPath + '/node_modules');
		utils.copySailsDependency('sails-disk', outputPath + '/node_modules');

		// Other grunt dependencies are automatically pulled from sails core deps.

		// Copy Sails itself into new project as a local dependency
		//
		// TODO:	examine using a symbolic link for the node_modules
		// 			instead of copying the directory over directly,
		//			since it would be much quicker, and wouldn't hurt anything
		utils.copySails(outputPath + '/node_modules/sails');

	};

};
<commit_msg>Add logic that gives correct view boilerplatedepending on templating engine specified on when creating a new sails app<commit_after>module.exports = function (sails) {

	/**
	 * Module dependencies.
	 */

	var _			= require( 'lodash' ),
		utils		= require( './utils' )(sails),
		fs			= utils.fs,
		ejs			= require('ejs'),
		Session	= require('../lib/session')(sails);

	// Output in directory where cmdline tool was run
	var outputPath = '.';

	// If coffeescript is not installed, fail silently
	try {
		require('coffee-script');
		sails.log.verbose('Enabling CoffeeScript...');
	}
	catch (e) {
		sails.log.verbose('CoffeeScript not installed.');
	}

	/**
	 * Expose `sails new` functionality
	 */

	return function createNewApp(appName, templateLang, useLinker) {
		// Whether the project being made in an existing directory or not
		var existingDirectory;

		// If app is being created inside the current directory
		if (appName === '.') {

			// The app name is the current directory name
			appName = _.last(process.cwd().split('/'));

			// Set the current directory to the parent directory of the new app
			process.chdir('../');

			// This will be checked to determine if a new app directory needs to be made
			existingDirectory = true;
		}

		// Check if the appName is an absolute path, if so don't prepend './'
		if (appName.substr(0, 1) === '/') {
			outputPath = appName;
		} else {
			outputPath = outputPath + '/' + appName;
		}

		// If app is being created in new directory
		if (!existingDirectory) {

			// Check if there is a directory in the current directory with the new
			// app name, log and exit if there is
			utils.verifyDoesntExist(outputPath, 'A file or directory already exists at: ' + outputPath);

			// Create a directory with the specified app name
			utils.generateDir(outputPath);
		}

		sails.log.info('Generating Sails project (' + appName + ')...');

		// useLinker will determin the assets dir stucture for the new sails project
		if (useLinker) {
			utils.copyBoilerplate('linkerAssets', outputPath + '/assets');
		} else {
			utils.copyBoilerplate('assets', outputPath + '/assets');
		}

		// Add these boilerplate dirs regardless
		utils.copyBoilerplate('api', outputPath + '/api');
		utils.copyBoilerplate('config', outputPath + '/config', function () {

			// Generate session secret
			var boilerplatePath = __dirname + '/boilerplates/config/session.js';
			var newSessionConfig = ejs.render(fs.readFileSync(boilerplatePath, 'utf8'), {
				secret: Session.generateSecret()
			});
			fs.writeFileSync(outputPath + '/config/session.js', newSessionConfig, 'utf8');
		});

		// Different stuff for different view engines
		if (templateLang === 'handlebars') templateLang = 'hbs';

		utils.copyBoilerplate('views/' + templateLang, outputPath + '/views', function () {
			// If using linker, override the layout file with linker layout file
			if (useLinker) {

				if (templateLang === 'hbs' || templateLang === 'jade') {
					sails.log.warn('script linking does not work with the `'+templateLang+'` templating '+
					'engine at this time. You must set up the Gruntfile yourself for this feature to work.');
				}
				utils.copyBoilerplate('linkerLayouts/' + templateLang, outputPath + '/views');
			}
		});

		var viewConfig = {
			viewEngine: templateLang
		};

		if (templateLang === 'jade' || templateLang === 'haml') {
			viewConfig.layout = false;
		}

		fs.createFileSync(outputPath + '/config/views.js');
		fs.writeFileSync(outputPath + '/config/views.js', 'module.exports = ' +
			JSON.stringify(viewConfig , null, '\t').split('"').join('\'') + ';');

		// Default app launcher file (for situations where sails lift isn't good enough)
		utils.generateFile('app.js', outputPath + '/app.js');

		// Create .gitignore
		utils.generateFile('gitignore', outputPath + '/.gitignore');

		// Generate package.json
		sails.log.debug('Generating package.json...');
		fs.writeFileSync(outputPath + '/package.json', JSON.stringify({
			name: appName,
			'private': true,
			version: '0.0.0',
			description: 'a Sails application',
			dependencies: {
				sails: sails.version,
				grunt: '0.4.1',
				optimist: '0.3.4' // TODO: remove this and handle it differently
			},
			scripts: {
				// Include this later when we have "sails test" ready.
				// test: './node_modules/mocha/bin/mocha -b',
				start: 'node app.js',
				debug: 'node debug app.js'
			},
			main: 'app.js',
			repository: '',
			author: '',
			license: ''
		}, null, 4));

		// Copy Gruntfile
		sails.log.debug('Generating README.md...');
		utils.generateFile('Gruntfile.js', outputPath + '/Gruntfile.js');

		// Generate README
		sails.log.debug('Generating README.md...');
		fs.writeFileSync(outputPath + '/README.md', '# ' + appName + '\n### a Sails application');

		// Copy dependencies (to avoid having to do a local npm install in new projects)
		utils.generateDir(outputPath + '/node_modules');
		utils.copySailsDependency('optimist', outputPath + '/node_modules');
		utils.copySailsDependency('grunt', outputPath + '/node_modules');
		utils.copySailsDependency('sails-disk', outputPath + '/node_modules');

		// Other grunt dependencies are automatically pulled from sails core deps.

		// Copy Sails itself into new project as a local dependency
		//
		// TODO:	examine using a symbolic link for the node_modules
		// 			instead of copying the directory over directly,
		//			since it would be much quicker, and wouldn't hurt anything
		utils.copySails(outputPath + '/node_modules/sails');

	};

};
<|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!",
  "Di<commit_msg>How many more of these can I make?<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<|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 = comm<commit_msg>Found an issue with the letter 'a', so I fixed it.<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 = commi<|endoftext|>


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

var cli   = require('commander');
var init   = require('./functions.js')

cli
  .version('0.1.0')
  .command('summarise <csv-file>')
  .description('Summarise a CSV file of transactions for a budget.')
  .action(init);

cli.parse(process.argv);

if(cli.args.length === 0) cli.help();

<commit_msg>fix indentation<commit_after>#!/usr/bin/env node

var cli   = require('commander');
var init  = require('./functions.js')

cli
  .version('0.1.0')
  .command('summarise <csv-file>')
  .description('Summarise a CSV file of transactions for a budget.')
  .action(init);

cli.parse(process.argv);

if(cli.args.length === 0) cli.help();

<|endoftext|>


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

const configUtil = require('../lib/config-util')
const foreground = require('foreground-child')
const resolveFrom = require('resolve-from')
const NYC = require('../index.js')

// parse configuration and command-line arguments;
// we keep these values in a few different forms,
// used in the various execution contexts of nyc:
// reporting, instrumenting subprocesses, etc.

async function main () {
  const { argv, childArgs, yargs } = await configUtil()

  if (['check-coverage', 'report', 'instrument', 'merge'].includes(argv._[0])) {
    // look in lib/commands for logic.
    return
  }

  if (argv._.length === 0) {
    // I don't have a clue what you're doing.
    process.exitCode = 1
    yargs.showHelp()
    return
  }

  // if instrument is set to false,
  // enable a noop instrumenter.
  if (!argv.instrument) argv.instrumenter = './lib/instrumenters/noop'
  else argv.instrumenter = './lib/instrumenters/istanbul'

  var nyc = (new NYC(argv))
  if (argv.clean) {
    await nyc.reset()
  } else {
    await nyc.createTempDirectory()
  }

  if (argv.all) {
    await nyc.addAllFiles()
  }

  const env = {
    NYC_CONFIG: JSON.stringify(argv),
    NYC_CWD: process.cwd()
  }

  if (argv['babel-cache'] === false) {
    // babel's cache interferes with some configurations, so is
    // disabled by default. opt in by setting babel-cache=true.
    env.BABEL_DISABLE_CACHE = process.env.BABEL_DISABLE_CACHE = '1'
  }

  if (!argv.useSpawnWrap) {
    const { preloadAppend, propagateEnv } = require('node-preload')

    nyc.require.forEach(requireModule => {
      const mod = resolveFrom.silent(nyc.cwd, requireModule) || requireModule
      preloadAppend(mod)
      require(mod)
    })
    preloadAppend(require.resolve('../lib/wrap.js'))
    Object.assign(propagateEnv, env)
  }

  if (argv.all) nyc.addAllFiles()

  if (argv.useSpawnWrap) {
    const wrapper = require.resolve('./wrap.js')
    // Support running nyc as a user without HOME (e.g. linux 'nobody'),
    // https://github.com/istanbuljs/nyc/issues/951
    env.SPAWN_WRAP_SHIM_ROOT = process.env.SPAWN_WRAP_SHIM_ROOT || process.env.XDG_CACHE_HOME || require('os').homedir()
    const sw = require('spawn-wrap')

    sw([wrapper], env)
  }

  // Both running the test script invocation and the check-coverage run may
  // set process.exitCode. Keep track so that both children are run, but
  // a non-zero exit codes in either one leads to an overall non-zero exit code.
  process.exitCode = 0
  foreground(childArgs, async () => {
    var mainChildExitCode = process.exitCode

    await nyc.writeProcessIndex()

    nyc.maybePurgeSourceMapCache()
    if (argv.checkCoverage) {
      await nyc.checkCoverage({
        lines: argv.lines,
        functions: argv.functions,
        branches: argv.branches,
        statements: argv.statements
      }, argv['per-file'])
      process.exitCode = process.exitCode || mainChildExitCode
    }

    if (!argv.silent) {
      await nyc.report()
    }
  })
}

main()
<commit_msg>chore: Fix merge error (#1193)<commit_after>#!/usr/bin/env node
'use strict'

const configUtil = require('../lib/config-util')
const foreground = require('foreground-child')
const resolveFrom = require('resolve-from')
const NYC = require('../index.js')

// parse configuration and command-line arguments;
// we keep these values in a few different forms,
// used in the various execution contexts of nyc:
// reporting, instrumenting subprocesses, etc.

async function main () {
  const { argv, childArgs, yargs } = await configUtil()

  if (['check-coverage', 'report', 'instrument', 'merge'].includes(argv._[0])) {
    // look in lib/commands for logic.
    return
  }

  if (argv._.length === 0) {
    // I don't have a clue what you're doing.
    process.exitCode = 1
    yargs.showHelp()
    return
  }

  // if instrument is set to false,
  // enable a noop instrumenter.
  if (!argv.instrument) argv.instrumenter = './lib/instrumenters/noop'
  else argv.instrumenter = './lib/instrumenters/istanbul'

  var nyc = (new NYC(argv))
  if (argv.clean) {
    await nyc.reset()
  } else {
    await nyc.createTempDirectory()
  }

  const env = {
    NYC_CONFIG: JSON.stringify(argv),
    NYC_CWD: process.cwd()
  }

  if (argv['babel-cache'] === false) {
    // babel's cache interferes with some configurations, so is
    // disabled by default. opt in by setting babel-cache=true.
    env.BABEL_DISABLE_CACHE = process.env.BABEL_DISABLE_CACHE = '1'
  }

  if (!argv.useSpawnWrap) {
    const { preloadAppend, propagateEnv } = require('node-preload')

    nyc.require.forEach(requireModule => {
      const mod = resolveFrom.silent(nyc.cwd, requireModule) || requireModule
      preloadAppend(mod)
      require(mod)
    })
    preloadAppend(require.resolve('../lib/wrap.js'))
    Object.assign(propagateEnv, env)
  }

  if (argv.all) {
    await nyc.addAllFiles()
  }

  if (argv.useSpawnWrap) {
    const wrapper = require.resolve('./wrap.js')
    // Support running nyc as a user without HOME (e.g. linux 'nobody'),
    // https://github.com/istanbuljs/nyc/issues/951
    env.SPAWN_WRAP_SHIM_ROOT = process.env.SPAWN_WRAP_SHIM_ROOT || process.env.XDG_CACHE_HOME || require('os').homedir()
    const sw = require('spawn-wrap')

    sw([wrapper], env)
  }

  // Both running the test script invocation and the check-coverage run may
  // set process.exitCode. Keep track so that both children are run, but
  // a non-zero exit codes in either one leads to an overall non-zero exit code.
  process.exitCode = 0
  foreground(childArgs, async () => {
    var mainChildExitCode = process.exitCode

    await nyc.writeProcessIndex()

    nyc.maybePurgeSourceMapCache()
    if (argv.checkCoverage) {
      await nyc.checkCoverage({
        lines: argv.lines,
        functions: argv.functions,
        branches: argv.branches,
        statements: argv.statements
      }, argv['per-file'])
      process.exitCode = process.exitCode || mainChildExitCode
    }

    if (!argv.silent) {
      await nyc.report()
    }
  })
}

/* istanbul ignore next: the error branch should be unreachable */
main().catch(error => {
  console.log('nyc error:', error)
  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) {
    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')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit_time = commit_count * max_sleep / 2
    var commit_time_hour = Math.floor(commit_time / 3600)
    var commit_time_rem = commit_time - (commit_time_hour * 3600)
    var commit_time_min = Math.floor(commit_time_rem / 60)
    var commit_time_sec = commit_time_rem - (commit_time_min * 60)
    console.info("Input file is %s By<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) {
    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')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit_time = commit_count * max_sleep / 2
    var commit_time_hour = Math.floor(commit_time / 3600)
    var commit_time_rem = commit_time - (commit_time_hour * 3600)
    var commit_time_min = Math.floor(commit_time_rem / 60)
    var commit_time_sec = commit_time_rem - (commit_time_min * 60)
    console.info("Input file is %s Byt<|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",<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 '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",
<|endoftext|>


<commit_before>/**
 * Created by dob on 01.04.14.
 */

var molecuel, elements;
var grid = require('gridfs-uploader');
var multer = require('multer');
var os = require('os');
var flowlib = require('./lib/flow.js');
var fs = require('fs');
var uuid = require('node-uuid');

/**
 * file module for molecuel CMS
 */
var files = function() {

  var self = this;

  this.uploadDir = os.tmpdir();

  if(molecuel.config && molecuel.config.files && molecuel.config.files.uploaddir) {
    this.uploadDir = molecuel.config.files.uploaddir;
  }
  this.flow = flowlib(this.uploadDir);

  molecuel.on('mlcl::elements::registrations:pre',  function(module) {

    elements = module;

    // get native mongo driver
    var mongo = elements.database.database.mongo;
    var db = elements.database.database.connection.db;
    self.grid = new grid(mongo);
    self.grid.db = db;

    self.fileSchema =  {
      // Definition of the filename
      filename: { type: String},
      // Define the content type
      contentType: { type: String},
      // length data
      length: {type: Number, 'default': 0, form: {readonly: true}},
      chunkSize: {type: Number, 'default': 0, form: {readonly: true}},
      // upload date
      uploadDate: { type: Date, 'default': Date.now, form: {readonly: true}},

      // additional metadata
      metadata: {
        filename: {type: String}
      },
      md5: { type: String, trim: true }
    };

    var schemaDefinition = {
      schemaName: 'file',
      schema: self.fileSchema,
      options: {
        indexable: true,
        avoidTranslate: true,
        noStrict: true,
        collection: 'fs.files',
        subSchema: true
      }
    };
    elements.registerSchemaDefinition(schemaDefinition);
    elements.registerTypeHandler('file', self.download);
  });

  molecuel.on('mlcl::core::middlewareRegister:post', function(module, app) {
    //app.use(multer());
    // send init event
    molecuel.emit('mlcl::files::init:post', self);
  });

};

/* ************************************************************************
 SINGLETON CLASS DEFINITION
 ************************************************************************ */
var instance = null;

/**
 * Singleton getInstance definition
 * @return singleton class
 */
var getInstance = function () {
  if (instance === null) {
    instance = new files();
  }
  return instance;
};

/**
 * Upload handler for files
 * @param req
 * @param res
 * @param next
 */
files.prototype.upload = function(req, res) {
  if(req.files) {
    this.saveFile(req.files.files.path, req.files.files.originalname, null, function(err, result) {
      if(err) {
        return res.send(500, err);
      }
      res.send({files: [result]});
    });
  } else {
    res.send(500);
  }
};

/**
 * Upload handler for files with flow library
 * @param req
 * @param res
 */
files.prototype.uploadFlow = function(req, res) {
  var files = getInstance();
  files.flow.post(req, function(status, filename, original_filename, identifier) {
    if(status === 'done') {
      var fileuuid = uuid.v4();
      var tmpfile = files.uploadDir + '/' +fileuuid;
      var stream = fs.createWriteStream(files.uploadDir + '/' +fileuuid);
      files.flow.write(identifier, stream);

      stream.on('finish', function() {
        files.saveFile(tmpfile, original_filename, null, function(errSave, result) {
          if(errSave) {
            res.send(400, 'Error saving file');
          } else {
            files.flow.clean(identifier);
            fs.unlink(tmpfile, function(errDelete) {
              res.send(200, {
                  'file': result.result._id
              });
            });
          }
        });
      });
    } else {
      res.send(200);
    }
  });
};

/**
 * Upload handler for files with flow library
 * @param req
 * @param res
 * @todo check via gridfs if file is already available.
 */
files.prototype.uploadFlowStatus = function(req, res) {
//  res.send(404);
  var files = getInstance();
  files.flow.get(req, function(status, filename, original_filename, identifier) {
      if(status === 'found') {
        res.send(200);
      } else {
        res.send(404);
      }
  });
};

/**
 * Download handler for elements file type
 * @param req
 * @param res
 * @param next
 */
files.prototype.download = function download(req, res, next) {
  var files = getInstance();
  var grid = files.grid;
  var id = res.locals.data.main._id;
  if(req.method === 'GET') {
    grid.getFileStream(id, function(err, filestream) {
      if(!filestream) {
        next();
      } else {
        filestream.pipe(res);
      }
    });
  } else if(req.method === 'DELETE') {
    files.deleteFile(req, res, next);
  }
};

/**
 * Delete file middleware function
 * @param req
 * @param res
 * @param next
 */
files.prototype.deleteFile = function deleteFile(req, res) {
  var files = getInstance();
  var id = res.locals.data.main._id;
  files.deleteById(id, function(err) {
    if(err) {
      res.send(500);
    } else {
      res.send(200);
    }
  });
};

files.prototype.getFileInfo = function getFileInfo(req, res) {
  var files = getInstance();
  files.getInfoById(req.params.id, function(err, doc) {
    if(err) {
      res.send(500);
    } else if(doc){
      res.send(doc);
    } else {
      res.send(404);
    }
  });
};

files.prototype.deleteById = function deleteById(id, callback) {
  var files = getInstance();
  var grid = files.grid;
  grid.deleteFile(id, null, function(err) {
    if(err) {
      return callback(err);
    } else {
      if(elements && elements.elastic) {
        elements.elastic.delete('file', id, function() {
          return callback();
        });
      }
    }
  });
};

files.prototype.getInfoById = function(id, callback) {
  var files = getInstance();
  var file = elements.getElementType('file');
  file.findById(id, callback);
};

files.prototype.saveFile = function saveFile(path, name, options, callback) {
  var files = getInstance();

  /**
   * renderResult
   * renders the result from the db into a json object with delete url etc
   * @param res
   * @param dataset
   */
  var renderResult = function renderResult(dataset) {
    var result;
    if(dataset) {
      result = {
        name: dataset.filename,
        size: dataset.length,
        url: dataset.url,
        thumbnailUrl: dataset.url,
        deleteUrl: dataset.url,
        deleteType: 'DELETE',
        result: dataset
      };

      // file path are never relative
      if (result.url && result.url.charAt(0) !== '/') {
        result.url = '/'+result.url;
      }
    }
    return result;
  };

  files.grid.putUniqueFile(path, name, options, function(err, result) {
    var dbResult;
    var fileModel = elements.getModel('file');

    if(err && err.name === 'NotUnique') { //File already in gridfs
      dbResult = err.result;
      if(dbResult) {
        if(!dbResult.url || (options && options.url && options.url !== dbResult.url)) {
          fileModel.findById(dbResult._id, function(err, myobj) {
            // save it again to ensure url creation
            if(options && options.url) {
              myobj.url = options.url;
            }
            myobj.save(function(err, obj) {
              if(err) {
                return callback(err);
              }
              return callback(null, renderResult(obj));
            });
          });
        } else {
          return callback(null, renderResult(dbResult));
        }
      }
    } else if(err) {
      return callback(err);
    } else {
      dbResult = result;
      fileModel.findById(dbResult._id, function(err, myobj) {
        if(options && options.url) {
          myobj.url = options.url;
        }
        // save it again to ensure url creation
        myobj.save(function(err, obj) {
          if(err) {
            return callback(err);
          }
          return callback(null, renderResult(obj));
        });
      });
    }
  });
};

var init = function(mlcl) {
  molecuel = mlcl;
  return getInstance();
};

module.exports = init;
<commit_msg>file model form<commit_after>/**
 * Created by dob on 01.04.14.
 */

var molecuel, elements;
var grid = require('gridfs-uploader');
var multer = require('multer');
var os = require('os');
var flowlib = require('./lib/flow.js');
var fs = require('fs');
var uuid = require('node-uuid');

/**
 * file module for molecuel CMS
 */
var files = function() {

  var self = this;

  this.uploadDir = os.tmpdir();

  if(molecuel.config && molecuel.config.files && molecuel.config.files.uploaddir) {
    this.uploadDir = molecuel.config.files.uploaddir;
  }
  this.flow = flowlib(this.uploadDir);

  molecuel.on('mlcl::elements::registrations:pre',  function(module) {

    elements = module;

    // get native mongo driver
    var mongo = elements.database.database.mongo;
    var db = elements.database.database.connection.db;
    self.grid = new grid(mongo);
    self.grid.db = db;

    self.fileSchema =  {
      // Definition of the filename
      filename: { type: String, select: true, index:true },
      // Define the content type
      contentType: { type: String},
      // length data
      length: {type: Number, 'default': 0, form: {readonly: true}},
      chunkSize: {type: Number, 'default': 0, form: {readonly: true}},
      // upload date
      uploadDate: { type: Date, 'default': Date.now, form: {readonly: true}},

      // additional metadata
      metadata: {
        filename: {type: String}
      },
      md5: { type: String, trim: true }
    };

    var schemaDefinition = {
      schemaName: 'file',
      schema: self.fileSchema,
      options: {
        indexable: true,
        avoidTranslate: true,
        noStrict: true,
        collection: 'fs.files',
        subSchema: true
      }
    };
    elements.registerSchemaDefinition(schemaDefinition);
    elements.registerTypeHandler('file', self.download);
  });

  molecuel.on('mlcl::core::middlewareRegister:post', function(module, app) {
    //app.use(multer());
    // send init event
    molecuel.emit('mlcl::files::init:post', self);
  });

};

/* ************************************************************************
 SINGLETON CLASS DEFINITION
 ************************************************************************ */
var instance = null;

/**
 * Singleton getInstance definition
 * @return singleton class
 */
var getInstance = function () {
  if (instance === null) {
    instance = new files();
  }
  return instance;
};

/**
 * Upload handler for files
 * @param req
 * @param res
 * @param next
 */
files.prototype.upload = function(req, res) {
  if(req.files) {
    this.saveFile(req.files.files.path, req.files.files.originalname, null, function(err, result) {
      if(err) {
        return res.send(500, err);
      }
      res.send({files: [result]});
    });
  } else {
    res.send(500);
  }
};

/**
 * Upload handler for files with flow library
 * @param req
 * @param res
 */
files.prototype.uploadFlow = function(req, res) {
  var files = getInstance();
  files.flow.post(req, function(status, filename, original_filename, identifier) {
    if(status === 'done') {
      var fileuuid = uuid.v4();
      var tmpfile = files.uploadDir + '/' +fileuuid;
      var stream = fs.createWriteStream(files.uploadDir + '/' +fileuuid);
      files.flow.write(identifier, stream);

      stream.on('finish', function() {
        files.saveFile(tmpfile, original_filename, null, function(errSave, result) {
          if(errSave) {
            res.send(400, 'Error saving file');
          } else {
            files.flow.clean(identifier);
            fs.unlink(tmpfile, function(errDelete) {
              res.send(200, {
                  'file': result.result._id
              });
            });
          }
        });
      });
    } else {
      res.send(200);
    }
  });
};

/**
 * Upload handler for files with flow library
 * @param req
 * @param res
 * @todo check via gridfs if file is already available.
 */
files.prototype.uploadFlowStatus = function(req, res) {
//  res.send(404);
  var files = getInstance();
  files.flow.get(req, function(status, filename, original_filename, identifier) {
      if(status === 'found') {
        res.send(200);
      } else {
        res.send(404);
      }
  });
};

/**
 * Download handler for elements file type
 * @param req
 * @param res
 * @param next
 */
files.prototype.download = function download(req, res, next) {
  var files = getInstance();
  var grid = files.grid;
  var id = res.locals.data.main._id;
  if(req.method === 'GET') {
    grid.getFileStream(id, function(err, filestream) {
      if(!filestream) {
        next();
      } else {
        filestream.pipe(res);
      }
    });
  } else if(req.method === 'DELETE') {
    files.deleteFile(req, res, next);
  }
};

/**
 * Delete file middleware function
 * @param req
 * @param res
 * @param next
 */
files.prototype.deleteFile = function deleteFile(req, res) {
  var files = getInstance();
  var id = res.locals.data.main._id;
  files.deleteById(id, function(err) {
    if(err) {
      res.send(500);
    } else {
      res.send(200);
    }
  });
};

files.prototype.getFileInfo = function getFileInfo(req, res) {
  var files = getInstance();
  files.getInfoById(req.params.id, function(err, doc) {
    if(err) {
      res.send(500);
    } else if(doc){
      res.send(doc);
    } else {
      res.send(404);
    }
  });
};

files.prototype.deleteById = function deleteById(id, callback) {
  var files = getInstance();
  var grid = files.grid;
  grid.deleteFile(id, null, function(err) {
    if(err) {
      return callback(err);
    } else {
      if(elements && elements.elastic) {
        elements.elastic.delete('file', id, function() {
          return callback();
        });
      }
    }
  });
};

files.prototype.getInfoById = function(id, callback) {
  var files = getInstance();
  var file = elements.getElementType('file');
  file.findById(id, callback);
};

files.prototype.saveFile = function saveFile(path, name, options, callback) {
  var files = getInstance();

  /**
   * renderResult
   * renders the result from the db into a json object with delete url etc
   * @param res
   * @param dataset
   */
  var renderResult = function renderResult(dataset) {
    var result;
    if(dataset) {
      result = {
        name: dataset.filename,
        size: dataset.length,
        url: dataset.url,
        thumbnailUrl: dataset.url,
        deleteUrl: dataset.url,
        deleteType: 'DELETE',
        result: dataset
      };

      // file path are never relative
      if (result.url && result.url.charAt(0) !== '/') {
        result.url = '/'+result.url;
      }
    }
    return result;
  };

  files.grid.putUniqueFile(path, name, options, function(err, result) {
    var dbResult;
    var fileModel = elements.getModel('file');

    if(err && err.name === 'NotUnique') { //File already in gridfs
      dbResult = err.result;
      if(dbResult) {
        if(!dbResult.url || (options && options.url && options.url !== dbResult.url)) {
          fileModel.findById(dbResult._id, function(err, myobj) {
            // save it again to ensure url creation
            if(options && options.url) {
              myobj.url = options.url;
            }
            myobj.save(function(err, obj) {
              if(err) {
                return callback(err);
              }
              return callback(null, renderResult(obj));
            });
          });
        } else {
          return callback(null, renderResult(dbResult));
        }
      }
    } else if(err) {
      return callback(err);
    } else {
      dbResult = result;
      fileModel.findById(dbResult._id, function(err, myobj) {
        if(options && options.url) {
          myobj.url = options.url;
        }
        // save it again to ensure url creation
        myobj.save(function(err, obj) {
          if(err) {
            return callback(err);
          }
          return callback(null, renderResult(obj));
        });
      });
    }
  });
};

var init = function(mlcl) {
  molecuel = mlcl;
  return getInstance();
};

module.exports = init;
<|endoftext|>


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

var argv = process.argv.slice(2)
  , path = require("path")
  , Runner = require("../lib/tap-runner")

  , nopt = require("nopt")

  , knownOpts =
    { cover: [path, false]
    , "cover-dir": path
    , stderr: Boolean
    , stdout: Boolean
    , diag: Boolean
    , version: Boolean
    , tap: Boolean
    , timeout: Number
    , gc: Boolean
    , debug: Boolean
    , "debug-brk": Boolean
    , strict: Boolean
    , harmony: Boolean
    }

  , shorthands =
    // debugging 1: show stderr
    { d: ["--stderr"]
    // debugging 2: show stderr and tap
    , dd: ["--stderr", "--tap"]
    // debugging 3: show stderr, tap, AND always show diagnostics.
    , ddd: ["--stderr", "--tap", "--diag"]
    , "expose-gc": ["--gc"]
    , g: ["--gc"]
    , e: ["--stderr"]
    , t: ["--timeout"]
    , o: ["--tap"]
    , c: ["--cover"]
    , v: ["--version"]
    , "?": ["--help"]
    , h: ["--help"]
    }

  , defaults =
    { cover: "./lib"
    , "cover-dir": "./coverage"
    , stderr: process.env.TAP_STDERR || process.env.TAP
    , tap: process.env.TAP
    , diag: process.env.TAP_DIAG
    , timeout: +process.env.TAP_TIMEOUT || 30
    , gc: false
    , debug: false
    , "debug-brk": false
    , strict: false
    , harmony: false
    , version: false
    , help: false }

  , options = nopt(knownOpts, shorthands)

if (options.version) {
  console.log(require("../package.json").version)
  process.exit(0)
}

if (options.help) {
  console.log(function(){/*

Usage:
    tap <options> <files>

    Run the files as tap tests, parse the output, and report the results

Options:

    --stderr     Print standard error output of tests to standard error.
    --tap        Print raw tap output.
    --diag       Print diagnostic output for passed tests, as well as failed.
                 (Implies --tap)
    --gc         Expose the garbage collector to tests.
    --timeout    Maximum time to wait for a subtest, in seconds. Default: 30
    --debug      Pass the '--debug' flag to node for debugging
    --debug-brk  Pass the '--debug-brk' flag to node for debugging
    --strict     Enforce strict mode when running tests.
    --harmony    Enable harmony features for tests.
    --version    Print the version of node tap.
    --help       Print this help.

Please report bugs!  https://github.com/isaacs/node-tap/issues

*/}.toString().split(/\n/).slice(1, -1).join("\n"))
  process.exit(0)
}

Object.keys(defaults).forEach(function (k) {
  if (!options.hasOwnProperty(k)) options[k] = defaults[k]
})

// other tests that might rely on these
if (options.diag) process.env.TAP_DIAG = true
if (options.tap) process.env.TAP = true
if (options.timeout) process.env.TAP_TIMEOUT = options.timeout

var r = new Runner(options)
  , TapProducer = require("../lib/tap-producer")

if (options.tap || options.diag) {
  r.pipe(process.stdout)
} else {
  r.on("file", function (file, results, details) {
    var s = (details.ok ? "" : "not ") + "ok "+results.name
      , n = details.pass + "/" + details.testsTotal
      , dots = new Array(Math.max(1, 60 - s.length - n.length)).join(".")
    console.log("%s %s %s", s, dots, n)
    if (details.ok) {
      if (details.skip) {
        console.log("  skipped: %s", details.skipTotal)
      }
    } else {
      // console.error(details)
      console.log("    Command: %s", results.command)
      console.log("    " + TapProducer.encode(details.list)
                  .split(/\n/).join("\n    "))
    }
  })
  r.on("end", function () {
    //console.log(r)
    var s = "total"
      , n = r.results.pass + "/" + r.results.testsTotal
      , dots = new Array(60 - s.length - n.length).join(".")
      , ok = r.results.ok ? "ok" : "not ok"
    console.log("%s %s %s\n\n%s", s, dots, n, ok)
    if (r.doCoverage) {
      console.error( "\nCoverage: %s\n"
                   , path.resolve(r.coverageOutDir, "index.html") )
    }
  })
}

r.on("end", function () {
  process.exit(r.results.tests - r.results.pass)
})
<commit_msg>passthrough stderr by default<commit_after>#!/usr/bin/env node

var argv = process.argv.slice(2)
  , path = require("path")
  , Runner = require("../lib/tap-runner")

  , nopt = require("nopt")

  , knownOpts =
    { cover: [path, false]
    , "cover-dir": path
    , stderr: Boolean
    , stdout: Boolean
    , diag: Boolean
    , version: Boolean
    , tap: Boolean
    , timeout: Number
    , gc: Boolean
    , debug: Boolean
    , "debug-brk": Boolean
    , strict: Boolean
    , harmony: Boolean
    }

  , shorthands =
    // debugging 1: show stderr
    { d: ["--stderr"]
    // debugging 2: show stderr and tap
    , dd: ["--stderr", "--tap"]
    // debugging 3: show stderr, tap, AND always show diagnostics.
    , ddd: ["--stderr", "--tap", "--diag"]
    , "expose-gc": ["--gc"]
    , g: ["--gc"]
    , e: ["--stderr"]
    , t: ["--timeout"]
    , o: ["--tap"]
    , c: ["--cover"]
    , v: ["--version"]
    , "?": ["--help"]
    , h: ["--help"]
    }

  , defaults =
    { cover: "./lib"
    , "cover-dir": "./coverage"
    , stderr: true
    , tap: process.env.TAP
    , diag: process.env.TAP_DIAG
    , timeout: +process.env.TAP_TIMEOUT || 30
    , gc: false
    , debug: false
    , "debug-brk": false
    , strict: false
    , harmony: false
    , version: false
    , help: false }

  , options = nopt(knownOpts, shorthands)

if (options.version) {
  console.log(require("../package.json").version)
  process.exit(0)
}

if (options.help) {
  console.log(function(){/*

Usage:
    tap <options> <files>

    Run the files as tap tests, parse the output, and report the results

Options:

    --stderr     Print standard error output of tests to standard error.
    --tap        Print raw tap output.
    --diag       Print diagnostic output for passed tests, as well as failed.
                 (Implies --tap)
    --gc         Expose the garbage collector to tests.
    --timeout    Maximum time to wait for a subtest, in seconds. Default: 30
    --debug      Pass the '--debug' flag to node for debugging
    --debug-brk  Pass the '--debug-brk' flag to node for debugging
    --strict     Enforce strict mode when running tests.
    --harmony    Enable harmony features for tests.
    --version    Print the version of node tap.
    --help       Print this help.

Please report bugs!  https://github.com/isaacs/node-tap/issues

*/}.toString().split(/\n/).slice(1, -1).join("\n"))
  process.exit(0)
}

Object.keys(defaults).forEach(function (k) {
  if (!options.hasOwnProperty(k)) options[k] = defaults[k]
})

// other tests that might rely on these
if (options.diag) process.env.TAP_DIAG = true
if (options.tap) process.env.TAP = true
if (options.timeout) process.env.TAP_TIMEOUT = options.timeout

var r = new Runner(options)
  , TapProducer = require("../lib/tap-producer")

if (options.tap || options.diag) {
  r.pipe(process.stdout)
} else {
  r.on("file", function (file, results, details) {
    var s = (details.ok ? "" : "not ") + "ok "+results.name
      , n = details.pass + "/" + details.testsTotal
      , dots = new Array(Math.max(1, 60 - s.length - n.length)).join(".")
    console.log("%s %s %s", s, dots, n)
    if (details.ok) {
      if (details.skip) {
        console.log("  skipped: %s", details.skipTotal)
      }
    } else {
      // console.error(details)
      console.log("    Command: %s", results.command)
      console.log("    " + TapProducer.encode(details.list)
                  .split(/\n/).join("\n    "))
    }
  })
  r.on("end", function () {
    //console.log(r)
    var s = "total"
      , n = r.results.pass + "/" + r.results.testsTotal
      , dots = new Array(60 - s.length - n.length).join(".")
      , ok = r.results.ok ? "ok" : "not ok"
    console.log("%s %s %s\n\n%s", s, dots, n, ok)
    if (r.doCoverage) {
      console.error( "\nCoverage: %s\n"
                   , path.resolve(r.coverageOutDir, "index.html") )
    }
  })
}

r.on("end", function () {
  process.exit(r.results.tests - r.results.pass)
})
<|endoftext|>


<commit_before>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300

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 args = ['commit', outFile, '-m', 'Update character']
    for (var counter = 0; counter < length; counter++)
    {
      fs.writeSync(outFD, data.slice(counter, counter+1), 0, 1)
      sleep(Math.random() * max_sleep)
      child_process.execFileSync('/usr/bin/git', args)
    }
  })
}

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

process.on('exit', function () {<commit_msg>Update character<commit_after>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300

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 args = ['commit', outFile, '-m', 'Update character']
    for (var counter = 0; counter < length; counter++)
    {
      fs.writeSync(outFD, data.slice(counter, counter+1), 0, 1)
      sleep(Math.random() * max_sleep)
      child_process.execFileSync('/usr/bin/git', args)
    }
  })
}

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

process.on('exit', function () {
<|endoftext|>


<commit_before>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (<commit_msg>Update character<commit_after>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300

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


<commit_before>var Fleetctl = require('fleetctl');
var Etcd = require('node-etcd');
var fleetctl, etcd;
var async = require('async');
var _ = require('lodash');

var api = module.exports = {};

var ACTIVE_TIMEOUT = 300000; // 5 minutes
var WAIT_TO_DESTROY = 20000; // 10 seconds

api.deploy = function(unit, etcdKey, count, sidekick, endpoint) {

  var opts = {
    binary: process.env.FLEET_BINARY || '/usr/bin/fleetctl',
    endpoint: process.env.FLEET_ENDPOINT || endpoint || 'http://172.17.42.1:4001'
  }
  console.log('fleetctl options', opts);
  fleetctl = new Fleetctl(opts);
  etcd = new Etcd(
    process.env.ETCD_HOST || '172.17.42.1',
    process.env.ETCD_PORT || 4001
  );

  if (sidekick) {
    sidekick = unit + '-sk';
  }

  async.waterfall([
    function(callback) {
      return startThisService(unit, sidekick, count, callback);
    },
    function(callback) {
      return waitForActive(unit, count, callback);
    },
    function(callback) {
      return waitForEtcd(unit, etcdKey, count, callback);
    },
    function(callback) {
      console.log('Waiting for ', WAIT_TO_DESTROY, ' ms before destroying');
      setTimeout(callback, WAIT_TO_DESTROY);
    },
    function(callback) {
      return getUnitsToDestroy(unit, callback);
    },
    function(destroy, callback) {
      return destroyUnits(destroy, callback);
    }
    //getAllUnits,
  ], function(err, success) {
    if (err) {
      console.error(err);
    }
  })
};

/*
 1) Start new instances
 2) Wait for new instances to all be active
 3) Check etcd keys for all instances
 4) Destroy old instances, but leave templates
*/

function getUnitsToDestroy(unitName, callback) {
  var prefix = unitName.slice(0, unitName.lastIndexOf('-'));
  fleetctl.list_units(function(err, units) {
    if (err) {
      return callback(err);
    }
    var destroy = units.filter(function(unit) {
      if (unit.unit.indexOf(unitName) === -1 && unit.unit.indexOf(prefix) === 0) {
        return true;
      }
      return false;
    });
    return callback(null, destroy);
  });
}

function destroyUnits(units, callback) {
  units = _.pluck(units, 'unit');
  console.log('about to destroy old units', units);
  fleetctl.destroy(units, function(err) {
    if (err) {
      console.log('error destroying old units');
      return callback(err);
    }
    console.log('Old units successfully destroyed');
    return callback();
  });
}

// waits for all service to be active
function waitForActive(unit, count, callback) {
  var units = getUnits(unit, count);
  var allActive = false;
  var startTime = new Date().getTime();
  async.doWhilst(
    function getStatus(callback) {
      setTimeout(function() {
        var countActive = 0;
        fleetctl.list_units(function(err, fltUnits) {
          if (err) {
            return callback(err);
          }
          units.forEach(function(unit) {
            var item = _.find(fltUnits, function(u) {
              return u.unit === unit+'.service';
            })
            if (item && item.active === 'active' && item.sub === 'running') {
              countActive++;
            }
            else {
              console.log('Service not active', item.unit, item.active, item.sub);
            }
          });
          console.log(countActive, 'services are active of expected ', count);
          if (countActive === count) {
            allActive = true;
          }
          return callback();
        })
      }, 1000);
    },
    function checkStatus() {
      var now = new Date().getTime();
      if (now - startTime > ACTIVE_TIMEOUT) {
        return false;
      }
      return !allActive;
    },
    function() {
      if (!allActive) {
        return callback(new Error('Failed to start all units'));
      }
      else {
        console.log('All services have been started');
        return callback();
      }
    }
  );
}

function waitForEtcd(unit, etcdKey, count, callback) {
  var keys = getEtcdKeys(unit, etcdKey, count);
  var allActive = false;
  var startTime = new Date().getTime();
  console.log('etcd keys to check:', keys);
  async.doWhilst(
    function getStatus(callback) {
      setTimeout(function() {
        async.each(keys, function(key, callback) {
          console.log('checking: ', key);
          etcd.get(key, function(err, data) {
            if (err) {
              console.log('data not ready for ', key);
              return callback(err);
            }
            console.log('data exists for ', key);
            return callback();
          });
        }, function(err) {
          if (err) {
            return callback();
          }
          allActive = true;
          return callback();
        });
      }, 1000);
    },
    function checkStatus() {
      var now = new Date().getTime();
      if (now - startTime > ACTIVE_TIMEOUT) {
        return false;
      }
      return !allActive;
    },
    function() {
      if (!allActive) {
        return callback(new Error('Failed to start all units'));
      }
      else {
        console.log('All services have been started');
        return callback();
      }
    }
  );
}

function getEtcdKeys(unit, etcdKey, count) {
  var units = _.chain(_.range(1, count+1))
    .map(function(iter) {
      return etcdKey + unit + '-' + iter;
    })
    .value();
  return units;
}

function getUnits(unit, count, sidekick) {
  var units = _.chain(_.range(1, count+1))
    .map(function(iter) {
      return unit + '@' + iter;
    })
    .value();
  var sidekicks = _.chain(_.range(1, count+1))
    .map(function(iter) {
      return unit + '-sk@' + iter;
    })
    .value();
  if (sidekick) {
    units = units.concat(sidekicks);
  }
  return units;
}

function startThisService(unit, sidekick, count, callback) {
  var units = getUnits(unit, count, sidekick);
  console.log('Starting these units:', units);
  fleetctl.start(units, callback);
}

// function getAllUnits(service, environment, callback) {
//   fleetctl.list_units(function(err, units) {
//     if (err) {
//       return callback(err);
//     }
//     return callback(null, units);
//   })
// }
<commit_msg>Boost kill timeout to 2 minutes, as nginx-yodlr has 60 second update cycle<commit_after>var Fleetctl = require('fleetctl');
var Etcd = require('node-etcd');
var fleetctl, etcd;
var async = require('async');
var _ = require('lodash');

var api = module.exports = {};

var ACTIVE_TIMEOUT = 300000; // 5 minutes
var WAIT_TO_DESTROY = 120000; // 120 seconds (2 minutes)

api.deploy = function(unit, etcdKey, count, sidekick, endpoint) {

  var opts = {
    binary: process.env.FLEET_BINARY || '/usr/bin/fleetctl',
    endpoint: process.env.FLEET_ENDPOINT || endpoint || 'http://172.17.42.1:4001'
  }
  console.log('fleetctl options', opts);
  fleetctl = new Fleetctl(opts);
  etcd = new Etcd(
    process.env.ETCD_HOST || '172.17.42.1',
    process.env.ETCD_PORT || 4001
  );

  if (sidekick) {
    sidekick = unit + '-sk';
  }

  async.waterfall([
    function(callback) {
      return startThisService(unit, sidekick, count, callback);
    },
    function(callback) {
      return waitForActive(unit, count, callback);
    },
    function(callback) {
      return waitForEtcd(unit, etcdKey, count, callback);
    },
    function(callback) {
      console.log('Waiting for ', WAIT_TO_DESTROY, ' ms before destroying');
      setTimeout(callback, WAIT_TO_DESTROY);
    },
    function(callback) {
      return getUnitsToDestroy(unit, callback);
    },
    function(destroy, callback) {
      return destroyUnits(destroy, callback);
    }
    //getAllUnits,
  ], function(err, success) {
    if (err) {
      console.error(err);
    }
  })
};

/*
 1) Start new instances
 2) Wait for new instances to all be active
 3) Check etcd keys for all instances
 4) Destroy old instances, but leave templates
*/

function getUnitsToDestroy(unitName, callback) {
  var prefix = unitName.slice(0, unitName.lastIndexOf('-'));
  fleetctl.list_units(function(err, units) {
    if (err) {
      return callback(err);
    }
    var destroy = units.filter(function(unit) {
      if (unit.unit.indexOf(unitName) === -1 && unit.unit.indexOf(prefix) === 0) {
        return true;
      }
      return false;
    });
    return callback(null, destroy);
  });
}

function destroyUnits(units, callback) {
  units = _.pluck(units, 'unit');
  console.log('about to destroy old units', units);
  fleetctl.destroy(units, function(err) {
    if (err) {
      console.log('error destroying old units');
      return callback(err);
    }
    console.log('Old units successfully destroyed');
    return callback();
  });
}

// waits for all service to be active
function waitForActive(unit, count, callback) {
  var units = getUnits(unit, count);
  var allActive = false;
  var startTime = new Date().getTime();
  async.doWhilst(
    function getStatus(callback) {
      setTimeout(function() {
        var countActive = 0;
        fleetctl.list_units(function(err, fltUnits) {
          if (err) {
            return callback(err);
          }
          units.forEach(function(unit) {
            var item = _.find(fltUnits, function(u) {
              return u.unit === unit+'.service';
            })
            if (item && item.active === 'active' && item.sub === 'running') {
              countActive++;
            }
            else {
              console.log('Service not active', item.unit, item.active, item.sub);
            }
          });
          console.log(countActive, 'services are active of expected ', count);
          if (countActive === count) {
            allActive = true;
          }
          return callback();
        })
      }, 1000);
    },
    function checkStatus() {
      var now = new Date().getTime();
      if (now - startTime > ACTIVE_TIMEOUT) {
        return false;
      }
      return !allActive;
    },
    function() {
      if (!allActive) {
        return callback(new Error('Failed to start all units'));
      }
      else {
        console.log('All services have been started');
        return callback();
      }
    }
  );
}

function waitForEtcd(unit, etcdKey, count, callback) {
  var keys = getEtcdKeys(unit, etcdKey, count);
  var allActive = false;
  var startTime = new Date().getTime();
  console.log('etcd keys to check:', keys);
  async.doWhilst(
    function getStatus(callback) {
      setTimeout(function() {
        async.each(keys, function(key, callback) {
          console.log('checking: ', key);
          etcd.get(key, function(err, data) {
            if (err) {
              console.log('data not ready for ', key);
              return callback(err);
            }
            console.log('data exists for ', key);
            return callback();
          });
        }, function(err) {
          if (err) {
            return callback();
          }
          allActive = true;
          return callback();
        });
      }, 1000);
    },
    function checkStatus() {
      var now = new Date().getTime();
      if (now - startTime > ACTIVE_TIMEOUT) {
        return false;
      }
      return !allActive;
    },
    function() {
      if (!allActive) {
        return callback(new Error('Failed to start all units'));
      }
      else {
        console.log('All services have been started');
        return callback();
      }
    }
  );
}

function getEtcdKeys(unit, etcdKey, count) {
  var units = _.chain(_.range(1, count+1))
    .map(function(iter) {
      return etcdKey + unit + '-' + iter;
    })
    .value();
  return units;
}

function getUnits(unit, count, sidekick) {
  var units = _.chain(_.range(1, count+1))
    .map(function(iter) {
      return unit + '@' + iter;
    })
    .value();
  var sidekicks = _.chain(_.range(1, count+1))
    .map(function(iter) {
      return unit + '-sk@' + iter;
    })
    .value();
  if (sidekick) {
    units = units.concat(sidekicks);
  }
  return units;
}

function startThisService(unit, sidekick, count, callback) {
  var units = getUnits(unit, count, sidekick);
  console.log('Starting these units:', units);
  fleetctl.start(units, callback);
}

// function getAllUnits(service, environment, callback) {
//   fleetctl.list_units(function(err, units) {
//     if (err) {
//       return callback(err);
//     }
//     return callback(null, units);
//   })
// }
<|endoftext|>