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 |
|---|---|
Entry point for CLI |
|
Create Bun environment |
|
List available Bun versions |
|
Get latest stable version |
|
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")
Configuration¶
- class bunenv.Config[source]¶
Bases:
objectConfiguration 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).
- prebuilt: bool = True
Always True for Bun (no source builds).
- ignore_ssl_certs: bool = False
Whether to ignore SSL certificate verification.
Example:
from bunenv import Config # Load from config files Config._load(["~/.bunenvrc"], verbose=True) # Access config print(Config.bun) # "latest" print(Config.variant) # ""
Environment Creation¶
- bunenv.create_environment(env_dir, args)[source]¶
Creates a new Bun environment in
env_dir.- Return type:
Create a new Bun virtual environment.
This is the main function that orchestrates environment creation:
Creates directory structure
Downloads and installs Bun binary
Installs activation scripts
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:
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 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 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:
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
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
Parse Bun version from argparse arguments.
Handles both explicit versions and
systemBun 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:
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:
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:
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:
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:
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:
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
requirementsattribute 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:
Install virtual environment activation scripts.
Creates platform-appropriate activation scripts in the environment.
Unix:
activate(bash/zsh),activate.fishWindows:
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:
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:
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:
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"
Utility Functions¶
File System¶
- bunenv.mkdir(path)[source]¶
Create directory
- Return type:
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:
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
String Processing¶
- bunenv.clear_output(out)[source]¶
Remove new-lines and decode
- Return type:
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:
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¶
Process Execution¶
- bunenv.callit(cmd, show_stdout=True, in_shell=False, cwd=None, extra_env=None)[source]¶
Execute cmd line in sub-shell
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:
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()
Logging¶
Shell Script Templates¶
bunenv includes shell script templates for activation:
These templates are populated with environment-specific values during installation.
See Also¶
Command-Line Interface - Command-line interface reference
Advanced Topics - Advanced usage patterns
Source code: https://github.com/JacobCoffee/bunenv