Welcome to mirror list, hosted at ThFree Co, Russian Federation.

Project.cs « src « nant « mcs - github.com/mono/mono.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 9746dadcfdced2538132c58a31432c482022f49c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
// NAnt - A .NET build tool
// Copyright (C) 2001 Gerry Shaw
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
// Gerry Shaw (gerry_shaw@yahoo.com)
// Ian MacLean (ian_maclean@another.com)

namespace SourceForge.NAnt {

    using System;
    using System.IO;
    using System.Reflection;
    using System.Text.RegularExpressions;
    using System.Xml;
    using System.Xml.XPath;
    using System.Collections;
    using System.Collections.Specialized;

    /// <summary>
    /// Central representation of an NAnt project.
    /// </summary>
    public class Project {

        public static readonly string BuildFilePattern = "*.build";

        /// <summary>
        /// Finds the file name for the build file in the specified directory.
        /// </summary>
        /// <param name="directory">The directory to look for a build file.  When in doubt use Environment.CurrentDirectory for directory.</param>
        /// <returns>The path to the build file or <c>null</c> if no build file could be found.</returns>
        public static string FindBuildFileName(string directory) {
            string buildFileName = null;

            // find first file ending in .build
            DirectoryInfo directoryInfo = new DirectoryInfo(directory);
            FileInfo[] files = directoryInfo.GetFiles(BuildFilePattern);
            if (files.Length > 0) {
                buildFileName = Path.Combine(directory, files[0].Name);
            }
            return buildFileName;
        }

        string _name;
        string _defaultTargetName;
        string _baseDirectory;
        string _buildFileName;
        bool _verbose = false;

        StringCollection _buildTargets = new StringCollection();
        TaskCollection _tasks = new TaskCollection();
        TargetCollection _targets = new TargetCollection();
        XPathTextPositionMap _positionMap; // created when Xml document is loaded
        TaskFactory _taskFactory; // created in constructor
        PropertyDictionary _properties = new PropertyDictionary();

        public Project() {
            _taskFactory = new TaskFactory(this);
        }

        /// <summary>
        /// The name of the project.
        /// </summary>
        public string Name {
            get { return _name; }
            set { _name = value; }
        }

        public string BaseDirectory {
            get { return _baseDirectory; }
            set { _baseDirectory = value; }
        }

        public string BuildFileName {
            get { return _buildFileName; }
            set { _buildFileName = value; }
        }

        /// <summary>
        /// When true tasks should output more output.
        /// </summary>
        public bool Verbose {
            get { return _verbose; }
            set { _verbose = value; }
        }

        /// <summary>
        /// The list of targets to built.
        /// </summary>
        /// <remarks>
        /// Targets are built in the order they appear in the collection.  If
        /// the collection is empty the default target will be built.
        /// </remarks>
        public StringCollection BuildTargets {
            get { return _buildTargets; }
        }

        /// <summary>
        /// The list of tasks to perform before any targets executed.
        /// </summary>
        /// <remarks>
        /// Tasks are executed in the order they appear in the collection.
        /// </remarks>
        public TaskCollection Tasks {
            get { return _tasks; }
        }

        public PropertyDictionary Properties {
            get { return _properties; }
        }

        public TargetCollection Targets {
            get { return _targets; }
        }

        public bool Run() {
            bool buildResult = false;
            try {
                DateTime startTime = DateTime.Now;

                if (BaseDirectory == null) {
                    BaseDirectory = Environment.CurrentDirectory;
                }
                BaseDirectory = Path.GetFullPath(BaseDirectory);

                if (BuildFileName == null || BuildFileName == String.Empty) {
                    BuildFileName = FindBuildFileName(BaseDirectory);
                    if (BuildFileName == null) {
                        throw new BuildException(String.Format("Could not find a '{0}' file in '{1}'", BuildFilePattern, BaseDirectory));
                    }
                }

                Log.WriteLine("Buildfile: {0}", BuildFileName);
                if (Verbose) {
                    Log.WriteLine("Base Directory: {0}", BaseDirectory);
                }

                XmlDocument doc = new XmlDocument();
                try {
                    doc.Load(BuildFileName);
                    // TODO: validate against xsd schema
                } catch (XmlException e) {
                    throw new BuildException(String.Format("Could not load '{0}'", BuildFileName), e);
                }

                Initialize(doc);
                Properties.Add("nant.buildfile", BuildFileName);

                Execute();

                Log.WriteLine();
                Log.WriteLine("BUILD SUCCEEDED");

                TimeSpan buildTime = DateTime.Now - startTime;
                Log.WriteLine();
                Log.WriteLine("Total time: {0} seconds", (int) buildTime.TotalSeconds);

                buildResult = true;
            } catch (BuildException e) {
                Log.WriteLine();
                Log.WriteLine("BUILD FAILED");
                Log.WriteLine(e.Message);
                if (e.InnerException != null) {
                    Log.WriteLine(e.InnerException.Message);
                }
            } catch (Exception e) {
                // all other exceptions should have been caught
                Log.WriteLine();
                Log.WriteLine("INTERNAL ERROR");
                Log.WriteLine(e.ToString());
            }
            return buildResult;
        }

