forked from EvilBeaver/OneScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileCodeSource.cs
More file actions
69 lines (60 loc) · 2.07 KB
/
FileCodeSource.cs
File metadata and controls
69 lines (60 loc) · 2.07 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
/*----------------------------------------------------------
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.IO;
using System.Text;
using OneScript.Commons;
using System;
using OneScript.Language.Sources;
namespace OneScript.Sources
{
public class FileCodeSource : ICodeSource
{
private readonly string _path;
private readonly Encoding _noBomEncoding;
public FileCodeSource(string path, Encoding defaultEncoding)
{
_path = Path.GetFullPath(path);
_noBomEncoding = defaultEncoding;
}
public FileCodeSource(string path)
{
_path = path;
_noBomEncoding = Encoding.UTF8;
}
public string GetSourceCode()
{
using (var fStream = new FileStream(_path, FileMode.Open, FileAccess.Read))
{
var buf = new byte[2];
fStream.Read(buf, 0, 2);
Encoding enc;
var 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();
return reader.ReadToEnd();
}
}
}
private static bool IsLinuxScript(byte[] buf)
{
return buf[0] == '#' && buf[1] == '!';
}
public string Location => string.Concat(_path[0].ToString().ToUpperInvariant(), _path.AsSpan(1));
}
}