Code Monkey home page Code Monkey logo

rules_kotlin's Introduction

Bazel Kotlin Rules

Build Status

Releases


For more information about release and changelogs please see Changelog or refer to the Github Releases page.

rules_kotlin Bazel Compatibility

Overview

rules_kotlin supports the basic paradigm of *_binary, *_library, *_test of other Bazel language rules. It also supports jvm, android, and js flavors, with the prefix kt_jvm and kt_js, and kt_android typically applied to the rules.

Support for kotlin's -Xfriend-paths via the associates= attribute in the jvm allow access to internal members.

Also, kt_jvm_* rules support the following standard java_* rules attributes:

  • data
  • resource_jars
  • runtime_deps
  • resources
  • resources_strip_prefix
  • exports

Android rules also support custom_package for R.java generation, manifest=, resource_files, etc.

Other features:

  • Persistent worker support.
  • Mixed-Mode compilation (compile Java and Kotlin in one pass).
  • Configurable Kotlinc distribution and version
  • Configurable Toolchain
  • Support for all recent major Kotlin releases.

Javascript is reported to work, but is not as well maintained (at present)

Documentation

Generated API documentation is available at https://bazelbuild.github.io/rules_kotlin/kotlin.

Quick Guide

WORKSPACE

In the project's WORKSPACE, declare the external repository and initialize the toolchains, like this:

load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")

rules_kotlin_version = "1.9.0"
rules_kotlin_sha = "5766f1e599acf551aa56f49dab9ab9108269b03c557496c54acaf41f98e2b8d6"
http_archive(
    name = "rules_kotlin",
    urls = ["https://github.com/bazelbuild/rules_kotlin/releases/download/v%s/rules_kotlin-v%s.tar.gz" % (rules_kotlin_version, rules_kotlin_version)],
    sha256 = rules_kotlin_sha,
)

load("@rules_kotlin//kotlin:repositories.bzl", "kotlin_repositories")
kotlin_repositories() # if you want the default. Otherwise see custom kotlinc distribution below

load("@rules_kotlin//kotlin:core.bzl", "kt_register_toolchains")
kt_register_toolchains() # to use the default toolchain, otherwise see toolchains below

BUILD files

In your project's BUILD files, load the Kotlin rules and use them like so:

load("@rules_kotlin//kotlin:jvm.bzl", "kt_jvm_library")

kt_jvm_library(
    name = "package_name",
    srcs = glob(["*.kt"]),
    deps = [
        "//path/to/dependency",
    ],
)

Custom toolchain

To enable a custom toolchain (to configure language level, etc.) do the following. In a <workspace>/BUILD.bazel file define the following:

load("@rules_kotlin//kotlin:core.bzl", "define_kt_toolchain")

define_kt_toolchain(
    name = "kotlin_toolchain",
    api_version = KOTLIN_LANGUAGE_LEVEL,  # "1.1", "1.2", "1.3", "1.4", "1.5" "1.6", "1.7", "1.8", or "1.9"
    jvm_target = JAVA_LANGUAGE_LEVEL, # "1.6", "1.8", "9", "10", "11", "12", "13", "15", "16", "17", "18", "19", "20" or "21"
    language_version = KOTLIN_LANGUAGE_LEVEL,  # "1.1", "1.2", "1.3", "1.4", "1.5" "1.6", "1.7", "1.8", or "1.9"
)

and then in your WORKSPACE file, instead of kt_register_toolchains() do

register_toolchains("//:kotlin_toolchain")

Custom kotlinc distribution (and version)

