nimscript.nim 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  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. ## To learn about scripting in Nim see `NimScript<nims.html>`_
  10. # Nim's configuration system now uses Nim for scripting. This module provides
  11. # a few things that are required for this to work.
  12. const
  13. buildOS* {.magic: "BuildOS".}: string = ""
  14. ## The OS this build is running on. Can be different from ``system.hostOS``
  15. ## for cross compilations.
  16. buildCPU* {.magic: "BuildCPU".}: string = ""
  17. ## The CPU this build is running on. Can be different from ``system.hostCPU``
  18. ## for cross compilations.
  19. template builtin = discard
  20. # We know the effects better than the compiler:
  21. {.push hint[XDeclaredButNotUsed]: off.}
  22. proc listDirsImpl(dir: string): seq[string] {.
  23. tags: [ReadIOEffect], raises: [OSError].} = builtin
  24. proc listFilesImpl(dir: string): seq[string] {.
  25. tags: [ReadIOEffect], raises: [OSError].} = builtin
  26. proc removeDir(dir: string, checkDir = true) {.
  27. tags: [ReadIOEffect, WriteIOEffect], raises: [OSError].} = builtin
  28. proc removeFile(dir: string) {.
  29. tags: [ReadIOEffect, WriteIOEffect], raises: [OSError].} = builtin
  30. proc moveFile(src, dest: string) {.
  31. tags: [ReadIOEffect, WriteIOEffect], raises: [OSError].} = builtin
  32. proc moveDir(src, dest: string) {.
  33. tags: [ReadIOEffect, WriteIOEffect], raises: [OSError].} = builtin
  34. proc copyFile(src, dest: string) {.
  35. tags: [ReadIOEffect, WriteIOEffect], raises: [OSError].} = builtin
  36. proc copyDir(src, dest: string) {.
  37. tags: [ReadIOEffect, WriteIOEffect], raises: [OSError].} = builtin
  38. proc createDir(dir: string) {.tags: [WriteIOEffect], raises: [OSError].} =
  39. builtin
  40. proc getError: string = builtin
  41. proc setCurrentDir(dir: string) = builtin
  42. proc getCurrentDir*(): string =
  43. ## Retrieves the current working directory.
  44. builtin
  45. proc rawExec(cmd: string): int {.tags: [ExecIOEffect], raises: [OSError].} =
  46. builtin
  47. proc warningImpl(arg, orig: string) = discard
  48. proc hintImpl(arg, orig: string) = discard
  49. proc paramStr*(i: int): string =
  50. ## Retrieves the ``i``'th command line parameter.
  51. builtin
  52. proc paramCount*(): int =
  53. ## Retrieves the number of command line parameters.
  54. builtin
  55. proc switch*(key: string, val="") =
  56. ## Sets a Nim compiler command line switch, for
  57. ## example ``switch("checks", "on")``.
  58. builtin
  59. proc warning*(name: string; val: bool) =
  60. ## Disables or enables a specific warning.
  61. let v = if val: "on" else: "off"
  62. warningImpl(name & ":" & v, "warning:" & name & ":" & v)
  63. proc hint*(name: string; val: bool) =
  64. ## Disables or enables a specific hint.
  65. let v = if val: "on" else: "off"
  66. hintImpl(name & ":" & v, "hint:" & name & ":" & v)
  67. proc patchFile*(package, filename, replacement: string) =
  68. ## Overrides the location of a given file belonging to the
  69. ## passed package.
  70. ## If the ``replacement`` is not an absolute path, the path
  71. ## is interpreted to be local to the Nimscript file that contains
  72. ## the call to ``patchFile``, Nim's ``--path`` is not used at all
  73. ## to resolve the filename!
  74. ##
  75. ## Example:
  76. ##
  77. ## .. code-block:: nim
  78. ##
  79. ## patchFile("stdlib", "asyncdispatch", "patches/replacement")
  80. discard
  81. proc getCommand*(): string =
  82. ## Gets the Nim command that the compiler has been invoked with, for example
  83. ## "c", "js", "build", "help".
  84. builtin
  85. proc setCommand*(cmd: string; project="") =
  86. ## Sets the Nim command that should be continued with after this Nimscript
  87. ## has finished.
  88. builtin
  89. proc cmpIgnoreStyle(a, b: string): int = builtin
  90. proc cmpIgnoreCase(a, b: string): int = builtin
  91. proc cmpic*(a, b: string): int =
  92. ## Compares `a` and `b` ignoring case.
  93. cmpIgnoreCase(a, b)
  94. proc getEnv*(key: string; default = ""): string {.tags: [ReadIOEffect].} =
  95. ## Retrieves the environment variable of name ``key``.
  96. builtin
  97. proc existsEnv*(key: string): bool {.tags: [ReadIOEffect].} =
  98. ## Checks for the existence of an environment variable named ``key``.
  99. builtin
  100. proc putEnv*(key, val: string) {.tags: [WriteIOEffect].} =
  101. ## Sets the value of the environment variable named ``key`` to ``val``.
  102. builtin
  103. proc delEnv*(key: string) {.tags: [WriteIOEffect].} =
  104. ## Deletes the environment variable named ``key``.
  105. builtin
  106. proc fileExists*(filename: string): bool {.tags: [ReadIOEffect].} =
  107. ## Checks if the file exists.
  108. builtin
  109. proc dirExists*(dir: string): bool {.
  110. tags: [ReadIOEffect].} =
  111. ## Checks if the directory `dir` exists.
  112. builtin
  113. template existsFile*(args: varargs[untyped]): untyped {.deprecated: "use fileExists".} =
  114. # xxx: warning won't be shown for nimsscript because of current logic handling
  115. # `foreignPackageNotes`
  116. fileExists(args)
  117. template existsDir*(args: varargs[untyped]): untyped {.deprecated: "use dirExists".} =
  118. dirExists(args)
  119. proc selfExe*(): string =
  120. ## Returns the currently running nim or nimble executable.
  121. # TODO: consider making this as deprecated alias of `getCurrentCompilerExe`
  122. builtin
  123. proc toExe*(filename: string): string =
  124. ## On Windows adds ".exe" to `filename`, else returns `filename` unmodified.
  125. (when defined(windows): filename & ".exe" else: filename)
  126. proc toDll*(filename: string): string =
  127. ## On Windows adds ".dll" to `filename`, on Posix produces "lib$filename.so".
  128. (when defined(windows): filename & ".dll" else: "lib" & filename & ".so")
  129. proc strip(s: string): string =
  130. var i = 0
  131. while s[i] in {' ', '\c', '\L'}: inc i
  132. result = s.substr(i)
  133. template `--`*(key, val: untyped) =
  134. ## A shortcut for ``switch(astToStr(key), astToStr(val))``.
  135. switch(astToStr(key), strip astToStr(val))
  136. template `--`*(key: untyped) =
  137. ## A shortcut for ``switch(astToStr(key)``.
  138. switch(astToStr(key), "")
  139. type
  140. ScriptMode* {.pure.} = enum ## Controls the behaviour of the script.
  141. Silent, ## Be silent.
  142. Verbose, ## Be verbose.
  143. Whatif ## Do not run commands, instead just echo what
  144. ## would have been done.
  145. var
  146. mode*: ScriptMode ## Set this to influence how mkDir, rmDir, rmFile etc.
  147. ## behave
  148. template checkError(exc: untyped): untyped =
  149. let err = getError()
  150. if err.len > 0: raise newException(exc, err)
  151. template checkOsError =
  152. checkError(OSError)
  153. template log(msg: string, body: untyped) =
  154. if mode in {ScriptMode.Verbose, ScriptMode.Whatif}:
  155. echo "[NimScript] ", msg
  156. if mode != ScriptMode.WhatIf:
  157. body
  158. proc listDirs*(dir: string): seq[string] =
  159. ## Lists all the subdirectories (non-recursively) in the directory `dir`.
  160. result = listDirsImpl(dir)
  161. checkOsError()
  162. proc listFiles*(dir: string): seq[string] =
  163. ## Lists all the files (non-recursively) in the directory `dir`.
  164. result = listFilesImpl(dir)
  165. checkOsError()
  166. proc rmDir*(dir: string, checkDir = false) {.raises: [OSError].} =
  167. ## Removes the directory `dir`.
  168. log "rmDir: " & dir:
  169. removeDir(dir, checkDir = checkDir)
  170. checkOsError()
  171. proc rmFile*(file: string) {.raises: [OSError].} =
  172. ## Removes the `file`.
  173. log "rmFile: " & file:
  174. removeFile file
  175. checkOsError()
  176. proc mkDir*(dir: string) {.raises: [OSError].} =
  177. ## Creates the directory `dir` including all necessary subdirectories. If
  178. ## the directory already exists, no error is raised.
  179. log "mkDir: " & dir:
  180. createDir dir
  181. checkOsError()
  182. proc mvFile*(`from`, to: string) {.raises: [OSError].} =
  183. ## Moves the file `from` to `to`.
  184. log "mvFile: " & `from` & ", " & to:
  185. moveFile `from`, to
  186. checkOsError()
  187. proc mvDir*(`from`, to: string) {.raises: [OSError].} =
  188. ## Moves the dir `from` to `to`.
  189. log "mvDir: " & `from` & ", " & to:
  190. moveDir `from`, to
  191. checkOsError()
  192. proc cpFile*(`from`, to: string) {.raises: [OSError].} =
  193. ## Copies the file `from` to `to`.
  194. log "cpFile: " & `from` & ", " & to:
  195. copyFile `from`, to
  196. checkOsError()
  197. proc cpDir*(`from`, to: string) {.raises: [OSError].} =
  198. ## Copies the dir `from` to `to`.
  199. log "cpDir: " & `from` & ", " & to:
  200. copyDir `from`, to
  201. checkOsError()
  202. proc exec*(command: string) {.
  203. raises: [OSError], tags: [ExecIOEffect].} =
  204. ## Executes an external process. If the external process terminates with
  205. ## a non-zero exit code, an OSError exception is raised.
  206. ##
  207. ## **Note:** If you need a version of ``exec`` that returns the exit code
  208. ## and text output of the command, you can use `system.gorgeEx
  209. ## <system.html#gorgeEx,string,string,string>`_.
  210. log "exec: " & command:
  211. if rawExec(command) != 0:
  212. raise newException(OSError, "FAILED: " & command)
  213. checkOsError()
  214. proc exec*(command: string, input: string, cache = "") {.
  215. raises: [OSError], tags: [ExecIOEffect].} =
  216. ## Executes an external process. If the external process terminates with
  217. ## a non-zero exit code, an OSError exception is raised.
  218. log "exec: " & command:
  219. let (output, exitCode) = gorgeEx(command, input, cache)
  220. if exitCode != 0:
  221. raise newException(OSError, "FAILED: " & command)
  222. echo output
  223. proc selfExec*(command: string) {.
  224. raises: [OSError], tags: [ExecIOEffect].} =
  225. ## Executes an external command with the current nim/nimble executable.
  226. ## ``Command`` must not contain the "nim " part.
  227. let c = selfExe() & " " & command
  228. log "exec: " & c:
  229. if rawExec(c) != 0:
  230. raise newException(OSError, "FAILED: " & c)
  231. checkOsError()
  232. proc put*(key, value: string) =
  233. ## Sets a configuration 'key' like 'gcc.options.always' to its value.
  234. builtin
  235. proc get*(key: string): string =
  236. ## Retrieves a configuration 'key' like 'gcc.options.always'.
  237. builtin
  238. proc exists*(key: string): bool =
  239. ## Checks for the existence of a configuration 'key'
  240. ## like 'gcc.options.always'.
  241. builtin
  242. proc nimcacheDir*(): string =
  243. ## Retrieves the location of 'nimcache'.
  244. builtin
  245. proc projectName*(): string =
  246. ## Retrieves the name of the current project
  247. builtin
  248. proc projectDir*(): string =
  249. ## Retrieves the absolute directory of the current project
  250. builtin
  251. proc projectPath*(): string =
  252. ## Retrieves the absolute path of the current project
  253. builtin
  254. proc thisDir*(): string =
  255. ## Retrieves the directory of the current ``nims`` script file. Its path is
  256. ## obtained via ``currentSourcePath`` (although, currently,
  257. ## ``currentSourcePath`` resolves symlinks, unlike ``thisDir``).
  258. builtin
  259. proc cd*(dir: string) {.raises: [OSError].} =
  260. ## Changes the current directory.
  261. ##
  262. ## The change is permanent for the rest of the execution, since this is just
  263. ## a shortcut for `os.setCurrentDir() <os.html#setCurrentDir,string>`_ . Use
  264. ## the `withDir() <#withDir.t,string,untyped>`_ template if you want to
  265. ## perform a temporary change only.
  266. setCurrentDir(dir)
  267. checkOsError()
  268. proc findExe*(bin: string): string =
  269. ## Searches for bin in the current working directory and then in directories
  270. ## listed in the PATH environment variable. Returns "" if the exe cannot be
  271. ## found.
  272. builtin
  273. template withDir*(dir: string; body: untyped): untyped =
  274. ## Changes the current directory temporarily.
  275. ##
  276. ## If you need a permanent change, use the `cd() <#cd,string>`_ proc.
  277. ## Usage example:
  278. ##
  279. ## .. code-block:: nim
  280. ## withDir "foo":
  281. ## # inside foo
  282. ## #back to last dir
  283. var curDir = getCurrentDir()
  284. try:
  285. cd(dir)
  286. body
  287. finally:
  288. cd(curDir)
  289. proc writeTask(name, desc: string) =
  290. if desc.len > 0:
  291. var spaces = " "
  292. for i in 0 ..< 20 - name.len: spaces.add ' '
  293. echo name, spaces, desc
  294. proc cppDefine*(define: string) =
  295. ## tell Nim that ``define`` is a C preprocessor ``#define`` and so always
  296. ## needs to be mangled.
  297. builtin
  298. proc stdinReadLine(): TaintedString {.
  299. tags: [ReadIOEffect], raises: [IOError].} =
  300. builtin
  301. proc stdinReadAll(): TaintedString {.
  302. tags: [ReadIOEffect], raises: [IOError].} =
  303. builtin
  304. proc readLineFromStdin*(): TaintedString {.raises: [IOError].} =
  305. ## Reads a line of data from stdin - blocks until \n or EOF which happens when stdin is closed
  306. log "readLineFromStdin":
  307. result = stdinReadLine()
  308. checkError(EOFError)
  309. proc readAllFromStdin*(): TaintedString {.raises: [IOError].} =
  310. ## Reads all data from stdin - blocks until EOF which happens when stdin is closed
  311. log "readAllFromStdin":
  312. result = stdinReadAll()
  313. checkError(EOFError)
  314. when not defined(nimble):
  315. template `==?`(a, b: string): bool = cmpIgnoreStyle(a, b) == 0
  316. template task*(name: untyped; description: string; body: untyped): untyped =
  317. ## Defines a task. Hidden tasks are supported via an empty description.
  318. ##
  319. ## Example:
  320. ##
  321. ## .. code-block:: nim
  322. ## task build, "default build is via the C backend":
  323. ## setCommand "c"
  324. ##
  325. ## For a task named ``foo``, this template generates a ``proc`` named
  326. ## ``fooTask``. This is useful if you need to call one task in
  327. ## another in your Nimscript.
  328. ##
  329. ## Example:
  330. ##
  331. ## .. code-block:: nim
  332. ## task foo, "foo": # > nim foo
  333. ## echo "Running foo" # Running foo
  334. ##
  335. ## task bar, "bar": # > nim bar
  336. ## echo "Running bar" # Running bar
  337. ## fooTask() # Running foo
  338. proc `name Task`*() =
  339. setCommand "nop"
  340. body
  341. let cmd = getCommand()
  342. if cmd.len == 0 or cmd ==? "help":
  343. setCommand "help"
  344. writeTask(astToStr(name), description)
  345. elif cmd ==? astToStr(name):
  346. `name Task`()
  347. # nimble has its own implementation for these things.
  348. var
  349. packageName* = "" ## Nimble support: Set this to the package name. It
  350. ## is usually not required to do that, nims' filename is
  351. ## the default.
  352. version*: string ## Nimble support: The package's version.
  353. author*: string ## Nimble support: The package's author.
  354. description*: string ## Nimble support: The package's description.
  355. license*: string ## Nimble support: The package's license.
  356. srcDir*: string ## Nimble support: The package's source directory.
  357. binDir*: string ## Nimble support: The package's binary directory.
  358. backend*: string ## Nimble support: The package's backend.
  359. skipDirs*, skipFiles*, skipExt*, installDirs*, installFiles*,
  360. installExt*, bin*: seq[string] = @[] ## Nimble metadata.
  361. requiresData*: seq[string] = @[] ## Exposes the list of requirements for read
  362. ## and write accesses.
  363. proc requires*(deps: varargs[string]) =
  364. ## Nimble support: Call this to set the list of requirements of your Nimble
  365. ## package.
  366. for d in deps: requiresData.add(d)
  367. {.pop.}