Compare commits
11 Commits
Author | SHA1 | Date | |
---|---|---|---|
7b274bfb98 | |||
e0eb8fd4c2 | |||
d368e85e33 | |||
49342818ec | |||
95f3bc48bd | |||
64fdcb359d | |||
4ed613523b | |||
441063a393 | |||
cce4e5ec80 | |||
9fba13a965 | |||
96b6832834 |
143
cliutils.nim
143
cliutils.nim
@ -1,11 +1,15 @@
|
|||||||
import docopt, json, osproc, posix, nre, streams, strutils, strtabs
|
import docopt, json, osproc, posix, nre, streams, strtabs, terminal, unicode
|
||||||
import os except sleep
|
import os except sleep
|
||||||
|
import strutils except toUpper, toLower
|
||||||
|
|
||||||
|
|
||||||
type
|
type
|
||||||
CombinedConfig* = object
|
CombinedConfig* = object
|
||||||
docopt*: Table[string, Value]
|
docopt*: Table[string, Value]
|
||||||
json*: JsonNode
|
json*: JsonNode
|
||||||
|
|
||||||
|
TermColor = ForegroundColor or BackgroundColor
|
||||||
|
|
||||||
proc getVal*(cfg: CombinedConfig, key, default: string): string =
|
proc getVal*(cfg: CombinedConfig, key, default: string): string =
|
||||||
let argKey = "--" & key
|
let argKey = "--" & key
|
||||||
let envKey = key.replace('-', '_').toUpper
|
let envKey = key.replace('-', '_').toUpper
|
||||||
@ -13,7 +17,16 @@ proc getVal*(cfg: CombinedConfig, key, default: string): string =
|
|||||||
|
|
||||||
if cfg.docopt[argKey]: return $cfg.docopt[argKey]
|
if cfg.docopt[argKey]: return $cfg.docopt[argKey]
|
||||||
elif existsEnv(envKey): return getEnv(envKey)
|
elif existsEnv(envKey): return getEnv(envKey)
|
||||||
elif cfg.json.hasKey(jsonKey): return cfg.json[jsonKey].getStr
|
elif cfg.json.hasKey(jsonKey):
|
||||||
|
let node = cfg.json[jsonKey]
|
||||||
|
case node.kind
|
||||||
|
of JString: return node.getStr
|
||||||
|
of JInt: return $node.getInt
|
||||||
|
of JFloat: return $node.getFloat
|
||||||
|
of JBool: return $node.getBool
|
||||||
|
of JNull: return ""
|
||||||
|
of JObject: return $node
|
||||||
|
of JArray: return $node
|
||||||
else: return default
|
else: return default
|
||||||
|
|
||||||
|
|
||||||
@ -28,53 +41,20 @@ type HandleProcMsgCB* = proc (outMsg: TaintedString,
|
|||||||
errMsg: TaintedString, cmd: string): void
|
errMsg: TaintedString, cmd: string): void
|
||||||
|
|
||||||
proc sendMsg*(h: HandleProcMsgCB, outMsg: TaintedString,
|
proc sendMsg*(h: HandleProcMsgCB, outMsg: TaintedString,
|
||||||
errMsg: TaintedString = nil, cmd: string): void =
|
errMsg: TaintedString = "", cmd: string = ""): void =
|
||||||
if h != nil: h(outMsg, errMsg, cmd)
|
if h != nil: h(outMsg, errMsg, cmd)
|
||||||
|
|
||||||
proc waitForWithOutput*(p: Process, msgCB: HandleProcMsgCB,
|
proc makeProcMsgHandler*(outSink, errSink: File, prefixCmd: bool = true): HandleProcMsgCB =
|
||||||
procCmd: string = ""):
|
|
||||||
tuple[output: TaintedString, error: TaintedString, exitCode: int] =
|
|
||||||
|
|
||||||
var pout = outputStream(p)
|
|
||||||
var perr = errorStream(p)
|
|
||||||
|
|
||||||
result = (TaintedString"", TaintedString"", -1)
|
|
||||||
var line = newStringOfCap(120).TaintedString
|
|
||||||
while true:
|
|
||||||
if pout.readLine(line):
|
|
||||||
msgCB.sendMsg(line, nil, procCmd)
|
|
||||||
result[0].string.add(line.string)
|
|
||||||
result[0].string.add("\n")
|
|
||||||
elif perr.readLine(line):
|
|
||||||
msgCB.sendMsg(nil, line, procCmd)
|
|
||||||
result[1].string.add(line.string)
|
|
||||||
result[1].string.add("\n")
|
|
||||||
else:
|
|
||||||
result[2] = peekExitCode(p)
|
|
||||||
if result[2] != -1: break
|
|
||||||
close(p)
|
|
||||||
|
|
||||||
proc exec*(command: string, workingDir: string = "",
|
|
||||||
args: openArray[string] = [], env: StringTableRef = nil,
|
|
||||||
options: set[ProcessOption] = {poUsePath},
|
|
||||||
msgCB: HandleProcMsgCB = nil):
|
|
||||||
tuple[output: TaintedString, error: TaintedString, exitCode: int]
|
|
||||||
{.tags: [ExecIOEffect, ReadIOEffect], gcsafe.} =
|
|
||||||
|
|
||||||
var p = startProcess(command, workingDir, args, env, options)
|
|
||||||
result = waitForWithOutput(p, msgCb, command)
|
|
||||||
|
|
||||||
proc makeProcMsgHandler*(outSink, errSink: File): HandleProcMsgCB =
|
|
||||||
result = proc(outMsg, errMsg: TaintedString, cmd: string): void {.closure.} =
|
result = proc(outMsg, errMsg: TaintedString, cmd: string): void {.closure.} =
|
||||||
let prefix = if cmd != nil: cmd & ": " else: ""
|
let prefix = if cmd.len == 0 or not prefixCmd: "" else: cmd & ": "
|
||||||
if outMsg != nil: outSink.writeLine(prefix & outMsg)
|
if outMsg.len > 0: outSink.writeLine(prefix & outMsg)
|
||||||
if errMsg != nil: errSink.writeLine(prefix & errMsg)
|
if errMsg.len > 0: errSink.writeLine(prefix & errMsg)
|
||||||
|
|
||||||
proc makeProcMsgHandler*(outSink, errSink: Stream): HandleProcMsgCB =
|
proc makeProcMsgHandler*(outSink, errSink: Stream, prefixCmd: bool = true): HandleProcMsgCB =
|
||||||
result = proc(outMsg, errMsg: TaintedString, cmd: string): void {.closure.} =
|
result = proc(outMsg, errMsg: TaintedString, cmd: string): void {.closure.} =
|
||||||
let prefix = if cmd != nil: cmd & ": " else: ""
|
let prefix = if cmd.len == 0 or not prefixCmd: "" else: cmd & ": "
|
||||||
if outMsg != nil: outSink.writeLine(prefix & outMsg)
|
if outMsg.len > 0: outSink.writeLine(prefix & outMsg)
|
||||||
if errMsg != nil: errSink.writeLine(prefix & errMsg)
|
if errMsg.len > 0: errSink.writeLine(prefix & errMsg)
|
||||||
|
|
||||||
proc combineProcMsgHandlers*(a, b: HandleProcMsgCB): HandleProcMsgCB =
|
proc combineProcMsgHandlers*(a, b: HandleProcMsgCB): HandleProcMsgCB =
|
||||||
if a == nil: result = b
|
if a == nil: result = b
|
||||||
@ -84,6 +64,48 @@ proc combineProcMsgHandlers*(a, b: HandleProcMsgCB): HandleProcMsgCB =
|
|||||||
a(cmd, outMsg, errMsg)
|
a(cmd, outMsg, errMsg)
|
||||||
b(cmd, outMsg, errMsg)
|
b(cmd, outMsg, errMsg)
|
||||||
|
|
||||||
|
proc waitFor*(p: Process, msgCB: HandleProcMsgCB, procCmd: string = ""): int =
|
||||||
|
|
||||||
|
var pout = outputStream(p)
|
||||||
|
var perr = errorStream(p)
|
||||||
|
|
||||||
|
var line = newStringOfCap(120).TaintedString
|
||||||
|
while true:
|
||||||
|
if pout.readLine(line):
|
||||||
|
msgCB.sendMsg(line, "", procCmd)
|
||||||
|
elif perr.readLine(line):
|
||||||
|
msgCB.sendMsg("", line, procCmd)
|
||||||
|
else:
|
||||||
|
result = peekExitCode(p)
|
||||||
|
if result != -1: break
|
||||||
|
close(p)
|
||||||
|
|
||||||
|
proc exec*(command: string, workingDir: string = "",
|
||||||
|
args: openArray[string] = [], env: StringTableRef = nil,
|
||||||
|
options: set[ProcessOption] = {poUsePath},
|
||||||
|
msgCB: HandleProcMsgCB = nil): int
|
||||||
|
{.tags: [ExecIOEffect, ReadIOEffect, RootEffect], gcsafe.} =
|
||||||
|
|
||||||
|
var p = startProcess(command, workingDir, args, env, options)
|
||||||
|
result = waitFor(p, msgCB, command)
|
||||||
|
|
||||||
|
proc execWithOutput*(command: string, workingDir:string = "",
|
||||||
|
args: openArray[string] = [], env: StringTableRef = nil,
|
||||||
|
options: set[ProcessOption] = {poUsePath},
|
||||||
|
msgCB: HandleProcMsgCB = nil):
|
||||||
|
tuple[output, error: TaintedString, exitCode: int] =
|
||||||
|
|
||||||
|
result = (TaintedString"", TaintedString"", -1)
|
||||||
|
var outSeq, errSeq: seq[TaintedString]
|
||||||
|
outSeq = @[]; errSeq = @[]
|
||||||
|
var outputCollector = combineProcMsgHandlers(msgCB,
|
||||||
|
proc(outMsg, errMsg: TaintedString, cmd: string): void {.closure.} =
|
||||||
|
if outMsg.len > 0: outSeq.add(outMsg)
|
||||||
|
if errMsg.len > 0: errSeq.add(errMsg))
|
||||||
|
|
||||||
|
result[2] = exec(command, workingDir, args, env, options, outputCollector)
|
||||||
|
result[0] = outSeq.join("\n")
|
||||||
|
result[1] = errSeq.join("\n")
|
||||||
|
|
||||||
## Daemonize
|
## Daemonize
|
||||||
|
|
||||||
@ -99,7 +121,7 @@ proc onStop(sig: cint) {.noconv.} =
|
|||||||
|
|
||||||
quit(QuitSuccess)
|
quit(QuitSuccess)
|
||||||
|
|
||||||
proc daemonize*(pidfile, si, so, se: string, daemonMain: proc(): void): int =
|
proc daemonize*(pidfile, si, so, se: string, daemonMain: proc(): void): Pid =
|
||||||
|
|
||||||
if fileExists(pidfile):
|
if fileExists(pidfile):
|
||||||
raise newException(IOError, "pidfile " & pidfile & " already exists, daemon already running?")
|
raise newException(IOError, "pidfile " & pidfile & " already exists, daemon already running?")
|
||||||
@ -125,15 +147,15 @@ proc daemonize*(pidfile, si, so, se: string, daemonMain: proc(): void): int =
|
|||||||
flushFile(stdout)
|
flushFile(stdout)
|
||||||
flushFile(stderr)
|
flushFile(stderr)
|
||||||
|
|
||||||
if not si.isNil and si != "":
|
if si.len > 0:
|
||||||
fi = open(si, fmRead)
|
fi = open(si, fmRead)
|
||||||
discard dup2(getFileHandle(fi), getFileHandle(stdin))
|
discard dup2(getFileHandle(fi), getFileHandle(stdin))
|
||||||
|
|
||||||
if not so.isNil and so != "":
|
if so.len > 0:
|
||||||
fo = open(so, fmAppend)
|
fo = open(so, fmAppend)
|
||||||
discard dup2(getFileHandle(fo), getFileHandle(stdout))
|
discard dup2(getFileHandle(fo), getFileHandle(stdout))
|
||||||
|
|
||||||
if not se.isNil and so != "":
|
if se.len > 0:
|
||||||
fe = open(se, fmAppend)
|
fe = open(se, fmAppend)
|
||||||
discard dup2(getFileHandle(fe), getFileHandle(stderr))
|
discard dup2(getFileHandle(fe), getFileHandle(stderr))
|
||||||
|
|
||||||
@ -151,3 +173,28 @@ proc daemonize*(pidfile, si, so, se: string, daemonMain: proc(): void): int =
|
|||||||
daemonMain()
|
daemonMain()
|
||||||
|
|
||||||
return pid1
|
return pid1
|
||||||
|
|
||||||
|
const termReset* = "\e[0;m"
|
||||||
|
|
||||||
|
proc termColor*(color: TermColor, bright, bold = false): string =
|
||||||
|
var colorVal = ord(color)
|
||||||
|
if bright: inc(colorVal, 60)
|
||||||
|
return "\e[" & $colorVal & (if bold: ";1" else: "") & "m"
|
||||||
|
|
||||||
|
proc withColor*(str: string, color: TermColor, bright, bold = false): string =
|
||||||
|
return termColor(color, bright, bold) & str
|
||||||
|
|
||||||
|
let STRIP_ANSI_REGEX = re"\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K]"
|
||||||
|
|
||||||
|
proc stripAnsi*(str: string): string = return str.replace(STRIP_ANSI_REGEX, "")
|
||||||
|
|
||||||
|
proc queryParamsToCliArgs*(queryParams: StringTableRef): seq[string] =
|
||||||
|
result = @[]
|
||||||
|
|
||||||
|
for k,v in queryParams:
|
||||||
|
# support ?arg1=val1&arg2=val2 -> cmd val1 val2
|
||||||
|
if k.startsWith("arg"): result.add(v)
|
||||||
|
|
||||||
|
else :
|
||||||
|
result[1].add("--" & k)
|
||||||
|
if v != "true": result[1].add(v) # support things like ?verbose=true -> cmd --verbose
|
||||||
|
@ -1,11 +1,11 @@
|
|||||||
# Package
|
# Package
|
||||||
|
|
||||||
version = "0.2.0"
|
version = "0.6.0"
|
||||||
author = "Jonathan Bernard"
|
author = "Jonathan Bernard"
|
||||||
description = "Helper functions for writing command line interfaces."
|
description = "Helper functions for writing command line interfaces."
|
||||||
license = "MIT"
|
license = "MIT"
|
||||||
|
|
||||||
# Dependencies
|
# Dependencies
|
||||||
|
|
||||||
requires @["nim >= 0.15.3", "docopt"]
|
requires @["nim >= 0.19.0", "docopt >= 0.6.8"]
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user