Well-Known metadata support is now in ProjectItemInstance too, sharing code 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 using System.Globalization;
45
46 namespace Microsoft.Build.Evaluation
47 {
48         public class ProjectCollection : IDisposable
49         {
50                 public delegate void ProjectAddedEventHandler (object target, ProjectAddedToProjectCollectionEventArgs args);
51                 
52                 public class ProjectAddedToProjectCollectionEventArgs : EventArgs
53                 {
54                         public ProjectAddedToProjectCollectionEventArgs (ProjectRootElement project)
55                         {
56                                 if (project == null)
57                                         throw new ArgumentNullException ("project");
58                                 ProjectRootElement = project;
59                         }
60                         
61                         public ProjectRootElement ProjectRootElement { get; private set; }
62                 }
63
64                 // static members
65
66                 static readonly ProjectCollection global_project_collection;
67
68                 static ProjectCollection ()
69                 {
70                         #if NET_4_5
71                         global_project_collection = new ProjectCollection (new ReadOnlyDictionary<string, string> (new Dictionary<string, string> ()));
72                         #else
73                         global_project_collection = new ProjectCollection (new Dictionary<string, string> ());
74                         #endif
75                 }
76
77                 public static string Escape (string unescapedString)
78                 {
79                         return Mono.XBuild.Utilities.MSBuildUtils.Escape (unescapedString);
80                 }
81
82                 public static string Unescape (string escapedString)
83                 {
84                         return Mono.XBuild.Utilities.MSBuildUtils.Unescape (escapedString);
85                 }
86
87                 public static ProjectCollection GlobalProjectCollection {
88                         get { return global_project_collection; }
89                 }
90
91                 // semantic model part
92
93                 public ProjectCollection ()
94                         : this (null)
95                 {
96                 }
97
98                 public ProjectCollection (IDictionary<string, string> globalProperties)
99                 : this (globalProperties, null, ToolsetDefinitionLocations.Registry | ToolsetDefinitionLocations.ConfigurationFile)
100                 {
101                 }
102
103                 public ProjectCollection (ToolsetDefinitionLocations toolsetDefinitionLocations)
104                 : this (null, null, toolsetDefinitionLocations)
105                 {
106                 }
107
108                 public ProjectCollection (IDictionary<string, string> globalProperties, IEnumerable<ILogger> loggers,
109                                 ToolsetDefinitionLocations toolsetDefinitionLocations)
110                         : this (globalProperties, loggers, null, toolsetDefinitionLocations, 1, false)
111                 {
112                 }
113
114                 public ProjectCollection (IDictionary<string, string> globalProperties,
115                                 IEnumerable<ILogger> loggers, IEnumerable<ForwardingLoggerRecord> remoteLoggers,
116                                 ToolsetDefinitionLocations toolsetDefinitionLocations,
117                                 int maxNodeCount, bool onlyLogCriticalEvents)
118                 {
119                         global_properties = globalProperties ?? new Dictionary<string, string> ();
120                         this.loggers = loggers != null ? loggers.ToList () : new List<ILogger> ();
121                         toolset_locations = toolsetDefinitionLocations;
122                         MaxNodeCount = maxNodeCount;
123                         OnlyLogCriticalEvents = onlyLogCriticalEvents;
124
125                         LoadDefaultToolsets ();
126                 }
127                 
128                 [MonoTODO ("not fired yet")]
129                 public event ProjectAddedEventHandler ProjectAdded;
130                 [MonoTODO ("not fired yet")]
131                 public event EventHandler<ProjectChangedEventArgs> ProjectChanged;
132                 [MonoTODO ("not fired yet")]
133                 public event EventHandler<ProjectCollectionChangedEventArgs> ProjectCollectionChanged;
134                 [MonoTODO ("not fired yet")]
135                 public event EventHandler<ProjectXmlChangedEventArgs> ProjectXmlChanged;
136
137                 public void AddProject (Project project)
138                 {
139                         this.loaded_projects.Add (project);
140                         if (ProjectAdded != null)
141                                 ProjectAdded (this, new ProjectAddedToProjectCollectionEventArgs (project.Xml));
142                 }
143
144                 public int Count {
145                         get { return loaded_projects.Count; }
146                 }
147
148                 public string DefaultToolsVersion {
149                         get { return Toolsets.Any () ? Toolsets.First ().ToolsVersion : null; }
150                 }
151
152                 public void Dispose ()
153                 {
154                         Dispose (true);
155                         GC.SuppressFinalize (this);
156                 }
157
158                 protected virtual void Dispose (bool disposing)
159                 {
160                         if (disposing) {
161                         }
162                 }
163
164                 public ICollection<Project> GetLoadedProjects (string fullPath)
165                 {
166                         return LoadedProjects.Where (p => p.FullPath != null && Path.GetFullPath (p.FullPath) == Path.GetFullPath (fullPath)).ToList ();
167                 }
168
169                 readonly IDictionary<string, string> global_properties;
170
171                 public IDictionary<string, string> GlobalProperties {
172                         get { return global_properties; }
173                 }
174
175                 readonly List<Project> loaded_projects = new List<Project> ();
176                 
177                 public Project LoadProject (string fileName)
178                 {
179                         return LoadProject (fileName, DefaultToolsVersion);
180                 }
181                 
182                 public Project LoadProject (string fileName, string toolsVersion)
183                 {
184                         return LoadProject (fileName, toolsVersion);
185                 }
186                 
187                 public Project LoadProject (string fileName, IDictionary<string,string> globalProperties, string toolsVersion)
188                 {
189                         return new Project (fileName, globalProperties, toolsVersion);
190                 }
191                 
192                 // These methods somehow don't add the project to ProjectCollection...
193                 public Project LoadProject (XmlReader xmlReader)
194                 {
195                         return LoadProject (xmlReader, DefaultToolsVersion);
196                 }
197                 
198                 public Project LoadProject (XmlReader xmlReader, string toolsVersion)
199                 {
200                         return LoadProject (xmlReader, null, toolsVersion);
201                 }
202                 
203                 public Project LoadProject (XmlReader xmlReader, IDictionary<string,string> globalProperties, string toolsVersion)
204                 {
205                         return new Project (xmlReader, globalProperties, toolsVersion);
206                 }
207                 
208                 public ICollection<Project> LoadedProjects {
209                         get { return loaded_projects; }
210                 }
211
212                 readonly List<ILogger> loggers = new List<ILogger> ();
213                 [MonoTODO]
214                 public ICollection<ILogger> Loggers {
215                         get { return loggers; }
216                 }
217
218                 [MonoTODO]
219                 public bool OnlyLogCriticalEvents { get; set; }
220
221                 [MonoTODO]
222                 public bool SkipEvaluation { get; set; }
223
224                 readonly ToolsetDefinitionLocations toolset_locations;
225                 public ToolsetDefinitionLocations ToolsetLocations {
226                         get { return toolset_locations; }
227                 }
228
229                 readonly List<Toolset> toolsets = new List<Toolset> ();
230                 // so what should we do without ToolLocationHelper in Microsoft.Build.Utilities.dll? There is no reference to it in this dll.
231                 public ICollection<Toolset> Toolsets {
232                         // For ConfigurationFile and None, they cannot be added externally.
233                         get { return (ToolsetLocations & ToolsetDefinitionLocations.Registry) != 0 ? toolsets : toolsets.ToList (); }
234                 }
235                 
236                 public Toolset GetToolset (string toolsVersion)
237                 {
238                         return Toolsets.FirstOrDefault (t => t.ToolsVersion == toolsVersion);
239                 }
240
241                 //FIXME: should also support config file, depending on ToolsetLocations
242                 void LoadDefaultToolsets ()
243                 {
244                         AddToolset (new Toolset ("2.0",
245                                 ToolLocationHelper.GetPathToDotNetFramework (TargetDotNetFrameworkVersion.Version20), this, null));
246                         AddToolset (new Toolset ("3.0",
247                                 ToolLocationHelper.GetPathToDotNetFramework (TargetDotNetFrameworkVersion.Version30), this, null));
248                         AddToolset (new Toolset ("3.5",
249                                 ToolLocationHelper.GetPathToDotNetFramework (TargetDotNetFrameworkVersion.Version35), this, null));
250 #if NET_4_0
251                         AddToolset (new Toolset ("4.0",
252                                 ToolLocationHelper.GetPathToDotNetFramework (TargetDotNetFrameworkVersion.Version40), this, null));
253 #endif
254 #if NET_4_5
255                         AddToolset (new Toolset ("12.0",
256                                 ToolLocationHelper.GetMSBuildInstallPath ("12.0"), this, ToolLocationHelper.GetPathToDotNetFramework (TargetDotNetFrameworkVersion.Version40)));
257 #endif
258                 }
259                 
260                 [MonoTODO ("not verified at all")]
261                 public void AddToolset (Toolset toolset)
262                 {
263                         toolsets.Add (toolset);
264                 }
265                 
266                 [MonoTODO ("not verified at all")]
267                 public void RemoveAllToolsets ()
268                 {
269                         toolsets.Clear ();
270                 }
271                 
272                 [MonoTODO ("not verified at all")]
273                 public void RegisterLogger (ILogger logger)
274                 {
275                         loggers.Add (logger);
276                 }
277                 
278                 [MonoTODO ("not verified at all")]
279                 public void RegisterLoggers (IEnumerable<ILogger> loggers)
280                 {
281                         foreach (var logger in loggers)
282                                 this.loggers.Add (logger);
283                 }
284
285                 public void UnloadAllProjects ()
286                 {
287                         throw new NotImplementedException ();
288                 }
289
290                 [MonoTODO ("Not verified at all")]
291                 public void UnloadProject (Project project)
292                 {
293                         this.loaded_projects.Remove (project);
294                 }
295
296                 [MonoTODO ("Not verified at all")]
297                 public void UnloadProject (ProjectRootElement projectRootElement)
298                 {
299                         foreach (var proj in loaded_projects.Where (p => p.Xml == projectRootElement).ToArray ())
300                                 UnloadProject (proj);
301                 }
302
303                 public static Version Version {
304                         get { throw new NotImplementedException (); }
305                 }
306
307                 // Execution part
308
309                 [MonoTODO]
310                 public bool DisableMarkDirty { get; set; }
311
312                 [MonoTODO]
313                 public HostServices HostServices { get; set; }
314
315                 [MonoTODO]
316                 public bool IsBuildEnabled { get; set; }
317                 
318                 internal string BuildStartupDirectory { get; set; }
319                 
320                 internal int MaxNodeCount { get; private set; }
321                 
322                 Stack<string> ongoing_imports = new Stack<string> ();
323                 
324                 internal Stack<string> OngoingImports {
325                         get { return ongoing_imports; }
326                 }
327                 
328                 // common part
329                 internal static IEnumerable<EnvironmentProjectProperty> GetWellKnownProperties (Project project)
330                 {
331                         Func<string,string,EnvironmentProjectProperty> create = (name, value) => new EnvironmentProjectProperty (project, name, value, true);
332                         return GetWellKnownProperties (create);
333                 }
334                 
335                 internal static IEnumerable<ProjectPropertyInstance> GetWellKnownProperties (ProjectInstance project)
336                 {
337                         Func<string,string,ProjectPropertyInstance> create = (name, value) => new ProjectPropertyInstance (name, true, value);
338                         return GetWellKnownProperties (create);
339                 }
340                 
341                 static IEnumerable<T> GetWellKnownProperties<T> (Func<string,string,T> create)
342                 {
343                         var ext = Environment.GetEnvironmentVariable ("MSBuildExtensionsPath") ?? DefaultExtensionsPath;
344                         yield return create ("MSBuildExtensionsPath", ext);
345                         var ext32 = Environment.GetEnvironmentVariable ("MSBuildExtensionsPath32") ?? DefaultExtensionsPath;
346                         yield return create ("MSBuildExtensionsPath32", ext32);
347                         var ext64 = Environment.GetEnvironmentVariable ("MSBuildExtensionsPath64") ?? DefaultExtensionsPath;
348                         yield return create ("MSBuildExtensionsPath64", ext64);
349                 }
350
351                 static string extensions_path;
352                 internal static string DefaultExtensionsPath {
353                         get {
354                                 if (extensions_path == null) {
355                                         // NOTE: code from mcs/tools/gacutil/driver.cs
356                                         PropertyInfo gac = typeof (System.Environment).GetProperty (
357                                                         "GacPath", BindingFlags.Static | BindingFlags.NonPublic);
358
359                                         if (gac != null) {
360                                                 MethodInfo get_gac = gac.GetGetMethod (true);
361                                                 string gac_path = (string) get_gac.Invoke (null, null);
362                                                 extensions_path = Path.GetFullPath (Path.Combine (
363                                                                         gac_path, Path.Combine ("..", "xbuild")));
364                                         }
365                                 }
366                                 return extensions_path;
367                         }
368                 }
369                 
370                 internal IEnumerable<ReservedProjectProperty> GetReservedProperties (Toolset toolset, Project project)
371                 {
372                         Func<string,Func<string>,ReservedProjectProperty> create = (name, value) => new ReservedProjectProperty (project, name, value);
373                         return GetReservedProperties<ReservedProjectProperty> (toolset, project.Xml, create, () => project.FullPath);
374                 }
375                 
376                 internal IEnumerable<ProjectPropertyInstance> GetReservedProperties (Toolset toolset, ProjectInstance project, ProjectRootElement xml)
377                 {
378                         Func<string,Func<string>,ProjectPropertyInstance> create = (name, value) => new ProjectPropertyInstance (name, true, null, value);
379                         return GetReservedProperties<ProjectPropertyInstance> (toolset, xml, create, () => project.FullPath);
380                 }
381                 
382                 // seealso http://msdn.microsoft.com/en-us/library/ms164309.aspx
383                 IEnumerable<T> GetReservedProperties<T> (Toolset toolset, ProjectRootElement project, Func<string,Func<string>,T> create, Func<string> projectFullPath)
384                 {
385                         yield return create ("MSBuildBinPath", () => toolset.ToolsPath);
386                         // FIXME: add MSBuildLastTaskResult
387                         // FIXME: add MSBuildNodeCount
388                         // FIXME: add MSBuildProgramFiles32
389                         yield return create ("MSBuildProjectDefaultTargets", () => project.DefaultTargets);
390                         yield return create ("MSBuildProjectDirectory", () => project.DirectoryPath + Path.DirectorySeparatorChar);
391                         yield return create ("MSBuildProjectDirectoryNoRoot", () => project.DirectoryPath.Substring (Path.GetPathRoot (project.DirectoryPath).Length));
392                         yield return create ("MSBuildProjectExtension", () => Path.GetExtension (project.FullPath));
393                         yield return create ("MSBuildProjectFile", () => Path.GetFileName (project.FullPath));
394                         yield return create ("MSBuildProjectFullPath", () => project.FullPath);
395                         yield return create ("MSBuildProjectName", () => Path.GetFileNameWithoutExtension (project.FullPath));
396                         yield return create ("MSBuildStartupDirectory", () => BuildStartupDirectory);
397                         yield return create ("MSBuildThisFile", () => Path.GetFileName (GetEvaluationTimeThisFile (projectFullPath)));
398                         yield return create ("MSBuildThisFileFullPath", () => GetEvaluationTimeThisFile (projectFullPath));
399                         yield return create ("MSBuildThisFileName", () => Path.GetFileNameWithoutExtension (GetEvaluationTimeThisFile (projectFullPath)));
400                         yield return create ("MSBuildThisFileExtension", () => Path.GetExtension (GetEvaluationTimeThisFile (projectFullPath)));
401
402                         yield return create ("MSBuildThisFileDirectory", () => Path.GetDirectoryName (GetEvaluationTimeThisFileDirectory (projectFullPath)));
403                         yield return create ("MSBuildThisFileDirectoryNoRoot", () => {
404                                 string dir = GetEvaluationTimeThisFileDirectory (projectFullPath) + Path.DirectorySeparatorChar;
405                                 return dir.Substring (Path.GetPathRoot (dir).Length);
406                                 });
407                         yield return create ("MSBuildToolsPath", () => toolset.ToolsPath);
408                         yield return create ("MSBuildToolsVersion", () => toolset.ToolsVersion);
409                 }
410                 
411                 // These are required for reserved property, represents dynamically changing property values.
412                 // This should resolve to either the project file path or that of the imported file.
413                 internal string GetEvaluationTimeThisFileDirectory (Func<string> nonImportingTimeFullPath)
414                 {
415                         var file = GetEvaluationTimeThisFile (nonImportingTimeFullPath);
416                         var dir = Path.IsPathRooted (file) ? Path.GetDirectoryName (file) : Directory.GetCurrentDirectory ();
417                         return dir + Path.DirectorySeparatorChar;
418                 }
419
420                 internal string GetEvaluationTimeThisFile (Func<string> nonImportingTimeFullPath)
421                 {
422                         return OngoingImports.Count > 0 ? OngoingImports.Peek () : (nonImportingTimeFullPath () ?? string.Empty);
423                 }
424                 
425                 static readonly char [] item_target_sep = {';'};
426                 
427                 internal static IEnumerable<T> GetAllItems<T> (Func<string,string> expandString, string include, string exclude, Func<string,T> creator, Func<string,ITaskItem> taskItemCreator, string directory, Action<T,string> assignRecurse, Func<ITaskItem,bool> isDuplicate)
428                 {
429                         var includes = expandString (include).Split (item_target_sep, StringSplitOptions.RemoveEmptyEntries);
430                         var excludes = expandString (exclude).Split (item_target_sep, StringSplitOptions.RemoveEmptyEntries);
431                         
432                         if (includes.Length == 0)
433                                 yield break;
434                         if (includes.Length == 1 && includes [0].IndexOf ('*') < 0 && excludes.Length == 0) {
435                                 // for most case - shortcut.
436                                 var item = creator (includes [0]);
437                                 yield return item;
438                         } else {
439                                 var ds = new Microsoft.Build.BuildEngine.DirectoryScanner () {
440                                         BaseDirectory = new DirectoryInfo (directory),
441                                         Includes = includes.Select (i => taskItemCreator (i)).ToArray (),
442                                         Excludes = excludes.Select (e => taskItemCreator (e)).ToArray (),
443                                 };
444                                 ds.Scan ();
445                                 foreach (var taskItem in ds.MatchedItems) {
446                                         if (isDuplicate (taskItem))
447                                                 continue; // skip duplicate
448                                         var item = creator (taskItem.ItemSpec);
449                                         string recurse = taskItem.GetMetadata ("RecursiveDir");
450                                         assignRecurse (item, recurse);
451                                         yield return item;
452                                 }
453                         }
454                 }
455                 
456                 static readonly char [] path_sep = {Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar};
457                 
458                 internal static string GetWellKnownMetadata (string name, string file, Func<string,string> getFullPath, string recursiveDir)
459                 {
460                         switch (name.ToLower (CultureInfo.InvariantCulture)) {
461                         case "fullpath":
462                                 return getFullPath (file);
463                         case "rootdir":
464                                 return Path.GetPathRoot (getFullPath (file));
465                         case "filename":
466                                 return Path.GetFileNameWithoutExtension (file);
467                         case "extension":
468                                 return Path.GetExtension (file);
469                         case "relativedir":
470                                         var idx = file.LastIndexOfAny (path_sep);
471                                         return idx < 0 ? string.Empty : file.Substring (0, idx + 1);
472                         case "directory":
473                                         var fp = getFullPath (file);
474                                         return Path.GetDirectoryName (fp).Substring (Path.GetPathRoot (fp).Length);
475                         case "recursivedir":
476                                 return recursiveDir;
477                         case "identity":
478                                 return file;
479                         case "modifiedtime":
480                                 return new FileInfo (getFullPath (file)).LastWriteTime.ToString ("yyyy-MM-dd HH:mm:ss.fffffff");
481                         case "createdtime":
482                                 return new FileInfo (getFullPath (file)).CreationTime.ToString ("yyyy-MM-dd HH:mm:ss.fffffff");
483                         case "accessedtime":
484                                 return new FileInfo (getFullPath (file)).LastAccessTime.ToString ("yyyy-MM-dd HH:mm:ss.fffffff");
485                         }
486                         return null;
487                 }
488         }
489 }