[bazel_to_cmake] rework escape hatches (#4943)
Following Stella's frustration at finding the escape hatches, I've
reworked them. They're now all mentioned in comments in the
autogenerated file itself.
The autogenerated header itself is used as an indicator for whether to
modify the file and trailing lines can always be preserved for quick
hacks that don't have positional requirements.
diff --git a/build_tools/bazel_to_cmake/bazel_to_cmake.py b/build_tools/bazel_to_cmake/bazel_to_cmake.py
index 0d8beb5..344cc38 100755
--- a/build_tools/bazel_to_cmake/bazel_to_cmake.py
+++ b/build_tools/bazel_to_cmake/bazel_to_cmake.py
@@ -43,6 +43,8 @@
r"bazel[\s_]*to[\s_]*cmake[\s_]*:?[\s_]*do[\s_]*not[\s_]*edit",
flags=re.IGNORECASE)
+PRESERVE_TAG = "### BAZEL_TO_CMAKE_PRESERVES_ALL_CONTENT_BELOW_THIS_LINE ###"
+
class Status(Enum):
SUCCEEDED = 1
@@ -160,28 +162,47 @@
if not os.path.isfile(build_file_path):
return Status.NO_BUILD_FILE
- if os.path.isfile(cmakelists_file_path):
- with open(cmakelists_file_path) as f:
- for i, line in enumerate(f):
- if EDIT_BLOCKING_PATTERN.search(line):
- if verbosity >= 1:
- log(f"Skipped. line {i + 1}: '{line.strip()}' prevents edits.",
- indent=2)
- return Status.SKIPPED
+ autogeneration_tag = f"Autogenerated by {repo_relpath(os.path.abspath(__file__))}"
- header = (f"# Autogenerated from {rel_build_file_path} by\n"
- f"# {repo_relpath(os.path.abspath(__file__))}")
+ header = "\n".join(["#" * 80] + [
+ l.ljust(79) + "#" for l in [
+ f"# {autogeneration_tag} from",
+ f"# {rel_build_file_path}",
+ "#",
+ "# Use iree_cmake_extra_content from iree/build_defs.oss.bzl to add arbitrary",
+ "# CMake-only content.",
+ "#",
+ f"# To disable autogeneration for this file entirely, delete this header.",
+ ]
+ ] + ["#" * 80])
+
+ preserved_footer = ["\n" + PRESERVE_TAG + "\n"]
+ if os.path.isfile(cmakelists_file_path):
+ found_autogeneration_tag = False
+ found_preserve_tag = False
+ with open(cmakelists_file_path) as f:
+ for line in f:
+ if not found_autogeneration_tag and autogeneration_tag in line:
+ found_autogeneration_tag = True
+ if not found_preserve_tag and PRESERVE_TAG in line:
+ found_preserve_tag = True
+ elif found_preserve_tag:
+ preserved_footer.append(line)
+ if not found_autogeneration_tag:
+ if verbosity >= 1:
+ log(f"Skipped. Did not find autogeneration line.", indent=2)
+ return Status.SKIPPED
with open(build_file_path, "rt") as build_file:
build_file_code = compile(build_file.read(), build_file_path, "exec")
try:
converted_text = bazel_to_cmake_converter.convert_build_file(
- build_file_code,
- header,
- allow_partial_conversion=allow_partial_conversion)
+ build_file_code, allow_partial_conversion=allow_partial_conversion)
if write_files:
with open(cmakelists_file_path, "wt") as cmakelists_file:
+ cmakelists_file.write(header)
cmakelists_file.write(converted_text)
+ cmakelists_file.writelines(preserved_footer)
else:
print(converted_text, end="")
except (NameError, NotImplementedError) as e: