in dockerfiles.py [0:0]
def substitute_from_directives(content: str, base_dir: str) -> str:
"""
Recursively replace lines of the form:
FROM identifier
where 'identifier' is composed of letters and dashes, with the contents of
<identifier>.Dockerfile found in 'base_dir'.
Args:
content (str): The Dockerfile content to process.
base_dir (str): The directory containing base Dockerfiles to include.
Returns:
str: The processed Dockerfile content with all FROM directives substituted.
"""
pattern = re.compile(r"^(FROM)\s+([A-Za-z-]+)\s*$")
lines = content.splitlines()
new_lines = []
for line in lines:
match = pattern.match(line)
if match:
identifier = match.group(2)
file_path = os.path.join(base_dir, f"{identifier}.Dockerfile")
if os.path.isfile(file_path):
try:
with open(file_path, "r", encoding="utf-8") as inc_file:
included_content = inc_file.read()
# Recursively process the included file's content
substituted_content = substitute_from_directives(included_content, base_dir)
new_lines.append(substituted_content.rstrip())
except OSError as e:
logger.error("Error reading included file '%s': %s", file_path, e)
new_lines.append(line)
else:
# If no file found, leave the line as is.
new_lines.append(line)
else:
new_lines.append(line)
return "\n".join(new_lines)