5 // Rolf Bjarne Kvinge (rolf@xamarin.com)
6 // Atsushi Enomoto (atsushi@xamarin.com)
8 // Copyright (C) 2011,2013 Xamarin Inc.
10 // Permission is hereby granted, free of charge, to any person obtaining
11 // a copy of this software and associated documentation files (the
12 // "Software"), to deal in the Software without restriction, including
13 // without limitation the rights to use, copy, modify, merge, publish,
14 // distribute, sublicense, and/or sell copies of the Software, and to
15 // permit persons to whom the Software is furnished to do so, subject to
16 // the following conditions:
18 // The above copyright notice and this permission notice shall be
19 // included in all copies or substantial portions of the Software.
21 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
22 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
23 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
24 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
25 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
26 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
27 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
31 using System.Collections;
32 using System.Collections.Generic;
35 using Microsoft.Build.Construction;
36 using Microsoft.Build.Evaluation;
37 using Microsoft.Build.Framework;
38 using Microsoft.Build.Internal.Expressions;
39 using Microsoft.Build.Logging;
42 // It is not always consistent to reuse Project and its evaluation stuff mostly because
43 // both BuildParameters.ctor() and Project.ctor() takes arbitrary ProjectCollection, which are not very likely eqivalent
44 // (as BuildParameters.ctor(), unlike Project.ctor(...), is known to create a new ProjectCollection instance).
46 // However, that inconsistency could happen even if you only use ProjectInstance and BuildParameters.
47 // They both have constructors that take ProjectCollection and there is no guarantee that the arguments are the same.
48 // BuildManager.Build() does not fail because of inconsistent ProjectCollection instance on .NET.
50 // Anyhow, I'm not going to instantiate Project within ProjectInstance code for another reason:
51 // ProjectCollection.GetLoadedProject() does not return any Project instnace for corresponding ProjectInstance
52 // (or I should say, ProjectRootElement for both).
53 using Microsoft.Build.Internal;
55 using Microsoft.Build.Exceptions;
59 namespace Microsoft.Build.Execution
61 public class ProjectInstance
65 public ProjectInstance (ProjectRootElement xml)
66 : this (xml, null, null, ProjectCollection.GlobalProjectCollection)
70 public ProjectInstance (string projectFile)
71 : this (projectFile, null, null, ProjectCollection.GlobalProjectCollection)
75 public ProjectInstance (string projectFile, IDictionary<string, string> globalProperties,
77 : this (projectFile, globalProperties, toolsVersion, ProjectCollection.GlobalProjectCollection)
81 public ProjectInstance (ProjectRootElement xml, IDictionary<string, string> globalProperties,
82 string toolsVersion, ProjectCollection projectCollection)
84 projects = projectCollection;
85 global_properties = globalProperties ?? new Dictionary<string, string> ();
86 tools_version = !string.IsNullOrEmpty (toolsVersion) ? toolsVersion :
87 !string.IsNullOrEmpty (xml.ToolsVersion) ? xml.ToolsVersion :
88 projects.DefaultToolsVersion;
89 InitializeProperties (xml, null);
92 public ProjectInstance (string projectFile, IDictionary<string, string> globalProperties,
93 string toolsVersion, ProjectCollection projectCollection)
94 : this (ProjectRootElement.Create (projectFile), globalProperties, toolsVersion, projectCollection)
98 ProjectCollection projects;
99 IDictionary<string, string> global_properties;
101 string full_path, directory;
103 ElementLocation location;
106 Dictionary<string, ProjectItemDefinitionInstance> item_definitions;
107 List<ResolvedImport> raw_imports; // maybe we don't need this...
108 List<ProjectItemInstance> all_evaluated_items;
109 List<ProjectItemInstance> raw_items;
110 List<ProjectPropertyInstance> properties;
111 Dictionary<string, ProjectTargetInstance> targets;
112 string tools_version;
114 List<string> GetDefaultTargets (ProjectRootElement xml)
116 var ret = xml.DefaultTargets.Split (item_target_sep, StringSplitOptions.RemoveEmptyEntries).Select (s => s.Trim ()).ToList ();
117 if (ret.Count == 0 && xml.Targets.Any ())
118 ret.Add (xml.Targets.First ().Name);
122 void InitializeProperties (ProjectRootElement xml, ProjectInstance parent)
125 location = xml.Location;
127 full_path = xml.FullPath;
128 directory = string.IsNullOrWhiteSpace (xml.DirectoryPath) ? System.IO.Directory.GetCurrentDirectory () : xml.DirectoryPath;
129 DefaultTargets = GetDefaultTargets (xml);
130 InitialTargets = xml.InitialTargets.Split (item_target_sep, StringSplitOptions.RemoveEmptyEntries).Select (s => s.Trim ()).ToList ();
132 raw_imports = new List<ResolvedImport> ();
133 item_definitions = new Dictionary<string, ProjectItemDefinitionInstance> ();
134 targets = new Dictionary<string, ProjectTargetInstance> ();
135 raw_items = new List<ProjectItemInstance> ();
137 // FIXME: this is likely hack. Test ImportedProject.Properties to see what exactly should happen.
138 if (parent != null) {
139 properties = parent.properties;
141 properties = new List<ProjectPropertyInstance> ();
143 foreach (DictionaryEntry p in Environment.GetEnvironmentVariables ())
144 // FIXME: this is kind of workaround for unavoidable issue that PLATFORM=* is actually given
145 // on some platforms and that prevents setting default "PLATFORM=AnyCPU" property.
146 if (!string.Equals ("PLATFORM", (string) p.Key, StringComparison.OrdinalIgnoreCase))
147 this.properties.Add (new ProjectPropertyInstance ((string) p.Key, false, (string) p.Value));
148 foreach (var p in global_properties)
149 this.properties.Add (new ProjectPropertyInstance (p.Key, false, p.Value));
150 var tools = projects.GetToolset (tools_version) ?? projects.GetToolset (projects.DefaultToolsVersion);
151 foreach (var p in projects.GetReservedProperties (tools, this, xml))
152 this.properties.Add (p);
153 foreach (var p in ProjectCollection.GetWellKnownProperties (this))
154 this.properties.Add (p);
157 ProcessXml (parent, xml);
160 static readonly char [] item_target_sep = {';'};
162 void ProcessXml (ProjectInstance parent, ProjectRootElement xml)
164 TaskDatabase = new BuildTaskDatabase (this, xml);
166 // this needs to be initialized here (regardless of that items won't be evaluated at property evaluation;
167 // Conditions could incorrectly reference items and lack of this list causes NRE.
168 all_evaluated_items = new List<ProjectItemInstance> ();
170 // property evaluation happens couple of times.
171 // At first step, all non-imported properties are evaluated TOO, WHILE those properties are being evaluated.
172 // This means, Include and IncludeGroup elements with Condition attribute MAY contain references to
173 // properties and they will be expanded.
174 var elements = EvaluatePropertiesAndImports (xml.Children).ToArray (); // ToArray(): to not lazily evaluate elements.
176 // next, evaluate items
177 EvaluateItems (xml, elements);
179 // finally, evaluate targets and tasks
180 EvaluateTasks (elements);
183 IEnumerable<ProjectElement> EvaluatePropertiesAndImports (IEnumerable<ProjectElement> elements)
185 // First step: evaluate Properties
186 foreach (var child in elements) {
188 var pge = child as ProjectPropertyGroupElement;
189 if (pge != null && EvaluateCondition (pge.Condition))
190 foreach (var p in pge.Properties)
191 // do not allow overwriting reserved or well-known properties by user
192 if (!this.properties.Any (_ => (_.IsImmutable) && _.Name.Equals (p.Name, StringComparison.InvariantCultureIgnoreCase)))
193 if (EvaluateCondition (p.Condition))
194 this.properties.Add (new ProjectPropertyInstance (p.Name, false, ExpandString (p.Value)));
196 var ige = child as ProjectImportGroupElement;
197 if (ige != null && EvaluateCondition (ige.Condition)) {
198 foreach (var incc in ige.Imports) {
199 foreach (var e in Import (incc))
203 var inc = child as ProjectImportElement;
204 if (inc != null && EvaluateCondition (inc.Condition))
205 foreach (var e in Import (inc))
210 internal IEnumerable<T> GetAllItems<T> (string include, string exclude, Func<string,T> creator, Func<string,ITaskItem> taskItemCreator, Func<string,bool> itemTypeCheck, Action<T,string> assignRecurse)
212 return ProjectCollection.GetAllItems<T> (ExpandString, include, exclude, creator, taskItemCreator, Directory, assignRecurse,
213 t => all_evaluated_items.Any (i => i.EvaluatedInclude == t.ItemSpec && itemTypeCheck (i.ItemType)));
216 void EvaluateItems (ProjectRootElement xml, IEnumerable<ProjectElement> elements)
218 foreach (var child in elements) {
219 var ige = child as ProjectItemGroupElement;
221 foreach (var p in ige.Items) {
222 if (!EvaluateCondition (ige.Condition) || !EvaluateCondition (p.Condition))
224 Func<string,ProjectItemInstance> creator = s => new ProjectItemInstance (this, p.ItemType, p.Metadata.Select (m => new KeyValuePair<string,string> (m.Name, m.Value)).ToList (), s);
225 foreach (var item in GetAllItems (p.Include, p.Exclude, creator, s => new ProjectTaskItem (p, s), it => string.Equals (it, p.ItemType, StringComparison.OrdinalIgnoreCase), (t, s) => t.RecursiveDir = s)) {
226 raw_items.Add (item);
227 all_evaluated_items.Add (item);
231 var def = child as ProjectItemDefinitionGroupElement;
233 foreach (var p in def.ItemDefinitions) {
234 if (EvaluateCondition (p.Condition)) {
235 ProjectItemDefinitionInstance existing;
236 if (!item_definitions.TryGetValue (p.ItemType, out existing))
237 item_definitions.Add (p.ItemType, (existing = new ProjectItemDefinitionInstance (p)));
238 existing.AddItems (p);
243 all_evaluated_items.Sort ((p1, p2) => string.Compare (p1.ItemType, p2.ItemType, StringComparison.OrdinalIgnoreCase));
246 void EvaluateTasks (IEnumerable<ProjectElement> elements)
248 foreach (var child in elements) {
249 var te = child as ProjectTargetElement;
251 this.targets.Add (te.Name, new ProjectTargetInstance (te));
255 IEnumerable<ProjectElement> Import (ProjectImportElement import)
257 string dir = projects.GetEvaluationTimeThisFileDirectory (() => FullPath);
258 string path = WindowsCompatibilityExtensions.NormalizeFilePath (ExpandString (import.Project));
259 path = Path.IsPathRooted (path) ? path : dir != null ? Path.Combine (dir, path) : Path.GetFullPath (path);
260 if (projects.OngoingImports.Contains (path))
261 throw new InvalidProjectFileException (import.Location, null, string.Format ("Circular imports was detected: {0} is already on \"importing\" stack", path));
262 projects.OngoingImports.Push (path);
264 using (var reader = XmlReader.Create (path)) {
265 var root = ProjectRootElement.Create (reader, projects);
266 if (DefaultTargets.Count == 0)
267 DefaultTargets.AddRange (GetDefaultTargets (root));
268 raw_imports.Add (new ResolvedImport (import, root, true));
269 return this.EvaluatePropertiesAndImports (root.Children).ToArray ();
272 projects.OngoingImports.Pop ();
276 internal IEnumerable<ProjectItemInstance> AllEvaluatedItems {
277 get { return all_evaluated_items; }
280 public List<string> DefaultTargets { get; private set; }
282 public string Directory {
283 get { return directory; }
286 public string FullPath {
287 get { return full_path; }
290 public IDictionary<string, string> GlobalProperties {
291 get { return global_properties; }
294 public List<string> InitialTargets { get; private set; }
297 public bool IsImmutable {
298 get { throw new NotImplementedException (); }
302 public IDictionary<string, ProjectItemDefinitionInstance> ItemDefinitions {
303 get { return item_definitions; }
306 public ICollection<ProjectItemInstance> Items {
307 get { return all_evaluated_items; }
310 public ICollection<string> ItemTypes {
311 get { return all_evaluated_items.Select (i => i.ItemType).Distinct ().ToArray (); }
315 public ElementLocation ProjectFileLocation {
316 get { return location; }
320 public ICollection<ProjectPropertyInstance> Properties {
321 get { return properties; }
329 IDictionary<string, ProjectTargetInstance> Targets {
330 get { return targets; }
333 public string ToolsVersion {
334 get { return tools_version; }
337 public ProjectItemInstance AddItem (string itemType, string evaluatedInclude)
339 return AddItem (itemType, evaluatedInclude, new KeyValuePair<string, string> [0]);
342 public ProjectItemInstance AddItem (string itemType, string evaluatedInclude, IEnumerable<KeyValuePair<string, string>> metadata)
344 var item = new ProjectItemInstance (this, itemType, metadata, evaluatedInclude);
345 raw_items.Add (item);
346 all_evaluated_items.Add (item);
352 return Build (new ILogger [0]);
355 public bool Build (IEnumerable<ILogger> loggers)
357 return Build (loggers, new ForwardingLoggerRecord [0]);
360 public bool Build (IEnumerable<ILogger> loggers, IEnumerable<ForwardingLoggerRecord> remoteLoggers)
362 return Build (DefaultTargets.ToArray (), loggers, remoteLoggers);
365 public bool Build (string target, IEnumerable<ILogger> loggers)
367 return Build (target, loggers, new ForwardingLoggerRecord [0]);
370 public bool Build (string [] targets, IEnumerable<ILogger> loggers)
372 return Build (targets, loggers, new ForwardingLoggerRecord [0]);
375 public bool Build (string target, IEnumerable<ILogger> loggers, IEnumerable<ForwardingLoggerRecord> remoteLoggers)
377 return Build (new string [] {target}, loggers, remoteLoggers);
380 public bool Build (string [] targets, IEnumerable<ILogger> loggers, IEnumerable<ForwardingLoggerRecord> remoteLoggers)
382 IDictionary<string, TargetResult> outputs;
383 return Build (targets, loggers, remoteLoggers, out outputs);
386 public bool Build (string[] targets, IEnumerable<ILogger> loggers, out IDictionary<string, TargetResult> targetOutputs)
388 return Build (targets, loggers, new ForwardingLoggerRecord [0], out targetOutputs);
391 public bool Build (string[] targets, IEnumerable<ILogger> loggers, IEnumerable<ForwardingLoggerRecord> remoteLoggers, out IDictionary<string, TargetResult> targetOutputs)
393 var manager = new BuildManager ();
394 var parameters = new BuildParameters (projects) {
395 ForwardingLoggers = remoteLoggers,
398 var requestData = new BuildRequestData (this, targets);
399 var result = manager.Build (parameters, requestData);
400 targetOutputs = result.ResultsByTarget;
401 return result.OverallResult == BuildResultCode.Success;
404 public ProjectInstance DeepCopy ()
406 return DeepCopy (false);
409 public ProjectInstance DeepCopy (bool isImmutable)
411 throw new NotImplementedException ();
414 public bool EvaluateCondition (string condition)
416 return string.IsNullOrWhiteSpace (condition) || new ExpressionEvaluator (this, null).EvaluateAsBoolean (condition);
419 public string ExpandString (string unexpandedValue)
421 return ExpandString (unexpandedValue, null);
424 string ExpandString (string unexpandedValue, string replacementForMissingStuff)
426 return new ExpressionEvaluator (this, replacementForMissingStuff).Evaluate (unexpandedValue);
429 public ICollection<ProjectItemInstance> GetItems (string itemType)
431 return new CollectionFromEnumerable<ProjectItemInstance> (Items.Where (p => p.ItemType.Equals (itemType, StringComparison.OrdinalIgnoreCase)));
434 public IEnumerable<ProjectItemInstance> GetItemsByItemTypeAndEvaluatedInclude (string itemType, string evaluatedInclude)
436 throw new NotImplementedException ();
439 public ProjectPropertyInstance GetProperty (string name)
441 return properties.FirstOrDefault (p => p.Name.Equals (name, StringComparison.OrdinalIgnoreCase));
444 public string GetPropertyValue (string name)
446 var prop = GetProperty (name);
447 return prop != null ? prop.EvaluatedValue : string.Empty;
450 public bool RemoveItem (ProjectItemInstance item)
452 // yeah, this raw_items should vanish...
453 raw_items.Remove (item);
454 return all_evaluated_items.Remove (item);
457 public bool RemoveProperty (string name)
459 var removed = properties.FirstOrDefault (p => p.Name.Equals (name, StringComparison.OrdinalIgnoreCase));
462 properties.Remove (removed);
466 public ProjectPropertyInstance SetProperty (string name, string evaluatedValue)
468 var p = new ProjectPropertyInstance (name, false, evaluatedValue);
473 public ProjectRootElement ToProjectRootElement ()
475 throw new NotImplementedException ();
479 public void UpdateStateFrom (ProjectInstance projectState)
481 throw new NotImplementedException ();
487 public static string GetEvaluatedItemIncludeEscaped (ProjectItemDefinitionInstance item)
489 // ?? ItemDefinition does not have Include attribute. What's the point here?
490 throw new NotImplementedException ();
493 public static string GetEvaluatedItemIncludeEscaped (ProjectItemInstance item)
495 return ProjectCollection.Escape (item.EvaluatedInclude);
498 public static string GetMetadataValueEscaped (ProjectMetadataInstance metadatum)
500 return ProjectCollection.Escape (metadatum.EvaluatedValue);
503 public static string GetMetadataValueEscaped (ProjectItemDefinitionInstance item, string name)
505 var md = item.Metadata.FirstOrDefault (m => m.Name.Equals (name, StringComparison.OrdinalIgnoreCase));
506 return md != null ? ProjectCollection.Escape (md.EvaluatedValue) : null;
509 public static string GetMetadataValueEscaped (ProjectItemInstance item, string name)
511 var md = item.Metadata.FirstOrDefault (m => m.Name.Equals (name, StringComparison.OrdinalIgnoreCase));
512 return md != null ? ProjectCollection.Escape (md.EvaluatedValue) : null;
515 public static string GetPropertyValueEscaped (ProjectPropertyInstance property)
518 //return ProjectCollection.Escape (property.EvaluatedValue);
519 return property.EvaluatedValue;
522 internal BuildTaskDatabase TaskDatabase { get; private set; }
524 internal string GetFullPath (string pathRelativeToProject)
526 if (Path.IsPathRooted (pathRelativeToProject))
527 return pathRelativeToProject;
528 return Path.GetFullPath (Path.Combine (Directory, pathRelativeToProject));