Files
lush/testes/lush/interpolation.lua
Cormac Shannon 42baabde34 Implement $VAR expansion in commands (issue #25)
Extend read_command_body() to detect $NAME and trigger interpolation
using the same fragment-split mechanism as ${expr}. The lexer collects
the identifier into cmd_envvar; the parser's unified parseinterp()
branches on it to emit tostring(getenv(NAME)).
2026-03-18 08:35:46 +00:00

113 lines
2.3 KiB
Lua

-- testes/lush/interpolation.lua
-- Tests for ${expr} interpolation in backtick commands (issue #02).
print "testing string interpolation"
-- single interpolation
do
local name = "world"
local r = `echo ${name}`
assert(r.stdout == "world\n")
end
-- multiple interpolations
do
local a = "hello"
local b = "world"
local r = `echo ${a} ${b}`
assert(r.stdout == "hello world\n")
end
-- interpolation with number
do
local n = 42
local r = `echo ${n}`
assert(r.stdout == "42\n")
end
-- interpolation with expression
do
local x = 3
local r = `echo ${x + 1}`
assert(r.stdout == "4\n")
end
-- interpolation with string concatenation
do
local prefix = "hello"
local r = `echo ${prefix .. " world"}`
assert(r.stdout == "hello world\n")
end
-- interpolation surrounded by literal text
do
local mid = "b"
local r = `echo a${mid}c`
assert(r.stdout == "abc\n")
end
-- literal $ (not followed by { or alpha) is kept
do
local r = `echo $`
assert(r.stdout == "$\n")
end
-- $NAME expands environment variable in backtick commands
do
local r = `echo $HOME`
assert(r.stdout:match("^/"), "expected absolute path, got: " .. r.stdout)
end
-- $NAME mid-command expansion
do
local r = `echo hello $USER world`
local expected = "hello " .. $USER .. " world\n"
assert(r.stdout == expected, "got: " .. r.stdout)
end
-- $NAME at end of command
do
local r = `echo $USER`
assert(r.stdout == $USER .. "\n", "got: " .. r.stdout)
end
-- multiple $NAME expansions
do
$_LUSH_INTERP_A = "aaa"
$_LUSH_INTERP_B = "bbb"
local r = `echo $_LUSH_INTERP_A $_LUSH_INTERP_B`
assert(r.stdout == "aaa bbb\n", "got: " .. r.stdout)
$_LUSH_INTERP_A = nil
$_LUSH_INTERP_B = nil
end
-- $NAME adjacent to text (no space)
do
$_LUSH_INTERP_C = "bar"
local r = `echo foo$_LUSH_INTERP_C`
assert(r.stdout == "foobar\n", "got: " .. r.stdout)
$_LUSH_INTERP_C = nil
end
-- $NAME mixed with ${expr}
do
local x = 42
local r = `echo $USER ${x}`
local expected = $USER .. " 42\n"
assert(r.stdout == expected, "got: " .. r.stdout)
end
-- undefined $NAME expands to "nil"
do
local r = `echo $_LUSH_UNDEFINED_VAR_XYZ`
assert(r.stdout == "nil\n", "got: " .. r.stdout)
end
-- escaped \$ remains literal
do
local r = `echo \$HOME`
assert(r.stdout == "$HOME\n", "got: " .. r.stdout)
end
print "OK"