Extract utility methods used in the loading phase from `impl/java_helper.bzl` into a separate bzl file Methods used only by a single other load-affecting bzl file are inlined there instead. This way `impl/java_helper.bzl` is only loaded from bzl files used during rule implementations and should not be needed for the loading-phase, so making changes to this file don't invalidate the results of `blaze query`[^1]. PiperOrigin-RevId: 838701557 Change-Id: If462c46b1b8f2e5be12322a8af7d1a27e392bdfd
diff --git a/java/common/rules/BUILD b/java/common/rules/BUILD index 1200638..5bb5c2f 100644 --- a/java/common/rules/BUILD +++ b/java/common/rules/BUILD
@@ -26,6 +26,12 @@ ) bzl_library( + name = "java_helper_bzl", + srcs = ["java_helper.bzl"], + visibility = ["//java:__subpackages__"], +) + +bzl_library( name = "core_rules", srcs = [ "basic_java_library.bzl", @@ -58,6 +64,15 @@ "//java:__subpackages__", "@compatibility_proxy//:__pkg__", ], + deps = [ + ":java_helper_bzl", + "//java/common:semantics_bzl", + "//java/private:boot_class_path_info_bzl", + "//java/private:java_info_bzl", + "//java/private:native_bzl", + "@bazel_skylib//lib:paths", + "@rules_cc//cc/common", + ], ) filegroup(
diff --git a/java/common/rules/impl/BUILD b/java/common/rules/impl/BUILD index aead373..70adecc 100644 --- a/java/common/rules/impl/BUILD +++ b/java/common/rules/impl/BUILD
@@ -30,6 +30,13 @@ name = "java_helper_bzl", srcs = ["java_helper.bzl"], visibility = ["//java:__subpackages__"], + deps = [ + "//java/common:semantics_bzl", + "//java/common/rules:java_helper_bzl", + "@bazel_skylib//lib:paths", + "@rules_cc//cc:find_cc_toolchain_bzl", + "@rules_cc//cc/common", + ], ) filegroup(
diff --git a/java/common/rules/impl/java_helper.bzl b/java/common/rules/impl/java_helper.bzl index d54c8f6..0667ee4 100644 --- a/java/common/rules/impl/java_helper.bzl +++ b/java/common/rules/impl/java_helper.bzl
@@ -12,12 +12,13 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""Common util functions for java_* rules""" +"""Common util functions for java_* rules implementations""" load("@bazel_skylib//lib:paths.bzl", "paths") load("@rules_cc//cc:find_cc_toolchain.bzl", "find_cc_toolchain") load("@rules_cc//cc/common:cc_common.bzl", "cc_common") load("//java/common:java_semantics.bzl", "semantics") +load("//java/common/rules:java_helper.bzl", _loading_phase_helper = "helper") # copybara: rules_java visibility @@ -93,7 +94,7 @@ for src in ctx.files.srcs: if src.basename == main: return _full_classname(_strip_extension(src)) - return _full_classname(_get_relative(ctx.label.package, ctx.label.name)) + return _full_classname(helper.get_relative(ctx.label.package, ctx.label.name)) def _strip_extension(file): return file.dirname + "/" + ( @@ -102,41 +103,9 @@ # TODO(b/193629418): once out of builtins, create a canonical implementation and remove duplicates in depot def _full_classname(path): - java_segments = _java_segments(path) + java_segments = _loading_phase_helper.java_segments(path) return ".".join(java_segments) if java_segments != None else None -def _java_segments(path): - if path.startswith("/"): - fail("path must not be absolute: '%s'" % path) - segments = path.split("/") - root_idx = -1 - for idx, segment in enumerate(segments): - if segment in ["java", "javatests", "src", "testsrc"]: - root_idx = idx - break - if root_idx < 0: - return None - is_src = "src" == segments[root_idx] - check_mvn_idx = root_idx if is_src else -1 - if (root_idx == 0 or is_src): - for i in range(root_idx + 1, len(segments) - 1): - segment = segments[i] - if "src" == segment or (is_src and (segment in ["java", "javatests"])): - next = segments[i + 1] - if next in ["com", "org", "net"]: - root_idx = i - elif "src" == segment: - check_mvn_idx = i - break - - if check_mvn_idx >= 0 and check_mvn_idx < len(segments) - 2: - next = segments[check_mvn_idx + 1] - if next in ["main", "test"]: - next = segments[check_mvn_idx + 2] - if next in ["java", "resources"]: - root_idx = check_mvn_idx + 2 - return segments[(root_idx + 1):] - def _concat(*lists): result = [] for list in lists: @@ -250,19 +219,8 @@ java_executable = ctx.workspace_name + "/" + java_executable return paths.normalize(java_executable) -def _has_target_constraints(ctx, constraints): - # Constraints is a label_list. - for constraint in constraints: - constraint_value = constraint[platform_common.ConstraintValueInfo] - if ctx.target_platform_has_constraint(constraint_value): - return True - return False - -def _is_target_platform_windows(ctx): - return _has_target_constraints(ctx, ctx.attr._windows_constraints) - def _is_absolute_target_platform_path(ctx, path): - if _is_target_platform_windows(ctx): + if helper.is_target_platform_windows(ctx): return len(path) > 2 and path[1] == ":" return path.startswith("/") @@ -274,139 +232,6 @@ return ctx.attr._test_support return None -def _resource_mapper(file): - root_relative_path = paths.relativize( - path = file.path, - start = paths.join(file.root.path, file.owner.workspace_root), - ) - return "%s:%s" % ( - file.path, - semantics.get_default_resource_path(root_relative_path, segment_extractor = _java_segments), - ) - -def _create_single_jar( - actions, - toolchain, - output, - sources = depset(), - resources = depset(), - mnemonic = "JavaSingleJar", - progress_message = "Building singlejar jar %{output}", - build_target = None, - output_creator = None): - """Register singlejar action for the output jar. - - Args: - actions: (actions) ctx.actions - toolchain: (JavaToolchainInfo) The java toolchain - output: (File) Output file of the action. - sources: (depset[File]) The jar files to merge into the output jar. - resources: (depset[File]) The files to add to the output jar. - mnemonic: (str) The action identifier - progress_message: (str) The action progress message - build_target: (Label) The target label to stamp in the manifest. Optional. - output_creator: (str) The name of the tool to stamp in the manifest. Optional, - defaults to 'singlejar' - Returns: - (File) Output file which was used for registering the action. - """ - args = actions.args() - args.set_param_file_format("shell").use_param_file("@%s", use_always = True) - args.add("--output", output) - args.add_all( - [ - "--compression", - "--normalize", - "--exclude_build_data", - "--warn_duplicate_resources", - ], - ) - args.add_all("--sources", sources) - args.add_all("--resources", resources, map_each = _resource_mapper) - - args.add("--build_target", build_target) - args.add("--output_jar_creator", output_creator) - - actions.run( - mnemonic = mnemonic, - progress_message = progress_message, - executable = toolchain.single_jar, - toolchain = semantics.JAVA_TOOLCHAIN_TYPE, - inputs = depset(transitive = [resources, sources]), - tools = [toolchain.single_jar], - outputs = [output], - arguments = [args], - use_default_shell_env = True, - ) - return output - -# TODO(hvd): use skylib shell.quote() -def _shell_escape(s): - """Shell-escape a string - - Quotes a word so that it can be used, without further quoting, as an argument - (or part of an argument) in a shell command. - - Args: - s: (str) the string to escape - - Returns: - (str) the shell-escaped string - """ - if not s: - # Empty string is a special case: needs to be quoted to ensure that it - # gets treated as a separate argument. - return "''" - for c in s.elems(): - # We do this positively so as to be sure we don't inadvertently forget - # any unsafe characters. - if not c.isalnum() and c not in "@%-_+:,./": - return "'" + s.replace("'", "'\\''") + "'" - return s - -def _detokenize_javacopts(opts): - """Detokenizes a list of options to a depset. - - Args: - opts: ([str]) the javac options to detokenize - - Returns: - (depset[str]) depset of detokenized options - """ - return depset( - [" ".join([_shell_escape(opt) for opt in opts])], - order = "preorder", - ) - -def _derive_output_file(ctx, base_file, *, name_suffix = "", extension = None, extension_suffix = ""): - """Declares a new file whose name is derived from the given file - - This method allows appending a suffix to the name (before extension), changing - the extension or appending a suffix after the extension. The new file is declared - as a sibling of the given base file. At least one of the three options must be - specified. It is an error to specify both `extension` and `extension_suffix`. - - Args: - ctx: (RuleContext) the rule context. - base_file: (File) the file from which to derive the resultant file. - name_suffix: (str) Optional. The suffix to append to the name before the - extension. - extension: (str) Optional. The new extension to use (without '.'). By default, - the base_file's extension is used. - extension_suffix: (str) Optional. The suffix to append to the base_file's extension - - Returns: - (File) the derived file - """ - if not name_suffix and not extension_suffix and not extension: - fail("At least one of name_suffix, extension or extension_suffix is required") - if extension and extension_suffix: - fail("only one of extension or extension_suffix can be specified") - if extension == None: - extension = base_file.extension - new_basename = paths.replace_extension(base_file.basename, name_suffix + "." + extension + extension_suffix) - return ctx.actions.declare_file(new_basename, sibling = base_file) - def _is_stamping_enabled(ctx, stamp): if ctx.configuration.is_tool_configuration(): return 0 @@ -416,40 +241,6 @@ # stamp == -1 / auto return int(ctx.configuration.stamp_binaries()) -def _get_relative(path_a, path_b): - if paths.is_absolute(path_b): - return path_b - return paths.normalize(paths.join(path_a, path_b)) - -def _tokenize_javacopts(ctx = None, opts = []): - """Tokenizes a list or depset of options to a list. - - Iff opts is a depset, we reverse the flattened list to ensure right-most - duplicates are preserved in their correct position. - - If the ctx parameter is omitted, a slow, but pure Starlark, implementation - of shell tokenization is used. Otherwise, tokenization is performed using - ctx.tokenize() which has significantly better performance (up to 100x for - large options lists). - - Args: - ctx: (RuleContext|None) the rule context - opts: (depset[str]|[str]) the javac options to tokenize - Returns: - [str] list of tokenized options - """ - if hasattr(opts, "to_list"): - opts = reversed(opts.to_list()) - if ctx: - return [ - token - for opt in opts - for token in ctx.tokenize(opt) - ] - else: - # TODO: optimize and use the pure Starlark implementation in cc_helper - return semantics.tokenize_javacopts(opts) - helper = struct( collect_all_targets_as_deps = _collect_all_targets_as_deps, filter_launcher_for_target = _filter_launcher_for_target, @@ -466,15 +257,14 @@ get_coverage_config = _get_coverage_config, get_java_executable = _get_java_executable, is_absolute_target_platform_path = _is_absolute_target_platform_path, - is_target_platform_windows = _is_target_platform_windows, + is_target_platform_windows = _loading_phase_helper.is_target_platform_windows, runfiles_enabled = _runfiles_enabled, get_test_support = _get_test_support, - create_single_jar = _create_single_jar, - shell_escape = _shell_escape, - detokenize_javacopts = _detokenize_javacopts, - tokenize_javacopts = _tokenize_javacopts, - derive_output_file = _derive_output_file, + create_single_jar = _loading_phase_helper.create_single_jar, + shell_escape = _loading_phase_helper.shell_escape, + detokenize_javacopts = _loading_phase_helper.detokenize_javacopts, + tokenize_javacopts = _loading_phase_helper.tokenize_javacopts, is_stamping_enabled = _is_stamping_enabled, - get_relative = _get_relative, - has_target_constraints = _has_target_constraints, + get_relative = _loading_phase_helper.get_relative, + has_target_constraints = _loading_phase_helper.has_target_constraints, )
diff --git a/java/common/rules/java_helper.bzl b/java/common/rules/java_helper.bzl new file mode 100644 index 0000000..ee274ad --- /dev/null +++ b/java/common/rules/java_helper.bzl
@@ -0,0 +1,212 @@ +# Copyright 2025 The Bazel Authors. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Common util functions for java_* rules""" + +load("@bazel_skylib//lib:paths.bzl", "paths") +load("//java/common:java_semantics.bzl", "semantics") + +# copybara: rules_java visibility + +def _java_segments(path): + if path.startswith("/"): + fail("path must not be absolute: '%s'" % path) + segments = path.split("/") + root_idx = -1 + for idx, segment in enumerate(segments): + if segment in ["java", "javatests", "src", "testsrc"]: + root_idx = idx + break + if root_idx < 0: + return None + is_src = "src" == segments[root_idx] + check_mvn_idx = root_idx if is_src else -1 + if (root_idx == 0 or is_src): + for i in range(root_idx + 1, len(segments) - 1): + segment = segments[i] + if "src" == segment or (is_src and (segment in ["java", "javatests"])): + next = segments[i + 1] + if next in ["com", "org", "net"]: + root_idx = i + elif "src" == segment: + check_mvn_idx = i + break + + if check_mvn_idx >= 0 and check_mvn_idx < len(segments) - 2: + next = segments[check_mvn_idx + 1] + if next in ["main", "test"]: + next = segments[check_mvn_idx + 2] + if next in ["java", "resources"]: + root_idx = check_mvn_idx + 2 + return segments[(root_idx + 1):] + +def _has_target_constraints(ctx, constraints): + # Constraints is a label_list. + for constraint in constraints: + constraint_value = constraint[platform_common.ConstraintValueInfo] + if ctx.target_platform_has_constraint(constraint_value): + return True + return False + +def _is_target_platform_windows(ctx): + return _has_target_constraints(ctx, ctx.attr._windows_constraints) + +def _resource_mapper(file): + root_relative_path = paths.relativize( + path = file.path, + start = paths.join(file.root.path, file.owner.workspace_root), + ) + return "%s:%s" % ( + file.path, + semantics.get_default_resource_path(root_relative_path, segment_extractor = _java_segments), + ) + +def _create_single_jar( + actions, + toolchain, + output, + sources = depset(), + resources = depset(), + mnemonic = "JavaSingleJar", + progress_message = "Building singlejar jar %{output}", + build_target = None, + output_creator = None): + """Register singlejar action for the output jar. + + Args: + actions: (actions) ctx.actions + toolchain: (JavaToolchainInfo) The java toolchain + output: (File) Output file of the action. + sources: (depset[File]) The jar files to merge into the output jar. + resources: (depset[File]) The files to add to the output jar. + mnemonic: (str) The action identifier + progress_message: (str) The action progress message + build_target: (Label) The target label to stamp in the manifest. Optional. + output_creator: (str) The name of the tool to stamp in the manifest. Optional, + defaults to 'singlejar' + Returns: + (File) Output file which was used for registering the action. + """ + args = actions.args() + args.set_param_file_format("shell").use_param_file("@%s", use_always = True) + args.add("--output", output) + args.add_all( + [ + "--compression", + "--normalize", + "--exclude_build_data", + "--warn_duplicate_resources", + ], + ) + args.add_all("--sources", sources) + args.add_all("--resources", resources, map_each = _resource_mapper) + + args.add("--build_target", build_target) + args.add("--output_jar_creator", output_creator) + + actions.run( + mnemonic = mnemonic, + progress_message = progress_message, + executable = toolchain.single_jar, + toolchain = semantics.JAVA_TOOLCHAIN_TYPE, + inputs = depset(transitive = [resources, sources]), + tools = [toolchain.single_jar], + outputs = [output], + arguments = [args], + use_default_shell_env = True, + ) + return output + +# TODO(hvd): use skylib shell.quote() +def _shell_escape(s): + """Shell-escape a string + + Quotes a word so that it can be used, without further quoting, as an argument + (or part of an argument) in a shell command. + + Args: + s: (str) the string to escape + + Returns: + (str) the shell-escaped string + """ + if not s: + # Empty string is a special case: needs to be quoted to ensure that it + # gets treated as a separate argument. + return "''" + for c in s.elems(): + # We do this positively so as to be sure we don't inadvertently forget + # any unsafe characters. + if not c.isalnum() and c not in "@%-_+:,./": + return "'" + s.replace("'", "'\\''") + "'" + return s + +def _detokenize_javacopts(opts): + """Detokenizes a list of options to a depset. + + Args: + opts: ([str]) the javac options to detokenize + + Returns: + (depset[str]) depset of detokenized options + """ + return depset( + [" ".join([_shell_escape(opt) for opt in opts])], + order = "preorder", + ) + +def _get_relative(path_a, path_b): + if paths.is_absolute(path_b): + return path_b + return paths.normalize(paths.join(path_a, path_b)) + +def _tokenize_javacopts(ctx = None, opts = []): + """Tokenizes a list or depset of options to a list. + + Iff opts is a depset, we reverse the flattened list to ensure right-most + duplicates are preserved in their correct position. + + If the ctx parameter is omitted, a slow, but pure Starlark, implementation + of shell tokenization is used. Otherwise, tokenization is performed using + ctx.tokenize() which has significantly better performance (up to 100x for + large options lists). + + Args: + ctx: (RuleContext|None) the rule context + opts: (depset[str]|[str]) the javac options to tokenize + Returns: + [str] list of tokenized options + """ + if hasattr(opts, "to_list"): + opts = reversed(opts.to_list()) + if ctx: + return [ + token + for opt in opts + for token in ctx.tokenize(opt) + ] + else: + # TODO: optimize and use the pure Starlark implementation in cc_helper + return semantics.tokenize_javacopts(opts) + +helper = struct( + is_target_platform_windows = _is_target_platform_windows, + create_single_jar = _create_single_jar, + shell_escape = _shell_escape, + detokenize_javacopts = _detokenize_javacopts, + tokenize_javacopts = _tokenize_javacopts, + get_relative = _get_relative, + has_target_constraints = _has_target_constraints, + java_segments = _java_segments, +)
diff --git a/java/common/rules/java_package_configuration.bzl b/java/common/rules/java_package_configuration.bzl index 2c24b45..e6b1885 100644 --- a/java/common/rules/java_package_configuration.bzl +++ b/java/common/rules/java_package_configuration.bzl
@@ -14,7 +14,7 @@ """Implementation for the java_package_configuration rule""" -load("//java/common/rules/impl:java_helper.bzl", "helper") +load("//java/common/rules:java_helper.bzl", "helper") load("//java/private:boot_class_path_info.bzl", "BootClassPathInfo") load("//java/private:native.bzl", "get_internal_java_common")
diff --git a/java/common/rules/java_runtime.bzl b/java/common/rules/java_runtime.bzl index 47a9343..2433549 100644 --- a/java/common/rules/java_runtime.bzl +++ b/java/common/rules/java_runtime.bzl
@@ -19,7 +19,7 @@ load("@bazel_skylib//lib:paths.bzl", "paths") load("@rules_cc//cc/common:cc_info.bzl", "CcInfo") load("//java/common:java_semantics.bzl", "semantics") -load("//java/common/rules/impl:java_helper.bzl", "helper") +load("//java/common/rules:java_helper.bzl", "helper") # copybara: default visibility
diff --git a/java/common/rules/java_toolchain.bzl b/java/common/rules/java_toolchain.bzl index 6aed2ec..d08775a 100644 --- a/java/common/rules/java_toolchain.bzl +++ b/java/common/rules/java_toolchain.bzl
@@ -17,7 +17,7 @@ """ load("//java/common:java_semantics.bzl", "semantics") -load("//java/common/rules/impl:java_helper.bzl", "helper") +load("//java/common/rules:java_helper.bzl", "helper") load("//java/private:boot_class_path_info.bzl", "BootClassPathInfo") load("//java/private:java_info.bzl", "JavaPluginDataInfo") load("//java/private:native.bzl", "get_internal_java_common")
diff --git a/java/private/BUILD b/java/private/BUILD index bbed12b..510c301 100644 --- a/java/private/BUILD +++ b/java/private/BUILD
@@ -23,10 +23,8 @@ bzl_library( name = "internals", srcs = [ - "boot_class_path_info.bzl", "java_common.bzl", "java_common_internal.bzl", - "java_info.bzl", "message_bundle_info.bzl", ], visibility = [ @@ -34,9 +32,12 @@ "@compatibility_proxy//:__pkg__", ], deps = [ + ":boot_class_path_info_bzl", + ":java_info_bzl", ":native_bzl", + "//java/common:semantics_bzl", + "//java/common/rules:java_helper_bzl", "//java/common/rules:toolchain_rules", - "//java/common/rules/impl:java_helper_bzl", "@bazel_skylib//lib:paths", "@bazel_skylib//rules:common_settings", "@rules_cc//cc:find_cc_toolchain_bzl", @@ -44,6 +45,24 @@ ], ) +bzl_library( + name = "boot_class_path_info_bzl", + srcs = ["boot_class_path_info.bzl"], + visibility = ["//java:__subpackages__"], + deps = ["@bazel_skylib//lib:paths"], +) + +bzl_library( + name = "java_info_bzl", + srcs = ["java_info.bzl"], + visibility = ["//java:__subpackages__"], + deps = [ + ":native_bzl", + "//java/common:semantics_bzl", + "@rules_cc//cc/common", + ], +) + # Exposed for use by the protobuf. bzl_library( name = "proto_support",
diff --git a/java/private/java_common.bzl b/java/private/java_common.bzl index 7046163..8a465c2 100644 --- a/java/private/java_common.bzl +++ b/java/private/java_common.bzl
@@ -16,9 +16,9 @@ load("@bazel_skylib//lib:paths.bzl", "paths") load("//java/common:java_semantics.bzl", "semantics") +load("//java/common/rules:java_helper.bzl", "helper") load("//java/common/rules:java_runtime.bzl", "JavaRuntimeInfo") load("//java/common/rules:java_toolchain.bzl", "JavaToolchainInfo") -load("//java/common/rules/impl:java_helper.bzl", "helper") load(":boot_class_path_info.bzl", "BootClassPathInfo") load( ":java_common_internal.bzl",
diff --git a/java/private/java_common_internal.bzl b/java/private/java_common_internal.bzl index 7af3bf7..249b925 100644 --- a/java/private/java_common_internal.bzl +++ b/java/private/java_common_internal.bzl
@@ -16,8 +16,8 @@ load("@bazel_skylib//lib:paths.bzl", "paths") load("//java/common:java_semantics.bzl", "semantics") +load("//java/common/rules:java_helper.bzl", "helper") load("//java/common/rules:java_toolchain.bzl", "JavaToolchainInfo") -load("//java/common/rules/impl:java_helper.bzl", "helper") load( ":java_info.bzl", "JavaPluginInfo", @@ -222,14 +222,14 @@ header_compilation_jar = compile_jar compile_deps_proto = None elif _should_use_header_compilation(ctx, java_toolchain): - compile_jar = helper.derive_output_file(ctx, output, name_suffix = "-hjar", extension = "jar") + compile_jar = _derive_output_file(ctx, output, name_suffix = "-hjar", extension = "jar") # TODO: b/417791104 - remove check after a Bazel release if ctx.fragments.java.use_header_compilation_direct_deps(): - header_compilation_jar = helper.derive_output_file(ctx, output, name_suffix = "-tjar", extension = "jar") + header_compilation_jar = _derive_output_file(ctx, output, name_suffix = "-tjar", extension = "jar") else: header_compilation_jar = None - compile_deps_proto = helper.derive_output_file(ctx, output, name_suffix = "-hjar", extension = "jdeps") + compile_deps_proto = _derive_output_file(ctx, output, name_suffix = "-hjar", extension = "jdeps") get_internal_java_common().create_header_compilation_action( ctx, java_toolchain, @@ -266,16 +266,16 @@ header_compilation_jar = compile_jar compile_deps_proto = None - native_headers_jar = helper.derive_output_file(ctx, output, name_suffix = "-native-header") - manifest_proto = helper.derive_output_file(ctx, output, extension_suffix = "_manifest_proto") + native_headers_jar = _derive_output_file(ctx, output, name_suffix = "-native-header") + manifest_proto = _derive_output_file(ctx, output, extension_suffix = "_manifest_proto") deps_proto = None if ctx.fragments.java.generate_java_deps() and has_sources: - deps_proto = helper.derive_output_file(ctx, output, extension = "jdeps") + deps_proto = _derive_output_file(ctx, output, extension = "jdeps") generated_class_jar = None generated_source_jar = None if uses_annotation_processing: - generated_class_jar = helper.derive_output_file(ctx, output, name_suffix = "-gen") - generated_source_jar = helper.derive_output_file(ctx, output, name_suffix = "-gensrc") + generated_class_jar = _derive_output_file(ctx, output, name_suffix = "-gen") + generated_source_jar = _derive_output_file(ctx, output, name_suffix = "-gensrc") get_internal_java_common().create_compilation_action( ctx, java_toolchain, @@ -309,7 +309,7 @@ create_output_source_jar = len(source_files) > 0 or source_jars != [output_source_jar] if not output_source_jar: - output_source_jar = helper.derive_output_file(ctx, output, name_suffix = "-src", extension = "jar") + output_source_jar = _derive_output_file(ctx, output, name_suffix = "-src", extension = "jar") if create_output_source_jar: helper.create_single_jar( ctx.actions, @@ -364,6 +364,35 @@ compilation_info = compilation_info, ) +def _derive_output_file(ctx, base_file, *, name_suffix = "", extension = None, extension_suffix = ""): + """Declares a new file whose name is derived from the given file + + This method allows appending a suffix to the name (before extension), changing + the extension or appending a suffix after the extension. The new file is declared + as a sibling of the given base file. At least one of the three options must be + specified. It is an error to specify both `extension` and `extension_suffix`. + + Args: + ctx: (RuleContext) the rule context. + base_file: (File) the file from which to derive the resultant file. + name_suffix: (str) Optional. The suffix to append to the name before the + extension. + extension: (str) Optional. The new extension to use (without '.'). By default, + the base_file's extension is used. + extension_suffix: (str) Optional. The suffix to append to the base_file's extension + + Returns: + (File) the derived file + """ + if not name_suffix and not extension_suffix and not extension: + fail("At least one of name_suffix, extension or extension_suffix is required") + if extension and extension_suffix: + fail("only one of extension or extension_suffix can be specified") + if extension == None: + extension = base_file.extension + new_basename = paths.replace_extension(base_file.basename, name_suffix + "." + extension + extension_suffix) + return ctx.actions.declare_file(new_basename, sibling = base_file) + def _should_use_header_compilation(ctx, toolchain): if not ctx.fragments.java.use_header_compilation(): return False