E2B/packages/python-sdk/e2b/template/dockerfile_parser.py

285 lines
9.0 KiB
Python
Raw Permalink Normal View History

import json
Add Templates SDK (#871) ### Merge Templates SDK into E2B SDK. This PR merges code from Templates SDK to E2B SDK. **Changelog** - Added new error classes: BuildError, FileUploadError. - Added template API endpoints to API Client generation (Python). - Updated API Clients error handling to throw BuildError in addition to SandboxError. - Exported Template and TemplateAsync classes. - Moved `getRuntime` utility method from api to utils. - Browser is supported except file operations (COPY). Incompatible modules are not bundled, using dynamic imports (tar, glob) in supported environments (Node, Deno, Bun) instead. - Basic tests were added, subject to expansion in a follow-up PR. - Breaking: Before, 401 error was raising `SandboxError`, which was incorrect, now it will raise `AuthenticationError`. I have also changed the `AuthenticationError` to extend Error class, not `SandboxError` anymore as it's now thrown by both Sandbox and Template. **Usage** JavaScript ```js import { Template } from 'e2b'; const template = Template() .fromImage('ubuntu:22.04') .copy('folder/*.txt', 'folder', { forceUpload: true }) .setEnvs({ ENV_1: 'value1', ENV_2: 'value2', }) .runCmd('cat folder/test.txt') .setWorkdir('/app') .setStartCmd('echo "Hello, world!"', Template.waitForTimeout('10s')) await Template.build(template, { alias: 'test-template', cpuCount: 1, memoryMB: 1024, onBuildLogs: (logEntry) => console.log(logEntry.toString()), }) ``` Python ```py from e2b import Template template = ( Template() .from_image("ubuntu:22.04") .copy("folder/*.txt", "folder", force_upload=True) .set_envs( { "ENV_1": "value1", "ENV_2": "value2", } ) .run_cmd("cat folder/test.txt") .set_workdir("/app") .set_start_cmd("echo 'Hello, world!'", Template.wait_for_timeout("10s")) ) Template.build( template, alias="test-template", cpu_count=1, memory_mb=1024, on_build_logs=lambda log_entry: print(log_entry), ) ``` Python Async ```py from e2b import AsyncTemplate template = ( AsyncTemplate() .from_image("ubuntu:22.04") .copy("folder/*.txt", "folder", force_upload=True) .set_envs( { "ENV_1": "value1", "ENV_2": "value2", } ) .run_cmd("cat folder/test.txt") .set_workdir("/app") .set_start_cmd("echo 'Hello, world!'", Template.wait_for_timeout("10s")) ) await AsyncTemplate.build( template, alias="test-template", cpu_count=1, memory_mb=1024, on_build_logs=lambda log_entry: print(log_entry), ) ``` --- Merge progress - [x] JavaScript SDK - [x] Python SDK - [x] Tests - [x] Split files for review
2025-09-05 22:00:22 +02:00
import os
import re
import tempfile
Improve method naming and consistency (#934) <!-- CURSOR_SUMMARY --> > [!NOTE] > Unifies Template APIs across JS/Python with PathLike support, new copyItems, option/name tweaks, and simpler registry auth via credentials; updates parser, exports, and tests. > > - **Template API (JS + Python)** > - Add PathLike support for paths in `copy`, `remove`, `rename`, `makeDir`, `makeSymlink`, `setWorkdir`, and `gitClone`. > - Introduce `copyItems` and corresponding `CopyItem` typing; adjust Dockerfile parser to use `copyItems` overload. > - Simplify registry auth: `fromImage(baseImage, credentials)` accepts `{username,password}`; remove `fromRegistry`; update `fromAWSRegistry`/`fromGCPRegistry` to take credentials and set config internally. > - Rename options: `ignoreFilePaths` -> `fileIgnorePatterns`; `fileContextPath` can be `PathLike`. > - Ensure internal hashing/upload use stringified paths; minor enum/type tweaks (e.g., `InstructionType` as string enum, `forceUpload?: true`). > - **Exports** > - Export `CopyItem` from JS `index.ts` and Python `__init__.py`. > - **Tests** > - Update stacktrace and build tests to new method names/signatures (e.g., registry via `fromImage` credentials, new `copyItems` tests, optional `skipCache` param). > > <sup>Written by [Cursor Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit 95391030550a340fe99ebaac4494867b3e3e9507. This will update automatically on new commits. Configure [here](https://cursor.com/dashboard?tab=bugbot).</sup> <!-- /CURSOR_SUMMARY --> --------- Co-authored-by: Jakub Dobry <jakub.dobry8@gmail.com>
2025-10-09 00:51:02 +02:00
from typing import Dict, List, Optional, Protocol, Union, Literal
Add Templates SDK (#871) ### Merge Templates SDK into E2B SDK. This PR merges code from Templates SDK to E2B SDK. **Changelog** - Added new error classes: BuildError, FileUploadError. - Added template API endpoints to API Client generation (Python). - Updated API Clients error handling to throw BuildError in addition to SandboxError. - Exported Template and TemplateAsync classes. - Moved `getRuntime` utility method from api to utils. - Browser is supported except file operations (COPY). Incompatible modules are not bundled, using dynamic imports (tar, glob) in supported environments (Node, Deno, Bun) instead. - Basic tests were added, subject to expansion in a follow-up PR. - Breaking: Before, 401 error was raising `SandboxError`, which was incorrect, now it will raise `AuthenticationError`. I have also changed the `AuthenticationError` to extend Error class, not `SandboxError` anymore as it's now thrown by both Sandbox and Template. **Usage** JavaScript ```js import { Template } from 'e2b'; const template = Template() .fromImage('ubuntu:22.04') .copy('folder/*.txt', 'folder', { forceUpload: true }) .setEnvs({ ENV_1: 'value1', ENV_2: 'value2', }) .runCmd('cat folder/test.txt') .setWorkdir('/app') .setStartCmd('echo "Hello, world!"', Template.waitForTimeout('10s')) await Template.build(template, { alias: 'test-template', cpuCount: 1, memoryMB: 1024, onBuildLogs: (logEntry) => console.log(logEntry.toString()), }) ``` Python ```py from e2b import Template template = ( Template() .from_image("ubuntu:22.04") .copy("folder/*.txt", "folder", force_upload=True) .set_envs( { "ENV_1": "value1", "ENV_2": "value2", } ) .run_cmd("cat folder/test.txt") .set_workdir("/app") .set_start_cmd("echo 'Hello, world!'", Template.wait_for_timeout("10s")) ) Template.build( template, alias="test-template", cpu_count=1, memory_mb=1024, on_build_logs=lambda log_entry: print(log_entry), ) ``` Python Async ```py from e2b import AsyncTemplate template = ( AsyncTemplate() .from_image("ubuntu:22.04") .copy("folder/*.txt", "folder", force_upload=True) .set_envs( { "ENV_1": "value1", "ENV_2": "value2", } ) .run_cmd("cat folder/test.txt") .set_workdir("/app") .set_start_cmd("echo 'Hello, world!'", Template.wait_for_timeout("10s")) ) await AsyncTemplate.build( template, alias="test-template", cpu_count=1, memory_mb=1024, on_build_logs=lambda log_entry: print(log_entry), ) ``` --- Merge progress - [x] JavaScript SDK - [x] Python SDK - [x] Tests - [x] Split files for review
2025-09-05 22:00:22 +02:00
from dockerfile_parse import DockerfileParser
class DockerfFileFinalParserInterface(Protocol):
"""Protocol defining the final interface for Dockerfile parsing callbacks."""
class DockerfileParserInterface(Protocol):
"""Protocol defining the interface for Dockerfile parsing callbacks."""
def run_cmd(
self, command: Union[str, List[str]], user: Optional[str] = None
) -> "DockerfileParserInterface":
"""Handle RUN instruction."""
...
def copy(
self,
Fix Python SDK type issues with ty type checker (#1122) ## Summary - Resolved 43 type diagnostics reported by ty (Astral's Python type checker) - Fixed Self type issues on class singletons - Added explicit type annotations for shadowed attributes - Replaced None with UNSET for auto-generated API parameters - Fixed method signature alignment for protocol matching - Added targeted type: ignore suppressions for pattern-based limitations All checks pass: ty check, ruff format, ruff check. <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **Medium Risk** > Mostly typing/CI changes, but some adjustments affect sandbox connect/pause overload dispatch and API response/parameter handling (`UNSET` vs `None`), which could alter edge-case runtime behavior. > > **Overview** > Fixes Python SDK static typing issues for Astral’s `ty` checker and wires typechecking into CI. > > Adds a new `Typecheck` GitHub Action plus workspace `typecheck` scripts (TS packages via `tsc`, Python SDK via `make typecheck` running `ty`), and publishes a patch changeset for `@e2b/python-sdk`. > > Across the Python SDK, adjusts type annotations and overloads (e.g., `Self`/singleton typing, `connect` overloads, optional `user`/token/domain handling), tightens API model parsing with `cast`/`Optional` checks and `UNSET` usage, and adds a few targeted `ty` ignore comments in tests/protocols to silence checker limitations. > > <sup>Written by [Cursor Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit f66402847c40cee7e44e1aaa7caa97e271ba9978. This will update automatically on new commits. Configure [here](https://cursor.com/dashboard?tab=bugbot).</sup> <!-- /CURSOR_SUMMARY --> --------- Co-authored-by: Claude Haiku 4.5 <noreply@anthropic.com> Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>
2026-02-12 17:23:39 +01:00
src: str,
dest: str,
Improve method naming and consistency (#934) <!-- CURSOR_SUMMARY --> > [!NOTE] > Unifies Template APIs across JS/Python with PathLike support, new copyItems, option/name tweaks, and simpler registry auth via credentials; updates parser, exports, and tests. > > - **Template API (JS + Python)** > - Add PathLike support for paths in `copy`, `remove`, `rename`, `makeDir`, `makeSymlink`, `setWorkdir`, and `gitClone`. > - Introduce `copyItems` and corresponding `CopyItem` typing; adjust Dockerfile parser to use `copyItems` overload. > - Simplify registry auth: `fromImage(baseImage, credentials)` accepts `{username,password}`; remove `fromRegistry`; update `fromAWSRegistry`/`fromGCPRegistry` to take credentials and set config internally. > - Rename options: `ignoreFilePaths` -> `fileIgnorePatterns`; `fileContextPath` can be `PathLike`. > - Ensure internal hashing/upload use stringified paths; minor enum/type tweaks (e.g., `InstructionType` as string enum, `forceUpload?: true`). > - **Exports** > - Export `CopyItem` from JS `index.ts` and Python `__init__.py`. > - **Tests** > - Update stacktrace and build tests to new method names/signatures (e.g., registry via `fromImage` credentials, new `copyItems` tests, optional `skipCache` param). > > <sup>Written by [Cursor Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit 95391030550a340fe99ebaac4494867b3e3e9507. This will update automatically on new commits. Configure [here](https://cursor.com/dashboard?tab=bugbot).</sup> <!-- /CURSOR_SUMMARY --> --------- Co-authored-by: Jakub Dobry <jakub.dobry8@gmail.com>
2025-10-09 00:51:02 +02:00
force_upload: Optional[Literal[True]] = None,
Add Templates SDK (#871) ### Merge Templates SDK into E2B SDK. This PR merges code from Templates SDK to E2B SDK. **Changelog** - Added new error classes: BuildError, FileUploadError. - Added template API endpoints to API Client generation (Python). - Updated API Clients error handling to throw BuildError in addition to SandboxError. - Exported Template and TemplateAsync classes. - Moved `getRuntime` utility method from api to utils. - Browser is supported except file operations (COPY). Incompatible modules are not bundled, using dynamic imports (tar, glob) in supported environments (Node, Deno, Bun) instead. - Basic tests were added, subject to expansion in a follow-up PR. - Breaking: Before, 401 error was raising `SandboxError`, which was incorrect, now it will raise `AuthenticationError`. I have also changed the `AuthenticationError` to extend Error class, not `SandboxError` anymore as it's now thrown by both Sandbox and Template. **Usage** JavaScript ```js import { Template } from 'e2b'; const template = Template() .fromImage('ubuntu:22.04') .copy('folder/*.txt', 'folder', { forceUpload: true }) .setEnvs({ ENV_1: 'value1', ENV_2: 'value2', }) .runCmd('cat folder/test.txt') .setWorkdir('/app') .setStartCmd('echo "Hello, world!"', Template.waitForTimeout('10s')) await Template.build(template, { alias: 'test-template', cpuCount: 1, memoryMB: 1024, onBuildLogs: (logEntry) => console.log(logEntry.toString()), }) ``` Python ```py from e2b import Template template = ( Template() .from_image("ubuntu:22.04") .copy("folder/*.txt", "folder", force_upload=True) .set_envs( { "ENV_1": "value1", "ENV_2": "value2", } ) .run_cmd("cat folder/test.txt") .set_workdir("/app") .set_start_cmd("echo 'Hello, world!'", Template.wait_for_timeout("10s")) ) Template.build( template, alias="test-template", cpu_count=1, memory_mb=1024, on_build_logs=lambda log_entry: print(log_entry), ) ``` Python Async ```py from e2b import AsyncTemplate template = ( AsyncTemplate() .from_image("ubuntu:22.04") .copy("folder/*.txt", "folder", force_upload=True) .set_envs( { "ENV_1": "value1", "ENV_2": "value2", } ) .run_cmd("cat folder/test.txt") .set_workdir("/app") .set_start_cmd("echo 'Hello, world!'", Template.wait_for_timeout("10s")) ) await AsyncTemplate.build( template, alias="test-template", cpu_count=1, memory_mb=1024, on_build_logs=lambda log_entry: print(log_entry), ) ``` --- Merge progress - [x] JavaScript SDK - [x] Python SDK - [x] Tests - [x] Split files for review
2025-09-05 22:00:22 +02:00
user: Optional[str] = None,
mode: Optional[int] = None,
Fix Python SDK type issues with ty type checker (#1122) ## Summary - Resolved 43 type diagnostics reported by ty (Astral's Python type checker) - Fixed Self type issues on class singletons - Added explicit type annotations for shadowed attributes - Replaced None with UNSET for auto-generated API parameters - Fixed method signature alignment for protocol matching - Added targeted type: ignore suppressions for pattern-based limitations All checks pass: ty check, ruff format, ruff check. <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **Medium Risk** > Mostly typing/CI changes, but some adjustments affect sandbox connect/pause overload dispatch and API response/parameter handling (`UNSET` vs `None`), which could alter edge-case runtime behavior. > > **Overview** > Fixes Python SDK static typing issues for Astral’s `ty` checker and wires typechecking into CI. > > Adds a new `Typecheck` GitHub Action plus workspace `typecheck` scripts (TS packages via `tsc`, Python SDK via `make typecheck` running `ty`), and publishes a patch changeset for `@e2b/python-sdk`. > > Across the Python SDK, adjusts type annotations and overloads (e.g., `Self`/singleton typing, `connect` overloads, optional `user`/token/domain handling), tightens API model parsing with `cast`/`Optional` checks and `UNSET` usage, and adds a few targeted `ty` ignore comments in tests/protocols to silence checker limitations. > > <sup>Written by [Cursor Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit f66402847c40cee7e44e1aaa7caa97e271ba9978. This will update automatically on new commits. Configure [here](https://cursor.com/dashboard?tab=bugbot).</sup> <!-- /CURSOR_SUMMARY --> --------- Co-authored-by: Claude Haiku 4.5 <noreply@anthropic.com> Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>
2026-02-12 17:23:39 +01:00
resolve_symlinks: Optional[bool] = None,
Add Templates SDK (#871) ### Merge Templates SDK into E2B SDK. This PR merges code from Templates SDK to E2B SDK. **Changelog** - Added new error classes: BuildError, FileUploadError. - Added template API endpoints to API Client generation (Python). - Updated API Clients error handling to throw BuildError in addition to SandboxError. - Exported Template and TemplateAsync classes. - Moved `getRuntime` utility method from api to utils. - Browser is supported except file operations (COPY). Incompatible modules are not bundled, using dynamic imports (tar, glob) in supported environments (Node, Deno, Bun) instead. - Basic tests were added, subject to expansion in a follow-up PR. - Breaking: Before, 401 error was raising `SandboxError`, which was incorrect, now it will raise `AuthenticationError`. I have also changed the `AuthenticationError` to extend Error class, not `SandboxError` anymore as it's now thrown by both Sandbox and Template. **Usage** JavaScript ```js import { Template } from 'e2b'; const template = Template() .fromImage('ubuntu:22.04') .copy('folder/*.txt', 'folder', { forceUpload: true }) .setEnvs({ ENV_1: 'value1', ENV_2: 'value2', }) .runCmd('cat folder/test.txt') .setWorkdir('/app') .setStartCmd('echo "Hello, world!"', Template.waitForTimeout('10s')) await Template.build(template, { alias: 'test-template', cpuCount: 1, memoryMB: 1024, onBuildLogs: (logEntry) => console.log(logEntry.toString()), }) ``` Python ```py from e2b import Template template = ( Template() .from_image("ubuntu:22.04") .copy("folder/*.txt", "folder", force_upload=True) .set_envs( { "ENV_1": "value1", "ENV_2": "value2", } ) .run_cmd("cat folder/test.txt") .set_workdir("/app") .set_start_cmd("echo 'Hello, world!'", Template.wait_for_timeout("10s")) ) Template.build( template, alias="test-template", cpu_count=1, memory_mb=1024, on_build_logs=lambda log_entry: print(log_entry), ) ``` Python Async ```py from e2b import AsyncTemplate template = ( AsyncTemplate() .from_image("ubuntu:22.04") .copy("folder/*.txt", "folder", force_upload=True) .set_envs( { "ENV_1": "value1", "ENV_2": "value2", } ) .run_cmd("cat folder/test.txt") .set_workdir("/app") .set_start_cmd("echo 'Hello, world!'", Template.wait_for_timeout("10s")) ) await AsyncTemplate.build( template, alias="test-template", cpu_count=1, memory_mb=1024, on_build_logs=lambda log_entry: print(log_entry), ) ``` --- Merge progress - [x] JavaScript SDK - [x] Python SDK - [x] Tests - [x] Split files for review
2025-09-05 22:00:22 +02:00
) -> "DockerfileParserInterface":
"""Handle COPY instruction."""
...
def set_workdir(self, workdir: str) -> "DockerfileParserInterface":
"""Handle WORKDIR instruction."""
...
def set_user(self, user: str) -> "DockerfileParserInterface":
"""Handle USER instruction."""
...
def set_envs(self, envs: Dict[str, str]) -> "DockerfileParserInterface":
"""Handle ENV instruction."""
...
def set_start_cmd(
self, start_cmd: str, ready_cmd: str
) -> "DockerfFileFinalParserInterface":
"""Handle CMD/ENTRYPOINT instruction."""
...
def parse_dockerfile(
dockerfile_content_or_path: str, template_builder: DockerfileParserInterface
) -> str:
"""
Parse a Dockerfile and convert it to Template SDK format.
Add Templates SDK (#871) ### Merge Templates SDK into E2B SDK. This PR merges code from Templates SDK to E2B SDK. **Changelog** - Added new error classes: BuildError, FileUploadError. - Added template API endpoints to API Client generation (Python). - Updated API Clients error handling to throw BuildError in addition to SandboxError. - Exported Template and TemplateAsync classes. - Moved `getRuntime` utility method from api to utils. - Browser is supported except file operations (COPY). Incompatible modules are not bundled, using dynamic imports (tar, glob) in supported environments (Node, Deno, Bun) instead. - Basic tests were added, subject to expansion in a follow-up PR. - Breaking: Before, 401 error was raising `SandboxError`, which was incorrect, now it will raise `AuthenticationError`. I have also changed the `AuthenticationError` to extend Error class, not `SandboxError` anymore as it's now thrown by both Sandbox and Template. **Usage** JavaScript ```js import { Template } from 'e2b'; const template = Template() .fromImage('ubuntu:22.04') .copy('folder/*.txt', 'folder', { forceUpload: true }) .setEnvs({ ENV_1: 'value1', ENV_2: 'value2', }) .runCmd('cat folder/test.txt') .setWorkdir('/app') .setStartCmd('echo "Hello, world!"', Template.waitForTimeout('10s')) await Template.build(template, { alias: 'test-template', cpuCount: 1, memoryMB: 1024, onBuildLogs: (logEntry) => console.log(logEntry.toString()), }) ``` Python ```py from e2b import Template template = ( Template() .from_image("ubuntu:22.04") .copy("folder/*.txt", "folder", force_upload=True) .set_envs( { "ENV_1": "value1", "ENV_2": "value2", } ) .run_cmd("cat folder/test.txt") .set_workdir("/app") .set_start_cmd("echo 'Hello, world!'", Template.wait_for_timeout("10s")) ) Template.build( template, alias="test-template", cpu_count=1, memory_mb=1024, on_build_logs=lambda log_entry: print(log_entry), ) ``` Python Async ```py from e2b import AsyncTemplate template = ( AsyncTemplate() .from_image("ubuntu:22.04") .copy("folder/*.txt", "folder", force_upload=True) .set_envs( { "ENV_1": "value1", "ENV_2": "value2", } ) .run_cmd("cat folder/test.txt") .set_workdir("/app") .set_start_cmd("echo 'Hello, world!'", Template.wait_for_timeout("10s")) ) await AsyncTemplate.build( template, alias="test-template", cpu_count=1, memory_mb=1024, on_build_logs=lambda log_entry: print(log_entry), ) ``` --- Merge progress - [x] JavaScript SDK - [x] Python SDK - [x] Tests - [x] Split files for review
2025-09-05 22:00:22 +02:00
:param dockerfile_content_or_path: Either the Dockerfile content as a string, or a path to a Dockerfile file
:param template_builder: Interface providing template builder methods
Add Templates SDK (#871) ### Merge Templates SDK into E2B SDK. This PR merges code from Templates SDK to E2B SDK. **Changelog** - Added new error classes: BuildError, FileUploadError. - Added template API endpoints to API Client generation (Python). - Updated API Clients error handling to throw BuildError in addition to SandboxError. - Exported Template and TemplateAsync classes. - Moved `getRuntime` utility method from api to utils. - Browser is supported except file operations (COPY). Incompatible modules are not bundled, using dynamic imports (tar, glob) in supported environments (Node, Deno, Bun) instead. - Basic tests were added, subject to expansion in a follow-up PR. - Breaking: Before, 401 error was raising `SandboxError`, which was incorrect, now it will raise `AuthenticationError`. I have also changed the `AuthenticationError` to extend Error class, not `SandboxError` anymore as it's now thrown by both Sandbox and Template. **Usage** JavaScript ```js import { Template } from 'e2b'; const template = Template() .fromImage('ubuntu:22.04') .copy('folder/*.txt', 'folder', { forceUpload: true }) .setEnvs({ ENV_1: 'value1', ENV_2: 'value2', }) .runCmd('cat folder/test.txt') .setWorkdir('/app') .setStartCmd('echo "Hello, world!"', Template.waitForTimeout('10s')) await Template.build(template, { alias: 'test-template', cpuCount: 1, memoryMB: 1024, onBuildLogs: (logEntry) => console.log(logEntry.toString()), }) ``` Python ```py from e2b import Template template = ( Template() .from_image("ubuntu:22.04") .copy("folder/*.txt", "folder", force_upload=True) .set_envs( { "ENV_1": "value1", "ENV_2": "value2", } ) .run_cmd("cat folder/test.txt") .set_workdir("/app") .set_start_cmd("echo 'Hello, world!'", Template.wait_for_timeout("10s")) ) Template.build( template, alias="test-template", cpu_count=1, memory_mb=1024, on_build_logs=lambda log_entry: print(log_entry), ) ``` Python Async ```py from e2b import AsyncTemplate template = ( AsyncTemplate() .from_image("ubuntu:22.04") .copy("folder/*.txt", "folder", force_upload=True) .set_envs( { "ENV_1": "value1", "ENV_2": "value2", } ) .run_cmd("cat folder/test.txt") .set_workdir("/app") .set_start_cmd("echo 'Hello, world!'", Template.wait_for_timeout("10s")) ) await AsyncTemplate.build( template, alias="test-template", cpu_count=1, memory_mb=1024, on_build_logs=lambda log_entry: print(log_entry), ) ``` --- Merge progress - [x] JavaScript SDK - [x] Python SDK - [x] Tests - [x] Split files for review
2025-09-05 22:00:22 +02:00
:return: The base image from the Dockerfile
Add Templates SDK (#871) ### Merge Templates SDK into E2B SDK. This PR merges code from Templates SDK to E2B SDK. **Changelog** - Added new error classes: BuildError, FileUploadError. - Added template API endpoints to API Client generation (Python). - Updated API Clients error handling to throw BuildError in addition to SandboxError. - Exported Template and TemplateAsync classes. - Moved `getRuntime` utility method from api to utils. - Browser is supported except file operations (COPY). Incompatible modules are not bundled, using dynamic imports (tar, glob) in supported environments (Node, Deno, Bun) instead. - Basic tests were added, subject to expansion in a follow-up PR. - Breaking: Before, 401 error was raising `SandboxError`, which was incorrect, now it will raise `AuthenticationError`. I have also changed the `AuthenticationError` to extend Error class, not `SandboxError` anymore as it's now thrown by both Sandbox and Template. **Usage** JavaScript ```js import { Template } from 'e2b'; const template = Template() .fromImage('ubuntu:22.04') .copy('folder/*.txt', 'folder', { forceUpload: true }) .setEnvs({ ENV_1: 'value1', ENV_2: 'value2', }) .runCmd('cat folder/test.txt') .setWorkdir('/app') .setStartCmd('echo "Hello, world!"', Template.waitForTimeout('10s')) await Template.build(template, { alias: 'test-template', cpuCount: 1, memoryMB: 1024, onBuildLogs: (logEntry) => console.log(logEntry.toString()), }) ``` Python ```py from e2b import Template template = ( Template() .from_image("ubuntu:22.04") .copy("folder/*.txt", "folder", force_upload=True) .set_envs( { "ENV_1": "value1", "ENV_2": "value2", } ) .run_cmd("cat folder/test.txt") .set_workdir("/app") .set_start_cmd("echo 'Hello, world!'", Template.wait_for_timeout("10s")) ) Template.build( template, alias="test-template", cpu_count=1, memory_mb=1024, on_build_logs=lambda log_entry: print(log_entry), ) ``` Python Async ```py from e2b import AsyncTemplate template = ( AsyncTemplate() .from_image("ubuntu:22.04") .copy("folder/*.txt", "folder", force_upload=True) .set_envs( { "ENV_1": "value1", "ENV_2": "value2", } ) .run_cmd("cat folder/test.txt") .set_workdir("/app") .set_start_cmd("echo 'Hello, world!'", Template.wait_for_timeout("10s")) ) await AsyncTemplate.build( template, alias="test-template", cpu_count=1, memory_mb=1024, on_build_logs=lambda log_entry: print(log_entry), ) ``` --- Merge progress - [x] JavaScript SDK - [x] Python SDK - [x] Tests - [x] Split files for review
2025-09-05 22:00:22 +02:00
:raises ValueError: If the Dockerfile is invalid or unsupported
Add Templates SDK (#871) ### Merge Templates SDK into E2B SDK. This PR merges code from Templates SDK to E2B SDK. **Changelog** - Added new error classes: BuildError, FileUploadError. - Added template API endpoints to API Client generation (Python). - Updated API Clients error handling to throw BuildError in addition to SandboxError. - Exported Template and TemplateAsync classes. - Moved `getRuntime` utility method from api to utils. - Browser is supported except file operations (COPY). Incompatible modules are not bundled, using dynamic imports (tar, glob) in supported environments (Node, Deno, Bun) instead. - Basic tests were added, subject to expansion in a follow-up PR. - Breaking: Before, 401 error was raising `SandboxError`, which was incorrect, now it will raise `AuthenticationError`. I have also changed the `AuthenticationError` to extend Error class, not `SandboxError` anymore as it's now thrown by both Sandbox and Template. **Usage** JavaScript ```js import { Template } from 'e2b'; const template = Template() .fromImage('ubuntu:22.04') .copy('folder/*.txt', 'folder', { forceUpload: true }) .setEnvs({ ENV_1: 'value1', ENV_2: 'value2', }) .runCmd('cat folder/test.txt') .setWorkdir('/app') .setStartCmd('echo "Hello, world!"', Template.waitForTimeout('10s')) await Template.build(template, { alias: 'test-template', cpuCount: 1, memoryMB: 1024, onBuildLogs: (logEntry) => console.log(logEntry.toString()), }) ``` Python ```py from e2b import Template template = ( Template() .from_image("ubuntu:22.04") .copy("folder/*.txt", "folder", force_upload=True) .set_envs( { "ENV_1": "value1", "ENV_2": "value2", } ) .run_cmd("cat folder/test.txt") .set_workdir("/app") .set_start_cmd("echo 'Hello, world!'", Template.wait_for_timeout("10s")) ) Template.build( template, alias="test-template", cpu_count=1, memory_mb=1024, on_build_logs=lambda log_entry: print(log_entry), ) ``` Python Async ```py from e2b import AsyncTemplate template = ( AsyncTemplate() .from_image("ubuntu:22.04") .copy("folder/*.txt", "folder", force_upload=True) .set_envs( { "ENV_1": "value1", "ENV_2": "value2", } ) .run_cmd("cat folder/test.txt") .set_workdir("/app") .set_start_cmd("echo 'Hello, world!'", Template.wait_for_timeout("10s")) ) await AsyncTemplate.build( template, alias="test-template", cpu_count=1, memory_mb=1024, on_build_logs=lambda log_entry: print(log_entry), ) ``` --- Merge progress - [x] JavaScript SDK - [x] Python SDK - [x] Tests - [x] Split files for review
2025-09-05 22:00:22 +02:00
"""
# Check if input is a file path that exists
if os.path.isfile(dockerfile_content_or_path):
# Read the file content
with open(dockerfile_content_or_path, "r", encoding="utf-8") as f:
dockerfile_content = f.read()
else:
# Treat as content directly
dockerfile_content = dockerfile_content_or_path
# Use a temporary directory to avoid creating files in the current directory
with tempfile.TemporaryDirectory() as temp_dir:
# Create a temporary Dockerfile
dockerfile_path = os.path.join(temp_dir, "Dockerfile")
with open(dockerfile_path, "w") as f:
f.write(dockerfile_content)
dfp = DockerfileParser(path=temp_dir)
# Check for multi-stage builds
from_instructions = [
instruction
for instruction in dfp.structure
if instruction["instruction"] == "FROM"
]
if len(from_instructions) > 1:
raise ValueError("Multi-stage Dockerfiles are not supported")
if len(from_instructions) == 0:
raise ValueError("Dockerfile must contain a FROM instruction")
# Set the base image from the first FROM instruction
base_image = from_instructions[0]["value"]
# Remove AS alias if present (e.g., "node:18 AS builder" -> "node:18")
if " as " in base_image.lower():
base_image = base_image.split(" as ")[0].strip()
2025-11-26 18:16:25 +01:00
user_changed = False
workdir_changed = False
# Set the user and workdir to the Docker defaults
template_builder.set_user("root")
template_builder.set_workdir("/")
Add Templates SDK (#871) ### Merge Templates SDK into E2B SDK. This PR merges code from Templates SDK to E2B SDK. **Changelog** - Added new error classes: BuildError, FileUploadError. - Added template API endpoints to API Client generation (Python). - Updated API Clients error handling to throw BuildError in addition to SandboxError. - Exported Template and TemplateAsync classes. - Moved `getRuntime` utility method from api to utils. - Browser is supported except file operations (COPY). Incompatible modules are not bundled, using dynamic imports (tar, glob) in supported environments (Node, Deno, Bun) instead. - Basic tests were added, subject to expansion in a follow-up PR. - Breaking: Before, 401 error was raising `SandboxError`, which was incorrect, now it will raise `AuthenticationError`. I have also changed the `AuthenticationError` to extend Error class, not `SandboxError` anymore as it's now thrown by both Sandbox and Template. **Usage** JavaScript ```js import { Template } from 'e2b'; const template = Template() .fromImage('ubuntu:22.04') .copy('folder/*.txt', 'folder', { forceUpload: true }) .setEnvs({ ENV_1: 'value1', ENV_2: 'value2', }) .runCmd('cat folder/test.txt') .setWorkdir('/app') .setStartCmd('echo "Hello, world!"', Template.waitForTimeout('10s')) await Template.build(template, { alias: 'test-template', cpuCount: 1, memoryMB: 1024, onBuildLogs: (logEntry) => console.log(logEntry.toString()), }) ``` Python ```py from e2b import Template template = ( Template() .from_image("ubuntu:22.04") .copy("folder/*.txt", "folder", force_upload=True) .set_envs( { "ENV_1": "value1", "ENV_2": "value2", } ) .run_cmd("cat folder/test.txt") .set_workdir("/app") .set_start_cmd("echo 'Hello, world!'", Template.wait_for_timeout("10s")) ) Template.build( template, alias="test-template", cpu_count=1, memory_mb=1024, on_build_logs=lambda log_entry: print(log_entry), ) ``` Python Async ```py from e2b import AsyncTemplate template = ( AsyncTemplate() .from_image("ubuntu:22.04") .copy("folder/*.txt", "folder", force_upload=True) .set_envs( { "ENV_1": "value1", "ENV_2": "value2", } ) .run_cmd("cat folder/test.txt") .set_workdir("/app") .set_start_cmd("echo 'Hello, world!'", Template.wait_for_timeout("10s")) ) await AsyncTemplate.build( template, alias="test-template", cpu_count=1, memory_mb=1024, on_build_logs=lambda log_entry: print(log_entry), ) ``` --- Merge progress - [x] JavaScript SDK - [x] Python SDK - [x] Tests - [x] Split files for review
2025-09-05 22:00:22 +02:00
# Process all other instructions
for instruction_data in dfp.structure:
instruction = instruction_data["instruction"]
value = instruction_data["value"]
if instruction == "FROM":
# Already handled above
continue
elif instruction == "RUN":
_handle_run_instruction(value, template_builder)
elif instruction in ["COPY", "ADD"]:
_handle_copy_instruction(value, template_builder)
elif instruction == "WORKDIR":
_handle_workdir_instruction(value, template_builder)
2025-11-26 18:16:25 +01:00
workdir_changed = True
Add Templates SDK (#871) ### Merge Templates SDK into E2B SDK. This PR merges code from Templates SDK to E2B SDK. **Changelog** - Added new error classes: BuildError, FileUploadError. - Added template API endpoints to API Client generation (Python). - Updated API Clients error handling to throw BuildError in addition to SandboxError. - Exported Template and TemplateAsync classes. - Moved `getRuntime` utility method from api to utils. - Browser is supported except file operations (COPY). Incompatible modules are not bundled, using dynamic imports (tar, glob) in supported environments (Node, Deno, Bun) instead. - Basic tests were added, subject to expansion in a follow-up PR. - Breaking: Before, 401 error was raising `SandboxError`, which was incorrect, now it will raise `AuthenticationError`. I have also changed the `AuthenticationError` to extend Error class, not `SandboxError` anymore as it's now thrown by both Sandbox and Template. **Usage** JavaScript ```js import { Template } from 'e2b'; const template = Template() .fromImage('ubuntu:22.04') .copy('folder/*.txt', 'folder', { forceUpload: true }) .setEnvs({ ENV_1: 'value1', ENV_2: 'value2', }) .runCmd('cat folder/test.txt') .setWorkdir('/app') .setStartCmd('echo "Hello, world!"', Template.waitForTimeout('10s')) await Template.build(template, { alias: 'test-template', cpuCount: 1, memoryMB: 1024, onBuildLogs: (logEntry) => console.log(logEntry.toString()), }) ``` Python ```py from e2b import Template template = ( Template() .from_image("ubuntu:22.04") .copy("folder/*.txt", "folder", force_upload=True) .set_envs( { "ENV_1": "value1", "ENV_2": "value2", } ) .run_cmd("cat folder/test.txt") .set_workdir("/app") .set_start_cmd("echo 'Hello, world!'", Template.wait_for_timeout("10s")) ) Template.build( template, alias="test-template", cpu_count=1, memory_mb=1024, on_build_logs=lambda log_entry: print(log_entry), ) ``` Python Async ```py from e2b import AsyncTemplate template = ( AsyncTemplate() .from_image("ubuntu:22.04") .copy("folder/*.txt", "folder", force_upload=True) .set_envs( { "ENV_1": "value1", "ENV_2": "value2", } ) .run_cmd("cat folder/test.txt") .set_workdir("/app") .set_start_cmd("echo 'Hello, world!'", Template.wait_for_timeout("10s")) ) await AsyncTemplate.build( template, alias="test-template", cpu_count=1, memory_mb=1024, on_build_logs=lambda log_entry: print(log_entry), ) ``` --- Merge progress - [x] JavaScript SDK - [x] Python SDK - [x] Tests - [x] Split files for review
2025-09-05 22:00:22 +02:00
elif instruction == "USER":
_handle_user_instruction(value, template_builder)
2025-11-26 18:16:25 +01:00
user_changed = True
Add Templates SDK (#871) ### Merge Templates SDK into E2B SDK. This PR merges code from Templates SDK to E2B SDK. **Changelog** - Added new error classes: BuildError, FileUploadError. - Added template API endpoints to API Client generation (Python). - Updated API Clients error handling to throw BuildError in addition to SandboxError. - Exported Template and TemplateAsync classes. - Moved `getRuntime` utility method from api to utils. - Browser is supported except file operations (COPY). Incompatible modules are not bundled, using dynamic imports (tar, glob) in supported environments (Node, Deno, Bun) instead. - Basic tests were added, subject to expansion in a follow-up PR. - Breaking: Before, 401 error was raising `SandboxError`, which was incorrect, now it will raise `AuthenticationError`. I have also changed the `AuthenticationError` to extend Error class, not `SandboxError` anymore as it's now thrown by both Sandbox and Template. **Usage** JavaScript ```js import { Template } from 'e2b'; const template = Template() .fromImage('ubuntu:22.04') .copy('folder/*.txt', 'folder', { forceUpload: true }) .setEnvs({ ENV_1: 'value1', ENV_2: 'value2', }) .runCmd('cat folder/test.txt') .setWorkdir('/app') .setStartCmd('echo "Hello, world!"', Template.waitForTimeout('10s')) await Template.build(template, { alias: 'test-template', cpuCount: 1, memoryMB: 1024, onBuildLogs: (logEntry) => console.log(logEntry.toString()), }) ``` Python ```py from e2b import Template template = ( Template() .from_image("ubuntu:22.04") .copy("folder/*.txt", "folder", force_upload=True) .set_envs( { "ENV_1": "value1", "ENV_2": "value2", } ) .run_cmd("cat folder/test.txt") .set_workdir("/app") .set_start_cmd("echo 'Hello, world!'", Template.wait_for_timeout("10s")) ) Template.build( template, alias="test-template", cpu_count=1, memory_mb=1024, on_build_logs=lambda log_entry: print(log_entry), ) ``` Python Async ```py from e2b import AsyncTemplate template = ( AsyncTemplate() .from_image("ubuntu:22.04") .copy("folder/*.txt", "folder", force_upload=True) .set_envs( { "ENV_1": "value1", "ENV_2": "value2", } ) .run_cmd("cat folder/test.txt") .set_workdir("/app") .set_start_cmd("echo 'Hello, world!'", Template.wait_for_timeout("10s")) ) await AsyncTemplate.build( template, alias="test-template", cpu_count=1, memory_mb=1024, on_build_logs=lambda log_entry: print(log_entry), ) ``` --- Merge progress - [x] JavaScript SDK - [x] Python SDK - [x] Tests - [x] Split files for review
2025-09-05 22:00:22 +02:00
elif instruction in ["ENV", "ARG"]:
_handle_env_instruction(value, instruction, template_builder)
elif instruction in ["CMD", "ENTRYPOINT"]:
_handle_cmd_entrypoint_instruction(value, template_builder)
else:
print(f"Unsupported instruction: {instruction}")
continue
feat: set default user and workdir when using Dockerfile (#954) Set default user for Dockerfiles. Includes also small migrate fixes. <!-- CURSOR_SUMMARY --> --- > [!NOTE] > Defaults Dockerfile-based templates to user 'user' and workdir '/home/user', updates CLI templates (sudo start/ready, relative Python import), and allows template migration without a config file. > > - **SDKs (Dockerfile parsing)**: > - JS (`packages/js-sdk/src/template/dockerfileParser.ts`) and Python (`packages/python-sdk/e2b/template/dockerfile_parser.py`): after parsing, set defaults `setUser('user')` and `setWorkdir('/home/user')`. > - **CLI Templates**: > - Python build scripts: switch to relative import `from .template import template`. > - Generated template hbs: start/ready commands now prefixed with `sudo`; removed explicit root/workdir before start/ready. > - **CLI Migrate**: > - Supports migration without `e2b.toml`; uses default config values and prints a warning instead of exiting. > - Initializes default config when missing; success messaging adjusted. > - **Tests**: > - Update fixtures to reflect new defaults (`set_user('user')`, `set_workdir('/home/user')`, `sudo` start/ready, relative imports). > - Relax error case to succeed with warning when config is missing. > - Comment out stacktrace tests for `fromDockerfile` in JS/Python until fixed. > - **Changesets**: Patch bumps for `@e2b/cli`, `@e2b/python-sdk`, and `e2b`. > > <sup>Written by [Cursor Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit 934dc3b23b5607f70d4a4f5b7a9413a9d04df28a. This will update automatically on new commits. Configure [here](https://cursor.com/dashboard?tab=bugbot).</sup> <!-- /CURSOR_SUMMARY -->
2025-10-15 14:51:40 +02:00
# Set the user and workdir to the E2B defaults
2025-11-26 18:16:25 +01:00
if not user_changed:
template_builder.set_user("user")
if not workdir_changed:
template_builder.set_workdir("/home/user")
feat: set default user and workdir when using Dockerfile (#954) Set default user for Dockerfiles. Includes also small migrate fixes. <!-- CURSOR_SUMMARY --> --- > [!NOTE] > Defaults Dockerfile-based templates to user 'user' and workdir '/home/user', updates CLI templates (sudo start/ready, relative Python import), and allows template migration without a config file. > > - **SDKs (Dockerfile parsing)**: > - JS (`packages/js-sdk/src/template/dockerfileParser.ts`) and Python (`packages/python-sdk/e2b/template/dockerfile_parser.py`): after parsing, set defaults `setUser('user')` and `setWorkdir('/home/user')`. > - **CLI Templates**: > - Python build scripts: switch to relative import `from .template import template`. > - Generated template hbs: start/ready commands now prefixed with `sudo`; removed explicit root/workdir before start/ready. > - **CLI Migrate**: > - Supports migration without `e2b.toml`; uses default config values and prints a warning instead of exiting. > - Initializes default config when missing; success messaging adjusted. > - **Tests**: > - Update fixtures to reflect new defaults (`set_user('user')`, `set_workdir('/home/user')`, `sudo` start/ready, relative imports). > - Relax error case to succeed with warning when config is missing. > - Comment out stacktrace tests for `fromDockerfile` in JS/Python until fixed. > - **Changesets**: Patch bumps for `@e2b/cli`, `@e2b/python-sdk`, and `e2b`. > > <sup>Written by [Cursor Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit 934dc3b23b5607f70d4a4f5b7a9413a9d04df28a. This will update automatically on new commits. Configure [here](https://cursor.com/dashboard?tab=bugbot).</sup> <!-- /CURSOR_SUMMARY -->
2025-10-15 14:51:40 +02:00
Add Templates SDK (#871) ### Merge Templates SDK into E2B SDK. This PR merges code from Templates SDK to E2B SDK. **Changelog** - Added new error classes: BuildError, FileUploadError. - Added template API endpoints to API Client generation (Python). - Updated API Clients error handling to throw BuildError in addition to SandboxError. - Exported Template and TemplateAsync classes. - Moved `getRuntime` utility method from api to utils. - Browser is supported except file operations (COPY). Incompatible modules are not bundled, using dynamic imports (tar, glob) in supported environments (Node, Deno, Bun) instead. - Basic tests were added, subject to expansion in a follow-up PR. - Breaking: Before, 401 error was raising `SandboxError`, which was incorrect, now it will raise `AuthenticationError`. I have also changed the `AuthenticationError` to extend Error class, not `SandboxError` anymore as it's now thrown by both Sandbox and Template. **Usage** JavaScript ```js import { Template } from 'e2b'; const template = Template() .fromImage('ubuntu:22.04') .copy('folder/*.txt', 'folder', { forceUpload: true }) .setEnvs({ ENV_1: 'value1', ENV_2: 'value2', }) .runCmd('cat folder/test.txt') .setWorkdir('/app') .setStartCmd('echo "Hello, world!"', Template.waitForTimeout('10s')) await Template.build(template, { alias: 'test-template', cpuCount: 1, memoryMB: 1024, onBuildLogs: (logEntry) => console.log(logEntry.toString()), }) ``` Python ```py from e2b import Template template = ( Template() .from_image("ubuntu:22.04") .copy("folder/*.txt", "folder", force_upload=True) .set_envs( { "ENV_1": "value1", "ENV_2": "value2", } ) .run_cmd("cat folder/test.txt") .set_workdir("/app") .set_start_cmd("echo 'Hello, world!'", Template.wait_for_timeout("10s")) ) Template.build( template, alias="test-template", cpu_count=1, memory_mb=1024, on_build_logs=lambda log_entry: print(log_entry), ) ``` Python Async ```py from e2b import AsyncTemplate template = ( AsyncTemplate() .from_image("ubuntu:22.04") .copy("folder/*.txt", "folder", force_upload=True) .set_envs( { "ENV_1": "value1", "ENV_2": "value2", } ) .run_cmd("cat folder/test.txt") .set_workdir("/app") .set_start_cmd("echo 'Hello, world!'", Template.wait_for_timeout("10s")) ) await AsyncTemplate.build( template, alias="test-template", cpu_count=1, memory_mb=1024, on_build_logs=lambda log_entry: print(log_entry), ) ``` --- Merge progress - [x] JavaScript SDK - [x] Python SDK - [x] Tests - [x] Split files for review
2025-09-05 22:00:22 +02:00
return base_image
def _handle_run_instruction(
value: str, template_builder: DockerfileParserInterface
) -> None:
"""Handle RUN instruction"""
if not value.strip():
return
# Remove line continuations and normalize whitespace
command = re.sub(r"\\\s*\n\s*", " ", value).strip()
template_builder.run_cmd(command)
def _handle_copy_instruction(
value: str, template_builder: DockerfileParserInterface
) -> None:
"""Handle COPY/ADD instruction"""
if not value.strip():
return
# Parse source and destination from COPY/ADD command
# Handle both quoted and unquoted paths
parts = []
current_part = ""
in_quotes = False
quote_char = None
i = 0
while i < len(value):
char = value[i]
if char in ['"', "'"] and (i == 0 or value[i - 1] != "\\"):
if not in_quotes:
in_quotes = True
quote_char = char
elif char == quote_char:
in_quotes = False
quote_char = None
else:
current_part += char
elif char == " " and not in_quotes:
if current_part:
parts.append(current_part)
current_part = ""
else:
current_part += char
i += 1
if current_part:
parts.append(current_part)
# Extract --chown flag and separate from paths
user = None
non_flag_parts = []
for part in parts:
if part.startswith("--chown="):
user = part[8:] # Extract value after "--chown="
elif not part.startswith("--"):
non_flag_parts.append(part)
if len(non_flag_parts) >= 2:
src = non_flag_parts[0]
dest = non_flag_parts[-1] # Last part is destination
template_builder.copy(src, dest, user=user)
Add Templates SDK (#871) ### Merge Templates SDK into E2B SDK. This PR merges code from Templates SDK to E2B SDK. **Changelog** - Added new error classes: BuildError, FileUploadError. - Added template API endpoints to API Client generation (Python). - Updated API Clients error handling to throw BuildError in addition to SandboxError. - Exported Template and TemplateAsync classes. - Moved `getRuntime` utility method from api to utils. - Browser is supported except file operations (COPY). Incompatible modules are not bundled, using dynamic imports (tar, glob) in supported environments (Node, Deno, Bun) instead. - Basic tests were added, subject to expansion in a follow-up PR. - Breaking: Before, 401 error was raising `SandboxError`, which was incorrect, now it will raise `AuthenticationError`. I have also changed the `AuthenticationError` to extend Error class, not `SandboxError` anymore as it's now thrown by both Sandbox and Template. **Usage** JavaScript ```js import { Template } from 'e2b'; const template = Template() .fromImage('ubuntu:22.04') .copy('folder/*.txt', 'folder', { forceUpload: true }) .setEnvs({ ENV_1: 'value1', ENV_2: 'value2', }) .runCmd('cat folder/test.txt') .setWorkdir('/app') .setStartCmd('echo "Hello, world!"', Template.waitForTimeout('10s')) await Template.build(template, { alias: 'test-template', cpuCount: 1, memoryMB: 1024, onBuildLogs: (logEntry) => console.log(logEntry.toString()), }) ``` Python ```py from e2b import Template template = ( Template() .from_image("ubuntu:22.04") .copy("folder/*.txt", "folder", force_upload=True) .set_envs( { "ENV_1": "value1", "ENV_2": "value2", } ) .run_cmd("cat folder/test.txt") .set_workdir("/app") .set_start_cmd("echo 'Hello, world!'", Template.wait_for_timeout("10s")) ) Template.build( template, alias="test-template", cpu_count=1, memory_mb=1024, on_build_logs=lambda log_entry: print(log_entry), ) ``` Python Async ```py from e2b import AsyncTemplate template = ( AsyncTemplate() .from_image("ubuntu:22.04") .copy("folder/*.txt", "folder", force_upload=True) .set_envs( { "ENV_1": "value1", "ENV_2": "value2", } ) .run_cmd("cat folder/test.txt") .set_workdir("/app") .set_start_cmd("echo 'Hello, world!'", Template.wait_for_timeout("10s")) ) await AsyncTemplate.build( template, alias="test-template", cpu_count=1, memory_mb=1024, on_build_logs=lambda log_entry: print(log_entry), ) ``` --- Merge progress - [x] JavaScript SDK - [x] Python SDK - [x] Tests - [x] Split files for review
2025-09-05 22:00:22 +02:00
def _handle_workdir_instruction(
value: str, template_builder: DockerfileParserInterface
) -> None:
"""Handle WORKDIR instruction"""
if not value.strip():
return
workdir = value.strip()
template_builder.set_workdir(workdir)
def _handle_user_instruction(
value: str, template_builder: DockerfileParserInterface
) -> None:
"""Handle USER instruction"""
if not value.strip():
return
user = value.strip()
template_builder.set_user(user)
def _handle_env_instruction(
value: str, instruction_type: str, template_builder: DockerfileParserInterface
) -> None:
"""Handle ENV/ARG instruction"""
if not value.strip():
return
# Parse environment variables from the value
# Handle both "KEY=value" and "KEY value" formats
env_vars = {}
# First try to split on = for KEY=value format
if "=" in value:
# Handle multiple KEY=value pairs on one line
pairs = re.findall(r"(\w+)=([^\s]*(?:\s+(?!\w+=)[^\s]*)*)", value)
for key, val in pairs:
env_vars[key] = val.strip("\"'")
else:
# Handle "KEY value" format
parts = value.split(None, 1)
if len(parts) == 2:
key, val = parts
env_vars[key] = val.strip("\"'")
elif len(parts) == 1 and instruction_type == "ARG":
# ARG without default value
key = parts[0]
env_vars[key] = ""
# Add each environment variable
if env_vars:
template_builder.set_envs(env_vars)
def _handle_cmd_entrypoint_instruction(
value: str, template_builder: DockerfileParserInterface
) -> None:
Improve method naming and consistency (#934) <!-- CURSOR_SUMMARY --> > [!NOTE] > Unifies Template APIs across JS/Python with PathLike support, new copyItems, option/name tweaks, and simpler registry auth via credentials; updates parser, exports, and tests. > > - **Template API (JS + Python)** > - Add PathLike support for paths in `copy`, `remove`, `rename`, `makeDir`, `makeSymlink`, `setWorkdir`, and `gitClone`. > - Introduce `copyItems` and corresponding `CopyItem` typing; adjust Dockerfile parser to use `copyItems` overload. > - Simplify registry auth: `fromImage(baseImage, credentials)` accepts `{username,password}`; remove `fromRegistry`; update `fromAWSRegistry`/`fromGCPRegistry` to take credentials and set config internally. > - Rename options: `ignoreFilePaths` -> `fileIgnorePatterns`; `fileContextPath` can be `PathLike`. > - Ensure internal hashing/upload use stringified paths; minor enum/type tweaks (e.g., `InstructionType` as string enum, `forceUpload?: true`). > - **Exports** > - Export `CopyItem` from JS `index.ts` and Python `__init__.py`. > - **Tests** > - Update stacktrace and build tests to new method names/signatures (e.g., registry via `fromImage` credentials, new `copyItems` tests, optional `skipCache` param). > > <sup>Written by [Cursor Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit 95391030550a340fe99ebaac4494867b3e3e9507. This will update automatically on new commits. Configure [here](https://cursor.com/dashboard?tab=bugbot).</sup> <!-- /CURSOR_SUMMARY --> --------- Co-authored-by: Jakub Dobry <jakub.dobry8@gmail.com>
2025-10-09 00:51:02 +02:00
"""Handle CMD/ENTRYPOINT instruction - convert to set_start_cmd with 20s timeout"""
Add Templates SDK (#871) ### Merge Templates SDK into E2B SDK. This PR merges code from Templates SDK to E2B SDK. **Changelog** - Added new error classes: BuildError, FileUploadError. - Added template API endpoints to API Client generation (Python). - Updated API Clients error handling to throw BuildError in addition to SandboxError. - Exported Template and TemplateAsync classes. - Moved `getRuntime` utility method from api to utils. - Browser is supported except file operations (COPY). Incompatible modules are not bundled, using dynamic imports (tar, glob) in supported environments (Node, Deno, Bun) instead. - Basic tests were added, subject to expansion in a follow-up PR. - Breaking: Before, 401 error was raising `SandboxError`, which was incorrect, now it will raise `AuthenticationError`. I have also changed the `AuthenticationError` to extend Error class, not `SandboxError` anymore as it's now thrown by both Sandbox and Template. **Usage** JavaScript ```js import { Template } from 'e2b'; const template = Template() .fromImage('ubuntu:22.04') .copy('folder/*.txt', 'folder', { forceUpload: true }) .setEnvs({ ENV_1: 'value1', ENV_2: 'value2', }) .runCmd('cat folder/test.txt') .setWorkdir('/app') .setStartCmd('echo "Hello, world!"', Template.waitForTimeout('10s')) await Template.build(template, { alias: 'test-template', cpuCount: 1, memoryMB: 1024, onBuildLogs: (logEntry) => console.log(logEntry.toString()), }) ``` Python ```py from e2b import Template template = ( Template() .from_image("ubuntu:22.04") .copy("folder/*.txt", "folder", force_upload=True) .set_envs( { "ENV_1": "value1", "ENV_2": "value2", } ) .run_cmd("cat folder/test.txt") .set_workdir("/app") .set_start_cmd("echo 'Hello, world!'", Template.wait_for_timeout("10s")) ) Template.build( template, alias="test-template", cpu_count=1, memory_mb=1024, on_build_logs=lambda log_entry: print(log_entry), ) ``` Python Async ```py from e2b import AsyncTemplate template = ( AsyncTemplate() .from_image("ubuntu:22.04") .copy("folder/*.txt", "folder", force_upload=True) .set_envs( { "ENV_1": "value1", "ENV_2": "value2", } ) .run_cmd("cat folder/test.txt") .set_workdir("/app") .set_start_cmd("echo 'Hello, world!'", Template.wait_for_timeout("10s")) ) await AsyncTemplate.build( template, alias="test-template", cpu_count=1, memory_mb=1024, on_build_logs=lambda log_entry: print(log_entry), ) ``` --- Merge progress - [x] JavaScript SDK - [x] Python SDK - [x] Tests - [x] Split files for review
2025-09-05 22:00:22 +02:00
if not value.strip():
return
command = value.strip()
# Try to parse as JSON (for array format like CMD ["sleep", "infinity"])
try:
parsed_command = json.loads(command)
if isinstance(parsed_command, list):
command = " ".join(str(item) for item in parsed_command)
except Exception:
pass
Add Templates SDK (#871) ### Merge Templates SDK into E2B SDK. This PR merges code from Templates SDK to E2B SDK. **Changelog** - Added new error classes: BuildError, FileUploadError. - Added template API endpoints to API Client generation (Python). - Updated API Clients error handling to throw BuildError in addition to SandboxError. - Exported Template and TemplateAsync classes. - Moved `getRuntime` utility method from api to utils. - Browser is supported except file operations (COPY). Incompatible modules are not bundled, using dynamic imports (tar, glob) in supported environments (Node, Deno, Bun) instead. - Basic tests were added, subject to expansion in a follow-up PR. - Breaking: Before, 401 error was raising `SandboxError`, which was incorrect, now it will raise `AuthenticationError`. I have also changed the `AuthenticationError` to extend Error class, not `SandboxError` anymore as it's now thrown by both Sandbox and Template. **Usage** JavaScript ```js import { Template } from 'e2b'; const template = Template() .fromImage('ubuntu:22.04') .copy('folder/*.txt', 'folder', { forceUpload: true }) .setEnvs({ ENV_1: 'value1', ENV_2: 'value2', }) .runCmd('cat folder/test.txt') .setWorkdir('/app') .setStartCmd('echo "Hello, world!"', Template.waitForTimeout('10s')) await Template.build(template, { alias: 'test-template', cpuCount: 1, memoryMB: 1024, onBuildLogs: (logEntry) => console.log(logEntry.toString()), }) ``` Python ```py from e2b import Template template = ( Template() .from_image("ubuntu:22.04") .copy("folder/*.txt", "folder", force_upload=True) .set_envs( { "ENV_1": "value1", "ENV_2": "value2", } ) .run_cmd("cat folder/test.txt") .set_workdir("/app") .set_start_cmd("echo 'Hello, world!'", Template.wait_for_timeout("10s")) ) Template.build( template, alias="test-template", cpu_count=1, memory_mb=1024, on_build_logs=lambda log_entry: print(log_entry), ) ``` Python Async ```py from e2b import AsyncTemplate template = ( AsyncTemplate() .from_image("ubuntu:22.04") .copy("folder/*.txt", "folder", force_upload=True) .set_envs( { "ENV_1": "value1", "ENV_2": "value2", } ) .run_cmd("cat folder/test.txt") .set_workdir("/app") .set_start_cmd("echo 'Hello, world!'", Template.wait_for_timeout("10s")) ) await AsyncTemplate.build( template, alias="test-template", cpu_count=1, memory_mb=1024, on_build_logs=lambda log_entry: print(log_entry), ) ``` --- Merge progress - [x] JavaScript SDK - [x] Python SDK - [x] Tests - [x] Split files for review
2025-09-05 22:00:22 +02:00
# Import wait_for_timeout locally to avoid circular dependency
def wait_for_timeout(timeout: int) -> str:
# convert to seconds, but ensure minimum of 1 second
seconds = max(1, timeout // 1000)
return f"sleep {seconds}"
template_builder.set_start_cmd(command, wait_for_timeout(20_000))