X Tutup
#!/usr/bin/env node 'use strict' const chalk = require('chalk') const cmd = require('commander') const fs = require('fs') const readFile = require('fs-readfile-promise') const writeFile = require('fs-writefile-promise') const HTTPSnippet = require('..') const path = require('path') const pkg = require('../package.json') cmd .version(pkg.version) .usage('[options] ') .option('-t, --target ', 'target output') .option('-c, --client [client]', 'target client library') .option('-o, --output ', 'write output to directory') .option('-x, --extra [{"optionKey": "optionValue"}]', 'provide extra options for the target/client') .parse(process.argv) if (!cmd.args.length || !cmd.target) { cmd.help() } let extraOptions if (cmd.extra) { try { extraOptions = JSON.parse(cmd.extra) } catch (e) { console.error('%s failed to parse options %s (should be JSON)', chalk.red('✖'), chalk.cyan.bold(cmd.extra)) process.exit() } } let dir if (cmd.output) { dir = path.resolve(cmd.output) if (!fs.existsSync(dir)) { fs.mkdirSync(dir) } } cmd.args.forEach(function (fileName) { const file = path.basename(fileName) readFile(fileName) .then(JSON.parse) .catch(function (e) { console.error('%s %s failed to read JSON: %s', chalk.red('✖'), chalk.cyan.bold(file), chalk.red(e.message)) }) .then(function (data) { return new HTTPSnippet(data) }) .catch(function (e) { e.errors.forEach(function (err) { console.error('%s %s failed validation: (%s: %s) %s', chalk.red('✖'), chalk.cyan.bold(file), chalk.cyan.italic(err.field), chalk.magenta.italic(err.value), chalk.red(err.message)) }) }) .then(function (snippet) { return snippet.convert(cmd.target, cmd.client, extraOptions) }) .then(function (output) { if (!output) { const targetNames = HTTPSnippet.availableTargets().map(function (t) { return t.key }).join(', ') return console.error('%s %s is not a valid target. Valid targets: %s', chalk.red('✖'), chalk.red(cmd.target), chalk.cyan(targetNames)) } // print if (!cmd.output) { return console.log('%s %s > %s [%s] :\n%s', chalk.green('✓'), chalk.cyan.bold(file), chalk.yellow(cmd.target), chalk.yellow(cmd.client ? cmd.client : 'default'), output) } // write to file const name = path.basename(file, path.extname(file)) const filename = path.format({ dir: dir, base: name + HTTPSnippet.extname(cmd.target) }) return writeFile(filename, output + '\n', function () { console.log('%s %s > %s', chalk.green('✓'), chalk.cyan.bold(file), filename) }) }) .catch(function (e) { console.error('%s %s fail: %s', chalk.red('✖'), chalk.cyan.bold(file), chalk.red(e.message)) }) })
X Tutup