xref: /aosp_15_r20/external/bazelbuild-kotlin-rules/kotlin/common/is_eligible_friend.bzl (revision 3a22c0a33dd99bcca39a024d43e6fbcc55c2806e)
1# Copyright 2022 Google LLC. All rights reserved.
2#
3# Licensed under the Apache License, Version 2.0 (the License);
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7#     http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15"""is_eligible_friend"""
16
17load("//:visibility.bzl", "RULES_DEFS_THAT_COMPILE_KOTLIN")
18
19visibility(RULES_DEFS_THAT_COMPILE_KOTLIN)
20
21def is_eligible_friend(target, friend):
22    """
23    Determines if `target` is allowed to use `internal` members of `friend`
24
25    To be eligible, one of:
26      1. `target` and `friend` in same pkg
27      2. `target` in `testing/` subpkg of `friend` pkg
28      3. `target` in `javatests/` pkg, `friend` in parallel `java/` pkg
29      4. `target` in `test/java/` pkg, `friend` in parallel `main/java/` pkg
30
31    Args:
32      target: (Target) The current target
33      friend: (Target) A potential friend of `target`
34
35    Returns:
36      True if `friend` is an eligible friend of `target`.
37    """
38
39    target_pkg = target.label.package + "/"
40    friend_pkg = friend.label.package + "/"
41
42    if target_pkg == friend_pkg:
43        # Case 1
44        return True
45
46    if target_pkg.removesuffix("testing/") == friend_pkg:
47        # Case 2
48        return True
49
50    if "javatests/" in target_pkg and "java/" in friend_pkg:
51        # Case 3
52        target_java_pkg = target_pkg.rsplit("javatests/", 1)[1]
53        friend_java_pkg = friend_pkg.rsplit("java/", 1)[1]
54        if target_java_pkg == friend_java_pkg:
55            return True
56
57    if ("test/java/" in target_pkg and "main/java/" in friend_pkg and
58        True):
59        # Case 4
60        target_split = target_pkg.rsplit("test/java/", 1)
61        friend_split = friend_pkg.rsplit("main/java/", 1)
62        if target_split == friend_split:
63            return True
64
65    return False
66