Skip to content
Open
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
30 changes: 30 additions & 0 deletions src/_bentoml_sdk/images.py
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,36 @@ def python_packages(self, *packages: str) -> t.Self:
self._after_pip_install = True
return self

def apt_sources_mirror(self, url: str) -> t.Self:
"""Swap the Debian apt mirror URL before running apt-get. Supports chaining call.

This is useful for users in regions where the default Debian mirrors are slow.
The command tries both the Debian 12+ format (``debian.sources``) and the
legacy ``sources.list`` format so it works across Debian releases.

Example:

.. code-block:: python

image = (
Image("debian:latest")
.apt_sources_mirror("https://mirrors.tuna.tsinghua.edu.cn/debian")
.system_packages("curl")
)

Args:
url: The mirror URL to use, e.g. ``https://mirrors.tuna.tsinghua.edu.cn/debian``.

Returns:
The current :class:`Image` instance (chainable).
"""
sed_cmd = (
f"sed -i 's|http://deb.debian.org/debian|{url}|g'"
" /etc/apt/sources.list.d/debian.sources 2>/dev/null ||"
f" sed -i 's|http://deb.debian.org/debian|{url}|g' /etc/apt/sources.list"
)
return self.run(sed_cmd)

def run(self, command: str) -> t.Self:
"""Add a command to the image. Supports chaining call.

Expand Down
20 changes: 20 additions & 0 deletions tests/unit/_bentoml_sdk/test_images.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,26 @@
from _bentoml_sdk.images import Image


def test_apt_sources_mirror_inserts_sed_command() -> None:
mirror = "https://mirrors.tuna.tsinghua.edu.cn/debian"
image = Image(distro="debian")
image.apt_sources_mirror(mirror)

# The sed command should be the last entry added to pre-pip commands
assert image.commands[-1] == (
f"sed -i 's|http://deb.debian.org/debian|{mirror}|g'"
" /etc/apt/sources.list.d/debian.sources 2>/dev/null ||"
f" sed -i 's|http://deb.debian.org/debian|{mirror}|g' /etc/apt/sources.list"
)


def test_apt_sources_mirror_is_chainable() -> None:
mirror = "https://mirrors.tuna.tsinghua.edu.cn/debian"
image = Image(distro="debian")
result = image.apt_sources_mirror(mirror)
assert result is image


def test_image_system_packages_are_shell_quoted() -> None:
image = Image(distro="debian")

Expand Down