<commit_before>var fs = require('fs');
var path = require('path');
var mkdirp = require('mkdirp');
var commander = require('commander');
var continuation = require('../continuation');
var meta = require('../package.json');

var options = {
  explicit: false,
  sourceMap: true,
  verbose: false,
  cache: false,
  force: false,
  indent: '  ',
};

var cacheDefaultPath = '/tmp/continuation';

var initialize = function () {
  commander.version(meta.version);
  commander.usage('[options] <file.js/file.coffee/file.ls> [arguments]');
  commander.option('-p, --print', 'compile script file and print it');
  commander.option('-o, --output <filename>', 'compile script file and save as <filename>');
  commander.option('-e, --explicit', 'compile only if "use continuation" is explicitly declared');
  commander.option('-c, --cache [directory]', 'run and cache compiled sources to [directory], by default [directory] is ' + cacheDefaultPath);
  commander.option('-v, --verbose', 'print verbosal information to stderr');
  commander.parse(process.argv);
};

var main = exports.main = function () {
  initialize();

  var filename = commander.args[0];
  if (commander.explicit) {
    options.explicit = true;
  }
  if (commander.cache) {
    options.cache = commander.cache;
    if (options.cache === true) {
      options.cache = cacheDefaultPath;
    }
  }
  if (commander.verbose) {
    options.verbose = true;
  }

  try {
    if (!filename) {
      throw ('You should specify a script file.');
    }
    filename = fs.realpathSync(filename);
  } catch (e) {
    console.error(e.toString());
    console.error(commander.helpInformation());
    process.exit(-1);
  }
  var code = compile(filename);

  var print = false;
  if (commander.print)
    print = true;
  if (commander.output)
    print = true;

  if (print) {
    outputCode(filename, code);
  } else {
    runCode(code, filename);
  }
};

var outputCode = function (originalFilename, code) {
  if (commander.output) {
    var filename = commander.output;
    if (options.sourceMap) {
      var sourceMapFilename = filename + '.map';
      var sourceMap = continuation.getSourceMap(
        path.basename(filename),
        [path.basename(originalFilename)]
      );
      code += '\n//@ sourceMappingURL=' + path.basename(sourceMapFilename);
      fs.writeFileSync(sourceMapFilename, sourceMap);
    }
    fs.writeFileSync(filename, code);
  } else {
    console.log(code);
  }
};

var runCode = function (code, filename) {
  //Set current module information
  var mainModule = require.main;
  mainModule.filename = filename;
  mainModule.moduleCache = {};
  mainModule.children = [];
  mainModule.paths = calculatePaths(filename);

  //Register require handler
  require.extensions['.js'] = execute;
  require.extensions['.coffee'] = execute;
  require.extensions['.ls'] = execute;

  //Generate program arguments
  var args = commander.args.slice(1);
  process.argv = [process.argv[0], filename].concat(args);

  //Run
  mainModule._compile(code, filename);
};

var compile = function (filename) {

  if (options.verbose) {
    console.error('Load ' + filename);
  }

  if (options.cache) {
    code = readCache(filename);
    if (code !== null) {
      if (options.verbose) {
        console.error('Cache hit');
      }
      return code;
    }
  }

  var code = fs.readFileSync(filename, 'utf-8');

  try {
    var ext = path.extname(filename);
    if (ext === '.coffee') {
      //Coffee-script support
      coffeescript = require('coffee-script');
      code = coffeescript.compile(code);
    } else if (ext === '.ls') {
      //LiveScript support
      var livescript = require('LiveScript');
      code = livescript.compile(code);
    }
    code = continuation.compile(code, options);
  } catch (err) {
    console.error('In file', filename);
    console.error(err.stack);
    process.exit(-1);
  }

  if (options.cache) {
    if (options.verbose) {
      console.error('Cache updated');
    }
    writeCache(filename, code);
  }

  return code;
};

var execute = function (module, filename) {
  global.currentFilename = filename;
  var code = compile(filename);
  module._compile(code, filename);
};

var calculatePaths = function (filename) {
  var paths = [];
  var pathSec = path.dirname(filename).split(path.sep);
  while (pathSec.length > 0) {
    var modulePath = pathSec.join(path.sep);
    modulePath += path.sep + 'node_modules';
    paths.push(modulePath);
    pathSec.pop();
  }
  return paths;
};

var getCachedFilePath = function (filename) {
  return path.join(options.cache, filename + '_c.js');
};

var readCache = function (filename) {
  var cachedFilePath = getCachedFilePath(filename);
  var exists = fs.existsSync(cachedFilePath);
  if (!exists) {
    return null;
  }

  var stat = fs.lstatSync(cachedFilePath);
  var cacheMtime = stat.mtime;
  var stat = fs.lstatSync(filename);
  var sourceMtime = stat.mtime;

  if (sourceMtime > cacheMtime) {
    return null;
  }

  return fs.readFileSync(cachedFilePath, 'utf-8');
};

var writeCache = function (filename, code) {
  var cachedFilePath = getCachedFilePath(filename);
  mkdirp.sync(path.dirname(cachedFilePath), 0777);
  fs.writeFileSync(cachedFilePath, code);
};
<commit_msg>Fix for Windows style path<commit_after>var fs = require('fs');
var path = require('path');
var mkdirp = require('mkdirp');
var commander = require('commander');
var continuation = require('../continuation');
var meta = require('../package.json');

var options = {
  explicit: false,
  sourceMap: true,
  verbose: false,
  cache: false,
  force: false,
  indent: '  ',
};

var cacheDefaultPath = '/tmp/continuation';

var initialize = function () {
  commander.version(meta.version);
  commander.usage('[options] <file.js/file.coffee/file.ls> [arguments]');
  commander.option('-p, --print', 'compile script file and print it');
  commander.option('-o, --output <filename>', 'compile script file and save as <filename>');
  commander.option('-e, --explicit', 'compile only if "use continuation" is explicitly declared');
  commander.option('-c, --cache [directory]', 'run and cache compiled sources to [directory], by default [directory] is ' + cacheDefaultPath);
  commander.option('-v, --verbose', 'print verbosal information to stderr');
  commander.parse(process.argv);
};

var main = exports.main = function () {
  initialize();

  var filename = commander.args[0];
  if (commander.explicit) {
    options.explicit = true;
  }
  if (commander.cache) {
    options.cache = commander.cache;
    if (options.cache === true) {
      options.cache = cacheDefaultPath;
    }
  }
  if (commander.verbose) {
    options.verbose = true;
  }

  try {
    if (!filename) {
      throw ('You should specify a script file.');
    }
    filename = fs.realpathSync(filename);
  } catch (e) {
    console.error(e.toString());
    console.error(commander.helpInformation());
    process.exit(-1);
  }
  var code = compile(filename);

  var print = false;
  if (commander.print)
    print = true;
  if (commander.output)
    print = true;

  if (print) {
    outputCode(filename, code);
  } else {
    runCode(code, filename);
  }
};

var outputCode = function (originalFilename, code) {
  if (commander.output) {
    var filename = commander.output;
    if (options.sourceMap) {
      var sourceMapFilename = filename + '.map';
      var sourceMap = continuation.getSourceMap(
        path.basename(filename),
        [path.basename(originalFilename)]
      );
      code += '\n//@ sourceMappingURL=' + path.basename(sourceMapFilename);
      fs.writeFileSync(sourceMapFilename, sourceMap);
    }
    fs.writeFileSync(filename, code);
  } else {
    console.log(code);
  }
};

var runCode = function (code, filename) {
  //Set current module information
  var mainModule = require.main;
  mainModule.filename = filename;
  mainModule.moduleCache = {};
  mainModule.children = [];
  mainModule.paths = calculatePaths(filename);

  //Register require handler
  require.extensions['.js'] = execute;
  require.extensions['.coffee'] = execute;
  require.extensions['.ls'] = execute;

  //Generate program arguments
  var args = commander.args.slice(1);
  process.argv = [process.argv[0], filename].concat(args);

  //Run
  mainModule._compile(code, filename);
};

var compile = function (filename) {

  if (options.verbose) {
    console.error('Load ' + filename);
  }

  if (options.cache) {
    code = readCache(filename);
    if (code !== null) {
      if (options.verbose) {
        console.error('Cache hit');
      }
      return code;
    }
  }

  var code = fs.readFileSync(filename, 'utf-8');

  try {
    var ext = path.extname(filename);
    if (ext === '.coffee') {
      //Coffee-script support
      coffeescript = require('coffee-script');
      code = coffeescript.compile(code);
    } else if (ext === '.ls') {
      //LiveScript support
      var livescript = require('LiveScript');
      code = livescript.compile(code);
    }
    code = continuation.compile(code, options);
  } catch (err) {
    console.error('In file', filename);
    console.error(err.stack);
    process.exit(-1);
  }

  if (options.cache) {
    if (options.verbose) {
      console.error('Cache updated');
    }
    writeCache(filename, code);
  }

  return code;
};

var execute = function (module, filename) {
  global.currentFilename = filename;
  var code = compile(filename);
  module._compile(code, filename);
};

