os.nim 118 KB

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