|
| 1 | +#!/usr/bin/env node |
| 2 | + |
| 3 | +const fs = require('fs') |
| 4 | +const yargs = require('yargs') |
| 5 | +const JSON5 = require('json5') |
| 6 | +const _ = require('lodash') |
| 7 | +const generateHTMLTable = require('../lib/generateHTMLTable') |
| 8 | +const generateExcel = function (data, schema) { |
| 9 | + return require('../lib/generateExcel')(data, schema, { writeTo: '/dev/stdout' }) |
| 10 | +} |
| 11 | + |
| 12 | +const argv = yargs |
| 13 | + .option('data', { |
| 14 | + alias: 'd', |
| 15 | + description: 'JSON5 格式的数据文件', |
| 16 | + type: 'string' |
| 17 | + }) |
| 18 | + .option('schema', { |
| 19 | + alias: 'e', |
| 20 | + description: 'JSON5 格式的 Schema 文件', |
| 21 | + type: 'string' |
| 22 | + }) |
| 23 | + .option('options', { |
| 24 | + alias: 'p', |
| 25 | + description: 'JSON5 格式的 Options 文件,仅支持 --type=html', |
| 26 | + type: 'string' |
| 27 | + }) |
| 28 | + .option('type', { |
| 29 | + alias: 't', |
| 30 | + description: '生成的格式', |
| 31 | + type: 'string', |
| 32 | + choices: ['html', 'excel'], |
| 33 | + conflicts: ['html', 'excel'] |
| 34 | + }) |
| 35 | + .option('html', { |
| 36 | + description: '等效于 --type=html', |
| 37 | + type: 'boolean' |
| 38 | + }) |
| 39 | + .option('excel', { |
| 40 | + description: '等效于 --type=excel', |
| 41 | + type: 'boolean' |
| 42 | + }) |
| 43 | + .conflicts('html', 'excel') |
| 44 | + .version(false) |
| 45 | + .help().alias('help', 'h') |
| 46 | + .strict() |
| 47 | + .middleware(function (argv) { |
| 48 | + if (argv.html) { |
| 49 | + argv.type = 'html' |
| 50 | + } else if (argv.excel) { |
| 51 | + argv.type = 'excel' |
| 52 | + } else { |
| 53 | + argv.type = argv.type || 'html' |
| 54 | + } |
| 55 | + }) |
| 56 | + .coerce('data', function (dataFile) { |
| 57 | + dataFile = dataFile || '/dev/stdin' |
| 58 | + return JSON5.parse(fs.readFileSync(dataFile)) |
| 59 | + }) |
| 60 | + .coerce('schema', function (schemaFile) { |
| 61 | + if (schemaFile) { |
| 62 | + return JSON5.parse(fs.readFileSync(schemaFile)) |
| 63 | + } |
| 64 | + }) |
| 65 | + .coerce('options', function (optionsFile) { |
| 66 | + if (optionsFile) { |
| 67 | + return JSON5.parse(fs.readFileSync(optionsFile)) |
| 68 | + } |
| 69 | + }) |
| 70 | + .argv |
| 71 | + |
| 72 | +let fn = argv.type === 'html' ? generateHTMLTable : generateExcel |
| 73 | + |
| 74 | +const keys = ['data', 'schema', 'options'] |
| 75 | +let { data, schema, options } = _.pick(argv, keys) |
| 76 | +if (_.isNil(schema) |
| 77 | + && ('data' in data && 'schema' in data) |
| 78 | + && _.isEmpty(_.difference(Object.keys(data), keys)) |
| 79 | +) { |
| 80 | + // 从 data 中读取 schema |
| 81 | + schema = data.schema |
| 82 | + options = data.options |
| 83 | + data = data.data |
| 84 | +} |
| 85 | + |
| 86 | +const htmlTable = fn(data, schema, options) |
| 87 | +console.log(htmlTable) |
0 commit comments