var calculatePaths = function (filename) {
  var paths = [];
  var pathSec = path.dirname(filename).split(path.sep);
  while (pathSec.length > 0) {
    var modulePath = pathSec.join(path.sep);
    modulePath += path.sep + 'node_modules';
    paths.push(modulePath);
    pathSec.pop();
  }
  return paths;
};

var getCachedFilePath = function (filename) {
  return path.join(options.cache, filename + '_c.js');
};

var readCache = function (filename) {
  var cachedFilePath = getCachedFilePath(filename);
  var exists = fs.existsSync(cachedFilePath);
  if (!exists) {
    return null;
  }

  var stat = fs.lstatSync(cachedFilePath);
  var cacheMtime = stat.mtime;
  var stat = fs.lstatSync(filename);
  var sourceMtime = stat.mtime;

  if (sourceMtime > cacheMtime) {
    return null;
  }

  return fs.readFileSync(cachedFilePath, 'utf-8');
};

var writeCache = function (filename, code) {
  var cachedFilePath = getCachedFilePath(filename);

  //Fix for Windows style path
  cachedFilePath = cachedFilePath.replace(':', '');

  mkdirp.sync(path.dirname(cachedFilePath), 0777);
  fs.writeFileSync(cachedFilePath, code);
};
<|endoftext|>


<commit_before>'use strict';

var fs = require('fs');
var execSync = require('child_process').execSync;
var semver = require('semver');
var inquirer = require('inquirer');

module.exports = createNpmBump('origin', 'master');
module.exports.custom = createNpmBump;

function createNpmBump(remote, branch) {
    remote = remote || 'origin';
    branch = branch || 'master';

    function UsageError(message) {
        this.name = 'UsageError';
        this.message = message;
    }
    UsageError.prototype = Object.create(Error.prototype);

    return function npmBump(kind) {

        if (['major', 'minor', 'patch'].indexOf(kind) === -1) {
            throw new UsageError('USAGE: npm-bump major|minor|patch');
        }

        ensureCleanBranch();
        doBump();

        function getHashFor(branchName) {
            return run('git rev-parse --verify ' + branchName).trim();
        }

        function ensureCleanBranch() {
            if (getHashFor('HEAD') !== getHashFor(branch)) {
                throw new UsageError('You need to be on the "' + branch + '" branch to run this script');
            }
            if (getHashFor(branch) !== getHashFor(remote + '/' + branch)) {
                throw new UsageError('You need to push your changes first');
            }
            if (run('git status -s').length) {
                throw new UsageError('You have uncommited changes! Commit them before running this script');
            }
        }

        function run(command) {
            return execSync(command, {encoding: 'utf8'});
        }

        function writePackageJson(configObject) {
            fs.writeFileSync('./package.json', JSON.stringify(configObject, null, 2) + '\n');
        }

        function doBump() {
            var packageJson = require(process.cwd() + '/package.json');
            var oldVersion = packageJson.version;

            // Tag a new release
            var newStableVersion = packageJson.version = semver.inc(oldVersion, kind);
            writePackageJson(packageJson);
            console.log('Version bumped from ' + oldVersion + ' to ' + packageJson.version);
            run('git add package.json');
            run('git commit -m "Tag ' + packageJson.version + '"');
            run('git tag ' + packageJson.version);

            // Bump to a new pre-release version
            packageJson.version = semver.inc(packageJson.version, 'patch') + '-pre';
            writePackageJson(packageJson);
            run('git add package.json');
            run('git commit -m "Bump to ' + packageJson.version + '"');

            // All public changes are done here.
            inquirer.prompt([{
                name: 'shouldProceed',
                type: 'confirm',
                message: 'Are you sure you want to publish the new version?',
            }], function (answers) {
                if (answers.shouldProceed) {
                    run('git checkout ' + newStableVersion + ' 2>/dev/null');
                    run('npm publish');
                    run('git checkout ' + branch + ' 2>/dev/null');
                    run('git push');
                    run('git push ' + newStableVersion);
                } else {
                    run('git tag -d ' + newStableVersion);
                    run('git reset --hard ' + remote + '/' + branch);
                    console.log('Changes reverted');
                }
            });
        }
    };
}
<commit_msg>A little refactor<commit_after>'use strict';

var fs = require('fs');
var execSync = require('child_process').execSync;
var semver = require('semver');
var inquirer = require('inquirer');

module.exports = createNpmBump('origin', 'master');
module.exports.custom = createNpmBump;

function createNpmBump(remote, branch) {
    remote = remote || 'origin';
    branch = branch || 'master';

    function UsageError(message) {
        this.name = 'UsageError';
        this.message = message;
    }
    UsageError.prototype = Object.create(Error.prototype);

    return function npmBump(kind) {

        if (['major', 'minor', 'patch'].indexOf(kind) === -1) {
            throw new UsageError('USAGE: npm-bump major|minor|patch');
        }

        ensureCleanBranch();
        doBump();

        function getHashFor(branchName) {
            return run('git rev-parse --verify ' + branchName).trim();
        }

        function ensureCleanBranch() {
            if (getHashFor('HEAD') !== getHashFor(branch)) {
                throw new UsageError('You need to be on the "' + branch + '" branch to run this script');
            }
            if (getHashFor(branch) !== getHashFor(remote + '/' + branch)) {
                throw new UsageError('You need to push your changes first');
            }
            if (run('git status -s').length) {
                throw new UsageError('You have uncommited changes! Commit them before running this script');
            }
        }

        function run(command) {
            return execSync(command, {encoding: 'utf8'});
        }

        function writePackageJson(configObject) {
            fs.writeFileSync('./package.json', JSON.stringify(configObject, null, 2) + '\n');
        }

        function doBump() {
            var packageJson = require(process.cwd() + '/package.json');
            var oldVersion = packageJson.version;

            // Tag a new release
            var newStableVersion = packageJson.version = semver.inc(oldVersion, kind);
            writePackageJson(packageJson);
            console.log('Version bumped from ' + oldVersion + ' to ' + newStableVersion);
            run('git add package.json');
            run('git commit -m "Tag ' + newStableVersion + '"');
            run('git tag ' + newStableVersion);

            // Bump to a new pre-release version
            packageJson.version = semver.inc(packageJson.version, 'patch') + '-pre';
            writePackageJson(packageJson);
            run('git add package.json');
            run('git commit -m "Bump to ' + packageJson.version + '"');

            // All public changes are done here.
            inquirer.prompt([{
                name: 'shouldProceed',
                type: 'confirm',
                message: 'Are you sure you want to publish the new version?',
            }], function (answers) {
                if (answers.shouldProceed) {
                    run('git checkout ' + newStableVersion + ' 2>/dev/null');
                    run('npm publish');
                    run('git checkout ' + branch + ' 2>/dev/null');
                    run('git push');
                    run('git push ' + newStableVersion);
                } else {
                    run('git tag -d ' + newStableVersion);
                    run('git reset --hard ' + remote + '/' + branch);
                    console.log('Changes reverted');
                }
            });
        }
    };
}
<|endoftext|>


<commit_before>var tools = require('./tools')

var cli = (function () {

  var _commands = {}
  var _version = ''
  var _self = process.argv[0]

  return {
    register: function (mod, cmd, args, desc, func) {
      if (!mod || !cmd || !desc || !func)
        return tools.error('Missing argument(s) in cli.register')
      if (!_commands[mod])
        _commands[mod] = {}
      _commands[mod][cmd] = {args: args, desc: desc, exec: func}
    },

    version: function (ver) {
      _version = ver
    },

    parse: function () {
      var args = process.argv
      if (args[0] === 'node') args = process.argv.splice(1)
      if (args.length < 2 ||
        args[1] === 'help' ||
        args[1] === '-h' ||
        args[1] === '--help') return cli.help(args[2])
      if (args[1] === '-v' ||
        args[1] === '--version') return console.log('Digio v' + _version)

      var mod = args[1]
      var com = args[2]

      if (!_commands[mod]) return tools.error('No such module "' + mod + '"')
      if (args.length === 2) return cli.help(mod)
      if (_commands[mod] && !_commands[mod][com])
        return tools.error('No such command "' + mod + ' ' + com + '"')

      if (_commands[mod][com].args.length > args.length - 3)
        return tools.error('Insufficient arguments given')

      var params = args.splice(3)

      _commands[mod][com].exec.apply(this, params)
    },

    help: function (mod) {
      if (mod && !_commands[mod]) return tools.error('No such module "' + mod + '"')
      console.log('Digio v' + _version + '\n')

      if (mod) console.log('  Usage: ' + _self + ' '+mod+' <command> [args]\n')
      else console.log('  Usage: ' + _self + ' <module> <command> [args]\n')

      if (mod) {
        console.log('  Commands:\n')
        var _coms = Object.getOwnPropertyNames(_commands[mod]).sort()
        _coms.forEach(function (c) {
          console.log('  - ' + c + ' ' + _commands[mod][c].args.join(' ') + ' ' +
            '(' + _commands[mod][c].desc + ')')
        })
        console.log('')
      }
      else {
        console.log('  Modules:\n')
        var _modules = Object.getOwnPropertyNames(_commands).sort()
        _modules.forEach(function (m) {
          console.log('  - ' + m)
        })
        console.log('')
      }
      if (!mod)
        console.log('Type "' + _self + ' help <module>" for available commands')
    }
  }
})()

