cfileutl.pas 39 KB

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