os.nim 118 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303
  1. #
  2. #
  3. # Nim's Runtime Library
  4. # (c) Copyright 2015 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## This module contains basic operating system facilities like
  10. ## retrieving environment variables, reading command line arguments,
  11. ## working with directories, running shell commands, etc.
  12. ##
  13. ## .. code-block::
  14. ## import os
  15. ##
  16. ## let myFile = "/path/to/my/file.nim"
  17. ##
  18. ## let pathSplit = splitPath(myFile)
  19. ## assert pathSplit.head == "/path/to/my"
  20. ## assert pathSplit.tail == "file.nim"
  21. ##
  22. ## assert parentDir(myFile) == "/path/to/my"
  23. ##
  24. ## let fileSplit = splitFile(myFile)
  25. ## assert fileSplit.dir == "/path/to/my"
  26. ## assert fileSplit.name == "file"
  27. ## assert fileSplit.ext == ".nim"
  28. ##
  29. ## assert myFile.changeFileExt("c") == "/path/to/my/file.c"
  30. ##
  31. ##
  32. ## **See also:**
  33. ## * `osproc module <osproc.html>`_ for process communication beyond
  34. ## `execShellCmd proc <#execShellCmd,string>`_
  35. ## * `parseopt module <parseopt.html>`_ for command-line parser beyond
  36. ## `parseCmdLine proc <#parseCmdLine,string>`_
  37. ## * `uri module <uri.html>`_
  38. ## * `distros module <distros.html>`_
  39. ## * `dynlib module <dynlib.html>`_
  40. ## * `streams module <streams.html>`_
  41. include "system/inclrtl"
  42. import std/private/since
  43. import
  44. strutils, pathnorm
  45. const weirdTarget = defined(nimscript) or defined(js)
  46. since (1, 1):
  47. const
  48. invalidFilenameChars* = {'/', '\\', ':', '*', '?', '"', '<', '>', '|', '^', '\0'} ## \
  49. ## Characters that may produce invalid filenames across Linux, Windows, Mac, etc.
  50. ## You can check if your filename contains these char and strip them for safety.
  51. ## Mac bans ``':'``, Linux bans ``'/'``, Windows bans all others.
  52. invalidFilenames* = [
  53. "CON", "PRN", "AUX", "NUL",
  54. "COM0", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9",
  55. "LPT0", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9"] ## \
  56. ## Filenames that may be invalid across Linux, Windows, Mac, etc.
  57. ## You can check if your filename match these and rename it for safety
  58. ## (Currently all invalid filenames are from Windows only).
  59. when weirdTarget:
  60. discard
  61. elif defined(windows):
  62. import winlean, times
  63. elif defined(posix):
  64. import posix, times
  65. proc toTime(ts: Timespec): times.Time {.inline.} =
  66. result = initTime(ts.tv_sec.int64, ts.tv_nsec.int)
  67. else:
  68. {.error: "OS module not ported to your operating system!".}
  69. when weirdTarget and defined(nimErrorProcCanHaveBody):
  70. {.pragma: noWeirdTarget, error: "this proc is not available on the NimScript/js target".}
  71. else:
  72. {.pragma: noWeirdTarget.}
  73. when defined(nimscript):
  74. # for procs already defined in scriptconfig.nim
  75. template noNimJs(body): untyped = discard
  76. elif defined(js):
  77. {.pragma: noNimJs, error: "this proc is not available on the js target".}
  78. else:
  79. {.pragma: noNimJs.}
  80. proc normalizePathAux(path: var string){.inline, raises: [], noSideEffect.}
  81. type
  82. ReadEnvEffect* = object of ReadIOEffect ## Effect that denotes a read
  83. ## from an environment variable.
  84. WriteEnvEffect* = object of WriteIOEffect ## Effect that denotes a write
  85. ## to an environment variable.
  86. ReadDirEffect* = object of ReadIOEffect ## Effect that denotes a read
  87. ## operation from the directory
  88. ## structure.
  89. WriteDirEffect* = object of WriteIOEffect ## Effect that denotes a write
  90. ## operation to
  91. ## the directory structure.
  92. OSErrorCode* = distinct int32 ## Specifies an OS Error Code.
  93. include "includes/osseps"
  94. proc absolutePathInternal(path: string): string {.gcsafe.}
  95. proc normalizePathEnd(path: var string, trailingSep = false) =
  96. ## Ensures ``path`` has exactly 0 or 1 trailing `DirSep`, depending on
  97. ## ``trailingSep``, and taking care of edge cases: it preservers whether
  98. ## a path is absolute or relative, and makes sure trailing sep is `DirSep`,
  99. ## not `AltSep`. Trailing `/.` are compressed, see examples.
  100. if path.len == 0: return
  101. var i = path.len
  102. while i >= 1:
  103. if path[i-1] in {DirSep, AltSep}: dec(i)
  104. elif path[i-1] == '.' and i >= 2 and path[i-2] in {DirSep, AltSep}: dec(i)
  105. else: break
  106. if trailingSep:
  107. # foo// => foo
  108. path.setLen(i)
  109. # foo => foo/
  110. path.add DirSep
  111. elif i > 0:
  112. # foo// => foo
  113. path.setLen(i)
  114. else:
  115. # // => / (empty case was already taken care of)
  116. path = $DirSep
  117. proc normalizePathEnd(path: string, trailingSep = false): string =
  118. ## outplace overload
  119. runnableExamples:
  120. when defined(posix):
  121. assert normalizePathEnd("/lib//.//", trailingSep = true) == "/lib/"
  122. assert normalizePathEnd("lib/./.", trailingSep = false) == "lib"
  123. assert normalizePathEnd(".//./.", trailingSep = false) == "."
  124. assert normalizePathEnd("", trailingSep = true) == "" # not / !
  125. assert normalizePathEnd("/", trailingSep = false) == "/" # not "" !
  126. result = path
  127. result.normalizePathEnd(trailingSep)
  128. since((1, 1)):
  129. export normalizePathEnd
  130. template endsWith(a: string, b: set[char]): bool =
  131. a.len > 0 and a[^1] in b
  132. proc joinPathImpl(result: var string, state: var int, tail: string) =
  133. let trailingSep = tail.endsWith({DirSep, AltSep}) or tail.len == 0 and result.endsWith({DirSep, AltSep})
  134. normalizePathEnd(result, trailingSep=false)
  135. addNormalizePath(tail, result, state, DirSep)
  136. normalizePathEnd(result, trailingSep=trailingSep)
  137. proc joinPath*(head, tail: string): string {.
  138. noSideEffect, rtl, extern: "nos$1".} =
  139. ## Joins two directory names to one.
  140. ##
  141. ## returns normalized path concatenation of `head` and `tail`, preserving
  142. ## whether or not `tail` has a trailing slash (or, if tail if empty, whether
  143. ## head has one).
  144. ##
  145. ## See also:
  146. ## * `joinPath(varargs) proc <#joinPath,varargs[string]>`_
  147. ## * `/ proc <#/,string,string>`_
  148. ## * `splitPath proc <#splitPath,string>`_
  149. ## * `uri.combine proc <uri.html#combine,Uri,Uri>`_
  150. ## * `uri./ proc <uri.html#/,Uri,string>`_
  151. runnableExamples:
  152. when defined(posix):
  153. assert joinPath("usr", "lib") == "usr/lib"
  154. assert joinPath("usr", "lib/") == "usr/lib/"
  155. assert joinPath("usr", "") == "usr"
  156. assert joinPath("usr/", "") == "usr/"
  157. assert joinPath("", "") == ""
  158. assert joinPath("", "lib") == "lib"
  159. assert joinPath("", "/lib") == "/lib"
  160. assert joinPath("usr/", "/lib") == "usr/lib"
  161. assert joinPath("usr/lib", "../bin") == "usr/bin"
  162. result = newStringOfCap(head.len + tail.len)
  163. var state = 0
  164. joinPathImpl(result, state, head)
  165. joinPathImpl(result, state, tail)
  166. when false:
  167. if len(head) == 0:
  168. result = tail
  169. elif head[len(head)-1] in {DirSep, AltSep}:
  170. if tail.len > 0 and tail[0] in {DirSep, AltSep}:
  171. result = head & substr(tail, 1)
  172. else:
  173. result = head & tail
  174. else:
  175. if tail.len > 0 and tail[0] in {DirSep, AltSep}:
  176. result = head & tail
  177. else:
  178. result = head & DirSep & tail
  179. proc joinPath*(parts: varargs[string]): string {.noSideEffect,
  180. rtl, extern: "nos$1OpenArray".} =
  181. ## The same as `joinPath(head, tail) proc <#joinPath,string,string>`_,
  182. ## but works with any number of directory parts.
  183. ##
  184. ## You need to pass at least one element or the proc
  185. ## will assert in debug builds and crash on release builds.
  186. ##
  187. ## See also:
  188. ## * `joinPath(head, tail) proc <#joinPath,string,string>`_
  189. ## * `/ proc <#/,string,string>`_
  190. ## * `/../ proc <#/../,string,string>`_
  191. ## * `splitPath proc <#splitPath,string>`_
  192. runnableExamples:
  193. when defined(posix):
  194. assert joinPath("a") == "a"
  195. assert joinPath("a", "b", "c") == "a/b/c"
  196. assert joinPath("usr/lib", "../../var", "log") == "var/log"
  197. var estimatedLen = 0
  198. for p in parts: estimatedLen += p.len
  199. result = newStringOfCap(estimatedLen)
  200. var state = 0
  201. for i in 0..high(parts):
  202. joinPathImpl(result, state, parts[i])
  203. proc `/`*(head, tail: string): string {.noSideEffect.} =
  204. ## The same as `joinPath(head, tail) proc <#joinPath,string,string>`_.
  205. ##
  206. ## See also:
  207. ## * `/../ proc <#/../,string,string>`_
  208. ## * `joinPath(head, tail) proc <#joinPath,string,string>`_
  209. ## * `joinPath(varargs) proc <#joinPath,varargs[string]>`_
  210. ## * `splitPath proc <#splitPath,string>`_
  211. ## * `uri.combine proc <uri.html#combine,Uri,Uri>`_
  212. ## * `uri./ proc <uri.html#/,Uri,string>`_
  213. runnableExamples:
  214. when defined(posix):
  215. assert "usr" / "" == "usr"
  216. assert "" / "lib" == "lib"
  217. assert "" / "/lib" == "/lib"
  218. assert "usr/" / "/lib/" == "usr/lib/"
  219. assert "usr" / "lib" / "../bin" == "usr/bin"
  220. return joinPath(head, tail)
  221. proc splitPath*(path: string): tuple[head, tail: string] {.
  222. noSideEffect, rtl, extern: "nos$1".} =
  223. ## Splits a directory into `(head, tail)` tuple, so that
  224. ## ``head / tail == path`` (except for edge cases like "/usr").
  225. ##
  226. ## See also:
  227. ## * `joinPath(head, tail) proc <#joinPath,string,string>`_
  228. ## * `joinPath(varargs) proc <#joinPath,varargs[string]>`_
  229. ## * `/ proc <#/,string,string>`_
  230. ## * `/../ proc <#/../,string,string>`_
  231. ## * `relativePath proc <#relativePath,string,string>`_
  232. runnableExamples:
  233. assert splitPath("usr/local/bin") == ("usr/local", "bin")
  234. assert splitPath("usr/local/bin/") == ("usr/local/bin", "")
  235. assert splitPath("/bin/") == ("/bin", "")
  236. when (NimMajor, NimMinor) <= (1, 0):
  237. assert splitPath("/bin") == ("", "bin")
  238. else:
  239. assert splitPath("/bin") == ("/", "bin")
  240. assert splitPath("bin") == ("", "bin")
  241. assert splitPath("") == ("", "")
  242. var sepPos = -1
  243. for i in countdown(len(path)-1, 0):
  244. if path[i] in {DirSep, AltSep}:
  245. sepPos = i
  246. break
  247. if sepPos >= 0:
  248. result.head = substr(path, 0,
  249. when (NimMajor, NimMinor) <= (1, 0):
  250. sepPos-1
  251. else:
  252. if likely(sepPos >= 1): sepPos-1 else: 0
  253. )
  254. result.tail = substr(path, sepPos+1)
  255. else:
  256. result.head = ""
  257. result.tail = path
  258. proc isAbsolute*(path: string): bool {.rtl, noSideEffect, extern: "nos$1", raises: [].} =
  259. ## Checks whether a given `path` is absolute.
  260. ##
  261. ## On Windows, network paths are considered absolute too.
  262. runnableExamples:
  263. assert not "".isAbsolute
  264. assert not ".".isAbsolute
  265. when defined(posix):
  266. assert "/".isAbsolute
  267. assert not "a/".isAbsolute
  268. assert "/a/".isAbsolute
  269. if len(path) == 0: return false
  270. when doslikeFileSystem:
  271. var len = len(path)
  272. result = (path[0] in {'/', '\\'}) or
  273. (len > 1 and path[0] in {'a'..'z', 'A'..'Z'} and path[1] == ':')
  274. elif defined(macos):
  275. # according to https://perldoc.perl.org/File/Spec/Mac.html `:a` is a relative path
  276. result = path[0] != ':'
  277. elif defined(RISCOS):
  278. result = path[0] == '$'
  279. elif defined(posix) or defined(js):
  280. # `or defined(js)` wouldn't be needed pending https://github.com/nim-lang/Nim/issues/13469
  281. # This works around the problem for posix, but windows is still broken with nim js -d:nodejs
  282. result = path[0] == '/'
  283. else:
  284. doAssert false # if ever hits here, adapt as needed
  285. when FileSystemCaseSensitive:
  286. template `!=?`(a, b: char): bool = a != b
  287. else:
  288. template `!=?`(a, b: char): bool = toLowerAscii(a) != toLowerAscii(b)
  289. when doslikeFileSystem:
  290. proc isAbsFromCurrentDrive(path: string): bool {.noSideEffect, raises: []} =
  291. ## An absolute path from the root of the current drive (e.g. "\foo")
  292. path.len > 0 and
  293. (path[0] == AltSep or
  294. (path[0] == DirSep and
  295. (path.len == 1 or path[1] notin {DirSep, AltSep, ':'})))
  296. proc isUNCPrefix(path: string): bool {.noSideEffect, raises: []} =
  297. path[0] == DirSep and path[1] == DirSep
  298. proc sameRoot(path1, path2: string): bool {.noSideEffect, raises: []} =
  299. ## Return true if path1 and path2 have a same root.
  300. ##
  301. ## Detail of windows path formats:
  302. ## https://docs.microsoft.com/en-us/dotnet/standard/io/file-path-formats
  303. assert(isAbsolute(path1))
  304. assert(isAbsolute(path2))
  305. let
  306. len1 = path1.len
  307. len2 = path2.len
  308. assert(len1 != 0 and len2 != 0)
  309. if isAbsFromCurrentDrive(path1) and isAbsFromCurrentDrive(path2):
  310. return true
  311. elif len1 == 1 or len2 == 1:
  312. return false
  313. else:
  314. if path1[1] == ':' and path2[1] == ':':
  315. return path1[0].toLowerAscii() == path2[0].toLowerAscii()
  316. else:
  317. var
  318. p1, p2: PathIter
  319. pp1 = next(p1, path1)
  320. pp2 = next(p2, path2)
  321. if pp1[1] - pp1[0] == 1 and pp2[1] - pp2[0] == 1 and
  322. isUNCPrefix(path1) and isUNCPrefix(path2):
  323. #UNC
  324. var h = 0
  325. while p1.hasNext(path1) and p2.hasNext(path2) and h < 2:
  326. pp1 = next(p1, path1)
  327. pp2 = next(p2, path2)
  328. let diff = pp1[1] - pp1[0]
  329. if diff != pp2[1] - pp2[0]:
  330. return false
  331. for i in 0..diff:
  332. if path1[i + pp1[0]] !=? path2[i + pp2[0]]:
  333. return false
  334. inc h
  335. return h == 2
  336. else:
  337. return false
  338. proc relativePath*(path, base: string, sep = DirSep): string {.
  339. rtl, extern: "nos$1".} =
  340. ## Converts `path` to a path relative to `base`.
  341. ##
  342. ## The `sep` (default: `DirSep <#DirSep>`_) is used for the path normalizations,
  343. ## this can be useful to ensure the relative path only contains `'/'`
  344. ## so that it can be used for URL constructions.
  345. ##
  346. ## On windows, if a root of `path` and a root of `base` are different,
  347. ## returns `path` as is because it is impossible to make a relative path.
  348. ## That means an absolute path can be returned.
  349. ##
  350. ## See also:
  351. ## * `splitPath proc <#splitPath,string>`_
  352. ## * `parentDir proc <#parentDir,string>`_
  353. ## * `tailDir proc <#tailDir,string>`_
  354. runnableExamples:
  355. assert relativePath("/Users/me/bar/z.nim", "/Users/other/bad", '/') == "../../me/bar/z.nim"
  356. assert relativePath("/Users/me/bar/z.nim", "/Users/other", '/') == "../me/bar/z.nim"
  357. assert relativePath("/Users///me/bar//z.nim", "//Users/", '/') == "me/bar/z.nim"
  358. assert relativePath("/Users/me/bar/z.nim", "/Users/me", '/') == "bar/z.nim"
  359. assert relativePath("", "/users/moo", '/') == ""
  360. assert relativePath("foo", ".", '/') == "foo"
  361. assert relativePath("foo", "foo", '/') == "."
  362. if path.len == 0: return ""
  363. var base = if base == ".": "" else: base
  364. var path = path
  365. path.normalizePathAux
  366. base.normalizePathAux
  367. let a1 = isAbsolute(path)
  368. let a2 = isAbsolute(base)
  369. if a1 and not a2:
  370. base = absolutePathInternal(base)
  371. elif a2 and not a1:
  372. path = absolutePathInternal(path)
  373. when doslikeFileSystem:
  374. if isAbsolute(path) and isAbsolute(base):
  375. if not sameRoot(path, base):
  376. return path
  377. var f = default PathIter
  378. var b = default PathIter
  379. var ff = (0, -1)
  380. var bb = (0, -1) # (int, int)
  381. result = newStringOfCap(path.len)
  382. # skip the common prefix:
  383. while f.hasNext(path) and b.hasNext(base):
  384. ff = next(f, path)
  385. bb = next(b, base)
  386. let diff = ff[1] - ff[0]
  387. if diff != bb[1] - bb[0]: break
  388. var same = true
  389. for i in 0..diff:
  390. if path[i + ff[0]] !=? base[i + bb[0]]:
  391. same = false
  392. break
  393. if not same: break
  394. ff = (0, -1)
  395. bb = (0, -1)
  396. # for i in 0..diff:
  397. # result.add base[i + bb[0]]
  398. # /foo/bar/xxx/ -- base
  399. # /foo/bar/baz -- path path
  400. # ../baz
  401. # every directory that is in 'base', needs to add '..'
  402. while true:
  403. if bb[1] >= bb[0]:
  404. if result.len > 0 and result[^1] != sep:
  405. result.add sep
  406. result.add ".."
  407. if not b.hasNext(base): break
  408. bb = b.next(base)
  409. # add the rest of 'path':
  410. while true:
  411. if ff[1] >= ff[0]:
  412. if result.len > 0 and result[^1] != sep:
  413. result.add sep
  414. for i in 0..ff[1] - ff[0]:
  415. result.add path[i + ff[0]]
  416. if not f.hasNext(path): break
  417. ff = f.next(path)
  418. when not defined(nimOldRelativePathBehavior):
  419. if result.len == 0: result.add "."
  420. proc isRelativeTo*(path: string, base: string): bool {.since: (1, 1).} =
  421. ## Returns true if `path` is relative to `base`.
  422. runnableExamples:
  423. doAssert isRelativeTo("./foo//bar", "foo")
  424. doAssert isRelativeTo("foo/bar", ".")
  425. doAssert isRelativeTo("/foo/bar.nim", "/foo/bar.nim")
  426. doAssert not isRelativeTo("foo/bar.nims", "foo/bar.nim")
  427. let path = path.normalizePath
  428. let base = base.normalizePath
  429. let ret = relativePath(path, base)
  430. result = path.len > 0 and not ret.startsWith ".."
  431. proc parentDirPos(path: string): int =
  432. var q = 1
  433. if len(path) >= 1 and path[len(path)-1] in {DirSep, AltSep}: q = 2
  434. for i in countdown(len(path)-q, 0):
  435. if path[i] in {DirSep, AltSep}: return i
  436. result = -1
  437. proc parentDir*(path: string): string {.
  438. noSideEffect, rtl, extern: "nos$1".} =
  439. ## Returns the parent directory of `path`.
  440. ##
  441. ## This is similar to ``splitPath(path).head`` when ``path`` doesn't end
  442. ## in a dir separator, but also takes care of path normalizations.
  443. ## The remainder can be obtained with `lastPathPart(path) proc
  444. ## <#lastPathPart,string>`_.
  445. ##
  446. ## See also:
  447. ## * `relativePath proc <#relativePath,string,string>`_
  448. ## * `splitPath proc <#splitPath,string>`_
  449. ## * `tailDir proc <#tailDir,string>`_
  450. ## * `parentDirs iterator <#parentDirs.i,string>`_
  451. runnableExamples:
  452. assert parentDir("") == ""
  453. when defined(posix):
  454. assert parentDir("/usr/local/bin") == "/usr/local"
  455. assert parentDir("foo/bar//") == "foo"
  456. assert parentDir("//foo//bar//.") == "/foo"
  457. assert parentDir("./foo") == "."
  458. assert parentDir("/./foo//./") == "/"
  459. assert parentDir("a//./") == "."
  460. assert parentDir("a/b/c/..") == "a"
  461. result = pathnorm.normalizePath(path)
  462. var sepPos = parentDirPos(result)
  463. if sepPos >= 0:
  464. result = substr(result, 0, sepPos)
  465. normalizePathEnd(result)
  466. elif result == ".." or result == "." or result.len == 0 or result[^1] in {DirSep, AltSep}:
  467. # `.` => `..` and .. => `../..`(etc) would be a sensible alternative
  468. # `/` => `/` (as done with splitFile) would be a sensible alternative
  469. result = ""
  470. else:
  471. result = "."
  472. proc tailDir*(path: string): string {.
  473. noSideEffect, rtl, extern: "nos$1".} =
  474. ## Returns the tail part of `path`.
  475. ##
  476. ## See also:
  477. ## * `relativePath proc <#relativePath,string,string>`_
  478. ## * `splitPath proc <#splitPath,string>`_
  479. ## * `parentDir proc <#parentDir,string>`_
  480. runnableExamples:
  481. assert tailDir("/bin") == "bin"
  482. assert tailDir("bin") == ""
  483. assert tailDir("bin/") == ""
  484. assert tailDir("/usr/local/bin") == "usr/local/bin"
  485. assert tailDir("//usr//local//bin//") == "usr//local//bin//"
  486. assert tailDir("./usr/local/bin") == "usr/local/bin"
  487. assert tailDir("usr/local/bin") == "local/bin"
  488. var i = 0
  489. while i < len(path):
  490. if path[i] in {DirSep, AltSep}:
  491. while i < len(path) and path[i] in {DirSep, AltSep}: inc i
  492. return substr(path, i)
  493. inc i
  494. result = ""
  495. proc isRootDir*(path: string): bool {.
  496. noSideEffect, rtl, extern: "nos$1".} =
  497. ## Checks whether a given `path` is a root directory.
  498. runnableExamples:
  499. assert isRootDir("")
  500. assert isRootDir(".")
  501. assert isRootDir("/")
  502. assert isRootDir("a")
  503. assert not isRootDir("/a")
  504. assert not isRootDir("a/b/c")
  505. result = parentDirPos(path) < 0
  506. iterator parentDirs*(path: string, fromRoot=false, inclusive=true): string =
  507. ## Walks over all parent directories of a given `path`.
  508. ##
  509. ## If `fromRoot` is true (default: false), the traversal will start from
  510. ## the file system root directory.
  511. ## If `inclusive` is true (default), the original argument will be included
  512. ## in the traversal.
  513. ##
  514. ## Relative paths won't be expanded by this iterator. Instead, it will traverse
  515. ## only the directories appearing in the relative path.
  516. ##
  517. ## See also:
  518. ## * `parentDir proc <#parentDir,string>`_
  519. ##
  520. ## **Examples:**
  521. ##
  522. ## .. code-block::
  523. ## let g = "a/b/c"
  524. ##
  525. ## for p in g.parentDirs:
  526. ## echo p
  527. ## # a/b/c
  528. ## # a/b
  529. ## # a
  530. ##
  531. ## for p in g.parentDirs(fromRoot=true):
  532. ## echo p
  533. ## # a/
  534. ## # a/b/
  535. ## # a/b/c
  536. ##
  537. ## for p in g.parentDirs(inclusive=false):
  538. ## echo p
  539. ## # a/b
  540. ## # a
  541. if not fromRoot:
  542. var current = path
  543. if inclusive: yield path
  544. while true:
  545. if current.isRootDir: break
  546. current = current.parentDir
  547. yield current
  548. else:
  549. for i in countup(0, path.len - 2): # ignore the last /
  550. # deal with non-normalized paths such as /foo//bar//baz
  551. if path[i] in {DirSep, AltSep} and
  552. (i == 0 or path[i-1] notin {DirSep, AltSep}):
  553. yield path.substr(0, i)
  554. if inclusive: yield path
  555. proc `/../`*(head, tail: string): string {.noSideEffect.} =
  556. ## The same as ``parentDir(head) / tail``, unless there is no parent
  557. ## directory. Then ``head / tail`` is performed instead.
  558. ##
  559. ## See also:
  560. ## * `/ proc <#/,string,string>`_
  561. ## * `parentDir proc <#parentDir,string>`_
  562. runnableExamples:
  563. when defined(posix):
  564. assert "a/b/c" /../ "d/e" == "a/b/d/e"
  565. assert "a" /../ "d/e" == "a/d/e"
  566. let sepPos = parentDirPos(head)
  567. if sepPos >= 0:
  568. result = substr(head, 0, sepPos-1) / tail
  569. else:
  570. result = head / tail
  571. proc normExt(ext: string): string =
  572. if ext == "" or ext[0] == ExtSep: result = ext # no copy needed here
  573. else: result = ExtSep & ext
  574. proc searchExtPos*(path: string): int =
  575. ## Returns index of the `'.'` char in `path` if it signifies the beginning
  576. ## of extension. Returns -1 otherwise.
  577. ##
  578. ## See also:
  579. ## * `splitFile proc <#splitFile,string>`_
  580. ## * `extractFilename proc <#extractFilename,string>`_
  581. ## * `lastPathPart proc <#lastPathPart,string>`_
  582. ## * `changeFileExt proc <#changeFileExt,string,string>`_
  583. ## * `addFileExt proc <#addFileExt,string,string>`_
  584. runnableExamples:
  585. assert searchExtPos("a/b/c") == -1
  586. assert searchExtPos("c.nim") == 1
  587. assert searchExtPos("a/b/c.nim") == 5
  588. assert searchExtPos("a.b.c.nim") == 5
  589. # BUGFIX: do not search until 0! .DS_Store is no file extension!
  590. result = -1
  591. for i in countdown(len(path)-1, 1):
  592. if path[i] == ExtSep:
  593. result = i
  594. break
  595. elif path[i] in {DirSep, AltSep}:
  596. break # do not skip over path
  597. proc splitFile*(path: string): tuple[dir, name, ext: string] {.
  598. noSideEffect, rtl, extern: "nos$1".} =
  599. ## Splits a filename into `(dir, name, extension)` tuple.
  600. ##
  601. ## `dir` does not end in `DirSep <#DirSep>`_ unless it's `/`.
  602. ## `extension` includes the leading dot.
  603. ##
  604. ## If `path` has no extension, `ext` is the empty string.
  605. ## If `path` has no directory component, `dir` is the empty string.
  606. ## If `path` has no filename component, `name` and `ext` are empty strings.
  607. ##
  608. ## See also:
  609. ## * `searchExtPos proc <#searchExtPos,string>`_
  610. ## * `extractFilename proc <#extractFilename,string>`_
  611. ## * `lastPathPart proc <#lastPathPart,string>`_
  612. ## * `changeFileExt proc <#changeFileExt,string,string>`_
  613. ## * `addFileExt proc <#addFileExt,string,string>`_
  614. runnableExamples:
  615. var (dir, name, ext) = splitFile("usr/local/nimc.html")
  616. assert dir == "usr/local"
  617. assert name == "nimc"
  618. assert ext == ".html"
  619. (dir, name, ext) = splitFile("/usr/local/os")
  620. assert dir == "/usr/local"
  621. assert name == "os"
  622. assert ext == ""
  623. (dir, name, ext) = splitFile("/usr/local/")
  624. assert dir == "/usr/local"
  625. assert name == ""
  626. assert ext == ""
  627. (dir, name, ext) = splitFile("/tmp.txt")
  628. assert dir == "/"
  629. assert name == "tmp"
  630. assert ext == ".txt"
  631. var namePos = 0
  632. var dotPos = 0
  633. for i in countdown(len(path) - 1, 0):
  634. if path[i] in {DirSep, AltSep} or i == 0:
  635. if path[i] in {DirSep, AltSep}:
  636. result.dir = substr(path, 0, if likely(i >= 1): i - 1 else: 0)
  637. namePos = i + 1
  638. if dotPos > i:
  639. result.name = substr(path, namePos, dotPos - 1)
  640. result.ext = substr(path, dotPos)
  641. else:
  642. result.name = substr(path, namePos)
  643. break
  644. elif path[i] == ExtSep and i > 0 and i < len(path) - 1 and
  645. path[i - 1] notin {DirSep, AltSep} and
  646. path[i + 1] != ExtSep and dotPos == 0:
  647. dotPos = i
  648. proc extractFilename*(path: string): string {.
  649. noSideEffect, rtl, extern: "nos$1".} =
  650. ## Extracts the filename of a given `path`.
  651. ##
  652. ## This is the same as ``name & ext`` from `splitFile(path) proc
  653. ## <#splitFile,string>`_.
  654. ##
  655. ## See also:
  656. ## * `searchExtPos proc <#searchExtPos,string>`_
  657. ## * `splitFile proc <#splitFile,string>`_
  658. ## * `lastPathPart proc <#lastPathPart,string>`_
  659. ## * `changeFileExt proc <#changeFileExt,string,string>`_
  660. ## * `addFileExt proc <#addFileExt,string,string>`_
  661. runnableExamples:
  662. assert extractFilename("foo/bar/") == ""
  663. assert extractFilename("foo/bar") == "bar"
  664. assert extractFilename("foo/bar.baz") == "bar.baz"
  665. if path.len == 0 or path[path.len-1] in {DirSep, AltSep}:
  666. result = ""
  667. else:
  668. result = splitPath(path).tail
  669. proc lastPathPart*(path: string): string {.
  670. noSideEffect, rtl, extern: "nos$1".} =
  671. ## Like `extractFilename proc <#extractFilename,string>`_, but ignores
  672. ## trailing dir separator; aka: `baseName`:idx: in some other languages.
  673. ##
  674. ## See also:
  675. ## * `searchExtPos proc <#searchExtPos,string>`_
  676. ## * `splitFile proc <#splitFile,string>`_
  677. ## * `extractFilename proc <#extractFilename,string>`_
  678. ## * `changeFileExt proc <#changeFileExt,string,string>`_
  679. ## * `addFileExt proc <#addFileExt,string,string>`_
  680. runnableExamples:
  681. assert lastPathPart("foo/bar/") == "bar"
  682. assert lastPathPart("foo/bar") == "bar"
  683. let path = path.normalizePathEnd(trailingSep = false)
  684. result = extractFilename(path)
  685. proc changeFileExt*(filename, ext: string): string {.
  686. noSideEffect, rtl, extern: "nos$1".} =
  687. ## Changes the file extension to `ext`.
  688. ##
  689. ## If the `filename` has no extension, `ext` will be added.
  690. ## If `ext` == "" then any extension is removed.
  691. ##
  692. ## `Ext` should be given without the leading `'.'`, because some
  693. ## filesystems may use a different character. (Although I know
  694. ## of none such beast.)
  695. ##
  696. ## See also:
  697. ## * `searchExtPos proc <#searchExtPos,string>`_
  698. ## * `splitFile proc <#splitFile,string>`_
  699. ## * `extractFilename proc <#extractFilename,string>`_
  700. ## * `lastPathPart proc <#lastPathPart,string>`_
  701. ## * `addFileExt proc <#addFileExt,string,string>`_
  702. runnableExamples:
  703. assert changeFileExt("foo.bar", "baz") == "foo.baz"
  704. assert changeFileExt("foo.bar", "") == "foo"
  705. assert changeFileExt("foo", "baz") == "foo.baz"
  706. var extPos = searchExtPos(filename)
  707. if extPos < 0: result = filename & normExt(ext)
  708. else: result = substr(filename, 0, extPos-1) & normExt(ext)
  709. proc addFileExt*(filename, ext: string): string {.
  710. noSideEffect, rtl, extern: "nos$1".} =
  711. ## Adds the file extension `ext` to `filename`, unless
  712. ## `filename` already has an extension.
  713. ##
  714. ## `Ext` should be given without the leading `'.'`, because some
  715. ## filesystems may use a different character.
  716. ## (Although I know of none such beast.)
  717. ##
  718. ## See also:
  719. ## * `searchExtPos proc <#searchExtPos,string>`_
  720. ## * `splitFile proc <#splitFile,string>`_
  721. ## * `extractFilename proc <#extractFilename,string>`_
  722. ## * `lastPathPart proc <#lastPathPart,string>`_
  723. ## * `changeFileExt proc <#changeFileExt,string,string>`_
  724. runnableExamples:
  725. assert addFileExt("foo.bar", "baz") == "foo.bar"
  726. assert addFileExt("foo.bar", "") == "foo.bar"
  727. assert addFileExt("foo", "baz") == "foo.baz"
  728. var extPos = searchExtPos(filename)
  729. if extPos < 0: result = filename & normExt(ext)
  730. else: result = filename
  731. proc cmpPaths*(pathA, pathB: string): int {.
  732. noSideEffect, rtl, extern: "nos$1".} =
  733. ## Compares two paths.
  734. ##
  735. ## On a case-sensitive filesystem this is done
  736. ## case-sensitively otherwise case-insensitively. Returns:
  737. ##
  738. ## | 0 if pathA == pathB
  739. ## | < 0 if pathA < pathB
  740. ## | > 0 if pathA > pathB
  741. runnableExamples:
  742. when defined(macosx):
  743. assert cmpPaths("foo", "Foo") == 0
  744. elif defined(posix):
  745. assert cmpPaths("foo", "Foo") > 0
  746. let a = normalizePath(pathA)
  747. let b = normalizePath(pathB)
  748. if FileSystemCaseSensitive:
  749. result = cmp(a, b)
  750. else:
  751. when defined(nimscript):
  752. result = cmpic(a, b)
  753. elif defined(nimdoc): discard
  754. else:
  755. result = cmpIgnoreCase(a, b)
  756. proc unixToNativePath*(path: string, drive=""): string {.
  757. noSideEffect, rtl, extern: "nos$1".} =
  758. ## Converts an UNIX-like path to a native one.
  759. ##
  760. ## On an UNIX system this does nothing. Else it converts
  761. ## `'/'`, `'.'`, `'..'` to the appropriate things.
  762. ##
  763. ## On systems with a concept of "drives", `drive` is used to determine
  764. ## which drive label to use during absolute path conversion.
  765. ## `drive` defaults to the drive of the current working directory, and is
  766. ## ignored on systems that do not have a concept of "drives".
  767. when defined(unix):
  768. result = path
  769. else:
  770. if path.len == 0: return ""
  771. var start: int
  772. if path[0] == '/':
  773. # an absolute path
  774. when doslikeFileSystem:
  775. if drive != "":
  776. result = drive & ":" & DirSep
  777. else:
  778. result = $DirSep
  779. elif defined(macos):
  780. result = "" # must not start with ':'
  781. else:
  782. result = $DirSep
  783. start = 1
  784. elif path[0] == '.' and (path.len == 1 or path[1] == '/'):
  785. # current directory
  786. result = $CurDir
  787. start = when doslikeFileSystem: 1 else: 2
  788. else:
  789. result = ""
  790. start = 0
  791. var i = start
  792. while i < len(path): # ../../../ --> ::::
  793. if i+2 < path.len and path[i] == '.' and path[i+1] == '.' and path[i+2] == '/':
  794. # parent directory
  795. when defined(macos):
  796. if result[high(result)] == ':':
  797. add result, ':'
  798. else:
  799. add result, ParDir
  800. else:
  801. add result, ParDir & DirSep
  802. inc(i, 3)
  803. elif path[i] == '/':
  804. add result, DirSep
  805. inc(i)
  806. else:
  807. add result, path[i]
  808. inc(i)
  809. include "includes/oserr"
  810. when not defined(nimscript):
  811. include "includes/osenv"
  812. proc getHomeDir*(): string {.rtl, extern: "nos$1",
  813. tags: [ReadEnvEffect, ReadIOEffect].} =
  814. ## Returns the home directory of the current user.
  815. ##
  816. ## This proc is wrapped by the `expandTilde proc <#expandTilde,string>`_
  817. ## for the convenience of processing paths coming from user configuration files.
  818. ##
  819. ## See also:
  820. ## * `getConfigDir proc <#getConfigDir>`_
  821. ## * `getTempDir proc <#getTempDir>`_
  822. ## * `expandTilde proc <#expandTilde,string>`_
  823. ## * `getCurrentDir proc <#getCurrentDir>`_
  824. ## * `setCurrentDir proc <#setCurrentDir,string>`_
  825. runnableExamples:
  826. assert getHomeDir() == expandTilde("~")
  827. when defined(windows): return string(getEnv("USERPROFILE")) & "\\"
  828. else: return string(getEnv("HOME")) & "/"
  829. proc getConfigDir*(): string {.rtl, extern: "nos$1",
  830. tags: [ReadEnvEffect, ReadIOEffect].} =
  831. ## Returns the config directory of the current user for applications.
  832. ##
  833. ## On non-Windows OSs, this proc conforms to the XDG Base Directory
  834. ## spec. Thus, this proc returns the value of the `XDG_CONFIG_HOME` environment
  835. ## variable if it is set, otherwise it returns the default configuration
  836. ## directory ("~/.config/").
  837. ##
  838. ## An OS-dependent trailing slash is always present at the end of the
  839. ## returned string: `\\` on Windows and `/` on all other OSs.
  840. ##
  841. ## See also:
  842. ## * `getHomeDir proc <#getHomeDir>`_
  843. ## * `getTempDir proc <#getTempDir>`_
  844. ## * `expandTilde proc <#expandTilde,string>`_
  845. ## * `getCurrentDir proc <#getCurrentDir>`_
  846. ## * `setCurrentDir proc <#setCurrentDir,string>`_
  847. when defined(windows):
  848. result = getEnv("APPDATA").string
  849. else:
  850. result = getEnv("XDG_CONFIG_HOME", getEnv("HOME").string / ".config").string
  851. result.normalizePathEnd(trailingSep = true)
  852. proc getTempDir*(): string {.rtl, extern: "nos$1",
  853. tags: [ReadEnvEffect, ReadIOEffect].} =
  854. ## Returns the temporary directory of the current user for applications to
  855. ## save temporary files in.
  856. ##
  857. ## **Please do not use this**: On Android, it currently
  858. ## returns ``getHomeDir()``, and on other Unix based systems it can cause
  859. ## security problems too. That said, you can override this implementation
  860. ## by adding ``-d:tempDir=mytempname`` to your compiler invocation.
  861. ##
  862. ## See also:
  863. ## * `getHomeDir proc <#getHomeDir>`_
  864. ## * `getConfigDir proc <#getConfigDir>`_
  865. ## * `expandTilde proc <#expandTilde,string>`_
  866. ## * `getCurrentDir proc <#getCurrentDir>`_
  867. ## * `setCurrentDir proc <#setCurrentDir,string>`_
  868. const tempDirDefault = "/tmp"
  869. result = tempDirDefault
  870. when defined(tempDir):
  871. const tempDir {.strdefine.}: string = tempDirDefault
  872. result = tempDir
  873. elif defined(windows): result = string(getEnv("TEMP"))
  874. elif defined(android): result = getHomeDir()
  875. else:
  876. if existsEnv("TMPDIR"): result = string(getEnv("TMPDIR"))
  877. normalizePathEnd(result, trailingSep=true)
  878. proc expandTilde*(path: string): string {.
  879. tags: [ReadEnvEffect, ReadIOEffect].} =
  880. ## Expands ``~`` or a path starting with ``~/`` to a full path, replacing
  881. ## ``~`` with `getHomeDir() <#getHomeDir>`_ (otherwise returns ``path`` unmodified).
  882. ##
  883. ## Windows: this is still supported despite Windows platform not having this
  884. ## convention; also, both ``~/`` and ``~\`` are handled.
  885. ##
  886. ## See also:
  887. ## * `getHomeDir proc <#getHomeDir>`_
  888. ## * `getConfigDir proc <#getConfigDir>`_
  889. ## * `getTempDir proc <#getTempDir>`_
  890. ## * `getCurrentDir proc <#getCurrentDir>`_
  891. ## * `setCurrentDir proc <#setCurrentDir,string>`_
  892. runnableExamples:
  893. assert expandTilde("~" / "appname.cfg") == getHomeDir() / "appname.cfg"
  894. assert expandTilde("~/foo/bar") == getHomeDir() / "foo/bar"
  895. assert expandTilde("/foo/bar") == "/foo/bar"
  896. if len(path) == 0 or path[0] != '~':
  897. result = path
  898. elif len(path) == 1:
  899. result = getHomeDir()
  900. elif (path[1] in {DirSep, AltSep}):
  901. result = getHomeDir() / path.substr(2)
  902. else:
  903. # TODO: handle `~bob` and `~bob/` which means home of bob
  904. result = path
  905. # TODO: consider whether quoteShellPosix, quoteShellWindows, quoteShell, quoteShellCommand
  906. # belong in `strutils` instead; they are not specific to paths
  907. proc quoteShellWindows*(s: string): string {.noSideEffect, rtl, extern: "nosp$1".} =
  908. ## Quote `s`, so it can be safely passed to Windows API.
  909. ##
  910. ## Based on Python's `subprocess.list2cmdline`.
  911. ## See `this link <http://msdn.microsoft.com/en-us/library/17w5ykft.aspx>`_
  912. ## for more details.
  913. let needQuote = {' ', '\t'} in s or s.len == 0
  914. result = ""
  915. var backslashBuff = ""
  916. if needQuote:
  917. result.add("\"")
  918. for c in s:
  919. if c == '\\':
  920. backslashBuff.add(c)
  921. elif c == '\"':
  922. result.add(backslashBuff)
  923. result.add(backslashBuff)
  924. backslashBuff.setLen(0)
  925. result.add("\\\"")
  926. else:
  927. if backslashBuff.len != 0:
  928. result.add(backslashBuff)
  929. backslashBuff.setLen(0)
  930. result.add(c)
  931. if needQuote:
  932. result.add("\"")
  933. proc quoteShellPosix*(s: string): string {.noSideEffect, rtl, extern: "nosp$1".} =
  934. ## Quote ``s``, so it can be safely passed to POSIX shell.
  935. ## Based on Python's `pipes.quote`.
  936. const safeUnixChars = {'%', '+', '-', '.', '/', '_', ':', '=', '@',
  937. '0'..'9', 'A'..'Z', 'a'..'z'}
  938. if s.len == 0:
  939. return "''"
  940. let safe = s.allCharsInSet(safeUnixChars)
  941. if safe:
  942. return s
  943. else:
  944. return "'" & s.replace("'", "'\"'\"'") & "'"
  945. when defined(windows) or defined(posix) or defined(nintendoswitch):
  946. proc quoteShell*(s: string): string {.noSideEffect, rtl, extern: "nosp$1".} =
  947. ## Quote ``s``, so it can be safely passed to shell.
  948. ##
  949. ## When on Windows, it calls `quoteShellWindows proc
  950. ## <#quoteShellWindows,string>`_. Otherwise, calls `quoteShellPosix proc
  951. ## <#quoteShellPosix,string>`_.
  952. when defined(windows):
  953. return quoteShellWindows(s)
  954. else:
  955. return quoteShellPosix(s)
  956. proc quoteShellCommand*(args: openArray[string]): string =
  957. ## Concatenates and quotes shell arguments `args`.
  958. runnableExamples:
  959. when defined(posix):
  960. assert quoteShellCommand(["aaa", "", "c d"]) == "aaa '' 'c d'"
  961. when defined(windows):
  962. assert quoteShellCommand(["aaa", "", "c d"]) == "aaa \"\" \"c d\""
  963. # can't use `map` pending https://github.com/nim-lang/Nim/issues/8303
  964. result = ""
  965. for i in 0..<args.len:
  966. if i > 0: result.add " "
  967. result.add quoteShell(args[i])
  968. when not weirdTarget:
  969. proc c_rename(oldname, newname: cstring): cint {.
  970. importc: "rename", header: "<stdio.h>".}
  971. proc c_system(cmd: cstring): cint {.
  972. importc: "system", header: "<stdlib.h>".}
  973. proc c_strlen(a: cstring): cint {.
  974. importc: "strlen", header: "<string.h>", noSideEffect.}
  975. proc c_free(p: pointer) {.
  976. importc: "free", header: "<stdlib.h>".}
  977. when defined(windows) and not weirdTarget:
  978. when useWinUnicode:
  979. template wrapUnary(varname, winApiProc, arg: untyped) =
  980. var varname = winApiProc(newWideCString(arg))
  981. template wrapBinary(varname, winApiProc, arg, arg2: untyped) =
  982. var varname = winApiProc(newWideCString(arg), arg2)
  983. proc findFirstFile(a: string, b: var WIN32_FIND_DATA): Handle =
  984. result = findFirstFileW(newWideCString(a), b)
  985. template findNextFile(a, b: untyped): untyped = findNextFileW(a, b)
  986. template getCommandLine(): untyped = getCommandLineW()
  987. template getFilename(f: untyped): untyped =
  988. $cast[WideCString](addr(f.cFileName[0]))
  989. else:
  990. template findFirstFile(a, b: untyped): untyped = findFirstFileA(a, b)
  991. template findNextFile(a, b: untyped): untyped = findNextFileA(a, b)
  992. template getCommandLine(): untyped = getCommandLineA()
  993. template getFilename(f: untyped): untyped = $cstring(addr f.cFileName)
  994. proc skipFindData(f: WIN32_FIND_DATA): bool {.inline.} =
  995. # Note - takes advantage of null delimiter in the cstring
  996. const dot = ord('.')
  997. result = f.cFileName[0].int == dot and (f.cFileName[1].int == 0 or
  998. f.cFileName[1].int == dot and f.cFileName[2].int == 0)
  999. proc fileExists*(filename: string): bool {.rtl, extern: "nos$1",
  1000. tags: [ReadDirEffect], noNimJs.} =
  1001. ## Returns true if `filename` exists and is a regular file or symlink.
  1002. ##
  1003. ## Directories, device files, named pipes and sockets return false.
  1004. ##
  1005. ## See also:
  1006. ## * `dirExists proc <#dirExists,string>`_
  1007. ## * `symlinkExists proc <#symlinkExists,string>`_
  1008. when defined(windows):
  1009. when useWinUnicode:
  1010. wrapUnary(a, getFileAttributesW, filename)
  1011. else:
  1012. var a = getFileAttributesA(filename)
  1013. if a != -1'i32:
  1014. result = (a and FILE_ATTRIBUTE_DIRECTORY) == 0'i32
  1015. else:
  1016. var res: Stat
  1017. return stat(filename, res) >= 0'i32 and S_ISREG(res.st_mode)
  1018. proc dirExists*(dir: string): bool {.rtl, extern: "nos$1", tags: [ReadDirEffect],
  1019. noNimJs.} =
  1020. ## Returns true if the directory `dir` exists. If `dir` is a file, false
  1021. ## is returned. Follows symlinks.
  1022. ##
  1023. ## See also:
  1024. ## * `fileExists proc <#fileExists,string>`_
  1025. ## * `symlinkExists proc <#symlinkExists,string>`_
  1026. when defined(windows):
  1027. when useWinUnicode:
  1028. wrapUnary(a, getFileAttributesW, dir)
  1029. else:
  1030. var a = getFileAttributesA(dir)
  1031. if a != -1'i32:
  1032. result = (a and FILE_ATTRIBUTE_DIRECTORY) != 0'i32
  1033. else:
  1034. var res: Stat
  1035. return stat(dir, res) >= 0'i32 and S_ISDIR(res.st_mode)
  1036. proc symlinkExists*(link: string): bool {.rtl, extern: "nos$1",
  1037. tags: [ReadDirEffect],
  1038. noWeirdTarget.} =
  1039. ## Returns true if the symlink `link` exists. Will return true
  1040. ## regardless of whether the link points to a directory or file.
  1041. ##
  1042. ## See also:
  1043. ## * `fileExists proc <#fileExists,string>`_
  1044. ## * `dirExists proc <#dirExists,string>`_
  1045. when defined(windows):
  1046. when useWinUnicode:
  1047. wrapUnary(a, getFileAttributesW, link)
  1048. else:
  1049. var a = getFileAttributesA(link)
  1050. if a != -1'i32:
  1051. result = (a and FILE_ATTRIBUTE_REPARSE_POINT) != 0'i32
  1052. else:
  1053. var res: Stat
  1054. return lstat(link, res) >= 0'i32 and S_ISLNK(res.st_mode)
  1055. when not defined(nimscript):
  1056. when not defined(js): # `noNimJs` doesn't work with templates, this should improve.
  1057. template existsFile*(args: varargs[untyped]): untyped {.deprecated: "use fileExists".} =
  1058. fileExists(args)
  1059. template existsDir*(args: varargs[untyped]): untyped {.deprecated: "use dirExists".} =
  1060. dirExists(args)
  1061. # {.deprecated: [existsFile: fileExists].} # pending bug #14819; this would avoid above mentioned issue
  1062. when not defined(windows) and not weirdTarget:
  1063. proc checkSymlink(path: string): bool =
  1064. var rawInfo: Stat
  1065. if lstat(path, rawInfo) < 0'i32: result = false
  1066. else: result = S_ISLNK(rawInfo.st_mode)
  1067. const
  1068. ExeExts* = ## Platform specific file extension for executables.
  1069. ## On Windows ``["exe", "cmd", "bat"]``, on Posix ``[""]``.
  1070. when defined(windows): ["exe", "cmd", "bat"] else: [""]
  1071. proc findExe*(exe: string, followSymlinks: bool = true;
  1072. extensions: openArray[string]=ExeExts): string {.
  1073. tags: [ReadDirEffect, ReadEnvEffect, ReadIOEffect], noNimJs.} =
  1074. ## Searches for `exe` in the current working directory and then
  1075. ## in directories listed in the ``PATH`` environment variable.
  1076. ##
  1077. ## Returns `""` if the `exe` cannot be found. `exe`
  1078. ## is added the `ExeExts <#ExeExts>`_ file extensions if it has none.
  1079. ##
  1080. ## If the system supports symlinks it also resolves them until it
  1081. ## meets the actual file. This behavior can be disabled if desired
  1082. ## by setting `followSymlinks = false`.
  1083. if exe.len == 0: return
  1084. template checkCurrentDir() =
  1085. for ext in extensions:
  1086. result = addFileExt(exe, ext)
  1087. if fileExists(result): return
  1088. when defined(posix):
  1089. if '/' in exe: checkCurrentDir()
  1090. else:
  1091. checkCurrentDir()
  1092. let path = string(getEnv("PATH"))
  1093. for candidate in split(path, PathSep):
  1094. if candidate.len == 0: continue
  1095. when defined(windows):
  1096. var x = (if candidate[0] == '"' and candidate[^1] == '"':
  1097. substr(candidate, 1, candidate.len-2) else: candidate) /
  1098. exe
  1099. else:
  1100. var x = expandTilde(candidate) / exe
  1101. for ext in extensions:
  1102. var x = addFileExt(x, ext)
  1103. if fileExists(x):
  1104. when not defined(windows):
  1105. while followSymlinks: # doubles as if here
  1106. if x.checkSymlink:
  1107. var r = newString(256)
  1108. var len = readlink(x, r, 256)
  1109. if len < 0:
  1110. raiseOSError(osLastError(), exe)
  1111. if len > 256:
  1112. r = newString(len+1)
  1113. len = readlink(x, r, len)
  1114. setLen(r, len)
  1115. if isAbsolute(r):
  1116. x = r
  1117. else:
  1118. x = parentDir(x) / r
  1119. else:
  1120. break
  1121. return x
  1122. result = ""
  1123. when weirdTarget:
  1124. const times = "fake const"
  1125. template Time(x: untyped): untyped = string
  1126. proc getLastModificationTime*(file: string): times.Time {.rtl, extern: "nos$1", noWeirdTarget.} =
  1127. ## Returns the `file`'s last modification time.
  1128. ##
  1129. ## See also:
  1130. ## * `getLastAccessTime proc <#getLastAccessTime,string>`_
  1131. ## * `getCreationTime proc <#getCreationTime,string>`_
  1132. ## * `fileNewer proc <#fileNewer,string,string>`_
  1133. when defined(posix):
  1134. var res: Stat
  1135. if stat(file, res) < 0'i32: raiseOSError(osLastError(), file)
  1136. result = res.st_mtim.toTime
  1137. else:
  1138. var f: WIN32_FIND_DATA
  1139. var h = findFirstFile(file, f)
  1140. if h == -1'i32: raiseOSError(osLastError(), file)
  1141. result = fromWinTime(rdFileTime(f.ftLastWriteTime))
  1142. findClose(h)
  1143. proc getLastAccessTime*(file: string): times.Time {.rtl, extern: "nos$1", noWeirdTarget.} =
  1144. ## Returns the `file`'s last read or write access time.
  1145. ##
  1146. ## See also:
  1147. ## * `getLastModificationTime proc <#getLastModificationTime,string>`_
  1148. ## * `getCreationTime proc <#getCreationTime,string>`_
  1149. ## * `fileNewer proc <#fileNewer,string,string>`_
  1150. when defined(posix):
  1151. var res: Stat
  1152. if stat(file, res) < 0'i32: raiseOSError(osLastError(), file)
  1153. result = res.st_atim.toTime
  1154. else:
  1155. var f: WIN32_FIND_DATA
  1156. var h = findFirstFile(file, f)
  1157. if h == -1'i32: raiseOSError(osLastError(), file)
  1158. result = fromWinTime(rdFileTime(f.ftLastAccessTime))
  1159. findClose(h)
  1160. proc getCreationTime*(file: string): times.Time {.rtl, extern: "nos$1", noWeirdTarget.} =
  1161. ## Returns the `file`'s creation time.
  1162. ##
  1163. ## **Note:** Under POSIX OS's, the returned time may actually be the time at
  1164. ## which the file's attribute's were last modified. See
  1165. ## `here <https://github.com/nim-lang/Nim/issues/1058>`_ for details.
  1166. ##
  1167. ## See also:
  1168. ## * `getLastModificationTime proc <#getLastModificationTime,string>`_
  1169. ## * `getLastAccessTime proc <#getLastAccessTime,string>`_
  1170. ## * `fileNewer proc <#fileNewer,string,string>`_
  1171. when defined(posix):
  1172. var res: Stat
  1173. if stat(file, res) < 0'i32: raiseOSError(osLastError(), file)
  1174. result = res.st_ctim.toTime
  1175. else:
  1176. var f: WIN32_FIND_DATA
  1177. var h = findFirstFile(file, f)
  1178. if h == -1'i32: raiseOSError(osLastError(), file)
  1179. result = fromWinTime(rdFileTime(f.ftCreationTime))
  1180. findClose(h)
  1181. proc fileNewer*(a, b: string): bool {.rtl, extern: "nos$1", noWeirdTarget.} =
  1182. ## Returns true if the file `a` is newer than file `b`, i.e. if `a`'s
  1183. ## modification time is later than `b`'s.
  1184. ##
  1185. ## See also:
  1186. ## * `getLastModificationTime proc <#getLastModificationTime,string>`_
  1187. ## * `getLastAccessTime proc <#getLastAccessTime,string>`_
  1188. ## * `getCreationTime proc <#getCreationTime,string>`_
  1189. when defined(posix):
  1190. # If we don't have access to nanosecond resolution, use '>='
  1191. when not StatHasNanoseconds:
  1192. result = getLastModificationTime(a) >= getLastModificationTime(b)
  1193. else:
  1194. result = getLastModificationTime(a) > getLastModificationTime(b)
  1195. else:
  1196. result = getLastModificationTime(a) > getLastModificationTime(b)
  1197. when not defined(nimscript):
  1198. proc getCurrentDir*(): string {.rtl, extern: "nos$1", tags: [].} =
  1199. ## Returns the `current working directory`:idx: i.e. where the built
  1200. ## binary is run.
  1201. ##
  1202. ## So the path returned by this proc is determined at run time.
  1203. ##
  1204. ## See also:
  1205. ## * `getHomeDir proc <#getHomeDir>`_
  1206. ## * `getConfigDir proc <#getConfigDir>`_
  1207. ## * `getTempDir proc <#getTempDir>`_
  1208. ## * `setCurrentDir proc <#setCurrentDir,string>`_
  1209. ## * `currentSourcePath template <system.html#currentSourcePath.t>`_
  1210. ## * `getProjectPath proc <macros.html#getProjectPath>`_
  1211. when defined(nodejs):
  1212. var ret: cstring
  1213. {.emit: "`ret` = process.cwd();".}
  1214. return $ret
  1215. elif defined(js):
  1216. doAssert false, "use -d:nodejs to have `getCurrentDir` defined"
  1217. elif defined(windows):
  1218. var bufsize = MAX_PATH.int32
  1219. when useWinUnicode:
  1220. var res = newWideCString("", bufsize)
  1221. while true:
  1222. var L = getCurrentDirectoryW(bufsize, res)
  1223. if L == 0'i32:
  1224. raiseOSError(osLastError())
  1225. elif L > bufsize:
  1226. res = newWideCString("", L)
  1227. bufsize = L
  1228. else:
  1229. result = res$L
  1230. break
  1231. else:
  1232. result = newString(bufsize)
  1233. while true:
  1234. var L = getCurrentDirectoryA(bufsize, result)
  1235. if L == 0'i32:
  1236. raiseOSError(osLastError())
  1237. elif L > bufsize:
  1238. result = newString(L)
  1239. bufsize = L
  1240. else:
  1241. setLen(result, L)
  1242. break
  1243. else:
  1244. var bufsize = 1024 # should be enough
  1245. result = newString(bufsize)
  1246. while true:
  1247. if getcwd(result, bufsize) != nil:
  1248. setLen(result, c_strlen(result))
  1249. break
  1250. else:
  1251. let err = osLastError()
  1252. if err.int32 == ERANGE:
  1253. bufsize = bufsize shl 1
  1254. doAssert(bufsize >= 0)
  1255. result = newString(bufsize)
  1256. else:
  1257. raiseOSError(osLastError())
  1258. proc setCurrentDir*(newDir: string) {.inline, tags: [], noWeirdTarget.} =
  1259. ## Sets the `current working directory`:idx:; `OSError`
  1260. ## is raised if `newDir` cannot been set.
  1261. ##
  1262. ## See also:
  1263. ## * `getHomeDir proc <#getHomeDir>`_
  1264. ## * `getConfigDir proc <#getConfigDir>`_
  1265. ## * `getTempDir proc <#getTempDir>`_
  1266. ## * `getCurrentDir proc <#getCurrentDir>`_
  1267. when defined(Windows):
  1268. when useWinUnicode:
  1269. if setCurrentDirectoryW(newWideCString(newDir)) == 0'i32:
  1270. raiseOSError(osLastError(), newDir)
  1271. else:
  1272. if setCurrentDirectoryA(newDir) == 0'i32: raiseOSError(osLastError(), newDir)
  1273. else:
  1274. if chdir(newDir) != 0'i32: raiseOSError(osLastError(), newDir)
  1275. proc absolutePath*(path: string, root = getCurrentDir()): string =
  1276. ## Returns the absolute path of `path`, rooted at `root` (which must be absolute;
  1277. ## default: current directory).
  1278. ## If `path` is absolute, return it, ignoring `root`.
  1279. ##
  1280. ## See also:
  1281. ## * `normalizedPath proc <#normalizedPath,string>`_
  1282. ## * `normalizePath proc <#normalizePath,string>`_
  1283. runnableExamples:
  1284. assert absolutePath("a") == getCurrentDir() / "a"
  1285. if isAbsolute(path): path
  1286. else:
  1287. if not root.isAbsolute:
  1288. raise newException(ValueError, "The specified root is not absolute: " & root)
  1289. joinPath(root, path)
  1290. proc absolutePathInternal(path: string): string =
  1291. absolutePath(path, getCurrentDir())
  1292. proc normalizeExe*(file: var string) {.since: (1, 3, 5).} =
  1293. ## on posix, prepends `./` if `file` doesn't contain `/` and is not `"", ".", ".."`.
  1294. runnableExamples:
  1295. import sugar
  1296. when defined(posix):
  1297. doAssert "foo".dup(normalizeExe) == "./foo"
  1298. doAssert "foo/../bar".dup(normalizeExe) == "foo/../bar"
  1299. doAssert "".dup(normalizeExe) == ""
  1300. when defined(posix):
  1301. if file.len > 0 and DirSep notin file and file != "." and file != "..":
  1302. file = "./" & file
  1303. proc normalizePath*(path: var string) {.rtl, extern: "nos$1", tags: [].} =
  1304. ## Normalize a path.
  1305. ##
  1306. ## Consecutive directory separators are collapsed, including an initial double slash.
  1307. ##
  1308. ## On relative paths, double dot (`..`) sequences are collapsed if possible.
  1309. ## On absolute paths they are always collapsed.
  1310. ##
  1311. ## Warning: URL-encoded and Unicode attempts at directory traversal are not detected.
  1312. ## Triple dot is not handled.
  1313. ##
  1314. ## See also:
  1315. ## * `absolutePath proc <#absolutePath,string>`_
  1316. ## * `normalizedPath proc <#normalizedPath,string>`_ for outplace version
  1317. ## * `normalizeExe proc <#normalizeExe,string>`_
  1318. runnableExamples:
  1319. when defined(posix):
  1320. var a = "a///b//..//c///d"
  1321. a.normalizePath()
  1322. assert a == "a/c/d"
  1323. path = pathnorm.normalizePath(path)
  1324. when false:
  1325. let isAbs = isAbsolute(path)
  1326. var stack: seq[string] = @[]
  1327. for p in split(path, {DirSep}):
  1328. case p
  1329. of "", ".":
  1330. continue
  1331. of "..":
  1332. if stack.len == 0:
  1333. if isAbs:
  1334. discard # collapse all double dots on absoluta paths
  1335. else:
  1336. stack.add(p)
  1337. elif stack[^1] == "..":
  1338. stack.add(p)
  1339. else:
  1340. discard stack.pop()
  1341. else:
  1342. stack.add(p)
  1343. if isAbs:
  1344. path = DirSep & join(stack, $DirSep)
  1345. elif stack.len > 0:
  1346. path = join(stack, $DirSep)
  1347. else:
  1348. path = "."
  1349. proc normalizePathAux(path: var string) = normalizePath(path)
  1350. proc normalizedPath*(path: string): string {.rtl, extern: "nos$1", tags: [].} =
  1351. ## Returns a normalized path for the current OS.
  1352. ##
  1353. ## See also:
  1354. ## * `absolutePath proc <#absolutePath,string>`_
  1355. ## * `normalizePath proc <#normalizePath,string>`_ for the in-place version
  1356. runnableExamples:
  1357. when defined(posix):
  1358. assert normalizedPath("a///b//..//c///d") == "a/c/d"
  1359. result = pathnorm.normalizePath(path)
  1360. when defined(Windows) and not weirdTarget:
  1361. proc openHandle(path: string, followSymlink=true, writeAccess=false): Handle =
  1362. var flags = FILE_FLAG_BACKUP_SEMANTICS or FILE_ATTRIBUTE_NORMAL
  1363. if not followSymlink:
  1364. flags = flags or FILE_FLAG_OPEN_REPARSE_POINT
  1365. let access = if writeAccess: GENERIC_WRITE else: 0'i32
  1366. when useWinUnicode:
  1367. result = createFileW(
  1368. newWideCString(path), access,
  1369. FILE_SHARE_DELETE or FILE_SHARE_READ or FILE_SHARE_WRITE,
  1370. nil, OPEN_EXISTING, flags, 0
  1371. )
  1372. else:
  1373. result = createFileA(
  1374. path, access,
  1375. FILE_SHARE_DELETE or FILE_SHARE_READ or FILE_SHARE_WRITE,
  1376. nil, OPEN_EXISTING, flags, 0
  1377. )
  1378. proc sameFile*(path1, path2: string): bool {.rtl, extern: "nos$1",
  1379. tags: [ReadDirEffect], noWeirdTarget.} =
  1380. ## Returns true if both pathname arguments refer to the same physical
  1381. ## file or directory.
  1382. ##
  1383. ## Raises `OSError` if any of the files does not
  1384. ## exist or information about it can not be obtained.
  1385. ##
  1386. ## This proc will return true if given two alternative hard-linked or
  1387. ## sym-linked paths to the same file or directory.
  1388. ##
  1389. ## See also:
  1390. ## * `sameFileContent proc <#sameFileContent,string,string>`_
  1391. when defined(Windows):
  1392. var success = true
  1393. var f1 = openHandle(path1)
  1394. var f2 = openHandle(path2)
  1395. var lastErr: OSErrorCode
  1396. if f1 != INVALID_HANDLE_VALUE and f2 != INVALID_HANDLE_VALUE:
  1397. var fi1, fi2: BY_HANDLE_FILE_INFORMATION
  1398. if getFileInformationByHandle(f1, addr(fi1)) != 0 and
  1399. getFileInformationByHandle(f2, addr(fi2)) != 0:
  1400. result = fi1.dwVolumeSerialNumber == fi2.dwVolumeSerialNumber and
  1401. fi1.nFileIndexHigh == fi2.nFileIndexHigh and
  1402. fi1.nFileIndexLow == fi2.nFileIndexLow
  1403. else:
  1404. lastErr = osLastError()
  1405. success = false
  1406. else:
  1407. lastErr = osLastError()
  1408. success = false
  1409. discard closeHandle(f1)
  1410. discard closeHandle(f2)
  1411. if not success: raiseOSError(lastErr, $(path1, path2))
  1412. else:
  1413. var a, b: Stat
  1414. if stat(path1, a) < 0'i32 or stat(path2, b) < 0'i32:
  1415. raiseOSError(osLastError(), $(path1, path2))
  1416. else:
  1417. result = a.st_dev == b.st_dev and a.st_ino == b.st_ino
  1418. proc sameFileContent*(path1, path2: string): bool {.rtl, extern: "nos$1",
  1419. tags: [ReadIOEffect], noWeirdTarget.} =
  1420. ## Returns true if both pathname arguments refer to files with identical
  1421. ## binary content.
  1422. ##
  1423. ## See also:
  1424. ## * `sameFile proc <#sameFile,string,string>`_
  1425. const
  1426. bufSize = 8192 # 8K buffer
  1427. var
  1428. a, b: File
  1429. if not open(a, path1): return false
  1430. if not open(b, path2):
  1431. close(a)
  1432. return false
  1433. var bufA = alloc(bufSize)
  1434. var bufB = alloc(bufSize)
  1435. while true:
  1436. var readA = readBuffer(a, bufA, bufSize)
  1437. var readB = readBuffer(b, bufB, bufSize)
  1438. if readA != readB:
  1439. result = false
  1440. break
  1441. if readA == 0:
  1442. result = true
  1443. break
  1444. result = equalMem(bufA, bufB, readA)
  1445. if not result: break
  1446. if readA != bufSize: break # end of file
  1447. dealloc(bufA)
  1448. dealloc(bufB)
  1449. close(a)
  1450. close(b)
  1451. type
  1452. FilePermission* = enum ## File access permission, modelled after UNIX.
  1453. ##
  1454. ## See also:
  1455. ## * `getFilePermissions <#getFilePermissions,string>`_
  1456. ## * `setFilePermissions <#setFilePermissions,string,set[FilePermission]>`_
  1457. ## * `FileInfo object <#FileInfo>`_
  1458. fpUserExec, ## execute access for the file owner
  1459. fpUserWrite, ## write access for the file owner
  1460. fpUserRead, ## read access for the file owner
  1461. fpGroupExec, ## execute access for the group
  1462. fpGroupWrite, ## write access for the group
  1463. fpGroupRead, ## read access for the group
  1464. fpOthersExec, ## execute access for others
  1465. fpOthersWrite, ## write access for others
  1466. fpOthersRead ## read access for others
  1467. proc getFilePermissions*(filename: string): set[FilePermission] {.
  1468. rtl, extern: "nos$1", tags: [ReadDirEffect], noWeirdTarget.} =
  1469. ## Retrieves file permissions for `filename`.
  1470. ##
  1471. ## `OSError` is raised in case of an error.
  1472. ## On Windows, only the ``readonly`` flag is checked, every other
  1473. ## permission is available in any case.
  1474. ##
  1475. ## See also:
  1476. ## * `setFilePermissions proc <#setFilePermissions,string,set[FilePermission]>`_
  1477. ## * `FilePermission enum <#FilePermission>`_
  1478. when defined(posix):
  1479. var a: Stat
  1480. if stat(filename, a) < 0'i32: raiseOSError(osLastError(), filename)
  1481. result = {}
  1482. if (a.st_mode and S_IRUSR.Mode) != 0.Mode: result.incl(fpUserRead)
  1483. if (a.st_mode and S_IWUSR.Mode) != 0.Mode: result.incl(fpUserWrite)
  1484. if (a.st_mode and S_IXUSR.Mode) != 0.Mode: result.incl(fpUserExec)
  1485. if (a.st_mode and S_IRGRP.Mode) != 0.Mode: result.incl(fpGroupRead)
  1486. if (a.st_mode and S_IWGRP.Mode) != 0.Mode: result.incl(fpGroupWrite)
  1487. if (a.st_mode and S_IXGRP.Mode) != 0.Mode: result.incl(fpGroupExec)
  1488. if (a.st_mode and S_IROTH.Mode) != 0.Mode: result.incl(fpOthersRead)
  1489. if (a.st_mode and S_IWOTH.Mode) != 0.Mode: result.incl(fpOthersWrite)
  1490. if (a.st_mode and S_IXOTH.Mode) != 0.Mode: result.incl(fpOthersExec)
  1491. else:
  1492. when useWinUnicode:
  1493. wrapUnary(res, getFileAttributesW, filename)
  1494. else:
  1495. var res = getFileAttributesA(filename)
  1496. if res == -1'i32: raiseOSError(osLastError(), filename)
  1497. if (res and FILE_ATTRIBUTE_READONLY) != 0'i32:
  1498. result = {fpUserExec, fpUserRead, fpGroupExec, fpGroupRead,
  1499. fpOthersExec, fpOthersRead}
  1500. else:
  1501. result = {fpUserExec..fpOthersRead}
  1502. proc setFilePermissions*(filename: string, permissions: set[FilePermission]) {.
  1503. rtl, extern: "nos$1", tags: [WriteDirEffect], noWeirdTarget.} =
  1504. ## Sets the file permissions for `filename`.
  1505. ##
  1506. ## `OSError` is raised in case of an error.
  1507. ## On Windows, only the ``readonly`` flag is changed, depending on
  1508. ## ``fpUserWrite`` permission.
  1509. ##
  1510. ## See also:
  1511. ## * `getFilePermissions <#getFilePermissions,string>`_
  1512. ## * `FilePermission enum <#FilePermission>`_
  1513. when defined(posix):
  1514. var p = 0.Mode
  1515. if fpUserRead in permissions: p = p or S_IRUSR.Mode
  1516. if fpUserWrite in permissions: p = p or S_IWUSR.Mode
  1517. if fpUserExec in permissions: p = p or S_IXUSR.Mode
  1518. if fpGroupRead in permissions: p = p or S_IRGRP.Mode
  1519. if fpGroupWrite in permissions: p = p or S_IWGRP.Mode
  1520. if fpGroupExec in permissions: p = p or S_IXGRP.Mode
  1521. if fpOthersRead in permissions: p = p or S_IROTH.Mode
  1522. if fpOthersWrite in permissions: p = p or S_IWOTH.Mode
  1523. if fpOthersExec in permissions: p = p or S_IXOTH.Mode
  1524. if chmod(filename, cast[Mode](p)) != 0: raiseOSError(osLastError(), $(filename, permissions))
  1525. else:
  1526. when useWinUnicode:
  1527. wrapUnary(res, getFileAttributesW, filename)
  1528. else:
  1529. var res = getFileAttributesA(filename)
  1530. if res == -1'i32: raiseOSError(osLastError(), filename)
  1531. if fpUserWrite in permissions:
  1532. res = res and not FILE_ATTRIBUTE_READONLY
  1533. else:
  1534. res = res or FILE_ATTRIBUTE_READONLY
  1535. when useWinUnicode:
  1536. wrapBinary(res2, setFileAttributesW, filename, res)
  1537. else:
  1538. var res2 = setFileAttributesA(filename, res)
  1539. if res2 == - 1'i32: raiseOSError(osLastError(), $(filename, permissions))
  1540. proc copyFile*(source, dest: string) {.rtl, extern: "nos$1",
  1541. tags: [ReadIOEffect, WriteIOEffect], noWeirdTarget.} =
  1542. ## Copies a file from `source` to `dest`, where `dest.parentDir` must exist.
  1543. ##
  1544. ## If this fails, `OSError` is raised.
  1545. ##
  1546. ## On the Windows platform this proc will
  1547. ## copy the source file's attributes into dest.
  1548. ##
  1549. ## On other platforms you need
  1550. ## to use `getFilePermissions <#getFilePermissions,string>`_ and
  1551. ## `setFilePermissions <#setFilePermissions,string,set[FilePermission]>`_ procs
  1552. ## to copy them by hand (or use the convenience `copyFileWithPermissions
  1553. ## proc <#copyFileWithPermissions,string,string>`_),
  1554. ## otherwise `dest` will inherit the default permissions of a newly
  1555. ## created file for the user.
  1556. ##
  1557. ## If `dest` already exists, the file attributes
  1558. ## will be preserved and the content overwritten.
  1559. ##
  1560. ## See also:
  1561. ## * `copyDir proc <#copyDir,string,string>`_
  1562. ## * `copyFileWithPermissions proc <#copyFileWithPermissions,string,string>`_
  1563. ## * `tryRemoveFile proc <#tryRemoveFile,string>`_
  1564. ## * `removeFile proc <#removeFile,string>`_
  1565. ## * `moveFile proc <#moveFile,string,string>`_
  1566. when defined(Windows):
  1567. when useWinUnicode:
  1568. let s = newWideCString(source)
  1569. let d = newWideCString(dest)
  1570. if copyFileW(s, d, 0'i32) == 0'i32: raiseOSError(osLastError(), $(source, dest))
  1571. else:
  1572. if copyFileA(source, dest, 0'i32) == 0'i32: raiseOSError(osLastError(), $(source, dest))
  1573. else:
  1574. # generic version of copyFile which works for any platform:
  1575. const bufSize = 8000 # better for memory manager
  1576. var d, s: File
  1577. if not open(s, source): raiseOSError(osLastError(), source)
  1578. if not open(d, dest, fmWrite):
  1579. close(s)
  1580. raiseOSError(osLastError(), dest)
  1581. var buf = alloc(bufSize)
  1582. while true:
  1583. var bytesread = readBuffer(s, buf, bufSize)
  1584. if bytesread > 0:
  1585. var byteswritten = writeBuffer(d, buf, bytesread)
  1586. if bytesread != byteswritten:
  1587. dealloc(buf)
  1588. close(s)
  1589. close(d)
  1590. raiseOSError(osLastError(), dest)
  1591. if bytesread != bufSize: break
  1592. dealloc(buf)
  1593. close(s)
  1594. flushFile(d)
  1595. close(d)
  1596. proc copyFileToDir*(source, dir: string) {.noWeirdTarget, since: (1,3,7).} =
  1597. ## Copies a file `source` into directory `dir`, which must exist.
  1598. if dir.len == 0: # treating "" as "." is error prone
  1599. raise newException(ValueError, "dest is empty")
  1600. copyFile(source, dir / source.lastPathPart)
  1601. when not declared(ENOENT) and not defined(Windows):
  1602. when NoFakeVars:
  1603. when not defined(haiku):
  1604. const ENOENT = cint(2) # 2 on most systems including Solaris
  1605. else:
  1606. const ENOENT = cint(-2147459069)
  1607. else:
  1608. var ENOENT {.importc, header: "<errno.h>".}: cint
  1609. when defined(Windows) and not weirdTarget:
  1610. when useWinUnicode:
  1611. template deleteFile(file: untyped): untyped = deleteFileW(file)
  1612. template setFileAttributes(file, attrs: untyped): untyped =
  1613. setFileAttributesW(file, attrs)
  1614. else:
  1615. template deleteFile(file: untyped): untyped = deleteFileA(file)
  1616. template setFileAttributes(file, attrs: untyped): untyped =
  1617. setFileAttributesA(file, attrs)
  1618. proc tryRemoveFile*(file: string): bool {.rtl, extern: "nos$1", tags: [WriteDirEffect], noWeirdTarget.} =
  1619. ## Removes the `file`.
  1620. ##
  1621. ## If this fails, returns `false`. This does not fail
  1622. ## if the file never existed in the first place.
  1623. ##
  1624. ## On Windows, ignores the read-only attribute.
  1625. ##
  1626. ## See also:
  1627. ## * `copyFile proc <#copyFile,string,string>`_
  1628. ## * `copyFileWithPermissions proc <#copyFileWithPermissions,string,string>`_
  1629. ## * `removeFile proc <#removeFile,string>`_
  1630. ## * `moveFile proc <#moveFile,string,string>`_
  1631. result = true
  1632. when defined(Windows):
  1633. when useWinUnicode:
  1634. let f = newWideCString(file)
  1635. else:
  1636. let f = file
  1637. if deleteFile(f) == 0:
  1638. result = false
  1639. let err = getLastError()
  1640. if err == ERROR_FILE_NOT_FOUND or err == ERROR_PATH_NOT_FOUND:
  1641. result = true
  1642. elif err == ERROR_ACCESS_DENIED and
  1643. setFileAttributes(f, FILE_ATTRIBUTE_NORMAL) != 0 and
  1644. deleteFile(f) != 0:
  1645. result = true
  1646. else:
  1647. if unlink(file) != 0'i32 and errno != ENOENT:
  1648. result = false
  1649. proc removeFile*(file: string) {.rtl, extern: "nos$1", tags: [WriteDirEffect], noWeirdTarget.} =
  1650. ## Removes the `file`.
  1651. ##
  1652. ## If this fails, `OSError` is raised. This does not fail
  1653. ## if the file never existed in the first place.
  1654. ##
  1655. ## On Windows, ignores the read-only attribute.
  1656. ##
  1657. ## See also:
  1658. ## * `removeDir proc <#removeDir,string>`_
  1659. ## * `copyFile proc <#copyFile,string,string>`_
  1660. ## * `copyFileWithPermissions proc <#copyFileWithPermissions,string,string>`_
  1661. ## * `tryRemoveFile proc <#tryRemoveFile,string>`_
  1662. ## * `moveFile proc <#moveFile,string,string>`_
  1663. if not tryRemoveFile(file):
  1664. raiseOSError(osLastError(), file)
  1665. proc tryMoveFSObject(source, dest: string): bool {.noWeirdTarget.} =
  1666. ## Moves a file or directory from `source` to `dest`.
  1667. ##
  1668. ## Returns false in case of `EXDEV` error.
  1669. ## In case of other errors `OSError` is raised.
  1670. ## Returns true in case of success.
  1671. when defined(Windows):
  1672. when useWinUnicode:
  1673. let s = newWideCString(source)
  1674. let d = newWideCString(dest)
  1675. if moveFileExW(s, d, MOVEFILE_COPY_ALLOWED or MOVEFILE_REPLACE_EXISTING) == 0'i32: raiseOSError(osLastError(), $(source, dest))
  1676. else:
  1677. if moveFileExA(source, dest, MOVEFILE_COPY_ALLOWED or MOVEFILE_REPLACE_EXISTING) == 0'i32: raiseOSError(osLastError(), $(source, dest))
  1678. else:
  1679. if c_rename(source, dest) != 0'i32:
  1680. let err = osLastError()
  1681. if err == EXDEV.OSErrorCode:
  1682. return false
  1683. else:
  1684. # see whether `strerror(errno)` is redundant with what raiseOSError already shows
  1685. raiseOSError(err, $(source, dest, strerror(errno)))
  1686. return true
  1687. proc moveFile*(source, dest: string) {.rtl, extern: "nos$1",
  1688. tags: [ReadIOEffect, WriteIOEffect], noWeirdTarget.} =
  1689. ## Moves a file from `source` to `dest`.
  1690. ##
  1691. ## If this fails, `OSError` is raised.
  1692. ## If `dest` already exists, it will be overwritten.
  1693. ##
  1694. ## Can be used to `rename files`:idx:.
  1695. ##
  1696. ## See also:
  1697. ## * `moveDir proc <#moveDir,string,string>`_
  1698. ## * `copyFile proc <#copyFile,string,string>`_
  1699. ## * `copyFileWithPermissions proc <#copyFileWithPermissions,string,string>`_
  1700. ## * `removeFile proc <#removeFile,string>`_
  1701. ## * `tryRemoveFile proc <#tryRemoveFile,string>`_
  1702. if not tryMoveFSObject(source, dest):
  1703. when not defined(windows):
  1704. # Fallback to copy & del
  1705. copyFile(source, dest)
  1706. try:
  1707. removeFile(source)
  1708. except:
  1709. discard tryRemoveFile(dest)
  1710. raise
  1711. proc exitStatusLikeShell*(status: cint): cint =
  1712. ## Converts exit code from `c_system` into a shell exit code.
  1713. when defined(posix) and not weirdTarget:
  1714. if WIFSIGNALED(status):
  1715. # like the shell!
  1716. 128 + WTERMSIG(status)
  1717. else:
  1718. WEXITSTATUS(status)
  1719. else:
  1720. status
  1721. proc execShellCmd*(command: string): int {.rtl, extern: "nos$1",
  1722. tags: [ExecIOEffect], noWeirdTarget.} =
  1723. ## Executes a `shell command`:idx:.
  1724. ##
  1725. ## Command has the form 'program args' where args are the command
  1726. ## line arguments given to program. The proc returns the error code
  1727. ## of the shell when it has finished (zero if there is no error).
  1728. ## The proc does not return until the process has finished.
  1729. ##
  1730. ## To execute a program without having a shell involved, use `osproc.execProcess proc
  1731. ## <osproc.html#execProcess,string,string,openArray[string],StringTableRef,set[ProcessOption]>`_.
  1732. ##
  1733. ## **Examples:**
  1734. ##
  1735. ## .. code-block::
  1736. ## discard execShellCmd("ls -la")
  1737. result = exitStatusLikeShell(c_system(command))
  1738. # Templates for filtering directories and files
  1739. when defined(windows) and not weirdTarget:
  1740. template isDir(f: WIN32_FIND_DATA): bool =
  1741. (f.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY) != 0'i32
  1742. template isFile(f: WIN32_FIND_DATA): bool =
  1743. not isDir(f)
  1744. else:
  1745. template isDir(f: string): bool {.dirty.} =
  1746. dirExists(f)
  1747. template isFile(f: string): bool {.dirty.} =
  1748. fileExists(f)
  1749. template defaultWalkFilter(item): bool =
  1750. ## Walk filter used to return true on both
  1751. ## files and directories
  1752. true
  1753. template walkCommon(pattern: string, filter) =
  1754. ## Common code for getting the files and directories with the
  1755. ## specified `pattern`
  1756. when defined(windows):
  1757. var
  1758. f: WIN32_FIND_DATA
  1759. res: int
  1760. res = findFirstFile(pattern, f)
  1761. if res != -1:
  1762. defer: findClose(res)
  1763. let dotPos = searchExtPos(pattern)
  1764. while true:
  1765. if not skipFindData(f) and filter(f):
  1766. # Windows bug/gotcha: 't*.nim' matches 'tfoo.nims' -.- so we check
  1767. # that the file extensions have the same length ...
  1768. let ff = getFilename(f)
  1769. let idx = ff.len - pattern.len + dotPos
  1770. if dotPos < 0 or idx >= ff.len or (idx >= 0 and ff[idx] == '.') or
  1771. (dotPos >= 0 and dotPos+1 < pattern.len and pattern[dotPos+1] == '*'):
  1772. yield splitFile(pattern).dir / extractFilename(ff)
  1773. if findNextFile(res, f) == 0'i32:
  1774. let errCode = getLastError()
  1775. if errCode == ERROR_NO_MORE_FILES: break
  1776. else: raiseOSError(errCode.OSErrorCode)
  1777. else: # here we use glob
  1778. var
  1779. f: Glob
  1780. res: int
  1781. f.gl_offs = 0
  1782. f.gl_pathc = 0
  1783. f.gl_pathv = nil
  1784. res = glob(pattern, 0, nil, addr(f))
  1785. defer: globfree(addr(f))
  1786. if res == 0:
  1787. for i in 0.. f.gl_pathc - 1:
  1788. assert(f.gl_pathv[i] != nil)
  1789. let path = $f.gl_pathv[i]
  1790. if filter(path):
  1791. yield path
  1792. iterator walkPattern*(pattern: string): string {.tags: [ReadDirEffect], noWeirdTarget.} =
  1793. ## Iterate over all the files and directories that match the `pattern`.
  1794. ##
  1795. ## On POSIX this uses the `glob`:idx: call.
  1796. ## `pattern` is OS dependent, but at least the `"\*.ext"`
  1797. ## notation is supported.
  1798. ##
  1799. ## See also:
  1800. ## * `walkFiles iterator <#walkFiles.i,string>`_
  1801. ## * `walkDirs iterator <#walkDirs.i,string>`_
  1802. ## * `walkDir iterator <#walkDir.i,string>`_
  1803. ## * `walkDirRec iterator <#walkDirRec.i,string>`_
  1804. walkCommon(pattern, defaultWalkFilter)
  1805. iterator walkFiles*(pattern: string): string {.tags: [ReadDirEffect], noWeirdTarget.} =
  1806. ## Iterate over all the files that match the `pattern`.
  1807. ##
  1808. ## On POSIX this uses the `glob`:idx: call.
  1809. ## `pattern` is OS dependent, but at least the `"\*.ext"`
  1810. ## notation is supported.
  1811. ##
  1812. ## See also:
  1813. ## * `walkPattern iterator <#walkPattern.i,string>`_
  1814. ## * `walkDirs iterator <#walkDirs.i,string>`_
  1815. ## * `walkDir iterator <#walkDir.i,string>`_
  1816. ## * `walkDirRec iterator <#walkDirRec.i,string>`_
  1817. walkCommon(pattern, isFile)
  1818. iterator walkDirs*(pattern: string): string {.tags: [ReadDirEffect], noWeirdTarget.} =
  1819. ## Iterate over all the directories that match the `pattern`.
  1820. ##
  1821. ## On POSIX this uses the `glob`:idx: call.
  1822. ## `pattern` is OS dependent, but at least the `"\*.ext"`
  1823. ## notation is supported.
  1824. ##
  1825. ## See also:
  1826. ## * `walkPattern iterator <#walkPattern.i,string>`_
  1827. ## * `walkFiles iterator <#walkFiles.i,string>`_
  1828. ## * `walkDir iterator <#walkDir.i,string>`_
  1829. ## * `walkDirRec iterator <#walkDirRec.i,string>`_
  1830. walkCommon(pattern, isDir)
  1831. proc expandFilename*(filename: string): string {.rtl, extern: "nos$1",
  1832. tags: [ReadDirEffect], noWeirdTarget.} =
  1833. ## Returns the full (`absolute`:idx:) path of an existing file `filename`.
  1834. ##
  1835. ## Raises `OSError` in case of an error. Follows symlinks.
  1836. when defined(windows):
  1837. var bufsize = MAX_PATH.int32
  1838. when useWinUnicode:
  1839. var unused: WideCString = nil
  1840. var res = newWideCString("", bufsize)
  1841. while true:
  1842. var L = getFullPathNameW(newWideCString(filename), bufsize, res, unused)
  1843. if L == 0'i32:
  1844. raiseOSError(osLastError(), filename)
  1845. elif L > bufsize:
  1846. res = newWideCString("", L)
  1847. bufsize = L
  1848. else:
  1849. result = res$L
  1850. break
  1851. else:
  1852. var unused: cstring = nil
  1853. result = newString(bufsize)
  1854. while true:
  1855. var L = getFullPathNameA(filename, bufsize, result, unused)
  1856. if L == 0'i32:
  1857. raiseOSError(osLastError(), filename)
  1858. elif L > bufsize:
  1859. result = newString(L)
  1860. bufsize = L
  1861. else:
  1862. setLen(result, L)
  1863. break
  1864. # getFullPathName doesn't do case corrections, so we have to use this convoluted
  1865. # way of retrieving the true filename
  1866. for x in walkFiles(result):
  1867. result = x
  1868. if not fileExists(result) and not dirExists(result):
  1869. # consider using: `raiseOSError(osLastError(), result)`
  1870. raise newException(OSError, "file '" & result & "' does not exist")
  1871. else:
  1872. # according to Posix we don't need to allocate space for result pathname.
  1873. # But we need to free return value with free(3).
  1874. var r = realpath(filename, nil)
  1875. if r.isNil:
  1876. raiseOSError(osLastError(), filename)
  1877. else:
  1878. result = $r
  1879. c_free(cast[pointer](r))
  1880. type
  1881. PathComponent* = enum ## Enumeration specifying a path component.
  1882. ##
  1883. ## See also:
  1884. ## * `walkDirRec iterator <#walkDirRec.i,string>`_
  1885. ## * `FileInfo object <#FileInfo>`_
  1886. pcFile, ## path refers to a file
  1887. pcLinkToFile, ## path refers to a symbolic link to a file
  1888. pcDir, ## path refers to a directory
  1889. pcLinkToDir ## path refers to a symbolic link to a directory
  1890. proc getCurrentCompilerExe*(): string {.compileTime.} = discard
  1891. ## This is `getAppFilename() <#getAppFilename>`_ at compile time.
  1892. ##
  1893. ## Can be used to retrieve the currently executing
  1894. ## Nim compiler from a Nim or nimscript program, or the nimble binary
  1895. ## inside a nimble program (likewise with other binaries built from
  1896. ## compiler API).
  1897. when defined(posix) and not weirdTarget:
  1898. proc getSymlinkFileKind(path: string): PathComponent =
  1899. # Helper function.
  1900. var s: Stat
  1901. assert(path != "")
  1902. if stat(path, s) == 0'i32 and S_ISDIR(s.st_mode):
  1903. result = pcLinkToDir
  1904. else:
  1905. result = pcLinkToFile
  1906. proc staticWalkDir(dir: string; relative: bool): seq[
  1907. tuple[kind: PathComponent, path: string]] =
  1908. discard
  1909. iterator walkDir*(dir: string; relative = false, checkDir = false):
  1910. tuple[kind: PathComponent, path: string] {.tags: [ReadDirEffect].} =
  1911. ## Walks over the directory `dir` and yields for each directory or file in
  1912. ## `dir`. The component type and full path for each item are returned.
  1913. ##
  1914. ## Walking is not recursive. If ``relative`` is true (default: false)
  1915. ## the resulting path is shortened to be relative to ``dir``.
  1916. ## Example: This directory structure::
  1917. ## dirA / dirB / fileB1.txt
  1918. ## / dirC
  1919. ## / fileA1.txt
  1920. ## / fileA2.txt
  1921. ##
  1922. ## and this code:
  1923. ##
  1924. ## .. code-block:: Nim
  1925. ## for kind, path in walkDir("dirA"):
  1926. ## echo(path)
  1927. ##
  1928. ## produce this output (but not necessarily in this order!)::
  1929. ## dirA/dirB
  1930. ## dirA/dirC
  1931. ## dirA/fileA1.txt
  1932. ## dirA/fileA2.txt
  1933. ##
  1934. ## See also:
  1935. ## * `walkPattern iterator <#walkPattern.i,string>`_
  1936. ## * `walkFiles iterator <#walkFiles.i,string>`_
  1937. ## * `walkDirs iterator <#walkDirs.i,string>`_
  1938. ## * `walkDirRec iterator <#walkDirRec.i,string>`_
  1939. when nimvm:
  1940. for k, v in items(staticWalkDir(dir, relative)):
  1941. yield (k, v)
  1942. else:
  1943. when weirdTarget:
  1944. for k, v in items(staticWalkDir(dir, relative)):
  1945. yield (k, v)
  1946. elif defined(windows):
  1947. var f: WIN32_FIND_DATA
  1948. var h = findFirstFile(dir / "*", f)
  1949. if h == -1:
  1950. if checkDir:
  1951. raiseOSError(osLastError(), dir)
  1952. else:
  1953. defer: findClose(h)
  1954. while true:
  1955. var k = pcFile
  1956. if not skipFindData(f):
  1957. if (f.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY) != 0'i32:
  1958. k = pcDir
  1959. if (f.dwFileAttributes and FILE_ATTRIBUTE_REPARSE_POINT) != 0'i32:
  1960. k = succ(k)
  1961. let xx = if relative: extractFilename(getFilename(f))
  1962. else: dir / extractFilename(getFilename(f))
  1963. yield (k, xx)
  1964. if findNextFile(h, f) == 0'i32:
  1965. let errCode = getLastError()
  1966. if errCode == ERROR_NO_MORE_FILES: break
  1967. else: raiseOSError(errCode.OSErrorCode)
  1968. else:
  1969. var d = opendir(dir)
  1970. if d == nil:
  1971. if checkDir:
  1972. raiseOSError(osLastError(), dir)
  1973. else:
  1974. defer: discard closedir(d)
  1975. while true:
  1976. var x = readdir(d)
  1977. if x == nil: break
  1978. when defined(nimNoArrayToCstringConversion):
  1979. var y = $cstring(addr x.d_name)
  1980. else:
  1981. var y = $x.d_name.cstring
  1982. if y != "." and y != "..":
  1983. var s: Stat
  1984. let path = dir / y
  1985. if not relative:
  1986. y = path
  1987. var k = pcFile
  1988. when defined(linux) or defined(macosx) or
  1989. defined(bsd) or defined(genode) or defined(nintendoswitch):
  1990. if x.d_type != DT_UNKNOWN:
  1991. if x.d_type == DT_DIR: k = pcDir
  1992. if x.d_type == DT_LNK:
  1993. if dirExists(path): k = pcLinkToDir
  1994. else: k = pcLinkToFile
  1995. yield (k, y)
  1996. continue
  1997. if lstat(path, s) < 0'i32: break
  1998. if S_ISDIR(s.st_mode):
  1999. k = pcDir
  2000. elif S_ISLNK(s.st_mode):
  2001. k = getSymlinkFileKind(path)
  2002. yield (k, y)
  2003. iterator walkDirRec*(dir: string,
  2004. yieldFilter = {pcFile}, followFilter = {pcDir},
  2005. relative = false, checkDir = false): string {.tags: [ReadDirEffect].} =
  2006. ## Recursively walks over the directory `dir` and yields for each file
  2007. ## or directory in `dir`.
  2008. ##
  2009. ## If ``relative`` is true (default: false) the resulting path is
  2010. ## shortened to be relative to ``dir``, otherwise the full path is returned.
  2011. ##
  2012. ## **Warning**:
  2013. ## Modifying the directory structure while the iterator
  2014. ## is traversing may result in undefined behavior!
  2015. ##
  2016. ## Walking is recursive. `followFilter` controls the behaviour of the iterator:
  2017. ##
  2018. ## --------------------- ---------------------------------------------
  2019. ## yieldFilter meaning
  2020. ## --------------------- ---------------------------------------------
  2021. ## ``pcFile`` yield real files (default)
  2022. ## ``pcLinkToFile`` yield symbolic links to files
  2023. ## ``pcDir`` yield real directories
  2024. ## ``pcLinkToDir`` yield symbolic links to directories
  2025. ## --------------------- ---------------------------------------------
  2026. ##
  2027. ## --------------------- ---------------------------------------------
  2028. ## followFilter meaning
  2029. ## --------------------- ---------------------------------------------
  2030. ## ``pcDir`` follow real directories (default)
  2031. ## ``pcLinkToDir`` follow symbolic links to directories
  2032. ## --------------------- ---------------------------------------------
  2033. ##
  2034. ##
  2035. ## See also:
  2036. ## * `walkPattern iterator <#walkPattern.i,string>`_
  2037. ## * `walkFiles iterator <#walkFiles.i,string>`_
  2038. ## * `walkDirs iterator <#walkDirs.i,string>`_
  2039. ## * `walkDir iterator <#walkDir.i,string>`_
  2040. var stack = @[""]
  2041. var checkDir = checkDir
  2042. while stack.len > 0:
  2043. let d = stack.pop()
  2044. for k, p in walkDir(dir / d, relative = true, checkDir = checkDir):
  2045. let rel = d / p
  2046. if k in {pcDir, pcLinkToDir} and k in followFilter:
  2047. stack.add rel
  2048. if k in yieldFilter:
  2049. yield if relative: rel else: dir / rel
  2050. checkDir = false
  2051. # We only check top-level dir, otherwise if a subdir is invalid (eg. wrong
  2052. # permissions), it'll abort iteration and there would be no way to
  2053. # continue iteration.
  2054. # Future work can provide a way to customize this and do error reporting.
  2055. proc rawRemoveDir(dir: string) {.noWeirdTarget.} =
  2056. when defined(windows):
  2057. when useWinUnicode:
  2058. wrapUnary(res, removeDirectoryW, dir)
  2059. else:
  2060. var res = removeDirectoryA(dir)
  2061. let lastError = osLastError()
  2062. if res == 0'i32 and lastError.int32 != 3'i32 and
  2063. lastError.int32 != 18'i32 and lastError.int32 != 2'i32:
  2064. raiseOSError(lastError, dir)
  2065. else:
  2066. if rmdir(dir) != 0'i32 and errno != ENOENT: raiseOSError(osLastError(), dir)
  2067. proc removeDir*(dir: string, checkDir = false) {.rtl, extern: "nos$1", tags: [
  2068. WriteDirEffect, ReadDirEffect], benign, noWeirdTarget.} =
  2069. ## Removes the directory `dir` including all subdirectories and files
  2070. ## in `dir` (recursively).
  2071. ##
  2072. ## If this fails, `OSError` is raised. This does not fail if the directory never
  2073. ## existed in the first place, unless `checkDir` = true
  2074. ##
  2075. ## See also:
  2076. ## * `tryRemoveFile proc <#tryRemoveFile,string>`_
  2077. ## * `removeFile proc <#removeFile,string>`_
  2078. ## * `existsOrCreateDir proc <#existsOrCreateDir,string>`_
  2079. ## * `createDir proc <#createDir,string>`_
  2080. ## * `copyDir proc <#copyDir,string,string>`_
  2081. ## * `copyDirWithPermissions proc <#copyDirWithPermissions,string,string>`_
  2082. ## * `moveDir proc <#moveDir,string,string>`_
  2083. for kind, path in walkDir(dir, checkDir = checkDir):
  2084. case kind
  2085. of pcFile, pcLinkToFile, pcLinkToDir: removeFile(path)
  2086. of pcDir: removeDir(path, true)
  2087. # for subdirectories there is no benefit in `checkDir = false`
  2088. # (unless perhaps for edge case of concurrent processes also deleting
  2089. # the same files)
  2090. rawRemoveDir(dir)
  2091. proc rawCreateDir(dir: string): bool {.noWeirdTarget.} =
  2092. # Try to create one directory (not the whole path).
  2093. # returns `true` for success, `false` if the path has previously existed
  2094. #
  2095. # This is a thin wrapper over mkDir (or alternatives on other systems),
  2096. # so in case of a pre-existing path we don't check that it is a directory.
  2097. when defined(solaris):
  2098. let res = mkdir(dir, 0o777)
  2099. if res == 0'i32:
  2100. result = true
  2101. elif errno in {EEXIST, ENOSYS}:
  2102. result = false
  2103. else:
  2104. raiseOSError(osLastError(), dir)
  2105. elif defined(haiku):
  2106. let res = mkdir(dir, 0o777)
  2107. if res == 0'i32:
  2108. result = true
  2109. elif errno == EEXIST or errno == EROFS:
  2110. result = false
  2111. else:
  2112. raiseOSError(osLastError(), dir)
  2113. elif defined(posix):
  2114. let res = mkdir(dir, 0o777)
  2115. if res == 0'i32:
  2116. result = true
  2117. elif errno == EEXIST:
  2118. result = false
  2119. else:
  2120. #echo res
  2121. raiseOSError(osLastError(), dir)
  2122. else:
  2123. when useWinUnicode:
  2124. wrapUnary(res, createDirectoryW, dir)
  2125. else:
  2126. let res = createDirectoryA(dir)
  2127. if res != 0'i32:
  2128. result = true
  2129. elif getLastError() == 183'i32:
  2130. result = false
  2131. else:
  2132. raiseOSError(osLastError(), dir)
  2133. proc existsOrCreateDir*(dir: string): bool {.rtl, extern: "nos$1",
  2134. tags: [WriteDirEffect, ReadDirEffect], noWeirdTarget.} =
  2135. ## Check if a `directory`:idx: `dir` exists, and create it otherwise.
  2136. ##
  2137. ## Does not create parent directories (fails if parent does not exist).
  2138. ## Returns `true` if the directory already exists, and `false`
  2139. ## otherwise.
  2140. ##
  2141. ## See also:
  2142. ## * `removeDir proc <#removeDir,string>`_
  2143. ## * `createDir proc <#createDir,string>`_
  2144. ## * `copyDir proc <#copyDir,string,string>`_
  2145. ## * `copyDirWithPermissions proc <#copyDirWithPermissions,string,string>`_
  2146. ## * `moveDir proc <#moveDir,string,string>`_
  2147. result = not rawCreateDir(dir)
  2148. if result:
  2149. # path already exists - need to check that it is indeed a directory
  2150. if not dirExists(dir):
  2151. raise newException(IOError, "Failed to create '" & dir & "'")
  2152. proc createDir*(dir: string) {.rtl, extern: "nos$1",
  2153. tags: [WriteDirEffect, ReadDirEffect], noWeirdTarget.} =
  2154. ## Creates the `directory`:idx: `dir`.
  2155. ##
  2156. ## The directory may contain several subdirectories that do not exist yet.
  2157. ## The full path is created. If this fails, `OSError` is raised.
  2158. ##
  2159. ## It does **not** fail if the directory already exists because for
  2160. ## most usages this does not indicate an error.
  2161. ##
  2162. ## See also:
  2163. ## * `removeDir proc <#removeDir,string>`_
  2164. ## * `existsOrCreateDir proc <#existsOrCreateDir,string>`_
  2165. ## * `copyDir proc <#copyDir,string,string>`_
  2166. ## * `copyDirWithPermissions proc <#copyDirWithPermissions,string,string>`_
  2167. ## * `moveDir proc <#moveDir,string,string>`_
  2168. var omitNext = false
  2169. when doslikeFileSystem:
  2170. omitNext = isAbsolute(dir)
  2171. for i in 1.. dir.len-1:
  2172. if dir[i] in {DirSep, AltSep}:
  2173. if omitNext:
  2174. omitNext = false
  2175. else:
  2176. discard existsOrCreateDir(substr(dir, 0, i-1))
  2177. # The loop does not create the dir itself if it doesn't end in separator
  2178. if dir.len > 0 and not omitNext and
  2179. dir[^1] notin {DirSep, AltSep}:
  2180. discard existsOrCreateDir(dir)
  2181. proc copyDir*(source, dest: string) {.rtl, extern: "nos$1",
  2182. tags: [WriteIOEffect, ReadIOEffect], benign, noWeirdTarget.} =
  2183. ## Copies a directory from `source` to `dest`.
  2184. ##
  2185. ## If this fails, `OSError` is raised.
  2186. ##
  2187. ## On the Windows platform this proc will copy the attributes from
  2188. ## `source` into `dest`.
  2189. ##
  2190. ## On other platforms created files and directories will inherit the
  2191. ## default permissions of a newly created file/directory for the user.
  2192. ## Use `copyDirWithPermissions proc <#copyDirWithPermissions,string,string>`_
  2193. ## to preserve attributes recursively on these platforms.
  2194. ##
  2195. ## See also:
  2196. ## * `copyDirWithPermissions proc <#copyDirWithPermissions,string,string>`_
  2197. ## * `copyFile proc <#copyFile,string,string>`_
  2198. ## * `copyFileWithPermissions proc <#copyFileWithPermissions,string,string>`_
  2199. ## * `removeDir proc <#removeDir,string>`_
  2200. ## * `existsOrCreateDir proc <#existsOrCreateDir,string>`_
  2201. ## * `createDir proc <#createDir,string>`_
  2202. ## * `moveDir proc <#moveDir,string,string>`_
  2203. createDir(dest)
  2204. for kind, path in walkDir(source):
  2205. var noSource = splitPath(path).tail
  2206. case kind
  2207. of pcFile:
  2208. copyFile(path, dest / noSource)
  2209. of pcDir:
  2210. copyDir(path, dest / noSource)
  2211. else: discard
  2212. proc moveDir*(source, dest: string) {.tags: [ReadIOEffect, WriteIOEffect], noWeirdTarget.} =
  2213. ## Moves a directory from `source` to `dest`.
  2214. ##
  2215. ## If this fails, `OSError` is raised.
  2216. ##
  2217. ## See also:
  2218. ## * `moveFile proc <#moveFile,string,string>`_
  2219. ## * `copyDir proc <#copyDir,string,string>`_
  2220. ## * `copyDirWithPermissions proc <#copyDirWithPermissions,string,string>`_
  2221. ## * `removeDir proc <#removeDir,string>`_
  2222. ## * `existsOrCreateDir proc <#existsOrCreateDir,string>`_
  2223. ## * `createDir proc <#createDir,string>`_
  2224. if not tryMoveFSObject(source, dest):
  2225. when not defined(windows):
  2226. # Fallback to copy & del
  2227. copyDir(source, dest)
  2228. removeDir(source)
  2229. proc createSymlink*(src, dest: string) {.noWeirdTarget.} =
  2230. ## Create a symbolic link at `dest` which points to the item specified
  2231. ## by `src`. On most operating systems, will fail if a link already exists.
  2232. ##
  2233. ## **Warning**:
  2234. ## Some OS's (such as Microsoft Windows) restrict the creation
  2235. ## of symlinks to root users (administrators).
  2236. ##
  2237. ## See also:
  2238. ## * `createHardlink proc <#createHardlink,string,string>`_
  2239. ## * `expandSymlink proc <#expandSymlink,string>`_
  2240. when defined(Windows):
  2241. # 2 is the SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE. This allows
  2242. # anyone with developer mode on to create a link
  2243. let flag = dirExists(src).int32 or 2
  2244. when useWinUnicode:
  2245. var wSrc = newWideCString(src)
  2246. var wDst = newWideCString(dest)
  2247. if createSymbolicLinkW(wDst, wSrc, flag) == 0 or getLastError() != 0:
  2248. raiseOSError(osLastError(), $(src, dest))
  2249. else:
  2250. if createSymbolicLinkA(dest, src, flag) == 0 or getLastError() != 0:
  2251. raiseOSError(osLastError(), $(src, dest))
  2252. else:
  2253. if symlink(src, dest) != 0:
  2254. raiseOSError(osLastError(), $(src, dest))
  2255. proc createHardlink*(src, dest: string) {.noWeirdTarget.} =
  2256. ## Create a hard link at `dest` which points to the item specified
  2257. ## by `src`.
  2258. ##
  2259. ## **Warning**: Some OS's restrict the creation of hard links to
  2260. ## root users (administrators).
  2261. ##
  2262. ## See also:
  2263. ## * `createSymlink proc <#createSymlink,string,string>`_
  2264. when defined(Windows):
  2265. when useWinUnicode:
  2266. var wSrc = newWideCString(src)
  2267. var wDst = newWideCString(dest)
  2268. if createHardLinkW(wDst, wSrc, nil) == 0:
  2269. raiseOSError(osLastError(), $(src, dest))
  2270. else:
  2271. if createHardLinkA(dest, src, nil) == 0:
  2272. raiseOSError(osLastError(), $(src, dest))
  2273. else:
  2274. if link(src, dest) != 0:
  2275. raiseOSError(osLastError(), $(src, dest))
  2276. proc copyFileWithPermissions*(source, dest: string,
  2277. ignorePermissionErrors = true) {.noWeirdTarget.} =
  2278. ## Copies a file from `source` to `dest` preserving file permissions.
  2279. ##
  2280. ## This is a wrapper proc around `copyFile <#copyFile,string,string>`_,
  2281. ## `getFilePermissions <#getFilePermissions,string>`_ and
  2282. ## `setFilePermissions<#setFilePermissions,string,set[FilePermission]>`_
  2283. ## procs on non-Windows platforms.
  2284. ##
  2285. ## On Windows this proc is just a wrapper for `copyFile proc
  2286. ## <#copyFile,string,string>`_ since that proc already copies attributes.
  2287. ##
  2288. ## On non-Windows systems permissions are copied after the file itself has
  2289. ## been copied, which won't happen atomically and could lead to a race
  2290. ## condition. If `ignorePermissionErrors` is true (default), errors while
  2291. ## reading/setting file attributes will be ignored, otherwise will raise
  2292. ## `OSError`.
  2293. ##
  2294. ## See also:
  2295. ## * `copyFile proc <#copyFile,string,string>`_
  2296. ## * `copyDir proc <#copyDir,string,string>`_
  2297. ## * `tryRemoveFile proc <#tryRemoveFile,string>`_
  2298. ## * `removeFile proc <#removeFile,string>`_
  2299. ## * `moveFile proc <#moveFile,string,string>`_
  2300. ## * `copyDirWithPermissions proc <#copyDirWithPermissions,string,string>`_
  2301. copyFile(source, dest)
  2302. when not defined(Windows):
  2303. try:
  2304. setFilePermissions(dest, getFilePermissions(source))
  2305. except:
  2306. if not ignorePermissionErrors:
  2307. raise
  2308. proc copyDirWithPermissions*(source, dest: string,
  2309. ignorePermissionErrors = true) {.rtl, extern: "nos$1",
  2310. tags: [WriteIOEffect, ReadIOEffect], benign, noWeirdTarget.} =
  2311. ## Copies a directory from `source` to `dest` preserving file permissions.
  2312. ##
  2313. ## If this fails, `OSError` is raised. This is a wrapper proc around `copyDir
  2314. ## <#copyDir,string,string>`_ and `copyFileWithPermissions
  2315. ## <#copyFileWithPermissions,string,string>`_ procs
  2316. ## on non-Windows platforms.
  2317. ##
  2318. ## On Windows this proc is just a wrapper for `copyDir proc
  2319. ## <#copyDir,string,string>`_ since that proc already copies attributes.
  2320. ##
  2321. ## On non-Windows systems permissions are copied after the file or directory
  2322. ## itself has been copied, which won't happen atomically and could lead to a
  2323. ## race condition. If `ignorePermissionErrors` is true (default), errors while
  2324. ## reading/setting file attributes will be ignored, otherwise will raise
  2325. ## `OSError`.
  2326. ##
  2327. ## See also:
  2328. ## * `copyDir proc <#copyDir,string,string>`_
  2329. ## * `copyFile proc <#copyFile,string,string>`_
  2330. ## * `copyFileWithPermissions proc <#copyFileWithPermissions,string,string>`_
  2331. ## * `removeDir proc <#removeDir,string>`_
  2332. ## * `moveDir proc <#moveDir,string,string>`_
  2333. ## * `existsOrCreateDir proc <#existsOrCreateDir,string>`_
  2334. ## * `createDir proc <#createDir,string>`_
  2335. createDir(dest)
  2336. when not defined(Windows):
  2337. try:
  2338. setFilePermissions(dest, getFilePermissions(source))
  2339. except:
  2340. if not ignorePermissionErrors:
  2341. raise
  2342. for kind, path in walkDir(source):
  2343. var noSource = splitPath(path).tail
  2344. case kind
  2345. of pcFile:
  2346. copyFileWithPermissions(path, dest / noSource, ignorePermissionErrors)
  2347. of pcDir:
  2348. copyDirWithPermissions(path, dest / noSource, ignorePermissionErrors)
  2349. else: discard
  2350. proc inclFilePermissions*(filename: string,
  2351. permissions: set[FilePermission]) {.
  2352. rtl, extern: "nos$1", tags: [ReadDirEffect, WriteDirEffect], noWeirdTarget.} =
  2353. ## A convenience proc for:
  2354. ##
  2355. ## .. code-block:: nim
  2356. ## setFilePermissions(filename, getFilePermissions(filename)+permissions)
  2357. setFilePermissions(filename, getFilePermissions(filename)+permissions)
  2358. proc exclFilePermissions*(filename: string,
  2359. permissions: set[FilePermission]) {.
  2360. rtl, extern: "nos$1", tags: [ReadDirEffect, WriteDirEffect], noWeirdTarget.} =
  2361. ## A convenience proc for:
  2362. ##
  2363. ## .. code-block:: nim
  2364. ## setFilePermissions(filename, getFilePermissions(filename)-permissions)
  2365. setFilePermissions(filename, getFilePermissions(filename)-permissions)
  2366. proc expandSymlink*(symlinkPath: string): string {.noWeirdTarget.} =
  2367. ## Returns a string representing the path to which the symbolic link points.
  2368. ##
  2369. ## On Windows this is a noop, ``symlinkPath`` is simply returned.
  2370. ##
  2371. ## See also:
  2372. ## * `createSymlink proc <#createSymlink,string,string>`_
  2373. when defined(windows):
  2374. result = symlinkPath
  2375. else:
  2376. result = newString(256)
  2377. var len = readlink(symlinkPath, result, 256)
  2378. if len < 0:
  2379. raiseOSError(osLastError(), symlinkPath)
  2380. if len > 256:
  2381. result = newString(len+1)
  2382. len = readlink(symlinkPath, result, len)
  2383. setLen(result, len)
  2384. proc parseCmdLine*(c: string): seq[string] {.
  2385. noSideEffect, rtl, extern: "nos$1".} =
  2386. ## Splits a `command line`:idx: into several components.
  2387. ##
  2388. ## **Note**: This proc is only occasionally useful, better use the
  2389. ## `parseopt module <parseopt.html>`_.
  2390. ##
  2391. ## On Windows, it uses the `following parsing rules
  2392. ## <http://msdn.microsoft.com/en-us/library/17w5ykft.aspx>`_:
  2393. ##
  2394. ## * Arguments are delimited by white space, which is either a space or a tab.
  2395. ## * The caret character (^) is not recognized as an escape character or
  2396. ## delimiter. The character is handled completely by the command-line parser
  2397. ## in the operating system before being passed to the argv array in the
  2398. ## program.
  2399. ## * A string surrounded by double quotation marks ("string") is interpreted
  2400. ## as a single argument, regardless of white space contained within. A
  2401. ## quoted string can be embedded in an argument.
  2402. ## * A double quotation mark preceded by a backslash (\") is interpreted as a
  2403. ## literal double quotation mark character (").
  2404. ## * Backslashes are interpreted literally, unless they immediately precede
  2405. ## a double quotation mark.
  2406. ## * If an even number of backslashes is followed by a double quotation mark,
  2407. ## one backslash is placed in the argv array for every pair of backslashes,
  2408. ## and the double quotation mark is interpreted as a string delimiter.
  2409. ## * If an odd number of backslashes is followed by a double quotation mark,
  2410. ## one backslash is placed in the argv array for every pair of backslashes,
  2411. ## and the double quotation mark is "escaped" by the remaining backslash,
  2412. ## causing a literal double quotation mark (") to be placed in argv.
  2413. ##
  2414. ## On Posix systems, it uses the following parsing rules:
  2415. ## Components are separated by whitespace unless the whitespace
  2416. ## occurs within ``"`` or ``'`` quotes.
  2417. ##
  2418. ## See also:
  2419. ## * `parseopt module <parseopt.html>`_
  2420. ## * `paramCount proc <#paramCount>`_
  2421. ## * `paramStr proc <#paramStr,int>`_
  2422. ## * `commandLineParams proc <#commandLineParams>`_
  2423. result = @[]
  2424. var i = 0
  2425. var a = ""
  2426. while true:
  2427. setLen(a, 0)
  2428. # eat all delimiting whitespace
  2429. while i < c.len and c[i] in {' ', '\t', '\l', '\r'}: inc(i)
  2430. if i >= c.len: break
  2431. when defined(windows):
  2432. # parse a single argument according to the above rules:
  2433. var inQuote = false
  2434. while i < c.len:
  2435. case c[i]
  2436. of '\\':
  2437. var j = i
  2438. while j < c.len and c[j] == '\\': inc(j)
  2439. if j < c.len and c[j] == '"':
  2440. for k in 1..(j-i) div 2: a.add('\\')
  2441. if (j-i) mod 2 == 0:
  2442. i = j
  2443. else:
  2444. a.add('"')
  2445. i = j+1
  2446. else:
  2447. a.add(c[i])
  2448. inc(i)
  2449. of '"':
  2450. inc(i)
  2451. if not inQuote: inQuote = true
  2452. elif i < c.len and c[i] == '"':
  2453. a.add(c[i])
  2454. inc(i)
  2455. else:
  2456. inQuote = false
  2457. break
  2458. of ' ', '\t':
  2459. if not inQuote: break
  2460. a.add(c[i])
  2461. inc(i)
  2462. else:
  2463. a.add(c[i])
  2464. inc(i)
  2465. else:
  2466. case c[i]
  2467. of '\'', '\"':
  2468. var delim = c[i]
  2469. inc(i) # skip ' or "
  2470. while i < c.len and c[i] != delim:
  2471. add a, c[i]
  2472. inc(i)
  2473. if i < c.len: inc(i)
  2474. else:
  2475. while i < c.len and c[i] > ' ':
  2476. add(a, c[i])
  2477. inc(i)
  2478. add(result, a)
  2479. when defined(nimdoc):
  2480. # Common forward declaration docstring block for parameter retrieval procs.
  2481. proc paramCount*(): int {.tags: [ReadIOEffect].} =
  2482. ## Returns the number of `command line arguments`:idx: given to the
  2483. ## application.
  2484. ##
  2485. ## Unlike `argc`:idx: in C, if your binary was called without parameters this
  2486. ## will return zero.
  2487. ## You can query each individual parameter with `paramStr proc <#paramStr,int>`_
  2488. ## or retrieve all of them in one go with `commandLineParams proc
  2489. ## <#commandLineParams>`_.
  2490. ##
  2491. ## **Availability**: When generating a dynamic library (see `--app:lib`) on
  2492. ## Posix this proc is not defined.
  2493. ## Test for availability using `declared() <system.html#declared,untyped>`_.
  2494. ##
  2495. ## See also:
  2496. ## * `parseopt module <parseopt.html>`_
  2497. ## * `parseCmdLine proc <#parseCmdLine,string>`_
  2498. ## * `paramStr proc <#paramStr,int>`_
  2499. ## * `commandLineParams proc <#commandLineParams>`_
  2500. ##
  2501. ## **Examples:**
  2502. ##
  2503. ## .. code-block:: nim
  2504. ## when declared(paramCount):
  2505. ## # Use paramCount() here
  2506. ## else:
  2507. ## # Do something else!
  2508. proc paramStr*(i: int): TaintedString {.tags: [ReadIOEffect].} =
  2509. ## Returns the `i`-th `command line argument`:idx: given to the application.
  2510. ##
  2511. ## `i` should be in the range `1..paramCount()`, the `IndexDefect`
  2512. ## exception will be raised for invalid values. Instead of iterating over
  2513. ## `paramCount() <#paramCount>`_ with this proc you can call the
  2514. ## convenience `commandLineParams() <#commandLineParams>`_.
  2515. ##
  2516. ## Similarly to `argv`:idx: in C,
  2517. ## it is possible to call ``paramStr(0)`` but this will return OS specific
  2518. ## contents (usually the name of the invoked executable). You should avoid
  2519. ## this and call `getAppFilename() <#getAppFilename>`_ instead.
  2520. ##
  2521. ## **Availability**: When generating a dynamic library (see `--app:lib`) on
  2522. ## Posix this proc is not defined.
  2523. ## Test for availability using `declared() <system.html#declared,untyped>`_.
  2524. ##
  2525. ## See also:
  2526. ## * `parseopt module <parseopt.html>`_
  2527. ## * `parseCmdLine proc <#parseCmdLine,string>`_
  2528. ## * `paramCount proc <#paramCount>`_
  2529. ## * `commandLineParams proc <#commandLineParams>`_
  2530. ## * `getAppFilename proc <#getAppFilename>`_
  2531. ##
  2532. ## **Examples:**
  2533. ##
  2534. ## .. code-block:: nim
  2535. ## when declared(paramStr):
  2536. ## # Use paramStr() here
  2537. ## else:
  2538. ## # Do something else!
  2539. elif defined(nimscript): discard
  2540. elif defined(nintendoswitch) or weirdTarget:
  2541. proc paramStr*(i: int): TaintedString {.tags: [ReadIOEffect].} =
  2542. raise newException(OSError, "paramStr is not implemented on Nintendo Switch")
  2543. proc paramCount*(): int {.tags: [ReadIOEffect].} =
  2544. raise newException(OSError, "paramCount is not implemented on Nintendo Switch")
  2545. elif defined(windows):
  2546. # Since we support GUI applications with Nim, we sometimes generate
  2547. # a WinMain entry proc. But a WinMain proc has no access to the parsed
  2548. # command line arguments. The way to get them differs. Thus we parse them
  2549. # ourselves. This has the additional benefit that the program's behaviour
  2550. # is always the same -- independent of the used C compiler.
  2551. var
  2552. ownArgv {.threadvar.}: seq[string]
  2553. ownParsedArgv {.threadvar.}: bool
  2554. proc paramCount*(): int {.rtl, extern: "nos$1", tags: [ReadIOEffect].} =
  2555. # Docstring in nimdoc block.
  2556. if not ownParsedArgv:
  2557. ownArgv = parseCmdLine($getCommandLine())
  2558. ownParsedArgv = true
  2559. result = ownArgv.len-1
  2560. proc paramStr*(i: int): TaintedString {.rtl, extern: "nos$1",
  2561. tags: [ReadIOEffect].} =
  2562. # Docstring in nimdoc block.
  2563. if not ownParsedArgv:
  2564. ownArgv = parseCmdLine($getCommandLine())
  2565. ownParsedArgv = true
  2566. if i < ownArgv.len and i >= 0: return TaintedString(ownArgv[i])
  2567. raise newException(IndexDefect, formatErrorIndexBound(i, ownArgv.len-1))
  2568. elif defined(genode):
  2569. proc paramStr*(i: int): TaintedString =
  2570. raise newException(OSError, "paramStr is not implemented on Genode")
  2571. proc paramCount*(): int =
  2572. raise newException(OSError, "paramCount is not implemented on Genode")
  2573. elif not defined(createNimRtl) and
  2574. not(defined(posix) and appType == "lib"):
  2575. # On Posix, there is no portable way to get the command line from a DLL.
  2576. var
  2577. cmdCount {.importc: "cmdCount".}: cint
  2578. cmdLine {.importc: "cmdLine".}: cstringArray
  2579. proc paramStr*(i: int): TaintedString {.tags: [ReadIOEffect].} =
  2580. # Docstring in nimdoc block.
  2581. if i < cmdCount and i >= 0: return TaintedString($cmdLine[i])
  2582. raise newException(IndexDefect, formatErrorIndexBound(i, cmdCount-1))
  2583. proc paramCount*(): int {.tags: [ReadIOEffect].} =
  2584. # Docstring in nimdoc block.
  2585. result = cmdCount-1
  2586. when declared(paramCount) or defined(nimdoc):
  2587. proc commandLineParams*(): seq[TaintedString] =
  2588. ## Convenience proc which returns the command line parameters.
  2589. ##
  2590. ## This returns **only** the parameters. If you want to get the application
  2591. ## executable filename, call `getAppFilename() <#getAppFilename>`_.
  2592. ##
  2593. ## **Availability**: On Posix there is no portable way to get the command
  2594. ## line from a DLL and thus the proc isn't defined in this environment. You
  2595. ## can test for its availability with `declared()
  2596. ## <system.html#declared,untyped>`_.
  2597. ##
  2598. ## See also:
  2599. ## * `parseopt module <parseopt.html>`_
  2600. ## * `parseCmdLine proc <#parseCmdLine,string>`_
  2601. ## * `paramCount proc <#paramCount>`_
  2602. ## * `paramStr proc <#paramStr,int>`_
  2603. ## * `getAppFilename proc <#getAppFilename>`_
  2604. ##
  2605. ## **Examples:**
  2606. ##
  2607. ## .. code-block:: nim
  2608. ## when declared(commandLineParams):
  2609. ## # Use commandLineParams() here
  2610. ## else:
  2611. ## # Do something else!
  2612. result = @[]
  2613. for i in 1..paramCount():
  2614. result.add(paramStr(i))
  2615. else:
  2616. proc commandLineParams*(): seq[TaintedString] {.error:
  2617. "commandLineParams() unsupported by dynamic libraries".} =
  2618. discard
  2619. when not weirdTarget and (defined(freebsd) or defined(dragonfly) or defined(netbsd)):
  2620. proc sysctl(name: ptr cint, namelen: cuint, oldp: pointer, oldplen: ptr csize_t,
  2621. newp: pointer, newplen: csize_t): cint
  2622. {.importc: "sysctl",header: """#include <sys/types.h>
  2623. #include <sys/sysctl.h>"""}
  2624. const
  2625. CTL_KERN = 1
  2626. KERN_PROC = 14
  2627. MAX_PATH = 1024
  2628. when defined(freebsd):
  2629. const KERN_PROC_PATHNAME = 12
  2630. elif defined(netbsd):
  2631. const KERN_PROC_ARGS = 48
  2632. const KERN_PROC_PATHNAME = 5
  2633. else:
  2634. const KERN_PROC_PATHNAME = 9
  2635. proc getApplFreebsd(): string =
  2636. var pathLength = csize_t(0)
  2637. when defined(netbsd):
  2638. var req = [CTL_KERN.cint, KERN_PROC_ARGS.cint, -1.cint, KERN_PROC_PATHNAME.cint]
  2639. else:
  2640. var req = [CTL_KERN.cint, KERN_PROC.cint, KERN_PROC_PATHNAME.cint, -1.cint]
  2641. # first call to get the required length
  2642. var res = sysctl(addr req[0], 4, nil, addr pathLength, nil, 0)
  2643. if res < 0:
  2644. return ""
  2645. result.setLen(pathLength)
  2646. res = sysctl(addr req[0], 4, addr result[0], addr pathLength, nil, 0)
  2647. if res < 0:
  2648. return ""
  2649. let realLen = len(cstring(result))
  2650. setLen(result, realLen)
  2651. when not weirdTarget and (defined(linux) or defined(solaris) or defined(bsd) or defined(aix)):
  2652. proc getApplAux(procPath: string): string =
  2653. result = newString(256)
  2654. var len = readlink(procPath, result, 256)
  2655. if len > 256:
  2656. result = newString(len+1)
  2657. len = readlink(procPath, result, len)
  2658. setLen(result, len)
  2659. when not weirdTarget and defined(openbsd):
  2660. proc getApplOpenBsd(): string =
  2661. # similar to getApplHeuristic, but checks current working directory
  2662. when declared(paramStr):
  2663. result = ""
  2664. # POSIX guaranties that this contains the executable
  2665. # as it has been executed by the calling process
  2666. let exePath = string(paramStr(0))
  2667. if len(exePath) == 0:
  2668. return ""
  2669. if exePath[0] == DirSep:
  2670. # path is absolute
  2671. result = exePath
  2672. else:
  2673. # not an absolute path, check if it's relative to the current working directory
  2674. for i in 1..<len(exePath):
  2675. if exePath[i] == DirSep:
  2676. result = joinPath(getCurrentDir(), exePath)
  2677. break
  2678. if len(result) > 0:
  2679. return expandFilename(result)
  2680. # search in path
  2681. for p in split(string(getEnv("PATH")), {PathSep}):
  2682. var x = joinPath(p, exePath)
  2683. if fileExists(x):
  2684. return expandFilename(x)
  2685. else:
  2686. result = ""
  2687. when not (defined(windows) or defined(macosx) or weirdTarget):
  2688. proc getApplHeuristic(): string =
  2689. when declared(paramStr):
  2690. result = string(paramStr(0))
  2691. # POSIX guaranties that this contains the executable
  2692. # as it has been executed by the calling process
  2693. if len(result) > 0 and result[0] != DirSep: # not an absolute path?
  2694. # iterate over any path in the $PATH environment variable
  2695. for p in split(string(getEnv("PATH")), {PathSep}):
  2696. var x = joinPath(p, result)
  2697. if fileExists(x): return x
  2698. else:
  2699. result = ""
  2700. when defined(macosx):
  2701. type
  2702. cuint32* {.importc: "unsigned int", nodecl.} = int
  2703. ## This is the same as the type ``uint32_t`` in *C*.
  2704. # a really hacky solution: since we like to include 2 headers we have to
  2705. # define two procs which in reality are the same
  2706. proc getExecPath1(c: cstring, size: var cuint32) {.
  2707. importc: "_NSGetExecutablePath", header: "<sys/param.h>".}
  2708. proc getExecPath2(c: cstring, size: var cuint32): bool {.
  2709. importc: "_NSGetExecutablePath", header: "<mach-o/dyld.h>".}
  2710. when defined(haiku):
  2711. const
  2712. PATH_MAX = 1024
  2713. B_FIND_PATH_IMAGE_PATH = 1000
  2714. proc find_path(codePointer: pointer, baseDirectory: cint, subPath: cstring,
  2715. pathBuffer: cstring, bufferSize: csize): int32
  2716. {.importc, header: "<FindDirectory.h>".}
  2717. proc getApplHaiku(): string =
  2718. result = newString(PATH_MAX)
  2719. if find_path(nil, B_FIND_PATH_IMAGE_PATH, nil, result, PATH_MAX) == 0:
  2720. let realLen = len(cstring(result))
  2721. setLen(result, realLen)
  2722. else:
  2723. result = ""
  2724. proc getAppFilename*(): string {.rtl, extern: "nos$1", tags: [ReadIOEffect], noWeirdTarget.} =
  2725. ## Returns the filename of the application's executable.
  2726. ## This proc will resolve symlinks.
  2727. ##
  2728. ## See also:
  2729. ## * `getAppDir proc <#getAppDir>`_
  2730. ## * `getCurrentCompilerExe proc <#getCurrentCompilerExe>`_
  2731. # Linux: /proc/<pid>/exe
  2732. # Solaris:
  2733. # /proc/<pid>/object/a.out (filename only)
  2734. # /proc/<pid>/path/a.out (complete pathname)
  2735. when defined(windows):
  2736. var bufsize = int32(MAX_PATH)
  2737. when useWinUnicode:
  2738. var buf = newWideCString("", bufsize)
  2739. while true:
  2740. var L = getModuleFileNameW(0, buf, bufsize)
  2741. if L == 0'i32:
  2742. result = "" # error!
  2743. break
  2744. elif L > bufsize:
  2745. buf = newWideCString("", L)
  2746. bufsize = L
  2747. else:
  2748. result = buf$L
  2749. break
  2750. else:
  2751. result = newString(bufsize)
  2752. while true:
  2753. var L = getModuleFileNameA(0, result, bufsize)
  2754. if L == 0'i32:
  2755. result = "" # error!
  2756. break
  2757. elif L > bufsize:
  2758. result = newString(L)
  2759. bufsize = L
  2760. else:
  2761. setLen(result, L)
  2762. break
  2763. elif defined(macosx):
  2764. var size = cuint32(0)
  2765. getExecPath1(nil, size)
  2766. result = newString(int(size))
  2767. if getExecPath2(result, size):
  2768. result = "" # error!
  2769. if result.len > 0:
  2770. result = result.expandFilename
  2771. else:
  2772. when defined(linux) or defined(aix):
  2773. result = getApplAux("/proc/self/exe")
  2774. elif defined(solaris):
  2775. result = getApplAux("/proc/" & $getpid() & "/path/a.out")
  2776. elif defined(genode) or defined(nintendoswitch):
  2777. raiseOSError(OSErrorCode(-1), "POSIX command line not supported")
  2778. elif defined(freebsd) or defined(dragonfly) or defined(netbsd):
  2779. result = getApplFreebsd()
  2780. elif defined(haiku):
  2781. result = getApplHaiku()
  2782. elif defined(openbsd):
  2783. result = getApplOpenBsd()
  2784. # little heuristic that may work on other POSIX-like systems:
  2785. if result.len == 0:
  2786. result = getApplHeuristic()
  2787. proc getAppDir*(): string {.rtl, extern: "nos$1", tags: [ReadIOEffect], noWeirdTarget.} =
  2788. ## Returns the directory of the application's executable.
  2789. ##
  2790. ## See also:
  2791. ## * `getAppFilename proc <#getAppFilename>`_
  2792. result = splitFile(getAppFilename()).dir
  2793. proc sleep*(milsecs: int) {.rtl, extern: "nos$1", tags: [TimeEffect], noWeirdTarget.} =
  2794. ## Sleeps `milsecs` milliseconds.
  2795. when defined(windows):
  2796. winlean.sleep(int32(milsecs))
  2797. else:
  2798. var a, b: Timespec
  2799. a.tv_sec = posix.Time(milsecs div 1000)
  2800. a.tv_nsec = (milsecs mod 1000) * 1000 * 1000
  2801. discard posix.nanosleep(a, b)
  2802. proc getFileSize*(file: string): BiggestInt {.rtl, extern: "nos$1",
  2803. tags: [ReadIOEffect], noWeirdTarget.} =
  2804. ## Returns the file size of `file` (in bytes). ``OSError`` is
  2805. ## raised in case of an error.
  2806. when defined(windows):
  2807. var a: WIN32_FIND_DATA
  2808. var resA = findFirstFile(file, a)
  2809. if resA == -1: raiseOSError(osLastError(), file)
  2810. result = rdFileSize(a)
  2811. findClose(resA)
  2812. else:
  2813. var f: File
  2814. if open(f, file):
  2815. result = getFileSize(f)
  2816. close(f)
  2817. else: raiseOSError(osLastError(), file)
  2818. when defined(Windows) or weirdTarget:
  2819. type
  2820. DeviceId* = int32
  2821. FileId* = int64
  2822. else:
  2823. type
  2824. DeviceId* = Dev
  2825. FileId* = Ino
  2826. type
  2827. FileInfo* = object
  2828. ## Contains information associated with a file object.
  2829. ##
  2830. ## See also:
  2831. ## * `getFileInfo(handle) proc <#getFileInfo,FileHandle>`_
  2832. ## * `getFileInfo(file) proc <#getFileInfo,File>`_
  2833. ## * `getFileInfo(path) proc <#getFileInfo,string>`_
  2834. id*: tuple[device: DeviceId, file: FileId] ## Device and file id.
  2835. kind*: PathComponent ## Kind of file object - directory, symlink, etc.
  2836. size*: BiggestInt ## Size of file.
  2837. permissions*: set[FilePermission] ## File permissions
  2838. linkCount*: BiggestInt ## Number of hard links the file object has.
  2839. lastAccessTime*: times.Time ## Time file was last accessed.
  2840. lastWriteTime*: times.Time ## Time file was last modified/written to.
  2841. creationTime*: times.Time ## Time file was created. Not supported on all systems!
  2842. template rawToFormalFileInfo(rawInfo, path, formalInfo): untyped =
  2843. ## Transforms the native file info structure into the one nim uses.
  2844. ## 'rawInfo' is either a 'BY_HANDLE_FILE_INFORMATION' structure on Windows,
  2845. ## or a 'Stat' structure on posix
  2846. when defined(Windows):
  2847. template merge(a, b): untyped = a or (b shl 32)
  2848. formalInfo.id.device = rawInfo.dwVolumeSerialNumber
  2849. formalInfo.id.file = merge(rawInfo.nFileIndexLow, rawInfo.nFileIndexHigh)
  2850. formalInfo.size = merge(rawInfo.nFileSizeLow, rawInfo.nFileSizeHigh)
  2851. formalInfo.linkCount = rawInfo.nNumberOfLinks
  2852. formalInfo.lastAccessTime = fromWinTime(rdFileTime(rawInfo.ftLastAccessTime))
  2853. formalInfo.lastWriteTime = fromWinTime(rdFileTime(rawInfo.ftLastWriteTime))
  2854. formalInfo.creationTime = fromWinTime(rdFileTime(rawInfo.ftCreationTime))
  2855. # Retrieve basic permissions
  2856. if (rawInfo.dwFileAttributes and FILE_ATTRIBUTE_READONLY) != 0'i32:
  2857. formalInfo.permissions = {fpUserExec, fpUserRead, fpGroupExec,
  2858. fpGroupRead, fpOthersExec, fpOthersRead}
  2859. else:
  2860. formalInfo.permissions = {fpUserExec..fpOthersRead}
  2861. # Retrieve basic file kind
  2862. if (rawInfo.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY) != 0'i32:
  2863. formalInfo.kind = pcDir
  2864. else:
  2865. formalInfo.kind = pcFile
  2866. if (rawInfo.dwFileAttributes and FILE_ATTRIBUTE_REPARSE_POINT) != 0'i32:
  2867. formalInfo.kind = succ(formalInfo.kind)
  2868. else:
  2869. template checkAndIncludeMode(rawMode, formalMode: untyped) =
  2870. if (rawInfo.st_mode and rawMode.Mode) != 0.Mode:
  2871. formalInfo.permissions.incl(formalMode)
  2872. formalInfo.id = (rawInfo.st_dev, rawInfo.st_ino)
  2873. formalInfo.size = rawInfo.st_size
  2874. formalInfo.linkCount = rawInfo.st_nlink.BiggestInt
  2875. formalInfo.lastAccessTime = rawInfo.st_atim.toTime
  2876. formalInfo.lastWriteTime = rawInfo.st_mtim.toTime
  2877. formalInfo.creationTime = rawInfo.st_ctim.toTime
  2878. formalInfo.permissions = {}
  2879. checkAndIncludeMode(S_IRUSR, fpUserRead)
  2880. checkAndIncludeMode(S_IWUSR, fpUserWrite)
  2881. checkAndIncludeMode(S_IXUSR, fpUserExec)
  2882. checkAndIncludeMode(S_IRGRP, fpGroupRead)
  2883. checkAndIncludeMode(S_IWGRP, fpGroupWrite)
  2884. checkAndIncludeMode(S_IXGRP, fpGroupExec)
  2885. checkAndIncludeMode(S_IROTH, fpOthersRead)
  2886. checkAndIncludeMode(S_IWOTH, fpOthersWrite)
  2887. checkAndIncludeMode(S_IXOTH, fpOthersExec)
  2888. formalInfo.kind =
  2889. if S_ISDIR(rawInfo.st_mode):
  2890. pcDir
  2891. elif S_ISLNK(rawInfo.st_mode):
  2892. assert(path != "") # symlinks can't occur for file handles
  2893. getSymlinkFileKind(path)
  2894. else:
  2895. pcFile
  2896. when defined(js):
  2897. when not declared(FileHandle):
  2898. type FileHandle = distinct int32
  2899. when not declared(File):
  2900. type File = object
  2901. proc getFileInfo*(handle: FileHandle): FileInfo {.noWeirdTarget.} =
  2902. ## Retrieves file information for the file object represented by the given
  2903. ## handle.
  2904. ##
  2905. ## If the information cannot be retrieved, such as when the file handle
  2906. ## is invalid, `OSError` is raised.
  2907. ##
  2908. ## See also:
  2909. ## * `getFileInfo(file) proc <#getFileInfo,File>`_
  2910. ## * `getFileInfo(path) proc <#getFileInfo,string>`_
  2911. # Done: ID, Kind, Size, Permissions, Link Count
  2912. when defined(Windows):
  2913. var rawInfo: BY_HANDLE_FILE_INFORMATION
  2914. # We have to use the super special '_get_osfhandle' call (wrapped above)
  2915. # To transform the C file descriptor to a native file handle.
  2916. var realHandle = get_osfhandle(handle)
  2917. if getFileInformationByHandle(realHandle, addr rawInfo) == 0:
  2918. raiseOSError(osLastError(), $handle)
  2919. rawToFormalFileInfo(rawInfo, "", result)
  2920. else:
  2921. var rawInfo: Stat
  2922. if fstat(handle, rawInfo) < 0'i32:
  2923. raiseOSError(osLastError(), $handle)
  2924. rawToFormalFileInfo(rawInfo, "", result)
  2925. proc getFileInfo*(file: File): FileInfo {.noWeirdTarget.} =
  2926. ## Retrieves file information for the file object.
  2927. ##
  2928. ## See also:
  2929. ## * `getFileInfo(handle) proc <#getFileInfo,FileHandle>`_
  2930. ## * `getFileInfo(path) proc <#getFileInfo,string>`_
  2931. if file.isNil:
  2932. raise newException(IOError, "File is nil")
  2933. result = getFileInfo(file.getFileHandle())
  2934. proc getFileInfo*(path: string, followSymlink = true): FileInfo {.noWeirdTarget.} =
  2935. ## Retrieves file information for the file object pointed to by `path`.
  2936. ##
  2937. ## Due to intrinsic differences between operating systems, the information
  2938. ## contained by the returned `FileInfo object <#FileInfo>`_ will be slightly
  2939. ## different across platforms, and in some cases, incomplete or inaccurate.
  2940. ##
  2941. ## When `followSymlink` is true (default), symlinks are followed and the
  2942. ## information retrieved is information related to the symlink's target.
  2943. ## Otherwise, information on the symlink itself is retrieved.
  2944. ##
  2945. ## If the information cannot be retrieved, such as when the path doesn't
  2946. ## exist, or when permission restrictions prevent the program from retrieving
  2947. ## file information, `OSError` is raised.
  2948. ##
  2949. ## See also:
  2950. ## * `getFileInfo(handle) proc <#getFileInfo,FileHandle>`_
  2951. ## * `getFileInfo(file) proc <#getFileInfo,File>`_
  2952. when defined(Windows):
  2953. var
  2954. handle = openHandle(path, followSymlink)
  2955. rawInfo: BY_HANDLE_FILE_INFORMATION
  2956. if handle == INVALID_HANDLE_VALUE:
  2957. raiseOSError(osLastError(), path)
  2958. if getFileInformationByHandle(handle, addr rawInfo) == 0:
  2959. raiseOSError(osLastError(), path)
  2960. rawToFormalFileInfo(rawInfo, path, result)
  2961. discard closeHandle(handle)
  2962. else:
  2963. var rawInfo: Stat
  2964. if followSymlink:
  2965. if stat(path, rawInfo) < 0'i32:
  2966. raiseOSError(osLastError(), path)
  2967. else:
  2968. if lstat(path, rawInfo) < 0'i32:
  2969. raiseOSError(osLastError(), path)
  2970. rawToFormalFileInfo(rawInfo, path, result)
  2971. proc isHidden*(path: string): bool {.noWeirdTarget.} =
  2972. ## Determines whether ``path`` is hidden or not, using `this
  2973. ## reference <https://en.wikipedia.org/wiki/Hidden_file_and_hidden_directory>`_.
  2974. ##
  2975. ## On Windows: returns true if it exists and its "hidden" attribute is set.
  2976. ##
  2977. ## On posix: returns true if ``lastPathPart(path)`` starts with ``.`` and is
  2978. ## not ``.`` or ``..``.
  2979. ##
  2980. ## **Note**: paths are not normalized to determine `isHidden`.
  2981. runnableExamples:
  2982. when defined(posix):
  2983. assert ".foo".isHidden
  2984. assert not ".foo/bar".isHidden
  2985. assert not ".".isHidden
  2986. assert not "..".isHidden
  2987. assert not "".isHidden
  2988. assert ".foo/".isHidden
  2989. when defined(Windows):
  2990. when useWinUnicode:
  2991. wrapUnary(attributes, getFileAttributesW, path)
  2992. else:
  2993. var attributes = getFileAttributesA(path)
  2994. if attributes != -1'i32:
  2995. result = (attributes and FILE_ATTRIBUTE_HIDDEN) != 0'i32
  2996. else:
  2997. let fileName = lastPathPart(path)
  2998. result = len(fileName) >= 2 and fileName[0] == '.' and fileName != ".."
  2999. proc getCurrentProcessId*(): int {.noWeirdTarget.} =
  3000. ## Return current process ID.
  3001. ##
  3002. ## See also:
  3003. ## * `osproc.processID(p: Process) <osproc.html#processID,Process>`_
  3004. when defined(windows):
  3005. proc GetCurrentProcessId(): DWORD {.stdcall, dynlib: "kernel32",
  3006. importc: "GetCurrentProcessId".}
  3007. result = GetCurrentProcessId().int
  3008. else:
  3009. result = getpid()
  3010. proc setLastModificationTime*(file: string, t: times.Time) {.noWeirdTarget.} =
  3011. ## Sets the `file`'s last modification time. `OSError` is raised in case of
  3012. ## an error.
  3013. when defined(posix):
  3014. let unixt = posix.Time(t.toUnix)
  3015. let micro = convert(Nanoseconds, Microseconds, t.nanosecond)
  3016. var timevals = [Timeval(tv_sec: unixt, tv_usec: micro),
  3017. Timeval(tv_sec: unixt, tv_usec: micro)] # [last access, last modification]
  3018. if utimes(file, timevals.addr) != 0: raiseOSError(osLastError(), file)
  3019. else:
  3020. let h = openHandle(path = file, writeAccess = true)
  3021. if h == INVALID_HANDLE_VALUE: raiseOSError(osLastError(), file)
  3022. var ft = t.toWinTime.toFILETIME
  3023. let res = setFileTime(h, nil, nil, ft.addr)
  3024. discard h.closeHandle
  3025. if res == 0'i32: raiseOSError(osLastError(), file)
  3026. func isValidFilename*(filename: string, maxLen = 259.Positive): bool {.since: (1, 1).} =
  3027. ## Returns true if ``filename`` is valid for crossplatform use.
  3028. ##
  3029. ## This is useful if you want to copy or save files across Windows, Linux, Mac, etc.
  3030. ## You can pass full paths as argument too, but func only checks filenames.
  3031. ## It uses ``invalidFilenameChars``, ``invalidFilenames`` and ``maxLen`` to verify the specified ``filename``.
  3032. ##
  3033. ## .. code-block:: nim
  3034. ## assert not isValidFilename(" foo") ## Leading white space
  3035. ## assert not isValidFilename("foo ") ## Trailing white space
  3036. ## assert not isValidFilename("foo.") ## Ends with Dot
  3037. ## assert not isValidFilename("con.txt") ## "CON" is invalid (Windows)
  3038. ## assert not isValidFilename("OwO:UwU") ## ":" is invalid (Mac)
  3039. ## assert not isValidFilename("aux.bat") ## "AUX" is invalid (Windows)
  3040. ##
  3041. # https://docs.microsoft.com/en-us/dotnet/api/system.io.pathtoolongexception
  3042. # https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
  3043. # https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247%28v=vs.85%29.aspx
  3044. result = true
  3045. let f = filename.splitFile()
  3046. if unlikely(f.name.len + f.ext.len > maxLen or
  3047. f.name[0] == ' ' or f.name[^1] == ' ' or f.name[^1] == '.' or
  3048. find(f.name, invalidFilenameChars) != -1): return false
  3049. for invalid in invalidFilenames:
  3050. if cmpIgnoreCase(f.name, invalid) == 0: return false