To choose a different kotlinc distribution (1.3 and 1.4 variants supported), do the following in your WORKSPACE file (or import from a .bzl file:

load("@rules_kotlin//kotlin:repositories.bzl", "kotlin_repositories", "kotlinc_version")

kotlin_repositories(
    compiler_release = kotlinc_version(
        release = "1.6.21", # just the numeric version
        sha256 = "632166fed89f3f430482f5aa07f2e20b923b72ef688c8f5a7df3aa1502c6d8ba"
    )
)

Third party dependencies

(e.g. Maven artifacts)

Third party (external) artifacts can be brought in with systems such as rules_jvm_external or bazel_maven_repository or bazel-deps, but make sure the version you use doesn't naively use java_import, as this will cause bazel to make an interface-only (ijar), or ABI jar, and the native ijar tool does not know about kotlin metadata with respect to inlined functions, and will remove method bodies inappropriately. Recent versions of rules_jvm_external and bazel_maven_repository are known to work with Kotlin.

Development Setup Guide

As of 1.5.0, to use the rules directly from the rules_kotlin workspace (i.e. not the release artifact) require the use of release_archive repository. This repository will build and configure the current workspace to use rules_kotlin in the same manner as the released binary artifact.

In the project's WORKSPACE, change the setup:

# Use local check-out of repo rules (or a commit-archive from github via http_archive or git_repository)
local_repository(
    name = "rules_kotlin",
    path = "../path/to/rules_kotlin_clone/",
)

load("@rules_kotlin//kotlin:dependencies.bzl", "kt_download_local_dev_dependencies")

kt_download_local_dev_dependencies()

load("@rules_kotlin//kotlin:repositories.bzl", "kotlin_repositories", "versions")

kotlin_repositories()

load("@rules_kotlin//kotlin:core.bzl", "kt_register_toolchains")

kt_register_toolchains()

To use rules_kotlin from head without cloning the repository, (caveat emptor, of course), change the rules to this:

# Download master or specific revisions
http_archive(
    name = "rules_kotlin",
    strip_prefix = "rules_kotlin-master",
    urls = ["https://github.com/bazelbuild/rules_kotlin/archive/refs/heads/master.zip"],
)

load("@rules_kotlin//kotlin:repositories.bzl", "kotlin_repositories")

kotlin_repositories()

load("@rules_kotlin//kotlin:core.bzl", "kt_register_toolchains")

kt_register_toolchains()

Debugging native actions

To attach debugger and step through native action code when using local checkout of rules_kotlin repo :

  1. Open rules_kotlin project in Android Studio, using existing .bazelproject file as project view.
  2. In terminal, build the kotlin target you want to debug, using the subcommand option, ex: bazel build //lib/mylib:main_kt -s. You can also use bazel aquery to get this info.
  3. Locate the subcommand for the kotlin action you want to debug, let's say KotlinCompile. Note: If you don't see it, target rebuild may have been skipped (in this case touch one of the source .kt file to trigger rebuild).
  4. Export REPOSITORY_NAME as specified in action env, ex : export REPOSITORY_NAME=rules_kotlin
  5. Copy the command line, ex : bazel-out/darwin_arm64-opt-exec-2B5CBBC6/bin/external/rules_kotlin/src/main/kotlin/build '--flagfile=bazel-out/darwin_arm64-fastbuild/bin/lib/mylib/main_kt-kt.jar-0.params'
  6. Change directory into the execRoot, normally bazel-MYPROJECT, available via bazel info | grep execution_root.
  7. Add --debug=5005 to command line to make the action wait for a debugger to attach, ex: bazel-out/darwin_arm64-opt-exec-2B5CBBC6/bin/external/rules_kotlin/src/main/kotlin/build --debug=5005 '--flagfile=bazel-out/darwin_arm64-fastbuild/bin/lib/mylib/main_kt-kt.jar-0.params'. Note: if command invokes java toolchain directly, use -agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=5005 instead.
  8. You should see in output that action is waiting for debugger. Use a default Remote JVM Debug configuration in Android Studio, set breakpoint in kotlin action java/kt code, and attach debugger. Breakpoints should be hit.

Kotlin and Java compiler flags

The kt_kotlinc_options and kt_javac_options rules allows passing compiler flags to kotlinc and javac.

Note: Not all compiler flags are supported in all language versions. When this happens, the rules will fail.

For example you can define global compiler flags by doing:

load("@rules_kotlin//kotlin:core.bzl", "kt_kotlinc_options", "kt_javac_options", "define_kt_toolchain")

kt_kotlinc_options(
    name = "kt_kotlinc_options",
    x_no_param_assertions = True,
    jvm_target = "1.8",
)

kt_javac_options(
    name = "kt_javac_options",
    warn = "off",
)

define_kt_toolchain(
    name = "kotlin_toolchain",
    kotlinc_options = "//:kt_kotlinc_options",
    javac_options = "//:kt_javac_options",
)

You can optionally override compiler flags at the target level by providing an alternative set of kt_kotlinc_options or kt_javac_options in your target definitions.

Compiler flags that are passed to the rule definitions will be taken over the toolchain definition.

Example:

load("@rules_kotlin//kotlin:core.bzl", "kt_kotlinc_options", "kt_javac_options")
load("@rules_kotlin//kotlin:jvm.bzl", "kt_jvm_library")

kt_kotlinc_options(
    name = "kt_kotlinc_options_for_package_name",
    x_no_param_assertions = True,
    x_optin = [
        "kotlin.Experimental",
        "kotlin.ExperimentalStdlibApi",
    ],
)

kt_javac_options(
    name = "kt_javac_options_for_package_name",
    warn = "off"
)

kt_jvm_library(
    name = "package_name",
    srcs = glob(["*.kt"]),
    kotlinc_opts = "//:kt_kotlinc_options_for_package_name",
    javac_opts = "//:kt_javac_options_for_package_name",
    deps = ["//path/to/dependency"],
)

Additionally, you can add options for both tracing and timing of the bazel build using the kt_trace and kt_timings flags, for example:

  • bazel build --define=kt_trace=1
  • bazel build --define=kt_timings=1

kt_trace=1 will allow you to inspect the full kotlinc commandline invocation, while kt_timings=1 will report the high level time taken for each step.

KSP (Kotlin Symbol Processing)

KSP is officially supported as of rules_kotlin 1.8 and can be declared using the new kt_ksp_plugin rule.

A few things to note:

  • As of now rules_kotlin only supports KSP plugins that generate Kotlin code.
  • KSP is not yet thread safe and will likely fail if you are using it in a build that has multiplex workers enabled. To work around this add the following flag to your Bazelrc:
    build --experimental_worker_max_multiplex_instances=KotlinKsp=1
    
load("@rules_kotlin//kotlin:core.bzl", "kt_ksp_plugin")
load("@rules_kotlin//kotlin:jvm.bzl", "kt_jvm_library")

kt_ksp_plugin(
    name = "moshi-kotlin-codegen",
    processor_class = "com.squareup.moshi.kotlin.codegen.ksp.JsonClassSymbolProcessorProvider",
    deps = [
        "@maven//:com_squareup_moshi_moshi",
        "@maven//:com_squareup_moshi_moshi_kotlin",
        "@maven//:com_squareup_moshi_moshi_kotlin_codegen",
    ],
)

kt_jvm_library(
    name = "lib",
    srcs = glob(["*.kt"]),
    plugins = ["//:moshi-kotlin-codegen"],
)

To choose a different ksp_version distribution, do the following in your WORKSPACE file (or import from a .bzl file):

load("@rules_kotlin//kotlin:repositories.bzl", "kotlin_repositories", "ksp_version")

kotlin_repositories(
    ksp_compiler_release = ksp_version(
        release = "1.8.22-1.0.11",
        sha256 = "2ce5a08fddd20ef07ac051615905453fe08c3ba3ce5afa5dc43a9b77aa64507d",
    ),
)

Kotlin compiler plugins

The kt_compiler_plugin rule allows running Kotlin compiler plugins, such as no-arg, sam-with-receiver and allopen.

For example, you can add allopen to your project like this:

load("@rules_kotlin//kotlin:core.bzl", "kt_compiler_plugin")
load("@rules_kotlin//kotlin:jvm.bzl", "kt_jvm_library")

kt_compiler_plugin(
    name = "open_for_testing_plugin",
    id = "org.jetbrains.kotlin.allopen",
    options = {
        "annotation": "plugin.allopen.OpenForTesting",
    },
    deps = [
        "//kotlin/compiler:allopen-compiler-plugin",
    ],
)

kt_jvm_library(
    name = "user",
    srcs = ["User.kt"], # The User class is annotated with OpenForTesting
    plugins = [
        ":open_for_testing_plugin",
    ],
    deps = [
        ":open_for_testing", # This contains the annotation (plugin.allopen.OpenForTesting)
    ],
)

Full examples of using compiler plugins can be found here.

Examples

Examples can be found in the examples directory, including usage with Android, Dagger, Node-JS, Kotlin compiler plugins, etc.

History

These rules were initially forked from pubref/rules_kotlin, and then re-forked from bazelbuild/rules_kotlin. They were merged back into this repository in October, 2019.

License

This project is licensed under the Apache 2.0 license, as are all contributions

Contributing

See the CONTRIBUTING doc for information about how to contribute to this project.

rules_kotlin's People

Contributors

alexeagle avatar arunkumar9t2 avatar bencodes avatar buchgr avatar cgruber avatar comius avatar davidstanke avatar fmeum avatar git-str avatar hanneskaeufler avatar hsyed avatar illicitonion avatar jeffzoch avatar jongerrish avatar justhecuke-zz avatar kernald avatar mai93 avatar mauriciogg avatar nkoroste avatar oliviernotteghem avatar pettermahlen avatar philwo avatar pswaminathan avatar puffnfresh avatar raghulvelusamy avatar restingbull avatar rockwotj avatar szinn avatar utzcoz avatar xingao267 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

rules_kotlin's Issues

Please move from native to Skylark rules for external git/http repositories

Bazel is planning to move away from native rules for external repositories to Skylark rules, mainly because bundling every version control system in bazel does not scale. As part of this effort, we plan to submit https://bazel-review.googlesource.com/c/bazel/+/55932 soon, which will cause bazel by default to insist that the skylark versions the git and http rules for external repositories be used. This can be disabled by a flag for at least the next 6 months, but we still would appreciate if you could adopt your repository to use the Skylark versions of those rules soon.

A test run of downstream projects with that flag flip in bazel enabled can be found at https://buildkite.com/bazel/bazel-with-downstream-projects-bazel/builds/286

For more background, see

Thanks.

Intellij/Bazel doesn't actually execute the kotlin rules when "build" is pressed

Not sure if this is an issue here or in the intellij integration, but:

Repro steps:

  1. Set up a project to use rules_kotlin per the readme instructions
  2. Import normally into intellij using "import bazel project"
  3. Press the build button (project builds normally and succeeds).
  4. Introduce a compile error into the kotlin code.
  5. Press build button
  6. Build from the command-line.

Symptoms:
After step 3, all looks well, the project is indexed and seems to build properly.
After step 5, the same exact results occur, even though there's a compiler error. The project seems to build properly.
After step 6, the build does fail, showing that at least the compiler is catching it when executed through blaze directly.

Note: Adding a java compile error to a java target in the project DOES result in a failed build through the intellij integration.

So it does seem to me that somehow the kotlin rules are not being executed even though they're part of the .bazelproject workspace definition.

I've tried this with //src/... or //src/main/kotlin/path/to/library:target specifications, and none of them work. The project definitely indexes fine, and intellij itself does (once the kotlin project config is set up) catch the error with its analyzers.

rules_kotlin breakage on Bazel CI

ERROR: /var/lib/buildkite-agent/builds/buildkite-worker-ubuntu1404-java8-w9pz-1/bazel-downstream-projects/rules_kotlin/tests/integrationtests/jvm/basic/BUILD:101:1: Couldn't build file tests/integrationtests/jvm/basic/test_friends_library.jar: Compiling Kotlin //tests/integrationtests/jvm/basic:test_friends_library { kt: 1, java: 0, srcjars: 0 } failed (Exit 1): builder failed: error executing command
--
ย  | (cd /var/lib/buildkite-agent/.cache/bazel/_bazel_buildkite-agent/39debe0ec575e8516eeb1a26933a8f6b/execroot/io_bazel_rules_kotlin && \
ย  | exec env - \
ย  | bazel-out/host/bin/external/io_bazel_rules_kotlin/kotlin/builder/builder '--flagfile=bazel-out/k8-fastbuild/bin/tests/integrationtests/jvm/basic/test_friends_library.jar-0.params')
ย  | ERROR: Worker threw uncaught exception with args: --flagfile=bazel-out/k8-fastbuild/bin/tests/integrationtests/jvm/basic/test_friends_library.jar-0.params
ย  | java.lang.IllegalStateException: unknown flag file format for bazel-out/k8-fastbuild/bin/tests/integrationtests/jvm/basic/test_friends_library.jar-0.params
ย  | at io.bazel.kotlin.builder.tasks.KotlinBuilder.execute(KotlinBuilder.kt:48)
ย  | at io.bazel.kotlin.builder.tasks.KotlinBuilder.apply(KotlinBuilder.kt:89)
ย  | at io.bazel.kotlin.builder.tasks.BazelWorker.runAsPersistentWorker(BazelWorker.kt:88)
ย  | at io.bazel.kotlin.builder.tasks.BazelWorker.apply(BazelWorker.kt:67)
ย  | at io.bazel.kotlin.builder.KotlinBuilderMain.main(KotlinBuilderMain.java:29)

14.04: https://buildkite.com/bazel/bazel-with-downstream-projects-bazel/builds/371#1464a8d4-1938-4f81-991e-94faa51dfc93
16.04: https://buildkite.com/bazel/bazel-with-downstream-projects-bazel/builds/371#feda06be-6a26-4b85-9fa0-535a74441ce7
macOS: https://buildkite.com/bazel/bazel-with-downstream-projects-bazel/builds/371#77a386ca-307a-443d-9b1a-fa74b427f993

Latest passing nightly was on Friday: https://buildkite.com/bazel/bazel-with-downstream-projects-bazel/builds/368

JDK 9: IllegalArgumentException: No enum constant com.sun.tools.javac.main.Option.BOOT_CLASS_PATH

Bazel at head uses JDK 9 as the default host_javabase, and rules_kotlin does not appear to be compatible with JDK 9.

bazel test //:all_tests
...
ERROR: /usr/local/google/home/cushon/src/rules_kotlin/examples/dagger/BUILD:39:1: Compiling 8 Kotlin source files to examples/dagger/coffee_lib.jar failed (Exit 2)
exception: java.lang.IllegalArgumentException: No enum constant com.sun.tools.javac.main.Option.BOOT_CLASS_PATH
	at java.base/java.lang.Enum.valueOf(Enum.java:240)
	at com.sun.tools.javac.main.Option.valueOf(Option.java:67)
	at org.jetbrains.kotlin.kapt3.base.util.Java9UtilsKt.putJavacOption(java9Utils.kt:30)
	at org.jetbrains.kotlin.kapt3.base.KaptContext.<init>(KaptContext.kt:75)
	at org.jetbrains.kotlin.kapt3.KaptContextForStubGeneration.<init>(KaptContextForStubGeneration.kt:43)
	at org.jetbrains.kotlin.kapt3.AbstractKapt3Extension.compileStubs(Kapt3Extension.kt:253)
	at org.jetbrains.kotlin.kapt3.AbstractKapt3Extension.generateStubs(Kapt3Extension.kt:204)
	at org.jetbrains.kotlin.kapt3.AbstractKapt3Extension.analysisCompleted(Kapt3Extension.kt:151)
	at org.jetbrains.kotlin.kapt3.ClasspathBasedKapt3Extension.analysisCompleted(Kapt3Extension.kt:93)
	at org.jetbrains.kotlin.cli.jvm.compiler.TopDownAnalyzerFacadeForJVM$analyzeFilesWithJavaIntegration$2.invoke(TopDownAnalyzerFacadeForJVM.kt:98)
	at org.jetbrains.kotlin.cli.jvm.compiler.TopDownAnalyzerFacadeForJVM.analyzeFilesWithJavaIntegration(TopDownAnalyzerFacadeForJVM.kt:116)
	at org.jetbrains.kotlin.cli.jvm.compiler.TopDownAnalyzerFacadeForJVM.analyzeFilesWithJavaIntegration$default(TopDownAnalyzerFacadeForJVM.kt:85)
	at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler$analyze$1.invoke(KotlinToJVMBytecodeCompiler.kt:370)
	at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler$analyze$1.invoke(KotlinToJVMBytecodeCompiler.kt:61)
	at org.jetbrains.kotlin.cli.common.messages.AnalyzerWithCompilerReport.analyzeAndReport(AnalyzerWithCompilerReport.kt:101)
	at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.analyze(KotlinToJVMBytecodeCompiler.kt:361)
	at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.analyzeAndGenerate(KotlinToJVMBytecodeCompiler.kt:343)
	at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.compileBunchOfSources(KotlinToJVMBytecodeCompiler.kt:242)
	at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:200)
	at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:51)
	at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.java:95)
	at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.java:50)
	at org.jetbrains.kotlin.cli.common.CLITool.exec(CLITool.kt:88)
	at io.bazel.kotlin.compiler.BazelK2JVMCompiler.exec(BazelK2JVMCompiler.kt:55)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.base/java.lang.reflect.Method.invoke(Method.java:564)
	at io.bazel.kotlin.builder.KotlinToolchain$TCModule$kotlincInvoker$1.compile(KotlinToolchain.kt:146)
	at io.bazel.kotlin.builder.mode.jvm.actions.DefaultKotlinCompiler.invokeCompilePhase(KotlinCompiler.kt:92)
	at io.bazel.kotlin.builder.mode.jvm.actions.DefaultKotlinCompiler.runAnnotationProcessor(KotlinCompiler.kt:51)
	at io.bazel.kotlin.builder.mode.jvm.DefaultKotlinJvmCompilationExecutor.runAnnotationProcessors(KotlinJvmCompilationExecutor.kt:69)
	at io.bazel.kotlin.builder.mode.jvm.DefaultKotlinJvmCompilationExecutor.compile(KotlinJvmCompilationExecutor.kt:54)
	at io.bazel.kotlin.builder.KotlinBuilder.doExecute(KotlinBuilder.kt:49)
	at io.bazel.kotlin.builder.KotlinBuilder.execute(KotlinBuilder.kt:36)
	at io.bazel.kotlin.builder.KotlinBuilder.execute(KotlinBuilder.kt:43)
	at io.bazel.kotlin.builder.KotlinBuilder.execute(KotlinBuilder.kt:39)
	at io.bazel.kotlin.builder.KotlinBuilder.apply(KotlinBuilder.kt:102)
	at io.bazel.kotlin.builder.BazelWorker.runAsPersistentWorker(BazelWorker.kt:105)
	at io.bazel.kotlin.builder.BazelWorker.apply(BazelWorker.kt:84)
	at io.bazel.kotlin.builder.KotlinBuilder$Companion.main(KotlinBuilder.kt:109)
	at io.bazel.kotlin.builder.KotlinBuilder.main(KotlinBuilder.kt)

