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, IDictionary targetOutputs)
319 throw new ArgumentException ("targetNames cannot contain null strings");
321 if (!targets.Exists (target)) {
323 Console.WriteLine ("Target named '{0}' not found in the project.", target);
327 // built targets are keyed by the particular set of global
328 // properties. So, a different set could allow a target
330 string key = fullFileName + ":" + target + ":" + GlobalPropertiesToString (GlobalProperties);
332 if (ParentEngine.BuiltTargetsOutputByName.TryGetValue (key, out outputs)) {
333 if (targetOutputs != null)
334 targetOutputs.Add (target, outputs);
335 LogTargetSkipped (target);
339 if (!targets [target].Build ())
342 ParentEngine.BuiltTargetsOutputByName [key] = (ITaskItem[]) targets [target].Outputs.Clone ();
343 builtTargetKeys.Add (key);
344 if (targetOutputs != null)
345 targetOutputs.Add (target, targets [target].Outputs);
350 string GlobalPropertiesToString (BuildPropertyGroup bgp)
352 StringBuilder sb = new StringBuilder ();
353 foreach (BuildProperty bp in bgp)
354 sb.AppendFormat (" {0}:{1}", bp.Name, bp.FinalValue);
355 return sb.ToString ();
359 public string [] GetConditionedPropertyValues (string propertyName)
361 if (conditionedProperties.ContainsKey (propertyName))
362 return conditionedProperties [propertyName].ToArray ();
364 return new string [0];
367 public BuildItemGroup GetEvaluatedItemsByName (string itemName)
369 if (needToReevaluate) {
370 needToReevaluate = false;
374 if (evaluatedItemsByName.ContainsKey (itemName))
375 return evaluatedItemsByName [itemName];
377 return new BuildItemGroup (this);
380 public BuildItemGroup GetEvaluatedItemsByNameIgnoringCondition (string itemName)
382 if (needToReevaluate) {
383 needToReevaluate = false;
387 if (evaluatedItemsByNameIgnoringCondition.ContainsKey (itemName))
388 return evaluatedItemsByNameIgnoringCondition [itemName];
390 return new BuildItemGroup (this);
393 public string GetEvaluatedProperty (string propertyName)
395 if (needToReevaluate) {
396 needToReevaluate = false;
400 if (propertyName == null)
401 throw new ArgumentNullException ("propertyName");
403 BuildProperty bp = evaluatedProperties [propertyName];
405 return bp == null ? null : (string) bp;
408 [MonoTODO ("We should remember that node and not use XPath to get it")]
409 public string GetProjectExtensions (string id)
411 if (id == null || id == String.Empty)
414 XmlNode node = xmlDocument.SelectSingleNode (String.Format ("/tns:Project/tns:ProjectExtensions/tns:{0}", id), XmlNamespaceManager);
419 return node.InnerXml;
423 public void Load (string projectFileName)
425 this.fullFileName = Utilities.FromMSBuildPath (Path.GetFullPath (projectFileName));
427 string filename = fullFileName;
428 if (String.Compare (Path.GetExtension (fullFileName), ".sln", true) == 0) {
429 Project tmp_project = ParentEngine.CreateNewProject ();
430 SolutionParser sln_parser = new SolutionParser ();
431 sln_parser.ParseSolution (fullFileName, tmp_project, delegate (int errorNumber, string message) {
432 LogWarning (filename, message);
434 filename = fullFileName + ".proj";
435 tmp_project.Save (filename);
436 ParentEngine.RemoveLoadedProject (tmp_project);
439 DoLoad (new StreamReader (filename));
442 [MonoTODO ("Not tested")]
443 public void Load (TextReader textReader)
445 fullFileName = String.Empty;
449 public void LoadXml (string projectXml)
451 fullFileName = String.Empty;
452 DoLoad (new StringReader (projectXml));
453 MarkProjectAsDirty ();
457 public void MarkProjectAsDirty ()
460 timeOfLastDirty = DateTime.Now;
463 [MonoTODO ("Not tested")]
464 public void RemoveAllItemGroups ()
466 int length = ItemGroups.Count;
467 BuildItemGroup [] groups = new BuildItemGroup [length];
468 ItemGroups.CopyTo (groups, 0);
470 for (int i = 0; i < length; i++)
471 RemoveItemGroup (groups [i]);
473 MarkProjectAsDirty ();
477 [MonoTODO ("Not tested")]
478 public void RemoveAllPropertyGroups ()
480 int length = PropertyGroups.Count;
481 BuildPropertyGroup [] groups = new BuildPropertyGroup [length];
482 PropertyGroups.CopyTo (groups, 0);
484 for (int i = 0; i < length; i++)
485 RemovePropertyGroup (groups [i]);
487 MarkProjectAsDirty ();
492 public void RemoveItem (BuildItem itemToRemove)
494 if (itemToRemove == null)
495 throw new ArgumentNullException ("itemToRemove");
497 if (!itemToRemove.FromXml && !itemToRemove.HasParentItem)
498 throw new InvalidOperationException ("The object passed in is not part of the project.");
500 BuildItemGroup big = itemToRemove.ParentItemGroup;
502 if (big.Count == 1) {
503 // ParentItemGroup for items from xml and that have parent is the same
504 groupingCollection.Remove (big);
506 if (big.ParentProject != this)
507 throw new InvalidOperationException ("The object passed in is not part of the project.");
509 if (itemToRemove.FromXml)
510 big.RemoveItem (itemToRemove);
512 big.RemoveItem (itemToRemove.ParentItem);
515 MarkProjectAsDirty ();
519 [MonoTODO ("Not tested")]
520 public void RemoveItemGroup (BuildItemGroup itemGroupToRemove)
522 if (itemGroupToRemove == null)
523 throw new ArgumentNullException ("itemGroupToRemove");
525 groupingCollection.Remove (itemGroupToRemove);
526 MarkProjectAsDirty ();
530 // NOTE: does not modify imported projects
531 public void RemoveItemGroupsWithMatchingCondition (string matchingCondition)
533 throw new NotImplementedException ();
537 public void RemoveItemsByName (string itemName)
539 if (itemName == null)
540 throw new ArgumentNullException ("itemName");
542 throw new NotImplementedException ();
545 [MonoTODO ("Not tested")]
546 public void RemovePropertyGroup (BuildPropertyGroup propertyGroupToRemove)
548 if (propertyGroupToRemove == null)
549 throw new ArgumentNullException ("propertyGroupToRemove");
551 groupingCollection.Remove (propertyGroupToRemove);
552 MarkProjectAsDirty ();
556 // NOTE: does not modify imported projects
557 public void RemovePropertyGroupsWithMatchingCondition (string matchCondition)
559 throw new NotImplementedException ();
563 public void ResetBuildStatus ()
565 // hack to allow built targets to be removed
571 public void Save (string projectFileName)
573 Save (projectFileName, Encoding.Default);
577 [MonoTODO ("Ignores encoding")]
578 public void Save (string projectFileName, Encoding encoding)
580 xmlDocument.Save (projectFileName);
584 public void Save (TextWriter outTextWriter)
586 xmlDocument.Save (outTextWriter);
590 public void SetImportedProperty (string propertyName,
591 string propertyValue,
593 Project importProject)
595 SetImportedProperty (propertyName, propertyValue, condition, importProject,
596 PropertyPosition.UseExistingOrCreateAfterLastPropertyGroup);
599 public void SetImportedProperty (string propertyName,
600 string propertyValue,
602 Project importedProject,
603 PropertyPosition position)
605 SetImportedProperty (propertyName, propertyValue, condition, importedProject,
606 PropertyPosition.UseExistingOrCreateAfterLastPropertyGroup, false);
610 public void SetImportedProperty (string propertyName,
611 string propertyValue,
613 Project importedProject,
614 PropertyPosition position,
615 bool treatPropertyValueAsLiteral)
617 throw new NotImplementedException ();
620 public void SetProjectExtensions (string id, string xmlText)
623 throw new ArgumentNullException ("id");
625 throw new ArgumentNullException ("xmlText");
627 XmlNode projectExtensions, node;
629 projectExtensions = xmlDocument.SelectSingleNode ("/tns:Project/tns:ProjectExtensions", XmlNamespaceManager);
631 if (projectExtensions == null) {
632 projectExtensions = xmlDocument.CreateElement ("ProjectExtensions", XmlNamespace);
633 xmlDocument.DocumentElement.AppendChild (projectExtensions);
635 node = xmlDocument.CreateElement (id, XmlNamespace);
636 node.InnerXml = xmlText;
637 projectExtensions.AppendChild (node);
639 node = xmlDocument.SelectSingleNode (String.Format ("/tns:Project/tns:ProjectExtensions/tns:{0}", id), XmlNamespaceManager);
642 node = xmlDocument.CreateElement (id, XmlNamespace);
643 projectExtensions.AppendChild (node);
646 node.InnerXml = xmlText;
650 MarkProjectAsDirty ();
653 public void SetProperty (string propertyName,
654 string propertyValue)
656 SetProperty (propertyName, propertyValue, "true",
657 PropertyPosition.UseExistingOrCreateAfterLastPropertyGroup, false);
660 public void SetProperty (string propertyName,
661 string propertyValue,
664 SetProperty (propertyName, propertyValue, condition,
665 PropertyPosition.UseExistingOrCreateAfterLastPropertyGroup);
668 public void SetProperty (string propertyName,
669 string propertyValue,
671 PropertyPosition position)
673 SetProperty (propertyName, propertyValue, condition,
674 PropertyPosition.UseExistingOrCreateAfterLastPropertyGroup, false);
678 public void SetProperty (string propertyName,
679 string propertyValue,
681 PropertyPosition position,
682 bool treatPropertyValueAsLiteral)
684 throw new NotImplementedException ();
687 internal void Unload ()
692 internal void CheckUnloaded ()
695 throw new InvalidOperationException ("This project object has been unloaded from the MSBuild engine and is no longer valid.");
698 internal void NeedToReevaluate ()
700 needToReevaluate = true;
703 // Does the actual loading.
704 void DoLoad (TextReader textReader)
707 ParentEngine.RemoveLoadedProject (this);
709 XmlReaderSettings settings = new XmlReaderSettings ();
711 if (SchemaFile != null) {
712 settings.Schemas.Add (null, SchemaFile);
713 settings.ValidationType = ValidationType.Schema;
714 settings.ValidationEventHandler += new ValidationEventHandler (ValidationCallBack);
717 XmlReader xmlReader = XmlReader.Create (textReader, settings);
718 xmlDocument.Load (xmlReader);
720 if (xmlDocument.DocumentElement.Name != "Project") {
721 throw new InvalidProjectFileException (String.Format (
722 "The element <{0}> is unrecognized, or not supported in this context.", xmlDocument.DocumentElement.Name));
725 if (xmlDocument.DocumentElement.GetAttribute ("xmlns") != ns) {
726 throw new InvalidProjectFileException (
727 @"The default XML namespace of the project must be the MSBuild XML namespace." +
728 " If the project is authored in the MSBuild 2003 format, please add " +
729 "xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\" to the <Project> element. " +
730 "If the project has been authored in the old 1.0 or 1.2 format, please convert it to MSBuild 2003 format. ");
733 ParentEngine.AddLoadedProject (this);
734 } catch (Exception e) {
735 throw new InvalidProjectFileException (String.Format ("{0}: {1}",
736 fullFileName, e.Message), e);
738 if (textReader != null)
750 groupingCollection = new GroupingCollection (this);
751 imports = new ImportCollection (groupingCollection);
752 usingTasks = new UsingTaskCollection (this);
753 itemGroups = new BuildItemGroupCollection (groupingCollection);
754 propertyGroups = new BuildPropertyGroupCollection (groupingCollection);
755 targets = new TargetCollection (this);
756 last_item_group_containing = new Dictionary <string, BuildItemGroup> ();
758 taskDatabase = new TaskDatabase ();
759 if (ParentEngine.DefaultTasksRegistered)
760 taskDatabase.CopyTasks (ParentEngine.DefaultTasks);
762 if (xmlDocument.DocumentElement.GetAttributeNode ("DefaultTargets") != null)
763 defaultTargets = xmlDocument.DocumentElement.GetAttribute ("DefaultTargets").Split (';');
765 defaultTargets = new string [0];
767 ProcessProjectAttributes (xmlDocument.DocumentElement.Attributes);
768 ProcessElements (xmlDocument.DocumentElement, null);
774 void ProcessProjectAttributes (XmlAttributeCollection attributes)
776 foreach (XmlAttribute attr in attributes) {
778 case "InitialTargets":
779 initialTargets = attr.Value.Split (new char [] {';'},
780 StringSplitOptions.RemoveEmptyEntries);
782 case "DefaultTargets":
783 defaultTargets = attr.Value.Split (new char [] {';'},
784 StringSplitOptions.RemoveEmptyEntries);
790 internal void ProcessElements (XmlElement rootElement, ImportedProject ip)
792 foreach (XmlNode xn in rootElement.ChildNodes) {
793 if (xn is XmlElement) {
794 XmlElement xe = (XmlElement) xn;
796 case "ProjectExtensions":
797 AddProjectExtensions (xe);
808 AddUsingTask (xe, ip);
814 AddItemGroup (xe, ip);
816 case "PropertyGroup":
817 AddPropertyGroup (xe, ip);
823 throw new InvalidProjectFileException ("Invalid element in project file.");
831 evaluatedItems = new BuildItemGroup (null, this, null, true);
832 evaluatedItemsIgnoringCondition = new BuildItemGroup (null, this, null, true);
833 evaluatedItemsByName = new Dictionary <string, BuildItemGroup> (StringComparer.InvariantCultureIgnoreCase);
834 evaluatedItemsByNameIgnoringCondition = new Dictionary <string, BuildItemGroup> (StringComparer.InvariantCultureIgnoreCase);
835 if (building && current_settings == BuildSettings.None)
836 RemoveBuiltTargets ();
838 InitializeProperties ();
840 groupingCollection.Evaluate ();
842 //FIXME: UsingTasks aren't really evaluated. (shouldn't use expressions or anything)
843 foreach (UsingTask usingTask in UsingTasks)
844 usingTask.Evaluate ();
847 // Removes entries of all earlier built targets for this project
848 void RemoveBuiltTargets ()
850 foreach (string key in builtTargetKeys)
851 ParentEngine.BuiltTargetsOutputByName.Remove (key);
854 void InitializeProperties ()
858 evaluatedProperties = new BuildPropertyGroup (null, null, null, true);
860 foreach (BuildProperty gp in GlobalProperties) {
861 bp = new BuildProperty (gp.Name, gp.Value, PropertyType.Global);
862 EvaluatedProperties.AddProperty (bp);
865 foreach (BuildProperty gp in GlobalProperties)
866 ParentEngine.GlobalProperties.AddProperty (gp);
868 // add properties that we dont have from parent engine's
870 foreach (BuildProperty gp in ParentEngine.GlobalProperties) {
871 if (EvaluatedProperties [gp.Name] == null) {
872 bp = new BuildProperty (gp.Name, gp.Value, PropertyType.Global);
873 EvaluatedProperties.AddProperty (bp);
877 foreach (DictionaryEntry de in Environment.GetEnvironmentVariables ()) {
878 bp = new BuildProperty ((string) de.Key, (string) de.Value, PropertyType.Environment);
879 EvaluatedProperties.AddProperty (bp);
882 EvaluatedProperties.AddProperty (new BuildProperty ("MSBuildProjectFile", Path.GetFileName (fullFileName),
883 PropertyType.Reserved));
884 EvaluatedProperties.AddProperty (new BuildProperty ("MSBuildProjectName",
885 Path.GetFileNameWithoutExtension (fullFileName),
886 PropertyType.Reserved));
887 EvaluatedProperties.AddProperty (new BuildProperty ("MSBuildBinPath", parentEngine.BinPath, PropertyType.Reserved));
888 EvaluatedProperties.AddProperty (new BuildProperty ("MSBuildToolsPath", parentEngine.BinPath, PropertyType.Reserved));
889 EvaluatedProperties.AddProperty (new BuildProperty ("MSBuildExtensionsPath", ExtensionsPath, PropertyType.Reserved));
891 // FIXME: make some internal method that will work like GetDirectoryName but output String.Empty on null/String.Empty
893 if (FullFileName == String.Empty)
894 projectDir = Environment.CurrentDirectory;
896 projectDir = Path.GetDirectoryName (FullFileName);
898 EvaluatedProperties.AddProperty (new BuildProperty ("MSBuildProjectDirectory", projectDir, PropertyType.Reserved));
901 void AddProjectExtensions (XmlElement xmlElement)
905 void AddMessage (XmlElement xmlElement)
909 void AddTarget (XmlElement xmlElement, ImportedProject importedProject)
911 Target target = new Target (xmlElement, this, importedProject);
912 targets.AddTarget (target);
914 if (firstTargetName == null)
915 firstTargetName = target.Name;
918 void AddUsingTask (XmlElement xmlElement, ImportedProject importedProject)
922 usingTask = new UsingTask (xmlElement, this, importedProject);
923 UsingTasks.Add (usingTask);
926 void AddImport (XmlElement xmlElement, ImportedProject importingProject)
930 import = new Import (xmlElement, this, importingProject);
931 Imports.Add (import);
934 void AddItemGroup (XmlElement xmlElement, ImportedProject importedProject)
936 BuildItemGroup big = new BuildItemGroup (xmlElement, this, importedProject, false);
937 ItemGroups.Add (big);
940 void AddPropertyGroup (XmlElement xmlElement, ImportedProject importedProject)
942 BuildPropertyGroup bpg = new BuildPropertyGroup (xmlElement, this, importedProject, false);
943 PropertyGroups.Add (bpg);
946 void AddChoose (XmlElement xmlElement)
948 BuildChoose bc = new BuildChoose (xmlElement, this);
949 groupingCollection.Add (bc);
952 static void ValidationCallBack (object sender, ValidationEventArgs e)
954 Console.WriteLine ("Validation Error: {0}", e.Message);
957 public bool BuildEnabled {
962 buildEnabled = value;
967 public Encoding Encoding {
968 get { return encoding; }
971 public string DefaultTargets {
973 return xmlDocument.DocumentElement.GetAttribute ("DefaultTargets");
976 xmlDocument.DocumentElement.SetAttribute ("DefaultTargets", value);
977 defaultTargets = value.Split (new char [] {';'}, StringSplitOptions.RemoveEmptyEntries);
981 public BuildItemGroup EvaluatedItems {
983 if (needToReevaluate) {
984 needToReevaluate = false;
987 return evaluatedItems;
991 public BuildItemGroup EvaluatedItemsIgnoringCondition {
993 if (needToReevaluate) {
994 needToReevaluate = false;
997 return evaluatedItemsIgnoringCondition;
1001 internal IDictionary <string, BuildItemGroup> EvaluatedItemsByName {
1003 // FIXME: do we need to do this here?
1004 if (needToReevaluate) {
1005 needToReevaluate = false;
1008 return evaluatedItemsByName;
1012 internal IDictionary <string, BuildItemGroup> EvaluatedItemsByNameIgnoringCondition {
1014 // FIXME: do we need to do this here?
1015 if (needToReevaluate) {
1016 needToReevaluate = false;
1019 return evaluatedItemsByNameIgnoringCondition;
1023 // For batching implementation
1024 Dictionary<string, BuildItemGroup> perBatchItemsByName;
1025 Dictionary<string, BuildItemGroup> commonItemsByName;
1027 internal void SetBatchedItems (Dictionary<string, BuildItemGroup> perBatchItemsByName, Dictionary<string, BuildItemGroup> commonItemsByName)
1029 this.perBatchItemsByName = perBatchItemsByName;
1030 this.commonItemsByName = commonItemsByName;
1034 internal bool TryGetEvaluatedItemByNameBatched (string itemName, out BuildItemGroup group)
1036 if (perBatchItemsByName == null && commonItemsByName == null)
1037 return EvaluatedItemsByName.TryGetValue (itemName, out group);
1039 if (perBatchItemsByName != null)
1040 return perBatchItemsByName.TryGetValue (itemName, out group);
1042 if (commonItemsByName != null)
1043 return commonItemsByName.TryGetValue (itemName, out group);
1049 internal string GetMetadataBatched (string itemName, string metadataName)
1051 BuildItemGroup group = null;
1052 if (itemName == null) {
1053 //unqualified, all items in a batch(bucket) have the
1054 //same metadata values
1055 group = GetFirst<BuildItemGroup> (perBatchItemsByName.Values);
1057 group = GetFirst<BuildItemGroup> (commonItemsByName.Values);
1060 TryGetEvaluatedItemByNameBatched (itemName, out group);
1063 if (group != null) {
1064 foreach (BuildItem item in group) {
1065 if (item.HasMetadata (metadataName))
1066 return item.GetMetadata (metadataName);
1069 return String.Empty;
1072 internal IEnumerable<BuildItemGroup> GetAllItemGroups ()
1074 if (perBatchItemsByName == null && commonItemsByName == null)
1075 foreach (BuildItemGroup group in EvaluatedItemsByName.Values)
1078 if (perBatchItemsByName != null)
1079 foreach (BuildItemGroup group in perBatchItemsByName.Values)
1082 if (commonItemsByName != null)
1083 foreach (BuildItemGroup group in commonItemsByName.Values)
1087 T GetFirst<T> (ICollection<T> list)
1092 foreach (T t in list)
1098 void LogTargetSkipped (string targetName)
1100 BuildMessageEventArgs bmea;
1101 bmea = new BuildMessageEventArgs (String.Format (
1102 "Target {0} skipped, as it has already been built.", targetName),
1103 null, null, MessageImportance.Low);
1105 ParentEngine.EventSource.FireMessageRaised (this, bmea);
1108 void LogWarning (string filename, string message, params object[] messageArgs)
1110 BuildWarningEventArgs bwea = new BuildWarningEventArgs (
1111 null, null, filename, 0, 0, 0, 0, String.Format (message, messageArgs),
1113 ParentEngine.EventSource.FireWarningRaised (this, bwea);
1116 static string ExtensionsPath {
1118 if (extensions_path == null) {
1119 // NOTE: code from mcs/tools/gacutil/driver.cs
1120 PropertyInfo gac = typeof (System.Environment).GetProperty (
1121 "GacPath", BindingFlags.Static | BindingFlags.NonPublic);
1124 MethodInfo get_gac = gac.GetGetMethod (true);
1125 string gac_path = (string) get_gac.Invoke (null, null);
1126 extensions_path = Path.GetFullPath (Path.Combine (
1127 gac_path, Path.Combine ("..", "xbuild")));
1130 return extensions_path;
1134 public BuildPropertyGroup EvaluatedProperties {
1136 if (needToReevaluate) {
1137 needToReevaluate = false;
1140 return evaluatedProperties;
1144 public string FullFileName {
1145 get { return fullFileName; }
1146 set { fullFileName = value; }
1149 public BuildPropertyGroup GlobalProperties {
1150 get { return globalProperties; }
1153 throw new ArgumentNullException ("value");
1156 throw new InvalidOperationException ("GlobalProperties can not be set to persisted property group.");
1158 globalProperties = value;
1159 NeedToReevaluate ();
1163 public bool IsDirty {
1164 get { return isDirty; }
1167 public bool IsValidated {
1168 get { return isValidated; }
1169 set { isValidated = value; }
1172 public BuildItemGroupCollection ItemGroups {
1173 get { return itemGroups; }
1176 public ImportCollection Imports {
1177 get { return imports; }
1180 public string InitialTargets {
1182 return xmlDocument.DocumentElement.GetAttribute ("InitialTargets");
1185 xmlDocument.DocumentElement.SetAttribute ("InitialTargets", value);
1186 initialTargets = value.Split (new char [] {';'}, StringSplitOptions.RemoveEmptyEntries);
1190 public Engine ParentEngine {
1191 get { return parentEngine; }
1194 public BuildPropertyGroupCollection PropertyGroups {
1195 get { return propertyGroups; }
1198 public string SchemaFile {
1199 get { return schemaFile; }
1200 set { schemaFile = value; }
1203 public TargetCollection Targets {
1204 get { return targets; }
1207 public DateTime TimeOfLastDirty {
1208 get { return timeOfLastDirty; }
1211 public UsingTaskCollection UsingTasks {
1212 get { return usingTasks; }
1217 get { return xmlDocument.InnerXml; }
1220 internal Dictionary <string, BuildItemGroup> LastItemGroupContaining {
1221 get { return last_item_group_containing; }
1224 internal static XmlNamespaceManager XmlNamespaceManager {
1226 if (manager == null) {
1227 manager = new XmlNamespaceManager (new NameTable ());
1228 manager.AddNamespace ("tns", ns);
1235 internal TaskDatabase TaskDatabase {
1236 get { return taskDatabase; }
1239 internal XmlDocument XmlDocument {
1240 get { return xmlDocument; }
1243 internal static string XmlNamespace {