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.BuildEngine;
39 namespace Mono.XBuild.CommandLine {
42 public string FileName;
45 public ProjectInfo (string name, string fileName)
51 public Dictionary<TargetInfo, TargetInfo> TargetMap = new Dictionary<TargetInfo, TargetInfo> ();
52 public Dictionary<Guid, ProjectInfo> Dependencies = new Dictionary<Guid, ProjectInfo> ();
53 public Dictionary<string, ProjectSection> ProjectSections = new Dictionary<string, ProjectSection> ();
54 public List<string> AspNetConfigurations = new List<string> ();
57 class ProjectSection {
59 public Dictionary<string, string> Properties = new Dictionary<string, string> ();
61 public ProjectSection (string name)
68 public string Configuration;
69 public string Platform;
72 public TargetInfo (string configuration, string platform)
73 : this (configuration, platform, false)
77 public TargetInfo (string configuration, string platform, bool build)
79 Configuration = configuration;
86 internal delegate void RaiseWarningHandler (int errorNumber, string message);
88 class SolutionParser {
89 static string[] buildTargets = new string[] { "Build", "Clean", "Rebuild", "Publish" };
91 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}}";
93 static Regex slnVersionRegex = new Regex (@"Microsoft Visual Studio Solution File, Format Version (\d?\d.\d\d)");
94 static Regex projectRegex = new Regex ("Project\\(\"(" + guidExpression + ")\"\\) = \"(.*?)\", \"(.*?)\", \"(" + guidExpression + ")\"(\\s*?)((\\s*?)ProjectSection\\((.*?)\\) = (.*?)EndProjectSection(\\s*?))*(\\s*?)(EndProject)?", RegexOptions.Singleline);
95 static Regex projectDependenciesRegex = new Regex ("ProjectSection\\((.*?)\\) = \\w*(.*?)EndProjectSection", RegexOptions.Singleline);
96 static Regex projectDependencyRegex = new Regex ("\\s*(" + guidExpression + ") = (" + guidExpression + ")");
97 static Regex projectSectionPropertiesRegex = new Regex ("\\s*(?<name>.*) = \"(?<value>.*)\"");
99 static Regex globalRegex = new Regex ("Global(.*)EndGlobal", RegexOptions.Singleline);
100 static Regex globalSectionRegex = new Regex ("GlobalSection\\((.*?)\\) = \\w*(.*?)EndGlobalSection", RegexOptions.Singleline);
102 static Regex solutionConfigurationRegex = new Regex ("\\s*(.*?)\\|(.*?) = (.*?)\\|(.+)");
103 static Regex projectConfigurationActiveCfgRegex = new Regex ("\\s*(" + guidExpression + ")\\.(.+?)\\|(.+?)\\.ActiveCfg = (.+?)\\|(.+)");
104 static Regex projectConfigurationBuildRegex = new Regex ("\\s*(" + guidExpression + ")\\.(.*?)\\|(.*?)\\.Build\\.0 = (.*?)\\|(.+)");
106 static string solutionFolderGuid = "{2150E333-8FDC-42A3-9474-1A3956D46DE8}";
107 static string vcprojGuid = "{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}";
108 static string websiteProjectGuid = "{E24C65DC-7377-472B-9ABA-BC803B73C61A}";
110 RaiseWarningHandler RaiseWarning;
112 public void ParseSolution (string file, Project p, RaiseWarningHandler RaiseWarning)
114 this.RaiseWarning = RaiseWarning;
115 EmitBeforeImports (p, file);
117 AddGeneralSettings (file, p);
119 StreamReader reader = new StreamReader (file);
121 string slnVersion = GetSlnFileVersion (reader);
123 if (slnVersion == "12.00")
125 p.DefaultToolsVersion = "12.0";
127 p.DefaultToolsVersion = "4.0";
129 else if (slnVersion == "11.00")
130 p.DefaultToolsVersion = "4.0";
131 else if (slnVersion == "10.00")
132 p.DefaultToolsVersion = "3.5";
134 p.DefaultToolsVersion = "2.0";
136 string line = reader.ReadToEnd ();
137 line = line.Replace ("\r\n", "\n");
138 string solutionDir = Path.GetDirectoryName (file);
140 List<TargetInfo> solutionTargets = new List<TargetInfo> ();
141 Dictionary<Guid, ProjectInfo> projectInfos = new Dictionary<Guid, ProjectInfo> ();
142 Dictionary<Guid, ProjectInfo> websiteProjectInfos = new Dictionary<Guid, ProjectInfo> ();
143 List<ProjectInfo>[] infosByLevel = null;
144 Dictionary<Guid, ProjectInfo> unsupportedProjectInfos = new Dictionary<Guid, ProjectInfo> ();
146 Match m = projectRegex.Match (line);
148 ProjectInfo projectInfo = new ProjectInfo (m.Groups[2].Value,
149 Path.GetFullPath (Path.Combine (solutionDir,
150 m.Groups [3].Value.Replace ('\\', Path.DirectorySeparatorChar))));
151 if (String.Compare (m.Groups [1].Value, solutionFolderGuid,
152 StringComparison.InvariantCultureIgnoreCase) == 0) {
153 // Ignore solution folders
158 projectInfo.Guid = new Guid (m.Groups [4].Value);
160 if (String.Compare (m.Groups [1].Value, vcprojGuid,
161 StringComparison.InvariantCultureIgnoreCase) == 0) {
163 RaiseWarning (0, string.Format("Ignoring vcproj '{0}'.", projectInfo.Name));
165 unsupportedProjectInfos [projectInfo.Guid] = projectInfo;
170 if (String.Compare (m.Groups [1].Value, websiteProjectGuid,
171 StringComparison.InvariantCultureIgnoreCase) == 0)
172 websiteProjectInfos.Add (new Guid (m.Groups[4].Value), projectInfo);
174 projectInfos.Add (projectInfo.Guid, projectInfo);
176 Match projectSectionMatch = projectDependenciesRegex.Match (m.Groups[6].Value);
177 while (projectSectionMatch.Success) {
178 string section_name = projectSectionMatch.Groups [1].Value;
179 if (String.Compare (section_name, "ProjectDependencies") == 0) {
180 Match projectDependencyMatch = projectDependencyRegex.Match (projectSectionMatch.Value);
181 while (projectDependencyMatch.Success) {
182 // we might not have projectInfo available right now, so
183 // set it to null, and fill it in later
184 projectInfo.Dependencies [new Guid (projectDependencyMatch.Groups[1].Value)] = null;
185 projectDependencyMatch = projectDependencyMatch.NextMatch ();
188 ProjectSection section = new ProjectSection (section_name);
189 Match propertiesMatch = projectSectionPropertiesRegex.Match (
190 projectSectionMatch.Groups [2].Value);
191 while (propertiesMatch.Success) {
192 section.Properties [propertiesMatch.Groups ["name"].Value] =
193 propertiesMatch.Groups ["value"].Value;
195 propertiesMatch = propertiesMatch.NextMatch ();
198 projectInfo.ProjectSections [section_name] = section;
200 projectSectionMatch = projectSectionMatch.NextMatch ();
205 foreach (ProjectInfo projectInfo in projectInfos.Values) {
206 string filename = projectInfo.FileName;
207 string projectDir = Path.GetDirectoryName (filename);
209 if (!File.Exists (filename)) {
210 RaiseWarning (0, String.Format ("Project file {0} referenced in the solution file, " +
211 "not found. Ignoring.", filename));
215 Project currentProject = p.ParentEngine.CreateNewProject ();
217 currentProject.Load (filename, ProjectLoadSettings.IgnoreMissingImports);
218 } catch (InvalidProjectFileException e) {
219 RaiseWarning (0, e.Message);
223 foreach (BuildItem bi in currentProject.GetEvaluatedItemsByName ("ProjectReference")) {
224 ProjectInfo info = null;
225 string projectReferenceGuid = bi.GetEvaluatedMetadata ("Project");
226 bool hasGuid = !String.IsNullOrEmpty (projectReferenceGuid);
228 // try to resolve the ProjectReference by GUID
229 // and fallback to project filename
232 Guid guid = new Guid (projectReferenceGuid);
233 projectInfos.TryGetValue (guid, out info);
234 if (info == null && unsupportedProjectInfos.TryGetValue (guid, out info)) {
235 RaiseWarning (0, String.Format (
236 "{0}: ProjectReference '{1}' is of an unsupported type. Ignoring.",
237 filename, bi.Include));
242 if (info == null || !hasGuid) {
243 // Project not found by guid or guid not available
244 // Try to find by project file
246 string fullpath = Path.GetFullPath (Path.Combine (projectDir, bi.Include.Replace ('\\', Path.DirectorySeparatorChar)));
247 info = projectInfos.Values.FirstOrDefault (pi => pi.FileName == fullpath);
250 if (unsupportedProjectInfos.Values.Any (pi => pi.FileName == fullpath))
251 RaiseWarning (0, String.Format (
252 "{0}: ProjectReference '{1}' is of an unsupported type. Ignoring.",
253 filename, bi.Include));
255 RaiseWarning (0, String.Format (
256 "{0}: ProjectReference '{1}' not found, neither by guid '{2}' nor by project file name '{3}'.",
257 filename, bi.Include, projectReferenceGuid.Replace ("{", "").Replace ("}", ""), fullpath));
263 projectInfo.Dependencies [info.Guid] = info;
267 // fill in the project info for deps found in the .sln file
268 foreach (ProjectInfo projectInfo in projectInfos.Values) {
269 List<Guid> missingInfos = new List<Guid> ();
270 foreach (KeyValuePair<Guid, ProjectInfo> dependency in projectInfo.Dependencies) {
271 if (dependency.Value == null)
272 missingInfos.Add (dependency.Key);
275 foreach (Guid guid in missingInfos) {
277 if (projectInfos.TryGetValue (guid, out info))
278 projectInfo.Dependencies [guid] = info;
280 projectInfo.Dependencies.Remove (guid);
284 Match globalMatch = globalRegex.Match (line);
285 Match globalSectionMatch = globalSectionRegex.Match (globalMatch.Groups[1].Value);
286 while (globalSectionMatch.Success) {
287 string sectionType = globalSectionMatch.Groups[1].Value;
288 switch (sectionType) {
289 case "SolutionConfigurationPlatforms":
290 ParseSolutionConfigurationPlatforms (globalSectionMatch.Groups[2].Value, solutionTargets);
292 case "ProjectConfigurationPlatforms":
293 ParseProjectConfigurationPlatforms (globalSectionMatch.Groups[2].Value,
294 projectInfos, websiteProjectInfos);
296 case "SolutionProperties":
297 ParseSolutionProperties (globalSectionMatch.Groups[2].Value);
299 case "NestedProjects":
301 case "MonoDevelopProperties":
304 RaiseWarning (0, string.Format("Don't know how to handle GlobalSection {0}, Ignoring.", sectionType));
307 globalSectionMatch = globalSectionMatch.NextMatch ();
310 int num_levels = AddBuildLevels (p, solutionTargets, projectInfos, ref infosByLevel);
312 AddCurrentSolutionConfigurationContents (p, solutionTargets, projectInfos, websiteProjectInfos);
313 AddProjectReferences (p, projectInfos);
314 AddWebsiteProperties (p, websiteProjectInfos, projectInfos);
315 AddValidateSolutionConfiguration (p);
317 EmitAfterImports (p, file);
319 AddGetFrameworkPathTarget (p);
320 AddWebsiteTargets (p, websiteProjectInfos, projectInfos, infosByLevel, solutionTargets);
321 AddProjectTargets (p, solutionTargets, projectInfos);
322 AddSolutionTargets (p, num_levels, websiteProjectInfos.Values);
325 string GetSlnFileVersion (StreamReader reader)
327 string strInput = null;
330 strInput = reader.ReadLine();
331 if (strInput == null)
334 match = slnVersionRegex.Match(strInput);
335 if (!match.Success) {
336 strInput = reader.ReadLine();
337 if (strInput == null)
339 match = slnVersionRegex.Match (strInput);
343 return match.Groups[1].Value;
348 void EmitBeforeImports (Project p, string file)
351 p.AddNewImport ("$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\SolutionFile\\ImportBefore\\*",
352 "'$(ImportByWildcardBeforeSolution)' != 'false' and " +
353 "Exists('$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\SolutionFile\\ImportBefore')");
356 string before_filename = Path.Combine (Path.GetDirectoryName (file), "before." + Path.GetFileName (file) + ".targets");
357 p.AddNewImport (before_filename, String.Format ("Exists ('{0}')", before_filename));
360 void EmitAfterImports (Project p, string file)
363 p.AddNewImport ("$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\SolutionFile\\ImportAfter\\*",
364 "'$(ImportByWildcardAfterSolution)' != 'false' and " +
365 "Exists('$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\SolutionFile\\ImportAfter')");
368 string after_filename = Path.Combine (Path.GetDirectoryName (file), "after." + Path.GetFileName (file) + ".targets");
369 p.AddNewImport (after_filename, String.Format ("Exists ('{0}')", after_filename));
372 void AddGeneralSettings (string solutionFile, Project p)
374 p.DefaultTargets = "Build";
375 p.InitialTargets = "ValidateSolutionConfiguration";
376 p.AddNewUsingTaskFromAssemblyName ("CreateTemporaryVCProject", "Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
377 p.AddNewUsingTaskFromAssemblyName ("ResolveVCProjectOutput", "Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
379 string solutionFilePath = Path.GetFullPath (solutionFile);
380 BuildPropertyGroup solutionPropertyGroup = p.AddNewPropertyGroup (true);
381 solutionPropertyGroup.AddNewProperty ("SolutionDir", Path.GetDirectoryName (solutionFilePath) + Path.DirectorySeparatorChar);
382 solutionPropertyGroup.AddNewProperty ("SolutionExt", Path.GetExtension (solutionFile));
383 solutionPropertyGroup.AddNewProperty ("SolutionFileName", Path.GetFileName (solutionFile));
384 solutionPropertyGroup.AddNewProperty ("SolutionName", Path.GetFileNameWithoutExtension (solutionFile));
385 solutionPropertyGroup.AddNewProperty ("SolutionPath", solutionFilePath);
388 void ParseSolutionConfigurationPlatforms (string section, List<TargetInfo> solutionTargets)
390 Match solutionConfigurationPlatform = solutionConfigurationRegex.Match (section);
391 while (solutionConfigurationPlatform.Success) {
392 string solutionConfiguration = solutionConfigurationPlatform.Groups[1].Value;
393 string solutionPlatform = solutionConfigurationPlatform.Groups[2].Value;
394 solutionTargets.Add (new TargetInfo (solutionConfiguration, solutionPlatform));
395 solutionConfigurationPlatform = solutionConfigurationPlatform.NextMatch ();
399 // ignores the website projects, in the websiteProjectInfos
400 void ParseProjectConfigurationPlatforms (string section, Dictionary<Guid, ProjectInfo> projectInfos,
401 Dictionary<Guid, ProjectInfo> websiteProjectInfos)
403 List<Guid> missingGuids = new List<Guid> ();
404 Match projectConfigurationPlatform = projectConfigurationActiveCfgRegex.Match (section);
405 while (projectConfigurationPlatform.Success) {
406 Guid guid = new Guid (projectConfigurationPlatform.Groups[1].Value);
407 ProjectInfo projectInfo;
408 if (!projectInfos.TryGetValue (guid, out projectInfo)) {
409 if (!missingGuids.Contains (guid)) {
410 if (!websiteProjectInfos.ContainsKey (guid))
411 // ignore website projects
412 RaiseWarning (0, string.Format("Failed to find project {0}", guid));
413 missingGuids.Add (guid);
415 projectConfigurationPlatform = projectConfigurationPlatform.NextMatch ();
418 string solConf = projectConfigurationPlatform.Groups[2].Value;
419 string solPlat = projectConfigurationPlatform.Groups[3].Value;
420 string projConf = projectConfigurationPlatform.Groups[4].Value;
421 string projPlat = projectConfigurationPlatform.Groups[5].Value;
422 // hack, what are they doing here?
423 if (projPlat == "Any CPU")
425 projectInfo.TargetMap.Add (new TargetInfo (solConf, solPlat), new TargetInfo (projConf, projPlat));
426 projectConfigurationPlatform = projectConfigurationPlatform.NextMatch ();
428 Match projectConfigurationPlatformBuild = projectConfigurationBuildRegex.Match (section);
429 while (projectConfigurationPlatformBuild.Success) {
430 Guid guid = new Guid (projectConfigurationPlatformBuild.Groups[1].Value);
431 ProjectInfo projectInfo;
432 if (!projectInfos.TryGetValue (guid, out projectInfo)) {
433 if (!missingGuids.Contains (guid)) {
434 RaiseWarning (0, string.Format("Failed to find project {0}", guid));
435 missingGuids.Add (guid);
437 projectConfigurationPlatformBuild = projectConfigurationPlatformBuild.NextMatch ();
440 string solConf = projectConfigurationPlatformBuild.Groups[2].Value;
441 string solPlat = projectConfigurationPlatformBuild.Groups[3].Value;
442 string projConf = projectConfigurationPlatformBuild.Groups[4].Value;
443 string projPlat = projectConfigurationPlatformBuild.Groups[5].Value;
444 // hack, what are they doing here?
445 if (projPlat == "Any CPU")
447 projectInfo.TargetMap[new TargetInfo (solConf, solPlat)] = new TargetInfo (projConf, projPlat, true);
448 projectConfigurationPlatformBuild = projectConfigurationPlatformBuild.NextMatch ();
452 void ParseSolutionProperties (string section)
456 void AddCurrentSolutionConfigurationContents (Project p, List<TargetInfo> solutionTargets,
457 Dictionary<Guid, ProjectInfo> projectInfos,
458 Dictionary<Guid, ProjectInfo> websiteProjectInfos)
460 TargetInfo default_target_info = new TargetInfo ("Debug", "Any CPU");
461 if (solutionTargets.Count > 0) {
463 foreach (TargetInfo tinfo in solutionTargets) {
464 if (String.Compare (tinfo.Platform, "Mixed Platforms") == 0) {
465 default_target_info = tinfo;
472 default_target_info = solutionTargets [0];
475 AddDefaultSolutionConfiguration (p, default_target_info);
477 foreach (TargetInfo solutionTarget in solutionTargets) {
478 BuildPropertyGroup platformPropertyGroup = p.AddNewPropertyGroup (false);
479 platformPropertyGroup.Condition = string.Format (
480 " ('$(Configuration)' == '{0}') and ('$(Platform)' == '{1}') ",
481 solutionTarget.Configuration,
482 solutionTarget.Platform
485 StringBuilder solutionConfigurationContents = new StringBuilder ();
486 solutionConfigurationContents.Append ("<SolutionConfiguration xmlns=\"\">");
487 foreach (KeyValuePair<Guid, ProjectInfo> projectInfo in projectInfos) {
488 AddProjectConfigurationItems (projectInfo.Key, projectInfo.Value, solutionTarget, solutionConfigurationContents);
490 solutionConfigurationContents.Append ("</SolutionConfiguration>");
492 platformPropertyGroup.AddNewProperty ("CurrentSolutionConfigurationContents",
493 solutionConfigurationContents.ToString ());
497 void AddProjectReferences (Project p, Dictionary<Guid, ProjectInfo> projectInfos)
499 BuildItemGroup big = p.AddNewItemGroup ();
500 foreach (KeyValuePair<Guid, ProjectInfo> pair in projectInfos)
501 big.AddNewItem ("ProjectReference", pair.Value.FileName);
504 void AddProjectConfigurationItems (Guid guid, ProjectInfo projectInfo, TargetInfo solutionTarget,
505 StringBuilder solutionConfigurationContents)
507 foreach (KeyValuePair<TargetInfo, TargetInfo> targetInfo in projectInfo.TargetMap) {
508 if (solutionTarget.Configuration == targetInfo.Key.Configuration &&
509 solutionTarget.Platform == targetInfo.Key.Platform) {
510 solutionConfigurationContents.AppendFormat (
511 "<ProjectConfiguration Project=\"{0}\">{1}|{2}</ProjectConfiguration>",
512 guid.ToString ("B").ToUpper (), targetInfo.Value.Configuration, targetInfo.Value.Platform);
517 void AddDefaultSolutionConfiguration (Project p, TargetInfo target)
519 BuildPropertyGroup configurationPropertyGroup = p.AddNewPropertyGroup (true);
520 configurationPropertyGroup.Condition = " '$(Configuration)' == '' ";
521 configurationPropertyGroup.AddNewProperty ("Configuration", target.Configuration);
523 BuildPropertyGroup platformPropertyGroup = p.AddNewPropertyGroup (true);
524 platformPropertyGroup.Condition = " '$(Platform)' == '' ";
525 platformPropertyGroup.AddNewProperty ("Platform", target.Platform);
527 // emit default for AspNetConfiguration also
528 BuildPropertyGroup aspNetConfigurationPropertyGroup = p.AddNewPropertyGroup (true);
529 aspNetConfigurationPropertyGroup.Condition = " ('$(AspNetConfiguration)' == '') ";
530 aspNetConfigurationPropertyGroup.AddNewProperty ("AspNetConfiguration", "$(Configuration)");
533 void AddWarningForMissingProjectConfiguration (Target target, string slnConfig, string slnPlatform, string projectName)
535 BuildTask task = target.AddNewTask ("Warning");
536 task.SetParameterValue ("Text",
537 String.Format ("The project configuration for project '{0}' corresponding " +
538 "to the solution configuration '{1}|{2}' was not found in the solution file.",
539 projectName, slnConfig, slnPlatform));
540 task.Condition = String.Format ("('$(Configuration)' == '{0}') and ('$(Platform)' == '{1}')",
541 slnConfig, slnPlatform);
545 // Website project methods
547 void AddWebsiteProperties (Project p, Dictionary<Guid, ProjectInfo> websiteProjectInfos,
548 Dictionary<Guid, ProjectInfo> projectInfos)
550 var propertyGroupByConfig = new Dictionary<string, BuildPropertyGroup> ();
551 foreach (KeyValuePair<Guid, ProjectInfo> infoPair in websiteProjectInfos) {
552 ProjectInfo info = infoPair.Value;
553 string projectGuid = infoPair.Key.ToString ();
555 ProjectSection section;
556 if (!info.ProjectSections.TryGetValue ("WebsiteProperties", out section)) {
557 RaiseWarning (0, String.Format ("Website project '{0}' does not have the required project section: WebsiteProperties. Ignoring project.", info.Name));
561 //parse project references
562 string [] ref_guids = null;
564 if (section.Properties.TryGetValue ("ProjectReferences", out references)) {
565 ref_guids = references.Split (new char [] {';'}, StringSplitOptions.RemoveEmptyEntries);
566 for (int i = 0; i < ref_guids.Length; i ++) {
568 ref_guids [i] = ref_guids [i].Split ('|') [0];
570 Guid r_guid = new Guid (ref_guids [i]);
571 ProjectInfo ref_info;
572 if (projectInfos.TryGetValue (r_guid, out ref_info))
573 // ignore if not found
574 info.Dependencies [r_guid] = ref_info;
578 foreach (KeyValuePair<string, string> pair in section.Properties) {
579 //looking for -- ConfigName.AspNetCompiler.PropName
580 string [] parts = pair.Key.Split ('.');
581 if (parts.Length != 3 || String.Compare (parts [1], "AspNetCompiler") != 0)
584 string config = parts [0];
585 string propertyName = parts [2];
587 BuildPropertyGroup bpg;
588 if (!propertyGroupByConfig.TryGetValue (config, out bpg)) {
589 bpg = p.AddNewPropertyGroup (true);
590 bpg.Condition = String.Format (" '$(AspNetConfiguration)' == '{0}' ", config);
591 propertyGroupByConfig [config] = bpg;
594 bpg.AddNewProperty (String.Format ("Project_{0}_AspNet{1}", projectGuid, propertyName),
597 if (!info.AspNetConfigurations.Contains (config))
598 info.AspNetConfigurations.Add (config);
603 // For WebSite projects
604 // The main "Build" target:
605 // 1. builds all non-website projects
606 // 2. calls target for website project
607 // - gets target path for the referenced projects
608 // - Resolves dependencies, satellites etc for the
609 // referenced project assemblies, and copies them
611 void AddWebsiteTargets (Project p, Dictionary<Guid, ProjectInfo> websiteProjectInfos,
612 Dictionary<Guid, ProjectInfo> projectInfos, List<ProjectInfo>[] infosByLevel,
613 List<TargetInfo> solutionTargets)
615 foreach (ProjectInfo w_info in websiteProjectInfos.Values) {
616 // gets a linear list of dependencies
617 List<ProjectInfo> depInfos = new List<ProjectInfo> ();
618 foreach (List<ProjectInfo> pinfos in infosByLevel) {
619 foreach (ProjectInfo pinfo in pinfos)
620 if (w_info.Dependencies.ContainsKey (pinfo.Guid))
621 depInfos.Add (pinfo);
624 foreach (string buildTarget in new string [] {"Build", "Rebuild"})
625 AddWebsiteTarget (p, w_info, projectInfos, depInfos, solutionTargets, buildTarget);
627 // clean/publish are not supported for website projects
628 foreach (string buildTarget in new string [] {"Clean", "Publish"})
629 AddWebsiteUnsupportedTarget (p, w_info, depInfos, buildTarget);
633 void AddWebsiteTarget (Project p, ProjectInfo webProjectInfo,
634 Dictionary<Guid, ProjectInfo> projectInfos, List<ProjectInfo> depInfos,
635 List<TargetInfo> solutionTargets, string buildTarget)
637 string w_guid = webProjectInfo.Guid.ToString ().ToUpper ();
639 Target target = p.Targets.AddNewTarget (GetTargetNameForProject (webProjectInfo.Name, buildTarget));
640 target.Condition = "'$(CurrentSolutionConfigurationContents)' != ''";
641 target.DependsOnTargets = GetWebsiteDependsOnTarget (depInfos, buildTarget);
643 // this item collects all the references
644 string final_ref_item = String.Format ("Project_{0}_References{1}", w_guid,
645 buildTarget != "Build" ? "_" + buildTarget : String.Empty);
647 foreach (TargetInfo targetInfo in solutionTargets) {
649 foreach (ProjectInfo depInfo in depInfos) {
650 TargetInfo projectTargetInfo;
651 if (!depInfo.TargetMap.TryGetValue (targetInfo, out projectTargetInfo))
652 // Ignore, no config, so no target path
655 // GetTargetPath from the referenced project
656 AddWebsiteMSBuildTaskForReference (target, depInfo, projectTargetInfo, targetInfo,
657 final_ref_item, ref_num);
662 // resolve the references
663 AddWebsiteResolveAndCopyReferencesTasks (target, webProjectInfo, final_ref_item, w_guid);
666 // emits the MSBuild task to GetTargetPath for the referenced project
667 void AddWebsiteMSBuildTaskForReference (Target target, ProjectInfo depInfo, TargetInfo projectTargetInfo,
668 TargetInfo solutionTargetInfo, string final_ref_item, int ref_num)
670 BuildTask task = target.AddNewTask ("MSBuild");
671 task.SetParameterValue ("Projects", depInfo.FileName);
672 task.SetParameterValue ("Targets", "GetTargetPath");
674 task.SetParameterValue ("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));
675 task.Condition = string.Format (" ('$(Configuration)' == '{0}') and ('$(Platform)' == '{1}') ", solutionTargetInfo.Configuration, solutionTargetInfo.Platform);
677 string ref_item = String.Format ("{0}_{1}",
678 final_ref_item, ref_num);
680 task.AddOutputItem ("TargetOutputs", ref_item);
682 task = target.AddNewTask ("CreateItem");
683 task.SetParameterValue ("Include", String.Format ("@({0})", ref_item));
684 task.SetParameterValue ("AdditionalMetadata", String.Format ("Guid={{{0}}}",
685 depInfo.Guid.ToString ().ToUpper ()));
686 task.AddOutputItem ("Include", final_ref_item);
689 void AddWebsiteResolveAndCopyReferencesTasks (Target target, ProjectInfo webProjectInfo,
690 string final_ref_item, string w_guid)
692 BuildTask task = target.AddNewTask ("ResolveAssemblyReference");
693 task.SetParameterValue ("Assemblies", String.Format ("@({0}->'%(FullPath)')", final_ref_item));
694 task.SetParameterValue ("TargetFrameworkDirectories", "$(TargetFrameworkPath)");
695 task.SetParameterValue ("SearchPaths", "{RawFileName};{TargetFrameworkDirectory};{GAC}");
696 task.SetParameterValue ("FindDependencies", "true");
697 task.SetParameterValue ("FindSatellites", "true");
698 task.SetParameterValue ("FindRelatedFiles", "true");
699 task.Condition = String.Format ("Exists ('%({0}.Identity)')", final_ref_item);
701 string copylocal_item = String.Format ("{0}_CopyLocalFiles", final_ref_item);
702 task.AddOutputItem ("CopyLocalFiles", copylocal_item);
704 // Copy the references
705 task = target.AddNewTask ("Copy");
706 task.SetParameterValue ("SourceFiles", String.Format ("@({0})", copylocal_item));
707 task.SetParameterValue ("DestinationFiles", String.Format (
708 "@({0}->'$(Project_{1}_AspNetPhysicalPath)\\Bin\\%(DestinationSubDirectory)%(Filename)%(Extension)')",
709 copylocal_item, w_guid));
711 // AspNetConfiguration, is config for the website project, useful
712 // for overriding from command line
713 StringBuilder cond = new StringBuilder ();
714 foreach (string config in webProjectInfo.AspNetConfigurations) {
716 cond.Append (" or ");
717 cond.AppendFormat (" ('$(AspNetConfiguration)' == '{0}') ", config);
719 task.Condition = cond.ToString ();
721 task = target.AddNewTask ("Message");
722 cond = new StringBuilder ();
723 foreach (string config in webProjectInfo.AspNetConfigurations) {
725 cond.Append (" and ");
726 cond.AppendFormat (" ('$(AspNetConfiguration)' != '{0}') ", config);
728 task.Condition = cond.ToString ();
729 task.SetParameterValue ("Text", "Skipping as the '$(AspNetConfiguration)' configuration is " +
730 "not supported by this website project.");
733 void AddWebsiteUnsupportedTarget (Project p, ProjectInfo webProjectInfo, List<ProjectInfo> depInfos,
736 Target target = p.Targets.AddNewTarget (GetTargetNameForProject (webProjectInfo.Name, buildTarget));
737 target.DependsOnTargets = GetWebsiteDependsOnTarget (depInfos, buildTarget);
739 BuildTask task = target.AddNewTask ("Message");
740 task.SetParameterValue ("Text", String.Format (
741 "Target '{0}' not support for website projects", buildTarget));
744 string GetWebsiteDependsOnTarget (List<ProjectInfo> depInfos, string buildTarget)
746 StringBuilder deps = new StringBuilder ();
747 foreach (ProjectInfo pinfo in depInfos) {
750 deps.Append (GetTargetNameForProject (pinfo.Name, buildTarget));
752 deps.Append (";GetFrameworkPath");
753 return deps.ToString ();
756 void AddGetFrameworkPathTarget (Project p)
758 Target t = p.Targets.AddNewTarget ("GetFrameworkPath");
759 BuildTask task = t.AddNewTask ("GetFrameworkPath");
760 task.AddOutputProperty ("Path", "TargetFrameworkPath");
763 void AddValidateSolutionConfiguration (Project p)
765 Target t = p.Targets.AddNewTarget ("ValidateSolutionConfiguration");
766 BuildTask task = t.AddNewTask ("Warning");
767 task.SetParameterValue ("Text", "On windows, an environment variable 'Platform' is set to MCD sometimes, and this overrides the Platform property" +
768 " for xbuild, which could be an invalid Platform for this solution file. And so you are getting the following error." +
769 " You could override it by either setting the environment variable to nothing, as\n" +
771 "Or explicity specify its value on the command line, as\n" +
772 " xbuild Foo.sln /p:Platform=Release");
773 task.Condition = "('$(CurrentSolutionConfigurationContents)' == '') and ('$(SkipInvalidConfigurations)' != 'true')" +
774 " and '$(Platform)' == 'MCD' and '$(OS)' == 'Windows_NT'";
776 task = t.AddNewTask ("Error");
777 task.SetParameterValue ("Text", "Invalid solution configuration and platform: \"$(Configuration)|$(Platform)\".");
778 task.Condition = "('$(CurrentSolutionConfigurationContents)' == '') and ('$(SkipInvalidConfigurations)' != 'true')";
779 task = t.AddNewTask ("Warning");
780 task.SetParameterValue ("Text", "Invalid solution configuration and platform: \"$(Configuration)|$(Platform)\".");
781 task.Condition = "('$(CurrentSolutionConfigurationContents)' == '') and ('$(SkipInvalidConfigurations)' == 'true')";
782 task = t.AddNewTask ("Message");
783 task.SetParameterValue ("Text", "Building solution configuration \"$(Configuration)|$(Platform)\".");
784 task.Condition = "'$(CurrentSolutionConfigurationContents)' != ''";
787 void AddProjectTargets (Project p, List<TargetInfo> solutionTargets, Dictionary<Guid, ProjectInfo> projectInfos)
789 foreach (KeyValuePair<Guid, ProjectInfo> projectInfo in projectInfos) {
790 ProjectInfo project = projectInfo.Value;
791 foreach (string buildTarget in buildTargets) {
792 string target_name = GetTargetNameForProject (project.Name, buildTarget);
793 bool is_build_or_rebuild = buildTarget == "Build" || buildTarget == "Rebuild";
794 Target target = p.Targets.AddNewTarget (target_name);
795 target.Condition = "'$(CurrentSolutionConfigurationContents)' != ''";
797 if (is_build_or_rebuild)
798 target.Outputs = "@(CollectedBuildOutput)";
799 if (project.Dependencies.Count > 0)
800 target.DependsOnTargets = String.Join (";",
801 project.Dependencies.Values.Select (
802 di => GetTargetNameForProject (di.Name, buildTarget)).ToArray ());
804 foreach (TargetInfo targetInfo in solutionTargets) {
805 BuildTask task = null;
806 TargetInfo projectTargetInfo;
807 if (!project.TargetMap.TryGetValue (targetInfo, out projectTargetInfo)) {
808 AddWarningForMissingProjectConfiguration (target, targetInfo.Configuration,
809 targetInfo.Platform, project.Name);
812 if (projectTargetInfo.Build) {
813 task = target.AddNewTask ("MSBuild");
814 task.SetParameterValue ("Projects", project.FileName);
815 task.SetParameterValue ("ToolsVersion", "$(ProjectToolsVersion)");
816 if (is_build_or_rebuild)
817 task.AddOutputItem ("TargetOutputs", "CollectedBuildOutput");
819 if (buildTarget != "Build")
820 task.SetParameterValue ("Targets", buildTarget);
821 task.SetParameterValue ("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));
823 task = target.AddNewTask ("Message");
824 task.SetParameterValue ("Text", string.Format ("Project \"{0}\" is disabled for solution configuration \"{1}|{2}\".", project.Name, targetInfo.Configuration, targetInfo.Platform));
826 task.Condition = string.Format (" ('$(Configuration)' == '{0}') and ('$(Platform)' == '{1}') ", targetInfo.Configuration, targetInfo.Platform);
833 string GetTargetNameForProject (string projectName, string buildTarget)
836 projectName = projectName.Replace ("\\", "/").Replace (".", "_");
837 string target_name = projectName +
838 (buildTarget == "Build" ? string.Empty : ":" + buildTarget);
840 if (IsBuildTargetName (projectName))
841 target_name = "Solution:" + target_name;
846 bool IsBuildTargetName (string name)
848 foreach (string tgt in buildTargets)
854 // returns number of levels
855 int AddBuildLevels (Project p, List<TargetInfo> solutionTargets, Dictionary<Guid, ProjectInfo> projectInfos,
856 ref List<ProjectInfo>[] infosByLevel)
858 infosByLevel = TopologicalSort<ProjectInfo> (projectInfos.Values);
860 foreach (TargetInfo targetInfo in solutionTargets) {
861 BuildItemGroup big = p.AddNewItemGroup ();
862 big.Condition = String.Format (" ('$(Configuration)' == '{0}') and ('$(Platform)' == '{1}') ",
863 targetInfo.Configuration, targetInfo.Platform);
865 //FIXME: every level has projects that can be built in parallel.
866 // levels are ordered on the basis of the dependency graph
868 for (int i = 0; i < infosByLevel.Length; i ++) {
869 string build_level = String.Format ("BuildLevel{0}", i);
870 string skip_level = String.Format ("SkipLevel{0}", i);
871 string missing_level = String.Format ("MissingConfigLevel{0}", i);
873 foreach (ProjectInfo projectInfo in infosByLevel [i]) {
874 TargetInfo projectTargetInfo;
875 if (!projectInfo.TargetMap.TryGetValue (targetInfo, out projectTargetInfo)) {
876 // missing project config
877 big.AddNewItem (missing_level, projectInfo.Name);
881 if (projectTargetInfo.Build) {
882 BuildItem item = big.AddNewItem (build_level, projectInfo.FileName);
883 item.SetMetadata ("Configuration", projectTargetInfo.Configuration);
884 item.SetMetadata ("Platform", projectTargetInfo.Platform);
887 big.AddNewItem (skip_level, projectInfo.Name);
893 return infosByLevel.Length;
896 void AddSolutionTargets (Project p, int num_levels, IEnumerable<ProjectInfo> websiteProjectInfos)
898 foreach (string buildTarget in buildTargets) {
899 Target t = p.Targets.AddNewTarget (buildTarget);
900 bool is_build_or_rebuild = buildTarget == "Build" || buildTarget == "Rebuild";
902 t.Condition = "'$(CurrentSolutionConfigurationContents)' != ''";
903 if (is_build_or_rebuild)
904 t.Outputs = "@(CollectedBuildOutput)";
906 BuildTask task = null;
907 for (int i = 0; i < num_levels; i ++) {
908 string level_str = String.Format ("BuildLevel{0}", i);
909 task = t.AddNewTask ("MSBuild");
910 task.SetParameterValue ("Condition", String.Format ("'@({0})' != ''", level_str));
911 task.SetParameterValue ("Projects", String.Format ("@({0})", level_str));
912 task.SetParameterValue ("ToolsVersion", "$(ProjectToolsVersion)");
913 task.SetParameterValue ("Properties",
914 string.Format ("Configuration=%(Configuration); Platform=%(Platform); BuildingSolutionFile=true; CurrentSolutionConfigurationContents=$(CurrentSolutionConfigurationContents); SolutionDir=$(SolutionDir); SolutionExt=$(SolutionExt); SolutionFileName=$(SolutionFileName); SolutionName=$(SolutionName); SolutionPath=$(SolutionPath)"));
915 if (buildTarget != "Build")
916 task.SetParameterValue ("Targets", buildTarget);
917 //FIXME: change this to BuildInParallel=true, when parallel
918 // build support gets added
919 task.SetParameterValue ("RunEachTargetSeparately", "true");
920 if (is_build_or_rebuild)
921 task.AddOutputItem ("TargetOutputs", "CollectedBuildOutput");
923 level_str = String.Format ("SkipLevel{0}", i);
924 task = t.AddNewTask ("Message");
925 task.Condition = String.Format ("'@({0})' != ''", level_str);
926 task.SetParameterValue ("Text",
927 String.Format ("The project '%({0}.Identity)' is disabled for solution " +
928 "configuration '$(Configuration)|$(Platform)'.", level_str));
930 level_str = String.Format ("MissingConfigLevel{0}", i);
931 task = t.AddNewTask ("Warning");
932 task.Condition = String.Format ("'@({0})' != ''", level_str);
933 task.SetParameterValue ("Text",
934 String.Format ("The project configuration for project '%({0}.Identity)' " +
935 "corresponding to the solution configuration " +
936 "'$(Configuration)|$(Platform)' was not found.", level_str));
939 // "build" website projects also
940 StringBuilder w_targets = new StringBuilder ();
941 foreach (ProjectInfo info in websiteProjectInfos) {
942 if (w_targets.Length > 0)
943 w_targets.Append (";");
944 w_targets.Append (GetTargetNameForProject (info.Name, buildTarget));
947 task = t.AddNewTask ("CallTarget");
948 task.SetParameterValue ("Targets", w_targets.ToString ());
949 task.SetParameterValue ("RunEachTargetSeparately", "true");
953 // Sorts the ProjectInfo dependency graph, to obtain
954 // a series of build levels with projects. Projects
955 // in each level can be run parallel (no inter-dependency).
956 static List<T>[] TopologicalSort<T> (IEnumerable<T> items) where T: ProjectInfo
959 allItems = items as IList<T>;
960 if (allItems == null)
961 allItems = new List<T> (items);
963 bool[] inserted = new bool[allItems.Count];
964 bool[] triedToInsert = new bool[allItems.Count];
965 int[] levels = new int [allItems.Count];
968 for (int i = 0; i < allItems.Count; ++i) {
969 int d = Insert<T> (i, allItems, levels, inserted, triedToInsert);
974 // Separate out the project infos by build level
975 List<T>[] infosByLevel = new List<T>[maxdepth];
976 for (int i = 0; i < levels.Length; i ++) {
977 int level = levels [i] - 1;
978 if (infosByLevel [level] == null)
979 infosByLevel [level] = new List<T> ();
981 infosByLevel [level].Add (allItems [i]);
987 // returns level# for the project
988 static int Insert<T> (int index, IList<T> allItems, int[] levels, bool[] inserted, bool[] triedToInsert)
991 if (inserted [index])
992 return levels [index];
994 if (triedToInsert[index])
995 throw new InvalidOperationException (String.Format (
996 "Cyclic dependency involving project {0} found in the project dependency graph",
997 allItems [index].Name));
999 triedToInsert[index] = true;
1000 ProjectInfo insertItem = allItems[index];
1003 foreach (ProjectInfo dependency in insertItem.Dependencies.Values) {
1004 for (int j = 0; j < allItems.Count; ++j) {
1005 ProjectInfo checkItem = allItems [j];
1006 if (dependency.FileName == checkItem.FileName) {
1007 int d = Insert (j, allItems, levels, inserted, triedToInsert);
1008 maxdepth = d > maxdepth ? d : maxdepth;
1013 levels [index] = maxdepth + 1;
1014 inserted [index] = true;
1016 return levels [index];
1019 public static IEnumerable<string> GetAllProjectFileNames (string solutionFile)
1021 StreamReader reader = new StreamReader (solutionFile);
1022 string line = reader.ReadToEnd ();
1023 line = line.Replace ("\r\n", "\n");
1024 string soln_dir = Path.GetDirectoryName (solutionFile);
1026 Match m = projectRegex.Match (line);
1028 if (String.Compare (m.Groups [1].Value, solutionFolderGuid,
1029 StringComparison.InvariantCultureIgnoreCase) != 0)
1030 yield return Path.Combine (soln_dir, m.Groups [3].Value).Replace ("\\", "/");