        public int AddTasks(string assemblyPath) {

            Assembly assembly;
            if (assemblyPath == null) {
                assembly = Assembly.GetExecutingAssembly();
            } else {
                assembly = Assembly.LoadFrom(assemblyPath);
            }

            int taskCount = 0;
            foreach(Type type in assembly.GetTypes()) {
                if (type.IsSubclassOf(typeof(Task)) && !type.IsAbstract) {
                    if (_taskFactory.Builders.Add(new TaskBuilder(type.FullName, assemblyPath))) {
                        taskCount++;
                    }
                }
            }
            return taskCount;
        }

        public void Initialize(XmlDocument doc) {

            Name = doc.SelectSingleNode("project/@name").Value;

            // make it possible for user to override this value
            if (BaseDirectory == null) {
                BaseDirectory = doc.SelectSingleNode("project/@basedir").Value;
            }

            // used only if BuildTargets collection is empty
            _defaultTargetName = doc.SelectSingleNode("project/@default").Value;

            // initialize builtin tasks
            AddTasks(null);

            // init static built in properties
            Properties.Add("nant.project.name", Name);
            Properties.Add("nant.base.dir",     BaseDirectory);
            Properties.Add("nant.default.name", _defaultTargetName);

            // add all environment variables
            IDictionary variables = Environment.GetEnvironmentVariables();
            foreach (string name in variables.Keys) {
                string value = (string) variables[name];
                Properties.Add("nant.env." + name, value);
            }

            // Load line Xpath to linenumber array
            _positionMap = new XPathTextPositionMap(doc.BaseURI);

            // process all the non-target nodes (these are global tasks for the project)
            XmlNodeList taskList = doc.SelectNodes("project/*[name() != 'target']");
            foreach (XmlNode taskNode in taskList) {

                // TODO: do somethiing like Project.CreateTask(taskNode) and have the project set the location
                TextPosition textPosition = _positionMap.GetTextPosition(taskNode);

                Task task = CreateTask(taskNode);
                if (task != null) {
                    Tasks.Add(task);
                }
            }

            // execute global tasks now - before anything else
            // this lets us include tasks that do things like add more tasks
            foreach (Task task in Tasks) {
                task.Execute();
            }

            // process all the targets
            XmlNodeList targetList = doc.SelectNodes("project/target");
            foreach (XmlNode targetNode in targetList) {
                Target target = new Target(this);
                target.Initialize(targetNode);
                Targets.Add(target);
            }
        }

        public void Execute() {
            if (BuildTargets.Count == 0) {
                BuildTargets.Add(_defaultTargetName);
            }

            foreach(string targetName in BuildTargets) {
                Execute(targetName);
            }
        }

        public void Execute(string targetName) {
            Target target = Targets.Find(targetName);
            if (target == null) {
                throw new BuildException(String.Format("unknown target '{0}'", targetName));
            }
            target.Execute();
        }

        public Task CreateTask(XmlNode taskNode) {
            return CreateTask(taskNode, null);
        }

        public Task CreateTask(XmlNode taskNode, Target target) {
            Task task = _taskFactory.CreateTask(taskNode, target);
            if (task != null) {
                // save task location in case of error
                TextPosition pos = _positionMap.GetTextPosition(taskNode);

                // initialize the task
                task.Initialize(taskNode, new Location(taskNode.BaseURI, pos.Line, pos.Column));
            }
            return task;
        }

        public string ExpandText(string input) {
            string output = input;
            if (input != null) {
                const string pattern = @"\$\{([^\}]*)\}";
                foreach (Match m in Regex.Matches(input, pattern)) {
                    if (m.Length > 0) {

                        string token         = m.ToString();
                        string propertyName  = m.Groups[1].Captures[0].Value;
                        string propertyValue = Properties[propertyName];

                        if (propertyValue != null) {
                            output = output.Replace(token, propertyValue);
                        }
                    }
                }
            }
            return output;
        }

        public string GetFullPath(string path) {
            string baseDir = ExpandText(BaseDirectory);

            if (path != null) {
                if (!Path.IsPathRooted(path)) {
                    path = Path.Combine(baseDir, path);
                }
            } else {
                path = baseDir;
            }
            return Path.GetFullPath(path);
        }
    }
}