module.exports = cli
<commit_msg>Update splice method - working only on arguments of called program<commit_after>var tools = require('./tools')

var cli = (function () {

  var _commands = {}
  var _version = ''
  var _self = process.argv[0]

  return {
    register: function (mod, cmd, args, desc, func) {
      if (!mod || !cmd || !desc || !func)
        return tools.error('Missing argument(s) in cli.register')
      if (!_commands[mod])
        _commands[mod] = {}
      _commands[mod][cmd] = {args: args, desc: desc, exec: func}
    },

    version: function (ver) {
      _version = ver
    },

    parse: function () {
      var args = process.argv.splice(2)

      if (args.length < 1 ||
        args[0] === 'help' ||
        args[0] === '-h' ||
        args[0] === '--help') return cli.help(args[1])

      if (args[0] === '-v' || args[0] === '--version')
        return console.log('Digio v' + _version)

      var mod = args[0]
      var com = args[1]

      if (!_commands[mod]) return tools.error('No such module "' + mod + '"')
      if (args.length === 1) return cli.help(mod)
      if (_commands[mod] && !_commands[mod][com])
        return tools.error('No such command "' + mod + ' ' + com + '"')

      if (_commands[mod][com].args.length > args.length - 2)
        return tools.error('Insufficient arguments given')

      var params = args.splice(2)

      _commands[mod][com].exec.apply(this, params)
    },

    help: function (mod) {
      if (mod && !_commands[mod]) return tools.error('No such module "' + mod + '"')
      console.log('Digio v' + _version + '\n')

      if (mod) console.log('  Usage: ' + _self + ' '+mod+' <command> [args]\n')
      else console.log('  Usage: ' + _self + ' <module> <command> [args]\n')

      if (mod) {
        console.log('  Commands:\n')
        var _coms = Object.getOwnPropertyNames(_commands[mod]).sort()
        _coms.forEach(function (c) {
          console.log('  - ' + c + ' ' + _commands[mod][c].args.join(' ') + ' ' +
            '(' + _commands[mod][c].desc + ')')
        })
        console.log('')
      }
      else {
        console.log('  Modules:\n')
        var _modules = Object.getOwnPropertyNames(_commands).sort()
        _modules.forEach(function (m) {
          console.log('  - ' + m)
        })
        console.log('')
      }
      if (!mod)
        console.log('Type "' + _self + ' help <module>" for available commands')
    }
  }
})()

module.exports = cli
<|endoftext|>


<commit_before>var fs = require('fs');
var program = require('commander');
var Vow = require('vow');

program
    .version(require('../package.json').version)
    .usage('[options] <file ...>')
    .option('-c, --config [path]', 'configuration file path')
    .parse(process.argv);

var Checker = require('./checker');
var checker = new Checker();

var configPath = program.config || (process.cwd() + '/.jscs.json');

if (fs.existsSync(configPath)) {
    checker.registerDefaultRules();
    checker.configure(require(configPath));
    if (program.args.length > 0) {
        Vow.all(program.args.map(function(path) {
            return checker.checkPath(path);
        })).then(function (results) {
            var errorsCollection = [].concat.apply([], results);
            var errorCount = 0;
            errorsCollection.forEach(function (errors) {
                if (!errors.isEmpty()) {
                    errors.getErrorList().forEach(function(error) {
                        errorCount++;
                        console.log(
                            errors.explainError(error, true) + '\n'
                        );
                    });
                }
            });
            if (errorCount) {
                console.log('\n' + errorCount + ' code style errors found.');
                process.exit(1);
            } else {
                console.log('No code style errors found.');
            }
        }).fail(function(e) {
            console.log(e.stack);
            process.exit(1);
        });
    } else {
        console.log('No input files specified. Try option --help for usage information.');
        process.exit(0);
    }
} else {
    console.log('Configuration file ' + configPath + ' was not found.');
    process.exit(1);
}

<commit_msg>Update cli.js<commit_after>/**
 * Command line implementation for JSCS.
 *
 * Common usage case is:
 *
 * ./node_modules/.bin/jscs file1 dir1 file2 dir2
 */
var fs = require('fs');
var program = require('commander');
var Vow = require('vow');

program
    .version(require('../package.json').version)
    .usage('[options] <file ...>')
    .option('-c, --config [path]', 'configuration file path')
    .parse(process.argv);

var Checker = require('./checker');
var checker = new Checker();

var configPath = program.config || (process.cwd() + '/.jscs.json');

/**
 * Trying to load config.
 * Custom config path can be specified using '-c' option.
 */
if (fs.existsSync(configPath)) {
    /**
     * Using default rule set.
     * There is no support for custom rule sets yet.
     */
    checker.registerDefaultRules();
    checker.configure(require(configPath));
    if (program.args.length > 0) {
        /**
         * Processing specified files and dirs.
         */
        Vow.all(program.args.map(function(path) {
            return checker.checkPath(path);
        })).then(function (results) {
            var errorsCollection = [].concat.apply([], results);
            var errorCount = 0;
            /**
             * Formatting every error set.
             */
            errorsCollection.forEach(function (errors) {
                if (!errors.isEmpty()) {
                    /**
                     * Formatting every single error.
                     */
                    errors.getErrorList().forEach(function(error) {
                        errorCount++;
                        console.log(
                            errors.explainError(error, true) + '\n'
                        );
                    });
                }
            });
            if (errorCount) {
                /**
                 * Printing summary.
                 */
                console.log('\n' + errorCount + ' code style errors found.');
                process.exit(1);
            } else {
                console.log('No code style errors found.');
            }
        }).fail(function(e) {
            console.log(e.stack);
            /**
             * Quitting with 1 error code.
             */
            process.exit(1);
        });
    } else {
        console.log('No input files specified. Try option --help for usage information.');
        process.exit(0);
    }
} else {
    console.log('Configuration file ' + configPath + ' was not found.');
    /**
     * Quitting with 1 error code.
     */
    process.exit(1);
}

<|endoftext|>


<commit_before>/* global Opal */
'use strict'

const yargs = require('yargs')
const asciidoctor = require('asciidoctor.js')()

function convertOptions (argv) {
  const backend = argv['backend']
  const doctype = argv['doctype']
  const safeMode = argv['safe-mode']
  const noHeaderFooter = argv['no-header-footer']
  const sectionNumbers = argv['section-numbers']
  const baseDir = argv['base-dir']
  const destinationDir = argv['destination-dir']
  const outFile = argv['out-file']
  const quiet = argv['quiet']
  const verbose = argv['verbose']
  const timings = argv['timings']
  const trace = argv['trace']
  const requireLib = argv['require']
  if (verbose) {
    console.log('require ' + requireLib)
    console.log('backend ' + backend)
    console.log('doctype ' + doctype)
    console.log('header-footer ' + !noHeaderFooter)
    console.log('section-numbers ' + sectionNumbers)
    console.log('quiet ' + quiet)
    console.log('verbose ' + verbose)
    console.log('timings ' + timings)
    console.log('trace ' + trace)
    console.log('base-dir ' + baseDir)
    console.log('destination-dir ' + destinationDir)
  }
  if (requireLib) {
    require(requireLib)
  }
  const verboseMode = quiet ? 0 : verbose ? 2 : 1
  const attributes = []
  if (noHeaderFooter) {
    attributes.push('showtitle')
  }
  if (sectionNumbers) {
    attributes.push('sectnums')
  }
  const cliAttributes = argv['attribute']
  if (cliAttributes) {
    attributes.push(...cliAttributes)
  }
  if (verbose) {
    console.log('verbose-mode ' + verboseMode)
    console.log('attributes ' + attributes)
  }
  const options = {
    backend: backend,
    doctype: doctype,
    safe: safeMode,
    header_footer: !noHeaderFooter,
    to_file: outFile,
    verbose: verboseMode,
    timings: timings,
    trace: trace
  }
  if (baseDir != null) {
    options.base_dir = baseDir
  }
  if (destinationDir != null) {
    options.to_dir = destinationDir
  }
  if (outFile === '') {
    options.to_file = '-'
  } else {
    options.mkdirs = true
  }
  options.attributes = attributes
  if (verbose) {
    console.log('options ' + JSON.stringify(options))
  }
  if (options.to_file === '-') {
    options.to_file = Opal.gvars.stdout
  }
  return options
}

