From a7b2098ec6f6c0c6bb5eaf4f1685839678eac0c8 Mon Sep 17 00:00:00 2001 From: Fabian Meumertzheim Date: Wed, 31 Jul 2024 18:46:53 +0200 Subject: [PATCH] Do not conflict with patches --- internal/go_repository.bzl | 33 ++++++++++++++++++++++++--------- tests/bcr/go_mod/tests.bzl | 2 +- 2 files changed, 25 insertions(+), 10 deletions(-) diff --git a/internal/go_repository.bzl b/internal/go_repository.bzl index b0b83d42f..bc3de5015 100644 --- a/internal/go_repository.bzl +++ b/internal/go_repository.bzl @@ -295,13 +295,11 @@ def _go_repository_impl(ctx): if generate: # Build file generation is needed. Populate Gazelle directive at root build file build_file_name = existing_build_file or build_file_names[0] - ctx.file( - build_file_name, - "\n".join(["# " + d for d in ctx.attr.build_directives] + [_generate_package_info( - importpath = ctx.attr.importpath, - version = ctx.attr.version, - )]), - ) + if len(ctx.attr.build_directives) > 0: + ctx.file( + build_file_name, + "\n".join(["# " + d for d in ctx.attr.build_directives]), + ) # Run Gazelle if gazelle_path == None: @@ -363,15 +361,32 @@ def _go_repository_impl(ctx): patch(ctx) if generate: - ctx.file("REPO.bazel", """\ + # Do not override a REPO.bazel patched in by users. This also provides a + # way for users to opt out of Gazelle-generated package_info. + repo_file = ctx.path("REPO.bazel") + if not repo_file.exists: + ctx.file("REPO.bazel", """\ repo(default_package_metadata = ["//:gazelle_generated_package_info"]) """) + # Modify the top-level build file after patches have been applied as the + # patches may otherwise conflict with our generated content. + build_file = ctx.path(build_file_name) + if build_file.exists: + build_file_content = ctx.read(build_file) + else: + build_file_content = "" + build_file_content += _generate_package_info( + importpath = ctx.attr.importpath, + version = ctx.attr.version, + ) + ctx.file(build_file_name, build_file_content) + def _generate_package_info(*, importpath, version): package_name = importpath package_url = "https://" + importpath package_version = version.removeprefix("v") - return """\ + return """ load("@rules_license//rules:package_info.bzl", "package_info") package_info( diff --git a/tests/bcr/go_mod/tests.bzl b/tests/bcr/go_mod/tests.bzl index 772472ed4..e77dc029e 100644 --- a/tests/bcr/go_mod/tests.bzl +++ b/tests/bcr/go_mod/tests.bzl @@ -25,7 +25,7 @@ def _package_info_aspect_impl(_, ctx): attr = ctx.rule.attr.applicable_licenses elif hasattr(ctx.rule.attr, "package_metadata"): attr = ctx.rule.attr.package_metadata - if PackageInfo in attr[0]: + if attr and PackageInfo in attr[0]: return [attr[0][PackageInfo]] return []