forked from EvilBeaver/OneScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCodeSources.cs
More file actions
108 lines (87 loc) · 2.86 KB
/
CodeSources.cs
File metadata and controls
108 lines (87 loc) · 2.86 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
/*----------------------------------------------------------
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.Text;
using System.IO;
namespace ScriptEngine.Environment
{
class StringBasedSource : ICodeSource
{
readonly string _src;
public StringBasedSource(string src)
{
_src = src;
}
#region ICodeSource Members
string ICodeSource.Code
{
get
{
return _src;
}
}
string ICodeSource.SourceDescription => $"<string {_src.GetHashCode().ToString("X8")}>" ;
#endregion
}
class FileBasedSource : ICodeSource
{
readonly string _path;
string _code;
readonly Encoding _noBomEncoding;
public FileBasedSource(string path, Encoding defaultEncoding)
{
_path = System.IO.Path.GetFullPath(path);
_noBomEncoding = defaultEncoding;
}
private string GetCodeString()
{
if (_code == null)
{
using (var fStream = new FileStream(_path, FileMode.Open, FileAccess.Read))
{
var buf = new byte[2];
fStream.Read(buf, 0, 2);
Encoding enc = null;
bool skipShebang = false;
if (IsLinuxScript(buf))
{
enc = Encoding.UTF8; // скрипты с shebang считать в формате UTF-8
skipShebang = true;
}
else
{
fStream.Position = 0;
enc = FileOpener.AssumeEncoding(fStream, _noBomEncoding);
}
using (var reader = new StreamReader(fStream, enc))
{
if (skipShebang)
reader.ReadLine();
_code = reader.ReadToEnd();
}
}
}
return _code;
}
private static bool IsLinuxScript(byte[] buf)
{
return buf[0] == '#' && buf[1] == '!';
}
#region ICodeSource Members
string ICodeSource.Code
{
get
{
return GetCodeString();
}
}
string ICodeSource.SourceDescription
{
get { return _path[0].ToString().ToUpperInvariant() + _path.Substring(1); }
}
#endregion
}
}