Add missing built-in properties. Resolve properties on import paths. Resolve \ with...
[mono.git] / mcs / class / Microsoft.Build / Microsoft.Build.Evaluation / ProjectCollection.cs
1 //
2 // ProjectCollection.cs
3 //
4 // Author:
5 //   Leszek Ciesielski (skolima@gmail.com)
6 //   Rolf Bjarne Kvinge (rolf@xamarin.com)
7 //   Atsushi Enomoto (atsushi@xamarin.com)
8 //
9 // (C) 2011 Leszek Ciesielski
10 // Copyright (C) 2011,2013 Xamarin Inc.
11 //
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:
19 // 
20 // The above copyright notice and this permission notice shall be
21 // included in all copies or substantial portions of the Software.
22 // 
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.
30 //
31
32 using Microsoft.Build.Construction;
33 using Microsoft.Build.Execution;
34 using Microsoft.Build.Framework;
35 using Microsoft.Build.Logging;
36 using Microsoft.Build.Utilities;
37 using System;
38 using System.Collections.Generic;
39 using System.Collections.ObjectModel;
40 using System.IO;
41 using System.Linq;
42 using System.Xml;
43 using System.Reflection;
44
45 namespace Microsoft.Build.Evaluation
46 {
47         public class ProjectCollection : IDisposable
48         {
49                 public delegate void ProjectAddedEventHandler (object target, ProjectAddedToProjectCollectionEventArgs args);
50                 
51                 public class ProjectAddedToProjectCollectionEventArgs : EventArgs
52                 {
53                         public ProjectAddedToProjectCollectionEventArgs (ProjectRootElement project)
54                         {
55                                 if (project == null)
56                                         throw new ArgumentNullException ("project");
57                                 ProjectRootElement = project;
58                         }
59                         
60                         public ProjectRootElement ProjectRootElement { get; private set; }
61                 }
62
63                 // static members
64
65                 static readonly ProjectCollection global_project_collection;
66
67                 static ProjectCollection ()
68                 {
69                         #if NET_4_5
70                         global_project_collection = new ProjectCollection (new ReadOnlyDictionary<string, string> (new Dictionary<string, string> ()));
71                         #else
72                         global_project_collection = new ProjectCollection (new Dictionary<string, string> ());
73                         #endif
74                 }
75
76                 public static string Escape (string unescapedString)
77                 {
78                         return Mono.XBuild.Utilities.MSBuildUtils.Escape (unescapedString);
79                 }
80
81                 public static string Unescape (string escapedString)
82                 {
83                         return Mono.XBuild.Utilities.MSBuildUtils.Unescape (escapedString);
84                 }
85
86                 public static ProjectCollection GlobalProjectCollection {
87                         get { return global_project_collection; }
88                 }
89
90                 // semantic model part
91
92                 public ProjectCollection ()
93                         : this (null)
94                 {
95                 }
96
97                 public ProjectCollection (IDictionary<string, string> globalProperties)
98                 : this (globalProperties, null, ToolsetDefinitionLocations.Registry | ToolsetDefinitionLocations.ConfigurationFile)
99                 {
100                 }
101
102                 public ProjectCollection (ToolsetDefinitionLocations toolsetDefinitionLocations)
103                 : this (null, null, toolsetDefinitionLocations)
104                 {
105                 }
106
107                 public ProjectCollection (IDictionary<string, string> globalProperties, IEnumerable<ILogger> loggers,
108                                 ToolsetDefinitionLocations toolsetDefinitionLocations)
109                         : this (globalProperties, loggers, null, toolsetDefinitionLocations, int.MaxValue, false)
110                 {
111                 }
112
113                 public ProjectCollection (IDictionary<string, string> globalProperties,
114                                 IEnumerable<ILogger> loggers, IEnumerable<ForwardingLoggerRecord> remoteLoggers,
115                                 ToolsetDefinitionLocations toolsetDefinitionLocations,
116                                 int maxNodeCount, bool onlyLogCriticalEvents)
117                 {
118                         global_properties = globalProperties ?? new Dictionary<string, string> ();
119                         this.loggers = loggers != null ? loggers.ToList () : new List<ILogger> ();
120                         toolset_locations = toolsetDefinitionLocations;
121                         max_node_count = maxNodeCount;
122                         OnlyLogCriticalEvents = onlyLogCriticalEvents;
123
124                         LoadDefaultToolsets ();
125                 }
126                 
127                 [MonoTODO ("not fired yet")]
128                 public event ProjectAddedEventHandler ProjectAdded;
129                 [MonoTODO ("not fired yet")]
130                 public event EventHandler<ProjectChangedEventArgs> ProjectChanged;
131                 [MonoTODO ("not fired yet")]
132                 public event EventHandler<ProjectCollectionChangedEventArgs> ProjectCollectionChanged;
133                 [MonoTODO ("not fired yet")]
134                 public event EventHandler<ProjectXmlChangedEventArgs> ProjectXmlChanged;
135
136                 readonly int max_node_count;
137
138                 public void AddProject (Project project)
139                 {
140                         this.loaded_projects.Add (project);
141                         if (ProjectAdded != null)
142                                 ProjectAdded (this, new ProjectAddedToProjectCollectionEventArgs (project.Xml));
143                 }
144
145                 public int Count {
146                         get { return loaded_projects.Count; }
147                 }
148
149                 public string DefaultToolsVersion {
150                         get { return Toolsets.Any () ? Toolsets.First ().ToolsVersion : null; }
151                 }
152
153                 public void Dispose ()
154                 {
155                         Dispose (true);
156                         GC.SuppressFinalize (this);
157                 }
158
159                 protected virtual void Dispose (bool disposing)
160                 {
161                         if (disposing) {
162                         }
163                 }
164
165                 public ICollection<Project> GetLoadedProjects (string fullPath)
166                 {
167                         return LoadedProjects.Where (p => p.FullPath != null && Path.GetFullPath (p.FullPath) == Path.GetFullPath (fullPath)).ToList ();
168                 }
169
170                 readonly IDictionary<string, string> global_properties;
171
172                 public IDictionary<string, string> GlobalProperties {
173                         get { return global_properties; }
174                 }
175
176                 readonly List<Project> loaded_projects = new List<Project> ();
177                 
178                 public Project LoadProject (string fileName)
179                 {
180                         return LoadProject (fileName, DefaultToolsVersion);
181                 }
182                 
183                 public Project LoadProject (string fileName, string toolsVersion)
184                 {
185                         return LoadProject (fileName, toolsVersion);
186                 }
187                 
188                 public Project LoadProject (string fileName, IDictionary<string,string> globalProperties, string toolsVersion)
189                 {
190                         return new Project (fileName, globalProperties, toolsVersion);
191                 }
192                 
193                 // These methods somehow don't add the project to ProjectCollection...
194                 public Project LoadProject (XmlReader xmlReader)
195                 {
196                         return LoadProject (xmlReader, DefaultToolsVersion);
197                 }
198                 
199                 public Project LoadProject (XmlReader xmlReader, string toolsVersion)
200                 {
201                         return LoadProject (xmlReader, null, toolsVersion);
202                 }
203                 
204                 public Project LoadProject (XmlReader xmlReader, IDictionary<string,string> globalProperties, string toolsVersion)
205                 {
206                         return new Project (xmlReader, globalProperties, toolsVersion);
207                 }
208                 
209                 public ICollection<Project> LoadedProjects {
210                         get { return loaded_projects; }
211                 }
212
213                 readonly List<ILogger> loggers = new List<ILogger> ();
214                 [MonoTODO]
215                 public ICollection<ILogger> Loggers {
216                         get { return loggers; }
217                 }
218
219                 [MonoTODO]
220                 public bool OnlyLogCriticalEvents { get; set; }
221
222                 [MonoTODO]
223                 public bool SkipEvaluation { get; set; }
224
225                 readonly ToolsetDefinitionLocations toolset_locations;
226                 public ToolsetDefinitionLocations ToolsetLocations {
227                         get { return toolset_locations; }
228                 }
229
230                 readonly List<Toolset> toolsets = new List<Toolset> ();
231                 // so what should we do without ToolLocationHelper in Microsoft.Build.Utilities.dll? There is no reference to it in this dll.
232                 public ICollection<Toolset> Toolsets {
233                         // For ConfigurationFile and None, they cannot be added externally.
234                         get { return (ToolsetLocations & ToolsetDefinitionLocations.Registry) != 0 ? toolsets : toolsets.ToList (); }
235                 }
236                 
237                 public Toolset GetToolset (string toolsVersion)
238                 {
239                         return Toolsets.FirstOrDefault (t => t.ToolsVersion == toolsVersion);
240                 }
241
242                 //FIXME: should also support config file, depending on ToolsetLocations
243                 void LoadDefaultToolsets ()
244                 {
245                         AddToolset (new Toolset ("2.0",
246                                 ToolLocationHelper.GetPathToDotNetFramework (TargetDotNetFrameworkVersion.Version20), this, null));
247                         AddToolset (new Toolset ("3.0",
248                                 ToolLocationHelper.GetPathToDotNetFramework (TargetDotNetFrameworkVersion.Version30), this, null));
249                         AddToolset (new Toolset ("3.5",
250                                 ToolLocationHelper.GetPathToDotNetFramework (TargetDotNetFrameworkVersion.Version35), this, null));
251 #if NET_4_0
252                         AddToolset (new Toolset ("4.0",
253                                 ToolLocationHelper.GetPathToDotNetFramework (TargetDotNetFrameworkVersion.Version40), this, null));
254 #endif
255 #if NET_4_5
256                         AddToolset (new Toolset ("4.5",
257                                 ToolLocationHelper.GetPathToDotNetFramework (TargetDotNetFrameworkVersion.Version45), this, null));
258 #endif
259                 }
260                 
261                 [MonoTODO ("not verified at all")]
262                 public void AddToolset (Toolset toolset)
263                 {
264                         toolsets.Add (toolset);
265                 }
266                 
267                 [MonoTODO ("not verified at all")]
268                 public void RemoveAllToolsets ()
269                 {
270                         toolsets.Clear ();
271                 }
272                 
273                 [MonoTODO ("not verified at all")]
274                 public void RegisterLogger (ILogger logger)
275                 {
276                         loggers.Add (logger);
277                 }
278                 
279                 [MonoTODO ("not verified at all")]
280                 public void RegisterLoggers (IEnumerable<ILogger> loggers)
281                 {
282                         foreach (var logger in loggers)
283                                 this.loggers.Add (logger);
284                 }
285
286                 public void UnloadAllProjects ()
287                 {
288                         throw new NotImplementedException ();
289                 }
290
291                 public void UnloadProject (Project project)
292                 {
293                         throw new NotImplementedException ();
294                 }
295
296                 public void UnloadProject (ProjectRootElement projectRootElement)
297                 {
298                         throw new NotImplementedException ();
299                 }
300
301                 public static Version Version {
302                         get { throw new NotImplementedException (); }
303                 }
304
305                 // Execution part
306
307                 [MonoTODO]
308                 public bool DisableMarkDirty { get; set; }
309
310                 [MonoTODO]
311                 public HostServices HostServices { get; set; }
312
313                 [MonoTODO]
314                 public bool IsBuildEnabled { get; set; }
315                 
316                 internal string BuildStartupDirectory { get; set; }
317                 
318                 Stack<string> ongoing_imports = new Stack<string> ();
319                 
320                 internal Stack<string> OngoingImports {
321                         get { return ongoing_imports; }
322                 }
323                 
324                 // common part
325                 internal static IEnumerable<EnvironmentProjectProperty> GetWellKnownProperties (Project project)
326                 {
327                         Func<string,string,EnvironmentProjectProperty> create = (name, value) => new EnvironmentProjectProperty (project, name, value, true);
328                         return GetWellKnownProperties (create);
329                 }
330                 
331                 internal static IEnumerable<ProjectPropertyInstance> GetWellKnownProperties (ProjectInstance project)
332                 {
333                         Func<string,string,ProjectPropertyInstance> create = (name, value) => new ProjectPropertyInstance (name, true, value);
334                         return GetWellKnownProperties (create);
335                 }
336                 
337                 static IEnumerable<T> GetWellKnownProperties<T> (Func<string,string,T> create)
338                 {
339                         var ext = Environment.GetEnvironmentVariable ("MSBuildExtensionsPath") ?? DefaultExtensionsPath;
340                         yield return create ("MSBuildExtensionsPath", ext);
341                         var ext32 = Environment.GetEnvironmentVariable ("MSBuildExtensionsPath32") ?? DefaultExtensionsPath;
342                         yield return create ("MSBuildExtensionsPath32", ext32);
343                         var ext64 = Environment.GetEnvironmentVariable ("MSBuildExtensionsPath64") ?? DefaultExtensionsPath;
344                         yield return create ("MSBuildExtensionsPath64", ext64);
345                 }
346
347                 static string extensions_path;
348                 internal static string DefaultExtensionsPath {
349                         get {
350                                 if (extensions_path == null) {
351                                         // NOTE: code from mcs/tools/gacutil/driver.cs
352                                         PropertyInfo gac = typeof (System.Environment).GetProperty (
353                                                         "GacPath", BindingFlags.Static | BindingFlags.NonPublic);
354
355                                         if (gac != null) {
356                                                 MethodInfo get_gac = gac.GetGetMethod (true);
357                                                 string gac_path = (string) get_gac.Invoke (null, null);
358                                                 extensions_path = Path.GetFullPath (Path.Combine (
359                                                                         gac_path, Path.Combine ("..", "xbuild")));
360                                         }
361                                 }
362                                 return extensions_path;
363                         }
364                 }
365                 
366                 internal IEnumerable<ReservedProjectProperty> GetReservedProperties (Toolset toolset, Project project)
367                 {
368                         Func<string,Func<string>,ReservedProjectProperty> create = (name, value) => new ReservedProjectProperty (project, name, value);
369                         return GetReservedProperties<ReservedProjectProperty> (toolset, project.Xml, create, () => project.FullPath);
370                 }
371                 
372                 internal IEnumerable<ProjectPropertyInstance> GetReservedProperties (Toolset toolset, ProjectInstance project, ProjectRootElement xml)
373                 {
374                         Func<string,Func<string>,ProjectPropertyInstance> create = (name, value) => new ProjectPropertyInstance (name, true, null, value);
375                         return GetReservedProperties<ProjectPropertyInstance> (toolset, xml, create, () => project.FullPath);
376                 }
377                 
378                 // seealso http://msdn.microsoft.com/en-us/library/ms164309.aspx
379                 IEnumerable<T> GetReservedProperties<T> (Toolset toolset, ProjectRootElement project, Func<string,Func<string>,T> create, Func<string> projectFullPath)
380                 {
381                         yield return create ("MSBuildBinPath", () => toolset.ToolsPath);
382                         // FIXME: add MSBuildLastTaskResult
383                         // FIXME: add MSBuildNodeCount
384                         // FIXME: add MSBuildProgramFiles32
385                         yield return create ("MSBuildProjectDefaultTargets", () => project.DefaultTargets);
386                         yield return create ("MSBuildProjectDirectory", () => project.DirectoryPath + Path.DirectorySeparatorChar);
387                         yield return create ("MSBuildProjectDirectoryNoRoot", () => project.DirectoryPath.Substring (Path.GetPathRoot (project.DirectoryPath).Length));
388                         yield return create ("MSBuildProjectExtension", () => Path.GetExtension (project.FullPath));
389                         yield return create ("MSBuildProjectFile", () => Path.GetFileName (project.FullPath));
390                         yield return create ("MSBuildProjectFullPath", () => project.FullPath);
391                         yield return create ("MSBuildProjectName", () => Path.GetFileNameWithoutExtension (project.FullPath));
392                         yield return create ("MSBuildStartupDirectory", () => BuildStartupDirectory);
393                         yield return create ("MSBuildThisFile", () => Path.GetFileName (GetEvaluationTimeThisFile (projectFullPath)));
394                         yield return create ("MSBuildThisFileFullPath", () => GetEvaluationTimeThisFile (projectFullPath));
395                         yield return create ("MSBuildThisFileName", () => Path.GetFileNameWithoutExtension (GetEvaluationTimeThisFile (projectFullPath)));
396                         yield return create ("MSBuildThisFileExtension", () => Path.GetExtension (GetEvaluationTimeThisFile (projectFullPath)));
397
398                         yield return create ("MSBuildThisFileDirectory", () => Path.GetDirectoryName (GetEvaluationTimeThisFileDirectory (projectFullPath)));
399                         yield return create ("MSBuildThisFileDirectoryNoRoot", () => {
400                                 string dir = GetEvaluationTimeThisFileDirectory (projectFullPath) + Path.DirectorySeparatorChar;
401                                 return dir.Substring (Path.GetPathRoot (dir).Length);
402                                 });
403                         yield return create ("MSBuildToolsPath", () => toolset.ToolsPath);
404                         yield return create ("MSBuildToolsVersion", () => toolset.ToolsVersion);
405                 }
406                 
407                 // These are required for reserved property, represents dynamically changing property values.
408                 // This should resolve to either the project file path or that of the imported file.
409                 internal string GetEvaluationTimeThisFileDirectory (Func<string> nonImportingTimeFullPath)
410                 {
411                         var file = GetEvaluationTimeThisFile (nonImportingTimeFullPath);
412                         var dir = Path.IsPathRooted (file) ? Path.GetDirectoryName (file) : Directory.GetCurrentDirectory ();
413                         return dir + Path.DirectorySeparatorChar;
414                 }
415
416                 internal string GetEvaluationTimeThisFile (Func<string> nonImportingTimeFullPath)
417                 {
418                         return OngoingImports.Count > 0 ? OngoingImports.Peek () : (nonImportingTimeFullPath () ?? string.Empty);
419                 }
420         }
421 }