kt_jvm_test should infer the test_class if unspecified.

If the rule is named FooTest and the test file is FooTest.java or FooTest.kt, and the test_class is unspecified, the test rule should just work out that the test_class is my.package.FooTest.

Note: it may be wrong if tests are specified differently in the .kt file, but that's totally fine, insofar as one can still override the test_class.

Switch rule naming scheme and start design docs

For the jvm rules the prefix will switch from kotlin_ to kt_jvm_.

I could add a macro layer for backwards compatibility but is there a point ? The intellij rules would also need to be updated.

@cgruber i am in agreement with all of the points you have raised. We should start a design doc in this repo. could you tabulate your email in a doc here , in design ?

In terms of in source docs I think rst (as used in rules_go) is appropriate. Much better cross referencing.

Anyhow I added kotlin_import and an internal kotlin_stdlib. Iโ€™ll move the latter to kt_stdlib as its used to declare the kotlin compiler jars. kotlin_import will go away i think, if we do need to keep it arround it will probably be multi-platform, should we shortened to kt_ ?

Please have a look at my issue on ijars in bazel core. If we can classify the jar type during ijar processing it will simplify the design of the skylark logic.

Port the documentation to RST (or fix skydoc).

The skydoc generation process is broken now that the rules are using newer features rule modelling features (declared providers etc).

