2 // Target.cs: Represents a target.
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;
34 using Microsoft.Build.Framework;
35 using Microsoft.Build.Utilities;
37 namespace Microsoft.Build.BuildEngine {
38 public class Target : IEnumerable {
40 TargetBatchingImpl batchingImpl;
41 BuildState buildState;
43 ImportedProject importedProject;
46 XmlElement targetElement;
47 List <XmlElement> onErrorElements;
48 List <BuildTask> buildTasks;
50 internal Target (XmlElement targetElement, Project project, ImportedProject importedProject)
53 throw new ArgumentNullException ("project");
54 if (targetElement == null)
55 throw new ArgumentNullException ("targetElement");
57 this.targetElement = targetElement;
58 this.name = targetElement.GetAttribute ("Name");
60 this.project = project;
61 this.engine = project.ParentEngine;
62 this.importedProject = importedProject;
64 this.onErrorElements = new List <XmlElement> ();
65 this.buildState = BuildState.NotStarted;
66 this.buildTasks = new List <BuildTask> ();
67 this.batchingImpl = new TargetBatchingImpl (project, this.targetElement);
69 bool onErrorFound = false;
70 foreach (XmlNode xn in targetElement.ChildNodes) {
71 if (xn is XmlElement) {
72 XmlElement xe = (XmlElement) xn;
73 if (xe.Name == "OnError") {
74 onErrorElements.Add (xe);
76 } else if (onErrorFound)
77 throw new InvalidProjectFileException (
78 "The element <OnError> must be last under element <Target>. Found element <Error> instead.");
80 buildTasks.Add (new BuildTask (xe, this));
86 public BuildTask AddNewTask (string taskName)
89 throw new ArgumentNullException ("taskName");
91 XmlElement task = project.XmlDocument.CreateElement (taskName, Project.XmlNamespace);
92 targetElement.AppendChild (task);
93 BuildTask bt = new BuildTask (task, this);
99 public IEnumerator GetEnumerator ()
101 foreach (BuildTask bt in buildTasks)
105 // FIXME: shouldn't we remove it from XML?
106 public void RemoveTask (BuildTask buildTask)
108 if (buildTask == null)
109 throw new ArgumentNullException ("buildTask");
110 buildTasks.Remove (buildTask);
118 internal bool Build (string built_targets_key)
120 bool executeOnErrors;
121 return Build (built_targets_key, out executeOnErrors);
124 bool Build (string built_targets_key, out bool executeOnErrors)
126 project.PushThisFileProperty (TargetFile);
128 return BuildActual (built_targets_key, out executeOnErrors);
130 project.PopThisFileProperty ();
134 bool BuildActual (string built_targets_key, out bool executeOnErrors)
137 executeOnErrors = false;
139 // built targets are keyed by the particular set of global
140 // properties. So, a different set could allow a target
142 built_targets_key = project.GetKeyForTarget (Name);
143 if (project.ParentEngine.BuiltTargetsOutputByName.ContainsKey (built_targets_key)) {
148 // Push a null/empty batch, effectively clearing it
149 project.PushBatch (null, null);
150 if (!ConditionParser.ParseAndEvaluate (Condition, Project)) {
151 LogMessage (MessageImportance.Low,
152 "Target {0} skipped due to false condition: {1}",
159 buildState = BuildState.Started;
162 result = BuildDependencies (out executeOnErrors) &&
163 BuildBeforeThisTargets (out executeOnErrors) &&
164 DoBuild (out executeOnErrors) && // deps & Before targets built fine, do main build
165 BuildAfterThisTargets (out executeOnErrors);
167 result = BuildDependencies (out executeOnErrors) && DoBuild (out executeOnErrors);
170 buildState = BuildState.Finished;
171 } catch (Exception e) {
172 LogError ("Error building target {0}: {1}", Name, e.ToString ());
178 project.ParentEngine.BuiltTargetsOutputByName [built_targets_key] = (ITaskItem[]) Outputs.Clone ();
183 bool BuildDependencies (out bool executeOnErrors)
185 executeOnErrors = false;
187 if (String.IsNullOrEmpty (DependsOnTargets))
190 var expr = new Expression ();
191 expr.Parse (DependsOnTargets, ParseOptions.AllowItemsNoMetadataAndSplit);
192 string [] targetNames = (string []) expr.ConvertTo (Project, typeof (string []));
194 bool result = BuildOtherTargets (targetNames,
195 tname => engine.LogError ("Target '{0}', a dependency of target '{1}', not found.",
197 out executeOnErrors);
198 if (!result && executeOnErrors)
205 bool BuildBeforeThisTargets (out bool executeOnErrors)
207 executeOnErrors = false;
208 bool result = BuildOtherTargets (BeforeThisTargets, null, out executeOnErrors);
209 if (!result && executeOnErrors)
215 bool BuildAfterThisTargets (out bool executeOnErrors)
217 executeOnErrors = false;
218 //missing_target handler not required as these are picked from actual target's
219 //"Before/AfterTargets attributes!
220 bool result = BuildOtherTargets (AfterThisTargets, null, out executeOnErrors);
221 if (!result && executeOnErrors)
228 bool BuildOtherTargets (IEnumerable<string> targetNames, Action<string> missing_target, out bool executeOnErrors)
230 executeOnErrors = false;
231 if (targetNames == null)
235 foreach (string target_name in targetNames) {
236 var t = project.Targets [target_name.Trim ()];
238 if (missing_target != null)
239 missing_target (target_name);
243 if (t.BuildState == BuildState.NotStarted)
244 if (!t.Build (null, out executeOnErrors))
247 if (t.BuildState == BuildState.Started)
248 throw new InvalidProjectFileException ("Cycle in target dependencies detected");
254 bool DoBuild (out bool executeOnErrors)
256 executeOnErrors = false;
259 if (BuildTasks.Count == 0)
264 result = batchingImpl.Build (this, out executeOnErrors);
265 } catch (Exception e) {
266 LogError ("Error building target {0}: {1}", Name, e.Message);
267 LogMessage (MessageImportance.Low, "Error building target {0}: {1}", Name, e.ToString ());
271 if (executeOnErrors == true)
277 void ExecuteOnErrors ()
279 foreach (XmlElement onError in onErrorElements) {
280 if (onError.GetAttribute ("ExecuteTargets") == String.Empty)
281 throw new InvalidProjectFileException ("ExecuteTargets attribute is required in OnError element.");
283 string on_error_condition = onError.GetAttribute ("Condition");
284 if (!ConditionParser.ParseAndEvaluate (on_error_condition, Project)) {
285 LogMessage (MessageImportance.Low,
286 "OnError for target {0} skipped due to false condition: {1}",
287 Name, on_error_condition);
291 string[] targetsToExecute = onError.GetAttribute ("ExecuteTargets").Split (';');
292 foreach (string t in targetsToExecute)
293 this.project.Targets [t].Build ();
297 void LogTargetSkipped ()
299 BuildMessageEventArgs bmea;
300 bmea = new BuildMessageEventArgs (String.Format (
301 "Target {0} skipped, as it has already been built.", Name),
302 null, null, MessageImportance.Low);
304 project.ParentEngine.EventSource.FireMessageRaised (this, bmea);
307 void LogError (string message, params object [] messageArgs)
310 throw new ArgumentException ("message");
312 BuildErrorEventArgs beea = new BuildErrorEventArgs (
313 null, null, null, 0, 0, 0, 0, String.Format (message, messageArgs),
315 engine.EventSource.FireErrorRaised (this, beea);
318 void LogMessage (MessageImportance importance, string message, params object [] messageArgs)
321 throw new ArgumentNullException ("message");
323 BuildMessageEventArgs bmea = new BuildMessageEventArgs (
324 String.Format (message, messageArgs), null,
326 engine.EventSource.FireMessageRaised (this, bmea);
329 public string Condition {
330 get { return targetElement.GetAttribute ("Condition"); }
331 set { targetElement.SetAttribute ("Condition", value); }
334 public string DependsOnTargets {
335 get { return targetElement.GetAttribute ("DependsOnTargets"); }
336 set { targetElement.SetAttribute ("DependsOnTargets", value); }
339 public bool IsImported {
340 get { return importedProject != null; }
347 internal Project Project {
348 get { return project; }
351 internal string TargetFile {
353 if (importedProject != null)
354 return importedProject.FullFileName;
355 return project != null ? project.FullFileName : String.Empty;
360 internal string BeforeTargets {
361 get { return targetElement.GetAttribute ("BeforeTargets"); }
364 internal string AfterTargets {
365 get { return targetElement.GetAttribute ("AfterTargets"); }
368 internal List<string> BeforeThisTargets { get; set; }
369 internal List<string> AfterThisTargets { get; set; }
372 internal List<BuildTask> BuildTasks {
373 get { return buildTasks; }
376 internal Engine Engine {
377 get { return engine; }
380 internal BuildState BuildState {
381 get { return buildState; }
384 internal ITaskItem [] Outputs {
386 string outputs = targetElement.GetAttribute ("Outputs");
387 if (outputs == String.Empty)
388 return new ITaskItem [0];
390 Expression e = new Expression ();
391 e.Parse (outputs, ParseOptions.AllowItemsNoMetadataAndSplit);
393 return (ITaskItem []) e.ConvertTo (project, typeof (ITaskItem []));
398 internal enum BuildState {