2 // Project.cs: Project class
5 // Marek Sieradzki (marek.sieradzki@gmail.com)
7 // (C) 2005 Marek Sieradzki
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:
17 // The above copyright notice and this permission notice shall be
18 // included in all copies or substantial portions of the Software.
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.
31 using System.Collections;
32 using System.Collections.Generic;
33 using System.Collections.Specialized;
35 using System.Reflection;
38 using System.Xml.Schema;
39 using Microsoft.Build.Framework;
40 using Mono.XBuild.Framework;
41 using Mono.XBuild.CommandLine;
43 namespace Microsoft.Build.BuildEngine {
44 public class Project {
47 Dictionary <string, List <string>> conditionedProperties;
48 string[] defaultTargets;
50 BuildItemGroup evaluatedItems;
51 BuildItemGroup evaluatedItemsIgnoringCondition;
52 Dictionary <string, BuildItemGroup> evaluatedItemsByName;
53 Dictionary <string, BuildItemGroup> evaluatedItemsByNameIgnoringCondition;
54 BuildPropertyGroup evaluatedProperties;
55 string firstTargetName;
57 BuildPropertyGroup globalProperties;
58 GroupingCollection groupingCollection;
61 BuildItemGroupCollection itemGroups;
62 ImportCollection imports;
63 string[] initialTargets;
64 Dictionary <string, BuildItemGroup> last_item_group_containing;
65 bool needToReevaluate;
67 BuildPropertyGroupCollection propertyGroups;
69 TaskDatabase taskDatabase;
70 TargetCollection targets;
71 DateTime timeOfLastDirty;
72 UsingTaskCollection usingTasks;
73 XmlDocument xmlDocument;
75 bool initialTargetsBuilt;
76 List<string> builtTargetKeys;
78 BuildSettings current_settings;
80 static string extensions_path;
81 static XmlNamespaceManager manager;
82 static string ns = "http://schemas.microsoft.com/developer/msbuild/2003";
85 : this (Engine.GlobalEngine)
89 public Project (Engine engine)
91 parentEngine = engine;
93 buildEnabled = ParentEngine.BuildEnabled;
94 xmlDocument = new XmlDocument ();
95 xmlDocument.PreserveWhitespace = false;
96 xmlDocument.AppendChild (xmlDocument.CreateElement ("Project", XmlNamespace));
97 xmlDocument.DocumentElement.SetAttribute ("xmlns", ns);
99 fullFileName = String.Empty;
100 timeOfLastDirty = DateTime.Now;
101 current_settings = BuildSettings.None;
103 builtTargetKeys = new List<string> ();
105 globalProperties = new BuildPropertyGroup (null, this, null, false);
106 foreach (BuildProperty bp in parentEngine.GlobalProperties)
107 GlobalProperties.AddProperty (bp.Clone (true));
112 [MonoTODO ("Not tested")]
113 public void AddNewImport (string importLocation,
114 string importCondition)
116 if (importLocation == null)
117 throw new ArgumentNullException ("importLocation");
119 XmlElement importElement = xmlDocument.CreateElement ("Import", XmlNamespace);
120 xmlDocument.DocumentElement.AppendChild (importElement);
121 importElement.SetAttribute ("Project", importLocation);
122 if (!String.IsNullOrEmpty (importCondition))
123 importElement.SetAttribute ("Condition", importCondition);
125 Import import = new Import (importElement, this, null);
126 imports.Add (import);
127 MarkProjectAsDirty ();
131 public BuildItem AddNewItem (string itemName,
134 return AddNewItem (itemName, itemInclude, false);
137 [MonoTODO ("Adds item not in the same place as MS")]
138 public BuildItem AddNewItem (string itemName,
140 bool treatItemIncludeAsLiteral)
144 if (itemGroups.Count == 0)
145 big = AddNewItemGroup ();
147 if (last_item_group_containing.ContainsKey (itemName)) {
148 big = last_item_group_containing [itemName];
151 BuildItemGroup [] groups = new BuildItemGroup [itemGroups.Count];
152 itemGroups.CopyTo (groups, 0);
157 BuildItem item = big.AddNewItem (itemName, itemInclude, treatItemIncludeAsLiteral);
159 MarkProjectAsDirty ();
165 [MonoTODO ("Not tested")]
166 public BuildItemGroup AddNewItemGroup ()
168 XmlElement element = xmlDocument.CreateElement ("ItemGroup", XmlNamespace);
169 xmlDocument.DocumentElement.AppendChild (element);
171 BuildItemGroup big = new BuildItemGroup (element, this, null, false);
172 itemGroups.Add (big);
173 MarkProjectAsDirty ();
179 [MonoTODO ("Ignores insertAtEndOfProject")]
180 public BuildPropertyGroup AddNewPropertyGroup (bool insertAtEndOfProject)
182 XmlElement element = xmlDocument.CreateElement ("PropertyGroup", XmlNamespace);
183 xmlDocument.DocumentElement.AppendChild (element);
185 BuildPropertyGroup bpg = new BuildPropertyGroup (element, this, null, false);
186 propertyGroups.Add (bpg);
187 MarkProjectAsDirty ();
193 [MonoTODO ("Not tested, isn't added to TaskDatabase (no reevaluation)")]
194 public void AddNewUsingTaskFromAssemblyFile (string taskName,
197 if (taskName == null)
198 throw new ArgumentNullException ("taskName");
199 if (assemblyFile == null)
200 throw new ArgumentNullException ("assemblyFile");
202 XmlElement element = xmlDocument.CreateElement ("UsingTask", XmlNamespace);
203 xmlDocument.DocumentElement.AppendChild (element);
204 element.SetAttribute ("TaskName", taskName);
205 element.SetAttribute ("AssemblyFile", assemblyFile);
207 UsingTask ut = new UsingTask (element, this, null);
209 MarkProjectAsDirty ();
212 [MonoTODO ("Not tested, isn't added to TaskDatabase (no reevaluation)")]
213 public void AddNewUsingTaskFromAssemblyName (string taskName,
216 if (taskName == null)
217 throw new ArgumentNullException ("taskName");
218 if (assemblyName == null)
219 throw new ArgumentNullException ("assemblyName");
221 XmlElement element = xmlDocument.CreateElement ("UsingTask", XmlNamespace);
222 xmlDocument.DocumentElement.AppendChild (element);
223 element.SetAttribute ("TaskName", taskName);
224 element.SetAttribute ("AssemblyName", assemblyName);
226 UsingTask ut = new UsingTask (element, this, null);
228 MarkProjectAsDirty ();
231 [MonoTODO ("Not tested")]
234 return Build (new string [0]);
237 [MonoTODO ("Not tested")]
238 public bool Build (string targetName)
240 if (targetName == null)
241 return Build ((string[]) null);
243 return Build (new string [1] { targetName });
246 [MonoTODO ("Not tested")]
247 public bool Build (string [] targetNames)
249 return Build (targetNames, null);
252 [MonoTODO ("Not tested")]
253 public bool Build (string [] targetNames,
254 IDictionary targetOutputs)
256 return Build (targetNames, targetOutputs, BuildSettings.None);
259 [MonoTODO ("Not tested")]
260 public bool Build (string [] targetNames,
261 IDictionary targetOutputs,
262 BuildSettings buildFlags)
266 ParentEngine.StartProjectBuild (this, targetNames);
267 string current_directory = Environment.CurrentDirectory;
269 current_settings = buildFlags;
270 if (!String.IsNullOrEmpty (fullFileName))
271 Directory.SetCurrentDirectory (Path.GetDirectoryName (fullFileName));
273 result = BuildInternal (targetNames, targetOutputs, buildFlags);
275 ParentEngine.EndProjectBuild (this, result);
276 current_settings = BuildSettings.None;
277 Directory.SetCurrentDirectory (current_directory);
284 bool BuildInternal (string [] targetNames,
285 IDictionary targetOutputs,
286 BuildSettings buildFlags)
289 if (buildFlags == BuildSettings.None)
292 if (targetNames == null || targetNames.Length == 0) {
293 if (defaultTargets != null && defaultTargets.Length != 0)
294 targetNames = defaultTargets;
295 else if (firstTargetName != null)
296 targetNames = new string [1] { firstTargetName};
301 if (!initialTargetsBuilt && initialTargets != null && initialTargets.Length > 0) {
302 foreach (string target in initialTargets) {
303 if (!BuildTarget (target.Trim (), targetOutputs))
306 initialTargetsBuilt = true;
309 foreach (string target in targetNames)
310 if (!BuildTarget (target.Trim (), targetOutputs))
316 bool BuildTarget (string target_name, IDictionary targetOutputs)
318 if (target_name == null)
319 throw new ArgumentException ("targetNames cannot contain null strings");
321 if (!targets.Exists (target_name)) {
323 Console.WriteLine ("Target named '{0}' not found in the project.", target_name);
327 string key = GetKeyForTarget (target_name);
328 if (!targets [target_name].Build (key))
331 ITaskItem[] outputs = ParentEngine.BuiltTargetsOutputByName [key];
332 if (targetOutputs != null)
333 targetOutputs.Add (target_name, outputs);
337 internal string GetKeyForTarget (string target_name)
339 return fullFileName + ":" + target_name + ":" + GlobalPropertiesToString (GlobalProperties);
342 string GlobalPropertiesToString (BuildPropertyGroup bgp)
344 StringBuilder sb = new StringBuilder ();
345 foreach (BuildProperty bp in bgp)
346 sb.AppendFormat (" {0}:{1}", bp.Name, bp.FinalValue);
347 return sb.ToString ();
351 public string [] GetConditionedPropertyValues (string propertyName)
353 if (conditionedProperties.ContainsKey (propertyName))
354 return conditionedProperties [propertyName].ToArray ();
356 return new string [0];
359 public BuildItemGroup GetEvaluatedItemsByName (string itemName)
361 if (needToReevaluate) {
362 needToReevaluate = false;
366 if (evaluatedItemsByName.ContainsKey (itemName))
367 return evaluatedItemsByName [itemName];
369 return new BuildItemGroup (this);
372 public BuildItemGroup GetEvaluatedItemsByNameIgnoringCondition (string itemName)
374 if (needToReevaluate) {
375 needToReevaluate = false;
379 if (evaluatedItemsByNameIgnoringCondition.ContainsKey (itemName))
380 return evaluatedItemsByNameIgnoringCondition [itemName];
382 return new BuildItemGroup (this);
385 public string GetEvaluatedProperty (string propertyName)
387 if (needToReevaluate) {
388 needToReevaluate = false;
392 if (propertyName == null)
393 throw new ArgumentNullException ("propertyName");
395 BuildProperty bp = evaluatedProperties [propertyName];
397 return bp == null ? null : (string) bp;
400 [MonoTODO ("We should remember that node and not use XPath to get it")]
401 public string GetProjectExtensions (string id)
403 if (id == null || id == String.Empty)
406 XmlNode node = xmlDocument.SelectSingleNode (String.Format ("/tns:Project/tns:ProjectExtensions/tns:{0}", id), XmlNamespaceManager);
411 return node.InnerXml;
415 public void Load (string projectFileName)
417 this.fullFileName = Utilities.FromMSBuildPath (Path.GetFullPath (projectFileName));
419 string filename = fullFileName;
420 if (String.Compare (Path.GetExtension (fullFileName), ".sln", true) == 0) {
421 Project tmp_project = ParentEngine.CreateNewProject ();
422 SolutionParser sln_parser = new SolutionParser ();
423 sln_parser.ParseSolution (fullFileName, tmp_project, delegate (int errorNumber, string message) {
424 LogWarning (filename, message);
426 filename = fullFileName + ".proj";
427 tmp_project.Save (filename);
428 ParentEngine.RemoveLoadedProject (tmp_project);
431 DoLoad (new StreamReader (filename));
434 [MonoTODO ("Not tested")]
435 public void Load (TextReader textReader)
437 fullFileName = String.Empty;
441 public void LoadXml (string projectXml)
443 fullFileName = String.Empty;
444 DoLoad (new StringReader (projectXml));
445 MarkProjectAsDirty ();
449 public void MarkProjectAsDirty ()
452 timeOfLastDirty = DateTime.Now;
455 [MonoTODO ("Not tested")]
456 public void RemoveAllItemGroups ()
458 int length = ItemGroups.Count;
459 BuildItemGroup [] groups = new BuildItemGroup [length];
460 ItemGroups.CopyTo (groups, 0);
462 for (int i = 0; i < length; i++)
463 RemoveItemGroup (groups [i]);
465 MarkProjectAsDirty ();
469 [MonoTODO ("Not tested")]
470 public void RemoveAllPropertyGroups ()
472 int length = PropertyGroups.Count;
473 BuildPropertyGroup [] groups = new BuildPropertyGroup [length];
474 PropertyGroups.CopyTo (groups, 0);
476 for (int i = 0; i < length; i++)
477 RemovePropertyGroup (groups [i]);
479 MarkProjectAsDirty ();
484 public void RemoveItem (BuildItem itemToRemove)
486 if (itemToRemove == null)
487 throw new ArgumentNullException ("itemToRemove");
489 if (!itemToRemove.FromXml && !itemToRemove.HasParentItem)
490 throw new InvalidOperationException ("The object passed in is not part of the project.");
492 BuildItemGroup big = itemToRemove.ParentItemGroup;
494 if (big.Count == 1) {
495 // ParentItemGroup for items from xml and that have parent is the same
496 groupingCollection.Remove (big);
498 if (big.ParentProject != this)
499 throw new InvalidOperationException ("The object passed in is not part of the project.");
501 if (itemToRemove.FromXml)
502 big.RemoveItem (itemToRemove);
504 big.RemoveItem (itemToRemove.ParentItem);
507 MarkProjectAsDirty ();
511 [MonoTODO ("Not tested")]
512 public void RemoveItemGroup (BuildItemGroup itemGroupToRemove)
514 if (itemGroupToRemove == null)
515 throw new ArgumentNullException ("itemGroupToRemove");
517 groupingCollection.Remove (itemGroupToRemove);
518 MarkProjectAsDirty ();
522 // NOTE: does not modify imported projects
523 public void RemoveItemGroupsWithMatchingCondition (string matchingCondition)
525 throw new NotImplementedException ();
529 public void RemoveItemsByName (string itemName)
531 if (itemName == null)
532 throw new ArgumentNullException ("itemName");
534 throw new NotImplementedException ();
537 [MonoTODO ("Not tested")]
538 public void RemovePropertyGroup (BuildPropertyGroup propertyGroupToRemove)
540 if (propertyGroupToRemove == null)
541 throw new ArgumentNullException ("propertyGroupToRemove");
543 groupingCollection.Remove (propertyGroupToRemove);
544 MarkProjectAsDirty ();
548 // NOTE: does not modify imported projects
549 public void RemovePropertyGroupsWithMatchingCondition (string matchCondition)
551 throw new NotImplementedException ();
555 public void ResetBuildStatus ()
557 // hack to allow built targets to be removed
563 public void Save (string projectFileName)
565 Save (projectFileName, Encoding.Default);
569 [MonoTODO ("Ignores encoding")]
570 public void Save (string projectFileName, Encoding encoding)
572 xmlDocument.Save (projectFileName);
576 public void Save (TextWriter outTextWriter)
578 xmlDocument.Save (outTextWriter);
582 public void SetImportedProperty (string propertyName,
583 string propertyValue,
585 Project importProject)
587 SetImportedProperty (propertyName, propertyValue, condition, importProject,
588 PropertyPosition.UseExistingOrCreateAfterLastPropertyGroup);
591 public void SetImportedProperty (string propertyName,
592 string propertyValue,
594 Project importedProject,
595 PropertyPosition position)
597 SetImportedProperty (propertyName, propertyValue, condition, importedProject,
598 PropertyPosition.UseExistingOrCreateAfterLastPropertyGroup, false);
602 public void SetImportedProperty (string propertyName,
603 string propertyValue,
605 Project importedProject,
606 PropertyPosition position,
607 bool treatPropertyValueAsLiteral)
609 throw new NotImplementedException ();
612 public void SetProjectExtensions (string id, string xmlText)
615 throw new ArgumentNullException ("id");
617 throw new ArgumentNullException ("xmlText");
619 XmlNode projectExtensions, node;
621 projectExtensions = xmlDocument.SelectSingleNode ("/tns:Project/tns:ProjectExtensions", XmlNamespaceManager);
623 if (projectExtensions == null) {
624 projectExtensions = xmlDocument.CreateElement ("ProjectExtensions", XmlNamespace);
625 xmlDocument.DocumentElement.AppendChild (projectExtensions);
627 node = xmlDocument.CreateElement (id, XmlNamespace);
628 node.InnerXml = xmlText;
629 projectExtensions.AppendChild (node);
631 node = xmlDocument.SelectSingleNode (String.Format ("/tns:Project/tns:ProjectExtensions/tns:{0}", id), XmlNamespaceManager);
634 node = xmlDocument.CreateElement (id, XmlNamespace);
635 projectExtensions.AppendChild (node);
638 node.InnerXml = xmlText;
642 MarkProjectAsDirty ();
645 public void SetProperty (string propertyName,
646 string propertyValue)
648 SetProperty (propertyName, propertyValue, "true",
649 PropertyPosition.UseExistingOrCreateAfterLastPropertyGroup, false);
652 public void SetProperty (string propertyName,
653 string propertyValue,
656 SetProperty (propertyName, propertyValue, condition,
657 PropertyPosition.UseExistingOrCreateAfterLastPropertyGroup);
660 public void SetProperty (string propertyName,
661 string propertyValue,
663 PropertyPosition position)
665 SetProperty (propertyName, propertyValue, condition,
666 PropertyPosition.UseExistingOrCreateAfterLastPropertyGroup, false);
670 public void SetProperty (string propertyName,
671 string propertyValue,
673 PropertyPosition position,
674 bool treatPropertyValueAsLiteral)
676 throw new NotImplementedException ();
679 internal void Unload ()
684 internal void CheckUnloaded ()
687 throw new InvalidOperationException ("This project object has been unloaded from the MSBuild engine and is no longer valid.");
690 internal void NeedToReevaluate ()
692 needToReevaluate = true;
695 // Does the actual loading.
696 void DoLoad (TextReader textReader)
699 ParentEngine.RemoveLoadedProject (this);
701 XmlReaderSettings settings = new XmlReaderSettings ();
703 if (SchemaFile != null) {
704 settings.Schemas.Add (null, SchemaFile);
705 settings.ValidationType = ValidationType.Schema;
706 settings.ValidationEventHandler += new ValidationEventHandler (ValidationCallBack);
709 XmlReader xmlReader = XmlReader.Create (textReader, settings);
710 xmlDocument.Load (xmlReader);
712 if (xmlDocument.DocumentElement.Name != "Project") {
713 throw new InvalidProjectFileException (String.Format (
714 "The element <{0}> is unrecognized, or not supported in this context.", xmlDocument.DocumentElement.Name));
717 if (xmlDocument.DocumentElement.GetAttribute ("xmlns") != ns) {
718 throw new InvalidProjectFileException (
719 @"The default XML namespace of the project must be the MSBuild XML namespace." +
720 " If the project is authored in the MSBuild 2003 format, please add " +
721 "xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\" to the <Project> element. " +
722 "If the project has been authored in the old 1.0 or 1.2 format, please convert it to MSBuild 2003 format. ");
725 ParentEngine.AddLoadedProject (this);
726 } catch (Exception e) {
727 throw new InvalidProjectFileException (String.Format ("{0}: {1}",
728 fullFileName, e.Message), e);
730 if (textReader != null)
742 groupingCollection = new GroupingCollection (this);
743 imports = new ImportCollection (groupingCollection);
744 usingTasks = new UsingTaskCollection (this);
745 itemGroups = new BuildItemGroupCollection (groupingCollection);
746 propertyGroups = new BuildPropertyGroupCollection (groupingCollection);
747 targets = new TargetCollection (this);
748 last_item_group_containing = new Dictionary <string, BuildItemGroup> ();
750 taskDatabase = new TaskDatabase ();
751 if (ParentEngine.DefaultTasksRegistered)
752 taskDatabase.CopyTasks (ParentEngine.DefaultTasks);
754 if (xmlDocument.DocumentElement.GetAttributeNode ("DefaultTargets") != null)
755 defaultTargets = xmlDocument.DocumentElement.GetAttribute ("DefaultTargets").Split (';');
757 defaultTargets = new string [0];
759 ProcessProjectAttributes (xmlDocument.DocumentElement.Attributes);
760 ProcessElements (xmlDocument.DocumentElement, null);
766 void ProcessProjectAttributes (XmlAttributeCollection attributes)
768 foreach (XmlAttribute attr in attributes) {
770 case "InitialTargets":
771 initialTargets = attr.Value.Split (new char [] {';'},
772 StringSplitOptions.RemoveEmptyEntries);
774 case "DefaultTargets":
775 defaultTargets = attr.Value.Split (new char [] {';'},
776 StringSplitOptions.RemoveEmptyEntries);
782 internal void ProcessElements (XmlElement rootElement, ImportedProject ip)
784 foreach (XmlNode xn in rootElement.ChildNodes) {
785 if (xn is XmlElement) {
786 XmlElement xe = (XmlElement) xn;
788 case "ProjectExtensions":
789 AddProjectExtensions (xe);
800 AddUsingTask (xe, ip);
806 AddItemGroup (xe, ip);
808 case "PropertyGroup":
809 AddPropertyGroup (xe, ip);
815 throw new InvalidProjectFileException ("Invalid element in project file.");
823 evaluatedItems = new BuildItemGroup (null, this, null, true);
824 evaluatedItemsIgnoringCondition = new BuildItemGroup (null, this, null, true);
825 evaluatedItemsByName = new Dictionary <string, BuildItemGroup> (StringComparer.InvariantCultureIgnoreCase);
826 evaluatedItemsByNameIgnoringCondition = new Dictionary <string, BuildItemGroup> (StringComparer.InvariantCultureIgnoreCase);
827 if (building && current_settings == BuildSettings.None)
828 RemoveBuiltTargets ();
830 InitializeProperties ();
832 groupingCollection.Evaluate ();
834 //FIXME: UsingTasks aren't really evaluated. (shouldn't use expressions or anything)
835 foreach (UsingTask usingTask in UsingTasks)
836 usingTask.Evaluate ();
839 // Removes entries of all earlier built targets for this project
840 void RemoveBuiltTargets ()
842 foreach (string key in builtTargetKeys)
843 ParentEngine.BuiltTargetsOutputByName.Remove (key);
846 void InitializeProperties ()
850 evaluatedProperties = new BuildPropertyGroup (null, null, null, true);
852 foreach (BuildProperty gp in GlobalProperties) {
853 bp = new BuildProperty (gp.Name, gp.Value, PropertyType.Global);
854 EvaluatedProperties.AddProperty (bp);
857 foreach (BuildProperty gp in GlobalProperties)
858 ParentEngine.GlobalProperties.AddProperty (gp);
860 // add properties that we dont have from parent engine's
862 foreach (BuildProperty gp in ParentEngine.GlobalProperties) {
863 if (EvaluatedProperties [gp.Name] == null) {
864 bp = new BuildProperty (gp.Name, gp.Value, PropertyType.Global);
865 EvaluatedProperties.AddProperty (bp);
869 foreach (DictionaryEntry de in Environment.GetEnvironmentVariables ()) {
870 bp = new BuildProperty ((string) de.Key, (string) de.Value, PropertyType.Environment);
871 EvaluatedProperties.AddProperty (bp);
874 EvaluatedProperties.AddProperty (new BuildProperty ("MSBuildProjectFile", Path.GetFileName (fullFileName),
875 PropertyType.Reserved));
876 EvaluatedProperties.AddProperty (new BuildProperty ("MSBuildProjectName",
877 Path.GetFileNameWithoutExtension (fullFileName),
878 PropertyType.Reserved));
879 EvaluatedProperties.AddProperty (new BuildProperty ("MSBuildBinPath", parentEngine.BinPath, PropertyType.Reserved));
880 EvaluatedProperties.AddProperty (new BuildProperty ("MSBuildToolsPath", parentEngine.BinPath, PropertyType.Reserved));
881 EvaluatedProperties.AddProperty (new BuildProperty ("MSBuildExtensionsPath", ExtensionsPath, PropertyType.Reserved));
882 EvaluatedProperties.AddProperty (new BuildProperty ("MSBuildProjectDefaultTargets", DefaultTargets, PropertyType.Reserved));
884 // FIXME: make some internal method that will work like GetDirectoryName but output String.Empty on null/String.Empty
886 if (FullFileName == String.Empty)
887 projectDir = Environment.CurrentDirectory;
889 projectDir = Path.GetDirectoryName (FullFileName);
891 EvaluatedProperties.AddProperty (new BuildProperty ("MSBuildProjectDirectory", projectDir, PropertyType.Reserved));
894 void AddProjectExtensions (XmlElement xmlElement)
898 void AddMessage (XmlElement xmlElement)
902 void AddTarget (XmlElement xmlElement, ImportedProject importedProject)
904 Target target = new Target (xmlElement, this, importedProject);
905 targets.AddTarget (target);
907 if (firstTargetName == null)
908 firstTargetName = target.Name;
911 void AddUsingTask (XmlElement xmlElement, ImportedProject importedProject)
915 usingTask = new UsingTask (xmlElement, this, importedProject);
916 UsingTasks.Add (usingTask);
919 void AddImport (XmlElement xmlElement, ImportedProject importingProject)
923 import = new Import (xmlElement, this, importingProject);
924 Imports.Add (import);
927 void AddItemGroup (XmlElement xmlElement, ImportedProject importedProject)
929 BuildItemGroup big = new BuildItemGroup (xmlElement, this, importedProject, false);
930 ItemGroups.Add (big);
933 void AddPropertyGroup (XmlElement xmlElement, ImportedProject importedProject)
935 BuildPropertyGroup bpg = new BuildPropertyGroup (xmlElement, this, importedProject, false);
936 PropertyGroups.Add (bpg);
939 void AddChoose (XmlElement xmlElement)
941 BuildChoose bc = new BuildChoose (xmlElement, this);
942 groupingCollection.Add (bc);
945 static void ValidationCallBack (object sender, ValidationEventArgs e)
947 Console.WriteLine ("Validation Error: {0}", e.Message);
950 public bool BuildEnabled {
955 buildEnabled = value;
960 public Encoding Encoding {
961 get { return encoding; }
964 public string DefaultTargets {
966 return xmlDocument.DocumentElement.GetAttribute ("DefaultTargets");
969 xmlDocument.DocumentElement.SetAttribute ("DefaultTargets", value);
970 defaultTargets = value.Split (new char [] {';'}, StringSplitOptions.RemoveEmptyEntries);
974 public BuildItemGroup EvaluatedItems {
976 if (needToReevaluate) {
977 needToReevaluate = false;
980 return evaluatedItems;
984 public BuildItemGroup EvaluatedItemsIgnoringCondition {
986 if (needToReevaluate) {
987 needToReevaluate = false;
990 return evaluatedItemsIgnoringCondition;
994 internal IDictionary <string, BuildItemGroup> EvaluatedItemsByName {
996 // FIXME: do we need to do this here?
997 if (needToReevaluate) {
998 needToReevaluate = false;
1001 return evaluatedItemsByName;
1005 internal IDictionary <string, BuildItemGroup> EvaluatedItemsByNameIgnoringCondition {
1007 // FIXME: do we need to do this here?
1008 if (needToReevaluate) {
1009 needToReevaluate = false;
1012 return evaluatedItemsByNameIgnoringCondition;
1016 // For batching implementation
1017 Dictionary<string, BuildItemGroup> perBatchItemsByName;
1018 Dictionary<string, BuildItemGroup> commonItemsByName;
1020 internal void SetBatchedItems (Dictionary<string, BuildItemGroup> perBatchItemsByName, Dictionary<string, BuildItemGroup> commonItemsByName)
1022 this.perBatchItemsByName = perBatchItemsByName;
1023 this.commonItemsByName = commonItemsByName;
1027 internal bool TryGetEvaluatedItemByNameBatched (string itemName, out BuildItemGroup group)
1029 if (perBatchItemsByName == null && commonItemsByName == null)
1030 return EvaluatedItemsByName.TryGetValue (itemName, out group);
1032 if (perBatchItemsByName != null)
1033 return perBatchItemsByName.TryGetValue (itemName, out group);
1035 if (commonItemsByName != null)
1036 return commonItemsByName.TryGetValue (itemName, out group);
1042 internal string GetMetadataBatched (string itemName, string metadataName)
1044 BuildItemGroup group = null;
1045 if (itemName == null) {
1046 //unqualified, all items in a batch(bucket) have the
1047 //same metadata values
1048 group = GetFirst<BuildItemGroup> (perBatchItemsByName.Values);
1050 group = GetFirst<BuildItemGroup> (commonItemsByName.Values);
1053 TryGetEvaluatedItemByNameBatched (itemName, out group);
1056 if (group != null) {
1057 foreach (BuildItem item in group) {
1058 if (item.HasMetadata (metadataName))
1059 return item.GetEvaluatedMetadata (metadataName);
1062 return String.Empty;
1065 internal IEnumerable<BuildItemGroup> GetAllItemGroups ()
1067 if (perBatchItemsByName == null && commonItemsByName == null)
1068 foreach (BuildItemGroup group in EvaluatedItemsByName.Values)
1071 if (perBatchItemsByName != null)
1072 foreach (BuildItemGroup group in perBatchItemsByName.Values)
1075 if (commonItemsByName != null)
1076 foreach (BuildItemGroup group in commonItemsByName.Values)
1080 T GetFirst<T> (ICollection<T> list)
1085 foreach (T t in list)
1091 void LogWarning (string filename, string message, params object[] messageArgs)
1093 BuildWarningEventArgs bwea = new BuildWarningEventArgs (
1094 null, null, filename, 0, 0, 0, 0, String.Format (message, messageArgs),
1096 ParentEngine.EventSource.FireWarningRaised (this, bwea);
1099 static string ExtensionsPath {
1101 if (extensions_path == null) {
1102 // NOTE: code from mcs/tools/gacutil/driver.cs
1103 PropertyInfo gac = typeof (System.Environment).GetProperty (
1104 "GacPath", BindingFlags.Static | BindingFlags.NonPublic);
1107 MethodInfo get_gac = gac.GetGetMethod (true);
1108 string gac_path = (string) get_gac.Invoke (null, null);
1109 extensions_path = Path.GetFullPath (Path.Combine (
1110 gac_path, Path.Combine ("..", "xbuild")));
1113 return extensions_path;
1117 public BuildPropertyGroup EvaluatedProperties {
1119 if (needToReevaluate) {
1120 needToReevaluate = false;
1123 return evaluatedProperties;
1127 public string FullFileName {
1128 get { return fullFileName; }
1129 set { fullFileName = value; }
1132 public BuildPropertyGroup GlobalProperties {
1133 get { return globalProperties; }
1136 throw new ArgumentNullException ("value");
1139 throw new InvalidOperationException ("GlobalProperties can not be set to persisted property group.");
1141 globalProperties = value;
1142 NeedToReevaluate ();
1146 public bool IsDirty {
1147 get { return isDirty; }
1150 public bool IsValidated {
1151 get { return isValidated; }
1152 set { isValidated = value; }
1155 public BuildItemGroupCollection ItemGroups {
1156 get { return itemGroups; }
1159 public ImportCollection Imports {
1160 get { return imports; }
1163 public string InitialTargets {
1165 return xmlDocument.DocumentElement.GetAttribute ("InitialTargets");
1168 xmlDocument.DocumentElement.SetAttribute ("InitialTargets", value);
1169 initialTargets = value.Split (new char [] {';'}, StringSplitOptions.RemoveEmptyEntries);
1173 public Engine ParentEngine {
1174 get { return parentEngine; }
1177 public BuildPropertyGroupCollection PropertyGroups {
1178 get { return propertyGroups; }
1181 public string SchemaFile {
1182 get { return schemaFile; }
1183 set { schemaFile = value; }
1186 public TargetCollection Targets {
1187 get { return targets; }
1190 public DateTime TimeOfLastDirty {
1191 get { return timeOfLastDirty; }
1194 public UsingTaskCollection UsingTasks {
1195 get { return usingTasks; }
1200 get { return xmlDocument.InnerXml; }
1203 internal List<string> BuiltTargetKeys {
1204 get { return builtTargetKeys; }
1207 internal Dictionary <string, BuildItemGroup> LastItemGroupContaining {
1208 get { return last_item_group_containing; }
1211 internal static XmlNamespaceManager XmlNamespaceManager {
1213 if (manager == null) {
1214 manager = new XmlNamespaceManager (new NameTable ());
1215 manager.AddNamespace ("tns", ns);
1222 internal TaskDatabase TaskDatabase {
1223 get { return taskDatabase; }
1226 internal XmlDocument XmlDocument {
1227 get { return xmlDocument; }
1230 internal static string XmlNamespace {