summary refs log tree commit diff stats
path: root/tests/manyloc/nake/nake.nim
blob: 1e88fa73b920e3c2b1b70f2bcd250b8413e75495 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
discard """
DO AS THOU WILST PUBLIC LICENSE

Whoever should stumble upon this document is henceforth and forever
entitled to DO AS THOU WILST with aforementioned document and the
contents thereof.

As said in the Olde Country, `Keepe it Gangster'."""

import strutils, parseopt, tables, os

type
  PTask* = ref object
    desc*: string
    action*: TTaskFunction
  TTaskFunction* = proc() {.closure.}
var
  tasks* = initTable[string, PTask](16)

proc newTask*(desc: string; action: TTaskFunction): PTask
proc runTask*(name: string) {.inline.}
proc shell*(cmd: varargs[string, `$`]): int {.discardable.}
proc cd*(dir: string) {.inline.}

template nakeImports*(): stmt {.immediate.} =
  import tables, parseopt, strutils, os

template task*(name: string; description: string; body: stmt): stmt {.dirty, immediate.} =
  block:
    var t = newTask(description, proc() {.closure.} =
      body)
    tasks[name] = t

proc newTask*(desc: string; action: TTaskFunction): PTask =
  new(result)
  result.desc = desc
  result.action = action
proc runTask*(name: string) = tasks[name].action()

proc shell*(cmd: varargs[string, `$`]): int =
  result = execShellCmd(cmd.join(" "))
proc cd*(dir: string) = setCurrentDir(dir)
template withDir*(dir: string; body: stmt): stmt =
  ## temporary cd
  ## withDir "foo":
  ##   # inside foo
  ## #back to last dir
  var curDir = getCurrentDir()
  cd(dir)
  body
  cd(curDir)

when isMainModule:
  if not existsFile("nakefile.nim"):
    echo "No nakefile.nim found. Current working dir is ", getCurrentDir()
    quit 1
  var args = ""
  for i in 1..paramCount():
    args.add paramStr(i)
    args.add " "
  quit(shell("nim", "c", "-r", "nakefile.nim", args))
else:
  addQuitProc(proc() {.noconv.} =
    var
      task: string
      printTaskList: bool
    for kind, key, val in getOpt():
      case kind
      of cmdLongOption, cmdShortOption:
        case key.tolower
        of "tasks", "t":
          printTaskList = true
        else:
          echo "Unknown option: ", key, ": ", val
      of cmdArgument:
        task = key
      else: discard
    if printTaskList or task.isNil or not(tasks.hasKey(task)):
      echo "Available tasks:"
      for name, task in pairs(tasks):
        echo name, " - ", task.desc
      quit 0
    tasks[task].action())