Motivating points for ripping skydoc out:

  • I tried updating to the newer versions of skydoc which had PR's applied -- the newer versions of skydoc have various other changes applied (splitting out skylib etc).
  • The static code analysis lib used by skydoc is rudamentary and forces us to structure the rules in certain ways.
  • Extra moving parts

The documentation should be migrated to rst just like rules-go.

kotlin-compiler packages not found by IntelliJ

When I open the rules_kotlin repo itself, and go to a file which uses kotlin-compiler classes,
such as kotlin/builder/src/io/bazel/kotlin/compiler/BazelK2JVMCompiler.kt, IntelliJ fails to
resolve the import paths (see attached screenshot).

I'd like these to work, because it will help me find my way around and learn the APIs faster
when hacking on this project (to add kotlin-js support, as we discussed elsewhere).

I've played with this some, and I see the reference to the compiler as a dependency
in places like this.

I think the solution is to make it automatically included as a dependency in the generated .project/.blaze/modules/.workspace.iml module. However, I'm unsure of the proper way to go
about that.

Happy to hack on it some more, but I'd need pointers on how to proceed.

Thanks,
-- Chad

screen shot 2018-07-11 at 9 25 21 pm

`-sources.jar` not correctly packed and primary jar is not normalised.

  1. The sources jar contains the workspace prefixes.

Package the source.jar in the builder is one solution.

Kotlin code doesn't have to be placed in a java package directory so there isn't a simple heuristic for determining the location. I've adapter JarHelper from bazel core and created an instance of it that packages sources correctly, it looks for the package line in a Java or Kotlin file and places the file in the correct package in the jar.

  1. The primary jar is currently not normalised.

The jars are not normalised and every build of a jar invalidates downstream targets every time. Since the builder is creating the jar, the simplest solution is to use JarCreator from bazel core. The builder generated jar can be augmented in skylark using the singlejar tool. Would need to verify that normalisation is working correctly once the jar is merged.

Minimise or optimize use of javac.

Mixed-mode compilation (#3) makes use of javac instead of compiling java directly via kotlinc. This is because:

  1. Getting sensible error output.
    a) Sequencing the error output so that java errors come first -- Kotlin is compiled first.
    b) Kotlinc does not format the javac errors sensibly.
  2. Exceptions being thrown from the Kotlin compiler due to obscure class path issues. CP issues should not result in exceptions from the compiler, we are wrapping the CLI compiler so exceptions in this scenario are fatal conditions. The classpath issues were also quite obscure.

Mixed-mode compilation is intended for porting java packages to Kotlin. So optimising for this use-case isn't that high a priority. tools.jar is loaded into the Kotlin eager class loader as it's needed by kapt and often after annotation processing to compile generated Java files. Invoking javac from the Kotlin eager class loader makes a lot of sense. However, if we get Kotlin to compile generated java we wouldn't need to invoke javac at all

Android extensions support

I have a Gradle project that I want to move to Bazel. I've managed to make everything works but these rules don't seem to provide a way to integrate Android extensions, which the project I mentioned makes heavy use of. I was wondering whether the support already exists or whether it is in the roadmap.

I was also wondering if this is not in the roadmap, would a PR implementing this be welcomed?

Thanks in advance for your response.

Passing kotlinc options

I don't see any documentation around hooks into the Kotlin compiler. Specifically, I want to be able to pass -Xcoroutines=enable

Strategy for dealing with kotlin implicit deps (stdlibs) that are not managed by the rules.

Transitive deps generated by bazel-deps, pubref-maven etc will pull in kotlin stdlibs. These will be in the standard maven labelling namespace --e.g., org_jetbrains_kotlin_kotlin_stdlib_jdk8. If such standard labels are detected we could filter them out or we could fail. Failure makes the most sense.

