API Reference

Complete technical reference for the bunenv module.

Note

Looking for command-line options? See Command-Line Interface.

Module Overview

bunenv is a single-module package providing Bun virtual environment functionality. All code lives in src/bunenv/__init__.py, following the architecture of nodeenv.

import bunenv

# Entry point
bunenv.main()  # Called by `bunenv` command

# Get available versions
versions = bunenv.get_bun_versions()

# Parse version strings
parsed = bunenv.parse_version("1.3.3")  # (1, 3, 3)

Quick Reference

Core Functions

Function

Purpose

main()

Entry point for CLI

create_environment()

Create Bun environment

get_bun_versions()

List available Bun versions

get_last_stable_bun_version()

Get latest stable version

install_bun()

Download and install Bun binary

Module Constants

bunenv_version: str = "0.1.0"

Current version of bunenv.

import bunenv
print(bunenv.bunenv_version)  # "0.1.0"
is_WIN: bool

True if running on Windows platform.

import bunenv
if bunenv.is_WIN:
    print("Running on Windows")
is_CYGWIN: bool

True if running on Cygwin or MSYS.

import bunenv
if bunenv.is_CYGWIN:
    print("Running on Cygwin/MSYS")
ignore_ssl_certs: bool = False

Whether to ignore SSL certificate verification.

Set to True when using --ignore_ssl_certs flag.

Warning

Setting this to True disables security verification!

Configuration

class bunenv.Config[source]

Bases: object

Configuration namespace.

Configuration class for bunenv defaults and settings.

Class Attributes:

bun: str = "latest"

Default Bun version to install.

variant: str = ""

Default Bun variant (auto-detect if empty).

github_token: str | None = None

GitHub personal access token for API requests.

prebuilt: bool = True

Always True for Bun (no source builds).

ignore_ssl_certs: bool = False

Whether to ignore SSL certificate verification.

mirror: str | None = None

Alternative mirror URL for downloads.

Example:

from bunenv import Config

# Load from config files
Config._load(["~/.bunenvrc"], verbose=True)

# Access config
print(Config.bun)  # "latest"
print(Config.variant)  # ""
bun: str = 'latest'
variant: str = ''
github_token: str | None = None
prebuilt: bool = True
ignore_ssl_certs: bool = False
mirror: str | None = None

Environment Creation

bunenv.create_environment(env_dir, args)[source]

Creates a new Bun environment in env_dir.

Return type:

None

Create a new Bun virtual environment.

This is the main function that orchestrates environment creation:

  1. Creates directory structure

  2. Downloads and installs Bun binary

  3. Installs activation scripts

  4. Optionally installs packages from requirements file

Example:

import argparse
from bunenv import create_environment

# Create args namespace
args = argparse.Namespace(
    bun="1.3.3",
    variant="",
    python_virtualenv=False,
    requirements="",
    clean_src=False,
    force=False,
    verbose=False,
    mirror=None,
    github_token=None,
)

# Create environment
create_environment("/tmp/myenv", args)
bunenv.get_env_dir(args)[source]
Return type:

Any

Get environment directory from arguments.

Determines the target directory based on whether using Python virtualenv or explicit directory.

Example:

from bunenv import get_env_dir
import argparse

args = argparse.Namespace(
    python_virtualenv=False,
    env_dir="/tmp/myenv"
)

env_dir = get_env_dir(args)  # "/tmp/myenv"

Version Management

bunenv.get_bun_versions()[source]

Return all available Bun versions

Return type:

list[str]

Return list of all available Bun versions from GitHub Releases.

Returns:

List of version strings (e.g., ['1.3.3', '1.3.2', ...])

Example:

from bunenv import get_bun_versions

versions = get_bun_versions()
print(f"Available versions: {len(versions)}")
print(f"Latest: {versions[0]}")
print(f"First 10: {versions[:10]}")

Note

This makes an API request to GitHub. Use a token to avoid rate limits.

bunenv.get_last_stable_bun_version()[source]

Return last stable Bun version (first in the list from GitHub)

Return type:

str | None

Return the most recent stable Bun version.

Returns:

Version string (e.g., "1.3.3") or None if fetch fails

Example:

from bunenv import get_last_stable_bun_version

latest = get_last_stable_bun_version()
print(f"Latest Bun: {latest}")
bunenv.print_bun_versions()[source]

Prints into stdout all available Bun versions

Return type:

None

Print all available Bun versions to stdout.

Formats output in columns of 8 versions each.

Example:

from bunenv import print_bun_versions

print_bun_versions()
# Output:
# 1.3.3    1.3.2    1.3.1    1.3.0    1.2.15   1.2.14   1.2.13   1.2.12
# ...
bunenv.parse_version(version_str)[source]

Parse version string to a tuple of integer parts

Return type:

tuple[int, ...]

Parse version string to tuple of integers.

Handles common prefixes (v, bun-v).

Args:

version_str: Version string to parse

Returns:

Tuple of integers (e.g., (1, 3, 3)) or empty tuple if invalid

Example:

from bunenv import parse_version

assert parse_version("1.3.3") == (1, 3, 3)
assert parse_version("v1.3.3") == (1, 3, 3)
assert parse_version("bun-v1.3.3") == (1, 3, 3)
assert parse_version("invalid") == ()
bunenv.bun_version_from_args(args)[source]

Parse the bun version from the argparse args

Return type:

tuple[int, ...]

Parse Bun version from argparse arguments.

Handles both explicit versions and system Bun detection.

Example:

from bunenv import bun_version_from_args
import argparse

args = argparse.Namespace(bun="1.3.3")
version = bun_version_from_args(args)
# (1, 3, 3)

Binary Management

bunenv.get_bun_bin_url(version, variant='', mirror=None)[source]

Construct GitHub releases URL for Bun binary

Bun provides prebuilt binaries for multiple platforms in the format: bun-{platform}-{arch}[-{variant}].zip

Return type:

str

Construct GitHub releases URL for Bun binary.

Detects platform and architecture automatically, builds appropriate URL.

Args:

version: Bun version (e.g., “1.3.3”) variant: Bun variant (“”, “baseline”, “musl”, “profile”) mirror: Alternative mirror URL (optional)

Returns:

Complete URL to download binary

Example:

from bunenv import get_bun_bin_url

# Auto-detect platform/arch
url = get_bun_bin_url("1.3.3")
# "https://github.com/oven-sh/bun/releases/download/bun-v1.3.3/bun-linux-x64.zip"

# With variant
url = get_bun_bin_url("1.3.3", variant="baseline")
# "https://github.com/oven-sh/bun/releases/download/bun-v1.3.3/bun-linux-x64-baseline.zip"

# With mirror
url = get_bun_bin_url("1.3.3", mirror="https://mirror.example.com")
# "https://mirror.example.com/bun-v1.3.3/bun-linux-x64.zip"
bunenv.download_bun_bin(bun_url, src_dir, args)[source]

Download Bun binary zip file

Return type:

None

Download Bun binary zip file from GitHub Releases.

Args:

bun_url: Complete URL to binary src_dir: Directory to extract to args: Argument namespace

Example:

from bunenv import get_bun_bin_url, download_bun_bin
import argparse

url = get_bun_bin_url("1.3.3")
args = argparse.Namespace(verbose=True)

download_bun_bin(url, "/tmp/src", args)
# Downloads and extracts to /tmp/src/
bunenv.copy_bun_from_prebuilt(env_dir, src_dir, bun_version)[source]

Copy prebuilt Bun binary into environment

Bun zip structure: bun-{platform}-{arch}/bun (or bun.exe on Windows) Extract to: env_dir/bin/bun (or env_dir/Scripts/bun.exe on Windows)

Return type:

None

Copy prebuilt Bun binary from extracted archive to environment.

