os.nim 127 KB

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