def replace_var_to_template()

in solutions_builder/cli/vars.py [0:0]


def replace_var_to_template(var_name, text, custom_template=False):
  # Regex test: https://regex101.com/r/XtnJQI/4
  # match_pattern matches lines with sb-var anchor in the comment at the end.
  # For example:
  #   PROJECT_ID: 12345          # sb-var:project_id
  #   region = "us-central1" # sb-var:region
  match_pattern = f"(\\s*[\":=-][ ]*)(-[ ]*)?([\"\']?)([^\"^\'^\r^\n]*)([\"\']?)\\s*#\\s*sb-var:{var_name}"

  # output_pattern prints the jinja2 template for the specific variable name.
  # For example:
  #   PROJECT_ID: {{project_id}} # sb-var:project_id
  output_pattern = f"\\1\\2\\3{{{{{var_name}}}}}\\5 # sb-var:{var_name}"

  # In addition, if custom_template is true, the pattern will extend to the custom
  # template string at the end of the anchor. For example:
  #   BUCKET_NAME: my-project-bucket # sb-var:project_id:{{project_id}}-bucket
  if custom_template:
    match_pattern = match_pattern + ":(.*)"
    output_pattern = f"\\1\\2\\3\\6\\5 # sb-var:{var_name}:\\6"

  # Replace with regex pattern and returns new text and count of changes.
  text, count = re.subn(match_pattern, output_pattern, text)

  return (text, count)