-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProjMgrWorker.cpp
4271 lines (3980 loc) · 156 KB
/
ProjMgrWorker.cpp
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
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2020-2023 Arm Limited. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*/
#include "ProjMgrWorker.h"
#include "ProjMgrLogger.h"
#include "ProjMgrYamlEmitter.h"
#include "CrossPlatformUtils.h"
#include "RteFsUtils.h"
#include <algorithm>
#include <iostream>
#include <regex>
using namespace std;
static const regex accessSequencesRegEx = regex(string("^(") +
ProjMgrUtils::AS_SOLUTION_DIR + "|" +
ProjMgrUtils::AS_PROJECT_DIR + "|" +
ProjMgrUtils::AS_OUT_DIR + "|" +
ProjMgrUtils::AS_BIN + "|" +
ProjMgrUtils::AS_ELF + "|" +
ProjMgrUtils::AS_HEX + "|" +
ProjMgrUtils::AS_LIB + "|" +
ProjMgrUtils::AS_CMSE + ")" +
"\\((.*)\\)$"
);
static const map<const string, tuple<const string, const string, const string>> affixesMap = {
{ "" , {ProjMgrUtils::DEFAULT_ELF_SUFFIX, ProjMgrUtils::DEFAULT_LIB_PREFIX, ProjMgrUtils::DEFAULT_LIB_SUFFIX }},
{ "AC6", {ProjMgrUtils::AC6_ELF_SUFFIX , ProjMgrUtils::AC6_LIB_PREFIX , ProjMgrUtils::AC6_LIB_SUFFIX }},
{ "GCC", {ProjMgrUtils::GCC_ELF_SUFFIX , ProjMgrUtils::GCC_LIB_PREFIX , ProjMgrUtils::GCC_LIB_SUFFIX }},
{ "CLANG", {ProjMgrUtils::GCC_ELF_SUFFIX , ProjMgrUtils::GCC_LIB_PREFIX , ProjMgrUtils::GCC_LIB_SUFFIX }},
{ "IAR", {ProjMgrUtils::IAR_ELF_SUFFIX , ProjMgrUtils::IAR_LIB_PREFIX , ProjMgrUtils::IAR_LIB_SUFFIX }},
};
ProjMgrWorker::ProjMgrWorker(ProjMgrParser* parser, ProjMgrExtGenerator* extGenerator) :
m_parser(parser),
m_extGenerator(extGenerator),
m_loadPacksPolicy(LoadPacksPolicy::DEFAULT),
m_checkSchema(false),
m_verbose(false),
m_debug(false),
m_dryRun(false)
{
RteCondition::SetVerboseFlags(0);
}
ProjMgrWorker::~ProjMgrWorker(void) {
ProjMgrKernel::Destroy();
for (auto context : m_contexts) {
for (auto componentItem : context.second.components) {
delete componentItem.second.instance;
}
}
}
bool ProjMgrWorker::AddContexts(ProjMgrParser& parser, ContextDesc& descriptor, const string& cprojectFile) {
error_code ec;
ContextItem context;
std::map<std::string, CprojectItem>& cprojects = parser.GetCprojects();
if (cprojects.find(cprojectFile) == cprojects.end()) {
ProjMgrLogger::Error(cprojectFile, "cproject not parsed, adding context failed");
return false;
}
context.cproject = &cprojects.at(cprojectFile);
context.cdefault = &parser.GetCdefault();
context.csolution = &parser.GetCsolution();
// No build/target-types
if (context.csolution->buildTypes.empty() && context.csolution->targetTypes.empty()) {
AddContext(descriptor, { "" }, context);
return true;
}
// No build-types
if (context.csolution->buildTypes.empty()) {
for (const auto& targetTypeItem : context.csolution->targetTypes) {
AddContext(descriptor, { "", targetTypeItem.first }, context);
}
return true;
}
// Add contexts for project x build-type x target-type combinations
for (const auto& buildTypeItem : context.csolution->buildTypes) {
for (const auto& targetTypeItem : context.csolution->targetTypes) {
AddContext(descriptor, { buildTypeItem.first, targetTypeItem.first }, context);
}
}
return true;
}
void ProjMgrWorker::AddContext(ContextDesc& descriptor, const TypePair& type, ContextItem& parentContext) {
if (CheckType(descriptor.type, {type})) {
ContextItem context = parentContext;
context.type.build = type.build;
context.type.target = type.target;
const string& buildType = (!type.build.empty() ? "." : "") + type.build;
const string& targetType = (!type.target.empty() ? "+" : "") + type.target;
context.name = context.cproject->name + buildType + targetType;
context.precedences = false;
// default directories
context.directories.cprj = m_outputDir.empty() ? context.cproject->directory : m_outputDir;
context.directories.intdir = "tmp/" + context.cproject->name + (type.target.empty() ? "" : "/" + type.target) + (type.build.empty() ? "" : "/" + type.build);
context.directories.outdir = "out/" + context.cproject->name + (type.target.empty() ? "" : "/" + type.target) + (type.build.empty() ? "" : "/" + type.build);
context.directories.rte = "RTE";
// customized directories
if (m_outputDir.empty() && !context.csolution->directories.cprj.empty()) {
context.directories.cprj = context.csolution->directory + "/" + context.csolution->directories.cprj;
}
if (!context.csolution->directories.intdir.empty()) {
context.directories.intdir = context.csolution->directories.intdir;
}
if (!context.csolution->directories.outdir.empty()) {
context.directories.outdir = context.csolution->directories.outdir;
}
if (!context.cproject->rteBaseDir.empty()) {
context.directories.rte = context.cproject->rteBaseDir;
}
error_code ec;
context.directories.cprj = fs::weakly_canonical(RteFsUtils::AbsolutePath(context.directories.cprj), ec).generic_string();
// context variables
context.variables[ProjMgrUtils::AS_SOLUTION] = context.csolution->name;
context.variables[ProjMgrUtils::AS_PROJECT] = context.cproject->name;
context.variables[ProjMgrUtils::AS_BUILD_TYPE] = context.type.build;
context.variables[ProjMgrUtils::AS_TARGET_TYPE] = context.type.target;
ProjMgrUtils::PushBackUniquely(m_ymlOrderedContexts, context.name);
m_contexts[context.name] = context;
}
}
bool ProjMgrWorker::ParseContextLayers(ContextItem& context) {
// user defined variables
auto userVariablesList = {
context.csolution->target.build.variables,
context.csolution->buildTypes[context.type.build].variables,
context.csolution->targetTypes[context.type.target].build.variables,
};
for (const auto& var : userVariablesList) {
for (const auto& [key, value] : var) {
if ((context.variables.find(key) != context.variables.end()) && (context.variables.at(key) != value)) {
ProjMgrLogger::Warn("variable '" + key + "' redefined from '" + context.variables.at(key) + "' to '" + value + "'");
}
context.variables[key] = value;
}
}
// parse clayers
for (const auto& clayer : context.cproject->clayers) {
if (clayer.layer.empty()) {
continue;
}
if (CheckContextFilters(clayer.typeFilter, context)) {
error_code ec;
string const& clayerRef = ExpandString(clayer.layer, context.variables);
string const& clayerFile = fs::canonical(fs::path(context.cproject->directory).append(clayerRef), ec).generic_string();
if (clayerFile.empty()) {
if (regex_match(clayer.layer, regex(".*\\$.*\\$.*"))) {
ProjMgrLogger::Warn(clayer.layer, "variable was not defined for context '" + context.name +"'");
} else {
ProjMgrLogger::Error(clayer.layer, "clayer file was not found");
return false;
}
} else {
if (!m_parser->ParseClayer(clayerFile, m_checkSchema)) {
return false;
}
context.clayers[clayerFile] = &m_parser->GetClayers().at(clayerFile);
}
}
}
return true;
}
void ProjMgrWorker::GetContexts(map<string, ContextItem>* &contexts) {
m_contextsPtr = &m_contexts;
contexts = m_contextsPtr;
}
void ProjMgrWorker::GetYmlOrderedContexts(vector<string> &contexts) {
contexts = m_ymlOrderedContexts;
}
void ProjMgrWorker::SetOutputDir(const std::string& outputDir) {
m_outputDir = outputDir;
}
void ProjMgrWorker::SetSelectedToolchain(const std::string& selectedToolchain) {
m_selectedToolchain = selectedToolchain;
}
void ProjMgrWorker::SetCheckSchema(bool checkSchema) {
m_checkSchema = checkSchema;
}
void ProjMgrWorker::SetVerbose(bool verbose) {
m_verbose = verbose;
}
void ProjMgrWorker::SetDebug(bool debug) {
m_debug = debug;
}
void ProjMgrWorker::SetDryRun(bool dryRun) {
m_dryRun = dryRun;
}
void ProjMgrWorker::SetLoadPacksPolicy(const LoadPacksPolicy& policy) {
m_loadPacksPolicy = policy;
}
void ProjMgrWorker::SetEnvironmentVariables(const StrVec& envVars) {
m_envVars = envVars;
}
bool ProjMgrWorker::GetRequiredPdscFiles(ContextItem& context, const std::string& packRoot, std::set<std::string>& errMsgs) {
if (!ProcessPackages(context)) {
return false;
}
for (auto packItem : context.packRequirements) {
// parse required version range
const auto& pack = packItem.pack;
const auto& reqVersion = pack.version;
string reqVersionRange;
if (!reqVersion.empty()) {
if (reqVersion.find(">=") != string::npos) {
reqVersionRange = reqVersion.substr(2);
} else {
reqVersionRange = reqVersion + ":" + reqVersion;
}
}
if (packItem.path.empty()) {
bool bPackFilter = (pack.name.empty() || WildCards::IsWildcardPattern(pack.name));
auto filteredPackItems = GetFilteredPacks(packItem, packRoot);
for (const auto& filteredPackItem : filteredPackItems) {
auto filteredPack = filteredPackItem.pack;
string packId, pdscFile, localPackId;
XmlItem attributes({
{"name", filteredPack.name},
{"vendor", filteredPack.vendor},
{"version", reqVersionRange},
});
// get installed and local pdsc that satisfy the version range requirements
pdscFile = m_kernel->GetInstalledPdscFile(attributes, packRoot, packId);
const string& localPdscFile = m_kernel->GetLocalPdscFile(attributes, packRoot, localPackId);
if (!localPdscFile.empty()) {
const size_t packIdLen = (filteredPack.vendor + '.' + filteredPack.name + '.').length();
if (pdscFile.empty() ? true : VersionCmp::Compare(localPackId.substr(packIdLen), packId.substr(packIdLen)) >= 0) {
// local pdsc takes precedence
pdscFile = localPdscFile;
}
}
if (pdscFile.empty()) {
if (!bPackFilter) {
std::string packageName =
(filteredPack.vendor.empty() ? "" : filteredPack.vendor + "::") +
filteredPack.name +
(reqVersion.empty() ? "" : "@" + reqVersion);
errMsgs.insert("required pack: " + packageName + " not installed");
context.missingPacks.push_back(filteredPack);
}
continue;
}
context.pdscFiles.insert({ pdscFile, {"", reqVersionRange }});
}
if (bPackFilter && context.pdscFiles.empty()) {
std::string filterStr = pack.vendor +
(pack.name.empty() ? "" : "::" + pack.name) +
(reqVersion.empty() ? "" : "@" + reqVersion);
errMsgs.insert("no match found for pack filter: " + filterStr);
}
} else {
if (!reqVersion.empty()) {
errMsgs.insert("pack '" + (pack.vendor.empty() ? "" : pack.vendor + "::") + pack.name
+ "' specified with 'path' must not have a version");
}
string packPath = packItem.path;
if (!RteFsUtils::Exists(packPath)) {
errMsgs.insert("pack path: " + packItem.path + " does not exist");
break;
}
string pdscFile = pack.vendor + '.' + pack.name + ".pdsc";
RteFsUtils::NormalizePath(pdscFile, packPath + "/");
if (!RteFsUtils::Exists(pdscFile)) {
errMsgs.insert("pdsc file was not found in: " + packItem.path);
break;
} else {
context.pdscFiles.insert({ pdscFile, {packPath, reqVersionRange}});
}
}
}
return (0 == errMsgs.size());
}
string ProjMgrWorker::GetPackRoot() {
error_code ec;
string packRoot;
packRoot = CrossPlatformUtils::GetEnv("CMSIS_PACK_ROOT");
if (packRoot.empty()) {
packRoot = CrossPlatformUtils::GetDefaultCMSISPackRootDir();
}
packRoot = fs::weakly_canonical(fs::path(packRoot), ec).generic_string();
return packRoot;
}
bool ProjMgrWorker::InitializeModel() {
m_packRoot = GetPackRoot();
m_kernel = ProjMgrKernel::Get();
if (!m_kernel) {
ProjMgrLogger::Error("initializing RTE Kernel failed");
return false;
}
m_model = m_kernel->GetGlobalModel();
if (!m_model) {
ProjMgrLogger::Error("initializing RTE Model failed");
return false;
}
m_kernel->SetCmsisPackRoot(m_packRoot);
m_model->SetCallback(m_kernel->GetCallback());
return true;
}
bool ProjMgrWorker::LoadAllRelevantPacks() {
// Get required pdsc files
std::list<std::string> pdscFiles;
std::set<std::string> errMsgs;
if (m_selectedContexts.empty()) {
for (const auto& [context,_] : m_contexts) {
m_selectedContexts.push_back(context);
}
}
for (const auto& context : m_selectedContexts) {
auto& contextItem = m_contexts.at(context);
if (!GetRequiredPdscFiles(contextItem, m_packRoot, errMsgs)) {
std::for_each(errMsgs.begin(), errMsgs.end(), [](const auto& errMsg) {ProjMgrLogger::Error(errMsg); });
return false;
}
for (const auto& [pdscFile, _] : contextItem.pdscFiles) {
ProjMgrUtils::PushBackUniquely(pdscFiles, pdscFile);
}
}
// Check load packs policy
if (pdscFiles.empty() && (m_loadPacksPolicy == LoadPacksPolicy::REQUIRED)) {
ProjMgrLogger::Error("required packs must be specified");
return false;
}
// Get installed packs
if (pdscFiles.empty() || (m_loadPacksPolicy == LoadPacksPolicy::ALL) || (m_loadPacksPolicy == LoadPacksPolicy::LATEST)) {
const bool latest = (m_loadPacksPolicy == LoadPacksPolicy::LATEST) || (m_loadPacksPolicy == LoadPacksPolicy::DEFAULT);
if (!m_kernel->GetInstalledPacks(pdscFiles, latest)) {
ProjMgrLogger::Error("parsing installed packs failed");
return false;
}
}
if (!m_kernel->LoadAndInsertPacks(m_loadedPacks, pdscFiles)) {
ProjMgrLogger::Error("failed to load and insert packs");
return CheckRteErrors();
}
if (!m_model->Validate()) {
RtePrintErrorVistior visitor(m_kernel->GetCallback());
m_model->AcceptVisitor(&visitor);
return CheckRteErrors();
}
return true;
}
bool ProjMgrWorker::LoadPacks(ContextItem& context) {
if (!InitializeModel()) {
return false;
}
if (m_loadedPacks.empty() && !LoadAllRelevantPacks()) {
return false;
}
if (!InitializeTarget(context)) {
return false;
}
// Filter context specific packs
if (!context.pdscFiles.empty() && (m_loadPacksPolicy != LoadPacksPolicy::ALL) && (m_loadPacksPolicy != LoadPacksPolicy::LATEST)) {
set<string> selectedPacks;
for (const auto& pack : m_loadedPacks) {
if (context.pdscFiles.find(pack->GetPackageFileName()) != context.pdscFiles.end()) {
selectedPacks.insert( pack->GetPackageID());
}
}
RtePackageFilter filter;
filter.SetSelectedPackages(selectedPacks);
context.rteActiveTarget->SetPackageFilter(filter);
context.rteActiveTarget->UpdateFilterModel();
}
RtePackageMap allRequiredPacks;
// check if all pack requirements are fulfilled
for (auto pack : m_loadedPacks) {
pack->GetRequiredPacks(allRequiredPacks, m_model);
}
for (auto [id, pack] : allRequiredPacks) {
if (!pack) {
string msg("context '");
msg += context.name;
msg += "': required pack '";
msg += id + "' is not loaded";
ProjMgrLogger::Warn(msg);
}
}
return CheckRteErrors();
}
std::vector<PackageItem> ProjMgrWorker::GetFilteredPacks(const PackageItem& packItem, const string& rtePath) const
{
std::vector<PackageItem> filteredPacks;
auto& pack = packItem.pack;
if (!pack.name.empty() && !WildCards::IsWildcardPattern(pack.name)) {
filteredPacks.push_back({{ pack.name, pack.vendor, pack.version }});
}
else {
error_code ec;
string dirName, path;
path = rtePath + '/' + pack.vendor;
for (const auto& entry : fs::directory_iterator(path, ec)) {
if (entry.is_directory()) {
dirName = entry.path().filename().generic_string();
if (pack.name.empty() || WildCards::Match(pack.name, dirName)) {
filteredPacks.push_back({{ dirName, pack.vendor }});
}
}
}
}
return filteredPacks;
}
bool ProjMgrWorker::CheckRteErrors(void) {
const auto& callback = m_kernel->GetCallback();
const list<string>& rteWarningMessages = callback->GetWarningMessages();
if (!rteWarningMessages.empty()) {
string warnMsg = "RTE Model reports:";
for (const auto& rteWarningMessage : rteWarningMessages) {
warnMsg += "\n" + rteWarningMessage;
}
ProjMgrLogger::Warn(warnMsg);
callback->ClearWarningMessages();
}
const list<string>& rteErrorMessages = callback->GetErrorMessages();
if (!rteErrorMessages.empty()) {
string errorMsg = "RTE Model reports:";
for (const auto& rteErrorMessage : rteErrorMessages) {
errorMsg += "\n" + rteErrorMessage;
}
ProjMgrLogger::Error(errorMsg);
return false;
}
return true;
}
bool ProjMgrWorker::InitializeTarget(ContextItem& context) {
if (context.rteActiveTarget == nullptr) {
// RteGlobalModel has the RteProject pointer ownership
RteProject* rteProject = make_unique<RteProject>().release();
m_model->AddProject(0, rteProject);
m_model->SetActiveProjectId(rteProject->GetProjectId());
context.rteActiveProject = m_model->GetActiveProject();
const string& targetName = (context.type.build.empty() && context.type.target.empty()) ? "Target 1" :
context.type.build.empty() ? context.type.target : context.type.build + (context.type.target.empty() ? "" : '+' + context.type.target);
context.rteActiveProject->AddTarget(targetName, map<string, string>(), true, true);
context.rteActiveProject->SetActiveTarget(targetName);
context.rteActiveProject->SetName(context.name);
context.rteActiveTarget = context.rteActiveProject->GetActiveTarget();
context.rteFilteredModel = context.rteActiveTarget->GetFilteredModel();
}
return CheckRteErrors();
}
bool ProjMgrWorker::SetTargetAttributes(ContextItem& context, map<string, string>& attributes) {
if (context.rteActiveTarget == nullptr) {
InitializeTarget(context);
}
if (context.cproject) {
if (!context.cproject->directory.empty()) {
context.rteActiveProject->SetProjectPath(context.cproject->directory + "/");
}
if (!context.directories.rte.empty()) {
error_code ec;
const string& rteFolder = fs::relative(context.directories.cprj + "/"+ context.directories.rte, context.cproject->directory, ec).generic_string();
context.rteActiveProject->SetRteFolder(rteFolder);
}
}
context.rteActiveTarget->SetAttributes(attributes);
context.rteActiveTarget->UpdateFilterModel();
return CheckRteErrors();
}
void ProjMgrWorker::GetDeviceItem(const std::string& element, DeviceItem& device) const {
string deviceInfoStr = element;
if (!element.empty()) {
device.vendor = RteUtils::RemoveSuffixByString(deviceInfoStr, "::");
deviceInfoStr = RteUtils::RemovePrefixByString(deviceInfoStr, "::");
device.name = RteUtils::GetPrefix(deviceInfoStr);
device.pname = RteUtils::GetSuffix(deviceInfoStr);
}
}
void ProjMgrWorker::GetBoardItem(const std::string& element, BoardItem& board) const {
string boardId = element;
if (!boardId.empty()) {
board.vendor = RteUtils::RemoveSuffixByString(boardId, "::");
boardId = RteUtils::RemovePrefixByString(boardId, "::");
board.name = RteUtils::GetPrefix(boardId);
board.revision = RteUtils::GetSuffix(boardId);
}
}
bool ProjMgrWorker::GetPrecedentValue(std::string& outValue, const std::string& element) const {
if (!element.empty()) {
if (!outValue.empty() && (outValue != element)) {
ProjMgrLogger::Error("redefinition from '" + outValue + "' into '" + element + "' is not allowed");
return false;
}
outValue = element;
}
return true;
}
void ProjMgrWorker::GetAllCombinations(const ConnectionsCollectionMap& src, const ConnectionsCollectionMap::iterator& it,
std::vector<ConnectionsCollectionVec>& combinations, const ConnectionsCollectionVec& previous) {
// combine items from a table of 'connections'
// see an example in the test case ProjMgrWorkerUnitTests.GetAllCombinations
const auto nextIt = next(it, 1);
// iterate over the input columns
for (const auto& item : it->second) {
ConnectionsCollectionVec combination = previous;
if (!item.filename.empty()) {
combination.push_back(item);
}
if (nextIt != src.end()) {
// run recursively over the next item
GetAllCombinations(src, nextIt, combinations, combination);
} else {
// add a new combination containing an item from each column
combinations.push_back(combination);
}
}
}
void ProjMgrWorker::GetAllSelectCombinations(const ConnectPtrVec& src, const ConnectPtrVec::iterator& it,
std::vector<ConnectPtrVec>& combinations) {
// combine items from a vector of 'select' nodes
// see an example in the test case ProjMgrWorkerUnitTests.GetAllSelectCombinations
// for every past combination add a new combination containing additionally the current item
for (auto combination : vector<ConnectPtrVec>(combinations)) {
combination.push_back(*it);
combinations.push_back(combination);
}
// add a new combination with the current item
combinations.push_back(ConnectPtrVec({*it}));
const auto nextIt = next(it, 1);
if (nextIt != src.end()) {
// run recursively over the next item
GetAllSelectCombinations(src, nextIt, combinations);
}
}
bool ProjMgrWorker::CollectLayersFromPacks(ContextItem& context, StrVecMap& clayers) {
for (const auto& clayerItem : context.rteActiveTarget->GetFilteredModel()->GetLayerDescriptors()) {
const string& clayerFile = clayerItem->GetOriginalAbsolutePath(clayerItem->GetFileString());
if (!RteFsUtils::Exists(clayerFile)) {
return false;
}
ProjMgrUtils::PushBackUniquely(clayers[clayerItem->GetTypeString()], clayerFile);
}
return true;
}
bool ProjMgrWorker::CollectLayersFromSearchPath(const string& clayerSearchPath, StrVecMap& clayers) {
if (!clayerSearchPath.empty()) {
error_code ec;
const auto& absSearchPath = RteFsUtils::MakePathCanonical(clayerSearchPath);
if (!RteFsUtils::Exists(absSearchPath)) {
ProjMgrLogger::Error(absSearchPath, "clayer search path does not exist");
return false;
}
for (auto& item : fs::recursive_directory_iterator(absSearchPath, ec)) {
if (fs::is_regular_file(item, ec) && (!ec)) {
const string& clayerFile = item.path().generic_string();
if (regex_match(clayerFile, regex(".*\\.clayer\\.(yml|yaml)"))) {
if (!m_parser->ParseGenericClayer(clayerFile, m_checkSchema)) {
return false;
}
ClayerItem* clayer = &m_parser->GetGenericClayers()[clayerFile];
ProjMgrUtils::PushBackUniquely(clayers[clayer->type], clayerFile);
}
}
}
}
return true;
}
void ProjMgrWorker::GetRequiredLayerTypes(ContextItem& context, LayersDiscovering& discover) {
for (const auto& clayer : context.cproject->clayers) {
if (clayer.type.empty() || !CheckContextFilters(clayer.typeFilter, context) ||
(ExpandString(clayer.layer, context.variables) != clayer.layer)) {
continue;
}
discover.requiredLayerTypes.push_back(clayer.type);
discover.optionalTypeFlags[clayer.type] = clayer.optional;
}
}
bool ProjMgrWorker::ProcessCandidateLayers(ContextItem& context, LayersDiscovering& discover) {
// get all candidate layers
if (!GetCandidateLayers(discover)) {
return false;
}
// load device/board specific packs specified in candidate layers
vector<PackItem> packRequirements;
for (const auto& [type, clayers] : discover.candidateClayers) {
for (const auto& clayer : clayers) {
const ClayerItem& clayerItem = m_parser->GetGenericClayers()[clayer];
if (!clayerItem.forBoard.empty() || !clayerItem.forDevice.empty()) {
InsertPackRequirements(clayerItem.packs, packRequirements, clayerItem.directory);
}
}
}
if (packRequirements.size() > 0) {
AddPackRequirements(context, packRequirements);
if (!LoadAllRelevantPacks() || !LoadPacks(context)) {
return false;
}
}
// process board/device filtering
if (!ProcessDevice(context)) {
return false;
}
if (!SetTargetAttributes(context, context.targetAttributes)) {
return false;
}
// recollect layers from packs after filtering
discover.genericClayersFromPacks.clear();
if (!CollectLayersFromPacks(context, discover.genericClayersFromPacks)) {
return false;
}
discover.candidateClayers.clear();
if (!GetCandidateLayers(discover)) {
return false;
}
return true;
}
bool ProjMgrWorker::GetCandidateLayers(LayersDiscovering& discover) {
// clayers matching required types
StrVecMap genericClayers = ProjMgrUtils::MergeStrVecMap(discover.genericClayersFromSearchPath, discover.genericClayersFromPacks);
for (const auto& requiredType : discover.requiredLayerTypes) {
if (genericClayers.find(requiredType) != genericClayers.end()) {
for (const auto& clayer : genericClayers.at(requiredType)) {
discover.candidateClayers[requiredType].push_back(clayer);
}
} else {
ProjMgrUtils::PushBackUniquely(discover.missedRequiredTypes, requiredType);
}
}
// parse matched type layers
for (const auto& [type, clayers] : discover.candidateClayers) {
for (const auto& clayer : clayers) {
if (!m_parser->ParseGenericClayer(clayer, m_checkSchema)) {
return false;
}
}
}
return true;
}
bool ProjMgrWorker::DiscoverMatchingLayers(ContextItem& context, string clayerSearchPath) {
// get all layers from packs and from search path
LayersDiscovering discover;
if (!CollectLayersFromPacks(context, discover.genericClayersFromPacks)) {
return false;
}
if (!CollectLayersFromSearchPath(clayerSearchPath, discover.genericClayersFromSearchPath)) {
return false;
}
// get required layer types
GetRequiredLayerTypes(context, discover);
// process candidate layers
if (!ProcessCandidateLayers(context, discover)) {
return false;
}
// process layer combinations
if (!ProcessLayerCombinations(context, discover)) {
return false;
}
return true;
}
bool ProjMgrWorker::ProcessLayerCombinations(ContextItem& context, LayersDiscovering& discover) {
// debug message
string debugMsg;
if (m_debug) {
debugMsg = "check for context '" + context.name + "'\n";
for (const auto& missedRequiredType : discover.missedRequiredTypes) {
debugMsg += "no clayer matches type '" + missedRequiredType + "'\n";
}
}
// collect connections from candidate layers
ConnectionsCollectionVec allConnections;
if (!discover.requiredLayerTypes.empty()) {
for (const auto& [type, clayers] : discover.candidateClayers) {
for (const auto& clayer : clayers) {
const ClayerItem& clayerItem = m_parser->GetGenericClayers()[clayer];
if (type != clayerItem.type) {
if (m_debug) {
debugMsg += "clayer type '" + clayerItem.type + "' does not match type '" + type + "' in pack description\n";
}
}
// skip non-matching 'for-board' and 'for-device' filters
if (!CheckBoardDeviceInLayer(context, clayerItem)) {
continue;
}
ConnectionsCollection collection = {clayerItem.path, type};
for (const auto& connect : clayerItem.connections) {
collection.connections.push_back(&connect);
}
allConnections.push_back(collection);
}
}
}
// collect connections from project and layers
CollectConnections(context, allConnections);
// classify connections according to layer types and set config-ids
ConnectionsCollectionMap classifiedConnections = ClassifyConnections(allConnections, discover.optionalTypeFlags);
// cross classified connections to get all combinations to be validated
vector<ConnectionsCollectionVec> combinations;
if (!classifiedConnections.empty()) {
GetAllCombinations(classifiedConnections, classifiedConnections.begin(), combinations);
}
// validate connections combinations
for (const auto& combination : combinations) {
// debug message
if (m_debug) {
debugMsg += "\ncheck combined connections:";
for (const auto& item : combination) {
const auto& type = m_parser->GetGenericClayers()[item.filename].type;
debugMsg += "\n " + item.filename + (type.empty() ? "" : " (layer type: " + type + ")");
for (const auto& connect : item.connections) {
debugMsg += "\n " + (connect->set.empty() ? "" : "set: " + connect->set + " ") + "(" +
connect->connect + (connect->info.empty() ? "" : " - " + connect->info) + ")";
}
}
debugMsg += "\n";
}
// validate connections
ConnectionsValidationResult result = ValidateConnections(combination);
// update list of compatible layers
if (result.valid) {
context.validConnections.push_back(combination);
for (const auto& [type, _] : discover.candidateClayers) {
for (const auto& collection : combination) {
if (collection.type == type) {
ProjMgrUtils::PushBackUniquely(context.compatibleLayers[type], collection.filename);
}
}
}
}
// debug message
if (m_debug) {
PrintConnectionsValidation(result, debugMsg);
debugMsg += "connections are " + string(result.valid ? "valid" : "invalid") + "\n";
}
}
// assess generic layers validation results
if (!discover.candidateClayers.empty()) {
if (!context.compatibleLayers.empty()) {
for (const auto& [type, _] : discover.candidateClayers) {
if (context.compatibleLayers[type].size() == 1) {
// unique match
const auto& clayer = context.compatibleLayers[type].front();
if (m_debug) {
debugMsg += "\nclayer of type '" + type + "' was uniquely found:\n " + clayer + "\n";
}
} else if (context.compatibleLayers[type].size() > 1) {
// multiple matches
if (m_debug) {
debugMsg += "\nmultiple clayers match type '" + type + "':";
for (const auto& clayer : context.compatibleLayers[type]) {
debugMsg += "\n " + clayer;
}
debugMsg += "\n";
}
}
}
} else {
// no valid combination
if (m_debug) {
debugMsg += "\nno valid combination of clayers was found\n";
}
}
}
if (m_debug) {
ProjMgrLogger::Debug(debugMsg);
}
if (!discover.candidateClayers.empty() && context.compatibleLayers.empty()) {
return false;
}
if (context.validConnections.size() > 0) {
// remove redundant sets
RemoveRedundantSubsets(context.validConnections);
}
if (m_verbose || m_debug) {
// print all valid configuration options
if (context.validConnections.size() > 0) {
map<int, map<string, map<string, set<const ConnectItem*>>>> configurationOptions;
int index = 0;
for (const auto& combination : context.validConnections) {
index++;
for (const auto& item : combination) {
for (const auto& connect : item.connections) {
configurationOptions[index][item.type][item.filename].insert(connect);
}
}
}
for (const auto& [index, types] : configurationOptions) {
string infoMsg = "valid configuration #" + to_string(index) + ": (context '" + context.name +"')";
for (const auto& [type, filenames] : types) {
for (const auto& [filename, options] : filenames) {
infoMsg += "\n " + filename + (type.empty() ? "" : " (layer type: " + type + ")");
for (const auto& connect : options) {
if (!connect->set.empty()) {
infoMsg += "\n set: " + connect->set + " (" + connect->connect + (connect->info.empty() ? "" : " - " + connect->info) + ")";
}
}
}
}
ProjMgrLogger::Info(infoMsg + "\n");
}
}
}
return true;
}
void ProjMgrWorker::PrintConnectionsValidation(ConnectionsValidationResult result, string& msg) {
if (!result.valid) {
if (!result.conflicts.empty()) {
msg += "connections provided multiple times:";
for (const auto& id : result.conflicts) {
msg += "\n " + id;
}
msg += "\n";
}
if (!result.incompatibles.empty()) {
msg += "required connections not provided:";
for (const auto& [id, value] : result.incompatibles) {
msg += "\n " + id + (value.empty() ? "" : ": " + value);
}
msg += "\n";
}
if (!result.overflows.empty()) {
msg += "sum of required values exceed provided:";
for (const auto& [id, value] : result.overflows) {
msg += "\n " + id + (value.empty() ? "" : ": " + value);
}
msg += "\n";
}
if (!result.missedCollections.empty()) {
msg += "provided combined connections not consumed:";
for (const auto& missedCollection : result.missedCollections) {
msg += "\n " + missedCollection.filename + (missedCollection.type.empty() ? "" : " (layer type: " + missedCollection.type + ")");
for (const auto& connect : missedCollection.connections) {
for (const auto& provided : connect->provides) {
msg += "\n " + provided.first;
}
}
}
msg += "\n";
}
}
}
void ProjMgrWorker::CollectConnections(ContextItem& context, ConnectionsCollectionVec& connections) {
// collect connections from project and layers
ConnectionsCollection projectCollection = { context.cproject->path, RteUtils::EMPTY_STRING };
for (const auto& connect : context.cproject->connections) {
projectCollection.connections.push_back(&connect);
}
connections.push_back(projectCollection);
for (const auto& [_, clayerItem] : context.clayers) {
ConnectionsCollection layerCollection = { clayerItem->path, clayerItem->type };
for (const auto& connect : clayerItem->connections) {
layerCollection.connections.push_back(&connect);
}
connections.push_back(layerCollection);
}
}
ConnectionsCollectionMap ProjMgrWorker::ClassifyConnections(const ConnectionsCollectionVec& connections, map<string, bool> optionalTypeFlags) {
// classify connections according to layer types and set config-ids
ConnectionsCollectionMap classifiedConnections;
for (const auto& collectionEntry : connections) {
// get type classification
const string& classifiedType = collectionEntry.type.empty() ? to_string(hash<string>{}(collectionEntry.filename)) : collectionEntry.type;
// group connections by config-id
map<string, ConnectPtrVec> connectionsMap;
for (const auto& connect : collectionEntry.connections) {
const string& configId = connect->set.substr(0, connect->set.find('.'));
connectionsMap[configId].push_back(connect);
}
// get common connections
ConnectPtrVec commonConnections;
bool hasMultipleSelect = false;
for (const auto& [configId, connectionsEntry] : connectionsMap) {
if (!configId.empty()) {
// 'config-id' has multiple 'select' choices
hasMultipleSelect = true;
} else {
// 'config-id' has only one 'select'
commonConnections.insert(commonConnections.end(), connectionsEntry.begin(), connectionsEntry.end());
}
}
// iterate over 'select' choices
if (hasMultipleSelect) {
for (const auto& [configId, selectConnections] : connectionsMap) {
if (!configId.empty()) {
// combine nodes with identical 'config-id'.'select'
map<string, ConnectPtrVec> selectMap;
for (const auto& connect : selectConnections) {
selectMap[connect->set].push_back(connect);
}
for (auto& [_, multipleSelectConnections] : selectMap) {
vector<ConnectPtrVec> selectCombinations;
GetAllSelectCombinations(multipleSelectConnections, multipleSelectConnections.begin(), selectCombinations);
for (const auto& selectCombination : selectCombinations) {
// insert a classified connections entry
ConnectionsCollection collection = { collectionEntry.filename, collectionEntry.type, commonConnections };
collection.connections.insert(collection.connections.end(), selectCombination.begin(), selectCombination.end());
classifiedConnections[classifiedType + configId].push_back(collection);
}
}
}
}
} else {
// insert a classified connections entry
ConnectionsCollection collection = { collectionEntry.filename, collectionEntry.type, commonConnections };
classifiedConnections[classifiedType].push_back(collection);
}
}
// add empty connection for optional handling in combinatory flow, unless differently specified
for (auto& [type, collectionVec] : classifiedConnections) {
if (optionalTypeFlags[type]) {
collectionVec.push_back({ RteUtils::EMPTY_STRING, RteUtils::EMPTY_STRING });
}
}
return classifiedConnections;
}
void ProjMgrWorker::GetConsumesProvides(const ConnectionsCollectionVec& collection, ConnectionsList& connections) {
// collect consumed and provided connections
ConnectPtrVec visitedConnect;
for (const auto& item : collection) {
for (const auto& connect : item.connections) {
if (find(visitedConnect.begin(), visitedConnect.end(), connect) != visitedConnect.end()) {
continue;
}
visitedConnect.push_back(connect);
for (const auto& consumed : connect->consumes) {
connections.consumes.push_back(&consumed);
}
for (const auto& provided : connect->provides) {
connections.provides.push_back(&provided);
}
}
}
}
bool ProjMgrWorker::ProvidedConnectionsMatch(ConnectionsCollection collection, ConnectionsList connections) {
// for a given collection check if provided connections match at least a consumed one
if (collection.connections.size() == 0) {
return true;
}
for (const auto& connect : collection.connections) {