forked from IronLanguages/dlr
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPlatformAdaptationLayer.cs
More file actions
332 lines (281 loc) · 11 KB
/
PlatformAdaptationLayer.cs
File metadata and controls
332 lines (281 loc) · 11 KB
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
#nullable enable
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Microsoft.Scripting.Utils;
namespace Microsoft.Scripting {
#if !FEATURE_PROCESS
public class ExitProcessException : Exception {
public int ExitCode { get { return exitCode; } }
int exitCode;
public ExitProcessException(int exitCode) {
this.exitCode = exitCode;
}
}
#endif
/// <summary>
/// Abstracts system operations that are used by DLR and could potentially be platform specific.
/// The host can implement its PAL to adapt DLR to the platform it is running on.
/// For example, the Silverlight host adapts some file operations to work against files on the server.
/// </summary>
[Serializable]
public class PlatformAdaptationLayer {
public static readonly PlatformAdaptationLayer Default = new();
[Obsolete("This will be removed in the the future.")]
public static readonly bool IsCompactFramework = false;
public static bool IsNativeModule { get; } = _IsNativeModule();
private static bool _IsNativeModule() {
return typeof(void).Assembly.Modules.FirstOrDefault()?.ToString() == "<Unknown>";
}
#region Assembly Loading
public virtual Assembly LoadAssembly(string name) {
return Assembly.Load(name);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods", MessageId = "System.Reflection.Assembly.LoadFile")]
public virtual Assembly LoadAssemblyFromPath(string path) {
#if FEATURE_FILESYSTEM
return Assembly.LoadFile(path);
#else
throw new NotImplementedException();
#endif
}
public virtual void TerminateScriptExecution(int exitCode) {
#if FEATURE_PROCESS
System.Environment.Exit(exitCode);
#else
throw new ExitProcessException(exitCode);
#endif
}
#endregion
#region Virtual File System
public virtual bool IsSingleRootFileSystem {
get {
#if FEATURE_FILESYSTEM
return Environment.OSVersion.Platform == PlatformID.Unix
|| Environment.OSVersion.Platform == PlatformID.MacOSX;
#else
return true;
#endif
}
}
public virtual StringComparer PathComparer {
get {
#if FEATURE_FILESYSTEM
return Environment.OSVersion.Platform == PlatformID.Unix ? StringComparer.Ordinal : StringComparer.OrdinalIgnoreCase;
#else
return StringComparer.OrdinalIgnoreCase;
#endif
}
}
public virtual bool FileExists(string path) {
#if FEATURE_FILESYSTEM
return File.Exists(path);
#else
throw new NotImplementedException();
#endif
}
public virtual bool DirectoryExists(string path) {
#if FEATURE_FILESYSTEM
return Directory.Exists(path);
#else
throw new NotImplementedException();
#endif
}
// TODO: better APIs
public virtual Stream OpenFileStream(string path, FileMode mode = FileMode.OpenOrCreate, FileAccess access = FileAccess.ReadWrite, FileShare share = FileShare.Read, int bufferSize = 8192) {
#if FEATURE_FILESYSTEM
if (string.Equals("nul", path, StringComparison.InvariantCultureIgnoreCase)) {
return Stream.Null;
}
return new FileStream(path, mode, access, share, bufferSize);
#else
throw new NotImplementedException();
#endif
}
// TODO: better APIs
public virtual Stream OpenInputFileStream(string path, FileMode mode = FileMode.Open, FileAccess access = FileAccess.Read, FileShare share = FileShare.Read, int bufferSize = 8192) {
return OpenFileStream(path, mode, access, share, bufferSize);
}
// TODO: better APIs
public virtual Stream OpenOutputFileStream(string path) {
return OpenFileStream(path, FileMode.Create, FileAccess.Write);
}
public virtual void DeleteFile(string path, bool deleteReadOnly) {
#if FEATURE_FILESYSTEM
FileInfo info = new FileInfo(path);
if (deleteReadOnly && info.IsReadOnly) {
info.IsReadOnly = false;
}
info.Delete();
#else
throw new NotImplementedException();
#endif
}
public string[] GetFiles(string path, string searchPattern) {
return GetFileSystemEntries(path, searchPattern, true, false);
}
public string[] GetDirectories(string path, string searchPattern) {
return GetFileSystemEntries(path, searchPattern, false, true);
}
public string[] GetFileSystemEntries(string path, string searchPattern) {
return GetFileSystemEntries(path, searchPattern, true, true);
}
public virtual string[] GetFileSystemEntries(string path, string searchPattern, bool includeFiles, bool includeDirectories) {
#if FEATURE_FILESYSTEM
// workaround for bug in .NET Framework 4.6.2 - https://github.com/IronLanguages/ironpython3/pull/1601
if (path == ".") {
path += Path.DirectorySeparatorChar;
}
if (includeFiles && includeDirectories) {
return Directory.GetFileSystemEntries(path, searchPattern);
}
if (includeFiles) {
return Directory.GetFiles(path, searchPattern);
}
if (includeDirectories) {
return Directory.GetDirectories(path, searchPattern);
}
return ArrayUtils.EmptyStrings;
#else
throw new NotImplementedException();
#endif
}
/// <exception cref="ArgumentException">Invalid path.</exception>
public virtual string GetFullPath(string path) {
#if FEATURE_FILESYSTEM
try {
return Path.GetFullPath(path);
} catch (Exception) {
throw Error.InvalidPath();
}
#else
throw new NotImplementedException();
#endif
}
public virtual string CombinePaths(string path1, string path2) {
return Path.Combine(path1, path2);
}
public virtual string? GetFileName(string? path) {
return Path.GetFileName(path);
}
public virtual string? GetDirectoryName(string? path) {
return Path.GetDirectoryName(path);
}
public virtual string? GetExtension(string? path) {
return Path.GetExtension(path);
}
public virtual string? GetFileNameWithoutExtension(string? path) {
return Path.GetFileNameWithoutExtension(path);
}
/// <exception cref="ArgumentException">Invalid path.</exception>
public virtual bool IsAbsolutePath(string path) {
#if FEATURE_FILESYSTEM
// GetPathRoot returns either :
// "" -> relative to the current dir
// "\" -> relative to the drive of the current dir
// "X:" -> relative to the current dir, possibly on a different drive
// "X:\" -> absolute
if (IsSingleRootFileSystem) {
return Path.IsPathRooted(path);
}
string? root = Path.GetPathRoot(path);
return root is not null && (root.EndsWith(@":\", StringComparison.Ordinal) || root.EndsWith(@":/", StringComparison.Ordinal));
#else
throw new NotImplementedException();
#endif
}
public virtual string CurrentDirectory {
get {
#if FEATURE_FILESYSTEM
return Directory.GetCurrentDirectory();
#else
throw new NotImplementedException();
#endif
}
set {
#if FEATURE_FILESYSTEM
Directory.SetCurrentDirectory(value);
#else
throw new NotImplementedException();
#endif
}
}
public virtual void CreateDirectory(string path) {
#if FEATURE_FILESYSTEM
Directory.CreateDirectory(path);
#else
throw new NotImplementedException();
#endif
}
public virtual void DeleteDirectory(string path, bool recursive) {
#if FEATURE_FILESYSTEM
Directory.Delete(path, recursive);
#else
throw new NotImplementedException();
#endif
}
public virtual void MoveFileSystemEntry(string sourcePath, string destinationPath) {
#if FEATURE_FILESYSTEM
Directory.Move(sourcePath, destinationPath);
#else
throw new NotImplementedException();
#endif
}
#endregion
#region Environmental Variables
public virtual string? GetEnvironmentVariable(string key) {
#if FEATURE_PROCESS
return Environment.GetEnvironmentVariable(key);
#else
throw new NotImplementedException();
#endif
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2201:DoNotRaiseReservedExceptionTypes")]
public virtual void SetEnvironmentVariable(string key, string? value) {
#if FEATURE_PROCESS
if (value is not null && value.Length == 0) {
SetEmptyEnvironmentVariable(key);
} else {
Environment.SetEnvironmentVariable(key, value);
}
#else
throw new NotImplementedException();
#endif
}
#if FEATURE_PROCESS
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2201:DoNotRaiseReservedExceptionTypes")]
[MethodImpl(MethodImplOptions.NoInlining)]
private static void SetEmptyEnvironmentVariable(string key) {
// System.Environment.SetEnvironmentVariable interprets an empty value string as
// deleting the environment variable. So we use the native SetEnvironmentVariable
// function here which allows setting of the value to an empty string.
// This will require high trust and will fail in sandboxed environments
if (!NativeMethods.SetEnvironmentVariable(key, String.Empty)) {
throw new ExternalException("SetEnvironmentVariable failed", Marshal.GetLastWin32Error());
}
}
#endif
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
public virtual Dictionary<string, string> GetEnvironmentVariables() {
#if FEATURE_PROCESS
var result = new Dictionary<string, string>();
foreach (DictionaryEntry entry in Environment.GetEnvironmentVariables())
{
result.Add((string)entry.Key, (entry.Value is string value) ? value : string.Empty);
}
return result;
#else
throw new NotImplementedException();
#endif
}
#endregion
}
}