From 0b5a5c306a8085ff6775c3113d3f9e2e689b9139 Mon Sep 17 00:00:00 2001 From: Alex Eagle Date: Mon, 21 Nov 2022 14:43:22 -0700 Subject: [PATCH] initial commit of working plugin --- .aspect/cli/plugins.yaml | 2 +- .github/workflows/release_notes.txt | 4 +- BUILD.bazel | 17 +- LICENSE | 256 ++++++---------------------- README.md | 41 ++--- example/BUILD.bazel | 5 + go.bzl | 15 +- go.mod | 4 +- go.sum | 7 +- plugin.go | 251 ++++++++++++++++++++------- release/BUILD.bazel | 9 +- release/release.bzl | 3 +- 12 files changed, 301 insertions(+), 313 deletions(-) create mode 100644 example/BUILD.bazel diff --git a/.aspect/cli/plugins.yaml b/.aspect/cli/plugins.yaml index 6f31c38..2b5c539 100644 --- a/.aspect/cli/plugins.yaml +++ b/.aspect/cli/plugins.yaml @@ -1,6 +1,6 @@ # Configuration of plugins to the Aspect CLI # See https://github.com/aspect-build/aspect-cli/blob/main/docs/help/topics/plugins.md -- name: hello-world +- name: fix-visibility # This file is created by running `bazel build :dev` so that we can easily test local changes. # Since the bazel-bin folder is in .gitignore, you'll get a warning on the first run. # Users will install the plugin from a pre-built binary, using the instructions in the release notes. diff --git a/.github/workflows/release_notes.txt b/.github/workflows/release_notes.txt index 640504f..c56ca7d 100644 --- a/.github/workflows/release_notes.txt +++ b/.github/workflows/release_notes.txt @@ -1,7 +1,7 @@ To use this plugin, add it to your `.aspect/cli/plugins.yaml` file like so: ``` -- name: hello-world - from: github.com/aspect-build/aspect-cli-plugin-template +- name: fix-visibility + from: github.com/aspect-build/plugin-fix-visibility version: ${GITHUB_REF_NAME} ``` diff --git a/BUILD.bazel b/BUILD.bazel index e560d13..ac35922 100644 --- a/BUILD.bazel +++ b/BUILD.bazel @@ -4,6 +4,7 @@ load("//release:release.bzl", "local_plugin") # Run this target to update the go_* rules in this file # bazel run //:gazelle +# gazelle:resolve go github.com/bazelbuild/buildtools/edit @com_github_bazelbuild_buildtools//edit:go_default_library gazelle(name = "gazelle") # Run this target to update the go.bzl file in this folder @@ -18,19 +19,19 @@ gazelle( command = "update-repos", ) -# gazelle:prefix github.com/aspect-build/aspect-cli-plugin-template +# gazelle:prefix github.com/aspect-build/plugin-fix-visibility go_library( - name = "aspect-cli-plugin-template_lib", + name = "plugin-fix-visibility_lib", srcs = ["plugin.go"], - importpath = "github.com/aspect-build/aspect-cli-plugin-template", + importpath = "github.com/aspect-build/plugin-fix-visibility", visibility = ["//:__subpackages__"], deps = [ + "@bazel_gazelle//label:go_default_library", "@build_aspect_cli//bazel/buildeventstream", - "@build_aspect_cli//bazel/command_line", - "@build_aspect_cli//pkg/bazel", "@build_aspect_cli//pkg/ioutils", "@build_aspect_cli//pkg/plugin/sdk/v1alpha3/config", "@build_aspect_cli//pkg/plugin/sdk/v1alpha3/plugin", + "@com_github_bazelbuild_buildtools//edit:go_default_library", "@com_github_hashicorp_go_plugin//:go-plugin", "@com_github_manifoldco_promptui//:promptui", ], @@ -39,8 +40,8 @@ go_library( # Only used for local development. # Release binaries are created by the target in /release go_binary( - name = "aspect-cli-plugin-template", - embed = [":aspect-cli-plugin-template_lib"], + name = "plugin-fix-visibility", + embed = [":plugin-fix-visibility_lib"], visibility = ["//visibility:public"], ) @@ -48,6 +49,6 @@ go_binary( # Referenced by the .aspect/cli/plugins.yaml in the `From:` line. local_plugin( name = "dev", - binary = ":aspect-cli-plugin-template", + binary = ":plugin-fix-visibility", path = "plugin", ) diff --git a/LICENSE b/LICENSE index d645695..ce93ccb 100644 --- a/LICENSE +++ b/LICENSE @@ -1,202 +1,56 @@ +Aspect Community License - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. +BY DOWNLOADING, COPYING, OR OTHERWISE USING THE SOFTWARE WITH WHICH THIS LICENSE AGREEMENT IS PROVIDED (THE "SOFTWARE"), YOU OR THE ENTITY YOU REPRESENT ("LICENSEE") ARE CONSENTING TO BE BOUND BY AND ARE BECOMING A PARTY TO THIS LICENSE AGREEMENT ("AGREEMENT"). + +IF YOU DO NOT AGREE TO ALL OF THE TERMS OF THIS AGREEMENT, THEN YOU MAY NOT DOWNLOAD THE SOFTWARE AND MUST DELETE ANY COPIES THAT YOU HAVE ALREADY DOWNLOADED. + +IF LICENSEE IS AN ENTITY, YOU REPRESENT AND WARRANT THAT YOU ARE AUTHORIZED TO BIND LICENSEE. IF THESE TERMS ARE CONSIDERED AN OFFER, ACCEPTANCE IS EXPRESSLY LIMITED TO THESE TERMS. + +Grant +Subject to the terms of this Agreement, Aspect Build Systems, Inc. (“Aspect”) hereby grants Licensee (and only Licensee) a limited, non-sublicensable, non-transferable, royalty-free, nonexclusive license to use the Software only in Licensee’s organization and only in accordance with any documentation that accompanies it. + +The Software may only be used by a Licensee who is: +(i) an individual (and only for personal use), + +(ii) a Small Business (as defined below), or + +(iii) a non-profit entity or an academic or university institution. + +A “Small Business” is any entity with fewer than 50 total employees (including, for purposes of such calculation, all employees of any entities affiliated with such entity). + +Restrictions +Licensee may not, directly or indirectly: +(i) copy, distribute, rent, lease, timeshare, operate a service bureau with, use commercially or for the benefit of a third party, the Software, + +(ii) reverse engineer, disassemble, decompile, attempt to discover the source code or structure, sequence and organization of, or remove any proprietary notices from, any non-source forms of the Software. + +As between the parties, title, ownership rights, and intellectual property rights in and to the Software, and any copies or portions thereof, shall remain in Aspect and its suppliers or licensors. Licensee understands that Aspect may modify or discontinue offering the Software at any time. The Software is protected by the copyright laws of the United States and international copyright treaties. + +This Agreement does not grant any rights not expressly granted herein. + +Feedback +Licensee may provide any feedback, suggestions, or comments to Aspect regarding the Software (“Feedback”). Licensee hereby grants Aspect a nonexclusive, perpetual, worldwide, royalty-free, fully paid-up, sublicensable, transferable license to use, make available and otherwise exploit the Feedback for any purpose. + +Support and Upgrades +This Agreement does not entitle Licensee to any support, upgrades, patches, enhancements, or fixes for the Software (collectively, “Support”). Any such Support for the Software that may be made available by Aspect shall become part of the Software and subject to this Agreement. + +Disclaimer +ASPECT PROVIDES THE SOFTWARE “AS IS” AND WITHOUT WARRANTY OF ANY KIND, AND ASPECT HEREBY DISCLAIMS ALL EXPRESS OR IMPLIED WARRANTIES, INCLUDING WITHOUT LIMITATION WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, PERFORMANCE, ACCURACY, RELIABILITY, AND NON-INFRINGEMENT. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS AGREEMENT. + +Limitation of liability +UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, INCLUDING, WITHOUT LIMITATION, TORT, CONTRACT, STRICT LIABILITY, OR OTHERWISE, SHALL ASPECT OR ITS LICENSORS, SUPPLIERS OR RESELLERS BE LIABLE TO LICENSEE OR ANY OTHER PERSON FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOST PROFITS, LOSS OF GOODWILL, WORK STOPPAGE, ACCURACY OF RESULTS, COMPUTER FAILURE OR MALFUNCTION, DAMAGES RESULTING FROM LICENSEE’S USE OF THE SOFTWARE. + +Termination +Licensee may terminate this Agreement and the license granted herein at any time by destroying or removing from all computers, networks, and storage media all copies of the Software. Aspect may terminate this Agreement and the license granted herein immediately if Licensee breaches any provision of this Agreement. Upon receiving notice of termination from Aspect, Licensee will destroy or remove from all computers, networks, and storage media all copies of the Software. Sections 2 through 9 shall survive termination of this Agreement + +Export Controls +Licensee shall comply with all export laws and restrictions and regulations of the Department of Commerce, the United States Department of Treasury Office of Foreign Assets Control (“OFAC”), or other United States or foreign agency or authority, and not to export, or allow the export or re-export of the Software in violation of any such restrictions, laws or regulations. By downloading or using the Software, Licensee is agreeing to the foregoing and Licensee is representing and warranting that Licensee is not located in, under the control of, or a national or resident of any restricted country or on any such list + +Miscellaneous +Licensee shall comply with all applicable export laws, restrictions and regulations in connection with Licensee’s use of the Software, and will not export or re-export the Software in violation thereof. This Agreement is personal to Licensee and Licensee shall not assign or transfer the Agreement or the Software to any third party under any circumstances. + +This Agreement represents the complete agreement concerning this license between the parties and supersedes all prior agreements and representations between them. It may be amended only by a writing executed by both parties. + +If any provision of this Agreement is held to be unenforceable for any reason, such provision shall be reformed only to the extent necessary to make it enforceable. + +This Agreement shall be governed by and construed under California law as such law applies to agreements between California residents entered into and to be performed within California. \ No newline at end of file diff --git a/README.md b/README.md index c6a9492..64318e0 100644 --- a/README.md +++ b/README.md @@ -1,29 +1,24 @@ -# Template for aspect-cli plugins +# Fix-visibility plugin -This repo provides the fastest way to make a plugin for the [aspect cli]. +This is a plugin for the [Aspect CLI]. -It contains a plugin written in Go, with a GitHub actions CI/CD pipeline to release it. +It listens to Bazel's build event protocol and filters for the Aborted_ANALYSIS_FAILURE event. +If the Analysis Failure is due to a message containing `is not visible from target` this indicates +that the `visibility` attribute of a target doesn't include the package where our target is defined. -More details about aspect cli plugins is on the [plugin documentation]. +After the build completes, the plugin offers to repair the problem by adding the missing `visibility` entry. -## Instructions +In this demo, we uncomment the `alias` target from `example/BUILD.bazel` and run `bazel build example` to see the failure. +The plugin offers to automatically add the missing entry to `visibility` of the `//:dev` target, +then we run the same build again, and it passes. +The demo then runs `git diff` so you can see what edit was made. -Create a new repo with the green "Use this template" button above. -Then in your repo... - -1. Find-and-replace `hello_world` with your plugin name. -1. Find-and-replace `github.com/aspect-build/aspect-cli-plugin-template` with the name of your Go module. See -1. Delete everything above the SNIP line below, and start coding on your features! - ----------- %< SNIP %< ------------ - -# My Plugin - -This is a plugin for the Aspect CLI. +[![asciicast](https://asciinema.org/a/1IRPgMQmhJC3L8RM1XTwRYUfa.svg)](https://asciinema.org/a/1IRPgMQmhJC3L8RM1XTwRYUfa) ## Developing -To try the plugin, first check that you have the most recent [aspect cli release] installed. +To try the plugin, first check that you have Aspect installed, by running `bazel version` and checking for +`Aspect CLI version` in the output. First build the plugin from source: @@ -35,16 +30,6 @@ Note that the `.aspect/cli/plugins.yaml` file has a reference to the path under On the first build, you'll see a warning printed that the plugin doesn't exist at this path. This is just the development flow for working on plugins; users will reference the plugin's releases which are downloaded for them automatically. -Now just run `aspect`. You should see that `hello-world` appears in the help output. This shows that our plugin was loaded and contributed a custom command to the CLI. - -``` -Usage: - aspect [command] - -Custom Commands from Plugins: - hello-world Print 'Hello World!' to the command line. -``` - ## Releasing Just push a tag to your GitHub repo. diff --git a/example/BUILD.bazel b/example/BUILD.bazel new file mode 100644 index 0000000..38ec9b0 --- /dev/null +++ b/example/BUILD.bazel @@ -0,0 +1,5 @@ +# Uncomment and build this package to see the feature work. +# alias( +# name = "example", +# actual = "//:dev", +# ) diff --git a/go.bzl b/go.bzl index c04853d..22601d8 100644 --- a/go.bzl +++ b/go.bzl @@ -46,8 +46,8 @@ def deps(): go_repository( name = "com_github_bazelbuild_rules_go", importpath = "github.com/bazelbuild/rules_go", - sum = "h1:cmObMtgIOaEU944SqXtJ9DnlS8IPGGa7pdRnsrpQzXM=", - version = "v0.34.0", + sum = "h1:ViPR65vOrg74JKntAUFY6qZkheBKGB6to7wFd8gCRU4=", + version = "v0.35.0", ) go_repository( name = "com_github_bgentry_go_netrc", @@ -236,8 +236,8 @@ def deps(): go_repository( name = "com_github_google_go_cmp", importpath = "github.com/google/go-cmp", - sum = "h1:e6P7q2lk1O+qJJb4BtCQXlK8vWEO8V1ZeuEdJNOqZyg=", - version = "v0.5.8", + sum = "h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=", + version = "v0.5.9", ) go_repository( name = "com_github_google_martian", @@ -740,6 +740,13 @@ def deps(): sum = "h1:7uVkIFmeBqHfdjD+gZwtXXI+RODJ2Wc4O7MPEh/QiW4=", version = "v1.3.0", ) + go_repository( + name = "net_starlark_go", + importpath = "go.starlark.net", + sum = "h1:xwwDQW5We85NaTk2APgoN9202w/l0DVGp+GZMfsrh7s=", + version = "v0.0.0-20210223155950-e043a3d3c984", + ) + go_repository( name = "org_golang_google_api", importpath = "google.golang.org/api", diff --git a/go.mod b/go.mod index 3f2a58f..642e5a8 100644 --- a/go.mod +++ b/go.mod @@ -1,9 +1,11 @@ -module github.com/aspect-build/aspect-cli-plugin-template +module github.com/aspect-build/plugin-fix-visibility go 1.19 require ( aspect.build/cli v1.0.1 + github.com/bazelbuild/bazel-gazelle v0.28.0 + github.com/bazelbuild/buildtools v0.0.0-20221004120235-7186f635531b github.com/hashicorp/go-plugin v1.4.5 github.com/manifoldco/promptui v0.9.0 ) diff --git a/go.sum b/go.sum index d61c4c2..7e1587c 100644 --- a/go.sum +++ b/go.sum @@ -40,8 +40,12 @@ cloud.google.com/go/storage v1.14.0/go.mod h1:GrKmX003DSIwi9o29oFT7YDnHYwZoctc3f dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= +github.com/bazelbuild/bazel-gazelle v0.28.0 h1:sPdMMujcMt5jeSLGFko5yF1XBD5MDqm6YeFoXx9ORm4= +github.com/bazelbuild/bazel-gazelle v0.28.0/go.mod h1:5Qer6FCMBeotA8eQYJEPxn2eAbHmTApPxyd7aD4A0S8= github.com/bazelbuild/bazelisk v1.13.2 h1:SpigbUorngcfDULmft0WkdrYVCqqqsFPEW4hm8UA+Gk= github.com/bazelbuild/bazelisk v1.13.2/go.mod h1:jVD8/E7hMAXgWKCljEz8hOV0PZ+nFBgCpjIOJ6Xyzus= +github.com/bazelbuild/buildtools v0.0.0-20221004120235-7186f635531b h1:jhiMzJ+8unnLRtV8rpbWBFE9pFNzIqgUTyZU5aA++w8= +github.com/bazelbuild/buildtools v0.0.0-20221004120235-7186f635531b/go.mod h1:689QdV3hBP7Vo9dJMmzhoYIyo/9iMhEmHkJcnaPRCbo= github.com/bazelbuild/rules_go v0.34.0/go.mod h1:MC23Dc/wkXEyk3Wpq6lCqz0ZAYOZDw2DR5y3N1q2i7M= github.com/bgentry/go-netrc v0.0.0-20140422174119-9fd32a8b3d3d h1:xDfNPAt8lFiC1UJrqV3uuy861HCTo708pDMbjHHdCas= github.com/bgentry/go-netrc v0.0.0-20140422174119-9fd32a8b3d3d/go.mod h1:6QX/PXZ00z/TKoufEY6K/a0k6AhaJrQKdFe6OfVXsa4= @@ -118,7 +122,7 @@ github.com/google/go-cmp v0.5.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/ github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.8 h1:e6P7q2lk1O+qJJb4BtCQXlK8vWEO8V1ZeuEdJNOqZyg= +github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38= github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs= github.com/google/martian/v3 v3.0.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0= github.com/google/martian/v3 v3.1.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0= @@ -230,6 +234,7 @@ go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= go.opencensus.io v0.22.3/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= go.opencensus.io v0.22.4/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= go.opencensus.io v0.22.5/go.mod h1:5pWMHQbX5EPX2/62yrJeAkowc+lfs/XD7Uxpq3pI6kk= +go.starlark.net v0.0.0-20210223155950-e043a3d3c984/go.mod h1:t3mmBBPzAVvK0L0n1drDmrQsJ8FoIx4INCqVMTr/Zo0= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= diff --git a/plugin.go b/plugin.go index 920fbc7..8c2d9c2 100644 --- a/plugin.go +++ b/plugin.go @@ -1,97 +1,224 @@ +/* + * Copyright 2022 Aspect Build Systems, Inc. All rights reserved. + * + * Licensed under the aspect.build Community License (the "License"); + * you may not use this file except in compliance with the License. + * Full License text is in the LICENSE file included in the root of this repository + * and at https://aspect.build/communitylicense + */ + +// The fix-visibility is a plugin for the aspect CLI. When running in interactive +// mode, it offers to automatically fix visibility issues, otherwise, it prints to +// the terminal the buildozer commands necessary to perform the fix manually. +// +// This plugin is also a reference implementation of a plugin using the Go SDK. +// You will find the code below commented to your satisfaction. package main import ( - "context" + "bytes" "fmt" "os" - - goplugin "github.com/hashicorp/go-plugin" - "github.com/manifoldco/promptui" + "regexp" + "strings" "aspect.build/cli/bazel/buildeventstream" - "aspect.build/cli/bazel/command_line" - "aspect.build/cli/pkg/bazel" "aspect.build/cli/pkg/ioutils" "aspect.build/cli/pkg/plugin/sdk/v1alpha3/config" aspectplugin "aspect.build/cli/pkg/plugin/sdk/v1alpha3/plugin" + goplugin "github.com/hashicorp/go-plugin" + "github.com/manifoldco/promptui" + "github.com/bazelbuild/bazel-gazelle/label" + "github.com/bazelbuild/buildtools/edit" ) // main starts up the plugin as a child process of the CLI and connects the gRPC communication. func main() { - goplugin.Serve(config.NewConfigFor(&HelloWorldPlugin{})) + goplugin.Serve(config.NewConfigFor(&FixVisibilityPlugin{ + buildozer: &buildozer{}, + targetsToFix: &fixOrderedSet{nodes: make(map[fixNode]struct{})}, + })) } -// HelloWorldPlugin declares the fields on an instance of the plugin. -type HelloWorldPlugin struct { - // Base gives default implementations of the plugin methods, so implementing them below is optional. - // See the definition of aspectplugin.Base for more methods that can be implemented by the plugin. +// FixVisibilityPlugin implements an aspect CLI plugin. +type FixVisibilityPlugin struct { aspectplugin.Base - // This plugin will store some state from the Build Events for use at the end of the build. - command_line.CommandLine -} -// CustomCommands contributes a new 'hello-world' command alongside the built-in ones like 'build' and 'test'. -func (plugin *HelloWorldPlugin) CustomCommands() ([]*aspectplugin.Command, error) { - return []*aspectplugin.Command{ - aspectplugin.NewCommand( - "hello-world", - "Print 'Hello World!' to the command line.", - "Print 'Hello World!' to the command line. Echo any given argument. Then run a 'bazel help'", - func(ctx context.Context, args []string, bzl bazel.Bazel) error { - fmt.Println("Hello World!") - fmt.Print("Arguments passed to command: ") - fmt.Println(args) - fmt.Println("Going to run: 'bazel help'") - - bzl.RunCommand(ioutils.DefaultStreams, "help") - - return nil - }, - ), - }, nil + buildozer runner + targetsToFix *fixOrderedSet } -// BEPEventCallback subscribes to all Build Events, and lets our logic react to ones we care about. -func (plugin *HelloWorldPlugin) BEPEventCallback(event *buildeventstream.BuildEvent) error { - switch event.Payload.(type) { - case *buildeventstream.BuildEvent_StructuredCommandLine: - commandLine := *event.GetStructuredCommandLine() - if commandLine.CommandLineLabel == "canonical" { - plugin.CommandLine = commandLine - } + +const visibilityIssueSubstring = "is not visible from target" +const removePrivateVisibilityBuildozerCommand = "remove visibility //visibility:private" +var visibilityIssueRegex = regexp.MustCompile(fmt.Sprintf(`.*target '(.*)' %s '(.*)'.*`, visibilityIssueSubstring)) + +// BEPEventCallback satisfies the Plugin interface. It processes all the analysis +// failures that represent a visibility issue, collecting them for later +// processing in the post-build hook execution. +func (plugin *FixVisibilityPlugin) BEPEventCallback(event *buildeventstream.BuildEvent) error { + // First, verify if the received event is of the type Aborted. The visibility + // issue events are emitted as ANALYSIS_FAILUE, so if there's an analysis + // failure and the description of the event contains the known-issue string, + // we perform a regex match to extract the targets. Note that strings.Contains + // is much cheaper than relying on the regex matching, so we only call regex + // when we are absolutely sure it will return a valid match. + aborted := event.GetAborted() + if aborted != nil && + aborted.Reason == buildeventstream.Aborted_ANALYSIS_FAILURE && + strings.Contains(aborted.Description, visibilityIssueSubstring) { + matches := visibilityIssueRegex.FindStringSubmatch(aborted.Description) + if len(matches) == 3 { + // Here, we insert the matched targets in a linked list for processing + // in the post-build hook. + plugin.targetsToFix.insert(matches[1], matches[2]) + } } return nil } -// PostBuildHook will be called at the end of an `aspect build` execution, after Bazel completes. -func (plugin *HelloWorldPlugin) PostBuildHook( +// PostBuildHook satisfies the Plugin interface. It prompts the user for +// automatic fixes when in interactive mode. If the user rejects the automatic +// fixes, or if running in non-interactive mode, the commands to perform the fixes +// are printed to the terminal. +func (plugin *FixVisibilityPlugin) PostBuildHook( isInteractiveMode bool, promptRunner ioutils.PromptRunner, ) error { - // We condition prompting on whether there's an interactive user to engage with. - if isInteractiveMode { - // The manifoldco/promptui library creates many styles of interactive prompts. - // Check out the examples: https://github.com/manifoldco/promptui/tree/master/_examples - prompt := promptui.Prompt{ - Label: "Thanks for trying the hello-world plugin! Would you like to see the command that was run", - IsConfirm: true, + if plugin.targetsToFix.size == 0 { + return nil + } + + // For each collected visibility issue... + for node := plugin.targetsToFix.head; node != nil; node = node.next { + // ... we construct the label for the target we want to add to the target + // being fixed. + fromLabel, err := label.Parse(node.from) + if err != nil { + return fmt.Errorf("failed to fix visibility: %w", err) } - // Since the prompt is a boolean, any non-nil error should represent a NO. - if _, err := promptRunner.Run(prompt); err == nil { - plugin.printTargetPattern() + fromLabel.Name = "__pkg__" + + // We need to verify if the target being fixed contains //visibility:private, + // otherwise Bazel will yell at us since we will need to remove it to add + // any package to the visibility attribute. + hasPrivateVisibility, err := plugin.hasPrivateVisibility(node.toFix) + if err != nil { + return fmt.Errorf("failed to fix visibility: %w", err) + } + + // We check whether it's running in interactive mode, if so, send a request + // to prompt the user using the promptRunner injected by the CLI core in + // this method. + var applyFix bool + if isInteractiveMode { + applyFixPrompt := promptui.Prompt{ + Label: "Would you like to auto-fix to the visibility attribute", + IsConfirm: true, + } + _, err := promptRunner.Run(applyFixPrompt) + // Since the prompt is a boolean, any non-nil error should represent a NO. + applyFix = err == nil + } + + // Here we either perform the fix automatically, or print the commands for + // the user to perform the fixes manually. + addVisibilityBuildozerCommand := fmt.Sprintf("add visibility %s", fromLabel) + if applyFix { + if _, err := plugin.buildozer.run(addVisibilityBuildozerCommand, node.toFix); err != nil { + return fmt.Errorf("failed to fix visibility: %w", err) + } + if hasPrivateVisibility { + if _, err := plugin.buildozer.run(removePrivateVisibilityBuildozerCommand, node.toFix); err != nil { + return fmt.Errorf("failed to fix visibility: %w", err) + } + } + } else { + fmt.Fprintf(os.Stdout, "To fix the visibility errors, run:\n") + fmt.Fprintf(os.Stdout, "buildozer '%s' %s\n", addVisibilityBuildozerCommand, node.toFix) + if hasPrivateVisibility { + fmt.Fprintf(os.Stdout, "buildozer '%s' %s\n", removePrivateVisibilityBuildozerCommand, node.toFix) + } } } + return nil } -// printTargetPattern is just representative of some logic a plugin might want to perform on the data collected. -func (plugin *HelloWorldPlugin) printTargetPattern() { - for _, section := range plugin.CommandLine.Sections { - fmt.Fprintf(os.Stdout, "%s\n", section.SectionLabel) - if section.SectionLabel == "residual" { - switch f := section.SectionType.(type) { - case *command_line.CommandLineSection_ChunkList: - fmt.Fprintf(os.Stdout, "target pattern was %s\n", f.ChunkList.Chunk[0]) - } +// PostTestHook satisfies the Plugin interface. In this case, it just calls the +// PostBuildHook. +func (plugin *FixVisibilityPlugin) PostTestHook( + isInteractiveMode bool, + promptRunner ioutils.PromptRunner, +) error { + return plugin.PostBuildHook(isInteractiveMode, promptRunner) +} + +// PostRunHook satisfies the Plugin interface. In this case, it just calls the +// PostBuildHook. +func (plugin *FixVisibilityPlugin) PostRunHook( + isInteractiveMode bool, + promptRunner ioutils.PromptRunner, +) error { + return plugin.PostBuildHook(isInteractiveMode, promptRunner) +} + +func (plugin *FixVisibilityPlugin) hasPrivateVisibility(toFix string) (bool, error) { + visibility, err := plugin.buildozer.run("print visibility", toFix) + if err != nil { + return false, fmt.Errorf("failed to check if target has private visibility: %w", err) + } + return bytes.Contains(visibility, []byte("//visibility:private")), nil +} + +type fixOrderedSet struct { + head *fixNode + tail *fixNode + nodes map[fixNode]struct{} + size int +} + +func (s *fixOrderedSet) insert(toFix, from string) { + node := fixNode{ + toFix: toFix, + from: from, + } + + if _, exists := s.nodes[node]; !exists { + s.nodes[node] = struct{}{} + if s.head == nil { + s.head = &node + } else { + s.tail.next = &node } + s.tail = &node + s.size++ + } +} + +type fixNode struct { + next *fixNode + toFix string + from string +} + +type runner interface { + run(args ...string) ([]byte, error) +} + +type buildozer struct{} + +func (b *buildozer) run(args ...string) ([]byte, error) { + var stdout bytes.Buffer + var stderr strings.Builder + edit.ShortenLabelsFlag = true + edit.DeleteWithComments = true + opts := &edit.Options{ + OutWriter: &stdout, + ErrWriter: &stderr, + NumIO: 200, + } + if ret := edit.Buildozer(opts, args); ret != 0 { + return stdout.Bytes(), fmt.Errorf("failed to run buildozer: exit code %d: %s", ret, stderr.String()) } + return stdout.Bytes(), nil } diff --git a/release/BUILD.bazel b/release/BUILD.bazel index 3a2499e..603fd8f 100644 --- a/release/BUILD.bazel +++ b/release/BUILD.bazel @@ -1,15 +1,16 @@ "Targets used by the automation in .github/workflows/release.yml" + load(":release.bzl", "multi_platform_binaries", "release") # Build a plugin for all supported platforms multi_platform_binaries( # This name will determine what users put in their .aspect/cli/plugins.yaml: - # - name: hello-world - name = "hello-world", - embed = ["//:aspect-cli-plugin-template_lib"], + # - name: fix-visibility + name = "fix-visibility", + embed = ["//:plugin-fix-visibility_lib"], ) release( name = "release", - targets = [":hello-world"], + targets = [":fix-visibility"], ) diff --git a/release/release.bzl b/release/release.bzl index 10b361f..8edde66 100644 --- a/release/release.bzl +++ b/release/release.bzl @@ -25,7 +25,7 @@ sha256 = rule( provides = [DefaultInfo], ) -def local_plugin(name, binary, path): +def local_plugin(name, binary, path, **kwargs): out = "_{}.out".format(name) sum = "_{}.sum".format(name) @@ -48,6 +48,7 @@ def local_plugin(name, binary, path): native.filegroup( name = name, srcs = [out, sum], + **kwargs ) PLATFORMS = [