2 // SolutionParser.cs: Generates a project file from a solution file.
5 // Jonathan Chambers (joncham@gmail.com)
6 // Ankit Jain <jankit@novell.com>
7 // Lluis Sanchez Gual <lluis@novell.com>
9 // (C) 2009 Jonathan Chambers
10 // Copyright 2008, 2009 Novell, Inc (http://www.novell.com)
12 // Permission is hereby granted, free of charge, to any person obtaining
13 // a copy of this software and associated documentation files (the
14 // "Software"), to deal in the Software without restriction, including
15 // without limitation the rights to use, copy, modify, merge, publish,
16 // distribute, sublicense, and/or sell copies of the Software, and to
17 // permit persons to whom the Software is furnished to do so, subject to
18 // the following conditions:
20 // The above copyright notice and this permission notice shall be
21 // included in all copies or substantial portions of the Software.
23 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
24 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
25 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
26 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
27 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
28 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
29 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
32 using System.Collections.Generic;
35 using System.Text.RegularExpressions;
37 using Microsoft.Build.Evaluation;
38 using Microsoft.Build.Execution;
39 using Microsoft.Build.Construction;
40 using Microsoft.Build.Exceptions;
42 namespace Mono.XBuild.CommandLine {
45 public string FileName;
48 public ProjectInfo (string name, string fileName)
54 public Dictionary<TargetInfo, TargetInfo> TargetMap = new Dictionary<TargetInfo, TargetInfo> ();
55 public Dictionary<Guid, ProjectInfo> Dependencies = new Dictionary<Guid, ProjectInfo> ();
56 public Dictionary<string, ProjectSection> ProjectSections = new Dictionary<string, ProjectSection> ();
57 public List<string> AspNetConfigurations = new List<string> ();
60 class ProjectSection {
62 public Dictionary<string, string> Properties = new Dictionary<string, string> ();
64 public ProjectSection (string name)
71 public string Configuration;
72 public string Platform;
75 public TargetInfo (string configuration, string platform)
76 : this (configuration, platform, false)
80 public TargetInfo (string configuration, string platform, bool build)
82 Configuration = configuration;
89 internal delegate void RaiseWarningHandler (int errorNumber, string message);
91 class SolutionParser {
92 static string[] buildTargets = new string[] { "Build", "Clean", "Rebuild", "Publish" };
94 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}}";
96 static Regex slnVersionRegex = new Regex (@"Microsoft Visual Studio Solution File, Format Version (\d?\d.\d\d)");
97 static Regex projectRegex = new Regex ("Project\\(\"(" + guidExpression + ")\"\\) = \"(.*?)\", \"(.*?)\", \"(" + guidExpression + ")\"(\\s*?)((\\s*?)ProjectSection\\((.*?)\\) = (.*?)EndProjectSection(\\s*?))*(\\s*?)(EndProject)?", RegexOptions.Singleline);
98 static Regex projectDependenciesRegex = new Regex ("ProjectSection\\((.*?)\\) = \\w*(.*?)EndProjectSection", RegexOptions.Singleline);
99 static Regex projectDependencyRegex = new Regex ("\\s*(" + guidExpression + ") = (" + guidExpression + ")");
100 static Regex projectSectionPropertiesRegex = new Regex ("\\s*(?<name>.*) = \"(?<value>.*)\"");
102 static Regex globalRegex = new Regex ("Global(.*)EndGlobal", RegexOptions.Singleline);
103 static Regex globalSectionRegex = new Regex ("GlobalSection\\((.*?)\\) = \\w*(.*?)EndGlobalSection", RegexOptions.Singleline);
105 static Regex solutionConfigurationRegex = new Regex ("\\s*(.*?)\\|(.*?) = (.*?)\\|(.+)");
106 static Regex projectConfigurationActiveCfgRegex = new Regex ("\\s*(" + guidExpression + ")\\.(.+?)\\|(.+?)\\.ActiveCfg = (.+?)\\|(.+)");
107 static Regex projectConfigurationBuildRegex = new Regex ("\\s*(" + guidExpression + ")\\.(.*?)\\|(.*?)\\.Build\\.0 = (.*?)\\|(.+)");
109 static string solutionFolderGuid = "{2150E333-8FDC-42A3-9474-1A3956D46DE8}";
110 static string vcprojGuid = "{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}";
111 static string websiteProjectGuid = "{E24C65DC-7377-472B-9ABA-BC803B73C61A}";
113 RaiseWarningHandler RaiseWarning;
115 public void ParseSolution (string file, ProjectCollection projects, ProjectRootElement p, RaiseWarningHandler RaiseWarning)
117 this.RaiseWarning = RaiseWarning;
118 EmitBeforeImports (p, file);
120 AddGeneralSettings (file, p);
122 StreamReader reader = new StreamReader (file);
123 string slnVersion = GetSlnFileVersion (reader);
124 if (slnVersion == "11.00")
125 projects.DefaultToolsVersion = "4.0";
126 else if (slnVersion == "10.00")
127 projects.DefaultToolsVersion = "3.5";
129 projects.DefaultToolsVersion = "2.0";
131 string line = reader.ReadToEnd ();
132 line = line.Replace ("\r\n", "\n");
133 string solutionDir = Path.GetDirectoryName (file);
135 List<TargetInfo> solutionTargets = new List<TargetInfo> ();
136 Dictionary<Guid, ProjectInfo> projectInfos = new Dictionary<Guid, ProjectInfo> ();
137 Dictionary<Guid, ProjectInfo> websiteProjectInfos = new Dictionary<Guid, ProjectInfo> ();
138 List<ProjectInfo>[] infosByLevel = null;
139 Dictionary<Guid, ProjectInfo> unsupportedProjectInfos = new Dictionary<Guid, ProjectInfo> ();
141 Match m = projectRegex.Match (line);
143 ProjectInfo projectInfo = new ProjectInfo (m.Groups[2].Value,
144 Path.GetFullPath (Path.Combine (solutionDir,
145 m.Groups [3].Value.Replace ('\\', Path.DirectorySeparatorChar))));
146 if (String.Compare (m.Groups [1].Value, solutionFolderGuid,
147 StringComparison.InvariantCultureIgnoreCase) == 0) {
148 // Ignore solution folders
153 projectInfo.Guid = new Guid (m.Groups [4].Value);
155 if (String.Compare (m.Groups [1].Value, vcprojGuid,
156 StringComparison.InvariantCultureIgnoreCase) == 0) {
158 RaiseWarning (0, string.Format("Ignoring vcproj '{0}'.", projectInfo.Name));
160 unsupportedProjectInfos [projectInfo.Guid] = projectInfo;
165 if (String.Compare (m.Groups [1].Value, websiteProjectGuid,
166 StringComparison.InvariantCultureIgnoreCase) == 0)
167 websiteProjectInfos.Add (new Guid (m.Groups[4].Value), projectInfo);
169 projectInfos.Add (projectInfo.Guid, projectInfo);
171 Match projectSectionMatch = projectDependenciesRegex.Match (m.Groups[6].Value);
172 while (projectSectionMatch.Success) {
173 string section_name = projectSectionMatch.Groups [1].Value;
174 if (String.Compare (section_name, "ProjectDependencies") == 0) {
175 Match projectDependencyMatch = projectDependencyRegex.Match (projectSectionMatch.Value);
176 while (projectDependencyMatch.Success) {
177 // we might not have projectInfo available right now, so
178 // set it to null, and fill it in later
179 projectInfo.Dependencies [new Guid (projectDependencyMatch.Groups[1].Value)] = null;
180 projectDependencyMatch = projectDependencyMatch.NextMatch ();
183 ProjectSection section = new ProjectSection (section_name);
184 Match propertiesMatch = projectSectionPropertiesRegex.Match (
185 projectSectionMatch.Groups [2].Value);
186 while (propertiesMatch.Success) {
187 section.Properties [propertiesMatch.Groups ["name"].Value] =
188 propertiesMatch.Groups ["value"].Value;
190 propertiesMatch = propertiesMatch.NextMatch ();
193 projectInfo.ProjectSections [section_name] = section;
195 projectSectionMatch = projectSectionMatch.NextMatch ();
200 foreach (ProjectInfo projectInfo in projectInfos.Values) {
201 string filename = projectInfo.FileName;
202 string projectDir = Path.GetDirectoryName (filename);
204 if (!File.Exists (filename)) {
205 RaiseWarning (0, String.Format ("Project file {0} referenced in the solution file, " +
206 "not found. Ignoring.", filename));
210 Project currentProject;
212 currentProject = new Project (filename, null, null, new ProjectCollection (), ProjectLoadSettings.IgnoreMissingImports);
213 } catch (InvalidProjectFileException e) {
214 RaiseWarning (0, e.Message);
218 foreach (var bi in currentProject.GetItems ("ProjectReference")) {
219 ProjectInfo info = null;
220 string projectReferenceGuid = bi.GetMetadataValue ("Project");
221 bool hasGuid = !String.IsNullOrEmpty (projectReferenceGuid);
223 // try to resolve the ProjectReference by GUID
224 // and fallback to project filename
227 Guid guid = new Guid (projectReferenceGuid);
228 projectInfos.TryGetValue (guid, out info);
229 if (info == null && unsupportedProjectInfos.TryGetValue (guid, out info)) {
230 RaiseWarning (0, String.Format (
231 "{0}: ProjectReference '{1}' is of an unsupported type. Ignoring.",
232 filename, bi.EvaluatedInclude));
237 if (info == null || !hasGuid) {
238 // Project not found by guid or guid not available
239 // Try to find by project file
241 string fullpath = Path.GetFullPath (Path.Combine (projectDir, bi.EvaluatedInclude.Replace ('\\', Path.DirectorySeparatorChar)));
242 info = projectInfos.Values.FirstOrDefault (pi => pi.FileName == fullpath);
245 if (unsupportedProjectInfos.Values.Any (pi => pi.FileName == fullpath))
246 RaiseWarning (0, String.Format (
247 "{0}: ProjectReference '{1}' is of an unsupported type. Ignoring.",
248 filename, bi.EvaluatedInclude));
250 RaiseWarning (0, String.Format (
251 "{0}: ProjectReference '{1}' not found, neither by guid '{2}' nor by project file name '{3}'.",
252 filename, bi.EvaluatedInclude, projectReferenceGuid.Replace ("{", "").Replace ("}", ""), fullpath));
258 projectInfo.Dependencies [info.Guid] = info;
262 // fill in the project info for deps found in the .sln file
263 foreach (ProjectInfo projectInfo in projectInfos.Values) {
264 List<Guid> missingInfos = new List<Guid> ();
265 foreach (KeyValuePair<Guid, ProjectInfo> dependency in projectInfo.Dependencies) {
266 if (dependency.Value == null)
267 missingInfos.Add (dependency.Key);
270 foreach (Guid guid in missingInfos) {
272 if (projectInfos.TryGetValue (guid, out info))
273 projectInfo.Dependencies [guid] = info;
275 projectInfo.Dependencies.Remove (guid);
279 Match globalMatch = globalRegex.Match (line);
280 Match globalSectionMatch = globalSectionRegex.Match (globalMatch.Groups[1].Value);
281 while (globalSectionMatch.Success) {
282 string sectionType = globalSectionMatch.Groups[1].Value;
283 switch (sectionType) {
284 case "SolutionConfigurationPlatforms":
285 ParseSolutionConfigurationPlatforms (globalSectionMatch.Groups[2].Value, solutionTargets);
287 case "ProjectConfigurationPlatforms":
288 ParseProjectConfigurationPlatforms (globalSectionMatch.Groups[2].Value,
289 projectInfos, websiteProjectInfos);
291 case "SolutionProperties":
292 ParseSolutionProperties (globalSectionMatch.Groups[2].Value);
294 case "NestedProjects":
296 case "MonoDevelopProperties":
299 RaiseWarning (0, string.Format("Don't know how to handle GlobalSection {0}, Ignoring.", sectionType));
302 globalSectionMatch = globalSectionMatch.NextMatch ();
305 int num_levels = AddBuildLevels (p, solutionTargets, projectInfos, ref infosByLevel);
307 AddCurrentSolutionConfigurationContents (p, solutionTargets, projectInfos, websiteProjectInfos);
308 AddProjectReferences (p, projectInfos);
309 AddWebsiteProperties (p, websiteProjectInfos, projectInfos);
310 AddValidateSolutionConfiguration (p);
312 EmitAfterImports (p, file);
314 AddGetFrameworkPathTarget (p);
315 AddWebsiteTargets (p, websiteProjectInfos, projectInfos, infosByLevel, solutionTargets);
316 AddProjectTargets (p, solutionTargets, projectInfos);
317 AddSolutionTargets (p, num_levels, websiteProjectInfos.Values);
320 string GetSlnFileVersion (StreamReader reader)
322 string strInput = null;
325 strInput = reader.ReadLine();
326 if (strInput == null)
329 match = slnVersionRegex.Match(strInput);
330 if (!match.Success) {
331 strInput = reader.ReadLine();
332 if (strInput == null)
334 match = slnVersionRegex.Match (strInput);
338 return match.Groups[1].Value;
343 void EmitBeforeImports (ProjectRootElement p, string file)
346 p.AddImportGroup ().AddImport ("$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\SolutionFile\\ImportBefore\\*").Condition =
347 "'$(ImportByWildcardBeforeSolution)' != 'false' and " +
348 "Exists('$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\SolutionFile\\ImportBefore')";
351 string before_filename = Path.Combine (Path.GetDirectoryName (file), "before." + Path.GetFileName (file) + ".targets");
352 p.AddImportGroup ().AddImport (before_filename).Condition = String.Format ("Exists ('{0}')", before_filename);
355 void EmitAfterImports (ProjectRootElement p, string file)
358 p.AddImportGroup ().AddImport ("$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\SolutionFile\\ImportAfter\\*").Condition =
359 "'$(ImportByWildcardAfterSolution)' != 'false' and " +
360 "Exists('$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\SolutionFile\\ImportAfter')";
363 string after_filename = Path.Combine (Path.GetDirectoryName (file), "after." + Path.GetFileName (file) + ".targets");
364 p.AddImportGroup ().AddImport (after_filename).Condition = String.Format ("Exists ('{0}')", after_filename);
367 void AddGeneralSettings (string solutionFile, ProjectRootElement p)
369 p.DefaultTargets = "Build";
370 p.InitialTargets = "ValidateSolutionConfiguration";
371 p.AddUsingTask ("CreateTemporaryVCProject", null, "Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
372 p.AddUsingTask ("ResolveVCProjectOutput", null, "Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
374 string solutionFilePath = Path.GetFullPath (solutionFile);
375 var solutionPropertyGroup = p.CreatePropertyGroupElement ();
376 //solutionPropertyGroup.ChildrenReversed = true;
377 solutionPropertyGroup.AddProperty ("SolutionDir", Path.GetDirectoryName (solutionFilePath) + Path.DirectorySeparatorChar);
378 solutionPropertyGroup.AddProperty ("SolutionExt", Path.GetExtension (solutionFile));
379 solutionPropertyGroup.AddProperty ("SolutionFileName", Path.GetFileName (solutionFile));
380 solutionPropertyGroup.AddProperty ("SolutionName", Path.GetFileNameWithoutExtension (solutionFile));
381 solutionPropertyGroup.AddProperty ("SolutionPath", solutionFilePath);
384 void ParseSolutionConfigurationPlatforms (string section, List<TargetInfo> solutionTargets)
386 Match solutionConfigurationPlatform = solutionConfigurationRegex.Match (section);
387 while (solutionConfigurationPlatform.Success) {
388 string solutionConfiguration = solutionConfigurationPlatform.Groups[1].Value;
389 string solutionPlatform = solutionConfigurationPlatform.Groups[2].Value;
390 solutionTargets.Add (new TargetInfo (solutionConfiguration, solutionPlatform));
391 solutionConfigurationPlatform = solutionConfigurationPlatform.NextMatch ();
395 // ignores the website projects, in the websiteProjectInfos
396 void ParseProjectConfigurationPlatforms (string section, Dictionary<Guid, ProjectInfo> projectInfos,
397 Dictionary<Guid, ProjectInfo> websiteProjectInfos)
399 List<Guid> missingGuids = new List<Guid> ();
400 Match projectConfigurationPlatform = projectConfigurationActiveCfgRegex.Match (section);
401 while (projectConfigurationPlatform.Success) {
402 Guid guid = new Guid (projectConfigurationPlatform.Groups[1].Value);
403 ProjectInfo projectInfo;
404 if (!projectInfos.TryGetValue (guid, out projectInfo)) {
405 if (!missingGuids.Contains (guid)) {
406 if (!websiteProjectInfos.ContainsKey (guid))
407 // ignore website projects
408 RaiseWarning (0, string.Format("Failed to find project {0}", guid));
409 missingGuids.Add (guid);
411 projectConfigurationPlatform = projectConfigurationPlatform.NextMatch ();
414 string solConf = projectConfigurationPlatform.Groups[2].Value;
415 string solPlat = projectConfigurationPlatform.Groups[3].Value;
416 string projConf = projectConfigurationPlatform.Groups[4].Value;
417 string projPlat = projectConfigurationPlatform.Groups[5].Value;
418 // hack, what are they doing here?
419 if (projPlat == "Any CPU")
421 projectInfo.TargetMap.Add (new TargetInfo (solConf, solPlat), new TargetInfo (projConf, projPlat));
422 projectConfigurationPlatform = projectConfigurationPlatform.NextMatch ();
424 Match projectConfigurationPlatformBuild = projectConfigurationBuildRegex.Match (section);
425 while (projectConfigurationPlatformBuild.Success) {
426 Guid guid = new Guid (projectConfigurationPlatformBuild.Groups[1].Value);
427 ProjectInfo projectInfo;
428 if (!projectInfos.TryGetValue (guid, out projectInfo)) {
429 if (!missingGuids.Contains (guid)) {
430 RaiseWarning (0, string.Format("Failed to find project {0}", guid));
431 missingGuids.Add (guid);
433 projectConfigurationPlatformBuild = projectConfigurationPlatformBuild.NextMatch ();
436 string solConf = projectConfigurationPlatformBuild.Groups[2].Value;
437 string solPlat = projectConfigurationPlatformBuild.Groups[3].Value;
438 string projConf = projectConfigurationPlatformBuild.Groups[4].Value;
439 string projPlat = projectConfigurationPlatformBuild.Groups[5].Value;
440 // hack, what are they doing here?
441 if (projPlat == "Any CPU")
443 projectInfo.TargetMap[new TargetInfo (solConf, solPlat)] = new TargetInfo (projConf, projPlat, true);
444 projectConfigurationPlatformBuild = projectConfigurationPlatformBuild.NextMatch ();
448 void ParseSolutionProperties (string section)
452 void AddCurrentSolutionConfigurationContents (ProjectRootElement p, List<TargetInfo> solutionTargets,
453 Dictionary<Guid, ProjectInfo> projectInfos,
454 Dictionary<Guid, ProjectInfo> websiteProjectInfos)
456 TargetInfo default_target_info = new TargetInfo ("Debug", "Any CPU");
457 if (solutionTargets.Count > 0) {
459 foreach (TargetInfo tinfo in solutionTargets) {
460 if (String.Compare (tinfo.Platform, "Mixed Platforms") == 0) {
461 default_target_info = tinfo;
468 default_target_info = solutionTargets [0];
471 AddDefaultSolutionConfiguration (p, default_target_info);
473 foreach (TargetInfo solutionTarget in solutionTargets) {
474 var platformPropertyGroup = p.AddPropertyGroup ();
475 platformPropertyGroup.Condition = string.Format (
476 " ('$(Configuration)' == '{0}') and ('$(Platform)' == '{1}') ",
477 solutionTarget.Configuration,
478 solutionTarget.Platform
481 StringBuilder solutionConfigurationContents = new StringBuilder ();
482 solutionConfigurationContents.Append ("<SolutionConfiguration xmlns=\"\">");
483 foreach (KeyValuePair<Guid, ProjectInfo> projectInfo in projectInfos) {
484 AddProjectConfigurationItems (projectInfo.Key, projectInfo.Value, solutionTarget, solutionConfigurationContents);
486 solutionConfigurationContents.Append ("</SolutionConfiguration>");
488 platformPropertyGroup.AddProperty ("CurrentSolutionConfigurationContents",
489 solutionConfigurationContents.ToString ());
493 void AddProjectReferences (ProjectRootElement p, Dictionary<Guid, ProjectInfo> projectInfos)
495 var big = p.AddItemGroup ();
496 foreach (KeyValuePair<Guid, ProjectInfo> pair in projectInfos)
497 big.AddItem ("ProjectReference", pair.Value.FileName);
500 void AddProjectConfigurationItems (Guid guid, ProjectInfo projectInfo, TargetInfo solutionTarget,
501 StringBuilder solutionConfigurationContents)
503 foreach (KeyValuePair<TargetInfo, TargetInfo> targetInfo in projectInfo.TargetMap) {
504 if (solutionTarget.Configuration == targetInfo.Key.Configuration &&
505 solutionTarget.Platform == targetInfo.Key.Platform) {
506 solutionConfigurationContents.AppendFormat (
507 "<ProjectConfiguration Project=\"{0}\">{1}|{2}</ProjectConfiguration>",
508 guid.ToString ("B").ToUpper (), targetInfo.Value.Configuration, targetInfo.Value.Platform);
513 void AddDefaultSolutionConfiguration (ProjectRootElement p, TargetInfo target)
515 var configurationPropertyGroup = p.AddPropertyGroup ();
516 //configurationPropertyGroup.PropertiesReversed = true;
517 configurationPropertyGroup.Condition = " '$(Configuration)' == '' ";
518 configurationPropertyGroup.AddProperty ("Configuration", target.Configuration);
520 var platformPropertyGroup = p.AddPropertyGroup ();
521 //platformPropertyGroup.PropertiesReversed = true;
522 platformPropertyGroup.Condition = " '$(Platform)' == '' ";
523 platformPropertyGroup.AddProperty ("Platform", target.Platform);
525 // emit default for AspNetConfiguration also
526 var aspNetConfigurationPropertyGroup = p.AddPropertyGroup ();
527 //aspNetConfigurationPropertyGroup.PropertiesReversed = true;
528 aspNetConfigurationPropertyGroup.Condition = " ('$(AspNetConfiguration)' == '') ";
529 aspNetConfigurationPropertyGroup.AddProperty ("AspNetConfiguration", "$(Configuration)");
532 void AddWarningForMissingProjectConfiguration (ProjectTargetElement target, string slnConfig, string slnPlatform, string projectName)
534 var task = target.AddTask ("Warning");
535 task.SetParameter ("Text",
536 String.Format ("The project configuration for project '{0}' corresponding " +
537 "to the solution configuration '{1}|{2}' was not found in the solution file.",
538 projectName, slnConfig, slnPlatform));
539 task.Condition = String.Format ("('$(Configuration)' == '{0}') and ('$(Platform)' == '{1}')",
540 slnConfig, slnPlatform);
544 // Website project methods
546 void AddWebsiteProperties (ProjectRootElement p, Dictionary<Guid, ProjectInfo> websiteProjectInfos,
547 Dictionary<Guid, ProjectInfo> projectInfos)
549 var propertyGroupByConfig = new Dictionary<string, ProjectPropertyGroupElement> ();
550 foreach (KeyValuePair<Guid, ProjectInfo> infoPair in websiteProjectInfos) {
551 ProjectInfo info = infoPair.Value;
552 string projectGuid = infoPair.Key.ToString ();
554 ProjectSection section;
555 if (!info.ProjectSections.TryGetValue ("WebsiteProperties", out section)) {
556 RaiseWarning (0, String.Format ("Website project '{0}' does not have the required project section: WebsiteProperties. Ignoring project.", info.Name));
560 //parse project references
561 string [] ref_guids = null;
563 if (section.Properties.TryGetValue ("ProjectReferences", out references)) {
564 ref_guids = references.Split (new char [] {';'}, StringSplitOptions.RemoveEmptyEntries);
565 for (int i = 0; i < ref_guids.Length; i ++) {
567 ref_guids [i] = ref_guids [i].Split ('|') [0];
569 Guid r_guid = new Guid (ref_guids [i]);
570 ProjectInfo ref_info;
571 if (projectInfos.TryGetValue (r_guid, out ref_info))
572 // ignore if not found
573 info.Dependencies [r_guid] = ref_info;
577 foreach (KeyValuePair<string, string> pair in section.Properties) {
578 //looking for -- ConfigName.AspNetCompiler.PropName
579 string [] parts = pair.Key.Split ('.');
580 if (parts.Length != 3 || String.Compare (parts [1], "AspNetCompiler") != 0)
583 string config = parts [0];
584 string propertyName = parts [2];
586 ProjectPropertyGroupElement bpg;
587 if (!propertyGroupByConfig.TryGetValue (config, out bpg)) {
588 bpg = p.AddPropertyGroup ();
589 //bpg.PropertiesReversed = true;
590 bpg.Condition = String.Format (" '$(AspNetConfiguration)' == '{0}' ", config);
591 propertyGroupByConfig [config] = bpg;
594 bpg.AddProperty (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 (ProjectRootElement 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 (ProjectRootElement 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 var target = p.AddTarget (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 (ProjectTargetElement target, ProjectInfo depInfo, TargetInfo projectTargetInfo,
668 TargetInfo solutionTargetInfo, string final_ref_item, int ref_num)
670 var task = target.AddTask ("MSBuild");
671 task.SetParameter ("Projects", depInfo.FileName);
672 task.SetParameter ("Targets", "GetTargetPath");
674 task.SetParameter ("Properties", string.Format ("Configuration={0}; Platform={1}; BuildingSolutionFile=true; CurrentSolutionConfigurationContents=$(CurrentSolutionConfigurationContents); SolutionDir=$(SolutionDir); SolutionExt=$(SolutionExt); SolutionFileName=$(SolutionFileName); SolutionName=$(SolutionName); SolutionPath=$(SolutionPath)", projectTargetInfo.Configuration, projectTargetInfo.Platform));
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.AddTask ("CreateItem");
683 task.SetParameter ("Include", String.Format ("@({0})", ref_item));
684 task.SetParameter ("AdditionalMetadata", String.Format ("Guid={{{0}}}",
685 depInfo.Guid.ToString ().ToUpper ()));
686 task.AddOutputItem ("Include", final_ref_item);
689 void AddWebsiteResolveAndCopyReferencesTasks (ProjectTargetElement target, ProjectInfo webProjectInfo,
690 string final_ref_item, string w_guid)
692 var task = target.AddTask ("ResolveAssemblyReference");
693 task.SetParameter ("Assemblies", String.Format ("@({0}->'%(FullPath)')", final_ref_item));
694 task.SetParameter ("TargetFrameworkDirectories", "$(TargetFrameworkPath)");
695 task.SetParameter ("SearchPaths", "{RawFileName};{TargetFrameworkDirectory};{GAC}");
696 task.SetParameter ("FindDependencies", "true");
697 task.SetParameter ("FindSatellites", "true");
698 task.SetParameter ("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.AddTask ("Copy");
706 task.SetParameter ("SourceFiles", String.Format ("@({0})", copylocal_item));
707 task.SetParameter ("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.AddTask ("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.SetParameter ("Text", "Skipping as the '$(AspNetConfiguration)' configuration is " +
730 "not supported by this website project.");
733 void AddWebsiteUnsupportedTarget (ProjectRootElement p, ProjectInfo webProjectInfo, List<ProjectInfo> depInfos,
736 var target = p.AddTarget (GetTargetNameForProject (webProjectInfo.Name, buildTarget));
737 target.DependsOnTargets = GetWebsiteDependsOnTarget (depInfos, buildTarget);
739 var task = target.AddTask ("Message");
740 task.SetParameter ("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 (ProjectRootElement p)
758 var t = p.AddTarget ("GetFrameworkPath");
759 var task = t.AddTask ("GetFrameworkPath");
760 task.AddOutputProperty ("Path", "TargetFrameworkPath");
763 void AddValidateSolutionConfiguration (ProjectRootElement p)
765 var t = p.AddTarget ("ValidateSolutionConfiguration");
766 var task = t.AddTask ("Warning");
767 task.SetParameter ("Text", "On windows, an environment variable 'Platform' is set to MCD sometimes, and this overrides the Platform property" +
768 " for Mono msbuild, 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 " msbuild Foo.sln /p:Platform=Release");
773 task.Condition = "('$(CurrentSolutionConfigurationContents)' == '') and ('$(SkipInvalidConfigurations)' != 'true')" +
774 " and '$(Platform)' == 'MCD' and '$(OS)' == 'Windows_NT'";
776 task = t.AddTask ("Error");
777 task.SetParameter ("Text", "Invalid solution configuration and platform: \"$(Configuration)|$(Platform)\".");
778 task.Condition = "('$(CurrentSolutionConfigurationContents)' == '') and ('$(SkipInvalidConfigurations)' != 'true')";
779 task = t.AddTask ("Warning");
780 task.SetParameter ("Text", "Invalid solution configuration and platform: \"$(Configuration)|$(Platform)\".");
781 task.Condition = "('$(CurrentSolutionConfigurationContents)' == '') and ('$(SkipInvalidConfigurations)' == 'true')";
782 task = t.AddTask ("Message");
783 task.SetParameter ("Text", "Building solution configuration \"$(Configuration)|$(Platform)\".");
784 task.Condition = "'$(CurrentSolutionConfigurationContents)' != ''";
787 void AddProjectTargets (ProjectRootElement 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 var target = p.AddTarget (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 ProjectTaskElement 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.AddTask ("MSBuild");
814 task.SetParameter ("Projects", project.FileName);
815 task.SetParameter ("ToolsVersion", "$(ProjectToolsVersion)");
816 if (is_build_or_rebuild)
817 task.AddOutputItem ("TargetOutputs", "CollectedBuildOutput");
819 if (buildTarget != "Build")
820 task.SetParameter ("Targets", buildTarget);
821 task.SetParameter ("Properties", string.Format ("Configuration={0}; Platform={1}; BuildingSolutionFile=true; CurrentSolutionConfigurationContents=$(CurrentSolutionConfigurationContents); SolutionDir=$(SolutionDir); SolutionExt=$(SolutionExt); SolutionFileName=$(SolutionFileName); SolutionName=$(SolutionName); SolutionPath=$(SolutionPath)", projectTargetInfo.Configuration, projectTargetInfo.Platform));
823 task = target.AddTask ("Message");
824 task.SetParameter ("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 (ProjectRootElement 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 var big = p.AddItemGroup ();
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.AddItem (missing_level, projectInfo.Name);
881 if (projectTargetInfo.Build) {
882 var item = big.AddItem (build_level, projectInfo.FileName);
883 item.AddMetadata ("Configuration", projectTargetInfo.Configuration);
884 item.AddMetadata ("Platform", projectTargetInfo.Platform);
887 big.AddItem (skip_level, projectInfo.Name);
893 return infosByLevel.Length;
896 void AddSolutionTargets (ProjectRootElement p, int num_levels, IEnumerable<ProjectInfo> websiteProjectInfos)
898 foreach (string buildTarget in buildTargets) {
899 var t = p.AddTarget (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 ProjectTaskElement task = null;
907 for (int i = 0; i < num_levels; i ++) {
908 string level_str = String.Format ("BuildLevel{0}", i);
909 task = t.AddTask ("MSBuild");
910 task.SetParameter ("Condition", String.Format ("'@({0})' != ''", level_str));
911 task.SetParameter ("Projects", String.Format ("@({0})", level_str));
912 task.SetParameter ("ToolsVersion", "$(ProjectToolsVersion)");
913 task.SetParameter ("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.SetParameter ("Targets", buildTarget);
917 //FIXME: change this to BuildInParallel=true, when parallel
918 // build support gets added
919 task.SetParameter ("RunEachTargetSeparately", "true");
920 if (is_build_or_rebuild)
921 task.AddOutputItem ("TargetOutputs", "CollectedBuildOutput");
923 level_str = String.Format ("SkipLevel{0}", i);
924 task = t.AddTask ("Message");
925 task.Condition = String.Format ("'@({0})' != ''", level_str);
926 task.SetParameter ("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.AddTask ("Warning");
932 task.Condition = String.Format ("'@({0})' != ''", level_str);
933 task.SetParameter ("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.AddTask ("CallTarget");
948 task.SetParameter ("Targets", w_targets.ToString ());
949 task.SetParameter ("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 ("\\", "/");