Skip to content

armgit / E2B

Public Imported from GitHub
0

Open-source, secure environment with real-world tools for enterprise-grade agents.

Correct file hashing logic in the SDK (#916)

Mish Ushakovb1e2701931a1
diff --git a/.changeset/metal-penguins-begin.md b/.changeset/metal-penguins-begin.md
new file mode 100644
index 000000000..16b682f73
--- /dev/null
+++ b/.changeset/metal-penguins-begin.md
@@ -0,0 +1,6 @@
+---
+'@e2b/python-sdk': patch
+'e2b': patch
+---
+
+fix template build files copy cache invalidation
diff --git a/packages/js-sdk/src/template/buildApi.ts b/packages/js-sdk/src/template/buildApi.ts
index 2aa4bce34..86fc53464 100644
--- a/packages/js-sdk/src/template/buildApi.ts
+++ b/packages/js-sdk/src/template/buildApi.ts
@@ -1,8 +1,8 @@
-import { ApiClient, paths, handleApiError } from '../api'
+import { ApiClient, handleApiError, paths } from '../api'
+import { stripAnsi } from '../utils'
import { BuildError, FileUploadError } from './errors'
import { LogEntry } from './types'
import { getBuildStepIndex, tarFileStreamUpload } from './utils'
-import { stripAnsi } from '../utils'
type RequestBuildInput = {
alias: string
@@ -91,14 +91,16 @@ export async function uploadFile(
fileName: string
fileContextPath: string
url: string
+ resolveSymlinks: boolean
},
- stackTrace?: string
+ stackTrace: string | undefined
) {
- const { fileName, url, fileContextPath } = options
+ const { fileName, url, fileContextPath, resolveSymlinks } = options
try {
const { contentLength, uploadStream } = await tarFileStreamUpload(
fileName,
- fileContextPath
+ fileContextPath,
+ resolveSymlinks
)
// The compiler assumes this is Web fetch API, but it's actually Node.js fetch API
diff --git a/packages/js-sdk/src/template/consts.ts b/packages/js-sdk/src/template/consts.ts
index d81a9ca54..c4ba56511 100644
--- a/packages/js-sdk/src/template/consts.ts
+++ b/packages/js-sdk/src/template/consts.ts
@@ -8,3 +8,5 @@ export const BASE_STEP_NAME = 'base'
* 3. Caller method (eg. copy(), fromImage(), etc.)
*/
export const STACK_TRACE_DEPTH = 3
+
+export const RESOLVE_SYMLINKS = false
diff --git a/packages/js-sdk/src/template/index.ts b/packages/js-sdk/src/template/index.ts
index 759f59d6e..6a9026807 100644
--- a/packages/js-sdk/src/template/index.ts
+++ b/packages/js-sdk/src/template/index.ts
@@ -9,7 +9,7 @@ import {
uploadFile,
waitForBuildFinish,
} from './buildApi'
-import { STACK_TRACE_DEPTH } from './consts'
+import { RESOLVE_SYMLINKS, STACK_TRACE_DEPTH } from './consts'
import { parseDockerfile } from './dockerfileParser'
import { ReadyCmd } from './readycmd'
import {
@@ -228,18 +228,30 @@ export class TemplateBase
copy(
src: string,
dest: string,
- options?: { forceUpload?: true; user?: string; mode?: number }
- ): TemplateBuilder
- copy(
- items: CopyItem[],
- options?: { forceUpload?: true; user?: string; mode?: number }
+ options?: {
+ forceUpload?: true
+ user?: string
+ mode?: number
+ resolveSymlinks?: boolean
+ }
): TemplateBuilder
+ copy(items: CopyItem[]): TemplateBuilder
copy(
srcOrItems: string | CopyItem[],
destOrOptions?:
| string
- | { forceUpload?: true; user?: string; mode?: number },
- options?: { forceUpload?: true; user?: string; mode?: number }
+ | {
+ forceUpload?: true
+ user?: string
+ mode?: number
+ resolveSymlinks?: boolean
+ },
+ options?: {
+ forceUpload?: true
+ user?: string
+ mode?: number
+ resolveSymlinks?: boolean
+ }
): TemplateBuilder {
if (runtime === 'browser') {
throw new Error('Browser runtime is not supported for copy')
@@ -254,6 +266,7 @@ export class TemplateBase
mode: options?.mode,
user: options?.user,
forceUpload: options?.forceUpload,
+ resolveSymlinks: options?.resolveSymlinks,
},
]
for (const item of items) {
@@ -269,6 +282,7 @@ export class TemplateBase
args,
force: item.forceUpload ?? this.forceNextLayer,
forceUpload: item.forceUpload,
+ resolveSymlinks: item.resolveSymlinks,
})
}
@@ -610,6 +624,7 @@ export class TemplateBase
fileName: src,
fileContextPath: this.fileContextPath,
url,
+ resolveSymlinks: instruction.resolveSymlinks ?? RESOLVE_SYMLINKS,
},
stackTrace
)
@@ -689,6 +704,7 @@ export class TemplateBase
? []
: readDockerignore(this.fileContextPath)),
],
+ instruction.resolveSymlinks ?? RESOLVE_SYMLINKS,
stackTrace
),
}
diff --git a/packages/js-sdk/src/template/types.ts b/packages/js-sdk/src/template/types.ts
index 3c7a50ca4..7c1f29e57 100644
--- a/packages/js-sdk/src/template/types.ts
+++ b/packages/js-sdk/src/template/types.ts
@@ -15,6 +15,7 @@ export type Instruction = {
force: boolean
forceUpload?: boolean
filesHash?: string
+ resolveSymlinks?: boolean
}
export type CopyItem = {
@@ -23,6 +24,7 @@ export type CopyItem = {
forceUpload?: boolean
user?: string
mode?: number
+ resolveSymlinks?: boolean
}
// Interface for the initial state
@@ -75,13 +77,15 @@ export interface TemplateBuilder {
copy(
src: string,
dest: string,
- options?: { forceUpload?: true; user?: string; mode?: number }
+ options?: {
+ forceUpload?: true
+ user?: string
+ mode?: number
+ resolveSymlinks?: boolean
+ }
): TemplateBuilder
- copy(
- items: CopyItem[],
- options?: { forceUpload?: true; user?: string; mode?: number }
- ): TemplateBuilder
+ copy(items: CopyItem[]): TemplateBuilder
remove(
path: string,
diff --git a/packages/js-sdk/src/template/utils.ts b/packages/js-sdk/src/template/utils.ts
index feef1dcab..8ab4dc96a 100644
--- a/packages/js-sdk/src/template/utils.ts
+++ b/packages/js-sdk/src/template/utils.ts
@@ -21,8 +21,9 @@ export async function calculateFilesHash(
src: string,
dest: string,
contextPath: string,
- ignorePatterns?: string[],
- stackTrace?: string
+ ignorePatterns: string[],
+ resolveSymlinks: boolean,
+ stackTrace: string | undefined
): Promise<string> {
const { glob } = await dynamicGlob()
const srcPath = path.join(contextPath, src)
@@ -44,13 +45,47 @@ export async function calculateFilesHash(
throw error
}
+ // Hash stats
+ const hashStats = (stats: fs.Stats) => {
+ hash.update(stats.mode.toString())
+ hash.update(stats.uid.toString())
+ hash.update(stats.gid.toString())
+ hash.update(stats.size.toString())
+ hash.update(stats.mtimeMs.toString())
+ }
+
for (const file of files) {
- if (!file.isFile()) {
- continue
+ // Add a relative path to hash calculation
+ const relativePath = path.relative(contextPath, file.fullpath())
+ hash.update(relativePath)
+
+ // Add stat information to hash calculation
+ if (file.isSymbolicLink()) {
+ // If the symlink is broken, it will return undefined, otherwise it will return a stats object of the target
+ const stats = fs.statSync(file.fullpath(), { throwIfNoEntry: false })
+ const shouldFollow =
+ resolveSymlinks && (stats?.isFile() || stats?.isDirectory())
+
+ if (!shouldFollow) {
+ const stats = fs.lstatSync(file.fullpath())
+
+ hashStats(stats)
+
+ const content = fs.readlinkSync(file.fullpath())
+ hash.update(content)
+
+ continue
+ }
}
- const content = fs.readFileSync(file.fullpath())
- hash.update(new Uint8Array(content))
+ const stats = fs.statSync(file.fullpath())
+
+ hashStats(stats)
+
+ if (stats.isFile()) {
+ const content = fs.readFileSync(file.fullpath())
+ hash.update(new Uint8Array(content))
+ }
}
return hash.digest('hex')
@@ -105,15 +140,20 @@ export function padOctal(mode: number): string {
return mode.toString(8).padStart(4, '0')
}
-export async function tarFileStream(fileName: string, fileContextPath: string) {
+export async function tarFileStream(
+ fileName: string,
+ fileContextPath: string,
+ resolveSymlinks: boolean
+) {
const { globSync } = await dynamicGlob()
const { create } = await dynamicTar()
- const files = globSync(fileName, { cwd: fileContextPath, nodir: false })
+ const files = globSync(fileName, { cwd: fileContextPath })
return create(
{
gzip: true,
cwd: fileContextPath,
+ follow: resolveSymlinks,
},
files
)
@@ -121,10 +161,15 @@ export async function tarFileStream(fileName: string, fileContextPath: string) {
export async function tarFileStreamUpload(
fileName: string,
- fileContextPath: string
+ fileContextPath: string,
+ resolveSymlinks: boolean
) {
// First pass: calculate the compressed size without buffering
- const sizeCalculationStream = await tarFileStream(fileName, fileContextPath)
+ const sizeCalculationStream = await tarFileStream(
+ fileName,
+ fileContextPath,
+ resolveSymlinks
+ )
let contentLength = 0
for await (const chunk of sizeCalculationStream as unknown as AsyncIterable<Buffer>) {
contentLength += chunk.length
@@ -132,7 +177,11 @@ export async function tarFileStreamUpload(
return {
contentLength,
- uploadStream: await tarFileStream(fileName, fileContextPath),
+ uploadStream: await tarFileStream(
+ fileName,
+ fileContextPath,
+ resolveSymlinks
+ ),
}
}
diff --git a/packages/js-sdk/tests/setup.ts b/packages/js-sdk/tests/setup.ts
index 5224373db..3fade5e0f 100644
--- a/packages/js-sdk/tests/setup.ts
+++ b/packages/js-sdk/tests/setup.ts
@@ -1,6 +1,7 @@
-import { Sandbox } from '../src'
+import { Sandbox, Template, TemplateClass } from '../src'
import { test as base } from 'vitest'
import { template } from './template'
+import { randomUUID } from 'node:crypto'
interface SandboxFixture {
sandbox: Sandbox
@@ -8,6 +9,19 @@ interface SandboxFixture {
sandboxTestId: string
}
+interface BuildTemplateFixture {
+ buildTemplate: (template: TemplateClass) => Promise<void>
+}
+
+function buildTemplate(template: TemplateClass, skipCache?: boolean) {
+ return Template.build(template, {
+ alias: randomUUID(),
+ cpuCount: 1,
+ memoryMB: 1024,
+ skipCache: skipCache,
+ })
+}
+
export const sandboxTest = base.extend<SandboxFixture>({
template,
sandboxTestId: [
@@ -41,6 +55,16 @@ export const sandboxTest = base.extend<SandboxFixture>({
],
})
+export const buildTemplateTest = base.extend<BuildTemplateFixture>({
+ buildTemplate: [
+ // eslint-disable-next-line no-empty-pattern
+ async ({}, use) => {
+ await use(buildTemplate)
+ },
+ { auto: true },
+ ],
+})
+
export const isDebug = process.env.E2B_DEBUG !== undefined
export const isIntegrationTest = process.env.E2B_INTEGRATION_TEST !== undefined
diff --git a/packages/js-sdk/tests/template/build.test.ts b/packages/js-sdk/tests/template/build.test.ts
index 3baeaeee3..281eacb67 100644
--- a/packages/js-sdk/tests/template/build.test.ts
+++ b/packages/js-sdk/tests/template/build.test.ts
@@ -1,31 +1,72 @@
-import { test } from 'vitest'
+import { afterAll, beforeAll } from 'vitest'
+import { buildTemplateTest } from '../setup'
import { Template, waitForTimeout } from '../../src'
-import { randomUUID } from 'node:crypto'
import path from 'node:path'
import fs from 'node:fs'
-test('build template', { timeout: 180000 }, async () => {
- const folderPath = path.join(__dirname, 'folder')
+const folderPath = path.join(__dirname, 'folder')
+
+beforeAll(async () => {
fs.mkdirSync(folderPath, { recursive: true })
fs.writeFileSync(path.join(folderPath, 'test.txt'), 'This is a test file.')
- const template = Template()
- .fromImage('ubuntu:22.04')
- .copy('folder/*.txt', 'folder', { forceUpload: true })
- .copy('folder', 'folder2', { forceUpload: true })
- .setEnvs({
- ENV_1: 'value1',
- ENV_2: 'value2',
- })
- .runCmd('cat folder/test.txt')
- .setWorkdir('/app')
- .setStartCmd('echo "Hello, world!"', waitForTimeout(10_000))
-
- await Template.build(template, {
- alias: randomUUID(),
- cpuCount: 1,
- memoryMB: 1024,
- })
+ // Create relative symlink
+ fs.symlinkSync('test.txt', path.join(folderPath, 'symlink.txt'))
+
+ // Create absolute symlink
+ fs.symlinkSync(
+ path.join(folderPath, 'test.txt'),
+ path.join(folderPath, 'symlink2.txt')
+ )
+ // Create a symlink to a file that does not exist
+ fs.symlinkSync('12345test.txt', path.join(folderPath, 'symlink3.txt'))
+})
+
+afterAll(() => {
fs.rmSync(folderPath, { recursive: true })
})
+
+buildTemplateTest(
+ 'build template',
+ { timeout: 180000 },
+ async ({ buildTemplate }) => {
+ const template = Template()
+ .fromImage('ubuntu:22.04')
+ .copy('folder/*', 'folder', { forceUpload: true })
+ .runCmd('cat folder/test.txt')
+ .setWorkdir('/app')
+ .setStartCmd('echo "Hello, world!"', waitForTimeout(10_000))
+
+ await buildTemplate(template)
+ }
+)
+
+buildTemplateTest(
+ 'build template with symlinks',
+ { timeout: 180000 },
+ async ({ buildTemplate }) => {
+ const template = Template()
+ .fromImage('ubuntu:22.04')
+ .copy('folder/*', 'folder', { forceUpload: true })
+ .runCmd('cat folder/symlink.txt')
+
+ await buildTemplate(template)
+ }
+)
+
+buildTemplateTest(
+ 'build template with resolveSymlinks',
+ { timeout: 180000 },
+ async ({ buildTemplate }) => {
+ const template = Template()
+ .fromImage('ubuntu:22.04')
+ .copy('folder/symlink.txt', 'folder/symlink.txt', {
+ forceUpload: true,
+ resolveSymlinks: true,
+ })
+ .runCmd('cat folder/symlink.txt')
+
+ await buildTemplate(template)
+ }
+)
diff --git a/packages/js-sdk/tests/template/stacktrace.test.ts b/packages/js-sdk/tests/template/stacktrace.test.ts
index 3782be658..a5560d3db 100644
--- a/packages/js-sdk/tests/template/stacktrace.test.ts
+++ b/packages/js-sdk/tests/template/stacktrace.test.ts
@@ -1,20 +1,11 @@
-import { assert, test } from 'vitest'
-import { Template, TemplateClass, waitForTimeout } from '../../src'
-import { randomUUID } from 'node:crypto'
+import { assert } from 'vitest'
+import { Template, waitForTimeout } from '../../src'
import fs from 'node:fs'
+import { buildTemplateTest } from '../setup'
const __fileContent = fs.readFileSync(__filename, 'utf8') // read current file content
const nonExistentPath = '/nonexistent/path'
-function buildTemplate(template: TemplateClass, skipCache?: boolean) {
- return Template.build(template, {
- alias: randomUUID(),
- cpuCount: 1,
- memoryMB: 1024,
- skipCache: skipCache,
- })
-}
-
function getStackTraceCallerMethod(
fileContent: string,
stackTrace: string | undefined
@@ -62,7 +53,7 @@ async function expectToThrowAndCheckTrace(
}
}
-test('traces on fromImage', async () => {
+buildTemplateTest('traces on fromImage', async ({ buildTemplate }) => {
const templateFrom = Template()
const template = templateFrom.fromImage('e2b.dev/this-image-does-not-exist')
await expectToThrowAndCheckTrace(async () => {
@@ -79,7 +70,7 @@ test('traces on fromImage', async () => {
// }, 'fromTemplate')
// })
-test('traces on fromDockerfile', async () => {
+buildTemplateTest('traces on fromDockerfile', async ({ buildTemplate }) => {
const templateFrom = Template()
const template = templateFrom.fromDockerfile(
'FROM ubuntu:22.04\nRUN nonexistent'
@@ -89,7 +80,7 @@ test('traces on fromDockerfile', async () => {
}, 'fromDockerfile')
})
-test('traces on fromRegistry', async () => {
+buildTemplateTest('traces on fromRegistry', async ({ buildTemplate }) => {
const templateFrom = Template()
const template = templateFrom.fromRegistry(
'registry.example.com/nonexistent:latest',
@@ -103,7 +94,7 @@ test('traces on fromRegistry', async () => {
}, 'fromRegistry')
})
-test('traces on fromAWSRegistry', async () => {
+buildTemplateTest('traces on fromAWSRegistry', async ({ buildTemplate }) => {
const templateFrom = Template()
const template = templateFrom.fromAWSRegistry(
'123456789.dkr.ecr.us-east-1.amazonaws.com/nonexistent:latest',
@@ -118,7 +109,7 @@ test('traces on fromAWSRegistry', async () => {
}, 'fromAWSRegistry')
})
-test('traces on fromGCPRegistry', async () => {
+buildTemplateTest('traces on fromGCPRegistry', async ({ buildTemplate }) => {
const templateFrom = Template()
const template = templateFrom.fromGCPRegistry(
'gcr.io/nonexistent-project/nonexistent:latest',
@@ -131,7 +122,7 @@ test('traces on fromGCPRegistry', async () => {
}, 'fromGCPRegistry')
})
-test('traces on copy', async () => {
+buildTemplateTest('traces on copy', async ({ buildTemplate }) => {
let template = Template().fromBaseImage()
template = template.skipCache().copy(nonExistentPath, nonExistentPath)
await expectToThrowAndCheckTrace(async () => {
@@ -139,7 +130,7 @@ test('traces on copy', async () => {
}, 'copy')
})
-test('traces on remove', async () => {
+buildTemplateTest('traces on remove', async ({ buildTemplate }) => {
let template = Template().fromBaseImage()
template = template.skipCache().remove(nonExistentPath)
await expectToThrowAndCheckTrace(async () => {
@@ -147,7 +138,7 @@ test('traces on remove', async () => {
}, 'remove')
})
-test('traces on rename', async () => {
+buildTemplateTest('traces on rename', async ({ buildTemplate }) => {
let template = Template().fromBaseImage()
template = template.skipCache().rename(nonExistentPath, '/tmp/dest.txt')
await expectToThrowAndCheckTrace(async () => {
@@ -155,7 +146,7 @@ test('traces on rename', async () => {
}, 'rename')
})
-test('traces on makeDir', async () => {
+buildTemplateTest('traces on makeDir', async ({ buildTemplate }) => {
let template = Template().fromBaseImage()
template = template.skipCache().makeDir('.bashrc')
await expectToThrowAndCheckTrace(async () => {
@@ -163,7 +154,7 @@ test('traces on makeDir', async () => {
}, 'makeDir')
})
-test('traces on makeSymlink', async () => {
+buildTemplateTest('traces on makeSymlink', async ({ buildTemplate }) => {
let template = Template().fromBaseImage()
template = template.skipCache().makeSymlink('.bashrc', '.bashrc')
await expectToThrowAndCheckTrace(async () => {
@@ -171,7 +162,7 @@ test('traces on makeSymlink', async () => {
}, 'makeSymlink')
})
-test('traces on runCmd', async () => {
+buildTemplateTest('traces on runCmd', async ({ buildTemplate }) => {
let template = Template().fromBaseImage()
template = template.skipCache().runCmd(`./${nonExistentPath}`)
await expectToThrowAndCheckTrace(async () => {
@@ -179,7 +170,7 @@ test('traces on runCmd', async () => {
}, 'runCmd')
})
-test('traces on setWorkdir', async () => {
+buildTemplateTest('traces on setWorkdir', async ({ buildTemplate }) => {
let template = Template().fromBaseImage()
template = template.skipCache().setWorkdir('.bashrc')
await expectToThrowAndCheckTrace(async () => {
@@ -187,7 +178,7 @@ test('traces on setWorkdir', async () => {
}, 'setWorkdir')
})
-test('traces on setUser', async () => {
+buildTemplateTest('traces on setUser', async ({ buildTemplate }) => {
let template = Template().fromBaseImage()
template = template.skipCache().setUser(';')
await expectToThrowAndCheckTrace(async () => {
@@ -195,7 +186,7 @@ test('traces on setUser', async () => {
}, 'setUser')
})
-test('traces on pipInstall', async () => {
+buildTemplateTest('traces on pipInstall', async ({ buildTemplate }) => {
let template = Template().fromBaseImage()
template = template.skipCache().pipInstall('nonexistent-package')
await expectToThrowAndCheckTrace(async () => {
@@ -203,7 +194,7 @@ test('traces on pipInstall', async () => {
}, 'pipInstall')
})
-test('traces on npmInstall', async () => {
+buildTemplateTest('traces on npmInstall', async ({ buildTemplate }) => {
let template = Template().fromBaseImage()
template = template.skipCache().npmInstall('nonexistent-package')
await expectToThrowAndCheckTrace(async () => {
@@ -211,7 +202,7 @@ test('traces on npmInstall', async () => {
}, 'npmInstall')
})
-test('traces on aptInstall', async () => {
+buildTemplateTest('traces on aptInstall', async ({ buildTemplate }) => {
let template = Template().fromBaseImage()
template = template.skipCache().aptInstall('nonexistent-package')
await expectToThrowAndCheckTrace(async () => {
@@ -219,7 +210,7 @@ test('traces on aptInstall', async () => {
}, 'aptInstall')
})
-test('traces on gitClone', async () => {
+buildTemplateTest('traces on gitClone', async ({ buildTemplate }) => {
let template = Template().fromBaseImage()
template = template
.skipCache()
@@ -229,7 +220,7 @@ test('traces on gitClone', async () => {
}, 'gitClone')
})
-test('traces on setStartCmd', async () => {
+buildTemplateTest('traces on setStartCmd', async ({ buildTemplate }) => {
let template: any = Template().fromBaseImage()
template = template.setStartCmd(
`./${nonExistentPath}`,
diff --git a/packages/python-sdk/e2b/template/consts.py b/packages/python-sdk/e2b/template/consts.py
index 1ae88cff4..9d6121863 100644
--- a/packages/python-sdk/e2b/template/consts.py
+++ b/packages/python-sdk/e2b/template/consts.py
@@ -7,3 +7,5 @@ Depths explained:
2. Caller method (eg. copy(), fromImage(), etc.)
"""
STACK_TRACE_DEPTH = 2
+
+RESOLVE_SYMLINKS = False
diff --git a/packages/python-sdk/e2b/template/main.py b/packages/python-sdk/e2b/template/main.py
index bc503fc7a..5d5a86240 100644
--- a/packages/python-sdk/e2b/template/main.py
+++ b/packages/python-sdk/e2b/template/main.py
@@ -1,10 +1,11 @@
import json
from typing import Dict, List, Optional, Union
-from types import TracebackType
+
from httpx import Limits
-from e2b.template.consts import STACK_TRACE_DEPTH
+from e2b.template.consts import STACK_TRACE_DEPTH, RESOLVE_SYMLINKS
from e2b.template.dockerfile_parser import parse_dockerfile
+from e2b.template.readycmd import ReadyCmd
from e2b.template.types import (
CopyItem,
Instruction,
@@ -20,7 +21,7 @@ from e2b.template.utils import (
read_gcp_service_account_json,
get_caller_frame,
)
-from e2b.template.readycmd import ReadyCmd
+from types import TracebackType
class TemplateBuilder:
@@ -34,19 +35,21 @@ class TemplateBuilder:
force_upload: Optional[bool] = None,
user: Optional[str] = None,
mode: Optional[int] = None,
+ resolve_symlinks: Optional[bool] = None,
) -> "TemplateBuilder":
if isinstance(src, str):
# Single copy operation
if dest is None:
raise ValueError("dest parameter is required when src is a string")
copy_items: List[CopyItem] = [
- {
- "src": src,
- "dest": dest,
- "forceUpload": force_upload,
- "user": user,
- "mode": mode,
- }
+ CopyItem(
+ src=src,
+ dest=dest,
+ forceUpload=force_upload,
+ user=user,
+ mode=mode,
+ resolveSymlinks=resolve_symlinks,
+ )
]
else:
# Multiple copy operations
@@ -65,6 +68,7 @@ class TemplateBuilder:
args=args,
force=force_upload or self._template._force_next_layer,
forceUpload=force_upload,
+ resolveSymlinks=resolve_symlinks,
)
self._template._instructions.append(instruction)
self._template._collect_stack_trace()
@@ -505,10 +509,11 @@ class TemplateBase:
for index, instruction in enumerate(self._instructions):
step: Instruction = Instruction(
- type=instruction["type"].value,
+ type=instruction["type"],
args=instruction["args"],
force=instruction["force"],
forceUpload=instruction.get("forceUpload"),
+ resolveSymlinks=instruction.get("resolveSymlinks"),
)
if instruction["type"] == InstructionType.COPY:
@@ -530,6 +535,7 @@ class TemplateBase:
*self._ignore_file_paths,
*read_dockerignore(self._file_context_path),
],
+ instruction.get("resolveSymlinks", RESOLVE_SYMLINKS),
stack_trace,
)
@@ -538,8 +544,26 @@ class TemplateBase:
return steps
def _serialize(self, steps: List[Instruction]) -> TemplateType:
+ _steps: List[Instruction] = []
+
+ for index, instruction in enumerate(steps):
+ step = {
+ # Serialize enum to string value
+ "type": instruction["type"].value,
+ "args": instruction["args"],
+ "force": instruction["force"],
+ }
+
+ if instruction.get("filesHash") is not None:
+ step["filesHash"] = instruction["filesHash"]
+
+ if instruction.get("forceUpload") is not None:
+ step["forceUpload"] = instruction["forceUpload"]
+
+ _steps.append(step)
+
template_data: TemplateType = {
- "steps": steps,
+ "steps": _steps,
"force": self._force,
}
diff --git a/packages/python-sdk/e2b/template/types.py b/packages/python-sdk/e2b/template/types.py
index 4d787cd3a..64fbd6e61 100644
--- a/packages/python-sdk/e2b/template/types.py
+++ b/packages/python-sdk/e2b/template/types.py
@@ -21,6 +21,7 @@ class CopyItem(TypedDict):
forceUpload: NotRequired[Optional[bool]]
user: NotRequired[Optional[str]]
mode: NotRequired[Optional[int]]
+ resolveSymlinks: NotRequired[Optional[bool]]
class Instruction(TypedDict):
@@ -29,6 +30,7 @@ class Instruction(TypedDict):
force: bool
forceUpload: NotRequired[Optional[bool]]
filesHash: NotRequired[Optional[str]]
+ resolveSymlinks: NotRequired[Optional[bool]]
@dataclass
diff --git a/packages/python-sdk/e2b/template/utils.py b/packages/python-sdk/e2b/template/utils.py
index 4753cd48d..7d330c3f7 100644
--- a/packages/python-sdk/e2b/template/utils.py
+++ b/packages/python-sdk/e2b/template/utils.py
@@ -1,6 +1,7 @@
import hashlib
import os
import json
+import stat
from glob import glob
import fnmatch
import re
@@ -30,8 +31,9 @@ def calculate_files_hash(
src: str,
dest: str,
context_path: str,
- ignore_patterns: Optional[List[str]] = None,
- stack_trace: Optional[TracebackType] = None,
+ ignore_patterns: List[str],
+ resolve_symlinks: bool,
+ stack_trace: Optional[TracebackType],
) -> str:
src_path = os.path.join(context_path, src)
hash_obj = hashlib.sha256()
@@ -52,12 +54,38 @@ def calculate_files_hash(
if len(files) == 0:
raise ValueError(f"No files found in {src_path}").with_traceback(stack_trace)
+ def hash_stats(stat_info: os.stat_result) -> None:
+ hash_obj.update(str(stat_info.st_mode).encode())
+ hash_obj.update(str(stat_info.st_uid).encode())
+ hash_obj.update(str(stat_info.st_gid).encode())
+ hash_obj.update(str(stat_info.st_size).encode())
+ hash_obj.update(str(stat_info.st_mtime).encode())
+
for file in files:
- if not os.path.isfile(file):
- # skip folders
- continue
- with open(file, "rb") as f:
- hash_obj.update(f.read())
+ # Add a relative path to hash calculation
+ relative_path = os.path.relpath(file, context_path)
+ hash_obj.update(relative_path.encode())
+
+ # Add stat information to hash calculation
+ if os.path.islink(file):
+ stats = os.lstat(file)
+ should_follow = resolve_symlinks and (
+ os.path.isfile(file) or os.path.isdir(file)
+ )
+
+ if not should_follow:
+ hash_stats(stats)
+
+ content = os.readlink(file)
+ hash_obj.update(content.encode())
+ continue
+
+ stats = os.stat(file)
+ hash_stats(stats)
+
+ if stat.S_ISREG(stats.st_mode):
+ with open(file, "rb") as f:
+ hash_obj.update(f.read())
return hash_obj.hexdigest()
diff --git a/packages/python-sdk/e2b/template_async/build_api.py b/packages/python-sdk/e2b/template_async/build_api.py
index 38b4f5cf5..21bd3163f 100644
--- a/packages/python-sdk/e2b/template_async/build_api.py
+++ b/packages/python-sdk/e2b/template_async/build_api.py
@@ -1,21 +1,21 @@
+import asyncio
import io
import os
-from glob import glob
import tarfile
-import asyncio
-from typing import Callable, Literal, Optional, List
+from glob import glob
from types import TracebackType
+from typing import Callable, Literal, Optional, List
import httpx
-from e2b.template.types import TemplateType, LogEntry
-from e2b.api.client.client import AuthenticatedClient
+from e2b.api import handle_api_exception
from e2b.api.client.api.templates import (
post_v2_templates,
get_templates_template_id_files_hash,
post_v_2_templates_template_id_builds_build_id,
get_templates_template_id_builds_build_id_status,
)
+from e2b.api.client.client import AuthenticatedClient
from e2b.api.client.models import (
TemplateBuildRequestV2,
TemplateBuildStartV2,
@@ -23,8 +23,8 @@ from e2b.api.client.models import (
TemplateBuild,
Error,
)
-from e2b.api import handle_api_exception
from e2b.template.exceptions import BuildException, FileUploadException
+from e2b.template.types import TemplateType, LogEntry
from e2b.template.utils import get_build_step_index
@@ -84,12 +84,17 @@ async def upload_file(
file_name: str,
context_path: str,
url: str,
- stack_trace: Optional[TracebackType] = None,
+ resolve_symlinks: bool,
+ stack_trace: Optional[TracebackType],
):
tar_buffer = io.BytesIO()
try:
- with tarfile.open(fileobj=tar_buffer, mode="w:gz") as tar:
+ with tarfile.open(
+ fileobj=tar_buffer,
+ mode="w:gz",
+ dereference=resolve_symlinks,
+ ) as tar:
src_path = os.path.join(context_path, file_name)
files = glob(src_path, recursive=True)
for file in files:
diff --git a/packages/python-sdk/e2b/template_async/main.py b/packages/python-sdk/e2b/template_async/main.py
index 2a0bc36e2..187bcd059 100644
--- a/packages/python-sdk/e2b/template_async/main.py
+++ b/packages/python-sdk/e2b/template_async/main.py
@@ -15,6 +15,7 @@ from .build_api import (
upload_file,
wait_for_build_finish,
)
+from e2b.template.consts import RESOLVE_SYMLINKS
class AsyncTemplate(TemplateBase):
@@ -84,6 +85,7 @@ class AsyncTemplate(TemplateBase):
src = args[0] if len(args) > 0 else None
force_upload = file_upload.get("forceUpload")
files_hash = file_upload.get("filesHash", None)
+ resolve_symlinks = file_upload.get("resolveSymlinks", RESOLVE_SYMLINKS)
if src is None or files_hash is None:
raise ValueError("Source path and files hash are required")
@@ -103,6 +105,8 @@ class AsyncTemplate(TemplateBase):
src,
template._template._file_context_path,
file_info.url,
+ resolve_symlinks,
+ stack_trace,
)
if on_build_logs:
on_build_logs(
diff --git a/packages/python-sdk/e2b/template_sync/build_api.py b/packages/python-sdk/e2b/template_sync/build_api.py
index cd8f52882..37d165542 100644
--- a/packages/python-sdk/e2b/template_sync/build_api.py
+++ b/packages/python-sdk/e2b/template_sync/build_api.py
@@ -1,21 +1,21 @@
import io
import os
-from glob import glob
import tarfile
import time
-from typing import Callable, Literal, Optional, List
+from glob import glob
from types import TracebackType
+from typing import Callable, Literal, Optional, List
import httpx
-from e2b.template.types import TemplateType, LogEntry
-from e2b.api.client.client import AuthenticatedClient
+from e2b.api import handle_api_exception
from e2b.api.client.api.templates import (
post_v2_templates,
get_templates_template_id_files_hash,
post_v_2_templates_template_id_builds_build_id,
get_templates_template_id_builds_build_id_status,
)
+from e2b.api.client.client import AuthenticatedClient
from e2b.api.client.models import (
TemplateBuildRequestV2,
TemplateBuildStartV2,
@@ -23,8 +23,8 @@ from e2b.api.client.models import (
TemplateBuild,
Error,
)
-from e2b.api import handle_api_exception
from e2b.template.exceptions import BuildException, FileUploadException
+from e2b.template.types import TemplateType, LogEntry
from e2b.template.utils import get_build_step_index
@@ -84,12 +84,17 @@ def upload_file(
file_name: str,
context_path: str,
url: str,
- stack_trace: Optional[TracebackType] = None,
+ resolve_symlinks: bool,
+ stack_trace: Optional[TracebackType],
):
tar_buffer = io.BytesIO()
try:
- with tarfile.open(fileobj=tar_buffer, mode="w:gz") as tar:
+ with tarfile.open(
+ fileobj=tar_buffer,
+ mode="w:gz",
+ dereference=resolve_symlinks,
+ ) as tar:
src_path = os.path.join(context_path, file_name)
files = glob(src_path, recursive=True)
for file in files:
diff --git a/packages/python-sdk/e2b/template_sync/main.py b/packages/python-sdk/e2b/template_sync/main.py
index 78ff9c039..671109c7d 100644
--- a/packages/python-sdk/e2b/template_sync/main.py
+++ b/packages/python-sdk/e2b/template_sync/main.py
@@ -1,5 +1,6 @@
from typing import Callable, Optional
+from e2b.template.consts import RESOLVE_SYMLINKS
from e2b.template.main import TemplateBase, TemplateClass
from e2b.template.types import LogEntry, InstructionType
@@ -84,6 +85,7 @@ class Template(TemplateBase):
src = args[0] if len(args) > 0 else None
force_upload = file_upload.get("forceUpload")
files_hash = file_upload.get("filesHash", None)
+ resolve_symlinks = file_upload.get("resolveSymlinks", RESOLVE_SYMLINKS)
if src is None or files_hash is None:
raise ValueError("Source path and files hash are required")
@@ -103,6 +105,8 @@ class Template(TemplateBase):
src,
template._template._file_context_path,
file_info.url,
+ resolve_symlinks,
+ stack_trace,
)
if on_build_logs:
on_build_logs(
diff --git a/packages/python-sdk/tests/async/template_async/test_build.py b/packages/python-sdk/tests/async/template_async/test_build.py
index 2a916ecf0..d0e87c495 100644
--- a/packages/python-sdk/tests/async/template_async/test_build.py
+++ b/packages/python-sdk/tests/async/template_async/test_build.py
@@ -1,41 +1,83 @@
+import tempfile
+
import pytest
import os
-from uuid import uuid4
import shutil
from e2b import AsyncTemplate, wait_for_timeout
-async def test_build():
- test_dir = os.path.dirname(os.path.abspath(__file__))
[email protected](scope="module")
+def setup_test_folder():
+ test_dir = tempfile.mkdtemp(prefix="python_async_test_")
folder_path = os.path.join(test_dir, "folder")
os.makedirs(folder_path, exist_ok=True)
with open(os.path.join(folder_path, "test.txt"), "w") as f:
- f.write("test")
+ f.write("This is a test file.")
+
+ # Create relative symlink
+ symlink_path = os.path.join(folder_path, "symlink.txt")
+ if os.path.exists(symlink_path):
+ os.remove(symlink_path)
+ os.symlink("test.txt", symlink_path)
+
+ # Create absolute symlink
+ symlink2_path = os.path.join(folder_path, "symlink2.txt")
+ if os.path.exists(symlink2_path):
+ os.remove(symlink2_path)
+ os.symlink(os.path.join(folder_path, "test.txt"), symlink2_path)
+
+ # Create a symlink to a file that does not exist
+ symlink3_path = os.path.join(folder_path, "symlink3.txt")
+ if os.path.exists(symlink3_path):
+ os.remove(symlink3_path)
+ os.symlink("12345test.txt", symlink3_path)
+
+ yield test_dir
+ # Cleanup
+ shutil.rmtree(test_dir, ignore_errors=True)
+
+
+async def test_build_template(async_build, setup_test_folder):
template = (
- AsyncTemplate()
+ AsyncTemplate(file_context_path=setup_test_folder)
.from_image("ubuntu:22.04")
- .copy("folder/*.txt", "folder", force_upload=True)
- .copy("folder", "folder2", force_upload=True)
- .set_envs(
- {
- "ENV_1": "value1",
- "ENV_2": "value2",
- }
- )
+ .copy("folder/*", "folder", force_upload=True)
.run_cmd("cat folder/test.txt")
.set_workdir("/app")
.set_start_cmd("echo 'Hello, world!'", wait_for_timeout(10_000))
)
- await AsyncTemplate.build(
- template,
- alias=str(uuid4()),
- cpu_count=1,
- memory_mb=1024,
+ await async_build(template)
+
+
+async def test_build_template_with_symlinks(async_build, setup_test_folder):
+ template = (
+ AsyncTemplate(file_context_path=setup_test_folder)
+ .from_image("ubuntu:22.04")
+ .copy("folder/*", "folder", force_upload=True)
+ .run_cmd("cat folder/symlink.txt")
+ )
+
+ await async_build(template)
+
+
+async def test_build_template_with_resolve_symlinks(async_build, setup_test_folder):
+ template = (
+ AsyncTemplate(file_context_path=setup_test_folder)
+ .from_image("ubuntu:22.04")
+ .copy(
+ "folder/symlink.txt",
+ "folder/symlink.txt",
+ force_upload=True,
+ resolve_symlinks=True,
+ )
+ .run_cmd("cat folder/symlink.txt")
)
- shutil.rmtree(folder_path)
+ await async_build(template)
diff --git a/packages/python-sdk/tests/async/template_async/test_stacktrace.py b/packages/python-sdk/tests/async/template_async/test_stacktrace.py
index 7b816d02f..d26c33a9b 100644
--- a/packages/python-sdk/tests/async/template_async/test_stacktrace.py
+++ b/packages/python-sdk/tests/async/template_async/test_stacktrace.py
@@ -1,21 +1,11 @@
import pytest
-from uuid import uuid4
import linecache
-from e2b import AsyncTemplate, wait_for_timeout, TemplateClass
+from e2b import AsyncTemplate, wait_for_timeout
non_existent_path = "/nonexistent/path"
-async def build(template: TemplateClass):
- return await AsyncTemplate.build(
- template,
- alias=str(uuid4()),
- cpu_count=1,
- memory_mb=1024,
- )
-
-
async def _expect_to_throw_and_check_trace(func, expected_method: str):
try:
await func()
@@ -38,38 +28,42 @@ async def _expect_to_throw_and_check_trace(func, expected_method: str):
@pytest.mark.skip_debug()
-async def test_traces_on_from_image():
+async def test_traces_on_from_image(async_build):
template = AsyncTemplate()
template = template.skip_cache().from_image("e2b.dev/this-image-does-not-exist")
- await _expect_to_throw_and_check_trace(lambda: build(template), "from_image")
+ await _expect_to_throw_and_check_trace(lambda: async_build(template), "from_image")
# @pytest.mark.skip_debug()
-# async def test_traces_on_from_template():
+# async def test_traces_on_from_template(async_build):
# template = AsyncTemplate().from_template("this-template-does-not-exist")
-# await _expect_to_throw_and_check_trace(lambda: build(template), "from_template")
+# await _expect_to_throw_and_check_trace(lambda: async_build(template), "from_template")
@pytest.mark.skip_debug()
-async def test_traces_on_from_dockerfile():
+async def test_traces_on_from_dockerfile(async_build):
template = AsyncTemplate()
template = template.from_dockerfile("FROM ubuntu:22.04\nRUN nonexistent")
- await _expect_to_throw_and_check_trace(lambda: build(template), "from_dockerfile")
+ await _expect_to_throw_and_check_trace(
+ lambda: async_build(template), "from_dockerfile"
+ )
@pytest.mark.skip_debug()
-async def test_traces_on_from_registry():
+async def test_traces_on_from_registry(async_build):
template = AsyncTemplate()
template = template.skip_cache().from_registry(
"registry.example.com/nonexistent:latest",
username="test",
password="test",
)
- await _expect_to_throw_and_check_trace(lambda: build(template), "from_registry")
+ await _expect_to_throw_and_check_trace(
+ lambda: async_build(template), "from_registry"
+ )
@pytest.mark.skip_debug()
-async def test_traces_on_from_aws_registry():
+async def test_traces_on_from_aws_registry(async_build):
template = AsyncTemplate()
template = template.skip_cache().from_aws_registry(
"123456789.dkr.ecr.us-east-1.amazonaws.com/nonexistent:latest",
@@ -77,11 +71,13 @@ async def test_traces_on_from_aws_registry():
secret_access_key="test",
region="us-east-1",
)
- await _expect_to_throw_and_check_trace(lambda: build(template), "from_aws_registry")
+ await _expect_to_throw_and_check_trace(
+ lambda: async_build(template), "from_aws_registry"
+ )
@pytest.mark.skip_debug()
-async def test_traces_on_from_gcp_registry():
+async def test_traces_on_from_gcp_registry(async_build):
template = AsyncTemplate()
template = template.skip_cache().from_gcp_registry(
"gcr.io/nonexistent-project/nonexistent:latest",
@@ -89,110 +85,116 @@ async def test_traces_on_from_gcp_registry():
"type": "service_account",
},
)
- await _expect_to_throw_and_check_trace(lambda: build(template), "from_gcp_registry")
+ await _expect_to_throw_and_check_trace(
+ lambda: async_build(template), "from_gcp_registry"
+ )
@pytest.mark.skip_debug()
-async def test_traces_on_copy():
+async def test_traces_on_copy(async_build):
template = AsyncTemplate()
template = template.from_base_image()
template = template.skip_cache().copy(non_existent_path, non_existent_path)
- await _expect_to_throw_and_check_trace(lambda: build(template), "copy")
+ await _expect_to_throw_and_check_trace(lambda: async_build(template), "copy")
@pytest.mark.skip_debug()
-async def test_traces_on_remove():
+async def test_traces_on_remove(async_build):
template = AsyncTemplate()
template = template.from_base_image()
template = template.skip_cache().remove(non_existent_path)
- await _expect_to_throw_and_check_trace(lambda: build(template), "remove")
+ await _expect_to_throw_and_check_trace(lambda: async_build(template), "remove")
@pytest.mark.skip_debug()
-async def test_traces_on_rename():
+async def test_traces_on_rename(async_build):
template = AsyncTemplate()
template = template.from_base_image()
template = template.skip_cache().rename(non_existent_path, "/tmp/dest.txt")
- await _expect_to_throw_and_check_trace(lambda: build(template), "rename")
+ await _expect_to_throw_and_check_trace(lambda: async_build(template), "rename")
@pytest.mark.skip_debug()
-async def test_traces_on_make_dir():
+async def test_traces_on_make_dir(async_build):
template = AsyncTemplate()
template = template.from_base_image()
template = template.skip_cache().make_dir(".bashrc")
- await _expect_to_throw_and_check_trace(lambda: build(template), "make_dir")
+ await _expect_to_throw_and_check_trace(lambda: async_build(template), "make_dir")
@pytest.mark.skip_debug()
-async def test_traces_on_make_symlink():
+async def test_traces_on_make_symlink(async_build):
template = AsyncTemplate()
template = template.from_base_image()
template = template.skip_cache().make_symlink(".bashrc", ".bashrc")
- await _expect_to_throw_and_check_trace(lambda: build(template), "make_symlink")
+ await _expect_to_throw_and_check_trace(
+ lambda: async_build(template), "make_symlink"
+ )
@pytest.mark.skip_debug()
-async def test_traces_on_run_cmd():
+async def test_traces_on_run_cmd(async_build):
template = AsyncTemplate()
template = template.from_base_image()
template = template.skip_cache().run_cmd(f"cat {non_existent_path}")
- await _expect_to_throw_and_check_trace(lambda: build(template), "run_cmd")
+ await _expect_to_throw_and_check_trace(lambda: async_build(template), "run_cmd")
@pytest.mark.skip_debug()
-async def test_traces_on_set_workdir():
+async def test_traces_on_set_workdir(async_build):
template = AsyncTemplate()
template = template.from_base_image()
template = template.skip_cache().set_workdir(".bashrc")
- await _expect_to_throw_and_check_trace(lambda: build(template), "set_workdir")
+ await _expect_to_throw_and_check_trace(lambda: async_build(template), "set_workdir")
@pytest.mark.skip_debug()
-async def test_traces_on_set_user():
+async def test_traces_on_set_user(async_build):
template = AsyncTemplate()
template = template.from_base_image()
template = template.skip_cache().set_user(";")
- await _expect_to_throw_and_check_trace(lambda: build(template), "set_user")
+ await _expect_to_throw_and_check_trace(lambda: async_build(template), "set_user")
@pytest.mark.skip_debug()
-async def test_traces_on_pip_install():
+async def test_traces_on_pip_install(async_build):
template = AsyncTemplate()
template = template.from_base_image()
template = template.skip_cache().pip_install("nonexistent-package")
- await _expect_to_throw_and_check_trace(lambda: build(template), "pip_install")
+ await _expect_to_throw_and_check_trace(lambda: async_build(template), "pip_install")
@pytest.mark.skip_debug()
-async def test_traces_on_npm_install():
+async def test_traces_on_npm_install(async_build):
template = AsyncTemplate()
template = template.from_base_image()
template = template.skip_cache().npm_install("nonexistent-package")
- await _expect_to_throw_and_check_trace(lambda: build(template), "npm_install")
+ await _expect_to_throw_and_check_trace(lambda: async_build(template), "npm_install")
@pytest.mark.skip_debug()
-async def test_traces_on_apt_install():
+async def test_traces_on_apt_install(async_build):
template = AsyncTemplate()
template = template.from_base_image()
template = template.skip_cache().apt_install("nonexistent-package")
- await _expect_to_throw_and_check_trace(lambda: build(template), "apt_install")
+ await _expect_to_throw_and_check_trace(lambda: async_build(template), "apt_install")
@pytest.mark.skip_debug()
-async def test_traces_on_git_clone():
+async def test_traces_on_git_clone(async_build):
template = AsyncTemplate()
template = template.from_base_image()
template = template.skip_cache().git_clone("https://github.com/repo.git")
- await _expect_to_throw_and_check_trace(lambda: build(template), "git_clone")
+ await _expect_to_throw_and_check_trace(lambda: async_build(template), "git_clone")
@pytest.mark.skip_debug()
-async def test_traces_on_set_start_cmd():
+async def test_traces_on_set_start_cmd(async_build):
template = AsyncTemplate()
template = template.from_base_image()
template = template.set_start_cmd(
f"./{non_existent_path}", wait_for_timeout(10_000)
)
- await _expect_to_throw_and_check_trace(lambda: build(template), "set_start_cmd")
+ await _expect_to_throw_and_check_trace(
+ lambda: async_build(template), "set_start_cmd"
+ )
diff --git a/packages/python-sdk/tests/conftest.py b/packages/python-sdk/tests/conftest.py
index e81c1d9b1..5e7289dd0 100644
--- a/packages/python-sdk/tests/conftest.py
+++ b/packages/python-sdk/tests/conftest.py
@@ -4,6 +4,7 @@ import uuid
import pytest
import pytest_asyncio
import os
+from uuid import uuid4
from logging import warning
@@ -13,6 +14,9 @@ from e2b import (
AsyncCommandHandle,
CommandExitException,
CommandHandle,
+ AsyncTemplate,
+ Template,
+ TemplateClass,
)
@@ -60,6 +64,32 @@ async def async_sandbox(template, debug, sandbox_test_id):
)
+def build():
+ def _build(template: TemplateClass):
+ return Template.build(
+ template,
+ alias=str(uuid4()),
+ cpu_count=1,
+ memory_mb=1024,
+ )
+
+ return _build
+
+
+@pytest_asyncio.fixture
+def async_build():
+ async def _async_build(template: TemplateClass):
+ return await AsyncTemplate.build(
+ template,
+ alias=str(uuid4()),
+ cpu_count=1,
+ memory_mb=1024,
+ )
+
+ return _async_build
+
+
@pytest.fixture
def debug():
return os.getenv("E2B_DEBUG") is not None
diff --git a/packages/python-sdk/tests/sync/template_sync/test_build.py b/packages/python-sdk/tests/sync/template_sync/test_build.py
index d8887cfbf..a7904abea 100644
--- a/packages/python-sdk/tests/sync/template_sync/test_build.py
+++ b/packages/python-sdk/tests/sync/template_sync/test_build.py
@@ -1,41 +1,83 @@
+import tempfile
+
import pytest
import os
-from uuid import uuid4
import shutil
from e2b import Template, wait_for_timeout
-def test_build():
- test_dir = os.path.dirname(os.path.abspath(__file__))
[email protected](scope="module")
+def setup_test_folder():
+ test_dir = tempfile.mkdtemp(prefix="python_sync_test_")
folder_path = os.path.join(test_dir, "folder")
os.makedirs(folder_path, exist_ok=True)
with open(os.path.join(folder_path, "test.txt"), "w") as f:
- f.write("test")
+ f.write("This is a test file.")
+
+ # Create relative symlink
+ symlink_path = os.path.join(folder_path, "symlink.txt")
+ if os.path.exists(symlink_path):
+ os.remove(symlink_path)
+ os.symlink("test.txt", symlink_path)
+
+ # Create absolute symlink
+ symlink2_path = os.path.join(folder_path, "symlink2.txt")
+ if os.path.exists(symlink2_path):
+ os.remove(symlink2_path)
+ os.symlink(os.path.join(folder_path, "test.txt"), symlink2_path)
+
+ # Create a symlink to a file that does not exist
+ symlink3_path = os.path.join(folder_path, "symlink3.txt")
+ if os.path.exists(symlink3_path):
+ os.remove(symlink3_path)
+ os.symlink("12345test.txt", symlink3_path)
+
+ yield test_dir
+ # Cleanup
+ shutil.rmtree(test_dir, ignore_errors=True)
+
+
+def test_build_template(build, setup_test_folder):
template = (
- Template()
+ Template(file_context_path=setup_test_folder)
.from_image("ubuntu:22.04")
- .copy("folder/*.txt", "folder", force_upload=True)
- .copy("folder", "folder2", force_upload=True)
- .set_envs(
- {
- "ENV_1": "value1",
- "ENV_2": "value2",
- }
- )
+ .copy("folder/*", "folder", force_upload=True)
.run_cmd("cat folder/test.txt")
.set_workdir("/app")
.set_start_cmd("echo 'Hello, world!'", wait_for_timeout(10_000))
)
- Template.build(
- template,
- alias=str(uuid4()),
- cpu_count=1,
- memory_mb=1024,
+ build(template)
+
+
+def test_build_template_with_symlinks(build, setup_test_folder):
+ template = (
+ Template(file_context_path=setup_test_folder)
+ .from_image("ubuntu:22.04")
+ .copy("folder/*", "folder", force_upload=True)
+ .run_cmd("cat folder/symlink.txt")
+ )
+
+ build(template)
+
+
+def test_build_template_with_resolve_symlinks(build, setup_test_folder):
+ template = (
+ Template(file_context_path=setup_test_folder)
+ .from_image("ubuntu:22.04")
+ .copy(
+ "folder/symlink.txt",
+ "folder/symlink.txt",
+ force_upload=True,
+ resolve_symlinks=True,
+ )
+ .run_cmd("cat folder/symlink.txt")
)
- shutil.rmtree(folder_path)
+ build(template)
diff --git a/packages/python-sdk/tests/sync/template_sync/test_stacktrace.py b/packages/python-sdk/tests/sync/template_sync/test_stacktrace.py
index 36afb67ec..4a53165cf 100644
--- a/packages/python-sdk/tests/sync/template_sync/test_stacktrace.py
+++ b/packages/python-sdk/tests/sync/template_sync/test_stacktrace.py
@@ -1,21 +1,11 @@
import pytest
-from uuid import uuid4
import linecache
-from e2b import Template, wait_for_timeout, TemplateClass
+from e2b import Template, wait_for_timeout
non_existent_path = "/nonexistent/path"
-def build(template: TemplateClass):
- return Template.build(
- template,
- alias=str(uuid4()),
- cpu_count=1,
- memory_mb=1024,
- )
-
-
def _expect_to_throw_and_check_trace(func, expected_method: str):
try:
func()
@@ -38,27 +28,27 @@ def _expect_to_throw_and_check_trace(func, expected_method: str):
@pytest.mark.skip_debug()
-def test_traces_on_from_image():
+def test_traces_on_from_image(build):
template = Template()
template = template.skip_cache().from_image("e2b.dev/this-image-does-not-exist")
_expect_to_throw_and_check_trace(lambda: build(template), "from_image")
# @pytest.mark.skip_debug()
-# def test_traces_on_from_template():
+# def test_traces_on_from_template(build):
# template = Template().from_template("this-template-does-not-exist")
# _expect_to_throw_and_check_trace(lambda: build(template), "from_template")
@pytest.mark.skip_debug()
-def test_traces_on_from_dockerfile():
+def test_traces_on_from_dockerfile(build):
template = Template()
template = template.from_dockerfile("FROM ubuntu:22.04\nRUN nonexistent")
_expect_to_throw_and_check_trace(lambda: build(template), "from_dockerfile")
@pytest.mark.skip_debug()
-def test_traces_on_from_registry():
+def test_traces_on_from_registry(build):
template = Template()
template = template.skip_cache().from_registry(
"registry.example.com/nonexistent:latest",
@@ -69,7 +59,7 @@ def test_traces_on_from_registry():
@pytest.mark.skip_debug()
-def test_traces_on_from_aws_registry():
+def test_traces_on_from_aws_registry(build):
template = Template()
template = template.skip_cache().from_aws_registry(
"123456789.dkr.ecr.us-east-1.amazonaws.com/nonexistent:latest",
@@ -81,7 +71,7 @@ def test_traces_on_from_aws_registry():
@pytest.mark.skip_debug()
-def test_traces_on_from_gcp_registry():
+def test_traces_on_from_gcp_registry(build):
template = Template()
template = template.skip_cache().from_gcp_registry(
"gcr.io/nonexistent-project/nonexistent:latest",
@@ -93,7 +83,7 @@ def test_traces_on_from_gcp_registry():
@pytest.mark.skip_debug()
-def test_traces_on_copy():
+def test_traces_on_copy(build):
template = Template()
template = template.from_base_image()
template = template.skip_cache().copy(non_existent_path, non_existent_path)
@@ -101,7 +91,7 @@ def test_traces_on_copy():
@pytest.mark.skip_debug()
-def test_traces_on_remove():
+def test_traces_on_remove(build):
template = Template()
template = template.from_base_image()
template = template.skip_cache().remove(non_existent_path)
@@ -109,7 +99,7 @@ def test_traces_on_remove():
@pytest.mark.skip_debug()
-def test_traces_on_rename():
+def test_traces_on_rename(build):
template = Template()
template = template.from_base_image()
template = template.skip_cache().rename(non_existent_path, "/tmp/dest.txt")
@@ -117,7 +107,7 @@ def test_traces_on_rename():
@pytest.mark.skip_debug()
-def test_traces_on_make_dir():
+def test_traces_on_make_dir(build):
template = Template()
template = template.from_base_image()
template = template.skip_cache().make_dir(".bashrc")
@@ -125,7 +115,7 @@ def test_traces_on_make_dir():
@pytest.mark.skip_debug()
-def test_traces_on_make_symlink():
+def test_traces_on_make_symlink(build):
template = Template()
template = template.from_base_image()
template = template.skip_cache().make_symlink(".bashrc", ".bashrc")
@@ -133,7 +123,7 @@ def test_traces_on_make_symlink():
@pytest.mark.skip_debug()
-def test_traces_on_run_cmd():
+def test_traces_on_run_cmd(build):
template = Template()
template = template.from_base_image()
template = template.skip_cache().run_cmd(f"cat {non_existent_path}")
@@ -141,7 +131,7 @@ def test_traces_on_run_cmd():
@pytest.mark.skip_debug()
-def test_traces_on_set_workdir():
+def test_traces_on_set_workdir(build):
template = Template()
template = template.from_base_image()
template = template.skip_cache().set_workdir(".bashrc")
@@ -149,7 +139,7 @@ def test_traces_on_set_workdir():
@pytest.mark.skip_debug()
-def test_traces_on_set_user():
+def test_traces_on_set_user(build):
template = Template()
template = template.from_base_image()
template = template.skip_cache().set_user(";")
@@ -157,7 +147,7 @@ def test_traces_on_set_user():
@pytest.mark.skip_debug()
-def test_traces_on_pip_install():
+def test_traces_on_pip_install(build):
template = Template()
template = template.from_base_image()
template = template.skip_cache().pip_install("nonexistent-package")
@@ -165,7 +155,7 @@ def test_traces_on_pip_install():
@pytest.mark.skip_debug()
-def test_traces_on_npm_install():
+def test_traces_on_npm_install(build):
template = Template()
template = template.from_base_image()
template = template.skip_cache().npm_install("nonexistent-package")
@@ -173,7 +163,7 @@ def test_traces_on_npm_install():
@pytest.mark.skip_debug()
-def test_traces_on_apt_install():
+def test_traces_on_apt_install(build):
template = Template()
template = template.from_base_image()
template = template.skip_cache().apt_install("nonexistent-package")
@@ -181,7 +171,7 @@ def test_traces_on_apt_install():
@pytest.mark.skip_debug()
-def test_traces_on_git_clone():
+def test_traces_on_git_clone(build):
template = Template()
template = template.from_base_image()
template = template.skip_cache().git_clone("https://github.com/repo.git")
@@ -189,7 +179,7 @@ def test_traces_on_git_clone():
@pytest.mark.skip_debug()
-def test_traces_on_set_start_cmd():
+def test_traces_on_set_start_cmd(build):
template = Template()
template = template.from_base_image()
template = template.set_start_cmd(