Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 0 additions & 23 deletions python/pip_install/tools/lib/bazel.py
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,3 @@
WHEEL_FILE_LABEL = "whl"
PY_LIBRARY_LABEL = "pkg"
DATA_LABEL = "data"
DIST_INFO_LABEL = "dist_info"
WHEEL_ENTRY_POINT_PREFIX = "rules_python_wheel_entry_point"


def sanitise_name(name: str, prefix: str) -> str:
"""Sanitises the name to be compatible with Bazel labels.

Expand All@@ -23,19 +16,3 @@ def sanitise_name(name: str, prefix: str) -> str:
"""

return prefix + name.replace("-", "_").replace(".", "_").lower()


def _whl_name_to_repo_root(whl_name: str, repo_prefix: str) -> str:
return "@{}//".format(sanitise_name(whl_name, prefix=repo_prefix))


def sanitised_repo_library_label(whl_name: str, repo_prefix: str) -> str:
return '"{}:{}"'.format(
_whl_name_to_repo_root(whl_name, repo_prefix), PY_LIBRARY_LABEL
)


def sanitised_repo_file_label(whl_name: str, repo_prefix: str) -> str:
return '"{}:{}"'.format(
_whl_name_to_repo_root(whl_name, repo_prefix), WHEEL_FILE_LABEL
)
Original file line numberDiff line numberDiff line change
Expand Up@@ -95,7 +95,6 @@ def parse_whl_library_args(args: argparse.Namespace) -> Dict[str, Any]:

def generate_parsed_requirements_contents(
requirements_lock: Path,
repo: str,
repo_prefix: str,
whl_library_args: Dict[str, Any],
annotations: Dict[str, str] = dict(),
Expand All@@ -115,19 +114,6 @@ def generate_parsed_requirements_contents(
install_req_and_lines, repo_prefix
)

all_requirements = ", ".join(
[
bazel.sanitised_repo_library_label(ir.name, repo_prefix=repo_prefix)
for ir, _ in install_req_and_lines
]
)
all_whl_requirements = ", ".join(
[
bazel.sanitised_repo_file_label(ir.name, repo_prefix=repo_prefix)
for ir, _ in install_req_and_lines
]
)

install_deps_macro = """
def install_deps(**whl_library_kwargs):
whl_config = dict(_config)
Expand All@@ -146,64 +132,37 @@ def install_deps(**whl_library_kwargs):

load("@rules_python//python/pip_install:pip_repository.bzl", "whl_library")

all_requirements = [{all_requirements}]

all_whl_requirements = [{all_whl_requirements}]

_packages = {repo_names_and_reqs}
_config = {args}
_annotations = {annotations}
_bzlmod = {bzlmod}

def _clean_name(name):
return name.replace("-", "_").replace(".", "_").lower()

def requirement(name):
if _bzlmod:
return "@@{repo}//:" + _clean_name(name) + "_{py_library_label}"
return "@{repo_prefix}" + _clean_name(name) + "//:{py_library_label}"
fail("This function has been replaced with a regular macro in TODO.bzl. Update your imports to TODO. See TODO for further migration details.")

def whl_requirement(name):
if _bzlmod:
return "@@{repo}//:" + _clean_name(name) + "_{wheel_file_label}"
return "@{repo_prefix}" + _clean_name(name) + "//:{wheel_file_label}"
fail("This function has been replaced with a regular macro in TODO.bzl. Update your imports to TODO. See TODO for further migration details.")

def data_requirement(name):
if _bzlmod:
return "@@{repo}//:" + _clean_name(name) + "_{data_label}"
return "@{repo_prefix}" + _clean_name(name) + "//:{data_label}"
fail("This function has been replaced with a regular macro in TODO.bzl. Update your imports to TODO. See TODO for further migration details.")

def dist_info_requirement(name):
if _bzlmod:
return "@@{repo}//:" + _clean_name(name) + "_{dist_info_label}"
return "@{repo_prefix}" + _clean_name(name) + "//:{dist_info_label}"
fail("This function has been replaced with a regular macro in TODO.bzl. Update your imports to TODO. See TODO for further migration details.")

def entry_point(pkg, script = None):
if not script:
script = pkg
return "@{repo_prefix}" + _clean_name(pkg) + "//:{entry_point_prefix}_" + script
fail("This function has been replaced with a regular macro in TODO.bzl. Update your imports to TODO. See TODO for further migration details.")

def _get_annotation(requirement):
# TODO(greg) Consider deprecating the annotation functionality to occur
# This expects to parse `setuptools==58.2.0 --hash=sha256:2551203ae6955b9876741a26ab3e767bb3242dafe86a32a749ea0d78b6792f11`
# down wo `setuptools`.
name = requirement.split(" ")[0].split("=")[0].split("[")[0]
return _annotations.get(name)
"""
+ (install_deps_macro if not bzlmod else "")
).format(
all_requirements=all_requirements,
all_whl_requirements=all_whl_requirements,
annotations=json.dumps(annotations),
args=dict(sorted(whl_library_args.items())),
data_label=bazel.DATA_LABEL,
dist_info_label=bazel.DIST_INFO_LABEL,
entry_point_prefix=bazel.WHEEL_ENTRY_POINT_PREFIX,
py_library_label=bazel.PY_LIBRARY_LABEL,
repo_names_and_reqs=repo_names_and_reqs,
repo=repo,
repo_prefix=repo_prefix,
wheel_file_label=bazel.WHEEL_FILE_LABEL,
bzlmod=bzlmod,
)
)

