Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Protobuf formatting using buf format #14907

Merged
merged 6 commits into from
Mar 25, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 9 additions & 18 deletions src/python/pants/backend/codegen/protobuf/lint/buf/format_rules.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from dataclasses import dataclass

from pants.backend.codegen.protobuf.lint.buf.skip_field import SkipBufField
from pants.backend.codegen.protobuf.lint.buf.skip_field import SkipBufFormatField
from pants.backend.codegen.protobuf.lint.buf.subsystem import BufSubsystem
from pants.backend.codegen.protobuf.target_types import (
ProtobufDependenciesField,
Expand Down Expand Up @@ -38,7 +38,7 @@ class BufFieldSet(FieldSet):

@classmethod
def opt_out(cls, tgt: Target) -> bool:
return tgt.get(SkipBufField).value
return tgt.get(SkipBufFormatField).value


class BufFormatRequest(LintTargetsRequest, FmtRequest):
Expand Down Expand Up @@ -95,9 +95,10 @@ async def setup_buf_format(setup_request: SetupRequest, buf: BufSubsystem) -> Se
argv = [
downloaded_buf.exe,
"format",
# If linting, use `-d` to error with a diff. Else, write the change with `-w`.
*(["-d"] if setup_request.check_only else ["-w"]),
*buf.args,
# If linting, use `-d` to error with a diff and `--exit-code` to exit with a non-zero exit code if
# the file is not already formatted. Else, write the change with `-w`.
*(["-d", "--exit-code"] if setup_request.check_only else ["-w"]),
*buf.format_args,
"--path",
",".join(source_files_snapshot.files),
]
Expand All @@ -116,7 +117,7 @@ async def setup_buf_format(setup_request: SetupRequest, buf: BufSubsystem) -> Se

@rule(desc="Format with buf format", level=LogLevel.DEBUG)
async def run_buf_format(request: BufFormatRequest, buf: BufSubsystem) -> FmtResult:
if buf.skip:
if buf.skip_format:
return FmtResult.skip(formatter_name=request.name)
setup = await Get(Setup, SetupRequest(request, check_only=False))
result = await Get(ProcessResult, Process, setup.process)
Expand All @@ -132,21 +133,11 @@ async def run_buf_format(request: BufFormatRequest, buf: BufSubsystem) -> FmtRes

@rule(desc="Lint with buf format", level=LogLevel.DEBUG)
async def run_buf_lint(request: BufFormatRequest, buf: BufSubsystem) -> LintResults:
if buf.skip:
if buf.skip_format:
return LintResults([], linter_name=request.name)
setup = await Get(Setup, SetupRequest(request, check_only=True))
result = await Get(FallibleProcessResult, Process, setup.process)

return LintResults(
[
LintResult(
exit_code=0 if not result.stdout else 1, # buf format always exits with code 0
stdout=result.stdout.decode(),
stderr=result.stderr.decode(),
)
],
linter_name=request.name,
)
return LintResults([LintResult.from_fallible_process_result(result)], linter_name=request.name)


def rules():
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ def test_failing(rule_runner: RuleRunner) -> None:
tgt = rule_runner.get_target(Address("", target_name="t", relative_file_path="f.proto"))
lint_results, fmt_result = run_buf(rule_runner, [tgt])
assert len(lint_results) == 1
assert lint_results[0].exit_code == 1
assert lint_results[0].exit_code == 100
assert "f.proto.orig" in lint_results[0].stdout
assert fmt_result.output == get_snapshot(rule_runner, {"f.proto": GOOD_FILE})
assert fmt_result.did_change is True
Expand All @@ -112,7 +112,7 @@ def test_multiple_targets(rule_runner: RuleRunner) -> None:
]
lint_results, fmt_result = run_buf(rule_runner, tgts)
assert len(lint_results) == 1
assert lint_results[0].exit_code == 1
assert lint_results[0].exit_code == 100
assert "bad.proto.orig" in lint_results[0].stdout
assert "good.proto" not in lint_results[0].stdout
assert fmt_result.output == get_snapshot(
Expand All @@ -124,7 +124,7 @@ def test_multiple_targets(rule_runner: RuleRunner) -> None:
def test_passthrough_args(rule_runner: RuleRunner) -> None:
rule_runner.write_files({"f.proto": GOOD_FILE, "BUILD": "protobuf_sources(name='t')"})
tgt = rule_runner.get_target(Address("", target_name="t", relative_file_path="f.proto"))
lint_results, fmt_result = run_buf(rule_runner, [tgt], extra_args=["--buf-args=--debug"])
lint_results, fmt_result = run_buf(rule_runner, [tgt], extra_args=["--buf-format-args=--debug"])
assert len(lint_results) == 1
assert lint_results[0].exit_code == 0
assert lint_results[0].stdout == ""
Expand All @@ -137,7 +137,7 @@ def test_passthrough_args(rule_runner: RuleRunner) -> None:
def test_skip(rule_runner: RuleRunner) -> None:
rule_runner.write_files({"f.proto": BAD_FILE, "BUILD": "protobuf_sources(name='t')"})
tgt = rule_runner.get_target(Address("", target_name="t", relative_file_path="f.proto"))
lint_results, fmt_result = run_buf(rule_runner, [tgt], extra_args=["--buf-skip"])
lint_results, fmt_result = run_buf(rule_runner, [tgt], extra_args=["--buf-format-skip"])
assert not lint_results
assert fmt_result.skipped is True
assert fmt_result.did_change is False
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from dataclasses import dataclass

from pants.backend.codegen.protobuf.lint.buf.skip_field import SkipBufField
from pants.backend.codegen.protobuf.lint.buf.skip_field import SkipBufLintField
from pants.backend.codegen.protobuf.lint.buf.subsystem import BufSubsystem
from pants.backend.codegen.protobuf.target_types import (
ProtobufDependenciesField,
Expand Down Expand Up @@ -31,7 +31,7 @@ class BufFieldSet(FieldSet):

@classmethod
def opt_out(cls, tgt: Target) -> bool:
return tgt.get(SkipBufField).value
return tgt.get(SkipBufLintField).value


class BufLintRequest(LintTargetsRequest):
Expand All @@ -41,7 +41,7 @@ class BufLintRequest(LintTargetsRequest):

@rule(desc="Lint with buf lint", level=LogLevel.DEBUG)
async def run_buf(request: BufLintRequest, buf: BufSubsystem) -> LintResults:
if buf.skip:
if buf.skip_lint:
return LintResults([], linter_name=request.name)

transitive_targets = await Get(
Expand Down Expand Up @@ -91,7 +91,7 @@ async def run_buf(request: BufLintRequest, buf: BufSubsystem) -> LintResults:
argv=[
downloaded_buf.exe,
"lint",
*buf.args,
*buf.lint_args,
"--path",
",".join(target_sources_stripped.snapshot.files),
],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ def test_passthrough_args(rule_runner: RuleRunner) -> None:
assert_success(
rule_runner,
tgt,
extra_args=[f"--buf-args='--config={config}'"],
extra_args=[f"--buf-lint-args='--config={config}'"],
)


Expand All @@ -142,7 +142,7 @@ def test_skip(rule_runner: RuleRunner) -> None:
{"foo/v1/f.proto": BAD_FILE, "foo/v1/BUILD": "protobuf_sources(name='t')"}
)
tgt = rule_runner.get_target(Address("foo/v1", target_name="t", relative_file_path="f.proto"))
result = run_buf(rule_runner, [tgt], extra_args=["--buf-skip"])
result = run_buf(rule_runner, [tgt], extra_args=["--buf-lint-skip"])
assert not result


Expand Down
16 changes: 12 additions & 4 deletions src/python/pants/backend/codegen/protobuf/lint/buf/skip_field.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,22 @@
from pants.engine.target import BoolField


class SkipBufField(BoolField):
class SkipBufFormatField(BoolField):
alias = "skip_buf_format"
default = False
help = "If true, don't run `buf format` on this target's code."


class SkipBufLintField(BoolField):
alias = "skip_buf_lint"
default = False
help = "If true, don't lint this target's code with Buf."
help = "If true, don't run `buf lint` on this target's code."


def rules():
return [
ProtobufSourceTarget.register_plugin_field(SkipBufField),
ProtobufSourcesGeneratorTarget.register_plugin_field(SkipBufField),
ProtobufSourceTarget.register_plugin_field(SkipBufFormatField),
ProtobufSourceTarget.register_plugin_field(SkipBufLintField),
ProtobufSourcesGeneratorTarget.register_plugin_field(SkipBufFormatField),
ProtobufSourcesGeneratorTarget.register_plugin_field(SkipBufLintField),
]
16 changes: 9 additions & 7 deletions src/python/pants/backend/codegen/protobuf/lint/buf/subsystem.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,12 @@ class BufSubsystem(TemplatedExternalTool):
name = "Buf"
help = "A linter and formatter for Protocol Buffers (https://github.com/bufbuild/buf)."

default_version = "v1.2.1"
default_version = "v1.3.0"
default_known_versions = [
"v1.2.1|linux_arm64 |8c9df682691436bd9f58efa44928e6fcd68ec6dd346e35eddac271786f4c0ae3|13940426",
"v1.2.1|linux_x86_64|eb227afeaf5f5c5a5f1d2aca92926d8c89be5b7a410e5afd6dd68f2ed0c00f22|15267079",
"v1.2.1|macos_arm64 |6877c9b8f895ec4962faff551c541d9d14e12f49b899ed7e553f0dc74a69b1b8|15388080",
"v1.2.1|macos_x86_64|652b407fd08e5e664244971f4a725763ef582f26778674490658ad2ce361fe95|15954329",
"v1.3.0|linux_arm64 |fbfd53c501451b36900247734bfa4cbe86ae05d0f51bc298de8711d5ee374ee5|13940828",
"v1.3.0|linux_x86_64|e29c4283b1cd68ada41fa493171c41d7605750d258fcd6ecdf692a63fae95213|15267162",
"v1.3.0|macos_arm64 |147985d7f2816a545792e38b26178ff4027bf16cd3712f6e387a4e3692a16deb|15391890",
"v1.3.0|macos_x86_64|3b6bd2e5a5dd758178aee01fb067261baf5d31bfebe93336915bfdf7b21928c4|15955291",
]
default_url_template = (
"https://github.com/bufbuild/buf/releases/download/{version}/buf-{platform}.tar.gz"
Expand All @@ -30,8 +30,10 @@ class BufSubsystem(TemplatedExternalTool):
"linux_x86_64": "Linux-x86_64",
}

skip = SkipOption("fmt", "lint")
args = ArgsListOption(example="--error-format json")
skip_format = SkipOption("fmt", "lint", flag_name="--format-skip")
skip_lint = SkipOption("lint", flag_name="--lint-skip")
format_args = ArgsListOption(example="--error-format json", flag_name="--format-args")
lint_args = ArgsListOption(example="--error-format json", flag_name="--lint-args")

def generate_exe(self, plat: Platform) -> str:
return "./buf/bin/buf"
7 changes: 4 additions & 3 deletions src/python/pants/option/option_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -761,12 +761,12 @@ def _convert_(self, val: Any) -> dict[str, _ValueT]:
class SkipOption(BoolOption[bool]):
"""A --skip option (for an invocable tool)."""

def __new__(cls, goal: str, *other_goals: str):
def __new__(cls, goal: str, *other_goals: str, flag_name: str | None = None):
jyggen marked this conversation as resolved.
Show resolved Hide resolved
goals = (goal,) + other_goals
invocation_str = " and ".join([f"`{bin_name()} {goal}`" for goal in goals])
return super().__new__(
cls, # type: ignore[arg-type]
"--skip",
flag_name or "--skip",
default=False, # type: ignore[arg-type]
help=(
lambda subsystem_cls: (
Expand All @@ -788,12 +788,13 @@ def __new__(
# This should be set when callers can alternatively use "--" followed by the arguments,
# instead of having to provide "--[scope]-args='--arg1 --arg2'".
passthrough: bool | None = None,
flag_name: str | None = None,
):
if extra_help:
extra_help = "\n\n" + extra_help
instance = super().__new__(
cls, # type: ignore[arg-type]
"--args",
flag_name or "--args",
help=(
lambda subsystem_cls: (
f"Arguments to pass directly to {tool_name or subsystem_cls.name}, "
Expand Down