in compute/client_library/sgs.py [0:0]
def render_recipe(recipe: str, ingredients: dict) -> str:
"""
Replace all `# IMPORTS` and `# INGREDIENT <name>` occurrences in
the provided recipe, producing a script ready to be saved to a file.
"""
ingredients_used = []
file_lines = recipe.splitlines()
# Scan the file to used ingredients
for line in file_lines:
match = INGREDIENT_FILL.match(line)
if match:
ingredients_used.append(ingredients[match.group(1)])
simple_imports_used = set()
for ingredient in ingredients_used:
for simple_import in ingredient.simple_imports:
simple_imports_used.add(simple_import)
from_imports_used = defaultdict(set)
for ingredient in ingredients_used:
for import_from in ingredient.imports_from:
from_imports_used[import_from[0]].add(import_from[1])
import_lines = set()
for simple_import in simple_imports_used:
if simple_import.asname:
import_lines.add(f"import {simple_import.name} as {simple_import.asname}")
else:
import_lines.add(f"import {simple_import.name}")
for module, from_imports in from_imports_used.items():
names = set()
for from_import in from_imports:
if from_import.asname:
name = f"{from_import.name} as {from_import.asname}"
else:
name = from_import.name
names.add(name)
names = ", ".join(names)
import_lines.add(f"from {module} import {names}")
import_lines = isort.code(
"\n".join(import_lines), config=isort.Config(profile="google")
)
output_file = []
header_added = False
for line in file_lines:
if IMPORTS_FILL.search(line):
output_file.append(import_lines)
elif INGREDIENT_FILL.search(line):
match = INGREDIENT_FILL.search(line)
output_file.append(ingredients[match.group(1)].text)
elif REGION_START.search(line):
# The string has to be broken up, so that the snippet
# machine doesn't recognize it as a valid start of a region
output_file.append(REGION_START.sub("# [" + "START \\1]", line))
elif REGION_END.search(line):
# The string has to be broken up, so that the snippet
# machine doesn't recognize it as a valid start of a region
output_file.append(REGION_END.sub("# [" + "END \\1]", line))
else:
output_file.append(line)
continue
if not header_added:
end = output_file[-1]
output_file[-1] = ""
output_file.append(HEADER)
output_file.append("")
output_file.append(end)
header_added = True
if output_file and not output_file[-1].endswith("\n"):
output_file.append("")
return os.linesep.join(output_file)