in src/doc_builder/style_doc.py [0:0]
def style_mdx_file(mdx_file, max_len=119, check_only=False):
"""
Style a MDX file by formatting all Python code samples.
Args:
mdx_file (`str` or `os.PathLike`): The file in which we want to style the examples.
max_len (`int`): The maximum number of characters per line.
check_only (`bool`, *optional*, defaults to `False`):
Whether to restyle file or just check if they should be restyled.
Returns:
`bool`: Whether or not the file was or should be restyled.
"""
with open(mdx_file, "r", encoding="utf-8", newline="\n") as f:
content = f.read()
lines = content.split("\n")
current_code = []
current_language = ""
in_code = False
new_lines = []
black_errors = []
for line in lines:
if _re_code.search(line) is not None:
in_code = not in_code
if in_code:
current_language = _re_code.search(line).groups()[1]
current_code = []
else:
code = "\n".join(current_code)
if current_language in ["py", "python"]:
code, error = format_code_example(code, max_len)
if len(error) > 0:
black_errors.append(error)
new_lines.append(code)
new_lines.append(line)
elif in_code:
current_code.append(line)
else:
new_lines.append(line)
if in_code:
raise ValueError(f"There was a problem when styling {mdx_file}. A code block is opened without being closed.")
clean_content = "\n".join(new_lines)
diff = clean_content != content
if not check_only and diff:
print(f"Overwriting content of {mdx_file}.")
with open(mdx_file, "w", encoding="utf-8", newline="\n") as f:
f.write(clean_content)
return diff, "\n\n".join(black_errors)