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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499
|
{
**********************************************************************
This file is part of LazUtils.
All functions are thread safe unless explicitely stated
See the file COPYING.modifiedLGPL.txt, included in this distribution,
for details about the license.
**********************************************************************
}
unit LazFileUtils;
{$mode objfpc}{$H+}
{$i lazutils_defines.inc}
interface
uses
Classes, SysUtils, SysConst, LazUTF8, LazUtilsStrConsts;
{$IF defined(Windows) or defined(darwin) or defined(HASAMIGA)}
{$define CaseInsensitiveFilenames}
{$IFDEF Windows}
{$define HasUNCPaths}
{$ENDIF}
{$ENDIF}
{$IF defined(CaseInsensitiveFilenames)}
{$define NotLiteralFilenames} // e.g. HFS+ normalizes file names
{$ENDIF}
function CompareFilenames(const Filename1, Filename2: string): integer; overload;
function CompareFilenamesIgnoreCase(const Filename1, Filename2: string): integer;
function CompareFileExt(const Filename, Ext: string;
CaseSensitive: boolean = False): integer;
function CompareFilenameStarts(const Filename1, Filename2: string): integer;
function CompareFilenames(Filename1: PChar; Len1: integer;
Filename2: PChar; Len2: integer): integer; overload;
function CompareFilenamesP(Filename1, Filename2: PChar;
IgnoreCase: boolean = false // false = use default
): integer;
function DirPathExists(DirectoryName: string): boolean;
function DirectoryIsWritable(const DirectoryName: string): boolean;
function ExtractFileNameOnly(const AFilename: string): string;
function ExtractFileNameWithoutExt(const AFilename: string): string;
function FilenameIsAbsolute(const TheFilename: string):boolean;
function FilenameIsWinAbsolute(const TheFilename: string):boolean;
function FilenameIsUnixAbsolute(const TheFilename: string):boolean;
function ForceDirectory(DirectoryName: string): boolean;
procedure CheckIfFileIsExecutable(const AFilename: string);
procedure CheckIfFileIsSymlink(const AFilename: string);
function FileIsExecutable(const AFilename: string): boolean;
function FileIsSymlink(const AFilename: string): boolean;
function FileIsHardLink(const AFilename: string): boolean;
function FileIsReadable(const AFilename: string): boolean;
function FileIsWritable(const AFilename: string): boolean;
function FileIsText(const AFilename: string): boolean;
function FileIsText(const AFilename: string; out FileReadable: boolean): boolean;
function FilenameIsTrimmed(const TheFilename: string): boolean;
function FilenameIsTrimmed(StartPos: PChar; NameLen: integer): boolean;
function TrimFilename(const AFilename: string): string;
function ResolveDots(const AFilename: string): string;
function CleanAndExpandFilename(const Filename: string): string; // empty string returns current directory
function CleanAndExpandDirectory(const Filename: string): string; // empty string returns current directory
function TrimAndExpandFilename(const Filename: string; const BaseDir: string = ''): string; // empty string returns empty string
function TrimAndExpandDirectory(const Filename: string; const BaseDir: string = ''): string; // empty string returns empty string
function CreateAbsolutePath(const Filename, BaseDirectory: string): string;
function TryCreateRelativePath(const Dest, Source: String; UsePointDirectory: boolean;
AlwaysRequireSharedBaseFolder: Boolean; out RelPath: String): Boolean;
function CreateRelativePath(const Filename, BaseDirectory: string;
UsePointDirectory: boolean = false; AlwaysRequireSharedBaseFolder: Boolean = True): string;
function FileIsInPath(const Filename, Path: string): boolean;
type
TPathDelimSwitch = (
pdsNone, // no change
pdsSystem, // switch to current PathDelim
pdsUnix, // switch to slash /
pdsWindows // switch to backslash \
);
const
PathDelimSwitchToDelim: array[TPathDelimSwitch] of char = (
PathDelim, // pdsNone
PathDelim, // pdsSystem
'/', // pdsUnix
'\' // pdsWindows
);
// Path delimiters
procedure ForcePathDelims(Var FileName: string);
function GetForcedPathDelims(const FileName: string): string;
function AppendPathDelim(const Path: string): string;
function ChompPathDelim(const Path: string): string;
function SwitchPathDelims(const Filename: string; Switch: TPathDelimSwitch): string;
function SwitchPathDelims(const Filename: string; Switch: boolean): string;
function CheckPathDelim(const OldPathDelim: string; out Changed: boolean): TPathDelimSwitch;
function IsCurrentPathDelim(Switch: TPathDelimSwitch): boolean;
// search paths
function CreateAbsoluteSearchPath(const SearchPath, BaseDirectory: string): string;
function CreateRelativeSearchPath(const SearchPath, BaseDirectory: string): string;
function MinimizeSearchPath(const SearchPath: string): string;
function FindPathInSearchPath(APath: PChar; APathLen: integer;
SearchPath: PChar; SearchPathLen: integer): PChar; overload;
function FindPathInSearchPath(const APath, SearchPath: string): integer; overload;
// file operations
function FileExistsUTF8(const Filename: string): boolean;
function FileAgeUTF8(const FileName: string): Longint;
function DirectoryExistsUTF8(const Directory: string): Boolean;
function ExpandFileNameUTF8(const FileName: string; {const} BaseDir: string = ''): string;
function FindFirstUTF8(const Path: string; Attr: Longint; out Rslt: TSearchRec): Longint;
function FindNextUTF8(var Rslt: TSearchRec): Longint;
procedure FindCloseUTF8(var F: TSearchrec); inline;
function FileSetDateUTF8(const FileName: String; Age: Longint): Longint;
function FileGetAttrUTF8(const FileName: String): Longint;
function FileSetAttrUTF8(const Filename: String; Attr: longint): Longint;
function DeleteFileUTF8(const FileName: String): Boolean;
function RenameFileUTF8(const OldName, NewName: String): Boolean;
function FileSearchUTF8(const Name, DirList : String; ImplicitCurrentDir : Boolean = True): String;
function FileIsReadOnlyUTF8(const FileName: String): Boolean;
function GetCurrentDirUTF8: String;
function SetCurrentDirUTF8(const NewDir: String): Boolean;
function CreateDirUTF8(const NewDir: String): Boolean;
function RemoveDirUTF8(const Dir: String): Boolean;
function ForceDirectoriesUTF8(const Dir: string): Boolean;
function FileOpenUTF8(Const FileName : string; Mode : Integer) : THandle;
function FileCreateUTF8(Const FileName : string) : THandle; overload;
function FileCreateUTF8(Const FileName : string; Rights: Cardinal) : THandle; overload;
Function FileCreateUtf8(Const FileName : String; ShareMode : Integer; Rights : Cardinal) : THandle; overload;
function FileSizeUtf8(const Filename: string): int64;
function GetFileDescription(const AFilename: string): string;
function ReadAllLinks(const Filename: string;
{%H-}ExceptionOnError: boolean): string; // if a link is broken returns ''
function TryReadAllLinks(const Filename: string): string; // if a link is broken returns Filename
function GetShellLinkTarget(const FileName: string): string;
// for debugging
function DbgSFileAttr(Attr: LongInt): String;
type
TPhysicalFilenameOnError = (pfeException,pfeEmpty,pfeOriginal);
function GetPhysicalFilename(const Filename: string;
OnError: TPhysicalFilenameOnError): string;
{$IFDEF Unix}
function GetUnixPhysicalFilename(const Filename: string;
ExceptionOnError: boolean): string; // if a link is broken returns ''
{$ENDIF}
function GetAppConfigDirUTF8(Global: Boolean; Create: boolean = false): string;
function GetAppConfigFileUTF8(Global: Boolean; SubDir: boolean = false;
CreateDir: boolean = false): string;
function GetTempFileNameUTF8(const Dir, Prefix: String): String;
// UNC paths
function IsUNCPath(const {%H-}Path: String): Boolean;
function ExtractUNCVolume(const {%H-}Path: String): String;
function ExtractFileRoot(FileName: String): String;
// darwin paths
{$IFDEF darwin}
function GetDarwinSystemFilename(Filename: string): string;
function GetDarwinNormalizedFilename(Filename: string; nForm:Integer=2): string;
{$ENDIF}
// windows paths
{$IFDEF windows}
function SHGetFolderPathUTF8(ID : Integer) : String;
{$ENDIF}
// Command line
procedure SplitCmdLineParams(const Params: string; ParamList: TStrings;
ReadBackslash: boolean = false);
function StrToCmdLineParam(const Param: string): string;
function MergeCmdLineParams(ParamList: TStrings): string;
// Command line functions moved from IDEProcs.
// ToDo: Study if they are needed or if the above functions could be used instead.
procedure SplitCmdLine(const CmdLine: string;
out ProgramFilename, Params: string);
function PrepareCmdLineOption(const Option: string): string;
//function AddCmdLineParameter(const CmdLine, AddParameter: string): string;
type
TInvalidateFileStateCacheEvent = procedure(const Filename: string);
var
OnInvalidateFileStateCache: TInvalidateFileStateCacheEvent = nil;
procedure InvalidateFileStateCache(const Filename: string = ''); inline;
implementation
// to get more detailed error messages consider the os
uses
{$IFDEF Windows}
Windows {$IFnDEF WinCE}, ShlObj, ActiveX, WinDirs{$ENDIF};
{$ELSE}
{$IFDEF HASAMIGA}
exec, amigados;
{$ELSE}
{$IFDEF darwin}
MacOSAll,
{$ENDIF}
Unix, BaseUnix;
{$ENDIF}
{$ENDIF}
{$I lazfileutils.inc}
{$IFDEF windows}
{$I winlazfileutils.inc}
{$ELSE}
{$IFDEF HASAMIGA}
{$I amigalazfileutils.inc}
{$ELSE}
{$I unixlazfileutils.inc}
{$ENDIF}
{$ENDIF}
function CompareFilenames(const Filename1, Filename2: string): integer;
{$IFDEF darwin}
var
F1: CFStringRef;
F2: CFStringRef;
{$ENDIF}
begin
{$IFDEF darwin}
if Filename1=Filename2 then exit(0);
if (Filename1='') or (Filename2='') then
exit(length(Filename2)-length(Filename1));
F1:=CFStringCreateWithCString(nil,Pointer(Filename1),kCFStringEncodingUTF8);
F2:=CFStringCreateWithCString(nil,Pointer(Filename2),kCFStringEncodingUTF8);
Result:=CFStringCompare(F1,F2,kCFCompareNonliteral
{$IFDEF CaseInsensitiveFilenames}+kCFCompareCaseInsensitive{$ENDIF});
CFRelease(F1);
CFRelease(F2);
{$ELSE}
{$IFDEF CaseInsensitiveFilenames}
Result:=UTF8CompareText(Filename1, Filename2);
{$ELSE}
Result:=CompareStr(Filename1, Filename2);
{$ENDIF}
{$ENDIF}
end;
function CompareFilenamesIgnoreCase(const Filename1, Filename2: string): integer;
{$IFDEF darwin}
var
F1: CFStringRef;
F2: CFStringRef;
{$ENDIF}
begin
{$IFDEF darwin}
if Filename1=Filename2 then exit(0);
F1:=CFStringCreateWithCString(nil,Pointer(Filename1),kCFStringEncodingUTF8);
F2:=CFStringCreateWithCString(nil,Pointer(Filename2),kCFStringEncodingUTF8);
Result:=CFStringCompare(F1,F2,kCFCompareNonliteral+kCFCompareCaseInsensitive);
CFRelease(F1);
CFRelease(F2);
{$ELSE}
Result:=UTF8CompareText(Filename1, Filename2);
{$ENDIF}
end;
function CompareFileExt(const Filename, Ext: string; CaseSensitive: boolean): integer;
// Ext can contain a point or not
var
n, e : AnsiString;
FileLen, FilePos, ExtLen, ExtPos: integer;
begin
FileLen := length(Filename);
ExtLen := length(Ext);
FilePos := FileLen;
while (FilePos>=1) and (Filename[FilePos]<>'.') do dec(FilePos);
if FilePos < 1 then begin
// no extension in filename
Result:=1;
exit;
end;
// skip point
inc(FilePos);
ExtPos := 1;
if (ExtPos <= ExtLen) and (Ext[1] = '.') then inc(ExtPos);
// compare extensions
n := Copy(Filename, FilePos, length(FileName));
e := Copy(Ext, ExtPos, length(Ext));
if CaseSensitive then
Result := CompareStr(n, e)
else
Result := UTF8CompareText(n, e);
if Result < 0
then Result := -1
else
if Result > 0 then Result := 1;
end;
function ExtractFileNameOnly(const AFilename: string): string;
var
StartPos: Integer;
ExtPos: Integer;
begin
StartPos:=length(AFilename)+1;
while (StartPos>1)
and not (AFilename[StartPos-1] in AllowDirectorySeparators)
{$IF defined(Windows) or defined(HASAMIGA)}and (AFilename[StartPos-1]<>':'){$ENDIF}
do
dec(StartPos);
ExtPos:=length(AFilename);
while (ExtPos>=StartPos) and (AFilename[ExtPos]<>'.') do
dec(ExtPos);
if (ExtPos<StartPos) then ExtPos:=length(AFilename)+1;
Result:=copy(AFilename,StartPos,ExtPos-StartPos);
end;
function ExtractFileNameWithoutExt(const AFilename: string): string;
var
p: Integer;
begin
Result:=AFilename;
p:=length(Result);
while (p>0) do begin
case Result[p] of
PathDelim: exit;
{$ifdef windows}
'/': if ('/' in AllowDirectorySeparators) then exit;
{$endif}
'.': exit(copy(Result,1, p-1));
end;
dec(p);
end;
end;
{$IFDEF darwin}
function GetDarwinSystemFilename(Filename: string): string;
var
s: CFStringRef;
l: CFIndex;
begin
if Filename='' then exit('');
s:=CFStringCreateWithCString(nil,Pointer(Filename),kCFStringEncodingUTF8);
l:=CFStringGetMaximumSizeOfFileSystemRepresentation(s);
SetLength(Result,l);
if Result<>'' then begin
CFStringGetFileSystemRepresentation(s,@Result[1],length(Result));
SetLength(Result,StrLen(PChar(Result)));
end;
CFRelease(s);
end;
// borrowed from CarbonProcs
function CFStringToStr(AString: CFStringRef; Encoding: CFStringEncoding): String;
var
Str: Pointer;
StrSize: CFIndex;
StrRange: CFRange;
begin
if AString = nil then
begin
Result := '';
Exit;
end;
// Try the quick way first
Str := CFStringGetCStringPtr(AString, Encoding);
if Str <> nil then
Result := PChar(Str)
else
begin
// if that doesn't work this will
StrRange.location := 0;
StrRange.length := CFStringGetLength(AString);
CFStringGetBytes(AString, StrRange, Encoding,
Ord('?'), False, nil, 0, StrSize{%H-});
SetLength(Result, StrSize);
if StrSize > 0 then
CFStringGetBytes(AString, StrRange, Encoding,
Ord('?'), False, @Result[1], StrSize, StrSize);
end;
end;
//NForm can be one of
//kCFStringNormalizationFormD = 0; // Canonical Decomposition
//kCFStringNormalizationFormKD = 1; // Compatibility Decomposition
//kCFStringNormalizationFormC = 2; // Canonical Decomposition followed by Canonical Composition
//kCFStringNormalizationFormKC = 3; // Compatibility Decomposition followed by Canonical Composition
function GetDarwinNormalizedFilename(Filename: string; nForm:Integer=2): string;
var
theString: CFStringRef;
Mutable: CFMutableStringRef;
begin
theString:=CFStringCreateWithCString(nil, Pointer(FileName), kCFStringEncodingUTF8);
Mutable := CFStringCreateMutableCopy(nil, 0, theString);
if (NForm<0) or (NForm>3) then NForm := kCFStringNormalizationFormC;
CFStringNormalize(Mutable, NForm);
Result := CFStringToStr(Mutable, kCFStringEncodingUTF8);
CFRelease(Mutable);
CFRelease(theString);
end;
{$ENDIF}
function CompareFilenameStarts(const Filename1, Filename2: string): integer;
var
len1: Integer;
len2: Integer;
begin
len1:=length(Filename1);
len2:=length(Filename2);
if len1=len2 then begin
Result:=CompareFilenames(Filename1,Filename2);
exit;
end else if len1>len2 then
Result:=CompareFilenames(copy(Filename1,1,len2),Filename2)
else
Result:=CompareFilenames(Filename1,copy(Filename2,1,len1));
if Result<>0 then exit;
if len1<len2 then
Result:=-1
else
Result:=1;
end;
function CompareFilenames(Filename1: PChar; Len1: integer; Filename2: PChar;
Len2: integer): integer;
var
{$IFDEF NotLiteralFilenames}
File1: string;
File2: string;
{$ELSE}
i: Integer;
{$ENDIF}
begin
if (Len1=0) or (Len2=0) then begin
Result:=Len1-Len2;
exit;
end;
{$IFDEF NotLiteralFilenames}
SetLength(File1,Len1);
System.Move(Filename1^,File1[1],Len1);
SetLength(File2,Len2);
System.Move(Filename2^,File2[1],Len2);
Result:=CompareFilenames(File1,File2);
{$ELSE}
Result:=0;
i:=0;
while (Result=0) and ((i<Len1) and (i<Len2)) do begin
Result:=Ord(Filename1[i])
-Ord(Filename2[i]);
Inc(i);
end;
if Result=0 Then
Result:=Len1-Len2;
{$ENDIF}
end;
function CompareFilenamesP(Filename1, Filename2: PChar;
IgnoreCase: boolean = false): integer;
var
{$IFDEF darwin}
F1: CFStringRef;
F2: CFStringRef;
Flags: CFStringCompareFlags;
{$ELSE}
File1, File2: string;
Len1: SizeInt;
Len2: SizeInt;
{$ENDIF}
begin
if (Filename1=nil) or (Filename1^=#0) then begin
if (Filename2=nil) or (Filename2^=#0) then begin
// both empty
exit(0);
end else begin
// filename1 empty, filename2 not empty
exit(-1);
end;
end else if (Filename2=nil) or (Filename2^=#0) then begin
// filename1 not empty, filename2 empty
exit(1);
end;
{$IFDEF CaseInsensitiveFilenames}
// this platform is by default case insensitive
IgnoreCase:=true;
{$ENDIF}
{$IFDEF darwin}
F1:=CFStringCreateWithCString(nil,Pointer(Filename1),kCFStringEncodingUTF8);
F2:=CFStringCreateWithCString(nil,Pointer(Filename2),kCFStringEncodingUTF8);
Flags:=kCFCompareNonliteral;
if IgnoreCase then Flags+=kCFCompareCaseInsensitive;
Result:=CFStringCompare(F1,F2,Flags);
CFRelease(F1);
CFRelease(F2);
{$ELSE}
if IgnoreCase then begin
// compare case insensitive
Len1:=StrLen(Filename1);
SetLength(File1,Len1);
System.Move(Filename1^,File1[1],Len1);
Len2:=StrLen(Filename2);
SetLength(File2,Len2);
System.Move(Filename2^,File2[1],Len2);
Result:=UTF8CompareText(File1,File2);
end else begin
// compare literally
while (Filename1^=Filename2^) and (Filename1^<>#0) do begin
inc(Filename1);
Inc(Filename2);
end;
Result:=ord(Filename1^)-ord(Filename2^);
end;
{$ENDIF}
end;
function DirPathExists(DirectoryName: string): boolean;
begin
Result:=DirectoryExistsUTF8(ChompPathDelim(DirectoryName));
end;
function DirectoryIsWritable(const DirectoryName: string): boolean;
var
TempFilename: String;
s: String;
fHandle: THANDLE;
begin
Result:=false;
if not DirPathExists(DirectoryName) then exit;
TempFilename:=SysUtils.GetTempFilename(AppendPathDelim(DirectoryName),'tstperm');
fHandle := FileCreateUtf8(TempFileName, fmCreate, 438);
if (THandle(fHandle) <> feInvalidHandle) then
begin
s:='WriteTest';
if FileWrite(fHandle,S[1],Length(S)) > 0 then Result := True;
FileClose(fHandle);
if not DeleteFileUTF8(TempFilename) then
InvalidateFileStateCache(TempFilename);
end;
end;
function ForceDirectory(DirectoryName: string): boolean;
var i: integer;
Dir: string;
begin
DirectoryName:=AppendPathDelim(DirectoryName);
i:=1;
while i<=length(DirectoryName) do begin
if DirectoryName[i] in AllowDirectorySeparators then begin
Dir:=copy(DirectoryName,1,i-1);
if not DirPathExists(Dir) then begin
Result:=CreateDirUTF8(Dir);
if not Result then exit;
end;
end;
inc(i);
end;
Result:=true;
end;
function FileIsText(const AFilename: string): boolean;
var
FileReadable: Boolean;
begin
Result:=FileIsText(AFilename,FileReadable);
if FileReadable then ;
end;
function FileIsText(const AFilename: string; out FileReadable: boolean): boolean;
var
Buf: string;
Len: integer;
NewLine: boolean;
p: PChar;
ZeroAllowed: Boolean;
fHandle: THandle;
begin
Result:=false;
FileReadable:=true;
fHandle := FileOpenUtf8(AFileName, fmOpenRead or fmShareDenyNone);
if (THandle(fHandle) <> feInvalidHandle) then
begin
try
Len:=1024;
SetLength(Buf,Len+1);
Len := FileRead(fHandle,Buf[1],Len);
if Len>0 then begin
Buf[Len+1]:=#0;
p:=PChar(Buf);
ZeroAllowed:=false;
if (p[0]=#$EF) and (p[1]=#$BB) and (p[2]=#$BF) then begin
// UTF-8 BOM (Byte Order Mark)
inc(p,3);
end else if (p[0]=#$FF) and (p[1]=#$FE) then begin
// ucs-2le BOM FF FE
inc(p,2);
ZeroAllowed:=true;
end else if (p[0]=#$FE) and (p[1]=#$FF) then begin
// ucs-2be BOM FE FF
inc(p,2);
ZeroAllowed:=true;
end;
NewLine:=false;
while true do begin
case p^ of
#0:
if p-PChar(Buf)>=Len then
break
else if not ZeroAllowed then
exit;
// #10,#13: new line
// #12: form feed
// #26: end of file
#1..#8,#11,#14..#25,#27..#31: exit;
#10,#13: NewLine:=true;
end;
inc(p);
end;
if NewLine or (Len<1024) then
Result:=true;
end else
Result:=true;
finally
FileClose(fHandle);
end
end
else
FileReadable := False;
end;
function FilenameIsTrimmed(const TheFilename: string): boolean;
begin
Result:=FilenameIsTrimmed(PChar(Pointer(TheFilename)),// pointer type cast avoids #0 check
length(TheFilename));
end;
function FilenameIsTrimmed(StartPos: PChar; NameLen: integer): boolean;
var
i: Integer;
c: Char;
begin
Result:=false;
if NameLen<=0 then begin
Result:=true;
exit;
end;
// check heading spaces
if StartPos[0]=' ' then exit;
// check trailing spaces
if StartPos[NameLen-1]=' ' then exit;
// check ./ at start
if (StartPos[0]='.') and (StartPos[1] in AllowDirectorySeparators) then exit;
i:=0;
while i<NameLen do begin
c:=StartPos[i];
if not (c in AllowDirectorySeparators) then
inc(i)
else begin
if c<>PathDelim then exit;
inc(i);
if i=NameLen then break;
// check for double path delimiter
if (StartPos[i] in AllowDirectorySeparators) then exit;
if (StartPos[i]='.') and (i>0) then begin
inc(i);
// check /./ or /. at end
if (StartPos[i] in AllowDirectorySeparators) or (i=NameLen) then exit;
if StartPos[i]='.' then begin
inc(i);
// check /../ or /.. at end
if (StartPos[i] in AllowDirectorySeparators) or (i=NameLen) then exit;
end;
end;
end;
end;
Result:=true;
end;
function TrimFilename(const AFilename: string): string;
//Trim leading and trailing spaces
//then call ResolveDots to trim double path delims and expand special dirs like .. and .
var
Len, Start: Integer;
begin
Result := AFileName;
Len := Length(AFileName);
if (Len = 0) or FilenameIsTrimmed(Result) then exit;
if AFilename[1] = #32 then
begin
Start := 1;
while (Start <= Len) and (AFilename[Start] = #32) do Inc(Start);
System.Delete(Result,1,Start-1);
Len := Length(Result);
end;
while (Len > 0) and (Result[Len] = #32) do Dec(Len);
SetLength(Result, Len);
Result := ResolveDots(Result);
end;
{------------------------------------------------------------------------------
function CleanAndExpandFilename(const Filename: string): string;
------------------------------------------------------------------------------}
function CleanAndExpandFilename(const Filename: string): string;
begin
Result:=ExpandFileNameUTF8(TrimFileName(Filename));
end;
{------------------------------------------------------------------------------
function CleanAndExpandDirectory(const Filename: string): string;
------------------------------------------------------------------------------}
function CleanAndExpandDirectory(const Filename: string): string;
begin
Result:=AppendPathDelim(CleanAndExpandFilename(Filename));
end;
function TrimAndExpandFilename(const Filename: string; const BaseDir: string): string;
begin
Result:=ChompPathDelim(TrimFilename(Filename));
if Result='' then exit;
Result:=TrimFilename(ExpandFileNameUTF8(Result,BaseDir));
end;
function TrimAndExpandDirectory(const Filename: string; const BaseDir: string): string;
begin
Result:=TrimFilename(Filename);
if Result='' then exit;
Result:=TrimFilename(AppendPathDelim(ExpandFileNameUTF8(Result,BaseDir)));
end;
function FileIsInPath(const Filename, Path: string): boolean;
var
ExpFile: String;
ExpPath: String;
l: integer;
begin
if Path='' then begin
Result:=false;
exit;
end;
ExpFile:=ResolveDots(Filename);
ExpPath:=AppendPathDelim(ResolveDots(Path));
l:=length(ExpPath);
Result:=(l>0) and (length(ExpFile)>l) and (ExpFile[l]=PathDelim)
and (CompareFilenames(ExpPath,LeftStr(ExpFile,l))=0);
end;
// Path delimiters
procedure ForcePathDelims(var FileName: string);
var
i: Integer;
begin
for i:=1 to length(FileName) do
{$IFDEF Windows}
if Filename[i]='/' then
Filename[i]:='\';
{$ELSE}
if Filename[i]='\' then
Filename[i]:='/';
{$ENDIF}
end;
function GetForcedPathDelims(const FileName: string): string;
begin
Result:=FileName;
ForcePathDelims(Result);
end;
function AppendPathDelim(const Path: string): string;
begin
if (Path<>'') and not (Path[length(Path)] in AllowDirectorySeparators) then
Result:=Path+PathDelim
else
Result:=Path;
end;
function ChompPathDelim(const Path: string): string;
var
Len, MinLen: Integer;
begin
Result:=Path;
if Path = '' then
exit;
Len:=length(Result);
if (Result[1] in AllowDirectorySeparators) then begin
MinLen := 1;
{$IFDEF HasUNCPaths}
if (Len >= 2) and (Result[2] in AllowDirectorySeparators) then
MinLen := 2; // keep UNC '\\', chomp 'a\' to 'a'
{$ENDIF}
end
else begin
MinLen := 0;
{$IFdef MSWindows}
if (Len >= 3) and (Result[1] in ['a'..'z', 'A'..'Z']) and
(Result[2] = ':') and (Result[3] in AllowDirectorySeparators)
then
MinLen := 3;
{$ENDIF}
end;
while (Len > MinLen) and (Result[Len] in AllowDirectorySeparators) do dec(Len);
if Len<length(Result) then
SetLength(Result,Len);
end;
function SwitchPathDelims(const Filename: string; Switch: TPathDelimSwitch): string;
var
i: Integer;
p: Char;
begin
Result:=Filename;
case Switch of
pdsSystem: p:=PathDelim;
pdsUnix: p:='/';
pdsWindows: p:='\';
else exit;
end;
for i:=1 to length(Result) do
if Result[i] in ['/','\'] then
Result[i]:=p;
end;
function SwitchPathDelims(const Filename: string; Switch: boolean): string;
begin
if Switch then
Result:=SwitchPathDelims(Filename,pdsSystem)
else
Result:=Filename;
end;
function CheckPathDelim(const OldPathDelim: string; out Changed: boolean): TPathDelimSwitch;
begin
Changed:=OldPathDelim<>PathDelim;
if Changed then begin
if OldPathDelim='/' then
Result:=pdsUnix
else if OldPathDelim='\' then
Result:=pdsWindows
else
Result:=pdsSystem;
end else begin
Result:=pdsNone;
end;
end;
function IsCurrentPathDelim(Switch: TPathDelimSwitch): boolean;
begin
Result:=(Switch in [pdsNone,pdsSystem])
or ((Switch=pdsUnix) and (PathDelim='/'))
or ((Switch=pdsWindows) and (PathDelim='\'));
end;
function CreateAbsoluteSearchPath(const SearchPath, BaseDirectory: string): string;
var
PathLen: Integer;
EndPos: Integer;
StartPos: Integer;
CurDir: String;
NewCurDir: String;
DiffLen: Integer;
BaseDir: String;
begin
Result:=SearchPath;
if (SearchPath='') or (BaseDirectory='') then exit;
BaseDir:=AppendPathDelim(BaseDirectory);
PathLen:=length(Result);
EndPos:=1;
while EndPos<=PathLen do begin
StartPos:=EndPos;
while (Result[StartPos]=';') do begin
inc(StartPos);
if StartPos>PathLen then exit;
end;
EndPos:=StartPos;
while (EndPos<=PathLen) and (Result[EndPos]<>';') do inc(EndPos);
CurDir:=copy(Result,StartPos,EndPos-StartPos);
if not FilenameIsAbsolute(CurDir) then begin
NewCurDir:=BaseDir+CurDir;
if NewCurDir<>CurDir then begin
DiffLen:=length(NewCurDir)-length(CurDir);
Result:=copy(Result,1,StartPos-1)+NewCurDir
+copy(Result,EndPos,PathLen-EndPos+1);
inc(EndPos,DiffLen);
inc(PathLen,DiffLen);
end;
end;
StartPos:=EndPos;
end;
end;
function CreateRelativeSearchPath(const SearchPath, BaseDirectory: string
): string;
var
PathLen: Integer;
EndPos: Integer;
StartPos: Integer;
CurDir: String;
NewCurDir: String;
DiffLen: Integer;
begin
Result:=SearchPath;
if (SearchPath='') or (BaseDirectory='') then exit;
PathLen:=length(Result);
EndPos:=1;
while EndPos<=PathLen do begin
StartPos:=EndPos;
while (Result[StartPos]=';') do begin
inc(StartPos);
if StartPos>PathLen then exit;
end;
EndPos:=StartPos;
while (EndPos<=PathLen) and (Result[EndPos]<>';') do inc(EndPos);
CurDir:=copy(Result,StartPos,EndPos-StartPos);
if FilenameIsAbsolute(CurDir) then begin
NewCurDir:=CreateRelativePath(CurDir,BaseDirectory);
if (NewCurDir<>CurDir) and (NewCurDir='') then
NewCurDir:='.';
if NewCurDir<>CurDir then begin
DiffLen:=length(NewCurDir)-length(CurDir);
Result:=copy(Result,1,StartPos-1)+NewCurDir
+copy(Result,EndPos,PathLen-EndPos+1);
inc(EndPos,DiffLen);
inc(PathLen,DiffLen);
end;
end;
StartPos:=EndPos;
end;
end;
function MinimizeSearchPath(const SearchPath: string): string;
// trim the paths, remove doubles and empty paths
var
StartPos: Integer;
EndPos: LongInt;
NewPath: String;
begin
Result:=SearchPath;
StartPos:=1;
while StartPos<=length(Result) do begin
EndPos:=StartPos;
while (EndPos<=length(Result)) and (Result[EndPos]<>';') do
inc(EndPos);
if StartPos<EndPos then begin
// trim path and chomp PathDelim
if (Result[EndPos-1] in AllowDirectorySeparators)
or (not FilenameIsTrimmed(@Result[StartPos],EndPos-StartPos)) then begin
NewPath:=ChompPathDelim(
TrimFilename(copy(Result,StartPos,EndPos-StartPos)));
Result:=copy(Result,1,StartPos-1)+NewPath+copy(Result,EndPos,length(Result));
EndPos:=StartPos+length(NewPath);
end;
// check if path already exists
if (Length(Result) > 0) and
(FindPathInSearchPath(@Result[StartPos],EndPos-StartPos, @Result[1],StartPos-1) <> nil)
then begin
// remove path
System.Delete(Result,StartPos,EndPos-StartPos+1);
end else begin
StartPos:=EndPos+1;
end;
end else begin
// remove empty path
System.Delete(Result,StartPos,1);
end;
end;
if (Result<>'') and (Result[length(Result)]=';') then
SetLength(Result,length(Result)-1);
end;
function FindPathInSearchPath(APath: PChar; APathLen: integer;
SearchPath: PChar; SearchPathLen: integer): PChar;
var
StartPos: Integer;
EndPos: LongInt;
NextStartPos: LongInt;
CmpPos: LongInt;
UseQuickCompare: Boolean;
PathStr: String;
CurFilename: String;
begin
Result:=nil;
if SearchPath=nil then exit;
if (APath=nil) or (APathLen=0) then exit;
// ignore trailing PathDelim at end
while (APathLen>1) and (APath[APathLen-1] in AllowDirectorySeparators) do dec(APathLen);
{$IFDEF CaseInsensitiveFilenames}
UseQuickCompare:=false;
{$ELSE}
{$IFDEF NotLiteralFilenames}
CmpPos:=0;
while (CmpPos<APathLen) and (ord(APath[CmpPos]<128)) do inc(CmpPos);
UseQuickCompare:=CmpPos=APathLen;
{$ELSE}
UseQuickCompare:=true;
{$ENDIF}
{$ENDIF}
if not UseQuickCompare then begin
SetLength(PathStr,APathLen);
System.Move(APath^,PathStr[1],APathLen);
end;
StartPos:=0;
while StartPos<SearchPathLen do begin
// find current path bounds
NextStartPos:=StartPos;
while (SearchPath[NextStartPos]<>';') and (NextStartPos<SearchPathLen) do
inc(NextStartPos);
EndPos:=NextStartPos;
// ignore trailing PathDelim at end
while (EndPos>StartPos+1) and (SearchPath[EndPos-1] in AllowDirectorySeparators) do
dec(EndPos);
// compare current path
if UseQuickCompare then begin
if EndPos-StartPos=APathLen then begin
CmpPos:=0;
while CmpPos<APathLen do begin
if APath[CmpPos]<>SearchPath[StartPos+CmpPos] then
break;
inc(CmpPos);
end;
if CmpPos=APathLen then begin
Result:=@SearchPath[StartPos];
exit;
end;
end;
end else if EndPos>StartPos then begin
// use CompareFilenames
CurFilename:='';
SetLength(CurFilename,EndPos-StartPos);
System.Move(SearchPath[StartPos],CurFilename[1],EndPos-StartPos);
if CompareFilenames(PathStr,CurFilename)=0 then begin
Result:=@SearchPath[StartPos];
exit;
end;
end;
StartPos:=NextStartPos+1;
end;
end;
function FindPathInSearchPath(const APath, SearchPath: string): integer;
var
p: PChar;
SearchP: PChar;
begin
SearchP:=PChar(SearchPath);
p:=FindPathInSearchPath(PChar(APath),length(APath),SearchP,length(SearchPath));
if p=nil then
Result:=-1
else
Result:=p-SearchP+1;
end;
function FileSearchUTF8(const Name, DirList: String; ImplicitCurrentDir : Boolean = True): String;
Var
I : longint;
Temp : String;
begin
Result:=Name;
temp:=SetDirSeparators(DirList);
// Start with checking the file in the current directory
If ImplicitCurrentDir and (Result <> '') and FileExistsUTF8(Result) Then
exit;
while True do begin
If Temp = '' then
Break; // No more directories to search - fail
I:=pos(PathSeparator,Temp);
If I<>0 then
begin
Result:=Copy (Temp,1,i-1);
system.Delete(Temp,1,I);
end
else
begin
Result:=Temp;
Temp:='';
end;
If Result<>'' then
Result:=AppendPathDelim(Result)+Name;
If (Result <> '') and FileExistsUTF8(Result) Then
exit;
end;
Result:='';
end;
function FileIsReadOnlyUTF8(const FileName: String): Boolean;
begin
Result:=FileGetAttrUTF8(FileName) and faReadOnly > 0;
end;
function GetTempFileNameUTF8(const Dir, Prefix: String): String;
var
I: Integer;
Start: String;
begin
if Assigned(OnGetTempFile) then
Result:=OnGetTempFile(Dir,Prefix)
else
begin
if (Dir='') then
Start:=GetTempDir
else
Start:=IncludeTrailingPathDelimiter(Dir);
if (Prefix='') then
Start:=Start+'TMP'
else
Start:=Start+Prefix;
I:=0;
repeat
Result:=SysUtils.Format('%s%.5d.tmp',[Start,I]);
Inc(I);
until not FileExistsUTF8(Result);
end;
end;
function ForceDirectoriesUTF8(const Dir: string): Boolean;
var
E: EInOutError;
ADrv : String;
function DoForceDirectories(Const Dir: string): Boolean;
var
ADir : String;
APath: String;
begin
Result:=True;
ADir:=ExcludeTrailingPathDelimiter(Dir);
if (ADir='') then Exit;
if Not DirectoryExistsUTF8(ADir) then
begin
APath := ExtractFilePath(ADir);
//this can happen on Windows if user specifies Dir like \user\name/test/
//and would, if not checked for, cause an infinite recusrsion and a stack overflow
if (APath = ADir) then
Result := False
else
Result:=DoForceDirectories(APath);
if Result then
Result := CreateDirUTF8(ADir);
end;
end;
function IsUncDrive(const Drv: String): Boolean;
begin
Result := (Length(Drv) > 2) and (Drv[1] in AllowDirectorySeparators) and (Drv[2] in AllowDirectorySeparators);
end;
begin
Result := False;
ADrv := ExtractFileDrive(Dir);
if (ADrv<>'') and (not DirectoryExistsUTF8(ADrv))
{$IFNDEF FORCEDIR_NO_UNC_SUPPORT} and (not IsUncDrive(ADrv)){$ENDIF} then Exit;
if Dir='' then
begin
E:=EInOutError.Create(SCannotCreateEmptyDir);
E.ErrorCode:=3;
Raise E;
end;
Result := DoForceDirectories(GetForcedPathDelims(Dir));
end;
function TryReadAllLinks(const Filename: string): string;
begin
Result:=ReadAllLinks(Filename,false);
if Result='' then
Result:=Filename;
end;
procedure InvalidateFileStateCache(const Filename: string);
begin
if Assigned(OnInvalidateFileStateCache) then
OnInvalidateFileStateCache(Filename);
end;
procedure SplitCmdLineParams(const Params: string; ParamList: TStrings;
ReadBackslash: boolean = false);
// split spaces, quotes are parsed as single parameter
// if ReadBackslash=true then \" is replaced to " and not treated as quote
// #0 is always end
type
TMode = (mNormal,mApostrophe,mQuote);
var
p: Integer;
Mode: TMode;
Param: String;
begin
p:=1;
while p<=length(Params) do
begin
// skip whitespace
while (p<=length(Params)) and (Params[p] in [' ',#9,#10,#13]) do inc(p);
if (p>length(Params)) or (Params[p]=#0) then
break;
//writeln('SplitCmdLineParams After Space p=',p,'=[',Params[p],']');
// read param
Param:='';
Mode:=mNormal;
while p<=length(Params) do
begin
case Params[p] of
#0:
break;
'\':
begin
inc(p);
if ReadBackslash then
begin
// treat next character as normal character
if (p>length(Params)) or (Params[p]=#0) then
break;
if ord(Params[p])<128 then
begin
Param+=Params[p];
inc(p);
end else begin
// next character is already a normal character
end;
end else begin
// treat backslash as normal character
Param+='\';
end;
end;
'''':
begin
inc(p);
case Mode of
mNormal:
Mode:=mApostrophe;
mApostrophe:
Mode:=mNormal;
mQuote:
Param+='''';
end;
end;
'"':
begin
inc(p);
case Mode of
mNormal:
Mode:=mQuote;
mApostrophe:
Param+='"';
mQuote:
Mode:=mNormal;
end;
end;
' ',#9,#10,#13:
begin
if Mode=mNormal then break;
Param+=Params[p];
inc(p);
end;
else
Param+=Params[p];
inc(p);
end;
end;
//writeln('SplitCmdLineParams Param=#'+Param+'#');
ParamList.Add(Param);
end;
end;
function StrToCmdLineParam(const Param: string): string;
{ <empty> -> ''
word -> word
word1 word2 -> 'word1 word2'
word's -> "word's"
a" -> 'a"'
"a" -> '"a"'
'a' -> "'a'"
#0 character -> cut the rest
}
const
NoQuot = ' ';
AnyQuot = '*';
var
Quot: Char;
p: PChar;
i: Integer;
begin
Result:=Param;
if Result='' then
Result:=''''''
else begin
p:=PChar(Result);
Quot:=NoQuot;
repeat
case p^ of
#0:
begin
i:=p-PChar(Result);
if i<length(Result) then
Delete(Result,i+1,length(Result));
case Quot of
AnyQuot: Result:=''''+Result+'''';
'''': Result+='''';
'"': Result+='"';
end;
break;
end;
' ',#9,#10,#13:
begin
if Quot=NoQuot then
Quot:=AnyQuot;
inc(p);
end;
'''':
begin
case Quot of
NoQuot,AnyQuot:
begin
// need "
Quot:='"';
i:=p-PChar(Result);
System.Insert('"',Result,1);
p:=PChar(Result)+i+1;
end;
'"':
inc(p);
'''':
begin
// ' within a '
// => end ', start "
i:=p-PChar(Result)+1;
System.Insert('''"',Result,i);
p:=PChar(Result)+i+1;
Quot:='"';
end;
end;
end;
'"':
begin
case Quot of
NoQuot,AnyQuot:
begin
// need '
Quot:='''';
i:=p-PChar(Result);
System.Insert('''',Result,1);
p:=PChar(Result)+i+1;
end;
'''':
inc(p);
'"':
begin
// " within a "
// => end ", start '
i:=p-PChar(Result)+1;
System.Insert('"''',Result,i);
p:=PChar(Result)+i+1;
Quot:='''';
end;
end;
end;
else
inc(p);
end;
until false;
end;
end;
function MergeCmdLineParams(ParamList: TStrings): string;
var
i: Integer;
begin
Result:='';
if ParamList=nil then exit;
for i:=0 to ParamList.Count-1 do
begin
if i>0 then Result+=' ';
Result+=StrToCmdLineParam(ParamList[i]);
end;
end;
procedure SplitCmdLine(const CmdLine: string;
out ProgramFilename, Params: string);
var p, s, l: integer;
quote: char;
begin
ProgramFilename:='';
Params:='';
if CmdLine='' then exit;
p:=1;
s:=1;
if (CmdLine[p] in ['"','''']) then
begin
// skip quoted string
quote:=CmdLine[p];
inc(s);
repeat
inc(p);
if p>Length(CmdLine) then Break;
// check if we have an escape char
if (CmdLine[p] = '\') and (CmdLine[p]<>PathDelim) then inc(p);
until (p>Length(CmdLine)) or (CmdLine[p]=quote);
// go past last character or quoted string
l:=p-s;
inc(p);
end else begin
while (p<=length(CmdLine)) and (CmdLine[p]>' ') do begin
if (CmdLine[p] in ['/','\']) and (CmdLine[p]<>PathDelim) then begin
// skip special char
inc(p);
end;
inc(p);
end;
l:=p-s;
end;
ProgramFilename:=Copy(CmdLine,s,l);
while (p<=length(CmdLine)) and (CmdLine[p]<=' ') do inc(p);
Params:=RightStr(CmdLine,length(CmdLine)-p+1);
end;
function PrepareCmdLineOption(const Option: string): string;
// If there is a space in the option add " " around the whole option
var
i: integer;
begin
Result:=Option;
if (Result='') or (Result[1]='"') then exit;
for i:=1 to length(Result) do begin
if Result[i]=' ' then begin
Result:='"'+Result+'"';
exit;
end;
end;
end;
{
function AddCmdLineParameter(const CmdLine, AddParameter: string): string;
begin
Result:=CmdLine;
if (Result<>'') and (Result[length(Result)]<>' ') then
Result:=Result+' ';
Result:=Result+AddParameter;
end;
}
{
Returns
- DriveLetter + : + PathDelim on Windows (if present) or
- UNC Share on Windows if present or
- PathDelim if FileName starts with PathDelim on Unix or Wince or
- Empty string of non eof the above applies
}
function ExtractFileRoot(FileName: String): String;
var
Len: Integer;
begin
Result := '';
Len := Length(FileName);
if (Len > 0) then
begin
if IsUncPath(FileName) then
begin
Result := ExtractUNCVolume(FileName);
// is it like \\?\C:\Directory? then also include the "C:\" part
if (Result = '\\?\') and (Length(FileName) > 6) and
(FileName[5] in ['a'..'z','A'..'Z']) and (FileName[6] = ':') and (FileName[7] in AllowDirectorySeparators)
then
Result := Copy(FileName, 1, 7);
end
else
begin
{$if defined(unix) or defined(wince)}
if (FileName[1] = PathDelim) then Result := PathDelim;
{$else}
{$ifdef HASAMIGA}
if Pos(':', FileName) > 1 then
Result := Copy(FileName, 1, Pos(':', FileName));
{$else}
if (Len > 2) and (FileName[1] in ['a'..'z','A'..'Z']) and (FileName[2] = ':') and (FileName[3] in AllowDirectorySeparators) then
Result := UpperCase(Copy(FileName,1,3));
{$endif}
{$endif}
end;
end;
end;
initialization
InitLazFileUtils;
finalization
FinalizeLazFileUtils;
end.
end.
|