<commit_before>/**
 * 命令行相关的信息和工具类方法暴露在此模块中。
 * @namespace fis.cli
 */
var cli = module.exports = {};

var path = require('path');
var _ = require('./util.js');
var util = require('util');
var lolcat = require('fis-lolcat');

/**
 * 命令行工具名字
 * @memberOf fis.cli
 * @name name
 * @defaultValue fis3
 */
cli.name = 'fis3';

/**
 * 指向 {@link https://www.npmjs.com/package/colors colors} 模块。
 * @memberOf fis.cli
 * @name colors
 */
cli.colors = require('colors');

//commander object
cli.commander = null;

/**
 * package.json 中的信息
 * @memberOf fis.cli
 * @name info
 */
cli.info = fis.util.readJSON(path.dirname(__dirname) + '/package.json');

/**
 * 显示帮助信息，主要用来格式化信息，处理缩进等。fis command 插件，可以用此方法来输出帮助信息。
 *
 * @param  {String} [cmdName]  命令名称
 * @param  {Object} [options]  配置
 * @param  {Array} [commands] 支持的命令集合
 * @memberOf fis.cli
 * @name help
 * @function
 */
cli.help = function(cmdName, options, commands) {
  var strs = [
    '',
    ' Usage: ' + cli.name + ' ' + (cmdName ? cmdName : '<command>')
  ];

  if (!cmdName) {
    commands = {};
    fis.media().get('modules.commands', []).forEach(function(name) {
      var cmd = fis.require('command', name);
      name = cmd.name || name;
      name = fis.util.pad(name, 12);
      commands[name] = cmd.desc || '';
    });

    options =  {
      '-h, --help': 'print this help message',
      '-v, --version': 'print product version and exit',
      '-r, --root <path>': 'specify project root',
      '-f, --file <filename>': 'specify the file path of `fis-conf.js`',
      '--no-color': 'disable colored output',
      '--verbose': 'enable verbose mode'
    };
  }

  options = options || {};
  commands = commands || {};
  var optionsKeys = Object.keys(options);
  var commandsKeys = Object.keys(commands);
  var maxWidth;

  if (commandsKeys.length) {
    maxWidth = commandsKeys.reduce(function(prev, curr) {
      return curr.length > prev ? curr.length : prev;
    }, 0) + 4;

    strs.push(null, ' Commands:', null);

    commandsKeys.forEach(function(key) {
      strs.push(util.format('   %s %s', _.pad(key, maxWidth), commands[key]));
    });
  }

  if (optionsKeys.length) {
    maxWidth = optionsKeys.reduce(function(prev, curr) {
      return curr.length > prev ? curr.length : prev;
    }, 0) + 4;

    strs.push(null, ' Options:', null);

    optionsKeys.forEach(function(key) {
      strs.push(util.format('   %s %s', _.pad(key, maxWidth), options[key]));
    });

    strs.push(null);
  }

  console.log(strs.join('\n'));
};

fis.set('modules.commands', ['init', 'install', 'release', 'server', 'inspect']);

/**
 * 输出 fis 版本信息。
 *
 * ```
 * v3.0.0
 *
 * /\\\\\\\\\\\\\\\  /\\\\\\\\\\\     /\\\\\\\\\\\
 * \/\\\///////////  \/////\\\///    /\\\/////////\\\
 *  \/\\\                 \/\\\      \//\\\      \///
 *   \/\\\\\\\\\\\         \/\\\       \////\\\
 *    \/\\\///////          \/\\\          \////\\\
 *     \/\\\                 \/\\\             \////\\\
 *      \/\\\                 \/\\\      /\\\      \//\\\
 *       \/\\\              /\\\\\\\\\\\ \///\\\\\\\\\\\/
 *        \///              \///////////    \///////////
 * ```
 *
 * @memberOf fis.cli
 * @name version
 * @function
 */
cli.version = function() {
  var content = ['',
    '  v' + cli.info.version,
    ''
  ].join('\n');

  var logo;

  if (fis.util.isWin()) {
    logo = [
      ' __' + '/\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'.bold.red + '__' + '/\\\\\\\\\\\\\\\\\\\\\\'.bold.yellow + '_____' + '/\\\\\\\\\\\\\\\\\\\\\\'.bold.green + '___',
      '  _' + '\\/\\\\\\///////////'.bold.red + '__' + '\\/////\\\\\\///'.bold.yellow + '____' + '/\\\\\\/////////\\\\\\'.bold.green + '_' + '       ',
      '   _' + '\\/\\\\\\'.bold.red + '_________________' + '\\/\\\\\\'.bold.yellow + '______' + '\\//\\\\\\'.bold.green + '______' + '\\///'.bold.green + '__',
      '    _' + '\\/\\\\\\\\\\\\\\\\\\\\\\'.bold.red + '_________' + '\\/\\\\\\'.bold.yellow + '_______' + '\\////\\\\\\'.bold.green + '_________' + '     ',
      '     _' + '\\/\\\\\\///////'.bold.red + '__________' + '\\/\\\\\\'.bold.yellow + '__________' + '\\////\\\\\\'.bold.green + '______' + '    ',
      '      _' + '\\/\\\\\\'.bold.red + '_________________' + '\\/\\\\\\'.bold.yellow + '_____________' + '\\////\\\\\\'.bold.green + '___' + '   ',
      '       _' + '\\/\\\\\\'.bold.red + '_________________' + '\\/\\\\\\'.bold.yellow + '______' + '/\\\\\\'.bold.green + '______' + '\\//\\\\\\'.bold.green + '__',
      '        _' + '\\/\\\\\\'.bold.red + '______________' + '/\\\\\\\\\\\\\\\\\\\\\\'.bold.yellow + '_' + '\\///\\\\\\\\\\\\\\\\\\\\\\/'.bold.green + '___',
      '         _' + '\\///'.bold.red + '______________' + '\\///////////'.bold.yellow + '____' + '\\///////////'.bold.green + '_____',
      ''
    ].join('\n');
  } else {
    logo = [
      '   /\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\  /\\\\\\\\\\\\\\\\\\\\\\     /\\\\\\\\\\\\\\\\\\\\\\   ',
      '   \\/\\\\\\///////////  \\/////\\\\\\///    /\\\\\\/////////\\\\\\        ',
      '    \\/\\\\\\                 \\/\\\\\\      \\//\\\\\\      \\///  ',
      '     \\/\\\\\\\\\\\\\\\\\\\\\\         \\/\\\\\\       \\////\\\\\\              ',
      '      \\/\\\\\\///////          \\/\\\\\\          \\////\\\\\\          ',
      '       \\/\\\\\\                 \\/\\\\\\             \\////\\\\\\      ',
      '        \\/\\\\\\                 \\/\\\\\\      /\\\\\\      \\//\\\\\\  ',
      '         \\/\\\\\\              /\\\\\\\\\\\\\\\\\\\\\\ \\///\\\\\\\\\\\\\\\\\\\\\\/   ',
      '          \\///              \\///////////    \\///////////     ',
      ''
    ].join('\n');
  }

  if (fis.get('options.color') !== false) {
    logo = lolcat(logo);
  }
  console.log(content + '\n' + logo);
};

/**
 * fis命令行执行入口。
 * @param  {Array} argv 由 {@link https://github.com/substack/minimist minimist} 解析得到的 argv, 已经转换成了对象。
 * @param  {Array} env  liftoff env
 * @name run
 * @memberOf fis.cli
 * @function
 */
cli.run = function(argv, env) {
  // [node, realPath(bin/fis.js)]
  var argvRaw = process.argv;

  process.title = cli.name +' ' + process.argv.slice(2).join(' ') + ' [ ' + env.cwd + ' ]';

  if (argv.verbose) {
    fis.log.level = fis.log.L_ALL;
  }

  fis.set('options', argv);
  fis.project.setProjectRoot(env.cwd);

   // 如果指定了 media 值
  if (['release', 'inspect'].indexOf(argv._[0]) > -1 && argv._[1]) {
    fis.project.currentMedia(argv._[1]);
  }

  if (env.configPath) {
    try {
      require(env.configPath);
    } catch (e) {
      fis.log.error('Load %s error: %s \n %s', env.configPath, e.message, e.stack);
    }

    fis.emit('conf:loaded');
  }

  if (fis.media().get('options.color') === false) {
    cli.colors.mode = 'none';
  }

  var location = env.modulePath ? path.dirname(env.modulePath) : path.join(__dirname, '../');
  fis.log.info('Currently running %s (%s)', cli.name, location);

  if (!argv._.length) {
    cli[argv.v || argv.version ? 'version' : 'help']();
  } else {

    // tip
    // if (argvRaw[2] === 'release' && !env.modulePath) {
    //   fis.log.warning('Local `fis3` not found, use global version instead.');
    // }

    //fix args
    var p = argvRaw.indexOf('--no-color');
    ~p && argvRaw.splice(p, 1);

    p = argvRaw.indexOf('--media');
    ~p && argvRaw.splice(p, argvRaw[p + 1][0] === '-' ? 1 : 2);

    //register command
    var commander = cli.commander = require('commander');
    var cmd = fis.require('command', argvRaw[2]);

    if (cmd.register) {
      // 兼容旧插件。
      cmd.register(
        commander
        .command(cmd.name || first)
        .usage(cmd.usage)
        .description(cmd.desc)
      );
      commander.parse(argvRaw);
    } else {
      cmd.run(argv, cli, env);
    }
  }
};
<commit_msg>test lib<commit_after>/**
 * 命令行相关的信息和工具类方法暴露在此模块中。
 * @namespace fis.cli
 */
var cli = module.exports = {};

var path = require('path');
var _ = require('./util.js');
var util = require('util');
var lolcat = require('fis-lolcat');

/**
 * 命令行工具名字
 * @memberOf fis.cli
 * @name name
 * @defaultValue fis3
 */
cli.name = 'fis3';

/**
 * 指向 {@link https://www.npmjs.com/package/colors colors} 模块。
 * @memberOf fis.cli
 * @name colors
 */
cli.colors = require('colors');

//commander object
cli.commander = null;

/**
 * package.json 中的信息
 * @memberOf fis.cli
 * @name info
 */
cli.info = fis.util.readJSON(path.dirname(__dirname) + '/package.json');

/**
 * 显示帮助信息，主要用来格式化信息，处理缩进等。fis command 插件，可以用此方法来输出帮助信息。
 *
 * @param  {String} [cmdName]  命令名称
 * @param  {Object} [options]  配置
 * @param  {Array} [commands] 支持的命令集合
 * @memberOf fis.cli
 * @name help
 * @function
 */
cli.help = function(cmdName, options, commands) {
  var strs = [
    '',
    ' Usage: ' + cli.name + ' ' + (cmdName ? cmdName : '<command>')
  ];

  if (!cmdName) {
    commands = {};
    fis.media().get('modules.commands', []).forEach(function(name) {
      var cmd = fis.require('command', name);
      name = cmd.name || name;
      name = fis.util.pad(name, 12);
      commands[name] = cmd.desc || '';
    });

    options =  {
      '-h, --help': 'print this help message',
      '-v, --version': 'print product version and exit',
      '-r, --root <path>': 'specify project root',
      '-f, --file <filename>': 'specify the file path of `fis-conf.js`',
      '--no-color': 'disable colored output',
      '--verbose': 'enable verbose mode'
    };
  }

  options = options || {};
  commands = commands || {};
  var optionsKeys = Object.keys(options);
  var commandsKeys = Object.keys(commands);
  var maxWidth;

  if (commandsKeys.length) {
    maxWidth = commandsKeys.reduce(function(prev, curr) {
      return curr.length > prev ? curr.length : prev;
    }, 0) + 4;

    strs.push(null, ' Commands:', null);

    commandsKeys.forEach(function(key) {
      strs.push(util.format('   %s %s', _.pad(key, maxWidth), commands[key]));
    });
  }

  if (optionsKeys.length) {
    maxWidth = optionsKeys.reduce(function(prev, curr) {
      return curr.length > prev ? curr.length : prev;
    }, 0) + 4;

    strs.push(null, ' Options:', null);

    optionsKeys.forEach(function(key) {
      strs.push(util.format('   %s %s', _.pad(key, maxWidth), options[key]));
    });

    strs.push(null);
  }

  console.log(strs.join('\n'));
};

fis.set('modules.commands', ['init', 'install', 'release', 'server', 'inspect']);

