Debian Codegraph @

tools/common-code/toolcommonutils.pas

raw
1 {
2 Copyright 2014-2024 Michalis Kamburelis.
3
4 This file is part of "Castle Game Engine".
5 Parts of this file are based on FPC packages/fcl-process/src/process.pp ,
6 which conveniently uses *exactly* the same license as Castle Game Engine.
7
8 "Castle Game Engine" is free software; see the file COPYING.txt,
9 included in this distribution, for details about the copyright.
10
11 "Castle Game Engine" is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
14
15 ----------------------------------------------------------------------------
16 }
17
18 { Common utilities shared by various tools. }
19 unit ToolCommonUtils;
20
21 interface
22
23 uses Classes,
24 CastleStringUtils;
25
26 var
27 { Trivial verbosity global setting. }
28 Verbose: boolean = false;
29
30 { In case of console application with Verbose, writes to stduot.
31 Otherwise, only to WritelnLog. }
32 procedure WritelnVerbose(const S: String);
33
34 { Like @link(FindExe), but additionally look for the exe in
35 Castle Game Engine bin/ subdirectory. }
36 function FindExeCastleTool(const ExeName: String): String;
37
38 var
39 { When non-empty, determines the CastleEnginePath result unconditionally. }
40 CastleEngineOverridePath: String;
41
42 { Path to CGE main directory.
43 Autodetected or obtained from $CASTLE_ENGINE_PATH environment variable.
44
45 Returns empty String if it wasn't possible to get a valid value.
46 Otherwise, the returned path always ends with path delimiter,
47 and always exists. }
48 function CastleEnginePath: String;
49
50 { Copy current environemt variables. }
51 function EnvironmentStrings: TStringList;
52
53 type
54 { Line filtering used by MyRunCommandIndir and friends.
55 You can process the variable Line in any way.
56 Return whether to pass it (return @false to completely discard it,
57 any edits to Line don't matter then). }
58 TLineFiltering = function (var Line: String; const Data: Pointer): Boolean;
59
60 TRunCommandFlag = (rcNoConsole);
61 TRunCommandFlags = set of TRunCommandFlag;
62
63 { Run command in the given directory with the given arguments,
64 gathering the output (including error output, i.e. stdout and stderr)
65 to a string.
66
67 Allows for filtering the gathered output too.
68
69 Like Process.RunCommandIndir in FPC >= 2.6.4,
70 but also captures error output,
71 and enables filtering.
72
73 @param(ExeName Executable name, should be an absolute filename
74 e.g. found by FindExe. This will avoid FPC errors (the default FPC
75 algorithm searching $PATH may mistake binary for a directory with
76 the same name).)
77
78 @param(OutputString Standard output (stdout) and standard error output
79 (stderr) of the command.)
80
81 @param(LineFiltering Allows to filter the gathered lines, see TLineFiltering docs.)
82
83 @param(LineFilteringData Passed to the LineFiltering callback.
84 Ignored if LineFiltering is nil.)
85
86 @param(If defined, this overrides all environment variables.
87 The value is owned by this routine.
88 You can start from EnvironmentStrings.)
89 }
90 procedure MyRunCommandIndir(
91 const CurrentDirectory: String; const ExeName: String;
92 const Options: array of string;
93 out OutputString: String; out ExitStatus: integer;
94 const LineFiltering: TLineFiltering = nil;
95 const LineFilteringData: Pointer = nil;
96 const Flags: TRunCommandFlags = [];
97 const OverrideEnvironment: TStringList = nil);
98
99 { Run command in given directory with given arguments,
100 gathering output and status to string, and also letting output
101 to go to our output.
102
103 @param(ExeName Executable name, should be an absolute filename
104 e.g. found by FindExe. Like for MyRunCommandIndir.)
105
106 @param(OutputString Stdout and stderr of the process.
107 Like by MyRunCommandIndir.)
108
109 @param(OverrideEnvironmentName
110 When not empty, this environment variable has set
111 value OverrideEnvironmentValue in the process.) }
112 procedure RunCommandIndirPassthrough(
113 const CurrentDirectory: String; const ExeName: String;
114 const Options: array of string;
115 var OutputString: String; var ExitStatus: Integer;
116 const OverrideEnvironmentName: String = '';
117 const OverrideEnvironmentValue: String = '';
118 const LineFiltering: TLineFiltering = nil;
119 const LineFilteringData: Pointer = nil);
120
121 var
122 ForcePipesPassthrough: Boolean = false;
123
124 { Run command in given (or current) directory with given arguments,
125 letting output (stdout and stderr) to go to our stdout / stderr.
126 Waits for the command to finish.
127 The core functionality is thus just like the standard FPC ExecuteProcess.
128
129 ExeName is searched on $PATH following standard OS conventions,
130 if it's not already an absolute exe filename.
131
132 Raises exception if command fails (detected by exit code <> 0).
133
134 If OverrideEnvironmentName is <> '', then we set this one specific
135 environment variable, to the value of OverrideEnvironmentValue.
136
137 Global variable ForcePipesPassthrough can be used to force
138 using pipes to communicate with the process (instead of just letting
139 child process to use our stdout/stderr).
140 It should not be necessary (and it may introduce some performance drop,
141 though I didn't observe any in practice)... except on Windows when you run
142 "castle-engine run" in PowerShell in VS Code.
143 For some reason, "castle-engine run" in CGE editor doesn't need it.
144
145 Writelns "magic" string 'Castle Game Engine Internal: ProcessID: '
146 that is helpful for CGE editor to detect the process ID of the child
147 of "castle-engine run" and thus perform "Stop" more reliably. }
148 procedure RunCommandSimple(
149 const ExeName: String; const Options: array of string); overload;
150 procedure RunCommandSimple(
151 const CurrentDirectory: String; const ExeName: String; const Options: array of string;
152 const OverrideEnvironmentName: String = '';
153 const OverrideEnvironmentValue: String = ''); overload;
154
155 { Run the command, and return immediately, without waiting for finish. }
156 procedure RunCommandNoWait(
157 const CurrentDirectory: String;
158 const ExeName: String; const Options: array of string;
159 const Flags: TRunCommandFlags = [];
160 const OverrideEnvironment: TStringList = nil);
161
162 { Determine and create a new (unique, with random number in the name) temp directory. }
163 function CreateTemporaryDir: String;
164
165 var
166 { CGE manifest filename, designating CGE project root.
167 Can be adjusted using `castle-engine --manifest-name=xxx`. }
168 ManifestName: String = 'CastleEngineManifest.xml';
169
170 implementation
171
172 uses SysUtils, Process,
173 CastleFilesUtils, CastleUtils, CastleUriUtils, CastleLog,
174 ToolArchitectures;
175
176 procedure WritelnVerbose(const S: String);
177 begin
178 if Verbose and IsConsole then
179 WriteLn(S)
180 else
181 WriteLnLog(S);
182 end;
183
184 function FindExeCastleTool(const ExeName: String): String;
185 begin
186 if CastleEnginePath <> '' then
187 begin
188 Result := CastleEnginePath + 'bin' + PathDelim + ExeName + ExeExtension;
189 if RegularFileExists(Result) then
190 Exit;
191
192 { Look for exe wrapped in macOS application bundle,
193 necessary to find castle-model-viewer, castle-image-viewer in CGE bin. }
194 {$ifdef DARWIN}
195 Result := CastleEnginePath + 'bin' + PathDelim +
196 ExeName + '.app' + PathDelim +
197 'Contents' + PathDelim +
198 'MacOS' + PathDelim +
199 ExeName + ExeExtension;
200 if RegularFileExists(Result) then
201 Exit;
202 {$endif}
203
204 Result := CastleEnginePath + 'tools' + PathDelim + 'contrib' + PathDelim +
205 CPUToString(DefaultCPU) + '-' + OSToString(DefaultOS) + PathDelim +
206 ExeName + ExeExtension;
207 if RegularFileExists(Result) then
208 Exit;
209 end;
210 Result := FindExe(ExeName);
211 end;
212
213 function GetCastleEnginePathFromExeName: String; forward;
214
215 function GetCastleEnginePathFromEnv: String;
216
217 { Do everything possible to make paths that actually point to the same
218 location be the same string. }
219 function PathCanonical(const S: String): String;
220 begin
221 Result := S;
222 if Length(Result) <> 1 then // do not change root directory '/'
223 Result := ExclPathDelim(Result);
224 Result := ExpandFileName(Result);
225 Result := SReplaceChars(Result, '\', '/');
226 end;
227
228 var
229 EnginePathFromExe: String;
230 begin
231 Result := GetEnvironmentVariable('CASTLE_ENGINE_PATH');
232 if Result = '' then
233 Exit;
234
235 Result := InclPathDelim(Result);
236
237 if not DirectoryExists(Result) then
238 begin
239 WritelnWarning('$CASTLE_ENGINE_PATH environment variable points to a non-existing directory "%s", ignoring',
240 [Result]);
241 Exit('');
242 end;
243
244 { $CASTLE_ENGINE_PATH environment variable may point to the directory
245 - containing castle_game_engine/ as subdirectory (deprecated but allowed)
246 - or containing castle-engine/ as subdirectory (deprecated but allowed)
247 - or pointing straight to castle_game_engine/ or castle-engine/ directory. }
248 if DirectoryExists(Result + 'castle_game_engine') then
249 begin
250 WritelnWarning('$CASTLE_ENGINE_PATH environment variable points to a parent of "castle_game_engine" directory: "%s". This is deprecated, better change $CASTLE_ENGINE_PATH to include the "castle_game_engine" suffix.',
251 [Result]);
252 Result := Result + 'castle_game_engine' + PathDelim
253 end else
254 if DirectoryExists(Result + 'castle-engine') then
255 begin
256 WritelnWarning('$CASTLE_ENGINE_PATH environment variable points to a parent of "castle-engine" directory: "%s". This is deprecated, better change $CASTLE_ENGINE_PATH to include the "castle-engine" suffix.',
257 [Result]);
258 Result := Result + 'castle-engine' + PathDelim;
259 end;
260
261 if not DirectoryExists(Result + 'src') then
262 WritelnWarning('$CASTLE_ENGINE_PATH environment variable defined, but we cannot find Castle Game Engine sources inside: "%s". We try to continue, assuming that engine unit paths are already specified within fpc.cfg file, otherwise compilation will fail.',
263 [Result]);
264 if not DirectoryExists(Result + 'tools' + PathDelim + 'build-tool' + PathDelim + 'data') then
265 WritelnWarning('$CASTLE_ENGINE_PATH environment variable defined, but we cannot find build tool data inside: "%s". We try to continue, but some packaging operations will fail.',
266 [Result]);
267
268 if Result <> '' then
269 begin
270 EnginePathFromExe := GetCastleEnginePathFromExeName;
271 if (EnginePathFromExe <> '') and
272 (not SameFileName(PathCanonical(Result), PathCanonical(EnginePathFromExe))) then
273 begin
274 WritelnWarning('$CASTLE_ENGINE_PATH environment variable points to a different directory than the one detected from the executable path: "%s" vs "%s". This may be a mistake, possibly you have two (different) engine versions installed. Please check your environment, likely remove one of the engine versions or undefine CASTLE_ENGINE_PATH to not point to the engine that shall be unused.', [
275 Result,
276 EnginePathFromExe
277 ]);
278 end;
279 end;
280 end;
281
282 { Check is Path a sensible CGE sources path.
283 Requires Path to end with PathDelim. }
284 function CheckCastlePath(const Path: String): Boolean;
285 begin
286 Result :=
287 DirectoryExists(Path + 'src') and
288 DirectoryExists(Path + 'tools' + PathDelim + 'build-tool' + PathDelim + 'data');
289 end;
290
291 function GetCastleEnginePathFromExeName: String;
292 var
293 ToolDir: String;
294 begin
295 try
296 // knowingly using deprecated ExeName, that should be non-deprecated and internal here
297 {$warnings off}
298 ToolDir := ExtractFileDir(ExeName);
299 {$warnings on}
300 { in case we're inside macOS bundle, use bundle path.
301 This makes detection in case of CGE editor work OK. }
302 {$ifdef DARWIN}
303 if BundlePath <> '' then
304 ToolDir := ExtractFileDir(ExclPathDelim(BundlePath));
305 {$endif}
306
307 { Check ../ of current exe, makes sense in released CGE version when
308 tools are precompiled in bin/ subdirectory. }
309 Result := InclPathDelim(ExtractFileDir(ToolDir));
310 if CheckCastlePath(Result) then
311 Exit;
312 { Check ../../ of current exe, makes sense in development when
313 each tool is compiled by various scripts in tools/xxx/ subdirectory. }
314 Result := InclPathDelim(ExtractFileDir(ExtractFileDir(ToolDir)));
315 if CheckCastlePath(Result) then
316 Exit;
317
318 Result := '';
319 except
320 on EExeNameNotAvailable do
321 WritelnVerbose('Cannot detect CGE path because ExeName not available on this platform, and $CASTLE_ENGINE_PATH not defined');
322 end;
323 end;
324
325 function GetCastleEnginePathSystemWide: String;
326 begin
327 {$ifdef UNIX}
328 Result := '/usr/src/castle-engine/';
329 if CheckCastlePath(Result) then
330 Exit;
331
332 Result := '/usr/local/src/castle-engine/';
333 if CheckCastlePath(Result) then
334 Exit;
335 {$endif}
336
337 Result := '';
338 end;
339
340 var
341 CastleEnginePathIsCached: Boolean;
342 CastleEnginePathCached: String;
343
344 function CastleEnginePath: String;
345 begin
346 { In case of CastleEngineOverridePath, ignore CastleEnginePathCached.
347 This avoids clearing this cache when CastleEngineOverridePath changes
348 at runtime, like in editor. }
349 if CastleEngineOverridePath <> '' then
350 Result := InclPathDelim(CastleEngineOverridePath)
351 else
352 if CastleEnginePathIsCached then
353 Result := CastleEnginePathCached
354 else
355 begin
356 // try to find CGE on $CASTLE_ENGINE_PATH
357 Result := GetCastleEnginePathFromEnv;
358 // try to find CGE on path relative to current exe
359 if Result = '' then
360 Result := GetCastleEnginePathFromExeName;
361 // try to find CGE on system-wide paths
362 if Result = '' then
363 Result := GetCastleEnginePathSystemWide;
364
365 if Result <> '' then
366 WritelnVerbose('Castle Game Engine directory detected: ' + Result)
367 else
368 WritelnWarning('Castle Game Engine directory cannot be detected:' + NL +
369 '- $CASTLE_ENGINE_PATH environment variable not defined, or points to an incorrect directory.' + NL +
370 '- Moreover we cannot find Castle Game Engine looking at parent directory of this program exe.');
371
372 CastleEnginePathIsCached := true;
373 CastleEnginePathCached := Result;
374 end;
375 end;
376
377 { Output capturing interface -------------------------------- }
378
379 type
380 { Read from Source stream (with the option to read without blocking) all contents.
381
382 Collected contents can be obtained by calling @link(Collected)
383 (it should be used only once all ReadAvailable and ReadEverything calls are done).
384
385 The TCaptureOutput class doesn't process the contents in any way.
386 When it reads newline characters (#10, #13) they are treated
387 just like any other character.
388 Descendants like TCaptureOutputFilter may have different behavior. }
389 TCaptureOutput = class
390 strict private
391 const
392 { Original code for this adjusted from fpc/trunk/packages/fcl-process/src/process.pp ,
393 although reworked many times.
394 MaxReadBytes is not too small to avoid fragmentation when reading large files. }
395 MaxReadBytes = 65536;
396 var
397 OutputUsefulCount: Integer;
398 OutputString: String;
399 protected
400 function ReadCore: Integer; virtual;
401 public
402 Source: TStream;
403
404 { Also write everything you collect to out output (stdout).
405 Note that it's not a perfect "passthrough": we collect both stdout and stderr
406 from the child process, and output it always on our stdout.
407 So we redirect child's stdout to our stderr. }
408 Passthrough: Boolean;
409
410 { Read from Source stream as much bytes as possible (without blocking waiting for more). }
411 procedure ReadAvailable;
412
413 { Read from Source stream all remaining bytes. }
414 procedure ReadEverything;
415
416 { Return read contents so far. Call this only after all the reading is done. }
417 function Collected: String; virtual;
418
419 { Create new instance of TCaptureOutput or a descendant,
420 like TCaptureOutputFilter, suitable for given parameters. }
421 class function Construct(const ASource: TStream;
422 const ALineFiltering: TLineFiltering;
423 const ALineFilteringData: Pointer): TCaptureOutput; static;
424 end;
425
426 { API just like ancestor, but filters the read lines through LineFiltering callback.
427 Output line endings are also converted to native (LineEnding) along the way. }
428 TCaptureOutputFilter = class(TCaptureOutput)
429 strict private
430 { Note that TCaptureOutputFilter has entirely different implementation than
431 ancestor. While it also defines private MaxReadBytes and OutputString,
432 they are used in very different way. }
433 const
434 MaxReadBytes = 65536;
435 var
436 OutputString: String;
437 Buffer: String;
438 PendingLine: String;
439 protected
440 function ReadCore: Integer; override;
441 public
442 LineFiltering: TLineFiltering; //< Never @nil
443 LineFilteringData: Pointer;
444 constructor Create;
445 function Collected: String; override;
446 end;
447
448 { Output capturing: TCaptureOutput -------------------------------- }
449
450 function TCaptureOutput.ReadCore: Integer;
451 begin
452 SetLength(OutputString, OutputUsefulCount + MaxReadBytes);
453 Result := Source.Read(OutputString[1 + OutputUsefulCount], MaxReadBytes);
454 if Passthrough then
455 Write(Copy(OutputString, 1 + OutputUsefulCount, Result));
456 if Result > 0 then
457 Inc(OutputUsefulCount, Result);
458 end;
459
460 procedure TCaptureOutput.ReadAvailable;
461 var
462 NumBytes: Integer;
463 begin
464 NumBytes := ReadCore;
465 if NumBytes = 0 then
466 begin
467 Sleep(100); // when no data, wait a bit instead of wasting CPU trying to query stream
468 Exit;
469 end;
470 end;
471
472 procedure TCaptureOutput.ReadEverything;
473 var
474 NumBytes: Integer;
475 begin
476 repeat
477 NumBytes := ReadCore;
478 until NumBytes <= 0;
479 end;
480
481 function TCaptureOutput.Collected: String;
482 begin
483 SetLength(OutputString, OutputUsefulCount);
484 Result := OutputString;
485 end;
486
487 class function TCaptureOutput.Construct(const ASource: TStream;
488 const ALineFiltering: TLineFiltering;
489 const ALineFilteringData: Pointer): TCaptureOutput;
490 begin
491 if Assigned(ALineFiltering) then
492 begin
493 Result := TCaptureOutputFilter.Create;
494 TCaptureOutputFilter(Result).LineFiltering := ALineFiltering;
495 TCaptureOutputFilter(Result).LineFilteringData := ALineFilteringData;
496 end else
497 begin
498 Result := TCaptureOutput.Create;
499 end;
500 Result.Source := ASource;
501 end;
502
503 { Output capturing: TCaptureOutputFilter ------------------------------------- }
504
505 constructor TCaptureOutputFilter.Create;
506 begin
507 inherited;
508 SetLength(Buffer, MaxReadBytes);
509 end;
510
511 function TCaptureOutputFilter.ReadCore: Integer;
512 var
513 NewlinePos, PreviousPendingLineLength, NextLineStart: Integer;
514 Line: String;
515 LineAllow: Boolean;
516 begin
517 Result := Source.Read(Buffer[1], MaxReadBytes);
518
519 if Result = 0 then
520 Exit;
521
522 PreviousPendingLineLength := Length(PendingLine);
523 PendingLine := PendingLine + Copy(Buffer, 1, Result);
524
525 // in a loop, remove as much lines from PendingLine as possible
526 repeat
527 // Using here CharsPosEx instead of CharsPos
528 // is just optimization to not search entire PendingLine every time.
529 NewlinePos := CharsPosEx([#10, #13], PendingLine, PreviousPendingLineLength + 1);
530
531 if NewlinePos = 0 then Break;
532
533 // we have a line -- filter it and possibly add to OutputString
534 Line := Copy(PendingLine, 1, NewlinePos - 1);
535 LineAllow := LineFiltering(Line, LineFilteringData);
536 if LineAllow then
537 begin
538 OutputString := OutputString + Line + LineEnding;
539 if Passthrough then
540 Writeln(Line);
541 end;
542
543 { If this is followed by 2nd newline character, we want to consume it.
544
545 TODO: We here assume that both newline characters will be returned by Source.Read,
546 which may not be true (when newline is 2-character, like on #13#10,
547 it is possible that line break will be split across MaxReadBytes borders).
548 When this assumption will break, we'll just cause an additional newline,
549 which is acceptable for now. }
550
551 if (NewlinePos + 1 <= Length(PendingLine)) and
552 { check we have #13 followed by #10 or #10 followed by #13.
553 Be careful to *not* eat #10 followed by #10, as that would
554 make us silently consume empty lines in files with Unix line ending. }
555 ( ( (PendingLine[NewlinePos] = #10) and (PendingLine[NewlinePos + 1] = #13) ) or
556 ( (PendingLine[NewlinePos] = #13) and (PendingLine[NewlinePos + 1] = #10) ) ) then
557 NextLineStart := NewlinePos + 2
558 else
559 NextLineStart := NewlinePos + 1;
560
561 PendingLine := SEnding(PendingLine, NextLineStart);
562 PreviousPendingLineLength := 0; // reset for next CharsPosEx search
563 until false;
564 end;
565
566 function TCaptureOutputFilter.Collected: String;
567 begin
568 Result := OutputString + PendingLine;
569 PendingLine := '';
570 end;
571
572 { Running processes ---------------------------------------------------------- }
573
574 function EnvironmentStrings: TStringList;
575 var
576 I: Integer;
577 begin
578 Result := TStringList.Create;
579 for I := 1 to GetEnvironmentVariableCount do
580 Result.Add(GetEnvironmentString(I));
581 end;
582
583 procedure MyRunCommandIndir(const CurrentDirectory: String;
584 const ExeName: String;const Options: array of string;
585 out OutputString: String; out ExitStatus: integer;
586 const LineFiltering: TLineFiltering = nil;
587 const LineFilteringData: Pointer = nil;
588 const Flags: TRunCommandFlags = [];
589 const OverrideEnvironment: TStringList = nil);
590 var
591 P: TProcess;
592 I: Integer;
593 Capture: TCaptureOutput;
594 begin
595 // default out values
596 OutputString := '';
597 ExitStatus := 0;
598
599 { Set to nil variables that will be later freed in the "finally" clause.
600 This makes code a bit simpler, no need for nesting multiple try..finally clauses. }
601 Capture := nil;
602 P := nil;
603 try
604 P := TProcess.Create(nil);
605 P.Executable := ExeName;
606 if CurrentDirectory <> '' then
607 P.CurrentDirectory := CurrentDirectory;
608 if High(Options) >= 0 then
609 for I := Low(Options) to High(Options) do
610 P.Parameters.Add(Options[I]);
611 WritelnVerbose('Calling ' + ExeName);
612 WritelnVerbose(P.Parameters.Text);
613
614 P.Options := [poUsePipes, poStderrToOutPut];
615 if rcNoConsole in Flags then
616 P.Options := P.Options + [poNoConsole];
617 if OverrideEnvironment <> nil then
618 P.Environment := OverrideEnvironment;
619 P.Execute;
620
621 Capture := TCaptureOutput.Construct(P.Output, LineFiltering, LineFilteringData);
622
623 // wait until P finishes, read OutputString
624 while P.Running do
625 Capture.ReadAvailable;
626 Capture.ReadEverything;
627 OutputString := Capture.Collected;
628
629 ExitStatus := P.ExitStatus;
630 finally
631 FreeAndNil(Capture);
632 FreeAndNil(P);
633 end;
634 end;
635
636 procedure RunCommandIndirPassthrough(const CurrentDirectory: String;
637 const ExeName: String;
638 const Options: array of string;
639 var OutputString: String; var ExitStatus: Integer;
640 const OverrideEnvironmentName: String = '';
641 const OverrideEnvironmentValue: String = '';
642 const LineFiltering: TLineFiltering = nil;
643 const LineFilteringData: Pointer = nil);
644 var
645 P: TProcess;
646 I: Integer;
647 NewEnvironment: TStringList;
648 Capture: TCaptureOutput;
649 begin
650 { Set to nil variables that will be later freed in the "finally" clause.
651 This makes code a bit simpler, no need for nesting multiple try..finally clauses. }
652 Capture := nil;
653 P := nil;
654 NewEnvironment := nil;
655 try
656 P := TProcess.Create(nil);
657 P.Executable := ExeName;
658 if CurrentDirectory <> '' then
659 P.CurrentDirectory := CurrentDirectory;
660 if High(Options) >= 0 then
661 for I := Low(Options) to High(Options) do
662 P.Parameters.Add(Options[I]);
663 WritelnVerbose('Calling ' + ExeName);
664 WritelnVerbose(P.Parameters.Text);
665
666 if OverrideEnvironmentName <> '' then
667 begin
668 NewEnvironment := EnvironmentStrings;
669 NewEnvironment.Values[OverrideEnvironmentName] := OverrideEnvironmentValue;
670 P.Environment := NewEnvironment;
671 // WritelnVerbose('Environment: ' + P.Environment.Text);
672 end;
673
674 P.Options := [poUsePipes, poStderrToOutPut];
675 P.Execute;
676
677 Capture := TCaptureOutput.Construct(P.Output, LineFiltering, LineFilteringData);
678 Capture.Passthrough := true;
679
680 // wait until P finishes, read OutputString
681 while P.Running do
682 Capture.ReadAvailable;
683 Capture.ReadEverything;
684 OutputString := Capture.Collected;
685
686 ExitStatus := P.ExitStatus;
687 finally
688 FreeAndNil(Capture);
689 FreeAndNil(P);
690 FreeAndNil(NewEnvironment);
691 end;
692 end;
693
694 procedure RunCommandSimple(
695 const ExeName: String; const Options: array of string);
696 begin
697 RunCommandSimple(GetCurrentDir, ExeName, Options);
698 end;
699
700 procedure RunCommandSimple(
701 const CurrentDirectory: String; const ExeName: String; const Options: array of string;
702 const OverrideEnvironmentName: String = '';
703 const OverrideEnvironmentValue: String = '');
704
705 { Run the given command, wait for it.
706 The stdout/stderr is not captured to any string,
707 it is only passed-through as our stdout/stderr.
708
709 ( Use RunCommandIndirPassthrough to capture output to String and pass-through,
710 use RunCommandIndir to only capture output to String. ) }
711 procedure RunCommandNoPipes(const CurrentDirectory: String;
712 const ExeName: String;
713 const Options: array of string;
714 var ExitStatus: Integer;
715 const OverrideEnvironmentName: String = '';
716 const OverrideEnvironmentValue: String = '');
717 var
718 P: TProcess;
719 I: Integer;
720 NewEnvironment: TStringList;
721 begin
722 { Set to nil variables that will be later freed in the "finally" clause.
723 This makes code a bit simpler, no need for nesting multiple try..finally clauses. }
724 P := nil;
725 NewEnvironment := nil;
726 try
727 P := TProcess.Create(nil);
728 P.Executable := ExeName;
729 if CurrentDirectory <> '' then
730 P.CurrentDirectory := CurrentDirectory;
731 if High(Options) >= 0 then
732 for I := Low(Options) to High(Options) do
733 P.Parameters.Add(Options[I]);
734 WritelnVerbose('Calling ' + ExeName);
735 WritelnVerbose(P.Parameters.Text);
736
737 if OverrideEnvironmentName <> '' then
738 begin
739 NewEnvironment := EnvironmentStrings;
740 NewEnvironment.Values[OverrideEnvironmentName] := OverrideEnvironmentValue;
741 P.Environment := NewEnvironment;
742 // WritelnVerbose('Environment: ' + P.Environment.Text);
743 end;
744
745 P.Execute;
746
747 Writeln('Castle Game Engine Internal: ProcessID: ', P.ProcessID);
748 Flush(Output);
749
750 P.WaitOnExit;
751
752 ExitStatus := P.ExitStatus;
753 finally
754 FreeAndNil(P);
755 FreeAndNil(NewEnvironment);
756 end;
757 end;
758
759 var
760 ProcessStatus: Integer;
761 AbsoluteExeName, IgnoredOutput: String;
762 begin
763 { use FindExe to use our fixed PathFileSearch that does not accidentally find
764 "ant" directory as "ant" executable }
765 if IsPathAbsolute(ExeName) then
766 AbsoluteExeName := ExeName
767 else
768 begin
769 AbsoluteExeName := FindExe(ExeName);
770 if AbsoluteExeName = '' then
771 raise Exception.CreateFmt('Cannot find "%s" on environment variable $PATH. Make sure "%s" is installed and $PATH is configured correctly',
772 [ExeName, ExeName]);
773 end;
774
775 if ForcePipesPassthrough then
776 { TODO: In this case, we don't make
777 Writeln('Castle Game Engine Internal: ProcessID: ', P.ProcessID);
778 Though it doesn't seem a problem for anything on Windows.
779 In practice this is used only to reliably doing "Stop" from CGE editor
780 on running "castle-engine run" (for desktop or Android apps),
781 and these work OK on Windows too. }
782 RunCommandIndirPassthrough(CurrentDirectory, AbsoluteExeName, Options,
783 IgnoredOutput, ProcessStatus, OverrideEnvironmentName, OverrideEnvironmentValue)
784 else
785 RunCommandNoPipes(CurrentDirectory, AbsoluteExeName, Options,
786 ProcessStatus, OverrideEnvironmentName, OverrideEnvironmentValue);
787
788 // this will cause our own status be non-zero
789 if ProcessStatus <> 0 then
790 raise Exception.CreateFmt('Process "%s" (absolute path "%s") failed with exit status %d',
791 [ExeName, AbsoluteExeName, ProcessStatus]);
792 end;
793
794 { Under Unix, we need to solve the problem that
795 parent process can die (and destroy child's IO handles)
796 and the new process (executed by RunCommandNoWait) should stil be running OK.
797 This is important when you execute in "castle-editor" the option
798 to "Restart and Rebuild" editor, then "castle-editor" calls "castle-engine editor",
799 and both "castle-editor" and "castle-engine" processes die
800 (while the new CGE editor should continue running).
801
802 - First solution was to execute using nohup.
803
804 Unfortunately it doesn't work reliably enough.
805 First execution of "Restart and Rebuild" is OK,
806 but then doing again "Restart and Rebuild" from this editor
807 (that is already under nohup) makes editor instance without output redirected to nohup.out
808 (even when CurrentDirectory is random every time to make nohup.out land in different dir),
809 possibly because nohup didn't detect
810 that input/output should be redirected to file.
811
812 In effect doing *again* "Restart and Rebuild" fails, as the process doesn't have
813 access to own input/output.
814 See https://trello.com/c/lDi33IRQ/20-linuxeditor-running-custom-editor-from-editor-gui-results-in-errors-stream-write-error-when-trying-to-run-another-child-applicat
815
816 - New solution is to execute by shell, using shell to redirect to files.
817
818 This works, as it always makes the run inside process (like "castle-editor") use output to files,
819 so that parent (like "castle-engine editor" call) dying has no effect.
820
821 The additional bonus is that we can put the output files in a temporary directory,
822 or send output to /dev/null,
823 regardless of the CurrentDirectory.
824 In contrast, nohup always put nohup.out in current dir,
825 forcing us to always set current dir to temporary dir (to avoid cluttering user-visible dir),
826 which is not always comfortable (e.g. when editor runs build tool,
827 it's easiest to set current directory = project directory).
828 }
829 {$define UNIX_RUN_NO_WAIT_BY_SHELL}
830
831 procedure RunCommandNoWait(
832 const CurrentDirectory: String;
833 const ExeName: String; const Options: array of string;
834 const Flags: TRunCommandFlags = [];
835 const OverrideEnvironment: TStringList = nil);
836 var
837 P: TProcess;
838 I: Integer;
839 {$ifdef UNIX} ShCommand, ShCommandOutput: String; {$endif}
840 begin
841 P := TProcess.Create(nil);
842 try
843 P.CurrentDirectory := CurrentDirectory;
844
845 {$if defined(UNIX) and defined(UNIX_RUN_NO_WAIT_BY_SHELL)}
846 P.Executable := FindExe('sh');
847 if P.Executable = '' then
848 raise Exception.Create('Cannot find sh (standard shell) on $PATH');
849
850 P.Parameters.Add('-c');
851
852 ShCommand := '"' + ExeName + '"';
853 for I := 0 to High(Options) do
854 ShCommand += ' "' + Options[I] + '"';
855 ShCommandOutput :=
856 {$ifdef DEBUG_UNIX_RUN_NO_WAIT_BY_SHELL} InclPathDelim(CreateTemporaryDir) + 'run-process-no-wait-' + IntToStr(Random(100000)) + '.log'
857 {$else} '/dev/null'
858 {$endif};
859 ShCommand += '< /dev/null > ' + ShCommandOutput + ' 2>&1';
860 P.Parameters.Add(ShCommand);
861
862 {$else}
863 P.Executable := ExeName;
864
865 { Old Unix solution with nohup, see above comments at UNIX_RUN_NO_WAIT_BY_SHELL }
866 {$ifdef UNIX}
867 NoHupExe := FindExe('nohup');
868 if NoHupExe <> '' then
869 begin
870 P.Executable := NoHupExe;
871 P.Parameters.Add(ExeName);
872 end;
873 {$endif}
874
875 for I := Low(Options) to High(Options) do
876 P.Parameters.Add(Options[I]);
877 {$endif}
878
879 { Under Windows, these options should make a process execute OK.
880 Following http://wiki.lazarus.freepascal.org/Executing_External_Programs . }
881 P.InheritHandles := false;
882 P.ShowWindow := swoShow;
883 if rcNoConsole in Flags then
884 P.Options := P.Options + [poNoConsole];
885 if OverrideEnvironment <> nil then
886 P.Environment := OverrideEnvironment;
887
888 WritelnVerbose('Calling ' + P.Executable); // show P.Executable, not ExeName, as code above may set other P.Executable
889 WritelnVerbose(' With Working Directory: ' + P.CurrentDirectory);
890 WritelnVerbose(P.Parameters.Text);
891
892 P.Execute;
893 finally FreeAndNil(P) end;
894 end;
895
896 function CreateTemporaryDir: String;
897 begin
898 Result := InclPathDelim(GetTempDir(false)) +
899 ApplicationName + IntToStr(Random(1000000));
900 CheckForceDirectories(Result);
901 WritelnVerbose('Created temporary dir for package: ' + Result);
902 end;
903
904 end.