Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Scala rules for Bazel

License

NotificationsYou must be signed in to change notification settings

bazel-contrib/rules_scala

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Build status

Where to get help

Overview

Bazel is a tool for building and testing software and can handle large,multi-language projects at scale.

This project defines core build rules forScala that can be used to build, test, and package Scala projects.

Rules

See thedocs directory for documentation on otherrules_scalacapabilities as well.

Getting started

Install Bazel, preferably using theBazelisk wrapper. See thecompatible Bazel versions section to select a suitableBazel version.

Add the following configuration snippet to yourMODULE.bazel file and updatethe release<VERSION> as specified on therules_scala releasespage.

# MODULE.bazel# You can add `repo_name = "io_bazel_rules_scala"` if you still need it.bazel_dep(name="rules_scala",version="<VERSION>")# Selects the Scala version and other configuration parameters.## 2.12 is the default version. Use other versions by passing them explicitly, as# illustrated below.## See the documentation of `_settings_attrs` in `scala/extensions/config.bzl`# for other available parameters.## You may define your own custom toolchain using Maven artifact dependencies# configured by your `WORKSPACE` file, imported using an external loader like# https://github.com/bazelbuild/rules_jvm_external. See docs/scala_toolchain.md.scala_config=use_extension("@rules_scala//scala/extensions:config.bzl","scala_config",)scala_config.settings(scala_version="2.13.17")# See the `scala/extensions/deps.bzl` docstring for a high level description of# the tag classes exported by this module extension.scala_deps=use_extension("@rules_scala//scala/extensions:deps.bzl","scala_deps",)# Defines a default toolchain repo for the configured Scala version that loads# Maven deps like the Scala compiler and standard libs. Enable and configure# other builtin toolchains by instantiating their corresponding tag classes.# See the documentation in `scala/extensions/deps.bzl` for all builtin# toolchain configuration options.## On production projects, you may consider defining a custom toolchain to use# your project's required dependencies instead. In that case, you can omit using# the module extension and this next line altogether. Or, you can still use the# module extension to instantiate other optional `rules_scala` toolchains# without it.scala_deps.scala()# The remaining items are optional, enabling the precompiled protocol compiler# toolchain via `--incompatible_enable_proto_toolchain_resolution`. See the# "Using a precompiled protocol compiler" section below.scala_protoc=use_extension("@rules_scala//scala/extensions:protoc.bzl","scala_protoc",dev_dependency=True,)use_repo(scala_protoc,"rules_scala_protoc_toolchains")# Register this toolchain before any others in the file. Still safe even when# `--incompatible_enable_proto_toolchain_resolution` is `False`.register_toolchains("@rules_scala_protoc_toolchains//...:all",dev_dependency=True,)# Temporarily required for protocol compiler toolchainization until resolution# of protocolbuffers/protobuf#19679. Assumes having copied# `protoc/0001-protobuf-19679-rm-protoc-dep.patch` from `rules_scala` to# `protobuf.patch` in the root package. See the "Using a precompiled protocol# compiler" section below.bazel_dep(name="protobuf",version="30.2",repo_name="com_google_protobuf",)single_version_override(module_name="protobuf",patch_strip=1,patches= ["//:protobuf.patch"],version="30.2",)

Resolvingprotobuf conflicts

If a newerprotobuf version in the module graph breaks your build, usesingle_version_override ormultiple_version_override to fix it:

bazel_dep(name="protobuf",version="25.5",repo_name="com_google_protobuf",)single_version_override(module_name="protobuf",version="25.5",)

LegacyWORKSPACE configuration

rules_scala 7.x enables existing users to migrate to Bzlmod.WORKSPACEcontinues to work for Bazel6.5.0 (for now), 7.6.1, and 8, butWORKSPACE is going away in Bazel 9.

Add the following configuration snippet to yourWORKSPACE file and update therelease<VERSION> and its<SHA256> as specified on therules_scala releasespage. This snippet is designed to ensure that users pick up thecorrect order of dependencies forrules_scala. If you want to override any ofthe following dependency versions, make sure toload() them before callingrules_scala_dependencies().

