2009-03-27 Jonathan Chambers <joncham@gmail.com>
[mono.git] / mcs / class / Microsoft.Build.Engine / Microsoft.Build.BuildEngine / BuildItem.cs
1 //
2 // BuildItem.cs:
3 //
4 // Author:
5 //   Marek Sieradzki (marek.sieradzki@gmail.com)
6 // 
7 // (C) 2005 Marek Sieradzki
8 //
9 // Permission is hereby granted, free of charge, to any person obtaining
10 // a copy of this software and associated documentation files (the
11 // "Software"), to deal in the Software without restriction, including
12 // without limitation the rights to use, copy, modify, merge, publish,
13 // distribute, sublicense, and/or sell copies of the Software, and to
14 // permit persons to whom the Software is furnished to do so, subject to
15 // the following conditions:
16 //
17 // The above copyright notice and this permission notice shall be
18 // included in all copies or substantial portions of the Software.
19 //
20 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
24 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
25 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
26 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
27
28 #if NET_2_0
29
30 using System;
31 using System.Collections;
32 using System.Collections.Generic;
33 using System.Collections.Specialized;
34 using System.IO;
35 using System.Text;
36 using System.Xml;
37 using Microsoft.Build.Framework;
38 using Microsoft.Build.Utilities;
39 using Mono.XBuild.Utilities;
40
41 namespace Microsoft.Build.BuildEngine {
42         public class BuildItem {
43
44                 List<BuildItem> child_items;
45                 XmlElement      itemElement;
46                 string          finalItemSpec;
47                 bool            isImported;
48                 string          itemInclude;
49                 string          name;
50                 BuildItemGroup  parent_item_group;
51                 BuildItem       parent_item;
52                 //string                recursiveDir;
53                 IDictionary     evaluatedMetadata;
54                 IDictionary     unevaluatedMetadata;
55
56                 BuildItem ()
57                 {
58                 }
59                 
60                 public BuildItem (string itemName, ITaskItem taskItem)
61                 {
62                         if (taskItem == null)
63                                 throw new ArgumentNullException ("taskItem");
64
65                         this.name = itemName;
66                         this.finalItemSpec = taskItem.ItemSpec;
67                         this.itemInclude = Utilities.Escape (taskItem.ItemSpec);
68                         this.evaluatedMetadata = (Hashtable) taskItem.CloneCustomMetadata ();
69                         this.unevaluatedMetadata = (Hashtable) taskItem.CloneCustomMetadata ();
70                 }
71
72                 public BuildItem (string itemName, string itemInclude)
73                 {
74                         if (itemInclude == null)
75                                 throw new ArgumentNullException ("itemInclude");
76                         if (itemInclude == String.Empty)
77                                 throw new ArgumentException ("Parameter \"itemInclude\" cannot have zero length.");
78
79                         name = itemName;
80                         finalItemSpec = itemInclude;
81                         this.itemInclude = itemInclude;
82                         unevaluatedMetadata = CollectionsUtil.CreateCaseInsensitiveHashtable ();
83                         evaluatedMetadata = CollectionsUtil.CreateCaseInsensitiveHashtable ();
84                 }
85
86                 internal BuildItem (XmlElement itemElement, BuildItemGroup parentItemGroup)
87                 {
88                         child_items = new List<BuildItem> ();
89                         isImported = parentItemGroup.IsImported;
90                         unevaluatedMetadata = CollectionsUtil.CreateCaseInsensitiveHashtable ();
91                         evaluatedMetadata = CollectionsUtil.CreateCaseInsensitiveHashtable ();
92                         this.parent_item_group = parentItemGroup;
93                         
94                         this.itemElement = itemElement;
95                         
96                         if (Include == String.Empty)
97                                 throw new InvalidProjectFileException (String.Format ("The required attribute \"Include\" is missing from element <{0}>.", Name));
98                 }
99                 
100                 BuildItem (BuildItem parent)
101                 {
102                         isImported = parent.isImported;
103                         name = parent.Name;
104                         parent_item = parent;
105                         parent_item.child_items.Add (this);
106                         parent_item_group = parent.parent_item_group;
107                         unevaluatedMetadata = CollectionsUtil.CreateCaseInsensitiveHashtable (parent.unevaluatedMetadata);
108                         evaluatedMetadata = CollectionsUtil.CreateCaseInsensitiveHashtable (parent.evaluatedMetadata);
109                 }
110                 
111                 public void CopyCustomMetadataTo (BuildItem destinationItem)
112                 {
113                         if (destinationItem == null)
114                                 throw new ArgumentNullException ("destinationItem");
115
116                         foreach (DictionaryEntry de in unevaluatedMetadata)
117                                 destinationItem.AddMetadata ((string) de.Key, (string) de.Value);
118                 }
119                 
120                 [MonoTODO]
121                 public BuildItem Clone ()
122                 {
123                         return (BuildItem) this.MemberwiseClone ();
124                 }
125
126                 public string GetEvaluatedMetadata (string metadataName)
127                 {
128                         if (ReservedNameUtils.IsReservedMetadataName (metadataName)) {
129                                 string metadata = ReservedNameUtils.GetReservedMetadata (FinalItemSpec, metadataName);
130                                 return (metadataName.ToLower () == "fullpath") ? Utilities.Escape (metadata) : metadata;
131                         }
132
133                         if (evaluatedMetadata.Contains (metadataName))
134                                 return (string) evaluatedMetadata [metadataName];
135                         else
136                                 return String.Empty;
137                 }
138
139                 public string GetMetadata (string metadataName)
140                 {
141                         if (ReservedNameUtils.IsReservedMetadataName (metadataName)) {
142                                 string metadata = ReservedNameUtils.GetReservedMetadata (FinalItemSpec, metadataName);
143                                 return (metadataName.ToLower () == "fullpath") ? Utilities.Escape (metadata) : metadata;
144                         } else if (unevaluatedMetadata.Contains (metadataName))
145                                 return (string) unevaluatedMetadata [metadataName];
146                         else
147                                 return String.Empty;
148                 }
149                 
150                 public bool HasMetadata (string metadataName)
151                 {
152                         if (ReservedNameUtils.IsReservedMetadataName (metadataName))
153                                 return true;
154                         else
155                                 return evaluatedMetadata.Contains (metadataName);
156                 }
157
158                 public void RemoveMetadata (string metadataName)
159                 {
160                         if (metadataName == null)
161                                 throw new ArgumentNullException ("metadataName");
162                         
163                         if (ReservedNameUtils.IsReservedMetadataName (metadataName))
164                                 throw new ArgumentException (String.Format ("\"{0}\" is a reserved item meta-data, and cannot be modified or deleted.",
165                                         metadataName));
166
167                         if (FromXml) {
168                                 if (unevaluatedMetadata.Contains (metadataName)) {
169                                         XmlNode node = itemElement [metadataName];
170                                         itemElement.RemoveChild (node);
171                                 }
172                         } else if (HasParentItem) {
173                                 if (parent_item.child_items.Count > 1)
174                                         SplitParentItem ();
175                                 parent_item.RemoveMetadata (metadataName);
176                         } 
177                         
178                         DeleteMetadata (metadataName);
179                 }
180
181                 public void SetMetadata (string metadataName,
182                                          string metadataValue)
183                 {
184                         SetMetadata (metadataName, metadataValue, false);
185                 }
186                 
187                 public void SetMetadata (string metadataName,
188                                          string metadataValue,
189                                          bool treatMetadataValueAsLiteral)
190                 {
191                         if (metadataName == null)
192                                 throw new ArgumentNullException ("metadataName");
193                         
194                         if (metadataValue == null)
195                                 throw new ArgumentNullException ("metadataValue");
196                         
197                         if (ReservedNameUtils.IsReservedMetadataName (metadataName))
198                                 throw new ArgumentException (String.Format ("\"{0}\" is a reserved item meta-data, and cannot be modified or deleted.",
199                                         metadataName));
200
201                         if (treatMetadataValueAsLiteral && !HasParentItem)
202                                 metadataValue = Utilities.Escape (metadataValue);
203
204                         if (FromXml) {
205                                 XmlElement element = itemElement [metadataName];
206                                 if (element == null) {
207                                         element = itemElement.OwnerDocument.CreateElement (metadataName, Project.XmlNamespace);
208                                         element.InnerText = metadataValue;
209                                         itemElement.AppendChild (element);
210                                 } else
211                                         element.InnerText = metadataValue;
212                         } else if (HasParentItem) {
213                                 if (parent_item.child_items.Count > 1)
214                                         SplitParentItem ();
215                                 parent_item.SetMetadata (metadataName, metadataValue, treatMetadataValueAsLiteral);
216                         }
217                         if (FromXml || HasParentItem) {
218                                 parent_item_group.ParentProject.MarkProjectAsDirty ();
219                                 parent_item_group.ParentProject.NeedToReevaluate ();
220                         }
221                         
222                         DeleteMetadata (metadataName);
223                         AddMetadata (metadataName, metadataValue);
224                 }
225
226                 void AddMetadata (string name, string value)
227                 {
228                         if (parent_item_group != null) {
229                                 Expression e = new Expression ();
230                                 e.Parse (value, true);
231                                 evaluatedMetadata [name] = (string) e.ConvertTo (parent_item_group.ParentProject, typeof (string));
232                         } else
233                                 evaluatedMetadata [name] = Utilities.Unescape (value);
234                                 
235                         unevaluatedMetadata [name] = value;
236                 }
237
238                 void DeleteMetadata (string name)
239                 {
240                         if (evaluatedMetadata.Contains (name))
241                                 evaluatedMetadata.Remove (name);
242                         
243                         if (unevaluatedMetadata.Contains (name))
244                                 unevaluatedMetadata.Remove (name);
245                 }
246
247                 internal void Evaluate (Project project, bool evaluatedTo)
248                 {
249                         // FIXME: maybe make Expression.ConvertTo (null, ...) work as Utilities.Unescape ()?
250                         if (project == null) {
251                                 this.finalItemSpec = Utilities.Unescape (Include);
252                                 return;
253                         }
254                         
255                         foreach (XmlNode xn in itemElement.ChildNodes) {
256                                 XmlElement xe = xn as XmlElement;
257                                 if (xe != null && ConditionParser.ParseAndEvaluate (xe.GetAttribute ("Condition"), project))
258                                         AddMetadata (xe.Name, xe.InnerText);
259                         }
260
261                         DirectoryScanner directoryScanner;
262                         Expression includeExpr, excludeExpr;
263                         string includes, excludes;
264
265                         includeExpr = new Expression ();
266                         includeExpr.Parse (Include, true);
267                         excludeExpr = new Expression ();
268                         excludeExpr.Parse (Exclude, true);
269                         
270                         includes = (string) includeExpr.ConvertTo (project, typeof (string));
271                         excludes = (string) excludeExpr.ConvertTo (project, typeof (string));
272
273                         this.finalItemSpec = includes;
274                         
275                         directoryScanner = new DirectoryScanner ();
276                         
277                         directoryScanner.Includes = includes;
278                         directoryScanner.Excludes = excludes;
279
280                         if (project.FullFileName != String.Empty)
281                                 directoryScanner.BaseDirectory = new DirectoryInfo (Path.GetDirectoryName (project.FullFileName));
282                         else
283                                 directoryScanner.BaseDirectory = new DirectoryInfo (Directory.GetCurrentDirectory ());
284                         
285                         directoryScanner.Scan ();
286                         
287                         foreach (string matchedFile in directoryScanner.MatchedFilenames)
288                                 AddEvaluatedItem (project, evaluatedTo, matchedFile);
289                 }
290                 
291                 void AddEvaluatedItem (Project project, bool evaluatedTo, string itemSpec)
292                 {
293                         BuildItemGroup big;                     
294                         BuildItem bi = new BuildItem (this);
295                         bi.finalItemSpec = itemSpec;
296
297                         project.EvaluatedItemsIgnoringCondition.AddItem (bi);
298
299                         if (evaluatedTo) {
300                                 project.EvaluatedItems.AddItem (bi);
301         
302                                 if (!project.EvaluatedItemsByName.ContainsKey (bi.Name)) {
303                                         big = new BuildItemGroup (null, project, null, true);
304                                         project.EvaluatedItemsByName.Add (bi.Name, big);
305                                 } else {
306                                         big = project.EvaluatedItemsByName [bi.Name];
307                                 }
308
309                                 big.AddItem (bi);
310                         }
311
312                         if (!project.EvaluatedItemsByNameIgnoringCondition.ContainsKey (bi.Name)) {
313                                 big = new BuildItemGroup (null, project, null, true);
314                                 project.EvaluatedItemsByNameIgnoringCondition.Add (bi.Name, big);
315                         } else {
316                                 big = project.EvaluatedItemsByNameIgnoringCondition [bi.Name];
317                         }
318
319                         big.AddItem (bi);
320                 }
321                 
322                 internal string ConvertToString (Expression transform)
323                 {
324                         return GetItemSpecFromTransform (transform);
325                 }
326                 
327                 internal ITaskItem ConvertToITaskItem (Expression transform)
328                 {
329                         TaskItem taskItem;
330                         taskItem = new TaskItem (GetItemSpecFromTransform (transform), evaluatedMetadata);
331                         return taskItem;
332                 }
333
334                 internal void Detach ()
335                 {
336                         if (FromXml)
337                                 itemElement.ParentNode.RemoveChild (itemElement);
338                         else if (HasParentItem) {
339                                 if (parent_item.child_items.Count > 1)
340                                         SplitParentItem ();
341                                 parent_item.Detach ();
342                         }
343                 }
344
345                 string GetItemSpecFromTransform (Expression transform)
346                 {
347                         StringBuilder sb;
348                 
349                         if (transform == null)
350                                 return finalItemSpec;
351                         else {
352                                 sb = new StringBuilder ();
353                                 foreach (object o in transform.Collection) {
354                                         if (o is string) {
355                                                 sb.Append ((string)o);
356                                         } else if (o is PropertyReference) {
357                                                 sb.Append (((PropertyReference)o).ConvertToString (parent_item_group.ParentProject));
358                                         } else if (o is ItemReference) {
359                                                 sb.Append (((ItemReference)o).ConvertToString (parent_item_group.ParentProject));
360                                         } else if (o is MetadataReference) {
361                                                 sb.Append (GetMetadata (((MetadataReference)o).MetadataName));
362                                         }
363                                 }
364                                 return sb.ToString ();
365                         }
366                 }
367
368                 void SplitParentItem ()
369                 {
370                         BuildItem parent = parent_item;
371                         List <BuildItem> list = new List <BuildItem> ();
372                         XmlElement insertAfter = parent.itemElement;
373                         foreach (BuildItem bi in parent.child_items) {
374                                 BuildItem added = InsertElementAfter (parent, bi, insertAfter);
375                                 insertAfter = added.itemElement;
376                                 list.Add (added);
377                         }
378                         parent.parent_item_group.ReplaceWith (parent, list);
379                         parent.itemElement.ParentNode.RemoveChild (parent.itemElement);                 
380                 }
381
382                 static BuildItem InsertElementAfter (BuildItem parent, BuildItem child, XmlElement insertAfter)
383                 {
384                         BuildItem newParent;
385
386                         XmlDocument doc = parent.itemElement.OwnerDocument;
387                         XmlElement newElement = doc.CreateElement (child.Name, Project.XmlNamespace);
388                         newElement.SetAttribute ("Include", child.FinalItemSpec);
389                         if (parent.itemElement.HasAttribute ("Condition"))
390                                 newElement.SetAttribute ("Condition", parent.itemElement.GetAttribute ("Condition"));
391                         foreach (XmlNode xn in parent.itemElement)
392                                 newElement.AppendChild (xn.Clone ());
393                         parent.itemElement.ParentNode.InsertAfter (newElement, insertAfter);
394
395                         newParent = new BuildItem (newElement, parent.parent_item_group);
396                         newParent.child_items.Add (child);
397                         child.parent_item = newParent;
398
399                         return newParent;
400                 }
401
402                 public string Condition {
403                         get {
404                                 if (FromXml)
405                                         return itemElement.GetAttribute ("Condition");
406                                 else
407                                         return String.Empty;
408                         }
409                         set {
410                                 if (FromXml)
411                                         itemElement.SetAttribute ("Condition", value);
412                                 else if (!HasParentItem)
413                                         throw new InvalidOperationException ("Cannot set a condition on an object not represented by an XML element in the project file.");
414                         }
415                 }
416
417                 public string Exclude {
418                         get {
419                                 if (FromXml)
420                                         return itemElement.GetAttribute ("Exclude");
421                                 else
422                                         return String.Empty;
423                         }
424                         set {
425                                 if (FromXml)
426                                         itemElement.SetAttribute ("Exclude", value);
427                                 else
428                                         throw new InvalidOperationException ("Assigning the \"Exclude\" attribute of a virtual item is not allowed.");
429                         }
430                 }
431
432                 public string FinalItemSpec {
433                         get { return finalItemSpec; }
434                 }
435
436                 public string Include {
437                         get {
438                                 if (FromXml)
439                                         return itemElement.GetAttribute ("Include");
440                                 else if (HasParentItem)
441                                         return parent_item.Include;
442                                 else
443                                         return itemInclude;
444                         }
445                         set {
446                                 if (FromXml)
447                                         itemElement.SetAttribute ("Include", value);
448                                 else if (HasParentItem) {
449                                         if (parent_item.child_items.Count > 1)
450                                                 SplitParentItem ();
451                                         parent_item.Include = value;
452                                 } else
453                                         itemInclude = value;
454                         }
455                 }
456
457                 public bool IsImported {
458                         get { return isImported; }
459                 }
460
461                 public string Name {
462                         get {
463                                 if (FromXml)
464                                         return itemElement.Name;
465                                 else if (HasParentItem)
466                                         return parent_item.Name;
467                                 else
468                                         return name;
469                         }
470                         set {
471                                 if (FromXml) {
472                                         XmlElement newElement = itemElement.OwnerDocument.CreateElement (value, Project.XmlNamespace);
473                                         newElement.SetAttribute ("Include", itemElement.GetAttribute ("Include"));
474                                         newElement.SetAttribute ("Condition", itemElement.GetAttribute ("Condition"));
475                                         foreach (XmlNode xn in itemElement)
476                                                 newElement.AppendChild (xn.Clone ());
477                                         itemElement.ParentNode.ReplaceChild (newElement, itemElement);
478                                         itemElement = newElement;
479                                 } else if (HasParentItem) {
480                                         if (parent_item.child_items.Count > 1)
481                                                 SplitParentItem ();
482                                         parent_item.Name = value;
483                                 } else
484                                         name = value;
485                         }
486                 }
487                 
488                 internal bool FromXml {
489                         get { return itemElement != null; }
490                 }
491                 
492                 internal bool HasParentItem {
493                         get { return parent_item != null; }
494                 }
495
496                 internal BuildItem ParentItem {
497                         get { return parent_item; }
498                 }
499
500                 internal BuildItemGroup ParentItemGroup {
501                         get { return parent_item_group; }
502                         set { parent_item_group = value; }
503                 }
504         }
505 }
506
507 #endif