11#include "../core/endian_func.hpp"
12#include "../error_func.h"
13#include "../string_func.h"
14#include "../strings_type.h"
15#include "../misc/getoptdata.h"
16#include "../table/control_codes.h"
17#include "../3rdparty/fmt/std.h"
24#include "../table/strgen_tables.h"
26#include "../safeguards.h"
30# define LINE_NUM_FMT(s) "{} ({}): warning: {} (" s ")\n"
32# define LINE_NUM_FMT(s) "{}:{}: " s ": {}\n"
35void StrgenWarningI(
const std::string &msg)
38 fmt::print(stderr, LINE_NUM_FMT(
"info"), _strgen.
file, _strgen.
cur_line, msg);
40 fmt::print(stderr, LINE_NUM_FMT(
"warning"), _strgen.
file, _strgen.
cur_line, msg);
45void StrgenErrorI(
const std::string &msg)
47 fmt::print(stderr, LINE_NUM_FMT(
"error"), _strgen.
file, _strgen.
cur_line, msg);
51[[noreturn]]
void StrgenFatalI(
const std::string &msg)
53 fmt::print(stderr, LINE_NUM_FMT(
"FATAL"), _strgen.
file, _strgen.
cur_line, msg);
55 fmt::print(stderr, LINE_NUM_FMT(
"warning"), _strgen.
file, _strgen.
cur_line,
"language is not compiled");
57 throw std::exception();
62 fmt::print(stderr, LINE_NUM_FMT(
"FATAL"), _strgen.
file, _strgen.
cur_line, msg);
64 fmt::print(stderr, LINE_NUM_FMT(
"warning"), _strgen.
file, _strgen.
cur_line,
"language is not compiled");
71 std::ifstream input_stream;
83 this->input_stream.open(
file, std::ifstream::binary);
89 if (!std::getline(this->input_stream, result))
return std::nullopt;
100 FatalError(
"Language must include ##name, ##ownname and ##isocode");
111 }
else if (name ==
"name") {
113 }
else if (name ==
"ownname") {
115 }
else if (name ==
"isocode") {
117 }
else if (name ==
"textdir") {
121 }
else if (dir ==
"rtl") {
124 FatalError(
"Invalid textdir {}", dir);
126 }
else if (name ==
"digitsep") {
129 }
else if (name ==
"digitsepcur") {
132 }
else if (name ==
"decimalsep") {
135 }
else if (name ==
"winlangid") {
137 if (langid > UINT16_MAX || langid < 0) {
138 FatalError(
"Invalid winlangid {}", langid);
140 lang.
winlangid =
static_cast<uint16_t
>(langid);
141 }
else if (name ==
"grflangid") {
143 if (langid >= 0x7F || langid < 0) {
144 FatalError(
"Invalid grflangid {}", langid);
147 }
else if (name ==
"gender") {
148 if (this->
master) FatalError(
"Genders are not allowed in the base translation.");
150 auto s = ParseWord(consumer);
152 if (!s.has_value())
break;
157 }
else if (name ==
"case") {
158 if (this->
master) FatalError(
"Cases are not allowed in the base translation.");
160 auto s = ParseWord(consumer);
162 if (!s.has_value())
break;
172static bool CompareFiles(
const std::filesystem::path &path1,
const std::filesystem::path &path2)
175 std::error_code error_code;
176 if (std::filesystem::file_size(path1, error_code) != std::filesystem::file_size(path2, error_code))
return false;
178 std::ifstream stream1(path1, std::ifstream::binary);
179 std::ifstream stream2(path2, std::ifstream::binary);
181 return std::equal(std::istreambuf_iterator<char>(stream1.rdbuf()),
182 std::istreambuf_iterator<char>(),
183 std::istreambuf_iterator<char>(stream2.rdbuf()));
189 const std::filesystem::path
path;
198 this->output_stream.open(
path, openmode);
204 this->output_stream.close();
211 if (this->output_stream.is_open()) {
212 this->output_stream.close();
213 std::filesystem::remove(this->path);
223 size_t total_strings;
232 this->
output_stream <<
"/* This file is automatically generated. Do not modify */\n\n";
240 fmt::print(this->
output_stream,
"static const StringID {} = 0x{:X};\n", name, stringid);
248 size_t max_plural_forms = 0;
250 max_plural_forms = std::max(max_plural_forms, pf.plural_count);
255 "static const uint LANGUAGE_PACK_VERSION = 0x{:X};\n"
256 "static const uint LANGUAGE_MAX_PLURAL = {};\n"
257 "static const uint LANGUAGE_MAX_PLURAL_FORMS = {};\n"
258 "static const uint LANGUAGE_TOTAL_STRINGS = {};\n"
267 std::error_code error_code;
268 if (CompareFiles(this->
path, this->real_path)) {
270 std::filesystem::remove(this->
path, error_code);
273 std::filesystem::rename(this->
path, this->real_path, error_code);
274 if (error_code) FatalError(
"rename({}, {}) failed: {}", this->
path, this->real_path, error_code.message());
291 this->
Write({
reinterpret_cast<const char *
>(header),
sizeof(*header)});
300 void Write(std::string_view buffer)
override
300 void Write(std::string_view buffer)
override {
…}
309 { .type =
ODF_NO_VALUE, .id =
'L', .longname =
"-export-plurals" },
310 { .type =
ODF_NO_VALUE, .id =
'P', .longname =
"-export-pragmas" },
311 { .type =
ODF_NO_VALUE, .id =
't', .shortname =
't', .longname =
"--todo" },
312 { .type =
ODF_NO_VALUE, .id =
'w', .shortname =
'w', .longname =
"--warning" },
313 { .type =
ODF_NO_VALUE, .id =
'h', .shortname =
'h', .longname =
"--help" },
315 { .type =
ODF_HAS_VALUE, .id =
's', .shortname =
's', .longname =
"--source_dir" },
316 { .type =
ODF_HAS_VALUE, .id =
'd', .shortname =
'd', .longname =
"--dest_dir" },
319int CDECL main(
int argc,
char *argv[])
321 std::filesystem::path src_dir(
".");
322 std::filesystem::path dest_dir;
324 std::vector<std::string_view> params;
325 for (
int i = 1; i < argc; ++i) params.emplace_back(argv[i]);
328 int i = mgo.GetOpt();
333 fmt::print(
"args\tflags\tcommand\treplacement\n");
334 for (
const auto &cs : _cmd_structs) {
336 if (cs.proc == EmitGender) {
338 }
else if (cs.proc == EmitPlural) {
345 fmt::print(
"{}\t{:c}\t\"{}\"\t\"{}\"\n", cs.consumes, flags, cs.cmd, cs.cmd.find(
"STRING") != std::string::npos ?
"STRING" : cs.cmd);
350 fmt::print(
"count\tdescription\tnames\n");
352 fmt::print(
"{}\t\"{}\"\t{}\n", pf.plural_count, pf.description, pf.names);
357 fmt::print(
"name\tflags\tdefault\tdescription\n");
358 for (
const auto &pragma :
_pragmas) {
359 fmt::print(
"\"{}\"\t{}\t\"{}\"\t\"{}\"\n",
360 pragma[0], pragma[1], pragma[2], pragma[3]);
365 _strgen.annotate_todos =
true;
369 _strgen.show_warnings =
true;
375 " -t | --todo replace any untranslated strings with '<TODO>'\n"
376 " -w | --warning print a warning for any untranslated strings\n"
377 " -h | -? | --help print this help message and exit\n"
378 " -s | --source_dir search for english.txt in the specified directory\n"
379 " -d | --dest_dir put output file in the specified directory, create if needed\n"
380 " -export-commands export all commands and exit\n"
381 " -export-plurals export all plural forms and exit\n"
382 " -export-pragmas export all pragmas and exit\n"
383 " Run without parameters and strgen will search for english.txt and parse it,\n"
384 " creating strings.h. Passing an argument, strgen will translate that language\n"
385 " file using english.txt as a reference and output <language>.lng.\n"
398 fmt::print(stderr,
"Invalid arguments\n");
403 if (dest_dir.empty()) dest_dir = src_dir;
410 if (mgo.arguments.empty()) {
411 std::filesystem::path input_path = std::move(src_dir);
412 input_path /=
"english.txt";
417 master_reader.ParseFile();
418 if (_strgen.errors != 0)
return 1;
421 std::filesystem::path output_path = dest_dir;
422 std::filesystem::create_directories(dest_dir);
423 output_path /=
"strings.h";
426 writer.WriteHeader(data);
427 writer.Finalise(data);
428 if (_strgen.errors != 0)
return 1;
430 std::filesystem::path input_path = std::move(src_dir);
431 input_path /=
"english.txt";
436 master_reader.ParseFile();
438 for (
auto &argument: mgo.arguments) {
439 data.FreeTranslation();
441 std::filesystem::path lang_file = argument;
442 FileStringReader translation_reader(data, lang_file,
false, lang_file.filename() !=
"english.txt");
443 translation_reader.ParseFile();
444 if (_strgen.errors != 0)
return 1;
447 std::filesystem::path output_file = dest_dir;
448 output_file /= lang_file.filename();
449 output_file.replace_extension(
"lng");
452 writer.WriteLang(data);
456 if (_strgen.show_warnings) {
457 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?