blob: c2d783709b95977b82efc1fc8ee43683c7026b10 [file] [log] [blame]
# Copyright 2024 The Fuchsia Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
def _clang_format(
ctx,
tool_ctx = lambda ctx: "clang-format",
extra_args = [],
emit_level = "error",
emit_message = "File is not formatted.",
# For testing
file_filter = lambda x: True):
"""Formats C/C++ files using clang-format."""
tool = tool_ctx(ctx)
base_cmd = [tool]
cc_files = [
f
for f in ctx.scm.affected_files()
if f.endswith((".c", ".cc", ".cpp", ".h")) and
file_filter(f)
]
if not cc_files:
return
original_contents = {}
procs = {}
for filepath in cc_files:
original = str(ctx.io.read_file(filepath))
original_contents[filepath] = original
procs[filepath] = ctx.os.exec(base_cmd + extra_args + [filepath])
for filepath, proc in procs.items():
res = proc.wait()
original = original_contents[filepath]
if res.stdout != original:
ctx.emit.finding(
filepath = filepath,
level = emit_level,
message = emit_message,
replacements = [res.stdout],
)
clang_format = shac.check(_clang_format, formatter = True)