android_configure.bzl 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. """Repository rule for Android SDK and NDK autoconfiguration.
  2. This rule is a no-op unless the required android environment variables are set.
  3. """
  4. # Based on https://github.com/tensorflow/tensorflow/tree/34c03ed67692eb76cb3399cebca50ea8bcde064c/third_party/android
  5. # Workaround for https://github.com/bazelbuild/bazel/issues/14260
  6. _ANDROID_NDK_HOME = "ANDROID_NDK_HOME"
  7. _ANDROID_SDK_HOME = "ANDROID_HOME"
  8. def _escape_for_windows(path):
  9. """Properly escape backslashes for Windows.
  10. Ideally, we would do this conditionally, but there is seemingly no way to
  11. determine whether or not this is being called from Windows.
  12. """
  13. return path.replace("\\", "\\\\")
  14. def _android_autoconf_impl(repository_ctx):
  15. sdk_home = repository_ctx.os.environ.get(_ANDROID_SDK_HOME)
  16. ndk_home = repository_ctx.os.environ.get(_ANDROID_NDK_HOME)
  17. # version 31.0.0 won't work https://stackoverflow.com/a/68036845
  18. sdk_rule = ""
  19. if sdk_home:
  20. sdk_rule = """
  21. native.android_sdk_repository(
  22. name="androidsdk",
  23. path="{}",
  24. build_tools_version="30.0.3",
  25. )
  26. """.format(_escape_for_windows(sdk_home))
  27. # Note that Bazel does not support NDK 22 yet, and Bazel 3.7.1 only
  28. # supports up to API level 29 for NDK 21
  29. ndk_rule = ""
  30. if ndk_home:
  31. ndk_rule = """
  32. native.android_ndk_repository(
  33. name="androidndk",
  34. path="{}",
  35. )
  36. """.format(_escape_for_windows(ndk_home))
  37. if ndk_rule == "" and sdk_rule == "":
  38. sdk_rule = "pass"
  39. repository_ctx.file("BUILD.bazel", "")
  40. repository_ctx.file("android_configure.bzl", """
  41. def android_workspace():
  42. {}
  43. {}
  44. """.format(sdk_rule, ndk_rule))
  45. android_configure = repository_rule(
  46. implementation = _android_autoconf_impl,
  47. environ = [
  48. _ANDROID_NDK_HOME,
  49. _ANDROID_SDK_HOME,
  50. ],
  51. )