diff --git a/src/js/watch.nim b/src/js/watch.nim index ac98002..3ce704c 100644 --- a/src/js/watch.nim +++ b/src/js/watch.nim @@ -1,18 +1,52 @@ import times, posix, strutils, os import strformat import times -import libfswatch -import std/[streams, osproc] +import std/[streams, osproc, md5, sequtils, terminal] -import libfswatch -import libfswatch/fswatch +import fswatch + +# import libfswatch +# import libfswatch/fswatch let file = "/home/floscr/Code/Projects/org-parser/src/js/example/sandbox.nim" -var ps: seq[Process] +type pT = tuple[md5: string, process: Process] +var ps: seq[pT] + +var data = "" + +type echoT = enum + Error + Success + Info + +proc errorEcho(x: string) = styledEcho(styleBright, fgRed, x) +proc successEcho(x: string) = styledEcho(styleBright, fgGreen, x) +proc infoEcho(x: string) = styledEcho(x) + +proc timedEcho(str: string, messageType = Info) = + let time = times.now().format("yyyy-MM-dd HH:MM:ss") + let echoFn = case messageType: + of Error: errorEcho + of Success: successEcho + else: infoEcho + echoFn(&"""[{time}]: {str}""") + +proc compileEcho(p: Process) {.thread.} = + var line: string + while p.running() and p.outputStream.readLine(line): + + echo line + + let exitStatus = p.peekExitCode() + case exitStatus: + of 0: timedEcho("Compilation Succeded", Success) + else: timedEcho("COMPILATION ERRORED!!", Error) + + p.close() proc compile(path: string) = - echo "Compiling..." + timedEcho("Compiling...\n") let p = startProcess( "nim", args= [ @@ -27,28 +61,23 @@ proc compile(path: string) = ], options = {poUsePath, poStdErrToStdOut} ) - ps.add(p) + let sha = path.readFile.getMD5() + ps.add((sha, p)) + + compileEcho(p) discard p.waitForExit() - var line: string - while p.running() and p.outputStream.readLine(line): - echo line +proc monitorCallback(eg: EventGroup) = + for e in eg: + if $e.kind == "Updated": + if not ps.anyIt(it.md5 == file.readFile.getMD5()): + for p in ps: + p.process.close() + ps = @[] - echo "Compilation Finished" - p.close() - ps = @[] + compile(file) -proc monitorCallback(event: fsw_cevent, event_num: cuint) = - echo event_num - if event_num == 10: - echo &"""[{times.now().format("yyyy-MM-dd HH:MM:ss")}]: {event.path} was modified. Compiling...""" - for p in ps: - p.close() - ps = @[] - - compile(file) - -var mon = newMonitor() -mon.addPath(file) -mon.setCallback(monitorCallback) -mon.start() +var monitor = newMonitor(latency=1) +monitor.add(file) +monitor.setCallback(monitorCallback) +monitor.start()