Skip to content

Commit

Permalink
Sort simple expansion by parameter name length kojiromike#16
Browse files Browse the repository at this point in the history
parameters are sorted by decreasing length such that we expand first
the longest names.

Signed-off-by: Philippe Ombredanne <[email protected]>
  • Loading branch information
pombredanne committed Jul 18, 2021
1 parent 1e91c63 commit e844b32
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 5 deletions.
12 changes: 7 additions & 5 deletions parameter_expansion/pe.py
Original file line number Diff line number Diff line change
Expand Up @@ -164,11 +164,13 @@ def expand_simple(s, env):
Uses the provided environment dict.
Similar to ``os.path.expandvars``.
"""
# TODO: validate if a plain replace is really what is supposed to happen
# in particular simple expansion may need to happen on tokens rather than
# on the whole string.
# For instance, with foo=bar, abc$fooBAR expands to abc
for name, value in env.items():
env_by_decreasing_name_length = sorted(
env.items(),
# [0] is the name. minus its length gets the longest first.
key=lambda name_value: -len(name_value[0]),
)

for name, value in env_by_decreasing_name_length:
s = s.replace(f"${name}", value)
name = "{" + name + "}"
s = s.replace(f"${name}", value)
Expand Down
7 changes: 7 additions & 0 deletions parameter_expansion/tests/test_pe.py
Original file line number Diff line number Diff line change
Expand Up @@ -561,6 +561,13 @@ def test_expand_can_handle_nested_substitution_and_pattern_expand():
assert expanded_var == "alpha19"


def test_expand_simple_expands_longest_param_name_first():
env = dict(pkg="foo", pkgver="bar")
var = "$pkgver"
expanded_var = pex.expand(var, env=env, strict=True)
assert expanded_var == "bar"


def test_tokenize_preserves_spaces():
s = " - $parameter/$aa/${bb} - \t- \n ${parameter/ aa / - zz }- "
tokens = list(parameter_expansion.pe.tokenize(s))
Expand Down

0 comments on commit e844b32

Please sign in to comment.