-
Notifications
You must be signed in to change notification settings - Fork 3
/
Project.cs
2145 lines (1753 loc) · 86 KB
/
Project.cs
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
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Security;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml.Linq;
using System.Xml.Serialization;
/// <summary>
/// Represents Visual studio project .xml model
/// </summary>
[DebuggerDisplay("{ProjectName}, {RelativePath}, {ProjectGuid}")]
public class Project
{
/// <summary>
/// Solution where project is included from. null if project loaded as standalone.
/// </summary>
[XmlIgnore]
public Solution solution;
/// <summary>
/// true if it's folder (in solution), false if it's project. (default)
/// </summary>
public bool bIsFolder = false;
/// <summary>
/// true if it's Android Ant or Gradle packaging project (Set separately from Keyword, because might be parsed out from solution file)
/// </summary>
public bool bIsPackagingProject = false;
/// <summary>
/// Don't generate project if defined as externalproject
/// </summary>
public bool bDefinedAsExternal = true;
const String csharp_uuid = "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}";
const String cpp_uuid = "{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}";
const String folder_uuid = "{2150E333-8FDC-42A3-9474-1A3956D46DE8}";
const String packagingProject_uuid = "{39E2626F-3545-4960-A6E8-258AD8476CE5}";
/// <summary>
/// Made as a property so can be set over reflection.
/// </summary>
public String ProjectHostGuid
{
get
{
if (bIsFolder)
{
return folder_uuid;
}
else
{
if (bIsPackagingProject)
return packagingProject_uuid;
if (language != null && language == "C#")
return csharp_uuid;
return cpp_uuid;
}
}
set
{
switch (value)
{
case folder_uuid:
bIsFolder = true;
break;
case cpp_uuid:
bIsFolder = false;
language = "C++";
break;
case csharp_uuid:
bIsFolder = false;
language = "C#";
break;
case packagingProject_uuid:
bIsFolder = false;
bIsPackagingProject = true;
break;
default:
throw new Exception2("Invalid project host guid '" + value + "'");
}
}
}
/// <summary>
/// Visual studio file format version, e.g. 2010, 2012, ...
/// </summary>
public int fileFormatVersion = 2015; // By default generate projects for vs2015
/// <summary>
/// Sets project file format version
/// </summary>
/// <param name="ver">Visual studio version number</param>
public void SetFileFormatVersion( int ver )
{
fileFormatVersion = ver;
switch (ver)
{
case 2010:
case 2012:
ToolsVersion = "4.0";
break;
case 2013:
ToolsVersion = "12.0";
break;
case 2015:
ToolsVersion = "14.0";
break;
case 2017:
ToolsVersion = "15.0";
break;
default:
// Try to predict the future here. :-)
ToolsVersion = (((ver - 2017) / 2) + 15).ToString() + ".0";
break;
} //switch
} //SetFileFormatVersion
/// <summary>
/// "4.0" for vs2010/vs2012, "12.0" for vs2013, "14.0" for vs2015
/// </summary>
public String ToolsVersion;
/// <summary>
/// Sets tools version, also tried to detect file format version
/// </summary>
/// <param name="ver"></param>
public void setToolsVersion(String ver)
{
ToolsVersion = ver;
double dVer;
if (!Double.TryParse(ver, NumberStyles.Any, CultureInfo.InvariantCulture, out dVer))
{
fileFormatVersion = 2022;
return;
}
if (dVer <= 4.0)
fileFormatVersion = 2010;
else if(dVer <= 12.0)
fileFormatVersion = 2012;
else if (dVer <= 14.0)
fileFormatVersion = 2015;
else if (dVer <= 15.0)
fileFormatVersion = 2017;
else if (dVer <= 16.0)
fileFormatVersion = 2019;
else
// Try guess the future
// 16 => 2019, increase by 2 years every major version.
fileFormatVersion = 2019 + (((int)(dVer) - 16) * 2);
} //setToolsVersion
public EKeyword Keyword = EKeyword.None;
public const String keyword_Windows = "windows";
public const String keyword_Android = "android";
public const String keyword_AntPackage = "antpackage";
public const String keyword_GradlePackage = "gradlepackage";
/// <summary>
/// Only if Keyword == GradlePackage
/// </summary>
GradlePackage gradlePackage;
public GradlePackage GradlePackage
{
get {
if( gradlePackage == null )
gradlePackage = new GradlePackage();
return gradlePackage;
}
}
/// <summary>
/// Gets target OS based on keyword, null if default. (windows or don't care)
/// </summary>
/// <returns></returns>
public String getOs()
{
switch (Keyword)
{
case EKeyword.Android:
return "android";
case EKeyword.AntPackage:
return Project.keyword_AntPackage;
case EKeyword.GradlePackage:
return Project.keyword_GradlePackage;
default:
return null;
}
} //getOs
/// <summary>
/// Target Platform Version, e.g. "8.1" or "10.0.14393.0"
/// </summary>
public String WindowsTargetPlatformVersion;
/// <summary>
/// .NET Target Framework Version, for example "v4.7.2"
/// </summary>
public string TargetFrameworkVersion;
[XmlIgnore]
public List<Project> nodes = new List<Project>(); // Child nodes (Empty folder also does not have any children)
[XmlIgnore]
public Project parent; // Points to folder which contains given project
/// <summary>
/// Project name and it's relative path in form: "subdir\\name"
/// </summary>
public string ProjectName;
/// <summary>
/// Sub-folder and filename of project to save. language defines project file extension
/// </summary>
public string RelativePath;
/// <summary>
/// if null - RelativePath includes file extension, if non-null - "C++" or "C#" - defines project file extension.
/// </summary>
public string language;
/// <summary>
/// Gets programming language of project.
/// </summary>
/// <returns></returns>
public string getLanguage()
{
if (language == null) return "C++";
return language;
}
/// <summary>
/// gets relative path based on programming language
/// </summary>
/// <returns></returns>
public String getRelativePath()
{
if (RelativePath == null)
throw new Exception2("Project '" + ProjectName + "' location was not specified");
String path = RelativePath.Replace("/", "\\");
if (bIsFolder)
return path;
if (Keyword == EKeyword.AntPackage || Keyword == EKeyword.GradlePackage)
return path + ".androidproj";
return path + getProjectExtension();
} //getRelativePath
/// <summary>
/// Gets project extension.
/// </summary>
/// <returns>Project extension</returns>
public String getProjectExtension()
{
switch (language)
{
default: return "";
case "C": return ".vcxproj";
case "C++": return ".vcxproj";
case "C#": return ".csproj";
}
}
/// <summary>
/// Gets folder where project will be saved in.
/// </summary>
public String getProjectFolder()
{
String dir;
if (solution == null)
dir = SolutionProjectBuilder.m_workPath;
else
dir = Path.GetDirectoryName(solution.path);
dir = Path.Combine(dir, Path.GetDirectoryName(RelativePath));
return dir;
}
/// <summary>
/// Gets project full path
/// </summary>
/// <returns>Project full path</returns>
public String getFullPath()
{
String dir;
if (solution == null)
dir = SolutionProjectBuilder.m_workPath;
else
dir = Path.GetDirectoryName(solution.path);
return Path.Combine(dir, RelativePath + getProjectExtension());
}
/// <summary>
/// Returns true if this is not a project, but solution folder instead.
/// </summary>
/// <returns>false - project, true - folder in solution</returns>
public bool IsSubFolder()
{
return bIsFolder;
}
/// <summary>
/// Same amount of configurations as in solution, this however lists project configurations, which correspond to solution configuration
/// using same index.
/// </summary>
public List<String> slnConfigurations = new List<string>();
/// <summary>
/// List of supported configuration|platform permutations, like "Debug|Win32", "Debug|x64" and so on.
/// </summary>
public List<String> configurations = new List<string>();
/// <summary>
/// Updates file configuration array from project configurations
/// </summary>
/// <param name="fi">File to which to add configurations</param>
public void updateFileConfigurations(FileInfo fi)
{
while (fi.fileConfig.Count < configurations.Count)
fi.fileConfig.Add(new FileConfigurationInfo()
{
confName = configurations[fi.fileConfig.Count],
Optimization = EOptimization.ProjectDefault
}
);
}
/// <summary>
/// Gets list of supported configurations like 'Debug' / 'Release'
/// </summary>
public List<String> getConfigurationNames()
{
return configurations.Select(x => x.Split('|')[0]).Distinct().ToList();
}
/// <summary>
/// Gets list of supported platforms like 'Win32' / 'x64'
/// </summary>
public List<String> getPlatforms()
{
return configurations.Select(x => x.Split('|')[1]).Distinct().ToList();
}
/// <summary>
/// true or false whether to build project or not.
/// </summary>
public List<bool> slnBuildProject = new List<bool>();
/// <summary>
/// true to deploy project, false - not, null - invalid. List is null if not used at all.
/// </summary>
public List<bool?> slnDeployProject = null;
/// <summary>
/// Enable clr support
/// </summary>
public ECLRSupport CLRSupport = ECLRSupport.None;
/// <summary>
/// Project guid, for example "{65787061-7400-0000-0000-000000000000}"
/// </summary>
public string ProjectGuid;
/// <summary>
/// Without "{}"
/// </summary>
public String ProjectGuidShort
{
get
{
return ProjectGuid.Substring(1, ProjectGuid.Length - 2);
}
}
/// <summary>
/// per configuration list
/// </summary>
public List<Configuration> projectConfig = new List<Configuration>();
/// <summary>
/// Project dependent guids. Set to null if not used.
/// </summary>
public List<String> ProjectDependencies { get; set; }
/// <summary>
/// This array includes all items from ItemGroup, independently whether it's include file or file to compile, because
/// visual studio is ordering them alphabetically - we keep same array to be able to sort files.
/// </summary>
public List<FileInfo> files = new List<FileInfo>();
public string AsSlnString()
{
return "Project(\"" + ((bIsFolder) ? "Folder" : "Project") + "\") = \"" + ProjectName + "\", \"" + RelativePath + "\", \"" + ProjectGuid + "\"";
}
static String[] RegexExract(String pattern, String input)
{
Match m = Regex.Match(input, pattern);
if (!m.Success)
throw new Exception("Error: Parse failed (input string '" + input + "', regex: '" + pattern + "'");
return m.Groups.Cast<Group>().Skip(1).Select(x => x.Value).ToArray();
} //RegexExract
/// <summary>
/// Extracts configuration name in readable form.
/// Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" => "Debug|x64"
/// </summary>
/// <returns>null if Condition node does not exists, configuration name otherwise</returns>
static String getConfiguration(XElement node)
{
var n = node.Attribute( "Condition" );
if( n == null )
return null;
String config = RegexExract("^ *'\\$\\(Configuration\\)\\|\\$\\(Platform\\)' *== *'(.*)'", n.Value)[0];
return config;
}
void confListInit<T>(ref List<T> list, T defT = default(T))
{
if( list == null )
list = new List<T>(configurations.Count);
while (list.Count < configurations.Count)
{
T t = defT;
if (t == null)
t = (T)Activator.CreateInstance(typeof(T));
list.Add(t);
}
}
/// <summary>
/// Extracts compilation options for single cpp/cs file.
/// </summary>
/// <param name="clCompile">xml node from where to get</param>
/// <param name="file2compile">compiler options to fill out</param>
/// <param name="subField">Into which field to enter if non null</param>
void ExtractCompileOptions(XElement clCompile, FileInfo file2compile, String subField)
{
foreach (XElement fileProps in clCompile.Elements())
{
int[] confIndexes2Process;
if (fileProps.Attribute("Condition") == null)
{
// This kind of nodes is possible to create only using custom build tools like premake5, Visual studio does not produce such projects.
confIndexes2Process = new int[configurations.Count];
for (int i = 0; i < configurations.Count; i++)
confIndexes2Process[i] = i;
}
else {
String config = getConfiguration(fileProps);
int iCfg = configurations.IndexOf(config);
if (iCfg == -1)
continue; // Invalid configuration string specified.
confIndexes2Process = new int[] { iCfg };
} //if-else
String localName = fileProps.Name.LocalName;
Type type = typeof(FileConfigurationInfo);
if (subField != null)
type = type.GetField(subField).FieldType; //==typeof(CustomBuildRule)
FieldInfo fi = null;
String xmlNodeName = fileProps.Name.LocalName;
if (xmlNodeName == "AdditionalOptions")
xmlNodeName = "ClCompile_AdditionalOptions";
fi = type.GetField(xmlNodeName);
if (fi == null)
{
// Generated by premake5, no clue what this tag is, maybe a bug in premake5 tool.
if (xmlNodeName == "FileType")
continue;
if (Debugger.IsAttached) Debugger.Break();
continue;
}
//
// FileConfigurationInfo: PrecompiledHeader, PreprocessorDefinitions, AdditionalUsingDirectories,
// AdditionalIncludeDirectories, ObjectFileName, XMLDocumentationFileName
// CustomBuildRule: Command, Message, Outputs, AdditionalInputs, DisableSpecificWarnings
//
while (file2compile.fileConfig.Count < configurations.Count)
{
int i = file2compile.fileConfig.Count;
// Add new configurations, use same precompiled header setting as project uses for given configuration.
FileConfigurationInfo nfci = new FileConfigurationInfo() { PrecompiledHeader = projectConfig[i].PrecompiledHeader };
nfci.Optimization = EOptimization.ProjectDefault;
file2compile.fileConfig.Add(nfci);
if (subField != null)
//file2compile.fileConfig[i].customBuildRule = new CustomBuildRule;
typeof(FileConfigurationInfo).GetField(subField).SetValue(nfci, Activator.CreateInstance(type));
} //while
foreach (int iCfg in confIndexes2Process)
{
FileConfigurationInfo fci = file2compile.fileConfig[iCfg];
Object o2set;
if (subField == null)
o2set = fci;
else
o2set = typeof(FileConfigurationInfo).GetField(subField).GetValue(fci); //fci.customBuildRule
object oValue;
if (fi.FieldType.IsEnum)
oValue = Enum.Parse(fi.FieldType, fileProps.Value);
else
oValue = Convert.ChangeType(fileProps.Value, fi.FieldType);
if (xmlNodeName == "AdditionalInputs")
oValue = oValue.ToString().Replace(";%(AdditionalInputs)", ""); //No need for this extra string.
fi.SetValue(o2set, oValue);
} //foreach
} //foreach
} //ExtractCompileOptions
/// <summary>
/// Gets xml node by name.
/// </summary>
/// <param name="node">Xml node from where to get</param>
/// <param name="field">Xml tag to query</param>
/// <returns>object if xml node value if any, null if not defined</returns>
static object ElementValue(XElement node, String field)
{
object oValue = node.Element(node.Document.Root.Name.Namespace + field)?.Value;
return oValue;
}
/// <summary>
/// Copies field by "field" - name, from node.
/// </summary>
/// <returns>false if fails (value does not exists)</returns>
static bool CopyField(object o2set, String field, XElement node)
{
FieldInfo fi = o2set.GetType().GetField(field);
Object oValue = null;
while (true)
{
oValue = ElementValue(node, field);
if (oValue != null)
break;
if (field == "ProjectGuid") // Utility projects can have such odd nodes naming.
{
field = "ProjectGUID";
continue;
}
break;
}
// EKeyword, ECLRSupport
if (fi.FieldType.IsEnum)
{
if (oValue == null)
return false;
// ECLRSupport, enum resolving via Description-attribute.
if (fi.FieldType.GetCustomAttribute<DescriptionAttribute>() != null)
{
int value = fi.FieldType.GetEnumNames().Select(x => fi.FieldType.GetMember(x)[0].GetCustomAttribute<DescriptionAttribute>().Description).ToList().IndexOf(oValue.ToString());
oValue = fi.FieldType.GetEnumNames()[value];
}
oValue = Enum.Parse(fi.FieldType, (String)oValue);
}
fi.SetValue(o2set, oValue);
return oValue != null;
}
static bool IsSimpleDataType(Type type)
{
if (type == typeof(bool) ||
type == typeof(double) ||
type == typeof(int) ||
type.IsEnum ||
type == typeof(string) ||
type == typeof(float) ||
type == typeof(System.Int64) ||
type == typeof(System.Int16)
)
return true;
return false;
}
/// <summary>
/// Copies data from node to object o, using field info fi.
/// </summary>
void copyNodeToObject(FieldInfo fi, XElement node, object o)
{
object childo = fi.GetValue(o);
Type type = fi.FieldType;
XElement[] nodes = node.Elements().ToArray();
// Explode sub nodes if we have anything extra to scan. (Comes from ItemDefinitionGroup)
for (int i = 0; i < nodes.Length; i++)
{
String nodeName = nodes[i].Name.LocalName;
FieldInfo childFi = type.GetField(nodeName);
if (childFi == null)
continue;
if (!IsSimpleDataType(childFi.FieldType))
continue;
childFi.SetValue(childo, Convert.ChangeType(nodes[i].Value, childFi.FieldType));
}
}
void extractGeneralCompileOptions(XElement node)
{
int[] cfgIndexes = null;
String config = getConfiguration(node);
if( config == null )
{
// Visual studio does not have projects like this, but GYP generator does
cfgIndexes = Enumerable.Range( 0, configurations.Count ).ToArray();
}
else
{
int iCfg = configurations.IndexOf( config );
if( iCfg == -1 )
return;
cfgIndexes = new int[] { iCfg };
}
foreach ( int iCfg in cfgIndexes )
{
Configuration cfg = projectConfig[iCfg];
List<XElement> nodes = node.Elements().ToList();
// Explode sub nodes if we have anything extra to scan. (Comes from ItemDefinitionGroup)
for (int i = 0; i < nodes.Count; i++)
{
String nodeName = nodes[i].Name.LocalName;
// Nodes can be exploded into same scan loop as long as key do not overlap (e.g. compile options versus link options).
if (nodeName == "ClCompile" || nodeName == "Link" || nodeName == "AntPackage" || nodeName == "Lib") // These nodes are located in ItemDefinitionGroup, we simply expand sub children.
{
foreach (XElement compLinkNode in nodes[i].Elements())
{
// ClCompile & Link has same named options, we try to differentiate them here.
if (compLinkNode.Name.LocalName == "AdditionalOptions")
compLinkNode.Name = nodeName + "_AdditionalOptions";
nodes.Add(compLinkNode);
}
nodes.RemoveAt(i);
i--;
}
} //for
foreach (XElement cfgNode in nodes)
{
String fieldName = cfgNode.Name.LocalName;
if (fieldName == "LibraryDependencies")
fieldName = "AdditionalDependencies";
//
// Visual studio project keeps Lib options in separate xml tag <Lib> <AdditionalOptions>... - but for us it's the same as LinkOptions.
//
if (fieldName == "Lib_AdditionalOptions") fieldName = "Link_AdditionalOptions";
FieldInfo fi = typeof(Configuration).GetField(fieldName);
if (fi == null)
continue;
if (!IsSimpleDataType(fi.FieldType))
{
copyNodeToObject(fi, cfgNode, cfg);
continue;
}
if (fi.FieldType.IsEnum)
{
if (fi.FieldType.GetCustomAttribute<DescriptionAttribute>() == null )
{
if (fi.FieldType == typeof(EUseOfMfc) && cfgNode.Value == "false")
{
fi.SetValue(cfg, EUseOfMfc._false);
}
else
{
String v = cfgNode.Value;
if (fi.Name == "PrecompiledHeader" && v == "")
v = "ProjectDefault";
// cmake produces file like this.
if (fi.Name == "DebugInformationFormat" && v == "")
v = "Invalid";
fi.SetValue(cfg, Enum.Parse(fi.FieldType, v));
}
}
else
{
// Extract from Description attributes their values and map corresponding enumeration.
int value = fi.FieldType.GetEnumNames().Select(x => fi.FieldType.GetMember(x)[0].GetCustomAttribute<DescriptionAttribute>().Description).ToList().IndexOf(cfgNode.Value);
if (value == -1)
throw new Exception2("Invalid / not supported value '" + cfgNode.Value + "'");
fi.SetValue(cfg, Enum.Parse(fi.FieldType, fi.FieldType.GetEnumNames()[value]));
}
if (fieldName == "ConfigurationType")
((Configuration)cfg).ConfigurationTypeUpdated();
}
else
{
fi.SetValue(cfg, Convert.ChangeType(cfgNode.Value, fi.FieldType));
}
} //foreach
} //foreach
} //extractGeneralCompileOptions
/// <summary>
/// Gets projects guid from file.
/// </summary>
/// <param name="path">path from where to load project</param>
/// <returns>Project guid</returns>
static public String getProjectGuid(String path)
{
Project p = LoadProject(null, path, null, 1);
return p.ProjectGuid;
}
/// <summary>
/// Loads project. If project exists in solution, it's loaded in same instance.
/// </summary>
/// <param name="solution">Solution if any exists, null if not available.</param>
/// <param name="path">path from where to load project</param>
/// <param name="project">instance into which to load, null if create new</param>
/// <param name="loadLevel">1 if interested only in guid</param>
static public Project LoadProject(Solution solution, String path, Project project = null, int loadLevel = 0 )
{
if (project == null)
project = new Project() { solution = solution };
if (path == null)
path = project.getFullPath();
// .csproj loading is not supported at the moment.
if (project.language == "C#" || !File.Exists(path))
{
project.bDefinedAsExternal = true;
return project;
}
project.bDefinedAsExternal = false;
XDocument p = XDocument.Load(path);
var toolsVerNode = p.Root.Attribute("ToolsVersion");
if (toolsVerNode == null) // For example vs2008 projects.
throw new Exception("Project file format is not supported: '" + path + "'");
String toolsVer = toolsVerNode.Value;
if(toolsVer != "")
project.setToolsVersion(toolsVer);
foreach (XElement node in p.Root.Elements())
{
String lname = node.Name.LocalName;
switch (lname)
{
case "ItemGroup":
if (loadLevel == 1) continue;
// ProjectConfiguration has Configuration & Platform sub nodes, but they cannot be reconfigured to anything else then this attribute.
if (node.Attribute("Label")?.Value == "ProjectConfigurations")
{
project.configurations = node.Elements().Select(x => x.Attribute("Include").Value).ToList();
project.configurations.ForEach(x => project.projectConfig.Add(new Configuration()));
}
else
{
//
// .h / .cpp / custom build files are picked up here.
//
foreach (XElement igNode in node.Elements())
{
FileInfo f = new FileInfo();
f.includeType = (IncludeType)Enum.Parse(typeof(IncludeType), igNode.Name.LocalName);
f.relativePath = igNode.Attribute("Include").Value;
// Simplify path apperance. (Potentially cmake / premake5 were used)
if (f.relativePath.StartsWith(".\\"))
f.relativePath = f.relativePath.Substring(2);
if (f.includeType == IncludeType.Reference)
{
foreach (XElement refNode in igNode.Elements())
{
// HintPath, Private, CopyLocalSatelliteAssemblies, ReferenceOutputAssembly
FieldInfo fi = f.GetType().GetField(refNode.Name.LocalName);
if (fi == null)
continue;
// "false" to false for bool
Type fieldType = Nullable.GetUnderlyingType(fi.FieldType); //typeof(bool?) => typeof(bool)
if (fieldType == null)
fieldType = fi.FieldType;
object oValue = Convert.ChangeType(refNode.Value, fieldType);
fi.SetValue(f, oValue);
}
}
if (f.includeType == IncludeType.ClCompile || f.includeType == IncludeType.CustomBuild)
project.ExtractCompileOptions(igNode, f, (f.includeType == IncludeType.CustomBuild) ? "customBuildRule" : null );
if (f.includeType == IncludeType.ProjectReference)
f.Project = igNode.Elements().Where(x => x.Name.LocalName == "Project").FirstOrDefault()?.Value;
project.files.Add(f);
} //for
}
break;
case "PropertyGroup":
{
String label = node.Attribute("Label")?.Value;
switch (label)
{
case "Globals":
foreach (String field in new String[] { "ProjectGuid",
"Keyword", "WindowsTargetPlatformVersion",
"TargetFrameworkVersion", "CLRSupport" /*, "RootNamespace"*/ })
{
bool bCopied = CopyField(project, field, node);
if (!bCopied && field == "Keyword")
{
if (Path.GetExtension(path).ToLower() == ".androidproj")
{
// Android packaging projects does not have Keyword
String buildType = ElementValue(node, "AndroidBuildType") as String;
if(buildType != null && buildType == "Gradle")
project.Keyword = EKeyword.GradlePackage;
else
project.Keyword = EKeyword.AntPackage;
}
} //if
// Is defined only in vs2017 or higher.
if (bCopied && field == "WindowsTargetPlatformVersion" && project.fileFormatVersion < 2017)
project.fileFormatVersion = 2017;
if (project.ProjectGuid != null && loadLevel == 1)
return project;
}
break;
case null: // Non tagged node contains rest of configurations like 'LinkIncremental', 'OutDir', 'IntDir', 'TargetName', 'TargetExt'
if (node.Attribute("Condition") == null)
{
// Android packaging project can contain such empty nodes. "<PropertyGroup />"
// C# project
foreach (XElement subNode in node.Elements())
{
if (subNode.Name.LocalName == "ProjectGuid")
{
project.ProjectGuid = subNode.Value;
if (project.ProjectGuid != null && loadLevel == 1)
return project;
}
}
continue;
}
project.extractGeneralCompileOptions(node);
break;
case "Configuration":
if (loadLevel == 1) continue;
project.extractGeneralCompileOptions(node);
break;
case "UserMacros":
// What is it - does needs to be supported ?
break;
case "Locals":
// GYP generator specific. What was it?
break;
default:
if (Debugger.IsAttached) Debugger.Break();
break;
} //switch
}
break;
case "Import": break; // Skip for now.
case "ImportGroup": break; // Skip for now.
case "ItemDefinitionGroup":
if (loadLevel == 1) continue;
project.extractGeneralCompileOptions(node);
break;
default:
if (Debugger.IsAttached) Debugger.Break();
break;
} //switch
} //foreach
return project;
} //LoadProject
static String condition( String confName )
{
return "Condition=\"'$(Configuration)|$(Platform)'=='" + confName + "'\"";
}
StringBuilder o; // Stream where we serialize project.
/// <summary>
/// Dumps file or project specific configuration.
/// </summary>
/// <param name="conf">Configuration to dump</param>
/// <param name="confName">Configuration name, null if project wise</param>
/// <param name="projectConf">If null, then conf is project wide configuration, if non-null - project configuration of file specific configuration</param>
void DumpConfiguration(FileConfigurationInfo conf, String confName = null, Configuration projectConf = null )
{
String sCond = "";
if (confName != null)
sCond = " " + condition(confName);
//-----------------------------------------------------------------------------------------
// When UseDebugLibraries is set to true, and optimizations are enabled
// we must disable run-time checks, otherwise will get compilation error.
// cl : Command line error D8016: '/O2' and '/RTC1' command-line options are incompatible
//-----------------------------------------------------------------------------------------
bool bUseDebugLibraries = false;
EOptimization opt = conf.Optimization;
EBasicRuntimeChecks rtc = conf.BasicRuntimeChecks;
if (projectConf != null) // If we have project wide configuration, copy values from there just to know if we need
{ // to configure on individual file level.
bUseDebugLibraries = projectConf.UseDebugLibraries;
if (opt == EOptimization.ProjectDefault)
opt = projectConf.Optimization;
if (rtc == EBasicRuntimeChecks.ProjectDefault)
rtc = projectConf.BasicRuntimeChecks;
}
else
bUseDebugLibraries = (conf as Configuration).UseDebugLibraries;
if (bUseDebugLibraries && opt != EOptimization.Disabled &&