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 AddGeneralSettings (file, p);
119 StreamReader reader = new StreamReader (file);
120 string slnVersion = GetSlnFileVersion (reader);
121 if (slnVersion == "11.00")
122 p.DefaultToolsVersion = "4.0";
123 else if (slnVersion == "10.00")
124 p.DefaultToolsVersion = "3.5";
126 p.DefaultToolsVersion = "2.0";
128 string line = reader.ReadToEnd ();
129 line = line.Replace ("\r\n", "\n");
130 string solutionDir = Path.GetDirectoryName (file);
132 List<TargetInfo> solutionTargets = new List<TargetInfo> ();
133 Dictionary<Guid, ProjectInfo> projectInfos = new Dictionary<Guid, ProjectInfo> ();
134 Dictionary<Guid, ProjectInfo> websiteProjectInfos = new Dictionary<Guid, ProjectInfo> ();
135 List<ProjectInfo>[] infosByLevel = null;
136 Dictionary<Guid, ProjectInfo> unsupportedProjectInfos = new Dictionary<Guid, ProjectInfo> ();
138 Match m = projectRegex.Match (line);
140 ProjectInfo projectInfo = new ProjectInfo (m.Groups[2].Value,
141 Path.GetFullPath (Path.Combine (solutionDir,
142 m.Groups [3].Value.Replace ('\\', Path.DirectorySeparatorChar))));
143 if (String.Compare (m.Groups [1].Value, solutionFolderGuid,
144 StringComparison.InvariantCultureIgnoreCase) == 0) {
145 // Ignore solution folders
150 projectInfo.Guid = new Guid (m.Groups [4].Value);
152 if (String.Compare (m.Groups [1].Value, vcprojGuid,
153 StringComparison.InvariantCultureIgnoreCase) == 0) {
155 RaiseWarning (0, string.Format("Ignoring vcproj '{0}'.", projectInfo.Name));
157 unsupportedProjectInfos [projectInfo.Guid] = projectInfo;
162 if (String.Compare (m.Groups [1].Value, websiteProjectGuid,
163 StringComparison.InvariantCultureIgnoreCase) == 0)
164 websiteProjectInfos.Add (new Guid (m.Groups[4].Value), projectInfo);
166 projectInfos.Add (projectInfo.Guid, projectInfo);
168 Match projectSectionMatch = projectDependenciesRegex.Match (m.Groups[6].Value);
169 while (projectSectionMatch.Success) {
170 string section_name = projectSectionMatch.Groups [1].Value;
171 if (String.Compare (section_name, "ProjectDependencies") == 0) {
172 Match projectDependencyMatch = projectDependencyRegex.Match (projectSectionMatch.Value);
173 while (projectDependencyMatch.Success) {
174 // we might not have projectInfo available right now, so
175 // set it to null, and fill it in later
176 projectInfo.Dependencies [new Guid (projectDependencyMatch.Groups[1].Value)] = null;
177 projectDependencyMatch = projectDependencyMatch.NextMatch ();
180 ProjectSection section = new ProjectSection (section_name);
181 Match propertiesMatch = projectSectionPropertiesRegex.Match (
182 projectSectionMatch.Groups [2].Value);
183 while (propertiesMatch.Success) {
184 section.Properties [propertiesMatch.Groups ["name"].Value] =
185 propertiesMatch.Groups ["value"].Value;
187 propertiesMatch = propertiesMatch.NextMatch ();
190 projectInfo.ProjectSections [section_name] = section;
192 projectSectionMatch = projectSectionMatch.NextMatch ();
197 foreach (ProjectInfo projectInfo in projectInfos.Values) {
198 string filename = projectInfo.FileName;
199 string projectDir = Path.GetDirectoryName (filename);
201 if (!File.Exists (filename)) {
202 RaiseWarning (0, String.Format ("Project file {0} referenced in the solution file, " +
203 "not found. Ignoring.", filename));
207 Project currentProject = p.ParentEngine.CreateNewProject ();
209 currentProject.Load (filename, ProjectLoadSettings.IgnoreMissingImports);
210 } catch (InvalidProjectFileException e) {
211 RaiseWarning (0, e.Message);
215 foreach (BuildItem bi in currentProject.GetEvaluatedItemsByName ("ProjectReference")) {
216 ProjectInfo info = null;
217 string projectReferenceGuid = bi.GetEvaluatedMetadata ("Project");
218 bool hasGuid = !String.IsNullOrEmpty (projectReferenceGuid);
220 // try to resolve the ProjectReference by GUID
221 // and fallback to project filename
224 Guid guid = new Guid (projectReferenceGuid);
225 projectInfos.TryGetValue (guid, out info);
226 if (info == null && unsupportedProjectInfos.TryGetValue (guid, out info)) {
227 RaiseWarning (0, String.Format (
228 "{0}: ProjectReference '{1}' is of an unsupported type. Ignoring.",
229 filename, bi.Include));
234 if (info == null || !hasGuid) {
235 // Project not found by guid or guid not available
236 // Try to find by project file
238 string fullpath = Path.GetFullPath (Path.Combine (projectDir, bi.Include.Replace ('\\', Path.DirectorySeparatorChar)));
239 info = projectInfos.Values.FirstOrDefault (pi => pi.FileName == fullpath);
242 if (unsupportedProjectInfos.Values.Any (pi => pi.FileName == fullpath))
243 RaiseWarning (0, String.Format (
244 "{0}: ProjectReference '{1}' is of an unsupported type. Ignoring.",
245 filename, bi.Include));
247 RaiseWarning (0, String.Format (
248 "{0}: ProjectReference '{1}' not found, neither by guid '{2}' nor by project file name '{3}'.",
249 filename, bi.Include, projectReferenceGuid.Replace ("{", "").Replace ("}", ""), fullpath));
255 projectInfo.Dependencies [info.Guid] = info;
259 // fill in the project info for deps found in the .sln file
260 foreach (ProjectInfo projectInfo in projectInfos.Values) {
261 List<Guid> missingInfos = new List<Guid> ();
262 foreach (KeyValuePair<Guid, ProjectInfo> dependency in projectInfo.Dependencies) {
263 if (dependency.Value == null)
264 missingInfos.Add (dependency.Key);
267 foreach (Guid guid in missingInfos) {
269 if (projectInfos.TryGetValue (guid, out info))
270 projectInfo.Dependencies [guid] = info;
272 projectInfo.Dependencies.Remove (guid);
276 Match globalMatch = globalRegex.Match (line);
277 Match globalSectionMatch = globalSectionRegex.Match (globalMatch.Groups[1].Value);
278 while (globalSectionMatch.Success) {
279 string sectionType = globalSectionMatch.Groups[1].Value;
280 switch (sectionType) {
281 case "SolutionConfigurationPlatforms":
282 ParseSolutionConfigurationPlatforms (globalSectionMatch.Groups[2].Value, solutionTargets);
284 case "ProjectConfigurationPlatforms":
285 ParseProjectConfigurationPlatforms (globalSectionMatch.Groups[2].Value,
286 projectInfos, websiteProjectInfos);
288 case "SolutionProperties":
289 ParseSolutionProperties (globalSectionMatch.Groups[2].Value);
291 case "NestedProjects":
293 case "MonoDevelopProperties":
296 RaiseWarning (0, string.Format("Don't know how to handle GlobalSection {0}, Ignoring.", sectionType));
299 globalSectionMatch = globalSectionMatch.NextMatch ();
302 int num_levels = AddBuildLevels (p, solutionTargets, projectInfos, ref infosByLevel);
304 AddCurrentSolutionConfigurationContents (p, solutionTargets, projectInfos, websiteProjectInfos);
305 AddWebsiteProperties (p, websiteProjectInfos, projectInfos);
306 AddValidateSolutionConfiguration (p);
308 AddGetFrameworkPathTarget (p);
309 AddWebsiteTargets (p, websiteProjectInfos, projectInfos, infosByLevel, solutionTargets);
310 AddProjectTargets (p, solutionTargets, projectInfos);
311 AddSolutionTargets (p, num_levels, websiteProjectInfos.Values);
314 string GetSlnFileVersion (StreamReader reader)
316 string strVersion = null;
317 string strInput = null;
320 strInput = reader.ReadLine();
321 if (strInput == null)
324 match = slnVersionRegex.Match(strInput);
325 if (!match.Success) {
326 strInput = reader.ReadLine();
327 if (strInput == null)
329 match = slnVersionRegex.Match (strInput);
333 return match.Groups[1].Value;
338 void AddGeneralSettings (string solutionFile, Project p)
340 p.DefaultTargets = "Build";
341 p.InitialTargets = "ValidateSolutionConfiguration";
342 p.AddNewUsingTaskFromAssemblyName ("CreateTemporaryVCProject", "Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
343 p.AddNewUsingTaskFromAssemblyName ("ResolveVCProjectOutput", "Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
345 string solutionFilePath = Path.GetFullPath (solutionFile);
346 BuildPropertyGroup solutionPropertyGroup = p.AddNewPropertyGroup (true);
347 solutionPropertyGroup.AddNewProperty ("SolutionDir", Path.GetDirectoryName (solutionFilePath) + Path.DirectorySeparatorChar);
348 solutionPropertyGroup.AddNewProperty ("SolutionExt", Path.GetExtension (solutionFile));
349 solutionPropertyGroup.AddNewProperty ("SolutionFileName", Path.GetFileName (solutionFile));
350 solutionPropertyGroup.AddNewProperty ("SolutionName", Path.GetFileNameWithoutExtension (solutionFile));
351 solutionPropertyGroup.AddNewProperty ("SolutionPath", solutionFilePath);
354 void ParseSolutionConfigurationPlatforms (string section, List<TargetInfo> solutionTargets)
356 Match solutionConfigurationPlatform = solutionConfigurationRegex.Match (section);
357 while (solutionConfigurationPlatform.Success) {
358 string solutionConfiguration = solutionConfigurationPlatform.Groups[1].Value;
359 string solutionPlatform = solutionConfigurationPlatform.Groups[2].Value;
360 solutionTargets.Add (new TargetInfo (solutionConfiguration, solutionPlatform));
361 solutionConfigurationPlatform = solutionConfigurationPlatform.NextMatch ();
365 // ignores the website projects, in the websiteProjectInfos
366 void ParseProjectConfigurationPlatforms (string section, Dictionary<Guid, ProjectInfo> projectInfos,
367 Dictionary<Guid, ProjectInfo> websiteProjectInfos)
369 List<Guid> missingGuids = new List<Guid> ();
370 Match projectConfigurationPlatform = projectConfigurationActiveCfgRegex.Match (section);
371 while (projectConfigurationPlatform.Success) {
372 Guid guid = new Guid (projectConfigurationPlatform.Groups[1].Value);
373 ProjectInfo projectInfo;
374 if (!projectInfos.TryGetValue (guid, out projectInfo)) {
375 if (!missingGuids.Contains (guid)) {
376 if (!websiteProjectInfos.ContainsKey (guid))
377 // ignore website projects
378 RaiseWarning (0, string.Format("Failed to find project {0}", guid));
379 missingGuids.Add (guid);
381 projectConfigurationPlatform = projectConfigurationPlatform.NextMatch ();
384 string solConf = projectConfigurationPlatform.Groups[2].Value;
385 string solPlat = projectConfigurationPlatform.Groups[3].Value;
386 string projConf = projectConfigurationPlatform.Groups[4].Value;
387 string projPlat = projectConfigurationPlatform.Groups[5].Value;
388 // hack, what are they doing here?
389 if (projPlat == "Any CPU")
391 projectInfo.TargetMap.Add (new TargetInfo (solConf, solPlat), new TargetInfo (projConf, projPlat));
392 projectConfigurationPlatform = projectConfigurationPlatform.NextMatch ();
394 Match projectConfigurationPlatformBuild = projectConfigurationBuildRegex.Match (section);
395 while (projectConfigurationPlatformBuild.Success) {
396 Guid guid = new Guid (projectConfigurationPlatformBuild.Groups[1].Value);
397 ProjectInfo projectInfo;
398 if (!projectInfos.TryGetValue (guid, out projectInfo)) {
399 if (!missingGuids.Contains (guid)) {
400 RaiseWarning (0, string.Format("Failed to find project {0}", guid));
401 missingGuids.Add (guid);
403 projectConfigurationPlatformBuild = projectConfigurationPlatformBuild.NextMatch ();
406 string solConf = projectConfigurationPlatformBuild.Groups[2].Value;
407 string solPlat = projectConfigurationPlatformBuild.Groups[3].Value;
408 string projConf = projectConfigurationPlatformBuild.Groups[4].Value;
409 string projPlat = projectConfigurationPlatformBuild.Groups[5].Value;
410 // hack, what are they doing here?
411 if (projPlat == "Any CPU")
413 projectInfo.TargetMap[new TargetInfo (solConf, solPlat)] = new TargetInfo (projConf, projPlat, true);
414 projectConfigurationPlatformBuild = projectConfigurationPlatformBuild.NextMatch ();
418 void ParseSolutionProperties (string section)
422 void AddCurrentSolutionConfigurationContents (Project p, List<TargetInfo> solutionTargets,
423 Dictionary<Guid, ProjectInfo> projectInfos,
424 Dictionary<Guid, ProjectInfo> websiteProjectInfos)
426 TargetInfo default_target_info = new TargetInfo ("Debug", "Any CPU");
427 if (solutionTargets.Count > 0) {
429 foreach (TargetInfo tinfo in solutionTargets) {
430 if (String.Compare (tinfo.Platform, "Mixed Platforms") == 0) {
431 default_target_info = tinfo;
438 default_target_info = solutionTargets [0];
441 AddDefaultSolutionConfiguration (p, default_target_info);
443 foreach (TargetInfo solutionTarget in solutionTargets) {
444 BuildPropertyGroup platformPropertyGroup = p.AddNewPropertyGroup (false);
445 platformPropertyGroup.Condition = string.Format (
446 " ('$(Configuration)' == '{0}') and ('$(Platform)' == '{1}') ",
447 solutionTarget.Configuration,
448 solutionTarget.Platform
451 StringBuilder solutionConfigurationContents = new StringBuilder ();
452 solutionConfigurationContents.Append ("<SolutionConfiguration xmlns=\"\">");
453 foreach (KeyValuePair<Guid, ProjectInfo> projectInfo in projectInfos) {
454 AddProjectConfigurationItems (projectInfo.Key, projectInfo.Value, solutionTarget, solutionConfigurationContents);
456 solutionConfigurationContents.Append ("</SolutionConfiguration>");
458 platformPropertyGroup.AddNewProperty ("CurrentSolutionConfigurationContents",
459 solutionConfigurationContents.ToString ());
463 void AddProjectConfigurationItems (Guid guid, ProjectInfo projectInfo, TargetInfo solutionTarget,
464 StringBuilder solutionConfigurationContents)
466 foreach (KeyValuePair<TargetInfo, TargetInfo> targetInfo in projectInfo.TargetMap) {
467 if (solutionTarget.Configuration == targetInfo.Key.Configuration &&
468 solutionTarget.Platform == targetInfo.Key.Platform) {
469 solutionConfigurationContents.AppendFormat (
470 "<ProjectConfiguration Project=\"{0}\">{1}|{2}</ProjectConfiguration>",
471 guid.ToString ("B").ToUpper (), targetInfo.Value.Configuration, targetInfo.Value.Platform);
476 void AddDefaultSolutionConfiguration (Project p, TargetInfo target)
478 BuildPropertyGroup configurationPropertyGroup = p.AddNewPropertyGroup (true);
479 configurationPropertyGroup.Condition = " '$(Configuration)' == '' ";
480 configurationPropertyGroup.AddNewProperty ("Configuration", target.Configuration);
482 BuildPropertyGroup platformPropertyGroup = p.AddNewPropertyGroup (true);
483 platformPropertyGroup.Condition = " '$(Platform)' == '' ";
484 platformPropertyGroup.AddNewProperty ("Platform", target.Platform);
486 // emit default for AspNetConfiguration also
487 BuildPropertyGroup aspNetConfigurationPropertyGroup = p.AddNewPropertyGroup (true);
488 aspNetConfigurationPropertyGroup.Condition = " ('$(AspNetConfiguration)' == '') ";
489 aspNetConfigurationPropertyGroup.AddNewProperty ("AspNetConfiguration", "$(Configuration)");
492 void AddWarningForMissingProjectConfiguration (Target target, string slnConfig, string slnPlatform, string projectName)
494 BuildTask task = target.AddNewTask ("Warning");
495 task.SetParameterValue ("Text",
496 String.Format ("The project configuration for project '{0}' corresponding " +
497 "to the solution configuration '{1}|{2}' was not found in the solution file.",
498 projectName, slnConfig, slnPlatform));
499 task.Condition = String.Format ("('$(Configuration)' == '{0}') and ('$(Platform)' == '{1}')",
500 slnConfig, slnPlatform);
504 // Website project methods
506 void AddWebsiteProperties (Project p, Dictionary<Guid, ProjectInfo> websiteProjectInfos,
507 Dictionary<Guid, ProjectInfo> projectInfos)
509 var propertyGroupByConfig = new Dictionary<string, BuildPropertyGroup> ();
510 foreach (KeyValuePair<Guid, ProjectInfo> infoPair in websiteProjectInfos) {
511 ProjectInfo info = infoPair.Value;
512 string projectGuid = infoPair.Key.ToString ();
514 ProjectSection section;
515 if (!info.ProjectSections.TryGetValue ("WebsiteProperties", out section)) {
516 RaiseWarning (0, String.Format ("Website project '{0}' does not have the required project section: WebsiteProperties. Ignoring project.", info.Name));
520 //parse project references
521 string [] ref_guids = null;
523 if (section.Properties.TryGetValue ("ProjectReferences", out references)) {
524 ref_guids = references.Split (new char [] {';'}, StringSplitOptions.RemoveEmptyEntries);
525 for (int i = 0; i < ref_guids.Length; i ++) {
527 ref_guids [i] = ref_guids [i].Split ('|') [0];
529 Guid r_guid = new Guid (ref_guids [i]);
530 ProjectInfo ref_info;
531 if (projectInfos.TryGetValue (r_guid, out ref_info))
532 // ignore if not found
533 info.Dependencies [r_guid] = ref_info;
537 foreach (KeyValuePair<string, string> pair in section.Properties) {
538 //looking for -- ConfigName.AspNetCompiler.PropName
539 string [] parts = pair.Key.Split ('.');
540 if (parts.Length != 3 || String.Compare (parts [1], "AspNetCompiler") != 0)
543 string config = parts [0];
544 string propertyName = parts [2];
546 BuildPropertyGroup bpg;
547 if (!propertyGroupByConfig.TryGetValue (config, out bpg)) {
548 bpg = p.AddNewPropertyGroup (true);
549 bpg.Condition = String.Format (" '$(AspNetConfiguration)' == '{0}' ", config);
550 propertyGroupByConfig [config] = bpg;
553 bpg.AddNewProperty (String.Format ("Project_{0}_AspNet{1}", projectGuid, propertyName),
556 if (!info.AspNetConfigurations.Contains (config))
557 info.AspNetConfigurations.Add (config);
562 // For WebSite projects
563 // The main "Build" target:
564 // 1. builds all non-website projects
565 // 2. calls target for website project
566 // - gets target path for the referenced projects
567 // - Resolves dependencies, satellites etc for the
568 // referenced project assemblies, and copies them
570 void AddWebsiteTargets (Project p, Dictionary<Guid, ProjectInfo> websiteProjectInfos,
571 Dictionary<Guid, ProjectInfo> projectInfos, List<ProjectInfo>[] infosByLevel,
572 List<TargetInfo> solutionTargets)
574 foreach (ProjectInfo w_info in websiteProjectInfos.Values) {
575 // gets a linear list of dependencies
576 List<ProjectInfo> depInfos = new List<ProjectInfo> ();
577 foreach (List<ProjectInfo> pinfos in infosByLevel) {
578 foreach (ProjectInfo pinfo in pinfos)
579 if (w_info.Dependencies.ContainsKey (pinfo.Guid))
580 depInfos.Add (pinfo);
583 foreach (string buildTarget in new string [] {"Build", "Rebuild"})
584 AddWebsiteTarget (p, w_info, projectInfos, depInfos, solutionTargets, buildTarget);
586 // clean/publish are not supported for website projects
587 foreach (string buildTarget in new string [] {"Clean", "Publish"})
588 AddWebsiteUnsupportedTarget (p, w_info, depInfos, buildTarget);
592 void AddWebsiteTarget (Project p, ProjectInfo webProjectInfo,
593 Dictionary<Guid, ProjectInfo> projectInfos, List<ProjectInfo> depInfos,
594 List<TargetInfo> solutionTargets, string buildTarget)
596 string w_guid = webProjectInfo.Guid.ToString ().ToUpper ();
598 Target target = p.Targets.AddNewTarget (GetTargetNameForProject (webProjectInfo.Name, buildTarget));
599 target.Condition = "'$(CurrentSolutionConfigurationContents)' != ''";
600 target.DependsOnTargets = GetWebsiteDependsOnTarget (depInfos, buildTarget);
602 // this item collects all the references
603 string final_ref_item = String.Format ("Project_{0}_References{1}", w_guid,
604 buildTarget != "Build" ? "_" + buildTarget : String.Empty);
606 foreach (TargetInfo targetInfo in solutionTargets) {
608 foreach (ProjectInfo depInfo in depInfos) {
609 TargetInfo projectTargetInfo;
610 if (!depInfo.TargetMap.TryGetValue (targetInfo, out projectTargetInfo))
611 // Ignore, no config, so no target path
614 // GetTargetPath from the referenced project
615 AddWebsiteMSBuildTaskForReference (target, depInfo, projectTargetInfo, targetInfo,
616 final_ref_item, ref_num);
621 // resolve the references
622 AddWebsiteResolveAndCopyReferencesTasks (target, webProjectInfo, final_ref_item, w_guid);
625 // emits the MSBuild task to GetTargetPath for the referenced project
626 void AddWebsiteMSBuildTaskForReference (Target target, ProjectInfo depInfo, TargetInfo projectTargetInfo,
627 TargetInfo solutionTargetInfo, string final_ref_item, int ref_num)
629 BuildTask task = target.AddNewTask ("MSBuild");
630 task.SetParameterValue ("Projects", depInfo.FileName);
631 task.SetParameterValue ("Targets", "GetTargetPath");
633 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));
634 task.Condition = string.Format (" ('$(Configuration)' == '{0}') and ('$(Platform)' == '{1}') ", solutionTargetInfo.Configuration, solutionTargetInfo.Platform);
636 string ref_item = String.Format ("{0}_{1}",
637 final_ref_item, ref_num);
639 task.AddOutputItem ("TargetOutputs", ref_item);
641 task = target.AddNewTask ("CreateItem");
642 task.SetParameterValue ("Include", String.Format ("@({0})", ref_item));
643 task.SetParameterValue ("AdditionalMetadata", String.Format ("Guid={{{0}}}",
644 depInfo.Guid.ToString ().ToUpper ()));
645 task.AddOutputItem ("Include", final_ref_item);
648 void AddWebsiteResolveAndCopyReferencesTasks (Target target, ProjectInfo webProjectInfo,
649 string final_ref_item, string w_guid)
651 BuildTask task = target.AddNewTask ("ResolveAssemblyReference");
652 task.SetParameterValue ("Assemblies", String.Format ("@({0}->'%(FullPath)')", final_ref_item));
653 task.SetParameterValue ("TargetFrameworkDirectories", "$(TargetFrameworkPath)");
654 task.SetParameterValue ("SearchPaths", "{RawFileName};{TargetFrameworkDirectory};{GAC}");
655 task.SetParameterValue ("FindDependencies", "true");
656 task.SetParameterValue ("FindSatellites", "true");
657 task.SetParameterValue ("FindRelatedFiles", "true");
658 task.Condition = String.Format ("Exists ('%({0}.Identity)')", final_ref_item);
660 string copylocal_item = String.Format ("{0}_CopyLocalFiles", final_ref_item);
661 task.AddOutputItem ("CopyLocalFiles", copylocal_item);
663 // Copy the references
664 task = target.AddNewTask ("Copy");
665 task.SetParameterValue ("SourceFiles", String.Format ("@({0})", copylocal_item));
666 task.SetParameterValue ("DestinationFiles", String.Format (
667 "@({0}->'$(Project_{1}_AspNetPhysicalPath)\\Bin\\%(DestinationSubDirectory)%(Filename)%(Extension)')",
668 copylocal_item, w_guid));
670 // AspNetConfiguration, is config for the website project, useful
671 // for overriding from command line
672 StringBuilder cond = new StringBuilder ();
673 foreach (string config in webProjectInfo.AspNetConfigurations) {
675 cond.Append (" or ");
676 cond.AppendFormat (" ('$(AspNetConfiguration)' == '{0}') ", config);
678 task.Condition = cond.ToString ();
680 task = target.AddNewTask ("Message");
681 cond = new StringBuilder ();
682 foreach (string config in webProjectInfo.AspNetConfigurations) {
684 cond.Append (" and ");
685 cond.AppendFormat (" ('$(AspNetConfiguration)' != '{0}') ", config);
687 task.Condition = cond.ToString ();
688 task.SetParameterValue ("Text", "Skipping as the '$(AspNetConfiguration)' configuration is " +
689 "not supported by this website project.");
692 void AddWebsiteUnsupportedTarget (Project p, ProjectInfo webProjectInfo, List<ProjectInfo> depInfos,
695 Target target = p.Targets.AddNewTarget (GetTargetNameForProject (webProjectInfo.Name, buildTarget));
696 target.DependsOnTargets = GetWebsiteDependsOnTarget (depInfos, buildTarget);
698 BuildTask task = target.AddNewTask ("Message");
699 task.SetParameterValue ("Text", String.Format (
700 "Target '{0}' not support for website projects", buildTarget));
703 string GetWebsiteDependsOnTarget (List<ProjectInfo> depInfos, string buildTarget)
705 StringBuilder deps = new StringBuilder ();
706 foreach (ProjectInfo pinfo in depInfos) {
709 deps.Append (GetTargetNameForProject (pinfo.Name, buildTarget));
711 deps.Append (";GetFrameworkPath");
712 return deps.ToString ();
715 void AddGetFrameworkPathTarget (Project p)
717 Target t = p.Targets.AddNewTarget ("GetFrameworkPath");
718 BuildTask task = t.AddNewTask ("GetFrameworkPath");
719 task.AddOutputProperty ("Path", "TargetFrameworkPath");
722 void AddValidateSolutionConfiguration (Project p)
724 Target t = p.Targets.AddNewTarget ("ValidateSolutionConfiguration");
725 BuildTask task = t.AddNewTask ("Warning");
726 task.SetParameterValue ("Text", "On windows, an environment variable 'Platform' is set to MCD sometimes, and this overrides the Platform property" +
727 " for xbuild, which could be an invalid Platform for this solution file. And so you are getting the following error." +
728 " You could override it by either setting the environment variable to nothing, as\n" +
730 "Or explicity specify its value on the command line, as\n" +
731 " xbuild Foo.sln /p:Platform=Release");
732 task.Condition = "('$(CurrentSolutionConfigurationContents)' == '') and ('$(SkipInvalidConfigurations)' != 'true')" +
733 " and '$(Platform)' == 'MCD' and '$(OS)' == 'Windows_NT'";
735 task = t.AddNewTask ("Error");
736 task.SetParameterValue ("Text", "Invalid solution configuration and platform: \"$(Configuration)|$(Platform)\".");
737 task.Condition = "('$(CurrentSolutionConfigurationContents)' == '') and ('$(SkipInvalidConfigurations)' != 'true')";
738 task = t.AddNewTask ("Warning");
739 task.SetParameterValue ("Text", "Invalid solution configuration and platform: \"$(Configuration)|$(Platform)\".");
740 task.Condition = "('$(CurrentSolutionConfigurationContents)' == '') and ('$(SkipInvalidConfigurations)' == 'true')";
741 task = t.AddNewTask ("Message");
742 task.SetParameterValue ("Text", "Building solution configuration \"$(Configuration)|$(Platform)\".");
743 task.Condition = "'$(CurrentSolutionConfigurationContents)' != ''";
746 void AddProjectTargets (Project p, List<TargetInfo> solutionTargets, Dictionary<Guid, ProjectInfo> projectInfos)
748 foreach (KeyValuePair<Guid, ProjectInfo> projectInfo in projectInfos) {
749 ProjectInfo project = projectInfo.Value;
750 foreach (string buildTarget in buildTargets) {
751 string target_name = GetTargetNameForProject (project.Name, buildTarget);
752 Target target = p.Targets.AddNewTarget (target_name);
753 target.Condition = "'$(CurrentSolutionConfigurationContents)' != ''";
754 if (project.Dependencies.Count > 0)
755 target.DependsOnTargets = String.Join (";",
756 project.Dependencies.Values.Select (
757 di => GetTargetNameForProject (di.Name, buildTarget)).ToArray ());
759 foreach (TargetInfo targetInfo in solutionTargets) {
760 BuildTask task = null;
761 TargetInfo projectTargetInfo;
762 if (!project.TargetMap.TryGetValue (targetInfo, out projectTargetInfo)) {
763 AddWarningForMissingProjectConfiguration (target, targetInfo.Configuration,
764 targetInfo.Platform, project.Name);
767 if (projectTargetInfo.Build) {
768 task = target.AddNewTask ("MSBuild");
769 task.SetParameterValue ("Projects", project.FileName);
770 task.SetParameterValue ("ToolsVersion", "$(ProjectToolsVersion)");
772 if (buildTarget != "Build")
773 task.SetParameterValue ("Targets", buildTarget);
774 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));
776 task = target.AddNewTask ("Message");
777 task.SetParameterValue ("Text", string.Format ("Project \"{0}\" is disabled for solution configuration \"{1}|{2}\".", project.Name, targetInfo.Configuration, targetInfo.Platform));
779 task.Condition = string.Format (" ('$(Configuration)' == '{0}') and ('$(Platform)' == '{1}') ", targetInfo.Configuration, targetInfo.Platform);
786 string GetTargetNameForProject (string projectName, string buildTarget)
789 projectName = projectName.Replace ("\\", "/").Replace (".", "_");
790 string target_name = projectName +
791 (buildTarget == "Build" ? string.Empty : ":" + buildTarget);
793 if (IsBuildTargetName (projectName))
794 target_name = "Solution:" + target_name;
799 bool IsBuildTargetName (string name)
801 foreach (string tgt in buildTargets)
807 // returns number of levels
808 int AddBuildLevels (Project p, List<TargetInfo> solutionTargets, Dictionary<Guid, ProjectInfo> projectInfos,
809 ref List<ProjectInfo>[] infosByLevel)
811 infosByLevel = TopologicalSort<ProjectInfo> (projectInfos.Values);
813 foreach (TargetInfo targetInfo in solutionTargets) {
814 BuildItemGroup big = p.AddNewItemGroup ();
815 big.Condition = String.Format (" ('$(Configuration)' == '{0}') and ('$(Platform)' == '{1}') ",
816 targetInfo.Configuration, targetInfo.Platform);
818 //FIXME: every level has projects that can be built in parallel.
819 // levels are ordered on the basis of the dependency graph
821 for (int i = 0; i < infosByLevel.Length; i ++) {
822 string build_level = String.Format ("BuildLevel{0}", i);
823 string skip_level = String.Format ("SkipLevel{0}", i);
824 string missing_level = String.Format ("MissingConfigLevel{0}", i);
826 foreach (ProjectInfo projectInfo in infosByLevel [i]) {
827 TargetInfo projectTargetInfo;
828 if (!projectInfo.TargetMap.TryGetValue (targetInfo, out projectTargetInfo)) {
829 // missing project config
830 big.AddNewItem (missing_level, projectInfo.Name);
834 if (projectTargetInfo.Build) {
835 BuildItem item = big.AddNewItem (build_level, projectInfo.FileName);
836 item.SetMetadata ("Configuration", projectTargetInfo.Configuration);
837 item.SetMetadata ("Platform", projectTargetInfo.Platform);
840 big.AddNewItem (skip_level, projectInfo.Name);
846 return infosByLevel.Length;
849 void AddSolutionTargets (Project p, int num_levels, IEnumerable<ProjectInfo> websiteProjectInfos)
851 foreach (string buildTarget in buildTargets) {
852 Target t = p.Targets.AddNewTarget (buildTarget);
853 t.Condition = "'$(CurrentSolutionConfigurationContents)' != ''";
855 BuildTask task = null;
856 for (int i = 0; i < num_levels; i ++) {
857 string level_str = String.Format ("BuildLevel{0}", i);
858 task = t.AddNewTask ("MSBuild");
859 task.SetParameterValue ("Condition", String.Format ("'@({0})' != ''", level_str));
860 task.SetParameterValue ("Projects", String.Format ("@({0})", level_str));
861 task.SetParameterValue ("ToolsVersion", "$(ProjectToolsVersion)");
862 task.SetParameterValue ("Properties",
863 string.Format ("Configuration=%(Configuration); Platform=%(Platform); BuildingSolutionFile=true; CurrentSolutionConfigurationContents=$(CurrentSolutionConfigurationContents); SolutionDir=$(SolutionDir); SolutionExt=$(SolutionExt); SolutionFileName=$(SolutionFileName); SolutionName=$(SolutionName); SolutionPath=$(SolutionPath)"));
864 if (buildTarget != "Build")
865 task.SetParameterValue ("Targets", buildTarget);
866 //FIXME: change this to BuildInParallel=true, when parallel
867 // build support gets added
868 task.SetParameterValue ("RunEachTargetSeparately", "true");
870 level_str = String.Format ("SkipLevel{0}", i);
871 task = t.AddNewTask ("Message");
872 task.Condition = String.Format ("'@({0})' != ''", level_str);
873 task.SetParameterValue ("Text",
874 String.Format ("The project '%({0}.Identity)' is disabled for solution " +
875 "configuration '$(Configuration)|$(Platform)'.", level_str));
877 level_str = String.Format ("MissingConfigLevel{0}", i);
878 task = t.AddNewTask ("Warning");
879 task.Condition = String.Format ("'@({0})' != ''", level_str);
880 task.SetParameterValue ("Text",
881 String.Format ("The project configuration for project '%({0}.Identity)' " +
882 "corresponding to the solution configuration " +
883 "'$(Configuration)|$(Platform)' was not found.", level_str));
886 // "build" website projects also
887 StringBuilder w_targets = new StringBuilder ();
888 foreach (ProjectInfo info in websiteProjectInfos) {
889 if (w_targets.Length > 0)
890 w_targets.Append (";");
891 w_targets.Append (GetTargetNameForProject (info.Name, buildTarget));
894 task = t.AddNewTask ("CallTarget");
895 task.SetParameterValue ("Targets", w_targets.ToString ());
896 task.SetParameterValue ("RunEachTargetSeparately", "true");
900 // Sorts the ProjectInfo dependency graph, to obtain
901 // a series of build levels with projects. Projects
902 // in each level can be run parallel (no inter-dependency).
903 static List<T>[] TopologicalSort<T> (IEnumerable<T> items) where T: ProjectInfo
906 allItems = items as IList<T>;
907 if (allItems == null)
908 allItems = new List<T> (items);
910 bool[] inserted = new bool[allItems.Count];
911 bool[] triedToInsert = new bool[allItems.Count];
912 int[] levels = new int [allItems.Count];
915 for (int i = 0; i < allItems.Count; ++i) {
916 int d = Insert<T> (i, allItems, levels, inserted, triedToInsert);
921 // Separate out the project infos by build level
922 List<T>[] infosByLevel = new List<T>[maxdepth];
923 for (int i = 0; i < levels.Length; i ++) {
924 int level = levels [i] - 1;
925 if (infosByLevel [level] == null)
926 infosByLevel [level] = new List<T> ();
928 infosByLevel [level].Add (allItems [i]);
934 // returns level# for the project
935 static int Insert<T> (int index, IList<T> allItems, int[] levels, bool[] inserted, bool[] triedToInsert)
938 if (inserted [index])
939 return levels [index];
941 if (triedToInsert[index])
942 throw new InvalidOperationException (String.Format (
943 "Cyclic dependency involving project {0} found in the project dependency graph",
944 allItems [index].Name));
946 triedToInsert[index] = true;
947 ProjectInfo insertItem = allItems[index];
950 foreach (ProjectInfo dependency in insertItem.Dependencies.Values) {
951 for (int j = 0; j < allItems.Count; ++j) {
952 ProjectInfo checkItem = allItems [j];
953 if (dependency.FileName == checkItem.FileName) {
954 int d = Insert (j, allItems, levels, inserted, triedToInsert);
955 maxdepth = d > maxdepth ? d : maxdepth;
960 levels [index] = maxdepth + 1;
961 inserted [index] = true;
963 return levels [index];
966 public static IEnumerable<string> GetAllProjectFileNames (string solutionFile)
968 StreamReader reader = new StreamReader (solutionFile);
969 string line = reader.ReadToEnd ();
970 line = line.Replace ("\r\n", "\n");
971 string soln_dir = Path.GetDirectoryName (solutionFile);
973 Match m = projectRegex.Match (line);
975 if (String.Compare (m.Groups [1].Value, solutionFolderGuid,
976 StringComparison.InvariantCultureIgnoreCase) != 0)
977 yield return Path.Combine (soln_dir, m.Groups [3].Value).Replace ("\\", "/");