|
| 1 | +""" |
| 2 | +Skylib module containing additional sugar for resolving or analyzing labels |
| 3 | +across workspaces / repositories and packages. |
| 4 | +""" |
| 5 | + |
| 6 | +# Possibly helpful pointers / complaints: |
| 7 | +# https://github.com/bazelbuild/bazel/issues/16210 |
| 8 | + |
| 9 | +def strip_prefix(prefix, value): |
| 10 | + if not value.startswith(prefix): |
| 11 | + fail("bad") |
| 12 | + return value[len(prefix):] |
| 13 | + |
| 14 | +def qualify_package(label): |
| 15 | + """ |
| 16 | + Returns a "qualified package" name, that is "@repository//package". |
| 17 | + """ |
| 18 | + if in_root_workspace(label): |
| 19 | + return "//" + label.package |
| 20 | + elif label.package == "": |
| 21 | + return "@" + label.workspace_name |
| 22 | + else: |
| 23 | + return "@" + label.workspace_name + "//" + label.package |
| 24 | + |
| 25 | +def current_qualified_package(): |
| 26 | + """ |
| 27 | + Gets the current package as "qualified package". |
| 28 | + """ |
| 29 | + label_str = "//" + native.package_name() |
| 30 | + repository = native.repository_name() |
| 31 | + if repository == "@": |
| 32 | + return "//" + native.package_name() |
| 33 | + else: |
| 34 | + return repository + "//" + native.package_name() |
| 35 | + |
| 36 | +def to_label(label_str): |
| 37 | + """ |
| 38 | + Converts any label string to a Label instance. |
| 39 | + Normally, Label() requires absolute paths, so this wraps the constructor to |
| 40 | + allow automatic scoping. |
| 41 | + This can be used to parse / canonicalize labels. |
| 42 | + """ |
| 43 | + if label_str.startswith(":"): |
| 44 | + label_str = current_qualified_package() + label_str |
| 45 | + return Label(label_str) |
| 46 | + |
| 47 | +def in_workspace(label, workspace): |
| 48 | + """True if given Label is in the specified workspace / repository.""" |
| 49 | + if workspace.startswith("@"): |
| 50 | + fail("Please supply name without @") |
| 51 | + return label.workspace_name == workspace |
| 52 | + |
| 53 | +def in_root_workspace(label): |
| 54 | + """True if given Label is in source workspace.""" |
| 55 | + return in_workspace(label, "") |
| 56 | + |
| 57 | +def workspace_name(): |
| 58 | + """Repository name, but without leading @.""" |
| 59 | + return strip_prefix("@", native.repository_name()) |
| 60 | + |
| 61 | +def in_current_package(label): |
| 62 | + """True if given label is in the current package.""" |
| 63 | + return ( |
| 64 | + label.workspace_name == workspace_name() and |
| 65 | + label.package == native.package_name() |
| 66 | + ) |
| 67 | + |
| 68 | +labels = struct( |
| 69 | + strip_prefix = strip_prefix, |
| 70 | + qualify_package = qualify_package, |
| 71 | + current_qualified_package = current_qualified_package, |
| 72 | + to_label = to_label, |
| 73 | + in_workspace = in_workspace, |
| 74 | + in_root_workspace = in_root_workspace, |
| 75 | + workspace_name = workspace_name, |
| 76 | + in_current_package = in_current_package, |
| 77 | +) |
0 commit comments