# WORKSPACEload("@bazel_tools//tools/build_defs/repo:http.bzl","http_archive")# See https://github.com/bazelbuild/rules_scala/releases for up to date version# information, including `<VERSION>` and `<SHA256>` values.http_archive(name="rules_scala",# Can be "io_bazel_rules_scala" if you still need it.sha256="<SHA256>",strip_prefix="rules_scala-<VERSION>",url="https://github.com/bazelbuild/rules_scala/releases/download/<VERSION>/rules_scala-<VERSION>.tar.gz",)# This imports the minimum versions supported by the minimum supported Bazel# version, plus `rules_java` 8.5.0. If you use `rules_java` 7 or an earlier# `rules_java` 8 version, the corresponding `load` statements are slightly# different. See the `WORKSPACE` snippet from# https://github.com/bazelbuild/rules_java/releases corresponding to the# `rules_java` version for details.## Also, this imports `rules_proto` 6.0.2, though 6.0.0 will work. This is# because the `WORKSPACE` snippets for different versions of `rules_proto` vary# somewhat, and the 6.0.2 snippet works with the latest version. See# https://github.com/bazelbuild/rules_proto/releases for the corresponding# `rules_proto` release for details.## If you want the latest dependency versions, change `deps.bzl` to# `latest_deps.bzl`.load("@rules_scala//scala:deps.bzl","rules_scala_dependencies")rules_scala_dependencies()# Only include the next two statements if using# `--incompatible_enable_proto_toolchain_resolution`.# See the "Using a precompiled protocol compiler" section below.load("@platforms//host:extension.bzl","host_platform_repo")# Instantiates the `@host_platform` repo to work around:# - https://github.com/bazelbuild/bazel/issues/22558host_platform_repo(name="host_platform")# This is optional, but register this toolchain before any others. Requires# invoking the `scala_protoc_toolchains` repo rule, but is safe to include even# `--incompatible_enable_proto_toolchain_resolution` is `False`.# See the "Using a precompiled protocol compiler" section below.register_toolchains("@rules_scala_protoc_toolchains//...:all")load("@rules_java//java:rules_java_deps.bzl","rules_java_dependencies")rules_java_dependencies()load("@bazel_features//:deps.bzl","bazel_features_deps")bazel_features_deps()load("@bazel_skylib//:workspace.bzl","bazel_skylib_workspace")bazel_skylib_workspace()# If you need a specific `rules_python` version, specify it here.# Otherwise you may get the version defined in the `com_google_protobuf` repo.http_archive(name="rules_python",sha256="2ef40fdcd797e07f0b6abda446d1d84e2d9570d234fddf8fcd2aa262da852d1c",strip_prefix="rules_python-1.2.0",url="https://github.com/bazelbuild/rules_python/releases/download/1.2.0/rules_python-1.2.0.tar.gz",)load("@rules_python//python:repositories.bzl","py_repositories")py_repositories()# Note that `rules_java` 8.x suggests loading `protobuf_deps()` after# `rules_java_dependencies` and before `rules_java_toolchains()`:# - https://github.com/bazelbuild/rules_java/releases/tag/8.9.0## `rules_java` 7.x also works with this ordering.load("@com_google_protobuf//:protobuf_deps.bzl","protobuf_deps")protobuf_deps()load("@rules_java//java:repositories.bzl","rules_java_toolchains")rules_java_toolchains()load("@rules_proto//proto:repositories.bzl","rules_proto_dependencies")rules_proto_dependencies()load("@rules_proto//proto:setup.bzl","rules_proto_setup")rules_proto_setup()load("@rules_proto//proto:toolchains.bzl","rules_proto_toolchains")rules_proto_toolchains()# Include this after loading `platforms`, `com_google_protobuf`, and# `rules_proto` to enable the `//protoc` precompiled protocol compiler# toolchains. Requires at least `protobuf` v29.0. See the "Using a precompiled# protocol compiler" section below.load("@rules_scala//protoc:toolchains.bzl","scala_protoc_toolchains")# This name can be anything, but we recommend `rules_scala_protoc_toolchains`.scala_protoc_toolchains(name="rules_scala_protoc_toolchains")load("@rules_scala//:scala_config.bzl","scala_config")# Stores the selected Scala version and other configuration parameters.## 2.12 is the default version. Use other versions by passing them explicitly:##   scala_config(scala_version = "2.13.17")## You may define your own custom toolchain using Maven artifact dependencies# configured by your `WORKSPACE` file, imported using an external loader like# https://github.com/bazelbuild/rules_jvm_external. See docs/scala_toolchain.md.scala_config()load("@rules_scala//scala:toolchains.bzl","scala_register_toolchains","scala_toolchains",)# Defines a default toolchain repo for the configured Scala version that loads# Maven deps like the Scala compiler and standard libs. Enable other builtin# toolchains by setting their corresponding parameters to `True`. See the# `scala_toolchains()` docstring for all builtin toolchain configuration# options.## On production projects, you may consider defining a custom toolchain to use# your project's required dependencies instead. In that case, you can omit# `scala_toolchains()` or explicitly set `scala = False` if you use it to# instantiate other builtin toolchains.scala_toolchains()scala_register_toolchains()

Important changes inrules_scala v7.0.0 configuration