/**
 * 输出 fis 版本信息。
 *
 * ```
 * v3.0.0
 *
 * /\\\\\\\\\\\\\\\  /\\\\\\\\\\\     /\\\\\\\\\\\
 * \/\\\///////////  \/////\\\///    /\\\/////////\\\
 *  \/\\\                 \/\\\      \//\\\      \///
 *   \/\\\\\\\\\\\         \/\\\       \////\\\
 *    \/\\\///////          \/\\\          \////\\\
 *     \/\\\                 \/\\\             \////\\\
 *      \/\\\                 \/\\\      /\\\      \//\\\
 *       \/\\\              /\\\\\\\\\\\ \///\\\\\\\\\\\/
 *        \///              \///////////    \///////////
 * ```
 *
 * @memberOf fis.cli
 * @name version
 * @function
 */
cli.version = function() {
  var content = ['',
    '  v' + cli.info.version,
    ''
  ].join('\n');

  var logo;

  if (fis.util.isWin()) {
    logo = [
      ' __' + '/\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'.bold.red + '__' + '/\\\\\\\\\\\\\\\\\\\\\\'.bold.yellow + '_____' + '/\\\\\\\\\\\\\\\\\\\\\\'.bold.green + '___',
      '  _' + '\\/\\\\\\///////////'.bold.red + '__' + '\\/////\\\\\\///'.bold.yellow + '____' + '/\\\\\\/////////\\\\\\'.bold.green + '_' + '       ',
      '   _' + '\\/\\\\\\'.bold.red + '_________________' + '\\/\\\\\\'.bold.yellow + '______' + '\\//\\\\\\'.bold.green + '______' + '\\///'.bold.green + '__',
      '    _' + '\\/\\\\\\\\\\\\\\\\\\\\\\'.bold.red + '_________' + '\\/\\\\\\'.bold.yellow + '_______' + '\\////\\\\\\'.bold.green + '_________' + '     ',
      '     _' + '\\/\\\\\\///////'.bold.red + '__________' + '\\/\\\\\\'.bold.yellow + '__________' + '\\////\\\\\\'.bold.green + '______' + '    ',
      '      _' + '\\/\\\\\\'.bold.red + '_________________' + '\\/\\\\\\'.bold.yellow + '_____________' + '\\////\\\\\\'.bold.green + '___' + '   ',
      '       _' + '\\/\\\\\\'.bold.red + '_________________' + '\\/\\\\\\'.bold.yellow + '______' + '/\\\\\\'.bold.green + '______' + '\\//\\\\\\'.bold.green + '__',
      '        _' + '\\/\\\\\\'.bold.red + '______________' + '/\\\\\\\\\\\\\\\\\\\\\\'.bold.yellow + '_' + '\\///\\\\\\\\\\\\\\\\\\\\\\/'.bold.green + '___',
      '         _' + '\\///'.bold.red + '______________' + '\\///////////'.bold.yellow + '____' + '\\///////////'.bold.green + '_____',
      ''
    ].join('\n');
  } else {
    logo = [
      '   /\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\  /\\\\\\\\\\\\\\\\\\\\\\     /\\\\\\\\\\\\\\\\\\\\\\   ',
      '   \\/\\\\\\///////////  \\/////\\\\\\///    /\\\\\\/////////\\\\\\        ',
      '    \\/\\\\\\                 \\/\\\\\\      \\//\\\\\\      \\///  ',
      '     \\/\\\\\\\\\\\\\\\\\\\\\\         \\/\\\\\\       \\////\\\\\\              ',
      '      \\/\\\\\\///////          \\/\\\\\\          \\////\\\\\\          ',
      '       \\/\\\\\\                 \\/\\\\\\             \\////\\\\\\      ',
      '        \\/\\\\\\                 \\/\\\\\\      /\\\\\\      \\//\\\\\\  ',
      '         \\/\\\\\\              /\\\\\\\\\\\\\\\\\\\\\\ \\///\\\\\\\\\\\\\\\\\\\\\\/   ',
      '          \\///              \\///////////    \\///////////     ',
      ''
    ].join('\n');
  }

  if (fis.get('options.color') !== false) {
    logo = lolcat(logo);
  }
  console.log(content + '\n' + logo);
};

/**
 * fis命令行执行入口。
 * @param  {Array} argv 由 {@link https://github.com/substack/minimist minimist} 解析得到的 argv, 已经转换成了对象。
 * @param  {Array} env  liftoff env
 * @name run
 * @memberOf fis.cli
 * @function
 */
cli.run = function(argv, env) {
  // [node, realPath(bin/fis.js)]
  var argvRaw = process.argv;

  process.title = cli.name +' ' + process.argv.slice(2).join(' ') + ' [ ' + env.cwd + ' ]';

  if (argv.verbose) {
    fis.log.level = fis.log.L_ALL;
  }

  fis.set('options', argv);
  fis.project.setProjectRoot(env.cwd);

   // 如果指定了 media 值
  if (['release', 'inspect'].indexOf(argv._[0]) > -1 && argv._[1]) {
    fis.project.currentMedia(argv._[1]);
  }

  fis.log.info('Load fis-conf from %s', env.configPath);

  if (env.configPath) {
    try {
      require(env.configPath);
    } catch (e) {
      fis.log.error('Load %s error: %s \n %s', env.configPath, e.message, e.stack);
    }

    fis.emit('conf:loaded');
  }

  if (fis.media().get('options.color') === false) {
    cli.colors.mode = 'none';
  }

  var location = env.modulePath ? path.dirname(env.modulePath) : path.join(__dirname, '../');
  fis.log.info('Currently running %s (%s)', cli.name, location);

  if (!argv._.length) {
    cli[argv.v || argv.version ? 'version' : 'help']();
  } else {

    // tip
    // if (argvRaw[2] === 'release' && !env.modulePath) {
    //   fis.log.warning('Local `fis3` not found, use global version instead.');
    // }

    //fix args
    var p = argvRaw.indexOf('--no-color');
    ~p && argvRaw.splice(p, 1);

    p = argvRaw.indexOf('--media');
    ~p && argvRaw.splice(p, argvRaw[p + 1][0] === '-' ? 1 : 2);

    //register command
    var commander = cli.commander = require('commander');
    var cmd = fis.require('command', argvRaw[2]);

    if (cmd.register) {
      // 兼容旧插件。
      cmd.register(
        commander
        .command(cmd.name || first)
        .usage(cmd.usage)
        .description(cmd.desc)
      );
      commander.parse(argvRaw);
    } else {
      cmd.run(argv, cli, env);
    }
  }
};
<|endoftext|>


<commit_before>#! /usr/bin/env node
import fs from 'graceful-fs'
import Promise from 'bluebird'

import {
    traceModuleTree,
    augmentModuleTree,
    pruneModuleTree,
    generateConfig,
    serializeConfig
} from 'systemjs-config-builder'

const pfs = {}

/**
 * Promisify all fs functions
 */
Object.keys(fs).map(key => {
    if (typeof fs[key] == 'function')
        pfs[key] = Promise.promisify(fs[key]);
})

const config = () => {
    return traceModuleTree(dir)
        .then(augmentModuleTree)
        .then(pruneModuleTree)
        .then(generateConfig)
        .then(serializeConfig)
        .then(pfs.writeFile.bind(null, './generated.config.js'))
}

if (process.argv[2] == 'config') config()
else console.log('At the moment all that SystemJS Tools does is generate a config from node_modules. \n Usage: systemjs config')<commit_msg>Fixed dir listing<commit_after>#! /usr/bin/env node
import fs from 'graceful-fs'
import Promise from 'bluebird'

import {
    traceModuleTree,
    augmentModuleTree,
    pruneModuleTree,
    generateConfig,
    serializeConfig
} from 'systemjs-config-builder'

const pfs = {}

/**
 * Promisify all fs functions
 */
Object.keys(fs).map(key => {
    if (typeof fs[key] == 'function')
        pfs[key] = Promise.promisify(fs[key]);
})

const config = () => {
    return traceModuleTree('.')
        .then(augmentModuleTree)
        .then(pruneModuleTree)
        .then(generateConfig)
        .then(serializeConfig)
        .then(pfs.writeFile.bind(null, './generated.config.js'))
}

if (process.argv[2] == 'config') config()
else console.log('At the moment all that SystemJS Tools does is generate a config from node_modules. \n Usage: systemjs config')<|endoftext|>


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

import chalk from 'chalk';
import path from 'path';
import fs from 'fs-promise';
import meow from 'meow';
import {
  buildTheme
}
from './';

async function listFiles(dirPath) {
  try {
    const filePaths = await fs.readdir(dirPath);
    filePaths
      .map(filePath => filePath.split('.')[0])
      .sort()
      .forEach(fileName => console.log(fileName));
  } catch (error) {
    writeErrorMessage(error);
  }
}

function writeErrorMessage(errorMessage) {
  console.error(chalk.red(errorMessage));
}

function toRelativePath(bar) {
  return path.join(__dirname, bar);
}

(async function() {
  const cli = meow(`Usage:
  $ base16-builder <command>
  $ base16-builder [-s <scheme>] [-t <template>]

Commands:
  ls-schemes List available schemes
  ls-templates List available templates

Options:
  -s, --scheme Build theme using this color scheme
  -t, --template Build theme using this template

Examples:
  $ base16-builder ls-schemes
  $ base16-builder ls-templates

  $ base16-builder -s oceanicnext -t i3wm
  $ base16-builder --scheme oceanicnext --template i3wm`, {
    alias: {
      t: 'template',
      s: 'scheme',
      h: 'help'
    }
  });

  const argument = cli.input[0];
  if (argument === 'ls-schemes') {
    await listFiles(toRelativePath('db/schemes'));
    return;
  } else if (argument === 'ls-templates') {
    await listFiles(toRelativePath('db/templates'));
    return;
  }

  const schemeName = cli.flags.s;
  const templName = cli.flags.t;

  if (!schemeName || !templName) {
    writeErrorMessage('fatal: You did not supply valid arguments. See \'base16-builder -h\' for help/examples.');
    return;
  }

  const templPath = toRelativePath(`db/templates/${templName}.nunjucks`);
  const schemePath = toRelativePath(`db/schemes/${schemeName}.yml`);

  try {
    const templ = await fs.readFile(templPath, 'utf8');
    const scheme = await fs.readFile(schemePath, 'utf8');
    const theme = buildTheme(scheme, templ);

    console.log(theme);
  } catch (e) {
    if (/\/schemes\//.test(e.path)) {
      writeErrorMessage(`Could not find a scheme called \"${schemeName}\". It is likely that no scheme with this
 name exists. For a complete list of schemes, see the database: https://goo.gl/qMu3R5`);
    } else if (/templates/.test(e.path)) {
      writeErrorMessage(`Could not find a template called \"${templName}\". It is likely that no template with this
name exists. For a complete list of templates, see the database: https://goo.gl/6c8djV`);
    }
  }
}());
<commit_msg>refactor(cli): Refactor argument if statement to a switch statement<commit_after>#!/usr/bin/env node

import chalk from 'chalk';
import path from 'path';
import fs from 'fs-promise';
import meow from 'meow';
import {
  buildTheme
}
from './';

async function listFiles(dirPath) {
  try {
    const filePaths = await fs.readdir(dirPath);
    filePaths
      .map(filePath => filePath.split('.')[0])
      .sort()
      .forEach(fileName => console.log(fileName));
  } catch (error) {
    writeErrorMessage(error);
  }
}

function writeErrorMessage(errorMessage) {
  console.error(chalk.red(errorMessage));
}

function toRelativePath(bar) {
  return path.join(__dirname, bar);
}

(async function() {
  const cli = meow(`Usage:
  $ base16-builder <command>
  $ base16-builder [-s <scheme>] [-t <template>]

Commands:
  ls-schemes List available schemes
  ls-templates List available templates

Options:
  -s, --scheme Build theme using this color scheme
  -t, --template Build theme using this template

Examples:
  $ base16-builder ls-schemes
  $ base16-builder ls-templates

  $ base16-builder -s oceanicnext -t i3wm
  $ base16-builder --scheme oceanicnext --template i3wm`, {
    alias: {
      t: 'template',
      s: 'scheme',
      h: 'help'
    }
  });

  const argument = cli.input[0];
  switch (argument) {
    case 'ls-schemes':
      await listFiles(toRelativePath('db/schemes'));
      return;
    case 'ls-templates':
      await listFiles(toRelativePath('db/templates'));
      return;
    default:
  }

  const schemeName = cli.flags.s;
  const templName = cli.flags.t;

  if (!schemeName || !templName) {
    writeErrorMessage('fatal: You did not supply valid arguments. See \'base16-builder -h\' for help/examples.');
    return;
  }

  const templPath = toRelativePath(`db/templates/${templName}.nunjucks`);
  const schemePath = toRelativePath(`db/schemes/${schemeName}.yml`);

  try {
    const templ = await fs.readFile(templPath, 'utf8');
    const scheme = await fs.readFile(schemePath, 'utf8');
    const theme = buildTheme(scheme, templ);

    console.log(theme);
  } catch (e) {
    if (/\/schemes\//.test(e.path)) {
      writeErrorMessage(`Could not find a scheme called \"${schemeName}\". It is likely that no scheme with this
 name exists. For a complete list of schemes, see the database: https://goo.gl/qMu3R5`);
    } else if (/templates/.test(e.path)) {
      writeErrorMessage(`Could not find a template called \"${templName}\". It is likely that no template with this
name exists. For a complete list of templates, see the database: https://goo.gl/6c8djV`);
    }
  }
}());
<|endoftext|>


