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 = toolsVersion ?? projects.DefaultToolsVersion;
87 InitializeProperties (xml, null);
90 public ProjectInstance (string projectFile, IDictionary<string, string> globalProperties,
91 string toolsVersion, ProjectCollection projectCollection)
92 : this (ProjectRootElement.Create (projectFile), globalProperties, toolsVersion, projectCollection)
96 ProjectCollection projects;
97 IDictionary<string, string> global_properties;
99 string full_path, directory;
101 ElementLocation location;
104 Dictionary<string, ProjectItemDefinitionInstance> item_definitions;
105 List<ResolvedImport> raw_imports; // maybe we don't need this...
106 List<ProjectItemInstance> all_evaluated_items;
107 List<ProjectItemInstance> raw_items;
108 List<ProjectPropertyInstance> properties;
109 Dictionary<string, ProjectTargetInstance> targets;
110 string tools_version;
112 List<string> GetDefaultTargets (ProjectRootElement xml)
114 var ret = xml.DefaultTargets.Split (item_target_sep, StringSplitOptions.RemoveEmptyEntries).Select (s => s.Trim ()).ToList ();
115 if (ret.Count == 0 && xml.Targets.Any ())
116 ret.Add (xml.Targets.First ().Name);
120 void InitializeProperties (ProjectRootElement xml, ProjectInstance parent)
123 location = xml.Location;
125 full_path = xml.FullPath;
126 directory = string.IsNullOrWhiteSpace (xml.DirectoryPath) ? System.IO.Directory.GetCurrentDirectory () : xml.DirectoryPath;
127 DefaultTargets = GetDefaultTargets (xml);
128 InitialTargets = xml.InitialTargets.Split (item_target_sep, StringSplitOptions.RemoveEmptyEntries).Select (s => s.Trim ()).ToList ();
130 raw_imports = new List<ResolvedImport> ();
131 item_definitions = new Dictionary<string, ProjectItemDefinitionInstance> ();
132 targets = new Dictionary<string, ProjectTargetInstance> ();
133 raw_items = new List<ProjectItemInstance> ();
135 // FIXME: this is likely hack. Test ImportedProject.Properties to see what exactly should happen.
136 if (parent != null) {
137 properties = parent.properties;
139 properties = new List<ProjectPropertyInstance> ();
141 foreach (DictionaryEntry p in Environment.GetEnvironmentVariables ())
142 // FIXME: this is kind of workaround for unavoidable issue that PLATFORM=* is actually given
143 // on some platforms and that prevents setting default "PLATFORM=AnyCPU" property.
144 if (!string.Equals ("PLATFORM", (string) p.Key, StringComparison.OrdinalIgnoreCase))
145 this.properties.Add (new ProjectPropertyInstance ((string) p.Key, false, (string) p.Value));
146 foreach (var p in global_properties)
147 this.properties.Add (new ProjectPropertyInstance (p.Key, false, p.Value));
148 var tools = projects.GetToolset (tools_version) ?? projects.GetToolset (projects.DefaultToolsVersion);
149 foreach (var p in projects.GetReservedProperties (tools, this, xml))
150 this.properties.Add (p);
151 foreach (var p in ProjectCollection.GetWellKnownProperties (this))
152 this.properties.Add (p);
155 ProcessXml (parent, xml);
158 static readonly char [] item_target_sep = {';'};
160 void ProcessXml (ProjectInstance parent, ProjectRootElement xml)
162 TaskDatabase = new BuildTaskDatabase (this, xml);
164 // this needs to be initialized here (regardless of that items won't be evaluated at property evaluation;
165 // Conditions could incorrectly reference items and lack of this list causes NRE.
166 all_evaluated_items = new List<ProjectItemInstance> ();
168 // property evaluation happens couple of times.
169 // At first step, all non-imported properties are evaluated TOO, WHILE those properties are being evaluated.
170 // This means, Include and IncludeGroup elements with Condition attribute MAY contain references to
171 // properties and they will be expanded.
172 var elements = EvaluatePropertiesAndImports (xml.Children).ToArray (); // ToArray(): to not lazily evaluate elements.
174 // next, evaluate items
175 EvaluateItems (xml, elements);
177 // finally, evaluate targets and tasks
178 EvaluateTasks (elements);
181 IEnumerable<ProjectElement> EvaluatePropertiesAndImports (IEnumerable<ProjectElement> elements)
183 // First step: evaluate Properties
184 foreach (var child in elements) {
186 var pge = child as ProjectPropertyGroupElement;
187 if (pge != null && EvaluateCondition (pge.Condition))
188 foreach (var p in pge.Properties)
189 // do not allow overwriting reserved or well-known properties by user
190 if (!this.properties.Any (_ => (_.IsImmutable) && _.Name.Equals (p.Name, StringComparison.InvariantCultureIgnoreCase)))
191 if (EvaluateCondition (p.Condition))
192 this.properties.Add (new ProjectPropertyInstance (p.Name, false, ExpandString (p.Value)));
194 var ige = child as ProjectImportGroupElement;
195 if (ige != null && EvaluateCondition (ige.Condition)) {
196 foreach (var incc in ige.Imports) {
197 foreach (var e in Import (incc))
201 var inc = child as ProjectImportElement;
202 if (inc != null && EvaluateCondition (inc.Condition))
203 foreach (var e in Import (inc))
208 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)
210 var includes = ExpandString (include).Split (item_target_sep, StringSplitOptions.RemoveEmptyEntries);
211 var excludes = ExpandString (exclude).Split (item_target_sep, StringSplitOptions.RemoveEmptyEntries);
213 if (includes.Length == 0)
215 if (includes.Length == 1 && includes [0].IndexOf ('*') < 0 && excludes.Length == 0) {
216 // for most case - shortcut.
217 var item = creator (includes [0]);
220 var ds = new Microsoft.Build.BuildEngine.DirectoryScanner () {
221 BaseDirectory = new DirectoryInfo (Directory),
222 Includes = includes.Select (i => taskItemCreator (i)).ToArray (),
223 Excludes = excludes.Select (e => taskItemCreator (e)).ToArray (),
226 foreach (var taskItem in ds.MatchedItems) {
227 if (all_evaluated_items.Any (i => i.EvaluatedInclude == taskItem.ItemSpec && itemTypeCheck (i.ItemType)))
228 continue; // skip duplicate
229 var item = creator (taskItem.ItemSpec);
230 string recurse = taskItem.GetMetadata ("RecursiveDir");
231 assignRecurse (item, recurse);
237 void EvaluateItems (ProjectRootElement xml, IEnumerable<ProjectElement> elements)
239 foreach (var child in elements) {
240 var ige = child as ProjectItemGroupElement;
242 foreach (var p in ige.Items) {
243 if (!EvaluateCondition (ige.Condition) || !EvaluateCondition (p.Condition))
245 Func<string,ProjectItemInstance> creator = s => new ProjectItemInstance (this, p.ItemType, p.Metadata.Select (m => new KeyValuePair<string,string> (m.Name, m.Value)).ToList (), s);
246 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)) {
247 raw_items.Add (item);
248 all_evaluated_items.Add (item);
252 var def = child as ProjectItemDefinitionGroupElement;
254 foreach (var p in def.ItemDefinitions) {
255 if (EvaluateCondition (p.Condition)) {
256 ProjectItemDefinitionInstance existing;
257 if (!item_definitions.TryGetValue (p.ItemType, out existing))
258 item_definitions.Add (p.ItemType, (existing = new ProjectItemDefinitionInstance (p)));
259 existing.AddItems (p);
264 all_evaluated_items.Sort ((p1, p2) => string.Compare (p1.ItemType, p2.ItemType, StringComparison.OrdinalIgnoreCase));
267 void EvaluateTasks (IEnumerable<ProjectElement> elements)
269 foreach (var child in elements) {
270 var te = child as ProjectTargetElement;
272 this.targets.Add (te.Name, new ProjectTargetInstance (te));
276 IEnumerable<ProjectElement> Import (ProjectImportElement import)
278 string dir = projects.GetEvaluationTimeThisFileDirectory (() => FullPath);
279 string path = WindowsCompatibilityExtensions.NormalizeFilePath (ExpandString (import.Project));
280 path = Path.IsPathRooted (path) ? path : dir != null ? Path.Combine (dir, path) : Path.GetFullPath (path);
281 if (projects.OngoingImports.Contains (path))
282 throw new InvalidProjectFileException (import.Location, null, string.Format ("Circular imports was detected: {0} is already on \"importing\" stack", path));
283 projects.OngoingImports.Push (path);
285 using (var reader = XmlReader.Create (path)) {
286 var root = ProjectRootElement.Create (reader, projects);
287 if (DefaultTargets.Count == 0)
288 DefaultTargets.AddRange (GetDefaultTargets (root));
289 raw_imports.Add (new ResolvedImport (import, root, true));
290 return this.EvaluatePropertiesAndImports (root.Children).ToArray ();
293 projects.OngoingImports.Pop ();
297 public List<string> DefaultTargets { get; private set; }
299 public string Directory {
300 get { return directory; }
303 public string FullPath {
304 get { return full_path; }
307 public IDictionary<string, string> GlobalProperties {
308 get { return global_properties; }
311 public List<string> InitialTargets { get; private set; }
314 public bool IsImmutable {
315 get { throw new NotImplementedException (); }
319 public IDictionary<string, ProjectItemDefinitionInstance> ItemDefinitions {
320 get { return item_definitions; }
323 public ICollection<ProjectItemInstance> Items {
324 get { return all_evaluated_items; }
327 public ICollection<string> ItemTypes {
328 get { return all_evaluated_items.Select (i => i.ItemType).Distinct ().ToArray (); }
332 public ElementLocation ProjectFileLocation {
333 get { return location; }
337 public ICollection<ProjectPropertyInstance> Properties {
338 get { return properties; }
346 IDictionary<string, ProjectTargetInstance> Targets {
347 get { return targets; }
350 public string ToolsVersion { get; private set; }
352 public ProjectItemInstance AddItem (string itemType, string evaluatedInclude)
354 return AddItem (itemType, evaluatedInclude, new KeyValuePair<string, string> [0]);
357 public ProjectItemInstance AddItem (string itemType, string evaluatedInclude, IEnumerable<KeyValuePair<string, string>> metadata)
359 var item = new ProjectItemInstance (this, itemType, metadata, evaluatedInclude);
360 raw_items.Add (item);
361 all_evaluated_items.Add (item);
367 return Build (new ILogger [0]);
370 public bool Build (IEnumerable<ILogger> loggers)
372 return Build (loggers, new ForwardingLoggerRecord [0]);
375 public bool Build (IEnumerable<ILogger> loggers, IEnumerable<ForwardingLoggerRecord> remoteLoggers)
377 return Build (DefaultTargets.ToArray (), loggers, remoteLoggers);
380 public bool Build (string target, IEnumerable<ILogger> loggers)
382 return Build (target, loggers, new ForwardingLoggerRecord [0]);
385 public bool Build (string [] targets, IEnumerable<ILogger> loggers)
387 return Build (targets, loggers, new ForwardingLoggerRecord [0]);
390 public bool Build (string target, IEnumerable<ILogger> loggers, IEnumerable<ForwardingLoggerRecord> remoteLoggers)
392 return Build (new string [] {target}, loggers, remoteLoggers);
395 public bool Build (string [] targets, IEnumerable<ILogger> loggers, IEnumerable<ForwardingLoggerRecord> remoteLoggers)
397 IDictionary<string, TargetResult> outputs;
398 return Build (targets, loggers, remoteLoggers, out outputs);
401 public bool Build (string[] targets, IEnumerable<ILogger> loggers, out IDictionary<string, TargetResult> targetOutputs)
403 return Build (targets, loggers, new ForwardingLoggerRecord [0], out targetOutputs);
406 public bool Build (string[] targets, IEnumerable<ILogger> loggers, IEnumerable<ForwardingLoggerRecord> remoteLoggers, out IDictionary<string, TargetResult> targetOutputs)
408 var manager = new BuildManager ();
409 var parameters = new BuildParameters (projects) {
410 ForwardingLoggers = remoteLoggers,
413 var requestData = new BuildRequestData (this, targets);
414 var result = manager.Build (parameters, requestData);
415 targetOutputs = result.ResultsByTarget;
416 return result.OverallResult == BuildResultCode.Success;
419 public ProjectInstance DeepCopy ()
421 return DeepCopy (false);
424 public ProjectInstance DeepCopy (bool isImmutable)
426 throw new NotImplementedException ();
429 public bool EvaluateCondition (string condition)
431 return string.IsNullOrWhiteSpace (condition) || new ExpressionEvaluator (this, null).EvaluateAsBoolean (condition);
434 public string ExpandString (string unexpandedValue)
436 return ExpandString (unexpandedValue, null);
439 string ExpandString (string unexpandedValue, string replacementForMissingStuff)
441 return new ExpressionEvaluator (this, replacementForMissingStuff).Evaluate (unexpandedValue);
444 public ICollection<ProjectItemInstance> GetItems (string itemType)
446 return new CollectionFromEnumerable<ProjectItemInstance> (Items.Where (p => p.ItemType.Equals (itemType, StringComparison.OrdinalIgnoreCase)));
449 public IEnumerable<ProjectItemInstance> GetItemsByItemTypeAndEvaluatedInclude (string itemType, string evaluatedInclude)
451 throw new NotImplementedException ();
454 public ProjectPropertyInstance GetProperty (string name)
456 return properties.FirstOrDefault (p => p.Name.Equals (name, StringComparison.OrdinalIgnoreCase));
459 public string GetPropertyValue (string name)
461 var prop = GetProperty (name);
462 return prop != null ? prop.EvaluatedValue : string.Empty;
465 public bool RemoveItem (ProjectItemInstance item)
467 // yeah, this raw_items should vanish...
468 raw_items.Remove (item);
469 return all_evaluated_items.Remove (item);
472 public bool RemoveProperty (string name)
474 var removed = properties.FirstOrDefault (p => p.Name.Equals (name, StringComparison.OrdinalIgnoreCase));
477 properties.Remove (removed);
481 public ProjectPropertyInstance SetProperty (string name, string evaluatedValue)
483 var p = new ProjectPropertyInstance (name, false, evaluatedValue);
488 public ProjectRootElement ToProjectRootElement ()
490 throw new NotImplementedException ();
494 public void UpdateStateFrom (ProjectInstance projectState)
496 throw new NotImplementedException ();
502 public static string GetEvaluatedItemIncludeEscaped (ProjectItemDefinitionInstance item)
504 // ?? ItemDefinition does not have Include attribute. What's the point here?
505 throw new NotImplementedException ();
508 public static string GetEvaluatedItemIncludeEscaped (ProjectItemInstance item)
510 return ProjectCollection.Escape (item.EvaluatedInclude);
513 public static string GetMetadataValueEscaped (ProjectMetadataInstance metadatum)
515 return ProjectCollection.Escape (metadatum.EvaluatedValue);
518 public static string GetMetadataValueEscaped (ProjectItemDefinitionInstance item, string name)
520 var md = item.Metadata.FirstOrDefault (m => m.Name.Equals (name, StringComparison.OrdinalIgnoreCase));
521 return md != null ? ProjectCollection.Escape (md.EvaluatedValue) : null;
524 public static string GetMetadataValueEscaped (ProjectItemInstance item, string name)
526 var md = item.Metadata.FirstOrDefault (m => m.Name.Equals (name, StringComparison.OrdinalIgnoreCase));
527 return md != null ? ProjectCollection.Escape (md.EvaluatedValue) : null;
530 public static string GetPropertyValueEscaped (ProjectPropertyInstance property)
533 //return ProjectCollection.Escape (property.EvaluatedValue);
534 return property.EvaluatedValue;
537 internal BuildTaskDatabase TaskDatabase { get; private set; }