The above configuration snippet reflects important changes sincerules_scalav6.x:

  • rules_scala no longer requires theio_bazel_rules_scala repositoryname unless yourBUILD files or those of your dependencies require it(#1696).

    Update your project's@io_bazel_rules_scala references to@rules_scalaif possible. Otherwise, userepo_name = "io_bazel_rules_scala" inbazel_dep() orname = "io_bazel_rules_scala" inhttp_archive.

    You can use therepo_mapping attribute ofhttp_archive or equivalentBzlmod mechanisms to translate@rules_scala to@io_bazel_rules_scala fordependencies. See theTranslating repo names fordependencies section below for details. (That section isabout@rules_scala_config, but the same mechanisms apply.)

  • rules_scala v7.0.0 introduces a newscala_toolchains() API that isvery different fromrules_scala 6. For details on what's changed, seetheNew 'scala_toolchains()' API for 'WORKSPACE'section below.

Loading thescala_* rules

Add the following to yourBUILD files to make thescala_* rules available:

load("@rules_scala//scala:scala.bzl","scala_binary","scala_library","scala_test",)

Using a precompiled protocol compiler

rules_scala now supports the--incompatible_enable_proto_toolchain_resolution flag when usingprotobufv29 or later with the minimum dependency versions specifiedbelow. When using this flag with theMODULE.bazel orWORKSPACEconfigurations below,rules_scala will use a precompiled protocol compilerbinary by default.

Windows builds now require usingprotobuf v29 or later with the precompiledprotocol compiler toolchain. See theWindows MSVC builds of protobuf brokenby default section below for details.

Minimum dependency versions

These are the minimum dependency versions required to enable the precompiledprotocol compiler toolchain. These are validated bytest_dependency_versions.sh.

Note thatrules_java can be as low as 8.3.0, compared torules_java 8.5.0specified inCompatible Bazel versions.

DependencyMinimum versionReason
protobufv29.0See theWhy this requires 'protobuf' v29 or later section.
Bazel7.1.0 (withrules_java 7.10.0, 8.3.2)
7.3.2 (withrules_java 8.3.0)
module(bazel_compatibility = "...") constraints inMODULE.bazel
platforms0.0.9Creates the@host_platform repo used to auto-detect the toolchain for the host platform.
rules_java7.10.0 (with--experimental_google_legacy_api), 8.3.0protobuf v29 needs 7.8.0 with--experimental_google_legacy_api forProguardSpecProvider. Then it needs 7.10.0 for//java/private:proto_support.bzl visibility.
protobuf v29 needs@rules_java//java/private:proto_support.bzl from v8.2.0. Seebazelbuild/rules_java@94d5617.
v8.3.0 fixesbazelbuild/rules_java#233.
rules_proto7.0.0Required byprotobuf v29 and later.
bazel_skylib1.7.0Containspaths.is_normalized, required by//bazel/private:bazel_proto_library_rule.bzl inprotobuf v29. Seebazelbuild/bazel-skylib@0e485c8.

Common setup

To set the flag in your.bazelrc file:

# .bazelrccommon --incompatible_enable_proto_toolchain_resolution

In bothMODULE.bazel andWORKSPACE, you must register the protocol compilertoolchainsbefore any other toolchains. It's safe to use even when--incompatible_enable_proto_toolchain_resolution isFalse.

It is OK to callregister_toolchains before using thescala_protoc extensionunder Bzlmod, and before thescala_protoc_toolchains() repo rule underWORKSPACE.

# MODULE.bazelregister_toolchains("@rules_scala_protoc_toolchains//...:all",dev_dependency=True,)# WORKSPACEregister_toolchains("@rules_scala_protoc_toolchains//...:all")

Using thescala_protoc module extension under Bzlmod

Thescala_protoc module extension instantiates the protocol compilertoolchain under Bzlmod. Itmust be marked as adev_dependency.

# MODULE.bazelscala_protoc=use_extension("@rules_scala//scala/extensions:protoc.bzl","scala_protoc",dev_dependency=True,)use_repo(scala_protoc,"rules_scala_protoc_toolchains")

Invoking thescala_protoc_toolchains() repo rule underWORKSPACE

Thescala_protoc_toolchains repo rule instantiates the protocol compilertoolchain. The repo name can be anything, but we recommendrules_scala_protoc_toolchains.

# WORKSPACE# Include this after loading `platforms`, `com_google_protobuf`, and# `rules_proto`.load("@rules_scala//protoc:toolchains.bzl","scala_protoc_toolchains")scala_protoc_toolchains(name="rules_scala_protoc_toolchains")

Specifying additionalprotoc platforms

Use theplatforms parameter to specify additionalplatforms if theexecution platform may differ from the host platform, as when building withremote execution. Valid values come from the file name suffixes ofprotocolbuffers/protobuf releases. It's also safe to explicitly include thehost platform.

For example, imagine the host platform is macOS running on Apple Silicon, butthe remote execution platform is Linux running on an x86 processor.rules_scala configures the"osx-aarch_64" platform automatically. Then inMODULE.bazel you would include:

# MODULE.bazelscala_protoc.toolchains(platforms= ["linux-x86_64"],)

InWORKSPACE you would include:

# WORKSPACEscala_protoc_toolchains(name="rules_scala_protoc_toolchains",platforms= ["linux-x86_64"],)

Temporary requiredprotobuf patch

At the moment, enabling protocol compiler toolchainization requires applyingprotoc/0001-protobuf-19679-rm-protoc-dep.patch. It is thegit diff outputfrom the branch used to createprotocolbuffers/protobuf#19679. Without it, atransitive dependency on@com_google_protobuf//:protoc remains, causingprotoc to recompile even with the precompiled toolchain registered first.

If and whenprotobuf merges that pull request, or applies an equivalent fix,this patch will no longer be necessary.

protobuf patch setup under Bzlmod

Applying theprotobuf patch requires usingsingle_version_override,which also requires that the patch be a regular file in your own repo. In otherwords, neither@rules_scala//protoc:0001-protobuf-19679-rm-protoc-dep.patchnor analias to it will work.

Assuming you've copied the patch to a file calledprotobuf.patch in the rootpackage of your repository, add the following to yourMODULE.bazel:

# MODULE.bazel# Required for protocol compiler toolchainization until resolution of# protocolbuffers/protobuf#19679.bazel_dep(name="protobuf",version="30.2",repo_name="com_google_protobuf",)single_version_override(module_name="protobuf",patch_strip=1,patches= ["//:protobuf.patch"],version="30.2",)

protobuf patch setup underWORKSPACE

scala/latest-deps.bzl currently applies theprotobuf patch toprotobuf v30.2.

If you need to apply the patch to a different version ofprotobuf, copy it toyour repo as described in the Bzlmod setup above. Then apply it in your ownhttp_archive call:

http_archive(name="com_google_protobuf",sha256="07a43d88fe5a38e434c7f94129cad56a4c43a51f99336074d0799c2f7d4e44c5",strip_prefix="protobuf-30.2",url="https://github.com/protocolbuffers/protobuf/archive/refs/tags/v30.2.tar.gz",repo_mapping= {"@com_google_absl":"@abseil-cpp"},patches= ["//protobuf.patch"],patch_args= ["-p1"],)

Setting up the@host_platform repo underWORKSPACE

WORKSPACE must include thehost_platform_repo snippet fromGetting started to work aroundbazelbuild/bazel#22558:

# WORKSPACEload("@platforms//host:extension.bzl","host_platform_repo")# Instantiates the `@host_platform` repo to work around:# - https://github.com/bazelbuild/bazel/issues/22558host_platform_repo(name="host_platform")

Why this requiresprotobuf v29 or later

Using--incompatible_enable_proto_toolchain_resolution with versions ofprotobuf before v29 causes build failures due to a missing internal Bazeldependency.

Bazel's builtinbazel_java_proto_aspect transitively depends on a toolchainwith atoolchain_type of@rules_java//java/proto:toolchain_type.Experimentation withprotobuf v28.2 using both Bazel 6.5.0 and 7.5.0 led tothe following error:

ERROR: .../external/bazel_tools/src/main/protobuf/BUILD:28:15:  in @@_builtins//:common/java/proto/java_proto_library.bzl%bazel_java_proto_aspect  aspect on proto_library rule  @@bazel_tools//src/main/protobuf:worker_protocol_proto:Traceback (most recent call last):  File "/virtual_builtins_bzl/common/java/proto/java_proto_library.bzl",    line 53, column 53, in _bazel_java_proto_aspect_impl  File "/virtual_builtins_bzl/common/proto/proto_common.bzl",    line 364, column 17, in _find_toolchainError in fail: No toolchains registered for  '@rules_java//java/proto:toolchain_type'.ERROR: Analysis of target  '@@bazel_tools//src/main/protobuf:worker_protocol_proto' failed

See#1710 for details of the experiment.

Forprotobuf v29.0,protocolbuffers/protobuf#18308 added the@protobuf//bazel/private/toolchains package and updatedprotobuf_deps() from@protobuf//:protobuf_deps.bzl to register it:

native.register_toolchains("//bazel/private/toolchains:all")

protocolbuffers/protobuf#18435 then introducedjava_source_toolchain_bazel7 with the requiredtoolchain_type.

More background on protocol compiler toolchainization

Persistent workers

To run with a persistent worker (much faster), add the following toyour.bazelrc file:

build --strategy=Scalac=workerbuild --worker_sandboxing

Coverage support

To produce a combined coverage report:

bazel coverage \  --combined_report=lcov \  --coverage_report_generator="@bazel_tools//tools/test/CoverageOutputGenerator/java/com/google/devtools/coverageoutputgenerator:Main" \  //...

This should produce a singlebazel-out/_coverage/_coverage_report.dat from all coverage files that are generated.

You can extract information from your coverage reports withlcov:

# For a summary:lcov --summary your-coverage-report.dat# For details:lcov --list your-coverage-report.dat

If you prefer an HTML report, then you can usegenhtml provided also by thelcov package.

Coverage support has been only tested withScalaTest.

Please checkcoverage.md for more details on coverage support.

Selecting the Scala version

With builtin toolchains

rules_scala supports the last two released minor versions for each of Scala 2.11, 2.12, 2.13.Previous minor versions may work but are supported only on a best effort basis.

TheGetting started section illustrates how to select thedefault Scala version and configure its dependencies.

With custom toolchains

You can define your own customscala_toolchain bycallingsetup_scala_toolchain() with dependencies that you specify.

Note: Toolchains are a more flexible way to configure dependencies, so you should prefer that way.Please also note, that theoverriden_artifacts parameter is likely to be removed in the future.

Multiple versions (cross-compilation)

rules_scala supports configuring multiple Scala versions and offers target-level control of which one to use.

Please checkcross-compilation.md for more details on cross-compilation support.

Compatible Bazel versions

Bazel compatibility is tied directly to the versions ofprotobuf required byBazel andrules_java, and their compatibility withscalapb/ScalaPB Maven artifacts. For extensive analysis,see#1647.

The Bazel versions and dependency versions below represent the minimum versionscompatible withrules_scala 7.x.

ModeSupported Bazel versions
Bzlmod>= 7.1.0, 8.x, 9.*
rolling,last_green
WORKSPACE6.5.0, >= 7.1.0, 8.x
(see thenotes on 6.5.0 compatibility)

rules_scala 7.0.0 usesScalaPB 1.0.0-alpha.1 to supportprotobuf v28.2 andlater, required by newer Bazel versions and other dependencies. Below are theminimum versions ofprotobuf and related dependencies supported for Bazel 7and 8.

DependencyBazel >= 7.1.0Bazel 8.x
bazel_skylib1.6.01.7.0
protobufv28.2v29.0
rules_java7.6.0, 8.4.08.5.0
rules_proto6.0.07.0.0

The next major release will likely drop support forprotobuf versions beforev29 and removerules_proto completely. This is to comply with the guidance inProtobuf News: News Announcements for Version 29.x. For more details, see thiscomment from #1710explaining why rules_proto remains for now.

Using a prebuilt@com_google_protobuf//:protoc or C++ compiler flags

Newer versions ofabseil-cpp, required by newer versions of@com_google_protobuf//:protoc, fail to compile under Bazel 6.5.0 by default.The latest versions ofabseil-cpp also fail to compile under Bazel 7 bydefault.protoc will also fail to build on Windows when usingMSVC. You will have to choose one of the following approaches toresolve this problem.

You may use protocol compiler toolchainization withprotobuf v29 or later toavoid recompilingprotoc. You may want to enable this even if your builddoesn't break, as it saves time by avoiding frequentprotoc recompilation. SeetheUsing a precompiled protocol compiler section for details.

Otherwise, if migrating to Bazel 8 isn't an immediate option, you will need toset the following compiler flags in.bazelrc per#1647:

common --enable_platform_specific_configcommon:linux --cxxopt=-std=c++17common:linux --host_cxxopt=-std=c++17common:macos --cxxopt=-std=c++17common:macos --host_cxxopt=-std=c++17common:windows --cxxopt=/std=c++17common:windows --host_cxxopt=/std=c++17

Note that this example usescommon: config settings instead ofbuild:. Thisseems to prevent invalidating the action cache betweenbazel runs, whichimproves performance.

Usage withbazel-deps

Bazel-deps allows you to generate bazel dependencies transitively for maven artifacts. Generally we don't want bazel-deps to fetchscala artifacts from maven but instead use the ones we get from callingscala_repositories. The artifacts can be overridden in thedependencies file used by bazel-deps:

replacements:org.scala-lang:scala-library:lang:scala/unmangledtarget:"@io_bazel_rules_scala_scala_library//:io_bazel_rules_scala_scala_library"scala-reflect:lang:scala/unmangledtarget:"@io_bazel_rules_scala_scala_reflect//:io_bazel_rules_scala_scala_reflect"scala-compiler:lang:scala/unmangledtarget:"@io_bazel_rules_scala_scala_compiler//:io_bazel_rules_scala_scala_compiler"org.scala-lang.modules:scala-parser-combinators:lang:scalatarget:"@io_bazel_rules_scala_scala_parser_combinators//:io_bazel_rules_scala_scala_parser_combinators"scala-xml:lang:scalatarget:"@io_bazel_rules_scala_scala_xml//:io_bazel_rules_scala_scala_xml"

Publishing to Maven repository

SeePublish your Scala Libraries to a Maven Repository.

Dependency Tracking

rules_scala supports multiple dependency modes including strict and unused dependency tracking. SeeDependency Tracking for more info.

Advanced configurable rules

To make the ruleset more flexible and configurable, we introduce a phase architecture. By using a phase architecture, where rule implementations are defined as a list of phases that are executed sequentially, functionality can easily be added (or modified) by adding (or swapping) phases.

Phases provide 3 major benefits:

  • Consumers are able to configure the rules to their specific use cases bydefining new phases within their workspace without impacting other consumers.
  • Contributors are able to implement new functionalities by creating additionaldefault phases.
  • Phases give us more clear idea what steps are shared across rules.

SeeCustomizable Phase for more info.

Phase extensions

Building from source

Build main sources only:

bazel build //src/...

Run all smaller tests:

bazel test //test/...

To run the full test suite:

bash test_all.sh

Note:bazel test //... will not work since we have a sub-folder on theroot folder which is meant to be used in a failure scenario in the integrationtests. Similarly, to only build you should usebazel build //src/... due tothat folder.

Breaking changes inrules_scala 7.x

The main objective ofrules_scala 7.x is to enable existing users to migrateto Bazel 8 and Bzlmod. To facilitate a gradual migration, it is compatiblewith both Bazel 7 and Bazel 8, and bothWORKSPACE and Bzlmod. It remainscompatible with Bazel 6.5.0 builds usingWORKSPACE for the time being, butBazel 6 is no longer officially supported.

rules_java 7.x contains the following breaking changes when upgrading fromrules_scala 6.x.

Newscala_toolchains() API forWORKSPACE

rules_scala 7.0.0 replaces existing*_repositories() and*_toolchains()macros with the combination ofrules_scala_dependencies(),scala_toolchains(), andscala_register_toolchains().

These macros no longer exist:

  • jmh_repositories()
  • junit_repositories()
  • junit_toolchain()
  • rules_scala_setup()
  • rules_scala_toolchain_deps_repositories()
  • scala_proto_default_repositories()
  • scala_proto_register_enable_all_options_toolchain()
  • scala_proto_register_toolchains()
  • scala_proto_repositories()
  • scala_register_unused_deps_toolchains()
  • scala_repositories()
  • scalafmt_default_config()
  • scalafmt_repositories()
  • scalatest_repositories()
  • scalatest_toolchain()
  • specs2_junit_repositories()
  • specs2_repositories()
  • specs2_version()
  • twitter_scrooge()

Replace toolchain configurations like the following:

load("@rules_scala//scala:scala.bzl","rules_scala_setup","rules_scala_toolchain_deps_repositories",)rules_scala_setup()rules_scala_toolchain_deps_repositories(fetch_sources=True)# Other dependency declarations...load("@rules_scala//:scala_config.bzl","scala_config")scala_config(scala_version="2.13.17")load("//testing:scalatest.bzl","scalatest_repositories","scalatest_toolchain",)scalatest_repositories()scalatest_toolchain()load("//scala/scalafmt:scalafmt_repositories.bzl","scalafmt_default_config","scalafmt_repositories",)scalafmt_default_config()scalafmt_repositories()

with calls torules_scala_dependencies(),scala_toolchains() (with theappropriate parameters set), andscala_register_toolchains():

load("@rules_scala//scala:deps.bzl","rules_scala_dependencies")rules_scala_dependencies()# See the `WORKSPACE` configuration snippet from the "Getting started" section# above for other dependency declarations.load("@rules_scala//:scala_config.bzl","scala_config")scala_config(scala_version="2.13.17")load("@rules_scala//scala:toolchains.bzl","scala_register_toolchains","scala_toolchains",)scala_toolchains(scalafmt=True,scalatest=True,)scala_register_toolchains()

See thescala_toolchains() docstring for theparameter list, which is almost in complete correspondence with parameters fromthe previous macros. TheWORKSPACE files in this repository also provide manyexamples.

Replacing toolchain registration macros

Almost allrules_scala toolchains configured usingscala_toolchains() areautomatically registered byscala_register_toolchains(). The same is true fortoolchains configured using thescala_deps module extension under Bzlmod.There are two toolchain macro replacements that require special handling.

The first is replacingscala_proto_register_enable_all_options_toolchain()with the following:

# MODULE.bazelscala_deps.scala_proto("default_gen_opts"= ["flat_package","grpc","single_line_to_proto_string",    ],)# WORKSPACEscala_toolchains(scala_proto= {"default_gen_opts": ["flat_package","grpc","single_line_to_proto_string",        ],    },)

The other is replacingscala_register_unused_deps_toolchains() with anexplicitregister_toolchains() call:

register_toolchains("@rules_scala//scala:unused_dependency_checker_error_toolchain",)

InWORKSPACE, thisregister_toolchains() call must come before callingscala_register_toolchains() to ensure this toolchain takes precedence. Thesame exact call will also work inMODULE.bazel.

Disabling builtin Scala toolchains when defining custom Scala toolchains

Whenusing 'setup_scala_toolchain()' with custom compiler JARs, don't usescala_deps orscala_toolchains() if you don't need any other builtintoolchains.

If you do need other builtin toolchains when using Bzlmod, then use the moduleextension and only instantiate the tag classes to the corresponding toolchains.

If you do need other builtin toolchains when usingWORKSPACE, then setscala = False.

# MODULE.bazelscala_deps.scala_proto()scala_deps.twitter_scrooge()# ...other scala_deps tag class instantations...# WORKSPACEscala_toolchains(scala=False,scala_proto=True,twitter_scrooge=True,# ...other toolchain parameters...)

This avoids instantiating the default Scala toolchain and compiler JARrepositories, and disables the corresponding Scala version check, which mayotherwise fail. This is equivalent to two ways in which the previous API avoidedthe same default behavior:

  • Callingscala_repositories(load_jar_deps = False) would instantiate onlyotherrules_scala dependency repos (rules_java,protobuf, etc.) andcompiler source JAR repos.

  • Callingrules_scala_setup() directly, instead of indirectly viascala_repositories(), instantiated the other dependency repositories only.

See"Defining your own scala_toolchain > Step 3 (optional)" fromdocs/scala_toolchain.md for futherdetails.

Bzlmod configuration

The Bzlmod implementation funnels through thescala_toolchains() macro aswell, ensuring maximum compatibility withWORKSPACE configurations. Theequivalent Bzlmod snippet for thescala_toolchains() snippet above would be:

bazel_dep(name="rules_scala",version="7.0.0")scala_config=use_extension("@rules_scala//scala/extensions:config.bzl","scala_config",)scala_config.settings(scala_version="2.13.17")scala_deps=use_extension("@rules_scala//scala/extensions:deps.bzl","scala_deps",)scala_deps.scala()scala_deps.scalafmt()scala_deps.scalatest()

The module extensions callscala_config() andscala_toolchains()respectively. TheMODULE.bazel file forrules_scala declares its owndependencies viabazel_dep(), allowing Bazel to resolve versions according tothe main repository/root module configuration. It also callsregister_toolchains(), so you don't have to (unless you want toregister a specific toolchain to resolve first).

TheMODULE.bazel files in this repository provide many examples.

Copyregister_toolchains() calls fromWORKSPACE toMODULE.bazel

TheMODULE.bazel file fromrules_scala automatically callsregister_toolchains() for toolchains configured via itsscala_deps moduleextension. However, you must register explicitly in yourMODULE.bazel file anytoolchains that you want to take precedence over the toolchains configured byscala_deps. This includes anyscala_toolchaintargets defined in your project, or optionalrules_scala toolchains like thedependency checker error toolchain from above:

register_toolchains("@rules_scala//scala:unused_dependency_checker_error_toolchain",)

@io_bazel_rules_scala_config is now@rules_scala_config

Since@io_bazel_rules_scala is no longer hardcoded inrules_scala internals,we've shortened@io_bazel_rules_scala_config to@rules_scala_config. Thisshouldn't affect most users, but it may break some builds using@io_bazel_rules_scala_config to define customcross-compilation targets.

If your project uses Bzlmod, you can remap@io_bazel_rules_scala_config to@rules_scala_config for your own project viause_repo(). Use this only ifupdating your project's own@io_bazel_rules_scala_config references isn'timmediately feasible.

scala_config=use_extension("@rules_scala//scala/extensions:config.bzl","scala_config",)use_repo(scala_config,io_bazel_rules_scala_config="rules_scala_config")

If your project usesWORKSPACE youmust update all@io_bazel_rules_scala_config references to@rules_scala_config. There is nouse_repo() equivalent.

Translating repo names for dependencies

For any dependencies referencing@io_bazel_rules_scala_config, use the workaroundsbelow. The same workarounds for your project's dependencies also apply totranslating@rules_scala to@io_bazel_rules_scala.

Bzlmod

For module extensions, useoverride_repo() to override@io_bazel_rules_scala_config with@rules_scala_config:

bazel_dep(name="foo",version="1.0.0")foo_ext=use_extension("@foo//:ext.bzl","foo_ext")override_repo(foo_ext,io_bazel_rules_scala_config="rules_scala_config")

bazel_dep() dependencies may still require@io_bazel_rules_scala_config(or@io_bazel_rules_scala) outside of a module extension. In this case, toavoid using the old name in your own project, usearchive_override() orgit_override() with therepo_mapping attribute. These overrides pass therepo_mapping through to the underlyinghttp_archive() andgit_repository() rules:

archive_override(    ...repo_mapping= {"@io_bazel_rules_scala_config":"@rules_scala_config",    }    ...)

WORKSPACE

For dependencies, use therepo_mapping attribute ofhttp_archive() orgit_repository():

http_archive(    ...repo_mapping= {"@io_bazel_rules_scala_config":"@rules_scala_config",    }    ...)

Windows MSVC builds ofprotobuf broken by default

MSVC builds of recentprotobuf versions started failing, as first noted in#1710. On top of that,protobuf is planning to stopsupporting Bazel + MSVC builds per:

Enableprotocol compiler toolchainization to fix broken Windowsbuilds by avoiding@com_google_protobuf//:protoc recompilation.

Minimum ofprotobuf v28.2

rules_scala requires at leastprotobuf v28.2, and at least v29 forprotocolcompiler toolchain support. NoScalaPB release supportsprotobufv25.6, v26, or v27.

Using earlierprotobuf versions

If you can't update toprotobuf v28.2 or later right now, build using Bazel 7and the following maximum versions of key dependencies. This is not officiallysupported, but should work for some time.

DependencyMax compatible versionReason
ScalaPB0.11.17
(0.9.8 for Scala 2.11)
Later versions only supportprotobuf >= v28.2.
protobufv25.5Maximum version supported byScalaPB 0.11.17.
rules_cc0.0.90.0.10 requires Bazel 7 to defineCcSharedLibraryHintInfo.
0.0.13 requires at leastprotobuf v27.0.
rules_java7.12.58.x requiresprotobuf v27 and later.
rules_proto6.0.2Maximum version supportingprotobuf v25.5

Embedded resource paths no longer begin withexternal/<repo_name>

Any program compiled with an external repo asset in its 'resources' attributewill need to strip the 'external/' and repo name components from itspath. For example, the path forresources = ["@some_external_repo//:resource.txt"] would change thus:

  • Before:external/some_external_repo/resource.txt
  • After:resource.txt

This avoids encoding repo names or any other Bazel system knowledge in thecompiled artifacts. This is especially important under Bzlmod, because thegenerated path would otherwise containthecanonical repo name, upon whichusers should neverdepend.

Update@bazel_tools//tools/jdk targets to@rules_java//toolchains targets

Per#1660,rules_java 7.10.0 and later precipitate theneed to replace@bazel_tools//tools/jdk targets with corresponding@rules_java//toolchains targets. Fix any targets broken by thisrules_javaupgrade by doing a global search and replace.

However,@bazel_tools//tools/jdk:toolchain_type dependencies must remain fornow, as there's not yet a correspondingtoolchain_type() targetin@rules_java.

Builtin repositories no longer visible by default under Bzlmod

Under Bzlmod, repos are only visible to the module extension that creates them,unless theMODULE.bazel file brings them into scope withuse_repo(). This canlead to errors like those from the following example, whichoriginally called'setup_scala_toolchain()' under Bzlmod:

load("@rules_scala//scala:scala.bzl","setup_scala_toolchain")setup_scala_toolchain(name="custom_scala_toolchain",scalacopts= ["-Wunused:all",    ],strict_deps_mode="error",unused_dependency_checker_mode="warn",)

setup_scala_toolchains is a macro that can take user specified classpathtargets as described indocs/scala_toolchain.md.Without explicit*_classpath or*_deps arguments,setup_scala_toolchain()defaults to using dependency repositories generated byrules_scala itself.This worked underWORKSPACE, but breaks under Bzlmod, because the builtintoolchain dependency repos are no longer in the project's scope by default:

ERROR: no such package    '@@[unknown repo 'org_scala_sbt_compiler_interface_3_3_5'        requested from @@]//':    The repository '@@[unknown repo 'org_scala_sbt_compiler_interface_3_3_5'        requested from @@]' could not be resolved:    No repository visible as '@org_scala_sbt_compiler_interface_3_3_5'

In this case, where the toolchain only sets different compiler options, the bestfix is touse the 'scala_toolchain' rule directly instead.Its underlyingBUILD rule uses builtin toolchain dependencies via existingtargets visible withinrules_scala, without forcing users to import them:

load("@rules_scala//scala:scala_toolchain.bzl","scala_toolchain")scala_toolchain(name="custom_scala_toolchain_impl",scalacopts= ["-Ywarn-unused",    ],strict_deps_mode="error",unused_dependency_checker_mode="warn",)toolchain(name="custom_scala_toolchain",toolchain=":custom_scala_toolchain_impl",toolchain_type="@rules_scala//scala:toolchain_type",visibility= ["//visibility:public"],)

A big part of the Bzlmodification work involved enablingrules_scala togenerate and register toolchainswithout forcing users to bring theirdependencies into scope. However, another way to fix this specific problem is tocalluse_repo for every builtin repository needed by thesetup_scala_toolchain() call.

Replace some$(location) calls with$(rootpath) for Bazel 8

This isn't actually arules_scala breakage, but a Bazel 8 breakage encounteredwhile preparingrules_scala for Bazel 8 in#1652.bazelbuild/bazel#25198 describes how the semantics of some instances of$(location) changed, and how changing these particular instances to$(rootpath) fixed them.

The good news is that replacing such instances$(location) with$(rootpath)is backwards compatible to Bazel 6.5.0 and 7.6.1. Updating them now will ensurefuture compatibility.

Limited Bazel 6.5.0 compatibility

rules_scala 7.x officially drops support for Bazel 6.5.0. Bzlmod buildswith Bazel 6.5.0 won't work at all becauseBazel 6.5.0 doesn't support'use_repo_rule', which'rules_jvm_external' >= 6.3 requires.

At the moment,WORKSPACE builds mostly continue to work with Bazel 6.5.0, butmay break at any time.

Configuring the protocol compiler toolchain

SeeUsing a prebuilt @com_google_protobuf//:protoc or C++ compilerflags for protocol compiler configuration requirements.

Using older versions ofprotobuf

SeeUsing earlier protobuf versions fordetails on using older versions of protobuf if necessary.

scala_proto not supported for Scala 2.11

ScalaPB 0.9.8, thelast version compatible with Scala 2.11, doesn't supportprotobuf v25.6 orlater. See#1712 for an example of what happens to Scala2.11 test cases when usingprotobuf v25.6. Sincerules_scala now supportsmore recentprotobuf versions viaScalaPB 1.0.0-alpha1, we had toremove the Scala 2.11 test cases.

Buildingscala_proto for Scala 2.11 requiresbuilding with Bazel 6.5.0under WORKSPACE, with the maximum dependency versions specified inthat section. While this may continue to work for some time, it is notofficially supported.

scala_proto_toolchain changes and newscalapb_toolchain macro

scala_proto_toolchain has a more flexible plugin configuration schema. Thenewgenerators andgenerators_opts attributes replace the followingattributes:

  • with_grpc
  • with_flat_package
  • with_single_line_to_string
  • main_generator
  • named_generators

Now each generator (plugin) will get a corresponding namethat can be used for further plugin options setup:

scala_proto_toolchain(name="example",generators= {"scala":"scripts.ScalaPbCodeGenerator","jvm_extra_protobuf_generator":"scalarules.test.extra_protobuf_generator.ExtraProtobufGenerator",    },generators_opts= {"scala": ["grpc","single_line_to_proto_string",        ],"jvm_extra_protobuf_generator": ["grpc","single_line_to_proto_string",        ],    },)

scalapb_grpc_deps no longer exists since it's now the user's responsibilityto configure dependencies based on the provided generators and their options.

The newscalapb_toolchain convenience macro wrapsscala_proto_toolchainto provide the defaultScalaPB implementation:

load("//scala_proto:scala_proto_toolchain.bzl","scalapb_toolchain")scalapb_toolchain(name="my_toolchain",opts= ["grpc","single_line_to_proto_string",    ],visibility= ["//visibility:public"],)

Similarly,setup_scala_proto_toolchains() now uses adefault_gen_optsparameter to replace the previous booleanenable_all_options parameter.

Removal ofbind() aliases fortwitter_scrooge dependencies

rules_scala 7.x removes all of the obsoletebind() aliases under//external:io_bazel_rules_scala/dependency/ created fortwitter_scroogetoolchain dependencies. If your project happens to depend on these aliases, youcan replace them with the following repository references:

bind() alias under//external:io_bazel_rules_scala/dependency/Repository reference
scala/guava@io_bazel_rules_scala_guava
thrift/javax_annotation_api@io_bazel_rules_scala_javax_annotation_api
thrift/libthrift@libthrift
thrift/mustache@io_bazel_rules_scala_mustache
thrift/scopt@io_bazel_rules_scala_scopt
thrift/scrooge_core@io_bazel_rules_scala_scrooge_core
thrift/scrooge_generator@io_bazel_rules_scala_scrooge_generator
thrift/util_core@io_bazel_rules_scala_util_core
thrift/util_logging@io_bazel_rules_scala_util_logging

To access these repositories under Bzlmod, you'll need to add the following toyourMODULE.bazel file:

scala_deps.twitter_scrooge()use_repo(scala_deps,"io_bazel_rules_scala_guava","io_bazel_rules_scala_javax_annotation_api","io_bazel_rules_scala_mustache","io_bazel_rules_scala_scopt","io_bazel_rules_scala_scrooge_core","io_bazel_rules_scala_scrooge_generator","io_bazel_rules_scala_util_core","io_bazel_rules_scala_util_logging","libthrift",)

Bazel module compatibility levels

rules_scala 7.0.0 will set thecompatibility_levelvalue for itsmodule()directive. Thecompatibility_level forrules_scala will track major versionnumbers (persemantic versioning), and thisREADME willclearly document the reason for the level bump.compatibility_level mismatchesin the module graph will cause module resolution to fail, signaling the presenceof known breaking changes.

The concept of propercompatibility_level usage is still up for discussion inbazelbuild/bazel#24302. However, the policy above favors forcing moduleresolution to fail, rather than allowing a later execution step to fail with apotentially confusing error message. If a version bump may break builds for anyknown reason, we will explain why up front instead of waiting for users to besurprised.

A comment from #1647 illustrates how 'rules_erlang' fails due to'compatibility_level' conflicts. The'rules_erlang' 3.0.0 releasenotes describe thebreaking changes. This seems like a reasonable model to follow.

Contributing

SeeCONTRIBUTING.md for more info.

Adopters

Here's a (non-exhaustive) list of companies that userules_scala in production. Don't see yours?You can add it in a PR!


[8]ページ先頭

©2009-2025 Movatter.jp