<commit_before>import { command as createCommand, Error as CliError } from 'clap';
import fs from 'fs';
import * as reporters from './reporter/index.js';
import { validatePath, validateString } from './helpers.js';
import { version } from './version.js';

function errorAndExit(message) {
    console.error(message);
    process.exit(1);
}

async function readStdin() {
    const buffer = [];

    for await (const chunk of process.stdin) {
        buffer.push(chunk);
    }

    return buffer.join('');
}

function printResult(result, reporter) {
    const output = reporter(result);

    if (Object.keys(result).length > 0) {
        errorAndExit(output);
    }

    if (output) {
        console.log(output);
    }
}

const command = createCommand('csstree-validate [fileOrDir]')
    .version(version)
    .option('-r, --reporter <name>', 'Output format: console (default), checkstyle, json, gnu', (name) => {
        if (!hasOwnProperty.call(reporters, name)) {
            errorAndExit('Wrong value for reporter: ' + name);
        }

        return name;
    })
    .action(async ({ options, args }) => {
        const inputPath = args[0];
        const reporter = reporters[options.reporter] || reporters.console;

        if (process.stdin.isTTY && !inputPath) {
            command.run(['--help']);
            return;
        }

        if (!inputPath) {
            readStdin().then(input =>
                printResult(validateString(input, '<stdin>'), reporter)
            );
        } else {
            if (!fs.existsSync(inputPath)) {
                errorAndExit(`ERROR! No such file or directory: ${inputPath}`);
            }

            printResult(validatePath(args[0]), reporter);
        }
    });

export const run = command.run.bind(command);
export function isCliError(err) {
    return err instanceof CliError;
}
<commit_msg>Return throw back<commit_after>import { command as createCommand, Error as CliError } from 'clap';
import fs from 'fs';
import * as reporters from './reporter/index.js';
import { validatePath, validateString } from './helpers.js';
import { version } from './version.js';

function errorAndExit(message) {
    console.error(message);
    process.exit(1);
}

async function readStdin() {
    const buffer = [];

    for await (const chunk of process.stdin) {
        buffer.push(chunk);
    }

    return buffer.join('');
}

function printResult(result, reporter) {
    const output = reporter(result);

    if (Object.keys(result).length > 0) {
        console.error(output);
        process.exit(1);
    }

    if (output) {
        console.log(output);
    }
}

const command = createCommand('csstree-validate [fileOrDir]')
    .version(version)
    .option('-r, --reporter <name>', 'Output format: console (default), checkstyle, json, gnu', (name) => {
        if (!hasOwnProperty.call(reporters, name)) {
            throw new Error('Wrong value for reporter: ' + name);
        }

        return name;
    })
    .action(async ({ options, args }) => {
        const inputPath = args[0];
        const reporter = reporters[options.reporter] || reporters.console;

        if (process.stdin.isTTY && !inputPath) {
            command.run(['--help']);
            return;
        }

        if (!inputPath) {
            readStdin().then(input =>
                printResult(validateString(input, '<stdin>'), reporter)
            );
        } else {
            if (!fs.existsSync(inputPath)) {
                throw new Error(`ERROR! No such file or directory: ${inputPath}`);
            }

            printResult(validatePath(args[0]), reporter);
        }
    });

export const run = command.run.bind(command);
export function isCliError(err) {
    return err instanceof CliError;
}
<|endoftext|>


<commit_before>"use strict";

var url = require("url"),
    path = require("path"),
    fs = require("fs"),
    nopt = require("nopt"),
    cjs = require("./capturejs");

var cli = module.exports = {};

cli.start = function (argv) {
    var knownOpts = {
            uri: url,
            output: path,
            "ssl-protocol": ["sslv3", "sslv2", "tlsv1", "any"],
            "ignore-ssl-errors": [Boolean, "true", "false", "yes", "no"],
            selector: String,
            "user-agent": String,
            "javascript-file": path,
            viewportsize: String,
            "cookies-file": path,
            timeout: Number,
            renderdely: Number,
            zoomfactor: Number,
            help: Boolean,
            version: Boolean
        },
        shortHands = {
            u: "--uri",
            o: "--output",
            p: "---ssl-protocol",
            I: "--ignore-ssl-errors",
            s: "--selector",
            A: "--user-agent",
            J: "--javascript-file",
            V: "--viewportsize",
            c: "--cookies-file",
            T: "--timeout",
            R: "--renderdely",
            z: "--zoomfactor",
            h: "--help",
            v: "--version"
        },
        errors = [],
        parsed;

    nopt.invalidHandler = function (key, val) {
        errors.push("Invalid: --" + key + "=" + val);
    };

    parsed = nopt(knownOpts, shortHands, argv, 0);
    if (parsed.help) {
        var data = fs.readFileSync(path.join(__dirname, "../doc/help.txt"));
        console.error(data.toString("utf-8"));
        process.exit(0);
    }

    if (parsed.version) {
        console.error(require("../package.json").version);
        process.exit(0);
    }

    if (!parsed.uri && parsed.argv.cooked.indexOf("--uri") === -1) {
        errors.push("Missing required: --uri");
    }

    if (!parsed.output) {
        errors.push("Missing required: --output");
    }

    if (errors.length > 0) {
        console.error(errors.join("\n"));
        process.exit(1);
    }

    cjs.capture(parsed);
};
// vim: set fenc=utf-8 ts=4 sts=4 sw=4 :
<commit_msg>Corrected name of "renderdelay" parameter<commit_after>"use strict";

var url = require("url"),
    path = require("path"),
    fs = require("fs"),
    nopt = require("nopt"),
    cjs = require("./capturejs");

var cli = module.exports = {};

cli.start = function (argv) {
    var knownOpts = {
            uri: url,
            output: path,
            "ssl-protocol": ["sslv3", "sslv2", "tlsv1", "any"],
            "ignore-ssl-errors": [Boolean, "true", "false", "yes", "no"],
            selector: String,
            "user-agent": String,
            "javascript-file": path,
            viewportsize: String,
            "cookies-file": path,
            timeout: Number,
            renderdelay: Number,
            zoomfactor: Number,
            help: Boolean,
            version: Boolean
        },
        shortHands = {
            u: "--uri",
            o: "--output",
            p: "---ssl-protocol",
            I: "--ignore-ssl-errors",
            s: "--selector",
            A: "--user-agent",
            J: "--javascript-file",
            V: "--viewportsize",
            c: "--cookies-file",
            T: "--timeout",
            R: "--renderdelay",
            z: "--zoomfactor",
            h: "--help",
            v: "--version"
        },
        errors = [],
        parsed;

    nopt.invalidHandler = function (key, val) {
        errors.push("Invalid: --" + key + "=" + val);
    };

    parsed = nopt(knownOpts, shortHands, argv, 0);
    if (parsed.help) {
        var data = fs.readFileSync(path.join(__dirname, "../doc/help.txt"));
        console.error(data.toString("utf-8"));
        process.exit(0);
    }

    if (parsed.version) {
        console.error(require("../package.json").version);
        process.exit(0);
    }

    if (!parsed.uri && parsed.argv.cooked.indexOf("--uri") === -1) {
        errors.push("Missing required: --uri");
    }

    if (!parsed.output) {
        errors.push("Missing required: --output");
    }

    if (errors.length > 0) {
        console.error(errors.join("\n"));
        process.exit(1);
    }

    cjs.capture(parsed);
};
// vim: set fenc=utf-8 ts=4 sts=4 sw=4 :
<|endoftext|>


<commit_before>/* @flow */

let file;
let format;

import gitBlameStats from './gitBlameStats.js';
import type { BlameStats } from './gitBlameStats.js';

export default function run() {
  parseArguments();
  gitBlameStats(file, (err: ?Error, stats: ?BlameStats) => {
    if (err || !stats) { throw err; }

    if (format === 'json') {
      console.log(stats.committers);
    } else {
      const maxPercentage = stats.committers.reduce((max, committer) => Math.max(max, committer.percentage), 0);

      stats.committers.forEach(function(committer) {
        const percentage = `${committer.percentage * 100}`;

        console.log(
          '%s%s% %s',
          new Array((`${maxPercentage}`).length - percentage.length + 1).join(' '),
          percentage,
          committer.email
        );
      });

      console.log();
      if (stats.pairedLines > 0) {
        console.log('%s lines, %s paired.', stats.totalLines, stats.pairedLines);
      } else {
        console.log('%s lines.', stats.totalLines);
      }
    }
  });
}

function parseArguments() {
  const args = process.argv.slice(2);
  let arg;

  while ((arg = args.shift())) {
    if (arg === '-h' || arg === '--help') {
      usage(0);
    } else if (arg === '-f' || arg === '--format') {
      let next = args.shift();
      if (!next) {
        usage(1);
      } else {
        next = next.toLowerCase();
      }
      if (next !== 'json') {
        usage(1);
      }
      format = next;
    } else if (arg[0] === '-') {
      usage(1);
    } else if (!file) {
      file = arg;
    } else {
      usage(1);
    }
  }

  if (!file) {
    usage(1);
  }
}

function usage(code: ?number=null) {
  console.error('git owner [-f JSON] FILE');
  if (code !== null) {
    process.exit(code);
  }
}
<commit_msg>fix: ensure a single author with 100% ownership prints correctly<commit_after>/* @flow */

let file;
let format;

import gitBlameStats from './gitBlameStats.js';
import type { BlameStats } from './gitBlameStats.js';

export default function run() {
  parseArguments();
  gitBlameStats(file, (err: ?Error, stats: ?BlameStats) => {
    if (err || !stats) { throw err; }

    if (format === 'json') {
      console.log(stats.committers);
    } else {
      const maxPercentage = stats.committers.reduce((max, committer) => Math.max(max, committer.percentage), 0);

      stats.committers.forEach(function(committer) {
        const percentage = `${committer.percentage * 100}`;

        console.log(
          '%s%s% %s',
          new Array((`${maxPercentage * 100}`).length - percentage.length + 1).join(' '),
          percentage,
          committer.email
        );
      });

      console.log();
      if (stats.pairedLines > 0) {
        console.log('%s lines, %s paired.', stats.totalLines, stats.pairedLines);
      } else {
        console.log('%s lines.', stats.totalLines);
      }
    }
  });
}

function parseArguments() {
  const args = process.argv.slice(2);
  let arg;

  while ((arg = args.shift())) {
    if (arg === '-h' || arg === '--help') {
      usage(0);
    } else if (arg === '-f' || arg === '--format') {
      let next = args.shift();
      if (!next) {
        usage(1);
      } else {
        next = next.toLowerCase();
      }
      if (next !== 'json') {
        usage(1);
      }
      format = next;
    } else if (arg[0] === '-') {
      usage(1);
    } else if (!file) {
      file = arg;
    } else {
      usage(1);
    }
  }

  if (!file) {
    usage(1);
  }
}

function usage(code: ?number=null) {
  console.error('git owner [-f JSON] FILE');
  if (code !== null) {
    process.exit(code);
  }
}
<|endoftext|>


<commit_before>'use strict';

var minimist = require('minimist');

exports.run = function() {
  var argv = minimist(process.argv.slice(2));

  // the process:
  // optionally clone a repo
  // enter working directory of repo
  // checkout requested commit
  // launch server
  // launch protractor and website
  // take screenshot
  // shutdown protractor/server
  // repeat
  // done.

};
<commit_msg>cloning and opening repositories<commit_after>'use strict';

var minimist = require('minimist');
var path = require('path');
var git = require('nodegit');

