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.
34 using System.Collections.Generic;
37 using System.Text.RegularExpressions;
39 using Microsoft.Build.BuildEngine;
41 namespace Mono.XBuild.CommandLine {
44 public string FileName;
47 public ProjectInfo (string name, string fileName)
53 public Dictionary<TargetInfo, TargetInfo> TargetMap = new Dictionary<TargetInfo, TargetInfo> ();
54 public Dictionary<Guid, ProjectInfo> Dependencies = new Dictionary<Guid, ProjectInfo> ();
55 public Dictionary<string, ProjectSection> ProjectSections = new Dictionary<string, ProjectSection> ();
56 public List<string> AspNetConfigurations = new List<string> ();
59 class ProjectSection {
61 public Dictionary<string, string> Properties = new Dictionary<string, string> ();
63 public ProjectSection (string name)
70 public string Configuration;
71 public string Platform;
74 public TargetInfo (string configuration, string platform)
75 : this (configuration, platform, false)
79 public TargetInfo (string configuration, string platform, bool build)
81 Configuration = configuration;
88 internal delegate void RaiseWarningHandler (int errorNumber, string message);
90 class SolutionParser {
91 static string[] buildTargets = new string[] { "Build", "Clean", "Rebuild", "Publish" };
93 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}}";
95 static Regex slnVersionRegex = new Regex (@"Microsoft Visual Studio Solution File, Format Version (\d?\d.\d\d)");
96 static Regex projectRegex = new Regex ("Project\\(\"(" + guidExpression + ")\"\\) = \"(.*?)\", \"(.*?)\", \"(" + guidExpression + ")\"(\\s*?)((\\s*?)ProjectSection\\((.*?)\\) = (.*?)EndProjectSection(\\s*?))*(\\s*?)(EndProject)?", RegexOptions.Singleline);
97 static Regex projectDependenciesRegex = new Regex ("ProjectSection\\((.*?)\\) = \\w*(.*?)EndProjectSection", RegexOptions.Singleline);
98 static Regex projectDependencyRegex = new Regex ("\\s*(" + guidExpression + ") = (" + guidExpression + ")");
99 static Regex projectSectionPropertiesRegex = new Regex ("\\s*(?<name>.*) = \"(?<value>.*)\"");
101 static Regex globalRegex = new Regex ("Global(.*)EndGlobal", RegexOptions.Singleline);
102 static Regex globalSectionRegex = new Regex ("GlobalSection\\((.*?)\\) = \\w*(.*?)EndGlobalSection", RegexOptions.Singleline);
104 static Regex solutionConfigurationRegex = new Regex ("\\s*(.*?)\\|(.*?) = (.*?)\\|(.+)");
105 static Regex projectConfigurationActiveCfgRegex = new Regex ("\\s*(" + guidExpression + ")\\.(.+?)\\|(.+?)\\.ActiveCfg = (.+?)\\|(.+)");
106 static Regex projectConfigurationBuildRegex = new Regex ("\\s*(" + guidExpression + ")\\.(.*?)\\|(.*?)\\.Build\\.0 = (.*?)\\|(.+)");
108 static string solutionFolderGuid = "{2150E333-8FDC-42A3-9474-1A3956D46DE8}";
109 static string vcprojGuid = "{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}";
110 static string websiteProjectGuid = "{E24C65DC-7377-472B-9ABA-BC803B73C61A}";
112 RaiseWarningHandler RaiseWarning;
114 public void ParseSolution (string file, Project p, RaiseWarningHandler RaiseWarning)
116 this.RaiseWarning = RaiseWarning;
117 EmitBeforeImports (p, file);
119 AddGeneralSettings (file, p);
121 StreamReader reader = new StreamReader (file);
122 string slnVersion = GetSlnFileVersion (reader);
123 if (slnVersion == "11.00")
124 p.DefaultToolsVersion = "4.0";
125 else if (slnVersion == "10.00")
126 p.DefaultToolsVersion = "3.5";
128 p.DefaultToolsVersion = "2.0";
130 string line = reader.ReadToEnd ();
131 line = line.Replace ("\r\n", "\n");
132 string solutionDir = Path.GetDirectoryName (file);
134 List<TargetInfo> solutionTargets = new List<TargetInfo> ();
135 Dictionary<Guid, ProjectInfo> projectInfos = new Dictionary<Guid, ProjectInfo> ();
136 Dictionary<Guid, ProjectInfo> websiteProjectInfos = new Dictionary<Guid, ProjectInfo> ();
137 List<ProjectInfo>[] infosByLevel = null;
138 Dictionary<Guid, ProjectInfo> unsupportedProjectInfos = new Dictionary<Guid, ProjectInfo> ();
140 Match m = projectRegex.Match (line);
142 ProjectInfo projectInfo = new ProjectInfo (m.Groups[2].Value,
143 Path.GetFullPath (Path.Combine (solutionDir,
144 m.Groups [3].Value.Replace ('\\', Path.DirectorySeparatorChar))));
145 if (String.Compare (m.Groups [1].Value, solutionFolderGuid,
146 StringComparison.InvariantCultureIgnoreCase) == 0) {
147 // Ignore solution folders
152 projectInfo.Guid = new Guid (m.Groups [4].Value);
154 if (String.Compare (m.Groups [1].Value, vcprojGuid,
155 StringComparison.InvariantCultureIgnoreCase) == 0) {
157 RaiseWarning (0, string.Format("Ignoring vcproj '{0}'.", projectInfo.Name));
159 unsupportedProjectInfos [projectInfo.Guid] = projectInfo;
164 if (String.Compare (m.Groups [1].Value, websiteProjectGuid,
165 StringComparison.InvariantCultureIgnoreCase) == 0)
166 websiteProjectInfos.Add (new Guid (m.Groups[4].Value), projectInfo);
168 projectInfos.Add (projectInfo.Guid, projectInfo);
170 Match projectSectionMatch = projectDependenciesRegex.Match (m.Groups[6].Value);
171 while (projectSectionMatch.Success) {
172 string section_name = projectSectionMatch.Groups [1].Value;
173 if (String.Compare (section_name, "ProjectDependencies") == 0) {
174 Match projectDependencyMatch = projectDependencyRegex.Match (projectSectionMatch.Value);
175 while (projectDependencyMatch.Success) {
176 // we might not have projectInfo available right now, so
177 // set it to null, and fill it in later
178 projectInfo.Dependencies [new Guid (projectDependencyMatch.Groups[1].Value)] = null;
179 projectDependencyMatch = projectDependencyMatch.NextMatch ();
182 ProjectSection section = new ProjectSection (section_name);
183 Match propertiesMatch = projectSectionPropertiesRegex.Match (
184 projectSectionMatch.Groups [2].Value);
185 while (propertiesMatch.Success) {
186 section.Properties [propertiesMatch.Groups ["name"].Value] =
187 propertiesMatch.Groups ["value"].Value;
189 propertiesMatch = propertiesMatch.NextMatch ();
192 projectInfo.ProjectSections [section_name] = section;
194 projectSectionMatch = projectSectionMatch.NextMatch ();
199 foreach (ProjectInfo projectInfo in projectInfos.Values) {
200 string filename = projectInfo.FileName;
201 string projectDir = Path.GetDirectoryName (filename);
203 if (!File.Exists (filename)) {
204 RaiseWarning (0, String.Format ("Project file {0} referenced in the solution file, " +
205 "not found. Ignoring.", filename));
209 Project currentProject = p.ParentEngine.CreateNewProject ();
211 currentProject.Load (filename, ProjectLoadSettings.IgnoreMissingImports);
212 } catch (InvalidProjectFileException e) {
213 RaiseWarning (0, e.Message);
217 foreach (BuildItem bi in currentProject.GetEvaluatedItemsByName ("ProjectReference")) {
218 ProjectInfo info = null;
219 string projectReferenceGuid = bi.GetEvaluatedMetadata ("Project");
220 bool hasGuid = !String.IsNullOrEmpty (projectReferenceGuid);
222 // try to resolve the ProjectReference by GUID
223 // and fallback to project filename
226 Guid guid = new Guid (projectReferenceGuid);
227 projectInfos.TryGetValue (guid, out info);
228 if (info == null && unsupportedProjectInfos.TryGetValue (guid, out info)) {
229 RaiseWarning (0, String.Format (
230 "{0}: ProjectReference '{1}' is of an unsupported type. Ignoring.",
231 filename, bi.Include));
236 if (info == null || !hasGuid) {
237 // Project not found by guid or guid not available
238 // Try to find by project file
240 string fullpath = Path.GetFullPath (Path.Combine (projectDir, bi.Include.Replace ('\\', Path.DirectorySeparatorChar)));
241 info = projectInfos.Values.FirstOrDefault (pi => pi.FileName == fullpath);
244 if (unsupportedProjectInfos.Values.Any (pi => pi.FileName == fullpath))
245 RaiseWarning (0, String.Format (
246 "{0}: ProjectReference '{1}' is of an unsupported type. Ignoring.",
247 filename, bi.Include));
249 RaiseWarning (0, String.Format (
250 "{0}: ProjectReference '{1}' not found, neither by guid '{2}' nor by project file name '{3}'.",
251 filename, bi.Include, projectReferenceGuid.Replace ("{", "").Replace ("}", ""), fullpath));
257 projectInfo.Dependencies [info.Guid] = info;
261 // fill in the project info for deps found in the .sln file
262 foreach (ProjectInfo projectInfo in projectInfos.Values) {
263 List<Guid> missingInfos = new List<Guid> ();
264 foreach (KeyValuePair<Guid, ProjectInfo> dependency in projectInfo.Dependencies) {
265 if (dependency.Value == null)
266 missingInfos.Add (dependency.Key);
269 foreach (Guid guid in missingInfos) {
271 if (projectInfos.TryGetValue (guid, out info))
272 projectInfo.Dependencies [guid] = info;
274 projectInfo.Dependencies.Remove (guid);
278 Match globalMatch = globalRegex.Match (line);
279 Match globalSectionMatch = globalSectionRegex.Match (globalMatch.Groups[1].Value);
280 while (globalSectionMatch.Success) {
281 string sectionType = globalSectionMatch.Groups[1].Value;
282 switch (sectionType) {
283 case "SolutionConfigurationPlatforms":
284 ParseSolutionConfigurationPlatforms (globalSectionMatch.Groups[2].Value, solutionTargets);
286 case "ProjectConfigurationPlatforms":
287 ParseProjectConfigurationPlatforms (globalSectionMatch.Groups[2].Value,
288 projectInfos, websiteProjectInfos);
290 case "SolutionProperties":
291 ParseSolutionProperties (globalSectionMatch.Groups[2].Value);
293 case "NestedProjects":
295 case "MonoDevelopProperties":
298 RaiseWarning (0, string.Format("Don't know how to handle GlobalSection {0}, Ignoring.", sectionType));
301 globalSectionMatch = globalSectionMatch.NextMatch ();
304 int num_levels = AddBuildLevels (p, solutionTargets, projectInfos, ref infosByLevel);
306 AddCurrentSolutionConfigurationContents (p, solutionTargets, projectInfos, websiteProjectInfos);
307 AddProjectReferences (p, projectInfos);
308 AddWebsiteProperties (p, websiteProjectInfos, projectInfos);
309 AddValidateSolutionConfiguration (p);
311 EmitAfterImports (p, file);
313 AddGetFrameworkPathTarget (p);
314 AddWebsiteTargets (p, websiteProjectInfos, projectInfos, infosByLevel, solutionTargets);
315 AddProjectTargets (p, solutionTargets, projectInfos);
316 AddSolutionTargets (p, num_levels, websiteProjectInfos.Values);
319 string GetSlnFileVersion (StreamReader reader)
321 string strInput = null;
324 strInput = reader.ReadLine();
325 if (strInput == null)
328 match = slnVersionRegex.Match(strInput);
329 if (!match.Success) {
330 strInput = reader.ReadLine();
331 if (strInput == null)
333 match = slnVersionRegex.Match (strInput);
337 return match.Groups[1].Value;
342 void EmitBeforeImports (Project p, string file)
345 p.AddNewImport ("$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\SolutionFile\\ImportBefore\\*",
346 "'$(ImportByWildcardBeforeSolution)' != 'false' and " +
347 "Exists('$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\SolutionFile\\ImportBefore')");
350 string before_filename = Path.Combine (Path.GetDirectoryName (file), "before." + Path.GetFileName (file) + ".targets");
351 p.AddNewImport (before_filename, String.Format ("Exists ('{0}')", before_filename));
354 void EmitAfterImports (Project p, string file)
357 p.AddNewImport ("$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\SolutionFile\\ImportAfter\\*",
358 "'$(ImportByWildcardAfterSolution)' != 'false' and " +
359 "Exists('$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\SolutionFile\\ImportAfter')");
362 string after_filename = Path.Combine (Path.GetDirectoryName (file), "after." + Path.GetFileName (file) + ".targets");
363 p.AddNewImport (after_filename, String.Format ("Exists ('{0}')", after_filename));
366 void AddGeneralSettings (string solutionFile, Project p)
368 p.DefaultTargets = "Build";
369 p.InitialTargets = "ValidateSolutionConfiguration";
370 p.AddNewUsingTaskFromAssemblyName ("CreateTemporaryVCProject", "Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
371 p.AddNewUsingTaskFromAssemblyName ("ResolveVCProjectOutput", "Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
373 string solutionFilePath = Path.GetFullPath (solutionFile);
374 BuildPropertyGroup solutionPropertyGroup = p.AddNewPropertyGroup (true);
375 solutionPropertyGroup.AddNewProperty ("SolutionDir", Path.GetDirectoryName (solutionFilePath) + Path.DirectorySeparatorChar);
376 solutionPropertyGroup.AddNewProperty ("SolutionExt", Path.GetExtension (solutionFile));
377 solutionPropertyGroup.AddNewProperty ("SolutionFileName", Path.GetFileName (solutionFile));
378 solutionPropertyGroup.AddNewProperty ("SolutionName", Path.GetFileNameWithoutExtension (solutionFile));
379 solutionPropertyGroup.AddNewProperty ("SolutionPath", solutionFilePath);
382 void ParseSolutionConfigurationPlatforms (string section, List<TargetInfo> solutionTargets)
384 Match solutionConfigurationPlatform = solutionConfigurationRegex.Match (section);
385 while (solutionConfigurationPlatform.Success) {
386 string solutionConfiguration = solutionConfigurationPlatform.Groups[1].Value;
387 string solutionPlatform = solutionConfigurationPlatform.Groups[2].Value;
388 solutionTargets.Add (new TargetInfo (solutionConfiguration, solutionPlatform));
389 solutionConfigurationPlatform = solutionConfigurationPlatform.NextMatch ();
393 // ignores the website projects, in the websiteProjectInfos
394 void ParseProjectConfigurationPlatforms (string section, Dictionary<Guid, ProjectInfo> projectInfos,
395 Dictionary<Guid, ProjectInfo> websiteProjectInfos)
397 List<Guid> missingGuids = new List<Guid> ();
398 Match projectConfigurationPlatform = projectConfigurationActiveCfgRegex.Match (section);
399 while (projectConfigurationPlatform.Success) {
400 Guid guid = new Guid (projectConfigurationPlatform.Groups[1].Value);
401 ProjectInfo projectInfo;
402 if (!projectInfos.TryGetValue (guid, out projectInfo)) {
403 if (!missingGuids.Contains (guid)) {
404 if (!websiteProjectInfos.ContainsKey (guid))
405 // ignore website projects
406 RaiseWarning (0, string.Format("Failed to find project {0}", guid));
407 missingGuids.Add (guid);
409 projectConfigurationPlatform = projectConfigurationPlatform.NextMatch ();
412 string solConf = projectConfigurationPlatform.Groups[2].Value;
413 string solPlat = projectConfigurationPlatform.Groups[3].Value;
414 string projConf = projectConfigurationPlatform.Groups[4].Value;
415 string projPlat = projectConfigurationPlatform.Groups[5].Value;
416 // hack, what are they doing here?
417 if (projPlat == "Any CPU")
419 projectInfo.TargetMap.Add (new TargetInfo (solConf, solPlat), new TargetInfo (projConf, projPlat));
420 projectConfigurationPlatform = projectConfigurationPlatform.NextMatch ();
422 Match projectConfigurationPlatformBuild = projectConfigurationBuildRegex.Match (section);
423 while (projectConfigurationPlatformBuild.Success) {
424 Guid guid = new Guid (projectConfigurationPlatformBuild.Groups[1].Value);
425 ProjectInfo projectInfo;
426 if (!projectInfos.TryGetValue (guid, out projectInfo)) {
427 if (!missingGuids.Contains (guid)) {
428 RaiseWarning (0, string.Format("Failed to find project {0}", guid));
429 missingGuids.Add (guid);
431 projectConfigurationPlatformBuild = projectConfigurationPlatformBuild.NextMatch ();
434 string solConf = projectConfigurationPlatformBuild.Groups[2].Value;
435 string solPlat = projectConfigurationPlatformBuild.Groups[3].Value;
436 string projConf = projectConfigurationPlatformBuild.Groups[4].Value;
437 string projPlat = projectConfigurationPlatformBuild.Groups[5].Value;
438 // hack, what are they doing here?
439 if (projPlat == "Any CPU")
441 projectInfo.TargetMap[new TargetInfo (solConf, solPlat)] = new TargetInfo (projConf, projPlat, true);
442 projectConfigurationPlatformBuild = projectConfigurationPlatformBuild.NextMatch ();
446 void ParseSolutionProperties (string section)
450 void AddCurrentSolutionConfigurationContents (Project p, List<TargetInfo> solutionTargets,
451 Dictionary<Guid, ProjectInfo> projectInfos,
452 Dictionary<Guid, ProjectInfo> websiteProjectInfos)
454 TargetInfo default_target_info = new TargetInfo ("Debug", "Any CPU");
455 if (solutionTargets.Count > 0) {
457 foreach (TargetInfo tinfo in solutionTargets) {
458 if (String.Compare (tinfo.Platform, "Mixed Platforms") == 0) {
459 default_target_info = tinfo;
466 default_target_info = solutionTargets [0];
469 AddDefaultSolutionConfiguration (p, default_target_info);
471 foreach (TargetInfo solutionTarget in solutionTargets) {
472 BuildPropertyGroup platformPropertyGroup = p.AddNewPropertyGroup (false);
473 platformPropertyGroup.Condition = string.Format (
474 " ('$(Configuration)' == '{0}') and ('$(Platform)' == '{1}') ",
475 solutionTarget.Configuration,
476 solutionTarget.Platform
479 StringBuilder solutionConfigurationContents = new StringBuilder ();
480 solutionConfigurationContents.Append ("<SolutionConfiguration xmlns=\"\">");
481 foreach (KeyValuePair<Guid, ProjectInfo> projectInfo in projectInfos) {
482 AddProjectConfigurationItems (projectInfo.Key, projectInfo.Value, solutionTarget, solutionConfigurationContents);
484 solutionConfigurationContents.Append ("</SolutionConfiguration>");
486 platformPropertyGroup.AddNewProperty ("CurrentSolutionConfigurationContents",
487 solutionConfigurationContents.ToString ());
491 void AddProjectReferences (Project p, Dictionary<Guid, ProjectInfo> projectInfos)
493 BuildItemGroup big = p.AddNewItemGroup ();
494 foreach (KeyValuePair<Guid, ProjectInfo> pair in projectInfos)
495 big.AddNewItem ("ProjectReference", pair.Value.FileName);
498 void AddProjectConfigurationItems (Guid guid, ProjectInfo projectInfo, TargetInfo solutionTarget,
499 StringBuilder solutionConfigurationContents)
501 foreach (KeyValuePair<TargetInfo, TargetInfo> targetInfo in projectInfo.TargetMap) {
502 if (solutionTarget.Configuration == targetInfo.Key.Configuration &&
503 solutionTarget.Platform == targetInfo.Key.Platform) {
504 solutionConfigurationContents.AppendFormat (
505 "<ProjectConfiguration Project=\"{0}\">{1}|{2}</ProjectConfiguration>",
506 guid.ToString ("B").ToUpper (), targetInfo.Value.Configuration, targetInfo.Value.Platform);
511 void AddDefaultSolutionConfiguration (Project p, TargetInfo target)
513 BuildPropertyGroup configurationPropertyGroup = p.AddNewPropertyGroup (true);
514 configurationPropertyGroup.Condition = " '$(Configuration)' == '' ";
515 configurationPropertyGroup.AddNewProperty ("Configuration", target.Configuration);
517 BuildPropertyGroup platformPropertyGroup = p.AddNewPropertyGroup (true);
518 platformPropertyGroup.Condition = " '$(Platform)' == '' ";
519 platformPropertyGroup.AddNewProperty ("Platform", target.Platform);
521 // emit default for AspNetConfiguration also
522 BuildPropertyGroup aspNetConfigurationPropertyGroup = p.AddNewPropertyGroup (true);
523 aspNetConfigurationPropertyGroup.Condition = " ('$(AspNetConfiguration)' == '') ";
524 aspNetConfigurationPropertyGroup.AddNewProperty ("AspNetConfiguration", "$(Configuration)");
527 void AddWarningForMissingProjectConfiguration (Target target, string slnConfig, string slnPlatform, string projectName)
529 BuildTask task = target.AddNewTask ("Warning");
530 task.SetParameterValue ("Text",
531 String.Format ("The project configuration for project '{0}' corresponding " +
532 "to the solution configuration '{1}|{2}' was not found in the solution file.",
533 projectName, slnConfig, slnPlatform));
534 task.Condition = String.Format ("('$(Configuration)' == '{0}') and ('$(Platform)' == '{1}')",
535 slnConfig, slnPlatform);
539 // Website project methods
541 void AddWebsiteProperties (Project p, Dictionary<Guid, ProjectInfo> websiteProjectInfos,
542 Dictionary<Guid, ProjectInfo> projectInfos)
544 var propertyGroupByConfig = new Dictionary<string, BuildPropertyGroup> ();
545 foreach (KeyValuePair<Guid, ProjectInfo> infoPair in websiteProjectInfos) {
546 ProjectInfo info = infoPair.Value;
547 string projectGuid = infoPair.Key.ToString ();
549 ProjectSection section;
550 if (!info.ProjectSections.TryGetValue ("WebsiteProperties", out section)) {
551 RaiseWarning (0, String.Format ("Website project '{0}' does not have the required project section: WebsiteProperties. Ignoring project.", info.Name));
555 //parse project references
556 string [] ref_guids = null;
558 if (section.Properties.TryGetValue ("ProjectReferences", out references)) {
559 ref_guids = references.Split (new char [] {';'}, StringSplitOptions.RemoveEmptyEntries);
560 for (int i = 0; i < ref_guids.Length; i ++) {
562 ref_guids [i] = ref_guids [i].Split ('|') [0];
564 Guid r_guid = new Guid (ref_guids [i]);
565 ProjectInfo ref_info;
566 if (projectInfos.TryGetValue (r_guid, out ref_info))
567 // ignore if not found
568 info.Dependencies [r_guid] = ref_info;
572 foreach (KeyValuePair<string, string> pair in section.Properties) {
573 //looking for -- ConfigName.AspNetCompiler.PropName
574 string [] parts = pair.Key.Split ('.');
575 if (parts.Length != 3 || String.Compare (parts [1], "AspNetCompiler") != 0)
578 string config = parts [0];
579 string propertyName = parts [2];
581 BuildPropertyGroup bpg;
582 if (!propertyGroupByConfig.TryGetValue (config, out bpg)) {
583 bpg = p.AddNewPropertyGroup (true);
584 bpg.Condition = String.Format (" '$(AspNetConfiguration)' == '{0}' ", config);
585 propertyGroupByConfig [config] = bpg;
588 bpg.AddNewProperty (String.Format ("Project_{0}_AspNet{1}", projectGuid, propertyName),
591 if (!info.AspNetConfigurations.Contains (config))
592 info.AspNetConfigurations.Add (config);
597 // For WebSite projects
598 // The main "Build" target:
599 // 1. builds all non-website projects
600 // 2. calls target for website project
601 // - gets target path for the referenced projects
602 // - Resolves dependencies, satellites etc for the
603 // referenced project assemblies, and copies them
605 void AddWebsiteTargets (Project p, Dictionary<Guid, ProjectInfo> websiteProjectInfos,
606 Dictionary<Guid, ProjectInfo> projectInfos, List<ProjectInfo>[] infosByLevel,
607 List<TargetInfo> solutionTargets)
609 foreach (ProjectInfo w_info in websiteProjectInfos.Values) {
610 // gets a linear list of dependencies
611 List<ProjectInfo> depInfos = new List<ProjectInfo> ();
612 foreach (List<ProjectInfo> pinfos in infosByLevel) {
613 foreach (ProjectInfo pinfo in pinfos)
614 if (w_info.Dependencies.ContainsKey (pinfo.Guid))
615 depInfos.Add (pinfo);
618 foreach (string buildTarget in new string [] {"Build", "Rebuild"})
619 AddWebsiteTarget (p, w_info, projectInfos, depInfos, solutionTargets, buildTarget);
621 // clean/publish are not supported for website projects
622 foreach (string buildTarget in new string [] {"Clean", "Publish"})
623 AddWebsiteUnsupportedTarget (p, w_info, depInfos, buildTarget);
627 void AddWebsiteTarget (Project p, ProjectInfo webProjectInfo,
628 Dictionary<Guid, ProjectInfo> projectInfos, List<ProjectInfo> depInfos,
629 List<TargetInfo> solutionTargets, string buildTarget)
631 string w_guid = webProjectInfo.Guid.ToString ().ToUpper ();
633 Target target = p.Targets.AddNewTarget (GetTargetNameForProject (webProjectInfo.Name, buildTarget));
634 target.Condition = "'$(CurrentSolutionConfigurationContents)' != ''";
635 target.DependsOnTargets = GetWebsiteDependsOnTarget (depInfos, buildTarget);
637 // this item collects all the references
638 string final_ref_item = String.Format ("Project_{0}_References{1}", w_guid,
639 buildTarget != "Build" ? "_" + buildTarget : String.Empty);
641 foreach (TargetInfo targetInfo in solutionTargets) {
643 foreach (ProjectInfo depInfo in depInfos) {
644 TargetInfo projectTargetInfo;
645 if (!depInfo.TargetMap.TryGetValue (targetInfo, out projectTargetInfo))
646 // Ignore, no config, so no target path
649 // GetTargetPath from the referenced project
650 AddWebsiteMSBuildTaskForReference (target, depInfo, projectTargetInfo, targetInfo,
651 final_ref_item, ref_num);
656 // resolve the references
657 AddWebsiteResolveAndCopyReferencesTasks (target, webProjectInfo, final_ref_item, w_guid);
660 // emits the MSBuild task to GetTargetPath for the referenced project
661 void AddWebsiteMSBuildTaskForReference (Target target, ProjectInfo depInfo, TargetInfo projectTargetInfo,
662 TargetInfo solutionTargetInfo, string final_ref_item, int ref_num)
664 BuildTask task = target.AddNewTask ("MSBuild");
665 task.SetParameterValue ("Projects", depInfo.FileName);
666 task.SetParameterValue ("Targets", "GetTargetPath");
668 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));
669 task.Condition = string.Format (" ('$(Configuration)' == '{0}') and ('$(Platform)' == '{1}') ", solutionTargetInfo.Configuration, solutionTargetInfo.Platform);
671 string ref_item = String.Format ("{0}_{1}",
672 final_ref_item, ref_num);
674 task.AddOutputItem ("TargetOutputs", ref_item);
676 task = target.AddNewTask ("CreateItem");
677 task.SetParameterValue ("Include", String.Format ("@({0})", ref_item));
678 task.SetParameterValue ("AdditionalMetadata", String.Format ("Guid={{{0}}}",
679 depInfo.Guid.ToString ().ToUpper ()));
680 task.AddOutputItem ("Include", final_ref_item);
683 void AddWebsiteResolveAndCopyReferencesTasks (Target target, ProjectInfo webProjectInfo,
684 string final_ref_item, string w_guid)
686 BuildTask task = target.AddNewTask ("ResolveAssemblyReference");
687 task.SetParameterValue ("Assemblies", String.Format ("@({0}->'%(FullPath)')", final_ref_item));
688 task.SetParameterValue ("TargetFrameworkDirectories", "$(TargetFrameworkPath)");
689 task.SetParameterValue ("SearchPaths", "{RawFileName};{TargetFrameworkDirectory};{GAC}");
690 task.SetParameterValue ("FindDependencies", "true");
691 task.SetParameterValue ("FindSatellites", "true");
692 task.SetParameterValue ("FindRelatedFiles", "true");
693 task.Condition = String.Format ("Exists ('%({0}.Identity)')", final_ref_item);
695 string copylocal_item = String.Format ("{0}_CopyLocalFiles", final_ref_item);
696 task.AddOutputItem ("CopyLocalFiles", copylocal_item);
698 // Copy the references
699 task = target.AddNewTask ("Copy");
700 task.SetParameterValue ("SourceFiles", String.Format ("@({0})", copylocal_item));
701 task.SetParameterValue ("DestinationFiles", String.Format (
702 "@({0}->'$(Project_{1}_AspNetPhysicalPath)\\Bin\\%(DestinationSubDirectory)%(Filename)%(Extension)')",
703 copylocal_item, w_guid));
705 // AspNetConfiguration, is config for the website project, useful
706 // for overriding from command line
707 StringBuilder cond = new StringBuilder ();
708 foreach (string config in webProjectInfo.AspNetConfigurations) {
710 cond.Append (" or ");
711 cond.AppendFormat (" ('$(AspNetConfiguration)' == '{0}') ", config);
713 task.Condition = cond.ToString ();
715 task = target.AddNewTask ("Message");
716 cond = new StringBuilder ();
717 foreach (string config in webProjectInfo.AspNetConfigurations) {
719 cond.Append (" and ");
720 cond.AppendFormat (" ('$(AspNetConfiguration)' != '{0}') ", config);
722 task.Condition = cond.ToString ();
723 task.SetParameterValue ("Text", "Skipping as the '$(AspNetConfiguration)' configuration is " +
724 "not supported by this website project.");
727 void AddWebsiteUnsupportedTarget (Project p, ProjectInfo webProjectInfo, List<ProjectInfo> depInfos,
730 Target target = p.Targets.AddNewTarget (GetTargetNameForProject (webProjectInfo.Name, buildTarget));
731 target.DependsOnTargets = GetWebsiteDependsOnTarget (depInfos, buildTarget);
733 BuildTask task = target.AddNewTask ("Message");
734 task.SetParameterValue ("Text", String.Format (
735 "Target '{0}' not support for website projects", buildTarget));
738 string GetWebsiteDependsOnTarget (List<ProjectInfo> depInfos, string buildTarget)
740 StringBuilder deps = new StringBuilder ();
741 foreach (ProjectInfo pinfo in depInfos) {
744 deps.Append (GetTargetNameForProject (pinfo.Name, buildTarget));
746 deps.Append (";GetFrameworkPath");
747 return deps.ToString ();
750 void AddGetFrameworkPathTarget (Project p)
752 Target t = p.Targets.AddNewTarget ("GetFrameworkPath");
753 BuildTask task = t.AddNewTask ("GetFrameworkPath");
754 task.AddOutputProperty ("Path", "TargetFrameworkPath");
757 void AddValidateSolutionConfiguration (Project p)
759 Target t = p.Targets.AddNewTarget ("ValidateSolutionConfiguration");
760 BuildTask task = t.AddNewTask ("Warning");
761 task.SetParameterValue ("Text", "On windows, an environment variable 'Platform' is set to MCD sometimes, and this overrides the Platform property" +
762 " for xbuild, which could be an invalid Platform for this solution file. And so you are getting the following error." +
763 " You could override it by either setting the environment variable to nothing, as\n" +
765 "Or explicity specify its value on the command line, as\n" +
766 " xbuild Foo.sln /p:Platform=Release");
767 task.Condition = "('$(CurrentSolutionConfigurationContents)' == '') and ('$(SkipInvalidConfigurations)' != 'true')" +
768 " and '$(Platform)' == 'MCD' and '$(OS)' == 'Windows_NT'";
770 task = t.AddNewTask ("Error");
771 task.SetParameterValue ("Text", "Invalid solution configuration and platform: \"$(Configuration)|$(Platform)\".");
772 task.Condition = "('$(CurrentSolutionConfigurationContents)' == '') and ('$(SkipInvalidConfigurations)' != 'true')";
773 task = t.AddNewTask ("Warning");
774 task.SetParameterValue ("Text", "Invalid solution configuration and platform: \"$(Configuration)|$(Platform)\".");
775 task.Condition = "('$(CurrentSolutionConfigurationContents)' == '') and ('$(SkipInvalidConfigurations)' == 'true')";
776 task = t.AddNewTask ("Message");
777 task.SetParameterValue ("Text", "Building solution configuration \"$(Configuration)|$(Platform)\".");
778 task.Condition = "'$(CurrentSolutionConfigurationContents)' != ''";
781 void AddProjectTargets (Project p, List<TargetInfo> solutionTargets, Dictionary<Guid, ProjectInfo> projectInfos)
783 foreach (KeyValuePair<Guid, ProjectInfo> projectInfo in projectInfos) {
784 ProjectInfo project = projectInfo.Value;
785 foreach (string buildTarget in buildTargets) {
786 string target_name = GetTargetNameForProject (project.Name, buildTarget);
787 bool is_build_or_rebuild = buildTarget == "Build" || buildTarget == "Rebuild";
788 Target target = p.Targets.AddNewTarget (target_name);
789 target.Condition = "'$(CurrentSolutionConfigurationContents)' != ''";
791 if (is_build_or_rebuild)
792 target.Outputs = "@(CollectedBuildOutput)";
793 if (project.Dependencies.Count > 0)
794 target.DependsOnTargets = String.Join (";",
795 project.Dependencies.Values.Select (
796 di => GetTargetNameForProject (di.Name, buildTarget)).ToArray ());
798 foreach (TargetInfo targetInfo in solutionTargets) {
799 BuildTask task = null;
800 TargetInfo projectTargetInfo;
801 if (!project.TargetMap.TryGetValue (targetInfo, out projectTargetInfo)) {
802 AddWarningForMissingProjectConfiguration (target, targetInfo.Configuration,
803 targetInfo.Platform, project.Name);
806 if (projectTargetInfo.Build) {
807 task = target.AddNewTask ("MSBuild");
808 task.SetParameterValue ("Projects", project.FileName);
809 task.SetParameterValue ("ToolsVersion", "$(ProjectToolsVersion)");
810 if (is_build_or_rebuild)
811 task.AddOutputItem ("TargetOutputs", "CollectedBuildOutput");
813 if (buildTarget != "Build")
814 task.SetParameterValue ("Targets", buildTarget);
815 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));
817 task = target.AddNewTask ("Message");
818 task.SetParameterValue ("Text", string.Format ("Project \"{0}\" is disabled for solution configuration \"{1}|{2}\".", project.Name, targetInfo.Configuration, targetInfo.Platform));
820 task.Condition = string.Format (" ('$(Configuration)' == '{0}') and ('$(Platform)' == '{1}') ", targetInfo.Configuration, targetInfo.Platform);
827 string GetTargetNameForProject (string projectName, string buildTarget)
830 projectName = projectName.Replace ("\\", "/").Replace (".", "_");
831 string target_name = projectName +
832 (buildTarget == "Build" ? string.Empty : ":" + buildTarget);
834 if (IsBuildTargetName (projectName))
835 target_name = "Solution:" + target_name;
840 bool IsBuildTargetName (string name)
842 foreach (string tgt in buildTargets)
848 // returns number of levels
849 int AddBuildLevels (Project p, List<TargetInfo> solutionTargets, Dictionary<Guid, ProjectInfo> projectInfos,
850 ref List<ProjectInfo>[] infosByLevel)
852 infosByLevel = TopologicalSort<ProjectInfo> (projectInfos.Values);
854 foreach (TargetInfo targetInfo in solutionTargets) {
855 BuildItemGroup big = p.AddNewItemGroup ();
856 big.Condition = String.Format (" ('$(Configuration)' == '{0}') and ('$(Platform)' == '{1}') ",
857 targetInfo.Configuration, targetInfo.Platform);
859 //FIXME: every level has projects that can be built in parallel.
860 // levels are ordered on the basis of the dependency graph
862 for (int i = 0; i < infosByLevel.Length; i ++) {
863 string build_level = String.Format ("BuildLevel{0}", i);
864 string skip_level = String.Format ("SkipLevel{0}", i);
865 string missing_level = String.Format ("MissingConfigLevel{0}", i);
867 foreach (ProjectInfo projectInfo in infosByLevel [i]) {
868 TargetInfo projectTargetInfo;
869 if (!projectInfo.TargetMap.TryGetValue (targetInfo, out projectTargetInfo)) {
870 // missing project config
871 big.AddNewItem (missing_level, projectInfo.Name);
875 if (projectTargetInfo.Build) {
876 BuildItem item = big.AddNewItem (build_level, projectInfo.FileName);
877 item.SetMetadata ("Configuration", projectTargetInfo.Configuration);
878 item.SetMetadata ("Platform", projectTargetInfo.Platform);
881 big.AddNewItem (skip_level, projectInfo.Name);
887 return infosByLevel.Length;
890 void AddSolutionTargets (Project p, int num_levels, IEnumerable<ProjectInfo> websiteProjectInfos)
892 foreach (string buildTarget in buildTargets) {
893 Target t = p.Targets.AddNewTarget (buildTarget);
894 bool is_build_or_rebuild = buildTarget == "Build" || buildTarget == "Rebuild";
896 t.Condition = "'$(CurrentSolutionConfigurationContents)' != ''";
897 if (is_build_or_rebuild)
898 t.Outputs = "@(CollectedBuildOutput)";
900 BuildTask task = null;
901 for (int i = 0; i < num_levels; i ++) {
902 string level_str = String.Format ("BuildLevel{0}", i);
903 task = t.AddNewTask ("MSBuild");
904 task.SetParameterValue ("Condition", String.Format ("'@({0})' != ''", level_str));
905 task.SetParameterValue ("Projects", String.Format ("@({0})", level_str));
906 task.SetParameterValue ("ToolsVersion", "$(ProjectToolsVersion)");
907 task.SetParameterValue ("Properties",
908 string.Format ("Configuration=%(Configuration); Platform=%(Platform); BuildingSolutionFile=true; CurrentSolutionConfigurationContents=$(CurrentSolutionConfigurationContents); SolutionDir=$(SolutionDir); SolutionExt=$(SolutionExt); SolutionFileName=$(SolutionFileName); SolutionName=$(SolutionName); SolutionPath=$(SolutionPath)"));
909 if (buildTarget != "Build")
910 task.SetParameterValue ("Targets", buildTarget);
911 //FIXME: change this to BuildInParallel=true, when parallel
912 // build support gets added
913 task.SetParameterValue ("RunEachTargetSeparately", "true");
914 if (is_build_or_rebuild)
915 task.AddOutputItem ("TargetOutputs", "CollectedBuildOutput");
917 level_str = String.Format ("SkipLevel{0}", i);
918 task = t.AddNewTask ("Message");
919 task.Condition = String.Format ("'@({0})' != ''", level_str);
920 task.SetParameterValue ("Text",
921 String.Format ("The project '%({0}.Identity)' is disabled for solution " +
922 "configuration '$(Configuration)|$(Platform)'.", level_str));
924 level_str = String.Format ("MissingConfigLevel{0}", i);
925 task = t.AddNewTask ("Warning");
926 task.Condition = String.Format ("'@({0})' != ''", level_str);
927 task.SetParameterValue ("Text",
928 String.Format ("The project configuration for project '%({0}.Identity)' " +
929 "corresponding to the solution configuration " +
930 "'$(Configuration)|$(Platform)' was not found.", level_str));
933 // "build" website projects also
934 StringBuilder w_targets = new StringBuilder ();
935 foreach (ProjectInfo info in websiteProjectInfos) {
936 if (w_targets.Length > 0)
937 w_targets.Append (";");
938 w_targets.Append (GetTargetNameForProject (info.Name, buildTarget));
941 task = t.AddNewTask ("CallTarget");
942 task.SetParameterValue ("Targets", w_targets.ToString ());
943 task.SetParameterValue ("RunEachTargetSeparately", "true");
947 // Sorts the ProjectInfo dependency graph, to obtain
948 // a series of build levels with projects. Projects
949 // in each level can be run parallel (no inter-dependency).
950 static List<T>[] TopologicalSort<T> (IEnumerable<T> items) where T: ProjectInfo
953 allItems = items as IList<T>;
954 if (allItems == null)
955 allItems = new List<T> (items);
957 bool[] inserted = new bool[allItems.Count];
958 bool[] triedToInsert = new bool[allItems.Count];
959 int[] levels = new int [allItems.Count];
962 for (int i = 0; i < allItems.Count; ++i) {
963 int d = Insert<T> (i, allItems, levels, inserted, triedToInsert);
968 // Separate out the project infos by build level
969 List<T>[] infosByLevel = new List<T>[maxdepth];
970 for (int i = 0; i < levels.Length; i ++) {
971 int level = levels [i] - 1;
972 if (infosByLevel [level] == null)
973 infosByLevel [level] = new List<T> ();
975 infosByLevel [level].Add (allItems [i]);
981 // returns level# for the project
982 static int Insert<T> (int index, IList<T> allItems, int[] levels, bool[] inserted, bool[] triedToInsert)
985 if (inserted [index])
986 return levels [index];
988 if (triedToInsert[index])
989 throw new InvalidOperationException (String.Format (
990 "Cyclic dependency involving project {0} found in the project dependency graph",
991 allItems [index].Name));
993 triedToInsert[index] = true;
994 ProjectInfo insertItem = allItems[index];
997 foreach (ProjectInfo dependency in insertItem.Dependencies.Values) {
998 for (int j = 0; j < allItems.Count; ++j) {
999 ProjectInfo checkItem = allItems [j];
1000 if (dependency.FileName == checkItem.FileName) {
1001 int d = Insert (j, allItems, levels, inserted, triedToInsert);
1002 maxdepth = d > maxdepth ? d : maxdepth;
1007 levels [index] = maxdepth + 1;
1008 inserted [index] = true;
1010 return levels [index];
1013 public static IEnumerable<string> GetAllProjectFileNames (string solutionFile)
1015 StreamReader reader = new StreamReader (solutionFile);
1016 string line = reader.ReadToEnd ();
1017 line = line.Replace ("\r\n", "\n");
1018 string soln_dir = Path.GetDirectoryName (solutionFile);
1020 Match m = projectRegex.Match (line);
1022 if (String.Compare (m.Groups [1].Value, solutionFolderGuid,
1023 StringComparison.InvariantCultureIgnoreCase) != 0)
1024 yield return Path.Combine (soln_dir, m.Groups [3].Value).Replace ("\\", "/");