function argsParser () {
  return yargs
    .detectLocale(false)
    .wrap(Math.min(120, yargs.terminalWidth()))
    .command('$0 [files...]', '', function (yargs) {
      return yargs
        .option('backend', {
          alias: 'b',
          default: 'html5',
          describe: 'set output format backend',
          type: 'string'
        })
        .option('doctype', {
          alias: 'd',
          default: 'article',
          describe: 'document type to use when converting document',
          choices: ['article', 'book', 'manpage', 'inline']
        })
        .option('out-file', {
          alias: 'o',
          describe: 'output file (default: based on path of input file) use \'\' to output to STDOUT',
          type: 'string'
        })
        .option('safe-mode', {
          alias: 'S',
          default: 'unsafe',
          describe: 'set safe mode level explicitly, disables potentially dangerous macros in source files, such as include::[]',
          choices: ['unsafe', 'safe', 'server', 'secure']
        })
        .option('no-header-footer', {
          alias: 's',
          default: false,
          describe: 'suppress output of header and footer',
          type: 'boolean'
        })
        .option('section-numbers', {
          alias: 'n',
          default: false,
          describe: 'auto-number section titles in the HTML backend disabled by default',
          type: 'boolean'
        })
        .option('base-dir', {
          // QUESTION: should we check that the directory exists ? coerce to a directory ?
          alias: 'B',
          describe: 'base directory containing the document and resources (default: directory of source file)',
          type: 'string'
        })
        .option('destination-dir', {
          // QUESTION: should we check that the directory exists ? coerce to a directory ?
          alias: 'D',
          describe: 'destination output directory (default: directory of source file)',
          type: 'string'
        })
        .option('quiet', {
          alias: 'q',
          default: false,
          describe: 'suppress warnings',
          type: 'boolean'
        })
        .option('trace', {
          default: false,
          describe: 'include backtrace information on errors',
          type: 'boolean'
        })
        .option('verbose', {
          alias: 'v',
          default: false,
          describe: 'enable verbose mode',
          type: 'boolean'
        })
        .option('timings', {
          alias: 't',
          default: false,
          describe: 'enable timings mode',
          type: 'boolean'
        })
        .option('attribute', {
          alias: 'a',
          array: true,
          describe: 'a document attribute to set in the form of key, key! or key=value pair',
          type: 'string'
        })
        .option('require', {
          alias: 'r',
          array: true,
          describe: 'require the specified library before executing the processor, using the standard Node require',
          type: 'string'
        })
        .option('version', {
          alias: 'V',
          default: false,
          describe: 'display the version and runtime environment (or -v if no other flags or arguments)',
          type: 'boolean'
        })
    })
    .help()
}

function run (argv) {
  const verbose = argv['verbose']
  const version = argv['version']
  const files = argv['files']
  const options = convertOptions(argv)
  if (version || (verbose && files && files.length === 0)) {
    console.log(`Asciidoctor ${asciidoctor.getCoreVersion()} [http://asciidoctor.org]`)
    const releaseName = process.release ? process.release.name : 'node'
    console.log(`Runtime Environment (${releaseName} ${process.version} on ${process.platform})`)
  } else if (files && files.length > 0) {
    files.forEach(function (file) {
      if (verbose) {
        console.log(`converting file ${file}`)
      }
      if (argv['timings']) {
        const timings = asciidoctor.Timings.$new()
        const instanceOptions = Object.assign({}, options, {timings: timings})
        asciidoctor.convertFile(file, instanceOptions)
        timings.$print_report(Opal.gvars.stderr, file)
      } else {
        asciidoctor.convertFile(file, options)
      }
    })
  } else {
    yargs.showHelp()
  }
}

module.exports = {
  run: run,
  argsParser: argsParser,
  convertOptions: convertOptions
}
<commit_msg>Set to_file only if outFile is specified<commit_after>/* global Opal */
'use strict'

const yargs = require('yargs')
const asciidoctor = require('asciidoctor.js')()

function convertOptions (argv) {
  const backend = argv['backend']
  const doctype = argv['doctype']
  const safeMode = argv['safe-mode']
  const noHeaderFooter = argv['no-header-footer']
  const sectionNumbers = argv['section-numbers']
  const baseDir = argv['base-dir']
  const destinationDir = argv['destination-dir']
  const outFile = argv['out-file']
  const quiet = argv['quiet']
  const verbose = argv['verbose']
  const timings = argv['timings']
  const trace = argv['trace']
  const requireLib = argv['require']
  if (verbose) {
    console.log('require ' + requireLib)
    console.log('backend ' + backend)
    console.log('doctype ' + doctype)
    console.log('header-footer ' + !noHeaderFooter)
    console.log('section-numbers ' + sectionNumbers)
    console.log('quiet ' + quiet)
    console.log('verbose ' + verbose)
    console.log('timings ' + timings)
    console.log('trace ' + trace)
    console.log('base-dir ' + baseDir)
    console.log('destination-dir ' + destinationDir)
  }
  if (requireLib) {
    require(requireLib)
  }
  const verboseMode = quiet ? 0 : verbose ? 2 : 1
  const attributes = []
  if (noHeaderFooter) {
    attributes.push('showtitle')
  }
  if (sectionNumbers) {
    attributes.push('sectnums')
  }
  const cliAttributes = argv['attribute']
  if (cliAttributes) {
    attributes.push(...cliAttributes)
  }
  if (verbose) {
    console.log('verbose-mode ' + verboseMode)
    console.log('attributes ' + attributes)
  }
  const options = {
    backend: backend,
    doctype: doctype,
    safe: safeMode,
    header_footer: !noHeaderFooter,
    verbose: verboseMode,
    timings: timings,
    trace: trace
  }
  if (baseDir != null) {
    options.base_dir = baseDir
  }
  if (destinationDir != null) {
    options.to_dir = destinationDir
  }
  if (outFile != null) {
    if (outFile === '') {
      options.to_file = '-'
    } else {
      options.to_file = outFile
      options.mkdirs = true
    }
  }
  options.attributes = attributes
  if (verbose) {
    console.log('options ' + JSON.stringify(options))
  }
  if (options.to_file === '-') {
    options.to_file = Opal.gvars.stdout
  }
  return options
}

function argsParser () {
  return yargs
    .detectLocale(false)
    .wrap(Math.min(120, yargs.terminalWidth()))
    .command('$0 [files...]', '', function (yargs) {
      return yargs
        .option('backend', {
          alias: 'b',
          default: 'html5',
          describe: 'set output format backend',
          type: 'string'
        })
        .option('doctype', {
          alias: 'd',
          default: 'article',
          describe: 'document type to use when converting document',
          choices: ['article', 'book', 'manpage', 'inline']
        })
        .option('out-file', {
          alias: 'o',
          describe: 'output file (default: based on path of input file) use \'\' to output to STDOUT',
          type: 'string'
        })
        .option('safe-mode', {
          alias: 'S',
          default: 'unsafe',
          describe: 'set safe mode level explicitly, disables potentially dangerous macros in source files, such as include::[]',
          choices: ['unsafe', 'safe', 'server', 'secure']
        })
        .option('no-header-footer', {
          alias: 's',
          default: false,
          describe: 'suppress output of header and footer',
          type: 'boolean'
        })
        .option('section-numbers', {
          alias: 'n',
          default: false,
          describe: 'auto-number section titles in the HTML backend disabled by default',
          type: 'boolean'
        })
        .option('base-dir', {
          // QUESTION: should we check that the directory exists ? coerce to a directory ?
          alias: 'B',
          describe: 'base directory containing the document and resources (default: directory of source file)',
          type: 'string'
        })
        .option('destination-dir', {
          // QUESTION: should we check that the directory exists ? coerce to a directory ?
          alias: 'D',
          describe: 'destination output directory (default: directory of source file)',
          type: 'string'
        })
        .option('quiet', {
          alias: 'q',
          default: false,
          describe: 'suppress warnings',
          type: 'boolean'
        })
        .option('trace', {
          default: false,
          describe: 'include backtrace information on errors',
          type: 'boolean'
        })
        .option('verbose', {
          alias: 'v',
          default: false,
          describe: 'enable verbose mode',
          type: 'boolean'
        })
        .option('timings', {
          alias: 't',
          default: false,
          describe: 'enable timings mode',
          type: 'boolean'
        })
        .option('attribute', {
          alias: 'a',
          array: true,
          describe: 'a document attribute to set in the form of key, key! or key=value pair',
          type: 'string'
        })
        .option('require', {
          alias: 'r',
          array: true,
          describe: 'require the specified library before executing the processor, using the standard Node require',
          type: 'string'
        })
        .option('version', {
          alias: 'V',
          default: false,
          describe: 'display the version and runtime environment (or -v if no other flags or arguments)',
          type: 'boolean'
        })
    })
    .help()
}

function run (argv) {
  const verbose = argv['verbose']
  const version = argv['version']
  const files = argv['files']
  const options = convertOptions(argv)
  if (version || (verbose && files && files.length === 0)) {
    console.log(`Asciidoctor ${asciidoctor.getCoreVersion()} [http://asciidoctor.org]`)
    const releaseName = process.release ? process.release.name : 'node'
    console.log(`Runtime Environment (${releaseName} ${process.version} on ${process.platform})`)
  } else if (files && files.length > 0) {
    files.forEach(function (file) {
      if (verbose) {
        console.log(`converting file ${file}`)
      }
      if (argv['timings']) {
        const timings = asciidoctor.Timings.$new()
        const instanceOptions = Object.assign({}, options, {timings: timings})
        asciidoctor.convertFile(file, instanceOptions)
        timings.$print_report(Opal.gvars.stderr, file)
      } else {
        asciidoctor.convertFile(file, options)
      }
    })
  } else {
    yargs.showHelp()
  }
}

module.exports = {
  run: run,
  argsParser: argsParser,
  convertOptions: convertOptions
}
<|endoftext|>


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

"use strict";
/* -------------------------------------------------------------------
 * Require Statements << Keep in alphabetical order >>
 * ---------------------------------------------------------------- */

var Mayflower = require('./mayflower');
var program = require('commander');

/* =============================================================================
 *
 * Commandline Interface for Mayflower
 *
 * ========================================================================== */

