Repository navigation
Expand file tree
/
Copy pathufrmInstallLog.pas
More file actions
294 lines (256 loc) · 9.37 KB
/
Copy pathufrmInstallLog.pas
File metadata and controls
294 lines (256 loc) · 9.37 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
unit ufrmInstallLog;
interface
uses
System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.ComCtrls, Vcl.StdCtrls, DosCommand,
Vcl.Buttons, Vcl.ExtCtrls;
type
TfrmInstallLog = class(TForm)
lbInstallLog: TListBox;
DosCmdGetItInstall: TDosCommand;
pnlLogBottom: TPanel;
btnCancel: TBitBtn;
lblCount: TLabel;
pbInstalls: TProgressBar;
btnClose: TBitBtn;
procedure DosCmdGetItInstallNewLine(ASender: TObject;
const ANewLine: string; AOutputType: TOutputType);
procedure DosCmdGetItInstallTerminated(Sender: TObject);
procedure DosCmdGetItInstallTerminateProcess(ASender: TObject; var ACanTerminate: Boolean);
procedure btnCancelClick(Sender: TObject);
procedure btnCloseClick(Sender: TObject);
private
FAbort: Boolean;
FFinished: Boolean;
FSucceeded: Integer;
FFailures: TStringList;
FPartialShown: Boolean;
FPromptAnswered: Boolean;
procedure AddLog(const LogMsg: string);
procedure ShowPartialLine(const Partial: string);
procedure AnswerYesNoPrompt(const Prompt: string);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Initialize;
procedure NotifyFinished(const Total: Integer);
function ProcessGetItPackage(const GetItCmdExe, GetItCmdArgs, PackageName: string;
const Count, Total: Integer;
var Aborted: Boolean): Boolean;
end;
var
frmInstallLog: TfrmInstallLog;
implementation
{$R *.dfm}
uses
Winapi.Windows, Winapi.TlHelp32, System.SysUtils, System.StrUtils, System.UITypes, System.IOUtils,
System.Diagnostics, System.Generics.Collections, Vcl.Dialogs;
const
// not declared in Winapi.Windows in every Delphi version; unlike PROCESS_QUERY_INFORMATION it is
// granted for an elevated process to an unelevated caller
PROCESS_QUERY_LIMITED_INFORMATION = $1000;
END_STATUS_TEXT: array[TEndStatus] of string = (
'stopped', 'finished', 'still running', 'not started', 'failed to run', 'timed out');
function ProcessCreationTime(const ProcessId: DWORD): UInt64;
var
Creation, ExitTime, Kernel, User: TFileTime;
begin
Result := 0;
var Handle := OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, False, ProcessId);
if Handle <> 0 then
try
if GetProcessTimes(Handle, Creation, ExitTime, Kernel, User) then
Result := UInt64(Creation.dwHighDateTime) shl 32 or Creation.dwLowDateTime;
finally
CloseHandle(Handle);
end;
end;
procedure TerminateProcessDescendants(const ProcessId: DWORD);
{ Terminates every process started by ProcessId (children, grandchildren, ...), deepest first, but
not ProcessId itself, which TDosCommand.Stop terminates. GetItCmd can start other processes
(installers, MSBuild) that would otherwise keep running after Cancel. A process counts as a child
only if it was created after its claimed parent, because Windows reuses process ids. }
var
Entry: TProcessEntry32;
begin
var Parents := TDictionary<DWORD, DWORD>.Create; // process id -> parent id
var Ordered := TList<DWORD>.Create;
var Queue := TQueue<DWORD>.Create;
try
var Snapshot := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if Snapshot = INVALID_HANDLE_VALUE then
Exit;
try
Entry.dwSize := SizeOf(Entry);
if Process32First(Snapshot, Entry) then
repeat
Parents.AddOrSetValue(Entry.th32ProcessID, Entry.th32ParentProcessID);
until not Process32Next(Snapshot, Entry);
finally
CloseHandle(Snapshot);
end;
// breadth-first from the root, so Ordered lists parents before their children
Queue.Enqueue(ProcessId);
while Queue.Count > 0 do begin
var Parent := Queue.Dequeue;
var ParentCreated := ProcessCreationTime(Parent);
for var Pair in Parents do
if (Pair.Value = Parent) and (Pair.Key <> Parent) and (Pair.Key <> ProcessId) and
not Ordered.Contains(Pair.Key) and (ProcessCreationTime(Pair.Key) >= ParentCreated) then begin
Ordered.Add(Pair.Key);
Queue.Enqueue(Pair.Key);
end;
end;
// deepest first, so no parent can start a replacement for a child just terminated
for var i := Ordered.Count - 1 downto 0 do begin
var Handle := OpenProcess(PROCESS_TERMINATE, False, Ordered[i]);
if Handle <> 0 then
try
TerminateProcess(Handle, 1);
finally
CloseHandle(Handle);
end;
end;
finally
Queue.Free;
Ordered.Free;
Parents.Free;
end;
end;
{ TfrmInstallLog }
constructor TfrmInstallLog.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FFailures := TStringList.Create;
end;
destructor TfrmInstallLog.Destroy;
begin
FFailures.Free;
inherited Destroy;
end;
procedure TfrmInstallLog.AddLog(const LogMsg: string);
begin
lbInstallLog.Items.Add(LogMsg);
lbInstallLog.ItemIndex := lbInstallLog.Items.Count - 1;
lbInstallLog.Update;
end;
procedure TfrmInstallLog.ShowPartialLine(const Partial: string);
begin
// TDosCommand reports the unfinished line so far (cumulatively) after each pipe read; showing it
// makes a question that GetItCmd asks without a line break visible at all
if FPartialShown then
lbInstallLog.Items[lbInstallLog.Items.Count - 1] := Partial
else begin
AddLog(Partial);
FPartialShown := True;
end;
end;
procedure TfrmInstallLog.AnswerYesNoPrompt(const Prompt: string);
begin
FPromptAnswered := True;
var Answer := MessageDlg('GetItCmd is asking:' + sLineBreak + sLineBreak + Trim(Prompt) + sLineBreak + sLineBreak +
'Answer Yes?', mtConfirmation, [mbYes, mbNo], 0);
DosCmdGetItInstall.SendLine(IfThen(Answer = mrYes, 'Y', 'N'), True);
end;
procedure TfrmInstallLog.btnCancelClick(Sender: TObject);
begin
FAbort := True;
// Stop raises OnTerminateProcess, which ends GetItCmd's own child processes first
DosCmdGetItInstall.Stop;
end;
procedure TfrmInstallLog.btnCloseClick(Sender: TObject);
begin
Hide;
end;
procedure TfrmInstallLog.Initialize;
begin
lbInstallLog.Items.Clear;
FFailures.Clear;
FSucceeded := 0;
btnCancel.BringToFront;
Show;
end;
procedure TfrmInstallLog.DosCmdGetItInstallNewLine(ASender: TObject;
const ANewLine: string; AOutputType: TOutputType);
begin
if AOutputType = otEntireLine then begin
// the finished line replaces the partial one shown for it
if FPartialShown then begin
lbInstallLog.Items[lbInstallLog.Items.Count - 1] := ANewLine;
FPartialShown := False;
end else
AddLog(ANewLine);
end else begin
ShowPartialLine(ANewLine);
// GetItCmd 7.0 writes "Do you accept" with no line break and waits for an answer on standard
// input; the " (Y/N) ? " part only appears after it has read one
var Line := TrimRight(ANewLine);
if (not FPromptAnswered) and (EndsText('(Y/N) ?', Line) or EndsText('Do you accept', Line)) then
AnswerYesNoPrompt(ANewLine);
end;
end;
procedure TfrmInstallLog.DosCmdGetItInstallTerminated(Sender: TObject);
begin
FFinished := True;
end;
procedure TfrmInstallLog.DosCmdGetItInstallTerminateProcess(ASender: TObject; var ACanTerminate: Boolean);
begin
// raised on Cancel and on the silence timeout, just before TDosCommand terminates GetItCmd.exe
TerminateProcessDescendants(DosCmdGetItInstall.ProcessInformation.dwProcessId);
ACanTerminate := True;
end;
function TfrmInstallLog.ProcessGetItPackage(const GetItCmdExe, GetItCmdArgs, PackageName: string;
const Count, Total: Integer;
var Aborted: Boolean): Boolean;
begin
lblCount.Caption := Format('%d of %d packages', [Count, Total]);
lblCount.Update;
pbInstalls.Max := Total;
pbInstalls.Position := Count;
pbInstalls.Update;
DosCmdGetItInstall.CurrentDir := ExtractFileDir(GetItCmdExe);
// GetItCmd.exe by its full path, with no cmd.exe in between; the selected Delphi's environment
// paths (rsvars.bat--thanks GitHub user toxinon12345!) are already set on this process
DosCmdGetItInstall.CommandLine := '"' + GetItCmdExe + '" ' + GetItCmdArgs;
AddLog('Command Line: ' + DosCmdGetItInstall.CommandLine);
FAbort := False;
FFinished := False;
FPartialShown := False;
FPromptAnswered := False;
btnCancel.Enabled := True;
Screen.Cursor := crHourGlass;
try
DosCmdGetItInstall.Execute;
repeat
Application.ProcessMessages;
until FFinished or FAbort;
// Cancel gets here before OnTerminated; wait for it so ExitCode and EndStatus are final
while not FFinished and DosCmdGetItInstall.IsRunning do
Application.ProcessMessages;
finally
Screen.Cursor := crDefault;
end;
// GetItCmd returns a non-zero exit code when it fails
var Status := DosCmdGetItInstall.EndStatus;
var Code := DosCmdGetItInstall.ExitCode;
Result := (Status = esProcess) and (Code = 0);
AddLog(Format('Result: %s, exit code %d', [END_STATUS_TEXT[Status], Code]));
AddLog('========================');
if Result then
Inc(FSucceeded)
else
FFailures.Add(Format('%s: %s, exit code %d', [PackageName, END_STATUS_TEXT[Status], Code]));
Aborted := FAbort;
if FAbort then
AddLog('Aborted!');
end;
procedure TfrmInstallLog.NotifyFinished(const Total: Integer);
begin
AddLog(Format('Finished: %d of %d packages succeeded.', [FSucceeded, Total]));
if FFailures.Count > 0 then begin
AddLog('Did not succeed:');
for var Failure in FFailures do
AddLog(' ' + Failure);
end;
btnClose.BringToFront;
end;
end.