Dep generators are designed with exclusions so it's straight forward for the user to filter them out.

Are there plans to make a kt_android_library rule?

The current rules seem to be limited to the jvm so they can't be used for building an Android lib. Is a kt_android_library rule something you want but haven't done yet, or is this not the right direction at all?

kt_android_library compilation step doesn't happen unless sources are depended on.

If I have a kt_android_library target a which is depended on by an android_binary target b (a <- b), then:

  1. bazel build //:a results in no compilation of sources
  2. bazel build //:a.aar results in no compilation of sources, and an empty classes.zip in the .aar file.
  3. bazel build //:b results in compilation of sources in a.

I'll try to whip up a repro case in a clean repo.

Create an example executing spek via junit4 runner or await support of a Jupiter runner

I'm trying to get Kotlin testing working on a Java project. I've tried using the rules_kotlin docs along with the java_test docs example here: https://docs.bazel.build/versions/master/be/java.html#java_test

and this example:
https://github.com/bazelbuild/bazel/blob/master/examples/java-native/src/test/java/com/example/myproject/BUILD

Below are the relevant build files:

https://github.com/ReduxJava/reduxjava/blob/bazel/WORKSPACE
https://github.com/ReduxJava/reduxjava/blob/bazel/reduxjava-api/BUILD
https://github.com/ReduxJava/reduxjava/blob/bazel/reduxjava/BUILD

And the resulting output:

$ bazel test //reduxjava:store_impl
ERROR: /Source/ReduxJava/reduxjava/reduxjava/BUILD:39:1: in kt_jvm_test rule //reduxjava:store_impl:


The following files have no generating action:
reduxjava/store_impl-sources.jar
ERROR: Analysis of target '//reduxjava:store_impl' failed; build aborted: Analysis of target '//reduxjava:store_impl' failed; build aborted
INFO: Elapsed time: 0.113s
FAILED: Build did NOT complete successfully (0 packages loaded)
ERROR: Couldn't start the build. Unable to run tests

I should mention that this is using Spek which requires a custom test runner for JUnit 4. I've also tried other kt_jvm_test configurations with different resultant errors, however I think those were improperly configured anyway.

  • Could we get some better documentation and examples for Kotlin rules?
  • Should they work the same way as the Java Rules, i.e. can I use those as reference?
  • Is there anything wrong with my build files which would result in the error output above?

Generate Dep files

Implement strict deps suggestions similar to what native java rules support.

Find a way to get rid of the`kt_kvm_import` rule.

I recently added kotlin_import and have it marked as experimental. This rule should not be needed. as java_import and java_library are sufficient to introduce jars into the workspace. The Ijar/hjar tools strips parts of the Kotlin ABI off thus breaking inlining. A workaround would be for the ABI tools to ignore Kotlin jars in the short term.

Proposal.

Support the most recent Kotlin compiler release only.

Currently the rules have a list of Kotlin compiler versions. There is no point to this. The rules offer no backward guarantee.

I'm going to make it so that the rules only support a single compiler version -- the most recent version. This user can override this but doing so at their own risk.

Add android example app to farm initial issues and for e2e testing.

Note:

Purpose:

  • End-to-End Tests for interaction with the native android rules.
  • Test app for validating the intellij and android studio plugins.
  • Farming issues with the rules that need to be made for android. This include discovering new macros that might be needed.

Must:

  • Exercise all appropriate rule orchestrations between the kt_jvm_* and the android rules.
  • Stay within the android SDK as much as possible, we don't add the entire universe as external (maven) deps -- if we need a lot of external deps we should consider bazel-deps or spotify/bazel-tools.
  • Use an external version of the android SDK --e.g., http_archive.
  • Wire up the android SDK in a way so that the recommended SDK version is used with the recommended Bazel version for CI testing -- in other words build flags, config settings and select.
  • (in addition to android studio) be compilable and navigable in intellij CE or ultimate, at least the Kotlin code.
  • Work without an IDE (this one might be obvious, but for all I know there is coupling with android studio).

Unable to load package for '@io_bazel_rules_kotlin//kotlin:kotlin.bzl': BUILD file not found on package path

When including the build rules like so in the WORKSPACE file (whether via a http zip archive or a git_repository):

http_archive(
    name = "io_bazel_rules_kotlin",
    urls = ["https://github.com/bazelbuild/rules_kotlin/archive/86bf70875361bcdce7fa8977cb60dcd389cb73a3.zip"],
)

And then using a simple BUILD file:

load("@io_bazel_rules_kotlin//kotlin:kotlin.bzl", "kt_library", "kt_jvm_library")

kt_library(
    name = "foo",
    srcs = glob(["src/main/kotlin/**/*.kt"]),
)

any use to load rules or bits from the .bzl files results in some variant of:

Skipping ':foo': error loading package '': Extension file not found. Unable to load package for '@io_bazel_rules_kotlin//kotlin:kotlin.bzl': BUILD file not found on package path

This is true whether trying to load the toolchain stuff, or directly use the kt_jvm_library.

Examining other bugs on other projects, it looks like BUILD file not found is basically just a "hey, this screwed up while we were loading it" with no further information provided. But I still can't make it work on a fresh project, empty WORKSPACE file (other than the kotlin_rules project load)

Transitive dependencies missing in compilation

This is reported in pubref/rules_kotlin#47 with no resolution, but I don't see any discussion in the context of the new fork. It seems pretty significant, so I thought I'd raise it. Apologies if it is discussed elsewhere and I missed it.

kt_jvm_library seems to omit transitive dependencies when compiling, requiring many more things to be declared as direct deps compared to java_library.

Here are some reproducers:
https://gist.github.com/jfancher/e56cdd806c3241177267c6542943c54d
https://gist.github.com/jfancher/d9db1a94277ae898aa3c0e6e2a1e3483

In both of these, bazel build //:third fails without adding :first as a dep, due to C0 not being on the compilation classpath. In both cases the equivalent Java code and java_library declarations would be fine.

Any plans or opportunities to improve this? Is it blocked on Skylark support? bazelbuild/bazel#4549 seems related but it's not clear to me whether there's a blocker for this simple use case or just more advanced Kotlin-specific features (it seems framed as the latter).

Mixed-Mode compilation - Compile Java and Kotlin in one pass in the worker.

The rules should be able to compile Java and Kotlin files in a single pass. Support has already been added, it needs to be further tested and refined. A lot of the work done for this is needed for annotation processing / kapt support.

Notes on implementation:

  • Java compilation only occurs when there is a Java source file present.

RFC:

* Workers creates a temp directory and compiles to that -- Is this ok to do ?

Todo:

  • Java compiler used by Kotlins prints out a pointless 1 java file compiled to to the console -- need to silence this without silencing anything else.
  • Verify warning and error reporting, the warnings and errors need to get to intellij / the console.
  • [ ] Mirror the compilation switches and classpath setup that is in use by the Java rules -- As far as Java compilation goes we should have same experience -- Whatever Linting is configured for Java core, it should work when Kotlin is compiling Java -- Could use help on this one as it will remain a bit low on my list of priorities. unrealistic

