Debian Codegraph @

tools/build-tool/code/toolutils.pas

raw
1 {
2 Copyright 2014-2024 Michalis Kamburelis.
3
4 This file is part of "Castle Game Engine".
5
6 "Castle Game Engine" is free software; see the file COPYING.txt,
7 included in this distribution, for details about the copyright.
8
9 "Castle Game Engine" is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 ----------------------------------------------------------------------------
14 }
15
16 { Utilities. }
17 unit ToolUtils;
18
19 interface
20
21 uses DOM,
22 CastleImages, CastleStringUtils, CastleUtils;
23
24 { Copy file, making sure the destination directory exists
25 (eventually creating it), and checking result. }
26 procedure SmartCopyFile(const Source, Dest: string);
27
28 function FileSize(const FileName: string): Int64;
29
30 var
31 { Output path base directory. Empty to use working project directory. }
32 OutputPathBase: string = '';
33
34 { Calculate the final location of temporary output files
35 (including the castle-engine-output subdir part),
36 as an absolute path ending with path delimiter.
37 Makes sure the dir exists, if CreateIfNecessary. }
38 function TempOutputPath(const WorkingDirectory: string;
39 const CreateIfNecessary: boolean = true): string;
40
41 type
42 TReplaceMacros = function (const Source: string): string of object;
43
44 const
45 MaxAndroidTagLength = 23;
46
47 const
48 { Interpolation to scale images with highest quality.
49
50 Latest FPC breaks alpha channel at resizing using riLanczos.
51 TODO: Submit a patch to FPC to restore previous behavior.
52
53 Index: packages/fcl-image/src/fpinterpolation.inc
54 ===================================================================
55 --- packages/fcl-image/src/fpinterpolation.inc (wersja 40746)
56 +++ packages/fcl-image/src/fpinterpolation.inc (kopia robocza)
57 @@ -223,7 +223,8 @@
58 NewCol.blue:=Min(NewCol.blue+round(Col.blue*f),$ffff);
59 NewCol.alpha:=Min(NewCol.alpha+round(Col.alpha*f),$ffff);
60 end;
61 - Canvas.Colors[x+dx,y+dy]:=AlphaBlend(Canvas.Colors[x+dx,y+dy], NewCol);
62 + //Canvas.Colors[x+dx,y+dy]:=AlphaBlend(Canvas.Colors[x+dx,y+dy], NewCol);
63 + Canvas.Colors[x+dx,y+dy]:=NewCol;
64 end;
65 end;
66 finally
67 }
68 BestInterpolation = {$ifdef VER3_0} riLanczos {$else} riBilinear {$endif};
69
70 { Add all parameters in Parameters to Macros.
71 Each parameter key is prefixed by ParameterMacroPrefix
72 when it is added to the Macros list. }
73 procedure ParametersAddMacros(const Macros, Parameters: TStringStringMap;
74 const ParameterMacroPrefix: String);
75
76 { Find the filename of linker input produced by FPC when called with -Cn .
77 Path must contain a final path delimiter.
78 Raises exception if not found (or found too many, and it is ambiguous what to use).
79
80 For old FPC, it is just link.res.
81
82 During FPC 3.2.0 -> 3.2.2 development:
83 it may be any link<id>.res and unfortunately we don't know the <id>
84 (it's not the TProcess.ProcessID of "fpc" process, at least under Windows).
85
86 Since FPC 3.2.2 it is linkfiles<id>.res (and we ignore link<id>.res and linksyms<id>.res). }
87 function FindLinkRes(const Path: String): String;
88
89 { Set Unix executable bit.
90 It will not be able to perform the CHMOD operation on non-Unix OS
91 and will log a corresponding warning instead. }
92 procedure DoMakeExecutable(const PathAndName: String);
93
94 { Simple GUI error box.
95
96 Implemented without depending on GTK, LCL or any other GUI library
97 on Unix, as build tool should remain command-line only, to be easy to use
98 on servers without GUI libraries installed. We depend on "zenity".
99
100 This is only used when --gui-errors was used. }
101 procedure ErrorBox(const Message: String);
102
103 const
104 SCannotFindCgePath = 'Cannot find Castle Game Engine path.' + NL +
105 'Solutions:' + NL +
106 '1. Run from CGE editor (where you can configure CGE path in "Preferences",' + NL +
107 '2. Or place the engine tools (exe) inside the bin/ subdirectory of the engine,' + NL +
108 '3. Or set the environment variable $CASTLE_ENGINE_PATH.';
109
110 function CachePath: String;
111
112 { Generate GUID using Seed to determine it, instead of using Random.
113 This is useful when you want to generate GUID that is stable between runs
114 (for example, when you want to have regenerate_auto_files_in_all_examples.sh
115 have stable output).
116
117 This is not a cryptographically secure hash, it's just a simple hash
118 to make GUID stable. }
119 function CreateGUIDFromHash(const Seed: String): TGuid;
120
121 { Create a .zip file named ZipFileName
122 containing all files (recursively) in the Directory.
123
124 Both ZipFileName and Directory may be absolute or relative filenames.
125 Directory may but doesn't have to end with PathDelim.
126
127 The Directory is added to the zip file as a top-level directory inside zip.
128 E.g. if Directory is '/home/michalis/mydir', then the zip file will contain
129 as top level 'mydir'. There shall be no trace of '/home/michalis/' in
130 the resulting zp file.
131
132 We gracefully handle the case when ZipFileName is inside Directory,
133 by not packing the ZipFileName in this case in itself (and making a warning),
134 to avoid possible reading and writing the file at the same time.
135 Though we don't rely on this feature in practice,
136 all curent usage of ZipDirectory in build tool places ZipFileName safely outside
137 of its input Directory. }
138 procedure ZipDirectory(const ZipFileName: String; Directory: String);
139
140 implementation
141
142 uses {$ifdef UNIX} BaseUnix, {$endif}
143 {$ifdef MSWINDOWS} Windows, {$endif}
144 Zipper,
145 Classes, Process, SysUtils,
146 CastleFilesUtils, CastleUriUtils, CastleLog, CastleXmlUtils, CastleFindFiles,
147 ToolCommonUtils;
148
149 procedure SmartCopyFile(const Source, Dest: string);
150 begin
151 CheckForceDirectories(ExtractFileDir(Dest));
152 CheckCopyFile(Source, Dest);
153 end;
154
155 function FileSize(const FileName: string): Int64;
156 var
157 SourceFile: TFileStream;
158 begin
159 SourceFile := TFileStream.Create(FileName, fmOpenRead);
160 try
161 Result := SourceFile.Size;
162 finally FreeAndNil(SourceFile) end;
163 end;
164
165 var
166 FOutputPath: String;
167 FOutputPathForWorkingDirectory: String;
168
169 function TempOutputPath(const WorkingDirectory: String; const CreateIfNecessary: Boolean): String;
170 const
171 OutputNoteContents = {$I ../embedded_templates/template-castle-engine-output-warning.txt.inc};
172 var
173 OutputNote: String;
174 begin
175 if (FOutputPath = '') or
176 { Do not reuse cached FOutputPath for different WorkingDirectory,
177 otherwise doing DoCompile for different projects in same run would accidentally
178 reuse output.
179 Testcase: "castle-engine cache", each mode (release valgrind debug)
180 must build new files. }
181 (FOutputPathForWorkingDirectory <> WorkingDirectory) then
182 begin
183 if OutputPathBase = '' then
184 FOutputPath := InclPathDelim(WorkingDirectory)
185 else
186 FOutputPath := InclPathDelim(OutputPathBase);
187 FOutputPath += 'castle-engine-output' + PathDelim;
188
189 if CreateIfNecessary then
190 begin
191 CheckForceDirectories(FOutputPath);
192
193 OutputNote := FOutputPath + 'DO-NOT-COMMIT-THIS-DIRECTORY.txt';
194 if not RegularFileExists(OutputNote) then
195 StringToFile(OutputNote, OutputNoteContents);
196 end;
197
198 FOutputPathForWorkingDirectory := WorkingDirectory;
199 end;
200
201 Result := FOutputPath;
202 end;
203
204 procedure ParametersAddMacros(const Macros, Parameters: TStringStringMap;
205 const ParameterMacroPrefix: String);
206 var
207 Pair: TStringStringMap.TDictionaryPair;
208 begin
209 for Pair in Parameters do
210 Macros.Add(UpperCase(ParameterMacroPrefix + Pair.Key), Pair.Value);
211 end;
212
213 type
214 TFindLinkResHandler = class
215 FileName: String;
216 procedure FoundFile(const FileInfo: TFileInfo; var StopSearch: boolean);
217 end;
218
219 procedure TFindLinkResHandler.FoundFile(const FileInfo: TFileInfo; var StopSearch: boolean);
220 begin
221 if FileName <> '' then
222 raise Exception.CreateFmt('Multiple linker input files in the same directory: "%s" and "%s". Delete all "link*.res" here and run the process again', [
223 FileName,
224 FileInfo.AbsoluteName
225 ]);
226 FileName := FileInfo.AbsoluteName;
227 end;
228
229 function FindLinkRes(const Path: String): String;
230 var
231 Handler: TFindLinkResHandler;
232 LinkFilesRes: String;
233 begin
234 LinkFilesRes := CombinePaths(Path, 'linkfiles.res');
235 if FileExists(LinkFilesRes) then
236 begin
237 { Latest FPC 3.3.1 introduced linkfiles.res file
238 (see FPC sources compiler/systems/t_bsd.pas , started in commit
239 https://github.com/graemeg/freepascal/commit/36d634bd87427e480d4f82344c5f7e5c7d6b57eb
240 it seems ).
241 It contains what we need: the list of .o files.
242 The link<some-process-id>.res is also generated, but it is no longer useful for us.
243 So exit with "linkfiles.res", without causing "Multiple linker input files..." error. }
244 Exit(LinkFilesRes);
245 end;
246
247 { First try to match linkfiles*.res, ignoring other link*.res.
248 This is good for FPC >= 3.2.2. }
249 Handler := TFindLinkResHandler.Create;
250 try
251 FindFiles(Path, 'linkfiles*.res', false, @Handler.FoundFile, []);
252 Result := Handler.FileName;
253 if Result <> '' then
254 Exit;
255 finally FreeAndNil(Handler) end;
256
257 { If no linkfiles*.res found, try to match any link*.res.
258 This is good for FPC development between 3.2.0 and 3.2.2. }
259 Handler := TFindLinkResHandler.Create;
260 try
261 FindFiles(Path, 'link*.res', false, @Handler.FoundFile, []);
262 Result := Handler.FileName;
263 if Result <> '' then
264 Exit;
265 finally FreeAndNil(Handler) end;
266
267 raise Exception.CreateFmt('Cannot find any linker input file in the directory "%s"', [
268 Path
269 ]);
270 end;
271
272 procedure DoMakeExecutable(const PathAndName: String);
273 {$ifdef UNIX}
274 var
275 ChmodResult: CInt;
276 begin
277 ChmodResult := FpChmod(PathAndName,
278 S_IRUSR or S_IWUSR or S_IXUSR or
279 S_IRGRP or S_IXGRP or
280 S_IROTH or S_IXOTH);
281 if ChmodResult <> 0 then
282 WritelnWarning('Package', Format('Error setting executable bit on "%s": %s', [
283 PathAndName,
284 SysErrorMessage(ChmodResult)
285 ]));
286 {$else}
287 begin
288 WritelnWarning('Package', 'Packaging for a platform where UNIX permissions matter, but we cannot set "chmod" on this platform. This usually means that you package for Unix from Windows, and means that "executable" bit inside binary in tar.gz archive may not be set --- archive may not be 100% comfortable for Unix users');
289 {$endif}
290 end;
291
292 procedure ErrorBox(const Message: String);
293
294 {$ifdef MSWINDOWS}
295 procedure WindowsErrorBox(const Text: String; const Caption: String = 'Error'; const Parent: HWND = 0);
296 begin
297 MessageBox(Parent, PChar(Text), PChar(Caption), MB_OK or MB_ICONERROR or MB_TASKMODAL);
298 end;
299 {$endif}
300
301 begin
302 {$ifdef MSWINDOWS}
303 WindowsErrorBox(Message);
304 {$else}
305 RunCommandSimple('zenity', ['--error', '--no-markup', '--text=' + Message]);
306 {$endif}
307 end;
308
309 function CachePath: String;
310 begin
311 Result := InclPathDelim(GetAppConfigDir(false)) + 'cache' + PathDelim;
312 end;
313
314 { Hash of arbitrary data. Always 0 for DataSize = 0. }
315 function HashData(const Data; const DataSize: SizeInt): UInt32;
316 var
317 DataBytes: TByteArray absolute Data;
318 I: SizeInt;
319 begin
320 Result := 0;
321 for I := 0 to DataSize - 1 do
322 begin
323 Result := Result xor DataBytes[I];
324 {$I norqcheckbegin.inc}
325 Result := Result * 16777619;
326 {$I norqcheckend.inc}
327 end;
328 end;
329
330 { Hash of a String. Always 0 for empty string. }
331 function HashString(const S: String): UInt32;
332 begin
333 if S = '' then
334 Result := 0
335 else
336 Result := HashData(S[1], Length(S) * SizeOf(Char));
337 end;
338
339 function CreateGUIDFromHash(const Seed: String): TGuid;
340
341 (*
342 var
343 { FPC: https://www.freepascal.org/docs-html/rtl/system/randseed.html
344 Delphi: https://docwiki.embarcadero.com/Libraries/Sydney/en/System.RandSeed }
345 SavedRandSeed: {$ifdef FPC} Cardinal {$else} Integer {$endif}};
346 begin
347 SavedRandSeed := RandSeed;
348 try
349 RandSeed := HashString(Seed);
350 Result := CreateGUID;
351 finally
352 RandSeed := SavedRandSeed;
353 end;
354 *)
355
356 { Use approach that doesn't depend on Random algorithm, which may differ between FPC, Delphi
357 and even their particular versions. }
358
359 var
360 I: Integer;
361 begin
362 Result.D1 := HashString(Seed);
363 { Below we assign UInt32 values (HashString) to smaller types, just ignore the overflows. }
364 {$I norqcheckbegin.inc}
365 Result.D2 := HashString(Seed + 'D2');
366 Result.D3 := HashString(Seed + 'D3');
367 for I := Low(Result.D4) to High(Result.D4) do
368 Result.D4[I] := HashString(Seed + 'D4' + IntToStr(I));
369 {$I norqcheckend.inc}
370 end;
371
372 procedure ZipDirectory(const ZipFileName: String; Directory: String);
373
374 procedure ZipUsingExternalApplication;
375 var
376 DirectoryParentPath, DirectoryName: String;
377 begin
378 Directory := ExclPathDelim(Directory);
379 DirectoryName := ExtractFileName(Directory);
380 DirectoryParentPath := ExtractFilePath(Directory);
381
382 // be sure to first delete target zip, otherwise zip command will add to existing file
383 if FileExists(ZipFileName) then
384 CheckDeleteFile(ZipFileName);
385
386 RunCommandSimple(DirectoryParentPath, 'zip',
387 ['-q', '-r', ZipFileName, DirectoryName]);
388 end;
389
390 var
391 Zipper: TZipper;
392 FilesList: TFileInfoList;
393 FileInfo: TFileInfo;
394 DirectoryParentPath: String;
395 ExpandedZipFileName: String;
396 begin
397 { On macOS, FPC Zipper seems not able to preserve "executable" bit when packing.
398 Observed with FPC 3.2.2, Darwin/x86_64.
399
400 What is weird is that Zipper used on Linux/x86_64 with the same FPC version
401 3.2.2 preserves executable permissions fine.
402 And the Zipper code doesn't seem to do anything Linux/Darwin specific,
403 there are only general "UNIX" defines,
404 and I (Michalis) didn't even find where it actually scans file permissions
405 for executable bit.
406 But evidently it fails on Darwin.
407
408 I double-checked the problem is indeed at zipping.
409 - Input files to zip have executable permissions OK (our packaging
410 preserves executable bit when copying the executable to temp dir OK).
411 - It is a problem of zipping, not of unzipping. Copying the zip made
412 on macOS to another system confirms that files inside lack executable
413 permission.
414 }
415 {$ifdef DARWIN}
416 ZipUsingExternalApplication;
417 Exit;
418 {$endif}
419
420 ExpandedZipFileName := ExpandFileName(ZipFileName);
421
422 Zipper := TZipper.Create;
423 try
424 Zipper.FileName := ZipFileName;
425
426 Directory := ExclPathDelim(Directory);
427 DirectoryParentPath := ExtractFilePath(Directory);
428
429 FilesList := FindFilesList(Directory, '*', { FindDirectories } false, [ffRecursive]);
430 try
431 for FileInfo in FilesList do
432 begin
433 if SameFileName(ExpandedZipFileName, FileInfo.AbsoluteName) then
434 begin
435 WritelnWarning('Package', Format('Directory to zip contains also the target zip file "%s", not packing (to avoid possible reading and writing the file at the same time)', [
436 FileInfo.AbsoluteName
437 ]));
438 Continue;
439 end;
440 Zipper.Entries.AddFileEntry(
441 FileInfo.AbsoluteName,
442 ExtractRelativePath(DirectoryParentPath, FileInfo.AbsoluteName));
443 end;
444 finally FreeAndNil(FilesList) end;
445
446 { Store filenames using UTF-8 in zip,
447 see https://wiki.lazarus.freepascal.org/paszlib#TZipper }
448 {$ifndef VER3_0} // only for FPC >= 3.2.0
449 Zipper.UseLanguageEncoding := true;
450 {$endif}
451
452 Zipper.ZipAllFiles;
453 finally FreeAndNil(Zipper) end;
454 end;
455
456 end.