program
  .option('-c, --connection [str]', 'Connection string to SQL Server Database.')
  .option('-d, --directory <dir>', 'Directory containing migration scripts.')
  .option('-f, --force', 'Forces scripts which have already been applied to be applied again.')
  .option('-s, --script [filename]', 'Specifies only a single script to be run.')
  .option('-t, --table [name]', 'Name of the Migrations history table (default: Migrations).')
  .option('-j, --json [filename]', 'Name of a json file where the connection string.')
  .option('-k, --key [key]', 'The key inside the json file for the connection string (dot notation).')
  .parse(process.argsv);

if (!program.connection)
{
  if (!(program.json && program.key)) {
    console.error('Must provide either a connection string OR a json file and key.');
    process.exit(1);
  }

  try {
    var json = JSON.parse(require('fs').readFileSync(program.json, { encoding: 'utf8' }));
    var parts = program.key.split('.');
    for (var i in parts) {
      json = json[parts[i]];
    }
    program.connection = json;
  }
  catch (ex) {
    console.error('Unable to read JSON file.');
    console.error(ex);
    process.exit(1);
  }
}

var m = new Mayflower(program.connection, program.directory, program.table);

var options = {
  output: true,
  force: program.force
};

var result;
if (!program.script) {
  //migrating all scripts
  result = m.migrateAll(options);
}
else {
  //running only a single script
  try {
    var script = m.getScript(program.script);
    var db = m.getDbConnection();
    result = m.migrate(db, options, script);
    db.closeSync();

  }
  catch (ex) {
    result = ex;
  }
}

if (result instanceof Error) {
  console.log(result);
  process.exit(-1);
}

process.exit(0);
<commit_msg>Maybe use the correct property name.<commit_after>#!/usr/bin/env node

"use strict";
/* -------------------------------------------------------------------
 * Require Statements << Keep in alphabetical order >>
 * ---------------------------------------------------------------- */

var Mayflower = require('./mayflower');
var program = require('commander');

/* =============================================================================
 *
 * Commandline Interface for Mayflower
 *
 * ========================================================================== */

program
  .option('-c, --connection [str]', 'Connection string to SQL Server Database.')
  .option('-d, --directory <dir>', 'Directory containing migration scripts.')
  .option('-f, --force', 'Forces scripts which have already been applied to be applied again.')
  .option('-s, --script [filename]', 'Specifies only a single script to be run.')
  .option('-t, --table [name]', 'Name of the Migrations history table (default: Migrations).')
  .option('-j, --json [filename]', 'Name of a json file where the connection string.')
  .option('-k, --key [key]', 'The key inside the json file for the connection string (dot notation).')
  .parse(process.argv);

if (!program.connection)
{
  if (!(program.json && program.key)) {
    console.error('Must provide either a connection string OR a json file and key.');
    process.exit(1);
  }

  try {
    var json = JSON.parse(require('fs').readFileSync(program.json, { encoding: 'utf8' }));
    var parts = program.key.split('.');
    for (var i in parts) {
      json = json[parts[i]];
    }
    program.connection = json;
  }
  catch (ex) {
    console.error('Unable to read JSON file.');
    console.error(ex);
    process.exit(1);
  }
}

var m = new Mayflower(program.connection, program.directory, program.table);

var options = {
  output: true,
  force: program.force
};

var result;
if (!program.script) {
  //migrating all scripts
  result = m.migrateAll(options);
}
else {
  //running only a single script
  try {
    var script = m.getScript(program.script);
    var db = m.getDbConnection();
    result = m.migrate(db, options, script);
    db.closeSync();

  }
  catch (ex) {
    result = ex;
  }
}

if (result instanceof Error) {
  console.log(result);
  process.exit(-1);
}

process.exit(0);
<|endoftext|>


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

function getCommandlineOptions() {
    'use strict';

    var version = require('../package.json').version;
    var opts = require('nomnom')
        .script('jison')
        .options({
            file: {
                flag: true,
                position: 0,
                help: 'file containing a grammar'
            },
            lexfile: {
                flag: true,
                position: 1,
                help: 'file containing a lexical grammar'
            },
            json: {
                abbr: 'j',
                flag: true,
                default: false,
                help: 'force jison to expect a grammar in JSON format'
            },
            outfile: {
                abbr: 'o',
                metavar: 'FILE',
                help : 'Filepath and base module name of the generated parser;\nwhen terminated with a / (dir separator) it is treated as the destination directory where the generated output will be stored'
            },
            debug: {
                abbr: 't',
                flag: true,
                default: false,
                help: 'Debug mode'
            },
            moduleType: {
                full: 'module-type',
                abbr: 'm',
                default: 'commonjs',
                metavar: 'TYPE',
                choices: ['commonjs', 'amd', 'js', 'es'],
                help: 'The type of module to generate (commonjs, amd, es, js)'
            },
            moduleName: {
                full: 'module-name',
            	abbr: 'n',
            	metavar: 'NAME',
            	help: 'The name of the generated parser object, namespace supported'
            },
            parserType: {
                full: 'parser-type',
                abbr: 'p',
                default: 'lalr',
                metavar: 'TYPE',
                help: 'The type of algorithm to use for the parser (lr0, slr, lalr, lr, ll)'
            },
            compressTables: {
                full: 'compress-tables',
                abbr: 'c',
                flag: false,
                default: 2,             // 0, 1, 2
                choices: [0, 1, 2],
                help: 'Output compressed parser tables in generated modules (0 = no compression, 1 = default compression, 2 = deep compression)'
            },
            outputDebugTables: {
                full: 'output-debug-tables',
                abbr: 'T',
                flag: true,
                default: false,
                help: 'Output extra parser tables (rules list + look-ahead analysis) in generated modules to assist debugging / diagnostics purposes'
            },
            noDefaultResolve: {
                full: 'no-default-resolve',
                abbr: 'X',
                flag: true,
                default: false,
                help: 'Act another way when a conflict is found in the grammar'
            },
            noDefaultAction: {
                full: 'no-default-action',
                flag: true,
                default: false,
                help: 'Generate a parser which does NOT include the default "$$ = $1" action for every rule. This produces a slightly faster parser but now you are solely reponsible for propagating rule action "$$" results.'
            },
            noTryCatch: {
                full: 'no-try-catch',
                flag: true,
                default: false,
                help: 'Generate a parser which does NOT try/catch exceptions (from the grammar action code or parseError error reporting calls. This produces a slightly faster parser at the cost of enhanced code safety.'
            },
            errorRecoveryTokenDiscardCount: {
                full: 'error-recovery-token-discard-count',
                abbr: 'Q',
                flag: false,
                default: 3,
                callback: function (count) {
                    if (count != parseInt(count)) {
                        return "count must be an integer";
                    }
                    count = parseInt(count);
                    if (count < 2) {
                        return "count must be >= 2";
                    }
                },
                help: 'Set the number of lexed tokens that may be gobbled by an error recovery process before we cry wolf (default: 3)'
            },
            exportAllTables: {
                full: 'export-all-tables',
                abbr: 'E',
                flag: true,
                default: false,
                help: 'Next to producing a grammar source file, also export the symbols, terminals, grammar and parse tables to separate JSON files for further use by other tools. The files\' names will be derived from the outputFile name by appending a suffix.'
            },
            main: {
                full: 'main',
            	abbr: 'x',
                flag: true,
                default: false,
                help: 'Include .main() entry point in generated commonjs module'
            },
            moduleMain: {
                full: 'module-main',
            	abbr: 'y',
            	metavar: 'NAME',
            	help: 'The main module function definition'
            },
            version: {
                abbr: 'V',
                flag: true,
                help: 'print version and exit',
                callback: function () {
                    return version;
                }
            }
        }).parse();

    return opts;
}

var cli = module.exports;