Unable to build basic Android project with kt_android_library

I've been trying to create an example Android project - more for my own reference than anything else - here: https://github.com/Pmcneice/AndroidBazelExample

It's a simple project - basically the default Android Studio project template - that contains a single .java activity and a single .kt activity. I hope to include KAPT and databinding examples in that project moving forward.

If I remove the Kotlin activity i can compile the project with this android_binary rule:

android_binary(
    name = "AndroidBazelExample",
    custom_package = PACKAGE,
    manifest = MANIFEST,
    srcs = glob(["src/main/java/**"]),
    resource_files = glob(["src/main/res/**"]),
    multidex = "native",
    dex_shards = 10,
    deps = [
        gmaven_artifact("androidx.appcompat:appcompat:aar:1.0.0-beta01"),
        gmaven_artifact("androidx.constraintlayout:constraintlayout:aar:1.1.2")
    ]
)

However, trying to compile with the following rules does not:

android_binary(
    name = "AndroidBazelExample",
    custom_package = PACKAGE,
    manifest = MANIFEST,
    multidex = "native",
    dex_shards = 10,
    deps = [
        "src"
    ]
)

kt_android_library(
    name = "src",
    custom_package = PACKAGE,
    manifest = MANIFEST,
    srcs = glob(["src/main/java/**"]),
    resource_files = glob(["src/main/res/**"]),
    deps = [
        gmaven_artifact("androidx.appcompat:appcompat:aar:1.0.0-beta01"),
        gmaven_artifact("androidx.constraintlayout:constraintlayout:aar:1.1.2")
    ]
)

Building with those rules always gives me an error about resources not found in the appcompat library. For example:

Error at 16 : /tmp/resource_validator_tmp2551691630083267333/tmp-expanded/res/values/values.xml:16: error: Error: No resource found that matches the given name: attr 'colorPrimaryDark'.

I've tried explicitly including the library dependencies and resources files in the android_library block just in case the dependencies of the kt_android_library block weren't being included but that gives me the same error.

Any ideas? I know there's some comments from @jin in #119 about some potential dependency issues but I wasn't sure if this was related or not?

Documentation strategy for this repo going forward.

Skydoc had a lot of problems and was becoming a major hinderance for this repo so it has been removed. A new documentation tool is in the works. I don't have any details for this but I think I will use it once it is available.

A lot of the internal and public elements of the rules are already documented but it is outdated. I suspect the new tool will work out of the box. However, this won't be the whole solution, design docs , usage tutorials and faqs cant all be inlined and extracted from the rules.

The go rules use rst for hand written documentation. I really like this approach. I have since discovered asciidoc it is functionally equivalent to rst as a better markdown but it is easier to work with (richer intellij plugin, simpler patterns and supported by github).

I wonder what output formats the new Skydoc tool will support. It would be nice to be able to weave the extracted documentation into technical documentation that is written in markdown / rst / asciidoc. It is quite valuable to have the rule contracts documented and browse-able via github without having to go to a separate website.

I'll make a start on some asciidoc -- but I need feedback on how heavily I should invest in it as I don't know what is on the horizon. The kotlin rules need a lot of documentation for users and developers alike so it's important to get to a stable documentation strategy. If you are working on bazel core, the new tool or have any insights please give your feedback.

aar as kt_jvm_library dependency

Hi. I want to compile Kotlin file with aar.

KotlinActivity.kt:

import android.support.v7.app.AppCompatActivity

class KotlinActivity : AppCompatActivity() {
}

Target:

java_import(
    name = "sdk",
    neverlink = 1,
    jars = ["//tools/defaults:android_jar"],
)

kt_jvm_library(
    name = main_kt,
    srcs = ["KotlinActivity.kt"],
    deps = ["@appcompat_v7//aar" + "sdk"],
 )

But when I build main_kt I got an error as this:

error: supertypes of the following classes cannot be resolved. Please make sure you have the required dependencies in the classpath:
    class android.support.v7.app.AppCompatActivity, unresolved supertypes: android.support.v4.app.FragmentActivity, android.support.v4.app.TaskStackBuilder.SupportParentable
    class android.support.v7.app.ActionBarDrawerToggle, unresolved supertypes: android.support.v4.widget.DrawerLayout.DrawerListener

I can achieve this using pubref's kotlin_android_library.

Is it possible to include aar as dependency for kt_jvm_library or maybe is there a replacement rule for pubref's kotlin_android_library?

Thanks.

0.12 and intellij plugin combo bug when using kt_jvm_import.

maven_jar in 0.11 and below produces build files that look like:

# DO NOT EDIT: automatically generated BUILD.bazel file for maven_jar rule org_jdbi_jdbi3_kotlin_sqlobject
java_import(
    name = 'jar',
    jars = ['jdbi3-kotlin-sqlobject-3.1.0.jar'],
    srcjar = 'jdbi3-kotlin-sqlobject-3.1.0-sources.jar',
    visibility = ['//visibility:public']
)

filegroup(
    name = 'file',
    srcs = [
        'jdbi3-kotlin-sqlobject-3.1.0.jar',
        'jdbi3-kotlin-sqlobject-3.1.0-sources.jar',
    ],
    visibility = ['//visibility:public']
)

in bazel 0.12 the srcjar seems to be missing.

bazel 0.12 java_common.create_provider does not accept source_jars as None and setting an empty list triggers a condition in the Intellij aspect processing when writing out files -- to_proto() fails when source_jars is empty.

JS Support

