forked from EvilBeaver/OneScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSerializeModuleBehavior.cs
More file actions
96 lines (82 loc) · 3 KB
/
SerializeModuleBehavior.cs
File metadata and controls
96 lines (82 loc) · 3 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
/*----------------------------------------------------------
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 System.Threading.Tasks;
using Newtonsoft.Json;
using ScriptEngine;
using ScriptEngine.HostedScript;
namespace oscript
{
internal class SerializeModuleBehavior : AppBehavior
{
private readonly string _path;
public SerializeModuleBehavior(string path)
{
_path = path;
}
public override int Execute()
{
var engine = new HostedScriptEngine
{
CustomConfig = ScriptFileHelper.CustomConfigPath(_path)
};
engine.Initialize();
ScriptFileHelper.OnBeforeScriptRead(engine);
var source = engine.Loader.FromFile(_path);
var compiler = engine.GetCompilerService();
engine.SetGlobalEnvironment(new DoNothingHost(), source);
var entry = compiler.Compile(source);
var embeddedContext = engine.GetExternalLibraries();
var serializer = new JsonSerializer();
var sb = new StringBuilder();
using (var textWriter = new StringWriter(sb))
{
var writer = new JsonTextWriter(textWriter);
writer.WriteStartArray();
WriteImage(new UserAddedScript
{
Type = UserAddedScriptType.Module,
Symbol = "$entry",
Image = entry
}, writer, serializer);
foreach (var item in embeddedContext)
{
item.Classes.ForEach(x => WriteImage(x, writer, serializer));
item.Modules.ForEach(x => WriteImage(x, writer, serializer));
}
writer.WriteEndArray();
}
string result = sb.ToString();
Output.WriteLine(result);
return 0;
}
private void WriteImage(UserAddedScript script, JsonTextWriter writer, JsonSerializer serializer)
{
writer.WriteStartObject();
writer.WritePropertyName("name");
writer.WriteValue(script.Symbol);
writer.WritePropertyName("type");
writer.WriteValue(script.Type.ToString());
writer.WritePropertyName("image");
serializer.Serialize(writer, script.Image);
writer.WriteEndObject();
}
public static AppBehavior Create(CmdLineHelper helper)
{
var path = helper.Next();
if (path != null)
{
return new SerializeModuleBehavior(path);
}
return new ShowUsageBehavior();
}
}
}