OpenTTD
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 <http://www.gnu.org/licenses/>.
6  */
7 
10 #include "../stdafx.h"
11 #include "../string_func.h"
12 #include "../strings_type.h"
13 #include "../misc/getoptdata.h"
14 #include "../ini_type.h"
15 #include "../core/smallvec_type.hpp"
16 
17 #include <stdarg.h>
18 
19 #if !defined(_WIN32) || defined(__CYGWIN__)
20 #include <unistd.h>
21 #include <sys/stat.h>
22 #endif
23 
24 #include "../safeguards.h"
25 
31 void NORETURN CDECL error(const char *s, ...)
32 {
33  char buf[1024];
34  va_list va;
35  va_start(va, s);
36  vseprintf(buf, lastof(buf), s, va);
37  va_end(va);
38  fprintf(stderr, "FATAL: %s\n", buf);
39  exit(1);
40 }
41 
42 static const size_t OUTPUT_BLOCK_SIZE = 16000;
43 
45 class OutputBuffer {
46 public:
48  void Clear()
49  {
50  this->size = 0;
51  }
52 
59  size_t Add(const char *text, size_t length)
60  {
61  size_t store_size = min(length, OUTPUT_BLOCK_SIZE - this->size);
62  assert(store_size <= OUTPUT_BLOCK_SIZE);
63  MemCpyT(this->data + this->size, text, store_size);
64  this->size += store_size;
65  return store_size;
66  }
67 
72  void Write(FILE *out_fp) const
73  {
74  if (fwrite(this->data, 1, this->size, out_fp) != this->size) {
75  fprintf(stderr, "Error: Cannot write output\n");
76  }
77  }
78 
83  bool HasRoom() const
84  {
85  return this->size < OUTPUT_BLOCK_SIZE;
86  }
87 
88  size_t size;
90 };
91 
93 class OutputStore {
94 public:
95  OutputStore()
96  {
97  this->Clear();
98  }
99 
101  void Clear()
102  {
103  this->output_buffer.clear();
104  }
105 
111  void Add(const char *text, size_t length = 0)
112  {
113  if (length == 0) length = strlen(text);
114 
115  if (length > 0 && this->BufferHasRoom()) {
116  size_t stored_size = this->output_buffer[this->output_buffer.size() - 1].Add(text, length);
117  length -= stored_size;
118  text += stored_size;
119  }
120  while (length > 0) {
121  /*C++17: OutputBuffer &block =*/ this->output_buffer.emplace_back();
122  OutputBuffer &block = this->output_buffer.back();
123  block.Clear(); // Initialize the new block.
124  size_t stored_size = block.Add(text, length);
125  length -= stored_size;
126  text += stored_size;
127  }
128  }
129 
134  void Write(FILE *out_fp) const
135  {
136  for (const OutputBuffer &out_data : output_buffer) {
137  out_data.Write(out_fp);
138  }
139  }
140 
141 private:
146  bool BufferHasRoom() const
147  {
148  size_t num_blocks = this->output_buffer.size();
149  return num_blocks > 0 && this->output_buffer[num_blocks - 1].HasRoom();
150  }
151 
152  typedef std::vector<OutputBuffer> OutputBufferVector;
153  OutputBufferVector output_buffer;
154 };
155 
156 
164  SettingsIniFile(const char * const *list_group_names = nullptr, const char * const *seq_group_names = nullptr) :
165  IniLoadFile(list_group_names, seq_group_names)
166  {
167  }
168 
169  virtual FILE *OpenFile(const char *filename, Subdirectory subdir, size_t *size)
170  {
171  /* Open the text file in binary mode to prevent end-of-line translations
172  * done by ftell() and friends, as defined by K&R. */
173  FILE *in = fopen(filename, "rb");
174  if (in == nullptr) return nullptr;
175 
176  fseek(in, 0L, SEEK_END);
177  *size = ftell(in);
178 
179  fseek(in, 0L, SEEK_SET); // Seek back to the start of the file.
180  return in;
181  }
182 
183  virtual void ReportFileError(const char * const pre, const char * const buffer, const char * const post)
184  {
185  error("%s%s%s", pre, buffer, post);
186  }
187 };
188 
190 
191 static const char *PREAMBLE_GROUP_NAME = "pre-amble";
192 static const char *POSTAMBLE_GROUP_NAME = "post-amble";
193 static const char *TEMPLATES_GROUP_NAME = "templates";
194 static const char *DEFAULTS_GROUP_NAME = "defaults";
195 
201 static IniLoadFile *LoadIniFile(const char *filename)
202 {
203  static const char * const seq_groups[] = {PREAMBLE_GROUP_NAME, POSTAMBLE_GROUP_NAME, nullptr};
204 
205  IniLoadFile *ini = new SettingsIniFile(nullptr, seq_groups);
206  ini->LoadFromDisk(filename, NO_DIRECTORY);
207  return ini;
208 }
209 
215 static void DumpGroup(IniLoadFile *ifile, const char * const group_name)
216 {
217  IniGroup *grp = ifile->GetGroup(group_name, 0, false);
218  if (grp != nullptr && grp->type == IGT_SEQUENCE) {
219  for (IniItem *item = grp->item; item != nullptr; item = item->next) {
220  if (item->name) {
221  _stored_output.Add(item->name);
222  _stored_output.Add("\n", 1);
223  }
224  }
225  }
226 }
227 
235 static const char *FindItemValue(const char *name, IniGroup *grp, IniGroup *defaults)
236 {
237  IniItem *item = grp->GetItem(name, false);
238  if (item == nullptr && defaults != nullptr) item = defaults->GetItem(name, false);
239  if (item == nullptr || item->value == nullptr) return nullptr;
240  return item->value;
241 }
242 
247 static void DumpSections(IniLoadFile *ifile)
248 {
249  static const int MAX_VAR_LENGTH = 64;
250  static const char * const special_group_names[] = {PREAMBLE_GROUP_NAME, POSTAMBLE_GROUP_NAME, DEFAULTS_GROUP_NAME, TEMPLATES_GROUP_NAME, nullptr};
251 
252  IniGroup *default_grp = ifile->GetGroup(DEFAULTS_GROUP_NAME, 0, false);
253  IniGroup *templates_grp = ifile->GetGroup(TEMPLATES_GROUP_NAME, 0, false);
254  if (templates_grp == nullptr) return;
255 
256  /* Output every group, using its name as template name. */
257  for (IniGroup *grp = ifile->group; grp != nullptr; grp = grp->next) {
258  const char * const *sgn;
259  for (sgn = special_group_names; *sgn != nullptr; sgn++) if (strcmp(grp->name, *sgn) == 0) break;
260  if (*sgn != nullptr) continue;
261 
262  IniItem *template_item = templates_grp->GetItem(grp->name, false); // Find template value.
263  if (template_item == nullptr || template_item->value == nullptr) {
264  fprintf(stderr, "settingsgen: Warning: Cannot find template %s\n", grp->name);
265  continue;
266  }
267 
268  /* Prefix with #if/#ifdef/#ifndef */
269  static const char * const pp_lines[] = {"if", "ifdef", "ifndef", nullptr};
270  int count = 0;
271  for (const char * const *name = pp_lines; *name != nullptr; name++) {
272  const char *condition = FindItemValue(*name, grp, default_grp);
273  if (condition != nullptr) {
274  _stored_output.Add("#", 1);
275  _stored_output.Add(*name);
276  _stored_output.Add(" ", 1);
277  _stored_output.Add(condition);
278  _stored_output.Add("\n", 1);
279  count++;
280  }
281  }
282 
283  /* Output text of the template, except template variables of the form '$[_a-z0-9]+' which get replaced by their value. */
284  const char *txt = template_item->value;
285  while (*txt != '\0') {
286  if (*txt != '$') {
287  _stored_output.Add(txt, 1);
288  txt++;
289  continue;
290  }
291  txt++;
292  if (*txt == '$') { // Literal $
293  _stored_output.Add(txt, 1);
294  txt++;
295  continue;
296  }
297 
298  /* Read variable. */
299  char variable[MAX_VAR_LENGTH];
300  int i = 0;
301  while (i < MAX_VAR_LENGTH - 1) {
302  if (!(txt[i] == '_' || (txt[i] >= 'a' && txt[i] <= 'z') || (txt[i] >= '0' && txt[i] <= '9'))) break;
303  variable[i] = txt[i];
304  i++;
305  }
306  variable[i] = '\0';
307  txt += i;
308 
309  if (i > 0) {
310  /* Find the text to output. */
311  const char *valitem = FindItemValue(variable, grp, default_grp);
312  if (valitem != nullptr) _stored_output.Add(valitem);
313  } else {
314  _stored_output.Add("$", 1);
315  }
316  }
317  _stored_output.Add("\n", 1); // \n after the expanded template.
318  while (count > 0) {
319  _stored_output.Add("#endif\n");
320  count--;
321  }
322  }
323 }
324 
330 static void CopyFile(const char *fname, FILE *out_fp)
331 {
332  if (fname == nullptr) return;
333 
334  FILE *in_fp = fopen(fname, "r");
335  if (in_fp == nullptr) {
336  fprintf(stderr, "settingsgen: Warning: Cannot open file %s for copying\n", fname);
337  return;
338  }
339 
340  char buffer[4096];
341  size_t length;
342  do {
343  length = fread(buffer, 1, lengthof(buffer), in_fp);
344  if (fwrite(buffer, 1, length, out_fp) != length) {
345  fprintf(stderr, "Error: Cannot copy file\n");
346  break;
347  }
348  } while (length == lengthof(buffer));
349 
350  fclose(in_fp);
351 }
352 
359 static bool CompareFiles(const char *n1, const char *n2)
360 {
361  FILE *f2 = fopen(n2, "rb");
362  if (f2 == nullptr) return false;
363 
364  FILE *f1 = fopen(n1, "rb");
365  if (f1 == nullptr) {
366  fclose(f2);
367  error("can't open %s", n1);
368  }
369 
370  size_t l1, l2;
371  do {
372  char b1[4096];
373  char b2[4096];
374  l1 = fread(b1, 1, sizeof(b1), f1);
375  l2 = fread(b2, 1, sizeof(b2), f2);
376 
377  if (l1 != l2 || memcmp(b1, b2, l1) != 0) {
378  fclose(f2);
379  fclose(f1);
380  return false;
381  }
382  } while (l1 != 0);
383 
384  fclose(f2);
385  fclose(f1);
386  return true;
387 }
388 
390 static const OptionData _opts[] = {
391  GETOPT_NOVAL( 'v', "--version"),
392  GETOPT_NOVAL( 'h', "--help"),
393  GETOPT_GENERAL('h', '?', nullptr, ODF_NO_VALUE),
394  GETOPT_VALUE( 'o', "--output"),
395  GETOPT_VALUE( 'b', "--before"),
396  GETOPT_VALUE( 'a', "--after"),
397  GETOPT_END(),
398 };
399 
420 static void ProcessIniFile(const char *fname)
421 {
422  IniLoadFile *ini_data = LoadIniFile(fname);
423  DumpGroup(ini_data, PREAMBLE_GROUP_NAME);
424  DumpSections(ini_data);
425  DumpGroup(ini_data, POSTAMBLE_GROUP_NAME);
426  delete ini_data;
427 }
428 
434 int CDECL main(int argc, char *argv[])
435 {
436  const char *output_file = nullptr;
437  const char *before_file = nullptr;
438  const char *after_file = nullptr;
439 
440  GetOptData mgo(argc - 1, argv + 1, _opts);
441  for (;;) {
442  int i = mgo.GetOpt();
443  if (i == -1) break;
444 
445  switch (i) {
446  case 'v':
447  puts("$Revision$");
448  return 0;
449 
450  case 'h':
451  puts("settingsgen - $Revision$\n"
452  "Usage: settingsgen [options] ini-file...\n"
453  "with options:\n"
454  " -v, --version Print version information and exit\n"
455  " -h, -?, --help Print this help message and exit\n"
456  " -b FILE, --before FILE Copy FILE before all settings\n"
457  " -a FILE, --after FILE Copy FILE after all settings\n"
458  " -o FILE, --output FILE Write output to FILE\n");
459  return 0;
460 
461  case 'o':
462  output_file = mgo.opt;
463  break;
464 
465  case 'a':
466  after_file = mgo.opt;
467  break;
468 
469  case 'b':
470  before_file = mgo.opt;
471  break;
472 
473  case -2:
474  fprintf(stderr, "Invalid arguments\n");
475  return 1;
476  }
477  }
478 
479  _stored_output.Clear();
480 
481  for (int i = 0; i < mgo.numleft; i++) ProcessIniFile(mgo.argv[i]);
482 
483  /* Write output. */
484  if (output_file == nullptr) {
485  CopyFile(before_file, stdout);
486  _stored_output.Write(stdout);
487  CopyFile(after_file, stdout);
488  } else {
489  static const char * const tmp_output = "tmp2.xxx";
490 
491  FILE *fp = fopen(tmp_output, "w");
492  if (fp == nullptr) {
493  fprintf(stderr, "settingsgen: Warning: Cannot open file %s\n", tmp_output);
494  return 1;
495  }
496  CopyFile(before_file, fp);
497  _stored_output.Write(fp);
498  CopyFile(after_file, fp);
499  fclose(fp);
500 
501  if (CompareFiles(tmp_output, output_file)) {
502  /* Files are equal. tmp2.xxx is not needed. */
503  unlink(tmp_output);
504  } else {
505  /* Rename tmp2.xxx to output file. */
506 #if defined(_WIN32)
507  unlink(output_file);
508 #endif
509  if (rename(tmp_output, output_file) == -1) error("rename() failed");
510  }
511  }
512  return 0;
513 }
A group within an ini file.
Definition: ini_type.h:36
static void ProcessIniFile(const char *fname)
Process a single INI file.
static void CopyFile(const char *fname, FILE *out_fp)
Copy a file to the output.
Subdirectory
The different kinds of subdirectories OpenTTD uses.
Definition: fileio_type.h:108
A plain option (no value attached to it).
Definition: getoptdata.h:15
int CDECL main(int argc, char *argv[])
And the main program (what else?)
char ** argv
Remaining command line arguments.
Definition: getoptdata.h:33
void Write(FILE *out_fp) const
Dump buffer to the output stream.
Definition: settingsgen.cpp:72
IniItem * item
the first item in the group
Definition: ini_type.h:39
#define GETOPT_VALUE(shortname, longname)
Short option with value.
Definition: getoptdata.h:76
int CDECL vseprintf(char *str, const char *last, const char *format, va_list ap)
Safer implementation of vsnprintf; same as vsnprintf except:
Definition: string.cpp:60
size_t Add(const char *text, size_t length)
Add text to the output buffer.
Definition: settingsgen.cpp:59
void Write(FILE *out_fp) const
Write all stored output to the output stream.
Data of an option.
Definition: getoptdata.h:22
#define lastof(x)
Get the last element of an fixed size array.
Definition: depend.cpp:48
IniGroup * GetGroup(const char *name, size_t len=0, bool create_new=true)
Get the group with the given name.
Definition: ini_load.cpp:154
IniItem * next
The next item in this group.
Definition: ini_type.h:24
static const size_t OUTPUT_BLOCK_SIZE
Block size of the buffer in OutputBuffer.
Definition: settingsgen.cpp:42
bool HasRoom() const
Does the block have room for more data?
Definition: settingsgen.cpp:83
static void DumpGroup(IniLoadFile *ifile, const char *const group_name)
Dump a IGT_SEQUENCE group into _stored_output.
static const char * FindItemValue(const char *name, IniGroup *grp, IniGroup *defaults)
Find the value of a template variable.
A single "line" in an ini file.
Definition: ini_type.h:23
std::vector< OutputBuffer > OutputBufferVector
Vector type for output buffers.
void Clear()
Prepare buffer for use.
Definition: settingsgen.cpp:48
IniGroup * group
the first group in the ini
Definition: ini_type.h:53
static bool CompareFiles(const char *n1, const char *n2)
Compare two files for identity.
IniGroupType type
type of group
Definition: ini_type.h:38
#define GETOPT_GENERAL(id, shortname, longname, flags)
General macro for creating an option.
Definition: getoptdata.h:62
void LoadFromDisk(const char *filename, Subdirectory subdir)
Load the Ini file&#39;s data from the disk.
Definition: ini_load.cpp:210
A path without any base directory.
Definition: fileio_type.h:125
bool BufferHasRoom() const
Does the buffer have room without adding a new OutputBuffer block?
void Clear()
Clear the temporary storage.
Temporarily store output.
Definition: settingsgen.cpp:93
static const OptionData _opts[]
Options of settingsgen.
#define GETOPT_END()
Option terminator.
Definition: getoptdata.h:107
char * value
The value of this item.
Definition: ini_type.h:26
void Add(const char *text, size_t length=0)
Add text to the output storage.
char * opt
Option value, if available (else nullptr).
Definition: getoptdata.h:31
static const char * TEMPLATES_GROUP_NAME
Name of the group containing the templates.
#define GETOPT_NOVAL(shortname, longname)
Short option without value.
Definition: getoptdata.h:69
char data[OUTPUT_BLOCK_SIZE]
Stored data.
Definition: settingsgen.cpp:89
#define lengthof(x)
Return the length of an fixed size array.
Definition: depend.cpp:40
static T min(const T a, const T b)
Returns the minimum of two values.
Definition: math_func.hpp:40
Output buffer for a block of data.
Definition: settingsgen.cpp:45
OutputStore _stored_output
Temporary storage of the output, until all processing is done.
static void DumpSections(IniLoadFile *ifile)
Output all non-special sections through the template / template variable expansion system...
static void MemCpyT(T *destination, const T *source, size_t num=1)
Type-safe version of memcpy().
Definition: mem_func.hpp:23
OutputBufferVector output_buffer
Vector of blocks containing the stored output.
static IniLoadFile * LoadIniFile(const char *filename)
Load the INI file.
A list of uninterpreted lines, terminated by the next group block.
Definition: ini_type.h:19
Data storage for parsing command line options.
Definition: getoptdata.h:30
size_t size
Number of bytes stored in data.
Definition: settingsgen.cpp:88
virtual void ReportFileError(const char *const pre, const char *const buffer, const char *const post)
Report an error about the file contents.
IniItem * GetItem(const char *name, bool create)
Get the item with the given name, and if it doesn&#39;t exist and create is true it creates a new item...
Definition: ini_load.cpp:103
static const char * POSTAMBLE_GROUP_NAME
Name of the group containing the post amble.
virtual FILE * OpenFile(const char *filename, Subdirectory subdir, size_t *size)
Open the INI file.
void NORETURN CDECL error(const char *s,...)
Report a fatal error.
Definition: settingsgen.cpp:31
int GetOpt()
Find the next option.
Definition: getoptdata.cpp:22
static const char * DEFAULTS_GROUP_NAME
Name of the group containing default values for the template variables.
IniGroup * next
the next group within this file
Definition: ini_type.h:37
int numleft
Number of arguments left in argv.
Definition: getoptdata.h:32
static const char * PREAMBLE_GROUP_NAME
Name of the group containing the pre amble.
Ini file that only supports loading.
Definition: ini_type.h:52
SettingsIniFile(const char *const *list_group_names=nullptr, const char *const *seq_group_names=nullptr)
Construct a new ini loader.
Derived class for loading INI files without going through Fio stuff.