11#include "../error_func.h"
12#include "../string_func.h"
13#include "../strings_type.h"
14#include "../misc/getoptdata.h"
15#include "../table/control_codes.h"
16#include "../3rdparty/fmt/std.h"
23#include "../table/strgen_tables.h"
25#include "../safeguards.h"
29# define LINE_NUM_FMT(s) "{} ({}): warning: {} (" s ")\n"
31# define LINE_NUM_FMT(s) "{}:{}: " s ": {}\n"
34void StrgenWarningI(
const std::string &msg)
37 fmt::print(stderr, LINE_NUM_FMT(
"info"), _strgen.
file, _strgen.
cur_line, msg);
39 fmt::print(stderr, LINE_NUM_FMT(
"warning"), _strgen.
file, _strgen.
cur_line, msg);
44void StrgenErrorI(
const std::string &msg)
46 fmt::print(stderr, LINE_NUM_FMT(
"error"), _strgen.
file, _strgen.
cur_line, msg);
50[[noreturn]]
void StrgenFatalI(
const std::string &msg)
52 fmt::print(stderr, LINE_NUM_FMT(
"FATAL"), _strgen.
file, _strgen.
cur_line, msg);
54 fmt::print(stderr, LINE_NUM_FMT(
"warning"), _strgen.
file, _strgen.
cur_line,
"language is not compiled");
56 throw std::exception();
61 fmt::print(stderr, LINE_NUM_FMT(
"FATAL"), _strgen.
file, _strgen.
cur_line, msg);
63 fmt::print(stderr, LINE_NUM_FMT(
"warning"), _strgen.
file, _strgen.
cur_line,
"language is not compiled");
70 std::ifstream input_stream;
82 this->input_stream.open(
file, std::ifstream::binary);
88 if (!std::getline(this->input_stream, result))
return std::nullopt;
99 FatalError(
"Language must include ##name, ##ownname and ##isocode");
110 }
else if (name ==
"name") {
112 }
else if (name ==
"ownname") {
114 }
else if (name ==
"isocode") {
116 }
else if (name ==
"textdir") {
120 }
else if (dir ==
"rtl") {
123 FatalError(
"Invalid textdir {}", dir);
125 }
else if (name ==
"digitsep") {
128 }
else if (name ==
"digitsepcur") {
131 }
else if (name ==
"decimalsep") {
134 }
else if (name ==
"winlangid") {
136 if (langid > UINT16_MAX || langid < 0) {
137 FatalError(
"Invalid winlangid {}", langid);
139 lang.
winlangid =
static_cast<uint16_t
>(langid);
140 }
else if (name ==
"grflangid") {
142 if (langid >= 0x7F || langid < 0) {
143 FatalError(
"Invalid grflangid {}", langid);
146 }
else if (name ==
"gender") {
147 if (this->
master) FatalError(
"Genders are not allowed in the base translation.");
149 auto s = ParseWord(consumer);
151 if (!s.has_value())
break;
156 }
else if (name ==
"case") {
157 if (this->
master) FatalError(
"Cases are not allowed in the base translation.");
159 auto s = ParseWord(consumer);
161 if (!s.has_value())
break;
171static bool CompareFiles(
const std::filesystem::path &path1,
const std::filesystem::path &path2)
174 std::error_code error_code;
175 if (std::filesystem::file_size(path1, error_code) != std::filesystem::file_size(path2, error_code))
return false;
177 std::ifstream stream1(path1, std::ifstream::binary);
178 std::ifstream stream2(path2, std::ifstream::binary);
180 return std::equal(std::istreambuf_iterator<char>(stream1.rdbuf()),
181 std::istreambuf_iterator<char>(),
182 std::istreambuf_iterator<char>(stream2.rdbuf()));
188 const std::filesystem::path
path;
197 this->output_stream.open(
path, openmode);
203 this->output_stream.close();
210 if (this->output_stream.is_open()) {
211 this->output_stream.close();
212 std::filesystem::remove(this->path);
222 size_t total_strings;
231 this->
output_stream <<
"/* This file is automatically generated. Do not modify */\n\n";
239 fmt::print(this->
output_stream,
"static const StringID {} = 0x{:X};\n", name, stringid);
247 size_t max_plural_forms = 0;
249 max_plural_forms = std::max(max_plural_forms, pf.plural_count);
254 "static const uint LANGUAGE_PACK_VERSION = 0x{:X};\n"
255 "static const uint LANGUAGE_MAX_PLURAL = {};\n"
256 "static const uint LANGUAGE_MAX_PLURAL_FORMS = {};\n"
257 "static const uint LANGUAGE_TOTAL_STRINGS = {};\n"
266 std::error_code error_code;
267 if (CompareFiles(this->
path, this->real_path)) {
269 std::filesystem::remove(this->
path, error_code);
272 std::filesystem::rename(this->
path, this->real_path, error_code);
273 if (error_code) FatalError(
"rename({}, {}) failed: {}", this->
path, this->real_path, error_code.message());
290 this->
Write({
reinterpret_cast<const char *
>(header),
sizeof(*header)});
299 void Write(std::string_view buffer)
override
308 { .type =
ODF_NO_VALUE, .id =
'L', .longname =
"-export-plurals" },
309 { .type =
ODF_NO_VALUE, .id =
'P', .longname =
"-export-pragmas" },
310 { .type =
ODF_NO_VALUE, .id =
't', .shortname =
't', .longname =
"--todo" },
311 { .type =
ODF_NO_VALUE, .id =
'w', .shortname =
'w', .longname =
"--warning" },
312 { .type =
ODF_NO_VALUE, .id =
'h', .shortname =
'h', .longname =
"--help" },
314 { .type =
ODF_HAS_VALUE, .id =
's', .shortname =
's', .longname =
"--source_dir" },
315 { .type =
ODF_HAS_VALUE, .id =
'd', .shortname =
'd', .longname =
"--dest_dir" },
318int CDECL main(
int argc,
char *argv[])
320 std::filesystem::path src_dir(
".");
321 std::filesystem::path dest_dir;
323 std::vector<std::string_view> params;
324 for (
int i = 1; i < argc; ++i) params.emplace_back(argv[i]);
327 int i = mgo.GetOpt();
332 fmt::print(
"args\tflags\tcommand\treplacement\n");
333 for (
const auto &cs : _cmd_structs) {
335 if (cs.proc == EmitGender) {
337 }
else if (cs.proc == EmitPlural) {
344 fmt::print(
"{}\t{:c}\t\"{}\"\t\"{}\"\n", cs.consumes, flags, cs.cmd, cs.cmd.find(
"STRING") != std::string::npos ?
"STRING" : cs.cmd);
349 fmt::print(
"count\tdescription\tnames\n");
351 fmt::print(
"{}\t\"{}\"\t{}\n", pf.plural_count, pf.description, pf.names);
356 fmt::print(
"name\tflags\tdefault\tdescription\n");
357 for (
const auto &pragma :
_pragmas) {
358 fmt::print(
"\"{}\"\t{}\t\"{}\"\t\"{}\"\n",
359 pragma[0], pragma[1], pragma[2], pragma[3]);
364 _strgen.annotate_todos =
true;
368 _strgen.show_warnings =
true;
374 " -t | --todo replace any untranslated strings with '<TODO>'\n"
375 " -w | --warning print a warning for any untranslated strings\n"
376 " -h | -? | --help print this help message and exit\n"
377 " -s | --source_dir search for english.txt in the specified directory\n"
378 " -d | --dest_dir put output file in the specified directory, create if needed\n"
379 " -export-commands export all commands and exit\n"
380 " -export-plurals export all plural forms and exit\n"
381 " -export-pragmas export all pragmas and exit\n"
382 " Run without parameters and strgen will search for english.txt and parse it,\n"
383 " creating strings.h. Passing an argument, strgen will translate that language\n"
384 " file using english.txt as a reference and output <language>.lng.\n"
397 fmt::print(stderr,
"Invalid arguments\n");
402 if (dest_dir.empty()) dest_dir = src_dir;
409 if (mgo.arguments.empty()) {
410 std::filesystem::path input_path = std::move(src_dir);
411 input_path /=
"english.txt";
416 master_reader.ParseFile();
417 if (_strgen.errors != 0)
return 1;
420 std::filesystem::path output_path = dest_dir;
421 std::filesystem::create_directories(dest_dir);
422 output_path /=
"strings.h";
425 writer.WriteHeader(data);
426 writer.Finalise(data);
427 if (_strgen.errors != 0)
return 1;
429 std::filesystem::path input_path = std::move(src_dir);
430 input_path /=
"english.txt";
435 master_reader.ParseFile();
437 for (
auto &argument: mgo.arguments) {
438 data.FreeTranslation();
440 std::filesystem::path lang_file = argument;
441 FileStringReader translation_reader(data, lang_file,
false, lang_file.filename() !=
"english.txt");
442 translation_reader.ParseFile();
443 if (_strgen.errors != 0)
return 1;
446 std::filesystem::path output_file = dest_dir;
447 output_file /= lang_file.filename();
448 output_file.replace_extension(
"lng");
451 writer.WriteLang(data);
455 if (_strgen.show_warnings) {
456 fmt::print(
"{} warnings and {} errors for {}\n", _strgen.warnings, _strgen.errors, output_file);
Parse data from a string / buffer.
std::string_view ReadUntilChar(char c, SeparatorUsage sep)
Read data until the first occurrence of 8-bit char 'c', and advance reader.
@ SKIP_ALL_SEPARATORS
Read and discard all consecutive separators, do not include any in the result.
T ReadIntegerBase(int base, T def=0, bool clamp=false)
Read and parse an integer in number 'base', and advance the reader.
std::string_view Read(size_type len)
Read the next 'len' bytes, and advance reader.
static constexpr size_type npos
Special value for "end of data".
@ ODF_NO_VALUE
A plain option (no value attached to it).
@ ODF_HAS_VALUE
An option with a value.
static const uint8_t MAX_NUM_GENDERS
Maximum number of supported genders.
static const uint8_t CASE_GENDER_LEN
The (maximum) length of a case/gender string.
static const uint8_t MAX_NUM_CASES
Maximum number of supported cases.
static const OptionData _opts[]
Options of strgen.
void FatalErrorI(const std::string &msg)
Error handling for fatal non-user errors.
Structures related to strgen.
static const std::string_view _pragmas[][4]
All pragmas used.
static const PluralForm _plural_forms[]
All plural forms used.
@ DontCount
These commands aren't counted for comparison.
void strecpy(std::span< char > dst, std::string_view src)
Copies characters from one buffer to another.
#define NBSP
A non-breaking space.
@ TEXT_TAB_END
End of language files.
@ TD_LTR
Text is written left-to-right by default.
@ TD_RTL
Text is written right-to-left by default.
A reader that simply reads using fopen.
FileStringReader(StringData &data, const std::filesystem::path &file, bool master, bool translation)
Create the reader.
void ParseFile() override
Start parsing the file.
std::optional< std::string > ReadLine() override
Read a single line from the source of strings.
void HandlePragma(std::string_view str, LanguagePackHeader &lang) override
Handle the pragma of the file.
Yes, simply writing to a file.
std::ofstream output_stream
The stream to write all the output to.
virtual ~FileWriter()
Make sure the file is closed.
const std::filesystem::path path
The file name we're writing to.
FileWriter(const std::filesystem::path &path, std::ios_base::openmode openmode)
Open a file to write to.
void Finalise()
Finalise the writing.
Data storage for parsing command line options.
Class for writing a language to disk.
LanguageFileWriter(const std::filesystem::path &path)
Open a file to write to.
void Finalise() override
Finalise writing the file.
void WriteHeader(const LanguagePackHeader *header) override
Write the header metadata.
void Write(std::string_view buffer) override
Write a number of bytes.
Base class for all language writers.
OptionDataType type
The type of option.
std::string file
The filename of the input, so we can refer to it in errors/warnings.
bool translation
Is the current file actually a translation or not.
LanguagePackHeader lang
Header information about a language.
size_t cur_line
The current line we're parsing in the input file.
Information about the currently known strings.
size_t next_string_id
The next string ID to allocate.
uint32_t Version() const
Make a hash of the file to get a unique "version number".
Helper for reading strings.
const std::string file
The file we are reading.
StringData & data
The data to fill during reading.
virtual void ParseFile()
Start parsing the file.
bool translation
Are we reading a translation, implies !master. However, the base translation will have this false.
virtual void HandlePragma(std::string_view str, LanguagePackHeader &lang)
Handle the pragma of the file.
bool master
Are we reading the master file?