-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSolutionMaker.cs
364 lines (310 loc) · 13.9 KB
/
SolutionMaker.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
using Microsoft.Build.Evaluation;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace SolGen
{
public class SolutionMaker
{
private readonly string [] _buildConfigurations;
private const string CsProjFileExtension = ".csproj";
private const string WixProjFileExtension = ".wixproj";
private const string VcxProjFileExtension = ".vcxproj";
private const string FsProjFileExtension = ".fsproj";
private const string ProjectGuidPropertyName = "ProjectGuid";
private const string PlatformPropertyName = "Platform";
private const string ProjectReferencePropertyName = "ProjectReference";
private const string ProjectFilePropertyName = "ProjectFile";
private const string CsProjGuid = "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}";
private const string WixProjGuid = "{930C7802-8A8C-48F9-8165-68863BCCD9DD}";
private const string FolderGuid = "{2150E333-8FDC-42A3-9474-1A3956D46DE8}";
private const string VcxProjGuid = "{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}";
private const string FsProjGuid = "{F2A71F9B-5D33-465A-A702-920D77279786}";
private readonly string _rootFolder;
private readonly string _solutionFileName;
private readonly Dictionary<string, ProjectInfo> _solutionProjects;
private string _commonRoot;
public SolutionMaker(string solutionFilePath, string [] buildConfigurations)
{
if (buildConfigurations == null || buildConfigurations.Length == 0)
{
buildConfigurations = new [] { "Any CPU" };
}
_buildConfigurations = buildConfigurations;
_rootFolder = Path.GetDirectoryName(solutionFilePath);
_solutionFileName = Path.GetFileName(solutionFilePath);
_solutionProjects = new Dictionary<string, ProjectInfo>(StringComparer.CurrentCultureIgnoreCase);
_commonRoot = _rootFolder;
}
public void AddProject(string path)
{
ProcessProjectFile(path);
}
public void CreateSolution()
{
WriteSolutionFile(Path.Combine(_rootFolder, _solutionFileName));
}
private void ProcessProjectFile(string path)
{
if (_solutionProjects.ContainsKey(path))
return;
try
{
ProjectCollection collection = new ProjectCollection();
collection.RemoveGlobalProperty("Platform");
Dictionary<string, string> properties = new Dictionary<string, string>();
Project project = new Project(path, properties, null, collection, ProjectLoadSettings.IgnoreMissingImports);
ProjectInfo pinfo = new ProjectInfo
{
MsBuildProject = project,
FilePath = Path.GetDirectoryName(path),
Filename = Path.GetFileName(path)
};
foreach (ProjectProperty buildProperty in project.Properties)
{
if (buildProperty.Name == ProjectGuidPropertyName)
{
pinfo.ProjectGuid = buildProperty.EvaluatedValue;
}
if (buildProperty.Name == PlatformPropertyName)
{
pinfo.Platform = buildProperty.EvaluatedValue;
}
}
_solutionProjects[path] = pinfo;
CreatePath(pinfo);
GatherProjectReferences(pinfo);
Console.WriteLine(pinfo);
}
catch (Exception e)
{
Console.Error.WriteLine(e);
}
}
/// <summary>
/// Retrieves the information on references in the project
/// </summary>
private void GatherProjectReferences(ProjectInfo projectInfo)
{
foreach (ProjectItem buildItem in projectInfo.MsBuildProject.Items)
{
if (buildItem.ItemType == ProjectReferencePropertyName || buildItem.ItemType == ProjectFilePropertyName)
{
projectInfo.References.Add(buildItem.EvaluatedInclude);
ProcessProjectFile(Path.GetFullPath(Path.Combine(projectInfo.FilePath, buildItem.EvaluatedInclude)));
}
}
}
private void CreatePath(ProjectInfo projectInfo)
{
string projectFolderPath = !projectInfo.IsFolder ?
Path.GetDirectoryName(projectInfo.FilePath) :
projectInfo.FilePath;
if (projectFolderPath == null)
return;
if (!_solutionProjects.ContainsKey(projectFolderPath))
{
var folder = new ProjectInfo
{
Filename = Path.GetFileName(projectFolderPath),
FilePath = Path.GetDirectoryName(projectFolderPath),
IsFolder = true
};
if (string.IsNullOrEmpty(folder.Filename))
return;
if (_commonRoot.StartsWith(projectFolderPath, StringComparison.CurrentCultureIgnoreCase))
{
_commonRoot = projectFolderPath;
}
else if (!projectFolderPath.StartsWith(_commonRoot, StringComparison.CurrentCultureIgnoreCase))
{
_commonRoot = string.Empty;
}
_solutionProjects.Add(projectFolderPath, folder);
projectInfo.FolderGuid = folder.ProjectGuid;
CreatePath(folder);
}
else
{
projectInfo.FolderGuid = _solutionProjects[projectFolderPath].ProjectGuid;
}
}
private void WriteSolutionFile(string solutionFile)
{
StreamWriter writer = new StreamWriter(solutionFile);
writer.WriteLine("Microsoft Visual Studio Solution File, Format Version 11.00");
writer.WriteLine("# Visual Studio 2010");
foreach (ProjectInfo projectInfo in _solutionProjects.Values)
{
var projectInfoCopy = projectInfo.ShallowCopy();
if (!projectInfoCopy.IsFolder ||
string.Compare(Path.Combine(projectInfoCopy.FilePath, projectInfoCopy.Filename), _commonRoot, StringComparison.InvariantCultureIgnoreCase) != 0)
{
WriteProjectEntry(writer, projectInfoCopy, Path.GetDirectoryName(solutionFile));
}
}
// Project and folder relations
writer.WriteLine("Global");
writer.WriteLine("\tGlobalSection(NestedProjects) = preSolution");
const string format = "\t\t{0} = {1}";
// Folder relations
foreach (ProjectInfo folderInfo in _solutionProjects.Values)
{
if (folderInfo.ProjectGuid != null && folderInfo.FolderGuid != null && folderInfo.FilePath != _commonRoot)
{
writer.WriteLine(format, folderInfo.ProjectGuid, folderInfo.FolderGuid);
}
}
writer.WriteLine("\tEndGlobalSection");
writer.WriteLine("\tGlobalSection(SolutionConfigurationPlatforms) = preSolution");
string [] buildModes = { "Debug", "Release" };
foreach(var buildMode in buildModes)
{
foreach (var buildConfig in _buildConfigurations)
{
writer.WriteLine("\t\t{0}|{1} = {0}|{1}", buildMode, buildConfig);
}
}
writer.WriteLine("\tEndGlobalSection");
writer.WriteLine("\tGlobalSection(ProjectConfigurationPlatforms) = postSolution");
foreach (ProjectInfo projectInfo in _solutionProjects.Values.Where(prj => !prj.IsFolder))
{
foreach (var buildMode in buildModes)
{
foreach (var buildConfig in _buildConfigurations)
{
string bc = buildConfig != "Mixed Platforms" ? buildConfig : projectInfo.Platform;
if (bc == "AnyCPU")
{
bc = "Any CPU";
}
writer.WriteLine("\t\t{0}.{1}|{2}.ActiveCfg = {3}|{4}", projectInfo.ProjectGuid, buildMode, buildConfig, buildMode, bc);
writer.WriteLine("\t\t{0}.{1}|{2}.Build.0 = {3}|{4}", projectInfo.ProjectGuid, buildMode, buildConfig, buildMode, bc);
}
}
}
writer.WriteLine("\tEndGlobalSection");
writer.WriteLine("EndGlobal");
writer.Close();
}
private static string LookupGuid(string extension)
{
switch (extension.ToLower())
{
case CsProjFileExtension:
return CsProjGuid;
case WixProjFileExtension:
return WixProjGuid;
case VcxProjFileExtension:
return VcxProjGuid;
case FsProjFileExtension:
return FsProjGuid;
default:
return null;
}
}
private static void WriteProjectEntry(TextWriter writer, ProjectInfo projectInfo, string rootFolder)
{
string projectPath;
string guid;
if (projectInfo.IsFolder == false)
{
string projectDir = Path.GetDirectoryName(projectInfo.FilePath) ?? string.Empty;
if (projectDir.StartsWith(rootFolder, StringComparison.InvariantCultureIgnoreCase))
{
projectPath = Path.Combine(projectInfo.FilePath, projectInfo.Filename).Substring(rootFolder.Length + 1);
}
else
{
projectPath = GetRelativePath(rootFolder, Path.Combine(projectInfo.FilePath, projectInfo.Filename));
}
guid = LookupGuid(Path.GetExtension(projectInfo.Filename));
}
else
{
projectPath = projectInfo.ProjectGuid;
guid = FolderGuid;
}
if (guid != null)
{
string format = "Project('{0}') = '{1}', '{2}', '{3}'".Replace('\'', '"');
writer.WriteLine(format, guid, projectInfo.Filename, projectPath, projectInfo.ProjectGuid);
writer.WriteLine("EndProject");
}
}
private static string GetRelativePath(string fromPath, string toPath)
{
string[] fromDirectories = fromPath.Split(Path.DirectorySeparatorChar);
string[] toDirectories = toPath.Split(Path.DirectorySeparatorChar);
// Get the shortest of the two paths
int length = fromDirectories.Length < toDirectories.Length
? fromDirectories.Length
: toDirectories.Length;
int lastCommonRoot = -1;
int index;
// Find common root
for (index = 0; index < length; index++)
{
if (fromDirectories[index].Equals(toDirectories[index], StringComparison.InvariantCultureIgnoreCase))
{
lastCommonRoot = index;
}
else
{
break;
}
}
// If we didn't find a common prefix then abandon
if (lastCommonRoot == -1)
{
return null;
}
// Add the required number of "..\" to move up to common root level
StringBuilder relativePath = new StringBuilder();
for (index = lastCommonRoot + 1; index < fromDirectories.Length; index++)
{
relativePath.Append(".." + Path.DirectorySeparatorChar);
}
// Add on the folders to reach the destination
for (index = lastCommonRoot + 1; index < toDirectories.Length - 1; index++)
{
relativePath.Append(toDirectories[index] + Path.DirectorySeparatorChar);
}
relativePath.Append(toDirectories[toDirectories.Length - 1]);
return relativePath.ToString();
}
/// <summary>
/// Represents a project reference or loaded project.
/// </summary>
private class ProjectInfo
{
public ProjectInfo()
{
ProjectGuid = Guid.NewGuid().ToString("B");
IsFolder = false;
}
public string ProjectGuid = null;
public string Filename = null;
public string FilePath { get; set; }
public string FolderGuid = null;
public bool IsFolder { get; set; }
public string Platform { get; set; }
// list of assemblynames
public readonly List<string> References = new List<string>();
public Project MsBuildProject;
public ProjectInfo ShallowCopy()
{
return (ProjectInfo)this.MemberwiseClone();
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat("'{0}', ", Filename);
sb.AppendFormat("'{0}', ", FilePath);
return sb.ToString();
}
}
}
}