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 = "14.0";
127 p.DefaultToolsVersion = "12.0";
129 p.DefaultToolsVersion = "4.0";
131 else if (slnVersion == "11.00")
132 p.DefaultToolsVersion = "4.0";
133 else if (slnVersion == "10.00")
134 p.DefaultToolsVersion = "3.5";
136 p.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 = p.ParentEngine.CreateNewProject ();
219 currentProject.Load (filename, ProjectLoadSettings.IgnoreMissingImports);
220 } catch (InvalidProjectFileException e) {
221 RaiseWarning (0, e.Message);
225 foreach (BuildItem bi in currentProject.GetEvaluatedItemsByName ("ProjectReference")) {
226 ProjectInfo info = null;
227 string projectReferenceGuid = bi.GetEvaluatedMetadata ("Project");
228 bool hasGuid = !String.IsNullOrEmpty (projectReferenceGuid);
230 // try to resolve the ProjectReference by GUID
231 // and fallback to project filename
234 Guid guid = new Guid (projectReferenceGuid);
235 projectInfos.TryGetValue (guid, out info);
236 if (info == null && unsupportedProjectInfos.TryGetValue (guid, out info)) {
237 RaiseWarning (0, String.Format (
238 "{0}: ProjectReference '{1}' is of an unsupported type. Ignoring.",
239 filename, bi.Include));
244 if (info == null || !hasGuid) {
245 // Project not found by guid or guid not available
246 // Try to find by project file
248 string fullpath = Path.GetFullPath (Path.Combine (projectDir, bi.Include.Replace ('\\', Path.DirectorySeparatorChar)));
249 info = projectInfos.Values.FirstOrDefault (pi => pi.FileName == fullpath);
252 if (unsupportedProjectInfos.Values.Any (pi => pi.FileName == fullpath))
253 RaiseWarning (0, String.Format (
254 "{0}: ProjectReference '{1}' is of an unsupported type. Ignoring.",
255 filename, bi.Include));
257 RaiseWarning (0, String.Format (
258 "{0}: ProjectReference '{1}' not found, neither by guid '{2}' nor by project file name '{3}'.",
259 filename, bi.Include, projectReferenceGuid.Replace ("{", "").Replace ("}", ""), fullpath));
265 projectInfo.Dependencies [info.Guid] = info;
268 // unload the project after reading info from it
269 // it'll be reloaded with proper context when building the solution
270 p.ParentEngine.UnloadProject (currentProject);
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 (Project p, string file)
357 p.AddNewImport ("$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\SolutionFile\\ImportBefore\\*",
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.AddNewImport (before_filename, String.Format ("Exists ('{0}')", before_filename));
366 void EmitAfterImports (Project p, string file)
369 p.AddNewImport ("$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\SolutionFile\\ImportAfter\\*",
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.AddNewImport (after_filename, String.Format ("Exists ('{0}')", after_filename));
378 void AddGeneralSettings (string solutionFile, Project p)
380 p.DefaultTargets = "Build";
381 p.InitialTargets = "ValidateSolutionConfiguration";
382 p.AddNewUsingTaskFromAssemblyName ("CreateTemporaryVCProject", "Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
383 p.AddNewUsingTaskFromAssemblyName ("ResolveVCProjectOutput", "Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
385 string solutionFilePath = Path.GetFullPath (solutionFile);
386 BuildPropertyGroup solutionPropertyGroup = p.AddNewPropertyGroup (true);
387 solutionPropertyGroup.AddNewProperty ("SolutionDir", Path.GetDirectoryName (solutionFilePath) + Path.DirectorySeparatorChar);
388 solutionPropertyGroup.AddNewProperty ("SolutionExt", Path.GetExtension (solutionFile));
389 solutionPropertyGroup.AddNewProperty ("SolutionFileName", Path.GetFileName (solutionFile));
390 solutionPropertyGroup.AddNewProperty ("SolutionName", Path.GetFileNameWithoutExtension (solutionFile));
391 solutionPropertyGroup.AddNewProperty ("SolutionPath", solutionFilePath);
394 void ParseSolutionConfigurationPlatforms (string section, List<TargetInfo> solutionTargets)
396 Match solutionConfigurationPlatform = solutionConfigurationRegex.Match (section);
397 while (solutionConfigurationPlatform.Success) {
398 string solutionConfiguration = solutionConfigurationPlatform.Groups[1].Value;
399 string solutionPlatform = solutionConfigurationPlatform.Groups[2].Value;
400 solutionTargets.Add (new TargetInfo (solutionConfiguration, solutionPlatform));
401 solutionConfigurationPlatform = solutionConfigurationPlatform.NextMatch ();
405 // ignores the website projects, in the websiteProjectInfos
406 void ParseProjectConfigurationPlatforms (string section, Dictionary<Guid, ProjectInfo> projectInfos,
407 Dictionary<Guid, ProjectInfo> websiteProjectInfos)
409 List<Guid> missingGuids = new List<Guid> ();
410 Match projectConfigurationPlatform = projectConfigurationActiveCfgRegex.Match (section);
411 while (projectConfigurationPlatform.Success) {
412 Guid guid = new Guid (projectConfigurationPlatform.Groups[1].Value);
413 ProjectInfo projectInfo;
414 if (!projectInfos.TryGetValue (guid, out projectInfo)) {
415 if (!missingGuids.Contains (guid)) {
416 if (!websiteProjectInfos.ContainsKey (guid))
417 // ignore website projects
418 RaiseWarning (0, string.Format("Failed to find project {0}", guid));
419 missingGuids.Add (guid);
421 projectConfigurationPlatform = projectConfigurationPlatform.NextMatch ();
424 string solConf = projectConfigurationPlatform.Groups[2].Value;
425 string solPlat = projectConfigurationPlatform.Groups[3].Value;
426 string projConf = projectConfigurationPlatform.Groups[4].Value;
427 string projPlat = projectConfigurationPlatform.Groups[5].Value;
428 // hack, what are they doing here?
429 if (projPlat == "Any CPU")
431 projectInfo.TargetMap.Add (new TargetInfo (solConf, solPlat), new TargetInfo (projConf, projPlat));
432 projectConfigurationPlatform = projectConfigurationPlatform.NextMatch ();
434 Match projectConfigurationPlatformBuild = projectConfigurationBuildRegex.Match (section);
435 while (projectConfigurationPlatformBuild.Success) {
436 Guid guid = new Guid (projectConfigurationPlatformBuild.Groups[1].Value);
437 ProjectInfo projectInfo;
438 if (!projectInfos.TryGetValue (guid, out projectInfo)) {
439 if (!missingGuids.Contains (guid)) {
440 RaiseWarning (0, string.Format("Failed to find project {0}", guid));
441 missingGuids.Add (guid);
443 projectConfigurationPlatformBuild = projectConfigurationPlatformBuild.NextMatch ();
446 string solConf = projectConfigurationPlatformBuild.Groups[2].Value;
447 string solPlat = projectConfigurationPlatformBuild.Groups[3].Value;
448 string projConf = projectConfigurationPlatformBuild.Groups[4].Value;
449 string projPlat = projectConfigurationPlatformBuild.Groups[5].Value;
450 // hack, what are they doing here?
451 if (projPlat == "Any CPU")
453 projectInfo.TargetMap[new TargetInfo (solConf, solPlat)] = new TargetInfo (projConf, projPlat, true);
454 projectConfigurationPlatformBuild = projectConfigurationPlatformBuild.NextMatch ();
458 void ParseSolutionProperties (string section)
462 void AddCurrentSolutionConfigurationContents (Project p, List<TargetInfo> solutionTargets,
463 Dictionary<Guid, ProjectInfo> projectInfos,
464 Dictionary<Guid, ProjectInfo> websiteProjectInfos)
466 TargetInfo default_target_info = new TargetInfo ("Debug", "Any CPU");
467 if (solutionTargets.Count > 0) {
469 foreach (TargetInfo tinfo in solutionTargets) {
470 if (String.Compare (tinfo.Platform, "Mixed Platforms") == 0) {
471 default_target_info = tinfo;
478 default_target_info = solutionTargets [0];
481 AddDefaultSolutionConfiguration (p, default_target_info);
483 foreach (TargetInfo solutionTarget in solutionTargets) {
484 BuildPropertyGroup platformPropertyGroup = p.AddNewPropertyGroup (false);
485 platformPropertyGroup.Condition = string.Format (
486 " ('$(Configuration)' == '{0}') and ('$(Platform)' == '{1}') ",
487 solutionTarget.Configuration,
488 solutionTarget.Platform
491 StringBuilder solutionConfigurationContents = new StringBuilder ();
492 solutionConfigurationContents.Append ("<SolutionConfiguration xmlns=\"\">");
493 foreach (KeyValuePair<Guid, ProjectInfo> projectInfo in projectInfos) {
494 AddProjectConfigurationItems (projectInfo.Key, projectInfo.Value, solutionTarget, solutionConfigurationContents);
496 solutionConfigurationContents.Append ("</SolutionConfiguration>");
498 platformPropertyGroup.AddNewProperty ("CurrentSolutionConfigurationContents",
499 solutionConfigurationContents.ToString ());
503 void AddProjectReferences (Project p, Dictionary<Guid, ProjectInfo> projectInfos)
505 BuildItemGroup big = p.AddNewItemGroup ();
506 foreach (KeyValuePair<Guid, ProjectInfo> pair in projectInfos)
507 big.AddNewItem ("ProjectReference", pair.Value.FileName);
510 void AddProjectConfigurationItems (Guid guid, ProjectInfo projectInfo, TargetInfo solutionTarget,
511 StringBuilder solutionConfigurationContents)
513 foreach (KeyValuePair<TargetInfo, TargetInfo> targetInfo in projectInfo.TargetMap) {
514 if (solutionTarget.Configuration == targetInfo.Key.Configuration &&
515 solutionTarget.Platform == targetInfo.Key.Platform) {
516 solutionConfigurationContents.AppendFormat (
517 "<ProjectConfiguration Project=\"{0}\">{1}|{2}</ProjectConfiguration>",
518 guid.ToString ("B").ToUpper (), targetInfo.Value.Configuration, targetInfo.Value.Platform);
523 void AddDefaultSolutionConfiguration (Project p, TargetInfo target)
525 BuildPropertyGroup configurationPropertyGroup = p.AddNewPropertyGroup (true);
526 configurationPropertyGroup.Condition = " '$(Configuration)' == '' ";
527 configurationPropertyGroup.AddNewProperty ("Configuration", target.Configuration);
529 BuildPropertyGroup platformPropertyGroup = p.AddNewPropertyGroup (true);
530 platformPropertyGroup.Condition = " '$(Platform)' == '' ";
531 platformPropertyGroup.AddNewProperty ("Platform", target.Platform);
533 // emit default for AspNetConfiguration also
534 BuildPropertyGroup aspNetConfigurationPropertyGroup = p.AddNewPropertyGroup (true);
535 aspNetConfigurationPropertyGroup.Condition = " ('$(AspNetConfiguration)' == '') ";
536 aspNetConfigurationPropertyGroup.AddNewProperty ("AspNetConfiguration", "$(Configuration)");
539 void AddWarningForMissingProjectConfiguration (Target target, string slnConfig, string slnPlatform, string projectName)
541 BuildTask task = target.AddNewTask ("Warning");
542 task.SetParameterValue ("Text",
543 String.Format ("The project configuration for project '{0}' corresponding " +
544 "to the solution configuration '{1}|{2}' was not found in the solution file.",
545 projectName, slnConfig, slnPlatform));
546 task.Condition = String.Format ("('$(Configuration)' == '{0}') and ('$(Platform)' == '{1}')",
547 slnConfig, slnPlatform);
551 // Website project methods
553 void AddWebsiteProperties (Project p, Dictionary<Guid, ProjectInfo> websiteProjectInfos,
554 Dictionary<Guid, ProjectInfo> projectInfos)
556 var propertyGroupByConfig = new Dictionary<string, BuildPropertyGroup> ();
557 foreach (KeyValuePair<Guid, ProjectInfo> infoPair in websiteProjectInfos) {
558 ProjectInfo info = infoPair.Value;
559 string projectGuid = infoPair.Key.ToString ();
561 ProjectSection section;
562 if (!info.ProjectSections.TryGetValue ("WebsiteProperties", out section)) {
563 RaiseWarning (0, String.Format ("Website project '{0}' does not have the required project section: WebsiteProperties. Ignoring project.", info.Name));
567 //parse project references
568 string [] ref_guids = null;
570 if (section.Properties.TryGetValue ("ProjectReferences", out references)) {
571 ref_guids = references.Split (new char [] {';'}, StringSplitOptions.RemoveEmptyEntries);
572 for (int i = 0; i < ref_guids.Length; i ++) {
574 ref_guids [i] = ref_guids [i].Split ('|') [0];
576 Guid r_guid = new Guid (ref_guids [i]);
577 ProjectInfo ref_info;
578 if (projectInfos.TryGetValue (r_guid, out ref_info))
579 // ignore if not found
580 info.Dependencies [r_guid] = ref_info;
584 foreach (KeyValuePair<string, string> pair in section.Properties) {
585 //looking for -- ConfigName.AspNetCompiler.PropName
586 string [] parts = pair.Key.Split ('.');
587 if (parts.Length != 3 || String.Compare (parts [1], "AspNetCompiler") != 0)
590 string config = parts [0];
591 string propertyName = parts [2];
593 BuildPropertyGroup bpg;
594 if (!propertyGroupByConfig.TryGetValue (config, out bpg)) {
595 bpg = p.AddNewPropertyGroup (true);
596 bpg.Condition = String.Format (" '$(AspNetConfiguration)' == '{0}' ", config);
597 propertyGroupByConfig [config] = bpg;
600 bpg.AddNewProperty (String.Format ("Project_{0}_AspNet{1}", projectGuid, propertyName),
603 if (!info.AspNetConfigurations.Contains (config))
604 info.AspNetConfigurations.Add (config);
609 // For WebSite projects
610 // The main "Build" target:
611 // 1. builds all non-website projects
612 // 2. calls target for website project
613 // - gets target path for the referenced projects
614 // - Resolves dependencies, satellites etc for the
615 // referenced project assemblies, and copies them
617 void AddWebsiteTargets (Project p, Dictionary<Guid, ProjectInfo> websiteProjectInfos,
618 Dictionary<Guid, ProjectInfo> projectInfos, List<ProjectInfo>[] infosByLevel,
619 List<TargetInfo> solutionTargets)
621 foreach (ProjectInfo w_info in websiteProjectInfos.Values) {
622 // gets a linear list of dependencies
623 List<ProjectInfo> depInfos = new List<ProjectInfo> ();
624 foreach (List<ProjectInfo> pinfos in infosByLevel) {
625 foreach (ProjectInfo pinfo in pinfos)
626 if (w_info.Dependencies.ContainsKey (pinfo.Guid))
627 depInfos.Add (pinfo);
630 foreach (string buildTarget in new string [] {"Build", "Rebuild"})
631 AddWebsiteTarget (p, w_info, projectInfos, depInfos, solutionTargets, buildTarget);
633 // clean/publish are not supported for website projects
634 foreach (string buildTarget in new string [] {"Clean", "Publish"})
635 AddWebsiteUnsupportedTarget (p, w_info, depInfos, buildTarget);
639 void AddWebsiteTarget (Project p, ProjectInfo webProjectInfo,
640 Dictionary<Guid, ProjectInfo> projectInfos, List<ProjectInfo> depInfos,
641 List<TargetInfo> solutionTargets, string buildTarget)
643 string w_guid = webProjectInfo.Guid.ToString ().ToUpper ();
645 Target target = p.Targets.AddNewTarget (GetTargetNameForProject (webProjectInfo.Name, buildTarget));
646 target.Condition = "'$(CurrentSolutionConfigurationContents)' != ''";
647 target.DependsOnTargets = GetWebsiteDependsOnTarget (depInfos, buildTarget);
649 // this item collects all the references
650 string final_ref_item = String.Format ("Project_{0}_References{1}", w_guid,
651 buildTarget != "Build" ? "_" + buildTarget : String.Empty);
653 foreach (TargetInfo targetInfo in solutionTargets) {
655 foreach (ProjectInfo depInfo in depInfos) {
656 TargetInfo projectTargetInfo;
657 if (!depInfo.TargetMap.TryGetValue (targetInfo, out projectTargetInfo))
658 // Ignore, no config, so no target path
661 // GetTargetPath from the referenced project
662 AddWebsiteMSBuildTaskForReference (target, depInfo, projectTargetInfo, targetInfo,
663 final_ref_item, ref_num);
668 // resolve the references
669 AddWebsiteResolveAndCopyReferencesTasks (target, webProjectInfo, final_ref_item, w_guid);
672 // emits the MSBuild task to GetTargetPath for the referenced project
673 void AddWebsiteMSBuildTaskForReference (Target target, ProjectInfo depInfo, TargetInfo projectTargetInfo,
674 TargetInfo solutionTargetInfo, string final_ref_item, int ref_num)
676 BuildTask task = target.AddNewTask ("MSBuild");
677 task.SetParameterValue ("Projects", depInfo.FileName);
678 task.SetParameterValue ("Targets", "GetTargetPath");
680 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));
681 task.Condition = string.Format (" ('$(Configuration)' == '{0}') and ('$(Platform)' == '{1}') ", solutionTargetInfo.Configuration, solutionTargetInfo.Platform);
683 string ref_item = String.Format ("{0}_{1}",
684 final_ref_item, ref_num);
686 task.AddOutputItem ("TargetOutputs", ref_item);
688 task = target.AddNewTask ("CreateItem");
689 task.SetParameterValue ("Include", String.Format ("@({0})", ref_item));
690 task.SetParameterValue ("AdditionalMetadata", String.Format ("Guid={{{0}}}",
691 depInfo.Guid.ToString ().ToUpper ()));
692 task.AddOutputItem ("Include", final_ref_item);
695 void AddWebsiteResolveAndCopyReferencesTasks (Target target, ProjectInfo webProjectInfo,
696 string final_ref_item, string w_guid)
698 BuildTask task = target.AddNewTask ("ResolveAssemblyReference");
699 task.SetParameterValue ("Assemblies", String.Format ("@({0}->'%(FullPath)')", final_ref_item));
700 task.SetParameterValue ("TargetFrameworkDirectories", "$(TargetFrameworkPath)");
701 task.SetParameterValue ("SearchPaths", "{RawFileName};{TargetFrameworkDirectory};{GAC}");
702 task.SetParameterValue ("FindDependencies", "true");
703 task.SetParameterValue ("FindSatellites", "true");
704 task.SetParameterValue ("FindRelatedFiles", "true");
705 task.Condition = String.Format ("Exists ('%({0}.Identity)')", final_ref_item);
707 string copylocal_item = String.Format ("{0}_CopyLocalFiles", final_ref_item);
708 task.AddOutputItem ("CopyLocalFiles", copylocal_item);
710 // Copy the references
711 task = target.AddNewTask ("Copy");
712 task.SetParameterValue ("SourceFiles", String.Format ("@({0})", copylocal_item));
713 task.SetParameterValue ("DestinationFiles", String.Format (
714 "@({0}->'$(Project_{1}_AspNetPhysicalPath)\\Bin\\%(DestinationSubDirectory)%(Filename)%(Extension)')",
715 copylocal_item, w_guid));
717 // AspNetConfiguration, is config for the website project, useful
718 // for overriding from command line
719 StringBuilder cond = new StringBuilder ();
720 foreach (string config in webProjectInfo.AspNetConfigurations) {
722 cond.Append (" or ");
723 cond.AppendFormat (" ('$(AspNetConfiguration)' == '{0}') ", config);
725 task.Condition = cond.ToString ();
727 task = target.AddNewTask ("Message");
728 cond = new StringBuilder ();
729 foreach (string config in webProjectInfo.AspNetConfigurations) {
731 cond.Append (" and ");
732 cond.AppendFormat (" ('$(AspNetConfiguration)' != '{0}') ", config);
734 task.Condition = cond.ToString ();
735 task.SetParameterValue ("Text", "Skipping as the '$(AspNetConfiguration)' configuration is " +
736 "not supported by this website project.");
739 void AddWebsiteUnsupportedTarget (Project p, ProjectInfo webProjectInfo, List<ProjectInfo> depInfos,
742 Target target = p.Targets.AddNewTarget (GetTargetNameForProject (webProjectInfo.Name, buildTarget));
743 target.DependsOnTargets = GetWebsiteDependsOnTarget (depInfos, buildTarget);
745 BuildTask task = target.AddNewTask ("Message");
746 task.SetParameterValue ("Text", String.Format (
747 "Target '{0}' not support for website projects", buildTarget));
750 string GetWebsiteDependsOnTarget (List<ProjectInfo> depInfos, string buildTarget)
752 StringBuilder deps = new StringBuilder ();
753 foreach (ProjectInfo pinfo in depInfos) {
756 deps.Append (GetTargetNameForProject (pinfo.Name, buildTarget));
758 deps.Append (";GetFrameworkPath");
759 return deps.ToString ();
762 void AddGetFrameworkPathTarget (Project p)
764 Target t = p.Targets.AddNewTarget ("GetFrameworkPath");
765 BuildTask task = t.AddNewTask ("GetFrameworkPath");
766 task.AddOutputProperty ("Path", "TargetFrameworkPath");
769 void AddValidateSolutionConfiguration (Project p)
771 Target t = p.Targets.AddNewTarget ("ValidateSolutionConfiguration");
772 BuildTask task = t.AddNewTask ("Warning");
773 task.SetParameterValue ("Text", "On windows, an environment variable 'Platform' is set to MCD sometimes, and this overrides the Platform property" +
774 " for xbuild, which could be an invalid Platform for this solution file. And so you are getting the following error." +
775 " You could override it by either setting the environment variable to nothing, as\n" +
777 "Or explicity specify its value on the command line, as\n" +
778 " xbuild Foo.sln /p:Platform=Release");
779 task.Condition = "('$(CurrentSolutionConfigurationContents)' == '') and ('$(SkipInvalidConfigurations)' != 'true')" +
780 " and '$(Platform)' == 'MCD' and '$(OS)' == 'Windows_NT'";
782 task = t.AddNewTask ("Error");
783 task.SetParameterValue ("Text", "Invalid solution configuration and platform: \"$(Configuration)|$(Platform)\".");
784 task.Condition = "('$(CurrentSolutionConfigurationContents)' == '') and ('$(SkipInvalidConfigurations)' != 'true')";
785 task = t.AddNewTask ("Warning");
786 task.SetParameterValue ("Text", "Invalid solution configuration and platform: \"$(Configuration)|$(Platform)\".");
787 task.Condition = "('$(CurrentSolutionConfigurationContents)' == '') and ('$(SkipInvalidConfigurations)' == 'true')";
788 task = t.AddNewTask ("Message");
789 task.SetParameterValue ("Text", "Building solution configuration \"$(Configuration)|$(Platform)\".");
790 task.Condition = "'$(CurrentSolutionConfigurationContents)' != ''";
793 void AddProjectTargets (Project p, List<TargetInfo> solutionTargets, Dictionary<Guid, ProjectInfo> projectInfos)
795 foreach (KeyValuePair<Guid, ProjectInfo> projectInfo in projectInfos) {
796 ProjectInfo project = projectInfo.Value;
797 foreach (string buildTarget in buildTargets) {
798 string target_name = GetTargetNameForProject (project.Name, buildTarget);
799 bool is_build_or_rebuild = buildTarget == "Build" || buildTarget == "Rebuild";
800 Target target = p.Targets.AddNewTarget (target_name);
801 target.Condition = "'$(CurrentSolutionConfigurationContents)' != ''";
803 if (is_build_or_rebuild)
804 target.Outputs = "@(CollectedBuildOutput)";
805 if (project.Dependencies.Count > 0)
806 target.DependsOnTargets = String.Join (";",
807 project.Dependencies.Values.Select (
808 di => GetTargetNameForProject (di.Name, buildTarget)).ToArray ());
810 foreach (TargetInfo targetInfo in solutionTargets) {
811 BuildTask task = null;
812 TargetInfo projectTargetInfo;
813 if (!project.TargetMap.TryGetValue (targetInfo, out projectTargetInfo)) {
814 AddWarningForMissingProjectConfiguration (target, targetInfo.Configuration,
815 targetInfo.Platform, project.Name);
818 if (projectTargetInfo.Build) {
819 task = target.AddNewTask ("MSBuild");
820 task.SetParameterValue ("Projects", project.FileName);
821 task.SetParameterValue ("ToolsVersion", "$(ProjectToolsVersion)");
822 if (is_build_or_rebuild)
823 task.AddOutputItem ("TargetOutputs", "CollectedBuildOutput");
825 if (buildTarget != "Build")
826 task.SetParameterValue ("Targets", buildTarget);
827 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));
829 task = target.AddNewTask ("Message");
830 task.SetParameterValue ("Text", string.Format ("Project \"{0}\" is disabled for solution configuration \"{1}|{2}\".", project.Name, targetInfo.Configuration, targetInfo.Platform));
832 task.Condition = string.Format (" ('$(Configuration)' == '{0}') and ('$(Platform)' == '{1}') ", targetInfo.Configuration, targetInfo.Platform);
839 string GetTargetNameForProject (string projectName, string buildTarget)
842 projectName = projectName.Replace ("\\", "/").Replace (".", "_");
843 string target_name = projectName +
844 (buildTarget == "Build" ? string.Empty : ":" + buildTarget);
846 if (IsBuildTargetName (projectName))
847 target_name = "Solution:" + target_name;
852 bool IsBuildTargetName (string name)
854 foreach (string tgt in buildTargets)
860 // returns number of levels
861 int AddBuildLevels (Project p, List<TargetInfo> solutionTargets, Dictionary<Guid, ProjectInfo> projectInfos,
862 ref List<ProjectInfo>[] infosByLevel)
864 infosByLevel = TopologicalSort<ProjectInfo> (projectInfos.Values);
866 foreach (TargetInfo targetInfo in solutionTargets) {
867 BuildItemGroup big = p.AddNewItemGroup ();
868 big.Condition = String.Format (" ('$(Configuration)' == '{0}') and ('$(Platform)' == '{1}') ",
869 targetInfo.Configuration, targetInfo.Platform);
871 //FIXME: every level has projects that can be built in parallel.
872 // levels are ordered on the basis of the dependency graph
874 for (int i = 0; i < infosByLevel.Length; i ++) {
875 string build_level = String.Format ("BuildLevel{0}", i);
876 string skip_level = String.Format ("SkipLevel{0}", i);
877 string missing_level = String.Format ("MissingConfigLevel{0}", i);
879 foreach (ProjectInfo projectInfo in infosByLevel [i]) {
880 TargetInfo projectTargetInfo;
881 if (!projectInfo.TargetMap.TryGetValue (targetInfo, out projectTargetInfo)) {
882 // missing project config
883 big.AddNewItem (missing_level, projectInfo.Name);
887 if (projectTargetInfo.Build) {
888 BuildItem item = big.AddNewItem (build_level, projectInfo.FileName);
889 item.SetMetadata ("Configuration", projectTargetInfo.Configuration);
890 item.SetMetadata ("Platform", projectTargetInfo.Platform);
893 big.AddNewItem (skip_level, projectInfo.Name);
899 return infosByLevel.Length;
902 void AddSolutionTargets (Project p, int num_levels, IEnumerable<ProjectInfo> websiteProjectInfos)
904 foreach (string buildTarget in buildTargets) {
905 Target t = p.Targets.AddNewTarget (buildTarget);
906 bool is_build_or_rebuild = buildTarget == "Build" || buildTarget == "Rebuild";
908 t.Condition = "'$(CurrentSolutionConfigurationContents)' != ''";
909 if (is_build_or_rebuild)
910 t.Outputs = "@(CollectedBuildOutput)";
912 BuildTask task = null;
913 for (int i = 0; i < num_levels; i ++) {
914 string level_str = String.Format ("BuildLevel{0}", i);
915 task = t.AddNewTask ("MSBuild");
916 task.SetParameterValue ("Condition", String.Format ("'@({0})' != ''", level_str));
917 task.SetParameterValue ("Projects", String.Format ("@({0})", level_str));
918 task.SetParameterValue ("ToolsVersion", "$(ProjectToolsVersion)");
919 task.SetParameterValue ("Properties",
920 string.Format ("Configuration=%(Configuration); Platform=%(Platform); BuildingSolutionFile=true; CurrentSolutionConfigurationContents=$(CurrentSolutionConfigurationContents); SolutionDir=$(SolutionDir); SolutionExt=$(SolutionExt); SolutionFileName=$(SolutionFileName); SolutionName=$(SolutionName); SolutionPath=$(SolutionPath)"));
921 if (buildTarget != "Build")
922 task.SetParameterValue ("Targets", buildTarget);
923 //FIXME: change this to BuildInParallel=true, when parallel
924 // build support gets added
925 task.SetParameterValue ("RunEachTargetSeparately", "true");
926 if (is_build_or_rebuild)
927 task.AddOutputItem ("TargetOutputs", "CollectedBuildOutput");
929 level_str = String.Format ("SkipLevel{0}", i);
930 task = t.AddNewTask ("Message");
931 task.Condition = String.Format ("'@({0})' != ''", level_str);
932 task.SetParameterValue ("Text",
933 String.Format ("The project '%({0}.Identity)' is disabled for solution " +
934 "configuration '$(Configuration)|$(Platform)'.", level_str));
936 level_str = String.Format ("MissingConfigLevel{0}", i);
937 task = t.AddNewTask ("Warning");
938 task.Condition = String.Format ("'@({0})' != ''", level_str);
939 task.SetParameterValue ("Text",
940 String.Format ("The project configuration for project '%({0}.Identity)' " +
941 "corresponding to the solution configuration " +
942 "'$(Configuration)|$(Platform)' was not found.", level_str));
945 // "build" website projects also
946 StringBuilder w_targets = new StringBuilder ();
947 foreach (ProjectInfo info in websiteProjectInfos) {
948 if (w_targets.Length > 0)
949 w_targets.Append (";");
950 w_targets.Append (GetTargetNameForProject (info.Name, buildTarget));
953 task = t.AddNewTask ("CallTarget");
954 task.SetParameterValue ("Targets", w_targets.ToString ());
955 task.SetParameterValue ("RunEachTargetSeparately", "true");
959 // Sorts the ProjectInfo dependency graph, to obtain
960 // a series of build levels with projects. Projects
961 // in each level can be run parallel (no inter-dependency).
962 static List<T>[] TopologicalSort<T> (IEnumerable<T> items) where T: ProjectInfo
965 allItems = items as IList<T>;
966 if (allItems == null)
967 allItems = new List<T> (items);
969 bool[] inserted = new bool[allItems.Count];
970 bool[] triedToInsert = new bool[allItems.Count];
971 int[] levels = new int [allItems.Count];
974 for (int i = 0; i < allItems.Count; ++i) {
975 int d = Insert<T> (i, allItems, levels, inserted, triedToInsert);
980 // Separate out the project infos by build level
981 List<T>[] infosByLevel = new List<T>[maxdepth];
982 for (int i = 0; i < levels.Length; i ++) {
983 int level = levels [i] - 1;
984 if (infosByLevel [level] == null)
985 infosByLevel [level] = new List<T> ();
987 infosByLevel [level].Add (allItems [i]);
993 // returns level# for the project
994 static int Insert<T> (int index, IList<T> allItems, int[] levels, bool[] inserted, bool[] triedToInsert)
997 if (inserted [index])
998 return levels [index];
1000 if (triedToInsert[index])
1001 throw new InvalidOperationException (String.Format (
1002 "Cyclic dependency involving project {0} found in the project dependency graph",
1003 allItems [index].Name));
1005 triedToInsert[index] = true;
1006 ProjectInfo insertItem = allItems[index];
1009 foreach (ProjectInfo dependency in insertItem.Dependencies.Values) {
1010 for (int j = 0; j < allItems.Count; ++j) {
1011 ProjectInfo checkItem = allItems [j];
1012 if (dependency.FileName == checkItem.FileName) {
1013 int d = Insert (j, allItems, levels, inserted, triedToInsert);
1014 maxdepth = d > maxdepth ? d : maxdepth;
1019 levels [index] = maxdepth + 1;
1020 inserted [index] = true;
1022 return levels [index];
1025 public static IEnumerable<string> GetAllProjectFileNames (string solutionFile)
1027 StreamReader reader = new StreamReader (solutionFile);
1028 string line = reader.ReadToEnd ();
1029 line = line.Replace ("\r\n", "\n");
1030 string soln_dir = Path.GetDirectoryName (solutionFile);
1032 Match m = projectRegex.Match (line);
1034 if (String.Compare (m.Groups [1].Value, solutionFolderGuid,
1035 StringComparison.InvariantCultureIgnoreCase) != 0)
1036 yield return Path.Combine (soln_dir, m.Groups [3].Value).Replace ("\\", "/");