Skip to content

Commit

Permalink
fix(expandvars, LP: #2055348: replace bash shell expansion with custo…
Browse files Browse the repository at this point in the history
…m routine (#222)
  • Loading branch information
st3v3nmw authored Feb 29, 2024
1 parent f8150c1 commit 2e64ecf
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 15 deletions.
36 changes: 24 additions & 12 deletions landscape/lib/format.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import inspect
import subprocess
import re


def format_object(object):
Expand Down Expand Up @@ -35,19 +35,31 @@ def format_percent(percent):
def expandvars(pattern: str, **kwargs) -> str:
"""Expand the pattern by replacing the params with values in `kwargs`.
This uses bash shell parameter expansion. Here are some examples of
possible patterns:
This implements a small subset of shell parameter expansion and the
patterns can only be in the following forms:
- ${parameter}
- ${parameter:offset} - start at `offset` to the end
- ${parameter:offset:length} - start at `offset` to `offset + length`
For simplicity, `offset` and `length` MUST be positive values.
"""
values = {k: str(v) for k, v in kwargs.items()}
shell = subprocess.run(
f'echo -n "{pattern.lower()}"',
text=True,
capture_output=True,
shell=True,
executable="/usr/bin/bash",
env=values,
regex = re.compile(
r"\$\{([a-zA-Z][a-zA-Z0-9]*)(?::([0-9]+))?(?::([0-9]+))?\}",
re.MULTILINE,
)
return shell.stdout
values = {k: str(v) for k, v in kwargs.items()}

def _replace(match):
param = match.group(1)
result = values[param.lower()]

offset, length = match.group(2), match.group(3)
if offset:
start = int(offset)
end = None
if length:
end = start + int(length)
return result[start:end]

return result

return re.sub(regex, _replace, pattern)
6 changes: 3 additions & 3 deletions landscape/lib/tests/test_format.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ def test_expand_without_offset_and_length(self):
"f315cab5:after",
)
self.assertEqual(
expandvars("be\\$fore:${serial}:after", serial="f315cab5"),
expandvars("be$fore:${serial}:after", serial="f315cab5"),
"be$fore:f315cab5:after",
)

Expand All @@ -100,7 +100,7 @@ def test_expand_with_offset(self):
)
self.assertEqual(
expandvars(
"be\\$fore:${serial:7}:after",
"be$fore:${serial:7}:after",
serial="01234567890abcdefgh",
),
"be$fore:7890abcdefgh:after",
Expand All @@ -121,7 +121,7 @@ def test_expand_with_offset_and_length(self):
)
self.assertEqual(
expandvars(
"be\\$fore:${serial:7:2}:after",
"be$fore:${serial:7:2}:after",
serial="01234567890abcdefgh",
),
"be$fore:78:after",
Expand Down

0 comments on commit 2e64ecf

Please sign in to comment.