cli.main = function cliMain(opts) {
    'use strict';

    opts = opts || {};

    var fs = require('fs');
    var path = require('path');

    function isDirectory(fp) {
        try {
            return fs.lstatSync(fp).isDirectory();
        } catch (e) {
            return false;
        }
    }

    function mkdirp(fp) {
        if (!fp || fp === '.' || fp.length === 0) {
            return false;
        }
        try {
            fs.mkdirSync(fp);
            return true;
        } catch (e) {
            if (e.code === 'ENOENT') {
                var parent = path.dirname(fp);
                // Did we hit the root directory by now? If so, abort!
                // Else, create the parent; iff that fails, we fail too...
                if (parent !== fp && mkdirp(parent)) {
                    try {
                        // Retry creating the original directory: it should succeed now
                        fs.mkdirSync(fp);
                        return true;
                    } catch (e) {
                        return false;
                    }
                }
            }
        }
        return false;
    }

    function processInputFile() {
        // getting raw files
        var lex;
        var original_cwd = process.cwd();

        if (opts.lexfile) {
            lex = fs.readFileSync(path.normalize(opts.lexfile), 'utf8');
        }
        var raw = fs.readFileSync(path.normalize(opts.file), 'utf8');

        // making best guess at json mode
        opts.json = path.extname(opts.file) === '.json' || opts.json;

        // When only the directory part of the output path was specified, then we
        // do NOT have the target module name in there as well!
        var outpath = opts.outfile;
        if (/[\\\/]$/.test(outpath) || isDirectory(outpath)) {
            opts.outfile = null;
            outpath = outpath.replace(/[\\\/]$/, '');
        }
        if (outpath && outpath.length > 0) {
            outpath += '/';
        } else {
            outpath = '';
        }

        // setting output file name and module name based on input file name
        // if they aren't specified.
        var name = path.basename((opts.outfile || opts.file));

        // get the base name (i.e. the file name without extension)
        // i.e. strip off only the extension and keep any other dots in the filename
        name = path.basename(name, path.extname(name));

        opts.outfile = opts.outfile || (outpath + name + '.js');
        if (!opts.moduleName && name) {
            opts.moduleName = name.replace(/-\w/g,
                function (match) {
                    return match.charAt(1).toUpperCase();
                });
        }

        // Change CWD to the directory where the source grammar resides: this helps us properly
        // %include any files mentioned in the grammar with relative paths:
        var new_cwd = path.dirname(path.normalize(opts.file));
        process.chdir(new_cwd);

        var parser = cli.generateParserString(raw, lex, opts);

        // and change back to the CWD we started out with:
        process.chdir(original_cwd);

        mkdirp(path.dirname(opts.outfile));
        fs.writeFileSync(opts.outfile, parser);
        console.log('JISON output for module [' + opts.moduleName + '] has been written to file:', opts.outfile);

        if (opts.exportAllTables) {
	        	// Determine the output file path 'template' for use by the exportAllTables
	        	// functionality:
	        	var out_ext = path.extname(opts.outfile);
	        	var out_re = new RegExp(out_ext.replace(/\./g, '\\.') + '$');			// re = /\.<ext>$/
	        	//opts.outfiletemplate = opts.outfile.replace(out_re, '@@');

	        	var t = opts.exportAllTables;

	        	for (var id in t) {
	        		if (t.hasOwnProperty(id) && id !== 'enabled') {
	        			var content = t[id];
	        			if (content) {
	        				var fname = opts.outfile.replace(out_re, '.' + id.replace(/[^a-zA-Z0-9_]/g, '_') + '.json');
					        fs.writeFileSync(fname, JSON.stringify(content, null, 2) /* .replace(/"([0-9]+)":/g, '$1:').replace(/^(\s+)"([a-z_][a-z_0-9]*)":/gmi, '$1$2:') */ );
					        console.log('JISON table export for [' + id + '] has been written to file:', fname);
	        			}
	        		}
	        	}
        }
    }

    function readin(cb) {
        var stdin = process.openStdin(),
        data = '';

        stdin.setEncoding('utf8');
        stdin.addListener('data', function (chunk) {
            data += chunk;
        });
        stdin.addListener('end', function () {
            cb(data);
        });
    }

    function processStdin() {
        readin(function processStdinReadInCallback(raw) {
            console.log(cli.generateParserString(raw, null, opts));
        });
    }

    // if an input file wasn't given, assume input on stdin
    if (opts.file) {
        processInputFile();
    } else {
        processStdin();
    }
};

cli.generateParserString = function generateParserString(grammar, optionalLexSection, opts) {
    'use strict';

    opts = opts || {};
    var jison = require('./jison.js');

    var settings = {};

    if (opts.parserType) {
        settings.type = opts.parserType;
    }
    settings.noMain = !opts.main;

    for (var key in opts) {
        if (opts[key]) {
            settings[key] = opts[key];
        }
    }
    delete settings.main;               // inverse known as settings.noMain
    delete settings.parserType;         // alias known as settings.type

    var generator = new jison.Generator(grammar, optionalLexSection, settings);
    var srcCode = generator.generate(settings);

    // as `settings` is cloned inside `generator.generate()`, we need to fetch
    // the extra exported tables from the `options` member of the generator
    // itself:
    opts.exportAllTables = generator.options.exportAllTables;

    return srcCode;
};

if (require.main === module) {
    var opts = getCommandlineOptions();
    cli.main(opts);
}
<commit_msg>BUGFIX: CLI wouldn't properly handle the `-c 0` compression mode setting.<commit_after>#!/usr/bin/env node

function getCommandlineOptions() {
    'use strict';

    var version = require('../package.json').version;
    var opts = require('nomnom')
        .script('jison')
        .options({
            file: {
                flag: true,
                position: 0,
                help: 'file containing a grammar'
            },
            lexfile: {
                flag: true,
                position: 1,
                help: 'file containing a lexical grammar'
            },
            json: {
                abbr: 'j',
                flag: true,
                default: false,
                help: 'force jison to expect a grammar in JSON format'
            },
            outfile: {
                abbr: 'o',
                metavar: 'FILE',
                help : 'Filepath and base module name of the generated parser;\nwhen terminated with a / (dir separator) it is treated as the destination directory where the generated output will be stored'
            },
            debug: {
                abbr: 't',
                flag: true,
                default: false,
                help: 'Debug mode'
            },
            moduleType: {
                full: 'module-type',
                abbr: 'm',
                default: 'commonjs',
                metavar: 'TYPE',
                choices: ['commonjs', 'amd', 'js', 'es'],
                help: 'The type of module to generate (commonjs, amd, es, js)'
            },
            moduleName: {
                full: 'module-name',
            	abbr: 'n',
            	metavar: 'NAME',
            	help: 'The name of the generated parser object, namespace supported'
            },
            parserType: {
                full: 'parser-type',
                abbr: 'p',
                default: 'lalr',
                metavar: 'TYPE',
                help: 'The type of algorithm to use for the parser (lr0, slr, lalr, lr, ll)'
            },
            compressTables: {
                full: 'compress-tables',
                abbr: 'c',
                flag: false,
                default: 2,             // 0, 1, 2
                choices: [0, 1, 2],
                help: 'Output compressed parser tables in generated modules (0 = no compression, 1 = default compression, 2 = deep compression)'
            },
            outputDebugTables: {
                full: 'output-debug-tables',
                abbr: 'T',
                flag: true,
                default: false,
                help: 'Output extra parser tables (rules list + look-ahead analysis) in generated modules to assist debugging / diagnostics purposes'
            },
            noDefaultResolve: {
                full: 'no-default-resolve',
                abbr: 'X',
                flag: true,
                default: false,
                help: 'Act another way when a conflict is found in the grammar'
            },
            noDefaultAction: {
                full: 'no-default-action',
                flag: true,
                default: false,
                help: 'Generate a parser which does NOT include the default "$$ = $1" action for every rule. This produces a slightly faster parser but now you are solely reponsible for propagating rule action "$$" results.'
            },
            noTryCatch: {
                full: 'no-try-catch',
                flag: true,
                default: false,
                help: 'Generate a parser which does NOT try/catch exceptions (from the grammar action code or parseError error reporting calls. This produces a slightly faster parser at the cost of enhanced code safety.'
            },
            errorRecoveryTokenDiscardCount: {
                full: 'error-recovery-token-discard-count',
                abbr: 'Q',
                flag: false,
                default: 3,
                callback: function (count) {
                    if (count != parseInt(count)) {
                        return "count must be an integer";
                    }
                    count = parseInt(count);
                    if (count < 2) {
                        return "count must be >= 2";
                    }
                },
                help: 'Set the number of lexed tokens that may be gobbled by an error recovery process before we cry wolf (default: 3)'
            },
            exportAllTables: {
                full: 'export-all-tables',
                abbr: 'E',
                flag: true,
                default: false,
                help: 'Next to producing a grammar source file, also export the symbols, terminals, grammar and parse tables to separate JSON files for further use by other tools. The files\' names will be derived from the outputFile name by appending a suffix.'
            },
            main: {
                full: 'main',
            	abbr: 'x',
                flag: true,
                default: false,
                help: 'Include .main() entry point in generated commonjs module'
            },
            moduleMain: {
                full: 'module-main',
            	abbr: 'y',
            	metavar: 'NAME',
            	help: 'The main module function definition'
            },
            version: {
                abbr: 'V',
                flag: true,
                help: 'print version and exit',
                callback: function () {
                    return version;
                }
            }
        }).parse();

    return opts;
}

var cli = module.exports;

