/
Shell.pas
290 lines (272 loc) · 11.5 KB
/
Shell.pas
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
namespace RemObjects.Train.API;
interface
uses RemObjects.Train,
System.Collections.Generic, System.Diagnostics, RemObjects.Script.EcmaScript;
type
[PluginRegistration]
ShellRegistration = public class(IPluginRegistration)
private
public
method &Register(aServices: IApiRegistrationServices);
end;
Shell = public class
private
fEngine: IApiRegistrationServices;
public
class method ExecuteProcess(aCommand, aArgs, AWD: String; aComSpec: Boolean; aTargetError: Action<String>; aTargetOutput: Action<String>; environment: array of KeyValuePair<String, String>; aTimeout: nullable TimeSpan): Integer;
constructor(aItem: IApiRegistrationServices);
method Exec(ec: RemObjects.Script.EcmaScript.ExecutionContext; aSelf: Object; args: array of Object): Object;
method ExecAsync(ec: RemObjects.Script.EcmaScript.ExecutionContext; aSelf: Object; args: array of Object): Object;
method INTSystem(ec: RemObjects.Script.EcmaScript.ExecutionContext; aSelf: Object; args: array of Object): Object;
end;
implementation
method Shell.Exec(ec: RemObjects.Script.EcmaScript.ExecutionContext; aSelf: Object; args: array of Object): Object;
begin
var lCMD := fEngine.ResolveWithBase(ec, Utilities.GetArgAsString(args, 0, ec), true);
var lFail := true;
var lArg := fEngine.Expand(ec, Utilities.GetArgAsString(args, 1, ec));
var lOpt := Utilities.GetArgAsEcmaScriptObject(args, 2, ec);
var lEnv := new List<KeyValuePair<String, String>>;
var lTimeout: nullable TimeSpan := nil;
var lCaptureMode: Boolean := false;
var lCaptureFunc: EcmaScriptBaseFunctionObject := nil;
var LWD: String := nil;
if lOpt <> nil then begin
var lVal := lOpt.Get('capture');
if (lVal <> nil) and (lVal <> Undefined.Instance) then begin
lCaptureFunc := EcmaScriptBaseFunctionObject(lVal);
if (lCaptureFunc = nil) and (Utilities.GetObjAsBoolean(lVal, ec)) then begin
lCaptureMode := true;
end;
end;
lVal := lOpt.Get('workdir');
if lVal is String then
LWD := fEngine.ResolveWithBase(ec,String (lVal), true);
lVal := lOpt.Get('timeout');
if (lVal <> nil) and (lVal <> Undefined.Instance) then
lTimeout := TimeSpan.FromSeconds(Utilities.GetObjAsInteger(lVal, ec));
lVal := lOpt.Get('environment');
var lObj := EcmaScriptObject(lVal);
if lObj <> nil then begin
for each el in lObj.Values do begin
lEnv.Add(new KeyValuePair<String,String>(el.Key, Utilities.GetObjAsString(el.Value.Value, ec)));
end;
end;
end;
fEngine.Engine.Logger.Enter(true,'shell.exec', lCMD+if not String.IsNullOrEmpty(lArg) then ' '+ lArg else '');
try
if fEngine.Engine.DryRun then begin
fEngine.Engine.Logger.LogMessage('Dry run.');
exit '';
end;
var sb := new System.Text.StringBuilder;
var lExit := ExecuteProcess(lCMD, lArg, coalesce(LWD, fEngine.Engine.WorkDir),false , a-> begin
locking(sb) do begin
sb.AppendLine(a);
end;
if assigned(lCaptureFunc) then begin
try
lCaptureFunc.Call(ec, a);
except
end;
end;
end, a-> begin
locking(sb) do sb.AppendLine(a);
if assigned(lCaptureFunc) then begin
try
lCaptureFunc.Call(ec, a);
except
end;
end;
end, lEnv.ToArray, lTimeout);
if 0 <> lExit then begin
var lErr := 'Failed with error code: '+lExit;
fEngine.Engine.Logger.LogError(lErr);
fEngine.Engine.Logger.LogMessage('Output: '#13#10+sb.ToString);
raise new Exception(lErr);
end;
fEngine.Engine.Logger.LogInfo('Output: '#13#10+sb.ToString);
lFail := false;
if lCaptureMode then
exit sb.ToString()
else
exit Undefined.Instance;
except
on e: Exception do begin
fEngine.Engine.Logger.LogError('Error when calling Process.Execute: '+e.Message);
raise new AbortException;
end;
finally
fEngine.Engine.Logger.Exit(true,String.Format('shell.exec({0})', lCMD), if lFail then RemObjects.Train.FailMode.Yes else RemObjects.Train.FailMode.No);
end;
end;
method Shell.ExecAsync(ec: RemObjects.Script.EcmaScript.ExecutionContext; aSelf: Object; args: array of Object): Object;
begin
var lCMD := fEngine.ResolveWithBase(ec, Utilities.GetArgAsString(args, 0, ec), true);
var lArg := fEngine.Expand(ec, Utilities.GetArgAsString(args, 1, ec));
var lFail := true;
var lOpt := Utilities.GetArgAsEcmaScriptObject(args, 2, ec);
var lEnv := new List<KeyValuePair<String, String>>;
var lTimeout: nullable TimeSpan := nil;
var lWD: String;
if lOpt <> nil then begin
var lVal := lOpt.Get('timeout');
if (lVal <> nil) and (lVal <> Undefined.Instance) then
lTimeout := TimeSpan.FromSeconds(Utilities.GetObjAsInteger(lVal, ec));
lVal := lOpt.Get('workdir');
if lVal is String then
lWD := fEngine.ResolveWithBase(ec,String (lVal), true);
lVal := lOpt.Get('environment');
var lObj := EcmaScriptObject(lVal);
if lObj <> nil then begin
for each el in lObj.Values do begin
lEnv.Add(new KeyValuePair<String,String>(el.Key, Utilities.GetObjAsString(el.Value.Value, ec)));
end;
end;
end;
var lLogger := new RemObjects.Train.DelayedLogger;
var lTask := new System.Threading.Tasks.Task(method begin
lLogger.Enter(true,String.Format('shell.execAsync({0})', lCMD), lArg);
try
if fEngine.Engine.DryRun then begin
lLogger.LogMessage('Dry run.');
exit '';
end;
var sb := new System.Text.StringBuilder;
var lExit := ExecuteProcess(lCMD, lArg, coalesce(lWD, fEngine.Engine.WorkDir), false, a-> begin
locking(sb) do begin
sb.AppendLine(a);
end;
end, a-> begin
locking(sb) do sb.AppendLine(a);
end, lEnv.ToArray, lTimeout);
lLogger.LogInfo('Output: '#13#10+sb.ToString);
if 0 <> lExit then begin
var lErr := 'Failed with error code: '+lExit;
lLogger.LogError(lErr);
raise new AbortException();
end;
lFail := false;
finally
lLogger.Exit(true,String.Format('shell.execAsync({0})', lCMD), if lFail then RemObjects.Train.FailMode.Yes else RemObjects.Train.FailMode.No, nil);
end;
end);
fEngine.RegisterTask(lTask, String.Format('[{0}] {1} {2}', lTask.Id, lCMD, lArg), lLogger);
exit new TaskWrapper(fEngine.Engine.Engine.GlobalObject, fEngine.AsyncWorker.TaskProto, Task := lTask);
end;
method Shell.INTSystem(ec: RemObjects.Script.EcmaScript.ExecutionContext; aSelf: Object; args: array of Object): Object;
begin
var lArg := fEngine.Expand(ec, Utilities.GetArgAsString(args, 0, ec));
var lWD := if length(args) < 2 then nil else fEngine.ResolveWithBase(ec, Utilities.GetArgAsString(args, 1, ec), true);
var lFail := true;
fEngine.Engine.Logger.Enter(true,'shell.system()', lArg+' WD: '+lWD);
try
if fEngine.Engine.DryRun then begin
fEngine.Engine.Logger.LogMessage('Dry run.');
exit '';
end;
var sb := new System.Text.StringBuilder;
var lExit := ExecuteProcess(nil, lArg, coalesce(lWD, fEngine.Engine.WorkDir),true , a-> begin
locking(sb) do sb.AppendLine(a);
end, a-> begin
locking(sb) do sb.AppendLine(a)
end, nil, nil);
fEngine.Engine.Logger.LogInfo('Output: '#13#10+sb.ToString);
if 0 <> lExit then begin
var lErr := 'Failed with error code: '+lExit;
fEngine.Engine.Logger.LogError(lErr);
raise new AbortException;
end;
lFail := false;
exit sb.ToString();
finally
fEngine.Engine.Logger.Exit(true,'shell.system()', if lFail then RemObjects.Train.FailMode.Yes else RemObjects.Train.FailMode.No);
end;
end;
constructor Shell(aItem: IApiRegistrationServices);
begin
fEngine := aItem;
end;
class method Shell.ExecuteProcess(aCommand: String; aArgs, AWD: String; aComSpec: Boolean; aTargetError: Action<String>; aTargetOutput: Action<String>; environment: array of KeyValuePair<String, String>; aTimeout: nullable TimeSpan): Integer;
begin
var lProcess := new Process();
if lProcess.StartInfo = nil then lProcess.StartInfo := new ProcessStartInfo();
if aComSpec then begin
lProcess.StartInfo.FileName := if MUtilities.Windows then coalesce(System.Environment.GetEnvironmentVariable('COMSPEC'), 'CMD.EXE') else coalesce(System.Environment.GetEnvironmentVariable('SHELL'), '/bin/sh');
if String.IsNullOrEmpty(aCommand) then begin
lProcess.StartInfo.Arguments := (if not MUtilities.Windows then '-c ' else '/C ')+ aArgs;
end else begin
if not aCommand.StartsWith('"') then
aCommand := '"'+aCommand.Replace('"', '""')+'"';
lProcess.StartInfo.Arguments := (if not MUtilities.Windows then '-c ' else '/C ')+ aCommand+' '+aArgs;
end;
end else begin
lProcess.StartInfo.FileName := aCommand;
lProcess.StartInfo.Arguments := aArgs;
end;
if assigned(AWD) then
lProcess.StartInfo.WorkingDirectory := AWD;
lProcess.StartInfo.UseShellExecute := false;
if aTargetError <> nil then begin
lProcess.StartInfo.RedirectStandardError := true;
lProcess.ErrorDataReceived += method (o: Object; ar: DataReceivedEventArgs) begin
aTargetError:Invoke(ar.Data);
end;
end;
if aTargetOutput <> nil then begin
lProcess.StartInfo.RedirectStandardOutput := true;
lProcess.OutputDataReceived += method (o: Object; ar: DataReceivedEventArgs) begin
aTargetOutput:Invoke(ar.Data);
end;
end;
for each el in environment do begin
lProcess.StartInfo.EnvironmentVariables[el.Key] := el.Value;
end;
try
if not lProcess.Start then raise new Exception('Could not start process');
if aTargetOutput <> nil then lProcess.BeginOutputReadLine;
if aTargetError <> nil then lProcess.BeginErrorReadLine;
if aTimeout = nil then
lProcess.WaitForExit()
else
if not lProcess.WaitForExit(Integer(aTimeout.TotalMilliseconds)) then raise new Exception('Timeout!');
exit lProcess.ExitCode;
finally
aTargetError := nil;
aTargetOutput := nil;
lProcess.Dispose;
end;
end;
method ShellRegistration.&Register(aServices: IApiRegistrationServices);
begin
var lInstance := new Shell(aServices);
aServices.RegisterValue('shell',
new RemObjects.Script.EcmaScript.EcmaScriptObject(aServices.Globals)
.AddValue('cd', RemObjects.Train.MUtilities.SimpleFunction(aServices.Engine, (a, b, c) ->
begin
var lCurrPath := aServices.Engine.WorkDir;
var lPath := aServices.ResolveWithBase(a, RemObjects.Script.EcmaScript.Utilities.GetArgAsString(c, 0, a), true);
try
if System.IO.Path.IsPathRooted(lPath) then
aServices.Engine.WorkDir := lPath
else
aServices.Engine.WorkDir := System.IO.Path.Combine(aServices.Engine.WorkDir, lPath);
except
on e: Exception do begin
aServices.Logger.LogError(e);
raise new AbortException;
end;
end;
var lFunc := RemObjects.Script.EcmaScript.Utilities.GetArgAsEcmaScriptObject(c, 1, a);
if lFunc <> nil then
try
lFunc.Call(a);
finally
aServices.Engine.WorkDir := lCurrPath;
end;
end))
.AddValue('exec', RemObjects.Train.MUtilities.SimpleFunction(aServices.Engine, @lInstance.Exec))
.AddValue('execAsync', RemObjects.Train.MUtilities.SimpleFunction(aServices.Engine, @lInstance.ExecAsync))
.AddValue('system', RemObjects.Train.MUtilities.SimpleFunction(aServices.Engine, @lInstance.INTSystem)));
end;
end.