Variables: Added a readVariable and evalVariable procedures

This commit is contained in:
Sekulum Forka 2021-05-11 18:31:02 +02:00
parent c00678603b
commit 8a5e6c3cea
1 changed files with 39 additions and 0 deletions

View File

@ -5,9 +5,20 @@
# imports
import streams
import osproc
import strtabs
import os
# globals
var shellVariables = newStringTable(modeCaseSensitive)
# Environment variables get defined in a separate var
var envVariables = newStringTable(modeCaseSensitive)
# populate the table
for k, v in envPairs():
envVariables[k]=v
# forward declarations
proc eval(cmd: string): string
proc substitute(strm: Stream, delim = ";\p"): string
# skipSpaces reads the stream until a non-space character is found
proc skipSpaces(strm: Stream): int =
@ -103,6 +114,34 @@ proc readCommand(strm: Stream): string =
of '\n', '\r', ';': break
else: result.add(c)
# readVariable reads a variable
proc readVariable(strm: Stream): string =
let c = strm.readChar()
case c:
of '{':
result = strm.readLiteral()
of '[':
result.add(strm.readInterpelation)
of '"':
result.add(strm.readSubstitution())
of ']', '}':
stderr.write("Unexpected " & c & ".\n")
else:
result.add(c)
while not strm.atEnd():
let d = strm.readChar()
case d:
of 'a'..'z', 'A'..'Z', '0'..'9', '_', ':': result.add(d)
else: break
# evalVariable finds a value of a variable
proc evalVariable(vari: string): string =
if shellVariables.hasKey(vari):
result=shellVariables[vari]
elif envVariables.hasKey(vari):
result = envVariables[vari]
else: raise newException(Exception, "No such variable: " & vari & ".")
# substitute does a substitution on the stream passed in
proc substitute(strm: Stream, delim=";\p"): string =
while not strm.atEnd():