-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConfigParsing.hpp
More file actions
548 lines (451 loc) · 22.7 KB
/
Copy pathConfigParsing.hpp
File metadata and controls
548 lines (451 loc) · 22.7 KB
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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
#ifndef RUNCPP2_CONFIG_PARSING_HPP
#define RUNCPP2_CONFIG_PARSING_HPP
#include "runcpp2/Data/Profile.hpp"
#include "runcpp2/Data/ScriptInfo.hpp"
#include "runcpp2/Data/ParseCommon.hpp"
#include "runcpp2/Data/StageInfo.hpp"
#include "runcpp2/StringUtil.hpp"
#include "runcpp2/ParseUtil.hpp"
#include "runcpp2/PlatformUtil.hpp"
#include "runcpp2/DeferUtil.hpp"
#include "runcpp2/LibYAML_Wrapper.hpp"
#include "runcpp2/ParameterUtil.hpp"
#include "DSResult/DSResult.hpp"
#include "cfgpath.h"
#include "ssLogger/ssLog.hpp"
#include "ghc/filesystem.hpp"
#include <string>
#include <vector>
#include <stdint.h>
#include <string.h>
#include <fstream>
#include <memory>
#include <sstream>
#include <stack>
#include <system_error>
#include <unordered_map>
#include <unordered_set>
#if defined(INTERNAL_RUNCPP2_UNIT_TESTS) && \
INTERNAL_RUNCPP2_UNIT_TESTS == INTERNAL_RUNCPP2_UNIT_TESTS_CONFIG_PARSING
#include "Tests/ConfigParsing/MockComponents.hpp"
#else
#define CO_NO_OVERRIDE 1
#include "CppOverride.hpp"
#endif
extern "C" const uint8_t DefaultUserConfig[];
extern "C" const size_t DefaultUserConfig_size;
extern "C" const uint8_t CommonFileTypes[];
extern "C" const size_t CommonFileTypes_size;
extern "C" const uint8_t G_PlusPlus[];
extern "C" const size_t G_PlusPlus_size;
extern "C" const uint8_t Vs2022_v17Plus[];
extern "C" const size_t Vs2022_v17Plus_size;
namespace
{
DS::Result<runcpp2::Data::Profile>
ResolveProfileImport( runcpp2::YAML::NodePtr currentProfileNode,
const ghc::filesystem::path& configPath,
runcpp2::YAML::ResourceHandle& currentYamlResources,
const std::unordered_map<std::string, std::string>& inputParameters)
{
using namespace runcpp2;
ssLOG_FUNC_INFO();
ghc::filesystem::path currentImportFilePath = configPath;
std::stack<ghc::filesystem::path> pathsToImport;
runcpp2::Data::Profile p = {};
std::unordered_map<std::string, std::vector<std::string>> substitutionMap;
runcpp2::Data::Profile::PopulateCompilingLinkingParams(substitutionMap);
//Resovle parameters and variables first, before importing
ParseParametersAndVariables(p, currentProfileNode).DS_TRY();
ApplyParametersAndVariables(p,
currentProfileNode,
currentYamlResources,
substitutionMap,
inputParameters,
{}).DS_TRY();
while(runcpp2::ExistAndHasChild(currentProfileNode, "Import") || !pathsToImport.empty())
{
//If we import field, we should deal with it instead
if(runcpp2::ExistAndHasChild(currentProfileNode, "Import"))
{
const YAML::ConstNodePtr importNode = currentProfileNode->GetMapValueNode("Import");
if( importNode->GetType() != YAML::NodeType::Scalar &&
importNode->GetType() != YAML::NodeType::Sequence)
{
return DS_ERROR_MSG("Import must be a path or sequence of paths of YAML file(s)");
}
ghc::filesystem::path currentImportDir = currentImportFilePath;
currentImportDir = currentImportDir.parent_path();
if(importNode->GetType() == YAML::NodeType::Scalar)
{
std::string importPath = importNode->GetScalar<std::string>().DS_TRY();
pathsToImport.push(currentImportDir / importPath);
}
else
{
if(importNode->GetChildrenCount() == 0)
return DS_ERROR_MSG("An import sequence cannot be an empty");
for(int i = 0; i < importNode->GetChildrenCount(); ++i)
{
if(importNode->GetSequenceChildNode(i)->GetType() != YAML::NodeType::Scalar)
return DS_ERROR_MSG("It must be a sequence of paths");
std::string importPath = importNode ->GetSequenceChildScalar<std::string>(i)
.DS_TRY();
pathsToImport.push(currentImportDir / importPath);
}
}
}
currentImportFilePath = pathsToImport.top();
pathsToImport.pop();
std::error_code ec;
if(!ghc::filesystem::exists(currentImportFilePath, ec))
return DS_ERROR_MSG("Import path doesn't exist: " + currentImportFilePath.string());
//Read compiler profiles
std::stringstream buffer;
{
std::ifstream importProfileFile(currentImportFilePath);
if(!importProfileFile)
{
return DS_ERROR_MSG("Failed to open profile import file: " +
DS_STR(currentImportFilePath));
}
buffer << importProfileFile.rdbuf();
}
YAML::ResourceHandle yamlResources;
DEFER { YAML::FreeYAMLResource(yamlResources); };
std::vector<YAML::NodePtr> yamlRootNodes = YAML::ParseYAML( buffer.str(),
yamlResources).DS_TRY();
DS_ASSERT_FALSE(yamlRootNodes.empty());
for(int i = 0; i < yamlRootNodes.size(); ++i)
{
YAML::ResolveAnchors(yamlRootNodes[i]).DS_TRY();
YAML::NodePtr importProfileNode = yamlRootNodes[i];
//Perform parameter & variable parsing if the imported stuff has parameters/variables
ParseParametersAndVariables(p, importProfileNode).DS_TRY();
//Modify the import yaml node
ApplyParametersAndVariables(p,
importProfileNode,
currentYamlResources,
substitutionMap,
inputParameters,
{}).DS_TRY();
MergeYAML_NodeChildren( importProfileNode,
currentProfileNode,
currentYamlResources,
true).DS_TRY();
//If the import doesn't have import, remove the current import
if(!ExistAndHasChild(importProfileNode, "Import"))
{
currentProfileNode->RemoveMapChild("Import").DS_TRY();
}
}
} //while(runcpp2::ExistAndHasChild(currentProfileNode, "Import") || !pathsToImport.empty())
return p;
}
DS::Result<void> GetPreferredProfile( runcpp2::YAML::NodePtr configNode,
std::string& outPreferredProfile)
{
using namespace runcpp2;
if(!ExistAndHasChild(configNode, "PreferredProfile"))
return {};
YAML::NodePtr preferredProfilesMapNode = configNode->GetMapValueNode("PreferredProfile");
if(preferredProfilesMapNode->IsMap())
{
std::unordered_map<PlatformName, std::string> preferredProfiles;
for(int j = 0; j < preferredProfilesMapNode->GetChildrenCount(); ++j)
{
PlatformName platform = preferredProfilesMapNode->GetMapKeyScalarAt<PlatformName>(j)
.DS_TRY();
YAML::NodePtr valueNode = preferredProfilesMapNode->GetMapValueNodeAt(j);
if(!valueNode->IsScalar())
{
return DS_ERROR_MSG("Failed to parse PreferredProfile map. "
"Keyval is expected in each platform");
}
preferredProfiles[platform] = valueNode ->GetScalar<std::string>().DS_TRY();
}
const std::string* selectedProfile = GetValueFromPlatformMap(preferredProfiles);
if(!selectedProfile && !outPreferredProfile.empty())
ssLOG_WARNING("Multiple preferred profile is found...");
outPreferredProfile = selectedProfile != nullptr ? *selectedProfile : outPreferredProfile;
}
else if(preferredProfilesMapNode->IsScalar())
{
if(!outPreferredProfile.empty())
ssLOG_WARNING("Multiple preferred profile is found...");
outPreferredProfile = preferredProfilesMapNode->GetScalar<std::string>().DS_TRY();
}
else
{
return DS_ERROR_MSG("PreferredProfile needs to be a map or string value: " +
DS_STR(YAML::NodeTypeToString(preferredProfilesMapNode->GetType())));
}
return {};
}
DS::Result<void> ParseUserConfig( const std::string& userConfigString,
const ghc::filesystem::path& configPath,
const std::unordered_map< std::string,
std::string>& inputParameters,
std::vector<runcpp2::Data::Profile>& outProfiles,
std::string& outPreferredProfile)
{
ssLOG_FUNC_INFO();
using namespace runcpp2;
YAML::ResourceHandle parseResource;
std::vector<YAML::NodePtr> parsedNodes = YAML::ParseYAML( userConfigString,
parseResource).DS_TRY();
DEFER { YAML::FreeYAMLResource(parseResource); };
DS_ASSERT_FALSE(parsedNodes.empty());
for(int i = 0; i < parsedNodes.size(); ++i)
{
YAML::NodePtr configNode = parsedNodes[i];
YAML::ResolveAnchors(configNode).DS_TRY();
if(!ExistAndHasChild(configNode, "Profiles"))
continue;
if(!configNode->GetMapValueNode("Profiles")->IsSequence())
return DS_ERROR_MSG("Profiles must be a sequence");
YAML::NodePtr profilesNode = configNode->GetMapValueNode("Profiles");
if(profilesNode->GetChildrenCount() == 0)
return DS_ERROR_MSG("No compiler profiles found");
ssLOG_INFO(profilesNode->GetChildrenCount() << " profiles found in user config");
for(int j = 0; j < profilesNode->GetChildrenCount(); ++j)
{
ssLOG_INFO("Parsing profile at index " << j);
YAML::NodePtr currentProfileNode = profilesNode->GetSequenceChildNode(j);
if(!currentProfileNode->IsMap())
return DS_ERROR_MSG("Profile entry must be a map");
runcpp2::Data::Profile p = ResolveProfileImport(currentProfileNode,
configPath,
parseResource,
inputParameters).DS_TRY();
p.ParseYAML_Node(currentProfileNode, false, inputParameters)
.DS_TRY_ACT(DS_TMP_ERROR.Message += "\nFailed to parse compiler profile at index " +
DS_STR(j);
DS_APPEND_TRACE(DS_TMP_ERROR);
return DS::Error(DS_TMP_ERROR));
outProfiles.push_back(std::move(p));
} //for(int j = 0; j < profilesNode->GetChildrenCount(); ++j)
GetPreferredProfile(configNode, outPreferredProfile).DS_TRY();
} //for(int i = 0; i < parsedNodes.size(); ++i)
if(outProfiles.empty())
return DS_ERROR_MSG("No profiles registered");
if(outPreferredProfile.empty())
{
outPreferredProfile = outProfiles.front().Name;
ssLOG_WARNING("PreferredProfile is empty. Using the first profile name");
}
return {};
}
}
namespace runcpp2
{
inline DS::Result<ghc::filesystem::path> GetConfigFilePath()
{
CO_INSERT_IMPL(OverrideInstance, DS::Result<std::string>, ());
//Check if user config exists
char configDirC_Str[MAX_PATH] = {0};
get_user_config_folder(configDirC_Str, MAX_PATH, "runcpp2");
DS_ASSERT_GT(strlen(configDirC_Str), 0);
std::string configDir = std::string(configDirC_Str);
ssLOG_INFO("configDir: " << configDir);
std::string compilerConfigFilePaths[2] =
{
configDir + "UserConfig.yaml",
configDir + "UserConfig.yml"
};
//config directory is created by get_user_config_folder if it doesn't exist
{
std::error_code ec;
for(int i = 0; i < sizeof(compilerConfigFilePaths) / sizeof(std::string); ++i)
{
//Check if the config file exists
if(ghc::filesystem::exists(compilerConfigFilePaths[i], ec))
return compilerConfigFilePaths[i];
}
}
return compilerConfigFilePaths[0];
}
inline DS::Result<void> WriteDefaultConfigs(const ghc::filesystem::path& userConfigPath,
const bool writeUserConfig,
const bool writeDefaultConfigs)
{
CO_INSERT_IMPL( OverrideInstance,
DS::Result<void>,
(userConfigPath, writeUserConfig, writeDefaultConfigs));
//Backup existing user config
std::error_code _;
if(writeUserConfig && ghc::filesystem::exists(userConfigPath, _))
{
int backupCount = 0;
do
{
if(backupCount > 10)
{
return DS_ERROR_MSG("Failed to backup existing user config: " +
userConfigPath.string());
}
std::string backupPath = userConfigPath.string();
if(backupCount > 0)
backupPath += "." + std::to_string(backupCount);
backupPath += ".bak";
if(ghc::filesystem::exists(backupPath, _))
{
ssLOG_WARNING("Backup path exists: " << backupPath);
++backupCount;
continue;
}
std::error_code copyErrorCode;
ghc::filesystem::copy(userConfigPath, backupPath, copyErrorCode);
if(copyErrorCode)
{
return DS_ERROR_MSG("Failed to backup existing user config: " +
userConfigPath.string() + " with error: " + _.message());
}
ssLOG_INFO("Backed up existing user config: " << backupPath);
if(!ghc::filesystem::remove(userConfigPath, _))
{
return DS_ERROR_MSG("Failed to delete existing user config: " +
userConfigPath.string());
}
break;
}
while(true);
}
//Create user config
if(writeUserConfig)
{
std::ofstream configFile(userConfigPath, std::ios::binary);
if(!configFile)
return DS_ERROR_MSG("Failed to create default config file: " + userConfigPath.string());
configFile.write((const char*)DefaultUserConfig, DefaultUserConfig_size);
}
if(!writeDefaultConfigs)
return {};
ghc::filesystem::path userConfigDirectory = userConfigPath;
userConfigDirectory = userConfigDirectory.parent_path();
ghc::filesystem::path defaultYamlDirectory = userConfigDirectory / "Default";
//Default configs
if(!ghc::filesystem::exists(defaultYamlDirectory , _))
DS_ASSERT_TRUE(ghc::filesystem::create_directories(defaultYamlDirectory, _));
//Writing default profiles
auto writeDefaultConfig =
[&defaultYamlDirectory](ghc::filesystem::path outputPath,
const uint8_t* outputContent,
size_t outputSize) -> DS::Result<void>
{
const ghc::filesystem::path currentOutputPath = defaultYamlDirectory / outputPath;
std::ofstream defaultFile( currentOutputPath.string(),
std::ios::binary | std::ios_base::trunc);
if(!defaultFile)
{
return DS_ERROR_MSG("Failed to create default config file: " +
currentOutputPath.string());
}
defaultFile.write((const char*)outputContent, outputSize);
return {};
};
writeDefaultConfig("CommonFileTypes.yaml", CommonFileTypes, CommonFileTypes_size).DS_TRY();
writeDefaultConfig("g++.yaml", G_PlusPlus, G_PlusPlus_size).DS_TRY();
writeDefaultConfig("vs2022_v17+.yaml", Vs2022_v17Plus, Vs2022_v17Plus_size).DS_TRY();
//Writing .version to indicate everything is up-to-date
std::ofstream configVersionFile(userConfigDirectory / ".version",
std::ios::binary | std::ios_base::trunc);
if(!configVersionFile)
{
return DS_ERROR_MSG("Failed to open version file: " +
ghc::filesystem::path(userConfigDirectory / ".version").string());
}
configVersionFile << std::to_string(RUNCPP2_CONFIG_VERSION);
return {};
}
inline DS::Result<void> ReadUserConfig( std::vector<Data::Profile>& outProfiles,
std::string& outPreferredProfile,
const std::string rawParameters,
const std::string& customConfigPath = "")
{
ssLOG_FUNC_INFO();
ghc::filesystem::path configPath = !customConfigPath.empty() ?
ghc::filesystem::path(customConfigPath) :
GetConfigFilePath().DS_VALUE_OR();
DS_CHECK_PREV();
ghc::filesystem::path configVersionPath = configPath.parent_path() / ".version";
DS_ASSERT_FALSE(configPath.empty());
std::error_code e;
bool writeUserConfig = false;
bool writeDefaultConfigs = false;
//Create default config files if it doesn't exist
if(!ghc::filesystem::exists(configPath, e))
{
if(!customConfigPath.empty())
return DS_ERROR_MSG("Config file doesn't exist: " + configPath.string());
ssLOG_INFO("Config file doesn't exist. Creating one at: " << configPath.string());
writeUserConfig = true;
writeDefaultConfigs = true;
}
//Overwrite default config files if it is using old version
else if(ghc::filesystem::exists(configVersionPath, e))
{
std::ifstream configVersionFile(configVersionPath);
if(!configVersionFile)
return DS_ERROR_MSG("Failed to open version file: " + configVersionPath.string());
std::string configVersionStr;
std::stringstream buffer;
buffer << configVersionFile.rdbuf();
configVersionStr = buffer.str();
Trim(configVersionStr);
int configVersion = std::stoi(configVersionStr);
if(configVersion < RUNCPP2_CONFIG_VERSION)
writeDefaultConfigs = true;
}
//Overwrite default config files if missing version file
else
writeDefaultConfigs = true;
if(writeUserConfig || writeDefaultConfigs)
{
WriteDefaultConfigs(configPath, writeUserConfig, writeDefaultConfigs).DS_TRY();
}
if(ghc::filesystem::is_directory(configPath, e))
return DS_ERROR_MSG("Config file path is a directory: " + configPath.string());
//Read compiler profiles
std::string userConfigContent;
{
std::ifstream userConfigFile(configPath);
if(!userConfigFile)
return DS_ERROR_MSG("Failed to open config file: " + configPath.string());
std::stringstream buffer;
buffer << userConfigFile.rdbuf();
userConfigContent = buffer.str();
}
std::unordered_map<std::string, std::string> parameterValues;
CreateParameterValues(rawParameters, parameterValues);
ParseUserConfig(userConfigContent,
configPath,
parameterValues,
outProfiles,
outPreferredProfile).DS_TRY();
return {};
}
inline DS::Result<void>
ParseScriptInfo(const std::string& scriptInfo,
const std::unordered_map<std::string, std::string> inputParameters,
Data::ScriptInfo& outScriptInfo)
{
if(scriptInfo.empty())
return {};
YAML::ResourceHandle resourceHandle;
std::vector<YAML::NodePtr> scriptNodes = YAML::ParseYAML(scriptInfo, resourceHandle).DS_TRY();
DEFER { YAML::FreeYAMLResource(resourceHandle); };
DS_ASSERT_FALSE(scriptNodes.empty());
//NOTE: Use the first one
YAML::ResolveAnchors(scriptNodes.front()).DS_TRY();
YAML::NodePtr rootScriptNode = scriptNodes.front();
outScriptInfo.ParseYAML_Node(rootScriptNode, inputParameters).DS_TRY();
outScriptInfo.Populated = true;
return {};
}
}
#if defined(INTERNAL_RUNCPP2_UNIT_TESTS) && \
INTERNAL_RUNCPP2_UNIT_TESTS == INTERNAL_RUNCPP2_UNIT_TESTS_CONFIG_PARSING
#include "Tests/ConfigParsing/UndefMocks.hpp"
#endif
#endif