cli.main = function cliMain(opts) {
    'use strict';

    opts = opts || {};

    var fs = require('fs');
    var path = require('path');

    function isDirectory(fp) {
        try {
            return fs.lstatSync(fp).isDirectory();
        } catch (e) {
            return false;
        }
    }

    function mkdirp(fp) {
        if (!fp || fp === '.' || fp.length === 0) {
            return false;
        }
        try {
            fs.mkdirSync(fp);
            return true;
        } catch (e) {
            if (e.code === 'ENOENT') {
                var parent = path.dirname(fp);
                // Did we hit the root directory by now? If so, abort!
                // Else, create the parent; iff that fails, we fail too...
                if (parent !== fp && mkdirp(parent)) {
                    try {
                        // Retry creating the original directory: it should succeed now
                        fs.mkdirSync(fp);
                        return true;
                    } catch (e) {
                        return false;
                    }
                }
            }
        }
        return false;
    }

    function processInputFile() {
        // getting raw files
        var lex;
        var original_cwd = process.cwd();

        if (opts.lexfile) {
            lex = fs.readFileSync(path.normalize(opts.lexfile), 'utf8');
        }
        var raw = fs.readFileSync(path.normalize(opts.file), 'utf8');

        // making best guess at json mode
        opts.json = path.extname(opts.file) === '.json' || opts.json;

        // When only the directory part of the output path was specified, then we
        // do NOT have the target module name in there as well!
        var outpath = opts.outfile;
        if (/[\\\/]$/.test(outpath) || isDirectory(outpath)) {
            opts.outfile = null;
            outpath = outpath.replace(/[\\\/]$/, '');
        }
        if (outpath && outpath.length > 0) {
            outpath += '/';
        } else {
            outpath = '';
        }

        // setting output file name and module name based on input file name
        // if they aren't specified.
        var name = path.basename((opts.outfile || opts.file));

        // get the base name (i.e. the file name without extension)
        // i.e. strip off only the extension and keep any other dots in the filename
        name = path.basename(name, path.extname(name));

        opts.outfile = opts.outfile || (outpath + name + '.js');
        if (!opts.moduleName && name) {
            opts.moduleName = name.replace(/-\w/g,
                function (match) {
                    return match.charAt(1).toUpperCase();
                });
        }

        // Change CWD to the directory where the source grammar resides: this helps us properly
        // %include any files mentioned in the grammar with relative paths:
        var new_cwd = path.dirname(path.normalize(opts.file));
        process.chdir(new_cwd);

        var parser = cli.generateParserString(raw, lex, opts);

        // and change back to the CWD we started out with:
        process.chdir(original_cwd);

        mkdirp(path.dirname(opts.outfile));
        fs.writeFileSync(opts.outfile, parser);
        console.log('JISON output for module [' + opts.moduleName + '] has been written to file:', opts.outfile);

        if (opts.exportAllTables) {
	        	// Determine the output file path 'template' for use by the exportAllTables
	        	// functionality:
	        	var out_ext = path.extname(opts.outfile);
	        	var out_re = new RegExp(out_ext.replace(/\./g, '\\.') + '$');			// re = /\.<ext>$/
	        	//opts.outfiletemplate = opts.outfile.replace(out_re, '@@');

	        	var t = opts.exportAllTables;

	        	for (var id in t) {
	        		if (t.hasOwnProperty(id) && id !== 'enabled') {
	        			var content = t[id];
	        			if (content) {
	        				var fname = opts.outfile.replace(out_re, '.' + id.replace(/[^a-zA-Z0-9_]/g, '_') + '.json');
					        fs.writeFileSync(fname, JSON.stringify(content, null, 2) /* .replace(/"([0-9]+)":/g, '$1:').replace(/^(\s+)"([a-z_][a-z_0-9]*)":/gmi, '$1$2:') */ );
					        console.log('JISON table export for [' + id + '] has been written to file:', fname);
	        			}
	        		}
	        	}
        }
    }

    function readin(cb) {
        var stdin = process.openStdin(),
        data = '';

        stdin.setEncoding('utf8');
        stdin.addListener('data', function (chunk) {
            data += chunk;
        });
        stdin.addListener('end', function () {
            cb(data);
        });
    }

    function processStdin() {
        readin(function processStdinReadInCallback(raw) {
            console.log(cli.generateParserString(raw, null, opts));
        });
    }

    // if an input file wasn't given, assume input on stdin
    if (opts.file) {
        processInputFile();
    } else {
        processStdin();
    }
};

cli.generateParserString = function generateParserString(grammar, optionalLexSection, opts) {
    'use strict';

    opts = opts || {};
    var jison = require('./jison.js');

    var settings = {};

    if (opts.parserType) {
        settings.type = opts.parserType;
    }
    settings.noMain = !opts.main;

    for (var key in opts) {
        if (opts[key] || opts[key] === 0) {
            settings[key] = opts[key];
        }
    }
    delete settings.main;               // inverse known as settings.noMain
    delete settings.parserType;         // alias known as settings.type

    var generator = new jison.Generator(grammar, optionalLexSection, settings);
    var srcCode = generator.generate(settings);

    // as `settings` is cloned inside `generator.generate()`, we need to fetch
    // the extra exported tables from the `options` member of the generator
    // itself:
    opts.exportAllTables = generator.options.exportAllTables;

    return srcCode;
};

if (require.main === module) {
    var opts = getCommandlineOptions();
    cli.main(opts);
}
<|endoftext|>


<commit_before>var js = require('atomify-js')
  , css = require('atomify-css')
  , fs = require('fs')
  , path = require('path')
  , writer = require('write-to-path')
  , server = require('./server')
  , pkgCfg = path.join(process.cwd(), 'package.json')

pkgCfg = fs.existsSync(pkgCfg) && require(pkgCfg).atomify ? require(pkgCfg).atomify : {}

module.exports = function (args) {
  if ((args._ && args._[0] === 'help') || args.help) {
    return fs.createReadStream(__dirname + '/usage.txt')
      .pipe(process.stdout)
      .on('close', function () { process.exit(1) });
  }

  if (args.version) {
    return console.log(require('../package.json').version);
  }

  args.css = args.css || pkgCfg.css || fs.existsSync('./index.css') && {entry: 'index.css'}
  args.js = args.js || pkgCfg.js || fs.existsSync('./index.js') && {entry: 'index.js'}
  args.server = args.server || pkgCfg.server

  if (pkgCfg && pkgCfg.assets) {
    if (args.css) args.css.assets = pkgCfg.assets
    if (args.js) args.js.assets = pkgCfg.assets
  }

  if (args.css) {
    args.css = parseArgs('css', args.css, args)

    args.css.variables = args.css.v || args.css.variables
    args.css.plugins = args.css.p || args.css.plugins
    args.css.compress = args.css.c || args.css.compress

    if (args.css.output) {
      css(args.css, function doWatchWriteServerstart(err, src, resourcepaths) {
        resourcepaths.cssEntry  = [path.join(process.cwd(), args.css.entry)];
        resourcepaths.jsEntry   = [path.join(process.cwd(), args.js.entry)];
        args.resourcepaths = resourcepaths;
        if (args.server) server(args);
      });
    }
  }

  if (args.js) {
    args.js = parseArgs('js', args.js, args)

    args.js.watch = args.js.w || args.js.watch
    args.js.transforms = args.js.t || args.js.transform

    if (args.js.output) js(args.js, writer(args.js.output, args.js))
  }
}

function parseArgs (ext, child, parent) {
  if (typeof child === 'string') child = {entry: child} // -j entry.js
  if (child._) child.entry = child._[0] // -j [ entry.js ]
  if (typeof child.e === 'string') child.entry = child.e // -j [ -e entry.js ]
  if (Array.isArray(child.e)) child.entries = child.e // -j [ -e entry.js -e other.js ]

  if (child.entry.indexOf(':') > 0) {
    var pieces = child.entry.split(':')
    child.entry = pieces[0]
    child.alias = pieces[1]
  }

  child.debug = child.d || child.debug || parent.debug

  child.output = child.o || child.output
  if (child._ && child._.length === 2) child.output = child._[1] // -j [ entry.js bundle.js ]
  if (!child.output && parent.output) child.output = parent.output.indexOf(ext) > 1 ? parent.output : parent.output + '.' + ext

  if (!child.output && !parent.server) {
    console.error('No output path provided for ' + ext.toUpperCase() + ' bundle!')
    process.exit(1)
  }

  return child;
}
<commit_msg>FIX error logging<commit_after>var js = require('atomify-js')
  , css = require('atomify-css')
  , fs = require('fs')
  , path = require('path')
  , writer = require('write-to-path')
  , server = require('./server')
  , pkgCfg = path.join(process.cwd(), 'package.json')

pkgCfg = fs.existsSync(pkgCfg) && require(pkgCfg).atomify ? require(pkgCfg).atomify : {}

module.exports = function (args) {
  if ((args._ && args._[0] === 'help') || args.help) {
    return fs.createReadStream(__dirname + '/usage.txt')
      .pipe(process.stdout)
      .on('close', function () { process.exit(1) });
  }

  if (args.version) {
    return console.log(require('../package.json').version);
  }

  args.css = args.css || pkgCfg.css || fs.existsSync('./index.css') && {entry: 'index.css'}
  args.js = args.js || pkgCfg.js || fs.existsSync('./index.js') && {entry: 'index.js'}
  args.server = args.server || pkgCfg.server

  if (pkgCfg && pkgCfg.assets) {
    if (args.css) args.css.assets = pkgCfg.assets
    if (args.js) args.js.assets = pkgCfg.assets
  }

  if (args.css) {
    args.css = parseArgs('css', args.css, args)

    args.css.variables = args.css.v || args.css.variables
    args.css.plugins = args.css.p || args.css.plugins
    args.css.compress = args.css.c || args.css.compress

    if (args.css.output) {
      css(args.css, function doWatchWriteServerstart(err, src, resourcepaths) {
        if (err) console.log(err);
        resourcepaths.cssEntry  = [path.join(process.cwd(), args.css.entry)];
        resourcepaths.jsEntry   = [path.join(process.cwd(), args.js.entry)];
        args.resourcepaths = resourcepaths;
        if (args.server) server(args);
      });
    }
  }

  if (args.js) {
    args.js = parseArgs('js', args.js, args)

    args.js.watch = args.js.w || args.js.watch
    args.js.transforms = args.js.t || args.js.transform

    if (args.js.output) js(args.js, writer(args.js.output, args.js))
  }
}

