-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathEncodingFixToolCore.pas
More file actions
1018 lines (913 loc) · 26.8 KB
/
EncodingFixToolCore.pas
File metadata and controls
1018 lines (913 loc) · 26.8 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.SysUtils,
System.Classes,
System.generics.collections,
System.IOUtils,
System.SyncObjs,
System.diagnostics,
System.StrUtils,
System.Character,
System.Threading;
type
TEncodingFixTool = class
public type
TOptions = record
DryRun: boolean;
Silent: boolean;
Verbose: boolean; // not compatible with Silent
Path: string;
Recursive: boolean; // default y
Exts: TArray<string>; // normalized: ".pas", ".dpr", etc.
Utf8Bom: boolean; // default y
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>;
// Encoding helpers
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 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): 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
AutoFree,
System.WideStrUtils;
{ ===================== 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;
fWantedExts := TStringList.Create;
fWantedExts.Sorted := True;
fWantedExts.Duplicates := dupIgnore;
fWantedExts.CaseSensitive := False;
fEnc1250 := TEncoding.GetEncoding(1250);
fEnc1252 := TEncoding.GetEncoding(1252);
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
lFiles: TList<string>;
lSearchOpt: TSearchOption;
Ext, pat: string;
begin
gc(lFiles, TList<string>.Create);
if aOptions.Recursive then
lSearchOpt := TSearchOption.soAllDirectories
else
lSearchOpt := TSearchOption.soTopDirectoryOnly;
for Ext in fWantedExts do
begin
pat := '*' + Ext; // e.g. ".pas" -> "*.pas"
lFiles.AddRange(TDirectory.GetFiles(aOptions.Path, pat, lSearchOpt));
end;
Result := lFiles.ToArray;
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.SplitLinesByBytes(const aBytes: TBytes): TArray<TBytes>;
var
i, lStart: integer;
b: BYTE;
lLine: TBytes;
lList: TList<TBytes>;
begin
lList := TList<TBytes>.Create;
gc(lList);
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.DecodeBestPerLine(const aLineBytes: TBytes; out aEncName: string): string;
var
lANSI: TEncoding;
s1250, s1252, sANSI: 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.
lANSI := TEncoding.ANSI;
s1250 := fEnc1250.GetString(aLineBytes);
s1252 := fEnc1252.GetString(aLineBytes);
sANSI := lANSI.GetString(aLineBytes);
bestS := s1250;
aEncName := 'Windows-1250';
bestScore := ScoreDecoded(s1250);
sc := ScoreDecoded(s1252);
if sc > bestScore then
begin
bestScore := sc;
bestS := s1252;
aEncName := 'Windows-1252';
end;
sc := ScoreDecoded(sANSI);
if sc > bestScore then
begin
bestScore := sc;
bestS := sANSI;
aEncName := 'ANSI';
end;
Result := bestS;
end;
function TEncodingFixTool.MakeBackupPath(const aOptions: TOptions; const aRootPath, aFile: string): string;
var
lRel: string;
begin
// Normalize root and compute relative path
// Ensure trailing delimiter on root
lRel := aFile;
if aRootPath <> '' then
begin
// Make relative to root path if possible
// We compare case-insensitively on Windows
if SameText(copy(aFile, 1, length(IncludeTrailingPathDelimiter(aRootPath))), IncludeTrailingPathDelimiter(aRootPath)) then
begin
lRel := copy(aFile, length(IncludeTrailingPathDelimiter(aRootPath)) + 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 SameText(copy(aFile, 1, length(sRoot)), sRoot) then
Result := copy(aFile, length(sRoot) + 1, MaxInt);
end;
end;
function TEncodingFixTool.SaveTextUTF8(const aFile: string; const aText: string; aWithBOM: boolean): boolean;
var
enc: TUTF8Encoding;
bytes: TBytes;
begin
Result := False;
enc := TUTF8Encoding.Create(aWithBOM);
try
try
bytes := enc.GetBytes(aText);
TFile.WriteAllBytes(aFile, bytes);
Result := True;
except
Result := False;
end;
finally
enc.Free;
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;
lUTF8: TEncoding;
lBom: TBytes;
lHasBOM: boolean;
lText: string;
lCRLF, lLF, lCR: integer;
i: integer;
lEOL: string;
lHadTrailingEOL: boolean;
rb: RawByteString;
lEncType: TEncodeType;
lCntUtf8, lCnt1250, lCnt1252, lCntAnsi, lCntAscii: Integer;
lEncName: string;
lReasonEnc: string;
lKinds: Integer;
begin
aChanged := False;
aReason := '';
lBytes := TFile.ReadAllBytes(aFile);
// 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
// Leave as-is. Do not add BOM even if option requests it.
if aOptions.DryRun then
begin
aChanged := False;
aReason := 'US-ASCII OK';
Result := True;
exit;
end;
aChanged := False;
aReason := 'US-ASCII OK';
Result := True;
exit;
end else
if lEncType = etUTF8 then
begin
// It's UTF-8 (ASCII subset or multibyte). Only ensure BOM matches option.
lUTF8 := TEncoding.Utf8;
lBom := lUTF8.GetPreamble;
lHasBOM := (length(lBytes) >= length(lBom)) and
((length(lBom) = 0) or CompareMem(@lBytes[0], @lBom[0], length(lBom)));
// Decode text ignoring BOM if present
if lHasBOM then
lText := lUTF8.GetString(copy(lBytes, length(lBom), length(lBytes) - length(lBom)))
else
lText := lUTF8.GetString(lBytes);
if aOptions.DryRun then
begin
if (aOptions.Utf8Bom and (not lHasBOM)) then
begin
aChanged := True;
aReason := 'Would add UTF-8 BOM (dry-run)';
end else if ((not aOptions.Utf8Bom) and lHasBOM) then
begin
aChanged := True;
aReason := 'Would remove UTF-8 BOM (dry-run)';
end else
begin
aChanged := False;
aReason := 'UTF-8 OK';
end;
Result := True;
exit;
end;
if (aOptions.Utf8Bom and (not lHasBOM)) or ((not aOptions.Utf8Bom) and lHasBOM) then
begin
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) then
begin
aChanged := True;
aReason := IfThen(aOptions.Utf8Bom and (not lHasBOM), 'Added UTF-8 BOM', 'Removed UTF-8 BOM');
Result := True;
end else
begin
aChanged := False;
aReason := 'Save failed';
Result := False;
end;
exit;
end;
// No change needed
Result := True;
aChanged := False;
aReason := 'UTF-8 OK';
exit;
end;
// Mixed encodings possible (ANSI detected): split by raw CR/LF bytes, decode per line.
lBytesNoBom := GetWithoutUtf8Bom(lBytes);
// Detect dominant EOL and whether the original had a trailing EOL
lCRLF := 0;
lLF := 0;
lCR := 0;
i := 0;
while i < length(lBytesNoBom) do
begin
if lBytesNoBom[i] = $0D then
begin
if (i + 1 < length(lBytesNoBom)) and (lBytesNoBom[i + 1] = $0A) then
begin
Inc(lCRLF);
Inc(i, 2);
end else
begin
Inc(lCR);
Inc(i);
end;
end else if lBytesNoBom[i] = $0A then
begin
Inc(lLF);
Inc(i);
end else
begin
Inc(i);
end;
end;
if (lCRLF >= lLF) and (lCRLF >= lCR) then
lEOL := #13#10
else if (lLF >= lCR) then
lEOL := #10
else
lEOL := #13;
lHadTrailingEOL := False;
if length(lBytesNoBom) > 0 then
begin
if (length(lBytesNoBom) >= 2) and (lBytesNoBom[length(lBytesNoBom) - 2] = $0D) and (lBytesNoBom[length(lBytesNoBom) - 1] = $0A) then
lHadTrailingEOL := True
else if (lBytesNoBom[length(lBytesNoBom) - 1] = $0A) or (lBytesNoBom[length(lBytesNoBom) - 1] = $0D) then
lHadTrailingEOL := True;
end;
lLinesBytes := SplitLinesByBytes(lBytesNoBom);
lFixedLines := TStringBuilder.Create(length(lBytes) + 1024);
gc(lFixedLines);
lCntUtf8 := 0;
lCnt1250 := 0;
lCnt1252 := 0;
lCntAnsi := 0;
lCntAscii := 0;
lFirst := True;
for lLine in lLinesBytes do
begin
if not lFirst then
begin
lFixedLines.append(lEOL);
end else
begin
lFirst := False;
end;
lFixedLines.append(DecodeBestPerLine(lLine, lEncName));
if lEncName = 'UTF-8' then
Inc(lCntUtf8)
else if lEncName = 'Windows-1250' then
Inc(lCnt1250)
else if lEncName = 'Windows-1252' then
Inc(lCnt1252)
else if lEncName = 'ANSI' then
Inc(lCntAnsi)
else if lEncName = 'ASCII' then
Inc(lCntAscii);
end;
if (length(lLinesBytes) > 0) and lHadTrailingEOL then
begin
lFixedLines.append(lEOL);
end;
// Summarize detected encoding(s)
lKinds := 0;
if lCntUtf8 > 0 then Inc(lKinds);
if lCnt1250 > 0 then Inc(lKinds);
if lCnt1252 > 0 then Inc(lKinds);
if lCntAnsi > 0 then Inc(lKinds);
if lKinds > 1 then
lReasonEnc := 'mixed bytes'
else if lCntUtf8 > 0 then
lReasonEnc := 'detected UTF-8'
else if lCnt1250 > 0 then
lReasonEnc := 'detected Windows-1250'
else if lCnt1252 > 0 then
lReasonEnc := 'detected Windows-1252'
else if lCntAnsi > 0 then
lReasonEnc := 'detected ANSI'
else
lReasonEnc := 'detected ASCII';
// If dry-run, do not write anything—just indicate change.
if aOptions.DryRun then
begin
aChanged := True;
aReason := Format('%s; would save UTF-8 (BOM=%s, EOL=%s) (dry-run)',
[lReasonEnc,
IfThen(aOptions.Utf8Bom, 'Y', 'N'),
IfThen(lEOL = #13#10, 'CRLF', IfThen(lEOL = #10, 'LF', 'CR'))]);
Result := True;
exit;
end;
// Backup if requested
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;
// Save fixed version
if SaveTextUTF8(aFile, lFixedLines.ToString, aOptions.Utf8Bom) then
begin
aChanged := True;
aReason := Format('%s; saved UTF-8 (BOM=%s, EOL=%s)',
[lReasonEnc,
IfThen(aOptions.Utf8Bom, 'Y', 'N'),
IfThen(lEOL = #13#10, 'CRLF', IfThen(lEOL = #10, 'LF', 'CR'))]);
Result := True;
end else
begin
aChanged := False;
aReason := 'Save failed';
Result := False;
end;
end;
function TEncodingFixTool.GetWithoutUtf8Bom(const aBytes: TBytes): TBytes;
var
lBom: TBytes;
lHasBOM: boolean;
begin
lBom := TEncoding.Utf8.GetPreamble;
lHasBOM := (length(aBytes) >= length(lBom)) and CompareMem(@aBytes[0], @lBom[0], length(lBom));
if lHasBOM then
Result := copy(aBytes, length(lBom), length(aBytes) - length(lBom))
else
Result := aBytes;
end;
function TEncodingFixTool.ShowHelp: integer;
const
HELP_TEXT: PChar =
'Delphi *.pas Encoding Fix Tool' + sLineBreak +
sLineBreak +
'Usage:' + sLineBreak +
' EncodingFixTool [params]' + sLineBreak +
sLineBreak +
'Params:' + sLineBreak +
' help : Show this help text.' + sLineBreak +
' dry : Dry run (no files are changed).' + sLineBreak +
' s | silent : No console output.' + sLineBreak +
' v | verbose : More output (not compatible with silent).' + sLineBreak +
' path=<dir> : Directory to scan. Default: current working dir.' + sLineBreak +
' recursive=y|n : Recurse into subfolders. Default: y.' + sLineBreak +
' ext=<csv> : Extensions list. Default: pas,dpr. Accepts "pas", ".pas", "*.pas".' + sLineBreak +
' utf8-bom=y|n : Save with UTF-8 BOM (default: y).' + sLineBreak +
' Note: Pure US-ASCII files are left without BOM regardless of utf8-bom.' + sLineBreak +
' bkp-dir=<dir> : If set, save a backup copy before overwriting.' + sLineBreak +
sLineBreak +
'How it works:' + sLineBreak +
'- Files are processed in parallel (TParallel.For).' + sLineBreak +
'- Each file is first tested for strict UTF-8.' + sLineBreak +
'- If that fails, lines are split by raw CR/LF and decoded per line using heuristics' + sLineBreak +
' between UTF-8, Windows-1250 (PL/CE), and Windows-1252 (DE/Western).' + sLineBreak +
'- Fixed text is saved as UTF-8 (with/without BOM per option).' + sLineBreak +
sLineBreak +
'Examples:' + sLineBreak +
' EncodingFixTool dry path=c:\src ext=pas,dpr recursive=n' + sLineBreak +
' EncodingFixTool path=./src ext="*.pas,*.dpr" utf8-bom=n v' + sLineBreak +
' EncodingFixTool path=c:\tmp bkp-dir=c:\bkp' + sLineBreak +
sLineBreak;
begin
writeln(HELP_TEXT);
Result := 0;
end;
function TEncodingFixTool.ParseCommandLine(out aOptions: TOptions): integer;
var
i: integer;
p, Key, Val: string;
eqPos: integer;
function AsYN(const s: string; const aDefault: boolean): boolean;
var
l: string;
begin
l := LowerCase(s.Trim);
if (l = '') then
begin
exit(aDefault);
end else
if (l = 'y') or (l = 'yes') or (l = '1') or (l = 'true') then
begin
exit(True);
end else
if (l = 'n') or (l = 'no') or (l = '0') or (l = 'false') then
begin
exit(False);
end else
begin
exit(aDefault);
end;
end;
begin
// Defaults
aOptions.DryRun := False;
aOptions.Silent := False;
aOptions.Verbose := False;
aOptions.Path := GetCurrentDir;
aOptions.Recursive := True;
aOptions.Exts := NormalizeExtList('pas,dpr');
aOptions.Utf8Bom := True; // default y (Delphi-friendly)
aOptions.BackupDir := '';
// Parse
for i := 1 to ParamCount do
begin
p := Trim(ParamStr(i));
// allow for "-" or "/" param prefixes
if startsStr('-', p) {$IFDEF MsWindows}or StartsStr('/', p){$ENDIF} then
delete(p, 1, 1);
if p = '' then
begin
Continue;
end;
// allow "key=value" or "key:value" or single flag
eqPos := p.IndexOf('=');
if eqPos < 0 then
begin
eqPos := p.IndexOf(':');
end;
if eqPos > 0 then
begin
Key := LowerCase(Trim(copy(p, 1, eqPos)));
Val := Trim(copy(p, eqPos + 2, MaxInt));
end else
begin
Key := LowerCase(p);
Val := '';
end;
if (Key = 'help') or (Key = 'h') then
begin
exit(ShowHelp);
end else
if (Key = 'dry') then
begin
aOptions.DryRun := True;
end else
if (Key = 's') or (Key = 'silent') then
begin
aOptions.Silent := True;
aOptions.Verbose := False;
end else
if (Key = 'v') or (Key = 'verbose') then
begin
if not aOptions.Silent then
begin
aOptions.Verbose := True;
end;
end else
if (Key = 'path') then
begin
if Val <> '' then
begin
aOptions.Path := ExpandFileName(Val);
end;
end else
if (Key = 'recursive') then
begin
aOptions.Recursive := AsYN(Val, True);
end else
if (Key = 'ext') then
begin
if Val <> '' then
begin
Val := Val.Trim([' ', '"', '''']); // remove outer quotes
aOptions.Exts := NormalizeExtList(Val);
end;
end else
if (Key = 'utf8-bom') then
begin
aOptions.Utf8Bom := AsYN(Val, True);
end else
if (Key = 'bkp-dir') then
begin
if Val <> '' then
begin
aOptions.BackupDir := ExpandFileName(Val);
end;
end else
begin
// Unknown param: ignore silently (or we could warn if verbose)
end;
end;
Result := -1; // continue execution
end;
class function TEncodingFixTool.RunFromCommandLine: integer;
var
lTool: TEncodingFixTool;
lOptions: TOptions;
lParseRes: integer;
lFiles: TArray<string>;
lChangedCount: integer;
lStopwatch: TStopWatch;
lSilent: boolean;
lVerbose: boolean;
lLoopProc: TProc<integer>;
lRoot: string;
begin
gc(lTool, TEncodingFixTool.Create);
lParseRes := lTool.ParseCommandLine(lOptions);
if lParseRes >= 0 then
begin
exit(lParseRes); // help shown or early exit
end;
lSilent := lOptions.Silent;
lVerbose := lOptions.Verbose and (not lSilent);
if not TDirectory.Exists(lOptions.Path) then
begin
if not lSilent then
begin
TSafeConsole.WriteLine('ERROR: path not found: ' + lOptions.Path);
end;
exit(2);
end;
if (lOptions.BackupDir <> '') and (not TDirectory.Exists(lOptions.BackupDir)) then
begin
// create backup root if needed
TDirectory.CreateDirectory(lOptions.BackupDir);
end;
lRoot := IncludeTrailingPathDelimiter(ExpandFileName(lOptions.Path));
// Prepare fast extension lookup
lTool.PrepareExtIndex(lOptions.Exts);
lFiles := lTool.CollectFiles(lOptions);
if (length(lFiles) = 0) and (not lSilent) then
begin
TSafeConsole.WriteLine('No files found.');
end;
lChangedCount := 0;
lStopwatch := TStopWatch.startNew;
lLoopProc :=
procedure(idx: integer)
var
lFile: string;
lChanged: boolean;
lReason: string;
lMsg: string;
lLocalChanged: integer;
lRelFile: string;
begin
lFile := lFiles[idx];
lLocalChanged := 0;
lRelFile := lTool.MakeRelativeTo(lRoot, lFile);
try
if lTool.FixFile(lFile, lOptions, lChanged, lReason) then
begin
if lChanged then
begin
if not lOptions.DryRun then
begin
lLocalChanged := 1;
end;
if not lSilent then
begin
TSafeConsole.WriteLine(Format('%s: %s (%s)',
[IfThen(lOptions.DryRun, 'Would fix', 'Fixed'), lRelFile, lReason]));
end;
end else
begin
if lVerbose and (not lSilent) then
begin
TSafeConsole.WriteLine('OK : ' + lRelFile + ' (' + lReason + ')');
end;
end;
end else
begin
if not lSilent then
begin
TSafeConsole.WriteLine('FAIL : ' + lRelFile + ' (' + lReason + ')');
end;
end;
except
on e: Exception do
begin
if not lSilent then
begin
lMsg := Format('ERROR: %s (%s)', [lRelFile, e.Message]);
TSafeConsole.WriteLine(lMsg);
end;
end;
end;
if lLocalChanged <> 0 then
begin
TInterlocked.Add(lChangedCount, lLocalChanged);
end;
end;
if length(lFiles) > 0 then
TParallel.&For(0, High(lFiles), lLoopProc);