Add mkpatsubst

Bug: 181797530
Test: rbcrun build/make/tests/run.rbc
Change-Id: Id15daaf6e3ed68982e50cdc710563095ffcf57ba
This commit is contained in:
Sasha Smundak
2021-07-12 15:41:28 -07:00
parent 827998ad08
commit 3b25eb1c98
2 changed files with 43 additions and 0 deletions

View File

@@ -433,6 +433,38 @@ def _mkinfo(file, message = ""):
"""Prints info."""
print(message)
def __mkpatsubst_word(parsed_pattern,parsed_subst, word):
(before, after) = parsed_pattern
if not word.startswith(before):
return word
if not word.endswith(after):
return word
if len(parsed_subst) < 2:
return parsed_subst[0]
return parsed_subst[0] + word[len(before):len(word) - len(after)] + parsed_subst[1]
def _mkpatsubst(pattern, replacement, s):
"""Emulates Make's patsubst.
Tokenizes `s` (unless it is already a list), and then performs a simple
wildcard substitution (in other words, `foo%bar` pattern is equivalent to
the regular expression `^foo(.*)bar$, and the first `%` in replacement is
$1 in regex terms). Escaping % is not supported
"""
if pattern.find("\\") >= 0:
fail("'\\' in pattern is not allowed")
parsed_pattern = pattern.split("%", 1)
words = s if type(s) == "list" else _mkstrip(s).split(" ")
if len(parsed_pattern) == 1:
out_words = [ replacement if x == pattern else x for x in words]
else:
parsed_replacement = replacement.split("%", 1)
out_words = [__mkpatsubst_word(parsed_pattern, parsed_replacement, x) for x in words]
return out_words if type(s) == "list" else " ".join(out_words)
def _mkstrip(s):
"""Emulates Make's strip.
@@ -507,6 +539,7 @@ rblf = struct(
indirect = _indirect,
mkinfo = _mkinfo,
mkerror = _mkerror,
mkpatsubst = _mkpatsubst,
mkwarning = _mkwarning,
mkstrip = _mkstrip,
mksubst = _mksubst,