function parseArgs (ext, child, parent) {
  if (typeof child === 'string') child = {entry: child} // -j entry.js
  if (child._) child.entry = child._[0] // -j [ entry.js ]
  if (typeof child.e === 'string') child.entry = child.e // -j [ -e entry.js ]
  if (Array.isArray(child.e)) child.entries = child.e // -j [ -e entry.js -e other.js ]

  if (child.entry.indexOf(':') > 0) {
    var pieces = child.entry.split(':')
    child.entry = pieces[0]
    child.alias = pieces[1]
  }

  child.debug = child.d || child.debug || parent.debug

  child.output = child.o || child.output
  if (child._ && child._.length === 2) child.output = child._[1] // -j [ entry.js bundle.js ]
  if (!child.output && parent.output) child.output = parent.output.indexOf(ext) > 1 ? parent.output : parent.output + '.' + ext

  if (!child.output && !parent.server) {
    console.error('No output path provided for ' + ext.toUpperCase() + ' bundle!')
    process.exit(1)
  }

  return child;
}
<|endoftext|>


<commit_before>'use strict';

var fs = require('fs');
var execSync = require('child_process').execSync;
var semver = require('semver');
var inquirer = require('inquirer');
var shellQuote = require('shell-quote');

module.exports = createNpmBump('origin', 'master');
module.exports.custom = createNpmBump;

function createNpmBump(remoteName, branch) {
    remoteName = remoteName || 'origin';
    branch = branch || 'master';

    function UsageError(message) {
        this.name = 'UsageError';
        this.message = message;
    }

    UsageError.prototype = Object.create(Error.prototype);

    return function npmBump(releaseType) {
        var isPrerelease = ['major', 'minor', 'patch'].indexOf(releaseType) === -1;

        ensureCleanBranch();
        doBump();

        function getHashFor(branchName) {
            try {
                return run('git rev-parse --verify ' + quote(branchName)).trim();
            } catch (error) {
                throw new UsageError('Git couldn\'t find the branch: "' + branchName + '"; please ensure it exists');
            }
        }

        function ensureCleanBranch() {
            if (getHashFor('HEAD') !== getHashFor(branch)) {
                throw new UsageError('You need to be on the "' + branch + '" branch to run this script');
            }
            if (getHashFor(branch) !== getHashFor(remoteName + '/' + branch)) {
                throw new UsageError('You need to push your changes first');
            }
            if (run('git status -s').length) {
                throw new UsageError('You have uncommited changes! Commit them before running this script');
            }
        }

        function getRootPath() {
            return run('git rev-parse --show-cdup').trim();
        }

        function getPackageJsonPath() {
            return process.cwd() + '/' + getRootPath() + 'package.json';
        }

        function quote(string) {
            return shellQuote.quote([string]);
        }

        function run(command) {
            return execSync(command, {encoding: 'utf8'});
        }

        function writePackageJson(configObject) {
            fs.writeFileSync(getPackageJsonPath(), JSON.stringify(configObject, null, 2) + '\n');
        }

        function doBump() {
            var packageJson = require(getPackageJsonPath());
            var oldVersion = packageJson.version;

            // Tag a new release
            var newStableVersion = packageJson.version = isPrerelease ?
                semver.inc(oldVersion, 'pre', releaseType) :
                semver.inc(oldVersion, releaseType);
            writePackageJson(packageJson);
            console.log('Version bumped from ' + oldVersion + ' to ' + newStableVersion);
            run('git add ' + quote(getPackageJsonPath()));
            run('git commit -m ' + quote('Tag ' + newStableVersion));
            run('git tag ' + quote(newStableVersion));

            // Bump to a new pre-release version but only if the version to publish is not
            // itself a pre-release; otherwise semver gets confused.
            if (!isPrerelease) {
                packageJson.version = semver.inc(packageJson.version, 'patch') + '-pre';
                writePackageJson(packageJson);
                run('git add ' + quote(getPackageJsonPath()));
                run('git commit -m ' + quote('Bump to ' + packageJson.version));
            }

            // All public changes are done here.
            inquirer.prompt([{
                name: 'shouldProceed',
                type: 'confirm',
                message: 'Are you sure you want to publish the new version?',
            }], function (answers) {
                if (answers.shouldProceed) {
                    run('git checkout ' + quote(newStableVersion) + ' 2>/dev/null');
                    run('npm publish ' + quote(getRootPath()) +
                        (isPrerelease ? ' --tag ' + quote(releaseType) : '')
                    );
                    run('git checkout ' + quote(branch) + ' 2>/dev/null');
                    run('git push ' + quote(remoteName) + ' ' + quote(newStableVersion));
                    run('git push ' + quote(remoteName) + ' ' + quote(branch));
                } else {
                    run('git tag -d ' + quote(newStableVersion));
                    run('git reset --hard ' + quote(remoteName) + '/' + quote(branch));
                    console.log('Changes reverted');
                }
            });
        }
    };
}
<commit_msg>Hack to make the last commit have a newer date than the tagged one<commit_after>'use strict';

var fs = require('fs');
var execSync = require('child_process').execSync;
var semver = require('semver');
var inquirer = require('inquirer');
var shellQuote = require('shell-quote');

module.exports = createNpmBump('origin', 'master');
module.exports.custom = createNpmBump;

function createNpmBump(remoteName, branch) {
    remoteName = remoteName || 'origin';
    branch = branch || 'master';

    function UsageError(message) {
        this.name = 'UsageError';
        this.message = message;
    }

    UsageError.prototype = Object.create(Error.prototype);

    return function npmBump(releaseType) {
        var isPrerelease = ['major', 'minor', 'patch'].indexOf(releaseType) === -1;

        ensureCleanBranch();
        doBump();

        function getHashFor(branchName) {
            try {
                return run('git rev-parse --verify ' + quote(branchName)).trim();
            } catch (error) {
                throw new UsageError('Git couldn\'t find the branch: "' + branchName + '"; please ensure it exists');
            }
        }

        function ensureCleanBranch() {
            if (getHashFor('HEAD') !== getHashFor(branch)) {
                throw new UsageError('You need to be on the "' + branch + '" branch to run this script');
            }
            if (getHashFor(branch) !== getHashFor(remoteName + '/' + branch)) {
                throw new UsageError('You need to push your changes first');
            }
            if (run('git status -s').length) {
                throw new UsageError('You have uncommited changes! Commit them before running this script');
            }
        }

        function getRootPath() {
            return run('git rev-parse --show-cdup').trim();
        }

        function getPackageJsonPath() {
            return process.cwd() + '/' + getRootPath() + 'package.json';
        }

        function quote(string) {
            return shellQuote.quote([string]);
        }

        function run(command) {
            return execSync(command, {encoding: 'utf8'});
        }

        function writePackageJson(configObject) {
            fs.writeFileSync(getPackageJsonPath(), JSON.stringify(configObject, null, 2) + '\n');
        }

        function doBump() {
            var commitMsg;
            var packageJson = require(getPackageJsonPath());
            var oldVersion = packageJson.version;

            // Tag a new release
            var newStableVersion = packageJson.version = isPrerelease ?
                semver.inc(oldVersion, 'pre', releaseType) :
                semver.inc(oldVersion, releaseType);
            writePackageJson(packageJson);
            console.log('Version bumped from ' + oldVersion + ' to ' + newStableVersion);
            run('git add ' + quote(getPackageJsonPath()));
            run('git commit -m ' + quote('Tag ' + newStableVersion));
            run('git tag ' + quote(newStableVersion));

            // Bump to a new pre-release version but only if the version to publish is not
            // itself a pre-release; otherwise semver gets confused.
            if (!isPrerelease) {
                packageJson.version = semver.inc(packageJson.version, 'patch') + '-pre';
                writePackageJson(packageJson);
                run('git add ' + quote(getPackageJsonPath()));
                run('git commit -m ' + quote('Bump to ' + packageJson.version));
            }

            // All public changes are done here.
            inquirer.prompt([{
                name: 'shouldProceed',
                type: 'confirm',
                message: 'Are you sure you want to publish the new version?',
            }], function (answers) {
                if (answers.shouldProceed) {
                    // Push & publish the tag.
                    run('git checkout ' + quote(newStableVersion) + ' 2>/dev/null');
                    run('npm publish ' + quote(getRootPath()) +
                        (isPrerelease ? ' --tag ' + quote(releaseType) : '')
                    );
                    run('git push ' + quote(remoteName) + ' ' + quote(newStableVersion));

                    // Push the latest commit.
                    run('git checkout ' + quote(branch) + ' 2>/dev/null');

                    if (!isPrerelease) {
                        // Force-update the date to prevent two commits having the same time stamp.
                        commitMsg = run('git show -s --format=%s');
                        run('git reset --soft HEAD^');
                        run('git commit -m ' + quote(commitMsg));
                    }

                    run('git push ' + quote(remoteName) + ' ' + quote(branch));
                } else {
                    run('git tag -d ' + quote(newStableVersion));
                    run('git reset --hard ' + quote(remoteName) + '/' + quote(branch));
                    console.log('Changes reverted');
                }
            });
        }
    };
}
<|endoftext|>