OpenTTD Source 20260206-master-g4d4e37dbf1
settingsgen.cpp
Go to the documentation of this file.
1/*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <https://www.gnu.org/licenses/old-licenses/gpl-2.0>.
6 */
7
9
10#include "../stdafx.h"
12#include "../string_func.h"
13#include "../strings_type.h"
14#include "../misc/getoptdata.h"
15#include "../ini_type.h"
16#include "../error_func.h"
17
18#include <filesystem>
19#include <fstream>
20
21#include "../safeguards.h"
22
28[[noreturn]] void FatalErrorI(const std::string &msg)
29{
30 fmt::print(stderr, "settingsgen: FATAL: {}\n", msg);
31 exit(1);
32}
33
34static const size_t OUTPUT_BLOCK_SIZE = 16000;
35
38public:
40 void Clear()
41 {
42 this->size = 0;
43 }
44
50 size_t Add(std::string_view text)
51 {
52 size_t store_size = text.copy(this->data + this->size, OUTPUT_BLOCK_SIZE - this->size);
53 this->size += store_size;
54 return store_size;
55 }
56
61 void Write(FILE *out_fp) const
62 {
63 if (fwrite(this->data, 1, this->size, out_fp) != this->size) {
64 FatalError("Cannot write output");
65 }
66 }
67
72 bool HasRoom() const
73 {
74 return this->size < OUTPUT_BLOCK_SIZE;
75 }
76
77 size_t size;
79};
80
82class OutputStore {
83public:
84 OutputStore()
85 {
86 this->Clear();
87 }
88
90 void Clear()
91 {
92 this->output_buffer.clear();
93 }
94
99 void Add(std::string_view text)
100 {
101 if (!text.empty() && this->BufferHasRoom()) {
102 size_t stored_size = this->output_buffer[this->output_buffer.size() - 1].Add(text);
103 text.remove_prefix(stored_size);
104 }
105 while (!text.empty()) {
106 OutputBuffer &block = this->output_buffer.emplace_back();
107 block.Clear(); // Initialize the new block.
108 size_t stored_size = block.Add(text);
109 text.remove_prefix(stored_size);
110 }
111 }
112
117 void Write(FILE *out_fp) const
118 {
119 for (const OutputBuffer &out_data : output_buffer) {
120 out_data.Write(out_fp);
121 }
122 }
123
124private:
129 bool BufferHasRoom() const
130 {
131 size_t num_blocks = this->output_buffer.size();
132 return num_blocks > 0 && this->output_buffer[num_blocks - 1].HasRoom();
133 }
134
135 typedef std::vector<OutputBuffer> OutputBufferVector;
137};
138
139
147 SettingsIniFile(const IniGroupNameList &list_group_names = {}, const IniGroupNameList &seq_group_names = {}) :
149 {
150 }
151
152 std::optional<FileHandle> OpenFile(std::string_view filename, Subdirectory, size_t *size) override
153 {
154 /* Open the text file in binary mode to prevent end-of-line translations
155 * done by ftell() and friends, as defined by K&R. */
156 auto in = FileHandle::Open(filename, "rb");
157 if (!in.has_value()) return in;
158
159 fseek(*in, 0L, SEEK_END);
160 *size = ftell(*in);
161 fseek(*in, 0L, SEEK_SET); // Seek back to the start of the file.
162
163 return in;
164 }
165
166 void ReportFileError(std::string_view message) override
167 {
168 FatalError("{}", message);
169 }
170};
171
174
175static const std::string_view PREAMBLE_GROUP_NAME = "pre-amble";
176static const std::string_view POSTAMBLE_GROUP_NAME = "post-amble";
177static const std::string_view TEMPLATES_GROUP_NAME = "templates";
178static const std::string_view VALIDATION_GROUP_NAME = "validation";
179static const std::string_view DEFAULTS_GROUP_NAME = "defaults";
180
186static void DumpGroup(const IniLoadFile &ifile, std::string_view group_name)
187{
188 const IniGroup *grp = ifile.GetGroup(group_name);
189 if (grp != nullptr && grp->type == IGT_SEQUENCE) {
190 for (const IniItem &item : grp->items) {
191 if (!item.name.empty()) {
192 _stored_output.Add(item.name);
193 _stored_output.Add("\n");
194 }
195 }
196 }
197}
198
206static std::optional<std::string_view> FindItemValue(std::string_view name, const IniGroup *grp, const IniGroup *defaults)
207{
208 const IniItem *item = grp->GetItem(name);
209 if (item == nullptr && defaults != nullptr) item = defaults->GetItem(name);
210 if (item == nullptr) return std::nullopt;
211 return item->value;
212}
213
221static void DumpLine(const IniItem *item, const IniGroup *grp, const IniGroup *default_grp, OutputStore &output)
222{
223 /* Prefix with #if/#ifdef/#ifndef */
224 static const auto pp_lines = {"if", "ifdef", "ifndef"};
225 int count = 0;
226 for (const auto &name : pp_lines) {
227 auto condition = FindItemValue(name, grp, default_grp);
228 if (condition.has_value()) {
229 output.Add("#");
230 output.Add(name);
231 output.Add(" ");
232 output.Add(*condition);
233 output.Add("\n");
234 count++;
235 }
236 }
237
238 /* Output text of the template, except template variables of the form '$[_a-z0-9]+' which get replaced by their value. */
239 static const std::string_view variable_name_characters = "_abcdefghijklmnopqrstuvwxyz0123456789";
240 StringConsumer consumer{*item->value};
241 while (consumer.AnyBytesLeft()) {
242 char c = consumer.ReadChar();
243 if (c != '$' || consumer.ReadIf("$")) {
244 /* No $ or $$ (literal $). */
245 output.Add(std::string_view{&c, 1});
246 continue;
247 }
248
249 std::string_view variable = consumer.ReadUntilCharNotIn(variable_name_characters);
250 if (!variable.empty()) {
251 /* Find the text to output. */
252 auto valitem = FindItemValue(variable, grp, default_grp);
253 if (valitem.has_value()) output.Add(*valitem);
254 } else {
255 output.Add("$");
256 }
257 }
258 output.Add("\n"); // \n after the expanded template.
259 while (count > 0) {
260 output.Add("#endif\n");
261 count--;
262 }
263}
264
269static void DumpSections(const IniLoadFile &ifile)
270{
272
273 const IniGroup *default_grp = ifile.GetGroup(DEFAULTS_GROUP_NAME);
274 const IniGroup *templates_grp = ifile.GetGroup(TEMPLATES_GROUP_NAME);
275 const IniGroup *validation_grp = ifile.GetGroup(VALIDATION_GROUP_NAME);
276 if (templates_grp == nullptr) return;
277
278 /* Output every group, using its name as template name. */
279 for (const IniGroup &grp : ifile.groups) {
280 /* Exclude special group names. */
281 if (std::ranges::find(special_group_names, grp.name) != std::end(special_group_names)) continue;
282
283 const IniItem *template_item = templates_grp->GetItem(grp.name); // Find template value.
284 if (template_item == nullptr || !template_item->value.has_value()) {
285 FatalError("Cannot find template {}", grp.name);
286 }
287 DumpLine(template_item, &grp, default_grp, _stored_output);
288
289 if (validation_grp != nullptr) {
290 const IniItem *validation_item = validation_grp->GetItem(grp.name); // Find template value.
291 if (validation_item != nullptr && validation_item->value.has_value()) {
292 DumpLine(validation_item, &grp, default_grp, _post_amble_output);
293 }
294 }
295 }
296}
297
303static void AppendFile(std::optional<std::string_view> fname, FILE *out_fp)
304{
305 if (!fname.has_value()) return;
306
307 auto in_fp = FileHandle::Open(*fname, "r");
308 if (!in_fp.has_value()) {
309 FatalError("Cannot open file {} for copying", *fname);
310 }
311
312 char buffer[4096];
313 size_t length;
314 do {
315 length = fread(buffer, 1, lengthof(buffer), *in_fp);
316 if (fwrite(buffer, 1, length, out_fp) != length) {
317 FatalError("Cannot copy file");
318 }
319 } while (length == lengthof(buffer));
320}
321
328static bool CompareFiles(std::filesystem::path path1, std::filesystem::path path2)
329{
330 /* Check for equal size, but ignore the error code for cases when a file does not exist. */
331 std::error_code error_code;
332 if (std::filesystem::file_size(path1, error_code) != std::filesystem::file_size(path2, error_code)) return false;
333
334 std::ifstream stream1(path1, std::ifstream::binary);
335 std::ifstream stream2(path2, std::ifstream::binary);
336
337 return std::equal(std::istreambuf_iterator<char>(stream1.rdbuf()),
338 std::istreambuf_iterator<char>(),
339 std::istreambuf_iterator<char>(stream2.rdbuf()));
340}
341
343static const OptionData _opts[] = {
344 { .type = ODF_NO_VALUE, .id = 'h', .shortname = 'h', .longname = "--help" },
345 { .type = ODF_NO_VALUE, .id = 'h', .shortname = '?' },
346 { .type = ODF_HAS_VALUE, .id = 'o', .shortname = 'o', .longname = "--output" },
347 { .type = ODF_HAS_VALUE, .id = 'b', .shortname = 'b', .longname = "--before" },
348 { .type = ODF_HAS_VALUE, .id = 'a', .shortname = 'a', .longname = "--after" },
349};
350
371static void ProcessIniFile(std::string_view fname)
372{
373 static const IniLoadFile::IniGroupNameList seq_groups = {PREAMBLE_GROUP_NAME, POSTAMBLE_GROUP_NAME};
374
375 SettingsIniFile ini{{}, seq_groups};
376 ini.LoadFromDisk(fname, NO_DIRECTORY);
377
379 DumpSections(ini);
381}
382
388int CDECL main(int argc, char *argv[])
389{
390 std::optional<std::string_view> output_file;
391 std::optional<std::string_view> before_file;
392 std::optional<std::string_view> after_file;
393
394 std::vector<std::string_view> params;
395 for (int i = 1; i < argc; ++i) params.emplace_back(argv[i]);
396 GetOptData mgo(params, _opts);
397 for (;;) {
398 int i = mgo.GetOpt();
399 if (i == -1) break;
400
401 switch (i) {
402 case 'h':
403 fmt::print("settingsgen\n"
404 "Usage: settingsgen [options] ini-file...\n"
405 "with options:\n"
406 " -h, -?, --help Print this help message and exit\n"
407 " -b FILE, --before FILE Copy FILE before all settings\n"
408 " -a FILE, --after FILE Copy FILE after all settings\n"
409 " -o FILE, --output FILE Write output to FILE\n");
410 return 0;
411
412 case 'o':
413 output_file = mgo.opt;
414 break;
415
416 case 'a':
417 after_file = mgo.opt;
418 break;
419
420 case 'b':
421 before_file = mgo.opt;
422 break;
423
424 case -2:
425 fmt::print(stderr, "Invalid arguments\n");
426 return 1;
427 }
428 }
429
430 _stored_output.Clear();
431 _post_amble_output.Clear();
432
433 for (auto &argument : mgo.arguments) ProcessIniFile(argument);
434
435 /* Write output. */
436 if (!output_file.has_value()) {
437 AppendFile(before_file, stdout);
438 _stored_output.Write(stdout);
439 _post_amble_output.Write(stdout);
440 AppendFile(after_file, stdout);
441 } else {
442 static const std::string_view tmp_output = "tmp2.xxx";
443
444 auto fp = FileHandle::Open(tmp_output, "w");
445 if (!fp.has_value()) {
446 FatalError("Cannot open file {}", tmp_output);
447 }
448 AppendFile(before_file, *fp);
449 _stored_output.Write(*fp);
450 _post_amble_output.Write(*fp);
451 AppendFile(after_file, *fp);
452 fp.reset();
453
454 std::error_code error_code;
455 if (CompareFiles(tmp_output, *output_file)) {
456 /* Files are equal. tmp2.xxx is not needed. */
457 std::filesystem::remove(tmp_output, error_code);
458 } else {
459 /* Rename tmp2.xxx to output file. */
460 std::filesystem::rename(tmp_output, *output_file, error_code);
461 if (error_code) FatalError("rename({}, {}) failed: {}", tmp_output, *output_file, error_code.message());
462 }
463 }
464 return 0;
465}
466
473std::optional<FileHandle> FileHandle::Open(const std::string &filename, std::string_view mode)
474{
475 auto f = fopen(filename.c_str(), std::string{mode}.c_str());
476 if (f == nullptr) return std::nullopt;
477 return FileHandle(f);
478}
static std::optional< FileHandle > Open(const std::string &filename, std::string_view mode)
Open an RAII file handle if possible.
Definition fileio.cpp:1173
Output buffer for a block of data.
bool HasRoom() const
Does the block have room for more data?
void Clear()
Prepare buffer for use.
size_t Add(std::string_view text)
Add text to the output buffer.
size_t size
Number of bytes stored in data.
void Write(FILE *out_fp) const
Dump buffer to the output stream.
char data[OUTPUT_BLOCK_SIZE]
Stored data.
Temporarily store output.
std::vector< OutputBuffer > OutputBufferVector
Vector type for output buffers.
OutputBufferVector output_buffer
Vector of blocks containing the stored output.
void Add(std::string_view text)
Add text to the output storage.
bool BufferHasRoom() const
Does the buffer have room without adding a new OutputBuffer block?
void Write(FILE *out_fp) const
Write all stored output to the output stream.
void Clear()
Clear the temporary storage.
Parse data from a string / buffer.
char ReadChar(char def='?')
Read 8-bit character, and advance reader.
bool AnyBytesLeft() const noexcept
Check whether any bytes left to read.
std::string_view ReadUntilCharNotIn(std::string_view chars)
Read 8-bit chars, while they are in 'chars', until they are not; and advance reader.
bool ReadIf(std::string_view str)
Check whether the next data matches 'str', and skip it.
Error reporting related functions.
Subdirectory
The different kinds of subdirectories OpenTTD uses.
Definition fileio_type.h:88
@ NO_DIRECTORY
A path without any base directory.
Library for parsing command-line options.
@ ODF_NO_VALUE
A plain option (no value attached to it).
Definition getoptdata.h:15
@ ODF_HAS_VALUE
An option with a value.
Definition getoptdata.h:16
Types related to reading/writing '*.ini' files.
@ IGT_SEQUENCE
A list of uninterpreted lines, terminated by the next group block.
Definition ini_type.h:19
A number of safeguards to prevent using unsafe methods.
OutputStore _stored_output
Temporary storage of the output, until all processing is done.
static const std::string_view VALIDATION_GROUP_NAME
Name of the group containing the validation statements.
static void DumpSections(const IniLoadFile &ifile)
Output all non-special sections through the template / template variable expansion system.
static std::optional< std::string_view > FindItemValue(std::string_view name, const IniGroup *grp, const IniGroup *defaults)
Find the value of a template variable.
static void DumpLine(const IniItem *item, const IniGroup *grp, const IniGroup *default_grp, OutputStore &output)
Parse a single entry via a template and output this.
OutputStore _post_amble_output
Similar to _stored_output, but for the post amble.
static const OptionData _opts[]
Options of settingsgen.
static const std::string_view POSTAMBLE_GROUP_NAME
Name of the group containing the post amble.
static const std::string_view PREAMBLE_GROUP_NAME
Name of the group containing the pre amble.
void FatalErrorI(const std::string &msg)
Report a fatal error.
int CDECL main(int argc, char *argv[])
And the main program (what else?).
static bool CompareFiles(std::filesystem::path path1, std::filesystem::path path2)
Compare two files for identity.
static void AppendFile(std::optional< std::string_view > fname, FILE *out_fp)
Append a file to the output stream.
static const std::string_view DEFAULTS_GROUP_NAME
Name of the group containing default values for the template variables.
static void ProcessIniFile(std::string_view fname)
Process a single INI file.
static void DumpGroup(const IniLoadFile &ifile, std::string_view group_name)
Dump a IGT_SEQUENCE group into _stored_output.
static const std::string_view TEMPLATES_GROUP_NAME
Name of the group containing the templates.
static const size_t OUTPUT_BLOCK_SIZE
Block size of the buffer in OutputBuffer.
Definition of base types and functions in a cross-platform compatible way.
#define lengthof(array)
Return the length of an fixed size array.
Definition stdafx.h:271
Parse strings.
Functions related to low-level strings.
Types related to strings.
Data storage for parsing command line options.
Definition getoptdata.h:29
std::string_view opt
Option value, if available (else empty).
Definition getoptdata.h:35
ArgumentSpan arguments
Remaining command line arguments.
Definition getoptdata.h:33
int GetOpt()
Find the next option.
A group within an ini file.
Definition ini_type.h:34
const IniItem * GetItem(std::string_view name) const
Get the item with the given name.
Definition ini_load.cpp:50
IniGroupType type
type of group
Definition ini_type.h:36
std::string name
name of group
Definition ini_type.h:37
std::list< IniItem > items
all items in the group
Definition ini_type.h:35
A single "line" in an ini file.
Definition ini_type.h:23
std::optional< std::string > value
The value of this item.
Definition ini_type.h:25
std::string name
The name of this item.
Definition ini_type.h:24
Ini file that only supports loading.
Definition ini_type.h:50
std::list< IniGroup > groups
all groups in the ini
Definition ini_type.h:53
const IniGroupNameList seq_group_names
list of group names that are sequences.
Definition ini_type.h:56
IniLoadFile(const IniGroupNameList &list_group_names={}, const IniGroupNameList &seq_group_names={})
Construct a new in-memory Ini file representation.
Definition ini_load.cpp:106
const IniGroup * GetGroup(std::string_view name) const
Get the group with the given name.
Definition ini_load.cpp:117
void LoadFromDisk(std::string_view filename, Subdirectory subdir)
Load the Ini file's data from the disk.
Definition ini_load.cpp:184
const IniGroupNameList list_group_names
list of group names that are lists
Definition ini_type.h:55
Data of an option.
Definition getoptdata.h:21
Derived class for loading INI files without going through Fio stuff.
void ReportFileError(std::string_view message) override
Report an error about the file contents.
SettingsIniFile(const IniGroupNameList &list_group_names={}, const IniGroupNameList &seq_group_names={})
Construct a new ini loader.
std::optional< FileHandle > OpenFile(std::string_view filename, Subdirectory, size_t *size) override
Open the INI file.