2 // SolutionParser.cs: Generates a project file from a solution file.
5 // Jonathan Chambers (joncham@gmail.com)
6 // Ankit Jain <jankit@novell.com>
7 // Lluis Sanchez Gual <lluis@novell.com>
9 // (C) 2009 Jonathan Chambers
10 // Copyright 2008, 2009 Novell, Inc (http://www.novell.com)
12 // Permission is hereby granted, free of charge, to any person obtaining
13 // a copy of this software and associated documentation files (the
14 // "Software"), to deal in the Software without restriction, including
15 // without limitation the rights to use, copy, modify, merge, publish,
16 // distribute, sublicense, and/or sell copies of the Software, and to
17 // permit persons to whom the Software is furnished to do so, subject to
18 // the following conditions:
20 // The above copyright notice and this permission notice shall be
21 // included in all copies or substantial portions of the Software.
23 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
24 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
25 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
26 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
27 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
28 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
29 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
32 using System.Collections.Generic;
35 using System.Text.RegularExpressions;
37 using Microsoft.Build.Evaluation;
38 using Microsoft.Build.Execution;
39 using Microsoft.Build.Construction;
40 using Microsoft.Build.Exceptions;
43 namespace Mono.XBuild.CommandLine {
46 public string FileName;
49 public ProjectInfo (string name, string fileName)
55 public Dictionary<TargetInfo, TargetInfo> TargetMap = new Dictionary<TargetInfo, TargetInfo> ();
56 public Dictionary<Guid, ProjectInfo> Dependencies = new Dictionary<Guid, ProjectInfo> ();
57 public Dictionary<string, ProjectSection> ProjectSections = new Dictionary<string, ProjectSection> ();
58 public List<string> AspNetConfigurations = new List<string> ();
61 class ProjectSection {
63 public Dictionary<string, string> Properties = new Dictionary<string, string> ();
65 public ProjectSection (string name)
72 public string Configuration;
73 public string Platform;
76 public TargetInfo (string configuration, string platform)
77 : this (configuration, platform, false)
81 public TargetInfo (string configuration, string platform, bool build)
83 Configuration = configuration;
90 internal delegate void RaiseWarningHandler (int errorNumber, string message);
92 class SolutionParser {
93 static string[] buildTargets = new string[] { "Build", "Clean", "Rebuild", "Publish" };
95 static string guidExpression = "{[A-Fa-f0-9]{8}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{12}}";
97 static Regex slnVersionRegex = new Regex (@"Microsoft Visual Studio Solution File, Format Version (\d?\d.\d\d)");
98 static Regex projectRegex = new Regex ("Project\\(\"(" + guidExpression + ")\"\\) = \"(.*?)\", \"(.*?)\", \"(" + guidExpression + ")\"(\\s*?)((\\s*?)ProjectSection\\((.*?)\\) = (.*?)EndProjectSection(\\s*?))*(\\s*?)(EndProject)?", RegexOptions.Singleline);
99 static Regex projectDependenciesRegex = new Regex ("ProjectSection\\((.*?)\\) = \\w*(.*?)EndProjectSection", RegexOptions.Singleline);
100 static Regex projectDependencyRegex = new Regex ("\\s*(" + guidExpression + ") = (" + guidExpression + ")");
101 static Regex projectSectionPropertiesRegex = new Regex ("\\s*(?<name>.*) = \"(?<value>.*)\"");
103 static Regex globalRegex = new Regex ("Global(.*)EndGlobal", RegexOptions.Singleline);
104 static Regex globalSectionRegex = new Regex ("GlobalSection\\((.*?)\\) = \\w*(.*?)EndGlobalSection", RegexOptions.Singleline);
106 static Regex solutionConfigurationRegex = new Regex ("\\s*(.*?)\\|(.*?) = (.*?)\\|(.+)");
107 static Regex projectConfigurationActiveCfgRegex = new Regex ("\\s*(" + guidExpression + ")\\.(.+?)\\|(.+?)\\.ActiveCfg = (.+?)\\|(.+)");
108 static Regex projectConfigurationBuildRegex = new Regex ("\\s*(" + guidExpression + ")\\.(.*?)\\|(.*?)\\.Build\\.0 = (.*?)\\|(.+)");
110 static string solutionFolderGuid = "{2150E333-8FDC-42A3-9474-1A3956D46DE8}";
111 static string vcprojGuid = "{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}";
112 static string websiteProjectGuid = "{E24C65DC-7377-472B-9ABA-BC803B73C61A}";
114 RaiseWarningHandler RaiseWarning;
116 public void ParseSolution (string file, ProjectCollection projects, ProjectRootElement p, RaiseWarningHandler RaiseWarning)
118 this.RaiseWarning = RaiseWarning;
119 EmitBeforeImports (p, file);
121 AddGeneralSettings (file, p);
123 StreamReader reader = new StreamReader (file);
124 string slnVersion = GetSlnFileVersion (reader);
125 if (slnVersion == "12.00")
127 projects.DefaultToolsVersion = "12.0";
129 projects.DefaultToolsVersion = "4.0";
131 else if (slnVersion == "11.00")
132 projects.DefaultToolsVersion = "4.0";
133 else if (slnVersion == "10.00")
134 projects.DefaultToolsVersion = "3.5";
136 projects.DefaultToolsVersion = "2.0";
138 string line = reader.ReadToEnd ();
139 line = line.Replace ("\r\n", "\n");
140 string solutionDir = Path.GetDirectoryName (file);
142 List<TargetInfo> solutionTargets = new List<TargetInfo> ();
143 Dictionary<Guid, ProjectInfo> projectInfos = new Dictionary<Guid, ProjectInfo> ();
144 Dictionary<Guid, ProjectInfo> websiteProjectInfos = new Dictionary<Guid, ProjectInfo> ();
145 List<ProjectInfo>[] infosByLevel = null;
146 Dictionary<Guid, ProjectInfo> unsupportedProjectInfos = new Dictionary<Guid, ProjectInfo> ();
148 Match m = projectRegex.Match (line);
150 ProjectInfo projectInfo = new ProjectInfo (m.Groups[2].Value,
151 Path.GetFullPath (Path.Combine (solutionDir,
152 m.Groups [3].Value.Replace ('\\', Path.DirectorySeparatorChar))));
153 if (String.Compare (m.Groups [1].Value, solutionFolderGuid,
154 StringComparison.InvariantCultureIgnoreCase) == 0) {
155 // Ignore solution folders
160 projectInfo.Guid = new Guid (m.Groups [4].Value);
162 if (String.Compare (m.Groups [1].Value, vcprojGuid,
163 StringComparison.InvariantCultureIgnoreCase) == 0) {
165 RaiseWarning (0, string.Format("Ignoring vcproj '{0}'.", projectInfo.Name));
167 unsupportedProjectInfos [projectInfo.Guid] = projectInfo;
172 if (String.Compare (m.Groups [1].Value, websiteProjectGuid,
173 StringComparison.InvariantCultureIgnoreCase) == 0)
174 websiteProjectInfos.Add (new Guid (m.Groups[4].Value), projectInfo);
176 projectInfos.Add (projectInfo.Guid, projectInfo);
178 Match projectSectionMatch = projectDependenciesRegex.Match (m.Groups[6].Value);
179 while (projectSectionMatch.Success) {
180 string section_name = projectSectionMatch.Groups [1].Value;
181 if (String.Compare (section_name, "ProjectDependencies") == 0) {
182 Match projectDependencyMatch = projectDependencyRegex.Match (projectSectionMatch.Value);
183 while (projectDependencyMatch.Success) {
184 // we might not have projectInfo available right now, so
185 // set it to null, and fill it in later
186 projectInfo.Dependencies [new Guid (projectDependencyMatch.Groups[1].Value)] = null;
187 projectDependencyMatch = projectDependencyMatch.NextMatch ();
190 ProjectSection section = new ProjectSection (section_name);
191 Match propertiesMatch = projectSectionPropertiesRegex.Match (
192 projectSectionMatch.Groups [2].Value);
193 while (propertiesMatch.Success) {
194 section.Properties [propertiesMatch.Groups ["name"].Value] =
195 propertiesMatch.Groups ["value"].Value;
197 propertiesMatch = propertiesMatch.NextMatch ();
200 projectInfo.ProjectSections [section_name] = section;
202 projectSectionMatch = projectSectionMatch.NextMatch ();
207 foreach (ProjectInfo projectInfo in projectInfos.Values) {
208 string filename = projectInfo.FileName;
209 string projectDir = Path.GetDirectoryName (filename);
211 if (!File.Exists (filename)) {
212 RaiseWarning (0, String.Format ("Project file {0} referenced in the solution file, " +
213 " not found. Ignoring.", filename));
217 Project currentProject;
219 using (var xmlReader = XmlReader.Create (filename)) {
220 var root = ProjectRootElement.Create (xmlReader, projects);
221 root.FullPath = filename;
222 currentProject = new Project (root, null, null, projects, ProjectLoadSettings.IgnoreMissingImports);
224 } catch (InvalidProjectFileException e) {
225 RaiseWarning (0, e.Message);
229 foreach (var bi in currentProject.GetItems ("ProjectReference")) {
230 ProjectInfo info = null;
231 string projectReferenceGuid = bi.GetMetadataValue ("Project");
232 bool hasGuid = !String.IsNullOrEmpty (projectReferenceGuid);
234 // try to resolve the ProjectReference by GUID
235 // and fallback to project filename
238 Guid guid = new Guid (projectReferenceGuid);
239 projectInfos.TryGetValue (guid, out info);
240 if (info == null && unsupportedProjectInfos.TryGetValue (guid, out info)) {
241 RaiseWarning (0, String.Format (
242 "{0}: ProjectReference '{1}' is of an unsupported type. Ignoring.",
243 filename, bi.EvaluatedInclude));
248 if (info == null || !hasGuid) {
249 // Project not found by guid or guid not available
250 // Try to find by project file
252 string fullpath = Path.GetFullPath (Path.Combine (projectDir, bi.EvaluatedInclude.Replace ('\\', Path.DirectorySeparatorChar)));
253 info = projectInfos.Values.FirstOrDefault (pi => pi.FileName == fullpath);
256 if (unsupportedProjectInfos.Values.Any (pi => pi.FileName == fullpath))
257 RaiseWarning (0, String.Format (
258 "{0}: ProjectReference '{1}' is of an unsupported type. Ignoring.",
259 filename, bi.EvaluatedInclude));
261 RaiseWarning (0, String.Format (
262 "{0}: ProjectReference '{1}' not found, neither by guid '{2}' nor by project file name '{3}'.",
263 filename, bi.EvaluatedInclude, projectReferenceGuid.Replace ("{", "").Replace ("}", ""), fullpath));
269 projectInfo.Dependencies [info.Guid] = info;
273 // fill in the project info for deps found in the .sln file
274 foreach (ProjectInfo projectInfo in projectInfos.Values) {
275 List<Guid> missingInfos = new List<Guid> ();
276 foreach (KeyValuePair<Guid, ProjectInfo> dependency in projectInfo.Dependencies) {
277 if (dependency.Value == null)
278 missingInfos.Add (dependency.Key);
281 foreach (Guid guid in missingInfos) {
283 if (projectInfos.TryGetValue (guid, out info))
284 projectInfo.Dependencies [guid] = info;
286 projectInfo.Dependencies.Remove (guid);
290 Match globalMatch = globalRegex.Match (line);
291 Match globalSectionMatch = globalSectionRegex.Match (globalMatch.Groups[1].Value);
292 while (globalSectionMatch.Success) {
293 string sectionType = globalSectionMatch.Groups[1].Value;
294 switch (sectionType) {
295 case "SolutionConfigurationPlatforms":
296 ParseSolutionConfigurationPlatforms (globalSectionMatch.Groups[2].Value, solutionTargets);
298 case "ProjectConfigurationPlatforms":
299 ParseProjectConfigurationPlatforms (globalSectionMatch.Groups[2].Value,
300 projectInfos, websiteProjectInfos);
302 case "SolutionProperties":
303 ParseSolutionProperties (globalSectionMatch.Groups[2].Value);
305 case "NestedProjects":
307 case "MonoDevelopProperties":
310 RaiseWarning (0, string.Format("Don't know how to handle GlobalSection {0}, Ignoring.", sectionType));
313 globalSectionMatch = globalSectionMatch.NextMatch ();
316 int num_levels = AddBuildLevels (p, solutionTargets, projectInfos, ref infosByLevel);
318 AddCurrentSolutionConfigurationContents (p, solutionTargets, projectInfos, websiteProjectInfos);
319 AddProjectReferences (p, projectInfos);
320 AddWebsiteProperties (p, websiteProjectInfos, projectInfos);
321 AddValidateSolutionConfiguration (p);
323 EmitAfterImports (p, file);
325 AddGetFrameworkPathTarget (p);
326 AddWebsiteTargets (p, websiteProjectInfos, projectInfos, infosByLevel, solutionTargets);
327 AddProjectTargets (p, solutionTargets, projectInfos);
328 AddSolutionTargets (p, num_levels, websiteProjectInfos.Values);
331 string GetSlnFileVersion (StreamReader reader)
333 string strInput = null;
336 strInput = reader.ReadLine();
337 if (strInput == null)
340 match = slnVersionRegex.Match(strInput);
341 if (!match.Success) {
342 strInput = reader.ReadLine();
343 if (strInput == null)
345 match = slnVersionRegex.Match (strInput);
349 return match.Groups[1].Value;
354 void EmitBeforeImports (ProjectRootElement p, string file)
357 p.AddImportGroup ().AddImport ("$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\SolutionFile\\ImportBefore\\*").Condition =
358 "'$(ImportByWildcardBeforeSolution)' != 'false' and " +
359 "Exists('$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\SolutionFile\\ImportBefore')";
362 string before_filename = Path.Combine (Path.GetDirectoryName (file), "before." + Path.GetFileName (file) + ".targets");
363 p.AddImportGroup ().AddImport (before_filename).Condition = String.Format ("Exists ('{0}')", before_filename);
366 void EmitAfterImports (ProjectRootElement p, string file)
369 p.AddImportGroup ().AddImport ("$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\SolutionFile\\ImportAfter\\*").Condition =
370 "'$(ImportByWildcardAfterSolution)' != 'false' and " +
371 "Exists('$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\SolutionFile\\ImportAfter')";
374 string after_filename = Path.Combine (Path.GetDirectoryName (file), "after." + Path.GetFileName (file) + ".targets");
375 p.AddImportGroup ().AddImport (after_filename).Condition = String.Format ("Exists ('{0}')", after_filename);
378 void AddGeneralSettings (string solutionFile, ProjectRootElement p)
380 p.DefaultTargets = "Build";
381 p.InitialTargets = "ValidateSolutionConfiguration";
382 //p.AddUsingTask ("CreateTemporaryVCProject", null, "Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
383 //p.AddUsingTask ("ResolveVCProjectOutput", null, "Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
385 string solutionFilePath = Path.GetFullPath (solutionFile);
386 var solutionPropertyGroup = p.CreatePropertyGroupElement ();
387 //solutionPropertyGroup.ChildrenReversed = true;
388 solutionPropertyGroup.AddProperty ("SolutionDir", Path.GetDirectoryName (solutionFilePath) + Path.DirectorySeparatorChar);
389 solutionPropertyGroup.AddProperty ("SolutionExt", Path.GetExtension (solutionFile));
390 solutionPropertyGroup.AddProperty ("SolutionFileName", Path.GetFileName (solutionFile));
391 solutionPropertyGroup.AddProperty ("SolutionName", Path.GetFileNameWithoutExtension (solutionFile));
392 solutionPropertyGroup.AddProperty ("SolutionPath", solutionFilePath);
395 void ParseSolutionConfigurationPlatforms (string section, List<TargetInfo> solutionTargets)
397 Match solutionConfigurationPlatform = solutionConfigurationRegex.Match (section);
398 while (solutionConfigurationPlatform.Success) {
399 string solutionConfiguration = solutionConfigurationPlatform.Groups[1].Value;
400 string solutionPlatform = solutionConfigurationPlatform.Groups[2].Value;
401 solutionTargets.Add (new TargetInfo (solutionConfiguration, solutionPlatform));
402 solutionConfigurationPlatform = solutionConfigurationPlatform.NextMatch ();
406 // ignores the website projects, in the websiteProjectInfos
407 void ParseProjectConfigurationPlatforms (string section, Dictionary<Guid, ProjectInfo> projectInfos,
408 Dictionary<Guid, ProjectInfo> websiteProjectInfos)
410 List<Guid> missingGuids = new List<Guid> ();
411 Match projectConfigurationPlatform = projectConfigurationActiveCfgRegex.Match (section);
412 while (projectConfigurationPlatform.Success) {
413 Guid guid = new Guid (projectConfigurationPlatform.Groups[1].Value);
414 ProjectInfo projectInfo;
415 if (!projectInfos.TryGetValue (guid, out projectInfo)) {
416 if (!missingGuids.Contains (guid)) {
417 if (!websiteProjectInfos.ContainsKey (guid))
418 // ignore website projects
419 RaiseWarning (0, string.Format("Failed to find project {0}", guid));
420 missingGuids.Add (guid);
422 projectConfigurationPlatform = projectConfigurationPlatform.NextMatch ();
425 string solConf = projectConfigurationPlatform.Groups[2].Value;
426 string solPlat = projectConfigurationPlatform.Groups[3].Value;
427 string projConf = projectConfigurationPlatform.Groups[4].Value;
428 string projPlat = projectConfigurationPlatform.Groups[5].Value;
429 // hack, what are they doing here?
430 if (projPlat == "Any CPU")
432 projectInfo.TargetMap.Add (new TargetInfo (solConf, solPlat), new TargetInfo (projConf, projPlat));
433 projectConfigurationPlatform = projectConfigurationPlatform.NextMatch ();
435 Match projectConfigurationPlatformBuild = projectConfigurationBuildRegex.Match (section);
436 while (projectConfigurationPlatformBuild.Success) {
437 Guid guid = new Guid (projectConfigurationPlatformBuild.Groups[1].Value);
438 ProjectInfo projectInfo;
439 if (!projectInfos.TryGetValue (guid, out projectInfo)) {
440 if (!missingGuids.Contains (guid)) {
441 RaiseWarning (0, string.Format("Failed to find project {0}", guid));
442 missingGuids.Add (guid);
444 projectConfigurationPlatformBuild = projectConfigurationPlatformBuild.NextMatch ();
447 string solConf = projectConfigurationPlatformBuild.Groups[2].Value;
448 string solPlat = projectConfigurationPlatformBuild.Groups[3].Value;
449 string projConf = projectConfigurationPlatformBuild.Groups[4].Value;
450 string projPlat = projectConfigurationPlatformBuild.Groups[5].Value;
451 // hack, what are they doing here?
452 if (projPlat == "Any CPU")
454 projectInfo.TargetMap[new TargetInfo (solConf, solPlat)] = new TargetInfo (projConf, projPlat, true);
455 projectConfigurationPlatformBuild = projectConfigurationPlatformBuild.NextMatch ();
459 void ParseSolutionProperties (string section)
463 void AddCurrentSolutionConfigurationContents (ProjectRootElement p, List<TargetInfo> solutionTargets,
464 Dictionary<Guid, ProjectInfo> projectInfos,
465 Dictionary<Guid, ProjectInfo> websiteProjectInfos)
467 TargetInfo default_target_info = new TargetInfo ("Debug", "Any CPU");
468 if (solutionTargets.Count > 0) {
470 foreach (TargetInfo tinfo in solutionTargets) {
471 if (String.Compare (tinfo.Platform, "Mixed Platforms") == 0) {
472 default_target_info = tinfo;
479 default_target_info = solutionTargets [0];
482 AddDefaultSolutionConfiguration (p, default_target_info);
484 foreach (TargetInfo solutionTarget in solutionTargets) {
485 var platformPropertyGroup = p.AddPropertyGroup ();
486 platformPropertyGroup.Condition = string.Format (
487 " ('$(Configuration)' == '{0}') and ('$(Platform)' == '{1}') ",
488 solutionTarget.Configuration,
489 solutionTarget.Platform
492 StringBuilder solutionConfigurationContents = new StringBuilder ();
493 solutionConfigurationContents.Append ("<SolutionConfiguration xmlns=\"\">");
494 foreach (KeyValuePair<Guid, ProjectInfo> projectInfo in projectInfos) {
495 AddProjectConfigurationItems (projectInfo.Key, projectInfo.Value, solutionTarget, solutionConfigurationContents);
497 solutionConfigurationContents.Append ("</SolutionConfiguration>");
499 platformPropertyGroup.AddProperty ("CurrentSolutionConfigurationContents",
500 solutionConfigurationContents.ToString ());
504 void AddProjectReferences (ProjectRootElement p, Dictionary<Guid, ProjectInfo> projectInfos)
506 var big = p.AddItemGroup ();
507 foreach (KeyValuePair<Guid, ProjectInfo> pair in projectInfos)
508 big.AddItem ("ProjectReference", pair.Value.FileName);
511 void AddProjectConfigurationItems (Guid guid, ProjectInfo projectInfo, TargetInfo solutionTarget,
512 StringBuilder solutionConfigurationContents)
514 foreach (KeyValuePair<TargetInfo, TargetInfo> targetInfo in projectInfo.TargetMap) {
515 if (solutionTarget.Configuration == targetInfo.Key.Configuration &&
516 solutionTarget.Platform == targetInfo.Key.Platform) {
517 solutionConfigurationContents.AppendFormat (
518 "<ProjectConfiguration Project=\"{0}\">{1}|{2}</ProjectConfiguration>",
519 guid.ToString ("B").ToUpper (), targetInfo.Value.Configuration, targetInfo.Value.Platform);
524 void AddDefaultSolutionConfiguration (ProjectRootElement p, TargetInfo target)
526 var configurationPropertyGroup = p.AddPropertyGroup ();
527 //configurationPropertyGroup.PropertiesReversed = true;
528 configurationPropertyGroup.Condition = " '$(Configuration)' == '' ";
529 configurationPropertyGroup.AddProperty ("Configuration", target.Configuration);
531 var platformPropertyGroup = p.AddPropertyGroup ();
532 //platformPropertyGroup.PropertiesReversed = true;
533 platformPropertyGroup.Condition = " '$(Platform)' == '' ";
534 platformPropertyGroup.AddProperty ("Platform", target.Platform);
536 // emit default for AspNetConfiguration also
537 var aspNetConfigurationPropertyGroup = p.AddPropertyGroup ();
538 //aspNetConfigurationPropertyGroup.PropertiesReversed = true;
539 aspNetConfigurationPropertyGroup.Condition = " ('$(AspNetConfiguration)' == '') ";
540 aspNetConfigurationPropertyGroup.AddProperty ("AspNetConfiguration", "$(Configuration)");
543 void AddWarningForMissingProjectConfiguration (ProjectTargetElement target, string slnConfig, string slnPlatform, string projectName)
545 var task = target.AddTask ("Warning");
546 task.SetParameter ("Text",
547 String.Format ("The project configuration for project '{0}' corresponding " +
548 "to the solution configuration '{1}|{2}' was not found in the solution file.",
549 projectName, slnConfig, slnPlatform));
550 task.Condition = String.Format ("('$(Configuration)' == '{0}') and ('$(Platform)' == '{1}')",
551 slnConfig, slnPlatform);
555 // Website project methods
557 void AddWebsiteProperties (ProjectRootElement p, Dictionary<Guid, ProjectInfo> websiteProjectInfos,
558 Dictionary<Guid, ProjectInfo> projectInfos)
560 var propertyGroupByConfig = new Dictionary<string, ProjectPropertyGroupElement> ();
561 foreach (KeyValuePair<Guid, ProjectInfo> infoPair in websiteProjectInfos) {
562 ProjectInfo info = infoPair.Value;
563 string projectGuid = infoPair.Key.ToString ();
565 ProjectSection section;
566 if (!info.ProjectSections.TryGetValue ("WebsiteProperties", out section)) {
567 RaiseWarning (0, String.Format ("Website project '{0}' does not have the required project section: WebsiteProperties. Ignoring project.", info.Name));
571 //parse project references
572 string [] ref_guids = null;
574 if (section.Properties.TryGetValue ("ProjectReferences", out references)) {
575 ref_guids = references.Split (new char [] {';'}, StringSplitOptions.RemoveEmptyEntries);
576 for (int i = 0; i < ref_guids.Length; i ++) {
578 ref_guids [i] = ref_guids [i].Split ('|') [0];
580 Guid r_guid = new Guid (ref_guids [i]);
581 ProjectInfo ref_info;
582 if (projectInfos.TryGetValue (r_guid, out ref_info))
583 // ignore if not found
584 info.Dependencies [r_guid] = ref_info;
588 foreach (KeyValuePair<string, string> pair in section.Properties) {
589 //looking for -- ConfigName.AspNetCompiler.PropName
590 string [] parts = pair.Key.Split ('.');
591 if (parts.Length != 3 || String.Compare (parts [1], "AspNetCompiler") != 0)
594 string config = parts [0];
595 string propertyName = parts [2];
597 ProjectPropertyGroupElement bpg;
598 if (!propertyGroupByConfig.TryGetValue (config, out bpg)) {
599 bpg = p.AddPropertyGroup ();
600 //bpg.PropertiesReversed = true;
601 bpg.Condition = String.Format (" '$(AspNetConfiguration)' == '{0}' ", config);
602 propertyGroupByConfig [config] = bpg;
605 bpg.AddProperty (String.Format ("Project_{0}_AspNet{1}", projectGuid, propertyName),
608 if (!info.AspNetConfigurations.Contains (config))
609 info.AspNetConfigurations.Add (config);
614 // For WebSite projects
615 // The main "Build" target:
616 // 1. builds all non-website projects
617 // 2. calls target for website project
618 // - gets target path for the referenced projects
619 // - Resolves dependencies, satellites etc for the
620 // referenced project assemblies, and copies them
622 void AddWebsiteTargets (ProjectRootElement p, Dictionary<Guid, ProjectInfo> websiteProjectInfos,
623 Dictionary<Guid, ProjectInfo> projectInfos, List<ProjectInfo>[] infosByLevel,
624 List<TargetInfo> solutionTargets)
626 foreach (ProjectInfo w_info in websiteProjectInfos.Values) {
627 // gets a linear list of dependencies
628 List<ProjectInfo> depInfos = new List<ProjectInfo> ();
629 foreach (List<ProjectInfo> pinfos in infosByLevel) {
630 foreach (ProjectInfo pinfo in pinfos)
631 if (w_info.Dependencies.ContainsKey (pinfo.Guid))
632 depInfos.Add (pinfo);
635 foreach (string buildTarget in new string [] {"Build", "Rebuild"})
636 AddWebsiteTarget (p, w_info, projectInfos, depInfos, solutionTargets, buildTarget);
638 // clean/publish are not supported for website projects
639 foreach (string buildTarget in new string [] {"Clean", "Publish"})
640 AddWebsiteUnsupportedTarget (p, w_info, depInfos, buildTarget);
644 void AddWebsiteTarget (ProjectRootElement p, ProjectInfo webProjectInfo,
645 Dictionary<Guid, ProjectInfo> projectInfos, List<ProjectInfo> depInfos,
646 List<TargetInfo> solutionTargets, string buildTarget)
648 string w_guid = webProjectInfo.Guid.ToString ().ToUpper ();
650 var target = p.AddTarget (GetTargetNameForProject (webProjectInfo.Name, buildTarget));
651 target.Condition = "'$(CurrentSolutionConfigurationContents)' != ''";
652 target.DependsOnTargets = GetWebsiteDependsOnTarget (depInfos, buildTarget);
654 // this item collects all the references
655 string final_ref_item = String.Format ("Project_{0}_References{1}", w_guid,
656 buildTarget != "Build" ? "_" + buildTarget : String.Empty);
658 foreach (TargetInfo targetInfo in solutionTargets) {
660 foreach (ProjectInfo depInfo in depInfos) {
661 TargetInfo projectTargetInfo;
662 if (!depInfo.TargetMap.TryGetValue (targetInfo, out projectTargetInfo))
663 // Ignore, no config, so no target path
666 // GetTargetPath from the referenced project
667 AddWebsiteMSBuildTaskForReference (target, depInfo, projectTargetInfo, targetInfo,
668 final_ref_item, ref_num);
673 // resolve the references
674 AddWebsiteResolveAndCopyReferencesTasks (target, webProjectInfo, final_ref_item, w_guid);
677 // emits the MSBuild task to GetTargetPath for the referenced project
678 void AddWebsiteMSBuildTaskForReference (ProjectTargetElement target, ProjectInfo depInfo, TargetInfo projectTargetInfo,
679 TargetInfo solutionTargetInfo, string final_ref_item, int ref_num)
681 var task = target.AddTask ("MSBuild");
682 task.SetParameter ("Projects", depInfo.FileName);
683 task.SetParameter ("Targets", "GetTargetPath");
685 task.SetParameter ("Properties", string.Format ("Configuration={0}; Platform={1}; BuildingSolutionFile=true; CurrentSolutionConfigurationContents=$(CurrentSolutionConfigurationContents); SolutionDir=$(SolutionDir); SolutionExt=$(SolutionExt); SolutionFileName=$(SolutionFileName); SolutionName=$(SolutionName); SolutionPath=$(SolutionPath)", projectTargetInfo.Configuration, projectTargetInfo.Platform));
686 task.Condition = string.Format (" ('$(Configuration)' == '{0}') and ('$(Platform)' == '{1}') ", solutionTargetInfo.Configuration, solutionTargetInfo.Platform);
688 string ref_item = String.Format ("{0}_{1}",
689 final_ref_item, ref_num);
691 task.AddOutputItem ("TargetOutputs", ref_item);
693 task = target.AddTask ("CreateItem");
694 task.SetParameter ("Include", String.Format ("@({0})", ref_item));
695 task.SetParameter ("AdditionalMetadata", String.Format ("Guid={{{0}}}",
696 depInfo.Guid.ToString ().ToUpper ()));
697 task.AddOutputItem ("Include", final_ref_item);
700 void AddWebsiteResolveAndCopyReferencesTasks (ProjectTargetElement target, ProjectInfo webProjectInfo,
701 string final_ref_item, string w_guid)
703 var task = target.AddTask ("ResolveAssemblyReference");
704 task.SetParameter ("Assemblies", String.Format ("@({0}->'%(FullPath)')", final_ref_item));
705 task.SetParameter ("TargetFrameworkDirectories", "$(TargetFrameworkPath)");
706 task.SetParameter ("SearchPaths", "{RawFileName};{TargetFrameworkDirectory};{GAC}");
707 task.SetParameter ("FindDependencies", "true");
708 task.SetParameter ("FindSatellites", "true");
709 task.SetParameter ("FindRelatedFiles", "true");
710 task.Condition = String.Format ("Exists ('%({0}.Identity)')", final_ref_item);
712 string copylocal_item = String.Format ("{0}_CopyLocalFiles", final_ref_item);
713 task.AddOutputItem ("CopyLocalFiles", copylocal_item);
715 // Copy the references
716 task = target.AddTask ("Copy");
717 task.SetParameter ("SourceFiles", String.Format ("@({0})", copylocal_item));
718 task.SetParameter ("DestinationFiles", String.Format (
719 "@({0}->'$(Project_{1}_AspNetPhysicalPath)\\Bin\\%(DestinationSubDirectory)%(Filename)%(Extension)')",
720 copylocal_item, w_guid));
722 // AspNetConfiguration, is config for the website project, useful
723 // for overriding from command line
724 StringBuilder cond = new StringBuilder ();
725 foreach (string config in webProjectInfo.AspNetConfigurations) {
727 cond.Append (" or ");
728 cond.AppendFormat (" ('$(AspNetConfiguration)' == '{0}') ", config);
730 task.Condition = cond.ToString ();
732 task = target.AddTask ("Message");
733 cond = new StringBuilder ();
734 foreach (string config in webProjectInfo.AspNetConfigurations) {
736 cond.Append (" and ");
737 cond.AppendFormat (" ('$(AspNetConfiguration)' != '{0}') ", config);
739 task.Condition = cond.ToString ();
740 task.SetParameter ("Text", "Skipping as the '$(AspNetConfiguration)' configuration is " +
741 "not supported by this website project.");
744 void AddWebsiteUnsupportedTarget (ProjectRootElement p, ProjectInfo webProjectInfo, List<ProjectInfo> depInfos,
747 var target = p.AddTarget (GetTargetNameForProject (webProjectInfo.Name, buildTarget));
748 target.DependsOnTargets = GetWebsiteDependsOnTarget (depInfos, buildTarget);
750 var task = target.AddTask ("Message");
751 task.SetParameter ("Text", String.Format (
752 "Target '{0}' not support for website projects", buildTarget));
755 string GetWebsiteDependsOnTarget (List<ProjectInfo> depInfos, string buildTarget)
757 StringBuilder deps = new StringBuilder ();
758 foreach (ProjectInfo pinfo in depInfos) {
761 deps.Append (GetTargetNameForProject (pinfo.Name, buildTarget));
763 deps.Append (";GetFrameworkPath");
764 return deps.ToString ();
767 void AddGetFrameworkPathTarget (ProjectRootElement p)
769 var t = p.AddTarget ("GetFrameworkPath");
770 var task = t.AddTask ("GetFrameworkPath");
771 task.AddOutputProperty ("Path", "TargetFrameworkPath");
774 void AddValidateSolutionConfiguration (ProjectRootElement p)
776 var t = p.AddTarget ("ValidateSolutionConfiguration");
777 var task = t.AddTask ("Warning");
778 task.SetParameter ("Text", "On windows, an environment variable 'Platform' is set to MCD sometimes, and this overrides the Platform property" +
779 " for Mono msbuild, which could be an invalid Platform for this solution file. And so you are getting the following error." +
780 " You could override it by either setting the environment variable to nothing, as\n" +
782 "Or explicity specify its value on the command line, as\n" +
783 " msbuild Foo.sln /p:Platform=Release");
784 task.Condition = "('$(CurrentSolutionConfigurationContents)' == '') and ('$(SkipInvalidConfigurations)' != 'true')" +
785 " and '$(Platform)' == 'MCD' and '$(OS)' == 'Windows_NT'";
787 task = t.AddTask ("Error");
788 task.SetParameter ("Text", "Invalid solution configuration and platform: \"$(Configuration)|$(Platform)\".");
789 task.Condition = "('$(CurrentSolutionConfigurationContents)' == '') and ('$(SkipInvalidConfigurations)' != 'true')";
790 task = t.AddTask ("Warning");
791 task.SetParameter ("Text", "Invalid solution configuration and platform: \"$(Configuration)|$(Platform)\".");
792 task.Condition = "('$(CurrentSolutionConfigurationContents)' == '') and ('$(SkipInvalidConfigurations)' == 'true')";
793 task = t.AddTask ("Message");
794 task.SetParameter ("Text", "Building solution configuration \"$(Configuration)|$(Platform)\".");
795 task.Condition = "'$(CurrentSolutionConfigurationContents)' != ''";
798 void AddProjectTargets (ProjectRootElement p, List<TargetInfo> solutionTargets, Dictionary<Guid, ProjectInfo> projectInfos)
800 foreach (KeyValuePair<Guid, ProjectInfo> projectInfo in projectInfos) {
801 ProjectInfo project = projectInfo.Value;
802 foreach (string buildTarget in buildTargets) {
803 string target_name = GetTargetNameForProject (project.Name, buildTarget);
804 bool is_build_or_rebuild = buildTarget == "Build" || buildTarget == "Rebuild";
805 var target = p.AddTarget (target_name);
806 target.Condition = "'$(CurrentSolutionConfigurationContents)' != ''";
808 if (is_build_or_rebuild)
809 target.Outputs = "@(CollectedBuildOutput)";
810 if (project.Dependencies.Count > 0)
811 target.DependsOnTargets = String.Join (";",
812 project.Dependencies.Values.Select (
813 di => GetTargetNameForProject (di.Name, buildTarget)).ToArray ());
815 foreach (TargetInfo targetInfo in solutionTargets) {
816 ProjectTaskElement task = null;
817 TargetInfo projectTargetInfo;
818 if (!project.TargetMap.TryGetValue (targetInfo, out projectTargetInfo)) {
819 AddWarningForMissingProjectConfiguration (target, targetInfo.Configuration,
820 targetInfo.Platform, project.Name);
823 if (projectTargetInfo.Build) {
824 task = target.AddTask ("MSBuild");
825 task.SetParameter ("Projects", project.FileName);
826 task.SetParameter ("ToolsVersion", "$(ProjectToolsVersion)");
827 if (is_build_or_rebuild)
828 task.AddOutputItem ("TargetOutputs", "CollectedBuildOutput");
830 if (buildTarget != "Build")
831 task.SetParameter ("Targets", buildTarget);
832 task.SetParameter ("Properties", string.Format ("Configuration={0}; Platform={1}; BuildingSolutionFile=true; CurrentSolutionConfigurationContents=$(CurrentSolutionConfigurationContents); SolutionDir=$(SolutionDir); SolutionExt=$(SolutionExt); SolutionFileName=$(SolutionFileName); SolutionName=$(SolutionName); SolutionPath=$(SolutionPath)", projectTargetInfo.Configuration, projectTargetInfo.Platform));
834 task = target.AddTask ("Message");
835 task.SetParameter ("Text", string.Format ("Project \"{0}\" is disabled for solution configuration \"{1}|{2}\".", project.Name, targetInfo.Configuration, targetInfo.Platform));
837 task.Condition = string.Format (" ('$(Configuration)' == '{0}') and ('$(Platform)' == '{1}') ", targetInfo.Configuration, targetInfo.Platform);
844 string GetTargetNameForProject (string projectName, string buildTarget)
847 projectName = projectName.Replace ("\\", "/").Replace (".", "_");
848 string target_name = projectName +
849 (buildTarget == "Build" ? string.Empty : ":" + buildTarget);
851 if (IsBuildTargetName (projectName))
852 target_name = "Solution:" + target_name;
857 bool IsBuildTargetName (string name)
859 foreach (string tgt in buildTargets)
865 // returns number of levels
866 int AddBuildLevels (ProjectRootElement p, List<TargetInfo> solutionTargets, Dictionary<Guid, ProjectInfo> projectInfos,
867 ref List<ProjectInfo>[] infosByLevel)
869 infosByLevel = TopologicalSort<ProjectInfo> (projectInfos.Values);
871 foreach (TargetInfo targetInfo in solutionTargets) {
872 var big = p.AddItemGroup ();
873 big.Condition = String.Format (" ('$(Configuration)' == '{0}') and ('$(Platform)' == '{1}') ",
874 targetInfo.Configuration, targetInfo.Platform);
876 //FIXME: every level has projects that can be built in parallel.
877 // levels are ordered on the basis of the dependency graph
879 for (int i = 0; i < infosByLevel.Length; i ++) {
880 string build_level = String.Format ("BuildLevel{0}", i);
881 string skip_level = String.Format ("SkipLevel{0}", i);
882 string missing_level = String.Format ("MissingConfigLevel{0}", i);
884 foreach (ProjectInfo projectInfo in infosByLevel [i]) {
885 TargetInfo projectTargetInfo;
886 if (!projectInfo.TargetMap.TryGetValue (targetInfo, out projectTargetInfo)) {
887 // missing project config
888 big.AddItem (missing_level, projectInfo.Name);
892 if (projectTargetInfo.Build) {
893 var item = big.AddItem (build_level, projectInfo.FileName);
894 item.AddMetadata ("Configuration", projectTargetInfo.Configuration);
895 item.AddMetadata ("Platform", projectTargetInfo.Platform);
898 big.AddItem (skip_level, projectInfo.Name);
904 return infosByLevel.Length;
907 void AddSolutionTargets (ProjectRootElement p, int num_levels, IEnumerable<ProjectInfo> websiteProjectInfos)
909 foreach (string buildTarget in buildTargets) {
910 var t = p.AddTarget (buildTarget);
911 bool is_build_or_rebuild = buildTarget == "Build" || buildTarget == "Rebuild";
913 t.Condition = "'$(CurrentSolutionConfigurationContents)' != ''";
914 if (is_build_or_rebuild)
915 t.Outputs = "@(CollectedBuildOutput)";
917 ProjectTaskElement task = null;
918 for (int i = 0; i < num_levels; i ++) {
919 string level_str = String.Format ("BuildLevel{0}", i);
920 task = t.AddTask ("MSBuild");
921 task.SetParameter ("Condition", String.Format ("'@({0})' != ''", level_str));
922 task.SetParameter ("Projects", String.Format ("@({0})", level_str));
923 task.SetParameter ("ToolsVersion", "$(ProjectToolsVersion)");
924 task.SetParameter ("Properties",
925 string.Format ("Configuration=%(Configuration); Platform=%(Platform); BuildingSolutionFile=true; CurrentSolutionConfigurationContents=$(CurrentSolutionConfigurationContents); SolutionDir=$(SolutionDir); SolutionExt=$(SolutionExt); SolutionFileName=$(SolutionFileName); SolutionName=$(SolutionName); SolutionPath=$(SolutionPath)"));
926 if (buildTarget != "Build")
927 task.SetParameter ("Targets", buildTarget);
928 //FIXME: change this to BuildInParallel=true, when parallel
929 // build support gets added
930 task.SetParameter ("RunEachTargetSeparately", "true");
931 if (is_build_or_rebuild)
932 task.AddOutputItem ("TargetOutputs", "CollectedBuildOutput");
934 level_str = String.Format ("SkipLevel{0}", i);
935 task = t.AddTask ("Message");
936 task.Condition = String.Format ("'@({0})' != ''", level_str);
937 task.SetParameter ("Text",
938 String.Format ("The project '%({0}.Identity)' is disabled for solution " +
939 "configuration '$(Configuration)|$(Platform)'.", level_str));
941 level_str = String.Format ("MissingConfigLevel{0}", i);
942 task = t.AddTask ("Warning");
943 task.Condition = String.Format ("'@({0})' != ''", level_str);
944 task.SetParameter ("Text",
945 String.Format ("The project configuration for project '%({0}.Identity)' " +
946 "corresponding to the solution configuration " +
947 "'$(Configuration)|$(Platform)' was not found.", level_str));
950 // "build" website projects also
951 StringBuilder w_targets = new StringBuilder ();
952 foreach (ProjectInfo info in websiteProjectInfos) {
953 if (w_targets.Length > 0)
954 w_targets.Append (";");
955 w_targets.Append (GetTargetNameForProject (info.Name, buildTarget));
958 task = t.AddTask ("CallTarget");
959 task.SetParameter ("Targets", w_targets.ToString ());
960 task.SetParameter ("RunEachTargetSeparately", "true");
964 // Sorts the ProjectInfo dependency graph, to obtain
965 // a series of build levels with projects. Projects
966 // in each level can be run parallel (no inter-dependency).
967 static List<T>[] TopologicalSort<T> (IEnumerable<T> items) where T: ProjectInfo
970 allItems = items as IList<T>;
971 if (allItems == null)
972 allItems = new List<T> (items);
974 bool[] inserted = new bool[allItems.Count];
975 bool[] triedToInsert = new bool[allItems.Count];
976 int[] levels = new int [allItems.Count];
979 for (int i = 0; i < allItems.Count; ++i) {
980 int d = Insert<T> (i, allItems, levels, inserted, triedToInsert);
985 // Separate out the project infos by build level
986 List<T>[] infosByLevel = new List<T>[maxdepth];
987 for (int i = 0; i < levels.Length; i ++) {
988 int level = levels [i] - 1;
989 if (infosByLevel [level] == null)
990 infosByLevel [level] = new List<T> ();
992 infosByLevel [level].Add (allItems [i]);
998 // returns level# for the project
999 static int Insert<T> (int index, IList<T> allItems, int[] levels, bool[] inserted, bool[] triedToInsert)
1000 where T: ProjectInfo
1002 if (inserted [index])
1003 return levels [index];
1005 if (triedToInsert[index])
1006 throw new InvalidOperationException (String.Format (
1007 "Cyclic dependency involving project {0} found in the project dependency graph",
1008 allItems [index].Name));
1010 triedToInsert[index] = true;
1011 ProjectInfo insertItem = allItems[index];
1014 foreach (ProjectInfo dependency in insertItem.Dependencies.Values) {
1015 for (int j = 0; j < allItems.Count; ++j) {
1016 ProjectInfo checkItem = allItems [j];
1017 if (dependency.FileName == checkItem.FileName) {
1018 int d = Insert (j, allItems, levels, inserted, triedToInsert);
1019 maxdepth = d > maxdepth ? d : maxdepth;
1024 levels [index] = maxdepth + 1;
1025 inserted [index] = true;
1027 return levels [index];
1030 public static IEnumerable<string> GetAllProjectFileNames (string solutionFile)
1032 StreamReader reader = new StreamReader (solutionFile);
1033 string line = reader.ReadToEnd ();
1034 line = line.Replace ("\r\n", "\n");
1035 string soln_dir = Path.GetDirectoryName (solutionFile);
1037 Match m = projectRegex.Match (line);
1039 if (String.Compare (m.Groups [1].Value, solutionFolderGuid,
1040 StringComparison.InvariantCultureIgnoreCase) != 0)
1041 yield return Path.Combine (soln_dir, m.Groups [3].Value).Replace ("\\", "/");