I have javascript compilation working, and support in the builder for it. Libs can depend on other local libs. But currently that is it (can't depend on node modules I think).

I am not a JS developer so I don't know what would and wouldn't be idiomatic. I need a JS developer as a client. I need a real world example app using JS modules, rules_nodes and local local Kotlin libraries being used in concert in the example directory.

@thewoolleyman do you want to be this guy ? I can push the existing work after tidying it up in a separate branch.

non-persistent worker race condition: missing external kotlin-compiler.jar

I seem to have gotten into a strange state that I am unable to find any resolution for.

When running bazel build //... I end up with the following missing kotlin compiler issue.

ERROR: /Users/zsiegel/src/github.com/my-app-folder/BUILD:45:1: Compiling Kotlin //:config { kt: 1, java: 0, srcjars: 0 } failed (Exit 1)
Exception in thread "main" java.lang.IllegalStateException: file did not exist: external/com_github_jetbrains_kotlin/lib/kotlin-compiler.jar
	at io.bazel.kotlin.builder.utils.IOUtils.verified(IOUtils.kt:74)
	at io.bazel.kotlin.builder.utils.IOUtils.resolveVerified(IOUtils.kt:69)
	at io.bazel.kotlin.builder.toolchain.KotlinToolchain$Companion.createClassLoader(KotlinToolchain.kt:52)
	at io.bazel.kotlin.builder.toolchain.KotlinToolchain$Companion.createToolchain(KotlinToolchain.kt:75)
	at io.bazel.kotlin.builder.toolchain.KotlinToolchain.createToolchain(KotlinToolchain.kt)
	at io.bazel.kotlin.builder.KotlinBuilderMain.main(KotlinBuilderMain.java:26)

This exact build seems to work on another machine but I am unable to track down why this issue is occurring on some machines. I have tried digging through the verbose outputs but I have no idea why this file might be missing.

Any ideas or thoughts on how to debug and resolve this?

Thanks

`kt_jvm_import` doesn't import all of a library's methods

I suspect this is a larger issue, but the current kt_jvm_import fails to import all of Arrow's methods.

I've published a minimal test case here:

https://github.com/Bakpax/bazel-arrow-kt

As far as I can tell, some of Arrow's methods are obscured behind typealias and an annotation (@higherkind). I can see that rules_kotlin will process annotations with kapt, but I think this information is lost somehow during a kt_jvm_import.

It would be great if there was a simple fix for this, but if there isn't, it would also be useful to know if/when this issue will get resolved, so we can plan accordingly.

Thanks for your help, we use rules_kotlin for all our kotlin code ๐Ÿ˜ƒ.

Kotlin 1.3 support

I tried to use these rules using the latest kotlin 1.3 release by manually setting kotlin repositories(compiler release={... }) It downloaded the compiler fine but then complained about a missing dependency. I am on my mobile now so unfortunately do not have the error message but will update once on my desktop tomorrow. Just wanted to report this in the meantime.

Fail to build on Windows

When I run bazel build //examples/dagger:coffee_app on Windows 10, it fails with the following error message: Error: Could not find or load main class org.jetbrains.kotlin.preloading.Preloader

I am running Bazel 0.10.1.

Annotation Processing

This needs some experimentation, notes:

  • Need an Aspect rule so that we can render an arbitrary java_plugin label into an abstract set of switches or preferably an encoded payload for the worker (bazel proto format ?).
    * Unless we can cache any of the results create a single set of temp directories for all annotation processors (src, classes and stubs). (RFC: Are temp directories OK ? also used in #3). (see #10).
  • If the compilers needs to be invoked twice (likely).
    • Expand sources to include generated sources.
    • Merge classes in a separate step if needed (likely).
  • RFC: look into what intellij aspects expect, if I remember correctly we need to declare the sources as a separate source jar, what about the stubs and classes ?
  • I knocked together a bit of a execution framework, a bit like the java builder. I can see the Kotlin worker becoming part of bazel core in the distant future. (RFC: Could we leverage the framework elements from the JavaBuilder, and / or potentially introduce Kotlin into the Worker ?)

Add android e2e test once native rules support it.

Once the native android rules have support for android remote android toolchains wire up an android example (#119) as an e2e test.

@jin added you to this issue as well -- I'll take care of this one once the native rules support non-local toolchains.

Beyond compiling and launching the example I don't think we need to test anything else since the integration is just a simple sandwich macro for now WDYT ? .

Design document for a `kt_library` rule.

I think before tackling JS we need a kt_library and have it fully working with the JVM rules.

Considering just the JVM aspect. A kt_library at the very least is a list of src files and it should be "somehow" be used in kt_jvm_library. Extending this to multiplatform a kt_library could be multiplatform. In which case to create a kt_jvm_library it would need srcs containing the JVM actual instances.

kt_library(
  name = "foo_api",
  srcs = glob(["api/*.kt"])
)

kt_jvm_library(
  name = "foo_jvm",
  expected_by = [ ":api" ] # should this be list or single ? 
  srcs = [ "jvm/*.kt" ]
)

Some questions:

  1. Is a kt_library always multiplatform -- can it be used just to group sources together --i.e., should it also be allowed in the srcs list of kt_jvm_library, kt_js_library ?.
  2. If a multiplatform library isn't always multiplatform do we need to explicetly mark it multiplatform or is this knowledge only required when compiling it --i.e., by virtue of being featured in the expected_by attribute ?
  3. What do the providers look like ?

Cannot run project with kotlin classes

I try run java project with kotlin files in android studio, but got error.

ERROR: /Users/olegBorisenkov/Desktop/examples-master/android/firebase-cloud-messaging/app/BUILD:10:1: Building app/libapp.jar (3 source files) failed (Exit 1).
app/src/main/java/com/example/myapplication/MainActivity.java:18: error: cannot find symbol
        new Test().Main();
            ^
  symbol:   class Test
  location: class MainActivity

2018-09-19 11 25 19

When I convert my Activity class from java to kotlin I don't see R class

2018-09-19 11 28 41

My BUILD File

load("@tools_android//tools/googleservices:defs.bzl", "google_services_xml")
load("@gmaven_rules//:defs.bzl", "gmaven_artifact")
load("@io_bazel_rules_kotlin//kotlin:kotlin.bzl", "kt_jvm_library")

GOOGLE_SERVICES_XML = google_services_xml(
    package_name = "com.example.myapplication",
    google_services_json = "google-services.json"
)

android_binary(
    name = "app",
    srcs = glob(["src/main/java/**/*.java"]),
    manifest = "src/main/AndroidManifest.xml",
    resource_files = glob(["src/main/res/**"]),

    # this sets the java package for the R class, since this android_binary
    # rule isn't under a java root (i.e., some directory named "java" for the
    # root of the java code for the app).
    custom_package = "com.example.myapplication",

    deps = [


        gmaven_artifact("com.google.firebase:firebase_messaging:aar:17.0.0"),
        gmaven_artifact("com.google.firebase:firebase_iid:aar:16.0.0"),
        gmaven_artifact("com.android.support:appcompat_v7:aar:26.1.0"),
        gmaven_artifact("com.android.support.constraint:constraint_layout:aar:1.0.2"),
        "@com_google_guava_guava//jar",
        #"@com_android_volley_volley//jar"

    ],
    manifest_values = {
      "minSdkVersion": "21",
      "applicationId": "com.example.myapplication",
    }
)

My WORKSPACE File


android_sdk_repository(
	name = "androidsdk",
	api_level = 28,
	# Replace with path to Android SDK on your system
	path = "/Users/olegBorisenkov/Library/Android/sdk/",
)


GMAVEN_TAG = "20180530-1"
http_archive(
    name = "gmaven_rules",
    strip_prefix = "gmaven_rules-%s" % GMAVEN_TAG,
    url = "https://github.com/bazelbuild/gmaven_rules/archive/%s.tar.gz" % GMAVEN_TAG,
)


load("@gmaven_rules//:gmaven.bzl", "gmaven_rules")
gmaven_rules()

TOOLS_ANDROID_COMMIT = "0e864ba5a86958513658250de587416d8e17c481"
http_archive(
  name = "tools_android",
  strip_prefix = "tools_android-" + TOOLS_ANDROID_COMMIT,
  url = "https://github.com/bazelbuild/tools_android/archive/%s.tar.gz" % TOOLS_ANDROID_COMMIT,
)
load("@tools_android//tools/googleservices:defs.bzl", "google_services_workspace_dependencies")
google_services_workspace_dependencies()


maven_jar(
    name = "com_google_guava_guava",
    artifact = "com.google.guava:guava:18.0"
)

maven_jar(
    name = "com_android_volley_volley",
    artifact = "com.android.volley:volley:1.1.0"
)



rules_kotlin_version = "67f4a6050584730ebae7f8a40435a209f8e0b48e"

http_archive(
    name = "io_bazel_rules_kotlin",
    urls = ["https://github.com/bazelbuild/rules_kotlin/archive/%s.zip" % rules_kotlin_version],
    type = "zip",
    strip_prefix = "rules_kotlin-%s" % rules_kotlin_version
)

load("@io_bazel_rules_kotlin//kotlin:kotlin.bzl", "kotlin_repositories", "kt_register_toolchains")
kotlin_repositories()
kt_register_toolchains()

Quastion kapt kotlin in bazel

In gradle I use Realm and Dagge librar library. These library require using kapt annotation for generate their classes. How I can in Bazel use this annotations?

Working with kt_jvm_binary

I see in the docs:

Note: This rule does not have all of the features found in java_binary. It is appropriate for building workspace utilities. java_binary should be preferred for release artefacts.

But it's not exactly clear what this means or what the preferred strategy is.


I have a code generation task written in Kotlin. I tried to use kt_jvm_binary along with genrule, but when running with bazel build //my_genrule I get a No such file or directory from bash.

# DOES NOT WORK
# Error: /bin/bash: bazel-out/host/bin/kt_bin: No such file or directory

kt_jvm_binary(
    main_class = "MainKt",
    name = "kt_bin",
    srcs = glob(["src/main/kotlin/**"]),
    resources = glob(["src/main/resources/**"]),
    deps = [
        ...
    ],
)

genrule(
        name = "some_genrule",
        tools = [":kt_bin"],
        cmd = "$(location :kt_bin) $(@D)",
        outs = [
                ...
        ],
)

My solution is to use kt_jvm_library + java_binary + genrule, where the java_binary is just a wrapper around the lib:

# DOES WORK!

kt_jvm_library(
    name = "kt_lib",
    srcs = glob(["src/main/kotlin/**"]),
    resources = glob(["src/main/resources/**"]),
    deps = [
        ...
    ],
)

java_binary(
        name = "java_bin",
        main_class = "MainKt",
        runtime_deps = [":kt_lib",],
)

genrule(
        name = "some_genrule",
        tools = [":java_bin"],
        cmd = "$(location :java_bin) $(@D)",
        outs = [
                ...
        ],
)

Is this expected?

expand the plugin classpath to include runtime_deps

The plugin aspect isn't including transitive runtime deps --i.e., currently you have to do:

java_plugin(
    name = "auto_factory_plugin",
    generates_api = 1,
    output_licenses = ["unencumbered"],
    processor_class = "com.google.auto.factory.processor.AutoFactoryProcessor",
    deps = [
        "//third_party/jvm/com/google/auto/factory:auto_factory",
        # should be picked up  runtime_deps from auto_factory
        "//third_party/jvm/com/google/auto:auto_common",
        "//third_party/jvm/com/google/auto/value:auto_value",
        "//third_party/jvm/com/google/googlejavaformat:google_java_format",
        "//third_party/jvm/com/google/guava",
        "//third_party/jvm/com/squareup:javapoet",
        "//third_party/jvm/javax/inject:javax_inject",
    ],
)

java_library(
    name = "auto_factory",
    exported_plugins = [":auto_factory_plugin"],
    exports = [":auto_factory_plugin"],
    neverlink = 1
)

Add representative Android example.

Android support has been added and the branch temp_android_example has an example from the android tutorial. This issue is for an example that demonstrates how to lay out an android project. There are no tests for android (see for blocker).

The macro routes srcs, deps and pluginsto kt_jvm_library so It would be good if the example could also use a java plugin --e.g., dagger.

Once the android rules have been updated then we can add tests that check if the example compiles and launches correctly.

Implicit dependency issue

I think something is wrong with my setup, any help would be appreciated. I get this error when I try to build my Kotlin targets:

INFO: SHA256 (https://github.com/bazelbuild/rules_kotlin/archive/c56299c32437cf9608612868beb1c2ba9386940d.zip) = 160e06a8d0a32b07b1c8ec4c88c9fd42988c3a4d4ba43776a87dbba99634f67e
ERROR: /Users/menny/dev/spotify/client-android/bazel/transformer/BUILD.bazel:17:1: every rule of type kt_jvm_binary implicitly depends upon the target '@com_github_jetbrains_kotlin//:kotlin-runtime', but this target could not be found because of: no such package '@com_github_jetbrains_kotlin//': Traceback (most recent call last):
	File "/private/var/tmp/_bazel_menny/abbd8cf9e5bbd5870afa5547369aa515/external/bazel_tools/tools/build_defs/repo/http.bzl", line 56
		workspace_and_buildfile(ctx)
	File "/private/var/tmp/_bazel_menny/abbd8cf9e5bbd5870afa5547369aa515/external/bazel_tools/tools/build_defs/repo/utils.bzl", line 59, in workspace_and_buildfile
		ctx.symlink(ctx.attr.build_file, "BUILD.bazel")
Unable to load package for //kotlin/internal/repositories:BUILD.com_github_jetbrains_kotlin: not found.
ERROR: Analysis of target '//bazel/transformer:transformer' failed; build aborted: no such package '@com_github_jetbrains_kotlin//': Traceback (most recent call last):
	File "/private/var/tmp/_bazel_menny/abbd8cf9e5bbd5870afa5547369aa515/external/bazel_tools/tools/build_defs/repo/http.bzl", line 56
		workspace_and_buildfile(ctx)
	File "/private/var/tmp/_bazel_menny/abbd8cf9e5bbd5870afa5547369aa515/external/bazel_tools/tools/build_defs/repo/utils.bzl", line 59, in workspace_and_buildfile
		ctx.symlink(ctx.attr.build_file, "BUILD.bazel")
Unable to load package for //kotlin/internal/repositories:BUILD.com_github_jetbrains_kotlin: not found.
INFO: Elapsed time: 6.004s
INFO: 0 processes.
FAILED: Build did NOT complete successfully (10 packages loaded)
FAILED: Build did NOT complete successfully (10 packages loaded)

In my WORKSPACE file I've setup Kotlin like this:

rules_kotlin_version = "c56299c32437cf9608612868beb1c2ba9386940d"

http_archive(
    name = "io_bazel_rules_kotlin",
    urls = ["https://github.com/bazelbuild/rules_kotlin/archive/%s.zip" % rules_kotlin_version],
    type = "zip",
    strip_prefix = "rules_kotlin-%s" % rules_kotlin_version
)

load("@io_bazel_rules_kotlin//kotlin:kotlin.bzl", "kotlin_repositories", "kt_register_toolchains")
kotlin_repositories()
kt_register_toolchains()

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.