forked from oleg-shilo/cs-script
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUtils.cs
2312 lines (1984 loc) · 88.2 KB
/
Utils.cs
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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#region Licence...
//-----------------------------------------------------------------------------
// Date: 25/10/10
// Module: Utils.cs
// Classes: ...
//
// This module contains the definition of the utility classes used by CS-Script modules
//
// Written by Oleg Shilo ([email protected])
//----------------------------------------------
// The MIT License (MIT)
// Copyright (c) 2004-2018 Oleg Shilo
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software
// and associated documentation files (the "Software"), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial
// portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//----------------------------------------------
#endregion Licence...
using System;
using System.IO;
using System.Reflection;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CSScriptLibrary;
using System.Runtime.InteropServices;
using System.CodeDom.Compiler;
using Microsoft.CSharp;
using System.Globalization;
using System.Threading;
using System.Collections;
using System.Text.RegularExpressions;
using System.Diagnostics;
using System.Xml;
using System.Runtime.Remoting.Lifetime;
namespace csscript
{
internal class CurrentDirGuard : IDisposable
{
string currentDir = Environment.CurrentDirectory;
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
Environment.CurrentDirectory = currentDir;
disposed = true;
}
~CurrentDirGuard()
{
Dispose(false);
}
bool disposed = false;
}
/// <summary>
/// Class containing all information about script compilation context and the compilation result.
/// </summary>
public class CompilingInfo
{
/// <summary>
/// The script file that the <c>CompilingInfo</c> is associated with.
/// </summary>
public string ScriptFile;
/// <summary>
/// The script parsing context containing the all CS-Script specific compilation/parsing info (e.g. probing directories,
/// NuGet packages, compiled sources).
/// </summary>
public ScriptParsingResult ParsingContext;
/// <summary>
/// The script compilation result.
/// </summary>
public CompilerResults Result;
/// <summary>
/// The compilation context object that contain all information about the script compilation input
/// (referenced assemblies, compiler symbols).
/// </summary>
public CompilerParameters Input;
}
internal static class Utils
{
public static Exception ToNewException(this Exception ex, string message, bool encapsulate)
{
var topLevelMessage = message;
Exception childException = ex;
if (!encapsulate)
{
topLevelMessage += Environment.NewLine + ex.Message;
childException = null;
}
var constructor = ex.GetType().GetConstructor(new Type[] { typeof(string), typeof(Exception) });
if (constructor != null)
return (Exception)constructor.Invoke(new object[] { topLevelMessage, childException });
else
return new Exception(message, childException);
}
internal static string Expand(this string text)
{
return Environment.ExpandEnvironmentVariables(text).Trim();
}
internal static string NormaliseAsDirectiveOf(this string statement, string parentScript)
{
var text = CSharpParser.UnescapeDirectiveDelimiters(statement);
if (text.Length > 1 && (text[0] == '.' && text[1] != '.')) //just a single-dot start dir
text = Path.Combine(Path.GetDirectoryName(parentScript), text);
return Environment.ExpandEnvironmentVariables(text).Trim();
}
internal static string NormaliseAsDirective(this string statement)
{
var text = CSharpParser.UnescapeDirectiveDelimiters(statement);
return Environment.ExpandEnvironmentVariables(text).Trim();
}
public static string[] ConcatWith(this string[] array1, IEnumerable<string> array2)
{
return array1.Concat(array2).ToArray();
}
public static string[] ConcatWith(this string[] array, string item)
{
return array.Concat(new[] { item }).ToArray();
}
public static string[] ConcatWith(this string item, IEnumerable<string> array)
{
return new[] { item }.Concat(array).ToArray();
}
public static string[] RemovePathDuplicates(this string[] list)
{
return list.Where(x => !string.IsNullOrEmpty(x))
.Select(x =>
{
var fullPath = Path.GetFullPath(x);
if (File.Exists(fullPath))
return fullPath;
else
return x;
})
.Distinct().ToArray();
}
public static string[] RemoveDuplicates(this string[] list)
{
return list.Distinct().ToArray();
}
public static bool NotEmpty(this string text)
{
return !string.IsNullOrEmpty(text);
}
// Mono doesn't like referencing assemblies without dll or exe extension
public static string EnsureAsmExtension(this string asmName)
{
if (asmName != null && Utils.IsMono)
{
if (!asmName.EndsWith(".exe", StringComparison.OrdinalIgnoreCase) &&
!asmName.EndsWith(".dll", StringComparison.OrdinalIgnoreCase))
asmName = asmName + ".dll";
}
return asmName;
}
public static IEnumerable<T> Map<T>(this IEnumerable<T> source, params Func<T, T>[] selectors)
{
IEnumerable<T> result = source;
foreach (Func<T, T> sel in selectors)
result = result.Select(sel);
return result;
}
public static string PathNormaliseSeparators(this string path)
{
return path.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
}
//to avoid throwing the exception
public static string GetAssemblyDirectoryName(this Assembly asm)
{
string location = asm.Location();
return location == "" ? "" : Path.GetDirectoryName(location);
}
//to avoid throwing the exception
public static string Location(this Assembly asm)
{
if (asm.IsDynamic())
{
string location = Environment.GetEnvironmentVariable("location:" + asm.GetHashCode());
if (location == null)
return "";
else
return location ?? "";
}
else
return asm.Location;
}
public static string RemoveAssemblyExtension(this string asmName)
{
if (asmName.EndsWith(".dll", StringComparison.CurrentCultureIgnoreCase) || asmName.EndsWith(".exe", StringComparison.CurrentCultureIgnoreCase))
return asmName.Substring(0, asmName.Length - 4);
else
return asmName;
}
public static string PathCombine(this string path, params string[] parts)
{
#if net35
string result = (path ?? "");
foreach (string item in parts)
result = Path.Combine(result, item);
return result;
#else
var allParts = new[] { path ?? "" }.Concat(parts.Select(x => x ?? ""));
return Path.Combine(allParts.ToArray());
#endif
}
public static string GetDirName(this string path)
{
return Path.GetDirectoryName(path ?? "");
}
public static bool IsSamePath(this string path1, string path2)
{
return string.Compare(path1, path2, Utils.IsWin) == 0;
}
public static bool IsEmpty(this string text)
{
return string.IsNullOrEmpty(text);
}
public static bool IsNotEmpty(this string text)
{
return !string.IsNullOrEmpty(text);
}
public static void ClearFile(string path)
{
string parentDir = null;
if (File.Exists(path))
parentDir = Path.GetDirectoryName(path);
FileDelete(path, false);
if (parentDir != null && Directory.GetFiles(parentDir).Length == 0)
try
{
Directory.Delete(parentDir);
}
catch { }
}
class Win32
{
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
internal static extern bool SetEnvironmentVariable(string lpName, string lpValue);
}
public static void SetEnvironmentVariable(string name, string value)
{
Environment.SetEnvironmentVariable(name, value);
if (Utils.IsWin)
try { Win32.SetEnvironmentVariable(name, value); } catch { }
}
public static void FileDelete(string path)
{
FileDelete(path, false);
}
public static void CleanUnusedTmpFiles(string dir, string pattern, bool verifyPid)
{
if (!Directory.Exists(dir))
return;
string[] oldTempFiles = Directory.GetFiles(dir, pattern);
foreach (string file in oldTempFiles)
{
try
{
if (verifyPid)
{
string name = Path.GetFileName(file);
int pos = name.IndexOf('.');
if (pos > 0)
{
string pidValue = name.Substring(0, pos);
int pid = 0;
if (int.TryParse(pidValue, out pid))
{
//Didn't use GetProcessById as it throws if pid is not running
if (Process.GetProcesses().Any(p => p.Id == pid))
continue; //still running
}
}
}
Utils.FileDelete(file);
}
catch { }
}
}
//public static Mutex FileLock_(string file, object context)
//{
// if (!IsLinux())
// file = file.ToLower(CultureInfo.InvariantCulture);
// string mutexName = context.ToString() + "." + CSSUtils.GetHashCodeEx(file).ToString();
// if (Utils.IsLinux())
// {
// //Utils.Ge
// //scriptTextCRC = Crc32.Compute(Encoding.UTF8.GetBytes(scriptText));
// }
// return new Mutex(false, mutexName);
//}
//public static bool Wait(Mutex @lock, int millisecondsTimeout)
//{
// return @lock.WaitOne(millisecondsTimeout, false);
//}
//public static void ReleaseFileLock(Mutex @lock)
//{
// if (@lock != null)
// try { @lock.ReleaseMutex(); }
// catch { }
//}
public delegate string ProcessNewEncodingHandler(string requestedEncoding);
public static ProcessNewEncodingHandler ProcessNewEncoding = DefaultProcessNewEncoding;
public static bool IsDefaultConsoleEncoding = true;
static string DefaultProcessNewEncoding(string requestedEncoding)
{
return requestedEncoding;
}
/// <summary>
/// Waits for file idle.
/// </summary>
/// <param name="file">The file.</param>
/// <param name="delay">The delay.</param>
/// <returns><c>true</c> if the wait is successful.</returns>
public static bool WaitForFileIdle(string file, int delay)
{
if (file == null || !File.Exists(file)) return true;
//very conservative "file in use" checker
int start = Environment.TickCount;
while ((Environment.TickCount - start) <= delay && IsFileLocked(file))
{
Thread.Sleep(200);
}
return IsFileLocked(file);
}
static bool IsFileLocked(string file)
{
try
{
using (File.Open(file, FileMode.Open)) { }
}
catch (IOException e)
{
int errorCode = Marshal.GetHRForException(e) & ((1 << 16) - 1);
return errorCode == 32 || errorCode == 33;
}
return false;
}
public static void FileDelete(string path, bool rethrow)
{
//There are the reports about
//anti viruses preventing file deletion
//See 18 Feb message in this thread https://groups.google.com/forum/#!topic/cs-script/5Tn32RXBmRE
for (int i = 0; i < 3; i++)
{
try
{
if (File.Exists(path))
File.Delete(path);
break;
}
catch
{
if (rethrow && i == 2)
throw;
}
Thread.Sleep(300);
}
}
public static bool IsNet45Plus()
{
// Class "ReflectionContext" exists from .NET 4.5 onwards.
return Type.GetType("System.Reflection.ReflectionContext", false) != null;
}
public static bool IsNet40Plus()
{
return Environment.Version.Major >= 4;
}
public static bool IsNet20Plus()
{
return Environment.Version.Major >= 2;
}
public static bool IsRuntimeCompatibleAsm(string file)
{
try
{
System.Reflection.AssemblyName.GetAssemblyName(file);
return true;
}
catch { }
return false;
}
public static bool IsWin
{
get { return !IsLinux; }
}
public static bool IsLinux
{
get
{
// Note it is not about OS being exactly Linux but rather about OS having Linux type of file system.
// For example path being case sensitive
return (Environment.OSVersion.Platform == PlatformID.Unix || Environment.OSVersion.Platform == PlatformID.MacOSX);
}
}
static bool isMono = (Type.GetType("Mono.Runtime") != null);
public static bool IsMono
{
get { return isMono; }
}
internal static void SetMonoRootDirEnvvar()
{
if (Environment.GetEnvironmentVariable("MONO") == null && isMono)
Environment.SetEnvironmentVariable("MONO", MonoRootDir);
}
public static string MonoRootDir
{
get
{
var runtime = Type.GetType("Mono.Runtime");
if (runtime != null)
try
{
// C:\Program Files(x86)\Mono\lib\mono\4.5\*.dll
// C:\Program Files(x86)\Mono\lib\mono
return Path.GetDirectoryName(Path.GetDirectoryName(runtime.Assembly.Location));
}
catch { }
return null;
}
}
public static string[] MonoGAC
{
get
{
try
{
// C:\Program Files(x86)\Mono\lib\mono\gac
var gacDir = Path.Combine(MonoRootDir, "gac");
return Directory.GetDirectories(gacDir).Select(x => Path.GetFileName(x)).ToArray();
}
catch { }
return new string[0];
}
}
public static Assembly AssemblyLoad(string asmFile)
{
try
{
return Assembly.LoadFrom(asmFile);
}
catch (FileNotFoundException e)
{
if (!Utils.IsMono)
throw e;
else
try
{
// GAC assemblies on Mono are returned as asm partial name not a file path.
// So file_not_found failures are expected so try load by name.
return Assembly.Load(asmFile);
}
catch
{
throw e;
}
}
}
public static string DbgFileOf(string assemblyFileName)
{
return DbgFileOf(assemblyFileName, IsMono);
}
internal static string DbgFileOf(string assemblyFileName, bool is_mono)
{
// .NET changes the asm extension to '.pdb'
// Mono adds '.mdb' to the asm file name
if (is_mono)
return assemblyFileName + ".mdb";
else
return Path.ChangeExtension(assemblyFileName, ".pdb");
}
public static bool ContainsPath(string path, string subPath)
{
return path.Substring(0, subPath.Length).IsSamePath(subPath);
}
public static bool IsNullOrWhiteSpace(string text)
{
#if net4
return string.IsNullOrWhiteSpace(text);
#else
return text == null || text.Trim() == "";
#endif
}
/// <summary>
/// Adds compiler options to the CompilerParameters in a manner that it does separate every option by the space character
/// </summary>
static public void AddCompilerOptions(CompilerParameters compilerParams, string option)
{
compilerParams.CompilerOptions += option + " ";
}
}
internal static class CSSUtils
{
internal static void VerbosePrint(this string message, ExecuteOptions options)
{
if (options.verbose)
Console.WriteLine(message);
}
public static string DbgInjectionCode = DbgInjectionCodeInterface;
internal static string DbgInjectionCodeInterface = @"// Auto-generated file
public static class dbg_extensions
{
static public T dump<T>(this T @object, params object[] args)
{
dbg.print(@object, args);
return @object;
}
static public T print<T>(this T @object, params object[] args)
{
dbg.print(@object, args);
return @object;
}
}
partial class dbg
{
public static bool publicOnly = true;
public static bool propsOnly = false;
public static int max_items = 25;
public static int depth = 1;
public static void printf(string format, params object[] args) { }
public static void print(object @object, params object[] args) { }
}";
internal static string CreateDbgInjectionInterfaceCode(string scriptFileName)
{
var file = CSExecutor.GetScriptTempDir().PathCombine("Cache", "dbg.cs");
try { File.WriteAllText(file, DbgInjectionCodeInterface); }
catch { }
return file;
}
internal static string GetScriptedCodeDbgInjectionCode(string scriptFileName)
{
if (DbgInjectionCode == null)
return null;
string dbg_injection_version = DbgInjectionCode.GetHashCode().ToString();
using (SystemWideLock fileLock = new SystemWideLock("CS-Script.dbg.injection", dbg_injection_version))
{
//Infinite timeout is not good choice here as it may block forever but continuing while the file is still locked will
//throw a nice informative exception.
if (!Utils.IsLinux)
fileLock.Wait(1000);
var cache_dir = Path.Combine(CSExecutor.GetScriptTempDir(), "Cache");
var dbg_file = Path.Combine(cache_dir, "dbg.inject." + dbg_injection_version + ".cs");
var dbg_interface_file = Path.Combine(cache_dir, "dbg.cs");
if (!File.Exists(dbg_file))
File.WriteAllText(dbg_file, DbgInjectionCode);
CreateDbgInjectionInterfaceCode(scriptFileName);
foreach (var item in Directory.GetFiles(cache_dir, "dbg.inject.*.cs"))
if (item != dbg_file)
try
{
File.Delete(item);
}
catch { }
return dbg_file;
}
}
internal static string GetScriptedCodeAttributeInjectionCode(string scriptFileName)
{
using (SystemWideLock fileLock = new SystemWideLock(scriptFileName, "attr"))
{
//Infinite timeout is not good choice here as it may block forever but continuing while the file is still locked will
//throw a nice informative exception.
if (Utils.IsWin)
fileLock.Wait(1000);
string code = string.Format("[assembly: System.Reflection.AssemblyDescriptionAttribute(@\"{0}\")]", scriptFileName);
string currentCode = "";
string file = Path.Combine(CSExecutor.GetCacheDirectory(scriptFileName), Path.GetFileNameWithoutExtension(scriptFileName) + ".attr.g.cs");
Exception lastError = null;
for (int i = 0; i < 3; i++)
{
try
{
if (File.Exists(file))
using (StreamReader sr = new StreamReader(file))
currentCode = sr.ReadToEnd();
if (currentCode != code)
{
string dir = Path.GetDirectoryName(file);
if (!Directory.Exists(dir))
Directory.CreateDirectory(dir);
using (StreamWriter sw = new StreamWriter(file)) //there were reports about the files being locked. Possibly by csc.exe so allow retry
{
sw.Write(code);
}
}
break;
}
catch (Exception e)
{
lastError = e;
}
Thread.Sleep(200);
}
if (!File.Exists(file))
throw new ApplicationException("Failed to create AttributeInjection file", lastError);
return file;
}
}
public static bool HaveSameTimestamp(string file1, string file2)
{
FileInfo info1 = new FileInfo(file1);
FileInfo info2 = new FileInfo(file2);
return (info2.LastWriteTime == info1.LastWriteTime &&
info2.LastWriteTimeUtc == info1.LastWriteTimeUtc);
}
public static void SetTimestamp(string fileDest, string fileSrc)
{
FileInfo info1 = new FileInfo(fileSrc);
FileInfo info2 = new FileInfo(fileDest);
try
{
info2.LastWriteTime = info1.LastWriteTime;
info2.LastWriteTimeUtc = info1.LastWriteTimeUtc;
}
catch
{
//On Linux it may fail for no obvious reason
}
}
/// <summary>
/// Compiles ResX file into .resources
/// </summary>
public static string CompileResource(string file, string out_name)
{
var resgen_exe = "ResGen.exe";
var input = file;
var output = Path.ChangeExtension(file, ".resources");
if (out_name != null)
output = Path.Combine(Path.GetDirectoryName(file), out_name);
string css_dir_res_gen = Environment.ExpandEnvironmentVariables(@"%CSSCRIPT_DIR%\lib\resgen.exe");
string user_res_gen = Environment.GetEnvironmentVariable("CSS_RESGEN");
if (File.Exists(user_res_gen))
resgen_exe = user_res_gen;
else if (File.Exists(css_dir_res_gen))
resgen_exe = css_dir_res_gen;
var error = new StringBuilder();
try
{
var proc = new Process();
proc.StartInfo.FileName = resgen_exe;
proc.StartInfo.Arguments = "\"" + input + "\" \"" + output + "\"";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.WorkingDirectory = Path.GetDirectoryName(input);
proc.Start();
string line = null;
while (null != (line = proc.StandardError.ReadLine()))
error.AppendLine(line);
proc.WaitForExit();
}
catch (Exception e)
{
if (!File.Exists(css_dir_res_gen))
throw new ApplicationException("Cannot invoke " + resgen_exe + ": " + e.Message +
"\nEnsure resgen.exe is in the %CSSCRIPT_DIR%\\lib or " +
"its location is in the system PATH. Alternatively you " +
"can specify the direct location of resgen.exe via " +
"CSS_RESGEN environment variable.");
}
if (error.Length > 0)
throw new ApplicationException("Cannot compile resources: " + error);
return output;
}
public delegate void ShowDocumentHandler();
static public string[] GetDirectories(string workingDir, string rootDir)
{
if (!Path.IsPathRooted(rootDir))
rootDir = Path.Combine(workingDir, rootDir); //cannot use Path.GetFullPath as it crashes if '*' or '?' are present
List<string> result = new List<string>();
if (rootDir.Contains("*") || rootDir.Contains("?"))
{
bool useAllSubDirs = rootDir.EndsWith("**");
string pattern = ConvertSimpleExpToRegExp(useAllSubDirs ? rootDir.Remove(rootDir.Length - 1) : rootDir);
Regex wildcard = new Regex(pattern, RegexOptions.IgnoreCase);
int pos = rootDir.IndexOfAny(new char[] { '*', '?' });
string newRootDir = rootDir.Remove(pos);
pos = newRootDir.LastIndexOf(Path.DirectorySeparatorChar);
newRootDir = rootDir.Remove(pos);
if (Directory.Exists(newRootDir))
{
foreach (string dir in Directory.GetDirectories(newRootDir, "*", SearchOption.AllDirectories))
if (wildcard.IsMatch(dir))
{
if (!result.Contains(dir))
{
result.Add(dir);
if (useAllSubDirs)
foreach (string subDir in Directory.GetDirectories(dir, "*", SearchOption.AllDirectories))
//if (!result.Contains(subDir))
result.Add(subDir);
}
}
}
}
else
result.Add(rootDir);
return result.ToArray();
}
//Credit to MDbg team: https://github.com/SymbolSource/Microsoft.Samples.Debugging/blob/master/src/debugger/mdbg/mdbgCommands.cs
public static string ConvertSimpleExpToRegExp(string simpleExp)
{
StringBuilder sb = new StringBuilder();
sb.Append("^");
foreach (char c in simpleExp)
{
switch (c)
{
case '\\':
case '{':
case '|':
case '+':
case '[':
case '(':
case ')':
case '^':
case '$':
case '.':
case '#':
case ' ':
sb.Append('\\').Append(c);
break;
case '*':
sb.Append(".*");
break;
case '?':
sb.Append(".");
break;
default:
sb.Append(c);
break;
}
}
sb.Append("$");
return sb.ToString();
}
internal class Args
{
static internal string Join(params string[] args)
{
StringBuilder sb = new StringBuilder();
foreach (string arg in args)
{
sb.Append(" ");
sb.Append("-");
sb.Append(arg);
}
return sb.ToString().Trim();
}
static internal string DefaultPrefix
{
get
{
if (Utils.IsLinux)
return "-";
else
return "/";
}
}
public static bool Same(string arg, params string[] patterns)
{
foreach (string pattern in patterns)
{
if (arg.StartsWith("-"))
if (arg.Length == pattern.Length + 1 && arg.IndexOf(pattern) == 1)
return true;
if (Utils.IsWin && arg[0] == '/')
if (arg.Length == pattern.Length + 1 && arg.IndexOf(pattern) == 1)
return true;
}
return false;
}
public static bool IsArg(string arg)
{
if (arg.StartsWith("-"))
return true;
if (Utils.IsWin)
return (arg[0] == '/');
return false;
}
public static bool StartsWith(string arg, string pattern)
{
if (arg.StartsWith("-"))
return arg.IndexOf(pattern) == 1;
if (Utils.IsWin)
if (arg[0] == '/')
return arg.IndexOf(pattern) == 1;
return false;
}
public static string ArgValue(string arg, string pattern)
{
return arg.Substring(pattern.Length + 1);
}
public static bool ParseValuedArg(string arg, string pattern, out string value)
{
value = null;
if (Args.Same(arg, pattern))
return true;
pattern += ":";
if (Args.StartsWith(arg, pattern))
{
value = Args.ArgValue(arg, pattern);
return true;
}
return false;
}
public static bool ParseValuedArg(string arg, string pattern, string pattern2, out string value)
{
value = null;
if (ParseValuedArg(arg, pattern, out value))
return true;
if (ParseValuedArg(arg, pattern2, out value))
return true;
return false;
}
// detects pseudo arguments - script files named as args (e.g. '-update')
// disabled as currently every arg that starts with '-' is treated as scripted arg (script file)
// public static bool IsScriptedArg(string arg)
// {
// var rootDir = Path.GetFullPath(Assembly.GetExecutingAssembly().Location());
// if (!string.IsNullOrEmpty(rootDir))