2 // ProjectCollection.cs
5 // Leszek Ciesielski (skolima@gmail.com)
6 // Rolf Bjarne Kvinge (rolf@xamarin.com)
7 // Atsushi Enomoto (atsushi@xamarin.com)
9 // (C) 2011 Leszek Ciesielski
10 // Copyright (C) 2011,2013 Xamarin Inc.
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 Microsoft.Build.Construction;
33 using Microsoft.Build.Execution;
34 using Microsoft.Build.Framework;
35 using Microsoft.Build.Logging;
36 using Microsoft.Build.Utilities;
38 using System.Collections.Generic;
39 using System.Collections.ObjectModel;
43 using System.Reflection;
44 using System.Globalization;
46 namespace Microsoft.Build.Evaluation
48 public class ProjectCollection : IDisposable
50 public delegate void ProjectAddedEventHandler (object target, ProjectAddedToProjectCollectionEventArgs args);
52 public class ProjectAddedToProjectCollectionEventArgs : EventArgs
54 public ProjectAddedToProjectCollectionEventArgs (ProjectRootElement project)
57 throw new ArgumentNullException ("project");
58 ProjectRootElement = project;
61 public ProjectRootElement ProjectRootElement { get; private set; }
66 static readonly ProjectCollection global_project_collection;
68 static ProjectCollection ()
71 global_project_collection = new ProjectCollection (new ReadOnlyDictionary<string, string> (new Dictionary<string, string> ()));
73 global_project_collection = new ProjectCollection (new Dictionary<string, string> ());
77 public static string Escape (string unescapedString)
79 return Mono.XBuild.Utilities.MSBuildUtils.Escape (unescapedString);
82 public static string Unescape (string escapedString)
84 return Mono.XBuild.Utilities.MSBuildUtils.Unescape (escapedString);
87 public static ProjectCollection GlobalProjectCollection {
88 get { return global_project_collection; }
91 // semantic model part
93 public ProjectCollection ()
98 public ProjectCollection (IDictionary<string, string> globalProperties)
99 : this (globalProperties, null, ToolsetDefinitionLocations.Registry | ToolsetDefinitionLocations.ConfigurationFile)
103 public ProjectCollection (ToolsetDefinitionLocations toolsetDefinitionLocations)
104 : this (null, null, toolsetDefinitionLocations)
108 public ProjectCollection (IDictionary<string, string> globalProperties, IEnumerable<ILogger> loggers,
109 ToolsetDefinitionLocations toolsetDefinitionLocations)
110 : this (globalProperties, loggers, null, toolsetDefinitionLocations, 1, false)
114 public ProjectCollection (IDictionary<string, string> globalProperties,
115 IEnumerable<ILogger> loggers, IEnumerable<ForwardingLoggerRecord> remoteLoggers,
116 ToolsetDefinitionLocations toolsetDefinitionLocations,
117 int maxNodeCount, bool onlyLogCriticalEvents)
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;
125 LoadDefaultToolsets ();
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;
137 public void AddProject (Project project)
139 this.loaded_projects.Add (project);
140 if (ProjectAdded != null)
141 ProjectAdded (this, new ProjectAddedToProjectCollectionEventArgs (project.Xml));
145 get { return loaded_projects.Count; }
148 public string DefaultToolsVersion {
149 get { return Toolsets.Any () ? Toolsets.First ().ToolsVersion : null; }
152 public void Dispose ()
155 GC.SuppressFinalize (this);
158 protected virtual void Dispose (bool disposing)
164 public ICollection<Project> GetLoadedProjects (string fullPath)
166 return LoadedProjects.Where (p => p.FullPath != null && Path.GetFullPath (p.FullPath) == Path.GetFullPath (fullPath)).ToList ();
169 readonly IDictionary<string, string> global_properties;
171 public IDictionary<string, string> GlobalProperties {
172 get { return global_properties; }
175 readonly List<Project> loaded_projects = new List<Project> ();
177 public Project LoadProject (string fileName)
179 return LoadProject (fileName, DefaultToolsVersion);
182 public Project LoadProject (string fileName, string toolsVersion)
184 return LoadProject (fileName, toolsVersion);
187 public Project LoadProject (string fileName, IDictionary<string,string> globalProperties, string toolsVersion)
189 return new Project (fileName, globalProperties, toolsVersion);
192 // These methods somehow don't add the project to ProjectCollection...
193 public Project LoadProject (XmlReader xmlReader)
195 return LoadProject (xmlReader, DefaultToolsVersion);
198 public Project LoadProject (XmlReader xmlReader, string toolsVersion)
200 return LoadProject (xmlReader, null, toolsVersion);
203 public Project LoadProject (XmlReader xmlReader, IDictionary<string,string> globalProperties, string toolsVersion)
205 return new Project (xmlReader, globalProperties, toolsVersion);
208 public ICollection<Project> LoadedProjects {
209 get { return loaded_projects; }
212 readonly List<ILogger> loggers = new List<ILogger> ();
214 public ICollection<ILogger> Loggers {
215 get { return loggers; }
219 public bool OnlyLogCriticalEvents { get; set; }
222 public bool SkipEvaluation { get; set; }
224 readonly ToolsetDefinitionLocations toolset_locations;
225 public ToolsetDefinitionLocations ToolsetLocations {
226 get { return toolset_locations; }
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 (); }
236 public Toolset GetToolset (string toolsVersion)
238 return Toolsets.FirstOrDefault (t => t.ToolsVersion == toolsVersion);
241 //FIXME: should also support config file, depending on ToolsetLocations
242 void LoadDefaultToolsets ()
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));
251 AddToolset (new Toolset ("4.0",
252 ToolLocationHelper.GetPathToDotNetFramework (TargetDotNetFrameworkVersion.Version40), this, null));
255 AddToolset (new Toolset ("12.0",
256 ToolLocationHelper.GetMSBuildInstallPath ("12.0"), this, ToolLocationHelper.GetPathToDotNetFramework (TargetDotNetFrameworkVersion.Version40)));
260 [MonoTODO ("not verified at all")]
261 public void AddToolset (Toolset toolset)
263 toolsets.Add (toolset);
266 [MonoTODO ("not verified at all")]
267 public void RemoveAllToolsets ()
272 [MonoTODO ("not verified at all")]
273 public void RegisterLogger (ILogger logger)
275 loggers.Add (logger);
278 [MonoTODO ("not verified at all")]
279 public void RegisterLoggers (IEnumerable<ILogger> loggers)
281 foreach (var logger in loggers)
282 this.loggers.Add (logger);
285 public void UnloadAllProjects ()
287 throw new NotImplementedException ();
290 [MonoTODO ("Not verified at all")]
291 public void UnloadProject (Project project)
293 this.loaded_projects.Remove (project);
296 [MonoTODO ("Not verified at all")]
297 public void UnloadProject (ProjectRootElement projectRootElement)
299 foreach (var proj in loaded_projects.Where (p => p.Xml == projectRootElement).ToArray ())
300 UnloadProject (proj);
303 public static Version Version {
304 get { throw new NotImplementedException (); }
310 public bool DisableMarkDirty { get; set; }
313 public HostServices HostServices { get; set; }
316 public bool IsBuildEnabled { get; set; }
318 internal string BuildStartupDirectory { get; set; }
320 internal int MaxNodeCount { get; private set; }
322 Stack<string> ongoing_imports = new Stack<string> ();
324 internal Stack<string> OngoingImports {
325 get { return ongoing_imports; }
329 internal static IEnumerable<EnvironmentProjectProperty> GetWellKnownProperties (Project project)
331 Func<string,string,EnvironmentProjectProperty> create = (name, value) => new EnvironmentProjectProperty (project, name, value, true);
332 return GetWellKnownProperties (create);
335 internal static IEnumerable<ProjectPropertyInstance> GetWellKnownProperties (ProjectInstance project)
337 Func<string,string,ProjectPropertyInstance> create = (name, value) => new ProjectPropertyInstance (name, true, value);
338 return GetWellKnownProperties (create);
341 static IEnumerable<T> GetWellKnownProperties<T> (Func<string,string,T> create)
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);
351 static string extensions_path;
352 internal static string DefaultExtensionsPath {
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);
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")));
366 return extensions_path;
370 internal IEnumerable<ReservedProjectProperty> GetReservedProperties (Toolset toolset, Project project)
372 Func<string,Func<string>,ReservedProjectProperty> create = (name, value) => new ReservedProjectProperty (project, name, value);
373 return GetReservedProperties<ReservedProjectProperty> (toolset, project.Xml, create, () => project.FullPath);
376 internal IEnumerable<ProjectPropertyInstance> GetReservedProperties (Toolset toolset, ProjectInstance project, ProjectRootElement xml)
378 Func<string,Func<string>,ProjectPropertyInstance> create = (name, value) => new ProjectPropertyInstance (name, true, null, value);
379 return GetReservedProperties<ProjectPropertyInstance> (toolset, xml, create, () => project.FullPath);
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)
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)));
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);
407 yield return create ("MSBuildToolsPath", () => toolset.ToolsPath);
408 yield return create ("MSBuildToolsVersion", () => toolset.ToolsVersion);
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)
415 var file = GetEvaluationTimeThisFile (nonImportingTimeFullPath);
416 var dir = Path.IsPathRooted (file) ? Path.GetDirectoryName (file) : Directory.GetCurrentDirectory ();
417 return dir + Path.DirectorySeparatorChar;
420 internal string GetEvaluationTimeThisFile (Func<string> nonImportingTimeFullPath)
422 return OngoingImports.Count > 0 ? OngoingImports.Peek () : (nonImportingTimeFullPath () ?? string.Empty);
425 static readonly char [] item_target_sep = {';'};
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)
429 var includes = expandString (include).Split (item_target_sep, StringSplitOptions.RemoveEmptyEntries);
430 var excludes = expandString (exclude).Split (item_target_sep, StringSplitOptions.RemoveEmptyEntries);
432 if (includes.Length == 0)
434 if (includes.Length == 1 && includes [0].IndexOf ('*') < 0 && excludes.Length == 0) {
435 // for most case - shortcut.
436 var item = creator (includes [0]);
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 (),
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);
456 static readonly char [] path_sep = {Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar};
458 internal static string GetWellKnownMetadata (string name, string file, Func<string,string> getFullPath, string recursiveDir)
460 switch (name.ToLower (CultureInfo.InvariantCulture)) {
462 return getFullPath (file);
464 return Path.GetPathRoot (getFullPath (file));
466 return Path.GetFileNameWithoutExtension (file);
468 return Path.GetExtension (file);
470 var idx = file.LastIndexOfAny (path_sep);
471 return idx < 0 ? string.Empty : file.Substring (0, idx + 1);
473 var fp = getFullPath (file);
474 return Path.GetDirectoryName (fp).Substring (Path.GetPathRoot (fp).Length);
480 return new FileInfo (getFullPath (file)).LastWriteTime.ToString ("yyyy-MM-dd HH:mm:ss.fffffff");
482 return new FileInfo (getFullPath (file)).CreationTime.ToString ("yyyy-MM-dd HH:mm:ss.fffffff");
484 return new FileInfo (getFullPath (file)).LastAccessTime.ToString ("yyyy-MM-dd HH:mm:ss.fffffff");