From 472ecf7b259f727e7aec67c2bfb275f785b53261 Mon Sep 17 00:00:00 2001 From: Sekulum Forka Date: Sat, 15 May 2021 13:31:16 +0200 Subject: [PATCH] builtins: Added an if command --- src/fsh.nim | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/src/fsh.nim b/src/fsh.nim index 0746d1b..886126c 100644 --- a/src/fsh.nim +++ b/src/fsh.nim @@ -18,11 +18,12 @@ for k, v in envPairs(): envVariables[k]=v # list of builtin commands -let builtins: array[4, string] = [ +let builtins: array[5, string] = [ "set", "setenv", "echo", "exit", +"if", ] # Exception types @@ -63,6 +64,7 @@ proc newShellCommandException(msg: string, command: string, line=0, col=0, while # forward declarations proc eval(cmd: string): string +proc execute(cmd: string): int proc substitute(strm: Stream, delim = ";\p"): string # ctrlc is the ctrl-c handler @@ -281,6 +283,28 @@ proc runBuiltin(builtin: string, args: openArray[string]): (string, int) = except ValueError: stdout.write(args.join(" "), "\p") quit(0) + of "if": + var i=0 + while true: + # if i is greater than args.high, we exit out. user probs doesn't want an else branch, we aren't going to stop him + if i > args.high: + break + + # Check if this is the last item, if so just execute it + # It's an else branch basically + if i == args.high: + return ("", execute(args[i])) + # Get the exitcode of the current arg (the condition) + let exitcode = args[i].execute + if exitcode == 0: + # if the condition is true + return ("", args[i+1].execute) + else: + # if the condition is false + i.inc + i.inc + continue + else: raise newShellCommandException("No such builtin implemented", builtin)