|
| 1 | +def _check_format(ctx, exe, config, infile, clang_format_bin): |
| 2 | + output = ctx.actions.declare_file(infile.path + ".clang-format.txt") |
| 3 | + |
| 4 | + args = ctx.actions.args() |
| 5 | + |
| 6 | + args.add("check_file") |
| 7 | + args.add(clang_format_bin.path) |
| 8 | + args.add(infile.path) |
| 9 | + args.add(output.path) |
| 10 | + |
| 11 | + ctx.actions.run( |
| 12 | + inputs = [clang_format_bin, infile, config], |
| 13 | + outputs = [output], |
| 14 | + executable = exe, |
| 15 | + arguments = [args], |
| 16 | + mnemonic = "ClangFormat", |
| 17 | + progress_message = "Check clang-format on {}".format(infile.short_path), |
| 18 | + ) |
| 19 | + return output |
| 20 | + |
| 21 | +def _extract_files(ctx): |
| 22 | + files = [] |
| 23 | + if hasattr(ctx.rule.attr, "srcs"): |
| 24 | + for src in ctx.rule.attr.srcs: |
| 25 | + files += [src for src in src.files.to_list() if src.is_source] |
| 26 | + |
| 27 | + if hasattr(ctx.rule.attr, "hdrs"): |
| 28 | + for hdr in ctx.rule.attr.hdrs: |
| 29 | + files += [hdr for hdr in hdr.files.to_list() if hdr.is_source] |
| 30 | + |
| 31 | + return files |
| 32 | + |
| 33 | +def _clang_format_check_aspect_impl(target, ctx): |
| 34 | + # if not a C/C++ target, we are not interested |
| 35 | + if not CcInfo in target: |
| 36 | + return [] |
| 37 | + |
| 38 | + exe = ctx.attr._clang_format.files_to_run |
| 39 | + config = ctx.attr._clang_format_config.files.to_list()[0] |
| 40 | + clang_format_bin = ctx.attr._clang_format_bin.files.to_list()[0] |
| 41 | + files = _extract_files(ctx) |
| 42 | + |
| 43 | + outputs = [] |
| 44 | + for file in files: |
| 45 | + if file.basename.endswith((".c", ".h", ".cpp", ".cc", ".hpp")): |
| 46 | + outputs.append(_check_format(ctx, exe, config, file, clang_format_bin)) |
| 47 | + |
| 48 | + return [ |
| 49 | + OutputGroupInfo(report = depset(direct = outputs)), |
| 50 | + ] |
| 51 | + |
| 52 | +clang_format_check_aspect = aspect( |
| 53 | + implementation = _clang_format_check_aspect_impl, |
| 54 | + fragments = ["cpp"], |
| 55 | + attrs = { |
| 56 | + "_clang_format": attr.label(default = Label("//clang_format:clang_format")), |
| 57 | + "_clang_format_config": attr.label(default = "//clang_format:clang_format_config"), |
| 58 | + "_clang_format_bin": attr.label(default = Label("//clang_format:clang_format_bin")), |
| 59 | + }, |
| 60 | +) |
0 commit comments