exports.run = function() {
  var argv = minimist(process.argv.slice(2));

  // the process:
  // optionally open configuration file
  // optionally clone a repo

  if (!argv.local) argv.local = './';

  getRepo(argv.url,argv.local).then(function(repo) {
    return repo.getBranchCommit("master");
  }, function (reason) {
    console.log('Couldn\'t get repository: ' + reason);
  }).then(function(commit) {
    return commit.message();
  }).then(function(message) {
    console.log(message);
  });

  // checkout requested commit
  // launch server
  // launch protractor and website
  // take screenshot
  // shutdown protractor/server
  // repeat
  // done.

};

var getRepo = function(repoUrl, localPath) {
  if (!repoUrl) {
    return openRepo(localPath);
  } else {
    return cloneRepo(repoUrl, localPath);
  }
}

var cloneRepo = function(repoUrl, localPath) {
  console.log('Cloning "' + repoUrl +'" into "' + localPath + '"');

  var cloneOptions = {};

  // override cert check for mac os x!
  if (/^https/.test(repoUrl) && process.platform == "darwin") {
    console.log('Warning: overriding certificate check for Mac OS X');
    cloneOptions.remoteCallbacks = {
      certificateCheck: function() { return 1; }
    };
  }

  return git.Clone(repoUrl, localPath, cloneOptions);
};

var openRepo = function(repoPath) {
  console.log('Opening repo "' + repoPath);
  return git.Repository.open(repoPath);;
};
<|endoftext|>


<commit_before>"use strict";

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

var required_properties = ['manifest_version', 'name', 'version'];
var homeDir = process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE;
var filename_template = "<%= pkg.name %>-<%= manifest.version %>.crx";

/**
 * Resolve the home directory of a supposed-path value
 *
 * @param {String} value
 * @returns {String}
 */
function resolveHomeDirectory(value){
  if (homeDir && typeof value === 'string' && value[0] === '~'){
    value = value.replace(/^~/, homeDir);
  }

  return value;
}

/**
 * Initializes the grunt helper
 *
 * @param {grunt} grunt
 * @returns {{build: Function, expandConfiguration: Function, getTaskConfiguration: Function, resolveHomeDirectory: Function}}
 */
exports.init = function(grunt){
  /**
   * Builds a pre-configured chrome extension in 3 steps
   *
   * @api
   * @param {crx} ChromeExtension
   * @param {Function} callback
   * @return null
   */
  function build(ChromeExtension, callback) {
    grunt.file.mkdir(path.dirname(ChromeExtension.dest));

    grunt.util.async.series([
      function(done){
        ChromeExtension.load(done);
      },
      function(done){
        if (!Array.isArray(ChromeExtension.exclude) || !ChromeExtension.exclude.length){
          return done();
        }

        var files = grunt.file.expand(ChromeExtension.exclude.map(function(pattern){
          return path.join(ChromeExtension.path, '/', pattern);
        }));

        grunt.util.async.map(files, rimraf, done);
      },
      function(done){
        ChromeExtension.pack(function(err, data){
          if (err){
            throw new grunt.task.taskError(err);
          }

          grunt.file.write(this.dest, data);

          done();
        });
      }
    ], callback);
  }

  function createObject(taskConfig, defaults){
    taskConfig = expandConfiguration(taskConfig, defaults);

    return new crx(taskConfig);
  }

  /**
   * Refines a task configuration (expand settings etc.)
   *
   * @param {Object} taskConfig
   * @param {Object=} defaults
   * @return {Object}
   */
  function expandConfiguration(taskConfig, defaults){
    defaults = defaults || getTaskConfiguration();
    var config = grunt.util._.defaults({}, taskConfig,  defaults);

    ['dest', 'src'].forEach(function(key){
      if ((Array.isArray(config[key]) && config[key].length === 0) || !config[key]){
        grunt.fail.fatal("You can't specify an empty '"+key+"' configuration value.");
      }
    });

    // XXX (alexeykuzmin): Is there a better way to get source folder path?
    var sourceDir = Array.isArray(config.src) ? config.src[0] : config.src;

    // Eventually expanding `~` in config paths
    ['privateKey', 'src', 'dest'].forEach(function(key){
      config[key] = resolveHomeDirectory(config[key]);
    });

    // Checking availability
    if (!grunt.file.exists(sourceDir)){
      grunt.fail.fatal('Unable to locate source directory.');
    }

    if (!grunt.file.exists(config.privateKey)){
      grunt.fail.fatal('Unable to locate your private key.');
    }
    else{
      config.privateKey = grunt.file.read(config.privateKey);
    }

    // Check extension manifest
    config.manifest = grunt.file.readJSON(path.join(sourceDir, 'manifest.json'));
    required_properties.forEach(function(prop) {
      if ('undefined' === typeof config.manifest[prop]) {
        grunt.fail.fatal('Invalid manifest: property "' + prop + '" is missing.');
      }
    });

    // Expanding destination
    if (grunt.file.isDir(config.dest)){
      var filename = config.filename || filename_template;

      config.dest = path.join(config.dest, filename);
    }

    ['dest'].forEach(function(key){
      config[key] = grunt.template.process(config[key], {
        "data": {
          "manifest": config.manifest,
          "pkg": grunt.file.readJSON('package.json')
        }
      });
    });

    // Codebase generation (@todo cleanup that with clean separation of grunt and chrome extension config)
    config.codebase = config.baseURL || config.codebase || null;

    if (config.codebase && !/.crx$/.test(config.codebase)){
      config.codebase = config.codebase.replace(/\/$/, '');
      config.codebase += '/' + path.basename(config.dest);
    }

    // @todo remove that to better separate grunt config and Chrome Extension config
    // rootDirectory should be a String, not Array
    config.rootDirectory = sourceDir;
    config.maxBuffer = config.options.maxBuffer || config.maxBuffer || undefined;

    return config;
  }

  /**
   * Returns a task configuration profile
   *
   * @param {String=} profile
   * @return {Object}
   */
  function getTaskConfiguration(profile){
    var config;

    profile = profile || 'default';

    config = grunt.file.readJSON(__dirname + '/../data/config-'+ profile +'.json');

    return config;
  }

  /*
   * Blending
   */
  return {
    "build": build,
    "createObject": createObject,
    "expandConfiguration": expandConfiguration,
    "filename": filename_template,
    "getTaskConfiguration": getTaskConfiguration,
    "resolveHomeDirectory": resolveHomeDirectory
  };
};
<commit_msg>Remove unused fs<commit_after>"use strict";

var crx = require('crx');
var path = require('path');
var rimraf = require('rimraf');

var required_properties = ['manifest_version', 'name', 'version'];
var homeDir = process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE;
var filename_template = "<%= pkg.name %>-<%= manifest.version %>.crx";

/**
 * Resolve the home directory of a supposed-path value
 *
 * @param {String} value
 * @returns {String}
 */
function resolveHomeDirectory(value){
  if (homeDir && typeof value === 'string' && value[0] === '~'){
    value = value.replace(/^~/, homeDir);
  }

  return value;
}

/**
 * Initializes the grunt helper
 *
 * @param {grunt} grunt
 * @returns {{build: Function, expandConfiguration: Function, getTaskConfiguration: Function, resolveHomeDirectory: Function}}
 */
exports.init = function(grunt){
  /**
   * Builds a pre-configured chrome extension in 3 steps
   *
   * @api
   * @param {crx} ChromeExtension
   * @param {Function} callback
   * @return null
   */
  function build(ChromeExtension, callback) {
    grunt.file.mkdir(path.dirname(ChromeExtension.dest));

    grunt.util.async.series([
      function(done){
        ChromeExtension.load(done);
      },
      function(done){
        if (!Array.isArray(ChromeExtension.exclude) || !ChromeExtension.exclude.length){
          return done();
        }

        var files = grunt.file.expand(ChromeExtension.exclude.map(function(pattern){
          return path.join(ChromeExtension.path, '/', pattern);
        }));

        grunt.util.async.map(files, rimraf, done);
      },
      function(done){
        ChromeExtension.pack(function(err, data){
          if (err){
            throw new grunt.task.taskError(err);
          }

          grunt.file.write(this.dest, data);

          done();
        });
      }
    ], callback);
  }

  function createObject(taskConfig, defaults){
    taskConfig = expandConfiguration(taskConfig, defaults);

    return new crx(taskConfig);
  }

  /**
   * Refines a task configuration (expand settings etc.)
   *
   * @param {Object} taskConfig
   * @param {Object=} defaults
   * @return {Object}
   */
  function expandConfiguration(taskConfig, defaults){
    defaults = defaults || getTaskConfiguration();
    var config = grunt.util._.defaults({}, taskConfig,  defaults);

    ['dest', 'src'].forEach(function(key){
      if ((Array.isArray(config[key]) && config[key].length === 0) || !config[key]){
        grunt.fail.fatal("You can't specify an empty '"+key+"' configuration value.");
      }
    });

    // XXX (alexeykuzmin): Is there a better way to get source folder path?
    var sourceDir = Array.isArray(config.src) ? config.src[0] : config.src;

    // Eventually expanding `~` in config paths
    ['privateKey', 'src', 'dest'].forEach(function(key){
      config[key] = resolveHomeDirectory(config[key]);
    });

    // Checking availability
    if (!grunt.file.exists(sourceDir)){
      grunt.fail.fatal('Unable to locate source directory.');
    }

    if (!grunt.file.exists(config.privateKey)){
      grunt.fail.fatal('Unable to locate your private key.');
    }
    else{
      config.privateKey = grunt.file.read(config.privateKey);
    }

    // Check extension manifest
    config.manifest = grunt.file.readJSON(path.join(sourceDir, 'manifest.json'));
    required_properties.forEach(function(prop) {
      if ('undefined' === typeof config.manifest[prop]) {
        grunt.fail.fatal('Invalid manifest: property "' + prop + '" is missing.');
      }
    });

    // Expanding destination
    if (grunt.file.isDir(config.dest)){
      var filename = config.filename || filename_template;

      config.dest = path.join(config.dest, filename);
    }

    ['dest'].forEach(function(key){
      config[key] = grunt.template.process(config[key], {
        "data": {
          "manifest": config.manifest,
          "pkg": grunt.file.readJSON('package.json')
        }
      });
    });

    // Codebase generation (@todo cleanup that with clean separation of grunt and chrome extension config)
    config.codebase = config.baseURL || config.codebase || null;

    if (config.codebase && !/.crx$/.test(config.codebase)){
      config.codebase = config.codebase.replace(/\/$/, '');
      config.codebase += '/' + path.basename(config.dest);
    }

    // @todo remove that to better separate grunt config and Chrome Extension config
    // rootDirectory should be a String, not Array
    config.rootDirectory = sourceDir;
    config.maxBuffer = config.options.maxBuffer || config.maxBuffer || undefined;

    return config;
  }

  /**
   * Returns a task configuration profile
   *
   * @param {String=} profile
   * @return {Object}
   */
  function getTaskConfiguration(profile){
    var config;

    profile = profile || 'default';

    config = grunt.file.readJSON(__dirname + '/../data/config-'+ profile +'.json');

    return config;
  }

  /*
   * Blending
   */
  return {
    "build": build,
    "createObject": createObject,
    "expandConfiguration": expandConfiguration,
    "filename": filename_template,
    "getTaskConfiguration": getTaskConfiguration,
    "resolveHomeDirectory": resolveHomeDirectory
  };
};
<|endoftext|>


<commit_before>'use strict';

function reducer(item, memo, sep, prependSep) {
  var foo = ''
  , c = new RegExp(sep, 'g')
  , q = new RegExp('"', 'g')
  , n = new RegExp('\n', 'g');

  if (!item) {
    item = '';
  }
  if (typeof item != 'string') {
    var s = item.toString();
    if (s == '[object Object]') {
      item = JSON.stringify(item);
      if (item == '{}') {
        item = '';
      }
    }
    else {
      item = s;
    }
  }
  if (memo || prependSep) {
    foo = memo + sep;
  }
  if (item.search(c) >= 0 || item.search(q) >= 0 || item.search(n) >= 0) {
    foo += '"' + item.replace(q, '""') + '"';
  }
  else {
    foo += ''+item;
  }
  return foo;
}

exports.eol = "\r\n";
exports.separator = ",";

exports.detect = function (input)
{
  var separators = [{c: 0, v: ','}, {c: 0, v: ';'}, {c: 0, v: '|'}, {c: 0, v: '\t'}, {c: 0, v: null}];
  separators.forEach(function (item, indice) {
      item.c += input.split(item.v).length;
    }
  );
  var max = 0;
  var separator = separators.reduce(function (prev, cur) {
      if (cur.c >= max) {
        max = cur.c;
        return cur.v;
      }
      else {
        return prev;
      }
    }, null
  );
  return separator;
}

