mirror of
https://github.com/samsonjs/csc360-a1-shell.git
synced 2026-04-27 14:57:43 +00:00
Expand default values recursively
This commit is contained in:
parent
5172c60910
commit
44dcfa7ba6
2 changed files with 20 additions and 6 deletions
|
|
@ -3,6 +3,7 @@ require "shellwords"
|
||||||
module Shell
|
module Shell
|
||||||
class WordExpander
|
class WordExpander
|
||||||
ENV_VAR_REGEX = /\$(?:\{([^}]+)\}|(\w+)\b)/
|
ENV_VAR_REGEX = /\$(?:\{([^}]+)\}|(\w+)\b)/
|
||||||
|
DEFAULT_VAR_REGEX = /\A(\w+):-([\s\S]*)\z/
|
||||||
ESCAPED_DOLLAR = "\u0001"
|
ESCAPED_DOLLAR = "\u0001"
|
||||||
|
|
||||||
# Splits the given line into multiple words, performing the following transformations:
|
# Splits the given line into multiple words, performing the following transformations:
|
||||||
|
|
@ -15,12 +16,7 @@ module Shell
|
||||||
protected_line = protect_escaped_dollars(line)
|
protected_line = protect_escaped_dollars(line)
|
||||||
shellsplit(protected_line)
|
shellsplit(protected_line)
|
||||||
.map do |word|
|
.map do |word|
|
||||||
word
|
expand_variables(word).tr(ESCAPED_DOLLAR, "$")
|
||||||
.gsub(ENV_VAR_REGEX) do
|
|
||||||
name = Regexp.last_match(2) || Regexp.last_match(1)
|
|
||||||
ENV.fetch(name)
|
|
||||||
end
|
|
||||||
.tr(ESCAPED_DOLLAR, "$")
|
|
||||||
# TODO: expand globs
|
# TODO: expand globs
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
@ -98,6 +94,20 @@ module Shell
|
||||||
Dir.glob(word)
|
Dir.glob(word)
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def expand_variables(value)
|
||||||
|
value.gsub(ENV_VAR_REGEX) do
|
||||||
|
raw = Regexp.last_match(2) || Regexp.last_match(1)
|
||||||
|
if (m = DEFAULT_VAR_REGEX.match(raw))
|
||||||
|
name = m[1]
|
||||||
|
fallback = m[2]
|
||||||
|
env_value = ENV[name]
|
||||||
|
env_value.nil? || env_value.empty? ? expand_variables(fallback) : env_value
|
||||||
|
else
|
||||||
|
ENV.fetch(raw)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
def protect_escaped_dollars(line)
|
def protect_escaped_dollars(line)
|
||||||
output = +""
|
output = +""
|
||||||
i = 0
|
i = 0
|
||||||
|
|
|
||||||
|
|
@ -88,6 +88,10 @@ class ShellTest < Minitest::Test
|
||||||
assert_equal "fallback", `#{A1_PATH} -c 'echo ${A1_UNSET_VAR:-fallback}'`.chomp
|
assert_equal "fallback", `#{A1_PATH} -c 'echo ${A1_UNSET_VAR:-fallback}'`.chomp
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def test_expands_parameter_default_value_with_variable_reference
|
||||||
|
assert_equal Dir.home, `#{A1_PATH} -c 'echo ${A1_UNSET_VAR:-$HOME}'`.chomp
|
||||||
|
end
|
||||||
|
|
||||||
#################################
|
#################################
|
||||||
### Execution and job control ###
|
### Execution and job control ###
|
||||||
#################################
|
#################################
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue