You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

38 lines
1.1 KiB

  1. def replace(template, ctx):
  2. """Replace placeholders with their values and return the result.
  3. Example:
  4. >>> replace("$NAME is down", {"$NAME": "foo"})
  5. foo is down
  6. This function explicitly ignores "variable variables".
  7. In this example, placeholder's value itself contains a placeholder:
  8. >>> replace("Hello $FOO", {"$FOO": "$BAR", "$BAR": "World"})
  9. Wrong: Hello World
  10. Correct: Hello $BAR
  11. >>> replace("Hello $$FOO", {"$FOO": "BAR", "$BAR": "World"})
  12. Wrong: Hello World
  13. Correct: Hello $BAR
  14. In other words, this function only replaces placeholders that appear
  15. in the original template. It ignores any placeholders that "emerge"
  16. during string substitutions. This is done mainly to avoid unexpected
  17. behavior when check names or tags contain dollar signs.
  18. """
  19. parts = template.split("$")
  20. result = [parts.pop(0)]
  21. for part in parts:
  22. part = "$" + part
  23. for placeholder, value in ctx.items():
  24. if part.startswith(placeholder):
  25. part = part.replace(placeholder, value, 1)
  26. break
  27. result.append(part)
  28. return "".join(result)