nimscript.nim 14 KB

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