nimscript.nim 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  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. ## The compiler also performs `path substitution <nimc.html#compiler-usage-commandminusline-switches>`_ on `replacement`.
  75. ##
  76. ## Example:
  77. ## ```nim
  78. ## patchFile("stdlib", "asyncdispatch", "patches/replacement")
  79. ## ```
  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. proc selfExe*(): string {.deprecated: "Deprecated since v1.7; Use getCurrentCompilerExe".} =
  114. ## Returns the currently running nim or nimble executable.
  115. builtin
  116. proc toExe*(filename: string): string =
  117. ## On Windows adds ".exe" to `filename`, else returns `filename` unmodified.
  118. (when defined(windows): filename & ".exe" else: filename)
  119. proc toDll*(filename: string): string =
  120. ## On Windows adds ".dll" to `filename`, on Posix produces "lib$filename.so".
  121. (when defined(windows): filename & ".dll" else: "lib" & filename & ".so")
  122. proc strip(s: string): string =
  123. var i = 0
  124. while s[i] in {' ', '\c', '\n'}: inc i
  125. result = s.substr(i)
  126. if result[0] == '"' and result[^1] == '"':
  127. result = result[1..^2]
  128. template `--`*(key, val: untyped) =
  129. ## A shortcut for `switch <#switch,string,string>`_
  130. ## Example:
  131. ## ```nim
  132. ## --path:somePath # same as switch("path", "somePath")
  133. ## --path:"someOtherPath" # same as switch("path", "someOtherPath")
  134. ## ```
  135. switch(strip(astToStr(key)), strip(astToStr(val)))
  136. template `--`*(key: untyped) =
  137. ## A shortcut for `switch <#switch,string,string>`_
  138. ## Example:
  139. ## ```nim
  140. ## --listCmd # same as switch("listCmd")
  141. ## ```
  142. switch(strip(astToStr(key)))
  143. type
  144. ScriptMode* {.pure.} = enum ## Controls the behaviour of the script.
  145. Silent, ## Be silent.
  146. Verbose, ## Be verbose.
  147. Whatif ## Do not run commands, instead just echo what
  148. ## would have been done.
  149. var
  150. mode*: ScriptMode ## Set this to influence how mkDir, rmDir, rmFile etc.
  151. ## behave
  152. template checkError(exc: untyped): untyped =
  153. let err = getError()
  154. if err.len > 0: raise newException(exc, err)
  155. template checkOsError =
  156. checkError(OSError)
  157. template log(msg: string, body: untyped) =
  158. if mode in {ScriptMode.Verbose, ScriptMode.Whatif}:
  159. echo "[NimScript] ", msg
  160. if mode != ScriptMode.Whatif:
  161. body
  162. proc listDirs*(dir: string): seq[string] =
  163. ## Lists all the subdirectories (non-recursively) in the directory `dir`.
  164. result = listDirsImpl(dir)
  165. checkOsError()
  166. proc listFiles*(dir: string): seq[string] =
  167. ## Lists all the files (non-recursively) in the directory `dir`.
  168. result = listFilesImpl(dir)
  169. checkOsError()
  170. proc rmDir*(dir: string, checkDir = false) {.raises: [OSError].} =
  171. ## Removes the directory `dir`.
  172. log "rmDir: " & dir:
  173. removeDir(dir, checkDir = checkDir)
  174. checkOsError()
  175. proc rmFile*(file: string) {.raises: [OSError].} =
  176. ## Removes the `file`.
  177. log "rmFile: " & file:
  178. removeFile file
  179. checkOsError()
  180. proc mkDir*(dir: string) {.raises: [OSError].} =
  181. ## Creates the directory `dir` including all necessary subdirectories. If
  182. ## the directory already exists, no error is raised.
  183. log "mkDir: " & dir:
  184. createDir dir
  185. checkOsError()
  186. proc mvFile*(`from`, to: string) {.raises: [OSError].} =
  187. ## Moves the file `from` to `to`.
  188. log "mvFile: " & `from` & ", " & to:
  189. moveFile `from`, to
  190. checkOsError()
  191. proc mvDir*(`from`, to: string) {.raises: [OSError].} =
  192. ## Moves the dir `from` to `to`.
  193. log "mvDir: " & `from` & ", " & to:
  194. moveDir `from`, to
  195. checkOsError()
  196. proc cpFile*(`from`, to: string) {.raises: [OSError].} =
  197. ## Copies the file `from` to `to`.
  198. log "cpFile: " & `from` & ", " & to:
  199. copyFile `from`, to
  200. checkOsError()
  201. proc cpDir*(`from`, to: string) {.raises: [OSError].} =
  202. ## Copies the dir `from` to `to`.
  203. log "cpDir: " & `from` & ", " & to:
  204. copyDir `from`, to
  205. checkOsError()
  206. proc exec*(command: string) {.
  207. raises: [OSError], tags: [ExecIOEffect, WriteIOEffect].} =
  208. ## Executes an external process. If the external process terminates with
  209. ## a non-zero exit code, an OSError exception is raised.
  210. ##
  211. ## **Note:** If you need a version of `exec` that returns the exit code
  212. ## and text output of the command, you can use `system.gorgeEx
  213. ## <system.html#gorgeEx,string,string,string>`_.
  214. log "exec: " & command:
  215. if rawExec(command) != 0:
  216. raise newException(OSError, "FAILED: " & command)
  217. checkOsError()
  218. proc exec*(command: string, input: string, cache = "") {.
  219. raises: [OSError], tags: [ExecIOEffect, WriteIOEffect].} =
  220. ## Executes an external process. If the external process terminates with
  221. ## a non-zero exit code, an OSError exception is raised.
  222. log "exec: " & command:
  223. let (output, exitCode) = gorgeEx(command, input, cache)
  224. if exitCode != 0:
  225. raise newException(OSError, "FAILED: " & command)
  226. echo output
  227. proc selfExec*(command: string) {.
  228. raises: [OSError], tags: [ExecIOEffect, WriteIOEffect].} =
  229. ## Executes an external command with the current nim/nimble executable.
  230. ## `Command` must not contain the "nim " part.
  231. let c = selfExe() & " " & command
  232. log "exec: " & c:
  233. if rawExec(c) != 0:
  234. raise newException(OSError, "FAILED: " & c)
  235. checkOsError()
  236. proc put*(key, value: string) =
  237. ## Sets a configuration 'key' like 'gcc.options.always' to its value.
  238. builtin
  239. proc get*(key: string): string =
  240. ## Retrieves a configuration 'key' like 'gcc.options.always'.
  241. builtin
  242. proc exists*(key: string): bool =
  243. ## Checks for the existence of a configuration 'key'
  244. ## like 'gcc.options.always'.
  245. builtin
  246. proc nimcacheDir*(): string =
  247. ## Retrieves the location of 'nimcache'.
  248. builtin
  249. proc projectName*(): string =
  250. ## Retrieves the name of the current project
  251. builtin
  252. proc projectDir*(): string =
  253. ## Retrieves the absolute directory of the current project
  254. builtin
  255. proc projectPath*(): string =
  256. ## Retrieves the absolute path of the current project
  257. builtin
  258. proc thisDir*(): string =
  259. ## Retrieves the directory of the current `nims` script file. Its path is
  260. ## obtained via `currentSourcePath` (although, currently,
  261. ## `currentSourcePath` resolves symlinks, unlike `thisDir`).
  262. builtin
  263. proc cd*(dir: string) {.raises: [OSError].} =
  264. ## Changes the current directory.
  265. ##
  266. ## The change is permanent for the rest of the execution, since this is just
  267. ## a shortcut for `os.setCurrentDir() <os.html#setCurrentDir,string>`_ . Use
  268. ## the `withDir() <#withDir.t,string,untyped>`_ template if you want to
  269. ## perform a temporary change only.
  270. setCurrentDir(dir)
  271. checkOsError()
  272. proc findExe*(bin: string): string =
  273. ## Searches for bin in the current working directory and then in directories
  274. ## listed in the PATH environment variable. Returns "" if the exe cannot be
  275. ## found.
  276. builtin
  277. template withDir*(dir: string; body: untyped): untyped =
  278. ## Changes the current directory temporarily.
  279. ##
  280. ## If you need a permanent change, use the `cd() <#cd,string>`_ proc.
  281. ## Usage example:
  282. ## ```nim
  283. ## # inside /some/path/
  284. ## withDir "foo":
  285. ## # move to /some/path/foo/
  286. ## # back in /some/path/
  287. ## ```
  288. let curDir = getCurrentDir()
  289. try:
  290. cd(dir)
  291. body
  292. finally:
  293. cd(curDir)
  294. proc writeTask(name, desc: string) =
  295. if desc.len > 0:
  296. var spaces = " "
  297. for i in 0 ..< 20 - name.len: spaces.add ' '
  298. echo name, spaces, desc
  299. proc cppDefine*(define: string) =
  300. ## tell Nim that `define` is a C preprocessor `#define` and so always
  301. ## needs to be mangled.
  302. builtin
  303. proc stdinReadLine(): string {.
  304. tags: [ReadIOEffect], raises: [IOError].} =
  305. builtin
  306. proc stdinReadAll(): string {.
  307. tags: [ReadIOEffect], raises: [IOError].} =
  308. builtin
  309. proc readLineFromStdin*(): string {.raises: [IOError].} =
  310. ## Reads a line of data from stdin - blocks until \n or EOF which happens when stdin is closed
  311. log "readLineFromStdin":
  312. result = stdinReadLine()
  313. checkError(EOFError)
  314. proc readAllFromStdin*(): string {.raises: [IOError].} =
  315. ## Reads all data from stdin - blocks until EOF which happens when stdin is closed
  316. log "readAllFromStdin":
  317. result = stdinReadAll()
  318. checkError(EOFError)
  319. when not defined(nimble):
  320. template `==?`(a, b: string): bool = cmpIgnoreStyle(a, b) == 0
  321. template task*(name: untyped; description: string; body: untyped): untyped =
  322. ## Defines a task. Hidden tasks are supported via an empty description.
  323. ##
  324. ## Example:
  325. ## ```nim
  326. ## task build, "default build is via the C backend":
  327. ## setCommand "c"
  328. ## ```
  329. ##
  330. ## For a task named `foo`, this template generates a `proc` named
  331. ## `fooTask`. This is useful if you need to call one task in
  332. ## another in your Nimscript.
  333. ##
  334. ## Example:
  335. ##
  336. ## ```nim
  337. ## task foo, "foo": # > nim foo
  338. ## echo "Running foo" # Running foo
  339. ##
  340. ## task bar, "bar": # > nim bar
  341. ## echo "Running bar" # Running bar
  342. ## fooTask() # Running foo
  343. ## ```
  344. proc `name Task`*() =
  345. setCommand "nop"
  346. body
  347. let cmd = getCommand()
  348. if cmd.len == 0 or cmd ==? "help":
  349. setCommand "help"
  350. writeTask(astToStr(name), description)
  351. elif cmd ==? astToStr(name):
  352. `name Task`()
  353. # nimble has its own implementation for these things.
  354. var
  355. packageName* = "" ## Nimble support: Set this to the package name. It
  356. ## is usually not required to do that, nims' filename is
  357. ## the default.
  358. version*: string ## Nimble support: The package's version.
  359. author*: string ## Nimble support: The package's author.
  360. description*: string ## Nimble support: The package's description.
  361. license*: string ## Nimble support: The package's license.
  362. srcDir*: string ## Nimble support: The package's source directory.
  363. binDir*: string ## Nimble support: The package's binary directory.
  364. backend*: string ## Nimble support: The package's backend.
  365. skipDirs*, skipFiles*, skipExt*, installDirs*, installFiles*,
  366. installExt*, bin*: seq[string] = @[] ## Nimble metadata.
  367. requiresData*: seq[string] = @[] ## Exposes the list of requirements for read
  368. ## and write accesses.
  369. proc requires*(deps: varargs[string]) =
  370. ## Nimble support: Call this to set the list of requirements of your Nimble
  371. ## package.
  372. for d in deps: requiresData.add(d)
  373. {.pop.}