Args:

env_dir: Environment directory src_dir: Source directory with extracted files bun_version: Bun version being installed

Example:

from bunenv import copy_bun_from_prebuilt

copy_bun_from_prebuilt(
    env_dir="/tmp/myenv",
    src_dir="/tmp/src",
    bun_version="1.3.3"
)
# Copies to /tmp/myenv/bin/bun

Installation Functions

bunenv.install_bun(env_dir, src_dir, args)[source]

Download Bun binary and install it in virtual environment. Bun only provides prebuilt binaries (no source builds).

Return type:

None

Download Bun binary and install it in virtual environment.

High-level wrapper that handles download, extraction, and installation.

Args:

env_dir: Environment directory src_dir: Source/download directory args: Argument namespace

Example:

from bunenv import install_bun
import argparse

args = argparse.Namespace(
    bun="1.3.3",
    variant="",
    mirror=None,
    verbose=True
)

install_bun("/tmp/myenv", "/tmp/src", args)
bunenv.install_bun_wrapped(env_dir, src_dir, args)[source]
Return type:

None

Internal wrapper for install_bun with error handling.

Note

Use install_bun() instead - it provides better error handling.

bunenv.install_packages(env_dir, args)[source]

Install packages via bun add -g

Return type:

None

Install packages via bun add -g.

Reads packages from requirements file and installs them globally in the environment.

Args:

env_dir: Environment directory args: Must have requirements attribute with file path

Example:

from bunenv import install_packages
import argparse

args = argparse.Namespace(
    requirements="requirements-bun.txt",
    verbose=True
)

install_packages("/tmp/myenv", args)

Activation Scripts

bunenv.install_activate(env_dir, args)[source]

Install virtual environment activation script

Return type:

None

Install virtual environment activation scripts.

Creates platform-appropriate activation scripts in the environment.

Unix: activate (bash/zsh), activate.fish

Windows: activate.bat, Activate.ps1

Args:

env_dir: Environment directory args: Argument namespace

Example:

from bunenv import install_activate
import argparse

args = argparse.Namespace(
    bun="1.3.3",
    prompt="",
    python_virtualenv=False
)

install_activate("/tmp/myenv", args)
bunenv.set_predeactivate_hook(env_dir)[source]
Return type:

None

Set pre-deactivation hook for Python virtualenv integration.

Creates a hook that deactivates Bun environment before deactivating Python virtualenv.

Args:

env_dir: Environment directory

Example:

from bunenv import set_predeactivate_hook

set_predeactivate_hook("/tmp/myenv")

Command-Line Interface

bunenv.make_parser()[source]

Make a command line argument parser.

Return type:

ArgumentParser

Create argument parser for bunenv CLI.

Returns:

Configured ArgumentParser instance

Example:

from bunenv import make_parser

parser = make_parser()
args = parser.parse_args(["myenv", "--bun=1.3.3"])
bunenv.parse_args(check=True)[source]

Parses command line arguments.

Set check to False to skip validation checks.

Return type:

Namespace

Parse command-line arguments with validation.

Args:

check: Whether to validate arguments (default True)

Returns:

Parsed argument namespace

Example:

from bunenv import parse_args
import sys

# Temporarily replace sys.argv
sys.argv = ["bunenv", "myenv", "--bun=1.3.3"]
args = parse_args()

print(args.env_dir)  # "myenv"
print(args.bun)  # "1.3.3"
bunenv.main()[source]

Entry point

Return type:

None

Main entry point for bunenv CLI.

Called when you run bunenv command.

Example:

import sys
from bunenv import main

# Run programmatically
sys.argv = ["bunenv", "--list"]
main()

Utility Functions

File System

bunenv.mkdir(path)[source]

Create directory

Return type:

None

Create directory with logging.

Args:

path: Directory path to create

Example:

from bunenv import mkdir

mkdir("/tmp/test/nested/dir")
bunenv.writefile(dest, content, overwrite=True, append=False)[source]