Expand DownExpand Up@@ -308,7 +267,6 @@ def main(output: TextIO) -> None:
output.write(
generate_parsed_requirements_contents(
requirements_lock=args.requirements_lock,
repo=args.repo,
repo_prefix=args.repo_prefix,
whl_library_args=whl_library_args,
annotations=annotated_requirements,
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -35,20 +35,11 @@ def test_generated_requirements_bzl(self) -> None:
whl_library_args = lock_file_generator.parse_whl_library_args(args)
contents = lock_file_generator.generate_parsed_requirements_contents(
requirements_lock=args.requirements_lock,
repo=args.repo,
repo_prefix=args.repo_prefix,
whl_library_args=whl_library_args,
)
library_target = "@pip_parsed_deps_pypi__foo//:pkg"
whl_target = "@pip_parsed_deps_pypi__foo//:whl"
all_requirements = 'all_requirements = ["{library_target}"]'.format(
library_target=library_target
)
all_whl_requirements = 'all_whl_requirements = ["{whl_target}"]'.format(
whl_target=whl_target
)
self.assertIn(all_requirements, contents, contents)
self.assertIn(all_whl_requirements, contents, contents)
self.assertIn(requirement_string, contents, contents)
all_flags = extra_pip_args + ["--require-hashes", "True"]
self.assertIn(
Expand Down
98 changes: 7 additions & 91 deletions python/pip_install/tools/wheel_installer/wheel_installer.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -89,66 +89,6 @@ def _setup_namespace_pkg_compatibility(wheel_dir: str) -> None:
namespace_pkgs.add_pkgutil_style_namespace_pkg_init(ns_pkg_dir)


def _generate_entry_point_contents(
module: str, attribute: str, shebang: str = "#!/usr/bin/env python3"
) -> str:
"""Generate the contents of an entry point script.

Args:
module (str): The name of the module to use.
attribute (str): The name of the attribute to call.
shebang (str, optional): The shebang to use for the entry point python
file.

Returns:
str: A string of python code.
"""
return textwrap.dedent(
"""\
{shebang}
import sys
from {module} import {attribute}
if __name__ == "__main__":
sys.exit({attribute}())
""".format(
shebang=shebang, module=module, attribute=attribute
)
)


def _generate_entry_point_rule(name: str, script: str, pkg: str) -> str:
"""Generate a Bazel `py_binary` rule for an entry point script.

Note that the script is used to determine the name of the target. The name of
entry point targets should be uniuqe to avoid conflicts with existing sources or
directories within a wheel.

Args:
name (str): The name of the generated py_binary.
script (str): The path to the entry point's python file.
pkg (str): The package owning the entry point. This is expected to
match up with the `py_library` defined for each repository.


Returns:
str: A `py_binary` instantiation.
"""
return textwrap.dedent(
"""\
py_binary(
name = "{name}",
srcs = ["{src}"],
# This makes this directory a top-level in the python import
# search path for anything that depends on this.
imports = ["."],
deps = ["{pkg}"],
)
""".format(
name=name, src=str(script).replace("\\", "/"), pkg=pkg
)
)


def _generate_copy_commands(src, dest, is_executable=False) -> str:
"""Generate a [@bazel_skylib//rules:copy_file.bzl%copy_file][cf] target

Expand DownExpand Up@@ -231,17 +171,17 @@ def _generate_build_file_contents(
package(default_visibility = ["//visibility:public"])

filegroup(
name = "{dist_info_label}",
name = "dist_info",
srcs = glob(["site-packages/*.dist-info/**"], allow_empty = True),
)

filegroup(
name = "{data_label}",
name = "data",
srcs = glob(["data/**"], allow_empty = True),
)

filegroup(
name = "{whl_file_label}",
name = "whl",
srcs = glob(["*.whl"], allow_empty = True),
data = [{whl_file_deps}],
)
Expand All@@ -260,12 +200,8 @@ def _generate_build_file_contents(
name=name,
dependencies=",".join(sorted(dependencies)),
data_exclude=json.dumps(sorted(data_exclude)),
whl_file_label=bazel.WHEEL_FILE_LABEL,
whl_file_deps=",".join(sorted(whl_file_deps)),
tags=",".join(sorted(['"%s"' % t for t in tags])),
data_label=bazel.DATA_LABEL,
dist_info_label=bazel.DIST_INFO_LABEL,
entry_point_prefix=bazel.WHEEL_ENTRY_POINT_PREFIX,
srcs_exclude=json.dumps(sorted(srcs_exclude)),
data=json.dumps(sorted(data)),
)
Expand DownExpand Up@@ -308,33 +244,13 @@ def _extract_wheel(
whl_deps = sorted(whl.dependencies(extras_requested) - self_edge_dep)

sanitised_dependencies = [
bazel.sanitised_repo_library_label(d, repo_prefix=repo_prefix) for d in whl_deps
_sanitised_repo_library_label(d, repo_prefix=repo_prefix) for d in whl_deps
]
sanitised_wheel_file_dependencies = [
bazel.sanitised_repo_file_label(d, repo_prefix=repo_prefix) for d in whl_deps
_sanitised_repo_file_label(d, repo_prefix=repo_prefix) for d in whl_deps
]

entry_points = []
for name, (module, attribute) in sorted(whl.entry_points().items()):
# There is an extreme edge-case with entry_points that end with `.py`
# See: https://github.com/bazelbuild/bazel/blob/09c621e4cf5b968f4c6cdf905ab142d5961f9ddc/src/test/java/com/google/devtools/build/lib/rules/python/PyBinaryConfiguredTargetTest.java#L174
entry_point_without_py = f"{name[:-3]}_py" if name.endswith(".py") else name
entry_point_target_name = (
f"{bazel.WHEEL_ENTRY_POINT_PREFIX}_{entry_point_without_py}"
)
entry_point_script_name = f"{entry_point_target_name}.py"
(installation_dir / entry_point_script_name).write_text(
_generate_entry_point_contents(module, attribute)
)
entry_points.append(
_generate_entry_point_rule(
entry_point_target_name,
entry_point_script_name,
bazel.PY_LIBRARY_LABEL,
)
)

with open(os.path.join(installation_dir, "BUILD.bazel"), "w") as build_file:
with open(os.path.join(incremental_dir, "BUILD.bazel"), "w") as build_file:
additional_content = entry_points
data = []
data_exclude = pip_data_exclude
Expand All@@ -355,7 +271,7 @@ def _extract_wheel(
additional_content.append(annotation.additive_build_content)

contents = _generate_build_file_contents(
name=bazel.PY_LIBRARY_LABEL,
name="pkg",
dependencies=sanitised_dependencies,
whl_file_deps=sanitised_wheel_file_dependencies,
data_exclude=data_exclude,
Expand Down
24 changes: 0 additions & 24 deletions python/pip_install/tools/wheel_installer/wheel_installer_test.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -40,30 +40,6 @@ def test_parses_requirement_for_extra(self) -> None:
)


class BazelTestCase(unittest.TestCase):
def test_generate_entry_point_contents(self):
got = wheel_installer._generate_entry_point_contents("sphinx.cmd.build", "main")
want = """#!/usr/bin/env python3
import sys
from sphinx.cmd.build import main
if __name__ == "__main__":
sys.exit(main())
"""
self.assertEqual(got, want)

def test_generate_entry_point_contents_with_shebang(self):
got = wheel_installer._generate_entry_point_contents(
"sphinx.cmd.build", "main", shebang="#!/usr/bin/python"
)
want = """#!/usr/bin/python
import sys
from sphinx.cmd.build import main
if __name__ == "__main__":
sys.exit(main())
"""
self.assertEqual(got, want)


class TestWhlFilegroup(unittest.TestCase):
def setUp(self) -> None:
self.wheel_name = "example_minimal_package-0.0.1-py3-none-any.whl"
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 0 additions & 23 deletions python/pip_install/tools/lib/bazel.py
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,3 @@
WHEEL_FILE_LABEL = "whl"
PY_LIBRARY_LABEL = "pkg"
DATA_LABEL = "data"
DIST_INFO_LABEL = "dist_info"
WHEEL_ENTRY_POINT_PREFIX = "rules_python_wheel_entry_point"


def sanitise_name(name: str, prefix: str) -> str:
"""Sanitises the name to be compatible with Bazel labels.

Expand All@@ -23,19 +16,3 @@ def sanitise_name(name: str, prefix: str) -> str:
"""

return prefix + name.replace("-", "_").replace(".", "_").lower()


def _whl_name_to_repo_root(whl_name: str, repo_prefix: str) -> str:
return "@{}//".format(sanitise_name(whl_name, prefix=repo_prefix))


def sanitised_repo_library_label(whl_name: str, repo_prefix: str) -> str:
return '"{}:{}"'.format(
_whl_name_to_repo_root(whl_name, repo_prefix), PY_LIBRARY_LABEL
)


def sanitised_repo_file_label(whl_name: str, repo_prefix: str) -> str:
return '"{}:{}"'.format(
_whl_name_to_repo_root(whl_name, repo_prefix), WHEEL_FILE_LABEL
)
Original file line numberDiff line numberDiff line change
Expand Up@@ -95,7 +95,6 @@ def parse_whl_library_args(args: argparse.Namespace) -> Dict[str, Any]:

def generate_parsed_requirements_contents(
requirements_lock: Path,
repo: str,
repo_prefix: str,
whl_library_args: Dict[str, Any],
annotations: Dict[str, str] = dict(),
Expand All@@ -115,19 +114,6 @@ def generate_parsed_requirements_contents(
install_req_and_lines, repo_prefix
)

all_requirements = ", ".join(
[
bazel.sanitised_repo_library_label(ir.name, repo_prefix=repo_prefix)
for ir, _ in install_req_and_lines
]
)
all_whl_requirements = ", ".join(
[
bazel.sanitised_repo_file_label(ir.name, repo_prefix=repo_prefix)
for ir, _ in install_req_and_lines
]
)

install_deps_macro = """
def install_deps(**whl_library_kwargs):
whl_config = dict(_config)
Expand All@@ -146,64 +132,37 @@ def install_deps(**whl_library_kwargs):

load("@rules_python//python/pip_install:pip_repository.bzl", "whl_library")

all_requirements = [{all_requirements}]

all_whl_requirements = [{all_whl_requirements}]

_packages = {repo_names_and_reqs}
_config = {args}
_annotations = {annotations}
_bzlmod = {bzlmod}

def _clean_name(name):
return name.replace("-", "_").replace(".", "_").lower()

def requirement(name):
if _bzlmod:
return "@@{repo}//:" + _clean_name(name) + "_{py_library_label}"
return "@{repo_prefix}" + _clean_name(name) + "//:{py_library_label}"
fail("This function has been replaced with a regular macro in TODO.bzl. Update your imports to TODO. See TODO for further migration details.")

def whl_requirement(name):
if _bzlmod:
return "@@{repo}//:" + _clean_name(name) + "_{wheel_file_label}"
return "@{repo_prefix}" + _clean_name(name) + "//:{wheel_file_label}"
fail("This function has been replaced with a regular macro in TODO.bzl. Update your imports to TODO. See TODO for further migration details.")

def data_requirement(name):
if _bzlmod:
return "@@{repo}//:" + _clean_name(name) + "_{data_label}"
return "@{repo_prefix}" + _clean_name(name) + "//:{data_label}"
fail("This function has been replaced with a regular macro in TODO.bzl. Update your imports to TODO. See TODO for further migration details.")

def dist_info_requirement(name):
if _bzlmod:
return "@@{repo}//:" + _clean_name(name) + "_{dist_info_label}"
return "@{repo_prefix}" + _clean_name(name) + "//:{dist_info_label}"
fail("This function has been replaced with a regular macro in TODO.bzl. Update your imports to TODO. See TODO for further migration details.")

def entry_point(pkg, script = None):
if not script:
script = pkg
return "@{repo_prefix}" + _clean_name(pkg) + "//:{entry_point_prefix}_" + script
fail("This function has been replaced with a regular macro in TODO.bzl. Update your imports to TODO. See TODO for further migration details.")

def _get_annotation(requirement):
# TODO(greg) Consider deprecating the annotation functionality to occur
# This expects to parse `setuptools==58.2.0 --hash=sha256:2551203ae6955b9876741a26ab3e767bb3242dafe86a32a749ea0d78b6792f11`
# down wo `setuptools`.
name = requirement.split(" ")[0].split("=")[0].split("[")[0]
return _annotations.get(name)
"""
+ (install_deps_macro if not bzlmod else "")
).format(
all_requirements=all_requirements,
all_whl_requirements=all_whl_requirements,
annotations=json.dumps(annotations),
args=dict(sorted(whl_library_args.items())),
data_label=bazel.DATA_LABEL,
dist_info_label=bazel.DIST_INFO_LABEL,
entry_point_prefix=bazel.WHEEL_ENTRY_POINT_PREFIX,
py_library_label=bazel.PY_LIBRARY_LABEL,
repo_names_and_reqs=repo_names_and_reqs,
repo=repo,
repo_prefix=repo_prefix,
wheel_file_label=bazel.WHEEL_FILE_LABEL,
bzlmod=bzlmod,
)
)

Expand DownExpand Up@@ -308,7 +267,6 @@ def main(output: TextIO) -> None:
output.write(
generate_parsed_requirements_contents(
requirements_lock=args.requirements_lock,
repo=args.repo,
repo_prefix=args.repo_prefix,
whl_library_args=whl_library_args,
annotations=annotated_requirements,
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -35,20 +35,11 @@ def test_generated_requirements_bzl(self) -> None:
whl_library_args = lock_file_generator.parse_whl_library_args(args)
contents = lock_file_generator.generate_parsed_requirements_contents(
requirements_lock=args.requirements_lock,
repo=args.repo,
repo_prefix=args.repo_prefix,
whl_library_args=whl_library_args,
)
library_target = "@pip_parsed_deps_pypi__foo//:pkg"
whl_target = "@pip_parsed_deps_pypi__foo//:whl"
all_requirements = 'all_requirements = ["{library_target}"]'.format(
library_target=library_target
)
all_whl_requirements = 'all_whl_requirements = ["{whl_target}"]'.format(
whl_target=whl_target
)
self.assertIn(all_requirements, contents, contents)
self.assertIn(all_whl_requirements, contents, contents)
self.assertIn(requirement_string, contents, contents)
all_flags = extra_pip_args + ["--require-hashes", "True"]
self.assertIn(
Expand Down
98 changes: 7 additions & 91 deletions python/pip_install/tools/wheel_installer/wheel_installer.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -89,66 +89,6 @@ def _setup_namespace_pkg_compatibility(wheel_dir: str) -> None:
namespace_pkgs.add_pkgutil_style_namespace_pkg_init(ns_pkg_dir)


def _generate_entry_point_contents(
module: str, attribute: str, shebang: str = "#!/usr/bin/env python3"
) -> str:
"""Generate the contents of an entry point script.

Args:
module (str): The name of the module to use.
attribute (str): The name of the attribute to call.
shebang (str, optional): The shebang to use for the entry point python
file.

Returns:
str: A string of python code.
"""
return textwrap.dedent(
"""\
{shebang}
import sys
from {module} import {attribute}
if __name__ == "__main__":
sys.exit({attribute}())
""".format(
shebang=shebang, module=module, attribute=attribute
)
)


def _generate_entry_point_rule(name: str, script: str, pkg: str) -> str:
"""Generate a Bazel `py_binary` rule for an entry point script.

Note that the script is used to determine the name of the target. The name of
entry point targets should be uniuqe to avoid conflicts with existing sources or
directories within a wheel.

Args:
name (str): The name of the generated py_binary.
script (str): The path to the entry point's python file.
pkg (str): The package owning the entry point. This is expected to
match up with the `py_library` defined for each repository.


Returns:
str: A `py_binary` instantiation.
"""
return textwrap.dedent(
"""\
py_binary(
name = "{name}",
srcs = ["{src}"],
# This makes this directory a top-level in the python import
# search path for anything that depends on this.
imports = ["."],
deps = ["{pkg}"],
)
""".format(
name=name, src=str(script).replace("\\", "/"), pkg=pkg
)
)


def _generate_copy_commands(src, dest, is_executable=False) -> str:
"""Generate a [@bazel_skylib//rules:copy_file.bzl%copy_file][cf] target

Expand DownExpand Up@@ -231,17 +171,17 @@ def _generate_build_file_contents(
package(default_visibility = ["//visibility:public"])

filegroup(
name = "{dist_info_label}",
name = "dist_info",
srcs = glob(["site-packages/*.dist-info/**"], allow_empty = True),
)

filegroup(
name = "{data_label}",
name = "data",
srcs = glob(["data/**"], allow_empty = True),
)

filegroup(
name = "{whl_file_label}",
name = "whl",
srcs = glob(["*.whl"], allow_empty = True),
data = [{whl_file_deps}],
)
Expand All@@ -260,12 +200,8 @@ def _generate_build_file_contents(
name=name,
dependencies=",".join(sorted(dependencies)),
data_exclude=json.dumps(sorted(data_exclude)),
whl_file_label=bazel.WHEEL_FILE_LABEL,
whl_file_deps=",".join(sorted(whl_file_deps)),
tags=",".join(sorted(['"%s"' % t for t in tags])),
data_label=bazel.DATA_LABEL,
dist_info_label=bazel.DIST_INFO_LABEL,
entry_point_prefix=bazel.WHEEL_ENTRY_POINT_PREFIX,
srcs_exclude=json.dumps(sorted(srcs_exclude)),
data=json.dumps(sorted(data)),
)
Expand DownExpand Up@@ -308,33 +244,13 @@ def _extract_wheel(
whl_deps = sorted(whl.dependencies(extras_requested) - self_edge_dep)

sanitised_dependencies = [
bazel.sanitised_repo_library_label(d, repo_prefix=repo_prefix) for d in whl_deps
_sanitised_repo_library_label(d, repo_prefix=repo_prefix) for d in whl_deps
]
sanitised_wheel_file_dependencies = [
bazel.sanitised_repo_file_label(d, repo_prefix=repo_prefix) for d in whl_deps
_sanitised_repo_file_label(d, repo_prefix=repo_prefix) for d in whl_deps
]

entry_points = []
for name, (module, attribute) in sorted(whl.entry_points().items()):
# There is an extreme edge-case with entry_points that end with `.py`
# See: https://github.com/bazelbuild/bazel/blob/09c621e4cf5b968f4c6cdf905ab142d5961f9ddc/src/test/java/com/google/devtools/build/lib/rules/python/PyBinaryConfiguredTargetTest.java#L174
entry_point_without_py = f"{name[:-3]}_py" if name.endswith(".py") else name
entry_point_target_name = (
f"{bazel.WHEEL_ENTRY_POINT_PREFIX}_{entry_point_without_py}"
)
entry_point_script_name = f"{entry_point_target_name}.py"
(installation_dir / entry_point_script_name).write_text(
_generate_entry_point_contents(module, attribute)
)
entry_points.append(
_generate_entry_point_rule(
entry_point_target_name,
entry_point_script_name,
bazel.PY_LIBRARY_LABEL,
)
)

with open(os.path.join(installation_dir, "BUILD.bazel"), "w") as build_file:
with open(os.path.join(incremental_dir, "BUILD.bazel"), "w") as build_file:
additional_content = entry_points
data = []
data_exclude = pip_data_exclude
Expand All@@ -355,7 +271,7 @@ def _extract_wheel(
additional_content.append(annotation.additive_build_content)

contents = _generate_build_file_contents(
name=bazel.PY_LIBRARY_LABEL,
name="pkg",
dependencies=sanitised_dependencies,
whl_file_deps=sanitised_wheel_file_dependencies,
data_exclude=data_exclude,
Expand Down
24 changes: 0 additions & 24 deletions python/pip_install/tools/wheel_installer/wheel_installer_test.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -40,30 +40,6 @@ def test_parses_requirement_for_extra(self) -> None:
)


class BazelTestCase(unittest.TestCase):
def test_generate_entry_point_contents(self):
got = wheel_installer._generate_entry_point_contents("sphinx.cmd.build", "main")
want = """#!/usr/bin/env python3
import sys
from sphinx.cmd.build import main
if __name__ == "__main__":
sys.exit(main())
"""
self.assertEqual(got, want)

def test_generate_entry_point_contents_with_shebang(self):
got = wheel_installer._generate_entry_point_contents(
"sphinx.cmd.build", "main", shebang="#!/usr/bin/python"
)
want = """#!/usr/bin/python
import sys
from sphinx.cmd.build import main
if __name__ == "__main__":
sys.exit(main())
"""
self.assertEqual(got, want)


class TestWhlFilegroup(unittest.TestCase):
def setUp(self) -> None:
self.wheel_name = "example_minimal_package-0.0.1-py3-none-any.whl"
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 0 additions & 23 deletions python/pip_install/tools/lib/bazel.py
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,3 @@
WHEEL_FILE_LABEL = "whl"
PY_LIBRARY_LABEL = "pkg"
DATA_LABEL = "data"
DIST_INFO_LABEL = "dist_info"
WHEEL_ENTRY_POINT_PREFIX = "rules_python_wheel_entry_point"


def sanitise_name(name: str, prefix: str) -> str:
"""Sanitises the name to be compatible with Bazel labels.

Expand All@@ -23,19 +16,3 @@ def sanitise_name(name: str, prefix: str) -> str:
"""

return prefix + name.replace("-", "_").replace(".", "_").lower()


def _whl_name_to_repo_root(whl_name: str, repo_prefix: str) -> str:
return "@{}//".format(sanitise_name(whl_name, prefix=repo_prefix))


def sanitised_repo_library_label(whl_name: str, repo_prefix: str) -> str:
return '"{}:{}"'.format(
_whl_name_to_repo_root(whl_name, repo_prefix), PY_LIBRARY_LABEL
)


def sanitised_repo_file_label(whl_name: str, repo_prefix: str) -> str:
return '"{}:{}"'.format(
_whl_name_to_repo_root(whl_name, repo_prefix), WHEEL_FILE_LABEL
)
Original file line numberDiff line numberDiff line change
Expand Up@@ -95,7 +95,6 @@ def parse_whl_library_args(args: argparse.Namespace) -> Dict[str, Any]:

def generate_parsed_requirements_contents(
requirements_lock: Path,
repo: str,
repo_prefix: str,
whl_library_args: Dict[str, Any],
annotations: Dict[str, str] = dict(),
Expand All@@ -115,19 +114,6 @@ def generate_parsed_requirements_contents(
install_req_and_lines, repo_prefix
)

all_requirements = ", ".join(
[
bazel.sanitised_repo_library_label(ir.name, repo_prefix=repo_prefix)
for ir, _ in install_req_and_lines
]
)
all_whl_requirements = ", ".join(
[
bazel.sanitised_repo_file_label(ir.name, repo_prefix=repo_prefix)
for ir, _ in install_req_and_lines
]
)

install_deps_macro = """
def install_deps(**whl_library_kwargs):
whl_config = dict(_config)
Expand All@@ -146,64 +132,37 @@ def install_deps(**whl_library_kwargs):

load("@rules_python//python/pip_install:pip_repository.bzl", "whl_library")

all_requirements = [{all_requirements}]

all_whl_requirements = [{all_whl_requirements}]

_packages = {repo_names_and_reqs}
_config = {args}
_annotations = {annotations}
_bzlmod = {bzlmod}

def _clean_name(name):
return name.replace("-", "_").replace(".", "_").lower()

def requirement(name):
if _bzlmod:
return "@@{repo}//:" + _clean_name(name) + "_{py_library_label}"
return "@{repo_prefix}" + _clean_name(name) + "//:{py_library_label}"
fail("This function has been replaced with a regular macro in TODO.bzl. Update your imports to TODO. See TODO for further migration details.")

def whl_requirement(name):
if _bzlmod:
return "@@{repo}//:" + _clean_name(name) + "_{wheel_file_label}"
return "@{repo_prefix}" + _clean_name(name) + "//:{wheel_file_label}"
fail("This function has been replaced with a regular macro in TODO.bzl. Update your imports to TODO. See TODO for further migration details.")

def data_requirement(name):
if _bzlmod:
return "@@{repo}//:" + _clean_name(name) + "_{data_label}"
return "@{repo_prefix}" + _clean_name(name) + "//:{data_label}"
fail("This function has been replaced with a regular macro in TODO.bzl. Update your imports to TODO. See TODO for further migration details.")

def dist_info_requirement(name):
if _bzlmod:
return "@@{repo}//:" + _clean_name(name) + "_{dist_info_label}"
return "@{repo_prefix}" + _clean_name(name) + "//:{dist_info_label}"
fail("This function has been replaced with a regular macro in TODO.bzl. Update your imports to TODO. See TODO for further migration details.")

def entry_point(pkg, script = None):
if not script:
script = pkg
return "@{repo_prefix}" + _clean_name(pkg) + "//:{entry_point_prefix}_" + script
fail("This function has been replaced with a regular macro in TODO.bzl. Update your imports to TODO. See TODO for further migration details.")

def _get_annotation(requirement):
# TODO(greg) Consider deprecating the annotation functionality to occur
# This expects to parse `setuptools==58.2.0 --hash=sha256:2551203ae6955b9876741a26ab3e767bb3242dafe86a32a749ea0d78b6792f11`
# down wo `setuptools`.
name = requirement.split(" ")[0].split("=")[0].split("[")[0]
return _annotations.get(name)
"""
+ (install_deps_macro if not bzlmod else "")
).format(
all_requirements=all_requirements,
all_whl_requirements=all_whl_requirements,
annotations=json.dumps(annotations),
args=dict(sorted(whl_library_args.items())),
data_label=bazel.DATA_LABEL,
dist_info_label=bazel.DIST_INFO_LABEL,
entry_point_prefix=bazel.WHEEL_ENTRY_POINT_PREFIX,
py_library_label=bazel.PY_LIBRARY_LABEL,
repo_names_and_reqs=repo_names_and_reqs,
repo=repo,
repo_prefix=repo_prefix,
wheel_file_label=bazel.WHEEL_FILE_LABEL,
bzlmod=bzlmod,
)
)

Expand DownExpand Up@@ -308,7 +267,6 @@ def main(output: TextIO) -> None:
output.write(
generate_parsed_requirements_contents(
requirements_lock=args.requirements_lock,
repo=args.repo,
repo_prefix=args.repo_prefix,
whl_library_args=whl_library_args,
annotations=annotated_requirements,
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -35,20 +35,11 @@ def test_generated_requirements_bzl(self) -> None:
whl_library_args = lock_file_generator.parse_whl_library_args(args)
contents = lock_file_generator.generate_parsed_requirements_contents(
requirements_lock=args.requirements_lock,
repo=args.repo,
repo_prefix=args.repo_prefix,
whl_library_args=whl_library_args,
)
library_target = "@pip_parsed_deps_pypi__foo//:pkg"
whl_target = "@pip_parsed_deps_pypi__foo//:whl"
all_requirements = 'all_requirements = ["{library_target}"]'.format(
library_target=library_target
)
all_whl_requirements = 'all_whl_requirements = ["{whl_target}"]'.format(
whl_target=whl_target
)
self.assertIn(all_requirements, contents, contents)
self.assertIn(all_whl_requirements, contents, contents)
self.assertIn(requirement_string, contents, contents)
all_flags = extra_pip_args + ["--require-hashes", "True"]
self.assertIn(
Expand Down
98 changes: 7 additions & 91 deletions python/pip_install/tools/wheel_installer/wheel_installer.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -89,66 +89,6 @@ def _setup_namespace_pkg_compatibility(wheel_dir: str) -> None:
namespace_pkgs.add_pkgutil_style_namespace_pkg_init(ns_pkg_dir)


def _generate_entry_point_contents(
module: str, attribute: str, shebang: str = "#!/usr/bin/env python3"
) -> str:
"""Generate the contents of an entry point script.

Args:
module (str): The name of the module to use.
attribute (str): The name of the attribute to call.
shebang (str, optional): The shebang to use for the entry point python
file.

Returns:
str: A string of python code.
"""
return textwrap.dedent(
"""\
{shebang}
import sys
from {module} import {attribute}
if __name__ == "__main__":
sys.exit({attribute}())
""".format(
shebang=shebang, module=module, attribute=attribute
)
)


def _generate_entry_point_rule(name: str, script: str, pkg: str) -> str:
"""Generate a Bazel `py_binary` rule for an entry point script.

Note that the script is used to determine the name of the target. The name of
entry point targets should be uniuqe to avoid conflicts with existing sources or
directories within a wheel.

Args:
name (str): The name of the generated py_binary.
script (str): The path to the entry point's python file.
pkg (str): The package owning the entry point. This is expected to
match up with the `py_library` defined for each repository.


Returns:
str: A `py_binary` instantiation.
"""
return textwrap.dedent(
"""\
py_binary(
name = "{name}",
srcs = ["{src}"],
# This makes this directory a top-level in the python import
# search path for anything that depends on this.
imports = ["."],
deps = ["{pkg}"],
)
""".format(
name=name, src=str(script).replace("\\", "/"), pkg=pkg
)
)


def _generate_copy_commands(src, dest, is_executable=False) -> str:
"""Generate a [@bazel_skylib//rules:copy_file.bzl%copy_file][cf] target

Expand DownExpand Up@@ -231,17 +171,17 @@ def _generate_build_file_contents(
package(default_visibility = ["//visibility:public"])

filegroup(
name = "{dist_info_label}",
name = "dist_info",
srcs = glob(["site-packages/*.dist-info/**"], allow_empty = True),
)

filegroup(
name = "{data_label}",
name = "data",
srcs = glob(["data/**"], allow_empty = True),
)

filegroup(
name = "{whl_file_label}",
name = "whl",
srcs = glob(["*.whl"], allow_empty = True),
data = [{whl_file_deps}],
)
Expand All@@ -260,12 +200,8 @@ def _generate_build_file_contents(
name=name,
dependencies=",".join(sorted(dependencies)),
data_exclude=json.dumps(sorted(data_exclude)),
whl_file_label=bazel.WHEEL_FILE_LABEL,
whl_file_deps=",".join(sorted(whl_file_deps)),
tags=",".join(sorted(['"%s"' % t for t in tags])),
data_label=bazel.DATA_LABEL,
dist_info_label=bazel.DIST_INFO_LABEL,
entry_point_prefix=bazel.WHEEL_ENTRY_POINT_PREFIX,
srcs_exclude=json.dumps(sorted(srcs_exclude)),
data=json.dumps(sorted(data)),
)
Expand DownExpand Up@@ -308,33 +244,13 @@ def _extract_wheel(
whl_deps = sorted(whl.dependencies(extras_requested) - self_edge_dep)

sanitised_dependencies = [
bazel.sanitised_repo_library_label(d, repo_prefix=repo_prefix) for d in whl_deps
_sanitised_repo_library_label(d, repo_prefix=repo_prefix) for d in whl_deps
]
sanitised_wheel_file_dependencies = [
bazel.sanitised_repo_file_label(d, repo_prefix=repo_prefix) for d in whl_deps
_sanitised_repo_file_label(d, repo_prefix=repo_prefix) for d in whl_deps
]

entry_points = []
for name, (module, attribute) in sorted(whl.entry_points().items()):
# There is an extreme edge-case with entry_points that end with `.py`
# See: https://github.com/bazelbuild/bazel/blob/09c621e4cf5b968f4c6cdf905ab142d5961f9ddc/src/test/java/com/google/devtools/build/lib/rules/python/PyBinaryConfiguredTargetTest.java#L174
entry_point_without_py = f"{name[:-3]}_py" if name.endswith(".py") else name
entry_point_target_name = (
f"{bazel.WHEEL_ENTRY_POINT_PREFIX}_{entry_point_without_py}"
)
entry_point_script_name = f"{entry_point_target_name}.py"
(installation_dir / entry_point_script_name).write_text(
_generate_entry_point_contents(module, attribute)
)
entry_points.append(
_generate_entry_point_rule(
entry_point_target_name,
entry_point_script_name,
bazel.PY_LIBRARY_LABEL,
)
)

with open(os.path.join(installation_dir, "BUILD.bazel"), "w") as build_file:
with open(os.path.join(incremental_dir, "BUILD.bazel"), "w") as build_file:
additional_content = entry_points
data = []
data_exclude = pip_data_exclude
Expand All@@ -355,7 +271,7 @@ def _extract_wheel(
additional_content.append(annotation.additive_build_content)

contents = _generate_build_file_contents(
name=bazel.PY_LIBRARY_LABEL,
name="pkg",
dependencies=sanitised_dependencies,
whl_file_deps=sanitised_wheel_file_dependencies,
data_exclude=data_exclude,
Expand Down
24 changes: 0 additions & 24 deletions python/pip_install/tools/wheel_installer/wheel_installer_test.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -40,30 +40,6 @@ def test_parses_requirement_for_extra(self) -> None:
)


class BazelTestCase(unittest.TestCase):
def test_generate_entry_point_contents(self):
got = wheel_installer._generate_entry_point_contents("sphinx.cmd.build", "main")
want = """#!/usr/bin/env python3
import sys
from sphinx.cmd.build import main
if __name__ == "__main__":
sys.exit(main())
"""
self.assertEqual(got, want)

def test_generate_entry_point_contents_with_shebang(self):
got = wheel_installer._generate_entry_point_contents(
"sphinx.cmd.build", "main", shebang="#!/usr/bin/python"
)
want = """#!/usr/bin/python
import sys
from sphinx.cmd.build import main
if __name__ == "__main__":
sys.exit(main())
"""
self.assertEqual(got, want)


class TestWhlFilegroup(unittest.TestCase):
def setUp(self) -> None:
self.wheel_name = "example_minimal_package-0.0.1-py3-none-any.whl"
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 0 additions & 23 deletions python/pip_install/tools/lib/bazel.py
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,3 @@
WHEEL_FILE_LABEL = "whl"
PY_LIBRARY_LABEL = "pkg"
DATA_LABEL = "data"
DIST_INFO_LABEL = "dist_info"
WHEEL_ENTRY_POINT_PREFIX = "rules_python_wheel_entry_point"


def sanitise_name(name: str, prefix: str) -> str:
"""Sanitises the name to be compatible with Bazel labels.

Expand All@@ -23,19 +16,3 @@ def sanitise_name(name: str, prefix: str) -> str:
"""

return prefix + name.replace("-", "_").replace(".", "_").lower()


def _whl_name_to_repo_root(whl_name: str, repo_prefix: str) -> str:
return "@{}//".format(sanitise_name(whl_name, prefix=repo_prefix))


def sanitised_repo_library_label(whl_name: str, repo_prefix: str) -> str:
return '"{}:{}"'.format(
_whl_name_to_repo_root(whl_name, repo_prefix), PY_LIBRARY_LABEL
)


def sanitised_repo_file_label(whl_name: str, repo_prefix: str) -> str:
return '"{}:{}"'.format(
_whl_name_to_repo_root(whl_name, repo_prefix), WHEEL_FILE_LABEL
)
Original file line numberDiff line numberDiff line change
Expand Up@@ -95,7 +95,6 @@ def parse_whl_library_args(args: argparse.Namespace) -> Dict[str, Any]:

def generate_parsed_requirements_contents(
requirements_lock: Path,
repo: str,
repo_prefix: str,
whl_library_args: Dict[str, Any],
annotations: Dict[str, str] = dict(),
Expand All@@ -115,19 +114,6 @@ def generate_parsed_requirements_contents(
install_req_and_lines, repo_prefix
)

all_requirements = ", ".join(
[
bazel.sanitised_repo_library_label(ir.name, repo_prefix=repo_prefix)
for ir, _ in install_req_and_lines
]
)
all_whl_requirements = ", ".join(
[
bazel.sanitised_repo_file_label(ir.name, repo_prefix=repo_prefix)
for ir, _ in install_req_and_lines
]
)

install_deps_macro = """
def install_deps(**whl_library_kwargs):
whl_config = dict(_config)
Expand All@@ -146,64 +132,37 @@ def install_deps(**whl_library_kwargs):

load("@rules_python//python/pip_install:pip_repository.bzl", "whl_library")

all_requirements = [{all_requirements}]

all_whl_requirements = [{all_whl_requirements}]

_packages = {repo_names_and_reqs}
_config = {args}
_annotations = {annotations}
_bzlmod = {bzlmod}

def _clean_name(name):
return name.replace("-", "_").replace(".", "_").lower()

def requirement(name):
if _bzlmod:
return "@@{repo}//:" + _clean_name(name) + "_{py_library_label}"
return "@{repo_prefix}" + _clean_name(name) + "//:{py_library_label}"
fail("This function has been replaced with a regular macro in TODO.bzl. Update your imports to TODO. See TODO for further migration details.")

def whl_requirement(name):
if _bzlmod:
return "@@{repo}//:" + _clean_name(name) + "_{wheel_file_label}"
return "@{repo_prefix}" + _clean_name(name) + "//:{wheel_file_label}"
fail("This function has been replaced with a regular macro in TODO.bzl. Update your imports to TODO. See TODO for further migration details.")

def data_requirement(name):
if _bzlmod:
return "@@{repo}//:" + _clean_name(name) + "_{data_label}"
return "@{repo_prefix}" + _clean_name(name) + "//:{data_label}"
fail("This function has been replaced with a regular macro in TODO.bzl. Update your imports to TODO. See TODO for further migration details.")

def dist_info_requirement(name):
if _bzlmod:
return "@@{repo}//:" + _clean_name(name) + "_{dist_info_label}"
return "@{repo_prefix}" + _clean_name(name) + "//:{dist_info_label}"
fail("This function has been replaced with a regular macro in TODO.bzl. Update your imports to TODO. See TODO for further migration details.")

def entry_point(pkg, script = None):
if not script:
script = pkg
return "@{repo_prefix}" + _clean_name(pkg) + "//:{entry_point_prefix}_" + script
fail("This function has been replaced with a regular macro in TODO.bzl. Update your imports to TODO. See TODO for further migration details.")

def _get_annotation(requirement):
# TODO(greg) Consider deprecating the annotation functionality to occur
# This expects to parse `setuptools==58.2.0 --hash=sha256:2551203ae6955b9876741a26ab3e767bb3242dafe86a32a749ea0d78b6792f11`
# down wo `setuptools`.
name = requirement.split(" ")[0].split("=")[0].split("[")[0]
return _annotations.get(name)
"""
+ (install_deps_macro if not bzlmod else "")
).format(
all_requirements=all_requirements,
all_whl_requirements=all_whl_requirements,
annotations=json.dumps(annotations),
args=dict(sorted(whl_library_args.items())),
data_label=bazel.DATA_LABEL,
dist_info_label=bazel.DIST_INFO_LABEL,
entry_point_prefix=bazel.WHEEL_ENTRY_POINT_PREFIX,
py_library_label=bazel.PY_LIBRARY_LABEL,
repo_names_and_reqs=repo_names_and_reqs,
repo=repo,
repo_prefix=repo_prefix,
wheel_file_label=bazel.WHEEL_FILE_LABEL,
bzlmod=bzlmod,
)
)

Expand DownExpand Up@@ -308,7 +267,6 @@ def main(output: TextIO) -> None:
output.write(
generate_parsed_requirements_contents(
requirements_lock=args.requirements_lock,
repo=args.repo,
repo_prefix=args.repo_prefix,
whl_library_args=whl_library_args,
annotations=annotated_requirements,
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -35,20 +35,11 @@ def test_generated_requirements_bzl(self) -> None:
whl_library_args = lock_file_generator.parse_whl_library_args(args)
contents = lock_file_generator.generate_parsed_requirements_contents(
requirements_lock=args.requirements_lock,
repo=args.repo,
repo_prefix=args.repo_prefix,
whl_library_args=whl_library_args,
)
library_target = "@pip_parsed_deps_pypi__foo//:pkg"
whl_target = "@pip_parsed_deps_pypi__foo//:whl"
all_requirements = 'all_requirements = ["{library_target}"]'.format(
library_target=library_target
)
all_whl_requirements = 'all_whl_requirements = ["{whl_target}"]'.format(
whl_target=whl_target
)
self.assertIn(all_requirements, contents, contents)
self.assertIn(all_whl_requirements, contents, contents)
self.assertIn(requirement_string, contents, contents)
all_flags = extra_pip_args + ["--require-hashes", "True"]
self.assertIn(
Expand Down
98 changes: 7 additions & 91 deletions python/pip_install/tools/wheel_installer/wheel_installer.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -89,66 +89,6 @@ def _setup_namespace_pkg_compatibility(wheel_dir: str) -> None:
namespace_pkgs.add_pkgutil_style_namespace_pkg_init(ns_pkg_dir)


def _generate_entry_point_contents(
module: str, attribute: str, shebang: str = "#!/usr/bin/env python3"
) -> str:
"""Generate the contents of an entry point script.

Args:
module (str): The name of the module to use.
attribute (str): The name of the attribute to call.
shebang (str, optional): The shebang to use for the entry point python
file.

Returns:
str: A string of python code.
"""
return textwrap.dedent(
"""\
{shebang}
import sys
from {module} import {attribute}
if __name__ == "__main__":
sys.exit({attribute}())
""".format(
shebang=shebang, module=module, attribute=attribute
)
)


def _generate_entry_point_rule(name: str, script: str, pkg: str) -> str:
"""Generate a Bazel `py_binary` rule for an entry point script.

Note that the script is used to determine the name of the target. The name of
entry point targets should be uniuqe to avoid conflicts with existing sources or
directories within a wheel.

Args:
name (str): The name of the generated py_binary.
script (str): The path to the entry point's python file.
pkg (str): The package owning the entry point. This is expected to
match up with the `py_library` defined for each repository.


Returns:
str: A `py_binary` instantiation.
"""
return textwrap.dedent(
"""\
py_binary(
name = "{name}",
srcs = ["{src}"],
# This makes this directory a top-level in the python import
# search path for anything that depends on this.
imports = ["."],
deps = ["{pkg}"],
)
""".format(
name=name, src=str(script).replace("\\", "/"), pkg=pkg
)
)


def _generate_copy_commands(src, dest, is_executable=False) -> str:
"""Generate a [@bazel_skylib//rules:copy_file.bzl%copy_file][cf] target

Expand DownExpand Up@@ -231,17 +171,17 @@ def _generate_build_file_contents(
package(default_visibility = ["//visibility:public"])

filegroup(
name = "{dist_info_label}",
name = "dist_info",
srcs = glob(["site-packages/*.dist-info/**"], allow_empty = True),
)

filegroup(
name = "{data_label}",
name = "data",
srcs = glob(["data/**"], allow_empty = True),
)

filegroup(
name = "{whl_file_label}",
name = "whl",
srcs = glob(["*.whl"], allow_empty = True),
data = [{whl_file_deps}],
)
Expand All@@ -260,12 +200,8 @@ def _generate_build_file_contents(
name=name,
dependencies=",".join(sorted(dependencies)),
data_exclude=json.dumps(sorted(data_exclude)),
whl_file_label=bazel.WHEEL_FILE_LABEL,
whl_file_deps=",".join(sorted(whl_file_deps)),
tags=",".join(sorted(['"%s"' % t for t in tags])),
data_label=bazel.DATA_LABEL,
dist_info_label=bazel.DIST_INFO_LABEL,
entry_point_prefix=bazel.WHEEL_ENTRY_POINT_PREFIX,
srcs_exclude=json.dumps(sorted(srcs_exclude)),
data=json.dumps(sorted(data)),
)
Expand DownExpand Up@@ -308,33 +244,13 @@ def _extract_wheel(
whl_deps = sorted(whl.dependencies(extras_requested) - self_edge_dep)

sanitised_dependencies = [
bazel.sanitised_repo_library_label(d, repo_prefix=repo_prefix) for d in whl_deps
_sanitised_repo_library_label(d, repo_prefix=repo_prefix) for d in whl_deps
]
sanitised_wheel_file_dependencies = [
bazel.sanitised_repo_file_label(d, repo_prefix=repo_prefix) for d in whl_deps
_sanitised_repo_file_label(d, repo_prefix=repo_prefix) for d in whl_deps
]

entry_points = []
for name, (module, attribute) in sorted(whl.entry_points().items()):
# There is an extreme edge-case with entry_points that end with `.py`
# See: https://github.com/bazelbuild/bazel/blob/09c621e4cf5b968f4c6cdf905ab142d5961f9ddc/src/test/java/com/google/devtools/build/lib/rules/python/PyBinaryConfiguredTargetTest.java#L174
entry_point_without_py = f"{name[:-3]}_py" if name.endswith(".py") else name
entry_point_target_name = (
f"{bazel.WHEEL_ENTRY_POINT_PREFIX}_{entry_point_without_py}"
)
entry_point_script_name = f"{entry_point_target_name}.py"
(installation_dir / entry_point_script_name).write_text(
_generate_entry_point_contents(module, attribute)
)
entry_points.append(
_generate_entry_point_rule(
entry_point_target_name,
entry_point_script_name,
bazel.PY_LIBRARY_LABEL,
)
)

with open(os.path.join(installation_dir, "BUILD.bazel"), "w") as build_file:
with open(os.path.join(incremental_dir, "BUILD.bazel"), "w") as build_file:
additional_content = entry_points
data = []
data_exclude = pip_data_exclude
Expand All@@ -355,7 +271,7 @@ def _extract_wheel(
additional_content.append(annotation.additive_build_content)

contents = _generate_build_file_contents(
name=bazel.PY_LIBRARY_LABEL,
name="pkg",
dependencies=sanitised_dependencies,
whl_file_deps=sanitised_wheel_file_dependencies,
data_exclude=data_exclude,
Expand Down
24 changes: 0 additions & 24 deletions python/pip_install/tools/wheel_installer/wheel_installer_test.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -40,30 +40,6 @@ def test_parses_requirement_for_extra(self) -> None:
)


class BazelTestCase(unittest.TestCase):
def test_generate_entry_point_contents(self):
got = wheel_installer._generate_entry_point_contents("sphinx.cmd.build", "main")
want = """#!/usr/bin/env python3
import sys
from sphinx.cmd.build import main
if __name__ == "__main__":
sys.exit(main())
"""
self.assertEqual(got, want)

def test_generate_entry_point_contents_with_shebang(self):
got = wheel_installer._generate_entry_point_contents(
"sphinx.cmd.build", "main", shebang="#!/usr/bin/python"
)
want = """#!/usr/bin/python
import sys
from sphinx.cmd.build import main
if __name__ == "__main__":
sys.exit(main())
"""
self.assertEqual(got, want)


class TestWhlFilegroup(unittest.TestCase):
def setUp(self) -> None:
self.wheel_name = "example_minimal_package-0.0.1-py3-none-any.whl"
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 0 additions & 23 deletions python/pip_install/tools/lib/bazel.py
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,3 @@
WHEEL_FILE_LABEL = "whl"
PY_LIBRARY_LABEL = "pkg"
DATA_LABEL = "data"
DIST_INFO_LABEL = "dist_info"
WHEEL_ENTRY_POINT_PREFIX = "rules_python_wheel_entry_point"


def sanitise_name(name: str, prefix: str) -> str:
"""Sanitises the name to be compatible with Bazel labels.

Expand All@@ -23,19 +16,3 @@ def sanitise_name(name: str, prefix: str) -> str:
"""

return prefix + name.replace("-", "_").replace(".", "_").lower()


def _whl_name_to_repo_root(whl_name: str, repo_prefix: str) -> str:
return "@{}//".format(sanitise_name(whl_name, prefix=repo_prefix))


def sanitised_repo_library_label(whl_name: str, repo_prefix: str) -> str:
return '"{}:{}"'.format(
_whl_name_to_repo_root(whl_name, repo_prefix), PY_LIBRARY_LABEL
)


def sanitised_repo_file_label(whl_name: str, repo_prefix: str) -> str:
return '"{}:{}"'.format(
_whl_name_to_repo_root(whl_name, repo_prefix), WHEEL_FILE_LABEL
)
Original file line numberDiff line numberDiff line change
Expand Up@@ -95,7 +95,6 @@ def parse_whl_library_args(args: argparse.Namespace) -> Dict[str, Any]:

def generate_parsed_requirements_contents(
requirements_lock: Path,
repo: str,
repo_prefix: str,
whl_library_args: Dict[str, Any],
annotations: Dict[str, str] = dict(),
Expand All@@ -115,19 +114,6 @@ def generate_parsed_requirements_contents(
install_req_and_lines, repo_prefix
)

all_requirements = ", ".join(
[
bazel.sanitised_repo_library_label(ir.name, repo_prefix=repo_prefix)
for ir, _ in install_req_and_lines
]
)
all_whl_requirements = ", ".join(
[
bazel.sanitised_repo_file_label(ir.name, repo_prefix=repo_prefix)
for ir, _ in install_req_and_lines
]
)

install_deps_macro = """
def install_deps(**whl_library_kwargs):
whl_config = dict(_config)
Expand All@@ -146,64 +132,37 @@ def install_deps(**whl_library_kwargs):

load("@rules_python//python/pip_install:pip_repository.bzl", "whl_library")

all_requirements = [{all_requirements}]

all_whl_requirements = [{all_whl_requirements}]

_packages = {repo_names_and_reqs}
_config = {args}
_annotations = {annotations}
_bzlmod = {bzlmod}

def _clean_name(name):
return name.replace("-", "_").replace(".", "_").lower()

def requirement(name):
if _bzlmod:
return "@@{repo}//:" + _clean_name(name) + "_{py_library_label}"
return "@{repo_prefix}" + _clean_name(name) + "//:{py_library_label}"
fail("This function has been replaced with a regular macro in TODO.bzl. Update your imports to TODO. See TODO for further migration details.")

def whl_requirement(name):
if _bzlmod:
return "@@{repo}//:" + _clean_name(name) + "_{wheel_file_label}"
return "@{repo_prefix}" + _clean_name(name) + "//:{wheel_file_label}"
fail("This function has been replaced with a regular macro in TODO.bzl. Update your imports to TODO. See TODO for further migration details.")

def data_requirement(name):
if _bzlmod:
return "@@{repo}//:" + _clean_name(name) + "_{data_label}"
return "@{repo_prefix}" + _clean_name(name) + "//:{data_label}"
fail("This function has been replaced with a regular macro in TODO.bzl. Update your imports to TODO. See TODO for further migration details.")

def dist_info_requirement(name):
if _bzlmod:
return "@@{repo}//:" + _clean_name(name) + "_{dist_info_label}"
return "@{repo_prefix}" + _clean_name(name) + "//:{dist_info_label}"
fail("This function has been replaced with a regular macro in TODO.bzl. Update your imports to TODO. See TODO for further migration details.")

def entry_point(pkg, script = None):
if not script:
script = pkg
return "@{repo_prefix}" + _clean_name(pkg) + "//:{entry_point_prefix}_" + script
fail("This function has been replaced with a regular macro in TODO.bzl. Update your imports to TODO. See TODO for further migration details.")

def _get_annotation(requirement):
# TODO(greg) Consider deprecating the annotation functionality to occur
# This expects to parse `setuptools==58.2.0 --hash=sha256:2551203ae6955b9876741a26ab3e767bb3242dafe86a32a749ea0d78b6792f11`
# down wo `setuptools`.
name = requirement.split(" ")[0].split("=")[0].split("[")[0]
return _annotations.get(name)
"""
+ (install_deps_macro if not bzlmod else "")
).format(
all_requirements=all_requirements,
all_whl_requirements=all_whl_requirements,
annotations=json.dumps(annotations),
args=dict(sorted(whl_library_args.items())),
data_label=bazel.DATA_LABEL,
dist_info_label=bazel.DIST_INFO_LABEL,
entry_point_prefix=bazel.WHEEL_ENTRY_POINT_PREFIX,
py_library_label=bazel.PY_LIBRARY_LABEL,
repo_names_and_reqs=repo_names_and_reqs,
repo=repo,
repo_prefix=repo_prefix,
wheel_file_label=bazel.WHEEL_FILE_LABEL,
bzlmod=bzlmod,
)
)

Expand DownExpand Up@@ -308,7 +267,6 @@ def main(output: TextIO) -> None:
output.write(
generate_parsed_requirements_contents(
requirements_lock=args.requirements_lock,
repo=args.repo,
repo_prefix=args.repo_prefix,
whl_library_args=whl_library_args,
annotations=annotated_requirements,
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -35,20 +35,11 @@ def test_generated_requirements_bzl(self) -> None:
whl_library_args = lock_file_generator.parse_whl_library_args(args)
contents = lock_file_generator.generate_parsed_requirements_contents(
requirements_lock=args.requirements_lock,
repo=args.repo,
repo_prefix=args.repo_prefix,
whl_library_args=whl_library_args,
)
library_target = "@pip_parsed_deps_pypi__foo//:pkg"
whl_target = "@pip_parsed_deps_pypi__foo//:whl"
all_requirements = 'all_requirements = ["{library_target}"]'.format(
library_target=library_target
)
all_whl_requirements = 'all_whl_requirements = ["{whl_target}"]'.format(
whl_target=whl_target
)
self.assertIn(all_requirements, contents, contents)
self.assertIn(all_whl_requirements, contents, contents)
self.assertIn(requirement_string, contents, contents)
all_flags = extra_pip_args + ["--require-hashes", "True"]
self.assertIn(
Expand Down
98 changes: 7 additions & 91 deletions python/pip_install/tools/wheel_installer/wheel_installer.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -89,66 +89,6 @@ def _setup_namespace_pkg_compatibility(wheel_dir: str) -> None:
namespace_pkgs.add_pkgutil_style_namespace_pkg_init(ns_pkg_dir)


def _generate_entry_point_contents(
module: str, attribute: str, shebang: str = "#!/usr/bin/env python3"
) -> str:
"""Generate the contents of an entry point script.

Args:
module (str): The name of the module to use.
attribute (str): The name of the attribute to call.
shebang (str, optional): The shebang to use for the entry point python
file.

Returns:
str: A string of python code.
"""
return textwrap.dedent(
"""\
{shebang}
import sys
from {module} import {attribute}
if __name__ == "__main__":
sys.exit({attribute}())
""".format(
shebang=shebang, module=module, attribute=attribute
)
)


def _generate_entry_point_rule(name: str, script: str, pkg: str) -> str:
"""Generate a Bazel `py_binary` rule for an entry point script.

Note that the script is used to determine the name of the target. The name of
entry point targets should be uniuqe to avoid conflicts with existing sources or
directories within a wheel.

Args:
name (str): The name of the generated py_binary.
script (str): The path to the entry point's python file.
pkg (str): The package owning the entry point. This is expected to
match up with the `py_library` defined for each repository.


Returns:
str: A `py_binary` instantiation.
"""
return textwrap.dedent(
"""\
py_binary(
name = "{name}",
srcs = ["{src}"],
# This makes this directory a top-level in the python import
# search path for anything that depends on this.
imports = ["."],
deps = ["{pkg}"],
)
""".format(
name=name, src=str(script).replace("\\", "/"), pkg=pkg
)
)


def _generate_copy_commands(src, dest, is_executable=False) -> str:
"""Generate a [@bazel_skylib//rules:copy_file.bzl%copy_file][cf] target

Expand DownExpand Up@@ -231,17 +171,17 @@ def _generate_build_file_contents(
package(default_visibility = ["//visibility:public"])

filegroup(
name = "{dist_info_label}",
name = "dist_info",
srcs = glob(["site-packages/*.dist-info/**"], allow_empty = True),
)

filegroup(
name = "{data_label}",
name = "data",
srcs = glob(["data/**"], allow_empty = True),
)

filegroup(
name = "{whl_file_label}",
name = "whl",
srcs = glob(["*.whl"], allow_empty = True),
data = [{whl_file_deps}],
)
Expand All@@ -260,12 +200,8 @@ def _generate_build_file_contents(
name=name,
dependencies=",".join(sorted(dependencies)),
data_exclude=json.dumps(sorted(data_exclude)),
whl_file_label=bazel.WHEEL_FILE_LABEL,
whl_file_deps=",".join(sorted(whl_file_deps)),
tags=",".join(sorted(['"%s"' % t for t in tags])),
data_label=bazel.DATA_LABEL,
dist_info_label=bazel.DIST_INFO_LABEL,
entry_point_prefix=bazel.WHEEL_ENTRY_POINT_PREFIX,
srcs_exclude=json.dumps(sorted(srcs_exclude)),
data=json.dumps(sorted(data)),
)
Expand DownExpand Up@@ -308,33 +244,13 @@ def _extract_wheel(
whl_deps = sorted(whl.dependencies(extras_requested) - self_edge_dep)

sanitised_dependencies = [
bazel.sanitised_repo_library_label(d, repo_prefix=repo_prefix) for d in whl_deps
_sanitised_repo_library_label(d, repo_prefix=repo_prefix) for d in whl_deps
]
sanitised_wheel_file_dependencies = [
bazel.sanitised_repo_file_label(d, repo_prefix=repo_prefix) for d in whl_deps
_sanitised_repo_file_label(d, repo_prefix=repo_prefix) for d in whl_deps
]

entry_points = []
for name, (module, attribute) in sorted(whl.entry_points().items()):
# There is an extreme edge-case with entry_points that end with `.py`
# See: https://github.com/bazelbuild/bazel/blob/09c621e4cf5b968f4c6cdf905ab142d5961f9ddc/src/test/java/com/google/devtools/build/lib/rules/python/PyBinaryConfiguredTargetTest.java#L174
entry_point_without_py = f"{name[:-3]}_py" if name.endswith(".py") else name
entry_point_target_name = (
f"{bazel.WHEEL_ENTRY_POINT_PREFIX}_{entry_point_without_py}"
)
entry_point_script_name = f"{entry_point_target_name}.py"
(installation_dir / entry_point_script_name).write_text(
_generate_entry_point_contents(module, attribute)
)
entry_points.append(
_generate_entry_point_rule(
entry_point_target_name,
entry_point_script_name,
bazel.PY_LIBRARY_LABEL,
)
)

with open(os.path.join(installation_dir, "BUILD.bazel"), "w") as build_file:
with open(os.path.join(incremental_dir, "BUILD.bazel"), "w") as build_file:
additional_content = entry_points
data = []
data_exclude = pip_data_exclude
Expand All@@ -355,7 +271,7 @@ def _extract_wheel(
additional_content.append(annotation.additive_build_content)

contents = _generate_build_file_contents(
name=bazel.PY_LIBRARY_LABEL,
name="pkg",
dependencies=sanitised_dependencies,
whl_file_deps=sanitised_wheel_file_dependencies,
data_exclude=data_exclude,
Expand Down
24 changes: 0 additions & 24 deletions python/pip_install/tools/wheel_installer/wheel_installer_test.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -40,30 +40,6 @@ def test_parses_requirement_for_extra(self) -> None:
)


class BazelTestCase(unittest.TestCase):
def test_generate_entry_point_contents(self):
got = wheel_installer._generate_entry_point_contents("sphinx.cmd.build", "main")
want = """#!/usr/bin/env python3
import sys
from sphinx.cmd.build import main
if __name__ == "__main__":
sys.exit(main())
"""
self.assertEqual(got, want)

def test_generate_entry_point_contents_with_shebang(self):
got = wheel_installer._generate_entry_point_contents(
"sphinx.cmd.build", "main", shebang="#!/usr/bin/python"
)
want = """#!/usr/bin/python
import sys
from sphinx.cmd.build import main
if __name__ == "__main__":
sys.exit(main())
"""
self.assertEqual(got, want)


class TestWhlFilegroup(unittest.TestCase):
def setUp(self) -> None:
self.wheel_name = "example_minimal_package-0.0.1-py3-none-any.whl"
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 0 additions & 23 deletions python/pip_install/tools/lib/bazel.py
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,3 @@
WHEEL_FILE_LABEL = "whl"
PY_LIBRARY_LABEL = "pkg"
DATA_LABEL = "data"
DIST_INFO_LABEL = "dist_info"
WHEEL_ENTRY_POINT_PREFIX = "rules_python_wheel_entry_point"


def sanitise_name(name: str, prefix: str) -> str:
"""Sanitises the name to be compatible with Bazel labels.

Expand All@@ -23,19 +16,3 @@ def sanitise_name(name: str, prefix: str) -> str:
"""

return prefix + name.replace("-", "_").replace(".", "_").lower()


def _whl_name_to_repo_root(whl_name: str, repo_prefix: str) -> str:
return "@{}//".format(sanitise_name(whl_name, prefix=repo_prefix))


def sanitised_repo_library_label(whl_name: str, repo_prefix: str) -> str:
return '"{}:{}"'.format(
_whl_name_to_repo_root(whl_name, repo_prefix), PY_LIBRARY_LABEL
)


def sanitised_repo_file_label(whl_name: str, repo_prefix: str) -> str:
return '"{}:{}"'.format(
_whl_name_to_repo_root(whl_name, repo_prefix), WHEEL_FILE_LABEL
)
Original file line numberDiff line numberDiff line change
Expand Up@@ -95,7 +95,6 @@ def parse_whl_library_args(args: argparse.Namespace) -> Dict[str, Any]:

def generate_parsed_requirements_contents(
requirements_lock: Path,
repo: str,
repo_prefix: str,
whl_library_args: Dict[str, Any],
annotations: Dict[str, str] = dict(),
Expand All@@ -115,19 +114,6 @@ def generate_parsed_requirements_contents(
install_req_and_lines, repo_prefix
)

all_requirements = ", ".join(
[
bazel.sanitised_repo_library_label(ir.name, repo_prefix=repo_prefix)
for ir, _ in install_req_and_lines
]
)
all_whl_requirements = ", ".join(
[
bazel.sanitised_repo_file_label(ir.name, repo_prefix=repo_prefix)
for ir, _ in install_req_and_lines
]
)

install_deps_macro = """
def install_deps(**whl_library_kwargs):
whl_config = dict(_config)
Expand All@@ -146,64 +132,37 @@ def install_deps(**whl_library_kwargs):

load("@rules_python//python/pip_install:pip_repository.bzl", "whl_library")

all_requirements = [{all_requirements}]

all_whl_requirements = [{all_whl_requirements}]

_packages = {repo_names_and_reqs}
_config = {args}
_annotations = {annotations}
_bzlmod = {bzlmod}

def _clean_name(name):
return name.replace("-", "_").replace(".", "_").lower()

def requirement(name):
if _bzlmod:
return "@@{repo}//:" + _clean_name(name) + "_{py_library_label}"
return "@{repo_prefix}" + _clean_name(name) + "//:{py_library_label}"
fail("This function has been replaced with a regular macro in TODO.bzl. Update your imports to TODO. See TODO for further migration details.")

def whl_requirement(name):
if _bzlmod:
return "@@{repo}//:" + _clean_name(name) + "_{wheel_file_label}"
return "@{repo_prefix}" + _clean_name(name) + "//:{wheel_file_label}"
fail("This function has been replaced with a regular macro in TODO.bzl. Update your imports to TODO. See TODO for further migration details.")

def data_requirement(name):
if _bzlmod:
return "@@{repo}//:" + _clean_name(name) + "_{data_label}"
return "@{repo_prefix}" + _clean_name(name) + "//:{data_label}"
fail("This function has been replaced with a regular macro in TODO.bzl. Update your imports to TODO. See TODO for further migration details.")

def dist_info_requirement(name):
if _bzlmod:
return "@@{repo}//:" + _clean_name(name) + "_{dist_info_label}"
return "@{repo_prefix}" + _clean_name(name) + "//:{dist_info_label}"
fail("This function has been replaced with a regular macro in TODO.bzl. Update your imports to TODO. See TODO for further migration details.")

def entry_point(pkg, script = None):
if not script:
script = pkg
return "@{repo_prefix}" + _clean_name(pkg) + "//:{entry_point_prefix}_" + script
fail("This function has been replaced with a regular macro in TODO.bzl. Update your imports to TODO. See TODO for further migration details.")

def _get_annotation(requirement):
# TODO(greg) Consider deprecating the annotation functionality to occur
# This expects to parse `setuptools==58.2.0 --hash=sha256:2551203ae6955b9876741a26ab3e767bb3242dafe86a32a749ea0d78b6792f11`
# down wo `setuptools`.
name = requirement.split(" ")[0].split("=")[0].split("[")[0]
return _annotations.get(name)
"""
+ (install_deps_macro if not bzlmod else "")
).format(
all_requirements=all_requirements,
all_whl_requirements=all_whl_requirements,
annotations=json.dumps(annotations),
args=dict(sorted(whl_library_args.items())),
data_label=bazel.DATA_LABEL,
dist_info_label=bazel.DIST_INFO_LABEL,
entry_point_prefix=bazel.WHEEL_ENTRY_POINT_PREFIX,
py_library_label=bazel.PY_LIBRARY_LABEL,
repo_names_and_reqs=repo_names_and_reqs,
repo=repo,
repo_prefix=repo_prefix,
wheel_file_label=bazel.WHEEL_FILE_LABEL,
bzlmod=bzlmod,
)
)

Expand DownExpand Up@@ -308,7 +267,6 @@ def main(output: TextIO) -> None:
output.write(
generate_parsed_requirements_contents(
requirements_lock=args.requirements_lock,
repo=args.repo,
repo_prefix=args.repo_prefix,
whl_library_args=whl_library_args,
annotations=annotated_requirements,
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -35,20 +35,11 @@ def test_generated_requirements_bzl(self) -> None:
whl_library_args = lock_file_generator.parse_whl_library_args(args)
contents = lock_file_generator.generate_parsed_requirements_contents(
requirements_lock=args.requirements_lock,
repo=args.repo,
repo_prefix=args.repo_prefix,
whl_library_args=whl_library_args,
)
library_target = "@pip_parsed_deps_pypi__foo//:pkg"
whl_target = "@pip_parsed_deps_pypi__foo//:whl"
all_requirements = 'all_requirements = ["{library_target}"]'.format(
library_target=library_target
)
all_whl_requirements = 'all_whl_requirements = ["{whl_target}"]'.format(
whl_target=whl_target
)
self.assertIn(all_requirements, contents, contents)
self.assertIn(all_whl_requirements, contents, contents)
self.assertIn(requirement_string, contents, contents)
all_flags = extra_pip_args + ["--require-hashes", "True"]
self.assertIn(
Expand Down
98 changes: 7 additions & 91 deletions python/pip_install/tools/wheel_installer/wheel_installer.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -89,66 +89,6 @@ def _setup_namespace_pkg_compatibility(wheel_dir: str) -> None:
namespace_pkgs.add_pkgutil_style_namespace_pkg_init(ns_pkg_dir)


def _generate_entry_point_contents(
module: str, attribute: str, shebang: str = "#!/usr/bin/env python3"
) -> str:
"""Generate the contents of an entry point script.

Args:
module (str): The name of the module to use.
attribute (str): The name of the attribute to call.
shebang (str, optional): The shebang to use for the entry point python
file.

Returns:
str: A string of python code.
"""
return textwrap.dedent(
"""\
{shebang}
import sys
from {module} import {attribute}
if __name__ == "__main__":
sys.exit({attribute}())
""".format(
shebang=shebang, module=module, attribute=attribute
)
)


def _generate_entry_point_rule(name: str, script: str, pkg: str) -> str:
"""Generate a Bazel `py_binary` rule for an entry point script.

Note that the script is used to determine the name of the target. The name of
entry point targets should be uniuqe to avoid conflicts with existing sources or
directories within a wheel.

Args:
name (str): The name of the generated py_binary.
script (str): The path to the entry point's python file.
pkg (str): The package owning the entry point. This is expected to
match up with the `py_library` defined for each repository.


Returns:
str: A `py_binary` instantiation.
"""
return textwrap.dedent(
"""\
py_binary(
name = "{name}",
srcs = ["{src}"],
# This makes this directory a top-level in the python import
# search path for anything that depends on this.
imports = ["."],
deps = ["{pkg}"],
)
""".format(
name=name, src=str(script).replace("\\", "/"), pkg=pkg
)
)


def _generate_copy_commands(src, dest, is_executable=False) -> str:
"""Generate a [@bazel_skylib//rules:copy_file.bzl%copy_file][cf] target

Expand DownExpand Up@@ -231,17 +171,17 @@ def _generate_build_file_contents(
package(default_visibility = ["//visibility:public"])

filegroup(
name = "{dist_info_label}",
name = "dist_info",
srcs = glob(["site-packages/*.dist-info/**"], allow_empty = True),
)

filegroup(
name = "{data_label}",
name = "data",
srcs = glob(["data/**"], allow_empty = True),
)

filegroup(
name = "{whl_file_label}",
name = "whl",
srcs = glob(["*.whl"], allow_empty = True),
data = [{whl_file_deps}],
)
Expand All@@ -260,12 +200,8 @@ def _generate_build_file_contents(
name=name,
dependencies=",".join(sorted(dependencies)),
data_exclude=json.dumps(sorted(data_exclude)),
whl_file_label=bazel.WHEEL_FILE_LABEL,
whl_file_deps=",".join(sorted(whl_file_deps)),
tags=",".join(sorted(['"%s"' % t for t in tags])),
data_label=bazel.DATA_LABEL,
dist_info_label=bazel.DIST_INFO_LABEL,
entry_point_prefix=bazel.WHEEL_ENTRY_POINT_PREFIX,
srcs_exclude=json.dumps(sorted(srcs_exclude)),
data=json.dumps(sorted(data)),
)
Expand DownExpand Up@@ -308,33 +244,13 @@ def _extract_wheel(
whl_deps = sorted(whl.dependencies(extras_requested) - self_edge_dep)

sanitised_dependencies = [
bazel.sanitised_repo_library_label(d, repo_prefix=repo_prefix) for d in whl_deps
_sanitised_repo_library_label(d, repo_prefix=repo_prefix) for d in whl_deps
]
sanitised_wheel_file_dependencies = [
bazel.sanitised_repo_file_label(d, repo_prefix=repo_prefix) for d in whl_deps
_sanitised_repo_file_label(d, repo_prefix=repo_prefix) for d in whl_deps
]

entry_points = []
for name, (module, attribute) in sorted(whl.entry_points().items()):
# There is an extreme edge-case with entry_points that end with `.py`
# See: https://github.com/bazelbuild/bazel/blob/09c621e4cf5b968f4c6cdf905ab142d5961f9ddc/src/test/java/com/google/devtools/build/lib/rules/python/PyBinaryConfiguredTargetTest.java#L174
entry_point_without_py = f"{name[:-3]}_py" if name.endswith(".py") else name
entry_point_target_name = (
f"{bazel.WHEEL_ENTRY_POINT_PREFIX}_{entry_point_without_py}"
)
entry_point_script_name = f"{entry_point_target_name}.py"
(installation_dir / entry_point_script_name).write_text(
_generate_entry_point_contents(module, attribute)
)
entry_points.append(
_generate_entry_point_rule(
entry_point_target_name,
entry_point_script_name,
bazel.PY_LIBRARY_LABEL,
)
)

with open(os.path.join(installation_dir, "BUILD.bazel"), "w") as build_file:
with open(os.path.join(incremental_dir, "BUILD.bazel"), "w") as build_file:
additional_content = entry_points
data = []
data_exclude = pip_data_exclude
Expand All@@ -355,7 +271,7 @@ def _extract_wheel(
additional_content.append(annotation.additive_build_content)

contents = _generate_build_file_contents(
name=bazel.PY_LIBRARY_LABEL,
name="pkg",
dependencies=sanitised_dependencies,
whl_file_deps=sanitised_wheel_file_dependencies,
data_exclude=data_exclude,
Expand Down
24 changes: 0 additions & 24 deletions python/pip_install/tools/wheel_installer/wheel_installer_test.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -40,30 +40,6 @@ def test_parses_requirement_for_extra(self) -> None:
)


class BazelTestCase(unittest.TestCase):
def test_generate_entry_point_contents(self):
got = wheel_installer._generate_entry_point_contents("sphinx.cmd.build", "main")
want = """#!/usr/bin/env python3
import sys
from sphinx.cmd.build import main
if __name__ == "__main__":
sys.exit(main())
"""
self.assertEqual(got, want)

def test_generate_entry_point_contents_with_shebang(self):
got = wheel_installer._generate_entry_point_contents(
"sphinx.cmd.build", "main", shebang="#!/usr/bin/python"
)
want = """#!/usr/bin/python
import sys
from sphinx.cmd.build import main
if __name__ == "__main__":
sys.exit(main())
"""
self.assertEqual(got, want)


class TestWhlFilegroup(unittest.TestCase):
def setUp(self) -> None:
self.wheel_name = "example_minimal_package-0.0.1-py3-none-any.whl"
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 0 additions & 23 deletions python/pip_install/tools/lib/bazel.py
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,3 @@
WHEEL_FILE_LABEL = "whl"
PY_LIBRARY_LABEL = "pkg"
DATA_LABEL = "data"
DIST_INFO_LABEL = "dist_info"
WHEEL_ENTRY_POINT_PREFIX = "rules_python_wheel_entry_point"


def sanitise_name(name: str, prefix: str) -> str:
"""Sanitises the name to be compatible with Bazel labels.

Expand All@@ -23,19 +16,3 @@ def sanitise_name(name: str, prefix: str) -> str:
"""

return prefix + name.replace("-", "_").replace(".", "_").lower()


def _whl_name_to_repo_root(whl_name: str, repo_prefix: str) -> str:
return "@{}//".format(sanitise_name(whl_name, prefix=repo_prefix))


def sanitised_repo_library_label(whl_name: str, repo_prefix: str) -> str:
return '"{}:{}"'.format(
_whl_name_to_repo_root(whl_name, repo_prefix), PY_LIBRARY_LABEL
)


def sanitised_repo_file_label(whl_name: str, repo_prefix: str) -> str:
return '"{}:{}"'.format(
_whl_name_to_repo_root(whl_name, repo_prefix), WHEEL_FILE_LABEL
)
Original file line numberDiff line numberDiff line change
Expand Up@@ -95,7 +95,6 @@ def parse_whl_library_args(args: argparse.Namespace) -> Dict[str, Any]:

def generate_parsed_requirements_contents(
requirements_lock: Path,
repo: str,
repo_prefix: str,
whl_library_args: Dict[str, Any],
annotations: Dict[str, str] = dict(),
Expand All@@ -115,19 +114,6 @@ def generate_parsed_requirements_contents(
install_req_and_lines, repo_prefix
)

all_requirements = ", ".join(
[
bazel.sanitised_repo_library_label(ir.name, repo_prefix=repo_prefix)
for ir, _ in install_req_and_lines
]
)
all_whl_requirements = ", ".join(
[
bazel.sanitised_repo_file_label(ir.name, repo_prefix=repo_prefix)
for ir, _ in install_req_and_lines
]
)

install_deps_macro = """
def install_deps(**whl_library_kwargs):
whl_config = dict(_config)
Expand All@@ -146,64 +132,37 @@ def install_deps(**whl_library_kwargs):

load("@rules_python//python/pip_install:pip_repository.bzl", "whl_library")

all_requirements = [{all_requirements}]

all_whl_requirements = [{all_whl_requirements}]

_packages = {repo_names_and_reqs}
_config = {args}
_annotations = {annotations}
_bzlmod = {bzlmod}

def _clean_name(name):
return name.replace("-", "_").replace(".", "_").lower()

def requirement(name):
if _bzlmod:
return "@@{repo}//:" + _clean_name(name) + "_{py_library_label}"
return "@{repo_prefix}" + _clean_name(name) + "//:{py_library_label}"
fail("This function has been replaced with a regular macro in TODO.bzl. Update your imports to TODO. See TODO for further migration details.")

def whl_requirement(name):
if _bzlmod:
return "@@{repo}//:" + _clean_name(name) + "_{wheel_file_label}"
return "@{repo_prefix}" + _clean_name(name) + "//:{wheel_file_label}"
fail("This function has been replaced with a regular macro in TODO.bzl. Update your imports to TODO. See TODO for further migration details.")

def data_requirement(name):
if _bzlmod:
return "@@{repo}//:" + _clean_name(name) + "_{data_label}"
return "@{repo_prefix}" + _clean_name(name) + "//:{data_label}"
fail("This function has been replaced with a regular macro in TODO.bzl. Update your imports to TODO. See TODO for further migration details.")

def dist_info_requirement(name):
if _bzlmod:
return "@@{repo}//:" + _clean_name(name) + "_{dist_info_label}"
return "@{repo_prefix}" + _clean_name(name) + "//:{dist_info_label}"
fail("This function has been replaced with a regular macro in TODO.bzl. Update your imports to TODO. See TODO for further migration details.")

def entry_point(pkg, script = None):
if not script:
script = pkg
return "@{repo_prefix}" + _clean_name(pkg) + "//:{entry_point_prefix}_" + script
fail("This function has been replaced with a regular macro in TODO.bzl. Update your imports to TODO. See TODO for further migration details.")

def _get_annotation(requirement):
# TODO(greg) Consider deprecating the annotation functionality to occur
# This expects to parse `setuptools==58.2.0 --hash=sha256:2551203ae6955b9876741a26ab3e767bb3242dafe86a32a749ea0d78b6792f11`
# down wo `setuptools`.
name = requirement.split(" ")[0].split("=")[0].split("[")[0]
return _annotations.get(name)
"""
+ (install_deps_macro if not bzlmod else "")
).format(
all_requirements=all_requirements,
all_whl_requirements=all_whl_requirements,
annotations=json.dumps(annotations),
args=dict(sorted(whl_library_args.items())),
data_label=bazel.DATA_LABEL,
dist_info_label=bazel.DIST_INFO_LABEL,
entry_point_prefix=bazel.WHEEL_ENTRY_POINT_PREFIX,
py_library_label=bazel.PY_LIBRARY_LABEL,
repo_names_and_reqs=repo_names_and_reqs,
repo=repo,
repo_prefix=repo_prefix,
wheel_file_label=bazel.WHEEL_FILE_LABEL,
bzlmod=bzlmod,
)
)

Expand DownExpand Up@@ -308,7 +267,6 @@ def main(output: TextIO) -> None:
output.write(
generate_parsed_requirements_contents(
requirements_lock=args.requirements_lock,
repo=args.repo,
repo_prefix=args.repo_prefix,
whl_library_args=whl_library_args,
annotations=annotated_requirements,
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -35,20 +35,11 @@ def test_generated_requirements_bzl(self) -> None:
whl_library_args = lock_file_generator.parse_whl_library_args(args)
contents = lock_file_generator.generate_parsed_requirements_contents(
requirements_lock=args.requirements_lock,
repo=args.repo,
repo_prefix=args.repo_prefix,
whl_library_args=whl_library_args,
)
library_target = "@pip_parsed_deps_pypi__foo//:pkg"
whl_target = "@pip_parsed_deps_pypi__foo//:whl"
all_requirements = 'all_requirements = ["{library_target}"]'.format(
library_target=library_target
)
all_whl_requirements = 'all_whl_requirements = ["{whl_target}"]'.format(
whl_target=whl_target
)
self.assertIn(all_requirements, contents, contents)
self.assertIn(all_whl_requirements, contents, contents)
self.assertIn(requirement_string, contents, contents)
all_flags = extra_pip_args + ["--require-hashes", "True"]
self.assertIn(
Expand Down
98 changes: 7 additions & 91 deletions python/pip_install/tools/wheel_installer/wheel_installer.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -89,66 +89,6 @@ def _setup_namespace_pkg_compatibility(wheel_dir: str) -> None:
namespace_pkgs.add_pkgutil_style_namespace_pkg_init(ns_pkg_dir)


def _generate_entry_point_contents(
module: str, attribute: str, shebang: str = "#!/usr/bin/env python3"
) -> str:
"""Generate the contents of an entry point script.

Args:
module (str): The name of the module to use.
attribute (str): The name of the attribute to call.
shebang (str, optional): The shebang to use for the entry point python
file.

Returns:
str: A string of python code.
"""
return textwrap.dedent(
"""\
{shebang}
import sys
from {module} import {attribute}
if __name__ == "__main__":
sys.exit({attribute}())
""".format(
shebang=shebang, module=module, attribute=attribute
)
)


def _generate_entry_point_rule(name: str, script: str, pkg: str) -> str:
"""Generate a Bazel `py_binary` rule for an entry point script.

Note that the script is used to determine the name of the target. The name of
entry point targets should be uniuqe to avoid conflicts with existing sources or
directories within a wheel.

Args:
name (str): The name of the generated py_binary.
script (str): The path to the entry point's python file.
pkg (str): The package owning the entry point. This is expected to
match up with the `py_library` defined for each repository.


Returns:
str: A `py_binary` instantiation.
"""
return textwrap.dedent(
"""\
py_binary(
name = "{name}",
srcs = ["{src}"],
# This makes this directory a top-level in the python import
# search path for anything that depends on this.
imports = ["."],
deps = ["{pkg}"],
)
""".format(
name=name, src=str(script).replace("\\", "/"), pkg=pkg
)
)


def _generate_copy_commands(src, dest, is_executable=False) -> str:
"""Generate a [@bazel_skylib//rules:copy_file.bzl%copy_file][cf] target

Expand DownExpand Up@@ -231,17 +171,17 @@ def _generate_build_file_contents(
package(default_visibility = ["//visibility:public"])

filegroup(
name = "{dist_info_label}",
name = "dist_info",
srcs = glob(["site-packages/*.dist-info/**"], allow_empty = True),
)

filegroup(
name = "{data_label}",
name = "data",
srcs = glob(["data/**"], allow_empty = True),
)

filegroup(
name = "{whl_file_label}",
name = "whl",
srcs = glob(["*.whl"], allow_empty = True),
data = [{whl_file_deps}],
)
Expand All@@ -260,12 +200,8 @@ def _generate_build_file_contents(
name=name,
dependencies=",".join(sorted(dependencies)),
data_exclude=json.dumps(sorted(data_exclude)),
whl_file_label=bazel.WHEEL_FILE_LABEL,
whl_file_deps=",".join(sorted(whl_file_deps)),
tags=",".join(sorted(['"%s"' % t for t in tags])),
data_label=bazel.DATA_LABEL,
dist_info_label=bazel.DIST_INFO_LABEL,
entry_point_prefix=bazel.WHEEL_ENTRY_POINT_PREFIX,
srcs_exclude=json.dumps(sorted(srcs_exclude)),
data=json.dumps(sorted(data)),
)
Expand DownExpand Up@@ -308,33 +244,13 @@ def _extract_wheel(
whl_deps = sorted(whl.dependencies(extras_requested) - self_edge_dep)

sanitised_dependencies = [
bazel.sanitised_repo_library_label(d, repo_prefix=repo_prefix) for d in whl_deps
_sanitised_repo_library_label(d, repo_prefix=repo_prefix) for d in whl_deps
]
sanitised_wheel_file_dependencies = [
bazel.sanitised_repo_file_label(d, repo_prefix=repo_prefix) for d in whl_deps
_sanitised_repo_file_label(d, repo_prefix=repo_prefix) for d in whl_deps
]

entry_points = []
for name, (module, attribute) in sorted(whl.entry_points().items()):
# There is an extreme edge-case with entry_points that end with `.py`
# See: https://github.com/bazelbuild/bazel/blob/09c621e4cf5b968f4c6cdf905ab142d5961f9ddc/src/test/java/com/google/devtools/build/lib/rules/python/PyBinaryConfiguredTargetTest.java#L174
entry_point_without_py = f"{name[:-3]}_py" if name.endswith(".py") else name
entry_point_target_name = (
f"{bazel.WHEEL_ENTRY_POINT_PREFIX}_{entry_point_without_py}"
)
entry_point_script_name = f"{entry_point_target_name}.py"
(installation_dir / entry_point_script_name).write_text(
_generate_entry_point_contents(module, attribute)
)
entry_points.append(
_generate_entry_point_rule(
entry_point_target_name,
entry_point_script_name,
bazel.PY_LIBRARY_LABEL,
)
)

with open(os.path.join(installation_dir, "BUILD.bazel"), "w") as build_file:
with open(os.path.join(incremental_dir, "BUILD.bazel"), "w") as build_file:
additional_content = entry_points
data = []
data_exclude = pip_data_exclude
Expand All@@ -355,7 +271,7 @@ def _extract_wheel(
additional_content.append(annotation.additive_build_content)

contents = _generate_build_file_contents(
name=bazel.PY_LIBRARY_LABEL,
name="pkg",
dependencies=sanitised_dependencies,
whl_file_deps=sanitised_wheel_file_dependencies,
data_exclude=data_exclude,
Expand Down
24 changes: 0 additions & 24 deletions python/pip_install/tools/wheel_installer/wheel_installer_test.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -40,30 +40,6 @@ def test_parses_requirement_for_extra(self) -> None:
)


class BazelTestCase(unittest.TestCase):
def test_generate_entry_point_contents(self):
got = wheel_installer._generate_entry_point_contents("sphinx.cmd.build", "main")
want = """#!/usr/bin/env python3
import sys
from sphinx.cmd.build import main
if __name__ == "__main__":
sys.exit(main())
"""
self.assertEqual(got, want)

def test_generate_entry_point_contents_with_shebang(self):
got = wheel_installer._generate_entry_point_contents(
"sphinx.cmd.build", "main", shebang="#!/usr/bin/python"
)
want = """#!/usr/bin/python
import sys
from sphinx.cmd.build import main
if __name__ == "__main__":
sys.exit(main())
"""
self.assertEqual(got, want)


class TestWhlFilegroup(unittest.TestCase):
def setUp(self) -> None:
self.wheel_name = "example_minimal_package-0.0.1-py3-none-any.whl"
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 0 additions & 23 deletions python/pip_install/tools/lib/bazel.py
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,3 @@
WHEEL_FILE_LABEL = "whl"
PY_LIBRARY_LABEL = "pkg"
DATA_LABEL = "data"
DIST_INFO_LABEL = "dist_info"
WHEEL_ENTRY_POINT_PREFIX = "rules_python_wheel_entry_point"


def sanitise_name(name: str, prefix: str) -> str:
"""Sanitises the name to be compatible with Bazel labels.

Expand All@@ -23,19 +16,3 @@ def sanitise_name(name: str, prefix: str) -> str:
"""

return prefix + name.replace("-", "_").replace(".", "_").lower()


def _whl_name_to_repo_root(whl_name: str, repo_prefix: str) -> str:
return "@{}//".format(sanitise_name(whl_name, prefix=repo_prefix))


def sanitised_repo_library_label(whl_name: str, repo_prefix: str) -> str:
return '"{}:{}"'.format(
_whl_name_to_repo_root(whl_name, repo_prefix), PY_LIBRARY_LABEL
)


def sanitised_repo_file_label(whl_name: str, repo_prefix: str) -> str:
return '"{}:{}"'.format(
_whl_name_to_repo_root(whl_name, repo_prefix), WHEEL_FILE_LABEL
)
Original file line numberDiff line numberDiff line change
Expand Up@@ -95,7 +95,6 @@ def parse_whl_library_args(args: argparse.Namespace) -> Dict[str, Any]:

def generate_parsed_requirements_contents(
requirements_lock: Path,
repo: str,
repo_prefix: str,
whl_library_args: Dict[str, Any],
annotations: Dict[str, str] = dict(),
Expand All@@ -115,19 +114,6 @@ def generate_parsed_requirements_contents(
install_req_and_lines, repo_prefix
)

all_requirements = ", ".join(
[
bazel.sanitised_repo_library_label(ir.name, repo_prefix=repo_prefix)
for ir, _ in install_req_and_lines
]
)
all_whl_requirements = ", ".join(
[
bazel.sanitised_repo_file_label(ir.name, repo_prefix=repo_prefix)
for ir, _ in install_req_and_lines
]
)

install_deps_macro = """
def install_deps(**whl_library_kwargs):
whl_config = dict(_config)
Expand All@@ -146,64 +132,37 @@ def install_deps(**whl_library_kwargs):

load("@rules_python//python/pip_install:pip_repository.bzl", "whl_library")

all_requirements = [{all_requirements}]

all_whl_requirements = [{all_whl_requirements}]

_packages = {repo_names_and_reqs}
_config = {args}
_annotations = {annotations}
_bzlmod = {bzlmod}

def _clean_name(name):
return name.replace("-", "_").replace(".", "_").lower()

def requirement(name):
if _bzlmod:
return "@@{repo}//:" + _clean_name(name) + "_{py_library_label}"
return "@{repo_prefix}" + _clean_name(name) + "//:{py_library_label}"
fail("This function has been replaced with a regular macro in TODO.bzl. Update your imports to TODO. See TODO for further migration details.")

def whl_requirement(name):
if _bzlmod:
return "@@{repo}//:" + _clean_name(name) + "_{wheel_file_label}"
return "@{repo_prefix}" + _clean_name(name) + "//:{wheel_file_label}"
fail("This function has been replaced with a regular macro in TODO.bzl. Update your imports to TODO. See TODO for further migration details.")

def data_requirement(name):
if _bzlmod:
return "@@{repo}//:" + _clean_name(name) + "_{data_label}"
return "@{repo_prefix}" + _clean_name(name) + "//:{data_label}"
fail("This function has been replaced with a regular macro in TODO.bzl. Update your imports to TODO. See TODO for further migration details.")

def dist_info_requirement(name):
if _bzlmod:
return "@@{repo}//:" + _clean_name(name) + "_{dist_info_label}"
return "@{repo_prefix}" + _clean_name(name) + "//:{dist_info_label}"
fail("This function has been replaced with a regular macro in TODO.bzl. Update your imports to TODO. See TODO for further migration details.")

def entry_point(pkg, script = None):
if not script:
script = pkg
return "@{repo_prefix}" + _clean_name(pkg) + "//:{entry_point_prefix}_" + script
fail("This function has been replaced with a regular macro in TODO.bzl. Update your imports to TODO. See TODO for further migration details.")

def _get_annotation(requirement):
# TODO(greg) Consider deprecating the annotation functionality to occur
# This expects to parse `setuptools==58.2.0 --hash=sha256:2551203ae6955b9876741a26ab3e767bb3242dafe86a32a749ea0d78b6792f11`
# down wo `setuptools`.
name = requirement.split(" ")[0].split("=")[0].split("[")[0]
return _annotations.get(name)
"""
+ (install_deps_macro if not bzlmod else "")
).format(
all_requirements=all_requirements,
all_whl_requirements=all_whl_requirements,
annotations=json.dumps(annotations),
args=dict(sorted(whl_library_args.items())),
data_label=bazel.DATA_LABEL,
dist_info_label=bazel.DIST_INFO_LABEL,
entry_point_prefix=bazel.WHEEL_ENTRY_POINT_PREFIX,
py_library_label=bazel.PY_LIBRARY_LABEL,
repo_names_and_reqs=repo_names_and_reqs,
repo=repo,
repo_prefix=repo_prefix,
wheel_file_label=bazel.WHEEL_FILE_LABEL,
bzlmod=bzlmod,
)
)

Expand DownExpand Up@@ -308,7 +267,6 @@ def main(output: TextIO) -> None:
output.write(
generate_parsed_requirements_contents(
requirements_lock=args.requirements_lock,
repo=args.repo,
repo_prefix=args.repo_prefix,
whl_library_args=whl_library_args,
annotations=annotated_requirements,
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -35,20 +35,11 @@ def test_generated_requirements_bzl(self) -> None:
whl_library_args = lock_file_generator.parse_whl_library_args(args)
contents = lock_file_generator.generate_parsed_requirements_contents(
requirements_lock=args.requirements_lock,
repo=args.repo,
repo_prefix=args.repo_prefix,
whl_library_args=whl_library_args,
)
library_target = "@pip_parsed_deps_pypi__foo//:pkg"
whl_target = "@pip_parsed_deps_pypi__foo//:whl"
all_requirements = 'all_requirements = ["{library_target}"]'.format(
library_target=library_target
)
all_whl_requirements = 'all_whl_requirements = ["{whl_target}"]'.format(
whl_target=whl_target
)
self.assertIn(all_requirements, contents, contents)
self.assertIn(all_whl_requirements, contents, contents)
self.assertIn(requirement_string, contents, contents)
all_flags = extra_pip_args + ["--require-hashes", "True"]
self.assertIn(
Expand Down
98 changes: 7 additions & 91 deletions python/pip_install/tools/wheel_installer/wheel_installer.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -89,66 +89,6 @@ def _setup_namespace_pkg_compatibility(wheel_dir: str) -> None:
namespace_pkgs.add_pkgutil_style_namespace_pkg_init(ns_pkg_dir)


def _generate_entry_point_contents(
module: str, attribute: str, shebang: str = "#!/usr/bin/env python3"
) -> str:
"""Generate the contents of an entry point script.

Args:
module (str): The name of the module to use.
attribute (str): The name of the attribute to call.
shebang (str, optional): The shebang to use for the entry point python
file.

Returns:
str: A string of python code.
"""
return textwrap.dedent(
"""\
{shebang}
import sys
from {module} import {attribute}
if __name__ == "__main__":
sys.exit({attribute}())
""".format(
shebang=shebang, module=module, attribute=attribute
)
)


def _generate_entry_point_rule(name: str, script: str, pkg: str) -> str:
"""Generate a Bazel `py_binary` rule for an entry point script.

Note that the script is used to determine the name of the target. The name of
entry point targets should be uniuqe to avoid conflicts with existing sources or
directories within a wheel.

Args:
name (str): The name of the generated py_binary.
script (str): The path to the entry point's python file.
pkg (str): The package owning the entry point. This is expected to
match up with the `py_library` defined for each repository.


Returns:
str: A `py_binary` instantiation.
"""
return textwrap.dedent(
"""\
py_binary(
name = "{name}",
srcs = ["{src}"],
# This makes this directory a top-level in the python import
# search path for anything that depends on this.
imports = ["."],
deps = ["{pkg}"],
)
""".format(
name=name, src=str(script).replace("\\", "/"), pkg=pkg
)
)


def _generate_copy_commands(src, dest, is_executable=False) -> str:
"""Generate a [@bazel_skylib//rules:copy_file.bzl%copy_file][cf] target

Expand DownExpand Up@@ -231,17 +171,17 @@ def _generate_build_file_contents(
package(default_visibility = ["//visibility:public"])

filegroup(
name = "{dist_info_label}",
name = "dist_info",
srcs = glob(["site-packages/*.dist-info/**"], allow_empty = True),
)

filegroup(
name = "{data_label}",
name = "data",
srcs = glob(["data/**"], allow_empty = True),
)

filegroup(
name = "{whl_file_label}",
name = "whl",
srcs = glob(["*.whl"], allow_empty = True),
data = [{whl_file_deps}],
)
Expand All@@ -260,12 +200,8 @@ def _generate_build_file_contents(
name=name,
dependencies=",".join(sorted(dependencies)),
data_exclude=json.dumps(sorted(data_exclude)),
whl_file_label=bazel.WHEEL_FILE_LABEL,
whl_file_deps=",".join(sorted(whl_file_deps)),
tags=",".join(sorted(['"%s"' % t for t in tags])),
data_label=bazel.DATA_LABEL,
dist_info_label=bazel.DIST_INFO_LABEL,
entry_point_prefix=bazel.WHEEL_ENTRY_POINT_PREFIX,
srcs_exclude=json.dumps(sorted(srcs_exclude)),
data=json.dumps(sorted(data)),
)
Expand DownExpand Up@@ -308,33 +244,13 @@ def _extract_wheel(
whl_deps = sorted(whl.dependencies(extras_requested) - self_edge_dep)

sanitised_dependencies = [
bazel.sanitised_repo_library_label(d, repo_prefix=repo_prefix) for d in whl_deps
_sanitised_repo_library_label(d, repo_prefix=repo_prefix) for d in whl_deps
]
sanitised_wheel_file_dependencies = [
bazel.sanitised_repo_file_label(d, repo_prefix=repo_prefix) for d in whl_deps
_sanitised_repo_file_label(d, repo_prefix=repo_prefix) for d in whl_deps
]

entry_points = []
for name, (module, attribute) in sorted(whl.entry_points().items()):
# There is an extreme edge-case with entry_points that end with `.py`
# See: https://github.com/bazelbuild/bazel/blob/09c621e4cf5b968f4c6cdf905ab142d5961f9ddc/src/test/java/com/google/devtools/build/lib/rules/python/PyBinaryConfiguredTargetTest.java#L174
entry_point_without_py = f"{name[:-3]}_py" if name.endswith(".py") else name
entry_point_target_name = (
f"{bazel.WHEEL_ENTRY_POINT_PREFIX}_{entry_point_without_py}"
)
entry_point_script_name = f"{entry_point_target_name}.py"
(installation_dir / entry_point_script_name).write_text(
_generate_entry_point_contents(module, attribute)
)
entry_points.append(
_generate_entry_point_rule(
entry_point_target_name,
entry_point_script_name,
bazel.PY_LIBRARY_LABEL,
)
)

with open(os.path.join(installation_dir, "BUILD.bazel"), "w") as build_file:
with open(os.path.join(incremental_dir, "BUILD.bazel"), "w") as build_file:
additional_content = entry_points
data = []
data_exclude = pip_data_exclude
Expand All@@ -355,7 +271,7 @@ def _extract_wheel(
additional_content.append(annotation.additive_build_content)

contents = _generate_build_file_contents(
name=bazel.PY_LIBRARY_LABEL,
name="pkg",
dependencies=sanitised_dependencies,
whl_file_deps=sanitised_wheel_file_dependencies,
data_exclude=data_exclude,
Expand Down
24 changes: 0 additions & 24 deletions python/pip_install/tools/wheel_installer/wheel_installer_test.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -40,30 +40,6 @@ def test_parses_requirement_for_extra(self) -> None:
)


class BazelTestCase(unittest.TestCase):
def test_generate_entry_point_contents(self):
got = wheel_installer._generate_entry_point_contents("sphinx.cmd.build", "main")
want = """#!/usr/bin/env python3
import sys
from sphinx.cmd.build import main
if __name__ == "__main__":
sys.exit(main())
"""
self.assertEqual(got, want)

def test_generate_entry_point_contents_with_shebang(self):
got = wheel_installer._generate_entry_point_contents(
"sphinx.cmd.build", "main", shebang="#!/usr/bin/python"
)
want = """#!/usr/bin/python
import sys
from sphinx.cmd.build import main
if __name__ == "__main__":
sys.exit(main())
"""
self.assertEqual(got, want)


class TestWhlFilegroup(unittest.TestCase):
def setUp(self) -> None:
self.wheel_name = "example_minimal_package-0.0.1-py3-none-any.whl"
Expand Down