exports.stringify = function (input, sep) {
  var ret = '';
  sep = sep || exports.separator;
  if (Array.isArray(input) && !Array.isArray(input[0])) {
    /*
    input.forEach(function (item) {
        ret = reducer(item, ret, sep);
      }
    );
     */

    for(var loop = 0; loop < input.length; loop++) {
      ret = reducer(input[loop], ret, sep, loop > 0);
    }
    ret += exports.eol;
  }
  else if (Array.isArray(input) && Array.isArray(input[0])) {
    input.forEach(function (item, index) {
        ret += exports.stringify(item, sep);
      }
    );
  }
  else if (typeof input == 'object') {
    for (var key in input) {
      if (input.hasOwnProperty(key)) {
        ret = reducer(input[key], ret, sep);
      }
    }
    ret += exports.eol;
  }
  else {
    ret = reducer(input, ret, sep) + exports.eol;
  }
  return ret;
}

exports.parse = function (input, sep) {

  var output = [];
  exports.forEach(input, sep, function (row, index) {
      output.push(row);
    }
  )
  return output;
}

exports.forEach = function (input, sep, callback) {
  if (arguments.length < 3) {
    callback = sep;
    sep = ',';
  }
  var i = 0, s = 0, r;
  while (r = exports.read(input.slice(s), sep, function (fields) {
        callback(fields, i++);
      }
    )
  ) {
    s += r;
  }
}

