cfileutl.pas 48 KB

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