Repository: apple/apple_rules_lint Branch: main Commit: ccfc3520169b Files: 42 Total size: 38.8 KB Directory structure: gitextract__zeszii1/ ├── .bazelignore ├── .bazelversion ├── .gitignore ├── CODE_OF_CONDUCT.md ├── LICENSE ├── MODULE.bazel ├── README.md ├── RELEASE.md ├── WORKSPACE ├── WORKSPACE.bzlmod ├── api.md ├── example/ │ ├── BUILD.bazel │ ├── MODULE.bazel │ ├── README.md │ ├── WORKSPACE │ ├── lint_rule/ │ │ ├── BUILD.bazel │ │ └── amazing_linter.bzl │ └── project/ │ ├── BUILD.bazel │ └── override/ │ └── BUILD.bazel ├── lint/ │ ├── BUILD.bazel │ ├── defs.bzl │ ├── extensions.bzl │ ├── private/ │ │ ├── BUILD.bazel │ │ ├── docs/ │ │ │ └── BUILD.bazel │ │ ├── get_lint_config.bzl │ │ ├── package_lint_config.bzl │ │ ├── providers.bzl │ │ └── register_linters.bzl │ ├── repositories.bzl │ └── setup.bzl ├── scripts/ │ ├── build-release-artifacts │ └── generate-docs └── tests/ └── bcr/ ├── .bazelignore ├── .bazelrc ├── .bazelversion ├── BUILD.bazel ├── MODULE.bazel ├── WORKSPACE ├── foo_config.json └── other_module/ ├── BUILD.bazel ├── MODULE.bazel └── WORKSPACE ================================================ FILE CONTENTS ================================================ ================================================ FILE: .bazelignore ================================================ example/ tests/bcr ================================================ FILE: .bazelversion ================================================ 7.3.1 ================================================ FILE: .gitignore ================================================ .ijwb/ *~ *.swp **/bazel-* **/MODULE.bazel.lock ================================================ FILE: CODE_OF_CONDUCT.md ================================================ # Contributor Covenant Code of Conduct ## Our Pledge We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. ## Our Standards Examples of behavior that contributes to a positive environment for our community include: * Demonstrating empathy and kindness toward other people * Being respectful of differing opinions, viewpoints, and experiences * Giving and gracefully accepting constructive feedback * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience * Focusing on what is best not just for us as individuals, but for the overall community Examples of unacceptable behavior include: * The use of sexualized language or imagery, and sexual attention or advances of any kind * Trolling, insulting or derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or email address, without their explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ## Enforcement Responsibilities Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. ## Scope This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at [INSERT CONTACT METHOD]. All complaints will be reviewed and investigated promptly and fairly. All community leaders are obligated to respect the privacy and security of the reporter of any incident. ## Enforcement Guidelines Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: ### 1. Correction **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested. ### 2. Warning **Community Impact**: A violation through a single incident or series of actions. **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban. ### 3. Temporary Ban **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior. **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban. ### 4. Permanent Ban **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. **Consequence**: A permanent ban from any sort of public interaction within the community. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0, available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity). [homepage]: https://www.contributor-covenant.org For answers to common questions about this code of conduct, see the FAQ at https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations. ================================================ FILE: 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 2020 Software Freedom Conservancy (SFC) 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. ================================================ FILE: MODULE.bazel ================================================ module( name = "apple_rules_lint", version = "0.4.0", ) bazel_dep(name = "bazel_skylib", version = "1.7.1") bazel_dep(name = "stardoc", version = "0.7.0", dev_dependency = True, repo_name = "io_bazel_stardoc") linter = use_extension("//lint:extensions.bzl", "linter") use_repo(linter, "apple_linters") ================================================ FILE: README.md ================================================ # apple_rules_lint A linting framework for Bazel ## Users You must load and configure the linting framework before anything else. This is because later rulesets that depend on the linting framework will attempt to ensure that linters are configured by registering no-op implementations of lint configs. You can do this by: ```py # WORKSPACE load("@apple_rules_lint//lint:repositories.bzl", "lint_deps") lint_deps() load("@apple_rules_lint//lint:setup.bzl", "lint_setup") lint_setup({ "java-checkstyle": "//your:checkstyle-config", }) ``` Alternatively, using Bzlmod: ```py # MODULE.bazel bazel_dep(name = "apple_rules_lint", version = "0.4.0") linter = use_extension("@apple_rules_lint//lint:extensions.bzl", "linter") linter.configure(name = "java-checkstyle", config = "//your:checkstyle-config") use_repo(linter, "apple_linters") ``` You may override specific lint configurations on a per-package basis by: ```py # BUILD.bazel load("@apple_rules_lint//lint:defs.bzl", "package_lint_config") package_lint_config({ "java-checkstyle": ":alternative-checkstyle-config", }) ``` ### Missing `@@apple_linters` error Bazel may report an error like this: ``` ERROR: Failed to load Starlark extension '@@apple_linters//:defs.bzl'. Cycle in the workspace file detected. This indicates that a repository is used prior to being defined. The following chain of repository dependencies lead to the missing definition. - @@apple_linters This could either mean you have to add the '@@apple_linters' repository with a statement like `http_archive` in your WORKSPACE file (note that transitive dependencies are not added automatically), or move an existing definition earlier in your WORKSPACE file. ``` The `@apple_linters` repository is defined when `lint_setup` is called. You'll need to figure out where `load("@apple_linters//:defs.bzl, ...)` is getting called, and modify your build to ensure that `lint_setup` is called _before_ linting is loaded. ### API Documentation Can be found in [the api docs](api.md) ## Ruleset Authors ### WORKSPACE setup To add linter support to your repo, add this to... ```py # repositories.bzl load("@apple_rules_lint//lint:repositories.bzl", "lint_deps") lint_deps() ``` Then add this to... ```py # setup.bzl load("@apple_rules_lint//lint:setup.bzl", "ruleset_lint_setup") ruleset_lint_setup() ``` ### Bzlmod setup Add: ```py # MODULE.bazel bazel_dep(name = "apple_rules_lint", version = "0.1.1") linter = use_extension("@apple_rules_lint//lint:extensions.bzl", "linter") linter.register(name = "java-checkstyle") ``` ### Getting the configured config for a linter To obtain the currently configured config for a ruleset, use: ```py # your_rules.bzl load("@apple_rules_lint//lint:defs.bzl", "get_lint_config") config = get_lint_config("java-checkstyle", tags) if config != None: # set up lint targets pass ``` Where `tags` are the tags of the rule to check. # Integrating `apple_rules_lint` With Your Rulesets For the sake of this example, we'll show how `apple_rules_lint` is integrated with the Selenium project, but the same process can be followed for any linter: 1. Wrap the linter with a `_test` rule, so you can run them with bazel test. In Selenium, this is the [spotbugs_test](https://github.com/SeleniumHQ/selenium/blob/selenium-4.0.0-beta-1/java/private/spotbugs.bzl) 2. It is recommended, but not required, that your test return a `LinterInfo` so that other tooling can detect whether this is a lint test. 3. Create a config rule or a marker rule of some sort. For example, [spotbugs_config](https://github.com/SeleniumHQ/selenium/blob/selenium-4.0.0-beta-1/java/private/spotbugs_config.bzl) 4. Pick a "well known" name: `lang-tool` seems to work well (such as `java-spotbugs`, but you might have `go-gofmt` or `py-black`) 5. Create a macro that uses [get_lint_config](./api.md#get_lint_config) to look up the config for you. If that's present, create a new instance of your test rule. You can see this in action [here](https://github.com/SeleniumHQ/selenium/blob/selenium-4.0.0-beta-1/java/private/library.bzl). 6. As you write code, make sure your macro is called. If you're a ruleset author, this can be as lightweight as exporting the macro created above as the default way to call your rules. 7. ... 8. Profit! Users can then use the "well known" name to point to an instance of the config rule in their `WORKSPACE` files: ```starlark lint_setup({ "java-spotbugs": "//java:spotbugs-config", }) ``` ================================================ FILE: RELEASE.md ================================================ # Releasing `apple_rules_lint` 1. Update the `MODULE.bazel` and bump the version number to whatever the next release will be. 2. `git tag "${TAG}"` where `${TAG}` is whatever the next release will be. 3. `./scripts/build-release-artifacts` 4. Create a new release on GitHub, and attach the artifacts generated by the previous step. 5. Update the BCR with the new release 6. ... 7. Profit! ================================================ FILE: WORKSPACE ================================================ workspace(name = "apple_rules_lint") load("//lint:repositories.bzl", "lint_deps") lint_deps() load("//lint:setup.bzl", "lint_setup") lint_setup() ================================================ FILE: WORKSPACE.bzlmod ================================================ workspace(name = "apple_rules_lint") ================================================ FILE: api.md ================================================ ## LinterInfo
load("@apple_rules_lint//lint:defs.bzl", "LinterInfo")
LinterInfo(language, name)
**FIELDS**
| Name | Description |
| :------------- | :------------- |
| language | The language or kind of thing we are linting. |
| name | The name of the linter |
## get_lint_config
load("@apple_rules_lint//lint:defs.bzl", "get_lint_config")
get_lint_config(linter_name, tags)
Gets the lint config for a particular linter from the tags of a rule.
This will return either `None` or the label configured in `lint_setup`.
If the tags `no-lint` or `no-linter_name` (eg. `no-java-checkstyle`) are
found, then `None` will be returned. This allows linting to be turned off
for specific rules.
**PARAMETERS**
| Name | Description | Default Value |
| :------------- | :------------- | :------------- |
| linter_name | The "well known" name of the linter (eg. `java-checkstyle`) | none |
| tags | The tags from the rule (eg. `ctx.attr.tags`) | none |
## package_lint_config
load("@apple_rules_lint//lint:defs.bzl", "package_lint_config")
package_lint_config(linters)
Register the given linters for the current bazel package.
This is expected to be near the top of the `BUILD.bazel` file and
allows users to override or configure specific linters for a bazel
package.
**PARAMETERS**
| Name | Description | Default Value |
| :------------- | :------------- | :------------- |
| linters | a dict of "well known name" to Label. | none |
================================================
FILE: example/BUILD.bazel
================================================
load("//lint_rule:amazing_linter.bzl", "example_linter_config")
# This is configured as the default lint config for `lintable_rule`
# targets. We configure it to always fail the build to demonstrate
# what could be done.
example_linter_config(
name = "default_config",
always_pass = False,
visibility = [
"//visibility:public",
],
)
================================================
FILE: example/MODULE.bazel
================================================
module(
name = "lint_example",
)
bazel_dep(name = "apple_rules_lint", version = "0.0.0")
local_path_override(
module_name = "apple_rules_lint",
path = "..",
)
linter = use_extension("@apple_rules_lint//lint:extensions.bzl", "linter")
linter.register(name = "lint_example")
#linter.configure(
# name = "lint_example",
# config = "//:default_config",
#)
use_repo(linter, "apple_linters")
================================================
FILE: example/README.md
================================================
# Example Lint Project
This example demonstrates some of the features of the `apple_rules_lint`.
To get started run:
`bazel build //project/...`
The build will pass. It should do! It does almost nothing! Now run:
`bazel test //project/...`
No tests are run. Boo! That's no fun! But all's not lost! Open up the `WORKSPACE` and change:
```py
lint_setup({
# "lint_example": "//:default_config",
})
```
to:
```py
lint_setup({
"lint_example": "//:default_config",
})
```
What does this do? It says that rules that are aware of the `lint_example`
tool should be using the `//:default_config` configuration for tests. By
default, we've set this up to fail all the lint tests.
But if you look closely, not all the lint tests have failed. This is because
the build file in `//project/override` uses the `package_lint_config_override`
rule to override the configuration for the `lint_example` tool.
================================================
FILE: example/WORKSPACE
================================================
workspace(name = "lint_example")
local_repository(
name = "apple_rules_lint",
path = "..",
)
load("@apple_rules_lint//lint:repositories.bzl", "lint_deps")
lint_deps()
load("@apple_rules_lint//lint:setup.bzl", "lint_setup")
lint_setup({
# "lint_example": "//:default_config",
})
================================================
FILE: example/lint_rule/BUILD.bazel
================================================
================================================
FILE: example/lint_rule/amazing_linter.bzl
================================================
load("@apple_rules_lint//lint:defs.bzl", "get_lint_config")
ExampleConfigInfo = provider(
fields = {
"always_pass": "Whether the lint check should always pass",
},
)
def _example_linter_config_impl(ctx):
return [
ExampleConfigInfo(
always_pass = ctx.attr.always_pass,
),
]
example_linter_config = rule(
_example_linter_config_impl,
attrs = {
"always_pass": attr.bool(),
},
provides = [
ExampleConfigInfo,
],
)
def _lintable_test_impl(ctx):
config = ctx.attr.config[ExampleConfigInfo]
exit_flag = 0 if config.always_pass else 1
test = ctx.actions.declare_file(ctx.label.name)
ctx.actions.write(
test,
"#!/bin/sh\nexit %d" % exit_flag,
is_executable = True,
)
return [
DefaultInfo(
executable = test,
),
]
lintable_test = rule(
_lintable_test_impl,
test = True,
attrs = {
"target": attr.label(
mandatory = True,
),
"config": attr.label(
providers = [
[ExampleConfigInfo],
],
),
},
)
def _lintable_rule_impl(ctx):
return [
]
_lintable_rule = rule(
_lintable_rule_impl,
attrs = {
},
)
def lintable_rule(name, tags = [], visibility = None):
_lintable_rule(name = name, visibility = visibility)
config = get_lint_config("lint_example", tags)
if config != None:
lintable_test(
name = "%s-test" % name,
target = name,
config = config,
)
================================================
FILE: example/project/BUILD.bazel
================================================
load("//lint_rule:amazing_linter.bzl", "lintable_rule")
# Because we've not overridden the lint config, we get the default config,
# which will cause the lint tests to fail.
lintable_rule(
name = "will_fail",
)
================================================
FILE: example/project/override/BUILD.bazel
================================================
load("@apple_rules_lint//lint:defs.bzl", "package_lint_config")
load("//lint_rule:amazing_linter.bzl", "example_linter_config", "lintable_rule")
# Override the default linter for "lint_example" only
package_lint_config({
"lint_example": ":override_config",
})
# This config will cause the lint tests to always pass
example_linter_config(
name = "override_config",
always_pass = True,
)
# And because the linting config has been overridden for this package
# alone, this lint test will pass.
lintable_rule(
name = "will_pass",
)
================================================
FILE: lint/BUILD.bazel
================================================
load("@bazel_skylib//:bzl_library.bzl", "bzl_library")
exports_files([
"defs.bzl",
])
bzl_library(
name = "implementation",
srcs = [
":defs.bzl",
":setup.bzl",
"@apple_linters//:defs.bzl",
],
visibility = [
"//visibility:public",
],
deps = [
"//lint/private:implementation",
],
)
================================================
FILE: lint/defs.bzl
================================================
load("//lint/private:get_lint_config.bzl", _get_lint_config = "get_lint_config")
load(
"//lint/private:package_lint_config.bzl",
_package_lint_config = "package_lint_config",
)
load("//lint/private:providers.bzl", _LinterInfo = "LinterInfo")
LinterInfo = _LinterInfo
get_lint_config = _get_lint_config
package_lint_config = _package_lint_config
================================================
FILE: lint/extensions.bzl
================================================
load("//lint/private:register_linters.bzl", "COMMON_NAME", "register_linters")
def _linter_impl(module_ctx):
linters = {}
for mod in module_ctx.modules:
for tag in mod.tags.register:
if not tag.name.islower():
fail("Linter names are expected to be in lowercase: {linter}".format(
linter = tag.name,
))
if tag.name in linters:
fail("Linter '{linter}' has been registered by both '{mod_1}' and '{mod_2}'".format(
linter = tag.name,
mod_1 = linters[tag.name],
mod_2 = mod.name,
))
linters[tag.name] = mod.name
name_to_linter_config = {}
for mod in module_ctx.modules:
# Only the root module's linter configuration should apply.
if not mod.is_root:
continue
for tag in mod.tags.configure:
if tag.name not in linters:
fail("Linter '{linter}' has not been registered".format(
linter = tag.name,
))
if tag.name in name_to_linter_config:
fail("Linter '{linter}' is configured multiple times".format(
linter = tag.name,
))
name_to_linter_config[tag.name] = str(tag.config)
register_linters(
name = COMMON_NAME,
linters = name_to_linter_config,
)
_register = tag_class(
attrs = {
"name": attr.string(mandatory = True),
},
)
_configure = tag_class(
attrs = {
"name": attr.string(mandatory = True),
"config": attr.label(mandatory = True),
},
)
linter = module_extension(
implementation = _linter_impl,
tag_classes = {
"register": _register,
"configure": _configure,
},
)
================================================
FILE: lint/private/BUILD.bazel
================================================
load("@bazel_skylib//:bzl_library.bzl", "bzl_library")
bzl_library(
name = "implementation",
srcs = [
"get_lint_config.bzl",
"package_lint_config.bzl",
"providers.bzl",
],
visibility = ["//visibility:public"],
)
================================================
FILE: lint/private/docs/BUILD.bazel
================================================
load("@io_bazel_stardoc//stardoc:stardoc.bzl", "stardoc")
stardoc(
name = "docs",
out = "api.md",
input = "//lint:defs.bzl",
symbol_names = [
"LinterInfo",
"get_lint_config",
"package_lint_config",
],
deps = [
"//lint:implementation",
"//lint/private:implementation",
],
)
================================================
FILE: lint/private/get_lint_config.bzl
================================================
load("@apple_linters//:defs.bzl", "configured_linters")
load("//lint/private:package_lint_config.bzl", "OVERRIDE_RULE_NAME")
def get_repo_name():
repo_name = getattr(native, "repo_name", None)
if not repo_name:
# We're using an old Bazel version (5.x), so this will be fine
return native.repository_name()
# Are we using `bzlmod` or not?
is_bzlmod = str(Label("@does_not_exist_i_promise//:BUILD.bazel")).startswith("@@")
prefix = "@@" if is_bzlmod else "@"
return prefix + repo_name()
def get_lint_config(linter_name, tags):
"""Gets the lint config for a particular linter from the tags of a rule.
This will return either `None` or the label configured in `lint_setup`.
If the tags `no-lint` or `no-linter_name` (eg. `no-java-checkstyle`) are
found, then `None` will be returned. This allows linting to be turned off
for specific rules.
Args:
linter_name: The "well known" name of the linter (eg. `java-checkstyle`)
tags: The tags from the rule (eg. `ctx.attr.tags`)
"""
if not linter_name.islower():
fail("Linter names are expected to be in lowercase: %s" % linter_name)
skip_names = [
"no-lint",
"no-%s" % linter_name,
]
skip_tags = [name for name in skip_names if name in tags]
if len(skip_tags) > 0:
return None
if native.existing_rule("%s_%s" % (OVERRIDE_RULE_NAME, linter_name)) != None:
return Label("%s//%s:%s_%s" % (get_repo_name(), native.package_name(), OVERRIDE_RULE_NAME, linter_name))
if linter_name in configured_linters:
return Label("@apple_linters//:%s_%s" % (OVERRIDE_RULE_NAME, linter_name))
return None
================================================
FILE: lint/private/package_lint_config.bzl
================================================
def _empty_rule_impl(ctx):
return [
DefaultInfo(),
]
_empty_rule = rule(
_empty_rule_impl,
attrs = {
},
)
OVERRIDE_RULE_NAME = "package_lint_config"
def package_lint_config(linters):
"""Register the given linters for the current bazel package.
This is expected to be near the top of the `BUILD.bazel` file and
allows users to override or configure specific linters for a bazel
package.
Args:
linters: a dict of "well known name" to Label.
"""
if native.existing_rule(":%s" % OVERRIDE_RULE_NAME):
fail("Lint configurations may only be overridden once per package")
for (key, value) in linters.items():
if not key.islower():
fail("All linter names should be lower case. eg. \"java-checkstyle\": %s" % key)
native.alias(
name = "%s_%s" % (OVERRIDE_RULE_NAME, key),
actual = value,
)
# Add a marker rule to indicate that we've finished overriding things
_empty_rule(name = OVERRIDE_RULE_NAME)
================================================
FILE: lint/private/providers.bzl
================================================
LinterInfo = provider(
fields = {
"language": "The language or kind of thing we are linting.",
"name": "The name of the linter",
},
)
================================================
FILE: lint/private/register_linters.bzl
================================================
COMMON_NAME = "apple_linters"
def _register_linters_impl(repository_ctx):
linter_names = [name.lower() for name in repository_ctx.attr.linters.keys()]
repository_ctx.file("defs.bzl", "configured_linters = %s" % linter_names)
# Ensure that all values are actually labels
linters = {}
for (name, value) in repository_ctx.attr.linters.items():
# Apparently the `Label` isn't available in this context. *sigh*
# Manually munge rule names so that they evaluate nicely
if value.startswith("//"):
linters.update({name.lower(): "@%s" % value})
elif value.startswith(":"):
linters.update({name.lower(): "@//%s%s" % (native.package_name, value)})
else:
linters.update({name.lower(): value})
repository_ctx.file(
"BUILD.bazel",
"""
load("@apple_rules_lint//lint/private:package_lint_config.bzl", "package_lint_config")
package(default_visibility = ["//visibility:public"])
package_lint_config(%s)
exports_files(["defs.bzl"])
""" % repr(linters),
)
register_linters = repository_rule(
_register_linters_impl,
attrs = {
"linters": attr.string_dict(
doc = "Dict of well-known linter name to label of linter configuration.",
allow_empty = True,
),
},
)
================================================
FILE: lint/repositories.bzl
================================================
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
load("@bazel_tools//tools/build_defs/repo:utils.bzl", "maybe")
def lint_deps():
maybe(
http_archive,
name = "bazel_skylib",
sha256 = "bc283cdfcd526a52c3201279cda4bc298652efa898b10b4db0837dc51652756f",
urls = [
"https://mirror.bazel.build/github.com/bazelbuild/bazel-skylib/releases/download/1.7.1/bazel-skylib-1.7.1.tar.gz",
"https://github.com/bazelbuild/bazel-skylib/releases/download/1.7.1/bazel-skylib-1.7.1.tar.gz",
],
)
================================================
FILE: lint/setup.bzl
================================================
load("@bazel_skylib//:workspace.bzl", "bazel_skylib_workspace")
load("//lint/private:register_linters.bzl", "COMMON_NAME", "register_linters")
def do_register_linters(name_to_linter_config):
for name in name_to_linter_config.keys():
if not name.islower():
fail("Linter names are expected to be in lowercase: %s" % name)
register_linters(
name = COMMON_NAME,
linters = name_to_linter_config,
)
def lint_setup(name_to_linter_config = {}):
"""Register the given linters.
This rule is designed to be run by users from the `WORKSPACE`. Ruleset
authors are expected to use `ruleset_lint_config`.
Args:
linters: a dict of "well known name" to Label.
"""
bazel_skylib_workspace()
if native.existing_rule(COMMON_NAME):
fail(
"Linting has already been configured. Please ensure that the call " +
"to `register_linters` is included as early as possible in your " +
"WORKSPACE. If you experience problems or need help, please raise an issue " +
"at https://github.com/apple/apple_rules_lint/issues/new",
)
return
# Ensure that labels are correct
do_register_linters(name_to_linter_config)
def ruleset_lint_setup():
"""Register the given linters.
This rule is designed to be run by authors of rulesets so that they
can ensure that they can call `get_lint_config` safely. Users should
use `lint_setup` instead.
"""
if not native.existing_rule(COMMON_NAME):
do_register_linters({})
================================================
FILE: scripts/build-release-artifacts
================================================
#!/usr/bin/env bash
set -euo pipefail
TAG="$1"
git archive --format=tar --prefix=apple_rules_lint-"${TAG}"/ "${TAG}" | gzip > apple_rules_lint-"${TAG}".tar.gz
================================================
FILE: scripts/generate-docs
================================================
#!/usr/bin/env bash
set -euo pipefail
bazel build lint/private/docs
cp -f bazel-bin/lint/private/docs/api.md api.md
================================================
FILE: tests/bcr/.bazelignore
================================================
other_module
================================================
FILE: tests/bcr/.bazelrc
================================================
build --experimental_enable_bzlmod
build --incompatible_unambiguous_label_stringification
================================================
FILE: tests/bcr/.bazelversion
================================================
c4a1ab8b6577c4376aaaa5c3c2d4ef07d524175c
================================================
FILE: tests/bcr/BUILD.bazel
================================================
exports_files(["foo_config.json"])
alias(
name = "foo-check-config",
actual = "@other_module//:foo-check-config",
)
================================================
FILE: tests/bcr/MODULE.bazel
================================================
module()
bazel_dep(name = "apple_rules_lint", version = "")
local_path_override(
module_name = "apple_rules_lint",
path = "../..",
)
bazel_dep(name = "other_module", version = "")
local_path_override(
module_name = "other_module",
path = "other_module",
)
linter = use_extension("@apple_rules_lint//lint:extensions.bzl", "linter")
linter.configure(
name = "foo-check",
config = "//:foo_config.json",
)
# No config for bar-lint
================================================
FILE: tests/bcr/WORKSPACE
================================================
================================================
FILE: tests/bcr/foo_config.json
================================================
{
"enabled": false
}
================================================
FILE: tests/bcr/other_module/BUILD.bazel
================================================
load("@apple_rules_lint//lint:defs.bzl", "get_lint_config")
fail("Expected no config for bar-lint") if get_lint_config("bar-lint", []) != None else []
fail("Expected config for foo-check") if get_lint_config("foo-check", []) == None else []
filegroup(
name = "foo-check-config",
srcs = [get_lint_config("foo-check", [])],
visibility = ["//visibility:public"],
)
================================================
FILE: tests/bcr/other_module/MODULE.bazel
================================================
module(
name = "other_module",
version = "",
)
bazel_dep(name = "apple_rules_lint", version = "0.4.0")
linter = use_extension("@apple_rules_lint//lint:extensions.bzl", "linter")
linter.register(name = "foo-check")
linter.register(name = "bar-lint")
# This config is ignored if other_module is not the root module.
linter.configure(
name = "bar-lint",
config = "//:does_not_exist",
)
================================================
FILE: tests/bcr/other_module/WORKSPACE
================================================