기호 매크로 만들기

문제 신고 소스 보기 나이틀리 빌드 · 8.4 · 8.3 · 8.2 · 8.1 · 8.0 · 7.6

중요: 이 튜토리얼은 Bazel 8에 도입된 새로운 매크로 시스템인 기호 매크로를 위한 것입니다. 이전 Bazel 버전을 지원해야 하는 경우 대신 기존 매크로를 작성해야 합니다. 기존 매크로 만들기를 참고하세요.

빌드의 일부로 도구를 실행해야 한다고 가정해 보겠습니다. 예를 들어 소스 파일을 생성하거나 전처리하거나 바이너리를 압축할 수 있습니다. 이 튜토리얼에서는 이미지 크기를 조절하는 기호 매크로를 만듭니다.

매크로는 간단한 작업에 적합합니다. 새 프로그래밍 언어 지원 추가와 같이 더 복잡한 작업을 하려면 규칙을 만드는 것이 좋습니다. 규칙을 사용하면 더 많은 제어 기능과 유연성을 확보할 수 있습니다.

이미지 크기를 조절하는 매크로를 만드는 가장 쉬운 방법은 genrule를 사용하는 것입니다.

genrule(
    name = "logo_miniature",
    srcs = ["logo.png"],
    outs = ["small_logo.png"],
    cmd = "convert $< -resize 100x100 $@",
)

cc_binary(
    name = "my_app",
    srcs = ["my_app.cc"],
    data = [":logo_miniature"],
)

이미지 크기를 더 조정해야 하는 경우 코드를 재사용하는 것이 좋습니다. 이렇게 하려면 별도의 .bzl 파일에 구현 함수매크로 선언을 정의하고 파일 이름을 miniature.bzl로 지정합니다.

# Implementation function
def _miniature_impl(name, visibility, src, size, **kwargs):
    native.genrule(
        name = name,
        visibility = visibility,
        srcs = [src],
        outs = [name + "_small_" + src.name],
        cmd = "convert $< -resize " + size + " $@",
        **kwargs,
    )

# Macro declaration
miniature = macro(
    doc = """Create a miniature of the src image.

    The generated file name will be prefixed with `name + "_small_"`.
    """,
    implementation = _miniature_impl,
    # Inherit most of genrule's attributes (such as tags and testonly)
    inherit_attrs = native.genrule,
    attrs = {
        "src": attr.label(
            doc = "Image file",
            allow_single_file = True,
            # Non-configurable because our genrule's output filename is
            # suffixed with src's name. (We want to suffix the output file with
            # srcs's name because some tools that operate on image files expect
            # the files to have the right file extension.)
            configurable = False,
        ),
        "size": attr.string(
            doc = "Output size in WxH format",
            default = "100x100",
        ),
        # Do not allow callers of miniature() to set srcs, cmd, or outs -
        # _miniature_impl overrides their values when calling native.genrule()
        "srcs": None,
        "cmd": None,
        "outs": None,
    },
)

참고 사항:

  • 기호 매크로 구현 함수에는 namevisibility 매개변수가 있어야 합니다. 매크로의 기본 타겟에 사용해야 합니다.

  • 기호 매크로의 동작을 문서화하려면 macro() 및 속성에 doc 매개변수를 사용합니다.

  • genrule 또는 다른 네이티브 규칙을 호출하려면 native.를 사용하세요.

  • **kwargs를 사용하여 상속된 추가 인수를 기본 genrule에 전달합니다 (Python에서와 동일하게 작동함). 이를 통해 사용자가 tags 또는 testonly과 같은 표준 속성을 설정할 수 있습니다.

이제 BUILD 파일의 매크로를 사용합니다.

load("//path/to:miniature.bzl", "miniature")

miniature(
    name = "logo_miniature",
    src = "image.png",
)

cc_binary(
    name = "my_app",
    srcs = ["my_app.cc"],
    data = [":logo_miniature"],
)