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);
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;
102 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 Dictionary<string,ProjectPropertyInstance> properties;
109 Dictionary<string, ProjectTargetInstance> targets;
110 string tools_version;
112 // FIXME: this is a duplicate code between Project and ProjectInstance
113 string [] GetDefaultTargets (ProjectRootElement xml)
115 var ret = GetDefaultTargets (xml, true, true);
116 return ret.Any () ? ret : GetDefaultTargets (xml, false, true);
119 string [] GetDefaultTargets (ProjectRootElement xml, bool fromAttribute, bool checkImports)
122 var ret = xml.DefaultTargets.Split (item_target_sep, StringSplitOptions.RemoveEmptyEntries).Select (s => s.Trim ()).ToArray ();
123 if (checkImports && ret.Length == 0) {
124 foreach (var imp in this.raw_imports) {
125 ret = GetDefaultTargets (imp.ImportedProject, true, false);
132 if (xml.Targets.Any ())
133 return new String [] { xml.Targets.First ().Name };
135 foreach (var imp in this.raw_imports) {
136 var ret = GetDefaultTargets (imp.ImportedProject, false, false);
141 return new string [0];
145 void InitializeProperties (ProjectRootElement xml)
147 location = xml.Location;
148 full_path = xml.FullPath;
149 directory = string.IsNullOrWhiteSpace (xml.DirectoryPath) ? System.IO.Directory.GetCurrentDirectory () : xml.DirectoryPath;
150 InitialTargets = xml.InitialTargets.Split (item_target_sep, StringSplitOptions.RemoveEmptyEntries).Select (s => s.Trim ()).ToList ();
152 raw_imports = new List<ResolvedImport> ();
153 item_definitions = new Dictionary<string, ProjectItemDefinitionInstance> ();
154 targets = new Dictionary<string, ProjectTargetInstance> ();
155 raw_items = new List<ProjectItemInstance> ();
157 properties = new Dictionary<string,ProjectPropertyInstance> ();
159 foreach (DictionaryEntry p in Environment.GetEnvironmentVariables ())
160 // FIXME: this is kind of workaround for unavoidable issue that PLATFORM=* is actually given
161 // on some platforms and that prevents setting default "PLATFORM=AnyCPU" property.
162 if (!string.Equals ("PLATFORM", (string) p.Key, StringComparison.OrdinalIgnoreCase))
163 this.properties [(string) p.Key] = new ProjectPropertyInstance ((string) p.Key, true, (string) p.Value);
164 foreach (var p in global_properties)
165 this.properties [p.Key] = new ProjectPropertyInstance (p.Key, false, p.Value);
166 var tools = projects.GetToolset (tools_version) ?? projects.GetToolset (projects.DefaultToolsVersion);
167 foreach (var p in projects.GetReservedProperties (tools, this, xml))
168 this.properties [p.Name] = p;
169 foreach (var p in ProjectCollection.GetWellKnownProperties (this))
170 this.properties [p.Name] = p;
174 DefaultTargets = GetDefaultTargets (xml).ToList ();
177 static readonly char [] item_target_sep = {';'};
179 void ProcessXml (ProjectRootElement xml)
181 UsingTasks = new List<ProjectUsingTaskElement> ();
183 // this needs to be initialized here (regardless of that items won't be evaluated at property evaluation;
184 // Conditions could incorrectly reference items and lack of this list causes NRE.
185 all_evaluated_items = new List<ProjectItemInstance> ();
187 // property evaluation happens couple of times.
188 // At first step, all non-imported properties are evaluated TOO, WHILE those properties are being evaluated.
189 // This means, Include and IncludeGroup elements with Condition attribute MAY contain references to
190 // properties and they will be expanded.
191 var elements = EvaluatePropertiesAndUsingTasksAndImportsAndChooses (xml.Children).ToArray (); // ToArray(): to not lazily evaluate elements.
193 // next, evaluate items
194 EvaluateItems (xml, elements);
196 // finally, evaluate targets and tasks
197 EvaluateTargets (elements);
200 IEnumerable<ProjectElement> EvaluatePropertiesAndUsingTasksAndImportsAndChooses (IEnumerable<ProjectElement> elements)
202 foreach (var child in elements) {
205 var ute = child as ProjectUsingTaskElement;
206 if (ute != null && EvaluateCondition (ute.Condition))
207 UsingTasks.Add (ute);
209 var pge = child as ProjectPropertyGroupElement;
210 if (pge != null && EvaluateCondition (pge.Condition))
211 foreach (var p in pge.Properties)
212 // do not allow overwriting reserved or well-known properties by user
213 if (!this.properties.Any (_ => (_.Value.IsImmutable) && _.Key.Equals (p.Name, StringComparison.InvariantCultureIgnoreCase)))
214 if (EvaluateCondition (p.Condition))
215 this.properties [p.Name] = new ProjectPropertyInstance (p.Name, false, ExpandString (p.Value));
217 var ige = child as ProjectImportGroupElement;
218 if (ige != null && EvaluateCondition (ige.Condition)) {
219 foreach (var incc in ige.Imports) {
220 if (EvaluateCondition (incc.Condition))
221 foreach (var e in Import (incc))
226 var inc = child as ProjectImportElement;
227 if (inc != null && EvaluateCondition (inc.Condition))
228 foreach (var e in Import (inc))
230 var choose = child as ProjectChooseElement;
231 if (choose != null && EvaluateCondition (choose.Condition)) {
233 foreach (ProjectWhenElement when in choose.WhenElements)
234 if (EvaluateCondition (when.Condition)) {
235 foreach (var e in EvaluatePropertiesAndUsingTasksAndImportsAndChooses (when.Children))
240 if (!done && choose.OtherwiseElement != null)
241 foreach (var e in EvaluatePropertiesAndUsingTasksAndImportsAndChooses (choose.OtherwiseElement.Children))
247 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)
249 return ProjectCollection.GetAllItems<T> (ExpandString, include, exclude, creator, taskItemCreator, Directory, assignRecurse,
250 t => all_evaluated_items.Any (i => i.EvaluatedInclude == t.ItemSpec && itemTypeCheck (i.ItemType)));
253 void EvaluateItems (ProjectRootElement xml, IEnumerable<ProjectElement> elements)
255 foreach (var child in elements.Reverse ()) {
256 var ige = child as ProjectItemGroupElement;
258 foreach (var p in ige.Items) {
259 if (!EvaluateCondition (ige.Condition) || !EvaluateCondition (p.Condition))
261 Func<string,ProjectItemInstance> creator = s => new ProjectItemInstance (this, p.ItemType, p.Metadata.Select (m => new KeyValuePair<string,string> (m.Name, m.Value)).ToList (), s);
262 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)) {
263 raw_items.Add (item);
264 all_evaluated_items.Add (item);
268 var def = child as ProjectItemDefinitionGroupElement;
270 foreach (var p in def.ItemDefinitions) {
271 if (EvaluateCondition (p.Condition)) {
272 ProjectItemDefinitionInstance existing;
273 if (!item_definitions.TryGetValue (p.ItemType, out existing))
274 item_definitions.Add (p.ItemType, (existing = new ProjectItemDefinitionInstance (p)));
275 existing.AddItems (p);
280 all_evaluated_items.Sort ((p1, p2) => string.Compare (p1.ItemType, p2.ItemType, StringComparison.OrdinalIgnoreCase));
283 void EvaluateTargets (IEnumerable<ProjectElement> elements)
285 foreach (var child in elements) {
286 var te = child as ProjectTargetElement;
288 // It overwrites same name target.
289 this.targets [te.Name] = new ProjectTargetInstance (te);
293 IEnumerable<ProjectElement> Import (ProjectImportElement import)
295 string dir = projects.GetEvaluationTimeThisFileDirectory (() => FullPath);
296 // FIXME: use appropriate logger (but cannot be instantiated here...?)
297 string path = ProjectCollection.FindFileInSeveralExtensionsPath (ref extensions_path_override, ExpandString, import.Project, TextWriter.Null.WriteLine);
298 path = Path.IsPathRooted (path) ? path : dir != null ? Path.Combine (dir, path) : Path.GetFullPath (path);
299 if (projects.OngoingImports.Contains (path))
300 throw new InvalidProjectFileException (import.Location, null, string.Format ("Circular imports was detected: {0} is already on \"importing\" stack", path));
301 projects.OngoingImports.Push (path);
303 using (var reader = XmlReader.Create (path)) {
304 var root = ProjectRootElement.Create (reader, projects);
305 raw_imports.Add (new ResolvedImport (import, root, true));
306 return this.EvaluatePropertiesAndUsingTasksAndImportsAndChooses (root.Children).ToArray ();
309 projects.OngoingImports.Pop ();
313 internal IEnumerable<ProjectItemInstance> AllEvaluatedItems {
314 get { return all_evaluated_items; }
317 public List<string> DefaultTargets { get; private set; }
319 public string Directory {
320 get { return directory; }
323 public string FullPath {
324 get { return full_path; }
327 public IDictionary<string, string> GlobalProperties {
328 get { return global_properties; }
331 public List<string> InitialTargets { get; private set; }
333 public bool IsImmutable {
334 get { throw new NotImplementedException (); }
337 public IDictionary<string, ProjectItemDefinitionInstance> ItemDefinitions {
338 get { return item_definitions; }
341 public ICollection<ProjectItemInstance> Items {
342 get { return all_evaluated_items; }
345 public ICollection<string> ItemTypes {
346 get { return all_evaluated_items.Select (i => i.ItemType).Distinct ().ToArray (); }
349 public ElementLocation ProjectFileLocation {
350 get { return location; }
353 public ICollection<ProjectPropertyInstance> Properties {
354 get { return properties.Values; }
358 IDictionary<string, ProjectTargetInstance> Targets {
359 get { return targets; }
362 public string ToolsVersion {
363 get { return tools_version; }
366 public ProjectItemInstance AddItem (string itemType, string evaluatedInclude)
368 return AddItem (itemType, evaluatedInclude, new KeyValuePair<string, string> [0]);
371 public ProjectItemInstance AddItem (string itemType, string evaluatedInclude, IEnumerable<KeyValuePair<string, string>> metadata)
373 var item = new ProjectItemInstance (this, itemType, metadata, evaluatedInclude);
374 raw_items.Add (item);
375 all_evaluated_items.Add (item);
381 return Build (new ILogger [0]);
384 public bool Build (IEnumerable<ILogger> loggers)
386 return Build (loggers, new ForwardingLoggerRecord [0]);
389 public bool Build (IEnumerable<ILogger> loggers, IEnumerable<ForwardingLoggerRecord> remoteLoggers)
391 return Build (DefaultTargets.ToArray (), loggers, remoteLoggers);
394 public bool Build (string target, IEnumerable<ILogger> loggers)
396 return Build (target, loggers, new ForwardingLoggerRecord [0]);
399 public bool Build (string [] targets, IEnumerable<ILogger> loggers)
401 return Build (targets, loggers, new ForwardingLoggerRecord [0]);
404 public bool Build (string target, IEnumerable<ILogger> loggers, IEnumerable<ForwardingLoggerRecord> remoteLoggers)
406 return Build (new string [] {target}, loggers, remoteLoggers);
409 public bool Build (string [] targets, IEnumerable<ILogger> loggers, IEnumerable<ForwardingLoggerRecord> remoteLoggers)
411 IDictionary<string, TargetResult> outputs;
412 return Build (targets, loggers, remoteLoggers, out outputs);
415 public bool Build (string[] targets, IEnumerable<ILogger> loggers, out IDictionary<string, TargetResult> targetOutputs)
417 return Build (targets, loggers, new ForwardingLoggerRecord [0], out targetOutputs);
420 public bool Build (string[] targets, IEnumerable<ILogger> loggers, IEnumerable<ForwardingLoggerRecord> remoteLoggers, out IDictionary<string, TargetResult> targetOutputs)
422 var manager = new BuildManager ();
423 var parameters = new BuildParameters (projects) {
424 ForwardingLoggers = remoteLoggers,
426 DefaultToolsVersion = projects.DefaultToolsVersion,
428 var requestData = new BuildRequestData (this, targets ?? DefaultTargets.ToArray ());
429 var result = manager.Build (parameters, requestData);
431 targetOutputs = result.ResultsByTarget;
432 return result.OverallResult == BuildResultCode.Success;
435 public ProjectInstance DeepCopy ()
437 return DeepCopy (false);
440 public ProjectInstance DeepCopy (bool isImmutable)
442 throw new NotImplementedException ();
445 public bool EvaluateCondition (string condition)
447 return string.IsNullOrWhiteSpace (condition) || new ExpressionEvaluator (this).EvaluateAsBoolean (condition);
450 public string ExpandString (string unexpandedValue)
452 return WindowsCompatibilityExtensions.NormalizeFilePath (new ExpressionEvaluator (this).Evaluate (unexpandedValue));
455 internal string ExpandString (ExpressionEvaluator evaluator, string unexpandedValue)
457 return WindowsCompatibilityExtensions.NormalizeFilePath (evaluator.Evaluate (unexpandedValue));
460 public ICollection<ProjectItemInstance> GetItems (string itemType)
462 return new CollectionFromEnumerable<ProjectItemInstance> (Items.Where (p => p.ItemType.Equals (itemType, StringComparison.OrdinalIgnoreCase)));
465 public IEnumerable<ProjectItemInstance> GetItemsByItemTypeAndEvaluatedInclude (string itemType, string evaluatedInclude)
467 throw new NotImplementedException ();
470 string extensions_path_override;
472 public ProjectPropertyInstance GetProperty (string name)
474 if (extensions_path_override != null && (name.Equals ("MSBuildExtensionsPath") || name.Equals ("MSBuildExtensionsPath32") || name.Equals ("MSBuildExtensionsPath64")))
475 return new ProjectPropertyInstance (name, true, extensions_path_override);
476 return properties.Values.FirstOrDefault (p => p.Name.Equals (name, StringComparison.OrdinalIgnoreCase));
479 public string GetPropertyValue (string name)
481 var prop = GetProperty (name);
482 return prop != null ? prop.EvaluatedValue : string.Empty;
485 public bool RemoveItem (ProjectItemInstance item)
487 // yeah, this raw_items should vanish...
488 raw_items.Remove (item);
489 return all_evaluated_items.Remove (item);
492 public bool RemoveProperty (string name)
494 var removed = properties.Values.FirstOrDefault (p => p.Name.Equals (name, StringComparison.OrdinalIgnoreCase));
497 properties.Remove (name);
501 public ProjectPropertyInstance SetProperty (string name, string evaluatedValue)
503 var p = new ProjectPropertyInstance (name, false, evaluatedValue);
504 properties [p.Name] = p;
508 public ProjectRootElement ToProjectRootElement ()
510 throw new NotImplementedException ();
513 public void UpdateStateFrom (ProjectInstance projectState)
515 throw new NotImplementedException ();
520 public static string GetEvaluatedItemIncludeEscaped (ProjectItemDefinitionInstance item)
522 // ?? ItemDefinition does not have Include attribute. What's the point here?
523 throw new NotImplementedException ();
526 public static string GetEvaluatedItemIncludeEscaped (ProjectItemInstance item)
528 return ProjectCollection.Escape (item.EvaluatedInclude);
531 public static string GetMetadataValueEscaped (ProjectMetadataInstance metadatum)
533 return ProjectCollection.Escape (metadatum.EvaluatedValue);
536 public static string GetMetadataValueEscaped (ProjectItemDefinitionInstance item, string name)
538 var md = item.Metadata.FirstOrDefault (m => m.Name.Equals (name, StringComparison.OrdinalIgnoreCase));
539 return md != null ? ProjectCollection.Escape (md.EvaluatedValue) : null;
542 public static string GetMetadataValueEscaped (ProjectItemInstance item, string name)
544 var md = item.Metadata.FirstOrDefault (m => m.Name.Equals (name, StringComparison.OrdinalIgnoreCase));
545 return md != null ? ProjectCollection.Escape (md.EvaluatedValue) : null;
548 public static string GetPropertyValueEscaped (ProjectPropertyInstance property)
551 //return ProjectCollection.Escape (property.EvaluatedValue);
552 return property.EvaluatedValue;
555 internal List<ProjectUsingTaskElement> UsingTasks { get; private set; }
557 internal string GetFullPath (string pathRelativeToProject)
559 if (Path.IsPathRooted (pathRelativeToProject))
560 return pathRelativeToProject;
561 return Path.GetFullPath (Path.Combine (Directory, pathRelativeToProject));