blob: 81ca450dcd0b3f5460a717e7b4e377254812a304 [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.
"""Common helper functions for the starlark checks."""
def get_affected_files(ctx, file_filter = lambda x: True):
return [
f
for f in ctx.scm.affected_files()
if (
f.endswith((".star", ".bzl", ".bazel", ".bzlmod", ".BUILD", ".WORKSPACE")) or
f.split("/")[-1] in ("/BUILD", "/WORKSPACE")
) and
file_filter(f)
]
def _run_command(ctx, command, files):
res = ctx.os.exec(command + files, ok_retcodes = (0, 4)).wait()
if res.retcode != 0:
fail(res)
return json.decode(res.stdout)
def get_unformatted_files(ctx, command, files):
data = _run_command(ctx, command, files)
if data["success"]:
return None
data["files"] = [i for i in data["files"] if not i["formatted"]]
return data
def get_files_with_warnings(ctx, command, files):
data = _run_command(ctx, command, files)
if data["success"]:
return None
data["files"] = [i for i in data["files"] if i["warnings"]]
return data
def apply_fixes_to_files(ctx, command, data, emit_level = "error", emit_message = "File is not linted."):
tempfiles = {}
warning_messages = {}
for file in data["files"]:
filename = file["filename"]
msg = "\n -> ".join([s["message"] for s in file["warnings"]])
if len(msg) > 0:
msg = "\n -> " + msg
warning_messages[filename] = msg
tempfiles[filename] = ctx.io.tempfile(ctx.io.read_file(filename), name = filename)
ctx.os.exec(command + tempfiles.values()).wait()
for filepath, temp in tempfiles.items():
formatted = ctx.io.read_file(temp)
msg = emit_message + warning_messages[filepath]
ctx.emit.finding(
level = emit_level,
filepath = filepath,
message = msg,
replacements = [str(formatted)],
)
return tempfiles