aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/Prebuild/src/Core/Utilities/Helper.cs
diff options
context:
space:
mode:
Diffstat (limited to 'Prebuild/src/Core/Utilities/Helper.cs')
-rw-r--r--Prebuild/src/Core/Utilities/Helper.cs661
1 files changed, 661 insertions, 0 deletions
diff --git a/Prebuild/src/Core/Utilities/Helper.cs b/Prebuild/src/Core/Utilities/Helper.cs
new file mode 100644
index 0000000..33c9618
--- /dev/null
+++ b/Prebuild/src/Core/Utilities/Helper.cs
@@ -0,0 +1,661 @@
1#region BSD License
2/*
3Copyright (c) 2004-2005 Matthew Holmes (matthew@wildfiregames.com), Dan Moorehead (dan05a@gmail.com)
4
5Redistribution and use in source and binary forms, with or without modification, are permitted
6provided that the following conditions are met:
7
8* Redistributions of source code must retain the above copyright notice, this list of conditions
9 and the following disclaimer.
10* Redistributions in binary form must reproduce the above copyright notice, this list of conditions
11 and the following disclaimer in the documentation and/or other materials provided with the
12 distribution.
13* The name of the author may not be used to endorse or promote products derived from this software
14 without specific prior written permission.
15
16THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
17BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
19EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
22IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
23*/
24#endregion
25
26#region CVS Information
27/*
28 * $Source$
29 * $Author: jendave $
30 * $Date: 2007-02-13 21:58:03 +0100 (ti, 13 feb 2007) $
31 * $Revision: 205 $
32 */
33#endregion
34
35using System;
36using System.Collections;
37using System.Diagnostics;
38using System.IO;
39using System.Runtime.InteropServices;
40using System.Text.RegularExpressions;
41using System.Collections.Specialized;
42using System.Xml;
43using Prebuild.Core.Nodes;
44
45namespace Prebuild.Core.Utilities
46{
47 /// <summary>
48 ///
49 /// </summary>
50 public class Helper
51 {
52 #region Fields
53
54 private static Stack dirStack;
55 private static Regex varRegex;
56 static bool checkForOSVariables;
57
58 /// <summary>
59 ///
60 /// </summary>
61 public static bool CheckForOSVariables
62 {
63 get
64 {
65 return checkForOSVariables;
66 }
67 set
68 {
69 checkForOSVariables = value;
70 }
71 }
72
73 #endregion
74
75 #region Constructors
76
77 /// <summary>
78 /// Initializes the <see cref="Helper"/> class.
79 /// </summary>
80 static Helper()
81 {
82 dirStack = new Stack();
83 //m_VarRegex = new Regex(@"\${(?<var>[\w|_]+)}");
84 }
85
86 #endregion
87
88 #region Properties
89
90 /// <summary>
91 ///
92 /// </summary>
93 public static Stack DirStack
94 {
95 get
96 {
97 return dirStack;
98 }
99 }
100
101 /// <summary>
102 ///
103 /// </summary>
104 public static Regex VarRegex
105 {
106 get
107 {
108 return varRegex;
109 }
110 set
111 {
112 varRegex = value;
113 }
114 }
115
116 #endregion
117
118 #region Public Methods
119
120 #region String Parsing
121 #region Inner Classes and Delegates
122 /// <summary>
123 ///
124 /// </summary>
125 public delegate string StringLookup(string key);
126
127 #endregion
128
129 /// <summary>
130 /// Gets a collection of StringLocationPair objects that represent the matches
131 /// </summary>
132 /// <param name="target">The target.</param>
133 /// <param name="beforeGroup">The before group.</param>
134 /// <param name="afterGroup">The after group.</param>
135 /// <param name="includeDelimitersInSubstrings">if set to <c>true</c> [include delimiters in substrings].</param>
136 /// <returns></returns>
137 public static StringCollection FindGroups(string target, string beforeGroup, string afterGroup, bool includeDelimitersInSubstrings)
138 {
139 if( beforeGroup == null )
140 {
141 throw new ArgumentNullException("beforeGroup");
142 }
143 if( afterGroup == null )
144 {
145 throw new ArgumentNullException("afterGroup");
146 }
147 StringCollection results = new StringCollection();
148 if(target == null || target.Length == 0)
149 {
150 return results;
151 }
152
153 int beforeMod = 0;
154 int afterMod = 0;
155 if(includeDelimitersInSubstrings)
156 {
157 //be sure to not exlude the delims
158 beforeMod = beforeGroup.Length;
159 afterMod = afterGroup.Length;
160 }
161 int startIndex = 0;
162 while((startIndex = target.IndexOf(beforeGroup,startIndex)) != -1) {
163 int endIndex = target.IndexOf(afterGroup,startIndex);//the index of the char after it
164 if(endIndex == -1)
165 {
166 break;
167 }
168 int length = endIndex - startIndex - beforeGroup.Length;//move to the first char in the string
169 string substring = substring = target.Substring(startIndex + beforeGroup.Length - beforeMod,
170 length - afterMod);
171
172 results.Add(substring);
173 //results.Add(new StringLocationPair(substring,startIndex));
174 startIndex = endIndex + 1;
175 //the Interpolate*() methods will not work if expressions are expandded inside expression due to an optimization
176 //so start after endIndex
177
178 }
179 return results;
180 }
181
182 /// <summary>
183 /// Replaces the groups.
184 /// </summary>
185 /// <param name="target">The target.</param>
186 /// <param name="beforeGroup">The before group.</param>
187 /// <param name="afterGroup">The after group.</param>
188 /// <param name="lookup">The lookup.</param>
189 /// <returns></returns>
190 public static string ReplaceGroups(string target, string beforeGroup, string afterGroup, StringLookup lookup) {
191 if( target == null )
192 {
193 throw new ArgumentNullException("target");
194 }
195 //int targetLength = target.Length;
196 StringCollection strings = FindGroups(target,beforeGroup,afterGroup,false);
197 if( lookup == null )
198 {
199 throw new ArgumentNullException("lookup");
200 }
201 foreach(string substring in strings)
202 {
203 target = target.Replace(beforeGroup + substring + afterGroup, lookup(substring) );
204 }
205 return target;
206 }
207
208 /// <summary>
209 /// Replaces ${var} statements in a string with the corresonding values as detirmined by the lookup delegate
210 /// </summary>
211 /// <param name="target">The target.</param>
212 /// <param name="lookup">The lookup.</param>
213 /// <returns></returns>
214 public static string InterpolateForVariables(string target, StringLookup lookup)
215 {
216 return ReplaceGroups(target, "${" , "}" , lookup);
217 }
218
219 /// <summary>
220 /// Replaces ${var} statements in a string with the corresonding environment variable with name var
221 /// </summary>
222 /// <param name="target"></param>
223 /// <returns></returns>
224 public static string InterpolateForEnvironmentVariables(string target)
225 {
226 return InterpolateForVariables(target, new StringLookup(Environment.GetEnvironmentVariable));
227 }
228
229 #endregion
230
231 /// <summary>
232 /// Translates the value.
233 /// </summary>
234 /// <param name="translateType">Type of the translate.</param>
235 /// <param name="translationItem">The translation item.</param>
236 /// <returns></returns>
237 public static object TranslateValue(Type translateType, string translationItem)
238 {
239 if(translationItem == null)
240 {
241 return null;
242 }
243
244 try
245 {
246 string lowerVal = translationItem.ToLower();
247 if(translateType == typeof(bool))
248 {
249 return (lowerVal == "true" || lowerVal == "1" || lowerVal == "y" || lowerVal == "yes" || lowerVal == "on");
250 }
251 else if(translateType == typeof(int))
252 {
253 return (Int32.Parse(translationItem));
254 }
255 else
256 {
257 return translationItem;
258 }
259 }
260 catch(FormatException)
261 {
262 return null;
263 }
264 }
265
266 /// <summary>
267 /// Deletes if exists.
268 /// </summary>
269 /// <param name="file">The file.</param>
270 /// <returns></returns>
271 public static bool DeleteIfExists(string file)
272 {
273 string resFile = null;
274 try
275 {
276 resFile = ResolvePath(file);
277 }
278 catch(ArgumentException)
279 {
280 return false;
281 }
282
283 if(!File.Exists(resFile))
284 {
285 return false;
286 }
287
288 File.Delete(resFile);
289 return true;
290 }
291
292 // This little gem was taken from the NeL source, thanks guys!
293 /// <summary>
294 /// Makes a relative path
295 /// </summary>
296 /// <param name="startPath">Path to start from</param>
297 /// <param name="endPath">Path to end at</param>
298 /// <returns>Path that will get from startPath to endPath</returns>
299 public static string MakePathRelativeTo(string startPath, string endPath)
300 {
301 string tmp = NormalizePath(startPath, '/');
302 string src = NormalizePath(endPath, '/');
303 string prefix = "";
304
305 while(true)
306 {
307 if((String.Compare(tmp, 0, src, 0, tmp.Length) == 0))
308 {
309 string ret;
310 int size = tmp.Length;
311 if(size == src.Length)
312 {
313 return "./";
314 }
315 if ((src.Length > tmp.Length) && src[tmp.Length-1] != '/' && src[tmp.Length-1] != '\\')
316 {
317 }
318 else
319 {
320 ret = prefix + endPath.Substring(size, endPath.Length - size);
321 ret = ret.Trim();
322 if(ret[0] == '/' || ret[0] == '\\')
323 {
324 ret = "." + ret;
325 }
326
327 return NormalizePath(ret);
328 }
329
330 }
331
332 if(tmp.Length < 2)
333 {
334 break;
335 }
336
337 int lastPos = tmp.LastIndexOf('/', tmp.Length - 2);
338 int prevPos = tmp.IndexOf('/');
339
340 if((lastPos == prevPos) || (lastPos == -1))
341 {
342 break;
343 }
344
345 tmp = tmp.Substring(0, lastPos + 1);
346 prefix += "../";
347 }
348
349 return endPath;
350 }
351
352 /// <summary>
353 /// Resolves the path.
354 /// </summary>
355 /// <param name="path">The path.</param>
356 /// <returns></returns>
357 public static string ResolvePath(string path)
358 {
359 string tmpPath = NormalizePath(path);
360 if(tmpPath.Length < 1)
361 {
362 tmpPath = ".";
363 }
364
365 tmpPath = Path.GetFullPath(tmpPath);
366 if(!File.Exists(tmpPath) && !Directory.Exists(tmpPath))
367 {
368 throw new ArgumentException("Path could not be resolved: " + tmpPath);
369 }
370
371 return tmpPath;
372 }
373
374 /// <summary>
375 /// Normalizes the path.
376 /// </summary>
377 /// <param name="path">The path.</param>
378 /// <param name="separatorCharacter">The separator character.</param>
379 /// <returns></returns>
380 public static string NormalizePath(string path, char separatorCharacter)
381 {
382 if(path == null || path == "" || path.Length < 1)
383 {
384 return "";
385 }
386
387 string tmpPath = path.Replace('\\', '/');
388 tmpPath = tmpPath.Replace('/', separatorCharacter);
389 return tmpPath;
390 }
391
392 /// <summary>
393 /// Normalizes the path.
394 /// </summary>
395 /// <param name="path">The path.</param>
396 /// <returns></returns>
397 public static string NormalizePath(string path)
398 {
399 return NormalizePath(path, Path.DirectorySeparatorChar);
400 }
401
402 /// <summary>
403 /// Ends the path.
404 /// </summary>
405 /// <param name="path">The path.</param>
406 /// <param name="separatorCharacter">The separator character.</param>
407 /// <returns></returns>
408 public static string EndPath(string path, char separatorCharacter)
409 {
410 if(path == null || path == "" || path.Length < 1)
411 {
412 return "";
413 }
414
415 if(!path.EndsWith(separatorCharacter.ToString()))
416 {
417 return (path + separatorCharacter);
418 }
419
420 return path;
421 }
422
423 /// <summary>
424 /// Ends the path.
425 /// </summary>
426 /// <param name="path">The path.</param>
427 /// <returns></returns>
428 public static string EndPath(string path)
429 {
430 return EndPath(path, Path.DirectorySeparatorChar);
431 }
432
433 /// <summary>
434 /// Makes the file path.
435 /// </summary>
436 /// <param name="path">The path.</param>
437 /// <param name="name">The name.</param>
438 /// <param name="ext">The ext.</param>
439 /// <returns></returns>
440 public static string MakeFilePath(string path, string name, string ext)
441 {
442 string ret = EndPath(NormalizePath(path));
443
444 if( name == null )
445 {
446 throw new ArgumentNullException("name");
447 }
448
449 ret += name;
450 if(!name.EndsWith("." + ext))
451 {
452 ret += "." + ext;
453 }
454
455 //foreach(char c in Path.GetInvalidPathChars())
456 //{
457 // ret = ret.Replace(c, '_');
458 //}
459
460 return ret;
461 }
462
463 /// <summary>
464 /// Makes the file path.
465 /// </summary>
466 /// <param name="path">The path.</param>
467 /// <param name="name">The name.</param>
468 /// <returns></returns>
469 public static string MakeFilePath(string path, string name)
470 {
471 string ret = EndPath(NormalizePath(path));
472
473 if( name == null )
474 {
475 throw new ArgumentNullException("name");
476 }
477
478 ret += name;
479
480 //foreach (char c in Path.GetInvalidPathChars())
481 //{
482 // ret = ret.Replace(c, '_');
483 //}
484
485 return ret;
486 }
487
488 /// <summary>
489 ///
490 /// </summary>
491 /// <param name="path"></param>
492 /// <returns></returns>
493 public static string MakeReferencePath(string path)
494 {
495 string ret = EndPath(NormalizePath(path));
496
497 //foreach (char c in Path.GetInvalidPathChars())
498 //{
499 // ret = ret.Replace(c, '_');
500 //}
501
502 return ret;
503 }
504
505 /// <summary>
506 /// Sets the current dir.
507 /// </summary>
508 /// <param name="path">The path.</param>
509 public static void SetCurrentDir(string path)
510 {
511 if( path == null )
512 {
513 throw new ArgumentNullException("path");
514 }
515 if(path.Length < 1)
516 {
517 return;
518 }
519
520 Environment.CurrentDirectory = path;
521 }
522
523 /// <summary>
524 /// Checks the type.
525 /// </summary>
526 /// <param name="typeToCheck">The type to check.</param>
527 /// <param name="attr">The attr.</param>
528 /// <param name="inter">The inter.</param>
529 /// <returns></returns>
530 public static object CheckType(Type typeToCheck, Type attr, Type inter)
531 {
532 if(typeToCheck == null || attr == null)
533 {
534 return null;
535 }
536
537 object[] attrs = typeToCheck.GetCustomAttributes(attr, false);
538 if(attrs == null || attrs.Length < 1)
539 {
540 return null;
541 }
542 if( inter == null )
543 {
544 throw new ArgumentNullException("inter");
545 }
546
547 if(typeToCheck.GetInterface(inter.FullName) == null)
548 {
549 return null;
550 }
551
552 return attrs[0];
553 }
554
555 /* A bit of overhead for simple group parsing, there are problems with Regex in Mono
556 public static string ParseValue(string val)
557 {
558 if(val == null || val.Length < 1 || !CheckForOSVariables)
559 return val;
560
561 string tmp = val;
562 Match m = m_VarRegex.Match(val);
563 while(m.Success)
564 {
565 if(m.Groups["var"] == null)
566 continue;
567
568 Capture c = m.Groups["var"].Captures[0];
569 if(c == null)
570 continue;
571
572 string var = c.Value;
573 string envVal = Environment.GetEnvironmentVariable(var);
574 if(envVal == null)
575 envVal = "";
576
577 tmp = tmp.Replace("${" + var + "}", envVal);
578 m = m.NextMatch();
579 }
580
581 return tmp;
582 }*/
583
584 /// <summary>
585 /// Attributes the value.
586 /// </summary>
587 /// <param name="node">The node.</param>
588 /// <param name="attr">The attr.</param>
589 /// <param name="def">The def.</param>
590 /// <returns></returns>
591 public static string AttributeValue(XmlNode node, string attr, string def)
592 {
593 if( node == null )
594 {
595 throw new ArgumentNullException("node");
596 }
597 if(node.Attributes[attr] == null)
598 {
599 return def;
600 }
601 string val = node.Attributes[attr].Value;
602 if(!CheckForOSVariables)
603 {
604 return val;
605 }
606
607 return InterpolateForEnvironmentVariables(val);
608 }
609
610 /// <summary>
611 /// Parses the boolean.
612 /// </summary>
613 /// <param name="node">The node.</param>
614 /// <param name="attr">The attr.</param>
615 /// <param name="defaultValue">if set to <c>true</c> [default value].</param>
616 /// <returns></returns>
617 public static bool ParseBoolean(XmlNode node, string attr, bool defaultValue)
618 {
619 if( node == null )
620 {
621 throw new ArgumentNullException("node");
622 }
623 if(node.Attributes[attr] == null)
624 {
625 return defaultValue;
626 }
627 return bool.Parse(node.Attributes[attr].Value);
628 }
629
630 /// <summary>
631 /// Enums the attribute value.
632 /// </summary>
633 /// <param name="node">The node.</param>
634 /// <param name="attr">The attr.</param>
635 /// <param name="enumType">Type of the enum.</param>
636 /// <param name="def">The def.</param>
637 /// <returns></returns>
638 public static object EnumAttributeValue(XmlNode node, string attr, Type enumType, object def)
639 {
640 if( def == null )
641 {
642 throw new ArgumentNullException("def");
643 }
644 string val = AttributeValue(node, attr, def.ToString());
645 return Enum.Parse(enumType, val, true);
646 }
647
648 /// <summary>
649 ///
650 /// </summary>
651 /// <param name="assemblyName"></param>
652 /// <param name="projectType"></param>
653 /// <returns></returns>
654 public static string AssemblyFullName(string assemblyName, ProjectType projectType)
655 {
656 return assemblyName + (projectType == ProjectType.Library ? ".dll" : ".exe");
657 }
658
659 #endregion
660 }
661}