Repository navigation
Expand file tree
/
Copy pathFileSystemDependencyResolver.cs
More file actions
334 lines (282 loc) · 12.2 KB
/
Copy pathFileSystemDependencyResolver.cs
File metadata and controls
334 lines (282 loc) · 12.2 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
333
334
/*----------------------------------------------------------
This Source Code Form is subject to the terms of the
Mozilla Public License, v.2.0. If a copy of the MPL
was not distributed with this file, You can obtain one
at http://mozilla.org/MPL/2.0/.
----------------------------------------------------------*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using OneScript.Compilation;
using OneScript.Exceptions;
using OneScript.Execution;
using OneScript.Localization;
using OneScript.Sources;
namespace ScriptEngine.HostedScript
{
public class FileSystemDependencyResolver : IDependencyResolver
{
public const string PREDEFINED_LOADER_FILE = "package-loader.os";
private readonly List<Library> _libs = new List<Library>();
private LibraryLoader _defaultLoader;
private object _defaultLoaderLocker = new object();
private string _libraryRoot;
#region Private classes
private class Library
{
public string id;
public ProcessingState state;
public LibraryLoader customLoader;
public PackageInfo loadingResult;
}
private enum ProcessingState
{
Discovered,
Processed
}
private enum LoadStatus
{
NotFound, // Каталог библиотеки не существует
Empty, // Каталог найден, но библиотека не содержит исполняемых файлов
Success // Библиотека успешно загружена
}
private class LoadResult
{
public PackageInfo Package { get; set; }
public LoadStatus Status { get; set; }
public static LoadResult NotFound() => new LoadResult { Status = LoadStatus.NotFound };
public static LoadResult Empty() => new LoadResult { Status = LoadStatus.Empty };
public static LoadResult Success(PackageInfo package) => new LoadResult
{
Status = LoadStatus.Success,
Package = package
};
}
#endregion
public FileSystemDependencyResolver()
{
}
public IList<string> SearchDirectories { get;} = new List<string>();
public string LibraryRoot
{
get
{
if (_libraryRoot == null)
_libraryRoot = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
return _libraryRoot;
}
set
{
if (string.IsNullOrWhiteSpace(value))
{
_libraryRoot = null;
}
_libraryRoot = value;
}
}
private ScriptingEngine Engine { get; set; }
public void Initialize(ScriptingEngine engine)
{
Engine = engine;
}
public PackageInfo Resolve(SourceCode module, string libraryName, IBslProcess process)
{
bool quoted = PrepareQuoted(ref libraryName);
var result = quoted ?
LoadByRelativePath(module, libraryName, process) :
LoadByName(libraryName, process);
if (result.Status == LoadStatus.NotFound)
{
throw new CompilerException($"Библиотека не найдена: '{libraryName}'");
}
else if (result.Status == LoadStatus.Empty)
{
throw new CompilerException(
$"Библиотека '{libraryName}' найдена, но не содержит исполняемых файлов.\n" +
"Для получения подробной информации установите переменную окружения OS_LIBRARY_LOADER_TRACE=1");
}
return result.Package;
}
private LoadResult LoadByName(string libraryName, IBslProcess process)
{
foreach (var path in SearchDirectories)
{
if(!Directory.Exists(path))
continue;
var libraryPath = Path.Combine(path, libraryName);
var result = LoadByPath(libraryPath, process);
// Если библиотека найдена (успешно загружена или пуста), сразу возвращаем
// Не ищем дальше, так как это более приоритетный путь
if (result.Status != LoadStatus.NotFound)
return result;
}
// Если в SearchDirectories ничего не нашли, проверяем rootPath
var rootPath = Path.Combine(LibraryRoot, libraryName);
return LoadByPath(rootPath, process);
}
private LoadResult LoadByRelativePath(SourceCode module, string libraryPath, IBslProcess process)
{
string realPath;
if (!Path.IsPathRooted(libraryPath) && module.Location != null)
{
var currentPath = module.Location;
// Загружаем относительно текущего скрипта, однако,
// если CurrentScript не файловый (TestApp или другой хост), то загружаем относительно рабочего каталога.
// немного костыльно, ага ((
//
if (!PathHasInvalidChars(currentPath))
realPath = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(currentPath), libraryPath));
else
realPath = libraryPath;
}
else
{
realPath = libraryPath;
}
return LoadByPath(realPath, process);
}
private LibraryLoader CreateDefaultLoader(IBslProcess process)
{
var loaderscript = Path.Combine(LibraryRoot, PREDEFINED_LOADER_FILE);
return File.Exists(loaderscript) ?
LibraryLoader.Create(Engine, loaderscript, process)
: LibraryLoader.Create(Engine, process);
}
private LibraryLoader GetDefaultLoader(IBslProcess process)
{
if (_defaultLoader != default)
return _defaultLoader;
lock (_defaultLoaderLocker)
{
if (_defaultLoader == default)
{
_defaultLoader = CreateDefaultLoader(process);
}
}
return _defaultLoader;
}
private bool PrepareQuoted(ref string value)
{
const string COMMENT = "//";
const char QUOTE = '"';
bool quoted = false;
if (value.IndexOf(QUOTE)==0)
{
var secondQuote = value.Substring(1).IndexOf(QUOTE);
if (secondQuote > 0)
{
if (secondQuote+2 < value.Length)
{
var tail = value.Substring(secondQuote+2, value.Length-secondQuote-2).TrimStart();
if (!string.IsNullOrWhiteSpace(tail) && tail.IndexOf(COMMENT, StringComparison.Ordinal) != 0)
throw new CompilerException($"Недопустимые символы после имени библиотеки: '{tail}'");
}
value = value.Substring(1, secondQuote);
quoted = true;
}
else
{
throw new CompilerException($"Ошибка в имени библиотеки: '{value}'");
}
}
else
{
var comment = value.IndexOf(COMMENT, StringComparison.Ordinal);
if( comment>=0 )
{
value = value.Substring(0,comment).TrimEnd();
}
}
if (String.IsNullOrWhiteSpace(value))
throw new CompilerException("Отсутствует имя библиотеки");
return quoted;
}
private LoadResult LoadByPath(string libraryPath, IBslProcess process)
{
if (!Directory.Exists(libraryPath))
return LoadResult.NotFound();
var package = LoadLibraryInternal(libraryPath, process);
return package == null
? LoadResult.Empty()
: LoadResult.Success(package);
}
private PackageInfo LoadLibraryInternal(string libraryPath, IBslProcess process)
{
// Библиотеки грузятся по одной: иначе поток, которому нужна библиотека, загружаемая
// сейчас в другом потоке, принимает ее за циклическую зависимость или грузит повторно.
// Вложенные #Использовать грузятся в том же потоке, блокировка их пропускает
lock (_libs)
{
return DoLoadLibrary(libraryPath, process);
}
}
private PackageInfo DoLoadLibrary(string libraryPath, IBslProcess process)
{
var id = GetLibraryId(libraryPath);
var existedLib = _libs.FirstOrDefault(x => x.id == id);
if(existedLib != null)
{
if (existedLib.state == ProcessingState.Discovered)
{
string libStack = ListToStringStack(_libs, id);
throw new DependencyResolveException(
new BilingualString(
$"Ошибка загрузки библиотеки {id}. Обнаружены циклические зависимости.\n",
$"Error loading library {id}. Circular dependencies found.\n") + libStack);
}
return existedLib.loadingResult;
}
var newLib = new Library() { id = id, state = ProcessingState.Discovered };
var customLoaderFile = Path.Combine(libraryPath, PREDEFINED_LOADER_FILE);
if (File.Exists(customLoaderFile))
newLib.customLoader = LibraryLoader.Create(Engine, customLoaderFile, process);
PackageInfo package;
try
{
_libs.Add(newLib);
package = ProcessLibrary(newLib, process);
newLib.state = ProcessingState.Processed;
newLib.loadingResult = package;
}
catch (Exception)
{
_libs.Remove(newLib);
throw;
}
return package;
}
private PackageInfo ProcessLibrary(Library lib, IBslProcess process)
{
LibraryLoader loader;
if (lib.customLoader != null)
loader = lib.customLoader;
else
loader = GetDefaultLoader(process);
return loader.ProcessLibrary(lib.id, process);
}
private static string ListToStringStack(IEnumerable<Library> libs, string stopToken)
{
var builder = new StringBuilder();
string offset = "";
foreach (var library in libs)
{
builder.Append(offset);
builder.Append("-> ");
builder.AppendLine(library.id);
offset += " ";
offset += " ";
}
return builder.ToString();
}
private static string GetLibraryId(string libraryPath)
{
return Path.GetFullPath(libraryPath);
}
private static bool PathHasInvalidChars(string path)
{
return (!string.IsNullOrEmpty(path) && path.IndexOfAny(Path.GetInvalidPathChars()) >= 0);
}
}
}