os.nim 127 KB

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