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 = GetDefaultTargets (xml, true, true);
117 return ret.Any () ? ret : GetDefaultTargets (xml, false, true);
120 List<string> GetDefaultTargets (ProjectRootElement xml, bool fromAttribute, bool checkImports)
123 var ret = xml.DefaultTargets.Split (item_target_sep, StringSplitOptions.RemoveEmptyEntries).Select (s => s.Trim ()).ToList ();
124 if (checkImports && ret.Count == 0) {
125 foreach (var imp in this.raw_imports) {
126 ret = GetDefaultTargets (imp.ImportedProject, true, false);
133 if (xml.Targets.Any ())
134 return new String [] { xml.Targets.First ().Name }.ToList ();
136 foreach (var imp in this.raw_imports) {
137 var ret = GetDefaultTargets (imp.ImportedProject, false, false);
142 return new List<string> ();
146 void InitializeProperties (ProjectRootElement xml, ProjectInstance parent)
149 location = xml.Location;
151 full_path = xml.FullPath;
152 directory = string.IsNullOrWhiteSpace (xml.DirectoryPath) ? System.IO.Directory.GetCurrentDirectory () : xml.DirectoryPath;
153 InitialTargets = xml.InitialTargets.Split (item_target_sep, StringSplitOptions.RemoveEmptyEntries).Select (s => s.Trim ()).ToList ();
155 raw_imports = new List<ResolvedImport> ();
156 item_definitions = new Dictionary<string, ProjectItemDefinitionInstance> ();
157 targets = new Dictionary<string, ProjectTargetInstance> ();
158 raw_items = new List<ProjectItemInstance> ();
160 // FIXME: this is likely hack. Test ImportedProject.Properties to see what exactly should happen.
161 if (parent != null) {
162 properties = parent.properties;
164 properties = new List<ProjectPropertyInstance> ();
166 foreach (DictionaryEntry p in Environment.GetEnvironmentVariables ())
167 // FIXME: this is kind of workaround for unavoidable issue that PLATFORM=* is actually given
168 // on some platforms and that prevents setting default "PLATFORM=AnyCPU" property.
169 if (!string.Equals ("PLATFORM", (string) p.Key, StringComparison.OrdinalIgnoreCase))
170 this.properties.Add (new ProjectPropertyInstance ((string) p.Key, false, (string) p.Value));
171 foreach (var p in global_properties)
172 this.properties.Add (new ProjectPropertyInstance (p.Key, false, p.Value));
173 var tools = projects.GetToolset (tools_version) ?? projects.GetToolset (projects.DefaultToolsVersion);
174 foreach (var p in projects.GetReservedProperties (tools, this, xml))
175 this.properties.Add (p);
176 foreach (var p in ProjectCollection.GetWellKnownProperties (this))
177 this.properties.Add (p);
180 ProcessXml (parent, xml);
182 DefaultTargets = GetDefaultTargets (xml);
185 static readonly char [] item_target_sep = {';'};
187 void ProcessXml (ProjectInstance parent, ProjectRootElement xml)
189 TaskDatabase = new BuildTaskDatabase (this, xml);
191 // this needs to be initialized here (regardless of that items won't be evaluated at property evaluation;
192 // Conditions could incorrectly reference items and lack of this list causes NRE.
193 all_evaluated_items = new List<ProjectItemInstance> ();
195 // property evaluation happens couple of times.
196 // At first step, all non-imported properties are evaluated TOO, WHILE those properties are being evaluated.
197 // This means, Include and IncludeGroup elements with Condition attribute MAY contain references to
198 // properties and they will be expanded.
199 var elements = EvaluatePropertiesAndImports (xml.Children).ToArray (); // ToArray(): to not lazily evaluate elements.
201 // next, evaluate items
202 EvaluateItems (xml, elements);
204 // finally, evaluate targets and tasks
205 EvaluateTasks (elements);
208 IEnumerable<ProjectElement> EvaluatePropertiesAndImports (IEnumerable<ProjectElement> elements)
210 // First step: evaluate Properties
211 foreach (var child in elements) {
213 var pge = child as ProjectPropertyGroupElement;
214 if (pge != null && EvaluateCondition (pge.Condition))
215 foreach (var p in pge.Properties)
216 // do not allow overwriting reserved or well-known properties by user
217 if (!this.properties.Any (_ => (_.IsImmutable) && _.Name.Equals (p.Name, StringComparison.InvariantCultureIgnoreCase)))
218 if (EvaluateCondition (p.Condition))
219 this.properties.Add (new ProjectPropertyInstance (p.Name, false, ExpandString (p.Value)));
221 var ige = child as ProjectImportGroupElement;
222 if (ige != null && EvaluateCondition (ige.Condition)) {
223 foreach (var incc in ige.Imports) {
224 if (EvaluateCondition (incc.Condition))
225 foreach (var e in Import (incc))
229 var inc = child as ProjectImportElement;
230 if (inc != null && EvaluateCondition (inc.Condition))
231 foreach (var e in Import (inc))
236 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)
238 return ProjectCollection.GetAllItems<T> (ExpandString, include, exclude, creator, taskItemCreator, Directory, assignRecurse,
239 t => all_evaluated_items.Any (i => i.EvaluatedInclude == t.ItemSpec && itemTypeCheck (i.ItemType)));
242 void EvaluateItems (ProjectRootElement xml, IEnumerable<ProjectElement> elements)
244 foreach (var child in elements) {
245 var ige = child as ProjectItemGroupElement;
247 foreach (var p in ige.Items) {
248 if (!EvaluateCondition (ige.Condition) || !EvaluateCondition (p.Condition))
250 Func<string,ProjectItemInstance> creator = s => new ProjectItemInstance (this, p.ItemType, p.Metadata.Select (m => new KeyValuePair<string,string> (m.Name, m.Value)).ToList (), s);
251 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)) {
252 raw_items.Add (item);
253 all_evaluated_items.Add (item);
257 var def = child as ProjectItemDefinitionGroupElement;
259 foreach (var p in def.ItemDefinitions) {
260 if (EvaluateCondition (p.Condition)) {
261 ProjectItemDefinitionInstance existing;
262 if (!item_definitions.TryGetValue (p.ItemType, out existing))
263 item_definitions.Add (p.ItemType, (existing = new ProjectItemDefinitionInstance (p)));
264 existing.AddItems (p);
269 all_evaluated_items.Sort ((p1, p2) => string.Compare (p1.ItemType, p2.ItemType, StringComparison.OrdinalIgnoreCase));
272 void EvaluateTasks (IEnumerable<ProjectElement> elements)
274 foreach (var child in elements) {
275 var te = child as ProjectTargetElement;
277 this.targets.Add (te.Name, new ProjectTargetInstance (te));
281 IEnumerable<ProjectElement> Import (ProjectImportElement import)
283 string dir = projects.GetEvaluationTimeThisFileDirectory (() => FullPath);
284 string path = WindowsCompatibilityExtensions.NormalizeFilePath (ExpandString (import.Project));
285 path = Path.IsPathRooted (path) ? path : dir != null ? Path.Combine (dir, path) : Path.GetFullPath (path);
286 if (projects.OngoingImports.Contains (path))
287 throw new InvalidProjectFileException (import.Location, null, string.Format ("Circular imports was detected: {0} is already on \"importing\" stack", path));
288 projects.OngoingImports.Push (path);
290 using (var reader = XmlReader.Create (path)) {
291 var root = ProjectRootElement.Create (reader, projects);
292 raw_imports.Add (new ResolvedImport (import, root, true));
293 return this.EvaluatePropertiesAndImports (root.Children).ToArray ();
296 projects.OngoingImports.Pop ();
300 internal IEnumerable<ProjectItemInstance> AllEvaluatedItems {
301 get { return all_evaluated_items; }
304 public List<string> DefaultTargets { get; private set; }
306 public string Directory {
307 get { return directory; }
310 public string FullPath {
311 get { return full_path; }
314 public IDictionary<string, string> GlobalProperties {
315 get { return global_properties; }
318 public List<string> InitialTargets { get; private set; }
321 public bool IsImmutable {
322 get { throw new NotImplementedException (); }
326 public IDictionary<string, ProjectItemDefinitionInstance> ItemDefinitions {
327 get { return item_definitions; }
330 public ICollection<ProjectItemInstance> Items {
331 get { return all_evaluated_items; }
334 public ICollection<string> ItemTypes {
335 get { return all_evaluated_items.Select (i => i.ItemType).Distinct ().ToArray (); }
339 public ElementLocation ProjectFileLocation {
340 get { return location; }
344 public ICollection<ProjectPropertyInstance> Properties {
345 get { return properties; }
353 IDictionary<string, ProjectTargetInstance> Targets {
354 get { return targets; }
357 public string ToolsVersion {
358 get { return tools_version; }
361 public ProjectItemInstance AddItem (string itemType, string evaluatedInclude)
363 return AddItem (itemType, evaluatedInclude, new KeyValuePair<string, string> [0]);
366 public ProjectItemInstance AddItem (string itemType, string evaluatedInclude, IEnumerable<KeyValuePair<string, string>> metadata)
368 var item = new ProjectItemInstance (this, itemType, metadata, evaluatedInclude);
369 raw_items.Add (item);
370 all_evaluated_items.Add (item);
376 return Build (new ILogger [0]);
379 public bool Build (IEnumerable<ILogger> loggers)
381 return Build (loggers, new ForwardingLoggerRecord [0]);
384 public bool Build (IEnumerable<ILogger> loggers, IEnumerable<ForwardingLoggerRecord> remoteLoggers)
386 return Build (DefaultTargets.ToArray (), loggers, remoteLoggers);
389 public bool Build (string target, IEnumerable<ILogger> loggers)
391 return Build (target, loggers, new ForwardingLoggerRecord [0]);
394 public bool Build (string [] targets, IEnumerable<ILogger> loggers)
396 return Build (targets, loggers, new ForwardingLoggerRecord [0]);
399 public bool Build (string target, IEnumerable<ILogger> loggers, IEnumerable<ForwardingLoggerRecord> remoteLoggers)
401 return Build (new string [] {target}, loggers, remoteLoggers);
404 public bool Build (string [] targets, IEnumerable<ILogger> loggers, IEnumerable<ForwardingLoggerRecord> remoteLoggers)
406 IDictionary<string, TargetResult> outputs;
407 return Build (targets, loggers, remoteLoggers, out outputs);
410 public bool Build (string[] targets, IEnumerable<ILogger> loggers, out IDictionary<string, TargetResult> targetOutputs)
412 return Build (targets, loggers, new ForwardingLoggerRecord [0], out targetOutputs);
415 public bool Build (string[] targets, IEnumerable<ILogger> loggers, IEnumerable<ForwardingLoggerRecord> remoteLoggers, out IDictionary<string, TargetResult> targetOutputs)
417 var manager = new BuildManager ();
418 var parameters = new BuildParameters (projects) {
419 ForwardingLoggers = remoteLoggers,
422 var requestData = new BuildRequestData (this, targets ?? DefaultTargets.ToArray ());
423 var result = manager.Build (parameters, requestData);
424 targetOutputs = result.ResultsByTarget;
425 return result.OverallResult == BuildResultCode.Success;
428 public ProjectInstance DeepCopy ()
430 return DeepCopy (false);
433 public ProjectInstance DeepCopy (bool isImmutable)
435 throw new NotImplementedException ();
438 public bool EvaluateCondition (string condition)
440 return string.IsNullOrWhiteSpace (condition) || new ExpressionEvaluator (this, null).EvaluateAsBoolean (condition);
443 public string ExpandString (string unexpandedValue)
445 return ExpandString (unexpandedValue, null);
448 string ExpandString (string unexpandedValue, string replacementForMissingStuff)
450 return new ExpressionEvaluator (this, replacementForMissingStuff).Evaluate (unexpandedValue);
453 public ICollection<ProjectItemInstance> GetItems (string itemType)
455 return new CollectionFromEnumerable<ProjectItemInstance> (Items.Where (p => p.ItemType.Equals (itemType, StringComparison.OrdinalIgnoreCase)));
458 public IEnumerable<ProjectItemInstance> GetItemsByItemTypeAndEvaluatedInclude (string itemType, string evaluatedInclude)
460 throw new NotImplementedException ();
463 public ProjectPropertyInstance GetProperty (string name)
465 return properties.FirstOrDefault (p => p.Name.Equals (name, StringComparison.OrdinalIgnoreCase));
468 public string GetPropertyValue (string name)
470 var prop = GetProperty (name);
471 return prop != null ? prop.EvaluatedValue : string.Empty;
474 public bool RemoveItem (ProjectItemInstance item)
476 // yeah, this raw_items should vanish...
477 raw_items.Remove (item);
478 return all_evaluated_items.Remove (item);
481 public bool RemoveProperty (string name)
483 var removed = properties.FirstOrDefault (p => p.Name.Equals (name, StringComparison.OrdinalIgnoreCase));
486 properties.Remove (removed);
490 public ProjectPropertyInstance SetProperty (string name, string evaluatedValue)
492 var p = new ProjectPropertyInstance (name, false, evaluatedValue);
497 public ProjectRootElement ToProjectRootElement ()
499 throw new NotImplementedException ();
503 public void UpdateStateFrom (ProjectInstance projectState)
505 throw new NotImplementedException ();
511 public static string GetEvaluatedItemIncludeEscaped (ProjectItemDefinitionInstance item)
513 // ?? ItemDefinition does not have Include attribute. What's the point here?
514 throw new NotImplementedException ();
517 public static string GetEvaluatedItemIncludeEscaped (ProjectItemInstance item)
519 return ProjectCollection.Escape (item.EvaluatedInclude);
522 public static string GetMetadataValueEscaped (ProjectMetadataInstance metadatum)
524 return ProjectCollection.Escape (metadatum.EvaluatedValue);
527 public static string GetMetadataValueEscaped (ProjectItemDefinitionInstance item, string name)
529 var md = item.Metadata.FirstOrDefault (m => m.Name.Equals (name, StringComparison.OrdinalIgnoreCase));
530 return md != null ? ProjectCollection.Escape (md.EvaluatedValue) : null;
533 public static string GetMetadataValueEscaped (ProjectItemInstance item, string name)
535 var md = item.Metadata.FirstOrDefault (m => m.Name.Equals (name, StringComparison.OrdinalIgnoreCase));
536 return md != null ? ProjectCollection.Escape (md.EvaluatedValue) : null;
539 public static string GetPropertyValueEscaped (ProjectPropertyInstance property)
542 //return ProjectCollection.Escape (property.EvaluatedValue);
543 return property.EvaluatedValue;
546 internal BuildTaskDatabase TaskDatabase { get; private set; }
548 internal string GetFullPath (string pathRelativeToProject)
550 if (Path.IsPathRooted (pathRelativeToProject))
551 return pathRelativeToProject;
552 return Path.GetFullPath (Path.Combine (Directory, pathRelativeToProject));