| 1 | #!/usr/bin/env node |
| 2 | |
| 3 | const fs = require('fs'); |
| 4 | const path = require('path'); |
| 5 | const { Transform, pipeline } = require('stream'); |
| 6 | const OpenCC = require('./opencc'); |
| 7 | |
| 8 | const BUILT_IN_CONFIGS = [ |
| 9 | ['s2t.json', 'Simplified Chinese to Traditional Chinese'], |
| 10 | ['t2s.json', 'Traditional Chinese to Simplified Chinese'], |
| 11 | ['s2tw.json', 'Simplified Chinese to Traditional Chinese (Taiwan Standard)'], |
| 12 | ['tw2s.json', 'Traditional Chinese (Taiwan Standard) to Simplified Chinese'], |
| 13 | ['s2hk.json', 'Simplified Chinese to Traditional Chinese (Hong Kong variant)'], |
| 14 | ['hk2s.json', 'Traditional Chinese (Hong Kong variant) to Simplified Chinese'], |
| 15 | ['s2hkp.json', 'Simplified Chinese to Traditional Chinese (Hong Kong variant) with Hong Kong idiom'], |
| 16 | ['hk2sp.json', 'Traditional Chinese (Hong Kong variant) to Simplified Chinese with Mainland Chinese idiom'], |
| 17 | ['s2twp.json', 'Simplified Chinese to Traditional Chinese (Taiwan Standard) with Taiwanese idiom'], |
| 18 | ['tw2sp.json', 'Traditional Chinese (Taiwan Standard) to Simplified Chinese with Mainland Chinese idiom'], |
| 19 | ['tw2t.json', 'Traditional Chinese (Taiwan Standard) to Traditional Chinese (OpenCC Standard)'], |
| 20 | ['t2tw.json', 'Traditional Chinese (OpenCC Standard) to Taiwan Standard'], |
| 21 | ['hk2t.json', 'Traditional Chinese (Hong Kong variant) to Traditional Chinese (OpenCC Standard)'], |
| 22 | ['t2hk.json', 'Traditional Chinese (OpenCC Standard) to Hong Kong variant'], |
| 23 | ['t2jp.json', 'Old Japanese Kanji (Kyujitai) to New Japanese Kanji (Shinjitai)'], |
| 24 | ['jp2t.json', 'New Japanese Kanji (Shinjitai) to Old Japanese Kanji (Kyujitai)'], |
| 25 | ]; |
| 26 | const BUILT_IN_CONFIG_NAMES = new Set(BUILT_IN_CONFIGS.map(([name]) => name)); |
| 27 | const BUILT_IN_CONFIG_STEMS = new Set( |
| 28 | BUILT_IN_CONFIGS.map(([name]) => name.replace(/\.json$/, '')) |
| 29 | ); |
| 30 | const OPTIONAL_JIEBA_CONFIGS = new Set([ |
| 31 | 's2hk_jieba.json', |
| 32 | 's2t_jieba.json', |
| 33 | 's2tw_jieba.json', |
| 34 | 's2twp_jieba.json', |
| 35 | 'tw2sp_jieba.json', |
| 36 | ]); |
| 37 | const OPTIONAL_JIEBA_CONFIG_STEMS = new Set( |
| 38 | Array.from(OPTIONAL_JIEBA_CONFIGS).map((name) => name.replace(/\.json$/, '')) |
| 39 | ); |
| 40 | |
| 41 | function printHelp() { |
| 42 | console.log(`Open Chinese Convert (OpenCC) npm Command Line Tool |
| 43 | |
| 44 | Usage: |
| 45 | opencc [options] |
| 46 | |
| 47 | Options: |
| 48 | -c, --config <file> Configuration file. Defaults to s2t.json. |
| 49 | -i, --input <file> Read original text from <file>. Defaults to stdin. |
| 50 | -o, --output <file> Write converted text to <file>. Defaults to stdout. |
| 51 | --include-tofu-risk-dictionaries |
| 52 | Include dictionaries that may output tofu (Chinese |
| 53 | characters rendered as missing-glyph boxes). |
| 54 | -v, --version Print OpenCC version. |
| 55 | -h, --help Print this help. |
| 56 | |
| 57 | Unsupported in the npm CLI: |
| 58 | --inspect Use the native OpenCC CLI for inspection output. |
| 59 | --segmentation Use the native OpenCC CLI for segmentation output. |
| 60 | |
| 61 | Built-in Configurations: |
| 62 | ${BUILT_IN_CONFIGS.map(([name, description]) => ` ${name.padEnd(11)} ${description}`).join('\n')} |
| 63 | `); |
| 64 | } |
| 65 | |
| 66 | function fail(message) { |
| 67 | console.error(message); |
| 68 | process.exitCode = 1; |
| 69 | } |
| 70 | |
| 71 | function readOptionValue(args, index, option) { |
| 72 | const value = args[index + 1]; |
| 73 | if (!value || value.startsWith('-')) { |
| 74 | throw new Error(`Missing value for ${option}`); |
| 75 | } |
| 76 | return value; |
| 77 | } |
| 78 | |
| 79 | function readInlineOptionValue(arg, option) { |
| 80 | const value = arg.slice((option + '=').length); |
| 81 | if (!value) { |
| 82 | throw new Error(`Missing value for ${option}`); |
| 83 | } |
| 84 | return value; |
| 85 | } |
| 86 | |
| 87 | function parseArgs(args) { |
| 88 | const options = { |
| 89 | config: 's2t.json', |
| 90 | input: null, |
| 91 | output: null, |
| 92 | resourceZip: null, |
| 93 | includeTofuRiskDictionaries: false, |
| 94 | help: false, |
| 95 | version: false, |
| 96 | }; |
| 97 | |
| 98 | for (let i = 0; i < args.length; i += 1) { |
| 99 | const arg = args[i]; |
| 100 | if (arg === '-h' || arg === '--help') { |
| 101 | options.help = true; |
| 102 | } else if (arg === '-v' || arg === '--version') { |
| 103 | options.version = true; |
| 104 | } else if (arg === '-c' || arg === '--config') { |
| 105 | options.config = readOptionValue(args, i, arg); |
| 106 | i += 1; |
| 107 | } else if (arg.startsWith('--config=')) { |
| 108 | options.config = readInlineOptionValue(arg, '--config'); |
| 109 | } else if (arg === '--resource-zip') { |
| 110 | options.resourceZip = readOptionValue(args, i, arg); |
| 111 | i += 1; |
| 112 | } else if (arg.startsWith('--resource-zip=')) { |
| 113 | options.resourceZip = readInlineOptionValue(arg, '--resource-zip'); |
| 114 | } else if (arg === '-i' || arg === '--input') { |
| 115 | options.input = readOptionValue(args, i, arg); |
| 116 | i += 1; |
| 117 | } else if (arg.startsWith('--input=')) { |
| 118 | options.input = readInlineOptionValue(arg, '--input'); |
| 119 | } else if (arg === '-o' || arg === '--output') { |
| 120 | options.output = readOptionValue(args, i, arg); |
| 121 | i += 1; |
| 122 | } else if (arg.startsWith('--output=')) { |
| 123 | options.output = readInlineOptionValue(arg, '--output'); |
| 124 | } else if (arg === '--include-tofu-risk-dictionaries') { |
| 125 | options.includeTofuRiskDictionaries = true; |
| 126 | } else if (arg === '--inspect' || arg === '--segmentation') { |
| 127 | throw new Error(`${arg} is not supported by the npm CLI. Use the native OpenCC CLI instead.`); |
| 128 | } else if (arg === '--path' || arg.startsWith('--path=')) { |
| 129 | throw new Error('--path is not supported by the npm CLI. Pass an explicit config file path instead.'); |
| 130 | } else if (arg === '--noflush' || arg === '--measured_result' || arg.startsWith('--measured_result=')) { |
| 131 | throw new Error(`${arg.split('=')[0]} is not supported by the npm CLI.`); |
| 132 | } else { |
| 133 | throw new Error(`Unknown option: ${arg}`); |
| 134 | } |
| 135 | } |
| 136 | |
| 137 | return options; |
| 138 | } |
| 139 | |
| 140 | function resolveConfigPath(config) { |
| 141 | if (BUILT_IN_CONFIG_NAMES.has(config) || OPTIONAL_JIEBA_CONFIGS.has(config) || path.isAbsolute(config)) { |
| 142 | return config; |
| 143 | } |
| 144 | |
| 145 | if (!config.endsWith('.json') && BUILT_IN_CONFIG_STEMS.has(config)) { |
| 146 | return config + '.json'; |
| 147 | } |
| 148 | |
| 149 | if (!config.endsWith('.json') && OPTIONAL_JIEBA_CONFIG_STEMS.has(config)) { |
| 150 | return config + '.json'; |
| 151 | } |
| 152 | |
| 153 | return path.resolve(process.cwd(), config); |
| 154 | } |
| 155 | |
| 156 | function createConverterStream(converter) { |
| 157 | const nativeStream = converter._createConverterStream(); |
| 158 | let pendingChunk = null; |
| 159 | |
| 160 | return new Transform({ |
| 161 | transform(chunk, encoding, callback) { |
| 162 | try { |
| 163 | const input = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding); |
| 164 | if (pendingChunk === null) { |
| 165 | pendingChunk = Buffer.from(input); |
| 166 | callback(); |
| 167 | return; |
| 168 | } |
| 169 | const output = nativeStream.convertChunk(pendingChunk); |
| 170 | pendingChunk = Buffer.from(input); |
| 171 | callback(null, output); |
| 172 | } catch (error) { |
| 173 | callback(error); |
| 174 | } |
| 175 | }, |
| 176 | flush(callback) { |
| 177 | try { |
| 178 | callback(null, pendingChunk === null |
| 179 | ? nativeStream.finish() |
| 180 | : nativeStream.finish(pendingChunk)); |
| 181 | } catch (error) { |
| 182 | callback(error); |
| 183 | } |
| 184 | }, |
| 185 | }); |
| 186 | } |
| 187 | |
| 188 | function isSameFile(inputFileName, outputFileName) { |
| 189 | if (!inputFileName || !outputFileName) { |
| 190 | return false; |
| 191 | } |
| 192 | |
| 193 | try { |
| 194 | const inputStat = fs.statSync(inputFileName); |
| 195 | const outputStat = fs.statSync(outputFileName); |
| 196 | return inputStat.dev === outputStat.dev && inputStat.ino === outputStat.ino; |
| 197 | } catch (error) { |
| 198 | return path.resolve(process.cwd(), inputFileName) === |
| 199 | path.resolve(process.cwd(), outputFileName); |
| 200 | } |
| 201 | } |
| 202 | |
| 203 | function convertStream(converter, options, callback) { |
| 204 | if (isSameFile(options.input, options.output)) { |
| 205 | throw new Error('Input and output refer to the same file.'); |
| 206 | } |
| 207 | |
| 208 | const input = options.input ? fs.createReadStream(options.input) : process.stdin; |
| 209 | const output = options.output ? fs.createWriteStream(options.output) : process.stdout; |
| 210 | pipeline(input, createConverterStream(converter), output, callback); |
| 211 | } |
| 212 | |
| 213 | function main() { |
| 214 | let options; |
| 215 | try { |
| 216 | options = parseArgs(process.argv.slice(2)); |
| 217 | } catch (error) { |
| 218 | fail(error.message); |
| 219 | return; |
| 220 | } |
| 221 | |
| 222 | if (options.help) { |
| 223 | printHelp(); |
| 224 | return; |
| 225 | } |
| 226 | |
| 227 | if (options.version) { |
| 228 | console.log(OpenCC.version); |
| 229 | return; |
| 230 | } |
| 231 | |
| 232 | try { |
| 233 | const converter = new OpenCC(resolveConfigPath(options.config), { |
| 234 | includeTofuRiskDictionaries: options.includeTofuRiskDictionaries, |
| 235 | resourceZip: options.resourceZip, |
| 236 | }); |
| 237 | convertStream(converter, options, (error) => { |
| 238 | if (error) { |
| 239 | const message = error && error.message ? error.message : String(error); |
| 240 | fail(path.basename(process.argv[1]) + ': ' + message); |
| 241 | } |
| 242 | }); |
| 243 | } catch (error) { |
| 244 | const message = error && error.message ? error.message : String(error); |
| 245 | fail(path.basename(process.argv[1]) + ': ' + message); |
| 246 | } |
| 247 | } |
| 248 | |
| 249 | main(); |