2007-01-12 Marek Sieradzki <marek.sieradzki@gmail.com>
[mono.git] / mcs / class / Microsoft.Build.Engine / Microsoft.Build.BuildEngine / Target.cs
1 //
2 // Target.cs: Represents a target.
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.Xml;
34 using Microsoft.Build.Framework;
35
36 namespace Microsoft.Build.BuildEngine {
37         public class Target : IEnumerable {
38         
39                 BatchingImpl    batchingImpl;
40                 BuildState      buildState;
41                 Engine          engine;
42                 ImportedProject importedProject;
43                 string          name;
44                 Project         project;
45                 XmlElement      targetElement;
46                 List <XmlElement>       onErrorElements;
47                 List <BuildTask>        buildTasks;
48                 
49                 internal Target (XmlElement targetElement, Project project, ImportedProject importedProject)
50                 {
51                         if (project == null)
52                                 throw new ArgumentNullException ("project");
53                         if (targetElement == null)
54                                 throw new ArgumentNullException ("targetElement");
55
56                         this.targetElement = targetElement;
57                         this.name = targetElement.GetAttribute ("Name");
58
59                         this.project = project;
60                         this.engine = project.ParentEngine;
61                         this.importedProject = importedProject;
62
63                         this.onErrorElements  = new List <XmlElement> ();
64                         this.buildState = BuildState.NotStarted;
65                         this.buildTasks = new List <BuildTask> ();
66                         this.batchingImpl = new BatchingImpl (project, this.targetElement);
67
68                         bool onErrorFound = false;
69                         foreach (XmlNode xn in targetElement.ChildNodes) {
70                                 if (xn is XmlElement) {
71                                         XmlElement xe = (XmlElement) xn;
72                                         if (xe.Name == "OnError") {
73                                                 onErrorElements.Add (xe);
74                                                 onErrorFound = true;
75                                         } else if (onErrorFound)
76                                                 throw new InvalidProjectFileException (
77                                                         "The element <OnError> must be last under element <Target>. Found element <Error> instead.");
78                                         else
79                                                 buildTasks.Add (new BuildTask (xe, this));
80                                 }
81                         }
82                 }
83                 
84                 [MonoTODO]
85                 public BuildTask AddNewTask (string taskName)
86                 {
87                         if (taskName == null)
88                                 throw new ArgumentNullException ("taskName");
89                 
90                         XmlElement task = project.XmlDocument.CreateElement (taskName, Project.XmlNamespace);
91                         targetElement.AppendChild (task);
92                         BuildTask bt = new BuildTask (task, this);
93                         buildTasks.Add (bt);
94                         
95                         return bt;
96                 }
97
98                 public IEnumerator GetEnumerator ()
99                 {
100                         foreach (BuildTask bt in buildTasks)
101                                 yield return bt;
102                 }
103
104                 // FIXME: shouldn't we remove it from XML?
105                 public void RemoveTask (BuildTask buildTask)
106                 {
107                         if (buildTask == null)
108                                 throw new ArgumentNullException ("buildTask");
109                         buildTasks.Remove (buildTask);
110                 }
111                 
112                 // FIXME: log errors instead of throwing exceptions
113                 internal bool Build ()
114                 {
115                         bool result = true;
116                 
117                         try {
118                                 buildState = BuildState.Started;
119
120                                 if (DependsOnTargets != String.Empty) {
121                                         Expression dependencies = new Expression ();
122                                         dependencies.Parse (DependsOnTargets);
123                                         
124                                         string[] targetsToBuildFirst = (string[]) dependencies.ConvertTo (Project, typeof (string[]));
125                                         foreach (string target in targetsToBuildFirst) {
126                                                 string trimmed = target.Trim ();
127                                                 Target t = (Target) project.Targets [trimmed];
128                                                 if (t == null)
129                                                         throw new InvalidProjectFileException (String.Format ("Target {0} not found.", trimmed));
130                                                 if (t.BuildState == BuildState.NotStarted) {
131                                                         if (!t.Build ()) {
132                                                                 result = false;
133                                                                 break;
134                                                         }
135
136                                                 }
137                                                 if (t.BuildState == BuildState.Started)
138                                                         throw new InvalidProjectFileException ("Cycle in target dependencies detected.");
139                                         }
140                                 }
141                         
142                                 if (result)
143                                         result = DoBuild ();
144                         } catch (Exception) {
145                                 return false;
146                         } finally {
147                                 buildState = BuildState.Finished;
148                         }
149                         
150                         return result;
151                 }
152                 
153                 bool DoBuild ()
154                 {
155                         bool executeOnErrors = false;
156                         bool result = true;
157                 
158                         LogTargetStarted ();
159                         
160                         if (batchingImpl.BuildNeeded ()) {
161                                 foreach (BuildTask bt in buildTasks) {
162                                         result = batchingImpl.BatchBuildTask (bt);
163                                 
164                                         if (!result && !bt.ContinueOnError) {
165                                                 executeOnErrors = true;
166                                                 break;
167                                         }
168                                 }
169                         } else {
170                                 LogTargetSkipped ();
171                         }
172
173                         LogTargetFinished (result);
174                         
175                         if (executeOnErrors == true)
176                                 ExecuteOnErrors ();
177                                 
178                         return result;
179                 }
180                 
181                 void ExecuteOnErrors ()
182                 {
183                         foreach (XmlElement onError in onErrorElements) {
184                                 // FIXME: add condition
185                                 if (onError.GetAttribute ("ExecuteTargets") == String.Empty)
186                                         throw new InvalidProjectFileException ("ExecuteTargets attribute is required in OnError element.");
187                                 string[] targetsToExecute = onError.GetAttribute ("ExecuteTargets").Split (';');
188                                 foreach (string t in targetsToExecute)
189                                         this.project.Targets [t].Build ();
190                         }
191                 }
192
193                 void LogTargetSkipped ()
194                 {
195                         BuildMessageEventArgs bmea;
196                         bmea = new BuildMessageEventArgs (String.Format ("Skipping target \"{0}\" because its outputs are up-to-date.",
197                                 name), null, "MSBuild", MessageImportance.Normal);
198                         engine.EventSource.FireMessageRaised (this, bmea);
199                 }
200                 
201                 void LogTargetStarted ()
202                 {
203                         TargetStartedEventArgs tsea;
204                         string projectFile = project.FullFileName;
205                         tsea = new TargetStartedEventArgs ("Target " + name + " started.", null, name, projectFile, null);
206                         engine.EventSource.FireTargetStarted (this, tsea);
207                 }
208                 
209                 void LogTargetFinished (bool succeeded)
210                 {
211                         TargetFinishedEventArgs tfea;
212                         string projectFile = project.FullFileName;
213                         tfea = new TargetFinishedEventArgs ("Target " + name + " finished.", null, name, projectFile, null, succeeded);
214                         engine.EventSource.FireTargetFinished (this, tfea);
215                 }
216         
217                 public string Condition {
218                         get { return targetElement.GetAttribute ("Condition"); }
219                         set { targetElement.SetAttribute ("Condition", value); }
220                 }
221
222                 public string DependsOnTargets {
223                         get { return targetElement.GetAttribute ("DependsOnTargets"); }
224                         set { targetElement.SetAttribute ("DependsOnTargets", value); }
225                 }
226
227                 public bool IsImported {
228                         get { return importedProject != null; }
229                 }
230
231                 public string Name {
232                         get { return name; }
233                 }
234                 
235                 internal Project Project {
236                         get { return project; }
237                 }
238                 
239                 internal BuildState BuildState {
240                         get { return buildState; }
241                 }
242         }
243         
244         internal enum BuildState {
245                 NotStarted,
246                 Started,
247                 Finished,
248                 Skipped
249         }
250 }
251
252 #endif