Debian Codegraph @

src/tools/CommandLineMain.cpp

raw symbols SCIP
1 /*
2 * Open Chinese Convert
3 *
4 * Copyright 2010-2026 Carbo Kuo and contributors
5 *
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 */
18
19 #include <chrono>
20 #include <cstdio>
21 #include <cstdlib>
22 #include <cstring>
23 #include <iostream>
24 #include <string>
25 #include <string_view>
26
27 #ifdef _WIN32
28 #include <fcntl.h>
29 #include <io.h>
30 #else
31 #include <unistd.h>
32 #endif
33
34 #include "rapidjson/prettywriter.h"
35 #include "rapidjson/stringbuffer.h"
36 #include "src/CmdLineOutput.hpp"
37 #include "src/Config.hpp"
38 #include "src/ConversionInspection.hpp"
39 #include "src/Converter.hpp"
40 #include "src/Exception.hpp"
41 #include "src/ResourceProvider.hpp"
42 #include "src/Segments.hpp"
43 #include "src/UTF8Util.hpp"
44 #include "src/tools/CommandLineMain.hpp"
45 #include "src/tools/PlatformIO.hpp"
46
47 using namespace opencc;
48 using namespace opencc::tools;
49
50 enum class OutputMode {
51 Convert,
52 Segmentation,
53 Inspect,
54 };
55
56 class OpenCCOutput : public CmdLineOutput {
57 public:
58 void usage(TCLAP::CmdLineInterface& cmd) override {
59 CmdLineOutput::usage(cmd);
60 std::cout
61 << "Built-in Configurations:" << std::endl
62 << std::endl
63 << " s2t.json Simplified Chinese to Traditional Chinese (OpenCC Standard)"
64 << std::endl
65 << " t2s.json Traditional Chinese (OpenCC Standard) to Simplified Chinese"
66 << std::endl
67 << " s2tw.json Simplified Chinese to Traditional Chinese (Taiwan Standard)"
68 << std::endl
69 << " tw2s.json Traditional Chinese (Taiwan Standard) to Simplified Chinese"
70 << std::endl
71 << " s2hk.json Simplified Chinese to Traditional Chinese (Hong Kong variant)"
72 << std::endl
73 << " hk2s.json Traditional Chinese (Hong Kong variant) to Simplified Chinese"
74 << std::endl
75 << " s2hkp.json Simplified Chinese to Traditional Chinese (Hong Kong variant, with Hong Kong Phrases)"
76 << std::endl
77 << " hk2sp.json Traditional Chinese (Hong Kong variant) to Simplified Chinese (Mainland China Phrases)"
78 << std::endl
79 << " s2twp.json Simplified Chinese to Traditional Chinese (Taiwan Standard, with Taiwan Phrases)"
80 << std::endl
81 << " tw2sp.json Traditional Chinese (Taiwan Standard) to Simplified Chinese (Mainland China Phrases)"
82 << std::endl
83 << " tw2t.json Traditional Chinese (Taiwan Standard) to Traditional Chinese (OpenCC Standard)"
84 << std::endl
85 << " t2tw.json Traditional Chinese (OpenCC Standard) to Traditional Chinese (Taiwan Standard)"
86 << std::endl
87 << " hk2t.json Traditional Chinese (Hong Kong variant) to Traditional Chinese (OpenCC Standard)"
88 << std::endl
89 << " t2hk.json Traditional Chinese (OpenCC Standard) to Traditional Chinese (Hong Kong variant)"
90 << std::endl
91 << " t2jp.json Old Japanese Kanji (Kyūjitai) to New Japanese Kanji (Shinjitai)"
92 << std::endl
93 << " jp2t.json New Japanese Kanji (Shinjitai) to Old Japanese Kanji (Kyūjitai)"
94 << std::endl
95 << std::endl;
96 }
97 };
98
99 Optional<std::string> inputFileName = Optional<std::string>::Null();
100 Optional<std::string> outputFileName = Optional<std::string>::Null();
101 Optional<std::string> measuredResultFileName = Optional<std::string>::Null();
102 std::string configFileName;
103 bool noFlush;
104 bool inPlace = false;
105 OutputMode outputMode = OutputMode::Convert;
106 Config config;
107 ConverterPtr converter;
108 bool variationSelectorWarningShown = false;
109 std::string variationSelectorScanTail;
110
111 struct MeasurementResult {
112 double loadMs = 0.0;
113 double convertMs = 0.0;
114 double writeMs = 0.0;
115 double totalMs = 0.0;
116 size_t inputBytes = 0;
117 size_t outputBytes = 0;
118 bool lineByLine = false;
119 OutputMode outputMode = OutputMode::Convert;
120 };
121
122 MeasurementResult measurement;
123
124 bool ReadLine(FILE* fp, std::string* line) {
125 line->clear();
126 int ch;
127 while ((ch = fgetc(fp)) != EOF) {
128 if (ch == '\n') {
129 return true;
130 }
131 line->push_back(static_cast<char>(ch));
132 }
133 return !line->empty();
134 }
135
136 void CopyFileContents(FILE* src, FILE* dst, const std::string& srcFileName,
137 const std::string& dstFileName) {
138 const size_t BUFFER_SIZE = 1024 * 1024;
139 std::string buffer(BUFFER_SIZE, '\0');
140 while (true) {
141 const size_t length = fread(&buffer[0], sizeof(char), buffer.size(), src);
142 if (length > 0) {
143 const size_t written = fwrite(buffer.data(), sizeof(char), length, dst);
144 if (written != length) {
145 throw FileNotWritable(dstFileName);
146 }
147 }
148 if (length < buffer.size()) {
149 if (ferror(src)) {
150 throw FileNotFound(srcFileName);
151 }
152 break;
153 }
154 }
155 }
156
157 void SetBinaryMode(FILE* fp) {
158 #ifdef _WIN32
159 _setmode(_fileno(fp), _O_BINARY);
160 #else
161 (void)fp;
162 #endif
163 }
164
165 double DurationToMilliseconds(
166 const std::chrono::steady_clock::duration& duration) {
167 return std::chrono::duration<double, std::milli>(duration).count();
168 }
169
170 void WriteMeasuredResult() {
171 if (measuredResultFileName.IsNull()) {
172 return;
173 }
174
175 rapidjson::StringBuffer buffer;
176 rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(buffer);
177 writer.SetFormatOptions(rapidjson::kFormatSingleLineArray);
178 writer.StartObject();
179 writer.Key("config");
180 writer.String(configFileName.c_str());
181 writer.Key("input");
182 if (inputFileName.IsNull()) {
183 writer.Null();
184 } else {
185 writer.String(inputFileName.Get().c_str());
186 }
187 writer.Key("output");
188 if (outputFileName.IsNull()) {
189 writer.Null();
190 } else {
191 writer.String(outputFileName.Get().c_str());
192 }
193 writer.Key("mode");
194 writer.String(measurement.lineByLine ? "line_by_line" : "file");
195 writer.Key("output_mode");
196 switch (measurement.outputMode) {
197 case OutputMode::Segmentation:
198 writer.String("segmentation");
199 break;
200 case OutputMode::Inspect:
201 writer.String("inspect");
202 break;
203 default:
204 writer.String("convert");
205 break;
206 }
207 writer.Key("load_ms");
208 writer.Double(measurement.loadMs);
209 writer.Key("convert_ms");
210 writer.Double(measurement.convertMs);
211 writer.Key("write_ms");
212 writer.Double(measurement.writeMs);
213 writer.Key("total_ms");
214 writer.Double(measurement.totalMs);
215 writer.Key("input_bytes");
216 writer.Uint64(measurement.inputBytes);
217 writer.Key("output_bytes");
218 writer.Uint64(measurement.outputBytes);
219 writer.EndObject();
220
221 FILE* fp = OpenFileUtf8(measuredResultFileName.Get(), "wb");
222 if (!fp) {
223 throw FileNotWritable(measuredResultFileName.Get());
224 }
225 fputs(buffer.GetString(), fp);
226 fputc('\n', fp);
227 fclose(fp);
228 }
229
230 FILE* GetOutputStream() {
231 if (outputFileName.IsNull()) {
232 SetBinaryMode(stdout);
233 return stdout;
234 } else {
235 FILE* fp = OpenFileUtf8(outputFileName.Get(), "wb");
236 if (!fp) {
237 throw FileNotWritable(outputFileName.Get());
238 }
239 return fp;
240 }
241 }
242
243 void PrintInteractiveStdinHint() {
244 #ifdef _WIN32
245 if (_isatty(_fileno(stdin))) {
246 fprintf(stderr,
247 "Reading from standard input. Press Ctrl+Z then Enter to "
248 "finish.\n");
249 }
250 #else
251 if (isatty(fileno(stdin))) {
252 fprintf(stderr,
253 "Reading from standard input. Press Ctrl+D to finish.\n");
254 }
255 #endif
256 }
257
258 void PrintVariationSelectorWarningOnce() {
259 if (variationSelectorWarningShown) {
260 return;
261 }
262 variationSelectorWarningShown = true;
263 fprintf(stderr,
264 "warning: input contains Unicode variation selectors (possible IVS); "
265 "conversion results may be inaccurate.\n");
266 }
267
268 void WarnIfTextContainsVariationSelector(const char* input, size_t length) {
269 if (variationSelectorWarningShown) {
270 return;
271 }
272 if (UTF8Util::ContainsVariationSelector(input, length)) {
273 PrintVariationSelectorWarningOnce();
274 }
275 }
276
277 void WarnIfStreamChunkContainsVariationSelector(const char* input,
278 size_t length) {
279 if (variationSelectorWarningShown) {
280 return;
281 }
282
283 std::string scan = variationSelectorScanTail;
284 scan.append(input, length);
285 if (UTF8Util::ContainsVariationSelector(scan.data(), scan.size())) {
286 PrintVariationSelectorWarningOnce();
287 variationSelectorScanTail.clear();
288 return;
289 }
290
291 const size_t maxVariationSelectorUtf8Bytes = 4;
292 const size_t keepBytes = scan.size() < maxVariationSelectorUtf8Bytes
293 ? scan.size()
294 : maxVariationSelectorUtf8Bytes;
295 variationSelectorScanTail.assign(scan.data() + scan.size() - keepBytes,
296 keepBytes);
297 }
298
299 // Serializes the segmentation-only view of an inspection result as a JSON
300 // object with "input" and "segments" fields. Used with --segmentation mode.
301 std::string SerializeSegmentationResultJson(
302 const ConversionInspectionResult& result) {
303 rapidjson::StringBuffer buffer;
304 rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
305 writer.StartObject();
306 writer.Key("input");
307 writer.String(result.input.c_str(), result.input.size());
308 writer.Key("segments");
309 writer.StartArray();
310 for (const auto& seg : result.segments) {
311 writer.String(seg.c_str(), seg.size());
312 }
313 writer.EndArray();
314 writer.EndObject();
315 return buffer.GetString();
316 }
317
318 // Writes a ConversionInspectionResult as a JSON object into writer.
319 // Handles both SingleStageConverter results (segments + stages) and
320 // PipelineConverter results (pipelineStages), and is called recursively
321 // for nested pipeline stages.
322 template <typename Writer>
323 void WriteInspectionResultJson(Writer& writer,
324 const ConversionInspectionResult& result) {
325 writer.StartObject();
326 writer.Key("input");
327 writer.String(result.input.c_str(), result.input.size());
328 writer.Key("segments");
329 writer.StartArray();
330 for (const auto& seg : result.segments) {
331 writer.String(seg.c_str(), seg.size());
332 }
333 writer.EndArray();
334 writer.Key("stages");
335 writer.StartArray();
336 for (const auto& stage : result.stages) {
337 writer.StartObject();
338 writer.Key("index");
339 writer.Uint64(stage.index);
340 writer.Key("segments");
341 writer.StartArray();
342 for (const auto& seg : stage.segments) {
343 writer.String(seg.c_str(), seg.size());
344 }
345 writer.EndArray();
346 writer.EndObject();
347 }
348 writer.EndArray();
349 writer.Key("pipelineStages");
350 writer.StartArray();
351 for (const auto& ps : result.pipelineStages) {
352 WriteInspectionResultJson(writer, ps);
353 }
354 writer.EndArray();
355 writer.Key("output");
356 writer.String(result.output.c_str(), result.output.size());
357 writer.EndObject();
358 }
359
360 // Serializes the full inspection result as a JSON object. Used with
361 // --inspect mode. Handles both single-stage and pipeline converters.
362 std::string SerializeInspectionResultJson(
363 const ConversionInspectionResult& result) {
364 rapidjson::StringBuffer buffer;
365 rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
366 WriteInspectionResultJson(writer, result);
367 return buffer.GetString();
368 }
369
370 std::string ConvertLineByMode(const std::string& line) {
371 WarnIfTextContainsVariationSelector(line.c_str(), line.size());
372 const auto convertStart = std::chrono::steady_clock::now();
373 std::string output;
374 if (outputMode == OutputMode::Segmentation) {
375 // True segmentation-only path: call the segmenter directly without
376 // running any conversion stage.
377 const SegmentsPtr& segments =
378 converter->GetSegmentation()->Segment(std::string_view(line));
379 ConversionInspectionResult result;
380 result.input = line;
381 result.segments = segments->ToVector();
382 output = SerializeSegmentationResultJson(result);
383 } else if (outputMode == OutputMode::Inspect) {
384 const ConversionInspectionResult& result = converter->Inspect(line);
385 output = SerializeInspectionResultJson(result);
386 } else {
387 output = converter->Convert(std::string_view(line));
388 }
389 measurement.convertMs += DurationToMilliseconds(
390 std::chrono::steady_clock::now() - convertStart);
391 return output;
392 }
393
394 void ConvertStream(FILE* fin, FILE* fout) {
395 const int BUFFER_SIZE = 1024 * 1024;
396 std::string buffer(BUFFER_SIZE, '\0');
397 ConverterStream stream(converter);
398
399 while (!feof(fin)) {
400 size_t length = fread(&buffer[0], sizeof(char), buffer.size(), fin);
401 if (length == 0) {
402 break;
403 }
404 measurement.inputBytes += length;
405 WarnIfStreamChunkContainsVariationSelector(buffer.data(), length);
406
407 const auto convertStart = std::chrono::steady_clock::now();
408 const bool isFinalChunk = length < buffer.size() && feof(fin);
409 const std::string converted =
410 isFinalChunk ? stream.Finish({buffer.data(), length})
411 : stream.ConvertChunk({buffer.data(), length});
412 measurement.convertMs += DurationToMilliseconds(
413 std::chrono::steady_clock::now() - convertStart);
414 measurement.outputBytes += converted.size();
415 const auto writeStart = std::chrono::steady_clock::now();
416 fputs(converted.c_str(), fout);
417 if (!noFlush) {
418 fflush(fout);
419 }
420 measurement.writeMs += DurationToMilliseconds(
421 std::chrono::steady_clock::now() - writeStart);
422 if (isFinalChunk) {
423 return;
424 }
425 }
426
427 const auto convertStart = std::chrono::steady_clock::now();
428 const std::string& converted = stream.Finish();
429 measurement.convertMs += DurationToMilliseconds(
430 std::chrono::steady_clock::now() - convertStart);
431 measurement.outputBytes += converted.size();
432 const auto writeStart = std::chrono::steady_clock::now();
433 fputs(converted.c_str(), fout);
434 if (!noFlush) {
435 fflush(fout);
436 }
437 measurement.writeMs += DurationToMilliseconds(
438 std::chrono::steady_clock::now() - writeStart);
439 }
440
441 void ConvertLineByLine() {
442 PrintInteractiveStdinHint();
443 std::istream& inputStream = std::cin;
444 FILE* fout = GetOutputStream();
445 bool isFirstLine = true;
446 std::string line;
447 while (std::getline(inputStream, line)) {
448 if (!isFirstLine) {
449 fputs("\n", fout);
450 } else {
451 isFirstLine = false;
452 }
453 measurement.inputBytes += line.size();
454 const std::string& output = ConvertLineByMode(line);
455 measurement.outputBytes += output.size();
456 const auto writeStart = std::chrono::steady_clock::now();
457 fputs(output.c_str(), fout);
458 if (!noFlush) {
459 // Flush every line if the output stream is stdout.
460 fflush(fout);
461 }
462 measurement.writeMs += DurationToMilliseconds(
463 std::chrono::steady_clock::now() - writeStart);
464 }
465 fclose(fout);
466 }
467
468 void ConvertFileStreams(FILE* fin, FILE* fout) {
469 try {
470 if (outputMode == OutputMode::Segmentation ||
471 outputMode == OutputMode::Inspect) {
472 // Inspect/segmentation modes process line by line using std::getline to
473 // handle arbitrarily long lines.
474 bool isFirstLine = true;
475 std::string line;
476 while (ReadLine(fin, &line)) {
477 if (!line.empty() && line.back() == '\r') {
478 line.pop_back();
479 }
480 measurement.inputBytes += line.size();
481 if (!isFirstLine) {
482 fputs("\n", fout);
483 } else {
484 isFirstLine = false;
485 }
486 const std::string& output = ConvertLineByMode(line);
487 measurement.outputBytes += output.size();
488 const auto writeStart = std::chrono::steady_clock::now();
489 fputs(output.c_str(), fout);
490 if (!noFlush) {
491 fflush(fout);
492 }
493 measurement.writeMs += DurationToMilliseconds(
494 std::chrono::steady_clock::now() - writeStart);
495 }
496 } else {
497 ConvertStream(fin, fout);
498 }
499 } catch (...) {
500 fclose(fin);
501 fclose(fout);
502 throw;
503 }
504
505 fclose(fin);
506 fclose(fout);
507 }
508
509 void ConvertFile(std::string fileName) {
510 FILE* fin = OpenFileUtf8(fileName, "rb");
511 if (!fin) {
512 throw FileNotFound(fileName);
513 }
514
515 if (!outputFileName.IsNull() &&
516 IsSameFileUtf8(fileName, outputFileName.Get())) {
517 if (!inPlace) {
518 fclose(fin);
519 throw Exception("Input and output refer to the same file; use "
520 "--in-place to overwrite it.");
521 }
522
523 std::string targetFileName = outputFileName.Get();
524 GetRealPathUtf8(outputFileName.Get(), &targetFileName);
525 if (HasMultipleLinksUtf8(targetFileName)) {
526 fclose(fin);
527 throw Exception("--in-place cannot safely update files with multiple "
528 "hard links.");
529 }
530
531 std::string tempFileName;
532 FILE* fout = CreateTempFileNearUtf8(targetFileName, &tempFileName);
533 if (!fout) {
534 fclose(fin);
535 if (tempFileName.empty()) {
536 tempFileName = "temporary file";
537 }
538 throw FileNotWritable(tempFileName);
539 }
540
541 try {
542 ConvertFileStreams(fin, fout);
543 if (PreserveMetadataUtf8(targetFileName, tempFileName) != 0) {
544 RemoveFileUtf8(tempFileName);
545 throw FileNotWritable(tempFileName);
546 }
547 if (ReplaceFileUtf8(tempFileName, targetFileName) != 0) {
548 RemoveFileUtf8(tempFileName);
549 throw FileNotWritable(targetFileName);
550 }
551 } catch (...) {
552 RemoveFileUtf8(tempFileName);
553 throw;
554 }
555 return;
556 }
557
558 FILE* fout = GetOutputStream();
559 ConvertFileStreams(fin, fout);
560 }
561
562 void ConvertStdin() {
563 PrintInteractiveStdinHint();
564 SetBinaryMode(stdin);
565 FILE* fout = GetOutputStream();
566 ConvertStream(stdin, fout);
567 fclose(fout);
568 }
569
570 namespace opencc {
571 namespace tools {
572
573 int CommandLineMain(std::vector<std::string> args) {
574 try {
575 const auto totalStart = std::chrono::steady_clock::now();
576 TCLAP::CmdLine cmd("Open Chinese Convert (OpenCC) Command Line Tool", ' ',
577 OPENCC_VERSION);
578 OpenCCOutput cmdLineOutput;
579 cmd.setOutput(&cmdLineOutput);
580
581 TCLAP::ValueArg<std::string> configArg(
582 "c", "config", "Configuration file", false /* required */,
583 "s2t.json" /* default */, "file" /* type */, cmd);
584 TCLAP::ValueArg<std::string> outputArg(
585 "o", "output", "Write converted text to <file>.", false /* required */,
586 "" /* default */, "file" /* type */, cmd);
587 TCLAP::ValueArg<std::string> inputArg(
588 "i", "input", "Read original text from <file>.", false /* required */,
589 "" /* default */, "file" /* type */, cmd);
590 TCLAP::ValueArg<bool> noFlushArg(
591 "", "noflush", "Disable flush for every line", false /* required */,
592 false /* default */, "bool" /* type */, cmd);
593 TCLAP::SwitchArg inPlaceArg(
594 "", "in-place",
595 "Allow overwriting the input file when input and output refer to the "
596 "same file.",
597 cmd, false);
598 TCLAP::MultiArg<std::string> pathArg(
599 "", "path", "Additional paths to locate config and dictionary files.",
600 false /* required */, "file" /* type */, cmd);
601 TCLAP::ValueArg<std::string> measuredResultArg(
602 "", "measured_result",
603 "Write measured timing results as JSON to <file>.", false /* required */,
604 "" /* default */, "file" /* type */, cmd);
605 TCLAP::SwitchArg segmentationArg(
606 "", "segmentation",
607 "Output segmentation result as JSON instead of converted text.", cmd,
608 false);
609 TCLAP::SwitchArg inspectArg(
610 "", "inspect",
611 "Output full inspection result (segmentation + per-stage conversion + "
612 "final output) as JSON.",
613 cmd, false);
614 TCLAP::SwitchArg includeTofuRiskDictionariesArg(
615 "", "include-tofu-risk-dictionaries",
616 "Include dictionaries marked as possibly outputting tofu, i.e. "
617 "Chinese characters that may render as missing-glyph boxes. By "
618 "default, the command line tool skips these dictionaries.",
619 cmd, false);
620 const std::string argv0String = args.empty() ? std::string() : args[0];
621 Optional<std::string> resourceZipFileName =
622 Optional<std::string>::Null();
623 std::vector<std::string> visibleArgs;
624 if (!args.empty()) {
625 visibleArgs.push_back(args[0]);
626 }
627 for (size_t i = 1; i < args.size(); i++) {
628 const std::string& arg = args[i];
629 std::string value;
630 if (arg == "--resource-zip") {
631 if (i + 1 >= args.size() || args[i + 1].empty() ||
632 args[i + 1][0] == '-') {
633 std::cerr << "error: Missing value for " << arg << std::endl;
634 return 1;
635 }
636 value = args[++i];
637 } else if (arg.rfind("--resource-zip=", 0) == 0) {
638 value = arg.substr(std::string("--resource-zip=").size());
639 } else {
640 visibleArgs.push_back(arg);
641 continue;
642 }
643 if (value.empty()) {
644 std::cerr << "error: Missing value for " << arg << std::endl;
645 return 1;
646 }
647 if (!resourceZipFileName.IsNull()) {
648 std::cerr << "error: resource zip specified more than once."
649 << std::endl;
650 return 1;
651 }
652 resourceZipFileName = Optional<std::string>(value);
653 }
654 cmd.parse(visibleArgs);
655
656 // Validate mutual exclusion and dependencies
657 if (segmentationArg.getValue() && inspectArg.getValue()) {
658 std::cerr << "error: --segmentation and --inspect are mutually exclusive."
659 << std::endl;
660 return 1;
661 }
662
663 if (segmentationArg.getValue()) {
664 outputMode = OutputMode::Segmentation;
665 } else if (inspectArg.getValue()) {
666 outputMode = OutputMode::Inspect;
667 } else {
668 outputMode = OutputMode::Convert;
669 }
670
671 configFileName = configArg.getValue();
672 noFlush = noFlushArg.getValue();
673 inPlace = inPlaceArg.getValue();
674 if (measuredResultArg.isSet()) {
675 measuredResultFileName =
676 Optional<std::string>(measuredResultArg.getValue());
677 }
678 if (inputArg.isSet()) {
679 inputFileName = Optional<std::string>(inputArg.getValue());
680 }
681 if (outputArg.isSet()) {
682 outputFileName = Optional<std::string>(outputArg.getValue());
683 noFlush = true;
684 }
685 const auto loadStart = std::chrono::steady_clock::now();
686 const char* argv0 = argv0String.empty() ? nullptr : argv0String.c_str();
687 ConfigLoadOptions configOptions;
688 configOptions.includeTofuRiskDictionaries =
689 includeTofuRiskDictionariesArg.getValue();
690 if (!resourceZipFileName.IsNull()) {
691 std::shared_ptr<ResourceProvider> provider(
692 new ZipResourceProvider(resourceZipFileName.Get()));
693 converter = config.NewFromFile(configFileName, provider, configOptions);
694 } else {
695 converter =
696 config.NewFromFile(configFileName, pathArg.getValue(), argv0,
697 configOptions);
698 }
699 measurement.loadMs +=
700 DurationToMilliseconds(std::chrono::steady_clock::now() - loadStart);
701 if (outputMode == OutputMode::Segmentation &&
702 converter->GetSegmentation() == nullptr) {
703 std::cerr << "error: this configuration has no segmentation step; "
704 "--segmentation is not supported.\n";
705 return 1;
706 }
707 bool lineByLine = inputFileName.IsNull();
708 measurement.lineByLine = lineByLine;
709 measurement.outputMode = outputMode;
710 if (lineByLine && outputMode == OutputMode::Convert) {
711 ConvertStdin();
712 } else if (lineByLine) {
713 ConvertLineByLine();
714 } else {
715 ConvertFile(inputFileName.Get());
716 }
717 measurement.totalMs +=
718 DurationToMilliseconds(std::chrono::steady_clock::now() - totalStart);
719 WriteMeasuredResult();
720 } catch (TCLAP::ArgException& e) {
721 std::cerr << "error: " << e.error() << " for arg " << e.argId()
722 << std::endl;
723 return 1;
724 } catch (Exception& e) {
725 std::cerr << e.what() << std::endl;
726 return 1;
727 }
728 return 0;
729 }
730
731 } // namespace tools
732 } // namespace opencc