exports.read = function (input, sep, callback) {
  sep = sep || ",";
  var fields = [], reminderIndex = 0, token = '', endingIndex = 0, endingLine = 0, startingIndex = 0,
      sepx = new RegExp('[^\\s' + sep + ']+.');

    //console.log('input:', input);
    //console.log('input.length:', input.length);
    //console.log('sep:', sep);
  while (startingIndex <= input.length) {
    endingIndex = input.indexOf(sep, startingIndex);
    endingLine = input.indexOf('\n', startingIndex);
        //console.log('startingIndex:', startingIndex);
        //console.log('endingIndex:', endingIndex);
        //console.log('endingLine:', endingLine);

    if (endingIndex < 0) {
      endingIndex = input.length;
    }
    token = input.slice(startingIndex, endingIndex).trim();
    if (token.charAt(0) == '"' && token.charAt(token.length - 1) == '"') {
       //console.log('D : "token" =>', token);
      fields.push(token.slice(1, -1).replace(/\"\"/g, '"'));
      startingIndex = endingIndex + 1;
    }
    else if (token.charAt(0) == '"') {
       //console.log('A : "token =>', token);
       var s = input.slice(startingIndex + 1);
       if (s.indexOf('"') < 0) {
         reminderIndex = startingIndex;
         callback(fields);
         return reminderIndex;
       }
       else {
         var i = s.search(/[^\"]\"(?!\")/) + 1;
         if (i === 0 /* -1 + 1 */) {
          i = s.search(/[^\"]\"\"\"(?!\")/) + 3;
         }
          fields.push(input.slice(startingIndex + 1, startingIndex + i + 1).replace(/\"\"/g, '"'));
          var j = input.slice(startingIndex + i + 2).search(sepx);
          startingIndex += i + 2 + (j >= 0 ? j : 0);
        }
    }
    else if (endingLine >= 0 && endingLine < endingIndex) {
      if (input.charAt(endingLine - 1) === '\r') {
        fields.push(input.slice(startingIndex, endingLine - 1));
      }
      else {
        fields.push(input.slice(startingIndex, endingLine));
      }
      reminderIndex = endingLine + 1;
      callback(fields);
      return reminderIndex;
    }
    else if (token.charAt(token.length - 1) == '"') {
       //console.log('C : token" =>', token);

      fields.push(input.slice(startingIndex, endingIndex));
      startingIndex = endingIndex + 1;
    }
    else {
      // console.log('B : token =>', token);
      //      console.log(endingLine, '<', endingIndex);
      fields.push(input.slice(startingIndex, endingIndex));
      startingIndex = endingIndex + 1;
    }
  }
  reminderIndex = null;
  callback(fields);
  return reminderIndex;
}

exports.fetch = function (input, sep) {
  var output;
  exports.read(input, sep, function (fields) {
      output = fields;
    }
  );
  return output;

}
<commit_msg>Added test and fix for new use case<commit_after>'use strict';

function reducer(item, memo, sep, prependSep) {
  var foo = ''
  , c = new RegExp(sep, 'g')
  , q = new RegExp('"', 'g')
  , n = new RegExp('\n', 'g');

  if (!item) {
    item = '';
  }
  if (typeof item != 'string') {
    var s = item.toString();
    if (s == '[object Object]') {
      item = JSON.stringify(item);
      if (item == '{}') {
        item = '';
      }
    }
    else {
      item = s;
    }
  }
  if (memo || prependSep) {
    foo = memo + sep;
  }
  if (item.search(c) >= 0 || item.search(q) >= 0 || item.search(n) >= 0) {
    foo += '"' + item.replace(q, '""') + '"';
  }
  else {
    foo += ''+item;
  }
  return foo;
}

exports.eol = "\r\n";
exports.separator = ",";

exports.detect = function (input)
{
  var separators = [{c: 0, v: ','}, {c: 0, v: ';'}, {c: 0, v: '|'}, {c: 0, v: '\t'}, {c: 0, v: null}];
  separators.forEach(function (item, indice) {
      item.c += input.split(item.v).length;
    }
  );
  var max = 0;
  var separator = separators.reduce(function (prev, cur) {
      if (cur.c >= max) {
        max = cur.c;
        return cur.v;
      }
      else {
        return prev;
      }
    }, null
  );
  return separator;
}

exports.stringify = function (input, sep) {
  var ret = '';
  sep = sep || exports.separator;
  if (Array.isArray(input) && !Array.isArray(input[0])) {
    for(var loop = 0; loop < input.length; loop++) {
      ret = reducer(input[loop], ret, sep, loop > 0);
    }
    ret += exports.eol;
  }
  else if (Array.isArray(input) && Array.isArray(input[0])) {
    input.forEach(function (item, index) {
        ret += exports.stringify(item, sep);
      }
    );
  }
  else if (typeof input == 'object') {
    for (var key in input) {
      if (input.hasOwnProperty(key)) {
        ret = reducer(input[key], ret, sep);
      }
    }
    ret += exports.eol;
  }
  else {
    ret = reducer(input, ret, sep) + exports.eol;
  }
  return ret;
}

exports.parse = function (input, sep) {

  var output = [];
  exports.forEach(input, sep, function (row, index) {
      output.push(row);
    }
  )
  return output;
}

exports.forEach = function (input, sep, callback) {
  if (arguments.length < 3) {
    callback = sep;
    sep = ',';
  }
  var i = 0, s = 0, r;
  while (r = exports.read(input.slice(s), sep, function (fields) {
        callback(fields, i++);
      }
    )
  ) {
    s += r;
  }
}

exports.read = function (input, sep, callback) {
  sep = sep || ",";
  var fields = [], reminderIndex = 0, token = '', endingIndex = 0, endingLine = 0, startingIndex = 0,
      sepx = new RegExp('[^\\s' + sep + ']+.');

    //console.log('input:', input);
    //console.log('input.length:', input.length);
    //console.log('sep:', sep);
  while (startingIndex <= input.length) {
    endingIndex = input.indexOf(sep, startingIndex);
    endingLine = input.indexOf('\n', startingIndex);
        //console.log('startingIndex:', startingIndex);
        //console.log('endingIndex:', endingIndex);
        //console.log('endingLine:', endingLine);

    if (endingIndex < 0) {
      endingIndex = input.length;
    }
    token = input.slice(startingIndex, endingIndex).trim();
    if (token.charAt(0) == '"' && token.charAt(token.length - 1) == '"') {
       //console.log('D : "token" =>', token);
      fields.push(token.slice(1, -1).replace(/\"\"/g, '"'));
      startingIndex = endingIndex + 1;
    }
    else if (token.charAt(0) == '"') {
       //console.log('A : "token =>', token);
       var s = input.slice(startingIndex + 1);
       if (s.indexOf('"') < 0) {
         reminderIndex = startingIndex;
         callback(fields);
         return reminderIndex;
       }
       else {
         var i = s.search(/[^\"]\"(?!\")/) + 1;
         if (i === 0 /* -1 + 1 */) {
          i = s.search(/[^\"]\"\"\"(?!\")/) + 3;
         }
          fields.push(input.slice(startingIndex + 1, startingIndex + i + 1).replace(/\"\"/g, '"'));
          var j = input.slice(startingIndex + i + 2).search(sepx);
          startingIndex += i + 2 + (j >= 0 ? j : 0);
        }
    }
    else if (endingLine >= 0 && endingLine < endingIndex) {
      if (input.charAt(endingLine - 1) === '\r') {
        fields.push(input.slice(startingIndex, endingLine - 1));
      }
      else {
        fields.push(input.slice(startingIndex, endingLine));
      }
      reminderIndex = endingLine + 1;
      callback(fields);
      return reminderIndex;
    }
    else if (token.charAt(token.length - 1) == '"') {
       //console.log('C : token" =>', token);

      fields.push(input.slice(startingIndex, endingIndex));
      startingIndex = endingIndex + 1;
    }
    else {
      // console.log('B : token =>', token);
      //      console.log(endingLine, '<', endingIndex);
      fields.push(input.slice(startingIndex, endingIndex));
      startingIndex = endingIndex + 1;
    }
  }
  reminderIndex = null;
  callback(fields);
  return reminderIndex;
}

exports.fetch = function (input, sep) {
  var output;
  exports.read(input, sep, function (fields) {
      output = fields;
    }
  );
  return output;

}
<|endoftext|>


<commit_before>/**
 * [cut image]
 * @param  {[Number]} x      x coordinate of source image
 * @param  {[Number]} y      y coordinate of source image
 * @param  {[Number]} width  desimage width
 * @param  {[Number]} height desimage height
 * @return {[tufu]} current tufu
 */
module.exports = cut = function(x,y,width,height) {
	var row = y+height,
		sourceWidth = this.imageData.width,
		sourceData = this.imageData.data,
		tempData = [],
		start=0,
		offset=0;

	for (var i = y; i < row; i++) {
		start = (i*sourceWidth+x)*4;
		offset = width*4;
		tempData = tempData.concat(sourceData.slice(start,start+offset));
	}

	tempData = Buffer.concat(tempData);

	this.imageData = {
		data:tempData,
		width:width,
		height:height
	};

	return this;
};<commit_msg>fix cut<commit_after>/**
 * [cut image]
 * @param  {[Number]} x      x coordinate of source image
 * @param  {[Number]} y      y coordinate of source image
 * @param  {[Number]} width  desimage width
 * @param  {[Number]} height desimage height
 * @return {[tufu]} current tufu
 */
module.exports = cut = function(x,y,width,height) {
	var row = y+height,
		sourceWidth = this.imageData.width,
		sourceData = this.imageData.data,
		tempData = [],
		start=0,
		offset=0;

	for (var i = y; i < row; i++) {
		start = (i*sourceWidth+x)*4;
		offset = width*4;
		tempData = tempData.concat(sourceData.slice(start,start+offset));
	}

//	tempData = Buffer.concat(tempData);

	this.imageData = {
		data:tempData,
		width:width,
		height:height
	};

	return this;
};
<|endoftext|>


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

module.exports = function(input, output, settings, cli) {
  return new Env(input, output, settings, cli);
};

function Env(input, output, settings, cli) {
  // shortcuts
  var join = path.join;

  // electrify version
  this.version = '2.0.1';

  // is running through cli?
  this.running_through_cli = !!cli;

  // is in development mode?
  this.is_development_mode = (process.env.DEVELECTRIFY == 'true');

  // is not running in test mode
  this.is_running_tests = (process.env.TESTELECTRIFY == 'true');

  // default stdio config for child processes
  var log_levels = process.env.LOGELECTRIFY || '';
  this.stdio = /TRACE|ALL/i.test(log_levels) ? 'inherit' : 'ignore';

  // platform and arch type
  this.sys = {};
  this.sys.platform   = process.platform;
  this.sys.arch       = process.arch;
  this.sys.is_windows = (process.platform == 'win32');
  this.sys.is_linux   = (process.platform == 'linux');
  this.sys.is_osx     = (process.platform == 'darwin');

  // operational System
  this.os = {
    name : (this.sys.platform === 'darwin' ? 'osx' : this.sys.platform),
    home : process.env[(this.sys.is_windows ? 'USERPROFILE' : 'HOME')],
    tmp  : os.tmpdir()
  };

  // app main paths
  this.app = {};
  this.app.root = path.resolve(input);
  this.app.meteor = join(this.app.root, '..');

  // .electrify folder will only exist in development mode, not after packaged
  if(/\.electrify$/m.test(this.app.root))
    this.app.is_packaged = false;
  else
    this.app.is_packaged = true;

  this.app.isnt_packaged = !this.app.is_packaged;

  this.app.bin         = join(this.app.root, 'bin');
  this.app.dist        = output || join(this.app.root, '.dist');
  this.app.config_path = join(this.app.root, 'electrify.json');

  if(this.app.is_packaged) {
    this.app.settings = require(join(this.app.root, 'app', 'settings.json'));
  }
  else if(process.env.ELECTRIFY_SETTINGS_FILE)
    this.app.settings = require(process.env.ELECTRIFY_SETTINGS_FILE);
  else
    this.app.settings = settings || {};

  // internal electron distro
  this.core = {};
  this.core.tmp       = join(this.os.tmp, 'electrify');
  this.core.root      = join(this.core.tmp, 'core');

  // meteor's info from system (only in development)
  if(this.is_development_mode) {

    var meteor_dir, meteor_bat, meteor_symlink;

    this.meteor = {};

    if (this.sys.is_windows) {
      meteor_dir     = join(this.os.home, 'AppData', 'Local', '.meteor');
      meteor_bat     = join(meteor_dir, 'meteor.bat');
      meteor_symlink = fs.readFileSync(meteor_bat).toString();
      meteor_symlink = meteor_symlink.match(/\\packages.*\\meteor\.bat/)[0];
    }
    else {
      meteor_dir    = join(this.os.home, '.meteor');
      meteor_symlink = fs.readlinkSync(join(meteor_dir, 'meteor'));
    }

    this.meteor.root           = join(meteor_dir, meteor_symlink);
    this.meteor.tools          = this.meteor.root.replace(/meteor(\.bat)?$/m, '');
    this.meteor.dev_bundle     = join(this.meteor.tools, 'dev_bundle');
    this.meteor.server_lib     = join(this.meteor.dev_bundle, 'server-lib');
    this.meteor.server_modules = join(this.meteor.server_lib, 'node_modules');

    if(this.sys.is_windows)
      this.meteor.node_mods = join(this.meteor.dev_bundle, 'bin', 'node_modules');
    else
      this.meteor.node_mods = join(this.meteor.dev_bundle, 'lib', 'node_modules');

    this.meteor.node   = join(this.meteor.dev_bundle, 'bin', 'node');
    this.meteor.npm    = join(this.meteor.node_mods, 'npm', 'bin', 'npm-cli.js');
    this.meteor.mongo  = join(this.meteor.dev_bundle, 'mongodb', 'bin', 'mongo');
    this.meteor.mongod = join(this.meteor.dev_bundle, 'mongodb', 'bin', 'mongod');

    if(this.sys.is_windows) {
      this.meteor.node  += '.exe';
      this.meteor.mongo  += '.exe';
      this.meteor.mongod += '.exe';
    }
  }

  if(this.stdio == 'inherit') {
    console.log('====================================');
    console.log(JSON.stringify(this, null, 2));
    console.log('====================================');
  }
}<commit_msg>fixing conditional<commit_after>var path = require('path');
var fs   = require('fs');
var os   = require('os');

module.exports = function(input, output, settings, cli) {
  return new Env(input, output, settings, cli);
};

function Env(input, output, settings, cli) {
  // shortcuts
  var join = path.join;

  // electrify version
  this.version = '2.0.1';

  // is running through cli?
  this.running_through_cli = !!cli;

  // is in development mode?
  this.is_development_mode = (process.env.DEVELECTRIFY == 'true');

  // is not running in test mode
  this.is_running_tests = (process.env.TESTELECTRIFY == 'true');

  // default stdio config for child processes
  var log_levels = process.env.LOGELECTRIFY || '';
  this.stdio = /TRACE|ALL/i.test(log_levels) ? 'inherit' : 'ignore';

  // platform and arch type
  this.sys = {};
  this.sys.platform   = process.platform;
  this.sys.arch       = process.arch;
  this.sys.is_windows = (process.platform == 'win32');
  this.sys.is_linux   = (process.platform == 'linux');
  this.sys.is_osx     = (process.platform == 'darwin');

  // operational System
  this.os = {
    name : (this.sys.platform === 'darwin' ? 'osx' : this.sys.platform),
    home : process.env[(this.sys.is_windows ? 'USERPROFILE' : 'HOME')],
    tmp  : os.tmpdir()
  };

  // app main paths
  this.app = {};
  this.app.root = path.resolve(input);
  this.app.meteor = join(this.app.root, '..');

  // .electrify folder will only exist in development mode, not after packaged
  if(/\.electrify$/m.test(this.app.root))
    this.app.is_packaged = false;
  else
    this.app.is_packaged = true;

  this.app.isnt_packaged = !this.app.is_packaged;

  this.app.bin         = join(this.app.root, 'bin');
  this.app.dist        = output || join(this.app.root, '.dist');
  this.app.config_path = join(this.app.root, 'electrify.json');

  if(this.app.is_packaged) {
    this.app.settings = require(join(this.app.root, 'app', 'settings.json'));
  }
  else if(process.env.ELECTRIFY_SETTINGS_FILE)
    this.app.settings = require(process.env.ELECTRIFY_SETTINGS_FILE);
  else
    this.app.settings = settings || {};

  // internal electron distro
  this.core = {};
  this.core.tmp       = join(this.os.tmp, 'electrify');
  this.core.root      = join(this.core.tmp, 'core');

  // meteor's info from system (only when not packaged yet)
  if(this.app.isnt_packaged) {

    var meteor_dir, meteor_bat, meteor_symlink;

    this.meteor = {};

    if (this.sys.is_windows) {
      meteor_dir     = join(this.os.home, 'AppData', 'Local', '.meteor');
      meteor_bat     = join(meteor_dir, 'meteor.bat');
      meteor_symlink = fs.readFileSync(meteor_bat).toString();
      meteor_symlink = meteor_symlink.match(/\\packages.*\\meteor\.bat/)[0];
    }
    else {
      meteor_dir    = join(this.os.home, '.meteor');
      meteor_symlink = fs.readlinkSync(join(meteor_dir, 'meteor'));
    }

    this.meteor.root           = join(meteor_dir, meteor_symlink);
    this.meteor.tools          = this.meteor.root.replace(/meteor(\.bat)?$/m, '');
    this.meteor.dev_bundle     = join(this.meteor.tools, 'dev_bundle');
    this.meteor.server_lib     = join(this.meteor.dev_bundle, 'server-lib');
    this.meteor.server_modules = join(this.meteor.server_lib, 'node_modules');

    if(this.sys.is_windows)
      this.meteor.node_mods = join(this.meteor.dev_bundle, 'bin', 'node_modules');
    else
      this.meteor.node_mods = join(this.meteor.dev_bundle, 'lib', 'node_modules');

    this.meteor.node   = join(this.meteor.dev_bundle, 'bin', 'node');
    this.meteor.npm    = join(this.meteor.node_mods, 'npm', 'bin', 'npm-cli.js');
    this.meteor.mongo  = join(this.meteor.dev_bundle, 'mongodb', 'bin', 'mongo');
    this.meteor.mongod = join(this.meteor.dev_bundle, 'mongodb', 'bin', 'mongod');

    if(this.sys.is_windows) {
      this.meteor.node  += '.exe';
      this.meteor.mongo  += '.exe';
      this.meteor.mongod += '.exe';
    }
  }

  if(this.stdio == 'inherit') {
    console.log('====================================');
    console.log(JSON.stringify(this, null, 2));
    console.log('====================================');
  }
}<|endoftext|>


<commit_before>/** section: nodeca.core
 *  lib.env(options) -> Object
 *
 *  Create new requet environment object.
 **/

'use strict';

/*global nodeca, _*/

module.exports = function env(options) {
  var ctx = {
    extras:  {},
    helpers: {
      asset_path: function asset_path(path) {
        var asset = nodeca.runtime.assets.environment.findAsset(path);
        return !asset ? "#" : ("/assets/" + asset.digestPath);
      }
    },
    origin: {
      http:     options.http,
      realtime: options.realtime
    },
    skip: (options.skip || []).slice(),
    // FIXME: should be filled by session middleware
    session: options.session || {
      theme:  'desktop',
      locale: nodeca.config.locales['default']
    },
    request: {
      // FIXME: should be deprecated in flavour of env.origin
      origin:     !!options.realtime ? 'RT' : 'HTTP',
      method:     options.method,
      namespace:  options.method.split('.').shift()
    },
    data: {},
    response: {
      data: {
        head: {
          title: null, // should be filled with default value
          route: options.method,
          // List of assets for yepnope,
          // Each element is an object with properties:
          //
          //    type:   css|js
          //    link:   asset_url
          //
          // example: assets.push({type: 'js', link: '//example.com/foo.js'});
          assets: []
        },
        menus: {},
        widgets: {}
      },
      headers: {},
      // Layouts are supporting "nesting" via `dots:
      //
      //    default.blogs
      //
      // In the example above, `default.blogs` will be rendered first and the
      // result will be provided for rendering to `default`.
      layout: options.layout || 'default',
      view: options.method
    }
  };

  //
  // env-dependent helper needs to be bounded to env
  //

  ctx.helpers.t = function (phrase, params) {
    return nodeca.runtime.i18n.t(this.session.locale, phrase, params);
  }.bind(ctx);

  //
  // deprecated helpers should go soon
  //

  ctx.t = function () {
    try {
      throw new Error('env.t is deprecated. Use env.heplers.t instead');
    } catch (err) {
      nodeca.logger.warn(err.stack);
      return ctx.helpers.t.apply(null, arguments);
    }
  };

  return ctx;
};
<commit_msg>Remove deprecated helper<commit_after>/** section: nodeca.core
 *  lib.env(options) -> Object
 *
 *  Create new requet environment object.
 **/

'use strict';

/*global nodeca, _*/

module.exports = function env(options) {
  var ctx = {
    extras:  {},
    helpers: {
      asset_path: function asset_path(path) {
        var asset = nodeca.runtime.assets.environment.findAsset(path);
        return !asset ? "#" : ("/assets/" + asset.digestPath);
      }
    },
    origin: {
      http:     options.http,
      realtime: options.realtime
    },
    skip: (options.skip || []).slice(),
    // FIXME: should be filled by session middleware
    session: options.session || {
      theme:  'desktop',
      locale: nodeca.config.locales['default']
    },
    request: {
      // FIXME: should be deprecated in flavour of env.origin
      origin:     !!options.realtime ? 'RT' : 'HTTP',
      method:     options.method,
      namespace:  options.method.split('.').shift()
    },
    data: {},
    response: {
      data: {
        head: {
          title: null, // should be filled with default value
          route: options.method,
          // List of assets for yepnope,
          // Each element is an object with properties:
          //
          //    type:   css|js
          //    link:   asset_url
          //
          // example: assets.push({type: 'js', link: '//example.com/foo.js'});
          assets: []
        },
        menus: {},
        widgets: {}
      },
      headers: {},
      // Layouts are supporting "nesting" via `dots:
      //
      //    default.blogs
      //
      // In the example above, `default.blogs` will be rendered first and the
      // result will be provided for rendering to `default`.
      layout: options.layout || 'default',
      view: options.method
    }
  };

  //
  // env-dependent helper needs to be bounded to env
  //

  ctx.helpers.t = function (phrase, params) {
    return nodeca.runtime.i18n.t(this.session.locale, phrase, params);
  }.bind(ctx);

  return ctx;
};
<|endoftext|>


<commit_before>module.exports = {
  "rules": {
    // require braces around arrow function bodies
    "arrow-body-style": "error",
    // require parentheses around arrow function arguments
    "arrow-parens": [ "error", "as-needed" ],
    // enforce consistent spacing before and after the arrow in arrow functions
    "arrow-spacing": "error",
    // enforce consistent spacing around * operators in generator functions
    "generator-star-spacing": ["error", {"before": false, "after": true}],
    // disallow arrow functions where they could be confused with comparisons
    "no-confusing-arrow": "error",
    // disallow duplicate module imports
    "no-duplicate-imports": "error",
    // disallow specified modules when loaded by import
    "no-restricted-imports:": "off"
  }
}<commit_msg>feat: add rules<commit_after>module.exports = {
  "rules": {
    // require braces around arrow function bodies
    "arrow-body-style": "error",
    // require parentheses around arrow function arguments
    "arrow-parens": [ "error", "as-needed" ],
    // enforce consistent spacing before and after the arrow in arrow functions
    "arrow-spacing": "error",
    // enforce consistent spacing around * operators in generator functions
    "generator-star-spacing": ["error", {"before": false, "after": true}],
    // disallow arrow functions where they could be confused with comparisons
    "no-confusing-arrow": "error",
    // disallow duplicate module imports
    "no-duplicate-imports": "error",
    // disallow specified modules when loaded by import
    "no-restricted-imports:": "off",
    // disallow unnecessary computed property keys in object literals
    "no-useless-computed-key": "error",
  }
}<|endoftext|>


<commit_before>/**
 * SubdomainHandler
 *
 * This runs on all routes and manipulates the req.url to include the tag
 * as the first parameter (/:tag/foo/bar). This then triggers different route listeners.
 * It is important because it transforms the fragile subdomain mesh tag into a more
 * tageable route parameter that is easily retrievable in later route middleware.
 *
 * USAGE:
 *
 *		// add express-subdomain-handler to your express middleware stack
 *		app.use( require('express-subdomain-handler')({ baseUrl: 'example.com', prefix: 'myprefix', logger: true, ignoreExtensions:[".css", ".js", ".html", ".jpg", ".png", ".svg", ".gif",".woff", ".ttf"]}) );
 *
 *		// setup routes to catch subdomain urls
 *		// eg. 'http://mysubdomain.example.com/homepage'
 *		app.get('/myprefix/:thesubdomain/thepage', function(req, res, next){
 *
 *			// for the example url this will print 'mysubdomain'
 *			res.send(req.params.thesubdomain);
 *
 *		});
 */

function _escapeRegExp(str) {
	return str.replace(/[-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}

/**
 * Creates the custom regex object from the specified baseUrl
 *
 * @param  {string} baseUrl [description]
 * @return {Object} the regex object
 */
function subdomainRegex(baseUrl){
	var regex;

	baseUrl = _escapeRegExp(baseUrl);

	regex = new RegExp('((?!www)\\b[-\\w\\.]+)\\.' + baseUrl + '(?::)?(?:\d+)?');

	return regex;
}

module.exports = function(options){

	// prefix default
	options.prefix = options.prefix || 'subdomain';

	// logger default
	options.logger = (options.logger === true) ? true : false;

	// allow 'base' or 'baseUrl'
	options.baseUrl = options.baseUrl || options.base;

	// ignore extensions
	options.ignoreExtensions = options.ignoreExtensions || [];

	// return error if no baseUrl was specified
	if(!options.baseUrl) return next("express-subdomain-handler: You haven't specified a baseUrl, this is required!");

	if(options.logger) console.log("\nESH: Rewriting all subdomain routes to /%s/[subdomain1]/[subdomain2]/path/after/baseurl for baseUrl %s \n", options.prefix, options.baseUrl);

	// the returned function
	return function(req, res, next){
		var i,

		// original req.url
		originalUrl = req.headers.host + req.url,

		// create our subdomain regex
		regex = subdomainRegex(options.baseUrl),

		// extract the subdomain string from the req.url
		subdomainString = regex.exec(req.headers.host);

		// if there is no subdomain, return
		if(!subdomainString) return next();

		// if there files with below extentions so don't apply subdomain logic
		for(var i=0;i<options.ignoreExtensions.length;i++){
			if(req.url.indexOf(options.ignoreExtensions[i])>0){
				return next();
			}
		}

		// create an array of subdomains
		subdomainArray = subdomainString[1].split('.');

		// cache number of subdomains
		i = subdomainArray.length;

		// prepend each subdomain in reverse order
		while(i--){ req.url = '/' + subdomainArray[i] + req.url; }

		// finally prepend the suffix so we end up with
		// something like: "/subdomain/[first]/[second]/page"
		req.url = '/' + options.prefix + req.url;

		// if logging is turned on
		if(options.logger) console.log('ESH: %s => %s', originalUrl, req.url);

		// jump to next middleware in stack
		next();
	};
};
<commit_msg>logs added<commit_after>/**
 * SubdomainHandler
 *
 * This runs on all routes and manipulates the req.url to include the tag
 * as the first parameter (/:tag/foo/bar). This then triggers different route listeners.
 * It is important because it transforms the fragile subdomain mesh tag into a more
 * tageable route parameter that is easily retrievable in later route middleware.
 *
 * USAGE:
 *
 *		// add express-subdomain-handler to your express middleware stack
 *		app.use( require('express-subdomain-handler')({ baseUrl: 'example.com', prefix: 'myprefix', logger: true, ignoreExtensions:[".css", ".js", ".html", ".jpg", ".png", ".svg", ".gif",".woff", ".ttf"]}) );
 *
 *		// setup routes to catch subdomain urls
 *		// eg. 'http://mysubdomain.example.com/homepage'
 *		app.get('/myprefix/:thesubdomain/thepage', function(req, res, next){
 *
 *			// for the example url this will print 'mysubdomain'
 *			res.send(req.params.thesubdomain);
 *
 *		});
 */

var log = require('../../../config/log-config');

log.log( 'info', 'ESH --'+ ' module loaded');
function _escapeRegExp(str) {
	return str.replace(/[-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}

/**
 * Creates the custom regex object from the specified baseUrl
 *
 * @param  {string} baseUrl [description]
 * @return {Object} the regex object
 */
function subdomainRegex(baseUrl){
  log.log( 'info', 'ESH --'+ 'subdomainRegex baseUrl' + baseUrl);
	var regex;

	baseUrl = _escapeRegExp(baseUrl);

	regex = new RegExp('((?!www)\\b[-\\w\\.]+)\\.' + baseUrl + '(?::)?(?:\d+)?');

	return regex;
}

module.exports = function(options){

	// prefix default
	options.prefix = options.prefix || 'subdomain';

	// logger default
	options.logger = (options.logger === true) ? true : false;

	// allow 'base' or 'baseUrl'
	options.baseUrl = options.baseUrl || options.base;

  log.log( 'info', 'ESH --'+ 'opt.baseUrl ' + options.baseUrl);
  log.log( 'info', 'ESH --'+ 'opt.base ' + options.base);
	// ignore extensions
	options.ignoreExtensions = options.ignoreExtensions || [];

	// return error if no baseUrl was specified
	if(!options.baseUrl) return next("express-subdomain-handler: You haven't specified a baseUrl, this is required!");

	if(options.logger) console.log("\nESH: Rewriting all subdomain routes to /%s/[subdomain1]/[subdomain2]/path/after/baseurl for baseUrl %s \n", options.prefix, options.baseUrl);

	// the returned function
	return function(req, res, next){
		var i,

		// original req.url
		originalUrl = req.headers.host + req.url,

		// create our subdomain regex
		regex = subdomainRegex(options.baseUrl),

		// extract the subdomain string from the req.url
		subdomainString = regex.exec(req.headers.host);

    log.log( 'info', 'ESH --'+ 'originalUrl ' + originalUrl);
    //log.log( 'info', 'ESH --'+ 'regex ' + regex);
    log.log( 'info', 'ESH --'+ 'subdomainString ' + subdomainString);
		// if there is no subdomain, return
		if(!subdomainString) return next();

		// if there files with below extentions so don't apply subdomain logic
		for(var i=0;i<options.ignoreExtensions.length;i++){
			if(req.url.indexOf(options.ignoreExtensions[i])>0){
				return next();
			}
		}

		// create an array of subdomains
		subdomainArray = subdomainString[1].split('.');

		// cache number of subdomains
		i = subdomainArray.length;

		// prepend each subdomain in reverse order
		while(i--){ req.url = '/' + subdomainArray[i] + req.url; }

		// finally prepend the suffix so we end up with
		// something like: "/subdomain/[first]/[second]/page"
		req.url = '/' + options.prefix + req.url;

    log.log( 'info', 'ESH --'+ 'generated req.url ' + req.url);
		// if logging is turned on
		if(options.logger) console.log('ESH: %s => %s', originalUrl, req.url);

		// jump to next middleware in stack
		next();
	};
};
<|endoftext|>


<commit_before>// Licensed under the Apache License, Version 2.0 (the 'License'); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an 'AS IS' BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.

'use strict';

// Necessary libs
var request = require('request');
var assert  = require('assert');
var _       = require('underscore');

// Global
var gds;

// Init
module.exports = exports = gds = function init(config) {

  // Validate config
  assert.equal(typeof config, 'object',
    'You must specify the endpoint url when invoking this module');
  assert.ok(/^https?:/.test(config.url), 'url is not valid');

  // Handle URL Requests
  function apiCall(opts, callback) {
    if (!opts) var opts = {}

    // Debug
    opts.debug = (config.debug) ? config.debug : ((!opts.debug) ? false : opts.debug);

    // Force the URL
    opts.url = config.url + opts.url;

    // Auth
    opts.auth = {
      user: config.username,
      pass: config.password
    }

    // Debug Opts
    if (opts.debug) console.log(opts);

    return request(opts, function(error, response, body) {
      var returnObject = {
        error: error,
        response: response,
        body: body
      };

      if (opts.debug) console.log(returnObject);

      if (!callback) {
        return returnObject;
      }

      return callback(error, response, body)
    })
  }

  /*
  Vertices
   */

  // Create Vertice
  function createVertices(keyPairs, callback) {
    var opts = {
      url: '/vertices',
      method: 'POST'
    }
    return apiCall(opts, callback);
  }

  // List Vertices
  function listVertices(callback) {
    var opts = {
      url: '/vertices',
      method: 'GET'
    };
    return apiCall(opts, callback);
  }

  // Vertex by ID
  function vertexById(id, callback) {
    var opts = {
      url: '/vertices/' + id,
      method: 'GET'
    }
    return apiCall(opts, callback);
  }

  // Vertex by properties
  function vertexByProperties(properties, callback) {
    var opts = {
      url: '/vertices',
      method: 'GET',
      qs: properties
    }
    return apiCall(opts, callback);
  }

  var vertices = {
    create: createVertices,
    list: listVertices,
    get: vertexById,
    properties: vertexByProperties
  };

  /*
  Edges
   */

   // List Edges
   function listEdges(callback) {
     var opts = {
       url: '/edges',
       method: 'GET',
     };
     return apiCall(opts, callback);
   }

   var edges = {
     list: listEdges,
   };

   /*
   Gremlin
    */

  // Gremlin Endpoint
  function gremlinQuery(traversal, callback) {
    var opts = {
      url: '/gremlin',
      method: 'POST',
      // @TODO: reimplement later
      // json: true,
      body: '{"gremlin": ""}',
      headers: {
        'Content-Type': 'application/json'
      }
    }

    // If traveral is string
    if (_.isArray(traversal)) {
      // Check first element is g
      if (traversal[0] != 'g') {
        traversal.unshift('g');
      }

      opts.body = JSON.stringify({gremlin:traversal.join('.')});
    }
    else {
      opts.body = JSON.stringify({gremlin:traversal});
    }

    return apiCall(opts, callback);
  }

  var gremlin = gremlinQuery;

  /*
  Input/Output
   */

  // Bulk Upload - GraphML
  function uploadGraphMl(graphml, callback) {

    if (typeof graphml != 'string' && !callback) var callback = graphml;

    var opts = {
      url: '/bulkload/graphml',
      method: 'POST',
      form: {graphml: graphml}
    }
    return apiCall(opts, callback);
  }

  //  Buld Upload - graphson
  function uploadGraphSON(graphson, callback) {

    if (typeof graphson != 'string' && !callback) var callback = graphson;

    var opts = {
      url: '/bulkload/graphson',
      method: 'POST',
      form: {graphson: graphson}
    }
    return apiCall(opts, callback);
  }

  // Extract
  function extractBulk(format, callback) {

    if (!callback) var callback = format;
    if (!format) var format = 'json';

    var opts = {
      url: '/extract',
      method: 'GET',
      headers: {
        'Content-Type': 'application/' + format
      }
    }

    return apiCall(opts, callback);
  }

  var io = {
    bulkload: {
      graphml: uploadGraphMl,
      graphson: uploadGraphSON
    },
    extract: extractBulk
  }

  // Return object
  return {
    vertices: vertices,
    edges: edges,
    gremlin: gremlin,
    io: io,
  }
}
<commit_msg>Get Edge by ID<commit_after>// Licensed under the Apache License, Version 2.0 (the 'License'); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an 'AS IS' BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.

'use strict';

// Necessary libs
var request = require('request');
var assert  = require('assert');
var _       = require('underscore');

// Global
var gds;

// Init
module.exports = exports = gds = function init(config) {

  // Validate config
  assert.equal(typeof config, 'object',
    'You must specify the endpoint url when invoking this module');
  assert.ok(/^https?:/.test(config.url), 'url is not valid');

  // Handle URL Requests
  function apiCall(opts, callback) {
    if (!opts) var opts = {}

    // Debug
    opts.debug = (config.debug) ? config.debug : ((!opts.debug) ? false : opts.debug);

    // Force the URL
    opts.url = config.url + opts.url;

    // Auth
    opts.auth = {
      user: config.username,
      pass: config.password
    }

    // Debug Opts
    if (opts.debug) console.log(opts);

    return request(opts, function(error, response, body) {
      var returnObject = {
        error: error,
        response: response,
        body: body
      };

      if (opts.debug) console.log(returnObject);

      if (!callback) {
        return returnObject;
      }

      return callback(error, response, body)
    })
  }

  /*
  Vertices
   */

  // Create Vertice
  function createVertices(keyPairs, callback) {
    var opts = {
      url: '/vertices',
      method: 'POST'
    }
    return apiCall(opts, callback);
  }

  // List Vertices
  function listVertices(callback) {
    var opts = {
      url: '/vertices',
      method: 'GET'
    };
    return apiCall(opts, callback);
  }

  // Vertex by ID
  function vertexById(id, callback) {
    var opts = {
      url: '/vertices/' + id,
      method: 'GET'
    }
    return apiCall(opts, callback);
  }

  // Vertex by properties
  function vertexByProperties(properties, callback) {
    var opts = {
      url: '/vertices',
      method: 'GET',
      qs: properties
    }
    return apiCall(opts, callback);
  }

  var vertices = {
    create: createVertices,
    list: listVertices,
    get: vertexById,
    properties: vertexByProperties
  };

  /*
  Edges
   */

   // List Edges
   function listEdges(callback) {
     var opts = {
       url: '/edges',
       method: 'GET',
     };
     return apiCall(opts, callback);
   }

   // Edge by ID
   function edgeById(id, callback) {
     var opts = {
       url: '/edges/' + id,
       method: 'GET'
     }
     return apiCall(opts, callback);
   }

   var edges = {
     list: listEdges,
     get: edgeById,
   };

   /*
   Gremlin
    */

  // Gremlin Endpoint
  function gremlinQuery(traversal, callback) {
    var opts = {
      url: '/gremlin',
      method: 'POST',
      // @TODO: reimplement later
      // json: true,
      body: '{"gremlin": ""}',
      headers: {
        'Content-Type': 'application/json'
      }
    }

    // If traveral is string
    if (_.isArray(traversal)) {
      // Check first element is g
      if (traversal[0] != 'g') {
        traversal.unshift('g');
      }

      opts.body = JSON.stringify({gremlin:traversal.join('.')});
    }
    else {
      opts.body = JSON.stringify({gremlin:traversal});
    }

    return apiCall(opts, callback);
  }

  var gremlin = gremlinQuery;

  /*
  Input/Output
   */

  // Bulk Upload - GraphML
  function uploadGraphMl(graphml, callback) {

    if (typeof graphml != 'string' && !callback) var callback = graphml;

    var opts = {
      url: '/bulkload/graphml',
      method: 'POST',
      form: {graphml: graphml}
    }
    return apiCall(opts, callback);
  }

  //  Buld Upload - graphson
  function uploadGraphSON(graphson, callback) {

    if (typeof graphson != 'string' && !callback) var callback = graphson;

    var opts = {
      url: '/bulkload/graphson',
      method: 'POST',
      form: {graphson: graphson}
    }
    return apiCall(opts, callback);
  }

  // Extract
  function extractBulk(format, callback) {

    if (!callback) var callback = format;
    if (!format) var format = 'json';

    var opts = {
      url: '/extract',
      method: 'GET',
      headers: {
        'Content-Type': 'application/' + format
      }
    }

    return apiCall(opts, callback);
  }

  var io = {
    bulkload: {
      graphml: uploadGraphMl,
      graphson: uploadGraphSON
    },
    extract: extractBulk
  }

  // Return object
  return {
    vertices: vertices,
    edges: edges,
    gremlin: gremlin,
    io: io,
  }
}
<|endoftext|>


<commit_before>var Git, exec, fs, options_to_argv, Q, pty, _, errors;

_ = require('underscore');
fs = require('fs');
pty = require('pty.js');
Q = require('q');
exec = require('child_process').exec;
errors = require('./errors');

module.exports = Git = function(git_dir, dot_git) {
    var git, execGit;
    dot_git || (dot_git = "" + git_dir + "/.git");
    execGit = function(useTerminal, command, options, args, creds) {
        var bash, d, err, stdout, termArgs, errCode = errors.codes.UNKNOWN;

        d = Q.defer();
        if (options == null) {
            options = {};
        }
        options = options_to_argv(options);
        options = options.join(" ");
        if (args == null) {
            args = [];
        }
        if (args instanceof Array) {
            args = args.join(" ");
        }
        bash = "" + Git.bin + " " + command + " " + options + " " + args;
        termArgs =  _.compact((command + " " + options + " " + args).split(" ")).join(" ").split(" ");

        d.notify(bash);
        if (useTerminal) {
            var pterm = pty.spawn(Git.bin, termArgs, {
                cwd: git_dir
            });
            creds = creds || {};
            stdout = "";
            pterm.on('data', function(data) {
                stdout = stdout + data;
                var prompt = data.toLowerCase();

                // Username
                if (prompt.indexOf('username') > -1) {
                    pterm.write(creds.username + '\r');

                // Password
                } else if (prompt.indexOf('password') > -1) {
                    pterm.write(creds.password + '\r');

                // SSH passphrase
                } else if (prompt.indexOf('passphrase') > -1) {
                    pterm.write(creds.passphrase + '\r');

                // Errors
                } else if ((prompt.indexOf('error') > -1)
                || (prompt.indexOf('fatal') > -1)
                || prompt.indexOf("permission denied") > -1) {
                    if ((prompt.indexOf("authentication") > -1)
                    || prompt.indexOf("permission denied") > -1) {
                        errCode = errors.codes.AUTH;
                    }

                    err = errors.error(
                        errCode,
                        _.compact(prompt.split('\r\n')).join(" ")
                    );
                }
            });
            pterm.on('exit', function() {
                if (err) {
                    d.reject(err);
                } else {
                    d.resolve({
                        'stdout': stdout,
                        'bash': bash
                    });
                }
            });
        } else {
            var pterm = exec(bash, {
                cwd: git_dir
            }, function(err, stdout, stderr) {
                if (err) return d.reject(errors.error(errors.codes.UNKNOWN, err));
                d.resolve({
                    'stdout': stdout,
                    'stderr': stderr,
                    'bash': bash
                })
            });
        }

        return d.promise;
    };

    git = _.partial(execGit, false);
    git.term = _.partial(execGit, true);

    git.list_remotes = function() {
        return Q.nfapply(fs.readdir, ["" + dot_git + "/refs/remotes"]).then(function(files) {
            return fiels || [];
        });
    };
    git.refs = function(type, options) {
        var prefix, _ref;
        prefix = "refs/" + type + "s/";
        return git("show-ref").then(function(out) {
            var text = out.stdout;
            var id, line, matches, name, _i, _len, _ref1, _ref2;
            matches = [];
            _ref1 = (text || "").split("\n");
            for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
                line = _ref1[_i];
                if (!line) {
                    continue;
                }
                _ref2 = line.split(' '), id = _ref2[0], name = _ref2[1];
                if (name.substr(0, prefix.length) === prefix) {
                    matches.push("" + (name.substr(prefix.length)) + " " + id);
                }
            }
            return matches.join("\n");
        });
    };
    return git;
};

Git.bin = "git";

Git.options_to_argv = options_to_argv = function(options) {
    var argv, key, val;
    argv = [];
    for (key in options) {
        val = options[key];
        if (key.length === 1) {
            if (val === true) {
                argv.push("-" + key);
            } else if (val === false) {

            } else {
                argv.push("-" + key);
                argv.push(val);
            }
        } else {
            if (val === true) {
                argv.push("--" + key);
            } else if (val === false) {

            } else {
                argv.push("--" + key + "=" + val);
            }
        }
    }
    return argv;
};
<commit_msg>Handle ssh unknown host<commit_after>var Git, exec, fs, options_to_argv, Q, pty, _, errors;

_ = require('underscore');
fs = require('fs');
pty = require('pty.js');
Q = require('q');
exec = require('child_process').exec;
errors = require('./errors');

module.exports = Git = function(git_dir, dot_git) {
    var git, execGit;
    dot_git || (dot_git = "" + git_dir + "/.git");
    execGit = function(useTerminal, command, options, args, creds) {
        var bash, d, err, stdout, termArgs, errCode = errors.codes.UNKNOWN;

        d = Q.defer();
        if (options == null) {
            options = {};
        }
        options = options_to_argv(options);
        options = options.join(" ");
        if (args == null) {
            args = [];
        }
        if (args instanceof Array) {
            args = args.join(" ");
        }
        bash = "" + Git.bin + " " + command + " " + options + " " + args;
        termArgs =  _.compact((command + " " + options + " " + args).split(" ")).join(" ").split(" ");

        d.notify(bash);
        if (useTerminal) {
            var pterm = pty.spawn(Git.bin, termArgs, {
                cwd: git_dir
            });
            creds = creds || {};
            stdout = "";
            pterm.on('data', function(data) {
                stdout = stdout + data;
                var prompt = data.toLowerCase();

                // SSH host
                if (prompt.indexOf('yes/no') > -1) {
                    // By default gittle accept all ssh host
                    if (creds.refuseUnknownHost) {
                        pterm.write('no\r');
                    } else {
                        pterm.write('yes\r');
                    }

                // Username
                } else if (prompt.indexOf('username') > -1) {
                    pterm.write(creds.username + '\r');

                // Password
                } else if (prompt.indexOf('password') > -1) {
                    pterm.write(creds.password + '\r');

                // SSH passphrase
                } else if (prompt.indexOf('passphrase') > -1) {
                    pterm.write(creds.passphrase + '\r');

                // Errors
                } else if ((prompt.indexOf('error') > -1)
                || (prompt.indexOf('fatal') > -1)
                || prompt.indexOf("permission denied") > -1) {
                    if ((prompt.indexOf("authentication") > -1)
                    || prompt.indexOf("permission denied") > -1) {
                        errCode = errors.codes.AUTH;
                    }

                    err = errors.error(
                        errCode,
                        _.compact(prompt.split('\r\n')).join(" ")
                    );
                }
            });
            pterm.on('exit', function() {
                if (err) {
                    d.reject(err);
                } else {
                    d.resolve({
                        'stdout': stdout,
                        'bash': bash
                    });
                }
            });
        } else {
            var pterm = exec(bash, {
                cwd: git_dir
            }, function(err, stdout, stderr) {
                if (err) return d.reject(errors.error(errors.codes.UNKNOWN, err));
                d.resolve({
                    'stdout': stdout,
                    'stderr': stderr,
                    'bash': bash
                })
            });
        }

        return d.promise;
    };

    git = _.partial(execGit, false);
    git.term = _.partial(execGit, true);

    git.list_remotes = function() {
        return Q.nfapply(fs.readdir, ["" + dot_git + "/refs/remotes"]).then(function(files) {
            return fiels || [];
        });
    };
    git.refs = function(type, options) {
        var prefix, _ref;
        prefix = "refs/" + type + "s/";
        return git("show-ref").then(function(out) {
            var text = out.stdout;
            var id, line, matches, name, _i, _len, _ref1, _ref2;
            matches = [];
            _ref1 = (text || "").split("\n");
            for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
                line = _ref1[_i];
                if (!line) {
                    continue;
                }
                _ref2 = line.split(' '), id = _ref2[0], name = _ref2[1];
                if (name.substr(0, prefix.length) === prefix) {
                    matches.push("" + (name.substr(prefix.length)) + " " + id);
                }
            }
            return matches.join("\n");
        });
    };
    return git;
};

Git.bin = "git";

Git.options_to_argv = options_to_argv = function(options) {
    var argv, key, val;
    argv = [];
    for (key in options) {
        val = options[key];
        if (key.length === 1) {
            if (val === true) {
                argv.push("-" + key);
            } else if (val === false) {

            } else {
                argv.push("-" + key);
                argv.push(val);
            }
        } else {
            if (val === true) {
                argv.push("--" + key);
            } else if (val === false) {

            } else {
                argv.push("--" + key + "=" + val);
            }
        }
    }
    return argv;
};
<|endoftext|>