This repository was archived by the owner on Nov 13, 2018. It is now read-only.
forked from ArthurHub/HTML-Renderer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeProjects.cs
More file actions
673 lines (614 loc) · 25.7 KB
/
Copy pathMergeProjects.cs
File metadata and controls
673 lines (614 loc) · 25.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
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
//MIT, 2016-2017, WinterDev
//credit: http://stackoverflow.com/questions/24557807/programmatically-create-a-csproj-on-the-fly-without-visual-studio-installed
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using System.Diagnostics;
using System.Reflection;
using Microsoft.Build.Construction;
using Microsoft.Build.Evaluation;
namespace BuildMergeProject
{
public static class StartupConfig
{
public static string defaultSln;
}
public enum ProjectAsmReferenceKind
{
ProjectReference,
Reference
}
public class ProjectAsmReference
{
public ProjectAsmReference(ProjectItem proItem, ProjectAsmReferenceKind kind)
{
this.Name = proItem.EvaluatedInclude;
this.Kind = kind;
this.Item = proItem;
}
public ProjectItem Item { get; set; }
public ProjectAsmReferenceKind Kind { get; set; }
public string Name { get; set; }
public override string ToString()
{
return Kind + " : " + Name;
}
}
public static class GlobalLoadedProject
{
static Dictionary<string, Project> s_loadedProjects = new Dictionary<string, Project>();
public static Project LoadProject(string projectFilename)
{
Project found;
if (!s_loadedProjects.TryGetValue(projectFilename, out found))
{
found = new Project(projectFilename);
return s_loadedProjects[projectFilename] = found;
}
return found;
}
}
public class SolutionMx
{
public Solution _currentSolution;
public string SolutionDir { get; set; }
public string FullPath { get; set; }
public void ReadSolution(string path)
{
this.FullPath = path;
this.SolutionDir = Path.GetDirectoryName(path);
//--------------
//since this should be run on .net4,
//so we read
//we just read what project are in the solution
//easy!
//--------------
_currentSolution = new Solution(path);
//foreach (SolutionProject pro in solution.Projects)
//{
// string proName = pro.ProjectName;
// string relPath = pro.RelativePath;
//}
}
public static string CombineRelativePath(string exePath)
{
string[] sub_paths = exePath.Split('\\');
List<string> totals = new List<string>();
int j = sub_paths.Length;
for (int i = 0; i < j; ++i)
{
string p = sub_paths[i];
if (p == "..")
{
//remove latest data in str
if (totals.Count > 0)
{
//remove the last one
totals.RemoveAt(totals.Count - 1);
}
else
{
}
}
else
{
totals.Add(p);
}
}
System.Text.StringBuilder stbuilder = new System.Text.StringBuilder();
j = totals.Count;
for (int i = 0; i < j; ++i)
{
stbuilder.Append(totals[i]);
if (i != j - 1)
{
stbuilder.Append("\\");
}
}
return stbuilder.ToString();
}
public string BuildPathRelativeToSolution(string subpath, out string rightPart)
{
//-----------------------------------
string rootSlnFolder = this.SolutionDir;
//exe dir
if (!subpath.StartsWith(rootSlnFolder))
{
throw new NotSupportedException();
}
string sub = subpath.Substring(rootSlnFolder.Length);
string[] sub_steps = sub.Split('\\');
//step up to reach solution folder
int nsteps = sub_steps.Length - 2;
string beginAt = "";
for (int i = 0; i < nsteps; ++i)
{
beginAt += "..\\";
}
rightPart = sub;
return beginAt;
}
static int FindFirstDiff(string[] s0_splits, string[] s1_splits)
{
int j = 0;
if ((j = s0_splits.Length) <= s1_splits.Length)
{
for (int i = 0; i < j; ++i)
{
//compare part by part
string s0_p = s0_splits[i];
string s1_p = s1_splits[i];
if (s0_p != s1_p)
{
//stop at this part
return i;
}
else
{
//next
}
}
return j - 1;
}
else
{
throw new NotSupportedException();
}
}
public string BuildPathRelativeToOther(string mainPath, string subpath, out string rightPart)
{
//s1.Length must >= s0.Length
string[] s0_splits = mainPath.Split('\\');
string[] s1_splits = subpath.Split('\\');
int diffPos = FindFirstDiff(s0_splits, s1_splits);
//same at diffPos-1
int nsteps = diffPos - 1;
string beginAt = "";
for (int i = 0; i < nsteps; ++i)
{
beginAt += "..\\";
}
rightPart = "";
int j = s1_splits.Length;
int m = 0;
for (int n = diffPos; n < j; ++n)
{
if (m > 0 && m < j - 1)
{
rightPart += '\\';
}
rightPart += s1_splits[n];
m++;
}
return beginAt;
}
public string GetFullProjectPath(string projectRelativePath)
{
string result = Path.Combine(this.SolutionDir, projectRelativePath);
return result;
}
public List<ProjectAsmReference> GetReferenceAsmList(string projectFile)
{
string fullProjectName = GetFullProjectPath(projectFile);
List<ProjectAsmReference> asmReferenceList = new List<ProjectAsmReference>();
Project pro = GlobalLoadedProject.LoadProject(fullProjectName);
foreach (ProjectItem item in pro.AllEvaluatedItems)
{
switch (item.ItemType)
{
default:
{
}
break;
case "BootstrapperPackage":
case "None":
break;
case "Compile":
//skip
break;
// {
// string onlyFileName = Path.GetFileName(item.EvaluatedInclude);
// if (onlyFileName != "AssemblyInfo.cs") //special case ***no include this file
// {
// allItems.Add(item);
// }
// }
// break;
case "ProjectReference":
asmReferenceList.Add(new ProjectAsmReference(item, ProjectAsmReferenceKind.ProjectReference));
break;
case "Reference":
asmReferenceList.Add(new ProjectAsmReference(item, ProjectAsmReferenceKind.Reference));
break;
}
}
return asmReferenceList;
}
}
public static class LinkProjectConverter
{
public static void ConvertToLinkProject2(SolutionMx slnMx, string srcProject, string autoGenFolder, bool removeOriginalSrcProject)
{
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(srcProject);
var compileNodes = SelectCompileNodes(xmldoc.DocumentElement);
string onlyFileName = Path.GetFileName(srcProject);
string saveFileName = slnMx.SolutionDir + "\\" + autoGenFolder + "\\" + onlyFileName;
string targetSaveFolder = slnMx.SolutionDir + "\\" + autoGenFolder;
string rightPart;
string beginAt = slnMx.BuildPathRelativeToSolution(targetSaveFolder, out rightPart);
foreach (XmlElement elem in compileNodes)
{
XmlAttribute includeAttr = elem.GetAttributeNode("Include");
string includeValue = includeAttr.Value;
string combinedPath = SolutionMx.CombineRelativePath(includeValue);
string b2 = slnMx.BuildPathRelativeToOther(targetSaveFolder, combinedPath, out rightPart);
//this version:
//auto gen project is lower than original 1 level
//so change the original src location
//and create linked child node
includeAttr.Value = "..\\" + beginAt + rightPart;
XmlElement linkNode = xmldoc.CreateElement("Link", elem.NamespaceURI);
linkNode.InnerText = rightPart;
elem.AppendChild(linkNode);
}
string targetSaveDir = System.IO.Path.GetDirectoryName(saveFileName);
if (!Directory.Exists(targetSaveDir))
{
Directory.CreateDirectory(targetSaveDir);
}
xmldoc.Save(saveFileName);
if (removeOriginalSrcProject)
{
File.Delete(srcProject);
}
}
public static void ConvertToLinkProject(string srcProject, string autoGenFolder, bool removeOriginalSrcProject)
{
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(srcProject);
var compileNodes = SelectCompileNodes(xmldoc.DocumentElement);
foreach (XmlElement elem in compileNodes)
{
XmlAttribute includeAttr = elem.GetAttributeNode("Include");
string includeValue = includeAttr.Value;
//this version:
//auto gen project is lower than original 1 level
//so change the original src location
//and create linked child node
includeAttr.Value = "..\\" + includeAttr.Value;
XmlElement linkNode = xmldoc.CreateElement("Link", elem.NamespaceURI);
linkNode.InnerText = includeValue;
elem.AppendChild(linkNode);
}
string onlyFileName = Path.GetFileName(srcProject);
if (!Directory.Exists(autoGenFolder))
{
Directory.CreateDirectory(autoGenFolder);
}
xmldoc.Save(autoGenFolder + "\\" + onlyFileName);
if (removeOriginalSrcProject)
{
File.Delete(srcProject);
}
}
static List<XmlElement> SelectCompileNodes(XmlElement projectNode)
{
//TODO: use xpath ...
List<XmlElement> compileNodes = new List<XmlElement>();
foreach (XmlElement item in projectNode)
{
if (item.Name == "ItemGroup")
{
foreach (XmlElement item2 in item)
{
if (item2.Name == "Compile")
{
compileNodes.Add(item2);
}
}
}
}
return compileNodes;
}
}
public class MergeProject
{
List<ToMergeProject> subProjects = new List<ToMergeProject>();
public List<string> _asmReferences = new List<string>();
bool portable;
public MergeProject(bool portable = false)
{
this.portable = portable;
}
public void LoadSubProject(string projectFile)
{
ToMergeProject pro = new ToMergeProject();
pro.Load(projectFile);
subProjects.Add(pro);
}
public string DefineConstants { get; set; }
public string TargetFrameworkVersion { get; set; }
static ProjectPropertyGroupElement CreatePropertyGroup(ProjectRootElement root,
string targetFrameworkVersion,
string condition, string platform_condition,
string configuration, string platform, bool unsafeMode,
string assemblyName)
{
ProjectPropertyGroupElement group = root.AddPropertyGroup();
var config = group.AddProperty("Configuration", configuration);
config.Condition = condition;
var platform_ = group.AddProperty("Platform", platform);
platform_.Condition = platform_condition;
group.AddProperty("SchemaVersion", "2.0");
group.AddProperty("OutputType", "Library");
group.AddProperty("TargetFrameworkVersion", targetFrameworkVersion);
group.AddProperty("FileAlignment", "512");
group.AddProperty("AssemblyName", assemblyName);
return group;
}
static ProjectPropertyGroupElement CreatePropertyGroupChoice(ProjectRootElement root,
string condition,
bool unsafeMode, string outputPath, bool optimize,
bool debugSymbol, string debugType, string constants
)
{
ProjectPropertyGroupElement group = root.AddPropertyGroup();
group.Condition = condition;
if (unsafeMode)
{
group.AddProperty("AllowUnsafeBlocks", "true");
}
group.AddProperty("ErrorReport", "prompt");
group.AddProperty("WarningLevel", "4");
group.AddProperty("OutputPath", outputPath); //,eg @"bin\Debug\"
group.AddProperty("Optimize", optimize ? "true" : "false");
group.AddProperty("DebugType", debugType);
if (debugSymbol)
{
group.AddProperty("DebugSymbols", "true");
}
group.AddProperty("DefineConstants", constants); //eg DEBUG; TRACE
return group;
}
public void MergeAndSave(string csprojFilename, string assemblyName, string targetFrameworkVersion, string additonalDefineConst, string[] references)
{
ProjectRootElement root = ProjectRootElement.Create();
if (portable)
{
root.ToolsVersion = "14.0";
root.DefaultTargets = "Build";
var import = root.AddImport(@"$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props");
import.Condition = @"Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')";
}
else
{
root.AddImport(@"$(MSBuildToolsPath)\Microsoft.CSharp.targets");
}
ProjectPropertyGroupElement one1 = CreatePropertyGroup(root,
targetFrameworkVersion,
" '$(Configuration)' == '' ",
" '$(Platform)' == '' ",
"Debug", "AnyCPU", true, assemblyName);
if (portable)
{
one1.AddProperty("MinimumVisualStudioVersion", "10.0");
one1.AddProperty("ProjectTypeGuids", "{786C830F-07A1-408B-BD7F-6EE04809D6DB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}");
one1.AddProperty("TargetFrameworkProfile", "Profile111");
}
ProjectPropertyGroupElement debugGroup = CreatePropertyGroupChoice(root,
" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ",
true,
@"bin\Debug\", false, true, "full", "DEBUG; TRACE" + additonalDefineConst);
ProjectPropertyGroupElement releaseGroup = CreatePropertyGroupChoice(root,
" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ",
true,
@"bin\Release\", true, false, "pdbonly", " TRACE" + additonalDefineConst);
if (references.Length > 0)
{
AddItems(root, "Reference", references);
}
List<string> allList = new List<string>();
Dictionary<string, bool> uniqueFileList = new Dictionary<string, bool>();
string onlyProjPath = Path.GetDirectoryName(csprojFilename) + "\\";
int onlyProjPathLength = onlyProjPath.Length;
//TODO: review here
//special for support .net20
bool foundFirstExtensionAttributeFile = false;
foreach (ToMergeProject toMergePro in subProjects)
{
List<string> allAbsFiles = toMergePro.GetAllAbsoluteFilenames();
foreach (string filename in allAbsFiles)
{
string onlyFileName = Path.GetFileName(filename);
if (onlyFileName == "PORTING_NOTMERGE.cs")
{
//our convention
continue;//skip
}
else if (onlyFileName == "ExtensionAttribute.cs")
{ //this is our convention
//... if we have ExtensionAttribute.cs
//the
if (foundFirstExtensionAttributeFile)
{
continue;
}
else
{
foundFirstExtensionAttributeFile = true;
}
}
string combindedFilename = SolutionMx.CombineRelativePath(filename).ToUpper();
if (uniqueFileList.ContainsKey(combindedFilename))
{
continue;
}
uniqueFileList[combindedFilename] = true;//
if (filename.StartsWith(onlyProjPath))
{
allList.Add(filename.Substring(onlyProjPathLength));
}
else
{
allList.Add(filename);
}
}
}
// items to compile
AddItems(root, "Compile", allList.ToArray());
if (portable)
{
root.AddImport(@"$(MSBuildExtensionsPath32)\Microsoft\Portable\$(TargetFrameworkVersion)\Microsoft.Portable.CSharp.targets");
}
root.Save(csprojFilename);
}
static void AddItems(ProjectRootElement elem, string groupName, params string[] items)
{
ProjectItemGroupElement group = elem.AddItemGroup();
foreach (var item in items)
{
ProjectItemElement projItem = group.AddItem(groupName, item);
//if (groupName == "Compile")
//{
// projItem.AddMetadata("Link", item);
//}
}
}
}
public class ToMergeProject
{
List<ProjectItem> allItems = new List<ProjectItem>();
public string ProjectFileName { get; set; }
public string DefineConstants { get; set; }
public string TargetFrameworkVersion { get; set; }
public void Load(string projectFile)
{
this.ProjectFileName = projectFile;
Project pro = GlobalLoadedProject.LoadProject(projectFile);
foreach (var item in pro.AllEvaluatedProperties)
{
//select some our interest features
switch (item.Name)
{
case "DefineConstants":
DefineConstants = item.EvaluatedValue;
break;
case "TargetFrameworkVersion":
TargetFrameworkVersion = item.EvaluatedValue;
break;
}
}
foreach (ProjectItem item in pro.AllEvaluatedItems)
{
switch (item.ItemType)
{
case "Compile":
{
string onlyFileName = Path.GetFileName(item.EvaluatedInclude);
if (onlyFileName != "AssemblyInfo.cs") //special case ***no include this file
{
allItems.Add(item);
}
}
break;
case "Reference":
break;
}
}
}
public List<string> GetAllAbsoluteFilenames()
{
List<string> absFilenames = new List<string>();
string projectDirName = Path.GetDirectoryName(ProjectFileName);
foreach (var item in allItems)
{
string filename = item.EvaluatedInclude;
if (!Path.IsPathRooted(filename))
{
absFilenames.Add(projectDirName + "\\" + filename);
}
else
{
absFilenames.Add(filename);
}
}
return absFilenames;
}
}
public class Solution
{
//from http://stackoverflow.com/questions/707107/parsing-visual-studio-solution-files
//internal class SolutionParser
//Name: Microsoft.Build.Construction.SolutionParser
//Assembly: Microsoft.Build, Version=4.0.0.0
static readonly Type s_SolutionParser;
static readonly PropertyInfo s_SolutionParser_solutionReader;
static readonly MethodInfo s_SolutionParser_parseSolution;
static readonly PropertyInfo s_SolutionParser_projects;
static Solution()
{
s_SolutionParser = Type.GetType("Microsoft.Build.Construction.SolutionParser, Microsoft.Build, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", false, false);
if (s_SolutionParser != null)
{
s_SolutionParser_solutionReader = s_SolutionParser.GetProperty("SolutionReader", BindingFlags.NonPublic | BindingFlags.Instance);
s_SolutionParser_projects = s_SolutionParser.GetProperty("Projects", BindingFlags.NonPublic | BindingFlags.Instance);
s_SolutionParser_parseSolution = s_SolutionParser.GetMethod("ParseSolution", BindingFlags.NonPublic | BindingFlags.Instance);
}
}
public List<SolutionProject> Projects { get; private set; }
public Solution(string solutionFileName)
{
if (s_SolutionParser == null)
{
throw new InvalidOperationException("Can not find type 'Microsoft.Build.Construction.SolutionParser' are you missing a assembly reference to 'Microsoft.Build.dll'?");
}
var solutionParser = s_SolutionParser.GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic)[0].Invoke(null);
using (var streamReader = new StreamReader(solutionFileName))
{
s_SolutionParser_solutionReader.SetValue(solutionParser, streamReader, null);
s_SolutionParser_parseSolution.Invoke(solutionParser, null);
}
var projects = new List<SolutionProject>();
var array = (Array)s_SolutionParser_projects.GetValue(solutionParser, null);
for (int i = 0; i < array.Length; i++)
{
projects.Add(new SolutionProject(array.GetValue(i)));
}
this.Projects = projects;
}
}
[DebuggerDisplay("{ProjectName}, {RelativePath}, {ProjectGuid}")]
public class SolutionProject
{
static readonly Type s_ProjectInSolution;
static readonly PropertyInfo s_ProjectInSolution_ProjectName;
static readonly PropertyInfo s_ProjectInSolution_RelativePath;
static readonly PropertyInfo s_ProjectInSolution_ProjectGuid;
static readonly PropertyInfo s_ProjectInSolution_ProjectType;
static SolutionProject()
{
s_ProjectInSolution = Type.GetType("Microsoft.Build.Construction.ProjectInSolution, Microsoft.Build, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", false, false);
if (s_ProjectInSolution != null)
{
s_ProjectInSolution_ProjectName = s_ProjectInSolution.GetProperty("ProjectName", BindingFlags.NonPublic | BindingFlags.Instance);
s_ProjectInSolution_RelativePath = s_ProjectInSolution.GetProperty("RelativePath", BindingFlags.NonPublic | BindingFlags.Instance);
s_ProjectInSolution_ProjectGuid = s_ProjectInSolution.GetProperty("ProjectGuid", BindingFlags.NonPublic | BindingFlags.Instance);
s_ProjectInSolution_ProjectType = s_ProjectInSolution.GetProperty("ProjectType", BindingFlags.NonPublic | BindingFlags.Instance);
}
}
public string ProjectName { get; private set; }
public string RelativePath { get; private set; }
public string ProjectGuid { get; private set; }
public string ProjectType { get; private set; }
public SolutionProject(object solutionProject)
{
this.ProjectName = s_ProjectInSolution_ProjectName.GetValue(solutionProject, null) as string;
this.RelativePath = s_ProjectInSolution_RelativePath.GetValue(solutionProject, null) as string;
this.ProjectGuid = s_ProjectInSolution_ProjectGuid.GetValue(solutionProject, null) as string;
object o = s_ProjectInSolution_ProjectType.GetValue(solutionProject, null);
this.ProjectType = s_ProjectInSolution_ProjectType.GetValue(solutionProject, null).ToString();
}
}
}