Create file and write content in it

Return type:

None

Create file and write content with executable permissions.

Args:

dest: Destination file path content: Content to write (str or bytes) overwrite: Whether to overwrite existing (default True) append: Whether to append to existing (default False)

Example:

from bunenv import writefile

writefile("/tmp/script.sh", "#!/bin/bash\necho Hello")
# Creates executable file
bunenv.make_executable(filename)[source]
Return type:

None

Make file executable (Unix mode 0755).

Args:

filename: File to make executable

Example:

from bunenv import make_executable

make_executable("/tmp/script.sh")

String Processing

bunenv.clear_output(out)[source]

Remove new-lines and decode

Return type:

str

Remove newlines and decode bytes to string.

Args:

out: Bytes output from subprocess

Returns:

Cleaned string

Example:

from bunenv import clear_output

output = b"1.3.3\n"
clean = clear_output(output)  # "1.3.3"
bunenv.remove_env_bin_from_path(env, env_bin_dir)[source]

Remove bin directory of the current environment from PATH

Return type:

str

Remove environment’s bin directory from PATH string.

Args:

env: PATH environment variable env_bin_dir: Bin directory to remove

Returns:

Modified PATH string

Example:

from bunenv import remove_env_bin_from_path

path = "/tmp/myenv/bin:/usr/bin:/bin"
clean = remove_env_bin_from_path(path, "/tmp/myenv/bin")
# ":/usr/bin:/bin"

System Detection

bunenv.is_x86_64_musl()[source]

Check if running on musl libc

Return type:

bool

Check if running on musl libc (Alpine Linux, Void Linux).

Returns:

True if musl detected

Example:

from bunenv import is_x86_64_musl

if is_x86_64_musl():
    print("Use musl variant")

Process Execution

bunenv.callit(cmd, show_stdout=True, in_shell=False, cwd=None, extra_env=None)[source]

Execute cmd line in sub-shell

Return type:

tuple[int, list[str]]

Execute command in subprocess with logging.

Args:

cmd: Command list or string show_stdout: Whether to show output (default True) in_shell: Run in shell (default False) cwd: Working directory (optional) extra_env: Additional environment variables (optional)

Returns:

Tuple of (return_code, output_lines)

Example:

from bunenv import callit

returncode, output = callit(
    ["bun", "--version"],
    show_stdout=True
)

Network

bunenv.urlopen(url)[source]
Return type:

Any

Open URL with custom headers and SSL handling.

Automatically adds User-Agent and GitHub token if configured.

Args:

url: URL to open

Returns:

urllib response object

Example:

from bunenv import urlopen

response = urlopen("https://api.github.com/repos/oven-sh/bun/releases")
data = response.read()
bunenv.zipfile_open(*args, **kwargs)[source]

Context manager for zipfile.

Return type:

Iterator[ZipFile]

Context manager for safe zipfile handling.

Example:

from bunenv import zipfile_open

with zipfile_open("archive.zip", "r") as zf:
    zf.extractall("/tmp/extracted")

Logging

bunenv.create_logger()[source]

Create logger for diagnostic

Return type:

Logger

Create logger for diagnostic output.

Returns:

Configured Logger instance

Example:

from bunenv import create_logger

logger = create_logger()
logger.info("Installing Bun...")

Shell Script Templates

bunenv includes shell script templates for activation:

ACTIVATE_SH: str

Bash/zsh activation script template.

ACTIVATE_FISH: str

Fish shell activation script template.

ACTIVATE_BAT: str

Windows cmd.exe activation script template.

ACTIVATE_PS1: str

Windows PowerShell activation script template.

DEACTIVATE_BAT: str

Windows cmd.exe deactivation script template.

SHIM: str

System Bun wrapper script template.

PREDEACTIVATE_SH: str

Pre-deactivation hook for Python virtualenv.

These templates are populated with environment-specific values during installation.

See Also