cfileutl.pas 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308
  1. {
  2. Copyright (c) 1998-2002 by Florian Klaempfl and Peter Vreman
  3. This module provides some basic file/dir handling utils and classes
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, write to the Free Software
  14. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  15. ****************************************************************************
  16. }
  17. unit cfileutl;
  18. {$i fpcdefs.inc}
  19. {$define usedircache}
  20. interface
  21. uses
  22. {$ifdef hasunix}
  23. Baseunix,unix,
  24. {$endif hasunix}
  25. {$ifdef win32}
  26. Windows,
  27. {$endif win32}
  28. {$if defined(go32v2) or defined(watcom)}
  29. Dos,
  30. {$endif}
  31. {$IFNDEF USE_FAKE_SYSUTILS}
  32. SysUtils,
  33. {$ELSE}
  34. fksysutl,
  35. {$ENDIF}
  36. GlobType,
  37. CUtils,CClasses,
  38. Systems;
  39. type
  40. TCachedDirectory = class(TFPHashObject)
  41. private
  42. FDirectoryEntries : TFPHashList;
  43. FCached : Boolean;
  44. procedure FreeDirectoryEntries;
  45. function GetItemAttr(const AName: TCmdStr): longint;
  46. function TryUseCache: boolean;
  47. procedure ForceUseCache;
  48. procedure Reload;
  49. public
  50. constructor Create(AList:TFPHashObjectList;const AName:TCmdStr);
  51. destructor destroy;override;
  52. function FileExists(const AName:TCmdStr):boolean;
  53. function FileExistsCaseAware(const path, fn: TCmdStr; out FoundName: TCmdStr):boolean;
  54. function DirectoryExists(const AName:TCmdStr):boolean;
  55. property DirectoryEntries:TFPHashList read FDirectoryEntries;
  56. end;
  57. TCachedSearchRec = record
  58. Name : TCmdStr;
  59. Attr : byte;
  60. Pattern : TCmdStr;
  61. CachedDir : TCachedDirectory;
  62. EntryIndex : longint;
  63. end;
  64. PCachedDirectoryEntry = ^TCachedDirectoryEntry;
  65. TCachedDirectoryEntry = record
  66. RealName: TCmdStr;
  67. Attr : longint;
  68. end;
  69. TDirectoryCache = class
  70. private
  71. FDirectories : TFPHashObjectList;
  72. function GetDirectory(const ADir:TCmdStr):TCachedDirectory;
  73. public
  74. constructor Create;
  75. destructor destroy;override;
  76. function FileExists(const AName:TCmdStr):boolean;
  77. function FileExistsCaseAware(const path, fn: TCmdStr; out FoundName: TCmdStr):boolean;
  78. function DirectoryExists(const AName:TCmdStr):boolean;
  79. function FindFirst(const APattern:TCmdStr;var Res:TCachedSearchRec):boolean;
  80. function FindNext(var Res:TCachedSearchRec):boolean;
  81. function FindClose(var Res:TCachedSearchRec):boolean;
  82. end;
  83. TSearchPathList = class(TCmdStrList)
  84. procedure AddPath(s:TCmdStr;addfirst:boolean);overload;
  85. procedure AddPath(SrcPath,s:TCmdStr;addfirst:boolean);overload;
  86. procedure AddList(list:TSearchPathList;addfirst:boolean);
  87. function FindFile(const f : TCmdStr;allowcache:boolean;var foundfile:TCmdStr):boolean;
  88. end;
  89. function bstoslash(const s : TCmdStr) : TCmdStr;
  90. {Gives the absolute path to the current directory}
  91. function GetCurrentDir:TCmdStr;
  92. {Gives the relative path to the current directory,
  93. with a trailing dir separator. E. g. on unix ./ }
  94. function CurDirRelPath(systeminfo: tsysteminfo): TCmdStr;
  95. function path_absolute(const s : TCmdStr) : boolean;
  96. Function PathExists (const F : TCmdStr;allowcache:boolean) : Boolean;
  97. Function FileExists (const F : TCmdStr;allowcache:boolean) : Boolean;
  98. function FileExistsNonCase(const path,fn:TCmdStr;allowcache:boolean;var foundfile:TCmdStr):boolean;
  99. Function RemoveDir(d:TCmdStr):boolean;
  100. Function FixPath(const s:TCmdStr;allowdot:boolean):TCmdStr;
  101. function FixFileName(const s:TCmdStr):TCmdStr;
  102. function TargetFixPath(s:TCmdStr;allowdot:boolean):TCmdStr;
  103. function TargetFixFileName(const s:TCmdStr):TCmdStr;
  104. procedure SplitBinCmd(const s:TCmdStr;var bstr: TCmdStr;var cstr:TCmdStr);
  105. function FindFile(const f : TCmdStr; const path : TCmdStr;allowcache:boolean;var foundfile:TCmdStr):boolean;
  106. { function FindFilePchar(const f : TCmdStr;path : pchar;allowcache:boolean;var foundfile:TCmdStr):boolean;}
  107. function FindFileInExeLocations(const bin:TCmdStr;allowcache:boolean;var foundfile:TCmdStr):boolean;
  108. function FindExe(const bin:TCmdStr;allowcache:boolean;var foundfile:TCmdStr):boolean;
  109. function GetShortName(const n:TCmdStr):TCmdStr;
  110. procedure InitFileUtils;
  111. procedure DoneFileUtils;
  112. { * Since native Amiga commands can't handle Unix-style relative paths used by the compiler,
  113. and some GNU tools, Unix2AmigaPath is needed to handle such situations (KB) * }
  114. {$IF DEFINED(MORPHOS) OR DEFINED(AMIGA)}
  115. { * PATHCONV is implemented in the Amiga/MorphOS system unit * }
  116. {$WARNING TODO Amiga: implement PathConv() in System unit, which works with AnsiString}
  117. function Unix2AmigaPath(path: ShortString): ShortString; external name 'PATHCONV';
  118. {$ELSE}
  119. function Unix2AmigaPath(path: String): String;{$IFDEF USEINLINE}inline;{$ENDIF}
  120. {$ENDIF}
  121. implementation
  122. uses
  123. Comphook,
  124. Globals;
  125. {$undef AllFilesMaskIsInRTL}
  126. {$if (FPC_VERSION > 2)}
  127. {$define AllFilesMaskIsInRTL}
  128. {$endif FPC_VERSION}
  129. {$if (FPC_VERSION = 2) and (FPC_RELEASE > 2)}
  130. {$define AllFilesMaskIsInRTL}
  131. {$endif}
  132. {$if (FPC_VERSION = 2) and (FPC_RELEASE = 2) and (FPC_PATCH > 0)}
  133. {$define AllFilesMaskIsInRTL}
  134. {$endif}
  135. {$ifndef AllFilesMaskIsInRTL}
  136. {$if defined(go32v2) or defined(watcom)}
  137. const
  138. AllFilesMask = '*.*';
  139. {$else}
  140. const
  141. AllFilesMask = '*';
  142. {$endif not (go32v2 or watcom)}
  143. {$endif not AllFilesMaskIsInRTL}
  144. var
  145. DirCache : TDirectoryCache;
  146. {$IF NOT (DEFINED(MORPHOS) OR DEFINED(AMIGA))}
  147. { Stub function for Unix2Amiga Path conversion functionality, only available in
  148. Amiga/MorphOS RTL. I'm open for better solutions. (KB) }
  149. function Unix2AmigaPath(path: String): String;{$IFDEF USEINLINE}inline;{$ENDIF}
  150. begin
  151. Unix2AmigaPath:=path;
  152. end;
  153. {$ENDIF}
  154. {****************************************************************************
  155. TCachedDirectory
  156. ****************************************************************************}
  157. constructor TCachedDirectory.create(AList:TFPHashObjectList;const AName:TCmdStr);
  158. begin
  159. inherited create(AList,AName);
  160. FDirectoryEntries:=TFPHashList.Create;
  161. FCached:=False;
  162. end;
  163. destructor TCachedDirectory.destroy;
  164. begin
  165. FreeDirectoryEntries;
  166. FDirectoryEntries.Free;
  167. inherited destroy;
  168. end;
  169. function TCachedDirectory.TryUseCache:boolean;
  170. begin
  171. Result:=True;
  172. if FCached then
  173. exit;
  174. if not current_settings.disabledircache then
  175. ForceUseCache
  176. else
  177. Result:=False;
  178. end;
  179. procedure TCachedDirectory.ForceUseCache;
  180. begin
  181. if not FCached then
  182. begin
  183. FCached:=True;
  184. Reload;
  185. end;
  186. end;
  187. procedure TCachedDirectory.FreeDirectoryEntries;
  188. var
  189. i: Integer;
  190. begin
  191. if not(tf_files_case_aware in source_info.flags) then
  192. exit;
  193. for i := 0 to DirectoryEntries.Count-1 do
  194. dispose(PCachedDirectoryEntry(DirectoryEntries[i]));
  195. end;
  196. function TCachedDirectory.GetItemAttr(const AName: TCmdStr): longint;
  197. var
  198. entry: PCachedDirectoryEntry;
  199. begin
  200. if not(tf_files_case_sensitive in source_info.flags) then
  201. if (tf_files_case_aware in source_info.flags) then
  202. begin
  203. entry:=PCachedDirectoryEntry(DirectoryEntries.Find(Lower(AName)));
  204. if assigned(entry) then
  205. Result:=entry^.Attr
  206. else
  207. Result:=0;
  208. end
  209. else
  210. Result:=PtrUInt(DirectoryEntries.Find(Lower(AName)))
  211. else
  212. Result:=PtrUInt(DirectoryEntries.Find(AName));
  213. end;
  214. procedure TCachedDirectory.Reload;
  215. var
  216. dir : TSearchRec;
  217. entry : PCachedDirectoryEntry;
  218. begin
  219. FreeDirectoryEntries;
  220. DirectoryEntries.Clear;
  221. if findfirst(IncludeTrailingPathDelimiter(Name)+AllFilesMask,faAnyFile or faDirectory,dir) = 0 then
  222. begin
  223. repeat
  224. if ((dir.attr and faDirectory)<>faDirectory) or
  225. ((dir.Name<>'.') and
  226. (dir.Name<>'..')) then
  227. begin
  228. { Force Archive bit so the attribute always has a value. This is needed
  229. to be able to see the difference in the directoryentries lookup if a file
  230. exists or not }
  231. Dir.Attr:=Dir.Attr or faArchive;
  232. if not(tf_files_case_sensitive in source_info.flags) then
  233. if (tf_files_case_aware in source_info.flags) then
  234. begin
  235. new(entry);
  236. entry^.RealName:=Dir.Name;
  237. entry^.Attr:=Dir.Attr;
  238. DirectoryEntries.Add(Lower(Dir.Name),entry)
  239. end
  240. else
  241. DirectoryEntries.Add(Lower(Dir.Name),Pointer(Ptrint(Dir.Attr)))
  242. else
  243. DirectoryEntries.Add(Dir.Name,Pointer(Ptrint(Dir.Attr)));
  244. end;
  245. until findnext(dir) <> 0;
  246. end;
  247. findclose(dir);
  248. end;
  249. function TCachedDirectory.FileExists(const AName:TCmdStr):boolean;
  250. var
  251. Attr : Longint;
  252. begin
  253. if not TryUseCache then
  254. begin
  255. { prepend directory name again }
  256. result:=cfileutl.FileExists(Name+AName,false);
  257. exit;
  258. end;
  259. Attr:=GetItemAttr(AName);
  260. if Attr<>0 then
  261. Result:=((Attr and faDirectory)=0)
  262. else
  263. Result:=false;
  264. end;
  265. function TCachedDirectory.FileExistsCaseAware(const path, fn: TCmdStr; out FoundName: TCmdStr):boolean;
  266. var
  267. entry : PCachedDirectoryEntry;
  268. begin
  269. if (tf_files_case_aware in source_info.flags) then
  270. begin
  271. if not TryUseCache then
  272. begin
  273. Result:=FileExistsNonCase(path,fn,false,FoundName);
  274. exit;
  275. end;
  276. entry:=PCachedDirectoryEntry(DirectoryEntries.Find(Lower(ExtractFileName(fn))));
  277. if assigned(entry) and
  278. (entry^.Attr<>0) and
  279. ((entry^.Attr and faDirectory) = 0) then
  280. begin
  281. FoundName:=ExtractFilePath(path+fn)+entry^.RealName;
  282. Result:=true
  283. end
  284. else
  285. Result:=false;
  286. end
  287. else
  288. { should not be called in this case, use plain FileExists }
  289. Result:=False;
  290. end;
  291. function TCachedDirectory.DirectoryExists(const AName:TCmdStr):boolean;
  292. var
  293. Attr : Longint;
  294. begin
  295. if not TryUseCache then
  296. begin
  297. Result:=PathExists(Name+AName,false);
  298. exit;
  299. end;
  300. Attr:=GetItemAttr(AName);
  301. if Attr<>0 then
  302. Result:=((Attr and faDirectory)=faDirectory)
  303. else
  304. Result:=false;
  305. end;
  306. {****************************************************************************
  307. TDirectoryCache
  308. ****************************************************************************}
  309. constructor TDirectoryCache.create;
  310. begin
  311. inherited create;
  312. FDirectories:=TFPHashObjectList.Create(true);
  313. end;
  314. destructor TDirectoryCache.destroy;
  315. begin
  316. FDirectories.Free;
  317. inherited destroy;
  318. end;
  319. function TDirectoryCache.GetDirectory(const ADir:TCmdStr):TCachedDirectory;
  320. var
  321. CachedDir : TCachedDirectory;
  322. DirName : TCmdStr;
  323. begin
  324. if ADir='' then
  325. DirName:='.'+source_info.DirSep
  326. else
  327. DirName:=ADir;
  328. CachedDir:=TCachedDirectory(FDirectories.Find(DirName));
  329. if not assigned(CachedDir) then
  330. CachedDir:=TCachedDirectory.Create(FDirectories,DirName);
  331. Result:=CachedDir;
  332. end;
  333. function TDirectoryCache.FileExists(const AName:TCmdStr):boolean;
  334. var
  335. CachedDir : TCachedDirectory;
  336. begin
  337. Result:=false;
  338. CachedDir:=GetDirectory(ExtractFilePath(AName));
  339. if assigned(CachedDir) then
  340. Result:=CachedDir.FileExists(ExtractFileName(AName));
  341. end;
  342. function TDirectoryCache.FileExistsCaseAware(const path, fn: TCmdStr; out FoundName: TCmdStr):boolean;
  343. var
  344. CachedDir : TCachedDirectory;
  345. begin
  346. Result:=false;
  347. CachedDir:=GetDirectory(ExtractFilePath(path+fn));
  348. if assigned(CachedDir) then
  349. Result:=CachedDir.FileExistsCaseAware(path,fn,FoundName);
  350. end;
  351. function TDirectoryCache.DirectoryExists(const AName:TCmdStr):boolean;
  352. var
  353. CachedDir : TCachedDirectory;
  354. begin
  355. Result:=false;
  356. CachedDir:=GetDirectory(ExtractFilePath(AName));
  357. if assigned(CachedDir) then
  358. Result:=CachedDir.DirectoryExists(ExtractFileName(AName));
  359. end;
  360. function TDirectoryCache.FindFirst(const APattern:TCmdStr;var Res:TCachedSearchRec):boolean;
  361. begin
  362. Res.Pattern:=ExtractFileName(APattern);
  363. Res.CachedDir:=GetDirectory(ExtractFilePath(APattern));
  364. Res.CachedDir.ForceUseCache;
  365. Res.EntryIndex:=0;
  366. if assigned(Res.CachedDir) then
  367. Result:=FindNext(Res)
  368. else
  369. Result:=false;
  370. end;
  371. function TDirectoryCache.FindNext(var Res:TCachedSearchRec):boolean;
  372. var
  373. entry: PCachedDirectoryEntry;
  374. begin
  375. if Res.EntryIndex<Res.CachedDir.DirectoryEntries.Count then
  376. begin
  377. if (tf_files_case_aware in source_info.flags) then
  378. begin
  379. entry:=Res.CachedDir.DirectoryEntries[Res.EntryIndex];
  380. Res.Name:=entry^.RealName;
  381. Res.Attr:=entry^.Attr;
  382. end
  383. else
  384. begin
  385. Res.Name:=Res.CachedDir.DirectoryEntries.NameOfIndex(Res.EntryIndex);
  386. Res.Attr:=PtrUInt(Res.CachedDir.DirectoryEntries[Res.EntryIndex]);
  387. end;
  388. inc(Res.EntryIndex);
  389. Result:=true;
  390. end
  391. else
  392. Result:=false;
  393. end;
  394. function TDirectoryCache.FindClose(var Res:TCachedSearchRec):boolean;
  395. begin
  396. { nothing todo }
  397. result:=true;
  398. end;
  399. {****************************************************************************
  400. Utils
  401. ****************************************************************************}
  402. function bstoslash(const s : TCmdStr) : TCmdStr;
  403. {
  404. return TCmdStr s with all \ changed into /
  405. }
  406. var
  407. i : longint;
  408. begin
  409. setlength(bstoslash,length(s));
  410. for i:=1to length(s) do
  411. if s[i]='\' then
  412. bstoslash[i]:='/'
  413. else
  414. bstoslash[i]:=s[i];
  415. end;
  416. {Gives the absolute path to the current directory}
  417. var
  418. CachedCurrentDir : TCmdStr;
  419. function GetCurrentDir:TCmdStr;
  420. begin
  421. if CachedCurrentDir='' then
  422. begin
  423. GetDir(0,CachedCurrentDir);
  424. CachedCurrentDir:=FixPath(CachedCurrentDir,false);
  425. end;
  426. result:=CachedCurrentDir;
  427. end;
  428. {Gives the relative path to the current directory,
  429. with a trailing dir separator. E. g. on unix ./ }
  430. function CurDirRelPath(systeminfo: tsysteminfo): TCmdStr;
  431. begin
  432. if systeminfo.system <> system_powerpc_macos then
  433. CurDirRelPath:= '.'+systeminfo.DirSep
  434. else
  435. CurDirRelPath:= ':'
  436. end;
  437. function path_absolute(const s : TCmdStr) : boolean;
  438. {
  439. is path s an absolute path?
  440. }
  441. begin
  442. result:=false;
  443. {$if defined(unix)}
  444. if (length(s)>0) and (s[1] in AllowDirectorySeparators) then
  445. result:=true;
  446. {$elseif defined(amiga) or defined(morphos)}
  447. (* An Amiga path is absolute, if it has a volume/device name in it (contains ":"),
  448. otherwise it's always a relative path, no matter if it starts with a directory
  449. separator or not. (KB) *)
  450. if (length(s)>0) and (Pos(':',s) <> 0) then
  451. result:=true;
  452. {$elseif defined(macos)}
  453. if IsMacFullPath(s) then
  454. result:=true;
  455. {$elseif defined(netware)}
  456. if (Pos (DriveSeparator, S) <> 0) or
  457. ((Length (S) > 0) and (S [1] in AllowDirectorySeparators)) then
  458. result:=true;
  459. {$elseif defined(win32) or defined(win64) or defined(go32v2) or defined(os2) or defined(watcom)}
  460. if ((length(s)>0) and (s[1] in AllowDirectorySeparators)) or
  461. (* The following check for non-empty AllowDriveSeparators assumes that all
  462. other platforms supporting drives and not handled as exceptions above
  463. should work with DOS-like paths, i.e. use absolute paths with one letter
  464. for drive followed by path separator *)
  465. ((length(s)>2) and (s[2] in AllowDriveSeparators) and (s[3] in AllowDirectorySeparators)) then
  466. result:=true;
  467. {$else}
  468. if ((length(s)>0) and (s[1] in AllowDirectorySeparators)) or
  469. (* The following check for non-empty AllowDriveSeparators assumes that all
  470. other platforms supporting drives and not handled as exceptions above
  471. should work with DOS-like paths, i.e. use absolute paths with one letter
  472. for drive followed by path separator *)
  473. ((AllowDriveSeparators <> []) and (length(s)>2) and (s[2] in AllowDriveSeparators) and (s[3] in AllowDirectorySeparators)) then
  474. result:=true;
  475. {$endif unix}
  476. end;
  477. Function FileExists ( Const F : TCmdStr;allowcache:boolean) : Boolean;
  478. begin
  479. {$ifdef usedircache}
  480. if allowcache then
  481. Result:=DirCache.FileExists(F)
  482. else
  483. {$endif usedircache}
  484. Result:=SysUtils.FileExists(F);
  485. if do_checkverbosity(V_Tried) then
  486. begin
  487. if Result then
  488. do_comment(V_Tried,'Searching file '+F+'... found')
  489. else
  490. do_comment(V_Tried,'Searching file '+F+'... not found');
  491. end;
  492. end;
  493. function FileExistsNonCase(const path,fn:TCmdStr;allowcache:boolean;var foundfile:TCmdStr):boolean;
  494. var
  495. fn2 : TCmdStr;
  496. begin
  497. result:=false;
  498. if tf_files_case_sensitive in source_info.flags then
  499. begin
  500. {
  501. Search order for case sensitive systems:
  502. 1. NormalCase
  503. 2. lowercase
  504. 3. UPPERCASE
  505. }
  506. FoundFile:=path+fn;
  507. If FileExists(FoundFile,allowcache) then
  508. begin
  509. result:=true;
  510. exit;
  511. end;
  512. fn2:=Lower(fn);
  513. if fn2<>fn then
  514. begin
  515. FoundFile:=path+fn2;
  516. If FileExists(FoundFile,allowcache) then
  517. begin
  518. result:=true;
  519. exit;
  520. end;
  521. end;
  522. fn2:=Upper(fn);
  523. if fn2<>fn then
  524. begin
  525. FoundFile:=path+fn2;
  526. If FileExists(FoundFile,allowcache) then
  527. begin
  528. result:=true;
  529. exit;
  530. end;
  531. end;
  532. end
  533. else
  534. if tf_files_case_aware in source_info.flags then
  535. begin
  536. {
  537. Search order for case aware systems:
  538. 1. NormalCase
  539. }
  540. {$ifdef usedircache}
  541. if allowcache then
  542. begin
  543. result:=DirCache.FileExistsCaseAware(path,fn,fn2);
  544. if result then
  545. begin
  546. FoundFile:=fn2;
  547. exit;
  548. end;
  549. end
  550. else
  551. {$endif usedircache}
  552. begin
  553. FoundFile:=path+fn;
  554. If FileExists(FoundFile,allowcache) then
  555. begin
  556. { don't know the real name in this case }
  557. result:=true;
  558. exit;
  559. end;
  560. end;
  561. end
  562. else
  563. begin
  564. { None case sensitive only lowercase }
  565. FoundFile:=path+Lower(fn);
  566. If FileExists(FoundFile,allowcache) then
  567. begin
  568. result:=true;
  569. exit;
  570. end;
  571. end;
  572. { Set foundfile to something useful }
  573. FoundFile:=fn;
  574. end;
  575. Function PathExists (const F : TCmdStr;allowcache:boolean) : Boolean;
  576. Var
  577. i: longint;
  578. hs : TCmdStr;
  579. begin
  580. if F = '' then
  581. begin
  582. result := true;
  583. exit;
  584. end;
  585. hs := ExpandFileName(F);
  586. I := Pos (DriveSeparator, hs);
  587. if (hs [Length (hs)] = DirectorySeparator) and
  588. (((I = 0) and (Length (hs) > 1)) or (I <> Length (hs) - 1)) then
  589. Delete (hs, Length (hs), 1);
  590. {$ifdef usedircache}
  591. if allowcache then
  592. Result:=DirCache.DirectoryExists(hs)
  593. else
  594. {$endif usedircache}
  595. Result:=SysUtils.DirectoryExists(hs);
  596. end;
  597. Function RemoveDir(d:TCmdStr):boolean;
  598. begin
  599. if d[length(d)]=source_info.DirSep then
  600. Delete(d,length(d),1);
  601. {$I-}
  602. rmdir(d);
  603. {$I+}
  604. RemoveDir:=(ioresult=0);
  605. end;
  606. Function FixPath(const s:TCmdStr;allowdot:boolean):TCmdStr;
  607. var
  608. i, L : longint;
  609. P: PChar;
  610. begin
  611. Result := s;
  612. L := Length(Result);
  613. if L=0 then
  614. exit;
  615. { Fix separator }
  616. P := @Result[1];
  617. for i:=0 to L-1 do
  618. begin
  619. if p^ in ['/','\'] then
  620. p^:=source_info.DirSep;
  621. inc(p);
  622. end;
  623. { Fix ending / }
  624. if (L>0) and (Result[L]<>source_info.DirSep) and
  625. (Result[L]<>DriveSeparator) then
  626. Result:=Result+source_info.DirSep; { !still results in temp AnsiString }
  627. { Remove ./ }
  628. if (not allowdot) and ((Length(Result)=2) and (Result[1]='.') and (Result[2] = source_info.DirSep)) then
  629. begin
  630. Result:='';
  631. Exit;
  632. end;
  633. { return }
  634. if not ((tf_files_case_aware in source_info.flags) or
  635. (tf_files_case_sensitive in source_info.flags)) then
  636. Result := lower(Result);
  637. end;
  638. {Actually the version in macutils.pp could be used,
  639. but that would not work for crosscompiling, so this is a slightly modified
  640. version of it.}
  641. function TranslatePathToMac (const path: TCmdStr; mpw: Boolean): TCmdStr;
  642. function GetVolumeIdentifier: TCmdStr;
  643. begin
  644. GetVolumeIdentifier := '{Boot}'
  645. (*
  646. if mpw then
  647. GetVolumeIdentifier := '{Boot}'
  648. else
  649. GetVolumeIdentifier := macosBootVolumeName;
  650. *)
  651. end;
  652. var
  653. slashPos, oldpos, newpos, oldlen, maxpos: Longint;
  654. begin
  655. oldpos := 1;
  656. slashPos := Pos('/', path);
  657. if (slashPos <> 0) then {its a unix path}
  658. begin
  659. if slashPos = 1 then
  660. begin {its a full path}
  661. oldpos := 2;
  662. TranslatePathToMac := GetVolumeIdentifier;
  663. end
  664. else {its a partial path}
  665. TranslatePathToMac := ':';
  666. end
  667. else
  668. begin
  669. slashPos := Pos('\', path);
  670. if (slashPos <> 0) then {its a dos path}
  671. begin
  672. if slashPos = 1 then
  673. begin {its a full path, without drive letter}
  674. oldpos := 2;
  675. TranslatePathToMac := GetVolumeIdentifier;
  676. end
  677. else if (Length(path) >= 2) and (path[2] = ':') then {its a full path, with drive letter}
  678. begin
  679. oldpos := 4;
  680. TranslatePathToMac := GetVolumeIdentifier;
  681. end
  682. else {its a partial path}
  683. TranslatePathToMac := ':';
  684. end;
  685. end;
  686. if (slashPos <> 0) then {its a unix or dos path}
  687. begin
  688. {Translate "/../" to "::" , "/./" to ":" and "/" to ":" }
  689. newpos := Length(TranslatePathToMac);
  690. oldlen := Length(path);
  691. SetLength(TranslatePathToMac, newpos + oldlen); {It will be no longer than what is already}
  692. {prepended plus length of path.}
  693. maxpos := Length(TranslatePathToMac); {Get real maxpos, can be short if String is ShortString}
  694. {There is never a slash in the beginning, because either it was an absolute path, and then the}
  695. {drive and slash was removed, or it was a relative path without a preceding slash.}
  696. while oldpos <= oldlen do
  697. begin
  698. {Check if special dirs, ./ or ../ }
  699. if path[oldPos] = '.' then
  700. if (oldpos + 1 <= oldlen) and (path[oldPos + 1] = '.') then
  701. begin
  702. if (oldpos + 2 > oldlen) or (path[oldPos + 2] in ['/', '\']) then
  703. begin
  704. {It is "../" or ".." translates to ":" }
  705. if newPos = maxPos then
  706. begin {Shouldn't actually happen, but..}
  707. Exit('');
  708. end;
  709. newPos := newPos + 1;
  710. TranslatePathToMac[newPos] := ':';
  711. oldPos := oldPos + 3;
  712. continue; {Start over again}
  713. end;
  714. end
  715. else if (oldpos + 1 > oldlen) or (path[oldPos + 1] in ['/', '\']) then
  716. begin
  717. {It is "./" or "." ignor it }
  718. oldPos := oldPos + 2;
  719. continue; {Start over again}
  720. end;
  721. {Collect file or dir name}
  722. while (oldpos <= oldlen) and not (path[oldPos] in ['/', '\']) do
  723. begin
  724. if newPos = maxPos then
  725. begin {Shouldn't actually happen, but..}
  726. Exit('');
  727. end;
  728. newPos := newPos + 1;
  729. TranslatePathToMac[newPos] := path[oldPos];
  730. oldPos := oldPos + 1;
  731. end;
  732. {When we come here there is either a slash or we are at the end.}
  733. if (oldpos <= oldlen) then
  734. begin
  735. if newPos = maxPos then
  736. begin {Shouldn't actually happen, but..}
  737. Exit('');
  738. end;
  739. newPos := newPos + 1;
  740. TranslatePathToMac[newPos] := ':';
  741. oldPos := oldPos + 1;
  742. end;
  743. end;
  744. SetLength(TranslatePathToMac, newpos);
  745. end
  746. else if (path = '.') then
  747. TranslatePathToMac := ':'
  748. else if (path = '..') then
  749. TranslatePathToMac := '::'
  750. else
  751. TranslatePathToMac := path; {its a mac path}
  752. end;
  753. function FixFileName(const s:TCmdStr):TCmdStr;
  754. var
  755. i : longint;
  756. begin
  757. if source_info.system = system_powerpc_MACOS then
  758. FixFileName:= TranslatePathToMac(s, true)
  759. else
  760. if (tf_files_case_aware in source_info.flags) or
  761. (tf_files_case_sensitive in source_info.flags) then
  762. begin
  763. setlength(FixFileName,length(s));
  764. for i:=1 to length(s) do
  765. begin
  766. case s[i] of
  767. '/','\' :
  768. FixFileName[i]:=source_info.dirsep;
  769. else
  770. FixFileName[i]:=s[i];
  771. end;
  772. end;
  773. end
  774. else
  775. begin
  776. setlength(FixFileName,length(s));
  777. for i:=1 to length(s) do
  778. begin
  779. case s[i] of
  780. '/','\' :
  781. FixFileName[i]:=source_info.dirsep;
  782. 'A'..'Z' :
  783. FixFileName[i]:=char(byte(s[i])+32);
  784. else
  785. FixFileName[i]:=s[i];
  786. end;
  787. end;
  788. end;
  789. end;
  790. Function TargetFixPath(s:TCmdStr;allowdot:boolean):TCmdStr;
  791. var
  792. i : longint;
  793. begin
  794. { Fix separator }
  795. for i:=1 to length(s) do
  796. if s[i] in ['/','\'] then
  797. s[i]:=target_info.DirSep;
  798. { Fix ending / }
  799. if (length(s)>0) and (s[length(s)]<>target_info.DirSep) and
  800. (s[length(s)]<>':') then
  801. s:=s+target_info.DirSep;
  802. { Remove ./ }
  803. if (not allowdot) and (s='.'+target_info.DirSep) then
  804. s:='';
  805. { return }
  806. if (tf_files_case_aware in target_info.flags) or
  807. (tf_files_case_sensitive in target_info.flags) then
  808. TargetFixPath:=s
  809. else
  810. TargetFixPath:=Lower(s);
  811. end;
  812. function TargetFixFileName(const s:TCmdStr):TCmdStr;
  813. var
  814. i : longint;
  815. begin
  816. if target_info.system = system_powerpc_MACOS then
  817. TargetFixFileName:= TranslatePathToMac(s, true)
  818. else
  819. if (tf_files_case_aware in target_info.flags) or
  820. (tf_files_case_sensitive in target_info.flags) then
  821. begin
  822. setlength(TargetFixFileName,length(s));
  823. for i:=1 to length(s) do
  824. begin
  825. case s[i] of
  826. '/','\' :
  827. TargetFixFileName[i]:=target_info.dirsep;
  828. else
  829. TargetFixFileName[i]:=s[i];
  830. end;
  831. end;
  832. end
  833. else
  834. begin
  835. setlength(TargetFixFileName,length(s));
  836. for i:=1 to length(s) do
  837. begin
  838. case s[i] of
  839. '/','\' :
  840. TargetFixFileName[i]:=target_info.dirsep;
  841. 'A'..'Z' :
  842. TargetFixFileName[i]:=char(byte(s[i])+32);
  843. else
  844. TargetFixFileName[i]:=s[i];
  845. end;
  846. end;
  847. end;
  848. end;
  849. procedure SplitBinCmd(const s:TCmdStr;var bstr:TCmdStr;var cstr:TCmdStr);
  850. var
  851. i : longint;
  852. begin
  853. i:=pos(' ',s);
  854. if i>0 then
  855. begin
  856. bstr:=Copy(s,1,i-1);
  857. cstr:=Copy(s,i+1,length(s)-i);
  858. end
  859. else
  860. begin
  861. bstr:=s;
  862. cstr:='';
  863. end;
  864. end;
  865. procedure TSearchPathList.AddPath(s:TCmdStr;addfirst:boolean);
  866. begin
  867. AddPath('',s,AddFirst);
  868. end;
  869. procedure TSearchPathList.AddPath(SrcPath,s:TCmdStr;addfirst:boolean);
  870. var
  871. staridx,
  872. i,j : longint;
  873. prefix,
  874. suffix,
  875. CurrentDir,
  876. currPath : TCmdStr;
  877. subdirfound : boolean;
  878. {$ifdef usedircache}
  879. dir : TCachedSearchRec;
  880. {$else usedircache}
  881. dir : TSearchRec;
  882. {$endif usedircache}
  883. hp : TCmdStrListItem;
  884. procedure WarnNonExistingPath(const path : TCmdStr);
  885. begin
  886. if do_checkverbosity(V_Tried) then
  887. do_comment(V_Tried,'Path "'+path+'" not found');
  888. end;
  889. procedure AddCurrPath;
  890. begin
  891. if addfirst then
  892. begin
  893. Remove(currPath);
  894. Insert(currPath);
  895. end
  896. else
  897. begin
  898. { Check if already in path, then we don't add it }
  899. hp:=Find(currPath);
  900. if not assigned(hp) then
  901. Concat(currPath);
  902. end;
  903. end;
  904. begin
  905. if s='' then
  906. exit;
  907. { Support default macro's }
  908. DefaultReplacements(s);
  909. {$warnings off}
  910. if PathSeparator <> ';' then
  911. for i:=1 to length(s) do
  912. if s[i]=PathSeparator then
  913. s[i]:=';';
  914. {$warnings on}
  915. { get current dir }
  916. CurrentDir:=GetCurrentDir;
  917. repeat
  918. { get currpath }
  919. if addfirst then
  920. begin
  921. j:=length(s);
  922. while (j>0) and (s[j]<>';') do
  923. dec(j);
  924. currPath:= TrimSpace(Copy(s,j+1,length(s)-j));
  925. if j=0 then
  926. s:=''
  927. else
  928. System.Delete(s,j,length(s)-j+1);
  929. end
  930. else
  931. begin
  932. j:=Pos(';',s);
  933. if j=0 then
  934. j:=length(s)+1;
  935. currPath:= TrimSpace(Copy(s,1,j-1));
  936. System.Delete(s,1,j);
  937. end;
  938. { fix pathname }
  939. DePascalQuote(currPath);
  940. currPath:=SrcPath+FixPath(currPath,false);
  941. if currPath='' then
  942. currPath:= CurDirRelPath(source_info)
  943. else
  944. begin
  945. currPath:=FixPath(ExpandFileName(currpath),false);
  946. if (CurrentDir<>'') and (Copy(currPath,1,length(CurrentDir))=CurrentDir) then
  947. begin
  948. {$if defined(amiga) and defined(morphos)}
  949. currPath:= CurrentDir+Copy(currPath,length(CurrentDir)+1,length(currPath));
  950. {$else}
  951. currPath:= CurDirRelPath(source_info)+Copy(currPath,length(CurrentDir)+1,length(currPath));
  952. {$endif}
  953. end;
  954. end;
  955. { wildcard adding ? }
  956. staridx:=pos('*',currpath);
  957. if staridx>0 then
  958. begin
  959. prefix:=ExtractFilePath(Copy(currpath,1,staridx));
  960. suffix:=Copy(currpath,staridx+1,length(currpath));
  961. subdirfound:=false;
  962. {$ifdef usedircache}
  963. if DirCache.FindFirst(Prefix+AllFilesMask,dir) then
  964. begin
  965. repeat
  966. if (dir.attr and faDirectory)<>0 then
  967. begin
  968. subdirfound:=true;
  969. currpath:=prefix+dir.name+suffix;
  970. if (suffix='') or PathExists(currpath,true) then
  971. begin
  972. hp:=Find(currPath);
  973. if not assigned(hp) then
  974. AddCurrPath;
  975. end;
  976. end;
  977. until not DirCache.FindNext(dir);
  978. end;
  979. DirCache.FindClose(dir);
  980. {$else usedircache}
  981. if findfirst(prefix+AllFilesMask,faDirectory,dir) = 0 then
  982. begin
  983. repeat
  984. if (dir.name<>'.') and
  985. (dir.name<>'..') and
  986. ((dir.attr and faDirectory)<>0) then
  987. begin
  988. subdirfound:=true;
  989. currpath:=prefix+dir.name+suffix;
  990. if (suffix='') or PathExists(currpath,false) then
  991. begin
  992. hp:=Find(currPath);
  993. if not assigned(hp) then
  994. AddCurrPath;
  995. end;
  996. end;
  997. until findnext(dir) <> 0;
  998. end;
  999. FindClose(dir);
  1000. {$endif usedircache}
  1001. if not subdirfound then
  1002. WarnNonExistingPath(currpath);
  1003. end
  1004. else
  1005. begin
  1006. if PathExists(currpath,true) then
  1007. AddCurrPath
  1008. else
  1009. WarnNonExistingPath(currpath);
  1010. end;
  1011. until (s='');
  1012. end;
  1013. procedure TSearchPathList.AddList(list:TSearchPathList;addfirst:boolean);
  1014. var
  1015. s : TCmdStr;
  1016. hl : TSearchPathList;
  1017. hp,hp2 : TCmdStrListItem;
  1018. begin
  1019. if list.empty then
  1020. exit;
  1021. { create temp and reverse the list }
  1022. if addfirst then
  1023. begin
  1024. hl:=TSearchPathList.Create;
  1025. hp:=TCmdStrListItem(list.first);
  1026. while assigned(hp) do
  1027. begin
  1028. hl.insert(hp.Str);
  1029. hp:=TCmdStrListItem(hp.next);
  1030. end;
  1031. while not hl.empty do
  1032. begin
  1033. s:=hl.GetFirst;
  1034. Remove(s);
  1035. Insert(s);
  1036. end;
  1037. hl.Free;
  1038. end
  1039. else
  1040. begin
  1041. hp:=TCmdStrListItem(list.first);
  1042. while assigned(hp) do
  1043. begin
  1044. hp2:=Find(hp.Str);
  1045. { Check if already in path, then we don't add it }
  1046. if not assigned(hp2) then
  1047. Concat(hp.Str);
  1048. hp:=TCmdStrListItem(hp.next);
  1049. end;
  1050. end;
  1051. end;
  1052. function TSearchPathList.FindFile(const f :TCmdStr;allowcache:boolean;var foundfile:TCmdStr):boolean;
  1053. Var
  1054. p : TCmdStrListItem;
  1055. begin
  1056. FindFile:=false;
  1057. p:=TCmdStrListItem(first);
  1058. while assigned(p) do
  1059. begin
  1060. result:=FileExistsNonCase(p.Str,f,allowcache,FoundFile);
  1061. if result then
  1062. exit;
  1063. p:=TCmdStrListItem(p.next);
  1064. end;
  1065. { Return original filename if not found }
  1066. FoundFile:=f;
  1067. end;
  1068. function FindFile(const f : TCmdStr; const path : TCmdStr;allowcache:boolean;var foundfile:TCmdStr):boolean;
  1069. Var
  1070. StartPos, EndPos, L: LongInt;
  1071. begin
  1072. Result:=False;
  1073. StartPos := 1;
  1074. L := Length(Path);
  1075. repeat
  1076. EndPos := StartPos;
  1077. while (EndPos <= L) and ((Path[EndPos] <> PathSeparator) and (Path[EndPos] <> ';')) do
  1078. Inc(EndPos);
  1079. Result := FileExistsNonCase(FixPath(Copy(Path, StartPos, EndPos-StartPos), False), f, allowcache, FoundFile);
  1080. if Result then
  1081. Exit;
  1082. StartPos := EndPos + 1;
  1083. until StartPos > L;
  1084. FoundFile:=f;
  1085. end;
  1086. {
  1087. function FindFilePchar(const f : TCmdStr;path : pchar;allowcache:boolean;var foundfile:TCmdStr):boolean;
  1088. Var
  1089. singlepathstring : TCmdStr;
  1090. startpc,pc : pchar;
  1091. begin
  1092. FindFilePchar:=false;
  1093. if Assigned (Path) then
  1094. begin
  1095. pc:=path;
  1096. repeat
  1097. startpc:=pc;
  1098. while (pc^<>PathSeparator) and (pc^<>';') and (pc^<>#0) do
  1099. inc(pc);
  1100. SetLength(singlepathstring, pc-startpc);
  1101. move(startpc^,singlepathstring[1],pc-startpc);
  1102. singlepathstring:=FixPath(ExpandFileName(singlepathstring),false);
  1103. result:=FileExistsNonCase(singlepathstring,f,allowcache,FoundFile);
  1104. if result then
  1105. exit;
  1106. if (pc^=#0) then
  1107. break;
  1108. inc(pc);
  1109. until false;
  1110. end;
  1111. foundfile:=f;
  1112. end;
  1113. }
  1114. function FindFileInExeLocations(const bin:TCmdStr;allowcache:boolean;var foundfile:TCmdStr):boolean;
  1115. var
  1116. Path : TCmdStr;
  1117. found : boolean;
  1118. begin
  1119. found:=FindFile(FixFileName(bin),exepath,allowcache,foundfile);
  1120. if not found then
  1121. begin
  1122. {$ifdef macos}
  1123. Path:=GetEnvironmentVariable('Commands');
  1124. {$else}
  1125. Path:=GetEnvironmentVariable('PATH');
  1126. {$endif}
  1127. found:=FindFile(FixFileName(bin),Path,allowcache,foundfile);
  1128. end;
  1129. FindFileInExeLocations:=found;
  1130. end;
  1131. function FindExe(const bin:TCmdStr;allowcache:boolean;var foundfile:TCmdStr):boolean;
  1132. begin
  1133. FindExe:=FindFileInExeLocations(ChangeFileExt(bin,source_info.exeext),allowcache,foundfile);
  1134. end;
  1135. function GetShortName(const n:TCmdStr):TCmdStr;
  1136. {$ifdef win32}
  1137. var
  1138. hs,hs2 : TCmdStr;
  1139. i : longint;
  1140. {$endif}
  1141. {$if defined(go32v2) or defined(watcom)}
  1142. var
  1143. hs : shortstring;
  1144. {$endif}
  1145. begin
  1146. GetShortName:=n;
  1147. {$ifdef win32}
  1148. hs:=n+#0;
  1149. { may become longer in case of e.g. ".a" -> "a~1" or so }
  1150. setlength(hs2,length(hs)*2);
  1151. i:=Windows.GetShortPathName(@hs[1],@hs2[1],length(hs)*2);
  1152. if (i>0) and (i<=length(hs)*2) then
  1153. begin
  1154. setlength(hs2,strlen(@hs2[1]));
  1155. GetShortName:=hs2;
  1156. end;
  1157. {$endif}
  1158. {$if defined(go32v2) or defined(watcom)}
  1159. hs:=n;
  1160. if Dos.GetShortName(hs) then
  1161. GetShortName:=hs;
  1162. {$endif}
  1163. end;
  1164. {****************************************************************************
  1165. Init / Done
  1166. ****************************************************************************}
  1167. procedure InitFileUtils;
  1168. begin
  1169. DirCache:=TDirectoryCache.Create;
  1170. end;
  1171. procedure DoneFileUtils;
  1172. begin
  1173. DirCache.Free;
  1174. end;
  1175. end.