Repository navigation
Expand file tree
/
Copy pathEncodingFixToolCore.pas
More file actions
1890 lines (1734 loc) · 53.5 KB
/
Copy pathEncodingFixToolCore.pas
File metadata and controls
1890 lines (1734 loc) · 53.5 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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
unit EncodingFixToolCore;
{
Delphi *.pas encoding fix tool
--------------------------------
- Gathers files by path / recursive / extensions
- Parallel processing (TParallel.For)
- For each file:
* Try strict UTF-8 decode; if OK => (verbose: "OK"), skip save
* Else fix per line (mixed encodings):
- Try UTF-8 (strict), CP1250 (Polish/Central Europe), CP1252 (Western/German)
- Score decodes and pick the best for each line
* Save as UTF-8 with configurable BOM (default: y)
* Optionally create a backup in bkp-dir preserving relative paths
- Modes:
dry, silent, verbose, help
- Summary: time elapsed, files changed
Notes:
* Default UTF-8 BOM = yes (Delphi IDE/compiler behave best with BOM).
}
interface
uses
System.Character, System.Classes, System.Generics.Collections, System.IOUtils, System.StrUtils,
System.SyncObjs, System.SysUtils, System.Threading;
type
TEncodingFixTool = class
public type
TEndOfLineMode = (elmPreserve, elmCrlf);
TOutputFormat = (ofText, ofJson);
TScopeMode = (smAll, smGitChanged);
TOptions = record
DryRun: boolean;
Silent: boolean;
Verbose: boolean; // not compatible with Silent
Path: string;
SingleFilePath: string;
Recursive: boolean; // default y
Exts: TArray<string>; // normalized: ".pas", ".dpr", etc.
Utf8Bom: boolean; // default y
EolMode: TEndOfLineMode; // default preserve
OutputFormat: TOutputFormat; // default text
ScopeMode: TScopeMode; // default all files
BackupDir: string; // if <> '', create backups preserving relative path
end;
private
type
TSafeConsole = class
strict private
class var FCrit: TCriticalSection;
public
class constructor Create;
class destructor Destroy;
class procedure WriteLine(const aMsg: string);
end;
private
fWantedExts: TStringList;
fEnc1250: TEncoding;
fEnc1252: TEncoding;
function ParseCommandLine(out aOptions: TOptions): integer;
function ShowHelp: integer;
function NormalizeExtList(const aCSV: string): TArray<string>;
function CollectFiles(const aOptions: TOptions): TArray<string>;
function CollectGitChangedFiles(const aOptions: TOptions): TArray<string>;
function IsWantedExt(const aFile: string): boolean;
function IsPathWithin(const aRootPath, aFileName: string): boolean;
function QuoteShellArg(const aValue: string): string;
function RunCommand(const aCommandLine, aWorkingDirectory: string): integer;
// Encoding helpers
function HasUtf8Bom(const aBytes: TBytes): boolean;
function HasUtf16BEBom(const aBytes: TBytes): boolean;
function HasUtf16LEBom(const aBytes: TBytes): boolean;
function IsUtf8Strict(const aBytes: TBytes): boolean;
function GetWithoutUtf8Bom(const aBytes: TBytes): TBytes;
function SplitLinesByBytes(const aBytes: TBytes): TArray<TBytes>;
function IsAsciiBytes(const aBytes: TBytes): boolean;
function IsBinaryDfmFile(const aFile: string; const aBytes: TBytes): boolean;
function NormalizeTextEolToCrlf(const aText: string; out aChanged: boolean): string;
function DecodeBestPerLine(const aLineBytes: TBytes; out aEncName: string): string;
function ScoreDecoded(const aText: string): integer;
function ContainsSpecials(const aText: string): integer;
function FixFile(const aFile: string; const aOptions: TOptions; out aChanged: boolean; out aReason: string): boolean;
function SaveTextUTF8(const aFile: string; const aText: string; aWithBOM: boolean; out aError: string): boolean;
function MakeBackupPath(const aOptions: TOptions; const aRootPath, aFile: string): string;
function MakeRelativeTo(const aRootPath, aFile: string): string;
procedure PrepareExtIndex(const aExts: TArray<string>);
public
constructor Create;
destructor Destroy; override;
class function RunFromCommandLine: integer; static;
end;
implementation
uses
System.Diagnostics, System.JSON,
System.WideStrUtils,
{$IFDEF MSWINDOWS}
Winapi.Windows,
{$ENDIF}
AutoFree;
{$IFDEF POSIX}
type
TPosixTimespec = record
Seconds: Int64;
Nanoseconds: Int64;
end;
const
cLibC = 'libc.so.6';
cPosixInterrupted = 4;
cPosixNoHang = 1;
cPosixSignalKill = 9;
function PosixClockGetTime(aClockId: integer; aTime: Pointer): integer; cdecl;
external cLibC name 'clock_gettime';
function PosixErrorLocation: PInteger; cdecl; external cLibC name '__errno_location';
function PosixExecv(aPath: PAnsiChar; aArgv: Pointer): integer; cdecl; external cLibC name 'execv';
procedure PosixExit(aStatus: integer); cdecl; external cLibC name '_exit';
function PosixFork: integer; cdecl; external cLibC name 'fork';
function PosixKill(aPid, aSignal: integer): integer; cdecl; external cLibC name 'kill';
function PosixSetProcessGroup(aPid, aProcessGroup: integer): integer; cdecl; external cLibC name 'setpgid';
function PosixUSleep(aMicroseconds: Cardinal): integer; cdecl; external cLibC name 'usleep';
function PosixWaitPid(aPid: integer; aStatus: PInteger; aOptions: integer): integer; cdecl;
external cLibC name 'waitpid';
function PosixLastError: integer;
begin
Result := PosixErrorLocation^;
end;
function PosixMonotonicMilliseconds: Int64;
var
lTime: TPosixTimespec;
begin
if PosixClockGetTime(1, @lTime) <> 0 then
begin
raise Exception.Create('clock_gettime failed');
end;
Result := (lTime.Seconds * 1000) + (lTime.Nanoseconds div 1000000);
end;
function PosixWaitForChild(aPid: integer; out aStatus: integer): boolean;
var
lWaitPid: integer;
begin
repeat
lWaitPid := PosixWaitPid(aPid, @aStatus, 0);
if lWaitPid = aPid then
begin
Exit(True);
end;
if (lWaitPid < 0) and (PosixLastError <> cPosixInterrupted) then
begin
Exit(False);
end;
until False;
end;
{$ENDIF}
const
cCommandPollMs = 10;
cCommandTimeoutMs = 30000;
cUtf8Bom0 = Byte($EF);
cUtf8Bom1 = Byte($BB);
cUtf8Bom2 = Byte($BF);
cUtf16LEBom0 = Byte($FF);
cUtf16LEBom1 = Byte($FE);
cUtf16BEBom0 = Byte($FE);
cUtf16BEBom1 = Byte($FF);
{ ===================== Utilities ===================== }
class constructor TEncodingFixTool.TSafeConsole.Create;
begin
FCrit := TCriticalSection.Create;
end;
class destructor TEncodingFixTool.TSafeConsole.Destroy;
begin
FCrit.Free;
end;
class procedure TEncodingFixTool.TSafeConsole.WriteLine(const aMsg: string);
begin
FCrit.Acquire;
try
writeln(aMsg);
finally
FCrit.release;
end;
end;
{ ===================== TEncodingFixTool lifecycle ===================== }
constructor TEncodingFixTool.Create;
begin
inherited Create;
try
fWantedExts := TStringList.Create;
fWantedExts.Sorted := True;
fWantedExts.Duplicates := dupIgnore;
fWantedExts.CaseSensitive := False;
fEnc1250 := TEncoding.GetEncoding(1250);
fEnc1252 := TEncoding.GetEncoding(1252);
except
fEnc1252.Free;
fEnc1252 := nil;
fEnc1250.Free;
fEnc1250 := nil;
fWantedExts.Free;
fWantedExts := nil;
raise;
end;
end;
destructor TEncodingFixTool.Destroy;
begin
fWantedExts.Free;
fEnc1252.Free;
fEnc1250.Free;
inherited;
end;
procedure TEncodingFixTool.PrepareExtIndex(const aExts: TArray<string>);
var
s: string;
begin
fWantedExts.BeginUpdate;
try
fWantedExts.Clear;
for s in aExts do
begin
if s <> '' then
begin
fWantedExts.Add(LowerCase(s));
end;
end;
finally
fWantedExts.EndUpdate;
end;
end;
function TEncodingFixTool.NormalizeExtList(const aCSV: string): TArray<string>;
var
lParts: TArray<string>;
i: integer;
s: string;
begin
lParts := aCSV.Split([',', ';', ' '], TStringSplitOptions.ExcludeEmpty);
SetLength(Result, length(lParts));
for i := 0 to High(lParts) do
begin
s := lParts[i].ToLower
.Trim([' ', '"', '''']);
if s.StartsWith('*.') then
begin
s := s.Substring(1); // "*.pas" -> ".pas"
end else if (s <> '') and (s[1] <> '.') then
begin
s := '.' + s; // "pas" -> ".pas"
end;
Result[i] := s;
end;
end;
function TEncodingFixTool.CollectFiles(const aOptions: TOptions): TArray<string>;
var
g: TGarbos;
lFiles: TList<string>;
lSearchOpt: TSearchOption;
lExt, lPattern: string;
begin
if aOptions.SingleFilePath <> '' then
begin
if IsWantedExt(aOptions.SingleFilePath) then
begin
Result := [aOptions.SingleFilePath];
end else begin
Result := [];
end;
Exit;
end;
if aOptions.ScopeMode = TScopeMode.smGitChanged then
begin
Exit(CollectGitChangedFiles(aOptions));
end;
GC(lFiles, TList<string>.Create, g);
if aOptions.Recursive then
lSearchOpt := TSearchOption.soAllDirectories
else
lSearchOpt := TSearchOption.soTopDirectoryOnly;
for lExt in fWantedExts do
begin
lPattern := '*' + lExt; // e.g. ".pas" -> "*.pas"
lFiles.AddRange(TDirectory.GetFiles(aOptions.Path, lPattern, lSearchOpt));
end;
Result := lFiles.ToArray;
end;
function TEncodingFixTool.CollectGitChangedFiles(const aOptions: TOptions): TArray<string>;
var
g: TGarbos;
lCommand: string;
lEntries: TArray<string>;
lEntryIndex: integer;
lExitCode: integer;
lFile: string;
lFiles: TList<string>;
lLine: string;
lOutputFileName: string;
lPath: string;
lRootPath: string;
lScanRootPath: string;
lStatus: string;
lWorkTreeRootFileName: string;
begin
GC(lFiles, TList<string>.Create, g);
lOutputFileName := TPath.Combine(TPath.GetTempPath, 'EncodingFixTool-git-' + TGuid.NewGuid.ToString + '.txt');
lWorkTreeRootFileName := TPath.Combine(TPath.GetTempPath, 'EncodingFixTool-git-root-' + TGuid.NewGuid.ToString + '.txt');
try
{$IFDEF MSWINDOWS}
lCommand := 'cmd.exe /C git -C ' + QuoteShellArg(aOptions.Path) + ' rev-parse --show-toplevel > ' +
QuoteShellArg(lWorkTreeRootFileName);
{$ELSE}
lCommand := 'git -C ' + QuoteShellArg(aOptions.Path) + ' rev-parse --show-toplevel > ' +
QuoteShellArg(lWorkTreeRootFileName);
{$ENDIF}
lExitCode := RunCommand(lCommand, aOptions.Path);
if lExitCode <> 0 then
begin
raise Exception.Create('git rev-parse failed');
end;
lRootPath := IncludeTrailingPathDelimiter(TFile.ReadAllText(lWorkTreeRootFileName, TEncoding.UTF8).Trim);
lScanRootPath := IncludeTrailingPathDelimiter(ExpandFileName(aOptions.Path));
{$IFDEF MSWINDOWS}
lCommand := 'cmd.exe /C git -C ' + QuoteShellArg(aOptions.Path) +
' status --porcelain=v1 -z --untracked-files=all > ' + QuoteShellArg(lOutputFileName);
{$ELSE}
lCommand := 'git -C ' + QuoteShellArg(aOptions.Path) +
' status --porcelain=v1 -z --untracked-files=all > ' + QuoteShellArg(lOutputFileName);
{$ENDIF}
lExitCode := RunCommand(lCommand, aOptions.Path);
if lExitCode <> 0 then
begin
raise Exception.Create('git status failed');
end;
lEntries := TEncoding.UTF8.GetString(TFile.ReadAllBytes(lOutputFileName))
.Split([#0], TStringSplitOptions.ExcludeEmpty);
lEntryIndex := 0;
while lEntryIndex <= High(lEntries) do
begin
lLine := lEntries[lEntryIndex];
Inc(lEntryIndex);
if Length(lLine) < 4 then
begin
Continue;
end;
lStatus := Copy(lLine, 1, 2);
if (lStatus = ' D') or (lStatus = 'D ') or (lStatus = 'DD') then
begin
Continue;
end;
lPath := Copy(lLine, 4, MaxInt);
if (Pos('R', lStatus) > 0) or (Pos('C', lStatus) > 0) then
begin
Inc(lEntryIndex); // -z appends the rename/copy source as a second entry.
end;
lPath := StringReplace(lPath, '/', TPath.DirectorySeparatorChar, [rfReplaceAll]);
lFile := TPath.GetFullPath(TPath.Combine(lRootPath, lPath));
if TFile.Exists(lFile) and IsPathWithin(lScanRootPath, lFile) and IsWantedExt(lFile) then
begin
lFiles.Add(lFile);
end;
end;
finally
if TFile.Exists(lOutputFileName) then
begin
TFile.Delete(lOutputFileName);
end;
if TFile.Exists(lWorkTreeRootFileName) then
begin
TFile.Delete(lWorkTreeRootFileName);
end;
end;
Result := lFiles.ToArray;
end;
function TEncodingFixTool.IsWantedExt(const aFile: string): boolean;
begin
Result := fWantedExts.IndexOf(LowerCase(ExtractFileExt(aFile))) >= 0;
end;
function TEncodingFixTool.IsPathWithin(const aRootPath, aFileName: string): boolean;
begin
{$IFDEF MSWINDOWS}
Result := StartsText(aRootPath, aFileName);
{$ELSE}
Result := StartsStr(aRootPath, aFileName);
{$ENDIF}
end;
function TEncodingFixTool.QuoteShellArg(const aValue: string): string;
begin
{$IFDEF MSWINDOWS}
Result := '"' + StringReplace(aValue, '"', '\"', [rfReplaceAll]) + '"';
{$ELSE}
Result := #39 + StringReplace(aValue, #39, #39 + '"' + #39 + '"' + #39, [rfReplaceAll]) + #39;
{$ENDIF}
end;
function TEncodingFixTool.RunCommand(const aCommandLine, aWorkingDirectory: string): integer;
var
{$IFDEF MSWINDOWS}
lExitCode: DWORD;
lCommandLineChars: TArray<Char>;
lProcessInformation: TProcessInformation;
lStartupInfo: TStartupInfo;
lWaitResult: Cardinal;
{$ELSE}
lArguments: array[0..3] of PAnsiChar;
lCommandLine: UTF8String;
lPid: integer;
lReaped: boolean;
lShellArg: UTF8String;
lShellName: UTF8String;
lShellPath: UTF8String;
lStartTime: Int64;
lStatus: integer;
lWaitPid: integer;
{$ENDIF}
begin
{$IFDEF MSWINDOWS}
lCommandLineChars := aCommandLine.ToCharArray;
SetLength(lCommandLineChars, Length(lCommandLineChars) + 1);
ZeroMemory(@lProcessInformation, SizeOf(lProcessInformation));
ZeroMemory(@lStartupInfo, SizeOf(lStartupInfo));
lStartupInfo.cb := SizeOf(lStartupInfo);
if not CreateProcess(nil, PChar(lCommandLineChars), nil, nil, False, CREATE_NO_WINDOW, nil, PChar(aWorkingDirectory),
lStartupInfo, lProcessInformation) then
begin
RaiseLastOSError;
end;
try
lWaitResult := WaitForSingleObject(lProcessInformation.hProcess, cCommandTimeoutMs);
if lWaitResult <> WAIT_OBJECT_0 then
begin
TerminateProcess(lProcessInformation.hProcess, 1);
raise Exception.Create('process timed out');
end;
if not GetExitCodeProcess(lProcessInformation.hProcess, lExitCode) then
begin
RaiseLastOSError;
end;
Result := Integer(lExitCode);
finally
CloseHandle(lProcessInformation.hThread);
CloseHandle(lProcessInformation.hProcess);
end;
{$ELSE}
lCommandLine := UTF8String('cd ' + QuoteShellArg(aWorkingDirectory) + ' && ' + aCommandLine);
lShellArg := UTF8String('-c');
lShellName := UTF8String('sh');
lShellPath := UTF8String('/bin/sh');
lArguments[0] := PAnsiChar(lShellName);
lArguments[1] := PAnsiChar(lShellArg);
lArguments[2] := PAnsiChar(lCommandLine);
lArguments[3] := nil;
lPid := PosixFork;
if lPid < 0 then
begin
raise Exception.Create('fork failed');
end;
if lPid = 0 then
begin
if PosixSetProcessGroup(0, 0) <> 0 then
begin
PosixExit(126);
end;
PosixExecv(PAnsiChar(lShellPath), @lArguments[0]);
PosixExit(127);
end;
lReaped := False;
try
PosixSetProcessGroup(lPid, lPid);
lStartTime := PosixMonotonicMilliseconds;
repeat
lWaitPid := PosixWaitPid(lPid, @lStatus, cPosixNoHang);
if lWaitPid = lPid then
begin
lReaped := True;
Break;
end;
if lWaitPid < 0 then
begin
if PosixLastError = cPosixInterrupted then
begin
Continue;
end;
raise Exception.Create('waitpid failed');
end;
if PosixMonotonicMilliseconds - lStartTime >= cCommandTimeoutMs then
begin
if PosixKill(-lPid, cPosixSignalKill) <> 0 then
begin
PosixKill(lPid, cPosixSignalKill);
end;
if not PosixWaitForChild(lPid, lStatus) then
begin
raise Exception.Create('waitpid failed after timeout');
end;
lReaped := True;
raise Exception.Create('process timed out');
end;
PosixUSleep(cCommandPollMs * 1000);
until False;
if (lStatus and $7F) = 0 then
Result := (lStatus shr 8) and $FF
else
Result := 128 + (lStatus and $7F);
finally
if not lReaped then
begin
PosixKill(-lPid, cPosixSignalKill);
PosixKill(lPid, cPosixSignalKill);
if not PosixWaitForChild(lPid, lStatus) then
begin
raise Exception.Create('waitpid cleanup failed');
end;
end;
end;
{$ENDIF}
end;
function TEncodingFixTool.IsUtf8Strict(const aBytes: TBytes): boolean;
var
lBytesNoBom: TBytes;
begin
lBytesNoBom := GetWithoutUtf8Bom(aBytes);
if length(lBytesNoBom) = 0 then
exit(True);
Result := TEncoding.Utf8.IsBufferValid(lBytesNoBom);
end;
function TEncodingFixTool.HasUtf8Bom(const aBytes: TBytes): boolean;
begin
Result := (length(aBytes) >= 3) and (aBytes[0] = cUtf8Bom0) and (aBytes[1] = cUtf8Bom1) and
(aBytes[2] = cUtf8Bom2);
end;
function TEncodingFixTool.HasUtf16BEBom(const aBytes: TBytes): boolean;
begin
Result := (length(aBytes) >= 2) and (aBytes[0] = cUtf16BEBom0) and (aBytes[1] = cUtf16BEBom1);
end;
function TEncodingFixTool.HasUtf16LEBom(const aBytes: TBytes): boolean;
begin
Result := (length(aBytes) >= 2) and (aBytes[0] = cUtf16LEBom0) and (aBytes[1] = cUtf16LEBom1);
end;
function TEncodingFixTool.SplitLinesByBytes(const aBytes: TBytes): TArray<TBytes>;
var
g: TGarbos;
i, lStart: integer;
b: BYTE;
lLine: TBytes;
lList: TList<TBytes>;
begin
GC(lList, TList<TBytes>.Create, g);
lStart := 0;
i := 0;
while i < length(aBytes) do
begin
b := aBytes[i];
if b = $0A then
begin
// LF: line ends before this char
SetLength(lLine, i - lStart);
if length(lLine) > 0 then
move(aBytes[lStart], lLine[0], length(lLine));
lList.Add(lLine);
Inc(i);
lStart := i;
end else if b = $0D then
begin
// CR: line ends here; handle CRLF or standalone CR
SetLength(lLine, i - lStart);
if length(lLine) > 0 then
move(aBytes[lStart], lLine[0], length(lLine));
lList.Add(lLine);
Inc(i);
if (i < length(aBytes)) and (aBytes[i] = $0A) then
begin
Inc(i); // consume LF
end;
lStart := i;
end else begin
Inc(i);
end;
end;
// last line (no trailing EOL)
if lStart <= length(aBytes) - 1 then
begin
SetLength(lLine, length(aBytes) - lStart);
if length(lLine) > 0 then
move(aBytes[lStart], lLine[0], length(lLine));
lList.Add(lLine);
end;
Result := lList.ToArray;
end;
function TEncodingFixTool.ContainsSpecials(const aText: string): integer;
const
// Polish + German diacritics; count good matches positively.
POL = 'ąćęłńóśźżĄĆĘŁŃÓŚŹŻ';
GER = 'äöüÄÖÜßẞ';
var
lScore: integer;
ch: char;
begin
lScore := 0;
for ch in aText do
begin
if (pos(ch, POL) > 0) or (pos(ch, GER) > 0) then
begin
Inc(lScore);
end;
end;
Result := lScore;
end;
function TEncodingFixTool.ScoreDecoded(const aText: string): integer;
var
lScore: integer;
ch: char;
begin
// Base heuristic:
// +2 for known PL/DE diacritics,
// +1 for typical source-text ASCII range,
// -2 for control chars (excluding tab),
// -1 for � replacement if it appears (just in case)
lScore := 0;
Inc(lScore, 2 * ContainsSpecials(aText));
for ch in aText do
begin
// U+FFFD REPLACEMENT CHARACTER: indicates decoding replacement for invalid/unknown bytes; penalize it.
if ch = #$FFFD then
begin
Dec(lScore, 1);
end else if (ch = #9) or (ch = #10) or (ch = #13) then
begin
// ignore tabs/newlines here
end else if ch.IsControl then
begin
Dec(lScore, 2);
end else if ch.IsLetterOrDigit or ch.IsWhiteSpace or CharInSet(ch, ['.', ',', ';', ':', '-', '_', '(', ')', '[', ']', '{', '}', '''', '"', '/', '\', '+', '*', '=', '<', '>', '!', '?', '@', '#', '$', '%', '^', '&', '|']) then
begin
Inc(lScore, 1);
end;
end;
Result := lScore;
end;
function TEncodingFixTool.IsAsciiBytes(const aBytes: TBytes): boolean;
var
b: Byte;
begin
for b in aBytes do
begin
if b >= $80 then
Exit(False);
end;
Exit(True);
end;
function TEncodingFixTool.IsBinaryDfmFile(const aFile: string; const aBytes: TBytes): boolean;
begin
Result := SameText(ExtractFileExt(aFile), '.dfm') and (Length(aBytes) >= 4) and
(aBytes[0] = Ord('T')) and (aBytes[1] = Ord('P')) and (aBytes[2] = Ord('F')) and (aBytes[3] = Ord('0'));
end;
function TEncodingFixTool.NormalizeTextEolToCrlf(const aText: string; out aChanged: boolean): string;
var
g: TGarbos;
i: integer;
c: Char;
lBuilder: TStringBuilder;
begin
aChanged := False;
GC(lBuilder, TStringBuilder.Create(Length(aText) + 16), g);
i := 1;
while i <= Length(aText) do
begin
c := aText[i];
if c = #13 then
begin
lBuilder.Append(#13#10);
if (i < Length(aText)) and (aText[i + 1] = #10) then
begin
Inc(i, 2);
end else begin
aChanged := True;
Inc(i);
end;
end else if c = #10 then
begin
lBuilder.Append(#13#10);
aChanged := True;
Inc(i);
end else begin
lBuilder.Append(c);
Inc(i);
end;
end;
if aChanged then
Result := lBuilder.ToString
else
Result := aText;
end;
function TEncodingFixTool.DecodeBestPerLine(const aLineBytes: TBytes; out aEncName: string): string;
var
{$IFDEF MSWINDOWS}
lANSI: TEncoding;
sANSI: string;
{$ENDIF}
s1250, s1252: string;
bestS: string;
bestScore, sc: integer;
begin
// 0) Pure ASCII? Treat as ASCII explicitly (safe UTF-8 subset)
if IsAsciiBytes(aLineBytes) then
begin
aEncName := 'ASCII';
Result := TEncoding.Utf8.GetString(aLineBytes);
exit;
end;
// 1) Try strict UTF-8 first
if IsUtf8Strict(aLineBytes) then
begin
aEncName := 'UTF-8';
Result := TEncoding.Utf8.GetString(aLineBytes);
exit;
end;
// 2) Try single-byte candidates; they never fail, so score them.
s1250 := fEnc1250.GetString(aLineBytes);
s1252 := fEnc1252.GetString(aLineBytes);
{$IFDEF MSWINDOWS}
lANSI := TEncoding.ANSI;
sANSI := lANSI.GetString(aLineBytes);
{$ENDIF}
bestS := s1250;
aEncName := 'Windows-1250';
bestScore := ScoreDecoded(s1250);
sc := ScoreDecoded(s1252);
if sc > bestScore then
begin
{$IFDEF MSWINDOWS}
bestScore := sc;
{$ENDIF}
bestS := s1252;
aEncName := 'Windows-1252';
end;
{$IFDEF MSWINDOWS}
sc := ScoreDecoded(sANSI);
if sc > bestScore then
begin
bestS := sANSI;
aEncName := 'ANSI';
end;
{$ENDIF}
Result := bestS;
end;
function TEncodingFixTool.MakeBackupPath(const aOptions: TOptions; const aRootPath, aFile: string): string;
var
lRel: string;
lRootPath: string;
begin
lRel := aFile;
if aRootPath <> '' then
begin
lRootPath := IncludeTrailingPathDelimiter(aRootPath);
if IsPathWithin(lRootPath, aFile) then
begin
lRel := copy(aFile, length(lRootPath) + 1, MaxInt);
end;
end;
Result := TPath.Combine(IncludeTrailingPathDelimiter(aOptions.BackupDir), lRel);
end;
function TEncodingFixTool.MakeRelativeTo(const aRootPath, aFile: string): string;
var
sRoot: string;
begin
Result := aFile;
if aRootPath <> '' then
begin
sRoot := IncludeTrailingPathDelimiter(aRootPath);
if IsPathWithin(sRoot, aFile) then
Result := copy(aFile, length(sRoot) + 1, MaxInt);
end;
end;
function TEncodingFixTool.SaveTextUTF8(const aFile: string; const aText: string; aWithBOM: boolean; out aError: string): boolean;
var
lContentBytes: TBytes;
lBytes: TBytes;
lTempFile: string;
begin
Result := False;
aError := '';
lTempFile := '';
try
try
lContentBytes := TEncoding.UTF8.GetBytes(aText);
if aWithBOM then
begin
SetLength(lBytes, length(lContentBytes) + 3);
lBytes[0] := cUtf8Bom0;
lBytes[1] := cUtf8Bom1;
lBytes[2] := cUtf8Bom2;
if length(lContentBytes) > 0 then
begin
Move(lContentBytes[0], lBytes[3], length(lContentBytes));
end;
end else begin
lBytes := lContentBytes;
end;
lTempFile := TPath.Combine(ExtractFileDir(aFile), TPath.GetRandomFileName);
TFile.WriteAllBytes(lTempFile, lBytes);
TFile.Copy(lTempFile, aFile, True);
Result := True;
except
on e: Exception do
begin
aError := e.ClassName + ': ' + e.Message;
end;
end;
finally
if (lTempFile <> '') and TFile.Exists(lTempFile) then
begin
TFile.Delete(lTempFile);
end;
end;
end;
function TEncodingFixTool.FixFile(const aFile: string; const aOptions: TOptions; out aChanged: boolean; out aReason: string): boolean;
var
lBytes: TBytes;
lBytesNoBom: TBytes;
lLinesBytes: TArray<TBytes>;
lLine: TBytes;
lFixedLines: TStringBuilder;
lFirst: boolean;
lRoot: string;
lBackupPath: string;
lHasBOM: boolean;
lText: string;
lCRLF, lLF, lCR: integer;
i: integer;
lEOL: string;
lHadTrailingEOL: boolean;
rb: RawByteString;
lEncType: TEncodeType;
lCntUtf8, lCnt1250, lCnt1252: Integer;
{$IFDEF MSWINDOWS}
lCntAnsi: Integer;
{$ENDIF}
lEncName: string;
lReasonEnc: string;
lEolChanged: boolean;
lKinds: Integer;
lSaveError: string;
g: TGarbos;
begin
aChanged := False;
aReason := '';
lBytes := TFile.ReadAllBytes(aFile);
if IsBinaryDfmFile(aFile, lBytes) then
begin
aChanged := False;
aReason := 'Skipped binary DFM';
Result := True;
exit;
end;
if HasUtf16LEBom(lBytes) or HasUtf16BEBom(lBytes) then
begin
if HasUtf16LEBom(lBytes) then
begin
lText := TEncoding.Unicode.GetString(copy(lBytes, 2, length(lBytes) - 2));
lReasonEnc := 'detected UTF-16 LE';
end else begin
lText := TEncoding.BigEndianUnicode.GetString(copy(lBytes, 2, length(lBytes) - 2));
lReasonEnc := 'detected UTF-16 BE';
end;
if aOptions.DryRun then
begin
aChanged := True;
aReason := Format('%s; would save UTF-8 (BOM=%s) (dry-run)',
[lReasonEnc, IfThen(aOptions.Utf8Bom, 'Y', 'N')]);
Result := True;
exit;
end;
if aOptions.BackupDir <> '' then
begin
lRoot := IncludeTrailingPathDelimiter(ExpandFileName(aOptions.Path));
lBackupPath := MakeBackupPath(aOptions, lRoot, aFile);
TDirectory.CreateDirectory(ExtractFileDir(lBackupPath));
TFile.copy(aFile, lBackupPath, True);
end;
if SaveTextUTF8(aFile, lText, aOptions.Utf8Bom, lSaveError) then
begin
aChanged := True;
aReason := Format('%s; saved UTF-8 (BOM=%s)', [lReasonEnc, IfThen(aOptions.Utf8Bom, 'Y', 'N')]);
Result := True;
end else begin
aChanged := False;
aReason := 'Save failed: ' + lSaveError;
Result := False;
end;
exit;
end;
// Detect encoding using System.WideStrUtils.DetectUTF8Encoding
SetLength(rb, length(lBytes));
if length(lBytes) > 0 then
move(lBytes[0], pAnsiChar(rb)^, length(lBytes));
lEncType := DetectUTF8Encoding(rb);
if lEncType = etUSAscii then
begin
if aOptions.EolMode = TEndOfLineMode.elmCrlf then
begin
lText := TEncoding.ASCII.GetString(lBytes);
lText := NormalizeTextEolToCrlf(lText, lEolChanged);
if lEolChanged then
begin
if aOptions.DryRun then
begin
aChanged := True;
aReason := 'Would normalize EOL to CRLF (dry-run)';
Result := True;
exit;
end;
if aOptions.BackupDir <> '' then
begin
lRoot := IncludeTrailingPathDelimiter(ExpandFileName(aOptions.Path));
lBackupPath := MakeBackupPath(aOptions, lRoot, aFile);
TDirectory.CreateDirectory(ExtractFileDir(lBackupPath));
TFile.copy(aFile, lBackupPath, True);
end;
if SaveTextUTF8(aFile, lText, False, lSaveError) then