-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSort.pas
More file actions
2469 lines (2204 loc) · 65.2 KB
/
Sort.pas
File metadata and controls
2469 lines (2204 loc) · 65.2 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
{ Sort.pas }
program Sort;
{$mode objfpc}{$H+}
uses
SysUtils, Classes, StrUtils, Process, MD5, fpjson, jsonparser;
type
TMode = (moDummy, moCopy, moMove, moCompare, moFind, moDelete, moDestroy);
TMimeRule = record
HexSignatures: TStringList;
Offsets: TStringList;
Extensions: TStringList;
Description: string;
end;
TOptions = record
Probe: Boolean;
Recursive: Boolean;
ReplaceExisting: Boolean;
ShowHelp: Boolean;
SelfTest: Boolean;
Mode: TMode;
TypeFilter: string;
DirsSpec: string;
SubDirsSpec: string;
RenameSpec: string;
ExtensionSpec: string;
Target: string;
Inputs: TStringList;
ReplaceConfirmed: Boolean;
end;
var
MimeRules: array of TMimeRule;
MimeRulesLoaded: Boolean = False;
MimeCache: TStringList;
HashCache: TStringList;
procedure InitOptions(out Opts: TOptions);
begin
Opts.Probe := False;
Opts.Recursive := False;
Opts.ReplaceExisting := False;
Opts.ShowHelp := False;
Opts.SelfTest := False;
Opts.Mode := moDummy;
Opts.TypeFilter := '';
Opts.DirsSpec := '';
Opts.SubDirsSpec := '';
Opts.RenameSpec := 'original';
Opts.ExtensionSpec := 'original';
Opts.Target := '';
Opts.Inputs := TStringList.Create;
Opts.ReplaceConfirmed := False;
end;
procedure FreeOptions(var Opts: TOptions);
begin
if Assigned(Opts.Inputs) then
Opts.Inputs.Free;
Opts.Inputs := nil;
end;
procedure FreeMimeRule(var Rule: TMimeRule);
begin
Rule.HexSignatures.Free;
Rule.Offsets.Free;
Rule.Extensions.Free;
Rule.Description := '';
end;
procedure FreeMimeRules;
var
I: Integer;
begin
for I := 0 to High(MimeRules) do
FreeMimeRule(MimeRules[I]);
SetLength(MimeRules, 0);
MimeRulesLoaded := False;
end;
procedure InitMimeCache;
begin
if Assigned(MimeCache) then
Exit;
MimeCache := TStringList.Create;
MimeCache.CaseSensitive := False;
MimeCache.NameValueSeparator := '=';
end;
procedure FreeMimeCache;
begin
MimeCache.Free;
MimeCache := nil;
end;
function GetCachedMime(const FilePath: string): string;
var
I: Integer;
begin
Result := '';
if not Assigned(MimeCache) then
Exit;
I := MimeCache.IndexOfName(FilePath);
if I >= 0 then
Result := MimeCache.ValueFromIndex[I];
end;
procedure PutCachedMime(const FilePath, Mime: string);
var
I: Integer;
begin
InitMimeCache;
I := MimeCache.IndexOfName(FilePath);
if I >= 0 then
MimeCache.ValueFromIndex[I] := Mime
else
MimeCache.Add(FilePath + '=' + Mime);
end;
procedure InitHashCache;
begin
if Assigned(HashCache) then
Exit;
HashCache := TStringList.Create;
HashCache.CaseSensitive := False;
HashCache.NameValueSeparator := '=';
end;
procedure FreeHashCache;
begin
HashCache.Free;
HashCache := nil;
end;
function MakeHashCacheKey(const Algo, FilePath: string): string;
begin
Result := LowerCase(Trim(Algo)) + '|' + ExpandFileName(FilePath);
end;
function GetCachedHash(const Algo, FilePath: string): string;
var
Key: string;
I: Integer;
begin
Result := '';
if not Assigned(HashCache) then
Exit;
Key := MakeHashCacheKey(Algo, FilePath);
I := HashCache.IndexOfName(Key);
if I >= 0 then
Result := HashCache.ValueFromIndex[I];
end;
procedure PutCachedHash(const Algo, FilePath, Digest: string);
var
Key: string;
I: Integer;
begin
InitHashCache;
Key := MakeHashCacheKey(Algo, FilePath);
I := HashCache.IndexOfName(Key);
if I >= 0 then
HashCache.ValueFromIndex[I] := Digest
else
HashCache.Add(Key + '=' + Digest);
end;
procedure PrintUsage;
begin
Writeln('Usage:');
Writeln(' sort [options] [files and directories]');
Writeln;
Writeln('Options:');
Writeln(' --Help');
Writeln(' Print this help.');
Writeln;
Writeln(' --SelfTest');
Writeln(' Run built-in MIME/filter/path self-tests and exit.');
Writeln;
Writeln(' --Probe');
Writeln(' Check whether the computed target file is an exact copy.');
Writeln;
Writeln(' --Mode=[dummy|copy|move|compare|find|delete|destroy]');
Writeln(' dummy : dry-run only, print planned actions');
Writeln(' copy : copy source file to computed target path');
Writeln(' move : move source file to computed target path');
Writeln(' compare : report whether source and target are exact matches');
Writeln(' find : print only target paths that exactly match the source');
Writeln(' delete : move matching target files into TARGET/DELETE/');
Writeln(' destroy : permanently delete matching target files');
Writeln;
Writeln(' --Type=[string[,string...]]');
Writeln(' Process only matching MIME, MIME main type, or MIME subtype.');
Writeln(' Multiple values are allowed, separated by commas: image,json,text');
Writeln;
Writeln(' --Recursive');
Writeln(' Recurse into subdirectories.');
Writeln;
Writeln(' --Replace');
Writeln(' Confirm once at startup, then replace existing target files.');
Writeln;
Writeln(' --Dirs=[item[,item...]]');
Writeln(' Items: mime, mime-main, mime-sub, extension, md5sum, sha...sum, random[length]');
Writeln;
Writeln(' --SubDirs=[item[,item...]]');
Writeln(' Items: format, size, format[sep]size, date[:year][:month][:day], random[length]');
Writeln;
Writeln(' --Rename=[original|long|md5sum|sha...sum|time[:hour][:minute][:second][:milliseconds]|random[length]|name]');
Writeln;
Writeln(' --Extension=[original|mime|mime-main|mime-sub|random[length]|ext]');
Writeln;
Writeln(' --Target=[directory]');
Writeln(' If the directory exists, it is used as-is.');
Writeln(' Otherwise it is created under the current working directory.');
end;
function LowerTrim(const S: string): string;
begin
Result := LowerCase(Trim(S));
end;
function IsSwitch(const S: string): Boolean;
begin
Result := (Length(S) >= 2) and (S[1] = '-') and (S[2] = '-');
end;
function SplitOption(const Arg: string; out Key, Value: string): Boolean;
var
P: SizeInt;
begin
Result := False;
Key := '';
Value := '';
if not IsSwitch(Arg) then
Exit;
P := Pos('=', Arg);
if P > 0 then
begin
Key := Copy(Arg, 3, P - 3);
Value := Copy(Arg, P + 1, MaxInt);
end
else
Key := Copy(Arg, 3, MaxInt);
Result := True;
end;
function ParseMode(const S: string; out Mode: TMode): Boolean;
var
V: string;
begin
V := LowerTrim(S);
Result := True;
if V = 'dummy' then Mode := moDummy
else if V = 'copy' then Mode := moCopy
else if V = 'move' then Mode := moMove
else if V = 'compare' then Mode := moCompare
else if V = 'find' then Mode := moFind
else if V = 'delete' then Mode := moDelete
else if V = 'destroy' then Mode := moDestroy
else Result := False;
end;
function ExpandToAbsolute(const Path: string): string;
begin
if Path = '' then
Exit('');
Result := ExpandFileName(Path);
end;
function EnsureDirExists(const DirPath: string): Boolean;
begin
if DirPath = '' then
Exit(False);
if DirectoryExists(DirPath) then
Exit(True);
Result := ForceDirectories(DirPath);
end;
function FileNameNoExt(const Path: string): string;
begin
Result := ChangeFileExt(ExtractFileName(Path), '');
end;
function FileExtNoDot(const Path: string): string;
var
E: string;
begin
E := ExtractFileExt(Path);
if (E <> '') and (E[1] = '.') then
Delete(E, 1, 1);
Result := E;
end;
function JoinPath2(const A, B: string): string;
begin
if A = '' then
Result := B
else if B = '' then
Result := A
else
Result := IncludeTrailingPathDelimiter(A) + B;
end;
function RandomString(ALength: Integer): string;
const
CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
var
I: Integer;
begin
if ALength <= 0 then
ALength := 4;
SetLength(Result, ALength);
for I := 1 to ALength do
Result[I] := CHARS[Random(Length(CHARS)) + 1];
end;
function IsRandomSpec(const S: string; out N: Integer): Boolean;
var
V: string;
P1, P2: Integer;
begin
Result := False;
N := 0;
V := LowerTrim(S);
if not StartsText('random', V) then
Exit;
P1 := Pos('[', V);
P2 := Pos(']', V);
if (P1 > 0) and (P2 > P1) then
N := StrToIntDef(Copy(V, P1 + 1, P2 - P1 - 1), 0);
Result := True;
end;
function IsTimeSpec(const S: string): Boolean;
begin
Result := StartsText('time', LowerTrim(S));
end;
function IsDateSpec(const S: string): Boolean;
begin
Result := StartsText('date', LowerTrim(S));
end;
function IsHashSpec(const S: string): Boolean;
var
V: string;
begin
V := LowerTrim(S);
Result := (V = 'md5sum') or EndsText('sum', V);
end;
function SplitSpecList(const Spec: string): TStringList;
var
Parts: TStringList;
I: Integer;
Item: string;
begin
Result := TStringList.Create;
Result.StrictDelimiter := True;
Result.Delimiter := ',';
if Trim(Spec) = '' then
Exit;
Parts := TStringList.Create;
try
Parts.StrictDelimiter := True;
Parts.Delimiter := ',';
Parts.DelimitedText := Spec;
for I := 0 to Parts.Count - 1 do
begin
Item := Trim(Parts[I]);
if Item <> '' then
Result.Add(Item);
end;
finally
Parts.Free;
end;
end;
function FileSizeInt64(const FilePath: string): Int64;
var
Info: TSearchRec;
begin
Result := -1;
if FindFirst(FilePath, faAnyFile, Info) = 0 then
begin
Result := Info.Size;
FindClose(Info);
end;
end;
function SizeBucket(const FilePath: string): string;
var
S: Int64;
begin
S := FileSizeInt64(FilePath);
if S < 0 then Result := 'UNKNOWN'
else if S < 1024 then Result := 'BYTE'
else if S < 1024 * 1024 then Result := 'KILO'
else if S < 1024 * 1024 * 1024 then Result := 'MEGA'
else if S < Int64(1024) * 1024 * 1024 * 1024 then Result := 'GIGA'
else Result := 'TERA';
end;
function ExactSizeLabel(const FilePath: string): string;
var
S: Int64;
begin
S := FileSizeInt64(FilePath);
if S < 0 then
Exit('UNKNOWN');
if S < 1024 then
Result := IntToStr(S) + 'B'
else if S < 1024 * 1024 then
Result := IntToStr(S div 1024) + 'KIB'
else if S < 1024 * 1024 * 1024 then
Result := IntToStr(S div (1024 * 1024)) + 'MIB'
else if S < Int64(1024) * 1024 * 1024 * 1024 then
Result := IntToStr(S div (1024 * 1024 * 1024)) + 'GIB'
else
Result := IntToStr(S div (Int64(1024) * 1024 * 1024 * 1024)) + 'TIB';
end;
function FileDateTime(const FilePath: string): TDateTime;
var
Info: TSearchRec;
begin
Result := 0;
if FindFirst(FilePath, faAnyFile, Info) = 0 then
begin
Result := FileDateToDateTime(Info.Time);
FindClose(Info);
end;
end;
function BuildDateToken(const Spec, FilePath: string): string;
var
V: string;
DT: TDateTime;
Y, M, D: Word;
begin
V := LowerTrim(Spec);
DT := FileDateTime(FilePath);
DecodeDate(DT, Y, M, D);
if Pos(':', V) = 0 then
Result := Format('%.4d-%.2d-%.2d', [Y, M, D])
else
begin
Result := '';
if Pos(':year', V) > 0 then
Result := Result + Format('%.4d', [Y]);
if Pos(':month', V) > 0 then
begin
if Result <> '' then Result := Result + '-';
Result := Result + Format('%.2d', [M]);
end;
if Pos(':day', V) > 0 then
begin
if Result <> '' then Result := Result + '-';
Result := Result + Format('%.2d', [D]);
end;
if Result = '' then
Result := Format('%.4d-%.2d-%.2d', [Y, M, D]);
end;
Result := UpperCase(Result);
end;
function BuildTimeToken(const Spec: string): string;
var
V: string;
H, N, S, MS: Word;
NowDT: TDateTime;
Added: Boolean;
begin
V := LowerTrim(Spec);
NowDT := Now;
DecodeTime(NowDT, H, N, S, MS);
Added := False;
Result := '';
if Pos(':', V) = 0 then
Exit(Format('%.2d:%.2d:%.2d', [H, N, S]));
if Pos(':hour', V) > 0 then
begin
Result := Result + Format('%.2d', [H]);
Added := True;
end;
if Pos(':minute', V) > 0 then
begin
if Added then Result := Result + ':';
Result := Result + Format('%.2d', [N]);
Added := True;
end;
if Pos(':second', V) > 0 then
begin
if Added then Result := Result + ':';
Result := Result + Format('%.2d', [S]);
Added := True;
end;
if (Pos(':milliseconds', V) > 0) or (Pos(':ms', V) > 0) then
begin
if Added then Result := Result + ':';
Result := Result + Format('%.3d', [MS]);
end;
end;
function ParseHexSignature(const S: string; out Bytes: array of Integer; out Count: Integer): Boolean;
var
Parts: TStringList;
I: Integer;
Token: string;
begin
Result := False;
Count := 0;
Parts := TStringList.Create;
try
Parts.Delimiter := ' ';
Parts.StrictDelimiter := True;
Parts.DelimitedText := Trim(S);
if (Parts.Count = 0) or (Parts.Count > Length(Bytes)) then
Exit;
for I := 0 to Parts.Count - 1 do
begin
Token := UpperCase(Trim(Parts[I]));
if Token = '??' then
Bytes[I] := 256
else
Bytes[I] := StrToInt('$' + Token);
end;
Count := Parts.Count;
Result := True;
finally
Parts.Free;
end;
end;
function ReadFileBytes(const FilePath: string; Offset, Count: Integer; out Buffer: TBytes): Boolean;
var
FS: TFileStream;
ReadCount: Integer;
begin
Result := False;
SetLength(Buffer, 0);
if (Offset < 0) or (Count <= 0) or (not FileExists(FilePath)) then
Exit;
FS := nil;
try
FS := TFileStream.Create(FilePath, fmOpenRead or fmShareDenyWrite);
if Offset >= FS.Size then
Exit;
FS.Position := Offset;
SetLength(Buffer, Count);
ReadCount := FS.Read(Buffer[0], Count);
if ReadCount <> Count then
Exit;
Result := True;
finally
FS.Free;
end;
end;
function FileMatchesHexSignature(const FilePath, HexSignature: string; Offset: Integer): Boolean;
var
Parsed: array[0..255] of Integer;
ParsedCount: Integer;
Buffer: TBytes;
I: Integer;
begin
Result := False;
if not ParseHexSignature(HexSignature, Parsed, ParsedCount) then
Exit;
if not ReadFileBytes(FilePath, Offset, ParsedCount, Buffer) then
Exit;
for I := 0 to ParsedCount - 1 do
begin
if Parsed[I] = 256 then
Continue;
if Buffer[I] <> Byte(Parsed[I]) then
Exit(False);
end;
Result := True;
end;
function MimeFromExtension(const Ext: string): string;
var
E: string;
begin
E := LowerCase(Ext);
if (E = 'txt') or (E = 'text') or (E = 'log') or (E = 'md') or (E = 'markdown') then Result := 'text/plain'
else if E = 'csv' then Result := 'text/csv'
else if E = 'tsv' then Result := 'text/tab-separated-values'
else if (E = 'html') or (E = 'htm') then Result := 'text/html'
else if E = 'css' then Result := 'text/css'
else if (E = 'js') or (E = 'mjs') then Result := 'text/javascript'
else if E = 'xml' then Result := 'application/xml'
else if E = 'json' then Result := 'application/json'
else if (E = 'yaml') or (E = 'yml') then Result := 'application/yaml'
else if E = 'toml' then Result := 'application/toml'
else if (E = 'ini') or (E = 'cfg') or (E = 'conf') then Result := 'text/plain'
else if (E = 'bat') or (E = 'cmd') then Result := 'text/x-script'
else if (E = 'sh') or (E = 'bash') or (E = 'zsh') or (E = 'fish') then Result := 'text/x-script'
else if E = 'py' then Result := 'text/x-python'
else if (E = 'pas') or (E = 'pp') or (E = 'lpr') then Result := 'text/x-pascal'
else if (E = 'c') or (E = 'h') then Result := 'text/x-c'
else if (E = 'cpp') or (E = 'cxx') or (E = 'cc') or (E = 'hpp') then Result := 'text/x-c++'
else if E = 'java' then Result := 'text/x-java'
else if E = 'cs' then Result := 'text/x-csharp'
else if E = 'go' then Result := 'text/x-go'
else if E = 'rs' then Result := 'text/x-rust'
else if E = 'php' then Result := 'text/x-php'
else if E = 'sql' then Result := 'text/x-sql'
else if E = 'tex' then Result := 'text/x-tex'
else if E = 'rtf' then Result := 'application/rtf'
else if E = 'svg' then Result := 'image/svg+xml'
else if (E = 'jpg') or (E = 'jpeg') then Result := 'image/jpeg'
else if E = 'png' then Result := 'image/png'
else if E = 'gif' then Result := 'image/gif'
else if (E = 'bmp') or (E = 'dib') then Result := 'image/bmp'
else if E = 'webp' then Result := 'image/webp'
else if E = 'pdf' then Result := 'application/pdf'
else if E = 'zip' then Result := 'application/zip'
else if E = 'gz' then Result := 'application/gzip'
else if E = 'tar' then Result := 'application/x-tar'
else if E = '7z' then Result := 'application/x-7z-compressed'
else if E = 'rar' then Result := 'application/vnd.rar'
else if E = 'mp3' then Result := 'audio/mpeg'
else if E = 'wav' then Result := 'audio/wav'
else if E = 'flac' then Result := 'audio/flac'
else if E = 'ogg' then Result := 'audio/ogg'
else if E = 'mp4' then Result := 'video/mp4'
else if E = 'mkv' then Result := 'video/x-matroska'
else if E = 'webm' then Result := 'video/webm'
else if E = 'avi' then Result := 'video/x-msvideo'
else if E = 'mov' then Result := 'video/quicktime'
else if E = 'docx' then Result := 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
else if E = 'xlsx' then Result := 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
else if E = 'pptx' then Result := 'application/vnd.openxmlformats-officedocument.presentationml.presentation'
else if E = 'odt' then Result := 'application/vnd.oasis.opendocument.text'
else if E = 'ods' then Result := 'application/vnd.oasis.opendocument.spreadsheet'
else if E = 'odp' then Result := 'application/vnd.oasis.opendocument.presentation'
else if E = 'jar' then Result := 'application/java-archive'
else if E = 'apk' then Result := 'application/vnd.android.package-archive'
else if E = 'epub' then Result := 'application/epub+zip'
else if (E = 'sqlite') or (E = 'sqlitedb') or (E = 'db') then Result := 'application/vnd.sqlite3'
else if (E = 'exe') or (E = 'dll') or (E = 'sys') then Result := 'application/vnd.microsoft.portable-executable'
else if E = 'elf' then Result := 'application/x-elf'
else Result := '';
end;
function MimeFromDescription(const Description: string): string;
var
D: string;
begin
D := LowerCase(Description);
if Pos('jpeg', D) > 0 then Result := 'image/jpeg'
else if Pos('png', D) > 0 then Result := 'image/png'
else if Pos('gif', D) > 0 then Result := 'image/gif'
else if Pos('bitmap', D) > 0 then Result := 'image/bmp'
else if Pos('pdf', D) > 0 then Result := 'application/pdf'
else if Pos('zip', D) > 0 then Result := 'application/zip'
else if Pos('gzip', D) > 0 then Result := 'application/gzip'
else if Pos('7-zip', D) > 0 then Result := 'application/x-7z-compressed'
else if Pos('rar', D) > 0 then Result := 'application/vnd.rar'
else if Pos('sqlite', D) > 0 then Result := 'application/vnd.sqlite3'
else if Pos('matroska', D) > 0 then Result := 'video/x-matroska'
else if Pos('webm', D) > 0 then Result := 'video/webm'
else if Pos('mpeg-4', D) > 0 then Result := 'video/mp4'
else if Pos('script', D) > 0 then Result := 'text/x-script'
else Result := 'application/octet-stream';
end;
function MimeFromRule(const Rule: TMimeRule): string;
var
I: Integer;
begin
for I := 0 to Rule.Extensions.Count - 1 do
begin
Result := MimeFromExtension(Rule.Extensions[I]);
if Result <> '' then
Exit;
end;
Result := MimeFromDescription(Rule.Description);
end;
procedure LoadMimeRules;
var
JsonPath: string;
JsonStream: TFileStream;
Root, Data: TJSONData;
Arr: TJSONArray;
Obj: TJSONObject;
I, J: Integer;
Rule: TMimeRule;
begin
if MimeRulesLoaded then
Exit;
JsonPath := IncludeTrailingPathDelimiter(ExtractFileDir(ParamStr(0))) + 'MIMEs.json';
if not FileExists(JsonPath) then
raise Exception.CreateFmt('MIMEs.json not found at: %s', [JsonPath]);
JsonStream := TFileStream.Create(JsonPath, fmOpenRead or fmShareDenyWrite);
Root := nil;
try
Root := GetJSON(JsonStream);
if Root.JSONType <> jtArray then
raise Exception.Create('MIMEs.json must contain a JSON array.');
Arr := TJSONArray(Root);
SetLength(MimeRules, Arr.Count);
for I := 0 to Arr.Count - 1 do
begin
Obj := Arr.Objects[I];
Rule.HexSignatures := TStringList.Create;
Rule.Offsets := TStringList.Create;
Rule.Extensions := TStringList.Create;
Rule.Description := Obj.Get('description', '');
Data := Obj.FindPath('hex_signature');
if Assigned(Data) and (Data.JSONType = jtArray) then
for J := 0 to TJSONArray(Data).Count - 1 do
Rule.HexSignatures.Add(TJSONArray(Data).Strings[J]);
Data := Obj.FindPath('offset');
if Assigned(Data) and (Data.JSONType = jtArray) then
for J := 0 to TJSONArray(Data).Count - 1 do
Rule.Offsets.Add(TJSONArray(Data).Strings[J]);
Data := Obj.FindPath('extensions');
if Assigned(Data) and (Data.JSONType = jtArray) then
for J := 0 to TJSONArray(Data).Count - 1 do
Rule.Extensions.Add(TJSONArray(Data).Strings[J]);
MimeRules[I] := Rule;
end;
MimeRulesLoaded := True;
finally
Root.Free;
JsonStream.Free;
end;
end;
function IsLikelyTextByte(B: Byte): Boolean;
begin
Result := (B = 9) or (B = 10) or (B = 13) or ((B >= 32) and (B <= 126)) or (B >= 128);
end;
function IsLikelyTextFile(const FilePath: string): Boolean;
var
FS: TFileStream;
Buffer: array[0..4095] of Byte;
ReadCount, I: Integer;
begin
Result := False;
FS := nil;
try
FS := TFileStream.Create(FilePath, fmOpenRead or fmShareDenyWrite);
ReadCount := FS.Read(Buffer, SizeOf(Buffer));
if ReadCount <= 0 then
Exit(False);
for I := 0 to ReadCount - 1 do
begin
if Buffer[I] = 0 then
Exit(False);
if not IsLikelyTextByte(Buffer[I]) then
Exit(False);
end;
Result := True;
finally
FS.Free;
end;
end;
function ReadTextSample(const FilePath: string; MaxBytes: Integer; out Sample: string): Boolean;
var
FS: TFileStream;
Buffer: AnsiString;
ReadCount: Integer;
begin
Result := False;
Sample := '';
if MaxBytes <= 0 then
Exit;
FS := nil;
try
FS := TFileStream.Create(FilePath, fmOpenRead or fmShareDenyWrite);
if FS.Size = 0 then
Exit(False);
if FS.Size < MaxBytes then
MaxBytes := FS.Size;
SetLength(Buffer, MaxBytes);
ReadCount := FS.Read(Buffer[1], MaxBytes);
if ReadCount <= 0 then
Exit(False);
SetLength(Buffer, ReadCount);
Sample := Buffer;
Result := True;
finally
FS.Free;
end;
end;
function TrimLeadingText(const S: string): string;
var
I: Integer;
begin
I := 1;
while (I <= Length(S)) and (S[I] <= ' ') do
Inc(I);
Result := Copy(S, I, MaxInt);
end;
function LooksLikeJson(const S: string): Boolean;
var
T: string;
I: Integer;
begin
T := TrimLeadingText(S);
if T = '' then
Exit(False);
if T[1] = '{' then
begin
I := 2;
while (I <= Length(T)) and (T[I] <= ' ') do
Inc(I);
Result := (I > Length(T)) or (T[I] in ['"', '}']);
Exit;
end;
if T[1] = '[' then
begin
I := 2;
while (I <= Length(T)) and (T[I] <= ' ') do
Inc(I);
Result := (I > Length(T)) or (T[I] in ['"', '{', ']', '-', '0'..'9']);
Exit;
end;
Result := False;
end;
function LooksLikeXml(const S: string): Boolean;
var
T: string;
P: Integer;
begin
T := TrimLeadingText(S);
if AnsiStartsText('<?xml', T) then
Exit(True);
if (Length(T) < 3) or (T[1] <> '<') then
Exit(False);
if not (T[2] in ['A'..'Z', 'a'..'z', '_', ':']) then
Exit(False);
P := Pos('>', T);
Result := P > 2;
end;
function LooksLikeHtml(const S: string): Boolean;
var
T: string;
begin
T := LowerCase(TrimLeadingText(S));
Result :=
AnsiStartsText('<!doctype html', T) or
AnsiStartsText('<html', T) or
AnsiStartsText('<head', T) or
AnsiStartsText('<body', T) or
AnsiStartsText('<meta', T) or
AnsiStartsText('<title', T) or
AnsiStartsText('<script', T) or
AnsiStartsText('<style', T) or
AnsiStartsText('<div', T) or
AnsiStartsText('<span', T) or
AnsiStartsText('<p', T) or
AnsiStartsText('<a ', T);
end;
function LooksLikeYaml(const S: string): Boolean;
var
T: string;
Lines: TStringList;
I: Integer;
LineText: string;
KeyPos: Integer;
KeyName: string;
MatchCount: Integer;
begin
Result := False;
T := TrimLeadingText(S);
if T = '' then
Exit(False);
if AnsiStartsText('---', T) then
Exit(True);
Lines := TStringList.Create;
try
Lines.Text := StringReplace(T, #13, '', [rfReplaceAll]);
MatchCount := 0;
for I := 0 to Lines.Count - 1 do
begin
LineText := Trim(Lines[I]);
if LineText = '' then
Continue;
if LineText[1] = '#' then
Continue;
if (Length(LineText) >= 2) and (Copy(LineText, 1, 2) = '- ') then
begin
Inc(MatchCount);
Continue;
end;
KeyPos := Pos(':', LineText);
if KeyPos > 1 then
begin
KeyName := Trim(Copy(LineText, 1, KeyPos - 1));
if (KeyName <> '') and
(Pos('{', LineText) = 0) and (Pos('}', LineText) = 0) and
(Pos('[', LineText) = 0) and (Pos(']', LineText) = 0) then
begin
Inc(MatchCount);
Continue;
end;
end;
if MatchCount = 0 then
Exit(False);
end;
Result := MatchCount >= 2;
finally
Lines.Free;
end;
end;
function LooksLikeShellScript(const S: string): Boolean;
var
T, L: string;
Lines: TStringList;
I: Integer;
MatchCount: Integer;
begin
Result := False;
T := TrimLeadingText(S);
if T = '' then
Exit(False);
L := LowerCase(T);
if AnsiStartsText('#!/bin/sh', L) or
AnsiStartsText('#!/usr/bin/sh', L) or
AnsiStartsText('#!/bin/bash', L) or
AnsiStartsText('#!/usr/bin/bash', L) or
AnsiStartsText('#!/usr/bin/env bash', L) or
AnsiStartsText('#!/bin/zsh', L) or
AnsiStartsText('#!/usr/bin/zsh', L) or
AnsiStartsText('#!/usr/bin/env zsh', L) or
AnsiStartsText('#!/bin/dash', L) or
AnsiStartsText('#!/usr/bin/env sh', L) then
Exit(True);
Lines := TStringList.Create;
try
Lines.Text := StringReplace(T, #13, '', [rfReplaceAll]);
MatchCount := 0;
for I := 0 to Lines.Count - 1 do
begin
L := Trim(LowerCase(Lines[I]));
if L = '' then
Continue;
if L[1] = '#' then
Continue;
if AnsiStartsText('if [', L) or
AnsiStartsText('if test ', L) or
AnsiStartsText('for ', L) or
AnsiStartsText('while ', L) or
AnsiStartsText('case ', L) or
AnsiStartsText('function ', L) or
AnsiStartsText('export ', L) then
Inc(MatchCount)
else if (L = 'then') or (L = 'do') or (L = 'done') or (L = 'fi') or (L = 'esac') then
Inc(MatchCount);