6932907ecabb25ada3d97bbe5820b139e41df658
[mono.git] / mcs / tools / xbuild / Parameters.cs
1 //
2 // Parameters.cs: Class that contains information about command line parameters
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.IO;
32 using System.Collections;
33 using System.Collections.Generic;
34 using System.Linq;
35 using System.Text;
36 using System.Reflection;
37 using Microsoft.Build.BuildEngine;
38 using Microsoft.Build.Framework;
39 using Microsoft.Build.Utilities;
40
41 namespace Mono.XBuild.CommandLine {
42         public class Parameters {
43         
44                 string                  consoleLoggerParameters;
45                 bool                    displayHelp;
46                 IList                   flatArguments;
47                 IList                   loggers;
48                 LoggerVerbosity         loggerVerbosity;
49                 bool                    noConsoleLogger;
50                 bool                    noLogo;
51                 string                  projectFile;
52                 BuildPropertyGroup      properties;
53                 IList                   remainingArguments;
54                 Hashtable               responseFiles;
55                 string[]                targets;
56                 bool                    validate;
57                 string                  validationSchema;
58                 string                  toolsVersion;
59                 
60                 string                  responseFile;
61         
62                 public Parameters ()
63                 {
64                         consoleLoggerParameters = "";
65                         displayHelp = false;
66                         loggers = new ArrayList ();
67                         loggerVerbosity = LoggerVerbosity.Normal;
68                         noConsoleLogger = false;
69                         noLogo = false;
70                         properties = new BuildPropertyGroup ();
71                         targets = new string [0];
72                         
73                         responseFile = Path.Combine (
74                                         Path.GetDirectoryName (Assembly.GetExecutingAssembly ().Location),
75                                         "xbuild.rsp");
76                 }
77                 
78                 public void ParseArguments (string[] args)
79                 {
80                         bool autoResponse = true;
81                         flatArguments = new ArrayList ();
82                         remainingArguments = new ArrayList ();
83                         responseFiles = new Hashtable ();
84                         foreach (string s in args) {
85                                 if (s.StartsWith ("/noautoresponse") || s.StartsWith ("/noautorsp")) {
86                                         autoResponse = false;
87                                         continue;
88                                 }
89                                 if (s [0] != '@') {
90                                         flatArguments.Add (s);
91                                         continue;
92                                 }
93                                 string responseFilename = Path.GetFullPath (UnquoteIfNeeded (s.Substring (1)));
94                                 if (responseFiles.ContainsKey (responseFilename))
95                                         ReportError (1, String.Format ("We already have {0} file.", responseFilename));
96                                 responseFiles [responseFilename] = responseFilename;
97                                 LoadResponseFile (responseFilename);
98                         }
99                         if (autoResponse == true) {
100                                 // FIXME: we do not allow nested auto response file
101                                 LoadResponseFile (responseFile);
102                         }
103                         foreach (string s in flatArguments) {
104                                 if (s [0] != '/' || !ParseFlatArgument (s))
105                                         remainingArguments.Add (s);
106                         }
107                         if (remainingArguments.Count == 0) {
108                                 string[] sln_files = Directory.GetFiles (Directory.GetCurrentDirectory (), "*.sln");
109                                 string[] proj_files = Directory.GetFiles (Directory.GetCurrentDirectory (), "*proj");
110
111                                 if (sln_files.Length == 0 && proj_files.Length == 0)
112                                         ReportError (3, "Please specify the project or solution file " +
113                                                         "to build, as none was found in the current directory.");
114
115                                 if (sln_files.Length == 1 && proj_files.Length > 0) {
116                                         var projects_table = new Dictionary<string, string> ();
117                                         foreach (string pfile in SolutionParser.GetAllProjectFileNames (sln_files [0])) {
118                                                 string full_path = Path.GetFullPath (pfile);
119                                                 projects_table [full_path] = full_path;
120                                         }
121
122                                         if (!proj_files.Any (p => !projects_table.ContainsKey (Path.GetFullPath (p))))
123                                                 // if all the project files in the cur dir, are referenced
124                                                 // from the single .sln in the cur dir, then pick the sln
125                                                 proj_files = new string [0];
126                                 }
127
128                                 if (sln_files.Length + proj_files.Length > 1)
129                                         ReportError (5, "Please specify the project or solution file " +
130                                                         "to build, as more than one solution or project file was found " +
131                                                         "in the current directory");
132
133                                 if (sln_files.Length == 1)
134                                         projectFile = sln_files [0];
135                                 else
136                                         projectFile = proj_files [0];
137                         } else if (remainingArguments.Count == 1) {
138                                 projectFile = (string) remainingArguments [0];
139                         } else {
140                                 ReportError (4, "Too many project files specified");
141                         }
142                 }
143
144                 private string UnquoteIfNeeded(string arg)
145                 {
146                         if (arg.StartsWith("\""))
147                                 return arg.Substring(1, arg.Length - 2);
148                         return arg;
149                 }
150
151                 void LoadResponseFile (string filename)
152                 {
153                         StreamReader sr = null;
154                         string line;
155                         try {
156                                 sr = new StreamReader (filename);
157                                 StringBuilder sb = new StringBuilder ();
158
159                                 while ((line = sr.ReadLine ()) != null) {
160                                         int t = line.Length;
161
162                                         for (int i = 0; i < t; i++) {
163                                                 char c = line [i];
164
165                                                 if (c == '#')
166                                                         // comment, ignore rest of the line
167                                                         break;
168
169                                                 if (c == '"' || c == '\'') {
170                                                         char end = c;
171
172                                                         for (i++; i < t; i++) {
173                                                                 c = line [i];
174
175                                                                 if (c == end)
176                                                                         break;
177                                                                 sb.Append (c);
178                                                         }
179                                                 } else if (c == ' ') {
180                                                         if (sb.Length > 0) {
181                                                                 flatArguments.Add (sb.ToString ());
182                                                                 sb.Length = 0;
183                                                         }
184                                                 } else
185                                                         sb.Append (c);
186                                         }
187                                         if (sb.Length > 0){
188                                                 flatArguments.Add (sb.ToString ());
189                                                 sb.Length = 0;
190                                         }
191                                 }
192                         } catch (IOException x) {
193                                 ErrorUtilities.ReportWarning (2, String.Format (
194                                                         "Error loading response file. (Exception: {0}). Ignoring.",
195                                                         x.Message));
196                         } finally {
197                                 if (sr != null)
198                                         sr.Close ();
199                         }
200                 }
201                 
202                 private bool ParseFlatArgument (string s)
203                 {
204                         switch (s) {
205                         case "/help":
206                         case "/h":
207                         case "/?":
208                                 ErrorUtilities.ShowUsage ();
209                                 break;
210                         case "/nologo":
211                                 noLogo = true;
212                                 break;
213                         case "/version":
214                         case "/ver":
215                                 ErrorUtilities.ShowVersion (true);
216                                 break;
217                         case "/noconsolelogger":
218                         case "/noconlog":
219                                 noConsoleLogger = true;
220                                 break;
221                         case "/validate":
222                         case "/val":
223                                 validate = true;
224                                 break;
225                         default:
226                                 if (s.StartsWith ("/target:") || s.StartsWith ("/t:")) {
227                                         ProcessTarget (s);
228                                 } else if (s.StartsWith ("/property:") || s.StartsWith ("/p:")) {
229                                         if (!ProcessProperty (s))
230                                                 return false;
231                                 } else  if (s.StartsWith ("/logger:") || s.StartsWith ("/l:")) {
232                                         ProcessLogger (s);
233                                 } else if (s.StartsWith ("/verbosity:") || s.StartsWith ("/v:")) {
234                                         ProcessVerbosity (s);
235                                 } else if (s.StartsWith ("/consoleloggerparameters:") || s.StartsWith ("/clp:")) {
236                                         ProcessConsoleLoggerParameters (s);
237                                 } else if (s.StartsWith ("/validate:") || s.StartsWith ("/val:")) {
238                                         ProcessValidate (s);
239                                 } else if (s.StartsWith ("/toolsversion:") || s.StartsWith ("/tv:")) {
240                                         ToolsVersion = s.Split (':') [1];
241                                 } else
242                                         return false;
243                                 break;
244                         }
245
246                         return true;
247                 }
248                 
249                 internal void ProcessTarget (string s)
250                 {
251                         TryProcessMultiOption (s, "Target names must be specified as /t:Target1;Target2",
252                                                 out targets);
253                 }
254                 
255                 internal bool ProcessProperty (string s)
256                 {
257                         string[] splitProperties;
258                         if (!TryProcessMultiOption (s, "Property name and value expected as /p:<prop name>=<prop value>",
259                                                 out splitProperties))
260                                 return false;
261
262                         foreach (string st in splitProperties) {
263                                 if (st.IndexOf ('=') < 0) {
264                                         ReportError (5,
265                                                         "Invalid syntax. Property name and value expected as " +
266                                                         "<prop name>=[<prop value>]");
267                                         return false;
268                                 }
269                                 string [] property = st.Split ('=');
270                                 properties.SetProperty (property [0], property.Length == 2 ? property [1] : "");
271                         }
272
273                         return true;
274                 }
275
276                 bool TryProcessMultiOption (string s, string error_message, out string[] values)
277                 {
278                         values = null;
279                         int colon = s.IndexOf (':');
280                         if (colon + 1 == s.Length) {
281                                 ReportError (5, error_message);
282                                 return false;
283                         }
284
285                         values = s.Substring (colon + 1).Split (';');
286                         return true;
287                 }
288
289                 private void ReportError (int errorCode, string message)
290                 {
291                         throw new CommandLineException (message, errorCode);
292                 }
293
294                 private void ReportError (int errorCode, string message, Exception cause)
295                 {
296                         throw new CommandLineException (message, cause, errorCode);
297                 }
298
299                 internal void ProcessLogger (string s)
300                 {
301                         loggers.Add (new LoggerInfo (s));
302                 }
303                 
304                 internal void ProcessVerbosity (string s)
305                 {
306                         string[] temp = s.Split (':');
307                         switch (temp [1]) {
308                         case "q":
309                         case "quiet":
310                                 loggerVerbosity = LoggerVerbosity.Quiet;
311                                 break;
312                         case "m":
313                         case "minimal":
314                                 loggerVerbosity = LoggerVerbosity.Minimal;
315                                 break;
316                         case "n":
317                         case "normal":
318                                 loggerVerbosity = LoggerVerbosity.Normal;
319                                 break;
320                         case "d":
321                         case "detailed":
322                                 loggerVerbosity = LoggerVerbosity.Detailed;
323                                 break;
324                         case "diag":
325                         case "diagnostic":
326                                 loggerVerbosity = LoggerVerbosity.Diagnostic;
327                                 break;
328                         }
329                 }
330                 
331                 internal void ProcessConsoleLoggerParameters (string s)
332                 {
333                         int colon = s.IndexOf (':');
334                         if (colon + 1 == s.Length)
335                                 ReportError (5, "Invalid syntax, specify parameters as /clp:parameters");
336
337                         consoleLoggerParameters = s.Substring (colon + 1);
338                 }
339                 
340                 internal void ProcessValidate (string s)
341                 {
342                         string[] temp;
343                         validate = true;
344                         temp = s.Split (':');
345                         validationSchema = temp [1];
346                 }
347                 public bool DisplayHelp {
348                         get { return displayHelp; }
349                 }
350                 
351                 public bool NoLogo {
352                         get { return noLogo; }
353                 }
354                 
355                 public string ProjectFile {
356                         get { return projectFile; }
357                 }
358                 
359                 public string[] Targets {
360                         get { return targets; }
361                 }
362                 
363                 public BuildPropertyGroup Properties {
364                         get { return properties; }
365                 }
366                 
367                 public IList Loggers {
368                         get { return loggers; }
369                 }
370                 
371                 public LoggerVerbosity LoggerVerbosity {
372                         get { return loggerVerbosity; }
373                 }
374                 
375                 public string ConsoleLoggerParameters {
376                         get { return consoleLoggerParameters; }
377                 }
378                 
379                 public bool NoConsoleLogger {
380                         get { return noConsoleLogger; }
381                 }
382                 
383                 public bool Validate {
384                         get { return validate; }
385                 }
386                 
387                 public string ValidationSchema {
388                         get { return validationSchema; }
389                 }
390
391                 public string ToolsVersion {
392                         get { return toolsVersion; }
393                         private set { toolsVersion = value; }
394                 }
395                 
396         }
397 }
398
399 #endif