-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathSolutionProjectBuilder.cs
2675 lines (2280 loc) · 100 KB
/
SolutionProjectBuilder.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.Diagnostics;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using Microsoft.Build.Utilities;
/// <summary>
/// Helper class for generating solution or projects.
/// </summary>
public class SolutionProjectBuilder
{
/// <summary>
/// List of solutions being generated.
/// </summary>
public static List<Solution> m_solutions = new List<Solution>();
/// <summary>
/// Currently selected active solution on which all function below operates upon. null if not selected yet.
/// </summary>
public static Solution m_solution = null;
/// <summary>
/// Currently selected active project on which all function below operates upon. null if not selected yet.
/// </summary>
public static Project m_project = null;
/// <summary>
/// project which perform update of solution, all newly added projects must be dependent on it.
/// </summary>
static String solutionUpdateProject = "";
/// <summary>
/// Path where we are building solution / project at. By default same as script is started from.
/// </summary>
public static String m_workPath;
/// <summary>
/// Sets currently work path (where we are building project / solutions )
/// if null is passed as input parameter, sets script's directory as working path.
/// </summary>
/// <param name="path">Path relative or aboslute, null if relative to calling script</param>
public static void setWorkPath(String path = null)
{
if (path == null)
{
m_workPath = Path.GetDirectoryName(Path2.GetScriptPath(2));
return;
}
if (!Path.IsPathRooted(path))
path = Path.GetFullPath(Path.Combine(getExecutingScript(), path));
if (!Directory.Exists(path))
throw new Exception2("Path '" + Exception2.getPath(path) + "' does not exists", 1);
m_workPath = path;
}
/// <summary>
/// Intialize testing settings from command line arguments.
/// </summary>
/// <param name="args"></param>
public static void initFromArgs(params String[] args)
{
for (int i = 0; i < args.Length; i++)
{
String arg = args[i];
if (!(arg.StartsWith("-") || arg.StartsWith("/")))
continue;
switch (arg.Substring(1).ToLower())
{
case "x": Exception2.g_bReportFullPath = false; break;
}
} //foreach
}
/// <summary>
/// Full path from where current execution proceeds (location of .cs script)
/// </summary>
public static String m_currentlyExecutingScriptPath = "";
/// <summary>
/// Gets directory and/or filename under which script is currently executing. This is either determined from script executed by invokeScript
/// or C# initial script location (script which created SolutionProjectBuilder)
/// </summary>
/// <returns>Empty string if no script is yet executing</returns>
public static String getExecutingScript( bool bDirectory = true, bool bFilename = false, bool bExtension = false)
{
if( m_currentlyExecutingScriptPath == "" )
return "";
if( bDirectory && bFilename )
return m_currentlyExecutingScriptPath;
if( bDirectory && !bFilename )
return Path.GetDirectoryName(SolutionProjectBuilder.m_currentlyExecutingScriptPath);
if( bExtension )
return Path.GetFileName(SolutionProjectBuilder.m_currentlyExecutingScriptPath);
return Path.GetFileNameWithoutExtension( SolutionProjectBuilder.m_currentlyExecutingScriptPath );
}
/// <summary>
/// Gets currently executing C# script directory
/// </summary>
public static String getCsPath( [CallerFilePath] string path = "" )
{
return path;
}
/// <summary>
/// Gets currently executing C# script directory
/// </summary>
public static String getCsDir( [CallerFilePath] string path = "" )
{
return Path.GetDirectoryName( path );
}
/// <summary>
/// Gets currently executing C# script filename
/// </summary>
public static String getCsFileName( [CallerFilePath] string path = "" )
{
return Path.GetFileName( path );
}
/// <summary>
/// Relative directory from solution. Set by RunScript.
/// </summary>
public static String m_scriptRelativeDir = "";
static List<String> m_platforms = new List<String>();
static List<String> m_configurations = new List<String>( new String[] { "Debug", "Release" } );
/// <summary>
/// If generating only project, this is global root
/// </summary>
static Project m_solutionRoot = new Project();
static String m_groupPath = "";
private static readonly Destructor Finalise = new Destructor();
static SolutionProjectBuilder()
{
String path = Path2.GetScriptPath(2);
//
// We could have couple of issues here. SolutionProjectBuilder can be instantiated directly or indirectly -
// in this case 2 or 3 varies. But additionally to that we might have or not have syncProj.pdb debug symbols
// causing path to be resolved (incorrectly) or not resolved (null)
// See CsCsInvoke.cs & CsCsInvoke3.cs differences.
//
if ( path == null || Path.GetFileNameWithoutExtension(path).ToLower() == "solutionprojectbuilder" )
path = Path2.GetScriptPath(3);
if (path == null) // If instantiated via C# script project
path = Path2.GetScriptPath(4);
if (path != null)
m_workPath = Path.GetDirectoryName(path);
//Console.WriteLine(m_workPath);
}
/// <summary>
/// true if to save generated solutions or projects.
/// </summary>
public static bool bSaveGeneratedProjects = true;
/// <summary>
/// Forces to save generated solution and projects.
/// </summary>
public static void SaveGenerated( bool bForce = false )
{
try
{
if (!bSaveGeneratedProjects && !bForce)
return;
UpdateInfo uinfo = new UpdateInfo(true);
if (m_solutions.Count != 0)
{
// Flush project into solution.
externalproject(null);
foreach ( Solution s in m_solutions )
{
m_solution = s; // Select just in case if someone is using static generation functions.
s.SaveSolution( uinfo );
foreach( Project p in s.projects )
if( !p.bDefinedAsExternal )
p.SaveProject( uinfo );
}
}
else
{
if (m_project != null)
m_project.SaveProject(uinfo);
else
{
Console.WriteLine("No solution or project defined. Use project() or solution() functions in script");
}
}
uinfo.DisplaySummary();
m_solution = null;
m_project = null;
resetConfigurations();
}
catch (Exception ex)
{
ConsolePrintException(ex);
}
}
/// <summary>
/// Execute once for each invocation of script. Not executed if multiple scripts are included.
/// </summary>
private sealed class Destructor
{
~Destructor()
{
SaveGenerated();
}
}
/// <summary>
/// Creates new solution.
/// </summary>
/// <param name="name">Solution name</param>
static public void solution(String name)
{
// Flush last project if any was generated, so it would end up into correct solution
externalproject( null );
Solution sln2select = m_solutions.Where( x => x.name == name ).FirstOrDefault();
if( sln2select == null )
{
m_solution = new Solution() { name = name };
m_solution.path = Path.Combine( m_workPath, name );
if( !m_solution.path.EndsWith( ".sln" ) )
m_solution.path += ".sln";
m_solutions.Add( m_solution );
}
else
{
m_solution = sln2select;
}
}
static void requireSolutionSelected(int callerFrame = 0)
{
if (m_solution == null)
throw new Exception2("Solution not specified (Use solution(\"name\" to specify new solution)", callerFrame + 1);
}
static void requireProjectSelected(int callerFrame = 0)
{
if (m_project == null)
throw new Exception2("Project not specified (Use project(\"name\" to specify new project)", callerFrame + 1);
}
static void generateConfigurations()
{
// Generating configurations for solution
if (m_project == null)
{
requireSolutionSelected(1);
m_solution.configurations.Clear();
foreach (String platform in m_platforms)
foreach (String configuration in m_configurations)
m_solution.configurations.Add(configuration + "|" + platform);
}
else {
requireProjectSelected(1);
if (m_project.projectConfig.Count != 0)
throw new Exception2("You must use platforms() or configurations() before you start to configure project using other functions", 2);
m_project.configurations.Clear();
foreach (String platform in m_platforms)
foreach (String configuration in m_configurations)
m_project.configurations.Add(configuration + "|" + platform);
}
}
/// <summary>
/// Specify platform list to be used for your solution or project.
/// For example: platforms("x86", "x64");
/// </summary>
/// <param name="platformList">List of platforms to support</param>
static public void platforms(params String[] platformList)
{
m_platforms = platformList.Distinct().ToList();
generateConfigurations();
}
/// <summary>
/// Specify which configurations to support. Typically "Debug" and "Release".
/// </summary>
/// <param name="configurationList">Configuration list to support</param>
static public void configurations(params String[] configurationList)
{
m_configurations = configurationList.Distinct().ToList();
generateConfigurations();
}
/// <summary>
/// Generates Guid based on String. Key assumption for this algorithm is that name is unique (across where it it's being used)
/// and if name byte length is less than 16 - it will be fetched directly into guid, if over 16 bytes - then we compute sha-1
/// hash from string and then pass it to guid.
/// </summary>
/// <param name="name">Unique name which is unique across where this guid will be used.</param>
/// <returns>For example "{706C7567-696E-7300-0000-000000000000}" for "plugins"</returns>
static public String GenerateGuid(String name)
{
byte[] buf = Encoding.UTF8.GetBytes(name);
byte[] guid = new byte[16];
if (buf.Length < 16)
{
Array.Copy(buf, guid, buf.Length);
}
else
{
using (SHA1 sha1 = SHA1.Create())
{
byte[] hash = sha1.ComputeHash(buf);
// Hash is 20 bytes, but we need 16. We loose some of "uniqueness", but I doubt it will be fatal
Array.Copy(hash, guid, 16);
}
}
// Don't use Guid constructor, it tends to swap bytes. We want to preserve original string as hex dump.
String guidS = "{" + String.Format("{0:X2}{1:X2}{2:X2}{3:X2}-{4:X2}{5:X2}-{6:X2}{7:X2}-{8:X2}{9:X2}-{10:X2}{11:X2}{12:X2}{13:X2}{14:X2}{15:X2}",
guid[0], guid[1], guid[2], guid[3], guid[4], guid[5], guid[6], guid[7], guid[8], guid[9], guid[10], guid[11], guid[12], guid[13], guid[14], guid[15]) + "}";
return guidS;
}
static void specifyproject(String name)
{
if (m_project != null)
{
if (m_solution != null)
{
if (!m_solution.projects.Contains(m_project))
m_solution.projects.Add(m_project);
}
else
// We are collecting projects only (no solution) and this is not last project
if (name != null)
m_project.SaveProject(new UpdateInfo(true));
}
// Release active project
m_project = null;
resetConfigurations();
if (name == null) // Will be used to "flush" last filled project.
{
return;
}
if (m_solution != null)
{
m_project = m_solution.projects.Where(x => x.ProjectName == name).FirstOrDefault();
// Selecting already specified project.
if (m_project != null)
return;
}
m_project = new Project() { solution = m_solution };
if (solutionUpdateProject != "")
dependson(solutionUpdateProject);
m_project.ProjectName = name;
m_project.language = "C++";
String path = Path.Combine(m_scriptRelativeDir, name);
path = new Regex(@"[^\\/]+[\\/]\.\.[\\/]").Replace(path, ""); // Remove extra upper folder references if any
m_project.RelativePath = path;
Project parent = m_solutionRoot;
if( m_solution != null ) parent = m_solution.solutionRoot;
String pathSoFar = "";
// Result of group() expansion - try to create correspondent "virtual projects / folders"
if (m_solution != null)
{
foreach (String pathPart in m_groupPath.Split(new char[] { '/', '\\' }, StringSplitOptions.RemoveEmptyEntries))
{
Project p = parent.nodes.Where(x => x.ProjectName == pathPart && x.RelativePath == pathPart).FirstOrDefault();
pathSoFar = pathSoFar + ((pathSoFar.Length != 0) ? "/" : "") + pathPart;
if (p == null)
{
// GenerateGuid uses extra garbage so group name and project name uuid's won't collide.
p = new Project() { solution = m_solution, ProjectName = pathPart, RelativePath = pathPart, ProjectGuid = GenerateGuid("!#¤%!#¤%" + pathSoFar), bIsFolder = true };
m_solution.projects.Add(p);
parent.nodes.Add(p);
p.parent = parent;
}
parent = p;
}
} //if
parent.nodes.Add(m_project);
m_project.parent = parent;
}
/// <summary>
/// Add to solution reference to external project. Call with null parameter to flush currently active project (Either to solution
/// or to disk).
/// </summary>
/// <param name="name">Project name</param>
static public void externalproject(String name)
{
specifyproject(name);
if( name != null )
m_project.bDefinedAsExternal = true;
}
/// <summary>
/// Adds new project to solution
/// </summary>
/// <param name="name">Project name</param>
static public void project(String name)
{
specifyproject(name);
if( name != null )
m_project.bDefinedAsExternal = false;
}
/// <summary>
/// Selects default toolset after vsver or kind project definition.
/// </summary>
static void selectDefaultToolset( bool force = false )
{
if (m_project.Keyword == EKeyword.Win32Proj || m_project.Keyword == EKeyword.MFCProj || m_project.Keyword == EKeyword.None)
{
// We can specify version before configurations / platforms were selected.
if (m_project.projectConfig.Count == 0)
return;
using (new UsingSyncProj(4))
{
switch (m_project.fileFormatVersion)
{
case 2010: toolset("v100", force); break;
case 2012: toolset("v110", force); break;
case 2013: toolset("v120", force); break;
case 2015: toolset("v140", force); break;
case 2017:
toolset("v141", force);
systemversion("10.0.17134.0", force); // Newer visual studio's also enforces specific Windows SDK version
break;
case 2019:
toolset("v141", force);
systemversion("10.0.17763.0", force);
break;
default:
// Try to guess the future. 2020 => "v160" ?
toolset("v" + (((m_project.fileFormatVersion - 2020) + 16) * 10).ToString());
break;
} //switch
} //using
} //if
}
/// <summary>
/// Sets Visual Studio file format version to be used.
/// </summary>
/// <param name="vsVersion">2010, 2012, 2013, ...</param>
/// <param name="force">set to true if besides selecting visual studio project format version, also set default toolset for specific project</param>
static public void vsver(int vsVersion, bool force = true)
{
if (m_solution == null && m_project == null)
requireSolutionSelected();
if (m_project != null)
{
m_project.SetFileFormatVersion(vsVersion);
// Reselect default toolset, if file format version changed.
selectDefaultToolset(force);
}
else
{
m_solution.fileFormatVersion = vsVersion;
}
} //vsver
/// <summary>
/// Sets visual studio version
/// </summary>
static public void VisualStudioVersion(String v, bool force = true)
{
requireSolutionSelected();
if (!force && m_solution.VisualStudioVersion != null)
return;
m_solution.VisualStudioVersion = v;
}
/// <summary>
/// Sets minimum visual studio version
/// </summary>
static public void MinimumVisualStudioVersion(String v, bool force = true)
{
requireSolutionSelected();
if (!force && m_solution.MinimumVisualStudioVersion != null)
return;
m_solution.MinimumVisualStudioVersion = v;
}
/// <summary>
/// The location function sets the destination directory for a generated solution or project file.
/// </summary>
/// <param name="_path"></param>
static public void location(String _path)
{
if (m_project == null)
{
setWorkPath(_path);
}
else
{
String absPath = _path;
if (!Path.IsPathRooted(_path))
absPath = Path.Combine(m_project.getProjectFolder(), _path);
if(!m_project.bDefinedAsExternal && !Directory.Exists( absPath ) )
throw new Exception2( "Path '" + _path + "' does not exists");
// Measure relative path against solution path if that one is present or against working path.
String solPath = m_workPath;
if( m_project.solution != null )
solPath = Path.GetDirectoryName(m_project.solution.path);
// Always recalculate relative directory, since it might change if solution is not specified.
String dir = Path2.makeRelative(absPath, solPath );
m_project.RelativePath = Path.Combine(dir, m_project.ProjectName);
}
}
/// <summary>
/// Sets project / solution generate location to be the same as script current location
/// </summary>
/// <param name="subDir">Additional sub-directory if any</param>
static public void setLocationFromScriptPath( String subDir = null )
{
String scriptPath = Path2.GetScriptPath(2 /* 1 - this function, + 1 - One function call back */);
String dir = Path.GetDirectoryName(scriptPath);
if(subDir != null )
dir = Path.Combine(dir, subDir);
location(dir);
}
/// <summary>
/// Specifies project or solution uuid - could be written in form of normal guid ("{5E40B384-095E-452A-839D-E0B62833256F}")
/// - use this kind of syntax if you need to produce your project in backwards compatible manner - so existing
/// solution can load your project.
/// Could be also written in any string form, but you need to take care that string is unique enough accross where your
/// project is used. For example project("test1"); uuid("test"); project("test1"); uuid("test"); will result in
/// two identical project uuid's and Visual studio will try to resave your project with changed uuid.
/// </summary>
/// <param name="nameOrUuid">Project uuid or some unique name</param>
static public void uuid(String nameOrUuid)
{
bool forceGuid = nameOrUuid.Contains('{') || nameOrUuid.Contains('}');
String uuid = "";
var guidMatch = SolutionProjectBuilder.guidMatcher.Match(nameOrUuid);
if (guidMatch.Success)
{
uuid = "{" + guidMatch.Groups[1].Value + "}";
}
else
{
if (forceGuid)
throw new Exception2("Invalid uuid value '" + nameOrUuid + "'");
uuid = GenerateGuid(nameOrUuid);
}
if (m_solution != null)
{
Project p = m_solution.projects.Where(x => x.ProjectGuid == uuid).FirstOrDefault();
if (p != null)
throw new Exception2("uuid '" + uuid + "' is already used by project '" +
p.ProjectName + "' - please consider using different uuid. " +
"For more information refer to uuid() function description.");
}
if (m_project == null && m_solution == null)
// You must have at least something selected.
requireProjectSelected();
if (m_project != null)
m_project.ProjectGuid = uuid;
else
m_solution.SolutionGuid = uuid;
} //uuid
/// <summary>
/// Sets project programming language (reflects to used project extension if used for non-file specific configuration)
/// </summary>
/// <param name="lang">C, C++, C#, if no parameter is specified (null), sets project to autodetect programming language</param>
static public void language(String lang = null)
{
requireProjectSelected();
ECompileAs compileAs = ECompileAs.Default;
switch (lang)
{
case null:
compileAs = ECompileAs.Default;
lang = "C++"; // File extension will be .vcxproj anyway, but to what to compile file will be left to VS.
break;
case "C":
compileAs = ECompileAs.CompileAsC;
break;
case "C++":
compileAs = ECompileAs.CompileAsCpp;
break;
case "C#":
break;
default:
throw new Exception2("Language '" + lang + "' is not supported");
} //switch
if (!m_project.bDefinedAsExternal)
{
// Set up default compilation language
foreach (var conf in getSelectedConfigurations(false))
conf.CompileAs = compileAs;
}
if (!bLastSetFilterWasFileSpecific)
m_project.language = lang;
} //language
public static Regex guidMatcher = new Regex("^[{(]?([0-9A-Fa-f]{8}[-][0-9A-Fa-f]{4}[-][0-9A-Fa-f]{4}[-][0-9A-Fa-f]{4}[-][0-9A-Fa-f]{12})[)}]?$");
/// <summary>
/// Specify one or more non-linking project build order dependencies.
/// </summary>
/// <param name="dependencies">List of dependent projects</param>
static public void dependson(params String[] dependencies)
{
requireProjectSelected();
if (m_project.ProjectDependencies == null)
m_project.ProjectDependencies = new List<string>();
m_project.ProjectDependencies.AddRange(dependencies);
} //dependson
/// <summary>
/// Specifies reference to another project. As an input you should provide project path, with optional project guid.
/// If project guid is not provided, it will be loaded from project itself. (Slight performance penalties)
/// </summary>
/// <param name="fileGuidList">Project file path + project guid list</param>
static public void referencesProject(params String[] fileGuidList)
{
requireProjectSelected();
for (int i = 0; i < fileGuidList.Length; i++)
{
String relPath = fileGuidList[i];
String path = Path.Combine(m_project.getProjectFolder(), relPath);
String guid = null;
if (i + 1 < fileGuidList.Length)
{
guid = fileGuidList[i + 1];
Match mGuid = guidMatcher.Match(guid);
if (!mGuid.Success)
{
String nameForGuid = guid;
if(nameForGuid.Length == 0 )
nameForGuid = Path.GetFileNameWithoutExtension(relPath);
guid = GenerateGuid(nameForGuid);
}
else
{
guid = "{" + mGuid.Groups[1].Value + "}";
}
i++;
} //if
if (guid == null)
{
if (!File.Exists(path))
throw new Exception2("Referenced project '" + Exception2.getPath(path) + "' does not exists.\r\n" +
"You can avoid loading project by specifying project guid after project path, for example:\r\n" +
"\r\n" +
" referencesProject(\"project.vcxproj\", \"{E3A9D624-DA07-DBBF-B4DD-0E33BE2390AE}\" ); \r\n" +
"\r\n" +
"or if you're using syncProj on that project:\r\n" +
"\r\n" +
" referencesProject(\"project.vcxproj\", \"unique name\" ); or \r\n" +
" referencesProject(\"project.vcxproj\", \"\" ); - same as referencesProject(\"project.vcproj\", \"project\" );"
);
guid = Project.getProjectGuid(path);
}
using (new UsingSyncProj(1))
files(relPath);
FileInfo fi = m_project.files.Last();
fi.includeType = IncludeType.ProjectReference;
fi.Project = guid;
} //for
}
/// <summary>
/// For C++/cli - adds reference to specific assemblies.
/// </summary>
/// <param name="assemblyNamesAndParameters">List of assembly names, for example "System" or path to specific assembly. use '?' as first character to
/// supress assembly name check. Assemby name can be followed by extra 0-3 booleans to configure assembly copy options.
/// Once you use booleans - they are applied to all previously listed assemblies. Make separate calls to distingvish different options.
///
/// references("System", "System.Data");
/// references("my1.dll", "my2.dll", false); Copy local will be disabled for both dll's.
///
/// </param>
static public void references(params object[] assemblyNamesAndParameters)
{
requireProjectSelected();
List<Tuple<String, bool>> dirs = null;
String[] referenceFields = new[] { "HintPath", "Private", "CopyLocalSatelliteAssemblies", "ReferenceOutputAssembly" };
int iFilesFromIndex = m_project.files.Count;
for ( int i = 0; i < assemblyNamesAndParameters.Length; i++)
{
String name = assemblyNamesAndParameters[i].ToString();
bool bCheck = true;
if (name.StartsWith("?"))
{
bCheck = false;
name = name.Substring(1);
}
bool bIsHintPath = name.IndexOf('\\') != -1 || Path.GetExtension(name) != "";
if (bCheck)
{
if (dirs == null)
{
String netVer = m_project.TargetFrameworkVersion;
if (netVer == null) netVer = "v4.0";
var dotnetDirs = ToolLocationHelper.GetPathToReferenceAssemblies(".NETFramework", netVer, "");
if (dotnetDirs.Count == 0)
throw new Exception2("Cannot locate .NET Framework " + netVer + "directory, is it possible that it's not installed ?\r\n"
+ "Use TargetFrameworkVersion() to specify correct .NET version");
dirs = dotnetDirs.Select(x => new Tuple<String, bool>(x, false)).ToList();
dirs.Add(new Tuple<String, bool>(m_project.getProjectFolder(), true));
}
bool bExists = false;
if (Path.IsPathRooted(name))
bExists = File.Exists(name);
else {
foreach (var dir in dirs)
{
bool bIsCustomDll = dir.Item2;
String dll = Path.Combine(dir.Item1, name);
// User will have to provide file extension, for .NET framework assemblies we try to add
// ".dll" automatically
if (!bIsCustomDll && Path.GetExtension(dll).ToLower() != ".dll")
dll += ".dll";
if (File.Exists(dll))
{
bIsHintPath = bIsCustomDll;
bExists = true;
break;
}
}
}
if (!bExists)
{
String paths = String.Join("\r\n", dirs.Select( x => " " + x.Item1).ToArray() );
throw new Exception2("Assembly referred by name '" + name + "' was not found.\r\n\r\n" +
"was searching within following paths: \r\n" + paths );
}
}
FileInfo fi = new FileInfo();
fi.includeType = IncludeType.Reference;
if (bIsHintPath)
{
//
// Theoretically name should be resolved from assembly name, which can be different from
// .dll filename (Only in .net you have "System" assembly name => "System.dll" assembly filename)
// But when loading project visual studio ignores 'Include=<name>' and replaces it with
// correct assembly name. From our perspective it does not matter as VS does not try to save project
// back
//
fi.relativePath = Path.GetFileNameWithoutExtension(name);
fi.HintPath = name;
}
else
{
fi.relativePath = name;
}
m_project.files.Add(fi);
//
// If next parameter is boolean, we mark all freshly added files with same copy options
//
if (i + 1 < assemblyNamesAndParameters.Length && assemblyNamesAndParameters[i + 1] is bool)
{
bool Private = (bool)assemblyNamesAndParameters[++i];
bool CopyLocalSatelliteAssemblies = true;
bool ReferenceOutputAssembly = true;
if (i + 1 < assemblyNamesAndParameters.Length && assemblyNamesAndParameters[i + 1] is bool)
CopyLocalSatelliteAssemblies = (bool)assemblyNamesAndParameters[++i];
if (i + 1 < assemblyNamesAndParameters.Length && assemblyNamesAndParameters[i + 1] is bool)
ReferenceOutputAssembly = (bool)assemblyNamesAndParameters[++i];
for (int iFile = iFilesFromIndex; iFile < m_project.files.Count; iFile++)
{
fi = m_project.files[iFile];
fi.Private = Private;
fi.CopyLocalSatelliteAssemblies = CopyLocalSatelliteAssemblies;
fi.ReferenceOutputAssembly = ReferenceOutputAssembly;
}
iFilesFromIndex = m_project.files.Count;
}
}
}
static Regex unrecognizedEscapeSequence = new Regex("[\x00-\x0D]");
static void validatePathName( String s )
{
var m = unrecognizedEscapeSequence.Match(s);
if (m.Success)
throw new Exception2( "Unrecognized escape sequence:\r\n'" + s.Substring(0,m.Index) + "**** here ****'\r\n", 1);
}
/// <summary>
/// Sets current "directory" where project should be placed.
/// </summary>
/// <param name="groupPath"></param>
static public void group(String groupPath)
{
validatePathName(groupPath);
m_groupPath = groupPath;
}
/// <summary>
/// Invokes C# Script by source code path. If any error, exception will be thrown.
/// </summary>
/// <param name="path">c# script path</param>
/// <param name="bCompileOnly">true if only to compile</param>
static public void invokeScript(String path, bool bCompileOnly = false)
{
String errors = "";
String dir;
String fullPath = path;
// Is not absolute path, then launch from currently executing .cs location
if (!Path.IsPathRooted(fullPath))
{
// By default search from same place where script is.
dir = SolutionProjectBuilder.getExecutingScript();
if( dir == "" )
fullPath = Path.GetFullPath( path );
else
fullPath = Path.Combine(dir, path);
}
CsScript.RunScript(fullPath, bCompileOnly, true, out errors, "no_exception_handling");
}
/// <summary>
/// Selected configurations (Either project global or file specific) selected by filter.
/// selectedFileConfigurations is file specific, selectedConfigurations is project wide.
/// </summary>
static List<FileConfigurationInfo> selectedFileConfigurations = new List<FileConfigurationInfo>();
static List<FileConfigurationInfo> selectedConfigurations = new List<FileConfigurationInfo>();
static String[] selectedFilters = null; // null if not set
/// <summary>
/// true if file specific filtering is active, false if not.
/// </summary>
public static bool bLastSetFilterWasFileSpecific = false;
/// <summary>
/// Resets static variables to be able to start next testing round.
/// </summary>
public static void resetStatics()
{
m_solutions = new List<Solution>();
m_solution = null;
m_project = null;
solutionUpdateProject = "";
m_workPath = null;
m_scriptRelativeDir = "";
m_platforms = new List<String>();
m_configurations = new List<String>(new String[] { "Debug", "Release" });
m_solutionRoot = new Project();
m_groupPath = "";
bSaveGeneratedProjects = true;
resetConfigurations();
}
static void resetConfigurations()
{
selectedFileConfigurations = new List<FileConfigurationInfo>();
selectedConfigurations = new List<FileConfigurationInfo>();
selectedFilters = null; // null if not set
bLastSetFilterWasFileSpecific = false;
}
/// <summary>
/// Gets currently selected configurations by filter.
/// </summary>
/// <param name="bForceNonFileSpecific">true to force project specific configuration set.</param>
/// <param name="callerFrame">Tells how many call call frame behind is end-user code. (Non syncproj code). (Reflects to error reporting)</param>
static List<FileConfigurationInfo> getSelectedConfigurations( bool bForceNonFileSpecific, int callerFrame = 0)
{
List<FileConfigurationInfo> list;
if (bForceNonFileSpecific)
list = selectedConfigurations;
else
list = (bLastSetFilterWasFileSpecific) ? selectedFileConfigurations: selectedConfigurations;
if (list.Count == 0)
filter();
if (list.Count == 0)
throw new Exception2("Please specify configurations() and platforms() before using this function. Amount of configurations and platforms must be non-zero.", callerFrame + 1);
return list;
}
/// <summary>
/// Gets project configuration list, throw exception if cannot be found
/// </summary>
static List<Configuration> getSelectedProjectConfigurations()
{
List<Configuration> projConfs = getSelectedConfigurations(true).Cast<Configuration>().Where(x => x != null).ToList();
return projConfs;
}
/// <summary>
/// Selects to which configurations to apply subsequent function calls (like "kind", "symbols", "files"