From 91c93b6a95159d02a96094b18919d4853065ef96 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?P=C4=93teris=20Caune?= Date: Wed, 20 Nov 2019 16:01:03 +0200 Subject: [PATCH] Add "Shell Commands" integration. Fixes #302 --- hc/lib/string.py | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 hc/lib/string.py diff --git a/hc/lib/string.py b/hc/lib/string.py new file mode 100644 index 00000000..f27cab85 --- /dev/null +++ b/hc/lib/string.py @@ -0,0 +1,38 @@ +def replace(template, ctx): + """Replace placeholders with their values and return the result. + + Example: + + >>> replace("$NAME is down", {"$NAME": "foo"}) + foo is down + + This function explicitly ignores "variable variables". + In this example, placeholder's value itself contains a placeholder: + + >>> replace("Hello $FOO", {"$FOO": "$BAR", "$BAR": "World"}) + Wrong: Hello World + Correct: Hello $BAR + + >>> replace("Hello $$FOO", {"$FOO": "BAR", "$BAR": "World"}) + Wrong: Hello World + Correct: Hello $BAR + + In other words, this function only replaces placeholders that appear + in the original template. It ignores any placeholders that "emerge" + during string substitutions. This is done mainly to avoid unexpected + behavior when check names or tags contain dollar signs. + + """ + + parts = template.split("$") + + result = [parts.pop(0)] + for part in parts: + part = "$" + part + for placeholder, value in ctx.items(): + if part.startswith(placeholder): + part = part.replace(placeholder, value, 1) + break + result.append(part) + + return "".join(result)