1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
|
// Copyright Epic Games, Inc. All Rights Reserved.
#include "luaconfig.h"
namespace zen::LuaConfig {
std::string
MakeSafePath(const std::string_view Path)
{
#if ZEN_PLATFORM_WINDOWS
if (Path.empty())
{
return std::string(Path);
}
std::string FixedPath(Path);
std::replace(FixedPath.begin(), FixedPath.end(), '/', '\\');
if (!FixedPath.starts_with("\\\\?\\"))
{
FixedPath.insert(0, "\\\\?\\");
}
return FixedPath;
#else
return std::string(Path);
#endif
};
void
EscapeBackslash(std::string& InOutString)
{
std::size_t BackslashPos = InOutString.find('\\');
if (BackslashPos != std::string::npos)
{
std::size_t Offset = 0;
zen::ExtendableStringBuilder<512> PathBuilder;
while (BackslashPos != std::string::npos)
{
PathBuilder.Append(InOutString.substr(Offset, BackslashPos + 1 - Offset));
PathBuilder.Append('\\');
Offset = BackslashPos + 1;
BackslashPos = InOutString.find('\\', Offset);
}
PathBuilder.Append(InOutString.substr(Offset, BackslashPos));
InOutString = PathBuilder.ToString();
}
}
//////////////////////////////////////////////////////////////////////////
BoolOption::BoolOption(bool& Value) : Value(Value)
{
}
void
BoolOption::Print(std::string_view, zen::StringBuilderBase& StringBuilder)
{
StringBuilder.Append(Value ? "true" : "false");
}
void
BoolOption::Parse(sol::object Object)
{
Value = Object.as<bool>();
}
//////////////////////////////////////////////////////////////////////////
StringOption::StringOption(std::string& Value) : Value(Value)
{
}
void
StringOption::Print(std::string_view, zen::StringBuilderBase& StringBuilder)
{
StringBuilder.Append(fmt::format("\"{}\"", Value));
}
void
StringOption::Parse(sol::object Object)
{
Value = Object.as<std::string>();
}
//////////////////////////////////////////////////////////////////////////
FilePathOption::FilePathOption(std::filesystem::path& Value) : Value(Value)
{
}
void
FilePathOption::Print(std::string_view, zen::StringBuilderBase& StringBuilder)
{
std::string Path = Value.string();
EscapeBackslash(Path);
StringBuilder.Append(fmt::format("\"{}\"", Path));
}
void
FilePathOption::Parse(sol::object Object)
{
std::string Str = Object.as<std::string>();
if (!Str.empty())
{
Value = MakeSafePath(Str);
}
}
//////////////////////////////////////////////////////////////////////////
LuaContainerWriter::LuaContainerWriter(zen::StringBuilderBase& StringBuilder, std::string_view Indent)
: StringBuilder(StringBuilder)
, InitialIndent(Indent.length())
, LocalIndent(Indent)
{
StringBuilder.Append("{\n");
LocalIndent.push_back('\t');
}
LuaContainerWriter::~LuaContainerWriter()
{
LocalIndent.pop_back();
StringBuilder.Append(LocalIndent);
StringBuilder.Append("}");
}
void
LuaContainerWriter::BeginContainer(std::string_view Name)
{
StringBuilder.Append(LocalIndent);
if (!Name.empty())
{
StringBuilder.Append(Name);
StringBuilder.Append(" = {\n");
}
else
{
StringBuilder.Append("{\n");
}
LocalIndent.push_back('\t');
}
void
LuaContainerWriter::WriteValue(std::string_view Name, std::string_view Value)
{
if (Name.empty())
{
StringBuilder.Append(fmt::format("{}\"{}\",\n", LocalIndent, Value));
}
else
{
StringBuilder.Append(fmt::format("{}{} = \"{}\",\n", LocalIndent, Name, Value));
}
}
void
LuaContainerWriter::EndContainer()
{
LocalIndent.pop_back();
StringBuilder.Append(LocalIndent);
StringBuilder.Append("}");
StringBuilder.Append(",\n");
}
//////////////////////////////////////////////////////////////////////////
StringArrayOption::StringArrayOption(std::vector<std::string>& Value) : Value(Value)
{
}
void
StringArrayOption::Print(std::string_view Indent, zen::StringBuilderBase& StringBuilder)
{
if (Value.empty())
{
StringBuilder.Append("{}");
}
if (Value.size() == 1)
{
StringBuilder.Append(fmt::format("\"{}\"", Value[0]));
}
else
{
LuaContainerWriter Writer(StringBuilder, Indent);
for (std::string String : Value)
{
Writer.WriteValue("", String);
}
}
}
void
StringArrayOption::Parse(sol::object Object)
{
if (Object.get_type() == sol::type::string)
{
Value.push_back(Object.as<std::string>());
}
else if (Object.get_type() == sol::type::table)
{
for (const auto& Kv : Object.as<sol::table>())
{
Value.push_back(Kv.second.as<std::string>());
}
}
}
std::shared_ptr<OptionValue>
MakeOption(std::string& Value)
{
return std::make_shared<StringOption>(Value);
}
std::shared_ptr<OptionValue>
MakeOption(std::filesystem::path& Value)
{
return std::make_shared<FilePathOption>(Value);
}
std::shared_ptr<OptionValue>
MakeOption(bool& Value)
{
return std::make_shared<BoolOption>(Value);
}
std::shared_ptr<OptionValue>
MakeOption(std::vector<std::string>& Value)
{
return std::make_shared<StringArrayOption>(Value);
}
void
Options::Parse(const std::filesystem::path& Path, const cxxopts::ParseResult& CmdLineResult)
{
zen::IoBuffer LuaScript = zen::IoBufferBuilder::MakeFromFile(Path);
if (LuaScript)
{
sol::state lua;
lua.open_libraries(sol::lib::base);
lua.set_function("getenv", [&](const std::string env) -> sol::object {
#if ZEN_PLATFORM_WINDOWS
std::wstring EnvVarValue;
size_t RequiredSize = 0;
std::wstring EnvWide = zen::Utf8ToWide(env);
_wgetenv_s(&RequiredSize, nullptr, 0, EnvWide.c_str());
if (RequiredSize == 0)
return sol::make_object(lua, sol::lua_nil);
EnvVarValue.resize(RequiredSize);
_wgetenv_s(&RequiredSize, EnvVarValue.data(), RequiredSize, EnvWide.c_str());
return sol::make_object(lua, zen::WideToUtf8(EnvVarValue.c_str()));
#elif ZEN_PLATFORM_LINUX || ZEN_PLATFORM_MAC
char* EnvVariable = getenv(env.c_str());
if (EnvVariable == nullptr)
{
return sol::make_object(lua, sol::lua_nil);
}
return sol::make_object(lua, EnvVariable);
#else
ZEN_UNUSED(env);
return sol::make_object(lua, sol::lua_nil);
#endif
});
try
{
sol::load_result config = lua.load(std::string_view((const char*)LuaScript.Data(), LuaScript.Size()), "zen_cfg");
if (!config.valid())
{
sol::error err = config;
std::string ErrorString = sol::to_string(config.status());
throw std::runtime_error(fmt::format("{} error: {}", ErrorString, err.what()));
}
config();
}
catch (const std::exception& e)
{
throw std::runtime_error(fmt::format("failed to load config script ('{}'): {}", Path, e.what()).c_str());
}
Parse(lua, CmdLineResult);
}
}
void
Options::Parse(const sol::state& LuaState, const cxxopts::ParseResult& CmdLineResult)
{
for (auto It : LuaState)
{
sol::object Key = It.first;
sol::type KeyType = Key.get_type();
if (KeyType == sol::type::string)
{
sol::type ValueType = It.second.get_type();
switch (ValueType)
{
case sol::type::table:
{
std::string Name = Key.as<std::string>();
if (Name.starts_with("_"))
{
continue;
}
if (Name == "base")
{
continue;
}
Traverse(It.second.as<sol::table>(), Name, CmdLineResult);
}
break;
default:
break;
}
}
}
}
void
Options::Touch(std::string_view Key)
{
UsedKeys.insert(std::string(Key));
}
void
Options::Print(zen::StringBuilderBase& SB, const cxxopts::ParseResult& CmdLineResult)
{
for (auto It : OptionMap)
{
if (CmdLineResult.count(It.second.CommandLineOptionName) != 0)
{
UsedKeys.insert(It.first);
}
}
std::vector<std::string> SortedKeys(UsedKeys.begin(), UsedKeys.end());
std::sort(SortedKeys.begin(), SortedKeys.end());
auto GetTablePath = [](const std::string& Key) -> std::vector<std::string> {
std::vector<std::string> Path;
zen::ForEachStrTok(Key, '.', [&Path](std::string_view Part) {
Path.push_back(std::string(Part));
return true;
});
return Path;
};
std::vector<std::string> CurrentTablePath;
std::string Indent;
auto It = SortedKeys.begin();
for (const std::string& Key : SortedKeys)
{
std::vector<std::string> KeyPath = GetTablePath(Key);
std::string Name = KeyPath.back();
KeyPath.pop_back();
if (CurrentTablePath != KeyPath)
{
size_t EqualCount = 0;
while (EqualCount < CurrentTablePath.size() && EqualCount < KeyPath.size() &&
CurrentTablePath[EqualCount] == KeyPath[EqualCount])
{
EqualCount++;
}
while (CurrentTablePath.size() > EqualCount)
{
CurrentTablePath.pop_back();
Indent.pop_back();
SB.Append(Indent);
SB.Append("}");
if (CurrentTablePath.size() == EqualCount && !Indent.empty() && KeyPath.size() >= EqualCount)
{
SB.Append(",");
}
SB.Append("\n");
if (Indent.empty())
{
SB.Append("\n");
}
}
while (EqualCount < KeyPath.size())
{
SB.Append(Indent);
SB.Append(KeyPath[EqualCount]);
SB.Append(" = {\n");
Indent.push_back('\t');
CurrentTablePath.push_back(KeyPath[EqualCount]);
EqualCount++;
}
}
SB.Append(Indent);
SB.Append(Name);
SB.Append(" = ");
OptionMap[Key].Value->Print(Indent, SB);
SB.Append(",\n");
}
while (!CurrentTablePath.empty())
{
Indent.pop_back();
SB.Append(Indent);
SB.Append("}\n");
CurrentTablePath.pop_back();
}
}
void
Options::Traverse(sol::table Table, std::string_view PathPrefix, const cxxopts::ParseResult& CmdLineResult)
{
for (auto It : Table)
{
sol::object Key = It.first;
sol::type KeyType = Key.get_type();
if (KeyType == sol::type::string || KeyType == sol::type::number)
{
sol::type ValueType = It.second.get_type();
switch (ValueType)
{
case sol::type::table:
case sol::type::string:
case sol::type::number:
case sol::type::boolean:
{
std::string Name = Key.as<std::string>();
if (Name.starts_with("_"))
{
continue;
}
Name = std::string(PathPrefix) + "." + Key.as<std::string>();
auto OptionIt = OptionMap.find(Name);
if (OptionIt != OptionMap.end())
{
UsedKeys.insert(Name);
if (CmdLineResult.count(OptionIt->second.CommandLineOptionName) != 0)
{
continue;
}
OptionIt->second.Value->Parse(It.second);
continue;
}
if (ValueType == sol::type::table)
{
if (Name == "base")
{
continue;
}
Traverse(It.second.as<sol::table>(), Name, CmdLineResult);
}
}
break;
default:
break;
}
}
}
}
} // namespace zen::LuaConfig
|